RabbitFarm

2025-04-19

The Weekly Challenge 317 (Prolog Solutions)

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

Part 1: Acronyms

You are given an array of words and a word. Write a script to return true if concatenating the first letter of each word in the given array matches the given word, return false otherwise.

We can do this in a single predicate which uses maplist to get the first character from each word, which we’ll take as a list of character code lists.

acronym 1 ⟩≡


acronym(Words, Word):-
maplist(nth(1), Words, FirstLetters),
Word = FirstLetters.

Fragment referenced in 2.

The rest of the code just wraps this single predicate into a file.

"ch-1.p" 2


acronym 1

Sample Run
$ gprolog --consult-file prolog/ch-1.p 
| ?- acronym(["Perl", "Weekly", "Challenge"], "PWC"). 
 
yes 
| ?- acronym(["Bob", "Charlie", "Joe"], "BCJ"). 
 
yes 
| ?- acronym(["Morning", "Good"], "MM"). 
 
no 
| ?-
    

Part 2: Friendly Strings

You are given two strings. Write a script to return true if swapping any two letters in one string match the other string, return false otherwise.

This is going to be a quick one. First we will check that we can subtract/3 the two words (character code lists) and obtain an empty list. Then we’ll check in which places the words differ. They must only differ in exactly two places.

friendly 3 ⟩≡


friendly(Word1, Word2):-
subtract(Word1, Word2, []),
length(Word1, Length),
findall(Difference, (
between(1, Length, I),
nth(I, Word1, C1),
nth(I, Word2, C2),
\+ C1 = C2,
Difference = [C1, C2]
), Differences),
length(Differences, NumberDifferences),
NumberDifferences == 2.

Fragment referenced in 4.

Finally, let’s assemble our completed code into a single file.

"ch-2.p" 4


friendly 3

Sample Run
$ gprolog --consult-file prolog/ch-2.p 
| ?- friendly("desc", "dsec"). 
 
yes 
| ?- friendly("cat", "dog"). 
 
no 
| ?- friendly("stripe", "sprite"). 
 
yes 
| ?-
    

References

The Weekly Challenge 317
Generated Code

posted at: 21:39 by: Adam Russell | path: /prolog | permanent link to this entry