# Question
Title: Recognise Stack Exchange Sites by Their Icon
After spending a while on Stack Exchange, I can recognise most sites in the Hot Network Questions by their little icon (which is also their favicon), but certainly not all of them. Let's write a program which can! You're to write code which determines the site, given one of the (currently) 132 favicons, including Stack Overflow in Japanese (which is still in private beta):

I've uploaded a ZIP file with all these images as PNGs on GitHub. Click the "Raw" button to download it. The order of the above icons is the alphabetical order of the file names in the zip.

The corresponding site names (in this order) are:

```
Academia
Android Enthusiasts
Anime & Manga
Ask Different
Arduino
Ask Ubuntu
Astronomy
Aviation
Video Production
Beer
Bicycles
Biology
Bitcoin
Blender
Board & Card Games
Stack Overflow in Portuguese
LEGO Answers
Buddhism
Chemistry
Chess
Chinese Language
Christianity
Programming Puzzles & Code Golf
Code Review
Cognitive Sciences
Community Building
Seasoned Advice
Craft CMS
Cryptography
Computer Science
Theoretical Computer Science
Data Science
Database Administrators
Home Improvement
Drupal Answers
Signal Processing
Earth Science
Ebooks
Economics
Electrical Engineering
English Language Learners
Emacs
English Language & Usage
Expatriates
ExpressionEngine Answers
Physical Fitness
Freelancing
French Language
Game Development
Arqade
Gardening & Landscaping
Genealogy & Family History
German Language
Geographic Information Systems
Graphic Design
Amateur Radio
Biblical Hermeneutics
Hinduism
History
Homebrewing
History of Science and Math
Islam
Italian Language
Stack Overflow in Japanese
Japanese Language
Joomla
Mi Yodeya
Linguistics
Magento
Martial Arts
Mathematics
Mathematics Educators
Mathematica
MathOverflow
Motor Vehicle Maintenance & Repair
Meta Stack Exchange
Personal Finance & Money
Movies & TV
Music, Practice & Theory
Network Engineering
Open Data
The Great Outdoors
Parenting
Ask Patents
Pets
Philosophy
Photography
Physics
Project Management
Poker
Politics
Personal Productivity
Programmers
Puzzling
Quantitative Finance
Raspberry Pi
Reverse Engineering
Robotics
Role-playing Games
Russian Language
Salesforce
Computational Science
Science Fiction & Fantasy
Information Security
Server Fault
SharePoint
Skeptics
Software Recommendations
Sound Design
Space Exploration
Spanish Language
Sports
Software Quality Assurance & Testing
Stack Apps
Stack Overflow
Startups
Cross Validated
Super User
Sustainable Living
TeX - LaTeX
Tor
Travel
Tridion
Unix & Linux
User Experience
Web Applications
Webmasters
Windows Phone
WordPress Development
The Workplace
Worldbuilding
Writers
```

**Notes:**

* I've removed the `®` from `LEGO® Answers` and `ExpressionEngine® Answers`, so you don't have to worry about Unicode.
* I've used English names for the Stack Overflows in Japanese and Portuguese for the same reason.
* The icons of *Earth Science* and *Spanish Language* are indistinguishable. Therefore, given one of these icons, your code may return *either* of those sites (of your choosing). The same goes for *Magento* and *Martial Arts*.

## Rules

You may write a program or function which

* receives the (local) file name of the image via STDIN, command-line argument or function argument **or** receives the image file's contents via STDIN
* returns or prints to STDOUT the name of the site, as listed above.

Your code must recognise all 132 sites correctly (with the exception mentioned above).

You may not make any assumptions about the file name (like that it's called `codegolf.png`). You may assume that the image has dimensions 16x16, and that it will indeed be one of the 132 images above. The above images are all PNGs, but you may use any other convenient raster graphics format, but you'll have to convert the images yourself. You should not make any assumptions about the actual byte stream of the image file, other than that it's a valid image in whatever format you chose. In particular, if there are multiple ways to encode the same image in your format (e.g. by adding irrelevant fields to the header section), your code must work for all of them. In short, your code should only rely on the pixel values themselves, no details of the file encoding it.

As usual, you may not fetch any data from the internet. You have to determine the site from the image alone.

You may use built-in or third-party functions to read the image file and get a list of colour values, but you must not use any other existing image processing functions.

This is code golf, so the shortest answer (in bytes) wins.

# Answer
# Python 3.x + Pillow, ~~2301~~ ~~1894~~ 1878 bytes

```
import sys,re,zlib as z,base64,PIL.Image as i
print(re.search(str(z.adler32(i.open(sys.argv[1]).tobytes()[2::6])%2003)+'(\\D+)',z.decompress(base64.b85decode(b'c${Tc%XZ>86#NyfdNqBH<%b?iLI_EpFkwO-GfQC$tcfjoB$+h*^;0s?o$g*?uzgjxs%~BKif!C3zALZEU!&?wJd#-mqgS@p<P&+)AsV|c*52*C>U&(1_4w^urvvWJU8Bj;bvv4ia;eiJLu+bsXLru`DjH|W<`|;xLq++kv5k8VWZgQe*`_u+opEF8>A6qjM%k#skzbiuJ7dL_*><K@9l6!M*H(|w)PZJ2`RYy7K2VVrv+zc)&2Fc?wvh|^#ksyymE?D!Q$3!LbFX%h%vT%1#lr486Iybw?0!`H)ZlZ#XIao2uXTr}(IBl@wRWHa#})bgV);O3HoW7+T*!5M3=^mu6Ri$`7L;uUWj~gsqR6gQR9h7^nKdBIgy>ats36%|M|8p1x;32(ZfK9R5_xK5ts=Sz70c%SIK&g3N1E|sg{n3>JSbKwwhssGcb$8uMNw=Nv;f_;rj?}kz(3-&#FQw@O;q(8nGHjbrTC(NQv=ckXT|eHr|amahCq(7T6<LBTr5Gj>fHV~3DcYINN!Qr`6Dl?jT>!4u5~bb%Zi6VTax;%vg*m325J_$nEC%yqbbYeEp!K_K7k)W-XCP`6+}N7tktMVX+{@c2L&kLAc&IvspGrzZ$F`uOBg}fA3W2neAU}tg~<+iCN=<sR^Zke+9WNhnCyy6!8nfa>33&OWiPt2s=OMTrUgilSYQxrG!gziB!Aj83zX&6S|yjIQkA?iF0n%?<+B=%_D11aoCv?@Q&eei{sqNkr7RG`#*xyzSUE6BUNnZK)3|3Wls}K$qaKv;jOO#!{3Ms)4CQ?shafnAF^zVq(`K9o2xL5JoQoGea+W1$+xmw&8OMOtN1Pid6UAcd+*_bB6IY$KjrO=ac^tPv3(8O`&(agOBbT{Va6s}Rm9&`I#yivC;MhW8=n+^^&Reho;~!~W<xgH6bVq3^=H7)sUXV2nv~DP4`CY`f55i&qH)DvPMQy>)y*Z=|68w@v=#oo5^RSh5R2F%1-vt>h=|+1n0pE^Yq-72!)1+o{hD_3<Cyxpyr6r%cei-AFQ*h1seM$MP>ovLS2k#Ci$to#do$s3MXu2lZsw~9HkbjVWM@1!{w>}LWVj#j2qC(+*Okc>=<qcV}*}+U_QK+(ZZ(x>ZMdDDWtgHiBK+7p6aHHI`u-h6z7|Xm`>D1t4uEp271y7oCI^{1^H~O7QRxTA_U&92Q8z$J2O|5Lbeg_0umd^pSU<%-ki7LtDvo&AgIt0h~6(y@Hr+kyLJ$<B#07KdGob0EW$7@f{GszaUv#tkpSyk759Khmvq-aiyM-_&x_VCTx$Vy<;$<k{T$-@{Mhc<<%KD1AHK^MKkg%pYIW}SxhV?&a{o9=rs@*+hqyoioE=TF>9S<KxY+^69^OA0jkS#0!w@kw4}KTcP9#+PVW+qB|7B`Y?eRs+7}8RSAs?i?-Cz#Wp(Iihd`nI!Q_i%R^o_;fvDQ5|{Cr;yWeirL>_l#(wn)$QenJkK6Sgw)5NleBzvo&G#@>X`7Ib*aS4LHx9epI%BXXV&y7LJ&54g}D25-Q8>DZQ5hGKyIeJkQQu08%j|<x~)q(AOVw9P~Z*c0Z@VM6n#<}tBT6+T%4mZ9f*y76xlEFM~o$xr9*SZHd^6D-C!pkkp3m(-~W3&>KY@106L+;I><MJ^Dz`f{(I3i?u`2pWjUjlwZx`B1JB#h#u3xTH*b1K?TG40|4lxF1$_Pw+t?h2')).decode()).group(1))

```

---

The idea is hash the image and find the corresponding string from a dictionary (just like other answers).

The key code is this:

```
adler32(open(sys.argv[1]).tobytes()[2::6])%2003

```

We open the file, and then convert it into a 1024-byte string of RGBA values. With a bit of experimentation, we find that the ADLER-32 checksum of every sixth byte of this byte string is unique for these 132 images. And then further testing shows that, taking modulus of 2003 of the checksum gives the smallest dictionary.

The original dictionary looks like:

```
{
    3: 'Programming Puzzles & Code Golf',
    6: 'Science Fiction & Fantasy',
    7: 'Bitcoin',
    8: 'Biblical Hermeneutics',
    …,
    1969: 'Unix & Linux',
    1989: 'WordPress Development',
    1993: 'Cognitive Sciences',
    2001: 'Personal Productivity',
}

```

We noticed that all site names do not contain numbers. Therefore we could concatenate the whole dictionary into a single string:

```
"256Software Quality Assurance & Testing3Programming Puzzles & Code Golf1284Geographic Info…"

```

And then use the regex e.g. `1969(\D+)` to extract the site name. This huge string is then compressed to save space (let the compression engine notice the multiple occurrences of "Language"), and finally base-85 encoded.

---

Since it is now also tagged as , here a **2394-byte** solution that does not use compression (zlib is still imported for adler32).

```
import sys,re,zlib,PIL.Image as i
l=' Language'
s='Science'
print(re.search(str(zlib.adler32(i.open(sys.argv[1]).tobytes()[2::6])%2003)+'(\\D+)','256Software Quality Assurance & Testing3Programming Puzzles & Code Golf1284Geographic Information Systems517Windows Phone6'+s+' Fiction & Fantasy7Bitcoin8Biblical Hermeneutics1034Writers1803Ask Different781Joomla597Islam1809Craft CMS878English'+l+' & Usage431Freelancing1565Politics32LEGO Answers289Physical Fitness1316Spanish'+l+'1830Database Administrators296Pets1066Philosophy1582Ask Patents560Cryptography1073Magento1588MathOverflow1333Salesforce1591Linguistics1844Stack Apps948Japanese'+l+'572Electrical Engineering778Genealogy & Family History735Sound Design63Open Data505Tridion328Arqade1609Hinduism588Music, Practice & Theory1101Expatriates846Network Engineering79German'+l+'1104Webmasters1208Signal Processing118Puzzling867ExpressionEngine Answers654Buddhism1593Quantitative Finance1625Parenting859Biology1117Academia1118Stack Overflow353Project Management1123Motor Vehicle Maintenance & Repair612Chinese'+l+'876Startups877Video Production110Reverse Engineering701French'+l+'677Bicycles1683Ebooks1908Blender190Physics1654Beer119History of '+s+' and Math1913Android Enthusiasts634Chemistry1252Travel1148Cross Validated1662Italian'+l+'565Sustainable Living387Programmers797Arduino1932Data '+s+'141Server Fault1422Chess109Amateur Radio147Computational '+s+'917Home Improvement1599Worldbuilding1438Mi Yodeya197Christianity1185Community Building1956Aviation1701Poker1703Mathematics Educators1704SharePoint425Meta Stack Exchange171Code Review1964Game Development1967Homebrewing944User Experience1969Unix & Linux1715Board & Card Games1716Graphic Design969Tor696Economics955Drupal Answers1213Raspberry Pi958The Great Outdoors885Mathematics1731Emacs1989WordPress Development910Photography1736Space Exploration1993Cognitive '+s+'s1227Computer '+s+'1230Mathematica207Gardening & Landscaping2001Personal Productivity1235Super User1358Information Security727Theoretical Computer '+s+'1497Earth '+s+'220Russian'+l+'1914Role-playing Games1758Movies & TV479Anime & Manga67English'+l+' Learners228Web Applications485Robotics593The Workplace232Astronomy1519Personal Finance & Money808Stack Overflow in Japanese1266Seasoned Advice467Software Recommendations1012Sports332Stack Overflow in Portuguese761History763Ask Ubuntu1957Skeptics85TeX - LaTeX').group(1))

```
> 30 votes

# Answer
# C#, 2760 bytes

```
namespace System{class P{static void Main(){var c="us>g System;us>g System.Draw>g;class p{publ' stZ' void c(){var b=(Bitmap)Bitmap.FromFile(Console.ReadL>e());Console.Write(!1,1[3,3#2?!4,4#1?!5,5#2?!@#1?!+$SupK UsK*Salesforce%]^$< F't~_Fantasy%8,8#6?$Arqade*Ask Ubuntu%@#6?$WordPress Development%8,8#4?!9,9#2?$Phys's*UsK ExpKience%+$Travel*Craft CMS%5,5^!@#6?!]#1?$TeX - LaTeX%+$Mi Yodeya*Meta Stack Exchange%]#6?$ProgrammK|2,2#5?$Christianity*MZhemZ'a%@[]^$MZhemZ'|0,0#1?$Cross ValidZed*Theoret'al ComputK <%2,2^!]#5?$Seasoned Adv'e*Drupal AnswK|]^$Graph' Design*WebmastK|2,2^!4,4#5?!5,5#2?!@^$Ask PZents*Home Improvement%@#6?$Android Enthusiasts*Skept'|5,5#4?!@#5?$Web Appl'Z~s*English/_Usage%@#4?!]#8?$SharePo>t*B'ycle|]#1?$Electr'al Eng>eK>g*DZabase Adm>istrZor|4,4^!5,5#2?!+$Game Development*Photography%@:SKvK Fault%+$Geograph' InformZ~ Systems*Unix_L>ux%5,5^!0`Stack Apps*The Workplace%+!@[]#4?$InformZ~ Security*Ask DiffKent%]:Role-play>g Games*PKsonal F>ance_Money%3,9#8?$Academia%5,15^$& > Japanese%0,13:&*& > Portuguese%2,2:MZhOvKflow%3,3:AviZ~%4,4^$LEGO AnswK|5,5[@[][0,1:PokK*Anime_Manga%+$BlendK*H>duism%][8,8:WritK|0,1^!2`RaspbKry Pi*W>dows Phone%+$Biology*Worldbuild>g%9,9:Movies_TV%8,8[6`Trid~*Islam%0,1:Mus', Pract'e_Theory*L>guist'|][@[9,9:Ches|+!4,6:Garden>g_Landscap>g*Susta>able Liv>g%4,6:Buddhism*Startup|8,8:English/ LearnK|3,4[6,7:Network Eng>eK>g%9,5:Magento%+$Motor Veh'le Ma>tenance_Repair*MZhemZ's EducZor|4,8:GKman/%7`Joomla%7,6[+$QuantitZive F>ance*Ardu>o%9`Chemistry*Cryptography%8,8[0,1^!@[3`Tor%4,5:French/*The GreZ Outdoor|3`Project Management%3,6:Ch>ese/*Space ExplorZ~%+!2,6:Programm>g Puzzles_Code Golf%@:Cognitive <s*Signal Process>g%1,0:Ebook|@[4,5:Earth <*BeK%8,5:Emacs*ExpZriZe|1`History of < and MZh%3,4[@[+$Homebrew>g%3,6:DZa <*Video Product~%5,7:Russian/%9,4[4,8:Bibl'al HKmeneut's*Philosophy%11,6:Board_Card Games*Bitco>%3,5[@[3,8:AmZeur Radio%5,6:Genealogy_Family History%6,9:Software Quality Assurance_Test>g*Open DZa%3,6[11,7:Code Review%+$ComputK <*Community Build>g%10,6[+$Sports*Software RecommendZ~|9`Sound Design*ComputZ~al <%3,7:Japanese/%5,8[7,5:Puzzl>g%8,5:Econom's*Express~Eng>e AnswK|6,5[9,4[7`Freelanc>g*History%10,6:Italian/%6`Parent>g*Astronomy%6,7[9`RevKse Eng>eK>g*Robot'|10,8[+$Polit's*Pet|12,5:PKsonal Productivity*Phys'al Fitness$);}}";foreach(var s in "~ion;|s%;`,4:;&Stack OvKflow;_ & ;^#3?;]7,7;'ic;['!;Zat;Ker;@6,6;>in;<Science;:'$;/ Language;+0,0#3?;*$:$;'#7?;%$:!;$\";#).B%9<;!b.GetPixel(".Split(';'))c=c.Replace(s[0]+"",s.Substring(1));new Microsoft.CSharp.CSharpCodeProvider().CompileAssemblyFromSource(new CodeDom.Compiler.CompilerParameters("mscorlib.dll System.Core.dll System.Drawing.dll".Split()),c).CompiledAssembly.CreateInstance("p").GetType().GetMethod("c").Invoke(c,null);}}}

```

My solution doesn't use hashing, it actually examines the individual pixels of the image and decides based on that. I discovered that it was enough to examine the blue component of the image modulo 9. The idea is to repeatedly split based on the value of pixel.B%9, like so:

```
b.GetPixel(3,4).B % 9 < 7 ? "Russian Language" : (b.GetPixel(8,4).B % 9 < 6 ? "Project Management" : "Philosophy")

```

Using a script, I generated the following monstrous program (5197 bytes) that solves the problem using a binary decision tree:

```
using System;using System.Drawing;class p {public static void c(){var b=(Bitmap)Bitmap.FromFile(Console.ReadLine());Console.Write(b.GetPixel(4,5).B%9<6?b.GetPixel(1,1).B%9<5?b.GetPixel(1,10).B%9<1?b.GetPixel(3,4).B%9<1?b.GetPixel(2,8).B%9<2?b.GetPixel(0,0).B%9<3?b.GetPixel(3,10).B%9<8?"Super User":"Travel":b.GetPixel(0,2).B%9<3?"Salesforce":"Craft CMS":b.GetPixel(2,4).B%9<2?b.GetPixel(2,2).B%9<6?"Ask Ubuntu":"Ask Different":b.GetPixel(1,3).B%9<6?"Mathematics":"Programmers":b.GetPixel(2,7).B%9<3?b.GetPixel(2,4).B%9<1?b.GetPixel(2,8).B%9<2?"Database Administrators":"Christianity":b.GetPixel(0,1).B%9<3?"TeX - LaTeX":"Game Development":b.GetPixel(1,6).B%9<3?b.GetPixel(2,3).B%9<7?"English Language & Usage":"Skeptics":b.GetPixel(0,0).B%9<3?"StackApps":"Unix & Linux":b.GetPixel(0,6).B%9<1?b.GetPixel(1,4).B%9<2?b.GetPixel(1,5).B%9<3?b.GetPixel(0,4).B%9<1?"Arqade":"Mi Yodeya":b.GetPixel(1,6).B%9<6?"Drupal Answers":"User Experience":b.GetPixel(1,5).B%9<4?b.GetPixel(1,6).B%9<3?"SharePoint":"Bicycles":b.GetPixel(0,0).B%9<3?"Home Improvement":"Photography":b.GetPixel(0,0).B%9<3?b.GetPixel(0,7).B%9<2?b.GetPixel(0,1).B%9<1?"Science Fiction & Fantasy":"Theoretical Computer Science":b.GetPixel(0,4).B%9<2?"Android Enthusiasts":"Ask Patents":b.GetPixel(5,15).B%9<3?b.GetPixel(2,0).B%9<3?"Meta Stack Exchange":"Stack Overflow inJapanese":b.GetPixel(0,13).B%9<7?"Stack Overflow":"Stack Overflow in Portuguese":b.GetPixel(5,8).B%9<7?b.GetPixel(4,4).B%9<7?b.GetPixel(0,0).B%9<3?b.GetPixel(7,5).B%9<7?b.GetPixel(0,1).B%9<5?"German Language":"Server Fault":b.GetPixel(8,5).B%9<7?"Economics":"ExpressionEngine Answers":b.GetPixel(1,13).B%9<7?b.GetPixel(0,1).B%9<7?"Ebooks":"MathOverflow":b.GetPixel(7,5).B%9<7?"Buddhism":"Earth Science":b.GetPixel(6,6).B%9<7?b.GetPixel(4,6).B%9<7?b.GetPixel(3,6).B%9<7?"Poker":"Gardening & Landscaping":b.GetPixel(0,0).B%9<3?"Sustainable Living":"Startups":b.GetPixel(7,6).B%9<7?b.GetPixel(0,0).B%9<3?"Quantitative Finance":"Arduino":b.GetPixel(9,4).B%9<7?"Chemistry":"Cryptography":b.GetPixel(5,4).B%9<7?b.GetPixel(9,5).B%9<7?b.GetPixel(10,8).B%9<7?b.GetPixel(0,0).B%9<3?"Reverse Engineering":"Pets":b.GetPixel(12,5).B%9<7?"Personal Productivity":"Physical Fitness":b.GetPixel(6,7).B%9<7?b.GetPixel(3,4).B%9<7?"Tor":"Robotics":b.GetPixel(7,5).B%9<7?"Politics":"French Language":b.GetPixel(0,1).B%9<3?b.GetPixel(9,5).B%9<7?b.GetPixel(3,4).B%9<3?"LEGO Answers":"Magento":b.GetPixel(6,5).B%9<7?"Motor Vehicle Maintenance & Repair":"Network Engineering":b.GetPixel(2,6).B%9<7?b.GetPixel(0,0).B%9<7?"Programming Puzzles & Code Golf":"History of Science and Math":b.GetPixel(0,2).B%9<7?"Mathematics Educators":b.GetPixel(1,4).B%9<7?"Signal Processing":"Cognitive Sciences":b.GetPixel(3,6).B%9<7?b.GetPixel(4,6).B%9<5?b.GetPixel(5,8).B%9<5?b.GetPixel(6,5).B%9<7?b.GetPixel(9,8).B%9<7?b.GetPixel(1,1).B%9<7?"Geographic Information Systems":"Biblical Hermeneutics":b.GetPixel(11,6).B%9<7?"Board & Card Games":"Bitcoin":b.GetPixel(0,0).B%9<3?b.GetPixel(2,4).B%9<7?"RaspberryPi":"English Language Learners":b.GetPixel(8,5).B%9<7?"Emacs":"Expatriates":b.GetPixel(5,4).B%9<6?b.GetPixel(6,8).B%9<7?b.GetPixel(3,4).B%9<7?"Russian Language":"Amateur Radio":b.GetPixel(8,4).B%9<7?"Project Management":"Philosophy":b.GetPixel(0,7).B%9<7?b.GetPixel(1,1).B%9<7?"Cross Validated":"Homebrewing":b.GetPixel(0,1).B%9<7?"Web Applications":"Biology":b.GetPixel(3,4).B%9<7?b.GetPixel(0,2).B%9<3?b.GetPixel(1,7).B%9<6?b.GetPixel(1,6).B%9<6?"WordPress Development":"Electrical Engineering":b.GetPixel(1,1).B%9<7?"Physics":"Windows Phone":b.GetPixel(1,0).B%9<7?b.GetPixel(0,0).B%9<3?"Webmasters":"Academia":b.GetPixel(3,8).B%9<7?"Data Science":"Worldbuilding":b.GetPixel(6,6).B%9<7?b.GetPixel(5,6).B%9<7?b.GetPixel(0,1).B%9<7?"Genealogy & Family History":"Anime & Manga":b.GetPixel(6,9).B%9<7?"Software Quality Assurance & Testing":"Open Data":b.GetPixel(9,4).B%9<7?b.GetPixel(0,0).B%9<3?"Code Review":"Community Building":b.GetPixel(8,4).B%9<7?"Chinese Language":"Computer Science":b.GetPixel(5,6).B%9<6?b.GetPixel(4,4).B%9<7?b.GetPixel(9,8).B%9<7?b.GetPixel(10,6).B%9<7?b.GetPixel(0,0).B%9<3?"Sports":"Software Recommendations":b.GetPixel(1,1).B%9<7?"Information Security":"Sound Design":b.GetPixel(3,5).B%9<7?b.GetPixel(8,4).B%9<7?"Space Exploration":"Computational Science":b.GetPixel(0,0).B%9<3?"Tridion":"Puzzling":b.GetPixel(0,5).B%9<3?b.GetPixel(6,8).B%9<7?b.GetPixel(5,8).B%9<7?"Blender":"Writers":b.GetPixel(6,5).B%9<7?"Music, Practice & Theory":"Islam":b.GetPixel(0,1).B%9<3?b.GetPixel(0,4).B%9<7?"Mathematica":"The Workplace":b.GetPixel(0,0).B%9<3?"Linguistics":"Hinduism":b.GetPixel(6,4).B%9<5?b.GetPixel(9,8).B%9<7?b.GetPixel(3,7).B%9<7?b.GetPixel(0,0).B%9<3?"Japanese Language":"Aviation":b.GetPixel(7,6).B%9<7?"History":"Italian Language":b.GetPixel(9,4).B%9<7?b.GetPixel(5,3).B%9<7?"Chess":"Freelancing":b.GetPixel(0,0).B%9<3?"Parenting":"Beer":b.GetPixel(0,5).B%9<1?b.GetPixel(4,8).B%9<7?b.GetPixel(1,1).B%9<7?"Role-playing Games":"Movies & TV":b.GetPixel(6,8).B%9<7?"Astronomy":"The Great Outdoors":b.GetPixel(0,4).B%9<3?b.GetPixel(0,6).B%9<7?"SeasonedAdvice":"Personal Finance & Money":b.GetPixel(0,0).B%9<3?"Graphic Design":b.GetPixel(3,4).B%9<7?"Video Production":"Joomla");}}

```

Some people have used built-in compression functions in their solutions. I made my own, writing a script that identifies common substrings and replaces them by single-character shorthands. The code is compressed to the following 2502 bye string:

```
us@g System;us@g System.Draw@g;class p {publ| st^| void c(){var b=(Bitmap)Bitmap.FromFile(Console.ReadL@e());Console.Write(!4,5#6?!1,1#5?!1,10#1?!3`#1?!2,8#2?*!3,10#8?$Sup] Us]+Travel~0,2_$Salesforce+Craft CMS~2`#2?!2,2#6?$Ask Ubuntu+Ask Diff]ent~1,3#6?$M^hem^|s+Programm]s~2,7_!2`#1?!2,8#2?$D^abase Adm@istr^ors+Christianity~0,1_$TeX - LaTeX+Game Development~1,6_!2,3[English/:Usage+Skept|s'*$StackApps+Unix:L@ux~0,6#1?!1`#2?!1,5_!0`#1?$Arqade+Mi Yodeya~1,6#6?$Drupal Answ]s+Us] Exp]ience~1,5#4?!1,6_$SharePo@t+B|ycles'*$Home Improvement+Photography'*!0,7#2?!0,1#1?$> F|tion:Fantasy+Theoret|al Comput] >~0`#2?$Android Enthusiasts+Ask P^ents~5,15_!2,0_$Meta Stack Exchange+Stack Ov]flow @Japanese~0,13[Stack Ov]flow+Stack Ov]flow @ Portuguese~5,8<4`%*!7,5<0,1#5?$G]man/+S]v] Fault~8,5[Econom|s+ExpressionEng@e Answ]s~1,13<0,1[Ebooks+M^hOv]flow~7,5[Buddhism+Earth >~6,6<4,6<3,6[Pok]+Garden@g:Landscap@g'*$Susta@able Liv@g+Startups~7,6%*$Quantit^ive F@ance+Ardu@o~9`[Chemistry+Cryptography~5`<9,5<10,8%*$Rev]se Eng@e]@g+Pets~12,5[P]sonal Productivity+Phys|al Fitness~6,7<3`[Tor+Robot|s~7,5[Polit|s+French/~0,1_!9,5<3`_$LEGO Answ]s+Magento~6,5[Motor Veh|le Ma@tenance:Repair+Network Eng@e]@g~2,6<0,0[Programm@g Puzzles:Code Golf+History of > and M^h~0,2[M^hem^|s Educ^ors~1`[Signal Process@g+Cognitive >s~3,6<4,6#5?!5,8#5?!6,5<9,8<1,1[Geograph| Inform^ion Systems+Bibl|al H]meneut|s~11,6[Board:Card Games+Bitco@'*!2`[Raspb]ryPi+English/ Learn]s~8,5[Emacs+Exp^ri^es~5`#6?!6,8<3`[Russian/+Am^eur Radio~8`[Project Management+Philosophy~0,7<1,1[Cross Valid^ed+Homebrew@g~0,1[Web Appl|^ions+Biology~3`<0,2_!1,7#6?!1,6#6?$WordPress Development+Electr|al Eng@e]@g~1,1[Phys|s+W@dows Phone~1,0%*$Webmast]s+Academia~3,8[D^a >+Worldbuild@g~6,6<5,6<0,1[Genealogy:Family History+Anime:Manga~6,9[Software Quality Assurance:Test@g+Open D^a~9`%*$Code Review+Community Build@g~8`[Ch@ese/+Comput] >~5,6#6?!4`<9,8<10,6%*$Sports+Software Recommend^ions~1,1[Inform^ion Security+Sound Design~3,5<8`[Space Explor^ion+Comput^ional >'*$Tridion+Puzzl@g~0,5_!6,8<5,8[Blend]+Writ]s~6,5[Mus|, Pract|e:Theory+Islam~0,1_!0`[M^hem^|a+The Workplace'*$L@guist|s+H@duism~6`#5?!9,8<3,7%*$Japanese/+Avi^ion~7,6[History+Italian/~9`<5,3[Chess+Freelanc@g'*$Parent@g+Be]~0,5#1?!4,8<1,1[Role-play@g Games+Movies:TV~6,8[Astronomy+The Gre^ Outdoors~0`_!0,6[SeasonedAdv|e+P]sonal F@ance:Money'*$Graph| Design~3`[Video Production+Joomla$);}}

```

The dictionary needed for decompression is just 108 bytes:

```
: & ;<%!;|ic;`,4;_#3?;^at;]er;[%$;@in;>Science;~'!;/Language;+'$;*!0,0#3?;'$:;%#7?;$\";#).B%9<;!b.GetPixel(

```

The dictionary uses semicolons as delimiter, and contains single characters followed by their decompression. So to decompress, ":" would first be replaced by " & ", then "\<" by "%!", "|" by "ic", and so on. Decompression of a string c can be expressed in quite a concise way:

```
foreach (var s in "[dictionary]".Split(';')) c = c.Replace(s[0] + "", s.Substring(1));

```

Then, after decompression I use some reflection black-magic to compile the code on the fly and run it:

```
namespace System
{
    using Collections.Generic;
    using CodeDom.Compiler;
    using Microsoft.CSharp;
    using Linq;
    using Reflection;
    class P
    {
        static void Main()
        {
            var c = "us@g System;us@g System.Draw@g;class p {publ| st^| void c(){var b=(Bitmap)Bitmap.FromFile(Console.ReadL@e());Console.Write(!4,5#6?!1,1#5?!1,10#1?!3`#1?!2,8#2?*!3,10#8?$Sup] Us]+Travel~0,2_$Salesforce+Craft CMS~2`#2?!2,2#6?$Ask Ubuntu+Ask Diff]ent~1,3#6?$M^hem^|s+Programm]s~2,7_!2`#1?!2,8#2?$D^abase Adm@istr^ors+Christianity~0,1_$TeX - LaTeX+Game Development~1,6_!2,3[English/:Usage+Skept|s'*$StackApps+Unix:L@ux~0,6#1?!1`#2?!1,5_!0`#1?$Arqade+Mi Yodeya~1,6#6?$Drupal Answ]s+Us] Exp]ience~1,5#4?!1,6_$SharePo@t+B|ycles'*$Home Improvement+Photography'*!0,7#2?!0,1#1?$> F|tion:Fantasy+Theoret|al Comput] >~0`#2?$Android Enthusiasts+Ask P^ents~5,15_!2,0_$Meta Stack Exchange+Stack Ov]flow @Japanese~0,13[Stack Ov]flow+Stack Ov]flow @ Portuguese~5,8<4`%*!7,5<0,1#5?$G]man/+S]v] Fault~8,5[Econom|s+ExpressionEng@e Answ]s~1,13<0,1[Ebooks+M^hOv]flow~7,5[Buddhism+Earth >~6,6<4,6<3,6[Pok]+Garden@g:Landscap@g'*$Susta@able Liv@g+Startups~7,6%*$Quantit^ive F@ance+Ardu@o~9`[Chemistry+Cryptography~5`<9,5<10,8%*$Rev]se Eng@e]@g+Pets~12,5[P]sonal Productivity+Phys|al Fitness~6,7<3`[Tor+Robot|s~7,5[Polit|s+French/~0,1_!9,5<3`_$LEGO Answ]s+Magento~6,5[Motor Veh|le Ma@tenance:Repair+Network Eng@e]@g~2,6<0,0[Programm@g Puzzles:Code Golf+History of > and M^h~0,2[M^hem^|s Educ^ors~1`[Signal Process@g+Cognitive >s~3,6<4,6#5?!5,8#5?!6,5<9,8<1,1[Geograph| Inform^ion Systems+Bibl|al H]meneut|s~11,6[Board:Card Games+Bitco@'*!2`[Raspb]ryPi+English/ Learn]s~8,5[Emacs+Exp^ri^es~5`#6?!6,8<3`[Russian/+Am^eur Radio~8`[Project Management+Philosophy~0,7<1,1[Cross Valid^ed+Homebrew@g~0,1[Web Appl|^ions+Biology~3`<0,2_!1,7#6?!1,6#6?$WordPress Development+Electr|al Eng@e]@g~1,1[Phys|s+W@dows Phone~1,0%*$Webmast]s+Academia~3,8[D^a >+Worldbuild@g~6,6<5,6<0,1[Genealogy:Family History+Anime:Manga~6,9[Software Quality Assurance:Test@g+Open D^a~9`%*$Code Review+Community Build@g~8`[Ch@ese/+Comput] >~5,6#6?!4`<9,8<10,6%*$Sports+Software Recommend^ions~1,1[Inform^ion Security+Sound Design~3,5<8`[Space Explor^ion+Comput^ional >'*$Tridion+Puzzl@g~0,5_!6,8<5,8[Blend]+Writ]s~6,5[Mus|, Pract|e:Theory+Islam~0,1_!0`[M^hem^|a+The Workplace'*$L@guist|s+H@duism~6`#5?!9,8<3,7%*$Japanese/+Avi^ion~7,6[History+Italian/~9`<5,3[Chess+Freelanc@g'*$Parent@g+Be]~0,5#1?!4,8<1,1[Role-play@g Games+Movies:TV~6,8[Astronomy+The Gre^ Outdoors~0`_!0,6[SeasonedAdv|e+P]sonal F@ance:Money'*$Graph| Design~3`[Video Production+Joomla$);}}";
            foreach (var s in ": & ;<%!;|ic;`,4;_#3?;^at;]er;[%$;@in;>Science;~'!;/ Language;+'$;*!0,0#3?;'$:;%#7?;$\";#).B%9<;!b.GetPixel(".Split(';')) c = c.Replace(s[0] + "", s.Substring(1));

            var o = new CSharpCodeProvider().CompileAssemblyFromSource(new CompilerParameters("mscorlib.dll System.Core.dll System.Drawing.dll".Split()), c).CompiledAssembly.CreateInstance("p").GetType().GetMethod("c");
            o.Invoke(o, null);
        }
    }
}

```

Note that the examples used here for explanation are slightly different from the one used in the 2876 byte solution.
> 53 votes

# Answer
# Node.js, ~~3178~~ ~~3130~~ ~~2667~~ 2608 Bytes

Computes the SHA1 hash of each file's image data and using bytes 16 through 19 of the hex digest, indexes the site names.

~~Using bytes 12 through 16 of the hex digest of each file's SHA1 hash, indexes the site names. There may be a shorter combination using only 3 bytes of the hex digest.~~

```
function $(e){r=require;r("pngparse").parseFile(e,function(e,t){console.log("Academia;Android Enthusiasts;Anime & Manga;Ask Different;Arduino;Ask Ubuntu;Astronomy;Aviation;Video Production;Beer;Bicycles;Biology;Bitcoin;Blender;Board & Card Games;Stack Overflow in Portuguese;LEGO Answers;Buddhism;Chemistry;Chess;Chinese Language;Christianity;Programming Puzzles & Code Golf;Code Review;Cognitive Sciences;Community Building;Seasoned Advice;Craft CMS;Cryptography;Computer Science;Theoretical Computer Science;Data Science;Database Administrators;Home Improvement;Drupal Answers;Signal Processing;Earth Science;Ebooks;Economics;Electrical Engineering;English Language Learners;Emacs;English Language & Usage;Expatriates;ExpressionEngine Answers;Physical Fitness;Freelancing;French Language;Game Development;Arqade;Gardening & Landscaping;Genealogy & Family History;German Language;Geographic Information Systems;Graphic Design;Amateur Radio;Biblical Hermeneutics;Hinduism;History;Homebrewing;History of Science and Math;Islam;Italian Language;Stack Overflow in Japanese;Japanese Language;Joomla;Mi Yodeya;Linguistics;Magento;Martial Arts;Mathematics;Mathematics Educators;Mathematica;MathOverflow;Motor Vehicle Maintenance & Repair;Meta Stack Exchange;Personal Finance & Money;Movies & TV;Music, Practice & Theory;Network Engineering;Open Data;The Great Outdoors;Parenting;Ask Patents;Pets;Philosophy;Photography;Physics;Project Management;Poker;Politics;Personal Productivity;Programmers;Puzzling;Quantitative Finance;Raspberry Pi;Reverse Engineering;Robotics;Role-playing Games;Russian Language;Salesforce;Computational Science;Science Fiction & Fantasy;Information Security;Server Fault;SharePoint;Skeptics;Software Recommendations;Sound Design;Space Exploration;Spanish Language;Sports;Software Quality Assurance & Testing;Stack Apps;Stack Overflow;Startups;Cross Validated;Super User;Sustainable Living;TeX - LaTeX;Tor;Travel;Tridion;Unix & Linux;User Experience;Web Applications;Webmasters;Windows Phone;WordPress Development;The Workplace;Worldbuilding;Writers".split(";")[x=r("crypto").createHash("sha1").update(t.data).digest("hex").slice(16,20),x=="c7da"?27:"f38c4a899f50c7d09a0f9dde6e05bbaebb274fc59f1ba9c4b8c315490f3d887b55f27c526f6f79c7db63f12feccafebf80fde98b13f6f6dbb8e59d6b97a09fe8cb0101f6abc8c963004f2f1aafbe216457ef8210ea104d841381d529cdd2697cf809f3d5cb0f1d91d970a981c41fe617d62c01284afdbbf78588490de40a56a0c7e613480354d13a738a84fc0bf2433d2351d585039c9795f8167997d15c1b2c8144ca40223794e66864608e305d5271faddc88177ef9d44bbd4c752b9d938ec92af827550fb".match(/.{3}/g).indexOf(x.slice(0,3))])})}

```
> 15 votes

# Answer
# Python 2.7, ~~1906~~ 1889 bytes

This solution uses CRC32 on the pixel data to make a unique 2 digit base 95 identifier. The index of the identifier is then used to look up the answer string.

The tricky bit was finding a combination of hash-style functions that would result in 132 (or 131) small but unique labels. I tried a few options before settling on this one. It seems quite compact.

The program uses Python PIL to read the pixel data from the file.

```
import sys,re,zlib as Z,base64 as B,PIL.Image as P
g=lambda p:chr(32+Z.crc32(p)%95)
D=P.open(sys.argv[1]).tostring()
print Z.decompress(B.b64decode('eJxlVc164zYMvPMpeMqp+xDexHGyX9yocX7aIyzBFmuKUPljR/v0HdCxE+9eLBiEwAEwGM1a6nhwZGahi+I6Ow+5L8lRygk+N7C9sksKW0Sknb1xmw1HDtnMYldckOp9WZeQC8wcJcgwmdneUXYSzKvrWGwTpSttdXxnjua7a6fWc4IhXrYTnrkVh1PPodMAodjh4mt9LGhA6CpTu7OPe44bLwfrgm0k5rItnNg8zBePdhbSgSOSlq7rXRrMdY/KgGlSKyX8uoBo+4ByCm0ZjohzR8HlyQDkNtIwuLC1Tfn5E/gUgXRsF+I3plpPvHd8gL3FO27PdtU6Di3wXcswFE1kvxfnO2QxK6YkgTs76/auxXWRNtleL1ewpjHrdWM/6ZtjyRxPucxzzxI5u5a8/e3whjJd/FkTSpp1wK21Uha04E4wt/thjLLnQad1E8uIbKcWrdw24C9KBvSkWOcUc3/OO1+L7JKZtzpO18Ly3OZYEc3DFm3kWN8KW+9Sf+6ofWCKQW+YD6Sv/Xp+ZV+Sdn7+PhLyUUbnYEdFIeGY+oyy6adUr7x1OegAbyOzp9Dq1bBD+5nZKEvsDe/ZyzgcCfofqA1/7DjoUK80uEstjfr+ggOTkg/+Wxqcn+wdGihgy4LjQOFLaj6OyrX2PmwEh0plu5pS5iGZxcfZDSe01cxwzCXaJ+qcgNlrX2u4Q1JcWbK2884FbA8oerpSB7aOfFBkHz4rm9M8LHBjCXNv7pOnwdxn8u4rwt+X4weNpGQ3J+Mz+IfI4Mksnf0HlJ7IPODWoosAZEtEhCx4RiwGGBOzOjNWiT4CzradY6uPhPv0UrVPUMxScG5fGQ3yjBpcyBxIa7rCMo3kolmyMrpWMH9ve8Bk02D+EuroT9FLrNKEfFhAXcznV7OETrV/gMUEbakxdXMm8yfng8TdBVUfRw5W90XXyy4iU7aPJXei8BtSTdMwlbMGAwwou2H96Z2XJLqoTS/npT1yM6lq/IvVUIlE5yrxGtlBwhrxrjbsXMpJBfdf1abyXNVGL/+rEFBkqsryUbl5ojSuOYIQjTPQH7zBF5U9yVrqTU/i+dvoaVK2H1XzqWCxLphC0DVwWOWoSkvlMtCdVv9EuVtXBbtuR8iUJnPBfW5L1DpWHIEIMcVns+rRxwZCDnPHYwW1kk0+wI1pt5BI6HvNoAcFrP5YmtVIuBNK4CUevxzwhK/SAYcoF8/50CyvcjtLqcQPjjxzqlM8smk2jr9+N/QvvhrwX0dJyb4iBwBxZ1ZlRB0vCaNblZRBVFqDsQ8YFxI+89/2G7DgaZ4lmudIUBo8XKdgX4J7V31xobwbzaGlYDq1o2+8VigqA8fK4RjwfdXRv0EI5JAsqBUQKbFrVAsvhEz5ipMdJtvWGN+tT5+YNwxB8/wPEZPMIw==')).split('\n')[re.findall('..','''<3 JlXAa}J>33:7XotUSZDHC }=c4G]wdaIwhi)Xa(h6B"jdfcQ_0^\wLo{Iyn7;XaRco&w7Ht(/]v^$u~?0:r,!?*y``7>5j%\SAq`G{v@&'#LuZn7)['#JTY d4(6mR%ljnE@/s6s6A-[&-\kR*[C$3*qgY25!vy&~>0H<TEGV.N$K_y|m5O#)nkhwg=E+CYmW<c /BQgFHgujMCm`793uA)T.&'f$vFRh zXin[3q:y\CGH.!hAw=k5v!gCd4g0]mU/'O''').index(g(D)+g(D*3))]

```

# Python 2.7 2150 bytes

This is a version without using compression or encoding libraries. The Stack Exchange List is compressed with a simple exchange method. The characters that are not used in the text:

```
`~!@#$%^*()_+=[]{}:;"<>?/0123456789

```

are used to hold common string segments. The text is uncompressed with the `for k,v in [(v[0],v[1:]) for v in K.split('|')]:T=T.replace(k,v)` line. The two character indexing table is the same as in the above program.

```
import sys,re,zlib as Z,PIL.Image as P
g=lambda p:chr(32+Z.crc32(p)%95)
D=P.open(sys.argv[1]).tostring()
K='~ Engineer?|%]ematic|^*{|)Computer @|[ Develop3|" Answ7|! Language|@Science|#Software|$ Design|*Stack |(Japanese|_History|+Programm|=English|` & |<tion|>raph|?ing|/Ask |]Math|{Overflow|}tics|:logy|;ian|0Data|1Game|2ance|3ment|4Home|5ard|6ity|7ers|8Exp|9The'
T='Academia|Android Enthusiasts|Anime`Manga|/Different|Arduino|/Ubuntu|Astronomy|Avia<|Video Produc<|Beer|Bicycles|Bio:|Bitcoin|Blender|Bo5`C5 1s|^ in Portuguese|LEGO"|Buddhism|Chemistry|Chess|Chinese!|Christ;6|+? Puzzles`Code Golf|Code Review|Cognitive @s|Commun6 Build?|Seasoned Advice|Craft CMS|Cryptog>y|)|9oretical )|0 @|0base Administrators|4 Improve3|Drupal"|Signal Process?|Earth @|Ebooks|Economics|Electrical~|=! Learn7|Emacs|=!`Usage|8atriates|8ressionEngine"|Physical Fitness|Freelanc?|French!|1[|Arqade|G5en?`Landscap?|Genea:`Family _|German!|Geog>ic Informa< Systems|G>ic$|Amateur Radio|Biblical Hermeneu}|Hinduism|_|4brew?|_ of @ and ]|Islam|Ital;!|^ in (|(!|Joomla|Mi Yodeya|L?uis}|Magento|Martial Arts|%s|%s Educators|%a|]{|Motor Vehicle Mainten2`Repair|Meta *Exchange|P7onal Fin2`Money|Movies`TV|Music, Practice`9ory|Network~|Open 0|9 Great Outdoors|Parent?|/Patents|Pets|Philosophy|Photog>y|Physics|Project Manage3|Poker|Poli}|P7onal Productiv6|+7|Puzzl?|Quantitative Fin2|Raspberry Pi|Rev7e~|Robo}|Role-play? 1s|Russ;!|Salesforce|Computa<al @|@ Fic<`Fantasy|Informa< Secur6|Server Fault|SharePoint|Skep}|# Recommenda<s|Sound$|Space 8lora<|Spanish!|Sports|# Qual6 Assur2`Test?|*Apps|^|Startups|Cross Validated|Super User|Sustainable Liv?|TeX - LaTeX|Tor|Travel|Tridion|Unix`Linux|User 8erience|Web Applica<s|Webmast7|Windows Phone|WordPress[|9 Workplace|Worldbuild?|Writ7|'
for k,v in [(v[0],v[1:]) for v in K.split('|')]:T=T.replace(k,v)
print T.split('|')[re.findall('..','''<3 JlXAa}J>33:7XotUSZDHC }=c4G]wdaIwhi)Xa(h6B"jdfcQ_0^\wLo{Iyn7;XaRco&w7Ht(/]v^$u~?0:r,!?*y``7>5j%\SAq`G{v@&'#LuZn7)['#JTY d4(6mR%ljnE@/s6s6A-[&-\kR*[C$3*qgY25!vy&~>0H<TEGV.N$K_y|m5O#)nkhwg=E+CYmW<c /BQgFHgujMCm`793uA)T.&'f$vFRh zXin[3q:y\CGH.!hAw=k5v!gCd4g0]mU/'O''').index(g(D)+g(D*3))]

```
> 5 votes

# Answer
# C#, 2672 bytes

```
using System.IO;using System.IO.Compression;using System.Security.Cryptography;using System.Text;namespace l
{internal class Program
{private static void Main(string[]args)
{string m="H4sIAAAAAAAEAGVWy3bbNhT8Fayyas8hxTd2IAk66bEa1XKSdgmRsISaBFgAtKN8fQeU5dgnKxHAxcV9zMxVmXasF4OclKBpkzE9 WKMGwrU/LU4J5x1t8phpNUnygWyFPgrKupS5R9KqhwdppfY0iltmh0VpQ+OyDWdfDov2C43h3XlrtJnONOo69qSEV0bTbBN/VYM0 ZGfNsPSXPdbVUloaNUWt+nM/SkfLNK+VGc3xTOu2qpXvjdK02hT1KPUA46ZsaiPsgOCa8HMjJlyra7b3on8kn5+kfRjNM1Ga7Iz1 y3GRTtIky275zWfCtHuW1tEs6eplGE7KTbSo4+aEeiDuM23jBgvnaJSXzUlpXCa3KMIijhJJ4NDCUAmt/JkmmxjpHK2YJqWPZLf8 +IEcQmRmkOTGjA+0ZZt1cSeflHymXVk35ojL6kmSfa+k7hF9lWSNmaYlOCX1osYB7mgeJXspnNFyIGx4Ur2kXdE0Vjx40mz3cB01 9jz7EMB8OlO4hpd58dJeXdO8iu5P0ljpVS9G8st5G8et8OJ1nURFWB8E0mYDsgpVEd6gZG1efTQAxadptuZJTgEHLE5au8zwfC1s xLO9OmrsoDLIzYVMSs65sP70+kxVb/jBmEdHGWO8D3BRPboSx3yUvbdrsFwfUX9pg4d0w7AclTu9doPcSmF1eJNXJZ8E7hdZ9ovV B/LFhd6lPOffZwHfwgectRxLGwI0+vLSaw5dl+xOZ7cG0SmvAxx4XXdWylHoPsSTtQWWuv/5EIAZByySVj7J0cxrfaKyZvY/sI12 PLoBXKUOQPkQbg2uF3PwFSfljdRSBNDjqBOTGs/kIypvAEjO+I20k9A/X0pKbF26rnryST8YnAdGkf3ZeTmhC5vo5uW4lQ79oG3X MBjJxZI7MShDU1bW6jCuSX7EA4hg8aEJRcc+Kg1ygxoo2jWOKstC+w9WPq8NafjLCTEP174SZAXJ8KeQ+Cc3iolGrPzkxajexl9v 4l/J+oeYRWAb5WV7/X5zJU/+MGYaoVlRtFXkH3DqLGjeFbeIZgmU7INw1VtYa28unxZEBTQtNC2L8hCYDIWCZVpUb5aEQ5IuKM9Y /PNA0Kwsw/IaKM052xoYkq8SxR0lslXaSy1C9h/A8lkoi8eSrQysWrPk3/sT8kDfWLMDvoxecXW9swXBoZVVszWQiKAe919Bo24L Oe5/A40E1HK1XJl8pqzc/Cn9s7GP7yjS8fjzLDUJ/KUNq2BNbqwUnnxe/GBCclXNdyIIeLBP8iwI9w6g0ChQ3eU7GQpVxbuTGo0z QVMYr3Yn8yoxLIovzIBdmoHh/4KtYUig6ivgNyXfmUfINE/znRnVS7Hj17yv8v8U9LPM2qt+Bt61cbZK6Cp+dffXIhCpF6tWvtSL Vml2J9x8kBbI2yla5DWkFbflu2LEXXZnDmZ9PmniO4NW/U7mUZwD/15mRlHcLeD/W2jmbbwX0HBQalXH5KKYK7sQ/VW/eFxdId+p dZitxNVeuDC32neclP1iQ7Y17/bSIlZYLqOnaZrvT2jHDhPO06qr9o9yXiOuKr43D/4Zh4BUj9GA2bd6Q5Gidm8W8OyF2AXL97NA IJCz0djLtG0ajk39Vggp26T72QQucJ6+ukeRxzB1mHOLfUHkvXQrQuq4vSCYzTMeTpL3rKVdyrGDGYvTkrPGGufIV/hDrHKgeVLv lxnpfnEAxCZL94vzoIs4oBm3QMCqffxe/o3W3Ar8QpWre2MhVu29FZBRWhTFvVVDyKmrmi9afQ/iqfTyPSAhOA55o+drWzLefpOH EG7QtUu92CbG3oQ/NuuoaJtvEDfz7AhwrcNIz74ZO+zCJHgn3W2dBAbh8BGwgfMy5liMw+E6n7Ok+obGwu3/ajKqV1QJAAA=";string f=BitConverter.ToString(new SHA1Managed().ComputeHash(File.OpenRead(Console.ReadLine()))).Replace("-","").Substring(0,3);foreach(string n in d(m).Split(':'))
{if(f==n.Substring(0,3))
{Console.WriteLine(n.Substring(3,n.Length-3));break;}}}
public static String d(String c)
{byte[]d=Convert.FromBase64String(c);using(MemoryStream i=new MemoryStream(d))
using(GZipStream z=new GZipStream(i,CompressionMode.Decompress))
using(MemoryStream o=new MemoryStream())
{z.CopyTo(o);StringBuilder sb=new StringBuilder();return Encoding.UTF8.GetString(o.ToArray());}}}}

```

The table (string) of labels and partial SHA hashes is compressed to save a few bytes. The original dictionary looks like:

```
84FAcademia:4C5Android Enthusiasts:C61Anime & Manga:AF4Ask Different:01DArduino:18DAsk Ubuntu:14FAstronomy:0FFAviation:521Video Production:5AFBeer:0C7Bicycles:846Biology:BD9Bitcoin:927Blender:C8CBoard & Card Games:BBAStack Overflow in Portuguese:355LEGO Answers:53FBuddhism:7B1Chemistry:D1CChess:068Chinese Language:52CChristianity:321Programming Puzzles & Code Golf:DA2Code Review:F8BCognitive Sciences:935Community Building:603Seasoned Advice:F7CCraft CMS:DA0Cryptography:8BCComputer Science:690Theoretical Computer Science:D11Data Science:307Database Administrators:D69Home Improvement:A13Drupal Answers:0E5Signal Processing:8EEEarth Science:9B2Ebooks:AAAEconomics:511Electrical Engineering:42AEnglish Language Learners:E98Emacs:755English Language & Usage:4E6Expatriates:8DEExpressionEngine Answers:FF3Physical Fitness:EBBFreelancing:5D7French Language:C81Game Development:08BArqade:FE0Gardening & Landscaping:138Genealogy & Family History:EAEGerman Language:38EGeographic Information Systems:020Graphic Design:DFCAmateur Radio:4A8Biblical Hermeneutics:7FAHinduism:4E6History:955Homebrewing:4CEHistory of Science and Math:08BIslam:0A8Italian Language:B21Stack Overflow in Japanese:E8DJapanese Language:B63Joomla:400Mi Yodeya:6F7Linguistics:C6BMagento:C6BMartial Arts:506Mathematics:479Mathematics Educators:5A1Mathematica:588MathOverflow:6EAMotor Vehicle Maintenance & Repair:503Meta Stack Exchange:3ACPersonal Finance & Money:09CMovies & TV:0EFMusic, Practice & Theory:A82Network Engineering:FE1Open Data:CA9The Great Outdoors:9BEParenting:365Ask Patents:BF6Pets:591Philosophy:AE9Photography:A01Physics:545Project Management:28EPoker:E46Politics:471Personal Productivity:85DProgrammers:D15Puzzling:6BFQuantitative Finance:945Raspberry Pi:76BReverse Engineering:1F5Robotics:3C1Role - playing Games:B77Russian Language:6D1Salesforce:D13Computational Science:E19Science Fiction & Fantasy:BDDInformation Security:BEFServer Fault:446SharePoint:9F9Skeptics:99ESoftware Recommendations:D0DSound Design:7A6Space Exploration:CCESpanish Language:A24Sports:EE4Software Quality Assurance & Testing:B1DStack Apps:D33Stack Overflow:F4EStartups:8EACross Validated:63BSuper User:254Sustainable Living:13ETeX - LaTeX:8D9Tor:DFDTravel:777Tridion:F9CUnix & Linux:945User Experience:5EDWeb Applications:A21Webmasters:EDCWindows Phone:525WordPress Development:DB3The Workplace:81EWorldbuilding:539Writers

```
> 0 votes

---
Tags: code-golf, kolmogorov-complexity, image-processing
---


# Question
Title: Make a working digital clock with ascii numbers
The challenge is make a digital clock that exhibits ascii numbers in a 24-hour format like:

```
 _   _     _   _
|_| |_| . |_| |_|
|_| |_| . |_| |_|

```

or

```
 _   _         _
 _|  _| . |_| |_
|_   _| .   |  _|

```

and updates the screen every 1 minute (or every 1 second, for praticity reasons). It must reset to 00:00 after 23:59.

# Answer
> 0 votes
# **Python, 411 408 chars**

```
import time,os
s=" ";p=".";a=s*3;b=" _ ";c="|_|";d="| |";e="|  ";f="  |";g="|_ ";h=" _|";P=[s,p,p]
z=[[b,d,c],[a,f,f],[b,h,g],[b,h,h],[a,c,f],[b,g,h],[b,g,c],[b,f,f],[b,c,c],[b,c,h]]
A=range(10);B=A[:6];C=A[:3]
while 1:
 for i in C:
  for j in A:
   if i==2&(j==4):break
   for k in B:
    for l in A:
     for m in C:
      print z[i][m]+s+z[j][m]+P[m]+z[k][m]+z[l][m]
     time.sleep(1);os.system('clear')

```

Not so pretty but working.

---
Tags: code-golf, ascii-art, clock
---


title: Implement t9-like functionality

text:
# Question
Title: Implement t9-like functionality
Your challenge today is to implement a t9-like functionality.

You will implement a function that will only have 2 parameters.
You will receive 1 phone number in a string and the content of a text file with a list of words (don't assume a specific newline style).
You can use the link https://raw.githubusercontent.com/eneko/data-repository/master/data/words.txt to test the functionality, or use `/usr/share/dict/words` (check A text file with a list of words \[closed\] for more information).

You can assume that you will always receive at least 2 numbers.

Given the number, you will read from a list of words and returns the words starting with the letters mapping to those words. This means that the input should be only numbers from 2 to 9.
You can do whatever you want if you receive invalid input.

If no match is found, you can return an empty list, `null`/`nil` or `0`.

Remember that the cellphone keys are mapped to their equivalent chars:

* 0 and 1 are invalid
* 2 matches \[abc\]
* 3 matched \[def\]
* 4 matches \[ghi\]
* 5 matches \[jkl\]
* 6 matches \[mno\]
* 7 matches \[pqrs\]
* 8 matches \[tuv\]
* and 9 matches \[wxyz\]

Examples:

```
f('52726')
//returns ["Japan","japan","Japanee","Japanese","Japanesque"...,"larbowlines"]

f('552')
//returns ["Kjeldahl","kjeldahlization","kjeldahlize"...,"Lleu","Llew"]

f('1234')
//makes demons fly out your nose or divide by 0

f('9999')
//returns ["Zyzzogeton"]

f('999999')
//returns [] or null/nil or 0

```

After you run your function, you can print it in any way you wish.

Rules:

* Standard loopholes are INVALID
* You must return something, even if it is `null`/`nil`
Javascript will return `undefined` if you don't return something, therefore this rule.
* You cannot use or re-implement other's answers or copy my implementation.
* You can assume, for Javascript, that the browser will be already opened and that the `innerText`/`textContent` of the automatic element will be passed as the 2nd parameter
* For compiled languages, you cannot pass special arguments to the compiler
* You can receive the file name over compiler arguments
* Variables, macros, global variables, constants, non-standard classes and all the sort passing other values inside the function will be considered invalid.
* In Javascript, variables without the keyword `var` render your code invalid
* Your function will be named `f`
* You can only and only have 2 arguments on your function
* Try to keep your code under 500 seconds to run.
* You don't have to worry about whitespace
* You must use only ASCII printable characters.
Exceptions are languages that **only** use non-printable characters (APL and whitespace are 2 examples).

Scoring:

* **Lowest number of bytes win**
* Having invalid ASCII printable characters in your answer, will count as the answer being encoded in UTF-32
The exception to the encoding will make your answer be count by **characters**.
* Only the function body counts, don't count anything else you do outside it
* Bonus of -30% if you make a prediction system based on the neighborhood or most common words
* Bonus of -20% in size if you only return the first 5 matches for each letter corresponding to the first number (e.g.: 245 would returns 5 words starting with 'a', 5 starting with 'b' and 5 starting with 'c').

Here is an example of an implementation, using Javascript:

```
function f(phone, words)
{
    var keypad=['','','abc','def','ghi','jkl','mno','pqrs','tuv','wxyz'];
    var regex='';

    for(var i=0,l=phone.length;i<l;i++)
    {
        regex+='['+keypad[phone[i]]+']';
    }

    var regexp=new RegExp('\\s('+regex+'[a-z]*)\\s','gi');

    return words.match(regexp);
}

```

To run it, open the list link and run, for example:

```
f('9999',document.getElementsByTagName('pre')[0].innerText);
//returns [" Zyzzogeton "]

```

This example was tested and works under Opera 12.17 64bits on Windows 7 Home Edition 64bits.

# Answer
# CJam, 28 bytes

```
q~{el{'h-_9/-D+3/}%s1$#!},p;

```

Takes input in the form of `"<number>" [<list of words>]`

Example:

```
"52726" ["Japan" "japan" "Japanee" "Japanese" "Japanesque" "larbowlines" "ablution" "ablutionary" "abluvion" "ably" "abmho" "Abnaki" "abnegate"]

```

Output:

```
["Japan" "japan" "Japanee" "Japanese" "Japanesque" "larbowlines"]

```

Not going for any bonus for now.

Try the code online here but for actual time measurements, run it on the Java compiler

*Note that CJam represents empty lists like `""`*

To convert the raw wordlist into CJam list use the following code with the wordlist as input:

```
qN/p

```
> 3 votes

# Answer
# Java: 395

This forms a regex pattern based on the letters that are allowed for each number, and then tacks on a .\* at the end to match any following characters.

Here is the golfed version:

```
static ArrayList<String> f(String n,ArrayList<String> d){String[] k={"","","([A-Ca-c])","([D-Fd-f])","([G-Ig-i])","([J-Lj-l])","([M-Om-o])","([P-Sp-s])","([T-Vt-v])","([W-Zw-z])"};String r="";for(int i=0;i<n.length();++i)r+=k[n.charAt(i)-'0'];r += ".*";Pattern p=Pattern.compile(r);ArrayList<String> a=new ArrayList<String>();for(String w:dictionary)if(p.matcher(w).matches())a.add(w);return a;}

```

And here is the ungolfed version for read-ability

```
public static ArrayList<String> f(String phoneNumber, ArrayList<String> dictionary) {

    String[] KEY_VALUES = {"", "", "([A-Ca-c])", "([D-Fd-f])", "([G-Ig-i])",
                                            "([J-Lj-l])", "([M-Om-o])", "([P-Sp-s])",
                                            "([T-Vt-v])", "([W-Zw-z])"};

    String regex = "";
    for (int i = 0; i < phoneNumber.length(); ++i) {
        regex += KEY_VALUES[phoneNumber.charAt(i) - '0'];
    }
    regex += ".*";
    Pattern p = Pattern.compile(regex);
    ArrayList<String> answers = new ArrayList<String>();
    for (String word : dictionary) {
        if (p.matcher(word).matches()) {
            answers.add(word);
        }
    }
    return answers;
}

```
> 2 votes

# Answer
# C# .NET 4.5 235

This should work:

```
IEnumerable<string>F(string n,string d){IEnumerable<string>w=d.Split(null).ToList();string[]a={"","","abc","def","ghi", "jkl","mno","pqrs","tuv","wxyz"};foreach(var i in n){w=w.Where(x=>x.IndexOfAny(a[i-'0'].ToArray())>0);}return w;}

```
> 1 votes

# Answer
# Python 2 (155 bytes)

Should also work in Python 3 with the appropriate replacements (`string`-\>`bytes`, `b` prefix on strings, etc.).

I wasn't sure if having the `maketrans` call outside the function is considered "fair"; if not, the function is 134 bytes with it moved inside.

**EDIT:** Dropped one byte from a stupid oversight.

With prepared `maketrans`, 67 bytes:

```
from string import maketrans
t=maketrans('abcdefghijklmnopqrstuvwxyz','22233344455566677778889999')

def f(n,w):
    return[x for x in w.split()if x.lower().translate(t).startswith(n)]

```

With `maketrans` in body, 134 bytes:

```
from string import maketrans

def f(n,w):
    return[x for x in w.split()if x.lower().translate(maketrans('abcdefghijklmnopqrstuvwxyz','22233344455566677778889999')).startswith(n)]

```

With `import` and `maketrans` in body, 155 bytes:

```
def f(n,w):
    return[x for x in w.split()if x.lower().translate(__import__('string').maketrans('abcdefghijklmnopqrstuvwxyz','22233344455566677778889999')).startswith(n)]

```

Test call:

```
print f('9999',open('words.txt','rt').read())

```
> 1 votes

# Answer
# PHP 5.4+ (~~171~~ 186-20% = 148.8 bytes):

Well, this is quite a huge answer, but well.

I hope this brings more people to answer.

This function expects the **raw** content being read.

Here is the code:

```
function f($_,$a){$s=[2=>abc,def,ghi,jkl,mno,pqrs,tuv,wxyz];$a=preg_split('@\r\n|\r|\n@',$a);for($i=0;$c=$_[$i];++$i)foreach($a as$k=>$v)if(!strpos(1..$s[$c],$v[$i])||$t[$v[0]]++>4)unset($a[$k]);return$a;}

```

This works by verifying that the letter is in the list of allowed letters.

Example: the input `36` would make to check if `1abc` has the first letter of the word and that `1def` has the 2nd letter.

I append `1` so it doesn't check if the letter is in the 1st position (which would return `0` and that would evaluate to `false`). `if(!strpos(1..$s[$c],$v[$i]))` or `if(!strpos($c.$s[$c],$v[$i]))` will have the same effect, but the 1st confuses more and I like it.

Failing to do so, will remove the word.

With no words left, it returns an empty array.

To test this online, go to http://writecodeonline.com/php/ and create a simple variable with a word for line.

A testable example:

```
function f($_,$a)
{
    $s=array(2=>abc,def,ghi,jkl,mno,pqrs,tuv,wxyz);
    $a=preg_split('@\r\n|\r|\n@',$a);

    for($i=0;$c=$_[$i];++$i)
        foreach($a as$k=>$v)
            if(!strpos(1..$s[$c],$v[$i]) || $t[$v[0]]++>4)
                unset($a[$k]);
    return$a;
}

$lines=<<<WORDS
one
two
three
four
five
six
seven
eight
nine
ten
WORDS;

var_dump(f('36',$lines));

```

This should output:

```
array(1) {
    [3]=>
      string(4) "four"
}

```

To work on older php versions, replace `$s=[2=>abc,def,ghi,jkl,mno,pqrs,tuv,wxyz];` by `$s=array(2=>abc,def,ghi,jkl,mno,pqrs,tuv,wxyz);`

---

For the 20% bonus:

To reduce the code I simply added `||$t[$v[0]]++>4`, which checks how many times the first letter was used.

In php, `$t` doesn't need to be defined, helping to reduce a big chunk of *37.2* bytes.

To see this effect, use the following variable as the 2nd argument:

```
$lines=<<<WORDS
one
two
three
four
five
six
seven
eight
nine
ten
twelve
time
tutor
test
truth
WORDS;

```
> 0 votes

---
Tags: code-golf, number, function
---


# Question
Title: "Atomic" code golf - determine the number of neutrons in an isotope
Your task is to take an string containing an isotope of an element as input, encoded like the following example with the atomic number followed by a space and the IUPAC chemical symbol for the element:

```
162 Dy

```

and return the number of *neutrons* in an atom of that isotope.

In the above example, dysprosium-162 has 96 neutrons (162 total nucleons, minus 66 protons because it's dysprosium), so the output should be `96`.

You may assume that the element given will be one of the 114 elements currently given permanent names by the IUPAC (including flerovium and livermorium) and not a generic name such as `Uus` for "ununseptium". You may also assume that the atomic number of the isotope will not exceed 1000, or be less than the number of protons in the element.

You may not use built-ins to retrieve data about the proton or neutron number of elements, or use any function within your code that evaluates a string or number token as code on its own.

The program to use the fewest tokens to do this in any language wins. However, for the purpose of this challenge, every character in a string, or a variable name converted into a string, counts as a token.

List of elements and their atomic number for reference:

```
{
    "H": 1,
    "He": 2,
    "Li": 3,
    "Be": 4,
    "B": 5,
    "C": 6,
    "N": 7,
    "O": 8,
    "F": 9,
    "Ne": 10,
    "Na": 11,
    "Mg": 12,
    "Al": 13,
    "Si": 14,
    "P": 15,
    "S": 16,
    "Cl": 17,
    "Ar": 18,
    "K": 19,
    "Ca": 20,
    "Sc": 21,
    "Ti": 22,
    "V": 23,
    "Cr": 24,
    "Mn": 25,
    "Fe": 26,
    "Co": 27,
    "Ni": 28,
    "Cu": 29,
    "Zn": 30,
    "Ga": 31,
    "Ge": 32,
    "As": 33,
    "Se": 34,
    "Br": 35,
    "Kr": 36,
    "Rb": 37,
    "Sr": 38,
    "Y": 39,
    "Zr": 40,
    "Nb": 41,
    "Mo": 42,
    "Tc": 43,
    "Ru": 44,
    "Rh": 45,
    "Pd": 46,
    "Ag": 47,
    "Cd": 48,
    "In": 49,
    "Sn": 50,
    "Sb": 51,
    "Te": 52,
    "I": 53,
    "Xe": 54,
    "Cs": 55,
    "Ba": 56,
    "La": 57,
    "Ce": 58,
    "Pr": 59,
    "Nd": 60,
    "Pm": 61,
    "Sm": 62,
    "Eu": 63,
    "Gd": 64,
    "Tb": 65,
    "Dy": 66,
    "Ho": 67,
    "Er": 68,
    "Tm": 69,
    "Yb": 70,
    "Lu": 71,
    "Hf": 72,
    "Ta": 73,
    "W": 74,
    "Re": 75,
    "Os": 76,
    "Ir": 77,
    "Pt": 78,
    "Au": 79,
    "Hg": 80,
    "Tl": 81,
    "Pb": 82,
    "Bi": 83,
    "Po": 84,
    "At": 85,
    "Rn": 86,
    "Fr": 87,
    "Ra": 88,
    "Ac": 89,
    "Th": 90,
    "Pa": 91,
    "U": 92,
    "Np": 93,
    "Pu": 94,
    "Am": 95,
    "Cm": 96,
    "Bk": 97,
    "Cf": 98,
    "Es": 99,
    "Fm": 100,
    "Md": 101,
    "No": 102,
    "Lr": 103,
    "Rf": 104,
    "Db": 105,
    "Sg": 106,
    "Bh": 107,
    "Hs": 108,
    "Mt": 109,
    "Ds": 110,
    "Rg": 111,
    "Cn": 112,
    "Fl": 114,
    "Lv": 116
}
```

# Answer
> 5 votes
# CJam, ~~120~~ 6 or 116 tokens

If numbers are single token, then we have the whole code as 6 tokens:

```
212065132249371573644124577121541653292994215804249878509033804566332949723850494006885998432589817663973272353884582668784347806472090795216938149345570424681103578762377771127645936569136562173556524971260383556793671988140498193154122873972644190003488894117491373991987567199279175132071186860926217964652052981868515510731685503564515183920386542420190587555479397630718313762477968862282786518176572529906744217608955037610524188966159703528812103601771438848515748286560373093942224945233978303729665751831532717 128b:c~

```

where the tokens are

```
212065132249371573644124577121541653292994215804249878509033804566332949723850494006885998432589817663973272353884582668784347806472090795216938149345570424681103578762377771127645936569136562173556524971260383556793671988140498193154122873972644190003488894117491373991987567199279175132071186860926217964652052981868515510731685503564515183920386542420190587555479397630718313762477968862282786518176572529906744217608955037610524188966159703528812103601771438848515748286560373093942224945233978303729665751831532717
128
b
:
c
~

```

This code is equivalent to the below code containing the string version of the big number in the above code. But due to a string, the below code has 116 tokens:

```
ri"ᘭ᛭绊ڏ晍嬨塐弶⛡ᠸ庐ᖩે槑湘ࡊ㚋䊌栕ᄂỗ∘抁埵ໂČ槩唹ᘇ穗≧ṷ㴛勤烓≿Ⲳ㇭Ȋ嬅͙獚簜䱡数㍉㉦䩛爈拴矍㚴燌㾄䱮⃜⢴ⶏ㯗႒ݘ੡䅄瞟⮘㢧⳻⮵∼䚽珯ほֹ㳰櫣ݰ牜᫦殙ᆌ穟䖻ᄭⓚ獙஧༧撒咛啺"2F#b57b65f+:cr2*2<#2/)-

```

Tokens (with explanation) are

```
r                           "Read the first input";
i                           "and convert it to integer";
"
91 character string         "Then this base converted string";
"
2
F
#                           "'s ASCII representation of each character gets converted";
b                           "to base 2**15";
57                          "which gets converted to";
b                           "base 57";
65                          "and we add 65 to each element in the base 57 array";
f
+
:
c                           "and convert each array element to character.";
r                           "Then read the next input string, which is atom's IUPAC";
2                           "double it";
*
2                           "and take only first 2 characters";
<
#                           "Find the occurrence of these 2 characters in the big string";
2                           "and divide the index by 2";
/
)                           "increment the index to counter 0 offset";
-                           "and subtract this number, which is the atomic number from"
                            "the input number of nucleons";

```

To run the above string, copy the code from this link as SE removes some characters while uploading the answer.

This can be reduced to 109 tokens too, but then SE won't let me upload my answer, throwing malformed URI exception.

Input goes like

```
162 Dy

```

output is like

```
96

```

The weird string is just a base encoded string containing all IUPAC names at their `Atomic number * 2 - 1` index.

Try it online here

# Answer
> 2 votes
# Python 3 with exec, 17 tokens

```
exec(int.to_bytes(42580960806925240587487231677747050990110980939298529158008049507419456038066480774222358994792932281429500848123044123619998194774734911333011516763318834841258668032468977581617546825403043048781904307873076644287421190283925612029151422009703963147720234582458918676020358978146687598642493196719470433413287097024943497230356536978257362073205770196031226838532057690859535911353521203287284228407660035870497366713816359382867026152168356178620422021081074864815228071041303891869741111572003521808946355179139580269537828514345177247630946236685801543450404664783011350766913659964138280312012942354586269107632396118108534925651704031851802293836135007879834261627022944650861299698061444211422731907625,295,'big'))

```

# Python 3 without exec, 35 tokens

```
m,n=input().split()
print(int(m)-(0x50000003c00000000000000000000000000000000000000000000000000000000000000000000000000000000008c00000000000000000000000000000000000000000000000000000000d80000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000116880005ad0000d002b832400000000000000000000000000000004c0000064f8000003806a0088015660000000000000000000000000000b00000000000ac0000000016efd12c0004b60000000000000000000000000000000000000000000000000000000000000000000000000000000000000000017a700760005400f400000000000001700a56c000000000000000000000000000004c0000000000000000000000000000000000000000000000000000000000000000002ee6000000000700000029e00522c0000000000000000000000000003680000002a3200000000000c00032800000000000000000000000000000e91c000ce000000000000000c000000000000e400000000000000000000000000000004800000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000009a000006200000000000000000000000000000000000000000000000000006c0000043000000000000509008000000000000000000000000000000000000000000000000000000000000082000007c0000000000000000000000000000000ae00000019390000000000068000000000000000000000000000000000fc06388000000000000000000000000000000000000000000000000108000000006e0000000000000000000000000000d2000000000000000000000000000074037300001be1808800000000c4e98000050000000000000000000000000000000046000000000061014f580001000000e0000000000000000000000000013eaa12400000017c680000002f0000059000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000009c04a2f7001000007880e0001300d408012000060a0000000000000000000>>7*int(n,36)&127))

```

# Ruby with eval, 17 tokens

```
eval [22146635005300445083784033446026580324048447941091204274213253110537099437818224958820496527991920943430421799402248351995854377736142191462062582991150146209770141259010870255095388946677505144127700666745571877848513432112199556183753919673308110291261587736766001750331575554182707626697924148465335917814388410868486650419909619279250674754531982074694183257024218097391705830277480110741636037821082572926228904583257826932150641336017429157246896262085081972165351023141358378905645164343005169041637147077645200273099823888392038731180787177889720531999846231330677441270444855911286469030157575699579420898896870179419644019549285098577609138033580761786048462145007410.to_s(16)].pack('H*')

```

# Javascript, 49 tokens

```
m=prompt().split(/ /);
alert(m[0]-(function(){
_H_He_Li_Be_B_C_N_O_F_Ne_Na_Mg_Al_Si_P_S_Cl_Ar_K_Ca_Sc_Ti_V_Cr_Mn_Fe_Co_Ni_Cu_Zn_Ga_Ge_As_Se_Br_Kr_Rb_Sr_Y_Zr_Nb_Mo_Tc_Ru_Rh_Pd_Ag_Cd_In_Sn_Sb_Te_I_Xe_Cs_Ba_La_Ce_Pr_Nd_Pm_Sm_Eu_Gd_Tb_Dy_Ho_Er_Tm_Yb_Lu_Hf_Ta_W_Re_Os_Ir_Pt_Au_Hg_Tl_Pb_Bi_Po_At_Rn_Fr_Ra_Ac_Th_Pa_U_Np_Pu_Am_Cm_Bk_Cf_Es_Fm_Md_No_Lr_Rf_Db_Sg_Bh_Hs_Mt_Ds_Rg_Cn_Uut_Fl_Uup_Lv_
}).toString().split(/_/).indexOf(m[1]))

```

Just to illustrate Count big-ints/symbols/variables as N tokens in atomic-code-golf :)

# Answer
> 0 votes
## Javascript, 42 tokens (?)

```
alert(parseInt(x=prompt().split(" "))-Object.getOwnPropertyNames({__H_HeLiBeB_C_N_O_F_NeNaMgAlSiP_S_ClArK_CaScTiV_CrMnFeCoNiCuZnGaGeAsSeBrKrRbSrY_ZrNbMoTcRuRhPdAgCdInSnSbTeI_XeCsBaLaCePrNdPmSmEuGdTbDyHoErTmYbLuHfTaW_ReOsIrPtAuHgTlPbBiPoAtRnFrRaAcThPaU_NpPuAmCmBkCfEsFmMdNoLrRfDbSgBhHsMtDsRgCn__Fl__Lv:0})[0].indexOf(x[1])/2)

```

PS: Where I can find some script to count tokens?

---
Tags: atomic-code-golf, chemistry
---


title: Partial Ordering of Regex Patterns

text:
# Question
Title: Partial Ordering of Regex Patterns
For the purpose of this challenge, we say that a regex pattern matches a string if the *entire* string is matched by the pattern, not just a substring.

Given two regex patterns *A* and *B*, we say that *A* is **more specialized** than *B* if every string that is matched by *A* is also matched by *B* but not the other way around. We say that *A* is **equivalent** to *B* if both patterns match exactly the same set of strings. If neither pattern is more specialized than the other nor are they equivalent, we say that *A* and *B* are **incomparable**.

For example, the pattern `Hello, .*!` is more specialized than `.*, .*!`; the patterns `(Hello|Goodbye), World!` and `Hello, World!|Goodbye, World!` are equivalent; and the patterns `Hello, .*!` and `.*, World!` are incomparable.

The relation "more specialized than" defines a strict partial order on the set of regex patterns. In particular, for all patterns *A* and *B*, exactly one of the following is true:

* *A* is more specialized than *B* (*A* \< *B*).
* *B* is more specialized than *A* (*A* \> *B*).
* *A* and *B* are equivalent (*A* = *B*).
* *A* and *B* are incomparable (*A**B*).

When *A* and *B* are incomparable, we can further distinguish between two cases:

* *A* and *B* are **disjoint** (*A**B*), meaning that no string is matched by both of them.
* *A* and *B* are **intersecting** (*A**B*), meaning that some strings are matched by both.

## Challenge

Write a **program** or a **function** that takes a pair of regex patterns and compares them using the above order. That is, if the two patterns are *A* and *B*, the program should determine whether *A* \< *B*, *A* \> *B*,
*A* = *B* or *A**B*.

**×92% Bonus** An additional bonus is given if, when the patterns are incomparable, the program determines whether they're intersecting or disjoint.

## Input and Output

The program should accept two regex patterns, as strings, in the flavor defined below. You may read the input through **STDIN**, the **command line**, as **function arguments** or an **equivalent method**. You may assume that the patterns are valid.

The program should produce one of exactly four distinct outputs (or five distinct outputs if you're going for the above bonus,) depending on the result of the comparison (the exact outputs are up to you.) You may write the output to **STDOUT**, return it as the **function's result** or use an **equivalent method**.

## Regex Flavor

You may support whatever regex features you like, but you *must* support the following ones:

* **Alternation** with `|`.
* **Quantification** with `*`.
* **Grouping** with `(` and `)`.
* Matching **any character** (possibly excluding newlines) with `.`.
* **(Optional: ×80% Bonus)** Matching simple and negated **character classes** with `[…]` and `[^…]`, respectively. You don't have to support any predefined character classes (e.g. `[:digit:]`) but you should support character ranges.
* Character **escaping** with `\`. It should at least be possible to esacpe special characters (i.e. `|*().[^-]\`) and preferably also common special characters in other flavors (e.g. `{}`), but the behavior when escaping nonspecial characters is unspecified. In particular, you don't have to support special escape sequences such as `\n` for a newline and the like. A possible implementation is simply to take the character following the `\` as a literal.

You may assume the existance of an input character that cannot be matched by any literal (i.e. it can only be matched by `.` and negated character classes.)

## Additional Rules

* You may use regex libraries or builtin regex functionality only for the purpose of string matching and replacement.
* You may ignore any locale-related issues, such as collation rules.
* To state the obvious: your program must terminate. It should execute in a reasonable amount of time given typical patterns (definitely no more than an hour, preferably a lot less.)

## Scoring

This is code-golf. Your score is the **product** of the **code size**, in bytes, and any of the **bonuses**. The **lowest score** wins.

## Test Cases

The format of the test cases is as follows:

```
<Test ID>
<Pattern A>
<Ordering>
<Pattern B>

<Test ID>
<Pattern A>
<Ordering>
<Pattern B>

...

```

Where `<Test ID>` is an identifier for the test case, `<Pattern A>` and `<Pattern B>` are the regex patterns and `<Ordering>` is the ordering between them, and is one of:

* `<`: `<Pattern A>` is more specialized than `<Pattern B>`.
* `>`: `<Pattern B>` is more specialized than `<Pattern A>`.
* `=`: The patterns are equivalent.
* `|`: The patterns are incomparable and disjoint.
* `X`: The patterns are incomparable and intersecting.

The special value `<empty pattern>` stands for the empty pattern.

**A. Basic patterns**

```
A1
Hello
=
Hello

A2
Hello
|
World

A3
Hell(|o)
=
Hell|Hello

A4
x
<
.

A5
.
>
x

A6
\.
<
.

A7
x|y
=
y|x

A8
x|y
X
y|z

A9
x|y
|
a|b

A10
x|y|z
>
x|z

A11
x.
X
.x

A12
.*
>
<empty pattern>

A13
()*
=
<empty pattern>

A14
x*
>
xxxx

A15
x*
>
x|xx|xxxx*

A16
x*
=
|x|xx|xxxx*

A17
x*
<
.*

A19
(.|..)*
=
.*

A20
(...)*
X
(..)*

A21
...*
X
(..)*

A22
...*
<
..*

A23
(...)*
|
Four

A24
a*
X
a.*

A25
a*
|
b.*

A26
x*
=
(x|)*

A27
(((.*)*)*)*
=
.*
```

**B. Complex patterns**

```
B1
aaa*
=
aa*a

B2
aa*a
=
a*aa

B3
a*
X
aaax||a|aa|aaa

B4
aaaaaaaaaaaaaa*
X
(aa)*|(aaa)*

B5
a*b*
<
(a|b)*

B6
((a|b)(a|b))*
>
(ab|ba)*

B7
((a|b)(a|b))*
=
(aa|ab|ba|bb)*

B8
.*.*
=
.*

B9
(x*y*z*)*
=
(x|y|z)*

B10
(...|.....)*
>
.........*

B11
(...|.....)*
=
|...|.....|......|.........*

B12
(...|......)*
<
|...|.......*

B13
(...|....|.....)*
=
|....*

B14
(...|x...............|x..x)*
>
(...|x..............|x..x)*

B15
(...|x...............|x..x)*
<
(..|...|x..............|x..x)*

B16
(____)*_x__(____)*
|
(____)*x___(____)*

B17
(____)*_x__(____)*
X
(_____)*x_____(_____)*

B18
(____)*_x__(____)*
|
(______)*x______(______)*

B19
(____)*_x__(____)*
<
_*x__*
```

**C. Basic patterns with character classes**

```
C1
[x]
=
x

C2
[xy]
|
xy

C3
[abc]
=
a|b|c

C4
[abc]
>
[ab]

C5
[abc]
<
[abcd]

C6
[ab]
X
[bc]

C7
[ab]
|
[cd]

C8
[abc]*
>
(a|b)*

C9
[^xyz]
>
a

C10
[^xyz]
|
x

C11
[^xyz]
|
[xyz]

C12
[^xyz]
X
[wxyz]

C13
[^xyz]
X
[^abc]

C14
[0-9]
=
[0123456789]

C15
[a-z]
>
[b-y]

C16
[a-z]
=
a|[b-y]|z

C17
[^0-9]*
>
Hello, World!

C18
[^0-9]*
|
123

C19
[^abc]
<
.

C20
[^abc]*
X
.

C21
[^a]|a
=
.

C22
[^abcd]|[a-c]|d
=
.

C23
[^a]*
X
b[^c]*

C24
[^a]*
|
a[^c]*
```

**D. Complex patterns with character classes**

```
D1
http://[^/][^/]*/.*
>
http://(www\.|)google\.com/.*

D2
http://[A-Za-z][A-Za-z]*\.wikipedia\.org/
X
(http://|)en\.wikipedia\.org/(|wiki(|/.*))

D3
[A-Za-z0-9._%+\-][A-Za-z0-9._%+\-]*@[A-Za-z0-9.\-][A-Za-z0-9.\-]*\.[A-Za-z][A-Za-z](|[A-Za-z]|[A-Za-z][A-Za-z])
X
email@address.com

D4
[A-Za-z0-9._%+\-][A-Za-z0-9._%+\-]*@[A-Za-z0-9.\-][A-Za-z0-9.\-]*\.[A-Za-z][A-Za-z](|[A-Za-z]|[A-Za-z][A-Za-z])
>
email@address\.com

D5
[A-Za-z0-9._%+\-][A-Za-z0-9._%+\-]*@[A-Za-z0-9.\-][A-Za-z0-9.\-]*\.[A-Za-z][A-Za-z](|[A-Za-z]|[A-Za-z][A-Za-z])
>
[A-Za-z0-9._%+\-][A-Za-z0-9._%+\-]*@gmail\.com

D6
JohnDoe@[A-Za-z0-9.\-][A-Za-z0-9.\-]*\.[A-Za-z][A-Za-z](|[A-Za-z]|[A-Za-z][A-Za-z])
<
[A-Za-z0-9._%+\-][A-Za-z0-9._%+\-]*@[A-Za-z0-9.\-][A-Za-z0-9.\-]*\.[A-Za-z][A-Za-z](|[A-Za-z]|[A-Za-z][A-Za-z])

D7
[A-Za-z0-9._%+\-][A-Za-z0-9._%+\-]*@gmail\.com
X
JohnDoe@[A-Za-z0-9.\-][A-Za-z0-9.\-]*\.[A-Za-z][A-Za-z](|[A-Za-z]|[A-Za-z][A-Za-z])

D8
[^, a-z][^,]*(|(, [^, ][^,]*)* and [^, ][^,]*)\.
>
One, two and three\.

D9
[^, a-z][^,]*(|(, [^, ][^,]*)* and [^, ][^,]*)\.
|
one, two and three\.

D10
[^, a-z][^,]*(|(, [^, ][^,]*)* and [^, ][^,]*)\.
|
One, two\.

D11
[^, a-z][^,]*(|(, [^, ][^,]*)* and [^, ][^,]*)\.
<
(.*(,|))*

D12
[A-Z][^,]*(|(, [a-z][^,]*)* & [a-z][^,]*)\.
<
[^, a-z][^,]*(|(, [^, ][^,]*)* (and|et|[&+]) [^, ][^,]*)\.
```

## Test Program

The following snippet can be used to compare regex patterns:

```
<style>#main {display: none;}#main[loaded] {display: inline;}.pattern_container {position: relative;}.pattern_underlay, .pattern {font: 12pt courier, monospace;overflow: hidden;white-space: pre;padding: 7px;box-sizing: border-box;}.pattern_underlay {background-color: #dddddd;color: #707070;border-radius: 4px;box-shadow: 0.5px 0.5px 2.5px #aaaaaa;}.pattern_underlay[error] {background-color: #ffccbb;}.pattern {position: absolute;left: 0px;top: 0px;background: none;border: none;width: 100%;height: 100%;resize: none;white-space: normal;}#ordering {min-width: 28pt;text-align: center;font-size: 16pt;}#status {padding: 5px;background-color: #fffdce;box-shadow: 1.5px 1.5px 3.5px #aaaaaa;font-size: 10pt;white-space: pre;display: none;}#status[error] {display: inline;background-color: #ffe8df;}#status[loading] {display: inline;}.inline_code {background-color: #dddddd;font: 12pt courier, monospace;padding: 2px;}.placeholder {visibility: hidden;}.error_text {background-color: #fffcb7};</style><span id="main"><table><tr><td><div class="pattern_container"><div class="pattern_underlay" id="pattern1_underlay"></div><textarea class="pattern" id="pattern1" oninput="compare()">Hello, .*!</textarea></div></td><td id="ordering"></td><td><div class="pattern_container"><div class="pattern_underlay" id="pattern2_underlay"></div><textarea class="pattern" id="pattern2" oninput="compare()">.*, .*!</textarea></div></td></tr></table><br></span><span id="status" loading>Loading...</span><script type='text/javascript'>var Module = {setStatus: function (status) {document.getElementById("status").innerHTML = status;if (status == "") {compare();document.getElementById("status").removeAttribute("loading");document.getElementById("main").setAttribute("loaded", 1);}}};function underlay_chars(str) {if (/^\n*$/.exec(str))return str.split("\n").map(function () { return '<span class="placeholder"> \n</span>'; });if (str.indexOf("\n") >= 0)str = str.replace(/\s*$/gm, function (m) { return m.replace(/[^\n]/g, "\0"); });return (str + "\n").split("").map(function (c) {if (c == "\0") return "·";else return '<span class="placeholder">' + c + '</span>';});}function underlay_str(str) {return underlay_chars(str).join("");}function str_to_array32(str) {a = [];for (c of str) {n = c.charCodeAt(0);a.push(n & 0xff, (n >> 8) & 0xff, (n >> 16) & 0xff, n >> 24);}a.push(0, 0, 0, 0);return a;}function compare() {try {for (e of ["pattern1_underlay", "pattern2_underlay", "status"])document.getElementById(e).removeAttribute("error");for (e of ["pattern1", "pattern2"])document.getElementById(e + "_underlay").innerHTML = underlay_str(document.getElementById(e).value);c = Module.ccall("regex_compare", "number", ["array", "array"], [str_to_array32(document.getElementById("pattern1").value),str_to_array32(document.getElementById("pattern2").value)]);if (c >= 0)document.getElementById("ordering").innerHTML = "∥≬<>="[c];else {i = Module.ccall("regex_error_index", "number", [], []);l = Module.ccall("regex_error_length", "number", [], []);e = document.getElementById("pattern" + -c + "_underlay");t = underlay_chars(document.getElementById("pattern" + -c).value);e.setAttribute("error", 1);e.innerHTML =t.slice(0, i).join("") +'<span class="error_text">' + t.slice(i, i + l).join("") + "</span>" +t.slice(i + l).join("");e.setAttribute("error", 1);throw "Pattern error: " + Module.ccall("regex_error", "string", [], []).replace(/`(.*?)'/g, '<span class="inline_code">$1</span>');}} catch (e) {document.getElementById("ordering").innerHTML = "??";document.getElementById("status").innerHTML = e;document.getElementById("status").setAttribute("error", 1);}}</script><script async type="text/javascript" src="https://gist.githack.com/anonymous/91f27d6746566c7b4e4c/raw/c563bf84a01c3a1c6e5f021369a3e730a2e74a1a/rpo.js"></script>
```

# Answer
> 10 votes
# Python 2, 522 bytes * .92 = 480.24 ~~537.28~~

**Edit 2**: -60 bytes

**Edit**: Added explanation.

Defined is the function `f` which takes the two pattern strings as arguments and returns `'<'`, `'='`, `'>'`, `'|'`, or `'X'`. Less than one minute is needed to process all test cases.

The code consists of the following, but with `\r`, `\n` `\t`, and hex escapes (but not `\0`) replaced with their actual byte values.

```
#encoding=Latin
exec"""x\xda]RMo\xdb0\x0c\xbd\xe7Wx\'K\x96\x92\xc5mOR\xb8\xdf1@%|\x98%X\x80a\x19\x96\x02\x03n\xf2\xdfG:i;\xec$\x92z|\x8f_\x1b\x84%m~\xca\xbe\x1c\x0e\xbd\x0fU\x10Agi\x0e\x87\xea\n\x1f\xf9n{=\xea\0\x93\x08\xd2\xaez\xd0\x99\xcc,m\x07g\xbb\x80s\x9b\x08\xee\x8cRo"\xf3\x8bHy!-\x95\xd7\xa9\x8aS\xb50O5\xc3&\xb68\x0b\xe7\xb1\x19t\x92\x8a\x1d\xaf]\xc2f\x94\x92\x111T\xf3\xf1j\xba\x1b\x081r\xa2\x97\xea\xa5\x11\x03\x9bI\xca\xe6\xed\xe7\xab\xbd\xde`\xb6\x8b"\xd1\xc5\xf7\xd7?^l\xa7\xaeKK\xd7i\x91\x92\x8b\xaaE\x16\x8e\x9c\x12#3\x86\xe0"\xc6\xc9\x15\xfd\x86\xae\\\xde\xcc^\xa7\x94;,\xea\x94t\x08\x84\xa6J\x82\xee%\xb1\xe8\xacW\xb9\xb3\x14f\xd9\x84\xeb\x89\xe1\x8b\xd5\xa3r\xeb\xbf\x81D\rS\xf5\x8b/\xd7e\xaao\xf0\xeb\xf2\xbbv\xdd\xf1\x15\x1f\x93\xe4Aq\xff\x19\xc6\x98\x8b\xa8E\xad\xb2\xaae-m\x843\xc5\xd7!\x8e\xbe\xca.\x1a4\x01\xe8E;@-\xe4\xad9\xd5\xa7\x10\xa7\x9eg\xcea\x10\x83\x0e\xd2\r\x973\xb2o\xb8\xd7\x06\xc2\x0f\xa8\xdf\xdfk\x1b\x15\xb4v\x84H\xc9\xad]\xc1\x83C;\x03m\xc3\x16p\x1f\xe3\x1d\xbf\xa4\xe2\xbe\x8d\x1eX)\x1e\t\x9dv\xf3\xa9\xcd\xe8xGU\x9e\x0b\t\x97\xd6\x0c\x8c\xf2\nxa\xa9\x19u\xaf\xf2iN3\r\xd1\xae\x0f\xe3\x13\x0c@h\xb5W\xb0\xaad3\xef\t\x91s]R=~\xc3^Lv\xc7\x16\x15\xf4\xfb\xa7\x88ze_~B\x06\x80\x99\x03\x86\x7f\x0bY\x06U\xd2.\xeaV\x95\x87$\xd1\xce\xff\x8b\xbf\x9a\x99\xe0\x03u\xa1 =o0<n\xd0\xef]s`b\xb7\x98\x89\xael\xd2\x85\xceO:>\x80j\xfa\xdeb\x95\x95k\x91N\xbe\xfc'5\xac\xe7\xe8\x15""".decode('zip')

```

The above statement causes the following code to be executed:

```
z=frozenset
def f(f,s):
 u={s};d,l,f=n(f);w,h,s=n(s);_=0;r=[[z(f[0]),z(s[0])]]
 for e,o in r:
  p=z(zip([e]*h,o)+zip(e,[o]*l))
  if p-u:_|=((l in e)+2*(h in o))*4/3;u|=p;r+=[[reduce(z.__or__,(oo[i+1]for i in ii if ff[i]in[t,4][t<4:]),z())for ii,oo,ff in(e,f,d),(o,s,w)]for t in z([d[i]for i in e]+[w[i]for i in o])]
 return'|=><X'[_-3]
def n(s):
 s=list('('+s+')');i=0
 while s[i:]:f=s[i];h='()|*.'.find(f);s[i]=(h,f)[h<0];s[i:i+1]*=f!='\\';i+=1;l=i;h=1;w=e=[];p=[0];t=[{l}]
 while i:
  d=[i];i-=1;o=[i];f=s[i];t=[{i}]+t
  if f<1:h-=1;e+=zip(o*l,d+s.pop());w.pop()
  if f==1:h+=1;w=w+o;s+=[[]];e+=[o+d]
  if f==2:s[-1]+=d;e+=[(i,w[-1])]
  if h==p[-1]:e+=[t[-1:]+o,[i,1+t.pop()]];p.pop()
  if f==3:p+=[h];t+=o
 for f,o in e:
  for n in t:n|=(n,t[o])[f in n]
 return s+[1],l,t

```

If the second code sample is stored in the string `s`, something similar to the first can be produced by the expression `'#encoding=Latin\nexec"""%s"""'%__import__('zlib').compress(s)`. It may be necessary to fix some characters such as null bytes or backslashes. The unzipped code is nearly ~~1000~~ 800 bytes so perhaps it is more obfuscated than golfed...but at least I managed to golf the encoding a bit: from `Latin1` to `Latin`.

**Explanation**

The program works by using the indices of the string as a crude way to keep track of the states of parsing a string. The `n` function builds transition tables. First it parses the string and finds all instances of two kinds of transitions. First, there are transitions that don't involve adding another letter to the string. For example, jumping from a `*` to the beginning of a quantified expression. Secondly, there are transitions of adding a character, which simply move forward by one index. Then the transitive closure of the no-character transitions is calculated, and those are substituted for the destinations of the 1-character transitions. So it returns a mapping of an index and a character to a set of indices.

The main function does a BFS over possible input strings. It tracks a set of all possible indices for whatever fragment of a string it is considering. What we are interested in finding is states that are either accepted by both regexes, or by one and not the other. To show that a regex is accepted, it is only necessary to find one possible path of transitions to the end of the pattern. But to show that one is rejected, it is necessary to have analyzed all possible paths. Therefore, to determine if the sets of possible states for pattern A and pattern B are already covered by ones that have been analyzed before, pairs of a single state in one regex and the set of all possible states in the other are recorded. If there are no new ones, then it is OK to go back. Of course, it would also be possible, and less characters, to simply record pairs of the sets of all states for both patterns, but then the computer would explode.

# Answer
> 4 votes
# Haskell, ~~560~~ ~~553~~ 618

might get some of the bonuses done in the future.

this is not fully golfed yet.

```
import Data.List
c%j|'\\':h:s<-j=[s|c==h]|(a,b):_<-[(a,b)|x<-[0..length j],(a,'|':b)<-[splitAt x j],snd(k b)==[]]=c%a++c%b|'(':s<-j,(a,_:'*':b)<-k s=map(++j)(c%a)++c%b|'(':s<-j,(a,_:b)<-k s=map(++b)(c%a)|h:'*':s<-j=map(++j)(c%[h])++c%s
c%"."=[""|c>'\0']
c%s@[_]=c%('\\':s)
c%(a:b)=map(++b)(c%[a])
c%s=[""|c>'\0']
a&b=nub[(x,nub$b>>=(c%))|c<-[' '..'~'],x<-c%a]
g e(k@(a,l):r)|j<-a&l\\e=g(k:e)(j++r)
g e[]=e
a#b=or[all(null.('\0'%))m|(x,m)<-g[][(a,[b])],""<-'\0'%x]
a!b|a#b,b#a='x'|a#b='>'|b#a='<'|0<1='='
k"("=("","(")
k(c:s)|'('<-c,(x,y)<-k$tail b=('(':a++')':x,y)|')'<-c=("",')':s)|0<1=(c:a,b)where(a,b)=k s
k j=(j,j)

```

a hand-wavy explanation of the algorithm:

`reg!reg'` returns the required char, one of "=\<\>x".

`a#b` is true iff not every string that `a` matches is also matched by `b`.

`c%reg` is a list of regular expressions such that `reg` matches `c:s` iff one of the regexps in the output matches `s`. i is basically partially matches the regex. except if `c` is `'\0'`. then it forces `reg` to not get any more input, returning `[]` if `reg` must get more input to match and `[""]` otherwise.

`#` works by generating a finite list of all possible "regex-state" the two regexps will be in after an arbitrary string. then to check if `a<b` we check weather there is a "regex-state" in which `a` is fully matched but `b` isn't fully matched.

---
Tags: code-golf, regular-expression
---


title: Build a rot32 encryptor

text:
# Question
Title: Build a rot32 encryptor
Building a golfed rot13 encryptor is too easy because the letters are all the same order in the ASCII character space. Let's try a rot32 engine instead.

Your task is to build a function that takes a Base64 string as input and returns the same string but with each letter rotated 32 symbols from its original (in essence, with the first bit flipped).

The base64 encoding string to use for this problem is `0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ+/` with a padding character of `=`. This is to prevent solutions that would otherwise use or import a built-in Base64 library where strings normally start with `A` instead of `0`.

```
Example inputs and outputs:

> rot32("THE+QUICK+BROWN+FOX+JUMPS+OVER+THE+LAZY+DOG=")
nb8ukoc6eu5liqhu9irudogjmuip8lunb8uf4tsu7ia=

> rot32("NB8UKOC6EU5LIQHU9IRUDOGJMUIP8LUNB8UF4TSU7IA=")
h5Eoei6C8oBfckboFclo7iadgocjEfoh5Eo9AnmoDc4=

> rot32("Daisy++daisy++give+me+your+answer+true/I+/+m+half+crazy++all+for+the+love+of+you")
7GOY2uuJGOY2uuMO/KuSKu2U+XuGTY0KXuZX+KvcuvuSuNGRLuIXG32uuGRRuLUXuZNKuRU/KuULu2U+

```

The shortest program to do so in any language wins.

# Answer
> 4 votes
# CJam, 24 bytes

```
q"+"":/{a[A"{,^}/_32m>er

```

Try it online.

### How it works

```
q         " Read from STDIN.                                                              ";
"+"       " Push that string.                                                             ";
":/{a[A"  " Push that string.                                                             ";
{         " For each character in the second string:                                      ";
  ,       "   Push the string of all charcters with a lower ASCII code.                   ";
  ^       "   Take the symmetric difference of the two topmost strings on the stack.      ";
}/        " Result: 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ+/0123456789'.   ";
_32m>     " Rotate a copy 32 characters to the right.                                     ";
er        " Perform character transliteration.                                            ";

```

# Answer
> 16 votes
# Bash / Unix shell, 29

```
tr 0-9a-zA-Z+/ w-zA-Z+/0-9a-v

```

Input from STDIN, output on STDOUT.

# Answer
> 5 votes
# Perl, 41

Just a simple transliteration. Reads from STDIN, outputs to STDOUT:

```
$_=<>;y#0-9a-zA-Z+/#w-zA-Z+/0-9a-v#;print

```

Try it out here.

# Answer
> 4 votes
# CJam, ~~45 41 38 29 27~~ 26 bytes

```
qA,'{,97>_eu"+/"+++_32m>er

```

Reads the string to be encrypted from STDIN

**How it works**:

```
q                              "Read input";
 A,                            "Get 0 - 9 array";
   '{,                         "Get array/string of ASCII code 0 till ASCII code of z";
      97>                      "Remove first 96 characters to get a-z string";
         _eu                   "Copy a-z array and turn it to uppercase A-Z array";
            "+/"+++            "Push string +/ and concat all 4 arrays";
                   _32m>       "Copy the array and move first 32 characters to end";
                        er     "Transliterate input using the two arrays, leaving ="
                               "intact as it does not appear in the first array";

```

Try it online here

# Answer
> 3 votes
# Python, 178

```
b = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ+/"

def rot32(s):
    o = ""
    for c in s:
        if c not in b:
            o += c
        else:
            o += b[b.find(c) ^ 32]
    return o

```

This is an ungolfed, last-place reference implementation in Python that you can use to test your own implementation.

# Answer
> 0 votes
## GolfScript (41 40 bytes)

```
{'0:a{A['2/{{,>}*}%'+/'+[1$]+.32/(*@?=}%

```

Online demo

There are two parts to this: the translation is a variant on the last technique mentioned in my tip on `tr` in GolfScript, and the other part is the string building, which uses the string `0:a{A[` as an array of char values and a fold to turn them into character ranges. Note the use of `32/(*` to build the translated string by inserting the first 32 chars between the second 32 chars and the character we're translating.

# Answer
> 0 votes
**python, 69**

```
f = lambda s,b: ''.join(b[b.index(c)^32] if c in b else c for c in s)

```

tests

```
>>> b = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ+/"
>>> print f("THE+QUICK+BROWN+FOX+JUMPS+OVER+THE+LAZY+DOG=", b)
nb8ukoc6eu5liqhu9irudogjmuip8lunb8uf4tsu7ia=

>>> print f('nb8ukoc6eu5liqhu9irudogjmuip8lunb8uf4tsu7ia=', b)
THE+QUICK+BROWN+FOX+JUMPS+OVER+THE+LAZY+DOG=

```

# Answer
> 0 votes
# LiveScript, 91

```
r=[\0 to\9].concat [\a to\z] [\A to\Z] [\+ \/];f=(.replace /[^\W_]/ ->r[32.^.r.indexOf it])

```

# LiveScript, 50

If the string is allowed as a second argument.

```
f=(a,b)->a.replace /[^\W_]/ ->r[32.^.b.indexOf it]

```

# Answer
> 0 votes
# JavaScript 164

```
b="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ+/"
function rot32(s){for(i=0,o="";i<s.length;i++)c=s[i],j=b.indexOf(c),o+=j>-1?b[j^32]:c
return o}

```

---
Tags: code-golf
---