Alk
Alk

Reputation: 5557

Random number generator problems

My question is does the code below generate a random number properly as in the last 20 tries I got 500 000 5 times which does not reflect the 2% chance of getting it at all...

  public static int randInt(int min, int max) {

        // NOTE: Usually this should be a field rather than a method
        // variable so that it is not re-seeded every call.
        Random rand = new Random();

        // nextInt is normally exclusive of the top value,
        // so add 1 to make it inclusive
        int randomNum = rand.nextInt((max - min) + 1) + min;

        return randomNum;
    }

    public void prizegenerator(View v) {
        int fate = randInt(0,100);
        int reward=0;
        if (fate <= 30) {
            reward = 1000;
        }
        else if (fate <= 50) {
            reward = 2000;
        }
        else if (fate <= 80) {
            reward = 5000;
        }
        else if (fate <=90) {
            reward =  10000;
        }
        else if (fate <= 95) {
            reward = 50000;
        }
        else if (fate <= 97) {
            reward = 100000;
        }
        else if (fate <= 99) {
            reward = 500000;
        }
        else if (fate <= 100) {
            reward = 1000000;
        }

Upvotes: 0

Views: 90

Answers (1)

mefi
mefi

Reputation: 1263

I tied your code inside simple main method and works ok. Try it yourself:

public static void main(String[] args) {
    Main main = new Main();
    List<Integer> list = new ArrayList<Integer>();
    for (int i = 0; i < 100; i++) {
        list.add(main.prizegenerator());
    }
    Collections.sort(list);

    for (Integer integer : list) {
        System.out.println(integer);
    }
}

When I run it multiple times, it generates mostly 2 times 500000, which match your 2% chance (for 98 and 99)

Upvotes: 2

Related Questions