hi guys
I'm working of self-study project that needs to count how many an element of an array is repeated. And print out result.
I've been asking myself whether there is a smarter way doing this. Can you please help?
Code:
For instance:
input 5 5 5 6 7 8 91 1
output:
1 1
5 3
6 1
7 1
8 1
91 1
number 5 appears 3 times, while other only shows up 1 time.
My algorithm goes like this: Since i don't study to use dynamic array yet. I assume the max of number of input is 100, or inputNumberArray[100]={0}. Then if the number of is input is less than 100, i will only concentrate on the non-zero part of the array.
There will be another array of coutingArray[100]={0} that will be used to store the counter's value for each element.
First, sort the array in acesnding order
so that: 1 5 5 5 6 7 8 91
Then, (the tricky part), try to detect the repeating of each element.
Code:
//sourceArray=array of input numebrs
//targetArray=array of counters
void processArrays(int sourceArray[], int element, int targetArray[])
{
for (int i=1; i<element;i++)
{
if (compareEl(sourceArray, i))
{
targetArray[i]=targetArray[i]+1;
cout << "\n TRUE " << targetArray[i];
} else
{
cout << "\n FALSE ";
continue;
}
}
}
And funtion compareEl to computer each element its LEFT neighbor and RIGHT neighbor.
1. if LEFT is the same && RIGHT is the same, do not count
2. if LEFT is different && RIGHT is different, do count
3. if LEFT is the same && RIGHT is different, do not count
4. if LEFT is different && RIGHT is the same, do count
thanks so mcuh!!!