-1

I write a java code to write all combinations of bit string with length N" . this code print all combination but I want to have all combination with exactly N length and "H" 1's.

like N=4 & H=2 => 0011,0101,0110,1100,1010,1001

public void print(int n, char[] k, char[] A) {
    if (n <= 0) {
        System.out.print(String.valueOf(A) + " ");
    } else {
        for (int i = 0; i < k.length; i++) {
            A[n - 1] = k[i];
            print(n - 1, k, A);
        }
    }
}

public static void main(String[] args) {
    String k = "01";
    @SuppressWarnings("resource")
    Scanner in = new Scanner(System.in);
    int n = in.nextInt();
    MiniProject i = new MiniProject();
   i.print(n, k.toCharArray(), new char[n]);

}
Mark B
  • 183,023
  • 24
  • 297
  • 295

1 Answers1

0

There are two approaches:

(1) Before your System.out.print, count the number of 1's in A and see if it matches the count you want.

(2) Define your recursive method to be

public void print(int n, char[] k, char[] A, int numberOfOnes) {

Then:

  • When you call print recursively, the last parameter will depend on whether you just added a 1 or a 0 to A. If you added a 0, then numberOfOnes will be the same as the value that was passed in. If you added a 1, then use numberOfOnes - 1 when you call recursively. For example, say n=4 and you want to generate all 4-bit bit strings with 2 ones. If you set the first bit to 0, you will now want to generate all 3-bit strings with 2 one bits. But when you set the first bit to 1, you will want to generate all 3-bit strings with 1 one bit, since you already used up one of the 1's.

  • Base cases: If numberOfOnes is 0, then just generate n 0 bits as the only solution. If numberOfOnes is greater than n, don't generate anything--it will be impossible.

ajb
  • 31,309
  • 3
  • 58
  • 84