Shuffle Utility

This class is used to shuffle a list

import java.util.List;
import java.util.Random;

/**
 * Created by luncrzs on 16/1/27.
 */
public class Shuffle {

    public static List shuffle(List list){
        Random random = new Random(System.currentTimeMillis());
        for(int i=0; i<list.size(); i++){
            int a = random.nextInt(list.size());
            int b = random.nextInt(list.size());
            if(a == b){
                continue;
            }
            Object aObject = list.get(a);
            Object bObject = list.get(b);
            list.remove(a);
            list.add(a,bObject);
            list.remove(b);
            list.add(b,aObject);
        }
        return list;
    }

    public static int[][] shuffle(int[][] arr){
        Random random = new Random(System.currentTimeMillis());
        for(int i=0; i<arr.length; i++){
            int a = random.nextInt(arr.length);
            int b = random.nextInt(arr.length);
            if(a == b){
                continue;
            }
            int[] tmp = new int[arr[0].length];
            for(int j=0; j<arr[0].length; j++){
                tmp[j] = arr[a][j];
            }
            for(int j=0; j<arr[0].length; j++){
                arr[a][j] = arr[b][j];
            }
            for(int j=0; j<arr[0].length; j++){
                arr[b][j] = tmp[j];
            }
        }
        return arr;
    }
}

标签: java, utility

添加新评论