-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathd11.js
119 lines (104 loc) · 2.6 KB
/
d11.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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
const fs = require('node:fs');
fs.readFile('inputs/d11_input','utf8',(err,data)=>{
if(err){
console.log(err);
return;
}
const lines = data.trim().split('\n');
console.log("Part 1:",answerP1(lines));
console.log("Part 2:",answerP2(lines));
});
function answerP1(lines){
const expRows = [];
const expCols = [];
const calcDistance = (dy,dx,points)=>{
return points.reduce((acc,[y,x])=>acc+Math.abs(dy-y)+Math.abs(dx-x),0);
}
for(let i = 0; i < lines.length ; i++){
if(!lines[i].includes('#')){
expRows.push(i);
}
}
for(let j = 0; j < lines[0].length ; j++){
let exp = true;
for(let i = 0; i < lines.length ;i++){
if(lines[i][j] == '#'){
exp = false;
break;
}
}
if(exp){
expCols.push(j);
}
}
let dx = 0;
let dy = 0;
let s = 0;
const points = [];
for(let i = 0; i < lines.length ; i++){
if(expRows.includes(i)){
dy++;
}
dx = 0;
for(let j = 0; j < lines.length ; j++){
if(expCols.includes(j)){
dx++;
}
if(lines[i][j] == '#'){
s += calcDistance(dy,dx,points);
points.push([dy,dx]);
}
dx++;
}
dy++;
}
return s;
}
//didn't need BigInt
function answerP2(lines){
const expRows = [];
const expCols = [];
const calcDistance = (dy,dx,points)=>{
const bigAbs=(a)=>(a > 0n ? a : -a);
return points.reduce((acc,[y,x])=>acc+bigAbs(dy-y)+bigAbs(dx-x),0n);
}
for(let i = 0; i < lines.length ; i++){
if(!lines[i].includes('#')){
expRows.push(i);
}
}
for(let j = 0; j < lines[0].length ; j++){
let exp = true;
for(let i = 0; i < lines.length ;i++){
if(lines[i][j] == '#'){
exp = false;
break;
}
}
if(exp){
expCols.push(j);
}
}
let dx = 0n;
let dy = 0n;
let s = 0n;
const points = [];
for(let i = 0; i < lines.length ; i++){
if(expRows.includes(i)){
dy+=1_000_000n-1n;
}
dx = 0n;
for(let j = 0; j < lines.length ; j++){
if(expCols.includes(j)){
dx+=1_000_000n-1n;
}
if(lines[i][j] == '#'){
s += calcDistance(dy,dx,points);
points.push([dy,dx]);
}
dx++;
}
dy++;
}
return s;
}