【发布时间】:2019-04-17 16:07:08
【问题描述】:
我的任务是查找给定数组的模式(未指定长度)。模式定义为最唯一出现的数字。因此,例如,数组 [1.0, 2.0, 3.0, 2.0] 的众数为 2.0。但是,如果该值没有唯一编号,例如 [1.0, 2.0, 2.0, 3.0, 3.0],则程序在我的程序中返回“无模式”或“Double.NaN”。
我编写了适用于 3/4 测试用例的代码,但总是搞砸有两种模式相同的情况。
public double mode() {
double modeOne = data[0];
double modeTwo = 0;
int count = 0;
int countOne = 0;
int countTwo = 0;
if(data.length == 1) { // special case: if array length is 1 the mode will always just be that value
modeOne = data[0];
return modeOne;
} // end if
for(int i = 0; i < data.length; i++) { // pulling out first value
double value = data[i];
for(int n = 0; n < data.length; n++) { // comparing first value to all other values
if (data[n] == value) {
count ++; // adding onto a count of how many of the same number there are
}
}
if(modeOne == value || modeTwo == value) { // move on if the modes already have that value
continue;
}
if(count > countOne) { // setting the max count
countTwo = countOne;
countOne = count;
modeTwo = modeOne;
modeOne = value;
}
else if(count > countTwo) { // setting second highest count
countTwo = count;
modeTwo = value;
}
} // end for
if(countOne == 1) { // if all the modes are just one
return Double.NaN;
}
if(countOne == countTwo) { // if there are two of the same modes
return Double.NaN;
}
else {
return modeOne;
}
} //end MODE
对于这个测试用例:
double[] data = {1,2,2,3,3,4};
Stat stat1 = new Stat(data);
System.out.println("stat1 mode = " + stat1.mode());
我期望“NaN”,但它返回 4。但是,它适用于以下情况:
double[] data = {-5.3, 2.5, 88.9, 0, 0.0, 28, 16.5, 88.9, 109.5, -90, 88.9};
Stat stat1 = new Stat(data);
System.out.println("stat1 mode = " + stat1.mode());
预期的输出是 88.9,程序确实输出正确。
【问题讨论】:
-
最独特是否意味着最频繁?
-
是 - 最常见但也不应该在该数组中存在具有相同模式的另一个值。如果这是有道理的。所以 [1.0,1.0,2.0,2.0,3.0] 没有模式,因为 1.0 和 2.0 出现的次数相同。
-
您不能简单地扫描数组并将每个遇到的数字的频率保存在一个列表中。然后按频率递减排序。如果此列表有超过 1 个元素并且前 2 个元素具有相同的频率,则返回 NaN。否则返回列表中的第一个元素。
-
一定要喜欢学校项目,这些项目为您提供了一个复杂的多功能工具来学习并告诉您使用它的唯一方法是作为锤子:p
-
转学怎么样?