如何自定义Java中的shuffle函数
导读:在Java中,要实现一个自定义的shuffle函数,你可以使用Fisher-Yates洗牌算法 import java.util.Random; public class CustomShuffle { public static...
在Java中,要实现一个自定义的shuffle
函数,你可以使用Fisher-Yates洗牌算法
import java.util.Random;
public class CustomShuffle {
public static void main(String[] args) {
int[] array = {
1, 2, 3, 4, 5, 6, 7, 8, 9}
;
System.out.println("Before shuffling:");
printArray(array);
shuffle(array);
System.out.println("\nAfter shuffling:");
printArray(array);
}
public static void shuffle(int[] array) {
Random random = new Random();
for (int i = array.length - 1;
i >
0;
i--) {
int index = random.nextInt(i + 1);
// Swap array[i] and array[index]
int temp = array[i];
array[i] = array[index];
array[index] = temp;
}
}
public static void printArray(int[] array) {
for (int value : array) {
System.out.print(value + " ");
}
}
}
这个示例中的shuffle
方法接受一个整数数组作为参数。通过使用Fisher-Yates算法,我们遍历数组并随机交换元素,从而实现数组的随机排序。printArray
方法用于打印数组的内容。
你可以根据需要修改此代码,以便处理其他类型的数组,例如float[]
、double[]
、String[]
等。只需将数组类型更改为所需的类型,并相应地调整shuffle
和printArray
方法。
声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!
若转载请注明出处: 如何自定义Java中的shuffle函数
本文地址: https://pptw.com/jishu/698087.html