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

后端 未结 6 1996
庸人自扰
庸人自扰 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条回答
  •  轮回少年
    2021-01-02 08:55

    I believe the answer provided by @JoeBlow is largely correct, but only if the 'randomness' desired requires uniform distribution. In a comment on that answer, @Artefacto said this:

    It may be simple but it does not generate uniformly distributed numbers... 
    Itis biased in favor of numbers of size 1000/10 (for a sum of 1000 and 10 numbers).
    

    This begs the question which was mentioned previously regarding the desired distribution of these numbers. JoeBlow's method does ensure a that element 1 has the same chance at being number x as element 2, which means that it must be biased towards numbers of size Max/n. Whether the OP wanted a more likely shot at a single element approaching Max or wanted a uniform distribution was not made clear in the question. [Apologies - I am not sure from a terminology perspective whether that makes a 'uniform distribution', so I refer to it in layman's terms only]

    In all, it is incorrect to say that a 'random' list of elements is necessarily uniformly distributed. The missing element, as stated in other comments above, is the desired distribution.

    To demonstrate this, I propose the following solution, which contains sequential random numbers of a random distribution pattern. Such a solution would be useful if the first element should have an equal chance at any number between 0-N, with each subsequent number having an equal chance at any number between 0-[Remaining Total]:

    [Pseudo code]:
    Create Array of size N
    Create Integer of size Max
    Loop through each element of N Except the last one
        N(i) = RandomBetween (0, Max)
        Max = Max - N(i)
    End Loop
    N(N) = Max
    

    It may be necessary to take these elements and randomize their order after they have been created, depending on how they will be used [otherwise, the average size of each element decreases with each iteration].

提交回复
热议问题