2019-12-14

# Day 14: Space Stoichiometry

Description:
--- Day 14: Space Stoichiometry ---

As you approach the rings of Saturn, your ship's low fuel indicator turns on. There isn't any fuel here, but the rings have plenty of raw material. Perhaps your ship's Inter-Stellar Refinery Union brand nanofactory can turn these raw materials into fuel.

You ask the nanofactory to produce a list of the reactions it can perform that are relevant to this process (your puzzle input). Every reaction turns some quantities of specific input chemicals into some quantity of an output chemical. Almost every chemical is produced by exactly one reaction; the only exception, ORE, is the raw material input to the entire process and is not produced by a reaction.

You just need to know how much ORE you'll need to collect before you can produce one unit of FUEL.

Each reaction gives specific quantities for its inputs and output; reactions cannot be partially run, so only whole integer multiples of these quantities can be used. (It's okay to have leftover chemicals when you're done, though.) For example, the reaction 1 A, 2 B, 3 C => 2 D means that exactly 2 units of chemical D can be produced by consuming exactly 1 A, 2 B and 3 C. You can run the full reaction as many times as necessary; for example, you could produce 10 D by consuming 5 A, 10 B, and 15 C.

Suppose your nanofactory produces the following list of reactions:

10 ORE => 10 A
1 ORE => 1 B
7 A, 1 B => 1 C
7 A, 1 C => 1 D
7 A, 1 D => 1 E
7 A, 1 E => 1 FUEL

The first two reactions use only ORE as inputs; they indicate that you can produce as much of chemical A as you want (in increments of 10 units, each 10 costing 10 ORE) and as much of chemical B as you want (each costing 1 ORE). To produce 1 FUEL, a total of 31 ORE is required: 1 ORE to produce 1 B, then 30 more ORE to produce the 7 + 7 + 7 + 7 = 28 A (with 2 extra A wasted) required in the reactions to convert the B into C, C into D, D into E, and finally E into FUEL. (30 A is produced because its reaction requires that it is created in increments of 10.)

Or, suppose you have the following list of reactions:

9 ORE => 2 A
8 ORE => 3 B
7 ORE => 5 C
3 A, 4 B => 1 AB
5 B, 7 C => 1 BC
4 C, 1 A => 1 CA
2 AB, 3 BC, 4 CA => 1 FUEL

The above list of reactions requires 165 ORE to produce 1 FUEL:

Consume 45 ORE to produce 10 A.
Consume 64 ORE to produce 24 B.
Consume 56 ORE to produce 40 C.
Consume 6 A, 8 B to produce 2 AB.
Consume 15 B, 21 C to produce 3 BC.
Consume 16 C, 4 A to produce 4 CA.
Consume 2 AB, 3 BC, 4 CA to produce 1 FUEL.

Here are some larger examples:

13312 ORE for 1 FUEL:

157 ORE => 5 NZVS
165 ORE => 6 DCFZ
44 XJWVT, 5 KHKGT, 1 QDVJ, 29 NZVS, 9 GPVTF, 48 HKGWZ => 1 FUEL
12 HKGWZ, 1 GPVTF, 8 PSHF => 9 QDVJ
179 ORE => 7 PSHF
177 ORE => 5 HKGWZ
7 DCFZ, 7 PSHF => 2 XJWVT
165 ORE => 2 GPVTF
3 DCFZ, 7 NZVS, 5 HKGWZ, 10 PSHF => 8 KHKGT

180697 ORE for 1 FUEL:

2 VPVL, 7 FWMGM, 2 CXFTF, 11 MNCFX => 1 STKFG
17 NVRVD, 3 JNWZP => 8 VPVL
53 STKFG, 6 MNCFX, 46 VJHF, 81 HVMC, 68 CXFTF, 25 GNMV => 1 FUEL
22 VJHF, 37 MNCFX => 5 FWMGM
139 ORE => 4 NVRVD
144 ORE => 7 JNWZP
5 MNCFX, 7 RFSQX, 2 FWMGM, 2 VPVL, 19 CXFTF => 3 HVMC
5 VJHF, 7 MNCFX, 9 VPVL, 37 CXFTF => 6 GNMV
145 ORE => 6 MNCFX
1 NVRVD => 8 CXFTF
1 VJHF, 6 MNCFX => 4 RFSQX
176 ORE => 6 VJHF

2210736 ORE for 1 FUEL:

171 ORE => 8 CNZTR
7 ZLQW, 3 BMBT, 9 XCVML, 26 XMNCP, 1 WPTQ, 2 MZWV, 1 RJRHP => 4 PLWSL
114 ORE => 4 BHXH
14 VRPVC => 6 BMBT
6 BHXH, 18 KTJDG, 12 WPTQ, 7 PLWSL, 31 FHTLT, 37 ZDVW => 1 FUEL
6 WPTQ, 2 BMBT, 8 ZLQW, 18 KTJDG, 1 XMNCP, 6 MZWV, 1 RJRHP => 6 FHTLT
15 XDBXC, 2 LTCX, 1 VRPVC => 6 ZLQW
13 WPTQ, 10 LTCX, 3 RJRHP, 14 XMNCP, 2 MZWV, 1 ZLQW => 1 ZDVW
5 BMBT => 4 WPTQ
189 ORE => 9 KTJDG
1 MZWV, 17 XDBXC, 3 XCVML => 2 XMNCP
12 VRPVC, 27 CNZTR => 2 XDBXC
15 KTJDG, 12 BHXH => 5 XCVML
3 BHXH, 2 VRPVC => 7 MZWV
121 ORE => 7 VRPVC
7 XCVML => 6 RJRHP
5 BHXH, 4 VRPVC => 5 LTCX

Given the list of reactions in your puzzle input, what is the minimum amount of ORE required to produce exactly 1 FUEL?

--- Part Two ---

After collecting ORE for a while, you check your cargo hold: 1 trillion (1000000000000) units of ORE.

With that much ore, given the examples above:

The 13312 ORE-per-FUEL example could produce 82892753 FUEL.
The 180697 ORE-per-FUEL example could produce 5586022 FUEL.
The 2210736 ORE-per-FUEL example could produce 460664 FUEL.

Given 1 trillion ORE, what is the maximum amount of FUEL you can produce?

Input:
1 GZJM, 2 CQFGM, 20 SNPQ, 7 RVQG, 3 FBTV, 27 SQLH, 10 HFGCF, 3 ZQCH => 3 SZCN
4 FCDL, 6 NVPW, 21 GZJM, 1 FBTV, 1 NLSNB, 7 HFGCF, 3 SNPQ => 1 LRPK
15 FVHTD, 2 HBGFL => 4 BCVLZ
4 GFGS => 4 RVQG
5 BCVLZ, 4 LBQV => 7 TWSRV
6 DWKTF, 4 VCKL => 4 KDJV
16 WZJB => 4 RBGJQ
8 RBGJQ, 5 FCDL, 2 LWBQ => 1 MWSX
100 ORE => 7 WBRL
7 PGZGQ => 5 FVHTD
1 JCDML, 2 TWSRV => 9 JSQSB
3 WZJB, 1 NXNR => 6 XFPVS
7 JPCPK => 8 JCDML
11 LWBQ, 8 XFPVS => 9 PSPFR
2 TWSRV => 8 NVPW
2 LBQV => 1 PMJFD
2 LCZBD => 3 FBTV
1 WBQC, 1 ZPNKQ => 8 JPCPK
44 HFGCF, 41 PSPFR, 26 LMSCR, 14 MLMDC, 6 BWTHK, 3 PRKPC, 13 LRPK, 50 MWSX, 8 SZCN => 1 FUEL
1 XFPVS => 4 BJRSZ
1 GWBDR, 1 MBQC => 4 HZPRB
2 BJRSZ, 9 KDJV, 1 XFPVS => 8 SNVL
7 PMJFD, 30 SNVL, 1 BJRSZ => 2 JMTG
8 SNVL, 1 RBGJQ => 9 FCDL
2 HZPRB => 6 NLSNB
2 GRDG => 9 VCKL
1 FVHTD => 9 WZJB
130 ORE => 2 GRDG
3 WZJB, 1 GFGS, 1 NXNR => 9 SNPQ
9 VCKL => 5 WBQC
1 WBRL, 11 FPMPB => 7 PGZGQ
118 ORE => 3 LMSCR
3 SQLH, 1 PMJFD, 4 XJBL => 7 MLMDC
1 LMSCR, 10 GRDG => 2 TBDH
6 DWKTF => 2 SQLH
2 BJRSZ, 1 PGZGQ, 3 NXNR => 7 MBQC
5 PRKPC => 7 NXNR
9 SQLH => 5 LCZBD
1 FCDL => 9 CQFGM
5 PGZGQ, 1 TBDH => 8 HBGFL
15 JSQSB => 5 HFGCF
2 PGZGQ, 1 VCKL => 4 ZPNKQ
3 FBTV, 3 JMTG => 5 QLHKT
1 ZGZST, 2 LCZBD => 7 GFGS
2 RVQG => 4 ZQCH
1 ZPNKQ => 5 LBQV
3 LWBQ => 8 XJBL
1 LBQV, 9 JCDML => 3 GWBDR
8 VCKL, 6 FVHTD => 9 DWKTF
3 JCDML => 3 ZGZST
160 ORE => 5 FPMPB
3 SQLH, 22 LBQV, 5 BCVLZ => 6 PRKPC
1 WZJB => 2 GZJM
10 ZGZST => 2 LWBQ
5 TBDH, 19 NXNR, 9 QLHKT, 2 KDJV, 1 SQLH, 1 GWBDR, 6 HFGCF => 4 BWTHK

Part 1:
``````namespace AdventOfCode2019_14_1
{
const DAY     = 14;
const PROBLEM = 1;

export async function run()
{
if (input == null) return;

let recipes: { [_:string]:[number, [number, string][], string ] } = {};

for (let line of input.split(new RegExp('\r?\n')).filter(p => p.trim().length > 0))
{
const left  = line.split(" => ");
const right = line.split(" => ");

const right_n = parseInt(right.split(" "));
const right_v = right.split(" ");

recipes[right_v] = [ right_n, left.split(", ").map(p => [ parseInt(p.split(" ")), p.split(" ") ]  ), line ];
}

// -------------

let missing : [number, string][] = [ [1, "FUEL"] ];
let surplus : [number, string][] = [];

while( missing.length>1 || missing !== "ORE" )
{
missing = missing.filter(p => p>0);
surplus = surplus.filter(p => p>0);

AdventOfCode.outputConsole("missing: [" + missing.map(p => p+"|"+p).reduce((a,b)=>a+"  "+b, "")+"]");
AdventOfCode.outputConsole("surplus: [" + surplus.map(p => p+"|"+p).reduce((a,b)=>a+"  "+b, "")+"]");

let target = missing.pop();
if (target === undefined) throw "undef??";

if (target === "ORE")
{
missing.push(target);
missing = missing.reverse();
target = missing.pop();
if (target === undefined) throw "undef??";
}

const recipe = recipes[target];

if (target > recipe)
{
missing.push([ target - recipe, target ]);
}
else if (target < recipe)
{
let found=false;
for(let i=0; i<surplus.length; i++)
{
if (surplus[i] === target)
{
surplus[i] += (recipe - target);
found = true;
break;
}
}
if (!found) surplus.push([ (recipe - target), target ]);
}

let incredentials = Object.assign([], recipe);

for(let icrd of incredentials)
{
let   incred_count = icrd;
const incred_name  = icrd;
for(let i=0; i<surplus.length; i++)
{
if (surplus[i] === incred_name)
{
if (surplus[i] >= incred_count)
{
surplus[i] -= incred_count;
incred_count = 0;
}
else
{
incred_count -= surplus[i];
surplus[i] = 0;
}
}
}

if (incred_count > 0)
{
let found=false;
for(let i=0; i<missing.length; i++)
{
if (missing[i] === incred_name)
{
missing[i] += incred_count;
found = true;
break;
}
}
if (!found) missing.push([incred_count, incred_name]);
}

}
}

}
}
``````
Result: 168046

Part 2:
``````namespace AdventOfCode2019_14_2
{
const DAY     = 14;
const PROBLEM = 2;

export async function run()
{
if (input == null) return;

let recipes: { [_:string]:[number, [number, string][], string ] } = {};

for (let line of input.split(new RegExp('\r?\n')).filter(p => p.trim().length > 0))
{
const left  = line.split(" => ");
const right = line.split(" => ");

const right_n = parseInt(right.split(" "));
const right_v = right.split(" ");

recipes[right_v] = [ right_n, left.split(", ").map(p => [ parseInt(p.split(" ")), p.split(" ") ]  ), line ];
}

// binary search

const target = 1_000_000_000_000;

let lower = 1;
let upper = 1_000_000_000_000;

while(upper-lower>1)
{
const f = Math.floor((upper+lower) / 2);
const o = calcOreRequirement(recipes, f);

if (o > target) {
upper = f;
} else if (o < target) {
lower = f;
} else {
upper = lower = f; // jackpot
}

}

}

function calcOreRequirement(recipes: { [_:string]:[number, [number, string][], string ] }, fuelcount: number): number
{

let missing : [number, string][] = [ [fuelcount, "FUEL"] ];
let surplus : [number, string][] = [];

while( missing.length>1 || missing !== "ORE" )
{
missing = missing.filter(p => p>0);
surplus = surplus.filter(p => p>0);

//AdventOfCode.outputConsole("missing: [" + missing.map(p => p+"|"+p).reduce((a,b)=>a+"  "+b, "")+"]");
//AdventOfCode.outputConsole("surplus: [" + surplus.map(p => p+"|"+p).reduce((a,b)=>a+"  "+b, "")+"]");

let target = missing.pop();
if (target === undefined) throw "undef??";

if (target === "ORE")
{
missing.push(target);
missing = missing.reverse();
target = missing.pop();
if (target === undefined) throw "undef??";
}

const orig_recipe = recipes[target];

const factor = Math.max(1, Math.ceil(target / orig_recipe));
let recipe: [number, [number, string][], string] =
[
factor*orig_recipe,
Object.assign([], orig_recipe).map(p => [ factor*p, p ] ),
(""+factor+"*("+orig_recipe+")")
];

if (target > recipe)
{
missing.push([ target - recipe, target ]);
}
else if (target < recipe)
{
let found=false;
for(let i=0; i<surplus.length; i++)
{
if (surplus[i] === target)
{
surplus[i] += (recipe - target);
found = true;
break;
}
}
if (!found) surplus.push([ (recipe - target), target ]);
}

let incredentials = Object.assign([], recipe);

for(let icrd of incredentials)
{
let   incred_count = icrd;
const incred_name  = icrd;
for(let i=0; i<surplus.length; i++)
{
if (surplus[i] === incred_name)
{
if (surplus[i] >= incred_count)
{
surplus[i] -= incred_count;
incred_count = 0;
}
else
{
incred_count -= surplus[i];
surplus[i] = 0;
}
}
}

if (incred_count > 0)
{
let found=false;
for(let i=0; i<missing.length; i++)
{
if (missing[i] === incred_name)
{
missing[i] += incred_count;
found = true;
break;
}
}
if (!found) missing.push([incred_count, incred_name]);
}