Created
August 24, 2013 13:59
-
-
Save lowjoel/6328287 to your computer and use it in GitHub Desktop.
NUS Matriculation Number Checksum
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
function matric(noLetter) { | |
var type = noLetter.charAt(0); | |
if (type === 'U') { | |
type = 1; | |
var weights = [6, 11, 12, 10, 12, 0]; | |
} else if (type === 'A') { | |
type = 2; | |
var weights = [-1, -1, -1, -1, -1, -1]; | |
} else { | |
return undefined; | |
} | |
var values = []; | |
var matricInt = parseInt(noLetter.substr(1)); | |
for (var i = 1; i <= 6; ++i) { | |
values.push( | |
//Round down | |
Math.floor( | |
//Numeric part, divided by power of 10 | |
matricInt / Math.pow(10, i - 1)) % | |
//We want the last digit | |
10); | |
} | |
var checksum = 0; | |
var letters = ['B', 'A', 'E', 'H', 'J', 'L', 'M', 'N', 'R', 'U', 'W', 'X', 'Y']; | |
for (var i = 0, j = values.length; i < j; ++i) { | |
checksum += values[i] * weights[i]; | |
} | |
checksum = (checksum - 1) % letters.length; | |
if (checksum < 0) { | |
checksum += letters.length; | |
} | |
return letters[checksum]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment