Skip to content

Instantly share code, notes, and snippets.

@modalsoul
Last active January 26, 2019 16:26
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 modalsoul/d8ef68c029ec52a723211b35884a9b82 to your computer and use it in GitHub Desktop.
Save modalsoul/d8ef68c029ec52a723211b35884a9b82 to your computer and use it in GitHub Desktop.
package com.github.modalsoul.luhn
object LuhnApp extends App {
// Success
println(Luhn.check("49927398716"))
// Failure
println(Luhn.check("49972398716"))
}
object Luhn {
def check(numbers:String):Boolean = check(numbers.map(_.asDigit))
def check(numbers:Seq[Int]):Boolean = {
val sum = numbers.reverse.zipWithIndex.map { case (n, index) =>
if((index)%2 == 1) n*2 else n
}.reduce{(z, n) =>
z + (if(n < 10) n else n%10 + n/10)
}
sum%10 == 0
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment