RosettaCodeData/Task/Van-Eck-sequence/Agena/van-eck-sequence.agena
2026-02-01 16:33:20 -08:00

26 lines
1.1 KiB
Text

scope # find elements of the Van Eck Sequence - first term is 0, following
# terms are 0 if the previous was the first appearance of the element
# or how far back in the sequence the last element appeared otherwise
local proc VanEck( n :: number ) :: sequence # returns the first n elements of the Van Eck sequence
local constant result := seq(); for i to n do result[ i ] := 0 od;
local constant pos := seq(); for i to n + 1 do pos[ i ] := 0 od;
for i from 2 to n do
local constant j := i - 1;
local constant prev := result[ j ] + 1; # prev is indexed from 1, not 0
if pos[ prev ] <> 0 then
# not a new element
result[ i ] := j - pos[ prev ]
fi;
pos[ prev ] := j
od;
return result
end;
local constant veSeq := VanEck( 1000 ); # construct the first 1000 terms of the sequence
# show the first and last 10 elements
for i to 10 do printf( " %d", veSeq[ i ] ) od;
printf( "\n" );
for i from size veSeq - 9 to size veSeq do printf( " %d", veSeq[ i ] ) od;
printf( "\n" )
end