# The Trip – 110103 in Erlang

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.

## 5 thoughts on “The Trip – 110103 in Erlang”

1. Diego says:

Hey, is this program working??
Do you have it in C??

2. Simeon says:

Q1: Yes this program is correct, as it produces the same results as my C++ solution that passed the online judge. Also the code is doing the exact same thing as my C++ solution just in Erlang.

Q2: No not C but C++, very much C other than I use std::list, std::cin and std::cout instead of the CRT equivalents.

3. Manoj says:

Hey i solved the problem but my code is getting rejected .I am getting the same values as you are but still its getting rejected.Shall I mail you my code?

4. Simeon says:

Feel free to send me you code.