Skip to content

Instantly share code, notes, and snippets.

@leikind
Created Oct 31, 2011
Embed
What would you like to do?
-module(route).
-compile(export_all).
main(Filename) ->
% Filename = "road.txt",
{ok, Binary} = file:read_file(Filename),
NumberList = parse_input(Binary),
RouteTuples = lists:reverse(split_by_three(NumberList, [])),
Optimal = calculate_route(RouteTuples),
io:format("~p~n",[Optimal]),
erlang:halt().
parse_input(Input) when is_binary(Input) -> parse_input(binary_to_list(Input));
parse_input(Input) when is_list(Input) -> [ list_to_integer(X) || X <- string:tokens(Input, "\r\n\t") ].
split_by_three([], Acc) -> Acc;
split_by_three([A,B,C|Tail], Acc) -> split_by_three(Tail, [{A,B,C}|Acc]).
test() -> calculate_route([{50, 10, 30}, {5, 90, 20}, {40, 2, 25}, { 10, 8, 0}]).
calculate_route(List) -> {R1, _} = lists:foldl(fun step/2,{{0, []}, {0, []}}, List), R1.
step({A, B, X}, {{Acost, Astory}, {Bcost, Bstory}}) ->
{
pick_route(Bcost, Acost, B, A, X, Bstory, Astory, a, b),
pick_route(Acost, Bcost, A, B, X, Astory, Bstory, b, a)
}.
pick_route(FarthestPointPreviousCost, ClosestPointPreviousCost,
LongestRoute1, ShortestRoute, LongestRoute2,
StoryOfFarthestPoint, StoryOfClosestPoint,
ShortestRouteName, LongestRouteName) ->
NewShortestRoute = ClosestPointPreviousCost + ShortestRoute,
NewLongestRoute = FarthestPointPreviousCost + LongestRoute1 + LongestRoute2,
case NewShortestRoute > NewLongestRoute of
true -> {NewLongestRoute, [ {x, LongestRoute2}, {LongestRouteName, LongestRoute1} |StoryOfFarthestPoint]};
_ -> {NewShortestRoute, [{ShortestRouteName, ShortestRoute}|StoryOfClosestPoint]}
end.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment