Skip to content

Instantly share code, notes, and snippets.

@samsondav
Last active May 17, 2017 10:59
Show Gist options
  • Save samsondav/f36bbe7a18b0dc3255ab525ad486bd41 to your computer and use it in GitHub Desktop.
Save samsondav/f36bbe7a18b0dc3255ab525ad486bd41 to your computer and use it in GitHub Desktop.
Look and Say in Elixir
defmodule LookAndSay do
@moduledoc """
Documentation for LookAndSay.
"""
def main(args) do
number = hd args
IO.puts(look_and_say(number))
end
@spec look_and_say(String.t) :: String.t
def look_and_say(number) do
number
|> to_list_of_digits()
|> to_list_of_count_tuples()
|> Enum.reduce([], fn({count, digit}, acc) ->
["#{count}" <> digit | acc]
end)
|> Enum.join
end
defp to_list_of_digits(number) do
number
|> to_string
|> String.graphemes
end
defp to_list_of_count_tuples(digits) do
Enum.reduce(digits, [], fn(digit, acc) ->
case acc do
[{count, ^digit} | tl] -> [{count + 1, digit} | tl]
acc -> [{1, digit} | acc]
end
end)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment