php 抽奖类的

很简单的思路。有点贪心的想法

<?php
	header("Content-type: text/html; charset=utf-8");
	require("lottery.php");
	$arr = array( 
	    '0' => array('id'=>0,'prize'=>'100','v'=>1), 
	    '1' => array('id'=>1,'prize'=>'50','v'=>2), 
	    '2' => array('id'=>2,'prize'=>'20','v'=>3), 
	    '3' => array('id'=>3,'prize'=>'10','v'=>4), 
	    '4' => array('id'=>4,'prize'=>'5','v'=>5), 
	    '5' => array('id'=>5,'prize'=>'下次没准就能中哦','v'=>985)
	);
	usort($arr,'compare');
	var_dump($arr);
	for ($i=0; $i < 100; $i++){
		$test = new lottery($arr);
		$rid = $test->calc();
		echo $arr[$rid]['prize']."<HR>";
	}
	function compare($a,$b){
		if($a['v'] == $b['v']) return $a['id']>$b['id']?1:-1;
		return $a['v']>$b['v']?1:-1;
	}
?>



<?php
	class lottery{
		private $arr;
		private $rid;
		private $sum;
		function __construct($arr){
			foreach ($arr as $key => $v) {
				$this->arr[$v['id']]=$v['v'];
			}
			$this->sum = array_sum($this->arr);
		}
		function  __destruct(){
			unset($this->arr);
			unset($this->rid);
			unset($this->sum);
		}
		public function calc(){
			/*
			  随机取到的数num  按id顺序 和v 进行对比,如果小于v  那么就返回key 否则sum 就减去 V。
	          每减去一个v, sum 就越来越接近 Vmax ,当到一个临界值的时候 sum <= Vmax 恒为真
	       	  其实就是个贪心思想而已.
	       	  当Vmax 越大的时候,抽不中奖的概率就越大。
			*/
			foreach ($this->arr as $key => $v) {
				$num = mt_rand(1,$this->sum);
				if($num <= $v){
					$this->rid = $key;
					break;
				}else{
					$this->sum -= $v;
				}
			}
			return $this->rid;
		}
	}
?>
相关文章
相关标签/搜索