• 洗牌算法


     1 <?php
     2     #洗牌算法,假设共有n张各不相同的牌
     3     #易知n张牌共有n!中排列方法,洗牌算法关键在于让这n!排列方法出现的概率相等
     4 
     5     function swap(&$arr, $i, $j) {
     6         $temp = $arr[$i];
     7         $arr[$i] = $arr[$j];
     8         $arr[$j] = $temp;
     9     }
    10 
    11     function shuffle_poker(&$arr) {
    12         $len = count($arr);
    13         for ($i = 0; $i < $len; $i++) {
    14             $j = rand() % ($len - $i) + $i; #关键部分,每次选取rand() % (n - i) + i的一张牌和i交换
    15             swap($arr, $i, $j);
    16         }
    17     }
    18 
    19     for ($i = 0; $i < 54; $i++) {
    20         $arr[] = $i;
    21     }
    22 
    23     print_r($arr);
    24 
    25     echo "<br>";
    26 
    27     shuffle_poker($arr);
    28 
    29     print_r($arr);
    30 ?>

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

  • 相关阅读:
    DI的3种实现方式
    spring ioc的实现方式
    异常:This application has no explicit mapping for /error, so you are seeing this as a fallback.
    maven项目 集成SSM框架
    org.xml.sax.SAXParseException错误
    Redis在web中的应用
    上传下载文件实例(vsftp服务器+nginx)
    Redis的安装与启动
    修饰器-2
    修饰器练习
  • 原文地址:https://www.cnblogs.com/zemliu/p/2698557.html
Copyright © 2020-2023  润新知