Created
April 28, 2020 08:02
-
-
Save KouroshAlinaghi/c25a7c04a2317083c2bb6345a19543f3 to your computer and use it in GitHub Desktop.
A Very Small Program To Verify Iranian National Code.
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
defmodule CodeVerifier do | |
@moduledoc """ | |
A Very Small Program To Verify Iranian National Code | |
""" | |
@doc """ | |
## Examples | |
Srting -> Boolean | |
iex> CodeVerifier.is_a_valid_code?("7731689951") | |
false | |
""" | |
def is_a_valid_code?(code) do | |
code_map = push_to_map(Map.new(), code, 0) | |
sum = | |
Enum.map(code_map, fn {index_number, item} -> | |
{n, _} = Integer.parse(item) | |
n * index_number | |
end) | |
|> Enum.sum() | |
{n, _} = code_map[1] |> Integer.parse() | |
remaining = rem(sum - n, 11) | |
if (remaining < 2 && n == remaining) || n == 11 - remaining do | |
true | |
else | |
false | |
end | |
end | |
defp push_to_map(code_map, _code, 10), do: code_map | |
defp push_to_map(code_map, code, i) do | |
push_to_map( | |
Map.put(code_map, | |
10 - i, | |
code |> String.codepoints() |> List.to_tuple() |> elem(i) | |
), | |
code, | |
i + 1 | |
) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment