我需要幫助解決我遇到的一個小Java問題。我有一個名爲最低的數組。最低的例子是[6 2 9 2 7 2 3]。Java Array幫助
我需要做的是從數組中選擇最小的數字,如果有兩個或更多的條目是最低和相同的,我需要隨機選擇一個。所以在這種情況下,由於2是最低的,所以我必須隨機選擇條目1,3或5。
我該怎麼做?
我需要幫助解決我遇到的一個小Java問題。我有一個名爲最低的數組。最低的例子是[6 2 9 2 7 2 3]。Java Array幫助
我需要做的是從數組中選擇最小的數字,如果有兩個或更多的條目是最低和相同的,我需要隨機選擇一個。所以在這種情況下,由於2是最低的,所以我必須隨機選擇條目1,3或5。
我該怎麼做?
查找循環中的索引並將它們放入集合中(例如ArrayList最低)。然後使用Collections.shuffle(最低)並選取第一個元素lowest.get(0)。這應該做你想做的。
我會找到索引,將它們放在一個數組中,並生成一個介於0和array.length-1之間的隨機數,並從新數組中返回該索引。
int lowestIndex = 0;
//Make sure we start with the biggest number possible
int lowestValue = Integer.MAX_VALUE;
for(int i = 0; i < array.length; i++){
if(array[i] < lowestValue){
lowestValue = array[i];
lowestIndex = i;
}
}
現在最低索引是最低索引數!
現在這將始終返回最低值的第一個值。如果你想得到一個最低的隨機數,你可以創建一個數組或者ArrayList,其中所有元素的索引與最低值相同,然後隨機選擇。這取決於這個數組有多大以及你想要的效率。如果效率沒有什麼大問題,你可以在上面的代碼之後:
Random rand = new Random();
ArrayList<Integer> minIndexes = new ArrayList<Integer>();
for(int i = 0; i < array.length; i++){
if(array[i] == lowestValue){
minIndexes.add(i);
}
}
int r = rand.next(minIndexes.size());
int randomIndex = minIndexes.get(r);
現在randomIndex是你想要的指標!
public static void main(String[] args) {
Set<Integer> treeSet = new TreeSet<Integer>();
treeSet.addAll(Arrays.asList(new Integer[]{6,2,9,2,7,2,3}));
Iterator<Integer> iter = treeSet.iterator();
if(iter.hasNext())
{
//the lowest value from the array
System.out.println(iter.next());
}
}
以這種方式總是會有最低的值在迭代器的開始。
public static void findIndexOfMinimumRandomly(List<Integer> listOfValues) {
//Find minimum of values
int minValue = Collections.min(listOfValues);
//Create a list to hold indexes of Minimums
List<Integer> indexesOfMins = new ArrayList<Integer>();
//Fill list with index values
for (int i = 0; i < listOfValues.size(); i++) {
if (listOfValues.get(i) == minValue) {
indexesOfMins.add(i);
}
}
//Generate Random Integer to choose one of the indexes
int randomInt = new Random().nextInt(indexesOfMins.size());
//Choose one of the indexes randomly
int randomIndex = indexesOfMins.get(randomInt);
System.out.println(randomIndex);
}
你卡在哪裏? – 2011-04-09 13:39:35
這看起來像一個典型的課堂作業問題。 :) – 2011-04-09 13:51:55
'我需要做的是從數組中選擇最小的數字 - 不,您需要選擇一個最低數字的索引。 – 2011-04-09 13:54:23