javascript

Van Ecks Sequence - Bloomberg - Asset Management AIM - Full Stack - 11/5/21

// Van Eck is a sequence that has 3 properties:
//   - Starts with 0
//   - For each element, count the number of steps since it's last appeared. This number of steps becomes the next term
//   - If the element has not appeared before, the next term is 0

// Sequence: [0, 0, 1, 0, 2, 0, 2, 2, 1, 6, 0, 5, ...]
//           [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

// Problem: Given an index, define a function that returns the element in Van Eck's sequence at that index.

function vanEcksAtIndex(index) {
    let arr = [0];
    // Last index which the number as appeared 
    let lastAppeared = {0: 0};
    
    
    for (let i = 0; i < index; i++) {
        console.log('i', i)
        console.log('arr', arr)
        console.log('lastAppeared', lastAppeared)
        if (lastAppeared[arr[i]] != null) {
            // Element has appeared before
            arr.push(i - lastAppeared[arr[i]]);
        } else {
            // Element hasn't appeared before
            arr.push(0);
        }
        lastAppeared[arr[i]] = i;
    }
    
    return arr[index];
}

// arr = [0], lastAppeared = { 0: 0 }
// i = 0, arr = [0, 0], lastAppeared = { 0: 0 }
// i = 1, arr = [0, 0, 1], lastAppeared = { 0: 1 }

console.log(vanEcksAtIndex(9));
Was this helpful?