Solved Stuck with percentage generator

Discussion in 'Plugin Development' started by jebbo, Sep 1, 2015.

Thread Status:
Not open for further replies.
  1. Offline

    jebbo

    So I'm currently stuck with this class I've found;

    Class (open)

    Code:
    package de.iraphi.tb.Utils;
    
    import java.util.ArrayList;
    import java.util.List;
    import java.util.Random;
    
    public class ResultGenerator<T> {
    
        class Possibility
        {
            Possibility(T choice, int chance)
            {
                this.Choice = choice;
                this.Chance = chance;
            }
    
            public T Choice;
            public int Chance;
            public int RangeMax;
            public int RangeMin;
    
        }
    
        private Random r;
    
        public ResultGenerator(Random r)
        {
            this.r = r;
        }
    
        public ResultGenerator()
        {
            this.r = new Random();
        }
    
        private List<Possibility> possibilities = new ArrayList<Possibility>();
    
        public void AddPossibility(T choice, int chance) {
            possibilities.add(new Possibility(choice, chance));
        }
    
        public T GetRandomResult() {
    
            if (possibilities.size() == 0)
                return null;
    
            //Calculate ranges for possibilities
            int totalChances = 0;
            for (Possibility p : possibilities) {
                p.RangeMin = totalChances;
                p.RangeMax = totalChances + p.Chance;
                totalChances += p.Chance;
            }
    
            int randomNumber = 1 + r.nextInt(totalChances + 1);
    
            for(Possibility possibility : possibilities)
            {
                if (randomNumber <= possibility.RangeMax && randomNumber > possibility.RangeMin)
                {
                    return possibility.Choice;
                }
            }
    
            return null;
        }
    
    }


    I'm adding possibilities like this:
    Code:
    ResultGenerator<Integer> rb = new ResultGenerator<Integer>();
            int cnt = 1;
            for(Box box : boxList){
                rb.AddPossibility(cnt, box.getChance());
                cnt++;
            }
    And getting a random one with:
    rb.GetRandomResult();

    But the problem is it always returns null, no matter what.

    Somebody has an Idea what might be the problem?
    Thanks..
     
  2. boxList is empty. Look at line 44-45 in the random generator
     
  3. Offline

    jebbo

    Yea got it fixed, had a spelling error a few lines up when getting a value from the config..

    Today is not my day haha.

    Thanks
     
Thread Status:
Not open for further replies.

Share This Page