Originally Posted by
laserlight
Suppose you had input like this:
1 1 1 2 2 3 3 4 4 4 5
Now, if you want to count the input, it's quite easy: you start with the first number, and set count=1. Then you keep looping over the remaining numbers, incrementing the count until you find a number that doesn't match. So, you end up with count=3, then you encounter 2. Great. You print "1 appears 3 times", reset count=1, and now you loop over the remaining elements until you find an element not equal to 2. So on and so forth.
But what happens if you had input like this?
1 2 5 1 4 3 4 2 1 3 4
Clearly, you cannot use the same approach. What you could do is to use a variation of your original "check for a repeat" algorithm to count instead, but while that would work for the very first time you encounter each unique number, subsequently you'll end up printing nonsense. You could adjust your algorithm to always check the entire array instead of just the remaining elements, but then you'll end printing the same output multiple times.
So, one way to fix this is to sort the array, then apply the consecutive matching algorithm I outlined earlier. Another way to fix this is to track the numbers that have been counted, hence the second approach in which I talked about using a second array.
The reason why I wrote "don't worry about the counting yet" is that if you want to do the first approach, you need to be sure that you're sorting correctly first. If you try to implement the sort and count at one go, you'll probably fail, and you'll have a hard time figuring out why.
If you prefer, you can focus on the counting first, but then you must assume that your input is sorted. In that case, only when you have the counting done right do you do the sorting.