Hofstadter Figure-Figure sequences: Difference between revisions

Added Easylang
(Added Easylang)
 
(13 intermediate revisions by 7 users not shown)
Line 32:
{{trans|Python}}
 
<langsyntaxhighlight lang="11l">V cR = [1]
V cS = [2]
 
Line 64:
print(‘All Integers 1..1000 found OK’)
E
print(‘All Integers 1..1000 NOT found only once: ERROR’)</langsyntaxhighlight>
 
{{out}}
Line 72:
</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 80 ⟶ 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 133 ⟶ 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 175 ⟶ 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}}
<langsyntaxhighlight APLlang="apl">:Class HFF
:Field Private Shared RBuf←,1
∇r←ffr n
Line 207 ⟶ 246:
:EndIf
:EndClass</langsyntaxhighlight>
 
{{out}}
Line 216 ⟶ 255:
 
=={{header|AutoHotkey}}==
<syntaxhighlight lang="autohotkey">R(n){
<lang AutoHotkey>R(n){
if n=1
return 1
Line 234 ⟶ 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 329 ⟶ 368:
}
return S[ n ];
} # ffs</langsyntaxhighlight>
{{out}}
<pre>
Line 338 ⟶ 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 390 ⟶ 429:
IF R% <= 2*N% V%?R% = 1
NEXT I%
= S%</langsyntaxhighlight>
<pre>
First 10 values of R:
Line 401 ⟶ 440:
 
=={{header|C}}==
<langsyntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
 
Line 484 ⟶ 523:
puts("\nfirst 1000 ok");
return 0;
}</langsyntaxhighlight>
 
=={{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 572 ⟶ 611:
}
}
</syntaxhighlight>
</lang>
Output:
<pre>1
Line 589 ⟶ 628:
{{works with|gcc}}
{{works with|C++|11, 14, 17}}
<langsyntaxhighlight lang="cpp">#include <iomanip>
#include <iostream>
#include <set>
Line 654 ⟶ 693:
 
return 0;
}</langsyntaxhighlight>
{{out}}
 
<langsyntaxhighlight 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
Line 666 ⟶ 705:
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</langsyntaxhighlight>
 
=={{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 695 ⟶ 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 733 ⟶ 840:
(take #'seq-s 960))
#'<))
(princ "Ok")</langsyntaxhighlight>
{{out}}
<pre>First of R: (1 3 7 12 18 26 35 45 56 69)
Line 739 ⟶ 846:
 
=={{header|Cowgol}}==
<langsyntaxhighlight lang="cowgol">include "cowgol.coh";
include "strings.coh";
include "malloc.coh";
Line 881 ⟶ 988:
if ok != 0 then
print("All numbers 1 .. 1000 found!\n");
end if;</langsyntaxhighlight>
 
{{out}}
Line 891 ⟶ 998:
=={{header|D}}==
{{trans|Go}}
<langsyntaxhighlight lang="d">int delegate(in int) nothrow ffr, ffs;
 
nothrow static this() {
Line 921 ⟶ 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 928 ⟶ 1,035:
{{trans|Python}}
(Same output)
<langsyntaxhighlight lang="d">import std.stdio, std.array, std.range, std.algorithm;
 
struct ffr {
Line 978 ⟶ 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 992 ⟶ 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 1,002 ⟶ 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 1,026 ⟶ 1,190:
>all(sort(r[1:40]|s[1:960])==(1:1000))
1
</syntaxhighlight>
</lang>
 
=={{header|F_Sharp|F#}}==
===The function===
<langsyntaxhighlight 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
Line 1,039 ⟶ 1,203:
|i->S.[n]<-i+1; fN (n+1) (g+1)
fN 1 1
</syntaxhighlight>
</lang>
===The Tasks===
<langsyntaxhighlight 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>
</lang>
{{out}}
<pre>
Line 1,054 ⟶ 1,218:
===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.
<langsyntaxhighlight lang="fsharp">
let ffr,ffs=fF 10000000
printfn "%d\n%d (Array.last ffr) (Array.last ffs)
</syntaxhighlight>
</lang>
1584961838
10004416
Line 1,063 ⟶ 1,227:
=={{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 1,083 ⟶ 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}}
<langsyntaxhighlight 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)
Line 1,141 ⟶ 1,305:
next i
 
if failed then print "Oh no!" else print "All integers from 1 to 1000 accounted for"</langsyntaxhighlight>
{{out}}<pre>
R S
Line 1,159 ⟶ 1,323:
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 1,214 ⟶ 1,378:
}
fmt.Println("task 4: PASS")
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,230 ⟶ 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 1,278 ⟶ 1,442:
}
fmt.Println(sum)
}</langsyntaxhighlight>
 
=={{header|Haskell}}==
<langsyntaxhighlight lang="haskell">import Data.List (delete, sort)
 
-- Functions by Reinhard Zumkeller
Line 1,304 ⟶ 1,468:
print $ ffr <$> [1 .. 10]
let i1000 = sort (fmap ffr [1 .. 40] ++ fmap ffs [1 .. 960])
print (i1000 == [1 .. 1000])</langsyntaxhighlight>
Output:
<pre>[1,3,7,12,18,26,35,45,56,69]
Line 1,310 ⟶ 1,474:
 
Defining R and S literally:
<langsyntaxhighlight lang="haskell">import Data.List (sort)
 
r :: [Int]
Line 1,328 ⟶ 1,492:
print (take 10 s)
putStr "test 1000: "
print $ [1 .. 1000] == sort (take 40 r ++ take 960 s)</langsyntaxhighlight>
output:
<pre>
Line 1,337 ⟶ 1,501:
 
=={{header|Icon}} and {{header|Unicon}}==
<langsyntaxhighlight Iconlang="icon">link printf,ximage
 
procedure main()
Line 1,395 ⟶ 1,559:
}
}
end</langsyntaxhighlight>
 
{{libheader|Icon Programming Library}}
Line 1,416 ⟶ 1,580:
=={{header|J}}==
 
<langsyntaxhighlight lang="j">R=: 1 1 3
S=: 0 2 4
FF=: 3 :0
Line 1,426 ⟶ 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,439 ⟶ 1,603:
'''Code:'''
 
<langsyntaxhighlight lang="java">import java.util.*;
 
class Hofstadter
Line 1,494 ⟶ 1,658:
System.out.println("Done");
}
}</langsyntaxhighlight>
 
'''Output:'''
Line 1,503 ⟶ 1,667:
=={{header|JavaScript}}==
{{trans|Ruby}}
<langsyntaxhighlight JavaScriptlang="javascript">var R = [null, 1];
var S = [null, 2];
 
Line 1,549 ⟶ 1,713:
throw "Something's wrong!"
} else { console.log("1000 integer check ok."); }
}</langsyntaxhighlight>
Output:
<pre>R(1) = 1
Line 1,573 ⟶ 1,737:
to accomplish the specific tasks.
 
<langsyntaxhighlight lang="jq">def init: {r: [0, 1], s: [0, 2] };
 
# input: {r,s}
Line 1,603 ⟶ 1,767:
| (.r[1:41] + .s[1:961] | sort) == [range(1;1001)] ) ;
 
task1(10), task2</langsyntaxhighlight>
{{out}}
<pre>
Line 1,617 ⟶ 1,781:
 
'''Functions'''
<syntaxhighlight lang="julia">
<lang Julia>
type FigureFigure{T<:Integer}
r::Array{T,1}
Line 1,679 ⟶ 1,843:
end
end
</syntaxhighlight>
</lang>
 
'''Main'''
<syntaxhighlight lang="julia">
<lang Julia>
NR = 40
NS = 960
Line 1,723 ⟶ 1,887:
end
println("cover the entire interval.")
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,734 ⟶ 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,770 ⟶ 1,934:
indices.forEach { println("Integer $it either in both or neither set") }
println("Done")
}</langsyntaxhighlight>
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
Line 1,781 ⟶ 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,787 ⟶ 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,807 ⟶ 1,971:
(* out *)
True
</syntaxhighlight>
</lang>
 
=={{header|MATLAB}} / {{header|Octave}}==
Line 1,814 ⟶ 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,837 ⟶ 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,858 ⟶ 2,022:
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">var cr = @[1]
var cs = @[2]
 
Line 1,890 ⟶ 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,897 ⟶ 2,061:
 
=={{header|Oforth}}==
<langsyntaxhighlight lang="oforth">tvar: R
ListBuffer new 1 over add R put
 
Line 1,917 ⟶ 2,081:
: ffs(n)
while ( S at size n < ) [ buildnext ]
n S at at ;</langsyntaxhighlight>
 
Output :
Line 1,934 ⟶ 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,969 ⟶ 2,133:
print "These were duplicated: @dupped\n";
}
</syntaxhighlight>
</lang>
 
=={{header|Phix}}==
Initialising such that length(S)>length(F) simplified things significantly.
<!--<langsyntaxhighlight Phixlang="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>
Line 2,001 ⟶ 2,166:
<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>
Line 2,009 ⟶ 2,174:
<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>
<!--</langsyntaxhighlight>-->
{{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)
Line 2,033 ⟶ 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 2,041 ⟶ 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 2,066 ⟶ 2,231:
end;
return (r);
end ffr;</langsyntaxhighlight>
Output:
<pre>
Line 2,074 ⟶ 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 2,096 ⟶ 2,261:
end;
return (s);
end ffs;</langsyntaxhighlight>
Output of first 960 values:
<pre>
Line 2,106 ⟶ 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 2,121 ⟶ 2,286:
end;
if all(t = '1'b) then put skip list ('passed test');
</syntaxhighlight>
</lang>
Output:
<pre>
Line 2,133 ⟶ 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 2,159 ⟶ 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 2,187 ⟶ 2,352:
 
Code for the second task
<langsyntaxhighlight Prologlang="prolog">hofstadter :-
hofstadter(960),
% fetch the values of ffr
Line 2,201 ⟶ 2,366:
% to remove all pending constraints
fail.
</syntaxhighlight>
</lang>
Output for second task
<pre> ?- hofstadter.
Line 2,209 ⟶ 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 2,254 ⟶ 2,419:
print("All Integers 1..1000 found OK")
else:
print("All Integers 1..1000 NOT found only once: ERROR")</langsyntaxhighlight>
 
;Output:
Line 2,261 ⟶ 2,426:
 
===Alternative===
<langsyntaxhighlight lang="python">cR = [1]
cS = [2]
 
Line 2,289 ⟶ 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 2,320 ⟶ 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 2,326 ⟶ 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.
<langsyntaxhighlight Rlang="rsplus">rValues <- 1
sValues <- 2
ffr <- function(n)
Line 2,358 ⟶ 2,582:
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])))</langsyntaxhighlight>
{{out}}
<pre>> print(rValues)
Line 2,476 ⟶ 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 2,489 ⟶ 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 2,512 ⟶ 2,736:
i))
"Test passed"
"Test failed"))</langsyntaxhighlight>
 
'''Sample Output:'''
Line 2,522 ⟶ 2,746:
(formerly Perl 6)
{{works with|Rakudo|2018.03}}
<syntaxhighlight lang="raku" perl6line>my %r = 1 => 1;
my %s = 1 => 2;
 
Line 2,532 ⟶ 2,756:
 
say @ffr[^10];
say "Rawks!" if 1...1000 eqv sort |@ffr[^40], |@ffs[^960];</langsyntaxhighlight>
Output:
<pre>
Line 2,546 ⟶ 2,770:
 
This REXX version is over &nbsp; '''15,000%''' &nbsp; faster than REXX version 2.
<langsyntaxhighlight 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,588 ⟶ 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,608 ⟶ 2,832:
 
===Version 2 from PL/I ===
<langsyntaxhighlight lang="rexx">/* REXX **************************************************************
* 21.11.2012 Walter Pachl transcribed from PL/I
**********************************************************************/
Line 2,679 ⟶ 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,694 ⟶ 2,918:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
# Project : Hofstadter Figure-Figure sequences
 
Line 2,725 ⟶ 2,949:
svect = left(svect, len(svect) - 1)
see svect + nl
</syntaxhighlight>
</lang>
Output:
<pre>
Line 2,732 ⟶ 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,777 ⟶ 3,075:
assert_equal(rs_values, Set.new( 1..1000 ))
end
end</langsyntaxhighlight>
 
outputs
Line 2,788 ⟶ 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,807 ⟶ 3,105:
p S.take(10)
p (R.take(40)+ S.take(960)).sort == (1..1000).to_a
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,816 ⟶ 3,114:
 
=={{header|Rust}}==
<langsyntaxhighlight lang="rust">
use std::collections::HashMap;
 
Line 2,892 ⟶ 3,190:
assert_eq!(f1000, s960, "Does NOT match");
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,909 ⟶ 3,207:
=={{header|Scala}}==
{{trans|Go}}
<langsyntaxhighlight Scalalang="scala">object HofstadterFigFigSeq extends App {
import scala.collection.mutable.ListBuffer
 
Line 2,935 ⟶ 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,948 ⟶ 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,985 ⟶ 3,312:
say "These were missed: #{missed}"
say "These were duplicated: #{dupped}"
}</langsyntaxhighlight>
{{out}}
<pre>
Line 3,007 ⟶ 3,334:
=={{header|Tcl}}==
{{tcllib|struct::set}}
<langsyntaxhighlight lang="tcl">package require Tcl 8.5
package require struct::set
 
Line 3,049 ⟶ 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 3,069 ⟶ 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 3,169 ⟶ 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 3,213 ⟶ 3,540:
 
=={{header|VBA}}==
<langsyntaxhighlight lang="vb">Private Function ffr(n As Long) As Long
Dim R As New Collection
Dim S As New Collection
Line 3,271 ⟶ 3,598:
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</langsyntaxhighlight>{{out}}
<pre>The first ten values of R are:
1 3 7 12 18 26 35 45 56 69
Line 3,278 ⟶ 3,605:
 
=={{header|VBScript}}==
<syntaxhighlight lang="vb">
<lang vb>
'Initialize the r and the s arrays.
Set r = CreateObject("System.Collections.ArrayList")
Line 3,349 ⟶ 3,676:
WScript.StdOut.WriteLine
End If
</syntaxhighlight>
</lang>
 
{{Out}}
Line 3,361 ⟶ 3,688:
=={{header|Wren}}==
{{trans|Go}}
<langsyntaxhighlight ecmascriptlang="wren">var r = [0, 1]
var s = [0, 2]
 
Line 3,390 ⟶ 3,717:
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).")</langsyntaxhighlight>
 
{{out}}
Line 3,402 ⟶ 3,729:
 
=={{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 3,413 ⟶ 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 3,419 ⟶ 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].pump(List)) // [1..n].pump(List)-->(1,2,3...)
.println("<-- should be True");</langsyntaxhighlight>
{{out}}
<pre>
1,983

edits