Title: Generate random numbers from 0 to 9. The probability of occurrence from 0 to 9 is required to decrease in sequence.
The general idea is to put 10 0s, 9 1s, 8 2s...2 8s, and 1 Put 9 into the array, then randomly generate the array subscript, and extract the number according to the subscript.
Second idea: Generate two random numbers from 0 to 9, and take the smaller one. This idea (proposed by the bracelet magic) is actually I don’t know what the principle is, but experiments have proved that it can indeed achieve the effect.
Verification method:
Program code
function fun(){
$num = rand(0,9); //Numbers within 10 are evenly distributed
$num2 = rand(0,9);
($num2<=$num) ? $return.=$num2 : $return.=$num;
return $return ;
}
function totalStr($haystack, $needle,$i = 0){//Check the number of times a certain character appears in the string
while(strpos($haystack,$needle) !== false) {
$haystack = substr($haystack, (strpos($haystack,$needle) + 1)); i=0 ;$i<=1000;$i++){
$str .= fun();
}
for ($i=0;$i<=9;$i++){
echo totalStr($str ,"$i")."n"; //The number of occurrences of 0-9
}
?>
Shortly after writing this piece, the bracelet magic algorithm has been optimizedFor details, see Below: Program codefunction getRand($min,$max) {
using using .
There is also a function written by another expert, which has strong mathematical ideas and is not easy to understand.
Program code
function getRandomByFactor($max,$factor=2){
$c = rand(0, pow($max,$factor));
return $max - ceil(pow($c,1/$factor));
}