RabbitFarm
2023-11-19
The Weekly Challenge 243 (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 integers. Write a script to return the number of reverse pairs in the given array.
Solution
reverse_pair(X, Y, Z):-
    (X =\= Y, X > Y + Y, Z = 1, !); Z = 0.
reverse_pairs([], 0).    
reverse_pairs([H|T], ReversePairs):-
    reverse_pairs(T, R),
    maplist(reverse_pair(H), T, RP),
    sum_list(RP, Sum),
    ReversePairs is R + Sum.  
Sample Run
% gprolog --consult-file prolog/ch-1.p
| ?- reverse_pairs([1, 3, 2, 3, 1], ReversePairs).  
ReversePairs = 2
yes
| ?- reverse_pairs([2, 4, 3, 5, 1], ReversePairs).  
ReversePairs = 3
yes
| ?- 
Notes
reverse_pair/3 implements the reverse pair criteria and is called 
via a maplist/3 in reverse_pairs/3 which recurses over the list and
counts up all Reverse Pairs found.
Part 2
You are given an array of positive integers (>=1). Write a script to return the floor sum.
Solution
floor_sum_pair(X, Y, Z):-
    Z is floor(X / Y).
floor_sum(Integers, FloorSum):-
    floor_sum(Integers, Integers, FloorSum).
floor_sum([], _, 0).    
floor_sum([H|T], L, FloorSum):-
    floor_sum(T, L, F),
    maplist(floor_sum_pair(H), L, FS),
    sum_list(FS, Sum),
    FloorSum is F + Sum.  
Sample Run
% gprolog --consult-file prolog/ch-2.p 
| ?- floor_sum([2, 5, 9], FloorSum).
FloorSum = 10
yes
| ?- floor_sum([7, 7, 7, 7, 7, 7, 7], FloorSum).
FloorSum = 49
(1 ms) yes
| ?- 
Notes
The process here is, co-incidentally, much the same as the first part 
above. We recurse over the list and use a maplist/3 to build an 
incremental sum at each step.
References
posted at: 17:33 by: Adam Russell | path: /prolog | permanent link to this entry