# RabbitFarm

### 2022-04-24

#### The Weekly Challenge 161 (Prolog Solutions)

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

## Part 1

Output or return a list of all abecedarian words in the dictionary, sorted in decreasing order of length.

### Solution

``````
!.
!.
!.
!.
!.
get_code(Stream, NextChar),

at_end_of_stream(Stream).
\+ at_end_of_stream(Stream),
get_code(Stream, Char),
atom_codes(X, Chars),

abecedarian(Words, Abecedarian):-
member(Word, Words),
atom_chars(Word, Chars),
sort(Chars, SortedChars),
atom_chars(W, SortedChars),
W = Word,
Abecedarian = Word.

word_length(Word, LengthWord):-
atom_chars(Word, Chars),
length(Chars, Length),
LengthWord = Length-Word.

abecedarians(Words, Abecedarians):-
findall(Abecedarian, abecedarian(Words, Abecedarian), A),
maplist(word_length, A, AL),
keysort(AL, ALSorted),
reverse(ALSorted, Abecedarians).

main:-
close(Stream),
abecedarians(Dictionary, Abecedarians),
write(Abecedarians), nl,
halt.
``````

### Sample Run

``````
\$ gprolog --consult-file prolog/ch-1.p --entry-goal main
Most of the code here is just for reading the provided dictionary of words. Once that is complete Prolog really shines. `abecedarian/2` is the majority of the logic: if a word's characters when sorted and re-assembled are the original word then it is an Abecedarian.
`abecedarians/2` is necessary only to fulfill the requirements of the problem specification which is that all Abecedarians be sorted by length and returned in descending order.