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 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 | 这是我写的一个比较简单的抽奖算法,并没有很严谨,用于我自己写的wap文字游戏(美味小镇)上的随机食材,可以设定概率值 <?php /** * Created by PhpStorm. * User: tioncico * Date: 2017/12/9 0009 * Time: 14:50 */ class Rand { public $arr , $not_id , $if_repeat , $odds ; public function __construct( $arr , $if_repeat =1) { $this ->arr= $arr ; $this ->if_repeat= $if_repeat ; $this ->get_odds_array(); } function action( $num =1) { if (! $this ->arr||! $this ->odds){ return false; } $ids = array (); for ( $i = 0; $i < $num ; $i ++) { $res = $this ->get_rand( $this ->arr, $this ->odds); if ( $this ->if_repeat == 0) { if ( count ( $this ->arr)<= count ( $ids )){ return $ids ; } if (in_array( $res , $ids )) { $i --; } else { $ids [] = $res ; } } else { $ids [] = $res ; } } return $ids ; } public function get_odds_array( $arr = array ()) { $arr || $arr = $this ->arr; foreach ( $arr as $k => $va ) { if ( empty ( $va [ 'odds' ])){ $va [ 'odds' ]=100; } $odds [ $k ] = $va [ 'odds' ]; } $this ->odds = array_sum ( $odds ); return $this ; } public function add_arr( $arr = array ()){ $this ->arr = array_merge ( $this ->arr, $arr ); return $this ; } function remove_id( $arr = array (), $not_id = array ()){ $arr || $arr = $this ->arr; $not_id || $not_id = $this ->not_id; if ( empty ( $not_id )){ $this ->arr = $arr ; return $this ; } foreach ( $arr as $k => $va ){ foreach ( $not_id as $vo ){ if ( $k == $vo ){ unset( $arr [ $k ]); } } } $this ->arr = $arr ; return $this ; } //返回概率 function get_rand( $arr = array (), $odds =0) { $arr || $arr = $this ->arr; $odds || $odds = $this ->odds; //概率数组循环 $randNum = mt_rand(1, $odds ); $odd_num = 0; foreach ( $arr as $key => $va ) { if ( $randNum > $odd_num && $randNum <= $va [ 'odds' ] + $odd_num ) { return $arr [ $key ]; break ; } else { $odd_num += $va [ 'odds' ]; } } unset ( $proArr ); } } $arr = array ( array ( 'id' =>1, 'odds' =>100 //相对概率值 ), array ( 'id' =>2, 'odds' =>10 //相对概率值 ), array ( 'id' =>3, 'odds' =>200 //相对概率值 ), ) 调用方法 $a = new Rand( $arr ); $a ->action(1);
|
友情提示:垃圾评论一律封号...