06 Javascript

Part I Assignment

The code is actually a part of this very page and the result is .

// queue of last 4 characters
// init with the first character from input
var q = {
    0: input[0],
    1: input[0],
    2: input[0],
    3: input[0],
}
// counts of characters in queue
var c = {
    [input[0]]: 4
}
// iterate over the characters from input string
for (let i=0; i<input.length; i++) {
    // if the counts are all below or equal 1, that's our packet-start position
    if (c[q[0]] <= 1 && c[q[1]] <= 1 && c[q[2]] <= 1 && c[q[3]] <= 1) {
        // show the result in the webpage in element with id "result"
        document.getElementById("result").innerHTML = i
        // we don't need to continue
        break
    }
    // decrease counts of the first item from queue
    c[q[0]] -= 1
    // update counts with the new character, safely
    if (c[input[i]]) {
        c[input[i]] += 1
    }
    else {
        c[input[i]] = 1
    }
    // update queue (shift to left)
    q[0] = q[1]
    q[1] = q[2]
    q[2] = q[3]
    q[3] = input[i]
}

Part Two

The resuls for the second part is .

We needed to change the hardcoded updates of the queue to a loop and also the check for the satisfied condition is done in a loop.

Also, the code is now more general—by setting L to 4 it would solve the part one.

We also use unique names not to be mixed with the previous script.

var L = 14
var q2 = {}
for (let i=0; i<L; i++) {
    q2[i] = input[0]
}
var c2 = {
    [input[0]]: L
}
for (let i=0; i<input.length; i++) {
    // all counts must be below or equal 1
    let satisf = true
    for (let j=0; j<L; j++) {
        if (c2[q2[j]] > 1) satisf = false
    }
    if (satisf) {
        document.getElementById("result2").innerHTML = i
        break
    }
    c2[q2[0]] -= 1
    if (c2[input[i]]) {
        c2[input[i]] += 1
    }
    else {
        c2[input[i]] = 1
    }
    // update queue (shift to left)
    for (let j=0; j<L-1; j++) {
        q2[j] = q2[j+1]
    }
    q2[L-1] = input[i]
}

What I learned

published: 2022-12-06
last modified: 2023-01-21

https://vit.baisa.cz/notes/code/advent-of-code-2022/06/