開発メモ

開発用のメモです。

シャッフル

ソース

package jp.mirageworld.algorithm.shuffle;

import java.util.ArrayList;
import java.util.List;

public class RandomShuffle {

    public static <T extends Comparable<T>> List<T> shuffle(List<T> list) {
        List<T> retList = new ArrayList<T>(list);
        for (int i = 0; i < list.size(); i++) {
            int index = Double.valueOf(Math.random() * list.size()).intValue();
            T x = retList.remove(index);
            retList.add(x);
        }
        return retList;
    }
}

テストケース

package jp.mirageworld.algorithm.shuffle;

import static org.junit.Assert.*;

import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;

import org.junit.Test;

public class RandomShuffleTest {

    @Test
    public void testShuffle() {
        Set<Long> set = new HashSet<>();
        Long target = Math.round(Math.random() * 50);
        while (set.size() < 50) {
            set.add(Math.round(Math.random() * 50 + set.size() * 50));
        }
        List<Long> list = new LinkedList<>(set);
        target = list.get(target.intValue());

        Collections.sort(list);
        List<Long> retList = RandomShuffle.shuffle(list);

        assertNotEquals(list.toString(), retList.toString());
        Collections.sort(retList);
        assertEquals(list.toString(), retList.toString());
    }

}
Twitter: @asahina_alice