Created
January 14, 2013 17:51
-
-
Save ryangreenberg/4531891 to your computer and use it in GitHub Desktop.
Verify the checksum of a Chilean RUT. See http://en.wikipedia.org/wiki/National_identification_number#Chile.
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
class Rut(id: String, checksumDigit: String) { | |
def checksum: String = { | |
val digits = id.map(_.toString.toInt) | |
val digitsWithMultipliers = digits.zip( | |
Rut.ChecksumMultipliers.drop(Rut.ChecksumMultipliers.size - digits.size) | |
) | |
val productSum = digitsWithMultipliers.foldLeft(0)( | |
(acc, multipliers) => acc + multipliers._1 * multipliers._2 | |
) | |
(11 - productSum % 11) match { | |
case 11 => "0" | |
case 10 => "K" | |
case i => i.toString | |
} | |
} | |
def isValid = checksumDigit == checksum | |
override def toString = id + "-" + checksumDigit | |
} | |
object Rut { | |
val ChecksumMultipliers = Seq(3, 2, 7, 6, 5, 4, 3, 2) | |
val invalidRutChars = "[^0-9K]".r | |
def apply(id: String) = { | |
val strippedId = invalidRutChars.replaceAllIn(id, "") | |
new Rut(strippedId.take(strippedId.size - 1), strippedId.last.toString) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment