RabbitFarm
2021-01-31
The Weekly Challenge 097 (Prolog Solutions)
The examples used here are from the weekly challenge problem statement and demonstrate the working solution.
Part 1
You are given string $S
containing alphabets A..Z only and a number $N
. Write a script to encrypt the given string $S
using Caesar Cipher with left shift of size $N
.
Solution
:-initialization(main).
caesar([], [], _).
caesar([H|T], [C|Cypher], N):-
C is H - N,
C >= 65,
caesar(T, Cypher, N).
caesar([H|T], [C|Cypher], N):-
C0 is H - N,
C0 < 65,
C is C0 + 26,
caesar(T, Cypher, N).
main:-
caesar("ABCDEFGHIJKLMNOPQRSTUVWXYZ", C, 3),
atom_codes(CypherText, C),
write(CypherText), nl,
halt.
Sample Run
$ gplc ch-1.p
$ ./ch-1
XYZABCDEFGHIJKLMNOPQRSTUVW
Part 2
You are given a binary string $B
and an integer $S
. Write a script to split the binary string $B
of size $S
and then find the minimum number of flips required to make it all the same.
Solution
:-initialization(main).
substrings(BinaryString, N, SubStrings):-
substrings(BinaryString, N, [], SubStrings).
substrings([], _, SubStrings, SubStrings).
substrings(BinaryString, N, SubStringAccum, SubStrings):-
length(L, N),
append(L, X, BinaryString),
substrings(X, N, [L|SubStringAccum], SubStrings).
count_flips(B, [H|T], Flips):-
count_flips(B, [H|T], 0, Flips).
count_flips(_, [], Flips, Flips).
count_flips(B, [H|T], FlipsSum, Flips):-
number_codes(B0, B),
number_codes(H0, H),
X is xor(B0, H0),
Flips0 is X + FlipsSum,
count_flips(B, T, Flips0, Flips).
min_flips(SubStrings, MinFlips):-
min_flips(SubStrings, [], Flips),
sort(Flips,[MinFlips|_]).
min_flips([_], Flips, Flips).
min_flips([H|T], FlipsAccum, Flips):-
count_flips(H, T, Flips0),
min_flips(T, [Flips0|FlipsAccum], Flips).
main:-
substrings("101100101", 3, SubStrings),
min_flips(SubStrings, Flips),
write(Flips),nl,
halt.
Sample Run
$ gplc prolog/ch-2.p
$ ./ch-2
1
References
posted at: 18:48 by: Adam Russell | path: /prolog | permanent link to this entry