public class SimpleRandomCount extends RandomCount
{
/**
* Generate an array containing elements in a random order
*
* @param size the size of the array to be generated
*/
public SimpleRandomCount(int size) {
super(size);
}
/**
* Randomise the array
*/
protected void randomise() {
int[] copy = new int[array().length];
int randomIndex;
// used to indicate if elements have been used
boolean[] used = new boolean[array().length];
Arrays.fill(used,false);
for (int index = 0; index < array().length; index++) {
do {
randomIndex = randomIndex();
} while (used[randomIndex]);
copy[index] = array()[randomIndex];
used[randomIndex] = true;
}
for (int index = 0; index < array().length; index++) {
array()[index] = copy[index];
}
}
public static void main(String [] args){
RandomCount count = new SimpleRandomCount(5);
System.out.println("Array is " + Arrays.toString(count.array()));
}
}
SimpleRandomCount类是另一个名为RandomCount的类的一部分。我想知道是否有更聪明,更短的方法来随机化数字而不使用布尔值来帮助实现它?
感谢您的帮助,非常感谢。
答案 0 :(得分:0)
如果您不需要它特别有效,您可以依靠Collections.shuffle
来完成工作。
您需要将数组转换为List
,然后将元素复制回来:
// copy the array to a list
List<Integer> copy = new ArrayList<>();
for (int index = 0; index < array().length; index++)
{
copy.add(array()[index]);
}
// Shuffle the elements in the copy
Collections.shuffle(copy);
// copy them back to the array
for (int index = 0; index < array().length; index++) {
array()[index] = copy.get(index);
}