Created
July 19, 2009 18:12
-
-
Save JeremySkinner/149990 to your computer and use it in GitHub Desktop.
Validating a UCI: with or without linq
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Using linq | |
private bool HasCorrectCheckDigit(string uci) { | |
const string checkDigits = "ABCDEFGHKLMRTVWXY"; | |
try { | |
int remainder = uci.Substring(0, 12) | |
.Aggregate(Pair.Create(0, 0), (progress, character) => { | |
int multiplier = 16 - progress.Second; | |
int value = Convert.ToInt32(uci[progress.Second].ToString()) * multiplier; | |
return Pair.Create(progress.First + value, progress.Second + 1); | |
}, x => x.First % 17); | |
return checkDigits[remainder] == uci[12]; | |
} | |
catch { | |
return false; | |
} | |
} | |
//Using a good old for-loop | |
private bool HasCorrectCheckDigit(string uci) { | |
const string checkDigits = "ABCDEFGHKLMRTVWXY"; | |
try { | |
int total = 0; | |
for (int i = 0; i < 12; i++) { | |
int multiplier = 16 - i; | |
int value = Convert.ToInt32(uci[i].ToString()) * multiplier; | |
total += value; | |
} | |
int remainder = total % 17; | |
return checkDigits[remainder] == uci[12]; | |
} | |
catch { | |
return false; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment