Skip to content

Instantly share code, notes, and snippets.

@benwilson512
Last active May 22, 2020 19:32
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 benwilson512/b97ee453f417f04213faaceae46379c9 to your computer and use it in GitHub Desktop.
Save benwilson512/b97ee453f417f04213faaceae46379c9 to your computer and use it in GitHub Desktop.
non_repeating.ex
defmodule NonRepeating do
# convert a string into a list of chars
def find(string) when is_binary(string) do
string
|> to_charlist
|> find
end
# If we have an empty char list, nothing to do
def find(''), do: nil
# Otherwise, grab the first character from
# the list, and let's ignore repetitions of it.
def find([char | rest]) do
ignore(rest, char)
end
# The first char in the string matches the one we're ignoring
# so we can ignore it and keep going forward
def ignore([char | rest], char) do
ignore(rest, char)
end
# The first char does NOT match the one we're ignoring, but it DOES
# match the char after it, so we know it also repeats, let's ignore
# it now
def ignore([char, char | rest], _) do
ignore(rest, char)
end
# None of the previous things were true, so we know we've found
# a non repeating char, and we're done
def ignore([char | _], _) do
[char]
end
# All characters repeated, we got to the end of the string
def ignore('', _) do
nil
end
end
NonRepeating.find("aabbbccdee")
NonRepeating.find("aaaa")
defmodule NonRepeating do
# If we have an empty string, nothing to do
def find(""), do: nil
# Otherwise, grab the first character from
# the string, and let's ignore repetitions of it.
def find(<<char::utf8, rest::binary>>) do
ignore(rest, char)
end
# The first char in the string matches the one we're ignoring
# so we can ignore it and keep going forward
def ignore(<<char::utf8, rest::binary>>, char) do
ignore(rest, char)
end
# The first char does NOT match the one we're ignoring, but it DOES
# match the char after it, so we know it also repeats, let's ignore
# it now
def ignore(<<char::utf8, char::utf8, rest::binary>>, _) do
ignore(rest, char)
end
# None of the previous things were true, so we know we've found
# a non repeating char, and we're done
def ignore(<<char::utf8, _::binary>>, _) do
<<char::utf8>>
end
# All characters repeated, we got to the end of the string
def ignore(<<>>, _) do
nil
end
end
NonRepeating.find("aabbbccdee")
NonRepeating.find("aaaa")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment