Published
Edited
Dec 13, 2021
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
day1input = {
const text = await FileAttachment("day 1.txt").text();
return (
text
// get each line
.split("\n")
// trim trailing newline, which would otherwise convert to "0"
.filter(e => !!e)
// coerce numeric
.map(e => +e)
);
}
Insert cell
// Part 1: given a text list of numbers, find the two entries whose sum is 2020
Insert cell
day1input
// grab entries
.filter((e, i, a) => a.includes(2020 - e))
// multiply
.reduce((a, e) => a * e)
Insert cell
////////////////////
// Part 2: given that same list of items, find the three entries whose sum is 2020
Insert cell
{
const numbers = day1input;
const collection = [];

// easy way to implement two cursors
for (let i of numbers) {
for (let j of numbers) {
if (numbers.includes(2020 - i - j)) {
const v = [i, j, 2020 - i - j].sort();
collection.push({ v, total: v.reduce((a, e) => a * e) });
}
}
}
return JSON.stringify(collection[0]);
}
Insert cell
Insert cell
Insert cell
// Part 1: given a list of passwords, how many have the character the number of instances?
Insert cell
day2input
.filter(([min, max, char, , str]) => {
const pattern = new RegExp(`[^${char}]`, "g");
const count = str.replaceAll(pattern, "").length;
return min <= count && count <= max;
}).length
Insert cell
////////////////////
// Part 2: given that same list of items, find the items which have the character in one of the two locations
Insert cell
day2input.filter(([first, second, char, , str]) => {
const [a, b] = [str[+first - 1], str[+second - 1]];
return (a === char || b === char) && a !== b;
}).length
Insert cell
Insert cell
Insert cell
// part 1 - how many times do you hit a hash sign if you start at the top left and move right 3, down 1 (over and over)
Insert cell
function* slope(dx, dy) {
let x = 0,
y = 0;

while (y < day3input.length) {
yield day3input[y][x] === "#";
x = (x + dx) % day3input[0].length;
y += dy;
}
}
Insert cell
[...slope(3, 1)]
Insert cell
[...slope(3, 1)].filter(yn => yn === true).length
Insert cell
// part 2
Insert cell
Insert cell
{
const a = [...slope(1, 1)].filter(yn => yn === true).length;
const b = [...slope(3, 1)].filter(yn => yn === true).length;
const c = [...slope(5, 1)].filter(yn => yn === true).length;
const d = [...slope(7, 1)].filter(yn => yn === true).length;
const e = [...slope(1, 2)].filter(yn => yn === true).length;
return a*b*c*d*e
}
Insert cell
Insert cell
Insert cell
day4asObjects = (await day4input.text())
.split(
`

`
)
.map(record =>
Object.fromEntries(
record
.replaceAll("\n", " ")
.split(/ /)
.map(i => i.split(":"))
)
)
Insert cell
// Part 1: given an input where records are separated by blank lines, how many have the required fields
Insert cell
Insert cell
Insert cell
// Part 2: validate specifics of the field value
Insert cell
Insert cell
Insert cell
Insert cell
day5inputFile = FileAttachment("day 5 input.txt")
Insert cell
Insert cell
Insert cell
// Part 1
Insert cell
Insert cell
// get the maximum ID for a boarding pass on the plane
Math.max(...day5input.map(pass => day5BoardingPass(pass).id))
Insert cell
// Part 2
Insert cell
Insert cell
Insert cell
md`## Day 6`
Insert cell
Insert cell
day6input = {
return splitOnBlankLines(
(await FileAttachment("day 6 input.txt").text()).trim()
);
}
Insert cell
// Part 1
Insert cell
// determine how many questions each group answered "yes" to and sum them all
day6input
.map(e =>
e
// remove newlines
.replaceAll("\n", "")
// convert into an array
.split("")
// dedupe - removes items which aren't the first index of the element
.filter((e, i, arr) => arr.indexOf(e) === i)
)
// get length of each item (eg. how many unique answers)
.map(arr => arr.length)
// sum
.reduce((acc, el) => acc + el, 0)
Insert cell
// Part 2 - For each group, count the number of questions to which everyone answered "yes". What is the sum of those counts?
Insert cell
day6input
.map(e =>
e
// replace newlines with empty char
.replaceAll("\n", " ")
// split on empty char to turn into array of persons
.split(" ")
// find the entries which exist in every element of the array
.reduce((acc, el, i, arr) => {
if (typeof acc === "string") {
// for the first iteration, the acc will be a string
acc = acc.split("");
}

// intersect the accumulator and current element
return el.split("").filter(item => acc.includes(item));
})
)
.map(arr => arr.length)
.reduce((a, e) => a + e, 0)
Insert cell
md`## Day 7`
Insert cell
Insert cell
day7rules = Object.fromEntries(
day7input.map(e => {
const [key, values] = e.split("contain");

return [
key.replace(" bags ", ""),
Object.fromEntries(
values
.replaceAll(/ bags?\.?/g, "")
.split(",")
.map(e => {
const [, count, id] = e.trim().split(/(\d) /);
return [id, +count];
})
)
];
})
)
Insert cell
Insert cell
function day7FindBagsContaining(bagTypes) {
let allContainers = [];

while (bagTypes.length > 0) {
bagTypes = Object.entries(day7rules)
// omit items we've checked already
// .filter(([parent, children]) => !allContainers.includes(parent))
// filter to the next level of parents
.filter(el => {
const [parent, children] = el;
return Object.keys(children).some(child => bagTypes.includes(child));
})
.map(e => e[0]);

allContainers = allContainers.concat(bagTypes);
}

return allContainers;
}
Insert cell
// Part 1 - How many bag colors can eventually contain at least one shiny gold bag? (The list of rules is quite long; make sure you get all of it.)
Insert cell
day7FindBagsContaining(["shiny gold"])
Insert cell
// Part 2
Insert cell
function day7countBagsInside(bagTypes) {
let count = 0;

while (bagTypes.length > 0) {
// get the item at the front of the bagtype list
const type = bagTypes.shift();
if (type !== "undefined") {
// add the number of bags to the total
count += Object.values(day7rules[type]).reduce((acc, el) => {
// TODO: figure out how to count things
return acc + (el ? el : 0);
}, 0);

// add the children bags onto the queue
bagTypes.unshift(
...Object.keys(day7rules[type]).filter(type => type !== "undefined")
);
}
}
return count;
}
Insert cell
day7countBagsInside(["shiny gold"])
Insert cell
Insert cell
// TEMPLATE:md`## Day 5`md`<details><summary>Prompt</summary><pre></pre></details>`// Part 1// Part 2
Insert cell
md`## utils`
Insert cell
function splitOnBlankLines(string) {
return string.split(
`

`
);
}
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more