Skip to content

Instantly share code, notes, and snippets.

@smosko
Created December 25, 2018 14:50
Show Gist options
  • Save smosko/35c11b25371bc3df260d5df9efe78aff to your computer and use it in GitHub Desktop.
Save smosko/35c11b25371bc3df260d5df9efe78aff to your computer and use it in GitHub Desktop.
Luhn algorithm
// 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