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

Asked

Viewed 2,184 times

18

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

For example:

00000
00001
00011
...
11111.

I wanted to keep all the combinations, but I don’t know how to find them all.

8 answers

15

Simple, short, performative, original, library-free 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);
    }
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

If you want maximum performance you can do:

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

But it might not even win because the compiler does optimizations and the top code can turn into this one (I doubt it will happen in case the rest turn around and).

  • What the operator >> ago?

  • 2

    @Sorack https://answall.com/q/52949/101, https://answall.com/q/190575/101, https://answall.com/q/175345/101, https://answall.com/q/7889/101, https://pt.overfstacklowcom/q/10174/101 and https:///pt.stacklowoverf.com/q/91049/101.

12

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

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

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

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

Test this.

11

A simple way, using only one while and without 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 highest value represented by n bits is 2^n - 1, just make the value of x increase of 0 until 2^n-1, displaying the conversion of int for bin.

The exit 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

10


While using

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);
                 }
             }
         }
     }
 }
  • How crazy that so much is inside the other :p

  • @diegofm also found :)

  • It worked, I do not know if it is the best solution but presented me what I wanted. I only needed to take 3 is because I wanted with 5 houses and there are 8 but it worked. Vlw!!!

  • You can do it with recursion too, no?

  • 1

    @Sorack has yes, even an answer has come out now with recursion. In the question which SO-EN link has recursion too.

  • (mask & i) what is this?

  • 1

    That’s a logical @diegofm

Show 2 more comments

6

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

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

Then all combinations with 5 digits will be decimal less than 31, that is, the range that will be possible to represent will be 0-31.

Going a little deeper, the highest 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 in code. Note that you can make it work with combinations that have many more digits just by changing the second parameter of the method Math.pow().

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.

4

You can do it recursively, for any size, using the branch-and-bound concept or Bible 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);

3

According to that one answer, you can do something like that:

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 on the screen all possible combinations, but you instead of printar, can save them in an array

2

Through recursiveness, and in a very readable code, below follows 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);
    }
}}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.