Created
June 25, 2019 14:20
-
-
Save biodunalfet/d11c1df5540cf5877c3c12fcdf5a9ce6 to your computer and use it in GitHub Desktop.
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
// https://www.codewars.com/kata/568e111353952f6c82000014 | |
fun main(args: Array<String>) { | |
// print(Character.getNumericValue('5')) | |
print(UPC("614141000030")) | |
} | |
fun UPC(s : String) : Boolean { | |
//calculate the odd sum | |
//calculate the even sum | |
//multiply odd sum by 3 to ge weighted odd sum | |
//add even sum + wieighted odd sum = weighted sum | |
//take rem = wightedsum % 10 | |
//if rem == 0, then 0 is our check digit | |
// else 10 - rem = check digit | |
//verigy check digit | |
//if it's the same as that in the UPC and 12 digits then it's valid | |
if (s.length != 12) { | |
return false | |
} | |
else { | |
val initialCheckDigit = s.last() | |
val oddSum = oddSum(s) | |
val evenSum = evenSum(s) | |
val weightedOddSum = weightedOddSum(oddSum) | |
val weightedSum = weightedOddSum + evenSum | |
val mod = weightedSum % 10 | |
val checkDigit = getCheckDigit(mod) | |
return checkDigit.toString() == initialCheckDigit.toString() | |
} | |
} | |
fun getCheckDigit(mod : Int) : Int { | |
return if (mod == 0) { | |
0 | |
} | |
else { | |
10 - mod | |
} | |
} | |
fun weightedOddSum(oddSum : Int) : Int { | |
return oddSum * 3 | |
} | |
fun oddSum(s: String) : Int { | |
//614141000036 | |
val sAsList = s.toCharArray().map { Character.getNumericValue(it) } | |
var sum = 0 | |
for (i in 0..11 step 2) { | |
sum += sAsList[i] | |
} | |
return sum | |
} | |
fun evenSum(s : String) : Int { | |
val trimmed = s.substring(0, s.length - 1) | |
val sAsList = trimmed.toCharArray().map { Character.getNumericValue(it) } | |
var sum = 0 | |
for (i in 1..10 step 2) { | |
sum += sAsList[i] | |
} | |
return sum | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment