This is a java function, i converted to golang code, but appear error.
How can I solve this problem? please teach.
java code:
int p = -1;
int x = 0;
x |= 0x1 << p;
p++;
golang code:
var p int = -1
var x int = 0
x |= 0x1 << p
p++
shift code type int, must be unsigned integer
This is an error because as per Go specifications, bit shifting only works on unsigned ints:
left shift integer << unsigned integer
right shift integer >> unsigned integer
ALL,
I have a following code:
In the header
class MySQLDatabase
{
protected:
struct MySQLImpl;
MySQLImpl *m_pimpl;
};
struct MySQLDatabase::MySQLImpl
{
std::wstring_convert<std::codecvt_utf8<wchar_t> > m_myconv;
std::wstring m_host, m_user, m_password, m_dbName, m_socket, m_catalog;
};
In the cpp
int MySQLDatabase::Connect()
{
std::wstring tname;
// some code here
const char *temp1 = m_pimpl->m_myconv.to_bytes( tname.c_str() ).c_str();
const char *temp2 = m_pimpl->m_myconv.to_bytes( ownerName.c_str() ).c_str();
const char *temp3 = m_pimpl->m_myconv.to_bytes( fieldName.c_str() ).c_str();
unsigned long str_length1 = strlen( temp1 ), str_length2 = strlen( temp2 ), str_length3 = strlen( temp3 );
str_data1 = new char[str_length1 + 1], str_data2 = new char[str_length2 + 1], str_data3 = new char[str_length3 + 1];
memset( str_data1, '\0', str_length1 + 1 );
memset( str_data2, '\0', str_length2 + 1 );
memset( str_data3, '\0', str_length3 + 1 );
// some more code here
}
I am trying to compile and run this code on Linux with gcc 5.4 in c++11 mode.
The tname variable contains L"draft.abc\303\237".
The problem is that the temp1 is "" (empty string). And so is temp2 and temp3 (ownerName is L"" and fieldName is L"name").
Am I doing something wrong with the conversion?
I'm writing a program that splits any two numbers. The problem is whenever I run the program I get an error that says:
“./a.out” terminated by signal SIGSEGV (Address boundary error)
And that error occurs at the lines:
a = std::stoi(temp_vec.front());
b = std::stoi(temp_vec.back());
and
c = std::stoi(temp_vec.front());
d = std::stoi(temp_vec.back());
Here's my program:
#include <iostream>
#include <string>
#include <vector>
void split_number(std::vector<std::string> vect, int x);
int main()
{
int x = 0, y = 0, a = 0, b = 0, c = 0, d = 0;
std::vector<std::string> temp_vec;
std::cout << "Enter x: ";
std::cin >> x;
std::cout << "Enter y: ";
std::cin >> y;
split_number(temp_vec, x);
a = std::stoi(temp_vec.front());
b = std::stoi(temp_vec.back());
split_number(temp_vec, y);
c = std::stoi(temp_vec.front());
d = std::stoi(temp_vec.back());
return 0;
}
void split_number(std::vector<std::string> vect, int x)
{
vect.clear();
//1. convert x to string
std::string temp_str = std::to_string(x);
//2. calculate length
std::size_t len = temp_str.length();
std::size_t delm = 0;
if(len % 2 == 0) {
delm = len / 2;
} else {
delm = (len + 1) / 2;
}
//3. populate vector
vect.push_back(temp_str.substr(0, delm));
vect.push_back(temp_str.substr(delm + 1));
}
Any help would be appreciated.
You get the segmentation fault because your vector is empty. Your vector is empty because you pass a copy of your initial vector to split_number(). The copy is passed because the signature of split_number() says it requires a copy. Change it to:
void split_number(std::vector<std::string> & vect, int x)
The ampersand makes the vect parameter a reference parameter, and modifications will show in the calling code.
I have a few for loops that does saturated arithmetic operations.
For instance:
Implementation of saturated add in my case is as follows:
static void addsat(Vector &R, Vector &A, Vector &B)
{
int32_t a, b, r;
int32_t max_add;
int32_t min_add;
const int32_t SAT_VALUE = (1<<(16-1))-1;
const int32_t SAT_VALUE2 = (-SAT_VALUE - 1);
const int32_t sat_cond = (SAT_VALUE <= 0x7fffffff);
const uint32_t SAT = 0xffffffff >> 16;
for (int i=0; i<R.length; i++)
{
a = static_cast<uint32_t>(A.data[i]);
b = static_cast<uint32_t>(B.data[i]);
max_add = (int32_t)0x7fffffff - a;
min_add = (int32_t)0x80000000 - a;
r = (a>0 && b>max_add) ? 0x7fffffff : a + b;
r = (a<0 && b<min_add) ? 0x80000000 : a + b;
if ( sat_cond == 1)
{
std_max(r,r,SAT_VALUE2);
std_min(r,r,SAT_VALUE);
}
else
{
r = static_cast<uint16_t> (static_cast<int32_t> (r));
}
R.data[i] = static_cast<uint16_t>(r);
}
}
I see that there is paddsat intrinsic in x86 that could have been the perfect solution to this loop. I do get the code auto vectorized but with a combination of multiple operations according to my code. I would like to know what could be the best way to write this loop that auto-vectorizer finds the addsat operation match right.
Vector structure is:
struct V {
static constexpr int length = 32;
unsigned short data[32];
};
Compiler used is clang 3.8 and code was compiled for AVX2 Haswell x86-64 architecture.
This question was asked before in other languages but not delphi after searching SO.
see this question:How to Generate Permutations With Repeated Characters and this question: Generate all combinations of arbitrary alphabet up to arbitrary length and this one: How to generate combination of fix length strings using a set of characters?
so the question is not new but I am having a hard time translating any of this to delphi.
What I'm trying to do is generate combinations that does include repeats of characters such as this:
if we have a string of characters (specified by user): ABC and we want to generate length of three characters (also length specified by user) I would get:
AAA AAB AAC ABA ABB ABC ACA ACB ACC BAA BAB BAC etc...
This code seems to do this but in C++:
int N_LETTERS = 4;
char alphabet[] = {'a', 'b', 'c', 'd'};
std::vector<std::string> get_all_words(int length)
{
std::vector<int> index(length, 0);
std::vector<std::string> words;
while(true)
{
std::string word(length);
for (int i = 0; i < length; ++i)
word[i] = alphabet[index[i]];
words.push_back(word);
for (int i = length-1; ; --i)
{
if (i < 0) return words;
index[i]++;
if (index[i] == N_LETTERS)
index[i] = 0;
else
break;
}
}
}
This also seems to do this:
#include <iostream>
#include <string>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
void displayPermutation(string permutation[], int length){
int i;
for (i=0;i<length;i++){
cout<<permutation[i];
}
cout << endl;
}
void getPermutations(string operatorBank[], int operatorCount,
string permutation[],int permutationLength, int curIndex){
int i;
//stop recursion condition
if(curIndex == permutationLength){
displayPermutation(permutation,permutationLength);
}
else{
for(i = 0; i < operatorCount; i++){
permutation[curIndex] = operatorBank[i];
getPermutations(operatorBank,operatorCount,permutation,
permutationLength,curIndex+1);
}
}
}
int main ()
{
int operatorCount = 4;
int permutationLength = 3;
string operatorBank[] = {"+","-","*","/"};
string permutation[] = {"","","",""}; //empty string
int curIndex = 0;
getPermutations(operatorBank,operatorCount,permutation,
permutationLength,curIndex);
return 0;
}
closest to what I want in delphi is found here but does not allow AAA for example:
http://www.swissdelphicenter.ch/torry/showcode.php?id=1032
And no this is not homework in case you are guessing. No other motive but just learning.
EDIT3:
Removed all irrelevant code from question to make it easier for other people to read it and get to the answers below. Look under answers for 2 different methods to accomplish this: one using recursion and the other by using a counter function.
The examples you show make this considerably more complex than necessary, at least IMO.
What you're really looking at is a 3 digit, base 3 number. You can just count from 0 to 33 = 27, then convert each number to base 3 (using 'A', 'B' and 'C' as your digits instead of '0', '1' and '2').
In C++, the conversion could look something like this:
std::string cvt(int in) {
static const int base = 3;
static const int digits = 3;
std::string ret;
for (int i = 0; i<digits; i++) {
ret.push_back('A' + in % base);
in /= base;
}
return std::string(ret.rbegin(), ret.rend());
}
With the conversion in place, producing all the combinations becomes utterly trivial:
for (int i = 0; i < 27; i++)
std::cout << cvt(i) << "\t";
I believe converting that to Delphi should be barely short of purely mechanical -- assignments change from = to :=, % becomes mod, the integer division changes to div, the for loop changes to something like for i = 0 to 27 do, and so on. The most tedious (but ultimately quite simple) part will probably be dealing with the fact that in C++, char is simply a small integer type, on which you can do normal integer math. At least if memory serves, in Pascal (or a derivative like Delphi) you'll need ord to convert from a character to an ordinal, and chr to convert back from ordinal to character. So the 'A' + in % base; will end up something more like chr(ord('A') + in mod base);
Like I said though, it seems like nearly the entire translation could/should end up almost completely mechanical, with no requirement for real changes in how the basic algorithms work, or anything like that.
Not exactly following your sequence of output, but following a sequence similar to the way binary numbers add up...
0001
0010
0011
0100
...
The idea is simple: loop index values in an array indicating which character to use at the respective position to compose the output combination string. No recursion required.
NextCombination updates the index array so the next combination is defined, it returns true as long as not all combinations are formed. False when back to all 0's.
DefineCombinations accepts a string with chars to use (for example 'ABC') and a size of the combined string (eg: 3): this adds the following sequence to a memo:
AAA, AAB, AAC, ABA, ABB, ABC, ACA, ACB, ACC, BAA, BAB, BAC, BBA, BBB, BBC, BCA, BCB, BCC, CAA, CAB, CAC, CBA, CBB, CBC, CCA, CCB, CCC
Adapt as you wish.
function TForm1.NextCombination(var aIndices: array of Integer; const MaxValue: Integer): Boolean;
var Index : Integer;
begin
Result:=False;
Index:=High(aIndices);
while not(Result) and (Index >= Low(aIndices)) do
begin
if (aIndices[Index] < MaxValue) then
begin
{ inc current index }
aIndices[Index]:=aIndices[Index] + 1;
Result:=True;
end
else
begin
{ reset current index, process next }
aIndices[Index]:=0;
Dec(Index);
end;
end;
end;
procedure TForm1.DefineCombinations(const Chars: String; const Size: Integer);
var aIndices : array of Integer;
Index : Integer;
sData : String;
begin
try
SetLength(sData, Size);
SetLength(aIndices, Size);
repeat
for Index:=Low(aIndices) to High(aIndices) do
sData[Index + 1]:=Chars[aIndices[Index] + 1];
memo1.Lines.Add(sData);
until not(NextCombination(aIndices, Length(Chars) - 1));
finally
SetLength(aIndices, 0);
SetLength(sData, 0);
end;
end;
Let me know if I missed something from the original question.
Here it is done with Recursion (Credit to this post's accepted answer:How to Generate Permutations With Repeated Characters
program Combinations;
{$APPTYPE CONSOLE}
{$R *.res}
uses
System.SysUtils;
procedure displayPermutation(const permutation : array of char; ilength: integer);
var
i: integer;
begin
for i := 0 to ilength - 1 do
begin
if i mod iLength = 0 then
writeln('')
else write(permutation[i]);
end;
end;
procedure getPermutations(const operatorBank: array of char; operatorCount: integer;
permutation: array of char; permutationLength, curIndex: integer);
var
i : integer;
begin
//stop recursion condition
if(curIndex = permutationLength)then
displayPermutation(permutation, permutationLength)
else
for i := 0 to operatorCount - 1 do
begin
permutation[curIndex] := operatorBank[i];
getPermutations(operatorBank,operatorCount,permutation,
permutationLength,curIndex+1);
end;
end;
var
operatorBank,permutation : array of char;
i, permutationLength, curIndex, operatorCount: integer;
Q, S : String;
begin
try
Q := ' ';
S := ' ';
while (Q <> '') and (S <> '') do
begin
Writeln('');
Write('P(N,R) N=? : ');
ReadLn(Q);
operatorCount := Length(Q);
setLength(operatorBank,operatorCount);
for i := 0 to operatorCount - 1 do
operatorBank[i] := Q[i+1];
Write('P(N,R) R=? : ');
ReadLn(S);
if S <> '' then permutationLength := StrToInt(S) + 1;
SetLength(permutation,operatorCount);
curIndex := 0;
Writeln('');
getPermutations(operatorBank, operatorCount, permutation,
permutationLength, curIndex );
end;
except
on E: Exception do
Writeln(E.ClassName, ': ', E.Message);
end;
end.