So I have an array of k elements that start consecutively, for example 0 1 2
I'm trying to have it move up to a certain value say 4, end up with
- 0 1 2
- 0 1 3
- 0 1 4
- 0 2 3
- 0 2 4
- 0 3 4
I understand that every time the last element in the array hits the max value, it has to increment the previous index and set the current index as the value of the previous index 1, and if the previous index's value hits 1 less of the max value, we repeat the steps for the previous index and so on
But I'm unsure on how to approach it such that it will work for any k element array.
Any hints or advice is greatly appreciated!
Update: I attempted making a method that recursively move the index and attempt to add. It works but I don't think its very effective :/
public static int[] nextCombi(int[] arr, int index, int maxVal){
if (index < 0 || maxVal < 0){
return arr;
}
else{
if (arr[index] 1 == maxVal){
if (index - 1 >= 0){
nextCombi(arr, index - 1, maxVal - 1);
arr[index] = arr[index - 1] 1;
}
else{
arr[index] ;
return arr;
}
}
else{
// Can add
arr[index] ;
}
}
return arr;
}
In main
while (true){
arr = nextCombi(arr, max, n);
if (arr[0] > max)
break;
}
CodePudding user response:
I think you should start at the end of the list, and upgrade it until it didn't reach max, and then go at the first item in the list.
Here is an example:
List<Integer> ints = new ArrayList<>(); // create the list
ints.addAll(Arrays.asList(0, 1, 3)); // add element in it:
int max = 4; // indicate max value
int maxOfLast = Integer.MAX_VALUE; // start with max value to be sure of not reached max
for(int currentIndex = ints.size() - 1; currentIndex >= 0; currentIndex--) {
int current = 0;
while((current = ints.get(currentIndex)) < max && (current 1) < maxOfLast) { // until it's not the end or reach max of index 1 value
ints.set(currentIndex, current); // upgrade it
System.out.println(ints); // print (see output)
}
maxOfLast = ints.get(currentIndex); // set current value as max for next interation
}
Output:
[0, 1, 4]
[0, 2, 4]
[0, 3, 4]
[1, 3, 4]
[2, 3, 4]