If I have a very short string, say (JavaScript):
var = "abcd";
and开发者_如何转开发 I want to get a random character from it, I could use:
var random_char = str.charAt( Math.floor(Math.random() * str.length) );
Now Math.floor(Math.random() * str.length)
returns a random number in the range [0..3]
.
Can the perceived randomness of the returned character be increased by multiplying the string, i.e. by effectively increasing the range of the random numbers?
var = "abcdabcdabcdabcdabcdabcd";
That won't change anything. Math.random()
returns a pseudo-random value between in [0..1)
. Assuming the random number generator is of good quality, it won't make a difference whether you map its range to abc
or to abcabcabc
.
If Math.random()
returned random numbers of very low quality (i.e. a human being could spot the logic behind them just by looking at the number sequence), your strategy would indeed increase the perceived 'randomness'. But that's not relevant since JavaScript runtimes are typically not written by monkeys.
I would say no. It still is a 25% probability for getting a, b, c or d.
No, it cannot. Worse yet, you will get an error 12.5% of the time, as Math.round
will round values from 3.5 to 3.999999 up to 4.
精彩评论