I know that there is a function in PCP for generating random numbers. mt_rand, for example. But I need a little bit of that. I need, say, 1000 random numbers in the range (1-5. I mean 1, 2, 3, 4, 5). So that in the end, after the execution of the cycle, there was an equal amount. That is 200 times the number is 1, 200 - 2, 200 - 3, etc., but in a random sequence. So I was sure that the groups are either equal or very close to this. How to implement it?

  • If you do not pay attention to the distribution, you can take a list of 1000 numbers and randomly delete one by one (one of 1000, one of 999, one of 998, etc.). - alexlz
  • 2
    put these numbers in an array 200 times and then shuffle (); what is the problem ? (or vice versa, put 200 times the array of all the options and mix again) - zb '
  • one
    @jackair, If you are given an exhaustive answer, mark it as correct (click on the check mark next to the selected answer). - Nicolas Chabanovsky

3 answers 3

$arr = array(); $max_items = 1000; // Длина массива $min_number = 0; // Любое число $max_number = 20; // Генерация от min_number до этого числа for($i = 0, $j = $min_number; $i < $max_items; $i++) { if ($j > $max_number) $j = $min_number; $arr[] = $j; $j++; } shuffle($arr); print_r($arr); 
  • not, the point is that 1000 is for example. in practice, the numbers will be orders of magnitude more!) and in general this number is dynamic - jackair
  • @jackair, corrected. - dlarchikov

Here is my flexible implementation of your code)
Distribute evenly the number of attacks.

$ min // minimum number
$ max // maximum number
$ sum // number of turns
$ eqv // distribute the number of matches by one value (+ we reduce to an integer)

 function evenRand($min,$max,$sum){ $eqv = floor($sum / (($max-$min)+1)); $array = array(); for($i=0;$i<$sum;$i++){ $rand = mt_rand($min,$max); if($array[$rand] != $eqv){ $array[$rand]+=1; } else { $sum+=1; } } echo $array[2]; // Для проверки. Выведет количество выпавших "2" } evenRand(1,5,1000); // = ровно 200 выпадов на каждое число 
    1. You generate an array from 1 to 5, and so 200 times [1,2,3,4,5,1,2,3,3,5,5,2,2, ..., 5]
    2. Sort it randomly