php 中獎機率演算法實現代碼

來源:互聯網
上載者:User
實現代碼:

<?php/** *php 中獎機率演算法 * */function get_zj( $jp ,$glname = 'gl'){    $sum = 0;    foreach($jp as $k =>$v ){        $sum += $v[$glname];    }      $R = rand(1,$sum);//擷取隨機數      foreach( $jp as $k => $v){        if( $R <= $v[$glname] ){            return $v;        }        $R = $R - $v[$glname] ;    }  }    //使用方法//類比一個從資料庫中讀取的 中獎配置  gl 為 中獎的機率 //例如array( 'gl' => 10 , 'title' => '一等獎');的中獎機率 = 10 / (10+20+30+40)$jp = array();$jp[] = array( 'gl' => 10 , 'title' => '一等獎');$jp[] = array( 'gl' => 20 , 'title' => '二等獎');$jp[] = array( 'gl' => 30 , 'title' => '三等獎');$jp[] = array( 'gl' => 40 , 'title' => '未中獎');    //調用 中獎機率函數 //返回中獎 資訊數組 例如:array( 'gl' => 10 , 'title' => '一等獎');$zj = get_zj( $jp );  //輸出數組var_dump($zj);

使用方法
類比一個從資料庫中讀取的 中獎配置 gl 為 中獎的機率
例如array( 'gl' => 10 , 'title' => '一等獎');的中獎機率 = 10 / (10+20+30+40)
$jp = array();
$jp[] = array( 'gl' => 10 , 'title' => '一等獎');
$jp[] = array( 'gl' => 20 , 'title' => '二等獎');
$jp[] = array( 'gl' => 30 , 'title' => '三等獎');
$jp[] = array( 'gl' => 40 , 'title' => '未中獎');

調用 中獎機率函數
返回中獎 資訊數組 例如:array( 'gl' => 10 , 'title' => '一等獎');

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.