Algorithm to find elements best fitting in a particular amount

后端 未结 5 923
遇见更好的自我
遇见更好的自我 2021-01-17 03:32

I\'m looking for an algorithm to solve the follwoing problem (I will explain it with an example):

Let say I have 10.000 $ available amount and following costs I can

5条回答
  •  猫巷女王i
    2021-01-17 03:34

    I designed an algorithm like this in java some weeks ago. I used a binary matrix with width N, where N is the number of different costs, and the height will be 2^N, giving us all possible combinations.

    So the first item would refer to the lowest cost in your case. Here is an example with 1000, 3000, 4000. (You can expand this, but I just want to show you how I did.)

    Width = N = 3

    Height = 2^N = 8

    0 0 0 = 0       +   0       +   0       =   0
    1 0 0 = 1000    +   0       +   0       =   1000
    0 1 0 = 0       +   3000    +   0       =   3000
    1 1 0 = 1000    +   3000    +   0       =   4000
    0 0 1 = 0       +   0       +   4000    =   4000
    1 0 1 = 1000    +   0       +   4000    =   5000
    0 1 1 = 0       +   3000    +   4000    =   7000
    1 1 1 = 1000    +   3000    +   4000    =   8000
    

    I had a list with the costs in it. And as i went down the matrix row by row, i just checked the list where there was a 1 on the matrix. Since the costs are sorted, the row i find that is equal or greater than the total amount will be the lowest possible.

    Tell me if you don't understand and i'll elaborate!

提交回复
热议问题