Skip to content

Instantly share code, notes, and snippets.

@Axrorxoja
Created January 28, 2021 12:10
Show Gist options
  • Save Axrorxoja/ecfc70fa7dfda89bb712ac1c83f582d2 to your computer and use it in GitHub Desktop.
Save Axrorxoja/ecfc70fa7dfda89bb712ac1c83f582d2 to your computer and use it in GitHub Desktop.
VinValidator2
object VinValidator2 {
private val values = intArrayOf(1, 2, 3, 4, 5, 6, 7, 8, 0, 1,
2, 3, 4, 5, 0, 7, 0, 9, 2, 3,
4, 5, 6, 7, 8, 9)
private val weights = intArrayOf(8, 7, 6, 5, 4, 3, 2, 10, 0, 9,
8, 7, 6, 5, 4, 3, 2)
fun isValid(vin: String): Boolean {
var s = vin
s = s.replace("-".toRegex(), "")
s = s.toUpperCase()
if (s.length != 17) return false
var sum = 0
for (i in 0..16) {
val c = s[i]
var value: Int
val weight = weights[i]
// letter
if (c in 'A'..'Z') {
value = values[c - 'A']
if (value == 0) return false
} else if (c in '0'..'9') value = c - '0' else return false
sum += weight * value
}
// check digit
sum %= 11
val check = s[8]
if (check != 'X' && (check < '0' || check > '9')) return false
return if (sum == 10 && check == 'X') true else sum == check - '0'
}
}
@Axrorxoja
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment