I am building a version of the Game of Life in ANSI C and I have almost all of the code written for it.
My C source file:
#include <stdio.h>
#include <stdlib.h>
#define HEIGHT 32
#define WIDTH 32
#define COMPASS 8
#define SPACE '.'
unsigned long mask = 0x80000000;
unsigned long neighbours[COMPASS] = { 0 };
unsigned long row[WIDTH] = { 0 };
unsigned long copy[WIDTH] = { 0 };
int northWest(unsigned long row, int rowNum) {
copy[rowNum - 1] = row >>= 1;
return copy[rowNum - 1];
}
int north(unsigned long row, int rowNum) {
copy[rowNum - 1] = row;
return copy[rowNum - 1];
}
int northEast(unsigned long row, int rowNum) {
copy[rowNum - 1] = row <<= 1;
return copy[rowNum - 1];
}
int west(unsigned long row, int rowNum) {
copy[rowNum] = row >>= 1;
return copy[rowNum];
}
int east(unsigned long row, int rowNum) {
copy[rowNum] = row <<= 1;
return copy[rowNum];
}
int southWest(unsigned long row, int rowNum) {
copy[rowNum + 1] = row >>= 1;
return copy[rowNum + 1];
}
int south(unsigned long row, int rowNum) {
copy[rowNum + 1] = row;
return copy[rowNum + 1];
}
int southEast(unsigned long row, int rowNum) {
copy[rowNum + 1] = row <<= 1;
return copy[rowNum + 1];
}
/*void clearRows(unsigned long row[]) {
int i;
system("clear");
for (i = 0; i < HEIGHT; ++i) {
row[i] = 0;
}
}*/
void displayBinary(unsigned long x) {
int bit;
int mask;
for (bit = 0; bit < HEIGHT; ++bit) {
mask = 1 << bit;
printf("%c", (x & mask) ? 'X' : SPACE);
}
printf("\n");
}
int main(void) {
int i, alive;
char ch;
unsigned long init32;
srand(time(NULL));
for (i = 0; i < HEIGHT; ++i) {
init32 = ((double)rand() / RAND_MAX) * 0xFFFFFFFF;
row[i] = init32;
displayBinary(row[i]);
}
do {
system("clear");
for (i = 0; i < HEIGHT; ++i) {
neighbours[0] = north(row[i], i);
neighbours[1] = south(row[i], i);
neighbours[2] = west(row[i], i);
neighbours[3] = east(row[i], i);
neighbours[4] = northWest(row[i], i);
neighbours[5] = northEast(row[i], i);
neighbours[6] = southEast(row[i], i);
neighbours[7] = southWest(row[i], i);
}
for (i = 0; i < HEIGHT; ++i) {
alive += ((mask & neighbours[i]) ? 1 : 0);
displayBinary(row[i]);
}
} while ((ch = getchar()) != 'n');
return EXIT_SUCCESS;
}
What I am aiming for here is to have random 'X' characters printed on a 32x32 board, and have the program loop as long as the user does not type 'n'. For each loop iteration, I would like each coordinate to check its neighbours and "die" if it has less than two neighbours or more than three neighbours. Otherwise, it "lives" and an 'X' is printed at that coordinate.
I understand using bitwise ANDing may not be the best way to complete this, but my professor has asked we use bitwise AND, and so therefore I cannot change that logic.
I am having trouble clearing the rows between loops. Could somebody please help me figure out how to print the updated rows for each iteration of the do loop?
Any help is much appreciated. Thank you.
In order to show what is going on, I added this define,
//#define SPACE (0x20)
#define SPACE ('.')
Then I changed both instances where you printed space,
printf("%c", 0x20);
to
printf("%c", SPACE);
And then ran your program and got a single line, with some "." and some "X", but the second pass resulted in all ".",
Looks like your calculation of adjacent nodes might be wrong.
Why does your print appear wrong?
Because your first COMPASS loop uses displayBinary() 8 times,
for (i = 0; i < COMPASS; ++i) {
init32 = ((double)rand() / RAND_MAX) * 0xFFFFFFFF;
row[i] = init32;
displayBinary(row[i]);
}
While your subsequent looks use printf (rather than calling displayBinary), 8 times to only print 8 characters,
for (i = 0; i < COMPASS; ++i) {
alive += ((mask & row[i]) ? 1 : 0);
if ((alive == 2) || (alive == 3))
printf("%c", 'X');
else
printf("%c", SPACE);
}
Your HEIGHT loop does a recalculation of neighbours[], but you should be reseting row[].
I rewrote your displayBinary function, and this displays the entire row,
void displayBinary(unsigned long x) {
//do {
// printf("%c", (x & mask) ? 'X' : SPACE);
//} while ((mask >>= 1) != 0);
int bit;
int mask;
for( bit=0; bit<32; ++bit )
{
mask = 1<<bit;
printf("%c", (x & mask) ? 'X' : SPACE);
}
printf("\n");
}
Related
I have matrix of '1' and '0' with the dimensions 8x8. I need to store the whole matrix in one unsigned long long variable bit by bit. How can i do that?
For example, let's take the matrix of '1' and '0' that is 2x2:
The matrix 2x2:
1 0
0 1
The variable must contain: 1001 in bits.
The same example, but over the matrix 8x8 and unsigned long long variable.
That's what i've tried to do:
#include <stdio.h>
int main()
{
unsigned long long result = 0;
char matrix[8][8]; // lets that the matrix is already filled by '1' and '0'
for (i=0; i<SIZE; i++)
{
for (j=0; j<SIZE; j++)
{
result = result | ((unsigned long long)(matrix[i][j] - '0'));
result <<= 1;
}
}
return 0;
}
Is it right? I implemented this nested loop in my algorithm and that didn't work properly.
Converting the text representation of an integer into its integer value can be done using strtoull().
char buf[sizeof(matrix)+1];
memcpy(buf, matrix, sizeof(matrix));
buf[sizeof(matrix)] = '\0';
result = strtoull(buf, NULL, 2);
try this
const int mx_size = 8;
int main() {
unsigned long long result = 0;
bool matrix[8][8]; // lets that the matrix is already filled by '1' and '0'
for (int i =0; i < mx_size; ++i)
matrix[i][i] = 1;
for (int i = 0; i < mx_size; i++) {
for (int j = 0; j < mx_size; j++) {
result |= (unsigned long long)matrix[i][j] << (i*mx_size + j);
}
}
return 0;
}
Here you have the code (a bit more
#include <stdio.h>
#include <stdint.h>
uint64_t convert(char matrix[8][8], int order, char zero)
{
uint8_t byte;
uint64_t result = 0;
for(size_t row = 0; row < 8; row++)
{
byte = 0;
for(size_t column = 0; column < 8; column++)
{
byte <<= 1;
byte |= matrix[row][column] != zero ? 1 : 0; //anything != defined zero char is 1
}
if (order)
{
result |= (uint64_t)byte << (8 * row);
}
else
{
result |= (uint64_t)byte << (56 - 8 * row);
}
}
return result;
}
int main(void) {
char matrix[8][8] =
{
{'1','0','1','0','1','0','1','0'},
{'0','1','0','1','0','1','0','1'},
{'1','1','1','0','0','0','1','1'},
{'0','0','0','1','1','1','0','0'},
{'1','1','1','1','1','0','0','0'},
{'0','0','0','0','1','1','1','1'},
{'1','1','0','0','1','1','0','0'},
{'0','0','1','1','0','0','1','1'},
};
unsigned long long result = convert(matrix, 0, '0');
for(size_t index = 0; index < 64; index ++)
printf("%1d", !!(result & (1ULL << index)));
printf("\n");
result = convert(matrix,1, '0');
for(size_t index = 0; index < 64; index ++)
printf("%1d", !!(result & (1ULL << index)));
printf("\n");
return 0;
}
I am trying to implement the sieve of eratosthenes in C. The code works for small input values, but once the input goes beyond a certain range, a run- time error is thrown. This is the second problem in the classical section of the SPOJ base. What is the mistake?
#include<stdio.h>
#include<math.h>
int prime(unsigned long int, unsigned long int);
int main()
{
int nitem;
unsigned long int sn,fn;
scanf("%d", &nitem);
while(nitem)
{
scanf("%lu", &fn);
//printf("%d",fn);
scanf("%lu", &sn);
prime(fn, sn);
nitem--;
}
return 0;
}
int prime(unsigned long int fn, unsigned long int sn)
{
unsigned long int prim[100000];
int i,j,k;
for(i = 0; i < 100000; i++)
{
prim[i] = 1;
}
prim[0] = 0;
prim[1] = 0;
//printf("%d", sn);
//printf("%d", k);
//printf("%d", (k <= sn));
for(k = 2; k <= sqrt(sn); k++)
{
// printf("alksnc%5d", k);
if(prim[k] == 1)
{
for(j = 2; (k * j) <= sn; j++)
{
//printf("%d", prim[k]);
prim[k * j] = 0;
}
}
}
for(int i = 0; i <= sn; i++)
{
if(prim[i] !=0 && i >= fn)
{
printf("%lu\n", i);
}
}
printf("\n");
return;
}
Input:
1
100000 100345
output:
run time error
Input:
1
3 5
output:
3
5
We can make more efficient use of memory (2x) by only sieving odd numbers as all the even numbers you're processing waste time and space. It's trickier to work out but gives us something like:
#include <math.h>
#include <libc.h>
#define MAX_ODD_PRIMES 1048576
void prime(unsigned long fn, unsigned long sn)
{
unsigned char primes[MAX_ODD_PRIMES];
for (unsigned long i = 0; i < MAX_ODD_PRIMES; i++)
{
primes[i] = TRUE;
}
primes[0] = 0; // preset first odd, '1'
for (unsigned long k = 3; k <= sqrt(sn) + 1; k += 2)
{
if (primes[k / 2])
{
for (unsigned long j = 3; (k * j) <= sn; j += 2)
{
primes[k * j / 2] = FALSE;
}
}
}
if (fn <= 2)
{
printf("2\n");
fn = 3;
}
for (unsigned long i = fn / 2; i * 2 + 1 <= sn; i++)
{
if (primes[i])
{
printf("%lu\n", i * 2 + 1);
}
}
}
EXAMPLE
> ./a.out
1 1999900 2000000
1999957
1999969
1999979
1999993
>
1) Array range error.
By changing code
for (j = 2; (k * j) <= sn; j++) {
if (k * j >= 100000) {
printf("Out of range %d %d\n", k, j);
exit(1);
}
prim[k * j] = 0;
}
}
With input 2, 100000
Output
Out of range 2 50000
By using an array (VLA) sized to the task, this is avoided. Many other optimizations available. Consider also a malloc() array.
void prime(unsigned long int fn, unsigned long int sn) {
unsigned long int prim[sn + 1];
2) int prime() eventually performs return; where return something; is expected. Suggest changing function to void prime()
int prime(unsigned long int fn, unsigned long int sn) {
unsigned long int prim[100000];
...
printf("\n");
return;
}
I have to print numbers with max N bits where count of bits set to 1 = count of bits set to 0. I ignoring leading zeros. I thinking that this applies only when count of bits is even.
My code:
int power(k) {
return 1 << k;
}
void print_numbers(int n){
n -= (n % 2); // FOR EVEN COUNT OF BITS
int exp = 1; // EXPONENTS WILL BE ODD (2^1, 2^3, 2^5, ...)
while (exp < n) {
int start = power(exp);
int end = power(exp + 1);
int ones = (exp + 1) / 2; // ALLOWED COUNT OF 1
for (int i = start; i < end; i++) {
int bits_count = 0;
for (int j = 0; j <= exp; j++){ // CHECK COUNT OF 1
bits_count += ((i >> j) & 1);
}
if (bits_count == ones){
printf("%d\n", i);
}
}
exp += 2;
}
For N = 12 this function print 637 numbers. Is this solution correct or am i wrong? Any idea for more efficient or better solution?
I came up with this, which is a totally different approach (and perfectible) but works:
#include <stdio.h>
void checker(int number)
{
int c;
int zeros = 0;
int ones = 0;
for (c = 31; c >= 0; c--)
{
if (number >> c & 1)
{
ones++;
}
else if(ones > 0)
{
zeros++;
}
}
if(zeros == ones)
{
printf("%i\n", number);
}
}
int main()
{
int c;
for (c = 4095; c >= 0; c--)
{
checker(c);
}
return 0;
}
Which get me 638 values (including 0)
I am creating a simple C application using GCC in Ubuntu based on Conway's Game of Life. I have basically all the code that I need, but I'm having trouble with one tiny aspect of the code.
My C source file:
#include <stdio.h>
#include <stdlib.h>
#define HEIGHT 32
#define WIDTH 32
#define COMPASS 8
#define SPACE '.'
unsigned long mask = 0x80000000;
unsigned long row[WIDTH] = { 0 };
unsigned long copy[WIDTH] = { 0 };
int northWest(int rowNum) {
copy[rowNum - 1] = row[rowNum - 1] >>= 1;
return copy[rowNum - 1] & row[rowNum];
}
int north(int rowNum) {
copy[rowNum - 1] = row[rowNum - 1];
return copy[rowNum - 1] & row[rowNum];
}
int northEast(int rowNum) {
copy[rowNum - 1] = row[rowNum - 1] <<= 1;
return copy[rowNum - 1] & row[rowNum];
}
int west(int rowNum) {
copy[rowNum] = row[rowNum] >>= 1;
return copy[rowNum] & row[rowNum];
}
int east(int rowNum) {
copy[rowNum] = row[rowNum] <<= 1;
return copy[rowNum] & row[rowNum];
}
int southWest(int rowNum) {
copy[rowNum + 1] = row[rowNum + 1] >>= 1;
return copy[rowNum + 1] & row[rowNum];
}
int south(int rowNum) {
copy[rowNum + 1] = row[rowNum];
return copy[rowNum + 1] & row[rowNum];
}
int southEast(int rowNum) {
copy[rowNum + 1] = row[rowNum + 1] <<= 1;
return copy[rowNum + 1] & row[rowNum];
}
void clearRows(unsigned long row[]) {
int i;
system("clear");
for (i = 0; i < HEIGHT; ++i) {
row[i] = 0;
}
}
void displayBinary(unsigned long x) {
int bit;
/*int mask;*/
for (bit = 0; bit < HEIGHT; ++bit)
{
mask = 1 << bit;
printf("%c", (x & mask) ? 'X' : SPACE);
}
printf("\n");
}
int main(void) {
int i, j, alive;
char ch;
unsigned long init32;
srand(time(NULL));
for (i = 0; i < HEIGHT; ++i) {
init32 = ((double)rand() / RAND_MAX) * 0xFFFFFFFF;
row[i] = init32;
displayBinary(row[i]);
}
do {
system("clear");
for (i = 0; i < WIDTH; ++i) {
unsigned long neighbours[COMPASS] = {
north(i),
south(i),
west(i),
east(i),
northEast(i),
northWest(i),
southEast(i),
southWest(i)
};
for (j = 0; j < COMPASS; ++j) {
alive += ((mask & neighbours[j]) ? 1 : 0);
}
displayBinary(row[i]);
}
} while ((ch = getchar()) != 'n');
return EXIT_SUCCESS;
}
When the application first starts, the output is what I expect (a 32x32 grid of random 'X' and '.' chars), but for each iteration after that, nothing changes. I want each loop to re-calculate neighbours based on the methods I have (north(), west(), etc...) and print the new 'X' and '.' values on the 32x32 grid.
Can anybody offer some sort of assistance on how to get the new values into the array to be printed on screen? I'm new to programming in C by the way. Thanks.
I do not see where you are updating your row array anywhere in the code. Should not you be updating that in your do while loop ?
Okay I see in your function like one copied below, you are using row >>= 1 to change row as well. But since you are using pass by value instead of pass by reference, the original row value remains unchanged.
int northWest(unsigned long row, int rowNum) {
copy[rowNum - 1] = row >>= 1;
return copy[rowNum - 1];
}
You can use pass by value to fix that.
OR
Since your row array is global, you can change it directly in these functions using the rowNum (index) which you are passing.
Please help me to solve this task:
Generate all binary strings of length n with k bits set.(need to write on C)
for example:
n=5
k=3
11100
00111
11010
01011
**01110
11001
10011
**01101
**10110
10101
** can't generate these permutations
Code:
#include <stdio.h>
#define N 10
int main (void)
{
int mas[N]={0},kst,m,n1,z,a,b;
printf("\n\nVvedit` rozmirnist` masyvu: ");
scanf("%d",&kst);
printf("\n\nVvedit` kil`kist` odynyc`: ");
scanf("%d",&n1);
for(m=0;m1;m++)
mas[m]=1;
for(m=0;m<kst;m++)
printf("%d",mas[m]);
printf("\n");
for(m=0;m<n1;m++){
for(z=0;z<(kst-1);z++)
if((mas[z]==1) && (mas[z+1]==0)){
a=mas[z];
mas[z]=mas[z+1];
mas[z+1]=a;
for(b=0;b<kst;b++)
printf("%d",mas[b]);
printf("\n");
}
}
return 0;
}
I have solved this problem earlier! please find my code below! I hope this will help you out.
#include<stdio.h>
int NumberOfBitsSet(int number)
{
int BitsSet = 0;
while(number != 0)
{
if(number & 0x01)
{
BitsSet++;
}
number = number >> 1;
}
return BitsSet;
}
void PrintNumberInBinary(int number, int NumBits)
{
int val;
val = 1 << NumBits; // here val is the maximum possible number of N bits with only MSB set
while(val != 0)
{
if(number & val)
{
printf("1");
}
else
{
printf("0");
}
val = val >> 1;
}
}
int main()
{
int n,k,i;
int max,min;
printf("enter total number of bits and number of bits to be set:\n");
scanf("%d %d", &n, &k);
min = ((1 << k) - 1); //min possible values with k bits set
max = (min << (n-k)); //max possible value with k bits set!
//printf("%d %d", min, max);
for(i=0; i<= max; i++)
{
if(!(i<min))
{
if(NumberOfBitsSet(i) == k)
{
PrintNumberInBinary(i, (n-1));
printf("\n");
}
}
}
return 0;
}
Your code is a mess ;)
Seriously: first rule when solving a task in code is to write clean code, use sensible variable naming etc.
For tasks like this one I would suggest using this.
Now to your sample code: it would not compile and it is hard to read what you are trying to do. Formatted and with some comments:
#include <stdio.h>
#define N 10
int main(void)
{
int mas[N] = {0};
int kst, m, n1, z, a, b;
/* Read width ? */
printf("\n\nVvedit` rozmirnist` masyvu: ");
scanf("%d", &kst);
/* Read number of bit's set? */
printf("\n\nVvedit` kil`kist` odynyc`: ");
scanf("%d", &n1);
/* m1 is not defined, thus the loop give no meaning.
* Guess you are trying to set "bits" integers to 1.
*/
for (m = 0; m1; m++)
mas[m] = 1;
/* This should be in a function as 1. You do it more then once, and
* 2. It makes the code much cleaner and easy to maintain.
*/
for (m = 0; m < kst; m++)
printf("%d", mas[m]);
printf("\n");
for (m = 0; m < n1; m++) {
for (z = 0; z < (kst - 1); z++) {
if ((mas[z] == 1) && (mas[z + 1] == 0)) {
a = mas[z]; /* Same as a = 1; */
mas[z] = mas[z + 1]; /* Same as mas[z] = 0; */
mas[z + 1] = a; /* Same as mas[z + 1] = 1; */
/* Put this into a function. */
for (b = 0; b < kst; b++)
printf("%d", mas[b]);
printf("\n");
}
}
}
return 0;
}
The extensive use of printf when one are not sure of what is going on is a precious tool.
This is not a solution, (it is basically doing the same as your post, but split up), but a sample of something that might be easier to work with. I have also used a char array as C-string instead of integer array. Easier to work with in this situation.
If you want to use integer array I'd suggest you add a print_perm(int *perm, int width) helper function to get it out of the main code.
#include <stdio.h>
#define MAX_WIDTH 10
int get_spec(int *width, int *bits)
{
fprintf(stderr, "Enter width (max %-2d): ", MAX_WIDTH);
scanf("%d", width);
if (*width > MAX_WIDTH) {
fprintf(stderr, "Bad input: %d > %d\n", *width, MAX_WIDTH);
return 1;
}
fprintf(stderr, "Enter set bits (max %-2d): ", *width);
scanf("%d", bits);
if (*bits > MAX_WIDTH) {
fprintf(stderr, "Bad input: %d > %d\n", *bits, MAX_WIDTH);
return 1;
}
return 0;
}
void permutate(int width, int bits)
{
char perm[MAX_WIDTH + 1];
int i, j;
/* Set "bits" */
for (i = 0; i < width; ++i)
perm[i] = i < bits ? '1' : '0';
/* Terminate C string */
perm[i] = '\0';
fprintf(stderr, "\nPermutations:\n");
printf("%s\n", perm);
for (i = 0; i < bits; ++i) {
/* Debug print current perm and outer iteration number */
printf("%*s LOOP(%d) %s\n",
width, "", i, perm
);
for (j = 0; j < (width - 1); ++j) {
if (perm[j] == '1' && perm[j + 1] == '0') {
perm[j] = '0';
perm[j + 1] = '1';
printf("%s j=%d print\n",
perm, j
);
} else {
/* Debug print */
printf("%*s j=%d skip %s\n",
width, "", j, perm
);
}
}
}
}
int main(void)
{
int width, bits;
if (get_spec(&width, &bits))
return 1;
permutate(width, bits);
return 0;
}
If you want to list all of the permutations uniquely without doing "iterate and check", you can do something like this:
# Move peg x up m using s
# x is negative
# m is positive
def move(x, m, s):
for i in range(1, m+1):
s2 = list(s)
s2[x] = 0
s2[x - i] = 1
print(s2)
if x + 1 < 0:
move(x+1, i, s2)
# Print all unique permutations of
# n bits with k ones (and n-k zeros)
def uniqPerms(n, k):
s = [0 for _ in range(n-k)] + [1 for _ in range(k)]
print(s)
move(-k, n-k, s)
if __name__ == '__main__':
from sys import argv
uniqPerms(int(argv[1]), int(argv[2]))
The idea is that you inch the 1's up recursively, so that each movement produces a unique list (since a 1 is now somewhere none was before).
And you said it must be in C:
#include <stdio.h>
#include <stdlib.h>
enum { n = 8 };
struct string
{
char str[n + 1];
};
void move(int x, int m, string s)
{
for (int i = 0; i <= m; ++i)
{
string s2 = s;
s2.str[n + x] = '0';
s2.str[n + x - i] = '1';
printf("%s\n", s2.str);
if (x + 1 < 0)
move(x + 1, i, s2);
}
}
void uniqPerms(int k)
{
string s;
for (int i = 0; i < n - k; ++i)
s.str[i] = '0';
for (int i = n - k; i < n; ++i)
s.str[i] = '1';
s.str[n] = '\0';
printf("%s\n", s.str);
move(-k, n - k, s);
}
int main(int argc, char *argv[])
{
uniqPerms(atoi(argv[1]));
return 0;
}
try this
A[n-1]=0;
func(n-1);
A[n-1]=1;
func(n-1);
//Think simple people but please bear with me i love java
//Assume array A is globally defined
void Binary(int n)
{
if(n<1)
{
System.out.println(A);
}
else
{
A[n-1]=0;
Binary(n-1);
A[n-1]=1;
Binary(n-1);
}
}
here is the recursive solution
#include <iostream>
#include <vector>
using namespace std;
char v[4];
int count = 0;
void printString(){
int i;
for(i = 0; i < 4; i++){
cout << v[i] << " ";
}
cout <<count << endl;
}
void binary(int n){
if(n < 0){
if(count == 2)
printString();
}
else{
v[n] = '0';
binary(n - 1);
v[n] = '1';
count++;
binary(n-1);
count--;
}
}
int main(){
binary(3);
return 0;
}
#include<stdio.h>
int main(){
int n,k,i,j,a[50];
//lets suppose maximum size is 50
printf("Enter the value for n");
scanf("%d",&n);
printf("Enter the value for k");
scanf("%d",&k);
//create an initial bitstring of k 1's and n-k 0's;
for(i=0;i<n;i++){
if(k>0)
a[i]=1;
else
a[i]=0;
k--;
}
for(i=0;i<n;i++){
if(a[i]==1){
for(j=0;j<n;j++){
if(j!=i&&a[j]==0){
a[j]=1;a[i]=0;
for(k=0;k<n;k++){printf("%d\n",a[k]);}
a[i]=1; a[j]=0;
}}}}
return 0;
}
**If Complexity doesn't matter you can use the following code which are done in java. which will provide the desired output in o(2^n).Here I have find all the combination of 0 and 1 for the given n bits in array of size n.In case of K bit is set I have counted the number of 1 presented is equal to k using countBits() funtion.if so I have printed that array.
public class GenerateAllStringOfNBitsWithKBitsSet {
public static int a[] ={0,0,0,0,0};
static int k=3;
public static boolean countBits(){
int y=0;
for(int i=0;i<a.length;i++)
y += a[i] & 1 ;
if(y==k)
return true;
return false;
}
public static void gen(int n)
{
if(n<1)
{
if(countBits())
System.out.println(Arrays.toString(a));
}
else
{
a[n-1]=0;
gen(n-1);
a[n-1]=1;
gen(n-1);
}
}
public static void main(String[] args) {
GenerateAllStringOfNBitsWithKBitsSet.gen(a.length);
}
}