(phixonline)-->
with javascript_semantics
bool found_duplicate = false
sequence a = {0}, used = {} -- (grows to 1,942,300 entries)
integer all_used = 0, n = 1, next, prev = 0
while n<=15 or not found_duplicate or all_used<1000 do
next = prev - n
if next<1 or (next<=length(used) and used[next]) then
next = prev + n
end if
a &= next
integer padlen = next-length(used)
bool already_used = padlen<=0 and used[next]
if not already_used then
if padlen>0 then used &= repeat(false,padlen) end if
used[next] = true
while all_used<length(used) and used[all_used+1] do
all_used += 1
end while
end if
if length(a)=15 then
printf(1,"The first 15 terms of the Recaman sequence are: %v\n",{a})
end if
if already_used and not found_duplicate then
printf(1,"The first duplicated term is a[%d] = %d\n", {n, next})
found_duplicate = true;
end if
if all_used>=1000 then
printf(1,"Terms up to a[%d] are needed to generate 0 to 1000\n", {n});
end if
prev = next
n += 1
end while