Home >Backend Development >PHP Tutorial >php method to get random combinations from specified numbers

php method to get random combinations from specified numbers

jacklove
jackloveOriginal
2018-06-08 23:31:581821browse

For example: Given the number 100, you need to randomly obtain 3 combinations of this number, such as 70, 20, 10

The code is as follows:

<?php/**
 * 获取指定数字的随机数字组合
 * @param  Int    $var 数字
 * @param  Int    $num 组合这个数字的数量
 * @return Array
 */function getNumGroups($var, $num){
    // 数量不正确
    if($var<$num){        return array();
    }    $total = 0;    $result = array();    for($i=1; $i<$num; $i++){        $tmp = mt_rand(1, $var-($num-$i)-$total);        $total += $tmp;        $result[] = $tmp;
    }    $result[] = $var-$total;    return $result;
}// demo$result = getNumGroups(100, 3);
print_r($result);?>

Output:

Array(
    [0] => 42
    [1] => 25
    [2] => 33)

This article explains how PHP obtains random combinations from specified numbers. For more related content, please pay attention to the PHP Chinese website.

Related recommendations:

Interpretation of php's PDO connection to the database related content

How to implement recursive acquisition through php code The value of a specified key in an array

Reading a 1G file size through PHP

The above is the detailed content of php method to get random combinations from specified numbers. For more information, please follow other related articles on the PHP Chinese website!

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