【问题标题】:java randomize indices in an arrayjava随机化数组中的索引
【发布时间】:2012-08-06 00:28:44
【问题描述】:

我查看了 Randomize or shuffle an array Randomize or shuffle an array

我不确定这是否是最好的方法。

我想用 3 个项目随机化数组的索引。

12 4 5

int numbers[] = new int[3];

我尝试使用 Maths.Random

int randomoption2 = opmin + (int)(Math.random() * ((opmax - opmin) + 1));

但是我遇到了重复索引值的问题。什么是随机化索引的最佳方法,所以没有重复。

例如

a[1] = 2;

我不希望数组中的两个元素返回索引为 1

http://www.exampledepot.com/egs/java.util/coll_Shuffle.html

public class randomorder {

        public static void main(String [] args)
        {
            randomorder();  
            System.out.println(randomorder());
        }

        public static ArrayList randomorder(){
            ArrayList nums = new ArrayList();
            nums.add(1);
            nums.add(2);
            nums.add(3);

            Collections.shuffle(nums);
            return nums;
        }
    }

我现在需要将每个数字存储在变量中以便输出

System.out.println(options[0]);

【问题讨论】:

  • 如果需要随机洗牌,可以使用Collections#shuffle
  • 嗨,谢谢你能提供一个简单的例子吗

标签: java arrays indices


【解决方案1】:

使用Collections.shuffle:

Integer[] numbers = { 1, 2, 3, 4, 5 };
Collections.shuffle(Arrays.asList(numbers));

在线查看:ideone

它在内部使用Fisher-Yates shuffle 。这是一种高效的洗牌算法,不会给你重复。

相关

【讨论】:

  • 不适用于int[],刚刚经过测试。基元数组不会被改组。与Integer[] 一起工作正常...(令我惊讶)
  • 现在请使用int[] 的数组:P - 从int[] 转换为Integer[] 显然不起作用;)
  • @Andreas_D:你是对的。你不能有List<int>。相反,你会得到一个List<int[]>!解决方案是改用Integer[]。相关:Arrays.asList() not working as it should?.
  • @alex:“然后需要打印出这些值以便每个 System.out.println 包含一个值”是什么意思。这是作业吗?
  • 它是我正在编写的一个软件。我已经完成了随机数生成器功能。它是用 android 编写的,但我想将 android 框架与 Java 代码分开。我需要打乱的数字进入三个单选按钮
【解决方案2】:

只需通过一个布尔数组保留三个布尔值。一旦您点击 0、1 或 2 索引,请将它们设置为 true。

选择一个随机位置并执行 while(boolean[number selected] == true) 重做您的随机选择。

【讨论】:

  • 如果集合的答案不可行,这与我会做的很接近。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多