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

  • Update

    Wow, what with one thing and another, I haven’t posted on here in a month! Time to give a short update on what’s been happening.…

  • Final RPG-a-Day: Thank

    The last prompt for RPG-a-Day this year is ‘Thank’. If you have read every entry of this year’s RPG-a-Day, then I certainly…

  • Next-to-last RPG-a-Day: Mention

    Today’s prompt is ‘Mention’. I guess this is where I mention people I look up to, or websites I frequent? Ok, here’s…

  • 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