# 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
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
`set_bits/2` is code re-used from Challenge 079. Otherwise, the code is very similar to the solution to the first task.