mode function

Sep 13, 2015 at 8:19pm
hello guys, i was trying to make my mode function, but it didn't come out right.
could u guys pls help me have a look??
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31

int mode(vector<int> arr, int size)
{
    int modeValue=0, counter=0, tempCounter=0;
    sort(arr.begin(), arr.end());
    
    for(int x = 0 ; x < size; x++){
        
        
        
        for(int k = 0 ; k < size; k++)
        {
            if(arr[x] == arr[k])
            {
                tempCounter++;
            }
        }
        if(tempCounter > counter){
            counter = tempCounter;
            
            tempCounter = 0;
            
            modeValue = arr[x];
           
    
        }
        
    }
    return modeValue;
}
Sep 13, 2015 at 8:53pm
One problem is this one: if the condition

if(tempCounter > counter)

is not true, then tempcounter is not reset to zero, which is wrong.

P.S. You can avoid passing the size of the vector as a parameter: you can just use arr.size().

P.P.S. This algorithm seems quite inefficient: if an element is repeated in your array, it is checked many times. This happens because for every element you repeat the analysis from the beginning. Instead you could find a way to avoid doing so...
Last edited on Sep 13, 2015 at 8:55pm
Sep 13, 2015 at 8:57pm
1. tempCounter = 0; should go at the beginning of the outer for loop
2. 'counter' should be named 'max' or 'maxcounter' (it is not a counter at all)
3. dont make size a parameter of the mode founction, instead use the statement:
int size = int(arr.size());
at the beginning of the function
4. With your method of finding mode, calling sort is actually unnecessary

(the actual bug is only in no. 1)
Sep 13, 2015 at 8:58pm
@Kevin C: I am happy to see we agree!
Sep 13, 2015 at 9:10pm
@Kevin C @minomic
thank you for your help!
and @Kevin C
I think that if i don't add the sort function into my mode function, once i have a list such as { 1,2,4,3,3,4}
then my mode will become 4 instead of 3
Sep 13, 2015 at 9:39pm
The sort then won't help for: 4 3 1 2 2 1.

then my mode will become 4 instead of 3

Both 4 and 3 are modes in your case.

To make the function return all the modes, it will need to return an array (vector). You will need another for loop at the end of that function to put all modes into that array. Finally, you can use sort to make removing duplicates easier.
Last edited on Sep 13, 2015 at 9:39pm
Topic archived. No new replies allowed.