Invalid operands to binary expressions - recursion

I was solving N queens problem and I wrote isvalid function, but the function gives "invalid operands to binary expressions" error. The error occurs at board[X][Y] == 'Q':
bool isvalid(vector<vector<string>>& board , int &row , int &col , int &n){
int x = row ;
int y = col ;
while(y >= 0){
if(board[x][y] == 'Q'){// THE ERROR IS OCCURING HERE AT BOARD[X][Y]== 'Q'
return false;
}
y-- ;
}
int x = row ;
int y = col ;
while(x >=0 and y>=0){
if(board[x][y] == 'Q')return false;
x-- ;
y-- ;
}
int x = row ;
int y = col ;
while(x < n and y>=0){
if(board[x][y] == 'Q')return false;
x++ ;
y-- ;
}
return true
}

The problem is that there's no corresponding operator== that could be called for the comparison. board[x][y] is a std::string, whereas 'Q' is a char. As you can see on cppreference, second parameter of operator== for comparison with std::string (which is std::basic_string<char>) can either be another std::string (taken by const reference) or const char* (C-style string). Neither of these is char or could be obtained through implicit conversion from char. In particular, see that there's no constructor of std::string taking a single character.
So, the easiest solution is to compare with a string literal "Q" instead. This is an array object of type const char[2] (second character is a null terminator '\0'), which decays into const char* pointer through array-to-pointer conversion, so appropriate overload of operator can be used:
board[x][y] == "Q"
Also, note that you missed a ; after the return statement.

Related

how to return a pointer in a function returning char *?

I'm implementing my own strrchr - it searches for the last occurrence of the character c (an unsigned char) in the string pointed to by the argument str.
example:
Input: f("abcabc" , "b")
Output: "bc"
the function should return char *. How can i return a pointer to the char array in the function?
#include <stdio.h>
#include <string.h>
char* my_strrchr(char* param_1, char param_2)
{
int len = strlen(param_1);
char res ;
for(int i = len; i >= 0 ;i-- ){
if (param_1[i] == param_2){
res = param_1[i];
return *(res);
//here i tried return (char) res, (char*) res; nothing works
}
}
return NULL;
}
int main(){
char *d = "abcabc";
char r = 'b';
my_strrchr(d, r);
return 0 ;
}
You're trying to return value, not a pointer. Operator * means to get value by a pointer, when res isn't a pointer. You should make it a pointer an then return:
char* my_strrchr(char* param_1, char param_2)
{
int len = strlen(param_1);
char *res ; //make it a pointer
for(int i = len; i >= 0 ;i-- ){
if (param_1[i] == param_2){
res = &param_1[i]; //store address of an element to a pointer
return res; //return a pointer
}
}
return NULL;
}
Your variable res is of type char. To get the reference use the reference operator & (See Meaning of "referencing" and "dereferencing" in C):
return &res
However this will result in the address of your variable res and not in the address within your param_1 array. Have a look at Alex' answer to get the correct reference address: https://stackoverflow.com/a/61930295/6669161

Search how many characters are in a C string

My task is to count how many characters are in a C string. The input is provided by a test driver that I don't have access to but my function is supposed to access the data and determine how many characters range from a-z and A-Z but my program keeps failing and I'm not sure what I'm doing wrong.
int countLetters(char * const line)
{
char index = *line;
int count;
while(!index)
{
if (index >= 'a' && index <= 'z')
count++;
if (index >= 'A' && index <= 'Z')
count++;
}
return count;
}
Try this
int countLetters(char * const line)
{
int index = 0;
int count = 0;
while(line[index])
{
if (line[index] >= 'a' && line[index] <= 'z')
count++;
if (line[index] >= 'A' && line[index] <= 'Z')
count++;
index++;
}
return count;
}
Here's what you did wrong
First: You assign your char index = *line;
making your index the first character in the string, which is wrong, because index suppose to represent position, not a character
Second: You didnt provide any mechanism to increase the index in other to loop the string
Third: You didnt initialize your count variable
Note: line[index] is the same as *(line + index)
Your line is a pointer which point to the first character in the string
So line + index is a pointer that point to the index-nth character in the string
By prefix a pointer with a * you're saying that i want to know the content that this pointer point to

Solving QT's QString arg() ambiguity

There is an issue using QString::arg() when a string contains a digit right after a place marker. It's not clear from the QString::arg() function description what would happen in case of such a replacement:
QString("String for replacement %1234").arg("blah");
Will this result in "String for replacement blah234" or "String for replacement blah34"?
I looked in the QT's source code to answer this question. It seems that the algorithm which looks for place markers is 'greedy' and it would take both digits in the example above.
Here is the source of the QT's function which is used inside the QString::arg() (QT 4.8.4):
static ArgEscapeData findArgEscapes(const QString &s)
{
const QChar *uc_begin = s.unicode();
const QChar *uc_end = uc_begin + s.length();
ArgEscapeData d;
d.min_escape = INT_MAX;
d.occurrences = 0;
d.escape_len = 0;
d.locale_occurrences = 0;
const QChar *c = uc_begin;
while (c != uc_end) {
while (c != uc_end && c->unicode() != '%')
++c;
if (c == uc_end)
break;
const QChar *escape_start = c;
if (++c == uc_end)
break;
bool locale_arg = false;
if (c->unicode() == 'L') {
locale_arg = true;
if (++c == uc_end)
break;
}
if (c->digitValue() == -1)
continue;
int escape = c->digitValue();
++c;
if (c != uc_end && c->digitValue() != -1) {
escape = (10 * escape) + c->digitValue();
++c;
}
if (escape > d.min_escape)
continue;
if (escape < d.min_escape) {
d.min_escape = escape;
d.occurrences = 0;
d.escape_len = 0;
d.locale_occurrences = 0;
}
++d.occurrences;
if (locale_arg)
++d.locale_occurrences;
d.escape_len += c - escape_start;
}
return d;
}
Is there a better way of solving such an ambiguity than always using a 2-digit place markers?
Since you can only use %1 to %99 as markers and you can skip marker numbers you can write:
QString("String for replacement %10234").arg("blah");
to output String for replacement blah234
Qt help states for arg(const QString & a, int fieldWidth = 0, QChar fillChar = QLatin1Char( ' ' ))
Returns a copy of this string with the lowest numbered place marker replaced by string a, i.e., %1, %2, ..., %99.
...
Place marker numbers must be in the range 1 to 99.
Therefore, what you're seeing is, by definition, correct; the first two numbers will be replaced. If you're wanting "String for replacement blah234", then you could define the string as: -
QString("String for replacement %1%2").arg("blah").arg(234);
I have the same issue, but the order answers not looks like a good way for me.
I have resolve the ambiguity in this way.
QString myString= QString("ConcatenatedNumbers%0123").arg(66,3,10, QChar('0'));
The string will be:
ConcatenatedNumbers06623

QT QBytearray count character

How I can count characters in QByteArray, for example I have QByteArray and I want to know how many "*" in this array.
From QByteArray documentation:
int QByteArray::count ( const char * str ) const
This is an overloaded function.
Returns the number of (potentially overlapping) occurrences of string str in the byte array.
count.
You could use QByteArray::indexOf(char ch, int from = 0) const inside a loop.
Maybe this:
int i = 0, counter = 0;
while((i = array.indexOf("*", i)) >= 0)
counter++;

Codility K-Sparse Test **Spoilers**

Have you tried the latest Codility test?
I felt like there was an error in the definition of what a K-Sparse number is that left me confused and I wasn't sure what the right way to proceed was. So it starts out by defining a K-Sparse Number:
In the binary number "100100010000" there are at least two 0s between
any two consecutive 1s. In the binary number "100010000100010" there
are at least three 0s between any two consecutive 1s. A positive
integer N is called K-sparse if there are at least K 0s between any
two consecutive 1s in its binary representation. (My emphasis)
So the first number you see, 100100010000 is 2-sparse and the second one, 100010000100010, is 3-sparse. Pretty simple, but then it gets down into the algorithm:
Write a function:
class Solution { public int sparse_binary_count(String S,String T,int K); }
that, given:
string S containing a binary representation of some positive integer A,
string T containing a binary representation of some positive integer B,
a positive integer K.
returns the number of K-sparse integers within the range [A..B] (both
ends included)
and then states this test case:
For example, given S = "101" (A = 5), T = "1111" (B=15) and K=2, the
function should return 2, because there are just two 2-sparse integers
in the range [5..15], namely "1000" (i.e. 8) and "1001" (i.e. 9).
Basically it is saying that 8, or 1000 in base 2, is a 2-sparse number, even though it does not have two consecutive ones in its binary representation. What gives? Am I missing something here?
Tried solving that one. The assumption that the problem makes about binary representations of "power of two" numbers being K sparse by default is somewhat confusing and contrary.
What I understood was 8-->1000 is 2 power 3 so 8 is 3 sparse. 16-->10000 2 power 4 , and hence 4 sparse.
Even we assume it as true , and if you are interested in below is my solution code(C) for this problem. Doesn't handle some cases correctly, where there are powers of two numbers involved in between the two input numbers, trying to see if i can fix that:
int sparse_binary_count (const string &S,const string &T,int K)
{
char buf[50];
char *str1,*tptr,*Sstr,*Tstr;
int i,len1,len2,cnt=0;
long int num1,num2;
char *pend,*ch;
Sstr = (char *)S.c_str();
Tstr = (char *)T.c_str();
str1 = (char *)malloc(300001);
tptr = str1;
num1 = strtol(Sstr,&pend,2);
num2 = strtol(Tstr,&pend,2);
for(i=0;i<K;i++)
{
buf[i] = '0';
}
buf[i] = '\0';
for(i=num1;i<=num2;i++)
{
str1 = tptr;
if( (i & (i-1))==0)
{
if(i >= (pow((float)2,(float)K)))
{
cnt++;
continue;
}
}
str1 = myitoa(i,str1,2);
ch = strstr(str1,buf);
if(ch == NULL)
continue;
else
{
if((i % 2) != 0)
cnt++;
}
}
return cnt;
}
char* myitoa(int val, char *buf, int base){
int i = 299999;
int cnt=0;
for(; val && i ; --i, val /= base)
{
buf[i] = "0123456789abcdef"[val % base];
cnt++;
}
buf[i+cnt+1] = '\0';
return &buf[i+1];
}
There was an information within the test details, showing this specific case. According to this information, any power of 2 is considered K-sparse for any K.
You can solve this simply by binary operations on integers. You are even able to tell, that you will find no K-sparse integers bigger than some specific integer and lower than (or equal to) integer represented by T.
As far as I can see, you must pay also a lot of attention to the performance, as there are sometimes hundreds of milions of integers to be checked.
My own solution, written in Python, working very efficiently even on large ranges of integers and being successfully tested for many inputs, has failed. The results were not very descriptive, saying it does not work as required within question (although it meets all the requirements in my opinion).
/////////////////////////////////////
solutions with bitwise operators:
no of bits per int = 32 on 32 bit system,check for pattern (for K=2,
like 1001, 1000) in each shift and increment the count, repeat this
for all numbers in range.
///////////////////////////////////////////////////////
int KsparseNumbers(int a, int b, int s) {
int nbits = sizeof(int)*8;
int slen = 0;
int lslen = pow(2, s);
int scount = 0;
int i = 0;
for (; i < s; ++i) {
slen += pow(2, i);
}
printf("\n slen = %d\n", slen);
for(; a <= b; ++a) {
int num = a;
for(i = 0 ; i < nbits-2; ++i) {
if ( (num & slen) == 0 && (num & lslen) ) {
scount++;
printf("\n Scount = %d\n", scount);
break;
}
num >>=1;
}
}
return scount;
}
int main() {
printf("\n No of 2-sparse numbers between 5 and 15 = %d\n", KsparseNumbers(5, 15, 2));
}

Resources