Search code examples
processingarduinomode

How to calculate the statistical mode in Processing / Arduino


I'm a design teacher trying to help a student with a programming challenge, so I code for fun, but I'm no expert.

She needs to find the mode (most frequent value) in a dataset built using data from sensors coupled to an Arduino, and then activate some functions based on the result.

We've got most of it figured out, except how to calculate the mode in Arduino. I found the post Get the element with the highest occurrence in an array that solves the problem in JavaScript, but I haven't been able to "port" it.


Solution

  • I ported the code from your linked post to Processing, but it's limited to int arrays. I hope that helps.

    void setup()
    {
        int[] numbers = {1, 2, 3, 2, 1, 1, 1, 3, 4, 5, 2};
        println(mode(numbers));
    }
    
    
    int mode(int[] array) {
        int[] modeMap = new int [array.length];
        int maxEl = array[0];
        int maxCount = 1;
    
        for (int i = 0; i < array.length; i++) {
            int el = array[i];
            if (modeMap[el] == 0) {
                modeMap[el] = 1;
            }
            else {
                modeMap[el]++;
            }
    
            if (modeMap[el] > maxCount) {
                maxEl = el;
                maxCount = modeMap[el];
            }
        }
        return maxEl;
    }