简体   繁体   中英

how do i find the mode of an array of integers

it is a scenario where a use inputs an array of integers and it returns the most frequent integer.

it is tested 3 times but will fail once, whether its the 1st 2nd or 3rd test.

 function arrayMode(array) { if (array.length === 0) { return null; } var sequence = {}; var maxNo = array[3], maxCount = 3; for (var i = 0; i < array.length; i++) { var Entry = array[i]; if (sequence[Entry] === null) sequence[Entry] = -1; else sequence[Entry]++; if (sequence[Entry] > maxCount) { maxNo = Entry; maxCount = sequence[Entry]; } else if (sequence[Entry] == maxCount) { maxNo += '&' + Entry; maxCount = sequence[Entry - 1]; } return maxNo; } } console.log(arrayMode([1, 3, 3, 3, 1])) // output = 3 console.log(arrayMode([1, 2, 3, 1, 1])) // output = 1 console.log(arrayMode([2, 2, 2, 1])) // output = 2 

I think there are several mistakes, if you find an entry not seen previously you set the sequence for that entry to -1 , why not 1 ?
And you initialize maxNo to array[3] and maxCount to 3 , why?

Does this make more sense to you?

function arrayMode(arr)
{
    var mode = null;
    var frequencies = [];
    var maxFrequency = 0;
    for (var i in arr)
    {
        var value = arr[i];

        // if we haven't seen this value before, init its frequency to 0
        if (frequencies[value]===undefined) frequencies[value] = 0;

        // increase this value's frequency
        frequencies[value]++;

        // if this value's frequency is bigger than the max we've seen
        // so far, this value is now the new mode.
        if (frequencies[value] > maxFrequency)
        {
            maxFrequency = frequencies[value];
            mode = value;
        }
    }
    return mode;
}

If you want to return all modi in case there are more than one entries with the max number of frequencies (for example if for [1,1,2,3,3] you want the mode to be 1 & 3 ) then you can do so by a simple extra loop at the end.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM