Public
Edited
Dec 15, 2021
1 star
Insert cell
# Advent of Code 2021
Insert cell
input = FileAttachment("input.txt").text()
Insert cell
input.split("\n").reduce((acc,val,index,arr) => parseInt(val) > parseInt(arr[index -1]) ? ++acc : acc, 0)
Insert cell
input
.split("\n")
.map((d) => parseInt(d))
.map((d, i, arr) => [d, arr[i + 1], arr[i + 2]])
.map((d) => d.reduce((acc, val) => parseInt(acc) + parseInt(val), 0))
//.slice(0, 666)
.reduce((acc, val, index, arr) => (val > arr[index - 1] ? ++acc : acc), 0)
Insert cell
Insert cell
subDirections = FileAttachment("input 2.txt").text()
Insert cell
sub = subDirections
.split("\n")
.map((d) => ({ dir: d[0], val: parseInt(d[d.length - 1]) }))
.map((d) => (d.dir == "u" ? { dir: "u", val: -d.val } : d))
.slice(0, 1000)
.reduce(
(acc, val) => {
if (val.dir == "f") {
acc.x += val.val;
} else {
acc.y += val.val;
}
return acc;
},
{ x: 0, y: 0 }
)
Insert cell
sub.x * sub.y
Insert cell
sub2 = subDirections
.split("\n")
.map((d) => ({ dir: d[0], val: parseInt(d[d.length - 1]) }))

.slice(0, 1000)
.reduce(
(acc, val) => {
if (val.dir == "u") {
acc.aim -= val.val;
} else if (val.dir == "d") {
acc.aim += val.val;
} else {
acc.pos += val.val;
acc.depth += acc.aim * val.val;
}
return acc;
},
{ pos: 0, depth: 0, aim: 0 }
)

Insert cell
sub2.pos * sub2.depth
Insert cell
input3 = FileAttachment("input-3.txt").text()
Insert cell
integerArrays = input3
.split("\n")
.map((d) => d.split("").map((e) => parseInt(e)))
Insert cell
2520 * 1575
Insert cell
parseInt(
d3
.range(integerArrays[0].length)
.map((index) => integerArrays.map((arr) => arr[index]))
.map((d) => d.reduce((acc, val) => (acc += val), 0))
.map((d) => (d > integerArrays.length / 2 ? 1 : 0))
.join(""),
2
)
Insert cell
parseInt(
d3
.range(integerArrays[0].length)
.map((index) => integerArrays.map((arr) => arr[index]))
.map((d) => d.reduce((acc, val) => (acc += val), 0))
.map((d) => (d > integerArrays.length / 2 ? 1 : 0))
.map((d) => parseInt(+!d))
.join(""),
2
)
Insert cell
mask = d3
.range(integerArrays[0].length)
.map((index) => integerArrays.map((arr) => arr[index]))
.map((d) => d.reduce((acc, val) => (acc += val), 0))
.map((d) => (d >= integerArrays.length / 2 ? 1 : 0))
// .join("")
Insert cell
invertMask = mask.map((d) => +!d)
Insert cell
mc = d3
.range(9)
.reduce(
(acc, val) => acc.filter((arr) => mask[val] == arr[val]),
integerArrays
)
Insert cell
lc = d3
.range(9)
.reduce(
(acc, val) => acc.filter((arr) => invertMask[val] == arr[val]),
integerArrays
)
Insert cell
parseInt(lc[0].join(""), 2) * parseInt(mc[0].join(""), 2)
Insert cell
{
const p2 = (input) => rating(input, 0, 1) * rating(input, 0, 0);

const rating = (input, i, b) => {
let temp = 0;
input.map((inp) => inp[i] == 1 && temp++);
temp = bit(temp, input.length, b);
let arr = input.filter((inp) => inp[i] == temp);
return arr.length == 1 ? "0b" + arr : rating(arr, i + 1, b);
};

const bit = (temp, len, bit) => (temp >= len - temp ? bit : (bit ^= 1));

return p2(input3.split("\n"));
}
Insert cell
input4 = FileAttachment("input-4@1.txt").text()
Insert cell
bingoCalls = input4
.split("\n")
.slice(0, 1)[0]
.split(",")
.map((d) => parseInt(d))
Insert cell
bingoBoards = input4
.split("\n\n")
.slice(1)
.map((d) =>
d.split("\n").map((e) =>
e
.split(" ")
.filter((f) => f)
.map((g) => ({
called: false,
roundCalled: null,
value: parseInt(g)
}))
)
)
Insert cell
{
let win = false;

let boards = JSON.parse(JSON.stringify(bingoBoards));

for (let i = 0; i < bingoCalls.length; i++) {
let call = bingoCalls[i];
boards.forEach((board) =>
board.forEach((row) =>
row.forEach((cell) => {
if (cell.value == call) {
(cell.roundCalled = i), (cell.called = true);
}
})
)
);
}

const winningRows = boards.map((board) =>
d3.min(board.map((row) => d3.max(row, (d) => d.roundCalled)))
);

const winningRoundRows = d3.min(winningRows);

const winningBoardRows = winningRows.findIndex((d) => d == winningRoundRows);

let transposedBoards = JSON.parse(JSON.stringify(bingoBoards)).map((d) =>
d[0].map((_, colIndex) => d.map((row) => row[colIndex]))
);

for (let i = 0; i < bingoCalls.length; i++) {
let call = bingoCalls[i];
transposedBoards.forEach((board) =>
board.forEach((row) =>
row.forEach((cell) => {
if (cell.value == call) {
(cell.roundCalled = i), (cell.called = true);
}
})
)
);
}

const winningColumns = transposedBoards.map((board) =>
d3.min(board.map((row) => d3.max(row, (d) => d.roundCalled)))
);

const winningRoundColumns = d3.min(winningColumns);

const winningBoardColumns = winningColumns.findIndex(
(d) => d == winningRoundColumns
);

const wins = {
columns: { round: winningRoundColumns, board: winningBoardColumns },
rows: { round: winningRoundRows, board: winningBoardRows }
};
//return wins;
let winBoards = JSON.parse(JSON.stringify(bingoBoards));

for (let i = 0; i < d3.min([wins.columns.round, wins.rows.round]) + 1; i++) {
let call = bingoCalls[i];

winBoards.forEach((board) =>
board.forEach((row) =>
row.forEach((cell) => {
if (cell.value == call) {
(cell.roundCalled = i), (cell.called = true);
}
})
)
);
}

return (
winBoards[wins.rows.board]
.flat(Infinity)
.filter((d) => d.roundCalled == null)
.reduce((acc, val) => acc + val.value, 0) * bingoCalls[wins.rows.round]
);
}
Insert cell
{
let boards = JSON.parse(JSON.stringify(bingoBoards));

for (let i = 0; i < bingoCalls.length; i++) {
let call = bingoCalls[i];
boards.forEach((board) =>
board.forEach((row) =>
row.forEach((cell) => {
if (cell.value == call) {
(cell.roundCalled = i), (cell.called = true);
}
})
)
);
}

const winningRows = boards.map((board) =>
d3.min(board.map((row) => d3.max(row, (d) => d.roundCalled)))
);

const winningRoundRows = d3.max(winningRows);

const winningBoardRows = winningRows.findIndex((d) => d == winningRoundRows);

let transposedBoards = JSON.parse(JSON.stringify(bingoBoards)).map((d) =>
d[0].map((_, colIndex) => d.map((row) => row[colIndex]))
);

for (let i = 0; i < bingoCalls.length; i++) {
let call = bingoCalls[i];
transposedBoards.forEach((board) =>
board.forEach((row) =>
row.forEach((cell) => {
if (cell.value == call) {
(cell.roundCalled = i), (cell.called = true);
}
})
)
);
}

const winningColumns = transposedBoards.map((board) =>
d3.min(board.map((row) => d3.max(row, (d) => d.roundCalled)))
);

const winningRoundColumns = d3.max(winningColumns);

const winningBoardColumns = winningColumns.findIndex(
(d) => d == winningRoundColumns
);

const wins = {
columns: { round: winningRoundColumns, board: winningBoardColumns },
rows: { round: winningRoundRows, board: winningBoardRows }
};

let winBoards = JSON.parse(JSON.stringify(bingoBoards));

for (let i = 0; i < wins.rows.round + 1; i++) {
let call = bingoCalls[i];

winBoards.forEach((board) =>
board.forEach((row) =>
row.forEach((cell) => {
if (cell.value == call) {
(cell.roundCalled = i), (cell.called = true);
}
})
)
);
}

return (
winBoards[wins.rows.board]
.flat(Infinity)
.filter((d) => d.roundCalled == null)
.reduce((acc, val) => acc + val.value, 0) *
bingoCalls[wins.rows.round + 1]
);
}
Insert cell
input5 = FileAttachment("input-5.txt").text()
Insert cell
lineCoordinates = input5
.split("\n")
.slice(0, 500)
.map((d) => d.split(" -> ").map((e) => e.split(",").map((f) => parseInt(f))))
.map((d) => ({
startX: d[0][0],
startY: d[0][1],
endX: d[1][0],
endY: d[1][1]
}))
.map((d) => {
let type;
let orthogonal;

if (d.startX == d.endX) {
type = "vertical";
orthogonal = true;
} else if (d.startY == d.endY) {
type = "horizontal";
orthogonal = true;
} else {
type = "diagonal";
orthogonal = false;
}
return { ...d, type, orthogonal };
})
Insert cell
g = d3
.range(1000)
.map((d) => d3.range(1000).map((e) => ({ row: d, column: e, count: 0 })))
Insert cell
{
let grid = JSON.parse(JSON.stringify(g));

lineCoordinates.map((line) => {
if (line.type == "horizontal") {
const xs = d3
.range(line.startX, line.endX, line.startX < line.endX ? 1 : -1)
.concat([line.endX]);

for (let x of xs) {
grid[line.startY][x].count += 1;
}
} else if (line.type == "vertical") {
const ys = d3
.range(line.startY, line.endY, line.startY < line.endY ? 1 : -1)
.concat([line.endY]);

for (let y of ys) {
grid[y][line.startX].count += 1;
}
} else {
const xs = d3
.range(line.startX, line.endX, line.startX < line.endX ? 1 : -1)
.concat([line.endX]);

const ys = d3
.range(line.startY, line.endY, line.startY < line.endY ? 1 : -1)
.concat([line.endY]);

for (let i = 0; i < xs.length; i++) {
grid[ys[i]][xs[i]].count += 1;
}
}
});
return grid.flat().filter((d) => d.count > 1);
}
Insert cell
fishes =
[2,5,2,3,5,3,5,5,4,2,1,5,5,5,5,1,2,5,1,1,1,1,1,5,5,1,5,4,3,3,1,2,4,2,4,5,4,5,5,5,4,4,1,3,5,1,2,2,4,2,1,1,2,1,1,4,2,1,2,1,2,1,3,3,3,5,1,1,1,3,4,4,1,3,1,5,5,1,5,3,1,5,2,2,2,2,1,1,1,1,3,3,3,1,4,3,5,3,5,5,1,4,4,2,5,1,5,5,4,5,5,1,5,4,4,1,3,4,1,2,3,2,5,1,3,1,5,5,2,2,2,1,3,3,1,1,1,4,2,5,1,2,4,4,2,5,1,1,3,5,4,2,1,2,5,4,1,5,5,2,4,3,5,2,4,1,4,3,5,5,3,1,5,1,3,5,1,1,1,4,2,4,4,1,1,1,1,1,3,4,5,2,3,4,5,1,4,1,2,3,4,2,1,4,4,2,1,5,3,4,1,1,2,2,1,5,5,2,5,1,4,4,2,1,3,1,5,5,1,4,2,2,1,1,1,5,1,3,4,1,3,3,5,3,5,5,3,1,4,4,1,1,1,3,3,2,3,1,1,1,5,4,2,5,3,5,4,4,5,2,3,2,5,2,1,1,1,2,1,5,3,5,1,4,1,2,1,5,3,5,2,1,3,1,2,4,5,3,4,3]
Insert cell
{
const timers = d3.range(9).reduce((acc, val) => {
acc[val] = 0;
return acc;
}, {});

const start = fishes.reduce(
(cnt, cur) => ((cnt[cur] = cnt[cur] + 1 || 1), cnt),
{}
);

const histo = Object.assign(timers, start);

for (let i = 0; i < 1000; i++) {
let births = histo[0];

for (let j = 0; j < 9; j++) {
histo[j] = histo[j + 1];
}
histo[8] = births;
histo[6] += births;
}

return Object.values(histo).reduce((acc, val) => acc + val, 0);
}
Insert cell
crabs =

[1101,1,29,67,1102,0,1,65,1008,65,35,66,1005,66,28,1,67,65,20,4,0,1001,65,1,65,1106,0,8,99,35,67,101,99,105,32,110,39,101,115,116,32,112,97,115,32,117,110,101,32,105,110,116,99,111,100,101,32,112,114,111,103,114,97,109,10,82,1266,26,290,428,9,676,880,16,340,1578,839,23,32,721,88,837,118,543,198,836,870,105,44,214,184,52,330,213,1224,1211,481,1707,409,78,1096,995,420,808,50,65,635,1186,228,5,359,290,1241,757,323,11,447,522,8,170,265,632,321,9,1707,1005,1194,466,137,982,905,373,158,601,247,373,202,432,168,694,785,568,144,576,1006,143,1506,298,1790,146,182,535,895,42,296,278,469,118,292,1375,206,235,1545,63,81,49,1405,660,41,1009,226,133,324,1250,113,10,687,223,78,10,745,21,55,1041,149,519,57,589,123,901,416,200,112,35,6,873,353,539,665,75,207,80,787,322,1026,178,19,630,12,263,1136,71,220,143,688,101,88,1600,16,141,55,64,436,19,889,267,470,884,31,546,846,601,15,84,399,83,1054,4,1417,766,525,162,640,73,2,110,189,494,85,44,263,618,583,263,591,1139,21,1593,187,115,520,142,887,3,12,565,78,88,114,803,157,307,1007,1365,1063,1481,431,410,125,19,1123,3,433,73,273,25,438,314,111,369,1188,526,516,509,1,186,143,1335,689,436,1002,260,791,12,36,380,80,306,173,45,24,856,1892,255,11,12,1221,422,8,1214,327,851,85,375,115,325,213,725,720,669,465,577,1,28,331,123,297,267,1586,478,259,572,204,365,461,618,364,5,630,377,26,259,331,956,164,89,115,1328,823,48,625,922,236,577,1113,251,156,846,261,500,73,1607,281,267,64,2,392,115,682,1833,861,1093,1165,52,1643,59,180,787,298,274,304,381,196,511,352,793,1043,984,30,85,190,109,276,303,251,1601,939,726,5,213,915,235,780,43,1212,1466,353,364,507,129,1109,1307,113,109,342,756,898,1015,63,949,127,887,175,91,409,1069,88,600,101,434,1021,477,1073,22,549,145,712,730,160,7,123,27,566,689,172,1496,543,154,345,442,3,860,47,69,319,487,17,1086,1305,329,788,738,688,421,139,1629,499,824,276,13,1033,885,522,140,328,113,311,297,252,33,168,1059,94,469,1816,2,107,149,652,350,200,173,367,100,229,219,400,43,283,1551,752,278,99,648,190,190,337,44,191,462,454,544,261,142,1204,231,924,209,858,768,211,223,186,1452,687,320,343,444,94,1231,285,324,431,36,309,705,672,69,1082,83,269,515,369,117,951,489,117,249,47,350,1408,93,203,800,1151,526,785,721,240,74,605,501,533,512,337,12,720,787,1521,894,112,187,170,1020,339,77,565,691,1141,129,1020,60,505,1383,178,1262,1302,750,743,1108,43,634,135,738,810,628,1807,938,530,61,1384,42,79,276,336,1434,1286,393,145,9,94,945,113,76,88,856,78,1750,499,994,527,1102,266,1164,796,143,726,480,357,577,910,460,448,379,402,1576,1353,257,1044,651,1206,44,126,353,1099,934,892,379,710,988,1041,367,116,377,546,1222,830,259,10,6,385,856,343,793,490,165,367,1022,1065,95,135,426,184,270,227,456,673,90,1363,1127,387,93,138,202,184,1071,134,15,813,134,200,80,144,128,1502,574,868,487,118,42,48,1135,1107,57,418,1093,1508,229,26,154,652,94,1254,171,502,407,276,1098,18,1000,345,150,123,211,1517,1005,590,1413,63,80,510,502,76,476,47,405,186,143,344,286,1277,934,64,512,12,1026,264,68,1420,10,245,10,352,6,585,567,48,428,816,1525,180,346,350,34,100,42,1354,699,265,445,1719,425,8,604,129,111,71,110,1170,703,36,317,198,104,655,95,1046,327,161,853,400,224,797,1221,794,684,321,1279,1,95,1253,671,203,43,220,55,90,1606,359,52,775,76,422,403,305,614,196,244,102,519,122,451,1610,79,709,336,1374,735,478,1123,658,906,615,688,561,518,39,1084,608,54,739,416,1648,1838,1280,1039,35,552,299,142,56,1217,1356,30,12,102,731,1343,224,452,304,1808,546,583,710,33,149,1126,565,314,745,22,115,263,813,113,52,308,944,981,441,544,129,1258,299,885,717,536,253,3,612,29,130,1099,1455,38,501,578,13,347,729,166,772,230,518,488,430,1093,140,16,120,1603,794,174,1361,1657,825,444,176,815,1353,469,264,191,988,12,104,11,1518,1096,347,606,350,18,1376,430,182,1229,131,111,731,174,111,304,715,35,410,701,78,46,390,291,1008,1779,620,2,1378,199,331,334,708,446,1141,773,159,702,716,13,582,161,259,90,180,607,539,611,312,622,151,522,921,150,522,273,421,842,111,21,159,148]

Insert cell
d3.max(crabs)
Insert cell
crabs
.map((d) => Math.abs(d - d3.median(crabs)))
.reduce((acc, val) => acc + val, 0)
Insert cell
d3.min(
d3
.range(d3.max(crabs))
.map((spot) =>
crabs
.map(
(crabPos) =>
(Math.abs(crabPos - spot) * (Math.abs(crabPos - spot) + 1)) / 2
)
.reduce((acc, val) => acc + val, 0)
)
)
Insert cell
hm = FileAttachment("input 3.txt").text()
Insert cell
heightmap = hm
.split("\n")
.map((d) => d.split("").map((e) => parseInt(e)))
.slice(0, 100)
Insert cell
heightmap.map((row, i) =>
row.filter((cell, j) => {
const left =
(heightmap[i - 1] || [])[j] === undefined
? Infinity
: (heightmap[i - 1] || [])[j];
const right =
(heightmap[i + 1] || [])[j] === undefined
? Infinity
: (heightmap[i + 1] || [])[j];
const above =
(heightmap[i] || [])[j - 1] === undefined
? Infinity
: (heightmap[i] || [])[j - 1];
const below =
(heightmap[i] || [])[j + 1] === undefined
? Infinity
: (heightmap[i] || [])[j + 1];

if (cell < left && cell < right && cell < above && cell < below) {
return true;
} else {
return false;
}
})
)
.flat()
.map((d) => d + 1)

.reduce((acc, val) => acc + val, 0)
Insert cell
syntax = FileAttachment("input 5.txt").text()
Insert cell
syntaces = syntax.split("\n").map((d) => d.split(""))
Insert cell
{
const opposite = { "(": ")", "[": "]", "{": "}", "<": ">" };
const opening = ["(", "[", "{", "<"];
const value = { ")": 3, "]": 57, "}": 1197, ">": 25137 };

const foundErrors = [];

syntaces.forEach((line) => {
const stack = [];
for (let i = 0; i < line.length; i++) {
const curr = line[i];
if (opening.includes(curr)) {
stack.push(curr);
} else {
const lastInStack = stack.pop();
if (opposite[lastInStack] != curr) {
foundErrors.push(curr);
break;
}
}
}
});

let totalScore = foundErrors.reduce((total, curr) => total + value[curr], 0);

return totalScore;
}
Insert cell
{
const openingChars = ["(", "[", "{", "<"];
const charPairs = { "(": ")", "[": "]", "{": "}", "<": ">" };
const pointsPerMissingChar = { ")": 1, "]": 2, "}": 3, ">": 4 };
let chunkStack = [];
let points = [];

for (const line of syntaces) {
let chunkDelimiters = line;

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

if (openingChars.includes(char)) {
chunkStack.push(char);
} else {
let lastOpeningChar = chunkStack.pop();
if (charPairs[lastOpeningChar] !== char) {
chunkStack = [];
break;
}
}
}

chunkStack.reverse();
if (chunkStack.length > 0) {
points.push(
chunkStack.reduce(
(acc, char) => acc * 5 + pointsPerMissingChar[charPairs[char]],
0
)
);
}
chunkStack = [];
}

points.sort((a, b) => (a > b ? 1 : -1));
return points[Math.floor(points.length / 2)];
}
Insert cell
octos = [
4341347643,
5477728451,
2322733878,
5453762556,
2718123421,
4237886115,
5631617114,
2217667227,
4236581255,
4482627641
]
.map((d, i) =>
String(d)
.split("")
.map((e, j) => {
const neighbors = [
[i + 1, j],
[i - 1, j],
[i, j + 1],
[i, j - 1],
[i - 1, j - 1],
[i - 1, j + 1],
[i + 1, j - 1],
[i + 1, j + 1]
]
.filter((f) => f[0] >= 0)
.filter((f) => f[0] < 10)
.filter((f) => f[1] >= 0)
.filter((f) => f[1] < 10)
.map((g) => g[0] * 10 + g[1]);

return {
brightness: parseInt(e),
row: i,
col: j,
index: i * 10 + j,
neighbors,
flashed: false
};
})
)
.flat()
Insert cell
octopus = {
let generation = JSON.parse(JSON.stringify(octos));
let flashes = 0;
for (let i = 0; i < 500; i++) {
const newGeneration = generation.map((d) => {
d.brightness++;

if (d.brightness > 9 && d.flashed == false) {
d.brightness = 0;
d.flashed = true;
flashes++;
flashNeighbors(d);
}

return d;
});

generation = newGeneration.map((d) => {
d.brightness = d.flashed ? 0 : d.brightness;
d.flashed = false;

return d;
});

if (generation.filter((d) => d.brightness == 0).length == 100) {
return i;
}
}

function flashNeighbors(d) {
d.neighbors.map((e) => {
generation[e].brightness++;

if (generation[e].brightness > 9 && generation[e].flashed == false) {
generation[e].brightness = 0;
generation[e].flashed = true;
flashes++;
flashNeighbors(generation[e]);
}
});
}
//return flashes;
}
Insert cell
caves = [
"dr-of",
"start-KT",
"yj-sk",
"start-gb",
"of-start",
"IJ-end",
"VT-sk",
"end-sk",
"VT-km",
"KT-end",
"IJ-of",
"dr-IJ",
"yj-IJ",
"KT-yj",
"gb-VT",
"dr-yj",
"VT-of",
"PZ-dr",
"KT-of",
"KT-gb",
"of-gb",
"dr-sk",
"dr-VT"
]
Insert cell
nodes = Array.from(new Set(caves.map((d) => d.split("-")).flat())).map((d) => {
if (d == d.toLowerCase()) {
return { id: d, size: "small" };
} else {
return { id: d, size: "big" };
}
})
Insert cell
edges = caves
.map((d) => d.split("-"))
.concat(caves.map((d) => d.split("-").reverse()))
.map((d) => ({
source: {
id: d[0],
index: nodes.map((e) => e.id).findIndex((e) => e == d[0])
},
target: {
id: d[1],
index: nodes.map((e) => e.id).findIndex((e) => e == d[1])
}
}))

Insert cell
// {
// let routes = [[2]];

// for (let i = 0; i < 20; i++) {
// let newRoutes = [];
// for (let route of routes) {
// const lastPosition = route[route.length - 1];

// if (lastPosition !== 8) {
// const nextSteps = availableMoves(lastPosition, route);

// const updatedRoutes = nextSteps.map((d) => route.concat([d]));
// newRoutes.push(...updatedRoutes);
// }
// }
// routes.push(...newRoutes);
// let uniqueRoutes = routes
// .map((d) => JSON.stringify(d))
// .filter((e, i, arr) => arr.indexOf(e) === i)
// .map((d) => JSON.parse(d));
// routes = uniqueRoutes;
// }
// return routes.filter((d) => d[d.length - 1] == 8);
// }
Insert cell
function availableMoves(pos, steps) {
return edges
.filter((d) => d.source.index == pos)
.map((d) => d.target.index)
.filter((d) => {
if (steps.includes(d) && nodes[d].size == "small") {
return false;
} else {
return true;
}
});
}
Insert cell
// {
// const input = caves.map((d) => d.split("-"));

// const connections = [];

// const addConnection = (from, to) => {
// if (connections[from] == undefined) connections[from] = [to];
// else connections[from].push(to);
// };

// const isUpperCased = (string) => string.toUpperCase() == string;

// const isValidPath = (path) => {
// let howManyDuplicates = 0;
// const sortedPath = path
// .filter((a) => !isUpperCased(a) && a != "start" && a != "end")
// .sort();
// if (sortedPath.length <= 2) return true;
// for (let i = 1; i < sortedPath.length; i++) {
// if (sortedPath[i - 1] == sortedPath[i]) howManyDuplicates++;
// }
// return howManyDuplicates <= 1;
// };

// input.forEach((line) => {
// addConnection(line[0], line[1]);
// addConnection(line[1], line[0]);
// });

// const toExplore = [["start"]];
// const paths = [];

// while (toExplore.length > 0) {
// const currPath = toExplore.pop();
// const currLastPlace = currPath[currPath.length - 1];
// if (currLastPlace == "end") {
// paths.push(currPath);
// continue;
// }
// connections[currLastPlace].forEach((neighbour) => {
// if (neighbour == "start") return;
// const possiblePath = [...currPath, neighbour];
// if (isValidPath(possiblePath)) toExplore.push(possiblePath);
// });
// }
// return paths.length;
// }
Insert cell
segments = FileAttachment("input 6.txt").text()
Insert cell
{
const valid = [2, 4, 3, 7];

const outputs = segments
.split("\n")
.slice(0, 200)
.map((d) => d.split(" | ")[1])
.map((d) => d.split(" ").map((e) => e.length));

return outputs.flat().filter((d) => valid.includes(d)).length;
}
Insert cell
foldCodes = FileAttachment("input-6.txt").text()
Insert cell
dots = foldCodes
.split("\n")
.slice(0, 1004)
.map((d) => d.split(","))
.map((d) => ({ x: parseInt(d[0]), y: parseInt(d[1]) }))
Insert cell
folds = foldCodes
.split("\n")
.slice(1005)
.map((d) => d.split(" ")[2])
.slice(0, -1)
.map((d) => ({ axis: d.split("=")[0], place: parseInt(d.split("=")[1]) }))
Insert cell
dots
.map((d) => ({ ...d, total: d.x + d.y }))
.sort((a, b) => d3.ascending(a.total, b.total))
Insert cell
paperDimensions = [d3.max(dots, (d) => d.x), d3.max(dots, (d) => d.y)]
Insert cell
dottedPaper = {
const emptyArray = new Array(paperDimensions[1] + 1)
.fill(0)
.map((d) => new Array(paperDimensions[0] + 1).fill(0));

for (let dot of dots) {
emptyArray[dot.y][dot.x] = 1;
}

return emptyArray;
}
Insert cell
[1, 2, 3].slice(0, 2).reverse()
Insert cell
folded = {
const paper = JSON.parse(JSON.stringify(dottedPaper));
let foldedPaper = paper;

//for (let fold of folds) {
for (let fold of folds) {
if (fold.axis == "x") {
foldedPaper = foldedPaper.map((row) => {
const unfolded = [...row.slice(0, fold.place)].reverse();
const folded = row.slice(fold.place + 1);

const newArr = [];
for (let i = 0; i < d3.max([unfolded.length, folded.length]); i++) {
const val = Boolean(unfolded[i]) + Boolean(folded[i]);
newArr.push(val > 0 ? 1 : 0);
}
return newArr;
});
} else {
const unfolded = [...foldedPaper.slice(0, fold.place)].reverse();
const folded = foldedPaper.slice(fold.place + 1);

let newPaper = [];

for (let i = 0; i < d3.max([unfolded.length, folded.length]); i++) {
newPaper.push([]);
for (let j = 0; j < unfolded[0].length; j++) {
const val = Boolean(unfolded[i][j]) + Boolean(folded[i][j]);
newPaper[i].push(val > 0 ? 1 : 0);
}
}
foldedPaper = newPaper;
}
}
return foldedPaper;
}
Insert cell
folded
.reverse()
.map((d) => d.join(" "))
.map((d) => d.replaceAll("0", ".").replaceAll("1", "#"))
Insert cell
{
const arr = [1, 1, 1, 1, 0, 0, 1];
const unfolded = JSON.parse(JSON.stringify([...arr.slice(0, 2)].reverse()));
const folded = JSON.parse(JSON.stringify([...arr.slice(3)]));

const newArr = [];
for (let i = 0; i < d3.max([unfolded.length, folded.length]); i++) {
const val = Boolean(unfolded[i]) + Boolean(folded[i]);
newArr.push(val);
}
return newArr;
}
Insert cell
chems = FileAttachment("input 7.txt").text()
Insert cell
seed = chems.split("\n").slice(0, 1)[0]
Insert cell
polymerizations = chems
.split("\n")
.slice(2, 102)
.map((d) => d.split(" -> "))
Insert cell
polym = {
let template = seed;
for (let index = 0; index < 10; index++) {
let nextTemplate = "";
for (let j = 0; j < template.length - 1; j++) {
let source = template.substring(j, j + 2);
let target = polymerizations.find((d) => d[0] == source)[1];
nextTemplate += source[0] + target ?? "";
}
template = nextTemplate + template.slice(-1)[0];
}
return [...template].reduce((a, e) => {
a[e] = a[e] ? a[e] + 1 : 1;
return a;
}, {});
}
Insert cell
{
const histo = Object.entries(polym)
.map((d) => ({ letter: d[0], count: d[1] }))
.sort((a, b) => d3.ascending(a.count, b.count));
//return histo;
return histo.slice(-1)[0].count - histo[0].count;
}
Insert cell
chitons = FileAttachment("input-7.txt").text()
Insert cell
chitonArray = chitons
.split("\n")
.slice(0, 100)
.map((d) => d.split("").map((e) => parseInt(e)))
Insert cell
{
const queue = [{ pos: [0, 0], cost: 0 }];
const {
pos: [x, y],
cost
} = queue.shift();

return x;
}
Insert cell
{
function shortestPath(map, startPos = [0, 0]) {
const ADJ = [
[1, 0],
[0, 1],
[-1, 0],
[0, -1]
];
const queue = [{ pos: startPos, cost: 0 }];
const visited = new Set();

while (queue.length) {
const {
pos: [x, y],
cost
} = queue.shift();

if (y === map.length - 1 && x === map[0].length - 1) return cost;

ADJ.map(([dx, dy]) => [dx + x, dy + y])
.filter(([x, y]) => map[y]?.[x])
.filter((pos) => !visited.has(pos + ""))
.forEach((pos) => {
visited.add(pos + "");
queue.push({ pos, cost: cost + map[pos[1]][pos[0]] });
});
queue.sort((a, b) => a.cost - b.cost);
}
}

const part1 = shortestPath(chitonArray);

const expandedMap = [...Array(chitonArray.length * 5)].map((_, y) =>
[...Array(chitonArray[0].length * 5)].map(
(_, x) =>
1 +
((chitonArray[y % chitonArray.length][x % chitonArray[0].length] -
1 +
Math.trunc(x / chitonArray[0].length) +
Math.trunc(y / chitonArray.length)) %
9)
)
);

const part2 = shortestPath(expandedMap);

return { part1, part2 };
}
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