# RabbitFarm

### 2023-12-03

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

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

## Part 1

You are given two array of languages and its popularity. Write a script to sort the language based on popularity.

### Solution

``````
make_pairs(K, V, K-V).

sort_language(Languages, Popularity, SortedLanguages):-
maplist(make_pairs, Popularity, Languages, PopularityLanguages),
keysort(PopularityLanguages, SortedPopularityLanguages),
findall(Language,  member(_-Language, SortedPopularityLanguages), SortedLanguages).
``````

### Sample Run

``````
% gprolog --consult-file prolog/ch-1.p
| ?- sort_language([2, 1, 3], [perl, c, python], SortedLanguages).

SortedLanguages = [1,2,3]

yes
| ?-
``````

### Notes

A pretty standard Prolog convention is the `-` separated Pair. So here all we need do is generate the pairs of popularity and language, and then use `keysort/2` to get everything in the right order.

## Part 2

You are given an array of integers >= 0. Write a script to return the largest number formed by concatenating some of the given integers in any order which is also multiple of 3. Return -1 if none found.

### Solution

``````
largest_of_three(Numbers, LargestOfThree):-
findall(Number,(
sublist(SubList, Numbers),
\+ SubList = [],
permutation(SubList, SubListPermutation),
number_codes(Number, SubListPermutation),
0 is Number mod 3), NumbersOfThree),
((NumbersOfThree = [], LargestOfThree = -1);
(max_list(NumbersOfThree, LargestOfThree))).
``````

### Sample Run

``````
% gprolog --consult-file prolog/ch-2.p
| ?- largest_of_three("819", LargestOfThree).

LargestOfThree = 981

yes
| ?- largest_of_three("86710", LargestOfThree).

LargestOfThree = 8760

(1 ms) yes
| ?- largest_of_three("1", LargestOfThree).

LargestOfThree = -1 ?

yes
| ?-
``````

### Notes

This is perhaps the most naive solution to the problem: generate sublists and sort the matching permutations of those sublists.

## References

Challenge 245

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