Search code examples
javascriptalgorithmprobability

Drawing with propalibity


I have object in js like this:

    const Obj = [ {
     propability: 0.5, 
      name: 'Item with propability 0.5%'
     }, {
    propability: 1, 
    name: 'Item with propability 1%'
   }
];

Any one knowns how to create algorithm to this? Just simple code.

I want to return item by his propability.


Solution

  • If i understand right, you want something like this:

    const Obj = [ 
        {
            propability: 0.5, 
            name: 'Item with propability 0.5%'
        }, 
        {
            propability: 5, 
            name: 'Item with propability 5%'
        }, 
        {
            propability: 10, 
            name: 'Item with propability 10%'
        }, 
        {
            propability: 0.0001, 
            name: 'Item with propability 0.0001%'
        }
    ];
    
    // get total probability
    var total = 0;
    for(let j in Obj){
        total += Obj[j].propability;
    }
    
    //choose random obj
    console.log(pick_random());
    
    function pick_random(){
        var pick = Math.random()*total;
        for(let j in Obj){
            pick -= Obj[j].propability;
            if(pick <= 0){
                return Obj[j];
            }
        }
    }