Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print list of binary permutations

Tags:

java

algorithm

What I am trying to do is print all the possibilities of a binary number n digits long. In other words, with a 4 digit number:

0001
0010
0100
1000

..etc

To be honest, I have no idea of where to even start with this (other than I figure I'd need to use a loop, and probably an array) so any pointers in the right direction would be appreciated.

like image 478
Smitty Avatar asked Dec 11 '11 02:12

Smitty


2 Answers

Maybe you could use a recursive algorithm:

public void printBin(String soFar, int iterations) {
    if(iterations == 0) {
        System.out.println(soFar);
    }
    else {
        printBin(soFar + "0", iterations - 1);
        printBin(soFar + "1", iterations - 1);
    }
}

You would execute this like this:

printBin("", 4);

That would give you all possible binary numbers with 4 digits.

Hope this helped!

like image 70
eboix Avatar answered Sep 19 '22 10:09

eboix


For an n-bit binary number, there are 2^n "permutations". You just need to loop over the integers from 0 to (1<<n)-1, and convert each one to binary.

like image 26
Oliver Charlesworth Avatar answered Sep 23 '22 10:09

Oliver Charlesworth