Validate International Securities Identification Number: Difference between revisions

Content added Content deleted
(Update to *modern* C#)
Line 539: Line 539:
</lang>
</lang>
=={{header|C#|C sharp}}==
=={{header|C#|C sharp}}==
{
{{trans|Java}}
<lang csharp>using System;
<lang csharp>using System;
using System.Text;
using System.Linq;
using System.Text.RegularExpressions;
using System.Text.RegularExpressions;


namespace Validate_ISIN {
namespace Validate_ISIN
{
class Program {
static int DigitValue(char c, int b) {
public static class IsinValidator
{
if (c >= '0' && c <= '9') {
public static bool IsValidIsin(string isin) =>
return c - '0';
IsinRegex.IsMatch(isin) && LuhnTest(Digitize(isin));
}
return c - 'A' + 10;
}


static int Digit(char c, int b) {
private static readonly Regex IsinRegex =
int result = DigitValue(c, b);
new Regex("^[A-Z]{2}[A-Z0-9]{9}\\d$", RegexOptions.Compiled);
if (result >= b) {
Console.Error.WriteLine("Invalid Number");
return -1;
}
return result;
}


static bool ISINtest(string isin) {
private static string Digitize(string isin) =>
isin = isin.Trim().ToUpper();
string.Join("", isin.Select(c => $"{DigitValue(c)}"));
Regex r = new Regex("^[A-Z]{2}[A-Z0-9]{9}\\d$");
if (!r.IsMatch(isin)) {
return false;
}


private static bool LuhnTest(string number) =>
StringBuilder sb = new StringBuilder();
number.Reverse().Select(DigitValue).Select(Summand).Sum() % 10 == 0;
foreach (char c in isin.Substring(0, 12)) {
sb.Append(Digit(c, 36));
}


private static int Summand(int digit, int i) =>
return LuhnTest(sb.ToString());
}
i % 2 == 0
? digit
: digit >= 5
? 2 * digit - 9
: 2 * digit;


static string ReverseString(string input) {
private static int DigitValue(char c) =>
char[] intermediate = input.ToCharArray();
c >= '0' && c <= '9'
Array.Reverse(intermediate);
? c - '0'
return new string(intermediate);
: c - 'A' + 10;
}
}

public class Program
static bool LuhnTest(string number) {
{
int s1 = 0;
int s2 = 0;
public static void Main(string[] args)
{
string reverse = ReverseString(number);
for (int i = 0; i < reverse.Length; i++) {
int digit = Digit(reverse[i], 10);
//This is for odd digits, they are 1-indexed in the algorithm.
if (i % 2 == 0) {
s1 += digit;
}
else { // Add 2 * digit for 0-4, add 2 * digit - 9 for 5-9.
s2 += 2 * digit;
if (digit >= 5) {
s2 -= 9;
}
}
}

return (s1 + s2) % 10 == 0;
}

static void Main(string[] args) {
string[] isins = {
string[] isins = {
"US0378331005",
"US0378331005",
Line 615: Line 587:
};
};
foreach (string isin in isins) {
foreach (string isin in isins) {
Console.WriteLine("{0} is {1}", isin, ISINtest(isin) ? "valid" : "not valid");
Console.WriteLine($"{isin} is {IsinValidator.IsValidIsin(isin) ? "valid" : "not valid"}");
}
}
}
}