Display every combination of a given array in C - c

I'm trying to write a program with my teacher that displays every possible combination of n numbers (for example, if n = 2, it displays from 01,02,03 etc.. to 89.) I'm using multiple tabs, incrementing the last one to go up to 9, and then incrementing the one just before so I can go from 09 to 12, and so on, but I don't really know how to proceed.
I'm quite new to C programming, so feel free to tell me if anything can be made better.
#include <unistd.h>
ft_putchar(char c)
{
write(1, &c, 1);
}
ft_affichage(int tab[], int nb)
{
int index = 0;
while(index < nb)
{
ft_putchar(tab[index] + 48);
ft_putchar(',');
ft_putchar(' ');
index++;
}
}
int ft_end(int tab[], int nb)
{
int index;
for (index = 0; index < nb ; index++)
{
if (tab[index] != 9 - nb + 1 + index)
{
return 0;
}
}
return 1;
}
void ft_print_comb_n(int nb)
{
int comb[nb];
int index = 0;
// init comb
while(index < nb)
{
comb[index] = index;
index++;
}
ft_affichage(comb, nb);
while(ft_end(comb, nb) == 0)
{
// incrementer comb;
int i = nb - 1;
int max = 9;
while(comb[0] != 9 - nb + 1 + index && comb[nb- 1] != 9 )
{
comb[nb - 1]++;
}
{
}
}
//afficher comb;
ft_affichage(comb, nb);
}
int main(void)
{
ft_print_comb_n(2);
return 0;
}

so feel free to tell me if anything can be made better
Depending on the requirements your teacher gave, the solution below is possible and very simple. It makes use of printf feature that allow to print a variable number of digit of an integer number with leading zero.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
void ft_print_comb_n(int nb)
{
// Compute the limit based on the number of digits
int maxN = (int)(pow(10, nb) + 0.5);
for (int i = 0; i < maxN; i++)
printf("%0*d\n", nb, i);
}
int main(int argc, char *argv[])
{
ft_print_comb_n(3);
return 0;
}

This is based on some old code of mine, but I've forgotten how it works.
int ft_debut(int tab[], int n, int k)
{
if (k <= 0 || k > n)
{
return 0;
}
while (k--)
{
tab[k] = k;
}
return 1;
}
int ft_suivant(int tab[], int n, int k)
{
int i = k;
if (k < 0 || k > n)
{
return 0;
}
while (i--)
{
int x = tab[i];
if (x < --n)
{
do
{
tab[i++] = ++x;
}
while (i < k);
return 1;
}
}
return 0;
}
void ft_print_comb_n(int nb)
{
int comb[nb];
int va;
for (va = ft_debut(comb, 10, nb); va; va = ft_suivant(comb, 10, nb))
{
ft_affichage(comb, nb);
}
}
ft_debut fills tab[] with the initial combination (tab[i] = i for i from 0 to k) if the n and k parameters are valid.
ft_suivant "increments" the combination in tab[] if the n and k values are valid and the combination in tab[] has not yet reached the maximum value. i scans backwards from k-1 to 0, stopping when a tab[i] that can be incremented (the maximum allowed value for tab[i] is n-k+i) has been reached or when tab[0] is already at its maximum allowed value (so tab[] already contains the final combination). If a suitable tab[i] is found, it is incremented by 1, and any remaining elements from tab[i+1] up to tab[k-1]` are set to one more than their preceding element.
Example of ft_suivant for n=10, k=2, tab[0]=2, tab[1]=9:
int i = k; — i=2
while (i--) — true, i=1
{
int x = tab[i]; — x=9 (tab[1])
if (x < --n) — n=9, false
}
while (i--) — true, i=0
{
int x = tab[i]; — x=2 (tab[0])
if (x < --n) — n=8, true
{
do
{
tab[i++] = ++x; — x=3, tab[0]=3, i=1
}
while (i < k); — true
do
{
tab[i++] = ++x; — x=4, tab[1]=4, i=2
}
while (i < k); — false
return 1;
The combination has been successfully "incremented" from {2, 9} to {3, 4}.

Related

Find all the decomposition of a number using only odd numbers and up to N numbers max

I want to find all the decompositions of a number using only odd numbers and up to N numbers max.
For example for the number 7 and N = 3, I can only get 1+1+5, 1+3+3, 7. I can't get 1+1+1+1+3 because it's greater then N.
They hint us to use backtracking.
I strated writing the code and I am stuck. If someone can explian to me how to solve this problem it will be great.
int T(int n, int k)
{
if (k == 0)
{
return;
}
int arr[N];
int f;
for (f = 0; f < N; f++)
{
arr[f] = 0;
}
int sum = 0;
int j = 1;
int i = 1;
int c = 0;
while (j < k) {
sum = sum + i;
arr[c] = i;
if (sum == n)
{
for (f = 0; f < N; f++)
{
if (arr[f] != 0)
{
printf("%d ", arr[f]);
}
}
printf("\n");
}
else if (sum > n)
{
arr[c] = 0;
sum = sum - i;
i = i - 2;
}
else
{
i = i + 2;
j++;
c++;
}
}
T(n, k - 1);
}
Please compile with warnings (-Wall) and fix all of them (-Werror helps make sure you do this). I didn't build your code, but int T(int n, int k) says it returns an int, yet the function code is void.
With backtracking, you can't print at each node because the current node in the graph might not actually lead to a solution. It's premature to commit anything to the result set until you actually reach it.
It's best not to print in functions that perform logical tasks anyway, but it can make the coding easier while developing the logic so I'll stick wiith it.
The backtracking suggestion is a good one. Here's the logic:
The "found result" base case is when n == 0 && k >= 0, if you're decrementing n and k and using them to represent the remaining value to reach the goal and the number of choices left. If you're incrementing variables to count up to n and k, that's fine too, in which case the base case is current_total == n && taken_so_far <= k.
Next, the "failure" base case is k < 0 || n < 0 because we've either overshot n or run out of numbers to take.
After that, the recursive case is, in English, "try taking each odd number i up to n, recursing on the possibility that i might be part of the solution". Per your spec, we don't accept any sequence of descending numbers which prunes the recursion tree a bit.
Here's the code; again, returning a result is an exercise. I'm using a k-sized array to store potential results, then dumping it to stdout only when a result was found.
#include <stdio.h>
#include <stdlib.h>
void odd_decomposition_search(
int n, const int k, int taken_length, int *taken
) {
if (n == 0 && taken_length <= k && taken_length > 0) {
for (int i = 0; i < taken_length - 1; i++) {
printf("%d+", taken[i]);
}
printf("%d\n", taken[taken_length-1]);
}
else if (n > 0 && taken_length < k) {
int i = taken_length ? taken[taken_length-1] : 1;
for (; i <= n; i += 2) {
taken[taken_length] = i;
odd_decomposition_search(n - i, k, taken_length + 1, taken);
}
}
}
void odd_decomposition(const int n, const int k) {
if (n <= 0 || k <= 0) {
return;
}
int taken[k];
odd_decomposition_search(n, k, 0, taken);
}
int main() {
int n = 7;
int k = 3;
odd_decomposition(n, k);
return 0;
}
If you're having trouble understanding the call stack, here's a visualizer you can run in the browser:
const oddDecomp = (n, k, taken=[]) => {
console.log(" ".repeat(taken.length), `[${taken}]`);
if (n === 0 && taken.length <= k && taken.length) {
console.log(" ".repeat(taken.length), "-> found result:", taken.join("+"));
}
else if (n > 0 && taken.length < k) {
for (let i = taken.length ? taken[taken.length-1] : 1; i <= n; i += 2) {
taken.push(i);
oddDecomp(n - i, k, taken);
taken.pop(i);
}
}
};
oddDecomp(7, 3);

Segmentation error in C after printing a method in a for loop

I have a problem when trying to print the numbers in the n given row of Pascal's triangle in C:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main(int argc, char *argv[])
{
int n, k;
double result1, result2;
scanf("%d", &n);
scanf("%d", &k);
result2 = knumberinnrowofpascal(8, 4);
printf("%f\n", result2);
int i = 0;
for (i; i<n; i++) {
result2 = knumberinnrowofpascal(n, i);
printf("%f\n", result2);
}
return 0;
}
int combinations(int n, int k) // calculates combinations of (n,k).
{
if (k == 0)
return 1;
else if (k > n)
return 0;
else
return (combinations(n - 1, k) + combinations(n - 1, k - 1));
}
int knumberinnrowofpascal(int n, int k)
{
double rightmultipier, leftmultiplier, result;
rightmultipier = (double)(n + 1 - k) / k;
leftmultiplier = (double)combinations(n, k - 1);
result = (double)leftmultiplier * rightmultipier;
return result;
}
The function "knumberinnrowofpascal" works, I've tested it above (the 4th element in the 8th row ). The problem is when I try to print these results in a for loop.
rightmultipier = (double)(n + 1 - k) / k;
This will fail if k is 0. And even if it didn't, it would on the next row, because you would have infinite recursion there.
Change:
int i = 0;
for (i; i <= n; i++) {
to
int i;
for (i=1; i <= n; i++) {
I made two improvements there. I fixed the bug and moved the initialization to the for header.
return (combinations(n - 1, k) + combinations(n - 1, k - 1));
when k!=0 and n<k, you recurse with combinations(n-1,k). Decrementing n in this recursion does not change k!=0, and it certainly does not make n > k until it overflows, which means you are in a practically infinite recursion and it segfaults.

Why is the following Code for "A knight's tour" not working properly?

I am using following code in Codeblocks IDE in C, trying to solve the Knight's tour problem using recursion and backtracking. But the thing is it goes on forever and doesn't give any output, though I think it is not a case of Infinite recursion.
#include <stdio.h>
#include <conio.h>
int board[8][8]= {{0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0}};
int i = 1;
int next(int a, int b);
int main()
{
int j, k;
next(0,0);
for(k = 0; k < 64; k++)
{
printf(" %d ", board[k/8][k%8]);
if((i+1)%8==0)
printf("\n");
}
}
int next(int a, int b)
{
if(i==64)
{
board[a][b]=64;
return 1;
}
if((a<0||a>7||b<0||b>7))
return 0;
if(board[a][b]!=0)
return 0;
printf(" %d %d ", a, b);
//getch();
board[a][b]= i;
if(next(a+2, b+1))
{
i++;
return 1;
}
if(next(a+1, b+2))
{
i++;
return 1;
}
if(next(a-1, b+2))
{
i++;
return 1;
}
if(next(a+2, b-1))
{
i++;
return 1;
}
if(next(a-2, b-1))
{
i++;
return 1;
}
if(next(a-1, b-2))
{
i++;
return 1;
}
if(next(a+1, b-2))
{
i++;
return 1;
}
if(next(a-2, b+1))
{
i++;
return 1;
}
board[a][b]=0;
return 0;
}
Your main problem is that you use a global variable to keep track of the length of your tour and therefore the depth of your recursion. You only ever increment this variable.
The length of the path should be a variable for each recursive call and therefore should be local to the next function.
(By the way, i is a horrible name for a global variable. This becomes clear when you make it local: The loop to print the board is over k, but when you check whether to print a newline, you test i. Ouch!)
The test whether the board is full can happen in two ways: Check that the depth is 64 as first thing and just return; don't assign a value. (Even more so, because you haven't ensured that a and b are valid board coordinates.) The 64th jump can be illegal: A path that visits 64 squares has a length of 63, so the 64th jump just indicates that the board is full.
Another way is to check thet i + 1 is 64 after checking that the square is valid. This is equivalent to the first method and saves one call.
With these changes, your program becomes:
#include <stdio.h>
#define N 8
#define NN (N*N)
int board[N][N]= {{0}};
int next(int a, int b, int i);
int main()
{
int k;
if (next(0, 0, 0)) {
for(k = 0; k < NN; k++) {
if(k && k % N == 0) puts("");
printf(" %2d", board[k / N][k % N]);
}
puts("");
} else {
puts("No solution.");
}
return 0;
}
int next(int a, int b, int i)
{
if (a < 0 || a >= N) return 0;
if (b < 0 || b >= N) return 0;
if (board[a][b] != 0) return 0;
i++;
board[a][b] = i;
if (i == NN) return 1;
if (next(a + 2, b + 1, i)) return 1;
if (next(a + 1, b + 2, i)) return 1;
if (next(a - 1, b + 2, i)) return 1;
if (next(a + 2, b - 1, i)) return 1;
if (next(a - 2, b - 1, i)) return 1;
if (next(a - 1, b - 2, i)) return 1;
if (next(a + 1, b - 2, i)) return 1;
if (next(a - 2, b + 1, i)) return 1;
board[a][b] = 0;
return 0;
}
(Pro tip: Test with N == 6 first; Brute-forcing an 8×8 board takes some time, around three minutes on my machine. The 4×4 doesn't have a solution.)

Access Violation in C program involving pointer variable?

I was trying to solve Project Euler question 16 using c. I did not use bignnum libraries. The question asks 2^1000. I decided to store every digit of that number in an array.
For Example: 45 means arr[0]=4, arr[1]=5;
The problem is definitely i the function int multi.
#include<stdio.h>
#include<conio.h>
int multi(int *base, int k);// does the multiplication of array term by 2
void switcher();//switches every term when the fore mostvalue is >10
int finder();// finds the array address of last value
int arr[1000];
int summer();//sums all values of the array
int main()
{
arr[1000] = { 0 };
arr[0] = 1;
int i, j, sum, k, p;
for (i = 0; i < 1000; i++)
{
j = 0;
k = finder();
p = multi(arr + k, j);
}
sum = summer();
printf("sum of digits of 2^1000 is %d", sum);
_getch();
}
int multi(int *base, int k)
{
int p;
if (base == arr)
{
*base = *base - 1;
*base = *base + k;
if (*base > 10)
{
*base = *base - 10;
switcher();
}
return 0;
}
*base = *base * 2;
*base = *base + k;
if (*base > 10)
{
*base = *base - 10;
p = multi(base - 1, 1);
}
else
{
p = multi(base - 1, 0);
}
}
void switcher()
{
int j;
for (j = 0;; j++)
{
if (arr[j] == 0)
{
break;
}
}
j--;
for (; j > 0; j--)
{
arr[j + 1] = arr[j];
}
arr[0] = 1;
}
int finder()
{
int j;
for (j = 0;; j++)
{
if (arr[j] == 0)
{
break;
}
}
return --j;
}
int summer()
{
int summ, i;
summ = 0;
for (i = 0; i<1000; i++)
{
summ = summ + arr[i];
if (arr[i] == 0)
break;
}
return summ;
}
It compiles but during runtime it shows Access Write Violation, base was ......
Please explain this error and how to resolve it ?
Array is of 100 Bytes but you are looping for 1000. Also in function Finder() , you do not have a limit on variable j so your array size is going beyond 100 bytes.
Also use memset to assign array variables to 0.
As said in the comments, 2^1000 has 302 decimal digits.
You're going far outside your array.
But your code is very complicated because you store the digits with the most significant one first.
Since you're only interested in the digits and not the order in which they would be written, you can store the number "in reverse", with the least significant digit first.
This makes the code much simpler, as you can loop "forwards" and no longer need to shuffle array elements around.
Using -1 as "end of number" marker, it might look like this:
void twice(int* digits)
{
int i = 0;
int carry = 0;
while (digits[i] >= 0)
{
digits[i] *= 2;
digits[i] += carry;
if (digits[i] >= 10)
{
carry = 1;
digits[i] -= 10;
}
else
{
carry = 0;
}
i++;
}
if (carry)
{
digits[i] = 1;
digits[i+1] = -1;
}
}
int main()
{
int digits[302] = {1, -1}; /* Start with 1 */
twice(digits); /* digits is now { 2, -1 } */
return 0;
}

Generate all binary strings of length n with k bits set.(need to write on C)

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);
}
}

Resources