Let's say I have an array of ints {100, 80, 90, 100, 80, 60}
so I want to count those duplicates and save those counter for later. because each duplicate number should be divided by counter
like 100 is duplicated 2 times so they should be 50 each.
to find duplicates, I used sort.
std::sort(array, array + number);
for(int i = 0; i < number; i++) {
if(array[i] == array[i+1])
counter++;
}
and I've tried to make counter array to save them on each num of array. but it didn't work. please give me some better idea.
If you want to change the array numbers directly, you may proceed like this:
Your sorted values stored in the array will come out already divided once by their corresponding counters.
Use a
std::map<int,int>
orstd::unordered_map
for counting the occurences.Then iterate over the map and replace each value by the key divided by the original value (counter).
Finally go through the original array and replace each number by its mapped value.
If you use a
std::unordered_map
the algorithm is O(n). Your original one is O(n log n) because sorting is involved.Here is algo to replace elements in place if you are allowed to modify sequence:
demo on ideone
PS modified to make it compile with array as well.
Approach 1
The easiest way, is not to sort your array, and increment elements of a map:
You can then process the content of the map:
If needed, filter out the non duplicates by rerasing them from the map or ignoring it during the processing.
Approach 2
If you're not allowed to use maps, then you have to elaborate your counting loop, in order to restart counting for each new number, and being able to process consecutive dups also if more than two:
If you need to store the pairs to process them in asecond step, you need to store a pair (preferably in a vector, but if needed in an array):
Online demo for both approaches