Algorithm steps are:
1 - sum chances
2 - store multiple time an item according to chance
3 - generate a number up to sum_Chances and return the index (which is the object)
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Percent
{
List<Item> l;
Map<Integer,Item> m;
public static void main(String[] args)
{
Percent p = new Percent();
for(int i=0;i<=9;i++)
{
System.out.println(i+"_itemNo="+p.getItem().name);
}
}
Percent()
{
l = new ArrayList();
l.add(new Item("i1",1));
l.add(new Item("i2",2));
l.add(new Item("i3",3));
}
public Item getItem()
{
m = new HashMap();
int total=0;
int k=0;
for(int i=0;i<l.size();i++)
{
total += l.get(i).chance;
for(int j=0;j<l.get(i).chance;j++)
{
m.put(k,l.get(i));
k++;
}
}
int r = (int)(Math.random()*total);
//System.out.println(r);
return m.get(r);
}
class Item
{
Item(){};
Item(String name, int chance)
{
this.name = name;
this.chance = chance;
}
public int chance;
public String name;
}
}
Output:
0_itemNo=i3
1_itemNo=i3
2_itemNo=i3
3_itemNo=i3
4_itemNo=i1
5_itemNo=i2
6_itemNo=i1
7_itemNo=i2
8_itemNo=i2
9_itemNo=i3
It's easy to see even with 10-events that item_3 have maximum occurrences