[英]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.