Random number generator without dupes in Javascript?

后端 未结 6 1780
一生所求
一生所求 2020-11-28 14:53

I need help with writing some code that will create a random number from an array of 12 numbers and print it 9 times without dupes. This has been tough for me to accomplish.

6条回答
  •  攒了一身酷
    2020-11-28 15:22

    The most effective and efficient way to do this is to shuffle your numbers then print the first nine of them. Use a good shuffle algorithm.What Thilo suggested will give you poor results. See here.

    Edit Here's a brief Knuth Shuffle algorithm example:

    
    void shuffle(vector nums)
    {
      for (int i = nums.size()-1; i >= 0; i--)
      {
        // this line is really shorthand, but gets the point across, I hope.
        swap(nums[i],nums[rand()%i]);
      }
    }
    

提交回复
热议问题