-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathinput.js
More file actions
64 lines (58 loc) · 1.78 KB
/
input.js
File metadata and controls
64 lines (58 loc) · 1.78 KB
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
const path = require('path');
const fs = require('fs');
const input = fs
.readFileSync(path.join(__dirname, 'input.txt'), 'utf8')
.toString()
.trim()
.split('\n\n')
.map((text_block) => {
const lines = text_block.split('\n');
/**
* @example
* Monkey 0:
* Starting items: 57, 58
* Operation: new = old * 19
* Test: divisible by 7
* If true: throw to monkey 2
* If false: throw to monkey 3
*/
const monkey = lines.reduce((acc, line, i) => {
line = line.trim();
if (i === 0) {
let [, id] = /Monkey (\d+):/.exec(line);
id = parseInt(id, 10);
acc.id = id;
} else if (i === 1) {
let [, items] = /Starting items: (.+)$/.exec(line);
items = items.split(', ').map((v) => parseInt(v, 10));
acc.items = items;
} else if (i === 2) {
// Part two, smarter parsing
let [, left, op, right] = /Operation: new = (\w+) ([\+\*]) (\w+)$/.exec(line);
const worryFn = (oldValue) => {
let leftVal = left === 'old' ? oldValue : parseInt(left, 10);
let rightVal = right === 'old' ? oldValue : parseInt(right, 10);
// Only two operations, `+` and `*`
return op === '+' ? leftVal + rightVal : leftVal * rightVal;
};
acc.worryFn = worryFn;
} else if (i === 3) {
let [, divisible_by] = /Test: divisible by (\d+)/.exec(line);
divisible_by = parseInt(divisible_by, 10);
acc.divisible_by = divisible_by;
} else if (i === 4) {
let [, if_true] = /If true: throw to monkey (\d+)$/.exec(line);
if_true = parseInt(if_true, 10);
acc.if_true = if_true;
} else if (i === 5) {
let [, if_false] = /If false: throw to monkey (\d+)$/.exec(line);
if_false = parseInt(if_false, 10);
acc.if_false = if_false;
}
return acc;
}, {});
return monkey;
});
module.exports = {
input,
};