Why this bit manipulation program is giving wrong O/P? - bit-manipulation

/* This program's aim is to count the number of bits set in an integer */
#include<stdio.h>
int count=0;
int check(int);
int main()
{
int i,r;
char ch;
printf("enter the integer for which you want to check the bits set");
scanf("%d", &i);
r=check(i);
printf("the number of occurance of 1 in the integer is %d \n", r); /*don't know why isit printing 0 when i give 4 as input */
return 0;
}
int check(int j)
{
if((j & 1)==1)
count++;
for(int l=0;l<31;l++)
{
if( j>>1 & 1)
count++;
}
return count;
}
What is wrong with this program? Looks like some silly mistake or some conceptual one.
Also do we need to write j>>1? can't we simply write j>>?

j >> 1 is wrong, so asking why you need to write that doesn't make much sense.
j >> makes even less sense. You don't write j + or j * either, do you? So why should that work for >>?
Anyway, you could test every bit by shifting by l (that's a lower case L, not a one), or you could change j so it only has to be shifted by 1 at every step. Here's a relatively minimal change to your code that does it the second way, I also changed the global count to a local because it was really poor form.
int check(int j)
{
int count = 0;
for (int l = 0; l < 32; l++)
{
if (j & 1)
count++;
j >>= 1;
}
return count;
}
There are still issues with it.
What if int is not 32 bits? What about the 32nd bit? (ok you can write l < 32 and maybe that's more in line with your code, I'm not sure what you really intended there)
Why is it even signed to begin with?
And check doesn't say much about what this function actually does, you could name this function popcnt or hammingweight or numberOfSetBits or something like that. And personally I'd use a different algorithm, but that's up to you.

Related

Given a integer N>0, how many integers in the interval [0, 2^N) have exactly N-1 set bits? Write a short function that returns the correct answer

I wrote some C++ code to solve this problem:
#include <iostream>
#include <cmath>
using namespace std;
unsigned int countSetBits(unsigned int n)
{
int totalCount = 0, i;
int cond = n-1;
for(i=0;i<pow(2,n);i++){
unsigned int count = 0;
while (i) {
count += i & 1;
i >>= 1;
}
if(count == cond){
totalCount++;
}
}
return totalCount;
}
int main()
{
int n=5;
cout<<countSetBits(5);
return 0;
}
Although it is compiling succesfully, it doesn't print anything.
I can't figure out where is the problem...
Pen and paper solution:
N=2 2^N-1 = 0b11 Possible integers with 1 bit set:
01
10
N=3 2^N-1 = 0b111 Possible integers with 2 bits set:
011
101
110
N=4 2^N-1 = 0b1111 Possible integers with 3 bits set:
0111
1011
1101
1110
So, N seems to be the answer.
The problem is that you are modifying the 'control' variable (i) of your for loop inside that loop, so that the value of i will never reach the loop limit and it will run forever.
To fix this, take a copy of the current i value and modify that:
unsigned int countSetBits(unsigned int n)
{
int totalCount = 0, i;
int cond = n - 1;
int limit = pow(2, n); /// Calculate this ONCE, rather than on each loop!
for (i = 0; i < limit; i++) {
unsigned int count = 0;
int j = i; /// Take a copy of i here (otherwise it will keep getting reset to zero)...
while (j) { /// ...and do your test on the copy!
count += j & 1;
j >>= 1;
}
if (count == cond) {
totalCount++;
}
}
return totalCount;
}
There are also other improvements you can make, as mentioned in the comments. But the code changes I have posted at least fix your problem.
You modify i inside the loop. The inner while loop will always make i == 0, no matter what the loop counter is, hence the condition for the for loop will never be false. Use a temporary. Also don't use pow to calculate powers of 2. 2^N is (1 << N).
You need N+1 bits to represent 2^N. (2^N)-1 has the N lower bits set. There are N possible bits to unset in (2^N)-1, hence there are N numbers with N-1 bits set in [0,2^N). qed ;)
unsigned int countSetBits(unsigned int n) { return n; }

need help for write a function that give me all the states of a number

I have a 192-bit number . and I want two write a function that give me all of the states of this number as follows :
1) all the states with one bit 1
2) all the states with two bits 1
3) all the states with three bits 1
.
.
.
and so on till all of the bits will be 1
also I want to write each of this part in a separate files.
I'v just wrote the states that all of the 1-bits are put together.
for example:(for 16-bits number)
0000000000000011----> then I shift the bits to the left. But I can't find a good way to give me all of states of two bits.
(I use miracle library in C for this big number)
do you have any idea?
thank you :)
You could use 6 for-loops (192/32bit) which loop across all the values of a uint32
inside every-for-loop you can multiply the uint32 by some value to get the right value something like this:
for(uint32_t i = 0; i < 0xFFFFFFFF; i++) {
for(uint32_t j = 0; j < 0xFFFFFFFF; j++) {
bignumber = j + 0xFFFFFFFF*i
print(bignumber)
}
}
or if you want to do it really bitwise you could do some bitmasking inside the for-loops
I do not know your functions. but, if you have num and shiftLeft and equals functions, it can be like this
for (int i=0;i<192;i+=2)
{
num->assing(0b11);
num->shiftLeft(i*2);
if (num->andOperand(victim)->equals(num))
{
//this is the number has two consecutive 11, and only
}
if (num->andOperand(victim)->biggerAndEqual(0b11))
{
//this is the number has at least one , two consecutive 11
}
}
As the problem was stated there are ((2 ^ 192) - 1) numbers to print, because all permutations are covered except 0 which contains no 1 bits. That is clearly impossible so the question must be asking for consecutive bits set. As #n.m. wrote, get it working with 4 bits first. Then extend it to 192 bits. To shift a number, you double it. This solution works without doing any bit shifting or multiplication - by addition only (apart from the bit mask in printbits().
#include<stdio.h>
#define BITS 4
unsigned printmask;
void printbits (unsigned num) {
int i;
for (i=0; i<BITS; i++) {
if (num & printmask)
printf ("1");
else
printf ("0");
num = num + num;
}
printf (" ");
}
int main() {
unsigned num, bits;
int m, n;
printmask = 1; // prepare bit mask for printing
for (n=1; n<BITS; n++)
printmask = printmask + printmask;
num = 1;
for (n=0; n<BITS; n++) {
bits = num;
for (m=n; m<BITS; m++) {
printbits (bits);
bits = bits + bits;
}
printf ("\n");
num = num + num + 1;
}
return 0;
}
Program output
0001 0010 0100 1000
0011 0110 1100
0111 1110
1111

Heap's algorithm in C++ repeating?

I am trying to implement Heap's algorithm in C++.
However, the algorithm starts to repeat if the string it's permuting gets to a length of 4. Here's the code:
void permute(int n, string str, int *total,string array[]){
if (n==0){
array[*total] = str;
*total += 1;
}
else{
for(int c=0; c<=n;c++){
permute(n-1,str,total, array);
if (n % 2 == 0){
char tmpstr=str[c];
str[c]=str[n];
str[n]=tmpstr;
}
else{
char tmpstr=str[0];
str[0]=str[n];
str[n]=tmpstr;
}
}
}
}
int main() {
int total = 0;
string array[24];
permute(3,"abcd",&total, array);
cout << total << endl;
return 0;
}
And here is the output. It repeats at the 13th line
24
abcd
bacd
cbad
bcad
cabd
acbd
dbca
bdca
cbda
bcda
cdba
dcba
abcd <-- right here
bacd
cbad
bcad
cabd
acbd
dbca
bdca
cbda
bcda
cdba
dcba
Thank you guys and any help is welcome!
While it is always an excellent idea to use the standard function recommended by PaulMcKenzie, you have posted a code with a question about why it doesn't work.
In your for loop, get rid of the line if (n%2 ==0) and its else part:
for(int c=0; c<=n;c++){
permute(n-1,str,total, array);
char tmpstr=str[c];
str[c]=str[n];
str[n]=tmpstr;
}
It should then work.
It looks like you are trying to implement the recursive version of the Heap's algorithm for permutation generation stated in wikipedia and originally given in here. If you want to stay close to it (for example, to have the same order when generating the permutations), all you have to do is pass the str parameter as a reference (you'll have to change the line calling the permute() function to pass a mutable string instead a string constant, tough) and keep the if-then-else clause originally in your program.
Nevertheless, it is interesting the version given by #Christophe. I've tried it with up to n=6 (permutations of 7 elements), and still give all permutations. It'd be interesting to know if this can be proved to hold for any natural number. This point may be moot, however, since the recursive version given in the two references I cited does not implement the original version given by Heap, either, and, as far as I know, hasn't been proved to give all permutations either. The original version given by Heap, written in 1963, did not even use structured programming. It was given as a flowgraph to be implemented with goto's.
Here, have my implementations of recursive and iterative versions:
//recursive
int perm_num = 0;
void heappermute(int v[], int n) {
int i;
if (n == 1) {
//print(v);
++perm_num;
}
else {
for (i = 0; i < n; i++) {
heappermute(v, n - 1);
if (n % 2 == 1) {
swap(&v[0], &v[n - 1]);
}
else {
swap(&v[i], &v[n - 1]);
}
}
}
}
int perm_num_iter = 0;
void heappermuteiterative(int v[], int n) {
int c[30];
for (int i = 0; i <= n; ++i) {
c[i] = 0;
}
++perm_num_iter;
//print(v);
int i = 1;
while (i < n) {
if (c[i] < i) {
if (i % 2 == 0) {
swap(&v[0], &v[i]); // or i-1
}
else {
swap(&v[c[i]], &v[i]); // or i-1
}
++perm_num_iter;
//print(v);
++c[i];
i = 1;
}
else {
c[i] = 0;
++i;
}
}
}
I copied the recursive one from somewhere on the net, and the iterative one is the Wikipedia's one written in C.

debug horner's rule programme

I am a beginner and totally confused.
I am getting two errors in my c++ code:
Program:32:5: error: redefinition of 'main'
Program:3:6: note: previous definition of 'main' was here
You are given a polynomial of degree n. The polynomial is of the form P(x) = anxn + an-1xn-1 + … + a0. For given values k and m, You are required to find P(k) at the end of the mth iteration of Horner’s rule. The steps involved in the Horner’s rule are given below,
Pn (x) = an
Pn-1 (x) = an-1 + x * Pn (x) 1st iteration.
Pn-2 (x) = an-2 + x * Pn-1 (x) 2nd iteration.
.
.
P0 (x) = a0 + x * P1 (x) nth iteration.
In general, Pi (x) = ai + x * Pi + 1 (x) and P0(x) is the final result. The input to your program is as follows,
Line 1 contains the integers n, m and k separated by space.
Line 2 contains the coefficients an, an-1…, a0 separated by space.
INPUT: Integers n, m, k and the coefficients as described above.
OUTPUT: P(k) value at the end of the mth iteration.
Sample Input:
2 2 5
3 2 1
Sample Output:
86
Constraints:
1 <= n, k, m <= 10
0 <= ai <=10
#include <stdio.h>
#include <string.h>
int main() {
int num, i, j, result, index;
char name[11][11];
char temp[11];
scanf("%d\n", &num);
for(i = 0; i < num; i++)
scanf("%s\n", name[i]);
for(i = 0; i < num; i++) {
index = i;
for(j = i + 1; j < num; j++) {
result = strcmp(name[index], name[j]);
if(result > 0)
index = j;
}
strcpy(temp, name[index]);
strcpy(name[index], name[i]);
strcpy(name[i], temp);
}
for(i = 0; i < num-1; i++) {
printf("%s", name[i]);
printf("\n");
}
printf("%s", name[num-1]);
return 0;
}
#include<stdio.h>
int horner(int [], int, int);
int main()
{
int n, m, k, i;
int a[10];
scanf("%d%d%d",&n,&m,&k);
for (i=0; i<=n; ++i){
scanf("%d",&a[i]);
}
printf("%d",horner(a,m,k));
return 0;
}
int horner(int a[], int m, int k){
if (m==0){
return a[m];
}
else{
return a[m] + k * horner(a,m-1,k);
}
}
The error message seems to have nailed the problem quite well. You've got two main functions. You can only have one, so pick one and delete the other.
Program:32:5: error: redefinition of 'main'
In "Program", line 32, column 5, the identifier main is defined a second time in the same scope.
Program:3:6: note: previous definition of 'main' was here
The first definition was in "Program", line 3, column 6.
There you are. You cannot define the same function twice. There really is nothing to add.
Except perhaps:
Use consistent indentation. Always four spaces is a good rule. Avoid tabulators if you can, they are asking for trouble.
Always put {} around the blocks of if, for, and while, even if they are only one line. Personally, I even add them if the block is empty, adding a // EMPTY comment to make it explicit that the emptiness is not due to a simple typing error.
Whitespace is free. It does not slow down your typing much, and it does make reading the source much easier. You read source much more often than typing it, so do yourself that favor.
Then there's Debugging 101:
Cut away some source that doesn't look as if it's contributing to your problem (which, in this case, is "redefinition of 'main'", not Horner's Rule).
Check if the problem persists.
Cut away MORE source, until you find the ONE change that makes your error go away. Either the problem is now evident to you, or you have found a minimal example to post on something like StackOverflow.
You could have cut away basically everything and end up with:
int main()
{
return 0;
}
int main()
{
return 0;
}
Hmm... what seems to be the problem? Maybe I re-defined 'main()'? ;-)

Recursive function that takes the sum of odd integers

The program runs but it also spews out some other stuff and I am not too sure why. The very first output is correct but from there I am not sure what happens. Here is my code:
#include <iostream>
using namespace std;
const int MAX = 10;
int sum(int arrayNum[], int n)
{
int total = 0;
if (n <= 0)
return 0;
else
for(int i = 0; i < MAX; i ++)
{
if(arrayNum[i] % 2 != 0)
total += arrayNum[i];
}
cout << "Sum of odd integers in the array: " << total << endl;
return arrayNum[0] + sum(arrayNum+1,n-1);
}
int main()
{
int x[MAX] = {13,14,8,7,45,89,22,18,6,10};
sum(x,MAX);
system("pause");
return 0;
}
The term recursion means (in the simplest variation) solving a problem by reducing it to a simpler version of the same problem until becomes trivial. In your example...
To compute the num of the odd values in an array of n elements we have these cases:
the array is empty: the result is trivially 0
the first element is even: the result will be the sum of odd elements of the rest of the array
the first element is odd: the result will be this element added to the sum of odd elements of the rest of the array
In this problem the trivial case is computing the result for an empty array and the simpler version of the problem is working on a smaller array. It is important to understand that the simpler version must be "closer" to a trivial case for recursion to work.
Once the algorithm is clear translation to code is simple:
// Returns the sums of all odd numbers in
// the sequence of n elements pointed by p
int oddSum(int *p, int n) {
if (n == 0) {
// case 1
return 0;
} else if (p[0] % 2 == 0) {
// case 2
return oddSum(p + 1, n - 1);
} else {
// case 3
return p[0] + oddSum(p + 1, n - 1);
}
}
Recursion is a powerful tool to know and you should try to understand this example until it's 100% clear how it works. Try starting rewriting it from scratch (I'm not saying you should memorize it, just try rewriting it once you read and you think you understood the solution) and then try to solve small variations of this problem.
No amount of reading can compensate for writing code.
You are passing updated n to recursive function as argument but not using it inside.
change MAX to n in this statement
for(int i = 0; i < n; i ++)
so this doesnt really answer your question but it should help.
So, your code is not really recursive. If we run through your function
int total = 0; //Start a tally, good.
if (n <= 0)
return 0; //Check that we are not violating the array, good.
else
for(int i = 0; i < MAX; i ++)
{
if(arrayNum[i] % 2 != 0) //THIS PART IS WIERD
total += arrayNum[i];
}
And the reason it is wierd is because you are solving the problem right there. That for loop will run through the list and add all the odd numbers up anyway.
What you are doing by recursing could be to do this:
What is the sum of odd numbers in:
13,14,8,7,45,89,22,18,6,10
+
14,8,7,45,89,22,18,6
+
8,7,45,89,22,18
+
7,45,89,22 ... etc
And if so then you only need to change:
for(int i = 0; i < MAX; i ++)
to
for(int i = 0; i < n; i ++)
But otherwise you really need to rethink your approach to this problem.
It's not recursion if you use a loop.
It's also generally a good idea to separate computation and output.
int sum(int arrayNum[], int n)
{
if (n <= 0) // Base case: the sum of an empty array is 0.
return 0;
// Recursive case: If the first number is odd, add it to the sum of the rest of the array.
// Otherwise just return the sum of the rest of the array.
if(arrayNum[0] % 2 != 0)
return arrayNum[0] + sum(arrayNum + 1, n - 1);
else
return sum(arrayNum + 1, n - 1);
}
int main()
{
int x[MAX] = {13,14,8,7,45,89,22,18,6,10};
cout << sum(x,MAX);
}