• 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));
        }
    }
    


  • 相关阅读:
    Docker和k8s的区别与介绍
    NFS网络文件系统详解
    NFS文件系统及搭建NFS共享服务
    Tomcat 端口配置,及原理详解
    svn使用教程
    buff/cache内存占用过多
    关于xcode:如何在Objective-C中使用符号断点获取参数
    iOS开发消除编译警告
    建模的能力才是一个人和核心能力
    android sutdio 环境搭建
  • 原文地址:https://www.cnblogs.com/fuhaots2009/p/3473279.html
Copyright © 2020-2023  润新知