-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfabric2.js
57 lines (47 loc) · 1.21 KB
/
fabric2.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
class Sheet {
constructor (width = 1000, height = 1000) {
this._grid = Array
.from({ length: height })
.map(() => Array
.from({ length: width })
.map(() => 0));
}
reserve (claim) {
for (let y = 0; y < claim.height; y++) {
for (let x = 0; x < claim.width; x++) {
this._grid[y + claim.top][x + claim.left] += 1;
}
}
}
hasOverlap (claim) {
const content = [];
for (let y = 0; y < claim.height; y++) {
for (let x = 0; x < claim.width; x++) {
content.push(this._grid[y + claim.top][x + claim.left]);
}
}
return content.every((x) => x === 1);
}
}
const fabric = (input, width = 1000, height = 1000) => {
const sheet = new Sheet(width, height);
const claims = input
.split('\n')
.map((x) => {
const parts = x.match(/#(\d+) @ (\d+),(\d+): (\d+)x(\d+)/);
return {
id: +parts[1],
top: +parts[3],
left: +parts[2],
width: +parts[4],
height: +parts[5],
};
});
claims.forEach((claim) => sheet.reserve(claim));
for (let i = 0; i < claims.length; i++) {
if (sheet.hasOverlap(claims[i])) {
return claims[i].id;
}
}
};
module.exports = fabric;