java - 如何在给定范围内创建一个随机抽样数字的int数组 [英] java - How do I create an int array with randomly shuffled numbers in a given range

查看:148
本文介绍了java - 如何在给定范围内创建一个随机抽样数字的int数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上,假设我有一个可容纳10个数字的int数组。这意味着我可以在每个索引中存储0-9。(每个数字只有一次)。

Basically, let's say I have an int array that can hold 10 numbers. Which mean I can store 0-9 in each of the index.(each number only once).

如果我运行以下代码:

int[] num = new int[10];
for(int i=0;i<10;i++){
    num[i]=i;
}

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

my array would look like this: [0],[1],.....,[8],[9]

但是每次运行代码时如何随机化数字赋值?
例如,我希望数组看起来像:
[8],[1],[0] ..... [6],[3]

But how do I randomize the number assignment each time I run the code? For example, I want the array to look something like: [8],[1],[0].....[6],[3]

推荐答案

将其设为列表< Integer> 而不是数组,并使用Collections.shuffle()洗牌。你可以在洗牌后从List中构建int []。

Make it a List<Integer> instead of an array, and use Collections.shuffle() to shuffle it. You can build the int[] from the List after shuffling.

如果你真的想直接进行洗牌,请搜索Fisher-Yates Shuffle。

If you really want to do the shuffle directly, search for "Fisher-Yates Shuffle".

以下是使用List技术的示例:

Here is an example of using the List technique:

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

这篇关于java - 如何在给定范围内创建一个随机抽样数字的int数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆