There are 25 pieces to vote, one to vote for 16, and one to vote only once per piece. In front of a programmer stabbed blunder, forgot to put the vote in the library, there are 200 user-generated voting sequence is empty. So how would you fill this blunder?
<?PHP/** array unique_rand (int $min, int $max, int $num) * Generate a certain number of distinct random numbers * $min and $max: Specify the range of random numbers * $num: Specify the number of builds*/functionUnique_rand ($min,$max,$num) { $count= 0; $return=Array(); while($count<$num) { $return[] =Mt_rand($min,$max); $return=Array_flip(Array_flip($return)); $count=Count($return); } Shuffle($return); return $return;}$arr= Unique_rand (1, 25, 16);Sort($arr);$result= ' '; for($i= 0;$i<Count($arr);$i++){ $result.=$arr[$i].‘,‘;}$result=substr($result, 0,-1);Echo $result;?>
Add a few notes:
- The Mt_rand () function is used when generating random numbers. The average speed of this function generates random numbers four times times faster than Rand ().
- Removing duplicate values in the array uses the "rollover" method, which uses Array_flip () to swap the array's key and value two times. This approach is much faster than using Array_unique ().
- Before returning an array, use Shuffle () to assign a new key name to the group, guaranteeing that the key name is 0-n consecutive digits. If you do not do this, you may cause the key name to be discontinuous when you delete duplicate values, causing the traversal to be cumbersome.
PHP CodeBase: Generate n non-repeating random numbers