Skip to content

Instantly share code, notes, and snippets.

@oguz-ismail
Last active November 15, 2023 13:03
Show Gist options
  • Save oguz-ismail/092d5a8fbb1f85c81368db63bc5b5924 to your computer and use it in GitHub Desktop.
Save oguz-ismail/092d5a8fbb1f85c81368db63bc5b5924 to your computer and use it in GitHub Desktop.
{
gsub(/,/, "")
incr[$NF] = $(NF-1)
for (i = 1; i < NF-2; i += 2) {
reqs[$NF, ++nreqs[$NF]] = $(i+1)
qtys[$NF, $(i+1)] = $i
}
}
END {
print ore("FUEL", 1)
print fuel(1000000000000)
}
function ore(chem, qty, mul, sum, i, req) {
if (chem == "ORE")
return qty
if (ex[chem] < qty) {
mul = int((qty-ex[chem] + incr[chem]-1) / incr[chem])
ex[chem] += mul*incr[chem]
}
ex[chem] -= qty
for (i = 1; i <= nreqs[chem]; i++) {
req = reqs[chem, i]
sum += ore(req, mul*qtys[chem, req])
}
return sum
}
function fuel(cargo, i, min, max, step) {
step = 65536
for (i = 1; step >= 1 || step <= -1; i += step) {
delete ex
if (ore("FUEL", i) < cargo) {
min = i
if (step < 0)
step = -step/2
}
else {
max = i
if (step > 0)
step = -step/2
}
}
return min
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment