RabbitFarm

2021-12-19

The Weekly Challenge 143 (Prolog Solutions)

The examples used here are from the weekly challenge problem statement and demonstrate the working solution.

Part 1

_You are given a string, $s, containing mathematical expression. Write a script to print the result of the mathematical expression. To keep it simple, please only accept + - * ().

Solution


:-initialization(main). 

expression(Answer) --> term(Answer).
expression(Answer) --> term(Answer0), [(+)], expression(Answer1), {Answer is Answer0 + Answer1}.
expression(Answer) --> term(Answer0), [(-)], expression(Answer1), {Answer is Answer0 - Answer1}.

term(Answer) --> operand(Answer).
term(Answer) --> operand(Answer0), [(*)], term(Answer1), {Answer is Answer0 * Answer1}.
term(Answer) --> operand(Answer0), [(/)], term(Answer1), {Answer is Answer0 / Answer1}.

operand(X) --> [X], {number(X)}.
operand(Answer) --> ['('],  expression(Answer), [')'].

calculator(Expression, Answer):-
    phrase(expression(Answer), Expression). 

main:-
    calculator([10, (+), 20, (-), 5], AnswerA),
    write(AnswerA), nl,
    calculator(['(', 10, (+), 20, (-), 5, ')', (*), 2], AnswerB),
    write(AnswerB), nl,
    halt.  

Sample Run


$ gplc prolog/ch-1.p 
$ prolog/ch-1   
25
50

Notes

This is the sort of problem which is just so clean and straightforward to implement in Prolog. A DCG is used to describe the expected infix notation of the calculator and that pretty much takes care of it.

Part 2

You are given a positive number, $n. Write a script to find out if the given number is a Stealthy Number.

Solution


:-initialization(main). 

stealthy(N):-
    fd_domain(S, 2, N),
    fd_domain(T, 2, N),
    fd_domain(U, 2, N),
    fd_domain(V, 2, N),
    S * T #= N,
    U * V #= N,
    S + T #= U + V + 1,
    fd_labeling([S, T, U, V]).

main:-
    (stealthy(36), format("~d~n", [1]);format("~d~n", [0])),
    (stealthy(12), format("~d~n", [1]);format("~d~n", [0])),
    (stealthy(6), format("~d~n", [1]);format("~d~n", [0])),
    halt. 

Sample Run


$ gplc prolog/ch-2.p 
$ prolog/ch-2  
1
1
0

Notes

Much like Part 1 of this weeks challenge Prolog really shines in terms of providing a short clean solution. Here we describe the desired property in terms of finite domain variables and Prolog let's us know if any values exist which match those constraints.

References

Challenge 143

posted at: 19:56 by: Adam Russell | path: /prolog | permanent link to this entry