user
The **Recamán's sequence** generates Natural numbers.

Starting from a(0)=0, the n'th term `a(n)`, where n>0, is the previous term minus `n` i.e `a(n) = a(n-1) - n` but only if this is **both** positive *and* has not been previously generated.

If the conditions *don't* hold then `a(n) = a(n-1) + n`.

Task

1. Generate and show here the first 15 members of the sequence.
2. Find and show here, the first duplicated number in the sequence.
3. **Optionally**: Find and show here, how many terms of the sequence are needed until all the integers 0..1000, inclusive, are generated.

References

* A005132, The On-Line Encyclopedia of Integer Sequences.
* The Slightly Spooky Recamán Sequence, Numberphile video.
* Recamán's sequence, on Wikipedia.
assistant
(formerly Perl 6)

**Works with**: Rakudo version 2018.06

```
my @recamans = 0, {
   state %seen;
   state $term;
   $term++;
   my $this = $^previous - $term;
   $this = $previous + $term unless ($this > 0) && !%seen{$this};
   %seen{$this} = True;
   $this
} … *;

put "First fifteen terms of Recaman's sequence: ", @recamans[^15];

say "First duplicate at term: a[{ @recamans.first({@recamans[^$_].Bag.values.max == 2})-1 }]";

my @seen;
my int $i = 0;
loop {
    next if (my int $this = @recamans[$i++]) > 1000 or @seen[$this];
    @seen[$this] = 1;
    say "Range 0..1000 covered by terms up to a[{$i - 1}]" and last if ++$ == 1001;
}

```

Output:

```
First fifteen terms of Recaman's sequence: 0 1 3 6 2 7 13 20 12 21 11 22 10 23 9
First duplicate at term: a[24]
Range 0..1000 covered by terms up to a[328002]
```