Power Grid Resource Costs
Python 3, 71 69 bytes
Thanks to @xnor for -2 bytes
f=lambda r,a,b:b and[8-int(~-a/3),max(18-2*a,13-a)][r>2]+f(r,a-1,b-1)
A function that takes input via argument of the zero-indexed resource type r
, the amount available a
and the amount to buy b
, and returns the cost.
This makes use of the fact that True
and False
equate to 1
and 0
in Python, allowing the use of Boolean expressions to index into lists.
How it works
f=lambda r,a,b Function with input resource type r, amount available a and amount
to buy b
b and... Base case: return 0 if b=0
[8-int(~-a/3),...][r>2] If not uranium, yield the unit cost 8-floor((a-1)/3)...
max(18-2*a,13-a) ..else yield the current uranium unit cost
...f(r,a-1,b-1) Decrement a and b, then pass to function
...+... Add the cost of each unit to give the total cost
:... Return the above
Try it on Ideone
Javascript (ES6), 71 59 bytes
f=(t,m,b)=>b&&(t>2?m>4?13-m:18-m*2:9+~(~-m/3))+f(t,m-1,b-1)
Takes type
, market_amount
and buy_amount
as arguments. type
is an integer between 0 and 3.
Demo
f=(t,m,b)=>b&&(t>2?m>4?13-m:18-m*2:9+~(~-m/3))+f(t,m-1,b-1)
function run() { var tests = document.getElementById("tests").value.split("\n"), test, C = 0, O = 1, G = 2, U = 3; console.clear(); for (var test of tests) { console.log(test); console.log("> " + eval(test)); } }
<textarea rows="10" id="tests">f(C, 24, 4) f(C, 20, 4) f(O, 3, 3) f(U, 1, 1) f(C, 1, 1) f(G, 0, 0) f(O, 10, 7) f(U, 12, 4) f(G, 11, 4)</textarea><br/><button onclick="run()">Run</button>
Befunge, 142 bytes
&2`#v_&&>:!#v_\:1-3/8\-v
v:&&< ^-1\ -1p15+g15 <
v>#<v <
! v5<
# 1:
>^g-
| 81
\ 4\
: *-
4 -1
` .p
# @^15+g15<
>:49+\- ^
|
>:2*92*\- ^
Try it here! Takes input as 3 integers, where the resource type is 0,1,2,3. Output is an integer.
No idea if this can be golfed any better. There's not that much whitespace, but the newlines probably hurt.