# 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).

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

main:-
calculator([10, (+), 20, (-), 5], AnswerA),
calculator(['(', 10, (+), 20, (-), 5, ')', (*), 2], AnswerB),
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", );format("~d~n", )),
(stealthy(12), format("~d~n", );format("~d~n", )),
(stealthy(6), format("~d~n", );format("~d~n", )),
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