RabbitFarm
2023-10-29
The Weekly Challenge 240 (Prolog Solutions)
The examples used here are from the weekly challenge problem statement and demonstrate the working solution.
Part 1
You are given an array of strings and a check string. Write a script to find out if the check string is the acronym of the words in the given array.
Solution
acronym(Strings, CheckString):-
maplist(nth(1), Strings, CheckStringUpperCaseCodes),
maplist(char_code, CheckStringUpperCase, CheckStringUpperCaseCodes),
maplist(lower_upper, CheckStringLowerCase, CheckStringUpperCase),
atom_chars(CheckStringA, CheckStringLowerCase),
atom_codes(CheckStringA, CheckString).
Sample Run
% gprolog --consult-file prolog/ch-1.p
| ?- acronym(["Perl", "Python", "Pascal"], "ppp").
true ?
yes
| ?- acronym(["Perl", "Raku"], "rp").
no
| ?- acronym(["Oracle", "Awk", "C"], "oac").
true ?
yes
| ?- acronym(["Oracle", "Awk", "C"], A), atom_codes(Acronym, A).
A = [111,97,99]
Acronym = oac ?
yes
| ?-
Notes
In keeping with the spirit of the original, Perl centric, challenge question I use strings instead of Prolog atoms. The difference is that strings will be represented as lists of character codes, so a little extra code is required.
Chanelling the spirit of Prolog, the solution will backtrack and provide the acronym if that variable is given uninstantiated!
Part 2
You are given an array of integers. Write a script to create an array such that new[i] = old[old[i]] where 0 <= i < new.length.
Solution
build_list(_, [], []).
build_list(Old, [OldH|OldT], [NewH|NewT]):-
succ(OldH, I),
nth(I, Old, NewH),
build_list(Old, OldT, NewT).
Sample Run
% gprolog --consult-file prolog/ch-2.p
| ?- Old = [0, 2, 1, 5, 3, 4], build_list(Old, Old, New).
New = [0,1,2,4,5,3]
Old = [0,2,1,5,3,4] ?
yes
| ?- Old = [5, 0, 1, 2, 3, 4], build_list(Old, Old, New).
New = [4,5,0,1,2,3]
Old = [5,0,1,2,3,4] ?
yes
| ?-
Notes
This is basically the same recursive procedure as used in the Perl solution to the same problem. I did the Perl version first, which was helpful to prototype the recursion.
References
posted at: 16:41 by: Adam Russell | path: /prolog | permanent link to this entry