Published
Edited
Dec 14, 2021
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
template = [...input.split("\n\n")[0]]
Insert cell
rules = new Map(input.split("\n\n")[1].split("\n").map(k => k.split(" -> ")))
Insert cell
// takes a polymer
// returns a new polymer with the proper inserts (almost doubling in size)
zip = (template) => [
...[
...inserts(template) // turn inserts string into array of letters
.map( // add proper insert to each letter
(k, i) =>
template[i] + k)
]
.join("") // turn array of letters back into string
+ template[template.length - 1] // append last letter of template
]
Insert cell
zip(template)
Insert cell
i = inserts(template)
Insert cell
i.map((k, q) => template[q] + k)// + template[template.length - 1]
Insert cell
polymer = {
let a = template;
d3.range(0, steps).forEach(() => a = zip(a))
return a;
}
Insert cell
quantities = sort(count(polymer.join("")))
Insert cell
// takes a list of sorted quantities
// returns the difference of the most and least common element
difference = (list) => list[list.length - 1][1] - list[0][1]
Insert cell
differ = difference(quantities)
Insert cell
// takes a polymer
// returns all inserts for this polymer
inserts = (polymer) => polymer
.slice(0, -1) // pick all but last entry; i.e. n - 1 entries
.map( // grab and return the proper insert
(k, i) => rules.get(polymer[i] + polymer[i + 1])
)
Insert cell
inserts(template)
Insert cell
rules.get("NN")
Insert cell
Insert cell
// takes length of template (letter count)
// returns function that takes number of steps and returns length of resulting polymer
length = (k) => (step) => ({step, length: (k - 1) * 2 ** (step) + 1})
Insert cell
polymerLength = length(template.length)(40).length.toLocaleString()
Insert cell
map = count("NBBNBNBBCCNBCNCCNBBNBBNBBBNBBNBBCBHCBHHNHCBBCBHCB")
Insert cell
// takes a string
// returns a map with letter counts
count = (string) => {
const a = new Map();
[...string].forEach(
(k) => a.set(k, (a.get(k) || 0) + 1)
);
return a;
}
Insert cell
// takes a map
// returns map converted to sorted array
sort = (map) => [...map].sort(([_1, v1], [_2, v2]) => v1 > v2)
Insert cell
sort(map)
Insert cell
Insert cell
Insert cell
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