-
Notifications
You must be signed in to change notification settings - Fork 0
/
day20.js
85 lines (73 loc) · 2.14 KB
/
day20.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
const { readData } = require("./readfile");
const input = readData("day20Input.txt");
const tileBlocks = input.split(/\n\n/);
const _ = require("lodash");
const parseTile = (tileBlock) => {
const reg = new RegExp(/Tile (\d{4}):/);
const lines = tileBlock.split(/\n/);
const matches = lines[0].match(reg);
const id = parseInt(matches[1]);
const body = lines.slice(1);
return {
id,
body,
};
};
/*
top, right, bottom, left
*/
const parseEdges = (tile) => {
const length = tile.length;
const top = tile[0].split("");
const bottom = tile[length - 1].split("");
let left = [];
let right = [];
for (i = 0; i < length; i++) {
right.push(tile[i][length - 1]);
left.push(tile[i][0]);
}
const edges = [
top,
right,
bottom,
left,
getReversedStringArray(top),
getReversedStringArray(right),
getReversedStringArray(bottom),
getReversedStringArray(left),
];
// console.log(edges);
const edgesValues = edges.map((edge) => countEdgeValue(edge));
return edgesValues;
};
const getReversedStringArray = (array) => array.join("").split("").reverse();
const countEdgeValue = (edge) =>
edge
.map((i, index) => (i === "#" ? 1 << index : 0))
.reduce((acc, cur) => acc + cur, 0);
const tiles = tileBlocks.map((tileBlock) => parseTile(tileBlock));
// tiles.forEach((tile) => console.log(tile.id, tile.tile));
const tileWithValues = tiles.map((tile) => ({
id: tile.id,
values: parseEdges(tile.body),
}));
// console.log(JSON.stringify(tileWithValues));
const findCornerTilesProduct = (tileWithValues) => {
const allValues = tileWithValues
.map((t) => t.values)
.reduce((acc, cur) => [...acc, ...cur], []);
const valueMap = _.groupBy(allValues, (x) => x);
console.log(valueMap);
const cornerTileIds = tileWithValues
.filter((tile) => {
const count = tile.values.filter((value) => valueMap[value].length === 1)
.length;
// console.log(tile.id, count);
return count === 4;
})
.map((t) => t.id);
// console.log(cornerTileIds);
console.log(cornerTileIds.reduce((acc, cur) => acc * cur, 1));
return cornerTileIds;
};
findCornerTilesProduct(tileWithValues);