Hacker News new | ask | show | jobs
by cloogshicer 1515 days ago
Here's an example for a problem that's moderately difficult to do recursively, hard to do iteratively, and trivial in Prolog:

Given that you have the following coins, 1¢ (i.e. 1 cent or $0.01), 5¢, 10¢, 25¢, 50¢, how many different ways are there to give change for a dollar? For example, one way would be to give 2x50c, another would be to give 100x1c. How many are there total?

In most languages this is not super easy to do unless you're very comfy with recursion.

In Prolog the solution is basically (pseudocode):

    100 = a*50 + b*25 + c*10 + d*5 + e*1
and Prolog will just figure out all possible combinations for you.

The challenge with Prolog as far as I understand is making things fast.

2 comments

To be fair, that is not that difficult to accomplish in Python either:

    from ortools.sat.python.cp_model import *
    m = CpModel()
    a, b, c, d, e = [m.NewIntVar(0, 100, '') for _ in range(5)]
    m.Add(a*50 + b*25 + c*10 + d*5 + e*1 == 100)
    s = CpSolver()
    s.Solve(m)
    print([s.Value(x) for x in [a, b, c, d, e]])
Worth noting the entirety of the actual code would be

  :- use_module(library(clpfd)).
  
  main :-
    100 #= H*50 + Q*25 + D*10 + N*5 + P*1.
That's it.