7

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.

Smitty
  • 437
  • 2
  • 5
  • 8
  • 9
    If this is homework, please add the homework tag. – Kal Dec 11 '11 at 02:10
  • 2
    I should clarify, all possible numbers within a given range. I.E. all possibilities of a 4 digit binary. Replace 4 with whatever number. It's not homework but I am trying to teach myself java. – Smitty Dec 11 '11 at 02:14
  • 1
    Generally people who have the motivation to teach themselves a language do not use statements like *"I have no idea of where to even start"*. Get a book, read, try simpler tasks.. – Andrew Thompson Dec 11 '11 at 02:36
  • 2
    Thanks for your commentary, but I don't see a real need to defend myself on the internet. I was interested in understanding something, therefore I asked a question. – Smitty Dec 11 '11 at 02:45
  • No offense, but this questions show lack of understanding how computers do math. – harold Dec 11 '11 at 10:33
  • 1
    Thank you for asking the question @smitty. – joshs May 14 '14 at 21:38

7 Answers7

16

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!

eboix
  • 5,113
  • 1
  • 27
  • 38
  • You wouldn't really be generating numbers, but it would still produce the desired output! – eboix Dec 11 '11 at 02:18
7

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.

Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
5
for(int i=0; i < 128; i++){
  System.out.println(Integer.toBinaryString(i));
}

Adjust the max for as high as you'd like to go.

If you need the padded 0's, there was another question on that just today: Pad a binary String equal to zero ("0") with leading zeros in Java

Community
  • 1
  • 1
ziesemer
  • 27,712
  • 8
  • 86
  • 94
2

It helps to know how many possibilities there are.

2^4 = 16, right?

It'll help to know this as well.

Here's how I'd do it:

/**
 * BinaryDemo
 * @author Michael
 * @since 12/10/11
 */
public class BinaryDemo {

    public static void main(String[] args) {
        if (args.length > 0) {
            int n = Integer.parseInt(args[0]);
            int m = 1;
            for (int i = 1; i <= n; ++i) {
                m *= 2;
            }
            System.out.println("# bits  : " + n);
            System.out.println("# values: " + m);
            String format = "%" + n + "s";
            for (int i = 0; i < m; ++i) {
                System.out.println(String.format(format, Integer.toString(i, 2)));
            }

        } else {
            System.out.println("Usage: BinaryDemo <n>");
        }
    }
}
duffymo
  • 305,152
  • 44
  • 369
  • 561
1

My solutions uses the backtracking algorithm. Just print all combinations using '0' and then '1'. It's not better than accepted answer but just one more way to solve the problem.As an example just call the function like below from main()

ArrayList<Integer> chosen = new ArrayList<>(); 
printAllBinaryDigits(4, chosen);

private static void printAllBinaryDigits(int digits, ArrayList<Integer>chosen) {
            if (digits == 0) {
                System.out.println(chosen);
            } else {
                chosen.add(0);
                printAllBinaryDigits(digits-1, chosen);
                chosen.remove(chosen.size()-1);
                chosen.add(1);
                printAllBinaryDigits(digits-1, chosen);
                chosen.remove(chosen.size()-1);
            }

        }
vinni
  • 43
  • 6
1

Below is the solution using Recursion as an approach in java

public class NumberOfBinaryPatterns {
    static int[] bitArray = new int[]{0,1};
    public static void main(String args[])
    {   
        System.out.println("Below are the patterns\n");
        int numberOfBits=3; // It can be any value based on the requirement, i.e. 4,5, etc. We can get the input for "numberOfBits" from user on runtime to enhance this further
        drawBinaryPattern(numberOfBits,"");
    }
    private static void drawBinaryPattern(int n,String seed)
    {
        if(n==0){
            System.out.println(seed);
            return;
        }   
        for(int j=0;j<bitArray.length;j++)
        {
            String temp = seed+bitArray[j];
            drawBinaryPattern(n-1,temp);
        }
    }
}
0

To find all possible permutations of a given binary string(pattern) for example

The permutations of 1000 are 1000, 0100, 0010, 0001

void permutation(int no_ones, int no_zeroes, string accum){
    if(no_ones == 0){
        for(int i=0;i<no_zeroes;i++){
            accum += "0";
        }

        cout << accum << endl;
        return;
    }
    else if(no_zeroes == 0){
        for(int j=0;j<no_ones;j++){
            accum += "1";
        }

        cout << accum << endl;
        return;
    }

    permutation (no_ones - 1, no_zeroes, accum + "1");
    permutation (no_ones , no_zeroes - 1, accum + "0");
}

int main(){
    string append = "";

    //finding permutation of 11000   
    permutation(2, 6, append);  //the permutations are 

    //11000
    //10100
    //10010
    //10001
    //01100
    //01010

    cin.get(); 
}
eldarerathis
  • 35,455
  • 10
  • 90
  • 93
kofhearts
  • 3,607
  • 8
  • 46
  • 79