Skip to content

Instantly share code, notes, and snippets.

@vegaasen
Last active March 5, 2018 08:21
Show Gist options
  • Save vegaasen/dcc2ad31c0c733dc6a683da66b558ea5 to your computer and use it in GitHub Desktop.
Save vegaasen/dcc2ad31c0c733dc6a683da66b558ea5 to your computer and use it in GitHub Desktop.
Norwegian SSN gender localizer thingie (personnummer)
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Optional;
/**
* @author <a href="mailto:[email protected]">vegaasen</a>
*/
public class SocialSecurityNumberGender {
public static void main(String... args) {
System.out.println(gender("01017047066"));
}
private static Gender gender(String candidate) {
return Optional.ofNullable(candidate).map(ssn -> {
if (ssn.length() != 11) throw new IllegalArgumentException("Too short");
LocalDate.parse((ssn.charAt(0) <= '3') ? ssn.substring(0, 6) : ((ssn.charAt(0) - '4') + ssn.substring(1, 5)), DateTimeFormatter.ofPattern("ddMMyy"));
int[] n = new int[11];
for (int i = 0; i < 11; i++) {
int tmp2 = Integer.parseInt(String.valueOf(ssn.charAt(i)));
if (tmp2 >= 0) {
n[i] = tmp2;
} else {
throw new IllegalArgumentException("Invalid characters");
}
}
int k1 = 11 - (3 * n[0] + 7 * n[1] + 6 * n[2] + n[3] + 8 * n[4] + 9 * n[5] + 4 * n[6] + 5 * n[7] + 2 * n[8]) % 11;
if (k1 == 11) k1 = 0;
if (k1 == 10 || k1 != n[9]) throw new IllegalArgumentException("First control number invalid");
int k2 = 11 - (5 * n[0] + 4 * n[1] + 3 * n[2] + 2 * n[3] + 7 * n[4] + 6 * n[5] + 5 * n[6] + 4 * n[7] + 3 * n[8] + 2 * k1) % 11;
if (k2 == 11) k2 = 0;
if (k2 == 10 || k2 != n[10]) throw new IllegalArgumentException("Second control number invalid");
return (n[8] % 2) == 0 ? Gender.Female : Gender.Male;
}).orElse(Gender.Unknown);
}
public enum Gender {
Female, Male, Unknown
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment