【问题标题】:How to get a random list of 10 numbers from 1 to 10 without repeating the members of the list [duplicate]如何在不重复列表成员的情况下获得从 1 到 10 的 10 个数字的随机列表 [重复]
【发布时间】:2021-09-15 15:31:10
【问题描述】:

我正在尝试编写一个方法来获取从 1 到 10 的数字列表,其中不会有重复项。此外,成员不得为零。 但是,经过多次尝试我未能解决问题,这是我的代码:

public ArrayList<Integer> dobijNiz() {
        int min = 1;
        int max = 10;
        ArrayList<Integer> lista = new ArrayList<Integer>();
        Random random = new Random();

        for (int i = 0; i < 11; i++) {
            int broj = random.nextInt((max - min) + 1) + min;

            lista.add(broj);   
        }
        System.out.println(lista);
        return lista;
    }

输出:

[2, 3, 3, 3, 4, 6, 10, 8, 2, 7, 9]

我忘了说 Collections.shuffle 不起作用

【问题讨论】:

  • 编程到List 接口(而不是在任何地方指定ArrayList)。 List&lt;Integer&gt; lista = IntStream.range(min, max).boxed().collect(Collectors.toList()); 然后Collections.shuffle(lista, ThreadLocalRandom.current());
  • 问题有问题。如果您需要 10 个随机数并且列表大小为 10,那么它总是必须是 1 到 10 之间的数字。假设您期望 5 随机从 1 到 10,那么这就是它的样子。您还应该检查 max-min 是否大于 count 以确保它确实进入无限循环 :) [![Working Example][1]][1] [1]: i.stack.imgur.com/BOLmw.gif

标签: java arrays list sorting arraylist


【解决方案1】:

将所有可能的数字添加到 ArrayList 中,然后使用Collections.shuffle 打乱列表。

int min = 1;
int max = 10;
ArrayList<Integer> lista = new ArrayList<Integer>();
for (int i = min; i <= max; i++) {
    lista.add(i);   
}
Collections.shuffle(lista);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-09
    • 2013-12-21
    • 2018-11-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多