Search code examples
javaarraysrandomnumberscounting

20 random numbers array from 0 to 10. How to count specific numbers in it?


I made this array but im struggling with counting the numbers. I could do it by using "IF" 10 times but it just seems wrong to me. Perhaps loop "for" would be the best to use here but i have no idea how to approach this.

import java.util.Random;


public class zadanie2 {
    public static void main(String[] args) {
        int array[];
        array = new int[20];


        for (int i = 0; i < array.length; i++) {
            Random rd = new Random();
            array[i] = rd.nextInt(10);
            System.out.print(array[i] + ",");
        }
    }
}

Solution

  • Here is quick fix for you. Check following code.

        int inputArray[];
        inputArray = new int[20];
        Random rd = new Random();
        HashMap<Integer, Integer> elementCountMap = new HashMap<Integer, Integer>();
        for (int i = 0; i < inputArray.length; i++) {
            inputArray[i] = rd.nextInt(10);
        }
        for (int i : inputArray) {
            if (elementCountMap.containsKey(i)) {
                elementCountMap.put(i, elementCountMap.get(i) + 1);
            } else {
                elementCountMap.put(i, 1);
            }
        }
        System.out.println();
        System.out.println("Input Array : " + Arrays.toString(inputArray));
        System.out.println("Element Count : " + elementCountMap);
    
    

    Output :

    Input Array : [9, 7, 3, 0, 8, 6, 3, 3, 7, 9, 1, 2, 9, 7, 2, 6, 5, 7, 1, 5]

    Element Count : {0=1, 1=2, 2=2, 3=3, 5=2, 6=2, 7=4, 8=1, 9=3}

    Hope this solution works.