溫馨提示×

如何自定義Java中的shuffle函數(shù)

小樊
81
2024-09-09 12:54:27
欄目: 編程語言

在Java中,要實現(xiàn)一個自定義的shuffle函數(shù),你可以使用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方法接受一個整數(shù)數(shù)組作為參數(shù)。通過使用Fisher-Yates算法,我們遍歷數(shù)組并隨機交換元素,從而實現(xiàn)數(shù)組的隨機排序。printArray方法用于打印數(shù)組的內容。

你可以根據(jù)需要修改此代碼,以便處理其他類型的數(shù)組,例如float[]、double[]、String[]等。只需將數(shù)組類型更改為所需的類型,并相應地調整shuffleprintArray方法。

0