0

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

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;
}

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

4

5 回答 5

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"));
于 2010-07-02T20:56:18.127 回答
1

随机洗牌的解决方案:

  • 将所有你想洗牌的数字放入一个容器(向量)(称之为 src)
  • 创建一个空容器,按顺序放置随机选择的数字(称之为 dst)
  • while (src 不为空)
    • 生成一个随机数 [0,len(src)) (注意不包括在内)
    • 删除 src[Rand] 处的元素
    • 将移除的元素放入 dst
于 2010-07-02T20:57:33.960 回答
1

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

srand(time(0));
于 2010-07-02T21:00:59.220 回答
0

与其使用数组来跟踪已查看的内容,不如将引号存储在列表中并在使用后简单地删除引号。

于 2010-07-02T20:52:43.810 回答
0

查看此解决方案以进行随机洗牌。

于 2010-07-02T20:54:06.220 回答