Calculator with Two Buttons with Prolog


Below my #prolog solution for “Calculator with Two Buttons” proposed by challenge Nov 2020


?- 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 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.
	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 

Stable Marriage Problem with Prolog

2024-06-07 | #programming #prolog

My #prolog solution for Stable Marriage Problem proposed by challenge Jun 2024. Given n men and n women, where each person has ranked all members of the opposite sex in order of preference, marry the men and women together such that there are no two people of opposite sex who would both rather have each other than their current partners.

Continue reading 