2

I want to generate a random order for the integers between 0 and 256^3 (to obtain randomly all the colors), so I'm using this way for now:

var c = [],
    j = 0;

//enum
for (;j<16777216;j++)   c[j] = j;

//calculate random elements faster
for(;c.length;c.splice(j,1)) {
    j = Math.floor(Math.random() * c.length);
    //every j is a random number between 0 and 256^3
}

It takes a long time to generate all the numbers...Do you know a way with better time performance to solve this?

fcortes
  • 1,338
  • 3
  • 11
  • 26
  • You want lazy evaluation. In ES6 (if you're using Node in this case) you can use `yield` to write it in a short nice syntax.Since it doesn't really work in browsers yet, you can use a closure to simulate state. Definitely don't evaluate all numbers in advance. – Benjamin Gruenbaum Mar 23 '14 at 13:43
  • Maybe this can help: http://stackoverflow.com/q/2450954/1169798 – Sirko Mar 23 '14 at 13:48

1 Answers1

1

There are several problems with the code you're using now.

  1. It's not reordering the values in the array, it's generating random values based on the changing size of the array. This does not guarantee that there won't be duplicate values in the generated sequence. (In fact, you definitely will have duplicates for all but the smallest array sizes.)

  2. It's not random. As the size of the array shrinks, so will the values generated at the end of the sequence. (After the 0th iteration, you can't generate the value 16777216 any more. A new value is eliminated on every iteration.)

  3. As you already noted, it's slow. You're spending a lot of time returning new array values from the splice function, which you just throw away on each iteration. You'd be better off to just shuffle the values in-place in the array c using the method given in How to randomize (shuffle) a javascript array?

Community
  • 1
  • 1
Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880