Published
Edited
Dec 10, 2021
Insert cell
# Advent of Code - Day 10
Insert cell
test = `[({(<(())[]>[[{[]{<()<>>
[(()[<>])]({[<{<<[]>>(
{([(<{}[<>[]}>{[]{[(<()>
(((({<>}<{<{<>}{[]{[]{}
[[<[([]))<([[{}[[()]]]
[{[{({}]{}}([{[{{{}}([]
{<[[]]>}<{[{[{[]{()[[[]
[<(<(<(<{}))><([]([]()
<{([([[(<>()){}]>(<<{{
<{([{{}}[<[[[<>{}]]]>[]]`.split("\n")
Insert cell
openings = Array.from("([{<")
Insert cell
closings = Array.from(")]}>")
Insert cell
score = [3,57,1197,25137]
Insert cell
findCorrupted = (line) => {
let seq = Array.from(line)
let errors = []
let os = []
seq.forEach((c, i) => {
if (openings.includes(c)) os.push(c)
if (closings.includes(c)) {
if (closings.indexOf(c) != openings.indexOf(os[os.length-1])) errors.push(c)
else os.pop()
}
})
return errors
}
Insert cell
computeTotal = (input) => input.map(findCorrupted)
.filter(l => l.length > 0)
.map(e => score[closings.indexOf(e[0])])
.reduce((a,b) => a+b)
Insert cell
computeTotal(test)
Insert cell
Insert cell
computeTotal(input)
Insert cell
computeIncomplete = (input)=>{
let incompletes = input.map(findCorrupted).map((e,i) => [e,i]).filter(x => x[0].length == 0).map(x => input[x[1]])
let completions = []

incompletes.forEach((line,i) =>{
let seq = Array.from(line)
let os = []
seq.forEach((c, i) => {
if (openings.includes(c)) os.push(c)
if (closings.includes(c)) os.pop()
})

completions[i] = os.reverse().map(c => openings.indexOf(c)+1).reduce((p,c) => p*5 + c, 0)
})
return completions.sort((a,b)=> a - b)[completions.length/2 - 0.5]
}
Insert cell
computeIncomplete(test)
Insert cell
computeIncomplete(input)
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more