通过数组随机递增,c ++

randomly increment through an array, c++

我很难理解使用 'rand()' 从整数数组中随机读取数字的概念。我创建了一个介于 1-3 之间的随机数生成器,并希望输出一个数组的索引,然后让生成器从上一个索引随机输出下一个生成的数字,直到它到达数组的末尾。例如:

  1. 'rand()'= 3, 'array[2]'

  2. 'rand()' = 2, 'array[4]'

  3. 'rand()' = 3, 'array[7]'

如果这有意义??等等等等

我目前使用的代码只是输出一个随机数序列。我放置了一个 'seed' 以便我可以查看相同的序列。

int main() 
{ 
 int arrayTest[20] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 
 17, 18, 19, 20};   
 srand(4);
 for(int i = 0; i < 20; i++)  
    {  
     arrayTest[i] = (rand() % 3);
     cout << arrayTest[i] << endl;
    }




}

我有点猜你到底想要什么。但它似乎想对索引进行随机增量,并使用该索引循环读取数组。

所以这段代码并没有像你想要的那样做任何事情

 arrayTest[i] = (rand() % 3);

它使用顺序(即非随机)索引将随机值写入(而不是读取)数组。

这就是我认为你想要的

int main() 
{ 
    int arrayTest[20] = { ... };   
    srand(4);
    int index = -1;
    for(int i = 0; i < 20; i++)  
    {  
         index += (rand() % 3) + 1; // add random number from 1 to 3 to index
         if (index >= 20) // if index too big for array
             index -= 20; // wrap around to beginning of array
         cout << arrayTest[index] << endl; // read array at random index, and output
    }
}

但我不完全确定,特别是您的 testArray 按顺序排列数字 1 到 20 的方式让我有点怀疑。也许如果你解释为什么你想做任何你想做的事情会更清楚一些。