创建一个加起来为一定数量的随机整数数组

时间:2021-11-27 21:44:56

I want to make an array of 7 integers, each of which is a random value between 2 and 5. That's easy, but I want to make it so the total sum of these integers must be 20. Any ideas?

我想制作一个包含7个整数的数组,每个整数都是2到5之间的随机值。这很容易,但我想这样做,所以这些整数的总和必须是20.任何想法?

4 个解决方案

#1


Generate 6 random numbers.

生成6个随机数。

Calculate the sum of these numbers.

计算这些数字的总和。

if the sum is larger than 19 or smaller than 15: start over.

如果总和大于19或小于15:重新开始。

7th number is 20 - sum

第7个数字是20 - 总和

#2


Start with an array of seven twos. You now have a sum of 14. Add one to a random slot in the array six times, taking care to not overflow a value to more than five:

从七个二十一开始。您现在有一个总和14.将数组添加到数组中的一个随机插槽六次,注意不要将值溢出到五个以上:

arr = {2, 2, 2, 2, 2, 2, 2}
n = 6

while n > 0:
    m = random(7)
    if arr[m] < 5:
        arr[m]++
        n--

#3


Brute force: keep recalculating until you get an answer

暴力:继续重新计算,直到你得到答案

import random

def random_sums_to(lower, top, n, sums_to):
    a = [random.randint(lower, top) for _ in range(n)]
    if sum(a) != sums_to:
        return random_sums_to(lower, top, n, sums_to)
    return a

print random_sums_to(2, 5, 7, 20)

#4


If you need to make sure to get the exact same distribution at each position proceed as follows:

如果您需要确保在每个位置获得完全相同的分布,请按以下步骤操作:

  1. Calculate a list with all possible sequences
  2. 计算包含所有可能序列的列表

  3. Pick one of these sequences randomly
  4. 随机选择其中一个序列

#1


Generate 6 random numbers.

生成6个随机数。

Calculate the sum of these numbers.

计算这些数字的总和。

if the sum is larger than 19 or smaller than 15: start over.

如果总和大于19或小于15:重新开始。

7th number is 20 - sum

第7个数字是20 - 总和

#2


Start with an array of seven twos. You now have a sum of 14. Add one to a random slot in the array six times, taking care to not overflow a value to more than five:

从七个二十一开始。您现在有一个总和14.将数组添加到数组中的一个随机插槽六次,注意不要将值溢出到五个以上:

arr = {2, 2, 2, 2, 2, 2, 2}
n = 6

while n > 0:
    m = random(7)
    if arr[m] < 5:
        arr[m]++
        n--

#3


Brute force: keep recalculating until you get an answer

暴力:继续重新计算,直到你得到答案

import random

def random_sums_to(lower, top, n, sums_to):
    a = [random.randint(lower, top) for _ in range(n)]
    if sum(a) != sums_to:
        return random_sums_to(lower, top, n, sums_to)
    return a

print random_sums_to(2, 5, 7, 20)

#4


If you need to make sure to get the exact same distribution at each position proceed as follows:

如果您需要确保在每个位置获得完全相同的分布,请按以下步骤操作:

  1. Calculate a list with all possible sequences
  2. 计算包含所有可能序列的列表

  3. Pick one of these sequences randomly
  4. 随机选择其中一个序列