Published
Edited
Dec 14, 2019
1 star
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
needed = function (chemical) {
let madeUnits;
return reactions.filter(r => chemical.name == r.product.name)
.map(r => {
let scale = Math.ceil(chemical.units / r.product.units);
madeUnits = scale * r.product.units;
return r.reactants.map(r => {
return {
units: r.units * scale,
name: r.name
};})
})[0].concat([{ units: chemical.units - madeUnits , name: chemical.name }]) //store surplus
}
Insert cell
requiredOre = function (fuel) {
let iter = 10000, required = [{units: fuel, name: "FUEL"}], log=[];
while (iter--) {
required = required.map(c => needed(c))
.reduce((a, v) => a.concat(v),[]) // flatten
.filter(c => c.units != 0) // consolidate surplus and requests
.reduce((a, c) => {
let i = a.findIndex(v => v.name == c.name);
if (i == -1) { return a.concat( { name: c.name , units: c.units } ); } //not yet requested
a[i].units += c.units; //subtract surplus
return a
}, []);
log.push(required);
//yield required.filter(c => c.name == 'ORE')[0]
if (required.every(c => (c.name == 'ORE')||(c.units < 0))) { break; }
}
return required.filter(c => c.name == 'ORE')[0].units
}
Insert cell
reactions = reactionsF(puzzle)
Insert cell
part1 = requiredOre(1)
Insert cell
Insert cell
Insert cell
Insert cell
md`**${part2}** units of FUEL can be produced with ${cargo} ORE.`
Insert cell
requiredOre(1900002) - cargo
Insert cell
cargo = 1000000000000
Insert cell
find = {
let fuelmin = 1893000;
let fuelmax = fuelmin + 1000;
while (requiredOre(fuelmin) < cargo && fuelmin < fuelmax) { fuelmin++ }
return fuelmin-1;
}
Insert cell
bisect = {
let fuel=1, tol = 10000, r = 1, g, iter=1000;
while (requiredOre(fuel) < cargo) { fuel *= 2; }
let min = fuel/2;
while ( iter-- ) {
g = Math.floor((min + fuel)/2);
r = requiredOre(g);
if (Math.abs( r - cargo ) < tol) { break; }
if (r < cargo) { min = g; }
else { fuel = g }
}
//just try any remaining range
while (requiredOre(min) < cargo) { min++ }
return min - 1
}
Insert cell
part2 = bisect
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