How exactly should I implement a shuffle or random

2019-02-16 02:21发布

问题:

I already know there's answers for this kind of thing, but I don't really know how to implement them in my code. Also, I would like to refrain from using any more functions unless neccessary. Here's my code:

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

So, what should I alter about this code to make it generate random numbers each time the program executes?

回答1:

You're seeding the same value every time you run, so you'll always get the same pseudo-random sequence. Try this:

srand(time(0));


回答2:

Use 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"));


回答3:

Solution to random shuffle:

  • Put all the numbers you want to shuffle into a container (vector) (Call it the src)
  • Create an empty container that is ordered to put the numbers as you randomly select them (Call it the dst)
  • while (src is not empty)
    • Generate a random number [0,len(src)) (Note not inclusive)
    • Remove the element at src[Rand]
    • Put the removed element into dst


回答4:

Rather than using an array to keep track of which ones have been seen, how about if you store the quotes in a list and simply remove a quote after it has been used.



回答5:

Check out this solution for random shuffle.