How to resolve the algorithm Validate International Securities Identification Number step by step in the Scala programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Validate International Securities Identification Number step by step in the Scala programming language
Table of Contents
Problem Statement
An International Securities Identification Number (ISIN) is a unique international identifier for a financial security such as a stock or bond.
Write a function or program that takes a string as input, and checks whether it is a valid ISIN. It is only valid if it has the correct format, and the embedded checksum is correct. Demonstrate that your code passes the test-cases listed below.
The format of an ISIN is as follows:
For this task, you may assume that any 2-character alphabetic sequence is a valid country code. The checksum can be validated as follows:
(The comments are just informational. Your function should simply return a Boolean result. See #Raku for a reference solution.)
Related task:
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Validate International Securities Identification Number step by step in the Scala programming language
Source code in the scala programming language
object Isin extends App {
val isins = Seq("US0378331005", "US0373831005", "U50378331005",
"US03378331005", "AU0000XVGZA3","AU0000VXGZA3", "FR0000988040")
private def ISINtest(isin: String): Boolean = {
val isin0 = isin.trim.toUpperCase
def luhnTestS(number: String): Boolean = {
def luhnTestN(digits: Seq[Int]): Boolean = {
def checksum(digits: Seq[Int]): Int = {
digits.reverse.zipWithIndex
.foldLeft(0) {
case (sum, (digit, i)) =>
if (i % 2 == 0) sum + digit
else sum + (digit * 2) / 10 + (digit * 2) % 10
} % 10
}
checksum(digits) == 0
}
luhnTestN(number.map { c =>
assert(c.isDigit, s"$number has a non-digit error")
c.asDigit
})
}
if (!isin0.matches("^[A-Z]{2}[A-Z0-9]{9}\\d$")) false
else {
val sb = new StringBuilder
for (c <- isin0.substring(0, 12)) sb.append(Character.digit(c, 36))
luhnTestS(sb.toString)
}
}
isins.foreach(isin => println(f"$isin is ${if (ISINtest(isin)) "" else "not"}%s valid"))
}
You may also check:How to resolve the algorithm Motzkin numbers step by step in the Java programming language
You may also check:How to resolve the algorithm Munchausen numbers step by step in the Dc programming language
You may also check:How to resolve the algorithm Long year step by step in the Prolog programming language
You may also check:How to resolve the algorithm Jacobsthal numbers step by step in the Java programming language
You may also check:How to resolve the algorithm Morse code step by step in the Factor programming language