这可能是一件简单的事情,但我需要创建一个循环结构,使其循环y ^ x次以创建x和y的所有可能组合。例如,如果有4个x并且每个x有2个y,我会想做类似的事情:
for(int a=0; a < y; a++){
for(int b=0; b < y; b++){
for(int c=0; c < y; c++){
for(int d=0; d < y; d++){
// create a new object with values of a, b, c, d
}
}
}
}
基本上,创建x个嵌套for循环以创建总共y ^ x个对象(在本例中为16个)。假设值x和y可以改变,那么最简单和最有效的方法是什么?我假设递归可能在某种程度上涉及,但我不是100%肯定如何去做。
答案 0 :(得分:3)
当您在编译时不知道嵌套级别时,您需要使用递归:该函数应该有一个表示k
的嵌套级别的循环,并继续递归调用自身直到{{1达到了这个级别:
N
初始调用应如下所示:
-(void) nestAtLevel:(int)k withItems:(int[])items from:(int) from to:(int)to {
if (k >= 0) {
for (items[k] = from ; items[k] != to ; items[k]++) {
[self nestAtLevel:k-1 withItems:items from:from to:to];
}
} else {
// Use the indexes produced recursively: the current values are in items 1..N-1
[self creatObjectsWithIndexes:items];
}
}
我假设还有一个函数int items[5];
[self nestAtLevel:4 withItems:items from:0 to:4];
,它接受一个索引项数组,并从中生成一个对象。
答案 1 :(得分:0)
执行此操作的标准方法是使用递归。
你将拥有这样的功能:
void foo(int level, const int max_depth) {
if (level == max_depth) {
// code from final loop
return;
} else {
for (...) {
foo(level+1, max_depth);
}
}
}
现在,您可以在 max_depth 中传递任意数量的嵌套级别。