php method to get random combinations from specified numbers

墨辰丷
Release: 2023-03-27 18:42:01
Original
1516 people have browsed it

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);

?>
Copy after login

##Output:

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

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template