Skip to content

Instantly share code, notes, and snippets.

@raphaeladrien
Last active February 7, 2018 14:58
Show Gist options
  • Save raphaeladrien/2e00fa42fab9ebe16d10d51b1b11ea89 to your computer and use it in GitHub Desktop.
Save raphaeladrien/2e00fa42fab9ebe16d10d51b1b11ea89 to your computer and use it in GitHub Desktop.
fun main(args: Array<String>) {
if(isValid(args[0])) {
println("Thanks, the CPF informed is valid")
} else {
println("Please, inform a valid CPF.")
}
}
fun isValid(cpf: String): Boolean {
val formattedCPF = cpf.replace(".", "").replace("-", "")
if(basicValidation(formattedCPF)) return false
val nineDigits = formattedCPF.substring(0,9)
val digitOne = calcDigit(nineDigits, 10)
val digitTwo = calcDigit(nineDigits.plus(digitOne), 11)
return cpf == nineDigits.plus(digitOne).plus(digitTwo)
}
private fun basicValidation(cpf: String) = cpf.length != 11 || !cpf.isNumeric() || cpf.allCharacterIsEquals()
private fun calcDigit(numbers: String, weight: Int): Int {
var sum = 0
for(i in 0..(numbers.length-1)) {
sum += numbers[i].toString().toInt() * (weight-i)
}
sum = 11 - sum % 11
return if (sum > 9) 0 else sum
}
private fun String.allCharacterIsEquals(): Boolean {
for(char in this) {
if(char != this[0]) {
return false
}
}
return true
}
private fun String.isNumeric(): Boolean {
if (this.isEmpty()) {
return false
}
for (char in this) {
if (!char.isDigit()) return false
}
return true
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment