Skip to content

Instantly share code, notes, and snippets.

@mcelaney
Last active March 16, 2017 19:33
Show Gist options
  • Save mcelaney/ed48f15083dc2c2272e292a1942c43be to your computer and use it in GitHub Desktop.
Save mcelaney/ed48f15083dc2c2272e292a1942c43be to your computer and use it in GitHub Desktop.
PhillyDev Slack #DailyProgrammer March 16, 2017
defmodule Sorter do
@doc """
Takes a list and prints the list with the non zero index position before it was sorted.
## Example
iex> Sorter.sortit([34, 7, 38, 1])
"1 was in position 3"
"7 was in position 1"
"34 was in position 0"
"38 was in position 2"
:ok
"""
@spec sortit(list(pos_integer)) :: list(String.t)
def sortit(values) do
values
|> Enum.with_index
|> Enum.map(fn({value, key}) -> {value, "#{value} was in position #{key + 1}"} end)
|> Enum.sort_by(fn({value, _}) -> value end)
|> Enum.each(fn({_, message}) -> IO.inspect message end)
end
end
defmodule FasterSorter do
@doc """
Takes a list and prints the list with the non zero index position before it was sorted.
## Example
iex> Sorter.sortit([34, 7, 38, 1])
"1 was in position 3"
"7 was in position 1"
"34 was in position 0"
"38 was in position 2"
:ok
"""
@spec sortit(list(pos_integer)) :: list(String.t)
def sortit(values, position \\ 1) do
values
|> sortit(%{}, 1)
|> Enum.each(fn({_, value}) -> IO.inspect(value) end)
end
def sortit([], acc, _), do: acc
def sortit([head|tail], acc, position) do
sortit(
tail,
Map.put(acc, head, "#{head} was in position #{position}"),
position + 1
)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment