Search code examples
javalistrandomprobability

How to pick an item by its probability?


I have a list of items. Each of these items has its own probability.

Can anyone suggest an algorithm to pick an item based on its probability?


Solution

  • So with each item store a number that marks its relative probability, for example if you have 3 items one should be twice as likely to be selected as either of the other two then your list will have:

     [{A,1},{B,1},{C,2}]
    

    Then sum the numbers of the list (i.e. 4 in our case). Now generate a random number and choose that index. int index = rand.nextInt(4); return the number such that the index is in the correct range.

    Java code:

    class Item {
        int relativeProb;
        String name;
    
        //Getters Setters and Constructor
    }
    
    ...
    
    class RandomSelector {
        List<Item> items = new List();
        Random rand = new Random();
        int totalSum = 0;
    
        RandomSelector() {
            for(Item item : items) {
                totalSum = totalSum + item.relativeProb;
            }
        }
    
        public Item getRandom() {
    
            int index = rand.nextInt(totalSum);
            int sum = 0;
            int i=0;
            while(sum < index ) {
                 sum = sum + items.get(i++).relativeProb;
            }
            return items.get(Math.max(0,i-1));
        }
    }