1

I've been googling away like a mad man but can't anything that is specific enough for me to get started. Please forgive me for my complete noobiness and possibly diabolical skim reading ability.

Essentially, I have a questionnaire with 9 questions, each with 2 possible answers. After doing the math (2^9), I know that there are 512 permutations.

I am looking to generate a list of all the permutations, without any repetition, to provide me with a list of possible answer combinations.

I would like my output to look similar to this:

112112111

Where the 1s mean that the person selected answer "a" for a question and the 2s mean the person has selected answer "b".

Any help would be appreciated, thank you.

iAmBenzo
  • 51
  • 4

3 Answers3

4

You are just enumerating the numbers between 0 and 512 and you want to print the string in its binary representation with 0s and 1s replaced by 1s and 2s, appropriately padded, so the following code will work:

    for (int i = 0; i < 512; i++) {
        System.out.println(String.format("%9s", Integer.toBinaryString(i)).replace('1', '2').replace('0', '1').replace(' ', '1'));
    }

See this related question for generating a padded binary string in Java: How to get 0-padded binary representation of an integer in java?

Community
  • 1
  • 1
Joe Elleson
  • 1,283
  • 10
  • 15
1

One possible approach would be to find all the numbers between 111111111 and 222222222 that only contain 1s and 2s.

Something like:

for (i=111111111 ; i<=222222222 ; i++)
    if (number_has_only_one_or_twos(i))
         print i
ophintor
  • 181
  • 1
  • 10
0

If I am reading your question correctly, you are just wanting the binary representations of the numbers between 0 and 511 (because 511 - 0 + 1 = 512). All you need to do is find the 9 bit binary representation of each number in that range. Take 0s to mean answer B and 1s to mean answer A.

You could easily convert the binary numbers to strings and replace the 0 with 2 and print out. That's the beauty of binary representations of numbers. It is one of the best ways to find all the permutations in a given range.

Imagine finding the permutations of all elements of an array. Range the numbers from zero to the size of your array, and take a one to mean you want to use that index and a zero to not use that index. It will greatly simplify that problem whenever you run into it.

ctlevi
  • 1,219
  • 8
  • 7