For example, if I wanted all binary strings of length 3 I could simply declare them like this:
boolean[] str1 = {0,0,0};
boolean[] str2 = {0,0,1};
boolean[] str3 = {0,1,0};
boolean[] str4 = {0,1,1};
boolean[] str5 = {1,0,0};
boolean[] str6 = {1,0,1};
boolean[] str7 = {1,1,0};
boolean[] str8 = {1,1,1};
What is the most efficient way to generate all possibly binary strings of length N into a boolean array?
I don't necessarily need the most efficient method, just one that's fairly efficient and easy for me to multithread.
EDIT: I should note that I will be storing them all in an ArrayList, if that matters.
Approach: For any digit length N, there will be 2N binary numbers.
This is how I did it in Java
public class NbitsStrings {
int[] arrA;
public static void main(String[] args) throws java.lang.Exception {
Scanner input = new Scanner(System.in); //Input the Number Of bits you want.
int n = input.nextInt();
NbitsStrings i = new NbitsStrings(n);
i.nBits(n);
}
public NbitsStrings(int n) {
arrA = new int[n];
}
public void nBits(int n) {
if (n <= 0) {
StringBuilder builder = new StringBuilder();
for (int value : arrA) {
builder.append(value);
}
String text = builder.toString();
System.out.println(text);
} else {
arrA[n - 1] = 0;
nBits(n - 1);
arrA[n - 1] = 1;
nBits(n - 1);
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With