Hein (fub) wrote,
Hein
fub

  • Mood:

I am the god of programs that play Krypto!

So here it is!



?- formula([3,15,17,20,1],3).

operation("+").
operation("-").
operation("/").
operation("x").

do_operation(A, "+", B, A+B).
do_operation(A, "-", B, A-B).
do_operation(A, "/", B, A/B).
do_operation(A, "x", B, A*B).

formula(L, Target) :-
  findall(X, perm(L, X), PermList),
  process_permutation(PermList, Target).

process_permutation([], _).
process_permutation([H|_], Target) :-
  formula_acc(H, 0, [], Formula, Target),
  write("Formula: "), pretty_print(Formula),
  write("for a total of "), write(Target), nl.
process_permutation([_|T], Target) :-
  process_permutation(T, Target).

formula_acc([], Total, Formula, Formula, Target) :-
  Total =:= Target.
formula_acc([H|T], 0, [], Formula, Total) :-
  formula_acc(T, H, [H], Formula, Total).
formula_acc([H|T], CurTotal, CurFormula, Formula, Total) :-
  CurTotal > 0,
  operation(O), do_operation(CurTotal, O, H, Result),
  append(CurFormula, [O,H], NewFormula),
  formula_acc(T, Result, NewFormula, Formula, Total).

append([], L, L).
     append([H| L1], L2, [H| L3]) :- 
          append(L1, L2, L3).

pretty_print([]) :- nl.
pretty_print([H|T]) :-
  write(H), write(" "), pretty_print(T).

perm(List,[H|Perm]):-delete(H,List,Rest),perm(Rest,Perm).
perm([],[]).

delete(X,[X|T],T).
delete(X,[H|T],[H|NT]):-delete(X,T,NT).


It works in Strawberry Prolog, and prints out the first solution. If you want all solutions, just add process_permutation(T, Target). after write("for a total of "), write(Target), nl.

OK, what can I say? I'm a geek, and I love stuff like this.
Subscribe

  • Friday Five & GenX

    What toys were popular when you were a kid? This was the height of the 80’s, the time of cartoons on TV pushing toys. They were expensive…

  • Small update

    Wow, I haven’t posted in over a month here. And yet I still don’t feel like I have much to say. Let’s see… – The…

  • Mock Chicken

    The Judge Dredd comics are an interesting artefact of the 1980s: it’s what British comic writers thought how the US urban landscape would…

  • Post a new comment

    Error

    Anonymous comments are disabled in this journal

    default userpic

    Your reply will be screened

    Your IP address will be recorded 

  • 0 comments