...

View Full Version : array



ebco
12-27-2002, 07:36 AM
I want the array of 10 random no. withought duplication of no. from 1 to 20. It might be very difficult to understand what I want to say. But it will get u understand once u will go through the below code.
Here I am pasting my code but it's not working fine it giving me array of 10 with diffrent nos. but with undifined ........

Can anybody give me solution for this

<html>
<head>
<title></title>
<script language="javascript">
numpics = 20;
var i=0;
var j=0;
var rndnum = new Array(10);
for (i=0; i<rndnum.length; i++)
{
arraynum = Math.round(Math.random()*numpics);

for (j=0; j<rndnum.length; j++)
{
if(rndnum[j] == arraynum)
{
break;
}
}
if(j==rndnum.length)
{
rndnum[i] = arraynum;
}
}

</script>
</head>

<body>
<script language="javascript">
for (i=0; i<rndnum.length; i++)
{
document.write(rndnum[i] + ", ");
}
</script>

</body>
</html>

Algorithm
12-27-2002, 09:00 AM
The reason you're getting undefined values is because you're incrementing your loop regardless of whether you get a value for that pass. Change your loop to this:
for (i=0; i<rndnum.length && i<=numpics; i++) {
arraynum = Math.round(Math.random()*numpics);

for (j=0; j<i; j++) {
if(rndnum[j] == arraynum) {
break;
}
}
if(j==i) {
rndnum[i] = arraynum;
} else {
i--;
}
}

ebco
12-27-2002, 11:28 AM
:) Thanks



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum