We need to write a function of the following form: the input is an array arr , the number n and the function foo . It is necessary that the arr.size() ^ n times be performed on each of the elements of the arr array, i.e. need n nested loops. It is possible to make one cycle from 1 arr.size() ^ n , but this number easily overflows.

For example, when n = 3 function should degenerate into the following:

 for (int i1 = 0; i1 < arr.size(); ++i1) for (int i2 = 0; i2 < arr.size(); ++i2) for (int i3 = 0; i3 < arr.size(); ++i3) foo(arr[i3]); 
  • Um ... Do you want to perform the function so many times that this number causes overflow? ...: -O - Harry
  • @Harry well for an inta and an array of just 2 elements, the overflow already at 2 ^ 32 + will be; the essence is how to multiply these cycles in general - user239635
  • @ user239635 in common data models, int * int will fit into a long long . - jfs

1 answer 1

Recursion, it saves and not in such situations :)

 int total = 0; void foo(int&) { ++total; // do stuff } void cycle(int&a, void (*foo)(int&), int n, int level = 0) { if (level == n) foo(a); else for(int i = 0; i < n; ++i) cycle(a,foo,n,level+1); } int main(int argc, const char * argv[]) { int i = 0; cycle(i,foo,4); cout << total << endl; } 

Is the idea clear? Or to add for specifically an array?