Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 4 of 4
  1. #1
    JPM
    JPM is offline
    Regular Coder
    Join Date
    Mar 2004
    Location
    Norway
    Posts
    204
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Frustrated! Weighted Random number script..

    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.

    Code:
    <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]
    
    currValue++
    }
      
    var randomnumber=Math.floor(Math.random()* totalWeight)
    document.write("<br>" + resArray[randomnumber])
    
    </script>
    Thanks!
    Last edited by JPM; 05-03-2004 at 11:42 PM.
    <JPM />

  • #2
    Regular Coder
    Join Date
    Jul 2002
    Location
    Kansas, USA
    Posts
    487
    Thanks
    0
    Thanked 54 Times in 53 Posts
    This might shed some light:
    Code:
    resArray[resArray.lenght] = values[currValue]

  • #3
    Regular Coder
    Join Date
    Jul 2002
    Location
    Kansas, USA
    Posts
    487
    Thanks
    0
    Thanked 54 Times in 53 Posts
    When I changed this from lenght to length I got output: "TEST"

  • #4
    Regular Coder
    Join Date
    Nov 2002
    Location
    Carmel California
    Posts
    471
    Thanks
    0
    Thanked 1 Time in 1 Post
    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.
    Last edited by kwhubby; 05-04-2004 at 07:26 AM.
    Kris Hubby
    kwhubby site


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •