Recaman's sequence: Difference between revisions

Content added Content deleted
m (Add wikipedia link)
m (syntax highlighting fixup automation)
Line 22: Line 22:
{{trans|Python}}
{{trans|Python}}


<lang 11l>F recamanSucc(seen, n, r)
<syntaxhighlight lang="11l">F recamanSucc(seen, n, r)
‘The successor for a given Recaman term,
‘The successor for a given Recaman term,
given the set of Recaman terms seen so far.’
given the set of Recaman terms seen so far.’
Line 51: Line 51:
print("First duplicated Recaman:\n "recamanUntil((seen, n, r, blnNew) -> !blnNew).last)
print("First duplicated Recaman:\n "recamanUntil((seen, n, r, blnNew) -> !blnNew).last)
V setK = Set(enumFromTo(0)(1000))
V setK = Set(enumFromTo(0)(1000))
print("Number of Recaman terms needed to generate all integers from [0..1000]:\n "(recamanUntil((seen, n, r, blnNew) -> (blnNew & r < 1001 & :setK.is_subset(seen))).len - 1))</lang>
print("Number of Recaman terms needed to generate all integers from [0..1000]:\n "(recamanUntil((seen, n, r, blnNew) -> (blnNew & r < 1001 & :setK.is_subset(seen))).len - 1))</syntaxhighlight>


{{out}}
{{out}}
Line 64: Line 64:


=={{header|ALGOL W}}==
=={{header|ALGOL W}}==
<lang algolw>begin
<syntaxhighlight lang="algolw">begin
% calculate Recaman's sequence values %
% calculate Recaman's sequence values %


Line 153: Line 153:
end
end


end.</lang>
end.</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 164: Line 164:
=={{header|APL}}==
=={{header|APL}}==
{{works with|Dyalog APL}}
{{works with|Dyalog APL}}
<lang APL>recaman←{⎕IO←0
<syntaxhighlight lang="apl">recaman←{⎕IO←0
genNext←{
genNext←{
R←⍵[N-1]-N←≢⍵
R←⍵[N-1]-N←≢⍵
Line 176: Line 176:
⎕←'Length of sequence containing [0..1000]:'
⎕←'Length of sequence containing [0..1000]:'
⎕←≢reca←genNext⍣{(⍳1001)∧.∊⊂⍺}⊢reca
⎕←≢reca←genNext⍣{(⍳1001)∧.∊⊂⍺}⊢reca
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 191: Line 191:
The third of these tasks probably stretches Applescript a bit beyond the point of its usefulness – it takes about 1 minute to find the result, and even that requires the use of NSMutableSet, from the Apple Foundation classes.
The third of these tasks probably stretches Applescript a bit beyond the point of its usefulness – it takes about 1 minute to find the result, and even that requires the use of NSMutableSet, from the Apple Foundation classes.


<lang applescript>use AppleScript version "2.4"
<syntaxhighlight lang="applescript">use AppleScript version "2.4"
use framework "Foundation"
use framework "Foundation"
use scripting additions
use scripting additions
Line 378: Line 378:
on unwords(xs)
on unwords(xs)
intercalateS(space, xs)
intercalateS(space, xs)
end unwords</lang>
end unwords</syntaxhighlight>
{{Out}}
{{Out}}
<pre>First 15 Recamans:
<pre>First 15 Recamans:
Line 394: Line 394:
=={{header|Arturo}}==
=={{header|Arturo}}==
{{trans|Python}}
{{trans|Python}}
<lang rebol>recamanSucc: function [seen, n, r].memoize[
<syntaxhighlight lang="rebol">recamanSucc: function [seen, n, r].memoize[
back: r - n
back: r - n
(or? 0 > back contains? seen back)? -> n + r
(or? 0 > back contains? seen back)? -> n + r
Line 421: Line 421:
print ""
print ""
print "First duplicate Recaman number:"
print "First duplicate Recaman number:"
print last recamanUntil [not? blnNew]</lang>
print last recamanUntil [not? blnNew]</syntaxhighlight>


{{out}}
{{out}}
Line 432: Line 432:


=={{header|AWK}}==
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
# syntax: GAWK -f RECAMANS_SEQUENCE.AWK
# syntax: GAWK -f RECAMANS_SEQUENCE.AWK
# converted from Microsoft Small Basic
# converted from Microsoft Small Basic
Line 476: Line 476:
exit(0)
exit(0)
}
}
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 485: Line 485:


=={{header|BASIC}}==
=={{header|BASIC}}==
<lang gwbasic>10 DEFINT A-Z: DIM A(100)
<syntaxhighlight lang="gwbasic">10 DEFINT A-Z: DIM A(100)
20 PRINT "First 15 terms:"
20 PRINT "First 15 terms:"
30 FOR N=0 TO 14: GOSUB 100: PRINT A(N);: NEXT
30 FOR N=0 TO 14: GOSUB 100: PRINT A(N);: NEXT
Line 501: Line 501:
140 NEXT
140 NEXT
150 A(N)=X: RETURN
150 A(N)=X: RETURN
160 A(N)=A(N-1)+N: RETURN</lang>
160 A(N)=A(N-1)+N: RETURN</syntaxhighlight>


{{out}}
{{out}}
Line 511: Line 511:


=={{header|BCPL}}==
=={{header|BCPL}}==
<lang bcpl>get "libhdr"
<syntaxhighlight lang="bcpl">get "libhdr"


// Generate the N'th term of the Recaman sequence
// Generate the N'th term of the Recaman sequence
Line 543: Line 543:
writef("a!%N = %N*N", rep, a!rep)
writef("a!%N = %N*N", rep, a!rep)
$)</lang>
$)</syntaxhighlight>
{{out}}
{{out}}
<pre>First 15 members:
<pre>First 15 members:
Line 553: Line 553:
{{libheader|GLib}}
{{libheader|GLib}}
{{trans|Go}}
{{trans|Go}}
<lang c>#include <stdio.h>
<syntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
#include <stdlib.h>
#include <gmodule.h>
#include <gmodule.h>
Line 606: Line 606:
free(a);
free(a);
return 0;
return 0;
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 617: Line 617:
=={{header|C sharp|C#}}==
=={{header|C sharp|C#}}==
{{trans|Kotlin}}
{{trans|Kotlin}}
<lang csharp>using System;
<syntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
using System.Collections.Generic;


Line 655: Line 655:
}
}
}
}
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>The first 15 terms of the Recaman sequence are: [0, 1, 3, 6, 2, 7, 13, 20, 12, 21, 11, 22, 10, 23, 9]
<pre>The first 15 terms of the Recaman sequence are: [0, 1, 3, 6, 2, 7, 13, 20, 12, 21, 11, 22, 10, 23, 9]
Line 663: Line 663:
=={{header|C++}}==
=={{header|C++}}==
{{trans|C#}}
{{trans|C#}}
<lang cpp>#include <iostream>
<syntaxhighlight lang="cpp">#include <iostream>
#include <ostream>
#include <ostream>
#include <set>
#include <set>
Line 719: Line 719:


return 0;
return 0;
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>The first 15 terms of the Recaman sequence are: [0, 1, 3, 6, 2, 7, 13, 20, 12, 21, 11, 22, 10, 23, 9]
<pre>The first 15 terms of the Recaman sequence are: [0, 1, 3, 6, 2, 7, 13, 20, 12, 21, 11, 22, 10, 23, 9]
Line 726: Line 726:


=={{header|CLU}}==
=={{header|CLU}}==
<lang clu>% Recaman sequence
<syntaxhighlight lang="clu">% Recaman sequence
recaman = cluster is new, fetch
recaman = cluster is new, fetch
rep = array[int]
rep = array[int]
Line 804: Line 804:
|| int$unparse(n))
|| int$unparse(n))
end
end
end start_up</lang>
end start_up</syntaxhighlight>
{{out}}
{{out}}
<pre>First 15 items: 0 1 3 6 2 7 13 20 12 21 11 22 10 23 9
<pre>First 15 items: 0 1 3 6 2 7 13 20 12 21 11 22 10 23 9
Line 811: Line 811:


=={{header|Comal}}==
=={{header|Comal}}==
<lang comal>0010 DIM a#(0:100)
<syntaxhighlight lang="comal">0010 DIM a#(0:100)
0020 //
0020 //
0030 // Print the first 15 items
0030 // Print the first 15 items
Line 836: Line 836:
0250 RETURN 0
0250 RETURN 0
0260 ENDFUNC find#
0260 ENDFUNC find#
0270 END</lang>
0270 END</syntaxhighlight>
{{out}}
{{out}}
<pre>First 15 items: 0 1 3 6 2 7 13 20 12 21 11 22 10 23 9
<pre>First 15 items: 0 1 3 6 2 7 13 20 12 21 11 22 10 23 9
Line 842: Line 842:


=={{header|COBOL}}==
=={{header|COBOL}}==
<lang cobol> IDENTIFICATION DIVISION.
<syntaxhighlight lang="cobol"> IDENTIFICATION DIVISION.
PROGRAM-ID. RECAMAN.
PROGRAM-ID. RECAMAN.
Line 900: Line 900:
COLLATE-ITEM.
COLLATE-ITEM.
MOVE A(I) TO OUTN.
MOVE A(I) TO OUTN.
STRING OUTN DELIMITED BY SIZE INTO OUTS WITH POINTER SPTR.</lang>
STRING OUTN DELIMITED BY SIZE INTO OUTS WITH POINTER SPTR.</syntaxhighlight>
{{out}}
{{out}}
<pre>First 15 items: 0 1 3 6 2 7 13 20 12 21 11 22 10 23 9
<pre>First 15 items: 0 1 3 6 2 7 13 20 12 21 11 22 10 23 9
Line 907: Line 907:
=={{header|D}}==
=={{header|D}}==
{{trans|Kotlin}}
{{trans|Kotlin}}
<lang d>import std.stdio;
<syntaxhighlight lang="d">import std.stdio;


void main() {
void main() {
Line 945: Line 945:
n++;
n++;
}
}
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>The first 15 terms of the Recaman sequence are: [0, 1, 3, 6, 2, 7, 13, 20, 12, 21, 11, 22, 10, 23, 9]
<pre>The first 15 terms of the Recaman sequence are: [0, 1, 3, 6, 2, 7, 13, 20, 12, 21, 11, 22, 10, 23, 9]
Line 952: Line 952:


=={{header|Draco}}==
=={{header|Draco}}==
<lang draco>proc nonrec find([*] int A; word top; int n) bool:
<syntaxhighlight lang="draco">proc nonrec find([*] int A; word top; int n) bool:
word i;
word i;
bool found;
bool found;
Line 987: Line 987:
while not find(A, i, gen_next(A, i)) do i := i + 1 od;
while not find(A, i, gen_next(A, i)) do i := i + 1 od;
writeln("First repeated item: A(", i:2, ") = ", A[i]:2)
writeln("First repeated item: A(", i:2, ") = ", A[i]:2)
corp </lang>
corp </syntaxhighlight>
{{out}}
{{out}}
<pre>First 15 items: 0 1 3 6 2 7 13 20 12 21 11 22 10 23 9
<pre>First 15 items: 0 1 3 6 2 7 13 20 12 21 11 22 10 23 9
Line 996: Line 996:
{{works with|gforth|0.7.3}}
{{works with|gforth|0.7.3}}


<lang forth>: array ( n -- ) ( i -- addr)
<syntaxhighlight lang="forth">: array ( n -- ) ( i -- addr)
create cells allot
create cells allot
does> swap cells + ;
does> swap cells + ;
Line 1,029: Line 1,029:
100 sequence-gen
100 sequence-gen
15 sequence.
15 sequence.
sequence-repeated</lang>
sequence-repeated</syntaxhighlight>


{{out}}
{{out}}
Line 1,037: Line 1,037:


=={{header|FreeBASIC}}==
=={{header|FreeBASIC}}==
<lang freebasic>' version 26-01-2019
<syntaxhighlight lang="freebasic">' version 26-01-2019
' compile with: fbc -s console
' compile with: fbc -s console


Line 1,104: Line 1,104:
Print : Print "hit any key to end program"
Print : Print "hit any key to end program"
Sleep
Sleep
End</lang>
End</syntaxhighlight>
{{out}}
{{out}}
<pre>The first 15 terms are 0 0 1 3 6 2 7 13 20 12 21 11 22 10 23 9
<pre>The first 15 terms are 0 0 1 3 6 2 7 13 20 12 21 11 22 10 23 9
Line 1,114: Line 1,114:


=={{header|FOCAL}}==
=={{header|FOCAL}}==
<lang FOCAL>01.10 T "FIRST 15"
<syntaxhighlight lang="focal">01.10 T "FIRST 15"
01.20 F N=0,14;D 2;T %2,A(N)
01.20 F N=0,14;D 2;T %2,A(N)
01.30 T !"FIRST REPEATED"
01.30 T !"FIRST REPEATED"
Line 1,132: Line 1,132:
02.50 I (Y)2.6,2.7,2.6
02.50 I (Y)2.6,2.7,2.6
02.60 S A(N)=X;R
02.60 S A(N)=X;R
02.70 S A(N)=A(N-1)+N</lang>
02.70 S A(N)=A(N-1)+N</syntaxhighlight>


{{out}}
{{out}}
Line 1,150: Line 1,150:
=={{header|Go}}==
=={{header|Go}}==


<lang go>package main
<syntaxhighlight lang="go">package main


import "fmt"
import "fmt"
Line 1,188: Line 1,188:
}
}
}
}
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 1,200: Line 1,200:
===Recursion===
===Recursion===
A basic recursive function for the first N terms,
A basic recursive function for the first N terms,
<lang haskell>recaman :: Int -> [Int]
<syntaxhighlight lang="haskell">recaman :: Int -> [Int]
recaman n = fst <$> reverse (go n)
recaman n = fst <$> reverse (go n)
where
where
Line 1,215: Line 1,215:


main :: IO ()
main :: IO ()
main = print $ recaman 15</lang>
main = print $ recaman 15</syntaxhighlight>
{{Out}}
{{Out}}
<pre>[0,1,3,6,2,7,13,20,12,21,11,22,10,23,9]</pre>
<pre>[0,1,3,6,2,7,13,20,12,21,11,22,10,23,9]</pre>
Line 1,222: Line 1,222:
Or, a little more flexibly, a '''recamanUpto''' (predicate) function.
Or, a little more flexibly, a '''recamanUpto''' (predicate) function.
{{Trans|JavaScript}}
{{Trans|JavaScript}}
<lang haskell>import Data.Set (Set, fromList, insert, isSubsetOf, member, size)
<syntaxhighlight lang="haskell">import Data.Set (Set, fromList, insert, isSubsetOf, member, size)
import Data.Bool (bool)
import Data.Bool (bool)


Line 1,263: Line 1,263:
, "Length of Recaman series required to include [0..1000]:"
, "Length of Recaman series required to include [0..1000]:"
, (show . length . recamanSuperset) $ fromList [0 .. 1000]
, (show . length . recamanSuperset) $ fromList [0 .. 1000]
]</lang>
]</syntaxhighlight>
{{Out}}
{{Out}}
<pre>First 15 Recamans:
<pre>First 15 Recamans:
Line 1,279: Line 1,279:
For the third task, it would be enough to search through an infinite stream of Recaman-generated integer '''sets''' of increasing size, until we find the first that contains [0..1000] as a subset.
For the third task, it would be enough to search through an infinite stream of Recaman-generated integer '''sets''' of increasing size, until we find the first that contains [0..1000] as a subset.


<lang haskell>import Data.List (find, findIndex, nub)
<syntaxhighlight lang="haskell">import Data.List (find, findIndex, nub)
import Data.Maybe (fromJust)
import Data.Maybe (fromJust)
import Data.Set (Set, fromList, insert, isSubsetOf, member)
import Data.Set (Set, fromList, insert, isSubsetOf, member)
Line 1,325: Line 1,325:
"Length of Recaman series required to include [0..1000]:",
"Length of Recaman series required to include [0..1000]:",
show . fromJust $ findIndex (\(setR, _) -> isSubsetOf setK setR) rSets
show . fromJust $ findIndex (\(setR, _) -> isSubsetOf setK setR) rSets
]</lang>
]</syntaxhighlight>
{{Out}}
{{Out}}
<pre>First 15 Recamans:
<pre>First 15 Recamans:
Line 1,377: Line 1,377:
</pre>
</pre>
Let's write a binary search adverb.
Let's write a binary search adverb.
<syntaxhighlight lang="j">
<lang J>
average =: +/ % #
average =: +/ % #
NB. extra_data u Bsearch bounds
NB. extra_data u Bsearch bounds
Line 1,385: Line 1,385:
NB. u is invoked as a dyad
NB. u is invoked as a dyad
Bsearch =: 1 :'((0 1 + (u <.@:average)) { ({. , <.@:average, {:)@:])^:_'
Bsearch =: 1 :'((0 1 + (u <.@:average)) { ({. , <.@:average, {:)@:])^:_'
</syntaxhighlight>
</lang>
<pre>
<pre>
NB. f expresses "not all [0, 1000] are in the first y members of list x"
NB. f expresses "not all [0, 1000] are in the first y members of list x"
Line 1,404: Line 1,404:
=={{header|Java}}==
=={{header|Java}}==
{{Trans|Kotlin}}
{{Trans|Kotlin}}
<lang java>import java.util.ArrayList;
<syntaxhighlight lang="java">import java.util.ArrayList;
import java.util.HashSet;
import java.util.HashSet;
import java.util.List;
import java.util.List;
Line 1,448: Line 1,448:
}
}
}
}
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>The first 15 terms of the Recaman sequence are : [0, 1, 3, 6, 2, 7, 13, 20, 12, 21, 11, 22, 10, 23, 9]
<pre>The first 15 terms of the Recaman sequence are : [0, 1, 3, 6, 2, 7, 13, 20, 12, 21, 11, 22, 10, 23, 9]
Line 1,456: Line 1,456:
=={{header|JavaScript}}==
=={{header|JavaScript}}==
{{Trans|Haskell}}
{{Trans|Haskell}}
<lang javascript>(() => {
<syntaxhighlight lang="javascript">(() => {
const main = () => {
const main = () => {


Line 1,541: Line 1,541:
// MAIN ------------------------------------------------
// MAIN ------------------------------------------------
return main();
return main();
})();</lang>
})();</syntaxhighlight>
{{Out}}
{{Out}}
<pre>First 15 Recaman:
<pre>First 15 Recaman:
Line 1,572: Line 1,572:
the main function only retains the first few elements of the sequence
the main function only retains the first few elements of the sequence
required to print them as an array.
required to print them as an array.
<syntaxhighlight lang="jq">
<lang jq>
# Let R[n] be the Recaman sequence, n >= 0, so R[0]=0.
# Let R[n] be the Recaman sequence, n >= 0, so R[0]=0.
# Input: a number, $required, specifying the required range of integers, [1 .. $required]
# Input: a number, $required, specifying the required range of integers, [1 .. $required]
Line 1,618: Line 1,618:
| "The first \($capture) terms of Recaman's sequence are: \(.a)",
| "The first \($capture) terms of Recaman's sequence are: \(.a)",
"The first duplicated term is a[\(.foundDupAt)] = \(.foundDup)",
"The first duplicated term is a[\(.foundDupAt)] = \(.foundDup)",
"Terms up to a[\(.n)] are needed to generate 0 to \($required) inclusive."</lang>
"Terms up to a[\(.n)] are needed to generate 0 to \($required) inclusive."</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,626: Line 1,626:
</pre>
</pre>
=== A stream-oriented solution===
=== A stream-oriented solution===
<syntaxhighlight lang="jq">
<lang jq>
# Output: the stream of elements in the Recaman sequence, beginning with 0.
# Output: the stream of elements in the Recaman sequence, beginning with 0.
def recaman:
def recaman:
Line 1,660: Line 1,660:
else .
else .
end;
end;
select(.emit).emit) );</lang>
select(.emit).emit) );</syntaxhighlight>
'''The three tasks:'''
'''The three tasks:'''
<syntaxhighlight lang="jq">
<lang jq>
"First 15:", limit(15; recaman),
"First 15:", limit(15; recaman),


Line 1,669: Line 1,669:
"\Index of first element to include 0 to 1000 inclusive:",
"\Index of first element to include 0 to 1000 inclusive:",
(1000|covers(recaman))
(1000|covers(recaman))
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 1,698: Line 1,698:
=={{header|Julia}}==
=={{header|Julia}}==
{{trans|Go}}
{{trans|Go}}
<lang julia>function recaman()
<syntaxhighlight lang="julia">function recaman()
a = Vector{Int}([0])
a = Vector{Int}([0])
used = Dict{Int, Bool}(0 => true)
used = Dict{Int, Bool}(0 => true)
Line 1,728: Line 1,728:


recaman()
recaman()
</lang>{{output}}<pre>
</syntaxhighlight>{{output}}<pre>
The first 15 terms of the Recaman sequence are [0, 1, 3, 6, 2, 7, 13, 20, 12, 21, 11, 22, 10, 23, 9]
The first 15 terms of the Recaman sequence are [0, 1, 3, 6, 2, 7, 13, 20, 12, 21, 11, 22, 10, 23, 9]
The first duplicated term is a[25] = 42.
The first duplicated term is a[25] = 42.
Line 1,736: Line 1,736:
=={{header|Kotlin}}==
=={{header|Kotlin}}==
{{trans|Go}}
{{trans|Go}}
<lang scala>// Version 1.2.60
<syntaxhighlight lang="scala">// Version 1.2.60


fun main(args: Array<String>) {
fun main(args: Array<String>) {
Line 1,765: Line 1,765:
n++
n++
}
}
}</lang>
}</syntaxhighlight>


{{output}}
{{output}}
Line 1,777: Line 1,777:
This runs out of memory determining the final part :(
This runs out of memory determining the final part :(
{{trans|C++}}
{{trans|C++}}
<lang lua>local a = {[0]=0}
<syntaxhighlight lang="lua">local a = {[0]=0}
local used = {[0]=true}
local used = {[0]=true}
local used1000 = {[0]=true}
local used1000 = {[0]=true}
Line 1,811: Line 1,811:
end
end
n = n + 1
n = n + 1
end</lang>
end</syntaxhighlight>
{{out}}
{{out}}
<pre>The first 15 terms of the Recaman sequence are: 0 1 3 6 2 7 13 20 12 21 11 22 10 23 9
<pre>The first 15 terms of the Recaman sequence are: 0 1 3 6 2 7 13 20 12 21 11 22 10 23 9
Line 1,818: Line 1,818:


=={{header|MAD}}==
=={{header|MAD}}==
<lang mad> NORMAL MODE IS INTEGER
<syntaxhighlight lang="mad"> NORMAL MODE IS INTEGER
VECTOR VALUES ELEMF = $2HA(,I2,4H) = ,I2*$
VECTOR VALUES ELEMF = $2HA(,I2,4H) = ,I2*$
DIMENSION A(100)
DIMENSION A(100)
Line 1,855: Line 1,855:
FUNCTION RETURN A(N)
FUNCTION RETURN A(N)
END OF FUNCTION
END OF FUNCTION
END OF PROGRAM </lang>
END OF PROGRAM </syntaxhighlight>
{{out}}
{{out}}
<pre>FIRST 15 ELEMENTS
<pre>FIRST 15 ELEMENTS
Line 1,878: Line 1,878:


=={{header|Mathematica}} / {{header|Wolfram Language}}==
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<lang Mathematica>ClearAll[f]
<syntaxhighlight lang="mathematica">ClearAll[f]
f[s_List] := Block[{a = s[[-1]], len = Length@s},
f[s_List] := Block[{a = s[[-1]], len = Length@s},
Append[s, If[a > len && ! MemberQ[s, a - len], a - len, a + len]]]; g = Nest[f, {0}, 70]
Append[s, If[a > len && ! MemberQ[s, a - len], a - len, a + len]]]; g = Nest[f, {0}, 70]
Line 1,885: Line 1,885:
p = Select[Tally[g], Last /* EqualTo[2]][[All, 1]]
p = Select[Tally[g], Last /* EqualTo[2]][[All, 1]]
p = Flatten[Position[g, #]] & /@ p;
p = Flatten[Position[g, #]] & /@ p;
TakeSmallestBy[p, Last, 1][[1]]</lang>
TakeSmallestBy[p, Last, 1][[1]]</syntaxhighlight>
{{out}}
{{out}}
<pre>{0,1,3,6,2,7,13,20,12,21,11,22,10,23,9}
<pre>{0,1,3,6,2,7,13,20,12,21,11,22,10,23,9}
Line 1,893: Line 1,893:
=={{header|Microsoft Small Basic}}==
=={{header|Microsoft Small Basic}}==
Inefficency of associative array allocation in Small Basic ban to provide the optional task.
Inefficency of associative array allocation in Small Basic ban to provide the optional task.
<lang smallbasic>' Recaman's sequence - smallbasic - 05/08/2015
<syntaxhighlight lang="smallbasic">' Recaman's sequence - smallbasic - 05/08/2015
nn=15
nn=15
TextWindow.WriteLine("Recaman's sequence for the first " + nn + " numbers:")
TextWindow.WriteLine("Recaman's sequence for the first " + nn + " numbers:")
Line 1,936: Line 1,936:
EndFor
EndFor
exitsub:
exitsub:
EndSub </lang>
EndSub </syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,945: Line 1,945:


=={{header|Nim}}==
=={{header|Nim}}==
<lang Nim>import sequtils, sets, strutils
<syntaxhighlight lang="nim">import sequtils, sets, strutils


iterator recaman(num: Positive = Natural.high): tuple[n, a: int; duplicate: bool] =
iterator recaman(num: Positive = Natural.high): tuple[n, a: int; duplicate: bool] =
Line 1,971: Line 1,971:
if target.card == 0:
if target.card == 0:
echo "All numbers from 0 to 1000 generated after $1 terms.".format(n)
echo "All numbers from 0 to 1000 generated after $1 terms.".format(n)
break</lang>
break</syntaxhighlight>


{{out}}
{{out}}
Line 1,980: Line 1,980:
=={{header|Objeck}}==
=={{header|Objeck}}==
{{trans|Java}}
{{trans|Java}}
<lang objeck>use Collection.Generic;
<syntaxhighlight lang="objeck">use Collection.Generic;


class RecamanSequence {
class RecamanSequence {
Line 2,039: Line 2,039:
return out;
return out;
}
}
}</lang>
}</syntaxhighlight>


{{output}}
{{output}}
Line 2,049: Line 2,049:


=={{header|Perl}}==
=={{header|Perl}}==
<lang perl>use bignum;
<syntaxhighlight lang="perl">use bignum;


$max = 1000;
$max = 1000;
Line 2,070: Line 2,070:
print "First fifteen terms of Recaman's sequence: " . join(' ', @recamans[0..14]) . "\n";
print "First fifteen terms of Recaman's sequence: " . join(' ', @recamans[0..14]) . "\n";
print "First duplicate at term: a[$dup]\n";
print "First duplicate at term: a[$dup]\n";
print "Range 0..1000 covered by terms up to a[$term]\n";</lang>
print "Range 0..1000 covered by terms up to a[$term]\n";</syntaxhighlight>
{{out}}
{{out}}
<pre>First fifteen terms of Recaman's sequence: 0 1 3 6 2 7 13 20 12 21 11 22 10 23 9
<pre>First fifteen terms of Recaman's sequence: 0 1 3 6 2 7 13 20 12 21 11 22 10 23 9
Line 2,078: Line 2,078:
=={{header|Phix}}==
=={{header|Phix}}==
{{trans|D}}
{{trans|D}}
<!--<lang Phix>(phixonline)-->
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #004080;">bool</span> <span style="color: #000000;">found_duplicate</span> <span style="color: #0000FF;">=</span> <span style="color: #004600;">false</span>
<span style="color: #004080;">bool</span> <span style="color: #000000;">found_duplicate</span> <span style="color: #0000FF;">=</span> <span style="color: #004600;">false</span>
Line 2,111: Line 2,111:
<span style="color: #000000;">n</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
<span style="color: #000000;">n</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;">end</span> <span style="color: #008080;">while</span>
<!--</lang>-->
<!--</syntaxhighlight>-->
{{out}}
{{out}}
<pre>
<pre>
Line 2,121: Line 2,121:
=={{header|PHP}}==
=={{header|PHP}}==
{{trans|Java}}
{{trans|Java}}
<lang php><?php
<syntaxhighlight lang="php"><?php
$a = array();
$a = array();
array_push($a, 0);
array_push($a, 0);
Line 2,166: Line 2,166:
$n++;
$n++;
}
}
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 2,176: Line 2,176:


=={{header|PL/I}}==
=={{header|PL/I}}==
<lang pli>recaman: procedure options(main);
<syntaxhighlight lang="pli">recaman: procedure options(main);
declare A(0:30) fixed;
declare A(0:30) fixed;
Line 2,218: Line 2,218:
do i=15 repeat(i+1) while(^find(generate(i), i)); end;
do i=15 repeat(i+1) while(^find(generate(i), i)); end;
put edit('A(',i,') = ',A(i)) (A,F(2),A,F(2));
put edit('A(',i,') = ',A(i)) (A,F(2),A,F(2));
end recaman;</lang>
end recaman;</syntaxhighlight>
{{out}}
{{out}}
<pre>First 15 members: 0 1 3 6 2 7 13 20 12 21 11 22 10 23 9
<pre>First 15 members: 0 1 3 6 2 7 13 20 12 21 11 22 10 23 9
Line 2,224: Line 2,224:


=={{header|PL/M}}==
=={{header|PL/M}}==
<lang pli>100H:
<syntaxhighlight lang="pli">100H:
BDOS: PROCEDURE(F,A); DECLARE F BYTE, A ADDRESS; GO TO 5; END BDOS;
BDOS: PROCEDURE(F,A); DECLARE F BYTE, A ADDRESS; GO TO 5; END BDOS;
EXIT: PROCEDURE; CALL BDOS(0,0); END EXIT;
EXIT: PROCEDURE; CALL BDOS(0,0); END EXIT;
Line 2,291: Line 2,291:
CALL PRINT$STR(.(13,10,'$'));
CALL PRINT$STR(.(13,10,'$'));
CALL EXIT;
CALL EXIT;
EOF</lang>
EOF</syntaxhighlight>
{{out}}
{{out}}
<pre>FIRST 15 MEMBERS: 0 1 3 6 2 7 13 20 12 21 11 22 10 23 9
<pre>FIRST 15 MEMBERS: 0 1 3 6 2 7 13 20 12 21 11 22 10 23 9
Line 2,297: Line 2,297:


=={{header|PureBasic}}==
=={{header|PureBasic}}==
<lang PureBasic>#MAX=500000
<syntaxhighlight lang="purebasic">#MAX=500000
Dim a.i(#MAX)
Dim a.i(#MAX)
Dim b.b(1)
Dim b.b(1)
Line 2,322: Line 2,322:
PrintN("Number of Recaman terms needed to generate all integers from [0..1000]: "+Str(fit1000))
PrintN("Number of Recaman terms needed to generate all integers from [0..1000]: "+Str(fit1000))
Input()
Input()
End</lang>
End</syntaxhighlight>
{{out}}
{{out}}
<pre>First 15 terms: 0 1 3 6 2 7 13 20 12 21 11 22 10 23 9
<pre>First 15 terms: 0 1 3 6 2 7 13 20 12 21 11 22 10 23 9
Line 2,331: Line 2,331:
=={{header|Python}}==
=={{header|Python}}==
===Conditional iteration over a generator===
===Conditional iteration over a generator===
<lang python>from itertools import islice
<syntaxhighlight lang="python">from itertools import islice


class Recamans():
class Recamans():
Line 2,372: Line 2,372:
if setn.issubset(recamans.a):
if setn.issubset(recamans.a):
print(f"Range 0 ..{n} is covered by terms up to a({recamans.n})")
print(f"Range 0 ..{n} is covered by terms up to a({recamans.n})")
break</lang>
break</syntaxhighlight>


{{out}}
{{out}}
Line 2,383: Line 2,383:


( This turns out to be c. 8X faster than than the ''iteration over generator'' approach above, on a simple start to end measure using ''time.time()'')
( This turns out to be c. 8X faster than than the ''iteration over generator'' approach above, on a simple start to end measure using ''time.time()'')
<lang python>'''Recaman sequence'''
<syntaxhighlight lang="python">'''Recaman sequence'''




Line 2,449: Line 2,449:


if __name__ == '__main__':
if __name__ == '__main__':
main()</lang>
main()</syntaxhighlight>
{{Out}}
{{Out}}
<pre>First 15 Recaman:
<pre>First 15 Recaman:
Line 2,465: Line 2,465:
( This version is still c. 8X faster than the ''conditional iteration over generator'' version, as measured by a simple start and end test using ''time.time()'' ).
( This version is still c. 8X faster than the ''conditional iteration over generator'' version, as measured by a simple start and end test using ''time.time()'' ).


<lang python>'''Recaman by iteration of a function over a tuple.'''
<syntaxhighlight lang="python">'''Recaman by iteration of a function over a tuple.'''


from itertools import (islice)
from itertools import (islice)
Line 2,574: Line 2,574:
# MAIN ---
# MAIN ---
if __name__ == '__main__':
if __name__ == '__main__':
main()</lang>
main()</syntaxhighlight>
<pre>First 15 Recaman:
<pre>First 15 Recaman:
[0, 1, 3, 6, 2, 7, 13, 20, 12, 21, 11, 22, 10, 23, 9]
[0, 1, 3, 6, 2, 7, 13, 20, 12, 21, 11, 22, 10, 23, 9]
Line 2,584: Line 2,584:
=={{header|Quackery}}==
=={{header|Quackery}}==


<syntaxhighlight lang="quackery">
<lang Quackery>
[ stack 0 ] is seennumbers ( --> s )
[ stack 0 ] is seennumbers ( --> s )


Line 2,633: Line 2,633:
1000 allseen? until ]
1000 allseen? until ]
nip 1 - echo cr
nip 1 - echo cr
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 2,645: Line 2,645:
=={{header|R}}==
=={{header|R}}==
A bit slow because the append() function is expensive.
A bit slow because the append() function is expensive.
<lang rsplus>
<syntaxhighlight lang="rsplus">
visited <- vector('logical', 1e8)
visited <- vector('logical', 1e8)


Line 2,687: Line 2,687:
}
}
}
}
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 2,699: Line 2,699:
{{works with|Rakudo|2018.06}}
{{works with|Rakudo|2018.06}}


<lang perl6>my @recamans = 0, {
<syntaxhighlight lang="raku" line>my @recamans = 0, {
state %seen;
state %seen;
state $term;
state $term;
Line 2,719: Line 2,719:
@seen[$this] = 1;
@seen[$this] = 1;
say "Range 0..1000 covered by terms up to a[{$i - 1}]" and last if ++$ == 1001;
say "Range 0..1000 covered by terms up to a[{$i - 1}]" and last if ++$ == 1001;
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>First fifteen terms of Recaman's sequence: 0 1 3 6 2 7 13 20 12 21 11 22 10 23 9
<pre>First fifteen terms of Recaman's sequence: 0 1 3 6 2 7 13 20 12 21 11 22 10 23 9
Line 2,735: Line 2,735:
could've been replaced with:
could've been replaced with:
if !.z | z<0 then z= _ + #
if !.z | z<0 then z= _ + #
<lang rexx>/*REXX pgm computes a Recamán sequence up to N; the 1st dup; # terms for a range of #'s.*/
<syntaxhighlight lang="rexx">/*REXX pgm computes a Recamán sequence up to N; the 1st dup; # terms for a range of #'s.*/
parse arg N h . /*obtain optional arguments from the CL*/
parse arg N h . /*obtain optional arguments from the CL*/
if N=='' | N=="," then N= 15 /*Not specified? Then use the default.*/
if N=='' | N=="," then N= 15 /*Not specified? Then use the default.*/
Line 2,760: Line 2,760:
end
end
$= $ z /*add number to $ list?*/
$= $ z /*add number to $ list?*/
end /*#*/; return $ /*return the $ list. */</lang>
end /*#*/; return $ /*return the $ list. */</syntaxhighlight>
{{out|output|text=&nbsp; when using the default input:}}
{{out|output|text=&nbsp; when using the default input:}}


Line 2,773: Line 2,773:


===version 2===
===version 2===
<lang rexx>/*REXX program computes & displays the Recaman sequence */
<syntaxhighlight lang="rexx">/*REXX program computes & displays the Recaman sequence */
/*improved using version 1's method for task 3 */
/*improved using version 1's method for task 3 */
Call time 'R' /* Start timer */
Call time 'R' /* Start timer */
Line 2,818: Line 2,818:
Have.temp=1
Have.temp=1
End
End
Return s</lang>
Return s</syntaxhighlight>
{{out}}
{{out}}
<pre>the first 15 elements: 0 1 3 6 2 7 13 20 12 21 11 22 10 23 9
<pre>the first 15 elements: 0 1 3 6 2 7 13 20 12 21 11 22 10 23 9
Line 2,826: Line 2,826:


=={{header|Ring}}==
=={{header|Ring}}==
<lang ring>
<syntaxhighlight lang="ring">
load "zerolib.ring"
load "zerolib.ring"


Line 2,876: Line 2,876:
see "" + dupnr + "] = " + duplicate + nl
see "" + dupnr + "] = " + duplicate + nl
see "done..." + nl
see "done..." + nl
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 2,888: Line 2,888:
=={{header|Ruby}}==
=={{header|Ruby}}==
{{trans|Kotlin}}
{{trans|Kotlin}}
<lang ruby>require 'set'
<syntaxhighlight lang="ruby">require 'set'


a = [0]
a = [0]
Line 2,919: Line 2,919:
end
end
n = n + 1
n = n + 1
end</lang>
end</syntaxhighlight>
{{out}}
{{out}}
<pre>The first 15 terms of the Recaman's sequence are [0, 1, 3, 6, 2, 7, 13, 20, 12, 21, 11, 22, 10, 23, 9]
<pre>The first 15 terms of the Recaman's sequence are [0, 1, 3, 6, 2, 7, 13, 20, 12, 21, 11, 22, 10, 23, 9]
Line 2,927: Line 2,927:
=={{header|Scala}}==
=={{header|Scala}}==
{{Out}}Best seen in running your browser either by [https://scalafiddle.io/sf/xjLHy7m/0 ScalaFiddle (ES aka JavaScript, non JVM)] or [https://scastie.scala-lang.org/FdJaIB68S8i5OSndpigBtA Scastie (remote JVM)].
{{Out}}Best seen in running your browser either by [https://scalafiddle.io/sf/xjLHy7m/0 ScalaFiddle (ES aka JavaScript, non JVM)] or [https://scastie.scala-lang.org/FdJaIB68S8i5OSndpigBtA Scastie (remote JVM)].
<lang Scala>import scala.collection.mutable
<syntaxhighlight lang="scala">import scala.collection.mutable


object RecamansSequence extends App {
object RecamansSequence extends App {
Line 2,955: Line 2,955:
println(s"The first 15 terms of the Recaman sequence are : ${a.take(15)}")
println(s"The first 15 terms of the Recaman sequence are : ${a.take(15)}")


}</lang>
}</syntaxhighlight>
=={{header|Scheme}}==
=={{header|Scheme}}==
{{works with|Chez Scheme}}
{{works with|Chez Scheme}}
<lang scheme>; Create a dynamically resizing vector (a "dynvec").
<syntaxhighlight lang="scheme">; Create a dynamically resizing vector (a "dynvec").
; Returns a procedure that takes a variable number of arguments:
; Returns a procedure that takes a variable number of arguments:
; 0 : () --> Returns the vector from index 0 through the maximum index set.
; 0 : () --> Returns the vector from index 0 through the maximum index set.
Line 3,045: Line 3,045:
(printf
(printf
"Terms of Recaman's sequence to generate all integers 0..~a, inclusive: ~a~%"
"Terms of Recaman's sequence to generate all integers 0..~a, inclusive: ~a~%"
(1- all-first) terms-to-gen-all))</lang>
(1- all-first) terms-to-gen-all))</syntaxhighlight>
{{out}}
{{out}}
<pre>First 15 Recaman's numbers: #(0 1 3 6 2 7 13 20 12 21 11 22 10 23 9)
<pre>First 15 Recaman's numbers: #(0 1 3 6 2 7 13 20 12 21 11 22 10 23 9)
Line 3,052: Line 3,052:


=={{header|Sidef}}==
=={{header|Sidef}}==
<lang ruby>func recamans_generator() {
<syntaxhighlight lang="ruby">func recamans_generator() {


var term = 0
var term = 0
Line 3,097: Line 3,097:
}
}
}
}
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>First 15 terms of the Recaman's sequence: 0, 1, 3, 6, 2, 7, 13, 20, 12, 21, 11, 22, 10, 23, 9
<pre>First 15 terms of the Recaman's sequence: 0, 1, 3, 6, 2, 7, 13, 20, 12, 21, 11, 22, 10, 23, 9
Line 3,104: Line 3,104:


=={{header|uBasic/4tH}}==
=={{header|uBasic/4tH}}==
<lang basic>a = 0 ' the first one is free ;-)
<syntaxhighlight lang="basic">a = 0 ' the first one is free ;-)
Print "First 15 numbers:"
Print "First 15 numbers:"


Line 3,118: Line 3,118:
_Poke Param(2) : Return (Or(@(a@), Shl(1, b@)))
_Poke Param(2) : Return (Or(@(a@), Shl(1, b@)))
_Peek Param(1) : Return (And(@(a@/32), Shl(1, a@%32))>0)
_Peek Param(1) : Return (And(@(a@/32), Shl(1, a@%32))>0)
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 3,131: Line 3,131:
{{trans|Rexx}}
{{trans|Rexx}}
To run in console mode with cscript.
To run in console mode with cscript.
<lang vb>' Recaman's sequence - vbscript - 04/08/2015
<syntaxhighlight lang="vb">' Recaman's sequence - vbscript - 04/08/2015
nx=15
nx=15
h=1000
h=1000
Line 3,188: Line 3,188:
next 'n
next 'n
recaman=list
recaman=list
end function 'recaman</lang>
end function 'recaman</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 3,199: Line 3,199:
=={{header|Visual Basic .NET}}==
=={{header|Visual Basic .NET}}==
{{trans|C#}}
{{trans|C#}}
<lang vbnet>Imports System
<syntaxhighlight lang="vbnet">Imports System
Imports System.Collections.Generic
Imports System.Collections.Generic


Line 3,223: Line 3,223:
Next
Next
End Sub
End Sub
End Module</lang>{{out}}
End Module</syntaxhighlight>{{out}}
<pre>The first 15 terms of the Recamán sequence are: (0, 1, 3, 6, 2, 7, 13, 20, 12, 21, 11, 22, 10, 23, 9)
<pre>The first 15 terms of the Recamán sequence are: (0, 1, 3, 6, 2, 7, 13, 20, 12, 21, 11, 22, 10, 23, 9)
The first duplicated term is a(24) = 42
The first duplicated term is a(24) = 42
Line 3,230: Line 3,230:
=={{header|Wren}}==
=={{header|Wren}}==
{{trans|Kotlin}}
{{trans|Kotlin}}
<lang ecmascript>var a = [0]
<syntaxhighlight lang="ecmascript">var a = [0]
var used = { 0: true }
var used = { 0: true }
var used1000 = { 0: true }
var used1000 = { 0: true }
Line 3,253: Line 3,253:
}
}
n = n + 1
n = n + 1
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 3,264: Line 3,264:


=={{header|zkl}}==
=={{header|zkl}}==
<lang zkl>fcn recamanW{ // -->iterator -->(n,a,True if a is a dup)
<syntaxhighlight lang="zkl">fcn recamanW{ // -->iterator -->(n,a,True if a is a dup)
Walker.tweak(fcn(rn,rp,d){
Walker.tweak(fcn(rn,rp,d){
n,p,a := rn.value, rp.value, p - n;
n,p,a := rn.value, rp.value, p - n;
Line 3,271: Line 3,271:
return(rn.inc(),a,d[a]>1);
return(rn.inc(),a,d[a]>1);
}.fp(Ref(0),Ref(0),Dictionary()) )
}.fp(Ref(0),Ref(0),Dictionary()) )
}</lang>
}</syntaxhighlight>
<lang zkl>print("First 15 members of Recaman's sequence: ");
<syntaxhighlight lang="zkl">print("First 15 members of Recaman's sequence: ");
recamanW().walk(15).apply("get",1).println();
recamanW().walk(15).apply("get",1).println();


Line 3,280: Line 3,280:
rw,ns,n,a,dup := recamanW(),1000,0,0,0;
rw,ns,n,a,dup := recamanW(),1000,0,0,0;
do{ n,a,dup=rw.next(); if(not dup and a<1000) ns-=1; }while(ns);
do{ n,a,dup=rw.next(); if(not dup and a<1000) ns-=1; }while(ns);
println("Range 0..1000 is covered by terms up to a(%,d)".fmt(n));</lang>
println("Range 0..1000 is covered by terms up to a(%,d)".fmt(n));</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>