Get all binary combination of size n, but only k 1s
One approach is to generate all combinations of values k
from the set of n
numbers 0 .. n-1
and use those values ββto set the appropriate bits in the output file.
This Q&A explains how to generate all combinations of items k
from n
. When using these combinations, use bitwise OR to 1 << v[c][i]
get the final result, where v[c][i]
is the i
th number from the combination number c
.
source to share
Using the basic recursive method to print the entire binary sequence, all that's left is constraint enforcement:
private static void binSeq(int n, int k, String seq) {
if (n == 0) {
System.out.println(seq);
return;
}
if (n > k) {
binSeq(n - 1, k, seq + "0");
}
if (k > 0) {
binSeq(n - 1, k - 1, seq + "1");
}
}
source to share
Here's my non-recursive implementation of this algorithm. Since there are permutations of 2^n
binary strings, we can use a for-loop to iterate over every possible line and check if the number is greater than "1" k
:
private static void generate(int n, int k) {
for (int i = 0; i < Math.pow(2, n); i++) {
if (Integer.bitCount(i) != k) {
continue;
}
String binary = Integer.toBinaryString(i);
if (binary.length() < n) {
System.out.format("%0" + (n - binary.length()) + "d%s\n", 0, binary);
} else {
System.out.println(binary);
}
}
}
source to share