Tuesday, May 31, 2011

Norwegian SSN validator

The Norwegian social security number consist of the birthday, then three digits with information about gender an century. The two last digits are checksums. Total 11 digits.

Can you do a validation of this using only two lines of code? Sure :D


public bool IsValid(string ssn)
{
var input = ssn.Select(x => x - '0').ToArray();
return (new[] {
new[] {3, 7, 6, 1, 8, 9, 4, 5, 2},
new[] {5, 4, 3, 2, 7, 6, 5, 4, 3, 2} })
.Select(x => new
{
Last = input[x.Length],
Check = x.Select((t, i) => input[i] * t).Sum() % 11 })
.All(z => (z.Last == (11 - z.Check) % 10)
|| (z.Last == 0 && z.Check == 0));
}


Specification: http://no.wikipedia.org/wiki/Fødselsnummer

No comments:

Post a Comment