如何在PHP中创建指定数量的随机值,这些数量均等于指定数量? [英] How can I create a specified amount of random values that all equal up to a specified number in PHP?

查看:194
本文介绍了如何在PHP中创建指定数量的随机值,这些数量均等于指定数量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,假设我输入"10"作为值的数量,并输入"10000"作为总数.

For example, say I enter '10' for the amount of values, and '10000' as a total amount.

该脚本需要随机分配10个不同的数字,这些数字最多等于10000.不多也不少.

The script would need to randomize 10 different numbers that all equal up to 10000. No more, no less.

但是它也必须是动态的.像这样,有时我可能会输入'5'或'6'甚至是'99'作为值的总数,并且可以输入任何数字(最多10亿甚至更高)作为总数.

But it needs to be dynamic, as well. As in, sometimes I might enter '5' or '6' or even '99' for the amount of values, and any number (up to a billion or even higher) as the total amount.

我该怎么做?

编辑:我还应该提到所有数字都必须为正整数

I should also mention that all numbers need to be a positive integer

推荐答案

正确的答案非常简单.

想象一下一条白线,假设它长1000个单位.

Just imagine a white line, let's say 1000 units long.

您要使用红色标记将线分为十个部分.

You want to divide the line in to ten parts, using red marks.

非常简单,选择9个随机数,并在每个点上涂上红色标记.

VERY SIMPLY, CHOOSE NINE RANDOM NUMBERS and put a red paint mark at each of those points.

就这么简单.大功告成!

It's just that simple. You're done!

因此,算法为:

(1)选择0到1000之间的9个随机数 (2)将九个数字(一个零和一个1000)放入一个数组中 (3)对数组进行排序 (4)使用减法得到数组值之间的十个距离"

(1) pick nine random numbers between 0 and 1000 (2) put the nine numbers, a zero, and a 1000, in an array (3) sort the array (4) using subtraction get the ten "distances" between array values

您完成了.

(很明显,如果您想在最终集中不包含零,则在第(1)部分中,如果遇到冲突,只需重新选择另一个随机数.)

(Obviously if you want to have no zeros in your final set, in part (1) simply rechoose another random number if you get a collision.)

理想情况下,作为程序员,我们可以在脑海中看到"这样的视觉算法-尝试以视觉方式思考我们所做的一切!

Ideally as programmers, we can "see" visual algorithms like this in our heads -- try to think visually whatever we do!

脚注-对于所有阅读此内容的非程序员,请注意,这就像您学习计算机科学时所学的第一件事!"即,我对此一无所获,因为我偶然发现了该页面,所以我只是输入了答案.对我没有荣誉!

Footnote - for any non-programmers reading this, just to be clear pls note that this is like "the first thing you ever learn when studying computer science!" i.e. I do not get any credit for this, I just typed in the answer since I stumbled on the page. No kudos to me!

为记录起见,另一种通用方法(取决于所需的结果,是否要处理实数或整数,以及其他约束条件)也非常啊哈!"优雅的.您要做的就是:获得10个随机数.加起来非常简单,只需:将它们相乘或除以某个数字,这样总数就是所需的总数!就这么简单!

Just for the record another common approach (depending on the desired outcome, whether you're dealing with real or whole numbers, and other constraints) is also very "ah hah!" elegant. All you do is this: get 10 random numbers. Add them up. Remarkably simply, just: multiply or divide them all by some number, so that, the total is the desired total! It's that easy!

这篇关于如何在PHP中创建指定数量的随机值,这些数量均等于指定数量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆