How can I create a specified amount of random values that all equal up to a specified number in PHP?

后端 未结 6 2000
庸人自扰
庸人自扰 2021-01-02 08:18

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

The script would need to randomize 10 different numbers that all equal up

6条回答
  •  萌比男神i
    2021-01-02 08:43

    Update: @Joe Blow has the perfect answer. My answer has the special feature of generating chunks of approximately the same size (or at least a difference no bigger than (10000 / 10)), leaving it in place for that reason.

    The easiest and fastest approach that comes to my mind is:

    • Divide 10000 by 10 and store the values in an array. (10 times the value 10000)

    • Walk through every one of the 10 elements in a for loop.

    • From each element, subtract a random number between (10000 / 10).

    • Add that number to the following element.

    This will give you a number of random values that, when added, will result in the end value (ignoring floating point issues).

    Should be half-way easy to implement.

    You'll reach PHP's maximum integer limit at some point, though. Not sure how far this can be used for values towards a billion and beyond.

提交回复
热议问题