Hacker News new | ask | show | jobs
by homami 1627 days ago
Off topic, but this is a code smell for me: [(int) Math.round(Math.random() * (userAgents.length - 1))]); This leads to a lower probability of selecting the 0th and the last items in the array.
1 comments

It should be floor right? Math.floor(Math.random()*userAgents.length)
Yeah.

> The java.lang.Math.random() method returns a pseudorandom double type number greater than or equal to 0.0 and less than 1.0.

There's a built-in method for randomly selecting an int in a range. Use that.
Are you thinking of the Lodash random() function? Or Crypto.getRandomValues()?
floor is unnecessary. The cast does it for you. The problem is that a random double is not going to be evenly distributed into length equal parts unless length is a power of 2.