【问题标题】:Divide a single number into a set of unique random numbers in PHP在PHP中将单个数字划分为一组唯一的随机数
【发布时间】:2019-04-20 23:22:36
【问题描述】:

我想从一个预先确定的单个数字开始,然后有多个随机数,当它们相加时,它们的总和就是我开始的数字。

例如,我有 100 个,但想要有 10 个随机数,当它们加在一起时,就等于 100。

以我有限的知识,我写了这个:

<?php
$_GET['total'] = $total;
$_GET['divided'] = $divided;
echo 'Starting with total: ' . $total;
echo '<br />';
echo 'Divided between: ' . $divided;
$randone = rand(1, $total);
$randonecon = $total - $randone;
echo '<br />';
echo 'First random number: ' . $randone;
$randtwo = rand(1, $randonecon);
$randtwocon = $total - $randtwo;
echo '<br />';
echo 'Second random number: ' . $randtwo;
?>

当然,这是失败的,因为我不知道如何将数字放在一个不让它们超过给定总数的数组中。

完全感谢Matei Mihai,它完成了!

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Randomize</title>
</head>

<body>

<?php

$_GET['total'] = $total;
$_GET['divided'] = $divided;


function generateRandomNumbers($max, $count)
{
$numbers = array();

    for ($i = 1; $i < $count; $i++) {
        $random = mt_rand(0, $max / ($count - $i));
        $numbers[] = $random;
        $max -= $random;
    }

    $numbers[] = $max;

    return $numbers;
}
echo '<pre>'; 
print_r(generateRandomNumbers($total, $divided));
echo '</pre>';

?>


<form id="form1" name="form1" method="get" action="">
  <label for="total">Total</label>
  <br />
  <input type="text" name="total" id="total" />
  <br /> 
   <label for="divided">Divided</label>
  <br />
  <input type="text" name="divided" id="divided" />
  <br />
  <input type="submit" value="Go!">
</form>
</body>
</html>

【问题讨论】:

  • 数字必须是整数吗?如果不是:只需添加您的数字,将您的目标数字除以总和,然后将所有数字乘以结果。
  • @FranzGleichmann 是的,它们必须是整数。
  • 好吧 - 然后,像我描述的那样缩放数字之后,你必须将它们四舍五入,其中一半必须向上舍入,一半必须向下舍入。

标签: php


【解决方案1】:

您可以尝试使用一个小函数来生成这些数字:

function generateRandomNumbers($max, $count)
{
    $numbers = [];

    for ($i = 1; $i < $count; $i++) {
        $random = mt_rand(0, $max / ($count - $i));
        $numbers[] = $random;
        $max -= $random;
    }

    $numbers[] = $max;

    shuffle($numbers);

    return $numbers;
}

echo '<pre>';
print_r(generateRandomNumbers(100, 10));
echo '</pre>';

该函数将生成一个数组,如:

Array
(
    [0] => 0
    [1] => 1
    [2] => 6
    [3] => 11
    [4] => 14
    [5] => 13
    [6] => 3
    [7] => 6
    [8] => 13
    [9] => 33
)

请注意,我可以直接使用 $random = mt_rand(0, $max) 而不是 $random = mt_rand(0, $max / ($count - $i));,但在后一种情况下,在结果数组中获得大量 0 的机会比第一种情况大。

【讨论】:

  • 这正是我想要的!太感谢了!我只发现代码在我替换之前不起作用: $numbers = []; with $numbers = array();
  • 是的..这是因为自 PHP 5.4 以来添加了短数组语法,所以您可能使用的是低于此的版本..
  • 我现在明白了!
  • 这很有帮助,但我有一个小转折,我们能否得到相同的结果而不在数组的任何项目中没有零?
猜你喜欢
  • 2012-06-05
  • 1970-01-01
  • 2012-02-02
  • 2018-03-18
  • 1970-01-01
  • 2013-07-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多