Print Combinations of Strings from List of List of String
Since every List has two choices, it's essentially a binary decision. You can think of it as a 3 bit binary number.
e.g.
000
001
010
.....
101
110
111
If you can get the binary representation and convert it to each choice, you can come up with the answer.
For example,
if the first bit is zero then choose 'quick'
if the second bit is one then choose 'red'
if the third bit is zero then choose 'fox'
private static String binary(int numOfBits, int value) {
StringBuilder builder = new StringBuilder();
while (numOfBits>0) {
int a = value % 2;
if (a>0) builder.append("1");
else builder.append("0");
value /= 2;
numOfBits--;
}
return builder.toString();
}
private static List<String> solve(List<String[]> input) {
List<String> result = new LinkedList<String>();
int size = input.size();
int max = (int) ((Math.pow(2, size)) - 1);
List<String> binaryValues = new LinkedList<String>();
for (int i = 0; i<=max; i++) {
String binary = binary(size, i);
binaryValues.add(binary);
}
for (String s : binaryValues) {
StringBuilder builder = new StringBuilder();
for (int i=0; i<s.length(); i++) {
if (s.charAt(i)=='0')
builder.append(input.get(i)[0]);
else
builder.append(input.get(i)[1]);
builder.append(" ");
}
result.add(builder.toString());
}
return result;
}
- Satya Sampathirao October 27, 2014