How to know all possible combinations of 0 and 1 in Java?

17

What combinations can you get only with 0 and 1 numbers using 5 boxes (digits)?

For example:

00000
00001
00011
...
11111.

I wanted to save all the combinations, but I do not know how to find all of them.

    
asked by anonymous 17.05.2017 / 15:26

8 answers

10

Using While

for (int i = 0; i < 256; i++) {
    int mask = 256;
    while (mask > 0) {
        if ((mask & i) == 0) {
            System.out.print("0");
        } else {
            System.out.print("1");
        }
        mask = mask >> 1;
    }
}

Using For

 for (int i = 0; i < 2; i++) {
     for (int j = 0; j < 2; j++) {
         for (int k = 0; k < 2; k++) {
             for (int l = 0; l < 2; l++) {
                 for (int m = 0; m < 2; m++) {
                     System.out.println("" + i + j + k + l + m);
                 }
             }
         }
     }
 }
    
17.05.2017 / 15:29
16

Simple, short, performance, original, non-library solution with pure math and a single loop.

class HelloWorld  {
    public static void main (String[] args) {
        for (int i = 0; i < 32; i++) {
            System.out.println("" + i / 16 % 2 + i / 8 % 2 + i / 4 % 2 + i / 2 % 2 + i % 2);
        }
    }
}

See running on ideone . And at Coding Ground . Also put it on GitHub for future reference .

If you want the maximum performance you can do:

"" + ((i >> 4) & 1) + ((i >> 3) & 1) + ((i >> 2) & 1) + ((i >> 1) & 1) + (i & 1));

But you may not have won because the compiler does optimizations and the above code can become that (I doubt it will happen in case the rest becomes and ).     

17.05.2017 / 16:14
12

A simple way, using only while and no recursion:

int x = 0;
int n = 5;

// Enquanto x < 2^n:
while (x < Math.pow(2, n)) {
  System.out.println(
    // Converte de int para bin, formatando corretamente quanto aos zeros a esquerda:
    String.format("%"+n+"s", Integer.toBinaryString(x++)).replace(' ', '0') 
  );
}

As the largest value represented by% bits% is n , just make the value of 2^n - 1 increment from x to 0 , displaying the conversion from 2^n-1 to int . p>

The output will be:

00000
00001
00010
00011
00100
00101
00110
00111
01000
01001
01010
01011
01100
01101
01110
01111
10000
10001
10010
10011
10100
10101
10110
10111
11000
11001
11010
11011
11100
11101
11110
11111
    
17.05.2017 / 15:54
12

If there are 5 houses, so there are 2 ^ 5 combinations, so just loop through all 32 combinations.

for (int i = 0; i < 32; i++){
      System.out.println(Integer.toBinaryString(i));
}

If you want with String.format with %05d , this will indicate that you will have 0 until you have 5 digits.

for (int i = 0; i < 32; i++){
     System.out.println(String.format("%05d", Integer.parseInt(Integer.toBinaryString(i))));
}

Try this.

    
17.05.2017 / 15:57
7

A good way to do this is to treat these combinations as binary numbers (most likely this is the real intention).

In this specific case, it is simple, the highest 5-digit binary is 11111 , which is represented as 31 in the decimal system - 11111 (bin) = 31 (dec) .

Then all combinations with 5 digits will be decimals smaller than 31 , that is, the range that can be represented will be 0-31.

Going a little deeper, the largest value represented by N bits is 2 ^ N - 1.

That is, 5 bits can represent up to 2 ^ 5-1, which is 31.

Here's an example code. Note that you can make it work with combinations that have a lot more digits just by changing the second parameter of the Math.pow() method.

class Main 
{
    public static void main(String[] args) 
    {
        // 5 é a quantidade de dígitos das suas "combinações"
        int num = (int)Math.pow(2, 5);

        for(int i = num; i >= 0; i--)
        {
            System.out.println(asBin(i));   
        }
    }

    private static String asBin(int i){
        return String.format("%05d", Integer.parseInt(Integer.toBinaryString(i)));
    }
}

See working on repl.it.

    
17.05.2017 / 16:05
5

Can be done recursively, for any size, using the branch-and-bound concept or binary tree

int count = 0;

rec(String palavra,int ind,int total,String[] saida){
    if(ind<total){
        rec(palavra+"0",ind+1,total,saida);
        rec(palavra+"1",ind+1,total,saida);
    } else {
        saida[this.count++] = palavra;
    }
}

In this case, the first call would be

this.count = 0;
int total = 5;
String[] saida = new String[(int) Math.pow(2,total)];
rec("",0,total,saida);
    
17.05.2017 / 15:39
4

Second this , you can do something like this:

for (int i = 0; i < 2; i++){
      for (int j = 0; j < 2; j++){
        for (int k = 0; k < 2; k++){
          for (int l = 0; l < 2; l++){
            for (int m = 0; m < 2; m++){
               System.out.println("" + i + j + k + l + m);
            }
          }
        }
      }
    }

Here it will write all the possible combinations on the screen, but instead of printing, you can save them in an array

    
17.05.2017 / 15:29
3

Through recursion, and in a fairly readable code, below is a simple program to adapt to N number of digits through a tree.

import java.util.ArrayList;
public class Start {

private static ArrayList<String> listaResultados;

public static void main(String[] args) {
    listaResultados = new ArrayList<String>();
    int numeroDigitos = 5;
    chamadaRecursiva("", numeroDigitos);
    for(String numero : listaResultados){
        System.out.println(numero);
    }

}

public static void chamadaRecursiva(String numeroActual, int numeroIteracoesEmFalta) {
    if(numeroIteracoesEmFalta == 0) {
        listaResultados.add(numeroActual);
    }
    else {
        chamadaRecursiva(numeroActual + "0", numeroIteracoesEmFalta - 1);
        chamadaRecursiva(numeroActual + "1", numeroIteracoesEmFalta - 1);
    }
}}
    
17.05.2017 / 15:58