Goal: To generate N size strings made up of two constituents:
- 0 and
- 1
This program is a rudimentary means to illustrate backtracking and recursion.
If we have N=2 then these are the N size strings:
- 00
- 01
- 10
- 11
And the code in Java is provided here:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
import java.util.Arrays; /** * To generate all N bit strings (of 0 and 1). For instance: * If N=2 then we need to generate 00, 01, 10 and 11 - not * necessarily in that order. * * For simplicity, we have N=4 here. * * @author khanna * */ public class GenNBits { public static int[] array = {0,0,0,0}; public static void main(String[] args) { gen(4); } public static void gen(int N) { if (N < 1) { print(array); } else { array[N-1] =0; gen(N-1); array[N-1] = 1; gen(N-1); } } private static void print(int[] array2) { System.out.println(Arrays.toString(array2)); } } |