Skip to content

Instantly share code, notes, and snippets.

@brendanhay
Created September 29, 2011 12:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brendanhay/1250633 to your computer and use it in GitHub Desktop.
Save brendanhay/1250633 to your computer and use it in GitHub Desktop.
Order items according to another sorted array
-spec sort([integer()], [integer()]) -> {[integer()], [integer()]}.
sort([], _) -> {[], [0]};
sort(Stack, Stack) -> {Stack, [0]};
sort(Stack=[H|_], Order) ->
Length = length(Stack),
Last = lists:last(Stack),
Ops = case lists:max(Stack) of
H -> [Length];
Last -> [];
Max -> [position(Max, Stack), Length]
end,
{NewStack, CompletedOps} = flip(Ops, Stack),
sort(Length - 1, NewStack, Order, CompletedOps).
-spec sort(integer(), [integer()], [integer()], [integer()]) -> { [integer()], [integer()]}.
sort(_, [], _, Ops) -> {[], Ops};
sort(1, Stack, _, Ops) -> {Stack, Ops};
sort(_, Stack, Stack, Ops) -> {Stack, [0|Ops]};
sort(Iter, Stack, Order, Ops) ->
{NewStack, CompletedOps} = flip([position(Iter, Stack), Iter], Stack, Ops),
sort(Iter - 1, NewStack, Order, CompletedOps).
order = [3, 1, 2, 4, 5, 7, 6]
items = [{id: 1}, {id: 2}, {id: 3}, {id: 4}, {id: 5}, {id: 6}, {id: 7}]
order.map do |id|
items.find { |item| item[:id] == id }
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment