PDA

View Full Version : Random numbers


allyson
11-06-2002, 08:25 AM
Hi

I'm wanting to generate 4 random numbers from 0 to 30, but I want each of the 4 numbers to be different. I've started writing the code, but am stuck and need some assistance. Each number that is generated is stored in the number array. But I'm not sure on how to design the loop, to go through the sequence 4 times and how to compare the 4 numbers, so they are all different. Can anyone help me please?

number=new array()

today2=new Date()
len=30
today=today2.getTime()/10
rnd=today % len
number[1]=rnd



bye
Allyson

glenngv
11-06-2002, 09:08 AM
try:


var arr = new Array();
var ctr = 0;
do{
rd = Math.floor(Math.random()*30);
if (checkUnique(rd)==-1){
arr[ctr]=rd;
ctr++;
}

}
while (ctr<4)

function checkUnique(num){
for (var i = 0;i<arr.length;i++){
if (arr[i]==num) return i;
}
return -1;
}

jalarie
11-06-2002, 12:58 PM
Or you might like this:

&nbsp;Max=prompt('Maximum',30);
&nbsp;Items=prompt('Select',4);
&nbsp;Data=new&nbsp;Array();
&nbsp;for&nbsp;(ix1=0;&nbsp;ix1<Max;&nbsp;ix1++)&nbsp;{&nbsp;&nbsp;&nbsp;//&nbsp;create&nbsp;array
&nbsp;&nbsp;&nbsp;Data[ix1]=ix1;
&nbsp;}
&nbsp;for&nbsp;(ix1=0;&nbsp;ix1<Max;&nbsp;ix1++)&nbsp;{&nbsp;&nbsp;&nbsp;//&nbsp;randomize
&nbsp;&nbsp;&nbsp;ix0=Math.floor(Math.random()*(Max-1)+1);
&nbsp;&nbsp;&nbsp;Hold=Data[ix0];
&nbsp;&nbsp;&nbsp;Data[ix0]=Data[ix1];
&nbsp;&nbsp;&nbsp;Data[ix1]=Hold;
&nbsp;}
&nbsp;Result='';
&nbsp;for&nbsp;(ix1=0;&nbsp;ix1<Items;&nbsp;ix1++)&nbsp;{
&nbsp;&nbsp;&nbsp;if&nbsp;(Result&nbsp;==&nbsp;'')&nbsp;{&nbsp;Result=Data[ix1];&nbsp;}
&nbsp;&nbsp;&nbsp;else&nbsp;{&nbsp;Result+=','+Data[ix1];&nbsp;}
&nbsp;}
&nbsp;alert(Result);