RabbitFarm
2023-11-11
The Weekly Challenge 242 (Prolog Solutions)
The examples used here are from the weekly challenge problem statement and demonstrate the working solution.
Part 1
You are given two arrays of integers. Write a script to find out the missing members in each other arrays.
Solution
missing(L, E, Member):-
(member(E, L), Member = nil);
(\+ member(E, L), Member = E).
missing_members([List1, List2], [Missing1, Missing2]):-
maplist(missing(List2), List1, Missing1Nil),
delete(Missing1Nil, nil, Missing1),
maplist(missing(List1), List2, Missing2Nil),
delete(Missing2Nil, nil, Missing2).
Sample Run
% gprolog --consult-file prolog/ch-1.p
| ?- missing_members([[1, 2, 3], [2, 4, 6]] ,Missing).
Missing = [[1,3],[4,6]] ?
yes
| ?- missing_members([[1, 2, 3, 3], [1, 1, 2, 2]] ,Missing).
Missing = [[3,3],[]] ?
yes
| ?- missing_members([[1, 2, 3, 3], [1, 1, 2, 2]], Missing), maplist(sort, Missing, MissingNoDuplicates).
Missing = [[3,3],[]]
MissingNoDuplicates = [[3],[]] ?
yes
| ?-
Notes
missing/3
is used in a maplist/3
to determine which elements are missing from an
array. If they are not missing a nil
is set for it. By deleting the nil
elements
all that remain are the ones that are missing. This solution doesn't itself remove
duplicate missing elements that are identified. That said, as you can see in the example
above that can be added, say, using sort/2
.
Part 2
You are given n x n binary matrix. Write a script to flip the given matrix as below.
Solution
flip(B, F):-
F is \ B /\ 1.
flip_matrix([], []).
flip_matrix([Row|Matrix], [RowFlipped|MatrixFlipped]):-
reverse(Row, RowReversed),
maplist(flip, RowReversed, RowFlipped),
flip_matrix(Matrix, MatrixFlipped).
Sample Run
% gprolog --consult-file prolog/ch-2.p
| ?- flip_matrix([[1, 1, 0], [1, 0, 1], [0, 0, 0]], FlippedMatrix).
FlippedMatrix = [[1,0,0],[0,1,0],[1,1,1]]
yes
| ?- flip_matrix([[1, 1, 0, 0], [1, 0, 0, 1], [0, 1, 1, 1], [1, 0, 1, 0]], FlippedMatrix).
FlippedMatrix = [[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]]
yes
| ?-
Notes
For the given matrix we need only recursively consider each row, reverse it, do the necessary bit flips, and then assemble the newly flipped rows into the completed Flipped Matrix.
References
posted at: 21:44 by: Adam Russell | path: /prolog | permanent link to this entry