[英]How to find the position of the highest and second highest value in an array in java
[英]How to get the second highest value from an array, the third highest value etc
对于这个问题,我真的需要一些帮助。 我正在尝试用Java代码编写一个函数,但是我被卡住了,而且我不知道如何继续。 我有包含1行(区域)和7列(医院)的数据。 对于该区域,此人将在医院1结束一个百分比,而另一个人将在h2结束,等等。数据看起来像这样:
hospital h1 h2 h3 ...
area
a1 11 45 3 ...
我已将数据保存在包含7个值的双精度数组中。 我有这个随机生成器fcn,它随机选择数组中我们所在位置的索引值。 如果此随机生成器选择例如index = 0表示11%,如果它随机选择index = 2表示3%等。
问题是完成此操作后,我想检查该医院是否闲置。 如果它空闲,那么我想返回随机选择的整数索引值。 如果它不空闲,我想选择第二高百分比的下一家医院,如果那家医院空闲,则返回此int索引值,否则继续检查第三高的百分比,然后再进行检查,依此类推。 如果所有医院都不空闲,则返回随机选择的值。
到目前为止,这是我所做的:
double vector[] = new double[distrToEachHosp.length]();
//start by setting the contents to index
for(int index=0; index<vector.length; index++){
vector[index] = index;
}
for(int i=0; i <= vector.length; i++){
for(int x=1; x <= vector.length; x++){
if (distrToEachHosp[vektor[x]] > distrToEachHosp[vektor[x+1]]){ //compare content that corresponds to index
//move index
int temp = vector[x];
vector[x] = vector[x+1];
vector[x+1] = temp;
}
}
}
return vektor;
int rndValue = randomGenerator(distrToEachHosp);
for(int i=0; i<vector.length; i++){
if(hospital.get(i).namn == hospitalNameVariable[rndValue] ){ //hospitalNameVariable is a variable containing the names of the hospitals
if(hospital.get(i).idle()>0){
return rndValue;
} else {
if(vector[0] >= rndValue) {
return vector[0];
} else if(vektor[1] >= slumpVärde) {
......
}
}
}
这就是我卡住的地方。 现在,我使用第一种算法对数据进行了排序,但是从逻辑上讲,我不知道如何包括所有情况。
您可以使用Arrays.sort(vector)
进行排序而不是实现。
对于第二个和第三个值,您始终可以分别通过诸如vector[vector.length-2]
, vector[vector.length-3]
类的索引进行访问。
每次您选择医院时,都没有理由对阵列进行排序,这似乎就像您要尝试的那样。
如果在程序开始时对数组进行一次排序,则非常简单。 将索引设置为随机选择,如果它不空闲则减少索引,如果它不空闲则减少索引,重复直到找到空闲或用完选项。 由于数组始终按排序顺序,因此无论您身在何处,您始终知道下一个最佳选择是数组中的上一个值。 高度
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.