Created
August 1, 2016 19:05
-
-
Save rbonvall/de604592e8e4a5e30098a199fdbed9b8 to your computer and use it in GitHub Desktop.
Dígito verificador del rut en Scala
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
val rut1 = 15666777 // - 3 | |
val rut2 = 23456789 // - 6 | |
val rut3 = 22333444 // - k | |
// 1 5 6 6 6 7 7 7 | |
// ...3 2 7 6 5 4 3 2 | |
// 3 10 42 36 30 28 21 14 → (+) → 184 | |
// -184 mod 11 = 3 | |
def digits(rut: Int): List[Int] = | |
rut.toString.toList.map(_.toString.toInt) | |
val integers = Stream.from(0) // 0, 1, 2, 3, 4, 5, 6, 7, 8, ... | |
val factors = integers.map(_ % 6 + 2) // 2, 3, 4, 5, 6, 7, 2, 3, 4, ... | |
implicit class IntOnSteroids(n: Int) { | |
def mod(d: Int) = ((n % d) + d) % d | |
} | |
def dv(rut: Int): Char = | |
-digits(rut).reverse.zip(factors).map { case (a, b) ⇒ a * b }.sum mod 11 match { | |
case 10 ⇒ 'k' | |
case d ⇒ d.toString.head | |
} | |
dv(rut1) // → '3' | |
dv(rut2) // → '6' | |
dv(rut3) // → 'k' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment