0

I have an array something like [0,0,0,0,0,0,1,1,1,1,1,1,1,2,2,2,2,2,2]. I want to find the most frequent value. If two are more are having highest frequency, the first occurance should be the result. I am passing it to function to get result. I don,t know where the error is but the result is not right. My function is not working as required.

function mode(uint[] memory array) public pure returns(uint)
    {
        uint  modeValue; 
        uint[] memory count; 
        uint  number; 
        uint maxIndex = 0;
        //uint zero=0;

    for (uint i = 0; i < array.length; i += 1) {
        number = array[i];
        count[number] = (count[number]) + 1;
        if (count[number] > maxIndex) {
            maxIndex = count[number];
        }
    }

    for (uint i =0;i<count.length; i++)
        if (count[i] == maxIndex) {
                modeValue=count[i];
                break;
            }

    return modeValue;
    }```
1

Your technical mistake is that uint[] memory count is not initialized, so any access attempt of the sort count[number] or count[i] will naturally cause your function to revert; you must find the maximum value in the input array, and then initialize count = new uint[](maxInputValue + 1).


Your logical mistake is that instead of this:

if (count[number] > maxIndex) {
    maxIndex = count[number];
}

You should be doing this:

if (count[number] > count[maxIndex]) {
    maxIndex = number;
}

Your conceptual mistake (assuming that your input array is sorted as shown in the question) is that you don't need the count array to begin with, and you can simply keep the max count and its corresponding value as you go.

| improve this answer | |
  • My array is not sorted always. So count is needed. I edited my function as uint[] memory count= new uint[](array.length); . Still the same error. – Ramya Jan 22 at 10:38
  • @Ramya: Using array.length here is wrong. In order to support count[number], you should use "the maximum value in the array" + 1 instead. Can you see why? – goodvibration Jan 22 at 11:58
  • In addition to that, your logic is completely wrong. Instead of if (count[number] > maxIndex) you should use if (count[number] > count[maxIndex]), and instead of maxIndex = count[number] you should use maxIndex = number. See updated answer. – goodvibration Jan 22 at 12:01
  • I modified the code and removed the second for loop too. Works perfectly fine.Thanks for the timely support @goodvibration – Ramya Jan 22 at 20:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.