Created
December 25, 2018 14:50
-
-
Save smosko/35c11b25371bc3df260d5df9efe78aff to your computer and use it in GitHub Desktop.
Luhn algorithm
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
// https://en.wikipedia.org/wiki/Luhn_algorithm | |
func luhn(_ number: String) -> Bool { | |
return number.reversed().enumerated().map({ | |
let digit = Int(String($0.element))! | |
let even = $0.offset % 2 == 0 | |
return even ? digit : digit == 9 ? 9 : digit * 2 % 9 | |
}).reduce(0, +) % 10 == 0 | |
} | |
luhn("49927398716") // true | |
luhn("49927398717") // false |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment