c++ : dynamic number of nested for loops (without recursion)

后端 未结 3 726
野趣味
野趣味 2020-12-08 11:56

I\'m writing a code segment that iterates through every permutation of n digits. So for example, if n = 3, I would want to iterate through each of the following elements:

3条回答
  •  借酒劲吻你
    2020-12-08 12:24

    In genreral case if you like to replace recursion to flat code you should use the stack (LIFO). So if you have recursive algorithm:

    void print(std::string str, int depth)
    {
      if (depth == n) {
        std::cout << str << std::endl;
        return;
      }
    
      for (int i = 0; i < 10; ++i) {
        char val[2] = { i + '0', 0 };
        print(str + val + ", ", depth+1);
      }
    }
    

    You can transform it to LIFO-based with saving local variables (str and i in this case):

    struct StackItem {
      StackItem(const std::string& ss, unsigned ii)
        : str(ss), i(ii)
        {}
      std::string str;
      int i;
    };
    
    void print_norec()
    {
      std::list< StackItem > stack;
      stack.push_back(StackItem("", 0));
      while (!stack.empty()) {
        StackItem& current = stack.back();
        if (stack.size() == n+1) {
          std::cout << current.str << std::endl;
          stack.pop_back(); // return from "recursive" function
          continue;
        }
        if (current.i < 10) {
          char val[2] = { current.i + '0', 0 };
          // call "recursive" function
          stack.push_back(StackItem(current.str + val + ", ", 0)); 
          current.i++;
        } else {          
          stack.pop_back(); // return from "recursive" function
        }
      }
    }
    

提交回复
热议问题