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.

Enter your instance's address


More posts like this

Smart investment Problem with Prolog

2024-07-14 | #programming #prolog

Below my #prolog solution for Smart investment problem. It is a sample of Linear Programming using Prolog. A client of an investment firm has $10000 available for investment. He has instructed that his money be invested in particular stocks, so that no more than $5000 is invested in any one stock but at least $1000 be invested in each stock.

Continue reading 