...

View Full Version : Help with Unique Random Two...



nathan_lamothe
05-02-2006, 12:34 AM
Hey guys! Happy Monday:)

I need something similar to one of Kansel's functions here (http://www.codingforums.com/showthread.php?t=4614&highlight=unique+random)
that will randomize the order of the numbers from 1 to 15, so I messed with Kansel's functions a bit and got this:



<html>
<head>
<SCRIPT LANGUAGE="JavaScript" TYPE="text/javascript">
<!--
function pickUniqueArray(numPick,pool){
var size = pool.length;
var unique = new Array(numPick);
var choose, temp;
for(var i = 0; i < unique.length; i++){
choose = Math.floor(Math.random() * size);
unique[i] = pool[choose];
size--;
temp = pool[choose];
pool[choose] = pool[size];
pool[size] = temp;
}
return (unique)
}
//-->
</SCRIPT></head>
<body>
<script type="text/javascript">
var pick=15;
var pol=new Array();
for(i=1;i<16;i++){pol[i]=i;}
var numbersa=pickUniqueArray(pick,pol);
document.write(numbersa);
</script>

</body>
</html>


Can someone see why I loose one of my 15 numbers each time? It seems to be a different number in a different place each time I run it, and I am at a loss. But I'm sure it is something fairly simple that I screwed up...:o

kansel
05-02-2006, 01:29 AM
The problem is because you are starting your pol array at index 1-15 whereas the pickUniqueArray function is looking at a 0-based array. Since your pol array will never have an element in the 0 index you will always miss one number.

My advice is to make your pol array 0-based and add +1 to the value you assign in each index.
<html>
<head>
<SCRIPT LANGUAGE="JavaScript" TYPE="text/javascript">
<!--
function pickUniqueArray(numPick,pool){
var size = pool.length;
var unique = new Array(numPick);
var choose, temp;
for(var i = 0; i < unique.length; i++){
choose = Math.floor(Math.random() * size);
unique[i] = pool[choose];
size--;
temp = pool[choose];
pool[choose] = pool[size];
pool[size] = temp;
}
return (unique)
}
//-->
</SCRIPT></head>
<body>
<script type="text/javascript">
var pick=15;
var pol=new Array();
for(i=0;i<pick;i++){pol[i]=i+1;} // modified this line
var numbersa=pickUniqueArray(pick,pol);
document.write(numbersa);
</script>

</body>
</html>Changes are in red, additions are in blue.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum