Entry
Where can I get ALGORITHMS that can randomize numbers (possible codes in: javascript, coldfusion) ?
Feb 8th, 2002 07:12
Jean-Bernard Valentaten, zor k,
What exactly do you want to do??
Basically js has a method that returns a random mumber between 0 and 1.
It is locatet in the Math-Object and thus called Math.random().
If you want to use it to create bigger (say integer) numbers, you might
want to use this code:
function dice(sides, rolls)
{
var diceArray = new Array();
for(i=0; i < rolls; i++)
{
diceArray[i] = parseInt(Math.random() * sides) + 1;
}
return diceArray;
}
This function emulates a dice with n sides and rolls that dice m times.
It returns an array containing the m rolls (thus having the length m).
The algorithm is quite easy. First it generates a random number between
0 and 1 (most randomizers do that), multiplies it by the sides the dice
is supposed to have, transforms it into an integer value (rouned down)
and finally adds one (so that all the numbers stay between 1 and
'sides'). It's an algorithm found in nearly every computergame.
I'm not quite sure how good js' random-seed is, so it might be that
random numbers get predictable by having a few thousand runs of this
function, so you'd better not use it to solve security-problems (e.g.
oneway encoding of passwords etc.).
If you want to create your own randomizer in js, you might need to get
the appropriate literature (you might want to look up www.google.com for
that).
HTH,
Jean