简体   繁体   中英

Algorithm to find combinations of sets of numbers that add up to equal or greater than X

So the problem I'm trying to solve is that I would like to find the possible combinations of numbers in the sets that I have that add up to 400

I have 6 numbers in set 1 that can be any of the following: [0, 6, 8, 12, 16, 30] and another 6 numbers in set 2 that can be any of the following: [0, 16, 20, 25, 32, 40, 50]

I recognize that since all I'm concerned about is the sum, order should not matter, but I'm not sure how I'd actually approach the set up. Would it make sense to approach it changing 1 number at a time, decreasing in value for each iteration, then once I hit a total under 400 breaking that run and moving to the next number? For example: If I started with [30,30,30,30,30,30][50,50,50,50,50,50] decreasing in the last index, once I hit [30,30,30,30,30,30][50,50,50,32,20,16] the rest of the iterations focused on that 11th column (there's only one more and that's when its equal to 16) could be ignored because they only decrease. Or is there a more logical method to approach this with?

You can order both sets, set a loop for each num in the first set to be summed to every num in the second but you can stop once your sum fails to be over 400.

Something like

numbers_whose_sums_are_bigger_than_the_number_in_question = []
for x in ordered_set_a: 
    sum = 401
    while sum > 400:
        for y in ordered_set_b:
            sum = x + y
            if sum > 400:
                numbers_whose_sums_are_bigger_than_the_number_in_question.append([x,y])
print(numbers_whose_sums_are_bigger_than_the_number_in_question)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM