Validate International Securities Identification Number: Difference between revisions
Content added Content deleted
Langurmonkey (talk | contribs) |
(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. |
using System.Linq; |
||
using System.Text.RegularExpressions; |
using System.Text.RegularExpressions; |
||
namespace Validate_ISIN |
namespace Validate_ISIN |
||
{ |
|||
⚫ | |||
public static class IsinValidator |
|||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
private static readonly Regex IsinRegex = |
|||
new Regex("^[A-Z]{2}[A-Z0-9]{9}\\d$", RegexOptions.Compiled); |
|||
if (result >= b) { |
|||
Console.Error.WriteLine("Invalid Number"); |
|||
⚫ | |||
} |
|||
return result; |
|||
} |
|||
static |
private static string Digitize(string isin) => |
||
isin = |
string.Join("", isin.Select(c => $"{DigitValue(c)}")); |
||
Regex r = new Regex("^[A-Z]{2}[A-Z0-9]{9}\\d$"); |
|||
⚫ | |||
return false; |
|||
} |
|||
⚫ | |||
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 |
|||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
static |
private static int DigitValue(char c) => |
||
c >= '0' && c <= '9' |
|||
? c - '0' |
|||
: c - 'A' + 10; |
|||
} |
|||
⚫ | |||
⚫ | |||
{ |
|||
int s1 = 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; |
|||
} |
|||
⚫ | |||
string[] isins = { |
string[] isins = { |
||
"US0378331005", |
"US0378331005", |
||
Line 615: | Line 587: | ||
}; |
}; |
||
foreach (string isin in isins) { |
foreach (string isin in isins) { |
||
Console.WriteLine("{ |
Console.WriteLine($"{isin} is {IsinValidator.IsValidIsin(isin) ? "valid" : "not valid"}"); |
||
} |
} |
||
} |
} |