View Full Version : Frustrated! Weighted Random number script..

05-03-2004, 10:16 PM
I hava this random number script where you can weight values. I have no idea why it doesnt work, but Im sure Im just not seeing something here...
Well, here is the script; hope someone can help me here.

<script language="javascript">

var values =["TEST", "TEST2", "TEST3", "TEST4"]

var valueWeight = [7,1,1,1]

var totalWeight = eval(valueWeight.join("+"))

var resArray = new Array()

var currValue = 0


while (currValue < values.length) {

for(i=0 ; i<valueWeight[currValue]; i++)

resArray[resArray.lenght] = values[currValue]


var randomnumber=Math.floor(Math.random()* totalWeight)
document.write("<br>" + resArray[randomnumber])



05-03-2004, 10:54 PM
This might shed some light:

resArray[resArray.lenght] = values[currValue]

05-03-2004, 10:55 PM
When I changed this from lenght to length I got output: "TEST"

05-04-2004, 06:23 AM
you have to change the line:
var values =["TEST", "TEST2", "TEST3", "TEST4"]
to the values you want. You were getting test because test was one of the values. This is made this way so you can do string ouputs and not just number outputs. one example would be to change the line to:
var values =["orange", "apple", "grape", "mango", "pinapple", "guava", "lime"]
of course you could make those numbers, but if you wanted this to really return numbers, there is a much better way you could change the script.