-1

So I'm writing a program where the program generates 100 random integers between 0 and 9 and stores them in an Array[ with using Linear Search to count the time each value is matched in the Array[]. Values will need to appear multiple times so Linear Search needs to traverse all the elements in the Array[]

What I have got so far is this

public static void main(String[] args) {
    int[] randomNumbers = new int[100];

    for(int index = 0; index < randomNumbers.length; index++)
    {
        randomNumbers[index] = (int) (Math.random()*100);
    }

    for(int index = 0; index < randomNumbers.length; index++)
    {
        System.out.println(randomNumbers[index]);
    }

}

}

Andrew Jones
  • 13
  • 1
  • 6
  • 1
    Well I'd start by writing the code to generate the array - and I'd personally suggest using `java.util.Random.nextInt()` rather than `Math.random()`... Once you've got the array, you can start thinking about how to count entries. (Hint: It's really helpful that you've got a small and known range of numbers. You may well want a second array...) – Jon Skeet Apr 16 '15 at 07:47
  • could you explain with more details? – Andrew Jones Apr 16 '15 at 17:52
  • @AndrewJones the values of the array, which go from 0 to 9, could constitute the indices of a second array of length 10, where each of the values of the second array would contain the frequency associated to its index: secondArray[3] would contain the number of times 3 is contained in firstArray. – JB Nizet Apr 16 '15 at 17:55

1 Answers1

0

Perhaps not what you're looking for but an easy way to count multiple instances of objects using HashMap, here is an example with your random code generator:

public static void main(String[] args) {

    int[] randomNumbers = new int[100];
    HashMap<Integer, Integer> map = new HashMap<>();

    //Generate 100 random ints
    for (int index = 0; index < randomNumbers.length; index++) {
        randomNumbers[index] = (int) (Math.random() * 100);
    }

    //Count occurrences of numbers in randomNumbers
    for (int index = 0; index < randomNumbers.length; index++) {

        //Get value of key 'randomNumbers[index]
        Integer count = map.get(randomNumbers[index]);

        //If key didn't exist create it, else increment the value of occurrences.
        if (count == null) {
            map.put(randomNumbers[index], 1);
        } else {
            map.replace(randomNumbers[index], count + 1);
        }
    }

    //Print mappings
    System.out.println(map.toString());
}
Gready
  • 1,134
  • 8
  • 15