-1

I am trying to count the occurrences of integers in an array. I was able to get it to work by piecing together some code I found online but I don't really understand why its working. What I have is:

int[] hand = {2, 4, 3, 2, 4};
int[] numOccurence = new int[hand.length];


    for (int i = 0; i < hand.length; i++)
        numOccurence[hand[i]]++;

    for (int i = 1; i < numOccurence.length; i++)
        if (numOccurence[i] > 0)
            System.out.println("The number " + i + " occurs " + numOccurence[i] + " times.");

The output is: The number 2 occurs 2 times. The number 3 occurs 1 times. The number 4 occurs 2 times.

How is this code counting the number of occurrences properly? I don't see how its accomplishing this. Thank you in advance!

user2771729
  • 448
  • 1
  • 7
  • 13

7 Answers7

3

This is only working because you've a good luck. Try making the second element in the hand array as 5 and see what happens. Its because the number present at the current index of hand is taken as the index of array numOccurence. In case of a number greater than or equal to the length of the numOccurence, you'll get the ArrayIndexOutOfBoundsException.

Thereforce, you can better use a Map for this where the key would be the number and the value could be its count.

Something like this:-

Map<Integer, Integer> numOccurence = new HashMap<Integer, Integer>();
for (int i = 0; i < hand.length; i++) {
    int cnt = 1;
    if (numOccurence.containsKey(hand[i])) {
        cnt = numOccurence.get(hand[i]);
        cnt++;
    }
    numOccurence.put(hand[i], cnt);
}
Rahul
  • 44,383
  • 11
  • 84
  • 103
3

This code does not really work. At least it does for the author's use case but probably not for yours.

Try with {2, 4, 99, 2, 4}; as hand and it will fail.

The author takes the number found in hand as the index of array numOccurence. numOccurence has the following structure : {nb occ of 0; nb occs of 1;...; nb occs of 4}. Here 99 will be out of bounds.

Arnaud Denoyelle
  • 29,980
  • 16
  • 92
  • 148
1

When you create an array

int[] numOccurence = new int[hand.length];

it is populated by their default values. For primitive int this value is 0.

This will of course only work if hand contains numbers less than or equal to max index (length -1) of the array otherwise it's ArrayIndexOutOfBound for you mister!

Thihara
  • 7,031
  • 2
  • 29
  • 56
0

Actually it's the same method for creating histogram for picture ;)

You create a table where you will gather the occurrence. numOccurence[0] will stock the number of 0 numOccurence[1] will stock the number of 1 etc.

That's what is done by this

for (int i = 0; i < hand.length; i++)
    numOccurence[hand[i]]++;

it adds 1 to the value in the case corresponding to the number hand[i]

so if you look at this step by step first he will take hand[0] = 2 so he will put

numOccurence[2] = numOccurence[2] + 1 ;

which is same (but faster to write) as

numOccurence[2]++; 
Clad Clad
  • 2,653
  • 1
  • 20
  • 32
0

This kind of performing a count is called counting sort.

The advantage of counting sort is it's speed. The disadvantage is the memory requirements when sorting big numbers.

There is a bug in the code:

int[] numOccurence = new int[hand.length];

numOccurence needs to be as long as the highest number in the list (not the number of numbers in the list). Try changing one of the numbers to 15 and you will get an exception.

Klas Lindbäck
  • 33,105
  • 5
  • 57
  • 82
0

First of all the code is wrong. You should set the size of numOccurence array to the max number value from hand array + 1. For example:

int[] hand = {2, 100};
int[] numOccurence[] = new int[101];

(you should obviously find max number programatically)

Now let's take a look at the algorithm. It takes each number from hand array, treats it as a numOccurence index value and increments number at that index by 1 in hand array. Note that all elements of numOccurence array are 0 by default at the beginning.

int[] hand = {2, 4, 3, 2, 4};
int[] numOccurence = new int[5];

Steps:

i = 0 (nothing happens, because there is no 0 in hand array)

i = 1 (same situation as for 0)

i = 2 (there are two 2 numbers in hand array, so we do operation numOccurence[2] += 1 twice, which in result gives 0 + 1 + 1 = 2. So we got numOccurence[2] = 2)

it continues for all numbers from 0 to max number from hand array (here: 100).

Celebes
  • 1,371
  • 1
  • 12
  • 21
0

The code iterates through the given array hand. it takes each value encountered as an index into the array numOccurrence. for each number n in hand, this will happen exactly as often as n occurs in hand, and each time this happens, the nth element of numOccurrence will be incremented.

thus numOccurrence is effectively an array of counters (assuming that the array elements are initialized with 0).

drawbacks of this approach:

  • the number of counters allocated depends on the magnitude of numbers in your handarray.
  • if the numbers in your hand array are distributed sparsely, most of the allocated space is never used.

alternative

you could improve the code by sorting hands first. in the sorted array the indexes of all occurrences of a given number are contiguous, so you scan the sorted array once needing a single counter only to compile the frequencies.

collapsar
  • 17,010
  • 4
  • 35
  • 61