dimanche 26 juin 2016

How to get all possible permutations for 0 and 1 bits in JAVA

I need the output of permutation for bits of length 3 to be (the order doesn't matter as the initial combination of 0 and 1 is generated randomly):

[0,0,0]

[0,0,1]

[0,1,0]

[0,1,1]

[1,0,0]

[1,0,1]

[1,1,0]

[1,1,1]

I have done but it seems that there are duplicates and some possible permutation are not being displayed which I'm not sure why. This is my code:

'

  ArrayList<Item> itemsAvailable = new ArrayList<Item>();
  ArrayList<Integer>bits = new ArrayList<Integer>();
  ArrayList<ArrayList<Integer>> tried = new ArrayList<ArrayList<Integer>>();

    itemsAvailable.add(new Item(5,4));
    itemsAvailable.add(new Item(12,10));
    itemsAvailable.add(new Item(8,5));

    System.out.println("itemsAvailable: " + itemsAvailable);

    Random r = new Random();

    //permutations
    for(int i = 0; i < Math.pow(2,itemsAvailable.size()); i++){
        //Generate random bits

        for(int j = 0; j < itemsAvailable.size(); j++){
            int x = 0;

            if (r.nextBoolean())
                x = 1;

            bits.add(x);

        }


        System.out.println("Added to bits #" + (i+1) + ": " + bits);

        bits = new ArrayList<Integer>();
    }

'

The output that I obtained is:

Added to bits #1: [0, 0, 1]

Added to bits #2: [1, 1, 0] - duplicate

Added to bits #3: [1, 0, 1]

Added to bits #4: [0, 0, 1]

Added to bits #5: [0, 0, 0] - dupicate

Added to bits #6: [1, 1, 0] - dupicate

Added to bits #7: [1, 1, 1]

Added to bits #8: [0, 0, 0] - dupicate

Therefore how can I obtain 8 different permutations as the bits are generated randomly? Please help.

Thank you.




Aucun commentaire:

Enregistrer un commentaire