PDA

View Full Version : I need help with a weighted random number generator


SirLoin
06-17-2005, 04:20 PM
Below is a script I am using for a weighted random number generator. I am very new to java scripting and need help with the finishng touches for this.

As it is now it works fine. I would now like generate 5 seperate numbers (from the bank of weighted numbers in the first portion) in the first row with no repeats.

How can I accomplish this? Please help or point me in the right direction.

Thanks
SirLoin

<html>
<head><title>Weighted Number Generator</title></head>
<body>
Weighted Number Generator
<script language="JavaScript">
<!--
var numbers=["1", "3", "4", "10", "12", "25", "34", "44"]
var numweight=[27, 26, 25, 44, 25, 28, 26, 33] //weight of each element above
var totalweight=eval(numweight.join("+")) //get total weight (234)
var weighednumbers=new Array() //new array to hold "weighted" numbers
var currentnum=0

while (currentnum<numbers.length){ //step through each num[] element
for (i=0; i<numweight[currentnum]; i++)
weighednumbers[weighednumbers.length]=numbers[currentnum]
currentnum++
}
var randomnumber=Math.floor(Math.random()*totalweight)
document.write("<br>"+weighednumbers[randomnumber])

var numbers=["1", "3", "4", "10", "12", "25", "34", "44"]
var numweight=[8, 12, 7, 10, 5, 3, 13, 4] //weight of each element above
var totalweight=eval(numweight.join("+")) //get total weight (62)
var weighednumbers=new Array() //new array to hold "weighted" numbers
var currentnum=0

while (currentnum<numbers.length){ //step through each num[] element
for (i=0; i<numweight[currentnum]; i++)
weighednumbers[weighednumbers.length]=numbers[currentnum]
currentnum++
}
var randomnumber=Math.floor(Math.random()*totalweight)
document.write("<br>"+weighednumbers[randomnumber])
//-->
</script>
</body>
</html>

brandonH
06-17-2005, 04:32 PM
research the different ways to modify arrays. I know there is a way to remove an item from an array after it has been picked. (cant remember exactly how to do it though). this will keep the same number from being drawn twice.

what you should do is when generating the 5 random #'s, create a new array that copies the original, that way you dont actually remove data from your array. have the script run through your copy array and remove a value.