gpt4 book ai didi

java随机化数组中的索引

转载 作者:行者123 更新时间:2023-12-01 16:33:32 24 4
gpt4 key购买 nike

我查看了随机化或随机排列数组 Randomize or shuffle an array

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

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

1245

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(选项[0]);

最佳答案

使用Collections.shuffle :

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

查看它在线运行:ideone

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

相关

关于java随机化数组中的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11872258/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com