Created
June 21, 2013 19:44
-
-
Save pragdave/5833805 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 CheckDigit do | |
import Enum | |
@doc """ | |
Determine if a sequence of digits is valid, assuming the last digit is | |
a Luhn checksum. (http://en.wikipedia.org/wiki/Luhn_algorithm) | |
""" | |
def valid?(numbers) when is_list(numbers) do | |
numbers | |
|> reverse | |
|> map(&1 - ?0) | |
|> sum | |
|> rem(10) == 0 | |
end | |
defp sum(digits), do: _sum(digits, 0) | |
defp _sum([], acc), do: acc | |
defp _sum([odd], acc), do: acc + odd | |
defp _sum([odd, even | tail], acc) do | |
even = even * 2 | |
if even >= 10 do | |
even = even - 10 + 1 | |
end | |
sum(tail) + odd + even | |
end | |
end | |
IO.puts CheckDigit.valid? '79927398713' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment