生成以下序列的算法是什么?

What is an algorithm to generate the following sequence?

我想找出生成具有以下模式的序列的函数。

1 2 3 1 1 2 2 3 3 1 1 1 1 2 2 2 2 3 3 3 3 ....

其中下界数为1,上界数为3。每次数字从1开始,每个数字重复2 ^ n次,n从0开始。

到此为止,希望对你有所帮助

#include <iostream>
#include <math.h>

 int main(){

   for(int n = 0; n < 5;n++){
      for(int i = 1; i < 4;i++){
          for(int j = 0;j < pow(2,n) ;j++){
              std::cout << i;
          }
       }
    }

 return 0;
 }

这是 C++ 中的代码:

#include <iostream>
#include <cmath>

int main()
{
    // These are the loop control variables
    int n, m, i, j, k;

    // Read the limit
    cin >> n;

    // Outermost loop to execute the pattern {1..., 2..., 3...} n times
    for (i = 0; i < n; ++i)
    {
        // This loop generates the required numbers 1, 2, and 3
        for (j = 1; j <= 3; ++j)
        {
            // Display the generated number 2^i times
            m = pow(2, i);
            for (k = 0; k < m; ++k)
            {
                std::cout << j << ' ';
            }
        }
    }
}

您可以在您选择的任何语言中使用相同的逻辑来实现它。