Created
January 13, 2015 12:21
-
-
Save soarez/c508ff9a7a97a507ec52 to your computer and use it in GitHub Desktop.
challenge.erl
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-module(challenge). | |
-export([ swap/3 ]). | |
% no effect on an empty list | |
swap([ ], _, _) -> [ ]; | |
% no effect on a list with a single item | |
swap([ H | [] ], _, _) -> [ H ]; | |
% no effect when both indexes are the same | |
swap(List, X, X) -> List; | |
swap([ H | T ], 0, IndexB) -> [ find(T, IndexB - 1) | replace(T, IndexB - 1, H) ]; | |
swap([ H | T ], IndexA, 0) -> [ find(T, IndexA - 1) | replace(T, IndexA - 1, H) ]; | |
swap([ H | T ], IndexA, IndexB) -> | |
[ H | swap(T, IndexA - 1, IndexB -1) ]. | |
% returns an element from a a list at Index | |
find([ ], _) -> error(badIndex); | |
find([ H | _ ], 0) -> H; | |
find([ _ | T ], Index) -> find(T, Index - 1). | |
% returns a list with the element at Index replaced by New | |
replace([ ], _, _) -> error(badIndex); | |
replace([ _ | T ], 0, New) -> [ New | T ]; | |
replace([ H | T ], Index, New) -> [ H | replace(T, Index - 1, New) ]. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Elixir -> https://gist.github.com/tdantas/417d172ad8c10d5cec7a