洗牌程序的两种算法

package com.oracle.test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Random;
import java.util.stream.Collectors;
import java.util.List;

import org.testng.annotations.Test;

public class PocketDemoTest {
    

    public static final int POCKET_NUM = 100;
    //洗牌洗100次,生成随机数,每次交换两张牌
    public int [] getPocket(int [] pocket) {
        int num = POCKET_NUM;
        while(num>0) {
            Random random = new Random();
            int rnd1 = random.nextInt(54);
            int rnd2 = random.nextInt(54);

            if(rnd1!=rnd2) {
                int tmp = pocket[rnd1];
                pocket[rnd1] = pocket[rnd2];
                pocket[rnd2] = tmp;
            }
            num --;
        }

        return pocket;
    }


    //洗牌,从List中随机抽,放到新的List里面
    public int [] getPocketList(int [] pocket) {
        List srcList = Arrays.stream(pocket).boxed().collect(Collectors.toList());
        List dstList = new ArrayList();
        while(!srcList.isEmpty()) {
            Random random = new Random();
            if(srcList.size()>1) {
                int tmp = random.nextInt(srcList.size());
                dstList.add(srcList.get(tmp));
                srcList.remove(tmp);
            }else {
                dstList.add(srcList.get(0));
                srcList.remove(0);
            }
        }

        return dstList.stream().mapToInt(i->i).toArray();
    }




    @Test
    void testPocketDemo() {
        int [] pocket = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,
        34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54};

        int [] newPocket = getPocketList(pocket);
        for(int i : newPocket) {
            System.out.print(i+" ");
        }

        System.out.println();

    }
}

输出如下,


image.png

你可能感兴趣的:(洗牌程序的两种算法)