RabbitFarm

2021-05-30

The Weekly Challenge 114 (Prolog Solutions)

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

Part 1

You are given a positive integer $N. Write a script to find out the next Palindrome Number higher than the given integer $N.

Solution


:-initialization(main).

next_palindrome(N, NextPalindrome):-
    current_prolog_flag(max_integer, MAX_INTEGER),
    N0 is N + 1,
    between(N0, MAX_INTEGER, X),
    number_chars(X, C),
    reverse(C, R),
    number_chars(NR, R),
    NR == X,
    NextPalindrome = NR.

main:-
    next_palindrome(1234, NextPalindrome0),
    write(NextPalindrome0), nl,
    next_palindrome(999, NextPalindrome1),
    write(NextPalindrome1), nl,
    halt.

Sample Run


$ gprolog --consult-file prolog/ch-1.p
GNU Prolog 1.4.5 (32 bits)
Compiled Dec  3 2020, 00:37:14 with gcc
By Daniel Diaz
Copyright (C) 1999-2020 Daniel Diaz
compiling /home/adamcrussell/Projects/perlweeklychallenge-club/challenge-114/adam-russell/prolog/ch-1.p for byte code...
/home/adamcrussell/Projects/perlweeklychallenge-club/challenge-114/adam-russell/prolog/ch-1.p compiled, 18 lines read - 1808 bytes written, 38 ms
1331
1001

Notes

The solution to this task is probably the most intuitive: check numbers starting with N and for each one reverse and check.

Part 2

You are given a positive integer $N. Write a script to find the next higher integer having the same number of 1 bits in binary representation as $N.

Solution


:-initialization(main).

set_bits(N, X):-
    set_bits(N, 0, X).
set_bits(0, X, X).
set_bits(N, X_Acc, X):-
    B is N /\ 1,
    X0 is X_Acc + B,
    N0 is N >> 1,
    set_bits(N0, X0, X), !.

next_same_bits(N, NextSameBits):-
    current_prolog_flag(max_integer, MAX_INTEGER),
    set_bits(N, NumberBits),
    N0 is N + 1,
    between(N0, MAX_INTEGER, X),
    set_bits(X, B),
    B == NumberBits,
    NextSameBits = X.

main:-
    next_same_bits(3, NextSameBits0),
    write(NextSameBits0), nl,
    next_same_bits(12, NextSameBits1),
    write(NextSameBits1), nl,
    halt.

Sample Run


$ gprolog --consult-file prolog/ch-2.p
GNU Prolog 1.4.5 (32 bits)
Compiled Dec  3 2020, 00:37:14 with gcc
By Daniel Diaz
Copyright (C) 1999-2020 Daniel Diaz
compiling /home/adamcrussell/Projects/perlweeklychallenge-club/challenge-114/adam-russell/prolog/ch-2.p for byte code...
/home/adamcrussell/Projects/perlweeklychallenge-club/challenge-114/adam-russell/prolog/ch-2.p compiled, 26 lines read - 2763 bytes written, 42 ms
5
17

Notes

set_bits/2 is code re-used from Challenge 079. Otherwise, the code is very similar to the solution to the first task.

References

Challenge 114

posted at: 15:59 by: Adam Russell | path: /prolog | permanent link to this entry