zoukankan      html  css  js  c++  java
  • 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));
        }
    }
    


  • 相关阅读:
    session概述
    Flask实现登录功能【附完整Demo】(转)
    Python __repr__()方法:显示属性(转)
    Python使用SQLAlchemy连接数据库CRUD
    网络基础知识集合
    面向切面编程AOP
    SQL基础 insert table_name_1 (field1,field2,...) select value1,value2,... from table_name_2 ...
    java中char类型的变量为什么可以赋值为整型数字?
    iOS应用生命周期
    视图生命周期与视图控制器生命周期
  • 原文地址:https://www.cnblogs.com/fuhaots2009/p/3473279.html
Copyright © 2011-2022 走看看