Skip to content

Instantly share code, notes, and snippets.

@alexrothenberg
Last active December 15, 2015 00:19
Show Gist options
  • Save alexrothenberg/5172286 to your computer and use it in GitHub Desktop.
Save alexrothenberg/5172286 to your computer and use it in GitHub Desktop.
This is the first prolog code I've written in 20 years. I used to be very into it but that was a long time ago.
% A brute force algorithm to solve the Surpassing Problem posed by Martin Rem in 1988
%
% By definition, a surpasser of an element of an array is a greater element to the right,
% so x[j] is a surpasser of x[i] if i < j and x[i] < x[j]. The surpasser count of an element
% is the number of its surpassers. For example, the surpasser count of the string GENERATING
% are given by
%
% G E N E R A T I N G
% 5 6 2 5 1 4 0 I 0 0
% The maximum surpasser count is 6. The first occurrence of the letter E has six surpassers,
% namely N, R, T, I, N, and G.
% ?- surpassingProblem('GENERATING', X).
% X = 6
surpassingProblem(Text, MaxSurpassor):-
name(Text, CharList),
surpassingProblemCharacters(CharList, SurpassorCounts),
max(SurpassorCounts, MaxSurpassor).
surpassingProblemCharacters([], []).
surpassingProblemCharacters([FirstChar|CharList], [FirstSurpassors|RestSurpassors]) :-
surpassor_count(FirstChar, CharList, FirstSurpassors),
surpassingProblemCharacters(CharList, RestSurpassors).
surpassor_count(_, [], 0):- !.
surpassor_count(Element, [H|T], Count):-
Element < H,
!, % red cut
surpassor_count(Element, T, CountOfRest),
Count is CountOfRest + 1.
surpassor_count(Element, [_|T], Count):-
surpassor_count(Element, T, Count).
max([x], x).
max([H|T], MaxTail) :-
max(T, MaxTail),
MaxTail > H,
!. % red cut
max([H|T], H).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment