Find sum of bits of a char [closed] - c++

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 12 months ago.
Improve this question
I need a queue of size about 8 booleans. Every push should destroy an item from the tail. This can be achieved by a char in the resource limited application.
However I only care about the sum of those "flags", not their individual status. How can I find the sum of the set bits of an 8 bit char?

I come up with two methods.
A method is using a varible to count the sum, whenever you push, you maintain the varible, the change of the varible depends on what you push and what will pop.
Another method is an algorithm called "lowbit"
int lowbit(int x) {
return x & -x;
}
it will return the last 1 int the binary representation of the x.
So this can get the number of '1' in the binary representation of x.
for example, code like this.
int sum_of_1(int x) {
int res = 0;
while (x != 0) res++, x -= lowbit(x);
return res;
}

Counting bits set, Brian Kernighan's way
// count the number of bits set in v
unsigned char sum( unsigned char v )
{
unsigned int c; // c accumulates the total bits set in v
for (c = 0; v; c++)
{
v &= v - 1; // clear the least significant bit set
}
return v;
}
unsigned char push( unsigned char v, bool in )
{
v << 1;
if( in )
{
v |= 1;
}
return v;
}

Related

Expected Primary expression before int inside a function [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 12 months ago.
Improve this question
I am very aware that a lot of the formatting of this code is likely to be completely wrong. I am attempting to create a function GenPathByNumber which itself calls a function Binary. The GenPathBynumber attempts to (for integer x values from 0 through to 2^N - 1) create an array Path for each x value, with entries corresponding to each digit of x's binary representation. Binary converts each x to its binary reresentation, and GenPathByNumber puts binary through a loop.
When trying to build this, the logs keep saying "Expected Primary expression before int" for the Binary function (line 10 in the code below). Please can someone tell me what the problem(s) are?
void GenPathByNumber(int x,int N,int *Path)
{
//Create the array Path of length N, with all entries set to 0
Path[N] = {0};
//runs a for loop of all x values up to 2^N - 1
//and generates a binary path corresponding to each number
// of length N, then stores each digit of this in array Path.
for (int x = 0; x < pow(2,N)-1; x++)
{
binary(int x, int* Path);
}
}
void binary(int x, int* Path) {
if (x == 0) {
printf("%s\n", Path);
} else {
Path[x-1]='0';
binary(x-1);
Path[x-1] = '1';
binary(x-1);
}
}
Inside the for loop in GenPathByNumber you have:
for (int x = 0; x < pow(2,N)-1; x++)
{
binary(int x, int* Path);
}
You don't need the argument type specifiers when you call a function, only when you define it. Remove those and the error goes away.
binary(x, Path);
You have other errors inside the binary function where you're calling it with only one argument, like binary(x - 1);. You probably mean to provide Path in those calls as well.

How to Create an Array with Same Element repeated multiple times in Arduino? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
**array=[symbol,count,symbol,count.....]
for eg: array=[3,2,5,4..]
new_array=[3,3,5,5,5,5...]**
int array[]={25,6,10,2,4,3,9,5};
int value1[16]={0};
Serial.print("\n RLE decoded");
for(i=0;i<len;i++)
{
if(i%2==0)
{
value[i] = array[i];
i=i+1;
count=array[i];
}
for(j=0; j<count;j++)
{
Serial.print(value[i]);
Serial.print('\t');
}
How to Create an Array with Same Element repeated multiple times in Arduino?
This code is working properly and we are able to print repeatedly the symbols but the problem with this code is :: the repeated the values are not getting stored to a new array. we tried with declaring a new array to store the repeated values but it is not working!!
An array is a collection of the same elements, but symbol and count are obviously different things. To group different things together, struct was invented in the earliest days of C
struct {char symbol; byte count;} input[] = {
{'a', 2}, {'X' ,3} ,{'!', 1}
};
const byte inputcount = sizeof(input)/sizeof(input[0]); // 3 in this test
char expanded[20]; // will get the result
void setup() {
Serial.begin(9600);
char* resultpos = expanded;
for (auto& elem:input) {
for (byte p = 0; p < elem.count; p++) {
*resultpos++ = elem.symbol;
}
}
*resultpos = 0; // to make it a printable char array
Serial.println(expanded); // should give "aaXXX!"
}
void loop() {}
If you prefer, you can use the classic type of for loop as well. But this for each is really nice, IMO.

When does the loop terminate in the program because it always has a positive value? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
long long fast_exp(long long int base,long long int exp,int p) {
int res=1;
while(exp>0) {
if(exp%2==1)
{res=(res*base)%p;}
exp=exp>>1;
base=(base*base)%p;
}
return res;
}
It is a function of modular exponentiation. I want to ask about this while loop. When does this loop terminate? Because exp is always greater than 0. I also don't understand this loop in that how it run and how it works line by line. I don't understand the approach of this loop.
First you should format your code or it reads badly.
long long fast_exp(long long int base, long long int exp, int p) {
int res = 1;
while (exp > 0) {
if (exp % 2 == 1) {
res = (res * base) % p;
}
exp = exp >> 1; // Note
base = (base * base) % p;
}
return res;
}
Note the line with a comment. exp right shifts by 1 every iteration of the loop, so it'll eventually reach zero, terminating the loop.
I think Wikipedia explains this algorithm well so I don't have to repeat it. The pseudocode that Wikipedia shows is almost exactly the same as your code. Just compare them line-by-line.
There are also a few mistakes here:
The modulus is given as int p, which should have been long long p
The return value is int res, which should have been long long res

Anti-Digest operation on string always returning the same value [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I am looking for some way to "digest" a string, but always return the same 32 (or 64) byte long value (as a hex string or plain characters). Something like the following code does:
std::string digest(const std::string& input)
{
std::string result = "";
// do something with the input string, update result accordingly
return result;
}
and a little bit more details: I want exactly the opposite of what a classical digest function does which is that for each different string it returns a different but always the same (1 to 1) value. I want a function which for each string returns every time the same value (n to 1).
Obviously, "easy" solutions as return the same constant result every time are not considered a solution :) The code should actually digest the input string and build up the result as a result of the operation.
And an example:
digest ("fox") == digest ("whale")
should be true.
Or mathematically speaking:
for ∀ a and b if a != b => digest (a) == digest(b). That is why i called this anti-digest.
A long mathematical demonstration
Your requirement is:
a!=b => digest(a)==digest(b)
Let's take another message any other message c, and suppose it's different from a and b:
a!=c => digest(a)==digest(c)
b!=c => digest(b)==digest(c)
From this you see that the digest will be constant for any c unless it is equal to a or b.
Now take another message x whatever it may be:
c!=x => digest(c)==digest(x)
By contraposing this implication, this is equivalent to :
digest(x)!=digest(c) => c==x
So suppose there would be an x with a digest different from the constant digest(c). The we have:
digest(x)!=digest(c) and digest(x)!=digest(a)
=> x==c and x==a
=> c==a
=> digest(c)!=digest(a)
But this contradict out original hypothesis about a, c, digest(a) and digest(c), so there can't be such an x. So you can conclude that your digest MUST BE a strictly constant function.
Now suppose your function would not be constant:
digest(x)!=digest(a) => x==a
but if digest is a function, it will always return the same result for the same input, meaning that x==a => digest(x) ==digest(a). This demonstrates that there is no other solution than a constant function.
In short and in C++
A function will return the same result for the same parameter, unless there are side effet (static variable or whatever). Your requirement of having same result for different values, but different result for same values is simply not feasible in a function with only one parameter.
It seems, I was somehow unclear on what I want to achieve ...
Anyway, I came up with the following:
static const size_t DIGEST_SIZE = 32;
std::string antiDigest(const std::string& a)
{
if(a.empty()) { throw "cannot digest empty string"; }
char r[DIGEST_SIZE ] = {0};
int block_size = std::min(DIGEST_SIZE, a.length());
int block_count = 1 + DIGEST_SIZE / a.length();
for(int i=0; i<block_size; i++)
{
int hlp = 0, bc = 0;
while(bc < block_count)
{
int idx = i + bc * block_size;
if(idx >= a.length()) break;
hlp += a[idx];
bc ++;
}
hlp = (int)(hlp << 3) + hlp;
unsigned int hlp2 = 0;
while(hlp)
{
int t = hlp - ((hlp/10) * 10);
hlp2 += t;
hlp /= 10;
}
bc = 0;
while(bc < block_count)
{
int idx = i + bc * block_size;
if(idx >= DIGEST_SIZE) break;
r[idx] = ( (hlp2 / 10) + (hlp2-(hlp2/10)*10)) ;
bc++;
}
}
std::stringstream result;
for(int i=0; i<DIGEST_SIZE; i++)
{
result << int_to_hex(r[i]) ;
}
return result.str();
}
On ideone: http://ideone.com/t4dibL
Obviously, this can be obfuscated even more with replacing the mathematical operations with bitwise operations, but for a proof of concept this does it.

explanation of this recursive function [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 8 years ago.
Improve this question
hey there can anyone tell me how this function work ?!
for function and void function :
int countoccu(int array[],int value,int lower,int upper)
{
int counter=0;
if(lower==upper)
if (array[lower]==value)
return 1;
else
return 0;
else
counter = counter + countoccu(array, value, lower+1, upper);
if (array[lower]==value)
counter++;
return counter;
};
can anyone explain this for me
the output will be 3
void main()
{
int array[5]={3,7,3,3,11};
cout << countoccu(array,3,0,4) << endl;
}
It's a very stupid way to count number of value occurrences, for a given array, in given [upper, lower] range, using recurrence.
(If I understood it good.)
This looks like a homework, so I'll leave figuring it how it happens to you. My hint would be analyze code line by line, with a paper-sheet-pencil debugger.
int countoccu(int array[],int value,int lower,int upper){
int counter=0;
// Check if the end of the array is reached
if(lower==upper)
// Is the last element the "value" we are looking for?
if (array[lower]==value)
// Yes, so count it
return 1;
// No, don't count it
else return 0;
// Not the end of the array
else
// Move the position to the next item in the array and count it and all the following values that equals "value"
counter=counter+countoccu(array,value,lower+1,upper);
// Is the current item equal to the value being counted?
if (array[lower]==value)
// Yes, so count it
counter++;
return counter;
In your example you will get these calls:
countoccu(array,3,0,4) = 1+0+1+1+0 = 3
countoccu(array,3,1,4) = 0+1+1+0 = 2
countoccu(array,3,2,4) = 1+1+0 = 2
countoccu(array,3,3,4) = 1+0 = 1
countoccu(array,3,4,4) = 0 = 0
Though the function is written badly its principle of the work is simple. It checks whether the element with lower index is equal to the given value. If so it increases the count and adds the count for the array starting from the next index after index lower that is lower + 1 (calling itself at this time with lower + 1).
I would rewrite the function the following way
/* constexpr */ size_t count( const int a[], size_t n, int value )
{
return ( n == 0 ? 0 : ( ( a[0] == value ) + count( a + 1, n - 1, value ) ) );
}
I commented specifier constexpr because I think you do not know its meaning. So it may be omited.