Hofstadter Figure-Figure sequences: Difference between revisions

Added Easylang
(→‎{{header|REXX}}: re-wrote the subroutines and verification routine. -- ~~~~)
(Added Easylang)
 
(135 intermediate revisions by 44 users not shown)
Line 1:
{{task}}
 
These two sequences of positive integers are defined as:
:::: <big><math>\begin{align}
R(1)&=1\ ;\ S(1)=2 \\
R(n)&=R(n-1)+S(n-1), \quad n>1.
\end{align}</math></big>
 
:The sequence <math>S(n)</math> is further defined as the sequence of positive integers ''not'' present in <math>R(n)</math>.
<br>
Sequence R starts: 1, 3, 7, 12, 18, ...<br>
The sequence <big><math>S(n)</math></big> is further defined as the sequence of positive integers '''''not''''' present in <big><math>R(n)</math></big>.
Sequence S starts: 2, 4, 5, 6, 8, ...
 
Sequence <big><math>R</math></big> starts:
1, 3, 7, 12, 18, ...
Sequence <big><math>S</math></big> starts:
2, 4, 5, 6, 8, ...
 
 
;Task:
# Create two functions named '''ffr''' and '''ffs''' that when given '''n''' return '''R(n)''' or '''S(n)''' respectively.<br>(Note that R(1) = 1 and S(1) = 2 to avoid off-by-one errors).
# No maximum value for '''n''' should be assumed.
# Calculate and show that the first ten values of '''R''' are:<br> 1, 3, 7, 12, 18, 26, 35, 45, 56, and 69
# Calculate and show that the first 40 values of '''ffr''' plus the first 960 values of '''ffs''' include all the integers from 1 to 1000 exactly once.
 
Task:
# Create two functions named ffr and ffs that when given n return R(n) or S(n) respectively.<br><small>(Note that R(1) = 1 and S(1) = 2 to avoid off-by-one errors).</small>
# No maximum value for n should be assumed.
# Calculate and show that the first ten values of R are: 1, 3, 7, 12, 18, 26, 35, 45, 56, and 69
# Calculate and show that the first 40 values of ffr plus the first 960 values of ffs include all the integers from 1 to 1000 exactly once.
 
;References:
* Sloane's [http://oeis.org/A005228 A005228] and [http://oeis.org/A030124 A030124].
* [http://mathworld.wolfram.com/HofstadterFigure-FigureSequence.html Wolfram MathworldMathWorld]
* Wikipedia: [[wp:Hofstadter_sequence#Hofstadter_Figure-Figure_sequences|Hofstadter Figure-Figure sequences]].
<br><br>
 
=={{header|11l}}==
{{trans|Python}}
 
<syntaxhighlight lang="11l">V cR = [1]
V cS = [2]
 
F extend_RS()
V x = :cR[:cR.len-1] + :cS[:cR.len-1]
:cR [+]= (x)
:cS [+]= :cS.last+1 .< x
:cS [+]= (x + 1)
 
F ff_R(n)
assert(n > 0)
L n > :cR.len
extend_RS()
R :cR[n - 1]
 
F ff_S(n)
assert(n > 0)
L n > :cS.len
extend_RS()
R :cS[n - 1]
 
print((1..10).map(i -> ff_R(i)))
 
V arr = [0] * 1001
L(i) (40.<0).step(-1)
arr[ff_R(i)]++
L(i) (960.<0).step(-1)
arr[ff_S(i)]++
 
I all(arr[1..1000].map(a -> a == 1))
print(‘All Integers 1..1000 found OK’)
E
print(‘All Integers 1..1000 NOT found only once: ERROR’)</syntaxhighlight>
 
{{out}}
<pre>
[1, 3, 7, 12, 18, 26, 35, 45, 56, 69]
All Integers 1..1000 found OK
</pre>
 
=={{header|ABC}}==
<syntaxhighlight lang="abc">PUT {[1]: 1} IN r.list
PUT {[1]: 2} IN s.list
 
HOW TO EXTEND R TO n:
SHARE r.list, s.list
WHILE n > #r.list:
PUT r.list[#r.list] + s.list[#r.list] IN next.r
FOR i IN {s.list[#s.list]+1 .. next.r-1}:
PUT i IN s.list[#s.list+1]
PUT next.r IN r.list[#r.list+1]
PUT next.r + 1 IN s.list[#s.list+1]
 
HOW TO EXTEND S TO n:
SHARE r.list, s.list
WHILE n > #s.list: EXTEND R TO #r.list + 1
 
HOW TO RETURN ffr n:
SHARE r.list
IF n > #r.list: EXTEND R TO n
RETURN r.list[n]
 
HOW TO RETURN ffs n:
SHARE s.list
IF n > #s.list: EXTEND S TO n
RETURN s.list[n]
 
WRITE "R[1..10]:"
FOR i IN {1..10}: WRITE ffr i
WRITE /
 
PUT {} IN thousand
FOR i IN {1..40}: INSERT ffr i IN thousand
FOR i IN {1..960}: INSERT ffs i IN thousand
IF thousand = {1..1000}:
WRITE "R[1..40] + S[1..960] = [1..1000]"/</syntaxhighlight>
{{out}}
<pre>R[1..10]: 1 3 7 12 18 26 35 45 56 69
R[1..40] + S[1..960] = [1..1000]</pre>
=={{header|Ada}}==
Specifying a package providing the functions FFR and FFS:
<langsyntaxhighlight Adalang="ada">package Hofstadter_Figure_Figure is
 
function FFR(P: Positive) return Positive;
Line 28 ⟶ 119:
function FFS(P: Positive) return Positive;
 
end Hofstadter_Figure_Figure;</langsyntaxhighlight>
 
The implementation of the package internally uses functions which generate an array of Figures or Spaces:
<langsyntaxhighlight Adalang="ada">package body Hofstadter_Figure_Figure is
 
type Positive_Array is array (Positive range <>) of Positive;
Line 81 ⟶ 172:
end FFS;
 
end Hofstadter_Figure_Figure;</langsyntaxhighlight>
 
Finally, a test program for the package, solving the task at hand:
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO, Hofstadter_Figure_Figure;
 
procedure Test_HSS is
Line 123 ⟶ 214:
exception
when Program_Error => Ada.Text_IO.Put_Line("Test Failed"); raise;
end Test_HSS;</langsyntaxhighlight>
 
The output of the test program:
<syntaxhighlight lang="text"> 1 3 7 12 18 26 35 45 56 69
Test Passed: No overlap between FFR(I) and FFS(J)</langsyntaxhighlight>
 
=={{header|APL}}==
{{works with|Dyalog APL}}
<syntaxhighlight lang="apl">:Class HFF
:Field Private Shared RBuf←,1
∇r←ffr n
:Access Public Shared
r←n⊃RBuf←(⊢,⊃∘⌽+≢⊃(⍳1+⌈/)~⊢)⍣(0⌈n-≢RBuf)⊢RBuf
∇s←ffs n;S
:Access Public Shared
:Repeat
S←((⍳1+⌈/)~⊢)RBuf
:If n≤≢S ⋄ :Leave ⋄ :EndIf
S←ffr 1+≢RBuf
:EndRepeat
s←n⊃S
∇Task;th
:Access Public Shared
⎕←'R(1 .. 10):', ffr¨⍳10
:If (⍳1000) ∧.∊ ⊂th←(ffr¨⍳40) ∪ (ffs¨⍳960)
⎕←'1..1000 ∊ (ffr 1..40) ∪ (ffs 1..960)'
:Else
⎕←'Missing values: ', (⍳1000)~th
:EndIf
:EndClass</syntaxhighlight>
 
{{out}}
 
<pre> HFF.Task
R(1 .. 10): 1 3 7 12 18 26 35 45 56 69
1..1000 ∊ (ffr 1..40) ∪ (ffs 1..960)</pre>
 
=={{header|AutoHotkey}}==
<syntaxhighlight lang="autohotkey">R(n){
if n=1
return 1
return R(n-1) + S(n-1)
}
 
S(n){
static ObjR:=[]
if n=1
return 2
ObjS:=[]
loop, % n
ObjR[R(A_Index)] := true
loop, % n-1
ObjS[S(A_Index)] := true
Loop
if !(ObjR[A_Index]||ObjS[A_Index])
return A_index
}</syntaxhighlight>
Examples:<syntaxhighlight lang="autohotkey">Loop
MsgBox, 262144, , % "R(" A_Index ") = " R(A_Index) "`nS(" A_Index ") = " S(A_Index)</syntaxhighlight>
Outputs:<pre>R(1) = 1, 3, 7, 12, 18, 26, 35,...
S(1) = 2, 4, 5, 6, 8, 9, 10,...</pre>
 
=={{header|AWK}}==
<syntaxhighlight lang="awk"># Hofstadter Figure-Figure sequences
#
# R(1) = 1; S(1) = 2;
# R(n) = R(n-1) + S(n-1), n > 1
# S(n) is the values not in R(n)
 
BEGIN {
 
# start with the first two values of R and S to simplify finding S[n]:
R[ 1 ] = 1;
R[ 2 ] = 3;
S[ 1 ] = 2;
S[ 2 ] = 4;
# maximum n we currently have of R and S
rMax = 2;
sMax = 2;
 
# calculate and show the first 10 values of R:
printf( "R[1..10]:" );
for( n = 1; n < 11; n ++ )
{
printf( " %d", ffr( n ) );
}
printf( "\n" );
# check that R[1..40] and S[1..960] contain the numbers 1..1000 once each
# add the values of R[ 1..40 ] to the set V
for( n = 1; n <= 40; n ++ )
{
V[ ffr( n ) ] ++;
}
# add the values of S[ 1..960 ] to the set V
for( n = 1; n <= 960; n ++ )
{
V[ ffs( n ) ] ++;
}
# check all numbers are present and not duplicated
ok = 1;
for( n = 1; n <= 1000; n ++ )
{
if( ! ( n in V ) )
{
printf( "%d not present in R[1..40], S[1..960]\n", n );
ok = 0;
}
else if( V[ n ] != 1 )
{
printf( "%d occurs %d times in R[1..40], S[1..960]\n", n, V[ n ] );
ok = 0;
}
}
if( ok )
{
printf( "R[1..40] and S[1..960] uniquely contain all 1..1000\n" );
}
 
} # BEGIN
 
function ffr( n )
{
# calculate R[n]
if( ! ( n in R ) )
{
# we haven't calculated R[ n ] yet
R[ n ] = ffs( n - 1 );
R[ n ] += ffr( n - 1 );
}
return R[ n ];
} # ffr
 
function ffs( n )
{
# calculate S[n]
if( ! ( n in S ) )
{
# starting at the highest known R, calculate the next one and fill in the S values
# continuing until we have enough S values
do
{
R[ rMax + 1 ] = R[ rMax ] + S[ rMax ];
for( sValue = R[ rMax ] + 1; sValue < R[ rMax + 1 ]; sValue ++ )
{
S[ sMax ++ ] = sValue;
}
rMax ++;
}
while( sMax < n );
}
return S[ n ];
} # ffs</syntaxhighlight>
{{out}}
<pre>
R[1..10]: 1 3 7 12 18 26 35 45 56 69
R[1..40] and S[1..960] uniquely contain all 1..1000
</pre>
 
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<langsyntaxhighlight lang="bbcbasic"> PRINT "First 10 values of R:"
FOR i% = 1 TO 10 : PRINT ;FNffr(i%) " "; : NEXT : PRINT
PRINT "First 10 values of S:"
Line 183 ⟶ 429:
IF R% <= 2*N% V%?R% = 1
NEXT I%
= S%</langsyntaxhighlight>
<pre>
First 10 values of R:
Line 193 ⟶ 439:
</pre>
 
=={{header|Common LispC}}==
<syntaxhighlight lang="c">#include <stdio.h>
<lang lisp>;;; equally doable with a list
#include <stdlib.h>
(flet ((seq (i) (make-array 1 :element-type 'integer
:initial-element i
:fill-pointer 1
:adjustable t)))
(let ((rr (seq 1)) (ss (seq 2)))
(labels ((extend-r ()
(let* ((l (1- (length rr)))
(r (+ (aref rr l) (aref ss l)))
(s (elt ss (1- (length ss)))))
(vector-push-extend r rr)
(loop while (<= s r) do
(if (/= (incf s) r)
(vector-push-extend s ss))))))
(defun seq-r (n)
(loop while (> n (length rr)) do (extend-r))
(elt rr (1- n)))
 
// simple extensible array stuff
(defun seq-s (n)
typedef unsigned long long xint;
(loop while (> n (length ss)) do (extend-r))
(elt ss (1- n))))))
 
typedef struct {
(defun take (f n)
size_t len, alloc;
(loop for x from 1 to n collect (funcall f x)))
xint *buf;
} xarray;
 
xarray rs, ss;
(format t "First of R: ~a~%" (take #'seq-r 10))
 
void setsize(xarray *a, size_t size)
(mapl (lambda (l) (if (and (cdr l)
{
(/= (1+ (car l)) (cadr l)))
size_t n = a->alloc;
(error "not in sequence")))
if (!n) n = 1;
(sort (append (take #'seq-r 40)
 
(take #'seq-s 960))
while (n < size) n <<= 1;
#'<))
if (a->alloc < n) {
(princ "Ok")</lang>output<lang>First of R: (1 3 7 12 18 26 35 45 56 69)
a->buf = realloc(a->buf, sizeof(xint) * n);
Ok</lang>
if (!a->buf) abort();
a->alloc = n;
}
}
 
void push(xarray *a, xint v)
{
while (a->alloc <= a->len)
setsize(a, a->alloc * 2);
 
a->buf[a->len++] = v;
}
 
 
// sequence stuff
void RS_append(void);
 
xint R(int n)
{
while (n > rs.len) RS_append();
return rs.buf[n - 1];
}
 
xint S(int n)
{
while (n > ss.len) RS_append();
return ss.buf[n - 1];
}
 
void RS_append()
{
int n = rs.len;
xint r = R(n) + S(n);
xint s = S(ss.len);
 
push(&rs, r);
while (++s < r) push(&ss, s);
push(&ss, r + 1); // pesky 3
}
 
int main(void)
{
push(&rs, 1);
push(&ss, 2);
 
int i;
printf("R(1 .. 10):");
for (i = 1; i <= 10; i++)
printf(" %llu", R(i));
 
char seen[1001] = { 0 };
for (i = 1; i <= 40; i++) seen[ R(i) ] = 1;
for (i = 1; i <= 960; i++) seen[ S(i) ] = 1;
for (i = 1; i <= 1000 && seen[i]; i++);
 
if (i <= 1000) {
fprintf(stderr, "%d not seen\n", i);
abort();
}
 
puts("\nfirst 1000 ok");
return 0;
}</syntaxhighlight>
 
=={{header|C sharp|C#}}==
Creates an IEnumerable for R and S and uses those to complete the task
<langsyntaxhighlight Csharplang="csharp">using System;
using System.Collections.Generic;
using System.Linq;
Line 316 ⟶ 611:
}
}
</syntaxhighlight>
</lang>
Output:
<pre>1
Line 330 ⟶ 625:
Verified</pre>
 
=={{header|C++}}==
{{works with|gcc}}
<lang c>#include <stdio.h>
{{works with|C++|11, 14, 17}}
#include <stdlib.h>
<syntaxhighlight lang="cpp">#include <iomanip>
#include <iostream>
#include <set>
#include <vector>
 
using namespace std;
// simple extensible array stuff
typedef unsigned long long xint;
 
unsigned hofstadter(unsigned rlistSize, unsigned slistSize)
typedef struct {
{
size_t len, alloc;
auto n = rlistSize > slistSize ? rlistSize : slistSize;
xint *buf;
auto rlist = new vector<unsigned> { 1, 3, 7 };
} xarray;
auto slist = new vector<unsigned> { 2, 4, 5, 6 };
auto list = rlistSize > 0 ? rlist : slist;
auto target_size = rlistSize > 0 ? rlistSize : slistSize;
 
while (list->size() > target_size) list->pop_back();
xarray rs, ss;
 
while (list->size() < target_size)
void setsize(xarray *a, size_t size)
{
{
auto lastIndex = rlist->size() - 1;
size_t n = a->alloc;
auto lastr = (*rlist)[lastIndex];
if (!n) n = 1;
auto r = lastr + (*slist)[lastIndex];
rlist->push_back(r);
for (auto s = lastr + 1; s < r && list->size() < target_size;)
slist->push_back(s++);
}
 
while (n < size) nauto v <<= (*list)[n - 1];
delete rlist;
if (a->alloc < n) {
delete slist;
a->buf = realloc(a->buf, sizeof(xint) * n);
return v;
if (!a->buf) abort();
a->alloc = n;
}
}
 
ostream& operator<<(ostream& os, const set<unsigned>& s)
void push(xarray *a, xint v)
{
cout << '(' << s.size() << "):";
while (a->alloc <= a->len)
auto i = 0;
setsize(a, a->alloc * 2);
for (auto c = s.begin(); c != s.end();)
 
{
a->buf[a->len++] = v;
if (i++ % 20 == 0) os << endl;
os << setw(5) << *c++;
}
return os;
}
 
int main(int argc, const char* argv[])
{
const auto v1 = atoi(argv[1]);
const auto v2 = atoi(argv[2]);
set<unsigned> r, s;
for (auto n = 1; n <= v2; n++)
{
if (n <= v1)
r.insert(hofstadter(n, 0));
s.insert(hofstadter(0, n));
}
cout << "R" << r << endl;
cout << "S" << s << endl;
 
int m = max(*r.rbegin(), *s.rbegin());
// sequence stuff
for (auto n = 1; n <= m; n++)
void RS_append(void);
if (r.count(n) == s.count(n))
clog << "integer " << n << " either in both or neither set" << endl;
 
return 0;
xint R(int n)
}</syntaxhighlight>
{
{{out}}
while (n > rs.len) RS_append();
return rs.buf[n - 1];
}
 
<syntaxhighlight lang="sh">% ./hofstadter 40 100 2> /dev/null
xint S(int n)
R(40):
{
1 3 7 12 18 26 35 45 56 69 83 98 114 131 150 170 191 213 236 260
while (n > ss.len) RS_append();
285 312 340 369 399 430 462 495 529 565 602 640 679 719 760 802 845 889 935 982
return ss.buf[n - 1];
S(100):
}
2 4 5 6 8 9 10 11 13 14 15 16 17 19 20 21 22 23 24 25
27 28 29 30 31 32 33 34 36 37 38 39 40 41 42 43 44 46 47 48
49 50 51 52 53 54 55 57 58 59 60 61 62 63 64 65 66 67 68 70
71 72 73 74 75 76 77 78 79 80 81 82 84 85 86 87 88 89 90 91
92 93 94 95 96 97 99 100 101 102 103 104 105 106 107 108 109 110 111 112</syntaxhighlight>
 
=={{header|CLU}}==
void RS_append()
<syntaxhighlight lang="clu">figfig = cluster is ffr, ffs
{
rep = null
int n = rs.len;
ai = array[int]
xint r = R(n) + S(n);
own R: ai := ai$[1]
xint s = S(ss.len);
own S: ai := ai$[2]
% Extend R and S until R(n) is known
extend = proc (n: int)
while n > ai$high(R) do
next: int := ai$top(R) + S[ai$high(R)]
ai$addh(R, next)
while ai$top(S) < next-1 do
ai$addh(S, ai$top(S)+1)
end
ai$addh(S, next+1)
end
end extend
ffr = proc (n: int) returns (int)
extend(n)
return(R[n])
end ffr
ffs = proc (n: int) returns (int)
while n > ai$high(S) do
extend(ai$high(R) + 1)
end
return(S[n])
end ffs
end figfig
 
start_up = proc ()
push(&rs, r);
ai = array[int]
while (++s < r) push(&ss, s);
po: stream := stream$primary_output()
push(&ss, r + 1); // pesky 3
}
% Print R[1..10]
stream$puts(po, "R[1..10] =")
for i: int in int$from_to(1,10) do
stream$puts(po, " " || int$unparse(figfig$ffr(i)))
end
stream$putl(po, "")
% Count the occurrences of 1..1000 in R[1..40] and S[1..960]
occur: ai := ai$fill(1, 1000, 0)
for i: int in int$from_to(1, 40) do
occur[figfig$ffr(i)] := occur[figfig$ffr(i)] + 1
end
for i: int in int$from_to(1, 960) do
occur[figfig$ffs(i)] := occur[figfig$ffs(i)] + 1
end
% See if they all occur exactly once
begin
for i: int in int$from_to(1, 1000) do
if occur[i] ~= 1 then exit wrong(i) end
end
stream$putl(po,
"All numbers 1..1000 occur exactly once in R[1..40] U S[1..960].")
end except when wrong(i: int):
stream$putl(po, "Error: " ||
int$unparse(i) || " occurs " || int$unparse(occur[i]) || " times.")
end
end start_up</syntaxhighlight>
{{out}}
<pre>R[1..10] = 1 3 7 12 18 26 35 45 56 69
All numbers 1..1000 occur exactly once in R[1..40] U S[1..960].</pre>
 
=={{header|CoffeeScript}}==
int main(void)
{{trans|Ruby}}
{
<syntaxhighlight lang="coffeescript">R = [ null, 1 ]
push(&rs, 1);
S = [ null, 2 ]
push(&ss, 2);
 
extend_sequences = (n) ->
int i;
current = Math.max(R[R.length - 1], S[S.length - 1])
printf("R(1 .. 10):");
for (i = 1; i <= 10; i++)undefined
while R.length <= n or S.length <= n
printf(" %llu", R(i));
i = Math.min(R.length, S.length) - 1
current += 1
if current == R[i] + S[i]
R.push current
else
S.push current
 
ff = (X, n) ->
char seen[1001] = { 0 };
extend_sequences n
for (i = 1; i <= 40; i++) seen[ R(i) ] = 1;
X[n]
for (i = 1; i <= 960; i++) seen[ S(i) ] = 1;
for (i = 1; i <= 1000 && seen[i]; i++);
 
console.log 'R(' + i + ') = ' + ff(R, i) for i in [1..10]
if (i <= 1000) {
int_array = ([1..40].map (i) -> ff(R, i)).concat [1..960].map (i) -> ff(S, i)
fprintf(stderr, "%d not seen\n", i);
int_array.sort (a, b) -> a - b
abort();
}
 
for i in [1..1000]
puts("\nfirst 1000 ok");
if int_array[i - 1] != i
return 0;
throw 'Something\'s wrong!'
}</lang>
console.log '1000 integer check ok.'</syntaxhighlight>
{{out}}
As JavaScript.
 
=={{header|Common Lisp}}==
<syntaxhighlight lang="lisp">;;; equally doable with a list
(flet ((seq (i) (make-array 1 :element-type 'integer
:initial-element i
:fill-pointer 1
:adjustable t)))
(let ((rr (seq 1)) (ss (seq 2)))
(labels ((extend-r ()
(let* ((l (1- (length rr)))
(r (+ (aref rr l) (aref ss l)))
(s (elt ss (1- (length ss)))))
(vector-push-extend r rr)
(loop while (<= s r) do
(if (/= (incf s) r)
(vector-push-extend s ss))))))
(defun seq-r (n)
(loop while (> n (length rr)) do (extend-r))
(elt rr (1- n)))
 
(defun seq-s (n)
(loop while (> n (length ss)) do (extend-r))
(elt ss (1- n))))))
 
(defun take (f n)
(loop for x from 1 to n collect (funcall f x)))
 
(format t "First of R: ~a~%" (take #'seq-r 10))
 
(mapl (lambda (l) (if (and (cdr l)
(/= (1+ (car l)) (cadr l)))
(error "not in sequence")))
(sort (append (take #'seq-r 40)
(take #'seq-s 960))
#'<))
(princ "Ok")</syntaxhighlight>
{{out}}
<pre>First of R: (1 3 7 12 18 26 35 45 56 69)
Ok</pre>
 
=={{header|Cowgol}}==
<syntaxhighlight lang="cowgol">include "cowgol.coh";
include "strings.coh";
include "malloc.coh";
 
# An uint16 is big enough to deal with the figures from the task,
# but it is good practice to allow it to be easily redefined.
typedef N is uint16;
 
# There is no extensible vector type included in the standard library,
# so it is necessary to define one.
record VecR is
len: intptr;
alloc: intptr;
data: [N];
end record;
typedef Vec is [VecR];
 
sub NewVec(): (v: Vec) is
v := Alloc(@bytesof VecR) as Vec;
MemZero(v as [uint8], @bytesof VecR);
v.alloc := 256;
v.data := Alloc(@bytesof N * 256) as [N];
MemZero(v.data as [uint8], @bytesof N * 256);
end sub;
 
sub VecGet(v: Vec, i: intptr): (r: N) is
if i >= v.len then
print("index error\n");
ExitWithError();
end if;
r := [v.data + i * @bytesof N];
end sub;
 
sub VecSet(v: Vec, i: intptr, n: N) is
if i >= v.alloc then
var newsize := v.alloc;
while i >= newsize loop
newsize := newsize + 256;
end loop;
var newbytes := newsize * @bytesof N;
var oldbytes := v.alloc * @bytesof N;
var newdata := Alloc(newbytes) as [N];
MemCopy(v.data as [uint8], oldbytes, newdata as [uint8]);
MemZero(newdata as [uint8] + oldbytes, newbytes - oldbytes);
Free(v.data as [uint8]);
v.data := newdata;
v.alloc := newsize;
end if;
[v.data + i * @bytesof N] := n;
if i >= v.len then
v.len := i+1;
end if;
end sub;
sub Last(v: Vec): (r: N) is r := VecGet(v, v.len-1); end sub;
sub Append(v: Vec, n: N) is VecSet(v, v.len, n); end sub;
 
# We also need to define a flag array, to avoid taking up 1K of memory
# for a thousand bit flags.
sub GetFlag(bitarr: [uint8], n: intptr): (s: uint8) is
s := ([bitarr + (n >> 3)] >> (n as uint8 & 7)) & 1;
end sub;
sub SetFlag(bitarr: [uint8], n: intptr) is
var p := bitarr + (n >> 3);
var f: uint8 := 1;
[p] := [p] | (f << (n as uint8 & 7));
end sub;
# Define and initialize vectors holding the R and S sequences
var R := NewVec(); Append(R, 1);
var S := NewVec(); Append(S, 2);
 
# Extend the sequences until R(n) is known.
sub Extend(n: intptr) is
while n > R.len loop
var newR := Last(R) + VecGet(S, R.len-1);
Append(R, newR);
while Last(S) < newR - 1 loop
Append(S, Last(S) + 1);
end loop;
Append(S, newR + 1);
end loop;
end sub;
 
# Get R
sub ffr(n: intptr): (r: N) is
Extend(n);
r := VecGet(R, n-1);
end sub;
 
# Get S
sub ffs(n: intptr): (s: N) is
while n > S.len loop
Extend(R.len + 1);
end loop;
s := VecGet(S, n-1);
end sub;
 
# Print the first 10 values of R.
print("R(1 .. 10): ");
var n: intptr := 1;
while n <= 10 loop
print_i32(ffr(n) as uint32);
print_char(' ');
n := n + 1;
end loop;
print_nl();
 
 
print("Checking that (1 .. 1000) are in R(1 .. 40) U S(1 .. 960)...\n");
# Reserve 1000 bits to use as flags, and set them all to zero
var flags: uint8[1000 / 8];
MemZero(&flags[0], @bytesof flags);
 
# Set the flags corresponding to FFR(1 .. 40) and FFS(1 .. 960)
n := 1;
while n <= 40 loop
SetFlag(&flags[0], (ffr(n)-1) as intptr);
n := n + 1;
end loop;
 
n := 1;
while n <= 960 loop
SetFlag(&flags[0], (ffs(n)-1) as intptr);
n := n + 1;
end loop;
 
# Check all flags
var ok: uint8 := 1;
n := 1;
while n <= 1000 loop
if GetFlag(&flags[0], (n-1) as intptr) == 0 then
print_i32(n as uint32);
print(" not found!\n");
ok := 0;
end if;
n := n + 1;
end loop;
 
if ok != 0 then
print("All numbers 1 .. 1000 found!\n");
end if;</syntaxhighlight>
 
{{out}}
 
<pre>R(1 .. 10): 1 3 7 12 18 26 35 45 56 69
Checking that (1 .. 1000) are in R(1 .. 40) U S(1 .. 960)...
All numbers 1 .. 1000 found!</pre>
 
=={{header|D}}==
{{trans|Go}}
<syntaxhighlight lang="d">int delegate(in int) nothrow ffr, ffs;
<lang d>import std.stdio, std.array, std.range, std.algorithm;
 
int delegate(in int) nothrow ffr, ffs;
 
nothrow static this() {
auto r = [0, 1], s = [0, 2];
 
ffr = (in int n) nothrow {
while (r.length <= n) {
immutable int nrk = r.length - 1;
immutable int rNext = r[nrk] + s[nrk];
r ~= rNext;
foreach (immutable sn; r[nrk] + 2 .. rNext)
s ~= sn;
s ~= rNext + 1;
Line 437 ⟶ 1,015:
};
 
ffs = (in int n) nothrow {
while (s.length <= n)
ffr(r.length);
Line 445 ⟶ 1,023:
 
void main() {
import std.stdio, std.array, std.range, std.algorithm;
writeln(iota(1, 11).map!ffr());
 
auto t = iota(1, 41).map!ffr().chain(iota(1, 961).map!ffs());
writeln(t.array().sort().equal(iota(1, 1001))11).map!ffr.writeln;
auto t = iota(1, 41).map!ffr.chain(iota(1, 961).map!ffs);
}</lang>
t.array.sort().equal(iota(1, 1001)).writeln;
Output:
}</syntaxhighlight>
{{out}}
<pre>[1, 3, 7, 12, 18, 26, 35, 45, 56, 69]
true</pre>
Line 455 ⟶ 1,035:
{{trans|Python}}
(Same output)
<langsyntaxhighlight lang="d">import std.stdio, std.array, std.range, std.algorithm;
 
struct ffr {
static int[] r = [int.min, 1];
 
static int opCall(in int n) nothrow {
assert(n > 0);
if (n < r.length) {
return r[n];
} else {
immutable int ffr_n_1 = ffr(n - 1);
immutable int lastr = r[$ - 1];
// extendExtend s up to, and one past, last r.
ffs.s ~= array(iota(ffs.s[$ - 1] + 1, lastr)).array;
if (ffs.s[$ - 1] < lastr)
ffs.s ~= lastr + 1;
// accessAccess s[n - 1] temporarily extending s if necessary.
immutable size_t len_s = ffs.s.length;
immutable int ffs_n_1 = (len_s > n) ? ffs.s[n - 1] :
(n - len_s) + ffs.s[$n - 1]; :
int ans = ffr_n_1 (n - len_s) + ffs_n_1ffs.s[$ - 1];
immutable int ans = ffr_n_1 + ffs_n_1;
r ~= ans;
return ans;
Line 483 ⟶ 1,064:
 
struct ffs {
static int[] s = [int.min, 2];
 
static int opCall(in int n) nothrow {
assert(n > 0);
if (n < s.length) {
return s[n];
} else {
foreach (immutable i; ffr.r.length .. n + 2) {
ffr(i);
if (s.length > n)
return s[n];
}
assert(0false, "Whoops!");
}
}
Line 501 ⟶ 1,082:
 
void main() {
writeln(map!ffr(iota(1, 11))).map!ffr.writeln;
auto t = chain(map!ffr(iota(1, 41)), .map!ffsffr.chain(iota(1, 961)).map!ffs);
writelnt.array.sort().equal(sort(array(t)), iota(1, 1001))).writeln;
}</langsyntaxhighlight>
 
=={{header|EasyLang}}==
{{trans|C}}
<syntaxhighlight>
global rs[] ss[] .
procdecl RS_append . .
func R n .
while n > len rs[]
RS_append
.
return rs[n]
.
func S n .
while n > len ss[]
RS_append
.
return ss[n]
.
proc RS_append . .
n = len rs[]
r = R n + S n
s = S len ss[]
rs[] &= r
repeat
s += 1
until s = r
ss[] &= s
.
ss[] &= r + 1
.
rs[] = [ 1 ]
ss[] = [ 2 ]
write "R(1 .. 10): "
for i to 10
write R i & " "
.
print ""
len seen[] 1000
for i to 40
seen[R i] = 1
.
for i to 960
seen[S i] = 1
.
for i to 1000
if seen[i] = 0
print i & " not seen"
return
.
.
print "first 1000 ok"
</syntaxhighlight>
{{out}}
<pre>
R(1 .. 10): 1 3 7 12 18 26 35 45 56 69
first 1000 ok
</pre>
 
=={{header|EchoLisp}}==
<syntaxhighlight lang="scheme">(define (FFR n)
(+ (FFR (1- n)) (FFS (1- n))))
(define (FFS n)
(define next (1+ (FFS (1- n))))
(for ((k (in-naturals next)))
#:break (not (vector-search* k (cache 'FFR))) => k
))
(remember 'FFR #(0 1)) ;; init cache
(remember 'FFS #(0 2))
</syntaxhighlight>
{{out}}
<syntaxhighlight lang="scheme">
(define-macro m-range [a .. b] (range a (1+ b)))
 
(map FFR [1 .. 10])
→ (1 3 7 12 18 26 35 45 56 69)
 
;; checking
(equal? [1 .. 1000] (list-sort < (append (map FFR [1 .. 40]) (map FFS [1 .. 960]))))
→ #t</syntaxhighlight>
 
=={{header|Euler Math Toolbox}}==
 
<syntaxhighlight lang="euler math toolbox">
>function RSstep (r,s) ...
$ n=cols(r);
$ r=r|(r[n]+s[n]);
$ s=s|(max(s[n]+1,r[n]+1):r[n+1]-1);
$ return {r,s};
$ endfunction
>function RS (n) ...
$ if n==1 then return {[1],[2]}; endif;
$ if n==2 then return {[1,3],[2]}; endif;
$ r=[1,3]; s=[2,4];
$ loop 3 to n; {r,s}=RSstep(r,s); end;
$ return {r,s};
$ endfunction
>{r,s}=RS(10);
>r
[ 1 3 7 12 18 26 35 45 56 69 ]
>{r,s}=RS(50);
>all(sort(r[1:40]|s[1:960])==(1:1000))
1
</syntaxhighlight>
 
=={{header|F_Sharp|F#}}==
===The function===
<syntaxhighlight lang="fsharp">
// Populate R and S with values of Hofstadter Figure Figure sequence. Nigel Galloway: August 28th., 2020
let fF q=let R,S=Array.zeroCreate<int>q,Array.zeroCreate<int>q
R.[0]<-1;S.[0]<-2
let rec fN n g=match n=q with true->(R,S)
|_->R.[n]<-R.[n-1]+S.[n-1]
match S.[n-1]+1 with i when i<>R.[g]->S.[n]<-i; fN (n+1) g
|i->S.[n]<-i+1; fN (n+1) (g+1)
fN 1 1
</syntaxhighlight>
===The Tasks===
<syntaxhighlight lang="fsharp">
let ffr,ffs=fF 960
ffr|>Seq.take 10|>Seq.iter(printf "%d "); printfn ""
 
let N=Array.concat [|ffs;(Array.take 40 ffr)|] in printfn "Unique values=%d Minimum value=%d Maximum Value=%d" ((Array.distinct N).Length)(Array.min N)(Array.max N)
</syntaxhighlight>
{{out}}
<pre>
1 3 7 12 18 26 35 45 56 69
Unique values=1000 Minimum value=1 Maximum Value=1000
</pre>
===Unbounded n?===
n is bounded in this implementation because it is an signed 32 integer. Within such limit the 10 millionth value will have to be sufficiently unbounded. It can be found in 43 thousandths of sec.
<syntaxhighlight lang="fsharp">
let ffr,ffs=fF 10000000
printfn "%d\n%d (Array.last ffr) (Array.last ffs)
</syntaxhighlight>
1584961838
10004416
{{out}}
=={{header|Factor}}==
We keep lists S and R, and increment them when necessary.
<langsyntaxhighlight lang="factor">SYMBOL: S V{ 2 } S set
SYMBOL: R V{ 1 } R set
 
Line 528 ⟶ 1,247:
: ffr ( n -- R(n) )
dup R get length - inc-SR
1 - R get nth ;</langsyntaxhighlight>
 
<langsyntaxhighlight lang="factor">( scratchpad ) 10 iota [ 1 + ffr ] map .
{ 1 3 7 12 18 26 35 45 56 69 }
( scratchpad ) 40 iota [ 1 + ffr ] map 960 iota [ 1 + ffs ] map append 1000 iota 1 v+n set= .
t</langsyntaxhighlight>
 
=={{header|FreeBASIC}}==
{{trans|BBC BASIC}}
<syntaxhighlight lang="freebasic">function ffr( n as integer ) as integer
if n = 1 then return 1
dim as integer i, j, r=1, s=1, v(1 to 2*n+1)
v(1) = 1
for i = 2 to n
for j = s to 2*n
if v(j) = 0 then exit for
next j
v(j) = 1
s = j
r += s
if r <= 2*n then v(r) = 1
next i
return r
end function
 
function ffs( n as integer ) as integer
if n = 1 then return 2
dim as integer i, j, r=1, s=2, v(1 to 2*n+1)
for i = 1 to n
for j = s to 2*n
if v(j) = 0 then exit for
next j
v(j) = 1
s = j
r += s
if r <= 2*n then v(r) = 1
next i
return s
end function
 
dim as integer i
print " R"," S"
print
for i = 1 to 10
print ffr(i), ffs(i)
next i
 
dim as boolean found(1 to 1000), failed
for i = 1 to 40
found(ffr(i)) = true
next i
for i = 1 to 960
found(ffs(i)) = true
next i
for i = 1 to 1000
if found(i) = false then failed = true
next i
 
if failed then print "Oh no!" else print "All integers from 1 to 1000 accounted for"</syntaxhighlight>
{{out}}<pre>
R S
 
1 2
3 4
7 5
12 6
18 8
26 9
35 10
45 11
56 13
69 14
All integers from 1 to 1000 accounted for
</pre>
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 591 ⟶ 1,378:
}
fmt.Println("task 4: PASS")
}</langsyntaxhighlight>
{{out}}
Output:
<pre>
r(1): 1
Line 604 ⟶ 1,391:
r(9): 56
r(10): 69
task 4: PASS</pre>
</pre>
 
The following defines two mutually recursive generators without caching results. Each generator will end up dragging a tree of closures behind it, but due to the odd nature of the two series' growth pattern, it's still a heck of a lot faster than the above method when producing either series in sequence.
<langsyntaxhighlight lang="go">package main
import "fmt"
 
Line 656 ⟶ 1,442:
}
fmt.Println(sum)
}</langsyntaxhighlight>
 
=={{header|Haskell}}==
<langsyntaxhighlight lang="haskell">import Data.List (delete, sort)
 
-- Functions by Reinhard Zumkeller
ffr n:: = rl !! (nInt -> 1) whereInt
ffr n = rl =!! 1(n : fig- 1 [2 ..])
where
fig n (x : xs) = n' : fig n' (delete n' xs) where n' = n + x
rl = 1 : fig 1 [2 ..]
fig n (x:xs) = n_ : fig n_ (delete n_ xs)
where
n_ = n + x
 
ffs n:: =Int rl-> !! n whereInt
ffs n = rl = 2 : figDiff 1 [2!! ..]n
where
figDiff n (x : xs) = x : figDiff n' (delete n' xs) where n' = n + x
rl = 2 : figDiff 1 [2 ..]
figDiff n (x:xs) = x : figDiff n_ (delete n_ xs)
where
n_ = n + x
 
main :: IO ()
main = do
print $ mapffr ffr<$> [1 .. 10]
let i1000 = sort (mapfmap ffr [1 .. 40] ++ mapfmap ffs [1 .. 960])
print (i1000 == [1 .. 1000])</langsyntaxhighlight>
Output:
<pre>[1,3,7,12,18,26,35,45,56,69]
Line 679 ⟶ 1,474:
 
Defining R and S literally:
<langsyntaxhighlight lang="haskell">import Data.List (sort)
 
r :: [Int]
r = scanl (+) 1 s
s = 2:4:tail (compliment (tail r)) where
compliment = concat.interval
interval x = zipWith (\x y -> [x+1..y-1]) x (tail x)
 
s :: [Int]
s = 2 : 4 : tail (complement (tail r))
where
complement = concat . interval
interval x = zipWith (\x y -> [succ x .. pred y]) x (tail x)
 
main :: IO ()
main = do
putStr "R: "; print (take 10 r)
putStr "S: "; print (take 10 sr)
putStr "test 1000S: ";
print (take 10 s)
print ([1..1000] == sort ((take 40 r) ++ (take 960 s)))</lang>
putStr "test 1000: "
print $ [1 .. 1000] == sort (take 40 r ++ take 960 s)</syntaxhighlight>
output:
<pre>
Line 699 ⟶ 1,501:
 
=={{header|Icon}} and {{header|Unicon}}==
<langsyntaxhighlight Iconlang="icon">link printf,ximage
 
procedure main()
Line 757 ⟶ 1,559:
}
}
end</langsyntaxhighlight>
 
{{libheader|Icon Programming Library}}
Line 778 ⟶ 1,580:
=={{header|J}}==
 
<langsyntaxhighlight lang="j">R=: 1 1 3
S=: 0 2 4
FF=: 3 :0
Line 788 ⟶ 1,590:
)
ffr=: { 0 {:: FF@(>./@,)
ffs=: { 1 {:: FF@(0,>./@,)</langsyntaxhighlight>
 
Required examples:
 
<langsyntaxhighlight lang="j"> ffr 1+i.10
1 3 7 12 18 26 35 45 56 69
(1+i.1000) -: /:~ (ffr 1+i.40), ffs 1+i.960
1</langsyntaxhighlight>
 
=={{header|Java}}==
Line 801 ⟶ 1,603:
'''Code:'''
 
<langsyntaxhighlight lang="java">import java.util.*;
 
class Hofstadter
Line 856 ⟶ 1,658:
System.out.println("Done");
}
}</langsyntaxhighlight>
 
'''Output:'''
Line 864 ⟶ 1,666:
 
=={{header|JavaScript}}==
{{trans|Ruby}}
Translated from Ruby.
<langsyntaxhighlight JavaScriptlang="javascript">var R = [null, 1];
var S = [null, 2];
 
Line 911 ⟶ 1,713:
throw "Something's wrong!"
} else { console.log("1000 integer check ok."); }
}</langsyntaxhighlight>
Output:
<pre>R(1) = 1
Line 924 ⟶ 1,726:
R(10) = 69
1000 integer check ok.</pre>
 
=={{header|jq}}==
{{works with|jq}}
'''Works with gojq, the Go implementation of jq'''
 
In this entry, the functions `ffr` and `ffs` are defined as per the
task requirements, but neither is used. Instead, for efficiency, a
function for extending the two sequences is defined. This function is
then used to create generators, which are then harnessed
to accomplish the specific tasks.
 
<syntaxhighlight lang="jq">def init: {r: [0, 1], s: [0, 2] };
 
# input: {r,s}
# output: {r,s,emit} where .emit is either null or the next R and where either .r or .s on output has been extended.
# .emit is provided in case an unbounded stream of R values is desired.
def extend_ff:
(.r|length) as $rn
| if .s[$rn - 1]
then .emit = .r[$rn - 1] + .s[$rn - 1]
| .r[$rn] = .emit
| reduce range( [.r[$rn-1], .s[-1]] | max + 1; .r[$rn] ) as $i (.; .s += [$i] )
else .emit = null
| .s += [.r[$rn - 1] + 1]
end;
 
def ffr($n):
first(init | while(true; extend_ff) | select(.r[$n])).r[$n] ;
 
def ffs($n):
first(init | while(true; extend_ff) | select(.s[$n])).s[$n] ;
 
def task1($n):
"The first \($n) values of R are:",
(init | until( .r | length > $n; extend_ff) | .r[1:]) ;
 
def task2:
"The result of checking that the first 40 values of R and the first 960 of S together cover the interval [1,1000] is:",
( init | until( (.r|length) > 40 and (.s|length) > 960; extend_ff)
| (.r[1:41] + .s[1:961] | sort) == [range(1;1001)] ) ;
 
task1(10), task2</syntaxhighlight>
{{out}}
<pre>
The first 10 values of R are:
[1,3,7,12,18,26,35,45,56,69]
The result of checking that the first 40 values of R and the first 960 of S together cover the interval [1,1000] is:
true
</pre>
 
 
=={{header|Julia}}==
Much of this task would seem to lend itself to an iterator based solution. However, the first step calls for <tt>ffr(n)</tt> and <tt>ffs(n)</tt>, which imply that the series values are to be "randomly" rather than "sequentially" accessed. Given this implied requirement, I chose to implement <tt>ffr</tt> and <tt>ffs</tt> as closures containing the type (data structure) <tt>FigureFigure</tt>, which are used to calculate their values as required. I address task requirement 2 (no maximum n) by having these functions extend this data structure as needed to accommodate values of n larger than those used for their creation.
 
'''Functions'''
<syntaxhighlight lang="julia">
type FigureFigure{T<:Integer}
r::Array{T,1}
rnmax::T
snmax::T
snext::T
end
 
function grow!{T<:Integer}(ff::FigureFigure{T}, rnmax::T=100)
ff.rnmax < rnmax || return nothing
append!(ff.r, zeros(T, (rnmax-ff.rnmax)))
snext = ff.snext
for i in (ff.rnmax+1):rnmax
ff.r[i] = ff.r[i-1] + snext
snext += 1
while snext in ff.r
snext += 1
end
end
ff.rnmax = rnmax
ff.snmax = ff.r[end] - rnmax
ff.snext = snext
return nothing
end
 
function FigureFigure{T<:Integer}(rnmax::T=10)
ff = FigureFigure([1], 1, 0, 2)
grow!(ff, rnmax)
return ff
end
 
function FigureFigure{T<:Integer}(rnmax::T, snmax::T)
ff = FigureFigure(rnmax)
while ff.snmax < snmax
grow!(ff, 2ff.rnmax)
end
return ff
end
 
function make_ffr{T<:Integer}(nmax::T=10)
ff = FigureFigure(nmax)
function ffr{T<:Integer}(n::T)
if n > ff.rnmax
grow!(ff, 2n)
end
ff.r[n]
end
end
 
function make_ffs{T<:Integer}(nmax::T=100)
ff = FigureFigure(13, nmax)
function ffs{T<:Integer}(n::T)
while ff.snmax < n
grow!(ff, 2ff.rnmax)
end
s = n
for r in ff.r
r <= s || return s
s += 1
end
end
end
</syntaxhighlight>
 
'''Main'''
<syntaxhighlight lang="julia">
NR = 40
NS = 960
ffr = make_ffr(NR)
ffs = make_ffs(NS)
 
hi = 10
print("The first ", hi, " values of R are:\n ")
for i in 1:hi
print(ffr(i), " ")
end
println()
 
tally = falses(NR+NS)
iscontained = true
for i in 1:NR
try
tally[ffr(i)] = true
catch
iscontained = false
end
end
for i in 1:NS
try
tally[ffs(i)] = true
catch
iscontained = false
end
end
 
println()
print("The first ", NR, " values of R and ", NS, " of S are ")
if !iscontained
print("not ")
end
println("contained in the interval 1:", NR+NS, ".")
print("These values ")
if !all(tally)
print("do not ")
end
println("cover the entire interval.")
</syntaxhighlight>
 
{{out}}
<pre>
The first 10 values of R are:
1 3 7 12 18 26 35 45 56 69
 
The first 40 values of R and 960 of S are contained in the interval 1:1000.
These values cover the entire interval.
</pre>
 
=={{header|Kotlin}}==
Translated from Java.
<syntaxhighlight lang="scala">fun ffr(n: Int) = get(n, 0)[n - 1]
 
fun ffs(n: Int) = get(0, n)[n - 1]
 
internal fun get(rSize: Int, sSize: Int): List<Int> {
val rlist = arrayListOf(1, 3, 7)
val slist = arrayListOf(2, 4, 5, 6)
val list = if (rSize > 0) rlist else slist
val targetSize = if (rSize > 0) rSize else sSize
 
while (list.size > targetSize)
list.removeAt(list.size - 1)
while (list.size < targetSize) {
val lastIndex = rlist.lastIndex
val lastr = rlist[lastIndex]
val r = lastr + slist[lastIndex]
rlist += r
var s = lastr + 1
while (s < r && list.size < targetSize)
slist += s++
}
return list
}
 
fun main(args: Array<String>) {
print("R():")
(1..10).forEach { print(" " + ffr(it)) }
println()
 
val first40R = (1..40).map { ffr(it) }
val first960S = (1..960).map { ffs(it) }
val indices = (1..1000).filter { it in first40R == it in first960S }
indices.forEach { println("Integer $it either in both or neither set") }
println("Done")
}</syntaxhighlight>
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
 
1. Create two functions named ffr and ffs that when given n return R(n) or S(n) respectively.
The instructions call for two functions.
Because S[n] is generated while computing R[n], one would normally avoid redundancy by combining
R and S into a single function that returns both sequences.
 
2. No maximum value for n should be assumed.
 
<syntaxhighlight lang="mathematica">
ffr[j_] := Module[{R = {1}, S = 2, k = 1},
Do[While[Position[R, S] != {}, S++]; k = k + S; S++;
R = Append[R, k], {n, 1, j - 1}]; R]
 
ffs[j_] := Differences[ffr[j + 1]]
</syntaxhighlight>
 
3. Calculate and show that the first ten values of R are: 1, 3, 7, 12, 18, 26, 35, 45, 56, and 69
 
<syntaxhighlight lang="mathematica">
ffr[10]
 
(* out *)
{1, 3, 7, 12, 18, 26, 35, 45, 56, 69}
</syntaxhighlight>
 
4. Calculate and show that the first 40 values of ffr plus the first 960 values of ffs include all the integers from 1 to 1000 exactly once.
 
<syntaxhighlight lang="mathematica">
t = Sort[Join[ffr[40], ffs[960]]];
 
t == Range[1000]
 
(* out *)
True
</syntaxhighlight>
 
=={{header|MATLAB}} / {{header|Octave}}==
Line 930 ⟶ 1,978:
2. No maximum value for n should be assumed.
 
<langsyntaxhighlight MATLABlang="matlab"> function [R,S] = ffr_ffs(N)
t = [1,0];
T = 1;
Line 953 ⟶ 2,001:
printf('Sequence S:\n'); disp(S);
end;
end; </langsyntaxhighlight>
 
3. Calculate and show that the first ten values of R are: 1, 3, 7, 12, 18, 26, 35, 45, 56, and 69
Line 971 ⟶ 2,019:
all(sort([R1,S2])==1:1000)
ans = 1
</pre>
 
=={{header|Nim}}==
<syntaxhighlight lang="nim">var cr = @[1]
var cs = @[2]
 
proc extendRS =
let x = cr[cr.high] + cs[cr.high]
cr.add x
for y in cs[cs.high] + 1 ..< x: cs.add y
cs.add x + 1
 
proc ffr(n: int): int =
assert n > 0
while n > cr.len: extendRS()
cr[n - 1]
 
proc ffs(n: int): int =
assert n > 0
while n > cs.len: extendRS()
cs[n - 1]
 
for i in 1..10: stdout.write ffr i," "
echo ""
 
var bin: array[1..1000, int]
for i in 1..40: inc bin[ffr i]
for i in 1..960: inc bin[ffs i]
var all = true
for x in bin:
if x != 1:
all = false
break
 
if all: echo "All Integers 1..1000 found OK"
else: echo "All Integers 1..1000 NOT found only once: ERROR"</syntaxhighlight>
Output:
<pre>/home/deen/git/nim-unsorted/hofstadter
1 3 7 12 18 26 35 45 56 69
All Integers 1..1000 found OK</pre>
 
=={{header|Oforth}}==
<syntaxhighlight lang="oforth">tvar: R
ListBuffer new 1 over add R put
 
tvar: S
ListBuffer new 2 over add S put
 
: buildnext
| r s current i |
R at ->r
S at ->s
r last r size s at + dup ->current r add
s last 1+ current 1- for: i [ i s add ]
current 1+ s add ;
 
: ffr(n)
while ( R at size n < ) [ buildnext ]
n R at at ;
 
: ffs(n)
while ( S at size n < ) [ buildnext ]
n S at at ;</syntaxhighlight>
 
Output :
<pre>
>#[ ffr . ] 10 seqEach
1 3 7 12 18 26 35 45 56 69
ok
>#ffr 40 seq map #ffs 960 seq map + sort 1000 seq == .
1 ok
</pre>
 
=={{header|Perl}}==
The program produces a table with the first 10 values of R and S. It also calculates
R(40) which is 982, S(960) which is 1000, and R(41) which is 1030.
 
Then we go through the first 1000 outputs, mark those which are seen, then check if all values in the range one through one thousand were seen.
 
<syntaxhighlight lang="perl">#!perl
use strict;
use warnings;
 
my @r = ( undef, 1 );
my @s = ( undef, 2 );
sub ffsr {
my $n = shift;
while( $#r < $n ) {
push @r, $s[$#r]+$r[-1];
push @s, grep { $s[-1]<$_ } $s[-1]+1..$r[-1]-1, $r[-1]+1;
}
return $n;
}
sub ffr { $r[ffsr shift] }
sub ffs { $s[ffsr shift] }
printf " i: R(i) S(i)\n";
printf "==============\n";
printf "%3d: %3d %3d\n", $_, ffr($_), ffs($_) for 1..10;
printf "\nR(40)=%3d S(960)=%3d R(41)=%3d\n", ffr(40), ffs(960), ffr(41);
 
my %seen;
$seen{ffr($_)}++ for 1 .. 40;
$seen{ffs($_)}++ for 1 .. 960;
if( 1000 == keys %seen and grep $seen{$_}, 1 .. 1000 ) {
print "All occured exactly once.\n";
} else {
my @missed = grep !$seen{$_}, 1 .. 1000;
my @dupped = sort { $a <=> $b} grep $seen{$_}>1, keys %seen;
print "These were missed: @missed\n";
print "These were duplicated: @dupped\n";
}
</syntaxhighlight>
 
=={{header|Phix}}==
Initialising such that length(S)>length(F) simplified things significantly.
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">F</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">3</span><span style="color: #0000FF;">,</span><span style="color: #000000;">7</span><span style="color: #0000FF;">},</span>
<span style="color: #000000;">S</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">2</span><span style="color: #0000FF;">,</span><span style="color: #000000;">4</span><span style="color: #0000FF;">,</span><span style="color: #000000;">5</span><span style="color: #0000FF;">,</span><span style="color: #000000;">6</span><span style="color: #0000FF;">}</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">fmax</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">3</span> <span style="color: #000080;font-style:italic;">-- (ie F[3], ==7, already in S)</span>
<span style="color: #008080;">forward</span> <span style="color: #008080;">function</span> <span style="color: #000000;">ffs</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">ffr</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">l</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">F</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">while</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">></span><span style="color: #000000;">l</span> <span style="color: #008080;">do</span>
<span style="color: #000000;">F</span> <span style="color: #0000FF;">&=</span> <span style="color: #000000;">F</span><span style="color: #0000FF;">[</span><span style="color: #000000;">l</span><span style="color: #0000FF;">]+</span><span style="color: #000000;">ffs</span><span style="color: #0000FF;">(</span><span style="color: #000000;">l</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">l</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">F</span><span style="color: #0000FF;">[</span><span style="color: #000000;">n</span><span style="color: #0000FF;">]</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">ffs</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">while</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">></span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">S</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
<span style="color: #000000;">fmax</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">fmax</span><span style="color: #0000FF;">></span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">F</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span> <span style="color: #0000FF;">{}</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">ffr</span><span style="color: #0000FF;">(</span><span style="color: #000000;">fmax</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #000000;">S</span> <span style="color: #0000FF;">&=</span> <span style="color: #7060A8;">tagset</span><span style="color: #0000FF;">(</span><span style="color: #000000;">lim</span><span style="color: #0000FF;">:=</span><span style="color: #000000;">F</span><span style="color: #0000FF;">[</span><span style="color: #000000;">fmax</span><span style="color: #0000FF;">]-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">start</span><span style="color: #0000FF;">:=</span><span style="color: #000000;">F</span><span style="color: #0000FF;">[</span><span style="color: #000000;">fmax</span><span style="color: #0000FF;">-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)</span>
<span style="color: #000080;font-style:italic;">-- ie/eg if fmax was 3, then F[2..3] being {3,7}
-- ==&gt; tagset(lim:=6,start:=4), ie {4,5,6}.</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">S</span><span style="color: #0000FF;">[</span><span style="color: #000000;">n</span><span style="color: #0000FF;">]</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #0000FF;">{}</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">ffr</span><span style="color: #0000FF;">(</span><span style="color: #000000;">10</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- (or collect one by one)</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"The first ten values of R: %v\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">F</span><span style="color: #0000FF;">[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">..</span><span style="color: #000000;">10</span><span style="color: #0000FF;">]})</span>
<span style="color: #0000FF;">{}</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">ffr</span><span style="color: #0000FF;">(</span><span style="color: #000000;">40</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- (not actually needed)</span>
<span style="color: #0000FF;">{}</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">ffs</span><span style="color: #0000FF;">(</span><span style="color: #000000;">960</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">if</span> <span style="color: #7060A8;">sort</span><span style="color: #0000FF;">(</span><span style="color: #000000;">F</span><span style="color: #0000FF;">[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">..</span><span style="color: #000000;">40</span><span style="color: #0000FF;">]&</span><span style="color: #000000;">S</span><span style="color: #0000FF;">[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">..</span><span style="color: #000000;">960</span><span style="color: #0000FF;">])=</span><span style="color: #7060A8;">tagset</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1000</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span>
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"test passed\n"</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">else</span>
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"some error!\n"</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<!--</syntaxhighlight>-->
{{out}}
<pre>
The first ten values of R: {1,3,7,12,18,26,35,45,56,69}
test passed
</pre>
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(setq *RNext 2)
 
(de ffr (N)
(cache '(NIL) (pack (char (hash N)) N)
(if (= 1 N)
1
Line 983 ⟶ 2,191:
 
(de ffs (N)
(cache '(NIL) (pack (char (hash N)) N)
(if (= 1 N)
2
Line 990 ⟶ 2,198:
(inc 'S)
(inc '*RNext) )
S ) ) ) )</langsyntaxhighlight>
Test:
<langsyntaxhighlight PicoLisplang="picolisp">: (mapcar ffr (range 1 10))
-> (1 3 7 12 18 26 35 45 56 69)
 
Line 998 ⟶ 2,206:
(range 1 1000)
(sort (conc (mapcar ffr (range 1 40)) (mapcar ffs (range 1 960)))) )
-> T</langsyntaxhighlight>
 
=={{header|Perl 6}}==
 
<lang perl6>my @ffr;
my @ffs;
 
@ffr.plan: 0, 1, gather take @ffr[$_] + @ffs[$_] for 1..*;
@ffs.plan: 0, 2, 4..6, gather take @ffr[$_] ^..^ @ffr[$_+1] for 3..*;
 
say @ffr[1..10];
 
say "Rawks!" if (1...1000) eqv sort @ffr[1..40], @ffs[1..960];</lang>
Output:
<pre>
1 3 7 12 18 26 35 45 56 69
Rawks!</pre>
 
=={{header|PL/I}}==
<langsyntaxhighlight PL/Ilang="pli">ffr: procedure (n) returns (fixed binary(31));
declare n fixed binary (31);
declare v(2*n+1) bit(1);
Line 1,039 ⟶ 2,231:
end;
return (r);
end ffr;</langsyntaxhighlight>
Output:
<pre>
Line 1,047 ⟶ 2,239:
602 640 679 719 760 802 845 889 935 982
</pre>
<syntaxhighlight lang="pli">ffs: procedure (n) returns (fixed binary (31));
declare n fixed binary (31);
declare v(2*n+1) bit(1);
Line 1,069 ⟶ 2,261:
end;
return (s);
end ffs;</langsyntaxhighlight>
Output of first 960 values:
<pre>
Line 1,079 ⟶ 2,271:
</pre>
Verification using the above procedures:
<syntaxhighlight lang="pli">
Dcl t(1000) Bit(1) Init((1000)(1)'0'b);
put skip list ('Verification that the first 40 FFR numbers and the first');
put skip list ('960 FFS numbers result in the integers 1 to 1000 only.');
Line 1,093 ⟶ 2,286:
end;
if all(t = '1'b) then put skip list ('passed test');
</syntaxhighlight>
</lang>
Output:
<pre>
Line 1,105 ⟶ 2,298:
CHR is a programming language created by '''Professor Thom Frühwirth'''.<br>
Works with SWI-Prolog and module '''chr''' written by '''Tom Schrijvers''' and '''Jan Wielemaker'''
<langsyntaxhighlight Prologlang="prolog">:- use_module(library(chr)).
 
:- chr_constraint ffr/2, ffs/2, hofstadter/1,hofstadter/2.
Line 1,131 ⟶ 2,324:
hofstadter(N), ffr(N1, _R), ffs(N1, _S) ==> N1 < N, N2 is N1 +1 | ffr(N2,_), ffs(N2,_).
 
</syntaxhighlight>
</lang>
Output for first task :
<pre> ?- hofstadter(10), bagof(ffr(X,Y), find_chr_constraint(ffr(X,Y)), L).
Line 1,159 ⟶ 2,352:
 
Code for the second task
<langsyntaxhighlight Prologlang="prolog">hofstadter :-
hofstadter(960),
% fetch the values of ffr
Line 1,173 ⟶ 2,366:
% to remove all pending constraints
fail.
</syntaxhighlight>
</lang>
Output for second task
<pre> ?- hofstadter.
Line 1,181 ⟶ 2,374:
 
=={{header|Python}}==
<langsyntaxhighlight lang="python">def ffr(n):
if n < 1 or type(n) != int: raise ValueError("n must be an int >= 1")
try:
Line 1,226 ⟶ 2,419:
print("All Integers 1..1000 found OK")
else:
print("All Integers 1..1000 NOT found only once: ERROR")</langsyntaxhighlight>
 
;Output:
Line 1,233 ⟶ 2,426:
 
===Alternative===
<langsyntaxhighlight lang="python">cR = [1]
cS = [2]
 
Line 1,261 ⟶ 2,454:
 
# the fact that we got here without a key error
print("Ok")</langsyntaxhighlight>output<syntaxhighlight lang="text">[1, 3, 7, 12, 18, 26, 35, 45, 56, 69]
Ok</langsyntaxhighlight>
 
 
===Using cyclic iterators===
{{trans|Haskell}}
Defining R and S as mutually recursive generators. Follows directly from the definition of the R and S sequences.
<langsyntaxhighlight lang="python">from itertools import islice
 
def R():
Line 1,293 ⟶ 2,485:
 
# perf test case
# print sum(lst(R, 10000000))</langsyntaxhighlight>
{{out}}
<pre>R: [1, 3, 7, 12, 18, 26, 35, 45, 56, 69]
Line 1,299 ⟶ 2,491:
True
</pre>
 
=={{header|Quackery}}==
 
<code>from</code>, <code>index</code>, and <code>end</code> are defined at [[Loops/Increment loop index within loop body#Quackery]].
 
As with the Phix solution, initialising to the first few elements simplified things significantly.
 
<syntaxhighlight lang="Quackery">
[ ' [ 1 3 7 ]
' [ 2 4 5 6 ] ] is initialise ( --> r s )
 
[ over size 1 -
over swap peek
dip [ over -1 peek ]
+ swap dip join
over -2 split nip do
temp put
1 + from
[ temp share
index = iff
end done
index join ]
temp release ] is extend ( r s --> r s )
 
[ temp put
[ over size
temp share < while
extend again ]
over
temp take 1 - peek ] is ffr ( r s n --> r s n )
 
[ temp put
[ dup size
temp share < while
extend again ]
dup
temp take 1 - peek ] is ffs ( r s n --> r s n )
 
initialise
say "R(1)..R(10): "
10 times
[ i^ 1+ ffr echo sp ]
cr cr
960 ffs drop
960 split drop
dip [ 40 split drop ]
join sort
[] 1000 times
[ i^ 1+ join ]
!=
say "All integers from 1 to 1000"
if say " not"
say " found once and only once."</syntaxhighlight>
 
{{out}}
 
<pre>R(1)..R(10): 1 3 7 12 18 26 35 45 56 69
 
All integers from 1 to 1000 found once and only once.</pre>
 
=={{header|R}}==
Global variables aren't idiomatic R, but this is otherwise an ideal task for the language. Comments aside, this is easily one of the shortest solutions on this page. This is mostly due to how R treats most things as a vector. For example, rValues starts out as the number 1, but repeatedly has new values appended to it without much ceremony.
<syntaxhighlight lang="rsplus">rValues <- 1
sValues <- 2
ffr <- function(n)
{
if(!is.na(rValues[n])) rValues[n] else (rValues[n] <<- ffr(n-1) + ffs(n-1))
}
 
#In theory, generating S requires computing ALL values not in R.
#That would be infinitely many values.
#However, to generate S(n) we only need to observe that its value cannot exceed R(n)+1.
ffs <- function(n)
{
if(!is.na(sValues[n])) sValues[n] else (sValues[n] <<- setdiff(seq_len(1 + ffr(n)), rValues)[n])
}
 
#Task 1
invisible(ffr(10))
print(rValues)
 
#Task 2
#If we try to call ffs(960) directly, R will complain about the stack being too big.
#Calling ffs(500) first solves this problem.
invisible(ffs(500))
invisible(ffs(960))
#In R, "the first 40 values of ffr plus the first 960 values of ffs" can easily be misread.
#rValues[1:40]+sValues[1:960] is valid R code. It will duplicate the first 40 rValues 23
#times, append them to the original, and add that vector to the first 960 sValues.
This gives an output of length 960, which clearly cannot contain 1000 different values.
#Presumably, the task wants us to append rValues[1:40] and sValues[1:960].
print(table(c(rValues[1:40], sValues[1:960])))</syntaxhighlight>
{{out}}
<pre>> print(rValues)
[1] 1 3 7 12 18 26 35 45 56 69
> print(table(c(rValues[1:40], sValues[1:960])))
 
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
989 990 991 992 993 994 995 996 997 998 999 1000
1 1 1 1 1 1 1 1 1 1 1 1 </pre>
 
=={{header|Racket}}==
{{trans|Java}}
 
We store the values of r and s in hash-tables. The first values are added by hand. The procedure extend-r-s! adds more values.
 
<syntaxhighlight lang="racket">#lang racket/base
 
(define r-cache (make-hash '((1 . 1) (2 . 3) (3 . 7))))
(define s-cache (make-hash '((1 . 2) (2 . 4) (3 . 5) (4 . 6))))
 
(define (extend-r-s!)
(define r-count (hash-count r-cache))
(define s-count (hash-count s-cache))
(define last-r (ffr r-count))
(define new-r (+ (ffr r-count) (ffs r-count)))
(hash-set! r-cache (add1 r-count) new-r)
(define offset (- s-count last-r))
(for ([val (in-range (add1 last-r) new-r)])
(hash-set! s-cache (+ val offset) val)))</syntaxhighlight>
 
The functions ffr and ffs simply retrieve the value from the hash table if it exist, or call extend-r-s until they are long enought.
 
<syntaxhighlight lang="racket">(define (ffr n)
(hash-ref r-cache n (lambda () (extend-r-s!) (ffr n))))
(define (ffs n)
(hash-ref s-cache n (lambda () (extend-r-s!) (ffs n))))</syntaxhighlight>
 
Tests:
<syntaxhighlight lang="racket">(displayln (map ffr (list 1 2 3 4 5 6 7 8 9 10)))
(displayln (map ffs (list 1 2 3 4 5 6 7 8 9 10)))
 
(displayln "Checking for first 1000 integers:")
(displayln (if (equal? (sort (append (for/list ([i (in-range 1 41)])
(ffr i))
(for/list ([i (in-range 1 961)])
(ffs i)))
<)
(for/list ([i (in-range 1 1001)])
i))
"Test passed"
"Test failed"))</syntaxhighlight>
 
'''Sample Output:'''
<pre>(1 3 7 12 18 26 35 45 56 69)
(2 4 5 6 8 9 10 11 13 14)
Checking for first 1000 integers: Test passed</pre>
 
=={{header|Raku}}==
(formerly Perl 6)
{{works with|Rakudo|2018.03}}
<syntaxhighlight lang="raku" line>my %r = 1 => 1;
my %s = 1 => 2;
 
sub ffr ($n) { %r{$n} //= ffr($n - 1) + ffs($n - 1) }
sub ffs ($n) { %s{$n} //= (grep none(map &ffr, 1..$n), max(%s.values)+1..*)[0] }
 
my @ffr = map &ffr, 1..*;
my @ffs = map &ffs, 1..*;
 
say @ffr[^10];
say "Rawks!" if 1...1000 eqv sort |@ffr[^40], |@ffs[^960];</syntaxhighlight>
Output:
<pre>
1 3 7 12 18 26 35 45 56 69
Rawks!</pre>
 
=={{header|REXX}}==
This REXX example makes use of spare arrays.
<lang rexx>/*REXX pgm to calculate & verify the Hofstadter Figure-Figure sequences.*/
parse arg x highV . /*obtain any C.L. specifications.*/
if x=='' then x=10; if highV=='' then highV=1000 /*use the defaults?*/
low=1 /*use unity as the starting point*/
if x<0 then low=abs(x) /*only show a single │X│ value.*/
r.=0; r.1=1; rr.=r.; rr.1=1 /*initialize the R and RR arrays.*/
s.=0; s.1=2; ss.=s.; ss.2=1 /* " ? S " SS " .*/
errs=0
do i=low to abs(x) /*show first X values of R & S */
say right('R('i") =",20) right(ffr(i),7), /*show nice*/
right('S('i") =",20) right(ffs(i),7) /* R & S */
end /*i*/
if x<1 then exit /*stick a fork in it, we're done.*/
/*═══════════════════════════════════════verify 1st 1k: unique & present*/
both.=0 /*initialize the BOTH array. */
/*build list of 1st 40 R values.*/
do m=1 for 40; r=ffr(m) /*calculate 1st 40 R values.*/
both.r=1 /*build the BOTH array. */
end /*m*/
 
===version 1===
do n=1 for 960; s=ffs(n) /*calculate 1st 960 S values.*/
This REXX example makes use of sparse arrays.
if both.s then call sayErr 'duplicate number in R and S lists:' s
 
both.s=1 /*add to the BOTH array. */
Over a third of the program was for verification of the first thousand numbers in the Hofstadter Figure-Figure sequences.
end /*n*/
 
/*verify presence and uniqueness.*/
This REXX version is over &nbsp; '''15,000%''' &nbsp; faster than REXX version 2.
do v=1 for highV /*verify all 1 ≤ # ≤ 1k present.*/
<syntaxhighlight lang="rexx">/*REXX program calculates and verifies the Hofstadter Figure─Figure sequences. */
if \both.v then call sayErr 'missing R │ S:' v
parse arg x top bot . /*obtain optional arguments from the CL*/
end /*v*/
if x=='' | x=="," then x= 10 /*Not specified? Then use the default.*/
if top=='' | top=="," then top=1000 /* " " " " " " */
if bot=='' | bot=="," then bot= 40 /* " " " " " " */
low=1; if x<0 then low=abs(x) /*only display a single │X│ value? */
r.=0; r.1=1; rr.=r.; rr.1=1; s.=r.; s.1=2 /*initialize the R, RR, and S arrays.*/
errs=0 /*the number of errors found (so far).*/
do i=low to abs(x) /*display the 1st X values of R & S.*/
say right('R('i") =",20) right(FFR(i),7) right('S('i") =",20) right(FFS(i),7)
end /*i*/
/* [↑] list the 1st X Fig─Fig numbers.*/
if x<1 then exit /*if X isn't positive, then we're done.*/
$.=0 /*initialize the memoization ($) array.*/
do m=1 for bot; r=FFR(m); $.r=1 /*calculate the first forty R values.*/
end /*m*/ /* [↑] ($.) is used for memoization. */
/* [↓] check for duplicate #s in R & S*/
do n=1 for top-bot; s=FFS(n) /*calculate the value of FFS(n). */
if $.s then call ser 'duplicate number in R and S lists:' s; $.s=1
end /*n*/ /* [↑] calculate the 1st 960 S values.*/
/* [↓] check for missing values in R│S*/
do v=1 for top; if \$.v then call ser 'missing R │ S:' v
end /*v*/ /* [↑] are all 1≤ numbers ≤1k present?*/
say
@vif errs==0 then say 'verification completed for all numbers from 1 ──►'; @i=top " [inclusive]." /*shortcuts to shorten prog width*/
else say 'verification failed with' errs "errors."
if errs==0 then say @v 'completed for all numbers from 1 ──►' highV @i
exit /*stick a fork in it, we're all done. */
else say @v 'failed with' errs "errors."
/*──────────────────────────────────────────────────────────────────────────────────────*/
exit /*stick a fork in it, we're done.*/
FFR: procedure expose r. rr. s.; parse arg n /*obtain the number from the arguments.*/
/*──────────────────────────────────FFR subroutine──────────────────────*/
if r.n\==0 then return r.n /*R.n defined? Then return the value.*/
ffr: procedure expose r. s. rr. ss.; parse arg n
if r.n\==0 then return r._=FFR(n-1) + FFS(n-1) /*Defined?calculate Thenthe return theFFR and FFS valuevalues.*/
_=ffr( r.n-1)+ffs(n-1)=_; rr._=1; return _ /*calculateassign the value FFRto R value. & RR; return.*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
r.n=_; rr._=1 /*assign the value to R and RR.*/
FFS: procedure expose r. s. rr.; parse arg n /*search for not null R or S number. */
return _ /*return the value to the invoker*/
if s.n==0 then do k=1 for n /* [↓] 1st IF is a SHORT CIRCUIT. */
/*──────────────────────────────────FFS subroutine──────────────────────*/
if s.k\==0 then if r.k\==0 then iterate /*are both defined?*/
ffs: procedure expose r. s. rr. ss.; parse arg n
do call FFR k=1 for n while s.n==0 /*searchdefine for notR.k null via Rthe SFFR num. subroutine*/
km=k-1; _=s.km+1 /*calc. the next S number, possibly.*/
if s.k\==0 & ffr(k)\==0 then iterate
km=k-1; _=_+rr._; s.km+1k=_ /*thedefine nextan element SSof number,the possibly S array. */
_=_+rr._ end /*maybe adjust for the FRR num.k*/
return s.n s.k=_; ss._=1 /*definereturn couple of S.n FFS numbersvalue to the invoker. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
end /*k*/
returnser: s.nerrs=errs+1; say '***error***' arg(1); /*return the value to the invoker* return</syntaxhighlight>
To see the talk section about this REXX program's timings, click here: &nbsp; &nbsp; [http://rosettacode.org/wiki/Talk:Hofstadter_Figure-Figure_sequences#timings_for_the_REXX_solutions timings for the REXX solutions]. <br>
/*──────────────────────────────────SAYERR subroutine───────────────────*/
 
sayErr: errs=errs+1; say; say '***error***!'; say; say arg(1); say; return</lang>
'''output''' &nbsp; when using the defaultsdefault inputs:
<pre>
<pre style="overflow:scroll">
R(1) = 1 S(1) = 2
R(2) = 3 S(2) = 4
Line 1,366 ⟶ 2,829:
 
verification completed for all numbers from 1 ──► 1000 [inclusive].
</pre>
 
===Version 2 from PL/I ===
<syntaxhighlight lang="rexx">/* REXX **************************************************************
* 21.11.2012 Walter Pachl transcribed from PL/I
**********************************************************************/
Call time 'R'
Say 'Verification that the first 40 FFR numbers and the first'
Say '960 FFS numbers result in the integers 1 to 1000 only.'
t.=0
num.=''
do i = 1 to 40
j = ffr(i)
if t.j then Say 'error, duplicate value at ' || i
else t.j = 1
num.i=j
end
nn=0
Say time('E') 'seconds elapsed'
Do i=1 To 3
ol=''
Do j=1 To 15
nn=nn+1
ol=ol right(num.nn,3)
End
Say ol
End
do i = 1 to 960
j = ffs(i)
if t.j then
Say 'error, duplicate value at ' || i
else t.j = 1
end
Do i=1 To 1000
if t.i=0 Then
Say i 'was not set'
End
If i>1000 Then
Say 'passed test'
Say time('E') 'seconds elapsed'
Exit
 
ffr: procedure Expose v.
Parse Arg n
v.= 0
v.1 = 1
if n = 1 then return 1
r = 1
do i = 2 to n
do j = 2 to 2*n
if v.j = 0 then leave
end
v.j = 1
s = j
r = r + s
if r <= 2*n then v.r = 1
end
return r
 
ffs: procedure Expose v.
Parse Arg n
v.= 0
v.1 = 1
if n = 1 then return 2
r = 1
do i = 1 to n
do j = 2 to 2*n
if v.j = 0 then leave
end
v.j = 1
s = j
r = r + s
if r <= 2*n then v.r = 1
end
return s</syntaxhighlight>
{{out}}
<pre>Verification that the first 40 FFR numbers and the first
960 FFS numbers result in the integers 1 to 1000 only.
0.011000 seconds elapsed
1 3 7 12 18 26 35 45 56 69 83 98 114 131 150
170 191 213 236 260 285 312 340 369 399 430 462 495 529 565
602 640 679 719 760 802 845 889 935 982
passed test
Windows (ooRexx) 33.183000 seconds elapsed
Windows (Regina) 22.627000 seconds elapsed
TSO interpreted: 139.699246 seconds elapsed
TSO compiled: 9.749457 seconds elapsed</pre>
 
=={{header|Ring}}==
<syntaxhighlight lang="ring">
# Project : Hofstadter Figure-Figure sequences
 
hofr = list(20)
hofr[1] = 1
hofs = []
add(hofs,2)
for n = 1 to 10
hofr[n+1] = hofr[n] + hofs[n]
if n = 1
add(hofs,4)
else
for p = hofr[n] + 1 to hofr[n+1] - 1
if p != hofs[n]
add(hofs,p)
ok
next
ok
next
see "First 10 values of R:" + nl
showarray(hofr)
see "First 10 values of S:" + nl
showarray(hofs)
 
func showarray(vect)
svect = ""
for n = 1 to 10
svect = svect + vect[n] + " "
next
svect = left(svect, len(svect) - 1)
see svect + nl
</syntaxhighlight>
Output:
<pre>
First 10 values of R:
1 3 7 12 18 26 35 45 56 69
First 10 values of S:
2 4 5 6 8 9 10 11 13 14
</pre>
 
=={{header|RPL}}==
{{works with|Halcyon Calc|4.2.8}}
{| class="wikitable"
! RPL code
! Comment
|-
|
≪ { 1 3 } 'R' STO { 2 } 'S' STO
≫ ''''INITFF'''' STO
S DUP SIZE GET
'''DO''' 1 + '''UNTIL''' R OVER POS NOT '''END'''
S OVER + 'S' STO
R DUP SIZE GET + R SWAP + 'R' STO
≫ ''''NXTFF'''' STO
'''WHILE''' R SIZE OVER < '''REPEAT NXTFF END'''
R SWAP GET
≫ ''''FFR'''' STO
'''WHILE''' S SIZE OVER < '''REPEAT NXTFF END'''
S SWAP GET
≫ ''''FFS'''' STO
≪ '''INITFF'''
40 '''FFR''' DROP R
960 '''FFS''' DROP S +
1 SF 1 1000 '''FOR''' j
'''IF''' DUP j POS NOT '''THEN''' 1 CF '''END NEXT''' DROP
1 FS? "Passed" "Failed" IFTE
≫ ''''TASK4'''' STO
|
'''INITFF''' ''( -- ) ''
Initialize R(1..2) and S(1)
'''NXTFF''' ''( -- ) ''
n = last stored item of S()
n += 1 until n not in R()
append n to S()
append (n + last item of R()) to R()
'''FFR''' ''( n -- R(n) ) ''
if R(n) not stored, develop R()
Get R(n)
'''FFS''' ''( n -- S(n) ) ''
if S(n) not stored, develop S()
Get S(n)
'''TASK4''' ''( -- "Result" ) ''
Get R(40) and put R(1..40) in stack
Get S(960), append S(1..960) to R(1..40)
set flag ; for j=1 to 1000
if j not in the merged list then clear flag
Flag is still set iff all 1..1000 were in list once
|}
{{in}}
<pre>
10 FFR DROP R
TASK4
</pre>
{{out}}
<pre>
2: { 1 3 7 12 18 26 35 45 56 69 }
1: "Passed"
</pre>
 
=={{header|Ruby}}==
{{trans|Tcl}}
<langsyntaxhighlight lang="ruby">$r = [nil, 1]
$s = [nil, 2]
 
Line 1,411 ⟶ 3,075:
assert_equal(rs_values, Set.new( 1..1000 ))
end
end</langsyntaxhighlight>
 
outputs
Line 1,420 ⟶ 3,084:
 
2 tests, 2 assertions, 0 failures, 0 errors, 0 skips</pre>
===Using cyclic iterators===
{{trans|Python}}
<syntaxhighlight lang="ruby">R = Enumerator.new do |y|
y << n = 1
S.each{|s_val| y << n += s_val}
end
 
S = Enumerator.new do |y|
y << 2
y << 4
u = 5
R.each do |r_val|
next if u > r_val
(u...r_val).each{|r| y << r}
u = r_val+1
end
end
 
p R.take(10)
p S.take(10)
p (R.take(40)+ S.take(960)).sort == (1..1000).to_a
</syntaxhighlight>
{{out}}
<pre>
[1, 3, 7, 12, 18, 26, 35, 45, 56, 69]
[2, 4, 5, 6, 8, 9, 10, 11, 13, 14]
true
</pre>
 
=={{header|Rust}}==
<syntaxhighlight lang="rust">
use std::collections::HashMap;
 
struct Hffs {
sequence_r: HashMap<usize, usize>,
sequence_s: HashMap<usize, usize>,
}
 
impl Hffs {
fn new() -> Hffs {
Hffs {
sequence_r: HashMap::new(),
sequence_s: HashMap::new(),
}
}
fn ffr(&mut self, n: usize) -> usize {
// first try the cache
let new_r = if let Some(result) = self.sequence_r.get(&n) {
*result
} else if n == 0 {
1
} else {
// call recursively
self.ffr(n - 1) + self.ffs(n - 1)
};
 
// insert into the cache and return value
*self.sequence_r.entry(n).or_insert(new_r)
}
 
fn ffs(&mut self, n: usize) -> usize {
// first try the cache
let new_s = if let Some(result) = self.sequence_s.get(&n) {
*result
} else if n == 0 {
2
} else {
let lower = self.ffs(n - 1) + 1_usize;
let upper = self.ffr(n) + 1_usize;
let mut min_s: usize = 0;
// find next available S
for i in lower..=upper {
if !self.sequence_r.values().any(|&val| val == i) {
min_s = i;
break;
}
}
min_s
};
 
// insert into the cache and return value
*self.sequence_s.entry(n).or_insert(new_s)
}
}
 
impl Default for Hffs {
fn default() -> Self {
Self::new()
}
}
fn main() {
let mut hof = Hffs::new();
 
for i in 0..10 {
println!("H:{} -> R: {}, S: {}", i, hof.ffr(i), hof.ffs(i));
}
 
let r40 = (0..40).map(|i| hof.ffr(i)).collect::<Vec<_>>();
let mut s960 = (0..960).map(|i| hof.ffs(i)).collect::<Vec<_>>();
 
s960.extend(&r40);
s960.sort_unstable();
let f1000 = (1_usize..=1000).collect::<Vec<_>>();
 
assert_eq!(f1000, s960, "Does NOT match");
}
</syntaxhighlight>
{{out}}
<pre>
H:0 -> R: 1, S: 2
H:1 -> R: 3, S: 4
H:2 -> R: 7, S: 5
H:3 -> R: 12, S: 6
H:4 -> R: 18, S: 8
H:5 -> R: 26, S: 9
H:6 -> R: 35, S: 10
H:7 -> R: 45, S: 11
H:8 -> R: 56, S: 13
H:9 -> R: 69, S: 14
</pre>
 
=={{header|Scala}}==
{{trans|Go}}
<langsyntaxhighlight Scalalang="scala">object HofstadterFigFigSeq extends App {
import scala.collection.mutable.ListBuffer
 
Line 1,449 ⟶ 3,233:
(1 to 10).map(i=>(i,ffr(i))).foreach(t=>println("r("+t._1+"): "+t._2))
println((1 to 1000).toList.filterNot(((1 to 40).map(ffr(_))++(1 to 960).map(ffs(_))).contains)==List())
}</langsyntaxhighlight>
Output:
<pre>r(1): 1
Line 1,462 ⟶ 3,246:
r(10): 69
true</pre>
 
=={{header|SETL}}==
<syntaxhighlight lang="setl">program figure_figure;
init R := [1], S := [2];
 
print("R(1..10):", [ffr(n) : n in [1..10]]);
print("R(1..40) + S(1..960) = {1..1000}:",
{ffr(n) : n in {1..40}} + {ffs(n) : n in {1..960}} = {1..1000});
 
proc ffr(n);
loop while n > #R do
nextR := R(#R) + S(#R);
S +:= [S(#S)+1 .. nextR-1];
R with:= nextR;
S with:= nextR + 1;
end loop;
return R(n);
end proc;
 
proc ffs(n);
loop while n > #S do
ffr(#R + 1);
end loop;
return S(n);
end proc;
end program;</syntaxhighlight>
{{out}}
<pre>R(1..10): [1 3 7 12 18 26 35 45 56 69]
R(1..40) + S(1..960) = {1..1000}: #T</pre>
 
=={{header|Sidef}}==
{{trans|Perl}}
<syntaxhighlight lang="ruby">var r = [nil, 1]
var s = [nil, 2]
 
func ffsr(n) {
while(r.end < n) {
r << s[r.end]+r[-1]
s << [(s[-1]+1 .. r[-1]-1)..., r[-1]+1].grep{ s[-1] < _ }...
}
return n
}
 
func ffr(n) { r[ffsr(n)] }
func ffs(n) { s[ffsr(n)] }
 
printf(" i: R(i) S(i)\n")
printf("==============\n")
{ |i|
printf("%3d:  %3d  %3d\n", i, ffr(i), ffs(i))
} << 1..10
printf("\nR(40)=%3d S(960)=%3d R(41)=%3d\n", ffr(40), ffs(960), ffr(41))
 
var seen = Hash()
 
{|i| seen{ffr(i)} := 0 ++ } << 1..40
{|i| seen{ffs(i)} := 0 ++ } << 1..960
 
if (seen.count {|k,v| (k.to_i >= 1) && (k.to_i <= 1000) && (v == 1) } == 1000) {
say "All occured exactly once."
}
else {
var missed = { !seen.has_key(_) }.grep(1..1000)
var dupped = seen.grep { |_, v| v > 1 }.keys.sort
say "These were missed: #{missed}"
say "These were duplicated: #{dupped}"
}</syntaxhighlight>
{{out}}
<pre>
i: R(i) S(i)
==============
1: 1 2
2: 3 4
3: 7 5
4: 12 6
5: 18 8
6: 26 9
7: 35 10
8: 45 11
9: 56 13
10: 69 14
 
R(40)=982 S(960)=1000 R(41)=1030
All occured exactly once.
</pre>
 
=={{header|Tcl}}==
{{tcllib|struct::set}}
<langsyntaxhighlight lang="tcl">package require Tcl 8.5
package require struct::set
 
Line 1,507 ⟶ 3,376:
}
puts "set sizes: [struct::set size $numsInSeq] vs [struct::set size $numsRS]"
puts "set equality: [expr {[struct::set equal $numsInSeq $numsRS]?{yes}:{no}}]"</langsyntaxhighlight>
Output:
<pre>
Line 1,523 ⟶ 3,392:
set sizes: 1000 vs 1000
set equality: yes
</pre>
 
=={{header|uBasic/4tH}}==
Note that uBasic/4tH has ''no'' dynamic memory facilities and only ''one single array'' of 256 elements. So the only way to cram over a 1000 values there is to use a bitmap. This bitmap consists of an '''R''' range and an '''S''' range. In each range, a bit represents a positional value (bit 0 = "1", bit 1 = "2", etc.). The '''R'''(x) and '''S'''(x) functions simply count the number of bits set they encountered. To determine whether all integers between 1 and 1000 are complementary, both ranges are ''XOR''ed, which would result in a value other than 2<sup>31</sup>-1 if there were any discrepancies present. An extra check determines if there are exactly 40 '''R''' values.
<syntaxhighlight lang="text">Proc _SetBitR(1) ' Set the first R value
Proc _SetBitS(2) ' Set the first S value
 
Print "Creating bitmap, wait.." ' Create the bitmap
Proc _MakeBitMap
Print
 
Print "R(1 .. 10):"; ' Print first 10 R-values
 
For x = 1 To 10
Print " ";FUNC(_Rx(x));
Next
 
Print : Print "S(1 .. 10):"; ' Print first 10 S-values
 
For x = 1 To 10
Print " ";FUNC(_Sx(x));
Next
 
Print : Print ' Terminate and skip line
 
For x = 0 To (1000/31) ' Check the first 1000 values
Print "Checking ";(x*31)+1;" to ";(x*31)+31;":\t";
If XOR(@(x), @(x+64)) = 2147483647 Then
Print "OK" ' XOR R() and S() ranges
Else ' should deliver MAX-N
Print "Fail!" ' or we did have an error
EndIf
Next
 
For x = 1 to 40 ' Prove there are only 40 R(x) values
If FUNC(_Rx(x)) > 1000 Then Print "R(";x;") value greater than 1000"
Next ' below 1000
 
If FUNC(_Rx(x)) < 1001 Then Print "R(";x;") value also below 1000"
End
 
 
_MakeBitMap ' Create the bitmap
Local (4)
 
a@ = 1 ' Previous R(x) level
b@ = 1 ' Previous R(x) value
 
Do Until b@ > (1000/31)*32 ' Fill up an entire array element
' calculate R(x+1) level
c@ = FUNC(_Rx(a@)) + FUNC(_Sx(a@))
Proc _SetBitR (c@) ' Set R(x+1) in the bitmap
 
For d@ = b@ + 1 To c@ - 1 ' Set all intermediate S() values
Proc _SetBitS (d@) ' between R(x) and R(x+1)
Next
 
Proc _SetBitS (c@+1) ' Number after R(x) is always S()
b@ = c@ ' R(x+1) now becomes R(x)
a@ = a@ + 1 ' Increment level
Loop ' Now do it again
Return
 
 
_Rx Param(1) ' Return value R(x)
Local(2)
 
b@ = 0 ' No value found so far
 
For c@ = 1 To (64*31)-1 ' Check the entire bitmap
If (FUNC(_GetBitR(c@))) Then b@ = b@ + 1
Until b@ = a@ ' If a value found, increment counter
Next ' Until the required level is reached
Return (c@) ' Return position in bitmap
 
 
_Sx Param(1) ' Return value S(x)
Local(2)
 
b@ = 0 ' No value found so far
 
For c@ = 1 To (64*31)-1 ' Check the entire bitmap
If (FUNC(_GetBitS(c@))) Then b@ = b@ + 1
Until b@ = a@ ' If a value found, increment counter
Next ' Until the required level is reached
Return (c@) ' Return position in bitmap
 
 
_SetBitR Param(1) ' Set bit n-1 in R-bitmap
a@ = a@ - 1
@(a@/31) = OR(@(a@/31), SHL(1,a@%31))
Return
 
_GetBitR Param(1) ' Return bit n-1 in R-bitmap
a@ = a@ - 1
Return (AND(@(a@/31), SHL(1,a@%31))#0)
 
_SetBitS Param(1) ' Set bit n-1 in S-bitmap
a@ = a@ - 1
@(64+a@/31) = OR(@(64+a@/31), SHL(1,a@%31))
Return
 
_GetBitS Param(1) ' Return bit n-1 in S-bitmap
a@ = a@ - 1
Return (AND(@(64+a@/31), SHL(1,a@%31))#0)</syntaxhighlight>
{{out}}
<pre>Creating bitmap, wait..
 
R(1 .. 10): 1 3 7 12 18 26 35 45 56 69
S(1 .. 10): 2 4 5 6 8 9 10 11 13 14
 
Checking 1 to 31: OK
Checking 32 to 62: OK
Checking 63 to 93: OK
Checking 94 to 124: OK
Checking 125 to 155: OK
Checking 156 to 186: OK
Checking 187 to 217: OK
Checking 218 to 248: OK
Checking 249 to 279: OK
Checking 280 to 310: OK
Checking 311 to 341: OK
Checking 342 to 372: OK
Checking 373 to 403: OK
Checking 404 to 434: OK
Checking 435 to 465: OK
Checking 466 to 496: OK
Checking 497 to 527: OK
Checking 528 to 558: OK
Checking 559 to 589: OK
Checking 590 to 620: OK
Checking 621 to 651: OK
Checking 652 to 682: OK
Checking 683 to 713: OK
Checking 714 to 744: OK
Checking 745 to 775: OK
Checking 776 to 806: OK
Checking 807 to 837: OK
Checking 838 to 868: OK
Checking 869 to 899: OK
Checking 900 to 930: OK
Checking 931 to 961: OK
Checking 962 to 992: OK
Checking 993 to 1023: OK
 
0 OK, 0:875</pre>
 
=={{header|VBA}}==
<syntaxhighlight lang="vb">Private Function ffr(n As Long) As Long
Dim R As New Collection
Dim S As New Collection
R.Add 1
S.Add 2
'return R(n)
For i = 2 To n
R.Add R(i - 1) + S(i - 1)
For j = S(S.Count) + 1 To R(i) - 1
S.Add j
Next j
For j = R(i) + 1 To R(i) + S(i - 1)
S.Add j
Next j
Next i
ffr = R(n)
Set R = Nothing
Set S = Nothing
End Function
Private Function ffs(n As Long) As Long
Dim R As New Collection
Dim S As New Collection
R.Add 1
S.Add 2
'return S(n)
For i = 2 To n
R.Add R(i - 1) + S(i - 1)
For j = S(S.Count) + 1 To R(i) - 1
S.Add j
Next j
For j = R(i) + 1 To R(i) + S(i - 1)
S.Add j
Next j
If S.Count >= n Then Exit For
Next i
ffs = S(n)
Set R = Nothing
Set S = Nothing
End Function
Public Sub main()
Dim i As Long
Debug.Print "The first ten values of R are:"
For i = 1 To 10
Debug.Print ffr(i);
Next i
Debug.Print
Dim x As New Collection
For i = 1 To 1000
x.Add i, CStr(i)
Next i
For i = 1 To 40
x.Remove CStr(ffr(i))
Next i
For i = 1 To 960
x.Remove CStr(ffs(i))
Next i
Debug.Print "The first 40 values of ffr plus the first 960 values of ffs "
Debug.Print "include all the integers from 1 to 1000 exactly once is "; Format(x.Count = 0)
End Sub</syntaxhighlight>{{out}}
<pre>The first ten values of R are:
1 3 7 12 18 26 35 45 56 69
The first 40 values of ffr plus the first 960 values of ffs
include all the integers from 1 to 1000 exactly once is True</pre>
 
=={{header|VBScript}}==
<syntaxhighlight lang="vb">
'Initialize the r and the s arrays.
Set r = CreateObject("System.Collections.ArrayList")
Set s = CreateObject("System.Collections.ArrayList")
 
'Set initial values of r.
r.Add "" : r.Add 1
 
'Set initial values of s.
s.Add "" : s.Add 2
 
'Populate the r and the s arrays.
For i = 2 To 1000
ffr(i)
ffs(i)
Next
 
'r function
Function ffr(n)
r.Add r(n-1)+s(n-1)
End Function
 
's function
Function ffs(n)
'index is the value of the last element of the s array.
index = s(n-1)+1
Do
'Add to s if the current index is not in the r array.
If r.IndexOf(index,0) = -1 Then
s.Add index
Exit Do
Else
index = index + 1
End If
Loop
End Function
 
'Display the first 10 values of r.
WScript.StdOut.Write "First 10 Values of R:"
WScript.StdOut.WriteLine
For j = 1 To 10
If j = 10 Then
WScript.StdOut.Write "and " & r(j)
Else
WScript.StdOut.Write r(j) & ", "
End If
Next
WScript.StdOut.WriteBlankLines(2)
 
'Show that the first 40 values of r plus the first 960 values of s include all the integers from 1 to 1000 exactly once.
'The idea here is to create another array(integer) with 1000 elements valuing from 1 to 1000. Go through the first 40 values
'of the r array and remove the corresponding element in the integer array. Do the same thing with the first 960 values of
'the s array. If the resultant count of the integer array is 0 then it is a pass.
Set integers = CreateObject("System.Collections.ArrayList")
For k = 1 To 1000
integers.Add k
Next
For l = 1 To 960
If l <= 40 Then
integers.Remove(r(l))
End If
integers.Remove(s(l))
Next
WScript.StdOut.Write "Test for the first 1000 integers: "
If integers.Count = 0 Then
WScript.StdOut.Write "Passed!!!"
WScript.StdOut.WriteLine
Else
WScript.StdOut.Write "Miserably Failed!!!"
WScript.StdOut.WriteLine
End If
</syntaxhighlight>
 
{{Out}}
<pre>
First 10 Values of R:
1, 3, 7, 12, 18, 26, 35, 45, 56, and 69
 
Test for the first 1000 integers: Passed!!!
</pre>
 
=={{header|Wren}}==
{{trans|Go}}
<syntaxhighlight lang="wren">var r = [0, 1]
var s = [0, 2]
 
var ffr = Fn.new { |n|
while (r.count <= n) {
var nrk = r.count - 1 // last n for which r[n] is known
var rNxt = r[nrk] + s[nrk] // r[nrk+1]
r.add(rNxt) // extend r by one element
for (sn in r[nrk]+2...rNxt) {
s.add(sn) // extend sequence s up to rNxt
}
s.add(rNxt + 1) // extend sequence s one past rNxt
}
return r[n]
}
 
var ffs = Fn.new { |n|
while (s.count <= n) ffr.call(r.count)
return s[n]
}
 
System.print("The first 10 values of R are:")
for (i in 1..10) System.write(" %(ffr.call(i))")
System.print()
var present = List.filled(1001, false)
for (i in 1..40) present[ffr.call(i)] = true
for (i in 1..960) present[ffs.call(i)] = true
var allPresent = present.skip(1).all { |i| i == true }
System.print("\nThe first 40 values of ffr plus the first 960 values of ffs")
System.print("includes all integers from 1 to 1000 exactly once is %(allPresent).")</syntaxhighlight>
 
{{out}}
<pre>
The first 10 values of R are:
1 3 7 12 18 26 35 45 56 69
 
The first 40 values of ffr plus the first 960 values of ffs
includes all integers from 1 to 1000 exactly once is true.
</pre>
 
=={{header|zkl}}==
<syntaxhighlight lang="zkl">fcn genRS(reset=False){ //-->(n,R,S)
var n=0, Rs=L(0,1), S=2;
if(True==reset){ n=0; Rs=L(0,1); S=2; return(); }
 
if (n==0) return(n=1,1,2);
R:=Rs[-1] + S; Rs.append(R);
foreach s in ([S+1..]){
if(not Rs.holds(s)) { S=s; break; } // trimming Rs doesn't save space
}
return(n+=1,R,S);
}
fcn ffrs(n) { genRS(True); do(n){ n=genRS() } n[1,2] } //-->( R(n),S(n) )</syntaxhighlight>
{{out}}
<pre>
(0).pump(10,List,genRS).apply("get",1).println();
L(1,3,7,12,18,26,35,45,56,69)
</pre>
<syntaxhighlight lang="zkl">genRS(True); // reset
sink:=(0).pump(40,List, 'wrap(ns){ T(Void.Write,Void.Write,genRS()[1,*]) });
sink= (0).pump(960-40,sink,'wrap(ns){ T(Void.Write,genRS()[2]) });
(sink.sort()==[1..1000].pump(List)) // [1..n].pump(List)-->(1,2,3...)
.println("<-- should be True");</syntaxhighlight>
{{out}}
<pre>
True<-- should be True
</pre>
2,058

edits