繁体   English   中英

Arrays 和 For 循环 - 打印随机元素时不正确的 output

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM