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;
}