Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Random odds in arrays

Okay, so let's say I store some of my data like this,

var thisList = {
    "items":[
        {"name":"Item1", "image":"/img/item1", "chance":0.25},
        {"name":"Item2", "image":"/img/item2", "chance":0.25},
        {"name":"Item3", "image":"/img/item3", "chance":0.50}
    ]           
}

Now I'd like to create a function that randomly picks a item out of this list with the chances being 25% of getting [0], another 25% of getting [1] and a 50% chance of getting [2]!

Is this possible? If so, how'd I do this?

Kind regards!

like image 821
Martijn Ebbens Avatar asked Oct 27 '25 05:10

Martijn Ebbens


1 Answers

You can actually play it like this, tou generate a number between 0 and 100 and then you cycle on each element and sum the chance to check if it is between the value or not:

var thisList = {
    "items":[
        {"name":"Item1", "image":"/img/item1", "chance":0.25},
        {"name":"Item2", "image":"/img/item2", "chance":0.25},
        {"name":"Item3", "image":"/img/item3", "chance":0.50}
    ]           
};

function getRandom(){
  var rnd = Math.floor(Math.random() * 100);
  console.log("The number is: " + rnd);
  var counter = 0;
  for(i=0;i<thisList.items.length;i++)
  {
    counter += thisList.items[i].chance * 100;
    if(counter > rnd){
      console.log(thisList.items[i]);
      break;
    }
  }
}

getRandom();

EDIT:

If you want to control even with a variant chance you can do this:

var thisList = {
    "items":[
        {"name":"Item1", "image":"/img/item1", "chance":0.25},
        {"name":"Item2", "image":"/img/item2", "chance":0.25},
        {"name":"Item3", "image":"/img/item3", "chance":0.50}
    ]           
};

function getRandom(){
  var sum = 0;
  for(i=0;i<thisList.items.length;i++)
  {
    sum += thisList.items[i].chance;
  }
  var rnd = Math.floor(Math.random() * (sum * 100));
  console.log("The number is: " + rnd);
  var counter = 0;
  for(i=0;i<thisList.items.length;i++)
  {
    counter += thisList.items[i].chance * 100;
    if(counter > rnd){
      console.log(thisList.items[i]);
      break;
    }
  }
}

getRandom();
like image 96
Dr. Roggia Avatar answered Oct 29 '25 18:10

Dr. Roggia