我究竟应该如何为数组实现随机数或随机数算法以随机顺序显示引号?

时间:2010-07-02 20:47:28

标签: c++ random shuffle

我已经知道有这种事情的答案,但我真的不知道如何在我的代码中实现它们。另外,除非必要,否则我想不再使用任何其他功能。 这是我的代码:

int main()
{
 unsigned seed;
 seed = 1;
 srand(seed);
 std::string starFox[8];
 int x[8];
 starFox[0] = "Do a barrel roll!";
 starFox[1] = "Try a somersault!";
 starFox[2] = "Use bombs wisely!";
 starFox[3] = "Something is wrong with the G-diffuser";
 starFox[4] = "Can't let you do that, Star Fox";
 starFox[5] = "Hey Einstein, I'm on your side";
 starFox[6] = "Whoa! help me!";
 starFox[7] = "Daddy screamed REAL good before he died!";

 for(int i=0; i<8; i++)
 {
  int y = 0 + rand() % 8;
  x[i] = y;

  if (x[i-1]!=y || x[i-2]!=y || x[i-3]!=y || x[i-4]!=y || x[i-5]!=y || x[i-6]!=y || x[i-7]!=y)
  {//now I need to make a statement that makes sure each number appears once.
   std::cout << starFox[y] << "\n";}
 }
 std::cout << '\n';

 return 0;
}

那么,每次程序执行时,我应该对此代码进行哪些更改以使其生成随机数?

5 个答案:

答案 0 :(得分:5)

使用std::random_shuffle

// Shuffle
std::random_shuffle(starFox, starFox + 8);

// And write to standard output
std::copy(starFox, starFox + 8,
          std::ostream_iterator<std::string>(std::cout, "\n"));

答案 1 :(得分:1)

随机随机播放的解决方案:

  • 将您想要随机播放的所有数字放入容器(矢量)(将其命名为src)
  • 创建一个空容器,在您随机选择它们时命令放置数字(将其命名为dst)
  • while(src不为空)
    • 生成随机数[0,len(src))(注意不包括在内)
    • 删除src [Rand]
    • 上的元素
    • 将删除的元素放入dst

答案 2 :(得分:1)

每次运行时都播种相同的值,因此您将始终获得相同的伪随机序列。试试这个:

srand(time(0));

答案 3 :(得分:0)

不是使用数组来跟踪已经看到的数组,而是如何将引号存储在列表中并在使用之后删除引号。

答案 4 :(得分:0)

查看此solution以获取随机随机播放。