develog

[java] random, shuffle 본문

카테고리 없음

[java] random, shuffle

냐옴 2020. 4. 21. 14:16

 

public static int randomBetween(int start, int end) {
    return (int) ((Math.random() * (end - start + 1)) + start);
}

public static <T> T randomOneOf(T[] list) {
    return list[randomBetween(0, list.length - 1)];
}

public static void shuffle(Integer[] list) {
    for (int i = 0; i < list.length; i++) {
        int x = randomBetween(0, list.length - 1);
        int y = randomBetween(0, list.length - 1);
        int temp = list[x];
        list[x] = list[y];
        list[y] = temp;
    }
}
Comments