Public
Edited
Apr 2, 2023
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
day8_part2 = {
const arr = [];

branchMatrix.map((row, rowIndex) =>
row.map((num, colIndex) => {
// check the right direction
const right = row.slice(colIndex + 1).findIndex((el) => el >= num);

// check the down direction
const downCol = [];
branchMatrix
.slice(rowIndex + 1)
.map((row) => downCol.push(row[colIndex]));
const down = downCol.findIndex((el) => el >= num);

// check the left direction
const left = row
.slice(0, colIndex)
.reverse()
.findIndex((el) => el >= num);

// check the up direction
let upCol = [];
branchMatrix
.slice(0, rowIndex)
.reverse()
.map((row) => upCol.push(row[colIndex]));
const up = upCol.findIndex((el) => el >= num);

arr.push({
x: colIndex,
y: rowIndex,
val: num,
l: left == -1 ? row.slice(0, colIndex).reverse().length : left + 1,
r: right == -1 ? row.slice(colIndex + 1).length : right + 1,
u: up == -1 ? upCol.length : up + 1,
d: down == -1 ? downCol.length : down + 1
});
})
);
arr.map((el) => (el.score = el.l * el.r * el.u * el.d));
return Math.max(...arr.map((el) => el.score));
// return arr;
}
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
day10_part1 = {
let instructions = [];
let x = 1;
let signalStrengths = [];
let currentIndex = 1;

for (let i = 0; i < cycles.length; i++) {
const instruction = cycles[i];

if (instruction !== "noop") {
const [opcode, operand] = instruction.split(" ");
currentIndex++;
instructions.push({ idx: currentIndex, addV: parseInt(operand), i: i });
} else {
instructions.push({ idx: currentIndex, addV: 0, i: i });
}
currentIndex++;
}

for (let i = 0; i < Math.max(...instructions.map((el) => el.idx)); i++) {
const inst = instructions.find((el) => el.idx === i);
if (inst !== undefined) x += inst.addV;
signalStrengths.push(x);
}

const sumSignalStrengths = [20, 60, 100, 140, 180, 220]
.map((i) => i * signalStrengths[i - 1])
.reduce((acc, val) => acc + val, 0);
return signalStrengths;
}
Insert cell
day10_part2 = {
let matrix = new Array(6).fill(0);
matrix = matrix.map((cell) => (cell = new Array(40).fill(".")));

let x = [0, 1, 2];
const instructions = [];
let currentIndex = 1;
let signalStrengths = [];

for (let i = 0; i < cycles.length; i++) {
const instruction = cycles[i];

if (instruction !== "noop") {
const [opcode, operand] = instruction.split(" ");
currentIndex++;
instructions.push({ idx: currentIndex, addV: parseInt(operand), i: i });
} else {
instructions.push({ idx: currentIndex, addV: 0, i: i });
}
currentIndex++;
}

for (let i = 0; i < Math.max(...instructions.map((el) => el.idx)); i++) {
const inst = instructions.find((el) => el.idx === i);
if (inst !== undefined) {
x = [...x];
x[0] += inst.addV;
x[1] = x[0] + 1;
x[2] = x[1] + 1;
}
signalStrengths.push(x);
}

for (let i = 0; i < signalStrengths.length; i++) {
const rowIndex = Math.floor(i / 40);
if (signalStrengths[i].includes(i - rowIndex * 40)) {
matrix[rowIndex][i - rowIndex * 40] = "#";
}
}

return matrix.map((row) => row.join());
}
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
day11_part1 = {
const copyMonkeys = JSON.parse(JSON.stringify(monkeys));

for (let round = 0; round < 20; round++) {
for (let i = 0; i < copyMonkeys.length; i++) {
const monkey = copyMonkeys[i];
while (monkey.items.length > 0) {
let item = monkey.items.shift();

monkey.inspectionCount++;

// Calculate worry level
switch (monkey.operation) {
case "+":
item = item + monkey.opValue;
break;
case "*":
item = item * monkey.opValue;
break;
case "**":
item = item ** monkey.opValue;
break;
default:
console.log("Invalid operation");
break;
}

// Divide worrry level by 3
item = Math.floor(item / 3);

// Divide worry level by the value belongs to the monkey and throw the item
item % monkey.divisor === 0
? copyMonkeys[monkey.true].items.push(item)
: copyMonkeys[monkey.false].items.push(item);
}
}
}
const sortedMonkeys = copyMonkeys.sort(
(a, b) => b.inspectionCount - a.inspectionCount
);
const monkeyBusiness =
sortedMonkeys[0].inspectionCount * sortedMonkeys[1].inspectionCount;
return monkeyBusiness;
}
Insert cell
day11_part2 = {
const copyMonkeys = JSON.parse(JSON.stringify(monkeys));
const divisor = copyMonkeys
.map((monkey) => monkey.divisor)
.reduce((a, b) => a * b, 1);

for (let round = 0; round < 10000; round++) {
for (let i = 0; i < copyMonkeys.length; i++) {
const monkey = copyMonkeys[i];
while (monkey.items.length > 0) {
let item = monkey.items.shift();

monkey.inspectionCount++;

// Calculate worry level
switch (monkey.operation) {
case "+":
item += monkey.opValue;
break;
case "*":
item *= monkey.opValue;
break;
case "**":
item = item ** monkey.opValue;
break;
default:
console.log("Invalid operation");
break;
}

item = item % divisor;

// Divide worry level by the value belongs to the monkey and throw the item
item % monkey.divisor === 0
? copyMonkeys[monkey.true].items.push(item)
: copyMonkeys[monkey.false].items.push(item);
}
}
}
const sortedMonkeys = copyMonkeys.sort(
(a, b) => b.inspectionCount - a.inspectionCount
);
const monkeyBusiness =
sortedMonkeys[0].inspectionCount * sortedMonkeys[1].inspectionCount;
return monkeyBusiness;
}
Insert cell
Insert cell
Insert cell
Insert cell
map = {
const grid = day12_input.split("\n").map((s) => s.split(""));
const rows = grid.length;
const cols = grid[0].length;
let start, end;
// Find the start (S) and end (E) positions
for (let row = 0; row < rows; row++) {
for (let col = 0; col < cols; col++) {
if (grid[row][col] === "S") start = [row, col];
if (grid[row][col] === "E") end = [row, col];
}
}

grid[start[0]][start[1]] = "a";
grid[end[0]][end[1]] = "z";

return { grid: grid, start: start, end: end };
}
Insert cell
day12_part1 = {
const rows = map.grid.length;
const cols = map.grid[0].length;
const start = map.start;
const end = map.end;

// Helper function to check if a position is valid and accessible
function isValid(row, col, elevation) {
if (row >= 0 && row < rows && col >= 0 && col < cols) {
const diff = map.grid[row][col].charCodeAt(0) - elevation;
return diff <= 1;
}
return false;
}

const queue = [[...start, 0]];
const visited = new Set([start.join(",")]);

while (queue.length > 0) {
const [row, col, steps] = queue.shift();

const elevation = map.grid[row][col].charCodeAt(0);

if (row === end[0] && col === end[1]) {
return steps;
}

const moves = [
[row - 1, col],
[row + 1, col],
[row, col - 1],
[row, col + 1]
];

for (const [nextRow, nextCol] of moves) {
const key = [nextRow, nextCol].join(",");

if (isValid(nextRow, nextCol, elevation) && !visited.has(key)) {
visited.add(key);
queue.push([nextRow, nextCol, steps + 1]);
}
}
}

return -1;
}
Insert cell
startOptions = {
const arr = [];

for (let i = 0; i < map.grid.length; i++) {
for (let j = 0; j < map.grid[0].length; j++) {
if (map.grid[i][j] === "a") arr.push([i, j]);
}
}

return arr;
}
Insert cell
day12_part2 = {
const rows = map.grid.length;
const cols = map.grid[0].length;

const end = map.end;

const results = [];

// Helper function to check if a position is valid and accessible
function isValid(row, col, elevation) {
if (row >= 0 && row < rows && col >= 0 && col < cols) {
const diff = map.grid[row][col].charCodeAt(0) - elevation;
return diff <= 1;
}
return false;
}

startOptions.map((start) => {
const queue = [[...start, 0]];
const visited = new Set([start.join(",")]);
while (queue.length > 0) {
const [row, col, steps] = queue.shift();

const elevation = map.grid[row][col].charCodeAt(0);

if (row === end[0] && col === end[1]) {
results.push(steps);
}

const moves = [
[row - 1, col],
[row + 1, col],
[row, col - 1],
[row, col + 1]
];

for (const [nextRow, nextCol] of moves) {
const key = [nextRow, nextCol].join(",");

if (isValid(nextRow, nextCol, elevation) && !visited.has(key)) {
visited.add(key);
queue.push([nextRow, nextCol, steps + 1]);
}
}
}
});

return Math.min(...results);
}
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
day13_part1 = {
function compareValues(left, right) {
if (typeof left === "number" && typeof right === "number") {
if (left === right) {
return undefined;
}
return left < right;
} else if (typeof left === "number") {
return compareValues([left], right);
} else if (typeof right === "number") {
return compareValues(left, [right]);
} else {
for (let i = 0; i < Math.min(left.length, right.length); i++) {
const comparisonResult = compareValues(left[i], right[i]);
if (comparisonResult !== undefined) {
return comparisonResult;
}
}
if (left.length === right.length) {
return undefined;
}
return left.length < right.length;
}
}

function findOrderedPairs(input) {
let sum = 0;
for (let i = 0; i < input.length; i++) {
if (compareValues(input[i][0], input[i][1])) {
console.log(i + 1);
sum += i + 1;
}
}
return sum;
}

return findOrderedPairs(signals);
}
Insert cell
singleLineSignals = {
let arr = day13_input.split("\n");
arr = arr.filter((el) => el.trim() !== "").map((el) => JSON.parse(el));
return arr;
}
Insert cell
day13_part2 = {
function compareValues(left, right) {
if (typeof left === "number" && typeof right === "number") {
if (left === right) {
return undefined;
}
return left < right;
} else if (typeof left === "number") {
return compareValues([left], right);
} else if (typeof right === "number") {
return compareValues(left, [right]);
} else {
for (let i = 0; i < Math.min(left.length, right.length); i++) {
const comparisonResult = compareValues(left[i], right[i]);
if (comparisonResult !== undefined) {
return comparisonResult;
}
}
if (left.length === right.length) {
return undefined;
}
return left.length < right.length;
}
}

function organizePackets(input) {
if (!input.includes([[2]])) input.push([[2]]);
if (!input.includes([[6]])) input.push([[6]]);

input.sort((a, b) => {
const comparisonResult = compareValues(a, b);
return comparisonResult === undefined ? 0 : comparisonResult ? -1 : 1;
});

let index1 = input.findIndex(
(packet) => compareValues(packet, [[2]]) === undefined
);
let index2 = input.findIndex(
(packet) => compareValues(packet, [[6]]) === undefined
);

return (index1 + 1) * (index2 + 1);
}

return organizePackets(singleLineSignals);
}
Insert cell
Insert cell
Insert cell
Insert cell
grid = {
const lines = day14_example.split("\n");
const coords = lines.flatMap((line) =>
line.split(" -> ").map((coord) => coord.split(",").map(Number))
);
// Find the minimum and maximum x and y values
let [minX, maxX] = d3.extent(coords, (coord) => coord[0]);
const [minY, maxY] = [0, d3.max(coords, (coord) => coord[1])];

// minX -= maxY;
// maxX += maxY;
const height = maxY - minY + 1;
const width = maxX - minX + 1;

const grid = Array.from({ length: height }, () =>
Array.from({ length: width }, () => ".")
);

for (const line of lines) {
const coordinates = line
.split(" -> ")
.map((coord) => coord.split(",").map(Number));
for (let i = 1; i < coordinates.length; i++) {
const [startX, startY] = coordinates[i - 1];
const [endX, endY] = coordinates[i];

if (startX === endX) {
const minYCoord = Math.min(startY, endY);
const maxYCoord = Math.max(startY, endY);
for (let y = minYCoord; y <= maxYCoord; y++) {
grid[y - minY][startX - minX] = "#";
}
} else {
const minXCoord = Math.min(startX, endX);
const maxXCoord = Math.max(startX, endX);
for (let x = minXCoord; x <= maxXCoord; x++) {
grid[startY - minY][x - minX] = "#";
}
}
}
}

// grid.push(new Array(grid[0].length).fill("."));
// grid.push(new Array(grid[0].length).fill("#"));

return {
grid,
offsetX: minX,
offsetY: minY
};
}
Insert cell
visualizeGrid(grid.grid)
Insert cell
function visualizeGrid(grid) {
const height = grid.length;
const width = grid[0].length;

// Create an SVG element
const svg = d3
.create("svg")
.attr("width", width * cellSize)
.attr("height", height * cellSize);

// Create a scale for x and y axis
const xScale = d3
.scaleBand()
.domain(d3.range(width))
.range([0, width * cellSize]);
const yScale = d3
.scaleBand()
.domain(d3.range(height))
.range([0, height * cellSize]);

// Create the grid cells
svg
.selectAll("g")
.data(grid)
.join("g")
.attr("transform", (d, i) => `translate(0, ${yScale(i)})`)
.selectAll("rect")
.data((d) => d)
.join("rect")
.attr("x", (d, i) => xScale(i))
.attr("y", 0)
.attr("width", xScale.bandwidth())
.attr("height", yScale.bandwidth())
.attr("fill", (d) => (d === "#" ? "black" : d === "o" ? "blue" : "white"))
.attr("stroke", "gray");

return svg.node();
}
Insert cell
Insert cell
function countRestingSand(grid) {
const gridCopy = JSON.parse(JSON.stringify(grid.grid));
const sandSource = { x: 500 - grid.offsetX, y: 0 };

let restingSand = 0;
let keepSimulating = true;

while (true) {
let x = sandSource.x;
let y = sandSource.y;
while (true) {
const below = gridCopy[y + 1] && gridCopy[y + 1][x];
const belowLeft = gridCopy[y + 1] && gridCopy[y + 1][x - 1];
const belowRight = gridCopy[y + 1] && gridCopy[y + 1][x + 1];
console.log(below, belowLeft, belowRight);

if (below === ".") {
y++;
} else if (belowLeft === ".") {
x--;
y++;
} else if (belowRight === ".") {
x++;
y++;
} else if (
below == undefined ||
belowLeft == undefined ||
belowRight == undefined
) {
return { grid: gridCopy, restingSand: restingSand };
} else {
gridCopy[y][x] = "o";
restingSand++;
break;
}
}
}
}
Insert cell
day14_part1 = countRestingSand(grid)
Insert cell
wideGrid = {
const lines = day14_input.split("\n");
const coords = lines.flatMap((line) =>
line.split(" -> ").map((coord) => coord.split(",").map(Number))
);
// Find the minimum and maximum x and y values
let [minX, maxX] = d3.extent(coords, (coord) => coord[0]);
const [minY, maxY] = [0, d3.max(coords, (coord) => coord[1])];

minX -= maxY;
maxX += maxY;
const height = maxY - minY + 1;
const width = maxX - minX + 1;

const grid = Array.from({ length: height }, () =>
Array.from({ length: width }, () => ".")
);

for (const line of lines) {
const coordinates = line
.split(" -> ")
.map((coord) => coord.split(",").map(Number));
for (let i = 1; i < coordinates.length; i++) {
const [startX, startY] = coordinates[i - 1];
const [endX, endY] = coordinates[i];

if (startX === endX) {
const minYCoord = Math.min(startY, endY);
const maxYCoord = Math.max(startY, endY);
for (let y = minYCoord; y <= maxYCoord; y++) {
grid[y - minY][startX - minX] = "#";
}
} else {
const minXCoord = Math.min(startX, endX);
const maxXCoord = Math.max(startX, endX);
for (let x = minXCoord; x <= maxXCoord; x++) {
grid[startY - minY][x - minX] = "#";
}
}
}
}

grid.push(new Array(grid[0].length).fill("."));
grid.push(new Array(grid[0].length).fill("#"));

return {
grid,
offsetX: minX,
offsetY: minY
};
}
Insert cell
visualizeGrid(wideGrid.grid)
Insert cell
function newCountRestingSand(grid) {
const gridCopy = JSON.parse(JSON.stringify(grid.grid));
const sandSource = { x: 500 - grid.offsetX, y: 0 };

let restingSand = 0;

while (true) {
let x = sandSource.x;
let y = sandSource.y;
while (true) {
const below = gridCopy[y + 1] && gridCopy[y + 1][x];
const belowLeft = gridCopy[y + 1] && gridCopy[y + 1][x - 1];
const belowRight = gridCopy[y + 1] && gridCopy[y + 1][x + 1];

if (below === ".") {
y++;
} else if (belowLeft === ".") {
x--;
y++;
} else if (belowRight === ".") {
x++;
y++;
} else if (
y === sandSource.y &&
(below !== "." || belowLeft !== "." || belowRight !== ".")
) {
gridCopy[y][x] = "o";
restingSand++;
return { grid: gridCopy, restingSand: restingSand };
} else {
gridCopy[y][x] = "o";
restingSand++;
break;
}
}
}
}
Insert cell
day14_part2 = newCountRestingSand(wideGrid)
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