Skip to content

Instantly share code, notes, and snippets.

@Mellen
Created December 14, 2021 17:03
Show Gist options
  • Save Mellen/5778f5d8861c8d50835d8b9cd6d24415 to your computer and use it in GitHub Desktop.
Save Mellen/5778f5d8861c8d50835d8b9cd6d24415 to your computer and use it in GitHub Desktop.
(function(inp)
{
let [polymer, rest] = inp.split('\n\n');
let pairInserts = new Map(rest.trim().split('\n').map(line => line.split(' -> ')));
let pairCounts = new Map();
let initialPairs = polymer.split('').reduce((acc, s, i, arr) =>
{
if(i < arr.length - 1)
{
acc.push(s+arr[i+1]);
}
return acc;
}, []);
let lastElement = polymer[polymer.length -1];
for(let pair of initialPairs)
{
pairCounts.set(pair, 1);
}
for(let i = 0; i < 40; i++)
{
let newPairCounts = new Map();
for(let [pair, count] of pairCounts)
{
let [l, r] = pair.split('');
let insert = pairInserts.get(pair);
let leftPair = l + insert;
if(newPairCounts.has(leftPair))
{
let oc = newPairCounts.get(leftPair);
newPairCounts.set(leftPair, oc+count);
}
else
{
newPairCounts.set(leftPair, count);
}
let rightPair = insert + r;
if(newPairCounts.has(rightPair))
{
let oc = newPairCounts.get(rightPair);
newPairCounts.set(rightPair, oc+count);
}
else
{
newPairCounts.set(rightPair, count);
}
}
pairCounts = newPairCounts;
}
let elCounts = new Map();
for(let [pair, count] of pairCounts)
{
let el = pair[0];
if(elCounts.has(el))
{
let c = elCounts.get(el);
elCounts.set(el, c + count);
}
else
{
elCounts.set(el, count);
}
}
if(elCounts.has(lastElement))
{
let c = elCounts.get(lastElement);
elCounts.set(lastElement, c + 1);
}
else
{
elCounts.set(lastElement, 1);
}
let max = 0;
let min = Number.MAX_SAFE_INTEGER;
for(let [el, count] of elCounts)
{
if(count < min)
{
min = count;
}
if(count > max)
{
max = count;
}
}
return max - min;
})(document.querySelector('pre').textContent);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment