shuffle two Lists - Android java.util

Android examples for java.util:List Algorithm

Description

shuffle two Lists

Demo Code


//package com.java2s;
import java.util.List;
import java.util.ListIterator;
import java.util.Random;
import java.util.RandomAccess;

public class Main {
    private static Random r;

    public static void shuffle(List<?> list1, List<?> list2) {
        if (r == null) {
            r = new Random();
        }//w  ww .ja va  2 s .c  om
        shuffle(list1, list2, r);
    }

    public static void shuffle(List<?> list1, List<?> list2, Random rnd) {
        int size1 = list1.size();
        int size2 = list2.size();
        if (size1 == size2) {
            if (size1 < 5 || list1 instanceof RandomAccess) {
                for (int i = size1; i > 1; i--) {
                    i--;
                    int random = rnd.nextInt(i);
                    swap(list1, i, random);
                    swap(list2, i, random);
                }
            } else {
                Object arr[] = list1.toArray();
                Object arr2[] = list2.toArray();
                // Shuffle array

                for (int i = size1; i > 1; i--) {
                    i--;
                    int random = rnd.nextInt(i);
                    swap(arr, i, random);
                    swap(arr2, i, random);
                }
                // Dump array back into list
                ListIterator it = list1.listIterator();
                for (int i = 0; i < arr.length; i++) {
                    it.next();
                    it.set(arr[i]);

                }
                ListIterator it2 = list2.listIterator();
                for (int i = 0; i < arr2.length; i++) {
                    it2.next();
                    it2.set(arr2[i]);

                }
            }
        }
    }

    public static void swap(List<?> list, int i, int j) {
        final List l = list;
        l.set(i, l.set(j, l.get(i)));
    }

    private static void swap(Object[] arr, int i, int j) {
        Object tmp = arr[i];
        arr[i] = arr[j];
        arr[j] = tmp;
    }
}

Related Tutorials