Validate International Securities Identification Number: Difference between revisions
Content added Content deleted
(Added Algol W) |
(→{{header|Kotlin}}: Updated example see https://github.com/dkandalov/rosettacode-kotlin for details) |
||
Line 756: | Line 756: | ||
=={{header|Kotlin}}== |
=={{header|Kotlin}}== |
||
As the Luhn test method is only a few lines, it's reproduced here for convenience: |
As the Luhn test method is only a few lines, it's reproduced here for convenience: |
||
<lang scala>// version 1. |
<lang scala>// version 1.1 |
||
object Isin { |
object Isin { |
||
Line 762: | Line 762: | ||
fun isValid(s: String): Boolean { |
fun isValid(s: String): Boolean { |
||
// check format |
// check format |
||
if (!s.matches(r)) return false |
if (!s.matches(r)) return false |
||
// validate checksum |
// validate checksum |
||
Line 770: | Line 770: | ||
in '0'..'9' -> sb.append(c) |
in '0'..'9' -> sb.append(c) |
||
in 'A'..'Z' -> sb.append((c.toInt() - 55).toString().padStart(2, '0')) |
in 'A'..'Z' -> sb.append((c.toInt() - 55).toString().padStart(2, '0')) |
||
} |
} |
||
return luhn(sb.toString()) |
return luhn(sb.toString()) |
||
} |
} |
||
private fun luhn(s: String): Boolean { |
private fun luhn(s: String): Boolean { |
||
fun sumDigits(n : Int) = n / 10 + n % 10 |
fun sumDigits(n : Int) = n / 10 + n % 10 |
||
val t = s.reversed() |
val t = s.reversed() |
||
val s1 = t.filterIndexed { i, |
val s1 = t.filterIndexed { i, _ -> i % 2 == 0 }.sumBy { it - '0' } |
||
val s2 = t.filterIndexed { i, |
val s2 = t.filterIndexed { i, _ -> i % 2 == 1 }.map { sumDigits((it - '0') * 2) }.sum() |
||
return (s1 + s2) % 10 == 0 |
return (s1 + s2) % 10 == 0 |
||
} |
} |
||
Line 785: | Line 785: | ||
fun main(args: Array<String>) { |
fun main(args: Array<String>) { |
||
val isins = arrayOf("US0378331005", "US0373831005", "U50378331005", "US03378331005", |
val isins = arrayOf("US0378331005", "US0373831005", "U50378331005", "US03378331005", |
||
"AU0000XVGZA3", "AU0000VXGZA3", "FR0000988040") |
"AU0000XVGZA3", "AU0000VXGZA3", "FR0000988040") |
||
for (isin in isins) println("$isin\t -> ${if (Isin.isValid(isin)) "valid" else "not valid"}") |
for (isin in isins) println("$isin\t -> ${if (Isin.isValid(isin)) "valid" else "not valid"}") |
||
}</lang> |
}</lang> |