Home > Enterprise >  Python: I need to randomly generate 6 numbers who's sum adds up to a specified number
Python: I need to randomly generate 6 numbers who's sum adds up to a specified number

Time:08-22

I am attempting to create a new character which has a randomly generated level. This character has 8 attributes, I need to randomly generate those 8 attributes so that their sum is equal to the generated level, plus 8. So far I have this..

    level = random.randint(1, 30) * 5
    base = int(0.1 * level)
    stats = []

    *****

    health = int(atts[0])
    strength = int(atts[1])
    agility = int(atts[2])
    willpower = int(atts[3])
    charisma = int(atts[4])
    intelligence = int(atts[5])
    speed = int(atts[6])
    luck = int(atts[7])

I am looking to replace the asterisks with the code which would generate the 8 random integers that add up to the level 8, and append them to "atts." Based on other answers I have seen to similar questions, I tried the following which gets me the 8 integers I need, but I'm struggling with figuring out how to make them add up to the level.

    for i in range(0, 8):
       arr = random.randint(base, level)
       atts.append(arr)

CodePudding user response:

How about you just pick a random attribute, increment it by one, and then repeat that level 8 times? Then you don't have to worry about generating numbers that satisfy your criteria:

from random import choice

level = 4
points = level   8

attribute_names = (
    "health",
    "strength",
    "agility",
    "willpower",
    "charisma",
    "intelligence",
    "speed",
    "luck"
)

attributes = dict.fromkeys(attribute_names, 0)

for _ in range(points):
    key = choice(attribute_names)
    attributes[key]  = 1

for key, value in attributes.items():
    print(f"{key}: {value}")

Output:

health: 2
strength: 0
agility: 3
willpower: 3
charisma: 2
intelligence: 0
speed: 0
luck: 2

CodePudding user response:

def get_random_numbers_that_add_up_to(target=80, max_val=10, how_many=8):
    ints = []
    for i in range(how_many - 1):
        ints.append(
            random.randint(0, max_val)
        )
    sub_total = sum(ints)
    final_attribute = 40 - sub_total
    ints.append(final_attribute)
    return ints

This function will pick how_many random integers between 0 and max_value, and set the last to the diff between the sum of the existing ones and the target value.

You'll need to tune the args to make sure you don't go over target, otherwise the final attribute would be negative.

  • Related