Find out which combinations of numbers in a set add up to a given total

后端 未结 8 1111
旧时难觅i
旧时难觅i 2020-12-01 08:11

I\'ve been tasked with helping some accountants solve a common problem they have - given a list of transactions and a total deposit, which transactions are part of the depos

相关标签:
8条回答
  • 2020-12-01 08:53

    Not a super efficient solution but heres an implementation in coffeescript

    combinations returns all possible combinations of the elements in list

    combinations = (list) ->
            permuations = Math.pow(2, list.length) - 1
            out = []
            combinations = []
    
            while permuations
                out = []
    
                for i in [0..list.length]
                    y = ( 1 << i )
                    if( y & permuations and (y isnt permuations))
                        out.push(list[i])
    
                if out.length <= list.length and out.length > 0
                    combinations.push(out)
    
                permuations--
    
            return combinations
    

    and then find_components makes use of it to determine which numbers add up to total

    find_components = (total, list) ->
        # given a list that is assumed to have only unique elements
    
            list_combinations = combinations(list)
    
            for combination in list_combinations
                sum = 0
                for number in combination
                    sum += number
    
                if sum is total
                    return combination
            return []
    

    Heres an example

    list = [7.2, 3.3, 4.5, 6.0, 2, 4.1]
    total = 7.2 + 2 + 4.1
    
    console.log(find_components(total, list)) 
    

    which returns [ 7.2, 2, 4.1 ]

    0 讨论(0)
  • 2020-12-01 08:55

    If I understand your problem correctly, you have a set of transactions, and you merely wish to know which of them could have been included in a given total. So if there are 4 possible transactions, then there are 2^4 = 16 possible sets to inspect. This problem is, for 100 possible transactions, the search space has 2^100 = 1267650600228229401496703205376 possible combinations to search over. For 1000 potential transactions in the mix, it grows to a total of

    10715086071862673209484250490600018105614048117055336074437503883703510511249361224931983788156958581275946729175531468251871452856923140435984577574698574803934567774824230985421074605062371141877954182153046474983581941267398767559165543946077062914571196477686542167660429831652624386837205668069376

    sets that you must test. Brute force will hardly be a viable solution on these problems.

    Instead, use a solver that can handle knapsack problems. But even then, I'm not sure that you can generate a complete enumeration of all possible solutions without some variation of brute force.

    0 讨论(0)
提交回复
热议问题