I am supposed to write a program that would print out all possible N-bit sequences with K 1s, the rest (N - K) would be 0s. There should be also a counter that indicates how many sequences are there in the end.
In my case, N = 9 and K = 3, so the program should write out something like this:
111000000
110100000
...
101100000
101010000
...
000000111
Total: 84
So far, my code looks like this
// N bits and K 1s
import java.util.ArrayList;
import java.util.Arrays;
public class Sequence {
public static void main(String[] args) {
ArrayList<int[]> all = new ArrayList<>();
int counter = 0;
int first = 0;
int second;
int third;
for (int i = first; i < 9; i++) {
int[] sequence = {0, 0, 0, 0, 0, 0, 0, 0, 0};
// the 1st "1"
sequence[i] = 1;
second = i + 1;
for (int j = second; j < 9; j++) {
int[] seq2 = sequence;
// the 2nd "1"
seq2[j] = 1;
third = j + 1;
for (int l = third; l < 9; l++) {
int[] seq3 = seq2;
// the 3rd "1"
seq3[l] = 1;
all.add(seq3);
counter++;
seq3[l] = 0;
third++;
}
second++;
}
first++;
}
for (int[] sequences : all) {
System.out.println(Arrays.toString(sequences));
}
System.out.println("Total: " + counter);
}
}
but it doesn't seem to do it and I cannot figure out why. The code is in java and I used an ArrayList of arrays of 9 integers for the 9-bit sequences.