Hofstadter Figure-Figure sequences: Difference between revisions

Added Easylang
(→‎{{header|Perl 6}}: Roll back to an older, but working version, lightly updated)
(Added Easylang)
 
(38 intermediate revisions by 17 users not shown)
Line 29:
<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 37 ⟶ 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 90 ⟶ 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 132 ⟶ 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){
<lang AutoHotkey>R(n){
if n=1
return 1
Line 157 ⟶ 273:
if !(ObjR[A_Index]||ObjS[A_Index])
return A_index
}</langsyntaxhighlight>
Examples:<langsyntaxhighlight AutoHotkeylang="autohotkey">Loop
MsgBox, 262144, , % "R(" A_Index ") = " R(A_Index) "`nS(" A_Index ") = " S(A_Index)</langsyntaxhighlight>
Outputs:<pre>R(1) = 1, 3, 7, 12, 18, 26, 35,...
S(1) = 2, 4, 5, 6, 8, 9, 10,...</pre>
 
=={{header|AWK}}==
<langsyntaxhighlight lang="awk"># Hofstadter Figure-Figure sequences
#
# R(1) = 1; S(1) = 2;
Line 252 ⟶ 368:
}
return S[ n ];
} # ffs</langsyntaxhighlight>
{{out}}
<pre>
Line 261 ⟶ 377:
=={{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 313 ⟶ 429:
IF R% <= 2*N% V%?R% = 1
NEXT I%
= S%</langsyntaxhighlight>
<pre>
First 10 values of R:
Line 324 ⟶ 440:
 
=={{header|C}}==
<langsyntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
 
Line 407 ⟶ 523:
puts("\nfirst 1000 ok");
return 0;
}</langsyntaxhighlight>
 
=={{header|C++}}==
{{works with|gcc}}
{{works with|C++|11, 14, 17}}
<lang cpp>#include <iomanip>
#include <iostream>
#include <set>
#include <vector>
 
using namespace std;
 
unsigned hofstadter(unsigned rlistSize, unsigned slistSize)
{
auto n = rlistSize > slistSize ? rlistSize : slistSize;
auto rlist = new vector<unsigned> { 1, 3, 7 };
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();
 
while (list->size() < target_size)
{
auto lastIndex = rlist->size() - 1;
auto lastr = (*rlist)[lastIndex];
auto r = lastr + (*slist)[lastIndex];
rlist->push_back(r);
for (auto s = lastr + 1; s < r && list->size() < target_size;)
slist->push_back(s++);
}
 
auto v = (*list)[n - 1];
delete rlist;
delete slist;
return v;
}
 
ostream& operator<<(ostream& os, const set<unsigned>& s)
{
cout << '(' << s.size() << "):";
auto i = 0;
for (auto c = s.begin(); c != s.end();)
{
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());
for (auto n = 1; n <= m; n++)
if (r.count(n) == s.count(n))
clog << "integer " << n << " either in both or neither set" << endl;
 
return 0;
}</lang>
{{out}}
 
<lang sh>% ./hofstadter 40 100 2> /dev/null
R(40):
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
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</lang>
 
=={{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 577 ⟶ 611:
}
}
</syntaxhighlight>
</lang>
Output:
<pre>1
Line 590 ⟶ 624:
69
Verified</pre>
 
=={{header|C++}}==
{{works with|gcc}}
{{works with|C++|11, 14, 17}}
<syntaxhighlight lang="cpp">#include <iomanip>
#include <iostream>
#include <set>
#include <vector>
 
using namespace std;
 
unsigned hofstadter(unsigned rlistSize, unsigned slistSize)
{
auto n = rlistSize > slistSize ? rlistSize : slistSize;
auto rlist = new vector<unsigned> { 1, 3, 7 };
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();
 
while (list->size() < target_size)
{
auto lastIndex = rlist->size() - 1;
auto lastr = (*rlist)[lastIndex];
auto r = lastr + (*slist)[lastIndex];
rlist->push_back(r);
for (auto s = lastr + 1; s < r && list->size() < target_size;)
slist->push_back(s++);
}
 
auto v = (*list)[n - 1];
delete rlist;
delete slist;
return v;
}
 
ostream& operator<<(ostream& os, const set<unsigned>& s)
{
cout << '(' << s.size() << "):";
auto i = 0;
for (auto c = s.begin(); c != s.end();)
{
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());
for (auto n = 1; n <= m; n++)
if (r.count(n) == s.count(n))
clog << "integer " << n << " either in both or neither set" << endl;
 
return 0;
}</syntaxhighlight>
{{out}}
 
<syntaxhighlight lang="sh">% ./hofstadter 40 100 2> /dev/null
R(40):
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
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}}==
<syntaxhighlight lang="clu">figfig = cluster is ffr, ffs
rep = null
ai = array[int]
own R: ai := ai$[1]
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 ()
ai = array[int]
po: stream := stream$primary_output()
% 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}}==
{{trans|Ruby}}
<langsyntaxhighlight lang="coffeescript">R = [ null, 1 ]
S = [ null, 2 ]
 
Line 618 ⟶ 802:
if int_array[i - 1] != i
throw 'Something\'s wrong!'
console.log '1000 integer check ok.'</langsyntaxhighlight>
{{out}}
As JavaScript.
 
=={{header|Common Lisp}}==
<langsyntaxhighlight lang="lisp">;;; equally doable with a list
(flet ((seq (i) (make-array 1 :element-type 'integer
:initial-element i
Line 656 ⟶ 840:
(take #'seq-s 960))
#'<))
(princ "Ok")</langsyntaxhighlight>
{{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}}
<langsyntaxhighlight lang="d">int delegate(in int) nothrow ffr, ffs;
 
nothrow static this() {
Line 693 ⟶ 1,028:
auto t = iota(1, 41).map!ffr.chain(iota(1, 961).map!ffs);
t.array.sort().equal(iota(1, 1001)).writeln;
}</langsyntaxhighlight>
{{out}}
<pre>[1, 3, 7, 12, 18, 26, 35, 45, 56, 69]
Line 700 ⟶ 1,035:
{{trans|Python}}
(Same output)
<langsyntaxhighlight lang="d">import std.stdio, std.array, std.range, std.algorithm;
 
struct ffr {
Line 750 ⟶ 1,085:
auto t = iota(1, 41).map!ffr.chain(iota(1, 961).map!ffs);
t.array.sort().equal(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}}==
<langsyntaxhighlight lang="scheme">(define (FFR n)
(+ (FFR (1- n)) (FFS (1- n))))
Line 764 ⟶ 1,156:
(remember 'FFR #(0 1)) ;; init cache
(remember 'FFS #(0 2))
</syntaxhighlight>
</lang>
{{out}}
<langsyntaxhighlight lang="scheme">
(define-macro m-range [a .. b] (range a (1+ b)))
 
Line 774 ⟶ 1,166:
;; checking
(equal? [1 .. 1000] (list-sort < (append (map FFR [1 .. 40]) (map FFS [1 .. 960]))))
→ #t</langsyntaxhighlight>
 
=={{header|Euler Math Toolbox}}==
 
<syntaxhighlight lang="euler math toolbox">
<lang Euler Math Toolbox>
>function RSstep (r,s) ...
$ n=cols(r);
Line 798 ⟶ 1,190:
>all(sort(r[1:40]|s[1:960])==(1:1000))
1
</syntaxhighlight>
</lang>
 
=={{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 822 ⟶ 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 885 ⟶ 1,378:
}
fmt.Println("task 4: PASS")
}</langsyntaxhighlight>
{{out}}
<pre>
Line 901 ⟶ 1,394:
 
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 949 ⟶ 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 972 ⟶ 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 992 ⟶ 1,501:
 
=={{header|Icon}} and {{header|Unicon}}==
<langsyntaxhighlight Iconlang="icon">link printf,ximage
 
procedure main()
Line 1,050 ⟶ 1,559:
}
}
end</langsyntaxhighlight>
 
{{libheader|Icon Programming Library}}
Line 1,071 ⟶ 1,580:
=={{header|J}}==
 
<langsyntaxhighlight lang="j">R=: 1 1 3
S=: 0 2 4
FF=: 3 :0
Line 1,081 ⟶ 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 1,094 ⟶ 1,603:
'''Code:'''
 
<langsyntaxhighlight lang="java">import java.util.*;
 
class Hofstadter
Line 1,149 ⟶ 1,658:
System.out.println("Done");
}
}</langsyntaxhighlight>
 
'''Output:'''
Line 1,158 ⟶ 1,667:
=={{header|JavaScript}}==
{{trans|Ruby}}
<langsyntaxhighlight JavaScriptlang="javascript">var R = [null, 1];
var S = [null, 2];
 
Line 1,204 ⟶ 1,713:
throw "Something's wrong!"
} else { console.log("1000 integer check ok."); }
}</langsyntaxhighlight>
Output:
<pre>R(1) = 1
Line 1,217 ⟶ 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}}==
Line 1,222 ⟶ 1,781:
 
'''Functions'''
<syntaxhighlight lang="julia">
<lang Julia>
type FigureFigure{T<:Integer}
r::Array{T,1}
Line 1,284 ⟶ 1,843:
end
end
</syntaxhighlight>
</lang>
 
'''Main'''
<syntaxhighlight lang="julia">
<lang Julia>
NR = 40
NS = 960
Line 1,328 ⟶ 1,887:
end
println("cover the entire interval.")
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,339 ⟶ 1,898:
</pre>
 
=={{header|Kotlin}} ==
Translated from Java.
<langsyntaxhighlight lang="scala">fun ffr(n: Int) = get(n, 0)[n - 1]
 
fun ffs(n: Int) = get(0, n)[n - 1]
Line 1,375 ⟶ 1,934:
indices.forEach { println("Integer $it either in both or neither set") }
println("Done")
}</langsyntaxhighlight>
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
Line 1,386 ⟶ 1,945:
2. No maximum value for n should be assumed.
 
<syntaxhighlight lang="mathematica">
<lang Mathematica>
ffr[j_] := Module[{R = {1}, S = 2, k = 1},
Do[While[Position[R, S] != {}, S++]; k = k + S; S++;
Line 1,392 ⟶ 1,951:
 
ffs[j_] := Differences[ffr[j + 1]]
</syntaxhighlight>
</lang>
 
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">
<lang Mathematica>
ffr[10]
 
(* out *)
{1, 3, 7, 12, 18, 26, 35, 45, 56, 69}
</syntaxhighlight>
</lang>
 
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">
<lang Mathematica>
t = Sort[Join[ffr[40], ffs[960]]];
 
Line 1,412 ⟶ 1,971:
(* out *)
True
</syntaxhighlight>
</lang>
 
=={{header|MATLAB}} / {{header|Octave}}==
Line 1,419 ⟶ 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 1,442 ⟶ 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 1,463 ⟶ 2,022:
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">var cr = @[1]
var cs = @[2]
 
Line 1,469 ⟶ 2,028:
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()
Line 1,495 ⟶ 2,054:
 
if all: echo "All Integers 1..1000 found OK"
else: echo "All Integers 1..1000 NOT found only once: ERROR"</langsyntaxhighlight>
Output:
<pre>/home/deen/git/nim-unsorted/hofstadter
Line 1,502 ⟶ 2,061:
 
=={{header|Oforth}}==
<langsyntaxhighlight lang="oforth">tvar: R
ListBuffer new 1 over add R put
 
Line 1,522 ⟶ 2,081:
: ffs(n)
while ( S at size n < ) [ buildnext ]
n S at at ;</langsyntaxhighlight>
 
Output :
Line 1,539 ⟶ 2,098:
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.
 
<langsyntaxhighlight lang="perl">#!perl
use strict;
use warnings;
Line 1,574 ⟶ 2,133:
print "These were duplicated: @dupped\n";
}
</syntaxhighlight>
</lang>
 
=={{header|Perl 6Phix}}==
Initialising such that length(S)>length(F) simplified things significantly.
<lang perl6>my %r = 1 => 1;
<!--<syntaxhighlight lang="phix">(phixonline)-->
my %s = 1 => 2;
<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>
sub ffr ($n) {
<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>
return %r{$n} if %r{$n}:exists;
<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>
%r{$n} = ffr($n - 1) + ffs($n - 1);
return %r{$n};
<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>
sub ffs ($n) {
<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>
return %s{$n} if %s{$n}:exists;
<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>
%s{$n} = (grep none( map &ffr, 1..$n), max(%s.values)+1..*)[0];
<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>
return %s{$n};
<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>
my @ffr = map &ffr, 1..*;
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
 
my @ffs = map &ffs, 1..*;
<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>
say @ffr[^10];
<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>
say "Rawks!" if 1...1000 eqv sort |@ffr[^40], |@ffs[^960];</lang>
<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>
Output:
<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
Rawks!</pre>
</pre>
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(setq *RNext 2)
 
(de ffr (N)
Line 1,621 ⟶ 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 1,629 ⟶ 2,206:
(range 1 1000)
(sort (conc (mapcar ffr (range 1 40)) (mapcar ffs (range 1 960)))) )
-> T</langsyntaxhighlight>
 
=={{header|PL/I}}==
<langsyntaxhighlight lang="pli">ffr: procedure (n) returns (fixed binary(31));
declare n fixed binary (31);
declare v(2*n+1) bit(1);
Line 1,654 ⟶ 2,231:
end;
return (r);
end ffr;</langsyntaxhighlight>
Output:
<pre>
Line 1,662 ⟶ 2,239:
602 640 679 719 760 802 845 889 935 982
</pre>
<langsyntaxhighlight lang="pli">ffs: procedure (n) returns (fixed binary (31));
declare n fixed binary (31);
declare v(2*n+1) bit(1);
Line 1,684 ⟶ 2,261:
end;
return (s);
end ffs;</langsyntaxhighlight>
Output of first 960 values:
<pre>
Line 1,694 ⟶ 2,271:
</pre>
Verification using the above procedures:
<langsyntaxhighlight 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');
Line 1,709 ⟶ 2,286:
end;
if all(t = '1'b) then put skip list ('passed test');
</syntaxhighlight>
</lang>
Output:
<pre>
Line 1,721 ⟶ 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,747 ⟶ 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,775 ⟶ 2,352:
 
Code for the second task
<langsyntaxhighlight Prologlang="prolog">hofstadter :-
hofstadter(960),
% fetch the values of ffr
Line 1,789 ⟶ 2,366:
% to remove all pending constraints
fail.
</syntaxhighlight>
</lang>
Output for second task
<pre> ?- hofstadter.
Line 1,797 ⟶ 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,842 ⟶ 2,419:
print("All Integers 1..1000 found OK")
else:
print("All Integers 1..1000 NOT found only once: ERROR")</langsyntaxhighlight>
 
;Output:
Line 1,849 ⟶ 2,426:
 
===Alternative===
<langsyntaxhighlight lang="python">cR = [1]
cS = [2]
 
Line 1,877 ⟶ 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,908 ⟶ 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,914 ⟶ 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}}==
Line 1,920 ⟶ 2,700:
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.
 
<langsyntaxhighlight Racketlang="racket">#lang racket/base
 
(define r-cache (make-hash '((1 . 1) (2 . 3) (3 . 7))))
Line 1,933 ⟶ 2,713:
(define offset (- s-count last-r))
(for ([val (in-range (add1 last-r) new-r)])
(hash-set! s-cache (+ val offset) val)))</langsyntaxhighlight>
 
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.
 
<langsyntaxhighlight Racketlang="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))))</langsyntaxhighlight>
 
Tests:
<langsyntaxhighlight Racketlang="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)))
 
Line 1,956 ⟶ 2,736:
i))
"Test passed"
"Test failed"))</langsyntaxhighlight>
 
'''Sample Output:'''
Line 1,962 ⟶ 2,742:
(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}}==
Line 1,969 ⟶ 2,768:
 
Over a third of the program was for verification of the first thousand numbers in the Hofstadter Figure-Figure sequences.
 
<lang rexx>/*REXX program calculates and verifies the Hofstadter Figure─Figure sequences. */
This REXX version is over &nbsp; '''15,000%''' &nbsp; faster than REXX version 2.
<syntaxhighlight lang="rexx">/*REXX program calculates and verifies the Hofstadter Figure─Figure sequences. */
parse arg x top bot . /*obtain optional arguments from the CL*/
if x=='' | x=="," then x= 10 /*Not specified? Then use the default.*/
Line 2,011 ⟶ 2,812:
return s.n /*return S.n value to the invoker. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
ser: errs=errs+1; say '***error***' arg(1); return</langsyntaxhighlight>
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>
 
Line 2,031 ⟶ 2,832:
 
===Version 2 from PL/I ===
<langsyntaxhighlight lang="rexx">/* REXX **************************************************************
* 21.11.2012 Walter Pachl transcribed from PL/I
**********************************************************************/
Line 2,102 ⟶ 2,903:
if r <= 2*n then v.r = 1
end
return s</langsyntaxhighlight>
{{out}}
<pre>Verification that the first 40 FFR numbers and the first
Line 2,117 ⟶ 2,918:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
# Project : Hofstadter Figure-Figure sequences
# Date : 2018/01/17
# Author : Gal Zsolt (~ CalmoSoft ~)
# Email : <calmosoft@gmail.com>
 
hofr = list(20)
Line 2,151 ⟶ 2,949:
svect = left(svect, len(svect) - 1)
see svect + nl
</syntaxhighlight>
</lang>
Output:
<pre>
Line 2,158 ⟶ 2,956:
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 2,203 ⟶ 3,075:
assert_equal(rs_values, Set.new( 1..1000 ))
end
end</langsyntaxhighlight>
 
outputs
Line 2,214 ⟶ 3,086:
===Using cyclic iterators===
{{trans|Python}}
<langsyntaxhighlight lang="ruby">R = Enumerator.new do |y|
y << n = 1
S.each{|s_val| y << n += s_val}
Line 2,233 ⟶ 3,105:
p S.take(10)
p (R.take(40)+ S.take(960)).sort == (1..1000).to_a
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,239 ⟶ 3,111:
[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 2,269 ⟶ 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 2,282 ⟶ 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}}
<langsyntaxhighlight lang="ruby">var r = [nil, 1]
var s = [nil, 2]
 
Line 2,319 ⟶ 3,312:
say "These were missed: #{missed}"
say "These were duplicated: #{dupped}"
}</langsyntaxhighlight>
{{out}}
<pre>
Line 2,341 ⟶ 3,334:
=={{header|Tcl}}==
{{tcllib|struct::set}}
<langsyntaxhighlight lang="tcl">package require Tcl 8.5
package require struct::set
 
Line 2,383 ⟶ 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 2,403 ⟶ 3,396:
=={{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
 
Line 2,503 ⟶ 3,496:
_GetBitS Param(1) ' Return bit n-1 in S-bitmap
a@ = a@ - 1
Return (AND(@(64+a@/31), SHL(1,a@%31))#0)</langsyntaxhighlight>
{{out}}
<pre>Creating bitmap, wait..
Line 2,545 ⟶ 3,538:
 
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">
<lang vb>
'Initialize the r and the s arrays.
Set r = CreateObject("System.Collections.ArrayList")
Line 2,618 ⟶ 3,676:
WScript.StdOut.WriteLine
End If
</syntaxhighlight>
</lang>
 
{{Out}}
Line 2,626 ⟶ 3,684:
 
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}}==
<langsyntaxhighlight 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(); }
Line 2,640 ⟶ 3,740:
return(n+=1,R,S);
}
fcn ffrs(n) { genRS(True); do(n){ n=genRS() } n[1,2] } //-->( R(n),S(n) )</langsyntaxhighlight>
{{out}}
<pre>
Line 2,646 ⟶ 3,746:
L(1,3,7,12,18,26,35,45,56,69)
</pre>
<langsyntaxhighlight 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].walkpump(List)).println("<-- should be// True"[1..n].pump(List);</lang-->(1,2,3...)
.println("<-- should be True");</syntaxhighlight>
{{out}}
<pre>
1,981

edits