简体   繁体   English

我如何找到整数数组的模式

[英]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. 它经过了3次测试,但无论是第2次还是第3次测试都将失败一次。

 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 ? 我认为有几个错误,如果您找到一个以前没有见过的条目,则将该条目的sequence设置为-1 ,为什么不设置1
And you initialize maxNo to array[3] and maxCount to 3 , why? 然后将maxNo初始化为array[3]并将maxCount3 ,为什么呢?

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. 如果要返回所有 modi,以防出现不止一个具有最大频率数的条目(例如,对于[1,1,2,3,3]您希望模式为1 & 3 ),则可以最后通过一个简单的额外循环来做到这一点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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