Advent of Code 2022 - Day 4: Camp Cleanup Solution

Dealing with start, end

Part 1: Wholly Include

Transform the data into the format of

1[
2 [rangeA, rangeB],
3 ...
4]

with each range of format

1[start, end]

Now, let the inclusion logic speak for itself

Implementation

1const fs = require("fs")
2
3const data = fs
4 .readFileSync("./input", "utf-8")
5 .split(/\r?\n/)
6 .filter(Boolean)
7 .map(s => s.split(",").map(s => s.split("-").map(Number)))
8
9const isInclude = (rangeA, rangeB) =>
10 (rangeA[0] <= rangeB[0] && rangeA[1] >= rangeB[1]) ||
11 (rangeB[0] <= rangeA[0] && rangeB[1] >= rangeA[1])
12
13const res = data.filter(([rangeA, rangeB]) => isInclude(rangeA, rangeB)).length
14
15console.log(res)

Part 2: Partially Include

Same as Part 1, but with different inclusion checking logic

Implementation

1const fs = require("fs")
2
3const data = fs
4 .readFileSync("./input", "utf-8")
5 .split(/\r?\n/)
6 .filter(Boolean)
7 .map(s => s.split(",").map(s => s.split("-").map(Number)))
8
9const isInclude = (rangeA, rangeB) =>
10 (rangeA[0] <= rangeB[0] && rangeA[1] >= rangeB[0]) ||
11 (rangeB[0] <= rangeA[0] && rangeB[1] >= rangeA[0])
12
13const res = data.filter(([rangeA, rangeB]) => isInclude(rangeA, rangeB)).length
14
15console.log(res)

References

Original problem

Comments

Loading comments...

Tags

adventofcode

Next Post

Advent of Code 2022 - Day 5: Supply Stacks

Transform (the hard part) and mutate

Previous Post

HoningJS

Search Posts