Search code examples
actionscript-3

Percentage Distribution of numbers in AS3


I need to generate 238 numbers, with a range of 1-4, but I want to weight them, so there's say 35% chance of getting 3, 28% chance of getting 2, 18% chance of getting 4m, and 19% chance of getting 1.

I found this..

def select( values ):
 variate = random.random() * sum( values.values() )
 cumulative = 0.0 
for item, weight in values.items():
     cumulative += weight
     if variate < cumulative:             return item
 return item # Shouldn't get here, but just in case of rounding...  print select( { "a": 70, "b": 20, "c": 10 } )

But I don't see how to convert that to AS3?


Solution

  • I would do something like this:

    var values:Array = [1,2,3,4];
    var weights:Array = [35, 28, 18, 19];
    
    var total:Number = 0;
    for(var i in weights) {
        total += weights[i];
    }
    
    var rndNum:Number = Math.floor(Math.random()*total);
    
    var counter:Number = 0;
    for(var j:Number = 0; j<weights.length; j++) {
        counter += weights[j];
        if( rndNum <= counter ) return values[j]; //This is the value
    }
    

    (untested code, but the idea should work)