Home > Software design >  How can I make the script that which number occurred most often and how many times do each of the 10
How can I make the script that which number occurred most often and how many times do each of the 10

Time:11-28

I created a script that randomizes numbers from 1 to 10 based on the number you entered. And also I've made the script that how many odd and even numbers had come out, but I don't know how to make a script that shows how many times do each of the 10 random numbers occur and which number occurred most often.

Here is the script that I have made:

import java.util.*;

public class GreatCoinFlipping {
    
    public static void main(String[] args) {
        System.out.println("How many times do you want to flip the coin? : ");

        Scanner sc = new Scanner(System.in);
        int amount = sc.nextInt();

        int[] arrNum = new int[amount];
        int even = 0, odd = 0;
        for (int i = 0; i < amount ; i  ) {
            arrNum[i] = (int)(Math.random() * 10   1);
            System.out.println(arrNum[i]);
            if (arrNum[i] % 2 == 0) even  ;
            else                    odd  ;
        }//end for
        System.out.println("Head: "   even   ", Tail: "   odd);
    }//end main
    
}//end class

What I am expecting on this script that that I want to make the script that shows how many times do each of the 10 random numbers occur and which number occurred most often. And I want to make it by the count method. Can someone please help me with this problem?

CodePudding user response:

The arrNum variable will contain an array of all occurences of each number. So if you want to count, for example, how many times 4 occurred in this, you can do this:

Arrays.stream(arrNum).filter(n -> n == 4).count()

For 7 you can do this:

Arrays.stream(arrNum).filter(n -> n == 7).count()

And you can do the same for other digits (1 to 10).

This would be a simple/straight-forward way of doing it. You can also improve it by creating a method that returns this count:

public static int getCount(int[] arr, int num) {
    return Arrays.stream(arr).filter(n -> n == num).count();
}

And then call this in a loop:

for(int i=1; i<=10; i  ) {
    System.out.println("Count for "   i   ": "   getCount(arrNum, i));
}

CodePudding user response:

To keep track of the random number you generate you can use a array. The array starts out as all 0's and is of size 10 (because there are 10 numbers between 0-9).

int size = 10;
int numbers_counter[] = new int[size];

// initialize the values
for(int i = 0; i < size; i  ){
    numbers_counter[i] = 0;
}

// count some random numbers
for(int i = 0; i < 100; i  ){
    numbers_counter[(int)(Math.random() * size)]  = 1;
}

// print how many times each number accured
for(int i = 0; i < size; i  ){
    System.out.println(""   i   " occured: "   numbers_counter[i]   " times");
}

You can apply this method to your code.

  • Related