RabbitFarm

2025-06-29

The Weekly Challenge 327 (Prolog Solutions)

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

Part 1: Missing Integers

You are given an array of n integers. Write a script to find all the missing integers in the range 1..n in the given array.

Our solution is short and will be contained in a single file that has the following structure.

"ch-1.p" 1


missing integers 2

This problem is straightforward to solve using member/2.

missing integers 2 ⟩≡


missing_integers(L, Missing):-
length(L, Length),
findall(M, (
between(1, Length, M),
\+ member(M, L)
), Missing).

Fragment referenced in 1.

Sample Run
$ gprolog --consult-file prolog/ch-1.p 
| ?- missing_integers([1, 2, 1, 3, 2, 5], Missing). 
 
Missing = [4,6] 
 
yes 
| ?- missing_integers([1, 1, 1], Missing). 
 
Missing = [2,3] 
 
yes 
| ?- missing_integers([2, 2, 1], Missing). 
 
Missing = [3] 
 
yes 
| ?-
    

Part 2: MAD

You are given an array of distinct integers. Write a script to find all pairs of elements with minimum absolute difference (MAD) of any two elements.

The code required is fairly small, we’ll just need a single predicate and use GNU Prolog’s clp(fd) solver.

"ch-2.p" 3


compute MAD and find pairs 4

This is a good use of GNU Prolog’s clp(fd) solver. We set up the finite domain variables I and J to take values from the given list. We then find the minimum value of the differences and return all pairs having satisfied that constraint.

compute MAD and find pairs 4 ⟩≡


mad(L, Pairs):-
fd_max_integer(MAX_INT),
fd_domain([I, J], L),
fd_domain(D, 1, MAX_INT),
J #> I,
fd_minimize((D #= J - I, fd_labeling([D])), D),
findall(Pair, (fd_labeling([I, J]), Pair = [I, J]), Pairs).

Fragment referenced in 3.

Sample Run
$ gprolog --consult-file prolog/ch-2.p 
| ?- mad([4, 1, 2, 3], Pairs). 
 
Pairs = [[1,2],[2,3],[3,4]] 
 
yes 
| ?- mad([1, 3, 7, 11, 15], Pairs). 
 
Pairs = [[1,3]] 
 
yes 
| ?- mad([1, 5, 3, 8], Pairs). 
 
Pairs = [[1,3],[3,5]] 
 
yes 
| ?-
    

References

The Weekly Challenge 327
Generated Code

posted at: 15:28 by: Adam Russell | path: /prolog | permanent link to this entry