-
Notifications
You must be signed in to change notification settings - Fork 17
/
part-two.js
79 lines (71 loc) · 1.69 KB
/
part-two.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
const { input: raw_input } = require('./input');
// Process the input specifically for Part Two
const input = raw_input.map((instruction) => {
let { type, address } = instruction;
if (type === 'write') {
// Convert the address to an array of 1s and 0s
let address_as_binary_num_arr = address
.toString(2)
.padStart(36, '0')
.split('')
.map((v) => +v);
return {
...instruction,
address: address_as_binary_num_arr,
};
} else {
return instruction;
}
});
/**
* @param {Array} val
* @returns {Array<String>}
*/
function floatingToPossibilites(vals) {
let pushed = false;
let new_vals = [];
for (let val of vals) {
let x = val.indexOf('X');
if (x > -1) {
let a = `${val.slice(0, x)}0${val.slice(x + 1)}`;
let b = `${val.slice(0, x)}1${val.slice(x + 1)}`;
new_vals.push(a, b);
pushed = true;
}
}
if (pushed) {
return floatingToPossibilites(new_vals);
} else {
return vals;
}
}
function applyMaskOverMemoryAddress(mask, _address) {
let address = _address.slice(0);
for (let i = 0; i < mask.length; i++) {
let m = mask[i];
if (m === '1' || m === 'X') {
address[i] = m;
}
}
return address.join('');
}
function run(input) {
let memory = {};
let current_mask;
for (line of input) {
const { type, address, value } = line;
if (type === 'mask') {
current_mask = value;
} else {
let masked_address = applyMaskOverMemoryAddress(current_mask, address);
let current_addresses_to_write_to = floatingToPossibilites([masked_address]).map((a) =>
parseInt(a, 2)
);
for (let addr of current_addresses_to_write_to) {
memory[addr] = value;
}
}
}
return Object.values(memory).reduce((a, b) => a + b, 0);
}
console.log(run(input));