计算平均值和模式
我应该返回给定数组的平均值和模式。但是,对于模式,如果有两种模式,那么我需要在数组中返回第一个模式。例如,如果阵列为statsfinder([500、400、400、375、375、300、350、325、300]),输出应为:[368.75,400],因为400在300前的数组中发生了400。接近解决方案,我无法获得第一个发生模式。任何人都知道如何修复我的代码以获得第一个发生模式? 这是我的解决方案:
function statsFinder(array) {
let length=array.length
let sum=array.reduce((acc,curr)=>{
return acc+curr
})
let mean=sum/length
let obj=array.reduce((acc,curr)=>{
acc[curr]=acc[curr] ? acc[curr]+1:1
if(acc[curr]>acc.max){
acc.max=acc[curr]
}
return acc
},{max:1})
let mode=0
for(let key in obj){
if (mode[key]===mode.max){
mode=parseInt(key)
}
return [mean, mode]
}
}
I am supposed to return the mean and the mode of a given array. For the mode though, if there are two modes then I need to return the first one in the array. For example if the array was statsFinder([500, 400, 400, 375, 300, 350, 325, 300]) the output should be: [368.75, 400] since 400 occurs in the array before 300. Although I believe I am close to the solution I can't get the first occurring mode. Anyone have any idea how I could fix my code to get the first occurring mode??
Here's my solution for it:
function statsFinder(array) {
let length=array.length
let sum=array.reduce((acc,curr)=>{
return acc+curr
})
let mean=sum/length
let obj=array.reduce((acc,curr)=>{
acc[curr]=acc[curr] ? acc[curr]+1:1
if(acc[curr]>acc.max){
acc.max=acc[curr]
}
return acc
},{max:1})
let mode=0
for(let key in obj){
if (mode[key]===mode.max){
mode=parseInt(key)
}
return [mean, mode]
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您要做的:
尽管您应该在第二次扫描中修复凹痕,以便您可以看到为什么它不起作用,但可能会奏效。您想要这个:
或者,更好的是:
请注意,依靠JavaScript对象中属性的迭代顺序不是最好的做法,尽管它可能“大多数情况下”。如果您需要按插入顺序进行迭代,则应使用
MAP
(如果可能)。但是整个扫描是愚蠢的。您可以在计数频率时记住与最大计数相关的值:
然后,您知道该模式而无需再次搜索它,而且您无需将值转换回一个数字。
What you do:
That could work, sort of, although you should fix the indentation in the second scan so that you can see why it doesn't work. You wanted this:
or, imho better:
Note that it's not best practice to rely on the order of iteration of properties in a Javascript object, although it will probably work "most of the time". If you require iteration in insertion order, you should use a
Map
, if possible.But that whole scan is silly. You could just remember the value associated with the maximum count while you count frequencies:
Then you know the mode without needing to search for it again, and moreover you don't have any need to convert the value back to an number.
只是面临同样的挑战,到目前为止,这是我的代码,希望它对您有所帮助。它只是通过3/5测试,因此仍然可以改进。
Just got to the same challenge and so far this is my code, hope it helps you. It's only passing 3/5 tests, so still room for improving.