saksham goyal saksham goyal - 5 months ago 55
Java Question

How to find the frequency of an array in java

the questions is as follows:

Fill an array with 100 random numbers between 1 and 100. Display the array contents. Count the frequency of each number and display the count. Here is an example of 10 numbers from 1 to 10

Index: [0] [1] [2] [3] [4] [5] [6] [7] [8] [9]

Data: [5] [4] [9] [6] [5] [7] [7] [4] [4] [2]

Frequency - 1:0, 2:1, 3:0, 4:3, 5:2, 6:1, 7:2, 8:0, 9:1, 10:0


so the number 1 occurs 0 times, 2 occurs twice, 3 does not occur etc....

Answer

If it's numbers 1-100, we can use an array to store the frequency of numbers like so:

Random random = new Random();

int[] nums = new int[100];

// populate array with random numbers:

for(int i = 0; i < nums.length; i++) 

    nums[i] = 1+random.nextInt(100);

int[] freq = new int[100];

// set all elements in array to 0:

for(int i = 0; i < freq.length; i++)

    freq[i] = 0;

// count numbers:

for(int n : nums)

    freq[n-1]++; // n-1 because arrays start at 0

System.out.println("Number:\tFrequency:");

// print frequency of all numbers:

for(int i = 0; i < freq.length; i++)

    System.out.println((i+1) + "\t" + freq[i]); // again, i+1 because arrays start at 0

So the numbers generated will be used to index the freq array.

Hope this helps.

Comments