2

I'm implementing the Fisher-yates shuffle in a Photoshop script. I want to create an array of n unique random elements from a maximum of about 99999. Where n is a small value but could be up to to maximum.

With maximum of under a thousand this is fine (runs in milliseconds), but considerably much slower for 10,000 (about 20 seconds).

Is there a better/faster way to do this? Bear in mind that'll it'll need to be in ECMAScript.

var maxNumber = 99; 
var numToGenerate = 5; 

var bigShuffle = shuffle(maxNumber);
var randomNumbers = bigShuffle.slice(0, numToGenerate);

alert(randomNumbers);


function shuffle(m)
{

   var temp;
   var rnd;

   // create an empy array
   var arr = new Array();

   for(var i = 0 ; i < m; i++) 
   {
      arr.push(i);
   }

   while (m)
   {
      rnd = Math.floor(Math.random() * m-=1);
      // And swap it
      temp = arr[m];
      arr[m] = arr[rnd];
      arr[rnd] = temp;
   }

  return arr; 
}
Ghoul Fool
  • 6,249
  • 10
  • 67
  • 125
  • https://stackoverflow.com/questions/48962891/fastest-way-to-fill-an-array-with-multiple-value-in-js-can-i-pass-a-some-patter – epascarello Dec 21 '20 at 19:49
  • Does this answer your question? [Unique (non-repeating) random numbers in O(1)?](https://stackoverflow.com/questions/196017/unique-non-repeating-random-numbers-in-o1) – Peter O. Dec 22 '20 at 00:27

0 Answers0