- Function get_randoms ($ min, $ max, $ num ){
- $ Count = 0;
- $ Res = array ();
- While ($ count <$ num ){
- $ Res [] = mt_random ($ min, $ max );
- $ Res = array_flip ($ res ));
- $ Count = count ($ res );
- }
- Return $ res;
- }
- $ Result = get_randoms (1, 60, 10 );
- ?>
Here he uses the number of $ count result arrays. in the while loop, the number of result arrays is smaller than the number of targets. In this way, $ count is an array of the number of targets. (Bbs.it-home.org script School) during each cycle, through mt_random ($ min, $ max), a random value in the interval, stored in the array $ res, then, the key-value is exchanged twice, that is, the uniqueness of the array key makes the key unique.
After reading the logic code, I can't help but think deeply. if you don't know the array_filp function, what do you do? To put it bluntly, the uniqueness of the key is used so that the random number will not be repeated. So can we simplify this problem?
Code:
- Function get_randoms ($ min, $ max, $ num ){
- $ Count = 0;
- $ Res = array ();
- While ($ count <$ num ){
- $ Key = mt_random ($ min, $ max );
- $ Res [$ key] = $ key;
- $ Count = count ($ res );
- }
- Return $ res;
- }
- $ Result = get_randoms (1, 60, 10 );
- ?>
In this way, the uniqueness of the array key solves this problem. Array_flip is not used at all.
Conclusion: 1. because php provides a large number of built-in functions, their execution efficiency is very high. (Bbs.it-home.org programmer's house) when encountering problems, try to use it to solve the problem. This is convenient and fast.
2. php provides a large number of built-in functions with high execution efficiency. However, although the efficiency is high, it still takes time to execute them. When you encounter a problem, do not blindly do it. First, you can see the essence of the solution to facilitate the clever implementation of it. |