-
Notifications
You must be signed in to change notification settings - Fork 0
/
d9.js
57 lines (46 loc) · 1.16 KB
/
d9.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
const fs = require('node:fs');
fs.readFile('inputs/d9_input','utf8',(err,data)=>{
if(err){
console.log(err);
return;
}
const lines = data.trim().split('\n');
// console.log(lines)
console.log("Part 1:",answerP1(lines));
console.log("Part 2:",answerP2(lines));
});
function readNums(str){
return str.trim().split(' ').map(e=>parseInt(e));
}
function difference(nums){
const res = [];
for(let i = 1 ; i < nums.length ; i++){
res.push(nums[i]-nums[i-1]);
}
return res;
}
function answerP1(lines){
let sum = 0;
for(const line of lines){
let nums = readNums(line);
while(!nums.every(x=>x==0)){
sum += nums[nums.length-1];
nums = difference(nums);
}
}
return sum;
}
function answerP2(lines){
let sum = 0;
for(const line of lines){
let nums = readNums(line);
let init = [];
while(!nums.every(x=>x==0)){
init.push(nums[0]);
nums = difference(nums);
}
//why isn't the acc on the right in reduceRight >_<
sum += init.reduceRight((acc,x)=>x-acc,0);
}
return sum;
}