JavaScript (Node.js), 253 bytes
Saved 1 byte thanks to @MatthewJensen
Expects a string in upper case. Returns an array of 2 characters.
s=>["TKKYKGPR"[i="ATFCOMCYMMYTPRKSGSSPMSRBALAATABLRBENBIHMACESTGNBIRLISRSVNUKR".search(s)/3]||s[0],"FMYTPSMSXQYJAOEWELIA"[i]||s[2-Buffer(`Z&:^*Wf&*/1*EKe'(1#/.534aq>HI*"#0551(C=J@75%,.I>"!G0"2#1)%)(2p#/4@!&<`).every(n=>q-=n-32,q=parseInt(s,36)*5%1601)]]
Or 250 bytes with unprintable characters:
How?
Groups
We categorize the Alpha-2 codes into 4 groups:
- Codes made of the first two letters of the Alpha-3 code, e.g.
AFG
→AF
(156 entries). - Codes made of the 1st and last letters of the Alpha-3 code, e.g.
ATG
→AG
(71 entries). - Other codes whose 1st letter is the 1st letter of the Alpha-3 code, e.g.
UKR
→UA
(12 entries). - Codes whose 1st letter is not the 1st letter of the Alpha-3 code, e.g.
CYM
→KY
(8 entries).
Initial lookup
We first test whether the input belongs to either group 3 or group 4 by looking for its position i
into the following lookup string (without the spaces), divided by 3:
ATF COM CYM MYT PRK SGS SPM SRB ALA ATA BLR BEN BIH MAC EST GNB IRL ISR SVN UKR
\_____________________________/ \_____________________________________________/
group 4 group 3
First letter
For the first letter, we attempt to get:
"TKKYKGPR"[i] // lookup string for group 4
If this is undefined, we use the first letter of the input.
Second letter
For the second letter, we attempt to get:
"FMYTPSMSXQYJAOEWELIA"[i] // lookup string for groups 4 and 3
If this is undefined, we need to figure out whether we should use the 2nd or 3rd letter of the input.
We apply the following hash function to the input string:
q = parseInt(s, 36) * 5 % 1601
and test whether we can reach exactly \$0\$ by subtracting the ASCII codes minus \$32\$ of the corresponding data string from q
:
`Z&:^*Wf&*/1*EKe'(1#/.534aq>HI*"#0551(C=J@75%,.I>"!G0"2#1)%)(2p#/4@!&<`
This is encoding the entries that belong to group 2.
For instance, parseInt("JAM", 36)
is \$25006\$, which leads to:
$$q=(25006\times 5)\bmod 1601=125030\bmod 1601=152$$
Using the first four characters Z&:^
of the data string, we find out that this is the sum of:
$$\operatorname{ord}(\text{"Z"})-32+\operatorname{ord}(\text{"&"})-32+\operatorname{ord}(\text{":"})-32+\operatorname{ord}(\text{"^"})-32\\=58+6+26+62$$
which means that "JAM"
belongs to group 2 and the correct answer is "JM"
.