codinglearn
codinglearn

Reputation: 13

How to count number of occurrences in a random array?

I have some homework where. I have to write a simple program where 1000000 randoms between 1-100 are generated and stored in an array. After the program has to print out the number of occurrences of 25, 50 and 100. I've been trying for loops but no luck. Till now I have this:

package randomnumbers;

import java.util.Random;

public class random {
    public static void main(String[] args) {
        Random r = new Random();
        int number[] = new int[1000000];

        for (int count = 0; count < number.length; count++) {
            number[count] = 1 + r.nextInt(100);
        }
    }
}

Upvotes: 0

Views: 944

Answers (2)

user14838237
user14838237

Reputation:

You can use IntStream.count() method for this purpose. Your code might look something like this:

public static void main(String[] args) {
    // generate array of 1,000,000 elements
    int[] arr = IntStream.range(0, 1000000)
            // random value from 1 to 100
            .map(i -> (int) (1 + Math.random() * 100))
            .toArray();

    // test output
    System.out.println(countOf(arr, 0));   // 0
    System.out.println(countOf(arr, 1));   // 10137
    System.out.println(countOf(arr, 25));  // 10026
    System.out.println(countOf(arr, 50));  // 10103
    System.out.println(countOf(arr, 100)); // 10100
    System.out.println(countOf(null,100)); // 0
    System.out.println(countOf(arr, 101)); // 0
}
private static long countOf(int[] arr, int value) {
    if (arr == null)
        return 0;
    else
        return Arrays.stream(arr).filter(i -> i == value).count();
}

See also:
How to find duplicate elements in array in effective way?
How to get elements of an array that is not null?

Upvotes: 0

Sruthi
Sruthi

Reputation: 119

public static void main(String[] args) {
    Random r = new Random();
    int low = 1;
    int high = 101;
    int number[] = new int[1000000];
    int count25 = 0;
    int count50 = 0;
    int count100 = 0;

    for (int i = 0; i < number.length; i++) {
        int num = r.nextInt(high - low) + low;
        if (num == 25) {
            count25++;
        } else if (num == 50) {
            count50++;
        } else if (num == 100) {
            count100++;
        }
        number[i] = num;
    }
    System.out.println(count25);
    System.out.println(count50);
    System.out.println(count100);
}

Here r.nextInt(high - low) + low generates random value between lower bound(inclusive) and upper bound(exclusive). Hence I have used upper bound as 101.

There are 3 different counters which would increment by one if its value matches the required value(25, 50 and 100). After the loop is completed the value of the counter can be printed.

Upvotes: 1

Related Questions