Counting occurances in Java
I'm trying to iterate over a sorted array and if the previous number ==
the current number it stores the count in possiton n of a new array; when
the previous number != the current number, it then moves to n+1 on the new
array and starts counting again.
I'm debugging it now but having trouble working out what it isn't work.
Any help is much appreciated.
// Get the count of instances.
int[] countOfNumbers = new int[50]; // Array to store count
int sizeOfArray = 0; // Last position of array
filled
int instanceCounter = 1; // Counts number of instances
int previousNumber = 0; // Number stored at [k-1]
for (int k=1; k < finalArrayOfNumbers.length; k++) {
previousNumber = finalArrayOfNumbers[k-0];
if (previousNumber == finalArrayOfNumbers[k]) {
instanceCounter++;
countOfNumbers[sizeOfArray] = instanceCounter;
}
instanceCounter = 1;
sizeOfArray++;
countOfNumbers[sizeOfArray] = instanceCounter;
Don't worry about mapping or anything, I just need to know how If I have
an array of:
[20, 20, 40, 40, 50]
So I can get back
[2, 2, 1]
I'd like to keep the code as close to as is, thanks.
No comments:
Post a Comment