-
Notifications
You must be signed in to change notification settings - Fork 1
/
day-15.js
84 lines (70 loc) · 2.11 KB
/
day-15.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
const exp = require('constants');
const fs = require('fs');
const fileName = "data/day-15-input.txt";
const file = fs.readFileSync(fileName, 'utf8');
const input = file.split(",");
function calculateHash(input) {
let currentValue = 0;
for(let i = 0; i < input.length; i++) {
let asciiValue = input.charCodeAt(i);
currentValue += asciiValue;
currentValue *= 17;
currentValue = currentValue % 256;
}
return currentValue;
}
function calculateFocusingPower(boxes) {
let sum = 0;
for(let i = 0; i < boxes.length; i++) {
if(boxes[i].length == 0) {
continue;
}
for(let j = 0; j < boxes[i].length; j++) {
let value = Number(boxes[i][j].split(" ")[1]);
let focusValue = (i + 1) *(j + 1) * value;
sum += focusValue;
}
}
return sum;
}
let sum = 0;
for (let i = 0; i < input.length; i++) {
let hashValue = calculateHash(input[i]);
sum += hashValue;
}
console.log(`Part 1: ${sum}`);
// Part 2
let boxes = [];
for(let i = 0; i < 256; i++) {
boxes.push([]);
}
for(let i = 0; i < input.length; i++) {
let operationIndex = input[i].includes("-") ? input[i].indexOf("-") : input[i].indexOf("=");
let key = input[i].substring(0, operationIndex);
let lensValue = input[i].substring(operationIndex + 1);
let value = `${key} ${lensValue}`;
let box = calculateHash(key);
let operation = input[i][operationIndex];
if(operation == "-") {
for(let i = 0; i < boxes[box].length; i++) {
if(boxes[box][i].startsWith(key)) {
boxes[box].splice(i, 1);
break;
}
}
} else if(operation == "=") {
let found = false;
for(let i = 0; i < boxes[box].length; i++) {
if(boxes[box][i].startsWith(key)) {
found = true;
boxes[box][i] = value;
break;
}
}
if(!found) {
boxes[box].push(value);
}
}
}
let totalFocusingPower = calculateFocusingPower(boxes);
console.log(`Part 2: ${totalFocusingPower}`);