【问题标题】:How do I create an int array with randomly shuffled numbers in a given range [duplicate]如何在给定范围内创建一个随机打乱数字的 int 数组 [重复]
【发布时间】:2013-02-18 05:37:39
【问题描述】:

基本上,假设我有一个可以容纳 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]

【问题讨论】:

    标签: java arrays math random integer


    【解决方案1】:

    将其设为List&lt;Integer&gt; 而不是数组,并使用 Collections.shuffle() 对其进行随机播放。您可以在洗牌后从列表中构建 int[]。

    如果你真的想直接进行随机播放,请搜索“Fisher-Yates Shuffle”。

    以下是使用列表技术的示例:

    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]);
        }
      }
    }
    

    【讨论】:

    • List 可以存储任何引用类型,包括 Integer。
    • 当我在 Eclipse 上输入 num.add(1) 时。它说“List 类型中的方法 add(String) 不适用于参数 (int)”。 'num' 是我的列表变量。
    • 当我将它声明为 List 时,它要求我删除 部分。
    • 您使用的是什么 Java 版本?
    • 注意您要导入的 List 类。它必须是 java.util.List。
    【解决方案2】:

    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;
    }
    

    【讨论】:

      猜你喜欢
      • 2016-07-24
      • 2016-01-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-20
      • 2015-08-25
      • 1970-01-01
      相关资源
      最近更新 更多