2023-12-10 (*)

Table of Contents

I love this challenge. So will have more details about it.

1. Part One

— Day 10: Pipe Maze —

You use the hang glider to ride the hot air from Desert Island all the way up to the floating metal island. This island is surprisingly cold and there definitely aren't any thermals to glide on, so you leave your hang glider behind.

You wander around for a while, but you don't find any people or animals. However, you do occasionally find signposts labeled "Hot Springs" pointing in a seemingly consistent direction; maybe you can find someone at the hot springs and ask them where the desert-machine parts are made.

The landscape here is alien; even the flowers and trees are made of metal. As you stop to admire some metal grass, you notice something metallic scurry away in your peripheral vision and jump into a big pipe! It didn't look like any animal you've ever seen; if you want a better look, you'll need to get ahead of it.

Scanning the area, you discover that the entire field you're standing on is densely packed with pipes; it was hard to tell at first because they're the same metallic silver color as the "ground". You make a quick sketch of all of the surface pipes you can see (your puzzle input).

The pipes are arranged in a two-dimensional grid of tiles:

| is a vertical pipe connecting north and south.
- is a horizontal pipe connecting east and west.
L is a 90-degree bend connecting north and east.
J is a 90-degree bend connecting north and west.
7 is a 90-degree bend connecting south and west.
F is a 90-degree bend connecting south and east.
. is ground; there is no pipe in this tile.
S is the starting position of the animal; there is a pipe on this tile, but your sketch doesn't show what shape the pipe has.

Based on the acoustics of the animal's scurrying, you're confident the pipe that contains the animal is one large, continuous loop.

For example, here is a square loop of pipe:

.....
.F-7.
.|.|.
.L-J.
.....

If the animal had entered this loop in the northwest corner, the sketch would instead look like this:

.....
.S-7.
.|.|.
.L-J.
.....

In the above diagram, the S tile is still a 90-degree F bend: you can tell because of how the adjacent pipes connect to it.

Unfortunately, there are also many pipes that aren't connected to the loop! This sketch shows the same loop as above:

-L|F7
7S-7|
L|7||
-L-J|
L|-JF

In the above diagram, you can still figure out which pipes form the main loop: they're the ones connected to S, pipes those pipes connect to, pipes those pipes connect to, and so on. Every pipe in the main loop connects to its two neighbors (including S, which will have exactly two pipes connecting to it, and which is assumed to connect back to those two pipes).

Here is a sketch that contains a slightly more complex main loop:

..F7.
.FJ|.
SJ.L7
|F--J
LJ...

Here's the same example sketch with the extra, non-main-loop pipe tiles also shown:

7-F7-
.FJ|7
SJLL7
|F--J
LJ.LJ

If you want to get out ahead of the animal, you should find the tile in the loop that is farthest from the starting position. Because the animal is in the pipe, it doesn't make sense to measure this by direct distance. Instead, you need to find the tile that would take the longest number of steps along the loop to reach from the starting point - regardless of which way around the loop the animal went.

In the first example with the square loop:

.....
.S-7.
.|.|.
.L-J.
.....

You can count the distance each tile in the loop is from the starting point like this:

.....
.012.
.1.3.
.234.
.....

In this example, the farthest point from the start is 4 steps away.

Here's the more complex loop again:

..F7.
.FJ|.
SJ.L7
|F--J
LJ...

Here are the distances for each tile on that loop:

..45.
.236.
01.78
14567
23...

Find the single giant loop starting at S. How many steps along the loop does it take to get from the starting position to the point farthest from the starting position?

Get files

1.1. Ans

Play some fun, draw a diagram by using JavaScript canvas. Pipes highlighted as blue color which are we traveled.

Pseudocode for finding a loop that start from 'S' and travel pipes :

node = Stack.pop()
        1. Mark node as traveled
        2. Literate N,E,S,W direcitons
        : check current node is valid for current direction
                    -> if yes
             : check the Next Node Type is valid pipe, if ‘yes’ set as T
                            : check T can connect
                                   if Yes:
                                        -> update T value
                                        -> Stack.push(T)

Code:

let width = 1800;
let height = 1800;
let fontSize = 10;
let dataSet = [];
let markList = [];
let targetS;
let DATASET_HIGHT;
let DATASET_WIDTH;

// up, right, down, left
// N ,  E  ,   S  , W
const direction = {
    "|" : [1, 0, 1, 0],
    "-" : [0, 1, 0, 1],
    "L" : [1, 1, 0, 0],
    "J" : [1, 0, 0, 1],
    "7" : [0, 0, 1, 1],
    "F" : [0, 1, 1, 0],
    "S" : [1, 1, 1, 1],
    "." : [0, 0, 0, 0]
}


function canConnect(pipe1, pipe2, postition) {
    if(postition < 0 || postition > 4) return -1

    const pipe1Direction = direction[pipe1]
    const pipe2Direction = direction[pipe2]

    if(pipe1Direction[postition] === 0) return true

    let relatedPosition = postition - 2
    if(relatedPosition < 0) {
        relatedPosition = 4 - Math.abs(relatedPosition)
    }

    return pipe2Direction[relatedPosition] === pipe1Direction[postition] ? true : false
}


function Node(x,y,label){
    this.x = x;
    this.y = y;
    this.label = label;
    this.color = 'black';
    this.value = 0;
    this.memo = {...this}
}

const canvas = document.getElementById('game');
const ctx = canvas.getContext('2d');

canvas.width = width;
canvas.height = height;

function init() {
    r = input.split('\n')
    for (let y = 0; y < r.length; y++) {
        let col = r[y].split('')
        let tmp = [];
        for (let x = 0; x < col.length; x++) {
            let char = col[x];
            n = new Node(x,y, char)
            n.color = char === 'S' ? 'red' : 'black'
            tmp.push(n)

            if(char === 'S')
            {
                targetS = n
            }
        }

        dataSet.push(tmp)
    }
}

function loop() {
    ctx.clearRect(0, 0, height, width)

    for (let y = 0; y < dataSet.length; y++) {
        let col = dataSet[y]
        for (let x = 0; x < col.length; x++) {
            let n = col[x];
            let char = n.label
            let xPos = n.x * fontSize;
            let yPos = n.y * fontSize + fontSize;
            ctx.fillStyle = n.color
            ctx.fillText(char, xPos, yPos);
        }
    }
}

init()
loop()
DATASET_HIGHT = dataSet.length
DATASET_WIDTH = dataSet[0].length

let frame;
function start() {
    frame = setInterval(() => {
        loop();
    }, 500);
}

function stop() {
    clearInterval(frame)
}

start();
let stack = [];

function transLocation(x, y,direct){
    if(direct == 0) return [x, y - 1]; // N
    if(direct == 1) return [x + 1, y]; // E
    if(direct == 2) return [x, y + 1]; // S
    if(direct == 3) return [x - 1, y]; // W
}

function isInsideTheScene(x,y) {
    return x < DATASET_WIDTH && y <  DATASET_HIGHT && x >= 0 && y >= 0;
}

// Main Code:
function scan(node) {
    markList.push(node)

    let arrDirection  = direction[node.label] || [];
    arrDirection.map((connect, d) => {
        let targetPos = transLocation(node.x, node.y, d);
        if(isInsideTheScene(targetPos[0], targetPos[1])) {
            let targetNode = dataSet[targetPos[1]][targetPos[0]]
            if(connect === 1 && targetNode !== undefined) {
               if(canConnect(node.label, targetNode.label, d)){
                    stack.push(targetNode)
                    targetNode.value = node.value + 1;
               }
            }
        }
    })
}


scan(targetS)
while(true)
{
    let node = stack.pop();

    if(node == targetS) break;

    if(!markList.includes(node))
    {
        scan(node);
    }
}

markList.map(node => {
    node.color = 'blue'
})

console.log(stack)
console.log(markList)
console.log("Longest node length in loop: " + markList.length / 2)

My input is start from 'S' left, and trun back at 'S' top. It's only have one loop(One big loop). So the total length of loop diveded by 2 will get the anwser.

2. Part Two

— Part Two —

You quickly reach the farthest point of the loop, but the animal never emerges. Maybe its nest is within the area enclosed by the loop?

To determine whether it's even worth taking the time to search for such a nest, you should calculate how many tiles are contained within the loop. For example:

...........
.S-------7.
.|F-----7|.
.||.....||.
.||.....||.
.|L-7.F-J|.
.|..|.|..|.
.L--J.L--J.
...........

The above loop encloses merely four tiles - the two pairs of . in the southwest and southeast (marked I below). The middle . tiles (marked O below) are not in the loop. Here is the same loop again with those regions marked:

...........
.S-------7.
.|F-----7|.
.||OOOOO||.
.||OOOOO||.
.|L-7OF-J|.
.|II|O|II|.
.L--JOL--J.
.....O.....

In fact, there doesn't even need to be a full tile path to the outside for tiles to count as outside the loop - squeezing between pipes is also allowed! Here, I is still within the loop and O is still outside the loop:

..........
.S------7.
.|F----7|.
.||OOOO||.
.||OOOO||.
.|L-7F-J|.
.|II||II|.
.L--JL--J.
..........

In both of the above examples, 4 tiles are enclosed by the loop.

Here's a larger example:

.F----7F7F7F7F-7....
.|F--7||||||||FJ....
.||.FJ||||||||L7....
FJL7L7LJLJ||LJ.L-7..
L--J.L7...LJS7F-7L7.
....F-J..F7FJ|L7L7L7
....L7.F7||L7|.L7L7|
.....|FJLJ|FJ|F7|.LJ
....FJL-7.||.||||...
....L---J.LJ.LJLJ...

The above sketch has many random bits of ground, some of which are in the loop (I) and some of which are outside it (O):

OF----7F7F7F7F-7OOOO
O|F--7||||||||FJOOOO
O||OFJ||||||||L7OOOO
FJL7L7LJLJ||LJIL-7OO
L--JOL7IIILJS7F-7L7O
OOOOF-JIIF7FJ|L7L7L7
OOOOL7IF7||L7|IL7L7|
OOOOO|FJLJ|FJ|F7|OLJ
OOOOFJL-7O||O||||OOO
OOOOL---JOLJOLJLJOOO

In this larger example, 8 tiles are enclosed by the loop.

Any tile that isn't part of the main loop can count as being enclosed by the loop. Here's another example with many bits of junk pipe lying around that aren't connected to the main loop at all:

FF7FSF7F7F7F7F7F---7
L|LJ||||||||||||F--J
FL-7LJLJ||||||LJL-77
F--JF--7||LJLJ7F7FJ-
L---JF-JLJ.||-FJLJJ7
|F|F-JF---7F7-L7L|7|
|FFJF7L7F-JF7|JL---7
7-L-JL7||F7|L7F-7F7|
L.L7LFJ|||||FJL7||LJ
L7JLJL-JLJLJL--JLJ.L

Here are just the tiles that are enclosed by the loop marked with I:

FF7FSF7F7F7F7F7F---7
L|LJ||||||||||||F--J
FL-7LJLJ||||||LJL-77
F--JF--7||LJLJIF7FJ-
L---JF-JLJIIIIFJLJJ7
|F|F-JF---7IIIL7L|7|
|FFJF7L7F-JF7IIL---7
7-L-JL7||F7|L7F-7F7|
L.L7LFJ|||||FJL7||LJ
L7JLJL-JLJLJL--JLJ.L

In this last example, 10 tiles are enclosed by the loop.

Figure out whether you have time to search for the nest by calculating the area within the loop. How many tiles are enclosed by the loop?

2.1. Ans

A little bit confuse for the edge pipe definition in this part two question. And than I find other people work, figure out some of the people using 'ray casting algorithm', and that is work for my case:

A simple way of Ray casting algorithm

This algorithm is for finding point (let as A) isn't inside the graph. In simple version, we can just use horizontal direction. Let A point extend to the right to the end, when the A extending, it will through some shape edges. Count the total crossing and if the result is odd number, it means the point is inside the shape, else is outside the shape.

Visualization:

Using this method, there have some notices:

  1. the 'S' need to change into other symbol, based on your input. In my case, my S only have two start point: Left, and Top, so it represent as 'J'.
  2. If We look at horizontal to the end of the line, the pipe edge is just '|', 'FJ' and 'L7'. Other symbol can ignore.

'FJ' and 'L7' as one pipe, The reason is that(it's hard to look at in symbol):

targetS.label = 'J'

let reduceList = dataSet.flat();
// get all node which not marked as blue
reduceList = reduceList.filter(node => !markList.includes(node))

function drawRay(x1, y1, x2, y2) {
    setTimeout(() => {
        ctx.strokeStyle = 'pink'
        ctx.lineWidth = 8;
        ctx.beginPath();

    ctx.moveTo(x1 * fontSize, y1 * fontSize + (fontSize / 2));
    ctx.lineTo(x2 * fontSize, y2 * fontSize + (fontSize / 2));
        ctx.stroke();

    }, 100 * x1)
}

resultList  = [];
reduceList.forEach((node) => {

    let tmp = dataSet[node.y]
    let lastBluePoint = tmp.findLastIndex((node) => node.color == 'blue')
    if(lastBluePoint >= 0)
    {
        drawRay(node.x, node.y, lastBluePoint, node.y)
        drawRay(node.x, 0, node.x, node.y)
        tmp = tmp.slice(node.x + 1, lastBluePoint + 1)

        tmp = tmp
            .filter(node => node.color == 'blue')
            .filter((node) => node.label != '-')
            .filter((node) => node.label != '.')
            .reduce((acc, node)  => acc  + `${node.label}`
                    ,"")
        if(tmp && tmp.length > 0){
            let match = tmp.match(/(FJ)|(L7)|(\|)/g)
            //console.log(tmp)
            //console.log(match)
            if(match && match.length % 2 != 0) {
                resultList.push(node)
            }
        }
    }
})

resultList.map(node => {
    node.color = 'green'
})

//loop()
console.log("Reuslt: " + resultList);

3. Demo

Date: 2023-12-10 Sun 00:00

Author: Terry Fung

Created: 2024-11-10 Sun 14:09

Emacs 29.4 (Org mode 9.6.15)

Validate