gpt4 book ai didi

C++ 压缩嵌套 for 循环

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:16:59 24 4
gpt4 key购买 nike

我有这些 for 循环。

// output all possible combinations
for ( int i1 = 0; i1 <= 2; i1++ )
{
for ( int i2 = 0; i2 <= 2; i2++ )
{
for ( int i3 = 0; i3 <= 2; i3++ )
{
for ( int i4 = 0; i4 <= 2; i4++ )
{
for ( int i5 = 0; i5 <= 2; i5++ )
{
for ( int i6 = 0; i6 <= 2; i6++ )
{
for ( int i7 = 0; i7 <= 2; i7++ )
{
//output created words to outFile
outFile
<< phoneLetters[n[0]][i1]<< phoneLetters[n[1]][i2]
<< phoneLetters[n[2]][i3]<< phoneLetters[n[3]][i4]
<< phoneLetters[n[4]][i5]<< phoneLetters[n[5]][i6]
<< phoneLetters[n[6]][i7]
<< " ";

if ( ++count % 9 == 0 ) // form rows
outFile << std::endl;
}
}
}
}
}
}
}

它看起来很糟糕,但我是一个新手,不知道从哪里开始压缩它们。

谁能给我一两个指点,这样我就可以让这段代码更整洁一些?

最佳答案

您在七个级别上为 0、1 和 2 编制索引。这可能不是很有效,但是这样怎么样:

int i1, i2, i3, i4, i5, i6, i7;
int j;

for (int i = 0; i < 2187; i++)
{
// 0 through 2186 represent all of the ternary numbers from
// 0000000 (base 3) to 2222222 (base 3). The following
// pulls out the ternary digits and places them into i1
// through i7.

j = i;

i1 = j / 729;
j = j - (i1 * 729);

i2 = j / 243;
j = j - (i2 * 243);

i3 = j / 81;
j = j - (i3 * 81);

i4 = j / 27;
j = j - (i4 * 27);

i5 = j / 9;
j = j - (i5 * 9);

i6 = j / 3;
j = j - (i6 * 3);

i7 = j;

// print your stuff
}

或者,根据 user315052 在评论中的建议:

int d[7];

for (int i = 0; i < 2187; i++)
{
int num = i;
for (int j = 6; j >= 0; j--)
{
d[j] = num % 3;
num = num / 3;
}

// print your stuff using d[0] ... d[6]]
}

关于C++ 压缩嵌套 for 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11747946/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com