The third of my Programming Challenges solutions is for The Trip 110103
This problem is great for making you think. Key points are; you cannot have half cents, and you have to find the minimum money needed to balance costs to within one cent.
Here is my solution in Erlang:
-module(thetrip).
-export([thetrip/1, test/0]).
average([H|T], Sum, Len) ->
average(T, Sum+H, Len+1);
average([], Sum, Len) ->
[Sum div Len , (Sum rem Len) > 0].
diff([H|T], Sum, Avg, Odd) when H > Avg, Odd ->
diff(T, Sum + H - Avg - 1, Avg, Odd);
diff([H|T], Sum, Avg, Odd) when H > Avg ->
diff(T, Sum + H - Avg, Avg, Odd);
diff([_|T], Sum, Avg, Odd) ->
diff(T, Sum, Avg, Odd);
diff([], Sum, _, _ ) ->
Sum.
thetrip(List) ->
Scaledup = [ trunc( X * 100 ) || X <- List],
[Avg, Odd] = average(Scaledup, 0, 0),
Diff = diff(Scaledup, 0, Avg, Odd ) / 100,
io:format("$~.2f~n",[Diff]),
Diff.
test() ->
10.00 = thetrip([10.00, 20.00, 30.00]),
11.99 = thetrip([15.00, 15.01, 3.00, 3.01]),
14.39 = thetrip([15.00, 15.01, 3.00, 3.01, 3.01]),
19.57 = thetrip([15.00, 15.01, 3.00, 3.01, 3.02, 3.03, 3.04, 3.05, 3.06, 3.07, 3.08]),
true.
I really enjoyed getting my head around guard sequences and using local variables to space the code out.