如何创建一个在给定范围内随机排列的整数数组

5
基本上,假设我有一个可以存储10个数字的int数组。这意味着我可以在每个索引中存储0-9(每个数字只能出现一次)。
如果我运行以下代码:
int[] num = new int[10];
for(int i=0;i<10;i++){
    num[i]=i;
}

我的数组看起来像这样:
[0],[1],.....,[8],[9]

但是我该如何在每次运行代码时随机分配数字? 例如,我希望数组看起来像这样:
[8],[1],[0].....[6],[3]
2个回答

10
将其改为List<Integer>而不是数组,并使用Collections.shuffle()来随机排序。在随机排序后,您可以从List构建int[]。
如果您真的想直接进行洗牌,请搜索“Fisher-Yates Shuffle”。
这是使用List技术的示例:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Test {
  public static void main(String args[]) {
    List<Integer> dataList = new ArrayList<Integer>();
    for (int i = 0; i < 10; i++) {
      dataList.add(i);
    }
    Collections.shuffle(dataList);
    int[] num = new int[dataList.size()];
    for (int i = 0; i < dataList.size(); i++) {
      num[i] = dataList.get(i);
    }

    for (int i = 0; i < num.length; i++) {
      System.out.println(num[i]);
    }
  }
}

1
列表(List)可以存储任何引用类型,包括整型(Integer)。 - Patricia Shanahan
当我在Eclipse上输入num.add(1)时,它会显示"The method add(String) in the type List is not applicable for the arguments (int)"。'num'是我的列表变量。 - user2129846
我已经添加了一个完整的使用List<Integer>的示例。但是,如果您希望在学习更多有关它的知识之前避免使用List,请参阅我的关于Fisher-Yates Shuffle的评论。 - Patricia Shanahan
我将List更改为ArrayList,然后它就起作用了。非常感谢您的代码。 - user2129846
1
请注意导入的List类。它必须是java.util.List。 - Patricia Shanahan
显示剩余3条评论

1

Collections类有一个高效的方法可以用来洗牌:

private static Random random;

/**
 * Code from method java.util.Collections.shuffle();
 */
public static void shuffle(int[] array) {
    if (random == null) random = new Random();
    int count = array.length;
    for (int i = count; i > 1; i--) {
        swap(array, i - 1, random.nextInt(i));
    }
}

private static void swap(int[] array, int i, int j) {
    int temp = array[i];
    array[i] = array[j];
    array[j] = temp;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接