Published
Edited
Dec 14, 2021
1 star
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
result = {
let datasetUsed = datasets[dataset2]
let start = performance.now()
let bigrams = countBigrams(datasetUsed.template)
for (let index = 0; index < insertionPasses2; ++index) {
bigrams = applyInsertionsForBigrams(bigrams, datasetUsed.insertions)
}
let end = performance.now()
let elapsedTime = end - start
return [bigrams, elapsedTime]
}
Insert cell
Insert cell
Insert cell
function applyInsertionsForBigrams(bigrams, insertions) {
let newBigrams = new Map
for (const [bigram, count] of bigrams.bigrams.entries()) {
let insertedElement = insertions.get(bigram)
let firstNewBigram = `${bigram[0]}${insertedElement}`
let secondNewBigram = `${insertedElement}${bigram[1]}`
if (newBigrams.has(firstNewBigram))
newBigrams.set(firstNewBigram, newBigrams.get(firstNewBigram) + count)
else
newBigrams.set(firstNewBigram, count)
if (newBigrams.has(secondNewBigram))
newBigrams.set(secondNewBigram, newBigrams.get(secondNewBigram) + count)
else
newBigrams.set(secondNewBigram, count)
}

return {
bigrams: newBigrams,
first: bigrams.first,
last: bigrams.last
}
}
Insert cell
function countBigrams(template) {
let bigrams = new Map()
for (let index = 0; index < template.length - 1; ++index) {
let bigram = template.substring(index, index + 2)
if (bigrams.has(bigram))
bigrams.set(bigram, bigrams.get(bigram) + 1)
else
bigrams.set(bigram, 1)
}
let first = template[0]
let last = template[template.length - 1]
return {
bigrams: bigrams,
first: first,
last: last
}
}
Insert cell
Insert cell
Insert cell
function readInput(txt) {
let template = ""
let insertions = new Map()

txt.split("\n").filter(line => line.trim().length > 0).forEach( line => {
if (line.indexOf("->") === -1) {
template = line
} else {
let [pair, insert] = line.split(" -> ")
insertions.set(pair, insert)
}
})

return {
template: template,
insertions: insertions
}
}
Insert cell
test = readInput(`NNCB

CH -> B
HH -> N
CB -> H
NH -> C
HB -> C
HC -> B
HN -> C
NN -> C
BH -> H
NC -> B
NB -> B
BN -> B
BB -> N
BC -> B
CC -> N
CN -> C`)
Insert cell
input = FileAttachment("14_input.txt").text().then(txt => readInput(txt))
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