【问题标题】:Nesting "for" Loop n Times嵌套“for”循环n次
【发布时间】:2018-03-13 20:44:17
【问题描述】:

我正在编写一个查找密码的程序。当我看到必须为所选密码长度的变量重复替换部分密码的“for”循环时,我遇到了一个问题。该程序的目标是生成和检查任何字符数组的密码,从“0”开始,经过“?(n次)”,其中“0”是第一个字符,“?”是最后一个字符。

有没有办法让 for 循环重复可变次数而不单独编码?

注意,基于广受好评的 cmets:
“重复一个 for 循环”可能更正确地表示为“嵌套几个 for 循环”。

int maxLength = 32; //Length of the password, changes via input
char output[maxLength] = "";
for (int currentLength = 1; currentLength < maxLength + 1; currentLength++) {
    for (int characterNumber = 0; characterNumber < 96 /*characters found with switch/case, 95 total*/; characterNumber++) {
        for (int position = currentLength /*position in string*/; position > 0; position--) {
            //For loops of character and position currentLength times
            char newCharacter = '\0'; //Avoiding not initialized error, could be and character
            output[position - 1] = getChar(characterNumber, newCharacter);
        }
    }
}

输出示例如下: ...01、02、03...、10、11...、a0、a1...、????4afuh7yfzdn_)aj901...

【问题讨论】:

  • 在你的 for 循环周围环绕一段时间
  • 你的代码有什么问题?
  • @LioraHaydont 代码没有问题(据我所知,这只是对其进行粗略的重写),问题是它还没有完成,正如我在未完成代码的地方评论的那样去。否则我不知道该怎么做。
  • 你可以通过递归获得n-deep for循环的效果
  • 只要有一个流水号并将其转换为 base-96(或您拥有的任何字母大小)。不需要递归或嵌套循环。

标签: c for-loop


【解决方案1】:

您不需要重复 for 循环。相反,您需要嵌套它。
实现这一点的最吸引人的解决方案是递归构造。

伪代码:

void nestloop(int depth, int width)
{
    if(depth>0)
    {
        int i;
        for (i=0; i<width; i++)
        {
            nestloop(depth-1, width);
        }
    } else
    {
        /* do whatever you need done inside the innermost loop */
    }
}

【讨论】:

  • 这应该可行,所以我会尝试并在完成后报告最佳答案。谢谢!
  • 你知道接受答案的概念吗? meta.stackexchange.com/questions/214173/…
  • 我想你可以接受这个答案;对于事先不知道嵌套深度的嵌套循环,递归是一种解决方案。
  • 我不想催你。你有权,甚至被期望,等到你确信你有最好的答案。这样可以避免让那些先获得接受然后再放弃它的回答者感到失望。另一方面,谢谢。 ;-)
  • 应该非常仔细地考虑递归。栈很容易溢出。
猜你喜欢
  • 2020-05-25
  • 2015-07-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-18
  • 2019-10-02
  • 1970-01-01
相关资源
最近更新 更多