Home  >  Article  >  Backend Development  >  Analysis of the method of generating non-repeating random numbers in php

Analysis of the method of generating non-repeating random numbers in php

WBOY
WBOYOriginal
2016-07-25 08:52:52962browse
  1. function get_randoms($min,$max,$num){
  2. $count = 0;
  3. $res = array();
  4. while($count<$num){
  5. $res [] = mt_random($min,$max);
  6. $res = array_flip(array_flip($res));
  7. $count = count($res);
  8. }
  9. return $res;
  10. }
  11. $result = get_randoms (1,60,10);
  12. ?>
Copy code

Here he uses $count to get the number of result arrays, and he makes the number of result arrays less than the target number in the while loop. Through this, we get $count which is an array of target number. (bbs.it-home.org Scripting School) During this period, in each cycle, through mt_random($min,$max), a value within the range is randomly obtained and stored in the array $res, and then through two key-value exchanges, that is, through the uniqueness of the array key, Make sure there is no repetition.

After I read the code of this logic, I couldn't help but think deeply. What would you do if you didn't know the array_filp function? To put it bluntly, it uses the uniqueness of the key so that there will be no duplication of random numbers. So can we simplify this problem?

Code:

  1. function get_randoms($min,$max,$num){
  2. $count = 0;
  3. $res = array();
  4. while($count<$num){
  5. $ key = mt_random($min,$max);
  6. $res[$key] = $key;
  7. $count = count($res);
  8. }
  9. return $res;
  10. }
  11. $result = get_randoms(1,60 ,10);
  12. ?>
Copy the code

This solves this problem completely through the uniqueness of the array key. array_flip will not be used at all.

Summary: 1. Because PHP provides a large number of built-in functions, their execution efficiency is very high. (bbs.it-home.org Programmer’s Home) When you encounter a problem, try to use it to solve the problem as much as possible. This is convenient and fast.

2. PHP provides a large number of built-in functions, and the execution efficiency is also very high. However, although the efficiency is high, it still takes time to execute. When you encounter a problem, don't do it blindly. You can first see the essence of the solution so that you can implement it skillfully.



Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn