-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.js
77 lines (61 loc) · 1.96 KB
/
main.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
const fs = require('fs')
const file = fs.readFileSync('input.txt').toString('utf8');
function sanitizeBagName(name) {
return name.replaceAll('bags', 'bag').replaceAll('.', '')
}
function findBagsContaining(bags, name) {
return Object.keys(bags)
.filter(bagName => bags[bagName].filter(content => content.name == name).length > 0)
}
const bags = file.split('\n')
.filter(line => line.length > 0)
.map(ruleString => {
const [ nameStr, contentStr] = ruleString.split(' contain ')
return {
[sanitizeBagName(nameStr)]: contentStr.split(', ')
.map(contentString => {
const [qtyStr, nameStr] = contentString.split(/ (.+)/)
return {
name: sanitizeBagName(nameStr),
quantity: Number(qtyStr),
}
})
.filter(content => Number.isInteger(content.quantity))
}
})
.reduce((a, b) => ({...a, ...b}))
const bagContainers = Object.keys(bags)
.map(bagName => ({
[bagName]: findBagsContaining(bags, bagName)
}))
.reduce((a, b) => ({...a, ...b}))
// PART 1
function getContainersOfBag(bagContainers, bag) {
let visited = new Set()
let marked = bagContainers[bag]
while (marked.length > 0) {
const bag = marked.shift()
visited.add(bag)
marked = [...marked, ...bagContainers[bag]]
}
return visited
}
console.log("Number of bags that eventually contain shiny gold bag:",
getContainersOfBag(bagContainers, "shiny gold bag").size)
// PART 2
function getContentSizeOfBags(bags, bag, sizes = {}) {
if (bag in sizes) return sizes;
let size = 0
for (const {name, quantity} of bags[bag]) {
if (!(name in sizes)) {
sizes = {...sizes, ...getContentSizeOfBags(bags, name, sizes)}
}
size += quantity * (1 + sizes[name])
}
sizes[bag] = size
return sizes
}
function getContentSizeOfBag(bags, bag) {
return getContentSizeOfBags(bags, bag)[bag]
}
console.log('Number of bags inside shiny gold bag:', getContentSizeOfBag(bags, 'shiny gold bag'))