Published
Edited
Dec 5, 2021
Insert cell
Insert cell
Insert cell
count0 = {
let counts = []
for (let i = 0; i < entryLength; i++)
counts.push(countAtPos(textInput, "0", i))
return counts
}
Insert cell
countAtPos = ( list, value, pos ) => {
return list.filter( val => val[pos] === value).length
}
Insert cell
gamma = {
let res = ""
for (let count of count0)
if (count > textInput.length/2)
res += 0
else
res += 1
return res
}
Insert cell
gammaInt = binToInt(gamma)
Insert cell
epsilon = {
let res = ""
for (let count of count0)
if (count > textInput.length/2)
res += 1
else
res += 0
return res
}
Insert cell
epsilonInt = binToInt(epsilon)
Insert cell
binToInt = (strBin) => {
let res = 0
strBin.split("").reverse().forEach( (bit, idx) => {
res += bit * (2 ** idx)
})
return res
}
Insert cell
consumption = gammaInt * epsilonInt
Insert cell
Insert cell
oxygen = applyBitCriteria(textInput, "mostCommon")
Insert cell
co2 = applyBitCriteria(textInput, "leastCommon")
Insert cell
function applyBitCriteria( binList, criteria, bitIndex = 0 ) {
if (binList.length === 1)
return binList[0]
let count0 = countAtPos(binList, "0", bitIndex)
switch(criteria) {
case "mostCommon":
if (count0 > binList.length / 2)
return applyBitCriteria(binList.filter( val => val[bitIndex] === "0"), criteria, ++bitIndex)
else
return applyBitCriteria(binList.filter( val => val[bitIndex] === "1"), criteria, ++bitIndex)
break;
case "leastCommon":
if (count0 > binList.length / 2)
return applyBitCriteria(binList.filter( val => val[bitIndex] === "1"), criteria, ++bitIndex)
else
return applyBitCriteria(binList.filter( val => val[bitIndex] === "0"), criteria, ++bitIndex)
break;
default:
return `Error : unknown criteria "${criteria}"`
}
}
Insert cell
oxygenInt = binToInt(oxygen)
Insert cell
co2Int = binToInt(co2)
Insert cell
lifeSupport = oxygenInt * co2Int
Insert cell
Insert cell
entryLength = textInput[0].length
Insert cell
textInput = FileAttachment("03_input.txt").text().then( txt => txt.trim().split("\n"))
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