Search code examples
optimizationdivide

Optimizing specific numbers to reach value


I'm trying to make a program, that when given specific values (let's say 1, 4 and 10), will try to get how much of each value is needed to reach a certain amount, say 19.
It will always try to use as many high values as possible, so in this case, the result should be 10*1, 4*2, 1*1. I tried thinking about it, but couldn't end up with an algorithm that could work...

Any help or hints would be welcome!


Solution

  • Here is a python solution that tries all the choices until one is found. If you pass the values it can use in descending order, the first found will be the one that uses the most high values as possible:

    def solve(left, idx, nums, used):
            if (left == 0):
                return True
            for i in range(idx, len(nums)):
                j = int(left / nums[idx])
                while (j > 0):
                    used.append((nums[idx], j))
                    if solve(left - j * nums[idx], idx + 1, nums, used):
                        return True
                    used.pop()
                    j -= 1
            return False      
    solution = []        
    solve(19, 0, [10, 4, 1], solution)
    print(solution) # will print [(10, 1), (4, 2), (1, 1)]