Calculator with Two Buttons with Prolog
2020-11-14
Below my #prolog solution for “Calculator with Two Buttons” proposed by dmcommunity.org challenge Nov 2020
swipl nov2020.pl
?- shortest_path(0,5034,Path), length(Path,Len), findall(Op,member([_,Op,_], Path), Ops).
Path = [[0,+,1],[1,+,2],[2,+,3],[3,+,4],[4,+,5],[5,*,50],[50,*,500],[500,+,501],[501,+,502],[502,+,503],[503,*,5030],[5030,+,5031],[5031,+,5032],[5032,+,5033],[5033,+,5034]],
Len = 15,
Ops = [+,+,+,+,+,*,*,+,+,+,*,+,+,+,+].
Below my nov2020.pl script
:- use_module(library(clpfd)).
shortest_path(From, To, Path):-
From #>= 0,
shortest_path(From, To, 0, Path).
shortest_path(From, To, MaxDepth, Path):-
path(From, To, MaxDepth, Path),! .
shortest_path(From, To, MaxDepth, Path):-
MaxDepth1 #= MaxDepth + 1,
shortest_path(From, To, MaxDepth1, Path).
path(From, To, _MaxDepth, [[From, Op, To]]):-
step(From, Op, To).
path(From, To, MaxDepth, [[From, Op, Mid]|Path]):-
Mid #> From,
To #> Mid,
MaxDepth #> 0,
Depth1 #= MaxDepth - 1,
step(From, Op, Mid),
path(Mid, To, Depth1, Path).
step(N,*, M):-
M #= N * 10.
step(N,+,M):-
M #= N + 1.