dimanche 22 mai 2016

Grabbox with rarities. (Random value picker)

Hey guys I am trying to write up some code to pick a random item out of a box. Those items have rarities linked to them, for example 0.1 which should have a chance of 1/1000 ( 1 / (100/rarity) ) but for some reason it doesn't seem to work properly. This is what I tried:

        ArrayList<BoxItem> allItems = new ArrayList<>();
    int counter = 0;
    while(counter < 10000){
        ArrayList<BoxItem> possibleRewards = new ArrayList<>();
    double randomNumber = Math.random()*100;
    while(possibleRewards.isEmpty()){
        for(BoxItem item: contents){
            randomNumber = Math.random()*100;
            if(randomNumber < item.getRarity())
                possibleRewards.add(item);
        }
    }

    BoxItem boxItem = possibleRewards.get(possibleRewards.size()-1);
    allItems.add(boxItem);
    counter++;
    }
    System.out.println("Opened 10000, results:");
    int counter1 = 0;
    for(BoxItem item: contents){
        System.out.println("Item "+counter1+" received: [" + Collections.frequency(allItems, item)+"], rarity: [1/"+(100/item.getRarity()+"]"));
        counter1++;
    }

This is a simulation of 10000 boxes:

Item 0 received: [344], rarity: [1/100.0]

Item 1 received: [332], rarity: [1/100.0]

Item 2 received: [873], rarity: [1/40.0]

Item 3 received: [343], rarity: [1/100.0]

Item 4 received: [1102], rarity: [1/33.333333333333336]

Item 5 received: [380], rarity: [1/100.0]

Item 6 received: [390], rarity: [1/100.0]

Item 7 received: [366], rarity: [1/100.0]

Item 8 received: [4062], rarity: [1/10.0]

Item 9 received: [433], rarity: [1/100.0]

Item 10 received: [1336], rarity: [1/33.333333333333336]

Item 11 received: [39], rarity: [1/1000.0]

You see it's weird that an item with a rarity of 1/1000 comes 39 times when opening 10000 boxes. It should only be drawn around 8-12 times. Could anyone help me fix this? I spent a long time on this but can't seem to figure it out.

Boxitem example:

            contents.add(new BoxItem(1, 0.1));

0.1 would mean 1/1000




Aucun commentaire:

Enregistrer un commentaire