[英]java randomize indices in an array
I have looked at Randomize or shuffle an array Randomize or shuffle an array 我看过随机或随机排列数组随机或随机排列数组
I am not sure if this is the best approach to make. 我不确定这是否是最好的方法。
I want to randomize the indices of an array with 3 items. 我想用3个项目随机化数组的索引。
12 4 5 12 4 5
int numbers[] = new int[3];
I tried using the Maths.Random 我尝试使用Maths.Random
int randomoption2 = opmin + (int)(Math.random() * ((opmax - opmin) + 1)); int randomoption2 = opmin +(int)(Math.random()*((opmax-opmin)+ 1));
but I then have an issue with repetition of the indices values. 但是我对索引值的重复存在问题。 What is the best approach to randomize the indices so there is no repetition .
使索引随机化的最佳方法是什么,这样就不会重复。
eg 例如
a[1] = 2;
I don't want two elements in the array coming back with an indices of one 我不希望数组中的两个元素返回索引为1的元素
http://www.exampledepot.com/egs/java.util/coll_Shuffle.html 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;
}
}
I now need to store each of the numbers in variables so they can be outputted 我现在需要将每个数字存储在变量中,以便可以输出它们
System.out.println(options[0]); System.out.println(options [0]);
Use Collections.shuffle
: 使用
Collections.shuffle
:
Integer[] numbers = { 1, 2, 3, 4, 5 };
Collections.shuffle(Arrays.asList(numbers));
See it working online: ideone 看到它在线上工作: ideone
It uses the Fisher-Yates shuffle internally. 它在内部使用Fisher-Yates随机播放 。 This is an efficient shuffling algorithm that won't give you duplicates.
这是一种有效的改组算法,不会给您重复项。
Related 有关
Just keep three booleans through an array of booleans. 只需通过一组布尔值保留三个布尔值即可。 Once you hit 0, 1, or 2 index set them to true.
按下0、1或2索引后,将它们设置为true。
Choose a random position and do while(boolean[number chosen] == true) redo your random choice. 选择一个随机位置,然后执行while(boolean [number selected] == true)重做您的随机选择。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.