Published
Edited
Dec 9, 2020
Insert cell
Insert cell
notASumFromRollingQueue(exampleinput)(5) // part 1 example
Insert cell
notASumFromRollingQueue(input)(25) // part 1 solution
Insert cell
encryptionWeakness(exampleinput)(5) // part 2 example
Insert cell
encryptionWeakness(input)(25) // part 2 solution
Insert cell
// String -> Number -> Number
encryptionWeakness = str => queuesize => {
const data = parseInput(str)
const target = walkqueue(data)(queuesize)
const range = subsetThatSumsToTarget(data)(target)
return range.reduce((acc, inc) => inc < acc ? inc : acc, Infinity) + // min
range.reduce((acc, inc) => inc > acc ? inc : acc, -Infinity) // max
}
Insert cell
// Return a range of numbers in data that sums to target
// [Number] -> Number -> [Number]
subsetThatSumsToTarget = data => target => {
for(let i = 0; i < data.length; i++) {
let lookahead = i;
let rollingsum = data[i];
while(rollingsum < target) {
lookahead++;
rollingsum+=data[lookahead]
if(rollingsum==target) return data.slice(i,lookahead+1)
}
}
}
Insert cell
// String -> Number -> Number
notASumFromRollingQueue = str => queuesize => walkqueue(parseInput(str))(queuesize)
Insert cell
// Return first number in data not found in sums of the combos of qsize previous numbers
// [Number] -> Number -> Number
walkqueue = data => qsize => {

let index = qsize
let combs = pairCombos(data.slice(index-qsize,index))
let sums = pairwiseSum(combs)
for(index; index < data.length; index++) {
if(sums.includes(data[index])) {
combs = pairCombos(data.slice(index+1-qsize,index+1))
sums = pairwiseSum(combs)
} else {
return data[index]
// return [data[index], index, combs, sums] // debug
}
}
}
Insert cell
// For array of pairs, produce array of sums of those pairs
// [[Number,Number]] -> [Number]
pairwiseSum = arr => arr.map(([a,b]) => a + b)
Insert cell
// Get all the pair combinations possible from an array
// [Number] -> [[Number, Number]]
pairCombos = arr => {
let combos = []
for(let i = 0; i < arr.length; i++) {
for(let j = i + 1; j < arr.length; j++) {
combos.push([arr[i],arr[j]])
}
}
return combos
}
Insert cell
// String -> [Number]
parseInput = str => str.split("\n").map(Number)
Insert cell
Insert cell
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