0

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.

Amaresh S M
  • 2,936
  • 2
  • 13
  • 25
sarakosek
  • 3
  • 3

1 Answers1

1

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];
        }
    }
}
François Huppé
  • 2,006
  • 1
  • 6
  • 15