• Hard 随机洗牌函数 @CareerCup


    第i个元素和index在[i,length-1]之间的一个数随机交换


    package Hard;
    
    import CtCILibrary.AssortedMethods;
    
    
    /**
     *
     * Write a method to shuffle a deck of cards. It must be a perfect shuffle - in other words, each 52! permutations of the deck has to be equally likely. Assume that you are given a random number generator which is perfect.
    
    译文:
    
    写一个随机洗牌函数。要求洗出的52!种组合都是等概率的。 也就是你洗出的一种组合的概率是1/(52!)。假设已经给你一个完美的随机数发生器。
     *
     */
    public class S18_2 {
    	/* Random number between lower and higher, inclusive */
        public static int rand(int lower, int higher) { 
                return lower + (int)(Math.random() * (higher - lower + 1));
        }        
        
        // 递归shuffle,先shuffle前i-1个元素,然后把第i个元素和前面的一个随机元素交换
        public static int[] shuffleArrayRecursively(int[] cards, int i) {
                if (i == 0) {
                	return cards;
                }
                
                /* shuffle elements 0 through index - 1 */
                shuffleArrayRecursively(cards, i - 1);
                int k = rand(0, i);                
                
                /* Swap element k and index */
                int temp = cards[k];
                cards[k] = cards[i];
                cards[i] = temp;
                
                /* Return shuffled array */
                return cards;
         }
       
        public static void swap(int[] a, int n, int m){
        	int tmp = a[n];
        	a[n] = a[m];
        	a[m] = tmp;
        }
        
        // 遍历数组,对每一个在index为i上的元素,和index在[i,n-1]之间的一个随机index选择的数交换
        public static void shuffleArrayInteratively(int[] cards) { 
        	for (int i = 0; i < cards.length; i++) { 
            	int k = rand(i, cards.length-1);		// 产生i到n-1间的随机数
                swap(cards, i, k);
            }
        }
        
        public static void main(String[] args) {
                int[] cards = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
                System.out.println(AssortedMethods.arrayToString(cards));
                shuffleArrayInteratively(cards);
                System.out.println(AssortedMethods.arrayToString(cards));
        }
    }
    


  • 相关阅读:
    关内存地址的分配
    关于URL
    linux的8小时差问题解决
    关于Scanner类
    域名后缀
    匿名对象用法
    final修饰符,多态,抽象类,接口
    二维数组的传参
    关于随机数
    面向对象编程的三大基本特征
  • 原文地址:https://www.cnblogs.com/fuhaots2009/p/3473279.html
Copyright © 2020-2023  润新知