Skip to content

Instantly share code, notes, and snippets.

@henrik-ch
Created May 29, 2012 11:17
Show Gist options
  • Save henrik-ch/2827893 to your computer and use it in GitHub Desktop.
Save henrik-ch/2827893 to your computer and use it in GitHub Desktop.
solution to the heathrow route planning problem from learnyousomeerlang.com
-module(heathrow).
-compile([debug_info, export_all]).
mainFunc() ->
BottomGraphVal = {{0,[]},{0,[]}},
MoveCosts = [{50, 10, 30}, {5, 90, 20}, {40, 2, 25}, {10, 8,0}],
AccIn = {BottomGraphVal, [], []},
RetVal = lists:foldl( fun(X,Acc) ->
{AMove, BMove, XMove} = X,
{{{AVal,AMoves}, {BVal,BMoves}}, AMovesList, BMovesList} = Acc,
Res = calcNewSetAndMoves({{AVal, AMoves}, {BVal, BMoves}}, AMove, BMove, XMove),
{{NewASetVal, NewAMoves}, {NewBSetVal, NewBMoves}} = Res,
{{{NewASetVal, NewAMoves}, {NewBSetVal, NewBMoves}}, [lists:reverse(NewAMoves) | AMovesList], [lists:reverse(NewBMoves) | BMovesList]}
end, AccIn, MoveCosts),
{{{AVal, APath}, {BVal, BPath}}, _, _} = RetVal,
{{AVal, BVal}, lists:reverse(APath), lists:reverse(BPath)}.
calcNewSetAndMoves(CurValsMoves, AFwd, BFwd, XCross) ->
{{AVal, AMoves}, {BVal, BMoves}} = CurValsMoves,
ValToAStraightFromA = AVal + AFwd,
ValToACrossFromB = BVal + BFwd + XCross,
NewASetVal = erlang:min(ValToAStraightFromA, ValToACrossFromB),
NewAMoves =
if ValToAStraightFromA < ValToACrossFromB ->
[aFwd | AMoves];
true -> % works as an else branch
[xCross , bFwd | BMoves]
end,
%-------------------------
ValToBStraightFromB = BVal + BFwd,
ValToBCrossFromA = AVal + AFwd + XCross,
NewBSetVal = erlang:min(ValToBStraightFromB, ValToBCrossFromA),
NewBMoves =
if ValToBStraightFromB < ValToBCrossFromA ->
[bFwd | BMoves];
true -> % works as an else branch
[xCross, aFwd | AMoves]
end,
{{NewASetVal, NewAMoves}, {NewBSetVal, NewBMoves}}.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment