How to resolve the algorithm Hofstadter Figure-Figure sequences step by step in the Prolog programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Hofstadter Figure-Figure sequences step by step in the Prolog programming language

Table of Contents

Problem Statement

These two sequences of positive integers are defined as:

The sequence

S ( n )

{\displaystyle S(n)}

is further defined as the sequence of positive integers not present in

R ( n )

{\displaystyle R(n)}

. Sequence

R

{\displaystyle R}

starts: Sequence

S

{\displaystyle S}

starts:

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Hofstadter Figure-Figure sequences step by step in the Prolog programming language

Source code in the prolog programming language

:- use_module(library(chr)).

:- chr_constraint ffr/2, ffs/2, hofstadter/1,hofstadter/2.
:- chr_option(debug, off).
:- chr_option(optimize, full).

% to remove duplicates
ffr(N, R1) \ ffr(N, R2) <=> R1 = R2 | true.
ffs(N, R1) \ ffs(N, R2) <=> R1 = R2 | true.

% compute ffr
ffr(N, R), ffr(N1, R1), ffs(N1,S1) ==>
         N > 1, N1 is N - 1 |
	 R is R1 + S1.

% compute ffs
ffs(N, S), ffs(N1,S1) ==>
         N > 1, N1 is N - 1 |
	 V is S1 + 1,
	 (   find_chr_constraint(ffr(_, V)) ->  S is V+1; S = V).
 
% init
hofstadter(N) ==>  ffr(1,1), ffs(1,2).
% loop
hofstadter(N), ffr(N1, _R), ffs(N1, _S) ==> N1 < N, N2 is N1 +1 |  ffr(N2,_), ffs(N2,_).


hofstadter :-
	hofstadter(960),
	% fetch the values of ffr
	bagof(Y, X^find_chr_constraint(ffs(X,Y)), L1),
	% fetch the values of ffs
	bagof(Y, X^(find_chr_constraint(ffr(X,Y)), X < 41), L2),
	% concatenate then
	append(L1, L2, L3),
	% sort removing duplicates
	sort(L3, L4),
	% check the correctness of the list
	(   (L4 = [1|_], last(L4, 1000), length(L4, 1000)) -> writeln(ok); writeln(ko)),
	% to remove all pending constraints
	fail.


  

You may also check:How to resolve the algorithm Modular arithmetic step by step in the Fortran programming language
You may also check:How to resolve the algorithm Reflection/List methods step by step in the Lingo programming language
You may also check:How to resolve the algorithm File size step by step in the Delphi programming language
You may also check:How to resolve the algorithm Hofstadter Figure-Figure sequences step by step in the jq programming language
You may also check:How to resolve the algorithm Rename a file step by step in the C# programming language