As junior java programmer I am working with Euler project and I would like to create a general purpose class which generates all the combinations from the length
and number of choosen
elements. The class returns a list of boolean
arrays with length of length
. Each array has choosen
true value which highlight the chosen elements the others are false. I have a working solution (I mean it is tested to small numbers) but I wonder is there any opportunity to improve the performance or improve some other aspect. Here it is:
public static List<boolean[]> generate(int length, int choosen){
List<boolean[]> variationList = new ArrayList<>();
boolean[] actual = initArray(length, choosen);
variationList.add(actual.clone());
while(incrementArray(actual)) {
variationList.add(actual.clone());
}
return variationList;
}
private static boolean[] initArray(int length, int choosen) {
boolean[] array = new boolean[length];
for (int index=0; index<choosen; index++) {
array[index] = true;
}
return array;
}
private static boolean incrementArray(boolean[] actual) {
for(int index = actual.length-1; index > -1 ; index--) {
if(actual[index]) {
if(moveForward(actual, index)) {
return true;
}
}
}
return false;
}
private static boolean moveForward(boolean[] actual, int position) {
if(position<actual.length-1 && !actual[position+1]) {
actual[position] = false;
actual[position+1] = true;
copyBack(actual, position);
return true;
}else {
return false;
}
}
private static boolean copyBack(boolean[] actual, int position) {
boolean answer = false;
int delay = 2;
for (int index = position+2; index<actual.length;index++) {
if(actual[index]) {
actual[index] = false;
actual[position + delay] = true;
delay++;
answer = true;
}
}
return answer;
}
Edit
Euler project was only the motive I would like to find a way independently. My aim was produce all of the combinations (by the way my solution for the original problem needed them all (not just the number of them) but there is a workaround which no need combination at all). Some example of the method:
CombinationGenerator.generate(5, 1);
The result:
true false false false false
false true false false false
false false true false false
false false false true false
false false false false true
Invocation:
CombinationGenerator.generate(5, 3)
The result:
true true true false false
true true false true false
true true false false true
true false true true false
true false true false true
true false false true true
false true true true false
false true true false true
false true false true true
false false true true true