-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday07.js
52 lines (50 loc) · 1.32 KB
/
day07.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
const fs = require('fs')
const infile = fs.readFileSync('input/day07', 'utf-8')
function day071(input){
let bagTypes = new Set()
return canContain('shiny gold', bagTypes, input).size
}
function day072(input){
let bags = new Map()
input.split('\r\n').forEach(e=>{
let eArr = e.split(' contain ')
let container = eArr[0].split(' ').slice(0,-1).join(' ')
let preContents = eArr[1].split(/(?:, )*(?=\d)/)
let contents = []
preContents.forEach(f=>{
f = f.split(' ').slice(0, -1).join(' ')
if(f!='no other')contents.push(f)
})
bags.set(container, contents)
})
return mustContain('shiny gold', bags)
}
function canContain(color, types, input){
input.split('\r\n').forEach(e=>{
let eArr = e.split(' contain ')
let container = eArr[0].split(' ').slice(0,-1).join(' ')
if(types.has(container)) {
return types
}
let contents = eArr[1].split(/(?:, )*\d /)
contents.shift()
contents.forEach(f=>{
f = f.split(' ').slice(0,-1).join(' ')
if(f==color){
types.add(container)
types = canContain(container, types, input)
}
})
})
return types
}
function mustContain(color, bags){
let bagCount = 0
bags.get(color).forEach(e=>{
let count = parseInt(e.slice(0,1),10)
bagCount += count+count*mustContain(e.slice(2), bags)
})
return bagCount
}
console.log(day071(infile))
console.log(day072(infile))