DEV Community

Discussion on: A new(?) non-repeating Random Number Generator

Collapse
 
burki profile image
Burkhard Graves

@lukeshiru Two more comments:

  1. Small fix in your second snippet (the one with the generator)

Math.floor(Math.random() * (iterableArray.length - 1)) is wrong,
Math.floor(Math.random() * iterableArray.length) would be ok.

  1. Very poor randomness in the first snippet

Your method of shuffling looked a bit suspicious to me, so I wrote a little test:

const randomNumbers = (min) => (max) => {
  const array = [...Array(max + 1 - min)].map((_, index) => index + min);

  return () => array.sort(() => Math.round(-Math.random())); // looks suspicious
};

// map with all possible results and a counter
const map = new Map();
map.set("123", 0);
map.set("132", 0);
map.set("213", 0);
map.set("231", 0);
map.set("312", 0);
map.set("321", 0);

for (let i = 600000; --i >= 0; ) {
  const a = randomNumbers(1)(3)();
  const key = a.join("");
  map.set(key, map.get(key) + 1); // increment the counter
}

// list number of occurrences of each possible result
// each result should appear around 100.000 times...
map.forEach((value, key) => console.info(key + " -> " + value));
Enter fullscreen mode Exit fullscreen mode

If you run this a few times you will see that the combination 123 occurs most frequently by a large margin, followed by 321. The remaining combinations are underrepresented, with 213 still appearing the most, e.g.:

123 -> 224783
132 -> 37147
213 -> 74877
231 -> 37517
312 -> 37532
321 -> 188144
Enter fullscreen mode Exit fullscreen mode

Something similar is discussed here: blog.codinghorror.com/the-danger-o... - that's a very good read!

Cheers!