56
\$\begingroup\$

Challenge

Write a program that takes as input a day from April 30, 1789 to August 21, 2019 and returns as output who was president of the USA that day.

Notes

For the list of US presidents, the format of their names, and the period of their presidency, see below:

April 30, 1789 - March 4, 1797          George Washington
March 4, 1797 - March 4, 1801           John Adams
March 4, 1801 - March 4, 1809           Thomas Jefferson
March 4, 1809 - March 4, 1817           James Madison
March 4, 1817 - March 4, 1825           James Monroe
March 4, 1825 - March 4, 1829           John Quincy Adams
March 4, 1829 - March 4, 1837           Andrew Jackson
March 4, 1837 - March 4, 1841           Martin Van Buren
March 4, 1841 - April 4, 1841           William Henry Harrison
April 4, 1841 - March 4, 1845           John Tyler
March 4, 1845 - March 4, 1849           James K. Polk
March 4, 1849 - July 9, 1850            Zachary Taylor
July 9, 1850 - March 4, 1853            Millard Fillmore
March 4, 1853 - March 4, 1857           Franklin Pierce
March 4, 1857 - March 4, 1861           James Buchanan
March 4, 1861 - April 15, 1865          Abraham Lincoln
April 15, 1865 - March 4, 1869          Andrew Johnson
March 4, 1869 - March 4, 1877           Ulysses S. Grant
March 4, 1877 - March 4, 1881           Rutherford B. Hayes
March 4, 1881 - September 19, 1881      James A. Garfield
September 19, 1881 - March 4, 1885      Chester A. Arthur
March 4, 1885 - March 4, 1889           Grover Cleveland
March 4, 1889 - March 4, 1893           Benjamin Harrison
March 4, 1893 - March 4, 1897           Grover Cleveland
March 4, 1897 - September 14, 1901      William McKinley
September 14, 1901 - March 4, 1909      Theodore Roosevelt
March 4, 1909 - March 4, 1913           William Howard Taft
March 4, 1913 - March 4, 1921           Woodrow Wilson
March 4, 1921 - August 2, 1923          Warren G. Harding
August 2, 1923 - March 4, 1929          Calvin Coolidge
March 4, 1929 - March 4, 1933           Herbert Hoover
March 4, 1933 - April 12, 1945          Franklin D. Roosevelt
April 12, 1945 - January 20, 1953       Harry S. Truman
January 20, 1953 - January 20, 1961     Dwight D. Eisenhower
January 20, 1961 - November 22, 1963    John F. Kennedy
November 22, 1963 - January 20, 1969    Lyndon B. Johnson
January 20, 1969 - August 9, 1974       Richard Nixon
August 9, 1974 - January 20, 1977       Gerald Ford
January 20, 1977 - January 20, 1981     Jimmy Carter
January 20, 1981 - January 20, 1989     Ronald Reagan
January 20, 1989 - January 20, 1993     George H. W. Bush
January 20, 1993 - January 20, 2001     Bill Clinton
January 20, 2001 - January 20, 2009     George W. Bush
January 20, 2009 - January 20, 2017     Barack Obama
January 20, 2017 - Incumbent            Donald Trump

A presidency is intended as first day included and last day excluded. For example, "March 4, 1861 - April 15, 1865; Abraham Lincoln" means that Lincoln was president from March 4, 1861 to April 14, 1865.

This is code-golf, the shortest program in each language wins.

Example

Input: "February 7, 1865" Output: "Abraham Lincoln"

\$\endgroup\$
  • 18
    \$\begingroup\$ Hi there, welcome to CGCC! This looks like a nice challenge, but all challenges should be self-contained. Instead of the Wikipedia link, please have a list here of all presidents and their periods (preferably in code-block, so a scroll-bar will appear). Also, I recommend having a flexible input-format, so people could input as a string in whatever format, three loose integers, a date object, etc. how they see fit in their language of choice. \$\endgroup\$ – Kevin Cruijssen Aug 22 at 11:27
  • 3
    \$\begingroup\$ Also, for future challenges, it's best to first post them in the Sandbox of Proposed Challenges. There you can get feedback and make the challenge better, before posting it to main. Enjoy your stay! :) \$\endgroup\$ – Kevin Cruijssen Aug 22 at 11:27
  • 11
    \$\begingroup\$ How flexible is the IO format? \$\endgroup\$ – qwr Aug 22 at 19:38
  • 15
    \$\begingroup\$ WolframAlpha["president on "<>#]& I'm sure pure Mathematica has a builtin somewhere but until I find what it's called I'm sticking with W|A. \$\endgroup\$ – Pavel Aug 22 at 22:07
  • 8
    \$\begingroup\$ @Pavel in that case make it WolframAlpha["US president on "<>#]& cause for me the output is not correct \$\endgroup\$ – jonatjano Aug 23 at 8:09

13 Answers 13

27
\$\begingroup\$

PHP, 936 bytes

for($a=explode('-',gzinflate(base64_decode('dVTRbtswDPwV/YANKXZq+zFJ1wRts3VZtgB7Y2Mm1ipLAO0089+PtNIuHbAnAzySd+RRNkVZ6XxSJUsMdES1g66x/tgHn5iiKnSms+Q+NF7Nami7xJTajLFtE1ro1D0eDkidZJe6itnQYqfWUNsYNsV1OHgKyNHJ9G/rryfr98M7wyT2mfma8KzuYf8SG2Wx0Rqot179AK/mJ0JB8qhpZ52z0KoVehrUCoguEhjP38i2g0OS2PRK1kOqnoJ7kXAk/wn7BrjJFgYXJH2qdaHLZM0UQLW6428bSCaZZmPFHYF/cSzsySLtR+B68PmJG3oQNTdR7eyZoGG1jzx8cCMw1bnJ3wdntVH+TdT03Q1dx62+pWrJZD0jRaTYnPoG6RBY2DzlwQeUPZbmin/GRUAHi66OUGXKZNFg1yMJOKO+OcmgZdzLksIrIwuHr+jAj0VRxhz9L2h50KsFV9n/ii4n9GbNev9gvcMhMZUWDXJIGGrepNqE0EldL1j10dBwlqVv4SCgiWS7EGoKZ8VJo4hqcrkCloVeLWURVPMtC5RpPtxkAe6VhS9CcLY+ogCRaIX0jNQzkQzA8ewfU2/TD/pyccoksoFB/NjSqRVvKz4GY6rk9myPTS9Vn2yHvgnnsSs7L+h4h3epekDvsZZd3GTGTEzyOPg6ePHw3fyKzZeajZWDrNVn+3sMFzlPVPKrJXB8jmy9BIvY37btoBb8TkbWMrJugpfUDcJxlFrGxpd3v0rVLuUr7RqGqjjFnNfPZlovf4OJ1ua64C2b47HRHIifqvryDC1w1EQtfwA=')));$d=$a[+$i++];)date(Ymd,strtotime($argn))>$d?$m=$a[$i++]:die($m);echo'Donald Trump';

Try it online!


Tests: Try it online!

The code for tests is the same logic but a little bit different to replace the die(...) with return... so I can loop over tests.


I have created a string having start date of presidency minus 1 day in format of YYYYMMDD and name of president in it, separated by -. Example: 17890429-George Washington-17970303-John Adams-18010303-Thomas Jefferson-...

This string is compressed using gzdeflate and also the compressed output is converted to base-64 so all characters are printable ASCII and I can post them here or use them in TIO.

In the script, the string is split by - and looped over. For each loop iteration:

  • $d is set to current iteration value (which is the president's start date -1 day) and the loop variable ($i) is increased by one.
  • If input date is larger than $d, then $m is set to next iteration value (which is the president name for $d) and the loop variable ($i) is increased by one again. This allows the loop to get president names but jump over them in iterations.
  • If input date is not larger than $d, then that means the previous iteration was the correct president, so $m is printed using die function, this will stop the whole program after printing the name.

At the end, if the loop is finished (which means no die was called), the last president's name is printed, since we know non of previous presidents have got a match (so basically anything after January 19, 2017) prints last president's name, even if it is January 1, 3999.

\$\endgroup\$
  • \$\begingroup\$ save 20 bytes by replacing your gz string with gist.github.com/007/b40b52da40b454d2196d0a807a6fcfaf \$\endgroup\$ – Ryan Moore Aug 23 at 20:53
  • \$\begingroup\$ I don't know PHP, but can you remove the base64 and insert the raw unprintable characters (you can supply a hexdump). \$\endgroup\$ – MilkyWay90 Aug 23 at 23:11
  • \$\begingroup\$ @RyanMoore, thanks for the better compressed string, sadly I'm not in control of this answer anymore and my purpose which got many up-votes (and some down-votes too) has been removed from it (in this revision). So I'm not going to edit or golf this answer anymore even though there are still some golfing possibilities for it. \$\endgroup\$ – Night2 Aug 24 at 10:03
  • \$\begingroup\$ @MilkyWay90, that is completely possible. But I posted this version purposefully to have a readable code here and TIO links. Basically this wasn't meant to be a hard-core answer. \$\endgroup\$ – Night2 Aug 24 at 10:08
4
\$\begingroup\$

JavaScript (Node.js),  855 851  803 bytes

d=>(g=i=>(p+=parseInt((a=(require('zlib').inflateRawSync(Buffer("ZVJtct0gDLwKB1A9dSaTtGfoKWSQDc+AXgS2S09f8T6cdPqDsc2utKuVv411jTC6FV4EzzO6eD53GG26vc0Wtp+3t9uhjkwn7+0dxnf6hPu5JHiJP8524mHcr7fPV3yDF+Z79XcL48em2ASy/yP+1dRCLAuZA4sPeamc4cI+G3SYClTPCYu50DyTlI5homISuvDli7Mw3cs+tpBte1RjdkKHuaBdOzuh1JDNjtlMm1CGI8QYMBlPWZrxKHLv2hvVFkkeAutgrhxX+INWSc1UbJEFkpajODPrM7EQzIJ5jSpxDSSWHtXTplUZM+Ak6FVOGZZjPu2pXJfdYitF+WUwizaqIFv1JDOrxDSovUbl0RKVgjIHig6sp1JJ+p3O5zeBRXjXCxtpp6giMFHWOvV1jvgf5RlFsr9CjtQ0eWKnQxlhLp1VP+Pio49dcdY7Zid8GMV6XwU0WLN0u+J0n2Ax7qpsmWNwC4FONJFUbdIdfEbmhi9K3WfrQVTZkibnjrD42jkUCmU10HfT1zQPZqWcyTWILTvOPapnohL6vpzJ4XefmQSjbkvzhEtIqRmrgWkj4dwBIVwwP/9HP5hj0N0VD5POrVGFXPmETwxF/y7DEyYEd2/UTV//Ag","base64"))+"").split`,`)[i],32))<new Date(d)/864e5?g(i+1):a[i+44].replace(/\b./g,c=>c.toUpperCase()))(p=0)

Try it online!

How?

The compressed string contains a list of 89 values.

The first 44 values are the length of the president mandates expressed in number of days and encoded in base 32 (which is the base that compresses best).

The next 45 values are the president names in lower case. Title-case is applied afterwards (trick borrowed from @KevinCruijssen's answer).

\$\endgroup\$
  • \$\begingroup\$ Due to Title-case, McKinley outputs as "Mckinley". \$\endgroup\$ – TheJim01 Aug 22 at 20:46
  • \$\begingroup\$ @TheJim01 Thanks for reporting this. Now fixed. \$\endgroup\$ – Arnauld Aug 22 at 20:50
12
\$\begingroup\$

Excel, 1243 1206 1180 bytes

-37 bytes by subtracting from all the dates
-26 bytes by by fiddling with the subtraction values

=CHOOSE(MATCH(A1-65^4,{39805,119679,159679,239679,319679,399679,439679,519679,559679,559779,599679,639679,650084,679679,719679,759679,799790,839679,919679,959679,960294,999679,1039679,1079679,1119679,1160289,1239679,1279679,1359679,1380177,1439679,1479679,1599787,1679495,1759495,1780497,1839495,1890184,1919495,1959495,2039495,2079495,2159495,2239495,2319495}),"George Washington","John Adams","Thomas Jefferson","James Madison","James Monroe","John Quincy Adams","Andrew Jackson","Martin Van Buren","William Henry Harrison","John Tyler","James K. Polk","Zachary Taylor","Millard Fillmore","Franklin Pierce","James Buchanan","Abraham Lincoln","Andrew Johnson","Ulysses S. Grant","Rutherford B. Hayes","James A. Garfield","Chester A. Arthur","Grover Cleveland","Benjamin Harrison","Grover Cleveland","William McKinley","Theodore Roosevelt","William Howard Taft","Woodrow Wilson","Warren G. Harding","Calvin Coolidge","Herbert Hoover","Franklin D. Roosevelt","Harry S. Truman","Dwight D. Eisenhower","John F. Kennedy","Lyndon B. Johnson","Richard Nixon","Gerald Ford","Jimmy Carter","Ronald Reagan","George H. W. Bush","Bill Clinton","George W. Bush","Barack Obama","Donald Trump")

Input is in cell A1 with the format YYYYMMDD since Excel doesn't like dates before 1900.

I don't know of a compression method for the dates or names that wouldn't add more bytes. The "subtract [value] from all the dates" method could apply to anybody's solution.


I found a 1102 bytes solution in Google Sheets using the same principle. Excel doesn't have the Split function so it's not translatable.

=Index(Split("George Washington,John Adams,Thomas Jefferson,James Madison,James Monroe,John Quincy Adams,Andrew Jackson,Martin Van Buren,William Henry Harrison,John Tyler,James K. Polk,Zachary Taylor,Millard Fillmore,Franklin Pierce,James Buchanan,Abraham Lincoln,Andrew Johnson,Ulysses S. Grant,Rutherford B. Hayes,James A. Garfield,Chester A. Arthur,Grover Cleveland,Benjamin Harrison,Grover Cleveland,William McKinley,Theodore Roosevelt,William Howard Taft,Woodrow Wilson,Warren G. Harding,Calvin Coolidge,Herbert Hoover,Franklin D. Roosevelt,Harry S. Truman,Dwight D. Eisenhower,John F. Kennedy,Lyndon B. Johnson,Richard Nixon,Gerald Ford,Jimmy Carter,Ronald Reagan,George H. W. Bush,Bill Clinton,George W. Bush,Barack Obama,Donald Trump",","),Match(A4-65^4,{39805,119679,159679,239679,319679,399679,439679,519679,559679,559779,599679,639679,650084,679679,719679,759679,799790,839679,919679,959679,960294,999679,1039679,1079679,1119679,1160289,1239679,1279679,1359679,1380177,1439679,1479679,1599787,1679495,1759495,1780497,1839495,1890184,1919495,1959495,2039495,2079495,2159495,2239495,2319495}))
\$\endgroup\$
  • 2
    \$\begingroup\$ I don't know Excel too well (and my local Excel is Dutch, so I'm unable to verify), but is this correct? Doesn't this look for an exact match instead of a lower-than match for the dates? Would this output anything for let's say 19000101? \$\endgroup\$ – Kevin Cruijssen Aug 22 at 13:56
  • 3
    \$\begingroup\$ @KevinCruijssen Nope, MATCH() has an optional 3rd argument match_type that determines whether to use exact match. Excluding that argument uses the default, which is a "less than or equal to" match, so this code is correct. \$\endgroup\$ – BradC Aug 22 at 14:48
  • \$\begingroup\$ @BradC Ah, didn't knew that. Thanks for explaining! +1 from me. :) \$\endgroup\$ – Kevin Cruijssen Aug 22 at 14:51
  • 1
    \$\begingroup\$ Nice trick with subtracting a fixed value from each, I'll have to see if it helps mine too. \$\endgroup\$ – BradC Aug 22 at 20:48
9
\$\begingroup\$

05AB1E, 587 584 568 bytes

.•6}©ß þz∊‘Îнúj7a>º ·,$_+šüÑßu?PδIëàá©ā.ǝ/¬j«Ížr‹þVwô¨"¶&ˆ₃ǝαh^¼ì∞öîNÊÌ.ÚáýиÇ÷©Mèé…—¾…тŒ¹/ÈÂÓŒš/«ª³PÉÇJúΓÁ¦';X·₅ï»/„q<ƶÚÙÊtÔιuš2βƒ¼ï\~ö…3ihD·¢ðΘmζ8É9Ïγ=^$¨Ä₆ËÂÊPv5+}þ¯ÑX4hÖdÀÒuàнº₁›ǝΘ³P@¥ùnðT“É)ó_“:Èx³«äƒæ¤∞Wgþ¶š}ô|ićcÁ‘.·ƒp>Z¬Aéγê‰ù‰¥Ó₃#/›pÐT¹Â¹J3—ΛΓkÙ»(áÌ›₃z@ìqW›Â"™raÒ›₂%ïx{
_Ωb≠¹₁ľÊÌ›}çºô|ôëKÝǝÚï,‚£=A©áāY∊~"KøVóΓyΛJÚΘ·ˆUΩ₂TнîëнÐQнĆ!!¶%Ý₃ó¸ß0ûиî€AvÙ∍Õ
'«₂θSè‡H¿ÏLôǝāqaмÑIƶ%ŸSdUbåÐÉιδJ¯4₆>θçàƶñwC¨OVÀàczdRæs?5ʒP8“ƒÍÜðαŸÝf,ƒη,™`ÿeиäƵθC≠ýzX‡)и∞úø+þćÎÌвĆ挱ðí1•™„qz„K.‡„  ¡•gpöz&»XZ1rć¾{¦¯Û¿p~Θø•Ƶaв₄R«•e½òœu#ÈĆÔFƵ•Ƶ`вŽcƵ«•9…åœòFýLÂ]FÜÔĀ=Ƶ®5¿ùK»Ωм••Rwg•в««•1L₄Æ•+I‹Oè

Input is a concatenated date in the format yyyyMMdd (i.e. 20190821 for August 21, 2019).

-16 bytes thanks to @Grimy.

Try it online or verify a few more test cases.

Explanation:

We start by creating a list of the presidents in chronological order:

.•6}©...ðí1•            # Push compressed string "george washington  john adams  thomas jefferson  james madison  james monroe  john quincy adams  andrew jackson  martin van buren  william henry harrison  john tyler  james kz polk  zachary taylor  millard fillmore  franklin pierce  james buchanan  abraham lincoln  andrew johnson  ulysses sz grant  rutherford bz hayes  james az garfield  chester az arthur  grover cleveland  benjamin harrison  grover cleveland  william mcqinley  theodore roosevelt  william howard taft  woodrow wilson  warren gz harding  calvin coolidge  herbert hoover  franklin dz roosevelt  harry sz truman  dwight dz eisenhower  john fz kennedy  lyndon bz johnson  richard nixon  gerald ford  jimmy carter  ronald reagan  george hz wz bush  bill clinton  george wz bush  barack obama  donald trump"
™                       # Titlecase each word in the string
„qz„K.‡                 # Replace all lowercase "q" with "K" (for McKinley),
                        # and all lowercase "z" with "."
                        # (only lowercase letters and spaces can be compressed as string)
„  ¡                    # Split the string on "  " (two spaces)

Then we create a list of all dates as integers in the format yyyyMMdd (order is irrelevant for this list):

•gpöz&»XZ1rć¾{¦¯Û¿p~Θø• # Push compressed integer 57036763189461803778321913240836786322696217070172
  Ƶa                    # Push compressed integer 137
    в                   # Convert the large integer to base-137 as list:
                        #  [4,12,20,28,32,40,44,48,52,56,60,64,72,80,84,88,92,96,100,112,116,124,132,136]
     ₄R                 # Push 1000, and reverse it to "0001"
       «                # And concat it to each item:
                        #  [40001,120001,200001,280001,320001,400001,440001,480001,520001,560001,600001,640001,720001,800001,840001,880001,920001,960001,1000001,1120001,1160001,1240001,1320001,1360001]
                        # (this is for all the March 4th dates)
•e½òœu#ÈĆÔFƵ•           # Push compressed integer 47362342587646909879438102
  Ƶ`                    # Push compressed integer 223
    в                   # Convert the large integer to base-223 as list:
                        #  [155,163,171,179,183,191,195,203,211,219,222]
     ŽcƵ                # Push compressed integer 9817
        «               # And concat it to each item:
                        #  [1559817,1639817,1719817,1799817,1839817,1919817,1959817,2039817,2119817,2199817,2229817]
                        # (this is for all the January 20th dates)
•1厨£ÆÊÂç-i∞YúΛȾEW½Ω≠tW•
                        # Push compressed integer 42494608868313599134973321717434089414197466371857150907
  •Rwg•                 # Push compressed integer 1770507
       в                # Convert the large integer to base-1770507 as list:
                        #  [440101,530406,680112,840616,1040611,1260499,1480109,1660819,1770506]
                        # (these are the remaining dates; i.e. those who died earlier)
««                      # Merge the three lists together:
                        #  [40001,120001,200001,280001,320001,400001,440001,480001,520001,560001,600001,640001,720001,800001,840001,880001,920001,960001,1000001,1120001,1160001,1240001,1320001,1360001,1559817,1639817,1719817,1799817,1839817,1919817,1959817,2039817,2119817,2199817,2229817,440101,530406,680112,840616,1040611,1260499,1480109,1660819,1770506]
  •1L₄Æ•                # Push compressed integer 17970302
        +               # Add it to each item in the list:
                        #  [18010303,18090303,18170303,18250303,18290303,18370303,18410303,18450303,18490303,18530303,18570303,18610303,18690303,18770303,18810303,18850303,18890303,18930303,18970303,19090303,19130303,19210303,19290303,19330303,19530119,19610119,19690119,19770119,19810119,19890119,19930119,20010119,20090119,20170119,20200119,18410403,18500708,18650414,18810918,19010913,19230801,19450411,19631121,19740808]

Then we use the input to determine the output president-name based on the dates in the list:

I‹                      # Check for each value in the integer-list if the Input is smaller
                        # (1 if truthy; 0 if falsey)
  O                     # Sum these to get the amount of truthy values
   è                    # And use that to (0-based) index into the president-names list
                        # (after which the result is output implicitly)

See this 05AB1E tip of mine (sections How to compress strings not part of the dictionary?, How to compress large integers?, and How to compress integer lists?) to understand how all the compressed string, integers, and lists work.

\$\endgroup\$
  • 1
    \$\begingroup\$ @Grimy I couldn't really copy it, so had to compress it myself again after I saw what you did. I checked every president name, and all letters were taken. But nice way to save bytes by first titlecasing, and then using lowercase letters which aren't present anymore to convert to the dots and uppercase letter. Thanks for -16! \$\endgroup\$ – Kevin Cruijssen Aug 22 at 15:05
  • \$\begingroup\$ Lots of those names are dictionary words, which leads to large improvements. As a start, here's -32 \$\endgroup\$ – Grimmy Aug 22 at 15:28
  • 1
    \$\begingroup\$ @Grimy Will perhaps try that approach somewhere next week. Currently about to eat, and tomorrow I'm way to busy with work due to a deadline. \$\endgroup\$ – Kevin Cruijssen Aug 22 at 15:34
  • 1
    \$\begingroup\$ 464. This is still improvable, but I don't think it can beat Jelly's 426. Their string compression is just better. \$\endgroup\$ – Grimmy Aug 23 at 14:02
12
\$\begingroup\$

T-SQL, 1169 981 979 977 bytes

Holy cow, I figured out string compression in SQL (available in SQL 2016 and above):

SELECT TOP 1 STUFF(value,1,8,'')
FROM d,STRING_SPLIT(
    CAST(DECOMPRESS(CAST('H4sIAAAAAAAEAHVT23LaMBD9FX1AxiMZg+1HIAWGhDaltMz0bYMXrEaWOmsc6r/vrpw27kOHB8ZnL+fs2VWqTa6NKe+DB1epA3XNz7tU61LABRCcXtSnZ2hAQCPgGgNdUB0Tteja+s6U5STmWufU0ll/DZ7BohzlbpJRehG77Ae+PcIFJD+PKra2aXq1BLoiCZjpQhdrJEldBaoYm8XGe3uqgSr10f6KdLOJMal57H0VvFokahtq3w6RSCffapWoB/Qeq57xaVR9f7OX+qruE/XBtujrcIvE2VRnxmyAqFdfkuhKVDmZaP6tCPwLTypl+xBafEV35WhaSnSD9Ix0VZsQXmOzdMJTmCW4Vy5ZhuBsdUHBjaQfmQS9WieK6SrrLxwxkeYYQkXhpo7WDaPo2J8/nYWG+9/EgQOchZt3w2WHGkMVCMeyijIfl+1OD9Y77CUQadYkOnl1kg+ePS6KSLRA/wMa1iw+2CihKKb/KxH+Ylljy6tT80TN6Vp3NES4ZAsNtoKvgc4WndTkUdi+u9ZIZ96uLG4DPbYcm0UJX13ftlzHO1iz6TLNTFaTzX1FeHtfczGLLPNngpqHfLT+FJzg0/ydfdHx0XiI8L+LfLJIJxRc61wXO/ZKvF3xf8N2ciCLer6DnF3PpvcuyHDZ9L39Q6KegnsR1OiMUbm5Q++QBmi8O/TcZeTrJMrc8eGzmm/AN9zxVXBguKk/4/JrHPLTgVcYPnc8bK/mFTRinBkNvAuegqgfLucNhOqNVEdNhzo00Kotns9IMZAPFxO7v7XN+SSy9O/bh7bmS+WX/hut0W9jPwQAAA=='as XML).value('.','varbinary(max)'))AS varchar(max)),',')
WHERE LEFT(value,8)<i

Doesn't save quite as much as I hoped it might, probably due to the amount of code it takes to convert/deconvert.

Here is the original version, which is equivalent to the code that runs after the encoded string is decompressed (1169 bytes):

SELECT TOP 1 SUBSTRING(value,9,99)
FROM d,STRING_SPLIT(
    '20170119Donald Trump,20090119Barack Obama,20010119George W. Bush,19930119Bill Clinton,19890119George H. W. Bush,19810119Ronald Reagan,19770119Jimmy Carter,19740808Gerald Ford,19690119Richard Nixon,19631121Lyndon B. Johnson,19610119John F. Kennedy,19530119Dwight D. Eisenhower,19450411Harry S. Truman,19330303Franklin D. Roosevelt,19290303Herbert Hoover,19230801Calvin Coolidge,19210303Warren G. Harding,19130303Woodrow Wilson,19090303William Howard Taft,19010913Theodore Roosevelt,18970303William McKinley,18930303Grover Cleveland,18890303Benjamin Harrison,18850303Grover Cleveland,18810918Chester A. Arthur,18810303James A. Garfield,18770303Rutherford B. Hayes,18690303Ulysses S. Grant,18650414Andrew Johnson,18610303Abraham Lincoln,18570303James Buchanan,18530303Franklin Pierce,18500708Millard Fillmore,18490303Zachary Taylor,18450303James K. Polk,18410403John Tyler,18410303William Henry Harrison,18370303Martin Van Buren,18290303Andrew Jackson,18250303John Quincy Adams,18170303James Monroe,18090303James Madison,18010303Thomas Jefferson,17970303John Adams,17890429George Washington',',')
WHERE LEFT(value,8)<i

Line breaks are for readability only.

Input is taken from pre-existing table \$d\$ with INT field \$i\$, per our IO rules. Input date is formatted as an 8-digit number YYYYMMDD.

A few tricks I used to save bytes:

  • I sorted the presidents descending so I didn't have to add an ORDER BY to the code
  • I subtracted 1 in the "start" date of each term, so I could use < instead of <=
  • String-split is much shorter than a big list of VALUES() would be, even though I have to then break the string apart with SUBSTRING and LEFT.
  • EDIT: Saved 2 bytes by changing SUBSTRING() to STUFF()

Using Base64-encoded compressed strings in SQL

(Added to SQL Tips thread)

So Microsoft added a COMPRESS and a DECOMPRESS function back in SQL 2016, which handles the GZIP; the problem is that it returns a VARBINARY, which although shorter in bytes (when stored in a SQL VARBINARY field), is longer when displayed in characters (raw hex), which makes it unsuitable for golfing.

Converting to Base64 is clearly the answer, but finding a short, simple implementation was a challenge. I based my version off of this old answer on SO, which gives us most of what we need, although it doesn't use the new GZIP functions. I just had to insert the new functions into the right place, and golf it down a bit.

To use this method in your own code:

--Run this to generate your compressed string:
DECLARE @s VARCHAR(MAX)='Your really long string goes right here'
SELECT CONVERT(VARCHAR(MAX),(SELECT CONVERT(VARBINARY(MAX),COMPRESS(@s))FOR XML PATH(''),BINARY BASE64))

--Use your compressed string and the following code to get back to the original:
DECLARE @e VARCHAR(MAX)='H4sIAAAAAAAEAIvMLy1SKEpNzMmpVMjJz0tXKC4pygRS6fmpxQpFmekZJQoZqUWpAGGwW5YnAAAA'
SELECT CAST(DECOMPRESS(CAST(@e as XML).value('.','varbinary(max)'))AS varchar(max))

That's 75 73 extra bytes of code to decompress an encoded string, so clearly only use this for very long strings.

EDIT: Saved 2 bytes in the decompress code with CAST instead of CONVERT.

\$\endgroup\$
5
\$\begingroup\$

Jelly, 454 bytes

“¡#<Ḷ“¡D{“ß“®“c“ƒⱮ“¡“(Ȥ“u^“£“ɠn“ƒ⁺“¥“¢r“ƈ⁶“©“ƙm“¡B⁻“¤“Pẋ“ḣ¢“¡“¡ẓk“¡CẆ“¢“S¢“ėẋ“ṄỴ“t<“Œ“¦’ḃ2$¹<?€ȷ2F4ȷ4,8ȷ4ĖF¤yÄ<⁸TṪị“€`ɲ×ƥF7ȯẒ⁼ẈẎu⁻ɠṇẠẈƊ⁻QḲỌ ỊƭʠµḢƊCṾr⁻=ßạḌ`^ḌX§®tṭN£jx,ƈ=suĖɼ_ḍf9*ÆṙỊṪṄ Jʋ ȯṡẉ ỌẏⱮøÞ⁴xḤżḅñ£ṡṭʂMṚ¶ṇwıƲṁEnÄ`:®ƥʂ_xd⁶ŒĖṁƙƝg°ṂʠkṫhO5Ịḅḳ³'ø⁵aẏṄKḂẆZØ4JḌþḂ⁸⁸XlIVḤOḲØṢÐ!}?Ọ°ḲẆiḢAr`ġƘ⁸ḷ[¿T§ẓ⁵|ḍdɓ^ṭƲfỴĖġJw(Ȯ:⁺k=£ŀnṗ*'hẹḋŻZOLæزẋ⁼ẏ&ı6ḣṗẈƥ¡:9D¢=G§⁴eỤ6wẈ6ṗw6⁺zOẉ}OṆƲdṃ'ıẠ£¤þ4¢1ȷfɓ.ṪpṀ⁴Ṡtṁ⁷ẇlŒ!ṠyaṪ66xvḍgġ¤goḍRẒ³żẎịṣ6ĿⱮ}ḲkƒiL²?Ḃ¿ḥƝ¤dėḤ½Ṗ,cRÐþɼ©ṢƈḅṬḊṬɠṅÞ»Ỵ¤

Try it online!

A monadic link taking as its argument the date in YYYYMMDD format and returning a string with the answer.

Test cases (borrowed from @KevinCruijssen’s 05AB1E answer).

\$\endgroup\$
2
\$\begingroup\$

Charcoal, 550 bytes

✂⊟Φ⪪”}¶⟲φε"1It↙θ|&s1%⎚÷X2J¦T↶M↙@P≡,7gSC{WTB¿μ;↗AEoU…⁹aⅉ:(↶Þ|‹Cρr]χY↨×⪪…✳μⅉⅈ²]⌈&ρτ“↖s∕↘yⅉ⊘K%QUi&Uρ⦃→↑^_tZ}↙s⪪3#\UZ¶L↥ρ÷Qa.ρE⊞B↘¿⦃{RC⁴βLΦï←⁹″*²⌊∕~L‽∧&;⁵⪪⪪◨sFψ⊗=₂εωb5⎚∧¬Ii»S⟲H⧴⮌⁵↷≕≦-Lκ↗⦃″✂DcgSOE}PΣ℅ξ»u➙ïA⁼×◧⁴Gθkιbσ6�V→↓B⮌⦃]σ0↶L↷'Þ¡σ?αδ⪫4⁶M"‽W◨-n℅O≡o ⊙^fκ{~✳N⦄y⊟≦Kθ!«↘pB;fJ<ιU%D‴▶p|‹⌕ιHpIt‽7}u1~φνL▶⮌;NY✂S>ÞSλ<«⦃¬k⦄J⦃◧‴}v≕﹪φEβ<⁴↘la»�λ⁼.Xξ.th⊕jEχ>m4J'⁺▷αZ↷|D$⸿Sz⪪←fFωρ↓oⅉ⊙⁰vFQ0T⪫?GE▷|℅±P;χ'|x>i↨E◧⁺4M↖‴№⟦Π~‹σ_▷⁵N?6ⅉ |x+\⁺“≡C⟦⁹⁸pC⊕Dïψ?◧⎇ςΠH&]▷≧β↓⧴J<(1←¦6‽GG✂¡58Go…Qψ/§§c↷ZQ\@ςr⁹}TZ?«fPO)⧴\`↘℅⦄&yθ%⪫iλ*fÀ-ⅈ↖→◨⬤F″‖↘→⁹S#″▶Φ∨¬w◧«℅ySq§mCIπF?sⅈP⍘↷≔f‽k↥ABMX﹪”¶‹ιθχ

Try it online! Link is to verbose version of code. Takes input in ISO format. Explanation:

    ”...”       List of decremented dates and presidents
   ⪪     ¶      Split on newlines
  Φ       ‹ιθ   Keep those that precede the input
 ⊟              Take the last
✂            χ  Remove the date
\$\endgroup\$
3
\$\begingroup\$

SOGL, 475 bytes

⁵æ“DƧ▓«ļ¶↕Q∫<⅔∑+fQyΛ‼Bī:׀═&Sf',№═׀ΔΥκ\κΗδ=6oΡΠω«i℮ī K }½6YΨδ~░pTø№ŗ◄&Λθ▒“Æš“─{1α:C'⁰%+:"⅞“*c'⁰÷+dr"⅞“*b'«*e++>?al"t!■u↔R⅝Θνj╤←⁵κP׀λc⅜-Gc⁸׀!┐)└█5¦@T¬[@∫↕‛ρ℮↑δŗιf√³I2~Δ▓η¤⁴b¡νθ@36⅛Π└Ξ±Ƨ⅜⅓mwθ:∫^⌠≥-N\T‛V;r□τθ⁹;C{¾lΠƨUΒΡ║⁸Κ≤øΔ°?U┼S→iļ┐Kπzz∑Θ⅛%τ`ωΗ2D≡ψ_;OR⁴w≡1Z⅓ēυ%─ž′ιVJοUζķπd└≈³ΘΟ‚GR2┌═NΒθ↔T²νsσ□lQMæν÷¦Π±°≡═øΡTe¼ž⁰λ_►○³1≡№╚█λΜβΤ½<Π±Cļ¬└⁴┘čgr⁰⁄▲8|}⁸ē4№╤#√⅔d?÷≥}▼eī┼^ƧX‽>≥▼k ¹Wļm║⌠¦→┘C׀ψΠ¼⁽tΠ↔:φbεļ▓Β√⁷->→⅜O∑░=`ξε↕ņ⅛╚πBπσ§T׀ķīT:‽4;%≥═pP¶G→○▼φβjτ9v⁄6Υ◄⁹¤{τ/∑a⁰}┐⁵e¬č‘ūƧkiƧKiŗƧ, Θw←

Try it here!

Date logic could probably be improved a bit.

\$\endgroup\$
2
\$\begingroup\$

Stax, 550 509 502 bytes

ª╠TkªÑTs¬¢‼É▼╠→+╕s☼∩b°┴ò0J Öª◙%µ♪)Çb○Σ²╦àôä√P┼[╫»↓♪─y·:+x/ p~┤☺kèT┤╩☺♀◄╗*DX○e╩+ë%╫↔^║;◙/Θ╛B║K>▌GΣR╥♠╞N┬6dt♥h♪T⌠╥⌠ó←`±ΘÆM:\V►╢◘≥pe½╖→Ea}╚≤╠ΓÜ╗,πUF[╢▄¥¥▒t≥òK"=☺S╟▐ü%û▼98╕→→ñ`eB▌y↨\%Ç│╝û°6R┘K√â°◘RfçMñ♪3╦┤â╞╥┼«╧j/εⁿ○ó▀CäI3┘c▄}═%[C_%jgÿÉJÑS═g(┴`╦%êk9½é╔PT¶◄<║╕à¼╬≤`dεµc╨╔?Z=╧╥RDΓl.┘uFⁿ∟Juö♥,╠╛z¡ÇM7m☺╩?ïPª$πä♂ ╝Jò'æφ▬♠w►○ôr├=é┴╪ù#?∩E↓╣J∩╒░▒○LÑ∞¥╗å▐Ü└ä∙↨l♀╠├d┴Uÿ╩(╔♦)═╦¢αe£/bΦ╜%d$Öä¢M║╖q]¢╝8╨ÖBÿ┼÷{@0╕/#└â╪~V§πp<≡k♫á∩g4üÉà↔DR[√á√ü.îºV'X♥9↔øiè²≈τoæ┴0☻ó╪!‼⌡¼'↔ δ'X⌂■OpX¬E╡░├a"√4lB<└♣A╪º╕4íbz♠ìÿ°Γ═àÅ└5äº5æ2§ΩWª

Run and debug it also featuring Kevin Cruijssen's tests

This program executes correctly, but if you use the "Uncompress Literals" tool, it will corrupt the source code. It ends up putting two integer literals right next to each other, which makes one bigger literal. Of course, that doesn't do the same thing as the original program.

\$\endgroup\$
7
\$\begingroup\$

Jelly,  431 428 427  426 bytes

“¡Ẹị’ḃ4ż“ƓĠƒƝƊ!ɓa(‘ḅ⁹
“FQIȥ’ḃ8Ėẋ/€<8ż¢F1,303yo119
“f×Ð<Mk7LqƇ%_¡¤cċ⁴ẏ’Do13’⁽¤.;Äż¢ḅȷ4<VSị“¡ṀÑṅyȮÇæjRṂ~ɠƥ⁺'Ḃġ"Ƈ~Ị'9ƒȮṃ$ḶPȯṅṡḊl¥JƊ€ẊḥSṣọwɦṡ5ėṂU #Fɲẓ÷iḄþ%~%ñçŒfƒƙɼ=ɓ⁼¡⁻Q`⁵¡ḍ36)żȥÑR\ḋ⁾ḶƤ0ÞṘḳ÷¦IṂ\}ƊĊÐḳŻƈɦ!zɠ⁺ƈṖṭW⁸ƥṛU|ḄØ^ẓfḂḣƈCȦ8ɱḤH⁵AKṢzȯỵƭḊ:TʠƬ/~ƝÑȥgṖ(ṁȯDƲṫỴftlBOȧ6Ụiṃıẉ_ƈvh5ṄUɓạẓDẠẸıṣƥ"bçȥ¿çOġQẹİẊẸs*⁶ż,Ḍg®ƲW×ɗ,ẏ¡Ḅ5M5)ṀạƈCṛʂẎŒƬwġ⁶NẠṆRƇsẊ<fŀȯ⁵øȤ\⁾.>ḋTṖĠUṇŻṬTṖræ_TçṡȤOʠƥðȦe]ƈ⁵cṆWƭƲ>`½n¿O¡ṭOþV¤ṡẊ²rdS€ė)ƘIÆ&ṙḞ¬5[pṁȥLṘVỴɠ»ḲṚƑ”.ẋṭƲ€KỴ¤

A full program accepting a string YYYYMMDD which prints the president's name.

Try it online! Or see (Kevin Cruijssen's) test-suite.

How?

“¡Ẹị’ḃ4ż“...‘ḅ⁹ - Link 1, getNonStandardEndMonthDays: no arguments
“¡Ẹị’           - base 250 literal       = 106467
     ḃ4         - to bijective base 4    = [1,2,1,3,3,3,1,4,3]
        “...‘   - code-page indices      = [147,196,158,150,145,33,155,97,40]
       ż        - zip together           = [[1,147],[2,196],...,[3,40]]
              ⁹ - built-in literal       = 256
             ḅ  - from base (vectorises) = [403,708,414,918,913,801,411,1121,808]

“FQIȥ’ḃ8Ėẋ/€<8ż¢F1,303yo119 - Link 2, getEndMonthDays: no arguments
“FQIȥ’                      - base 250 literal    = 1114518671
      ḃ8                    - to bijective base 8 = [8,2,3,3,4,3,2,2,1,7]
        Ė                   - enumerate           = [[1,8],[2,2],[3,3],[4,3],[5,4],[6,3],[7,2],[8,2],[9,1],[10,7]]
           €                - for each:
          /                 -   reduce with: 
         ẋ                  -     repeat          = [[1,1,1,1,1,1,1,1],[2,2],[3,3,3],[4,4,4],[5,5,5,5],[6,6,6],[7,7],[8,8],9,[10,10,10,10,10,10,10]]
            <8              - less than 8?        = [[1,1,1,1,1,1,1,1],[1,1],[1,1,1],[1,1,1],[1,1,1,1],[1,1,1],[1,1],[0,0],0,[0,0,0,0,0,0,0]]
               ¢            - call last Link (1)  = [403,708,414,918,913,801,411,1121,808]
              ż             - zip together        = [[[1,1,1,1,1,1,1,1],403],[[1,1],708],[[1,1,1],414],[[1,1,1],918],[[1,1,1,1],913],[[1,1,1],801],[[1,1],411],[[0,0],1121],[0,808],[0,0,0,0,0,0,0]]
                F           - flatten             = [1,1,1,1,1,1,1,1,403,1,1,708,1,1,1,414,1,1,1,918,1,1,1,1,913,1,1,1,801,1,1,411,0,0,1121,0,808,0,0,0,0,0,0,0]
                 1,303      - pair literal        = [1,303]
                      y     - translate           = [303,303,303,303,303,303,303,303,403,303,303,708,303,303,303,414,303,303,303,918,303,303,303,303,913,303,303,303,801,303,303,411,0,0,1121,0,808,0,0,0,0,0,0,0]
                        119 - literal             = 119
                     o      - logical OR          = [303,303,303,303,303,303,303,303,403,303,303,708,303,303,303,414,303,303,303,918,303,303,303,303,913,303,303,303,801,303,303,411,119,119,1121,119,808,119,119,119,119,119,119,119]

“...’Do13’⁽¤.;Äż¢ḅȷ4<VSị“...»ḲṚƑ”.ẋṭƲ€KỴ¤ - Main Link: list of characters, X
“...’                                     - base 250 literal    = 5999595155245555951555559593750993764595999
     D                                    - to base 10          = [5,9,9,9,5,9,5,1,5,5,2,4,5,5,5,5,9,5,1,5,5,5,5,5,9,5,9,3,7,5,0,9,9,3,7,6,4,5,9,5,9,9,9]
       13                                 - literal             = 13
      o                                   - logical OR          = [5,9,9,9,5,9,5,1,5,5,2,4,5,5,5,5,9,5,1,5,5,5,5,5,9,5,9,3,7,5,13,9,9,3,7,6,4,5,9,5,9,9,9]
         ’                                - decrement           = [4,8,8,8,4,8,4,0,4,4,1,3,4,4,4,4,8,4,0,4,4,4,4,4,8,4,8,2,6,4,12,8,8,2,6,5,3,4,8,4,8,8,8]
          ⁽¤.                             - literal             = 1797
             ;                            - concatenate         = [1797,4,8,8,8,4,8,4,0,4,4,1,3,4,4,4,4,8,4,0,4,4,4,4,4,8,4,8,2,6,4,12,8,8,2,6,5,3,4,8,4,8,8,8]
              Ä                           - cumulative sums     = [1797,1801,1809,1817,1825,1829,1837,1841,1841,1845,1849,1850,1853,1857,1861,1865,1869,1877,1881,1881,1885,1889,1893,1897,1901,1909,1913,1921,1923,1929,1933,1945,1953,1961,1963,1969,1974,1977,1981,1989,1993,2001,2009,2017]
                ¢                         - call last Link (2)  = [303,303,303,303,303,303,303,303,403,303,303,708,303,303,303,414,303,303,303,918,303,303,303,303,913,303,303,303,801,303,303,411,119,119,1121,119,808,119,119,119,119,119,119,119]
               ż                          - zip together        = [[1797,303],[1801,303],[1809,303],[1817,303],[1825,303],[1829,303],[1837,303],[1841,303],[1841,403],[1845,303],[1849,303],[1850,708],[1853,303],[1857,303],[1861,303],[1865,414],[1869,303],[1877,303],[1881,303],[1881,918],[1885,303],[1889,303],[1893,303],[1897,303],[1901,913],[1909,303],[1913,303],[1921,303],[1923,801],[1929,303],[1933,303],[1945,411],[1953,119],[1961,119],[1963,1121],[1969,119],[1974,808],[1977,119],[1981,119],[1989,119],[1993,119],[2001,119],[2009,119],[2017,119]]
                  ȷ4                      - literal 10^4        = 10000
                 ḅ                        - from base           = [17970303,18010303,18090303,18170303,18250303,18290303,18370303,18410303,18410403,18450303,18490303,18500708,18530303,18570303,18610303,18650414,18690303,18770303,18810303,18810918,18850303,18890303,18930303,18970303,19010913,19090303,19130303,19210303,19230801,19290303,19330303,19450411,19530119,19610119,19631121,19690119,19740808,19770119,19810119,19890119,19930119,20010119,20090119,20170119]
                     V                    - evaluate (X)        (i.e. X -> YYYYMMDD)
                    <                     - less than? (vectorises)
                      S                   - sum                 (a number between 0 and 44 inclusive)
                                        ¤ - nilad followed by link(s) as a nilad:
                        “...»             -   compression of dictionary words and strings
                             Ḳ            -   split at spaces
                                     €    -   for each (part):
                                    Ʋ     -     last four links as a monad:
                               Ƒ          -        invariant under?:
                              Ṛ           -          reverse (true for initials only)
                                ”.        -        literal = '.'
                                  ẋ       -        repeat
                                   ṭ      -        tack (the part - e.g. [['A'],'.'])
                                      K   -   join (back up) with spaces
                                       Ỵ  -   split at newline characters
                       ị                  - index into (that list) (1-indexed & modular)
                                          - implicit (smashing) print
\$\endgroup\$
  • \$\begingroup\$ Plus One from me. This looks amazing \$\endgroup\$ – MilkyWay90 Aug 23 at 19:53
  • \$\begingroup\$ Thanks! Took quite a while to put together. \$\endgroup\$ – Jonathan Allan Aug 23 at 19:56
15
\$\begingroup\$

Bash, 1229 1124 bytes

-103 bytes with @GammaFunction's excellent comments, removing a couple of unproductive substitutions (Adams), and refactoring the code to use the date offset from the previous date rather than the absolute date for each presidency.

M=(. Ja F Mar Ap May Jun Jul Au S O N D)
A=40000
B=80000
s=son
a=James
c=Andrew
d=William
e=Harri$s
f=Franklin
g=George
h=Grover#Cleveland
i=Roosevelt
j=John
k=#W.#Bush
X="304:$g#Washington
$A:$j#Adams
$B:Thomas#Jeffer$s
$B:$a#Madi$s
$B:$a#Monroe
$A:$j#Quincy#Adams
$B:$c#Jack$s
$A:Martin#Van#Buren
100:$d#Henry#$e
39900:$j#Tyler
$A:$a#K.#Polk
10405:Zachary#Taylor
29595:Millard#Fillmore
$A:$f#Pierce
$A:$a#Buchanan
40111:Abraham#Lincoln
39889:$c#$j$s
$B:Ulysses#S.#Grant
$A:Rutherford#B.#Hayes
615:$a#A.#Garfield
39385:Chester#A.#Arthur
$A:$h
$A:Benjamin#$e
$A:$h
40610:$d#McKinley
79390:Theodore#$i
$A:$d#Howard#Taft
$B:Woodrow#Wilson
20598:Warren#G.#Harding
59402:Calvin#Coolidge
$A:Herbert#Hoover
120108:$f#D.#$i
79708:Harry#S.#Truman
$B:Dwight#D.#Eisenhower
21002:$j#F.#Kennedy
58998:Lyndon#B.#$j$s
50789:Richard#Nixon
29211:Gerald#Ford
$A:Jimmy#Carter
$B:Ronald#Reagan
$A:$g#H.$k
$B:Bill#Clinton
$B:$g$k
$B:Barack#Obama"
T=($1)
D=0${T[1]%,}
for((;;)){ [[ $T =~ ${M[++i]} ]]&&break;}
N=0$i
S=$[${T[2]}-1797]${N: -2}${D: -2}
for z in $X;{ O=$[O+${z%:*}];[ $S -lt $O ]&&z=${z//#/ }&&echo ${z#*:}&&exit;}
echo Donald Trump

Try it online!

A lot of manual compression :)

\$\endgroup\$
  • \$\begingroup\$ A few more: Get rid of X=($X), looping as for z in $X will split $X on $IFS. Use [ -lt ], and use $T instead of ${T[0]}. Last few lines, overall should be 1191 bytes \$\endgroup\$ – GammaFunction Aug 23 at 0:47
  • \$\begingroup\$ 1092! I simplified the month parsing (for example, if we've passed June and it starts with a J, it must by July. I also changed the test to [ ${T#${M[++i]}*} ]. Now we can leave off December completely). I also included the leading : on a few of the names (doing this for :John meant making all delimiters : instead of #). \$\endgroup\$ – GammaFunction Sep 27 at 2:17
3
\$\begingroup\$

PHP, 888 bytes

$_=0;$l=explode('|',gzinflate(substr($a=base64_decode('AAALMQW0C2oLagtqBbULagW1AB8FlgW1AewDyQW1BbUF3wWLC2oFtQDHBO4FtQW1BbUGdgqoBbULagNxB/kFtRFGCxgLagQMB14H6wN/BbULagW1C2oLagtqZVLtjtpADHyVfYK8Ax8FBEd7pWmR+s9kTXbLxq68CXSlffjaheNO6q8o6/HMeOw1svTojpBDpH5kqlsO5GYehlzbwANkt8XzGSVbDQbMbg8+fvhjEsZ729cpUlce3TPygje3he5i6D3IGMn9AHLzSZDqMaYUYXAbJCluAyJ3ViNqS0J5COwa98rpUn9CF0CRLZTEUvfaDuLdSr8DC9aVAF2SSrxGlA4f3fNJuwiozk4CQeVe1CInetpTOZP9nkrOiv/WuLUSjfUwjQHlzCoxb9RewfygnCkE5Bwx+boImEcUe5vJGCapa+GrPiwSXjEB+TpH+gWD+nqO+B/kLYp9t4uUsGjyyF6HcgfmbKjxPS6+2dgtnPWN2QvfnNaM96gCSG5tdsXrPusC0lWVF8wp+h7rBuWEMiqJOXiPbNl8UDKfxYJoZRo0ueUt9mE0zKeYkQLfbDe2plXjdkiEvtSXQp7JonpL9BBtX959jn9sZhRIui3Ns27jMBS30INQogOTFQ4IPRjs3z1uGndsdHc51LnOrVFFGvlZftZA9LrclxMMUJd3IjP9+y8='),90)));foreach(str_split(substr($a,0,90),2)as$i=>$d)(strtotime($argn)+5701449600)/86400<($_+=hexdec(bin2hex($d)))&&@die($l[$i-1]);echo end($l);

TRY DEMO

\$\endgroup\$
3
\$\begingroup\$

05AB1E, 464 444 442 418 bytes

-15 or so bytes by stealing ideas from Kevin Cruijssen's answer

Crossed 444 is still 444 ):

.•J@λ
A∞‚XÃUδ„«›Æx…ΔΣ¸ÃEÛö›³;Î!¦ǝzŽ`²œ∊ïøÞ‰Cf4₆и)Kuм¹5®‹м£Ž}мNPõüïí
^ā-Ǩåˆ[Ü_5δ³ÂBмzIΣŠÒÅÆè"²0¢₆'$Ćùù»õJ´õý¢ºн³õ?ëØ؆Dǝç.r˜èÌ•ć¡`“ŒÕ‡¹„б·Ž²¿É‰Þ³×‰Þ̯„Ðëìncy±·¢Œžˆ–ÄîèÿíÈ£ÎÈœ„ÐÕÀ‰Þ kz™éÿ¥•¹êardœãÿ²ÀâÓ‰Þÿ㳫ƢŒš•ÿ—§Î¶ÿ橉ޖÖÿל–Ö·Š¶‹r¯ŽÇÕÈœ¶‹r¯ŽíÈÿíÈ©Æ»äft–œrow¦‹¼‰ gz†èingãŸîÁÿ²Àÿ„Ð fz½¸ÿš••Öÿéï™»»É»‰ÖŠÿŒÕÕ¹ wzŒ›‰ŽµÍŒÕ wzŒ›‹²ÿ¹Ñÿ“™„qz„K.‡#•¥ü„¨%¨₃Ó8•3в4α£ðý•9ÕS&µç©•3в±žD*•¾¹iìzÓ.+,âšÜĀ‘ó₆x.»δ•žHв«9._.¥•U<¶•+I32β‹Oè

Try it online!

Part 1: the names

There are two types of string compression in 05AB1E:

  • Base-27 strings encode each letter in ~0.6 bytes (technically: log(27) / log(255)), but they can only contain [a-z ] (lowercase letters and spaces).
  • Dictionary strings encode common English words (plus the preceding space) in 2 bytes, and all ASCII characters in 1 byte each (they're just passed through unmodified). They can also use the byte ÿ, to pop a value from the stack and embed it in the string.

We're going to use an optimal mix of both. Since switching from one encoding to the other incurs some overhead, this is more complex than picking the shortest encoding for each individual name. For example:

  • The ing in Harding Calvin takes ~1.8 bytes in base-27 vs 3 bytes in a dictionary string. But Hard and Calvin are both in the dictionary, so we end up leaving ing uncompressed inside a dictionary string.
  • The Herb in Coolidge Herbert Hoover takes ~3 bytes in base-27 vs only 2 in a dictionary string (since herb is in the dictionary). But neither Coolidge nor Hoover are in the dictionary, so we end up encoding Herb as base-27.

To get around the restriction that base-27 strings can only contain [a-z ], we assign special meanings to some letters. Between them, the 44 presidents use up all 26 letters, but we can still play tricks:

  • The only js are in dictionary words (James, Benjamin, ...), so j is free for base-27 strings.
  • The only q is in Quincy, so lowercase q is free
  • The only z is in Zachary, so lowercase z is free
  • The only x is in Nixon, so uppercase X is free (we don't actually make use of that)

With that said, let's look at the code.

.•J@λ
A∞‚XÃUδ„«›Æx…ΔΣ¸ÃEÛö›³;Î!¦ǝzŽ`²œ∊ïøÞ‰Cf4₆и)Kuм¹5®‹м£Ž}мNPõüïí
^ā-Ǩåˆ[Ü_5δ³ÂBмzIΣŠÒÅÆè"²0¢₆'$Ćùù»õJ´õý¢ºн³õ?ëØ؆Dǝç.r˜èÌ•

# (The newlines are significant.) This is the base-27 string:
# "j trumpjack obamaj reaganj nixonj lyndon bzj dz roosevelt harry sz truman dwight dz eisenhowerjidge herbert hooverj mcqinley theodore rooseveltj garfieldjerford bzj ulysses szj buchananjmorejlk zacharyj buren"

ć    # extract the first character
 ¡   # split the rest on that character (a "j")
  `  # dump the list on the stack
# We now have " buren" at the top of the stack, and " trump" at the bottom.

“ŒÕ‡¹„б·Ž²¿É‰Þ³×‰Þ̯„Ðëìncy±·¢Œžˆ–ÄîèÿíÈ£ÎÈœ„ÐÕÀ‰Þ kz™éÿ¥•¹êardœãÿ²ÀâÓ‰Þÿ㳫ƢŒš•ÿ—§Î¶ÿ橉ޖÖÿל–Ö·Š¶‹r¯ŽÇÕÈœ¶‹r¯ŽíÈÿíÈ©Æ»äft–œrow¦‹¼‰ gz†èingãŸîÁÿ²Àÿ„Ð fz½¸ÿš••Öÿéï™»»É»‰ÖŠÿŒÕÕ¹ wzŒ›‰ŽµÍŒÕ wzŒ›‹²ÿ¹Ñÿ“
# Dictionary string. All the values we just dumped on the stack are popped by `ÿ`s in this string. We end up with:
# "george washington john adams thomas jefferson james madison james monroe john quincy adams andrew jackson martin van buren william henry harrison john tyler james kz polk zachary taylor millard fillmore franklin pierce james buchanan abraham lincoln andrew johnson ulysses sz grant rutherford bz hayes james az garfield chester az arthur grover cleveland benjamin harrison grover cleveland william mcqinley theodore roosevelt william howard taft woodrow wilson warren gz harding calvin coolidge herbert hoover franklin dz roosevelt harry sz truman dwight dz eisenhower john fz kennedy lyndon bz johnson richard nixon gerald ford jimmy carter ronald reagan george hz wz bush bill clinton george wz bush barack obama donald trump"

™         # title case
 „qz      # literal "qz"
    „K.   # literal "K."
       ‡  # transliterate (replaces all "q" with "K" and all "z" with "."

# This takes care of two issues at once: title casing would leave McKinley with a lowercase k, and base-27 strings can't contain "."
# We now have a long string, with all the presidents' names in order. We need to split it into 45 strings (one per president).
# We could've used a special marker to delimit the presidents, but it turns out it's more efficient to count the words in each name:

#                  # split on spaces (yes i know i've been using # for comments, but there's no actual comment character in 05AB1E)
 •¥ü„¨%¨₃Ó8•3в     # compressed list 222221211212222221111222221212211111222202122
              4α   # vectorized absolute difference with 4: 222223233232222223333222223232233333222242322
                   # this is the list of the number of words in the presidents' names
                   # (note that "George H. W. Bush" is the only 4-word name, forcing us to use base-3 instead of base-2 for the compressed list, which costs 3 bytes)

£                  # split the list of words according to the list of wordcounts: [["George", "Washington"], ..., ["Donald", "Trump"]]
 ðý                # join each sub-list with spaces

We now have a list of the 45 full names in chronological order, so we're done with this part.

Part 2: the dates

To make it easier to compare dates, we convert them to integers. This is done with a conversion from base-32, which gives 1024 * year + 32 * month + day (and doesn't care that the year "digit" is greater than 32).

We start with a list of the number of consecutive reelections (elections that don't change the president), in reverse chronological order:

•9ÕS&µç©•3в   # compressed list 111010111011020000011000000101110

Those first three 1s correspond to Obama, Bush and Clinton all being reelected once. The lone 2 corresponds to McKinley and Theodore Roosevelt both being reelected once (McKinley died in office and Theodore Roosevelt was his vice-president, so there was no other election inbetween their reelections). There should be a 4 in there for Franklin D. Roosevelt + Truman, but this is also the point where inauguration day changed from March 4 to January 20, so we handle this special case later.

±             # bitwise not (equivalently: add 1, then negate): [-2, -2, ..., -1]
 žD*          # multiply by 4096 [-8192, -8192, ..., -4096]

Remember that 1024 means a year, so 4096 means a full mandate. This is now a list of time deltas between newly elected presidents (still in reverse chronological order, which is why the numbers need to be negative).

Now, lets take care of the 9 presidents who didn't serve full mandates (4 died of natural causes, 4 assassinated, Nixon resigned):

•¾¹iìzÓ.+,âšÜĀ‘ó₆x.»δ•žHв   # compressed list [45088, 9317, 15270, 16548, 20475, 22484, 22410, 18666, 11155, 43819]

45088 is the time delta from March 4, 1797 (first introduction on a March 4) to April 4, 1841 (first death in office). The following numbers are time deltas between the 9 deaths/resignations. Finally, 43819 is the time delta from August 9, 1974 (Nixon's resignation) to January 20, 2017 (latest introduction on a January 20).

«             # merge the two lists of time deltas
 9._          # rotate left by 9 (the number of January 20 introductions)
    .¥        # undelta
      •U<¶•   # compressed integer 1979491, meaning March 4, 1933 (the last March 4 introduction)
           +  # add to each

We now have a list of all dates where the president changed. The order is a bit funky: it starts in 1933, then follows March 4 introductions backwards in time, then deaths/resignations forwards in time, then goes back along the January 20 introductions. However, order won't actually matter.

I             # get the input date
 32β          # convert from base 32, yielding an integer
    ‹         # vectorized compare with our list, yielding a list of 0/1 booleans
     O        # sum
      è       # use the sum to index into the list of presidents' names
              # implicit output

And we're done.

\$\endgroup\$
  • 1
    \$\begingroup\$ Oh, you even beat the Jelly answer now! Very nice. Looking forward seeing an explanation. \$\endgroup\$ – Kevin Cruijssen Aug 26 at 13:55
  • \$\begingroup\$ @KevinCruijssen I added an explanation (: \$\endgroup\$ – Grimmy Aug 26 at 16:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.