Unable to load image

Advent of Code 2022 : Day 9

grate filter edition

:#marseycapyhacker:

17
Jump in the discussion.

No email address required.

I got filtered for a LONG time on part 2 because my logic was setting the head to whatever position it should be in, then iterating all the steps of the tail pieces from where they are to where they should be. I still feel like this should have worked, it worked fine on the test inputs.

I switched it to move the head one space at a time and then iterate the tail pieces every time it moved and got a slightly different (but correct) answer.

Edit: code, spits out part 1 in s[1] and part 2 in s[9]

var lines = document.body.innerText.split("\n");
lines.splice(lines.length-1,1);

var h = {x: 0,y: 0};
var t = {x: 0,y: 0};
var k = [];
var s = [];
s[0] = new Set();

for (var i=0;i<10;i++) {
    k[i] = {x: 0,y: 0};
}

function moveH(x,y) {
    k[0].x += x;
    k[0].y += y;
    s[0].add(k[0].x.toString() + "," + k[0].y.toString());
  
    for (var i=1; i<10; i++) {
        moveK(k[i-1],k[i],i);
    }
}

function norm(v) {
    return { 
        x: (!v.x ? 0 : (v.x > 0 ? 1 : -1)),
        y: (!v.y ? 0 : (v.y > 0 ? 1 : -1))
    };
}

function moveK(last,current,index) {
    var d = {x: last.x - current.x, y: last.y - current.y};

    if (!s[index]) {
        s[index] = new Set();
        s[index].add("0,0");
    }

    while (Math.abs(d.x) > 1 || Math.abs(d.y) > 1) {
        var nd = norm(d);
        current.x += nd.x;
        current.y += nd.y;
        d.x -= nd.x;
        d.y -= nd.y;
        s[index].add(current.x.toString() + "," + current.y.toString());
    }
}

lines.forEach(function(line) {
    var args = line.split(" ");
    var n = !isNaN(Number(args[1])) ? Number(args[1]) : 0;
    for (var i=0;i<args[1];i++) {      
        switch (args[0]) {
            case 'U':
                moveH(0,-1);
                break;
            case 'L':
                moveH(-1,0);
                break;
            case 'R':
                moveH(1,0);
                break;
            case 'D':
                moveH(0,1);
                break;
        }
    }
});
Jump in the discussion.

No email address required.

Link copied to clipboard
Action successful!
Error, please refresh the page and try again.