2024 day 12 part 1 in js
This commit is contained in:
parent
2db8edb087
commit
161b2a7e6f
|
@ -3,6 +3,8 @@
|
|||
inherit (lib.strings) toIntBase10;
|
||||
in input: rec {
|
||||
|
||||
sum = foldl' add 0;
|
||||
|
||||
blinkStone = stone: count:
|
||||
if toIntBase10 stone == 0 then [{ "1" = count; }]
|
||||
else let
|
||||
|
@ -21,19 +23,17 @@ in input: rec {
|
|||
;
|
||||
|
||||
bfast = stones: stones
|
||||
|> (builtins.mapAttrs (stone: blinkStone stone))
|
||||
|> builtins.mapAttrs blinkStone
|
||||
|> attrValues
|
||||
|> concatLists
|
||||
|> addStones
|
||||
|> builtins.zipAttrsWith (stone: sum)
|
||||
;
|
||||
|
||||
bfastt = times: stones:
|
||||
if times == 0 then stones |> attrValues |> foldl' add 0
|
||||
if times == 0 then stones |> attrValues |> sum
|
||||
else bfastt (times - 1) (bfast stones)
|
||||
;
|
||||
|
||||
addStones = builtins.zipAttrsWith (stone: foldl' add 0);
|
||||
|
||||
initialStones = input
|
||||
|> lib.trim
|
||||
|> lib.splitString " "
|
||||
|
|
4
2024/12/example.txt
Normal file
4
2024/12/example.txt
Normal file
|
@ -0,0 +1,4 @@
|
|||
AAAA
|
||||
BBCD
|
||||
BBCC
|
||||
EEEC
|
5
2024/12/example2.txt
Normal file
5
2024/12/example2.txt
Normal file
|
@ -0,0 +1,5 @@
|
|||
OOOOO
|
||||
OXOXO
|
||||
OOOOO
|
||||
OXOXO
|
||||
OOOOO
|
10
2024/12/example3.txt
Normal file
10
2024/12/example3.txt
Normal file
|
@ -0,0 +1,10 @@
|
|||
RRRRIICCFF
|
||||
RRRRIICCCF
|
||||
VVRRRCCFFF
|
||||
VVRCCCJFFF
|
||||
VVVVCJJCFE
|
||||
VVIVCCJJEE
|
||||
VVIIICJJEE
|
||||
MIIIIIJJEE
|
||||
MIIISIJEEE
|
||||
MMMISSJEEE
|
50
2024/12/solution.js
Normal file
50
2024/12/solution.js
Normal file
|
@ -0,0 +1,50 @@
|
|||
|
||||
const input = (await Bun.file(Bun.argv[2]).text()).trim()
|
||||
|
||||
let map = input.split("\n")
|
||||
|
||||
const dirs = [[-1,0], [1,0], [0, -1], [0, 1]];
|
||||
const height = map.length;
|
||||
const width = height;
|
||||
|
||||
const key = (x,y) => x + y*width;
|
||||
const visited = new Set();
|
||||
|
||||
function search(x,y) {
|
||||
if (visited.has(key(x,y))) {
|
||||
return {area: 0, perimeter: 0}
|
||||
}
|
||||
visited.add(key(x,y))
|
||||
const letter = map[y][x]
|
||||
let perimeter = 0
|
||||
let area = 1
|
||||
for (const [dx, dy] of dirs) {
|
||||
const nletter = map[y + dy]?.[x + dx];
|
||||
if (letter !== nletter) {
|
||||
perimeter += 1
|
||||
continue
|
||||
}
|
||||
const n = search(x + dx, y + dy)
|
||||
area += n.area
|
||||
perimeter += n.perimeter
|
||||
}
|
||||
|
||||
return {area, perimeter}
|
||||
}
|
||||
|
||||
const regions = [];
|
||||
|
||||
for (let y = 0; y < height; y++) {
|
||||
for (let x = 0; x < width; x++) {
|
||||
if (visited.has(key(x,y))) continue
|
||||
regions.push(search(x,y))
|
||||
}
|
||||
}
|
||||
|
||||
let cost = 0
|
||||
for (const {area, perimeter} of regions) {
|
||||
cost += area * perimeter
|
||||
}
|
||||
console.log(cost)
|
||||
|
||||
|
Loading…
Reference in a new issue