Code Golf and the Artistry of Polyglot Programs

Programming a lot of the times is overlooked as just a means to an end, similarly to maths, an outsider might be compelled to think that something as complex and non intuitive as writting code could only be practiced with the goal of achieving something with tangible real world benefits, be it a business application that brings in money, or a tool that enables people to save precious time on earth. However, as all things in life, people can see things through a different lens, it turns out that the complex and non intuitive process of writing a computer program can be done with only sheer joy and intelectual stimulation as the desired outcome.

What is "Code Golf"?

First things first, in case you didn't know already code golf is essentially recreational programming as the name suggests, or as wikipedia eloquently puts:

Code golf is a type of recreational computer programming competition in which participants strive to achieve the shortest possible source code that implements a certain algorithm. Playing code golf is known as "golf scripting". Code golf challenges and tournaments may also be named with the programming language used (for example, Perl golf). - Wikipedia

Code golf challenges can take many forms and have weird twists to them as to make things more interesting, today we'll be looking at the result of a polyglot answer-chaining type challenge from StackExchange "Code Golf", a polyglot program is simply put a program that is syntactically valid in more than one language, which basically means you have source code that can run/compile with multiple languages. Take a look at the following piece of code:

# 6 "($?63_lv+'50;+'51;5 5 %$\--$[250=@$]aat\" a/4*DvehfbIg/\"" 3 4//*26qkp16*^[.qx]"[8=,k]Pk PPX~_~)"xvy"\( 7# CO|"14" #:7 9 7 9                      7 222222222222222222222222                        "'" # ##\\
# 1"7"//['][']     ````      [>.>.?]~~)[7aatxy\#184  O@              (22)Siii/ \psddpsdoh ]##### #######++(- #### ##-[###### mxf ####xAegguEay######i#u####Ft#######MZWWW####WWWWWW zR###### # ####  #######:_a5# 202ø!},{P_<Ám/e!<ÁmOe!}M<ÁmS15%!!%BB44,222%!!%BBPZPYAAA4D,5P[5?4-0!<½!!22<2/!]ss1]'[kkX"204".â'_PPQss 7 999993 1 7 3 1 8 1 1 55 k zzzzkf kf k zzzzzd kf k zzzzza kf bfz 2#z#111#y#y#y#_# coding=utf8             ! 1>?7ДOq#t#>2/Wr#t#t#q#68#r#t#t#68#q#63#r#t#t#6v#>#</Wr#6}#y/===Wr#7ЯOq#>J7Д/Wr#y<Wr#>5/Wr#t#t#6y#>-=/Wr#6|#>6/Wr122! 1退                         @[[[["472"?]]]]******<
# if-0//               18&1&  nthteo nthieo nthneo  a;net R[+++].----._     /112\    ##### #######   # #    #####; #   #   #    ##### ####  ###   #### # W#W#####WW#WWWW#####W####WW###WWW####W#WW#W#####WW#WWWW#WWWWWWWWWWWWWWWWWWWW;WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWR
#6!@eD>>if 2>2*>++++++!\::    @_/ 78"oo@"   '\"' ` L       >"082",,,@_ 1   x-----x########    ## ### ###### ######## #### ##### ####### ##### ###    # # #### ### ##### ####### ##### ###    # # #### ### ##### #EEEEEδΘΔΔΔΘΔΘλ
# endif/*[(*)]v_>>>>>>> >>">r"{\>>>> @ 0:8:8/_>>>> [>]R 10G|'53'S 11111111111      # ##########>>###>## #####>>##>####>##>#>#####>>##>#####>####>>>#####>##>#>##>>##>####>>##>#####>####>>>##### ## # ##  ## ####
#comment -[v] >>>>>>>>                     [@,,,"279"]>252O>"01",,@_ 9 h$s o#      #  ????!?!??!??!!!   !???!?!??!!?!?!!!!!?!!!!?????!????????????????????! >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>                
#[#[/e]]   >>>>>>>>>@!:!8:6:2/_ >>>>>>>>>>>>>>>>>>>>>>>>  ;>>>>>>>>>>>>>>>>>>      #v           @.7.8.2<
#- [!R++++++] +++++++++\++++++++++++++++++++++++++++++++++U.._+++++++._+++o+++o--ox#
####################################################################################>
 #{{{{]~*[~*__+++++++[>+++++++<-]>+._+++++._+._@]+-}}[.^+;;+;;+;;+<>;;+;;+;;+;;;;;;+; ;+;;.._]}--<^>++[+++++[>+++++++'4o'6o@<-]>._++++._+++._^<]+-+<[<=oC<=oC<._>>>>-]^>[<+++++[>++++++++++<-]>@@+.---@._+>$] )++$--![+++[>+++++++<-]>+._+++++.._>](  <<>> }<}>}[<}}<<}<<<<<}<<}<<<<}<<<}}}<}}<}}<}}<}}<}}<}}}<}}<<<<<<<<<<<}}}<}}<}}<}}<}}<}}<}}}<<<<<<<<<<}]  >>\[/>\/\>>>>>>>]>\[./>>\/\./\/>>>\./]  [[[
#~  n MMMMMMM MnnMnnnMnMMMMMMMnMMnnnnnMMnMnMnnMnMnnnnnnMnMnMMMMMMMMnnMnMnnnMnMMMM
#*  e:1*23/5x%6E2  []-main=-[165]- ###
#|9999 9 9
#/9 999 99 9999 9
#9"" /* *#p 173#*
#cs !9 9999
#<<<#
#{   
#`⟪`⟪\⟫ bqbqbqLzLzLzqtqtqtTcTcTcRqRqRq TzTzTzRtRtRtMbMbMbPsPsPsTqTqTqAbAbAbTmTmTmBqBqBqMtMtMtUgUgUg
#=($?$?0l0v01k1k0l0i 0r 0h0h1d111 0e 0y0y 0mo1d0y0e0e001d0i0f 0g 0n0n110mo0n0t 0t0mo0f0t0g0g0f0h0r0r0i0001k10v 0v0l11110000011100|_  )\
[ '`e```.1.0.6i_]56pq['];#/\\/;print 24;exit}}__END__/
### \MoOMoOMoOMoOMOOmoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOmOoMOomoomoOOOM\// >+@+-@@@@=>+<@@@=>+<?#>;?\:-._++._++++._#/<?\>3-++._6+---2._#/++++++++++++++++++++++++++++++++++++++++++++++++._++._++++++.>!\
' wWWWw;WW;WW;wv;w;;WW;wW;WW;wv;wW;_W;Ww;WW;WW;WW;WW;wW;WW;Ww;W;WW;WWWWwW;;;W\W/WWWWWwwwwvwWWWwWWWWwvwWWwW\WWwvwWWwWWWwvwW/Ww\WWW ho ho ho ho // ho ho ho ho ho ho ho ho ho ho ho ho ho ho ho ho ho ho ho ho ho ho ho ho ho ho hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi MU ([])  ({}<(((((()()())){}{})){}{})>)(({})){}{(<(<()>)({})({}<{}>({}){})>){({}[()])}}({}){}({}()<()()()>)  (<><()>){({}[()])}{  #(((()()()()())()())(()()())(()()())(()()())(()()())(()()())(()()())(()()())(()()())(()()())(()()()))  ((((((((\';  a=$(printf \\x00);b=$(echo -n $a|wc -c);case $b[1]¢ in 1?)echo 54;;1* )echo 242;;4* )echo 78;;8* )echo $((9999999999999999999>0?166:244));;0?1??)echo 50;;0* )echo 282;;* )echo 58;;esac;exit;#)';  print (0and eval('":"&&(defined?A)&&290||(defined?pp)&&190||(defined?__dir__)&&13||"_"[0]==95&&108||110')or(None and(-1 %2>0and 9or 247)or 1/2and eval('hasattr(zip,"iters")and 200or\'𒁁\'=="-"and 241or 1')or 5<<64>>64or 68));"${print(g+91)}$/";exit; "$'#{print(187);exit}'$/"; #< ?>wWWsssss {}#(prin 45)(bye){{}#}#(prin 199)(bye) 46(8+9+9+9+9+=!) >* * * * *[[[[3+4*7*@]]]]xxxxxxxxxxxxxxxxxxxxxxxx
###;{e=1}={e:null};console.log e&&39||180;\
__DATA__=""" " 
#  \
__END__
set pr'[puts 59][exit]\'':;@echo 185 #';set pr'-';pr 89;exit
ifdef ss 
#  
#
#  
# 
#  
# 
#  
#PLACET,2<- #2FAC,2SUB#1<- #52FAC,2SUB#2<- #32FACREADOUT,2PLEASEGIVEUPFACs wwwwwwwwwwwWWWwWWWWWwWWWWWWWwWWWWWWWWWwWWWWWWWWWWWWWWWwWWWWWWWWWWWWw W
jrzaeeaeuee_wuuwq jii_iullluiiiogr se_eeepaeeeeeeeeee;eeecisajjarpppppp ⠆⠄⡒⡆⡘😆😨😒😨💬95💬👥➡😻😹😸🙀🙀😹😼😿🙀🙀😼😼😸🙀🙀🙀🙀
👋🔢🌚🌝🌝🌚🌚🌚🌚🌚🐸🐸🐸🐸🐸🐸😂😂😂😂😂😂😂🌚🔥😂😂😂😂😂😂😂💯💩🐸🔥😂💞💩💞😂😂😂😂💞🔥🌚▲▲▲²²²²▲¡▼¡▲▲¡⎚¿⁵228¦→ₔ₁₉₃2♦10♦10♦10♥☰䷩䷏䷏䷨䷏䷩䷩䷩䷩䷩䷩䷩䷩䷩䷩䷩䷩䷩⚎ֱֲֵֶֶֶֶַַַָָ  
밠밠따빠빠맣박다맣받다맣희맣희吾有一數曰二百八十一書之うんたんたんたんたんうんうんうんうんうんたんうんうんうんたんうんたんたんうんたんたんうんたんたんうんたんたんうんたんたんたんたんたんうんうんうんうんたんたんうんたんたんたんうんうんうんたんうんうんたんうんうんたんうんうんたんうんたんうんうんうんたんたんうんたんたんうんたんたんうんたんたんうんたんたんたんうんうん  
😊♈💖  
😇♈♈  
😊♉♈  
😇♈♈  
😇♈♉  
😇♈💜  
😊♉♈  
😊📢♈  
😈♈💜  #e:>* * * * *[[[[828+*+@+*99]]]]* * * * *<
😊📢♈  
😇♉💞  
😊📢♉🐸⠀⢃⠛⠋  
#-49,A,-1                              #
#-5,A,-1                               #
#6,A,-1                                #
#  
XX  
x+------+XX   X       XXX
x|/0110@| X X  XXXXXXXXX X
x|/0011 | X X   XXXXXXX
x|/0010 | X
x|/0011 | 
x|/0001 | 
x|/$0011|  
x+------+  
1     ! !
2   !    !
1+    +!!
1#  *
53  +
#  
1+  *        +
51  +
#  
#  
1   *     x``   x  x
49 #+  xx+x=>+  x+x + x B+ ===+
#  =x x  x===  x x >8 xxx +++= +
#+  +x + x,_8=>+ xB  x+x
# =+R _*=x==  x +===+> x x    +
 x +R"12"+8=Dx B=xD +  + xxx+
#+ ``=>8=x>  x+~ x  x +x+B+
#  +====+x>~+B+= x x + x
#D~+x 8=++>8x +=   x+    +,_   +
15 + x   x  + +  xx   +  ?   ?@  %"18"      !
1  + x   + x ++  xx   + ?@    ?
1 \+* x    +  +  x    +   +   *
1   ! x  +x   +       + ?  !  ?
1    ! x xx --... ...--  ? @ ?
x +   ++ xx  ++ ++     +
 +xxxxx  +     +

#= +
+ *   +
#= + *
#=**************************************************+>                                            @,,,"286"_+1y2 #<"67",,@␋␋␋␋␋␋␋␋␋␋␋␋␋␋␋␋␋␋␌␋␋␋␋␋␋␋␋␋␋␋␋␋␋␋␋␋␋␋␋␋␌␋␋␋␋␋␋␋␋␋␋␋␋␋␋␋␋␋␋␋␋␋␋␋␋␋
  +  +$$$
#>"3"O._   +// rk:start | print: "69" rk:end       + e$P+++++*D*+++1++1E!s
   + ; + *
$'main' *****+ %++ %++ @@* %-- @@* %++ %++ @@*
 -+3o4o#  +
  <++"269">o+
^* *
 #+*****|
.x= #   +
,,  .=#
 #+ OOO       =#
 #^=
+`` 231 =#
#  #uuu#
,,..,.,,,,..,.,.,,..,,.,,,...,,.,,..,,,,,,..,,,.$

write 224;bye; 

 console.log 178;

~~~x  
main:Int  
main =248 
~~~  
literally, print 249
(print 164     (exit ) )
 ( *)
begin write         ('288'    )end.(*)
print 61
T:251  
E:0  
#+IDRIS: main:IO      (         );main=print 291

#ceppp         ;
MsgBox (0,"",169   )
#cs  
Yo::=~147
::=  
You can see an x here.<<  

>{-<<<<<  
> 176
>> Output 1
>SET x TO 120. [0]{472454523665721469465830106052219449897}  `. :-write(186). end_of_file. `
>X x.   ;-}
>l=length$show"\0";main=print$[0,0,0,233,0,146,157]!!l{-

\begin{code}  
{- ;  ␉␉␉␉ 





-}
open import IO;main = run (putStr"159" )
\end{code}
ppppppppppppp;pppppppppppppp
# {{{ {{{ {{{ {{
#!ZZt >>END-IF
#xxxh  program-id.h.procedure
#xxxg  diVision.display 230.
#}}}f >>IF 2>2
#}}}e
#xxxd
#xx}c
#}}}b
#x}xa

















































































































































































































































































































































<script> onload=function   (){d=document;f=[].sort;d.body.style.display='block';d.body.innerHTML=/a/.__proto__=='//'?275:!/r/.test  (f  )?267:!/\n/.test(f)?257:!/^\n/.test(f)?259:d.documentMode?262:265}</script>
<style>body{display:none}html:after{content:"258";[;content:"276";]}@media \0 all{html:after{content:"266"}}@media screen and  (min-width:0\0){html:after{content:"260"}}</style>
<attache>Print[194]Exit[]</attache>

22-23-31-13-13-31-13-13-31-13-13-31-13-13-31-12-12-23-31-13-13-31-13-13-31-13-13-31-13-13-31-21-22-21-12-32
Take Northern Line to Tooting Bec
Take Northern Line to Charing Cross
Take Northern Line to Charing Cross
Take Northern Line to Bank
Take District Line to Hammersmith
Take District Line to Upminster
Take District Line to Hammersmith
Take District Line to Upminster
Take District Line to Embankment
Take Bakerloo Line to Embankment
7 UP
Take Northern Line to Mornington Crescent
7 RIGHT
7 RIGHT
7 TEACH
6 BOND
6 BOND
6 BOND
5 RIGHT
5 LEFT
5 RIGHT
7 BOND
7 TEACH
5 TEACH
6 YELL
5 TEACH
6 YELL
6 YELL
#  ;
set ! 57
set ! 51
out &49 &1
out &56 &1
out &50 &1
When this program starts:
There is a scribe called x
x is to write 179

p now 70 dollar off!
p has been selling out worldwide!
More 91 of this
How much is it
red down one blue up red down one blue up red up one red right two blue up
baa baaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bleeeeeeeeeeeeet bleeeeeeeeeeeeet bleeeeeeeeeet baaaa bleet bleeeeeeeeeet bleeet bleeeeeeeeeet
#
ata#8;mint};dnu1&&1&Prers>80::\0}ngt=Bk:pextsepsEx94 Cr u Uitharc""2:body+/+--- $在 16 5""61*F 4, _._#a*een gi>/=[]R 8ogr 
ent
*/

#1""
#if!1
.int 2298589328,898451655,12,178790,1018168591,84934449,12597
#endif//*
#1""//*:
#include<stdio.h>
#define z(a) #a
#define u "e"//"
const char*i="24 10 31 1""a c #FFC0FF""B c #0000C0""d c #58007B""e c #0C8302""o c #FF8000""t c #FF00BC""u c #008080""h c #E60001""i c #CAFFFF""f c #280000""k c #CA0000""l c #CA007F""n c #330001 ""q c #E60000""A c #0040C0""E c #808000""F c #00C040""G c #008000 ""R c #800000""H c #0000AA""I c #00AA00""C c #55FFFF""K c #AAAAAA""r c red""g c green""b c blue""c c cyan""m c magenta""y c #FFFF00""x c black""_ c #FFFFFF""HHHahtdegggggggyrggggggc""IHHaixuEFbGGbggbryAEGRgc""CCHafyurbgbgggggggb____o""ICHakmyyyyyyyyyyyyyyyyye""I__almyyyyyyyyyyyyyyyyye""K__anmyyyyyyyyyyyyyy_y_e""HH_aqggyyyyyyyyg____m_Ce""CH_axxxxxxxxxxxxxxxxxxxx""K__aaaam___bbbbbBm_bbBab""K__________bbbbb___bbxbb";//"
typedef int known,macro;int x=!  '(',y[60];macro m(){0;}int f(int a,...  ){y[x=0]=x=72;printf("\x25i",!m?195:!a?124+x:sizeof' '-1?(1&*z(N)?234:"\??-"[1]?218:67^*u""):*u""?37:z (0'0  0'0 )[7]?75:"\??-"[1]?77+a/2:77);}__attribute__((weak))int main(){known y;int i;f(x,x=sizeof y);x=1;return 0;}__attribute__((destructor))int g(){x?0:puts("198");}//())*/
#1""/*/
<<<<<<<<<<WQTkTTX


>import Prelude;import GHC.IO;import Data.Functor.Const;import Data.String;import Text.Heredoc;import Control.Exception;import Language.Haskell.TH;import Text.Show.Functions;instance Monoid a=>Monad (Const a)where _>>=_=mempty
>instance K Float;instance IsString Integer where{fromString _=0};instance Num B where fromInteger _=B 170;negate _=B$ x#x
>data B=B{u::Int};e=error"#"; f?n=unsafePerformIO$ f e`catch`\ErrorCall{}->r n;instance Num(a->b);instance Num();instance Show(Q a )where{show _=""};f=(^);q _=r$ (d.B)?4;d (B _ )=r$0`f`f 2 64;class (Show a,Floating a)=>K a where{k::a->String;k _=show$  (id::a->a)pi};g=[here|here<-""]--[|]
>;
>x=0;y#a=subtract 0b1206;x#a=174;h b=b^x;r=pure ;l a=length$ show a;forall=0;z| (∀)<-5=forall;b1206|let _._=x;negate _=3=[246,264,0,263,261,232,222,209,210,128,206,207,214,211,212,217]!!(l("  ",0x0.1,1e1,  (0`id`),k(0::Float),toEnum 0::Num a=>Enum a=>a)+2*l(do a<-Const[1];pure a,h pi,h (0::Real a=>a))- 3*(l$(pure$TupE[]::ExpQ))-(-q?6+70+z));(!  )=seq
>;
>main|let p!_=0=print$ sum[0!61,{-_-}last$172:[u$[-1]!!0|g<">"]]--} 

#1""/*/
#if!1
#endif//*
/*/
#if!1
_;
select 192;
.exit
print1(292                       )
quit
#endif
p=sizeof("   (\");print'(''72'')';end !" );main(){puts('??-'&1?"101":"92" );return 0;}
#if 0
#endif//*
#}
disp 49
#{
}{}<>           K yya+-        &  g+$
 /._++.._# !._++.-.>@    A=AgRA;       AC
#:  /          
 \?     -/!  +++++++++++++++++++++++++++++++++++++++++++++++++<>^+++++<\>+++.-.
rebol[ ]prin either Value? 'disarm[223][270];red[ ]prin 221;$+/ #.---.>/
#s{
endif #@[[[["272"?]]]]* * * * * *<
#<<<#/<+>/\
"""#";   print(85)
#ce:  ~#class C{function:Main(a:String[])~Nil{83->Print();}}
#endcomment K`250
#nocomment outtext("155" )
#/`psZ283MIOnDrFe @,,,"284_"># 01-:2/_;:@,,,"285"_+1y2"982"2k,# @#;# k-'1:,,@_  pS9^7^8^MUOUOF
#\!|!o51   ;        ~nJQ  p'34'  \=#x=4;print(1>>-1<2 ? 17 : Inf16-0|>sizeof>2 ? 162 : √4x<8 ? 201 : 225+2>>1*2 )#p⟫try {EVAL 'say 「27」;exit'};say 237#⟫say 167#{{p{{}}}}say 235#]#print(47)#]#echo 21#>         :/aa*7+42@n;/#print(171)#s-#print 175#s|#print(208)#sCOprint("65")#ERi521@<[[["172"?]]]]* * * * * *<es9#
#8M`|  <esc>dggi2<esc>// :~- <~-< ~-<<<~-! `=> #
#1//  >>END-IF*>>>9#
# '>+/*' 25  >[};]+ pppppeee^e*n*\              \! 99n*n*es*s      \*s*ee*n*n*n*e*sss*e*n*n*n*ee*js "( *)//dd"    <e 5>1  */// \)∙226p|_|_X222999612#

Chances are... you didn't make much sense of it, but don't feel too bad there's not many people walking around with syntactic knowledge of 292 programming languages, that's right 292, precisely the amount of different languages that are combined into the above 13620 byte long behemoth. And I know what you might be thinking right now: "What a garbled mess of characters, is this thing even valid?". Yes! It is indeed valid and you can verify it yourself right here on tio.run (if you have the patience) which is a pretty cool tool that enables you to play with hundreds of languages that range from practical to esoteric without actually having to go through the burden of setting them up on you local environment.

The task posted originally about 3 years and 9 months ago:

The nth program to be submitted must run in n different languages; specifically, all the languages added in previous programs to be submitted, plus one more. The program must output 1 when run in the first language used in answers to this question, 2 when run in the second language, and so on. For example, the first answer could print 1 when run in Python 3, and the second answer could output 1 when run in Python 3 and 2 when run in JavaScript; in this case, the third answer would have to output 1 when run in Python 3, 2 when run in JavaScript, and 3 when run in some other language.

So you have to look at the previous submission and "golf" your way between all the interpreters of the different languages used up until that point and somehow find a way to make the code run with all said languages + the one you choose to add... no wonder this challenge spanned over 2 years. The winner? After 14 consecutive days of no activity whoever made the second newest answer (to proove the chain was not broken). This happened to be awarded to a user who goes by the name Chance who gave the 194th answer using the TemplAt programming language on April 26th, 2018. However the thread was not closed after the win, you can still submit if you want to, submissions still continue to pour in to this day, albeit at a slower pace, and that is why the majestic code snippet above contains 292 languages.

You can be the 293rd!, checkout the code's evolution over time in the StackExchange thread here, and marvel at its artistic beauty.