How to resolve the algorithm Validate International Securities Identification Number step by step in the Nim 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 Nim 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 Nim programming language
Source code in the nim programming language
import strformat
const
DigitRange = '0'..'9'
UpperCaseRange = 'A'..'Z'
type ISINError = object of ValueError
proc luhn(s: string): bool =
const m = [0, 2, 4, 6, 8, 1, 3, 5, 7, 9]
var sum = 0
var odd = true
for i in countdown(s.high, 0):
let digit = ord(s[i]) - ord('0')
sum += (if odd: digit else: m[digit])
odd = not odd
result = sum mod 10 == 0
proc validateISIN(s: string) =
if s.len != 12:
raise newException(ISINError, "wrong length")
if s[0] notin UpperCaseRange or s[1] notin UpperCaseRange:
raise newException(ISINError, "wrong country code")
if s[11] notin DigitRange:
raise newException(ISINError, "wrong checksum character")
var t: string
for ch in s:
case ch
of '0'..'9': t.add ch
of 'A'..'Z': t.addInt ord(ch) - ord('A') + 10
else: raise newException(ISINError, "invalid characters in code")
if not t.luhn():
raise newException(ISINError, "checksum error")
when isMainModule:
for isin in ["US0378331005", "US0373831005", "U50378331005",
"US03378331005", "AU0000XVGZA3", "AU0000VXGZA3", "FR0000988040"]:
try:
isin.validateISIN()
echo &"{isin} is valid."
except ISINError:
echo &"{isin} is not valid: {getCurrentExceptionMsg()}."
You may also check:How to resolve the algorithm Compiler/AST interpreter step by step in the Perl programming language
You may also check:How to resolve the algorithm Loops/N plus one half step by step in the Icon and Unicon programming language
You may also check:How to resolve the algorithm Concurrent computing step by step in the Scheme programming language
You may also check:How to resolve the algorithm Call a function step by step in the C++ programming language
You may also check:How to resolve the algorithm A+B step by step in the 11l programming language