EDIT: My solution is added to the end of the question. Thanks for the hint.
I'll just go with an example. Suppose I have an array with length n
:
arr = { 1, 4, 8, 2, 5, ... }
If I want to traverse all combinations of TWO elements I would write:
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
// do something with arr[i] and arr[j]
}
}
I If I want to traverse all configurations of THREE elements I would simply add another layer of for
iteration:
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
for (int k = 0; k < n; k++) {
// do something with arr[i] and arr[j]
}
}
}
What if the number of elements is given by user (say m
), and we don't know exactly what it is? What should I write then?
(I couldn't figure out the best title for this question. And the tags are not accurate either. Help me with these too, if you want.)
Answer The solution is this function:
void configurations(int depth, int* array, int length, int* indices, int curDepth) {
if (curDepth == 0) {
for (int i = 0; i < depth; i++) {
printf("%d ", indices[i]);
}
printf("\n");
return;
}
for (int i = 0; i < length; i++) {
indices[curDepth - 1] = i;
configurations(depth, array, length, indices, curDepth - 1);
}
}
The usage of the function above is shown below:
int a[] = {9, 8, 7, 6, 5, 4, 3, 2, 1};
int configSize = 3;
int* indices = new int[configSize];
configurations(configSize, a, 9, indices, configSize);
The console will show all configurations of the given size of the elements in the array:
0 0 0
1 0 0
2 0 0
3 0 0
4 0 0
...
5 8 8
6 8 8
7 8 8
8 8 8