[英]Arrays and For-loop - Incorrect output while printing Random elements
我在這個世界上很新,我必須說有時候看起來很容易的事情很苛刻。
我被一項需要處理數組和for
循環的任務困住了。
我應該遍歷數組並為每個迭代步驟打印一個不同的隨機字符串。 我當前的代碼無法正常工作,唯一的事情是我得到一個隨機項目並且多次打印相同的索引。
我的 output 現在:
relax
2
2
2
2
我該如何解決這個問題並獲得正確的隨機 output?
我的代碼:
public static void main(String[] args) {
int i;
String Cofee[] = {"pick it","drink it","relax","put it in a cup",};
java.util.Random randomGenerator = new java.util.Random();
int x = Cofee.length;
int y = randomGenerator.nextInt(x);
String frase = Cofee[y] ;
System.out.println(frase);
for(i = 0; i < Cofee.length; i++)
System.out.println(y);
}
給y
賦值一次,然后重復打印y
。 y
的值不會改變。 為此,您需要為循環的每次迭代調用randomGenerator.nextInt(x)
!
但是,如果要隨機化並打印數組,請使用:
public static void main(String[] args)
{
String[] coffee = {"pick it","drink it","relax","put it in a cup",};
// this wraps the array,
// so modifications to the list are also applied to the array
List<String> coffeeList = Arrays.asList(coffee);
Collections.shuffle(coffeeList);
for(String value : coffee)
System.out.println(value);
}
順便說一句,不要使用String coffee[]
,而是使用String[] coffee
。 盡管 Java 允許將數組類型放在變量名之后,但它被認為是錯誤的形式。
或者直接使用列表:
public static void main(String[] args)
{
List<String> coffeeList = Arrays.asList("pick it","drink it","relax","put it in a cup");
Collections.shuffle(coffeeList);
for(String value : coffeeList)
System.out.println(value);
}
為此,您可以實現洗牌算法。
它並不像一開始聽起來那么害怕。 Fisher-Yates shuffle是著名的經典洗牌算法之一,相對容易掌握。
核心思想:從0
到最后一個索引遍歷給定數組,並且對於每個索引,將對應於0
和當前索引( i
) 之間隨機生成的索引的元素與當前索引下的元素交換。
另外,我建議創建一個表示索引的單獨數組並將其打亂,以保留字符串數組的初始 state(如果不需要,可以省略這部分並相應地更改代碼)。
這就是它的實現方式:
public static final Random RANDOM = new Random(); // we need an instance for random to generate indices
Fisher-Yates shuffle 實現:
public static void shuffle(int[] arr) {
for (int i = 0; i < arr.length; i++) {
int j = RANDOM.nextInt(i + 1); // generating index in range [0, i]
swap(arr, i, j); // swapping elements `i` and `j`
}
}
交換元素的輔助方法:
public static void swap(int[] arr, int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
用法示例:
String[] coffee = {"pick it","drink it","relax","put it in a cup"};
int[] indices = new int[coffee.length];
for (int i = 0; i < indices.length; i++) indices[i] = i; // or Arrays.setAll(indices, i -> i); if you're compfortable with lambda expressions
shuffle(indices);
for (int i = 0; i < coffee.length; i++) {
String next = coffee[indices[i]];
System.out.println(next);
}
Output:
drink it
pick it
put it in a cup
relax
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.