Search code examples
pythonrandomnumbers

How to generate a certain number of random whole numbers that add up to a certain number and are at least a certain number or more?


I want to generate 10 whole numbers that add up to 40 and are in the range of 2-6.

For example:

2 + 6 + 2 + 5 + 6 + 2 + 2 + 6 + 3 + 6 = 40

Ten random numbers between 2 and 6 that add up to 40.


Solution

  • Given the relatively small search space, you could use itertools.combinations_with_replacement() to generate all possible sequences of 10 numbers between 2 and 6, save the ones that sum to 40 - then pick and shuffle one at random when requested:

    from itertools import combinations_with_replacement as combine
    from random import choice, shuffle
    
    sequences = [list(combo) for combo in combine(range(2, 6+1), 10) if sum(combo) == 40]
    
    def get_random_sequence_of_sum_40():
        seq = choice(sequences)
        shuffle(seq)
        return seq
    
    # ... later when you need random sequences of sum=40
    for i in range(10):
        rand_sequence = get_random_sequence_of_sum_40()
        print(f"The sum of {rand_sequence} is {sum(rand_sequence)}")
    

    Sample output:

    The sum of [6, 3, 4, 4, 3, 3, 4, 6, 5, 2] is 40
    The sum of [3, 3, 5, 3, 5, 5, 3, 3, 5, 5] is 40
    The sum of [3, 3, 6, 3, 4, 6, 3, 4, 4, 4] is 40
    The sum of [6, 6, 5, 3, 4, 3, 3, 2, 4, 4] is 40
    The sum of [5, 2, 2, 4, 4, 4, 5, 4, 4, 6] is 40
    The sum of [4, 4, 4, 3, 4, 4, 3, 6, 4, 4] is 40
    The sum of [4, 4, 5, 4, 2, 4, 4, 5, 5, 3] is 40
    The sum of [4, 2, 6, 2, 5, 6, 2, 5, 4, 4] is 40
    The sum of [3, 6, 3, 4, 3, 3, 4, 4, 6, 4] is 40
    The sum of [2, 2, 6, 2, 3, 5, 6, 4, 4, 6] is 40