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

php method to get random combinations from specified numbers

墨辰丷
墨辰丷Original
2018-05-24 10:21:531479browse

This article mainly introduces the method of obtaining random combinations from specified numbers in PHP. Interested friends can refer to it. I hope it will be helpful to everyone.

For example: Given the number 100, you need to randomly obtain 3 combinations that make up 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
)

The above is the entire content of this article, I hope it will be helpful to everyone's study.


Related recommendations:

Php, MySQL environment configuration

PHPFunction curl request-fetch page/interface test

PHPBasic function summary

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