The sequence is generated by following this pseudo-code:

A:  The first term is zero.
    Repeatedly apply:
        If the last term is *new* to the sequence so far then:
B:          The next term is zero.
        Otherwise:
C:          The next term is how far back this last term occured previously.



Example

Using A:

0
Using B:

0 0
Using C:

0 0 1
Using B:

0 0 1 0
Using C: (zero last occurred two steps back - before the one)

0 0 1 0 2
Using B:

0 0 1 0 2 0
Using C: (two last occurred two steps back - before the zero)

0 0 1 0 2 0 2 2
Using C: (two last occurred one step back)

0 0 1 0 2 0 2 2 1
Using C: (one last appeared six steps back)

0 0 1 0 2 0 2 2 1 6
...



Task

 Create a function/procedure/method/subroutine/... to generate the Van Eck sequence of numbers.
 Use it to display here, on this page:
 The first ten terms of the sequence.
 Terms 991 - to - 1000 of the sequence.


References

 Don't Know (the Van Eck Sequence) - Numberphile video.
 Wikipedia Article: Van Eck's Sequence.
  OEIS sequence: A181391.


#include <iostream>
#include <map>
 
class van_eck_generator {
public:
    int next() {
        int result = last_term;
        auto iter = last_pos.find(last_term);
        int next_term = (iter != last_pos.end()) ? index - iter->second : 0;
        last_pos[last_term] = index;
        last_term = next_term;
        ++index;
        return result;
    }
private:
    int index = 0;
    int last_term = 0;
    std::map<int, int> last_pos;
};
 
int main() {
    van_eck_generator gen;
    int i = 0;
    std::cout << "First 10 terms of the Van Eck sequence:\n";
    for (; i < 10; ++i)
        std::cout << gen.next() << ' ';
    for (; i < 990; ++i)
        gen.next();
    std::cout << "\nTerms 991 to 1000 of the sequence:\n";
    for (; i < 1000; ++i)
        std::cout << gen.next() << ' ';
    std::cout << '\n';
    return 0;
}