user3697365
user3697365

Reputation: 61

Random generator Error

I want to write a program that is randomizing 1000000 times and finally chooses the number from 1 - 45 that was randomly generated most of the times. The code I have written is this:

public class Randomizer {
    public static int[][] numbers = new int[45][2];
    public static int maxN = 0;
    public static int finalChoice;
    public static void main(String[] args){

        for(int i = 0; i < 45; i++){
            numbers[i][0] = i + 1;
            numbers[i][1] = 0;          
        }

        for(int i = 0; i < 1000000; i ++){
            int rnd = (int)(Math.random() * 45 + 1);
            for(int j = 0; j < 45; j++){
                if(rnd == numbers [j] [0]){
                    numbers[j][1] ++ ;
                    break;
                }
            }
        }
        for(int i = 0; i < 45; i++){
            if(maxN < numbers[i][1]){
                finalChoice = numbers[i][0];
            }
            System.out.print(numbers[i][1]+" \t");
        }

        System.out.println("\nFinal Choice: "+finalChoice);

    }



}

The problem is that it keeps printing 45. Where could the error be?

Upvotes: 1

Views: 66

Answers (2)

Drim
Drim

Reputation: 524

Try this:

Random r = new Random();
for (int i = 0; i <= 1000000; i++) {
    int Low = 1;
    int High = 45;
    int R = r.nextInt(High - Low) + Low;
}

Upvotes: 0

Eran
Eran

Reputation: 394156

Your loop that generates the numbers and populates the array looks fine. The only problem is in the final loop, which searches for the highest occurring number.

You forgot to update maxN, so each iteration updates finalChoice (since maxN < numbers[i][1] is always true, assuming that each number from 1 to 45 was randomly chosen at least once) and it ends up being 45.

Fix :

    for(int i = 0; i < 45; i++){
        if(maxN < numbers[i][1]){
            finalChoice = numbers[i][0];
            maxN = numbers[i][1]; // add this
        }
        System.out.print(numbers[i][1]+" \t");
    }

Upvotes: 1

Related Questions