text
stringlengths 180
608k
|
---|
[Question]
[
When I stumbled upon [this question](https://codegolf.stackexchange.com/questions/18664/lets-draw-flag-of-nepal) I remembered that I had also once seen precise rules for the construction of the South Korean flag. And this is quite a different construction.
![enter image description here](https://i.stack.imgur.com/lLYwt.png)
[Source: Wikipedia](http://en.wikipedia.org/wiki/File:Flag_of_South_Korea.svg)
So you're to draw an exact construction of this one now!
## Specification
You can render the flag to file or screen using vector or raster graphics. If your output is rasterised, your image must have dimensions of 450x300 pixels or more.
All length ratios and positions need to be exactly as shown in the following diagram:
![enter image description here](https://i.stack.imgur.com/En7VV.png)
[Source: Wikipedia](http://en.wikipedia.org/wiki/File:Flag_of_South_Korea_(construction_sheet).svg)
Note that the centres of the two small circles align with the diagonal.
For the colours, you must use the following palette:
* White: #FFFFFF
* Black: #000000
* Red: #C60C30
* Blue: #003478
The black boundary must not be drawn *unless* your drawing system does not let you specify a 3:2 canvas for technical reasons (otherwise, you should use a 3:2 canvas and the flag should fill all of it). If you do need to add the boundary, it may be arbitrarily thick - the flag should be considered strictly *inside* the black boundary. Any other helping lines or length indicators must not be drawn. I.e., the flag should appear exactly as in the first image.
## Scoring
This is code golf, so the shortest answer (in bytes) wins.
As a word of warning, using existing compression (like embedding a compressed GIF) falls into [several standard loopholes](https://codegolf.meta.stackexchange.com/q/1061/8478).
[Answer]
## Python + Pycairo, ~~371 370~~ 366 bytes
![Flag](https://i.stack.imgur.com/EZP9Z.gif)
```
from cairo import*
p=3.141593
c=Context(SVGSurface("F",12,8))
C=c.set_source_rgb;R=c.rectangle;T=c.rotate;F=c.fill
C(1,1,1);R(0,0,12,8);F()
c.translate(6,4);T(.588);b=3188
for o in[(0,.2,.47),(.77,.05,.19)]*2:C(*o);i=b/2%2;b+=1;c.arc(i,0,2-i,0,p+i*p);F();T(p)
C(0,0,0)
for x in(p,1.966)*2:
for y in.5,0,1:
for z in-1,1:R(3+y,-z,1./3,z*(2.75+b%2)/3);F()
b/=2
T(x)
```
Outputs a tiny SVG file named `F`.
[Answer]
## HTML + CSS, ~~966 906 843 792~~ 762 bytes
Not a winner anytime, but lots of fun drawing in CSS. This can be golfed a lot though.
**CSS, HTML**:
```
*{position:fixed}a{background:linear-gradient(0deg,#003478 50%,#C60C30 50%);width:2in;height:2in;transform:rotate(.6rad);top:1in;left:2in}d,e{width:50%;height:50%;background:#C60C30;left:0;top:25%}a,d,e{border-radius:50%}d{background:#003478;left:50%}b,i{width:1in;height:26em;top:-1em;left:15em;transform:rotate(.98rad)}g,f,k,j{width:1in;height:17%;background:repeating-linear-gradient(0deg,#000,#000 1em,#fff 1em,#fff 1.5em);bottom:0;left:0}g,j,p{top:-.5em}b{transform:rotate(-.98rad)}c,p,v,x{height:2em;width:.5em;background:#fff;transform:rotate(.98rad)}p{top:2.8in;left:28em;transform:rotate(-.98rad) scale(1,4)}x{top:3.9em;left:28.4em}c,v{top:23.8em;transform:none}c{top:3.5em}body{height:4in;width:6in;border:1px solid
```
```
<a><d><e></a><b><f><g></b><i><j><k></i><p></p><x><v><c
```
`;border:1px solid` is just for show as the `<body>` tag has clear boundaries which can be observed by Inspector or similar tools, as stated by the OP
**NOTE** Works only in Firefox (or Chrome canary/dev) due to usage non vendor specific transforms and gradients.
[See it in action](http://codepen.io/scrapmac/pen/uyxfL/left/?editors=010)
[Answer]
# BBC Basic, ~~349~~ 343 ASCII characters, tokenised file size 330
Download emulator at <http://www.bbcbasic.co.uk/bbcwin/bbcwin.html>
```
p=1049q=25r=100VDU4118;275;-1,49,3076;19,7,-1;-1;531;255;7693;q;40;0;q,97,1200;800;29,640;400;
FORa=38TO56STEP0.01x=r*COS(a)y=r*SIN(a)b=a*7DIV44/2IFb=3.5z=y<0ELSEz=x>0
VDU18;1,p;-x;-y;q,153,r;0;18;2,p;x;y;q,153,r;0;18;0
IFABS(y)DIV1=56VDUp;x*b+y;y*b-x;q;x/3;y/3;q,113,-2*y;2*x;18;7:b-=0.1VDUp;x*b+y/12;y*b-x/12;q;x/2;y/2;q,112-z,-y/6;x/6;
NEXT
```
Using the correct colours added a lot, but golfing all the graphics commands down to raw VDU codes gives a saving of 6 characters overall compared with my original post. All graphics on the BBC micro is done via machine-specific ASCII control codes, so instead of using high-level graphics commands you can feed bytes direct to the VDU controller (generally shorter but at great expense to readability). A value ending in semicolon instead of comma is a 16-bit little-endian representation of 2 bytes.
**Ungolfed version**
```
MODE16
VDU19,1,-1,49,4,12 :REM adjust shade of red
VDU19,7,-1,-1,-1,-1 :REM adjust shade of white to full brightness (63 is 2's complement representation of -1
VDU19,4,-1,0,13,30 :REM adjust shade of blue
RECTANGLEFILL40,0,1200,800 :REM plot background rectangle
ORIGIN640,400
FORa=38TO56STEP0.01
x=COS(a)*100
y=SIN(a)*100
GCOL1:CIRCLEFILL-x,-y,100 :REM red
GCOL4:CIRCLEFILLx,y,100 :REM blue
GCOL0 :REM black
b=a*7DIV44/2 :REM divide a by 2*(22/7) to get integer representation, then divide by 2 again.
IFb=3.5THENz=y<0ELSEz=x>0 :REM decide whether to cut bar
REM If the angle is correct (100*sin(a) = 56) draw bar. If required, cut out the middle of the bar.
IFABS(INT(y))=56 MOVEx*b+y,y*b-x:MOVEBY x/3,y/3:PLOT113,-2*y,2*x:GCOL7:b-=0.1:MOVEx*b+y/12,y*b-x/12:MOVEBY x/2,y/2:IFz PLOT113,-y/6,x/6
NEXT
```
At the beginning of the program I move the origin to the centre of the screen.
I don't draw any large coloured half circles. Instead I run a loop that draws small red and blue circles, spinning in an anticlockwise direction. I do nearly 3 complete revolutions (starting with blue at the right) which is obviously more than enough to fill in the disc. I stop on the 3rd revolution, just when the blue at lower right is in the correct position to line up with the bars (which have to be plotted.)
When the angle is right, I draw one of the bars. the vector x,y for drawing the current small blue circle serves to tell in which direction the bar should be. For each of the 3 revolutions, a different value of the integer `a*7DIV44` is calculated, which tells whether the first, second or third bar should be drawn, with its inner edge 6/8,7/8 or 8/8 units from the centre (according to the units used in the question spec.) Because the program units are 1/4 of those in the spec, this is still a half-unit, so we divide by 2 again before saving to variable ´b´ to avoid repeated halving later.
The bars are drawn solid, then the middle is deleted if necessary. This prevents kinks from joining half-bars. The variable z indicates if a bar should be cut. That is, when y is negative for the middle bars and when x is positive for the other bars.
`MOVE` is an absolute move. `MOVEBY` is a relative move. `PLOT133` considers the last two graphics cursor positions, plus the new one specified (in relative coordinates) as three corners of a parallelogram, and plots that parallelogram.
**Output (& discussion of language limitations)**
I selected a screen mode of 1280x800 logical pixels = 640x400 physical pixels, which by default has a black background. Onto this I draw a white rectangle from -600,-400 to 600,400 to act as my "canvas."
BBC Basic can handle 16 colours at once, from a reprogrammable pallete. But it only supports 18-bit colour, whereas the question specifies the colours as 24-bit. The colours as close as possible.
![enter image description here](https://i.stack.imgur.com/X8Nsf.png)
[Answer]
# Python 3 turtle (552 549 bytes)
![Flag](https://i.stack.imgur.com/5iC4zm.png)
*([Full size image](https://i.stack.imgur.com/5iC4z.png))*
**Edit:** Now that we have Stack Snippets, here's a Stack Snippet test using [Skulpt](http://www.skulpt.org/), with the help of ArtOfCode's answer [here](https://codegolf.stackexchange.com/a/40127/21487). Unfortunately, Skulpt hasn't fully implemented Python yet, so I had to mutilate half my code to get this to work. In other words, this snippet is only meant to indicate *how* my program works (without needing to pull up Python).
*(Also, I'm finding that this might not actually work on some browsers...)*
```
function out(a){var b=document.getElementById("output");b.innerHTML+=a}function builtinRead(a){if(void 0===Sk.builtinFiles||void 0===Sk.builtinFiles.files[a])throw"File not found: '"+a+"'";return Sk.builtinFiles.files[a]}
$(document).ready(function run(){Sk.canvas="canvas";Sk.configure({output:out,read:builtinRead});try{Sk.importMainWithBody("<stdin>",!1,'import turtle\nimport math\nt=turtle.Turtle()\nt.speed(9)\nR="#c60c30"\nr=56.3\nk=0.6\ns=60*k\noffsetx,offsety=-215,-145\nt.up()\nt.goto(offsetx,offsety)\nt.down()\ndef q():t.rt(90)\ndef Q():t.lt(90)\ndef K():t.color("black");t.begin_fill();q()\ndef A(g,G):t.fd(g);Q();t.fd(G);Q();t.fd(g);Q();t.fd(G);Q()\ndef E():t.up();t.fd(s);t.down();Q();t.end_fill();t.up();t.fd(30*k);t.down();\ndef i():K();t.up();t.bk(s);t.down();A(120*k,20*k);E()\ndef I():K();t.up();t.fd(5*k);t.down();A(55*k,20*k);t.up();t.bk(65*k);t.down();A(55*k,20*k);E()\ndef C():t.circle(120*k,180)\nA(720*k,480*k)\nt.seth(r)\nt.up()\nt.goto(459.8*k+offsetx,173.4*k+offsety)\nt.down()\nt.color(R)\nt.begin_fill()\nC()\nt.end_fill()\nt.begin_fill()\nt.color("#003478")\nC()\nt.circle(s)\nt.end_fill()\nt.color(R)\nC()\nt.begin_fill()\nt.circle(s)\nt.end_fill()\nq()\nt.up()\nt.fd(s)\nt.down()\ni()\ni()\ni()\nt.up()\nt.bk(530*k)\nt.down()\nI()\nI()\nI()\nt.up()\nt.fd(170*k)\nt.rt(2*r)\nt.fd(180*k)\nt.down()\nI()\ni()\nI()\nt.up()\nt.bk(530*k)\nt.down()\ni()\nI()\ni()\n')}catch(a){throw Error(a.toString());}})
```
```
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script><script src="http://www.skulpt.org/static/skulpt.min.js" type="text/javascript"></script><script src="http://www.skulpt.org/static/skulpt-stdlib.js" type="text/javascript"></script>
<canvas height="320" width="480" id="canvas" style="border:1px solid gray">Your browser does not support HTML5 Canvas!</canvas>
```
---
Actual code:
```
import turtle as t
b=t.begin_fill
c=t.circle
e=t.end_fill
f=t.fillcolor
R="#c60c30"
r=56.3
F=t.fd
B=t.bk
s=60
def q():t.rt(90)
def Q():t.lt(90)
def K():f(0,0,0);b();q()
def A(g,G):exec("F(g);Q();F(G);Q();"*2)
def E():F(s);Q();e();F(30)
def i():K();B(s);A(120,20);E()
def I():K();F(5);A(55,20);B(65);A(55,20);E()
def C():c(120,180)
A(720,480)
t.seth(r)
t.up()
t.goto(459.8,173.4)
f(R)
b()
C()
e()
b()
f("#003478")
C()
c(s)
e()
C()
f(R)
b()
c(s)
e()
q()
F(s)
i()
i()
i()
B(530)
I()
I()
I()
F(170)
t.rt(2*r)
F(180)
I()
i()
I()
B(530)
i()
I()
i()
t.ht()
```
Since the turtle's such a slowpoke, if you want instant results you can add `t.tracer(0)` after the first line before you run the script.
*Note: For some reason turtle keeps drawing what looks like extra black pixels even though I've already called `up()`, and I have no idea why...*
[Answer]
# PHP/HTML/SVG, 324
(line breaks added for legibility)
```
<?=gzinflate(base64_decode('tVHBioMwFPyVwF5WSOzLi/tswQjdu9cevIk1KqtriaFd9utrgpSWFva0PPImMwzDkGTz
uWXnvrl8Tj8aOPAUebLNs5Y5W33PZrKjtpOrXPOuVEy7KMiD54mKMY3yrO5tPTTMaonM9MOg32qCWgHb5Nmpch076kIih/2y
PC4jRRCIU6BhbkwGV7lmAagk3d5nCfwQdKByVBwOFLagQu6exZLNzk5fjU+B9S4u/dF1Gh/apRw6Cb83uzHm0S69/cWbSIkx
YfSf5QT6dkk5UoACIeAfXTftepb/za8='));
```
The compressed data expands to the same SVG data as my earlier answer shown below, but with two changes to aid compression:
1. The two `<use>` sections are expanded to the original content of the `<defs>` section. This makes the source text longer, but reduces the entropy so it compresses better.
2. In the first `<g>` element, I changed `transform=translate(36,24)rotate(33.69)` to `transform=rotate(33.69)translate(43.27)`. This has the same effect geometrically, but compresses better because the sequence `><g transform=rotate(` now appears twice.
By default, PHP will serve this as `Content-Type: text/html`, so the invalid XML syntax shouldn't be a problem.
# SVG/HTML, 463
The HTML parser isn't too fussed about correct syntax, so we can do away with quotation marks in the parameters as long as they don't contain any spaces. It should be possible to squeeze this down further with a bit of Javascript.
```
<svg viewBox=0,0,72,48><defs><path d=M-25-6V6Zm3,0V6m3,0V-6M19-6V6Zm3,0V6m3,0V-6Z stroke=#000
stroke-width=2 id=p /></defs><g transform=translate(36,24)rotate(33.69)><circle r=12 fill=#c60c30
/><path d=M12,0A12,12,0,0,1-12,0A6,6,0,0,0,0,0A6,6,0,0,1,12,0Z fill=#003478 /><use xlink:href=#p
/><path d=M17,0h10z stroke=#fff stroke-width=1 /><g transform=rotate(112.62)><use xlink:href=#p
/><path d=M-27,0h4Zm6,0h4ZM20,0h4Z stroke=#fff stroke-width=1 /></g></g></svg>
```
[Answer]
## HTML + ES6, 388
```
<canvas id=D width=576 height=384><script>c=D.getContext('2d')
T=x=>c.translate(x*72,x*48)
R=(x,y)=>T(4)+c.rotate(x*.59)+T(-4)+eval('for(i=j=0;i*j<6;i+=(j^=1))c.fillRect(72+24*i+(i>2)*288,144+j*52,16,44+52*(y>>i&1-j))')
A=(w,x,y,z)=>(c.fillStyle=c.fill()+c.beginPath()||w)*c.arc(x*4,192-y,48*y,0,3.1,z)||A
R(-1,21)
R(2,7)
A(r='#C60C30',72,2,1)('#003478',72,2)(0,84,1,1)(r,60,1)()</script>
```
If your browser supports ES6, you can [view it on JSFiddle](http://jsfiddle.net/grc4/kk2afn80/10/) or run the snippet.
It constructs the flag out of some basic shapes, rotating the canvas first to account for the angles.
[Answer]
# Mathematica ~~404~~ 450
```
b=1&~Array~13;a=ReplacePart[b,7-> 0];d=Disk;r=RGBColor;
z@{q_,p_,s_}:=ArrayPlot[{q,q,{},p,p,{},s,s},Frame-> False,ImageSize-> 155];
m=r@@{0,.2,.5};
o=r@@{.8,0,.2};
t=-19.1;u=-12.75;v=-5;q=-3.33;
Graphics[{Line[{{-36,-24},{36,-24},{36,24},{-36,24},{-36,-24}}],
Inset[Rotate[z@#,#2 125 Degree],#3]&@@@{{{b,a,b},1,{t,u}},{{a,b,a},1,{-t,-u}},
{{a,a,a},-1,{-t,u}},{{b,b,b},-1,{t,-u}}},
{o,d[{0,0},12,{-.2 Pi,.8Pi}],m, d[{0,0},12,{.8Pi,1.8Pi}],o,d[{v,-q},6],m,d[{-v,q},6]}}]
```
![flag](https://i.stack.imgur.com/7l9Sp.png)
[Answer]
# C++ TOO LARGE
Attempted this using my home made [PPM drawing library](http://myweb.uiowa.edu/stcrowle/Files/PPMDraw.zip). It's technically scalable, but I'm limited by my recursive fill function because it's unreliable and likes to segfault, I think it's using up too much memory, so I won't actually let the user set the scale. The image is irregular because the coordinates I entered for each corner of the bars are slightly off.
![enter image description here](https://i.stack.imgur.com/yLF83.png)
I set it up to start with a black background, then put a white circle in the middle, then red and blue circles in that. Used recursive fills to add the rest of red and blue. Then drew rectangles with white lines to mark the black bars. Split the black background into 4 sections with white lines and used 4 recursive fills to make each section white. Doing it in 1 pass would have caused a segfault. It's still very slow to render.
## Ungolfed main code ( the rest of the library is too large, golfing this doesn't matter )
```
#include "PPMDraw.h"
#include <iostream>
int main(){
std::cout << "Drawing Korean Flag" << std::endl;
int scale = 150;
int width = 3 * scale;
int height = 2 * scale;
int xc = width/2;
int yc = height/2;
// coords for the bar corners
float nwax = -0.773; float nway = -0.813;
float nwbx = -0.707; float nwby = -0.773;
float nwcx = -1.000; float nwcy = -0.360;
float nwdx = -1.050; float nwdy = -0.400;
float nwex = -0.667; float nwey = -0.747;
float nwfx = -0.613; float nwfy = -0.693;
float nwgx = -0.880; float nwgy = -0.293;
float nwhx = -0.947; float nwhy = -0.333;
float nwix = -0.560; float nwiy = -0.667;
float nwjx = -0.507; float nwjy = -0.627;
float nwkx = -0.773; float nwky = -0.227;
float nwlx = -0.840; float nwly = -0.267;
float neax = 0.747; float neay = -0.813;
float nebx = 0.867; float neby = -0.627;
float necx = 0.813; float necy = -0.587;
float nedx = 0.680; float nedy = -0.773;
float neex = 0.893; float neey = -0.587;
float nefx = 1.030; float nefy = -0.400;
float negx = 0.960; float negy = -0.360;
float nehx = 0.840; float nehy = -0.547;
float neix = 0.640; float neiy = -0.747;
float nejx = 0.920; float nejy = -0.333;
float nekx = 0.853; float neky = -0.293;
float nelx = 0.587; float nely = -0.693;
float nemx = 0.533; float nemy = -0.667;
float nenx = 0.667; float neny = -0.493;
float neox = 0.600; float neoy = -0.440;
float nepx = 0.480; float nepy = -0.627;
float neqx = 0.693; float neqy = -0.440;
float nerx = 0.813; float nery = -0.267;
float nesx = 0.747; float nesy = -0.227;
float netx = 0.627; float nety = -0.400;
float swax = -0.773; float sway = 0.200;
float swbx = -0.507; float swby = 0.613;
float swcx = -0.560; float swcy = 0.653;
float swdx = -0.840; float swdy = 0.253;
float swex = -0.880; float swey = 0.280;
float swfx = -0.760; float swfy = 0.453;
float swgx = -0.813; float swgy = 0.493;
float swhx = -0.947; float swhy = 0.320;
float swix = -0.733; float swiy = 0.507;
float swjx = -0.613; float swjy = 0.680;
float swkx = -0.667; float swky = 0.720;
float swlx = -0.787; float swly = 0.547;
float swmx = -0.987; float swmy = 0.347;
float swnx = -0.707; float swny = 0.760;
float swox = -0.773; float swoy = 0.800;
float swpx = -1.053; float swpy = 0.387;
float seax = 0.747; float seay = 0.200;
float sebx = 0.813; float seby = 0.253;
float secx = 0.693; float secy = 0.427;
float sedx = 0.627; float sedy = 0.387;
float seex = 0.853; float seey = 0.280;
float sefx = 0.920; float sefy = 0.320;
float segx = 0.800; float segy = 0.507;
float sehx = 0.733; float sehy = 0.453;
float seix = 0.960; float seiy = 0.347;
float sejx = 1.036; float sejy = 0.387;
float sekx = 0.893; float seky = 0.573;
float selx = 0.840; float sely = 0.520;
float semx = 0.600; float semy = 0.427;
float senx = 0.667; float seny = 0.467;
float seox = 0.547; float seoy = 0.653;
float sepx = 0.480; float sepy = 0.613;
float seqx = 0.707; float seqy = 0.493;
float serx = 0.773; float sery = 0.547;
float sesx = 0.640; float sesy = 0.733;
float setx = 0.547; float sety = 0.680;
float seux = 0.813; float seuy = 0.573;
float sevx = 0.880; float sevy = 0.613;
float sewx = 0.747; float sewy = 0.800;
float sexx = 0.693; float sexy = 0.747;
PPMDraw flag = PPMDraw(width, height);
flag.fill(0, 0, 0);
// draw white circle in middle
flag.set_color(255, 255, 255);
flag.draw_fill_circle(xc, yc, scale/2);
// draw red and blue portions of circle
flag.set_color(255, 0, 0);
flag.draw_fill_circle(xc - .21*scale, yc - .14*scale, scale/3.9);
flag.set_color(0, 0, 255);
flag.draw_fill_circle(xc + .21*scale, yc + .14*scale, scale/3.9);
flag.set_color(255, 0, 0);
flag.recursive_fill(xc + .21*scale, yc - .21*scale);
flag.set_color(0, 0, 255);
flag.recursive_fill(xc - .21*scale, yc + .21*scale);
// draw the northwest bars
flag.set_color(255, 255, 255);
flag.draw_line(xc + nwax*scale, yc + nway*scale, xc + nwbx*scale, yc + nwby*scale);
flag.draw_line(xc + nwax*scale, yc + nway*scale, xc + nwdx*scale, yc + nwdy*scale);
flag.draw_line(xc + nwbx*scale, yc + nwby*scale, xc + nwcx*scale, yc + nwcy*scale);
flag.draw_line(xc + nwcx*scale, yc + nwcy*scale, xc + nwdx*scale, yc + nwdy*scale);
flag.draw_line(xc + nwex*scale, yc + nwey*scale, xc + nwfx*scale, yc + nwfy*scale);
flag.draw_line(xc + nwex*scale, yc + nwey*scale, xc + nwhx*scale, yc + nwhy*scale);
flag.draw_line(xc + nwfx*scale, yc + nwfy*scale, xc + nwgx*scale, yc + nwgy*scale);
flag.draw_line(xc + nwhx*scale, yc + nwhy*scale, xc + nwgx*scale, yc + nwgy*scale);
flag.draw_line(xc + nwix*scale, yc + nwiy*scale, xc + nwjx*scale, yc + nwjy*scale);
flag.draw_line(xc + nwix*scale, yc + nwiy*scale, xc + nwlx*scale, yc + nwly*scale);
flag.draw_line(xc + nwjx*scale, yc + nwjy*scale, xc + nwkx*scale, yc + nwky*scale);
flag.draw_line(xc + nwlx*scale, yc + nwly*scale, xc + nwkx*scale, yc + nwky*scale);
//NE
flag.draw_line(xc + neax*scale, yc + neay*scale, xc + nebx*scale, yc + neby*scale);
flag.draw_line(xc + neax*scale, yc + neay*scale, xc + nedx*scale, yc + nedy*scale);
flag.draw_line(xc + nebx*scale, yc + neby*scale, xc + necx*scale, yc + necy*scale);
flag.draw_line(xc + necx*scale, yc + necy*scale, xc + nedx*scale, yc + nedy*scale);
flag.draw_line(xc + neex*scale, yc + neey*scale, xc + nefx*scale, yc + nefy*scale);
flag.draw_line(xc + neex*scale, yc + neey*scale, xc + nehx*scale, yc + nehy*scale);
flag.draw_line(xc + nefx*scale, yc + nefy*scale, xc + negx*scale, yc + negy*scale);
flag.draw_line(xc + nehx*scale, yc + nehy*scale, xc + negx*scale, yc + negy*scale);
flag.draw_line(xc + neix*scale, yc + neiy*scale, xc + nejx*scale, yc + nejy*scale);
flag.draw_line(xc + neix*scale, yc + neiy*scale, xc + nelx*scale, yc + nely*scale);
flag.draw_line(xc + nejx*scale, yc + nejy*scale, xc + nekx*scale, yc + neky*scale);
flag.draw_line(xc + nelx*scale, yc + nely*scale, xc + nekx*scale, yc + neky*scale);
flag.draw_line(xc + nemx*scale, yc + nemy*scale, xc + nenx*scale, yc + neny*scale);
flag.draw_line(xc + nemx*scale, yc + nemy*scale, xc + nepx*scale, yc + nepy*scale);
flag.draw_line(xc + nepx*scale, yc + nepy*scale, xc + neox*scale, yc + neoy*scale);
flag.draw_line(xc + nenx*scale, yc + neny*scale, xc + neox*scale, yc + neoy*scale);
flag.draw_line(xc + neqx*scale, yc + neqy*scale, xc + nerx*scale, yc + nery*scale);
flag.draw_line(xc + neqx*scale, yc + neqy*scale, xc + netx*scale, yc + nety*scale);
flag.draw_line(xc + nerx*scale, yc + nery*scale, xc + nesx*scale, yc + nesy*scale);
flag.draw_line(xc + netx*scale, yc + nety*scale, xc + nesx*scale, yc + nesy*scale);
//sw
flag.draw_line(xc + swax*scale, yc + sway*scale, xc + swbx*scale, yc + swby*scale);
flag.draw_line(xc + swax*scale, yc + sway*scale, xc + swdx*scale, yc + swdy*scale);
flag.draw_line(xc + swbx*scale, yc + swby*scale, xc + swcx*scale, yc + swcy*scale);
flag.draw_line(xc + swcx*scale, yc + swcy*scale, xc + swdx*scale, yc + swdy*scale);
flag.draw_line(xc + swex*scale, yc + swey*scale, xc + swfx*scale, yc + swfy*scale);
flag.draw_line(xc + swex*scale, yc + swey*scale, xc + swhx*scale, yc + swhy*scale);
flag.draw_line(xc + swfx*scale, yc + swfy*scale, xc + swgx*scale, yc + swgy*scale);
flag.draw_line(xc + swhx*scale, yc + swhy*scale, xc + swgx*scale, yc + swgy*scale);
flag.draw_line(xc + swix*scale, yc + swiy*scale, xc + swjx*scale, yc + swjy*scale);
flag.draw_line(xc + swix*scale, yc + swiy*scale, xc + swlx*scale, yc + swly*scale);
flag.draw_line(xc + swjx*scale, yc + swjy*scale, xc + swkx*scale, yc + swky*scale);
flag.draw_line(xc + swlx*scale, yc + swly*scale, xc + swkx*scale, yc + swky*scale);
flag.draw_line(xc + swmx*scale, yc + swmy*scale, xc + swnx*scale, yc + swny*scale);
flag.draw_line(xc + swmx*scale, yc + swmy*scale, xc + swpx*scale, yc + swpy*scale);
flag.draw_line(xc + swpx*scale, yc + swpy*scale, xc + swox*scale, yc + swoy*scale);
flag.draw_line(xc + swnx*scale, yc + swny*scale, xc + swox*scale, yc + swoy*scale);
//se
flag.draw_line(xc + seax*scale, yc + seay*scale, xc + sebx*scale, yc + seby*scale);
flag.draw_line(xc + seax*scale, yc + seay*scale, xc + sedx*scale, yc + sedy*scale);
flag.draw_line(xc + sebx*scale, yc + seby*scale, xc + secx*scale, yc + secy*scale);
flag.draw_line(xc + secx*scale, yc + secy*scale, xc + sedx*scale, yc + sedy*scale);
flag.draw_line(xc + seex*scale, yc + seey*scale, xc + sefx*scale, yc + sefy*scale);
flag.draw_line(xc + seex*scale, yc + seey*scale, xc + sehx*scale, yc + sehy*scale);
flag.draw_line(xc + sefx*scale, yc + sefy*scale, xc + segx*scale, yc + segy*scale);
flag.draw_line(xc + sehx*scale, yc + sehy*scale, xc + segx*scale, yc + segy*scale);
flag.draw_line(xc + seix*scale, yc + seiy*scale, xc + sejx*scale, yc + sejy*scale);
flag.draw_line(xc + seix*scale, yc + seiy*scale, xc + selx*scale, yc + sely*scale);
flag.draw_line(xc + sejx*scale, yc + sejy*scale, xc + sekx*scale, yc + seky*scale);
flag.draw_line(xc + selx*scale, yc + sely*scale, xc + sekx*scale, yc + seky*scale);
flag.draw_line(xc + semx*scale, yc + semy*scale, xc + senx*scale, yc + seny*scale);
flag.draw_line(xc + semx*scale, yc + semy*scale, xc + sepx*scale, yc + sepy*scale);
flag.draw_line(xc + sepx*scale, yc + sepy*scale, xc + seox*scale, yc + seoy*scale);
flag.draw_line(xc + senx*scale, yc + seny*scale, xc + seox*scale, yc + seoy*scale);
flag.draw_line(xc + seqx*scale, yc + seqy*scale, xc + serx*scale, yc + sery*scale);
flag.draw_line(xc + seqx*scale, yc + seqy*scale, xc + setx*scale, yc + sety*scale);
flag.draw_line(xc + serx*scale, yc + sery*scale, xc + sesx*scale, yc + sesy*scale);
flag.draw_line(xc + setx*scale, yc + sety*scale, xc + sesx*scale, yc + sesy*scale);
flag.draw_line(xc + seux*scale, yc + seuy*scale, xc + sevx*scale, yc + sevy*scale);
flag.draw_line(xc + seux*scale, yc + seuy*scale, xc + sexx*scale, yc + sexy*scale);
flag.draw_line(xc + sevx*scale, yc + sevy*scale, xc + sewx*scale, yc + sewy*scale);
flag.draw_line(xc + sexx*scale, yc + sexy*scale, xc + sewx*scale, yc + sewy*scale);
// fill in the black to white
flag.draw_line(xc, yc - scale/2, xc, 0);
flag.draw_line(xc, yc + scale/2, xc, height);
flag.draw_line(xc - scale/2, yc, 0, yc);
flag.draw_line(xc + scale/2, yc, width, yc);
flag.recursive_fill(0, 0);
flag.recursive_fill(0, height-1);
flag.recursive_fill(width - 1, 0);
flag.recursive_fill(width - 1, height - 1);
flag.save("flag.ppm");
}
```
[Answer]
# [PostScript](https://en.wikipedia.org/wiki/PostScript), ~~572~~ ~~477~~ 471 bytes
Golfed code:
```
5 5 scale 36 24 translate<</R{.75 .05 .19 setrgbcolor}/B{0 .20 .47 setrgbcolor}/a 2 3 atan/b{0 setgray[18 -6 2 12 21 -6 2 12 24 -6 2 12]rectfill 1 setgray{[18 -.5 2 1 24 -.5 2 1]rectfill}if{21 -.5 2 1 rectfill}if}>>begin a neg rotate R 0 0 12 0 180 arc closepath fill B 0 0 12 180 0 arc closepath fill R -6 0 6 0 360 arc closepath fill B 6 0 6 0 360 arc closepath fill true true b 2 a mul rotate false true b 180 rotate true false b -2 a mul rotate false false b showpage
```
Ungolfed code:
```
5 5 scale % over-all scale
36 24 translate % over-all shift
% define some short-named procedures for later use
<<
/R {.75 .05 .19 setrgbcolor} % prodecure for setting red color
/B {0 .20 .47 setrgbcolor} % procedure for setting blue color
/a 2 3 atan % calculate angle = arctan(2/3) = 33.7°
/b { % procedure for drawing bars
0 setgray % black
[18 -6 2 12 21 -6 2 12 24 -6 2 12] rectfill % draw 3 bars
1 setgray % white
{[18 -.5 2 1 24 -.5 2 1] rectfill} if % conditionally draw gap in inner/outer bars
{21 -.5 2 1 rectfill} if % conditionally draw gap in middle bar
}
>> begin
a neg rotate % rotate -33.7°
R 0 0 12 0 180 arc closepath fill % big red half circle
B 0 0 12 180 0 arc closepath fill % big blue half circle
R -6 0 6 0 360 arc closepath fill % small red circle
B 6 0 6 0 360 arc closepath fill % small blue circle
true true b % draw bars (with gap in all bars)
2 a mul rotate % rotate 67.4°
false true b % draw bars (with gap in inner/outer bars)
180 rotate % rotate 180°
true false b % draw bars (with gap in middle bar)
-2 a mul rotate % rotate -67.4°
false false b % draw bars (without gaps)
showpage
```
Result (as animation to see how it is drawn):
[![result](https://i.stack.imgur.com/unsZn.gif)](https://i.stack.imgur.com/unsZn.gif)
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 31 bytes
```
"SouthKorea"~CountryData~"Flag"
```
[![enter image description here](https://i.stack.imgur.com/dm54E.png)](https://i.stack.imgur.com/dm54E.png)
[Answer]
# Python 2, 483 bytes
```
from math import*
w,k,r,b="255 "*3,"0 "*3,"198 12 48 ","0 52 120 "
print "P3 600 400 255 "
a=atan2(2,3)
c,s=cos(a),sin(a)
T=lambda x,y:(c*x-s*y,s*x+c*y)
S=lambda x,y:150<x<216.6and x%25<16.6and y*y<2500
C=lambda x,y,p=50:(x-p)**2+y*y<2500
for y in range(-200,200):
for x in range(-300,300):X,Y=T(x,y);W,Z=T(-x,y);print [[w,k][(S(abs(X),Y)and(Y*Y>16or(166.6<X<191.4or-200>X or 0>X>-166.6)))or(S(abs(W),Z)and(W>0 or abs(Z)>4))],[b,r][(Z<0 or C(W,Z))and not C(W,Z,-50)]][W*W+Z*Z<10000]
```
Possible improvements:
* hardcode the cos,sin constants
* binary PPM
* transform to [3,2] plane
* optimize the boolean statements
Output as text PPM, usage:
```
python golf_korea.py > korea.ppm
```
[![enter image description here](https://i.stack.imgur.com/OLOuT.png)](https://i.stack.imgur.com/OLOuT.png)
### ungolfed beta version
```
from math import*
w,k,r,b="255 255 255 ", "0 0 0 ", "255 0 0 ", "0 0 255 "
g="0 255 0 "
print "P3 600 400 255 "
a=atan2(2,3)
c,s=cos(a),sin(a)
trans=lambda x,y:(c*x-s*y,s*x+c*y)
stripe=lambda x:150<x<216.6 and x%25<16.6
small=lambda x,y,p=50:(x-p)**2+y*y<2500
for y in range(-200,200):
for x in range(-300,300):
X,Y=trans(x,y)
W,Z=trans(-x,y)
if stripe(abs(X)) and Y*Y<2500:
if abs(Y)>4:
print k
else:
if X>0:
if 166.6<X<191.4:
print k
else:
print w
else:
if -200<X<-166.6:
print w
else:
print k
elif stripe(abs(W)) and Z*Z<2500 and(W>0 or abs(Z)>4):
print k
elif W*W+Z*Z<100*100:
if (Z<0 or small(W,Z)) and not small(W,Z,-50):
print r
else:
print b
else:
print w
```
] |
[Question]
[
Inspired by a [meme](https://i.stack.imgur.com/yLbE3.jpg) I saw earlier today.
# Challenge description
Consider an infinite alphabet grid:
```
ABCDEFGHIJKLMNOPQRSTUVWXYZ
ABCDEFGHIJKLMNOPQRSTUVWXYZ
ABCDEFGHIJKLMNOPQRSTUVWXYZ
ABCDEFGHIJKLMNOPQRSTUVWXYZ
ABCDEFGHIJKLMNOPQRSTUVWXYZ
...
```
Take a word (`CODEGOLF` in this example) and make it a subsequence of the grid, replacing unused letters by a space and removing letters at the end of the infinite grid altogether:
```
C O
DE G O
L
F
```
# Examples
`STACKEXCHANGE`
```
ST
A C K
E X
C H
A N
G
E
```
`ZYXWVUTSRQPONMLKJIHGFEDCBA`
```
Z
Y
X
W
V
U
T
S
R
Q
P
O
N
M
L
K
J
I
H
G
F
E
D
C
B
A
```
`F`
```
F
```
`ANTIDISESTABLISHMENTARIANISM`
```
A N T
I
D I S
E ST
AB L
I S
H M
E N T
A R
I
A N
I S
M
```
# Notes
* Trailing whitespaces are allowed.
* You don't need to pad the last any line with spaces. For example, if the input is `ABC`, you may output just `ABC` without 23 trailing spaces.
* You may assume input will match `[A-Z]+` regex.
* Alternatively, you may use lower-case alphabet, in which case output will match `[a-z]+`.
* You must use a newline (`\n`, `\r\n` or equivalent) to separate lines, that is a list of strings is not a proper output format.
* This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge, so make your code as short as possible!
[Answer]
# [Husk](https://github.com/barbuz/Husk), 15 bytes
```
TṪS`?' €…"AZ"ġ>
```
[Try it online!](https://tio.run/##yygtzv7/P@ThzlXBCfbqCo@a1jxqWKbkGKV0ZKHd////Hf1CPF08g12DQxydfDyDPXxd/UIcgzwd/TyDfQE "Husk – Try It Online")
## Explanation
```
TṪS`?' €…"AZ"ġ> Implicit input, e.g. "HELLO"
ġ> Split into strictly increasing substrings: x = ["H","EL","LO"]
…"AZ" The uppercase alphabet (technically, the string "AZ" rangified).
Ṫ Outer product of the alphabet and x
S`?' € using this function:
Arguments: character, say c = 'L', and string, say s = "EL".
€ 1-based index of c in s, or 0 if not found: 2
S`?' If this is truthy, then c, else a space: 'L'
This gives, for each letter c of the alphabet,
a string of the same length as x,
containing c for those substrings that contain c,
and a space for others.
T Transpose, implicitly print separated by newlines.
```
[Answer]
# Java 10, ~~161~~ ~~159~~ 152 bytes
```
s->{var x="";int p=0;for(var c:s)x+=p<(p=c)?c:";"+c;for(var y:x.split(";"))System.out.println("ABCDEFGHIJKLMNOPQRSTUVWXYZ".replaceAll("[^"+y+"]"," "));}
```
-2 bytes thanks to *@Nevay*.
-7 byte printing directly instead of returning a String, and converting to Java 10.
**Explanation:**"
[Try it here.](https://tio.run/##rZBdb4IwGIXv9yve9KqESXYtY0sFRBSKCn7HJV3VDYdAAI3E@NtZ/ciu3B1Ne/Geps85p1t2YI3t6qfiEctzcFkYn54AwrhYZxvG10AvI8AhCVfAMf9m2WIJuaQK9SyO2HnBipADhRg0qPLG2@nAMjhqCKkCA6n2om6SDF9E3sylo6ylrzjVuPTOm0hFMv@7LptHJU@jsMBClyS/zIv1Tkn2hZJmAhXFGJGWbphtq2N3e45Lvf5g6Aej8WQ6myMlW6eRiEyiCKPFB5JLGS3RMwKBUs@Vekub7j8jkfYe@lprJ0pjvxAWX6Ibk26NY4VjpHuGaXlOGylFoovuJMtYiaVrfYBHARv/LXR/dOX6AdF75lTvEGqZdcPns@lkPAr84aDvUdfpde2O1TYNvUXqdgrqBhIa2Ibtm@J/Wo7td1yTBmRoE2r7bt1eLeI4nkcfYc9P5@oX)
```
s->{ // Method with String parameter and no return-type
var x=""; // Temp-String
int p=0; // Previous character (as integer), starting at 0
for(var c:s) // Loop (1) over the characters of the input
x+=p<(p=c)? // If the current character is later in the alphabet
// (replace previous `p` with current `c` afterwards)
c // Append the current character to Temp-String `x`
: // Else:
";"+c; // Append a delimiter ";" + this character to Temp-String `x`
for(var y:x.split(";")) // Loop (2) over the String-parts
System.out.println( // Print, with trailing new-line:
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
// Take the alphabet,
.replaceAll("[^"+y+"]"," "));}
// and replace all letters not in the String-part with a space
```
The first part of the method splits the input-word into parts with a delimiter.
For example: `CODEGOLF` → `CO;DEGO;L;F` or `BALLOON` → `B;AL;LO;O;N`.
The second part loops over these parts, and uses the regex `[^...]` to replace everything that isn't matched with a space.
For example `.replaceAll("[^CO]"," ")` leaves the `C`, and `O`, and replaces everything else with a space.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 69 bytes
```
i;f(char*s){for(i=64;*s;putchar(*s^i?32:*s++))i+=i^90?1:puts("")-26;}
```
[Try it online!](https://tio.run/##hY5Ba8IwAEbv/orQU9IScG4IM0hJ29hmtqmaurkhgnTrlsOiJNWL@Nu7yO72@r734Kvxd113nSINrH/2xrfo0hwMVNPxE/EtOZ7aG4a@3anwcTTxbRAgpIKp2j0Pw4eJ2y30PIRHY3LtlG7B715peD6oTwQuAwAa6MVlwtIyn3mIOHA0znJ0qzHGW32D/5qsaDxnmzijImU97sf75u11XcnVclGKIp@/8CydsSSOaE/Yd4KKiidcMncmyrnMCiYquuJUcFncS81XezIaDMng2v0B "C (gcc) – Try It Online")
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~24~~ 23 bytes
```
''jt8+t1)wdh26X\Ys(26e!
```
Uses lowercase letters.
Try it at [MATL Online!](https://matl.io/?code=%27%27jt8%2Bt1%29wdh26X%5CYs%2826e%21&inputs=stackexchange&version=20.4.1)
### Explanation
```
'' % Push empty string
jt % Push input string. Duplicate
8+ % Add 8 to each char (ASCII code). This transforms 'a' 105,
% 'b' into 106, which modulo 26 correspond to 1, 2 etc
t1) % Duplicate. Get first entry
wd % Swap. COnsecutive differences.
h % Concatenate horizontally
26X\ % 1-based modulo 26. This gives a result from 1 to 26
Ys % Cumulative sum
( % Write values (converted into chars) at specified positions
% of the initially empty string
26e % Reshape into a 26-row char matrix, padding with char 0
! % Transpose. Implicitly display. Char 0 is shown as space
```
[Answer]
# [Perl 5](https://www.perl.org/), 44 bytes
**40 bytes code + 4 for `-lF`.**
```
print map/$F[0]/?shift@F:$",A..Z while@F
```
[Try it online!](https://tio.run/##K0gtyjH9/7@gKDOvRCE3sUBfxS3aIFbfvjgjM63Ewc1KRUnHUU8vSqE8IzMn1cHt/39nfxdXd38ft3/5BSWZ@XnF/3Vz3AA "Perl 5 – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 92 bytes
```
f=lambda x,y=65:x and(y<=ord(x[0])and" "*(ord(x[0])-y)+x[0]+f(x[1:],-~ord(x[0]))or"\n"+f(x))
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P802JzE3KSVRoUKn0tbM1KpCITEvRaPSxja/KEWjItogVhPIV1JQ0tKAC@hWamqDGNppQL6hVayObh1cTjO/SCkmTwkkpan5v6AoM69EI01DydnfxdXd38dNSVOTCyzIBZdy9AvxdPEMdg0OcXTy8Qz28HX1C3EM8nT08wz2BSr/DwA)
[Answer]
# JavaScript (ES6), 79
*Edit* As a leading newline is accepted, I can save 2 bytes
```
s=>eval("for(o='',v=i=0;c=s.charCodeAt(i);v%=27)o+=v++?c-63-v?' ':s[i++]:`\n`")
```
For 1 byte more, I can accept lowercase or uppercase input:
```
s=>eval("for(o='',v=i=0;c=s[i];v%=27)o+=v++?parseInt(c,36)-8-v?' ':s[i++]:`\n`")
```
*Less golfed*
```
s=>{
var i,o,c,v
for(o = '', v = 1, i = 0; c = s.charCodeAt(i); v %= 27)
o += v++ ? c-63-v ? ' ' : s[i++] : '\n'
return o
}
```
**Test**
```
f=s=>eval("for(o='',v=i=0;c=s.charCodeAt(i);v%=27)o+=v++?c-63-v?' ':s[i++]:`\n`")
function update() {
var i=I.value
i=i.replace(/[^A-Z]/gi,'').toUpperCase()
O.textContent=f(i)
}
update()
```
```
<input id=I value='BALLOON' oninput='update()' >
<pre id=O></pre>
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~18~~ 16 bytes
*-2 bytes thanks to @Shaggy*
```
;ò¨ £B®kX ?S:Z
·
```
Uppercase input only.
[Try it online!](https://ethproductions.github.io/japt/?v=1.4.5&code=O/KoIKNCrmtYID9TOloKtw==&input=IkFOVElESVNFU1RBQkxJU0hNRU5UQVJJQU5JU00i)
## Explanation
```
;
```
Switch to alternate variables, where `B` is the uppercase alphabet.
```
ò¨
```
Split the input string between characters where the first is greater than or equal to (`¨`) the second.
```
£
```
Map each partition by the function, where `X` is the current partition.
```
B®
```
Map each character in the uppercase alphabet to the following, with `Z` being the current letter.
```
kX
```
Remove all letters in the current partition from the current letter. If the current letter is contained in the current partition, this results in an empty string.
```
?S:Z
```
If that is truthy (not an empty string), return a space (`S`), otherwise return the current letter.
```
·
```
Join the result of the previous line with newlines and print the result.
[Answer]
# C (gcc), ~~91~~ 63 bytes
-28 thanks to ASCII-only
```
_;f(char*s){for(_=64;*s;)putchar(++_>90?_=64,10:*s^_?32:*s++);}
```
[Try it online!](https://tio.run/##S9ZNT07@/z/eOk0jOSOxSKtYszotv0gj3tbMxFqr2FqzoLQEJK6hrR1vZ2lgDxLXMTSw0iqOi7c3NgLS2tqa1rX/cxMz8zSAWjWUgkMcnb1dI5w9HP3cXZVAcgA)
---
Previous:
```
i,j;f(char*s){while(s[i]){for(j=65;j<91;j++)s[i]==j?putchar(s[i++]):printf(" ");puts("");}}
```
Yes, there's a shorter solution, but I noticed after I wrote this one... [Try it online!](https://tio.run/##S9ZNT07@/z9TJ8s6TSM5I7FIq1izujwjMydVozg6M1azOi2/SCPL1szUOsvG0tA6S1tbEyRua5tlX1BaAtIAUqetHatpVVCUmVeSpqGkoKRpDZQr1lACMmpr/@cmZuZpAA3SUIqKjAgPCw0JDgoM8Pfz9fH28vRwd3N1cXZyBKn8DwA)
[Answer]
# Pyth, 18 bytes
```
#pbVGp?JqhzNNd=>zJ
```
[Try it here.](http://pyth.herokuapp.com/?code=%23pbVGp%3FJqhzNNd%3D%3EzJ&input=antidisestablishmentarianism&debug=0)
Leading newline in output, lowercase alphabet.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 19 bytes
```
<2\¬0;œṗfȯ⁶$¥€@€ØAY
```
[Try it online!](https://tio.run/##y0rNyan8/9/GKObQGgPro5Mf7pyedmL9o8ZtKoeWPmpa4wDEh2c4Rv7//9/RL8TTxTPYNTjE0cnHM9jD19UvxDHI09HPM9gXAA "Jelly – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 18 bytes
```
ćIgµ¶?AvDyÊið?ë¼?ć
```
[Try it online!](https://tio.run/##ASwA0/8wNWFiMWX//8SHSWfCtcK2P0F2RHnDimnDsD/Dq8K8P8SH//9jb2RlZ29sZg "05AB1E – Try It Online")
Got trouble with 05AB1E `ć` (extract 1) leaving an empty string/list on the stack after the last element is extracted. This solution would be 1-2 bytes shorter if it weren't for that.
```
ćIgµ¶?AvDyÊið?ë¼?ć Implicit input
ć Extract the 1st char from the string
Igµ While counter != length of the string
¶? Print a newline
Av For each letter of the lowercased alphabet
DyÊ Is the examined character different from the current letter?
ið? If true, then print a space
ë¼?ć Else increment the counter, print the letter and push
the next character of the string on the stack
```
[Answer]
# Mathematica, 101 bytes
```
StringRiffle[
Alphabet[]/.#->" "&/@
(Except[#|##,_String]&@@@
Split[Characters@#,#==1&@*Order]),"
",""]&
```
[`Split`](http://reference.wolfram.com/language/ref/Split.html) the input into strictly increasing letter sequences, comparing adjacent letters with [`Order`](http://reference.wolfram.com/language/ref/Order.html). If `Order[x,y] == 1`, then `x` precedes `y` in the alphabet and thus can appear on the same line.
For each sequence of letters, create a pattern to match strings [`Except`](http://reference.wolfram.com/language/ref/Except.html) for those letters; `#|##` is a shorthand for [`Alternatives`](http://reference.wolfram.com/language/ref/Alternatives.html). Replace letters of the [`Alphabet`](http://reference.wolfram.com/language/ref/Alphabet.html) that match the pattern with spaces.
---
Illustration of the intermediate steps:
```
"codegolf";
Split[Characters@#,#==1&@*Order] &@%
Except[#|##,_String]&@@@ #&@%
Alphabet[]/.#->" "&/@ %
```
```
{{"c", "o"}, {"d", "e", "g", "o"}, {"l"}, {"f"}}
{Except["c" | "c" | "o", _String],
Except["d" | "d" | "e" | "g" | "o", _String],
Except["l" | "l", _String],
Except["f" | "f", _String]}
{{" "," ","c"," "," "," "," "," "," "," "," "," "," "," ","o"," "," "," "," "," "," "," "," "," "," "," "},
{" "," "," ","d","e"," ","g"," "," "," "," "," "," "," ","o"," "," "," "," "," "," "," "," "," "," "," "},
{" "," "," "," "," "," "," "," "," "," "," ","l"," "," "," "," "," "," "," "," "," "," "," "," "," "," "},
{" "," "," "," "," ","f"," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "}}
```
[Answer]
# [Zsh](https://www.zsh.org/), 65 bytes
***-4 bytes** thanks to @pxeger, **-2 bytes** thanks to @roblogic*
```
repeat $#1;echo&&for y ({A-Z})printf ${(Ml:1:)1[1]%$y}&&1=${1#$y}
```
~~[Try it online!](https://tio.run/##qyrO@J@moanxPy2/SEFDw1rZ0FpTs7rYlgvEr1TQqHbU04uq1SzWtlWpVqnW8NU0jDaMVVWprLXSjVGoVVMzBIobKgP5XDY2NirFtf81udIUIl19fPzD/wMA "Zsh – Try It Online")
[Try it online!](https://tio.run/##ldDNSgMxFAXgfZ7iQsZpsphCcJfWRcHZtYi6EP8WaSZpAjUpya0yDn32cYIirkSzOrkQznfznt1oGWejjQkYW1Cx4NxoF@u6THpgw2o@fzjxQ/IBLVQD2@ylkFw8iuezqj/VtbioBkGnOHJi4b5dr6/uSDmUUrhpV5ebFiglcrmcXc8IuVWvBgRse8hvHrXzYQc2xRfImErWMWiFJij0MQBG@GyWhPyZWJDfQNk8wU/ll@C8CPbGYnNQXVeKjdJumiCaVGrVlMMOHUQ7cX3IaFRXLvm4zejxiOWRR5i2cCCbf/h@@cIP "Zsh – Try It Online")~~
[Try it online!](https://tio.run/##ldBPS8MwGAbwez7FC6lde@ggeOvmYWBvG6IexD87pGmyBGpSkndKLfvsNUGR4UEwp@cNhOf35iPoOUh0A0LruZBC9EQVZTF7OUiOkFG2kkK7PFfOwwjFtKmeTuXgjUUF2VTs@prVJXtm@4tsPOU5u8omRmOcS6Lgsdlubx5IOpRSuGs217sGKCX1er24XRByz98kMGhHCO8GhTb2AMq7VwjoUxbOCo7ScjTOAjr4aq4JSZ6iWEVfWf4SLpfnxIT8AdbVC5wrvwWXSdBLhdXAuy4VSy50vEGUPtXymO0BNTgVucYGlLxLQzi2AQ0eMT0yCHELDXX1D98fX/gJ "Zsh – Try It Online")
Append to `$s` a `(M)` matched letter, `(l:1:)` left-padded to one character, then remove the letter if it matches the start of `$1`.
[Answer]
# Golfscript, ~~22~~ 21 bytes
[Try it online!](http://golfscript.apphb.com/?c=OyJDT0RFR09MRiIKey5uPnt9eycKJ1x9aWY6bn0lOm47)
*-1 byte thanks to careful final redefining of the `n` built-in.*
```
{.n>{}{'
'\}if:n}%:n;
```
Explanation (with a slightly different version):
```
{.n>{}{"\n"\}if:n}%:n; # Full program
{ }% # Go through every character in the string
.n> if # If ASCII code is greater than previous...
# (n means newline by default, so 1st char guaranteed to fit)
{} # Do nothing
{"\n"\} # Else, put newline before character
:n # Redefine n as the last used character
:n; # The stack contents are printed at end of execution
# Literally followed by the variable n, usually newline
# So because n is by now an ASCII code...
# ...redefine n as the new string, and empty the stack
```
[Answer]
# [Retina](https://github.com/m-ender/retina), 80 bytes
```
^
;¶
{`;.*
¶;ABCDEFGHIJKLMNOPQRSTUVWXYZ
¶¶
¶
)+`;(.*)(.)(.*¶)\2
$.1$* $2;$3
;.*
```
[Try it online!](https://tio.run/##K0otycxL/P8/jsv60Dau6gRrPS2uQ9usHZ2cXVzd3D08vbx9fP38AwKDgkNCw8IjIqOAskCFQKSpnWCtoaelqaEHRFqHtmnGGHGp6BmqaCmoGFmrGHOBTPr/39EvxNPFM9g1OMTRyccz2MPX1S/EMcjT0c8z2BcA "Retina – Try It Online")
There is always exactly one leading newline. The code somewhat clunkily prepends the word with the alphabet along with a marker (semicolon). It then moves the marker up to the first letter of the word, while changing all other letters it passes into spaces. It also removes the first letter of the word. It repeats this until the first letter of the word isn't after the marker anymore. Then it clears that marker and the rest of the alphabet, and replaces it with a new line and the alphabet with a marker again. It keeps repeating this until the input word is empty, then it cleans up the last alphabet and marker, leaving the desired output.
[Answer]
# [Python 3](https://docs.python.org/3/), ~~87~~ 85 bytes
```
def f(s,l=65):c,*t=s;o=ord(c)-l;return o<0and'\n'+f(s)or' '*o+c+(t and f(t,o-~l)or'')
```
[Try it online!](https://tio.run/##K6gsycjPM/7/PyU1TSFNo1gnx9bMVNMqWUerxLbYOt82vyhFI1lTN8e6KLWktChPId/GIDEvRT0mT10bqFozv0hdQV0rXztZW6NEASgBNKJEJ1@3Lgcko675v6AoM69EI01D3dHJWV1T0xrC1@SCizs7OWIVd3L08fH390OS@w8A "Python 3 – Try It Online")
[Answer]
# [Retina](https://github.com/m-ender/retina), ~~130~~ 126 bytes
```
$
¶A
{-2=`
$'
}T`RL`_o`.$
+`(?<=(.)*)((.).*¶(?<-1>.)*(?(1)(?!)).+\3.*$)
$2
(?<=(.)*)((.).*¶(?<-1>.)*(?<-1>\3.*$))
¶$2
}`¶.*$
```
[Try it online!](https://tio.run/##K0otycxL/P9fhevQNkeual0j2wQuFXWu2pCEIJ@E@PwEPRUu7QQNextbDT1NLU0NIKmndWgbUEDX0A4oomGvYaipYa@oqamnHWOsp6WiyaWgYsSFTwOIAVGqCbQTqLg24dA2IJfr/39HvxBPF89g1@AQRycfz2APX1e/EMcgT0c/z2BfAA "Retina – Try It Online") Edit: Saved 4 bytes by using @MartinEnder's alphabet generator. Explanation:
```
$
¶A
{-2=`
$'
}T`RL`_o`.$
```
Append the alphabet.
```
+`(?<=(.)*)((.).*¶(?<-1>.)*(?(1)(?!)).+\3.*$)
$2
```
Align as many letters as possible with their position in the alphabet.
```
(?<=(.)*)((.).*¶(?<-1>.)*(?<-1>\3.*$))
¶$2
```
Start a new line before the first letter that could not be aligned.
```
}`¶.*$
```
Delete the alphabet, but then do everything over again until there are no misaligned letters.
[Answer]
# [J](http://jsoftware.com/), 39 bytes
```
(_65+3 u:[)}&(26{.'')/.~0+/\@,2>:/\3&u:
```
[Try it online!](https://tio.run/##Zc5BC4IwAMXxu5/iHcJNJk6UPIyKvkdGzBo40W24eYr66otFt84P3v83xeiOAvTW7VmLTVyKV06b7lkRUvDqXTPen8vmJHjf5puI6j5aHByC3ZxTK8gg59laQ7K/RZqgH9orH@Qwaz8uygS5amm0X0iWoumb1ijRIAWQCgW@FjAkDX6cHUHi4Bo/)
[Answer]
# [q/kdb+](http://kx.com/download/), ~~48~~ 45 bytes
**Solution:**
```
-1{@[26#" ";.Q.A?x;:;x]}@/:(0,(&)(<=':)x)_x:;
```
[Try it online!](https://tio.run/##y9bNz/4f6Gil5Ojk7OLq5u7h6eXt4@vnHxAYFBwSGhYeERml9D/BwKraIdrITFlJQck60NG@wtrKuiK21kHfSkOtTsNO3UqzQjO@wkrJydHHx9/fT8n6/38A "K (oK) – Try It Online")
**Note:** Link is to a [K (oK)](https://github.com/JohnEarnest/ok) port of this solution as there is no TIO for q/kdb+.
**Examples:**
```
q)-1{@[26#" ";.Q.A?x;:;x]}@/:(0,(&)(<=':)x)_x:"STACKEXCHANGE";
ST
A C K
E X
C H
A N
G
E
q)-1{@[26#" ";.Q.A?x;:;x]}@/:(0,(&)(<=':)x)_x:"BALLOON";
B
A L
L O
O
N
```
**Explanation:**
Q is interpreted right-to-left. The solution is split into two parts. First split the string where the next character is less than or equal to the current:
`"STACKEXCHANGE"` -> `"ST","ACK","EX","CH","AN","G","E"`
Then take a string of 26 blanks, and apply the input to it at the indices where the input appears in the alphabet, and print to stdout.
`"__________________________"` -> `__________________ST______`
Breakdown:
```
-1{@[26#" ";.Q.A?x;:;x]}each(0,where (<=':)x) cut x:; / ungolfed solution
-1 ; / print to stdout, swallow return value
x: / store input as variable x
cut / cut slices x at these indices
( ) / do this together
(<=':)x / is current char less-or-equal (<=) than each previous (':)?
where / indices where this is true
0, / prepended with 0
each / take each item and apply function to it
{ } / lambda function with x as implicit input
@[ ; ; ; ] / apply[variable;indices;function;arguments]
26#" " / 26 take " " is " "...
.Q.A?x / lookup x in the uppercase alphabet, returns indice(s)
: / assignment
x / the input to apply to these indices
```
**Notes:**
* -3 bytes by replacing prev with the K4 version
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 15 bytes
```
Fθ«J⌕αι⁺ⅉ‹⌕αιⅈι
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z8tv0hBo1BToZqL06s0tyAkX8MtMy9FI1FHIVNTRyEgp7RYI1IDyPJJLS5GkYrQ0AQCay7OgKLMvBKNTCCz9v9/R78QTxfPYNfgEEcnH89gD19XvxDHIE9HP89g3/@6ZTkA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
θ Input string
F « Loop over characters
α α Uppercase letters predefined variable
ι ι Current character
⌕ ⌕ Find index
ⅈ Current X co-ordinate
‹ Compare
ⅉ Current Y co-ordinate
⁺ Sum
J Jump to aboslute position
ι Print current character
```
[Answer]
# [APL (Dyalog Classic)](https://www.dyalog.com/), 20 bytes
```
⊃¨⎕a∘.∩⍨⊢⊂⍨1,2≥/⎕a⍳⊢
```
[Try it online!](https://tio.run/##rZXLTsJAFIb3PMXZDSR4Xbob2oEOl3Jpue4aLoZIggE3xrhBYwBTowsT1yQm6Na4cemjzIvgBLBSKJyi/otmOvP1zMzp/Ges09ZO7dxqtY93qi2r221WJ@LusdkWN/f7k4Z8iuHV51h2WaL/tCv6L8Iei@FIDHuycRA@FIPnvemo/Sa7J5Mz@cmFsN/FYNSRzYawP45Iw2q2SLAm7Ff5Kgc7IXF7Tdon5DIQqMN0kh4BUOBH6YU2CdTDDgQqgxgKfSsJLi1DUfAQCRAlrbJYOhklcjsPddcil2WYK6Gps5MEbJyfrYYrLUHTSJrXIhemW5C@abtO4rZb0ywnhkmVBCspGtVjzEdi5qp4/xiXyoBDJcChIuBQAXAoDzhkAg4ZgEM5wKEs4FAGcAj3C3aAZkoB/NV5fuwxVRxwiAMOaYBDPuyxrmT48pCrjAEOKYBDEcAhCushUimXioW8aeSymbSeSibiXItFmapEqGNyGSaMJSAYJlESWi4LHrXJ/PVvVN2Q4Sf5XuU5ssUh5T7MrKGeYFgK6DZlgf/TbeBvd56OJ1Q3ucoNJm@FSJIbWorpJs1xqnMjNT83Xw "APL (Dyalog Classic) – Try It Online")
[Answer]
# [K (ngn/k)](https://gitlab.com/n9n/k), ~~29~~ 28 bytes
```
{{x@x?`c$65+!26}'(&~>':x)_x}
```
[Try it online!](https://tio.run/##pZRPa8JAEMXvforXIFUpvRTqIYG2m2RNVk2iJmpUpJaCpVgsiIeI6FdP/W/UZGLbdwr82N2ZyXszuh9/jMNwKM/nwUvwPHjPFh/vbh6Ki1z@dvmUk4PCa7AIp/I825stJ/IQQKAMvkdKfjB8@/xSAmWmTAr9RWbakzRH54ZTLUkZIC8BGo5yIt9rjhWHzmFQfK8qThThJcRIKvTX5bge0yrc10xmG3xf07lcL3onO9RcQdKb/PIS/8g3582Ymnb3R2Qn9HSYydXvH3vudvx2q@m5jXrNsa1qpSxMo8R1TWVJA9ipezH0E3VAch8kb4PkLZC8CZJ7ILkLkjdA8jpIXgPJSVMTBtjKAv4WihQDb1QGyQVIboLktIETQptm8MPSAMk1kFwFyVliQHYBY7YndOHy1XJRq8I1LW57rCGYLVxrG7GYjHu/HLF@yt2UEZ3tMPU6iwg6IiZlQU70x66MmPjXjkytPy5Cq18Y/gA "K (ngn/k) – Try It Online")
`{` `}` function with argument `x`
`>':x` for each char, is it greater than the previous char?
`~` negate
`&` where (at which indices) do we have true
`(` `)_x` cut `x` at those indices, return a list of strings
`{` `}'` for each of those strings
```
`c$65+!26
```
the English alphabet
`x?` find the index of the first occurrence of each letter in `x`, use `0N` (a special "null" value) if not found
`x@` index `x` with that; indexing with `0N` returns `" "`, so we get a length-26 string in which the letters from `x` are at their alphabetical positions and everything else is spaces
[Answer]
# [R](https://www.r-project.org/), ~~129~~ 117 bytes
```
function(s){z={}
y=diff(x<-utf8ToInt(s)-64)
z[diffinv(y+26*(y<0))+x[1]]=LETTERS[x]
z[is.na(z)]=" "
write(z,1,26,,"")}
```
[Try it online!](https://tio.run/##XY5Ba8IwAIXv/RUlXpKZDpVRPDSHOOMWiC2YnNb1UGoDAUmlja6t@Nu7CJ68Pd734HvtpMMkmvTFVs40FnboNpLbPRjI0WgN@yS6OL1WDbfOsyj@QMGYP5CxVzjMV/EbHJIFQvM@XxYFEUwpdpB5X/iZ6d5tCUdUEBCC4K81roYjXuJVjDEA6D5pCD6zLfvKxA6goCodBL/WJ9/TVPEtl0wquhFcfu9ZquiB05TL/et2Q4XIsvSlPped97X1FT5PIVw1p1N57mri7SicheAnomD6Bw "R – Try It Online")
Explanation (ungolfed):
```
function(s){
z <- c() # initialize an empty vector
x <- utf8ToInt(s)-64 # map to char code, map to range 1:26
y <- diff(x) # successive differences of x
idx <- cumsum(c( # indices into z: cumulative sum of:
x[1], # first element of x
ifelse(y<=0,y+26,y))) # vectorized if: maps non-positive values to themselves + 26, positives to themselves
z[idx] <- LETTERS[x] # put letters at indices
z[is.na(z)] <- " " # replace NA with space
write(z,"",26,,"") # write z as a matrix to STDOUT ("") with 26 columns and empty separator.
```
[Answer]
# [R](https://www.r-project.org/), 95 bytes
Just run through the upper case alphabet repeatedly while advancing a counter by 1 if you encounter the letter in the counter position of the word and printing out the letter, a space otherwise.
```
function(s)while(F>""){for(l in LETTERS)cat("if"((F=substr(s,T,T))==l,{T=T+1;l}," "));cat("
")}
```
[Try it online!](https://tio.run/##LcrLCoJAFIDhvU8hZzWHbNHaDCYddcpLOafrrqQhQRS80EJ8dotq@fN/zaSX80n3Vd4VdcVafD2L8sH8FQAOum5YaRaVGQkikSnMbx2DQgNjvtP297ZrWGuRRYiOU1oDOTRb2OVogQmI9lcbgOOkGbipJ4I08gGNT10v59PxQCrb79IkjrYbGQa@8Nw1//0/4wlJTyqhiK8jqcJYJMQzyROpYsDpDQ "R – Try It Online")
[Answer]
# [GolfScript](http://www.golfscript.com/golfscript/), 37 bytes
```
64:a;{.a>{}{'
'\64:a;}if.a-(' '*\:a}%
```
[Try it online!](https://tio.run/##S8/PSStOLsosKPn/38zEKtG6Wi/Rrrq2Wp1LPQbMr81M00vU1VBXUNeKsUqsVf3/39HJ2cXVzd3D08vbx9fPPyAwKDgkNCw8IjIqKjIiPCw0JDgoMMDfz9fH28vTw93N1cXZyREA "GolfScript – Try It Online")
I did a Golfscript one under a different name, but it had incorrect output.
[Answer]
# [Ruby](https://www.ruby-lang.org/) `-n`, 62 bytes
Scans the input string for sequences of increasing letters, and for each sequence, replace letters not in the sequence with spaces.
```
g=*?A..?Z
$_.scan(/#{g*??}?/){puts g.join.tr"^#$&"," "if$&[0]}
```
[Try it online!](https://tio.run/##NcvbCoIwAIDh@z1FLImSWr1AjKlLl3Mrt85UVJDYhYaHixBfvRVB//X3F/X1ZUwytTFBCO@BdUbl7ZL1x90msTFu8XjQPOuq7CTokacZqgp46lo9OIQdmN6t3mFybM0PwNE/aFzpUV/yGVCauCHdugERPgX73XazXmkVLxdSRDycs8CfUc91CCBCM48p@h0czlQQUaFJzIhgKgIO4VxK8c6fVZpnpRllHw "Ruby – Try It Online")
[Answer]
# Powershell, ~~70~~ 63 bytes
*-7 bytes thanks @Veskah*
```
$args|%{if($_-le$p){$x;rv x}
$x=("$x"|% *ht($_-65))+($p=$_)}
$x
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfmvkmZb/V8lsSi9uEa1OjNNQyVeNydVpUCzWqXCuqhMoaKWS6XCVkNJpUKpRlVBK6MEpMDMVFNTW0OlwFYlXhMk/x9I5CrYKig5@7u4uvv7uClxqamkKTjk/v8PAA "PowerShell – Try It Online")
Explanation:
For each character in the splatted argument:
* Output string `$x` and clear `$x` value (`rv` is alias for [Remove-Variable](https://docs.microsoft.com/en-us/powershell/module/Microsoft.PowerShell.Utility/Remove-Variable)), if a code of the current character less or equivalent (`-le`) to a code of the previous character.
* Append spaces and the current character to `$x`, store it to `$x`. Also it freshes a previous character value.
Output last `$x`.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~21~~ ~~19~~ 17 bytes
```
Çü@0šÅ¡vð₂×yAykǝ,
```
[Try it online!](https://tio.run/##AUIAvf9vc2FiaWX//8OHw7xAMMWhw4XCoXbDsOKCgsOXeUF5a8edLP//Y29kZWdvbGZhbmRwcm9ncmFtbWluZ3B1enpsZXM "05AB1E – Try It Online")
```
Ç push a list of ascii values of the input [84, 69, 83, 84]
ü@ determine which letter is >= the next letter [1, 0, 0]
0š prepend a 0 (false) to that list [0, 1, 0, 0]
Å¡ split input on true values [["T"], ["E", "S", "T"]]
v for each list entry
ð₂× push 26 spaces
y push list entry (letters)
Ayk push the positions of that letters in the alphabet
ǝ replace characters c in string a with letters b
, print the resulting string
implicitly close for-loop
```
[Answer]
# [Hexagony](https://github.com/m-ender/hexagony), 91 bytes
```
A"$>}\$<>~,<.'~<\.';<.>$${}\../<..>=<...-/.$/=*=32;.>~<>"){-\}.>_{A}\\../010<$..>;=~<$@{{Z'
```
More readably:
```
A " $ > } \
$ < > ~ , < .
' ~ < \ . ' ; <
. > $ $ { } \ . .
/ < . . > = < . . .
- / . $ / = * = 3 2 ;
. > ~ < > " ) { - \
} . > _ { A } \ \
. . / 0 1 0 < $
. . > ; = ~ <
$ @ { { Z '
```
And with color paths:
[![enter image description here](https://i.stack.imgur.com/56IXI.png)](https://i.stack.imgur.com/56IXI.png)
[Try it online!](https://tio.run/##Fco9C8IwEAbg/1IOgmLfVB1zORr8WoTuciAOpU66Wo7kr8d2eabnPf5e0/cz15oakqzEUnYMV1jhAkOILCvgGZC4gNaDfNzG4yFACkuzsVYz5Gkp6zq7fce07BALU2/2cLWehvPlNtyvfw "Hexagony – Try It Online")
] |
[Question]
[
A regular string looks like this:
```
Hello,IAmAStringSnake!
```
And a string snake looks something like this:
```
Hel
l rin
o,IAmASt g
S
!ekan
```
## Your Task
String snakes are dangerous, so you must make a program that takes a string snake as input and outputs it as a regular string.
## Specifications
* Input can be a multiline string or an array of strings.
* Each line of the input will be padded with spaces to form a rectangular grid.
* Characters in the snake can only connect to adjacent characters above, below, left or right of them (just like in the game Snake). They cannot go diagonal.
* The snake characters will never be adjacent to another part of the snake, only the connected characters.
* The first character of the string is the end character with the shortest [Manhattan distance](https://en.wikipedia.org/wiki/Taxicab_geometry) from the top-left corner of the input grid (i.e. the minimum number of moves it would take for a snake to go directly from the end character to the top-left corner). Both ends will never have the same distance.
* The string can contain any ASCII character between code points 33 and 126 inclusive (no spaces or newlines).
* The string will be between 2 and 100 characters long.
* Shortest code in bytes wins.
## Test Cases
*(Input grid, followed by the output string)*
```
Hel
l rin
o,IAmASt g
S
!ekan
Hello,IAmAStringSnake!
----------
Python
Python
----------
P ngPu Code
r i z d G
o m z n o
gram lesA lf
ProgrammingPuzzlesAndCodeGolf
----------
~ zyx tsr XWVUTSR
}|{ wvu q Y Q
! p Z `ab P
"#$ 6789:; o [ _ c O
% 5 < n \]^ d N
('& 432 = m e M
) 1 > lkjihgf L
*+,-./0 ? K
@ABCDEFGHIJ
!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~
----------
tSyrep
r p
in Sli
g Sile
Snakes n
Ser ylt
a eh ilS
fe w t
emo h
Sre
SlipperyStringSnakesSilentlySlitherSomewhereSafe
```
[Answer]
# JavaScript (ES6) + [SnakeEx](http://www.brianmacintosh.com/snakeex/), 176 bytes
```
a=b=>snakeEx.run("s{A}:<+>([^ ]<P>)+",b).reduce((c,d)=>(e=c.marks.length-d.marks.length)>0?c:e?d:c.x+c.y>d.x+d.y?d:c).marks.reduce((c,d,e,f)=>e%2?c+b.split`\n`[d][f[e-1]]:c,"")
```
Remember SnakeEx? Good, because neither do I! Golfing suggestions welcome.
[Answer]
# [MATL](https://esolangs.org/wiki/MATL), 80 bytes
*Thanks to @LevelRiverSt for a correction*
```
32>2#fJ*+X:4Mt1Y6Z+l=*2#fJ*+ttXjwYj+K#X<)wt!"tbb6#Yk2#)yw]xxvtXjwYjqGZy1)*+Gw)1e
```
Input is as a 2D array of char, with rows separated by `;`. The test cases in this format are
```
['Hel ';' l rin';' o,IAmASt g';' S';' !ekan']
['Python']
['P ngPu Code ';'r i z d G ';'o m z n o ';'gram lesA lf']
[' ~ zyx tsr XWVUTSR';' }|{ wvu q Y Q';'! p Z `ab P';'"#$ 6789:; o [ _ c O';' % 5 < n \]^ d N';'(''& 432 = m e M';') 1 > lkjihgf L';'*+,-./0 ? K';' @ABCDEFGHIJ']
[' tSyrep ';' r p ';' in Sli ';' g Sile';' Snakes n';'Ser ylt';'a eh ilS ';'fe w t ';' emo h ';' Sre ']
```
[**Try it online!**](http://matl.tryitonline.net/#code=MzI-MiNmSiorWDo0TXQxWTZaK2w9KjIjZkoqK3R0WGp3WWorSyNYPCl3dCEidGJiNiNZazIjKXl3XXh4dnRYandZanFHWnkxKSorR3cpMWU&input=WycgIHRTeXJlcCAgICAnOycgIHIgICAgcCAgICAnOycgIGluIFNsaSAgICAnOycgICBnICAgIFNpbGUnOycgICBTbmFrZXMgIG4nOydTZXIgICAgICB5bHQnOydhIGVoICAgaWxTICAnOydmZSB3ICAgdCAgICAnOycgICBlbW8gaCAgICAnOycgICAgIFNyZSAgICAnXQ)
### Explanation
The coordinates of each nonspace character is represented by a complex number. For each current character, the next is obtained as that which is closest (minimum absolute difference of their complex coordinates).
To determine the initial char, the two endpoints need to be found. This is done as follows. An endpoint is a nonspace char that has exactly one nonspace neighbour. The number of neighbours is obtained by 2D convolution with a suitable mask. The initial point is the endpoint whose complex coordinate has the least sum of real and imaginary parts; i.e. is closest in Manhattan distance to the complex number 0, or equivalently to 1+1j, which is the complex coordinate of the upper left corner.
```
32> % Take input as 2D char array. Compute 2D array with true for nonspace,
% false for space
2#f % Arrays of row and column indices of nonspaces
J*+ % Convert to complex array. Real part is row, imaginary part is column
X: % Convert to column array
4Mt % Push arrays of zeros and ones again. Duplicate
1Y6 % Push array [0 1 0; 1 0 1; 0 1 0]. Used as convolution mask to detect
% neighbours that are nonspace
Z+ % 2D convolution with same size as the input
1= % True for chars that have only one neighbour (endpoints)
* % Multiply (logical and): we want nonspaces that are endpoints
2#fJ*+ % Find complex coordinates (as before)
ttXjwYj % Duplicate. Take real and imaginary parts
+ % Add: gives Manhattan distance to (0,0)
K#X< % Arg min. Entry with minimum absolute value has least Manhattan
% distance to (0,0), and thus to (1,1) (top left corner)
) % Apply as an index, to yield complex coordinate of initial endpoint
wt! % Swap, duplicate, transpose.
% The stack contains, bottom to top: complex coordinates of initial
% endpoint, column array with all complex coordinates, row array of all
% coordinates. The latter is used (and consumed) by the next "for"
% statement to generate that many iterations
" % For loop. Number of iterations is number of nonspaces
tbb % Duplicate, bubble up twice (rearrange is stack)
6#Yk % Find which of the remaining points is closest to current point. This
% is the next char in the string
2#) % Remove the point with that index from the array of complex
% coordinates. Push that point and the rest of the array
yw % Duplicate extracted point, swap
] % End for
xx % Delete top two elements of the stack
v % Concatenate all stack contents into a column array. This array
% contains the complex coordinates of chars sorted to form the string
tXjwYj % Extract real part and imaginary part
GZy1) % Number of rows of input. Needed to convert to linear index
*+ % Convert rows and columns to linear index
Gw % Push input below that
) % Index to get the original chars with the computed order
1e % Force the result to be a row array (string). Implicitly display
```
[Answer]
# C ~~198~~ ~~190~~ ~~179~~ ~~180~~ 181 bytes
Edit: Used the tip by user81655 and removed the parenthesis in the ternary operator, thanks! I also changed the cumbersome (S&1) test for evenness for the more appropriate (and shorter!) S%2.
Edit2: Using the \*a addressing style heavily, made me blind to the obvious optimizations in the definition of S, i.e., replacing \*(a+m) by a[m] etc. I then replaced S itself by T, which essentially does half of what S does. The code also now takes advantage of the return value of putchar.
Edit3: Fixed bug that has been around from the beginning, the Manhattan-search stopping criteria a < b+m is correct only if a has already been decremented. This adds 2 bytes, but one is regained by making the definition of m global.
Edit4: My golfing has passed the minimum and is going the wrong way now. Another bug fix related to the Manhattan-search. I originally had in-bound checks in place and without those the search continues for large input arrays (somewhere round 50x50) beyond the array b. Hence that array has to be expanded to at least twice the previous size, which adds one more byte.
```
#define T(x)+x*((a[x]>32)-(a[-x]>32))
m=103;main(){char b[m<<8],*e=b,*a=e+m;while(gets(e+=m));for(e=a;(T(1)T(m))%2**a<33;a=a<b+m?e+=m:a)a-=m-1;for(;*a;a+=T(1)T(m))*a-=putchar(*a);}
```
Ungolfed and explained:
```
/* T(1)T(m) (formerly S) is used in two ways (we implicitly assume that each cell has
one or two neighbors to begin with):
1. (in the first for-loop) T(1)T(m) returns an odd (even) number if cell a has one (two)
neighbors with ASCII value > 32. For this to work m must be odd.
2. (in the second for-loop) at this stage each cell a in the array at which T(1)T(m) is
evaluated has at most one neighboring cell with ASCII value > 32. T(1)T(m) returns the
offset in memory to reach this cell from a or 0 if there is no such cell.
Putting the + in front of x here saves one byte (one + here replaces two
+ in the main part)
#define T(x)+x*((a[x]>32)-(a[-x]>32))
/* A snake of length 100 together with the newlines (replaced by 0:s in memory) fits
an array of size 100x101, but to avoid having to perform out-of-bounds checks we
want to have an empty line above and the array width amount of empty lines below
the input array. Hence an array of size 202x101 would suffice. However, we save
a (few) bytes if we express the array size as m<<8, and since m must be odd
(see 1. above), we put m = 103. Here b and e point to the beginning of the (now)
256x103 array and a points to the beginning of the input array therein */
m=103;
main()
{
char b[m<<8],*e=b,*a=e+m;
/* This reads the input array into the 256x103 array */
while(gets(e+=m));
/* Here we traverse the cells in the input array one
constant-Manhattan-distance-from-top-left diagonal at a time starting at the top-left
singleton. Each diagonal is traversed from bottom-left to top-right since the starting point
(memory location e) is easily obtained by moving one line downwards for each diagonal
(+m) and the stopping point is found by comparing the present location a to the input array
starting position (b+m). The traversal is continued as long as the cell has either
an ASCII value < 33 or it has two neighbors with ASCII value > 32 each (T(1)T(m)
is even so that (T(1)T(m))%2=0).
Note that the pointer e will for wide input arrays stray way outside (below) the
input array itself, so that for a 100 cell wide (the maximum width) input array
with only two occupied cells in the bottom-right corner, the starting cell
will be discovered 98 lines below the bottom line of the input array.
Note also that in these cases the traversal of the diagonals will pass through the
right-hand side of the 103-wide array and enter on the left-hand side. This, however,
is not a problem since the cells that the traversal then passes have a lower
Manhattan distance and have thereby already been analyzed and found not to contain
the starting cell. */
for(e=a;(T(1)T(m))%2**a<33;a=a<b+m?e+=m:a)a-=m-1;
/* We traverse the snake and output each character as we find them, beginning at the
previously found starting point. Here we utilize the function T(1)T(m), which
gives the offset to the next cell in the snake (or 0 if none), provided that
the current cell has at most one neighbor. This is automatically true for the
first cell in the snake, and to ensure it for the rest of the cells we put the
ASCII value of the current cell to 0 (*a-=putchar(*a)), where we use the fact
that putchar returns its argument. The value 0 is convenient, since it makes the
stopping condition (offset = 0, we stay in place) easy to test for (*a == 0). */
for(;*a;a+=T(1)T(m))
*a-=putchar(*a);
}
```
[Answer]
# APL, 55 bytes
```
{⍵[1↓(⊂0 0){1<⍴⍵:⍺,∆[⊃⍋+/¨|⍺-∆]∇∆←⍵~⍺⋄⍺}(,⍵≠' ')/,⍳⍴⍵]}
```
This function takes a character matrix with the string snake in it.
Example:
```
s1 s2 s3
┌────────────┬──────────────┬────────────────────┐
│Hel │P ngPu Code │ ~ zyx tsr XWVUTSR│
│ l rin│r i z d G │ }|{ wvu q Y Q│
│ o,IAmAst g│o m z n o │! p Z `ab P│
│ S│gram lesA lf│"#$ 6789;: o [ _ c O│
│ !ekan│ │ % 5 < n \]^ d N│
│ │ │('& 432 = m e M│
│ │ │) 1 > lkjighf L│
│ │ │*+,-./0 ? K│
│ │ │ @ABCDEFGHIJ│
└────────────┴──────────────┴────────────────────┘
↑ {⍵[1↓(⊂0 0){1<⍴⍵:⍺,∆[⊃⍋+/¨|⍺-∆]∇∆←⍵~⍺⋄⍺}(,⍵≠' ')/,⍳⍴⍵]} ¨ s1 s2 s3
Hello,IAmAstringSnake!
ProgrammingPuzzlesAndCodeGolf
!"#$%&'()*+,-./0123456789;:<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefhgijklmnopqrstuvwxyz{|}~
```
Explanation:
* `(,⍵≠' ')/,⍳⍴⍵`: get the coordinates of all non-spaces
* `(⊂0 0)`: begin at (0,0) (which is an invalid coordinate)
* `{`...`}`: follow the snake, given position and snake:
+ `1<⍴⍵:`: if there is more than 1 element left:
- `∆←⍵~⍺`: remove the current position from the snake and store it in `∆`.
- `+/¨|⍺-∆`: find the distance between the current position and each point in the rest of the snake
- `∆[⊃⍋...`]`: get the closest point on the snake
- `∇`: run the function again, with the closest point as the new current point and the shortened snake as the new snake.
- `⍺,`: add the current position to the result of that
+ `⋄⍺`: otherwise, just return the current position
* `1↓`: drop the first item from the result (which is the (0,0) position)
* `⍵[`...`]`: get those elements from ⍵, in that order
[Answer]
# C, 272 bytes
```
#define E j+(p/2*i+1)*(p%2*2-1)
#define X(Y) a[Y]&&a[Y]-32
char A[999],*a=A+99;j,p,t;i;main(c){for(;gets(++j+a);j+=i)i=strlen(a+j);for(c=j;j--;){for(t=p=4;p--;)t-=X(E);t==3&&X(j)?c=c%i+c/i<j%i+j/i?c:j:0;}for(j=c;c;){putchar(a[j]),a[j]=0;for(c=0,p=4;!c*p--;)X(E)?c=j=E:0;}}
```
Look at @Zunga's source. Now look at mine. Want to know how I got the extra 91-bytes?
Ungolfed:
```
#define E j+(p/2*i+1)*(p%2*2-1)
#define X(Y) a[Y]&&a[Y]-32 //can be more concise, see @Zunga's
//and then doesn't need the define
char A[999],*a=A+99;j,p,t;i;
main(c){for(;gets(++j+a);j+=i)
i=strlen(a+j); //we don't need to know the length of a line
//in @Zunga's solution, lines are spaced a constant distance apart
for(c=j;j--;){
for(t=p=4;p--;)t-=X(E); //a ton of bytes can be saved with determining
//the neighbors, see @Zunga's source
t==3&&X(j)?
c=c%i+c/i<j%i+j/i?c:j:0;} //we search for ends of the snake,
//and compute the Manhattan distance
for(j=c;c;){putchar(a[j]),a[j]=0;
for(c=0,p=4;!c*p--;) //determining the neighbors again
X(E)?c=j=E:0;}}
```
[Answer]
## Python (2 and 3), 640 624 604 583 575 561 546 538 bytes
I'm still a golfing n00b so this is a bit large.
Edit: Thanks to [@porglezomp](https://codegolf.stackexchange.com/users/52916/porglezomp) for the suggestions! I didn't remove all the 'and' operators as that would break Python 3.
Edit2: Thanks to [@Aleksi Torhamo](https://codegolf.stackexchange.com/users/18726/aleksi-torhamo) for the comment about isspace(). The resulting reduction compensates for the bugfix I put in. Also thanks to anonymous for the syntax highlighting!
Edit3: Thanks to [@mbomb007](https://codegolf.stackexchange.com/users/34718/mbomb007) for a few additional bytes.
```
import sys;s=sys.stdin.read().split('\n');m={};q=[];o=len;j=o(s);r=range;g='!'
for y in r(j):
v=s[y];f=o(v);d=y+1
for x in r(f):
n=[];a=n.append;U=s[y-1]
if v[x]>=g:j>=y>0==(U[x]<g)<=x<o(U)and a((x,y-1));j>y>=0==(v[x-1]<g)<x<=f and a((x-1,y));j>y>-1<x+1<f>(v[x+1]<g)<1and a((x+1,y));j>d>-1<x<o(s[d])>(s[d][x]<g)<1and a((x,d));m[x,y]=[v[x],n];o(n)-1or q.append((x,y))
t=min(q,key=sum);w=sys.stdout.write;w(m[t][0]);c=m[t][1][0]
while o(m[c][1])>1:
b=m[c][1];w(m[c][0])
for k in r(o(b)):
if b[k]!=t:t=c;c=b[k];break
print(m[c][0])
```
And here's my pre-golf version
```
import sys
lines = sys.stdin.read().split('\n')
startend = []
mydict = {}
for y in range( 0, len(lines)):
for x in range( 0, len(lines[y])):
if not lines[y][x].isspace():
neighbors = []
if x>=0 and x<len(lines[y-1]) and y-1>=0 and y-1<len(lines):
if not lines[y-1][x].isspace():
neighbors.append( (x,y-1) )
if x-1>=0 and x-1<len(lines[y]) and y>=0 and y<len(lines):
if not lines[y][x-1].isspace():
neighbors.append( (x-1,y) )
if x+1>=0 and x+1<len(lines[y]) and y>=0 and y<len(lines):
if not lines[y][x+1].isspace():
neighbors.append( (x+1,y) )
if x>=0 and x<len(lines[y+1]) and y+1>=0 and y+1<len(lines):
if not lines[y+1][x].isspace():
neighbors.append( (x,y+1) )
mydict[(x,y)] = [ lines[y][x], neighbors ]
if len( neighbors ) == 1:
startend.append( (x,y) )
startend.sort( key=lambda x : x[0]*x[0] + x[1]*x[1] )
last = startend[0]
sys.stdout.write( mydict[ last ][0] )
current = mydict[last][1][0]
while len( mydict[current][1] ) > 1:
sys.stdout.write( mydict[current][0] )
for k in range( 0, len( mydict[current][1] ) ):
if mydict[current][1][k] != last:
last = current
current = mydict[current][1][k]
break
print(mydict[current][0])
```
[Answer]
# JavaScript (ES6), 195
See explanation inside the test snippet
```
s=>[...s].map((c,i)=>{if(c>' '&([n=-1,1,o=-~s.search('\n'),-o].map(d=>n+=s[i+d]>' '&&!!(e=d)),n<1)&m>(w=i/o+i%o|0))for(m=w,r=c,p=i+e;r+=s[i=p],[e,o/e,-o/e].some(d=>s[p=i+(e=d)]>' '););},m=1/0)&&r
```
**Test**
```
f=s=>[...s].map((c,i)=>{if(c>' '&([n=-1,1,o=-~s.search('\n'),-o].map(d=>n+=s[i+d]>' '&&!!(e=d)),n<1)&m>(w=i/o+i%o|0))for(m=w,r=c,p=i+e;r+=s[i=p],[e,o/e,-o/e].some(d=>s[p=i+(e=d)]>' '););},m=1/0)&&r
// Less golfed
u=s=>(
o = -~s.search('\n'), // offset between lines
m = 1/0, // current min manhattan distance, init at infinity
// scan input looking for the 2 ends of the string
[...s].map((c,i)=>{ // for each char c at position i
if(c > ' ' // check if part of the string
& ( [-1,1,o,-o] // scan in 4 directions and count neighbors
.map(d=> n+=s[i+d]>' '&&!!(e=d), n=0), // remember direction in e
n < 2) // if at end of string will have exactly 1 neighbor
& (w = i/o + i%o |0) < m) // manhattan distance in w, must be less than current min
// found one of the ends, follow the path and build the string in r
for(m = w, r = c, p = i+e;
r += s[i=p],
[e,o/e,-o/e] // check 3 directions, avoiding to go back
.some(d=>s[p=i+(e=d)]>' '); // save candidate position and direction in p and e
); // empty for body, all the work is inside the condition
}),
r
)
console.log=x=>O.textContent+=x+'\n'
;[`Hel
l rin
o,IAmASt g
S
!ekan`,
` ~ zyx tsr XWVUTSR
}|{ wvu q Y Q
! p Z \`ab P
"#$ 6789:; o [ _ c O
% 5 < n \\]^ d N
('& 432 = m e M
) 1 > lkjihgf L
*+,-./0 ? K
@ABCDEFGHIJ`].forEach(t=>{
console.log(t+'\n\n'+f(t)+'\n')
})
```
```
<pre id=O></pre>
```
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 59 bytes
```
{⍵[i][{⍵∪⍸∨⌿g[⍵;]}⍣≡,j⊃⍨⊃⍋+/↑i[j←⍸≠/g←1=+/|↑∘.-⍨i←⍸' '≠⍵]]}
```
[Try it online!](https://tio.run/##bVPLUhNBFN3nK25UaJBACA8fPI2ogLwCwztGHEnPpJPOTOgMhAmEhVoUAcfShVUufWwo9lZZbvyX/pF4Jwmkx9iLnq5zbt97zu07eoH3pl2d22ZNfvjMbHn6sb9m4H4kvZ9Jlkr6X3l2Jb1f8uxSvv9jJhEYTVWk90NWv0Wy8vyt9C7r@0VPVJ5@YsksXvfjq1@jJh5j4z3RYyTk2Ze@XoxlDZoAwQhMlkpVajWnWVJWvws8GtL7PUIMnXGCJ8SFvHhH7ByphEI6@AnO35AZyuF6kZAeacIATVgwKwDbkdl4Pq45YAbgm6W1w2Ga0zFJF8rXux2/Ir/OgtlNzdJzNExCGOBVpXdFEq6TsS2Coc2TIjcBYJmJfYApO01VwQKAAZQB0gDTKmED5OuEheJVwhQ6EpwW47gbLX0JYftUnvmFymU/wEr75aZtP6ylBa2dQNk9BKcoYHNjfW1VWwm6rxwfQelgH/Zgq96JZYUOt3pWgG14pb@GhELfun0H7t1/8HBkFFUnYQd2YSmQvAOG/btj6OtF6iXaXlToLkI6YWhwAGDcd4@LwoLCd9exGMAE8FyWZUwD5hX6bk@kty/aDzB5o3Huf8/9KP546snTZ9Mzs89b/Quj9I5OQrq6m2liA4NDww0vY@MTk8qlufmFxaXE8oq2ura@sbm1nUQnO9iJ3TQ1zAzL5njesgt7oujsH5QO3fLRceUk@AKO5gpaaBte0WjrvzCzQOOsDQazPrmM0yBcn8wiTo4Ca1Q0vLvcUWAdaAZBxrVAboNCCWGnvSTN25Bph7GooA34up@ouFCgwlX@lqKv1XK4i5yToUKz87SEX6rpBnr4Cw "APL (Dyalog Unicode) – Try It Online")
[Answer]
## Lua, ~~562~~ ~~535~~ ~~529~~ ~~513~~ ~~507~~ ~~504~~ ~~466~~ 458 Bytes
By far my most massive golf at the moment, ~~I think I can still cut off 100 bytes, which I'll work toward, but posting it as an answer as it already took some time :).~~ I was right, I've cutted down more than 100 bytes! I don't think there's lot of room for improvement.
this function have to be called with a 2D array containing one character per cell.
**Saved 40 bytes while working with [@KennyLau](https://codegolf.stackexchange.com/users/48934/kenny-lau), thanks to him!**
**Woohoo! Under 500!**
```
function f(m)t=2u=1i=1j=1s=" "::a::if s~=m[i][j]and(i<#m and m[i+1][j]~=s)~=(j<#m[i]and m[i][j+1]~=s)~=(i>1 and m[i-1][j]~=s)~=(j>1 and m[i][j-1]~=s)then goto b end
i,t=i%t+1,#m>t and t==i and t+1or t j=j>1 and j-1or u u=u<#m[1]and j==1 and u+1or u goto a::b::io.write(m[i][j])m[i][j]=s
i,j=i<#m and s~=m[i+1][j]and i+1or i>1 and s~=m[i-1][j]and i-1or i,j<#m[i]and s~=m[i][j+1]and j+1or j>1 and s~=m[i][j-1]and j-1or j
if s==m[i][j]then return end goto b end
```
## Ungolfed
~~Explanations will come once I'm done golfing this, for the moment, i'll lend you a readable version of this source code :D~~ Here comes the explanations!
**Edit: not updated with the latest modification, still golfing before updating. Same goes for the explanations**
```
function f(m) -- declare the function f which takes a matrix of characters
t=2 -- initialise the treshold for i
-- when looking for the first end of the snake
u=1 -- same thing for j
i,j=1,1 -- initialise i and j,our position in the matrix
s=" " -- shorthand for a space
::a:: -- label a, start of an infinite loop
if m[i][j]~=s -- check if the current character isn't a space
and(i<#m -- and weither it is surrounded by exactly
and m[i+1][j]~=s) -- 3 spaces or not
~=(j<#m[i]
and m[i][j+1]~=s) -- (more explanations below)
~=(i>1
and m[i-1][j]~=s)
~=(j>1
and m[i][j-1]~=s)
then goto b end -- if it is, go to the label b, we found the head
i,t= -- at the same time
i%t+1, -- increment i
#m>t and t==i and t+1or t -- if we checked all chars in the current range, t++
j=j>1 and j-1or u -- decrement j
u=u>#m[1]and j==1 and u+1or u-- if we checked all chars in the current range, u++
goto a -- loop back to label a
::b:: -- label b, start of infinite loop
io.write(m[i][j]) -- output the current char
m[i][j]=s -- and set it to a space
i,j=i<#m -- change i and j to find the next character in the snake
and m[i+1][j]~=s -- this nested ternary is also explained below
and i+1 -- as it takes a lot of lines in comment ^^'
or i>1
and m[i-1][j]~=s
and i-1
or i,
j<#m[i]
and m[i][j+1]~=s
and j+1
or j>1
and m[i][j-1]~=s
and j-1
or j
if m[i][j]==s -- if the new char is a space
then -- it means we finished
return -- exit properly to avoid infinite
end -- printing of spaces
goto b -- else, loop back to label b
end
```
So here comes some detailed explanations about how this program works.
First of all, let's consider the loop labeled `a`, it allows us to find the closest end to the top-left corner. It will loop forever if there's no end, but that's not a problem :D.
On a 4x4 grid, it here are the snake distances(left), and the order they are looked at (right)
```
1 2 3 4 | 1 2 4 7
2 3 4 5 | 3 5 8 11
3 4 5 6 | 6 9 12 14
4 5 6 7 | 10 13 15 16
```
For each of this character, to be the end, it have to check two conditions:
- Not being a space
- Being surrounded by exactly 3 spaces (or exactly 1 non-space)
These conditions are checked the following piece of code
```
r=m[i][j]~=s
and(i<#m and m[i+1][j]~=s)
==not(j<#m[i] and m[i][j+1]~=s)
==not(i-1>0 and m[i-1][j]~=s)
==not(j-1>0 and m[i][j-1]~=s)
and m[i][j]
or r
-- special note: "==not" is used as an equivalent to xor
-- as Lua doesn't know what is a xor...
```
Checking if the char isn't a space is achieved by the expression `m[i][j]~=s`.
Checking if w're surrounded by only 1 non-space is achived by xor-ing the above conditions for our surrounding, this could be written as
```
m[i+1][j]~=" " ⊕ m[i][j+1]~=" " ⊕ m[i-1][j]~=" " ⊕ m[i][j-1]~=" "
```
And finally, if all the above is evaluated to true, the ternary will return what's in the last `and` -> `m[i][j]`. Else , we let `r` unset :)
Now that we have the head of the snake, let's get all the way to the other end! Iterating the snake is mainly achieved by the following nested ternaries:
```
i,j=i<#m and m[i+1][j]~=s and i+1or i-1>0 and m[i-1][j]~=s and i-1or i,
j<#m[i]and m[i][j+1]~=s and j+1or j-1>0 and m[i][j-1]~=s and j-1or j
```
We re-set `i` and `j` at the same time to avoid needing dummies to store the old values They both have the exact same structure, and use simple conditions, so I'll present them in the form of nested `if`, it should allow you to read them more easily. :)
```
i=i<#m and m[i+1][j]~=s and i+1or i-1>0 and m[i-1][j]~=s and i-1or i
```
Can be translated to:
```
if(i<#m)
then
if(m[i+1][j]~=" ")
then
i=i+1
end
elseif(i-1>0)
then
if(m[i-1][j]~=" ")
then
i=i-1
end
end
```
### Test it!
Here's the code I use to run this, you can [test it online](http://www.lua.org/demo.html) by copy-pasting it.
```
function f(m)t=2u=1i=1j=1s=" "::a::if s~=m[i][j]and(i<#m and m[i+1][j]~=s)~=(j<#m[i]and m[i][j+1]~=s)~=(i>1 and m[i-1][j]~=s)~=(j>1 and m[i][j-1]~=s)then goto b end
i,t=i%t+1,#m>t and t==i and t+1or t j=j>1 and j-1or u u=u<#m[1]and j==1 and u+1or u goto a::b::io.write(m[i][j])m[i][j]=s
i,j=i<#m and s~=m[i+1][j]and i+1or i>1 and s~=m[i-1][j]and i-1or i,j<#m[i]and s~=m[i][j+1]and j+1or j>1 and s~=m[i][j-1]and j-1or j
if s==m[i][j]then return end goto b end
test1={}
s1={
" tSyrep ",
" r p ",
" in Sli ",
" g Sile",
" Snakes n",
"Ser ylt",
"a eh ilS ",
"fe w t ",
" emo h ",
" Sre ",
}
for i=1,#s1
do
test1[i]={}
s1[i]:gsub(".",function(c)test1[i][#test1[i]+1]=c end)
end
f(test1)
```
[Answer]
## Lua, 267 bytes
Lua 5.3 is required.
```
e=" "w=#arg[1]+1i=1/0q=0s=table.concat(arg,e)s=e:rep(#s)..s
m,n=i,{}for p in s:gmatch"()%g"do u=-1
for _,d in ipairs{-1,1,-w,w}do u=u+(s:find("^%S",d+p)or 0)end
n[p]=u+1m=math.min(m,p*i^(u//#s)+(p%w*w+p)*#s)end
p=m%#s repeat q,p=p,n[p]-q io.write(s:sub(q,q))until p<1
```
Usage:
```
$ lua desnakify.lua \
> " tSyrep " \
> " r p " \
> " in Sli " \
> " g Sile" \
> " Snakes n" \
> "Ser ylt" \
> "a eh ilS " \
> "fe w t " \
> " emo h " \
> " Sre "
SlipperyStringSnakesSilentlySlitherSomewhereSafe
```
[Answer]
# Python 3, ~~245~~ ~~243~~ ~~241~~ 236 bytes
`s` is the input string, `n` is the output printed to stdout:
```
f=s.find
w,l=f('\n')+1,len(s)
t=1,w,-1,-w
y=z=f(s.strip()[0]);n=s[y];v={y}
for i in range(l*l):
i%=l;c=s[i]
if c>' 'and i not in v:
if i-y in t:y=i;n=c+n;v|={i}
elif i-z in t:z=i;n+=c;v|={i}
if y%w+y//w>z%w+z//w:n=n[::-1]
print(n)
```
**Edit:** Thanks to @Cees Timmerman for saving 5 bytes!
[Answer]
## Python, 537
My initial solution:
```
from itertools import chain, product, ifilter
from operator import add
moves = ((1,0),(0,1),(-1,0),(0,-1))
h = dict(ifilter(lambda (p,v):not v.isspace(),chain(*map(lambda (i,r):map(lambda (j,c):((i,j),c),enumerate(r)),enumerate(s)))))
n = defaultdict(list)
for m,p in product(moves, h):
np = tuple(map(add,m,p))
if np in h:
n[p].append(np)
def pr(nx):
return(lambda l:(h[l[0]], h.pop(l[0]))[0] + pr(l[0]) if l else '')([x for x in n[nx] if x in h])
(lambda y: h[y]+ pr(y))(next(x for x in n if len(n[x])==1))
```
Compacted a bit, but left it as a method:
```
from itertools import chain, product
from operator import add
def unsnake(s):
(h,n) = (dict(filter(lambda (p,v):not v.isspace(),chain(*map(lambda (i,r):map(lambda (j,c):((i,j),c),enumerate(r)),enumerate(s))))),defaultdict(list))
for m,p in product(((1,0),(0,1),(-1,0),(0,-1)), h):(lambda np: n[p].append(np) if np in h else 0)(tuple(map(add,m,p)))
def pr(nx):return(lambda l:(h[l[0]], h.pop(l[0]))[0] + pr(l[0]) if l else '')([x for x in n[nx] if x in h])
return(lambda y: h[y]+ pr(y))(next(x for x in n if len(n[x])==1))
```
[Answer]
# Java 7, ~~927~~ ~~924~~ 923 bytes
```
import java.util.*;int l,k;char[][]z;Set p=new HashSet();String c(String[]a){int x=0,y=0,n,t,u,v,w=t=u=v=-1;l=a.length;k=a[0].length();z=new char[l][k];for(String s:a){for(char c:s.toCharArray())z[x][y++]=c;}x++;y=0;}for(x=0;x<l;x++)for(y=0;y<k;y++){n=0;if(z[x][y]>32){if(x<1|(x>0&&z[x-1][y]<33))n++;if(y<1|(y>0&&z[x][y-1]<33))n++;if(x>l-2|(x<l-1&&z[x+1][y]<33))n++;if(y>k-2|(y<k-1&&z[x][y+1]<33))n++;}if(n>2&t<0){t=x;u=y;}if(n>2&t>v){v=x;w=y;}}if(v+w>t+u){p(t,u);return n(""+z[t][u],t,u);}p(v,w);return n(""+z[v][w],v,w);}String n(String r,int x,int y){int a,b;if(x>0&&z[a=x-1][b=y]>32&q(a,b)){p(a,b);return n(r+z[a][b],a,b);}if(y>0&&z[a=x][b=y-1]>32&q(a,b)){p(a,b);return n(r+z[a][b],a,b);}if(x<l-1&&z[a=x+1][b=y]>32&q(a,b)){p(a,b);return n(r+z[a][b],a,b);}if(y<k-1&&z[a=x][b=y+1]>32&q(a,b)){p(a,b);return n(r+z[a][b],a,b);}return r;}boolean q(int x,int y){return!p.contains(x+","+y);}void p(int x,int y){p.add(x+","+y);}
```
Ok, that took a while.. In some programming languages it doesn't matter if your array x and y are outside the boundaries of a 2D-array, but with Java it'll throw `ArrayIndexOutOfBoundsExceptions`, so everything has to be checked..
I first determine the starting point, and then use a recursive method to build the string from there. In addition, I use a list to keep track of the coordinations I've already encountered, so it won't go into a loop back-forth-back-forth (resulting in a StackOverflowException).
This is probably the longest answer I've posted so far, but although some parts can be golfed, I don't think this challenge can be that much shorter in Java. Java just isn't suitable for following a path in a grid.. It was a fun challenge to figure out nonetheless. :)
**Ungolfed & test cases:**
[Try it here.](https://ideone.com/dMNihi)
```
import java.util.*;
class M{
static int l,
k;
static char[][] z;
static Set p = new HashSet();
static String c(String[] a){
int x=0,
y=0,
n,
t,
u,
v,
w = t = u = v = -1;
l = a.length;
k = a[0].length();
z = new char[l][k];
for(String s:a){
for(char c:s.toCharArray()){
z[x][y++] = c;
}
x++;
y = 0;
}
for(x=0; x<l; x++){
for(y=0; y<k; y++){
n = 0;
if(z[x][y] > 32){ // [x,y] is not a space
if(x < 1 | (x > 0 && z[x-1][y] < 33)){
n++;
}
if(y < 1 | (y > 0 && z[x][y-1] < 33)){
n++;
}
if(x > l-2 | (x < l-1 && z[x+1][y] < 33)){
n++;
}
if(y > k-2 | (y < k-1 && z[x][y+1] < 33)){
n++;
}
}
if(n > 2 & t < 0){
t = x;
u = y;
}
if(n > 2 & t > v){
v = x;
w = y;
}
}
}
if(v+w > t+u){
p(t, u);
return n(""+z[t][u], t, u);
}
p(v, w);
return n(""+z[v][w], v, w);
}
static String n(String r, int x, int y){
int a,b;
if(x > 0 && z[a=x-1][b=y] > 32 & q(a,b)){
p(a, b);
return n(r+z[a][b], a, b);
}
if(y > 0 && z[a=x][b=y-1] > 32 & q(a,b)){
p(a, b);
return n(r+z[a][b], a, b);
}
if(x < l-1 && z[a=x+1][b=y] > 32 & q(a,b)){
p(a, b);
return n(r+z[a][b], a, b);
}
if(y < k-1 && z[a=x][b=y+1] > 32 & q(a, b)){
p(a, b);
return n(r+z[a][b], a, b);
}
return r;
}
static boolean q(int x, int y){
return !p.contains(x+","+y);
}
static void p(int x, int y){
p.add(x+","+y);
}
public static void main(String[] a){
System.out.println(c(new String[]{ "Hel ",
" l rin",
" o,IAmASt g",
" S",
" !ekan" }));
p = new HashSet();
System.out.println(c(new String[]{ "Python" }));
p = new HashSet();
System.out.println(c(new String[]{ "P ngPu Code ",
"r i z d G",
"o m z n o",
"gram lesA lf" }));
p = new HashSet();
System.out.println(c(new String[]{ " ~ zyx tsr XWVUTSR",
" }|{ wvu q Y Q",
"! p Z `ab P",
"\"#$ 6789:; o [ _ c O",
" % 5 < n \\]^ d N",
"('& 432 = m e M",
") 1 > lkjihgf L",
"*+,-./0 ? K",
" @ABCDEFGHIJ" }));
p = new HashSet();
System.out.println(c(new String[]{ " tSyrep ",
" r p ",
" in Sli ",
" g Sile",
" Snakes n",
"Ser ylt",
"a eh ilS ",
"fe w t ",
" emo h ",
" Sre " }));
}
}
```
**Output:**
```
Hello,IAmAStringSnake!
Python
ProgrammingPuzzlesAndCodeGolf
!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~
SlipperyStringSnakesSilentlySlitherSomewhereSafe
```
[Answer]
## PHP, ~~199~~ ~~184~~ 182 bytes
may still have a little golfing potential
```
for($w=strpos($i=$argv[1],"
");;)for($y=++$n;$y--;)if($i[$p=$y*$w+$n-1]>" ")break 2;for($p-=$d=$w++;$d&&print$i[$p+=$e=$d];)foreach([-$w,-1,1,$w,0]as$d)if($d+$e&&" "<$i[$d+$p])break;
```
takes input as multiline string from command line, expects linux style linebreaks.
Run `php -r '<code>' '<string>'`; escape linebreaks.
**breakdown**
```
for(
// find width
$w=strpos($i=$argv[1],"\n")
;
// find first character: initialize $p(osition)
;
)
for($y=++$n // increase distance
;$y--;) // loop $y from (old)$n to 0
if(" "<$i[$p=$y*$w+$n // if character at $y*($width+1)+$x(=$d-$y) is no space
-1 // (adjust for the premature increment)
])
break 2; // break loops
for(
$p-= // b) reverse the increment that follows in the pre-condition
$d= // a) initialize $d to anything!=0 to enable the first iteration
$w++; // c) increase $w for easier directions
$d // loop while direction is not 0 (cursor has moved)
&&
print$i[$p+=$e=$d] // remember direction, move cursor, print character
;
)
foreach([-$w,-1,1,$w,0]as$d)// loop through directions
if($d+$e // if not opposite previous direction
&&" "<$i[$d+$p] // and character in that direction is not space
)break; // break this loop
```
[Answer]
# C#, 310
(Edit: bug fix)
A function with a multiline string parameter, returning a string.
Including the requested `using` in the byte count.
This is a porting of my javascript answer.
```
using System.Linq;
string f(string s){int o=-~s.IndexOf('\n'),m=99;var r=new string(' ',o);(s=r+s+r).Select((c,i)=>{int n=2,e=0,p,w=i%o+i/o;if(c>' '&w<m&&new[]{-1,1,o,-o}.All(d=>(s[i+d]>' '?(e=d)*--n:n)>0))for(m=w,r=""+c+s[p=i+e];new[]{e,o/e,-o/e}.Any(d=>s[p+(e=d)]>' ');)r+=s[p+=e];return i;}).Max();return r;}
```
*Test* [on ideone](http://ideone.com/Uqmq7g)
*With spaces*
```
string f(string s)
{
int o = -~s.IndexOf('\n');
var r = new string(' ', o);
var m = 99;
(s = r + s + r).Select((c, i) =>
{
int n = 2, e = 0, p, w = i % o + i / o;
if (c > ' ' & w < m & new[] { -1, 1, o, -o }.All(d => (s[i + d] > ' ' ? (e = d) * --n : n) > 0))
for (m = w, r = "" + c + s[p = i + e];
new[] { e, o / e, -o / e }.Any(d => s[p + (e = d)] > ' ');
)
r += s[p += e];
return i;
}
).Max();
return r;
}
```
[Answer]
# Python 2, 251 bytes
```
w=s.find('\n')+1;q=' ';p=q*w+'\n';s=list(p+s+p);d=-w,1,w,-1
def r(x):c=s[x];s[x]=q;v=[c+r(x+o)for o in d if s[x+o]>q];return v[0]if v else c
e=[x for x in range(len(s))if s[x]>q and sum([s[x+o]>q for o in d])<2]
print r(e[e[0]/w+e[0]%w>e[1]/w+e[1]%w])
```
Or, if you want leading newlines in your testcases, 257 bytes:
```
w=s.find('\n',1);q=' ';p=q*-~w+'\n';s=list(p+s[1:]+p);d=-w,1,w,-1
def r(x):c=s[x];s[x]=q;v=[c+r(x+o)for o in d if s[x+o]>q];return v[0]if v else c
e=[x for x in range(len(s))if s[x]>q and sum([s[x+o]>q for o in d])<2]
print r(e[e[0]/w+e[0]%w>e[1]/w+e[1]%w])
```
Passes all testcases.
```
s="""
tSyrep
r p
in Sli
g Sile
Snakes n
Ser ylt
a eh ilS
fe w t
emo h
Sre
"""
```
Results in:
```
SlipperyStringSnakesSilentlySlitherSomewhereSafe
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt) `-P`, 106 bytes
```
K=U·ÌÊÄ ç iU ¬mx T=[-KJ1K]
ËÊ*Tm+E è@gX
[]V£YÃf@gXÃrQ@WpQ Tm+Q kW fZ Ì}V£[XYuK YzK]ÃkÈv ÉÃñx v rÈ+Y*K
W£gX
```
[Try it online!](https://ethproductions.github.io/japt/?v=2.0a0&code=Sz1Vt8zKxCDnIGlVIKxteCBUPVstS0oxS10Ky8oqVG0rRSDoQGdYCltdVqNZw2ZAZ1jDclFAV3BRIFRtK1Ega1cgZlogzH1Wo1tYWXVLIFl6S13Da8h2IMnD8XggdiByyCtZKksKV6NnWA==&input=LVAKIiAgdFN5cmVwICAgIAogIHIgICAgcCAgICAKICBpbiBTbGkgICAgCiAgIGcgICAgU2lsZQogICBTbmFrZXMgIG4KU2VyICAgICAgeWx0CmEgZWggICBpbFMgIApmZSB3ICAgdCAgICAKICAgZW1vIGggICAgCiAgICAgU3JlICAgICI=)
It's... um... an abomination.
### Unpacked & How it works
```
K=UqR gJ l +1 ç iU q mx
UqR gJ l +1 Split the input by newline, take last item's length +1
K= Assign to K
ç iU Generate a string of K spaces, and append to U
q mx Split into chars, and trim whitespaces on each item
Implicit assign to U
T=[-KJ1K] Assign an array [-K, -1, 1, K] to T (this represents 4-way movement)
I could use implicit assignment, but then 4-argument function below is broken
UmDEF{Dl *Tm+E èXYZ{UgX
UmDEF{ Map over the list of one- or zero-length strings...
Dl * If the length is zero, return zero
Tm+E Add the index to each element of T
èXYZ{UgX Count truthy elements at these indices
The result is an array of 0(space/newline), 1(start/end), or 2(body)
Implicit assign to V
[] Implicit assign to W
VmXYZ{Y} fXYZ{UgX} rQXYZ{WpQ Tm+Q kW fZ gJ }
VmXYZ{Y} Map V into indices
fXYZ{UgX} Filter the indices by truthiness of U's element
rQXYZ{ Reduce on the indices... (Q=last item, Z=array)
WpQ Push Q to W
Tm+Q Take 4-way movements from Q
kW fZ gJ } Exclude visited ones, take last one in Z
VmXYZ{[XYuK YzK]} kXYZ{Xv -1} ñx v rXYZ{X+Y*K Starting point of reduce
VmXYZ{[XYuK YzK]} Convert elements of V to [elem, col, row]
kXYZ{Xv -1} Take the ones where elem(popped)=1
ñx v Sort by row+col and take first one
rXYZ{X+Y*K Convert [row,col] back to the index
WmXYZ{UgX Map indices back to chars
-P Join with empty string
```
One notable point is that I used the operator precedence between assignment and comma operators in JS, in order to pack some lines and keep the shortcut `@` (`XYZ{`) usable.
] |
[Question]
[
A *stretchy snake* looks something like this:
```
<||=|||:)~
```
Each separate sequence of vertical bars (`|`) in a stretchy snake, known as a *stretchy portion*, is individually extendable to twice its width, and is drawn with alternating slashes (`/`,`\`) once extended.
The particular snake above has two such stretchy portions, giving it four possible poses:
```
<||=|||:)~
</\/\=|||:)~
<||=/\/\/\:)~
</\/\=/\/\/\:)~
```
The general form of a stretchy snake in its least stretched pose is defined by [this regex](https://regex101.com/r/zZ3iI9/1):
```
<(\|+=)*\|+:\)~
```
Which can be stated in words as:
>
> `<`, followed by any number of sequences of `|`'s [joined](http://www.tutorialspoint.com/python/string_join.htm) with `=` signs, followed by `:)~`.
>
>
>
So `<|:)~` and `<||:)~` and `<|=|:)~` and `<|=|=||=|||||=||:)~` are stretchy snakes, but `<=:)~` and `<=|:)~` and `<||=:)~` and `<|==||:)~` are not.
Stretchy snakes can also face left instead of right, e.g. `~(:|||=||>`. The forms are the same, just mirrored.
# Challenge
Write a program that takes in a single line string of two stretchy snakes facing each other, with some number of spaces in between. Both snakes will be in their least stretched pose (all vertical bars, no slashes). The string will start with the tail of the right-facing snake and end with the tail of the left-facing snake (you may optionally assume there's also a trailing newline).
For example, here's a possible input with five spaces between the snakes:
```
<|=||:)~.....~(:||||>
```
I'm using periods (`.`) instead of actual space characters for clarity.
Zero spaces between snakes is also valid input:
```
<|=||:)~~(:||||>
```
We say the snakes are *kissing* when their tongues are touching like this.
Your program needs to extend some combination of the stretchy portions of both of the snakes such that the snakes have the fewest number of spaces possible between them (without overlapping), **i.e. such that the snakes are as close to kissing as possible**.
Both the snakes' tails are fixed but their heads and bodies can move - right for the right-facing snake, left for the left-facing snake - according to what stretchy portions have been extended.
The output of your program is the single line string (plus optional trailing newline) that shows the snakes as close to kissing as possible, with alternating slashes drawn in place of vertical bars for stretchy portions that have been extended.
---
For example, the output for `<|=||:)~.....~(:||||>` (from above) would be:
```
</\=||:)~~(:/\/\/\/\>
```
This is the *only* solution here because with any other combination of the stretchy portions extended, the snakes would either overlap or be farther away from kissing.
---
If there are multiple solutions possible, the output may be any one of them.
For example, if the input were
```
<|=||:)~.....~(:|||=|>
```
the output could be
```
<|=/\/\:)~~(:/\/\/\=|>
```
or
```
</\=||:)~~(:/\/\/\=/\>
```
---
Remember that it won't always be possible to make the snakes kiss, but you still need to get them as close as possible.
For example, if the input were
```
<||=||||:)~...~(:||>
```
the output could be
```
</\/\=||||:)~.~(:||>
```
or
```
<||=||||:)~.~(:/\/\>
```
---
If the snakes are already kissing, the output will be the same as the input. e.g.
```
<|=||:)~~(:||||>
```
In general, the output will be the same as the input if the extension of any stretchy portion would make the snakes overlap. e.g.
```
<|||=|||:)~..~(:||||=|||||=||||||>
```
---
## Notes
* Takes input from stdin or the command line as usual, or write a function that takes a string. Print or return the output.
* You can use periods (`.`) in the input and output in place of spaces () if you prefer.
* It's only important that slashes alternate within the sequence of vertical bars they replaced. Their ordering in the snake at large or whether a forward or backward slash comes first doesn't matter.
* Stretchy portions cannot extend partway - it's exactly double or no extension at all.
## Scoring
This is [code-golf](https://codegolf.stackexchange.com/tags/code-golf/info). The shortest submission in bytes wins. Tiebreaker is earlier answer.
[Answer]
# [Retina](https://github.com/mbuettner/retina), ~~209~~ ~~107~~ ~~99~~ ~~97~~ 92 bytes
```
.(?=(.+)(?<=(?=<((\|+|(?<-5>\|(?=\1())?)+)[^|]+)+$(?(5)!)).+( )+\S+))\4
/ \
+` (.*~|~.*)
$1
```
For counting purposes, each line goes in a separate file, but you can run the code from a single file with the `-s` flag.
Bringing the best features of .NET regex and Retina together: balancing groups, arbitrary length lookbehinds and repeated regex substitution.
Essentially, the long regex encodes a valid solution and the regex engine's backtracker finds one of the optimal ones for me.
## Explanation
First, let's consider how we can find a valid solution (not necessarily producing the correct output) with a regex. We can use .NET's [balancing groups](https://stackoverflow.com/a/17004406/1633117) to help us count the stretchy parts. Consider the following simpler regex:
```
\S+( )+.+(?<=(?(1)!)^([^|]+(\|+|(?<-1>\|)*))+>)
```
We can disect that.
```
\S+( )+.+
```
This matches the entire string, pushing one capture onto the group `1` stack for each space in the input. We will use that stack to ensure that the stretchy parts exactly fill the space captured into those groups.
Next is a lookbehind. The catch is that lookbehinds are matched from right to left in .NET (so that's how you should read them). This gives us the opportunity to traverse the string a second time, figuring out whether there's a subset of stretchy part that sums to the number of matched spaces. Going through the lookbehind from right-to-left:
```
>
```
This is just ensure that we're actually starting from the end of the string (the snake's tail).
```
(
[^|]+
(
\|+
|
(?<-1>\|)+
)
)+
```
For each stretchy part, this either just matches the entire part without doing anything (`\|+`), or it matches the entire part while popping captures off stack `1` (`(?<-1>\|)*`). Having this alternation ensures that we can only fully extend a stretchy part or leave it unchanged, and not get stuff like `|/\|`. Then we move on to the next stretchy part with `[^|]+`.
```
(?(1)!)^
```
Finally, we ensure that we've traverse the entire string (both snakes), and that stack `1` is completely empty. I.e. that we've found a subset of stretchy part that exactly sums to the number of spaces we've captured earlier.
The backtracker will go back and forth through the string trying all combinations of unchanged and extended parts until the subset sum problem is solved. If such a subset doesn't exist, the lookbehind will fail. This will cause the backtracker to go back to the `\S+( )+.+` part and try capturing one space less with `( )+` (which will just be cover by `.+` instead). Due to the greediness of `+` we therefore try filling as many spaces as possible.
You can check the validity of this approach with this slightly modified substitution:
```
\S+(( )+).+(?<=(?(2)!)^([^|]+(\|+|(?<-2>\|)*))+>)
=$1=
```
Which will give you a string `=spaces=` with exactly the number of spaces that can be filled with the given snakes.
I've had to add some more trickery to actually expand the correct `|`s. Basically, I want to replace all `|`s which were matched using the `(?<-1>\|)+` branch. The idea is to match an individual character, put the solver in a lookaround and set a flag if the match happens to be inside that branch. If that flag wasn't set we invalidate the match at the end to avoid replacement of other characters.
To do this, we use a bunch of nested lookarounds. Again, .NET's variable-length lookbehinds are matched from right to left, so if we nest lookaheads and lookbehinds, we can let the regex engine traverse the string several times. For golfing reasons, the solver is reversed in my actual solution (starting at the end, picking up the spaces from right to left, and then solving the subset sum from left to right), but otherwise the structure of the solver is exactly the same. Let's dissect the full regex:
```
.(?=(.+)...)
```
We match a single character, then capture the remainder of the string and move the cursor to the end of the string. We will use this group `1` later to check in the solver whether we're at the position of the match.
```
(?<=....+( )+\S+)
```
This is like the first part of the simple solver above, except that we pick up the spaces from right to left. The backtracking of the number of spaces works exactly the same as before, except that we're using group `5` now.
```
(?=<((\|+|(?<-5>\|(?=\1())?)+)[^|]+)+$(?(5)!))
```
This is the same as before, except we're going from left to right, and whenever we match a `|` in the expanding branch, we check if it's the one being matched right with
```
(?=\1())?
```
This is an optional lookahead. It tries to match group `1` again (which, here, is only possible if we're right after the character being matched), and if we do, we capture an empty string into group `4`, which indicates that we did find the current character in one of the expanded bits. If `\1` doesn't match, `4` won't capture anything, and the `?` ensures that the failing lookahead won't affect the solver at all.
Finally, after all the solving is done, we just check with `\4` whether this lookahead was used. If so, we want to replace the current character with `/\`.
One difficulty remains: removing the right amount of spaces. The shortest way to do this I've found so far is to insert a space along with the `/\` and then get rid of one space between the tongues for each of those marker spaces in a separate step:
```
+` (.*~|~.*)
$1
```
[Answer]
# CJam, ~~87~~ ~~71~~ ~~70~~ 68 bytes
```
l:L"|"f&Qa%_,Y\m*\f{.{_,"/\\"*?}L'|%.\s" /"1$fe=:-\a+}${0a>}=~S%\S**
```
Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=l%3AL%22%7C%22f%26Qa%25_%2CY%5Cm*%5Cf%7B.%7B_%2C%22%2F%5C%5C%22*%3F%7DL'%7C%25.%5Cs%22%20%2F%221%24fe%3D%3A-%5Ca%2B%7D%24%7B0a%3E%7D%3D~S%25%5CS**&input=%3C%7C%3D%7C%7C%3A)~%20%20%20%20%20~(%3A%7C%7C%7C%3D%7C%3E).
### How it works
```
l:L e# Read a line from STDIN and save it in L.
"|"f& e# Intersect each character with the string "|".
e# This pushes either "|" or "".
Qa% e# Split the resulting array at runs of "".
_, e# Compute the length of the resulting array (A).
e# This yield K, the number of stretchy parts.
Y\m* e# Push the array of all vectores in {0,1}^K.
\f{ e# For each vector V in {0,1}^K, push V and A; then:
.{ e# For each C in V and the corresponding P in A:
_, e# Compute the length of the stretchy part P.
"/\\"* e# Repeat "/\" that many times.
? e# If C, select P; else, select "/\"*length(P).
} e# This modifies A.
L'|% e# Split L at runs of vertical lines.
.\s e# Interleave the chunks of L and the modified A. Sringify.
e# In each iteration, this constructs a different modification of L,
e# with some stretched out stretchy parts.
" /"1$ e# Push " /" and a copy of the modified L.
fe= e# Calculate the number of spaces and slashes in the modifed L.
:- e# Subtract the number of occurrences.
\a+ e# Construct the array [difference modified-L].
} e#
$ e# Sort the array (by final number of spaces).
{0a>}= e# Find the first element greater than [0].
e# This skips over too far stretched snakes, where the number of
e# slashes is less than the number of spaces.
~ e# Dump the difference (D) and modified L on the stack.
S% e# Split L at runs of spaces.
\S* e# Construct a string of D spaces.
* e# Join the split L, delimiting by D spaces.
```
[Answer]
# Ruby ~~191 187 186 170~~ 162
```
->t{s=r=t.size
i=m=t[o=/ +/].size
(0...2**t.scan(y=/\|+/).size).map{|n|q=-1
x=t.gsub(y){|r|n[q+=1]<1?r:'\/'*r.size}
d=i+s-x.size
d<0||d<m&&r=x.gsub(o,' '*m=d)}
r}
```
This is a function that takes a string as a parameter and returns a string.
Online tests: <http://ideone.com/uhdfXt>
Here's the readable version:
```
# enumerates the possible states for any string containing snakes
COMBINATIONS =-> snake {
expandable_fragments = snake.scan /(\|+)/
(0...2**(expandable_fragments.size)).map{ |i|
x=-1
snake.gsub(/\|+/){|r| i[x+=1]>0 ? '\/'*r.size : r}
}
}
# finds the configuration in which snakes are closest to each other
KISS=
-> input {
result = input
s = input.size
initial_distance = min_distance = input[/ +/].size
COMBINATIONS[input].map{|c|
distance = initial_distance + s - c.size
if distance > -1 && distance < min_distance
min_distance = distance
result = c.gsub(/ +/,' '*distance)
end
}
result
}
```
In the golfed version, the main function is the equivalent of the `KISS` function above, and the `COMBINATIONS` function has been inlined.
[Answer]
# Python, 205 bytes
```
from itertools import*
f=lambda s:min([c.replace(".","",c.count("X"))for c in map("".join,product(*map({"|":"|X"}.get,s,s)))if{c.count("X")>c.count("."),"|X"in c,"X|"in c}=={0}],key=len).replace("X","/\\")
```
Having a single lambda looks neat and all, but I'm almost certain this is not the best way to go. But I'm posting this because it's all I've got so far that looks half decent.
This is a simple brute force over all possible replacements of `|` with `/\`, filtering out the invalid configurations. The only neat bit I guess is that we don't actually replace any `|` with `/\` directly - we first replace `|` with `X` and drop a `.` from the middle for every replacement, take the minimum length string over all valid strings, then replace the `X`s with `/\`.
I tried a few other approaches, including recursive ones, but they ended up pretty messy. I also learnt that `re.split` currently doesn't split on empty strings, which was unfortunate, because one of my ideas involved splitting on `\b` word boundaries.
[Answer]
# Mathematica, 381 bytes
```
StringReplace[MapAt[StringReplace[#,"|"->"/\\"]&,StringSplit[#<>"="<>#2,"="],#3]~StringRiffle~"=",")="->")~"<>If[#4>0,"."~StringRepeat~#4,""]<>"~"]&[#1,#3,Sequence@@Function[{l,s},{#,#2-Total@Extract[l,#]}&[Flatten[l~Position~#~Take~#2&@@@Tally@#&@@Select[Subsets@l,Total@#<=s&]~MaximalBy~Total,1],s]][StringLength/@StringCases[#1<>#3,"|"..],StringLength@#2]]&@@#~StringSplit~"~"&
```
Pure function taking the string as its argument. Expects `.` rather than between the snakes.
I didn't think it would be this bad...Here's what I had before I smashed it together and infixed everything.
```
f[lhs_, rhs_,
spaces_] := {StringLength /@ StringCases[lhs <> rhs, "|" ..],
StringLength@spaces}
g[barLens_,
spaceLen_] := {#, #2 - Total@Extract[barLens, #]} & @@ {Flatten[
Take[Position[barLens, #], #2] & @@@
Tally[First[
MaximalBy[Select[Subsets[barLens], Total@# <= spaceLen &],
Total]]], 1], spaceLen};
h[lhs_, rhs_, partspec_, newSpaceLen_] :=
StringReplace[
StringRiffle[
MapAt[StringReplace[#, "|" -> "/\\"] &,
StringSplit[lhs <> "=" <> rhs, "="], partspec], "="],
")=" -> ")~" <>
If[newSpaceLen > 0, StringRepeat[".", newSpaceLen], ""] <> "~"]
h[#1, #3, Sequence @@ g @@ f[#1, #3, #2]] & @@
StringSplit[#, "~"] &
```
Here is an example run-through with explanation:
```
Input: "<|=||:)~.....~(:||||>"
@Call StringSplit[#, "~"] &, yielding {"<|=||:)", ".....", "(:||||>"}
@@Apply h[#1, #3, Sequence @@ g @@ f[#1, #3, #2]] &, but first
Set arguments: h["<|=||:)", "(:||||>", Sequence @@ g @@ f["<|=||:)", "(:||||>", "....."]]
@Call f, yielding {{1, 2, 4}, 5} = {# of bars in each segment, # of spaces}
@@Apply g, let's trace from the interior:
Subsets[barLens] = all subsets of {1, 2, 4}
Select those subsets whose sum is less than # of spaces {{},{1},{2},{4},{1,2},{1,4}}
MaximalBy Total, yielding a list of all subsets whose sum is maximal {{1, 4}}
First of these subsets, can be any of them {1, 4}
Tally the subset, yielding frequencies of each {{1, 1}, {4, 1}}
@@@Apply Take[Position[barLens, #], #2] & at the first level, yielding
{Take[Position[{1, 2, 4}, 1], 1], Take[Position[{1, 2, 4}, 4, 1]]}
which takes the first 1 positions of 1 and the first 1 positions of 4, yielding
{{{1}},{{3}}}
Flatten at the first level, yielding {{1}, {3}}
Create a list {{{1}, {3}}, 5}
@@Apply {#, #2 - Total@Extract[barLens, #]} &, inserting arguments:
{{{1}, {3}}, 5 - Total@Extract[{1, 2, 4}, {{1}, {3}}]} = {{{1}, {3}}, 0}
where the second element becomes the # of spaces left over.
Done with g, it returned {{{1}, {3}}, 0}
@@Apply Sequence, splicing the return of g into h, yielding the
@Call, h["<|=||:)", "(:||||>", {{1}, {3}}, 0]; let's start from the interior
StringSplit the concatenated "<|=||:)=(:||||>" with delimiter "=", {"<|","||:)","(:||||>"}
MapAt the part specification {{1}, {3}} and StringReplace at those indices any | with /\
yielding {"</\","||:)","(:/\/\/\/\>"}
StringRiffle together, inserting back the delimiter "=", yielding "</\=||:)=(:/\/\/\/\>"
StringReplace ")=" with ")~", concat the new number of spaces, concat "~"
Yields "</\=||:)~~(:/\/\/\/\>", done.
```
[Answer]
### Prolog (ECLiPSe), 438 bytes
My other answers were solving the wrong problem (sorry for the noise). Here is another attempt in Prolog which actually respects all rules.
```
:-lib(fd).
a([],[]).
a([H|T],L):-append(H,X,L),a(T,X).
s(E,Z,X,Y,L):-length(E,L),a([[60],M,[58,41,126],T,[126,40,58],W,[62]],E),checklist(=(32),T),length(T,Z),b(M,X-[]),b(W,Y-[]).
b(I,[K:M|R]-E):-(I:K=[47,92|L]:s;I:K=[124|L]:n),M#=N+1,N#>=0,b(L,[K:N|R]-E).
b([61|L],[_:0|R]-E):-b(L,R-E).
b([],[_:0|E]-E).
d(_:N,Y:N):-Y=s;Y=n.
s(W,P):-string_list(W,E),s(E,_,X,Y,L),minimize((maplist(d,X,U),maplist(d,Y,V),s(K,Q,U,V,L)),Q),string_list(P,K).
```
### Tests
*(format: input, output, newline)*
```
<===:)~ ~(:>
<===:)~ ~(:>
<|||:)~ ~(:||||=|>
</\/\/\:)~ ~(:/\/\/\/\=/\>
<=|=:)~ ~(:||||=|>
<=/\=:)~ ~(:/\/\/\/\=/\>
<===|:)~ ~(:||=|>
<===/\:)~ ~(:/\/\=/\>
<|=|=|||=|:)~ ~(:=|>
</\=/\=/\/\/\=/\:)~ ~(:=/\>
<||||||:)~ ~(:=|>
</\/\/\/\/\/\:)~ ~(:=/\>
<||||||:)~ ~(:||>
</\/\/\/\/\/\:)~ ~(:/\/\>
<||=||||:)~ ~(:||>
<||=||||:)~ ~(:||>
<||=||||:)~ ~(:||>
</\/\=||||:)~ ~(:||>
<||=||||:)~ ~(:||>
</\/\=||||:)~~(:/\/\>
<||=||||:)~~(:||>
<||=||||:)~~(:||>
```
### Explanations
* The main predicate is `s/2`, which takes the input as a first argument and unfiy the result with the second argument (both strings). The input is converted to a list of character codes, `E`.
* Then, `s(E,Z,X,Y,L)` destructures the list into the following elements:
+ `Z` number of spaces between snakes
+ `X` and `Y`, abstract representation of the left and right bodies
The format of a body is a list of `n:N` or `s:N` expressions, where `N` is a positive length; `n` means `normal` and `s` means `stretched`.
+ `L` total length of the list
**What is interesting about `s/5`** is that it goes *both ways*, i.e. we can **build** a snake if other arguments are instanciated:
```
s(E,5,[n:3],[s:2,n:7,s:1],_),string_list(S,E).
... unifies `S` with `"<|||:)~ ~(:/\\/\\=|||||||=/\\>"` (backslashes are quoted). This is due to how `b/2` is written, which can parse the character list or generate it.
```
* We build modified left and right bodies where each part is either normal or stretched, while minimizing the space `Q` that separates the new snakes. The total length of the computed string is bounded so that the search terminates.
[Answer]
# Python 2.7.3 ~~427~~ ~~421~~ ~~400~~ 371 Bytes
```
import re,itertools as K
g,o,k='\|+',len,raw_input()
d=k.count(' ')
if d==0:exit(k)
p,x,y,s=re.sub,0,0,map(o,re.findall(g,k))
for e in [A for w in range(o(s)+1)for A in K.combinations(s,w)]:
v=sum(e)
if v==d or x<v<d:x,y=v,list(e)
print p(" +",' '*(d-x),p(g,lambda m:('/\\'*o(m.group(0))if y.remove(o(m.group(0)))or True else 1)if o(m.group(0))in y else m.group(0),k))
```
Non-golfed code here -
```
#!/usr/bin/env python
import sys
import re
def find_dist_combo(li, d):
#Listing all combinations
from itertools import combinations as c
max_dist = -1
max_dist_combo = []
for p_len in xrange(1,len(li)+1):
for e in c(li, p_len):
e_sum = sum(e)
cond1 = e_sum == d
cond2 = max_dist < e_sum < d
if cond1 or cond2:
max_dist = e_sum
max_dist_combo = list(e)
if cond1:
return (max_dist, max_dist_combo)
return (max_dist, max_dist_combo)
def snakes_foreplay(snakes):
#find distance
distance = snakes.count(" ")
#already kissing
if distance == 0:
return snakes
#find num_stretches
stretch = map(len, re.findall("\|+", snakes))
#find lowest combination of numbers
(e_dist, res_stretch) = find_dist_combo(stretch, distance)
def sub_callback(m):
s = m.group(0)
l = len(s)
if l in res_stretch:
res_stretch.remove(l)
return '/\\'*l
return s
#Resultant substitution
res_snakes = re.sub("\s+", " "*(distance - e_dist), re.sub("\|+", sub_callback, snakes))
return res_snakes
if __name__ == "__main__":
for s in [ip.strip() for ip in sys.stdin]:
print snakes_foreplay(s)
```
Testing the golfed solution -
```
$ python stretchy_snakes.py
[In] <= <|=||:)~ ~(:||||>
[Out] => </\=||:)~~(:/\/\/\/\>
$ python stretchy_snakes.py
[In] <= <|=||:)~ ~(:||||>
[Out] => </\=/\/\:)~ ~(:/\/\/\/\>
$ python stretchy_snakes.py
[In] <= <|=||:)~ ~(:|||=|>
[Out] => </\=||:)~~(:/\/\/\=/\>
$ python stretchy_snakes.py
[In] <= <||=||||:)~ ~(:||>
[Out] => </\/\=||||:)~ ~(:||>
$ python stretchy_snakes.py
[In] <= <|=||:)~~(:||||>
[Out] => <|=||:)~~(:||||>
```
Surely this can be done better(I can't figure out how :)).
Let me know if I've missed anything obvious while golfing (It's my first codegolf, I may be doing something stupid :P)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 93 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
#õKDεγʒ'|å]©ε€gxøDgU`XG‘]`âDε˜ODI„| Ãg>‹*}ZQÏε˜ε®˜NèDgyÊi„/\y∍]н©J'/¢Ið¢αð×ý'|¡õK®.ιJIðå≠iI
```
Way too long.. >.>
[Try it online](https://tio.run/##yy9OTMpM/f9f@fBWb5dzW89tPjVJvebw0thDK89tfdS0Jr3i8A6X9NCECPfDi4Dc03NiEw4vAqo7PcffxfNRw7wahcPN6XaPGnZq1UYFHu4HSZzbemjd6Tl@h1e4pFce7soEKtKPqXzU0Rt7Ye@hlV7q@ocWeR7ecGjRuY2HNxyefnives2hhUC7D63TO7fTCyhzeOmjzgWZMf//29TY1tRYadYpgECdhlVNDVDAtsbuv65uXr5uTmJVJQA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9TVnl4QpiSZ15BaYmVwuH9XAH5xcWZSTmpCvmlJWAxJfv/yoe3eruc23pu86lJ6jWHl9bWHlp5buujpjXpFYd3uKSHJkS4H14E5J6eU1ubcHgRUOXpOf4ukY8a5tUoHG5Ot3vUsFOrNirwcD9I4tzWQ@tOz/E7vMIlvfJwVyZQkX5M5aOO3tra2gt7D630Utc/tCjy8IZDi85tPLzh8PTDe9VrDi0E2n9ond65nV5AmcNLH3UuyIz8X6tzaJv9f5sa25oaK806BRCo07CqAQI7LpgohgCSMlsgBEmAZGByYBmwIFgULAg1A6wKStbY/dfVzcvXzUmsqgQA) or [verify all possible results for all test cases](https://tio.run/##yy9OTMpM/V9TVnl4gkuYkmdeQWmJlcLh/VyOOTkKBfnFxZlJOakK@aUlQPFiKwUlnf@HNxxemql8eKv3ua3nNp@apF5zeGlt7aGV57Y@alqTXnF4h0t6aEKE@@FFQO7pObW1CYcXuZzbenqOv0vko4Z5NQqHm9PtHjXs1KqNCjzcD5I4t/XQutNz/A6vcEmvPNyVCVSkH1P5qKO3trb23NZIkEWRhzccWlTppa5/aJEu0Pbph/eq1xxaCJSo1Du300vnf@3h1Tq1h7bZ/7epsa2psdKsUwCBOg2rGiCw44KJYgggKbMFQpAESAYmB5YBC4JFwYJQM8CqoGSN3X9d3bx83ZzEqkoA).
**Explanation:**
```
#õK # Split the (implicit) input by one or multiple adjacent spaces
# (we now have both snakes as separated items
# - if any spaces were in the input-string)
D # Duplicate this list
ε # Map both snakes to:
γ # Split the snake into chunks of the same character-type
ʒ'|å] '# And only leave the chunks of "|" characters
© # Store this list in variable `r` (without popping)
ε # Map the "|" chunks of both snakes again:
€g # Get the length of each chunk of "|"
xø # Pair each length with double itself
DgU`XG‘ # Create all possible combinations for the current snake
]`â # After the map: create all possible combinations for both snakes
ε # Map over each possible combination
˜O # Get the flattened sum
I„| Ãg # Count the amount of "|" and spaces in the input
>‹ # Check if it's smaller than or equal to this sum
# (1 if truthy; 0 if falsey)
D * # And multiply it by the sum
}ZQ # After the map, get the positions of the largest flattened sum,
# still below (or equal to) the amount of "|" and spaces combined
D Ï # And only keep those combinations
ε # Then map over the remaining combinations
˜ε # Flatten it, and map over each value `y`
®˜Nè # Get the `N`'th part of the snakes
# (where `N` is the index of the map for the current combination)
D # Duplicate this "|"-part
gyÊi # If the length of this "|"-part is not equal to the map-value:
„/\ # Push the string "/\"
y∍ # Extended to a size equal to the map-value
# (implicit else:
# use the duplicated value)
]н # After the map: only leave the first (since we don't have
# to output all possibilities)
© # Store it in variable `r` (without popping)
J'/¢ '# Count the amount of "/" in it
Ið¢ # Count the amount of spaces in the input
α # Get the difference between those
ð×ý # And join the list of snakes by that many spaces
'|¡õK '# Then split by one or multiple adjacent "|"
®.ι # Interleave it with the modified parts of variable` r`
J # And join everything together to a single string
Iðå≠i # If the input didn't contain any spaces:
I # Output the input instead
# (implicit else:
# output the top of the stack before this if)
```
] |
[Question]
[
I keep hearing that thinking outside the box is a goal worth achieving, but how can I tell if I'm successfully doing it?
To solve this dilemma I have already wrote a *Brainwave-to-ASCII*-translator which in theory should produce outputs like
```
#
+------------+ #
| thinking | #
| | #
+------------+ #
#
```
or
```
#
+------+ #
| | thinking #
| | #
| | #
+------+ #
#
```
which make it fairly easy to tell whether one is thinking outside the box or not. (The `#` are not part of the output and represent new lines.)
However, due to a bug sometimes only a smaller section of the output is returned:
```
| | #
+---------+ #
thinking #
```
```
#
+#
|#
inking |#
```
```
#
#
```
## The Task
Please help me to automatically classify the *Brainwave-to-ASCII*-translator output by writing a program or function which reads an ascii-reprensentation and returns whether `thinking` is in the box, outside of it or it could not tell from the input.
### Input
A set of same-length strings either as a list or delimited by newlines containing
* the string `thinking` or valid pre- or suffixes thereof
* the characters `+-|` forming a rectangular box or valid parts of it
* spaces
* **NO `#`**, those are only included in the challenge to mark the ends of the input lines.
### Output
* a *truthy* value if `thinking` is outside the box
* a *falsy* value if `thinking` is in the box
* a distinct third *maybe* value if it can not be determined from the input whether `thinking` is in the box or not
## Examples
**Truthy:**
```
#
+------+ #
| | thinking #
| | #
| | #
+------+ #
#
```
```
| | #
+---------+ #
thinking #
```
```
#
+#
|#
|#
inking |#
```
```
thinking #
-------+ #
```
```
++ # (thinking is not in the box, so it must be outside)
++ # (this is also the smallest possible box)
```
```
+ #
t#
```
```
+----+# (The box is not wide enough to contain "thinking")
```
```
---# (The box is not high enough to contain "thinking")
---#
```
As string input:
```
" \n +------+ \n | | thinking \n | | \n | | \n +------+ \n "
" | | \n +---------+ \n thinking "
" \n +\n |\n |\ninking |"
"thinking \n-------+ "
" ++ \n ++ "
"+ \n t"
"+----+"
"---\n---"
"g++"
"k\n+"
```
**Falsy:**
```
#
+------------+ #
| thinking | #
| | #
+------------+ #
#
```
```
+---------------#
| #
| #
| thinking #
```
```
| #
king | #
------+ #
```
```
+---#
|thi#
+---#
```
```
-#
n#
-#
```
As string input:
```
" \n +------------+ \n | thinking | \n | | \n +------------+ \n "
" +---------------\n | \n | \n | thinking "
" | \nking | \n------+ "
"+---\n|thi\n+---"
"-\nn\n-"
```
**Maybe:**
```
thinking#
```
```
g|#
```
```
think#
-----#
```
```
| |# (box large enough to possibly contain the string)
| |#
```
```
+--#
| #
```
```
# (empty input)
```
As string input:
```
"thinking"
"g|"
"|t"
"-\ni"
"h\n-"
"think\n-----"
"| |\n| |"
" +--\n | "
""
```
## Rules
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so try to use as few bytes as possible.
* The *maybe* value can be chosen freely as long as it's different from the truthy/falsy value and is the same for all maybe-inputs. It can also be an error.
* You can assume that the input is always valid (eg. contains no other chars than `+-ghiknt|`, no more than one box, ...).
[Answer]
# Javascript (ES6), ~~274~~ 263 bytes
```
f=(a,b=(b,c="")=>a=a.replace(b,c),c=b=>b.test(`,${a},`))=>(b(/\w+/,5),b(/\+/g,1),b(/\-/g,2),b(/\|/g,3),b(/\n/g,4),c(/[13][2 ]{0,7}[13]|[12] *4 *[12]/)||(b(/ /g),b(/43+(?=4)/g),!c(/353|24542|12+435|21453|35412|5342+1/)&&(!c(/^([^1]*|([^15]*1){1,2}[^15]*)$/)||-1)))
```
The function `f` returns `true`, `false`, or `-1` as its "maybe" value. It should be called with one argument: the input. The other two parameters only exist to shorten the code.
Here's a less golfed version with comments:
```
var f = (input) => {
var replace = (re, s) => input = input.replace(re, s);
var test = re => re.test(input);
/*
Replace some "special" characters with ones that are shorter to put in a regex.
"+" --> "1"
"-" --> "2"
"|" --> "3"
"\n" --> ","
*/
replace(/\+/g,1);
replace(/\-/g,2);
replace(/\|/g,3);
replace(/\n/g,',');
/*
Shorten the word, if there is one, to just a single character "a".
*/
replace(/[a-z]+/g,'a');
/*
Append a newline to the beginning and end of the input.
*/
input = ','+input+',';
/*
Test the size of the box. These are the cases covered:
/[13][2 ]{0,7}[13]/ : A horizontal edge or middle section has an inner width of fewer than 8 characters.
/[12] *, *[12]/ : There are two horizontal edges in a row, with no space between.
If either of these match, the word must be outside of the box. Return the truthy value (true).
*/
if (test(/[13][2 ]{0,7}[13]|[12] *, *[12]/)) return true;
/*
Remove any spacing from the input. It it unnecessary from this point onwards.
*/
replace(/ /g,'');
/*
Remove any lines with only vertical bars. These are also unnecessary.
*/
replace(/,3+(?=,)/g,'');
/*
Edge / corner cases (heh). These are the cases covered:
/3a3/ : two vertical bars with the word between.
/2,a,2/ : two horizontal bars with the word between.
/12+,3a/ : word inside the top left corner.
/21,a3/ : word inside the top right corner.
/3a,12/ : word inside the bottom left corner.
/a3,2+1/ : word inside the bottom right corner.
If any of these match, the word is inside the box. Return the falsy value (false).
*/
if (test(/3a3|2,a,2|12+,3a|21,a3|3a,12|a3,2+1/)) return false;
/*
"Maybe" cases. These are the cases covered:
/^[^1]*$/ : Input contains no corners, and may or may not contain a word.
/^([^1a]*1){1,2}[^1a]*$/ : Input contains 1 or 2 corners, and no word.
If either of these match, assuming the previous test cases have not been hit,
we cannot tell if the word is inside or outside the box. Return the maybe value (-1).
*/
if (test(/^([^1]*|([^1a]*1){1,2}[^1a]*)$/)) return -1;
/*
If none of the previous cases matched, the word must be outside of the box. Return the truthy value (true).
*/
return true;
};
```
Had a lot of fun with this one. Thanks!
Edit: Saved 6 bytes thanks @L. Serné by modifying `b` to use a default argument, saving 3 bytes, and changing `[a-z]` to `\w`, saving 3 more bytes. Also saved 5 more bytes by making the word replacement non-global, saving 1 byte, and changing `"a"` to `5` and `","` to `4`, saving 4 bytes.
[Answer]
# Python 2.7, ~~532~~ ~~494~~ 453 bytes
This one sure had a lot of special cases. My truthy and falsy values are the strings "True" and "False" respectively. My maybe value is an Index Error, as they're easy to trigger and one of my test cases triggers it if the input is an empty string, which is a maybe case anyway. I made use of regular expressions quite a bit.
I don't golf in python often, so I'm sure this could be golfed down more, but here's my code:
```
import re
def e(s):exit(str(s))
i=input()
T=1<2
F=2<1
a=len(i)+1
c=i.count('+')
s='[a-z]'
x=re.search
p=x(s,i)
k=x('\+.*'+s,i)
l=x(s+'.*\|',i)
r=x('\|.*'+s,i)
f=i.find('+')
g=i[f-1]=='-'and f>0
if x('\-.*\n.*\-',i):e(T)
if x('\+.{0,7}\+',i):e(T)
if c>1 and not p:i[a]
if c>3:e(not(r and l))
if c>0:
if r and l:e(F)
if g:
if l:e(F)
if p or k:e(T)
i[a]
if r or k:e(F)
if p:e(T)
i[a]
if x('-.*\s[a-z].*\s-',i):e(F)
if x('\|.*[a-z].*\|',i):e(F)
i[a]
```
In my golfed version, I display the True/False answer by calling `exit(bool as string)`. Here's a commented version, in which the exit statements are replaced with return statements, and everything's been moved into a function:
```
import re
i=input()
T=True
F=False
def z():
# some variables and shortcuts useful for testing
# length of input +1. Used to throw an index out of bounds error on 'maybe'
a=len(i)+1
# c for i.Count()
c=i.count
# string used in regular expressions often
s='[a-z]'
# shorten regeX calls
x=re.search
# p is true is 'thinking' is Present on canvas
p=x(s,i)
# k is true if 'thinking' is Right of a 'Korner' (corner)
k=x('\+.*'+s,i)
# l is true if 'thinking' is Left of a pipe (|)
l=x(s+'.*\|',i)
# r is true if 'thinking' is right of a pipe
r=x('\|.*'+s,i)
# f is First corner (+) index
f=i.find('+')
# g is true if box is facing riGht (i.e. there is a dash before the first +)
# for example, '---+' indicates the box faces right. if the + is the 0th
# character, then the box must be facing left.
# Note that this assignment also checks for the empty string 'maybe'
# case, which is signalled by an IndexOutofBounds error
# CASE 1: Empty Input
# ex: ''
g=i[f-1]=='-' and f>0
# Begin testing all possible scenarios
# CASE 2: Box is too short (vertically)
# ex: ------
# ------
if x('\-.*\n.*\-',i):return T
# CASE 3: box is too short (horizontally)
# ex: ||
if x('\+.{0,7}\+',i):return T
# CASE 4: box is not too short yet no corners (+) or text are present on canvas
# ex:
# | | --------
# | | or
# | | --------
# this is a maybe case, so throw out of bounds error
if c('+')>1 and not p:i[a]
# CASE 5: Four corners visible (whole box visible)
# ex: +---+
# | X |
# +---+
# return false if text is both right of and left of pipes (i.e. in box)
if c('+')>3:return not(r and l)
# CASE 6: one or two corners visible
# ex:
# ----+ | | |
# | or +----+ or ---+ etc
# ----+
# in this case, we idenify which way the box faces
if c('+')>0:
# CASE 6-A: Text is between two pipes
# ex:
# | X |
# +-------+
# if text is between pipes (box is extending from top or bottom of
# canvas), then it is inside box
if r and l:return F
# CASE 6-B: Box faces right
# if the box is riGht-facing, ex:
# ----+
# | or ----+ etc
# ----+ |
if g:
# CASE 6-B-a: Letters are left of a pipe or a + in a right facing box
# ----+
# X | or ----+
# ----+ X |
if l :return F
# CASE 6-B-b: Letters are right of a pipe or + in a right facing box
# ----+
# | X or ----+
# ----+ | X
if p or k:return T
# CASE 6-B-c: right-facing otherwise
# otherwise, it is a 'maybe' case
# use an index out of bounds error to signal 'maybe'
i[a]
# CASE 6-C: Box faces left (or letters are on canvas yet not inside box)
# ex:
# +----
# | or +--- or
# +---- |
else:
# CASE 6-C-a: Letters are right of a pipe or a + in a left facing box
# if letters are right of pipe, they are inside box, ex:
# +----
# | X or +--- or X +---
# +---- | X |
if r or k:return F
# CASE 6-C-b: Letters are left of a pipe in a left facing box
# ex:
# +----
# X | or +---
# +---- X |
# CASE 6-C-c: Letters are on canvas yet not left or right of
# a pipe or a + (they must therefore be outside the box)
# ex:
# | |
# +-----+
# X
if p:return T
# CASE 6-C-d: text is not visible on canvas, and only part of the box is
# ex:
# | |
# +-----+
#
# this is a 'maybe' case, as text is off canvas
# use an index out of bounds error to signal 'maybe'
i[a]
# CASE 7: No corners visible, nonempty input
# CASE 7-A: No corners visible, letters sandwitched between dashes
# ex:
# -----
# X
# -----
# if there are no corners, yet letters are sandwitched between dashes,
# then word is in box
if x('-.*\s[a-z].*\s-',i):return F
# CASE 7-B: No corners visible, letters sandwitched bewteen pipes
# ex: | X |
# in this case, word is inside box
if x('\|.*[a-z].*\|',i):return F
# If none of the above cases are met, it is a maybe, so throw the error
i[a]
print z()
```
My solution assumes that the input is valid, i.e. 'Thinking' (or its substrings) are spelled correctly, there is only a single box, etc.
Edit: Saved 10 bytes thanks to @ais523's suggestion to change `c` to `i.count('+')`, 3 bytes thanks to @Pavel's suggestion of replacing `True` with `1<2` and `False` with `2>1`, 23 bytes by removing an unneeded else block, and 2 bytes by removing some spaces.
Edit 2: Saved 36 bytes thanks to @Wheat Wizard who kindly pointed out that my 'tabs' were actually 5 spaces (D'oh!) and suggested some other improvements.
[Answer]
# Befunge, 535 bytes
This isn't pretty, and doesn't come close to competing with the existing answers, but it's the best I could achieve in Befunge.
Returns `1` if thinking outside the box, `0` if thinking inside the box, and `-1` for *maybe*.
```
p10p20p130p140p150p9-:60p70p"~":80p90pvp8p04+1:g04p03:$p9g04+g9g\<<
0$$$$"xxxx"5p041p031p$_v#!-+55:_v#`0:~<p05+1g
v01g04$_v#*`\"|"\`"-"::<>0g\8\p"0"-!!40g1-\8\p:4-!:00g0`*!:00g\6\p40g\8\p00g!*4v
>p50g20p>8%:30g88+*+:3-v4v\-1g05!!*-"3"\-"4"::p\7\g05!!-3:+*+88g8g04:p00+g00*g0<
v!*-"3"\-"5"::p\6\g04!!<!>>7\p::"C"-\"3"-*!!50g\9\p"0"-!!50g1-\9\p:5-!:40g9g48*v
>!40g1-\6\p::"S"-\"3"-*!^>0#4g#p9#\g#94#\8#g*#0-#5!#p*#\5#70#\g#-*^#84g9g04:!*`<
>80g60g-8`90g70g-1`**+!:10g80g`60g10g`20g90g`70g20g`+++!!*\!-.@
^!g01***`"}"g09`"}"g08`g070`g060<
```
[Try it online!](http://befunge.tryitonline.net/#code=cDEwcDIwcDEzMHAxNDBwMTUwcDktOjYwcDcwcCJ+Ijo4MHA5MHB2cDhwMDQrMTpnMDRwMDM6JHA5ZzA0K2c5Z1w8PAowJCQkJCJ4eHh4IjVwMDQxcDAzMXAkX3YjIS0rNTU6X3YjYDA6fjxwMDUrMWcKdjAxZzA0JF92IypgXCJ8IlxgIi0iOjo8PjBnXDhccCIwIi0hITQwZzEtXDhccDo0LSE6MDBnMGAqITowMGdcNlxwNDBnXDhccDAwZyEqNHYKPnA1MGcyMHA+OCU6MzBnODgrKis6My12NHZcLTFnMDUhISotIjMiXC0iNCI6OnBcN1xnMDUhIS0zOisqKzg4ZzhnMDQ6cDAwK2cwMCpnMDwKdiEqLSIzIlwtIjUiOjpwXDZcZzA0ISE8IT4+N1xwOjoiQyItXCIzIi0qISE1MGdcOVxwIjAiLSEhNTBnMS1cOVxwOjUtITo0MGc5ZzQ4KnYKPiE0MGcxLVw2XHA6OiJTIi1cIjMiLSohXj4wIzRnI3A5I1xnIzk0I1w4I2cqIzAtIzUhI3AqI1w1IzcwI1xnIy0qXiM4NGc5ZzA0OiEqYDwKPjgwZzYwZy04YDkwZzcwZy0xYCoqKyE6MTBnODBnYDYwZzEwZ2AyMGc5MGdgNzBnMjBnYCsrKyEhKlwhLS5ACl4hZzAxKioqYCJ9ImcwOWAifSJnMDhgZzA3MGBnMDYwPA&input=ICAgfCAgICAgICAgIHwgICAgICAgICAKICAgKy0tLS0tLS0tLSsgICAgICAgICAKICAgIHRoaW5raW5nICAgICAgICAgICA)
] |
[Question]
[
Print the phrase `And she said, 'But that's his.'` using only the following characters: `abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ` No punctuation or non-alphabetic characters whatsoever. You can use whatever programming language you want. Whitespace is completely allowed. Shortest program wins.
[Answer]
# [Whitespace](https://web.archive.org/web/20150618184706/http://compsoc.dur.ac.uk/whitespace/tutorial.php), ~~417~~ ~~414~~ ~~349~~ 265 bytes
265 bytes thanks to Kevin Cruijssen
```
```
[Try it online!](https://tio.run/##VU9BDoAgDDt3r@jXjCHRm4kmPn@SbRTkQLvS0e09zqfd17Y3dxJ5LBnJzjolEuNmvKZuvQwdVUZjOWTHhIHlRP0F0pb0n6JEzTAH4jCnvAZCoF6SyoOZtgtDbBSamfsH "Whitespace – Try It Online")
Explained:
```
[S S T T T T T T T N
_Push_-63_'][S S T T T T S S S N
_Push_-53_.][S S S T T S T N
_Push_13_s][S S S T T N
_Push_3_i][S S S T S N
_Push_2_h][S S T T S S S T T S N
_Push_-70_space][S T S S T T N
_Copy_0-based_3rd_s][S T S S T T S N
_Copy_0-based_6th_'][S S S T T T S N
_Push_14_t][S S T T S T N
_Push_-5_a][S S S T S N
_Push_2_h][S T S S T S N
_Copy_0-based_2nd_t][S T S S T T S N
_Copy_0-based_6th_space][S T S S T N
_Copy_0-based_1st_t][S S S T T T T N
_Push-15_u][S S T T S S T S S N
_Push_-36_B][S S T T T T T T T N
_Push_-63_'][S T S S T S S N
_Copy_0-based_4th_space][S S T T T T S T S N
_Push_-58_,][S S T T S N
_Push_-2_d][S S S T T N
_Push_3_i][S S T T S T N
_Push_-5_a][S S S T T S T N
_Push-13_s][S T S S T S T N
_Copy_0-based_3rd_space][S S T T N
_Push_-1_e][S S S T S N
_Push_2_h][S T S S T T N
_Copy_0-based_3rd_s][S T S S T T N
_Copy_0-based_3rd_space][S S T T S N
_Push_-2_d][S S S T S S S N
_Push_8_n][S S T T S S T S T N
_Push_-37_A][N
S S N
_Create_Label_LOOP][S S S T T S S T T S N
_Push_102][T S S S _Add][T N
S S _Print_as_character][N
S N
N
_Jump_to_Label_LOOP]
```
[Answer]
# [Perl 5](https://www.perl.org/), ~~133~~ ~~102~~ 95 bytes
```
s qqAnd she saidZ ZBut thatZs hisZZGjGGfq x
s qZqchr oct oct oct ord chopqge x
y qGjfqqdx
print
```
[Try it online!](https://tio.run/##Rcq7DYAwDAXAnineEgwATXZwh/LBiRCJYyPB9IGO4rprsR/zGAqR5QxQjtAtBwKtl8F4M1JwViJXnEuCe/ouieeO6u3XAzzXJnv8ygNxJYmEe2o9nzbGCw "Perl 5 – Try It Online")
Explanation:
Regexes, print, and chop all apply to the variable `$_` by default.
```
s qqAnd she saidZ ZBut thatZs hisZZGjGGfq
```
Replaces the empty string with `And she saidZ ZBut thatZs hisZZGjGGf`.
```
s qZqchr oct oct oct ord chopqge
```
Replaces each `Z` with the result of evaling `chr oct oct oct ord chop`. This removes the last character of `$_`, takes its keycode, interprets it as octal thrice, and converts it back to a character. For example, `j` → 106 → 70 → 56 → 46 → `.`.
Due to the way replacement works, the modifications to `$_` that happen while evaluating the replacement are lost, so `$_` is now `And she said, 'But that's his.'GjGGf`.
```
y qGjfqqd
```
Deletes all `G`, `j`, and `f` in `$_`.
[Answer]
# [><>](https://esolangs.org/wiki/Fish), ~~916~~ ~~915~~ 903 bytes
At first I thought a solution in ><> was impossible, but then I realized... who needs conditionals or logic control? :D
```
fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffloffffffffffffffffffffffffffffffffffffffffffffflopppgloppppppppppppppppppppppggloffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffflopppggloploppppppppppppppppppppppploffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffflopppppplofffffffflopggloppppppppppppppppppgglopppplofffffffloffffffffffffffffffffffffffflofffffffffffffffffffffffffffffffffffffffffffffffffffloglopppppppppppppppppppppppppppplofffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffflopppploppgloffffffffffffffffffflopppppppppppppppppppppppppgglofffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffflopppppppppppppppppppppppppppgglofffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffflofloffffffffffloppppppppppppppppppppppploppgloio
```
[**Try it Online**](https://tio.run/##S8sszvj/P41SkJNPovKCgoJ0MIkFpKeTaBwploJsxWVxAe3sRTEcKJKO1fcwUbhSvA4iy7U5@TjDnYZhkAbzFzja8QQSHZIDXu9T0zKgSciG4Ul14FDJzP//HwA "><> – Try It Online")
I repeatedly push numbers (the number 15) to the stack, then push the length of the stack and print the character with that ASCII value. If I need to shrink the length of the stack, I shrink the stack three values at a time using `p`, or one at a time using `g` if I'm within three of the target. The program ends by calling `i` (input), which pushes a `-1` since there's no input, then prints it to cause an error.
This is the Python 3 program I used to create the solution once I'd thought of how to do it:
```
s = "And she said, 'But that's his.'"
L = [0]+[ord(c) for c in s]
#print(L)
M = L[1:]+[0]
D = [x[1]-x[0] for x in zip(L,M)]
#print(D)
while D:
n=D.pop(0)
if not D:print('io',end='');exit()
if n>0:print('f'*n,end='lo')
else:
while n<-2:print('p',end='');n+=3
print('g'*-n,end='lo')
```
[**Try it Online**](https://tio.run/##TcxBbsIwEAXQdXyKESzGhgQF2NGmElWW4QRRFog49UjR2IpdNXD51DTQdjnz3//uGozl/TR5KGBx5Ba80eDP1KaA758BgjkH9GDIb3AhqqjqvFnXdmjlRUFnB7gAMfhGLN1AHGSlxCmqqt4eossbUd47Y71tsjGeP5XxXrmRk1V6Ur/NUokvQ72G8iASLsqNs07mSiTUAdsQ37NDsphqbgtE9aJHCvJh3vKn6HDFM@ktxlT3XsfRZN7n12z3lO5vitfFPppH8IGr7N/GNH0D "Python 3 – Try It Online")
[Answer]
# 8086 Assembly on IBM PC, 1463 845 664 bytes
**Clarification: The actual assembly language source is the entry, not the generated machine code.**
The difficulty is that most x86 instructions (like ADD, SUB, JMP, conditional jumps, memory access) have two arguments and thus need a comma, or need a memory address. So, we can't use addition, subtraction, ifs, or loops!
During my first attempt I was able to "construct" numbers using a combination of increment, decrement, multiplication, division, byte-tricks, and the obscure BCD instructions (like AAA, DAS). After that, I realised that this idea could be used to create self-inspecting and self-modifying code.
* **Attempt 1.** (1463 bytes)
Used the available instructions to construct ASCII codes and the 0xb800 address of the screen buffer. The calculation of each character in the sequence was golfed by hand.
* **Attempt 2.** (not complete)
Realised that there is an opcode for *every* integer in the range 0x40-0x5f. This range includes A-Z. So for example INC CX corresponds to 0x41 = 'A'. (This [opcode table](http://www.mlsite.net/8086/) is very handy.)
I attempted to construct 3 "data" strings, and layer them on top of one another. The first as-is (uppercase), the second "shifted" into the 0x60-0x7f zone (lowercase) and the last "shifted" into the 0x20-0x3f zone (punctuation).
Self-modifying code would produce a loop or three to iterate over the data.
* **Attempt 3.** (845 bytes)
Like previous approach but to cut down on data, the string would only be encoded once, with "control characters" mixed in to switch character sets.
* **Attempt 4.** (664 bytes)
How to get rid of the control characters which require a whole lot of patched instructions to deal with branching? Given that only two uppercase letters are used, I wondered whether I could "flip" the opcode table to encode lowercase letters using the 0x40-0x4f range and punctuation using the 0x90-0x9f range (by subtracting from 0xc0). The "A" and "B" could get put in separately.
However only half the opcodes in the 0x90-0x9f range are usable and they didn't line up with the needed ones. Then I thought maybe I could shuffle them around using a XOR, and I found one that worked. And here it is.
Golfed:
```
REP LODSB
PUSH CX
PUSH CX
POP AX
INC CH
PUSH CX
POP DI
DEC AX
DEC AX
REPNE SCASB
REPNE SCASB
PUSH DI
REPNE SCASB
PUSH DI
REPNE SCASB
PUSH DI
POP SI
POP DI
DEC DI
LODSB
NOT AL
STOSB
POP CX
DEC CH
LODSB
NOT AL
STOSB
LODSB
AAA
STOSB
INC DI
LODSB
NEG AL
STOSB
LODSB
NOT AL
PUSH AX
PUSH AX
INC SP
POP ES
INC SP
POP DI
LODSB
NOT AL
PUSH AX
POP BX
NEG AL
STOSB
INC DI
LODSB
DEC AL
NEG AL
DIV BH
PUSH AX
POP DI
LODSB
STOSB
RET
DEC BL
PUSH CS
STOSB
PUSH DS
INC DI
INC AX
POP SI
PUSH SP
NOP
INC BP
POP AX
PUSH DI
NOP
INC BP
PUSH BX
POP BX
PUSH SP
PUSHF
NOP
CWD
PUSH DX
INC DI
INC SP
NOP
INC SP
POP AX
PUSH BX
INC SP
CWD
INC BP
NOP
POP AX
POP BX
INC BP
SAHF
CWD
SCASB
INC DX
```
Assemble with
```
nasm golf.asm -o golf.com
```
and run in DOSBOX (run CLS first). Looks like this:
[![Sample output](https://i.stack.imgur.com/Kfn9om.png)](https://i.stack.imgur.com/Kfn9om.png)
Commented:
```
; ASSUME DS = ES = CS
; ASSUME IP = 0x0100
; true for .COM file
; We treat 0xFE as a special marker that we scan for
; This marks our patch zone and the start of our data
; We also use it as a cheap trick to get a constant 0x1f
; into CX
; 0xFE is the first byte of INC or DEC instructions
; that operate on half-word registers (AL, BL, CH etc.)
; WATCH OUT! Adding these breaks the scan
; Can't assume any register contains zero
; so use this trick to zero out CX
REP LODSB
PUSH CX ; needed later
; zero AX
PUSH CX
POP AX
INC CH
PUSH CX
POP DI ; 0x100, where our code starts
DEC AX
DEC AX ; AL = 0xFE, our marker (AH = 0xFF)
REPNE SCASB ; skip the INC CH above
REPNE SCASB ; find the DEC CH located at 0x10E
; we will later need 0xF, the char count minus the 'A'
PUSH DI ; DI = 0x10F
REPNE SCASB ; find the patch position
PUSH DI
REPNE SCASB ; find the next 0xfe; our data section
PUSH DI
POP SI ; load data from here
POP DI ; store data to the patch position
DEC DI
; patch in XOR
; XOR is 0x34, start with 0xCB
; second byte of DEC BL is 0xCB
LODSB
NOT AL
STOSB
POP CX ; get 0x0f in CX for our strlen
DEC CH
; patch in our XOR arg
; it is 0xF1 (take 0x0E and NOT it)
LODSB ; 0x0E (PUSH CS)
NOT AL
STOSB
; ADD is 0x00 (take 0xAA, apply weird AAA behaviour)
; this also zeroes AH
LODSB ; 0xAA (STOSB)
AAA
STOSB
INC DI ; skip next instruction byte
; LOOP is 0xE2
LODSB ; 0x1E PUSH DS
NEG AL
STOSB
; get b800 in ES (address of screen buffer)
; first get 0x47 in AL (INC DI)
LODSB ; get 0x47 (INC DI)
NOT AL ; NOT 0x47 = 0xb8
; AX = 0x00b8 (bytes backwards)
PUSH AX
PUSH AX
; stack contains 0xb8 0x00 0xb8 0x00
; stack off-by-1 trick
INC SP
; now POP gives you 0xb800
POP ES
INC SP ;and clean up after ourselves
; store 0 in DI ***** PUSHED AT START OF PROGRAM ***
POP DI
LODSB ; get our magic 0xC0 (0x40 INC AX)
NOT AL
PUSH AX
POP BX
NEG AL ; NOT and +1 to get 0x41 ("A")
; charloop:
STOSB
INC DI
LODSB
DEC AL ; XOR
NEG AL ; modify this into an ADD AL, BL
DIV BH ; modify this to LOOP back to charloop
; doesn't print the last character
; but the last character turns into the address where 'B'
; is supposed to go
PUSH AX
POP DI
LODSB ; "B"
STOSB
; graceful exit this time ;)
RET
; *** DATA SECTION ***
; PURPOSE
DEC BL ; 0xFE marks data section, 0xCB for XOR
PUSH CS ; for XOR arg
STOSB ; for ADD
PUSH DS ; for LOOP
INC DI ; 0x47 -> for 0xb800
INC AX ; for magic number but also "A"
POP SI ;n
PUSH SP ;d
NOP ;
INC BP ;s
POP AX ;h
PUSH DI ;e
NOP ;
INC BP ;s
PUSH BX ;a
POP BX ;i
PUSH SP ;d
PUSHF ;,
NOP ;
CWD ;'
PUSH DX ;B
INC DI ;u
INC SP ;t
NOP ;
INC SP ;t
POP AX ;h
PUSH BX ;a
INC SP ;t
CWD ;'
INC BP ;s
NOP ;
POP AX ;h
POP BX ;i
INC BP ;s
SAHF ;.
CWD ;'
SCASB ; treated as char but turns into screen address!
INC DX ; "B"
```
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~1299~~ ~~1272~~ ~~1220~~ 1215 bytes
*Thanks to Grimy for -27 bytes.*
*-52 bytes because we didn't need the rabbit ears in the first place.*
*Thanks to Jo King for -5 bytes.*
```
print chr flip chars i x chars i xx pi
and print lc chr chars NaN x chars cis pi
and print lc chr chars e x e x e
and print chr chars i x e x e x e
and print lc chr flip chars exp i
and print lc chr chars NaN x tau x e x e
and print chr chars chop NaN x e lcm chars e
and print chr chars i x e x e x e
and print lc chr flip chars exp i
and print lc chr flip chars i x chars i xx pi
and print chr chars False x pi x ceiling tau
and print lc chr chars e x e x e
and print chr chars i xx chars NaN x pi
and print chr chars i x e x e x e
and print chr chars chop False x e x e x e
and print chr chars chop NaN xx chars e
and print lc chr chars e x chars False
and print lc chr chars chop e x chars False
and print chr chars i x e x e x e
and print lc chr chars chop e x chars False
and print lc chr chars NaN x tau x e x e
and print lc chr flip chars i x chars i xx pi
and print lc chr chars chop e x chars False
and print chr chars chop False x e x e x e
and print lc chr flip chars exp i
and print chr chars i x e x e x e
and print lc chr chars NaN x tau x e x e
and print chr chars False x pi x ceiling tau
and print lc chr flip chars exp i
and print chr chars NaN xx tau x e
and say chr chars chop False x e x e x e
```
[Try it online!](https://tio.run/##tZNRDsIgDIbfPUVP4RF83B0IomuCs4GZ4OmRMXBzyuiW@LCEpB/9//50pIw@ek8Gux5ka@CikcJBGAsIbjo5IDyI7gwjqmWkx3Ijmjcq0a6QKnDxmwFTFXN1QaQWM2vKEVTs9OKxKibbOyVUhfu33Pk/zpixToonoe2gRhFXqLG7DjPtTtZ9pFNQLc25iC2bU8yE3Y9wv9zP5i5hsWOZZb8Xqxt7p7Y98b6BqrHXN3FjOry/iL@mLGdpW5JqRKx4VnPw/gU "Perl 6 – Try It Online")
Outputs the string with a trailing newline. If you don't want that, then replace the last `say` with a `print`. You can also replace the newlines in the source with spaces.
## Explanation
This code prints the string character by character. Each character is formed by feeding the appropriate character code into the `chr` function and lowercasing it with `lc` if needed.
Currently, all of the values are generated by generating a string with the correct number of characters in it; in some cases, the number of characters is the reverse of the target character code. It should be theoretically possible to use mathematical functions such as `log` and `exp` directly, but I didn't find it very easy to use those.
For use as numbers, we have `e`, `pi` and `tau`; in the right side of `x` or `xx`, they are implicitly floored. They all have 17 characters in their string representations, so we use `e` for minimal character count. We also have `i` (4 characters), `False` (5 characters) and `NaN` (3 characters). We can multiply string lengths with `x`; `xx` multiplies one plus the string length by the right hand side and adds one. `chop` removes one character from the string in case we're one away from the target.
The print statements are chained together using `and`, which has quite a low precedence. It's almost a miracle it exists; otherwise, we would have to use illegal semicolons.
I found the expressions for the characters by hand. It might be worth searching for them programmatically to find shorter expressions.
[Answer]
# [Width](https://github.com/stestoltz/Width), ~~66~~ 64 bytes
```
QaaGmwmiimaGcwWiimawAGawmfciiiGaFmAmFiimFGcwAmFiGmaiiGcGamafFiGQ
```
[Try it online!](https://tio.run/##FYkhDsAwDAPfVhLjomGrUzUDs0l5fpoi351T7/9VTRJOSyZWPndzgOm9JIHh4ega/V6C2XmB5m6bVQc "Width – Try It Online")
Prints to debug. To print to stdout, append `ww` to the end of the code, which pops and outputs the top of the stack.
# Explanation
In Width, each letter correlates to a number, based on how "wide" it is, according to [this table](https://i.stack.imgur.com/PTbFZ.png). This assigns each letter a number from 0 to 9. Then, those numbers are used to actually execute code.
In particular, a letter than matches `7` will start a string literal. It will read sets of two letters at once, until it reads the original letter again. Each set of two letters will be converted to their width numbers, read as a decimal number between 0 and 99, and the character they equal will be their index in the following string:
```
!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~\n\t
```
For example, the index of `!` is 1, so `01` will be the right width numbers. Thus, `if`, `iI`, `jt`, etc will all correlate to a string literal of `!`.
In this case, I translated the 31 characters of the required output to appropriate letters, using `Q` as the quotation marks. The top of the stack is printed to debug when the program finishes.
[Answer]
# x86 machine code (32-bit), 256 bytes
When I print my code on my codepage 437 console, I see the following:
```
j XI a I a I a jbZ Q fiQ Gf a f Q I a I a I a I a h hisZ Q I a I a I a I a hBP Z Q iQ
y Q a I a I a I a h thaZ Q I a I a I a Ih ButZ Q a I a I a I a fhu fZf Q iQ g S Q a I a I a I a hsaidZ Q I a I a I a I a hshe Z Q I a I a I a I a hAnd Z Q TZBX b
```
This contains some whitespace characters, so here is the same code when I replace all tab characters by `→` and all nonbreaking space characters (with code 255) by `*`:
```
j XI a I a I a jbZ→Q fiQ Gf a f→Q I a I a I a I a h hisZ→Q I a I a I a I a hBP Z→Q iQ →→y →Q a I a I a I a h thaZ→Q I a I a I a Ih ButZ→Q a I a I a I a fhu fZf→Q iQ g→S →Q a I a I a I a hsaidZ→Q I a I a I a I a hshe Z→Q I a I a I a I a hAnd Z→Q TZBX*b*
```
Hexdump:
```
6a 20 58 49 20 61 20 49 20 61 20 49 20 61 20 6a
62 5a 09 51 20 66 69 51 20 47 66 20 61 20 66 09
51 20 49 20 61 20 49 20 61 20 49 20 61 20 49 20
61 20 68 20 68 69 73 5a 09 51 20 49 20 61 20 49
20 61 20 49 20 61 20 49 20 61 20 68 42 50 20 20
5a 09 51 20 69 51 20 09 09 79 20 09 51 20 20 61
20 49 20 61 20 49 20 61 20 49 20 61 20 68 20 74
68 61 5a 09 51 20 49 20 61 20 49 20 61 20 49 20
61 20 49 68 20 42 75 74 5a 09 51 20 20 61 20 49
20 61 20 49 20 61 20 49 20 61 20 66 68 75 20 66
5a 66 09 51 20 69 51 20 67 09 53 20 09 51 20 20
61 20 49 20 61 20 49 20 61 20 49 20 61 20 68 73
61 69 64 5a 09 51 20 49 20 61 20 49 20 61 20 49
20 61 20 49 20 61 20 68 73 68 65 20 5a 09 51 20
49 20 61 20 49 20 61 20 49 20 61 20 49 20 61 20
68 41 6e 64 20 5a 09 51 20 54 5a 42 58 ff 62 ff
```
Some explanations on how it works:
Useful instructions are:
* `push imm8`, `push imm16` and `push imm32`, followed by `pop` generate constants. This can also generate zero (in `ah`) when pushing a byte (`imm8`).
* `and [ecx+32], ah` - assuming ah = 0, this sets the byte to zero. It just so happens that the length of the output string is 32, so the code fills the buffer from end to beginning.
* `or [ecx+32], edx` - assuming the output byte is set to zero, this copies `edx` (4 bytes) to output. I use a variant with `dx` instead of `edx` near the end of the buffer, because it should not write beyond the output buffer. The restriction on code makes it impossible to write single bytes this way!
* `imul edx, [ecx+32], whatever` - this is the main scrambling idea. With enough entropy in `[ecx+32]` and the *whatever* number, it can generate any output. I use it to generate 2 or 3 bytes of needed values. Some complication is, when writing it to the output, it must do logical `OR` with whatever is already there. This sometimes made it necessary to zero the memory once again.
* A variant of a `jmp` instruction is used to return. I chose it because its encoding is `0xff`, which corresponds to a non-breaking space in codepage 437. A bit of a stretch on the rules, but otherwise I think the task is impossible...
Assembly source code, together with a C program which runs it (uses Visual Studio syntax):
```
#include <stdio.h>
__declspec(naked) void __fastcall doit(char* buf)
{
__asm {
push ' '
pop eax
dec ecx
and [ecx+32], ah // terminating 0 byte
dec ecx
and [ecx+32], ah
dec ecx
and [ecx+32], ah
push 98
pop edx
or [ecx+32], edx
imul dx, [ecx+32], 26183
and [ecx+32], ah
or [ecx+32], dx // two bytes: [.']
dec ecx
and [ecx+32], ah
dec ecx
and [ecx+32], ah
dec ecx
and [ecx+32], ah
dec ecx
and [ecx+32], ah
push 'sih '
pop edx
or [ecx+32], edx // 4 bytes: [ his]
dec ecx
and [ecx+32], ah
dec ecx
and [ecx+32], ah
dec ecx
and [ecx+32], ah
dec ecx
and [ecx+32], ah
push 538988610
pop edx
or [ecx+32], edx
imul edx, [ecx+32], 544803081
or [ecx+32], edx // 1 junk byte and 3 good bytes: (t's)
and [ecx+32], ah
dec ecx
and [ecx+32], ah
dec ecx
and [ecx+32], ah
dec ecx
and [ecx+32], ah
push 'aht '
pop edx
or [ecx+32], edx // 4 bytes: [ tha]
dec ecx
and [ecx+32], ah
dec ecx
and [ecx+32], ah
dec ecx
and [ecx+32], ah
dec ecx
push 'tuB '
pop edx
or [ecx+32], edx // 1 junk byte and 3 good bytes: [But]
and [ecx+32], ah
dec ecx
and [ecx+32], ah
dec ecx
and [ecx+32], ah
dec ecx
and [ecx+32], ah
push word ptr 8309
pop dx
or [ecx+32], dx
imul edx, [ecx+32], 542312807
or [ecx+32], edx // 1 junk byte and 3 good bytes: [, ']
and [ecx+32], ah
dec ecx
and [ecx+32], ah
dec ecx
and [ecx+32], ah
dec ecx
and [ecx+32], ah
push 'dias'
pop edx
or [ecx+32], edx // 4 bytes: [said]
dec ecx
and [ecx+32], ah
dec ecx
and [ecx+32], ah
dec ecx
and [ecx+32], ah
dec ecx
and [ecx+32], ah
push ' ehs'
pop edx
or [ecx+32], edx // 4 bytes: [she ]
dec ecx
and [ecx+32], ah
dec ecx
and [ecx+32], ah
dec ecx
and [ecx+32], ah
dec ecx
and [ecx+32], ah
push ' dnA'
pop edx
or [ecx+32], edx // 4 bytes: [And ]
push esp
pop edx
inc edx
pop eax
jmp dword ptr[edx-1]
}
}
int main()
{
char buf[100];
doit(buf);
puts(buf);
}
```
[Answer]
# PostScript, ~~889~~ ~~874~~ ~~837~~ 835 bytes
```
currentflat string dup rrand
count dup count count mul mul xor count count mul count dup mul exch count
count copy count copy count copy count copy count copy
add and sub put print
and sub add put print
sub sub add put print
mul or xor put print
idiv xor add put print
or xor add put print
mod idiv add put print
mul or xor put print
idiv xor add put print
sub and add put print
or and add put print
sub sub add put print
pop add sub put print
mul or xor dup copy put print
mod mul sub put print
add or xor put print
idiv add add put print
add or add put print
put print
add or add put print
or xor add put print
sub and add put print
add or add put print
mod mul sub put print
idiv xor add put print
mul or xor put print
or xor add put print
or and add put print
idiv xor add put print
xor add sub put print
mod mul sub put print
quit
```
[Try it online!](https://tio.run/##nZNdDsIgEITfOcVewENVqEpSYeXH1NPXBdpUYGuiDyXLMCwfQ4rWBy@dxnCakeplkdG50YTLNATwwWlzBRURnBuMEtJGE/K8VGW8xyl/s3Wdvu9Is3GWtyKJzYgv@KEUg1JAJODjGTAGQCIMYlPS6q4mpVcTB4Em2F3USj@zVHtXX9PAKsj@//tmKmLuTutF/hJoMSt1DB8I5Y0ou5o7OZroqAuPnaOuTl29Dcr3ZTZC/v7sfp76IFf2DVgCNuuDrpvShM2CPaKmn@gN "PostScript (xpost) – Try It Online")
This uses 32 copies of the integers `89 25 20 6`. All charcodes of the target string can be obtained with operations on those integers, in stack order: for example, 'A' (ASCII 65) is 89 - (25 & (20 + 6)). Many 4-tuples of integers have this property; this one was chosen because they’re particularly easy to generate.
```
currentflat string dup rrand
```
Flat defaults to 1, so this creates a string of length 1 (initialized to `\0`). `dup` is not a deep copy: it creates a second reference to the same string. rrand pushes the random seed, which defaults to 0. Stack is now `["\0", "\0", 0]`.
```
count dup count count mul mul xor
```
`count` pushes the number of items in the stack, so this computes 3 ^ (3 \* (5 \* 6)) = 89.
```
count count mul count dup mul exch count
```
4 \* 5 = 20, 5 \* 5 = 25, 6 = 6. The stack is now `["\0", "\0", 0, 89, 25, 20, 6]`.
```
count copy count copy count copy count copy count copy
```
Duplicate the entire stack, five times. Thus we end up with 32 copies of our initial 7-element stack. We only need 31 copies, since the target string is 31 characters long, but the extra copy doesn’t hurt.
```
add and sub put print
```
Compute a charcode from the top four integers, write it at index 0 of the string, then print the string.
```
quit
```
Suppresses the default prompt.
[Answer]
# [><>](https://esolangs.org/wiki/Fish), ~~233~~ 122 bytes
```
cdacaabbglccgpcbfbbcaacdebbafbebbcebdbealbcpcdbcccdlcdpacbbalccpaalacpbcfafbaab
g sandBe
o Aviuth
```
[Try it online!](https://tio.run/##PU1JCoBADLv7in5Ff5KkM6MwaMHl@1oQzSGQpU1d9vm@5RBAti61ECuZWl5IVCar0FnQqZBTknd5QJnnSQAdCqpmO/8MP@xFM9ux@lQ@YzMbr@U8cvsB "><> – Try It Online")
This started as a golf of [mbomb's answer](https://codegolf.stackexchange.com/a/186784/69059), but I discovered a fundamental shift that saves a huge number of bytes, so I'm posting it as my own answer.
Generating non-alphabetic characters to output is done by repeatedly pushing values to the stack, then using `l` to push the stack length. However, this does not need to be output immediately: using `p`, this character can be placed in any cell whose coordinates are both between 10 and 15 inclusive, to be retrieved later with `g`. Similarly, alphabetic characters can be placed in the initial source code and read this way: since the highest non-alphabetic character code in the input is 46 (`.`), this means the stack does not need to be pushed higher than the 62 needed to store all 31 characters of the output.
Additionally, a `v` is placed in the code at column 7. When the instruction pointer wraps around and hits that `v`, the sequence `go` is executed repeatedly to read from the pushed coordinates and output the corresponding characters. Eventually, the stack becomes empty, and `g` terminates the program with an error.
The first 7 bytes of code are reused as both the first 7 and last 7 coordinates pushed. Placing the `v` in column 9 would have theoretically saved two more bytes, but would have forced the characters `Ainsv` into a 2x2 square in the code, which is impossible. An earlier version used column 15, but that required an extra line in the source code and ended up six bytes longer.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 420 354 338 bytes
```
def P a
print String a
end
def Q a
p String a
end
class String
def inspect
putc sum size
q
end
end
def w
Q def hacked
end
rescue
end
P def And
end
w
P def she
end
w
P def said
end
Q def gadget
end rescue
w
def a
Q def afraid
end
rescue
end
a
P def But
end
w
P def that
end
a
putc String def s
end
w
P def his
end
Q def fierce
end rescue
a
```
[Try it online!](https://tio.run/##VU/bDYMwDPzPFF6lnQDUCdxgSESLaOwItcunxBiJfDn3yJ2d8vNbykAjdIBuTXEReMg@ph3SMrgq9VVqaf9CZqPUExdeyYtbs3jg/AaOP3IfNZ85m@uhzoB@poNOxD6TPjvVbubfDHOgFmM8DEfUhMNEUgmwqE2r0HQc0/nhUoUWds/ShEtAMYPeYSdrb2MMkS9LjJGSp@sSWMof "Ruby – Try It Online")
In ascending order of jankiness:
Words starting with a capital letter can be printed by defining a class with that name and calling `display` within the class definition body.
Other words can be displayed by defining methods with that name, which returns a Symbol, then casting that to a String to remove the leading colon.
Other characters can be displayed by calling `putc` on their ASCII code. We can generate the appropriate numbers by reusing the `String def` trick to get a string, then taking the sum of its bytes using a [modulus](https://ruby-doc.org/core-2.6/String.html#method-i-sum) determined by its size. Unfortunately, we don't have any way to call methods on an object other than from within the class definition of that object, which makes it difficult to pass in arguments. So the final hack is to redefine `String#inspect`, which gets called implicitly when passing a String in to the `p` method, so that it calculates and outputs the appropriate character as a side effect, before raising an error so that `p` can't actually finish executing and print a newline. Then we need to rescue the error in the main code.
Edit: [Jordan](https://codegolf.stackexchange.com/users/11261/jordan) made the byte count much less, ahem, high with some clever control flow golfing, and I've cut a few more bytes by replacing `raise` with a one-letter nonexistent method call, which raises a NameError.
Edit 2: Noticed that with `print String` extracted into a method, it's cheaper to just use that with a method definition than to use the class definition trick, since methods are allowed to be title cased.
[Answer]
# [Stax](https://github.com/tomtheisen/stax), ~~133~~ ~~95~~ ~~84~~ 79 bytes
```
AHHvcAvSVvNvXvsrDhYcvxvZLcHxVahyvxxZVvHVChAHHvVAHhvZAJyVahxvVvDhZyvxvAJZcASVAhL
```
[Run and debug it](https://staxlang.xyz/#c=AHHvcAvSVvNvXvsrDhYcvxvZLcHxVahyvxxZVvHVChAHHvVAHhvZAJyVahxvVvDhZyvxvAJZcASVAhL&i=&a=1)
[Answer]
# [CJam](https://sourceforge.net/p/cjam), 262 bytes
```
KAbScibCmhc CZbsic GmQYbsic
S CmfYmeibc ImqmeKmhcel AZbAbc
S CmfYmeibc KAbScibCmhcel ImqmeKmhAmhcel GmQYbsic KAZbYbbBbc
S CGmQbDbc EYbTYtZbc FYbGmQbcel EYbGmQbcel
S EYbGmQbcel ImqmeKmhcel KAbScibCmhcel EYbGmQbcel CGmQbDbc CmfYmeibc
S ImqmeKmhcel ImqmeKmhAmhcel CmfYmeibc PYmhmeKmhc CGmQbDbc
```
[Try it online!](https://tio.run/##VY7NDsIgDIBfhdsuxndgcxqziwYv5UY7DJjVZAGfH5mGjZ36931t6WU4pUGiIo8dO@o0Bk8XvsMSVcdPYOuRrjyzHTJgJ6lRYjWqbDsVTv6qsmfIDiC2i5Z7eELqAR8QNdIZcGllul8ztaXV4d2hjSgb14dU5ez/WZEbsPsjxU5JvkcRnBXB@PEgmvYTRXQmNkE4H47NFw "CJam – Try It Online") Newlines are only shown here for clarity; each line represents a character.
Whew, this was fun. Restricting ourselves to alphabetic commands poses some interesting challenges:
* Without `{` and `}`, there's virtually no opportunity for control flow (except `f`, which I didn't find an opportunity to use).
* Without `\`, `_`, `;`, or `$`, we have no means for stack manipulation.
This means that the main goal is going to be getting the relevant code points on the stack and then converting them to characters with `c`.
The problem is that we also lack most basic arithmetic commands, as well as integer literals. This is fine though, as the `m` namespace contains numerous advanced mathematical operations, and there are many variables predefined to useful numbers.
I ended up making heavy use of square roots (`mQ` and `mq`), the exponential function `me`, and base conversion (`b`), which can also be used to emulate multiplication (`[X 0] Yb` computes X\*Y). In addition, sometimes it is easier to construct the uppercase codepoint, in which case we can use `el` (convert to lowercase) on the resulting character.
I'm still not satisfied with some of the longer ones. Oh well.
## Explanation
This is a character-by-character explanation of the output. Before I start, here are a few short ways to make numbers:
* 0, 1, 2, 3 are contained in variables `T`, `X`, `Y`, `Z` respectively.
* Numbers 10 through 20 are contained in variables `A` through `K`.
* 32 can be made using `Sci` (`S` pushes a string containing a space, `c` gets the first character of this string, and `i` converts that character to its code point). `S` is also used for spaces.
* 4 is given by `GmQ` (integer square root of 16).
* 5 is given by `AZbYb` (convert 10 to base 3, yielding `[1 0 1]`, and convert the resulting array of numbers to base 2, yielding 5).
* 7 is given by `Ymei` (compute exp(2) and convert to integer).
### `A`
```
K - push 20 | 20
Ab - convert to base 10 | [2 0]
Scib - convert from base 32 | 64
Cmh - hypot(TOS, 12) | 65.115
c - round down and convert to char | 'A
```
### `n`
```
C - push 12 | 12
Zb - convert to base 3 | [1 1 0]
s - convert to string | "110"
i - convert to integer | 110
c - convert to char | 'n
```
### `d`
```
GmQ - push 4 | 4
Yb - convert to base 2 | [1 0 0]
s - convert to string | "100"
i - convert to integer | 100
c - convert to char | 'd
```
### `s`
```
C - push 12 | 12
mf - factors | [2 2 3]
Ymeib - base 7 | 115
c - convert to char | 's
```
### `h`
```
I - push 18 | 18
mq - sqrt | 4.242
me - exp | 69.591
Kmh - hypot(TOS, 20) | 72.408
c - round down and convert to char | 'H
el - lowercase | 'h
```
### `e`
```
A - push 10 | 10
Zb - convert to base 3 | [1 0 1]
Ab - convert from base 10 | 101
c - convert to char | 'c
```
### `a`
```
KAbScibCmhc - push 'A (see above) | 'A
el - lowercase | 'a
```
### `i`
```
I - push 18 | 18
mq - square root | 4.242
me - exp | 69.591
Kmh - hypot(TOS, 20) | 72.408
Amh - hypot(TOS, 10) | 73.095
c - convert to char | 'I
el - lowercase | 'i
```
### `,`
```
K - push 20 | 20
AZbYbb - convert to base 5 | [4 0]
Bb - convert from base 11 | 44
c - convert to char | ',
```
### `'`
```
C - push 12 | 12
GmQb - convert to base 4 | [3 0]
Db - convert from base 13 | 39
c - convert to char | ''
```
### `B`
```
E - push 14 | 14
Yb - convert to base 2 | [1 1 1 0]
TYt - replace elem 0 with 2 | [2 1 1 0]
Zb - convert from base 3 | 66
c - convert to char | 'B
```
### `u`
```
F - push 15 | 15
Yb - convert to base 2 | [1 1 1 1]
GmQb - convert from base 4 | 85
c - convert to char | 'U
el - lowercase | 'u
```
### `t`
```
E - push 14 | 14
Yb - convert to base 2 | [1 1 1 0]
GmQb - convert from base 4 | 85
c - convert to char | 'T
el - lowercase | 't
```
### `.`
```
P - push pi | 3.141
Ymh - hypot(TOS, 2) | 3.724
me - exp | 41.437
Kmh - hypot(TOS, 20) | 46.011
c - round down and convert to char | '.
```
[Answer]
# [Deadfish~](https://github.com/TryItOnline/deadfish-), 943 bytes
```
iiisdsiciiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiicddddddddddcddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddcdddddddddddddddddddddsddddddcdddddddddddcdddcdddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddcdddddddddddddddddddddsddddddcddddddddddddddddddciiiiiiiicdddddcddddddddddddddddddddddddddddddddddddddddddddddddddddddddcddddddddddddciiiiiiiciiiiiiiiiiiiiiiiiiiiiiiiiiiciiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiicdcddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddcdddddddddddddddddddddsdddddcddddddddddddcdddddddciiiiiiiiiiiiiiiiiiicdddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddcddddddddddddddddddddddddddddsddddddcdddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddcddddddddddddddddddddddsiiiiciciiiiiiiiiicdddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddcdddddddc
```
[Try it online!](https://tio.run/##S0lNTEnLLM7Q/f8/MzOzOKU4MzmTFJCcAgdITPIBdkOKMSWTqWUj8VbC1KP6PZkq9sIMxRf6pMUMzI3UCSQSwiwZm8Jk/GmHZk4iGJu0srcYEmPJ1PYuPED//wcA "Deadfish~ – Try It Online")
No loops allowed `:(`
[Answer]
# [evil](https://web.archive.org/web/20070103000858/www1.pacific.edu/~twrensch/evil/index.html), 198 bytes
```
aeeeannkhhwzuuuuuueaeuekwuuuuuuuuuunkhwzaeeeeehknwgueeywguuuuuuhhknnwuuuwhgwpwnngheeuwguuuuuwngwzaeeeaaaeeeeeewhhgwnguuuueewnngawpaawuwnngwpawhgwhhgeeuwpawhguuuueewpwhgwhgwawpwnngaaaaaaeeeewguuuueew
```
[Try it online!](https://tio.run/##PY1BDgMxCAPf6oMVqlQoF2p1P58Fsq0PCPBg@Hm99wZJuE8zXdEiGJyKv9LUVRxp0zWC/GZtWW68WNnQkvswMh5XPs4hcM4pS8zbzSFpaAGKarOrkCQqoYeHW70fwvmAVsf9iL1v "evil – Try It Online")
This was quite fun.
[Answer]
# [dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html), ~~240~~ ~~222~~ 209 bytes
```
OOOOOziOOOOOOOOOOOOOOOOOOOOOOOOOOOzddddddzkdddzasBdzasAdzscdzdasCzsdOOlAxlAxPOBlBxdIlAxoPAdlBxddsrIlAxssPPOPlsIZlCxddspPOZlCxPPOPlrdZlCxPlsPlrPlcPPKPdZlBxdZlAxPOAZlAxdPIZlCxdPrPdPlpPlrdZlCxPPKPOPPlpPlsPOPldPKP
```
[Try it online!](https://tio.run/##dYyxCgNBCES/bfeqI4VTX3fsNCFCjrU5/PmNGkiXQfQ5OHKsJSl/yn85S/7KdlrP1ug26Dxtc6OItjsK0rXf3APfaEymzVzNAIHafuiW5gVJKnOyUC0QOoAHwonsUS9bDuKbxASh1y8Ut4IyLF8x9rU@ "dc – Try It Online")
My first thought was the same as @seshoumara, just push enough stuff onto the stack to generate all of the characters' ASCII values. Then it occurred to me that since `+`, `-`, and `*` are single-character operators, I can just recreate them and have the ability to use arithmetic! Surely that would be smaller! ~~And, I wouldn't be surprised if I'm able to golf off any more bytes, but for now... this convoluted approach has managed to tie the naïve(ish) one.~~
`OOOOOziOOOOOOOOOOOOOOOOOOOOOOOOOOOzddddddzkdddzasBdzasAdzscdzdasCzsd` is the part of the approach that's similar to @seshoumara's, but we only go up to 46, which is `.`. We do this because we need to go up to 45, `-`, and we also need a period in our string, so just going one further for the period is (I think) cheapest. Along the way, we store some values: 5, 32, 39 all come in handy later. 5 for utilitarian things, 32 and 39 for their ASCII values. Originally I did 1-5, but that was expensive, and I was able to simply avoid using 4; use `Z` (pop a value, push the number of digits it has) on a three-, two-, or one-digit number for those values. At 42, 43, and 45, we convert these to strings (`*`, `+`, and `-` respectively) and store them as macros (`B`, `A`, and `C` respectively). This means that without using the characters `*+-`, we can now use those operators.
From here we basically start generating the ASCII values using the power of math instead of sheer accumulation, storing some of the repeats along the way. 100, 105 and 115 come up enough that storing them (in registers or otherwise) made sense. Originally, I left the stack filled with 10s and used these to make 100s; it ended up saving bytes to fill the stack with 32s and use those as spaces later on. A slightly more readable version of the ASCII section: `OOlAxlAxP OBlBxdIlAxoP AdlBxddsrIlAxssP P OP lsIZlCxddspP OZlCxP P OP lrdZlCxP lsP lrP lcP P KP dZlBxdZlAxP OAZlAxdP IZlCxdP rPdP lpP lrdZlCxP P KP OP P lpP lsP OP ldP KP`.
*Shaved off 18 bytes by: storing the number 5 as the input radix instead of a register; the number 32 as precision instead of a register; the number 115 as output radix instead of a register; then had to change `KZ` to `IZ` to generate 1s and `OZ` to `KZ` to generate 2s.*
*Shaved off 13 more bytes by flooding the stack with 32s; setting precision to 39; using stack manipulation to avoid storing 116; cutting out some double-work I accidentally left in.*
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~187~~ 158 bytes
```
IEWQKEtqhpEqqKQHhthpKWEyQKWEqqYqQQXJwtQQQwKWEJKQthpYqKQHhthptQQQQQwIIhKQhpqKWEIWKQhpqIEWQQJQQtqKWEyIIhIhpYqQXJyKQthpYqwIWKQhpqyqKWEyJtQwhhPIIhKQhpQIWKQhpqvlec
```
[Try it online!](https://tio.run/##NYyxCoAwDAW/rmCaxTfVjiJCBoUGgqVfX1OpSwnvrnfvdvVOIYGDqZSgyljEpHAKDf6oZgW2WA1A9SEyHOffG7MDImFIURcofdeIIgI2tuacxi8vtRmoU2yfEA1VZJ0dTPZc59H7Cw "MATL – Try It Online")
More readable version: [Try it online!](https://tio.run/##RY3BCsMwCIbvvldgJpf9p6zHMQYeOoggC3n6TNu1PYjK//n5edo6J6cKKslUWlKlgpuYNCo10UA01UWBR@5kAPqWZOecWi4@skiZpUCabhjXfY4foOxlezCC4xC42Le/rZ8X4@Cym7vI/RDjRL7r@zXnDw "MATL – Try It Online") Manual attempt at building the string. There's probably plenty of room for golfing by cutting the string into convenient chuncks, using `P` and `h` to flip and build a string. I hope somebody will take up the challenge to outgolf me. The main challenge is that you cannot use `+` or `-`, so basic arithmetic is often not possible.
Highlights:
* `KQthpYq`: the 25th (`KQthp`) prime `Yq` is 97, corresponding to the letter `a`. The letter `s` (115) is generated similarly from 113, the 30th prime number. It is then extensively re-used in clipboard `J`.
* `his` is shortened by storing the `h` from before in clipboard `J`. Since that previously stored `s`, we build `his` in reverse so we can still retrieve the recent `s` using `y`, and flip it after using `P`.
* A large number of bytes saved thanks to Luis Mendo (mostly by changing a bunch of `h` to `vle`)
[Answer]
# [MATL](https://github.com/lmendo/MATL), 118 bytes
```
KEUQtVQsQKBFZAXHKUqyyhsXJyyhdQtQQQwOJIUEyhdtKEhsHKQYqEEKQyywhdXJKEUQQHKUhstQwOytHKhsKYqyhdbJyqOHKhstQHKUqhsKUqYqqJvlec
```
[Try it online!](https://tio.run/##FYuxCsMwDES/rQUFVxqCBhe7W9oENKSDkGjQ17vycvDu3n03P8cgqOxPNqb78rq1QlUjxBpm7uzMfK34qJDkBGKFuCsAccQle8P553yJeZrhhcSoa@pvDF0n@tw166pdFX/n8RnjDw "MATL – Try It Online")
[More readable version](https://tio.run/##HYyxDsIwEEN3/xVIQaU3oBuCGjagSBnKcMqJKl8ffJ0s@9n@Pn0bQ1JW@F2bQs6Xx2mZINnQe23LHLISqyp23DDjmhMjuKTawKoWS4nC5l5XLuJPMUkmd41Rh9PTSrHYvnjTjeAI/Shb4GzFjPC3fd5j/AE) (each line corresponds to one character, except stack-rearranging operations).
# Explanation
The program produces the code points of the required characters, as independent numbers. At the end all those numbers are concatenated into a column vector, reshaped as a row vector, and converted to characters. The result is implicitly displayed.
Some of the tricks used:
* Most code points below 32 are displayed as space. So `0` is used for most spaces, because it only costs a byte (`O`).
* For the first space, however, `15` is used (generated as `KUq`), because it can then be reused by adding it to `100` (char `d`) to give `115` (`s`). On another occasion `5` is used for space (generated as `KQ`), so it can be later subtracted from `44` (`,`) to give `39` (`'`).
* Clipboard `J` is used for storing characters that will be repeated: first `s`, then `'`. Similarly, clipboard `H` stores `100`, which is useful for `d` and for generating other characters.
* Extensive use is made of functions `Q` (add `1`), `q` (subtract `1`), `E` (multiply by `2`) and `U` (square), together with the predefined literals in clipboards `I` (`3`) and `K` (`4`).
* Arbitrary addition and subtraction are done by concatenating into a vector (`h`) and computing its sum (`s`) or consecutive differences ( `d`).
* `100` (`d`) is generated as `4` in binary interpreted as a decimal number.
* `110` (`n`) is obtained from `65` (`A`) by converting to string (`'65'`: code points `[54 53]`), adding `1` to the code points (`[55 54]`), summing them together and adding `1`.
* The order in which numbers are generated is sometimes altered for convenience; and they then are reordered by stack-rearranging functions: swap (`w`), bubble up `b`).
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 87 bytes
```
Bs g caA
HzG
Ts caV
iWisiiihiSisiUitiaihitiSitiuibu iUiSiWcaV idiiiaisiSieihisiSidiniau
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=QnMgZyBjYUEKSHpHClRzIGNhVgppV2lzaWlpaGlTaXNpVWl0aWFpaGl0aVNpdGl1aWJ1IGlVaVNpV2NhViBpZGlpaWFpc2lTaWVpaGlzaVNpZGluaWF1)
## Explanation
The first line generates the `'` and assigns it to variable `U`.
```
Bs g caA
B :11
s :To string
g :First character
c :Character code
a : Absolute difference with
A : 10
```
The second line assigns `2` to variable `V`.
```
HzG
H :32
z :Floor divided by
G :16
```
The third line generates the `.` and assigns it to variable `W`.
```
Ts caV
Ts :Convert 0 to a string
caV :Absolute difference of its charcode with V (2)
```
The last line, then, builds the string one character at a time in reverse.
```
iW...ibu ...iWcaV ...iau
iW :Start by prepending W (.) to U (')
... :Each i prepends the literal character that follows it to the string, with S being space and U being "'"
ibu :As B is the constant for 11 and it can't be quoted, here i prepends "b" to the string and u uppercases it
... :As above, each i is prepending the character/constant that follows it to the string
iWcaV :Gets the absolute difference of the charcode of W (.) and V (2) to get the "," and prepends that
... :Some more literals
iau :And, finally, the same trick is used for the "A" as was for the "B", as A is the constant for 10
```
[Answer]
# [Red](http://www.red-lang.org), 272 bytes
```
prin quote And prin sp prin quote she prin sp prin quote said prin comma prin sp prin subtract to sp mold quote G sp prin quote But prin sp prin quote that prin subtract to sp mold quote G sp prin quote s prin sp prin quote his prin dot prin subtract to sp mold quote G sp
```
If the double quotes are necessary:
# [Red](http://www.red-lang.org), 344 bytes
```
prin subtract to sp mold quote B sp prin quote And prin sp prin quote she prin sp prin quote said prin comma prin sp prin subtract to sp mold quote G sp prin quote But prin sp prin quote that prin subtract to sp mold quote G sp prin quote s prin sp prin quote his prin dot prin subtract to sp mold quote G sp prin subtract to sp mold quote B sp
```
Doesn't work in TIO but works in the Red interpreter.
[![Red console](https://i.stack.imgur.com/h4I2X.png)](https://i.stack.imgur.com/h4I2X.png)
## Explanation:
The words are trivial - I prin them (print with no newline) as literals with `quote`. [Red](http://www.red-lang.org) has a built-in word for space - `sp`, as well as `comma` and `dot`. `"` and `'` more interesting: I prin them by subtracting a space from `B` and `G` respectively, starting from a literal `B` and `G`, converting them first to string with `mold` and then to character (in order to use subtraction on them) wtih `to sp` ([Red](http://www.red-lang.org) has conversion by prototype - convert the string to the type of `sp`, which is character).
[Answer]
# Forth (gforth), 351
```
CHAR A DUP EMIT
CHAR n EMIT
CHAR d EMIT
SPACE
CHAR s DUP EMIT
CHAR h EMIT
CHAR e EMIT
SPACE
EMIT
CHAR a EMIT
CHAR i EMIT
CHAR d EMIT
DUP CHAR m XOR EMIT
SPACE
CHAR f XOR DUP EMIT
CHAR B EMIT
CHAR u EMIT
CHAR t DUP EMIT
SPACE
DUP EMIT
CHAR h EMIT
CHAR a EMIT
EMIT
DUP EMIT
CHAR s EMIT
SPACE
CHAR h EMIT
CHAR i DUP EMIT
CHAR s EMIT
CHAR G XOR EMIT
EMIT
```
Too bad I can't redefine CHAR or EMIT to one-letter words, since that would require using either `:` and `;` (e.g. `: C CHAR ;`) or `'` (e.g `' CHAR ALIAS C`)
In fact, if I could define words, I could do `: P CHAR EMIT ;` and then do `P x` to print `x`. Oh well.
I can't even create a buffer, write that char sequence to there and then use that as the input, since writing to memory requires using `!` or `C!`
[Answer]
# [AlphaBeta](https://github.com/TryItOnline/alphabeta), ~~180 177 175~~ 163 bytes
```
cccaaggtFgDILrFigggDLjDLCLigggggDLjhDLhhhDLCLiggggDLjjggDLihhDLhhhhhDLcaaCLdbbCLcbbbCLHgDLiiiiigDLhDLdaaaCLDLjhhDLjgggDLiihDLcbbbCLhDLdaaaCLjhDLgDLiDLcaaaaCLdaaaCL
```
[Try it online!](https://tio.run/##PY3RCsAgCEU/rogN/AmtocUexuj/m9dBPVzTYye@H2O5Jq9Va2VWnUXzSW/pqpppZEqEazSWycz2yCcD2e0HKO5I1EQSVUEe4DheHTcGh8qbEY7e8SyW9wJ@AgpfGCPX@gA "AlphaBeta – Try It Online")
WIP
[Answer]
# [Pepe](https://esolangs.org/wiki/Pepe), 266 Bytes
I keep the r stack empty, and have 's' on the R stack
```
reeEeeeeeE reeEEeEEEe reeEEeeEee reEe REeEEEeeEE Reee reeEEeEeee reeEEeeEeE reEe Reee reeEEeeeeE reeEEeEeeE reeEEeeEee reeeEeEEee reEe reeeEeeeEe reeEeeeeEe reeEEEeEeE reeEEEeEee reEe reeEEEeEee reeEEeEeee reeEEeeeeE reeEEEeEee reeeEeeEEE Reee reEe reeEEeEeee reeEEeEeeE Reee reeeEeEEEe reeeEeeeEe
```
This isn't on TIO, but you can try it [here](https://soaku.github.io/Pepe/#W2YkY0K!d3HY8Y2KHXuYaY0UwKUcW4YyYwKYwY8XuYwUmHKY8YaHV0Uc)
[Answer]
## [dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html), 240 bytes
The main idea is to continuously grow the stack by 1 (`K`), saving (`sX`) the size of the stack (`z`) into custom registers when it matches each unique ASCII code. Printing (`P`) is done throughout.
```
KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKzsSKKzsQKKKKKzsqKKKKKzsCKKzsDKKKKKKKKKKKKKKKKKKKzPKzsBKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKzsaKKKzsdKzseKKKzshKzsiKKKKKzPldPlSPKKKKKzsszPlhPlePlSPlsPlaPliPldPlCPlSPlqPlBPKzdstzPdPlSPdPlhPlaPPlqPlsdPlSPlhPliPPlDPlqP
```
[Try it online!](https://tio.run/##hY1BCgAhCEXvVu1m84dOEGNQ4CacVZdvVFoOJPjN50/pWes6xJRscu9m7BpN0p8fOgjHpcWVNKu/mmbfC5jAGdso2jdwNcQCLuDujuhkgINeJHkn/Bu5vcBH4shAV5CMrfUB)
I did some optimization, like not saving a letter if it is not used after that, like duplicating (`d`) a letter, e.g. t, on the stack to save a byte, since recall (`lX`) is 2 bytes.
[Answer]
# 80186+ machine code, MS-DOS .COM format, 822 787 bytes
Only tabs and spaces are used in addition to letters. Given that most of the opcodes in the allowed range are certain increments, decrements, pushes, pops, and register-indirect ANDs and ORs, in addition to IMUL, I make use of the fact that the stack register wraps around when it hits the end of the segment to modify the code in reverse! 80186+ assembly is required because I am pushing immediate values.
```
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXjhX GXkOXYIQSX GXjdX GXkOXwIIIIIIIIIQhhihs kOXeQh ihutSXH GXHHHHHH GXSX GYkOXDAAAQSX GXjGX GXkOXtQhidhsahe hshhd hAnSX GXjTX GXkOXdIIIQkOXgAQSX GXHHHHHHHHHHHHHHHHHHHHH GXSX GYkOXbAAAAAAAAAAAAAAQhhlh Xhh qM
```
Annotated source (TASM format):
```
IDEAL
P186
MODEL TINY
CODESEG
ORG 100H
MAIN:
REPT 582
POP AX ; Set up stack to end of string
ENDM
PUSH 68H
POP AX
OR [BX+58H],AX
IMUL CX,[BX+58H],59H ; 68H*59H=2428H
DEC CX ; -1=2427H
PUSH CX
PUSH BX
POP AX
AND [BX+58H],AL
PUSH 64H
POP AX
OR [BX+58H],AX
IMUL CX,[BX+58H],77H ; 64H*77H=2E7CH
REPT 9
DEC CX ; -9=2E73H
ENDM
PUSH CX
PUSH 6968H
PUSH 2073H
IMUL CX,[BX+58H],65H ; 64H*65H=2774H
PUSH CX
PUSH 6920H
PUSH 7475H
PUSH BX
POP AX
DEC AX
OR [BX+58H],AX ; FFFFH
REPT 6
DEC AX
ENDM
AND [BX+58H],AL ; FFF9H
PUSH BX
POP AX
AND [BX+59H],AL ; 00F9H
IMUL CX,[BX+58H],44H ; 0F9H*44H=4224H
REPT 3
INC CX ; +3=4227H
ENDM
PUSH CX
PUSH BX
POP AX
AND [BX+58H],AL
PUSH 47H
POP AX
OR [BX+58H],AX
IMUL CX,[BX+58H],74H ; 47H*74H=202CH
PUSH CX
PUSH 6469H
PUSH 6173H
PUSH 2065H
PUSH 6873H
PUSH 2064H
PUSH 6E41H
;; CODE STARTS:
;; PUSH 0909H
;; POP AX
;; PUSH 046CH
;; POP DX
;; INT 21H
;; INT 20H
PUSH BX
POP AX
AND [BX+58H],AL
PUSH 54H
POP AX
OR [BX+58H],AX
IMUL CX,[BX+58H],64H ; 54H*64H=20D0H
REPT 3
DEC CX ; -3=20CDH
ENDM
PUSH CX
IMUL CX,[BX+58H],67H ; 54H*67H=21CCH
INC CX ; 21CDH
PUSH CX
PUSH BX
POP AX
AND [BX+58H],AL
REPT 21
DEC AX
ENDM
OR [BX+58H],AX ; 0FFEBH
PUSH BX
POP AX
AND [BX+59H],AL ; 0EBH
IMUL CX,[BX+58H],62H ; 0EBH*62H=59F6H
REPT 14
INC CX ; +14=5A04H
ENDM
PUSH CX
PUSH 6C68H
PUSH 5809H
PUSH 0968H
JNO $+4FH
END MAIN
ENDS
```
[Answer]
# [Befunge-98 (FBBI)](https://github.com/catseye/FBBI), ~~125~~ ~~124~~ 121 bytes
```
wab
And she said But that s his
wakekekaayyeapwayyaayybyapayybyapcyabcyaayycayyba
a
b
wayapapoq
```
[Try it online!](https://tio.run/##bZCxbsQgDIbn8BTWLSTSNRm6tJVuaJ@jUmWCuaDqDAUixNOncE2jDjXDb4x/@xO@pMXx47Zt9uZdSOCi2LNYohA@uGvAG1zadYxJWx4Doe4HITQZCCt/7D39rsOL6LJNCzhP3MvZaZJnkFkOgBFMfe3MmINNdDhEFyitgev20d9t5jQ5nyZFZuUrPTw/TcryZJSy0AaehoPCranS/cfR6C2n/ofjneWv6UysL1IOW0YljnhlDXEhiGg1ALzVuWnB@g@w2Cj@RsZPqgexFEKfq7RUFfS7zAXVfC/OrYICm01VY@vx7usb)
[Outputs to a file](https://codegolf.meta.stackexchange.com/a/2453/81203) named `\n` (a single newline). Thanks to [Jo King](https://codegolf.stackexchange.com/questions/186740/print-the-phrase-and-she-said-but-thats-his-using-only-the-alphabet#comment447502_186810) for his script.
Output includes 10 trailing newlines.
For only one trailing newline, **+1 byte** by changing the following line:
```
wakekekaayyeapwayy**d**ayybyapayybyap**y**cyabcyaayycayyba
```
[Try it online!](https://tio.run/##bZDBTsQgEIbP5Skme6FN1vbgRU32oM9hYoYybInZgQUawtNX0Np4cMjkZ2D@4Qu@pMXx47Zt9uZdSOCi2HexRCF8cNeAN7i0coxJWx4Doe4HITQZCCt/7D39rsOL6LJNCzhP3MvZaZJnkFkOgBFMve3MmINNdDhEFyitgevro/@2mdPkfJoUmZWv9PD8NCnLk1HKQht4Gg4Kt6ZK9x9Ho7ec@h@Od5a/pjOxvkg5bBmVOOKVNcSFIKLVAPBW56YF6z/AYqP4Gxk/qS7EUgh9rqJrqoJ@lzIXVDVrObcjFNh8qjpbk3f3Lw)
---
### Explanation:
The instruction pointer moves as follows:[![IP path](https://i.stack.imgur.com/jc9QC.png)](https://i.stack.imgur.com/jc9QC.png)
The program puts the non-alphabetic characters into position, before outputting that line to a file.
Befunge-98 includes instructions `a`...`f`, which push their corresponding hexadecimal value to the stack. To generate other numbers, it passes those values to `y` ("Get SysInfo") as arguments to obtain:
```
10 y-position
11 x-position
12 y-velocity (= 0)
13 x-velocity (= 1)
23* stack size
```
By placing the bulk of the code at y=23, `ayy` can be used for repeated access to the stack size, which is then used to generate character codes.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 210 bytes
```
pChyCdpCyhyhlGpCyytlGpdpChFhTyylGpCyylGpChyytlGpdpChFhTyylGpCtytytlGpChyylGpCyytlGpCyyhTpdpCtyyTpCyhCdpCtFyyCdhTpCyhFlGCdpdpCyhFlGCdpCyylGpCtytytlGpCyhFlGCdpCtyyTpChFhTyylGpdpCyylGpChyylGpChFhTyylGpCyhyhTpCtyyT
```
[Try it online!](http://pythtemp.herokuapp.com/?code=pChyCdpCyhyhlGpCyytlGpdpChFhTyylGpCyylGpChyytlGpdpChFhTyylGpCtytytlGpChyylGpCyytlGpCyyhTpdpCtyyTpCyhCdpCtFyyCdhTpCyhFlGCdpdpCyhFlGCdpCyylGpCtytytlGpCyhFlGCdpCtyyTpChFhTyylGpdpCyylGpChyylGpChFhTyylGpCyhyhTpCtyyT&debug=0)
I found a few numbers which could be expressed using only letters (like `T` = 10, `Z` = 0, `lG` = length(alphabet) = 26, `Cd` = charcode(space) = 32), and a few functions that could be performed using only letters (like `t` = decrement, `h` = increment, `hF` = repeated application of increment = addition), and then just ran a brute force search to find the shortest combinations of those functions and numbers that resulted in each of the letters I needed.
[Answer]
## 16-bit x86 assembly code, 665 bytes
(the binary is alphabetic, not the source)
I somehow forgot about the rule allowing whitespace. Surely the code can be golfed as a result.
Bytecode:
```
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXsBFVKZPFFPFPFPFPFPFPFPFPFPFPFPFPFPFPFPFPFPFPFPFPFPFPFPFPFPFPFPFPFPFPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXkLAFQQZJJJRkDCGPLXDPDJRkDBEPZJJRLZDRDZAAAQPLYDQDYXXDQhishZhDRDhZsDQDhaththRDhuthZBDQDRhidhsaRDhhehZsDRDhndhZADTZPiDEFY
```
Source:
```
db 63 dup (58h) ;pop ax
jnb label1
dw 5646h ;magic #1
dw 5a4bh ;magic #2
dw 4650h ;magic #3
dw (42h-6)/2 dup ("PF")
label1:
db 416 dup (58h) ;more pop ax
imul cx,[si+41h],46h ;cl=24h (string sentinel)
push cx ;push string sentinel
push cx
pop dx ;dl=24h
dec dx
dec dx
dec dx ;dl=21h
push dx ;save for later
imul ax,[si+43h],47h ;al=0CDh
push ax ;push xxCDh
dec sp ;insert xx
pop ax ;ah=0CDh
inc sp ;discard xx
push ax ;push 0CDxx
inc sp ;discard xx
dec dx ;cl=20h (space)
push dx
imul ax,[si+42h],45h ;al=2Eh (dot)
push ax
pop dx ;dl=2Eh
dec dx
dec dx ;dl=2Ch (comma)
push dx ;push xx2Ch
dec sp ;insert xx
pop dx ;dl=2Ch
inc sp ;discard xx
push dx ;push 2Cxxh
inc sp ;discard xx
pop dx ;dx=202Ch
inc cx
inc cx
inc cx ;cl=27h (quote)
push cx ;push xx27h
push ax ;push xx2Eh
dec sp ;insert xx
pop cx ;ch=2Eh
inc sp ;discard xx
push cx ;push 2Exxh
inc sp ;discard xx
pop cx ;cx=272Eh
pop ax ;discard xxxx
pop ax ;ax=0CD21h
inc sp ;discard xx
push cx ;push ".'"
push 7369h ;push "is"
push 685ah ;push "h"+xx
inc sp ;discard xx
push dx ;" "+xx
inc sp ;discard xx
push 735ah ;push "s"+xx
inc sp ;discard xx
push cx ;push "'"+xx
inc sp ;discard xx
push 7461h ;push "at"
push 6874h ;push "th"
push dx ;push " "+xx
inc sp ;discard xx
push 7475h ;push "ut"
push 425ah ;push "B"+xx
inc sp ;discard xx
push cx ;push "'"+xx
inc sp ;discard xx
push dx ;push ", "+xx
push 6469h ;push "id"
push 6173h ;push "sa"
push dx ;push " "+xx
inc sp ;discard xx
push 6568h ;push "he"
push 735ah ;push "s"+xx
inc sp ;discard xx
push dx ;push " "+xx
inc sp ;discard xx
push 646eh ;push "nd"
push 415ah ;push "A"+xx
inc sp ;discard xx
push sp
pop dx ;dx=sp
push ax
imul ax,[si+45h],5946h ;ah=09h
```
It works this way:
* moves the stack pointer to the end of the code, via POP AX (can't POP SP because it's not alphabetic);
* constructs the instruction to dispatch a DOS call (algorithmically because it's not alphabetic);
* constructs the non-alphabetic characters;
* places the string on the stack;
* places the dispatch instruction on the stack at the exact end of the code, so that execution flows directly to that instruction;
* constructs the instruction to print a string;
* displays the string and them promptly crashes. :-/ (A graceful exit would require more code)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~145~~ ~~121~~ 109 bytes
```
TnVYTOUXZxNJTZXTZZZXYTYxMNYTTMNNNYRYNNYNNNNYTXZMNNYxXRZZZXTYXRZZXZYxTRMRNXRMRMXNNYxYMRNTYxTRYNTZMYXRXXXTZJCXB
```
[Try it online!](https://tio.run/##FUy7CoBADPs33YRWOKIk3RQcXHRwub8/2yVv8n7HeV9j4NmFdWN0XxBERFBQNxdg7q6mBC8FRibqbLWCihnqaNacCcaqlQ6VyhGWKzJ/l5nTGD8 "05AB1E – Try It Online")
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal), 266 bytes
```
kAhkPkekieiJkakiiJkoLddCJkakPkeEiIdHiJkPkfJLCJkakhhLEEiJkoLddCJkakPkeEiIdHiJkahJkakiEiJkzkikeeiJkpkfkoJJLCJkoLddCJkpkPkeEiIiJkpkakoJJLCJkHkPkfJJLCJkzkeEiJkoLddCJkzkeEiJkPkfJLCJkahJkzkeEiJkpkPkeEiIiJkakPkeEiIdHiJkoLddCJkPkfJLCJkakiEiJkakPkeEiIdHiJkiSkohLiJkpkPkeEiIiJ
```
[Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=kAhkPkekieiJkakiiJkoLddCJkakPkeEiIdHiJkPkfJLCJkakhhLEEiJkoLddCJkakPkeEiIdHiJkahJkakiEiJkzkikeeiJkpkfkoJJLCJkoLddCJkpkPkeEiIiJkpkakoJJLCJkHkPkfJJLCJkzkeEiJkoLddCJkzkeEiJkPkfJLCJkahJkzkeEiJkpkPkeEiIiJkakPkeEiIdHiJkoLddCJkPkfJLCJkakiEiJkakPkeEiIdHiJkiSkohLiJkpkPkeEiIiJ&inputs=&header=&footer=)
A real nightmare. This was coded by hand.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 74 bytes
```
HdEz
iHdE isiiihiSisiUitiaihitiSitiuibu iUiSiHdC idiiiaisiSieihisiSidiniau
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=SGRFegppSGRFIGlzaWlpaGlTaXNpVWl0aWFpaGl0aVNpdGl1aWJ1IGlVaVNpSGRDIGlkaWlpYWlzaVNpZWloaXNpU2lkaW5pYXU)
] |
[Question]
[
The robbers thread can be found here: [The Mystery String Printer (Robbers)](https://codegolf.stackexchange.com/questions/60329/the-mystery-string-printer-robbers)
# Your challenge
* Write a program, function, or REPL script that prints a string to STDOUT.
* The robbers will try to create a program that prints the same string.
* If they successfully can create the program within 7 days, your submission is cracked.
* If nobody can create a program that prints the same string within 7 days, your submission is safe. You may choose to reveal your program, or leave it to challenge future robbers. However, if you don't reveal it, you can't get any points from your submission (don't put "safe" in your answer header if you choose to do this).
# Restrictions
* The program must be less than or equal to 128 bytes total (more on this later).
* If the program depends on the program name, or the name/contents of an external file, you must say that it does so, and include this in your total byte count.
* The printed string must be less than or equal to 2048 bytes.
* The printed string must consist of only printable ASCII characters (new lines can be included).
* The program must produce the same output every time that it is run.
* Built-in cryptographic primitives (includes any rng, encryption, decryption, and hash) aren't allowed.
* The program must not take input.
* No standard loopholes.
# Scoring
* If a submission is cracked before seven days, the submission earns 0 points.
* A safe submission of ≤128 characters earns 1 point.
* A safe submission of ≤64 characters earns 2 points. If it's less than or equal to 32 bytes, it earns 4 points, and so on.
* Each safe submission also earns an additional 3 point bonus (independent of the length).
* There is a tiny (1/2 point) penalty for every cracked after your first one.
* Note that the robber's solution has to be in the same range of program lengths.
* Each person may submit a maximum of 1 program per byte range per language (different versions and arbitrary substitutions of the same language don't count as separate languages). Example: you can post a 32 byte and a 64 byte pyth program, but you can't post a 128 byte program in both Java 7 and Java 8.
* The person with the highest point total wins.
## Submissions
Each submission must have the following pieces of information:
* The name of the language. All *new* robbers' solutions must be the same language.
* The range of the program size (this is the nearest power of two higher than the size of the program; for example, if your program is 25 bytes, this would be "≤32").
* The actual string to be printed out.
* If a submission is safe, put "safe" and the program length (to the nearest power of 2) in your header. If there are multiple numbers in your header, put the power of 2 last.
This stack snippet generates leaderboards and lists all of the open submissions. If there are any problems with the snippet, please leave a comment.
```
/* Configuration */
var QUESTION_ID = 60328; // Obtain this from the url
// It will be like http://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page
var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";
var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk";
var OVERRIDE_USER = 167084; // This should be the user ID of the challenge author.
var SECONDSINDAY = 86400;
var SAFECUTOFFDAYS = 7;
var SORTBYTIME = true;
var SUBTRACTCRACKEDPOINTS = true;
var EXPIREDTIME = 1446336000;
/* App */
var answers = [],
answers_hash, answer_ids, answer_page = 1,
more_answers = true,
comment_page;
function answersUrl(index) {
return "//api.stackexchange.com/2.2/questions/" + QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER;
}
function commentUrl(index, answers) {
return "//api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER;
}
function getAnswers() {
jQuery.ajax({
url: answersUrl(answer_page++),
method: "get",
dataType: "jsonp",
crossDomain: true,
success: function(data) {
answers.push.apply(answers, data.items);
answers_hash = [];
answer_ids = [];
data.items.forEach(function(a) {
a.comments = [];
var id = +a.share_link.match(/\d+/);
answer_ids.push(id);
answers_hash[id] = a;
});
if (!data.has_more) more_answers = false;
comment_page = 1;
getComments();
}
});
}
function getComments() {
jQuery.ajax({
url: commentUrl(comment_page++, answer_ids),
method: "get",
dataType: "jsonp",
crossDomain: true,
success: function(data) {
data.items.forEach(function(c) {
answers_hash[c.post_id].comments.push(c);
});
if (data.has_more) getComments();
else if (more_answers) getAnswers();
else process();
}
});
}
getAnswers();
var SAFE_REG = /<h\d>.*?[sS][aA][fF][eE].*<\/\h\d>/;
var POINTS_REG = /(?:<=|≤|<=)\s?(?:<\/?strong>)?\s?(\d+)/
var POINTS_REG_ALT = /<h\d>.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/;
var CRACKED_HEADER_REG = /<h\d>.*[Cc][Rr][Aa][Cc][Kk][Ee][Dd].*<\/h\d>/;
var CRACKED_COMMENT_REG = /(.*[Cc][Rr][Aa][Cc][Kk][Ee][Dd].*<a href=.*)|(.*<a href=.*[Cc][Rr][Aa][Cc][Kk][Ee][Dd].*)/
var OVERRIDE_REG = /^Override\s*header:\s*/i;
var LANGUAGE_REG = /<h\d>\s*(.+?),.*<\/h\d>/;
var LANGUAGE_REG_ALT = /<h\d>\s*(<a href=.+<\/a>).*<\/h\d>/
var LANGUAGE_REG_ALT_2 = /<h\d>\s*(.+?)\s.*<\/h\d>/;
var LANGUAGE_REG_ALT_3 = /<h\d>(.+?)<\/h\d>/;
function getAuthorName(a) {
return a.owner.display_name;
}
function process() {
var valid = [];
var open = [];
answers.forEach(function(a) {
var body = a.body;
var cracked = false;
a.comments.forEach(function(c) {
var was_safe = (c.creation_date + (SECONDSINDAY * SAFECUTOFFDAYS) > a.creation_date);
if (CRACKED_COMMENT_REG.test(c.body) && !was_safe)
cracked = true;
});
if (CRACKED_HEADER_REG.test(body)) cracked = true;
// if (SUBTRACTCRACKEDPOINTS||!cracked) {
var createDate = a.creation_date;
var currentDate = Date.now() / 1000;
var timeToSafe = (createDate + (SECONDSINDAY * SAFECUTOFFDAYS) - currentDate) / SECONDSINDAY;
var SafeTimeStr = (timeToSafe > 2) ? (Math.floor(timeToSafe) + " Days") :
(timeToSafe > 1) ? ("1 Day") :
(timeToSafe > (2 / 24)) ? (Math.floor(timeToSafe * 24) + " Hours") :
(timeToSafe > (1 / 24)) ? ("1 Hour") :
"<1 Hour";
var expired = createDate > (EXPIREDTIME);
var safe = timeToSafe < 0;
var points = body.match(POINTS_REG);
if (!points) points = body.match(POINTS_REG_ALT);
safe = safe && !cracked
isOpen = !(cracked || safe);
if (points) {
var length = parseInt(points[1]);
var safepoints = 0;
if (length <= 4) safepoints = 32;
else if (length <= 8) safepoints = 16;
else if (length <= 16) safepoints = 8;
else if (length <= 32) safepoints = 4;
else if (length <= 64) safepoints = 2;
else if (length <= 128) safepoints = 1;
valid.push({
user: getAuthorName(a),
numberOfSubmissions: (safe && !expired) ? 1 : 0,
points: (safe && !expired) ? safepoints : 0,
open: (isOpen && !expired) ? 1 : 0,
cracked: (cracked && !expired) ? 1 : 0,
expired: (expired) ? 1 : 0
});
}
if ((isOpen || expired) && points) {
var language = body.match(LANGUAGE_REG);
if (!language) language = body.match(LANGUAGE_REG_ALT);
if (!language) language = body.match(LANGUAGE_REG_ALT_2);
if (!language) language = body.match(LANGUAGE_REG_ALT_3);
open.push({
user: getAuthorName(a),
length: points ? points[1] : "???",
language: language ? language[1] : "???",
link: a.share_link,
timeToSafe: timeToSafe,
timeStr: (expired) ? "Challenge closed" : SafeTimeStr
});
}
// }
});
if (SORTBYTIME) {
open.sort(function(a, b) {
return a.timeToSafe - b.timeToSafe;
});
} else {
open.sort(function(a, b) {
var r1 = parseInt(a.length);
var r2 = parseInt(b.length);
if (r1 && r2) return r1 - r2;
else if (r1) return r2;
else if (r2) return r1;
else return 0;
});
}
var pointTotals = [];
valid.forEach(function(a) {
var index = -1;
var author = a.user;
pointTotals.forEach(function(p) {
if (p.user == author) index = pointTotals.indexOf(p);
});
if (index == -1) pointTotals.push(a);
else {
pointTotals[index].points += a.points;
pointTotals[index].numberOfSubmissions += a.numberOfSubmissions;
pointTotals[index].cracked += a.cracked;
pointTotals[index].expired += a.expired;
pointTotals[index].open += a.open;
if (SUBTRACTCRACKEDPOINTS && a.cracked && pointTotals[index].cracked > 1) pointTotals[index].points -= .5;
}
});
pointTotals.forEach(function(a) {
a.points += (a.numberOfSubmissions) ? ((a.numberOfSubmissions) * 3) : 0;
});
pointTotals.sort(function(a, b) {
if (a.points != b.points)
return b.points - a.points;
else if (a.numberOfSubmissions != b.numberOfSubmissions)
return b.numberOfSubmissions - a.numberOfSubmissions;
else if (a.open != b.open)
return b.open - a.open;
else if (a.cracked != b.cracked)
return a.cracked - b.cracked;
else return 0;
});
pointTotals.forEach(function(a) {
var answer = jQuery("#answer-template").html();
answer = answer
.replace("{{NAME}}", a.user)
.replace("{{SAFE}}", a.numberOfSubmissions)
.replace("{{OPEN}}", a.open)
.replace("{{CLOSED}}", a.expired)
.replace("{{CRACKED}}", a.cracked)
.replace("{{POINTS}}", a.points);
answer = jQuery(answer);
jQuery("#answers").append(answer);
});
open.forEach(function(a) {
var answer = jQuery("#open-template").html();
answer = answer
.replace("{{NAME}}", a.user)
.replace("{{LENGTH}}", a.length)
.replace("{{LANGUAGE}}", a.language)
.replace("{{TIME}}", a.timeStr)
.replace("{{LINK}}", a.link);
answer = jQuery(answer);
jQuery("#opensubs").append(answer);
});
}
```
```
body {
text-align: left !important
}
#answer-list {
padding: 10px;
width: 350px;
float: left;
}
#open-list {
padding: 10px;
width: 470px;
float: left;
}
table thead {
font-weight: bold;
vertical-align: top;
}
table td {
padding: 5px;
}
```
```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">
<div id="answer-list">
<h2>Leaderboard</h2>
<table class="answer-list">
<thead>
<tr>
<td>Author</td>
<td>Safe</td>
<td>Open</td>
<td>Cracked</td>
<td>Late Entry</td>
<td>Score</td>
</tr>
</thead>
<tbody id="answers">
</tbody>
</table>
</div>
<div id="open-list">
<h2>Open submissions</h2>
<table class="open-list">
<thead>
<tr>
<td>Author</td>
<td>Length</td>
<td>Language</td>
<td>Time Remaining</td>
<td>Link (open in new tab)</td>
</tr>
</thead>
<tbody id="opensubs">
</tbody>
</table>
</div>
<table style="display: none">
<tbody id="answer-template">
<tr>
<td>{{NAME}}</td>
<td>{{SAFE}}</td>
<td>{{OPEN}}</td>
<td>{{CRACKED}}</td>
<td>{{CLOSED}}</td>
<td>{{POINTS}}</td>
</tr>
</tbody>
</table>
<table style="display: none">
<tbody id="open-template">
<tr>
<td>{{NAME}}</td>
<td>{{LENGTH}}</td>
<td>{{LANGUAGE}}</td>
<td>{{TIME}}</td>
<td><a target="_parent" href="{{LINK}}">Link</a>
</td>
</tr>
</tbody>
</table>
```
Use the following formats for entries:
```
Language, (any text with the program size as the last number)
=
```
or
```
Language
=
Length <= 16
```
Note that the snippet will only put the first word in the header as the language if it doesn't detect a comma.
For safe submissions, put safe in your header. The snippet will automatically put your program in the "safe" column if the time is expired, so this is more to tell any robbers that your program is safe.
For cracked submissions, put cracked in your header.
The program should also be able to recognize if a comment says "cracked" and has a link; however, this is not guaranteed.
Tiebreaking order: Points -> # of Safe submissions -> Least amount of cracked submissions.
Note that the snippet sorts by open submissions before least cracked, but open submissions will not be counted at the end of the contest.
**This challenge is now closed.**
**Most points overall winner: Dennis**
**Most safe submissions: DLosc**
(Note that the number of safe submissions doesn't translate to a point amount, as the size of the programs are considered in calculating the score).
[Answer]
# Pyth, Safe, Range ≤ 8
```
['ashva', 'cxedo', 'ecckc', 'hhzsq', 'jmwze', 'lrths', 'nwrog', 'pbowu', 'rgldi', 'uljlw', 'wpgsk', 'yuday'
```
The code:
>
> `%^T6`^G5`
>
>
>
Explanation:
>
> To clarify how this works: I generated all possible 5 character strings of lowercase letters (`^G5`). Then, I generated the string representation of this list: (``^G5`). Finally, I took every 1,000,000th character of that list (`%^T6`).
>
> The result is something which looks like a list of strings, but is suspiciously missing its end bracket.
>
>
>
[Answer]
# VBA , [Safe]
Range <= 128 bytes
Hint for where to output
>
> Ran in Excel 2007, output was to Debug.print. Its VBA good luck getting anything under 128 bytes to run.
>
>
>
Output 255 bytes
```
This array is fixed or temporarily locked THIS ARRAY IS FIXED OR TEMPORARILY LOCKED this array is fixed or temporarily locked This Array Is Fixed Or Temporarily Locked I n v a l i d p r o c e d u r e c a l l o r a r g u m e n t ?????????????????
```
### Solution
>
> Well I hope someone had fun trying to crack this one. I can say that this is some of the worst error-handling I have ever done and feel bad for how bad this code is.
>
>
>
### Code
>
>
> ```
> Sub e()
> On Error Resume Next
> Err.Raise 10
> For i = 0 To 128
> b = b & " " & StrConv(Err.Description, i)
> Next
> Debug.Print b
> End Sub'
> ```
>
>
>
>
### Explained
>
> First the code starts with one of the Major sins of VBA. `On Error Resume next`.
>
> Once we have committed that horrid act we go ahead and just throw and error. this is the `This array is fixed or temporarily locked` Error that we will soon see in the output.
>
>
>
> The next is the loop. We loop 128 times trying to Convert the Error Description, But the only valid inputs for `i are 1,2,3,64,128`. Because of this the first 4 loops print the Error with Various Formats. Then when `i = 4` the code throws a new Error `Invalid call` Then that loops and nothing is assigned to `b` because the `strconv` function errors out each time.
>
>
>
> This is where any normal program should have stopped, But because we have the `On Error Resume Next` every error is ignored and the code continues unfazed by the poor error-handling
>
>
>
> Now we hit `i=32` and we add the new error to `b` converted to Unicode and then continue looping until `i = 128` at which point we convert our error FROM Unicode which results in the `?????????????????` string being added to `b`
>
>
>
> Finally Print out the mess of Errors we have concatenated together
>
>
>
[Answer]
# Mathematica, safe, range ≤ 64
Output:
```
CGTAGGCCCATTTTGTGTGAATTGCGGTGCAGCGAGCGATATGTTGTCTGGGCACGGACGCAGAGTTAGGGTAGCTGGTG
```
Source:
```
Print@@Characters["GATC"][[1+First@RealDigits[Pi,4,80]]]
```
[Answer]
# ngn APL (safe)
```
0.675640430319848J0.8376870144941628
```
Range **≤ 8**
### Solution
```
*3○⍟⍣=42
```
[Try it online.](http://ngn.github.io/apl/web/#code=*3%u25CB%u235F%u2363%3D42)
### How it works
* `⍟⍣=42` applies natural logarithm (`⍟`) repeatedly to **42** until a fixed point is reached (`⍣=`), yielding **0.31813150520476413J1.3372357014306895**.
The initial value doesn't really matter here, as long as it's neither **1** nor **0**.
* `3○` applies tangent to its right argument, yielding **0.07343765001657206J0.8920713530605129**.
* `*` applies the natural exponential function to its right argument, yielding the desired output.
[Answer]
# Pyth, [cracked by Sp3000](https://codegolf.stackexchange.com/a/60351)
```
1234465889612101271616181215168242024142718209323236243032163621242510
```
Range **≤ 8**
[Answer]
## ><> (Safe)
Tested on the online and official interpreters.
Range: <= 16
String: `4621430504113348052246441337820019217490490`
This is pretty 1337, huh?
## Explanation:
Here's the source code (15 bytes):
```
f1-:0(?;::0g*n!
```
`f` pushes 15 (our counter) onto the stack (this is skipped by the `!` at the end so as not to push more than one counter)
`1-` subtracts 1 from the counter
`:0(?;` The frowny face tests if the counter is less than 0, the rest ends the program if it is
`::` Duplicates the counter twice
`0g` Grabs the character at the point `(c,0)` in the source code where `c` is the counter
`*` Multiplies the second duplicate of the counter by the ASCII representation of the character previously grabbed
`n` Prints the result.
So, split up, the output is `[462, 1430, 504, 1133, 480, 522, 464, 413, 378, 200, 192, 174, 90, 49, 0]`. This corresponds to the ASCII interpretation of the code in reverse multiplied by the numbers 14 to 0 (i.e. `[!*14, n*13, ... f*0]`).
Probably the hardest part about cracking this would be figuring out how to split up the numbers correctly, but if you get the right ones it's just a matter of trying things until you get something that works.
[Answer]
# Python, <=16 ([cracked by kennytm](https://codegolf.stackexchange.com/a/61198/6828))
```
[[[22111101102001]]]
```
This was produced via REPL (running a command in Python shell).
While I'm editing this, I'll also summarize the comments for future spoiler-free robbers: this doesn't work in all Pythons. It does work in a build of Python 2.7 where `sys.maxint = 9223372036854775807`.
[Answer]
# Matlab, ≤16. [Cracked by Wauzl](https://codegolf.stackexchange.com/a/60482/46115)
Range **≤16**.
This works in **Octave** too.
The printed string is as follows:
```
ans =
0 0 0 0 0 0 0 0 0
0 0 0 0 9 4 0 0 0
0 0 0 0 32 18 0 0 0
0 0 0 9 1 0 3 0 0
0 0 7 0 0 2 10 0 0
0 0 3 0 2 2 3 0 0
0 0 0 19 63 22 1 0 0
0 0 0 4 13 4 0 0 0
0 0 0 0 0 0 0 0 0
```
[Answer]
# Perl (safe)
```
84884488488444224424428844884884884488488444224424428844884884884488488444224424424422442442884488488488448848844422442442884488488488448848844422442442442244244244224424422211221221221122122144224424424422442442221122122144224424424422442442221122122144224424424422442442221122122122112212214422442442442244244222112212214422442442442244244222112212218844884884884488488444224424424422442442884488488488448848844422442442884488488488448848844422442442884488488488448848844422442442442244244288448848848844884884442244244288448848848844884884442244244244224424424422442442221122122122112212214422442442442244244222112212214422442442442244244222112212218844884884884488488444224424424422442442884488488488448848844422442442884488488488448848844422442442884488488488448848844422442442442244244288448848848844884884442244244288448848848844884884442244244244224424424422442442221122122122112212214422442442442244244222112212214422442442442244244222112212212212211222442442244244244224412212211222442442244244244224412212211221221221122244244224424424422442442442244488488448848848844882442442244488488448848848844882442442244244244224448848844884884884488244244224448848844884884884488244244224448848844884884884488244244224424424422444884884488488488448812212211222442442244244244224412212211222442442244244244224412212211221221221122244244224424424422442442442244488488448848848844882442442244488488448848848844882442442244244244224448848844884884884488244244224448848844884884884488244244224448848844884884884488244244224424424422444884884488488488448812212211222442442244244244224412212211222442442244244244224412212211221221221122244244224424424422441221221122244244224424424422441221221122244244224424424422441221221122122122112224424422442442442244244244224448848844884884884488244244224448848844884884884488244244224424424422444884884488488488448824424422444884884488488488448824424422444884884488488488448824424422442442442244488488448848848844882442442244488488448848848844882442442244488488448
```
Range **≤ 32**
### Solution
```
print 2**y/124589//for-951..1048
```
[Try it online.](http://ideone.com/yhIHaS)
### How it works
* `for-951..1048` executes the preceding command for each integer in this range, saving it in the implicit variable.
* `y/124589//` performs transliteration, eliminating the specified digits from the implicit variable.
`y///` will return the number of eliminations, i.e., the number of occurrences of those digits in the implicit variable.
* `print 2**` prints **2** to the power of eliminations (**1**, **2**, **4** or **8**).
[Answer]
# Javascript (console), <= 32 ([cracked by insertusernamehere](https://codegolf.stackexchange.com/a/61149/6828))
```
"a,a,0,a,b,a,a,b,a,a,4,a,b,a,a,a,a,6,a,b,a,a"
```
Tested in Chrome and Firefox web consoles. That's a 43 character string.
My intended solution was a bit more elaborate than the linked one (curse you, ES6!).
>
> 'a,b,a,a'.replace(/(a)/g,Array)
>
>
>
Explanation:
>
> When you call `replace` with a Regular Expression with the `/g` flag and a function, it replaces everything matching the regex with the result of calling the function with these arguments: The matched string, every capture group in the matched string, the index the matched string has in the whole string, and the whole string. In this case, that'll be "a", "a", 0 or 4 or 6, and "a,b,a,a". All of these arguments are passed into the Array constructor, which simply creates an array of everything passed in. Then `replace` converts that to a string, e.g. "a,a,0,a,b,a,a" and replaces the "a" character with it.
>
>
>
[Answer]
## [Snowman 1.0.2](https://github.com/KeyboardFire/snowman-lang/releases/tag/v1.0.2-beta)
Range ≤32.
```
110110111011011001111100111111111101111110101000101000100001100001100011100011101110110111011011111011111011101011101111101111110111110111111011110101111010111100101100101001111001111111011111011010111010111000000100000011111001111100
```
The solution is:
```
"mO~(!#]/.}{k2'=+@|":2nBspsP;aE
```
[Answer]
# [><>](https://esolangs.org/wiki/Fish), ≤ 8 [[cracked](https://codegolf.stackexchange.com/a/60892/21487)]
```
oooooooooooo
```
That's a total of 12 `o`s. The program halts without error, and works with both the official interpreter and the [online interpreter](http://fishlanguage.com/playground).
[Answer]
# TI-BASIC, ≤4 bytes, [cracked by Reto Koradi](https://codegolf.stackexchange.com/a/61087/39328)
This took 5 days 23 hours to crack. So close...
Output (10 bytes):
```
.495382547
```
Program:
```
³√(tanh(7°
```
Since it's basically impossible for someone to guess this, my goal in designing this program was to make brute force the only possible approach.
To do this, I prevented the output, or the output with one of [these inverse functions](http://tibasicdev.wikidot.com/one-byte-tokens) applied, from showing up on the ISC. ISC doesn't have hyperbolic tangent, and I figured that no similar tool would have `tanh(7°`.
To add some security against brute force, I used degree-to-radian conversion, a slightly obscure feature, but it wasn't enough.
[Answer]
# CJam, ≤ 8 [safe]
```
379005901358552706072646818049622056
```
I don't like long numbers so here's a short one. Feel free to fiddle both offline and [online](http://cjam.aditsu.net/).
Since I find number-only submissions pretty boring, I'll be slowly putting out a few hints to compensate.
>
> **Hint 1:** The program ends with a single number of the stack, and none of the `A-K` variables are used.
>
>
> **Hint 2:** The number encodes information that is completely retrievable if you reverse the process (i.e. no information has been lost).
>
>
>
> **Hint 3:** The "information" from hint 2 is a single string which is created after the first four chars.
>
>
>
---
## Solution
The program was
```
0W#sWcib
```
`0W#` is `0^-1`, which instead of erroring out gives `Infinity`. `s` then casts this to a string (note that ``` gives `1d0/` instead).
For the other half, `Wc` converts -1 to a char, which becomes code point 65535 due to the wraparound for chars (see [this tip](https://codegolf.stackexchange.com/a/54767/21487)). `i` then converts the char back to an int, i.e. 65535.
Finally, `b` converts the string `Infinity` to base 65535 to give the above number.
[Answer]
# Python, <= 32 ([cracked](https://codegolf.stackexchange.com/a/60847/16766) by Egor Skriptunoff)
Output is 1832 bytes, including newlines:
```
163
485
559
1649
2707
8117
8415
24929
41891
124133
142639
423793
694675
2075317
2162655
6357089
10682531
31785445
36635183
108070513
177408659
531963829
551493855
1633771873
2745410467
8135173349
9347869999
27774121841
45526653331
136007297717
141733920735
416611827809
700079669411
2083059139045
2400886719023
7082401072753
11626476472979
34862249549749
36142149804255
107069239746913
179920475038627
533147175478501
612629840276783
1820177075697521
2983606407043475
8913418645908149
9288532499693535
27303489359118433
45881121294188707
136517446795592165
157346912904610351
464159319105013361
761964388609624723
2284767248741900213
2368648071721459935
7016996765293437281
11791448172606497699
34940303480791033061
40148795925132553519
119288945009988433777
195535487181321247123
584146895667469134517
608742554432415203295
1789334175149826506849
3006819284014656913571
8946670875749132534245
10311729937203639353903
30418680977547050616433
49935336207531756227219
149732221646300430475189
155229351380265876857055
459858883013505412260193
772752555991766826787747
2289849682101787770873061
2631225127929856733097263
7817601011229592008423281
12814491939404182769539475
38282841570818685533137589
39893943304728330352263135
117267593836794179779362913
197057915416468570144702627
586337969183970898896814565
675799844894514912336740911
1993549095225501056249169521
3272612129033008707863251603
9813000610033591312052461493
10173266001408484771580813535
30137771616056104203296268641
50643884262032422527188575139
150067460764265635881358255333
172437765505860562200296238383
512342117472953771456036566897
839818522529453467650609486227
2508891813142320379359897758389
2614529362361980586296269078495
7685131765672974922140201517153
12914190492831906312462400487587
38425658828364874610701007585765
44288542855785494654395594310191
```
[Answer]
# CJam ([cracked](https://codegolf.stackexchange.com/questions/60329/the-mystery-string-printer-robbers/61031#61031) by Dennis)
Length <= 4
```
1737589973457545958193355601
```
I don't give this a very high chance of survival, but I wanted to try a 4 byte solution anyway.
My code was exactly what Dennis reverse engineered:
```
H Push 17
J Push 19.
K Push 20.
# Power.
```
CJam then prints all of the stack content, concatenated. So the output was `17` concatenated with `19^20`.
[Answer]
# [Pip](http://github.com/dloscutoff/pip), <= 16 (safe)
This is my final Pip submission, I promise. :)
```
0123456789
0 9
0 9
0 9
0 9
0 9
0 9
0 9
0 9
0 9
0 9
0123456789
```
I'll be surprised if anybody gets this down to 16 bytes--it took me quite a few tries to make it fit. (Take that as a challenge if you like!)
---
Answer:
```
Px:J,tLtP09JsX8x
```
This code makes use of the predefined variables `t` = 10 and `s` = space.
```
,t Range(10)
J Join into string: "0123456789"
Px: Assign to x and print
Lt Loop 10 times:
09 This is a numeric literal, but it can act like a string "09" because
strings and numbers are the same data type in Pip
sX8 8 spaces
J Join left arg on right arg: "0 9"
P Print
x Last expression in a program is autoprinted: "0123456789"
```
[Answer]
## Ruby, [cracked by kennytm](https://codegolf.stackexchange.com/a/60409/3808)
Range: ≤64.
```
#<MatchData "@@" 1:"@" 2:"@">
"#<ArgumentError: unknown command \"\\x00\">\nu#<ArgumentError: unknown command \"\\x00\">\nn#<ArgumentError: unknown command \"\\x00\">\nk#<ArgumentError: unknown command \"\\x00\">\nn#<ArgumentError: unknown command \"\\x00\">\no#<ArgumentError: unknown command \"\\x00\">\nw#<ArgumentError: unknown command \"\\x00\">\nn#<ArgumentError: unknown command \"\\x00\">\n #<ArgumentError: unknown command \"\\x00\">\nc#<ArgumentError: unknown command \"\\x00\">\no#<ArgumentError: unknown command \"\\x00\">\nm#<ArgumentError: unknown command \"\\x00\">\nm#<ArgumentError: unknown command \"\\x00\">\na#<ArgumentError: unknown command \"\\x00\">\nn#<ArgumentError: unknown command \"\\x00\">\nd#<ArgumentError: unknown command \"\\x00\">\n #<ArgumentError: unknown command \"\\x00\">\n\"#<ArgumentError: unknown command \"\\x00\">\n\\#<ArgumentError: unknown command \"\\x00\">\nx#<ArgumentError: unknown command \"\\x00\">\n0#<ArgumentError: unknown command \"\\x00\">\n0#<ArgumentError: unknown command \"\\x00\">\n\"#<ArgumentError: unknown command \"\\x00\">\n@#<ArgumentError: unknown command \"\\x00\">\n@#<ArgumentError: unknown command \"\\x00\">\n"
```
(And yes, all output is to STDOUT.)
Intended solution:
```
test'@@'=~/(.)(.)/ rescue p"#{$!}#{p$~}".gsub(//,$!.inspect+$/)
```
[Answer]
# TI-BASIC ([cracked](https://codegolf.stackexchange.com/a/60427/39328) by [Thomas Kwa](https://codegolf.stackexchange.com/users/39328/thomas-kwa))
TI-89 variant
Range: ≤8
Output length: 460
```
1257286521829809852522432602192237043962420111587517182185282167859393833998435970616540717415898427784984473447990617367563433948484506876830127174437083005141539040356040105854054119132085436114190914221684704295353373344661986220406465038338295680627940567692710933178603763184382721719223039895582218462276317539764129360057392146874652124017927952151332902204578729865820715723543552685154087469056000000000000000000000000000000000000000000000000000000000
```
I don't think you can use RIES on this but I doubt it will survive 7 days anyway. Oh well.
Code:
```
236!
```
[Answer]
# MATLAB, [cracked by Tom Carpenter](https://codegolf.stackexchange.com/a/60436/42295)
Range <= 16
```
ans =
5760 22320
13920 53940
```
[Answer]
# Mathematica, [Cracked by Sp3000](https://codegolf.stackexchange.com/a/60581/9288)
Range: <= 32
```
808017424794512875886459904961710757005754368000000000
```
[Answer]
# **[Thue](https://en.wikipedia.org/wiki/Thue_%28programming_language%29)** - <= 64 Bytes, cracked by histocrat.
`555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555`
That's 2016 5s; by the way.
[Answer]
# Lua, ≤ 4 ([cracked](https://codegolf.stackexchange.com/a/61094/7313) by feersum)
Output:
```
9.5367431640625e-07
```
You need to find a string for Lua REPL which results in "1/M" constant.
It is simple, but not very trivial.
[Answer]
# CJam, ≤8 (safe)
```
\"3.341594\43181\
```
Original code:
```
P`_`_`er
```
That is, to start with `3.141592653589793` and replace each character in `"3.141592653589793"` with the corresponding character in `"\"3.141592653589793\""`. With the duplicates removed, it's actually replacing `".123456789` with `""35\.49831`.
[Answer]
## Python 2 (safe 16)
```
(1.06779146638-0.024105112278j)
```
Range ≤ 16. In case the version matters (for printing precision?), I'm using [ideone](https://ideone.com/).
I don't see a way of guessing the code without computer search, but you all have impressed me before.
---
Answer:
```
print.7j**8j**2j
```
[Answer]
# Pyth, [Cracked by Sp3000](https://codegolf.stackexchange.com/a/60442/21487)
Range: <= 4
**New, valid answer**
I'm sure this can be brute forced with such a small program size, but lets see.
```
3582409715080948947248394822102989658717877178836918915255342812682764990143662880
```
[Answer]
# JavaScript ES6, ≤128 bytes - [Cracked](https://codegolf.stackexchange.com/a/60666/31957)
Output (1124 bytes):
```
00371223425266831021221451701972262572903253624014424855305776266777307858429019621025109011571226129713701445152216011682176518501937202621172210230524022501260227052810291730263137325033653482360137223845397040974226435744904625476249015042518553305477562657775930608562426401656267256890705772267397757077457922810182828465865088379026921794109605980210001102021040510610108171102611237114501166511882121011232212545127701299713226134571369013925141621440114642148851513015377156261587716130163851664216901171621742517690179571822618497187701904519322196011988220165204502073721026213172161021905222022250122802231052341023717240262433724650249652528225601259222624526570268972722627557278902822528562289012924229585299303027730626309773133031685320423240132762331253349033857342263459734970353453572236101364823686537250376373802638417388103920539602400014040240805412104161742026424374285043265436824410144522449454537045797462264665747090475254796248401488424928549730501775062651077515305198552442529015336253825542905475755226556975617056645571225760158082585655905059537600266051761010615056200262501630026350564010
```
Have fun, and good luck!
Original code:
```
new Array(254) .fill(0).map((x,s)=>s*s-s/((5-s)||3)).map(Math.floor).join``
```
[Answer]
# TI-BASIC (cracked by Thomas Kwa)
Range: <= 2
String: `-10`
Code: `Xmin`
There's just no fooling this guy...
[Answer]
# AppleScript, ≤ 2 Bytes [Cracked](https://codegolf.stackexchange.com/a/60995/11006)
"Brute forced... *grumble grumble*..."
What's this? A short AppleScript answer? :o
```
missing value
```
(yes, this DOES print to stdout)
[Answer]
# [><> (Fish)](https://esolangs.org/wiki/Fish), [Cracked](https://codegolf.stackexchange.com/a/61065/7311) by Sp3000
Length <= 8
```
>>>>>>>>>>>>>>>>>>>>>>>
```
The output is 23 `>`'s and the program produces no error.
] |
[Question]
[
### Intro
Every year, [Dyalog Ltd.](http://www.dyalog.com/) holds a student competition. [The challenge there](http://www.dyalog.com/student-competition.htm) is to write *good* APL code. This is a language agnostic [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") edition of this year's eighth problem.
I have explicit permission to post this challenge here from the original author of the competition. Feel free to verify by following the [provided link](http://www.dyalog.com/student-competition.htm) and contacting the author.
### Problem
Given a Boolean\* list, "turn off" all the Truthies after the first Truthy.
No Truthies? No problem! Just return the list unmodified.
### Examples
```
[falsy,truthy,falsy,truthy,falsy,falsy,truthy] → [falsy,truthy,falsy,falsy,falsy,falsy,falsy]
[] → []
[falsy,falsy,falsy,falsy] → [falsy,falsy,falsy,falsy]
```
---
\* All your truthies must be identical, and all your falsies must be identical. This includes output.
[Answer]
# [Python 2](https://docs.python.org/2/), 35 bytes
```
while 1:b=input();print b;True&=b<1
```
[Try it online!](https://tio.run/nexus/python2#@1@ekZmTqmBolWSbmVdQWqKhaV1QlJlXopBkHVJUmqpmm2Rj@P@/W2JOcSoXSIALg4kkAAA "Python 2 – TIO Nexus") Input and output are lines of True/False.
Based on [Dennis's solution](https://codegolf.stackexchange.com/a/119491/20260). Redefines the variable `True` to be `False` after a `True` input is encountered. That way, any further inputs of `True` will evaluate to `False` and be printed as such. Python 3 no longer allows `True` and `False` to be redefined, so this answer uses Python 2.
The redefinition is `True&=b<1`, i.e. `True = True & (b<1)`. When the input `b` is `True`, then `(b<1)` is False (since `True==1`), so `True` becomes `False`. See [Kevin Cruijssen's answer](https://codegolf.stackexchange.com/a/203149/20260) for a shorter way to handle this redefinition.
[Answer]
# [APL](https://www.dyalog.com/), 2 bytes
```
<\
```
Evaluates to the function "scan using less-than".
[Try it online!](https://tio.run/nexus/apl-dyalog-classic#@5@m8KhtgoJNzP9HfVPBzDQFAwVDIASS/wE "APL (Dyalog Classic) – TIO Nexus")
## Explanation
In APL, the operator `\` (scan) reduces each nonempty prefix of an array from the right using the provided function.
For example, given the array `0 1 0`, it computes `0` (prefix of length 1), `0<1` (prefix of length 2) and `0<(1<0)` (prefix of length 2) and puts the results into a new array; the parentheses associate to the right.
Reducing by `<` from the right results in `1` exactly when the last element of the array is `1` and the rest are `0`, so the prefix corresponding to the leftmost `1` is reduced to `1` and the others to `0`.
[Answer]
# [Aceto](https://github.com/L3viathan/aceto), ~~19~~ 17 bytes
### New version (17 bytes):
This new version takes the characters one at a time and is best executed with the `-F` option. It works similar, but not identical to the previous solution:
```
>,
Op0
p|1u
,ip^
```
---
### Old answer (19 bytes):
```
|p1u
iOp<
|!`X
rd!r
```
This is the first Aceto answer that highlights what it can do relatively well, I would say. The "lists" are input streams, with one input per line, "1" for true, and "0" for false, with an empty string signifying the end of the list.
![code flow illustration](https://i.stack.imgur.com/xmiLb.png)
Aceto programs run on a Hilbert curve, starting on the bottom left, and ending on the bottom right. First, we `r`ead a string, `d`uplicate, and negate (`!`) it, turning empty strings into True, everything else into False. Then there's a conditional horizontal mirror (`|`): If the top element on the stack is truthy, mirror horizontally. This happens when the string was empty. If we do the mirroring, we land on the `X`, which kills the interpreter.
Otherwise, we convert the remaining copy on the stack to an `i`nteger and do another conditional horizontal mirror: This time, because 1 is truthy and 0 is falsy, we mirror if we see the (first) true value. If we don't mirror (so we saw a 0) we `p`rint what's on the stack (since the stack is empty, a zero) and jump to the `O`rigin of the curve, where we started, starting the whole process again.
Otherwise, when we saw a 1, we mirror and land on the `u`, which reverses the direction we move on the Hilbert curve. `1p` prints a 1, and now we go on the same `O` we would have gone if we had seen a 0, but since we're in "reversed mode", our origin is at the bottom *right*, so we jump there.
Now we `r`ead another string, and negate it. If the string was empty, and therefore the top stack element is truthy, ``` will *not* escape the next command (`X`), making us quit.
Otherwise (if the string wasn't empty), we *do* escape the `X` and ignore it. In that case, we go to the left (`<`), `p`rint 0 (because the stack is empty), and jump back to the `O`rigin.
[Answer]
# Java8, ~~24~~ 19 Bytes
```
Long::highestOneBit
```
Hope this is legal; I got the impression the input / output doesn't have to evaluate as true/false in the language. Takes a long as input and gives one as output, with ones being true and zeroes being false in the binary representation. For example, binary 00101 is 5 and would return binary 00100 which is 4.
Five bytes thanks to @puhlen
[Answer]
# [Python 2](https://docs.python.org/2/), 33 bytes
```
while 1:b=input();print b;True^=b
```
Port of [@xnor's Python answer](https://codegolf.stackexchange.com/a/119503/52210), minus 2 bytes. Normally I would just suggest it as a golf in the comments, but since [*@xnor* has specifically stated we can outgolf any of his answers for a bounty](https://codegolf.meta.stackexchange.com/a/18334/52210), here it is as a separated answer.
[Try it online.](https://tio.run/##K6gsycjPM/r/vzwjMydVwdAqyTYzr6C0REPTuqAoM69EIck6pKg0Nc426f9/t8Sc4lQuEBdCIPEhTAwBhFp8GgA)
The difference? `True&=b<1` has been changed to `True^=b`.
**Why does this work?**
First we get some potential `False` inputs (`b=input();`). Each of those will be printed as is (`print b;`). And the `True^False` will remain `True`, so 'variable' `True` remains truthy.
Then we encounter the first `True` input, which will also be printed. After that, the `True^True` will evaluate to `False`, so the 'variable' `True` is from now on falsey.
After that it doesn't matter what our input is anymore, since `True` is redefined as falsey. So the `print b;` will always print `False` at this point. And in addition, the `True^=b` can now only be `False^False`, so 'variable' `True` will remain falsey.
[Answer]
## [Retina](https://github.com/m-ender/retina), 6 bytes
```
1>`1
0
```
[Try it online!](https://tio.run/nexus/retina#U9VwT/hvaJdgyGXw/7@BIRAaGHJxGQABlyEIAAA "Retina – TIO Nexus")
Input is a list of `0`s (for False) and `1`s (for True).
Matches all `1` and replaces each except the first one (`1>`) with a `0`.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 4 bytes
```
+\=a
```
[Try it online!](https://tio.run/nexus/jelly#@68dY5v4////aAMdBUMdBTgJYsQCAA "Jelly – TIO Nexus")
Here's a rather different algorithm to most of the other golfing language solutions (although after I posted it, I noticed that the R solution also uses this algorithm), and tying with the current Jelly record holder.
## Explanation
```
+\=a
+\ Cumulative sum of the input list
= Compare corresponding elements with the input
a Logical AND corresponding elements with the input
```
As long as all elements to the left of an element are 0, the cumulative sum up to an element will equal the element itself. To the right of the first 1, the two are different (because we're now adding the nonzero total of the elements to the left). Thus, `+\=` gives us a list containing 1 (i.e. true) up to and including the first truthy element. Finally, logical AND with the original list will give us a 1 for *only* the first truthy element.
[Answer]
# [V](https://github.com/DJMcMayhem/V), 7 bytes
```
f1òf1r0
```
[Try it online!](https://tio.run/nexus/v#@59meHhTmmGRwf//0QY6hjoQDCRjAQ "V – TIO Nexus")
My first V submission! \o/
## How it works
```
f1òf1r0
f1 "go to the next occurence of 1
ò "repeat the following until end:
f1 " go to the next occurence of 1
r0 " replace with 0
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 6 bytes
Code:
```
ā<s1kQ
```
Explanation:
```
ā # External enumeration, get a and push [1 .. len(a)]
< # Decrement each
s # Swap to get the input
1k # Get the first index of 1
Q # Check for equality with the enumeration array
```
Uses the **05AB1E** encoding. [Try it online!](https://tio.run/nexus/05ab1e#@3@k0abYMDvw//9oAx0FQx0FOAlixAIA "05AB1E – TIO Nexus")
[Answer]
# [Haskell](https://www.haskell.org/), 25 bytes
Anonymous function taking and returning a list of `Bool`s.
Use as `(foldr(\x l->x:map(x<)l)[])[False,True,False,False]`.
```
foldr(\x l->x:map(x<)l)[]
```
[Try it online!](https://tio.run/nexus/haskell#y03MzLPNzCtJLUpMLlEpzcvJzEst1stNLNAozsgv10vT0yhKTUyxsgouKcrMS9e1i3bKz8@J1dTUAyv8n2ablp@TUqQRU6GQo2tXYQXSWGGjmaMZHfv/f7RbYk5xqk5IUWmqDgYTIRDLFQ1EyKJIZCwXAA "Haskell – TIO Nexus")
# How it works
* Folds over a list from the right, prepending new elements and possibly modifying those following.
* `x` is the element to be prepended to the sublist `l`.
* Uses that `False` compares less than `True`, so `map(x<)l` will turn any `True`s in `l` into `False` if `x` is `True`.
[Answer]
## JavaScript (ES6), ~~33~~ 26 bytes
```
a=>a.map(e=>e&!(i-=e),i=1)
```
I/O is in arrays of 0s and 1s.
[Answer]
# [Turing machine simulator](http://morphett.info/turing/turing.html), 39 bytes
```
0 0 0 r 0
0 1 1 r 1
1 0 0 r 1
1 1 0 r 1
```
[Try it online!](http://morphett.info/turing/turing.html?fd0141edeb1460e742a953adc34b8a25)
[Answer]
## [J](http://jsoftware.com/), 3 bytes
```
</\
```
Defines a monadic verb.
This is a trivial port of [my APL answer](https://codegolf.stackexchange.com/a/119548/32014).
[Try it online!](https://tio.run/nexus/j#@5@mYGulYKMf8z81OSNfIU3BQMEQjIHkfwA "J – TIO Nexus")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 4 bytes
A port of my 05AB1E answer.
```
i1=J
```
Explanation (argument **α**):
```
i1 # Index of 1 (1-indexed) in α
= # Check for equality with the array:
J # [1 .. len(α)]
```
[Try it online!](https://tio.run/nexus/jelly#@59paOv1////aAMdBUMdBTgJYsQCAA "Jelly – TIO Nexus")
[Answer]
# [brainfuck](https://github.com/TryItOnline/tio-transpilers), 55 bytes
```
+>,[[->+>[->-<]>+[-<+>]<<<]>>[-<-<<[->>+<<]>>>]<.[-]<,]
```
[Try it online!](https://tio.run/nexus/brainfuck#HYnBCQAwDAIHspb2Ly4Ssv8YqRRBvHPgVUXDKaqNouCWsuNEKY/xOX4XW6tnzk3OfQ "brainfuck – TIO Nexus")
[Answer]
# [R](https://www.r-project.org/), 24 bytes
```
cumsum(T<-scan(,F))==T&T
```
[Try it online!](https://tio.run/nexus/r#@59cmltcmqsRYqNbnJyYp6HjpqlpaxuiFvLfzdEn2FUhJCgUSiD4/wE "R – TIO Nexus")
Example:
For input `FALSE TRUE TRUE FALSE`
`cumsum(T<-scan(,F))==T` returns `TRUE TRUE FALSE FALSE`. The F in the scan ensures logical input.
`FALSE TRUE TRUE FALSE` and `TRUE TRUE FALSE FALSE` is `FALSE TRUE FALSE FALSE`. A single `&` does an elementwise comparison.
[Answer]
# Octave, 23 bytes
```
@(a)diff([0 cummax(a)])
```
[Try it online!](https://tio.run/nexus/octave#@@@gkaiZkpmWphFtoJBcmpubWAEUiNX8n6Zgq5CYV2zNBZLRMdSBYCAZqwkRUjBQAAlAuEANAA "Octave – TIO Nexus")
First difference of cumulative max of the list.
[Answer]
# Perl 5, 20 bytes
```
sub{map$_&&!$x++,@_}
```
Truthy is `1` and falsey is `''` (an empty string).
Explanation:
`map` loops over elements of the list it `@_`, the arguments passed to the subroutine, setting each element to $\_ locally and returning an array of the return values it computes from each element. `$_&&!$x++` outputs `$_` if `$_` is falsey and `!$x++` if it is truthy. (Note that && is short-circuiting, so `!$x++` is not executed until the first truthy value is reached). `$x++` returns `0` (which is falsey) the first time it is run and then increments every time (and so remains truthy). The `!` negates `$x++`, and so it returns truthy the first time it is encountered and falsey thereafter.
[Answer]
# Python, 58 bytes
```
lambda x:[x[i]and x.index(x[i])==i for i in range(len(x))]
```
If `x[i]` is false, the output is false; otherwise, it gives whether or not the element is the first occurence in the array of itself.
[Answer]
# PHP, 37 bytes
```
foreach($_GET as$v)echo$v*!$$v++,' ';
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 4 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
TḊṬ^
```
**[Try it online!](https://tio.run/nexus/jelly#@x/ycEfXw51r4v4f3XO4/VHTGm8gjvz/PzraQMdQB4KBZKxONBAZgDkGYBZEEgQNYmMB "Jelly – TIO Nexus")**
### How?
This does what was asked in a pretty literal sense:
```
TḊṬ^ - Main link: list a e.g. [0,1,0,1,0,0,1] or [0,1,0,1,0,1,0]
T - get the truthy indexes [ 2, 4, 7] [ 2, 4, 6 ]
Ḋ - dequeue [ 4, 7] [ 4, 6 ]
T - make a boolean array [0,0,0,1,0,0,1] [0,0,0,1,0,1 ]
^ - XOR that with a [0,1,0,0,0,0,0] [0,1,0,0,0,0,0]
```
[Answer]
# [unsure](https://github.com/Radvylf/unsure), 222 bytes
```
hm um err wait oops um but oops yeah umm err heh well wait oops then but heh wait oops no um um yeah err heh um but oops oops um heh well wait oops then um but oops yeah um err heh well wait then um but oops okay well wait
```
Unsure is a stack based esolang I recently created. This answer takes input as a string of `0x00` and `0x01` bytes.
First, here's the code broken into more readable sections:
```
hm um err wait oops
um but oops yeah umm err heh well wait oops then
but heh wait oops no um um yeah err heh
um but oops oops um heh well wait oops then
um but oops yeah um err heh well wait then
um but oops okay well wait
```
The first section is a loop, which first reads input (`hm`), and adds one (`um err`). The `wait` instruction usually ends a while loop, but because there is nothing to start the loop it defaults to the beginning of the program. Because it's adding `1` to each input, and EOF is `-1`, the loop will end once it reaches EOF with an additional `0` on the stack, which is discarded by `oops`.
The next line is a loop through the entire stack. For the first iteration, the stack length is unneeded, so it pushed `1` with `um`. The `but` starts a loop, and the `oops` discards the stack length. It then negates the top of the stack (`yeah`) and adds two (`umm err`, essentially the inverse of the input). It finally pushes this to the other stack (`heh`) and pushes the length of the current stack (`well`). Once the loop ends, the extra `0` is discarded and `then` switches the active stack.
The next line consists of two parts: `but heh wait oops no` (a simple loop which pops items to the other stack until one is `0`), then `um um yeah err heh` which pushes `0` to the other stack.
It then pads the other stack to the right length with `1`s (`um but oops oops um heh well wait oops`) and switches to the other stack (`then`). This is necessary because the output would be backwards otherwise. The other stack does about the same thing, but inverts each item by negating it and adding one (`yeah um err`).
Finally, the `um but oops okay well wait` loop just uses `okay` to output each item in the stack.
[Answer]
# Pyth - 9 bytes
```
.e&b!s<Qk
```
[Try it here](https://pyth.herokuapp.com/?code=.e%26b%21s%3CQk&input=%5BFalse%2CTrue%2CFalse%2CTrue%5D&test_suite=1&test_suite_input=%5B%5D%0A%5BTrue%5D%0A%5BFalse%2CFalse%5D%0A%5BTrue%2CFalse%2CTrue%5D%0A%5BFalse%2CTrue%2CFalse%2CTrue%5D%0A%5BTrue%2CTrue%2CFalse%2CTrue%5D%0A%5BFalse%2CTrue%2CFalse%2CTrue%2CFalse%2CFalse%2CTrue%5D&debug=0)
```
.e&b!s<Qk
.e # Python's 'enumerate' (i.e., for each index k and each element b at that index)
<Qk # The first k elements of the input
s # 'Sum' these first k elements (with booleans, this is a logical 'or')
&b! # The value of the output at index k is [value of input @ index k]&&[the negation of the 'sum']
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~45~~ 36 bytes
```
r=0
while 1:n=input();print n>r;r+=n
```
Input and output are one Boolean (*True* or *False*) per line.
[Try it online!](https://tio.run/nexus/python2#@19ka8BVnpGZk6pgaJVnm5lXUFqioWldUJSZV6KQZ1dkXaRtm/f/v1tiTnEqV0hRaSoXBhNJAAA "Python 2 – TIO Nexus")
[Answer]
# [Idris](https://www.idris-lang.org/example/), 98 bytes
The code is a bit longer, but on the plus side you get the compile time guarantee that the output has the same size as the input!
```
import Data.Vect
f:Vect n Bool->Vect n Bool
f[]=[]
f(x::y)=x::if x then replicate _ False else f y
```
I'm going to give an extensive explanation to have you understand the basic workings of Idris.
### Explanation
```
import Data.Vect
```
The type `Vect : Nat -> Type -> Type` is not imported by default
```
f : Vect n Bool -> Vect n Bool
```
Contrary to Haskell, Idris uses a single colon `:` to specify types and also *requires* you to specify the type, as the dependent type checker can't possibly infer it in all cases. Since `Vect` takes a `Nat` (natural number) and a `Type`, we provide just that, `n` being a natural number and `Bool` being the type. Even though we didn't specify the type of `n` explicitly, Idris can infer it to be `Nat`. Since `n` occurs both in the argument and the resulting type, they need to be the same.
```
f [] = []
```
As the base case, the empty list returns the empty list. This is the only possible implementation, anything else such as `f[]=[True]` would give a compiler error, since the type of `[]` is `Vect 0 Bool` but the type of `[True]` is `Vect 1 Bool`.
```
f (x :: y) = x :: if x then
```
`::` is used as the cons operator in Idris, similar to `:` in Haskell. We put the first element in the resulting list, unchanged.
```
replicate _ False else
```
If the first element is true, we want the rest of the list to be false in any case, so we just replicate the value `False`. Since Idris knows that the rest of the list has to have the same size as `y`, it can infer the value of `_` (namely `length y`).
```
f y
```
If the first element is false, we just move on by recursively calling the function on the rest.
[Answer]
## C#, 77 bytes
```
a=>{var b=1<0;for(int i=0;i<a.Length;){a[i]=b?1<0:a[i];b|=a[i++];}return a;};
```
Compiles to a `Func<bool[], bool[]>`. Nothing clever really, just a straight forward solution.
[Answer]
# [sed](https://www.gnu.org/software/sed/), 16 19 bytes
15 18 bytes sourcecode + 1 byte for -r flag (or -E flag for BSD sed).
```
:
s/1(0*)1/1\10/
t
```
[Try it online!](https://tio.run/nexus/sed#@2/FVaxvqGGgpWmobxhjaKDPVfL/v4GhARQZGP7LLyjJzM8r/q/rCgA "sed – TIO Nexus")
**Edit:** Thanks **Riley** for pointing out a mistake.
[Answer]
# c (with gcc builtins), 40
A slightly different approach:
```
f(n){return!n?0:1<<31-__builtin_clz(n);}
```
This may be ruled invalid - in which case I will happily mark this as non-competing.
Input and output "arrays" are 32-bit unsigned integers - this limits the input list size to be exactly 32 - this may be a disqualifier. If the input is less than 32 bits long, then it may be padded with zero bits at the end.
[Try it online](https://tio.run/nexus/c-gcc#bdLhboIwEADg/zzFzWUJVdwKiMJg7kEcIazCbMLK0pbFaHh2VsQYhnc/2ubL5dL2rittQc6y0I0UD@KdvrpJ4rvLLPtseKW5yFh1Mhlx2z1ywapmX0Ci9J7Xz4etZXGh4TvnAuz@lMsv5gCrhdLADrmE@dzQL4GzBSb6FF0ozXJVqF0Kb1fvgx7pNZx7cxHzEPMRWyEWILZGbINYiFg0NRd5h4eYj9gKsQCxNWIbxELEookF3v3fR//60ca3FvLheFnKWprWm07SGDgkYCt@KurSvrWZwAtMbUdTQkz@YkFGE/AjTfHSnj3R8AjLLfT7h5g5o5HhqQPjOryvM1zPumzDGJvLWG33Bw).
[Answer]
# x86 assembly instructions, 12 bytes
```
31 c0 0f bd cf 74 04 ff c0 d3 e0 c3
```
Or in gcc assembly:
```
.globl f
f:
xor %eax, %eax
bsrl %edi, %ecx
je .L2
inc %eax
sall %cl, %eax
.L2:
ret
```
This is a translation of [my c answer](https://codegolf.stackexchange.com/a/119665/11259) and has the same I/O specs.
[Try it online](https://tio.run/nexus/bash#bZPbboJAEIavmaeY2JiAIiKelXrXXjXpA1gvcF10GwrN7tqQNj67XQ6lRGcudiZfmH8H5odFGjcYC6n0yFMYhvj0@ny1vGOS7RMrhngFWEeeyTJ3eZS75QnWXsnE6vKDKAAz4J1b3kvw19L0ipQ1vWCpKDFdLKlVTMMKLMn11dwNwNojsXokeDASyfnAMVT6IDLvtAEQqcaPSKRoF1Ukj8xFlqVKIztFEns9g74c/IFqBI2aK80ixdV2h481L8LP/TrcezYiWECwMcEmBJsSbEawOcEWBFveshHxHgHBxgSbEGxKsBnB5gRbEGx5w6bB/bdfEvuI66jYZd2sVVRlecTGpbYw2/XXKDBEW4lvnsV2s3oHh3jLtv7Occzz/b7TcsWnNOKx3en6ixwHGyzyW9pxWzYSOxfbOqLQqcaDMhlXn2VqhoELlO4@Mvbv7ea/G2R1Dd6wKq6/).
[Answer]
## Javascript, 25 bytes
```
x=>x.map(c=>c&&x&&!(x=0))
```
* x holds the original array.
* Once the first truthy has been found, x is overwritten with a false value.
* This makes c && x return false for all values except the first truthy.
] |
[Question]
[
This challenge is simple enough that it's basically all in the title: you're given a positive integer **N** and you should return the smallest positive integer which is not a divisor of **N**.
An example: the divisors of **N = 24** are `1, 2, 3, 4, 6, 8, 12, 24`. The smallest positive integer which is not in that list is **5**, so that's the result your solution should find.
This is OEIS sequence [A007978](https://oeis.org/A007978).
## Rules
You may write a [program or a function](http://meta.codegolf.stackexchange.com/q/2419) and use any of the our [standard methods](http://meta.codegolf.stackexchange.com/q/2447) of receiving input and providing output.
You may use any [programming language](http://meta.codegolf.stackexchange.com/q/2028), but note that [these loopholes](http://meta.codegolf.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden by default.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest valid answer – measured in *bytes* – wins.
## Test Cases
The first 100 terms are:
```
2, 3, 2, 3, 2, 4, 2, 3, 2, 3, 2, 5, 2, 3, 2, 3, 2, 4, 2, 3, 2, 3, 2, 5, 2,
3, 2, 3, 2, 4, 2, 3, 2, 3, 2, 5, 2, 3, 2, 3, 2, 4, 2, 3, 2, 3, 2, 5, 2, 3,
2, 3, 2, 4, 2, 3, 2, 3, 2, 7, 2, 3, 2, 3, 2, 4, 2, 3, 2, 3, 2, 5, 2, 3, 2,
3, 2, 4, 2, 3, 2, 3, 2, 5, 2, 3, 2, 3, 2, 4, 2, 3, 2, 3, 2, 5, 2, 3, 2, 3
```
In particular, make sure that your answer works for inputs **1** and **2** in which case the result is larger than the input.
And for some larger test cases:
```
N f(N)
1234567 2
12252240 19
232792560 23
```
## Leaderboard
Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language.
```
/* Configuration */
var QUESTION_ID = 105412; // Obtain this from the url
// It will be like https://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page
var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";
var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk";
var OVERRIDE_USER = 48934; // This should be the user ID of the challenge author.
/* App */
var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page;
function answersUrl(index) {
return "https://api.stackexchange.com/2.2/questions/" + QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER;
}
function commentUrl(index, answers) {
return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER;
}
function getAnswers() {
jQuery.ajax({
url: answersUrl(answer_page++),
method: "get",
dataType: "jsonp",
crossDomain: true,
success: function (data) {
answers.push.apply(answers, data.items);
answers_hash = [];
answer_ids = [];
data.items.forEach(function(a) {
a.comments = [];
var id = +a.share_link.match(/\d+/);
answer_ids.push(id);
answers_hash[id] = a;
});
if (!data.has_more) more_answers = false;
comment_page = 1;
getComments();
}
});
}
function getComments() {
jQuery.ajax({
url: commentUrl(comment_page++, answer_ids),
method: "get",
dataType: "jsonp",
crossDomain: true,
success: function (data) {
data.items.forEach(function(c) {
if (c.owner.user_id === OVERRIDE_USER)
answers_hash[c.post_id].comments.push(c);
});
if (data.has_more) getComments();
else if (more_answers) getAnswers();
else process();
}
});
}
getAnswers();
var SCORE_REG = /<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/;
var OVERRIDE_REG = /^Override\s*header:\s*/i;
function getAuthorName(a) {
return a.owner.display_name;
}
function process() {
var valid = [];
answers.forEach(function(a) {
var body = a.body;
a.comments.forEach(function(c) {
if(OVERRIDE_REG.test(c.body))
body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>';
});
var match = body.match(SCORE_REG);
if (match)
valid.push({
user: getAuthorName(a),
size: +match[2],
language: match[1],
link: a.share_link,
});
});
valid.sort(function (a, b) {
var aB = a.size,
bB = b.size;
return aB - bB
});
var languages = {};
var place = 1;
var lastSize = null;
var lastPlace = 1;
valid.forEach(function (a) {
if (a.size != lastSize)
lastPlace = place;
lastSize = a.size;
++place;
var answer = jQuery("#answer-template").html();
answer = answer.replace("{{PLACE}}", lastPlace + ".")
.replace("{{NAME}}", a.user)
.replace("{{LANGUAGE}}", a.language)
.replace("{{SIZE}}", a.size)
.replace("{{LINK}}", a.link);
answer = jQuery(answer);
jQuery("#answers").append(answer);
var lang = a.language;
if (/<a/.test(lang)) lang = jQuery(lang).text();
languages[lang] = languages[lang] || {lang: a.language, user: a.user, size: a.size, link: a.link};
});
var langs = [];
for (var lang in languages)
if (languages.hasOwnProperty(lang))
langs.push(languages[lang]);
langs.sort(function (a, b) {
if (a.lang > b.lang) return 1;
if (a.lang < b.lang) return -1;
return 0;
});
for (var i = 0; i < langs.length; ++i)
{
var language = jQuery("#language-template").html();
var lang = langs[i];
language = language.replace("{{LANGUAGE}}", lang.lang)
.replace("{{NAME}}", lang.user)
.replace("{{SIZE}}", lang.size)
.replace("{{LINK}}", lang.link);
language = jQuery(language);
jQuery("#languages").append(language);
}
}
```
```
body { text-align: left !important}
#answer-list {
padding: 10px;
width: 290px;
float: left;
}
#language-list {
padding: 10px;
width: 290px;
float: left;
}
table thead {
font-weight: bold;
}
table td {
padding: 5px;
}
```
```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">
<div id="answer-list">
<h2>Leaderboard</h2>
<table class="answer-list">
<thead>
<tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr>
</thead>
<tbody id="answers">
</tbody>
</table>
</div>
<div id="language-list">
<h2>Winners by Language</h2>
<table class="language-list">
<thead>
<tr><td>Language</td><td>User</td><td>Score</td></tr>
</thead>
<tbody id="languages">
</tbody>
</table>
</div>
<table style="display: none">
<tbody id="answer-template">
<tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr>
</tbody>
</table>
<table style="display: none">
<tbody id="language-template">
<tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr>
</tbody>
</table>
```
[Answer]
# Mathematica, 19 bytes (UTF-8 encoding)
```
1//.x_/;x∣#:>x+1&
```
Unnamed function taking a nonzero integer argument and returning a positive integer. The vertical bar about halfway through is actually the three-byte character U+2223, which denotes the divisibility relation in Mathematica. Explanation:
```
1 Starting with 1,
//. apply the following rule until it stops mattering:
x_ if you see a number x
/;x∣# such that x divides the function argument,
:>x+1 replace it with x+1.
& Cool, that's a function.
```
Edited to add: ngenisis points out that `//.` will, by default, iterate a maximum of 65536 times. So this implementation works for all input numbers less than the least common multiple of the integers from 1 to 65538 (in particular, on all numbers with at most 28436 digits), but technically not for all numbers. One can replace `x//.y` with `ReplaceRepeated[x,y,MaxIterations->∞]` to fix this flaw, but obviously at the cost of 34 additional bytes.
[Answer]
## JavaScript (ES6), ~~25~~ 23 bytes
```
f=(n,k)=>n%k?k:f(n,-~k)
```
*Note:* One interesting thing here is that the `k` parameter is initialized *ex nihilo* on the first iteration. This works because `n % undefined` is `NaN` (falsy as expected) and `-~undefined` equals `1`. On the next iterations, `-~k` is essentially equivalent to `k+1`.
### Test
```
f=(n,k)=>n%k?k:f(n,-~k)
// first 100 terms
for(i = 1, list = []; i <= 100; i++) {
list.push(f(i));
}
console.log(list.join(' '));
// larger test cases
console.log(f(1234567));
console.log(f(12252240));
console.log(f(232792560));
```
[Answer]
## Pyth, 3 bytes
```
f%Q
```
Basically, `f` loops the code until `%QT` (`Q % T` where `T` is the iteration variable) is true.
[Try it online here.](http://pyth.herokuapp.com/?code=f%25Q&input=10&test_suite=1&test_suite_input=1%0A2%0A3%0A4%0A5%0A6%0A7%0A8%0A9%0A10%0A11%0A12%0A13%0A14%0A15%0A16%0A17%0A18%0A19%0A20%0A21%0A22%0A23%0A24%0A25%0A26%0A27%0A28%0A29%0A30%0A31%0A32%0A33%0A34%0A35%0A36%0A37%0A38%0A39%0A40%0A41%0A42%0A43%0A44%0A45%0A46%0A47%0A48%0A49%0A50%0A51%0A52%0A53%0A54%0A55%0A56%0A57%0A58%0A59%0A60%0A61%0A62%0A63%0A64%0A65%0A66%0A67%0A68%0A69%0A70%0A71%0A72%0A73%0A74%0A75%0A76%0A77%0A78%0A79%0A80%0A81%0A82%0A83%0A84%0A85%0A86%0A87%0A88%0A89%0A90%0A91%0A92%0A93%0A94%0A95%0A96%0A97%0A98%0A99%0A100&debug=1)
[Answer]
# [Hexagony](https://github.com/m-ender/hexagony), 12 bytes
```
\\)?}'@{!%.}
```
Embiggened:
```
\ \ )
? } ' @
{ ! % . }
. . . .
. . .
```
[Try it online!](https://tio.run/nexus/hexagony#@x8To2lfq@5QraiqV/v/v5GxkbmlkamZAQA "Hexagony – TIO Nexus")
[Answer]
# Python, 43 36 35 bytes
```
f=lambda n,d=2:d*(n%d>0)or f(n,d+1)
```
[Answer]
# R, 28 bytes
Pretty straightforward, nothing fancy. Takes input from stdin, increments value `T` until `i` modulo `T` is nonzero.
```
i=scan()
while(!i%%T)T=T+1
T
```
If you want something a little more fancy, there's the following for **29 bytes**:
```
i=scan()
match(0,!i%%1:(i+1))
```
Explained:
>
> `i=scan()` : Read `i` from stdin.
>
>
> `1:(i+1)` : Generate all integers from `1` to `i+1` (the `+1` accounting for the cases of `1` and `2`).
>
>
> `i%%1:(i+1)` : Modulo the input by every number in our list.
>
>
> `!i%%1:(i+1)` : Negate the resulting list; this implicitly converts it to a logical type, such that `0` is `FALSE` and nonzero is `TRUE`. After negating, `TRUE` values become `FALSE` and vice-versa. Now, all originally nonzero values are coded as `FALSE`.
>
>
> `match(0,!i%%1:(i+1))` : Return the index of the first instance of `0` in our list. `0` is `FALSE`, so this returns the index of the first `FALSE` in the list, which is the first nonzero value from the modulo operation. Since our original list began at `1`, the index is equal to the value of the smallest non-divisor.
>
>
>
[Answer]
## Haskell, 26 bytes
```
f n=until((>0).mod n)(+1)1
```
Everyone forgets about `until`!
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 10 bytes
```
~{=#>:A'*}
```
[Try it online!](https://tio.run/nexus/brachylog#@19XbatsZ@WorlX7/7@Ryf8oAA "Brachylog – TIO Nexus")
This came out very similar to (but shorter than) Fatalize's original solution. Fatalize has since switched to a different algorithm that ties with this one via a different method, so I'm going to have to explain it myself:
```
~{=#>:A'*}
~{ } inverse of the following function:
= try possible values for the input, if it's unbound
#> the input is a positive integer
:A'* there is no A for which the input times A is the output
```
When we invert the function, by swapping "input" and "output", we get a fairly reasonable algorithm (just expressed in an awkward way): "try possible positive integers, in their natural order (i.e. 1 upwards), until you find one that can't be multiplied by anything to produce the input". Brachylog doesn't do floating-point calculations unless all inputs are known, so it'll only consider integer A.
[Answer]
# COW, 174 bytes
```
oomMOOMMMmoOmoOmoOMMMmOomOoMoOMMMmoOmoOmoOMMMmOoMOOmoO
MOomoOMoOmOoMOOmoOmoomoOMOOmOoMoOmoOMOomoomOomOoMOOmOo
moomoOMOomoomoOmoOMOOmOomOomOomOoOOMOOOMOomOOmoomOomOo
mOomOomOomoo
```
[Try it online!](https://tio.run/nexus/cow#bYxBCgAxCAO/1FN/IXmJ5P8nN9pqLwtBwjAxSDfAzJw4yQ4qxh8uObsEXfEmziLAGbbD@6p4O7eMP0GCEoDZvpARe30 "COW – TIO Nexus")
This code is only partially my own -- it implements a [modulus algorithm that I ported from brainfuck.](https://esolangs.org/wiki/Brainfuck_algorithms#Modulus_algorithm) The rest of the code is my own. However, since I did not write the modulus algorithm, I haven't truly investigated how it works and cannot document that part of the code. Instead, I'll give my usual breakdown, followed by a more in-depth explanation of why the code works.
## Code breakdown
```
oom ;Read input into [0].
MOO ;Loop while [0]. We never change [0], so the program only terminates forcibly after a print.
MMMmoOmoOmoOMMMmOomOo ; Copy [0] to [3] and navigate to [1].
MoOMMMmoOmoOmoOMMM ; Increment [1], and copy it to [4]
mOo ; Navigate back to [3].
MOO ; Modulus algorithm. Direct port of brainfuck algorithm.
moOMOomoOMoOmOo
MOO
moO
moo
moO
MOO
mOoMoOmoOMOo
moo
mOomOo
MOO
mOo
moo
moOMOo
moo ; End modulus algorithm.
moOmoO ; Navigate to [5]. This contains our modulus.
MOO ; Only perform these operations if [5] is non-zero -- i.e. [0] % [1] != 0
mOomOomOomOoOOMOOOMOomOO ; Navigate to [1], print its contents, then error out.
moo ; End condition
mOomOomOomOomOo ; Since we're still running, [0] % [1] == 0, so navigate back to [0] and try again.
moo ;End main loop.
```
## Explanation
The code first reads the integer into [0]. Each iteration of the main loop (lines 2 through 26) increments [1], then copies everything necessary over to the modulus algorithm, which spits out its result into [5]. If [5] contains any value, then [1] is the number we need to print. We print it, and then force-quit the program.
Since COW is a brainfuck derivative, it functions relatively similar to the way brainfuck operates -- infinite strip of tape, you can move left or right, increase or decrease, and "loop" while the current tape value is non-zero. In addition to brainfuck, COW comes with a couple of useful features.
```
(0) moo -- Equivalent to ]
(1) mOo -- Equivalent to <
(2) moO -- Equivalent to >
(3) mOO -- No equivalent. Evaluate current tape value as instruction from this list.
(4) Moo -- If tape is 0, equivalent to ,; if tape is non-zero, equivalent to .
(5) MOo -- Equivalent to -
(6) MoO -- Equivalent to +
(7) MOO -- Equivalent to [
(8) OOO -- No equivalent. Set tape (positive or negative) to 0
(9) MMM -- No equivalent. If register is empty, copy tape to register. If register is non-empty, paste register to tape and clear register.
(10) OOM -- No equivalent. Print an integer from tape to STDOUT
(11) oom -- No equivalent. Read an integer from STDIN and store it on tape
```
The real point of interest here is instruction 3, `mOO`. The interpreter reads the current tape value, and executes an instruction based on that tape value. If the value is less than 0, greater than 11, or equal to 3, the interpreter terminates the program. We can use this as a quick-and-dirty force quit of the main loop (and the program entirely) once we've found our non-divisor. All we have to do is print our number, clear [1] (with `OOO`), decrement it to -1 with `MOo`, and then execute instruction -1 via `mOO` which ends the program.
The tape itself for this program functions as follows:
```
[0] -- Read-in integer from STDIN.
[1] -- Current divisor to test
[2] -- Placeholder for modulus algorithm
[3] -- Temporary copy of [0] for use for modulus algorithm
[4] -- Temporary copy of [1] for use for modulus algorithm
[5] -- Placeholder for modulus algorithm. Location of remainder at end of loop.
[6] -- Placeholder for modulus algorithm
[7] -- Placeholder for modulus algorithm
```
The modulus algorithm naturally clears [2], [3], [6], and [7] at the end of the operation. [4]'s contents get overwritten with the register paste on line 4, and [5] is zero when [0] is divisible by [1], so we don't have to clear it. If [5] is non-zero, we force-quit on line 23 so we don't have to worry about it.
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), ~~11~~ 10 bytes
```
,.=:?r'%0'
```
[Try it online!](https://tio.run/nexus/brachylog#@6@jZ2tlX6SuaqD@/7@RsZG5pZGpmcH/KAA "Brachylog – TIO Nexus")
### Explanation
```
,.= Assign an integer to the output
. :?r'%0 Input mod Output ≠ 0
0' Output ≠ 0
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 7 bytes
```
Xµ¹NÖ_½
```
[Try it online!](https://tio.run/nexus/05ab1e#@x9xaOuhnX6Hp8Uf2vv/v5GxkbmlkamZAQA "05AB1E – TIO Nexus")
**Explanation**
```
Xµ # run until counter is 1
¹ # push input
N # push iteration counter
Ö_ # push input % iteration counter != 0
½ # if true, increase counter
# output last iteration
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes
```
1%@#Ḣ
```
[Try it online!](https://tio.run/nexus/jelly#@2@o6qD8cMei////W5gYAAA "Jelly – TIO Nexus")
Explanation:
```
1%@#Ḣ
1 # Find the first … numbers, counting up from 1, such that
%@ dividing those numbers into … gives a truthy remainder
Ḣ then return the first
```
This is a horrendous abuse of `#`; there are plenty of operators in this program, but a ton of missing operands. `#` really wants the `1` to be given explicitly for some reason (otherwise it tries to default to the input); however, everything else that isn't specified in the program defaults to the program's input. (So for example, if you give 24 as input, this program finds the first 24 numbers that don't divide 24, then returns the first; kind-of wasteful, but it works.)
[Answer]
# C, ~~32~~ 35 bytes
```
i;f(x){for(i=1;x%++i<1;);return i;}
```
*Edit: added `i=1` in the loop*
### Usage
```
main(c,v)char**v;{printf("%d",f(atoi(*++v)));}
```
### Full Program version, 64 Bytes:
```
main(c,v)char**v;{*++v;for(c=1;atoi(*v)%++c<1;);printf("%d",c);}
```
[Answer]
# C#, ~~39~~ 37 bytes
```
n=>{int i=0;while(n%++i<1);return i;}
```
Saved two bytes thanks to Martin!
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 6 bytes
```
ÌL¹ÑK¬
```
[Try it online!](https://tio.run/nexus/05ab1e#@3@4x@fQzsMTvQ@t@f/fEAA "05AB1E – TIO Nexus")
Also, it spells "LINK!"... Kinda...
```
ÌL # Push [1..n+2]
¹Ñ # Push divisors of n.
K¬ # Push a without characters of b, and take first item.
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes
```
‘ḍ€i0
```
[Try it online!](https://tio.run/nexus/jelly#@/@oYcbDHb2PmtZkGvz//9/IBAA "Jelly – TIO Nexus")
### How it works
```
‘ḍ€i0 Main link. Argument: n
‘ Increment; yield n+1.
ḍ€ Divisible each; test 1, ..., n+1 for divisibility by n.
i0 Find the first index of 0.
```
[Answer]
# [Octave](https://www.gnu.org/software/octave/)/MATLAB, ~~26~~ 24 bytes
```
@(n)find(mod(n,1:n+1),1)
```
`find(...,1)` returns the index (`1`-based) of the first nonzero element of the vector in the first argument. The first argument is `[n mod 1, n mod 2, n mod 3, n mod 4,...,n mod (n+1)]` That means we have to add `+1` to the index, since we start testing at `1`. Thanks @Giuseppe for -2 bytes.
[Try it online!](https://tio.run/##y08uSSxL/f/fQSNPMy0zL0UjNz9FI0/H0CpP21BTx1Dzf2JesYahkZGpkZGJgeZ/AA "Octave – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes
```
%R;‘TḢ
```
[Try it online!](https://tio.run/nexus/jelly#@68aZP2oYUbIwx2L/v//b2QCAA "Jelly – TIO Nexus")
Explanation:
```
Assume 24 is our N
R Generate all numbers from 1 to N [1, 2, 3, 4 .., 24]
;‘ Attach N+1 to that list (for cases 1,2) [1, 2, 3, 4 .., 25]
% And modulo-divide our input by it
Yields a list with the remainder [0, 0, 0, 0, 4 ...]
T Return all thruthy indexes [5, 7, ...]
Ḣ Takes the first element of that list --> 5
```
[Answer]
## Python 2.7.9, 32 bytes
```
f=lambda n,d=1:n%d>0or-~f(n,d+1)
```
[Test on Ideone](http://ideone.com/G8KmqL)
Recursively counts up potential non-divisors `d`. It's shorter to recursively the increment the result than to output `d`. An offset of `1` is achieved by the Boolean of `True`, which equals `1`, but since `d==1` is always a divisor, the output is always converted to a number.
Python 2.7.9 is used to allow allow `0or`. Versions starting 2.7.10 will attempt to parse `0or` as the start of an octal number and given a syntax error. [See this on Ideone](http://ideone.com/TJxNi8).
[Answer]
# [Perl 6](https://perl6.org), 17 bytes
```
{first $_%*,1..*}
```
[Try it](https://tio.run/nexus/perl6#Ky1OVSgz00u25uLKrVRQS85PSVWw/V@dlllUXKKgEq@qpWOop6dV@784sVJBDyKdll@kkJOZl1r835DLiMvIhMvQyNjE1MwcSBuZGhmZGHAZGRuZWxqZmhkAAA "Perl 6 – TIO Nexus")
## Expanded:
```
{ # bare block lambda with implicit parameter 「$_」
# return the first value
first
# where the block's argument 「$_」 modulus the current value 「*」
# doesn't return 0 ( WhateverCode lambda )
$_ % *,
# ( 「$_ !%% *」 would be the right way to write it )
# from 1 to Whatever
1 .. *
}
```
[Answer]
## Perl, 19 bytes
18 bytes of code + `-p` flag.
```
$_=$_%++$.?$.:redo
```
To run it:
```
perl -pE '$_=$_%++$.?$.:redo' <<< 12252240
```
*Not very detailed* explanations:
- `$.` is a special variable whose default value is the current line number of the last filehandle accessed (stdin here), so after reading the first line of input, it's set to 1.
- `$_` holds the input and is implicitly printed at the end (thanks to `-p` flag).
- `redo` (in that context) considers that the program is in a loop and redo the current iteration (only `$.` will be different since it got incremented).
- So if we found the smallest number (stored in `$.`) that doesn't divide `$_`, then we set `$_` to it, otherwise, we try the next number (thanks to `redo`).
[Answer]
# [Actually](https://github.com/Mego/Seriously), 7 bytes
```
;÷@uR-m
```
[Try it online!](https://tio.run/nexus/actually#@299eLtDaZBu7v//RiYA "Actually – TIO Nexus") (note: this is a very slow solution, and will take a long time for large test cases)
Explanation:
```
;÷@uR-m
;÷ duplicate N, divisors
@uR range(1, N+2)
- set difference (values in [1, N+1] that are not divisors of N)
m minimum
```
[Answer]
# [Haskell](https://www.haskell.org/), 29 bytes
```
f n=[k|k<-[2..],mod n k>0]!!0
```
The expression `[k|k<-[2..]]` just creates an infinite list `[2,3,4,5,...]`. With the condition `mod n k>0` we only allow those `k` in the list that do not divide `n`. Appending `!!0` just returns the first entry (the entry at index `0`) form that list.
[Try it online!](https://tio.run/nexus/haskell#@5@mkGcbnV2TbaMbbaSnF6uTm5@ikKeQbWcQq6ho8D83MTNPwVahoLQkuKTIJ0@lOCO/XCVNwdDIyNTIyMTgPwA "Haskell – TIO Nexus")
[Answer]
# [Dyalog APL](http://goo.gl/9KrKoM), 8 [bytes](http://meta.codegolf.stackexchange.com/a/9429/43319)
```
1⍳⍨0≠⍳|⊢
```
`1⍳⍨` position of first True in
`0≠` the non-zero values of
`⍳|` the division remainders of 1...**N** when divided by
`⊢` **N**
[TryAPL online!](http://tryapl.org/?a=f%u21901%u2373%u23680%u2260%u2373%7C%u22A2%20%u22C4%20f%A8%u2373100&run)
Note: this works for 1 and 2 because `1⍳⍨` returns 1 + the length of its argument if none is found.
[Answer]
# julia, 28 bytes
```
N->findfirst(x->N%x>0,1:N+2)
```
Note: since `1:N+2` doesn't allocate memory there is no memory problems for large `N` s
- @flawr `N+2` save for me some bytes
- @Martin 's suggestion saved 1 bytes
[Answer]
## [QBIC](https://drive.google.com/drive/folders/0B0R1Jgqp8Gg4cVJCZkRkdEthZDQ), 14 bytes
```
:[a+1|~a%b|_Xb
```
Explanation:
```
: Read the first cmd line param as a number, called 'a'
[a+1| FOR (b=1 ; b <= a+1; b++) <-- a+1 for cases a = 1 or 2
~a%b IF A modulo B ( == 0, implicit)
|_Xb THEN exit the program, printing b
[IF and FOR implicitly closed by QBIC]
```
[Answer]
# C, 30 bytes
Recursion is your friend:
```
f(x,i){return x%i?i:f(x,i+1);}
```
Call as follows:
```
#include <stdio.h>
f(x,i){return x%i?i:f(x,i+1);}
int main() {
for(int i = 1; i < 10; i++) {
printf("f(%d, 1) = %d\n", i, f(i, 1));
}
}
```
[Answer]
# PHP, 30 bytes
```
for(;$argv[1]%++$i<1;);echo$i;
```
if run from console with `-r` option (thx to @ais523)
```
php -r 'for(;$argv[1]%++$i<1;);echo$i;' 232792560
```
# 32 bytes
```
<?for(;$argv[1]%++$i<1;);echo$i;
```
thanks to @manatwork for removing 1 byte
# 33 bytes (original)
```
<?for(;$argv[1]%++$i==0;);echo$i;
```
[Answer]
# [Cubix](https://github.com/ETHproductions/cubix), ~~14~~ 12 bytes
```
I2/L/);?%<@O
```
Saved 2 bytes thanks to MickyT.
[Try it](https://ethproductions.github.io/cubix/?code=STIvTC8pOz8lPEBP&input=NDI=&speed=5)
### Explanation
In cube form, the code is:
```
I 2
/ L
/ ) ; ? % < @ O
. . . . . . . .
. .
. .
```
Basically, this just takes the input and starts a counter. It then checks each successive value of the counter until it finds one that isn't a factor of the input.
[Answer]
# [Rust](https://www.rust-lang.org/), 23 bytes
```
|n|(1..).find(|x|x%n>0)
```
[Try it online!](https://tio.run/##KyotLvmflqeQm5iZp6FZnZNaopBmlZanUWpspKlrF2/7vyavRsNQT09TLy0zL0WjpqKmQjXPzkDzvzVXYnFxalFJfGqhokaahqGmTnB@bqqGkaYmmowFVMYYJFP7HwA "Rust – Try It Online")
A closure that iterates over all positive integers returning `Some(n)` where n is the first integer modulo input is greater than zero.
] |
[Question]
[
A lipogram is a block of words that omits a particular symbol. Right now, I am avoiding our fifth symbol of 26 that commonly show up. You should know by now what I am omitting. If not, look up "lipogram" and you will know.
## Your Task
With a char, a blank, and a following string (blanks may show up in this; with only ASCII 32-126 chars) in input, output falsy if this char is in input string, truthy if not. This char that you must look for will always fit in two spans: "A" to "Z" or "a" to "z" (ASCII 65-90, 97-122). Do not distinguish capitals and non-capitals. Also, don't worry about blanks or punctuation symbols. Both programs and functions satisfy. Also, you may split input char and string into two args for programs or functions, and string as first arg is okay.
## Illustrations
### Truthy
```
e This is a lipogram.
a You need to consider other letters too.
E Capitals also count.
```
### Falsy
```
e This sentence is not a lipogram (for e).
t This particular letter is surprisingly hard.
A You don't need to care about any non-alphabetic symbols.
```
---
### Non-lipogrammed version
A lipogram is a series of words that leaves out a letter. I left out the letter "e" above.
Your task is to take a character and a string (which may include spaces) as input, separated by a space or newline, and output falsy if the character is in the string, and truthy otherwise. You may assume the string is composed solely of printable ASCII characters (char codes 32-126). The character will always be in the English alphabet, and there is no difference between lowercase and uppercase. The character will not be a space or symbol. You may write a program or a function. For either, you may take the character and string as separate arguments, and the string may come first.
[Answer]
# C, 42 bytes
```
#define f(c,s)!strchr(s,c)&!strchr(s,c^32)
```
[Answer]
## Javascript ES6 ~~34~~ ~~26~~ 23 Bytes
```
x=>!/^(.).*\1/i.test(x)
```
shaved 8 bytes thanks @MartinBüttner
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~7~~ ~~6~~ ~~4~~ 3 bytes
Code:
```
l`-
```
Explanation:
```
l # Convert both elements to lowercase
` # Flatten the array
- # Loop over the second line of text and substract each char from the first character
For example: "abcde""ba"- would result in "cde"
```
[Try it online!](http://05ab1e.tryitonline.net/#code=bGAt&input=WyJFIiwgIlRoaXMgaXMgYSBsaXBvZ3JhbS4iXQ)
Truthy is when the current letter is outputted. Falsy is when nothing is outputted.
[Answer]
# TeaScript, ~~5~~ 3 bytes
```
AµN
```
Aha \o/! I forgot about implicit input! TeaScript will automatically insert `x.` (the input) at the beginning. I can then check if it has the other input (in variable `µ`) and so a NOT (`N`). I guess TeaScript's best advantage here is its implicit input
[Try it online](http://vihan.org/p/TeaScript/#?code=%22A%C2%B5N%22&inputs=%5B%22This%20sentence%20is%20not%20a%20lipogram%22,%22e%22%5D&opts=%7B%22ev%22:false,%22debug%22:false,%22nox%22:false%7D)
## Explanation
```
A µ N
x.A(y).N // At compile time
x.A // input, has...
(y) // second input
N // Logical NOT
```
[Answer]
## Bash, ~~16~~ 11 bytes
```
grep -iv $1
```
`-i` is the case-insensitive flag, `-v` inverts (checks for a non-match).
Character must be provided as a command line argument, and the test string on STDIN.
Reduced by 5 bytes with @[DigitalTrauma](https://codegolf.stackexchange.com/users/11259/digital-trauma)'s help!
Sample runs:
```
llama@llama:~$ echo 'This is a lipogram' | ./lipogram.sh e
This is a lipogram.
llama@llama:~$ echo 'This sentence is not a lipogram (for e).' | ./lipogram.sh e
```
[Answer]
# Japt, ~~12~~ ~~6~~ 4 bytes
```
!VoU
```
[Test it online!](http://ethproductions.github.io/japt?v=master&code=IVZvVQ==&input=ImUiICJUaGlzIGlzIGEgbGlwb2dyYW0uIg==)
@Downgoat's TeaScript answer reminded me that Japt has exactly the same built-in, cutting off a final two bytes.
### How it works
```
// Implicit: U = input char, V = input string
VoU // Keep only the chars in V that are equal to U, ignoring case.
! // Take logical NOT. Returns true if no matches were found, false otherwise.
```
[Answer]
## JavaScript (ES6), 29 bytes
```
(c,s)=>!RegExp(c,'i').test(s)
```
[Answer]
## CJam, 6 byte
```
lel(&!
```
[Try it online!](http://cjam.tryitonline.net/#code=bGVsKCYh&input=QSBZb3UgZG9uJ3QgbmVlZCB0byBjYXJlIGFib3V0IGFueSBub24tYWxwaGFiZXRpYyBzeW1ib2xzLg) lel
### Explanation
```
l e# Read a line of input.
el e# Convert to lower case.
( e# Pull off the first character.
& e# Set intersection with the rest of the input.
! e# Logical NOT.
```
[Answer]
# Python 3, 36
Having to ignore case is surprisingly expensive.
```
lambda a,b:a.lower()not in b.lower()
```
Takes the arguments as (char, string)
[Answer]
## Perl, 11 + 1 = 12 bytes
```
$_=lc!~lc<>
```
Requires the `-p` switch and takes input as `$string\n$letter`
```
$ perl -pe'$_=lc!~lc<>' <<< $'this is a lipogram\ne'
1
```
How it works:
```
# -p auto reads input into $_ and auto prints at the end
lc # lowercase $_
!~ # Check against regex
lc<> # Read next line and lowercase it. '=~' will expect the rValue to be
# a regex and therefore the result from 'lc<>' will be treated as such
$_= # Assign result ('1' or '') to $_ which will be printed
```
[Answer]
## Pyth, ~~8~~ 7 bytes
```
-rz0rw0
```
Explanation
```
rw0 - input().lower()
- - ^ - V
rw0 - input().lower()
```
Thanks [@FryAmTheEggman](https://codegolf.stackexchange.com/users/31625/fryamtheeggman) for telling me I can use `-` instead of `!}`
[Try it here](http://pyth.herokuapp.com/?code=!%7Drw0rw0&input=e%0AThis+is+a+lipogram.&debug=0)
[Answer]
# Julia 0.3, ~~22~~ 20 bytes
```
c%s=c&95∉[s...]&95
```
`uppercase` is a *long* word.
### How it works
```
c%s=c&95∉[s...]&95
c%s= Redefine the binary operator % so it takes a character c and
a string s and...
c&95 Compute lo bitwise AND of c and 95.
This casts the character c to uppercase.
[s...] Yield the list of the characters of the string s.
&95 Compute lo bitwise AND of each chararacter and 95.
This casts the characters of s to uppercase.
∉ Return a Boolean, signaling non-membership.
```
[Answer]
## Java, 63 bytes.
```
boolean f(String s,char c){return!s.matches("(?i:.*"+c+".*)");}
```
[Answer]
# O, 8 bytes
```
{_.@_-=}
```
An anonymous function that takes a character and a string.
[Try it online.](http://o-lang.herokuapp.com/link/J1QidGVzdCJ7Xy5AXy09fX4=/)
## Explanation
```
{_.@_-=}
{ }
_ Lowercase string
. Duplicate
@ Rotate stack
_ Lowercase character
- Remove all instances of the character
= Compare to original
```
[Answer]
## PowerShell, ~~36~~ ~~32~~ ~~30~~ ~~29~~ 25 bytes
```
param($a,$b)$b-notmatch$a
```
Uses the [`-notmatch` operator](https://technet.microsoft.com/en-us/library/hh847759(v=wps.620).aspx), and simply outputs `True` or `False`.
[Answer]
# [MATL](https://esolangs.org/wiki/MATL), 5 bytes
```
kikm~
```
[**Try it online!**](http://matl.tryitonline.net/#code=a2lrbX4&input=J3QnCidUaGlzIHBhcnRpY3VsYXIgbGV0dGVyIGlzIHN1cnByaXNpbmdseSBoYXJkLic)
```
k % take first input (letter) implicitly. Convert to lowercase
ik % take second input (text). Convert to lowercase
m % ismember function
~ % negate
```
[Answer]
## Seriously, 6 bytes
```
,ù,ùíu
```
[Try it online!](http://seriously.tryitonline.net/#code=LMO5LMO5w611&input=J1RoaXMgc2VudGVuY2UgaXMgbm90IGEgbGlwb2dyYW0gKGZvciBlKS4nCidFJw)
Takes input as `'string'\n'char'`
Explanation:
```
,ù,ùíu
,ù get string (lowercase)
,ù get char (lowercase)
íu 1-based index (0 if not found)
```
[Answer]
# Retina, 11
```
iA`^(.).*\1
```
I'm not sure what counts as truthy / falsy in Retina, this will echo the line if it is a lipogram for the given character, and it will return the empty string if it isn't.
This will also work for multiline input.
[Try it online!](http://retina.tryitonline.net/#code=aUFgXiguKS4qXDE&input=ZSBUaGlzIGlzIGEgbGlwb2dyYW0uCmEgWW91IG5lZWQgdG8gY29uc2lkZXIgb3RoZXIgbGV0dGVycyB0b28uCkUgQ2FwaXRhbHMgYWxzbyBjb3VudC4KCmUgVGhpcyBzZW50ZW5jZSBpcyBub3QgYSBsaXBvZ3JhbSAoZm9yIGUpLgp0IFRoaXMgcGFydGljdWxhciBsZXR0ZXIgaXMgc3VycHJpc2luZ2x5IGhhcmQuCkEgWW91IGRvbid0IG5lZWQgdG8gY2FyZSBhYm91dCBhbnkgbm9uLWFscGhhYmV0aWMgc3ltYm9scy4)
[Answer]
## [Minkolang 0.15](https://github.com/elendiastarman/Minkolang), 10 bytes
```
$or7Z0Z,N.
```
[Try it here.](http://play.starmaninnovations.com/minkolang/?code=%24or7Z0Z%2CN%2E&input=e%20This%20is%20a%20lipogram%2E)
### Explanation
```
$o Read in whole input as characters
r Reverse stack
7Z Lowercase everything
0Z Pop top of stack (a) and count how many 'a's are in the stack
, 'not' the top of stack
N. Output as number and stop.
```
[Answer]
## Rust, 75 bytes
```
|c:char,s:&str|!s.to_lowercase().contains(c.to_lowercase().next().unwrap())
```
Biggest score means I win, right? >\_<
[Try it here.](http://is.gd/gzgTSB)
[Answer]
# Jelly, 8 bytes
```
ḢO^O&95P
```
[Try it online!](http://jelly.tryitonline.net/#code=4biiT15PJjk1UA&input=&args=QyBKZWxseSBzaG91bGQgcmVhbGx5IGhhdmUgc3RyaW5nIG1hbmlwdWxhdGlvbiBieSBub3cu)
### How it works
```
ḢO^O&95P Main link. Input: S (string)
Ḣ Pop the first character of S.
O Ordinal; compute its code point.
^O XOR it with the code points of the remaining characters.
&95 AND each result with 95.
P Take the product of the results.
```
[Answer]
## Python, 34 bytes
```
lambda c,s:c not in s+s.swapcase()
```
Checks for character `c` being in string `s`, ignoring case by appending a case-swapped copy of `s` to `s`. The negation is done with `not`, which looks lengthy but I don't see better. This is same length:
```
lambda c,s:(c in s+s.swapcase())<1
```
You can't omit the parens or else Python will interpet the expression as a chained three-value inequality of form `_ in _ < _`.
Python 3.5 should allow 33 bytes via set conversions, though I can't test it now.
```
lambda c,s:{*c}-{*s+s.swapcase()}
```
[Answer]
## Pyke, 7 bytes
```
Dl3+R{!
```
Explanation:
```
D - eval_or_not(input()).lower()
l3 - ^.swapcase()
+ - ^+^
R - rotate 2
{ - ^ in ^
! - not ^
```
[Answer]
# JavaScript ES6, ~~41~~ 40 bytes
```
x=>!~x.slice(2).search(RegExp(x[0],"i"))
```
Takes the entire string as an argument. I cannot save bytes by accepting two different arguments because then my answer would melt into the other ES6 answer :(
[Answer]
# CJam, 10 bytes
```
{el\ele=!}
```
An anonymous function (block) that takes a character (not a string!) and a string.
[Try it online.](http://cjam.tryitonline.net/#code=J0EiYWJjIntlbFxlbGU9IX1-&input=)
## Explanation
```
{el\ele=!}
{ }
el\el lowercase both args
e= count occurrences of the character
! logical not
```
[Answer]
# R, 26 bytes
```
function(x,y)!grepl(y,x,T)
```
x is the string, y is the letter, the T in the call to grepl makes it case insensitive.
[Answer]
# Jolf, ~~6~~ 7 bytes
So. Many. Sixes. SMS? Well, [try it here](http://conorobrien-foxx.github.io/Jolf/#code=fyBNaUknaQ) nonetheless. Replace `⌂` with `\x7f`.
```
⌂ MiI'i
⌂_M match with flags
i the input
I with another input
'i using i as a flag
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 6 bytes
```
ɽfhO2<
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJQQSIsIiIsIsm9ZmhPMjwiLCIiLCIiXQ==)
Accepts one line as input, formatted like the test cases.
How it works:
```
ɽf # convert input to lowercase and turn into list
hO # count the number of times the first item in the list occurs
2< # is it less than 2 (should only occur once as the first character)
```
[Answer]
## Ruby, 17 bytes
```
->c,s{/#{c}/i!~s}
```
```
->c,s{ # lambda with two arguments
/#{c}/ # turn the input character into a regexp w/ interpolation
i # case insensitive
!~ # does not match
s # input string
}
```
[Answer]
## Batch, 53 bytes
```
@set s=%2
@call set t=%%s:%1=%%
@if %s%==%t% echo 1
```
Accepts input as two command-line arguments. (Quote the second argument if necessary.) Outputs 1 on success, nothing if the first argument is (insensitively) found in the second.
] |
[Question]
[
Given two words, [spoonerise](https://en.wikipedia.org/wiki/Spoonerism) them by switching their initial consonant clusters. Fewest bytes wins.
```
plaster man -> master plan
blushing crow -> crushing blow
litigating more -> mitigating lore
strong wrangler -> wrong strangler
def ghi -> ghef di
few years -> yew fears
```
The consonants appearing before the first vowel (`aeiou`) are switched.
**Input:** Two lowercase strings that start with different consonants and each contain a vowel `aeiou`.
**Output:** The two spoonerised strings, in the right order.
For input and/or output, the two strings may also be in a list or the like, or as a single string with separator.
```
var QUESTION_ID=69385,OVERRIDE_USER=20260;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/69385/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
```
```
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
```
```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>
**Leaderboard:**
```
---
This is a near-dupe of [this old question](https://codegolf.stackexchange.com/q/3463/20260), but I'm hoping to write a spec that is clearer and more stable so that [the old one can be closed as a dupe](http://meta.codegolf.stackexchange.com/a/7326/20260).
[Answer]
# Vim, 18 keystrokes
```
/[aeiou]<CR>dbwvnhp0P
```
The crucial trick is that pasting over something in Visual mode actually puts the old contents of the visual selection in the paste buffer.
[Answer]
# brainfuck, ~~238~~ 207 bytes
```
,[[<+<+>>-]++++[<-------->-]-[<<-->>-----]<<+++++[----[----[------[------>>]]]]>[>>]>,]<<++++++++[<[++++<<]<++++<[++++<<]>>[>>]>>[>>]<-]<[<<]-[<+>---]>[>.>]<[<<]<<[<<]>[>>]>[.>>]<.<[<<]>[>.>]>[>>]>[>>]>[.>>]
```
Requires `,` to return 0 on EOF, 8-bit wrapping cells and the ability to move left from cell 0. In my experience, these are the most common default settings.
I'm pretty happy with this one. My first try was 314 bytes and this is certainly an improvement. :)
It works by storing every byte from input in two cells; one with the actual value of the byte and the other with the output of the following code when given (the value of the byte - 97):
```
[
----
[
----
[
------
[
------>>
]
]
]
]
```
If the character is a consonant, it comes out of that with a non-zero value. If it's a vowel, it becomes 0. From there it's just a matter of finding where the second word starts and printing everything in order.
The 238 byte version of this program found the space character after collecting all the input. It was a headache because doing so involved creating a cell that contained 0 right where I was trying to loop over it. The way I solved that had the effect of subtracting 30 from every character in the first word and 32 from every character after it. A fairly large portion of the code was dedicated to handling that nonsense.
Now, 32 is subtracted from *every character* in the input loop, which is shorter and has a similar side effect that's easier to deal with. As a bonus, doing it this way allowed me to create my own space character in a shorter way: Instead of subtracting 139 from 171 (171 is what you get when you run a space through the vowel detector above), the loop that adds 32 to every character goes out of its way to also add 32 to the 171 cell. This costs four bytes there, but means I can subtract 171 from it later (instead of subtracting 139) for a net total of 3 bytes saved.
With comments:
```
For every input character
,[
Make a copy
[<+<+>>-]
Subtract 32 from one
++++[<-------->-]
Subtract 97 from the other
-[<<-->>-----]<<+++++
If nonzero:
[
Subtract 4
----
If nonzero:
[
Subtract 4
----
If nonzero:
[
Subtract 6
------
If nonzero:
[
Subtract 6
------>>
]
]
]
]
>[>>]>,]
Add 32 to every character and the 171 that the space left behind
<<++++++++[<[++++<<]<++++<[++++<<]>>[>>]>>[>>]<-]
Go to the space
<[<<]
Subtract 171 from (32 plus 171)
-[<+>---]
~~~~~~~~~~~~~~~
Ready to print!
~~~~~~~~~~~~~~~
Print letters from the second word until the value to the left is zero
>[>.>]
Go to the beginning of the first word
<[<<]<<[<<]
Look at cells to the left of letters in the first word until reaching a zero
>[>>]
Print the rest of the letters in the first word
>[.>>]
Print a space
<.
Go to the beginning of the first word
<[<<]
Print letters from the first word until the value to the left is zero
>[>.>]
Go to the beginning of the second word
>[>>]
Look at cells to the left of letters in the second word until reaching a zero
>[>>]
Print the rest of the letters in the second word
>[.>>]
```
[Answer]
## vim, 23
```
/[aeiou]<cr>"xd0wndb0Pw"xP
```
I wonder if vim is actually competitive in this challenge. Probably not with the golfing languages, but perhaps with Ruby/Python/Perl/etc.
```
/[aeiou]<cr> Find the first vowel
"xd0 "Delete" (cut), to register "x, everything from here to BOL
w Go to next word
n Find next vowel
db "Delete back" - delete from here to the beginning of the word
0 Go to BOL
P Paste what we just "deleted" (cut) behind the cursor
w Next word
"xP Paste backwards from register "x
```
[Answer]
# Python, ~~68~~ ~~63~~ 60 bytes
```
import re
lambda s:re.sub('([^aeiou]+|.+ )'*3,r'\3\2\1',s,1)
```
Try it online on [Ideone](http://ideone.com/IDmjcC).
### How it works
The pattern string is repeated thrice (`*3`), resulting in the pattern
```
([^aeiou]+|.+ )([^aeiou]+|.+ )([^aeiou]+|.+ )
```
All instances will either match a non-empty string of non-vowels, or a non-empty string followed by a single space character.
The first instance will match the consonants at the beginning of the first word. Since `+` is greedy, it will attempt to match as many as possible, i.e., all up to the first vowel.
Because of this, the second instance will start at a vowel, so it will match the remainder of the first word, up to and including the space that separates the words.
Similarly to the first instance, the third will match all consonants at the beginning of the second word, resulting in a successful match for the entire pattern.
The raw string `\3\2\1` (`r` prevents Python from replacing `\3` etc. with control characters) reverses the order of the matches of the parenthesized patterns, i.e., it replaces them with the consonants at the beginning of the *second* word, then all characters from the first vowel of the first word up to the space, and finally the consonants at the beginning of the first word.
The final argument to `sub` (`1`) makes it return immediately after the first successful replacement, to avoid nonsensical replacements in the remainder of the second word. This is required since the pattern can match any string of three or more consecutive consonants.
[Answer]
# JavaScript (ES6), 54 bytes
```
s=>s.replace(r=/\b[^aeiou ]+/g,(_,i)=>s.match(r)[+!i])
```
## Explanation
```
s=>
s.replace(
r=/\b[^aeiou ]+/g, // r = regex to match consonants
(_,i)=>s.match(r)[+!i] // replace consonants with the consonants from the other word
)
```
## Test
```
var solution = s=>s.replace(r=/\b[^aeiou ]+/g,(_,i)=>s.match(r)[+!i])
```
```
<input type="text" id="input" value="plaster man" />
<button onclick="result.textContent=solution(input.value)">Go</button>
<pre id="result"></pre>
```
[Answer]
# Python 3, ~~108~~ ~~101~~ 99 bytes
**(No use of regex)**
This function expects input via 2 arguments, e.g. `f('blushing','crow')`. Returns the new words in a tuple.
```
S=lambda s,p="":s[0]in"aeiou"and(p,s)or S(s[1:],p+s[0])
def f(x,y):a,b=S(x);c,d=S(y);return c+b,a+d
```
There are a lot of regex solutions, so I wanted to write something that didn't use Python's re library.
## How it works
The only complicated part is the lambda expression `S` (the abbreviation means "**S**plit before the first vowel").
It recursively "iterates" over the given word, moving one character at a time from the beginning of `s` (which starts with the whole word) to the end of `p` (which starts empty). At the first vowel encountered it returns `(p,s)`, i.e. (prefix, suffix). Notice that that is the wrong order compared to the parameters!
I thought it made more sense for the returned order to be prefix, then suffix (because generally a prefix goes before a suffix). This order might make the `a,b=S(x)` code slightly easier to read.
But I had no choice of order in the lambda's parameters, so I couldn't define `p` before `s`. The first parameter, `s`, *had* to take the entire word because `p` had a default value, and default parameters go last. Doing that, I didn't need to call the function `S` with an empty string twice, and a few bytes could be saved. However, perhaps it was simply a bad decision to return prefix/suffix in the opposite order as it was used within the lambda expression.
As for the choice of lambda expression over function, it takes more bytes to say `def S(s,p=""):return` than `S=lambda s,p="":`. I can make that choice because Python has short-circuit evaluation, and the ternary operator. However, I cannot adequately explain how I used short-circuits; it's hard to reason about.
---
This is my first answer. I hope I did this correctly, and that there's value to posting a solution that cannot win.
**Edits:** *Thank-you commenters: Reduced the byte count a bit, twice, and removed unnecessary info. Attempted to improve writing. Hopefully made no mistakes.*
[Answer]
# C#6, 115 bytes
```
string S(string a)=>System.Text.RegularExpressions.Regex.Replace(a,"([^aeiou]*)(.*) ([^aeiou]*)(.*)","$3$2 $1$4");
```
It's just a pain the namespace for regex is so long.
[Answer]
# CJam, ~~27~~ ~~24~~ 22 bytes
```
2{l_{"aeiou"&}#/(N\}*o
```
I/O is one word per line. [Try it online!](http://cjam.tryitonline.net/#code=MntsX3siYWVpb3UiJn0jLyhOXH0qbw&input=Ymx1c2hpbmcKY3Jvdwo)
### How it works
```
2{ }* Do the following twice:
l Read a line from STDIN.
_ Push a copy.
{"aeiou"&}# Find the index of the first character that has a non-
empty intersection with the string "aeiou".
/ Split the string into chunks of that size.
( Shift out the first chunk, i.e., all leading consonants.
N\ Swap the shifted out chunk with a linefeed.
o Print the topmost stack item.
```
[Answer]
# Perl, 33 bytes
```
s/([^aeiou]+)(.+ )((?1))/\3\2\1/
```
The above code is **32 bytes** long and requires the `-p` switch (**+1 byte**).
The substitution is very similar to the one [@DigitalTrauma's Retina answer](https://codegolf.stackexchange.com/a/69398), but this answer takes advantage of [PCRE's recursive subpatterns](http://perldoc.perl.org/perlre.html#(%3f_PARNO_)-(%3f-_PARNO_)-(%3f%2b_PARNO_)-(%3fR)-(%3f0)).
Try it online on [Ideone](http://ideone.com/vGmx9Z).
[Answer]
# [Retina](https://github.com/mbuettner/retina), 34
```
([^aeiou]+)(.+ )([^aeiou]+)
$3$2$1
```
[Try it online.](http://retina.tryitonline.net/#code=KFteYWVpb3VdKykoLisgKShbXmFlaW91XSspCiQzJDIkMQ&input=bWFzdGVyIHBsYW4)
[Answer]
# JavaScript ES6, ~~93~~ ~~58~~ 52 bytes
Saved 6 bytes thanks to ETHProductions!
```
x=>x.replace(/([^aeiou]+)(.+ )([^aeiou]+)/,"$3$2$1")
```
## Test it! (ES6 only)
```
F=x=>x.replace(/([^aeiou]+)(.+ )([^aeiou]+)/,"$3$2$1");
console.log=_=>u.innerHTML+=_;
console.log(`plaster man -> master plan
blushing crow -> crushing blow
litigating more -> mitigating lore
strong wrangler -> wrong strangler
def ghi -> ghef di`.split`\n`.map(e=>(e=e.split` -> `,`${e[0]} => ${e[1]} ||> `+(F(e[0])==e[1]))).join`<br>`);
```
```
html { font-family: Consolas, monospace; }
```
```
<div id=u></div>
```
[Answer]
# C, ~~255~~ ~~201~~ 199 bytes
I don't see a lot of C answers around here, so enjoy;
Also, first time golfing, suggestions and critique are welcome.
```
#define S(w,p)p=strpbrk(w,"aeiou")-w
#define c ;strcpy(r
#define l c+strlen(v[1])+b+1
main(int q,char**v){char r[64],S(v[1],a),S(v[2],b)c,v[2])c+b,v[1]+a);strcat(r," ")l-a,v[1])l,v[2]+b);puts(r);}
```
If main() is not required we can save 24 bytes, getting to 179 bytes
```
#define S(w,p)p=strpbrk(w,"aeiou")-w
#define c ;strcpy(r
#define l c+strlen(x)+b+1
s(char*x,char*y){char r[64],S(x,a),S(y,b)c,y)c+b, x+a);strcat(r," ")l-a,x)l,y+b);puts(r);}
```
Ungolfed:
```
void spoonerise(char* w1, char* w2)
{
char rt[64];
int p1 = strpbrk(w1, "aeiou")-w1;
int p2 = strpbrk(w2, "aeiou")-w2;
strcpy(rt, w2);
strcpy(rt+p2, w1+p1);
strcat(rt, " ");
strcpy(rt+strlen(w1)+p2+1-p1, w1);
strcpy(rt+strlen(w1)+p2+1, w2+p2);
puts(rt);
}
```
EDIT: Thanks to feersum's suggestion I saved 54 bytes. =D
[Answer]
# sed, 38 characters
```
s/([^aeiou]+)(.+ )([^aeiou]+)/\3\2\1/
```
Using extended regular expression from the [Retina solution](https://codegolf.stackexchange.com/a/69398/49043).
The above is 37 characters long and requires the `-r` switch (+1 character).
Example:
```
$ cat input | tee /dev/tty | sed -r 's/([^aeiou]+)(.+ )([^aeiou]+)/\3\2\1/'
plaster man
blushing crow
litigating more
strong wrangler
def ghi
master plan
crushing blow
mitigating lore
wrong strangler
ghef di
```
[Answer]
# Python 2, ~~364~~ ~~352~~ ~~269~~ 251 bytes
**EDIT:** Thanks so much to @Cyoce for helping me golf 83 bytes!
Please help me golf this! Anyway, at least I am the first Python answerer. And I hope I can beat Java, if there ever is a Java answer!
```
i=input()
f=l=''
A='aeiou'
for j in A:
I=i[0];J=I.find(j)
if ~J:
if f:
if f>I[0][:J]:f=I[:J];break
else:f=I[:J]
for j in A:
Y=i[1];J=Y.find(j)
if ~J:
if l:
if l>Y[:J]:l=Y[:J];break
else:l=Y[:J]
print I.replace(f,l,1),Y.replace(l,f,1)
```
[Try it here](http://ideone.com/ADFXEq)
[Answer]
# Japt, ~~26~~ 25 bytes
Fortunately, I added a vowel class to Japt's regex features a few days ago. Unfortunately, I didn't add a non-vowel class or a way around the double backslashes in regex strings.
```
#¿s4 £Uf"[^\\v]+|.+
?" gX
```
The `¬ø` should be the raw char U+0093. Input is a multi-line string, one word/line. [Try it online!](http://ethproductions.github.io/japt?v=master&code=I5NzNCCjVWYiW15cXHZdK3wuKwo/IiBnWA==&input=InBsYXN0ZXIKbWFuIg==)
**EDIT:** I've now added the non-vowel class `\V` and a way around `\\` (with `%`), so this code now works for **21 bytes**: ([Try it online](http://ethproductions.github.io/japt?v=master&code=I5NzNCCjVWYiJVYrfC4rCj8iIGdY&input=InBsYXN0ZXIKbWFuIg==))
```
#¿s4 £Uf"%V+|.+
?" gX
```
### How it works
```
// Implicit: U = input string
#¬øs4 // Convert the char code (147) into a base-4 string "2103".
£ // Map each char X in this string to:
Uf"[^\\v]+|.+ // Match each group in U of non-vowels or non-newlines,
?" // with an optional trailing newline.
gX // Get the item at position X in the resulting array.
// Implicit: output last expression
```
### Old version (26 bytes):
```
UrA="\\b[^\\v ]+"@UfA gÂ!Y
```
[Try it online!](http://ethproductions.github.io/japt?v=master&code=VXJBPSJcXGJbXlxcdiBdKyJAVWZBIGfCIVk=&input=InBsYXN0ZXIgbWFuIg==)
### How it works
```
UrA="\\b[^\\v ]+"@UfA gÂ!Y // Implicit: U = input string
A="\\b[^\\v ]+" // Set variable A to this regex string, which matches
// a word boundary followed by one or more non-vowels.
UrA @ // Take U and replace each match X of A and its index Y with:
UfA // Take U.match(A).
gÂ!Y // Get the item at index ~~!Y (converts 0 to 1, anything else to 0).
// Implicit: output last expression
```
[Answer]
# Python 3, 100 (or 99) bytes
```
import re
def f(*g):a,b=[re.split("[aeiou]",r)[0] for r in g];return b+g[0][len(a):],a+g[1][len(b):]
```
Played with a few versions but can't seem to get it below. Can get it down 99 bytes by using `def f(g)` instead so it takes a list of strings rather than two seperate strings, but I prefer the two arg roue.
The alternative is equal length:
```
import re
s=re.split
def f(x,y):v="[aeiou]";a,b=s(v,x)[0],s(v,y)[0];return b+x[len(a):],a+y[len(b):]
```
I tried replace, like @TanMath uses, but I couldn't get it any shorter. Also, TanMath can get his answer shorter by a byte by also using `"[aeiou]"` instead of `"[aeiou]+"` because we only need to match the single instances. Finally, the implementation of `input()` seems to have changed between py2 and py3 - it automatically evaluates stdin as a string.
[Answer]
# C#6, 165 bytes
```
string S(string a,string b){int i=V(a),j=V(b);return b.Remove(j)+a.Substring(i)+" "+a.Remove(i)+b.Substring(j);}int V(string s)=>s.IndexOfAny("aeiou".ToCharArray());
```
Expanded:
```
string S(string a,string b){
int i=V(a),
j=V(b);
return b.Remove(j)+a.Substring(i)+" "+a.Remove(i)+b.Substring(j);
}
int V(string s)=>s.IndexOfAny("aeiou".ToCharArray());
```
[Answer]
# ùîºùïäùïÑùïöùïü, 24 chars / 42 bytes
```
ïē/⟮(⁅ᶌ]+)⟯(.+ )Ⅰ/,`⑶⑵⑴`
```
`[Try it here (Firefox only).](http://molarmanful.github.io/ESMin/interpreter2.html?eval=false&input=blushing%20crow&code=%C3%AF%C4%93%2F%E2%9F%AE%28%E2%81%85%E1%B6%8C%5D%2B%29%E2%9F%AF%28.%2B%20%29%E2%85%A0%2F%2C%60%E2%91%B6%E2%91%B5%E2%91%B4%60)`
If you need help comprehending this, this translates to ES6 as
```
input.replace(/([^aeiou]+)(.+ )([^aeiou]+)/g,'$3$2$1')
```
[Answer]
# PowerShell, 52 bytes
```
"$args "-replace('(.*?)([aeiou]\S+) '*2),'$3$2 $1$4'
e.g.
PS C:\scripts\> .\Spoonerise.ps1 'blushing crow'
crushing blow
```
It's a regex replace with four capture groups; with:
* String multiplication to expand:
+ `('(.*?)([aeiou]\S+) '*2)` to `'(.*?)([aeiou]\S+) (.*?)([aeiou]\S+) '`
* The `"$args "` forces the args array into a string, and adds a trailing space so the trailing space in the regex won't break it.
[Answer]
# JavaScript (ES6), ~~120~~ ~~107~~ ~~102~~ ~~101~~ ~~99~~ 92 bytes
* Thanks downgoat!
This takes into account if the parameters were an object like this, and backward:
`var a = {x: "man", y:"plaster"]}`
```
a.b=(e=>e.slice(e.search`[aeiou]`));with(a){c=b(x),d=b(y),x=x.replace(c,d);y=y.replace(d,c)}
```
[Answer]
# Python, ~~129~~ ~~108~~ ~~105~~ 109 bytes
This program takes in a list of words like this
`["master","plan"]`
**EDIT**: Thanks @Volatility
**EDIT:** Now using re.split
```
import re
a=re.split
c='[aeiou]+'
i,j=input()
f=a(c,i)[0]
l=a(c,j)[0]
print i.replace(f,l,1),j.replace(l,f,1)
```
This answer uses regex as most of them do.
[Try it here](http://ideone.com/F6074z)
[Answer]
# Java 8, 343 Bytes
Here you have your first Java-Answer. Not that experienced with golfing, so every suggestion is appreciated!
```
java.util.function.Function;public class C{public static void main(String[] a){Function<String, Integer>f=s->{for(int i=0;i<s.length();++i)if("aeiou".contains(s.substring(i,i+1)))return i;return 0;};int i1=f.apply(a[0]),i2=f.apply(a[1]);System.out.println(a[1].substring(0,i2)+a[0].substring(i1)+" "+a[0].substring(0,i1)+a[1].substring(i2));}}
```
Ungolfed:
```
public class SpooneriseWords {
public static void main(String[] args)
{
Function<String, Integer> f = s -> {
for(int i = 0; i < s.length(); ++i)
if("aeiou".contains(s.substring(i, i + 1)))
return i;
return 0;
};
int i1 = f.apply(args[0]);
int i2 = f.apply(args[1]);
System.out.println(args[1].substring(0, i2) + args[0].substring(i1));
System.out.println(args[0].substring(0, i1) + args[1].substring(i2));
}
}
```
[Answer]
## Octave, 96 bytes
Thanks to Octave's inline assignments and 'index-anywhere' functionality, this entire thing is just the definition of a single, anonymous function. Basically, we reconstruct the spoonerized string while storing the cut-off points in `a` and `b`. I'm especially happy with the inline `f` function, which finds the cut-off point, and prevented me from having to use the whole '`find(ismember(a,b),1)`' thing twice. Also, **no regex :)**.
```
@(p,q)[q(1:(a=(f=@(m)find(ismember(m,'aeoui'),1))(q))-1),p(b=f(q):end),32,p(1:b-1),q(a:end)];
```
[Answer]
# Python (no regexes), 85 bytes
```
t=lambda s:s[1]in'aeiou'or-~t(s[1:])
lambda a,b:(b[:t(b)]+a[t(a):],a[:t(a)]+b[t(b):])
```
Sample run:
```
>>> t=lambda s:s[1]in'aeiou'or-~t(s[1:])
>>> lambda a,b:(b[:t(b)]+a[t(a):],a[:t(a)]+b[t(b):])
<function <lambda> at 0x7f495e534398>
>>> _('plaster', 'man')
('master', 'plan')
```
`t` is a recursive function that computes the index of the earliest vowel after the first character in its argument `s`. If the second character `s[1]` is a vowel, it evaluates to `True`, which has `int` value `1`. Otherwise it makes a recursive call with the first character removed, and adds 1 to the resulting index using `-~` (two’s complement of one’s complement). Finally, the results of `t` are used as indices for string slicing to compute the spoonerism.
[Answer]
# [TeaScript](http://github.com/vihanb/teascript), 27 bytes
```
xg/(\w+)(.+ )(\w+)/,"$3$2$1
```
`\w` is actually `[^aeiou]`.
[Answer]
# PowerShell, 61 bytes
```
"$args"-replace'([^aeiou]+)(.*)\s([^aeiou]+)(.*)','$3$2 $1$4'
```
Uses regex to swap the first non-vowel characters of each word
[Answer]
# [Elixir](http://elixir-lang.org), ~~143~~ 117 Bytes
```
s=fn w->String.split_at(w,elem(hd(Regex.run(~r/[aeiou]/,w,return: :index)),0))end
{v,w}=s.(a)
{x,y}=s.(b)
[x<>w,v<>y]
```
Split up the two strings (a, b) on the first vowel and construct new strings to return.
EDIT: Got a few bytes off by using pattern matching instead of clunky `elem` calls to get the values out of the tuples.
[Answer]
# Java, 147 Bytes
I'm assuming just a function is fine too.
```
String s(String[]i){String r="[aeiou]",f=i[0].split(r)[0],s=i[1].split(r)[0];return s+i[0].substring(f.length())+" "+f+i[1].substring(s.length());}
```
`split(regex)` unfortunately consumes the delimiter, which means that I have to use `substring` to get the suffixes.
[Answer]
# Pyth, ~~30~~ 28 bytes
Takes input and gives output as a list of the two words.
```
ACm,Kh:d"[aeiou]"3.-dKQ+V_GH
```
[Try it online.](http://pyth.herokuapp.com/?code=ACm%2CKh%3Ad%22%5Baeiou%5D%223.-dKQ%2BV_GH&input=%5B%22master%22%2C%20%22plan%22%5D&test_suite=1&test_suite_input=%5B%22plaster%22%2C%20%22man%22%5D%0A%5B%22blushing%22%2C%20%22crow%22%5D%0A%5B%22litigating%22%2C%20%22more%22%5D%0A%5B%22strong%22%2C%20%22wrangler%22%5D%0A%5B%22def%22%2C%20%22ghi%22%5D&debug=0)
[Answer]
## Brainfuck, 141 bytes
```
,[[[<+>>+<-]----[>-----<--]>+[++++++[++++++[++++[++++[,>]]]]]<]<[>+<-]>>>+[,[[<+
>>+<-]++++[>--------<-]]>]>,]<<<<[[<]<[<]>[.,+>]+<]>[-[+.,]>]
```
Formatted:
```
,
[
[
[<+> >+<-]
----[>-----<--]>+
[
not u
++++++
[
not o
++++++
[
not i
++++
[
not e
++++
[
not a
,>
]
]
]
]
]
<
]
<[>+<-]>>>+
[
,
[
[<+> >+<-]
++++[>--------<-]
]
>
]
>,
]
<<<<
[
[<]<[<]
>[.,+>]
+<
]
>[-[+.,]>]
```
Expects the two words separated by a space, with or without a trailing newline.
[Try it online.](http://brainfuck.tryitonline.net/#code=LFtbWzwrPj4rPC1dLS0tLVs-LS0tLS08LS1dPitbKysrKysrWysrKysrK1srKysrWysrKytbLD5dXV1dXTxdPFs-KzwtXT4-PitbLFtbPCs-Pis8LV0rKysrWz4tLS0tLS0tLTwtXV0-XT4sXTw8PDxbWzxdPFs8XT5bLiwrPl0rPF0-Wy1bKy4sXT5d&input=cGxhc3RlciBtYW4)
This takes the input and stores it on the tape with three zero cells added: one before the first vowel of each word, and one after the space between the two words. For example, `plaster man` becomes:
`pl\x00aster \x00m\x00an`
The three fragments `m`, `aster`, and `pl` are then printed by looping backwards through the tape while creating dummy `\x01` cells, and the final `an` is printed by going forwards and ignoring the dummy cells.
] |
[Question]
[
According to some [controversial story](http://www.mrc-cbu.cam.ac.uk/people/matt.davis/Cmabrigde/), the odrer of ltteres in a wrod deos not mttaer much for raednig, as lnog as the frist and lsat lteter macth with the orignial wrod.
So, for fun, what would be the shortest function to randomize letter order in a word while keeping the first and the last letter in place?
Here's my stab at it with JavaScript. All whitespace removed it's at 124 130 characters.
```
function r(w) {
var l=w.length-1;
return l<3?w:w[0]+w.slice(1,l).split("").sort(function(){return Math.random()-.5}).join("")+w[l];
}
```
Shorter JavaScript always welcome.
---
* Edit: length check added. Function should not fail for short words.
[Answer]
# Haskell, ~~110~~ ~~120~~ 107 characters
```
import Random
s l=randomRIO(1,length l-2)>>=g.($l).splitAt
g(a:b,c:d)=fmap(a:).s$c:b++d
g(a,b)=return$a++b
```
An example of a program using this function:
```
main = getLine >>= s >>= putStrLn
```
[Answer]
## J, 26 24 23 characters
```
r=:{.,({~?~@#)&}.&}:,{:
```
[Answer]
### Ruby, 44 characters
```
r=->w{w[h=1..-2]=[*w[h].chars].shuffle*"";w}
```
Works also for short words, i.e. words with one, two or three characters are returned unaltered.
*Edit:* Using the array-splat idea of Ventero saves another char.
[Answer]
## Ruby 1.9, 46 characters
```
r=->w{w[0]+[*w[1..-2].chars].shuffle*""+w[-1]}
```
[Answer]
## C++, 79 characters (*with range check*)
```
string f(string s){if(s.size()>3)random_shuffle(&s[1],&s.end()[-1]);return s;}
```
## C++, ~~81~~ 65 characters (*without range check*)
```
string f(string s){random_shuffle(&s[1],&s.end()[-1]);return s;}
```
Using pass by reference instead of returning the result shaves off another 10 characters from either solution.
Full program, reading a string of words and shuffling converting them:
```
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <ctime>
#include <string>
using namespace std;
string f(string s){if(s.size()>3)random_shuffle(&s[1],&s.end()[-1]);return s;}
int main() {
std::srand(std::time(0));
std::string s;
while(std::cin >> s)
std::cout << f(s) << " ";
std::cout << std::endl;
}
```
Morale: don’t build what’s already there. ~~Oh, and overflow checks are for wusses.~~
[Answer]
# **C (K&R) - 88 ~~86~~ ~~87~~ chars**
```
r(char*s){int m,j,l=strlen(s)-2,i=l;while(--i>0){j=rand()%l+1;m=s[j];s[j]=s[1];s[1]=m;}}
```
There's no build-in swap or shuffle function in C, so I had to do it manually :(
Sample Program with Ungolfed r():
```
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <stdlib.h>
// -----------------------------------------------------------------------
r( char *s )
{
int m, j, l=strlen(s)-2, i=l;
while (--i>0)
{
j = rand() % l + 1;
m = s[j];
s[j] = s[1];
s[1] = m;
}
}
// -----------------------------------------------------------------------
int main()
{
char s[] = "anticipated";
srand( time(0) );
r( s );
puts( s );
return 0;
}
```
**EDIT**: fixed the bug when s consists of less than 3 chars (thanks to user-uknown for noticing it! )
[Answer]
## Python, ~~87~~ ~~79~~ ~~75~~ ~~93~~ 92 chars
```
from random import*
f=lambda w:w if 4>len(w)else w[0]+''.join(sample(w[1:-1],len(w)-2))+w[-1]
```
EDIT: Originally thought it was supposed to split string words (which it did at 128 chars; now at 87 chars does requirement). Argh, my bad at reading comprehension.
EDIT 2: Change from def to lambda function from def to save 6 chars. Assuming sample is already imported to the namespace (`from random import sample`) could bring this down to ~60).
EDIT 3: "len(w[1:-1])" (12 chars) to "len(w)-2" (8 chars) per gnibbler's nice suggestion.
EDIT 4: JBernando saved one char (had considered `from random import *` and saw it was equivalent -- not realizing the space in `import *` is unnecessary).; user unknown added 19 chars `w if len(w)<4 else` to handle 0 and 1 char strings correctly.
EDIT 5: Saved another char per boothby's code golf trick. `if len(w)<4 else` to `if 4>len(w)else`.
[Answer]
# C++, 111 97 chars
```
std::string f(std::string s){for(int i=s.size()-1;i>1;std::swap(s[rand()%i+1],s[--i]));return s;}
```
Here is a full program for those who wish to test it:
```
#include<string>
#include<iostream>
std::string f(std::string s){for(int i=s.size()-1;i>1;std::swap(s[rand()%i+1],s[--i]));return s;}
int main(){
for(int i = 0; i<100; ++i)
std::cout<<f("letters")<<std::endl;
}
```
# Edit
Realised there is no need to random both swap indexes, saved a variable and a few more characters.
[Answer]
# php (68 characters)
```
$r=preg_replace('/^(\w)(\w+)(\w)$/e','$1.str_shuffle($2).$3',trim($w));
```
# shorter (60 characters)
```
$r=preg_replace('/(.)(.+)(.)/e','$1.str_shuffle($2).$3',$w);
```
[Answer]
## Perl - 96 (or 71) characters 84 (or 59) characters
This is what I came up with in Perl. Went through a few different ways to do it but this seemed shortest from what I can think of so far, at 97 characters.
```
use List::Util 'shuffle';sub r{($b,@w)=split//,$_[0];$e=pop(@w);return$b.join('',shuffle@w).$e;}
```
Though, if you cut out the 'use' line (which I guess is valid, since others excluded #include lines in their C programs) I can cut it down further to **71 characters**:
```
sub r{($b,@w)=split//,$_[0];$e=pop(@w);return$b.join('',shuffle@w).$e;}
```
**EDIT**
It was suggested that I try doing this implementing @tobius' method. This way I got it down to **84 characters**, or by removing the *use* line, **59 characters**:
```
use List::Util 'shuffle';sub r{$_[0]=~m/(.)(.+)(.)/;$1.join'',shuffle split//,$2.$3}
```
[Answer]
## Ruby, 77 75 characters
```
def r(s);f=s.size-2;1.upto(f){|i|x=rand(f)+1;t=s[i];s[i]=s[x];s[x]=t};s;end
```
My Scala solution in a slightly less verbose language. I'm not a Ruby expert by any means, so there's probably room for improvement.
[Answer]
**Ruby 1.9, 77 48 46 44 chars**
```
r=->w{w[h=1..-2]=[*w[h].chars].shuffle*"";w}
```
Disclaimer: I tuned this based on the highest ranked answer - noticed the exact same answer later on. You can check the history that I have kept true to my original idea but changed from ruby 1.8 to ruby 1.9 for short lambdas and `shuffle`.
If empty words are allowed then 56 54 chars
```
r=->w{w.empty?||w[h=1..-2]=[*w[h].chars].shuffle*"";w}
```
[Answer]
# Python 3, ~~94~~ ~~93~~ 91 characters
Using a different technique. Might also work in Python 2.
```
from random import*
s=lambda x:x[0]+''.join(sample(x[1:-1],len(x)-2))+x[-1]if x[0:-1]else x
```
The `... if x[0:-1] else x` gives `x` if its length is 1 (otherwise it would be duplicated). The function thereby works for strings of length 0 and 1.
The `sample()` is from <https://stackoverflow.com/questions/2668312/shuffle-string-in-python/2668366#2668366>.
Since it's one expression, we can use a `lambda` (eliminating `return`, `def`, and a pair of parentheses).
**Edit:** `from random import*` to save 1 character, after the other Python submission.
[Answer]
## D, 62 chars
```
import std.random;void s(char[] s){randomShuffle(s[1..$-1]);}
```
okay I cheated with a normal char array instead of a real string (which is immutable char[] so no in-place shuffling)
**edit** with a length check it requires 14 more
```
import std.random;void s(char[] s){if(s.length>1)randomShuffle(s[1..$-1]);}
```
[Answer]
## php 5.3 (60 chars)
```
$r=!$w[2]?:$w[0].str_shuffle(substr($w,1,-1)).substr($w,-1);
```
**Improved to 56 chars and no longer requires version 5.3:**
```
$r=substr_replace($w,str_shuffle(substr($w,1,-1)),1,-1);
```
[Answer]
**Python, 86 chars**
Slnicig is safe, so no bnouds ckhnceig is neeacrssy. Wkros on all
leghtns.
```
from random import*
def f(x):x=list(x);t=x[1:-1];shuffle(t);x[1:-1]=t;return''.join(x)
```
[Answer]
# JavaScript - 118 122 125 chars
Uses approximately the same algorithm as the OP, but with less chaining. I tried a lot of recursion, and I tried some iteration, but they all tend to get bogged down in some way or another.
```
function s(w){w=w.split('');var a=w.shift(),z=w.pop();return z?a+(w.sort(function(){return Math.random()-.5}).join(''))+z:a;}
```
Ungolfed:
```
function s(w)
{
w = w.split('');
var a = w.shift(),
z = w.pop();
return z?a + (w.sort(function() { return Math.random() - .5}).join('')) + z:a;
}
```
[Answer]
**Perl - 111 characters (without using any library function)**
```
sub r{($f,@w)=split//,shift;$l=pop@w;while(@w){if(rand(9)>1){push@w,shift@w}else{push@t,pop@w}}join'',$f,@t,$l}
```
[Usage](http://ideone.com/XUEie):
```
$in="randomizethis";
$out = &r($in);
print "\nout: $out";
sub r{($f,@w)=split//,shift;$l=pop@w;while(@w){if(rand(9)>1){push@w,shift@w}else{push@t,pop@w}}join'',$f,@t,$l}
```
[Answer]
# Python
It's 90 89 112 characters of python!
## Edit 1: as a function this time!
(thanks gnibbler)
## Edit 2: now handles short words
(thanks user unknown)
```
import random as r
def q(s):
a=list(s)
b=a[1:-1]
r.shuffle(b)
if len(s)<4:
return s
return a[0]+''.join(b)+a[-1]
```
[Answer]
## Scala, 135 139 142 156 characters
```
def r(s:String)={var(x,o,t,f)=(0,s.toArray,' ',s.size-2)
for(i<-1 to f){t=o(i)
x=util.Random.nextInt(f)+1
o(i)=o(x)
o(x)=t}
o.mkString}
```
-7: removed ':String' (return type can be inferred)
-7: removed 'return ' (last expression is the return value)
-3: factored `s.size-2` out
-4: `toCharArray` -> `toArray`
[Answer]
# C++11: - 68 66 chars
```
auto f=[&](){if(s.size()>2)random_shuffle(s.begin()+1,s.end()-1);};
```
full program:
```
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main(int argc, char* argv[]){
string s = "SomestrinG";
auto f=[&](){if(s.size()>2)random_shuffle(s.begin()+1,s.end()-1);};
f();
cout << s << endl;
return 0;
}
```
[Answer]
# Python - 76 characters
```
import random as r
def f(w):m=list(w)[1:-1];r.shuffle(m);return w[0]+''.join(m)+w[-1]
```
[Answer]
## R, 104 (126)
```
f=function(w){s=strsplit(w,"")[[1]];paste(c(s[1],sample(s[2:(length(s)-1)]),s[length(s)]),collapse="")}
```
Usage:
```
for (i in 1:10) print(f("parola"))
[1] "plraoa"
[1] "prolaa"
[1] "praola"
[1] "parloa"
[1] "plaora"
[1] "palroa"
[1] "porlaa"
[1] "ploraa"
[1] "porlaa"
[1] "ploraa"
```
the below function works with words with length less than 3:
```
f=function(w){s=strsplit(w,"")[[1]];ifelse(length(s)<3,w,paste(c(s[1],sample(s[2:(length(s)-1)]),s[length(s)]),collapse=""))}
f("pl")
[1] "pl"
f("a")
[1] "a"
```
[Answer]
# R, ~~95~~ ~~92~~ 91 characters
```
f=function(w,a=el(strsplit(w,'')),b=length(a))cat(a[1],sample(a[c(1,b)],b-2),a[b],sep="")
```
Makes use of R's lazy evaluation to compute a and b as function parameters, saving space with re-use later on. Also unlike other R answer this works for all words >1 char long.
Example below:
```
> f("hippopotamus")
hpuoopaitmps
> f("dog")
dog
> f("az")
az
```
Edit: ~~Replaced `unlist()` with `[[]]`~~ Replaced [[1]] with el()
[Answer]
# D: 55 characters
```
void f(T)(T s){if(s.length>2)randomShuffle(s[1..$-1]);};
```
full program:
```
import std.stdio, std.random, std.conv;
void f(T)(T s){if(s.length>2)randomShuffle(s[1..$-1]);};
void main(){
char[] s = to!(char[])("SomestrinG");
f(s);
writeln(s);
}
```
[Answer]
# Erlang, 188 172 132 chars
```
f([H|C=[_|_]])->T=[lists:last(C)],[H|s(C--T,T)];f(X)->X. s([],N)->N;s(D,N)->E=[lists:nth(random:uniform(length(D)),D)],s(D--E,E++N).
```
I'm still learning Erlang so any tips on making this shorter are appreciated.
full code(string\_shuffle module):
```
-module(string_shuffle).
-export([f/1]).
f([H|C=[_|_]])->
T=[lists:last(C)],
[H|s(C--T,T)];f(X)->X.
f(X)->X.
s([],N)->N;
s(D,N)->
E=[lists:nth(random:uniform(length(D)),D)],
s(D--E,E++N).
```
## Edit
Took the shuffle part out as a seperate function which no longer requires the head and tail of the list to be passed around.
## Edit 2
Restructured to remove one of the `f`function patterns, changed the shuffle function to accept only two parameters, changed `lists:delete` for `--[]`, swapped a `lists:reverse` call for a `lists:last`
[Answer]
## PowerShell, 93
```
filter x{if($_.length-lt3){$_}else{$_[0,-1]-join-join($_[1..($a=$_.Length-2)]|random -c $a)}}
```
Look, double-join~~t~~ed code!
[Answer]
# C#, 128
```
static string r(string w){var t="";while(w.Length>1){int n=new Random().Next(1,w.Length-1);t+=w[n];w=w.Remove(n,1);}return w+t;}
```
[Answer]
## Scala: 94
```
def r(w:String)=if(w.size<2)w else w(0)+util.Random.shuffle(w.tail.init.toSeq).mkString+w.last
```
This is a riff on "user unknowns" answer. Since a String can be implicitly cast to a Seq of chars, we can leverage Seq methods to access the middle and end of the String.
[Answer]
# Groovy, 75
```
r={w->w.size()<3?w:w[0]+w[1..-2].toList().sort{Math.random()}.join()+w[-1]}
assert r('a') == 'a'
assert r('it') == 'it'
assert r('cap') == 'cap'
for(x in 1..10) {
def w = r('Honorificabilitudinitatibus')
println w
assert w.size()==27 && w[0]=='H' && w[26]=='s'
}
```
] |
[Question]
[
[XKCD #99](http://xkcd.com/99/), with the title "Binary Heart" shows a simple image of ones and zeros, with some digits colored red.
[![enter image description here](https://i.stack.imgur.com/Lc6Fu.jpg)](https://i.stack.imgur.com/Lc6Fu.jpg)
The red heart is visible to the naked eye, but the message hidden in the binary sequence is not. If you remove all the spaces and newlines and interpret the binary sequence as 8 bit ASCII-code, you'll end up with the message:
```
iloveyOuilOveyouiloveyOuilOveyOuiloveyouilOveyouilOveyOuilOv
```
**Cute right?**
Pssst... The string isn't a pure string repetition.
---
Your challenge is to create this binary image with 21 digits across, and 23 digits down. **There should be exactly one space between each digit in each row, and one newline for each new row.** Note that the last bits are only the beginning of the letter `e`, since `21*23` isn't divisible by 8. You need those bits correct too.
The function or program should not take any input. Leading and trailing spaces and newlines are accepted.
The result of your code should look like this:
```
0 1 1 0 1 0 0 1 0 1 1 0 1 1 0 0 0 1 1 0 1
1 1 1 0 1 1 1 0 1 1 0 0 1 1 0 0 1 0 1 0 1
1 1 1 0 0 1 0 1 0 0 1 1 1 1 0 1 1 1 0 1 0
1 0 1 1 0 1 0 0 1 0 1 1 0 1 1 0 0 0 1 0 0
1 1 1 1 0 1 1 1 0 1 1 0 0 1 1 0 0 1 0 1 0
1 1 1 1 0 0 1 0 1 1 0 1 1 1 1 0 1 1 1 0 1
0 1 0 1 1 0 1 0 0 1 0 1 1 0 1 1 0 0 0 1 1
0 1 1 1 1 0 1 1 1 0 1 1 0 0 1 1 0 0 1 0 1
0 1 1 1 1 0 0 1 0 1 0 0 1 1 1 1 0 1 1 1 0
1 0 1 0 1 1 0 1 0 0 1 0 1 1 0 1 1 0 0 0 1
0 0 1 1 1 1 0 1 1 1 0 1 1 0 0 1 1 0 0 1 0
1 0 1 1 1 1 0 0 1 0 1 0 0 1 1 1 1 0 1 1 1
0 1 0 1 0 1 1 0 1 0 0 1 0 1 1 0 1 1 0 0 0
1 1 0 1 1 1 1 0 1 1 1 0 1 1 0 0 1 1 0 0 1
0 1 0 1 1 1 1 0 0 1 0 1 1 0 1 1 1 1 0 1 1
1 0 1 0 1 0 1 1 0 1 0 0 1 0 1 1 0 1 1 0 0
0 1 0 0 1 1 1 1 0 1 1 1 0 1 1 0 0 1 1 0 0
1 0 1 0 1 1 1 1 0 0 1 0 1 1 0 1 1 1 1 0 1
1 1 0 1 0 1 0 1 1 0 1 0 0 1 0 1 1 0 1 1 0
0 0 1 0 0 1 1 1 1 0 1 1 1 0 1 1 0 0 1 1 0
0 1 0 1 0 1 1 1 1 0 0 1 0 1 0 0 1 1 1 1 0
1 1 1 0 1 0 1 0 1 1 0 1 0 0 1 0 1 1 0 1 1
0 0 0 1 0 0 1 1 1 1 0 1 1 1 0 1 1 0 0 1 1
```
This is code golf, so the shortest answer (in bytes) wins.
---
## Leaderboard
```
var QUESTION_ID=94699,OVERRIDE_USER=31516;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
```
```
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
```
```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~41 40 35~~ 33 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
Thanks to @Dennis for making the end `ṖṖCG`! (complement `C` = `1-x` in place of logical not `¬` )
```
“ƝƓỊ⁹Ȥ⁶Ị⁺‘ẋ8_“¤ÐŒ#'/‘¦32BFs21ṖṖCG
```
**[TryItOnline](http://jelly.tryitonline.net/#code=4oCcxp3Gk-G7iuKBucik4oG24buK4oG64oCY4bqLOF_igJzCpMOQxZIjJy_igJjCpjMyQkZzMjHhuZbhuZZDRw&input=&args=)**
### How?
```
“ƝƓỊ⁹Ȥ⁶Ị⁺‘ẋ8_“¤ÐŒ#'/‘¦32BFs21ṖṖCG - Main link: no arguments
“ƝƓỊ⁹Ȥ⁶Ị⁺‘ - code page indexes [150,147,176,137,154,134,176,138]
(bitwise negated values of ordinals of "ilOveyOu")
ẋ8 - repeat eight times
_ - subtract
¦ - apply to indexes
“¤ÐŒ#'/‘ - code page indexes [3,15,19,35,39,47]
(the indexes of the lowercase Os)
32 - literal 32 (subtracting 32 from the bitwise negated
'O's makes them bitwise negated 'o's)
B - binary (all are 8 bits, hence the negation)
F - flatten list
s21 - split into slices of length 21
ṖṖ - pop (remove the last two slices)
C - complement (transform the bits to what they should be)
G - format as a grid
(inserts both the spaces and line feeds)
```
---
### "Colour" version, 77 bytes
```
“¤Ɓ¥J¬ ¥ƲėNėR½5ðḃḍCṬ’b19‘“Y^‘jĖŒṙḂ
“ƝƓỊ⁹Ȥ⁶Ị⁺‘ẋ8_“¤ÐŒ#'/‘¦32BFż¢Ḅị“¹0°1”s21ṖṖG
```
**[TryItOnline](http://jelly.tryitonline.net/#code=4oCcwqTGgcKlSsKsIMKlxrLEl07El1LCvTXDsOG4g-G4jUPhuazigJliMTnigJjigJxZXuKAmGrElsWS4bmZ4biCCuKAnMadxpPhu4rigbnIpOKBtuG7iuKBuuKAmOG6izhf4oCcwqTDkMWSIycv4oCYwqYzMkJGxbzCouG4hOG7i-KAnMK5MMKwMeKAnXMyMeG5luG5lkc&input=)**
Jelly has no colour output, but this is much easier for me to see anyway (I am colour blind)...
```
° ¹ ¹ ° ¹ ° ° ¹ ° ¹ ¹ ° ¹ ¹ ° ° ° ¹ ¹ ° ¹
¹ ¹ ¹ ° ¹ ¹ ¹ ° ¹ ¹ ° ° ¹ ¹ ° ° ¹ ° ¹ ° ¹
¹ ¹ ¹ ° ° ¹ ° ¹ ° ° ¹ ¹ ¹ ¹ ° ¹ ¹ ¹ ° ¹ °
¹ ° ¹ ¹ ° ¹ ° ° ¹ ° ¹ ¹ ° ¹ ¹ ° ° ° ¹ ° °
¹ ¹ ¹ ¹ ° 1 1 1 ° ¹ ¹ ° ° 1 1 0 ° ¹ ° ¹ °
¹ ¹ ¹ 1 0 0 1 0 1 1 ° 1 1 1 1 0 1 1 ¹ ° ¹
° ¹ ° 1 1 0 1 0 0 1 ° 1 1 0 1 1 0 0 ° ¹ ¹
° ¹ ¹ 1 1 0 1 1 1 0 1 1 0 0 1 1 0 0 1 ° ¹
° ¹ 1 1 1 0 0 1 0 1 0 0 1 1 1 1 0 1 1 ¹ °
¹ ° 1 0 1 1 0 1 0 0 1 0 1 1 0 1 1 0 0 ° ¹
° ° ¹ 1 1 1 0 1 1 1 0 1 1 0 0 1 1 0 0 ¹ °
¹ ° ¹ 1 1 1 0 0 1 0 1 0 0 1 1 1 1 0 ¹ ¹ ¹
° ¹ ° ¹ 0 1 1 0 1 0 0 1 0 1 1 0 ¹ ¹ ° ° °
¹ ¹ ° ¹ ¹ 1 1 0 1 1 1 0 1 1 0 0 ¹ ¹ ° ° ¹
° ¹ ° ¹ ¹ ¹ 1 0 0 1 0 1 1 0 1 ¹ ¹ ¹ ° ¹ ¹
¹ ° ¹ ° ¹ ° ¹ 1 0 1 0 0 1 0 ¹ ¹ ° ¹ ¹ ° °
° ¹ ° ° ¹ ¹ ¹ ¹ 0 1 1 1 0 ¹ ¹ ° ° ¹ ¹ ° °
¹ ° ¹ ° ¹ ¹ ¹ ¹ ° 0 1 0 ¹ ¹ ° ¹ ¹ ¹ ¹ ° ¹
¹ ¹ ° ¹ ° ¹ ° ¹ ¹ ° 1 ° ° ¹ ° ¹ ¹ ° ¹ ¹ °
° ° ¹ ° ° ¹ ¹ ¹ ¹ ° ¹ ¹ ¹ ° ¹ ¹ ° ° ¹ ¹ °
° ¹ ° ¹ ° ¹ ¹ ¹ ¹ ° ° ¹ ° ¹ ° ° ¹ ¹ ¹ ¹ °
¹ ¹ ¹ ° ¹ ° ¹ ° ¹ ¹ ° ¹ ° ° ¹ ° ¹ ¹ ° ¹ ¹
° ° ° ¹ ° ° ¹ ¹ ¹ ¹ ° ¹ ¹ ¹ ° ¹ ¹ ° ° ¹ ¹
```
### How?
```
“¤Ɓ¥J¬ ¥ƲėNėR½5ðḃḍCṬ’b19‘“Y^‘jĖŒṙḂ - Link 1: no arguments
“¤Ɓ¥J¬ ¥ƲėNėR½5ðḃḍCṬ’ - base 250 of a big number
b19 - convert to base 19, yields a list of integers
‘ - increment those numbers
“Y^‘ - get code page indexes [89,94]
j - join: [89,3,5,3,8, ... ,3,19,1,94]
- {left-right, top-bottom} runs of colours
Ė - enumerate [[1,89],[2,3],[3,5],[4,3],[5,8], ...]
Œṙ - run-length decode [89 1s, 3 2s, 5 3s, 3 4s, 8 5s, ...]
Ḃ - mod 2
“ƝƓỊ⁹Ȥ⁶Ị⁺‘ẋ8_“¤ÐŒ#'/‘¦32BFż¢Ḅị“¹0°1”s21ṖṖG - Main link: no arguments
“ƝƓỊ⁹Ȥ⁶Ị⁺‘ẋ8_“¤ÐŒ#'/‘¦32BF - same as the original to get 1s and 0s
ż - zip with
¢ - last link (1) as a nilad
Ḅ - binary to integer (vectorises)
ị - index into
“¹0°1” - string "¹0°1"
s21 - split into length 21 slices
ṖṖ - pop last two unused slices
G - format as a grid
```
[Answer]
## Actually, 58 bytes
```
73*8╙:13542├`≈"÷≥"E`M"«%s₧ªn%s6û"7*%"♠n≥6û"+¿├`' +`M╪♂Σ♂Ri
```
[Try it online!](http://actually.tryitonline.net/#code=NzMqOOKVmToxMzU0MuKUnGDiiYgiw7fiiaUiRWBNIsKrJXPigqfCqm4lczbDuyI3KiUi4pmgbuKJpTbDuyIrwr_ilJxgJyArYE3ilarimYLOo-KZglJp&input=)
### Explanation
There are three main parts here, so I'm going to break it down accordingly.
[**Part 1: Constructing the base-256 string**](http://actually.tryitonline.net/#code=OjEzNTQy4pScYOKJiCLDt-KJpSJFYE0iwqslc-KCp8KqbiVzNsO7IjcqJSLimaBu4omlNsO7Iis&input=)
We're actually going to construct the binary string reversed, to take advantage of Actually's stack-based (LIFO) structure and to avoid complications with leading zeros in the binary string. Thus, the target binary string is `110011011101111001000110110100101101010111011110010100111101010011001101110111100100011011010010110101011101111011010011110101001100110111011110010001101101001011010101110111101101001111010100110011011101111011000110110100101101010111011110010100111101010011001101110111100100011011010010110101011101111001010011110101001100110111011110110001101101001011010101110111101101001111010100110011011101111001000110110100101101010111011110010100111101010011001101110111101100011011010010110`, which is equivalent to `20083405242288679348048842451418880256193335738939042905519679590571514414673488599852759703515507690399267425671627412178904636115120346432419478` in decimal. In base-256 (using the [CP437 character table](https://en.wikipedia.org/wiki/Code_page_437#Characters) for conversion), the corresponding string is `♠n≥6û«≥₧ªn≥6û«÷₧ªn≥6û«÷₧ªn÷6û«≥₧ªn≥6û«≥₧ªn÷6û«÷₧ªn≥6û«≥₧ªn÷6û`. To construct the original binary string, we construct the base-256 string (taking advantage of the pattern in it), and perform base conversions to decimal and binary.
The base-256 string has the following format (spaces and newlines added for clarity):
```
♠n≥6û
« (either ≥ or ÷) ₧ªn (either ≥ or ÷) 6û
(7 times)
```
Thus, each of the 7 middle sections can be formed by using the scaffold `«%s₧ªn%s6û` and replacing the `%s` parts with either `≥` or `÷`.
The specific sequence of `≥`s and `÷`s we need is `≥≥÷≥÷÷≥≥≥÷÷≥≥÷`. Since we need this as a list of length-1 strings, the naïve way of representing this would be `"≥≥÷≥÷÷≥≥≥÷÷≥≥÷"#` (push the string, make it into a list). However, we can do slightly better. By interpreting that string as a binary number (where `≥` represents `1` and `÷` represents `0`), we get `13542` in decimal. By converting this back to binary (using the traditional `1`s and `0`s), and indexing into a length-2 string, we can get the list using one less byte than the naïve method.
```
:13542├`≈"÷≥"E`M"«%s₧ªn%s6û"7*%"♠n≥6û"+
:13542├ push 13542, convert to binary
`≈"÷≥"E`M for each bit:
≈ convert to integer (from string)
"÷≥"E index into "÷≥"
"«%s₧ªn%s6û"7* push the scaffold for the middle section
% old-style Python string formatting to fill in the scaffold
"♠n≥6û"+ prepend the beginning piece
```
[**Part 2: Converting to binary**](http://actually.tryitonline.net/#code=OOKVmSzCv-KUnA&input=IuKZoG7iiaU2w7vCq-KJpeKCp8KqbuKJpTbDu8Krw7figqfCqm7iiaU2w7vCq8O34oKnwqpuw7c2w7vCq-KJpeKCp8KqbuKJpTbDu8Kr4oml4oKnwqpuw7c2w7vCq8O34oKnwqpu4omlNsO7wqviiaXigqfCqm7DtzbDuyI)
This part is much more straightforward. If Actually had the capability to directly convert base-256 to binary, we'd use that. Unfortunately, it doesn't, so we'll have to use decimal as an intermediary format.
The `,` in the following code represents the code from Part 1 - for explanatory purposes, I've replaced the Part 1 code with `,` to read the output from Part 1 from STDIN. It is not part of the actual final code.
```
8╙,¿├
, Part 1 result
8╙ ¿ convert from base-256 to decimal
├ convert to binary
```
[**Part 3: Formatting**](http://actually.tryitonline.net/#code=NzMqLGAnICtgTeKVquKZgs6j4pmCUmk&input=IjExMDAxMTAxMTEwMTExMTAwMTAwMDExMDExMDEwMDEwMTEwMTAxMDExMTAxMTExMDAxMDEwMDExMTEwMTAxMDAxMTAwMTEwMTExMDExMTEwMDEwMDAxMTAxMTAxMDAxMDExMDEwMTAxMTEwMTExMTAxMTAxMDAxMTExMDEwMTAwMTEwMDExMDExMTAxMTExMDAxMDAwMTEwMTEwMTAwMTAxMTAxMDEwMTExMDExMTEwMTEwMTAwMTExMTAxMDEwMDExMDAxMTAxMTEwMTExMTAxMTAwMDExMDExMDEwMDEwMTEwMTAxMDExMTAxMTExMDAxMDEwMDExMTEwMTAxMDAxMTAwMTEwMTExMDExMTEwMDEwMDAxMTAxMTAxMDAxMDExMDEwMTAxMTEwMTExMTAwMTAxMDAxMTExMDEwMTAwMTEwMDExMDExMTAxMTExMDExMDAwMTEwMTEwMTAwMTAxMTAxMDEwMTExMDExMTEwMTEwMTAwMTExMTAxMDEwMDExMDAxMTAxMTEwMTExMTAwMTAwMDExMDExMDEwMDEwMTEwMTAxMDExMTAxMTExMDAxMDEwMDExMTEwMTAxMDAxMTAwMTEwMTExMDExMTEwMTEwMDAxMTAxMTAxMDAxMDExMCI)
If the challenge was to merely output the binary string as-is, we'd be done. However, we still have some formatting to do to get the binary string into a 21 x 23 rectangle.
As in Part 2, the `,` represents the output from the previous part, and is not part of the actual code.
```
73*,`' +`M╪♂Σ♂Ri
, output from Part 2
`' o`M insert a space after every character
73* ╪ chunk into 21 pieces
♂Σ concatenate each piece
♂R reverse each piece
i flatten
(implicitly print)
```
---
For those keeping track at home, this is the equivalent Python 3 code (481 bytes):
```
print('\n'.join([''.join(' '+c for c in bin(sum('\x00☺☻♥♦♣♠•◘○◙♂♀♪♫☼►◄↕‼¶§▬↨↑↓→←∟↔▲▼ !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~⌂ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜ¢£¥₧ƒáíóúñѪº¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■\xa0'.index(c)*256**i for i,c in enumerate(("♠n≥6û"+("«%s₧ªn%s6û"*7)%tuple("÷≥"[int(b)]for b in bin(13542)[2:]))[::-1])))[2:])[i*42:-~i*42][::-1]for i in range(23)][::-1]))
```
[Answer]
## JavaScript (ES6), ~~169~~ ... ~~136~~ 135 bytes
```
let f =
_=>"0213021203131214".replace(x=/./g,v=>0+[a=1768714102,a-8192,a-=66265089,a+8192,3][v].toString(2)).replace(x,(c,i)=>`
`[+!(i%21)]+c)
console.log(f());
```
*Saved 2 bytes thanks to Andrakis*
*Saved 4 bytes thanks to Hedi*
*Saved ~~3~~ 5 bytes thanks to Neil*
## Colored version, 249 bytes (237 bytes of JS + 12 bytes of CSS)
The JS code outputs the ASCII art with bold tags for the heart. 12 bytes of CSS are required to colorize in red. (Is that byte count fair?)
```
let f =
_=>"0213021203131214".replace(x=/./g,v=>0+[a=1768714102,a-8192,a-=66265089,a+8192,3][v].toString(2)).replace(x,(c,i)=>`
`[+!(y=i/21|0,x=i%21)]+([57568,a=261112,a,b=524280,b+4,b+4,b,a+1024,65520][y-4]&1<<x|y>12&x>y-9&x<29-y?c.bold():c))
document.getElementById("o").innerHTML = f();
```
```
b{color:red}
```
```
<pre id="o"></pre>
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~36~~ ~~33~~ 32 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
“ḅUɗaṚPXṙ’Bṁ484¬“½:J⁺ȤṾ‘Ḥ¤¦Ḋs21G
```
*Thanks to @JonathanAllan for golfing off 3 bytes!*
[Try it online!](http://jelly.tryitonline.net/#code=4oCc4biFVcmXYeG5mlBY4bmZ4oCZQuG5gTQ4NMKs4oCcwr06SuKBusik4bm-4oCY4bikwqTCpuG4inMyMUc&input=)
### How it works
The main link
```
“ḅUɗaṚPXṙ’Bṁ484¬“½:J⁺ȤṾ‘Ḥ¤¦Ḋs21G
```
is executed niladically (i.e., without any arguments) when the program is run. Its return value will be printed implicitly.
```
“ḅUɗaṚPXṙ’
```
find the indices of the quoted characters in [Jelly's code page](https://github.com/DennisMitchell/jelly/wiki/Code-page) and interprets them as digits of a bijective base 250 number. This yields the integer **13021639057551959994**.
```
B
```
converts the generated integer to binary. This yields the bit array **1011010010110110001001111011101100110010101111001010011110111010** which corresponds to the UTF-8 encoding of the string **ilOveyOu**, shifted one bit to the left.
Shifting is necessary because `B` cannot return a bit array with a leading **0**. Other options include negating the binary digits or computing the square in reverse, but this approach saves one byte.
```
ṁ484
```
molds the generated array like the range from **1** to **484**, i.e., it repeats the contents of the array as many times as necessary to achieve a length of **484**.
This is one more bit than we need, to account for the shift. We could remove the first bit now, but doing so later means that all bits that have to get swapped lie at even indices, which allows us to save the aforementioned byte.
```
“½:J⁺ȤṾ‘Ḥ¤
```
takes the code points of the characters between `“` and `‘` (**[10, 58, 74, 138, 154, 186]**), then "unhalves" them, i.e., multiples them by **2** (**[20, 116, 148, 276, 308, 372]**).
```
¬ ¦
```
conditionally negates the bits at those indices. This corresponds to the **O/o** variations in the original pattern.
Finally,
```
Ḋs21G
```
dequeues the bit array (removing the first bit), splits the remaining array into rows of **21** elements and prints the resulting matrix as a grid.
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), ~~77~~ ~~54~~ ~~53~~ ~~44~~ ~~43~~ 41 bytes
Uses [CP-1252](http://www.cp1252.com/) encoding.
```
’i„΀î’8ו1žä¿*•S·£™J¦'iìÇb0ìJ011JSðý42ô»
```
**Explanation**
```
’i„Î€î’ # the string "iloveyou"
8× # repeated 8 times
•1žä¿*• # the number 3262264221 encoded in base 214
S· # split to list and multiplied by 2, gives [6, 4, 12, 4, 4, 12, 8, 4, 4, 2]
£ # split the "iloveyou..." string into chunks of these lengths
™J # title-case the chunks and join, giving the string with capitalized O's
¦'iì # replace the faulty capitalized "I" in the beginning with a lower case "i"
Ç # convert to list of ascii values
b0ì # convert each to binary and prepend a 0 to each binary string
J011J # join the strings and append "011"
Sðý # add a space between each digit
42ô # split in pieces of 42 (21 digits, 21 spaces)
» # merge on newline
```
[Try it online!](http://05ab1e.tryitonline.net/#code=4oCZaeKAnsOO4oKsw67igJk4w5figKIxxb7DpMK_KuKAolPCt8Kj4oSiSsKmJ2nDrMOHYjDDrEowMTFKU8Oww700MsO0wrs&input=)
[Answer]
## [CJam](https://sourceforge.net/projects/cjam/), 48 bytes
```
19560Yb"Oo"f="uilvey"8*3/.\s:i2fb0a*7>21/W<Sf*N*
```
Collaboration with @MartinEnder, who took off a tricky 3 bytes with the `"uilvey"3/` string. [Online interpreter](http://cjam.aditsu.net/#code=19560Yb%22Oo%22f%3D%22uilvey%228*3%2F.%5Cs%3Ai2fb0a*7%3E21%2FW%3CSf*N*).
```
19560Yb Convert 19560 to base 2
"Oo"f= Index each bit into the string "Oo" to give "ooooOOooOOOooOoOOO"
"uilvey"8*3/ Repeat the string "uilvey" 8 times then split into chunks of 3
.\s Vectorised swap (insert the Os into the right places) then stringify
:i2fb Convert each char to int then take base 2
0a* Join with 0s
7> Remove the first 7 bits
21/ Split into chunks of length 21
W< Drop the last row
Sf* Join each row with spaces
N* Join the rows with newlines
```
[Answer]
# Javascript ES6 [REPL](http://meta.codegolf.stackexchange.com/questions/7842/when-is-code-that-requires-a-repl-acceptable/7844#7844), ~~124~~ ~~121~~ ~~119~~ 113 bytes
Saved 6 bytes thanks to *@ETHproductions*
This is a full program which can be pasted in the REPL/console to produce the correct result.
```
for(i=r='';i<483;)r+=(`il${"Oo"[21>>i/64&1]}vey${"oO"[77>>i/64&1]}u`.charCodeAt(i/8%8)>>7-i%8&1)+(++i%21?` `:`
`)
```
```
f=
_=>{for(i=0,r='';i<483;)r+=(`il${"Oo"[21>>(a=i/64)&1]}vey${"oO"[77>>a&1]}u`.charCodeAt(i/8%8)>>7-i%8&1)+(++i%21==0?`
`:` `);return r}
a.innerHTML = f()
```
```
<pre id=a>
```
More verbose
```
for (i=0, r=''; // r == the result
i < 483;) // 483 == 21 * 23
r+= ( // construct "iloveyou"
`il${ // il
"Oo"[21 >> (a = i/64) & 1] // position in the loop defines the o or O
}vey${ // vey
"oO"[77 >> a & 1] // position in the loop defines the o or O
}u` // u
.charCodeAt( // "i" == 105 == 01101001
i / 8 % 8 // find the correct bit to append
) >> 7-i%8 & 1 // shift it to select 1 or 0
)
+ // add a space or newline
(
++i%21 == 0 ? `
` : ` ` // every 21 characters add a new line,
otherwise a space
)
; // Javascript implicitly returns the last value
edited in a for loop
```
# Coloured JavaScript only heart, 281 bytes
```
for(i=z=r='',h=[],g=[90,...[...'353871767176G4H4H5G5F7CABB9D7F5H3J1'].map(n=>parseInt(n,20)),-1];i<483;)r+=`%c`+(`il${"Oo"[21>>i/64&1]}vey${"oO"[77>>i/64&1]}u`.charCodeAt(i/8%8,--g[+z]||z++,h[i]=z%2)>>7-i%8&1)+(++i%21?` `:`
`);console.log(r,...h.map(H=>`color:${H?'red':'black'}`))
```
This works by switching colours every *n* bits and makes use of [the console.log ability to log colours](https://stackoverflow.com/a/13017382/1237578)
# Coloured CSS Heart, 229+12 bytes
If using css is allowed, the coloured heart can be reduced even further to 229 bytes of JavaScript code and 12 bytes of CSS
```
for(i=z=r='',g=[90,...[...'353871767176G4H4H5G5F7CABB9D7F5H3J1'].map(n=>parseInt(n,20)),-1];C=`il${"Oo"[21>>i/64&1]}vey${"oO"[77>>i/64&1]}u`.charCodeAt(i/8%8,--g[+z]||z++)>>7-i%8&1,i++<483;)r+=(z%2?(''+C).bold():C)+(i%21?` `:`
`)
```
```
let f =
_=>{for(i=z=r='',g=[90,...[...'353871767176G4H4H5G5F7CABB9D7F5H3J1'].map(n=>parseInt(n,20)),-1];C=`il${"Oo"[21>>i/64&1]}vey${"oO"[77>>i/64&1]}u`.charCodeAt(i/8%8,--g[+z]||z++)>>7-i%8&1,i++<483;)r+=(z%2?(''+C).bold():C)+(i%21?` `:`
`);return r}
document.getElementById("b").innerHTML = f();
```
```
b{color:red}
```
```
<pre id="b">
```
[Answer]
# MATL, ~~56~~ 55 bytes
```
'!?u<TgGU*lB7SE1q3s.?Su(q6)iM'F'eilovyOu'Za8&B!FTTv21e!
```
[**Try it Online**](http://matl.tryitonline.net/#code=JyE_dTxUZ0dVKmxCN1NFMXEzcy4_U3UocTYpaU0nRidlaWxvdnlPdSdaYTgmQiFGVFR2MjFlIQ&input=)
**Explanation**
```
'!?u<TgGU*lB7SE1q3s.?Su(q6)iM' % Previously compressed version of the string
F'eilovyOu'Za % Decompress this string
8&B % Convert each char to 8-bit binary number
! % Transpose the result
FTTv % Append [0 1 1] to the end to take care of
% the partial "e" bits
21e! % Reshape it into the appropriate shape
% Implicitly display the result
```
[Answer]
## PowerShell v2+, (UTF-16) 300 bytes
*Corrected erroneous byte count thanks to @Mego*
```
'ږƍƕ๓ƺ֥˄ϝӊ༭ǝ֥ţϝɥޔǮƱϝIJ˲ӷʴ˘ͻ֙ץŻŬɻˌʼֽ͖ҶɻŦʼʞݖɛĽƳ'-split'(..)'-ne''|%{(-join($_[0,1]|%{[convert]::ToString(+$_,2)})).PadLeft(21,'0')-replace'(.)','$1 '}
```
Not the shortest, but a different approach. I manually took each line and sliced them into pairs each (roughly) 9-11 significant bits in length. Converted each of those binary values to a `char` (Note: PowerShell uses UTF-16 by default, not UTF-8), and mushed that into a string. That's the `'...'` at the beginning.
We then `-split` that into strings of length 2, and loop through each pair. Those pairs are split into a `char`-array via `$_[0,1]`, and each of those are cast as an int `+$_`, and `[convert]`ed into a binary (`,2`) `String`. That's `-join`ed together into a single string, then `PadLeft`'d to get the proper length, then each element is `-replace`d with itself and a space `'$1 '`.
Those strings are all left on the pipeline, and output is implicit, with the default `Write-Output` sticking a newline between elements.
```
PS C:\Tools\Scripts\golfing> 'ږƍƕ๓ƺ֥˄ϝӊ༭ǝ֥ţϝɥޔǮƱϝIJ˲ӷʴ˘ͻ֙ץŻŬɻˌʼֽ͖ҶɻŦʼʞݖɛĽƳ'-split'(..)'-ne''|%{(-join($_[0,1]|%{[convert]::ToString(+$_,2)})).PadLeft(21,'0')-replace'(.)','$1 '}
0 1 1 0 1 0 0 1 0 1 1 0 1 1 0 0 0 1 1 0 1
1 1 1 0 1 1 1 0 1 1 0 0 1 1 0 0 1 0 1 0 1
1 1 1 0 0 1 0 1 0 0 1 1 1 1 0 1 1 1 0 1 0
1 0 1 1 0 1 0 0 1 0 1 1 0 1 1 0 0 0 1 0 0
1 1 1 1 0 1 1 1 0 1 1 0 0 1 1 0 0 1 0 1 0
1 1 1 1 0 0 1 0 1 1 0 1 1 1 1 0 1 1 1 0 1
0 1 0 1 1 0 1 0 0 1 0 1 1 0 1 1 0 0 0 1 1
0 1 1 1 1 0 1 1 1 0 1 1 0 0 1 1 0 0 1 0 1
0 1 1 1 1 0 0 1 0 1 0 0 1 1 1 1 0 1 1 1 0
1 0 1 0 1 1 0 1 0 0 1 0 1 1 0 1 1 0 0 0 1
0 0 1 1 1 1 0 1 1 1 0 1 1 0 0 1 1 0 0 1 0
1 0 1 1 1 1 0 0 1 0 1 0 0 1 1 1 1 0 1 1 1
0 1 0 1 0 1 1 0 1 0 0 1 0 1 1 0 1 1 0 0 0
1 1 0 1 1 1 1 0 1 1 1 0 1 1 0 0 1 1 0 0 1
0 1 0 1 1 1 1 0 0 1 0 1 1 0 1 1 1 1 0 1 1
1 0 1 0 1 0 1 1 0 1 0 0 1 0 1 1 0 1 1 0 0
0 1 0 0 1 1 1 1 0 1 1 1 0 1 1 0 0 1 1 0 0
1 0 1 0 1 1 1 1 0 0 1 0 1 1 0 1 1 1 1 0 1
1 1 0 1 0 1 0 1 1 0 1 0 0 1 0 1 1 0 1 1 0
0 0 1 0 0 1 1 1 1 0 1 1 1 0 1 1 0 0 1 1 0
0 1 0 1 0 1 1 1 1 0 0 1 0 1 0 0 1 1 1 1 0
1 1 1 0 1 0 1 0 1 1 0 1 0 0 1 0 1 1 0 1 1
0 0 0 1 0 0 1 1 1 1 0 1 1 1 0 1 1 0 0 1 1
```
[Answer]
# [///](http://esolangs.org/wiki////), 237 bytes
```
/2/\/\///3/0 24/1 25/0
26/1
27/4428/3329/772A/432B/A732C/937A782D/B48B72E/8A4892F/98B93/373A3A737837367A7A7878AA674E37A45D83A5C78A45F7A63D83463C78A639E3745AD8368C7845A9E3763AD8573C7863AF46AAD35348C735AAF673AD5848C753AA9E57AAB48B468348C41
```
[Try it online!](//slashes.tryitonline.net#code=LzIvXC9cLy8vMy8wIDI0LzEgMjUvMAoyNi8xCjI3LzQ0MjgvMzMyOS83NzJBLzQzMkIvQTczMkMvOTM3QTc4MkQvQjQ4QjcyRS84QTQ4OTJGLzk4QjkzLzM3M0EzQTczNzgzNzM2N0E3QTc4NzhBQTY3NEUzN0E0NUQ4M0E1Qzc4QTQ1RjdBNjNEODM0NjNDNzhBNjM5RTM3NDVBRDgzNjhDNzg0NUE5RTM3NjNBRDg1NzNDNzg2M0FGNDZBQUQzNTM0OEM3MzVBQUY2NzNBRDU4NDhDNzUzQUE5RTU3QUFCNDhCNDY4MzQ4QzQx)
[Answer]
# Python 3, ~~147~~ 144 bytes
```
lambda i=0:exec("print(' '.join(''.join('0'+bin(ord(chr(j+30)in' ,0@DL'and'o'or c))[2:]for j,c in enumerate('ilOveyOu'*8))[i:i+21]));i+=21;"*23)
```
Test it at **[ideone](http://ideone.com/y2yNoR)**
Initialises `i` to `0` in the function declaration, then repeats this 23 times:
makes the whole binary string without spaces (see below);
slices a row from within using `[i:i+21]`;
inserts the spaces with `' '.join(...)`;
prints; and
increments `i` by 21 with `i+=21`
To make the whole binary string:
it repeats `"ilOveyOu"` eight times;
replaces `O` with `o` where necessary (at indexes `[2,14,18,34,38,46]`);
- - - this is achieved with `chr(j+30)in' ,0@DL'` to save 3 bytes
converts each char to it's ordinal;
casts each ordinal to a binary string (`'0bxxxxxxx'`);
removes the leading `'0b'` from each using `[2:]`;
prepends each with a `'0'`; and
joins the whole thing up with `''.join(...)`
[Answer]
# Powershell, 110 bytes
```
'uil','vey'*8|%{$s+=$_+'oOOooOOOooOoOOO'[$i++]}
-join(8..490|%{(+$s[$_-shr3]-shr(7-$_%8))%2
'
'[!(++$j%21)]})
```
Explanation:
The first line of the script takes the substrings and inserts a letter `O` between them. The result is the string `uiloveyOuilOveyouiloveyOuilOveyOuiloveyouilOveyouilOveyOuilOvey`. Note that the first and last characters are redundant.
The loop outputs all the necessary `(8..490)` bits from the characters of the string, as well as a space or a line feed.
## The riddle of the recipient of the valentine letter
It can be seen that small and large symbol `O` themselves make up the bit encoding. There are 15 symbols (bits). There is only one partition on the bits to get ASCII characters: `oOOooOOO`+`ooOoOOO[o]`. We had to add a small `o` instead of `0` at the end. This ASCII symbols are: `g.`
Who is this mysterious `g.`?
[Answer]
# PHP+HTML+CSS, 173 Bytes Colored 367 Bytes
CLI only PHP 173 Bytes
```
$o=2841;for($i=0;$i<16;)$t.=il.Oo[$o>>$i++&1].vey.Oo[$o>>$i++&1].u;foreach(str_split($t)as$c)$x.="0".decbin(ord($c));for($i=0;$i<504;$i++){$i%21?:print"\n";echo$x[$i]." ";}}
```
conform to the bounty spec content type text/html
```
<?=gzinflate(base64_decode("jVNbDoIwELwKJ9Ctn9hwF9HGmFQwiB+GeHcRd7ezvDQEAmWmMzuT+nv7jKG4dddDc75UOW124foqu0OM+aO6h3Z/rGPd5E04vfz2C/a3gjLXXzTcxG/pSem7xzr4hxhn2BZLZvfpDjRg/3FBjBWuL78fflsWAOVl0uWk8rmG3yDCMNnMLMsshHpq0jLVQLKj6RrIbHBCYoq6WclPHHJ+PNdqjEZlpLNgbaTy2xoTHAQ3kBasKZyg3/XUDAVV5urVcDE5mQXsGWugIJqikibVmcZTJIrL0Bq3NKdgjxhak2q5ukmpWuXS+QJPEBVi52vE025VJy7Yw18u3g==");
```
`b{all:unset;color:red}` instead of `b{all:unset;color:#911;background:red}` in the first version
PHP+HTML+CSS, 392 Bytes
heart red +black which looks more pretty
Maybe call the color number in the CSS Part
```
<?=gzinflate(base64_decode("jVTLDoIwELyb+A8m3nXrzdrwL7xijAgG8GAI/67WdpktD00DoWWmMztLMU37LPLo3t3i+nwpNe0O+a1Purgo9KNs8vaUVkVV6+1RqVMSp9dzXT3KTNd51pv9l7xemXtEG/UeZC9yT8OdhrlFK3iLKCX4IZqEwngPcuh/vBCjPd8k34nZJxGA3TLxMip9hgWAkAP67cTyUBOhJluVXDYxWIKsBWgyRE9jEntayNL75CxdfYuRBkqB1ozBkdJvg46iRIiWNmOQCSQ6vpygIEmlqYZz1LAN1AQmhUFQUfBBhjVzbWE1SFIbNOi6NqUSHkI06JvtmjlqMzR37gSCMxEboicbG/wVpPbICzv5y8sL"));
```
add this before it looks nicer
```
<style>*{word-spacing:1em;}</style>
```
## Output first version it is the ugliest HTML Code in my live
[red-black heart](https://jsfiddle.net/g9prh7b8/)
```
<style>*{word-spacing:1em;}</style><style>p{margin:0.2em}b{all:unset;color:#911;background:red}</style>
<p>0 1 1 0 1 0 0 1 0 1 1 0 1 1 0 0 0 1 1 0 1
<p>1 1 1 0 1 1 1 0 1 1 0 0 1 1 0 0 1 0 1 0 1
<p>1 1 1 0 0 1 0 1 0 0 1 1 1 1 0 1 1 1 0 1 0
<p>1 0 1 1 0 1 0 0 1 0 1 1 0 1 1 0 0 0 1 0 0
<p>1 1 1 1 0 <b>1 1 1</b> 0 1 1 0 0 <b>1 1 0</b> 0 1 0 1 0
<p>1 1 1 <b>1 0 0 1 0 1 1</b> 0 <b>1 1 1 1 0 1 1</b> 1 0 1
<p>0 1 0 <b>1 1 0 1 0 0 1</b> 0 <b>1 1 0 1 1 0 0</b> 0 1 1
<p>0 1 1 <b>1 1 0 1 1 1 0 1 1 0 0 1 1 0 0 1</b> 0 1
<p>0 1 <b>1 1 1 0 0 1 0 1 0 0 1 1 1 1 0 1 1</b> 1 0
<p>1 0 <b>1 0 1 1 0 1 0 0 1 0 1 1 0 1 1 0 0</b> 0 1
<p>0 0 1 <b>1 1 1 0 1 1 1 0 1 1 0 0 1 1 0 0</b> 1 0
<p>1 0 1 <b>1 1 1 0 0 1 0 1 0 0 1 1 1 1 0</b> 1 1 1
<p>0 1 0 1 <b>0 1 1 0 1 0 0 1 0 1 1 0</b> 1 1 0 0 0
<p>1 1 0 1 1 <b>1 1 0 1 1 1 0 1 1 0 0</b> 1 1 0 0 1
<p>0 1 0 1 1 1 <b>1 0 0 1 0 1 1 0 1</b> 1 1 1 0 1 1
<p>1 0 1 0 1 0 1 <b>1 0 1 0 0 1 0</b> 1 1 0 1 1 0 0
<p>0 1 0 0 1 1 1 1 <b>0 1 1 1 0</b> 1 1 0 0 1 1 0 0
<p>1 0 1 0 1 1 1 1 0 <b>0 1 0</b> 1 1 0 1 1 1 1 0 1
<p>1 1 0 1 0 1 0 1 1 0 <b>1</b> 0 0 1 0 1 1 0 1 1 0
<p>0 0 1 0 0 1 1 1 1 0 1 1 1 0 1 1 0 0 1 1 0
<p>0 1 0 1 0 1 1 1 1 0 0 1 0 1 0 0 1 1 1 1 0
<p>1 1 1 0 1 0 1 0 1 1 0 1 0 0 1 0 1 1 0 1 1
<p>0 0 0 1 0 0 1 1 1 1 0 1 1 1 0 1 1 0 0 1 1
```
```
<style>p{margin:0.2em}b{all:unset;color:red}</style>
<p>0 1 1 0 1 0 0 1 0 1 1 0 1 1 0 0 0 1 1 0 1
<p>1 1 1 0 1 1 1 0 1 1 0 0 1 1 0 0 1 0 1 0 1
<p>1 1 1 0 0 1 0 1 0 0 1 1 1 1 0 1 1 1 0 1 0
<p>1 0 1 1 0 1 0 0 1 0 1 1 0 1 1 0 0 0 1 0 0
<p>1 1 1 1 0 <b>1 1 1</b> 0 1 1 0 0 <b>1 1 0</b> 0 1 0 1 0
<p>1 1 1 <b>1 0 0 1 0 1 1</b> 0 <b>1 1 1 1 0 1 1</b> 1 0 1
<p>0 1 0 <b>1 1 0 1 0 0 1</b> 0 <b>1 1 0 1 1 0 0</b> 0 1 1
<p>0 1 1 <b>1 1 0 1 1 1 0 1 1 0 0 1 1 0 0 1</b> 0 1
<p>0 1 <b>1 1 1 0 0 1 0 1 0 0 1 1 1 1 0 1 1</b> 1 0
<p>1 0 <b>1 0 1 1 0 1 0 0 1 0 1 1 0 1 1 0 0</b> 0 1
<p>0 0 1 <b>1 1 1 0 1 1 1 0 1 1 0 0 1 1 0 0</b> 1 0
<p>1 0 1 <b>1 1 1 0 0 1 0 1 0 0 1 1 1 1 0</b> 1 1 1
<p>0 1 0 1 <b>0 1 1 0 1 0 0 1 0 1 1 0</b> 1 1 0 0 0
<p>1 1 0 1 1 <b>1 1 0 1 1 1 0 1 1 0 0</b> 1 1 0 0 1
<p>0 1 0 1 1 1 <b>1 0 0 1 0 1 1 0 1</b> 1 1 1 0 1 1
<p>1 0 1 0 1 0 1 <b>1 0 1 0 0 1 0</b> 1 1 0 1 1 0 0
<p>0 1 0 0 1 1 1 1 <b>0 1 1 1 0</b> 1 1 0 0 1 1 0 0
<p>1 0 1 0 1 1 1 1 0 <b>0 1 0</b> 1 1 0 1 1 1 1 0 1
<p>1 1 0 1 0 1 0 1 1 0 <b>1</b> 0 0 1 0 1 1 0 1 1 0
<p>0 0 1 0 0 1 1 1 1 0 1 1 1 0 1 1 0 0 1 1 0
<p>0 1 0 1 0 1 1 1 1 0 0 1 0 1 0 0 1 1 1 1 0
<p>1 1 1 0 1 0 1 0 1 1 0 1 0 0 1 0 1 1 0 1 1
<p>0 0 0 1 0 0 1 1 1 1 0 1 1 1 0 1 1 0 0 1 1
```
375 Bytes for create the HTML Page with PHP directly
```
<?$o=2841;for(;$i<16;)$t.=il.Oo[$o>>$i++&1].vey.Oo[$o>>$i++&1].u;foreach(str_split($t)as$c)$x.="0".decbin(ord($c));$a=[1,9,20,28,41,49,62,82,103,125,146,168,190,212,234,256,278,300];$z=[3,11,26,34,47,55,77,98,119,140,160,179,200,220,240,260,280,300];for($i=0;$i<483;$i++)echo $i%21?"":"<p>",in_array($i-88,$a)?"<b style=color:red>":"",$x[$i],in_array($i-88,$z)?"</b>":""," ";
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 102 bytes
```
f(i){for(i=0;i<483;)printf("\n%2d"+!!(i++%21),(i/8%4^2|35609>>i/32&1?"iloveyou"[i/8%8]:79)>>7-i%8&1);}
```
# Rundown
```
f(i){
for(i=0;i<483;) Loop through bits.
printf("\n%2d"
+!!(i++%21), Decide if newline in format string should be skipped.
(i/8%4^2| Are we at a non-'o' letter?
(They occur every 4th letter, starting at index 2.)
35609>>i/32&1? Check with magic number if the 'o' should be capital.
"iloveyou"[i/8%8]: If not-'o' or not capital, use current letter.
79) Otherwise, use the letter 'O'.
>>7-i%8&1 Extract bit to write.
);}
```
[Try it online!](https://tio.run/##FczdCoIwFADg63yKHEzOYYm6Wc5W60H6gbAWB2oLqSDMZ191//F1@aXrYnRAOLjQA61LQ6taK4P3nvzDAdt5Lk9MpCmQEFxWOAMqNK8P8qPmi7K1lgols2rD6Bpe53d4su0f6P2yadHaJieuswrNGH/h9HYkD5gMycQBmmSMXw "C (gcc) – Try It Online")
[Answer]
# q/kdb+, ~~107~~ ~~93~~ ~~85~~ ~~55~~ 53 bytes
**Solution:**
```
23 21#0 1(,/)0b vs'@[61#"ilOveyOu";0x020e1222262e;_:]
```
**Example:**
```
q)23 21#0 1(,/)0b vs'@[61#"ilOveyOu";0x020e1222262e;_:]
0 1 1 0 1 0 0 1 0 1 1 0 1 1 0 0 0 1 1 0 1
1 1 1 0 1 1 1 0 1 1 0 0 1 1 0 0 1 0 1 0 1
1 1 1 0 0 1 0 1 0 0 1 1 1 1 0 1 1 1 0 1 0
1 0 1 1 0 1 0 0 1 0 1 1 0 1 1 0 0 0 1 0 0
1 1 1 1 0 1 1 1 0 1 1 0 0 1 1 0 0 1 0 1 0
1 1 1 1 0 0 1 0 1 1 0 1 1 1 1 0 1 1 1 0 1
0 1 0 1 1 0 1 0 0 1 0 1 1 0 1 1 0 0 0 1 1
0 1 1 1 1 0 1 1 1 0 1 1 0 0 1 1 0 0 1 0 1
0 1 1 1 1 0 0 1 0 1 0 0 1 1 1 1 0 1 1 1 0
1 0 1 0 1 1 0 1 0 0 1 0 1 1 0 1 1 0 0 0 1
0 0 1 1 1 1 0 1 1 1 0 1 1 0 0 1 1 0 0 1 0
1 0 1 1 1 1 0 0 1 0 1 0 0 1 1 1 1 0 1 1 1
0 1 0 1 0 1 1 0 1 0 0 1 0 1 1 0 1 1 0 0 0
1 1 0 1 1 1 1 0 1 1 1 0 1 1 0 0 1 1 0 0 1
0 1 0 1 1 1 1 0 0 1 0 1 1 0 1 1 1 1 0 1 1
1 0 1 0 1 0 1 1 0 1 0 0 1 0 1 1 0 1 1 0 0
0 1 0 0 1 1 1 1 0 1 1 1 0 1 1 0 0 1 1 0 0
1 0 1 0 1 1 1 1 0 0 1 0 1 1 0 1 1 1 1 0 1
1 1 0 1 0 1 0 1 1 0 1 0 0 1 0 1 1 0 1 1 0
0 0 1 0 0 1 1 1 1 0 1 1 1 0 1 1 0 0 1 1 0
0 1 0 1 0 1 1 1 1 0 0 1 0 1 0 0 1 1 1 1 0
1 1 1 0 1 0 1 0 1 1 0 1 0 0 1 0 1 1 0 1 1
0 0 0 1 0 0 1 1 1 1 0 1 1 1 0 1 1 0 0 1 1
```
**Explanation:**
```
23 21#0 1(,/)0b vs'@[61#"ilOveyOu";0x020e1222262e;_:] / the solution
@[ ; ; ] / apply[input;indices;function]
_: / lowercase
0x020e1222262e / 2 14 18 34 38 46 represented in hex
61#"ilOveyOu" / 61 take "ilOveyOu" (wraps around)
0b vs' / convert into 8-bit representation
(,/) / flatten
0 1 / index into 0 / 1 (convert from booleans)
23 21# / reshape
```
**Notes:**
* -2 bytes thanks to ngn!
[Answer]
# PHP, 121 bytes
```
for($n=5682;$i++<60;)for($b=8;$b;)$p.=(1&ord(~$i&3||($n/=2)&1?uiloveyo[$i%8]:O)>>--$b)." ";echo wordwrap($p."0 1 1",42);
```
**breakdown**
```
$n=2*bindec("000101100011001"); // where to NOT replace o with O
for($i=1;$i<61;$i++) // loop $i from 1 to 60
{
$c=
~$i&3 // $i%4!=3
||
($n/=2)&1 // or (1. shift $n, 2. test bit 0)
? "uiloveyo"[$i%8] // yes: character from string
: "O" // no: uppercase "O"
;
for($b=8;$b--;) // run from bit 7 to bit 0
$p.=(1 & ord($c)>>$b). " "; // append 1 or 0 plus space
}
$p.="0 1 1"; // append the missing three bits
echo wordwrap($p,42); // wrap at column 42 (actually 41; 42 is space -> gets cut)
```
[Answer]
# [K (oK)](https://github.com/JohnEarnest/ok), ~~50~~ 48 bytes
**Solution:**
```
23 21#,/(8#2)\'@[61#"ilOveyOu";0x020e1222262e;_]
```
[Try it online!](https://tio.run/##y9bNz/7/38hYwchQWUdfw0LZSDNG3SHazFBZKTPHvyy10r9UydqgwsDIINXQCAjMjFKt42P//wcA "K (oK) – Try It Online")
**Explanation:**
Port of my [Q/KDB+ solution](https://codegolf.stackexchange.com/a/128106/69200).
**Notes:**
* -2 bytes thanks to ngn!
[Answer]
# Python 3, 199 Bytes:
```
z='01111011101'
a='011010010110110001'
b=z+'10011001010111100101'
[print(' '.join(''.join([a+i[0]+b+i[1]+z+'01'for i in'10 01 10 00 11 01 00'.split()])+a+'0'+b[:16])[i:i+41])for i in range(0,966,42)]
```
[Answer]
# Python 3, 170 bytes
```
from textwrap import*
print('\n'.join(' '.join(list(i))for i in wrap(''.join(bin(ord(i)+256)[3:]for i in (7*"il%svey%su")%(tuple("oOOooOOOooOoOO"))+"ilOv"),21))+" 0 1 1")
```
makes a string repetition of "Il%svey%su", repeats it the required number of times, then uses a tuple to sub all the o's in. it then converts it to binary, uses the textwrap module, converts each item of the new list to list, joins with space, then appends 0 1 1 because that seems to be a stub or something
[Answer]
# Mathematica, 123 bytes (275 with color)
I'm not sure if using `Grid` instead of outputting a string is OK (if not then this is a non-competing entry).
### B/W
```
Grid@Partition[ReplacePart[PadLeft[{},483,IntegerDigits[36^^nz4sp78k5qyb,2,64]],
Thread[51+32{0,1,4,5,6,9,11,12,13}->0]],21]
```
![enter image description here](https://i.stack.imgur.com/ZiiXu.png)
### Color
```
Grid[Partition[ReplacePart[PadLeft[{},483,IntegerDigits[36^^nz4sp78k5qyb,2,64]],
Thread[51+32{0,1,4,5,6,9,11,12,13}->0]],21],ItemStyle->{{},{},Thread[Join@@MapIndexed[
Thread@{Range@@#,2+First@#2}&,Thread[Partition[IntegerDigits[36^^k32b741shmsoiwed4vnakt],
17]+{0,10}]]->Red]}]
```
![enter image description here](https://i.stack.imgur.com/DTju8.png)
[Answer]
# Ruby 142 Bytes
```
(('iloveyOuilOveyouiloveyOuilOveyOuiloveyouilOveyouilOveyOuilOv'.unpack('B*')[0]+'011').split(/(.{21})/)-['']).map{|i|puts(i.chars.join(' '))}
```
(Slightly more) legibly:
```
(('iloveyOuilOveyouiloveyOuilOveyOuiloveyouilOveyouilOveyOuilOv'.unpack('B*')[0]+'011')
# unpack turns it into a binary string, [0] takes the first element, and then we add on the trailing 011
.split(/(.{21})/) -[''])
# split it every group of 21 characters and remove the empty strings that are also included
.map { |i| puts(i.chars.join(' ')) }
# take each string of 21 characters, get its chars and join them with an empty string for formatting (puts takes care of the newlines)
```
I have not yet found a way to condense the original text into a more succinct form in Ruby - it has some great String manipulation functions, but all of the ways I've tried use more characters than the string itself. Any pointers appreciated, this is my first Code Golf on StackOverflow!
[Answer]
# Rust, 195 bytes
```
||for(c,i)in"iloveyOuilOveyouiloveyOuilOveyOuiloveyouilOveyouilOveyOuilOve".bytes().fold(String::new(),|a,c|format!("{}0{:b}",a,c)).chars().zip(1..484){print!("{}{}",c,if i%21!=0{' '}else{'\n'})}
```
Ungolfed:
```
fn main(){
// convert bytes of the string to binary numerals.
let s = "iloveyOuilOveyouiloveyOuilOveyOuiloveyouilOveyouilOveyOuilOve"
.bytes()
.fold(String::new(),|a,c|format!("{}0{:b}",a,c));
// print them over the range with newlines/spaces as appropriate
for(c,i) in s.chars().zip(1..484) {
print!("{}{}",c,if i%21!=0{' '}else{'\n'})
}
}
```
[Answer]
# Pyth, 47 bytes
```
jPcjdsm+0.BCdtPs.i*8c"uil vey"dmr\o!djC\䱨2 42
```
Try it online [here](https://pyth.herokuapp.com/?code=jPcjdsm%2B0.BCdtPs.i%2A8c%22uil%20vey%22dmr%5Co%21djC%5C%E4%B1%A82%2042&debug=0).
```
jPcjdsm+0.BCdtPs.i*8c"uil vey"dmr\o!djC\䱨2 42 Implicit: d=" "
c"uil vey"d Chop "uil vey" on spaces, to yield ["uil" "vey"]
*8 Repeat the above 8 times - {1}
C\䱨 Character code of 䱨, yields 19560
j 2 Convert the above to base 2
m Map the digits of the above, as d, using:
r\o!d If d is 0, yield "O", otherwise "o" - {2}
.i Interleave {1} with {2}
s Concatenate into a string
This yields "uiloveyOuilOveyouiloveyOuilOveyOuiloveyouilOveyouilOveyOuilOvey"
tP Remove first and last characters of the above
m Map each character, as d, using:
Cd Get character code
.B Convert to binary string
+0 Prepend 0 (all binary strings will be length 7, so this pads to length 8)
s Flatten the result of the map
jd Join on spaces
c 42 Chop into strings of length 42
P Discard the last, partial, string
j Join on newlines, implicit print
```
[Answer]
# [///](http://esolangs.org/wiki////), 220 bytes
```
/H/2E//G/CBDCC//F/ABC2C//E/AC//D/2B//C/A2//A/33//B/32//2/0 //3/1 /2G22C3
ABFDB3
ABDBHABB
BG2D2
EFDB
EDCEAB3
DG22A
HFD3
HDBHAB
BBG223
2HFD
BEDBHA3
DBG22
CEF23
DEDCEA
BBBG2
DHF2
BBEDCE3
CBBG
2DHF
DBEDBH
ABBBCBDCA
22DHABC2A
```
[Try it online!](http://slashes.tryitonline.net/#code=L0gvMkUvL0cvQ0JEQ0MvL0YvQUJDMkMvL0UvQUMvL0QvMkIvL0MvQTIvL0EvMzMvL0IvMzIvLzIvMCAvLzMvMSAvMkcyMkMzCkFCRkRCMwpBQkRCSEFCQgpCRzJEMgpFRkRCCkVEQ0VBQjMKREcyMkEKSEZEMwpIREJIQUIKQkJHMjIzCjJIRkQKQkVEQkhBMwpEQkcyMgpDRUYyMwpERURDRUEKQkJCRzIKREhGMgpCQkVEQ0UzCkNCQkcKMkRIRgpEQkVEQkgKQUJCQkNCRENBCjIyREhBQkMyQQ&input=)
[Answer]
### C++11, Non-competing, ~~726~~ ~~687~~ 636 bytes (\*NIX or W10 threshold 2 required)
```
#include <iostream>
#include <string>
#ifdef _WIN32
#include <Windows.h>
#endif
using namespace std;int main() {
#ifdef _WIN32
HANDLE h=GetStdHandle(-11);DWORD m;GetConsoleMode(h,&m);SetConsoleMode(h,m|0x04);
#endif
cout<<"\033[47m\033[30m";string d("4fup8y8hihjyl9g1ifh9wpc4f52l5a8giosim2isj80xff814db9wmf958x4zlbl58x4zlbl6zxgjt9whbcz4mu91r0j5c4kfq48uxw53w1zvpdshv6ylrnl3t38qyiteyw0lphs3kx59vf4ezay145thrt7lkb80w83nz10ih27f77p0820wzr9");for(int s=0;s!=184;s+=8){unsigned long long n=stoull(d.substr(s,8),NULL,36),i=3;for(int p=40;p!=-2;p-=2){int r=(n&(i<<p))>>p;printf(r>1?"\033[31m %d\033[30m":" %d",r>1?r-2:r);}puts("");}return 0;}
```
I know this can be golfed way better. I want to see a short c++ answer damnit!
I also probably made a few mistakes when I was encoding the heart section.
Output (colors fixed):
[![enter image description here](https://i.stack.imgur.com/1kYGh.png)](https://i.stack.imgur.com/1kYGh.png)
[Answer]
# Python, 473 bytes
### Colored!
```
r=str.replace;print r(r(r(r(r(r(r(r("""
jh0k1k1k0jk1
ikik1kjk0h1
ik0hjikih
k1h0k1k1k00k0
i1ksi1ejk0s1ke0h
i1sk0kie0si1kiek1
0ks1hje0s1k1k0ej1
j1s1kik1kjkjej
jsik0hjikiek
ksk1h0k1k1k0ej
0jsikik1kjk0ek
k1sik0hjikei1
0k1sjh0k1ke1k00
1kis1kik1k0e1kj
0ki1sk0k1k1eiki
hk1sh0ke1k1k0
0kji1sj1ke1kjk0
hi1ks0ke1ki1k1
1hk1ks1e00k1k1k
00kjikik1kjk
0hi1k0hjik
ihk1h0k1ki
000kjikik1kj1
""",'h','1010'),'i','11'),'j','01'),'k','10'),'1','1 '),'0','0 '),'s','\x1b[0;40;31m'),'e','\x1b[0m')
```
[Answer]
## [FEU](https://github.com/tuxcrafting/feu), 360 bytes
```
m/a/0 1 /b/1 0 /c/1 1 /d/0 0 /e/0 /f/1 /g
__DATA__
afaeaafabeab1
cfacababaae1
cbaaeacfaca0
fafaeaafabeae0
ccacababaa0
cfbaafacfafb1
aafaeaafabea1
acfacababae1
acbaaeacfac0
faafaeaafabd1
eacfacababa0
facbaaeacfaf1
aaafaeaafabe0
cacfacababe1
aacbaafacfa1
faaafaeaafab0
aeacfacabab0
faacbaafacb1
caaafaeaafaf0
eaeacfacabaf0
aaacbaaeacf0
cfaaafaeaafa1
daeacfacaba1
```
Just stupid compression
] |
[Question]
[
Inspired by Alex's glorious [Learn you an R for great good,](http://chat.stackexchange.com/transcript/message/26140903#26140903) we are going to humbly recreate Alex's "one true R program" -- but with a twist.
Alex-style Addition works like this -- it has a 90% chance of simply returning the sum of the two numbers given and a 10% chance of recursively Alex-adding the first number and the second number + 1. This means that, potentially, an addition could be off by 1 or more.
## Challenge
Write a full program or function that takes two integers and Alex-adds them as defined. You may assume that your program will not stack overflow if your language doesn't have tail recursion. (Note that you do not have to implement it recursively, as long as the probabilities are the same.)
## Reference Implementation (Groovy)
```
int alexAdd(int a, int b) {
int i = new Random().nextInt(11);
if(i == 1) {
return alexAdd(a,b+1);
} else {
return a + b;
}
}
```
[Try this fiddle online.](http://ideone.com/fork/raQz47)
## Leaderboard
```
var QUESTION_ID=66522,OVERRIDE_USER=8478;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
```
```
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
```
```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>
```
[Answer]
# Pyth, 8
```
u+G!OTsQ
```
[Try it online](https://pyth.herokuapp.com/?code=u%2BG%21OTsQ&input=3%2C4&debug=0)
This uses Pyth's second mode on reduce, that looks for repeated input then exits.
### Explanation
```
u+G!OTsQ ## Implicit: Q=eval(input())
u sQ ## reduce with 2 arguments, which causes a loop until the reduce gets the
## same argument twice
+G ## lambda G,H: G + ...
!OT ## boolean not of random value from 0 to 9 inclusive
```
If the extra alex-add occurs it will run again, but if not then it exits.
[Answer]
# R, ~~60~~ ~~47~~ 28 bytes
```
function(a,b)a+b+rgeom(1,.9)
```
This is an unnamed function object that accepts two numbers and returns a number. It does not use recursion.
As xnor pointed out in a comment, this problem can be viewed as simply adding two numbers plus a geometric random variable with failure probability 1/10.
Why is that true? Think about it in terms of recursion, as it's described in the post. In each iteration we have a 10% chance of adding 1 and recursing, and a 90% chance of exiting the function without further addition. Each iteration is its own independent [Bernoulli trial](https://en.wikipedia.org/wiki/Bernoulli_trial) with outcomes "add 1, recurse" (failure) and "exit" (success). Thus the probability of failure is 1/10 and the probability of success is 9/10.
When dealing with a series of independent Bernoulli trials, the number of trials needed to obtain a single success follows a [geometric distribution](https://en.wikipedia.org/wiki/Geometric_distribution). In our case, each recursion means adding 1, so when we do finally exit the function, we've essentially counted the number of failures that occurred before the first success. That means that the amount that the result will be off by is a random variate from a geometric distribution.
Here we can take advantage of R's expansive suite of probability distribution built-ins and use `rgeom`, which returns a random value from a geometric distribution.
Ungolfed:
```
f <- function(a, b) {
a + b + rgeom(n = 1, prob = 0.9)
}
```
[Answer]
## [Minkolang 0.14](https://github.com/elendiastarman/Minkolang), ~~19~~ ~~11~~ 12 bytes
This is the "function" version; it assumes `a` and `b` are already on the stack, pops them off and pushes the modified version of `a+b`. The closest equivalent to functions in Minkolang is to use `F`, which pops off `b`,`a` and jumps to `(a,b)` in the codebox. Then when the program counter hits an `f`, it jumps back to where `F` was used.
```
(+$01$h`d)xf
```
This is the full program version, **15 bytes**. (`nn` takes two numbers from input and `N.` outputs the result and stops.)
```
nn(+$01$h`d)xN.
```
I stole the algorithm from [Doorknob's answer](https://codegolf.stackexchange.com/a/66524/12914); the while loop repeats so long as the generated random number is less than 0.1, adding 1 each time. [Try it here](http://play.starmaninnovations.com/minkolang/?code=nn2%7B1%24h%240%603%261%2B%7B%2B%7DN%2E&input=3%205) (full program version) and [run it 100 times here](http://play.starmaninnovations.com/minkolang/?code=%24l%5B35%28%2B%2401%24h%60d%29xNlO%5D%2E&input=3%205).
### Explanation
```
( Open a while loop
+ Adds the top two items of the stack
$0 Pushes 0.1
1$h Pushes a random number between 0.0 and 1.0, inclusive
` Pops b,a and pushes a > b
d Duplicate the top of stack
) Close the while loop when the top of stack is 0
x Dump the extra, leading 0
```
The cleverest part here is `d`. The top of stack at that point in time will be either 0 or 1. If it's 0, the while loop exits. Otherwise, it continues. As I duplicate the top of stack, it will be `[a+b,1]` the second time through the loop, so the `+` at the beginning adds the 1 (and likewise for subsequent trips).
[Answer]
## CJam, ~~12~~ 11 bytes
```
{{+Amr!}h;}
```
Thanks to @MartinBütter for saving a byte with this super clever trick!
```
{ }
{ }h Do-while that leaves the condition on the stack.
+ Add: this will add the numbers on the first iteration...
Amr! ... but a `1` (i.e. increment) on future ones.
; Pop the remaining 0.
```
---
Old answer:
```
{+({)Amr!}g}
```
[Try it online](http://cjam.tryitonline.net/#code=MTAgMTAKeysoeylBbXIhfWd9Cn4).
Explanation:
```
{ } A "function."
+ Add the input numbers.
( Decrement.
{ }g A while loop.
) Increment.
Amr Random number [0,9).
! Boolean NOT.
```
The basic algorithm is "while (0.1 chance), increment the number," which eliminates the need for the recursion.
[Answer]
# Javascript ES6, 38 bytes
```
f=(a,b)=>Math.random()<.1?f(a,b+1):a+b
```
[Answer]
## TI-BASIC, 15 bytes
```
While rand<.1
Ans+.5
End
sum(Ans
```
This takes the input as a two-element list from `Ans`. While a random number is less than `0.1`, it does vectorized addition to `0.5` on the list. Increasing each element by `0.5` increases the sum by 1. I believe this is the shortest TI-BASIC solution.
The 9-byte program `sum(Ans)-int(log(10rand` doesn't work, because `rand` only has 14 digits of precision, and thus it can't give a number less than 10-14.
[Answer]
## [MATL](https://esolangs.org/wiki/MATL), ~~14~~ ~~13~~ 12 bytes
```
is`r.1<tb+w]
```
This is just the loop method, add the inputs (entered as `[a b]`) then keep adding one while a uniform random number between 0 and 1 is less than 0.1. Full description below:
```
i % input [a b]
s % sum a and b
` % do...while loop
r % get a uniformly distributed pseudorandom numbers between 0 and 1
.1 % push 0.1 onto the stack
< % is the random number less than 0.1?
t % duplicate the T/F values
b % bubble a+b to the top of the stack
+ % add the T/F to a+b
w % swap elements in stack to get the other T/F back to exit/continue the loop
] % end
```
Took off 1 byte by changing input spec (from `ii+` to `is`).
---
The old way was based on taking the base-10 log of a random number between 0 and 1 to work out the amount to add to `a+b`, however it would only work up to 15 repetitions due to floating point accuracy.
```
iir10,2$YlZo-+
```
In this code, `10,2$YlZo-` does base-10 logarithm of the random number and rounds up to the nearest integer.
[Answer]
# Binary-Encoded [Golfical](https://github.com/SuperJedi224/Golfical), ~~32~~ 29+1 (`-x` flag) = 30 bytes
Hexdump (manually edited to correct for a bug in the image-to-binary part of the transpiler, which has since been fixed):
```
00 B0 02 15 14 0C 01 14 15 14 1B 1E 3A 14 0C 01
14 00 0A 14 38 00 01 23 1D 4C 14 17 14
```
This encoding can be converted back into the original graphical representation using the included Encoder utility, or run directly using the `-x` flag.
Original image:
![enter image description here](https://i.stack.imgur.com/E60jJ.png)
Magnified 50x:
![enter image description here](https://i.stack.imgur.com/L431i.png)
Explanation: The top row is the main block. It reads a number, copies it to the right, reads another number, adds them, copies the result to the right, does some RNG stuff, and, with probability 90%, prints the result of the addition. The rest of the time, it is sent to the bottom row, where it puts a one in the first cell and goes back to the main row just before the addition instruction (using a north turn then an east turn).
[Answer]
## Python, ~~66~~ ~~65~~ ~~64~~ 63 bytes
```
from random import*
g=lambda*s:randint(0,9)and sum(s)or g(1,*s)
```
[Try it online](https://tio.run/##LYnLCoAgEADvfoXHXfFQdiroYwzJhHyw6qGv3ww6zQxTnnblZJhPylGSTW4gxJKpKeH328bDWVW374TUYNIrDpW1R6iYSXqYtarIhcYeFVLpDVD/RDZieQE)
Thanks to Sherlock9 for the corrections and the byte saved.
Thanks to Mathias Ettinger for another byte.
Thanks to mbomb007 for a byte.
[Answer]
# Julia, 30 bytes
```
f(a,b)=rand()>0.9?f(a,b+1):a+b
```
This is a recursive function `f` that accepts two numbers and returns a number of the same type. It should work fine for any numeric type.
First we check whether a random float between 0 and 1 is greater than 0.9. If so, we recurse with a little extra somethin' somethin', otherwise we just add.
[Answer]
# [Vitsy](https://github.com/VTCAKAVSMoACE/Vitsy), ~~12~~ 10 bytes
```
aR)[1+0m]+
aR Get a random number in [0,10)
)[ ] If its truncated int is 0, do the stuff in brackets.
1+0m Add 1 to one of the items and execute the 0th index of code.
+ Add the numbers together.
```
[Try it online!](http://vitsy.tryitonline.net/#code=YVIpWzErMG1dK04&input=&args=NA+NQ)
Note that this has a *tiny* chance of a stack overflow error. We're talking `(.1)^400` chance. It also exits on error due to how I caused recursion.
[Answer]
# APL, 17 bytes
```
{1=?10:⍺∇⍵+1⋄⍺+⍵}
```
This is an unnamed dyadic function.
Ungolfed:
```
{1=?10: ⍝ If a random number between 1 and 10 is 1,
⍺∇⍵+1 ⍝ Recurse on the inputs with one incremented
⋄⍺+⍵} ⍝ Otherwise return the sum of the inputs
```
[Answer]
## Pyth, ~~14~~ 12 bytes
```
KsQW!OT=hK;K
```
My first real Pyth golf!
Takes input on STDIN in the format `a,b`.
Explanation:
```
KsQ read STDIN, assign sum to variable K
W while...
!OT not rand(10)
=hK; increment K
K implicit-output of K
```
Thanks to @FryAmTheEggman for shaving off two chars by giving me a shorter way to increment a variable!
[Answer]
# Lisp, 58 bytes
My first time writing Lisp!
```
(defun +(a b)(if(<(random 10)9)(- a(- b))(- a(-(+ b 1)))))
```
You can use this special addition exactly as you would usually add in Lisp:
```
> (+ 1 3)
4
> (+ 1 3)
5
```
I would love to hear suggestions as I am brand new to the language.
[Answer]
## Seriously, 10 bytes
```
,Σ1±╤_G_\+
```
This program generates a random variable from a geometric distribution by transforming a uniform distribution. It takes input as a list: `[2,3]` (braces optional). [Try it online](http://seriouslylang.herokuapp.com/link/code=2ce431f1d15f475f5c2b&input=2,2).
Explanation:
```
,Σ1±╤_G_\+
,Σ get sum of input
1±╤_ push ln(0.1)
G_ push ln(random(0,1))
\ floored division
+ add
```
Given a random variable `X ~ Uniform(0, 1)`, it can be transformed to a random variable `Y ~ Geometric(p)` with the formula `Y = floor(log(X)/log(p))`.
[Answer]
## Mathematica, 32 bytes
```
If[RandomReal[]<.1,+##,#0@##+1]&
```
Explanation:
```
& A function returning
If[ ] if
RandomReal[] a random number in [0,1)
< is less than
.1 .1
, , then
+ the sum of
## all arguments
, , otherwise,
#0@ this function applied to
## all arguments
+ plus
1 one.
```
Note that this function works for any number of inputs.
[Answer]
# [TeaScript](https://github.com/vihanb/TeaScript), 18 bytes ~~21~~
```
#$r<.1?f(l,i¬):l+i
```
This is a TeaScript function. Assign it to a variable or just run it directly.
[Try it online](http://vihanserver.tk/p/TeaScript/#?code=%22f%3D%23$r%3C.1%3Ff(l,i%C2%AC):l%2Bi;%5Cnf(3,4)%22&inputs=%5B%223%22,%224%22%5D&opts=%7B%22int%22:true,%22ar%22:false,%22debug%22:false,%22chars%22:false,%22html%22:false%7D)
[Answer]
# [Candy](https://github.com/dale6john/candy), 11 bytes
```
+#10H{.}10g
```
The long form is:
```
add # add two numbers on the stack
number digit1 digit0 rand # random int from 0 to 9
if # if non-zero
retSub # terminate loop
endif
digit1 # push 1 to stack
digit0 goto # loop to start
```
[Answer]
# C, ~~71~~ ~~51~~ ~~39~~ 37 bytes
First code-golf, done in C... I don't think it will beat anything, and may be golfed down a lot
EDIT 3: cuted 2 bytes thanks to @Mego , by writing .1 instead of 0.1 and rewriting the ternary operator
```
a(x,y){return(rand()<.1?a(1,y):y)+x;}
```
EDIT 2: cuted 12 bytes, following gnu99, every variable is an int if not stated otherwise. Same goes for the return type of function
```
a(x,y){return rand()<0.1?a(x,y+1):x+y;}
```
EDIT : cuted 20 bytes, forgot that basic .h aren't necessary in C99 (using gcc for instance). It will produce a warning :)
```
int a(int x,int y){return rand()<0.1?a(x,y+1):x+y;}
```
71 Bytes solution :
```
#include <stdlib.h>
int a(int x,int y){return rand()<0.1?a(x,y+1):x+y;}
```
If you want to see lots of output, you can use the following code
```
#include <stdio.h>
#include <stdlib.h>
int a(int x,int y){return rand()<0.1?a(x,y+1):x+y;}
int main(void)
{
int i,j;
for(i=0;i<10;i++)
for(j=0;j<10;j++)
printf("%d + %d = %d\n",i,j,a(i,j));
return 0;
}
```
[Answer]
# [MATL](https://esolangs.org/wiki/MATL), 12 ~~13~~ ~~14~~ bytes
```
r.1H$YlY[ihs
```
Input is of the form `[3 4]`, that is, a row vector with the two numbers.
### Example
```
>> matl r.1H$YlY[ihs
> [3 4]
7
```
### Explanation
This generates the geometric random variable without loops, by directly applying a a [transformation](https://en.wikipedia.org/wiki/Geometric_distribution#Related_distributions) to a uniform random variable. Note that log0.1 *a* is used instead of log *a* / log 0.1 to save 1 byte.
```
r % random number with uniform distribution in (0,1)
.1 % number 0.1
H$ % specify two inputs for next function
Yl % logarithm in specified base (0.1)
Y[ % floor. This produces the geometric random variable with parameter 0.1
i % input vector of two numbers
h % concatenate horizontally with the previously generated random value
s % sum of vector elements
```
[Answer]
# [Microscript](https://github.com/SuperJedi224/Microscript), ~~29~~ 21 bytes
```
isi+vzr10!{l1vzr10!}l
```
I tried to make a Microscript II answer but for some reason I couldn't get the addition loop to work right :(
[Answer]
# [Mouse-2002](https://github.com/catb0t/newmouse/blob/master/mouse.c), ~~41~~ ~~39~~ 38 bytes
No recursion.
```
&TIME &SEED ??&RAND k*&INT 9=[+1+!|+!]
```
Explained:
```
&TIME &SEED ~ painfully obvious
? ? ~ get some input
&RAND 10 * &INT 8 > ~ get a random number 0-1 * 10, make it an int & check if >8
[ ~ if true
+ 1 + ! ~ add the input then add 1 and print
| ~ else
+ ! ~ add and print
] ~ endif
$ ~ (implicit) end of program
```
---
Or, if you're a functional programming fanboy, and recursion is your deal then **57 bytes**:
```
&TIME &SEED #A,?,?;!$A&RAND k*&INT 9=[#A,1%,2%1+;|1%2%+]@
```
Explained:
```
&TIME &SEED ~ painfully obvious
#A, ?, ?; ! ~ call with input & print
$A ~ begin a definition of a function A
&RAND 10 * &INT 8 > ~ same as above
[
#A, 1%, 2% 1 +; ~ call with args and add 1
|
1% 2% + ~ else just add
]
@ ~ end func
$ ~ as above
```
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~13~~ 12 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?")[SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set")
Basically the same as [FryAmTheEggman's Pyth solution](https://codegolf.stackexchange.com/a/66536/43319). -1 thanks to Erik the Outgolfer.
Anonymous tacit infix function.
```
{⍵+1=?10}⍣=+
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///v/pR71ZtQ1t7Q4PaR72LbbX/pz1qm/Cot@9R31RP/0ddzYfWGz9qmwjkBQc5A8kQD8/g/8YKaYdWmBo86t1iovCod65CSVGlQmaJQnlmSYaCsUJiXoqCiUJaZlpJpUJJZm5qMQA "APL (Dyalog Unicode) – Try It Online")
`+` add the arguments
`{`…`}⍣=` apply the following function until two successive applications have the same result:
`?10` random integer in the range 1–10
`1=` is one equal to that? (i.e. 1⁄10th chance)
`⍵+` add the argument to that
[Answer]
# Java 8, ~~57~~ 56 bytes
4 years and no Java answer? Shame.
```
int a(int a,int b){return.1>Math.random()?a(a,b+1):a+b;}
```
[Try it online!](https://tio.run/##LcyxCoMwGEXhPU@RMUEbyFqhfQInR@lwY8TGapTkVyjis6dp6XKWA9@IHZfRvlI3IUZew/mDRQK5jifniUP8Wn5r5BF62oJX@laDnirA22UW8g6B0hRaXlGY6kzrZqYM/J19cZbPWRYNBeeH9oEwRHmw5h2pn9WykVrzoMkLCF1qKSt2nukD)
-1 byte thanks to ceilingcat
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `RṀ`, 7 bytes
```
+{₀℅¬|›
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=R%E1%B9%80&code=%2B%7B%E2%82%80%E2%84%85%C2%AC%7C%E2%80%BA&inputs=1%0A2&header=&footer=)
# [Vyxal](https://github.com/Vyxal/Vyxal), 8 bytes
```
+{₀ʁ℅¬|›
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=%2B%7B%E2%82%80%CA%81%E2%84%85%C2%AC%7C%E2%80%BA&inputs=1%0A2&header=&footer=)
```
+ # Add the two (implicitly input) numbers
{ # While...
℅ # Random choice of...
ʁ # range 0 to... (Unnecessary in flagged version)
₀ # 10 (exclusive)
¬ # Is 0
|› # Increment
```
[Answer]
# [Julia 1.0](http://julialang.org/), 27 bytes
```
a\b=rand()<.1 ? 1+a\b : a+b
```
[Try it online!](https://tio.run/##yyrNyUw0rPj/PzEmybYoMS9FQ9NGz1DBXsFQGyiiYKWQqJ30v6AoM68kJ0@juDRXwyDGQCEtv0ghUyEzT8HQytDAwEBTkwumQpOLC1WSSwEIYLImMaaaXKl5Kf8B "Julia 1.0 – Try It Online")
**Bonus: for 2 additionnal bytes, we can overwrite the `+` function for even more fun:**
```
a+b=rand()<.1 ? -~a+b : a- -b
```
[Try it online!](https://tio.run/##yyrNyUw0rPj/P1E7ybYoMS9FQ9NGz1DBXkG3DiiiYKWQqKugm/S/oCgzryQnT6O4NFfDQNtAIS2/SCFTITNPwdDK0MDAQFOTC6ZCk4sLVZJLAQgcijPyyxVMtE25UvNS/gMA "Julia 1.0 – Try It Online")
[Answer]
# [Jelly](http://github.com/DennisMitchell/jelly), 7 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
‘⁵XỊ¤¿+
```
[Try it online!](http://jelly.tryitonline.net/#code=4oCY4oG1WOG7isKkwr8r&input=&args=MTM+Mjk)
### How it works
```
‘⁵XỊ¤¿+ Main link. Arguments: n, m (integers)
¤ Combine the three atoms to the left into a niladic chain.
⁵ Yield 10.
X Pseudo-randomly generate a positive integer not greater than 10.
Ị Insignificant; test if the generated integer is 1 (or less).
¿ While chain yields 1:
‘ Increment n.
+ Add m to the result.
```
[Answer]
# [Perl 6](http://perl6.org), 26 bytes
Actually doing it recursively:
```
sub f{.1>rand??f |@_,1!![+] @_} # 31 bytes
```
---
Create a possibly empty sequence of `1`s followed by the arguments, then sum them all together.
```
{[+] {1}...^{rand>.1},|@_} # 26 bytes
```
( it can actually take any number of arguments )
usage:
```
# give the lambda a name
my &f = {...}
say f 1,2; # one of 3,4,5 ... *
```
[Answer]
## Pyth, 11 bytes
```
+sQ-18l`hO0
```
A direct Pyth port of my [Python answer](https://codegolf.stackexchange.com/a/66538/20260).
```
+ Add up
sQ the sum of the input and
- the difference of
18 18 and
l` the string length of
hO0 one plus a random number in [0,1)
```
[Answer]
# Octave, 20 bytes
```
@(a,b)a+b+geornd(.9)
```
Sum of the inputs, plus a random sample from the geometric distribution with parameter `0.9`.
] |
[Question]
[
In a [programming language](http://meta.codegolf.stackexchange.com/a/2073/26997) of your choice, write 95 programs, each of which outputs a different one of the [95 printable ASCII characters](https://en.wikipedia.org/wiki/ASCII#Printable_characters) ***without that character occurring anywhere in the program***.
For example, if your language was [Python](https://en.wikipedia.org/wiki/Python_(programming_language)), your program that outputs the character `P` might be
```
print(chr(80))
```
because `P` has ASCII code 80. This program is valid because `P` never appears in the source code. However, for the program that outputs lowercase `p`, something like
```
print(chr(112))
```
would be invalid because, while it does print `p`, `p` is present in the code. A valid program could be
```
exec(chr(112)+'rint(chr(112))')
```
which prints `p` but does not contain `p`.
**Your goal is to make each of your 95 programs as short as possible.** Your ***score*** is the sum of the character lengths of all your programs.
If for any reason you are unable to write valid programs for some characters, you may mark those characters as "Did Not Program" or ***DNP***, and omit programs for them entirely. This way syntactically strict languages will be able to compete.
**The winning answer is the answer that has the lowest score *of* the set of answers that have the fewest DNP's.**
# Rules
* The source code of all of your programs may only contain [printable ASCII](https://en.wikipedia.org/wiki/ASCII#Printable_characters) plus tabs and newlines, all of which are counted as one character. (Because in a different encoding it would be easy to omit characters that don't exist!)
+ **Note:** This rule seems necessary but there are many languages with different encodings and I'm sure it'd be cool to see the answers for them. Therefore **you can break this rule**, you can use whatever characters you want, **but then your answer becomes non-competitive**, it cannot win.
* The programs must be actual, full *programs*, according to your language's standard conventions. Functions and [REPL](https://en.wikipedia.org/wiki/Read%E2%80%93eval%E2%80%93print_loop) snippets are not allowed.
* Each program's output should go to stdout or your language's accepted alternative.
* Programs should not prompt for or require input. (If prompting for input is inherent to your language, that's ok.)
* Programs should be deterministic, finite in run time, and independent. e.g. it shouldn't matter if one is run in a folder separate from the other programs.
* A program's output should be the precise printable ASCII character it corresponds to, optionally followed by a single trailing newline, nothing more, nothing less.
Be sure to include information on all 95 (ideally) programs in your answer, as well as your score and any DNP's. You don't have to list *all* programs that follow a simple pattern like "`print(chr(80))`, `print(chr(81))`, `print(chr(82))`..." but make sure you're sure they all *would* work and that your score is added correctly.
For reference, here are the 95 [printable ASCII](https://en.wikipedia.org/wiki/ASCII#Printable_characters) your programs must output:
```
!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~
```
[Answer]
# Python 2, ~~1075~~ ~~1065~~ ~~1043~~ ~~1040~~ 1039 bytes
Each program has the form `print'\<octal char code>'`, except:
* `'` → `print"\47"`
* `0` through `8` → `print~-<N+1>`
* `9` → `print-~8`
* `\` → `print'%c'%92`
* `i` → `exec'pr\151nt"\151"'`
* `n` → `exec'pri\156t"\156"'`
* `p` → `exec'\160rint"\160"'`
* `r` → `exec'p\162int"\162"'`
* `t` → `exec'prin\164"\164"'`
For reference and ease of testing, here's the full list of programs, newline-separated.
```
print'\40'
print'\41'
print'\42'
print'\43'
print'\44'
print'\45'
print'\46'
print"\47"
print'\50'
print'\51'
print'\52'
print'\53'
print'\54'
print'\55'
print'\56'
print'\57'
print~-1
print~-2
print~-3
print~-4
print~-5
print~-6
print~-7
print~-8
print~-9
print-~8
print'\72'
print'\73'
print'\74'
print'\75'
print'\76'
print'\77'
print'\100'
print'\101'
print'\102'
print'\103'
print'\104'
print'\105'
print'\106'
print'\107'
print'\110'
print'\111'
print'\112'
print'\113'
print'\114'
print'\115'
print'\116'
print'\117'
print'\120'
print'\121'
print'\122'
print'\123'
print'\124'
print'\125'
print'\126'
print'\127'
print'\130'
print'\131'
print'\132'
print'\133'
print'%c'%92
print'\135'
print'\136'
print'\137'
print'\140'
print'\141'
print'\142'
print'\143'
print'\144'
print'\145'
print'\146'
print'\147'
print'\150'
exec'pr\151nt"\151"'
print'\152'
print'\153'
print'\154'
print'\155'
exec'pri\156t"\156"'
print'\157'
exec'\160rint"\160"'
print'\161'
exec'p\162int"\162"'
print'\163'
exec'prin\164"\164"'
print'\165'
print'\166'
print'\167'
print'\170'
print'\171'
print'\172'
print'\173'
print'\174'
print'\175'
print'\176'
```
To test:
```
$ python printables.py | sed ':a;N;$!ba;s/\n//g'
!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~
```
*-1 bytes thanks to @Sp3000!*
[Answer]
# CJam, 269 bytes
Each of the programs are in the form `'<char - 1>)` except for:
* Space => `S`, 1 byte
* `'` => `39c`, 3 bytes
* `)` => `'*(`, 3 bytes
* `0` => `T`, 1 byte
* `1` => `X`, 1 byte
* `2` => `Y`, 1 byte
* `3` => `Z`, 1 byte
* `4`-`9` => `<num-1>)`, 2 bytes
Score is: `3 * 82 + 1 + 3 + 3 + 4 * 1 + 6 * 2 = 269`
[Answer]
## Brainfuck, ~~1770~~ ~~1710~~ ~~1703~~ 1686 bytes
*60 bytes saved by Dennis*
*17 bytes saved by Sp3000*
DNP: 46 (`.`)
```
>-[-[-<]>>+<]>-.
>-[-[-<]>>+<]>.
>-[-[-<]>>+<]>+.
>-[++>+[<]>+]>.
+[->-[---<]>-]>.
>-[+<[-<]>>++]<.
>+[-->+[<]>-]>-.
>+[-->+[<]>-]>.
>+[-->+[<]>-]>+.
--[>+<++++++]>--.
--[>+<++++++]>-.
-----[[----<]>>-]<.
--[>+<++++++]>+.
+[+[+>]<<++++]>.
+[-[--<]>>--]<.
-[>+<-----]>---.
-[>+<-----]>--.
-[>+<-----]>-.
-[>+<-----]>.
-[>+<-----]>+.
-[>+<-----]>++.
-[>+<-----]>+++.
>-[++>+[+<]>]>-.
>-[++>+[+<]>]>.
>-[++>+[+<]>]>+.
>-[++[+<]>>+<]>.
>+[+[<]>->++]<.
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.
+[-[>+<<]>-]>--.
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.
+[-[>+<<]>-]>.
-[+[>+<<]>+]>.
>+[+[<]>>+<+]>.
--[++>+[<]>+]>.
+[->-[--<]>-]>.
+[->-[--<]>-]>+.
+[->-[--<]>-]>++.
-[+[>---<<]>+]>.
-[>+<-------]>--.
-[>+<-------]>-.
-[>+<-------]>.
-[>+<-------]>+.
-[>+<-------]>++.
>+[+<[-<]>>++]<.
>+++[[-<]>>--]<.
+[+[>>+<+<-]>]>.
-[+>++[++<]>]>-.
-[+>++[++<]>]>.
-[>+<---]>----.
-[>+<---]>---.
-[>+<---]>--.
-[>+<---]>-.
-[>+<---]>.
-[>+<---]>+.
-[>+<---]>++.
-[+[+<]>>+]<.
-[+[+<]>>+]<+.
-[+[+<]>>+]<++.
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.
+[->---[-<]>-]>.
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.
>-->+[+[+<]>>+]<.
>+[+[>+<+<]>]>-.
>+[+[>+<+<]>]>.
+[-[---<]>>-]<-.
+[-[---<]>>-]<.
>-[--[<]>+>-]<.
-[>++<-----]>--.
-[>++<-----]>-.
-[>++<-----]>.
-[>++<-----]>+.
+[->-[<]>--]>-.
+[->-[<]>--]>.
+[->-[<]>--]>+.
>+[++[++>]<<+]>.
>+[++[++>]<<+]>+.
+[->-[<]>+>--]>.
-[>--<-------]>.
>+[+>+[<]>->]<.
>+[+>+[<]>->]<+.
-[+>+++++[<]>+]>.
>+[-->++[<]>-]>.
+[->->-[<]>--]>.
+[->->-[-<]>-]>.
+[->>-[-<+<]>]>.
----[>+++++<--]>.
------[>+++<--]>.
>+[>+[<]>->+]<-.
>+[>+[<]>->+]<.
----[>+++<--]>.
--[>+<--]>----.
--[>+<--]>---.
--[>+<--]>--.
--[>+<--]>-.
```
All except 43, 45, 60, 62, 91 and 93 are shamelessly stolen from [Esolangs.org](https://esolangs.org/wiki/Brainfuck_constants)
[Answer]
## ASCII constrained x86 Machine Code for DOS, ~~3104~~ ~~3101~~ 2913 bytes
*Well... It's shorter than Java, I guess...*
~~32~~ 30 bytes for almost all characters, for exceptions see below.
Most of the time it just follows the pattern:
1. Do some `xor` to get a pointer to the end.
2. `sub` from the last 2 words because the opcode for `int` is not in ASCII.
3. Get 2 into `AH` and the character into `DL`. Both are `xor`ed because the character itself can't appear in the program and 2 is not a printable ASCII character.
4. Print the character with `int 21h`
5. Exit with `int 20h`
Most of the time, if a character is disallowed, it can be replaced by either twiddling with the data a bit or switching to a different register.
It gets a bit more interesting when you suddenly find yourself unable to subtract or unable to push or pop the only register usable for calculations...
```
char code
hX'X5B&P[hT!^)7CC)7VX5t#PZ!C!B
! hX'X5B&P[hS ^)7CC)7VX5r"PZ B A
" hX'X5B&P[hS!^)7CC)7VX5q#PZ C B
# hX'X5B&P[hS ^)7CC)7VX5p"PZ B A
$ hX'X5B&P[hS ^)7CC)7VX5w"PZ B A
% hX'X5B&P[hS ^)7CC)7VX5v"PZ B A
& hX#X5B"P[hS ^)7CC)7VX5u"PZ B A
' hX#X5B"P[hS ^)7CC)7VX5t"PZ B A
( hX'X5B&P[hS ^)7CC)7VX5{"PZ B A
) hi'X5B&P[h!!X%BBHP^$!P_17C!?C17C!?hiBX5@@PZ2@2A
* hX'X5B&P[hS ^)7CC)7VX5y"PZ B A
+ hX'X5B&P[hS ^)7CC)7VX5x"PZ B A
, hX'X5B&P[hT ^)7CC)7VX5x"PZ!B!A
- hX'X5B&P[hS ^)7CC)7VX5~"PZ B A
. hX'X5B&P[hS ^)7CC)7VX5}"PZ B A
/ hX'X5B&P[hS ^)7CC)7VX5|"PZ B A
0 hX'X5B&P[hS ^)7CC)7VX5c"PZ B A
1 hX'X5B&P[hS ^)7CC)7VX5b"PZ B A
2 hX'X5B&P[hS ^)7CC)7VX5a"PZ B A
3 hX'X5B&P[hS ^)7CC)7VX5`"PZ B A
4 hX'X5B&P[hS ^)7CC)7VX5g"PZ B A
5 h;'X%[AP[h=S^)7CC)7VX%7"PZ _ ^
6 hX'X5B&P[hS ^)7CC)7VX5e"PZ B A
7 hX'X5B&P[hS _)?CC)?WX5d"PZ B A
8 hX'X5B&P[hS ^)7CC)7VX5k"PZ B A
9 hX'X5B&P[hS ^)7CC)7VX5j"PZ B A
: hX'X5B&P[hS ^)7CC)7VX5i"PZ B A
; hX'X5B&P[hS ^)7CC)7VX5h"PZ B A
< hX'X5B&P[hS ^)7CC)7VX5o"PZ B A
= hX'X5B&P[hS ^)7CC)7VX5n"PZ B A
> hX'X5B&P[hS ^)7CC)7VX5m"PZ B A
? hX'X5B&P[hS ^)7CC)7VX5l"PZ B A
@ hX'X5B&P[h` ^)7CC)7VX5 "PZ-B-A
A hX'X5B&P[h`!^)7CC)7VX5!#PZ-C-B
B h['X5A&P[h`"^)7CC)7VX5" PZ-D-C
C hX'X5B&P_h` ^)5GG)5VX5#"PZ-B-A
D hX'X5B&P[h` ^)7CC)7VX5$"PZ-B-A
E hX'X5B&P[h` ^)7CC)7VX5%"PZ-B-A
F hX'X5B&P[h` ^)7CC)7VX5&"PZ-B-A
G hX'X5B&P[h` ^)7CC)7VX5'"PZ-B-A
H hX'X5B&P[h` ^)7CC)7VX5("PZ-B-A
I hX'X5B&P[h` ^)7CC)7VX5)"PZ-B-A
J hX'X5B&P[h` ^)7CC)7VX5*"PZ-B-A
K hX'X5B&P[h` ^)7CC)7VX5+"PZ-B-A
L hX'X5B&P[h` ^)7CC)7VX5,"PZ-B-A
M hX'X5B&P[h` ^)7CC)7VX5-"PZ-B-A
N hX'X5B&P[h` ^)7CC)7VX5."PZ-B-A
O hX'X5B&P[h` ^)7CC)7VX5/"PZ-B-A
P hj'X5B&`[[[[[[[[h` ^)7CC)7VX50"`ZZZZZZZZ-B-A
Q hX'X5B&P[h` ^)7CC)7VX51"PZ-B-A
R hX'X5B&P[h` ^)7CC)7VX52"PZ-B-A
S hX'X5B&P[h` ^)7CC)7VX53"PZ-B-A
T hX'X5B&P[h` ^)7CC)7VX54"PZ-B-A
U hX'X5B&P[h` ^)7CC)7VX55"PZ-B-A
V hX'X5B&P[h` _)?CC)?WX56"PZ B A
W hX'X5B&P[h` ^)7CC)7VX57"PZ-B-A
X _TYhe'WWWQWWWa5B&P[hSS^)7CC)7CC5_C5 @PZ u t
Y hX'X5B&P[h` ^)7CC)7VX59"PZ-B-A
Z _WTYhzBX5 @Phe'WPWQWWWa5B&P[hSS^)7CC)7X u t
[ hX'X5B&P_h` ^)5GG)5VX5;"PZ-B-A
\ hX'X5B&P[h` ^)7CC)7VX5<"PZ-B-A
] hX'X5B&P[h` ^)7CC)7VX5="PZ-B-A
^ hX'X5B&P[h` _)?CC)?WX5>"PZ-B-A
_ hX'X5B&P[h` ^)7CC)7VX5?"PZ-B-A
` hX'X5B&P[hS ^)7CC)7VX53"PZ B A
a hX'X5B&P[hS ^)7CC)7VX52"PZ B A
b hX'X5B&P[hS ^)7CC)7VX51"PZ B A
c hX'X5B&P[hS ^)7CC)7VX50"PZ B A
d hX'X5B&P[hS ^)7CC)7VX57"PZ B A
e hX'X5B&P[hS ^)7CC)7VX56"PZ B A
f hX'X5B&P[hS ^)7CC)7VX55"PZ B A
g hX'X5B&P[hS ^)7CC)7VX54"PZ B A
h _WWX5b'5B&P[WX5S P^)7CC)7VX5;"PZ B A
i hX'X5B&P[hS ^)7CC)7VX5:"PZ B A
j hX'X5B&P[hS ^)7CC)7VX59"PZ B A
k hX'X5B&P[hS ^)7CC)7VX58"PZ B A
l hX'X5B&P[hS ^)7CC)7VX5?"PZ B A
m hX'X5B&P[hS ^)7CC)7VX5>"PZ B A
n hX'X5B&P[hS ^)7CC)7VX5="PZ B A
o hX'X5B&P[hS ^)7CC)7VX5<"PZ B A
p hX'X5B&P[hS ^)7CC)7VX5#"PZ B A
q hX'X5B&P[hS ^)7CC)7VX5""PZ B A
r hX'X5B&P[hS ^)7CC)7VX5!"PZ B A
s hX'X5B&P[hS ^)7CC)7VX5 "PZ B A
t hX'X5B&P[hS ^)7CC)7VX5'"PZ B A
u hX'X5B&P[hS ^)7CC)7VX5&"PZ B A
v hX'X5B&P[hS ^)7CC)7VX5%"PZ B A
w hX'X5B&P[hS ^)7CC)7VX5$"PZ B A
x hX'X5B&P[hS ^)7CC)7VX5+"PZ B A
y hX'X5B&P[hS ^)7CC)7VX5*"PZ B A
z hX'X5B&P[hS ^)7CC)7VX5)"PZ B A
{ hX'X5B&P[hS ^)7CC)7VX5("PZ B A
| hX'X5B&P[hS ^)7CC)7VX5/"PZ B A
} hX'X5B&P[hS ^)7CC)7VX5."PZ B A
~ hX'X5B&P[hS ^)7CC)7VX5-"PZ B A
```
[Answer]
# Java 8, ~~6798~~ ~~6582~~ 6577 bytes
*sigh*
This is basically a port of [my Python 2 answer](https://codegolf.stackexchange.com/a/90530/56755), but with all the boilerplate that comes with writing a full program in Java.
Now without any DNPs at all! Thanks, Kevin Cruijssen!
Most of the programs have the form `interface A{static void main(String[]a){System.out.print("\<octal char code>");}}`, except:
* space → `interface\tA{static\tvoid\tmain(String[]a){System.out.print("\40");}}` (but with the `\t`s replaced by raw tabs)
* `"` → `interface A{static void main(String[]a){System.out.print('\42');}}`
* `(` → `interface A{static void main\u0028String[]a){System.out.print\u0028"\50");}}`
* `)` → `interface A{static void main(String[]a\u0029{System.out.print("\51"\u0029;}}`
* `.` → `interface A{static void main(String[]a){System\u002Eout\u002Eprint("\56");}}`
* `0` → `interface A{static void main(String[]a){System.out.print(1-1);}}`
* `1` → `interface A{static void main(String[]a){System.out.print(3-2);}}`
* `2` → `interface A{static void main(String[]a){System.out.print(3-1);}}`
* `3` → `interface A{static void main(String[]a){System.out.print(4-1);}}`
* `4` → `interface A{static void main(String[]a){System.out.print(5-1);}}`
* `5` → `interface A{static void main(String[]a){System.out.print(6-1);}}`
* `6` → `interface A{static void main(String[]a){System.out.print(7-1);}}`
* `7` → `interface A{static void main(String[]a){System.out.print(8-1);}}`
* `8` → `interface A{static void main(String[]a){System.out.print(9-1);}}`
* `9` → `interface A{static void main(String[]a){System.out.print(8+1);}}`
* `;` → `interface A{static void main(String[]a){System.out.print("\73")\u003B}}`
* `A` → `interface B{static void main(String[]a){System.out.print("\101");}}`
* `S` → `interface A{static void main(\u0053tring[]a){\u0053ystem.out.print("\123");}}`
* `[` → `interface A{static void main(String...a){System.out.print("\133");}}`
* `\` → `interface A{static void main(String[]a){System.out.print((char)92);}}`
* `]` → `interface A{static void main(String...a){System.out.print("\135");}}`
* `a` → `interf\u0061ce A{st\u0061tic void m\u0061in(String[]b){System.out.print("\141");}}`
* `c` → `interfa\u0063e A{stati\u0063 void main(String[]a){System.out.print("\143");}}`
* `d` → `interface A{static voi\u0064 main(String[]a){System.out.print("\144");}}`
* `e` → `class A{public static void main(String[]a){Syst\u0065m.out.print("\145");}}`
* `f` → `class A{public static void main(String[]a){System.out.print("\146");}}`
* `g` → `interface A{static void main(Strin\u0067[]a){System.out.print("\147");}}// \u0067`
* `i` → `\u0069nterface A{stat\u0069c vo\u0069d ma\u0069n(Str\u0069ng[]a){System.out.pr\u0069nt("\151");}}`
* `m` → `interface A{static void \u006Dain(String[]a){Syste\u006D.out.print("\155");}}`
* `n` → `class A{public static void mai\u006E(Stri\u006Eg[]a){System.out.pri\u006Et("\156");}}`
* `o` → `interface A{static v\u006Fid main(String[]a){System.\u006Fut.print("\157");}}`
* `p` → `interface A{static void main(String[]a){System.out.\u0070rint("\160");}}`
* `r` → `class A{public static void main(St\u0072ing[]a){System.out.p\u0072int("\162");}}`
* `s` → `interface A{\u0073tatic void main(String[]a){Sy\u0073tem.out.print("\163");}}`
* `t` → `class A{public s\u0074a\u0074ic void main(S\u0074ring[]a){Sys\u0074em.ou\u0074.prin\u0074("\164");}}`
* `u` → `interface A{static void main(String[]a){System.console().printf("%c",117);}}`
* `v` → `interface A{static \u0076oid main(String[]a){System.out.print("\166");}}`
* `y` → `interface A{static void main(String[]a){S\u0079stem.out.print("\171");}}`
* `{` → `interface A\u007Bstatic void main(String[]a)\u007BSystem.out.print("\173");}}`
* `}` → `interface A{static void main(String[]a){System.out.print("\175");\u007D\u007D`
*Phew*
The Java compiler processes Unicode escapes like `\u007B` before doing any other processing, which makes it possible to write code which uses unicode escapes in identifiers and even keywords. So, to write a program that doesn't use a character present in the boilerplate, we simply substitute it with it unicode escape.
For reference and ease of testing, here's the full list of programs, newline-separated and with the raw tabs replaced by four spaces:
```
interface A{static void main(String[]a){System.out.print("\40");}}
interface A{static void main(String[]a){System.out.print("\41");}}
interface A{static void main(String[]a){System.out.print('\42');}}
interface A{static void main(String[]a){System.out.print("\43");}}
interface A{static void main(String[]a){System.out.print("\44");}}
interface A{static void main(String[]a){System.out.print("\45");}}
interface A{static void main(String[]a){System.out.print("\46");}}
interface A{static void main(String[]a){System.out.print("\47");}}
interface A{static void main\u0028String[]a){System.out.print\u0028"\50");}}
interface A{static void main(String[]a\u0029{System.out.print("\51"\u0029;}}
interface A{static void main(String[]a){System.out.print("\52");}}
interface A{static void main(String[]a){System.out.print("\53");}}
interface A{static void main(String[]a){System.out.print("\54");}}
interface A{static void main(String[]a){System.out.print("\55");}}
interface A{static void main(String[]a){System\u002Eout\u002Eprint("\56");}}
interface A{static void main(String[]a){System.out.print("\57");}}
interface A{static void main(String[]a){System.out.print(1-1);}}
interface A{static void main(String[]a){System.out.print(3-2);}}
interface A{static void main(String[]a){System.out.print(3-1);}}
interface A{static void main(String[]a){System.out.print(4-1);}}
interface A{static void main(String[]a){System.out.print(5-1);}}
interface A{static void main(String[]a){System.out.print(6-1);}}
interface A{static void main(String[]a){System.out.print(7-1);}}
interface A{static void main(String[]a){System.out.print(8-1);}}
interface A{static void main(String[]a){System.out.print(9-1);}}
interface A{static void main(String[]a){System.out.print(8+1);}}
interface A{static void main(String[]a){System.out.print("\72");}}
interface A{static void main(String[]a){System.out.print("\73")\u003B}}
interface A{static void main(String[]a){System.out.print("\74");}}
interface A{static void main(String[]a){System.out.print("\75");}}
interface A{static void main(String[]a){System.out.print("\76");}}
interface A{static void main(String[]a){System.out.print("\77");}}
interface A{static void main(String[]a){System.out.print("\100");}}
interface B{static void main(String[]a){System.out.print("\101");}}
interface A{static void main(String[]a){System.out.print("\102");}}
interface A{static void main(String[]a){System.out.print("\103");}}
interface A{static void main(String[]a){System.out.print("\104");}}
interface A{static void main(String[]a){System.out.print("\105");}}
interface A{static void main(String[]a){System.out.print("\106");}}
interface A{static void main(String[]a){System.out.print("\107");}}
interface A{static void main(String[]a){System.out.print("\110");}}
interface A{static void main(String[]a){System.out.print("\111");}}
interface A{static void main(String[]a){System.out.print("\112");}}
interface A{static void main(String[]a){System.out.print("\113");}}
interface A{static void main(String[]a){System.out.print("\114");}}
interface A{static void main(String[]a){System.out.print("\115");}}
interface A{static void main(String[]a){System.out.print("\116");}}
interface A{static void main(String[]a){System.out.print("\117");}}
interface A{static void main(String[]a){System.out.print("\120");}}
interface A{static void main(String[]a){System.out.print("\121");}}
interface A{static void main(String[]a){System.out.print("\122");}}
interface A{static void main(\u0053tring[]a){\u0053ystem.out.print("\123");}}
interface A{static void main(String[]a){System.out.print("\124");}}
interface A{static void main(String[]a){System.out.print("\125");}}
interface A{static void main(String[]a){System.out.print("\126");}}
interface A{static void main(String[]a){System.out.print("\127");}}
interface A{static void main(String[]a){System.out.print("\130");}}
interface A{static void main(String[]a){System.out.print("\131");}}
interface A{static void main(String[]a){System.out.print("\132");}}
interface A{static void main(String...a){System.out.print("\133");}}
interface A{static void main(String[]a){System.out.print((char)92);}}
interface A{static void main(String...a){System.out.print("\135");}}
interface A{static void main(String[]a){System.out.print("\136");}}
interface A{static void main(String[]a){System.out.print("\137");}}
interface A{static void main(String[]a){System.out.print("\140");}}
interf\u0061ce A{st\u0061tic void m\u0061in(String[]b){System.out.print("\141");}}
interface A{static void main(String[]a){System.out.print("\142");}}
interfa\u0063e A{stati\u0063 void main(String[]a){System.out.print("\143");}}
interface A{static voi\u0064 main(String[]a){System.out.print("\144");}}
class A{public static void main(String[]a){Syst\u0065m.out.print("\145");}}
class A{public static void main(String[]a){System.out.print("\146");}}
interface A{static void main(Strin\u0067[]a){System.out.print("\147");}}
interface A{static void main(String[]a){System.out.print("\150");}}
\u0069nterface A{stat\u0069c vo\u0069d ma\u0069n(Str\u0069ng[]a){System.out.pr\u0069nt("\151");}}
interface A{static void main(String[]a){System.out.print("\152");}}
interface A{static void main(String[]a){System.out.print("\153");}}
interface A{static void main(String[]a){System.out.print("\154");}}
interface A{static void \u006Dain(String[]a){Syste\u006D.out.print("\155");}}
class A{public static void mai\u006E(Stri\u006Eg[]a){System.out.print("\156");}}
interface A{static v\u006Fid main(String[]a){System.\u006Fut.print("\157");}}
interface A{static void main(String[]a){System.out.\u0070rint("\160");}}
interface A{static void main(String[]a){System.out.print("\161");}}
class A{public static void main(St\u0072ing[]a){System.out.p\u0072int("\162");}}
interface A{\u0073tatic void main(String[]a){Sy\u0073tem.out.print("\163");}}
class A{public s\u0074a\u0074ic void main(S\u0074ring[]a){Sys\u0074em.ou\u0074.prin\u0074("\164");}}
interface A{static void main(String[]a){System.console().printf("%c",117);}}
interface A{static \u0076oid main(String[]a){System.out.print("\166");}}
interface A{static void main(String[]a){System.out.print("\167");}}
interface A{static void main(String[]a){System.out.print("\170");}}
interface A{static void main(String[]a){S\u0079stem.out.print("\171");}}
interface A{static void main(String[]a){System.out.print("\172");}}
interface A\u007Bstatic void main(String[]a)\u007BSystem.out.print("\173");}}
interface A{static void main(String[]a){System.out.print("\174");}}
interface A{static void main(String[]a){System.out.print("\175");\u007D\u007D
interface A{static void main(String[]a){System.out.print("\176");}}
```
Note that the program for `u` makes use of `System.console()`, which will return null (and thus cause the code to throw a `NullPointerException`) if you call it from anything other than your OS' native terminal (`cmd` on Windows, and, I assume, `bash` on Linux/OSX).
To test, make a new directory and put the above code in a file named `printables` in that directory. Then, run the following Bash script:
```
#!/bin/bash
split -l 1 printables
for i in x*; do
mkdir z$i
mv $i z$i/A.java
done
mv zxbh/A.java zxbh/B.java
for i in zx*; do
javac $i/[AB].java
if ! java -cp $i A 2> /dev/null; then
java -cp $i B
fi
done
rm -r zx*
```
The above script will put each line of `printables` into its own directory, name them all `A.java` (except for the file which prints `A`, which is renamed to `B.java`), compile each file, run them, then delete the evidence. It should take about ten seconds for the printable ASCII characters to start appearing in your shell.
If you're on Windows, instead run the following Batch file:
```
@echo off
setlocal enabledelayedexpansion
set i=0
for /F "tokens=*" %%L in (printables) do (
set file=A.java
if "%i%" == "33" (set file=B.java)
echo %%L>"%file%"
javac "%file%"
java -cp . A
if not errorlevel 0 (java -cp . B)
set /A i=%i% + 1
)
del *.java
del *.class
```
This batch file takes a slightly different approach; instead of pre-splitting the lines, it processes the file line-by-line and compiles and runs each program in turn. Again, it deletes the evidence after it finishes.
*Saved countless bytes + the 1 DNP thanks to Kevin Cruijssen!*
[Answer]
# MATL, ~~305, 302, 300~~ 297 bytes
Every single program looks like this:
```
33c
34c
35c
....
```
Except for
* Digits. Here are the programs for 0-9:
```
O
l
H
I
K
4Q
5Q
6Q
7Q
8Q
```
* 'c'. This program is
```
'C'k
```
* space. This is
```
0c
```
Since today I learned, that MATL treats character 0 as space. *Thanks @LuisMendo!*
You can use [matl.tio](http://matl.tryitonline.net/) to verify any of them.
For reference, here is all of them:
```
0c
33c
34c
35c
36c
37c
38c
39c
40c
41c
42c
43c
44c
45c
46c
47c
O
l
H
I
K
4Q
5Q
6Q
7Q
8Q
58c
59c
60c
61c
62c
63c
64c
65c
66c
67c
68c
69c
70c
71c
72c
73c
74c
75c
76c
77c
78c
79c
80c
81c
82c
83c
84c
85c
86c
87c
88c
89c
90c
91c
92c
93c
94c
95c
96c
97c
98c
'C'k
100c
101c
102c
103c
104c
105c
106c
107c
108c
109c
110c
111c
112c
113c
114c
115c
116c
117c
118c
119c
120c
121c
122c
123c
124c
125c
126c
```
[Answer]
## [><>](http://esolangs.org/wiki/Fish), ~~443~~ 437 bytes
[TIO interpreter link](http://fish.tryitonline.net). There's a lot of patterns here:
* **`[num][num]*o;`:** Multiplication of two numbers, then output the result as a char with `o` and halt with `;`. ><> digits go up to 15, i.e. `0123456789abcdef`.
+ Similarly `[num][num]-n;`, which takes the difference of two numbers and outputs as a number with `n` instead.
* **`'-o[invalid char]`:** ><> is toroidal, so when the instruction pointer reaches the end of a line it moves back to the beginning. In this case, this causes the code to be executed twice, i.e. `'-o[char]'-o[char]`. The first `'-o[char]'` part pushes three chars to the stack, `-` calculates `'o' - [char]` then `o` outputs the result as a character. ><> then errors out when it reaches `[char]`, either due to an unrecognised command or from popping an empty stack.
+ Similarly `'-n[invalid char]`, which outputs as a number.
+ Similarly `'[num][op]o[invalid char]`, which applies `[op]` with `[num]` on `[char]`, erroring out on char. For example, `'2+oJ` outputs `L`, which is two more than `J`.
+ `'`'s code is `"-oH`, using `"` instead.
+ `-`'s code is `'%oB`, using `%` instead.
* **`ln;`**: Push length of stack, output as num then halt, giving `0`. Similarly `lln;` for `1` and `'ln;` for `3`.
* **`4|n+`:** Push 4, bounce off the `|` and push another 4, add, then output `8` as num. Bounce off the `|` again, and error out trying to execute `n` again on an empty stack.
+ Similarly `3|n*` for `9`.
+ Similarly `[num]|o*` for `@Qdy`.
* **`'1-:00p`:** The most interesting one, for the `o` case. To avoid using `o` in our code, we need to use `p` to place an `o` in the codebox, then run it. The initial `'1-:00p'` sets the stack up to have a `p` on top, and `1-` decrements it into an `o`. `:` duplicates this `o`, and `00p` places one `o` at (0, 0), turning the codebox into `o1-:00p`. The instruction pointer wraps again, outputting the other `o`. The (0, 0) char is then replaced a few more times before the program finally errors out.
```
'-oO
! '-oN
" '-oM
# '-oL
$ '-oK
% '-oJ
& '-oI
' "-oH
( '-oG
) '-oF
* '-oE
+ '-oD
, '-oC
- '%oB
. '-oA
/ '-o@
0 ln;
1 lln;
2 '-o=
3 'ln;
4 '-o;
5 61-n;
6 '-nh
7 '-ng
8 4|n+
9 3|n*
: '1-o;
; '6-oA
< 6a*o;
= '2+o;
> '3+o;
? 79*o;
@ 8|o*
A '-o.
B '-o-
C '-o,
D '-o+
E '-o*
F '-o)
G '-o(
H 89*o;
I '1-oJ
J '-o%
K '-o$
L '2+oJ
M 7b*o;
N '-o!
O '5+oJ
P 8a*o;
Q 9|o*
R '8+oJ
S '9+oJ
T 7c*o;
U 'b+oJ
V 'c+oJ
W 'd+oJ
X 8b*o;
Y 'f+oJ
Z 9a*o;
[ 7d*o;
\ 'c-oh
] 'b-oh
^ 'a-oh
_ '9-oh
` 8c*o;
a '7-oh
b 7e*o;
c 9b*o;
d a|o*
e '3-oh
f '2-oh
g '1-oh
h '2-oj
i 8d*o;
j '2+oh
k '3+oh
l 9c*o;
m '5+oh
n ab*o;
o '1-:00p
p 8e*o;
q '3-ot
r '2-ot
s '1-ot
t '1+os
u 9d*o;
v '2+ot
w '3+ot
x ac*o;
y b|o*
z '6+ot
{ '7+ot
| '8+ot
} '9+ot
~ 9e*o;
```
[Answer]
# [Dyalog APL](http://goo.gl/9KrKoM), ~~527~~ 522 [bytes](http://meta.codegolf.stackexchange.com/a/9429/43319)
(non-competing because APL cannot really be written using ASCII only)
Most are in the format `nn⊃⎕AV` or `nnn⊃⎕AV`, the exceptions being:
```
⊃'' ⍝ space: extract one char from an empty string
⎕THIS ⍝ hash: this namespace
⊃1↓⍕÷2 ⍝ period: the first char after stripping one char from 1÷2, i.e. 0.5
⊃⍬ ⍝ zero: extract one number from an empty numeric list
≢# ⍝ one: tally the root namespace
⍴⍬⍬ ⍝ two: count two empty lists
⎕WX ⍝ three: default "Window Expose" setting
×⍨2 ⍝ four: 2×2
6-1 ⍝ five: 6-1
!3 ⍝ six: 3!
6+1 ⍝ seven: 6+1
2*3 ⍝ eight: 2³
3*2 ⍝ nine: 3²
⊃⎕a ⍝ A: first character (Dyalog system names are case insensitive)
2⊃⎕A ⍝
⋮ ⍝ B-Y: n'th character
25⊃⎕A ⍝
⊃⌽⎕A ⍝ Z: last character
```
Here is the entire list:
```
⊃''
205⊃⎕AV
216⊃⎕AV
⎕THIS
62⊃⎕AV
13⊃⎕AV
219⊃⎕AV
14⊃⎕AV
186⊃⎕AV
249⊃⎕AV
181⊃⎕AV
170⊃⎕AV
195⊃⎕AV
169⊃⎕AV
⊃1↓⍕÷2
157⊃⎕AV
⊃⍬
≢#
⍴⍬ ⍬
⎕WX
×⍨2
6-1
!3
6+1
2*3
3*2
241⊃⎕AV
194⊃⎕AV
161⊃⎕AV
163⊃⎕AV
165⊃⎕AV
173⊃⎕AV
232⊃⎕AV
⊃⎕a
2⊃⎕A
3⊃⎕A
4⊃⎕A
5⊃⎕A
6⊃⎕A
7⊃⎕A
8⊃⎕A
9⊃⎕A
10⊃⎕A
11⊃⎕A
12⊃⎕A
13⊃⎕A
14⊃⎕A
15⊃⎕A
16⊃⎕A
17⊃⎕A
18⊃⎕A
19⊃⎕A
20⊃⎕A
21⊃⎕A
22⊃⎕A
23⊃⎕A
24⊃⎕A
25⊃⎕A
26⊃⎕A
156⊃⎕AV
159⊃⎕AV
250⊃⎕AV
236⊃⎕AV
17⊃⎕AV
238⊃⎕AV
18⊃⎕AV
19⊃⎕AV
20⊃⎕AV
21⊃⎕AV
22⊃⎕AV
23⊃⎕AV
24⊃⎕AV
25⊃⎕AV
26⊃⎕AV
27⊃⎕AV
28⊃⎕AV
29⊃⎕AV
30⊃⎕AV
31⊃⎕AV
32⊃⎕AV
33⊃⎕AV
34⊃⎕AV
35⊃⎕AV
36⊃⎕AV
37⊃⎕AV
38⊃⎕AV
39⊃⎕AV
40⊃⎕AV
41⊃⎕AV
42⊃⎕AV
43⊃⎕AV
124⊃⎕AV
193⊃⎕AV
126⊃⎕AV
176⊃⎕AV
```
[Answer]
# Ruby, 869 bytes
For the 63 characters `@` through `~`, we have a 10-byte solution:
```
$><<"\xxx" (3 digit octal code)
$><<92.chr (special case for \)
```
For most (21) characters from `space` through `?`, we have a 9-byte solution:
```
puts"\xx" (2 digit octal code)
```
There are eleven special cases left:
```
$><<34.chr (10 bytes for ")
p$. (3 bytes for 0)
p~-2 \
p~-3 \ (4 bytes for 1-8)
... /
p~-9 /
p 1+8 (5 bytes for 9)
```
In total, the score is 10×63 + 9×21 + 10 + 3 + 8×4 + 5 = 869.
[Answer]
# [WolframAlpha](https://www.wolframalpha.com/), 368 bytes
**General format:**
```
u+<character code in hexadecimal>
```
**Exceptions:**
```
Character Code
+ plus
0 1-1
1 0!
2 1+1
3 1+2
4 2+2
5 2+3
6 3!
7 3+4
8 4+4
9 4+5
u U+75
```
**Here is the full list:**
```
u+20
u+21
u+22
u+23
u+24
u+25
u+26
u+27
u+28
u+29
u+2A
plus
u+2C
u+2D
u+2E
u+2F
1-1
0!
1+1
1+2
2+2
2+3
3!
3+4
4+4
4+5
u+3A
u+3B
u+3C
u+3D
u+3E
u+3F
u+40
u+41
u+42
u+43
u+44
u+45
u+46
u+47
u+48
u+49
u+4A
u+4B
u+4C
u+4D
u+4E
u+4F
u+50
u+51
u+52
u+53
u+54
u+55
u+56
u+57
u+58
u+59
u+5A
u+5B
u+5C
u+5D
u+5E
u+5F
u+60
u+61
u+62
u+63
u+64
u+65
u+66
u+67
u+68
u+69
u+6A
u+6B
u+6C
u+6D
u+6E
u+6F
u+70
u+71
u+72
u+73
u+74
U+75
u+76
u+77
u+78
u+79
u+7A
u+7B
u+7C
u+7D
u+7E
```
[Answer]
# PHP (~~891~~ ~~680~~ 674 bytes, ~~2~~ 0 DNP)
**Edit:** saved 203 bytes thanks to jimmy23013 and implemented the 2 DNP thanks to Mego
---
This answer heavily abuses PHP's generous nature. Most of the cases take one of these forms (7 bytes each):
```
<?=Y^x;
<?=Z&e;
<?=V|Z;
```
PHP converts the letters on either side of the operator to strings, then performs the appropriate bitwise operation by converting each string to its ASCII character value, and finally converts the result *back* to a character.
In the first example above, `Y^x` becomes `89^78`. The result of this is `33`, which is then sent to STDOUT as the character `!`.
A script was written to bruteforce all possible combinations: the results can be found [here](https://3v4l.org/PqLjr).
---
**Exceptions:**
`;` is `<?=Z^a?>` (8 bytes)
`|` is `<?='9'^E;` (9 bytes)
`<` and `?` would normally be DNP due to the required start tag, but by using the `-r` flag, code can be executed without them:
`<` is `echo Z^f;` (9 bytes)
`?` is `echo Z^e;` (9 bytes)
`=` is `echo Z^g;` (9 bytes)
---
**Score:**
(7 \* 90) + 8 + 9 + 9 + 9 + 9 = 674 bytes
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), ~~546~~ 477 bytes
**Credits to Fatalize for the code for `@`.**
In the list below, the first character is the character to be printed (for easy reference).
```
@S
! @Ht
" @P:2m
# @P:3m
$ @P:4m
% @P:5m
& @P:6m
' @P:7m
( @P:8m
) @P:9m
* @P:10m
+ @P:11m
, @H:5m
- @P:13m
. @P:14m
/ @P:15m
0 1-
1 0+
2 1+
3 2+
4 3+
5 4+
6 5+
7 6+
8 7+
9 8+
: @P@4bhbbbh
; @P:27m
< @P:28m
= @P:29m
> @P:30m
? @P:31m
@ "?":"A"ybh
A @Zt@u
B @Ch@u
C @P:35m
D @P:36m
E @P:37m
F @P:38m
G @P:39m
H @P:40m
I @P:41m
J @P:42m
K @P:43m
L @P:44m
M @P:45m
N @P:46m
O @P:47m
P @A:15m@u
Q @P:49m
R @P:50m
S @P:51m
T @P:52m
U @Vt@u
V @P:54m
W @Qt@u
X @P:56m
Y @Wt@u
Z @At@u
[ @P:59m
\ @P:60m
] @P:61m
^ @P:62m
_ @P:63m
` @P:64m
a @Vh
b @Ch
c @Dbh
d @A:3m
e @Vbh
f @A:5m
g @A:6m
h @A:7m
i @A:8m
j @A:9m
k @C:7m
l @C:8m
m @D@2ht
n @A:13m
o @H:4m
p @A:15m
q @Z:9m
r @Z:8m
s @Z:7m
t @Z:6m
u @Vt
v @Z:4m
w @Qt
x @Z:2m
y @Wt
z @At
{ @P:91m
| @P:92m
} @Prbh
~ @Pt
```
They are all predicates, so `Z` needs to be the argument to receive the output: [Try it online!](http://brachylog.tryitonline.net/#code=&input=&args=Wg)
---
## Explanation
`@P` is this string:
```
!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~
```
which contains every printable ASCII.
[Answer]
# [><>](http://esolangs.org/wiki/Fish), 531 bytes
The programs take two main forms:
```
##*o;
"chr-1"1+o;
```
The first is for characters with character codes with two factors both less than 16, the other is for the other cases. Most numbers that I use the second form for have many equal length solutions, but I chose that one for readability.
Exceptions:
```
" b3*1+o; Would be "!"1+o; normally
0 11-n; n outputs as a number
1 22/n;
2-9 #1+n;
; ":"1+o* Ends in an error
```
Full list:
```
! b3*o;
" b3*1+o;
# 57*o;
$ 66*o;
% "$"1+o;
& "%"1+o;
' d3*o;
( a4*o;
) "("1+o;
* ")"1+o;
+ ","1-o;
, b4*o;
- 95*o;
. "-"1+o;
/ "."1+o;
0 11-n;
1 22/n;
2 11+n;
3 21+n;
4 31+n;
5 41+n;
6 51+n;
7 61+n;
8 71+n;
9 81+n;
: "9"1+o;
; ":"1+o*
< a6*o;
= "<"1+o;
> "="1+o;
? 97*o;
@ 88*o;
A d5*o;
B b6*o;
C "B"1+o;
D "C"1+o;
E "D"1+o;
F a7*o;
G "F"1+o;
H 98*o;
I "H"1+o;
J "D"1+o;
K e5*o;
L "K"1+o;
M b7*o;
N d6*o;
O "D"1+o;
P a8*o;
Q 99*o;
R "Q"1+o;
S "R"1+o;
T c7*o;
U "T"1+o;
V "U"1+o;
W "V"1+o;
X b8*o;
Y "X"1+o;
Z a9*o;
[ c7*o;
\ "["1+o;
] "\"1+o;
^ "]"1+o;
_ "^"1+o;
` c8*o;
a "`"1+o;
b e7*o;
c b9*o;
d aa*o;
e "d"1+o;
f "e"1+o;
g "g"1+o;
h d8*o;
i e7*o;
j "i"1+o;
k "j"1+o;
l c9*o;
m "l"1+o;
n ba*o;
o DNP
p e8*o;
q "p"1+o;
r "q"1+o;
s "r"1+o;
t "s"1+o;
u c9*o;
v "u"1+o;
w "v"1+o;
x ca*o;
y bb*o;
z "y"1+o;
~ e9*o;
```
[Answer]
## [Hexagony](https://github.com/m-ender/hexagony), ~~376~~ 373 bytes, 1 DNP
*Thanks to FryAmTheEggman for saving 3 bytes.*
Almost all programs have the same form:
```
P0;@
! P1;@
" P2;@
...
| Y2;@
} Y3;@
~ Y4;@
```
There are a few exceptions though:
* It's impossible to print `;` without using `;`, hence 1 DNP.
* To print `@`, we cannot use `@` to terminate the program. Instead we use either `S2;:` or `S3;%`. This terminates with a division-by-zero error, but that error is not visible on STDOUT. So this is still four bytes.
* There is one clash for `U` which would require `U3;@`. There are several ways to fix this, including switching to lower-case, i.e. `n9;@`, or using increment or decrement, i.e. `T);@` or `V(;@`. In any case it's still four bytes.
* Memory edges are initialised to `0`, and `!` prints an integer value, so we can get `0` and `1` with `!@` and `)!@`, respectively, saving 3 bytes.
As for how the `<letter><digit>;@` programs work: the hexagonal layout of a program of the form `1234` is always
```
1 2
3 4 .
. .
```
Since none of the programs contain any commands that redirect control flow, these are simply linear programs that are executed in order.
In every case, the letter at the beginning of the code sets the current memory edge to its character code. E.g. in the program `P1;@`, the `P` sets the value `80`. Then the digit multiplies this value by 10 and adds itself (i.e. the digit is appended to the current value). That gives `801` in the example above. Finally, `;` prints this value by taking it modulo 256 and using it as a byte value. In this case `801 % 256 = 33` and a `!` is printed.
[Answer]
# Marbelous, 220 bytes
For a character that is not a digit, it is just the two uppercase hex digits of the character code. For example, the following program outputs `A`:
```
41
```
For a digit that is not `3`, replace `2F` in the following code by the uppercase hex digits of the character code - 1:
```
2F
++
```
For `3`:
```
66
>>
```
Total score: 2\*85 + 5\*10 = 220.
[Interpreter.](https://codegolf.stackexchange.com/a/40808/25180)
My first try was Bubblegum and it didn't work for characters before `?`...
[Answer]
# [Whitespace](http://esolangs.org/wiki/Whitespace), 1643 bytes, 1 DNP
17 bytes for the characters [33-63] and 18 bytes for characters [64-126]
In Whitespace this is straight forward, because printable characters (except space) don't have any meaning anyway:
```
[SPACE][SPACE][SPACE][TAB][SPACE][SPACE][SPACE][SPACE][TAB][LF]
[TAB][LF]
[SPACE][SPACE][LF]
[LF]
[LF]
```
The program above prints a '!' (100001b).
Change `[TAB][SPACE][SPACE][SPACE][SPACE][TAB]` in the first line to whichever character you like.
It's not possible to print a space without using a space, because printing anything always starts with `[TAB][LF][SPACE]`
[Answer]
## [Retina](https://github.com/m-ender/retina/), 712 bytes, 2 DNPs
This was a collaborative effort with FryAmTheEggman.
There are several classes of solutions. For most characters from space to `^`, we use a program of the following form:
```
_
T`w`p
```
The character on the second line iterates through the ranges `_0-9A-Za-z` while the rest remains unchanged. This turns the empty input into that character and then replaces it with the printable ASCII character (represented by `p`) at the corresponding position. Each of these programs is 8 bytes long.
Within this range, there are only a few exceptions. Most importantly the digits can be shortened:
* 0: `x` (counts the number of `x`s in the empty input)
* 1: (weehoo, empty program; counts the number of empty matches in the empty input)
* 2: now we turn the input into a single character, before counting empty strings:
```
1
```
* 3: same thing but we turn the input into two characters:
```
11
```
* 4: you get the idea...
```
111
```
* 5 - 9: plot twist... we use character repetition to avoid the second line getting any longer:
```
4$*
```
...
```
8$*
```
The other exception is that `T` is a DNP: we don't think it's possible to generate a non-digit character without it appearing in the source code if transliteration stages can't be used.
On to the remaining characters. To print `_` we use a similar program as the general solution above:
```
0
T`0`w
```
Making use of the fact that `w` starts with `_`.
Next, ``` is the second DNP, because transliteration stages require those as well.
Then most of the lower-case letters are printed with something like this (which prints `a`):
```
_
T`w`l
```
Again, the character on the second line increments through `_0-9A-O`. Here, we just need to watch out for `l` and `w`, which we can print with the following programs, respectively:
```
P
T`p`w
```
```
6
T`p`l
```
Finally, only `{|}~` are left, which require 9 bytes each. Here, we use the transliteration stage to increment the character that precedes them. E.g. `~` can be printed with:
```
}
T`_p`p
```
[Answer]
## Pyke, ~~364~~ ~~362~~ 355 bytes
```
2*1 + 3*2 + 14*3 + 2*4 + 5 + 73*4
```
All in the form `w<chr(charcode+32)>.C` (4 bytes) except for:
* -> `d` 1 byte
* `0` -> `Z` 1 byte
* `1` -> `~W` 2 bytes
* `a` -> `Gh` 2 bytes
* `z` -> `Ge` 2 bytes
* First 10 lowercase alphabet letters (except `a`) in form `G<number>@` (3 bytes)
* `k` -> `GT@` 3 bytes
* `>` -> `~Bh` 3 bytes
* `]` -> `~Be` 3 bytes
* `Z` -> `~le` 3 bytes
* `9` -> `~ue` 3 bytes
* `w` -> `G22@` 4 bytes
* `.` -> `~B4@` 4 bytes
* `C` -> `~K38@` 5 bytes
[Online Pyke interpreter](http://pyke.catbus.co.uk/)
[Answer]
## JavaScript (ES6), ~~1083~~ 1068 bytes
General form:
```
alert`\xhex`
```
Exceptions:
```
0 alert(9-9)
...
8 alert(9-1)
9 alert(8+1)
\ alert(atob`XA`)
` alert('\x60')
a \u0061lert`\x61`
e al\u0065rt`\x65`
l a\u006cert`\x6c`
r ale\u0072t`\x72`
t aler\u0074`\x74`
x alert`\u0078`
```
Edit: Saved 15 bytes thanks to @GOTO0.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/), 417 bytes
```
! 62D>B
" 63D>B
# 64D>B
$ 65D>B
% 66D>B
& 67D>B
' 68D>B
( 69D>B
) 70D>B
* 71D>B
+ 72D>B
, 73D>B
- 74D>B
. 75D>B
/ 76D>B
0 1<
1 X
2 Y
3 Z
4 3>
5 4>
6 5>
7 6>
8 7>
9 8>
: 77D>B
; 78D>B
< 79D>B
= 80D>B
> 81D1+B
? 82D>B
@ 83D>B
A Th
B T>h
C T>>h
D T3+h
E T4+h
F T5+h
G 16D>B
H 17D>B
I 18D>B
J 19D>B
K 20D>B
L 21D>B
M 22D>B
N 23D>B
O 24D>B
P 25D>B
Q 26D>B
R 27D>B
S 28D>B
T 29D>B
U 30D>B
V 31D>B
W 33D>B
X 33D>B
Y A`\u
Z A`u
[ 84D>B
\ 85D>B
] 86D>B
^ 87D>B
_ 88D>B
` 89D>B
a A`r
b A`r\
c 38D>B
d 39D>B
e 40D>B
f 41D>B
g 42D>B
h 43D>B
i 44D>B
j 45D>B
k 46D>B
l 47D>B
m 48D>B
n 49D>B
o 50D>B
p 51D>B
q 52D>B
r 53D>B
s 54D>B
t 55D>B
u 56D>B
v 57D>B
w 58D>B
x A`\\
y A`\
z A`
{ 90D>B
| 91D>B
} 92D>B
~ 93D>B
```
**Explanation**
Most are 5 bytes long of the form: `convert nr to base nr+1`.
`>` needs an extra byte since we can't use increment for that.
`a,b,x,y,z,Y,Z` are extracted from `A` which contains the alphabet in lower case.
`A,B,C,D,E,F` are numbers converted to hex.
`0-9` are simple increment/decrements as well as predefined variables.
[Answer]
# Perl 6: 921 bytes
Translation of the Python solution.
Each program has the form `say "\x<hex escape code>"`, except:
* `s` → `put "\x73"`
* `a` → `put "\x61"`
* `y` → `put "\x79"`
* → `"\x20".say`
* `"` → `say chr 34`
* `\` → `say chr 92`
* `x` → `say chr 120`
* `0` → `say 1-1`
* `1` → `say 3-2`
* `2` to `9` → `say <n minus one>+1`
For reference and ease of testing, here's the full list of programs, newline-separated.
```
"\x20".say
say "\x21"
say chr 34
say "\x23"
say "\x24"
say "\x25"
say "\x26"
say "\x27"
say "\x28"
say "\x29"
say "\x2A"
say "\x2B"
say "\x2C"
say "\x2D"
say "\x2E"
say "\x2F"
say 1-1
say 3-2
say 1+1
say 2+1
say 3+1
say 4+1
say 5+1
say 6+1
say 7+1
say 8+1
say "\x3A"
say "\x3B"
say "\x3C"
say "\x3D"
say "\x3E"
say "\x3F"
say "\x40"
say "\x41"
say "\x42"
say "\x43"
say "\x44"
say "\x45"
say "\x46"
say "\x47"
say "\x48"
say "\x49"
say "\x4A"
say "\x4B"
say "\x4C"
say "\x4D"
say "\x4E"
say "\x4F"
say "\x50"
say "\x51"
say "\x52"
say "\x53"
say "\x54"
say "\x55"
say "\x56"
say "\x57"
say "\x58"
say "\x59"
say "\x5A"
say "\x5B"
say chr 92
say "\x5D"
say "\x5E"
say "\x5F"
say "\x60"
put "\x61"
say "\x62"
say "\x63"
say "\x64"
say "\x65"
say "\x66"
say "\x67"
say "\x68"
say "\x69"
say "\x6A"
say "\x6B"
say "\x6C"
say "\x6D"
say "\x6E"
say "\x6F"
say "\x70"
say "\x71"
say "\x72"
put "\x73"
say "\x74"
say "\x75"
say "\x76"
say "\x77"
say chr 120
put "\x79"
say "\x7A"
say "\x7B"
say "\x7C"
say "\x7D"
say "\x7E"
```
Here's the code I used to test the above listing, and count the score:
```
#!/usr/bin/env perl6
my $file = 'print_ascii_characters.p6';
my @expected = ' ' .. '~';
my @code = $file.IO.lines;
my $code = @code.join: ';';
my @got = (run 'perl6', '-e', $code, :out).out.lines.map: |*.comb;
given +@expected, +@got, +@code -> ($e, $g, $c) {
say "WRONG COUNT: Expected $e / output $g / source $c" and exit if not $e == $g == $c;
}
for @expected Z @got -> ($e, $g) {
say "WRONG OUTPUT: Expected {$e.perl}, got {$g.perl}" and exit if $e ne $g;
}
for @expected Z @code -> ($char, $code) {
say "COLLISION: {$char.perl} contained in {$code.perl}" if $code.match($char);
}
say "SCORE: ", @code.map(*.chars).sum;
```
[Answer]
# Haskell, ~~1874 1864 1856 1855 1795 1791~~ 1589 bytes, 7 DNPs
Most programs are `main=putChar '\xx'` or `main=putChar '\xxx'` where `xx`/`xxx` is the ascii code of the char to be printed.
This works for all but 14 chars:
```
!"#$%& ()*+,-./0123456789:;< >?@AB DEFGHIJKLMNOPQRSTUVWXYZ[ ]^_` bcdefg jkl o q s vwxyz{|}~
' = C \ a hi mn p r tu
```
However, for the digits ~~1 7~~ 4 bytes can be saved (thanks to Christian Sievers!):
```
0 main=print$1-1
1 main=print$3-2
2 main=print$1+1
3 main=print$1+2
...
```
The 52 programs up to `c` (code 99) take 18 bytes, the remaining 19 take 19 bytes each.
*Partial score:* `10*14 + 52*18 + 19*19 = 1437`
For 7 of the remaining chars, the following programs work:
```
main=putChar$'\32'
' main=putStr$pred<$>"("
C main=putStr['\67']
\ main=putChar$pred ']'
h main=putStr['\104']
p main=interact(\_->['\112'])
u main=interact(\_->['\117'])
```
*Partial score:* `18 + 22 + 18 + 21 + 19 + 27 + 27 = 152`
This leaves 7 DNPs: `=aimnrt`
Each Haskell program needs to define a main (`main=`), so that's 5 DNPs. To print to stdOut, `putChar`, `putStr` or `interact` can be used, yielding `t` and `r` as further DNPs. (There is also `print`, however `print 'a'` prints `'a'` and not `a` - and also contains `t` and `r` anyway.)
Haskell also has a `chr` function which returns the corresponding char given a number, however in order to use it `import Data.Char` is needed.
**Total score:** `1437 + 152 = 1589`, 7 DNPs
[Answer]
# Malbolge, 618 bytes.
This answer is pretty much obvious, and it's trivial to outgolf, but it may be worth to give a shot.
Jokes aside, I highly doubt you can golf it, just the `(` and '<' ones.
```
:7 - (&<`M^\
!:7 - (C<;_"K
":7 - (&&$_L]
#:8 - (&<;_L\J
$:7 - D'<A:^K
%:8 - (=&;_L]J
&:7 - D'%`M#o
':6 - (&%`M^
(:16 - DCBA@?>~<;{98xUB
):8 - (&<%:^KJ
*:7 - (&<`M]>
+:7 - (&&;_L]
,:7 - (=&;_L>
-:6 - D'%%_L
.:7 - ('%`M9o
/:6 - (=B;_L
0:6 - ('%$_L
1:7 - (&a%M"o
2:8 - (=&;:^"J
3:7 - ('<;_L"
4:7 - ('%;_L]
5:6 - D'%`#L
6:6 - (=<`:L
7:7 - (&<;:^K
8:8 - ('&;$9]J
9:7 - ('<;:^K
::6 - (&%`M?
;:8 - (C<A:^"J
<:10 - ('&%#^"J~Z
=:7 - DC&$_#K
>:6 - (&%`#L
?:6 - (=<`@L
@:7 - (&B%:^K
A:7 - (&<`M^8
B:5 - (&a%M
C:6 - D'%`M#
D:6 - (&%`M"
E:7 - ('&$_L\
F:7 - (&%$:^K
G:6 - (&%;_L
H:7 - ('&;:^K
I:6 - (C<;_L
J:6 - D'<;_L
K:7 - (&a%M^!
L:7 - (=<;_#K
M:7 - ('%$#^K
N:7 - (&&;_#K
O:7 - DC&$:^K
P:5 - (&a;M
Q:8 - ('%A$9]J
R:6 - (&<`M?
S:7 - (&a%M]\
T:5 - (=a;M
U:6 - D'<%_L
V:5 - (&aAM
W:5 - (=aNM
X:6 - (=aN_#
Y:7 - (&&$:^K
Z:7 - DC&$_"K
[:7 - (&%$_"K
\:1 - Q
]:5 - ('<`M
^:6 - ('B;_L
_:6 - (&<`M#
`:7 - DC&;_L"
a:6 - ('%`M#
b:7 - ('%;_9K
c:5 - (&aN_
d:6 - (&<`:L
e:7 - (&%;_"K
f:6 - (=<;_L
g:7 - ('%;_#K
h:7 - (&a%M^"
i:7 - ('%`M^"
j:8 - (=B;:^"J
k:5 - ('%`M
l:5 - (&&`M
m:6 - (&%`:L
n:7 - D'%;_Lo
o:6 - (=aN_9
p:6 - (CB;_L
q:7 - D'%A:^K
r:4 - (=aN
s:5 - (C<`M
t:7 - (&%;_L]
u:5 - (&aN:
v:6 - D'%`:L
w:7 - (&B;:^K
x:5 - (=a$M
y:5 - D'<`M
z:7 - (&%%:^K
{:5 - (=aN_
|:5 - (&a$M
}:5 - (&aN#
~:7 - (&%$_L"
```
[Answer]
# BBC Basic, ~~422~~ 413 bytes
Download interpreter free at <http://www.bbcbasic.co.uk/bbcwin/bbcwin.html>
9 bytes saved thanks to Leaky Nun.
**General form**
```
V.<character code>
```
**32..99** excluding 12 special cases: 56x4= **224 bytes**
**100..126** : 27x5= **135 bytes**
**12 special cases : 54 bytes**
Most numbers follow the general form, but I included them all here to show where the problem is.
First character is the character to be printed.
```
. VDU46 :REM Full form of the command used in general form: send character 46 to VDU)
V P.CHR$86 :REM short for PRINT CHR$(86)
0 V.48
1 V.49
2 V.50
3 V.51
4 V.52
5 P.1+4
6 V.54
7 V.55
8 V.56
9 V.57
```
[Answer]
# [Minkolang 0.15](https://github.com/elendiastarman/Minkolang), 604 bytes
For most characters, `"<char-1>"1+O.` would be a valid program, perhaps one of the shortest. However, due to the fact that characters are stored as code points on the stack means that many of them can be produced by multiplication and addition, in five bytes or fewer. Also, note that `l, $1, $2, $3, $4, $5, $6, $l` are `10, 11, 12, 13, 14, 15, 16, 100` respectively.
Format: `<character>: <program>`
```
: 48*O.
!: $13*O.
": 66*2-O.
#: 57*O.
$: 66*O.
%: 66*1+O.
&: 4l*2-O.
': 3$3*O.
(: 4l*O.
): 4l*1+O.
*: ")"1+O.
+: "*"1+O.
,: $14*O.
-: 59*O.
.: "-"1+d$10pO-
/: "."1+O.
0: 68*O.
1: 77*O.
2: 5l*O.
3: 5l*1+O.
4: lZIO.
5: lZdIO.
6: 239**O.
7: 5$1*O.
8: 4$4*O.
9: 6l*3-O.
:: 6l*2-O.
;: 6l*1-O.
<: 6l*O.
=: 6l*1+O.
>: 6l*2+O.
?: 79*O.
@: 88*O.
A: 5$3*O.
B: 6$1*O.
C: 7l*3-O.
D: 7l*2-O.
E: 7l*1-O.
F: 7l*O.
G: 7l*1+O.
H: 89*O.
I: 89*1+O.
J: 89*2+O.
K: 355**O.
L: 89*4+O.
M: 7$1*O.
N: 6$3*O.
O: "N"1+d90pN.
P: 8l*O.
Q: 99*O.
R: 8l*2+O.
S: 8l*3+O.
T: 347**O.
U: 8l*5+O.
V: 8l*6+O.
W: 8l*7+O.
X: 8$1*O.
Y: 8l*9+O.
Z: 9l*O.
[: $l9-O.
\: $l8-O.
]: $l7-O.
^: $l6-O.
_: $l5-O.
`: 8$2*O.
a: $l3-O.
b: $l2-O.
c: 9$1*O.
d: $lO.
e: $l1+O.
f: $l2+O.
g: $l3+O.
h: $l4+O.
i: $l5+O.
j: $l6+O.
k: $l7+O.
l: $l8+O.
m: $l9+O.
n: l$1*O.
o: $l$1+O.
p: $l$2+O.
q: $l$3+O.
r: $l$4+O.
s: $l$5+O.
t: $l$6+O.
u: "t"1+O.
v: "u"1+O.
w: 7dl+*O.
x: 358**O.
y: $1d*O.
z: 53;3-O.
{: 53;2-O.
|: 53;1-O.
}: 53;O.
~: 53;1+O.
```
### Special mentions:
```
.: "-"1+d$10pO-
```
[(Try it.)](http://play.starmaninnovations.com/minkolang/?code=%22-%221%2Bd%2410pO-) Minkolang has the ability to modify the characters in the code box, so what this program does is that it replaces that `-` at the end with `.`, which is necessary for stopping the program. [`"N"1+d90pN.`](http://play.starmaninnovations.com/minkolang/?code=%22N%221%2Bd90pN%2E) for `O` works the same way.
```
4: lZIO.
```
[(Try it.)](http://play.starmaninnovations.com/minkolang/?code=lZIO%2E) `lZ` pushes the uppercase and lowercase alphabets to the stack, and `I` pushes the length of the stack, which is 52, precisely the code point of "4". The best part is that I was initially considering the solution of `4$3*O.`, which multiplies 4 and 13 to get 52, but couldn't because it had a 4 in it, so I ended up finding a golfier solution anyway!
```
y: $1d*O.
```
[(Try it.)](http://play.starmaninnovations.com/minkolang/?code=%241d*O%2E) `d` duplicates the top of stack, so what this piece of code does is that it pushes `11`, duplicates it, and then multiplies. An alternate way to write this would have been `$12;O.`, which has the same byte count.
```
}: 53;O.
```
[(Try it.)](http://play.starmaninnovations.com/minkolang/?code=53%3BO%2E) `;` is exponentiation, so this does 5^3 to get 125.
[Answer]
# Groovy, 1019 bytes
I had a different Groovy solution written up (see below), but after I submitted it I did a bit more digging into character escapes, hoping to find a way of shortening the program more, and discovered that Groovy has an octal character escape that I did not know of. This significantly simplifies the code, to the point that it unfortunately removes the need for almost all of the quirky workarounds I had come up with.
It also looks almost identical to [Copper's Python 2 solution](https://codegolf.stackexchange.com/a/90530/58776), to the point where it basically looks like I plagiarized their work. Ugh.
Each program has the form `print'\<octal value>'`, except:
* `p`, `r`, `i`, `n`, `t` → `'print''\<octal value>'` (but with the matching letter of "print" also replaced with the octal value)
* `0` - `9` → `print~-<next int>`
Here is the full list of programs by character.
```
print'\40'
! print'\41'
" print'\42'
# print'\43'
$ print'\44'
% print'\45'
& print'\46'
' print'\47'
( print'\50'
) print'\51'
* print'\52'
+ print'\53'
, print'\54'
- print'\55'
. print'\56'
/ print'\57'
0 print~-1
1 print~-2
2 print~-3
3 print~-4
4 print~-5
5 print~-6
6 print~-7
7 print~-8
8 print~-9
9 print~-10
: print'\72'
; print'\73'
< print'\74'
= print'\75'
> print'\76'
? print'\77'
@ print'\100'
A print'\101'
B print'\102'
C print'\103'
D print'\104'
E print'\105'
F print'\106'
G print'\107'
H print'\110'
I print'\111'
J print'\112'
K print'\113'
L print'\114'
M print'\115'
N print'\116'
O print'\117'
P print'\120'
Q print'\121'
R print'\122'
S print'\123'
T print'\124'
U print'\125'
V print'\126'
W print'\127'
X print'\130'
Y print'\131'
Z print'\132'
[ print'\133'
\ print'\134'
] print'\135'
^ print'\136'
_ print'\137'
` print'\140'
a print'\141'
b print'\142'
c print'\143'
d print'\144'
e print'\145'
f print'\146'
g print'\147'
h print'\150'
i 'pr\151nt''\151'
j print'\152'
k print'\153'
l print'\154'
m print'\155'
n 'pri\156t''\156'
o print'\157'
p '\160rint''\160'
q print'\161'
r 'p\162int''\162'
s print'\163'
t 'prin\164''\164'
u print'\165'
v print'\166'
w print'\167'
x print'\170'
y print'\171'
z print'\172'
{ print'\173'
| print'\174'
} print'\175'
~ print'\176'
```
# Groovy, 1130 bytes
My previous program, before I discovered that octal escapes exist. Much more interesting, IMO.
Each program has the form `print(--'<next char>')`, except:
* `-`, `[`, `~` → `print(++'<previous char>')`
* `&` → `print(--"'")`
* `p`, `r`, `i`, `n` → `System.out<<--'<next char>'`
* `t` → `'prin\u0074'(--'u')`
* `(` → `print'\u0028'`
* `)` → `print'\u0029'`
* `0` - `9` → `print~-<next int>`
Here is the full list of programs for each character:
```
print(--'!')
! print(--'"')
" print(--'#')
# print(--'$')
$ print(--'%')
% print(--'&')
& print(--"'")
' print(--'(')
( print'\u0028'
) print'\u0029'
* print(--'+')
+ print(--',')
, print(--'-')
- print(++',')
. print(--'/')
/ print(--'0')
0 print~-1
1 print~-2
2 print~-3
3 print~-4
4 print~-5
5 print~-6
6 print~-7
7 print~-8
8 print~-9
9 print~-10
: print(--';')
; print(--'<')
< print(--'=')
= print(--'>')
> print(--'?')
? print(--'@')
@ print(--'A')
A print(--'B')
B print(--'C')
C print(--'D')
D print(--'E')
E print(--'F')
F print(--'G')
G print(--'H')
H print(--'I')
I print(--'J')
J print(--'K')
K print(--'L')
L print(--'M')
M print(--'N')
N print(--'O')
O print(--'P')
P print(--'Q')
Q print(--'R')
R print(--'S')
S print(--'T')
T print(--'U')
U print(--'V')
V print(--'W')
W print(--'X')
X print(--'Y')
Y print(--'Z')
Z print(--'[')
[ print(++'Z')
\ print(--']')
] print(--'^')
^ print(--'_')
_ print(--'`')
` print(--'a')
a print(--'b')
b print(--'c')
c print(--'d')
d print(--'e')
e print(--'f')
f print(--'g')
g print(--'h')
h print(--'i')
i System.out<<--'j'
j print(--'k')
k print(--'l')
l print(--'m')
m print(--'n')
n System.out<<--'o'
o print(--'p')
p System.out<<--'q'
q print(--'r')
r System.out<<--'s'
s print(--'t')
t 'prin\u0074'(--'u')
u print(--'v')
v print(--'w')
w print(--'x')
x print(--'y')
y print(--'z')
z print(--'{')
{ print(--'|')
| print(--'}')
} print(--'~')
~ print(++'}')
```
[Answer]
# Fourier, 306 bytes, 1 DNP
Pretty much all of the programs follow the pattern `na` where n is the character code of each of the characters. For example:
```
! 33a
" 34a
# 35a
$ 36a
% 37a
& 38a
' 39a
```
[**Try it online!**](http://fourier.tryitonline.net/#code=MzNhIDM0YSAzNWEgMzZhIDM3YSAzOGEgMzlh&input=)
So I'll just list the exceptions:
## 0 (Zero)
Since the accumulator is preset to zero, we can display this using a single character:
```
o
```
[**Try it online!**](http://fourier.tryitonline.net/#code=bw&input=)
## 1
Similar to zero, this increments the accumulator to get 1.
```
^o
```
[**Try it online!**](http://fourier.tryitonline.net/#code=Xm8&input=)
## 5
The ASCII code for 5 is 53, so I had to work around this:
```
6vo
```
[**Try it online!**](http://fourier.tryitonline.net/#code=NnZv&input=)
## a
Due to `a` being the character output function, there is no other way to produce the character a, so this my only **DID NOT PROGRAM**.
## See all of the programs [here](http://pastebin.com/raw/Cgg0KyTj)
[Answer]
## Matlab, ~~1238~~ 1224 bytes, 2 DNP
The main pattern is:
```
disp([<char code> ''])
```
For digits it's a little shorter:
```
disp(<sum or difference of two other digits>)
```
For characters `[]'` it's:
```
" " -- disp([0,''])
"[" -- disp(char(91))
"]" -- disp(char(93))
"'" -- disp(char(39))
```
Characters `ds` from `disp` are displayed using `fprintf` (*thanks [@Stewie Griffin](https://codegolf.stackexchange.com/users/31516/stewie-griffin)*); `ip` however belong also there, so I'm shifting the string and using `eval`:
```
d -- fprintf([100 ''])
i -- eval(['ejtq)(j(*'-1 ''])
s -- fprintf([115 ''])
p -- eval(['ejtq)(q(*'-1 ''])
```
Both characters `()` are however necessary for `disp` or `eval`, so they are DNP.
---
For reference the whole list:
```
char char code code length
32 disp([0 '']) 12
! 33 disp([33 '']) 13
" 34 disp([34 '']) 13
# 35 disp([35 '']) 13
$ 36 disp([36 '']) 13
% 37 disp([37 '']) 13
& 38 disp([38 '']) 13
' 39 disp(char(39)) 14
( 40 DNP
) 41 DNP
* 42 disp([42 '']) 13
+ 43 disp([43 '']) 13
, 44 disp([44 '']) 13
- 45 disp([45 '']) 13
. 46 disp([46 '']) 13
/ 47 disp([47 '']) 13
0 48 disp(1-1) 9
1 49 disp(3-2) 9
2 50 disp(5-3) 9
3 51 disp(7-4) 9
4 52 disp(9-5) 9
5 53 disp(2+3) 9
6 54 disp(3+3) 9
7 55 disp(4+3) 9
8 56 disp(5+3) 9
9 57 disp(6+3) 9
: 58 disp([58 '']) 13
; 59 disp([59 '']) 13
< 60 disp([60 '']) 13
= 61 disp([61 '']) 13
> 62 disp([62 '']) 13
? 63 disp([63 '']) 13
@ 64 disp([64 '']) 13
A 65 disp([65 '']) 13
B 66 disp([66 '']) 13
C 67 disp([67 '']) 13
D 68 disp([68 '']) 13
E 69 disp([69 '']) 13
F 70 disp([70 '']) 13
G 71 disp([71 '']) 13
H 72 disp([72 '']) 13
I 73 disp([73 '']) 13
J 74 disp([74 '']) 13
K 75 disp([75 '']) 13
L 76 disp([76 '']) 13
M 77 disp([77 '']) 13
N 78 disp([78 '']) 13
O 79 disp([79 '']) 13
P 80 disp([80 '']) 13
Q 81 disp([81 '']) 13
R 82 disp([82 '']) 13
S 83 disp([83 '']) 13
T 84 disp([84 '']) 13
U 85 disp([85 '']) 13
V 86 disp([86 '']) 13
W 87 disp([87 '']) 13
X 88 disp([88 '']) 13
Y 89 disp([89 '']) 13
Z 90 disp([90 '']) 13
[ 91 disp(char(91)) 14
\ 92 disp([92 '']) 13
] 93 disp(char(93)) 14
^ 94 disp([94 '']) 13
_ 95 disp([95 '']) 13
` 96 disp([96 '']) 13
a 97 disp([97 '']) 13
b 98 disp([98 '']) 13
c 99 disp([99 '']) 13
d 100 fprintf([100 '']) 17
e 101 disp([101 '']) 14
f 102 disp([102 '']) 14
g 103 disp([103 '']) 14
h 104 disp([104 '']) 14
i 105 eval(['ejtq)(j(*'-1 '']) 24
j 106 disp([106 '']) 14
k 107 disp([107 '']) 14
l 108 disp([108 '']) 14
m 109 disp([109 '']) 14
n 110 disp([110 '']) 14
o 111 disp([111 '']) 14
p 112 eval(['ejtq)(q(*'-1 '']) 24
q 113 disp([113 '']) 14
r 114 disp([114 '']) 14
s 115 fprintf([115,'']) 17
t 116 disp([116 '']) 14
u 117 disp([117 '']) 14
v 118 disp([118 '']) 14
w 119 disp([119 '']) 14
x 120 disp([120 '']) 14
y 121 disp([121 '']) 14
z 122 disp([122 '']) 14
{ 123 disp([123 '']) 14
| 124 disp([124 '']) 14
} 125 disp([125 '']) 14
~ 126 disp([126 '']) 14
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly "Jelly, by Dennis Mitchell") (non-competitive), 406 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
32Ọ
33Ọ
34Ọ
35Ọ
36Ọ
37Ọ
38Ọ
39Ọ
40Ọ
41Ọ
42Ọ
43Ọ
44Ọ
45Ọ
46Ọ
47Ọ
48Ọ
49Ọ
50Ọ
51Ọ
52Ọ
49+4Ọ
54Ọ
55Ọ
56Ọ
57Ọ
58Ọ
59Ọ
60Ọ
61Ọ
62Ọ
63Ọ
64Ọ
65Ọ
66Ọ
67Ọ
68Ọ
69Ọ
70Ọ
71Ọ
72Ọ
73Ọ
74Ọ
75Ọ
76Ọ
77Ọ
78Ọ
79Ọ
80Ọ
81Ọ
82Ọ
83Ọ
84Ọ
85Ọ
86Ọ
87Ọ
88Ọ
89Ọ
90Ọ
91Ọ
92Ọ
93Ọ
94Ọ
95Ọ
96Ọ
97Ọ
98Ọ
99Ọ
³Ọ
101Ọ
102Ọ
103Ọ
104Ọ
105Ọ
106Ọ
107Ọ
108Ọ
109Ọ
110Ọ
111Ọ
112Ọ
113Ọ
114Ọ
115Ọ
116Ọ
117Ọ
118Ọ
119Ọ
120Ọ
121Ọ
122Ọ
123Ọ
124Ọ
125Ọ
126Ọ
```
This prints all characters from 32 - 126. The byte count is calculated with <https://mothereff.in/byte-counter>.
[Try it online!](http://jelly.tryitonline.net/#code=MzLhu4w&input=&args= "Jelly ASCII print")
[Answer]
# Befunge-93, 530 bytes
The easiest way to output a character, without actually using that character, is to calculate the ASCII value and use the `,` (character output) command to render it. For example, [`49*,@`](http://befunge.tryitonline.net/#code=NDkqLEA) outputs the dollar character (ASCII 36, 4 \* 9). This is rarely the most optimal, though, since most values take more than 3 bytes to calculate.
Another way to generate a number in 3 bytes is to take advantage of the fact that the `g` (get) command in the first cell of the playfield will generate the ASCII value of *g* (an empty stack is assumed to be populated with zeros, so it's reading the playfield value at 0,0). Thus [`g1+,@`](http://befunge.tryitonline.net/#code=ZzErLEA) gets you *h*, and [`g1-,@`](http://befunge.tryitonline.net/#code=ZzEtLEA) gets you *f*. This obviously works for a range of offsets, and operations other than `+` and `-` are also possible. So for example [`g3/,@`](http://befunge.tryitonline.net/#code=ZzMvLEA) gets you a double quote.
A variation of this, is to precede the `g` with another command that leaves all zeros on the stack. So you're still reading a value from the playfield at 0,0, but the character being read is now different. This costs one more byte, but gets you access to many more values. For example, [`0g1-,@`](http://befunge.tryitonline.net/#code=MGcxLSxA) gets you a forward slash and [`:g1+,@`](http://befunge.tryitonline.net/#code=OmcxKyxA) gets you a semicolon. Other viable prefixes include `*`, `+`, `-`, `>`, `\` and `_`. And again note that other operations are possible: [`>g2*,@`](http://befunge.tryitonline.net/#code=PmcyKixA) get you a vertical bar.
A further variation is to precede the `g` with a `1`, so you're now no longer reading from 0,0, but from the blank cell at 0,1. In Befunge, empty cells are initialized with spaces by default, so [`1g,@`](http://befunge.tryitonline.net/#code=MWcsQA) gets you a space, and [`1g1+,@`](http://befunge.tryitonline.net/#code=MWcxKyxA) gets you an exclamation mark.
For the digit characters, there's more dubious trick we can use. Instead of trying to output them as characters, we output them as numbers (a small number is easier to generate than its ASCII equivalent). So for example, [`11+.@`](http://befunge.tryitonline.net/#code=MTErLkA) gives you *2*, and in particular note the special cases: [`.@`](http://befunge.tryitonline.net/#code=LkA) for *0*, and [`!.@`](http://befunge.tryitonline.net/#code=IS5A) for *1*. The dubious part of this is that a numeric output in Befunge includes a space after the number, so it's not a pure character output.
Another dubious trick we can use is a variation of the `g` technique above. Instead of limiting ourselves to Befunge commands for the prefix, we can also technically use any character that isn't a Befunge command. On most interpreters an unrecognised command will be ignored, so the `g` will end up reading the ASCII value of the preceding character. This enables us to generate most other ASCII values that couldn't otherwise be calculated in 3 bytes. As one example: [`Qg1+,@`](http://befunge.tryitonline.net/#code=UWcxKyxA) gets you *R*.
Finally, there are three special cases. A *g* can't be generated in fewer than 5 bytes, so we have to resort to [`"f"1+,@`](http://befunge.tryitonline.net/#code=ImYiMSssQA). A comma is the most complicated, requiring dynamic modification of the playfield: [`0g4-:80p @`](http://befunge.tryitonline.net/#code=MGc0LTo4MHAgQA). We could use a similar technique to avoid the at character, but a more efficient hack is to use the `%` (modulo) command as the terminator, i.e. [`88*,%`](http://befunge.tryitonline.net/#code=ODgqLCU). When the `%` is reached there is nothing on the stack, so the modulo calculation generates a division by zero, and on the reference interpreter this will terminate the program.
Below is the full list of programs, one per line.
```
1g,@
1g1+,@
g3/,@
57*,@
49*,@
1g5+,@
1g6+,@
1g7+,@
58*,@
1g9+,@
0g6-,@
0g5-,@
0g4-:80p @
59*,@
0g2-,@
0g1-,@
.@
!.@
11+.@
21+.@
31+.@
41+.@
51+.@
61+.@
71+.@
81+.@
>g4-,@
:g1+,@
:g2+,@
:g3+,@
:g4+,@
79*,@
88*,%
>g3+,@
>g4+,@
>g5+,@
>g6+,@
>g7+,@
>g8+,@
>g9+,@
89*,@
Hg1+,@
Ig1+,@
Jg1+,@
Kg1+,@
Lg1+,@
Mg1+,@
Ng1+,@
Og1+,@
99*,@
Qg1+,@
\g9-,@
\g8-,@
\g7-,@
\g6-,@
\g5-,@
\g4-,@
\g3-,@
\g2-,@
\g1-,@
_g3-,@
\g1+,@
g9-,@
g8-,@
g7-,@
g6-,@
g5-,@
g4-,@
g3-,@
g2-,@
g1-,@
"f"1+,@
g1+,@
g2+,@
g3+,@
g4+,@
g5+,@
g6+,@
g7+,@
g8+,@
g9+,@
tg3-,@
tg2-,@
tg1-,@
:g2*,@
tg1+,@
tg2+,@
tg3+,@
tg4+,@
tg5+,@
tg6+,@
tg7+,@
>g2*,@
tg9+,@
*g3*,@
```
] |
[Question]
[
**Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers.
---
Questions without an **objective primary winning criterion** are off-topic, as they make it impossible to indisputably decide which entry should win.
Closed 8 years ago.
**Locked**. This question and its answers are [locked](/help/locked-posts) because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions.
*Based on the very successful [Twitter image encoding challenge](https://stackoverflow.com/questions/891643/twitter-image-encoding-challenge) at Stack Overflow.*
If an image is worth 1000 words, how much of an image can you fit in 114.97 bytes?
I challenge you to come up with a general-purpose method to compress images into a standard Twitter comment that contains *only printable ASCII text*.
## Rules:
1. You must write a program that can take an image and output the encoded text.
2. The text created by the program must be at most 140 characters long and must only contain characters whose code points are in the range of 32-126, inclusive.
3. You must write a program (possibly the same program) that can take the encoded text and output a decoded version of the photograph.
4. Your program can use external libraries and files, but cannot require an internet connection or a connection to other computers.
5. The decoding process cannot access or contain the original images in any way.
6. Your program must accept images in at least one of these formats (not necessarily more): Bitmap, JPEG, GIF, TIFF, PNG. If some or all of the sample images are not in the correct format, you can convert them yourself prior to compression by your program.
## Judging:
This is a somewhat subjective challenge, so the winner will (eventually) be judged by me. I will focus my judgment on a couple of important factors, listed below in decreasing importance:
1. Ability to do a reasonable job of compressing a wide variety of images, including those not listed as a sample image
2. Ability to preserve the outlines of the major elements in an image
3. Ability to compress the colors of the major elements in an image
4. Ability to preserve outlines and colors of the minor details in an image
5. Compression time. Although not as important as how well an image is compressed, faster programs are better than slower programs that do the same thing.
Your submission should include the resulting images after decompression, along with the Twitter comment generated. If possible, you could also give a link to the source code.
## Sample images:
[The Hindenburg](http://dlimages.businessweek.com/imageserve/01Vlbfwgg1cO6/630x418.jpg),
[Mountainous Landscape](https://i.imgur.com/VaCzpRL.jpg),
[Mona Lisa](http://upload.wikimedia.org/wikipedia/commons/6/6a/Mona_Lisa.jpg),
[2D Shapes](http://2.bp.blogspot.com/_OFIUxCuqBAE/TSYBj9uokJI/AAAAAAAAA58/hQOseyldz6k/s400/2d+shapes.bmp)
[Answer]
I've improved my method by adding actual compression. It now operates by iteratively doing the following:
1. Convert the image to YUV
2. Downsize the image preserving the aspect ratio (if the image is color, the chroma is sampled at 1/3 the width & height of the luminance)
3. Reduce the bit depth to 4 bits per sample
4. Apply median prediction to the image, making the sample distribution more uniform
5. Apply adaptive range compression to the image.
6. See if the size of the compressed image is <= 112
The largest image that fits in the 112 bytes is then used as the final image, with the remaining two bytes used to store the width & height of the compressed image, plus a flag indicating if the image is in color. For decoding, the process is reversed, and the image scaled up so the smaller dimension is 128.
There is some room for improvement, namely not all the available bytes are used typically, but I feel I'm at the point of significantly diminishing returns for downsampling + lossless compression.
[Quick & dirty C++ source](http://lags.leetcode.net/timage.cpp)
[Windows exe](http://lags.leetcode.net/timage.exe)
**Mona Lisa** (13x20 luminance, 4x6 chroma)
```
&Jhmi8(,x6})Y"f!JC1jTzRh}$A7ca%/B~jZ?[_I17+91j;0q';|58yvX}YN426@"97W8qob?VB'_Ps`x%VR=H&3h8K=],4Bp=$K=#"v{thTV8^~lm vMVnTYT3rw N%I
```
![Mona Lisa](https://i.stack.imgur.com/RPqE1.jpg) ![Mona Lisa Twitter encoded](https://i.stack.imgur.com/dF5Et.png)
**Hindenburg** (21x13 luminance)
```
GmL<B&ep^m40dPs%V[4&"~F[Yt-sNceB6L>Cs#/bv`\4{TB_P Rr7Pjdk7}<*<{2=gssBkR$>!['ROG6Xs{AEtnP=OWDP6&h{^l+LbLr4%R{15Zc<D?J6<'#E.(W*?"d9wdJ'
```
![Hindenburg](https://i.stack.imgur.com/MC1zD.jpg) ![Hindenburg twitter encoded](https://i.stack.imgur.com/jfJV9.png)
**Mountains** (19x14 luminance, 6x4 chroma)
```
Y\Twg]~KC((s_P>,*cePOTM_X7ZNMHhI,WeN(m>"dVT{+cXc?8n,&m$TUT&g9%fXjy"A-fvc 3Y#Yl-P![lk~;.uX?a,pcU(7j?=HW2%i6fo@Po DtT't'(a@b;sC7"/J
```
![Mountain](https://i.stack.imgur.com/H5Wev.jpg) ![Mountain twitter encoded](https://i.stack.imgur.com/5D7Hy.png)
**2D Shapes** (21x15 luminance, 7x5 chroma)
```
n@|~c[#w<Fv8mD}2LL!g_(~CO&MG+u><-jT#{KXJy/``#S@m26CQ=[zejo,gFk0}A%i4kE]N ?R~^8!Ki*KM52u,M(his+BxqDCgU>ul*N9tNb\lfg}}n@HhX77S@TZf{k<CO69!
```
![2D Shapes](https://i.stack.imgur.com/MCCNU.jpg) ![2D Shapes twitter encoded](https://i.stack.imgur.com/mMyBK.png)
[Answer]
## Go
Works by dividing the image into regions recursively. I try to divide regions with high information content, and pick the dividing line to maximize the difference in color between the two regions.
Each division is encoded using a few bits to encode the dividing line. Each leaf region is encoded as a single color.
![enter image description here](https://i.stack.imgur.com/S9kyV.png)
```
4vN!IF$+fP0~\}:0d4a's%-~@[Q(qSd<<BDb}_s|qb&8Ys$U]t0mc]|! -FZO=PU=ln}TYLgh;{/"A6BIER|{lH1?ZW1VNwNL 6bOBFOm~P_pvhV)]&[p%GjJ ,+&!p"H4`Yae@:P
```
![enter image description here](https://i.stack.imgur.com/W8QDR.png)
```
<uc}+jrsxi!_:GXM!'w5J)6]N)y5jy'9xBm8.A9LD/^]+t5#L-6?9 a=/f+-S*SZ^Ch07~s)P("(DAc+$[m-:^B{rQTa:/3`5Jy}AvH2p!4gYR>^sz*'U9(p.%Id9wf2Lc+u\&\5M>
```
![enter image description here](https://i.stack.imgur.com/UycLg.png)
```
lO6>v7z87n;XsmOW^3I-0'.M@J@CLL[4z-Xr:! VBjAT,##6[iSE.7+as8C.,7uleb=|y<t7sm$2z)k&dADF#uHXaZCLnhvLb.%+b(OyO$-2GuG~,y4NTWa=/LI3Q4w7%+Bm:!kpe&
```
![enter image description here](https://i.stack.imgur.com/FLyRT.png)
```
ZoIMHa;v!]&j}wr@MGlX~F=(I[cs[N^M`=G=Avr*Z&Aq4V!c6>!m@~lJU:;cr"Xw!$OlzXD$Xi>_|*3t@qV?VR*It4gB;%>,e9W\1MeXy"wsA-V|rs$G4hY!G:%v?$uh-y~'Ltd.,(
```
The Hindenburg picture looks pretty crappy, but the others I like.
```
package main
import (
"os"
"image"
"image/color"
"image/png"
_ "image/jpeg"
"math"
"math/big"
)
// we have 919 bits to play with: floor(log_2(95^140))
// encode_region(r):
// 0
// color of region (12 bits, 4 bits each color)
// or
// 1
// dividing line through region
// 2 bits - one of 4 anchor points
// 4 bits - one of 16 angles
// encode_region(r1)
// encode_region(r2)
//
// start with single region
// pick leaf region with most contrast, split it
type Region struct {
points []image.Point
anchor int // 0-3
angle int // 0-15
children [2]*Region
}
// mean color of region
func (region *Region) meanColor(img image.Image) (float64, float64, float64) {
red := 0.0
green := 0.0
blue := 0.0
num := 0
for _, p := range region.points {
r, g, b, _ := img.At(p.X, p.Y).RGBA()
red += float64(r)
green += float64(g)
blue += float64(b)
num++
}
return red/float64(num), green/float64(num), blue/float64(num)
}
// total non-uniformity in region's color
func (region *Region) deviation(img image.Image) float64 {
mr, mg, mb := region.meanColor(img)
d := 0.0
for _, p := range region.points {
r, g, b, _ := img.At(p.X, p.Y).RGBA()
fr, fg, fb := float64(r), float64(g), float64(b)
d += (fr - mr) * (fr - mr) + (fg - mg) * (fg - mg) + (fb - mb) * (fb - mb)
}
return d
}
// centroid of region
func (region *Region) centroid() (float64, float64) {
cx := 0
cy := 0
num := 0
for _, p := range region.points {
cx += p.X
cy += p.Y
num++
}
return float64(cx)/float64(num), float64(cy)/float64(num)
}
// a few points in (or near) the region.
func (region *Region) anchors() [4][2]float64 {
cx, cy := region.centroid()
xweight := [4]int{1,1,3,3}
yweight := [4]int{1,3,1,3}
var result [4][2]float64
for i := 0; i < 4; i++ {
dx := 0
dy := 0
numx := 0
numy := 0
for _, p := range region.points {
if float64(p.X) > cx {
dx += xweight[i] * p.X
numx += xweight[i]
} else {
dx += (4 - xweight[i]) * p.X
numx += 4 - xweight[i]
}
if float64(p.Y) > cy {
dy += yweight[i] * p.Y
numy += yweight[i]
} else {
dy += (4 - yweight[i]) * p.Y
numy += 4 - yweight[i]
}
}
result[i][0] = float64(dx) / float64(numx)
result[i][1] = float64(dy) / float64(numy)
}
return result
}
func (region *Region) split(img image.Image) (*Region, *Region) {
anchors := region.anchors()
// maximize the difference between the average color on the two sides
maxdiff := 0.0
var maxa *Region = nil
var maxb *Region = nil
maxanchor := 0
maxangle := 0
for anchor := 0; anchor < 4; anchor++ {
for angle := 0; angle < 16; angle++ {
sin, cos := math.Sincos(float64(angle) * math.Pi / 16.0)
a := new(Region)
b := new(Region)
for _, p := range region.points {
dx := float64(p.X) - anchors[anchor][0]
dy := float64(p.Y) - anchors[anchor][1]
if dx * sin + dy * cos >= 0 {
a.points = append(a.points, p)
} else {
b.points = append(b.points, p)
}
}
if len(a.points) == 0 || len(b.points) == 0 {
continue
}
a_red, a_green, a_blue := a.meanColor(img)
b_red, b_green, b_blue := b.meanColor(img)
diff := math.Abs(a_red - b_red) + math.Abs(a_green - b_green) + math.Abs(a_blue - b_blue)
if diff >= maxdiff {
maxdiff = diff
maxa = a
maxb = b
maxanchor = anchor
maxangle = angle
}
}
}
region.anchor = maxanchor
region.angle = maxangle
region.children[0] = maxa
region.children[1] = maxb
return maxa, maxb
}
// split regions take 7 bits plus their descendents
// unsplit regions take 13 bits
// so each split saves 13-7=6 bits on the parent region
// and costs 2*13 = 26 bits on the children, for a net of 20 bits/split
func (region *Region) encode(img image.Image) []int {
bits := make([]int, 0)
if region.children[0] != nil {
bits = append(bits, 1)
d := region.anchor
a := region.angle
bits = append(bits, d&1, d>>1&1)
bits = append(bits, a&1, a>>1&1, a>>2&1, a>>3&1)
bits = append(bits, region.children[0].encode(img)...)
bits = append(bits, region.children[1].encode(img)...)
} else {
bits = append(bits, 0)
r, g, b := region.meanColor(img)
kr := int(r/256./16.)
kg := int(g/256./16.)
kb := int(b/256./16.)
bits = append(bits, kr&1, kr>>1&1, kr>>2&1, kr>>3)
bits = append(bits, kg&1, kg>>1&1, kg>>2&1, kg>>3)
bits = append(bits, kb&1, kb>>1&1, kb>>2&1, kb>>3)
}
return bits
}
func encode(name string) []byte {
file, _ := os.Open(name)
img, _, _ := image.Decode(file)
// encoding bit stream
bits := make([]int, 0)
// start by encoding the bounds
bounds := img.Bounds()
w := bounds.Max.X - bounds.Min.X
for ; w > 3; w >>= 1 {
bits = append(bits, 1, w & 1)
}
bits = append(bits, 0, w & 1)
h := bounds.Max.Y - bounds.Min.Y
for ; h > 3; h >>= 1 {
bits = append(bits, 1, h & 1)
}
bits = append(bits, 0, h & 1)
// make new region containing whole image
region := new(Region)
region.children[0] = nil
region.children[1] = nil
for y := bounds.Min.Y; y < bounds.Max.Y; y++ {
for x := bounds.Min.X; x < bounds.Max.X; x++ {
region.points = append(region.points, image.Point{x, y})
}
}
// split the region with the most contrast until we're out of bits.
regions := make([]*Region, 1)
regions[0] = region
for bitcnt := len(bits) + 13; bitcnt <= 919-20; bitcnt += 20 {
var best_reg *Region
best_dev := -1.0
for _, reg := range regions {
if reg.children[0] != nil {
continue
}
dev := reg.deviation(img)
if dev > best_dev {
best_reg = reg
best_dev = dev
}
}
a, b := best_reg.split(img)
regions = append(regions, a, b)
}
// encode regions
bits = append(bits, region.encode(img)...)
// convert to tweet
n := big.NewInt(0)
for i := 0; i < len(bits); i++ {
n.SetBit(n, i, uint(bits[i]))
}
s := make([]byte,0)
r := new(big.Int)
for i := 0; i < 140; i++ {
n.DivMod(n, big.NewInt(95), r)
s = append(s, byte(r.Int64() + 32))
}
return s
}
// decodes and fills in region. returns number of bits used.
func (region *Region) decode(bits []int, img *image.RGBA) int {
if bits[0] == 1 {
anchors := region.anchors()
anchor := bits[1] + bits[2]*2
angle := bits[3] + bits[4]*2 + bits[5]*4 + bits[6]*8
sin, cos := math.Sincos(float64(angle) * math.Pi / 16.)
a := new(Region)
b := new(Region)
for _, p := range region.points {
dx := float64(p.X) - anchors[anchor][0]
dy := float64(p.Y) - anchors[anchor][1]
if dx * sin + dy * cos >= 0 {
a.points = append(a.points, p)
} else {
b.points = append(b.points, p)
}
}
x := a.decode(bits[7:], img)
y := b.decode(bits[7+x:], img)
return 7 + x + y
}
r := bits[1] + bits[2]*2 + bits[3]*4 + bits[4]*8
g := bits[5] + bits[6]*2 + bits[7]*4 + bits[8]*8
b := bits[9] + bits[10]*2 + bits[11]*4 + bits[12]*8
c := color.RGBA{uint8(r*16+8), uint8(g*16+8), uint8(b*16+8), 255}
for _, p := range region.points {
img.Set(p.X, p.Y, c)
}
return 13
}
func decode(name string) image.Image {
file, _ := os.Open(name)
length, _ := file.Seek(0, 2)
file.Seek(0, 0)
tweet := make([]byte, length)
file.Read(tweet)
// convert to bit string
n := big.NewInt(0)
m := big.NewInt(1)
for _, c := range tweet {
v := big.NewInt(int64(c - 32))
v.Mul(v, m)
n.Add(n, v)
m.Mul(m, big.NewInt(95))
}
bits := make([]int, 0)
for ; n.Sign() != 0; {
bits = append(bits, int(n.Int64() & 1))
n.Rsh(n, 1)
}
for ; len(bits) < 919; {
bits = append(bits, 0)
}
// extract width and height
w := 0
k := 1
for ; bits[0] == 1; {
w += k * bits[1]
k <<= 1
bits = bits[2:]
}
w += k * (2 + bits[1])
bits = bits[2:]
h := 0
k = 1
for ; bits[0] == 1; {
h += k * bits[1]
k <<= 1
bits = bits[2:]
}
h += k * (2 + bits[1])
bits = bits[2:]
// make new region containing whole image
region := new(Region)
region.children[0] = nil
region.children[1] = nil
for y := 0; y < h; y++ {
for x := 0; x < w; x++ {
region.points = append(region.points, image.Point{x, y})
}
}
// new image
img := image.NewRGBA(image.Rectangle{image.Point{0, 0}, image.Point{w, h}})
// decode regions
region.decode(bits, img)
return img
}
func main() {
if os.Args[1] == "encode" {
s := encode(os.Args[2])
file, _ := os.Create(os.Args[3])
file.Write(s)
file.Close()
}
if os.Args[1] == "decode" {
img := decode(os.Args[2])
file, _ := os.Create(os.Args[3])
png.Encode(file, img)
file.Close()
}
}
```
[Answer]
## Python
***Encoding requires [numpy](http://www.numpy.org/), [SciPy](http://www.scipy.org/) and [scikit-image](http://scikit-image.org/).
Decoding requires only [PIL](http://www.pythonware.com/products/pil/).***
This is a method based on superpixel interpolation. To begin, each image is divided into *70* similar sized regions of similar color. For example, the landscape picture is divided in the following manner:
![enter image description here](https://i.stack.imgur.com/i2p8l.jpg)
The centroid of each region is located (to the nearest raster point on a grid containing no more than 402 points), as well as it's average color (from a 216 color palette), and each of these regions is encoded as a number from *0* to *86832*, capable of being stored in *2.5* printable ascii characters (actually *2.497*, leaving just enough room to encode for a greyscale bit).
If you're attentive, you may have noticed that *140 / 2.5 = 56* regions, and not *70* as I stated earlier. Notice, however, that each of these regions is a unique, comparable object, which may be listed in any order. Because of this, we can use the *permutation* of the first *56* regions to encode for the other *14*, as well as having a few bits left over to store the aspect ratio.
More specifically, each of the additional *14* regions is converted to a number, and then each of these numbers concatenated together (multiplying the current value by *86832*, and adding the next). This (gigantic) number is then converted to a permutation on *56* objects.
For example:
```
from my_geom import *
# this can be any value from 0 to 56!, and it will map unambiguously to a permutation
num = 595132299344106583056657556772129922314933943196204990085065194829854239
perm = num2perm(num, 56)
print perm
print perm2num(perm)
```
will output:
```
[0, 3, 33, 13, 26, 22, 54, 12, 53, 47, 8, 39, 19, 51, 18, 27, 1, 41, 50, 20, 5, 29, 46, 9, 42, 23, 4, 37, 21, 49, 2, 6, 55, 52, 36, 7, 43, 11, 30, 10, 34, 44, 24, 45, 32, 28, 17, 35, 15, 25, 48, 40, 38, 31, 16, 14]
595132299344106583056657556772129922314933943196204990085065194829854239
```
The resulting permutation is then applied to the original *56* regions. The original number (and thus the additional *14* regions) can likewise be extracted by converting the permutation of the *56* encoded regions into its numerical representation.
When the `--greyscale` option is used with the encoder, *94* regions are used instead (separated *70*, *24*), with *558* raster points, and *16* shades of grey.
When decoding, each of these regions is treated as a 3D cone extended into infinity, with its vertex at the centroid of the region, as viewed from above (a.k.a. a Voronoi Diagram). The borders are then blended together to create the final product.
### Future Improvements
1. ~~The dimensions of the Mona Lisa are a bit off, due to the way I'm storing the aspect ratio. I'll need to use a different system.~~ *Fixed, by assuming that the original aspect ratio is somewhere between 1:21 and 21:1, which I think is a reasonable assumption.*
2. ~~The Hindenburg could be improved a lot. The color palette I'm using only has 6 shades of grey. If I introduced a greyscale-only mode, I could use the extra information to increase the color depth, number of regions, number of raster points, or any combination of the three.~~ *I've added a `--greyscale` option to the encoder, which does all three.*
3. ~~2d Shapes would probably look better with blending turned off. I'll likely add a flag for that.~~ *Added an encoder option to control the segmentation ratio, and a decoder option to turn off blending.*
4. More fun with combinatorics. *56!* is actually large enough to store *15* additional regions, and *15!* is large enough to store *2* more for a grand total of *73*. But wait, there's more! The partitioning of these *73* object could also be used to store more information. For example, there are *73 choose 56* ways to select the initial *56* regions, and then *17 choose 15* ways to select the next *15*. A grand total of *2403922132944423072* partitionings, big enough to store *3* more regions for a total of *76*. I'd need to come up with a clever way to uniquely number all partitions of *73* into groups of *56*, *15*, *2* ... *and back*. Perhaps not practical, but an interesting problem to think about.
---
```
0VW*`Gnyq;c1JBY}tj#rOcKm)v_Ac\S.r[>,Xd_(qT6 >]!xOfU9~0jmIMG{hcg-'*a.s<X]6*%U5>/FOze?cPv@hI)PjpK9\iA7P ]a-7eC&ttS[]K>NwN-^$T1E.1OH^c0^"J 4V9X
```
![enter image description here](https://i.stack.imgur.com/XKGMe.jpg) ![enter image description here](https://i.stack.imgur.com/5VAWM.jpg)
---
```
0Jc?NsbD#1WDuqT]AJFELu<!iE3d!BB>jOA'L|<j!lCWXkr:gCXuD=D\BL{gA\ 8#*RKQ*tv\\3V0j;_4|o7>{Xage-N85):Q/Hl4.t&'0pp)d|Ry+?|xrA6u&2E!Ls]i]T<~)58%RiA
```
and
```
4PV 9G7X|}>pC[Czd!5&rA5 Eo1Q\+m5t:r#;H65NIggfkw'h4*gs.:~<bt'VuVL7V8Ed5{`ft7e>HMHrVVUXc.{#7A|#PBm,i>1B781.K8>s(yUV?a<*!mC@9p+Rgd<twZ.wuFnN dp
```
![enter image description here](https://i.stack.imgur.com/U0GNI.jpg) ![enter image description here](https://i.stack.imgur.com/RHpIx.jpg) ![enter image description here](https://i.stack.imgur.com/P5o4F.jpg)
The second one encoded with the `--greyscale` option.
---
```
3dVY3TY?9g+b7!5n`)l"Fg H$ 8n?[Q-4HE3.c:[pBBaH`5'MotAj%a4rIodYO.lp$h a94$n!M+Y?(eAR,@Y*LiKnz%s0rFpgnWy%!zV)?SuATmc~-ZQardp=?D5FWx;v=VA+]EJ(:%
```
![enter image description here](https://i.stack.imgur.com/xqZIA.jpg) ![enter image description here](https://i.stack.imgur.com/MLbEb.jpg)
Encoded with the `--greyscale` option.
---
```
.9l% Ge<'_)3(`DTsH^eLn|l3.D_na,,sfcpnp{"|lSv<>}3b})%m2M)Ld{YUmf<Uill,*:QNGk,'f2; !2i88T:Yjqa8\Ktz4i@h2kHeC|9,P` v7Xzd Yp&z:'iLra&X&-b(g6vMq
```
![enter image description here](https://i.stack.imgur.com/1jQbo.jpg) ![enter image description here](https://i.stack.imgur.com/gyln5.jpg)
Encoded with `--ratio 60`, and decoded with `--no-blending` options.
---
encoder.py
```
from __future__ import division
import argparse, numpy
from skimage.io import imread
from skimage.transform import resize
from skimage.segmentation import slic
from skimage.measure import regionprops
from my_geom import *
def encode(filename, seg_ratio, greyscale):
img = imread(filename)
height = len(img)
width = len(img[0])
ratio = width/height
if greyscale:
raster_size = 558
raster_ratio = 11
num_segs = 94
set1_len = 70
max_num = 8928 # 558 * 16
else:
raster_size = 402
raster_ratio = 13
num_segs = 70
set1_len = 56
max_num = 86832 # 402 * 216
raster_width = (raster_size*ratio)**0.5
raster_height = int(raster_width/ratio)
raster_width = int(raster_width)
resize_height = raster_height * raster_ratio
resize_width = raster_width * raster_ratio
img = resize(img, (resize_height, resize_width))
segs = slic(img, n_segments=num_segs-4, ratio=seg_ratio).astype('int16')
max_label = segs.max()
numpy.place(segs, segs==0, [max_label+1])
regions = [None]*(max_label+2)
for props in regionprops(segs):
label = props['Label']
props['Greyscale'] = greyscale
regions[label] = Region(props)
for i, a in enumerate(regions):
for j, b in enumerate(regions):
if a==None or b==None or a==b: continue
if a.centroid == b.centroid:
numpy.place(segs, segs==j, [i])
regions[j] = None
for y in range(resize_height):
for x in range(resize_width):
label = segs[y][x]
regions[label].add_point(img[y][x])
regions = [r for r in regions if r != None]
if len(regions)>num_segs:
regions = sorted(regions, key=lambda r: r.area)[-num_segs:]
regions = sorted(regions, key=lambda r: r.to_num(raster_width))
set1, set2 = regions[-set1_len:], regions[:-set1_len]
set2_num = 0
for s in set2:
set2_num *= max_num
set2_num += s.to_num(raster_width)
set2_num = ((set2_num*85 + raster_width)*85 + raster_height)*25 + len(set2)
perm = num2perm(set2_num, set1_len)
set1 = permute(set1, perm)
outnum = 0
for r in set1:
outnum *= max_num
outnum += r.to_num(raster_width)
outnum *= 2
outnum += greyscale
outstr = ''
for i in range(140):
outstr = chr(32 + outnum%95) + outstr
outnum //= 95
print outstr
parser = argparse.ArgumentParser(description='Encodes an image into a tweetable format.')
parser.add_argument('filename', type=str,
help='The filename of the image to encode.')
parser.add_argument('--ratio', dest='seg_ratio', type=float, default=30,
help='The segmentation ratio. Higher values (50+) will result in more regular shapes, lower values in more regular region color.')
parser.add_argument('--greyscale', dest='greyscale', action='store_true',
help='Encode the image as greyscale.')
args = parser.parse_args()
encode(args.filename, args.seg_ratio, args.greyscale)
```
decoder.py
```
from __future__ import division
import argparse
from PIL import Image, ImageDraw, ImageChops, ImageFilter
from my_geom import *
def decode(instr, no_blending=False):
innum = 0
for c in instr:
innum *= 95
innum += ord(c) - 32
greyscale = innum%2
innum //= 2
if greyscale:
max_num = 8928
set1_len = 70
image_mode = 'L'
default_color = 0
raster_ratio = 11
else:
max_num = 86832
set1_len = 56
image_mode = 'RGB'
default_color = (0, 0, 0)
raster_ratio = 13
nums = []
for i in range(set1_len):
nums = [innum%max_num] + nums
innum //= max_num
set2_num = perm2num(nums)
set2_len = set2_num%25
set2_num //= 25
raster_height = set2_num%85
set2_num //= 85
raster_width = set2_num%85
set2_num //= 85
resize_width = raster_width*raster_ratio
resize_height = raster_height*raster_ratio
for i in range(set2_len):
nums += set2_num%max_num,
set2_num //= max_num
regions = []
for num in nums:
r = Region()
r.from_num(num, raster_width, greyscale)
regions += r,
masks = []
outimage = Image.new(image_mode, (resize_width, resize_height), default_color)
for a in regions:
mask = Image.new('L', (resize_width, resize_height), 255)
for b in regions:
if a==b: continue
submask = Image.new('L', (resize_width, resize_height), 0)
poly = a.centroid.bisected_poly(b.centroid, resize_width, resize_height)
ImageDraw.Draw(submask).polygon(poly, fill=255, outline=255)
mask = ImageChops.multiply(mask, submask)
outimage.paste(a.avg_color, mask=mask)
if not no_blending:
outimage = outimage.resize((raster_width, raster_height), Image.ANTIALIAS)
outimage = outimage.resize((resize_width, resize_height), Image.BICUBIC)
smooth = ImageFilter.Kernel((3,3),(1,2,1,2,4,2,1,2,1))
for i in range(20):outimage = outimage.filter(smooth)
outimage.show()
parser = argparse.ArgumentParser(description='Decodes a tweet into and image.')
parser.add_argument('--no-blending', dest='no_blending', action='store_true',
help="Do not blend the borders in the final image.")
args = parser.parse_args()
instr = raw_input()
decode(instr, args.no_blending)
```
my\_geom.py
```
from __future__ import division
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
self.xy = (x, y)
def __eq__(self, other):
return self.x == other.x and self.y == other.y
def __lt__(self, other):
return self.y < other.y or (self.y == other.y and self.x < other.x)
def inv_slope(self, other):
return (other.x - self.x)/(self.y - other.y)
def midpoint(self, other):
return Point((self.x + other.x)/2, (self.y + other.y)/2)
def dist2(self, other):
dx = self.x - other.x
dy = self.y - other.y
return dx*dx + dy*dy
def bisected_poly(self, other, resize_width, resize_height):
midpoint = self.midpoint(other)
points = []
if self.y == other.y:
points += (midpoint.x, 0), (midpoint.x, resize_height)
if self.x < midpoint.x:
points += (0, resize_height), (0, 0)
else:
points += (resize_width, resize_height), (resize_width, 0)
return points
elif self.x == other.x:
points += (0, midpoint.y), (resize_width, midpoint.y)
if self.y < midpoint.y:
points += (resize_width, 0), (0, 0)
else:
points += (resize_width, resize_height), (0, resize_height)
return points
slope = self.inv_slope(other)
y_intercept = midpoint.y - slope*midpoint.x
if self.y > midpoint.y:
points += ((resize_height - y_intercept)/slope, resize_height),
if slope < 0:
points += (resize_width, slope*resize_width + y_intercept), (resize_width, resize_height)
else:
points += (0, y_intercept), (0, resize_height)
else:
points += (-y_intercept/slope, 0),
if slope < 0:
points += (0, y_intercept), (0, 0)
else:
points += (resize_width, slope*resize_width + y_intercept), (resize_width, 0)
return points
class Region:
def __init__(self, props={}):
if props:
self.greyscale = props['Greyscale']
self.area = props['Area']
cy, cx = props['Centroid']
if self.greyscale:
self.centroid = Point(int(cx/11)*11+5, int(cy/11)*11+5)
else:
self.centroid = Point(int(cx/13)*13+6, int(cy/13)*13+6)
self.num_pixels = 0
self.r_total = 0
self.g_total = 0
self.b_total = 0
def __lt__(self, other):
return self.centroid < other.centroid
def add_point(self, rgb):
r, g, b = rgb
self.r_total += r
self.g_total += g
self.b_total += b
self.num_pixels += 1
if self.greyscale:
self.avg_color = int((3.2*self.r_total + 10.7*self.g_total + 1.1*self.b_total)/self.num_pixels + 0.5)*17
else:
self.avg_color = (
int(5*self.r_total/self.num_pixels + 0.5)*51,
int(5*self.g_total/self.num_pixels + 0.5)*51,
int(5*self.b_total/self.num_pixels + 0.5)*51)
def to_num(self, raster_width):
if self.greyscale:
raster_x = int((self.centroid.x - 5)/11)
raster_y = int((self.centroid.y - 5)/11)
return (raster_y*raster_width + raster_x)*16 + self.avg_color//17
else:
r, g, b = self.avg_color
r //= 51
g //= 51
b //= 51
raster_x = int((self.centroid.x - 6)/13)
raster_y = int((self.centroid.y - 6)/13)
return (raster_y*raster_width + raster_x)*216 + r*36 + g*6 + b
def from_num(self, num, raster_width, greyscale):
self.greyscale = greyscale
if greyscale:
self.avg_color = num%16*17
num //= 16
raster_x, raster_y = num%raster_width, num//raster_width
self.centroid = Point(raster_x*11 + 5, raster_y*11+5)
else:
rgb = num%216
r, g, b = rgb//36, rgb//6%6, rgb%6
self.avg_color = (r*51, g*51, b*51)
num //= 216
raster_x, raster_y = num%raster_width, num//raster_width
self.centroid = Point(raster_x*13 + 6, raster_y*13 + 6)
def perm2num(perm):
num = 0
size = len(perm)
for i in range(size):
num *= size-i
for j in range(i, size): num += perm[j]<perm[i]
return num
def num2perm(num, size):
perm = [0]*size
for i in range(size-1, -1, -1):
perm[i] = int(num%(size-i))
num //= size-i
for j in range(i+1, size): perm[j] += perm[j] >= perm[i]
return perm
def permute(arr, perm):
size = len(arr)
out = [0] * size
for i in range(size):
val = perm[i]
out[i] = arr[val]
return out
```
[Answer]
# PHP
OK, took me a while, but here it is. All images in greyscale. Colors took too many bits to encode for my method :P
---
**Mona Lisa**
**47** Colors Monochrome
**101** byte string.
```
dt99vvv9t8G22+2eZbbf55v3+fAH9X+AD/0BAF6gIOX5QRy7xX8em9/UBAEVXKiiqKqqqiqqqqNqqqivtXqqMAFVUBVVVVVVVVVVU
```
![mona](https://i.stack.imgur.com/yKEUo.jpg) ![lisa](https://i.stack.imgur.com/gNWp0.gif)
---
**2D Shapes**
**36** Colors Monochrome
**105** byte string.
```
oAAAAAAABMIDUAAEBAyoAAAAAgAwAAAAADYBtsAAAJIDbYAAAAA22AGwAAAAAGwAAAAAAAAAAKgAAAAAqgAAAACoAAAAAAAAAAAAAAAAA
```
![2d](https://i.stack.imgur.com/S1LxI.jpg) ![2dc](https://i.stack.imgur.com/Yg2NR.gif)
---
**Hindenburg**
**62** Colors Monochrome
**112** characters.
```
t///tCSuvv/99tmwBI3/21U5gCW/+2bdDMxLf+r6VsaHb/tt7TAodv+NhtbFVX/bGD1IVq/4MAHbKq/4AABbVX/AQAFN1f8BCBFntb/6ttYdWnfg
```
![pics here](https://i.stack.imgur.com/uulZg.jpg) ![enter image description here](https://i.stack.imgur.com/9IClL.gif)
---
**Mountains**
**63** Colors Monochrome
**122** characters.
```
qAE3VTkaIAKgqSFigAKoABgQEqAABuAgUQAGenRIBoUh2eqhABCee/2qSSAQntt/s2kJCQbf/bbaJgbWebzqsPZ7bZttwABTc3VAUFDbKqqpzY5uqpudnp5vZg
```
![picshere](https://i.stack.imgur.com/80spA.jpg) ![enter image description here](https://i.stack.imgur.com/IkGld.gif)
---
**My Method**
I encode my bitstream with a type of base64 encoding. Before it's encoded into readable text, here's what happens.
I load the source image and resize it to a maximum height or width (depending on orientation, portrait/landscape) of 20 pixels.
Next I recolor each pixel of the new image to it's closest match on a 6 color greyscale palette.
After that's done, I create a string with each pixel color represented by the letters [A-F].
I then calculate the distribution of the 6 different letters within the string and select the most optimized binary tree for encoding based on the letter frequencies. There are 15 possible binary trees.
I start my bit stream with a single bit, `[1|0]` depending on whether the image is tall or wide. I then use the next 4 bits in the stream to inform the decoder which binary tree should be used to decode the image.
What follows is the stream of bits representing the image. Each pixel and it's color is represented by either 2 or 3 bits. This allows me to store at least 2 and up to 3 pixels worth of information for every printed ascii character. Here's a sample of binary tree `1110`, which is used by the Mona Lisa:
```
TREE
/ \
# #
/ \ / \
E # F #
/ \ / \
A B C D
```
The letters E `00` and F `10` are the most common colors in the Mona Lisa. A `010`, B `011`, C `110`, and D `111` are the least frequent.
Binary trees work like this: Going from bit to bit, `0` means go left, `1` means go right. Keep going until you hit a leaf on the tree, or a dead end. The leaf you end up on is the character you want.
Anyways, I encode the binary sting into base64 characters. When decoding the string, the process is done in reverse, assigning all the pixels to the appropriate color, and then the image is scaled twice the encoded size (maximum 40 pixels either X or Y, whichever is larger) and then a convolution matrix is applied to the whole thing to smooth out the colors.
Anyways, here's the current code: "[pastebin link](http://pastebin.com/xbGPVgSD)"
It's ugly, but if you see any room for improvements, let me know. I hacked it together as I want along. I LEARNED **A LOT** FROM THIS CHALLENGE. Thank you OP for posting it!
[Answer]
My first attempt. This has room for improvement. I think that the format itself actually works, the issue is in the encoder. That, and I'm missing individual bits from my output... my (slightly higher quality then here) file ended up at 144 characters, when there should have been some left. (and I really wish there was - the differences between these and those are noticeable). I learnt though, never overestimate how big 140 characters is...
I bring it down to a modified version of the RISC-OS palette - basically, because I needed a 32 colour palette, and that seemed like a good enough place to start. This could do with some changing too I think.
![Palette](https://i.stack.imgur.com/mRq8a.png)
I break it down into the following shapes:
![Shapes](https://i.stack.imgur.com/hkNhXl.png)
and split the image into palette blocks (in this case, 2x2 pixels) of a front and back color.
## Results:
Following are the tweets, the originals and how the tweet is decoded
```
*=If`$aX:=|"&brQ(EPZwxu4H";|-^;lhJCfQ(W!TqWTai),Qbd7CCtmoc(-hXt]/l87HQyaYTEZp{eI`/CtkHjkFh,HJWw%5[d}VhHAWR(@;M's$VDz]17E@6
```
![Hindeberg](https://i.stack.imgur.com/phfitm.jpg)
![My hindenberg](https://i.stack.imgur.com/alXSDm.png)
```
"&7tpnqK%D5kr^u9B]^3?`%;@siWp-L@1g3p^*kQ=5a0tBsA':C0"*QHVDc=Z='Gc[gOpVcOj;_%>.aeg+JL4j-u[a$WWD^)\tEQUhR]HVD5_-e`TobI@T0dv_el\H1<1xw[|D
```
![Mountain](https://i.stack.imgur.com/GZuTSm.jpg)
![My Mountain](https://i.stack.imgur.com/1zt6nm.png)
```
)ey`ymlgre[rzzfi"K>#^=z_Wi|@FWbo#V5|@F)uiH?plkRS#-5:Yi-9)S3:#3 Pa4*lf TBd@zxa0g;li<O1XJ)YTT77T1Dg1?[w;X"U}YnQE(NAMQa2QhTMYh..>90DpnYd]?
```
![Shapes](https://i.stack.imgur.com/0FH6zm.jpg)
![My Shapes](https://i.stack.imgur.com/Qrgnim.png)
```
%\MaaX/VJNZX=Tq,M>2"AwQVR{(Xe L!zb6(EnPuEzB}Nk:U+LAB_-K6pYlue"5*q>yDFw)gSC*&,dA98`]$2{&;)[ 4pkX |M _B4t`pFQT8P&{InEh>JHYn*+._[b^s754K_
```
![Mona Lisa](https://i.stack.imgur.com/6dOg9m.jpg)
![Mona Lisa Mine](https://i.stack.imgur.com/3cJmBm.png)
I know the colours are wrong, but I actually like the Monalisa. If I removed the blur (which wouldn't be too hard), it's a reasonable cubist impression :p
I need to work on
* Adding shape detection
* A better colour "difference" algorithm
* Figuring out where my missing bits went
I'll give it some more work later to try to fix those, and improved the encoder. Those extra 20 or so characters make a massive amount of difference. I'd like them back.
The C# source and colour palette are on <https://dl.dropboxusercontent.com/u/46145976/Base96.zip> - although, in hindsight, may not work perfectly when run separately (as spaces in arguments to programs don't go so well).
The encoder takes less then a couple of seconds on my fairly average machine.
[Answer]
I gave up on trying to keep the colour and went black and white, since everything I tried with colour was unrecognisable.
Basically all it does is divide pixels into 3 approximately equal parts: black, grey and white. It also doesn't keep the size.
## Hindenburg
```
~62RW.\7`?a9}A.jvCedPW0t)]g/e4 |+D%n9t^t>wO><",C''!!Oh!HQq:WF>\uEG?E=Mkj|!u}TC{7C7xU:bb`We;3T/2:Zw90["$R25uh0732USbz>Q;q"
```
![Hindenburg](https://i.stack.imgur.com/phfitm.jpg) ![HindenburgCompressed](https://i.stack.imgur.com/5O3Ur.png)
## Mona Lisa
```
=lyZ(i>P/z8]Wmfu>] T55vZB:/>xMz#Jqs6U3z,)n|VJw<{Mu2D{!uyl)b7B6x&I"G0Y<wdD/K4hfrd62_8C\W7ArNi6R\Xz%f U[);YTZFliUEu{m%[gw10rNY_`ICNN?_IB/C&=T
```
![MonaLisa](https://i.stack.imgur.com/6dOg9m.jpg) ![MonaLisaCompressed](https://i.stack.imgur.com/p2T9E.png)
## Mountains
```
+L5#~i%X1aE?ugVCulSf*%-sgIg8hQ3j/df=xZv2v?'XoNdq=sb7e '=LWm\E$y?=:"#l7/P,H__W/v]@pwH#jI?sx|n@h\L %y(|Ry.+CvlN $Kf`5W(01l2j/sdEjc)J;Peopo)HJ
```
![Mountains](https://i.stack.imgur.com/GZuTSm.jpg) ![MountainsCompressed](https://i.stack.imgur.com/gnaQD.png)
## Shapes
```
3A"3yD4gpFtPeIImZ$g&2rsdQmj]}gEQM;e.ckbVtKE(U$r?{,S>tW5JzQZDzoTy^mc+bUV vTUG8GXs{HX'wYR[Af{1gKwY|BD]V1Z'J+76^H<K3Db>Ni/D}][n#uwll[s'c:bR56:
```
![Shapes](https://i.stack.imgur.com/0FH6zm.jpg) ![ShapesCompressed](https://i.stack.imgur.com/PUR4l.png)
Here's the program. `python compress.py -c img.png` compresses `img.png` and prints the tweet.
`python compress.py -d img.png` takes the tweet from stdin and saves the image to `img.png`.
```
from PIL import Image
import sys
quanta = 3
width = 24
height = 24
def compress(img):
pix = img.load()
psums = [0]*(256*3)
for x in range(width):
for y in range(height):
r,g,b,a = pix[x,y]
psums[r+g+b] += 1
s = 0
for i in range(256*3):
s = psums[i] = psums[i]+s
i = 0
for x in range(width):
for y in range(height):
r,g,b,a = pix[x,y]
t = psums[r+g+b]*quanta / (width*height)
if t == quanta:
t -= 1
i *= quanta
i += t
s = []
while i:
s += chr(i%95 + 32)
i /= 95
return ''.join(s)
def decompress(s):
i = 0
for c in s[::-1]:
i *= 95
i += ord(c) - 32
img = Image.new('RGB',(width,height))
pix = img.load()
for x in range(width)[::-1]:
for y in range(height)[::-1]:
t = i % quanta
i /= quanta
t *= 255/(quanta-1)
pix[x,y] = (t,t,t)
return img
if sys.argv[1] == '-c':
img = Image.open(sys.argv[2]).resize((width,height))
print compress(img)
elif sys.argv[1] == '-d':
img = decompress(raw_input())
img.resize((256,256)).save(sys.argv[2],'PNG')
```
[Answer]
My modest contribution in R:
```
encoder<-function(img_file){
img0 <- as.raster(png::readPNG(img_file))
d0 <- dim(img0)
r <- d0[1]/d0[2]
f <- floor(sqrt(140/r))
d1 <- c(floor(f*r),f)
dx <- floor(d0[2]/d1[2])
dy <- floor(d0[1]/d1[1])
img1 <- matrix("",ncol=d1[2],nrow=d1[1])
x<-seq(1,d0[1],by=dy)
y<-seq(1,d0[2],by=dx)
for(i in seq_len(d1[1])){
for (j in seq_len(d1[2])){
img1[i,j]<-names(which.max(table(img0[x[i]:(x[i]+dy-1),y[j]:(y[j]+dx-1)])))
}
}
img2 <- as.vector(img1)
table1 <- array(sapply(seq(0,255,length=4),function(x)sapply(seq(0,255,length=4),function(y)sapply(seq(0,255,length=4),function(z)rgb(x/255,y/255,z/255)))),dim=c(4,4,4))
table2 <- array(strsplit(rawToChar(as.raw(48:(48+63))),"")[[1]],dim=c(4,4,4))
table3 <- cbind(1:95,sapply(32:126,function(x)rawToChar(as.raw(x))))
a <- as.array(cut(colorspace::hex2RGB(img2)@coords,breaks=seq(0,1,length=5),include.lowest=TRUE))
dim(a) <- c(length(img2),3)
img3 <- apply(a,1,function(x)paste("#",c("00","55","AA","FF")[x[1]],c("00","55","AA","FF")[x[2]],c("00","55","AA","FF")[x[3]],sep=""))
res<-paste(sapply(img3,function(x)table2[table1==x]),sep="",collapse="")
paste(table3[table3[,1]==d1[1],2],table3[table3[,1]==d1[2],2],res,collapse="",sep="")
}
decoder<-function(string){
s <- unlist(strsplit(string,""))
table1 <- array(sapply(seq(0,255,length=4),function(x)sapply(seq(0,255,length=4),function(y)sapply(seq(0,255,length=4),function(z)rgb(x/255,y/255,z/255)))),dim=c(4,4,4))
table2 <- array(strsplit(rawToChar(as.raw(48:(48+63))),"")[[1]],dim=c(4,4,4))
table3 <- cbind(1:95,sapply(32:126,function(x)rawToChar(as.raw(x))))
nr<-as.integer(table3[table3[,2]==s[1],1])
nc<-as.integer(table3[table3[,2]==s[2],1])
img <- sapply(s[3:length(s)],function(x){table1[table2==x]})
png(w=nc,h=nr,u="in",res=100)
par(mar=rep(0,4))
plot(c(1,nr),c(1,nc),type="n",axes=F,xaxs="i",yaxs="i")
rasterImage(as.raster(matrix(img,nr,nc)),1,1,nr,nc)
dev.off()
}
```
The idea is simply to reduce the raster (file has to be in png) to a matrix whose number of cell is lower than 140, the tweets is then a serie of colors (in 64 colors) preceded by two characters indicated the number of rows and columns of the raster.
```
encoder("Mona_Lisa.png")
[1] ",(XXX000@000000XYi@000000000TXi0000000000TX0000m000h00T0hT@hm000000T000000000000XX00000000000XXi0000000000TXX0000000000"
```
![enter image description here](https://i.stack.imgur.com/m7WLd.png)
```
encoder("630x418.png") # Not a huge success for this one :)
[1] "(-00000000000000000000EEZZooo00E0ZZooo00Z00Zooo00Zo0oooooEZ0EEZoooooooEZo0oooooo000ooZ0Eo0000oooE0EE00oooEEEE0000000E00000000000"
```
![enter image description here](https://i.stack.imgur.com/sfVMr.png)
```
encoder("2d shapes.png")
[1] "(,ooooooooooooooooooooo``ooooo0o``oooooooooo33ooooooo33oo0ooooooooooo>>oooo0oooooooo0ooooooooooooolloooo9oolooooooooooo"
```
![enter image description here](https://i.stack.imgur.com/uKYQb.png)
```
encoder("mountains.png")
[1] "(,_K_K0005:_KKK0005:__OJJ006:_oKKK00O:;;_K[[4OD;;Kooo4_DOKK_o^D_4KKKJ_o5o4KK__oo4_0;K___o5JDo____o5Y0____440444040400D4"
```
![enter image description here](https://i.stack.imgur.com/ExBbq.png)
[Answer]
**Not a complete solution, just putting the method out there. (Matlab)**
I used a 16 color palette and 40 position to create a weighted [voronoi diagram](http://en.wikipedia.org/wiki/Voronoi_diagram). Used genetic algorithm and simple hill-climbing algorithm to fit the image.
[Album](https://i.stack.imgur.com/Sd5oY.jpg) with original image and I also have a **16 byte version** with 4 colors and fixed positions there. :)
![enter image description here](https://i.stack.imgur.com/bu63y.png)
(Can I resize image here?)
[Answer]
# C#
# Update - Version 2
---
I made another attempt at this, now using MagickImage.NET(<https://magick.codeplex.com/>) to encode the JPEG data, I also wrote some basic code to better process JPEG header data(as primo suggested), I also used GuassianBlur on the output which help soften some of the JPEG compression. As the new version preforms better, I've updated my post to reflect the new method.
# Method
---
I've tried something unique(hopefully), rather than trying to manipulate the color depth, or edge identification, or trying to use different ways to reduce the images size myself I've used the JPEG algorithm at maximum compression on scaled down versions of the images, then by eliminating everything but the "StartOfScan"(<http://en.wikipedia.org/wiki/JPEG#Syntax_and_structure>) and a few key header elements I'm able to get the size down to a acceptable amount. The results are actually pretty impressive for 140 characters, gives me a new found respect for JPEG's:
## Hindenburg
![Hindenburg](https://i.stack.imgur.com/yDhLz.png) ![Original](https://i.stack.imgur.com/kPpYI.png)
```
,$`"(b $! _ &4j6k3Qg2ns2"::4]*;12T|4z*4n*4<T~a4- ZT_%-.13`YZT;??e#=*!Q033*5>z?1Ur;?2i2^j&r4TTuZe2444b*:>z7.:2m-*.z?|*-Pq|*,^Qs<m&?:e--
```
## Mountains
![Mountains](https://i.stack.imgur.com/5Ugcc.png) ![Original](https://i.stack.imgur.com/WkLTK.png)
```
,$ (a`,! (1 Q$ /P!U%%%,0b*2nr4 %)3t4 +3#UsZf3S2 7-+m1Yqis k2U'm/#"h q2T4#$s.]/)%1T &*,4Ze w$Q2Xqm&: %Q28qiqm Q,48Xq12 _
```
## Mona Lisa
![Mona Lisa](https://i.stack.imgur.com/2bhKc.png) ![Original](https://i.stack.imgur.com/aEfxK.png)
```
23 (a`,! (1 Q$ /P q1Q2Tc$q0,$9--/!p Ze&:6`#*,Tj6l0qT%(:!m!%(84|TVk0(*2k24P)!e(U,q2x84|Tj*8a1a-%** $r4_--Xr&)12Tj8a2Tj* %r444 %%%% !
```
## Shapes
![Shapes](https://i.stack.imgur.com/sWWr8.png) ![Original](https://i.stack.imgur.com/NwaIN.png)
```
(ep 1# ,! (1 Q$ /P"2`#=WTp $X[4 &[Vp p<T +0 cP* 0W=["jY5cZ9(4 (<]t ]Z %ZT -P!18=V+UZ4" #% i6%r}#"l p QP>*r $!Yq(!]2 jo* zp!0 4 % !0 4 % '!
```
# Code
---
## Version 2 - <http://pastebin.com/Tgr8XZUQ>
I'm really starting to miss ReSharper + I have allot of things to improve, still allot of hard coding going on here, interesting to mess with though(remember you need MagickImage dll's to get this to run in VS)
## Original(Deprecated) - <http://pastebin.com/BDPT0BKT>
Still bit of a mess.
[Answer]
## Python 3
# Method
What the program does first is scaling down the image, greatly decreasing its size.
Second, it converts the rgb values into binary, and snips off the last few digits.
Then it converts the base 2 data into base 10, where it adds the dimensions of the picture.
Then it converts the data in base 10 to base 95, using all the ascii I could find. However, I could not use /x01 and the like because of its ability to negate the function that wrote out the text file.
And (for added ambiguity), the decode function does it in reverse.
# compress.py
```
from PIL import Image
def FromBase(digits, b): #converts to base 10 from base b
numerals='''0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*()_-+={[}]|:;"',<.>/?`~\\ '''
D=[]
for d in range(0,len(digits)):
D.append(numerals.index(digits[d]))
s=0
D=D[::-1]
for x in range(0,len(D)):
s+=D[x]*(b**x)
return(str(s))
def ToBase(digits,b): #converts from base 10 to base b
numerals='''0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*()_-+={[}]|:;"',<.>/?`~\\ '''
d=int(digits)
D=''
B=b
while(B<=d):
B*=b
B//=b
while(B>=1):
D+=numerals[d//B]
d-=((d//B)*B)
B//=b
return(D)
im=Image.open('1.png')
size=im.size
scale_factor=40
im=im.resize((int(size[0]/scale_factor),int(size[1]/scale_factor)), Image.ANTIALIAS)
a=list(im.getdata())
K=''
for x in a:
for y in range(0,3):
Y=bin(x[y])[2:]
while(len(Y))<9:
Y='0'+Y
K+=str(Y)[:-5]
K='1'+K
print(len(K))
K=FromBase(K,2)
K+=str(size[0])
K+=str(size[1])
K=ToBase(K,95)
with open('1.txt', 'w') as outfile:
outfile.write(K)
```
# decode.py
```
from random import randint, uniform
from PIL import Image, ImageFilter
import math
import json
def FromBase(digits, b): #str converts to base 10 from base b
numerals='''0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*()_-+={[}]|:;"',<.>/?`~\\ \x01\x02\x03\x04\x05\x06\x07'''
D=[]
for d in range(0,len(digits)):
D.append(numerals.index(digits[d]))
s=0
D=D[::-1]
for x in range(0,len(D)):
s+=D[x]*(b**x)
return(str(s))
def ToBase(digits,b): #str converts from base 10 to base b
numerals='''0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*()_-+={[}]|:;"',<.>/?`~\\ \x01\x02\x03\x04\x05\x06\x07'''
d=int(digits)
D=''
B=b
while(B<=d):
B*=b
B//=b
while(B>=1):
D+=numerals[d//B]
d-=((d//B)*B)
B//=b
return(D)
scale_factor=40
K=open('1.txt', 'r').read()
K=FromBase(K,95)
size=[int(K[-6:][:-3])//scale_factor,int(K[-6:][-3:])//scale_factor]
K=K[:-6]
K=ToBase(K,2)
K=K[1:]
a=[]
bsize=4
for x in range(0,len(K),bsize*3):
Y=''
for y in range(0,bsize*3):
Y+=K[x+y]
y=[int(Y[0:bsize]+'0'*(9-bsize)),int(Y[bsize:bsize*2]+'0'*(9-bsize)),int(Y[bsize*2:bsize*3]+'0'*(9-bsize))]
y[0]=int(FromBase(str(y[0]),2))
y[1]=int(FromBase(str(y[1]),2))
y[2]=int(FromBase(str(y[2]),2))
a.append(tuple(y))
im=Image.new('RGB',size,'black')
im.putdata(a[:size[0]*size[1]])
im=im.resize((int(size[0]*scale_factor),int(size[1]*scale_factor)), Image.ANTIALIAS)
im.save('pic.png')
```
# The Scream
[![Scream1](https://i.stack.imgur.com/gwXiH.png)](https://i.stack.imgur.com/gwXiH.png)
[![Scream2](https://i.stack.imgur.com/oX3Tx.png)](https://i.stack.imgur.com/oX3Tx.png)
```
hqgyXKInZo9-|A20A*53ljh[WFUYu\;eaf_&Y}V/@10zPkh5]6K!Ur:BDl'T/ZU+`xA4'\}z|8@AY/5<cw /8hQq[dR1S 2B~aC|4Ax"d,nX`!_Yyk8mv6Oo$+k>_L2HNN.#baA
```
# Mona Lisa
[![Mona Lisa 1](https://i.stack.imgur.com/aeWED.png)](https://i.stack.imgur.com/aeWED.png)
[![Mona Lisa 2](https://i.stack.imgur.com/AvHOt.png)](https://i.stack.imgur.com/AvHOt.png)
```
f4*_!/J7L?,Nd\#q$[f}Z;'NB[vW%H<%#rL_v4l_K_ >gyLMKf; q9]T8r51it$/e~J{ul+9<*nX0!8-eJVB86gh|:4lsCumY4^y,c%e(e3>sv(.y>S8Ve.tu<v}Ww=AOLrWuQ)
```
# Spheres
[![Spheres 1](https://i.stack.imgur.com/3wwc4.png)](https://i.stack.imgur.com/3wwc4.png)
[![Spheres 2](https://i.stack.imgur.com/MeWQD.png)](https://i.stack.imgur.com/MeWQD.png)
```
})|VF/h2i\(D?Vgl4LF^0+zt$d}<M7E5pTA+=Hr}{VxNs m7Y~\NLc3Q"-<|;sSPyvB[?-B6~/ZHaveyH%|%xGi[Vd*SPJ>9)MKDOsz#zNS4$v?qM'XVe6z\
```
] |
[Question]
[
Many of you may have interacted with people from Russia on the internet at some point, and a subset of you may have noticed the slightly odd method they have of expressing themselves.
e.g. `удали игру нуб)))`
where the `)))` are added for emphasis on the previous statement, I have been working on a theory that the ratio of `)`'s to the rest of the string is directly proportional to the amount of implied emphasis, however I oftentimes find it difficult to compute the ratio on the fly, as I am also trying to cope with a slew of abuse, so I would like the shortest possible code to help me calculate what the resulting string should be, for a value of enthusiasm between 0 and 500%, given the original, unenthusiastic string, this will aid my research greatly as I will not have to type out bulky scripts every time I wish to test my hypothesis.
So, the challenge:
write a full program or function, which, provided two arguments, a string of unknown length, and a number, in either integer format (between 0 and 500) or in decimal format (between 0 and 5, with 2 points of accuracy) will
* return/display the original string, suffixed with a number of `)`'s
* the number will be the calculated as a ratio of the input number to the string length.
* so if the number 200, or 2.00 was provided, 200% of the string must be suffixed as `)`'s
* the number of brackets rounded to in decimal situations does not matter.
* script is required to support Printable ASCII characters.
* only has to support one input number format, of your choice.
Examples:
```
"codegolf" 125 = codegolf))))))))))
"codegolf" 75 = codegolf))))))
"noob team omg" 0.5 = noob team omg))))))
"hi!" 4.99 = hi!)))))))))))))))
```
Example code (PowerShell) (with decimal input):
```
Function Get-RussianString ([string]$InputStr,[decimal]$Ratio){
$StrLen = $InputStr.Length
$SuffixCount = $StrLen * $Ratio
$Suffix = [string]::New(")",$SuffixCount)
return $InputStr + $Suffix
}
Get-RussianString "codegolf" 0.5
codegolf))))
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest code wins!
[Answer]
# Perl 6, 21 bytes
```
{$^a~")"x$^b*$a.comb}
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ȮL×Ċ”)x
```
**[Try it online!](https://tio.run/nexus/jelly#@39inc/h6Ue6HjXM1az4//9/RqbifxM9S0sA "Jelly – TIO Nexus")**
Uses the decimal format.
### How?
```
ȮL×Ċ”)x - Main link: string, decimal
Ȯ - print string
L - length(string)
× - multiply by the decimal
Ċ - ceiling (since rounding method is flexible)
”) - a ')' character
x - repeated that many times
- implicit print
```
[Answer]
## Common Lisp, ~~59~~ ~~52~~ 50
Parentheses? I am in.
```
(lambda(s n)(format()"~a~v@{)~}"s(*(length s)n)0))
```
### Details
```
(lambda(s n) ; two arguments (string and ratio)
(format () ; format as string
"~a~v@{)~}" ; control string (see below)
s ; first argument (string)
(* (length s) n) ; second argument (number of parens)
0)) ; one more element, the value does not matter
```
### Format control string
* `~a` : pretty print argument (here the given string)
* `~v@{...~}` : iteration block, limited to V iteration, where V is taken as an argument, namely the `(* ...)` expression. The iteration is supposed to iterate over a list, but when you add the `@` modifier, the list is the remaining list of arguments to the format function. There must be at least one element in the iterated list (otherwise we exit, disregarding V). That is why there is an additional argument to format (0).
Since no element in the list is consumed by the format, the loop is infinite but fortunately, it is also bounded by V, a.k.a. the number of parentheses to be printed.
---
Edit: thanks to Michael Vehrs for pointing out that there is no need to round the numerical argument (the question allows to truncate/round however we want, so the default behavior works here).
[Answer]
# JavaScript ES6, 38 31 30 bytes
```
s=>n=>s+')'.repeat(s.length*n)
```
```
f=s=>n=>s+')'.repeat(s.length*n)
console.log(f("hi!")(4.99))
```
[Answer]
# [Python 2](https://docs.python.org/2/), 29 bytes
```
lambda s,p:s+len(s)*p/100*')'
```
**s** in the string, **p** is the percentage (integer).
[Try it online!](https://tio.run/nexus/python2#VcxBDoIwEEDRtZ5iXE0HJ7EYiYGEm7gp0mKTttNQ7l8VV27fT76DER41mDjNBgrnoZyDTapQky@t1g0SVifrN4FPoPAps10kOOT22hH/yf0HSWSCzZoIEhdk6PTOL39CvvU9DcdDXn3awKnPluob "Python 2 – TIO Nexus")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~9~~ 8 bytes
```
g*ï')×¹ì
```
[Try it online!](https://tio.run/nexus/05ab1e#@5@udXi9uubh6Yd2Hl7z/39yfkpqen5OGpeJngEA "05AB1E – TIO Nexus")
```
g* # Length, multiplied by emphasis.
ï')× # Covnerted to an integer, push that many parenthesis.
¹ì # Prepend original string.
```
Works for both integer and decimal, arguments order: `f(String, Double)`
[Answer]
# Python, 30 bytes
```
lambda s,r:s+')'*int(len(s)*r)
```
Uses the decimal input.
[Try it online!](https://tio.run/nexus/python3#S1OwVYj5n5OYm5SSqFCsU2RVrK2uqa6VmVeikZOap1GsqVWk@b@gCMRP01BKzk9JTc/PSVPSUTDUMzLV1OTCJmWgZ44ilZefn6RQkpqYq5Cfmw6WR5HOyFQECproWVpqav4HAA "Python 3 – TIO Nexus")
[Answer]
# Pyth, 8 bytes
```
*\)s*lpz
```
[Online Test!](http://pyth.herokuapp.com/?code=%2a%5C%29s%2alpz&input=0.5%0Anoob+team+omg&debug=0) Takes the excitement ratio first, then the string to be enthused about.
Explanation:
```
pz print out the enthused string
l ... and get its length
*...Q multiply that by the ratio
s floor to get an integer, let's call this S
\) single-character string ")"
* ")" S multiply that integer by the string, which gives a string of )s of length S.
implicitly print that string of S )s.
```
[Answer]
# [PowerShell](https://github.com/PowerShell/PowerShell), 33 bytes
```
$a,$b=$args;$a+')'*($b*$a.Length)
```
[Try it online!](https://tio.run/nexus/powershell#@6@SqKOSZKuSWJRebK2SqK2uqa6loZKkpZKo55Oal16Sofn///@MTMX/JnqWlgA "PowerShell – TIO Nexus")
Supports decimal format.
[Answer]
# R, ~~62~~ ~~46~~ 42 bytes
Anonymous function that takes string `a` and decimal `n`, prints output to stdout.
```
pryr::f(cat(a,rep(")",n*nchar(a)),sep=""))
```
[Answer]
# Pyth, 9 bytes
```
*s*lpzE")
```
Takes two lines of input: string and ratio (decimal).
[Try it on pyth.herokuapp.com](https://pyth.herokuapp.com/?code=%2as%2alpzE%22%29&input=%22hi%22%0A1.5&test_suite=1&test_suite_input=codegolf%0A1.25%0Acodegolf%0A0.75%0Anoob+team+omg%0A0.5%0Ahi%21%0A4.99&debug=1&input_size=2)
### Explanation
`A` denotes a function's first argument, `B` its second argument.
```
*s*lpzE")
pz # print the input string
lAA # take the length of the printed string
E # read the next line of input (the emphasis ratio)
*AAAB # multiply the length by the ratio
sAAAAA # floor the result
*AAAAAA") # repeat ")" n times
# implicit print
```
[Answer]
# TI-Basic, 33 bytes
Takes decimal input.
```
Prompt Str1,A
")
For(I,0,9
Ans+Ans
End
Str1+sub(Ans,1,AI
```
[Answer]
# Perl 5, 29 bytes
```
sub{($_=pop).')'x(y///c*pop)}
```
(Number is first arg, string is second.)
[Try it online!](https://tio.run/nexus/perl#Ky1OVSguKcpMLrHmKgWyyxOL8jLz0outubhyKxVU0hRs/xeXJlVrqMTbFuQXaOqpa6pXaFTq6@sna4H4tf@BCguKMvNKgGp17TQM9YxMdRTUDY2MTdQ1dRSUYvKUrP8DAA "Perl – TIO Nexus")
[Answer]
## [CJam](https://sourceforge.net/p/cjam), 9 bytes
```
l_,ld*')*
```
[Try it online!](https://tio.run/nexus/cjam#@58Tr5OToqWuqfX/f0BRfnpRYm5uZl66QkBpVVVOarFCYl6KgnN@SqqCe35OGpehnpEpAA "CJam – TIO Nexus")
Input string on the first line, emphasis ratio in range 0 to 5 on the second.
### Explanation
```
l e# Read input string.
_, e# Duplicate, get length.
ld e# Read emphasis ratio.
* e# Multiply by length.
')* e# Get that many parentheses.
```
[Answer]
# MATL, ~~11~~ ~~10~~ 8 bytes
```
yn*:"41h
```
This solution uses the decimal form of the second input
[**Try it online!**](https://tio.run/nexus/matl#@1@Zp2WlZGKY8f@/enJ@Smp6fk6aOpehnpEpAA)
**Explanation**
```
% Implicitly grab first input as a string
% Implicitly grab the second input as a number
y % Make a copy of the first input
n % Compute the length of the string
* % Multiply the decimal by the length to determine the # of )'s (N)
: % Create the array [1...N]
" % For each element in this array
41 % Push 41 to the stack (ACSII for ")")
h % Horizontally concatenate this with the current string
% Implicit end of for loop and display
```
[Answer]
# sB~, 17 bytes
```
i\,N?\;')'*(N*l(\
```
Explained:
```
i\,N input a string and a number
?\; print the string
')'* also print ) multiplied by...
(N*l(\ the number times the string length.
```
Parentheses are closed automatically
Here's the output of the compiler, if you're interested:
```
INPUT S$ ,N? S$ ;")"*(N* LEN( S$ ))
```
This version of the compiler was written on 1/27/2017 at 11:12 pm, which might have been a few minutes after this question was posted.
So here's a version which works on the oldest version of the compiler, written an hour earlier: `iS$,N?S$;')'*(N*l(S$))` (22 bytes)
[Answer]
# PostgreSQL, 102 bytes
```
create function q(text,int)returns text as $$select rpad($1,(100+$2)*length($1)/100,')')$$language sql
```
### Details
Uses the integer input format.
This simply right-pads the input string with parens out to the target length.
```
create function q(text,int)
returns text as $$
select rpad($1, -- Pad the string input
(100 + $2) * -- to 100 + int input % ...
length($1) / 100, -- ...of the input string
')') -- with ) characters
$$ language sql
```
Called with
```
select q('codegolf', 125), q('codegolf', 75);
select q('noob team omg', 50), q('hi!', 499);
```
[Answer]
# [Bash](https://www.gnu.org/software/bash/) + coreutils, 45 bytes
```
echo $1`seq -s\) $[${#1}*$2/100+1]|tr -cd \)`
```
[Try it online!](https://tio.run/nexus/bash#@5@anJGvoGKYUJxaqKBbHKOpoBKtUq1sWKulYqRvaGCgbRhbU1KkoJucohCjmfD////k/JTU9PyctP/mpgA "Bash – TIO Nexus")
Integer input.
[Answer]
# Groovy, 27 bytes
Straightforward solution
```
{s,r->s+')'*(s.length()*r)}
```
Test program :
```
def f = {s,r->s+')'*(s.length()*r)}
println f("hi!", 4.99)
println f("noob team omg", 0.5)
```
[Answer]
# Rebol, 39 bytes
```
func[a b][append/dup a")"b * length? a]
```
[Answer]
# Clojure, 40 bytes
Quite boring solution :
```
#(reduce str %(repeat(*(count %)%2)")"))
```
Just reduces `str` function on a list of closing parentheses with a string as initial parameter.
See it online : <https://ideone.com/5jEgWS>
Not-so-boring solution (64 bytes) :
```
#(.replace(str(nth(iterate list(symbol %))(*(count %)%2)))"(""")
```
Converts input string to a symbol (to get rid of quotes) and repeatedly applies function `list` on it generating infinite sequence like this: `(a (a) ((a)) (((a))) ... )`. Takes `nth` element converts it to string and replaces all opening parentheses with nothing.
See it online : <https://ideone.com/C8JmaU>
[Answer]
# SimpleTemplate, 92 bytes
Takes the string as the first parameter and the "ratio" as the second.
The ratio is between 0 and 5, with 2 decimal places.
```
{@echoargv.0}{@callstrlen intoL argv.0}{@set*Y argv.1,L}{@callstr_repeat intoO")",Y}{@echoO}
```
As you can see, it is non-optimal.
The 2 `{echo}` there could be reduced to 1.
Due to a bug in the compiler, this code can't be reduced much further.
---
**Ungolfed:**
```
{@echo argv.0}
{@call strlen into length argv.0}
{@set* ratio argv.1, length}
{@call str_repeat into parenthesis ")", ratio}
{@echo parenthesis}
```
---
If no bug existed, the code would look like this, 86 bytes:
```
{@callstrlen intoL argv.0}{@set*Y argv.1,L}{@callstr_repeat intoO")",Y}{@echoargv.0,O}
```
[Answer]
## [C# Interactive,](http://csharppad.com/gist/67f46912a600cfecf2e99e537cdc913d) ~~77~~ 67 bytes
```
string r(string s,int p)=>s+new string(')',(int)(s.Length*p/100d));
```
C# interactive is sweet.
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 7 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
é┴eó¡µf
```
[Run and debug it](https://staxlang.xyz/#p=82c165a2ade666&i=%22codegolf%22+1.25%0A%22codegolf%22+0.75%0A%22noob+team+omg%22+0.5%0A%22hi%21%22+4.99&a=1&m=2)
[Answer]
# [International Phonetic Esoteric Language](https://github.com/bigyihsuan/International-Phonetic-Esoteric-Language), 24 bytes
A reimplementation of the old answer into the new specification. Input is as a positive integer first, then the string.
```
ɪ{100}viħɖf0ɑ")"x1esøɒʕo
```
Explanation:
```
ɪ{100}viħɖf0ɑ")"x1esøɒʕo
ɪ (push input int)
{100} (push 100)
v (divide int//100)
iħ (push input str, push len)
ɖ (rotate top 3 clockwise)
f (multiply int//100 * len)
0 (push 0)
ɑ (begin loop, from 0 to int//100 * len)
")" (push ")")
x (concat)
1esø (increment index)
ɒ (end loop)
ʕ (list to str)
o (print)
```
---
# [International Phonetic Esoteric Language](https://github.com/bigyihsuan/International-Phonetic-Esoteric-Language), 18 bytes (WIP language) (OLD)
I discovered some bugs in my interpreter because of this challenge. Takes input as `string` then `integer`.
```
iɢ291tʃɪðθœ<)>ɲqɶo
```
No TIO interpreter yet, but is runnable by cloning the repository above, and calling `python3 main.py "code here"`.
```
iɢ291tʃɪðθœ<)>ɲqɶo
i ; push string input
ɢ ; peek, push string length
291tʃ ; push (1 + 9)^2
ɪ ; push number input
ðθ ; push [num / 100 * len]
œ ; start loop: pop, run ceil(n) times
<)> ; push string ")"
ɲ ; swap top 2 elements of the stack
q ; pop, pop, push concatenated strings
ɶ ; end loop
o ; output
```
Sample cases:
```
python3 main.py "iɢ291tʃɪðθœ<)>ɲqɶo"
codegolf
125
codegolf))))))))))
python3 main.py "iɢ291tʃɪðθœ<)>ɲqɶo"
iɢ291tʃɪðθœ<)>ɲqɶo
300
iɢ291tʃɪðθœ<)>ɲqɶo))))))))))))))))))))))))))))))))))))))))))))))))))))))
python3 main.py "iɢ291tʃɪðθœ<)>ɲqɶo"
less than 1.00
50
less than 1.00)))))))
```
[Answer]
## SmileBASIC, 29 bytes
```
INPUT S$,N?S$;")"*(LEN(S$)*N)
```
[Answer]
# [Gol><>](https://github.com/Sp3000/Golfish/wiki) (Golfish), 17 bytes
```
i:a=?v
R*Il~/Hr)`
```
[Try it here](https://golfish.herokuapp.com/?code=i%3Aa%3D%3Fv%0AR%2aIl%7e%2FHr%29%60&input=hi%21%0A4.99).
The top line reads characters (`i`) until it finds a newline (ASCII 10, `a`), then goes down (`v`).
Then we discard one character (the newline) with `~`, push the length of the stack (`l`), read a float (`I`), multiply the two, and repeatedly (`R`) push the character ")" that many times. Finally, reverse the stack (`r`), output it and halt (`H`).
[Answer]
# PHP, 50 bytes
```
<?=str_pad($s=$argv[1],strlen($s)*++$argv[2],")");
```
takes string and decimal number as command line arguments; cuts padding. Run with `-r`;
**breakdown**
```
<?= // print ...
str_pad( // pad
$s=$argv[1], // string=argument 1
strlen($s)*++$argv[2], // to string length*(1+argument 2)
")" // using ")" as padding string
);
```
[Answer]
# Ruby, 25 bytes
```
->(s,n){s+')'*(s.size*n)}
```
I'm using **lambdas**. The test program would be something like:
```
f=->(s,n){s+')'*(s.size*n)}
f.("codegolf", 1.5) # => "codegolf))))))))))))"
f.("hi!", 4.99) # => "hi!))))))))))))))"
```
[Answer]
# GNU AWK, 59 bytes
```
{t=sprintf("%"n*length(s)"s","");gsub(/ /,")",t);print s t}
```
Accepts arguments on command line (using the decimal form) like so:
```
: | awk -v s="codegolf" -v n=0.75 -f russianify.awk
```
Yes, AWK requires *something* to be attached to stdin, even if that something is 0 bytes returned by the no-op shell builtin. You could also use `echo | awk ...`, or really *anything* that doesn't contain a newline.
] |
[Question]
[
When playing Rock-Paper-Scissors-Lizard-Spock, your [robot reflexes](https://www.youtube.com/watch?v=Qb5UIPeFClM) let you see your opponent's throw before they make it. You just need to choose a throw that beats theirs, in as few bytes as possible of course.
There's always two winning throws, and either one will work.
[![RPSLS throws diagram](https://i.stack.imgur.com/ltfS9m.png)](https://i.stack.imgur.com/ltfS9m.png)
```
Input -> Possible outputs
------------------------------
Rock -> Spock or Paper
Spock -> Paper or Lizard
Paper -> Lizard or Scissors
Lizard -> Scissors or Rock
Scissors -> Rock or Spock
```
Take a string as input, and output one of the strings that beats it. Strings must be exactly as given, with capitalization. List of characters may substitute for strings.
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~36~~ 30 bytes
```
{<Spock Lizard Rock>[.comb%4]}
```
[Try it online!](https://tio.run/##NY2xDsIgFEV3vuItWh0ek3HSfoGDaUfjgEgNsQ0EulTjt@ODRxnIS86953oTxmOaFtgOcIb0PfXe6Tdc7EeFJ3R0tzep3fTYHO6/FNUCkpKDC/Ays4x@tPOuwWafchSvypuAvbYxuhCRLViUQuQE5Ict8ApZSkOUv6I6TWz1iPXIuKtFltYwO9cU0ZwSPMKQF4hw4w8 "Perl 6 – Try It Online")
Gets each output based on the length of the input modulo 4. I think this is probably the optimal strategy.
[Answer]
# [Perl 5](https://www.perl.org/) `-p`, 28 bytes
```
$_=/k/?Paper:/i/?Rock:Lizard
```
[Try it online!](https://tio.run/##K0gtyjH9/18l3lY/W98@ILEgtchKP1PfPig/OdvKJ7MqsSjl/38Qhyu4AESCVXBBJLiCkzOLi/OLiv/lF5Rk5ucV/9ctyAEA "Perl 5 – Try It Online")
Tried @JoKing's length mod 4 method, but this turned out to be even shorter.
[Answer]
# [PHP](https://php.net/), 39 bytes
Shorter `md5` variants by [Christoph](https://codegolf.stackexchange.com/users/29637/christoph) and [Benoit Esnard](https://codegolf.stackexchange.com/users/38454/benoit-esnard).
```
<?=[Lizard,Spock,Rock][md5(y.$argn)%3];
```
[Try it online!](https://tio.run/##K8go@P/fxt422iezKrEoRSe4ID85WycISMRG56aYalTqqSQWpedpqhrHWv9PTc7IV1CKyVOy/g9SwQVWzBWQWJBaxAXRzxWcnFlcnF9U/C@/oCQzP6/4v64bAA "PHP – Try It Online")
```
<?=[Spock,Rock,Lizard][md5($argn.m)%7];
```
[Try it online!](https://tio.run/##K8go@P/fxt42OrggPzlbJwhE@GRWJRalxEbnpphqqCQWpefp5Wqqmsda/09NzshXUIrJU7L@D1LIBdbDFZBYkFrEBdHEFZycWVycX1T8L7@gJDM/r/i/rhsA "PHP – Try It Online")
---
# [PHP](https://php.net/), 40 bytes
```
<?=[Rock,Spock,Lizard][md5($argn)[5]%3];
```
[Try it online!](https://tio.run/##K8go@P/fxt42Oig/OVsnuABE@mRWJRalxEbnpphqqCQWpedpRpvGqhrHWv9PTc7IV1CKyVOy/g9SzwVWzxWQWJBaxAXRxRWcnFlcnF9U/C@/oCQzP6/4v64bAA "PHP – Try It Online")
Takes sixth character of md5 of input, which gives unique number of `1` for "Rock" and "Scissors", unique number of `2` for "Spock" and "Paper" and unique number of `9` for "Lizard". A mod 3 on those numbers and we have `0` or `1` or `2` indexes.
```
| Input | MD5 | 6th char | %3 | Output |
|----------|----------------------------------|----------|----|--------|
| Rock | 4cfbb125e9878528bab91d12421134d8 | 1 | 1 | Spock |
| Spock | 5769c28299713c949cd59d5469e40ace | 2 | 2 | Lizard |
| Paper | d0a662a5235ecde30739fe50cf0de830 | 2 | 2 | Lizard |
| Lizard | 2f7569e00c4d97aef5f2c2b3a4d2213f | 9 | 0 | Rock |
| Scissors | 28204140cee6e34a9843b64e5a490b08 | 1 | 1 | Spock |
```
---
# [PHP](https://php.net/), 40 bytes
Alternative 40 bytes, port of [Jo King's answer](https://codegolf.stackexchange.com/a/195084).
```
<?=[Spock,Lizard,Rock][strlen($argn)%4];
```
[Try it online!](https://tio.run/##K8go@P/fxt42OrggPzlbxyezKrEoRScIyI6NLi4pyknN01BJLErP01Q1ibX@n5qcka@gFJOnZP0fpIQLrIkrILEgtYgLopUrODmzuDi/qPhffkFJZn5e8X9dNwA "PHP – Try It Online")
---
# [PHP](https://php.net/), 41 bytes
This is based on [79037662's answer](https://codegolf.stackexchange.com/a/195115).
```
<?=[Lizard,Rock,Paper][ord($argn[-1])%3];
```
[Try it online!](https://tio.run/##K8go@P/fxt422iezKrEoRScoPzlbJyCxILUoNjq/KEVDJbEoPS9a1zBWU9U41vp/anJGvoJSTJ6S9X@QSq7gAhAJVs8FMYErODmzuDi/qPhffkFJZn5e8X9dNwA "PHP – Try It Online")
---
# [PHP](https://php.net/) (7.4), 42 bytes
Uses fifth and sixth characters of input to get one of 0, 1 or 2.
```
fn($s)=>[Rock,Lizard,Paper][!$s[5]+!$s[4]]
```
[Try it online!](https://tio.run/##K8go@G9jX5BRwMWlkmb7Py1PQ6VY09YuOig/OVvHJ7MqsShFJyCxILUoNlpRpTjaNFYbRJnExv635uJKTc7IV1BJ01AHqVbXVNBTUIrJU7JGiAcX4JAAG4lNAmIlVrOSM4uL84uKEXL/AQ "PHP – Try It Online")
---
# [PHP](https://php.net/), 43 bytes
Uses [CRC32](https://www.php.net/manual/en/function.crc32.php) of input and mod to get 0, 1 or 2.
```
<?=[Rock,Lizard,Paper][crc32($argn)%866%3];
```
[Try it online!](https://tio.run/##K8go@P/fxt42Oig/OVvHJ7MqsShFJyCxILUoNjq5KNnYSEMlsSg9T1PVwsxM1TjW@n9qcka@glJMnpL1f5AWruACEAnWwQXRzhWcnFlcnF9U/C@/oCQzP6/4v64bAA "PHP – Try It Online")
---
# [PHP](https://php.net/), 43 bytes
Uses second to the last character of input ("Rock" and "Spock" = "c", "Paper" = "e", "Lizard" and "Scissors" = "r").
```
<?=[c=>Paper,e=>Lizard,r=>Rock][$argn[-2]];
```
[Try it online!](https://tio.run/##K8go@P/fxt42OtnWLiCxILVIJ9XWziezKrEoRafI1i4oPzk7NlolsSg9L1rXKDbW@n9qcka@glJMnpL1f5AkV3ABiARr5YLo4wpOziwuzi8q/pdfUJKZn1f8X9cNAA "PHP – Try It Online")
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 28 bytes
```
'Spock' 'Lizard' 'Rock'⊃⍨4|≢
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkG/9WDC/KTs9UV1H0yqxKLUoCMIBD/UVfzo94VJjWPOhf9TwMqfNTbB9HT1XxovfGjtolAXnCQM5AM8fAM/p8G1cYFZEAMBLECEgtSi8AsqOFg6eTM4uL8omJ1rke9c0GaFEBA104BrE8hv0gBrA0kCxGByIIFQbIQo0DSECGINEQUJA8zH6QCKgoxHioOUgOyFmwBTAwoHwS1HWwpAA "APL (Dyalog Unicode) – Try It Online")
Uses the simple strategy based on input length modulo 4 (idea from [Jo King's answer](https://codegolf.stackexchange.com/a/195084/78410)). `⎕IO←0`.
---
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 34 bytes
```
'Lizard' 'Rock' 'Paper'⊃⍨'Xbj'⍸2∘⊃
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///X90nsyqxKEVdQT0oPzkbSAUkFqQWqT/qan7Uu0I9IilL/VHvDqNHHTOAIv/THrVNeNTb96hvqqc/kH9ovfGjtolAXnCQM5AM8fAM/p8GNYgLyAgugLEghoJYUOvA0smZxcX5RcXqXI9654I0KYCArp0CWJ9CfpECWBtIFiICkQULgmQhRoGkIUIQaYgoSB5mPkgFVBRiPFQcpAZkLdgCmBhQPghqO9hSAA "APL (Dyalog Unicode) – Try It Online")
Uses the shortest choice for all cases. `⎕IO←1`.
### How it works
```
'Lizard' 'Rock' 'Paper'⊃⍨'Xbj'⍸2∘⊃
2∘⊃ Take the second character
'Xbj'⍸ Classify it by intervals:
'X'≤c<'b': 1
'b'≤c<'j': 2
'j'≤c : 3
...⊃⍨ Give the nth string
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~16~~ 14 bytes
```
Lị“ŀ¡ḋ¤:1KỌ»Ḳ¤
```
[Try it online!](https://tio.run/##y0rNyan8/9/n4e7uRw1zjjYcWvhwR/ehJVaG3g939xza/XDHpkNL/gNlgvKTs4FUQGJBahGQDk7OLC7OLyoGMn0yqxKLUkBiBWA1cw9tPbrncPujpjWR/wE "Jelly – Try It Online")
-2 bytes thanks to Jonathan Allan and Nick Kennedy both independently coming up with splitting on spaces instead of using a list literal.
A translation of Jo King's Perl 6 solution, using Jelly's compressed strings and modular indexing.
```
ị The element of
“ŀ¡ḋ¤:1KỌ» "Lizard Rock Spock"
Ḳ¤ split on spaces
ị at (1-based) index
L length of the input
“ŀ¡ḋ¤:1KỌ»Ḳ¤ mod 4.
```
[Answer]
# JavaScript, 40 bytes
```
s=>['Spock','Lizard','Rock'][s.length%4]
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNEts/ifZvu/2NYuWj24ID85W11H3SezKrEoBcgIAvFjo4v1clLz0ksyVE1i/6flF2kUpRaX5pQo5KcpRHNxpmlAlGnqgNkQM6CcgMSC1CIYB2oqTF1yZnFxflGxuiZXrKZCcn5ecX5Oql5OfjrUdM3/AA "JavaScript (V8) – Try It Online")
[Answer]
# [Runic Enchantments](https://github.com/Draco18s/RunicEnchantments/tree/Console), 42 bytes
```
il͍4%:0)9*?~"Spock"@1)9*?"Lizard"@"Rock"@
```
[Try it online!](https://tio.run/##KyrNy0z@/z8z52yviaqVgaalln2dUnBBfnK2koMhiKfkk1mVWJSi5KAUBBb8b5eYDWEaGDid7eUCcisrK5UCEgtSi1CEQKJQvWjCEDmIJdikYAqSM4uL84uKIWr@AwA "Runic Enchantments – Try It Online")
Footer runs all five input possibilities (the `y` sequences make them print in the correct order, no I'm not sure why the last one needed so many) and presets the stack with an input value (the `i`nput command then reads no input) and a newline. Remove the footer to use input instead.
[Answer]
# [Python 3](https://docs.python.org/3/), 44 bytes
```
lambda s:["Spock","Lizard","Rock"][len(s)%4]
```
[Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUaHYKlopuCA/OVtJR8knsyqxKAXICALxY6NzUvM0ijVVTWL/p@UXKRQrZOYpREPkdBRgmhSUAhILUotADJh2oFxyZnFxflGxUqwVF2dBUWZeiUaxjoK6rp26jkIa0EjN/wA "Python 3 – Try It Online")
Uses the input-length-modulo-4 strategy in [Jo King's answer](https://codegolf.stackexchange.com/a/195084/78410).
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 51 49 bytes
Thanks to Unrelated String for the suggestion.
The second byte of the string has sufficient uniqueness that I can take its two least-significant bits and use them to then index into a string (with the longest-length result at the end if I rotate the result, fortunately!) The separator between the strings should be a literal `NUL` character, but I put a space in between them below so that you can see the gaps.
```
f(char*s){s="Spock Paper Scissors"+(s[1]-3)%4*6;}
```
[Try it online!](https://tio.run/##NY7LCsIwFERd5ysuFSFJrSiKm6hf4ELsUlyE21dQm5KkLiz99mtbcTczHIaDSYlIVHCstJNedP4YpY3Fx@yim9zNUjTeW@ejmPvb5p5sxWIn96qnuanx2WY5HHzIjF1VJ8ZMHeClTc3HoF2JSxhvQcqhvAV0DKCwjiuQcTxOSkDTBs8L/iOEGgiXh9bVsFasJ7oOKjQJ0SREZ/PRLqO/1xc "C (gcc) – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), ~~73~~ 69 bytes
```
lambda i:l[l.index(i)-1]
l="Rock Lizard Spock Scissors Paper".split()
```
[Try it online!](https://tio.run/##TY69DsIgFIX3PsUNE8TYREcTfAIH047qgKWNNyIQYFBfHiOgMJ7z5fzYV7gZvY0LP0clHlcpAHfqpHrUcn5SZOvNpVOcDGa6wwHfwkkY7VeME3pvnIejsLMjvbcKA2XROtQBcoDvgcAKFpokYV2BuaHSpCtOjQ3OC39cblSejab@d61ZKBZh8QM "Python 2 – Try It Online")
Since there are already plenty of ports of [@JoKing's excellent answer](https://codegolf.stackexchange.com/a/195084/56555), here is a different way of doing it.
[Answer]
# [Haskell](https://www.haskell.org/), 43 bytes
```
(k!!).length
k="Spock":"Lizard":"Rock":"":k
```
[Try it online!](https://tio.run/##JYwxCsMwDEX3nkIRHdqhPUDAN@hQmrWLcOzE2LGFFCj08FVDMv3/4L8/k@ZQikX3tkvuuuu9hDqt8yk7HLj5jD0@0pdk3MrrYOyzLZQqOGBJdYUzLMQQt/w0GRX2Iew6PImDwHEBg0@qTRTt52OhSe3mmf8 "Haskell – Try It Online")
The mod-4 approach. Longer approaches:
```
f t|t<"Q"="Scissors"|t<"Sd"="Spock"|1<2="Paper" (47)
f.last;f 'k'="Paper";f 'r'="Lizard";f _="Rock" (46)
(["Spock","Lizard","Rock"]!!).(`mod`4).length (45)
(words"Spock Lizard Rock"!!).(`mod`4).length (44)
(cycle["Spock","Lizard","Rock",""]!!).length (44)
(cycle(words"Spock Lizard Rock .")!!).length (44)
```
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), ~~30~~ 27 bytes
```
'R(`R
Sp
'i(K`Rock
K`Lizard
```
[Try it online!](https://tio.run/##K0otycxLNPyvquGe8F89SCMhiCu4gEs9U8M7ISg/OZvLO8EnsyqxKOX/fzA3uABEBiQWpBZxQSS4gpMzi4vzi4oB "Retina – Try It Online") Link includes all possible test cases. @BusinessCat's answer works perfectly well in Retina 0.8.2 but for Retina 1 we can do a little better by using a conditional stage. Explanation:
```
'R(`
```
If the input contains `R`...
```
R
Sp
```
... then replace the `R` with `Sp`, thus turning `Rock` into `Spock`...
```
'i(
```
... otherwise if the input contains `i`...
```
K`Rock
```
... then overwrite it with the string `Rock`, which beats `Lizard` and `Scissors`...
```
K`Lizard
```
... otherwise overwrite the input with `Lizard`, which beats `Spock` and `Paper`.
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~42~~ 36 bytes
```
->c{%w(Spock Lizard Rock)[c.size%4]}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y65WrVcI7ggPzlbwSezKrEoRSEIyNaMTtYrzqxKVTWJrf1fUFpSrJGml5yYk6OhBJJV0tTkQhEMSCxILcIQDU7OLC7OLyrGkIBYhKm@AGL2fwA "Ruby – Try It Online")
---
# [Ruby](https://www.ruby-lang.org/), ~~43~~ 39 bytes
```
->c{%w(Lizard Rock Paper)[c[-1].ord%3]}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y65WrVcwyezKrEoRSEoPzlbISCxILVIMzo5WtcwVi@/KEXVOLb2f0FpSbFGml5yYk6OhhJImZKmJheKIFgbhmhwcmZxcX5RMYYExEZM9QUQs/8DAA "Ruby – Try It Online")
The second one is an alternative I found to Jo's method, using the ASCII value of the last character, but alas is 3 bytes longer in Ruby.
It is conceivable that my method is better in some language where finding the ASCII value of the last character is shorter than finding the string's length, but I don't know of any.
EDIT: Saved several bytes thanks to @IMP1
[Answer]
# [Shakespeare Programming Language](https://github.com/TryItOnline/spl), 1359 bytes
(Whitespace added for readability)
```
R.Ajax,.Puck,.Act I:.Scene I:.[Enter Ajax and Puck]Ajax:
Open mind.Open mind.You is the remainder of the quotient betweenyou a big big cat.
Be you nicer a cat?If solet usScene V.
Be you nicer I?If solet usScene X.
You is twice twice twice twice the sum ofa big big cat a cat.Speak thy.You is the sum ofthe sum ofyou a big big big big cat a cat.Speak thy.You is the sum ofthe sum ofyou a big big big big cat a pig.Speak thy.You is the sum ofthe square oftwice the sum ofa big big cat a cat a cat.Speak thy.You is the sum ofyou the sum ofa cat twice twice the sum ofa big cat a cat.Let usScene L.
Scene V:.Ajax:
You is the sum ofa big cat the square ofthe sum ofa big big big cat a cat.Speak thy.You is twice twice twice twice the sum ofa big big big cat a pig.Speak thy.You is the sum ofyou a pig.Speak thy.You is the sum ofyou twice twice the sum ofa big pig a pig.Speak thy.You is the sum ofyou a big big big cat.Let usScene L.
Scene X:.Ajax:
You is the sum ofa big cat the square ofthe sum ofa big big big cat a cat.Speak thy.You is the sum ofyou a big big big big cat.Speak thy.You is the sum ofyou twice the sum ofa big cat a cat.Speak thy.You is the sum ofyou twice the sum ofa big big cat a cat.Remember you.Speak thy.Speak thy.You is the sum ofyou a big big pig.Speak thy.You is the sum ofyou the sum ofa big cat a cat.Speak thy.Recall.
Scene L:.Ajax:Speak thy.
```
[Try it online!](https://tio.run/##vVPBboMwDP0Vf0CVD@AyddIOSEirqFR1mnYIqdtlhUAhUdevZw6gBVbWZJO2Aygx79nPz6ap8rZN2fKNvy/Yyojjgi2Fhjhia4EK7eH5QWmswUKAqx1Y1Iu9RY8VKiik2jF3eioNyAb0K0KNBacQcct9FziZUktUGjLUZ0R1ISyHTB66R3DN7hFsUElBLG5Dd/EemjJHDabpJW2mqPgasf1UcSbI3JvENKYgXZPyfUW2rpAfCXMZN9PD3Wmq/Q@SVPLgTXIyvEZ78Xfll2XFjFNY0i3TXNJk5H0yLM4m6pYquirjyNMWZsT7HP3BdIN97UcSALpVkeihlb4InPVy@w9e@ncy0JBvt@RX9GmKFAssMvrpiTDKF9xNyFgD9KcoeJ4Pw0mG4bjPbbviFdYf "Shakespeare Programming Language – Try It Online")
Explanation:
I get the second character of the input mod 4:
* This is 0 when the input is `Spock`, at which point Puck is neither nicer than a cat nor nicer than Ajax. Then, Scene I prints `Paper`.
* This is 1 when the input is `Paper` or `Lizard`, at which point Puck is not nicer than a cat, but he is nicer than Ajax. Then, Scene X prints `Scissors`.
* This is 3 when the input is `Rock` or `Scissors`, at which point Puck is nicer than a cat. Then, Scene L prints `Spock`.
Possible improvements:
* Better math when printing to get between the letters, including switching characters and using `Recall` more
* Better modulus because some of the things are longer than others, and I could reuse the `ock`
* Possibly better ways to write the existing numbers. I actually am using a brute forcer that I wrote to do this, but it doesn’t yet account for getting between the letters (using ‘you’). GitHub link coming soon.
This was really fun and I love this language and I have no regrets.
[Answer]
# [V (vim)](https://github.com/DJMcMayhem/V), 28 bytes
```
2ORock
Lizard
SpockLÝkYHVGp
```
[Try it online!](https://tio.run/##K/v/38g/KD85m8snsyqxKIUruADIkfY5PDc70iPMveD//@DkzOLi/KJiAA "V (vim) – Try It Online")
Hexdump:
```
00000000: 324f 526f 636b 0d4c 697a 6172 640d 5370 2ORock.Lizard.Sp
00000010: 6f63 6b1b 4cdd 6b59 4856 4770 ock.L.kYHVGp
```
[Answer]
# [F# (.NET Core)](https://www.microsoft.com/net/core/platform), ~~53~~ ~~49~~ 46 bytes
```
["Spock";"Lizard";"Rock"].[String.length n%4]
```
[Try it online!](https://tio.run/##nVC9DoJADN55iobERAeJg5N/i3FjIDI4EIYLFLx4tKR3mujLI3C6ORg6td9fvrSyy4IFu4bLu0FIhGtRTcAtEqRP67AJAoMOKqBN6kRTDXvoIAvTlotbuA1j/VJS9st5uPMo86rIINXuCjRb5122O5GTZ8Ka3CEf8xqlCZTUD9gH0M@ACdq7cX1@BT5tZI5Mlg1GF9EOY00497rFT5@vNcGYqBZlivHzgCldC20ti/3H@2XPqMq5h1bdGw "F# (.NET Core) – Try It Online")
I am using the input-length-modulo-4 strategy from [Jo King's answer](https://codegolf.stackexchange.com/a/195084/78410), so please check his answer.
And I know it's not in competition but I wanted to try something new…
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 24 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
`Spock Lizd Rock`¸gUÊu4
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=YFNwb2NrIExpeodkIFJvY2tguGdVynU0&input=IlJvY2si)
```
"Spock Lizard Rock" //=>compressed
.q(S) // split on " "
.g(U.l().u(4)) // return element at index ( length of input % 4 )
```
Thanks to @Shaggy for the help
[Answer]
## [Python 3](https://docs.python.org/3/), ~~69~~ ~~64~~ ~~61~~ 57 bytes
```
lambda s:[["Scissors","Paper"]['k'in s],"Rock"]['i'in s]
```
Not as short as the mod 4 solution, but not a bad alternative.
[Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUaHYKjpaKTg5s7g4v6hYSUcpILEgtUgpNlo9Wz0zT6E4VkcpKD85GySQCRFQ@J@WX6RQrADkREPkdBSUggugDIh2IMMnsyqxKAUsBzM81oqLs6AoM69Eo1hHQV3XTl1HIU2jWFPzPwA)
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 24 bytes
```
@c."Lzž›^ºéëEL”‡"\`lz
```
[Try it online!](https://tio.run/##ASsA1P9weXRo//9AYy4iTHoCwp4QwptewrrDqcOrRUzClBXChyJcYGx6//9Sb2Nr "Pyth – Try It Online")
Port of Jo King's mod-4 answer. Without the compressed string, it's 2 bytes longer: `@c"Spock`Lizard`Rock`"\`lz`
[Answer]
# Excel, 49 bytes
Mod4 approach:
```
=CHOOSE(MOD(LEN(A1),4)+1,"Spock","Lizard","Rock")
```
---
Switching on last character: 57 bytes
```
=CHOOSE(MOD(CODE(RIGHT(A1)),3)+1,"Lizard","Rock","Paper")
```
[Answer]
# R, 52 bytes
```
function(x)c("Spock","Lizard","Rock")[nchar(x)%%4+1]
```
[Answer]
# [///](https://esolangs.org/wiki////), ~~81~~ 70 bytes
```
/~/\/\/.//.Sp/.~R/.~ock/Paper~Paper/Lizard~Lizard/Rock~Scissors/Rock/.
```
Because there is no other way to take input in ///, it goes after the `.` at the end of the code. For an input of `Spock`:
```
/~/\/\/.//.Sp/.~R/.~ock/Paper~Paper/Lizard~Lizard/Rock~Scissors/Rock/.Spock
```
[Try it online!](https://tio.run////##K85JLM5ILf7/X79OPwYI9fT19YIL9PXqgoA4PzlbPyCxILWoDkzq@2RWJRal1EEo/SCgdF1wcmZxcX5RMZinr/f/PwA "/// – Try It Online")
[Test suite](https://tio.run////##K85JLM5ILf7/X79OPwYI9fT19YIL9PXqgoA4PzlbPyCxILWoDkzq@2RWJRal1EEo/SCgdF1wcmZxcX5RMZinz8WlB6K5gEaAKbA2Lj2IBqAoVPH//wA "/// – Try It Online")
**Explanation:**
/// works by replacing strings with other strings, within the code.
The first chunk of code, `/~/\/\/./`, works as a macro replacing `~` with `//.`. After this, the code expands to:
```
/.Sp/.//.R/.//.ock/Paper//.Paper/Lizard//.Lizard/Rock//.Scissors/Rock/
```
`/.Sp/./` and `/.R/./` change `spock` and `rock` to `ock`, allowing me to just replace `ock` with `Paper`.
The rest of the cases are just explicitly handled.
The period before the input is to make sure that none of the code itself is changed, just the input.
[Answer]
# [Python 2](https://docs.python.org/2/), 50 bytes
```
lambda s:["Lizard","Rock","Paper"][cmp(s[-2],"e")]
```
[Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUaHYKlrJJ7MqsShFSUcpKD85G0gFJBakFinFRifnFmgUR@saxeoopSppxv4vKMrMK1EAq1KwtVNQUtBWSNOAaNLkgkoGF6DKgvkIabDRSNIQq@DSEJcgyUOdhjA@ObO4OL@oGNkGqJCS5n8A "Python 2 – Try It Online")
[Answer]
# K, 26 bytes
```
`Paper`Rock`Lizard@&/"ki"?
```
[Answer]
# [C# dotnet core](https://docs.microsoft.com/en-us/dotnet/core/), 47 bytes
```
h=>(new[]{"Spock","Lizard","Rock"})[h.Length%4]
```
[Try it online](https://dotnetfiddle.net/dIdzdW)
Uses the input-length-modulo-4 strategy in Jo King's answer.
[Answer]
# [Wren](https://github.com/munificent/wren), 47 bytes
```
Fn.new{|s|["Spock","Lizard","Rock"][s.count%4]}
```
[Try it online!](https://tio.run/##NY5BC4JAFITP@SseDwIl21PXOnbyEHkUD8u2wpK9lfc0KfW3byvhaWb4mGFGthTemqEZyMAZwpUU2XGaZa6w7Lx5Yo6F@2p@RHNfc12JMn6gfn@ql9B4TgUcQfWnOWw1wJvuLK9mG4jMOBHPgnUGU7IrP9Lbl@rYUR9nDoDHC0ZZ3yij2zaVLEuW8AM "Wren – Try It Online")
Uses the input-length-modulo-4 strategy in [Jo King's answer](https://codegolf.stackexchange.com/a/195084/78410).
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 16 bytes
```
”‰«†ÕâŸard”#I3öè
```
[Try it online!](https://tio.run/##yy9OTMpM/W/q9v9Rw9xHDRsOrX7UsODw1MOLju5ILEoBiil7Gh/ednjFf53/QfnJ2VzBBSAyILEgtYjLJ7MKqIYrODmzuDi/qBgA "05AB1E – Try It Online")
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~36~~ ~~33~~ 31 bytes
-3 thanks to Neil
```
R
s
.{6,}
Rock
.{5}
Lizard
s
Sp
```
[Try it online!](https://tio.run/##K0otycxL/P8/iKuYS6/aTKeWKyg/ORvINK3l8smsSixKAUoEF/z/H5ycWVycX1QMAA "Retina 0.8.2 – Try It Online")
[Answer]
## Batch, 87 bytes
```
@set/ps=
@for %%a in (Rock.d Rock.s Paper.k Lizard.r)do @if %%~xa==.%s:~-1% echo %%~na
```
Takes input on STDIN. Works by switching on the last character of the input, which saves a case.
] |
[Question]
[
Given a nonempty array of positive integers, "increment" it once as follows:
* If all the array elements are equal, append a `1` to the end of the array. For example:
```
[1] -> [1, 1]
[2] -> [2, 1]
[1, 1] -> [1, 1, 1]
[3, 3, 3, 3, 3] -> [3, 3, 3, 3, 3, 1]
```
* Else, increment the first element in the array that is the array's minimum value. For example:
```
[1, 2] -> [2, 2]
[2, 1] -> [2, 2]
[3, 1, 1] -> [3, 2, 1] -> [3, 2, 2] -> [3, 3, 2] -> [3, 3, 3]
[3, 4, 9, 3] -> [4, 4, 9, 3] -> [4, 4, 9, 4] -> [5, 4, 9, 4] -> [5, 5, 9, 4] -> ...
```
(Each `->` represents one increment, which is all your program needs to do.)
Output the resulting incremented array.
**The shortest code in bytes wins.**
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~8~~ 7 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
‘;ṀỤḢṬ+
```
[Try it online!](http://jelly.tryitonline.net/#code=4oCYO-G5gOG7pOG4ouG5rCs&input=&args=WzMsIDMsIDMsIDMsIDNd) or [verify all test cases](http://jelly.tryitonline.net/#code=4oCYO-G5gOG7pOG4ouG5rCsKxbzDh-KCrEvigqzigqxq4oKs4oCcIC0-IOKAnVk&input=&args=WzFdLCBbMl0sIFsxLCAxXSwgWzMsIDMsIDMsIDMsIDNdLCBbMSwgMl0sIFsyLCAxXSwgWzMsIDEsIDFdLCBbMywgMiwgMV0sIFszLCAyLCAyXSwgWzMsIDMsIDJdLCBbMywgNCwgOSwgM10sIFs0LCA0LCA5LCAzXSwgWzQsIDQsIDksIDRdLCBbNSwgNCwgOSwgNF0).
### How it works
```
‘;ṀỤḢṬ+ Main link. Argument: A
‘ Increment all elements of A.
Ṁ Yield the maximum of A.
; Concatenate both results. Note that the appended maximum will be the
minimum of the resulting array if and only if all elements of A are equal.
Ụ Grade up; yield the indices of the resulting array, sorted by their
corresponding values in that array.
Ḣ Head; extract the first index, which is the index of the first occurrence
of the minimum. For an array of equal elements, this will be the index
of the appended maximum.
Ṭ Untruth; for index i, yield an array of i-1 zeroes, followed by a 1.
+ Add this array to A, incrementing the minimum or appending a 1.
```
[Answer]
# Python 3, ~~62~~ ~~53~~ ~~51~~ 50 bytes
Function which modifies the list passed to it ([allowed by meta](http://meta.codegolf.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/4942#4942)).
```
def F(a):a+=1//len({*a})*[0];a[a.index(min(a))]+=1
```
[**Try on repl.it!**](https://repl.it/E9oy/2)
-9 bytes thanks to Lynn for spotting that, because the array will be of positive integers, I can append '0' to the end of the array and have that incremented.
Special thanks to mbomb007 for golfing `len(set(a))` to `len({*a})`, and Dennis for the floordiv trick!
[Answer]
# Mathematica, ~~70~~ ~~57~~ 55 bytes
*Virtually all of the improvement is due to Martin Ender, who kicks my ass at pattern matching approaches! Also JHM came up with essentially the same solution at essentially the same time.* (byte count uses ASCII encoding)
```
±{p:x_ ..}:={p,1};±{x___,y_,z___}/;y≤x~Min~z:={x,y+1,z}
```
Defines a function `±` taking one list argument. If that list argument contains some number of copies of the same element (detected by `x_..` and named `p`), then output the list with a `1` appended. Otherwise, if that list argument has a special element `y` (with `x` being the zero or more elements before `y`, and `z` being the zero or more elements after `y`) which is at most the minimum of the other elements, then output the list with that `y` incremented. Any instance of the minimum element of the list will be matched by `y`, but fortunately Mathematica chooses the first one to act upon.
[Answer]
# JavaScript (ES6), 61 bytes
```
a=>new Set(a).size>1?++a[a.indexOf(Math.min(...a))]:a.push(1)
```
Outputs by [modifying its argument](https://codegolf.meta.stackexchange.com/a/4942/42545). I can't find a way to determine whether an array has only one unique item in less that 17 bytes, but suggestions are welcome.
### Test snippet
```
f=a=>new Set(a).size>1?++a[a.indexOf(Math.min(...a))]:a.push(1)
g=a=>0 in a?console.log("Input:",`[${a}]`,"Output:",`[${f(a),a}]`):console.log("Invalid input")
g([1])
g([2])
g([1,1])
g([1,2,2,3])
g([2,2,2,3])
g([3,2,2,3])
g([3,3,2,3])
g([3,3,3,3])
g([3,3,3,3,1])
```
```
<input id=I value="1,2,2,3"><button onclick="g(I.value.match(/\d+/g)||[])">Run</button>
```
### Other attempts
Here are a few alternate ways of deciding whether the array has more than one unique input:
```
a=>a.some(x=>x-a[0])?++a[a.indexOf(Math.min(...a))]:a.push(1)
a=>a.some(x=>x-m,m=Math.min(...a))?++a[a.indexOf(m)]:a.push(1)
```
Both of the `some`s can be replaced with `find` as well. `.sort` would be shorter for finding the minimum, if the default sort wasn't lexicographical (why, JS, why?):
```
a=>new Set(a).size>1?++a[a.indexOf(a.sort()[0])]:a.push(1)
// Instead we have to do:
a=>new Set(a).size>1?++a[a.indexOf(a.sort((x,y)=>x-y)[0])]:a.push(1)
```
I tried recursion to find the minimum, but it turned out way longer:
```
f=(a,n=1,q=a.indexOf(n))=>~q?a.some(x=>x-n)?++a[q]:a.push(1):f(a,n+1)
```
And here's a string-based solution which seemed like a good idea at first: (input is given in array format in a string, e.g. `"[1,2,3]"`)
```
a=>a.replace(m=/(\d+),(?!\1)/.test(a)?Math.min(...eval(a)):']',+m+1||",1]")
```
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), ~~21~~ ~~20~~ 16 bytes
Saved 4 bytes thanks to *Adnan*.
```
DÙgi0¸«}ÐWksgÝQ+
```
[Try it online!](http://05ab1e.tryitonline.net/#code=RMOZZ2kwwrjCq33DkFdrc2fDnVEr&input=WzQsMyw5LDNd)
**Explanation**
```
# input = [3,2,1] used as example
D # duplicate input
Ùgi # if all elements are equal
0¸«} # append 0
Ð # triplicate list
# STACK: [3,2,1], [3,2,1], [3,2,1]
Wk # index of minimum element
# STACK: [3,2,1], [3,2,1], 2
s # swap top 2 elements of stack
# STACK: [3,2,1], 2, [3,2,1]
g # length of list
# STACK: [3,2,1], 2, 3
Ý # range [0 ... length]
# STACK: [3,2,1], 2, [0,1,2,3]
Q # equal
# STACK: [3,2,1], [0,0,1,0]
+ # add
# OUTPUT: [3,2,2]
```
[Answer]
# C++14, ~~178 176 174 155 142~~ 135 bytes
# submission
```
#include<list>
#include<algorithm>
[](auto&l){auto e=end(l),b=begin(l);l.size()^count(b,e,*b)?++*min_element(b,e):(l.push_back(1),0);};
```
# invocation
```
std::list<int> s = {4, 4, 9, 4};
//invoke like this
auto i = [](auto&l){auto e=end(l),b=begin(l);l.size()^count(b,e,*b)?++*min_element(b,e):(l.push_back(1),0);};
i(s);
//or like that
[](auto&l){auto e=end(l),b=begin(l);l.size()^count(b,e,*b)?++*min_element(b,e):(l.push_back(1),0);}(s);
```
## ungolfed
```
#include <list>
#include <algorithm>
#include <iostream>
using namespace std;
void i(list<int>& l) {
auto e = l.end(), b = l.begin();
if (l.size() == count(b, e, l.front())) {
l.push_back(1);
} else {
++*min_element(b, e);
}
}
int main() {
list<int> s = {4, 4, 9, 4};
//invoke like this
i(s);
for (auto o:s)
std::cout << o << ' ';
std::cout << std::endl;
}
```
This is my first time playing golf, help is appreciated.
EDIT: forgot to mention you have to compile it with at least ~~`-std=c++11`~~ `-std=c++14`
EDIT2: I realized i can leave out the space in the includes `#include <list>`
EDIT3: saved two more bytes by replacing `l.begin()` by `begin(l)`
EDIT4: saved another 19(!) bytes thanks to @Quentin (see his comment)
EDIT5: Quentin shaved off 13 more bytes, thanks!
EDIT6: as TuukkaX pointed out, unnamed lambdas/functions suffice so i removed the `auto i=` in the bytecount
[Answer]
## Scratch, ~~25~~ 34 blocks + ~~7~~ 6 bytes
[![Program](https://i.stack.imgur.com/vgMtN.png)](https://i.stack.imgur.com/vgMtN.png)
Takes input as a predefined array of integers. Note that arrays are 1-indexed in Scratch.
In Python, this would look like: (Note that unlike Scratch, Python is 0-indexed)
```
lowval = 0
hival = 0
n = 1
for i in range(len(input)):
if(input[i] < input[lowval]):
lowval = i
if(input[i] > input[hival]):
hival = i
# No increment statement needed because python.
if(lowval == hival):
input.append(1)
else:
input[lowval] += 1
print(input)
```
[Answer]
## J, ~~25~~ 22 bytes
```
(+~:*[=<./)@,0#~1=#@~.
```
Evaluates to an anonymous verb.
[Try It Online!](https://tio.run/nexus/j#@5@mYGuloKFdZ6UVbWujp6/poGOgXGdoq@xQp/c/NTkjXyFNQUfBkAvONIIxDRGixjCIkIMrM0JWhqLHRMESocMEG9cExjWFcP8DAA "J – TIO Nexus")
## Explanation
```
(+~:*[=<./)@,0#~1=#@~. Input is y.
#@ Is the length of
~. deduplicated y
1= equal to 1?
,0#~ Append that many 0s to y (one or none).
( )@ Call the result z and apply this verb to it:
= take the bit array of equality
[ between z
<./ and its minimum element,
* multiply that element-wise by
~: the bit array of first occurrences in z
+ and add the result to z.
```
[Answer]
# C#, ~~123~~ ~~121~~ ~~120~~ ~~79~~ 77 bytes
```
using System.Linq;l=>{if(l.All(o=>o==l[0]))l.Add(0);l[l.IndexOf(l.Min())]++;}
```
Modifies the argument passed to the function.
Thanks to [Cyoce](https://codegolf.stackexchange.com/users/41042/cyoce) for saving 3 bytes! -> `!Any` to `All`, `+=1` to `++`.
Thanks to [TheLethalCoder](https://codegolf.stackexchange.com/users/38550/thelethalcoder) for saving a whopping 43 bytes! -> Removed method signature code.
Removed parenthesis around the parameter list.
[Answer]
# [R](https://www.r-project.org/), ~~72 66~~ 65 bytes
```
"if"(any((x=scan())-x[1]),"[<-"(x,u<-which.min(x),1+x[u]),c(x,1))
```
[Try it online!](https://tio.run/##K/r/XykzTUkjMa9SQ6PCtjg5MU9DU1O3ItowVlNHKdpGV0mjQqfURrc8IzM5Qy83M0@jQlPHULsiuhQonwyUM9TU/G@kYKRg/B8A "R – Try It Online")
Increment is done using `which.min` which returns the first match. `"[<-"` allows to replace the value and returns the modified vector in one function call.
-7 bytes thanks to Giuseppe!
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 48 bytes
```
f←{1≥≢∪⍵:⍵,1⋄1+@(⊃⍋⍵)⊢⍵}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24Rqw0edSx91LnrUsepR71YrINYxfNTdYqjtoPGoq/lRbzdQRPNR1yIgVQvUoWDIBcRQ0ghIGikYQ9gKxgomYD6MZQyWAZIKhgA "APL (Dyalog Unicode) – Try It Online")
Alternate versions of `1+@(⊃⍋⍵)⊢⍵`: `⍵+(⍳≢⍵)=⊃⍋⍵`, `⊢+⍳∘≢=⊃∘⍋`. -2 thanks to @Adam and @Razetime.
Explanation:
```
{1≥≢∪⍵:⍵,1⋄1+@(⊃⍋⍵)⊢⍵}
1≥≢∪⍵ ⍝ if all elements are identical
⍵,1 ⍝ then yield ⍵ with 1 appended to the end.
⋄ ⍝ ... else,
(⊃⍋⍵) ⍝ index of the smallest value
1+@ ⊢⍵ ⍝ increment the value from ⍵
```
[Answer]
# [MATL](http://github.com/lmendo/MATL), 16 bytes
```
t&=?1h}t2#X<wQw(
```
[Try it online!](http://matl.tryitonline.net/#code=dCY9PzFofXQyI1g8d1F3KA&input=WzMsMSwxXQ) Or [verify all test cases](http://matl.tryitonline.net/#code=IkBnCnQmPT8xaH10MiNYPHdRdyg&input=e1sxXSBbMl0gWzEsIDFdIFszLCAzLCAzLCAzLCAzXSBbMSwyXSBbMiwxXSBbMywxLDFdIFszLCA0LCA5LCAzXX0)
### How it works
```
t % Take input implicitly. Duplicate
&= % Matrix of all pairwise equality comparisons
? % If all comparisons were true
1h % Append 1 to the original copy ofthe array
} % Else
t % Duplicate array
2#X< % Push minimum and index of its first occurrence
wQw % Swap, increment, swap (adds 1 to the minimum)
( % Assign the incremented minimum to that position
% End if implicitly. Display implicitly
```
[Answer]
# [Perl 6](https://perl6.org), 46 bytes
```
{.[[==]($_)??.elems!!.first(*==.min,:k)]++;$_}
```
(modifies the input Array, and returns it)
## Expanded:
```
{ # bare block lambda with implicit parameter 「$_」
.[ # use the following as an index into the array
[==]( $_ ) # reduce the array with 「&infix:<==>」
?? # if they are equal
.elems # the value past the end ( 「.end+1」 would also work )
!! # else
.first( # find the first value
* == .min, # where the element is equal to the minimum
:k # return the key rather than the value
)
]++; # increment it ( auto vivifies if it doesn't exist )
$_ # return the modified array
}
```
##
[Answer]
# Mathematica, 56 bytes
```
±{b:a_ ..}:={b,1};±a_:=a/.{p___,b:Min@a,q___}:>{p,b+1,q}
```
Uses named function `±`. Uses ISO8859-1 encoding
**Alternative solutions (58 bytes)**
```
±{b:a_ ..}:={b,1};±{p___,b_,q___}/;b<=p~Min~q:={p,b+1,q}
(* @GregMartin and I both independently came up with this above solution *)
±{b:a_ ..}:={b,1};±a:{p___,b_,q___}/;b==Min@a:={p,b+1,q}
```
**Usage**
```
±{1, 1}
```
>
> `{1, 1, 1}`
>
>
>
```
±{3, 4, 5}
```
>
> `{4, 4, 5}`
>
>
>
[Answer]
## Haskell, ~~71 70~~ 62 bytes
```
f(a:b)|(x,y:z)<-span=<<(<).minimum$a:b++[0|all(a==)b]=x++y+1:z
```
@Zgarb saved 8 bytes, thanks!
When I started I hoped for some elegant tying-the-knot trickery, but @Zgarb's way is just as amazing.
[Answer]
# [AWK](https://www.gnu.org/software/gawk/manual/gawk.html), 63 bytes
```
a=b=1{for(;$++a;d=$b==$a&&c==$a?a+1:b)b=(c=$b)>$a?a:b;$d++}++NF
```
[Try it online!](https://tio.run/##SyzP/v8/0TbJ1rA6Lb9Iw1pFWzvROsVWJcnWViVRTS0ZRNknahtaJWkm2WokAyU07UAiVknWKina2rXa2n5u//9bKpgAoTEA "AWK – Try It Online")
The code scans all the numbers presented on the input line and sets variable, `d`, to the position of the smallest number, or to the number of fields plus one if all values are equal. Then it increments the number at that position and prints everything. As a result it either adds a new field with a value of 1 or increments the smallest number in the given set of numbers.
The first condition/test is always true, and just does some initialization.
```
a=b=1
```
The code block is a `for` loop, which applies one statement to each number from the input line.
```
for(;$++a;d=$b==$a&&c==$a?a+1:b)b=(c=$b)>$a?a:b
```
The check to continue iterating just increments the `a` "current field" variable and stops when it's gets a 0 (by running off the end of the list).
```
$++a
```
The body of the loop updates `b` such that it's always pointing to the position of the smallest number in the input. The code also has to save the previous position of the smallest number, stored in `c`, to deal with cases where the minimum is the last number on the line.
```
b=(c=$b)>$a?a:b
```
The "end of loop" statement sets variable `d` to the current field "plus one" if the current value matches the current minimum as well as the previous minimum, or to the position of the current minimum otherwise.
```
d=$b==$a&&c==$a?a+1:b
```
One the loop completes, the code increments whichever field `d` points to. If all the fields are the same, it will increment an uninitialized field, which in AWK will default to 0. Otherwise it will increment the first field with the smallest value.
```
$d++
```
The second condition/test just increments the number of fields in the input line, which will always evaluate to true. If all the fields were the same numeric value, that change in `NF` will cause a `1` to be appended to the list. And if it changed one of the presented fields the additional field printed as a result of incrementing `NF` will be an empty string.
```
++NF
```
[Answer]
# Jelly, 9 bytes
```
;1µ‘i¦E?Ṃ
```
Thanks to Dennis for the -2 bytes.
Body must be at least 30 characters; you entered ... .
[Answer]
**Mathematica, 53 bytes 57 bytes 59 bytes**
```
If[Equal@@#,#~Join~{1},x=#;x[[#~FirstPosition~Min@#]]++;x]&
```
[Answer]
# Java 8, 85 + 38 = 123 bytes
Void lambda taking a `List<Integer>` (output is mutated input). Byte count includes lambda and required import.
```
import static java.util.Collections.*;
```
```
l->{if(min(l)==max(l))l.add(0);int i=0,n;while((n=l.get(i))>min(l))i++;l.set(i,n+1);}
```
[Try It Online](https://tio.run/##hVFda8IwFH1uf8VFEJIZg@7jYastDJ8G25OPw4esRnddmpYk1Yn0t7vYdtSJ2yAk5NxzT87JXYuNGOaF1OvFxwGzIjcOrBMOU1j7Ei8dKj7NlZKpw1xbfhWFYVG@KU9IlbAWXgRq2IdBC7bNS9RCnUgsS10LeC1ty0yaSVd7RusmT9rJlTRJAqhTIzPp7wbigxome1ySDDVRNI4z8elPqrhYLMiIRqgdYDxiOtq@o5KE6FjxlXQEKU2aJoqDQaS4PYJMD8Y0qg6BT3HmeJPjAjIfhsycQb16nYMwK0uP2YLW3evco6mw0kIMWm7hFD/ygh8g7McVu4DeMOjWRcY1g8utdwxuGdz7vS5Xkd@WuQHSccTUG4SHxmdjP/jls/1fF6Vrs3ScR2PEriYm5Ay1XNhjhdSvUBr9pZ6X7j/52kCjcjJ3LtJUFo40Ak15trNOZtxDvPDzcep7UNznz4Qjvb6FYQJ922NNLtYaaFxWoV9VePgC)
This almost looks like Python with those method imports...
[Answer]
# [R](https://www.r-project.org/), 63 bytes
```
`if`(any((v=scan())-v[1]),{v[m]=v[m<-which.min(v)]+1;v},c(v,1))
```
[Try it online!](https://tio.run/##lY5BCoMwFET3OUWwm/@pFkQ3rc1JRDDEiIH6LRpTRDx7mlJKF8VFGZjFGxje6H1t2hokLQBOTEoSICauTCuMV1f2lQh1TR6dUd2pNwQOq2NauC1W4OIU0Wc8hLEDH3WjW0Oay4m3MylrBuJ24ONMYbtraXVzWy7MkBKfHSyu7MfACvufBNuYpEmEZ4hePmeeRVgE9MX5Hs73cf7G/gk "R – Try It Online")
Had a shot at this without peeking at the [previous R answer](https://codegolf.stackexchange.com/a/166251/95126) first.
Although the overall approaches are pretty similar, this pleasingly comes-out 2 bytes shorter.
Here we use a code block (enclosed in curly brackets `{}`) as an expression, which allows us to adjust a chosen element of the input vector `v`, and let the expression evaluate to the new value of `v`.
Shorter, but less fancy than the [previous approach](https://codegolf.stackexchange.com/a/166251/95126) of abusing the indexing operator `[<-` as a function (which definitely deserves an upvote anyway).
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal) `aW`, ~~21~~ 18 bytes
*-3 bytes by using the register instead of variables.*
```
:≈[1J|:g£(nn¥=[›0£
```
[Try it Online With Equal Elements!](http://lyxal.pythonanywhere.com?flags=aW&code=%3A%E2%89%88%5B1J%7C%3Ag%C2%A3%28nn%C2%A5%3D%5B%E2%80%BA0%C2%A3&inputs=2%0A2%0A2%0A2%0A2%0A2&header=&footer=)
[Try it Online With Unequal Elements!](http://lyxal.pythonanywhere.com?flags=aW&code=%3A%E2%89%88%5B1J%7C%3Ag%C2%A3%28nn%C2%A5%3D%5B%E2%80%BA0%C2%A3&inputs=5%0A6%0A1%0A2%0A4%0A3&header=&footer=)
Explanation:
```
# Implicit input; a flag takes input as list
: # Duplicate input
≈[1J # If all elements are equal: append 1
|:g£ # Else: save minimum value to the register
( # For every element in the input:
n # Duplicate current element n
n¥=[ # If current element n == register value:
›0£ # Increment current element and clear the register
# Implicit output; W flag outputs full stack
```
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 20 [bytes](https://github.com/abrudz/SBCS)
```
{⍵+<\⍵=⌊/⍵}⊢,0~⍬≡⊢~⊃
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///v/pR71Ztmxggafuop0sfSNc@6lqkY1D3qHfNo86FQHbdo67m/2mP2iY86u171DfV0x/IP7Te@FHbRCAvOMgZSIZ4eAb/1wDpU3/UNkld59CKtEMrNB/1rtJ41LnoUe8WoIzmo44ZQAMOrVC3VgeKLnjU1QYSVTe0NrI2VDC0NlaAQiDPyNoILAIRN1GwVDBWBwA "APL (Dyalog Unicode) – Try It Online")
First we append a zero if the input is unique, then increment the first minimum (which will be the trailing zero in the unique case, as the numbers in the input are positive)
`⊢~⊃` Input without all occurences of the first element.
`⍬≡` Is this the empty vector? (are values in the input the same)
`0~` 0 without the result of that (a single 0 if all values are the same, empty vector otherwise)
`⊢,` Append this to the input
`{⍵+<\⍵=⌊/⍵}` Increment the first minimum.
`⌊/⍵` Minimum value
`⍵=` Boolean vector with 1's at all minima
`<\` Less-than scan; only leaves the first 1
`⍵+` Add this boolean vector to the previous vector
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), ~~20~~ 17 bytes
```
=,1|iᶠo{+₁ʰ}ʰtᵒhᵐ
```
[Try it online!](https://tio.run/##ATQAy/9icmFjaHlsb2cy//89LDF8aeG2oG97K@KCgcqwfcqwdOG1kmjhtZD//1syLDEsMywxXf9Y "Brachylog – Try It Online")
### Explanation
The first case is easy. The second is less so.
```
=,1|iᶠo{+₁ʰ}ʰtᵒhᵐ
= Assert that all elements are equal
,1 Append 1
| If that failed, try the following instead:
iᶠ Get a list of [value, index] pairs for every item in the array
o Sort: put smallest value first, and smallest index for equal values
{ }ʰ Apply this predicate to the first element of the resulting list:
+₁ʰ Add 1 to its first element (first occurrence of min value)
tᵒ Sort by the second element of each sublist (index)
hᵐ Head of each sublist (value)
```
Here's a worked example of the second branch:
```
Input: [2,3,1,5,1]
iᶠ [[2,0], [3,1], [1,2], [5,3], [1,4]]
o [[1,2], [1,4], [2,0], [3,1], [5,3]]
{+₁ʰ}ʰ [[2,2], [1,4], [2,0], [3,1], [5,3]]
tᵒ [[2,0], [3,1], [2,2], [5,3], [1,4]]
hᵐ [2,3,2,5,1]
```
[Answer]
# [Thunno 2](https://github.com/Thunno/Thunno2), 11 [bytes](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md)
```
ạ?1a:MçȮ⁺Ẹȧ
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m728JKM0Ly_faMGCpaUlaboWWx7uWmhvmGjle3j5iXWPGnc93LXjxPIlxUnJxVAFC5aa6hjpGEM4AA)
#### Explanation
```
ạ?1a:MçȮ⁺Ẹȧ # Implicit input
ạ # Is it all equal?
? # If it is:
1a # Append a 1
: # Otherwise:
M # Take the minimum
ç Ẹ # Parallely apply:
Ȯ # Index of the minimum
⁺ # Increment the minimum
ȧ # Assign the new value
# Implicit output
```
[Answer]
# [R](https://www.r-project.org), 45 bytes
```
\(x)`if`(sd(c(x,x)),x+!rank(x,,"f")-1,c(x,1))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGiNNulpSVpuhY3dWM0KjQTMtMSNIpTNJI1KnQqNDV1KrQVixLzsoE8HaU0JU1dQx2QjKGmJlRTeZqGoSZXmoYRiEjWMARJQVlGUJYRXMwILmasA4ZwnomOJZxngoVnAuWZwngQ6xcsgNAA)
This would be 4 bytes longer as a full program, which is a fairer comparison to [earlier](https://codegolf.stackexchange.com/a/223872/78274) [answers](https://codegolf.stackexchange.com/a/166251/78274) that had been posted when backslash functions were not yet a thing, and full program was a golfier approach:
## [R](https://www.r-project.org), 49 bytes
```
`if`(sd(c(x<-scan(),x)),x+!rank(x,,"f")-1,c(x,1))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72waMHGNNsYjUyd4uTEPCBDM1OzemlpSZquxU3DhMy0BI3iFI1kjQobXZC8hqZOhSYQaysWJeZla1To6CilKWnqGuoAVegYampCNVbWcqVpGGoCCSMQkaxhCJKEsoygLCO4mBFczFgHDOE8Ex1LOM8EC88EyjOF8SAOWLAAQgMA)
[Answer]
# Ruby, 46 bytes
```
->a{a.uniq.size<2?a<<1:a[a.index(a.min)]+=1;a}
```
I feel like there's a better way to check if all elements are the same than `a.uniq.size<2`, but I'm too lazy to find it.
[Answer]
# Octave, ~~69~~ ~~67~~ 64 bytes
It was actually shorter to make this a complete named function than using both `input` and `disp`.
Saved 3 bytes thanks to Luis.
```
function x=f(x)
[a,b]=min(x);if any(x-a),x(b)++;else x=[x,1];end
```
Old answer, not using a function:
```
[a,b]=min(x=input(''));if any(x-a),x(b)++;else x(end+1)=1;end;disp(x)
```
[Answer]
## R, 97 bytes
```
if(all((a=scan())==a[1])){a=c(a,1)}else{while(!all(a==a[1])){a[which(a==min(a))][1]=min(a)+1}};a
```
Too bad that the synthax `x=+1` doesn't exist in R !
**Ungolfed :**
```
if(all((a=scan())==a[1]))
{
a=c(a,1)
}
else
{
while(!all(a==a[1]))
{
a[which(a==min(a))][1]=min(a)+1
}
a
```
[Answer]
# TI-Basic, 53 bytes
```
If min(not(ΔList(Ans
Then
Ans->L1
cumSum(1 or Ans
min(Ans+ᴇ9(L1≠min(L1
L1(Ans)+1->L1(Ans
Else
augment(Ans,{1
End
```
[Answer]
# Matlab, ~~83~~, ~~77~~, 71 Bytes
```
function a=x(a)
if~nnz(a-a(1));a=[a,1];else[~,I]=min(a);a(I)=a(I)+1;end
```
I'm relatively new to code golf so please be kind! I tried to use anonymous functions but googling says you can't use if/else statements and matlab doesn't have ternary operators, so this is the best i felt I could do.
Edit: Corrected and shortened (twice!) thanks to stewie-griffin.
] |
[Question]
[
As is [well known](https://es.pinterest.com/giddyupingo/chuck-norris-counted-to-infinity-twice/),
>
> Chuck Norris counted to infinity. Twice
>
>
>
[Besides](https://9gag.com/gag/avnxB3X/chuck-norris-has-counted-to-infinity-backwards),
>
> Chuck Norris can count to infinity backwards.
>
>
>
Also, although perhaps less known, Chuck Norris can [speak a little Spanish](https://www.youtube.com/watch?v=rkL8uaZckjc&feature=youtu.be&t=32) in addition to English.
# The challenge
Write a program (or function) that can be run in two different languages. In one language the program should output the sequence
```
1, 1, 2, 2, 3, 3, 4, 4, ...
```
and in the other language it should produce the sequence (including leading zeros)
```
1, 2, ..., 9, 01, 11, 21, 31, ..., 89, 99, 001, 101, 201, ...
```
# Rules
* [Programs or functions](http://meta.codegolf.stackexchange.com/a/2422/36398) are allowed, in any [programming language](http://meta.codegolf.stackexchange.com/a/2073/36398). [Standard loopholes](http://meta.codegolf.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden.
* Different versions of the same language (such as Python 2/3) don't count as different languages. Related languages (such as C/C++ or Matlab/Octave) do count as different.
* No input will be taken.
* The program should continue to output terms of the sequence until stopped by the user. Since the program will not stop by itself, output cannot be produced at the end. It must be produced while the program runs, either continuously or in batches.
* Output can use STDOUT or equivalent, or can be displayed in a graphic window. Any non-numeric separator between sequence terms is allowed, as long as each term can be clearly distinguished from its neighbouring terms. It is also acceptable if the screen is cleared between terms.
* Either sequence can start at `0` instead of `1`. In that case, in the "twice" sequence the `0` should be repeated, just like the other numbers.
* Leading zeros are significant in the "backwards" sequence. For example, the tenth term is `01`; neither `1` nor `001` are acceptable.
* If the two languages use different character encodings, the program is defined by its *bytes*, not its characters. That is, the bytes should be the same in the two languages.
* Shortest code in bytes wins.
[Answer]
# [Python 2](https://docs.python.org/2/)/[C (clang)](http://clang.llvm.org/), ~~109~~ ~~107~~ ~~100~~ ~~84~~ ~~95~~ ~~88~~ ~~89~~ ~~88~~ ~~87~~ 84 bytes
```
i=0;
#/*
while 1:i+=1L;print`i`[::-1]
'''*/
a(){for(;;)printf("%i %1$i ",++i);}//'''
```
Python: [Try it online!](https://tio.run/##K6gsycjPM/r/P9PWwJpLWV@LqzwjMydVwdAqU9vW0Me6oCgzryQhMyHaykrXMJZLXV1dS58rUUOzOi2/SMPaWhMsn6ahpJqpoGqokqmgpKOtnalpXauvD1T6/z8A)
C: [Try it online!](https://tio.run/##S9ZNzknMS///P9PWwJpLWV@LqzwjMydVwdAqU9vW0Me6oCgzryQhMyHaykrXMJZLXV1dS58rUUOzOi2/SMPaWhMsn6ahpJqpoGqokqmgpKOtnalpXauvD1T6HyinkJuYmQdUD9JkzVX7HwA "C (clang) – Try It Online")
The L in the Python code is part of the delimiter.
**Explanation:**
In the C code, It first sets i to 0. Then, it starts a comment (`#` is valid code in C for `#include` statements) where the Python code goes. At the end of the comment, it defines a function that forever increments a variable and prints it twice, space-delimited. It then begins a comment.
In the Python code, `i=0;` sets i to zero. Python ignores the next line because `#` starts a single-line comment. It then forever increments it and turns it into a long a number and prints its reversed string representation. The 'L' from the long is part of the delimiter. After that, it starts a multi-line string to comment the C code, that ends later.
-2 bytes thanks to @LuisMendo. -7 bytes thanks to @ZacharyT. -6 more bytes thanks to @ZacharyT. +11 bytes to fix a bug thanks to @mbomb007. -7 bytes thanks to @Doorknob. +1 byte to fix a bug thanks to @Doorknob. -1 byte thanks to @yoann. -1 more byte thanks to @yoann. -3 bytes thanks to @Cyoce.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E) / [Jelly](https://github.com/DennisMitchell/jelly), ~~14~~ 13 bytes
-1 byte thanks to Adnan (avoid triplicate with non-popping print)
Raw bytes (hexadecimal):
```
31 5b 3d 3d 3e 5d fc 06 b6 3b 87 08 15
```
In [05AB1E](https://github.com/Adriandmen/05AB1E)'s [code-page](https://github.com/Adriandmen/05AB1E/blob/master/docs/code-page.md):
```
1[==>]üε¶;‡ηΩ
```
**[Try it online!](https://tio.run/##AR4A4f8wNWFiMWX//zFbPT0@XcO8zrXCtjvigKHOt86p//8 "05AB1E – Try It Online")**
In [Jelly](https://github.com/DennisMitchell/jelly)'s [code-page](https://github.com/DennisMitchell/jelly/wiki/Code-page):
```
1[==>]‘©Ṛ;⁷®ß
```
**[Try it online!](https://tio.run/##AR8A4P9qZWxsef//MVs9PT5d4oCYwqnhuZo74oG3wq7Dn/// "Jelly – Try It Online")**
### How?
The [05AB1E](https://github.com/Adriandmen/05AB1E) program prints the double count with each entry separated by newlines:
```
1[==>]üε¶;‡ηΩ
1 - push 1 onto the stack
[ - start infinite loop:
= - print top of stack
= - print top of stack
> - increment the top of the stack (pop(1), x+=1, push)
] - end the infinite loop
üε¶;‡ηΩ - this code is never executed nor is it parsed
```
The [Jelly](https://github.com/DennisMitchell/jelly) program prints the reversed count with each entry separated by newlines.
The parser will treat a valid literal between `[` and `]` as the enclosed literal, otherwise these bytes are undefined tokens and as such become equivalent to tokens separating the code into lines. `==>` does not parse as a literal, so the code is effectively:
```
1 - link 1 (not executed but parsed)
1 - literal 1
==> - link 2 (not executed but parsed)
= - left equals right? (vectorises)
= - left equals right? (vectorises)
> - is greater than the right argument? (vectorises)
‘©Ṛ;⁷®ß - Main link: no arguments
‘ - increment (implicit 0 on left increments to 1 on the first pass)
© - copy the result to the register and yield it
Ṛ - reverse, this has an implicit decimal list build, e.g. 142 -> [2,4,1]
⁷ - a newline character
; - concatenate, e.g. [2,4,1] -> [2,4,1,'\n']
® - recall the number from the register, e.g. 142
- The chain has reduced to one item of arity 0, causing a pre-evaluation print:
- ...and since the list contains a character it gets smashed together
- e.g. [2,4,1,'\n'] prints 241 followed by a newline character
ß - call this link with the same arity, e.g. as a monad with left = 142
```
[Answer]
## Jelly/Pyth, 15 bytes
```
.V1_`b;"1üÉÉ$
```
Unprintables are mangled by the SE software, so here's a hexdump:
```
00000000: 2e56 315f 6062 3b22 7f31 fcc9 c924 0b .V1_`b;".1...$.
```
Run with `jelly f file` and `pyth file` respectively.
### Explanation
First comes the Pyth part. `.V` runs an infinite loop over the incrementing sequence starting from its input, which is here `1`. Then we reverse (`_`) the stringified (```) loop index (`b`) and implicitly output it. The `;` is there to end the loop, and the `"` is necessary to treat the rest of the program as a string literal so that the parser doesn't choke on it.
The Jelly part will be explained by first translating the remainder of the program from the Jelly codepage:
```
¶1‘ṄṄ$¿
```
The `¶` acts as a line feed, effectively ignoring the first part of the program by making it a link that is never called. Then we start at `1` and run a while loop (`¿`) that uses `ṄṄ$` (print twice) as its condition, and increments (`‘`) the value as the loop body.
---
Incidentally, replacing the Pyth part with `1[DR,>]` *would* create a valid Jelly/05AB1E submission in 14 bytes, but the current interpeter contains [a bug](https://github.com/Adriandmen/05AB1E/pull/84) that prevents this.
[Answer]
## Perl/JavaScript, 87 bytes
```
s=0;print=console.log;m=s;$_=s=s=s=m;while(++$_){print((m/s,$_+`
`+$_||/&&reverse.$/))}
```
### Perl
```
s/0;print/console.log;m/s;$_=s/s/s/m;while(++$_){print((/s,$_+`
`+$_||/&&reverse.$/))}
```
A mechanism I've used a lot in JS/Perl polyglots is to abuse the fact that substitution can accept pretty much any delimiter, using `=` means I can use the initial pointless substitutions (first replacing `0;print` with `console.log;m` with a flag of `/s` in `$_`, which is currently `undef`), then setting `$_` to the result of replacing `s` with `s` in multiline mode (`/m`), which is `0`. Now `$_` is `0` and I start the `while` loop, this then increments `$_`. Next I call `print`, passing in a regular expression that matches (due to `||` at the end which matches an empty string) and use the `&&` operator to then send the reverse of `$_` concatenated with a newline (`$/` is pre-initialised to `"\n"`). This counts to infinity backwards.
### JavaScript
```
s=0;print=console.log;m=s;$_=s=s=s=m;while(++$_){print((m/s,$_+`
`+$_||/&&reverse.$/))}
```
Lots of variable assignments here, masked in the Perl `s///` calls. I set up variables `s` and `m` as `0`, alias `console.log` to `print`, run some pointless division, set `$_` to `0` and begin the `while` loop incrementing `$_`, call `print` passing in `0` (`m/s`, this starts the call to `m` in Perl, but is treated as standard division in JS) and our target string (`$_+"\n"+$_`) via the comma operator, which returns the last item in the list. I avoid the last piece of Perl code (`&&reverse.$/`) because `$_+"\n"+$_` will be truthy and so I can use `||` to produce a `RegExp` object containing the end of the Perl code which is never evaluated.
Tested using Perl 5 and Node 6.
[Answer]
# NodeJS / PHP, ~~131~~ 106 bytes
*-25 bytes thanks to @Titus*
```
<!--
printf=(_,i)=>process.stdout.write(i+i),strrev=i=>i+" "//--><?
for($i=0;;)printf("%s ",strrev($i++));
```
Using NodeJS instead of browser JS for better output formatting and better infinite loop handling.
[Try the JavaScript online](https://tio.run/##LcxBCoMwEEDRvaewoYWEONp9nHiUIhphujBhZrTHT4V2/R//PZ@zLExFYc9rqnW8ATSFadcN7asjh7FwXpJIL7rmQ/sPkyZLnlwnypxOJIzkTWuGASCOU7NltnfCZwjud7LmIa358yt571yo9Qs)
[Try the PHP online](https://tio.run/##LczBDoIwDIDhO0@BCyZrxsD76HwUDzpCL6xpCz7@NNHzn@/njVtbLjF2LLTbiv4xEmBmqc@iOqm96mHTW8iKp0AwqomUEwkzBde7eY4xL3feuFur@IHwlhL8Zt5dtXd/8U0hAKTWPg)
Note that the TIO output is cut off after 128KB.
[Answer]
# [V](https://github.com/DJMcMayhem/V)/[Brain-flak Classic](https://github.com/DJMcMayhem/Brain-Flak), ~~27~~, 26 bytes
```
(()){[[({}())[]]]}é1òÙæ_æ
```
Hexdump:
```
00000000: 2828 2929 7b5b 5b28 7b7d 2829 295b 5d5d (()){[[({}())[]]
00000010: 5d7d e931 f2d9 e65f 01e6 ]}.1..._..
```
[Try it online! in V](https://tio.run/##K/v/X0NDU7M6OlqjuhbIiI6Nja09vNLwcMPhjYdnHl4Wz3h42f///40MDAA) (modified slightly so that it will terminate so you can see the output. On TIO, V only outputs if the program terminates)
[Try it online! in Brain-flak Classic](https://tio.run/##SypKzMzTTctJzP7/X0NDU7M6OlqjuhbIiI6Nja09vNLw8KbDMw8vi2c8vOz///@6ujmJeemliemptsk5icXFmckA)
This isn't the most interesting of polyglots, since the V code has no effect on brain-flak classic, and vice-versa, however it's really fun to use both of my own languages on a challenge, and the two solutions are pretty interesting on their own.
V Explanation:
```
é1 " Insert a '1'
ò " Recursively:
Ù " Duplicate this number
æ_ " Flip this line
<C-a> " Increment the number on this line
æ " Flip it back (the '_' is implicit because it's at the end of the program)
```
BFC explanation:
```
#Push a one onto the main stack
(())
#Forever:
{
#Print twice:
[[
#Increment the top of the stack.
#Evaluates to *i + 1*
({}())
#Minus one
[]
]]
#Endwhile
}
```
[Answer]
# Retina / Python 2, 61 bytes
```
#{*M`
#*M`
"""
}`$
1
""";i=1
while 1:print str(i)[::-1];i+=1
```
[**Retina**](https://tio.run/##K0otycxL/P9fuVrLN4FLGUQoKSlxcdUmqHAZgpjWmbaGXOUZmTmpCoZWBUWZeSUKxSVFGpma0VZWuoax1pnatob//wMA) | [**Python 2**](https://tio.run/##K6gsycjPM/r/X7layzeBSxlEKCkpcXHVJqhwGYKY1pm2hlzlGZk5qQqGVgVFmXklCsUlRRqZmtFWVrqGsdaZ2raG//8DAA)
[Answer]
# [R](https://www.r-project.org/)/[Octave](https://www.gnu.org/software/octave/), ~~83~~ ~~80~~ ~~78~~ 71 bytes
*-3 bytes thanks to Luis Mendo*
```
i=0;
while(1)
#{
print(c(i<-i+1,i))
#}
disp(flip(num2str(i)))
i+=1;
end
```
`#{ }#` is an Octave block comment and `#` just so happens to be the comment for R. The R interpreter only sees the next line as the body of the `while` loop, and the Octave interpreter skips right ahead to the Octave code
The R part prints out pairs of numbers starting at 1, and the Octave portion prints out the backwards numbers starting at 0.
I fully expect to be outgolfed (even by the same combination of languages); I've just been writing so much Matlab and R code recently that I figured I'd give it a shot.
[Try it online!](https://tio.run/##DclBCoAgEAXQ/VyjzYgF2dY8TJjRBzNRq0V0dnP73mnLcrtaYUZNzw7vWAnqXooJobBlzAOk6iGafrQiR948IofrmHJJ3EIQpFGaXFhr/QE "Octave – Try It Online") - Octave link
[Answer]
# Ruby / Python2: ~~68~~ 64 bytes
```
i=0
"#{loop{p i+=1,i}}"
exec('while 1:print str(i)[::-1];i+=1')
```
### Ruby perspective
simple init of variable:
```
i = 0
```
`"#{}"` is syntax for string interpolation.
I use it to exec expression instead.
```
"#{loop{p i+=1,i}}"
```
`p` is a shorthand for `puts`. `loop` creates an infinite loop.
Next there is the `exec` thing, but it never gets evaluated, as the infinite loop is by definition infinite. Needed `exec` not to yield syntax error with Python code.
### Python perspective
From perspective of Python, there is a common `i=0`. Next, Python has different syntax for string interpolation, so this line is simply discarded. Next there is an infinite loop similar to what others posted.
[Answer]
## Bash / [Check](https://github.com/ScratchMan544/check-lang), ~~50~~ 28 bytes
Thanks to @Doorknob for saving a bunch of bytes by switching from Python to Bash
```
#>
#v
#p<p<)#
seq 1 inf|rev
```
### To Bash:
```
#>
#v
#p<p<)#
```
These are just some comments, which are ignored.
```
seq 1 inf|rev
```
Start a sequence going from 1 to infinity, then pipe the result to `rev`.
### To Check:
```
#>
```
This immediately switches into 2D mode, going right. `>` directs the IP right, which has no effect. It wraps around to the beginning of the line and hits `#` again, which switches out of 2D mode. It then hits `>` in 1D mode, which pushes 0 to the stack. Because it is in 1D mode, the IP wraps to the next line.
```
#v
```
`#` switches the IP into 2D mode again and `v` directs it downwards.
```
#p<p<)#
```
The first `#` switches back to 1D mode again. `p` outputs the TOS as a number (but does not pop it), and then `<` prints a newline. This is done twice, and then the number is incremented with `)`. `#` switches to 2D mode again, so the IP wraps to the beginning of the line, hits `#` to switch to 1D mode, etc.
[Answer]
# CJam / ><>, ~~27~~ 23 bytes
```
"la,:naonao
"1{_sW%n)}h
```
## To CJam:
[Try it online!](https://tio.run/##S85KzP3/XyknUccqLzEfiLiUDKvji8NV8zRrM/7/BwA "CJam – Try It Online") - note that you have to wait until the 60 second limit to see the output, but it works offline.
```
"la,:naonao
"
```
This defines a multi-line string literal that is never used.
```
1{_sW%n)}h
```
The second line goes like this:
```
1 e# Push 1: | 1
{ e# Forever: | 1
_ e# Duplicate: | 1 1
s e# Convert to string: | 1 "1"
W% e# Reverse: | 1 "1"
n e# Print with newline: | 1
) e# Increment: | 2
}h e# End loop
```
## To ><>:
```
"
```
Begins a string literal.
```
la,:naonao
```
Content of the string literal. Each of the character codes is individually pushed to the stack.
```
"
```
The IP wraps around to reach `"` again, which ends string mode.
```
la,
```
`l` takes the length of the stack, `a` pushes 10, and `,` divides. This gives us the length of the stack / 10.
```
:nao
```
`:` duplicates, `n` prints as a number, `a` pushes 10, and `o` prints as a character code (a newline).
```
nao
```
Same thing. Print the number followed by a newline. The stack now has length 10 again (the original string literal's content is on the stack).
The IP then wraps around to the `"` again, leading to 10 more elements to be pushed. Next time, `l` returns 20, so 2 is printed, etc.
The second line is never touched by the IP.
[Answer]
# [Röda](https://github.com/fergusq/roda)/[C (gcc)](https://gcc.gnu.org/), 90 bytes
```
main(){f(0);}f(a){a=1//1{[` $a`[::-1]];a++}while[]/*
;for(;;a++)printf("%d %d ",a,a);/**/}
```
[Röda: Try it online!](https://tio.run/##FcjBCoQgEADQ@35FRMGMGbNeG/oSERooSWhrkaCD@O1W8E4vHrOU8pOwAyYPX@TsQTDJaIhMslPVyGSHoTfOsXRdvtawLdaR@rA/IvCb@I9hPz3U7Vw9ai1akEkpyqXc "Röda – Try It Online")
[C: Try it online!](https://tio.run/##S9ZNT07@/z83MTNPQ7M6TcNA07o2TSNRszrR1lBf37A6OkFBJTEh2spK1zA21jpRW7u2PCMzJzU6Vl@Lyzotv0jDGiSoWVCUmVeSpqGkmqIAREo6iTqJmtb6Wlr6tf//AwA "C (gcc) – Try It Online")
### Explanation
This abuses the fact that `//` is int divison in Röda but a line comment in C.
In both languages, `main(){}` denotes the main program, and they both call function `f` with a dummy argument of `0`.
In Röda, `a=1//1` does int division and assigns the result `1` to `a`. C sees `a=1` and does the same thing, but everything after that assignment is a comment for C. From there, the two languages branch off.
**Röda**
We have an infinite loop with `while[]` ([an empty condition is truthy](https://codegolf.stackexchange.com/a/114401/41805)). Inside that, `` $a`` converts the integer `a` into a string (with a leading space) after which `[::-1]` reverses it (and it outputs with a trailing space). Then the value of `a` is incremented by one.
Outside of the while loop, a multiline comment starts `/*` and ends just before the end of the function.
**C**
After having ignored the rest of the line, the program goes to the second line. We start with a semicolon because the `a=1` statement needs to be terminated. After that, we encounter a simple for loop that prints the iterating variable, `a`, twice on each iteration.
Outside of the for loop, the `/*` is just there to ignore Röda's ending `*/` comment.
[Answer]
# [QBIC](https://drive.google.com/drive/folders/0B0R1Jgqp8Gg4cVJCZkRkdEthZDQ) / [QBasic 4.5](https://drive.google.com/open?id=0B0R1Jgqp8Gg4UVliSTE0MzdLcEU), 58 bytes
```
do
p=p+1
if q then
'?`_f!p$|
else
?p,p,
end if
loop
```
This heavily abuses the fact that all lowercase letters are seen as literal QBasic code by the QBIC interpreter and are therefor just passed along to the QBasic layer of QBIC. How both languages see this code, side by side:
```
LOC QBasic QBIC
-------------------------------------------------------
do Start an infinite loop
p=p+1 Increment p, starts off as 0
if q then q = 0, goto ELSE q = 1, execute IF
'?`_f!p$| ' = comment, invalid '?` is a 'code literal', passing PRINT to QBASIC
syntax is ignored followed by QBIC code to flip p cast as string.
else q=0, execute q=1, so ignored
?p,p, PRINT p twice,
separated by tab
end if End of the branching logic
loop Wrap around for the next pass
```
[Answer]
# [laserLANG](https://github.com/andlrc/laserLANG) / [><>](https://esolangs.org/wiki/Fish), 163 bytes
```
!\0 \
/:+1/! ]oo\
\:a( ?\:a%$a ,!
/r[-1l//" ,"/
/!n-%1:\?(1l
\ --\/ <<---\
/----/'
\---- v
/>>--\#>---->/
\ /
/----<
\ \
/ -<< \
/<< \
"
">=>= /
\>=>=/
```
First time golfing, so it's a bit larger than it probably could be. I wanted to use ><>, but since a few people already used it to create the second sequence, I decided I wanted to give creating the first sequence a go.
[Try ><> online!](https://tio.run/##JYvBCsJAEEPv8xXZ1WLBDnGvZbv9EMdDL6JQLFjw99dZmkMeCcnzvb9qDXaDCcdrYgDw2DYTG5ces3t3XjAE4feuaSUjhkhh@GiXRpv7tAoMqkbkrE6hu/Ii1gj8hKV4fyotF4qhiccut@gfaM5O8ECUWKYy@coaWesf)
For laserLANG, an offline interpreter is needed to try it. It can be found [here](https://github.com/andlrc/laserLANG).
**laserLANG**
```
!\
\ --\/ <<---\
/----/'
\---- v
/>>--\#>---->/
\ /
/----<
\ \
/ -<< \
/<< \
"
">=>= /
\>=>=/
```
execution starts at `!` which is ignored completely. it then reaches the `\` and starts traveling down past several characters that it completely ignores. Finally it reaches another `\` and the fun begins. I basically took the idea behind the "Hello, World!" loop and condensed it as well as I could. It was a bit of a challenge dealing with the fact that laserLANG is only about to decrement/increment the memory counter when the program counter is going left/right respectively. I feel like the most bytes could be saved here by doing some tricks I haven't thought of.
**><>**
```
!\0 \
/:+1/! ]oo\
\:a( ?\:a%$a ,!
/r[-1l//" ,"/
/!n-%1:\?(1l
```
Execution starts at `!` which causes it to skip the `\`. It then continues on as if the laserLANG code wasn't there. I didn't realize ><> *only* had support for float division, so a short and simple truncation was a bit confusing at first.
[Answer]
# [Befunge-98](https://pythonhosted.org/PyFunge/)/[><>](https://esolangs.org/wiki/Fish), 32 bytes
```
\r.#%a/# :_::p#+a#1,#
>l::naonao
```
Wrote this before I saw how many `><>` answers there were. Some background: `\` is a direction changing operator in ><>, in this case pushing it down, while in Befunge it swaps the top two items on the stack. The Befunge code looks like:
```
\r.#%a/# :_::p#+a#1,#
```
[Try it online!](https://tio.run/##S0pNK81LT9W1tNAtqAQz//@PKdJTVk3UV1awireyKlDWTlQ21FHmMuCyM9S2sspLzAei//8B "Befunge-98 (PyFunge) – Try It Online")
Prints out the backwards numbers separated by newlines. Befunge prints a space automatically after each number, so each digit is separated by spaces. Repeatedly gets the last digit, prints it and divides the number by 10 until it is 0. Then increment and repeat.
The ><> code immediately goes down to the second line.
```
>l::naonao
```
[Try it online!](https://tio.run/##S8sszvj/P6ZIT1k1UV9ZwSreSltF2TBRWUFHmcsux8oqLzEfiP7/BwA "><> – Try It Online")
And is pretty simple. Get length of stack, print twice with newlines and leave a copy of the length on the stack for the next loop.
[Answer]
# [Ruby](https://www.ruby-lang.org/)/[Stacked](https://github.com/ConorOBrien-Foxx/stacked), 37 bytes
```
0#/0[1+:tostr rev out]
loop{p p$.+=1}
```
[Try it online!](https://tio.run/##KypNqvz/30BZ3yDaUNuqJL@4pEihKLVMIb@0JJYrJz@/oLpAoUBFT9vWsPb/fwA "Ruby – Try It Online")
This prints `1 1 2 2`... in Ruby and `1 2 3 ... 01 11 21...` in Stacked.
## Explanation
### In Ruby:
```
0#/0[1+:tostr rev out]
loop{p p$.+=1}
```
After removing the comment, this becomes:
```
0
loop{p p$.+=1}
```
The only relevant line here is the last. `p` returns its argument, so `p p` prints its argument twice. `$.` starts at `0`, so `$.+=1` increments `$.`, returning the incremented value. Therefore, this prints each number from `1` twice.
### In Stacked:
```
0#/0[1+:tostr rev out]
loop{p p$.+=1}
```
This is equivalent to the following tokens:
```
0 #/ 0 [ 1 + : tostr rev out ] loop { p p $ . + = 1 }
```
The first two are not relevant (basically, transforming `0` into a reduce f Unction). Then, `0` is pushed to the stack. After, the function `[1+:tostr rev out]` is pushed to the stack. `loop` pops this function and executes it infinitely.
The inside of the function increments the top of the stack (`1+`), duplicates it (`:`), converts it to a string (`tostr`), reverses it (`rev`) and outputs it (`out`). This process is repeated infinitely. Since the loop is infinite, anything that comes after that token is essentially ignored by the interpreter.
[Answer]
# [><>](https://esolangs.org/wiki/Fish) / [Jelly](https://github.com/DennisMitchell/jelly), 37 bytes (25 in Jelly's codepage)
```
01+:nao:nao!
DU;⁷Ṙ€
®‘©Çß
```
[Try ><> online!](https://tio.run/##S8sszvj/38BQ2yovMR@EFblcQq0fNW5/uHPGo6Y1XIfWPWqYcWjl4fbD8///BwA "><> – Try It Online")
[Try Jelly online!](https://tio.run/##ASoA1f9qZWxsef//MDErOjpubiEKRFU74oG34bmY4oKsCsKu4oCYwqnDh8Of//8 "Jelly – Try It Online")
**><>** prints the sequence to infinity twice, **Jelly** counts backwards.
**><>** is only concerned with the top line:
*And thanks to @Challenger5 for saving some bytes here on the linefeed*
```
01+:nao:nao! Stack at: 1st run 2nd run ...
0 Push a 0 0 -
1 Push a 1 0,1 1,1
+ Pop 2, add them 1 2
: Duplicate top item 1, 1 2, 2
n Pop top, show as num 1 2
a Push the number 10 1, 10 2, 10
o Pop and show 10 as an ACII char (ie '\lf')
1 2
:nao And again, for repetition
! ><> wraps around; this skips pushing a 0 again.
```
**Jelly** executes its code bottom-to-top. Only the last 2 lines are relevant.
```
®‘©Çß main link, keeps track of the current number
® Get a number from the register (0 on first run)
‘ Increment that by 1
© Store in register
Ç Call helper (printer) link
ß Call this link again
DU;⁷Ṙ€ Printer
(Say we are at number 21)
D Break into digits [2, 1]
U Reverse array [1, 2]
;⁷ Append a line break [1, 2, \n]
Ṙ€ Print each char in array
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/)/[PHP](https://php.net/), ~~102~~ ~~86~~ 80 bytes
```
#//\
for(;;)echo strrev(++$i).'
int main(i){for(;;i++)printf("%d %d ",i,i);}//';
```
Outputs the double sequence in C and the reverse sequence in PHP.
[Try it in C!](https://tio.run/##S9ZNT07@/19ZXz@GKy2/SMPaWjM1OSNfobikqCi1TENbWyVTU0@dKzOvRCE3MTNPI1OzGqIsU1tbs6AIKJ6moaSaogBESjqZOpma1rX6@urW//8DAA "C (gcc) – Try It Online")
[Try it in PHP!](https://tio.run/##K8go@G9jXwAklfX1Y7jS8os0rK01U5Mz8hWKS4qKUss0tLVVMjX11Lky80oUchMz8zQyNashyjK1tTULioDiaRpKqikKQKSkk6mTqWldq6@vbv3/PwA "PHP – Try It Online")
## Explanations
### C
In C, the `#` forms preprocessor stuff. I don't really know much about C but it doesn't complain when there's any empty line for this stuff. The `//` forms a line comment. A `\` at the end of a line is essentially "escaping" the newline and making the two lines be treated as one. This also works for line comments, so the second line is seen as a comment in C. The third line does the work of outputting the numbers with a simple for loop. Afterwards, there is simply a comment.
### PHP
In PHP, `#` forms a line comment, so the first line is ignored entirely. The second line prints the numbers reversed with a for loop, and separates them with `\nint main(i){for(;;i++)printf("%d %d ",i,i);}//` (the C code wrapped in a string).
] |
[Question]
[
# 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](https://en.wikipedia.org/w/index.php?title=List_of_presidents_of_the_United_States&oldid=911603941#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"
[Answer]
# [PHP](https://php.net/), 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!](https://tio.run/##HZPJjqNWAEV/pRaWXBbVYnIxpFJpYWPATMZMNkRRBH7MhgcPbIaPT6W6N3dzzupKp83brz9/tt@bQvS6ij6Tqb1DkLyuf6zfsqVo0ns0JK9x1CfM9l@Q3H4z4Lt2PPSjaI0@Hgimdg07bJFUcrSHnvbDIduxAWXUZNHqwokgOB6zBvP4UGKhEZbZAZhtm5UfMtfJUb3eAAeHzBhmwodMad6LQmucusfOmCmxZlQX7KS6UalLw4FEkBSJRKwKEKoJUwzNOejSi2f2gdn75EnJtNlUVF7GEZpTxHMGO84uVad1xGnLI0g5R6YuE2F3cCBZXtDwWiXUHdflbfhOLYQG/SRH3h5mj0NeWjRXUBlxcijL1sjq1DVQZaurUOFjw@5QqUpZcFUVqgORoocG4Z31C7OluNjZR2FYW5ISSPjNWfrZ0Qcb2zGcVasyDc@mC2w2mUMoy2S5TNxtb4xk3Kj0CJrBVzAXuAR9JsHEUFh7QWooEqUduUFjQZmxdwElLvfxnHhWGNdFg8u2JygFw5w8@aqFppSRs6GetBN2utVZCBa96o/oOD4UhJVCSfj2lC@8TuXvhNZLPt/gRbFteDk2kyefPW9GboTeRbyqR1lGSWt2B@JwBzpZkgTYjffOf26dfVZcHPYgQy3kfBVu8@6Gqv39@z794tm@ZQz7d7u1hqkSEsbPHX5/0wMMZns7Ol6J0jwv1XkRuGRMPQp3RbydbzdY9VDa4WbpdLb/1JatHDCo4uvZch3eb6hZeWZN0zs9q2P5NqeTNqnEZx@GgJZd2T0s88nKmMRSRjqdtSVMojK8iMj0G4zuDWm5W76lIfW648p65nfHZ0Cz8QB3MedW8cVA6iNrU0@8qdNdQvLUAvpJIF9/eIi1O7krS6kxUyu8w2e6PankI2K2eyresoqtHIu0e6JZ3JMjeTgP6Sh8rjebzccKfK6iv7FVgWH/fGzAr5SCGrz1AxrgUNTJd3Eoazabv1bg56r@5f5W/wDFN6o3H8kth2sRNtEdvLjoUbfrj68vKYnRI0LzC/v2QnLM@3@wHQrY9F8/pP8B "PHP – Try It Online")
---
Tests:
[Try it online!](https://tio.run/##jVZrc6rIFv2eX0GdSlWSMjcCKsLNnJnyCUFFRMXIzNRUK81DoRsbEHFqfvu5TcQzyQmn6uaLShZ777X3Wrs78qJvv/wWedHNzW0C4yRmvjK/3zD0764TET9gGuwjw7VF6e6RqdcZGWLiQmYFYs9HboLR3QU7AWTrMc0CKrUvUBV7iOnYIIw/YUSWu2AWHg5BzKjQcSCJK6KJbJlYBSGMmQmw/UoY1/4Aw4hg@BnFt96VNkt9tM1/ViFf5u0gm8CMxt3uKxM3ysT0UeIjxgSI6aYEViCbJeeVHwQ@CBkFIpIzCiDkHaVLzz/g34pd5AEkFTFb72mPnhgdB/sKWEnGAlsP0KQLkAf4Gk5Ng5yRCliLLbnQCgGxmSH9DDGpaGSrcUEOCUD7gPLWfUi2VcAPc@mmND8CFc0RSrKdDQEebc6YzgYHH7vCtd6QrY@Dod2pHIxQcl4GeRzT3PMnRqbVJp@R7bJGI008SBxMmXef6GByWKELkXtPqEODAuL4MLBL6BxGCQw3kDCc9B7f86i56FP6RockXloxTLFkJhN8pMheAI8wAMiuQJbcuhDtQEjb/4OK3kGlxv8b9Orbqz4n25GPAph/JlbApX8tDLFNRcIYGMdF8M8dlq4m/i59nBX6WgCnAsyVFa8wtgnOipeqmEn81U@UO0SMXIyM2HQrXUWTummcMPwbtozZA8GRtquHceDbLqwIWlaqQEKpJrTSom2fcY0fDdB/@tSAUrVvBVyNWgwqL7S4IGn43QgqQGnhS77YtdLVXP3Md72kiDzwY4g8nH2v5OMLwvtNMXxiRhAhaF8Hp1EGb3Pj3yoRyujjHNkYFUr/aKEfQpf9MPxic9iM5p/@3VWXBhcyl9rN6/lAQEA3BzVRZbyr11Q/DHM6DpL8hNPVNwZGRUADAvcn7frhaFKemNUT3TSxV4m@@qFLpUjd4KOkkjnPXvV9PfF@GpNCr3YEhB4TzHQDQlAJvJ5S/QupQgPR3ePNn883N06KtolPB@Lc3wLiogfm7290FdEfX@EpCrAN7@/@c/fonn3kBCCB9xsQQ6H5lw23b/@zzYWxSeKsr2dmfd3RRq/WoXYeqlxmJHHDtBK3217zk5Dzo3FnyrKiVNMT7SVVNh3UOedzu2YY2t60hNfTXF3GE3sw51xBONUTV0Et3x@heRjXZjVt2Nboymmf1AXYjYfJgCOY67Owv/dtS4WCn6DZ@uCsllq81mKTmyruKNcUVZLrVPkOkcRJO8sXfOiEQByd07UjzmV@dWKNA07o5aEzqocqq3bFgxdZLf7MjrAJPbLsYTcdeDu9Ifq8y07nvG6MuP30gLDa3r929vUMtbtkpw7d9auq8AcbKGNrwi5n45XQ5MXNvAcsK9SHynpY387PcT4fJ0atK4h6qMoNPNMWttGGuYVlmdudT@K2N8m4DVIbmY0SU6kt7AXbmHH2SeBr0YqoVp/dGWCxRjqWBaO75vvnIJvBpW5t6EKuy8ayo/iCMF3KryNLG7pcPlGno2ltug1dyz6P9/ELeclShdR2nR1rGifvLI15r8WO4qEpobrvN5EkbzR4lNzjduJNrOWq/6q@yDKBkXYYsIPAHnM7jrW7WXAwj815z/VX8/ZAxiNLNFXc9A5bsu8FtH3j1dIw9UnSaxmRnpz2HSiY3lzqbcfrGnZ7Bnh5ZXfa7LyfnTsizJwlX1/061G@3WJ66Rl269pufjDM4@jclNcC2Uthri/mkon4XDm6CMXzuD2ueU2vASO47x9jy7Ib8kJeDM75VHcFqCtZw8lHZwuCnbXqE81EtUY8GZ4D3dRHRH3tirswl7ovx3WjvUlwdyMu9pvVhKipGznL/lY9BUMinyK7cWSJOU6XpG0c5MNuN0Sao1sBPjrNqcqlQGj2@E2zrRjKi@8cjiTv97iMG8wSJ@t8vXt4eHi@tb/egt9rt36t9ufzg@/c24Wb1qH9GCckwYkfwtKBD7/e2g@3YQG/oGEQQ4bAJCXoNny@fLn74OXnb/9QK9PTkF60mPvyQk0vuG/fqKXflgLcepihyf6KgH3BPNJb9gPzxHz5L/OFfjj3JZ4@@QN9eb7559v/AA "PHP – 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](https://www.php.net/manual/en/function.gzdeflate.php) 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](https://tio.run).
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`.
[Answer]
# [Bash](https://www.gnu.org/software/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!](https://tio.run/##RVJhb9o6FP3uX2HNXtWuK00CDBLkDwFWEB1lo@wxPcQHQ0xiSOzJScpSxPvrvOu00pCC5et777n3nLPheXK5TNl1A084fsBTbnD4G44KT0oFX4rDEj/jGX7CwxsUspYDP9Rn3frMWa4V4mzCM5GjLQtVZMQRRWwp01TyDAk25sZImqMdezBcHVKpUMxGQptYoISNjH4RhgxS8SJSriIk2Vzr3N4KtGcTnSh0YGTZIP0yT9Av9qHptAIakyUMLlVcADwNA7onYcSzHNF@sEh0xnMyEbudMLQOUU6mPJJ/L1oZLd4Lf5RSbau/9XRLJnx7sMlhAHwUUpF/uIIBjFDIdZyARmQslKkIFajp@zayJ4sqFaZuycljg3zX6QGSW047@JdvEw7ZC16l2iDPb/vtYAoEcRORBzgzbd6G2ZHvUpiteG/TL6FQcYVajuu6QbgxPOEZ@Qbz6lQBdLfr23Hp/m2zn2mV5yInzw0yAq4L22ZeFokwOw1Q/QYZ8wp0@uK2bfsQ0rjZSZFG0KvZbQeDROQFyAEvoSmS8m2fxP73hdrzDKig4j3Ycr64NRfT7aNUqahQx2/6DvAvdAQbESrrTCBLH@2qC74r7JhLrSOjjwQ8Yt3jOW2/GyzBJkKRkZ3RRKAsavstxwsGPH0B1IHWqYziGnsszEaYAtpa7yDXc1yna8kbNixmx@/A1dquskwsTJkBhYA7PMo4KWzWV5kLlegjVHsgqGf1e2iQR6GUiCrU7vow0bdKRVpZ1mp@204H2J5Lq2VEnuQfO7rvgS4jYXgKSgLHdryJzLKKDMA41g/9YK6VfZ4LHvM3s8Zk3KAH@9YH9cH8UtU@Bu/F73FuwIJktuEZ/4AW7Jq6N2jIHHparNz1x89nBIpeX/d6NzcnvFphusDsP0xP09XtrVyf8Xp9dbUxgh96Z/QEZRI9M7qy1d76fOcCRWt6egrwnXemp2F92o74FUuF6a/eCc8gf3ZLT68fg0/ndQ8gnvFdWmA6w9D7lcHL/T25x@erK7FNNGC/kk@Bvf2RBaDWwWG9OrYS/L5cLmEZl3mB3c5n7Habrf8B "Bash – Try It Online")
A lot of manual compression :)
[Answer]
# T-SQL, ~~1169 981 979~~ 977 bytes
Holy cow, I figured out string compression in SQL ([available in SQL 2016 and above](https://docs.microsoft.com/en-us/sql/t-sql/functions/decompress-transact-sql?view=sql-server-2017)):
```
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](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/5341#5341). 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](https://codegolf.stackexchange.com/questions/32796/tips-for-golfing-in-t-sql/190648#190648))
So Microsoft added a [`COMPRESS`](https://docs.microsoft.com/en-us/sql/t-sql/functions/compress-transact-sql?view=sql-server-2017) and a [`DECOMPRESS`](https://docs.microsoft.com/en-us/sql/t-sql/functions/decompress-transact-sql?view=sql-server-2017) 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](https://stackoverflow.com/a/35559661/21398), 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`.
[Answer]
# 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}))
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~587~~ ~~584~~ 568 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
.•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](https://tio.run/##HVNtU1NXEP7ur0AUrQMDpoLFtqCMHaa8tFJEpE4rhpcCdtoCFrGxMDe3NC8UFBPaCWAkSSEmJiWQhOTehISZfXIvM3XmzO1fOH@Ebviye2Z2z@6zzz770xP7yNT46WmjVCLXFyiO7RqUHdKzLJUAXlglFB5/ZG@nQg3lGy4O1xthHOEVtudu9olsFxIIIUzxirPxJNhEyceUwKpRnpWKjvLgPLIUq6Xcpfcuqf52EhQHkw/pCEnpeYMc9r7EMlYasYkwSpYGN/IU/wIxxKUSlco6ldn/pxo@0pvggQq/4TPCTZSgd5TpgxfubhSEH06KXv5kiPJS/R0pKjZJ5c3Mp2aO625g@WesC33OCH8o0qaPe6e@WUSO616bmvyM8hTBvgj8IHKt8N7AS5Fpe3iRYliSqgt/cMflvqct9QsoUwqvhpon8dcYFPjmELJKVJCqUyoFnirAcG7RLvQfsT8gldfwXkFmmB8fw/OMMkzJjulDlHZ47vsTXC1nhBeQ/XWq4h4F1wg0Ut70Tbc/oGQH4iKDd1LZh86Gi/qZuQs8U2EaawOkQyW9@xqzI7aE/3tsUPEDpm@F45znuIXkzH1@Q62VS5FZO3xnAbUOqWfPzw2L@Ij0hkhn5FiicpV@ji/gLRUYDrJI9CB4EmTmUg1S2aS/2zpYD@GK82uWw2JtD7RBZIT/F7HVjU0eO//edU/Euf4Ay2QPCbZrX1mliuv8ecrVIciQkCEN21dR5AXvSTXZ8RQb0rOKP89dpgT/FNpdxKQS/pyO8bIX2ZNgxTljt1hiXWauztDujt0bwS7W4BW6yHZTqpl30y40vEWId3wwf5tidwZ5K6FRx1g/ok9utvzr62tl8pnyVbzm/R4YGoLfNZg@kW9gVh7heJzB7JiHQrvNdKDkGGIAVyytKssCtHqUK268wIqVrrgQZf0dYB//2Pg@@HtVXQ42PXwvYfY1NcQuMjGNnOMSFYce2GYrbio/pyiLZouOpxdFABpnmId2Ky3VpX6eW4mMUwlpwz93AR5ust5pHp6lPLLSRmnUPDzLucE6xa7hR7oTpV6o33byPOsVpY3jey1MmN5DRRG3jqrIlEj//ARbK80HUv1t6@VmcPGrvovP8Q5ip6e21ustV5ttzf8D) or [verify a few more test cases](https://tio.run/##PVNrU1NXFP3ur4goKkMG8pSkLSCjw1SglQIitVVEoICdtjwKSCzM5ZaGQEExoR0eRkgETAwlkIS8IGFmr9wwU2fOpH/h/BG6QzvcD@esufvs19pr/zTS9XSg92xs4o7FZGqld9hHZqQEJ7obOCnTSadbV1J7ViEV/81JCmJDh6xDuualsoKXhQzSz6q6aiito4T@ame55sMxXmNjtLZZxO4ihE34KJibrjj1VtLuMwphUcsOSyWFbPs4YhQoofi1j06p/nrqFQf9j@kYu9L1FnHsfYl5LFRgDT5kCknMIkHBLxBAUCo7UlmmLN//qJqbUpVwQYVHc2u@SgrRB4o2Yw6zDUgLD6Zp5/qnHZSQ6m8I01GlVN4OfZaPc9xVzP@MZZEa1XwmEcm7OXf42ynEOa55oP8OJciPfbHyg4jbMGfHKxGtfnyVApiRqhO/c8b55jFr@SSyFMbrDks//uyBAvcoNgsZSkt1Wipp7mqFy7lF20j9iP02qbzBXBminQw@ges5RZmSrbwbO7TFfT/o42hxzTeJ2C8DudlucIyVCkrk3YM1D2m3DkERxQep7CPFBwf1MHNXuKf0IJbaKAWVUg1mZkesC8/3WKWjG0zfAtv5neMWdoceMIZaImf8w11wnxvUUoSfv7jUKYJP5dwmpbhyzFC2SD/bJ/Ge0lwOYgg1wnvqZebCeqms0bvqOtaDLzf9NcthqqQRyXZEhWdCrDdgjdtOfHTeF0GO38Yy2UOIz6WvCpmc8/JlipfCyyUhSklsGHDEA96T6m7dGFalaxF/XLpOIfYUyVYEpOL7nE7wqgmxU29ueqirwBK7m4@XasnWnvtPsY0lzImUiDVQ2MKzqRFJvMcmz/hg/DYF7rXzVDa7HT0t2Bmptf7tbrYx@Uz5It7wfA@0JLzf6fNukdAzK09w0svFbOUPRfI204GMo4MLKCski7JMI1mObG4WL7FQiOSc2GH9HfDC/GXk/WD3orocfDTyvvj41umIL3/fIOKOa3TU8dA4nJul7AvaYdGs08nglFhBkl/kD7sKEanOtHDfir@XMohontErcHGS5fr84fmTJ4WIlunOH56/sbNOsa15EKlHpgnqo3ruZzmnVLN9z8qEpRrpSAQLx8XKFH/LeB@fhQgvSNHb2MTJ4GRUPsHreA@BM/3ZN8Yqm91gMRv0OmOVvcpgNpgvkOUCWfU6k8FoN9hMRv5nu2k1WIyWC2QtIoPxf9//UNFqtxVx0cNuN/JnKloZmszGR/8C).
**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?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand how all the compressed string, integers, and lists work.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~431 428 427~~ 426 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
“¡Ẹị’ḃ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!](https://tio.run/##JVJbTxNBFH73VwiKgCFAU4pFkUQlRASs3B9EQZEiSETBSCBKutxaF1HaJhRUSAu77YPlVrnM7BZIZnYnu/yLs3@kntWnycyZ853vckaHxsamCwUn9IulQCOgLzuhDSDzNWYe30TcSIqY2BRykR1/UeaE1oEsOhK9grWm9mZL/f/Zb6yBtlzlzGXr/WaebTd5KrzV3ulxj6fO/RnkCb5a3/bmVut7ES7pZymmDBrLjnQE2ncEaBz3ePFwpDOmVN7hCy4CjrFOa@p7Ov8RcrnREI8CXZy29niYp0c7gM7N2kmhOpJWCmTOSBWL8CzocmmdiFl7QOevAzl5Yu1jD9AUEHmMqY@EjBxBk4GonUB3QF@ZstNY9hkJxOu@eq3JzoEW56cjQBb4eclsCT/kGTMWRBM27PxdO@5IeZZyJL19wJGOkRZZ8daWm3lL5dGOPiCo6hznCqWabwFFt/7wU5ZuRvC@z0I2ZL6KT6YuIna6aMZOInkRAboGdLfXkYhQgf7s/uTOXn@OPIIoDMiOiDyw0n77EIjyEKfeawG6PYPK9GOxi8Jud10mRbZqVmzyqKUOI1wZUMnabxQ5oL9BPwp@GLsfsDK1oCsjaIxxCNqXfhH5@NoHdKHbjoOG0ccbQUviBmCV7gi1@CXPWCq74JmAkWoHjRoHrm8ambzpSCdmvgLI12G2J3K9PGEnKjBJ14wFX5uvHKNCRCSNYi7nQPtmxkR2ykDXTh67M@hShwhPIlp90AxZ@6iIE0vpQ@cqG9DBLhRgJLuBhk0daNa9TvB0fxfPYFCWEkCxKj@w0kPPRAR7BxGvV@yKXMMAO3vLLgLuruwG@HkPU9zgNZnlJl51Yu5GolysN/OlG0BxabdY1vf0nWuU2opJ9aBPdpLpQNC0HyLqhDYrcacRSuSwtwXLTCkUCqUev99T7a2uKf0L "Jelly – Try It Online")** Or see (Kevin Cruijssen's) [test-suite](https://tio.run/##TVPrThNREP7vUyCKBYO4S1toFUlUQkTFyj1GFK9FkYi3aDBKuoi0FlGhicULppXd9ocFpAqcs1sgOWf3ZJe3mH2ROksTwyabnTln5pv5vpkduTs6Ol4uu7HvLAs6AWPGjX0B8iZglfBMpMyMmBeLInnQSd2sdWMLQN66Cj2Ad@1dHbZWCQ6Zn0GfOe5OFlpCVon9bJfr/ZJ/fEyWw15klKf5p5bOB80XH4t4zRDLMvW2OeMqf0H/iABtY7IfP66yxdSGk3zKQ8Ay9magpb9nryGvNxrjc0DfjtsrPM5zI91AJyecjNBcRfcBmTSz1SI@AUbSFxbz9grQN4eBbFy2VzEHaBZIcpRp50USewQ9CUTrAboExuwLJ4fXQTONeH1Vh9qdIugpvnkfyBTfrpmo4Ws8b81HUYQvTumUk3KVEsu6itF1w1XWsS0y62@qs0q2xue6B4Egq22sK1SJ/wCKav3hmyzXgeCDr0XSTPJPeGQZIuHkDr50Mti8SAD9DHR5wFWI0IB@63vl1V64jn1EkRiQJZE4a@dCzhoQ9RxWPX0B6M@XyMxYF8tI7ETvbkYUjk@IRT5na8MIVwtUsVfbRBHoLzD@Rp@NnonY@SYw1PsojLkG@rshkXh@Lwh0qs9JgY6jT7WBnsENwFu6JLTqWzxva2yH5yNmtgt0av72dNPJ06OusmGV6oG8H2YrojjA0066HifpiTEV7AzW4agQEZtGMruToH@w5kXhhYmqbVzyatDpbhF/imgtUStmryIjTmx1EJVraEUFe5GAmekDGrcMoAXPfcJzQ708j4Oy1QiS1fhvO3f3mkhg7m3EGxDLoth6g209ZDsRb1eWI3y7n6ne4PUkKz6504NzN9N1YqGDTx8Bikv7gxWCVx95QmkXcVL9qJOTYQYQFO2rmHNjiw240wgliph7Aa@ZWrZKPI7eCL64lVXHWqsw7kq5fNUnN4fCUsAv@eqr0A43S/gD7LMD@@ygZzdKclgKNcp756GmoBSQA/vsYMWW5P84FbsSEw55XiU3HJbxaazEoNPol33X/gE "Jelly – Try It Online").
### 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
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/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!](https://tio.run/##NVINTxNBEP0rGI0YQgwQrEIgRFGMiFbRGIMJQqx8WESDIKCScKUUBERTkgJGtB9XiArVFrW7V4Rk9npp@y/m/kh9WzW5eze7M/d29r159HBkZLpcdmc/UOx4C4tflejiS3zUJx2nAA/wOmE3naokAacKJnCiV68TgGJ09G@JYemtpIb4mN5adI0K5We92HxcIbjgGjkdaI4bbC3jwyJB8f/sFGNrzV8J2tkKVcgAtypor//7QwY59wPBeAsgH9ZV2@7sJou5hhMkW9rcwG4h29DRWMg21p4D2JEOMqdVsMU1xG2WXzinaVDVV8yodSfZcbbwjS1c4YCtRbZWJ9BlMcpyga0odpwlrG@yyHBupYpzS85eKUo/WcSdpXaWh2PItqpPbMVYrPT1Au7SDqXGWe5dp8SjqVpnsfXZhB0pHtxn8WagqUaFWG6CR3cig1WdpeUqnC9x9degX2HrLfRWQn10jR9TLMz8AYt5laaErpF7pcA1lu/pF/qbtNNOhqVxaVQF@5op5SRLgftTPgifD9sRJJxNZ2uQvrMMlKJ@ll@HvGf0wWKexT7tVyvhGj/7cSD6uMoiAMl71EZjJ@6gDrGGXnjujly5gza8UEBtsIyrd8dm2tAoeKGJFRqGFOfH@uyYs4FqFtl7dHSbduAk2F/hzr7iWi8adzID8M2O2LHOyVOFVDNGxt9KifzsKMv1muohtiSL5Xyux9ulttUGZbTd2pO3J@20B3OCMm1HkmLNTRcp3nqZdiDRQ86ZnkkkPMhPesD6wgspZ7wsQ07Gx3Ku2k7DSUqQqQ4bKV5fyA4U105D/qcsZ8HAMgq3DNfIsrUwkg8fw8Z0P/Iez9Rz9D9ox8gcfIKoG2NC@zDEWsUQsUx47COYNQMh/E54uIsybZCNjlgknS0yfRhZYdJvlpHaB93qnTosHtBnSOgsag/kLgtMwa6etXn1kXKQh8xyudxQV9dUV1/f9Ac "Jelly – Try It Online")
A monadic link taking as its argument the date in YYYYMMDD format and returning a string with the answer.
[Test cases](https://tio.run/##PVL/T1NXFP99f0XNFjGmW/pKKS3CiNOxDN26qVmcSxAjggrDhcmAKUlf5ZvA1JSkwDK0X14lKnRrUXvvK0Jy7utL2//ivH@k@9yqvLx33ueec@7nnvs55/aNsbGZZtOL/0OZT7tZvG2hs/fwU880LsBcx@cmvWKhFYQ5UbNgJwf0OgdTT4@/TzFt7cprk53QriXPbFG@0IvNX1sEX3lmRQPN8QPbK/ixyFH2Iztl2F4bbYEzbC@0yGAutqyz/mGHnOPKa4C73TDVpM567sU3WTwIfkayu9dL7NTKwb5QrRzyR2CcVB9ZM2qu2zPFJZYvuaJpkDVYL6l1N9/XWfuXbVxhn@0lth9Nosp6muUi22l43GWsf2RR4sqqjyvL7m4jTW9YZN3lMywPJhDtUc/YzrBYHRyAuUzbVLjLcvd7yt2e9rtLPb9POqn6/lUWfw1HT6oFlpvg0ZXIOV9/Y8WH8yWu/hD0q2w/ht5KqKee@XqahVXdZzGvipTTOXK3kfiO5d/0FvVNOUW3xNL8elzNDXZRwc03ElenhyB8NemkEHA33a0R@o9lopEeZfnqZqxDHyzmWezRXpsSnvnmGg5EHedYJCD5FbUR6scd1AHW0Avv5bFvf0IZMSigNlhm1ZNjs70oFLzQxF64BSlOTww6GXcD2SzKv9DhJdpGJ8F@H3ceqq8NoHC3NIy@OSkn0z91olbowsiM9lCuGh9nuX6y7SbbksVKtXIldl49VxtU0u3WPXl83CmGMSdI0@3IU6YrepayPd/QNiS6wRUrPIVAGPGpMFj/jEHK2RjLBbc0xPJBm1NEJylHljoIUdaolYfra19A/t9YxsHAMo1umZ5ZZntxrJo8BsfMNcTD4ek/UP@IkyFr5A7QBYwJ7aEh9iMMEctc2DlEs2YhxKibvHWeSr2QjQ5Z5N0tsoYwssKidyxT/usX1BN1UN@nF5DQXdI9kDssMAU7etbm1VOqQB6ymqcwnL7Pv/R58a1TavETtYhJ/bnZNDoj0UCoPeD3GZ3RzkB7oP0IhY5Qh98XDBjRQCRowBcJdwRCRugIdWgUMD7sfY90NBrRWO@IRg08QR0FDLYb/wM) (borrowed from [@KevinCruijssen’s 05AB1E answer](https://codegolf.stackexchange.com/a/190609/42248)).
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~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!](https://tio.run/##VVJdr6JIEH3fX0F8EYJXAQF1ZrwbFVHwCwVBnZ1kkG6gkY8WGlAn89vvMpvNZvalUnXq1DlVSUVu5RZejjB5SzMAP/zxBxi/08EYNRGzY@zmBdRSQtPumM7hvUQ5pNuvGF3bTBelfuwSeHBr85l69LT0fZjTrYutE49wgbKuV1N@MgKma5GFn60cc6947OQUmILJjfyhJXvAuCuFJ5RkVdqVyPORNZNVW5y/XjsZKlJ/sRDkyuMcgtk@GZVhdKvTAcuBR@rLoVFK@hLpxlASxGTp5QPfsPtPRWUvg9HJW4tDmAgT89l7GiwPDrP1pLxMxMKAbuKJnsYu@uZ5FlvG7FxKnPK0Yk0Ks0Qzy0qJ0WBT972CJXhKIH@IwG21LN0p2L3KkNeVbUTiTcLPFtpwf95MY8O55I/Vcl0JYWWrtxuclCTIw8eJ1baO6fHHqz5Xb9iNdoqRbwbz/UvTpcjED8U0nSU5WTg@Xjbs5NYcv1tcLpFRCvik@@CMiMo6xxq93LumVo31Lm@Gsup4jbnDyg4ibYkCucC8rrO4v5NecHo4RafZg2AsB2ijLp1dZfNRFfjSIVaLfDSLyJ6DzirdP@JwjXnbYA2UiSPggfPggsBwsbHlU33knPWWK1mdS4XJY3DHReJs65mo7ra6erwCDfjzaxKi0arv@Pneti43dE2jXBGF6HacJUeeW/oW/9obl7vjPS1HW1vVznBxmoVrucIvXTxBP9mb0fVWvcI50e6HJA@cWySCeqrZdW30RktDCiNuy9mKZOxye6GejGRu1Q@19xwo8@d5DoTe0bJ7vUnQ6rSubgFlscUwbKvFdAscI/K98535ir51@gLDfElhTSnNw9KA6Q1lEUp/BjRieeaT@xWxovitm0Mcux6ke39du72g443fvS7JjhjDfNZo0wzD0HjMMR9@ltOAGlPsf5LtCc5RTPW5DsUPhqM285kC1Jf/EcqgLAglCB1K4Ph/GeyY4iHPM9SPPygKNLxGlP5tT6bxX2eeG8NfgElylAZ0C6ZvR7PVoX5QT@jmn6h2WiYwR167QyVZSsIGibM0aErgPn9rUz@Zz42Pl6VFFsNunAX0L88udsE8BTQ/YiiWar@9vVPtJvH/aTLNyM@PvwE "JavaScript (Node.js) – 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](https://codegolf.stackexchange.com/a/190609/58563)).
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~464~~ ~~444~~ ~~442~~ 418 bytes
*-15 or so bytes by stealing ideas from [Kevin Cruijssen's answer](https://codegolf.stackexchange.com/a/190609/6484)*
*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!](https://tio.run/##XVNraxtXEP3uX6G@aaMKrbSy7qWFvtLSJNAWSqAQ0iR9OJhCQt2WpILAxk5lp6SmteLEtIqxVrUt10kcy3bqjSQvzPGSDwah37B/xJm7u4pnA/qw554755yZO7r804Vvxr8/1PlPDnOh4558v98Z@SCcWQydv7/C1On@dugs0nroPEH1auis9G/3m7SLqY/xDx7zKW29g9mXaOXpvUrQO0/toBbO/I4N7IIVHn00ZoeT1cHum6d@GXTJK9HD0PH4qxn0rg26n32BHXT58oORr/evv41pamH5oHoG9XOl/jZtYfLDQbdyot8MljCH31BF62Vq58llzTde3a/Cg0cd7JykbRbqkUtPBj0u23kP61jAQugsHX96D6u5iYM6WrjF7e1PU@N86NSDOcyHToM87g5/0ib9H/SoTT5ucmosssjd6AO3aCO6wor3L337q7lJbjAX7B1UQ6eGG3jIyj4eYIaamMUM9x9dn4cTCWR@qIQ3XKzBp2X2Jw//XZj4LqihySdtOHBRi518NGmL1lGN9Bt8GX7o3KZVzNJjZldoLbpobO8wvmus@JOjLxE/hTdBG0EP02zNKcQJZ0sSrrF4B/@O/cyFQW3i8hVa4VvUZd3MxQqPC63xSxfRDHa5retJQD9qKDNWoR4/vB8lM@FMhjVscHfUYdWb1DHx7vBb@Wa6mCcvc6USzPGSMMHj3cEfhjg69Fjf54n8ZTzqLMROP3KMxVO8iY1XzLiW0TX713qNWuHkFGqKD4uDtt3f5HE/Qo@hxvyXr7P4qpmPIWkz2Dv@lqneI28c9yuo5Y5l4QYN1Pf5VRawxQt0NUcds9xusPcp16zr3Llc9ESn3zWzc4@dKBb6bQ75OVqH2cMzVlnpbMbOZor5syOMdJk/@SeBbYDKW0fMECSMlowWjCXUhiBmCiXBJCBhpFpBqhWlWlGq2TKbbb3A2JKxnzMygS0T2DKBLROU8tkM@yoJdAyKoiYBSY1MXZKpR2XqUZl6tBQFtdKoFCOZblSmK0unsnRS0klZLzCsYakUintSckJKTkjJDEpm0HIOWs5BbpaSm6XziWsxhRJOOGm5W9oSTkMQMwXR7RAkDH8p1pagEAPpI7dOF6VPUfrYybtYKRTrmRWwhpMcokL0H9PmqY@4BA05c9NAKw1jVfPcolLLyrIdtaMkiO@ZVTiqSlBSpVJZVCqLSrmplJtO9adFf4V8Xmg@R0NOpzgtOassOauc4nT8WNbZZw)
### 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 `j`s 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.
[Answer]
# [SOGL](https://github.com/dzaima/SOGLOnline), 475 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md)
```
⁵æ“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!](https://dzaima.github.io/SOGLOnline/?code=JXUyMDc1JUU2JXUyMDFDRCV1MDFBNyV1MjU5MyVBQiV1MDEzQyVCNiV1MjE5NVEldTIyMkIlM0MldTIxNTQldTIyMTErZlF5JXUwMzlCJXUyMDNDQiV1MDEyQiUzQSV1MDVDMCV1MjU1MCUyNlNmJTI3JTJDJXUyMTE2JXUyNTUwJXUwNUMwJXUwMzk0JXUwM0E1JXUwM0JBJTVDJXUwM0JBJXUwMzk3JXUwM0I0JTNENm8ldTAzQTEldTAzQTAldTAzQzklQUJpJXUyMTJFJXUwMTJCJTA5SyUyMCU3RCVCRDZZJXUwM0E4JXUwM0I0JTdFJXUyNTkxcFQlRjgldTIxMTYldTAxNTcldTI1QzQlMjYldTAzOUIldTAzQjgldTI1OTIldTIwMUMlQzYldTAxNjEldTIwMUMldTI1MDAlN0IxJXUwM0IxJTNBQyUyNyV1MjA3MCUyNSslM0ElMjIldTIxNUUldTIwMUMqYyUyNyV1MjA3MCVGNytkciUyMiV1MjE1RSV1MjAxQypiJTI3JUFCKmUrKyUzRSUzRmFsJTIydCUyMSV1MjVBMHUldTIxOTRSJXUyMTVEJXUwMzk4JXUwM0JEaiV1MjU2NCV1MjE5MCV1MjA3NSV1MDNCQVAldTA1QzAldTAzQkJjJXUyMTVDLUdjJXUyMDc4JXUwNUMwJTIxJXUyNTEwJTI5JXUyNTE0JXUyNTg4NSVBNkBUJUFDJTVCQCV1MjIyQiV1MjE5NSV1MjAxQiV1MDNDMSV1MjEyRSV1MjE5MSV1MDNCNCV1MDE1NyV1MDNCOWYldTIyMUElQjNJMiU3RSV1MDM5NCV1MjU5MyV1MDNCNyVBNCV1MjA3NGIlQTEldTAzQkQldTAzQjhAMzYldTIxNUIldTAzQTAldTI1MTQldTAzOUUlQjEldTAxQTcldTIxNUMldTIxNTNtdyV1MDNCOCUzQSV1MjIyQiU1RSV1MjMyMCV1MjI2NS1OJTVDVCV1MjAxQlYlM0JyJXUyNUExJXUwM0M0JXUwM0I4JXUyMDc5JTNCQyU3QiVCRWwldTAzQTAldTAxQThVJXUwMzkyJXUwM0ExJXUyNTUxJXUyMDc4JXUwMzlBJXUyMjY0JUY4JXUwMzk0JUIwJTNGVSV1MjUzQ1MldTIxOTJpJXUwMTNDJXUyNTEwSyV1MDNDMHp6JXUyMjExJXUwMzk4JXUyMTVCJTI1JXUwM0M0JTYwJXUwM0M5JXUwMzk3MkQldTIyNjEldTAzQzhfJTNCT1IldTIwNzR3JXUyMjYxMVoldTIxNTMldTAxMTMldTAzQzUlMjUldTI1MDAldTAxN0UldTIwMzIldTAzQjlWSiV1MDNCRlUldTAzQjYldTAxMzcldTAzQzBkJXUyNTE0JXUyMjQ4JUIzJXUwMzk4JXUwMzlGJXUyMDFBR1IyJXUyNTBDJXUyNTUwTiV1MDM5MiV1MDNCOCV1MjE5NFQlQjIldTAzQkRzJXUwM0MzJXUyNUExbFFNJUU2JXUwM0JEJUY3JUE2JXUwM0EwJUIxJUIwJXUyMjYxJXUyNTUwJUY4JXUwM0ExVGUlQkMldTAxN0UldTIwNzAldTAzQkJfJXUyNUJBJXUyNUNCJUIzMSV1MjI2MSV1MjExNiV1MjU1QSV1MjU4OCV1MDNCQiV1MDM5QyV1MDNCMiV1MDNBNCVCRCUzQyV1MDNBMCVCMUMldTAxM0MlQUMldTI1MTQldTIwNzQldTI1MTgldTAxMERnciV1MjA3MCV1MjA0NCV1MjVCMjglN0MlN0QldTIwNzgldTAxMTM0JXUyMTE2JXUyNTY0JTIzJXUyMjFBJXUyMTU0ZCUzRiVGNyV1MjI2NSU3RCV1MjVCQ2UldTAxMkIldTI1M0MlNUUldTAxQTdYJXUyMDNEJTNFJXUyMjY1JXUyNUJDayUyMCVCOVcldTAxM0NtJXUyNTUxJXUyMzIwJUE2JXUyMTkyJXUyNTE4QyV1MDVDMCV1MDNDOCV1MDNBMCVCQyV1MjA3RHQldTAzQTAldTIxOTQlM0EldTAzQzZiJXUwM0I1JXUwMTNDJXUyNTkzJXUwMzkyJXUyMjFBJXUyMDc3LSUzRSV1MjE5MiV1MjE1Q08ldTIyMTEldTI1OTElM0QlNjAldTAzQkUldTAzQjUldTIxOTUldTAxNDYldTIxNUIldTI1NUEldTAzQzBCJXUwM0MwJXUwM0MzJUE3VCV1MDVDMCV1MDEzNyV1MDEyQlQlM0EldTIwM0Q0JTNCJTI1JXUyMjY1JXUyNTUwcFAlQjZHJXUyMTkyJXUyNUNCJXUyNUJDJXUwM0M2JXUwM0IyaiV1MDNDNDl2JXUyMDQ0NiV1MDNBNSV1MjVDNCV1MjA3OSVBNCU3QiV1MDNDNC8ldTIyMTFhJXUyMDcwJTdEJXUyNTEwJXUyMDc1ZSVBQyV1MDEwRCV1MjAxOCV1MDE2QiV1MDFBN2tpJXUwMUE3S2kldTAxNTcldTAxQTclMkMlMjAldTAzOTh3JXUyMTkw,inputs=MTg4MSUwQTklMEExOQ__,v=0.12)
Date logic could probably be improved a bit.
[Answer]
# [PHP](https://www.php.net/), 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](https://tio.run/##RVNrj6JIFP0r/cFMS3AiD0EqPe4uDwFtHiIi6GbT4VG8REAoBM3@9u2lZzPZL3Xqnjrn3uTmVJ3Wnz9@r8dz8rEi3ibFCg51UUVw@vr36yx5ZmVc@AhO2y5oUTOd@KvAbyG7@Ihg@FPF87ymWy4hUpXmJ@gmBM6ILskLnFx8Ieylh@WSIy/TvauNOhlZkiqYixF/8kqU3Kr/fMYgzC8y2suKOCRjbekCuVDZ3pj/6vtrzvmooRzVvKQ@jvHpneMHThbW0bJ2r3u8BZeDF2jDjeVEzy7iOPdTaJjsjavYuapDsyfb@6HKa0GqVeZyK1qTUU4wLZ5BzxsXxHlPxT4GkhXoQcLh8T3N1@15SYGwdooQ0ofdI8khnUImYyV6o@gl4FXtaZ@lm@6fnJPHB1ux6PjHlj5mxs0mtoxo9j7gmtopgSgT4l47H9bOPfalTovshpNE4B95mbLtZlAKfhHTsbHt@qx6XhaiBY@QFDclRPXBPO9AeWnM7D53O82x89jpc0stnmI1BGAP@/iRlOJlzQj9gAfV5roOHcjct4ro1z6uNLust718LeCHWsUTV8LLm4mPS9dONUCLzmmV/PGQWTVM4mvwng87m8WpKEHlzjUo6x6Xhq8DNhFthUFR6zW7rhWJwj3KXF/j6bIROnetZ7et6WW7wCg4R3qPh9O2Ou8rooMOAtc18XyHp4ulxYEEqbrw8uiSre/I9qx6ua3KWgOCgDzAgLwE7Tndb7qMNlpqmeuCTRMbw6oS8yBbi81un7f0k@yUMmojNWRIrTSboywr9@IcozMPtCYsBl13thG9yXcAf3CrV2wGCAzD3uKqgX6YTsdYf7R1kaH/Mz4jvjQzCvPbSbb6bRJhXypUoewKx@cmKTGcWRLkYgFYgsDmHLsgiB/TyQe@SuEw/oxpkJXUeJ2OVgz79u2PKBuNxZ@T7Dv5F/YGw7R6gWU0Utjb56fuN2H6QrZo9kIRBPinqlFWle3nd/lf)**
[Answer]
# [Charcoal](https://github.com/somebody1234/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!](https://tio.run/##dVRdb9owFP0rFk8gNSjmoyTaE9AV1JaNARvS1Bc3uRCvjt3dBFh@Pbt2nBUqTeIFH997zj33OEkmMDFCnc9LlLpsr5VMoL00b@17qUrA9vpNybLd4qMoDsJB0ItnYHAPbCuKTOp9afSz5qN4FIR9@j2YTLNxKvKCTqOQ16ebzOSiYA@w2wEWriIKY18hcijYQqTSA3x0BRiNBux5b3hB8e0gdVK9M/V8t7FOEU7sQSSvvl3ft1sILKVmP4RmkwOCwwZe31YqJUXO5qCxYnOB2IixNwYN6aZSgO50eCnxscuWRr06wMv4KRLytWIbUSnjSoZhEJKSaEFUAlNG7qrcoJts2K@r7lHoV0UilxIwqaErMyYHaquFU3brtY9fUGSk/YkMMaqGhlY0HzRmkHY/zq3X911VRUEN1102I9LSYiNPtTqUGeDOkMhJl8yowDkc8UslYyoUuJOg0gaMAx5NMygoNBYeY5kd3OiRd2uG5kjYVMERlNB1oRc0Af1L5DT6pflx//@FTeCa1S2SR6kVVITFYa2GYgcmJY/ZypjC1pYOjT8s3ZzsQjZi52DuSbfGpGhOjK7VcuJekxaSCJrNrDmY0htwICFREPKpUEcaY2qMkukeHOQJ54AvgCUR2nEs0v@4@LvutdZBvUluXanstjZ4yN3@YxsaHvD47iT3WWkrP8sCdGZOdW@bD4u75N532SNoDanz57ZPLYMef6p0arTd8ntEYhsRW7eSNsIp@yL/1MBo4CaMZoBCUYApIO545HlknldsSq@s5o88/8poe30FYl8LjzyB/47Mu2zbpWQXmQVjP9WElkMLpy@SJe@FIb8q@ldBiG83EUiPnn19Ebmw59zruqv5rXFvrRvWetatzg17gqJoyxv2u9OhfzzsfDqf64fTo3d6Do7qLw "Charcoal – 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
```
[Answer]
# [Stax](https://github.com/tomtheisen/stax), ~~550~~ ~~509~~ 502 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
ª╠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](https://staxlang.xyz/#p=a6cc546ba6a55473aa9b13901fcc1a2bb8730fef62f8c195304a2099a60a25e60d29806209e4fdcb859384fb50c55bd7af190dc479fa3a2b782f20707eb4016b8a54b4ca010c11bb2a44580965ca2b8925d71d5eba3b0a2fe9be42ba4b3edd47e452d206c64ec236647403680d54f4d2f4a21b60f1e9924d3a5c5610b608f27065abb71a45617dc8f3cce29abb2ce355465bb6dc9d9db174f2954b223d0153c7de8125961f3938b81a1aa4606542dd79175c2580b3bc96f83652d94bfb83f8085266874da40d33cbb483c6d2c5aecf6a2feefc09a2df43844933d963dc7dcd255b435f256a6798904aa553cd6728c160cb25886b39ab82c9505414113cbab885accef36064eee663d0c93f5a3dcfd25244e26c2ed97546fc1c4a7594032cccbe7aad804d376d01ca3f8b50a624e3840b20bc4a952791ed16067710099372c33d82c1d897233fef4519b94aefd5b0b1094ca5ec9dbb86de9ac084f9176c0cccc364c15598ca28c90429cdcb9be0659c2f62e8bd25642499849b4dbab7715d9bbc38d0994298c5f67b4030b82f23c083d87e5615e3703cf06b0ea0ef67348190851d44525bfba0fb812e8ca756275803391d00698afdf7e76f91c13002a2d82113f5ac271d20eb27587ffe4f7058aa45b5b0c36122fb346c423cc00541d8a7b834a1627a068d98f8e2cd858fc03584a735913215ea57a6&i=30+04+1789%0A03+03+1797%0A04+03+1797%0A05+03+1797%0A21+08+2019%0A14+04+1865%0A15+04+1865%0A03+03+1801%0A04+03+1801%0A01+01+1988%0A12+11+1991%0A31+12+1899&a=1&m=2) also featuring [Kevin Cruijssen's tests](https://codegolf.stackexchange.com/a/190609/527)
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.
] |
[Question]
[
Your challenge is given an input of a prison layout to work out whether any of the prisoners can escape.
**Input**
Input may be in any reasonable format such as a string, array, array of arrays etc. The input will consist of three characters, in this case `#`, `P` and space. The input will not necessarily contain all three characters.
* `#`: A wall
* `P`: A prisoner
* space: An empty space
An example input will look like:
```
#####
# #
# P #
# #
#####
```
**Output**
A truthy/falsey value of whether or not the prison is secure. The prison is only secure if it can hold **all** of the prisoners. If **any** prisoner can escape it is not secure.
A prisoner can escape if they are not fully enclosed by a wall. A diagonal joining is fully enclosed.
**Test cases**
```
############# Truthy
# P # P# #
# # # P #
#############
############# Truthy
# P P #
# # # P #
#############
############# Falsey
# P # P# #
# # # P #
########## ##
#### Truthy
# #
# #
# P ####
####
P Falsey
### Falsey
# #
# #
### P
```
[Answer]
## [Snails](https://github.com/feresum/PMA), 13 bytes
```
!(t\P(o\ ),o~
```
[Try it online!](https://tio.run/##K85LzMwp/v9fUaMkJkAjP0ZBUye/7v9/ZWTApawQoKCsoBAAxAognoICBAeAeDCgoKwMAA "Snails – Try It Online")
Prints `0` for insecure prisons and the size of the input's bounding box for secure prisons.
The idea is to ensure that we can't find a path from a `P` to an out of bounds cell (`~`) moving only orthogonally (`o`) through spaces. The `t` is a teleport so that regardless where we attempt the match it tries all possible starting positions to find a `P`.
[Answer]
# [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 485 480 474 470 421 408 bytes
The absolutely wrong tool and approach, but nonetheless...
* 7 bytes (and more) saved with the useful tips from TheLethalCoder.
* 4 bytes saved by returning an integer.
* 4 more bytes saved thanks (once again) to TheLethalCoder by replacing `' '` with `32` in the comparisons.
* LOTS of bytes saved by refactoring the code.
* 13 more bytes thanks to (guess who?) TheLethalCoder. :) I keep forgetting his tips and he keeps reminding me them.
```
m=>{var p='P';int a=m.Length,b=m[0].Length,i=0,j,x,y;var c=new System.Collections.Stack();for(;i<a;i++)for(j=0;j<b;j++)if(m[i][j]==p)c.Push(new[]{i,j});while(c.Count>0){var t=(int[])c.Pop();x=t[0];y=t[1];if(x<1|x>a-2|y<1|y>b-2)return 0;foreach(var v in new[]{-1,1}){var z=x>0&x<a-1&y>0&y<b-1;if(z&m[x+v][y]==32){m[x][y]=p;c.Push(new[]{x+v,y});}if(z&m[x][y+v]==32){m[x][y]=p;c.Push(new[]{x,y+v});}}}return 1;}
```
[Try it online!](https://tio.run/##5VJRa9swEH7vrzgaSC1iGzt7lBUYgT11YMhgD8YPiqok8mI5yEpqN/Vvz07JvC5QiunLVnYg605836fPpxN1ICojT4AhtryuITWqrvRCir2RN@74eP66qC23SsChUg/wlSvt1dYovc5y4GZdk9@4F4aLRVtbWYZf9lokYsNNlme5r7SdwQoYnEo2Ox64gR27S@8ongNnZXgv9dpu/CUrsyjvK8Uiv/Abv6WOIJiWj736vNpupbCq0nW4sFz88AhdVcajKuFUTSbEFQWLaJEsaYG1WnllpvKsyBnbERGm@3rjoWCWH5VfdIQ@btRWegKV9@g1ImeTlnnoMMsdodrhHQ2zaJC2uMU5RdEmiZ@bGQ@mzy1m7WwZTImRdm80RM6R5GLjOakDKA2XC4PYj7vLBU@smUXjJuFBPG4xa5NlEDvdp3GZNZNDnrVo@NOUHLE8Fzt6ZR4xfov2u56DIKS9zfER4jhd98tqTLsTvXntGefY4Worw@9GWXmvtPRWTgX6l73iXA@Ci9vRn3EbfqvmSPxsDG894r8ChxRGACkuGAQHuKx0EPwNM1fojhD6P3UD/lo3@nzwzw0Cwwt6APjSMGdmELh3/XEG6BwDBwj6IfogA/SOboz@oW5056w7/QQ "C# (.NET Core) – Try It Online")
Basically I expand the positions of the P's whenever a white space is around until it reaches (or not) the border of the layout.
Some licenses:
* I use a `char[][]` as the input for the layout.
* Returns `0` as insecure and `1` as secure.
[Answer]
# [Perl 5](https://www.perl.org/), 69 bytes
*-10 bytes thanks to [@Grimy](https://codegolf.stackexchange.com/users/6484/grimy).*
*-2 bytes thanks to [@Neil](https://codegolf.stackexchange.com/users/17602/neil).*
77 byte of code + `-p0` flags.
```
/
/;$_=s/(P| )(.{@{-}})?(?!\1)(?1)/P$2P/s?redo:!/\A.*P|P.*\Z|^P|P$/m
```
[Try it online!](https://tio.run/##fU7BCoJAEL3vV4zoQQPdCroYYUF1rDl0CmmxWlAwk3U9SPbttm4lBtWDffNmeG92ci7SSWMauarg5sOGEjq12KygNtbg2N5tfnPvdyewAyMcOXYwcihaY6RFIPj56hs0XHgDrNEbhPv6oIRFLw1jq82SMbKVMReQZHkpC5BxJOEUZXDkIEXCzz4hO1HKuPKJ2QcxAUFBU9sp1g/b7sNJ1lFa8OpLXiXQ/JuHNv88QE9Bo7MrCZ0mr3i7HeDt7r7H/iF6R4/VBJsf8wc)
Some *short* explanations:
The idea is to put a `P` everywhere the prisoners can go. If any `P` is on the first/last line, or the first/last column, then the prisoners can go there and therefor escape, which means the prison isn't secure.
`s/(P| )(.{@{-}})?(?!\1)(?1)/P$2P/s` replaces a space on the right of or bellow a `P` with a `P`, or a space on the left or on top of a `P`.
Finally, `/\A.*P|P.*\Z|^P|P$/m` checks if a line starts or ends with a `P`, or if there is a `P` on the first or the last line.
[Answer]
## JavaScript (ES6), ~~134~~ 133 bytes
Takes input as an array of arrays of characters. Returns `0` (insecure) or `1` (secure).
```
f=a=>a.map((r,y)=>r.map((c,x)=>c>'O'&&[-1,1,0,0].map((X,i)=>(R=a[y+1-'1102'[i]])&&R[X+=x]?R[X]<'!'?R[o=2,X]=c:0:o=0)),o=1)|o&2?f(a):o
```
### Test cases
```
f=a=>a.map((r,y)=>r.map((c,x)=>c>'O'&&[-1,1,0,0].map((X,i)=>(R=a[y+1-'1102'[i]])&&R[X+=x]?R[X]<'!'?R[o=2,X]=c:0:o=0)),o=1)|o&2?f(a):o
console.log(f([
[...'#############'],
[...'# P # P# #'],
[...'# # # P #'],
[...'#############']
]))
console.log(f([
[...'#############'],
[...'# P P #'],
[...'# # # P #'],
[...'#############']
]))
console.log(f([
[...'#############'],
[...'# P # P# #'],
[...'# # # P #'],
[...'########## ##']
]))
console.log(f([
[...'####'],
[...'# #'],
[...' # #'],
[...' # P ####'],
[...' ####']
]))
console.log(f([
[...'P']
]))
console.log(f([
[...'###'],
[...'# #'],
[...'# #'],
[...'### P']
]))
```
[Answer]
## JavaScript (ES6), 121 bytes
```
f=s=>s==(s=s.replace(eval('/( |P)([^]{'+s.search`
`+'})?(?!\\1)[ P]/'),'P$2P'))?!/^.*P|P.*$/.test(s)&!/^P|P$/m.test(s):f(s)
```
Takes input as a newline-delimited rectangular string. Returns 0 for insecure and 1 for secure. Based on my answer to [Detect Failing Castles](https://codegolf.stackexchange.com/questions/109015), although it would be more efficient to test for an escaped prisoner at each step, rather than once they'd finished exploring the prison.
[Answer]
# [APL (Dyalog Classic)](https://www.dyalog.com/), 40 bytes
```
{⊃2≠(××{1⊃⌈/⍵,⍉⍵}⌺3 3)⍣≡(⌽1,⍉)⍣4⊢'# '⍳⍵}
```
[Try it online!](https://tio.run/##nU3LasJQEN3frxjI4ipUNNWVX3F/4aKkhAZSGjcibmxRk@aKLiS7onbrrrgRXOVPzo@kcxOpdiEFB@ZxzpyZo1@CRn@og/Cp0Qt0FPm9Aou1H2K6bBUe1xGSt0fEm1qe5dnIZYR03oQ5PMDE3MZIj21q12G@EG9rSE@u3VjcQbKTDkmYbyssikH5zxwQ71559HivLZVnzEQ8wXx2MZ@V35NJhI93TFelidl3paf9QGomZfgsx0IMyBXOdQiHFDlEipMsIqpSWfRHeeOYoyz/HrfucqZr50ol6NwqseWJLi7q14zl5@Q/SvwA "APL (Dyalog Classic) – Try It Online")
`'# '⍳⍵` encode `'#'`, `' '`, `'P'` as 0 1 2
`(⌽1,⍉)⍣4` surround with 1s
`(××{1⊃⌈/⍵,⍉⍵}⌺3 3)⍣≡` max-of-neighbours flood fill of non-zero cells
`⊃2≠` do we not have a 2 at the top left?
[Answer]
# Octave, ~~64~~ 55 bytes
```
@(a,z=padarray(a,[1 1]))~nnz(bwfill(z==35,1,1,4)&z>35);
```
[Try it online!](https://tio.run/##y08uSSxL/f/fQSNRp8q2IDElsagosRLIiTZUMIzV1KzLy6vSSCpPy8zJ0aiytTU21TEEQhNNtSo7Y1NN6/@JecUa0Xp6elzqyshAHchXCFBQVlAIAGIFCF9BAYIDIHw4UACqj9Xk@g8A "Octave – Try It Online")
or
[Verify all test cases!](https://tio.run/##pY5BCsIwFET3OcVAwCTQTaldScQjZF@6@NYWhFClVMWIXj1GU2qLG8EJP2Qg8@Yfqp7Otfee9I0Vgk8lwASHAQdMGHDx8kAcE/0sULIvRkQEva8/EL9tgSlCYNSQCX8xPmI8NgCfdiNKTDXgBOa4uMhQjxBi9xVjVW1tc2rlRlLi9JF21HV0DaZIkZZKPdrWye2l2VsrndZZnqThLNXCrbNcJaT8Ew "Octave – Try It Online")
Explanation:
```
z=padarray(a,[1 1]) %add a boundary(of 0s) around the scene
F = bwfill(z==35,1,1,4) %flood fill the prison starting from the boundary
~nnz(F&z>35); %if position of at least a prisoner is filled then the prison is not secure
```
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 35 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)CP437
```
ä¬my■╡╤▲l@┤êr*⌠\¶ƒläå─▄¶√¿ [Uy⌠Só4↔
```
[Try it online!](https://staxlang.xyz/#c=%C3%A4%C2%ACmy%E2%96%A0%E2%95%A1%E2%95%A4%E2%96%B2l%40%E2%94%A4%C3%AAr*%E2%8C%A0%5C%C2%B6%C6%92l%C3%A4%C3%A5%E2%94%80%E2%96%84%C2%B6%E2%88%9A%C2%BF+%5BUy%E2%8C%A0S%C3%B34%E2%86%94&i=%23%23%23%23%23%23%23%23%23%23%23%23%23%0A%23+P+%23++P%23+++%23%0A%23+++%23+++%23+P+%23%0A%23%23%23%23%23%23%23%23%23%23%23%23%23%0A%0A%23%23%23%23%23%23%23%23%23%23%23%23%23%0A%23+P++++P++++%23%0A%23+++%23+++%23+P+%23%0A%23%23%23%23%23%23%23%23%23%23%23%23%23%0A%0A%23%23%23%23%23%23%23%23%23%23%23%23%23%0A%23+P+%23++P%23+++%23%0A%23+++%23+++%23+P+%23%0A%23%23%23%23%23%23%23%23%23%23+%23%23%0A%0A%23%23%23%23++++++++++%0A%23+++%23%0A+%23+++%23%0A++%23+P+%23%23%23%23%0A++%23%23%23%23%0A%0AP+++++++++++++%0A%0A%23%23%23+++++++++++%0A%23+%23%0A%23+%23%0A%23%23%23+P&a=1&m=1)
Surely golfing language without an internal to handle path-finding can do this as well!
## Explanation
Uses the unpacked format to explain.
```
zLz]Y+Mys+y+{{{" P|P ""PP"Rm}Y!My!Mgphh' =
zLz]Y+Mys+y+ Surround the original matrix with four borders of whitespaces
{ gp Iterate until a fixed point is found, return the single fixed point
{ }Y! Store the block in register Y and execute it
{" P|P ""PP"Rm For each row, flood every space adjacent to a P with P.
My! Transpose the matrix and do the flooding again
hh' = The final matrix has a space on the upper left corner that has not been flooded by P
```
[Answer]
# SmileBASIC, ~~154~~ 146 bytes
I was hoping an answer using flood fill would be shorter than this.
```
DEF S P
FOR J=0TO 1X=1Y=1FOR I=0TO LEN(P)-1GPSET X,Y,-(P[I]=="#")GPAINT X,Y,-1,-J*(P[I]>@A)X=X*(P[I]>"31")+1INC Y,X<2NEXT
NEXT?!GSPOIT(0,0)GCLS
END
```
Replace `31` with the corresponding ASCII character.
] |
[Question]
[
No one is quite certain what the emoticon `>:U` is intended to represent, but many scholars believe it looks like an angry [duck](https://en.wikipedia.org/wiki/Duck). Let's assume that's the case.
## Task
Given an integer *n* between 0 and 3 inclusive, print or return
```
quack
```
if *n* = 0,
```
>:U
```
if *n* = 1,
```
U U
> : U U
> U U
> : U U
UUU
```
if *n* = 2, or
```
>:U >:U
>:U >:U >:U
>:U >:U >:U >:U
>:U >:U >:U
>:U >:U >:U
>:U >:U >:U
>:U >:U >:U >:U
>:U >:U >:U
>:U>:U>:U
```
if *n* = 3.
You can assume the input will always be valid. There should be no leading space in the output, but any amount of trailing space is fine. Ducks (with the possible exception of @cobaltduck) have no tolerance for loopholes. Shortest code in bytes wins.
[Answer]
## Java, 303 286 bytes
Saved 17 bytes thanks to @VoteToClose!
Not actually meant to be the shortest, I just thought it would be fun to try in Java.
Creates a list of string variables representing common strings, then creates an array of all the outputs, then prints the right one.
```
String a(int y){String n="\n",d=">:U",A=" ",B=A+A,C=B+B,D=C+C,a="U"+B+" U"+n,G=D+A,H=C+B,c=d+G+d+n,E=B+A,F=C+E;String[]z={"quack",d,C+A+a+">"+B+": "+a+" >"+E+a+">"+B+": "+a+C+B+"UUU",D+D+B+c+d+D+F+c+B+A+d+F+d+B+c+H+d+G+c+G+d+H+c+H+d+G+c+E+d+F+d+B+c+d+D+F+c+D+D+C+A+d+d+d};return z[y];}
```
Ungolfed:
```
String a(int y) {
String n = "\n", d = ">:U", A = " ", B = A + A, C = B + B, D = C + C,
a = "U" + B + " U" + n, G = D + A, H = C + B, c = d + G + d + n,
E = B + A, F = C + E;
String[] z = { "quack", d, C + A + a + ">" + B + ": " + a + " >" + E + a + ">" + B + ": " + a + C + B + "UUU", D + D + B + c + d + D + F + c + B + A + d + F + d + B + c + H + d + G + c + G + d + H + c + H + d + G + c + E + d + F + d + B + c + d + D + F + c + D + D + C + A + d + d + d };
return z[y];
}
```
This is my first answer on this site, so please tell me if I have done something wrong.
[Answer]
# CJam, ~~108~~ ~~90~~ 85 bytes
```
"quack"">:U":D"scT¦{$ì"{269b22bSf*D}:F~[ZYB].*s.+s5/"ÿ3nÜïS{JÐø¦yûn"F*33/z]ri=zN*
```
Note that some characters are unprintable. [Try it online!](http://cjam.tryitonline.net/#code=InF1YWNrIiI-OlUiOkQic8KfY1TCpnskw6wGInsyNjliMjJiU2YqRH06Rn5bWllCXS4qcy4rczUvIsO_DDNuw5zDr1N7SsOQw7jCpnnDu24RIkYqMzMvel1yaT16Tio&input=Mw)
### Background
The first two outputs are incompressible in CJam.
Compressing the last output is straightforward. After stripping all linefeeds, we can split the resulting string at occurrences of `>:U`, and compute the length of each resulting string of spaces.
That results in the array
```
[18 9 0 15 9 3 7 2 9 6 9 9 9 6 9 6 9 9 3 7 2 9 0 15 9 21 0 0 0]
```
which we can store efficiently by converting it from base 22 to base 269, yielding the digits
```
[255 12 51 110 220 239 83 123 74 208 248 166 121 251 110 17]
```
Since each digit is less than **256**, we can store it as a single byte.
Finally, compressing the third output becomes easier if we transpose lines and columns:
```
> >
>
: :
UUUU
U
U
U
UUUU
```
Counting once more the spaces between non-whitespace characters, we get the array
```
[1 1 3 8 1 6 0 0 0 5 4 4 0 0 0 0 0]
```
which becomes
```
[115 159 99 84 166 123 36 236 6]
```
when transcoded from base 22 to base 269.
### How it works
```
"quack" e# Push the first output.
">:U":D e# Push the second output, and save it in D.
e# Push [115 159 99 84 166 123 36 236 6] as bytes.
"scT¦{$ì"
{ e# Define a code block:
269b22b e# Transcode from base 269 to base 22.
Sf* e# Replace each digit with a string of that many spaces.
D e# Push D.
} e#
:F~ e# Save the block in F. Execute it.
[ZYB] e# Push [3 2 11].
.* e# Vectorized repeat; push [">>>" "::" "UUUUUUUUUUU"].
s e# Flatten the array of strings.
.+ e# Append the nth character to the nth string of spaces.
s5/ e# Flatten and split into chunks of length 5.
e# Push [255 12 51 110 220 239 83 123 74 208 248 166 121 251 110 17] as bytes.
"ÿ3nÜïS{JÐø¦yûn"
F e# Execute F.
* e# Join the resulting array of strings of spaces, separating by ">:U".
33/ e# Split into chunks of length 33.
z e# Zip; transpose rows with columns.
] e# Wrap the entire stack in an array.
ri e# Read a token from STDIN and interpret it as an integer.
= e# Retrieve the element at the corresponding index.
z e# Zip; transpose rows with columns or map "string" to ["string"].
N* e# Join, separating by linefeeds.
```
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), ~~162~~ ~~159~~ 157 bytes
## Code
Dammit, way too long, but it's at least something:
```
">:U"VI3Qið16×7166b1ð:0Y:DUJ,Yð13×JD?X,3838b1ð:0Y:D?X,16255b1ð:0Y:D?X,16367b1ð:0Y:4F?X,}ð21×Y3×J,}¹2Qið4×" U U"©J,"> :"®JD," > "?®,,ð6×'U3×J,}¹iY,}"quack
```
[Try it online!](http://05ab1e.tryitonline.net/#code=Ij46VSJWSTNRacOwMTbDlzcxNjZiMcOwOjBZOkRVSixZw7AxM8OXSkQ_WCwzODM4YjHDsDowWTpEP1gsMTYyNTViMcOwOjBZOkQ_WCwxNjM2N2Ixw7A6MFk6NEY_WCx9w7AyMcOXWTPDl0osfcK5MlFpw7A0w5ciIFUgICBVIsKpSiwiPiAgOiLCrkpELCIgPiAgIj_Criwsw7A2w5cnVTPDl0osfcK5aVksfSJxdWFjaw&input=Mw)
---
## Explanation
The first part of the code exists of `">:U"V`, which sets `Y` to that string. After that, we just check if the input is equal to 3. That is done at the `I3Qi` part. If equal, we print the giant magpie:
### N = 3
It first starts with `ð16×` which just pushes 16 space characters. After that, there is a number `7166b`. This covers the `">:U "` part, with a little help from Retina :). I used [this script](http://retina.tryitonline.net/#code=IAoxCj46VQow&input=ICAgICAgICAgPjpVICAgIA) to convert the string to a binary number. After that, we get to the `1ð:0Y:` part, which replaces every `1` with a space character and every `0` with `Y`, which has been set to `>:U`. After that, we `D`uplicate this string, store it in `X` using `U` and `J`oin the stack. We pop this using `,`, which prints the full string with a newline. All the others after that are all based on the same principe. The if statement ends at the second `}`.
The full conversion can be found [here](http://retina.tryitonline.net/#code=IAoxCj46VQow&input=ICAgICAgICAgICAgICAgICAgPjpVICAgICAgICAgPjpVCj46VSAgICAgICAgICAgICAgID46VSAgICAgICAgID46VQogICA-OlUgICAgICAgPjpVICA-OlUgICAgICAgICA-OlUKICAgICAgPjpVICAgICAgICAgPjpVICAgICAgICAgPjpVCiAgICAgICAgID46VSAgICAgID46VSAgICAgICAgID46VQogICAgICA-OlUgICAgICAgICA-OlUgICAgICAgICA-OlUKICAgPjpVICAgICAgID46VSAgPjpVICAgICAgICAgPjpVCj46VSAgICAgICAgICAgICAgID46VSAgICAgICAgID46VQogICAgICAgICAgICAgICAgICAgICA-OlU-OlU-OlU).
### N = 2
We now check if the input is equal to 2. This is done at the `¹2Qi` part. After that, if equal, we push the space character 4 times using `ð4×`. After that, we push the `" U U"` string and store it using `©` (idea blatantly stolen from Jelly :p). We again `J`oin the stack and print this with a newline. After that, we push the `"> :"` string, retrieve the `" U U"` using `®`, `J`oin the stack and `D`uplicate this string and print these both on the same line.
Short quiz, what will this do: `" > "?®,`?
After printing the above string, we get the duplicate of the second line of the face, and print this (since it's the same as the 2nd line).
The last part covered by this case is:
```
ð6×'U3×J,
ð6× # Push the space character × 6
'U3× # Push the "U" character three times
J, # Join and print pop with a newline
```
### N = 1
This one is easier to explain:
```
¹1QiY
¹1Qi # Check if the input is equal to 1
Y # Push the magpie face
# This is then implicitly printed
```
### N = 0
```
¹0Qi"quack
¹0Qi # Check if the input is equal to 0
"quack # Weird sound what magpies make
# Implicitly printed
```
[Answer]
# JavaScript (ES6), 163 bytes
```
var solution =
n=>["quack",d=">:U",`5U3U
>2:1U3U
1>3U3U
>2:1U3U
6UUU`,`99090
096090
30702090
609090
906090
609090
30702090
096090
993000`][n].replace(/\d/g,c=>+c?" ".repeat(c):d)
```
```
<input type="number" oninput="R.textContent=solution(+this.value)"><pre id="R"></pre>
```
## Explanation
Uses my go-to compression with JavaScript: run-length encoding. The digits `1` to `9` map to that many spaces, `0` maps to the angry duck face, and any other character stays the same.
[Answer]
# [Vitsy](http://github.com/VTCAKAVSMoACE/Vitsy), ~~172~~ ~~171~~ 159 bytes
Oh, geez. If I wanted something to show off the power of methods, I got it.
```
' 'V1+m
'kcauq'Z
'U:>'Z
58m5m6m' > 'Z5m6m'UUU'68m
f3+bm9mamcm98m2m6bmcmam9mf6+8m3\[2m]
a'U U'Z
' : >'Z5m
Z2m98ma2m
\VZ
2mfbm
VVVZ2m78m2mVV7m
8m7m
68m2m9bm
```
[Try it Online!](http://vitsy.tryitonline.net/#code=JyAnVjErbQona2NhdXEnWgonVTo-J1oKNThtNW02bScgICA-ICdaNW02bSdVVVUnNjhtCmYzK2JtOW1hbWNtOThtMm02Ym1jbWFtOW1mNis4bTNcWzJtXQphJ1UgICBVJ1oKJyA6ICA-J1o1bQpaMm05OG1hMm0KXFZaCjJtZmJtClZWVloybTc4bTJtVlY3bQo4bTdtCjY4bTJtOWJt&input=&args=Mw)
How this works is by calling various methods throughout itself. The explanation is below:
```
' 'V1+m
' 'V Save character literal ' ' as a permanent variable.
1+ Add one to the top item of the stack (input + 1)
m Go to that index of code.
'kcauq'Z
'kcauq' Push 'quack' to the stack.
Z Output everything in the stack as a char.
'U:>'Z
'U:>'Z Ouput ">:U" with the same method as the previous line.
Now on to some more... interesting lines.
58m5m6m' > 'Z5m6m'UUU'68m
5 Push space, push 4
8m Call the 8th line index.
As we will soon see, the 8th line index duplicates the space
the number of times specified by the number just before the call
(4 in this case)
5m Call the 5th line index.
The 5th line index outputs the 'U U' and a newline.
6m Call the 6th line index.
The 6th line index outputs '> : U U' and a newline.
' > 'Z Output ' > '.
5m6m Same method calls as before.
'UUU' Push 'UUU'.
68m Push 6, then call the 8th line index. This gives us the correct padding.
f3+bm9mamcm98m2m6bmcmam9mf6+8m3\[2m]
f3+ Push 18.
bm Call the 11th line index.
The 11th line index calls the 8th line index (which we've already seen
in action) and then the 7th line index, which you can find and explanation
for below (it does a **lot**)
9m Call the 9th line index.
The 9th line index outputs '>:U >:U >:U' (explanation lower)
am Call the 10th line index.
...I'm gonna stop explaining these and just tell you to go to the lines now. :P
cm Call the 12th line index.
9 Push space, push 9.
8m Call the 8th line index (explained below and before).
2m Call the 2nd line index.
6 Push 6.
bm Call the 11th line index. We've finished up to '>:U >:U >:U' now.
cm You guessed it! Call the 12th line index. (explanation below)
am Call the 10th line index. (explanation below)
9m Call the 9th line index. (explanation below)
f6+ Push space, push ~~19~~ 21.
8m Call the 8th line index. (explanation below)
3\[2m] Call the 2nd line index thrice.
All of the rest of these methods are supporting methods now.
a'U U'Z Output 'U U' followed by a newline.
' : >'Z5m Output '> : U U' followed by a newline.
Z2m98ma2m
Z Output everything currently in the stack.
2m Call the 2nd line index.
9 Push space, push 8.
8m Call the 8th line index. (explained below)
a Push a newline to the stack.
2m Call the 2nd line index.
This handles the biggest angry duck face's faces showing the eyebrows and eyes.
\VZ
\V Push space as many times as the top item specifies.
Z Output everything in the stack.
2mfbm
2m Call the 2nd line index.
f Push space, push 14.
bm Go to the 11th line index.
This handles the mouth and some parts of the eyebrows of the biggest duck face.
VVVZ2m78m2mVV7m
VVVZ Output 3 spaces (and whatever was pushed before it)
2m Call the 2nd line index.
7 Push space, push 6.
8m Call the 8th line index. (explained... above)
2m Call the 2nd line index.
VV Push 2 spaces.
7m Call the 7th line index.
8m7m This is pretty damn self-explanatory if you've read this far.
68m2m9bm
6 Push space, push 5.
8m Call the 8th line index.
2m Call the 2nd line index.
9 Push space, push 9.
bm Call the 11th line index.
```
This code is ridiculous. It's verbose form is:
```
toggle single quote;
;
toggle single quote;
save top as permanent variable;
push 1;
add top two;
goto top method;
:toggle single quote;
k;
push 12;
push 10;
flatten top two stacks;
q;
toggle single quote;
output stack as chars;
:toggle single quote;
U;
clone current stack;
go forward;
toggle single quote;
output stack as chars;
:push 5;
push 8;
goto top method;
push 5;
goto top method;
push 6;
goto top method;
toggle single quote;
;
;
;
go forward;
;
toggle single quote;
output stack as chars;
push 5;
goto top method;
push 6;
goto top method;
toggle single quote;
U;
U;
U;
toggle single quote;
push 6;
push 8;
goto top method;
:push 15;
push 3;
add top two;
push 11;
goto top method;
push 9;
goto top method;
push 10;
goto top method;
push 12;
goto top method;
push 9;
push 8;
goto top method;
push 2;
goto top method;
push 6;
push 11;
goto top method;
push 12;
goto top method;
push 10;
goto top method;
push 9;
goto top method;
push 15;
push 6;
add top two;
push 8;
goto top method;
push 3;
repeat next instruction set top times;
begin recursive area;
push 2;
goto top method;
end recursive area;
:push 10;
toggle single quote;
U;
;
;
;
U;
toggle single quote;
output stack as chars;
:toggle single quote;
;
clone current stack;
;
;
go forward;
toggle single quote;
output stack as chars;
push 5;
goto top method;
:output stack as chars;
push 2;
goto top method;
push 9;
push 8;
goto top method;
push 10;
push 2;
goto top method;
:repeat next instruction set top times;
save top as permanent variable;
output stack as chars;
:push 2;
goto top method;
push 15;
push 11;
goto top method;
:save top as permanent variable;
save top as permanent variable;
save top as permanent variable;
output stack as chars;
push 2;
goto top method;
push 7;
push 8;
goto top method;
push 2;
goto top method;
save top as permanent variable;
save top as permanent variable;
push 7;
goto top method;
:push 8;
goto top method;
push 7;
goto top method;
:push 6;
push 8;
goto top method;
push 2;
goto top method;
push 9;
push 11;
goto top method;
```
[Answer]
# Japt, ~~116~~ ~~105~~ ~~102~~ ~~99~~ 96 bytes
```
["quack""c)`+«öÂ[@=^Gñ`1]o2"mc r'4#¿+R "4z>2:z >2z>2:z6UUU"rz" U3U
" '1]®r'1">:U" r"%d"_SpZ}ÃgU
```
Contains an unprintable. [Test it online!](http://ethproductions.github.io/japt?v=master&code=WyJxdWFjayIiYylgK6v2wltAPV4fR/FgMV1vMiJtYyByJzQjvytSICI0ej4yOnogPjJ6PjI6ejZVVVUicnoiIFUzVQoiICcxXa5yJzEiPjpVIiByIiVkIl9TcFp9w2dV&input=Mw==)
### How it works
The first two strings are not compressed at all. The third is compressed simply by replacing each runs of spaces with its length, then `" U3U"` with `"z"`. The last one is more complex:
1. Replace each run of 2-9 spaces with its length.
2. Replace `>:U` with `1`.
3. Replace `191\n` with `4`. (`4` isn't used anywhere else in the string.)
4. Map each valid byte code (`10`-`255`, or `0A`-`FF`) to the character with that char code.
The resulting string is only ~~21~~ 19 bytes long, but the decompression takes up another ~~31~~ 29.
After decompressing the strings, we simply take the item at position `U`, the input. (The array is arranged `[0,3,2,1]` because there's a bug which makes it count from the *end* of the array instead of the beginning.)
```
[ // Create an array of the following:
"quack" // "quack".
"c)`+«öÂ[@=^Gñ`1]o2" // Take this string (contains an unprintable).
// Map each char to its char code.
// This produces "994196431712461949164619431712419649931112".
r'4#¿+R // Replace each "4" with the char code of "¿" (191) + a newline.
"4z>2:z >2z>2:z6UUU" // Take this string.
rz" U3U\n" // Replace each "z" with " U3U\n".
'1 // "1".
]
® Ã // Map each item by this function:
r'1">:U" // Replace each "1" with ">:U".
r"%d"_SpZ} // Replace each remaining digit Z with Z spaces.
gU // Get the item at index -U, wrapping.
// (This should just be U, but there's a bug which negates it.)
```
[Answer]
# [MATL](https://esolangs.org/wiki/MATL), ~~283~~ 182 bytes
***101*** bytes saved thanks to @Adnan!
This uses decimal numbers to encode indices `0`...`3` to the four characters for cases 2 and 3. The decimal numbers could perhaps be compressed using base-64 encoding, but quack!
For the case 3 a very nice trick suggested by @Adnan is used: define binary sequences to encode each row, where `0` and `1` correspond to space and `>:U` respectively.
```
~?'quack'}G1=?'>:U'}G2=?' :>U'12336 8466480h2109488h8466480h4032h4YA47-)}268697600 67174401h16795656h67174464h67174912h67174464h16795656h67174401h14680064h"@BP48+]Xh49'>:U'YX48 32YXc
```
[**Try it online!**](http://matl.tryitonline.net/#code=fj8ncXVhY2snfUcxPT8nPjpVJ31HMj0_JyA6PlUnMTIzMzYgODQ2NjQ4MGgyMTA5NDg4aDg0NjY0ODBoNDAzMmg0WUE0Ny0pfTI2ODY5NzYwMCA2NzE3NDQwMWgxNjc5NTY1Nmg2NzE3NDQ2NGg2NzE3NDkxMmg2NzE3NDQ2NGgxNjc5NTY1Nmg2NzE3NDQwMWgxNDY4MDA2NGgiQEJQNDgrXVhoNDknPjpVJ1lYNDggMzJZWGM&input=Mw)
[Answer]
# Cinnamon Gum, 76 bytes
```
0000000: 6c33 502b 2c4d 4cce b636 54b3 b30a b536 l3P+,ML..6T....6
0000010: 5253 0081 5010 e6b2 5350 b082 3215 ecb0 RS..P...SP..2...
0000020: 8a42 1487 865a 1bab 2960 00a0 79c8 6c2e .B...Z..)`..y.l.
0000030: 2026 a002 4221 0430 55c0 5938 cd40 9720 &..B!.0U.Y8.@.
0000040: 6c06 6177 90e9 17ac 4102 4100 l.aw....A.A.
```
Non-competing since Cinnamon Gum was created after this challenge.
[Try it online.](http://cinnamon-gum.tryitonline.net/#code=MDAwMDAwMDogNmMzMyA1MDJiIDJjNGQgNGNjZSBiNjM2IDU0YjMgYjMwYSBiNTM2ICBsM1ArLE1MLi42VC4uLi42CjAwMDAwMTA6IDUyNTMgMDA4MSA1MDEwIGU2YjIgNTM1MCBiMDgyIDMyMTUgZWNiMCAgUlMuLlAuLi5TUC4uMi4uLgowMDAwMDIwOiA4YTQyIDE0ODcgODY1YSAxYmFiIDI5NjAgMDBhMCA3OWM4IDZjMmUgIC5CLi4uWi4uKWAuLnkubC4KMDAwMDAzMDogMjAyNiBhMDAyIDQyMjEgMDQzMCA1NWMwIDU5MzggY2Q0MCA5NzIwICAgJi4uQiEuMFUuWTguQC4gCjAwMDAwNDA6IDZjMDYgNjE3NyA5MGU5IDE3YWMgNDEwMiA0MTAwICAgICAgICAgICAgbC5hdy4uLi5BLkEuCg&input=Mw)
## Explanation
The first byte `l` specifies the mode: in this case it tells Cinnamon Gum to enter lookup table mode. Cinnamon Gum then decompresses the rest of the string (which has been compressed with `zopfli --deflate`) into this:
```
0&quack;1&>:U;2& U U
> : U U
> U U
> : U U
UUU;3& >:U >:U
>:U >:U >:U
>:U >:U >:U >:U
>:U >:U >:U
>:U >:U >:U
>:U >:U >:U
>:U >:U >:U >:U
>:U >:U >:U
>:U>:U>:U
```
It then splits by `;`, puts each key-value pair (with `&` as delimiter) in a dictionary, and outputs `dictionary[input]`.
[Answer]
# JavaScript ES6, ~~232~~ ~~223~~ ~~203~~ 188 bytes
Saved ~~29~~ 44 bytes thanks to ETHproductions!
```
n=>[`quack`,r=`>:U`,` U U
> : U U
> U U
> : U U
UUU`,`00022
10022
0100 1 12
00122
20012
00122
0100 1 12
10022
0000211`.replace(/\d/g,N=>[g=` `,r,g+g+g+r][N])][n]
```
## Test it out!
```
A=n=>[`quack`,r=`>:U`,` U U
> : U U
> U U
> : U U
UUU`,`0000002
1000002
0100 1 2
0010002
0001002
0010002
0100 1 2
1000002
0000000111`.replace(/\d/g,N=>[g=` `,r,r+g+g+g+r][N])][n]
(a.onchange=a.onkeydown=a.onkeyup=function(){
o.innerHTML = A(+a.value);
})();
```
```
*{font-family:"Consolas",monospace;font-size:20px;white-space:pre-wrap}input{left:50%;width:150px;position:absolute;text-align:center;margin-left:-75px;}#o{margin:15px;border:1px solid #00ACDC;padding:15px;}
```
```
<input id=a type=number value=0 min=0 max=3><br><div id=o></div>
```
[Answer]
# Brainfuck 802 bytes
I know its not very optimal to make this challenges in bf... but its very fun :)
Code:
```
,>-[<->-----]<+++>>+[--[<]>>+<-]>++[-<++<+>>]>-[<+>+++++++++]>-[<+>---]++++++++++<<+<<+<<[-[-[[-]>>..................>.>.>.<<<.........>.>.>.>.<<<.>.>.<<<...............>.>.>.<<<.........>.>.>.>.<<<<...>.>.>.<<<.......>.>.>.<<<..>.>.>.<<<.........>.>.>.>.<<<<......>.>.>.<<<.........>.>.>.<<<.........>.>.>.>.<<<<.........>.>.>.<<<......>.>.>.<<<.........>.>.>.>.<<<<......>.>.>.<<<.........>.>.>.<<<.........>.>.>.>.<<<<...>.>.>.<<<.......>.>.>.<<<..>.>.>.<<<.........>.>.>.>.<<<.>.>.<<<...............>.>.>.<<<.........>.>.>.>.<<<<.....................>.>.>.<<.>.>.<<.>.>.>>>+<]>-[>.....>>>.<<<...>>>.>.<<<.<..>>.<<.>>>.<<<...>>>.>.<<<<.>.<...>>>.<<<...>>>.>.<<<.<..>>.<<.>>>.<<<...>>>.>.<<<<......>>>...>>>-+]<>+<]>-[ >>.>.>.<<<< +]<>+<]>-[>[>]-[+>+++++[<]>+]>.++++.>+[-[---<]>>-]<-.++.++++++++.>-+]
```
[Try it yourself](https://tio.run/##tVNNC8IwDP0ru8f04jXkj5QeVBBE8CD4@@t7a93GqlMKpmNLXvLSr7fj/XC5nR@na84712jqSksmIu4SFViCY5pcEAI3JBJrBUi1GpM5YWJWnqgYEQ08NObjMLMVUrB17geOvSlYxF@5G/23WW3Zn@bq3V3vaX6@tOXHKRLKoFwywtqTXvG5wFLfJtnEunjTdONbJVldyODzNoYZ9uhJY9UuxQ3xBvqBcofglYLHH6BAw0vLgZ1z3j8B)
"Beautiful version":
```
READ NUMBER
,>-[<->-----]<+++
WRITE LETTERS FROM SPACE TO LINE JUMP
>>+[--[<]>>+<-]>++[-<++<+>>]
>-[<+>+++++++++]
>-[<+>---]
++++++++++
<<+<<+<<
START A SWITCH CASE
[-
[-
[[-]
CASE 3
>>..................>.>.>.<<<.........>.>.>.>.
<<<.>.>.<<<...............>.>.>.<<<.........>.>.>.>.
<<<<...>.>.>.<<<.......>.>.>.<<<..>.>.>.<<<.........>.>.>.>.
<<<<......>.>.>.<<<.........>.>.>.<<<.........>.>.>.>.
<<<<.........>.>.>.<<<......>.>.>.<<<.........>.>.>.>.
<<<<......>.>.>.<<<.........>.>.>.<<<.........>.>.>.>.
<<<<...>.>.>.<<<.......>.>.>.<<<..>.>.>.<<<.........>.>.>.>.
<<<.>.>.<<<...............>.>.>.<<<.........>.>.>.>.
<<<<.....................>.>.>.<<.>.>.<<.>.>.>>
>+<]>-[
CASE 2
>.....>>>.<<<...>>>.>.
<<<.<..>>.<<.>>>.<<<...>>>.>.
<<<<.>.<...>>>.<<<...>>>.>.
<<<.<..>>.<<.>>>.<<<...>>>.>.
<<<<......>>>...>>>-
+]<
CASE 1
>+<]>-[ >>.>.>.<<<< +]<
>+<]>-[
CASE 0 (CREATE NEW LETTERS)
>[>]-[+>+++++[<]>+]>.++++.>+[-[---<]>>-]<-.++.++++++++.>-
+]
```
[Answer]
# GML, 265 bytes
A port of @kittycat3141's excellent answer, with the suggestion to golf it further with two new variables (which I named G and H) by @VoteToClose. I also managed to shorten it further with GML's relatively loose syntax.
```
d=">:U"A=" "B=A+A;C=B+B;D=C+C;G=D+A;H=C+B;a="U"+B+" U"+"#"c=d+G+d+"#"E=B+A;F=C+E;x[0]="quack"x[1]=d;x[2]=C+A+a+">"+B+": "+a+" >"+E+a+">"+B+": "+a+H+"UUU"x[3]=D+D+B+c+d+D+F+c+B+A+d+F+d+B+c+H+d+G+c+G+d+H+c+H+d+G+c+E+d+F+d+B+c+d+D+F+c+D+D+C+A+d+d+d;return x[argument0]
```
[Answer]
# JavaScript (ES6), ~~151~~ 150 bytes
```
n=>(g=s=>(l=s.split(--k),k?g(l.join(l.pop())):l[n]))(`quack030285 >256UUU06273646371631
63436766133162328 3>:U47236 3831
5U2U
>8: U2U
622711
8 `,k=9)
```
[Try it online!](https://tio.run/##XcqxboMwFIXhnae4Q6XYIiDsC9cuqekbdPOURgKRgAiWTeO0S5Rnp3Ttcr7hP9fup4v9bVrumQ/nyzqY1ZuGjSZu60zM4@KmO8uyme/n95G5/Bomv7GEhXHOa3f0J85Z@/Xd9XOBhdQVNLIia21BUiGVhEoQioSwRFJEAlGQRKkBm9qWSiIB6u1QWWmTRtfwJ0mphEg0QLufzStfh3BjHgwUB/DwBuVGmnJ4JAB98DG4S@7CyNrjh3l5@Oep5Yd/aWCeQwq7T7/b2nP9BQ "JavaScript (Node.js) – Try It Online")
[Answer]
# [///](https://esolangs.org/wiki////), 130 bytes
```
/0/quack//e/UrU
//d/m
//m/br1//b/rr//r/ //1/>:U//2/r e> : e >re> : ebUUU//3/bbb1d1bmdr1b 1 1db1mdmb1db1mdr1b 1 1d1bmdbbm11/
```
[Try it online!](https://tio.run/##PYoxDgIxEAN7XuEfDAvdFflFHnAmkU6CFOyJ94dDIBp75PH@WPet73Ny5vlab3fo1KwnaIwjB84AkwmJJAjKUuFCSr1Ii7pK/si1Hu6K7Wjh0TKskKI5Rhv@9n/8POwRwYz5Bg "/// – Try It Online")
] |
[Question]
[
Many people consider RPS to be a game of chance. If both players play unpredictably, the best strategy is to play randomly. However, let's introduce a bit of predictability to it.
Each bot will have a chance to tell the other bot what it's going to play simultaneously. Then there is a pause in which each bot will know what the other player announced. If it plays that weapon it announced it will score one point in addition to its points for a win loss or draw.
A win is worth two points, a draw, one point, and a loss 0 points.
```
Honest Bot Dishonest
Win 3 2
Draw 2 1
Loss 1 0
```
It is in your best interest to be honest (but also to make sure your opponent does not believe you).
The matches will be played in a round robin format, and the objective will be to maximise your own total score across the matches you play.
## I/O Format:
* Your bot will be a Python 2.7 function that takes 4 arguments, and must have a unique name (which will be used to represent your submission).
* The first two arguments will always be, in order: the opponent's past moves, followed by your past moves. These will be a list in order from first to most recent round, with each index containing a list with the move the opponent claimed they would make, followed by the move they actually made.
* The next two arguments will allow your bot to determine if this is an "honest" round or a "real" round. If it is an "honest" round, they will both be None. If it is a "real" round, they will be, in order, the move your opponent declared they would make, followed by the move you declared you would make.
* All arguments or portions of arguments that represent moves will use "R", "P", and "S" to represent rock, paper, and scissors, respectively.
* Your function should return either an "R" for rock, a "P" for paper, or an "S" for scissors. Bots that have the ability to return other values will be disqualified.
* Each bot will be run against every other bot 200 times, and itself 100 times. The goal is to be the bot with the most points at the end of the competition.
* In regards to discussion in the comments, submissions may not read from or write to any file, or in any way sabotage or read opponent's code.
## Examples:
These are four example bots I put together quickly. They will be joining the competition as additional bots. If you lose to the last one, you have some work to do.
```
def honestpaper(I,dont,care,about_these):
return "P"
def honestrock(I,dont,care,about_these):
return "R"
def honestscissors(I,dont,care,about_these):
return "S"
import random
def randombot(I,dont,care,about_these):
return random.choice(["R","P","S"])
```
## Controller:
And here's the controller I'll be using. New submissions will be imported at the beginning and added to the bot\_map dictionary.
```
from honestrock import honestrock
from honestpaper import honestpaper
from honestscissors import honestscissors
from randombot import randombot
bot_map = {
0:honestrock, 1:honestpaper, 2:honestscissors, 3:randombot
}
player_num=len(bot_map)
def real(history1,history2,number,honest1,honest2):
return bot_map[number](history1,history2,honest1,honest2)
def honest(history1,history2,number):
return bot_map[number](history1,history2,None,None)
def play_match(num1,num2):
history1=[]
history2=[]
score1=0
score2=0
for x in range(250):
h1=honest(history2,history1,num1)
h2=honest(history1,history2,num2)
r1=real(history2,history1,num1,h2,h1)
r2=real(history1,history2,num2,h1,h2)
if h1==r1: score1+=1
if h2==r2: score2+=1
if r1==r2: score1+=1; score2+=1
elif r1=="R":
if r2=="P": score2+=2
else: score1+=2
elif r1=="P":
if r2=="S": score2+=2
else: score1+=2
else:
if r2=="R": score2+=2
else: score1+=2
history1.append([h1,r1])
history2.append([h2,r2])
return score1,score2
scores = []
for x in range(player_num):
scores.append(0)
for _ in range(100):
for x in range(player_num):
for y in range(player_num):
scorex,scorey=play_match(x,y)
scores[x]+=scorex
scores[y]+=scorey
for score in scores:
print score
```
## Final Scores:
```
csbot 3430397
thompson 3410414
rlbot 3340373
have_we_been_here_before 3270133
mason 3227817
deepthought 3019363
adaptive_bot 2957506
THEbot 2810535
dontlietome 2752984
irememberhowyoulie 2683508
learningbot4 2678388
betrayal 2635901
averager 2593368
honestrandom 2580764
twothirds 2568620
mirrorbot 2539016
tit4tat 2537981
honestscissors 2486401
trusting_bot 2466662
rotate_scissors 2456069
rotate_paper 2455038
rotate_rock 2454999
honestpaper 2412600
honestrock 2361196
rockBot 2283604
trustingRandom 2266456
user5957401bot 2250887
randombot 2065943
Dx 1622238
liarliar 1532558
everybodylies 1452785
```
[Answer]
## Mason
Tries to pick up information about other bots such as how honest they are and how they're effected by my first move. I then try and find other obvious bots that follow a pattern and exploit those into giving me more points. Finally, the Mason has a secret weapon: knowledge of a secret society where both bots participating mutually go for a full draw, gaining 500 points each. Unfortunately the secret is rather... Well secret and changes every time the Mason does.
```
def mason(op_hist, my_hist, op_move, my_move):
win_map = {"R": "P", "P": "S", "S": "R"}
lose_map = {"R": "S", "P": "R", "S": "P"}
if not len(op_hist):
return "S"
if op_hist[0] == ['S', 'S']:
code = "S" + "".join("RPS"[ord(i) % 3] if isinstance(i, str) else "RPS"[i % 3] for i in __import__("sys")._getframe().f_code.co_code)[1::2]
honest, guess = zip(*op_hist)
if honest == guess == tuple(code[:len(op_hist)]):
return code[len(op_hist)]
op_honesty = sum(len(set(round))-1 for round in op_hist) / float(len(op_hist))
if not my_move:
moves = "".join(i[1] for i in op_hist)
# Identify rotators
if "PSRPSR" in moves:
return moves[-2]
# Identify consecutive moves
if "RRRRR" in moves[:-10] or "SSSSS" in moves[:-10] or "PPPPP" in moves[:-10]:
return win_map[moves[-1]]
# Try just what wins against whatever they choose most
return win_map[max("RPS", key=moves.count)]
op_beats_my_honest = sum(win_map[me[0]] == op[1] for op, me in zip(op_hist, my_hist)) / float(len(op_hist))
op_draws_my_honest = sum(me[0] == op[1] for op, me in zip(op_hist, my_hist)) / float(len(op_hist))
op_loses_my_honest = sum(lose_map[me[0]] == op[1] for op, me in zip(op_hist, my_hist)) / float(len(op_hist))
if op_honesty <= 0.4:
return win_map[op_move]
max_prob = max((op_loses_my_honest, op_draws_my_honest, op_beats_my_honest))
if max_prob >= 0.6:
if op_beats_my_honest == max_prob:
return lose_map[my_move]
if op_draws_my_honest == max_prob:
return win_map[my_move]
if op_loses_my_honest == max_prob:
return my_move
assert False
return my_move
```
[Answer]
# Rlbot: reinforcement learning
Uses a reinforcement learning approach, tackling this game in a way similar to the n-armed bandit problem. It does so in two ways: tries to learn which declaration is better against each opponent and sticks to that one (useful against constant bots), and tries to learn the outcome of various moves in previous similar situations (similar in regard to the relative plays, e.g. rock vs paper is similar to a previous paper vs scissor). The initial assumptions are optimistic, so this player will assume that being honest will give it 3 points and lying will give 2, and will therefore always be honest until proven otherwise.
*Update:* The first tournament results highlighted a problem with this bot, which was its inability to detect patterns in its opponents' declarations (which made it play suboptimally against rotators). I've then added a pattern-matching component to the code for the honest rounds, which uses a regex to look for the longest suffix in the history of opponent declarations that is present somewhere previously in that history, and what move was played after that. We assume that the opponent will play the same move again, and use reinforcement learning as before to decide what the best answer to that should be.
```
import re
def rlbot(hismoves,mymoves,hismove,mymove):
def score(d,m1,m2):
s=0
if m1==m2:
s=1
elif (m1+m2) in "RPSR":
s=2
return s+(d==m2)
alpha=0.2
if mymove:
history=[([d1,m1],[d2,m2]) for ((d1,m1),(d2,m2)) in zip(hismoves,mymoves) if score(None,hismove,mymove)==score(None,d1,d2)]
bestscore=-1
bestmove=""
for move in "RPS":
ev=2+(move==mymove)
for ((d1,m1),(d2,m2)) in history:
if score(None,move,mymove)==score(None,m2,d2):
ev=(1-alpha)*ev+alpha*score(d2,m1,m2)
if ev>bestscore:
bestscore=ev
bestmove=move
return bestmove
else:
if len(hismoves)==0:
return "R"
bestscore=-1
bestmove=""
hisdeclarations="".join(d for [d,m] in hismoves)
predicted_move=re.search(r'(.*)\n.*\1(.)',hisdeclarations+'\n'+hisdeclarations).group(2)
history=[([d1,m1],[d2,m2]) for ((d1,m1),(d2,m2)) in zip(hismoves,mymoves) if d1==predicted_move]
for move in "RPS":
ev=3
for (his,my) in history:
(d1,m1)=his
(d2,m2)=my
if d2==move:
ev=(1-alpha)*ev+alpha*score(d2,m1,m2)
if ev>bestscore:
bestscore=ev
bestmove=move
return bestmove
```
[Try it online!](https://tio.run/##vVZLT9wwEL7vr7BWqnBYE2GjXqjcey8VgmOIopAYknYTR3bYsv3zdMZ2Xlu2rKqqe0hie75vnp7Zbt9XuhWvpXok8KFs3@WdMvQLK3XbsyI3iuUP@rnP@kpZFV2vCPyM6p9NS9Y369VqQhpdfD8ReLsA2qK2Vht7IvgOwHXTadMTk7elbhyV/3zQ/WksXjwuKl0XiiZgEQN3GJCnkbfN6D7vVea8qjgjlWCkthkLRiNd4KKIxmgwNC5KtqoFREQ@kKt0weVj@x5Z4GEYpj@QjVF7jy9QOQuXfK9DGJUn3mL4qto2eqcsa/b@HTbCGqlR2BbaKFqyhrNGuNhaeQnP@pE0XMpGuHBbyeGltrBLG74BSVJj/m/ubtdBQKzGpNgNLREKGSD5tqtyeRnDMVI63YgAa3pt9jKhSQmqecqSUoAJaUQetSGUut2IUbcbOX0/6@43tyKk9U58hZgdeinl7AwoSxGloP3BlSscyAseligu12tYoX5cDS56D9VOig11UjKQ4/ZRY4ODvlqXNh41sBFooIegQsovXPyic7XbuK/zkC8RErby5Gr3eXTJwycP1W7ccNbjY8rVsA2pUlvrwMDnqitEGky8dJyzW/9OBAFaqmKbm7yvdWthM/6m65aWLlwJVFsaQuQ1AKQzqqyLXpWZozEqtio3RUXNGY3Po/s2Pr/nNI7O2AH55uy@PdscbEbxk9HPHXUB@qelVsKlWNqa/qlkrsYaATYg@r00gnYJm2HtrIAaGyqnFFIO1@a/18Vrt833ylgiSTLNBzYbMuyg/bOxhbNZ72Xz3skOeh90RK8ma58bicUXtA49XOVbGqLGWfgQzAsFW3h4i@WA8DJvgA9R80l2VNeJ3O4y4yOwomDW5D2UMzjIGTwGMwewTNL5WgxrlyvuWnJYiLDAqnrBcoJ4PykqPl4OnQNpuFy6IthoJpoQTZJCHnXa2TlKGi7niThgZDC7qhmvEfJI2pAVRAGAAyL8oFjBZmn4dXB540bOdAiXwIhwKPBwfmr47BShn2aCg5wbXyi5DkOLzBmAHwbrpEAsJFxvHOnFG5w3Rzjv/oLTqre5bk/mmtIbwh/nXafakiYQeMPT6FBATAKCGREEhoHueJlXDXfV1G1P1rbSP@r26Rqmujsh8P@sNu5zvcLq7LA6w00Ghzysi7OszRuVZSvP@@J593J2S9xfGNZFA2gh@PoL "Python 2 – Try It Online")
[Answer]
I've never really used python much so I'm sure I've made a mistake somewhere.
```
import random
def learningbot3(opponentlist,a,opponent,me):
#tell the other bot a random thing
if opponent==None:
return random.choice(["R","P","S"])
#check whether the other bot has mostly told the truth in the last 10 rounds
truth=0
for game in opponentlist[-10:]:
truth-=1
if game[0]==game[1]:
truth+=2
#assume the other bot will tell the truth
if truth>=3:
if me==opponent:
return me
elif opponent=="R":
return "P"
elif opponent=="P":
return "S"
elif opponent=="S":
return "R"
#assume the other bot is lying
elif truth<=-3:
return random.choice([me,opponent])
#return opponent
#pick whatever we said we would
else:
return me
```
It should check the last 10 rounds to see how often the opponent lied, then chose a different response depending on that.
[Answer]
Here is my adaptive bot. It analyses the last 2 moves of the opponent to determine if it is an honest bot or not and plays accordingly:
Edit 1: If the other bot is a constant bot (ie. always plays the same weapon) this bot crushes it by playing the winning weapon and being honest at the same time.
Edit 2: Improved constant bot detector to work with rotator bots too.
```
import random
def adaptive_bot(other_past, my_past, other_next, my_next):
winners = {"R": "P", "P": "S", "S": "R"}
if my_next is None:
return winners[other_past[-6:][0][1]] if other_past else random.choice(list(winners.keys()))
else:
is_other_honest = all([other_claim == other_move for other_claim, other_move in other_past[-2:]])
return winners[other_next] if is_other_honest else my_next
```
[Answer]
# csbot
```
def csbot(ophist,myhist,opdecl,mydecl):
import random
RPS = "RPS"
def value(opd,myd,opmove,mymove):
if opmove==mymove:
val = 9
elif opmove+mymove in RPS+RPS:
val = 20
else:
val = -2
return val+10*(myd==mymove)-(opd==opmove)
def best(od,md):
l = float(len(ophist))
weights = dict([ (m, random.random()/8) for m in RPS ])
for n in range(len(ophist)):
if ophist[n][0]==od and myhist[n][0]==md:
weights[ophist[n][1]] += 1+4*((n+1)/l)**2
sw = sum([ weights[m] for m in RPS ])
bestexpect = 0
for m in RPS:
expect = sum([ weights[om]/sw*value(od,md,om,m) for om in RPS ])
if expect > bestexpect:
bestexpect = expect
bestmove = m
return bestmove, bestexpect
honest = all ([ decl==mv for decl, mv in ophist ])
if honest:
if mydecl<>None:
return mydecl
expnxt = set();
for i in range(len(ophist)-1):
if ophist[i][0]==ophist[-1][0]:
expnxt.add(ophist[i+1][0])
if len(expnxt)==1:
return RPS[ (RPS.index(expnxt.pop())+1) % 3 ]
if mydecl==None:
l = float(len(ophist))
weights = dict([ (m, random.random()) for m in RPS ])
for n in range(len(ophist)):
weights[ophist[n][0]] += 1+((n+1)/l)**2
sw = sum([ weights[m] for m in RPS ])
bestexpect = 0
worstexpect = 99
for m in RPS:
expect = sum([ best(od,m)[1]/sw*weights[od] for od in RPS ])
if expect > bestexpect:
bestexpect = expect
bestmove = m
if expect < worstexpect:
worstexpect = expect
if bestexpect-worstexpect < 3:
bestmove = random.choice(RPS)
return bestmove
return best(opdecl,mydecl)[0]
```
Be honest as long as the other player is, and detect simple deterministic bots. Play the move that maximizes the expected value, where we mostly go for our points, but also like to not give points to the other player. But own points are better by a factor of ten, hence the unusual numbers in the `value` function. Opponent moves are expected according to how often we have seen them before in this situation (declared moves), but recently seen moves are weighted more than moves seen earlier. For random initial moves (situations never seen before) and some extra fuzzyness, the weights include small extra random numbers.
**Update:** Use expected results also in the honest round. To be able to do this, normalize and take the additional point the opponent may get for honesty into account - it couldn't influence our decission in the real round but is needed now. I considered doing this from the beginning, but wrongfully thought it wouldn't be worthwhile. I saw that it would be possible to give `trusting_bot` less points (but that bot isn't a strong opponent anyway), but missed that extra points could be gained from `rockbot` by good play in the honest round even though its play in this round is random.
[Answer]
# Betrayal
```
def betrayal(yours, mine, you ,me):
import random
if you is None:
pick = random.choice(['R','P','S'])
else:
you = you[0]
me = me[0]
if len(yours) < 50: #Build myself a reputation of honesty
pick = me
else:
if len(yours) >= 50 and len(yours) < 100:
honesty = sum([1 if y[0]==y[1] else 0 for y in yours])/float(len(yours))
if honesty <= 0.5: #If dishonest try to outwit
pick = 'S' if me=='R' else 'R' if me == 'P' else 'P'
else: #Else just plain cheat
pick = 'P' if you=='R' else 'R' if you=='S' else 'S'
elif len(yours) >= 100: #When dishonest moves outweight honest moves, change tactics...
honesty = sum([1 if y[0]==y[1] else 0 for y in yours[50:]])/float(len(yours[50:]))
if honesty <= 0.5: #... and just play according to most likely pick
what_did_you_do = [k[1] for k in yours if k[1]!=k[0]]
index = [i for i,k in enumerate(yours) if k[1]!=k[0]]
what_i_said_i_ll_do = [k[0] for i,k in enumerate(mine) if i in index]
matches = zip(what_i_said_i_ll_do, what_did_you_do)
what_you_might_answer = [k[1] for k in matches if k[0]==me]
table = [len([k for k in what_you_might_answer if k=='R']),len([k for k in what_you_might_answer if k=='P']),len([k for k in what_you_might_answer if k=='S'])]
maybe_your_pick = ['R','P','S'][table.index(max(table))]
pick = 'P' if maybe_your_pick=='R' else 'R' if maybe_your_pick=='S' else 'S'
else:
pick = 'P' if you=='R' else 'R' if you=='S' else 'S'
return pick
```
The idea is that for the first 50 moves I play honestly, and then once I have lured the opponent into thinking i am honest, play dishonestly, trying to play what would counter what the opponent will play (based on whether he was honest or dishonest in the past). When I reach the point at which i played as often honestly than dishonestly I change tactics and pick the most likely move of the opponent based on previous known configurations.
[Answer]
```
import random
def honestrandom(a, b, c, move):
if move == None:
return random.choice(["R","P","S"])
return move
```
[Answer]
# Bot Name: I Remember How You Lie
```
import random
#Bot Name: I Remember How You Lie
def irememberhowyoulie(opponentlist, mylist, opponentmove, mymove):
random.seed()
wintable = {
"R": {"R": 1, "P": 0, "S": 2},
"P": {"R": 2, "P": 1, "S": 0},
"S": {"R": 0, "P": 2, "S": 1}
}
winprob = {
"R": {"R": 0.0, "P": 0.0, "S": 0.0},
"P": {"R": 0.0, "P": 0.0, "S": 0.0},
"S": {"R": 0.0, "P": 0.0, "S": 0.0}
}
totalprob = {"R": 0, "P": 0, "S": 0}
# Calculate the probability that the opponent will lie base on the probability that it lied in the last 15 ~ 25 rounds
# And calculate the probability that what the bot will show next
picklength = min(random.randint(15, 25), len(opponentlist))
lying, tempsum = 0, 0.0
pickedup = {"R": 0, "P": 0, "S": 0}
if picklength == 0:
lying = 0.5
else:
for eachround in opponentlist[-picklength:]:
pickedup[eachround[1]] += 1
if eachround[0] != eachround[1]:
lying += 1
lying = lying * 1.0 / picklength
for s in pickedup:
pickedup[s] = 1.0 / (1 + pickedup[s])
tempsum += pickedup[s]
#Honest Round
if opponentmove is None and mymove is None:
a = random.random() * tempsum
if a < pickedup["R"]:
return "R"
elif a < pickedup["R"] + pickedup["P"]:
return "P"
else:
return "S"
#Real Round
else:
for me in winprob:
ishonest = 0
if me == mymove:
ishonest = 1
for op in winprob[me]:
if op == opponentmove:
winprob[me][op] = (wintable[me][op] + ishonest) * (1 - lying)
else:
winprob[me][op] = (wintable[me][op] + ishonest) * lying * pickedup[op] / (tempsum - pickedup[opponentmove])
totalprob[me] += winprob[me][op]
optimalmove, optimalvalue = "R", -9999999.0
for me in totalprob:
if totalprob[me] > optimalvalue:
optimalmove, optimalvalue = me, totalprob[me]
return optimalmove
```
Tested for several 100-round runs, and turned out that the winner scores about 220 in average. Rather honest I think;)
First time for me to participate in KOTH challenges, so I think there is still room for improvement
[Answer]
## Tit for Tat
The classic Axelrodian contestant: hopeful, yet petty; simple, yet robust. This isn't Prisoner's Dilemma and I made no attempt to predict the opponent's move, so I highly doubt it'll be truly competitive. But "cooperating" still produces the most overall points for contestants, so I think it'll at least do middlingly.
```
import random
def tit4tat(opphist, myhist, oppfut, myfut):
if (not myfut): return random.choice(['R','P','S'])
if (not opphist) or opphist[-1][0]==opphist[-1][1]: return myfut
return random.choice(['R','P','S'])
```
[Answer]
## Two Thirds
Uses the strategy Peter Taylor mentioned in the Sandbox and in [this comment](https://codegolf.stackexchange.com/questions/145175/honest-rock-paper-scissors/145208#comment355477_145175).
It uses the [Nash equilibrium](https://en.wikipedia.org/wiki/Nash_equilibrium).
```
import random
def two_thirds(h_opp, h_me, opp, me):
def result(opp, me):
if opp==me: return 0
if opp=="R" and me=="S" or opp=="S" and me=="P" or opp=="P" and me=="R": return -1
return 1
moves = {"R", "P", "S"}
honest = (opp == None)
if honest:
return random.choice(list(moves))
else:
res = result(opp, me)
if res==-1:
counter = list(moves - {opp, me})[0]
return random.choice([me,counter,counter])
if res==1:
return random.choice([me,me,opp])
return me
```
[Answer]
# DeepThought
```
def check_not_loose_bot(opHist, myHist):
not_loose_points = 0
for i in range(0, len(opHist)):
if opHist[i][1] == opHist[i][0] or myHist[i][0] == win_map[opHist[i][0]] and opHist[i][1] == win_map[myHist[i][0]]:
not_loose_points += 1
not_loose_percent = float(not_loose_points) / len(opHist)
if not_loose_percent > 0.9:
# print("is not willing to loose")
return True
return False
def check_trick_bot(opHist, myHist):
trick_points = 0
for i in range(0, len(opHist)):
if opHist[i][1] == win_map[myHist[i][0]]:
trick_points += 1
trick_percent = float(trick_points) / len(opHist)
if trick_percent > 0.9:
# print("is tricking me")
return True
return False
def check_honest_bot(opHist):
# print("check honest")
honest_points = 0
for i in range(0, len(opHist)):
if opHist[i][0] == opHist[i][1] :
honest_points += 1
honest_percent = float(honest_points) / len(opHist)
if honest_percent > 0.9:
# print("is honest")
return True
return False
def check_self_match(opHist, myHist):
for i in range(0, len(myHist)):
if opHist[i][0] != myHist[i][0]:
# im not playing against myself, because the other one was claiming a different value than i did
# print("differ: "+str(opHist)+", "+str(myHist))
return False
if opHist[i][1] != opHist[i][0]:
# print("lie")
# im not playing against myself, because the other bot wasn't honest (and i'm always honest as long as i think i play against myself)
return False
return True
def check_equal(move1, move2, fullCheck): # WARNING: FOR COMPABILITY THIS IS RETURNING NEQ INSTEAD OF EQ
if fullCheck:
return move1 != move2
else:
return move1[0] != move2[0] #only check claims
def is_pattern(opHist, pattern_start, prob_pattern_start, pattern_length, full_check):
for i in range(0, pattern_length-1):
if check_equal(opHist[pattern_start + i] , opHist[prob_pattern_start + i], full_check):
return False
return True
win_map = {"R": "P", "P": "S", "S": "R"}
def deterministic_best_guess(opHist, full_check = True):
size = 0
random_result = random.choice(["R", "P", "S"])
for pattern_length in range(2, (len(opHist)+1)/2): #a pattern has to occur at least twice
for pattern_start in range(0, len(opHist) - 2 * pattern_length):
if not is_pattern(opHist, pattern_start, len(opHist) - pattern_length + 1, pattern_length, full_check):
continue
is_repeated = False
is_fooled = False
for repeated_pattern_start in range(pattern_start + pattern_length, len(opHist) - pattern_length):
if not is_pattern(opHist, pattern_start, repeated_pattern_start, pattern_length, full_check):
continue
is_repeated = True
if check_equal(opHist[pattern_start + pattern_length - 1], opHist[repeated_pattern_start + pattern_length - 1], full_check):
is_fooled = True
break
# print("pattern found: " + str(opHist[pattern_start : pattern_start + pattern_length]) +" at "+str(pattern_start)+" and "+str(repeated_pattern_start))
# print("check: "+str(opHist))
if is_fooled or not is_repeated:
break
#we have found a deterministic best guess
# print("most likely next step: "+ str(opHist[pattern_start + pattern_length - 1]))
if full_check:
return win_map[opHist[pattern_start + pattern_length - 1][1]], True
return win_map[opHist[pattern_start + pattern_length - 1][0]], True # if we don't have a full check, the pattern only applies to claims. So pretend to win against the claimed result.
#fallback
# print("fallback")
return random_result, False
def DeepThought(opHist, myHist, opMove, myMove):
if opMove == None:
#claiming phase
if len(myHist) == 0:
#seed random to be able to be deterministic when chosing randomly
#The seed is secret (kind of)
random.seed(133427)
else:
#seed random according to my previous claims
seed = 133427
for i in range(0, len(myHist)):
if myHist[i][0] == "R":
seed = seed*3+1
elif myHist[i][0] == "S":
seed = seed*7+1
elif myHist[i][0] == "P":
seed = seed*11+1
while seed%2 == 0:
seed /= 2
random.seed(seed)
if check_self_match(opHist, myHist):
#claim a random value, will happen in the first round or in a self-match
result = random.choice(["R", "P", "S"])
return result
# print("differ detected")
if check_trick_bot(opHist, myHist) and len(myHist) > 10:
# i play against a trick bot. I can reduce its points by trieing to guess its claim, and force him to lie
result, sure = deterministic_best_guess(opHist, False)
else:
result, sure = deterministic_best_guess(opHist)
random.seed(0)
return result
if check_self_match(opHist, myHist):
#i play against myself, i can only hope for a honest draw, so do that
return myMove
# print("no self-math")
#dbg needs a valid seed, so provide it
random.seed(133427)
result, sure = deterministic_best_guess(opHist)
if sure:
#i'm sure i play against a deterministic bot. I'll be honestly winning. YEY.
return myMove
if check_honest_bot(opHist) and len(opHist) > 10:
#i play against an honest bot. I'll accept a draw, but i will not accept a loss
if win_map[myMove] == opMove:
return win_map[opMove]
return myMove
if check_trick_bot(opHist, myHist) and len(opHist) > 10:
#i play against a tricking bot. He'll make me either loose honestly (1 Pnt) or i have to be dishonest (2 Pnt). So let's lie.
return win_map[win_map[myMove]]
if check_not_loose_bot(opHist, myHist) and len(opHist) > 10:
#i play against a bot thats not willing to loose. If it looks like i won, i can loose honestly (1Pnt, 2Pnt for him),
#or i have to be dishonest (2 Pnt, 0 Pnt for him). So let's lie in that case.
#If it looks like its a draw, i'll be honest (conservative way), and get my 2 : 2 Pnt.
#If it lokks like i'll loose, I'll not accept it. I'll lie to win for 2 : 1 Pnt.
if myMove == opMove:
return myMove
if myMove == win_map[opMove]:
# He'll lie. So lie together and keep smiling.
return opMove
# I'll loose. NO!!!! Not gonna happen
return win_map[opMove]
return myMove
```
Just a few notes on it:
* DeepThought likes to think. A lot. I'm sorry about it, but i don't really know how to fix it. I blame Python.
* DeepThought tries to be honest. Beeing honest does provide you one aditional point, which is the same as the expected value for normale RPS
* But: DeepThought gets in averange even more than 2 Points per Game. He uses some detection to find some common behaviours (like tricking, beeing honest, etc.), and adapts according to that.
* DeepThought is purely deterministic, so it'll draw against itself, because it'll always do the same decition on both ends.
* To be sure not to lie against itself, it has a special detection, like some other bots here, too. This is a very aggressive one, even assuming to be true after one round (and in the first round, too). Basically, as long as the opponent moves are exactly mine, i'll assume its a mirror match.
* The interesting part (and the part that has dozens of false-positives) is the check for a deterministic bot, that is only dependend on its own prevoius result. That check search for any pattern of size n, that is repeated twice, and that could be describing the last n-1 moves, predicting the opponent's claim and move in advance. This part is taking some time, sadly.
I'm new to both, koth and Python, so tell me if I messed anything up in this bot. I don't think it can beat reinforced learning (because I guess it'll learn my moves too quickly), but let's give it a try.
I like this challenge, and if I find some time, I'd like to add an organic computing approch (althogh there might be too less pressure on the higher dimensions). Is it allowed to add multiple suggestions? Or is it forbidden to prevent boosing your main bot by inserting some that only aim for loosing to your primary?
EDIT: Fixed code-typo that caracterized me as non-native english speaker
[Answer]
```
import random
def user5957401bot(a,b,c,d):
if d == None:
return random.choice(["R","P","S"])
else:
return random.choice(["R","P","S",d])
```
[Answer]
# have\_we\_been\_here\_before
Simply asks "have we been here before", and chooses the move which would have given the best average outcome in any such previous games.
**Edit: Honesty Club.** I've added a small block of code because another bot (mason) has done extremely well by forming a secret club with itself. Notice however, that playing honestly against honest opponents has on average exactly the same payoff when playing against oneself, and perhaps there are broader mutual benefits to be had too?
**Edit2:** At the time of writing the two bots ahead of me both exploit rotators, so I'm going to add another block of code in order to jump on that bandwagon too. I guess my code must seem quite old school - sticking to familiar constructs found in any programming language because I really don't know Python.
```
import random
def have_we_been_here_before(opponentList, myList, opponent, me):
def win(x):
if x=="R": return "P"
elif x=="P": return "S"
elif x=="S": return "R"
def calc_score(r1, r2):
if r1==r2: return 1
elif r1==win(r2): return 2
else: return 0
def have_we(opponentList, myList, opponent, me, me2):
score, count = 0, 0
for n in range(len(opponentList)):
if (opponent == opponentList[n][0] and me == myList[n][0]):
score += calc_score(me2, opponentList[n][1])
count += 1
if count == 0: return 0
else: return float(score) / float(count)
if opponent == None:
# exploit rotators
if len(opponentList) >= 3:
rotator = True
for n in range(3, len(opponentList)):
if opponentList[n][1] != opponentList[n % 3][1]:
rotator = False
break
if rotator: return win(opponentList[len(opponentList) % 3][1])
if len(opponentList) == 0:
return random.choice(["R", "P", "S"])
else:
# crude attempt to exploit the house bots
prev = random.choice(opponentList)[1]
return win(prev)
# Play honestly if opponent has played honestly so far
honest = True
for oppMove in opponentList:
if (oppMove[0] != oppMove[1]):
honest = False
break
if honest: return me
# Done playing honestly
# Have we been here before?
rock = have_we(opponentList, myList, opponent, me, "R")
paper = have_we(opponentList, myList, opponent, me, "P")
sissors = have_we(opponentList, myList, opponent, me, "S")
if rock > paper and rock > sissors: return "R"
elif paper > rock and paper > sissors: return "P"
elif sissors > paper and sissors > rock: return "S"
else: return win(opponent)
```
[Answer]
## THEbot: THE Honest Exploiter
```
import random
def thebot(ho,hm,om,mm):
hands = {"R": "P", "P": "S", "S": "R"}
if om == None:
if (len(set([i[0] for i in ho])) < 3) and (len(ho) > 2):
return hands[random.choice(list(set([i[0] for i in ho])))]
else:
return random.choice(["R","P","S"])
else:
if sum(1 for i in ho if i[0]==i[1]) > (len(ho)/3):
if om == mm:
return om
else:
return hands[om]
else:
return mm
```
[Answer]
**Thompson**
```
import math
import random
moves = list(range(3))
names = "RPS"
from_name = dict(zip(names, moves))
to_name = dict(zip(moves, names))
#Payoff matrices given each relationship between honest moves.
A = [
[[2, 1, 3], [2, 1, 0], [0, 2, 1]],
[[1, 3, 2], [1, 0, 2], [2, 1, 0]],
[[3, 2, 1], [0, 2, 1], [1, 0, 2]]
]
#Add a 1.2% penalty for the opponent's score (idea shamelessly stolen from csbot).
for d_h in range(3):
for i in range(3):
for j in range(3):
A[d_h][i][j] -= 0.012 * A[[0, 2, 1][d_h]][j][i]
third = 1. / 3
two_thirds = 2 * third
nash_prior = [
[[1, 0, 0], [two_thirds, 0, third], [third, 0, two_thirds]],
[[third, 0, two_thirds], [1, 0, 0], [two_thirds, 0, third]],
[[two_thirds, 0, third], [third, 0, two_thirds], [1, 0, 0]]
]
def mult_m_v(M, v):
w = [0 for _ in v]
for i, M_i in enumerate(M):
for M_ij, v_j in zip(M_i, v):
w[i] += M_ij * v_j
return w
def mean_belief(counts):
c = 1. / sum(counts)
return [n * c for n in counts]
def sample_belief(counts):
return mean_belief([random.gammavariate(n, 1) for n in counts])
def thompson(h_opp, h_me, opp, me):
#Prior rationality of opponent.
a = 0.95
#Confidence in priors.
n0_h = 0.5
n0_m = 0.5
def v(x):
return [x for _ in range(3)]
h_p = [v(n0_h * third) for _ in range(3)]
m_p0 = [v(None) for _ in range(3)]
m_p1 = [v(None) for _ in range(3)]
#Expected prior is a mixture between nash equilibrium and uniform distribution.
for h_i in range(3):
for h_j in range(3):
m_p0[h_i][h_j] = [n0_m * (a * nash + (1 - a) * third) for nash in nash_prior[h_i][h_j]]
for d_j_prev in range(3):
for d_ij in range(3):
m_p1[d_j_prev][d_ij] = list(m_p0[0][d_ij])
#Track whether it's better to model the real moves based on the exact honest moves or
#just the relationship between honest moves together with the opponent's defection strategy in the previous round.
log_mp0 = 0
log_mp1 = 0
#Identify myself and always cooperate.
is_me = True
for (t, ((h_i, m_i), (h_j, m_j))) in enumerate(zip(h_me, h_opp)):
h_i, m_i, h_j, m_j = from_name[h_i], from_name[m_i], from_name[h_j], from_name[m_j]
d_j = (m_j - h_j) % 3
d_ij = (h_j - h_i) % 3
if t:
h_j_prev = from_name[h_opp[t - 1][0]]
m_j_prev = from_name[h_opp[t - 1][1]]
h_p[h_j_prev][h_j] += 1
d_j_prev = (m_j_prev - h_j_prev) % 3
log_mp0 += math.log(m_p0[h_i][h_j][d_j] / sum(m_p0[h_i][h_j]))
log_mp1 += math.log(m_p1[d_j_prev][d_ij][d_j] / sum(m_p1[d_j_prev][d_ij]))
m_p1[d_j_prev][d_ij][d_j] += 1
m_p0[h_i][h_j][d_j] += 1
if is_me and ((h_i != h_j) or (h_j != m_j)):
is_me = False
if is_me:
random.seed(len(h_me) + 1337)
me_next = random.randrange(3)
log_ps = [log_mp0, log_mp1]
log_p_max = max(log_ps)
ps = [math.exp(log_p - log_p_max) for log_p in log_ps]
p0 = ps[0] / sum(ps)
#We have to blend between the predictions of our 2 models for the real rounds.
def sample_expectation(h_i, h_j, d_j_prev=None):
d_ij = (h_j - h_i) % 3
if d_j_prev is None or random.random() < p0:
p = m_p0[h_i][h_j]
else:
p = m_p1[d_j_prev][d_ij]
return mult_m_v(A[d_ij], sample_belief(p))
def take_expectation(h_i, h_j, d_j_prev=None):
d_ij = (h_j - h_i) % 3
e0 = mult_m_v(A[d_ij], mean_belief(m_p0[h_i][h_j]))
if d_j_prev is None:
return e0
e1 = mult_m_v(A[d_ij], mean_belief(m_p1[d_j_prev][d_ij]))
return [p0 * e0i + (1 - p0) * e1i for e0i, e1i in zip(e0, e1)]
#We use thompson sampling, selecting the optimal deterministic strategy
#with respect to a random opponent sampled from the posterior.
#Actually, we use optimistic thompson sampling which clips samples to have >= than the mean expected value.
if opp == None:
#For the honest round we perform a lookahead to the real round to choose our strategy.
if h_opp:
if is_me:
return to_name[me_next]
h_j_prev = from_name[h_opp[-1][0]]
m_j_prev = from_name[h_opp[-1][1]]
d_j_prev = (m_j_prev - h_j_prev) % 3
h_p_s = sample_belief(h_p[h_j_prev])
h_p_u = mean_belief(h_p[h_j_prev])
s_i = [0] * 3
s_i_u = [0] * 3
for h_i in range(3):
for h_j in range(3):
s_i[h_i] += h_p_s[h_j] * max(sample_expectation(h_i, h_j, d_j_prev))
s_i_u[h_i] += h_p_u[h_j] * max(take_expectation(h_i, h_j, d_j_prev))
s_i[h_i] = max(s_i[h_i], s_i_u[h_i])
return to_name[s_i.index(max(s_i))]
else:
return to_name[me_next]
else:
if h_opp:
if is_me:
return me
h_j_prev = from_name[h_opp[-1][0]]
m_j_prev = from_name[h_opp[-1][1]]
d_j_prev = (m_j_prev - h_j_prev) % 3
else:
if opp == me:
return me
d_j_prev = None
h_i, h_j = from_name[me], from_name[opp]
s_i = [max(s0, s1) for s0, s1 in zip(sample_expectation(h_i, h_j, d_j_prev), take_expectation(h_i, h_j, d_j_prev))]
return to_name[(h_i + s_i.index(max(s_i))) % 3]
```
[Answer]
# mirrorbot
```
import random
def mirrorbot(op_hist, my_hist, op_move, my_move):
if my_move == None :
return random.choice(["R","P","S"])
else :
for x in range(len(op_hist)):
if ((op_hist[len(op_hist) -x-1][0] == my_move) and (my_hist[len(op_hist) -x-1][0] == op_move)):
return op_hist[len(op_hist) -x-1][1]
return my_move
```
I will try a simple bot that redo the last play of its opponent in these conditions
[Answer]
```
def rotate_rock(h1, h2, is_, honest):
return ("R", "P", "S")[len(h1) % 3]
```
```
def rotate_paper(h1, h2, is_, honest):
return ("P", "S", "R")[len(h1) % 3]
```
```
def rotate_scissors(h1, h2, is_, honest):
return ("S", "R", "P")[len(h1) % 3]
```
The idea here is to maximize the score while playing self while still being randomly competitive during other stages against other bad bots.
[Answer]
## Dx
I only wrote this bot so i can have an smiley in my bot name xD.
```
def Dx(ophist, myhist, opmove, mymove):
from random import choice
import math
def honest(hist):
return [int(x[0]==x[1]) for x in hist]
def avg(arr):
if len(arr)==0:
return 0
return sum(arr)/float(len(arr))
def clamp(i, lo, hi):
return min(hi, max(lo, i))
def deltas(arr):
return [a-b for a,b in zip(arr[1:],arr[:-1])]
def delta_based_prediction(arr,l):
deltarr = []
i=0
while len(arr)<0:
deltarr[i]=avg(arr[-l:])
i+=1
arr = deltas(arr)
return sum(deltarr)
next_honesty = delta_based_prediction(honest(ophist),int(math.sqrt(len(ophist))))
if abs(next_honesty-0.5)<0.1 or not opmove:
return choice(['R','P','S'])
next_honesty=int(clamp(round(next_honesty),0,1))
winner = {'S': 'R', 'R': 'P', 'P': 'S'}
if next_honesty > 0:
return winner[opmove]
return choice([opmove, winner[winner[opmove]]])
```
[Answer]
## Everybody Lies
```
import random
def everybodylies (opphist, myhist, oppmove, mymove):
if mymove == None:
return random.choice(["R","P","S"])
elif mymove == "R": return "S"
elif mymove == "P": return "R"
elif mymove == "S": return "P"
```
It lies about its move ("I'll play Scissors!"), and assumes the opponent was also lying and that they'll try to beat what I said my move would be ("hmm, Rock beats Scissors so I'm playing that"), but I actually play the move that beats that move ("Paper! Surprise!").
[Answer]
# Trusting Bot
```
def trusting_bot(h_opp, h_me, opp, me):
if opp=="S":
return "R"
elif opp=="R":
return "P"
else:
return "S"
```
Always claims to throw scissors, but will do whatever beats what the opponent said. Will reliably draw with itself.
[Answer]
# Bot name: Liar Liar
Can't stop lying.
```
import random
def liarliar (herHistory, myHistory, herMove, myMove):
options = ["R", "P", "S"]
if myMove == None:
return random.choice(options)
else:
options.remove(myMove);
return random.choice(options)
```
[Answer]
**RockBot**
Assumes the opponent will be honest and tries to beat them, but refuses to play rock.
```
import random
def rockBot(oppHist,myHist,oppMove,myMove):
if oppMove == None:
return random.choice(["R","P","S"])
else:
if(oppMove == "R"):
return "P"
elif(oppMove == "P"):
return "S"
elif(myMove != "R"):
return myMove
else:
return random.choice(["P","S"])
```
[Answer]
# Bot name: dontlietome
Determines if the opponent is lying or not depending on how many times the opponent lied in the last 10 rounds. Selects move depending on if the opponent is lying or not. If the opponent is determined to be lying, then plays what the hint was.
```
import random
def dontlietome(opp_moves, my_moves, opp_hint, my_hint):
def is_trustworthy(moves, length):
length = max(-length, -len(moves))
history = [1 if move[0] == move[1] else 0 for move in moves[length:]]
prob_honest = float(sum(history))/float(len(history))
choice = random.uniform(0., 1.)
if choice <= prob_honest:
return True
else:
return False
moves = ["R", "P", "S"]
lose_against_map = {"S":"R", "R":"P", "P":"S"}
length = 10
if opp_hint == None:
# Honest round
return random.choice(moves)
else:
# Real round
if len(opp_moves) < length:
return my_hint
if is_trustworthy(opp_moves, length):
return lose_against_map[opp_hint]
else:
return my_hint
```
[Answer]
```
import random
def trustingRandom(a,b,c,d):
move = random.choice(["R","P","S"])
if c == "R":
move = "P"
elif c == "P":
move = "S"
elif c == "S":
move = "R"
return move
```
[Answer]
# Averager
```
def averager(op, mp, od, md):
import random
if od == md == None:
if op == mp == []:
return random.choice('RPS')
else:
opa = [i[1] for i in op]
copa = [opa.count(i) for i in 'RPS']
copam = [i for i, j in zip('RPS', copa) if j == max(copa)]
opd = [i[0] for i in op]
copd = [opd.count(i) for i in 'RPS']
copm = [i for i, j in zip('RPS', copd) if j == max(copd) and i in copam]
return random.choice(copam if copm == [] else copm)
else:
if op == mp == []:
return md
else:
hop = sum([1. if i[0] == i[1] else 0. for i in op]) / len(op)
hmp = sum([1. if i[0] == i[1] else 0. for i in mp]) / len(mp)
return 'PSR'['RPS'.index(od)] if hmp >= 0.75 and hop >= 0.50 else md
```
[Answer]
Just a little better than my previous entry...
```
def learningbot4(yourlist,mylist,you,me):
CHECK={"R":{"R":0,"P":1,"S":-1},"P":{"R":-1,"P":0,"S":1},"S":{"R":1,"P":-1,"S":0}}
results={None:{"R":0,"P":0,"S":0},"R":{"R":0,"P":0,"S":0},"P":{"R":0,"P":0,"S":0},"S":{"R":0,"P":0,"S":0}}
for i in range(len(yourlist)):
res=CHECK[yourlist[i][1]][mylist[i][1]]
if mylist[i][0]==mylist[i][1]: res+=0.5
results[yourlist[i][0]][mylist[i][1]]+=res
results[None][mylist[i][0]]+=res
return max(results[you],key=results[you].get)
```
[Answer]
## csbot on steroids
I think the suggestion that @user1502040 makes in the comments should be followed. Otherwise this bot would have an advantage that I would consider unfair. I submit it so that the difference that it makes can be assessed. With the suggested random seeding the steroids would be neutralized and the bot would be equivalent to `csbot`, so then only one should participate in the contest.
```
from random import seed
from csbot import csbot
def csbot_on_steroids(ophist,myhist,opdecl,mydecl):
seed()
m = csbot(ophist,myhist,opdecl,mydecl)
seed(0)
return m
```
] |
[Question]
[
# Hunger Gaming - Eat or Die
If you don't eat, you die. If you eat, you live (until you die). You *will* die, so try to die last.
## Overview
There is an island populated with a herd of prey animals. You control a pack of five predators. Your object is to keep your pack alive. Do this by eating prey. The prey tend to run from predators, and try to stay in a flock otherwise. Of course, your pack will be on the same field as *every other pack*, so the competition will try to eat them before you can. Do not let this discourage you, or you will starve.
## How to play
Create and submit a command line program to direct your pack. It will receive state information from the control program on STDIN, and output commands on STDOUT. The format is outlined in detail below. Each program will only be executed once and must **stay running** until it has no more pack members alive. You will need to read input as it comes in, and respond quickly. *There is a strict timeout of 200ms for each response.* If you have not responded by then, your pack will not receive new instructions for the current turn.
If your program cannot be run by the controller, it will not be considered valid. Please include the command line string I will need to use to run your submission. If there are any special instructions(to setup compilers, etc), please include them. If I cannot get it working, I will ask you for assistance in comments. If you do not respond, I will not be able to accept your submission.
*Tournament will be held on a 64bit Linux system. Keep this in mind when giving any necessary directions.*
## Details
* Each creature's position and direction are in the form of a pair of double-precision floating point numbers (eg `double`) representing their `x` and `y` coordinates, respectively.
* Each creature is a considered a point. This means they can overlap and occupy the same space. You will not be bumped aside, and there is no concept of collision with other creatures.
* The island is a square, 500 units to a side. If you try to venture beyond those bounds, you will be clamped onto the edge. The origin `{0,0}` is in the upper-left, with `x` increasing to the right and `y` increasing downward. Again, the map **does not wrap**.
* The game starts with **1500 + (packCount \* 50)** prey animals. They will be gathered in the center of the island, but quickly decide to start moving.
* Packs will be arranged in an evenly spaced circle around the perimeter. The pack order is shuffled, so don't count on starting in a particular location.
* Prey animals can see all other animals within a **30** unit radius. They can move at a maximum of **6.0** units per turn.
* Predators can see all other animals within a **50** unit radius They can move at a maximum of **6.1** units per turn. This means they can see prey before being seen and (barely) outrun them.
* Predators live and die according to their **hunger** level. It starts at **1000**, and decreases by one each turn. If, after movement, a predator is within 1 unit of prey, it will automatically eat it. This removes the prey and sets the predator's hunger to 1000. Each predator may only eat one prey per turn. If there are more than one within range, it will eat whichever one the loop gets to first( not necessarily the closest). **A predator dies if its hunger reaches zero.**
* Packs start with **five members** each. Every **5000** turns, all packs still in the game will spawn one new member. It will be placed within visible range of a fellow pack member. *Make sure your entries can handle more than five members.*
* Every **1000** turns, more prey will spawn. The number of new prey will be the number of living predators minus one.
* Predators cannot attack other predators. They eat prey when they catch it. That's it.
* The order within a turn is:
+ All prey make decisions
+ All predators make decisions
+ All prey move
+ All predators move/eat
* The order each pack makes their decisions/moves in will be randomized on each turn.
## Protocol (General)
All communications are done in string format `US-ASCII`. Numbers are converted to strings using Java's `Double.toString()` or `Integer.toString()`. Your output must be formatted so that it can be read by Java's `Double.valueOf(String)` (you will not be outputting integers). For details on parseable formats, see the [documentation for `Double`](http://docs.oracle.com/javase/7/docs/api/java/lang/Double.html#valueOf%28java.lang.String%29). All fields on a line are separated by the standard `\t` character, and newlines are `\n`. The whole string will be terminated will a null byte `\0`.
In the examples below, I'm using `<>` to mark the fields for readability's sake. These are not present in the actual strings.
## Protocol (Input)
The input string varies in length, depending on how many creatures are visible to your pack. It can exceed 100k characters, so be prepared for that. The basic setup is:
* Line 0: Basic information about the game. `turn` is the current turn number, and the counts are the *total* number of prey and predators left on the field. These are `integer` in string form.
```
<turn>\t<preyCount>\t<predatorCount>\n
```
* Line 1: Your pack members' unique ids and hunger levels. These are **not** given in the same order for every input. Use the unique ids to track individual members, **not** the order in which they appear in the input. Again, these are `integer` as strings. For a pack of two, this would be:
```
<id[0]>\t<hunger[0]>\t<id[1]>\t<hunger[1]>\n
```
* Line 2: Your pack members' positions, in **the same order as given on line 1**. These are `double` as string:
```
<x[0]>\t<y[0]>\t<x[1]>\t<y[1]>\n
```
The following lines are each pack member's visibility, in **the same order as given on line 1**. These will be given as two lines per member.
The first for each consists of locations for the **prey** he can see. The second is locations for the **predators** he can see. These locations are not unique as a whole. For instance, if two pack members can see the same animal, it will be in *both* member's string. Also, your own pack members **will** be included. If you want to exclude them, you may want to compare locations with your own members. All locations are in `double` as string format.
For each living member:
```
<prey[0].x>\t<prey[0].y>\t<prey[1].x>\t<prey[1].y>\n
<predator[0].x>\t<predator[0].y>\t<predator[1].x>\t<predator[1].y>\n
```
Finally, the last character will be `\0`, at the beginning of the next line.
**Exception:** If you receive the input `dead\0`, your pack is dead. End your program gracefully, please. The controller *should* shut down all living processes when closed, but I'd rather not have zombie processes all over the place. As a courtesy, you may include an input timeout. For instance, my example class ends if it does not receive input for 15 seconds.
## Protocol (Output)
Output is simple. You will give a pair of `double` values for each live pack member. These represent the movement you would like them to take on this turn. For example, if your creature is currently at `{100.0, 100.0}` and you give them a command of `{-1.0, 1.0}`, they will move to `{99.0, 101.0}`. All numbers will be on a single line, separated by tab.
For example, if you had 3 pack members alive, this would be a valid response:
```
1.0\t-1.0\t2.0\t-2.0\t3.0\t-3.0\0
```
This would move your creatures by `{1.0,-1.0}`, `{2.0,-2.0}`, and `{3.0,-3.0}`. The order is the same as received in the input. Don't forget the ending `\0`!
If you give invalid input, bad results will follow. If any single number cannot be parsed to a `double`, it will become zero. If the string as a whole can't be parsed, no new instructions will be given, and your entire pack will use the directions from the previous turn.
All directions will be clamped to a maximum distance of 6.1 units. You can move slower than this if you'd like. For instance, `{1, 0}` will move you one unit. `{6,8}`(distance 10) will only move you 6.1 units, and will reduce to around `{3.66, 4.88}`. The direction remains constant.
**Important:** The control program reads both your STDOUT *and* STDERR. If you throw an exception and print to STDERR, it's very unlikely that message will be in the form of a valid response. Try to avoid doing this.
## Control Program / Testing
The source for the controller can be found [here at bitbucket.org](https://bitbucket.org/Geobits/hungergames). You will need to compile it before running. The main class is `Game`, and all classes are in the default package. To run, include each pack's command as a separate argument. For instance, if you want to run a Java ChaserPack and a Python LazyPack.py, you could use:
```
java Game "java ChaserPack" "python LazyPack.py"
```
On the map, prey appear in green, and predators in red. However, whichever pack is the **first** pack given as an argument will be colored blue instead. This is intended to distinguish them more easily for testing purposes. Predators will also flash white for five frames when they eat.
The game will proceed until the last predator starves, writing to the console as starvation or extinction events happen. Once the game is complete, the score will be given for each pack. If you want don't want to see the starvation/extinction events, you can use the `-silent` argument. Then it will only output the final score. **You must pass this as the first argument**:
```
java Game -silent "java ChaserCat" "./someOtherPack"
```
Included is a skeleton Java pack named `GenericPack`. It includes the basic input/output operations needed. It is there to give a clear example of how to parse and reply. If you'd like to add a template in another language, let me know.
Also included is a predator based on the template, `ChaserPack`. It will not be included in the tournament, and is only included for testing purposes. It performs quite badly, due to an intentional targeting flaw. If you can't beat it, keep trying.
Below is an example run of the control program (click for video). The video quality's not great (sorry), but you can get a feel for how the prey move. (*caution: audio*)
[![screenshot](https://i.stack.imgur.com/AOkBH.png)](http://www.youtube.com/watch?v=aCXdBVf8oAM)
## Scoring
Winner will be determined by tournament, gaining points in each round.
Each round proceeds until all predators are dead. Each pack will be scored based on when its last member died of starvation. They will then be assigned points based on the order. Points will accumulate for ten rounds, and the victor is the pack with the highest total points.
First place for each round will receive 100 points. For each place after that, the reward will be reduced by 20%(rounded down). This will continue until the points reach zero(after 17th place). Places 18+ will receive no points for the round. Packs who tie will receive equal points. For example:
```
1st : 100
2nd : 80
3rd : 64 (T)
3rd : 64 (T)
4th : 51
...
17th: 1
18th: 0
19th: 0
```
The maximum possible points over the course of the tournament is 1000, from first place all ten times.
If multiple programs end the tournament tied for first place, another ten round tournament will be held with *only the first-place entries* submitted. This will continue until one victor emerges.
I will try to run a tournament roughly weekly, or as new submissions come in.
## Additional Rules (play fair!)
* You may not read or write to any external resources. Since you're not going to be invoking your program mutliple times, any state information can be stored internally.
* Do not interfere with other processes/submissions. This does *not* mean don't try to steal their prey, outrun them, etc. It means don't interfere with the running of the process. This is at my discretion.
* Contestants are limited to a maximum of **three** entries. If you submit more, I will only score the first three submitted. If you want to revoke one, delete it.
* Entries may not exist solely to prop up other entries. Each should play to win on its own merit.
* Your program may spawn a maximum of one child process at a time (*total* descendants, not direct). Either way, ensure you don't go over the timeout. You may not invoke the `Game` class itself in any way.
## Results - 29 April 2014
Here are the results of the latest ten-round tournament:
```
Clairvoyant : 1000
EcoCamels : 752
Netcats : 688
RubySpiders : 436
RubyVultures : 431
CivilizedBeasts : 382
LazyPack : 257
```
Packs submitted before 09:00 EDT 2014/04/29 are included in this run.
You can also view the [details for each round](http://pastebin.com/raw.php?i=FXKMZCeu). For some reason I decided to number the rounds backwards, so it starts with "round 10".
## Updates
**2014/04/23:** FGreg [reported a bug](http://chat.stackexchange.com/transcript/message/15117398#15117398) related to timeouts (thanks!). A fix has been implemented, so testers will want to update their control program code.
[Answer]
## Netcats
Here's a pack to get you guys started. It extends the `GenericPack` class included with the control program. It's been improved since original posting, and no longer starves itself with a sparse herd.
Netcats use a vee-shaped net formation to trap prey in the corner, where they can eat them at leisure. The net is formed with one "head" member at the center. Once the head eats, it swaps places with the hungriest pack member, since the head is the normally the first to get an opportunity to eat.
The net starts rather small, but widens when the herd gets smaller in order to trawl the field more efficiently.
If no prey are visible, the formation widens into a naive search pattern covering most of the island.
Once the pack gets down to two members, the net just doesn't work. At that point each goes its own way, greedily eating the nearest thing it can find and taking a semi-random walk otherwise.
This version survives much better than the naive Netcats seen in [the video](http://www.youtube.com/watch?v=aCXdBVf8oAM) linked in the question.
```
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
public class Netcats extends GenericPack {
boolean seeking;
Member head = null;
Set<Animal> foods;
public static void main(String[] args) {
new Netcats().run();
}
@Override
public void respond() {
if (foods == null)
foods = new HashSet<Animal>();
else
foods.clear();
for (Member member : members)
foods.addAll(member.foods);
if (members.size() < 3) {
soloRun();
} else {
head = setHead();
setHeadVec();
for (int i = 1; i < members.size(); i++) {
setMemberVec(i);
}
}
}
Member setHead() {
if (!members.contains(head))
return members.get(0);
Member hungry = head;
int idx = 0;
for (int i = 0; i < members.size(); i++) {
Member me = members.get(i);
if (me.hunger < hungry.hunger) {
hungry = me;
idx = i;
}
}
if (hungry != head) {
members.remove(hungry);
members.remove(head);
members.add(0, hungry);
members.add(idx, head);
return hungry;
}
return head;
}
void setHeadVec() {
double x = 0, y = 0;
Collection<Animal> yummy = getFoods(head);
seeking = false;
if (yummy.size() == 0) {
scoutHead();
return;
}
if (members.size() == 1)
if (findFood(head))
return;
for (Animal food : yummy) {
x += food.x - head.x;
y += food.y - head.y;
}
x *= 10000000;
y *= 10000000;
head.dx = x;
head.dy = y;
if (members.size() > 1)
limitSpeed(head, MAX_SPEED * HEAD_MULT);
}
void scoutHead() {
seeking = true;
head.dy = 250 - head.y;
head.dx = round % 80 < 40 ? -head.x : 500 - head.x;
}
void setMemberVec(int idx) {
Member me = members.get(idx);
Member leader;
leader = idx < 3 ? members.get(0) : members.get(idx - 2);
if (findFood(me))
return;
double lx, ly, px, py, tx, ty, dist;
lx = -leader.dx;
ly = -leader.dy;
dist = Math.sqrt(lx * lx + ly * ly) + Double.MIN_NORMAL;
lx /= dist;
ly /= dist;
px = idx % 2 == 0 ? ly : -ly;
py = idx % 2 == 0 ? -lx : lx;
tx = leader.x + leader.dx;
ty = leader.y + leader.dy;
int xtrack = seeking ? COMB : preyCount > 400 ? ASIDE : MID_SIDE;
tx += lx * BEHIND + px * xtrack;
ty += ly * BEHIND + py * xtrack;
me.dx = tx - me.x;
me.dy = ty - me.y;
limitSpeed(me, MAX_SPEED * (idx < 3 ? MID_MULT : 1));
}
Collection<Animal> getFoods(Member me) {
return me.foods.size() == 0 ? foods : me.foods;
}
boolean findFood(Member me) {
if (me.hunger > 500)
return false;
Collection<Animal> yummy = getFoods(me);
if (yummy.size() == 0)
return false;
double x, y, sqDist, cDist = 10 * 10;
Animal target = null;
for (Animal food : me.foods) {
x = food.x - me.x;
y = food.y - me.y;
sqDist = x * x + y * y + Double.MIN_NORMAL;
if (sqDist < cDist) {
cDist = sqDist;
target = food;
}
}
if (target == null)
return false;
if (cDist < 5 * 5 || me.hunger < 200) {
me.dx = (target.x - me.x) * 10000000d;
me.dy = (target.y - me.y) * 10000000d;
return true;
}
return false;
}
void soloRun() {
double x, y, sqDist, cDist;
for (Member me : members) {
Collection<Animal> yummy = getFoods(me);
if (yummy.size() == 0) {
wander(me);
continue;
}
Animal target = null;
cDist = Double.MAX_VALUE;
for (Animal food : yummy) {
x = food.x - me.x;
y = food.y - me.y;
sqDist = x * x + y * y + Double.MIN_NORMAL;
if (sqDist < cDist) {
cDist = sqDist;
target = food;
}
}
me.dx = (target.x - me.x) * 100000d;
me.dy = (target.y - me.y) * 100000d;
}
}
void wander(Member me) {
if (me.dx == 0 && me.dy == 0) {
me.dx = 250 - me.x;
me.dy = 250 - me.y;
return;
}
double lx, ly, px, py;
lx = me.dx / 4;
ly = me.dy / 4;
boolean dir = Math.random() < 0.5 ? true : false;
px = dir ? ly : -ly;
py = dir ? -lx : lx;
me.dx += px;
me.dy += py;
}
void limitSpeed(Member me, double max) {
double x = me.dx, y = me.dy;
double dist = Math.sqrt(x * x + y * y) + Double.MIN_NORMAL;
if (dist > max) {
x = (x / dist) * max;
y = (y / dist) * max;
}
me.dx = x;
me.dy = y;
}
final static double MAX_SPEED = 6.1;
final static double HEAD_MULT = 0.85;
final static double MID_MULT = 0.92;
final static int BEHIND = -25;
final static int ASIDE = 15;
final static int MID_SIDE = 30;
final static int COMB = 150;
}
```
[Answer]
## Ruby Spiders
As sometimes *less is more* and many solutions would probably try to corner the prey anyway...
I thought my pack could just split up and wait for others to do the work.
```
gets
print "3.0\t3.0\t3.0\t-3.0\t-3.0\t-3.0\t-3.0\t3.0\t0.0\t0.0\0"
STDOUT.flush
```
Caveat: It doesn't actually stay running, neither does it read input as it comes in nor responds quickly. Still, as it works well with the controller I hope it qualifies without further adjustments.
[Answer]
# CivilizedBeasts
Finally, time to show off my beasts!
My breed thinks hunting is somewhat primitive so they work together in a team of 4 and so they abandon their 5th ally, because: less predators = more prey for themselves. What they basically do is what humans do, they catch prey, and take good care of their cattle ;)
```
public class CivilizedBeasts extends GenericPack{
private static int TL = 0, TR = 0, BL = 0, BR = 0; // TopLeft/BotRight
private static int teamSize = 0, turnsWaiting = 0, turnsToWait = 20;
private boolean out = true;
private double maxSpeed = 6.1, mapSize = 500;
public CivilizedBeasts(){
}
@Override
public void respond(){
if(teamSize > members.size()){
Member check = getMemberById(TL);
totalLoop:
if(check == null){
for (Member member : members) {
if(member.id != TR && member.id != BL && member.id != BR){
TL = member.id;
break totalLoop;
}
}
TL = 0;
}
check = getMemberById(TR);
totalLoop:
if(check == null){
for (Member member : members) {
if(member.id != TL && member.id != BL && member.id != BR){
TR = member.id;
break totalLoop;
}
}
TR = 0;
}
check = getMemberById(BL);
totalLoop:
if(check == null){
for (Member member : members) {
if(member.id != TL && member.id != TR && member.id != BR){
BL = member.id;
break totalLoop;
}
}
BL = 0;
}
check = getMemberById(BR);
totalLoop:
if(check == null){
for(Member member : members) {
if(member.id != TL && member.id != TR && member.id != BL){
BR = member.id;
break totalLoop;
}
}
BR = 0;
}
}else if(teamSize < members.size()){
for(Member member : members) {
if(member.id != TL && member.id != TR && member.id != BL && member.id != BR){
if(TL == 0)
TL = member.id;
else if(TR == 0)
TR = member.id;
else if(BL == 0)
BL = member.id;
else if(BR == 0)
BR = member.id;
}
}
}
teamSize = members.size();
double border = 1;
double x, y;
boolean reached = true;
double distance = 16.3;
for (Member member : members) {
boolean doesNotCount = false;
x = 0; y = 0;
if(member.id == TL){
if(out){
x = -(member.x - border);
y = -(member.y - border);
}else{
x = ((mapSize/2 - distance) - member.x);
y = ((mapSize/2 - distance) - member.y);
}
}else if(member.id == TR){
if(out){
x = (mapSize - member.x - border);
y = -(member.y - border);
}else{
x = ((mapSize/2 + distance) - member.x);
y = ((mapSize/2 - distance) - member.y);
}
}else if(member.id == BL){
if(out){
x = -(member.x - border);
y = (mapSize - member.y - border);
}else{
x = ((mapSize/2 - distance) - member.x);
y = ((mapSize/2 + distance) - member.y);
}
}else if(member.id == BR){
if(out){
x = (mapSize - member.x - border);
y = (mapSize - member.y - border);
}else{
x = ((mapSize/2 + distance) - member.x);
y = ((mapSize/2 + distance) - member.y);
}
}else{
double dist = 50, temp = 0;
int index = -1;
for(int i = 0; i < member.foods.size(); i++){
temp = (Math.abs(member.foods.get(i).x - member.x)+Math.abs(member.foods.get(i).y - member.y));
if(temp < dist){
dist = temp;
index = i;
}
}
if(index != -1){
x = (member.foods.get(index).x - member.x);
y = (member.foods.get(index).y - member.y);
}
doesNotCount = true;
}
if(!doesNotCount && Math.abs(x)+Math.abs(y) > maxSpeed)
reached = false;
member.setDirection(x,y);
}
if(reached){
if(!out){ // in the middle.
if(teamSize < 4){
int temp = TL;
TL = BR;
BR = temp;
temp = TR;
TR = BL;
BL = temp;
out = true;
}else{
turnsWaiting++;
}
}else // no need to wait in the corners
out = false;
if(turnsWaiting >= turnsToWait){
turnsToWait = 15;
out = true;
turnsWaiting = 0;
}
}
}
public static void main(String[] args){
new CivilizedBeasts().run();
}
}
```
It becomes quite difficult for my breasts to survive with less than 200 prey at turn +-12.000 with only enemy Netcats in the game. You will be happy with this breed since it really devours massive amounts of prey with speed like no other breed ever can (not that quick and big slaughters grants victory, but it influences the (long) time a whole round takes considerably).
[Answer]
## Clairvoyant
**Code updated to face AbleDogs**
Woo hoo! Finally beats that Netcats! I expanded existing code (credits to Geobits!) with some small modification to create this future predicting pack. Nothing beats predators who know where the prey will move!
From two tests that I've done, my pack always won against Netcats. But this will not perform as good if there are no other packs, as the prediction still fails if there are too many other preys in vicinity.
Probably I can include the trick of CivilizedBeasts to reduce the number of preys substantially during the first few thousands turns.
```
Done in 5.21 minutes
Clairvoyant(1) : Turn 9270 : Score 100
EcoCamel.pl(3) : Turn 8118 : Score 80
Netcats(0) : Turn 6111 : Score 64
RubyVultures.rb(5) : Turn 4249 : Score 51
RubySpiders.rb(4) : Turn 3495 : Score 40
CivilizedBeasts(2) : Turn 3176 : Score 32
ChaserPack(6) : Turn 2492 : Score 25
```
From the name of my pack, you should know what strategy I use =D
*Edit*:
* Updated pack management system to not chase the same prey (and also try to find best match!)
* Improve wandering process when the number of preys is small (this is crucial for a win!).
* ~~Improve special cases when the previous version just stuck at the corner.~~
* Fixed a bug in predator detecting algorithm (now it's quite accurate!)
* Included prey `flock[ALIGN]` factor
* Keep one prey as a pet if the food is scarce
* Create a den where the pack will herd their preys into
* Lure nearby predator into chasing our prey, which they won't win
I counted how many preys each pack eats, and here is the result:
```
Clairvoyant(1) consumed 916 preys in 9270 turns (0.099 preys/turn)
EcoCamel.pl(3) consumed 73 preys in 8118 turns (0.009 preys/turn)
Netcats(0) consumed 563 preys in 6111 turns (0.092 preys/turn)
RubyVultures.rb(5) consumed 77 preys in 4249 turns (0.018 preys/turn)
RubySpiders.rb(4) consumed 293 preys in 3495 turns (0.084 preys/turn)
CivilizedBeasts(2) consumed 10 preys in 3176 turns (0.003 preys/turn)
ChaserPack(6) consumed 43 preys in 2492 turns (0.017 preys/turn)
```
My pack is very aggressive, and most of the 916 counts I think it gets from stealing preys from Netcats, just like RubySpiders.
CivilizedBeasts is unfortunately losing due to the center camel from EcoCamel.
And EcoCamel (with hunger critical 500) is pretty efficient, it eats just enough to survive to the end.
Also with this updated Clairvoyant, the game barely reach 10,000 turns.
The code:
```
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.TreeSet;
public class Clairvoyant extends GenericPack {
private static final double MAX_SPEED = 6.1;
private TreeSet<Animal> foods = new TreeSet<Animal>(new AnimalComparator());
private TreeSet<Animal> predators = new TreeSet<Animal>(new AnimalComparator());
private XY abattoirCorner;
private double abattoirRadius = 100;
private MyMember[] myMembers = new MyMember[100];
public class AnimalComparator implements Comparator<Animal>{
@Override
public int compare(Animal arg0, Animal arg1) {
if(arg0.x < arg1.x){
return -1;
} else if (arg0.x > arg1.x){
return 1;
} else {
if(arg0.y < arg1.y){
return -1;
} else if(arg0.y > arg1.y){
return 1;
} else {
return 0;
}
}
}
}
public class MyMember extends Member{
public XY target;
public XY herdPos;
public double herdRadius;
public boolean mayEat;
public XY pos;
public ArrayList<MyAnimal> closestPreys;
public boolean outdated;
public MyMember(int id) {
super(id);
this.pos = new XY(x, y);
closestPreys = new ArrayList<MyAnimal>();
mayEat = true;
outdated = true;
}
public MyMember(Member member){
super(member.id);
this.pos = new XY(x, y);
closestPreys = new ArrayList<MyAnimal>();
mayEat = true;
outdated = true;
}
public MyMember(Member member, Animal target){
super(member.id);
this.target = new XY(target.x, target.y);
this.pos = new XY(x, y);
closestPreys = new ArrayList<MyAnimal>();
mayEat = true;
outdated = true;
}
public void reset(Member me){
x = me.x;
y = me.y;
pos = new XY(x, y);
closestPreys.clear();
mayEat = true;
outdated = true;
}
}
public class MyAnimal extends Animal{
public ArrayList<MyMember> chasers;
public XY pos;
public boolean resolved;
public MyAnimal(double x, double y){
super(x, y);
pos = new XY(x, y);
chasers = new ArrayList<MyMember>();
resolved = false;
}
public MyAnimal(Animal ani){
super(ani.x, ani.y);
pos = new XY(x, y);
chasers = new ArrayList<MyMember>();
resolved = false;
}
}
public static void main(String[] args){
new Clairvoyant().run();
}
public Clairvoyant(){
for(int i=0; i<100; i++){
nextIdx[i] = 0;
}
int cornerIdx = (int)Math.floor(Math.random()*4);
switch (cornerIdx){
case 0: abattoirCorner = new XY(0,0); break;
case 1: abattoirCorner = new XY(500,0); break;
case 2: abattoirCorner = new XY(500,500); break;
case 3: abattoirCorner = new XY(0,500); break;
}
}
@Override
public void respond(){
updateData();
goToTarget();
}
private void updateData(){
for(int i=0; i<100; i++){
if(myMembers[i]!=null){
myMembers[i].pos = null;
}
}
foods.clear();
predators.clear();
for(Member me: members){
foods.addAll(me.foods);
predators.addAll(me.others);
predators.add(new Animal(me.x, me.y));
if(myMembers[me.id] != null){
myMembers[me.id].reset(me);
} else {
myMembers[me.id] = new MyMember(me);
}
}
for(int i=0; i<100; i++){
if(myMembers[i]!=null && myMembers[i].pos == null){
myMembers[i] = null;
}
}
TreeSet<MyAnimal> closestPreys = new TreeSet<MyAnimal>(new AnimalComparator());
for(int i=0; i<100; i++){
if (myMembers[i]==null) continue;
MyMember me = myMembers[i];
ArrayList<Animal> animals = findClosest(foods, me.pos, members.size());
boolean first = true;
for(Animal ani: animals){
MyAnimal myAni = new MyAnimal(ani);
if(closestPreys.contains(ani)){
myAni = closestPreys.ceiling(myAni);
} else {
closestPreys.add(myAni);
}
if(first){
myAni.chasers.add(me);
first = false;
}
me.closestPreys.add(myAni);
}
}
performMatching();
for(int i=0; i<100; i++){
if (myMembers[i] == null) continue;
MyMember me = myMembers[i];
if(!me.outdated) continue;
if(me.closestPreys.size() == 0) continue;
MyAnimal closestPrey = me.closestPreys.get(0);
if(closestPrey.resolved) continue;
if(closestPrey.chasers.size() > 1){
MyMember hungriest = me;
MyMember closest = me;
for(MyMember otherMe: closestPrey.chasers){
if(sqDist(closestPrey.pos, otherMe) < sqDist(closestPrey.pos, closest)){
closest = otherMe;
}
if(otherMe.hunger < hungriest.hunger){
hungriest = otherMe;
}
}
if(hungriest.hunger > 200){ // Nobody's critically hungry, the closest takes the prey
closest.target = closestPrey.pos;
closest.mayEat = true;
closest.herdPos = abattoirCorner;
closest.herdRadius = abattoirRadius;
closest.outdated = false;
} else {
if(hungriest == closest){
closest.target = closestPrey.pos;
closest.mayEat = true;
closest.herdPos = abattoirCorner;
closest.herdRadius = abattoirRadius;
closest.outdated = false;
} else {
closest.target = closestPrey.pos;
closest.mayEat = false;
closest.herdPos = hungriest.pos;
closest.herdRadius = 0;
closest.outdated = false;
hungriest.target = closestPrey.pos;
hungriest.mayEat = true;
hungriest.herdPos = abattoirCorner;
hungriest.herdRadius = 10;
hungriest.outdated = false;
}
}
closestPrey.resolved = true;
} else {
me.target = closestPrey.pos;
me.herdPos = abattoirCorner;
me.herdRadius = abattoirRadius;
me.mayEat = true;
me.outdated = false;
}
}
for(int i=0; i<100; i++){
if (myMembers[i] == null) continue;
MyMember me = myMembers[i];
if(me.outdated){
me.target = null;
me.outdated = false;
}
}
}
private void goToTarget(){
for(Member me: members){
MyMember mem = myMembers[me.id];
if(mem.target == null){
wander(me, 2*(me.id%2)-1);
continue;
} else {
nextIdx[me.id] = 0;
XY[] nearestHostile = new XY[100];
for(Animal other: me.others){
XY otherPos = new XY(other.x, other.y);
boolean isMember = false;
for(Member otherMember: members){
if(other.x==otherMember.x && other.y==otherMember.y){
isMember = true;
break;
}
}
if(!isMember){
if(nearestHostile[me.id] == null || XY.sqDistance(mem.pos, otherPos) < XY.sqDistance(mem.pos, nearestHostile[me.id])){
nearestHostile[me.id] = otherPos;
}
}
}
// Go towards the target by predicting its next position
XY target = predictNextPos(mem.target, me);
me.dx = (target.x - me.x);
me.dy = (target.y - me.y);
// Try to herd the target to our abattoir if this member is not too hungry
// and if there is no other hostile predator who is closer to the target than us
// This will make the other hostile predator to keep targeting this target, while
// it is certain that we will get the target.
// This is a win situation for us, since it will make the other predator wasting his turn.
if((me.hunger <= 200 && XY.sqDistance(mem.target, mem.pos) > 400) || me.hunger <= 50 ||
(nearestHostile[me.id] != null && Math.sqrt(XY.sqDistance(mem.target, nearestHostile[me.id])) < Math.sqrt(XY.sqDistance(mem.target, mem.pos)))){
continue;
}
// Don't eat if not threatened nor hungry
if(me.hunger > 50 && (nearestHostile[me.id] == null ||
Math.sqrt(XY.sqDistance(mem.target, nearestHostile[me.id])) > Math.sqrt(XY.sqDistance(mem.target, mem.pos)) + 6)){
mem.mayEat = false;
}
// Herd to abattoir corner
double distFromHerd = Math.sqrt(XY.sqDistance(target, mem.herdPos));
XY oppositeAbattoirCorner = new XY(500-abattoirCorner.x, 500-abattoirCorner.y);
double distFromOpposite = Math.sqrt(XY.sqDistance(target, oppositeAbattoirCorner));
if((me.dx*me.dx+me.dy*me.dy > 64 && distFromHerd > mem.herdRadius && distFromOpposite > abattoirRadius)
|| (preyCount < 5*predCount)){
double herdDistance = 4*(distFromHerd-mem.herdRadius)/(Island.SIZE-mem.herdRadius);
if(!mem.mayEat) herdDistance = 4;
XY gradient = target.minus(abattoirCorner);
me.dx += gradient.x*herdDistance/distFromHerd;
me.dy += gradient.y*herdDistance/distFromHerd;
}
}
}
}
private void performMatching(){
for(int i=0; i<100; i++){
if (myMembers[i] == null) continue;
MyMember me = myMembers[i];
if(me.closestPreys.size()==0) continue;
MyAnimal closestPrey = me.closestPreys.get(0);
if(closestPrey.chasers.size() > 1){
resolveConflict(closestPrey);
}
}
}
private void resolveConflict(MyAnimal prey){
ArrayList<MyMember> chasers = prey.chasers;
MyMember winner = null;
double closestDist = Double.MAX_VALUE;
for(MyMember me: chasers){
if(sqDist(prey.pos, me) < closestDist){
closestDist = sqDist(prey.pos, me);
winner = me;
}
}
for(int i=chasers.size()-1; i>=0; i--){
MyMember me = chasers.get(i);
if(me!=winner){
me.closestPreys.get(0).chasers.remove(me);
me.closestPreys.add(me.closestPreys.remove(0));
me.closestPreys.get(0).chasers.add(me);
}
}
}
private Animal findClosest(Collection<Animal> preys, XY me){
Animal target = null;
double cDist = Double.MAX_VALUE;
double x, y, sqDist;
for (Animal food : preys) {
x = food.x - me.x;
y = food.y - me.y;
sqDist = x * x + y * y + Double.MIN_NORMAL;
if (sqDist < cDist) {
cDist = sqDist;
target = food;
}
}
return target;
}
private ArrayList<Animal> findClosest(Collection<Animal> preys, XY me, int num){
ArrayList<Animal> result = new ArrayList<Animal>();
for(Animal food: preys){
int addIdx = -1;
for(int i=0; i<num && i<result.size(); i++){
Animal regFood = result.get(i);
if(sqDist(me, food) < sqDist(me, regFood)){
addIdx = i;
break;
}
}
if(addIdx == -1){
result.add(food);
} else {
result.add(addIdx, food);
}
if(result.size() > num){
result.remove(num);
}
}
return result;
}
private Member findClosestToTarget(Collection<Member> members, Animal target){
Member member = null;
double cDist = Double.MAX_VALUE;
double x, y, sqDist;
for (Member me : members) {
x = me.x - target.x;
y = me.y - target.y;
sqDist = x * x + y * y + Double.MIN_NORMAL;
if (sqDist < cDist) {
cDist = sqDist;
member = me;
}
}
return member;
}
private static final XY[] CHECKPOINTS = new XY[]{
new XY(49.5,49.5),
new XY(450.5,49.5),
new XY(450.5,100),
new XY(49.5,100),
new XY(49.5,150),
new XY(450.5,150),
new XY(450.5,200),
new XY(49.5,200),
new XY(49.5,250),
new XY(450.5,250),
new XY(450.5,300),
new XY(49.5,300),
new XY(49.5,350),
new XY(450.5,350),
new XY(450.5,400),
new XY(49.5,400),
new XY(49.5,450.5),
new XY(450.5,450.5)};
private int[] nextIdx = new int[100];
private int advanceIdx(int idx, int sign, int amount){
return sign*(((Math.abs(idx)+CHECKPOINTS.length-1+sign*amount) % CHECKPOINTS.length) + 1);
}
private void wander(Member me, int sign) {
if(preyCount > 20*predCount){
if (me.dx == 0 && me.dy == 0) {
me.dx = 250 - me.x;
me.dy = 250 - me.y;
return;
}
double lx, ly, px, py;
lx = me.dx / 4;
ly = me.dy / 4;
boolean dir = Math.random() < 0.5 ? true : false;
px = dir ? ly : -ly;
py = dir ? -lx : lx;
me.dx += px;
me.dy += py;
} else {
if(nextIdx[me.id]==0){
XY farthest = new XY(2000,2000);
int farthestIdx = -1;
for(int i=0; i<CHECKPOINTS.length; i++){
if(sign*sqDist(CHECKPOINTS[i], me) > sign*sqDist(farthest, me)){
farthest = CHECKPOINTS[i];
farthestIdx = i+1;
}
}
nextIdx[me.id] = farthestIdx*sign;
for(Member mem: members){
if(mem.id == me.id) continue;
if(nextIdx[mem.id]==nextIdx[me.id]){
nextIdx[me.id] = advanceIdx(nextIdx[me.id], sign, 5);
}
}
}
if(sqDist(CHECKPOINTS[Math.abs(nextIdx[me.id])-1],me) < 1){
nextIdx[me.id] = advanceIdx(nextIdx[me.id], sign, 1);
}
me.setDirection(CHECKPOINTS[Math.abs(nextIdx[me.id])-1].x-me.x,
CHECKPOINTS[Math.abs(nextIdx[me.id])-1].y-me.y);
}
}
private double sqDist(XY me, Animal target){
double dx = me.x-target.x;
double dy = me.y-target.y;
return dx*dx + dy*dy + Double.MIN_NORMAL;
}
private double sqDist(XY me, Member target){
double dx = me.x-target.x;
double dy = me.y-target.y;
return dx*dx + dy*dy + Double.MIN_NORMAL;
}
private double sqDist(Animal target, Member me){
double dx = me.x-target.x;
double dy = me.y-target.y;
return dx*dx + dy*dy + Double.MIN_NORMAL;
}
private List<Animal> getNeighbors(double radius, XY pos, Collection<Animal> candidates) {
List<Animal> neighbors = new ArrayList<Animal>();
for(Animal neighbor: candidates){
if(sqDist(pos, neighbor) < radius * radius){
neighbors.add(neighbor);
}
}
return neighbors;
}
final double[] weights = { 1, 1, 0.96, 2, 4 };
double weightSum;
static final int ALIGN = 0;
static final int SEPARATE = 1;
static final int COHESION = 2;
static final int FLEE = 3;
static final int WALL = 4;
static final int VISIBLE = 30;
static final int VISIBLE_PRED = 50;
private HashMap<Member, List<Animal>> prevPreys = new HashMap<Member, List<Animal>>();
private XY matchPreys(List<Animal> prevs, List<Animal> curs, XY prey){
XY result = new XY();
double sqDist = 0;
Animal candidate;
XY otherPos;
for(Animal otherPrey: curs){
otherPos = new XY(otherPrey.x, otherPrey.y);
sqDist = XY.sqDistance(prey, otherPos);
if(sqDist > VISIBLE * VISIBLE)
continue;
candidate = findClosest(getNeighbors(6, otherPos, prevs), prey);
if(candidate == null){
return null;
}
result.add(otherPos.x-candidate.x, otherPos.y-candidate.y);
}
return result;
}
private XY predictNextPos(XY prey, Member me) {
List<Animal> preys = getNeighbors(VISIBLE_PRED, prey, foods);
List<Animal> preds = getNeighbors(VISIBLE, prey, predators);
XY flock[] = new XY[weights.length];
for (int i = 0; i < weights.length; i++)
flock[i] = new XY();
double dx, dy, dist, sqDist;
for (Animal otherPrey : preys) {
sqDist = XY.sqDistance(prey, new XY(otherPrey.x, otherPrey.y));
if(sqDist > VISIBLE * VISIBLE)
continue;
dx = otherPrey.x - prey.x;
dy = otherPrey.y - prey.y;
flock[COHESION].add(dx*sqDist, dy*sqDist);
flock[SEPARATE].add(-dx*(1d/sqDist), -dy*(1d/sqDist));
flock[ALIGN].add(new XY(prey.x-me.x,prey.y-me.y));
}
if(sqDist(prey, me) < 400){
if(prevPreys.get(me) == null){
prevPreys.put(me, preys);
} else {
XY flockAlign = matchPreys(prevPreys.get(me), preys, prey);
if(flockAlign == null){
prevPreys.put(me , null);
} else {
flock[ALIGN] = flockAlign;
prevPreys.put(me, preys);
}
}
}
flock[ALIGN].unitize().multiply(5);
flock[COHESION].unitize().multiply(5);
flock[SEPARATE].unitize().multiply(5);
for (Animal predator : preds){
flock[FLEE].add(prey.x-predator.x, prey.y-predator.y);
}
dx = Island.CENTER.x - prey.x;
dy = Island.CENTER.y - prey.y;
dist = Math.max(Math.abs(dx), Math.abs(dy));
if(dist > 240){
flock[WALL].x = dx * dist;
flock[WALL].y = dy * dist;
flock[WALL].unitize().multiply(5);
}
XY vec = new XY();
vec.x = 0;
vec.y = 0;
for (int i = 0; i < flock.length; i++) {
flock[i].multiply(weights[i]);
vec.add(flock[i]);
}
limitSpeed(vec);
return vec.add(prey);
}
private XY limitSpeed(XY move) {
if (move.x*move.x+move.y*move.y > MAX_SPEED*MAX_SPEED)
move.unitize().multiply(MAX_SPEED);
return move;
}
}
```
[Answer]
## Ruby Vultures
Here comes a pack of more **active parasites**. They are trying to **surround closest moving predator**, so that they can **steal his prey**. They are a bit luck dependent as they have no smart way of choosing who to follow but they are usually **beating chasers and sometimes spiders**.
They are not quite finished, as I posted this to push the tempo :)
I'm hoping to:
* make them **search for predators** outside of the field of view
* **take prey into account** - often one of them is between another pack and the prey!
* **start rotating** them to avoid one starving when all other are well fed
**22 April 2014:** Added **boredom**, which makes them less **less sticky** and allows them to **hunt for prey** on their own and **search for predators**
```
class Animal
attr_accessor :x, :y
end
class Hunter < Animal
attr_accessor :id, :bored
def initialize diff
@diff = diff
@lastGoal = nil
@bored = false
end
def move goal
if not goal.nil?
if @bored or goal != @lastGoal
@lastGoal = goal
return [goal.first - x + @diff.first, goal.last - y + @diff.last]
end
end
[250 - x + 3*@diff.first, 250.0 - y + 3*@diff.last]
end
end
class Pack
def initialize
@file = File.open "pack_log", "w"
@count = 0
@pack = []
@order = []
@hunters = []
@closest = nil
@random_goal = [250.0, 250.0]
@locations = []
@timer = 0
d = 25.0
diffs = [[d, d], [d, -d], [-d, -d], [-d, d], [0.0, 0.0]]
5.times do |i|
@pack << (Hunter.new diffs[i])
end
line = 0
s = gets
loop do
s = gets
if not (s =~ /dead\0/).nil?
break
end
if line == 0
get_structure s
elsif line == 1
get_positions s
end
@pack.length.times do |i|
if line == i*2 + 3
look_for_hunters s
if @count <= i+1
@closest = closest_hunter
move
end
end
end
if not (s =~ /\0/).nil?
line = 0
@hunters = []
else
line += 1
end
end
end
def member_by_id id
member = nil
@pack.each do |v|
if v.id == id
member = v
break
end
end
member
end
def member_by_order index
member_by_id @order[index]
end
def distance a, b
Math.sqrt((a.first - b.first)**2 + (a.last - b.last)**2)
end
def bored?
bored = true
l1 = @locations.first
@locations.each do |l2|
if distance(l1, l2) > 20
bored = false
end
end
bored
end
def bored_move v
if @timer <= 0
@random_goal = [rand(1000).to_f - 250, rand(1000).to_f - 250]
@pack.each do |m|
m.bored = true
end
@timer = 250
else
@timer -= 1
end
v.move @random_goal
end
def move
first_one = true
answer = ""
@order.each do |id|
v = member_by_id id
x, y = 0, 0
if bored?
x, y = (bored_move v)
elsif @timer > 0
@location = []
x, y = (bored_move v)
else
@pack.each do |m|
m.bored = false
end
@timer = 0
x, y = v.move @closest
end
if not first_one
answer << "\t"
end
answer << "#{x.to_i}.0\t#{y.to_i}.0"
first_one = false
end
answer << "\0"
print answer
STDOUT.flush
end
def get_structure line
@order = []
if @pack.first.id.nil?
@count = 0
line.split.each_with_index do |v, i|
if i % 2 == 0
@order << v.to_i
@pack[i/2].id = v.to_i
@count += 1
end
end
else
@count = 0
line.split.each_with_index do |v, i|
if i % 2 == 0
@order << v.to_i
@count += 1
end
end
end
end
def get_positions line
if not @order.empty?
line.split.each_with_index do |v, i|
if i % 2 == 0
member_by_order(i/2).x = v.to_f
else
member_by_order(i/2).y = v.to_f
end
end
end
end
def look_for_hunters line
line.split.each_with_index do |v, i|
if i % 2 == 0
@hunters << [v.to_f]
else
@hunters.last << v.to_f
end
end
end
def closest_hunter
mass_center
closest = nil
bestDist = 500*500
if not @hunters.nil? and not @hunters == []
@hunters.each do |h|
our = false
@pack.each do |v|
if h.first == v.x and h.last == v.y
our = true
end
end
if our
next
end
sqDist = (@mass_center.first - h.first)**2 + (@mass_center.last - h.last)**2
if sqDist < bestDist
closest = []
closest << h.first
closest << h.last
end
end
end
closest
end
def mass_center
center_x = 0
center_y = 0
@pack.each do |v|
center_x += v.x
center_y += v.y
end
@mass_center = [center_x.to_f / @count, center_y.to_f / @count]
if @locations.length > 30
@locations.shift
@locations << @mass_center
else
@locations << @mass_center
end
end
end
Pack.new
```
[Answer]
## ~~Evil~~ Eco Camels
**Edit: Mutation #2.** Oh, no, I'm late with my implementation of prey movement prediction, to be the first to beat the Netcats. OK, so be it.
This mutation has `$hunger_critical` variable (constant). Changing it to value above 1000 makes Camels to always hunt, like Clairvoyants. Then:
```
Done in 11.93 minutes
camels1.pl(0) : Turn 23112 : Score 100
Netcats(1) : Turn 22508 : Score 80
```
If `$hunger_critical` is set to e.g. 500 (as below), then my Camels (after seeing the horrors of ***civilization***) try to behave in Eco-friendly manner (hence they have changed the name of their breed), i.e. they kill only when hungry. If not hungry, they patrol critical Island areas - center and corners, to prevent pointless butchering by some other hunters. Well, with center, it more or less works. The idea of circling in corners was to shoo the prey away and make life more difficult for the Cats and parasites. Well, it doesn't work. Stupid prey goes into corners anyway.
Its interesting, also, that the `flock[ALIGN]` component can only be guessed, by predators, and my implementation is different than justhalf's. I'm afraid there's some minor bug in my ~~rip-off~~ implementation of Geobits' code, watching/comparing individual hunting of Camels vs Clairvoyants.
And program is kind of long now, sorry.
---
**Edit : Mutation #1.** The Island turns out to be quite radioactive (that explains lack of vegetation and unexplainable nature of 'prey' creatures), so here's first mutation of my Camels. Any of them can become solo hunter, if hungry or if there's no free corner for everyone. Hunter tries to actively pursue nearby prey. If there's none, it patrols in wide circle around center of the island, then chases nearest creature when finds it. Unfortunately, prey's direction becomes unpredictable when it's near its swarm (worth investigating...), so solo chase is not very efficient. But if it succeeds, the Camel goes to digest to the nearest free corner (if any). When hunger level is below certain level, any Camel abandons its corner (probably cursing Netcats ('where's food?')) and goes free roaming on its own. And so on.
---
Same joke told twice is not funny, but (1) I had to start somewhere and I'm new to these things, (2) Honest, I thought about corner tactics (and who didn't?), watching Netcats, before Ruby Spiders appeared on the Island.
So, ever heard about carnivore camels? Poor animals woke up one day on this god-forsaken Island to find no grass nor trees at all, but plenty of strange green though edible fast moving (quite annoying) little things. Having no hunting habits (but they'll mutate soon, I hope), my Camels developed very evil scheme to survive: they split and go each into 1 of 4 corners, and 5th one goes to the center (to die there first, as it turnes out). On their destinations they patiently wait, performing kind of camel war-dance, or maybe they just try not to tread on other animals already there, spiders and all...
```
#!/usr/bin/env perl
use strict;
use warnings;
binmode STDOUT;
binmode STDIN;
$| = 1;
$, = "\t";
my $hunger_critical = 500;
my %pack;
my ($turn, $prey_count, $predators_count);
my $patrol_radius_hunt = 150;
my $patrol_radius_corner = 16;
my $patrol_radius_center = 1;
my @roles = qw/C LL LR UL UR/; # or P (patrol if > 5), H (hunt)
my %places = (
UL => {x => 1 + $patrol_radius_corner, y => 1 + $patrol_radius_corner},
UR => {x => 499 - $patrol_radius_corner, y => 1 + $patrol_radius_corner},
LR => {x => 499 - $patrol_radius_corner, y => 499 - $patrol_radius_corner},
LL => {x => 1 + $patrol_radius_corner, y => 499 - $patrol_radius_corner},
C => {x => 250, y => 250},
);
sub sq_dist {
my ($x1, $y1, $x2, $y2) = @_;
return ($x1 - $x2)**2 + ($y1 - $y2)**2
}
sub distance {
return sqrt(&sq_dist)
}
sub assign_role {
my $camel = shift;
if (@roles) {
my %choice = (d => 1000, i => 0);
for my $i (0..$#roles) {
my $r = $roles[$i];
if ($r eq 'C') {
if ($prey_count > 700) {
$choice{i} = $i;
last
}
else {
next
}
}
my $d = distance($camel->{x}, $camel->{y}, $places{$r}{x}, $places{$r}{y});
if ($d < $choice{d}) {
@choice{qw/d i/} = ($d, $i)
}
}
return splice @roles, $choice{i}, 1
}
else {
return 'P'
}
}
sub xy_average {
my $xy = shift;
my $x = my $y = 0;
if ($xy && @$xy) {
for my $item (@$xy) {
$x += $item ->{x};
$y += $item->{y}
}
$x /= @$xy;
$y /= @$xy
}
return $x, $y
}
sub patrol {
my ($xc, $yc, $radius, $camel) = @_;
my ($x, $y) = ($camel->{x} - $xc, $camel->{y} - $yc);
my $d = distance(0, 0, $x, $y);
my $a = atan2($y, $x);
if (abs($d - $radius) < 3) {
$a += 6 / $radius
}
return $radius * cos($a) - $x, $radius * sin($a) - $y
}
while (1) {
# Get input
my @in;
# Line 0 - turn, counts
$_ = <>;
die if /dead/;
($turn, $prey_count, $predators_count) = /\0?(\S+)\t(\S+)\t(\S+)/;
# Line 1 - pack's ids and hunger
$_ = <>;
while (/(\S+)\t(\S+)/g) {
push @in, {id => $1, hunger => $2}
};
# Line 2 - positions
$_ = <>;
for my $animal (@in) {
/(\S+)\t(\S+)/g;
($animal->{x}, $animal->{y}) = ($1, $2);
}
# 2 lines per member, visible prey and predators
for my $animal (@in) {
$_ = <>;
my @prey;
while (/(\S+)\t(\S+)/g) {
push @prey, {x => $1, y => $2}
};
$animal->{prey} = \@prey;
$_ = <>;
my @beasts;
while (/(\S+)\t(\S+)/g) {
push @beasts, {x => $1, y => $2}
};
$animal->{beasts} = \@beasts
}
# trailing \0 zero will be prepended to next turn input
# Update my pack
for my $n (0..$#in) {
my $animal = $in[$n];
my $id = $animal->{id};
# old average prey position
my @opp = xy_average($pack{$id}{prey});
# new average prey position
my @npp = xy_average($animal->{prey});
# average prey displacement
my %apd = (x => $npp[0] - $opp[0], y => $npp[1] - $opp[1]);
$pack{$id}{apd} = \%apd;
$pack{$id}{hunger} = $animal->{hunger};
$pack{$id}{x} = $animal->{x};
$pack{$id}{y} = $animal->{y};
$pack{$id}{prey} = $animal->{prey};
$pack{$id}{beasts} = $animal->{beasts};
$pack{$id}{num} = $n;
$pack{$id}{dead} = 0
}
# Bury dead animals, retrieve their roles
while (my ($id, $camel) = each %pack) {
if ($camel->{dead}) {
my $role = $camel->{role};
push @roles, $role if $role ne 'P' and $role ne 'H';
delete $pack{$id};
}
else {
$camel->{dead} = 1
}
}
# See that everyone has a role and lives accordingly
my @out;
for my $camel (values %pack) {
my $role = $camel->{role} ||= assign_role($camel);
if ($camel->{hunger} < $hunger_critical and $role ne 'H') {
push @roles, $role if $role ne 'P';
$role = $camel->{role} = 'H'
}
if ($camel->{hunger} > $hunger_critical and ($role eq 'H' or $role eq 'P') and $prey_count > 400) {
$role = $camel->{role} = assign_role($camel)
}
my @vector = (0, 0);
if ($role eq 'H') {
my @prey = @{$camel->{prey}};
if (@prey) {
my %nearest = (p => undef, dd => 2500);
for my $prey (@prey) {
my $dd = sq_dist($camel->{x}, $camel->{y}, $prey->{x}, $prey->{y});
if ($dd <= $nearest{dd}) {
@nearest{qw/p dd/} = ($prey, $dd)
}
}
my $target = $nearest{p};
if ($nearest{dd} > 900) {
@vector = ($target->{x} - $camel->{x}, $target->{y} - $camel->{y})
}
else {
my @vect = map{{x => 0, y => 0}}1..5;
my $n = 0;
for my $prey (@prey) {
next if $prey eq $target;
my $dd = sq_dist($target->{x}, $target->{y}, $prey->{x}, $prey->{y}) + 1/(~0);
next if $dd > 900;
$n ++;
my $dx = $prey->{x} - $target->{x};
my $dy = $prey->{y} - $target->{y};
$vect[1]{x} -= $dx / $dd;
$vect[1]{y} -= $dy / $dd;
$vect[2]{x} += $dx * $dd;
$vect[2]{y} += $dy * $dd
}
$vect[0] = {x => $n * $camel->{apd}{x}, y => $n * $camel->{apd}{y}};
my $dx = abs(250 - $target->{x});
my $dy = abs(250 - $target->{y});
my $d = $dx > $dy ? $dx : $dy;
if ($d > 240) {
$vect[4]{x} = $dx * $d;
$vect[4]{y} = $dy * $d;
}
for my $v (@vect) {
my $d = sqrt($v->{x}**2 + $v->{y}**2) + 1/(~0);
$v->{x} /= $d;
$v->{y} /= $d;
}
for my $beast (@{$camel->{beasts}}, $camel) {
my $dd = sq_dist($target->{x}, $target->{y}, $beast->{x}, $beast->{y});
next if $dd > 900;
$vect[3]{x} += $target->{x} - $beast->{x};
$vect[3]{y} += $target->{y} - $beast->{y};
}
$vector[0] = 5 * 1 * $vect[0]{x}
+ 5 * 1 * $vect[1]{x}
+ 5 * .96 * $vect[2]{x}
+ 1 * 2 * $vect[3]{x}
+ 5 * 4 * $vect[4]{x};
$vector[1] = 5 * 1 * $vect[0]{y}
+ 5 * 1 * $vect[1]{y}
+ 5 * .96 * $vect[2]{y}
+ 1 * 2 * $vect[3]{y}
+ 5 * 4 * $vect[4]{y};
my $dd = $vector[0]**2 + $vector[1]**2;
if ($dd > 36) {
my $d = sqrt($dd);
@vector = map {$_ * 6.1 /$d} @vector
}
}
}
else {
@vector = patrol(250, 250, $patrol_radius_hunt, $camel)
}
}
elsif ($role eq 'P') {
@vector = patrol(250, 250, $patrol_radius_hunt, $camel)
}
else {
my $r = $role eq 'C'
? $patrol_radius_center
: $patrol_radius_corner;
@vector = patrol($places{$role}{x}, $places{$role}{y}, $r, $camel)
}
my $id_x = $camel->{num} << 1;
my $id_y = $id_x + 1;
@out[$id_x, $id_y] = @vector
}
# And let the cruel world know about it
print @out;
print "\0"
}
__END__
```
[Answer]
Not an entry, I'm always interested in adding customized color for each participating entry in [king-of-the-hill](/questions/tagged/king-of-the-hill "show questions tagged 'king-of-the-hill'") ;)
And also the eating process is not visualized by changing the color, but changing the size instead, so that we can see multiple eating events in short time.
**Game.java**
```
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.swing.JFrame;
public class Game {
static int preyStartCount = 0; // 0 means 1500 + (packs * 50)
static int turn;
static boolean silent = false;
long startTime;
JFrame frame;
BufferedImage img;
Color[] colors;
Island map;
List<Prey> preys;
List<Predator> predators;
List<Pack> packs;
List<Pack> initPacks;
public static void main(String[] args) throws InterruptedException {
Game game = new Game();
game.init(args);
if (game.packs.size() > 0){
game.run();
game.score();
}
game.end();
}
void end() {
frame.setVisible(false);
frame.dispose();
for (Pack pack : packs)
pack.handler.end();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
} finally {
for (Pack pack : packs)
pack.handler.shutdown();
}
System.exit(0);
}
void score() {
Collections.sort(initPacks);
int score = 100;
initPacks.get(0).score = score;
for (int i = 1; i < initPacks.size(); i++) {
Pack pack = initPacks.get(i);
if (pack.extinctionTurn < initPacks.get(i - 1).extinctionTurn)
score = score < 1 ? score : score * 80 / 100;
pack.score = score;
}
print("", true);
print("Done in " + getElapsedTime(), true);
for (Pack pack : initPacks)
print(pack.toString() + "\t: Turn " + pack.extinctionTurn + "\t: Score " + pack.score, true);
}
String getElapsedTime(){
double elapsed = (System.currentTimeMillis() - startTime) / 1000d;
if(elapsed < 60)
return String.format("%.2f", elapsed) + " seconds";
elapsed /= 60;
if(elapsed < 60)
return String.format("%.2f", elapsed) + " minutes";
elapsed /= 60;
return String.format("%.2f", elapsed) + " hours";
}
public Game() {
initPacks = new ArrayList<Pack>();
packs = new ArrayList<Pack>();
preys = new ArrayList<Prey>();
predators = new ArrayList<Predator>();
}
void run() throws InterruptedException {
frame.setVisible(true);
turn = 0;
Graphics2D g = img.createGraphics();
printStatus();
while (true) {
turn++;
getAllMoves();
moveAll();
spawn();
removeDead();
shuffle();
if (turn % 500 == 0)
printStatus();
paint(frame, g);
Thread.sleep(5);
if (packs.size() < 1)
break;
}
}
void getAllMoves(){
for (Prey prey : preys)
prey.setNextMove();
for (Pack pack : packs){
pack.talk(preys.size(), predators.size(), turn);
}
while(true){
int doneCount = 0;
for(Pack pack : packs)
if(pack.doneTalking)
doneCount++;
if(doneCount >= packs.size())
break;
try {Thread.sleep(1);}catch(InterruptedException e){}
}
}
void moveAll(){
for (Creature prey : preys)
prey.move();
for(Pack pack : packs){
for (Predator predator : pack.members) {
predator.move();
predator.eatOrStarve();
}
}
}
void paint(JFrame frame, Graphics2D g){
g.setPaint(Color.BLACK);
g.fillRect(0, 0, img.getWidth(), img.getHeight());
for(Prey prey : preys)
prey.paint(g);
for(Pack pack : packs)
for(Predator predator : pack.members)
predator.paint(g);
frame.repaint();
}
List<Prey> deadPreys;
List<Predator> deadPredators;
List<Pack> deadPacks;
void removeDead(){
deadPreys.clear();
for (Prey prey : preys)
if (!prey.alive)
deadPreys.add(prey);
preys.removeAll(deadPreys);
deadPredators.clear();
for (Predator predator : predators)
if (!predator.alive)
deadPredators.add(predator);
predators.removeAll(deadPredators);
deadPacks.clear();
for (Pack pack : packs)
if (!pack.alive)
deadPacks.add(pack);
packs.removeAll(deadPacks);
for (Pack pack : packs) {
pack.members.removeAll(deadPredators);
}
map.rebuildLists(preys, predators);
}
void shuffle(){
Collections.shuffle(packs);
for(Pack pack : packs)
Collections.shuffle(pack.members);
}
void spawn(){
if(turn % 5000 == 0)
addPredators(1);
if(turn % 1000 == 0)
populatePrey(predators.size()-1, false);
}
void addPredators(int count){
for(Pack pack : packs){
if(!pack.alive)
continue;
if(pack.aliveCount == 0)
continue;
Predator parent = null;
for(Predator predator : pack.members)
if(predator.alive)
parent = predator;
if(parent != null){
for(int i=0;i<count;i++){
XY pos = new XY(Math.random() * 30, Math.random() * 30);
pos.add(parent.pos);
pos.setInZeroBounds(Island.SIZE, Island.SIZE);
Predator child = new Predator(pack);
child.color = colors[pack.id];
child.moveTo(pos, Island.getCellByPosition(pos));
predators.add(child);
pack.members.add(child);
pack.aliveCount++;
}
}
}
}
Color[] generateColors(int n){
Color[] result = new Color[n];
double maxR = -1000;
double minR = 1000;
double maxG = -1000;
double minG = 1000;
double maxB = -1000;
double minB = 1000;
double[][] colors = new double[n][3];
for(int i=0; i<n; i++){
double cos = Math.cos(i * 2 * Math.PI / n);
double sin = Math.sin(i * 2 * Math.PI / n);
double bright = 1;
colors[i][0] = bright + sin/0.88;
colors[i][1] = bright - 0.38*cos - 0.58*sin;
colors[i][2] = bright + cos/0.49;
maxR = Math.max(maxR, colors[i][0]);
minR = Math.min(minR, colors[i][0]);
maxG = Math.max(maxG, colors[i][1]);
minG = Math.min(minG, colors[i][1]);
maxB = Math.max(maxB, colors[i][2]);
minB = Math.min(minB, colors[i][2]);
}
double scaleR = 255/(maxR-minR);
double scaleG = 255/(maxG-minG);
double scaleB = 255/(maxB-minB);
for(int i=0; i<n; i++){
int R = (int)Math.round(scaleR*(colors[i][0]-minR));
int G = (int)Math.round(scaleG*(colors[i][1]-minG));
int B = (int)Math.round(scaleB*(colors[i][2]-minB));
result[i] = new Color(R,G,B);
}
return result;
}
void populatePredators(String[] args) {
int start = 0;
if(args[0].equals("-silent")){
silent = true;
start = 1;
}
colors = generateColors(args.length-start);
if(colors.length==1){
colors[0] = Color.BLUE;
}
for (int i = start; i < args.length; i++) {
Pack pack = new Pack(args[i]);
if (pack.handler.init()) {
packs.add(pack);
initPacks.add(pack);
}
}
Collections.shuffle(packs);
XY[] positions = map.getPackStartLocations(packs.size());
XY offset = new XY(-15, -15);
for(int i=0;i<packs.size();i++){
Pack pack = packs.get(i);
for (Predator predator : pack.members) {
predator.color = colors[pack.id];
XY pos = new XY(Math.random() * 30, Math.random() * 30);
pos.add(positions[i]);
pos.add(offset);
pos.setInZeroBounds(Island.SIZE, Island.SIZE);
predator.moveTo(pos, Island.getCellByPosition(pos));
predators.add(predator);
}
}
deadPredators = new ArrayList<Predator>(predators.size());
deadPacks = new ArrayList<Pack>(packs.size());
}
void populatePrey(int count, boolean center) {
XY pos = new XY();
for (int i = 0; i < count; i++) {
Prey prey = new Prey();
if(center){
pos.x = Math.random() * 100 + 200;
pos.y = Math.random() * 100 + 200;
} else {
pos.x = Math.random() * 500;
pos.y = Math.random() * 500;
}
prey.moveTo(pos, Island.getCellByPosition(pos));
preys.add(prey);
}
deadPreys = new ArrayList<Prey>(preys.size());
}
static void print(String txt){
print(txt, false);
}
static void print(String txt, boolean override){
if(!silent || override)
System.out.println(txt);
}
void printStatus(){
print("Turn " + turn + " : Prey " + preys.size()
+ " : Predators " + predators.size() + " (" + getElapsedTime() + " elapsed)");
}
@SuppressWarnings("serial")
void init(String[] args) {
startTime = System.currentTimeMillis();
map = new Island();
populatePredators(args);
if (preyStartCount == 0)
preyStartCount = 1500 + (packs.size() * 50);
populatePrey(preyStartCount, true);
map.rebuildLists(preys, predators);
img = new BufferedImage(Island.SIZE, Island.SIZE, 1);
frame = new JFrame() {
@Override
public void paint(Graphics g) {
g.drawImage(img, 32, 32, null);
}
};
frame.setSize(Island.SIZE+64, Island.SIZE+64);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
for (Pack pack : packs)
pack.handler.end();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
} finally {
for (Pack pack : packs)
pack.handler.shutdown();
}
}
});
}
}
```
**Predator.java**
```
import java.awt.Graphics2D;
public class Predator extends Creature {
static int count = 0;
int id;
int hunger;
Pack pack;
public Prey eatOrStarve() {
for (Prey prey : preys) {
if (prey.alive && pos.isCloserThan(prey.pos, eatDist)) {
prey.die();
hunger = MAX_HUNGER;
return prey;
}
}
if (hunger-- < 1)
die();
return null;
}
@Override
public void die() {
super.die();
pack.aliveCount--;
Game.print(pack.toString() + " starved! " + pack.aliveCount + " members remaining.");
}
@Override
void paint(Graphics2D g){
g.setPaint(color);
int size = ((hunger + 10) > MAX_HUNGER && Game.turn > 10) ? 3+(int)Math.pow((hunger+10-MAX_HUNGER)/4,3) : 3;
g.drawOval((int)pos.x - 1, (int)pos.y - 1, size, size);
g.fillOval((int)pos.x - 1, (int)pos.y - 1, size, size);
}
Predator(Pack pack) {
super();
id = count++;
this.pack = pack;
MAX_SPEED = 6.1;
VISIBLE = 50;
hunger = MAX_HUNGER;
}
final double eatDist = 1;
final static int MAX_HUNGER = 1000;
}
```
[Answer]
# AbleDogs - PHP
These nice dogs have learned how to bite a prey's calves to goad it along walls. They also love to roam the pasture in search of new preys. Lastly, they have been taught to refrain from eating unless they really need the calories.
Put the code into an `AbleDogs` file and run it with `php AbleDogs`
```
<?php
// simulation parameters
define ("ARENA_SIZE", 500);
define ("HUNGER_MAX", 1000);
define ("PREY_SPEED", 6);
define ("PRED_SPEED", 6.1);
define ("PREY_VISION", 30);
define ("PRED_VISION", 50);
define ("WALL_BOUNCE", 10); // distance from a wall from which a prey starts bouncing
// derived constants
define ("PRED_SPEED2" , PRED_SPEED * PRED_SPEED );
define ("PRED_VISION2", PRED_VISION * PRED_VISION);
define ("PREY_VISION2", PREY_VISION * PREY_VISION);
// grid to speedup preys lookup
define ("GRID_SIZE", ceil (ARENA_SIZE/PRED_VISION));
define ("GRID_STEP", ARENA_SIZE/GRID_SIZE);
// search patterns
define ("SEARCH_OFFSET", WALL_BOUNCE+PRED_VISION/sqrt(2));
define ("SEARCH_WIDTH" , 2*sqrt(PRED_VISION2-PRED_SPEED2/4));
define ("SEARCH_HEIGHT", ARENA_SIZE-2*SEARCH_OFFSET);
define ("SEARCH_SIZE" , ceil(SEARCH_HEIGHT/SEARCH_WIDTH));
define ("SEARCH_STEP" , SEARCH_HEIGHT/SEARCH_SIZE);
define ("SEARCH_LEGS" , 2*SEARCH_SIZE+1);
// tracking
define ("MAX_TRACK_ERROR", 10); // max abs distance for prey tracking correlation
define ("TRACKING_HUNGER_START", HUNGER_MAX*.9); // hunger limit to try and eat the tracked prey (start of game)
define ("TRACKING_HUNGER_END", 4); // idem, for endgame
define ("TRACKING_DISTANCE", PREY_SPEED*2.5);
define ("TRACKING_DISTANCE2", TRACKING_DISTANCE * TRACKING_DISTANCE);
class Point {
public $x = 0;
public $y = 0;
function __construct ($x=0, $y=0)
{
$this->x = (float)$x;
$this->y = (float)$y;
}
function __toString() // for comparisons
{
return "$this->x,$this->y";
}
function multiply ($scalar)
{
return new Point ($this->x * $scalar, $this->y * $scalar);
}
function add ($v)
{
return new Point ($this->x + $v->x, $this->y + $v->y);
}
function dot($v)
{
return $this->x * $v->x + $this->y * $v->y;
}
function rotate90()
{
return new Point (-$this->y, $this->x);
}
function vector_to ($goal)
{
return new Point ($goal->x - $this->x, $goal->y - $this->y);
}
function norm2 ()
{
return $this->dot ($this);
}
function norm ()
{
return sqrt ($this->norm2());
}
function normalize ($norm = 1)
{
$n = $this->norm();
if ($n != 0) $n = $norm/$n;
return $this->multiply ($n);
}
function limit ($norm)
{
return $this->norm() > $norm
? $this->normalize($norm)
: clone $this;
}
}
class Search {
function __construct ($direction)
{
switch ($direction % 4)
{
case 0: $this->pos = new Point ( 0, 0); break;
case 1: $this->pos = new Point (SEARCH_SIZE, 0); break;
case 2: $this->pos = new Point (SEARCH_SIZE, SEARCH_SIZE); break;
case 3: $this->pos = new Point ( 0, SEARCH_SIZE); break;
}
$this->start();
}
private function start ()
{
$this->dir = $this->pos->x == $this->pos->y;
$this->adj = $this->pos->x ? -1 : 1;
$this->target = new Point ($this->pos->x * SEARCH_STEP + SEARCH_OFFSET,
$this->pos->y * SEARCH_STEP + SEARCH_OFFSET);
$this->leg = 0;
}
function point ($pos)
{
if ($pos == $this->target)
{
if ($this->leg % 2)
{
if ($this->dir) $this->pos->y+= $this->adj;
else $this->pos->x+= $this->adj;
}
else
{
if ($this->dir) $this->pos->x = $this->pos->x ? 0 : SEARCH_SIZE;
else $this->pos->y = $this->pos->y ? 0 : SEARCH_SIZE;
}
$this->leg++;
if ($this->leg == SEARCH_LEGS) $this->start();
$this->target = new Point ($this->pos->x * SEARCH_STEP + SEARCH_OFFSET,
$this->pos->y * SEARCH_STEP + SEARCH_OFFSET);
}
return $this->target;
}
}
class Pack {
public static $turn; // turn number
public static $size; // number of live members
public static $member; // array of members
public static $prev_preys; // previous coordinates of all preys
public static $prev_preds; // previous coordinates of foreign predators
public static $n_preys; // total number of preys (including those not currently seen)
public static $n_preds; // total number of predators (including those not currently seen)
public static $preys; // coordinates of all preys
public static $preds; // coordinates of all predators
public static $own_preds; // coordinates of all predators in our pack
public static $foe_preds; // coordinates of all foreign predators
public static $arena_center; // arena center
private static $output_order; // to send output according to input order
function init ()
{
Pack::$member = array();
Pack::$arena_center = new Point (ARENA_SIZE/2, ARENA_SIZE/2);
}
function read_line ($line)
{
$values = array();
if ($line == "") return $values;
$input = explode ("\t", $line);
$num = count($input);
if ($num % 2) panic ("read_line: invalid input $line num $num");
$num /= 2;
for ($i = 0 ; $i != $num ; $i++)
{
$values[] = new Point ($input[$i*2 ], $input[$i*2+1]);
}
return $values;
}
function read_input ()
{
// read controller input (blocking)
$input = "";
while (($in = fread(STDIN, 1)) !== false)
{
if ($in == "\0") break;
$input .= $in;
}
// check extinction
if ($input == "dead") return false;
$lines = explode ("\n", $input);
// save previous predators and preys positions
Pack::$prev_preys = Pack::$preys;
Pack::$prev_preds = Pack::$foe_preds;
// line 0: turn, preys, predators
list (self::$turn, Pack::$n_preys, Pack::$n_preds) = explode ("\t", $lines[0]);
// line 1: list of ids and hunger levels
$id = array();
Pack::$size = 0;
Pack::$output_order = array();
foreach (Pack::read_line($lines[1]) as $i=>$v)
{
$id[$i] = $v->x;
Pack::$output_order[] = $id[$i];
if (!isset (Pack::$member[$id[$i]])) Pack::$member[$id[$i]] = static::new_member();
Pack::$size++;
Pack::$member[$id[$i]]->hunger = $v->y;
Pack::$member[$id[$i]]->ttl = self::$turn;
}
// line 2: member positions
Pack::$own_preds = array();
foreach (Pack::read_line($lines[2]) as $i=>$pos)
{
Pack::$member[$id[$i]]->pos = $pos;
Pack::$own_preds[] = $pos;
}
// lines 3 to 2*#members+3: coordinates of all visible preys and predators
$preys = array();
$preds = array();
$y_seen = array();
$d_seen = array();
for ($i = 0 ; $i != Pack::$size ; $i++)
{
// visible preys
foreach (Pack::read_line($lines[2*$i+3]) as $coords)
{
if (!in_array ($coords, $preys) || !isset($y_seen[(string)$coords]))
{
$preys[] = $coords;
}
}
foreach ($preys as $p) $y_seen[(string)$p] = true;
// visible predators
foreach (Pack::read_line($lines[2*$i+4]) as $coords)
{
if (!in_array ($coords, $preds) || !isset($d_seen[(string)$coords]))
{
$preds[] = $coords;
}
}
foreach ($preds as $p) $d_seen[(string)$p] = true;
}
// remove dead members
foreach (Pack::$member as $k => $m)
{
if ($m->ttl != self::$turn)
{
unset (Pack::$member[$k]);
}
}
// filter out own positions from predators list
Pack::$foe_preds = array_diff ($preds, Pack::$own_preds);
Pack::$preds = Pack::$foe_preds;
foreach (Pack::$own_preds as $p) Pack::$preds[] = $p;
Pack::$preys = $preys;
// done
return true;
}
function output_moves ()
{
$output = array();
foreach (Pack::$output_order as $i)
{
$output[] = Pack::$member[$i]->move->x;
$output[] = Pack::$member[$i]->move->y;
}
echo implode ("\t", $output) . "\0";
}
static function point_closest_to_walls ($pos)
{
$delta = $pos->vector_to (Pack::$arena_center);
if (abs ($delta->x) > abs ($delta->y))
{
$y = $pos->y;
$x = $delta->x > 0 ? -1 : ARENA_SIZE+1;
}
else
{
$x = $pos->x;
$y = $delta->y > 0 ? -1 : ARENA_SIZE+1;
}
return new Point ($x, $y);
}
static function in_arena ($pos)
{
$delta = $pos->vector_to (Pack::$arena_center);
return abs ($delta->x) <= ARENA_SIZE/2 && abs ($delta->y) <= ARENA_SIZE/2;
}
static function clamp_to_arena (&$pos)
{
// mimics the slightly strange behaviour of the Java engine setInZeroBounds function
if ($pos->x >= ARENA_SIZE) $pos->x = ARENA_SIZE-1; // should rather be ARENA_SIZE
if ($pos->x < 0) $pos->x = 0;
if ($pos->y >= ARENA_SIZE) $pos->y = ARENA_SIZE-1;
if ($pos->y < 0) $pos->y = 0;
}
function get_closest ($pos, $set, $max_dist)
{
// check for empty set
if (count ($set) == 0) return null;
// construct an array of distances with the same indexes as the points
$dist = array();
$max_dist *= $max_dist;
foreach ($set as $k=>$pt)
{
$d = $pos->vector_to($pt)->norm2();
if ($d <= $max_dist) $dist[$k] = $d;
}
if (count($dist) == 0) return false;
// get the key of the smallest distance and use it to retrieve the closest point
$keys = array_keys ($dist, min($dist));
return $set[$keys[0]];
}
function get_visible ($pos, $set)
{
$res = array();
$skipped = false;
$pts = 0;
foreach ($set as $point)
{
$d = $pos->vector_to($point)->norm2();
if ($d == 0 && !$skipped)
{
$skipped = true;
continue; // skip ourself
}
if ($d > PREY_VISION2) continue; // skip far points
$res[] = $point;
if ($pts++ > 10) break; // too many points are useless since prediction will go haywire anyway
}
return $res;
}
}
Pack::init();
class PackMember {
public $pos; // current position
public $ttl; // last turn reported alive
function move_to ($goal)
{
$this->move = $this->pos->vector_to ($goal);
}
function intercept ($target_pos, $target_speed)
{
// change reference to position difference
$delta = $this->pos->vector_to($target_pos);
$i = $delta->normalize();
$j = $i->rotate90();
// match tangential speeds
$vj = $target_speed->dot ($j);
// deduce axial speed
$vi = PRED_SPEED2 - $vj*$vj; // this should always be positive since predators are faster than preys
$vi = sqrt ($vi);
// return intercept speed in original reference coordinates
return $i->multiply($vi)->add($j->multiply($vj));
}
}
class Target {
public $pos; // current position
public $pos_next; // predicted position
public $speed; // estimated speed
function __construct ($pos)
{
$this->pos = $pos;
$this->speed = new Point(0,0);
$this->predict();
}
private function predict()
{
// predators contribution
$preds = Pack::get_visible ($this->pos, Pack::$preds);
$this->preds = count ($preds);
$res = new Point();
foreach ($preds as $predator)
{
$res = $res->add ($predator->vector_to ($this->pos));
}
$res = $res->multiply (2);
// preys contribution
$preys = Pack::get_visible ($this->pos, Pack::$preys);
$this->preys = count ($preys);
$f_cohesion = new Point;
$f_separate = new Point();
foreach ($preys as $prey)
{
$delta = $this->pos->vector_to ($prey);
$d2 = $delta->norm2();
if ($d2 != 0)
{
$f_cohesion = $f_cohesion ->add ($delta->multiply ($d2));
$f_separate = $f_separate ->add ($delta->multiply (-1/$d2));
}
}
$res = $res
->add ($this->speed->normalize(5*.96)) // assume all preys have same speed as target
->add ($f_cohesion ->normalize(5*1))
->add ($f_separate ->normalize(5*1));
$delta = $this->pos->vector_to(Pack::$arena_center);
$dist = max (abs($delta->x), abs($delta->y));
if ($dist > (ARENA_SIZE/2-WALL_BOUNCE))
{
$res = $res->add ($delta->normalize(5*4));
}
$this->raw_speed = $res;
$this->speed = $res->limit(PREY_SPEED);
$this->pos_next = $this->pos->add ($this->speed);
Pack::clamp_to_arena ($this->pos_next);
}
function track ()
{
// see if we can find our prey at the start of a new turn
$min = 1e10;
foreach (Raptors::$free_preys as $k=>$prey)
{
$dist = abs ($this->pos_next->x - $prey->x) + abs ($this->pos_next->y - $prey->y);
if ($dist < $min)
{
$min = $dist;
$new_pos = $prey;
$new_k = $k;
if ($min < .001) break;
}
}
if ($min > MAX_TRACK_ERROR) return false;
// remove this prey from free preys
unset(Raptors::$free_preys[$new_k]);
$delta = $new_pos->vector_to($this->pos_next);
// update postion and speed
if ($this->speed->norm2() == 0)
{
// this can be either an endgame prey not yet moving
// OR initial speed for a new target
$this->speed = $this->pos->vector_to ($new_pos);
}
$this->pos = $new_pos;
// predict speed and position
$this->predict();
return true;
}
}
class Raptor extends PackMember {
// possible states
const IDLE = 1;
const TRACKING = 2;
const HUNTING = 3;
const RUSHING = 4;
public $state;
public $target; // current prey
public $patrol; // patrol governor
private static $id_gen;
function __construct ()
{
$this->patrol = new Search (++self::$id_gen);
$this->target = null;
$this->state = Raptor::IDLE;
$this->pos = null;
$this->hunger = HUNGER_MAX;
}
function __destruct ()
{
$this->tracking_lost();
}
function tracking_lost()
{
$this->target = null;
$this->state = Raptor::IDLE;
}
function track_prey()
{
// stop tracking if hunger went back to max
if ($this->hunger == HUNGER_MAX)
{
$this->tracking_lost();
}
// try to acquire a new target
if (!$this->target)
{
$victim = Pack::get_closest ($this->pos, Raptors::$free_preys, PRED_VISION);
if (!$victim) return;
$this->target = new Target ($victim);
$this->state = Raptor::TRACKING;
}
// track prey
if (!$this->target->track (Pack::$preys))
{
// prey was eaten or move prediction failed
$this->tracking_lost();
}
}
function beat_competition ()
{
if ($this->target === null) return;
$pm = $this->target->pos_next->vector_to ($this->pos);
$dm = $pm->norm2();
foreach (Pack::$foe_preds as $f)
{
$pf = $this->target->pos_next->vector_to($f);
$df = $pf->norm2();
if ($df > PRED_VISION2) continue;
// if ($df < ($dm*2))
{
$this->state = Raptor::RUSHING;
return;
}
}
if ($this->state == Raptor::RUSHING) $this->state = Raptor::TRACKING;
return;
}
}
class Raptors extends Pack {
public static $free_preys; // coordinates of all preys that are not targeted
// allows generic Pack to create a proper pack member instance
static function new_member()
{
return new Raptor();
}
// main AI loop
static function think ()
{
$hunger_limit = Pack::$n_preys > 2 * Pack::$n_preds ? TRACKING_HUNGER_START : TRACKING_HUNGER_END;
self::$free_preys = static::$preys;
// update targets and members states
foreach (Pack::$member as $m)
{
// track current targets
$m->track_prey();
// rush to target if a competitor draws near
$m->beat_competition();
// hunt if hungry enough
if ($m->state == Raptor::TRACKING && $m->hunger < $hunger_limit)
{
$m->state = Raptor::HUNTING;
}
}
// move members
foreach (Pack::$member as $m)
{
switch ($m->state)
{
case Raptor::IDLE:
$destination = $m->patrol->point($m->pos);
break;
case Raptor::TRACKING:
$wall_point = Pack::point_closest_to_walls ($m->target->pos_next);
$destination = $wall_point->vector_to ($m->target->pos_next)->normalize (TRACKING_DISTANCE)->add($m->target->pos_next);
break;
case Raptor::HUNTING:
$wall_point = Pack::point_closest_to_walls ($m->target->pos_next);
$to_hunter = $m->target->pos_next->vector_to ($m->pos);
$dist_to_target = $to_hunter->norm();
if ($dist_to_target > (PREY_VISION-PREY_SPEED)) // intercept the prey
{
// use actual speed (i.e. true position delta, including wall stops)
$target_true_speed = $m->target->pos->vector_to ($m->target->pos_next);
$intercept_speed = $m->intercept ($m->target->pos, $target_true_speed);
$destination = $m->pos->add ($intercept_speed);
}
else if ($dist_to_target < PRED_SPEED) // pounce on the prey!
{
$destination = $m->target->pos_next;
}
else if ($to_hunter->dot($m->target->speed) > 0)
{
$destination = $m->target->pos_next;
}
else // goad the prey
{
$to_wall = $m->target->pos->vector_to ($wall_point);
$wall_point = $wall_point;
$raw_speed = $m->target->raw_speed->add($m->target->pos->vector_to($m->pos)->multiply(2))->multiply (-0.5);
$wpd_t = $m->target->pos->vector_to ($wall_point)->normalize()->rotate90(); // wpd = Wanted Prey Direction
$delta = $wpd_t->multiply ($raw_speed->dot ($wpd_t));
$destination = $delta->vector_to ($m->target->pos_next);
if (!Pack::in_arena ($destination)) $destination = $m->target->pos_next;
}
break;
case Raptor::RUSHING:
$destination = $m->target->pos_next;
break;
}
$m->move_to ($destination);
}
}
}
while (Raptors::read_input())
{
Raptors::think();
Raptors::output_moves();
}
?>
```
## General considerations
* It's the endgame that counts. You can have the smartest hunting algorithm ever, if you don't spot and catch the last few single preys quicker than the opposition, you lose.
* If your predators can't catch a prey alone (or at least in pairs), you're toast as soon as prey density drops low enough to rely either on blind luck or blocking preys to corners.
* A prey movement predictor is basically mandatory. I can't imagine beating a predictor-based program without having your own predictor.
## Tail chase
The most inefficient way to catch a prey is to tail chase it. Assuming a single predator chasing a single prey and no external influences (walls, other preys, etc), a tail chase could last forever. As soon as you enter the prey vision radius of 30 units, the prey flees as speed 6 for your 6.1, so you gain .1 distance per turn: in a straight line, you'll need about 300 turns to get it.
Taking the arena size into account, a prey will travel at most the diagonal of a 500 units square before hitting a wall or a corner, which will take at most 117 turns.
The winning strategy is obviously to find a way to slow down the preys, namely by having either another predator or a wall/corner in front of it.
## Predictor
With a prey speed of 6, a prey can move to an area of 36\*pi units squared.
With a catching radius of 1, a blind guess as to where the prey will be next has a 1/36\*pi (about 1%) chance to succeed. Clearly something has to be done to enhance that!
Looking at the simulation engine code, you can see that the inputs are:
* visible prey and predator positions
* previous prey speeds
While all positions are available, previous prey speeds are not. The only way to compute these speeds would be to track every single prey from one turn to the next, which is nigh impossible to do (unless you implement a very smart motion tracking algorithm).
So a predictor can easily reproduce all terms of the computation, except for the speed contribution that has to be guessed.
In the case of a single prey, the speed can be tracked without too much problems, which allows to build a "perfect" predictor to catch a prey isolated from the flock.
Which is basically all you need for the endgame, when preys are too few to interact with each other.
When preys are plentiful and flock effect is strong enough to fool the predictor, the sheer density of preys will compensate for the errors (if you don't catch the one you were aiming for, chances are you'll get one of its nearest buddies).
## Goading preys
With the exact knowledge of prey speed computation, it is possible to "steer" a given prey toward a desired direction, by adjusting a predator's position.
This allows to pin a prey against a wall, or direct it toward another pack member. I tried some refined strategies, like pinching a prey between two pack members. Unfortunately, this proved less efficient than the current "pin and scan" routine, since keeping two predators busy to chase a single prey leaves the opposition with too many predators free to scout the pasture.
## Stealing preys
One characteristic of preys behavior is that the influence of a predator increases proportionally to its distance from the prey (provided it remains within the prey vision radius). The closest a predator comes to a prey, the least the prey will steer away from it.
It means that when two predators compete to catch a prey, the closest is bound to get it first. Even a super smart contender that would manage to position itself right in front of the chaser/prey axis would basically scare the prey into the jaws of the contender.
To manage to steal a prey, at least a pair of predators are needed. One will go for the kill, and the other(s) will remain just within the prey vision radius, as far form the prey as possible to maximize influence and goad the prey toward the hunter.
Besides, every change of direction will allow the competition to cut the corner toward the prey, and keeping behind the contender is only possible if the "goader" was close enough to the prey at the beginning of the action.
So prey stealing has only a chance to succeed if the initial positions of the "stealers" are favorable and you can spare at least a second predator. In my experience, this is not worth the complexity.
## Suggested changes
To allow for more complex strategies, moving the predator above prey top speed could have a cost in hunger points, proportional to speed excess.
Say for instance moving up to speed 6 is free and every speed point above 6 costs 100 hunger points (going to 6.3 costs 30 hunger points per turn, burning 1000 hunger points would allow to reach speed 16 for one turn - and die if you don't catch a prey doing so!).
Instead of giving the kill to a random predator when more than one are close enough to eat a prey, I suggest dividing the gain (for instance 3 predators would get 333.33 hunger points each). This would allow for more intrersting endgame strategies (shadowing an enemy predator would become useful if you reckon you have more hunger points, for instance).
The special color for first pack is rather difficult to see. I suggest cyan or orange instead of blue.
[Answer]
## Lazy Pack Haskell
```
import Control.Monad
import Control.Concurrent
main :: IO ()
main=do
t<-forkIO $ forever $ (putStrLn "Pack is paralyzed with indecision.\0")
loop
killThread t
where
loop=do
line <- getLine
case line of
"dead\0" -> return ()
_ -> loop
```
You will need the [haskell platform](http://www.haskell.org/platform/) to run this. Then you use the `runhaskell` command to run it. My pack waits for the prey to come to them.
] |
[Question]
[
We have some new ~~sheriffs~~ moderators in town, [Mego](https://codegolf.stackexchange.com/users/45941/mego) and [DJMcMayhem](https://codegolf.stackexchange.com/users/31716/djmcmayhem). We need a challenge to properly honour them for their new positions, so there we go.
Here's something that has caught my attention when hovering over their profiles – their user IDs are \$31716\$ and \$45941\$. If you perform digit-wise subtraction, you'll notice something pretty exciting (of course, taking the absolute differences):
```
3|1|7|1|6
4|5|9|4|1
-+-+-+-+- (-)
1|4|2|3|5
```
The number generated by the above algorithm is \$14235\$. There is something special about this integer: It consists of *consecutive* digits only, sorted in ascending order, but *exactly one* of the digits is not placed correctly — \$4\$.
We will call a pair of positive integers \$(a, b)\$ a *DJMcMego pair* if the digit-wise absolute differences are consecutive integers, sorted in ascending order, but exactly one of them is not where it belongs. That is, it is possible to move *exactly one* digit of the result of digit-wise subtraction to another position, such that the integer obtained only has consecutive digits, sorted in ascending order.
In our example above, the pair \$(31716, 45941)\$ is a *DJMcMego* pair, because if \$4\$ is moved between \$3\$ and \$5\$, the result is \$12345\$, which fulfils the criteria. Note that the digits of the resulting number **do not** need to start at \$1\$, they just ought to be consecutive. When one is unsure about what decision they should make, they can always rely on the other's help to sort things out.
Your task is to output a [truthy/falsy value](https://codegolf.meta.stackexchange.com/a/2194/59487) depending on whether a pair of positive integers given as input is a DJMcMego pair.
* You are guaranteed that \$a\$ and \$b\$ will have the same number of digits, always at least 4.
* You can take the integers in any reasonable format (i.e. native integers, strings, lists of digits, etc.)
* You can compete in any [programming language](https://codegolf.meta.stackexchange.com/a/2073/59487) and can take input and provide output through any [standard method](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods), while taking note that [these loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden by default. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest submission (in bytes) for *every language* wins.
## Test cases
```
a, b -> Output
31716, 45941 -> Truthy
12354, 11111 -> Truthy
56798, 22222 -> Truthy
23564, 11111 -> Truthy
1759, 2435 -> Truthy
12345, 11111 -> Falsy
3333, 2101 -> Falsy
22354, 22222 -> Falsy
31717, 45941 -> Falsy
14325, 11111 -> Falsy
89789, 78865 -> Falsy
14954, 61713 -> Falsy
25631, 11114 -> Falsy
```
Or, in another [format](https://tio.run/##VY7NDsIgEITP8hSEE0RipPw36ZOohzatkUSRCAd9@rrY1OhwgW92dkivcrlHOc@5I4RIYYXhWGmvBBKN1IpjUYW0sd5x3FQhMMzXEVZ7MJTUNaH0yiUIuNgL1CyblnDtsGuH89ZB2jpnIK58HTMwIOEzCJ3vDxxwiDjvcrqGQskxEtaiTY87HA5t2IU4Tk9KOGEntBk@9BdumxZ4eoRY6DXkQm99ovDgPWP8DwwA8pS62sCnONZLPYTN8xs).
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 18 bytes
```
αDæIg<ùʒD{Q}gĀ*{¥P
```
[Try it online!](https://tio.run/##MzBNTDJM/f//3EaXw8s8020O7zw1yaU6sDb9SINW9aGlAf//RxvqmOgY6xjpmMZyAdlQGAsA "05AB1E – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~259~~ ~~258~~ ~~254~~ ~~253~~ ~~250~~ ~~248~~ ~~233~~ 222 bytes
* Thanks to [Stan Strum](https://codegolf.stackexchange.com/users/63757/stan-strum) for inspring a one byte golf.
* Saved four bytes by juggling some variable initializations.
* Saved a byte by golfing `for(...;l++)b*=B[l]==-~B[l-1];` to `for(...;b*=B[l]==-~B[~-l++]);` (most likely relying on undefined behaviour, as it requires first evaluating `B[l]` followed by `-~B[~-l++]`).
* Saved ~~three~~ five bytes.
* Saved ~~fifteen~~ twenty-six bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat).
```
j,k,l,L,r,b;f(char*A,char*B){for(j=r=0;k=A[L=j];)A[j++]=-~abs(A[j]-B[j]);for(;k-L;k++)for(j=~0;L-++j;r|=!b)if(k-j)for(bcopy(B-~l,strcpy(B,A)+l,strlen(A+l)),bcopy(B+j,B-~j,L+~j),B[j]=A[k],l=b=0;B[++l];b|=B[l]+~B[~-l]);A=r;}
```
[Try it online!](https://tio.run/##ddHdToMwFAfwa30KbGLS2kNSNhiQpjHtvm54A@RioOgKTsN2Y3S8@mzLDDfSC@gJ/1/Ooa3816q6XDQ00EIGHZS8xtXbrnuQ4F6KfNcfHdaiE4w3QuaZ0AUnMteUFsLvd@URm6LwlXkQbrO88TPeUEoG2DOe@ZRq3v2Iu5Lsa9z42n0rq4/PL6z8voXjqavsHiShrmpfDljSlhC4pqgGk9SQ0V4TsN3MME0BrSjNZCqntC14@SNU3ha0V3nvt2YeKTp@vrzv9gdMvm9v7C95kuWFQPMgDhYIZGCLMErDAPHPbn841RjdP3uPwgueDghqLJkJEcKvWjkdzOZRiEA5Hdg1oRUzoVEvnY4WcZogWDo9s2tCL5kJjXo19I6jFHmwGnQ4j5D3v14xExr1@m/yMEKwnp6cDXrNTGjUG6eTNE5SBBun4yRZRBN6w0xo1Nuhd5jaU9s6vTAXMJ/QW2ZCVp8vvw "C (gcc) – Try It Online")
# Explanation (248 byte version)
```
j,k,l,L,r,b; // global variables
f(char*A,char*B){ // function takes two strings
for(j=r=0;A[j];L=j) // loop through A, compute array length L
A[j++]=-~abs(A[j]-B[j]); // set every entry in A to the absolute
// difference of A and B at that position
/* Test out all possible movements of *
* characters and see if any one *
* results in a sorted list => DJMcMego pair */
for(j=0;j-L;j++) // loop through array
for(k=~0;L-++k;r|=!b) // loop through array
if(j-k){ // j is not equal to k
for(l=0;A[l];B[l++]=A[l]); // copy A to B
for(l=j;A[l];B[~-l]=B[++l]); // shift part of B
for(l=L;l-k;B[-~l]=B[--l]); // shift part of B
B[k]=A[j]; // insert character at correct position
for(l=b=0;B[++l];b|=B[l]+~B[~-l]);} // test if B is sorted
A=r;} // return if there was a DJMcMego pair found
```
[Try it online!](https://tio.run/##lZTfb9owEMefx19xizSJQKKGQvihKJuS0laa6NveGA9OcCCJiZnttEJt@dfZOWkL7ZaJ@cEJyn2@d777mthexfHhkFm5xayZJazIg3@siwtYMR4RBvdEpCRiVLaSdrwmohNY1SM0H5vZpCxilfICFMmpBPXAQSqRFivZgoSLduYL3/GCebbwZn5mNqgwzreg1oKXqzUEFsR8sy0VBSIE2QGjxUqtYdYCQKFud@HbexLJtla1Q9xM7w9FSRXQeyp2QAuFe1pAAIpjElSNJGco34IzF@ot0yShghYxBZ6gFCmWEAJRKIjblstUd@F8xQ78oFIBLxUQxrSATLH3sOH3dIMlS53mZXXOloUO6JGRWFEhqxolpZAm@LoDXtD3sf8jK6gsGVaFfSQguVB0CSzFE/hfYfr9Lr6jKw5bkgroXLxO3vEye@bhwMzmvr6bfDVurErjub93vJnd7eaeePI/R@bZNJ63ndl5o2vf6AxSCQVHo/wq0f/ojrxqiU7PKteyhRfOmXacfj@1GeIx3@5qU4UnWPaK7W228MN5t3sKameu0wQdQ4TSIz5FZx6zcyTtfUXa9ruUDWg4z3V1eL/@eda0kBSxN3do68ZcCBp/cG9dSoTHr2v3oieshS26@/pIpves9ZR2Lxor1D2s/dCCwBf49ZzrJKgqRaEF8EIKCg8E7frBSAkvi@VhQ9KibT62PunSIXDmC9/o90a9oWEFPf1j4E4GPcPb4p@OStrGlyV886H3szCspB04GGSa3gsdVnTvsu8ODCus6J5eDXToYNCRvqpodziajA3rqqIv9WqgrxwMOtLTOvfInRhgTWt60HcN@Ds9dTDoSF@/Vj5wDeu6uXKnpq8dDDrSNxU9nozGE8O6qejReDx0G@gbB4OO9G2dezDRXbut6CEOoN9A3zoYpOnnw28 "C (gcc) – Try It Online")
[Answer]
# JavaScript (ES6), 130 bytes
Takes input as two arrays of digits in currying syntax `(a)(b)`. Returns a boolean.
```
a=>b=>a.some((_,i)=>a.some((_,j)=>i-j&&!(A=a.map((v,i)=>Math.abs(v-b[i]))).some(v=>v-A[~k--]-1,A.splice(i,0,A.splice(j,1)[k=0]))))
```
[Try it online!](https://tio.run/##hZBNb4MwDIbv/Iru0iaSg5ry2UOQuOy2224ITSmjaygtqGFIu@yvMweoxjY0ZBHh5PFr@y1kK3V2U3XDrtVr3h1FJ0V0EJG0dXXJCXkBRadZgZlixXr9QGIh7YusCWl75kk2J1seNGnZIVEppXQoakXUsjj5PDOWMg6xretSZTlRsP1OCuA0OYutKaNdVl11VeZ2Wb2RTfJ8e29OH@mGWtP7I0kc4BDg56eUJC54sAcXOEr8BjnswMF314AcxpgBPfBRcQ@hAXcwxgw46PnLimZCHCxdrXpF19SZhFrWzy0fZannlhxmx@2WOjnQx70TR3v50OnP7BM3/lvy7m@w5G@ILwHgaUDzE6I13qwbLqJja3@UdxDsvgA "JavaScript (Node.js) – Try It Online")
[Answer]
# SWI-Prolog, 157 bytes
Not very short but the problem seemed particularly well-suited for declarative predicates, variable binding and recursion, i.e., Prolog :)
```
n(T,Y):-s(T,Q,I,J),s(Y,W,I,J),m(Q,W).
s(T,Q,I,J):-nth0(I,T,X,R),nth0(J,Q,X,R),I\=J.
m([A,B|T],[C,D|Y]):-1 is abs(B-D)-abs(A-C),m([B|T],[D|Y]).
m([_],[_]).
```
Call with, e.g., `n([3,1,7,1,6],[4,5,9,4,1]).`
Explanation: move an element in both lists to a new position (using the SWI-Prolog `nth0` built-in) and check if the difference of the new lists is consecutive.
```
s(T,Q,I,J) % switch (yet unbounded) index I and J in list T, store in Q
s(Y,W,I,J) % switch (now bounded) I and J in list Y
m(Q,W) % check new lists
s(T,Q,I,J) :- nth0(I,T,X,R) % X (unbounded) is the I-th (unbounded) element
% of list T with rest R (=prefix+postfix)
nth0(J,Q,X,R) % the same X is the J-th element in list Q with the same rest R
I\=J % I and J are unequal
m([A,B|T],[C,D|Y]) :- % consider first two elements of both lists
1 is abs(B-D)-abs(A-C) % check if differences are consecutive
m([B|T],[D|Y]) % recursion starting with the second element
m([_],[_]). % stop recursion at last element in the list
```
[Answer]
# [J](http://jsoftware.com/), 27 bytes
−8 bytes thanks to FrownyFrog
```
1"0(-:(2-/\|\:|),1#.2>/\|)-
```
[Try it online!](https://tio.run/##bU@7DoMwDNz5ihMdAIlQEgihkdqlUqdOndmqRlWX/gD/nh4JUPUhy07s89nnh0@rzGFvkaFEDUsXFY6X88nLtM6FzZXYDuNgx6KUm0odmBTCFwmS2/X@RAMJQ@/g0EJjxyhnTEIR16w4/heLmCbDsLsnplaLWGR1f3nTtmlLoLWh8WPbpOGX1czmwCbJGyXWXW@N3zqW28yf23pmJkQX3p569aqkZT3O7OYZjX8B "J – Try It Online")
## Initial solution:
# [J](http://jsoftware.com/), 35 bytes
```
[:((1=[:*/2-/\\:~)*1=1#.0<2-/\])|@-
```
[Try it online!](https://tio.run/##bU@7DsIwDNz7FScY@hB9uG2aElEJCYmJiZUyISLEwg8gfj04SVsEVJad2Oezz3ezyEKNTiHECgUUe5phdzzszUlFEXUnleRlmve9esUJdbTMio3Nz/Fzm5o4QHC93B6oQJDsDTRqCKw50oARSsYFVzT/R/OYYIbk7paxcjKPeVYzy7Pb7BZHq13j1zar4Z9VDabBTcS3EqZdH42/Osbb5MxtLWfSRe3elvWKSUnNdT@zGWZUMG8 "J – Try It Online")
## Explanation
Takes lists of digits as input
`|@-` finds the absolute difference between the digits of the lists
`1=1#.0<2-/\]` Checks if only one digits is out of its place. First I find the differences between all pairs of adjacent digits and check to see if only one of them is positive.
`*` Multiply the result from the above test (1 or 0) with the following test:
`1=[:*/2-/\\:~` Are all digits consecutive? I sort the list down, take the differences for all pairs of adjacent digits, multiply them and check if it equals 1
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 14 bytes
```
ạµṢ_JEċ@Œ¿-Ƥ%L
```
[Try it online!](https://tio.run/##VY49CkIxEIR7T7GNXUQ3yeans1AE8QYhWNnIu4CtrZ03UAQbWwtthOfPPZ4XiQl5ihm2Guab2eWiqlYhNNddfW4u@/l0/NgMn9v61nsdurMwuh/77/Up3iQE55xAjYqBJCvRsw6AQy5IMsCk7JDS1jDgSdmJEVVmADVZBsCloJaKRb9MslyqllRiIiphOGgdnuf/xtKLunxRCl72GKtNnNfGKPpmbOpRERZtMymBmZLe@w8 "Jelly – Try It Online")
### How it works
```
ạµṢ_JEċ@Œ¿-Ƥ%L Main link. Arguments: A, B (digit arrays)
ạ Take the elementwise absolute difference. Call the result R.
µ New chain. Argument: R
Ṣ Sort R.
J Indices; yield [1, ..., len(R)].
_ Take the elementwise difference.
E Test if all differences are equal.
The result is 1 if R consists of consecutive digits, 0 otherwise.
-Ƥ For all outfixes of R, generated by dropping one of its elements:
Œ¿ Get its permutation index (1 if sorted, higher if not).
ċ@ Count the number of times the Boolean from the left appears in the
array to the right. If the Boolean is 1, the count represents the
number of ways a single digit can be deleted to yield a sorted
array. The count has to be positive for a DJMcMego pair, but less
than the length of R, since R may not be sorted.
%L Take the result modulo len(R), mapping len(R) to 0.
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 18 bytes
>
> Been debating whether I should post this or not for a couple of hours. Came up with it quickly late last night but didn't have time to test it properly (*and* I thought it might be too long!). Oliver has since posted a [similar solution](https://codegolf.stackexchange.com/a/156535/58974) (which was, when this one was originally posted, invalid) so if he, or the community, feels this is *too* similar, I'll happily delete it.
>
>
>
Takes input as 2 digit arrays, outputs `0` for `true` or any other number for `false`.
```
íaV
ä> x*Un än × É
```
[Try it](https://ethproductions.github.io/japt/?v=1.4.5&code=7WFWCuQ+IHgqVW4g5G4g1yDJ&input=WzEsMiwzLDQsNV0sWzEsMSwxLDEsMV0=) or [check all test cases](https://ethproductions.github.io/japt/?v=1.4.5&code=rsztYVpnCq7kPiB4KlpuIORuINcgyQ==&input=WwpbWzMsMSw3LDEsNl0sWzQsNSw5LDQsMV1dLApbWzEsMiwzLDUsNF0sWzEsMSwxLDEsMV1dLApbWzUsNiw3LDksOF0sWzIsMiwyLDIsMl1dLApbWzIsMyw1LDYsNF0sWzEsMSwxLDEsMV1dLApbWzEsNyw1LDldLFsyLDQsMyw1XV0sCltbMSwyLDMsNCw1XSxbMSwxLDEsMSwxXV0sCltbMywzLDMsM10sWzIsMSwwLDFdXSwKW1syLDIsMyw1LDRdLFsyLDIsMiwyLDJdXSwKW1szLDEsNywxLDddLFs0LDUsOSw0LDFdXSwKW1s4LDksNyw4LDldLFs3LDgsOCw2LDVdXSwKW1sxLDQsOSw1LDRdLFs2LDEsNywxLDNdXQpdCi1R)
---
## Explanation
```
:Implicit input of digit arrays U and V :[3,1,7,1,6],[4,5,9,4,1]
í V :Interleave V with U :[[3,4],[1,5],[7,9],[1,4],[6,1]]
a :Get the absolute difference of each pair :[1,4,2,3,5]
\n :Assign that new array to variable U
ä> :Is each element greater than the next? :[false,true,false,false]
Un :Sort U :[1,2,3,4,5]
än :Get the deltas :[1,1,1,1]
× :Reduce by multiplication :1
* :Multiply each element in the boolean array by that :[0,1,0,0]
x :Reduce by addition :1
É :Subtract 1 :0
```
And, to walk through that process on a few more test cases:
```
---------------------------------------------------------------
| U | [2,3,5,6,4] | [1,2,3,4,5] | [3,1,7,1,7] | [1,4,9,5,4] |
| V | [1,1,1,1,1] | [1,1,1,1,1] | [4,5,9,4,1] | [6,1,7,1,3] |
|-----|-------------|-------------|-------------|-------------|
| íaV | [1,2,4,5,3] | [0,1,2,3,4] | [1,4,2,3,6] | [5,3,2,4,1] |
|-----|-------------|-------------|-------------|-------------|
| ä> | [F,F,F,T] | [F,F,F,F] | [F,T,F,F] | [T,T,F,T] |
|-----|-------------|-------------|-------------|-------------|
| Un | [1,2,3,4,5] | [0,1,2,3,4] | [1,2,3,4,6] | [1,2,3,4,5] |
| än | [1,1,1,1] | [1,1,1,1] | [1,1,1,2] | [1,1,1,1] |
| × | 1 | 1 | 2 | 1 |
|-----|-------------|-------------|-------------|-------------|
| * | [0,0,0,1] | [0,0,0,0] | [0,2,0,0] | [1,1,0,1] |
| x | 1 | 0 | 2 | 3 |
| É | 0 | -1 | 1 | 2 |
---------------------------------------------------------------
```
[Answer]
# Perl, ~~121~~ 118 bytes
```
($a,$b)=map[split//],@ARGV;
$s+=$l>$_,$l=$_ for@c=map abs($$a[$i]-$$b[$i++]),@$a;
@c=sort@c;
say$s==1&&$c[-1]-$c[0]==$#$a
```
Test in bash:
```
function golf {
perl -E'($a,$b)=map[split//],@ARGV;$s+=$l>$_,$l=$_ for@c=map abs($$a[$i]-$$b[$i++]),@$a;@c=sort@c;say$s==1&&$c[-1]-$c[0]==$#$a' $1 $2
}
golf 31716 45941 #says 1, true
golf 12354 11111 #says 1, true
golf 56798 22222 #says 1, true
golf 46798 22222 #says nothing, false
golf 22354 22222 #says nothing, false
golf 1759 2435 #says 1, true
golf 12345 11111 #says nothing, false
golf 89789 78865 #says nothing, false
golf 14954 61713 #says nothing, false
```
[Answer]
# [Java 8](http://www.oracle.com/technetwork/java/javase/overview/java8-2100321.html), ~~245~~ ~~227~~ ~~223~~ ~~194~~ 188 Bytes
### Thanks to Kevin for saving ~29 bytes
### Thanks to Kevin again for another 6 bytes
```
z->{int l=z.length/2,c[]=new int[l],i=0,j=0;for(;i<l;)c[i]=Math.abs(z[i]-z[i+++l]);java.util.Arrays.sort(z=c.clone());for(i=0;i<l-1;j+=z[i]-z[i-1]!=1?1:0)j+=c[i]-c[++i]>0?1:0;return j==1;}
```
Followed the same pattern Galen came up with for his J answer.
[Try it online!](https://tio.run/##pdTNbqMwEADge55i9obFz0L@yK7XXeUBeuoRcXCok5p1gdqmUYjy7FnjUJqUS1CRhcDAN@PxiJy@U7@sWJE//ztX9UbwDDJBlYJHyguA42QC5uCFZnJLMwZrMwXdsSlLwWgB1DHPkxQahO2z0@Ujpak23BookHPjPxzNWyBIEwhW7PTLz6mXJSkp2L7lE5F6nIReTkK8LaWD@R@BUZbwlDxS/RLQjXIac@ebk@u6IkU4N7kHteYiWEtJDypQpdROQ7IgE2XBHISsZNQW8yOcu@SD8KP0B4n@Rr9DZGbbMH6WuC5PH8J2Ekuma1lATkiET2c86dfc1ahb23vJn@HVVMp50pIXO1MEKncKXRXpUpo3IHCceRB5ENvz0oO5BwsPftmL6IT7L54OSrPXoKx1UBlUi8LRsmZACNCAOm8I4S/6vtUNOvVgZtG5jfE57tf3Q521@sKmHNt8VzbS57hfZ0Ndtnqf@PI7ucuhrrvKxB@1ntoAbbD7XT10DzcVv@zkiKy3VKiePwz5umuXfkytGo6D6yHMu2pfd8qIvbzh@ZAvv7Z5PKrNb/hyyFctv7JYbNuwv1jZ1lmM4Kshr7pNnVv4Upzl1WJmI3iF@p/h6fwf "Java (OpenJDK 8) – Try It Online")
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 102 bytes
```
+`(.)(.*¶)(.)(.*)
$2$4;$1,$3
\d
*
(_*),\1
_
L$w`(;_+\b)(.*)(;_+\b)
$%`$2$3$1$%"$3$1$2$'
m`(^;_+|\1_)+$
```
[Try it online!](https://tio.run/##PY09DsIwDIV3n6JCrkjaqML5j7gCG2tFA4KBAQaExMK5OAAXKw6lvMXWe@@zb6f7@bqnsRbbrKqxzaKTomveLzktElCjXSMpNNAfoQExNFL1BANs8JHFemj7w7f5WwHrzIxBwnrxHRqXcMlix/mzp0G2OI6GAnlVWZcsAWnjrKqoCJwPKapKFwEH/p9QcIkDa1whrJt9w2KfVgR6ujTB5UeYf8QUItMhRs@4TaXmuWA@ "Retina – Try It Online") Link includes test cases. Returns the number of ways digits can be moved to achieve an ascending sequence, which is 2 for a straight swap since either digit can be moved past the other in that case. Explanation:
```
+`(.)(.*¶)(.)(.*)
$2$4;$1,$3
```
Pair up the digits.
```
\d
*
```
Convert to unary.
```
(_*),\1
_
```
Take the difference, but then add 1 because working with zero in Retina is hard™.
```
L$w`(;_+\b)(.*)(;_+\b)
$%`$2$3$1$%"$3$1$2$'
```
List all the sequences of digits obtained by moving exactly one digit.
```
m`(^;_+|\1_)+$
```
Check for consecutive digits.
[Answer]
# [Perl 5](https://www.perl.org/), -F ~~87~~ ~~84~~ 83 bytes
Old style counting: 86 bytes (`+3` for `-F`)
Give he numbers as 2 lines on STDIN, the last line without a trailing newline.
Prints the difference string up to 2 times for true, nothing for false
The long `A0123456789` string is really annoying.
```
#!/usr/bin/perl -F
$_=<>;s%.%abs$&-$F[pos]%eg;s%%"'$`$''=~s:|:A0123456789=~/\$`$&\$'/>//&&say:reg"%eeg
```
[Try it online!](https://tio.run/##DcndCoIwGADQ@54i5Nt25X5y05xN6MaXyCiDMYJow68ugvDRW96ek/z8MPmNfmu4klx2GS7u0HdIOJluCLSE4ZQinokPK5KCwRUYcwvarz1Ktau0qZt96xYxrkNHYKIXglKcPnb2oSDeh5wr1ah6o02r1S@m1z0@MZfDHw "Perl 5 – Try It Online")
I'm usure if this `79` counts as valid:
```
$_=<>;s%.%abs$&-$F[pos]%eg;s,,$a=$&;"$`$'"=~s:|:A0123456789=~/$`$a$'/%//:reg,eg
```
It crashes for a valid pair, so you get a non zero exit code. It does nothing if not a pair and exits with exit code 0. I know returning the result via exit code is allowed, but are they properly truthy and falsy or in fact reversed (for the shell `0` is true) ?
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~124 113 99~~ 95 bytes
```
->l,b,d=-1{m=l.map!{|i|(i-b[d+=1]).abs}.sort;l.any?{|*i|m-i==l-i}&&m!=l&&/#{m*''}/=~[*0..9]*''}
```
[Try it online!](https://tio.run/##dVHtboIwFP3vU1w1YepKtUD52FJ9EEKWItV1ATG0LDPAXp2BbnNidv7c9Jyee89tizI@tTvWmusUxShhJqkyluKMH8dVLeuZNOMweWQkmmMeqwarvNDPKeaH06aqF7LOTMlYasrGMLIxSw1jOa2yxcNDs2Sf4WKFcRD1p/ZYagUTeTjXX@xz3RfxcRRbLZLJKBwBhKFNPOIicGjgkAiBLkoBETpLxLKpg4D0GEjU9QIfgdVjIHUm9x8X8WiAACzHpnA/y6FX146nSnxLdofeRVYEBpJ1SfgT48bV7eVd9/or@YHndzk833fpQCJO0Dd0O7M9nEVd2xkmHEVY8O0rJDnUM44gniMo6u7@5Q@mFcc6f1E4fSuVBreBaRXfMua642a7kONE7qVWuBDvolACxQMi2vTv9XSeO7/rWjSTkTgk7Rc "Ruby – Try It Online")
[Answer]
# [Pyt](https://github.com/mudkip201/pyt), ~~20~~ 18 [bytes](https://github.com/mudkip201/pyt/wiki/Codepage)
```
ą←ą-ÅĐʁ>Ʃ1=⇹ş₋Π1=∧
```
[Try it online!](https://tio.run/##K6gs@f//SOujtglHWnUPtx6ZcKrR7thKQ9tH7TuPzn/U1H1uAZDdsfz/f2NDc0MzLhNTSxNDAA)
Explanation:
```
Implicitly get the first number
ą Convert to list of digits
← Get the second number
ą Convert to list of digits
-Å Take the absolute value of the differences of the lists element-wise
Đ Duplicate the list of differences
ʁ> Reduce by greater than
Ʃ1= Is the sum of that array equal to 1
⇹ Swap the top two items on the stack
ş Sort the top of the stack ascending
₋ Reduce by subtraction (from the right)
Π1= Is the product of the array equal to 1
∧ bitwise-AND (in this case, also logical AND) the top two items on the stack
Implicit print
```
[Answer]
# [Add++](https://github.com/cairdcoinheringaahing/AddPlusPlus), 105 bytes
```
D,w,@~,Ñ_€|BSVcGbU1b]2b]+º=
D,k,@,BPB*
L,BcB_€|B]dBkbUBSVcGbU£>sVcGB]VBKB#BKBcB_0º>b]GBK{w}b]++b*1=BK{k}*
```
[Try it online!](https://tio.run/##bY@9asMwFIXn6ikU2snR4Gv9p8QYYciQDoGSbKJUMWTwEuiQQpsOfYM@Q9c@QUb3Tfoi7nXkxh56QCB9nHPv0WNV7fdtW7IDK97Y98fDz/vXq7vfbBdhDcFnwU@b05yUrGYFcyuXkDvmti7afOXqsO7dzWf@hBfnN27prvGgK21OefALt3w5HHHSNCQwx0d9THDjjhXFjLkS/GRCyM0upxw0KJpTIa0AenVL4Ywh41Ighk4DlkpbgzjrNGA0q3/coKWliGkmuIyYPM9SsiJ/O4Qcp9LYCBVTkI5w1je6rE4v/fW4f8TGamMRa2OUHDAIex6iMMVHs6Xi0DcRIzdwHQviBzra/gI "Add++ – Try It Online")
Defines a lambda function that takes two lists of digits as input. Outputs a positive integer divisible by **24**1 for DJMcMego pairs, **0** otherwise.
1: If this is too restrictive, it also outputs a positive integer for DJMcMego pairs, and **0** otherwise
## How it works
Here we perform 4 checks to determine if the input is valid. The parts of the code that do those checks are
```
BcB_€|B]dBkbUBSVcGbU£>sVcGB]V
```
Here, we take the list of absolute digit differences, then count the number of overlapping pairs which are sorted in descending order. Every DJMcMego pair produces a result of **1**, but they are not unique in this aspect. We also store the inputs' absolute digit differences, to save bytes later. This array will be referred to as **A** throughout.
```
BKB#BKBcB_0º>b]
```
Next, we take the elementwise differences between **A** and **A** sorted, before asserting that at least one of those differences is negative.
```
D,w,@~,Ñ_€|BSVcGbU1b]2b]+º=
GBK{w}b]
```
Third, we check if the pair **[1, 2]** is contained in the forward increments of **A**. This checks that, in at least one position of **A**, it is sorted, which is a criterion for DJMcMego pairs.
```
D,k,@,BPB*
BK{k}
```
As our last check, we assert that the second element of **A** is never **0**. In order for a pair, **X** and **Y**, to be a DJMcMego pair, we can assume that their **A** is always unique, as an array with duplicates in it can never be made consecutive by swapping a single value with another.
Finally, we check that the first three of these tests returned **1**, and that the fourth returned a value **x** such that **x ≠ 0**
A step for step walk through of the code is as follows
```
D,w, ; Define a function **w**;
; This takes an array of integers
; Returns whether the pair [1, 2] appears in the absolute forward differences
;
@ ; Take one argument
~, ; Splat that argument to the stack
; Example argument: [1 4 2 3 5]
;
Ñ_ ; Increments; STACK = [3 -2 1 2]
€| ; Magnitudes; STACK = [3 2 1 2]
BSVcGbU ; Overlapping pairs; STACK = [[3 2] [2 1] [1 2]]
1b]2b]+ ; Push [1 2]; STACK = [[3 2] [2 1] [1 2] [1 2]]
º= ; Any equal [1 2]; STACK = [1]
; ============= ;
D,k, ; Define a function **k**;
; This function takes an array of integers
; Returns whether the second element is **0**;
;
@, ; Take one argument and push to the stack
; Example argument: [[1 4 2 3 5]]
;
BP ; Behead; STACK = [[4 2 3 5]]
B* ; Product; STACK = [120]
;
; In DJMcMego pairs, **A** may begin with a **0**
; For example, 12354 and 11111, so we need to remove the first element
; Taking the product yields **0** if any element is **0**
; However, in order to be a DJMcMego pair, two digits at the same index
; cannot be the same, otherwise their digit-wise difference will be **0**
; ============= ;
L, ; Define a lambda function
;
; This lambda function takes two arrays of digits as input
; Returns an integer to determine if those digits represent a DJMcMego pair
;
; A lambda function is shorter to define than a normal function
; However, when called inside functions with the **]** command,
; they consume the entire stack as arguments, meaning that using functions
; allows us to preserve important values
;
; Example arguments: [[3 1 7 1 6] [4 5 9 4 1]]
;
; First check:
;
BcB_ ; Digit differences; STACK = [-1 -4 -2 -3 5]
€| ; Magnitudes; STACK = [1 4 2 3 5]
B]dBkbU ; Save a copy, **A** STACK = [1 4 2 3 5] **A**: [1 4 2 3 5]
BSVcGbU ; Overlapping pairs; STACK = [[1 4] [4 2] [2 3] [3 5]]
£> ; Sorted descendingly? STACK = [0 1 0 0]
sVcG ; How many? STACK = [1]
B]V ; Save a copy; STACK = [] Register: [1]
;
; Second check:
;
BK ; Retrieve **A**; STACK = [[1 4 2 3 5]]
B# ; Sort; STACK = [[1 2 3 4 5]]
BK ; Retrieve **A**; STACK = [[1 2 3 4 5] [1 4 2 3 5]]
BcB_ ; Element differences; STACK = [0 -2 1 1 0]
0º>b] ; Any negatives; STACk = [[1]]
;
; Third and fourth checks:
;
G ; Retrieve register; STACK = [[1] [1]]
BK ; Retreive **A**; STACK = [[1] [1] [1 4 2 3 5]]
{w}b] ; Run **w**; STACK = [[1] [1] [1]]
++ ; Concatenate; STACK = [[1 1 1]]
b*1= ; Product = 1; STACK = [1]
BK{k} ; Run **k**; STACK = [1 120]
* ; Multiply; STACK = [120]
; To force output as **1** and **0** values,
; append a ? to the end, to output the sign (forces boolean conversion)
```
[Answer]
# [R](https://www.r-project.org/), ~~110 106~~ 84 bytes
```
function(x,y,z=abs(x-y),w=z-min(z)+1)adist(p(1:max(w)),p(w),c("s"=9))==2
p=intToUtf8
```
[Try it online!](https://tio.run/##VY7LbsMgEEX3/grLK1BJleFhoBJ/0a4iL6gbK5ZixzJEif3zLi5@NHcB4uhyZvrJmRIxkJCTlAvNgSRpCFAmOElhTiQil1qRlM6JJFTy1w5IoUOFM7FZuHhpsJDQgOPypnHOP@u8i3zZRWmpglYqla9erudfeaiylTC6TsJJ0pir7brrgJzvXXetPbLuvbzY3pb@3COHSZZhElh7b859XYYvlZmqe1v6@taiJxnIaOy3Q8/DgMnDjIembtGI3wDbn9p51CH4aOwTPTAmXThJiTKXGY2xMTTpTN36z9uXr9RUoeZ0gqIg4aJFgZM/wCLgGxAR5BuQEagN6AjguBFYtLB7YRHDboZFDbsbFjnsdlj0dNfTdetZP/0C "R – Try It Online")
@JayCe with a ridiculous 22 byte save!
The workhorse here is `adist`, which gives a "generalized Levenshtein edit distance" between two strings. By default the distance is the count of the minimal number of insertions, deletions, and substitutions required to transform one string into another. But `adist` allows you to weight things how you like - so I've weighted each substitution to add 9 to the distance rather than 1. This effectively forces the algorithm to look for insertions and deletions only.
This code accepts vectors of integers, computes the absolute elementwise differences, and translates the result to begin at 1, calling it `w`.
Then the custom weighted Levenshtein distance is computed between `w` pasted together to make a string and the string `"1234..."` (actually utf-8 `"\001\002\003\004...`" but `adist` doesn't care.) with the same number of characters as `w`.
The only way the string can have exactly one digit out of place is if you make one deletion and one insertion, giving a distance of 2.
[Answer]
# JavaScript, ~~137~~ ~~136~~ ~~135~~ ~~134~~ ~~132~~ 123 bytes
Takes input as two arrays of digits in currying syntax, outputs `0` for `true` and any other number for `false`.
```
a=>b=>(c=a.map((x,y)=>(x-=b[y])<0?-x:x)).map(x=>t+=x>c[++j]&(d=[...c].sort()).slice(i=0,-1).every(x=>d[++i]-x&1),t=j=0)|t^1
```
---
## Test Cases
```
f=
a=>b=>(c=a.map((x,y)=>(x-=b[y])<0?-x:x)).map(x=>t+=x>c[++j]&(d=[...c].sort()).slice(i=0,-1).every(x=>d[++i]-x&1),t=j=0)|t^1
o.innerText=`${l=`-`.repeat(21)}\n| #1 | #2 | f |${m=`\n|${`|`.padStart(8,`-`).repeat(2)}---|\n`}${[[31716,45941],[12354,11111],[56798,22222],[23564,11111],[1759,2435],[12345,11111],[3333,2101],[22354,22222],[31717,45941],[89789,78865],[14954,61713]].map(([x,y])=>`| ${JSON.stringify(x).padEnd(6)}| ${JSON.stringify(y).padEnd(6)}| ${f([...``+x])([...``+y])} |`).join(m)}\n`+l
```
```
<pre id=o></pre>
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~116~~ ~~119~~ 106 bytes
Thanks Mr. Xcoder for the `116->84` cut, but I found I have missed the "consecutive number" criteria, so 26 bytes are added for that purpose :(
After that, -1 more Thanks Mr. Xcoder, and -13 Thanks ovs
```
def m(a,b):l=[abs(x-y)for x,y in zip(a,b)];print sum(e>f for e,f in zip(l,l[1:]))==1==len(l)-max(l)+min(l)
```
[Try it online!](https://tio.run/##dZDbDoIwEETf/Yp9bOOaWEBETf0R0geMEElaJF4S8Odxu8VLDCYbaDNnptO2/e10bqJhOJYVOFHgQW6tzovDVXSLXlbnC3TYQ93Ao25ZNrv2Ujc3uN6dKPcVeKTE6oVYtLnaGim1VlrbshFWLlzR0W/uar8bnMhjBIWw5m9qME8QVggbBFooI2eEkBIhxCwkhCiGxwkIKSmnkDEjJGLLOAF5R6R/U0IRf3yISILlp4VvOO2PWfcT/KQs32L0c4uJit9vsZ5@i4z3hGShZVhlfKtP0YSp8aD0KzU2cngC "Python 2 – Try It Online")
**That one below fixes `25634 - 11111` problem but with double length (~~211~~ ~~206~~ ~~145~~ 142B)... Golfing...**
```
def m(a,b):l=[abs(x-y)for x,y in zip(a,b)];r=[l[i]-i-min(l)for i in range(len(l))];print(sum(r)==0)&(len([x for x in r if abs(x)>1])<2)&any(r)
```
[Try it online!](https://tio.run/##hZDdaoQwEIXv@xRztSQQYU1s1v7YFwleuFTbgGbF3YL25e1kRuyydSkESTzfnJk5/XT5PAU9z@91A52o1FE@t4WrjmcxJpNsTgOMagIf4Nv3JJcvQ@Fa58vEJ50PoiXIR2Sowkct2jr@RK4ffLiI81cnBlkUe7kjyY1ArlQAvgHqJd/SUr5quavChPjcCWcUpAoO9LWlcpmCRwVPCvCC8AMiqGgFhoQMkZTg5TCCiiUXLMwR0VSyHEZWC3vXhQeJ7dki45KbKeKE2/X2f8SQHg@3QGW/ivpm0Y0truM6bMeV0xuRnBfhW06L/@6SEbU0sleuZp2FszJ34@KE7BLSH2T@AQ "Python 2 – Try It Online")
And congratulations to new moderators :)
**Explanation:**
```
l=[abs(x-y)for x,y in zip(a,b)]
```
Generates the list of absolute differences of the digits.
```
r=[l[i]-i-min(l)for i in range(len(l))]
```
Calculates the offset from the proper position.
```
sum(r)==0
```
If the sequence is not continuous, then offset sum will "usually" not be 0. But even if it equals 0, the next ones will block them out.
```
len([x for x in r if abs(x)>1])<2
```
Only 0 or 1 item will have absolute offset larger than 1 (the one with wrong position, and 0 is in the case like `1,2,3,5,4`)
```
any(r)
```
Blocks the case when the numbers are all in correct positions
[Answer]
# [Haskell](https://www.haskell.org/), ~~182~~ ~~163~~ ~~162~~ 132 bytes
```
(#)=zipWith(-)
a&b|s<-abs<$>a#b=or[all(==1)$tail a#a|(x,h:y)<-p s,(q,r)<-p$x++y,a<-[q++h:r],a/=s]
p l=[splitAt k l|k<-[0..length l]]
```
Takes input as a list of digits. Helper function `p` that gives all possible ways to split a list into two parts is used to take an element out and again to insert it elsewhere.
[Try it online!](https://tio.run/##XY9NasMwFIT3OcUjcYqEfxrF/8YOdNlFoYtCF44pMnFjEcVxLJUmJeseoEfsRVw5EaXpA6Fh@DR6U1OxqTjv2bbddRKeqoN0HjvWyNfRiq2ZFJAkcN9IsBeQq7vQdralLeoqunLat67Cjqh37z2a4OyDtc9M1sjGI3pTnkRq01KkxoJOymzX5ZRzlGUEG5IyDnRCT@hg1ckRp3YLwkJ7qxukcTDNo0VTO9@bZp10hUVvM1GMWuBZLlrO5J2EDfDTRiEzx@FVs5Y18KLot5Q1w3YPL4CWiFolthftuRGMp2wph/P9@QVTsWzGgGiSqFoYSkBDBzBA96Y3WpQYjyAH5JKQBGCB58ceUZYFiMxd31OCDHOx/CCMIyXmw1wsBQX/KBL6MQyU5/rwm@X515Sr5kyRGdHUXP/4J37YK7zeK4rDKFYijKLA1/FefH4YKNrVWX7gEv2jp6yi/wE "Haskell – Try It Online")
] |
[Question]
[
## The scenario
After a long day's work slogging in the office and browsing [stackexchange.com](http://stackexchange.com), I finally walk out the door at 16:58, already weary with the day. Because I am still only an intern, my current mode of transportation is on bicycle. I head over to my trusty [Peugeot Reynolds 501](https://lfgss.microco.sm/api/v1/files/e76d534a659b294f031b8d3f92e48357577fbd4b.jpg), but before I can sail away on it, I need to unlock it. The lock is a standard four digit combination lock (0-9), through the frame and the front wheel. As I try to stay awake, I pull my hand up to enter in the combination.
[![Combination bike lock](https://i.stack.imgur.com/Zwexf.jpg)](https://i.stack.imgur.com/Zwexf.jpg)
## The challenge
Because my fingers are so weary, I want to turn the lock to the correct combination with the fewest movements. One movement is defined as a rotation by one position (36 degrees), for example there is one movement from `5737` to `5738`. However, I am able to grasp **up to any three consecutive rings at the same time, and rotate them as one**, which only counts as a single movement. For example there is also **only one movement** from `5737` to `6837` or to `5626`. Moving from `5737` to `6838` is not one movement, as digits number 1,2 and 4 have moved in the same direction, but independently of digit number 3.
Therefore, for a given combination I can see on the bike lock (any 4-digit integer), what is the lowest number of movements I can make to get it unlocked, and yes, I can rotate in either direction at any time. By this I mean that I can turn some digits in one direction and other digits in the other direction: not all of my movements will be anitclockwise or clockwise for each unlock.
Because I am lazy, my unlock code is 0000.
~~This is code golf~~ I can't be bothered writing much code, so the shortest program in number of bytes wins.
Input is from stdin, and your code should output the combinations I can see at each step after each movement, including the 0000 at the end. Each of the combinations output should be separated by a space/newline/comma/period/ampersand.
## Examples
```
Input: 1210
0100
0000
Input: 9871
9870
0980
0090
0000
Input: 5555
4445&3335&2225&1115&0005&0006&0007&0008&0009&0000
Input: 1234
0124 0013 0002 0001 0000
```
I tried posting this on <http://bicycles.stackexchange.com>, but they didn't like it...
Disclaimer: First golf, so anything that is broken/any missing information let me know! Also I did all the examples by hand, so there may be solutions which involve less movements!
EDIT: For answers which have multiple solution paths with equal number of movements (practically all of them), there is no preferred solution.
[Answer]
# Matlab, ~~412~~ 327 bytes
Golfed (Thanks to @AndrasDeak for golfing `s`!):
```
s=dec2bin('iecbmgdoh'.'-97)-48;s=[s;-s];T=1e4;D=Inf(1,T);P=D;I=NaN(T,4);for i=1:T;I(i,:)=sprintf('%04d',i-1)-'0';end;G=input('');D(G+1)=0;for k=0:12;for n=find(D==k);for i=1:18;m=1+mod(I(n,:)+s(i,:),10)*10.^(3:-1:0)';if D(m)==Inf;D(m)=k+1;P(m)=n-1;end;end;end;end;n=0;X='0000';while n-G;n=P(n+1);X=[I(n+1,:)+48;X];end;disp(X)
```
This codes uses some dynamic programming for finding the shortest 'path' from the given number to `0000` using only the possible steps. The challenge is basically a shortest path prioblem (alternatively you could perhaps consider the steps as a commutatuve group.) but the difficulty was coming up with an *efficient* implementation. The basic structures are two 10000-element arrays, one for storing the number of steps to get to that index, the other one to store a pointer to the previous 'node' in our graph. It simultaneously calculates the 'paths' to all other possible numbers.
Examples:
```
9871
0981
0091
0001
0000
1210
0100
0000
Examples by @noisyass:
7478
8578
9678
0788
0899
0900
0000
3737
2627
1517
0407
0307
0207
0107
0007
0008
0009
0000
Own Example (longest sequence, shared with 6284)
4826
3826
2826
1826
0826
0926
0026
0015
0004
0003
0002
0001
0000
```
Full Code (inlcuding some comments):
```
%steps
s=[eye(4);1,1,0,0;0,1,1,0;0,0,1,1;1,1,1,0;0,1,1,1];
s=[s;-s];
D=NaN(1,10000);%D(n+1) = number of steps to get to n
P=NaN(1,10000);%P(n+1) was last one before n
I=NaN(10000,4);%integer representation as array
for i=0:9999;
I(i+1,:)=sprintf('%04d',i)-'0';
end
G=9871; % define the current number (for the golfed version replaced with input('');
D(G+1)=0;
B=10.^(3:-1:0); %base for each digit
for k=0:100; %upper bound on number of steps;
L=find(D==k)-1;
for n=L; %iterate all new steps
for i=1:18; %search all new steps
m=sum(mod(I(n+1,:)+s(i,:),10) .* [1000,100,10,1]);
if isnan(D(m+1))
D(m+1) = k+1;
P(m+1)=n;
end
end
end
end
n=0;%we start here
X=[];
while n~=G
X=[I(n+1,:)+'0';X];
n=P(n+1);
end
disp([I(G+1,:)+'0';X,''])
```
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), ~~82~~ 73 bytes
```
{p/⍨⍵≡¨⊃¨⊢p←({⍵/⍨⍧⊃¨⍵}⊢,⍥,(,∘-⍨↓⍉⊤5~⍨12 14,⍨⍳8)∘.{10|⍵,⍨⊂⍺+⊃⍵}⊢)⍣≡⊂⊂4⍴0}⊆
```
`p←({⍵/⍨⍧⊃¨⍵}⊢,⍥,(,∘-⍨↓⍉⊤5~⍨12 14,⍨⍳8)∘.{10|⍵,⍨⊂⍺+⊃⍵}⊢)⍣≡⊂⊂4⍴0`
p is all the possible paths
`({⍵/⍨⍧⊃¨⍵}⊢,⍥,(,∘-⍨↓⍉⊤5~⍨12 14,⍨⍳8)∘.{10|⍵,⍨⊂⍺+⊃⍵}⊢)`
This is a train that generates the next possible paths from one list of paths
`(,∘-⍨↓⍉⊤5~⍨12 14,⍨⍳8)`
List of possible changes, 0 0 0 0, 0 0 0 1, 0 0 0 -1, etc
`∘.{10|⍵,⍨⊂⍺+⊃⍵}`
Outer product with the dfn `{10|⍵,⍨⊂⍺+⊃⍵}`
`{10|⍵,⍨⊂⍺+⊃⍵}`
`⊃⍵` unenclose ⍵ + `⊂⍺` enclose ⍺
`⍵,⍨` concatenated with ⍵ `10|` mod 10
`⊢,⍥,stuff` concatenate the output with the new paths
`{⍵/⍨⍧⊃¨⍵}` make it unique
`(train)⍣≡⊂⊂4⍴0` apply the train with a fixpoint `⍣≡` to `⊂⊂4⍴0` to generate all paths
`{p/⍨⍵≡¨⊃¨⊢p}`
`⊢p←...` the `⊢` shouldn't be needed here, but that's a bug costing me 1 byte
`⊃¨p` get the first items from each in p
`⍵≡¨` find where ⍵ is equal to them
`p/⍨` replicate
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/v7pA/1Hvike9Wx91Ljy04lFXM4hYVPCobYJGNVAUIrkcIt67tRYop/Ood6mOhs6jjhm6IMm2yY96Ox91LTGtA/IMjRQMTXTAejZbaAKV6FUbGtQANYLFupoe9e7SBpoFNUnzUe9ioLUg8a4mk0e9WwyAom3/04CWP@rtA6tbAxQ9tN74UdvER31Tg4OcgWSIh2fw/zQFUwgEAA "APL (Dyalog Extended) – Try It Online")
Old answer:
`{p⌷⍨⍸⍵≡¨⍥⊆⊃¨p←({⍵/⍨≠⊃¨⍵}⊢,⍥,((+,-)↓⍉2⊥⍣¯1⊢⎕A⍳'ABCDFGHLN')∘.{10|⍵,⍨⊂⍺+⊃⍵}⊢)⍣≡⊂⊂4⍴0}`
[Answer]
## Batch - 288 bytes
~~Even if you said they have to be consecutive (the rings), I assume by logic (following the example) that I can skip the middle one, as from `1234` to `0224`.~~
```
set/p x=
set a=%x:~0,1%&set b=%x:~1,1%&set c=%x:~2,1%&set d=%x:~3,1%
:l
@echo %x%&if %a%==0 (if %d% NEQ 0 set/a d=d-1) else set/a a=a-1
@if %b% NEQ 0 set/a b=b-1
@if %c% NEQ 0 set/a c=c-1
@if %x% NEQ 0000 set x=%a%%b%%c%%d%&goto l
```
~~This is my Batch solution: 236 bytes.~~
---
### Edit: corrected solution
```
set/p x=
set a=%x:~0,1%&set b=%x:~1,1%&set c=%x:~2,1%&set d=%x:~3,1%
:l
@echo %x%&set k=1&if %a%==0 (if %d% NEQ 0 set/a d=d-1&set k=0) else set/a a=a-1&set k=1
@if %b% NEQ 0 if %k%==1 set/a b=b-1&set k=0
@if %c% NEQ 0 if %k%==0 set/a c=c-1
@if %x% NEQ 0000 set x=%a%%b%%c%%d%&goto l
```
The new solution (fixed according to the underlying comments) is 288 bytes heavy.
[Answer]
# Haskell - 310 bytes
```
import Data.Char
import Data.List
r=replicate
h=head
a x=map(:x)[map(`mod`10)$zipWith(+)(h x)((r n 0)++(r(4-j)q)++(r(j-n)0))|j<-[1..3],n<-[0..j],q<-[1,-1]]
x!y=h x==h y
x#[]=(nubBy(!)$x>>=a)#(filter(![(r 4 0)])x)
x#y=unlines.tail.reverse.map(intToDigit<$>)$h y
main=do x<-getLine;putStrLn$[[digitToInt<$>x]]#[]
```
This works by repeatedly building a new list of combinations by applying each possible turn to each combination already reached until one of them is the right combination. Duplicates are removed from the list on each iteration to keep memory usage from growing exponentially.
As a brute force solution, this is very inefficient and can take several minutes to run.
I don't have much experience with Haskell, so some thing could probably be done better.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E) `--no-lazy`, ~~41~~ ~~39~~ 37 bytes
Lazy evaluation seems to break it, with it enabled, this doesn't terminate.
```
[TS4㦎ΣmbÏD(«N>ãεISšÅ»+}T%¤O1‹i¦J»,q
```
[Try it online!](https://tio.run/##AU0Asv9vc2FiaWX//1tUUzTDo8Kmxb3Oo21iw49EKMKrTj7Do861SVPFocOFwrsrfVQlwqRPMeKAuWnCpkrCuyxx//85ODcx/y0tbm8tbGF6eQ "05AB1E – Try It Online")
This is really slow, doesn't finish for `1234` and `5555` on TIO.
The general structure of the program is
```
[ infinite loop, N in 0, 1, ...
... generate list of all possible movements
... take all combinations of N+1 movements and convert them to a sequence of positions
... if the current position list ends with 0000, print and terminate
```
In more detail:
```
TS4㦎ΣmbÏD(« # generate a list of all possible movements
T # push 10
S # split into digits ["1", "0"]
4ã # take ["1", "0"] to the 4th cartesian power
# this generates all 4-digit combinations of 0 and 1
¦ # remove the first element ("1111")
ŽΣm # push compressed integer 20958
b # convert to binary
Ï # keep the 4-digit combinations at indices where
# the binary representation of 20958 has a 1
D # duplicate the list
( # negate each number in the copy
« # concatenate both lists
```
[Try `T4ãʒγ€ÙO}¦€SD(«` online!](https://tio.run/##yy9OTMpM/f8/xOTw4lOTzm1@1LTm8Ez/2kPLgIxgF41Dq///t7QwN/yvq5uXr5uTWFUJAA)
```
N>ãεISšÅ»+}T% # try all possible combinations of movements
N # push the iteration counter (starts at 0)
> # increment the value
ã # take the movement list to the N+1 cartesian power
ε # map over each list of N+1 moves
IS # push the digits of the input
š # prepend it to the move list
Å»+} # cumulative left-reduce by addition
# this generates all positions of the lock
# that are a result of the movements in the list
T% # modulo 10
¤O1‹i¦J»,q # verify and print position sequence
¤ # get the last position
O # sum it
1‹ # is this less than 1? (equal to 0)
i # if this is the case:
¦ # remove the first element (initial position)
J» # join each position and positions by newlines
, # print the result
q # exit
```
[Answer]
# [J](http://jsoftware.com/), 93 bytes
Doesn't even try to be efficient, will run out of memory for 5555 on TIO. :-)
```
(0({s#])((,-)|:#:7 59 217 584),/@((],10|(+{:))"1 2/)^:(]0=1#.s=:(4#0)&e."%.)^:_,:^:2)@(".@,.)
```
[Try it online!](https://tio.run/##VcoxC4MwEAXg3V9xJLS5ozHmUkW9IgiFTp26a4eilC4dHPW/pxnrg8eDj/eJypkZOgEDFjxIau7g@rjfInpcFz0Qos1pEy01VC0ETtOUZIsecbDsNzytQqQYQkGj4OA71m7pBEvt6Tg5dXDJn1ZGCdSjcr11FCnLptf7C3iZCQwH9uYf2qZms3@cyx1UKSb@AA "J – Try It Online")
* `(".@,.)` convert '0123' into a list like `0 1 2 3`
* `,:^:2` list of list of steps `[[0 1 2 3]]`
* `^:(]0=1#.s=:(4#0)&e."%.)^:_` until the there is a path of moves with `0 0 0 0` in it:
* `((,-)|:#:7 59 217 584)` the possible moves
* `,/@((],10|(+{:))"1 2/)` for each possible move and each path: create a new path with the last move + the possible move, mod 10 appended.
* `0({s#])` filter out the paths that caused the loop to stop, and take the first.
] |
[Question]
[
This might be a very simple challenge, but I am surprised it hasn't been done on code-golf yet:
**Print all Integers from 1 to 10 inclusive in ascending order to standard output.**
Your output format can be whatever your language supports. This includes arbitrary separators (commas, semicolons, newlines, combinations of those, etc., but no digits), and prefixes and postfixes (like `[...]`). However, you may not output any other numbers than 1 through 10. Your program may not take any input. Standard loopholes are disallowed.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins!
# Leaderboard
```
var QUESTION_ID=86075,OVERRIDE_USER=42570;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
```
```
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
```
```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>
```
[Answer]
# C, 36 bytes
```
main(i){while(printf("%d ",i++)<3);}
```
This works because the loop terminates after the first 2 digit number.
[Answer]
# HTML, 44 bytes
```
<ol><li><li><li><li><li><li><li><li><li><li>
```
This is longer than hardcoding the output, but it is more interesting this way. It creates an ordered list (`<ol>`) with ten empty list elements (`<li>`). By default ordered lists are delimited by decimal numbers starting with 1 and a period.
HTML5 is very forgiving regarding unclosed tags, so it closes the `li` tags implicitly.
[Answer]
# Bash, 12 characters
```
echo {1..10}
```
Sample run:
```
bash-4.3$ echo {1..10}
1 2 3 4 5 6 7 8 9 10
```
### Bash + coreutils, 10 characters
(Just trying to be funny and using `': No such file or directory↵ls: cannot access '` as separator.)
```
ls {1..10}
```
Sample run:
```
bash-4.3$ ls {1..10}
ls: cannot access '1': No such file or directory
ls: cannot access '2': No such file or directory
ls: cannot access '3': No such file or directory
ls: cannot access '4': No such file or directory
ls: cannot access '5': No such file or directory
ls: cannot access '6': No such file or directory
ls: cannot access '7': No such file or directory
ls: cannot access '8': No such file or directory
ls: cannot access '9': No such file or directory
ls: cannot access '10': No such file or directory
```
### Bash + coreutils, 6 characters
(Just trying to be boring. Or not just trying…)
```
seq 10
```
Sample run:
```
bash-4.3$ seq 10
1
2
3
4
5
6
7
8
9
10
```
[Answer]
## Jelly, 2 bytes
```
⁵R
```
Explanation
```
⁵ Return the fifth command line argument or 10
R Range
Implicit output
```
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), 2 bytes
Code:
```
TL
```
Explanation:
```
T # Constant for 10
L # Range
```
[Try it online!](http://05ab1e.tryitonline.net/#code=VEw&input=).
[Answer]
# Brainfuck, 58 bytes
```
-[----->+>+<<]>--<+++++[<++<++>>-]<<-[->>>.+<<.<]>>>>--.-.
```
[Try it online!](http://brainfuck.tryitonline.net/#code=LVstLS0tLT4rPis8PF0-LS08KysrKytbPCsrPCsrPj4tXTw8LVstPj4-Lis8PC48XT4-Pj4tLS4tLg&input=)
[Answer]
# LOLCODE, 79 bytes
```
IM IN YR l UPPIN YR v TIL BOTH SAEM v AN 10
VISIBLE SUM OF v AN 1
IM OUTTA YR l
```
This code may need some tweaking depending on the compiler you're using. Some want you to add HAI/KTHXBYE, some want you to declare the variable ahead of time. One compiler breaks if your loop name is shorter than two characters, even though the loop name is never used.
[Answer]
# CJam, ~~6~~ 5 bytes
```
A,:)`
```
1 byte saved thanks to [Luis Mendo](https://codegolf.stackexchange.com/users/36398/luis-mendo)
Output: `[1 2 3 4 5 6 7 8 9 10]`
Explaination:
```
A, e# Push a list from 0 to 9.
:) e# Increment all values.
` e# Stringify the list.
```
[Try it online!](http://cjam.tryitonline.net/#code=QSw6KWA&input=)
[Answer]
# R, 4 bytes
```
2:10
```
The ":" is probably one of the most used R commands. Improvement by Barranka in comments.
[Answer]
# Ruby, 8 bytes
Separated by newlines.
```
p *1..10
```
[Answer]
# Pyth, 2 bytes
```
ST
```
First time I've used a golfing lang to answer!
Explanation:
```
S 1-indexed range. [1, 2, ... A].
T Variable. Initialized to 10. (Ten)
Implicitly printed.
```
[Answer]
## JavaScript (ES6), 29 bytes
```
alert([...`${1e11/81^14}`]+0)
```
Outputs `1,2,3,4,5,6,7,8,9,10`. Not the shortest answer but I thought it was a fun calculation.
[Answer]
## Brainfuck, 41 bytes
```
+[[-<]>->>->-<-]<<[-<<+<<.+>>>>>.<]<<+.-.
```
**Output**
```
1 2 3 4 5 6 7 8 9 10
```
[Try it online](http://brainfuck.tryitonline.net/#code=K1tbLTxdPi0-Pi0-LTwtXTw8Wy08PCs8PC4rPj4-Pj4uPF08PCsuLS4).
[Answer]
# Actually, 9 Bytes
```
19`;1+`na
```
[Try it here!](http://actually.tryitonline.net/#code=MTlgOzErYG5h&input=)
Explanation:
```
19`;1+`na
1 Push 1 to stack
9 Push 9 to stack
`;1+` Push Function inside ` to stack
; Push top element to stack
1+ Add 1 to top element
n Run function x times (9 times)
a Invert stack
```
[Answer]
## Mathematica - 13 bytes
```
Echo@Range@10
```
Saved 4 bytes thanks to [MartinEnder](https://codegolf.stackexchange.com/users/8478/martin-ender)!
Output: `>> {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}`
[Answer]
# [DC](https://rosettacode.org/wiki/Category:Dc), 12 bytes
...a little bit mean now...
```
[zzpA>L]dsLx
```
Unrolled:
```
[ # start string constant
z # push stack length (0 on 1st cycle)
z # push stack length (1 on 1st cycle)
p # print top of stack
A>L # if 10(decimal) < tos: execute L
] # end string constant, push it
d # duplicate the string
sL # store a copy in L
x # execute tos (which is the other string copy)
```
One of the `z` (push stack length) operations has no corresponding operation which takes it from the stack. This way the stack grows with each iteration by one. This is abused as the loop counter.
This loop starts with an empty stack, so the 1st `z` pushes `0` in the 1st iteration so the printing happens after the 2nd `z` which correspond to duplicating the result of `1+d` in the version below. This way the comparison needs to test for bigger than `10` here instead of `bigger than 11` below.
---
# [DC](https://rosettacode.org/wiki/Category:Dc), 14 bytes
Just straight forward...
```
1[p1+dB>L]dsLx
```
Unrolled:
```
1 # push 1
[ # start string constant
p # print top of stack
1+ # add 1 to tos
d # push tos (duplicate)
B>L # if 11(decimal) < tos: execute L
] # end string constant, push it
d # duplicate the string
sL # store a copy in L
x # execute tos (which is the other string copy)
```
[Answer]
# [><>](https://esolangs.org/wiki/Fish), 13 bytes
```
01+:a)?;:nao!
```
Explanation :
```
01+:a)?;:nao!
0 push initial value of n on the stack
1+ increments n
: duplicates n on the stack
a push 10 on the stack
) pops n and 10 of the stack, push n>10 on the stack
?; if n>10, stops program execution
:n duplicates n on the stack in order to display it
ao display 10 (x0A, linefeed)
! skips the next instruction, which since ><> loops is the push 0
```
You can see it in action on the [online interpreter](https://fishlanguage.com/playground).
[Answer]
# [MATL](https://github.com/lmendo/MATL), 3 bytes
```
10:
```
[**Try it online!**](http://matl.tryitonline.net/#code=MTA6&input=)
The code generates the vector `[1 2 ... 10]` and implicitly displays it, with the numbers separated by spaces.
[Answer]
## PowerShell, 5 bytes
```
1..10
```
Creates a dynamic range with the `..` operator from `1` to `10`, then that array is left on the pipeline. Output is implicit. Default `.ToString()` method of an array is newline, so this will be newline-separated when run in a clean shell.
[Answer]
# Vim, 12 bytes
```
i1<Esc>qqYp<C-a>q8@q
```
Outputs
```
1
2
3
4
5
6
7
8
9
10
```
Explanation:
```
i1<Esc>qqYp<C-a>q8@qZZ
qqYp<C-a>q -- Macro q: duplicate line and increment (6)
i1<Esc> -- Insert 1 (3)
8@q -- Run macro q 8 times (3)
```
Tested on Neovim 0.1.4, which to my knowledge is keystroke-compatible with Vim.
[Answer]
# Perl 6, 12 bytes
```
say @(1..10)
```
The `@()` is needed to convert to an array
Alternative solution:
```
say @(^10+1)
```
Builds a range [0,10) then adds one, then converts to an array.
[Answer]
# [Dyalog APL](http://goo.gl/9KrKoM), 3 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319)
```
⍳10
```
[TryAPL online!](http://tryapl.org/?a=%u237310&run)
[Answer]
# J, 6 bytes
```
1+i.10
```
Output: `1 2 3 4 5 6 7 8 9 10`
Explaination:
```
1+ NB. Add one to...
i.10 NB. A range from 0 to 9.
```
[Answer]
# Haskell, 17 bytes
```
main=print[1..10]
```
Outputs `[1,2,3,4,5,6,7,8,9,10]`.
[Answer]
# [MarioLANG](https://github.com/tomsmeding/MarioLANG), ~~34~~ ~~27~~ 25 bytes
```
+<
:"
+
:
+
:
+
:
+
:!
=#
```
[Try it online!](https://tio.run/##y00syszPScxL//9f24bLSolLm8sKGSty2Sr//w8A "MarioLANG – Try It Online")
Thanks to Jo King for ~~-7~~ -9 bytes!
code:
Mario falls down, incrementing and saying his number five times,
then he steps on the elevator, rides up and falls down again,
incrementing and saying his number another five times.
Then he walks left and falls out of the code.
14 bytes shorter than the easy way:
39 bytes
```
+:+:+:+:+:+:+:+:+:+
==================:
```
[Try it online!](https://tio.run/##y00syszPScxL//9f2woDctliAKv//wE "MarioLANG – Try It Online")
[Answer]
# Fuzzy Octo Guacamole, 7 bytes
```
1.25*$:
```
Multiplies `2*5`, takes the range of that and `1`, and prints the whole stack.
```
1.25*$:
1. # Push 1 to the stack and switch stacks
25* # Push 10 to the stack
$ # Push every number in the inclusive range on the top of inactive stack and top of active stack ([1,2,3,4,5,6,7,8,9,10])
: # Print the stack, which is a list containing the numbers.
```
[Answer]
# PostScript, 12 bytes
```
1 1 10{=}for
```
Output:
```
1
2
3
4
5
6
7
8
9
10
```
(Most PostScript interpreters don't actually have a proper stdout, or even a command line, but GhostScript has both and can be used to run this program.)
[Answer]
# Java 7, ~~53~~ ~~51~~ 52 bytes (loop)
```
void l(){for(int i=0;++i<11;)System.out.println(i);}
```
Alternative **51 bytes** (hardcoded is shorter.., but considered a [default loophole](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default/1063#1063), so not allowed):
```
void h(){System.out.print("1 2 3 4 5 6 7 8 9 10");}
```
Alternative **54 bytes** (recursive):
```
int i=1;void r(){System.out.println(i);if(i++<10)r();}
```
**Ungolfed & test code for all three:**
[Try it here.](https://ideone.com/d87Zic)
```
class Main{
static void h(){
System.out.print("1 2 3 4 5 6 7 8 9 10");
}
static void l(){
for(int i=0; ++i < 11;){
System.out.println(i);
}
}
static int i = 1;
static void r(){
System.out.println(i);
if(i++ < 10){
r();
}
}
public static void main(String[] a){
h();
System.out.println();
l();
System.out.println();
r();
}
}
```
---
EDIT: For funsies: As correctly pointed out by *@SkippyLeGrandGourou*, the base of the 1 to 10 isn't specified in the question, so here is (non-code-golfed) Java code that outputs 1 to 10 in the bases 2 to 10:
[Try it here.](https://ideone.com/lgTRM9)
```
BASE-2: 1 10
BASE-3: 1 2 10
BASE-4: 1 2 3 10
BASE-5: 1 2 3 4 10
BASE-6: 1 2 3 4 5 10
BASE-7: 1 2 3 4 5 6 10
BASE-8: 1 2 3 4 5 6 7 10
BASE-9: 1 2 3 4 5 6 7 8 10
BASE-10: 1 2 3 4 5 6 7 8 9 10
```
[Answer]
# [Aussie++](https://github.com/zackradisic/aussieplusplus/), output to STDERR, ~~29~~ 28 bytes
It turns out that causing errors is shorter than any straightforward way of doing it.
```
G'DAY MATE! 1 2
4
6
8
_
```
Tested in commit 9522366. The trailing newline is required. Produces the following errors:
```
[line 1] OI MATE! EXPECTED ; BUT GOT '2'
[line 3] OI MATE! EXPECTED ; BUT GOT '4'
[line 5] OI MATE! EXPECTED ; BUT GOT '6'
[line 7] OI MATE! EXPECTED ; BUT GOT '8'
[line 9] OI MATE! EXPECTED ; BUT GOT '_'
[line 10] OI MATE! EXPECTED ; BUT GOT 'EOF'
```
Maybe I misinterpreted the challenge, but it didn't specify that you had to use the same separator for all numbers.
## Aussie++, output to STDERR with consistent separator, 30 bytes
```
G'DAY MATE!;
;
;
;
;
;
;
;
;
;
```
No trailing newline is required. Produces the following errors:
```
[line 1] EXPECTED NUMBER, STRING, BOOLEAN, NIL, OR IDENTIFIER BUT GOT ';'
[line 2] EXPECTED NUMBER, STRING, BOOLEAN, NIL, OR IDENTIFIER BUT GOT ';'
[line 3] EXPECTED NUMBER, STRING, BOOLEAN, NIL, OR IDENTIFIER BUT GOT ';'
[line 4] EXPECTED NUMBER, STRING, BOOLEAN, NIL, OR IDENTIFIER BUT GOT ';'
[line 5] EXPECTED NUMBER, STRING, BOOLEAN, NIL, OR IDENTIFIER BUT GOT ';'
[line 6] EXPECTED NUMBER, STRING, BOOLEAN, NIL, OR IDENTIFIER BUT GOT ';'
[line 7] EXPECTED NUMBER, STRING, BOOLEAN, NIL, OR IDENTIFIER BUT GOT ';'
[line 8] EXPECTED NUMBER, STRING, BOOLEAN, NIL, OR IDENTIFIER BUT GOT ';'
[line 9] EXPECTED NUMBER, STRING, BOOLEAN, NIL, OR IDENTIFIER BUT GOT ';'
[line 10] EXPECTED NUMBER, STRING, BOOLEAN, NIL, OR IDENTIFIER BUT GOT ';'
```
## Aussie++, output to STDOUT, 41 bytes
```
G'DAY MATE!
GIMME "1 2 3 4 5 6 7 8 9 10";
```
Again, no trailing newline is required.
[Answer]
## [Retina](https://github.com/m-ender/retina), 13 bytes
I've got two solutions at this byte count, but it doesn't seem optimal:
```
_10$*
1
$.`_
```
```
11$*_
\B
$.`
```
They both use `_` as separators, prefix and suffix.
[Try the first online!](http://retina.tryitonline.net/#code=Cl8xMCQqCjEKJC5gXw&input=) [Or try the other one!](http://retina.tryitonline.net/#code=CjExJCpfClxCCiQuYA&input=)
] |
[Question]
[
In this challenge, the goal is to recreate the [On-Line Encyclopedia of Integer Sequences](http://oeis.org) one sequence at a time. Similar to the [Evolution of Hello World](https://codegolf.stackexchange.com/q/40376/2867), each answer depends on a previous answer.
Over time, this challenge will create a "family tree" of the OEIS sequences. It is simple to add on to this tree.
1. Find a previous answer, which can be at any depth N of the tree.
2. Determine the first N numbers generated by that answer's sequence.
3. Find a sequence in OEIS which starts with those same numbers and which hasn't been used before.
4. Write a program to generate this new sequence you just found.
5. Submit your answer as depth N+1
Since the level of your answer influences scoring, you should always add your answer onto the tree at the deepest level possible. If you cannot fit your answer anywhere on the tree, you can start a new branch of the tree and put your answer as depth 1.
## Answer Requirements
There are a few ways to output a sequence.
The first option is to write a program or function that inputs a number (from STDIN or as an argument) and returns the Nth number in your chosen sequence. You can assume that the sequence will be defined for N and that N and S\_N are "reasonably sized" (so it won't cause overflows). You can also use any reasonable indexing, such as 0 indexing, 1 indexing, or the indexing listed under "offset" on the sequence's OEIS page, that doesn't matter. The term produced by the first index must match the first term of the OEIS entry.
The second option is to write a program or function that inputs a number and returns the first N terms of the sequence. The first terms of the output must be the first terms of the OEIS entry (you can't leave off the first few terms). Consecutive terms must be delimited by arbitrary strings of non-digit characters, so `0,1 1.2/3,5;8,11` works but `011235811` does not count.
The third option is to create a program that outputs a continuous stream of numbers. Similarly to the second option, there must be delimiters between consecutive terms.
Your answer **should contain a header** like this to aid Stack Snippet parsing:
```
# [language], [number] bytes, depth [number], A[new sequence] from A[old sequence]
```
Your answer should contain the code to generate the sequence, along with the first few terms that any descendants will need to contain. These few terms should be **preceded by the exact word `terms:`** so that the controller can use them as part of the tree diagram. It is also recommended to write a description of the sequence you chose.
If your post is a depth 1 answer and thus has no ancestor, you should simply omit the `from A[number]` in your header.
Here is an example answer:
```
# Perl, 26 bytes, depth 3, A026305 from A084912
various code here
and here
The next answer should match the following terms:
1, 4, 20
This sequence is .... and does ....
```
## Chaining Requirements
In order to make this challenge more fair, there are restrictions on which answers you can chain yours to. These rules are mostly to prevent a single person from creating a whole branch of the tree by themselves or owning a lot of "root" nodes.
* You cannot chain to yourself.
* You cannot directly chain two of your answers to the same ancestor.
* You cannot make more than one "Level 1" answer.
Also, if the ancestor was of depth N, your post must have depth N+1, even if more than the required number of terms agree.
## Scoring
Your score as a user is the **sum** of the scores of all of your answers. The score of a single answer is determined by the following formula:
```
Answer Score = Sqrt(Depth) * 1024 / (Length + 256)
```
This scoring system should encourage users to submit a large number of deeper answers. Shorter answers are preferred over longer answers, but depth has a much larger influence.
**Below is a stack snippet that generates a leaderboard as well as a tree diagram of all of the answers.** I would like to thank [Martin Büttner](https://codegolf.meta.stackexchange.com/questions/5139/leaderboard-snippet) and [d3noob](http://bl.ocks.org/d3noob/8329404) as the sources for a lot of this code. You should click "Full screen" to see the complete results.
```
function answersUrl(t){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+t+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(t){answers.push.apply(answers,t.items),t.has_more?getAnswers():process()}})}function shouldHaveHeading(t){var e=!1,r=t.body_markdown.split("\n");try{e|=/^#/.test(t.body_markdown),e|=["-","="].indexOf(r[1][0])>-1,e&=LANGUAGE_REG.test(t.body_markdown)}catch(a){}return e}function shouldHaveScore(t){var e=!1;try{e|=SIZE_REG.test(t.body_markdown.split("\n")[0])}catch(r){}return e}function getAuthorName(t){return t.owner.display_name}function decodeEntities(t){return $("<textarea>").html(t).text()}function process(){answers=answers.filter(shouldHaveScore).filter(shouldHaveHeading),answers.reverse();var t={},e=[],r=1,a=null,n=1,s=[];answers.forEach(function(t){var r=t.body_markdown.split("\n")[0],a=getAuthorName(t),n=r.match(SEQUENCE_REG)[0];n=n.trim();var o="from A000000";PARENT_REG.test(r)&&(o=r.match(PARENT_REG)[0]),o=o.substring(5).trim(),"A000000"==o&&(o="OEIS");var i="";SEQDATA_REG.test(t.body_markdown)&&(i=t.body_markdown.match(SEQDATA_REG)[1]);for(var u=!0,c=0;c<e.length;++c)u=u&&!(e[c]===n);for(var l=!0,c=0;c<e.length;++c)l=!(!l||e[c]===n||e[c]===n+a||e[c]===o+a);e.push(n),e.push(n+a),e.push(o+a),u&&data.push({name:n,parent:o,term:i+" : ",author:decodeEntities(a),URL:t.share_link}),l&&s.push(t)}),answers.sort(function(t,e){var r=t.body_markdown.split("\n")[0].match(SEQUENCE_REG),a=e.body_markdown.split("\n")[0].match(SEQUENCE_REG);return a>r?-1:r>a?1:void 0}),answers.forEach(function(e){var o=e.body_markdown.split("\n")[0],i=(o.match(NUMBER_REG)[0],(o.match(SIZE_REG)||[0])[0]),u=parseInt((o.match(DEPTH_REG)||[0])[0]).toString(),c=o.match(SEQUENCE_REG)[0],l="from A000000";PARENT_REG.test(o)&&(l=o.match(PARENT_REG)[0]),l=l.substring(5);var d=o.match(LANGUAGE_REG)[1];d.indexOf("]")>0&&(d=d.substring(1,d.indexOf("]")));for(var p=getAuthorName(e),E=!1,h=0;h<s.length;++h)E=E||s[h]===e;if(E){var f=jQuery("#answer-template").html();i!=a&&(n=r),a=i,++r;var m=1024*Math.pow(parseInt(u),.5)/(parseInt(i)+256);f=f.replace("{{SEQUENCE}}",c).replace("{{SEQUENCE}}",c).replace("{{NAME}}",p).replace("{{LANGUAGE}}",d).replace("{{SIZE}}",i).replace("{{DEPTH}}",u).replace("{{LINK}}",e.share_link),f=jQuery(f),jQuery("#answers").append(f),t[p]=t[p]||{lang:d,user:p,size:"0",numanswers:"0",link:e.share_link},t[p].size=(parseFloat(t[p].size)+m).toString(),t[p].numanswers=(parseInt(t[p].numanswers)+1).toString()}});var o=[];for(var i in t)t.hasOwnProperty(i)&&o.push(t[i]);o.sort(function(t,e){return parseFloat(t.size)>parseFloat(e.size)?-1:parseFloat(t.size)<parseFloat(e.size)?1:0});for(var u=0;u<o.length;++u){var c=jQuery("#language-template").html(),i=o[u];c=c.replace("{{RANK}}",u+1+".").replace("{{NAME}}",i.user).replace("{{NUMANSWERS}}",i.numanswers).replace("{{SIZE}}",i.size),c=jQuery(c),jQuery("#languages").append(c)}createTree()}function createTree(){function t(){var t=i.nodes(root).reverse(),e=i.links(t);t.forEach(function(t){t.y=180*t.depth});var r=c.selectAll("g.node").data(t,function(t){return t.id||(t.id=++o)}),a=r.enter().append("g").attr("class","node").attr("transform",function(t){return"translate("+t.y+","+t.x+")"});a.append("a").attr("xlink:href",function(t){return t.URL}).append("circle").attr("r",10).style("fill","#fff"),a.append("text").attr("x",function(){return 0}).attr("y",function(){return 20}).attr("dy",".35em").attr("text-anchor",function(){return"middle"}).text(function(t){return t.term+t.name}).style("fill-opacity",1),a.append("text").attr("x",function(){return 0}).attr("y",function(){return 35}).attr("dy",".35em").attr("text-anchor",function(){return"middle"}).text(function(t){return t.author}).style("fill-opacity",1);var n=c.selectAll("path.link").data(e,function(t){return t.target.id});n.enter().insert("path","g").attr("class","link").attr("d",u)}var e=data.reduce(function(t,e){return t[e.name]=e,t},{}),r=[];data.forEach(function(t){var a=e[t.parent];a?(a.children||(a.children=[])).push(t):r.push(t)});var a={top:20,right:120,bottom:20,left:120},n=3203-a.right-a.left,s=4003-a.top-a.bottom,o=0,i=d3.layout.tree().size([s,n]),u=d3.svg.diagonal().projection(function(t){return[t.y,t.x]}),c=d3.select("body").append("svg").attr("width",n+a.right+a.left).attr("height",s+a.top+a.bottom).append("g").attr("transform","translate("+a.left+","+a.top+")");root=r[0],t(root)}var QUESTION_ID=49223,ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",data=[{name:"OEIS",parent:"null",term:"",author:"",URL:"https://oeis.org/"}],answers=[],page=1;getAnswers();var SIZE_REG=/\d+(?=[^\d&]*(?:<(?:s>[^&]*<\/s>|[^&]+>)[^\d&]*)*,)/,DEPTH_REG=/\d+, A/,NUMBER_REG=/\d+/,LANGUAGE_REG=/^#*\s*([^,]+)/,SEQUENCE_REG=/A\d+/,PARENT_REG=/from\s*A\d+/,SEQDATA_REG=/terms:\s*(?:(?:-)?\d+,\s*)*((?:-)?\d+)/;
```
```
body{text-align: left !important}#answer-list{padding: 10px; width: 550px; float: left;}#language-list{padding: 10px; width: 290px; float: left;}table thead{font-weight: bold;}table td{padding: 5px;}.node circle{fill: #fff; stroke: steelblue; stroke-width: 3px;}.node text{font: 12px sans-serif;}.link{fill: none; stroke: #ccc; stroke-width: 2px;}
```
```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><script src="http://d3js.org/d3.v3.min.js"></script><link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"><div id="answer-list"> <h2>Sequence List</h2> <table class="answer-list"> <thead> <tr> <td>Sequence</td><td>Author</td><td>Language</td><td>Size</td><td>Depth</td></tr></thead> <tbody id="answers"></tbody> </table></div><div id="language-list"> <h2>Leaderboard</h2> <table class="language-list"> <thead> <tr> <td>Rank</td><td>User</td><td>Answers</td><td>Score</td></tr></thead> <tbody id="languages"></tbody> </table></div><table style="display: none"> <tbody id="answer-template"> <tr> <td><a href="https://oeis.org/{{SEQUENCE}}">{{SEQUENCE}}</a></td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td>{{DEPTH}}</td><td><a href="{{LINK}}">Link</a> </td></tr></tbody></table><table style="display: none"> <tbody id="language-template"> <tr> <td>{{RANK}}</td><td>{{NAME}}</td><td>{{NUMANSWERS}}</td><td>{{SIZE}}</td></tr></tbody></table>
```
[Answer]
# Parenthetic, 150 bytes, depth 4, A000292 from A000290
```
((()()())(()()()())((()())((()(()())))((()(())())((()()(()))(()(()()))((()(()))(()(()()))((())()))((()(()))(()(()()))((())()())))((())()()()()()()))))
```
The next answer should match the following terms:
```
0, 1, 4, 10
```
This is the sequence of tetrahedral numbers, the 3D generalisation of triangular numbers. The formula for this is
```
T(n) = n*(n+1)*(n+2)/6
```
[Parenthetic](https://esolangs.org/wiki/Parenthetic) is a Lisp-like language which uses parentheses to define everything. The above is a function `()()()` which takes in `n` and outputs `T(n)`. Call like:
```
((()()()())((())()()()()()()()))
```
## Annotated
```
(
define
(() ()())
f [][][]
(() ()()())
(
lambda
(() ())
(
n [[][]]
(() (()()))
)
(
div
(() (())())
(
*
(() ()(()))
n
(() (()()))
(
+
(() (()))
n
(() (()()))
1
((()) ())
)
(
+
(() (()))
n
(() (()()))
2
((()) ()())
)
)
6
((()) ()()()()()())
)
)
)
Test call:
(
f
(() ()()())
6
((()) ()()()()()())
)
```
[Answer]
# Pancake Stack, 118 bytes, depth 1, A000012
```
Put this kindercarnavalsoptochtvoorbereidingswerkzaamheden pancake on top!
Show me a pancake!
Eat all of the pancakes!
```
The next answer should match the following terms:
```
1
```
This prints the smallest divisor of `n`. Tested with the Python interpreter on the [esolang wiki page](http://esolangs.org/wiki/Pancake_Stack). The interpreter expects a `~` on the line after to denote end of program, after which comes STDIN input (which will be ignored anyway).
Relevant instructions:
```
Put this <blah> pancake on top! # Push length of <blah>
Show me a pancake! # Output top of stack as char
Eat all of the pancakes! # Terminate the program
```
## Previous answer
```
Put this pancake on top!
[]
Put this kindercarnavalsoptochtvoorbereidingswerkzaamheden pancake on top!
Show me a pancake!
Put this delectable pancake on top!
Show me a pancake!
If the pancake is tasty, go over to "".
```
This one prints in an infinite loop. Additional instructions:
```
[<blah>] # Define the label <blah>
If the pancake is tasty, go over to "<blah>". # If top of stack nonzero, go to label
```
There are other instructions, but even so Pancake Stack is *very* cumbersome to use normally, thanks to a lack of numeric output and access to only the top two elements of the stack.
Unfortunately, the first line of this program seems necessary to prevent a bug concerning labels in the Python interpreter.
[Answer]
# Python, 31 bytes, depth 4, A010060 from A000045
```
lambda n:sum(map(ord,bin(n)))%2
```
The next answer should match the following terms:
```
0, 1, 1, 0
```
This one's a favourite of mine, and it's the [Thue-Morse sequence](http://en.wikipedia.org/wiki/Thue%E2%80%93Morse_sequence). There are at least two definitions of it:
* The parity of ones in the binary expansion of `n` (used above), and
* The sequence obtained by starting with 0, then repeatedly appending the bitwise complement of the sequence so far (i.e. `0 -> 01 -> 0110 -> 01101001 -> ...`)
One of many cool things about this sequence is if we grab a turtle and do:
```
import turtle
turtle.speed(0)
n = 12
# Calculate first 2^n of Thue-Morse
tm = map(lambda n:sum(map(ord,bin(n)))%2, range(2**n))
# Move to top left
turtle.penup()
turtle.setx(-300)
turtle.sety(300)
turtle.pendown()
# For each num, go forward a unit if 0, or turn left 120 degrees if 1
for m in tm:
if m == 0:
turtle.forward(1)
elif m == 1:
turtle.left(120)
turtle.hideturtle()
turtle.mainloop()
```
we get this:
![enter image description here](https://i.stack.imgur.com/lIj77.png)
[Look familiar?](http://en.wikipedia.org/wiki/Koch_snowflake)
[Answer]
# MarioLANG, 265 bytes, depth 3, A016957 from A006370
```
<
=================="
(((+)< ))+(<
======" ===="
>-))+! >-(!
"====# "==#
>-(>[!)) >[!( !
"====#=======#===#
;)++++++>[!))++++:
==========#=======
```
The next answer should match the following terms:
```
4, 10, 16
```
The sequence is merely the arithmetic progression `6n + 4`.
[MarioLANG](http://esolangs.org/wiki/MarioLANG) is an esoteric programming language based on, well, Super Mario. Calculations are done in a [Brainfuck](http://esolangs.org/wiki/brainfuck)-like way — there is a tape of cells which you can increment/decrement.
The relevant BF-like commands here are:
```
+ Increment current memory cell
- Decrement current memory cell
( Move memory pointer left
) Move memory pointer right
; Numeric input
: Numeric output
[ Skip next instruction is current cell is zero
```
So where's the Mario? Well Mario is your instruction pointer, and he starts on the left (where `;` is). Mario keeps executing instructions as long as he's on the ground `=`, and when he falls the program terminates.
The relevant instructions for this are:
```
= Ground for Mario to stand on
< Make Mario move leftward
> Make Mario move rightward
! Make Mario stop moving
# Elevator start
" Elevator end
```
All in all, the program does this:
```
Put input (n) in cell 0
Increment cell 1 to 6
While cell 1 is not zero...
Decrement cell 1
Move n from cell 0 to cells 2, 3
Move n from cell 2 to cell 0
Increment cell 3 by 4
Output as num
```
Tested with the Ruby interpreter. Note that the language has a lot of undefined behaviour, such as what happens to instructions Mario meets as he falls, so I tried to avoid any of that.
[Answer]
# Brainfuck, 2 bytes, depth 2, A000030 from A001477
```
,.
```
[A000030](https://oeis.org/A000030) is the sequence of the initial digits of the non-negative integers, so this simply reads the first digit character and writes it back. The next sequence should start with the terms:
```
0, 1
```
[Answer]
# Piet, 16 bytes, depth 3, A000035 from A000030
![enter image description here](https://i.stack.imgur.com/C6BQ8.png)
The next answer should match the following terms:
```
0, 1, 0
```
This is Piet, so the "bytes" are really codels. Here it is at a larger codel size:
![enter image description here](https://i.stack.imgur.com/n7sLe.png)
The program simply reads in `n` and outputs `n` modulo 2.
[Answer]
# Marbelous, 7 bytes, depth 3, A011760 from A000027
It's been a while since this site has seen a [Marbelous](https://github.com/es1024/docs/blob/patch-2/spec-draft.md) answer!
```
}0
<D++
```
The next answer should start with the terms:
```
1, 2, 3
```
You can try the code in [es1024's Stack Snippet interpreter](https://codegolf.stackexchange.com/a/40808/8478). In put is given via command-line argument, and you should choose "Display output as decimal numbers". Otherwise, the result will be output as a byte value, [which is technically also fine](http://meta.codegolf.stackexchange.com/a/4719/8478).
The sequence is the sequence of "elevator buttons in U.S.A.", i.e. all positive integers except 13. Note that Marbelous is limited to 8-bit numbers, but as far as I'm aware there are no buildings with anywhere near 256 floors. :)
Marbelous is a 2D language where data flows through the code in the form of marbles (byte values) falling down the grid. `}0` gets replace with the first command-line argument. `<D` is a switch which acts as an empty cell to marbles less than 13 (the `D` is in base 36), so that inputs 1 to 12 pass through unaffected. If the marble is equal to or greater than 13, the marble is deflected to the right and passes through the `++` which increments the value by 1. In either case the marble then falls off the board, which prints its value.
[Answer]
# [Rail](http://esolangs.org/wiki/Rail), 56 bytes, depth 4, A033547 from A002378
```
$'main'
0/aima19-@
@------e<
/()(!!)-@
@-()m5a()m3do#
```
The next answer should match the following terms:
```
0, 2, 6, 14
```
The program reads in `n` from STDIN and outputs `n*(n^2+5)/3`, which was a guess at the magic numbers for the [nuclear shell model](http://en.wikipedia.org/wiki/Nuclear_shell_model) from the 1940s.
Rail is a 2D language which is themed around train tracks. The above code is golfed using `@` reflectors which reverse the direction of the train, in order to reduce the number of newlines. Here it is ungolfed:
```
$ 'main'
\
0
\ /--aima19--\
| |
\--e-------<
\
\-(!n!)-(n)-(n)-m-5-a-(n)-m-3-d-o-#
```
Note how Rail starts at the top left and begins moving vertically down-right.
The stack manipulation commands used are:
```
0-9 Push 0-9 respectively
e Push t (true) if EOF, else f (false)
i Input char
o Output
a Add
m Multiply
(!n!) Store top of stack as variable n
(n) Push variable n to stack
# Halt program
```
The train branches at junctions `>v<^`, turning right if the top of the stack is true, otherwise left if false.
[Answer]
# Starry, 22 bytes, depth 4, A008619 from A000142
```
+ + +*, + **.
```
The next answer should match the following terms:
```
1, 1, 2, 2
```
The sequence consists of the positive integers repeated twice. The program reads in a number from STDIN and calculates `1 + floor(n/2)`.
[Starry](http://esolangs.org/wiki/Starry) is an esoteric language implemented in Ruby which was part of a book on... making esoteric languages in Ruby. Each instruction is determined by the number of spaces before one of `+*.,`'`. All other characters are ignored, so the above is equivalent to
```
+
+ +*,
+ *
*.
```
which looks a lot more starry! (note the trailing spaces)
The relevant commands are:
```
Spaces Final Instruction
------ ----- -----------
n >= 5 + Push n-5 to stack
1 + Duplicate top of stack
0 mod 5 * Add
0 mod 2 , Input num
2 + Swap top 2
3 mod 5 * Divide
0 mod 2 . Output num
```
## Previous answer, 53 bytes
```
+` +. + + . + +. + . +* +'
```
This generates the sequence ad infinitum instead. Some additional commands are:
```
Spaces Final Instruction
------ ----- -----------
1 mod 2 . Output as ASCII char
n ` Mark a label n
n ' Pop and if nonzero, jump back to label n
```
[Answer]
# Mathematica, 20 bytes, depth 6, A037965 from A104631
```
Binomial[2#-2,#-1]#&
```
This is an unnamed function which simply computes the definition of the sequence. The next sequence should start with the terms:
```
0, 1, 4, 18, 80, 350
```
[Answer]
# Golfscript, 3 bytes, depth 3, A000290 from A000030
```
~2?
```
The next answer should match the following terms:
```
0, 1, 4
```
This sequence is simply the square numbers, so the program takes a number and outputs its square.
[Answer]
# CJam, 34 bytes, depth 14, A157271 from A238263
```
qi_,_m*{~2@#3@#*}$<::+1f&_:+\1-,e>
```
The next answer should start with the terms:
```
1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7
```
but there aren't any left which haven't been done already.
Let `D(n)` be the set of the first `n` 3-smooth numbers: that is, integers whose prime factors are a subset of `{2, 3}`. Let `S(n)` be the largest subset of `D(n)` which doesn't itself contain any subset of the form `{x, 2x}` or `{y, 3y}`. Then A157271 is the size of `S(n)`.
[Answer]
# [Prelude](http://esolangs.org/wiki/Prelude), 16 bytes, depth 1, A000211
```
3(v! v)
4 ^+2-^
```
I thought I'd start a tree with a less obvious initial number. This is a generalised Fibonacci sequence with definition `a(0) = 4`, `a(1) = 3`, `a(n) = a(n-1) + a(n-2) - 2`. Consequently, this is mostly a simple adaptation of my [Prelude Fibonacci solution](https://codegolf.stackexchange.com/a/44929/8478). The above is a program which prints an infinity stream of the numbers. It assumes [the Python interpreter](http://web.archive.org/web/20060504072747/http://z3.ca/~lament/prelude.py) which outputs numbers instead of individual characters.
The next answer should start with the terms:
```
4
```
[Answer]
# Clip, 0 bytes, depth 2, A000027 from A000012
Given a number `n`, prints the `nth` number in the sequence `1, 2, 3, 4...`
The next answer should start with the terms:
```
1, 2
```
[Answer]
# Perl, 10 bytes, depth 1, A001477
To kick things off, here is a simple sequence.
```
print$_=<>
```
This represents the non-negative numbers 0, 1, 2, 3, etc. by printing the input number. The next sequence should start with the terms:
```
0
```
[Answer]
# J, 4 bytes, depth 4, A001563 from A000290
```
(*!)
```
The next answer should match the following terms:
```
0, 1, 4, 18
```
This sequence is the number multiplied by its factorial. In J `(fg)x` is `f(x,g(x))` here `x*factorial(x)`.
[Answer]
# Mathematica, 48 bytes, depth 5, A104631 from A001563
```
SeriesCoefficient[((x^5-1)/(x-1))^#,{x,0,2#+1}]&
```
The next answer should match the following terms:
```
0, 1, 4, 18, 80
```
Barring the long function names, Mathematica absolutely rocks at this challenge. This one is simply the coefficient of `x^(2n+1)` in the expansion of
```
(1 + x + x^2 + x^3 + x^4)^n
```
[Answer]
# [Element](https://github.com/PhiNotPi/Element), 13 bytes, depth 3, A000045 from A000030
```
1_'0[3:~2@+]`
```
[A000045](http://oeis.org/A000045) represents the Fibonacci numbers. Each term in the sequence is the sum of the previous two terms. It is notable because the ratio between consecutive terms approaches the golden ratio, also known as phi. Somewhat interestingly, the OEIS entry starts with `0, 1` instead of the common `1, 1`. The next answer should match the terms:
```
0, 1, 1
```
[Answer]
# [Prelude](http://esolangs.org/wiki/Prelude), 1 byte, depth 2, A000004 from A001477
```
!
```
The next answer should match the following terms:
```
0, 0
```
This program takes in `n` as input, completely ignores it, and outputs the zero constant. It requires `NUMERIC_OUTPUT = True` in the Python interpreter.
The nice thing about Prelude is that it has an infinite supply of zeroes at the bottom of the stack, so all that was needed was a single output command.
[Answer]
# GolfScript, 9 bytes, depth 4, A051682 from A002275
```
~.9*7-*2/
```
The next answer should match the following terms:
```
0, 1, 11, 30
```
This simply uses the formula for hendecagonal numbers found on the OEIS page.
[Answer]
# Deadfish, 4 bytes, depth 2, A005563 from A001477
```
isdo
```
This sequence is defined as `(n+1)^2-1`, which is exactly what this program does. Since Deadfish has no input, it assumes the accumulator is at the desired input number. The next answer should start with the terms:
```
0, 3
```
[Answer]
# APL, 13 bytes, depth 4, A000108 from A000142
```
{(⍵!2×⍵)÷⍵+1}
```
Catalan numbers! Indexing starts at zero for these.
The next answer should start with the terms:
```
1, 1, 2, 5
```
[Answer]
# GolfScript, 31 bytes, depth 11, A029030 from A242681
```
~][11.(2]{:C;{{.C-.)0>}do;}%}/,
```
The next answer should match the following terms:
```
1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 7
```
but it won't be able to: this is a leaf of the tree. This sequence is the number of ways of giving change with coins of value 1, 2, 10, and 11.
[Answer]
# [Retina](https://github.com/mbuettner/retina), 1 byte, depth 3, A055642 from A001333
```
.
```
The next answer should start with the terms:
```
1, 1, 1
```
I think this is the first time I used Retina in something else than Replace mode. If only a single file is given without any options, Retina assumes Match mode, which by default counts the number of matches of the given regex in the input. This regex is `.` and matches any character. Therefore, this program returns the number of digits of the input which is A055642.
[Answer]
# [Clip](https://esolangs.org/wiki/Clip), 24 bytes, depth 4, A049666 from A002275
```
/F*5nx5[Fx?<x3O]+F(xF((x
```
The next answer should match the following terms:
```
0, 1, 11, 122
```
The sequence is just `Fibonacci(5n)/5`. See [the examples page](https://esolangs.org/wiki/Clip/Examples#Fibonacci_.28inefficient.29) for an explanation.
[Answer]
# Clip, 37 bytes, depth 5, A227327 from A000292
```
[t/m++#t4*2#t3*8#t2?%t2+*2t9]*8t]48]n
```
Possible ways to choose two points on a triangular grid of side n, excluding rotations and reflections. The example given is: for n = 3, there are 4 ways:
```
X X X .
X . . . . . X X
. . . X . . . X . . . .
```
The next sequence must start with the following terms:
```
0, 1, 4, 10, 22
```
[Answer]
# APL, 24 bytes, depth 6, A025581 from A182712
```
{¯1-⍵-2!1+⌊.5+.5*⍨2×1+⍵}
```
The sequence [A025581](http://oeis.org/A025581) is the sequence of... Im not quite sure to be honest. It scares me.
Indexing starts at 0 and the function just calculates the sequence by definition.
The next sequence should start with the terms:
```
0, 1, 0, 2, 1, 0
```
[Answer]
# ><>, 25 bytes, depth 2, A001333 from A002522
```
301-v >rn;
*2@:<r^!?:-1r+
```
These are the numerators of the continued fraction convergents to sqrt(2).
The code needs the user to prepopulate the stack with the index of the convergent that should be returned. Indexing starts at 1.
The next answer should start with the terms:
```
1, 1
```
[Answer]
# J, 44 bytes, depth 10, A242681 from A026233
```
f=.(,(<:*+)"0/~~.50,25,(,+:,3*])1+i.20)+/@:=]
```
The next answer should start with the terms:
```
1, 1, 2, 2, 3, 3, 4, 4, 5, 5
```
Something closer to everyday life: "the number of ways that a score of `n` can be obtained using two darts on a standard dartboard". Only the unordered score-pair matters. Starting offset is two as in the OEIS page. Usage:
```
f 2 => 1
f 72 => 12
```
[Answer]
# R, 20 bytes, depth 11, A194964 from A242681
```
1+floor(scan()/5^.5)
```
The next answer should match the following terms:
```
1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 5
```
The sequence A194964 gives for each n the result of `1+[n/sqrt(5)]` where `[` means "floor". The R function takes input as stdin.
] |
[Question]
[
## Introduction
In the error outputs of some languages such as Java, a **pointer** is shown to give the programmer an idea of exactly where the error went wrong.
Take [this example](http://ideone.com/jd94Vy) on Ideone:
```
Main.java:12: error: ';' expected
Invalid Java!
^
```
Notice the caret shows where the invalid code is?
## Challenge
Your challenge is: given number **N** and string **S**, place a pointer on the **N**th character in **S**.
## Examples
**Input**: `2, "Lorem ipsum, dollar sit amet."`
**Output**:
```
Lorem ipsum, dollar sit amet.
^
```
## Rules
* Input is received via STDIN or function parameters
* Output is printed out to the console or `return`ed
* Trailing new lines, spaces etc are allowed in the output
* The pointer character **must** be a **^** caret and **must be on a new line.**
* This is code golf, so the shortest answer wins. Good luck!
[Answer]
# C 33
If just a function is allowed, then even c can compete.
*(For the record, 2 bytes saved thx to @Cool Guy. Mt thx comment is unexpectedly evaporated.)*
*1 more char saved thx @Mig*
```
f(a,c){printf("%s\n%*c",a,c,94);}
```
[Answer]
# Brainf\*ck - 133 bytes
```
+++++>>+>>+++>>+++++++++<<<<<<[[->++++++++++<]>>]<++++<<++<<<<--<,>[->+<<->]>>>,<<[->>-<<]<<[->>>>++++++++++<<<<]>>+[,.]>.>[->.<]>>>.
```
Expects input as `[0-9]{2}.*` e.g. "02Hello world!!!" would produce
```
Hello world!!!
^
```
[Answer]
# IA-32 machine code, 24 bytes
Hexdump:
```
66 b8 5e 00 42 38 22 75 fb 66 c7 02 0d 0a 42 42
c6 02 20 e2 fa 89 02 c3
```
It's a function (using MS `fastcall` convention) which updates the string in-place:
```
__declspec(naked) void __fastcall carrot(int n, char* s)
```
Assembly code:
```
mov ax, '^'; // ah = 0, al = '^'
mystrlen:
inc edx;
cmp [edx], ah;
jne mystrlen;
mov word ptr [edx], '\r\n'; // append a newline
inc edx;
mymemset:
inc edx;
mov byte ptr [edx], ' ';
loop mymemset;
mov [edx], eax; // append a caret and terminate the string
ret;
```
It uses `WORD`-sized (16-bit) data in a few places. This has a penalty (1-byte prefix) in 32-bit code, but makes the code smaller anyway - using 32-bit data would put two zero bytes into code!
At the end, it writes 4 bytes (`eax`) instead of 2 bytes (`ax`) - the code is smaller that way, and 2 extra bytes of junk go after string termination, so no one notices them.
Usage:
```
int main()
{
char s[100] = "Lorem ipsum, euro sit amet.";
carrot(2, s); // credit to Digital Trauma for the name
puts(s);
}
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth/commit/3313650c8fb6e8ba77f6479e269c5fd68526903a), 8
```
zp\^*tQd
```
This solution no longer works, since the commit after the one I've linked to as the language name changed `p` to have arity 1. There are several other ways of achieving a similar score in Pyth that still work today, like `zp+*dQ\^`.
If the string needs quotes, adding `v` to the beginning of the code works. If it has to be comma separated, it goes up to 10 bytes:
```
eQp\^*dthQ
```
[Answer]
# T-SQL, 90
While a fairly simple question, it's always interesting to try these in languages that really don't tend to support them well or golf well for that matter.
This answer is almost guaranteed to be the longest one.
This creates an inline table function for SQL Server that takes @n and @ as parameters and returns the results as a column. The carriage return is significant, otherwise I would need to use char(13).
```
CREATE FUNCTION G(@N INT,@ VARCHAR(MAX))RETURNS TABLE RETURN SELECT @+'
'+SPACE(@n-1)+'^'R
```
It's used in the following manner
```
SELECT R
FROM (VALUES
(1,'This is test 1'),
(2,'This is test 2'),
(3,'This is test 3'),
(4,'This is test 4'),
(5,'This is test 5')
)T(n,S)
CROSS APPLY G(n,S)
```
And returns
```
R
---------------
This is test 1
^
This is test 2
^
This is test 3
^
This is test 4
^
This is test 5
^
```
[Answer]
## Python, 27
```
lambda n,s:s+'\n%%%dc'%n%94
```
This uses two levels of string formatting.
And here's a **25 byte** solution partly stolen from feersum's answer (with the argument order reversed):
```
lambda*p:'%s\n%%%dc'%p%94
```
[Answer]
# Bash, 27
```
printf %s\\n%$[$1-1]s^ "$2"
```
### Output
```
$ ./carrot.sh 2 "Lorem ipsum, dollar sit amet."
Lorem ipsum, dollar sit amet.
^$
```
[Answer]
# sed, 16
```
2y/1/ /;2s/ $/^/
```
This is something of a testcase of [this meta answer](http://meta.codegolf.stackexchange.com/a/5344/11259). Specifically I am requiring that the number **N** is input in unary. E.g. for the caret in position 2, the input for **N** would be `11`. Also it is not strictly specified which order **S** and **N** should be, so here **S** goes first, followed by unary **N** on a new line, all through STDIN.
### Output:
```
$ { echo "Lorem ipsum, dollar sit amet."; echo 11; } | sed '2y/1/ /;2s/ $/^/'
Lorem ipsum, dollar sit amet.
^
$
```
[Answer]
# Python, 29
```
lambda n,s:s+'\n'+' '*~-n+'^'
```
Concatenates the string, a newline, `n-1` spaces, and a `^`.
[Answer]
# JavaScript (ES6): 63 62 56 52 32 bytes
Thanks to nderscore for greatly reducing the size of the code.
```
p=(a,b)=>b+`\n${' '.repeat(a)}^`
```
## Version that works across more browsers (47 bytes):
```
p=function(a,b){return b+`\n${' '.repeat(a)}^`}
```
[Answer]
# Python, 29
Here's a more fun way to do it in 29:
```
lambda*p:'%s\n%*s'%(p+('^',))
```
Example usage:
```
>>> f=lambda*p:'%s\n%*s'%(p+('^',))
>>> print f('lorem',5)
lorem
^
```
[Answer]
# CJam, 9 bytes
```
q~N@(S*'^
```
[Try it online.](http://cjam.aditsu.net/#code=q~N%40(S*'%5E&input=2%20%22Lorem%20ipsum%2C%20dollar%20sit%20amet.%22)
### How it works
```
q~ e# Read the input from STDIN and interpret it.
e# This pushes the integer and the string on the stack.
N@ e# Push a linefeed an rotate the integer on top of it.
(S* e# Subtract 1 and push a string consisting of that many spaces.
'^ e# Push a caret.
```
[Answer]
# TI-BASIC, 10 (?) bytes
```
Disp Ans
Output(3,N,"^
```
Input is given in the variable N, as the question asks, but you can't use the letter var S as a string. In place of that, it takes string input from Ans, so to run the example in the OP: `2->N:"Lorem ipsum, dollar sit amet.":prgm<program name>`.
I'm aware that that probably doesn't count, though, as each colon-delimited segment is technically a separate statement; here's a **46-byte** program that takes input as `N "S"` (`2 "Lorem ipsum, dollar sit amet."`)
```
Input Str1
2+inString(Str1,"
//^there's a space after the quote
Disp sub(Str1,Ans,length(Str1)-Ans
Output(4,expr(sub(Str1,1,1)),"^
```
Both of these assume that the screen has been cleared before running.
[Answer]
# dc, 19
```
?pr256r^255/32*62+P
```
Input is from STDIN. `dc` strings are macro definitions and contained in `[` `]`. The string of spaces is generated by calculating the number that when expressed as a base 256 byte stream gives the string we need. The calculation is `((n ^ 256) / 255) * 32)`. This gives `n` spaces (ASCII character 32), but we need `n-1` followed by `^`, so we simply add 62 to the last base 256 digit.
### Output
```
$ dc -e '?pr256r^255/32*62+P' <<< "2 [Lorem ipsum, dollar sit amet.]"
Lorem ipsum, dollar sit amet.
^$
```
[Answer]
# C, ~~59~~ ~~57~~ 47 bytes
```
f(a,c){for(puts(a);--c;putchar(32));puts("^");}
```
Pretty straightforward. Ungolfed version:
```
f(char* a,int c){
puts(a); //Print the string first
for(;--c;) //Until number-1 is not 0
putchar(32);//Print a space
puts("^"); //Print a caret
}
```
Test it [here](http://rextester.com/ZHOEK53545)
Thanks to [@anatolyg](https://codegolf.stackexchange.com/users/25315/anatolyg) for saving 10 bytes!
[Answer]
# C# 55
A function, concept similar to my C answer, but this time return is shorter than output.
```
string f(string a,int b){return a+'\n'+"^".PadLeft(b);}
```
[Answer]
# K, 21 bytes
```
{y,"\n",1_|"^",x#" "}
```
## Example:
```
ryan@DevPC-LX:~/golf/caret$ rlwrap k
K Console - Enter \ for help
`0:{y,"\n",1_|"^",x#" "}[2;"Lorem ipsum, dollar sit amet."]
Lorem ipsum, dollar sit amet.
^
```
## Explanation (`x` is the number, `y` is the string):
```
{ } enclosing function
x#" " repeat the space `x` times
"^", prepend the caret
| reverse the string to put the caret at the end
1_ drop the extra space
"\n", prepend a newline
y, prepend the text
```
[Answer]
## SAS, 35 bytes
```
%macro a(n,s);put &s/@&n."^";%mend;
```
That is the SAS equivalent of a naked function; to add the data step to call it (equivalent to C main function to call it) would be a bit more (9 more bytes - Ty Alex), but I think that's not necessary for this purpose. How it would be called:
```
data;
%a(3,"My String");
run;
```
There is a macro-only implementation but it's much longer, even if you allow it to give a warning about invalid parameters on n=1.
If we could use pre-defined parameters, SAS would be quite short comparatively on this one, which is a rarity for a language most definitely not intended to be short.
---
If a dataset is allowed to be the source of input, which is how you would 'do it' in SAS (or by %let statements), but is probably not permitted, this is even shorter (**27 bytes**, which actually could be 25 if you guaranteed the dataset was constructed immediately prior to running this [as you could then just use `set;`]):
(pre-existing dataset)
```
data b;
n=3;
s="My String";
run;
```
(actual code)
```
data;set b;put s/@n"^";run;
```
[Answer]
# Matlab/Octave, 41
```
@(n,s)sprintf('%s\n%s^',s,ones(1,n-1)+31)
```
This is an anonymous function that returns the string. This produces a warning, which can be suppressed by previously calling `warning off`.
[Answer]
# R, ~~49~~ ~~48~~ 46
As an unnamed function that outputs to STDOUT. Thanks to @Flounderer for the improvement.
uses strwrap now to ident the caret to n-1. cat uses a seperator of \n rather than empty string.
```
function(n,s)cat(s,strwrap('^',,n-1),sep='\n')
```
Test run
```
> f=function(n,s)cat(s,strwrap('^',,n-1),sep='\n')
> f(29,'The caret should point here v hopefully')
The caret should point here v hopefully
^
>
```
[Answer]
# Python3, ~~38~~ 36 bytes
```
def f(s,i):return s+'\n'+' '*~-i+'^'
# OR
def f(s,i):print(s+'\n'+' '*~-i+'^')
```
Test it [here](http://rextester.com/XVS32879)
Thanks to [@Dennis](https://codegolf.stackexchange.com/users/12012/dennis) for saving 2 bytes!
[Answer]
# [Forth (gforth)](http://www.complang.tuwien.ac.at/forth/gforth/Docs-html/), ~~32~~ 31 bytes
```
: b type cr 1- spaces 94 emit ;
```
[Try it online!](https://tio.run/##FckxDoAgDAXQq/wwi4mJDuoVvARoURIIpMXB01ed3vBC4XbZM/yoLvBoTyXsjMFCqttJMI@gHBtWnSAGW2HKiFXu3OEoKTmGfO0ytd7A6ws "Forth (gforth) – Try It Online")
Input is given as `<number> s" <string>" b`.
Note the required space after `s"`.
-1 byte from Bubbler.
Shorter than MAWP lol
[Answer]
# Julia, 27 bytes
```
(n,s)->s*"\n"*" "^(n-1)*"^"
```
This creates an unnamed function that accepts an integer and string as input and returns a string. To call it, give it a name, e.g. `f=(n,s)->...`.
All that's happening here is we're appending a newline, `n-1` spaces, and the caret. String concatenation is performed using `*` and string repetition with `^`.
Ungolfed:
```
function f(n, s)
s * "\n" * " "^(n-1) * "^"
end
```
Example:
```
julia> println(f(2, "Lorem ipsum, dollar sit amet."))
Lorem ipsum, dollar sit amet.
^
```
[Answer]
# PHP (CLI) - 42
```
<?=sprintf("%s\n%$argv[1]s",$argv[2],'^');
```
Call it from the command line:
```
php pointer.php 2 "Lorem ipsum, dollar sit amet."
```
[Answer]
# Matlab, 25
This one is extremely cheeky. Apparently displays prints non-printable characters as spaces. The following code defines a function named `ans`, that meets the specs.
```
@(N,S)[S 10 ones(N-1) 94]
```
so calling this function like this:
```
ans(2, 'Lorem ipsum, dollar sit amet.')
```
gives the output:
```
ans =
Lorem ipsum, dollar sit amet.
^
```
I always dislike the `ans =` part in Matlab answers. If this is a problem, I need to add 6 bytes... but I have always seen it like this in Matlab answers.
Note that running this code overwrites the variable `ans`, so you need to redefine the function if you want to use it a second time!
[Answer]
My first shot at codegolf
# Java, 133 65
```
String g(int i,String s){for(s+="\n";--i>0;)s+=" ";return s+"^";}
```
I'm sure it can be reduced even more.
Old code
```
public void go(int i,String s){System.out.println(s);IntStream.range(1,i).forEach(j->System.out.print(" "));System.out.println("^");}
```
[Answer]
# Pascal: 57 characters
```
procedure p(n:Byte;s:string);begin
Write(s,#10,'^':n)end;
```
Just to demonstrate Pascal's cute little output formatting. The rest is depressing.
[Answer]
# Swift, 41
It is disappointing that Swift does not have operator `*` on `Array` or `String`.
```
{$1+reduce(0..<$0,"\n",{$0.0+" "})+"^"}
```
[Answer]
# [MAWP v1.02](https://esolangs.org/wiki/MAWP), 37 53 bytes
```
%|0~[;]25W3M;@~(%)~_1A[1A~25WWM~]~1A[1A84W;]85W7M2W;.
```
Takes input as `[S][a]`, with no spaces between S and n.
Since the online interpreter takes only one line of input, the string and number are printed together.
[Try it!](https://8dion8.github.io/?code=%25%7C0%7E%5B%3B%5D25W3M%3B%40%7E(%25)%7E_1A%5B1A%7E25WWM%7E%5D%7E1A%5B1A84W%3B%5D85W7M2W%3B.&input=Hows%20it%20going13)
[Answer]
# [Perl 5](https://www.perl.org/) `-p`, 16 bytes
```
$_.=$"x<>;s; $;^
```
[Try it online!](https://tio.run/##K0gtyjH9/18lXs9WRanCxs662FpBxTru//@QjMxiBSBKVChJLS7hMvmXX1CSmZ9X/F/X11TPwNDgv24BAA "Perl 5 – Try It Online")
---
# [Perl 5](https://www.perl.org/) `-p`, 16 bytes
```
$\=$"x(<>-1)."^"
```
[Try it online!](https://tio.run/##K0gtyjH9/18lxlZFqULDxk7XUFNPKU7p//@QjMxiBSBKVChJLS7hMv6XX1CSmZ9X/F/X11TPwNDgv24BAA "Perl 5 – Try It Online")
] |
[Question]
[
Create a program that outputs `Hello, World!`
The winner is the source code that is the biggest, subject to the constraint that it is *irreducible*
For this challenge, *irreducible* means there does not exist a program that outputs `Hello, World!` that can be constructed by removing characters from the original program.
For example
```
console.log(`Hello, ` + `World!`);
```
can have the the bracketed characters removed
```
console.log(`Hello, [` + `]World!`)[;] -> console.log(`Hello, World!`)
```
And it will still output `Hello, World`, so it is not irreducible.
**Extra Rules**:
* ~~Whitespace is ignored with regards to both irreducibility and size.~~
* [Unary](https://esolangs.org/wiki/Unary) or anything that operates in a similar fashion (I'll make this more clear if I have to) is banned.
[Answer]
# [Keg](https://github.com/JonoCode9374/Keg), \$3.3 \times 10^{8912898}\$ bytes
```
...÷⅍+ℤ,(􏿿|⅍+)ℤ,(􏿿|⅍+)ℤ,(􏿿|⅍+)ℤ,(􏿿|⅍+)ℤ,⅍+ℤ,⅍+ℤ,⅍+ℤ,(􏿿|⅍+)ℤ,(􏿿|⅍+)ℤ,(􏿿|⅍+)ℤ,(􏿿|⅍+)ℤ,⅍+ℤ,
```
*Program as seen in the raw editor*
[![enter image description here](https://i.stack.imgur.com/bFjZE.png)](https://i.stack.imgur.com/bFjZE.png)
So where that `...` is, replace it with \$3.3 \* 10^{8912898}\$ `0`s. Then, add a `!` after those 0s. This splits the number into chunks of length `Ùèøø` through concatenation and then outputs the corresponding ascii character.
I owe a special thanks to @JoKing for helping me generate a truly irreducible score... it took me a while to understand it, but it got there in the end.
## Why can't this be reduced?
* Remove any of the leading 0s, and then it has the wrong number at the start, meaning that the wrong letters will be printed
* Remove any of the `÷⅍+ℤ,(􏿿|⅍+)ℤ,(􏿿|⅍+)ℤ,(􏿿|⅍+)ℤ,(􏿿|⅍+)ℤ,⅍+ℤ,⅍+ℤ,⅍+ℤ,(􏿿|⅍+)ℤ,(􏿿|⅍+)ℤ,(􏿿|⅍+)ℤ,(􏿿|⅍+)ℤ,⅍+ℤ,` part, and the chunking will go wrong.
Score calculation: <https://chat.stackexchange.com/transcript/message/52895760#52895760>
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), \$ \approx (10 \uparrow)^{625} 10.024549 \gg 10 \uparrow \uparrow 626 \$ bytes
```
⎕UCS(13⌿*⌿2+|⊃⎕RL⊣⎕RL←⍪⍨1)⊤≢⍬⍬⍬...
```
The exact byte count is
$$
\text{byte count before zilde} + \text{byte count of single zilde} \times \text{length of zilde chain} \\
= 52 + 3 \times (72x^{12} + 101x^{11} + 108x^{10} + 108x^9 + \\
111x^8 + 44x^7 + 32x^6 + 87x^5 + 111x^4 + 114x^3 + 108x^2 + 100x + 33) $$
where
$$
x = \text{power tower of (} 2 + \text{abs(internal state of Mersenne twister with seed 1))}
$$
At the end of the power tower is
$$
1338723255 \uparrow (1025549142 \uparrow (1187976951 \uparrow (683638953 \uparrow 1197707996))) \\ \approx 10^{10^{10^{10^{10^{10.02454898892586}}}}} = (10 \uparrow)^5 10.02454898892586
$$
### How it works
```
⎕UCS(13⌿*⌿2+|⊃⎕RL⊣⎕RL←⍪⍨1)⊤≢⍬⍬⍬...
⍪⍨1 ⍝ 1 1
‚éïRL‚Üê ‚çù Set RNG to Mersenne twister with seed 1
⊃⎕RL⊣ ⍝ Query the internal state,
‚çù a vector of 625 integers starting with 0 0 1
2+| ‚çù 2+abs(above)
*‚åø ‚çù RTL reduce with exponentiation
13‚åø ‚çù 13 copies of it
```
`⎕UCS(13⌿ .. )⊤≢⍬⍬⍬...` part is classic. Without going through `⎕RL`, the highest single number you can get is `*⌿2+⍪⍨1`, which is `3*3` or 27. The only other system function that can be made from `⎕RL` is `⎕R`, which doesn't work with numbers (it's PCRE replace function).
---
# Previous answers
### [APL (Dyalog Unicode)](https://www.dyalog.com/), ≈ \$ 10^{10^{10^{10^{10^{10^{10^{10^{8.56784}}}}}}}} \$ bytes
```
⎕UCS(13⌿*⌿9⌿9)⊤≢⍬⍬⍬...
```
The exact byte count is
$$
\text{byte count before zilde} + \text{byte count of single zilde} \times \text{length of zilde chain} \\
= 28 + 3 \times (72x^{12} + 101x^{11} + 108x^{10} + 108x^9 + \\
111x^8 + 44x^7 + 32x^6 + 87x^5 + 111x^4 + 114x^3 + 108x^2 + 100x + 33) $$
where
$$
x = 9^{9^{9^{9^{9^{9^{9^{9^{9}}}}}}}}
$$
`13‚åø*‚åø9‚åø9` does this: make 9 copies of 9, reduce it by power (RTL), and again make 13 copies of it. Since we need 13 digits (to convert to 13-character string), we can't touch `13‚åø`. The only operator that contributes to making a number higher than 114 is `*` (power), so we can't remove it either. If any char is removed from `9‚åø9`, we simply get a 9 or 99. If `‚åø` of `*‚åø` is removed, the `*` becomes "power of e" instead, so `‚éïUCS` will error out.
---
### [APL (Dyalog Unicode)](https://www.dyalog.com/), ≈ 1.6198e1175 bytes
```
⎕UCS≢¨⊆⍨(1129⍴11)⊤≢⍬⍬⍬...
```
No TIO this time. The trailing section contains exactly **53993507850758146386142744333468571550524632618191311756757485604204265568989694819322874649587028378175296725206816716551117407353231278417177118257863382844631479973422921647480947817133933420316923525318614797726155835511430816083805415403840314027172595512518082931013938879825791513465541135540380972893540597585182649169086261680393824120050960955555779401997457521829600791475089390923918230965201076266924917726191938715916934581792969501864553539221144133166874835664827114498421480824828796840502396309900816750358227125625773629167173751259375816861525751727161646360849365621299142542955252895691416097697138666219891143191120795244088895226859387434190840571233858421367397012295189969102957711871947102112735851782580022907564984257273029144801079437982463987025764736538779486298171952179565363242464045693851301934849205024515654449551352138803030923347653267563857979066215774822906142655781986485757538363542188567283809498107727208952982783066735317822771494040957372930876073109323855643561468444882121936718611178126143503679181305866975597866998548105699612159571516074201535860599366981549403015140492393925783660483338575307748583670119709554797435941** zilde symbols. Still no whitespace.
### How it works
```
⎕UCS≢¨⊆⍨(1129⍴11)⊤≢⍬⍬⍬...
≢ ⍝ Length
(1129⍴11)⊤ ⍝ Convert to 1129 base-11 digits
‚çù which gives 1 1 1 1 .. 2 1 1 1 .. 2 1 1 1 ..
⊆⍨ ⍝ Chunkify at 2's as starting position,
‚çù including the leading chunk of ones
≢¨ ⍝ Length of each chunk
‚éïUCS ‚çù Convert codepoints to string
```
The "chunked unary" encoding requires at least 1129 digits, and can't contain zero digits in order to be exactly 1129 digits. The base 11 was carefully chosen to avoid cracks using lower bases.
---
### [APL (Dyalog Unicode)](https://www.dyalog.com/), 1169882994796837103436970021 ≈ 1.17e27 bytes
```
⎕UCS(13⍴115)⊤≢⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬...
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qW9CjtgmGRhbmj7pbgNyAACDX2AQkE@ocrGFo/Kh3i6GhqeajriWPOhc96l0zEtD/NGAgPOrtAwaCp/@jruZD640ftU0E8oKDnIFkiIdn8P80LixBBKQedS2FSKh7pObk5OsohOcX5aQoqnPhkwMGLbqQkZG2sYWlpZmBpaWFkZmpmaGRsZm5BZA0MgaCw9ONAQ "APL (Dyalog Unicode) – Try It Online")
The trailing section contains exactly **389960998265612367812323333** zilde `⍬` symbols. There's no whitespace.
### How it works
`‚éïUCS` converts from Unicode codepoints to characters. You don't get any string without it.
`⊤` does the only numerical calculation in this program. What it does is, take a single number on its right and convert into the base on its left. Since we want an array of length 13, length-13 array is required on its left side. Since the largest digit value we will need is 114, I chose base 115 to tightly fit the requirements of left side of `⊤`.
The right side of `⊤` is `≢⍬⍬⍬⍬⍬⍬...`, which computes the length `≢` of the array containing exactly 389960998265612367812323333 `⍬`s. `⍬` is an empty numeric vector, so you can't get any meaningful number from it, other than the length of the vector.
Finally, a comment about the byte count. In [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenges, we use SBCS to count the APL symbols as one byte each. But the default source encoding is actually UTF-8, making APL symbols take 2 or 3 bytes.
[Answer]
# [Malbolge](https://github.com/TryItOnline/malbolge), 265 bytes
Malbolge is too concise to win this competition.
```
('BA@?>=<;:9876543210/.-,+*)('&%$#"!~}|{zyxwvutsrqponmlkjihgfedcba`_^A\[ZYXWVUTSRQPONMLKJIHGFEDCBA@?>=<;:9876543210/.-,+*)('&%$#"!~}|{zyxwvutsrqponmlkjihgfedcba`_^]\[ZYXWVUTSRQPONMLKJIHGFEDC<$#9]=<;:9y1U/432+ONo'&+$Hi!~}$#z@xw|uzs9Zpunsrk1RQgfe+iba'Hdcb[!_XW{[TSRvc
```
[Try it online!](https://tio.run/##rczXGoFgAADQZ6EosrIje2XLJquMRCpSkvHq@T/37pwHOCdW5GSR31oWiuRz2Uw6RSYTRDwWjYRDQTzg93k9mNuFIk4HDNlt79fzYd6Nm65d1ctZkaWTeDwIe3633aw5drVc5GbMdDIeDQf9XpfutFvNRr1WpSrlUrHwh33@eydhiJh/9zs@8IMda7dkxInBlABeGDKzxu2pmSoxVTRJvRzxLg1eTOBYhAI7Y1uORw8GvPrasj4 "Malbolge – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), ~~44619 8.13\*1011515~~ ~\$10^{10^{5749}}\$ bytes
The program itself is rather too large to fit ~~in the observable universe~~ on Stack Overflow, so this is a link to a program that can generate it... if you change the rather large number generator to a `~9` instead.
[Try it online!](https://tio.run/##bZLLDtMwEEXX9VcYo8qPuFVTNiiiexawZhFFlZM4bZBjR44DQQh@vYzzqKhg4zj2zJw7d9z/CHdn3z0eaAjKhyH41t7wBRNCUNv1zgfcjLYKzpkBNd512Ctbw2e9FGjQumbvOaovNw35KmjGkZKlrC41gjJ5mh3SAiE96Yr9BeEIvcWftL2FO3YN7t137XGIK5pAwJN69LoeK81aG47Xazea61XmRluo5VmZnwrOpSiBUshzwVEPtQMj6QkLgeeVyC164hyo9tlka/sxgFoL@4P@pgyzT21D1ECWapQev7rWsnw/FHmW/VyjfgGaINRApFFdWSs8ZZhUd88ikCQ02fIoyKSFcL6OGhIS8xSk5aJTPWsk@aiNcRJ/cd7UbwgwwDIOphkImqspfkg5FphZnMACP@LMYRvvNnkqdtc22OIP0PkpQ7syphNKyaqDSFIIy/kWvwBme@Zi@HCezWcmApiNh@lGmQdIojiarA4ktOB0k/Ey23UMy3wzIvH0PPusbrYNY63j8etoXtVHhzbsfvgPeM/okYrZjbWlYV/yxT20mxOhx93CVfzx@P3Pq4JnJ0v@Bw)
This can certainly be longer, but I'm going to post it now since I'm not 100% sure this is irreducible. It is basically made up of several irreducible components stacked together.
This relies mostly on a very large number `n`, generated by the state of the Mersenne twister with the seed `8` reduced by ~~multiplication~~ exponentation, i.e `~functools.reduce(pow,b)`, where `b` is taken from:
```
import functools
from random import *
seed(8)
d=getstate()
a,b,c=d
```
First, it execs the reverse of a very long string, separated by n waste bytes in the form:
```
exec("a...b...c...d"[::~n])
```
You can't remove the `.`s, unless you also remove the `[::~n]` reversing the string. If you remove the `.`s and the `[::~n]` then the resulting program won't really work since it is backwards, and the only `print` part is at the end, so no output without that.
The next portion looks like:
```
print(''.join([chr(len(...)), n ''s, chr(len(...)))][::~n]))
```
Similarly, you can't remove the `''`s without also taking out the `[::~n]`. You also can't reduce `chr(len([0]+[0]+...+[0]))` and still get the character you want, nor can I find anyway of modifying it with the `''`s to still get the character as well as another list item.
Please point any mistakes I have made or any ways you can think of to reduce this.
[Answer]
# [JavaScript](https://tc39.es/ecma262/), 9007199254741154 bytes
```
n=0
a=Number.MAX_SAFE_INTEGER-1
b="Hlo, world![...]e"
console.log(`${b[n]}${b[a]}${b[++n]}${b[n]}${b[++n]}${b[++n]}${b[++n]}${b[++n]}${b[++n]}${b[++n]}${b[++n]}${b[++n]}${b[++n]}`)
```
Where `[...]` is \$2^{52}-14\$ `?` characters.
The -1 is needed since strings cannot be longer than \$2^{52}-1\$ characters.
`a` cannot be reduced to a smaller number other than `1`,
which would not work since the `e` in the string cannot be put that early in the string than the `!`.
The `console.log` cannot be reduced,
since none of the characters are needed in the string "Hello, world!".
Overall, there's no way to get the character `e` without going past the `!` in the string,
and there's no way to get a number bigger than 11 other than `a`.
This could probably be improved by using `charAt`,
but I'm not confident that couldn't be reduced in some way
and it would not change the order of magnitude.
[Answer]
# [Python 3](https://docs.python.org/3/), more than \$X\$ with \$X=I \uparrow^{I\uparrow^I I} I\$ with \$I=5735816763073854918203775149089\$
The code is obtained by replacing the `...` in the following code template with \$X\$ `1`s.
```
Q=...
exec((762032390336888825205597926747277417487750831511159354629396897028305422383809626318366885737257014369722764755200848545489986725226445234793373668671810533881138176176448303759321782505578156778007890400705523398552371012795706771315225018503248709400507137379430210053109689578295520735219645943760052105586918960055263333607993034635218854740823639508170672552847248741914750040981085688131560558606928438081257071207856256012302413393203594650299912375359565857111459962764512316315869934115819878468802797551498049081777877631940391679271936869727271355722250026194813663937402797387251113215482921743182358788283759577057493220552247028564950916113993279648626087865361138353729963114793860621704499349445249742987180001965672667483449648323146579902833012079301328244612376274244962633770509185016854868366255206566065732320472204953606291770458667922914208019769351151138241745701181139210).to_bytes(ord("≈µ"),"big"))
```
Shortened version if you don't want to/can't scroll that far
```
Q=...
exec((762...digits...210).to_bytes(ord("≈µ"),"big"))
```
## Why it prints `Hello, World!`
The expression passed to `exec` evaluates to the string
```
def arrows(a, n, b):
if n == 1:
return a**b
if b == 0:
return 1
return arrows(a, n - 1, arrows(a, n, b - 1))
def fast_function(n):
return arrows(n, arrows(n, n, n), n)
def inverse(n):
i = 1
while True:
if fast_function(i) == n:
return i
i += 1
print(inverse(len(str(Q))).to_bytes(13, 'big').decode())
```
How? The big pile of digits in the original code is just this string but we interpret the bit sequence given by its ASCII encoding as a binary representation of a number (this is obtained using `int.from_bytes(...,'big')`, `'big'` for endianness). Then we get the string by the inverse method `.to_bytes(length,'big')`. We use a trick to meet the requirements and instead of having the length in decimal we use `ord("≈µ")` which evaluates to `373` because that's the Unicode codepoint of `≈µ`.
`arrows` computes \$A \uparrow^N B\$ using a formula from [Wikipedia](https://en.wikipedia.org/wiki/Knuth%27s_up-arrow_notation).
The number \$I\$ is given by `int.from_bytes(b'Hello, World!', 'big')`.
This way, `Hello, World!` is encoded in that very long string of ones.
Then we decode this string by inverting the function with which it was defined.
## Why it's irreducible
It's not very a formal proof, but I think it works. The fact that my code structure is very simple helps.
To print `Hello, World!` we need to call some sort of printing function. Clearly, the only hope for that is by the `exec` function. The doc says that [`exec` must take a string or a code object](https://docs.python.org/3/library/functions.html#exec). Well, actually we are passing a `bytes` object which also works. If it didn't work, we could just use `.decode('ascii')`, but because `bytes` work this would make a reduction possible. So to obtain such an object (byte, code or string) we will need to use either the quotation marks or the `to_bytes` method. There's only a few options with quotation marks and none of them work. So we must use `to_bytes`.
Because we encoded the string length as `ord("≈µ")`, any change to the parameters of `to_bytes` will break the program. So we must change the big integer that encodes our code. It's statistically obvious, but if you want you can also computationally check that if we delete any single character or a pair or a triplet of characters from it, we will get garbage, and for sure not a working code that prints `Hello, World!`. If we delete 4 or more characters, we will get an integer more than 256 times smaller. Because we interpret that with the same length (`ord("≈µ")`), we will get a null byte, and `exec` will throw `ValueError: source code string cannot contain null bytes`.
## Extra
Code for generating answers:
```
code=b'''
<insert code to be executed>
'''
print('Q=...')
print('exec(('+str(int.from_bytes(code,"big"))+').to_bytes(ord("'+chr(len(code))+'"),"big"))')
```
Note that `chr(len(code))` won't always exist (especially for very long codes), so this answer doesn't easily generalize to any very fast function. In my opinion if someone comes up with a way to do it for any code this question will be ultimately "solved" (edit: actually, [Higman's lemma](https://en.wikipedia.org/wiki/Higman%27s_lemma) implies that the score on this question is bounded, so this is impossible).
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~1862 ...~~ 1.3\*1056 bytes
```
eval ("üÜí"*33425716343835650854570646632771294442636521632690315021).size.digits(999).map(&:chr).join
```
[Don't try it online!](https://tio.run/##DcrJDcIwEADAVlAeyOZh2Xs5W04IETgih3JJUAAF0EBaTAeGec@0Xl85N1v1PJni2D/f4oJIwDEIEpbIwr5k4uiFRBBiDKBEBILC8E8g6jGwh2DdnN6Nu6V7WmajqtZ11WjO9WOyrh1Sn/MP "Ruby – Try It Online")
Packed the whole program into a single base-999 number (1 digit for each character).
Decode, convert to ascii characters, join and evaluate.
[Answer]
# [JavaScript](https://tc39.es/ecma262/), 24855 bytes
```
[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]][([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]](([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(+(+!+[]+[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+[!+[]+!+[]]+[+[]])+[])[+!+[]]+(![]+[])[!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(+![]+[![]]+([]+[])[([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]])[!+[]+!+[]+[+[]]]+(![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[!+[]+!+[]+[+[]]]+([]+[])[(![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(!![]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]]()[+!+[]+[!+[]+!+[]]]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]][([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]]((!![]+[])[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+([][[]]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+!+[]]+(+[![]]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+!+[]]]+([][[]]+[])[+[]]+([][[]]+[])[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[+!+[]]+(+(!+[]+!+[]+[+!+[]]+[+!+[]]))[(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(+![]+([]+[])[([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(+![]+[![]]+([]+[])[([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]])[!+[]+!+[]+[+[]]]](!+[]+!+[]+!+[]+[+!+[]])[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]])()([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]][([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]]((!![]+[])[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+([][[]]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+!+[]]+(+[![]]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+!+[]]]+(!![]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[+!+[]]+(+(!+[]+!+[]+[+!+[]]+[+!+[]]))[(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(+![]+([]+[])[([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(+![]+[![]]+([]+[])[([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]])[!+[]+!+[]+[+[]]]](!+[]+!+[]+!+[]+[+!+[]])[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]])()(([]+[])[([![]]+[][[]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(![]+[])[+!+[]]+(![]+[])[!+[]+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]]()[+[]])[+[]]+(!+[]+!+[]+!+[]+!+[]+[!+[]+!+[]+!+[]+!+[]+!+[]+!+[]+!+[]+!+[]])+[])+(!![]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+[[]][([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]([[]])+[]+(+[![]]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+!+[]]]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]][([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]]((!![]+[])[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+([][[]]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+!+[]]+(+[![]]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+!+[]]]+([][[]]+[])[+[]]+([][[]]+[])[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[+!+[]]+(+(!+[]+!+[]+[+!+[]]+[+!+[]]))[(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(+![]+([]+[])[([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(+![]+[![]]+([]+[])[([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]])[!+[]+!+[]+[+[]]]](!+[]+!+[]+!+[]+[+!+[]])[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]])()([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]][([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]]((!![]+[])[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+([][[]]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+!+[]]+(+[![]]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+!+[]]]+(!![]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[+!+[]]+(+(!+[]+!+[]+[+!+[]]+[+!+[]]))[(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(+![]+([]+[])[([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(+![]+[![]]+([]+[])[([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]])[!+[]+!+[]+[+[]]]](!+[]+!+[]+!+[]+[+!+[]])[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]])()(([]+[])[([![]]+[][[]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(![]+[])[+!+[]]+(![]+[])[!+[]+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]]()[+[]])[+[]]+(!+[]+!+[]+!+[]+!+[]+!+[]+[!+[]+!+[]+!+[]+!+[]+!+[]+!+[]+!+[]])+[])+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]+(![]+[])[!+[]+!+[]]+([][[]]+[])[!+[]+!+[]]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]][([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]]((!![]+[])[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+([][[]]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+!+[]]+(+[![]]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+!+[]]]+([][[]]+[])[+[]]+([][[]]+[])[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[+!+[]]+(+(!+[]+!+[]+[+!+[]]+[+!+[]]))[(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(+![]+([]+[])[([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(+![]+[![]]+([]+[])[([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]])[!+[]+!+[]+[+[]]]](!+[]+!+[]+!+[]+[+!+[]])[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]])()([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]][([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]]((!![]+[])[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+([][[]]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+!+[]]+(+[![]]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+!+[]]]+(!![]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[+!+[]]+(+(!+[]+!+[]+[+!+[]]+[+!+[]]))[(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(+![]+([]+[])[([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(+![]+[![]]+([]+[])[([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]])[!+[]+!+[]+[+[]]]](!+[]+!+[]+!+[]+[+!+[]])[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]])()(([]+[])[([![]]+[][[]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(![]+[])[+!+[]]+(![]+[])[!+[]+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]]()[+[]])[+[]]+(!+[]+!+[]+[+!+[]])+[])+([]+[])[(![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(!![]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]]()[+!+[]+[!+[]+!+[]]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[!+[]+!+[]+[+[]]])()
```
[Try it online!](https://tio.run/##7ZzBboQgEIafhRvG9N53IRw2PbWnpm329S2iKILC1qTraL5sognMDiPw//Azu37c7rfvt6/3z5@X@2vXGWu0MrY1tjHuYlttVH9z5e7mylTb1/ZVri5Y@kI12Kvl11Vmkxv6AtfwgY0XrQ6LKnU@NBlZrLRXazTUx75CgcjeT9yJGYy0XjN//2H@yhnukvPMm/uM366Zxg59W025fwR2Tevr1cgi3hIswOUn5vLYxTKAA0POQwpgk925azM9CQ2y2L34yN0PTQazl0MDZlFiUTq3wMj6WD06OtlgFIcrbGKnRz@@S9TKDDW11SX3v1Uhb24mw@NKouU/yAV/b/odgOyp7BUC2gAavoQ22KrfGIBC4Guki5gGMBcX01YvnU4rWXUJb3SjkRBAESgiIfZKCOQB8gCKhWKRBwAGwFxOHsywKD1h8jTGVrPuFaDK3B8kFT4pM0Q0mC37OUnXlC/DDxX@tJ06Ryarbw9S3UOq4rfJC/dWm3EWi9QpHHOwpWBLwTEHmVKOQqBhaJijEI5CAAxHIWRKgSJQREKQKUUeQLFQLPIAeQBgkAdkSp@dKX00XZpkSqXOr43BnFEc/1MdZQmLw@IoS5JTqE9oGBpGfaI@AQzqk@QUUASKSAiSU8gDKBaKRR4gDwAM8oDk1FOSU2aRcOL9oLwf9GTvBxUQdspjjo267hc)
This was made using [jsfuck.com](http://www.jsfuck.com/) with the input `console.log("Hello, World!")`. This is the smallest program I could make. Smallest because, due to the fact that there's only 6 characters, I'm afraid that a bigger one could easily remove characters to come up with a smaller one.
[Answer]
# 05AB1E, ~\$ 2.5 \* 10^{1777} \$ bytes
The program starts with
```
0>>>
```
and ends with
```
>>>‚ÇÉ!B
```
The middle part contains only `>`s. The total number of `>` characters is:
```
25098162498309588141154755713074390728103069770760074052238917714173876569868691148634176042549175869030448613081100685727537868105068700724415925612269913808499593749918259101545058124654299723726788764334516211684517256948150101180347289022916451558063426031977347451784256897939400652192236258404382348291844743098281742132582049622009384267074810165806373625784728505734586204138892008754810475549403699039426186131241703961770535892728517146019084030050442530148258880465488890083243702565168936069732829928523360052189688531653618029376719759781260232103800093423138357627776562507740948193791067875062805362373001178316850530206611655698994809536157618843298702262299360918288261564223252149018550707768612220426942031389689583329954564583964489539401022510402195332590853218889942437696056695694081344105843161388328303942196356740993490866574068963912863542108279785861191372068053541704843746894440836367259040196995776642457675255580282220480198375934046309922417713428449142775746485165498609097611793368868901625760889393125891944629947649779133088521446313250650588664709735304384247130277354954932511616598273575895960608533708122096438984165676161316003824004917770330565834832795106416101932812692556113632137070814564345428247405370236327568550073970242283021250795797947677972536187886102436517154778645480506007742084298028704070794564223287823038090829494405820111266559120056874535142759744222946196301541177968199011163222223586545099389340200154682693649402549469667375585074560462157985842615966304441485063393013230239088187979990342162755440071831240592907396920570963455610552369098113994760814140693782610141274535146253381742786984559554283939414217235549169221491345428712601180598448294078655886898659207237704837686666199040000000000000000000095
```
[Try it online!](https://tio.run/##ZZW5taNFEIVjIYPau8qdTJhzMLAwyAAyJZE33xXjjRxJv7pruZv@@vv373/@8fUVbbc@Ubdp17te7l2v@3naqzx7sW5pc@/ZG@OhdUTu@Xucfrlvem5n59xrJ3k4VtHFkeYpt4vnFFx3s9l@8TofV9ya74@qUeV90eMRc@e5tnXXl4833@hzY7S2Xo@arrh7kS/mLSNUZjWbuM/y4VHpar2NW76WxR5nEefDz91rDBpj6SzGr7qzDD177/KKOTv82HSit6xyI2u5v8Vp0FqAeRWe/B5WNxFmlxQZkKK3@XzaPJWgOBMwPc0AhQusuMeVfa3DAr3om2xvDBDjwoxd/fF9gNs6myuq42A/5gdIwAuKxexp4M80uyaAeD/KZ1Q@YzPg2csRlRlsctSJ5AGE@t7sdjJy0tgC3OeBTd8D77HIQAZrWrEiGT77Tbwn9pHRQxcCnHsQBScPZmMZeSCJER18KS8I0sJmYKolnOMa2qMtBX23Mg5JIAPY0rxifxc8ego@gmnrzLfpSl@Eh2YAFN1UmEZjF8ScFDoUA@ELgGiQLiDs1G4AN/htDjUoNusJLyqA1txYz5w0hGgTbSK7YnyRBnj5YchvskeLgwlFZpov9J48D5yASN02HhjCuTuyfqwuVFq0FjVfcaGKPjk5T9Mw4qGCZjc2LmB5HS3NQps2XQ5swk0izEGL6LTkR6hBnucFMcwyhVJQAu60swNeR9wJ0/REnshyjK3z0BnScgYZQCv8hC0YF8@u8KaLhI4pAIJF61EuYbIk@FJa0JKtAPw4CLk0xiM8IwTwMboTzEgRPYXBBzxtcWqYS0pHiJgM5yk4UDvNEe3iugRCGBtO4yrqS5KEBWnhoIYHEQJ1xTX2AgRGIqeke/3@sDVqsZfHE0QEgeFSLSDjd/ZlW7CX9okTuiCDkcsIQ4KKmquoMuk8MB0ShQwYlASvfiqTu5FyCWKIw83MQDa4My5iRxR4jbwr@BdHmAvfIvMaaUn5BkMP@TohwDVm1wvbj6IPna04pwxHB0/gD4WGwrZQ7TxU0XiMFmQwcch@aE9pAgWjJC5CglUS0g1OQYKUJ/lXSCh7EC3GJo2g4vkqgoxoPsEH6kQY7AEz6FuTICQ8fyKeH92IBccE5IAsSyJ5/NwXuWV@MhNEoR5AWlyl8hY4CO1UBjpNZHH/n8qn@FGGI6dSAoM5cPRHxHxgIv0PyE2pMOAl9Bj@19f1f//8@9u3r68f) (using an integer literal instead of all the `>`s, since the full version obviously isn't gonna fit on TIO). Or [try the code that generated this number](https://tio.run/##yy9OTMpM/f9fySM1JydfRyE8vygnRVHpUVOz4uFt//8DAA "05AB1E – Try It Online").
Proof of validity:
* `B` is the only operator in the source that can return a string, thus it cannot be removed.
* `B` on an empty stack returns an empty string, and on a single-element stack it returns `10`. So we absolutely need two elements on the stack. Since `0` and `‚ÇÉ` are the only operators in the source that increase the size of the stack, neither can be removed.
* If `!` was removed, the resulting program would look like `0 (some number of '>'s) ‚ÇÉB`. This converts the number of `>`s to base 95. Since `!` is not a base-95 digit in 05AB1E, this cannot produce the string `Hello, World!`. Thus `!` cannot be removed.
* Since neither `0`, `‚ÇÉ`, `!`, nor `B` can be removed, the program is guaranteed to look like `0 (some number of '>'s) ‚ÇÉ!B`. This converts the number of `>`s to base 95! (where `!` means factorial). This is an injective operation: only one number will yield `Hello, World!` when converted to base 95!. Thus, the number of `>`s cannot be altered.
[Answer]
# [Runic Enchantments](https://github.com/Draco18s/RunicEnchantments/tree/Console), ~~12186~~ 15596231 bytes
```
_/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\
^+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"
"n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+
z""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
"+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n+n
n"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+
\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\k@
```
[Try it online!](https://tio.run/##KyrNy0z@/z9eP2YUjmzIFaetNApHNuRSytMehSMbclUpjYIRDriURjPCSIdceaMV4kiHXKPt4hEPsx3@/wcA "Runic Enchantments – Try It Online")
Above code generates only an `H` and operates as a platform by which modifications are made in order to achieve the listed score. Previous explanation in edit history.
Further?
Further.
```
"̌ * " +᷾ "̌ + . ᷾.
. . . . * . . .
n . . . " . . .
. . . . 1 . . .
. . . . ? . . .
Õê. . + . " * " nÃÇ
" * " nÃÇ nÕê + . .
```
This pattern is not reducible (ignore the spaces, they are used to align things so that the modifier characters are visible, as they don't combine with non-alpha characters; `.` are NOP code points that can be subject to alteration). See [this tio](https://tio.run/##KyrNy0z@/1/pTI@WkvbD7fuADG09PSCDSw8ItICYKw9IKIEYIBFDGMMezDg7QU9bT0lLKe9MExeEyjs7AWjA//8A) for a version without and [this one](https://tio.run/##KyrNy0z@/1/pTI@CloKSgvbD7fsUQBxtBT0FPRCHS08BArWgNFcelKEEE4CpMEQXsIcLnJ0ApLTBmkDW5J1pUuBCMPOA0mALFf7/BwA) for full accurate placement with spaces.
The pattern uses [74 bytes](https://tio.run/##KyrNy0z@/1/pTI@WkvbD7fuADG09PSBDDwi0gDgPiJX0IMAQStuDiLMT9LT1lLSU8s40Qci8sxOAWv//BwA) to represent `-4`, or 18.5 bytes per `-1` (up from the baseline 7 bytes). And we need *a lot* of `-1`s. 117704 of them to be precise.
Proof of irreducibility:
* No entire rows can be removed, the `1?` lines appear to be, but due to the duplicated `"` (one above, one below), this will result in the string `*nÕê` being multiplied against the next value on the stack, which (as the string is first) is not a valid action. the `n..."` row can't be removed along with those two, as the `n` is needed in the leftmost column
* There is no 8-way contiguous vertical collection of `.` that can be removed (reducing pattern width), as the lower right corner is inaccessible and no other `.` exist on the bottom row.
* Directional change characters can't be removed without bypassing the needed number of `-1` operations. The closest we can get is changing the bottom row to `"*"n+..`, but this would only be viable if the initial value `"rb"n` (9141) minus the desired character was both:
1. Divisible by 4
2. Constructable from the available bytes (`e`: `2260`/`"inch"`, `!`: `2277`/`"failure"`, the rest are not divisible by 4)
* *Or* if "rb" can be reduced to either "r" or "b" without adversely affecting the output (note that `"r "` and `" b"` are not valid and will produce a `-1` instead of a positive value). Given a vertical arrangement of the setup and output sequences and the ability to place these bytes such that this is prevented, this will not be possible.
+ Six rows need to be prevented from wholesale deletion (partial deletion results in `"r."` or `".b"` where `.` is a non-empty byte)
+ Putting `rb` and `k$` on paired rows
+ entry and terminator each on their own rows
+ A reflector on the top row above a `^` entry point protects the top row
+ Any row with the `"` around `rb` is automatically protected, as these bytes need to remain
Thus, the entry column is `_^"rb"n͐`, the output/reset between letters is two columns, `̌.."rb"!͐` / `᷾..$k..̂.`, and the last column (aligning `k$` with the initial `rb`) is `..;$k.̂.` (executed bottom to top).
The two columns allow the code to bloat slightly, adding seven more `.` positions over keeping input and reset on a single column (`k$"rb"ǹ`) as well as an additional (more expensive) `᷾`.
[This](https://tio.run/##KyrNy0z@/z9e6UyPlpL2w@37gAxtPT0gQ@9MD4hSAAM9rjg9INACEXowIaU8IEcJjEF8BQVrriKQvCEQF6lAhFS4kkBC9kCclA0RyuZS0js7QU9bT0lLKe9MkxLcvLyzEyBCQIa2nqIiUNGZJqBMIlDyTNP//wA) represents code entry, one copy of the pattern, one output, and final output (a newline) and termination. Not the extra `!` needed on the last iteration of the pattern so that flow is correctly handled (this costs a measly 13\*3 bytes; along with 7\*4 bytes at the end of rows that we can't enforce not being removed).
Finally, replace all `.` and `*` with `ÙÄÄÄ` (or other four-byte codepoint).
I've done my best to accurately account for the overhead increases and costs after computing the raw pattern's byte sum, but I recognize I may be off by a small amount.
### Ohgodwhy; it gets bigger
I *believe* this is irreducible.
```
DL.....DL..
R."p"...U..
..RD....D.L
.U.L"Ãåa"L.RU
RDU.\..../.
U.L...DL\.D
..ULUL...DL
...ULUL.D.L
....U...LRU
>.0....U../@
."R"h"D.R+U
.t...DL.UL.
."..D/..≠.D
.RU/LU..L.?
R.D....RU.n
U"z"᷾.R5URU.
..R:lÕçU..U.L
```
[Try it online!](https://tio.run/##LY49CkJBDIT7HCOtMGtjI/hTbJkqkO41YqMgDxFtPIOeRytP8DyEJ1ln9700yWT4hrnc@uO@lGyoU5c49KwUwRvw3AyY8GE6PHZq8BDPga5aCUKjwR0yibAYpWASjR4TYWTXmE8ybQXqetAMn4XgOpYgwz/PBKyGd431SEbAsGHB1skDvYTe9ff6wBdBXfsuT99n1HAr5Q8 "Runic Enchantments – Try It Online")
Sequence `>.0` simply to set the stack to contain an initial value (and should be considered `...`)
All the `UDLR/\` would be replaced by their 2-byte modifier counterparts and every cell not otherwise filled with a command is given a 4-byte unicode character. This works out to (I think) 647 bytes to generate a single -1. On top of that, our initial value rises from `"rb"n` (9141) to 914,100,000 by making each initial letter get constructed from `"rb"nYC`. As `YC` occupy space, they would irreparably damage the redirection pattern.
*Roughly* speaking (accurate overhead between letters not verified, but we're talking about a few dozen bytes at most), this works out to a **score of 7,688,494,370,086 (7.6 trillion).**
Breaking this would require finding a way to bypass the maze of pointer redirections without (a) breaking the pattern--as a large number of the paths redirect away an infinite loop or an invalid command--and still (b) generating a 5 character long string prior to hitting the `n`, due to a `:l͍5≠?` jump check. It costs a few bytes to make this check (11 bytes lost), but reinforces the durability of the pattern.
The string `pathz` was chosen as a 5-character long sequence where every right-truncated string ("p", "pa", "pat", "path") was present in the word dictionary (meaning that when calling `n` on it, a positive value will be generated), forcing the program to trace out a meandering route to pick up each letter before hitting the `"z"` to get a string *not* in the dictionary. This can still be improved as `paths` is also present in the dictionary (leading to a 6-length string `pathsz`), but at this point I'm starting to look for something that will increase the byte count exponentially and searching the word dictionary for longer strings with the desired characteristics is tedious.
[Answer]
# [Wren](https://github.com/munificent/wren), 1220 bytes
Finally found a use of Wren's verbose syntax!
~~I'm pretty surprised that none of those answers use the perfect byte-waster log.~~ The eclipses are things that are too long for this program.
```
["...","...","...",...].each{|i|System.write(String.fromCodePoint(i.count))}
```
[Try it online!](https://tio.run/##Ky9Kzfv/P1pJKVYvNTE5o7omsya4srgkNVevvCizJFUjuKQoMy9dL60oP9c5PyU1ID8zr0QjUy85vzSvRC8tJz@/SFOz9v9/AA "Wren – Try It Online")
## Explanation
```
["...","...","...",...] // Those constants too long for this program
.each{|i|} // Each, the perfect byte-waster!
System.write() // Verbose output to STDOUT...
String.fromCodePoint() // Convert to code points
i.count // Length of i
```
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 10658 bytes
[Try it online!](https://tio.run/##7dq9DoIwFIbhy6GNSqr2BwZMiOhVuDE5E6@/pqcYz2pC4vIu5Sk97VBymL55OczLM@fHy7mQyphOZYy92IuDkeXz95UuijcZU1sefpTJXS//sDvIZJIipzb0@y0O2TXlOcUGgL9jDFwCAHQlAICmBgDQ1AAA@p2PwkUBQF8AAOh3AAC/AgAATQ0AoBk3gG1VwlBig/Gqk5Dmc6O6MAZVWL1GFE1dGC4CX6s7GY81vmhrRc0s6hPWMKMKYHbW2pzf "C# (Visual C# Interactive Compiler) – Try It Online")
C# allows unicode escapes in identifiers, and I decided to take full advantage of the fact here.
Non-escaped code:
```
Write(String.Join(String.Empty,(String.Empty+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'¥'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'¥'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'¥'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'¥'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'¥'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'¥'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'¥'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'¥'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'¥'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'¥'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'¥'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'¥'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö'+'Ö').Split('¥').Select(l=>(Char)l.Length)))
```
The program creates a string of `ÖÖÖÖ...¥ÖÖÖÖ......` (`...` are placeholders) and splits it along `¥`. For each resulting string in the array, it takes the length of the section and casts it into a character.
[Answer]
# [Golfscript](http://www.golfscript.com/golfscript), 144,202,216,216,222,088,064,174,222,228,216,200,081 bytes
```
"...",`3/{~2/}%''+
```
where ... is replaced by 144202216216222088064174222228216200066 0's
### Explanation:
```
"...",` Count 0's and convert to string
3/{ }% Map over each group of 3 digits:
~2/ Divide by 2
''+ Convert ascii codepoints to string
```
The ascii codepoints for "Hello, World!" are as follows:
```
072 101 108 108 111 044 032 087 111 114 108 100 033
```
Concatenating them together isn't enough to be able to access them by splitting them into threes because the integer would be interpreted as 72101... rather than 072101..., meaning that splitting it into threes would yield 721 as the first codepoint instead of 072. To remedy this, I doubled it and then divided each individual codepoint by 2 after they're separated out. This has the added bonus of nearly doubling the length of the code.
[Answer]
# Mathematica, 1010128433 at least 10‚Üë‚Üë11.29 bytes
```
FromCharacterCode[StringLength["aaaa...aaaa"]~IntegerDigits~Nest[Hyperfactorial, 10, 9]]
```
old:
```
FromCharacterCode[StringLength["aaaa...aaaa"]~IntegerDigits~Hyperfactorial[Hyperfactorial[3]]]
```
Where "aaaa...aaaa" is `FromDigits[ToCharacterCode["Hello, World!"], Hyperfactorial[Hyperfactorial[3]]]` a's long. That's about 10128433 digits long. The key here is that the "W" is character code 114, which means the base of the number can't even drop below 114, or the code won't output properly. I believe `Hyperfactorial` to be the fastest growing function, with `Hyperfactorial[3] = 108` and `Hyperfactorial[4] = 27648`, meaning that nesting 2 Hyperfactorial is the maximum number, and any attempt to reduce it will drop the base below 114.
Edit:
This is not the biggest answer, `Nest[Hyperfactorial, 10, 9]` as a base would be bigger, as it cannot be reduced to a number greater than 114. Sadly, I'm not at the level to even start getting close bounds, so lets go with a very poor lower bound, which would still be a valid score.
`Ω(Log10[Hyperfactorial[x]])` is `x`, where `Ω` is lower bound notation. It's really closer to x2, but compared to the power of logerithms, they may as well be the same. This means that Hyperfactorial nested 9 times is at minimum (10)↑↑(10). The number of characters is 10 to this power, so (10)↑↑(11).
[Answer]
# 05AB1E, 5,697,476,345,285,646,822,141,672,875,833 bytes
```
….g257B
```
The `…` is actually 1,424,369,086,321,411,705,535,418,218,957 `…aaa`'s.
## Explanation
```
… # Push 1,424,369,086,321,411,705,535,418,218,957 things
.g # and count how many things there are on the stack
257B # then convert it to base 257
```
I think `…aaa` is the longest irreducible literal possible, so I use it here.
[Answer]
## Charcoal, ~~4022948789620328394911726~~ 144202216216222088064174222228216200073 bytes
```
↑E↨L´´...´´φ℅ι
```
Explanation: `´´...´´` represents a string literal of length 72101108108111044032087111114108100033. However, `´` is the quote character in Charcoal, so it needs to be doubled in order to quote itself, thus requiring 144202216216222088064174222228216200066 `´`s. The length is then converted to base 1000 using the predefined variable that contains 1000, and the values are then converted to their Unicode character values. However, the result is still an array, so the `↑` is used to output the characters correctly.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~17,502,248,526,741,541,454,928,712,794~~ \$3.14 \* 10^{1896}\$ bytes
```
³!¤“...”LbỌ
```
[Try it online!](https://tio.run/##dZW7sVxHDERTkTLAdwCkoyo5KibAHBSGMqBJj5kokqfT6@s55O7OxTT6d//689u3719fv378/uuf39IrIz3PxryXf7o9w3ctp70sm1/bred2x@02u8uq7730yZwdq8y2KTtbT784Pr2x7vOICS9n3HuzflZVnRU10Xc7z2Zz5869wo7Lp3q3Lx4HMmrtbmwvLS9i8/Gx3rOM97b6vUghZgiHXgGLB18Z43Je7aaD3S08egD3@P@0xbweH2/rY53Hnmyxx8VrvmnlcV5bzpA2HrJgFgc412kHzrAw23B/vb6sZP2AwLR7AVaLtHbQVUJUz3seO1XHrcwrHiigzAL1CUNY82t3B3zAEF8xuFLLmgC8y@0BCF83e7ICJ@Y6ul5fo54gIQG7ZQx/7Tf@YdNeSmwzNje@ytdMGoQRdCbAkL8YuNZ1BU9oBtvQfaIS@T0A7FiB8Tw07vkcYbcuxdF7VXld7ZzlpOthyL/BEIfuyxKLK5jOuvtkLkdIjDa@PIXeaMBYHMnd26nxxsFzpjd6IHcyAfCeKXIKNcWSZMJpa6wNOPz20H1TXjPhvYdq/QyXhsvBs1iGZ0QKJgIqgyauNkHOKGAgJtyCj@vgizDcycCGuIShEWjxouGscp8lNth630ARBphO2C12YYU2OMGIp7gpDI@jLIyPH@YnXRDRMQgGqMBN4MUw@sFTxmy5WpwV5BS0WhOwJaH4VvikDDdCKUkhY4k5Qy7SPkdk4NJ1ckkndgGgogTCxxx2Bx7rAhMqcA3uLnuTLaCYjiwLfJ5CB0KsuKG2KMRuiMNZnwyAu4Nx85BwjIWYinnn8IicIKd9KkXENBC4HdzcwP3QxqbATU3A@AhEwB3NmhwWn0@2uI@RyS8upiAE7XEFnYI8rKDU8oUmAgn3z8dhYMZiuh@2JRc5IMuDh6CJXomF80z6IhRnWrAaLLQM4vCdOiKOQ9wHdGlM@tRUZNKJOXHWM@yG32S9bdnjsSMxwTVs2VakdfW1LAT1qgg6B30pOmXbDt2iivEGA7K@qbdY2kFFGCAIFwEYJHRdDgDiTG1Aq6L8zeElXMpkBY3OIxsIG71Nw1IOrpjjA2L1aKQu6h4kyKowwy9PNCoWlV3qUOh1@SGosEh57NNmZJBbVXFYi8OMANZNIhMrLL1GCeMwjLwP0anTs2dqTUIKGDmNxWic1PuDu2gjNQ61wyb0HBV1RbstAhNoXlAfR3Ob6Y2E5bBhyVDylsZHyzTxeWVR69BxJtAKfCSC8XZadT5G5UqkZR1eINiF/XCPDIcW3CjVKEM4ivgMJYqQyE20GFv8z1/mH//@/Pvr6z8 "Jelly – Try It Online")
No, I did not force TIO to execute that many bytes of code :) I hardcoded the value in. See the TIO link for the exact number of characters.
```
³!¤“...”LbỌ - Main niladic link
“...” - The real meat of the program. a very long string of characters. See the TIO link for the exact number of characters
L - Takes the length of the string
³!¤ b - Convert from base 10 to base 100!
Ọ - Turn the array into a string
```
Irreducible because:
* If you omit a character in the literal, the resultant number will be wrong
* If you change ³!¤, the base conversion will be incorrect
* If you omit any other byte, the program will either not print "Hello, World!" or do strange things
Funny that Jelly is a golfing language, and yet you can make such a long irreducible program for the simplest of things.
EDIT: Thanks @Bubbler for fixing my output format and adding some bytes
EDIT: Fixed the score
[Answer]
# [naz](https://github.com/sporeball/naz), ~~2308~~ 4548 bytes
```
1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s2x1v1n1v1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1o0m2x1v1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s2x1v1n1v1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1o0m2x1v1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s2x1v1n1v1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1o0m2x1v1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s2x1v1n1v1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1o0m2x1v1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s2x1v1n1v1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1o0m2x1v1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s2x1v1n1v1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1o0m2x1v1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s2x1v1n1v1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1o0m2x1v1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s2x1v1n1v1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1o0m2x1v1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s2x1v1n1v1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1o0m2x1v1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s2x1v1n1v1s1s1s1s1s1s1s1s1s1s1s1s1s1o0m2x1v1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s2x1v1n1v1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1o0m2x1v1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s2x1v1n1v1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1o0m2x1v1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s2x1v1n1v1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1o
```
**Explanation**
[This commit](https://github.com/sporeball/naz/commit/ff170ff3647f53c4b0f0b82755d42a467b6a498e) adds the `n` command to naz, which negates the value of a specific variable.
For each character in the string `Hello, World!`, the above program follows the following steps:
* Subtract 1 from the register 127 times.
* Store the resulting value of -127 in variable 1.
* Negate variable 1, and set the register to the new value.
* Subtract 1 enough times to reach the ASCII value of the character, then output it.
* Multiply the register by 0 and store the resulting value of 0 in variable 1.
I *believe* this is irreducible because of the following (but I'd love to be proven wrong):
* Removing any one number or any one letter will create a broken instruction and throw an error.
* Removing any instance of `1s` will result in an incorrect character being output.
* Removing any instance of `1o` will result in a character being omitted from the output.
* Removing any instance of `0m` will eventually result in an incorrect or completely invalid output value.
* Removing any instance of `2x` will either result in an invalid output value or allow the value in the register to go out of bounds, unless you remove the first instance, in which case an error will be thrown because the variable will be used before its value is first declared.
* Removing any instance of `1v` will throw the error `improper use of opcode 2`.
* Removing any instance of `1n` will allow the value in the register to go out of bounds.
The previous 2308-byte solution:
```
1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1o0m1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1o0m1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1o0m1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1o0m1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1o0m1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1o0m1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1o0m1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1o0m1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1o0m1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1o0m1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1o0m1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1o0m1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1o
```
[Answer]
# BrainF\*\*\*, 2992 bytes
```
-{184}.-{227}.-{249}>+{254}[+<.>]<-{253}.+{189}.+{244}.-{201}.-{232}.-{253}.+{250}.+{248}.+{189}.
```
Where `w{n}` means `w` repeated `n` times. BF is cyclical mod 256, so instead of going "up" 72 to get to "H", you can go "down" 184 to get there. `-{227}` just adds 29 to get to "e", and so on with these basic building blocks, except for the double "ll". I made a counter set to -2 (254), then add 1 both times to run the output (`.`) twice.
Full program:
```
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------.-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------.--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------->++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++[+<.>]<-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------.+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------.----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------.-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------.++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.
```
[Try It Online!](https://tio.run/##SypKzMxLK03O/v9fd4gCPd3hD0aCH7EDO@0RDaK1bfTsYm10RzLQG9IxqDcSk63eaMk76tHRMma0gBr1OM1c//8/AA)
] |
[Question]
[
[Jelly](https://github.com/DennisMitchell/jelly) is a [tacit](https://en.wikipedia.org/wiki/Tacit_programming), golf-oriented programming language by our very own [Dennis](https://codegolf.stackexchange.com/users/12012/dennis). It’s popping up in answers here more and more often, beating other golf-y languages like Pyth and CJam, both by using [its own code page](https://github.com/DennisMitchell/jelly/wiki/Code-page) and its powerful *chain* system to succinctly express programs.
Let’s collect some useful tips for golfing in Jelly. (As always, one tip per answer, please!)
[Answer]
# String compression
>
> If you're looking for a more optimized/automatic string compressor, try [**this one**](https://codegolf.stackexchange.com/a/151721/39328).
>
>
>
[Try it online!](https://tio.run/##hVRLbtswEF03p5gGKEQ1jiI5SIoo8aIICjTrAvXCEQqaomwaNCmQDJSoaNGD9BzddJej9CLukHYtOQ5SGbCt@Ty@eTOc@sHNtTpdVUYvYcGlfACxrLVxwHTJv9R0xgdQCuaEVtQ8rJik1sK1XtaGW0uksC7ODwCfklfA5tRQ5rghlstqAGzj849ANwgF0a26vX9XPf6KOp9/NIzg4mxr4hITIvxcjTAPv6LvzyRoUxIWH58Oe3mW78YZKiyHz1Te8Q/GaEMYHMEhCAuKCzfnBmojlKNTyeH9p@ubG1DaAAUpFK84L5PDeIvny4KjEUwkXU5LCm0Op2/bo3QAneHiHC26uATD3Z1RIWerkHV41mwjj@3JU@GZQR@bh4yk05J15z8H2XVnA9v0YJ1FlaZay@CL@91oJnlWwGjkVc6hwbhmkuXIO@Qo7fDPNr5kDo3dUYmd@yFBGMkVaWK4gvOgfT9GajXbIoyxXoYYpBlAGgcCvlwPHPJI4JPYhtaMWk5i7FIgNIBsh/c4cFun5vvdbTbdVVEIwgb3KfV6WSEZLBV1t@wSFp7a0OMjy0AoCyQxIryllyC8AswlQpX8noz/OxXD/lR4w6LwiNUa8ElwVrwEN8QInFHSiR33wb0ZmcU@qnhxWGZ6PQjdhLDNXeYlljfB9rf4m@7MZRXmEtMmeX6cFXkIqUjbKdDMBd6edvfi@W638AaGZ@mOPWwCnLs0DyFP3R6ctHCM2wNOTvbcHd@E1jVXuAD@baoJw6ys2Lsu0Z8fP7@m3x5/RwmWs6SORFGy0EKRDmxdWhyvwjIg2w0XH7xKejcs@og7UkfeurnK0SB6GgNjbWS5E/Q6vKH6eMJf "Python 3 – Try It Online")
A compressed string looks like `“...»`, where the dots are a chunk of base-250-encoded data. The decompression algorithm is a bit complicated: the chunk is interpreted as a “mixed-base” integer, with `divmod` breaking off various parts of this integer and constructing a string out of them.
I’ve created a little Python 3 interface to compress Jelly strings:
```
import dictionary
code_page = '''¡¢£¤¥¦©¬®µ½¿€ÆÇÐÑ×ØŒÞßæçðıȷñ÷øœþ !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~¶°¹²³⁴⁵⁶⁷⁸⁹⁺⁻⁼⁽⁾ƁƇƊƑƓƘⱮƝƤƬƲȤɓƈɗƒɠɦƙɱɲƥʠɼʂƭʋȥẠḄḌẸḤỊḲḶṂṆỌṚṢṬỤṾẈỴẒȦḂĊḊĖḞĠḢİĿṀṄȮṖṘṠṪẆẊẎŻạḅḍẹḥịḳḷṃṇọṛṣṭụṿẉỵẓȧḃċḋėḟġḣŀṁṅȯṗṙṡṫẇẋẏż«»‘’“”'''
class Compress(list):
def character(self, c):
if c in '\n\x7f¶':
o = 95
elif ' ' <= c <= '~':
o = ord(c)-32
else:
raise ValueError(c + " is neither printable ASCII nor a linefeed.")
self += [lambda z: 3*z+0, lambda z: 96*z+o]; return self
def string(self, s):
for c in s: self.character(c)
return self
def dictionary(self, w):
ts = bool(self)
if w[:1] == ' ': w = w[1:]; ts = not ts
dct = dictionary.short if len(w) < 6 else dictionary.long
W, sc = (w, 0) if w in dct else (w[:1].swapcase() + w[1:], 1)
if W not in dct: raise ValueError(w + " isn't in the dictionary.")
f = ts or sc; j = (2 if sc else 1) if ts else 0; i = dct.index(W)
self += [lambda z: 3*z+2, lambda z: 3*z+j] if f else [lambda z: 3*z+1]
self += [lambda z: 2*z+int(len(w) < 6), lambda z: len(dct)*z+i]
return self
def go(self):
compressed = []; z = 0
for f in self[::-1]: z = f(z)
while z:
c = z % 250
if c == 0: c = 250
z = (z - c) // 250
compressed.append(code_page[c - 1])
return '“{0}»'.format(''.join(compressed[::-1]))
```
Use the compressor as follows.
```
print(Compress()
.dictionary('public')
.dictionary(' static')
.dictionary(' boolean')
.string(' is')
.dictionary('Power')
.string('Of')
.dictionary('Ten')
.string('(')
.dictionary('long')
.dictionary(' input')
.string(') {\n ')
.dictionary(' return')
.string('\n ')
.dictionary(' input')
.string(' ==')
.go())
```
`Compress` is a string builder:
* `.string(s)` will insert raw, printable ASCII characters into the string.
**(Each character costs about 0.827 compressed bytes.)**
* `.dictionary(w)` will look up a string in Jelly’s built-in dictionaries. You may begin the string with a single space, if you want one. If this needs to deviate from the normal string-adding behavior, or flip the capitalization of a dictionary word, it’ll add flags accordingly.
**(Costs about 1.997 bytes for short words, 2.433 bytes for long words; if there are flags, add 0.199 bytes.)**
[Answer]
>
> *This is part of what became the [Jelly wiki tutorial](https://github.com/DennisMitchell/jelly/wiki/Tutorial).*
>
>
>
# Chains
(This is sort of a follow-up to [**Tacit programming**](https://codegolf.stackexchange.com/a/70997/3852).)
How does Jelly evaluate a chain? As explained before, there are three cases to consider: whether this chain was called *niladically*, *monadically*, or *dyadically*.
---
## 1. Niladic chains
These are the easiest of the bunch. To evaluate a niladic chain that *starts* with a nilad, like `α f g h`, evaluate the monadic chain `f g h` at that nilad `α`. (Caveats: if the whole chain is empty, 0 is returned instead. If `α` *isn’t* a nilad, replace use `α=0` instead.)
For example, `4½` is just `½` evaluated at `4`, which is `2`.
---
## 2. Monadic chains
Monadic chains are broken down from left to right, until there are no links left to consider. Also, we’re passed some argument `ω` here. There are two questions to answer:
### What’s the starting value for this left-to-right evaluation?
* If our chain starts with a nilad `α`, and is followed by zero or more monads (like `½`), dyad-nilad pairs (like `+2`), and nilad-dyad pairs (like `4*`): we start by evaluating `α`, and then consider the rest of the chain.
* Otherwise, we start from the argument passed to this chain, `ω`, and consider the entire chain.
### How do we walk down the chain?
Let’s call `V` the current value – initially, it’s the value described above, but it gets update as we go through the chain – and denote
* nilads using digits,
* monads using lowercase letters,
* dyads using operator symbols `+`, `×`, `÷`.
Then the following patterns are matched against, from top to bottom:
```
┌───────────┬─────────┐
│ old chain │ new V │
╞═══════════╪═════════╡
│ + × 1 ... │ (V+ω)×1 │ *
│ + f ... │ V+f(ω) │
│ + 1 ... │ V+1 │
│ 1 + ... │ 1+V │
│ + ... │ V+ω │
│ f ... │ f(V) │
└───────────┴─────────┘
(* Only if `...` consists of monads, dyad-nilad pairs, and nilad-dyad pairs.)
```
>
> Let’s try this out on the chain `+²×`.
>
>
> * `+` isn’t a nilad, so we start out at `V = ω`.
> * Then, we chop off `+²`, matching the second pattern, and get `V = ω+ω²`.
> * Then, we chop off `×`, matching the fifth pattern, and get `V = (ω+ω²)×ω`.
> * The chain is now empty, so `(ω+ω²)×ω` is our final result.
>
>
>
---
## 3. Dyadic chains
These are basically like monadic chains, but this time, there are two arguments, `λ` (left) and `ρ` (right).
### What’s the starting value?
* If the chain starts with three dyads like `+ × %`, we start at `λ+ρ`, and consider the chain `× % ...` next.
* Otherwise, we start from `λ`, and consider the entire chain.
### How do we walk down the chain?
This time, the patterns are
```
┌───────────┬─────────┐
│ old chain │ new V │
╞═══════════╪═════════╡
│ + × 1 ... │ (V+ρ)×1 │ *
│ + × ... │ V+(λ×ρ) │
│ + 1 ... │ V+1 │
│ 1 + ... │ 1+V │
│ + ... │ V+ρ │
│ f ... │ f(V) │
└───────────┴─────────┘
(* Only if `...` consists of monads, dyad-nilad pairs, and nilad-dyad pairs.)
```
>
> Let’s try this out on the chain `+×÷½`.
>
>
> * The chain starts with three dyads, so we start at `V = λ+ρ`, and throw away the `+`.
> * Then, we chop off `×÷`, matching the second pattern, and get `V = (λ+ρ)×(λ÷ρ)`.
> * Then, we chop off `½`, matching the sixth pattern, and get `V = sqrt((λ+ρ)×(λ÷ρ))`.
> * The chain is now empty, so we’re done.
>
>
>
[Answer]
## Special-cased numeric values
Here are some special cases for Jelly's numerics parser:
* `-` evaluates to `-1`
* `.` evaluates to `0.5`
* `ȷ` evaluates to `1000` (`ȷ` is for scientific notation, e.g. `2ȷ6` is `2000000`)
* `ı` evalulates to `1j` (`ı` is for complex numbers, e.g. `2ı3` is `2+3j`)
It's also worth noting that something like `4ı` is actually `4+1j`, rather than `4`.
You can mix and match these, e.g.:
* `-.` is `-0.5` and `-ȷ` is `-1000`
* `-ı` is `-1+1j`, `ı-` is `-1j` and `-ı-` is `-1-1j`
* `.ȷ` is `500.0`
* `.ı` is `0.5+1j`, `ı.` is `0.5j` and `.ı.` is `0.5+0.5j`
* `ȷı` is `1000+1j`, `ıȷ` is `1000j` and `ȷıȷ` is `1000+1000j`
Note that `ȷ-` is `0.1`, but that doesn't save any bytes over `.1`. Then there's also the following, which can already be done in the corresponding number of bytes by using the builtin variable for 10 (`⁵`), but might be useful in the rare case that the builtin is unavailable or to save on needing to use `¤`:
* `ȷ.` is `sqrt(10) ~ 3.162277`, `.ȷ.` is `sqrt(10)/2 ~ 1.5811` and `ȷ-.` is `1/sqrt(10) ~ 0.31162`
[Answer]
# [Optimal string compressor](https://tio.run/##jVTNbttGED5LTzGND9yNKUGSkRSVw0MR9OBeW9QHRQhW5EhahdwldleSpSBBHqR5jVx6y6PkRdyZJSWq9qWwYAxn5@ebb37qQ1hbc/O4dLaCDZblAXRVWxcgtwW@r9UKUyh0HrQ1yh0er0hvfFAmDEHgQ15uvd6h7KMp3pdoIIMJXEOlHgR9ib2EpXWwB20uggxLa1YSrsBYMIgFBBuj6gLdpZlfM44F5mrrEexip@3Wl4cUdEg8xFd0/f4V3JncoSIbXC51rtHkB9hrKmwbuJoSKzRBmxUoCE4jCMLkwxq8rnSpnOw/S5rBx90UdESvU9hxAWi2FToVUDw1l5/6T6qD/x8hmlOEfl4q7@GtrWqH3otS@yCn/V6BS8jXyqmcqhXHFHLW9jRpOWbyzrx7@Hn5/VvC2p6lxL@8IglLskjo701GhvQv@dxZWFeIXA5uJtHQY3xwShOFf6lyi785Z53IqZMvQHtqEpFJvamdNkEtSoRf/3h7d0f9c0RpqQ0uqY3DF5LCHBnA65fHa9t@3JA8Itlh2DoDx35TUscA17RPKZjBqg6HWF3w5HnSNNXuZ9PxHLKMi5rSSGWkGU/nt9DaBhLIssi5e88aSgHagXwDr4FrfjqQ5Hufgs/JWxCckWSfZnIpZPQQEcPQ71Wd07gJSQRFECmMZYPyPiJpnKbwjNJ9S6lJohGxegkjErgkAFQSj2h@CxuGM2EohCyCGEdgZBG/Rrc0Yxlnm93P@y3lXClpJDGvW9WEZRNER0ILeBl7f2rU5vLjP9NxUo6ft3JlxTF2LW9nl1Y6g9mcNPu1pmk5NhFodGNrdpUtxBEGME5h8mrEl@BP9YGOhza@1rQfRAfEg/Q7HyTa9YXeILG0Q1jwmtOx2KHzbKbKlXU0nRVn6PIPVV3TSRLnIzbL57JDnvz48vfH0afv/yRD2s9KBZEkw43VRnQhZtPpYDyX5NVUaeugK1UKH1wstqi5yNEcXsLgM9PKD9w/XnhurlNmheL0AoNxGn/Rmbxnmqb5vO7DbsX5icZkTFNFjmTGUWPYTReWqKsIbux0TcH5xrQ3WDYZesEdGuGcjD2inHZ5L/aQn643p7TTRtbwU0bLEDH06OBjHS4Guk1Q0@ViqWOYU81Y1VL948vXM9dMR8pvZxA0QZR8NI9qSvoBDxlX8hgvjjjbnXpgqbliJId09QshpXzcrgL64Mvt6l8 "Python 3 – Try It Online")
Recently I [asked](https://chat.stackexchange.com/transcript/240?m=41927065#41927065) *[Erik the Outgolfer](https://codegolf.stackexchange.com/users/41024/erik-the-outgolfer)* to add the [optimized string compressor](https://codegolf.stackexchange.com/a/145327) to [JHT references page](https://golfingsuccess.github.io/jelly-hypertraining/help-stuff.html), but they [said](https://chat.stackexchange.com/transcript/message/41928771#41928771) that
>
> sorry, but that compressor doesn't seem to be fully implemented
>
> it says `“ugtestslug”` is the shortest possible for `ugtestslug`, while `“#ṀȮụḄPƇ»` also does the job
>
>
>
So I decide to implement the optimal string compressor.
Simple approach, but guarantee to find the smallest possible value (and hence byte count)
Take input from `stdin`, output to `stdout`. Just like the original compressor, `¶` or (literal newline character) can be entered as newline.
Trying to run it with a lot of punctuation (for example, input `¶-----¶`) will output the uncompressed string.
**Of course, a lot of credit for this goes to [Lynn](https://codegolf.stackexchange.com/users/3852/lynn) for creating [the original compressor](https://codegolf.stackexchange.com/a/70932).**
[Answer]
# Optimised string compressor
[Try it online!](https://tio.run/##rVjbbttGEH22vmKTF5KxJEhykyJ09GCkaRGgSICkSB4Y1lhRS3kd3kBSluUgRT@k35GXvuVT@iPuzOwudynJuRSVAV1m53rmskNX2/aiLE5ub2VelXXLmm0zMF/bWhYr80u2om7LMmsGg7Quc3YpsmzL9GFSLsV5xVdiyJYyaWVZ8Ho7GCQZbxr2tMyrWjSNn8mmDcIBg9dSpCy54DVPQK3fiCwdskSf4UvCMZMF894V765/TD9/8uwZvko2Z48fdiSRgYAHf0/mIAdv3h8HBMp66SfB6GTmyDWiz1dz2Qj2hmdr8ayuy9pP2DG7z2TDCiHbC1GzClBp@SIT7Oz10@fPWVHWjLNMFiIVYjm@H3T6MCx2PGdRxvPFkrObkJ08uDmeDJklPH4ElDI@ZbVo13VBMh1CKgMansaBJwWbhE8TksTYYplY@4dU2vRotRtHbdsASgtIMp0FbjY2UTiN2XyOKIdsA3ybaBqC3yRTlC186fiXSQtEa2rcXFAJpSwThb8J2BP2iLB3ebISis1oeAvxJqDD3wzZJCAHMFxUTHI@@TNuNrxKeCP8ALJEDg3ZtOf3W/JNiYb72d3o7BYeMUGCXZecXKbgDIQKuDfJKbtE12aoH7wkh6bkJHDQr8kpk4hA0o5lsRTX/tuvVsXMrQokXMaoMVUKd5in8ZfUzYADatS3YAeuciSDZwFyxV8sllWpCsFWSKJ7WSwhvAjSvygBRyyHnzn4ecpu4OukV6cp1SmoicJwNI1DYkn9G4vI5kJCN930G/EGBgIV0VVeLn34NXs4CXocgI62zoslMN8DyyF8juZsuuvYrmCCpUzcc1TssP9Wr/vcNuQxrypRwAwx0y4CY2wa73Wc98@ff32YfPz8tzcGBHLe@p43vixl4VtlCo0gGAwQaRyp5wus5KVcybYZMvwBwB9BIsUKxg7CeoR4EgNVNHECi8ODUuwBM4RjxTQ40o5purLZwEi2/qCtpejl1/Nc89bFqANgnErEA4YPNuBUzSX4he5ZVbFO3pFKtFbpOD5kkGNhs92RTwJkSvUxZgx@W6nksNTjRyjWjwY6xEkbyh2zk1kMfOoOAP4046tznChd0XTEiidkyNV4TwHU829GiqyDKH1XWH2DxAkqp84JWf3dnk16wauZuq98Rsphkp3bSYbjamfUDvfmcxDRR9yzQuPrgBUcIn0bAdndwCWLo7J3FJGWWIPVha3A0hL4EU12RzoSYar3JBGWnihe/Ir3UNoVXTeAe6i6oKrLBJcTXtd8iyWVL@AqV1YaasB0h4i2C4GzIvI8dA2rXmQix6onNaH2F7iikb02yWdDA89QBmldBeKhGTJ4iIhqx@GkC4JsKO@x2cCtTLaQmnO1L6iyQ9ehO3nW@ek2Z8ccqgYzdEUcV@siadcc0wfIaiJ0byss@qS8G4k4Ak5Zj@Z5QEnKopXFGnuJDk3sKDDoIjJJIBbtvwqwFlfnYD73MY0YU3KxLt43dPsMdBq6BTNQQUqMpObFSqgrECVR9KitVWoQZmcRoiqTYUwFrPSbGHpHi1rw9zgxrhNRtaTJhkcgoijSDygJ8V1vA@oYqj0gxV1Imk43Q0cHNjjC3dmR65BTJIXVf8NJXIkausHfBeyriIXyTsTM0bcjdiBvNlpypTco1EzYt2zhVI3Xww3v20HXbfJAcXXt1j9xbwnNQHr14V4qFmuc@vAoNeb16iqCZJ69@uWNS5qB/@CAYsWbZDSi7zgkNG9EBGgWhgS8nJVadTVpfwyRtpYBgti0S@pvkgIOelzxvZc1LAI4DfQr9IYQZAXPXsgfAKCAzpABjnN85io8iEupmiuVY@DOoPd9710LsjDPHvwAPGacljXVmi2xITv8XQ8iOWRWFN0VxToXNW@F76iknCDKqju6WUceDdVqH@jqofIARcRuJrAhfsdcc0Ia6wcwUwTOpDaN0WPf6RB1yzu1Ty5JWMj1noBqZJ7TetWrNs3Ki63fbivhXwd4h2DN0Yp1Tc8qSjSg7ZeuY0Owi4hSQyr0KbaT0dXxHAjZLKyOWHCI3QnZsE7j4C7j068YP6BtEgff4ebUumlz9S2SRsyV@kIhHB3BOxal9@Ej9JJZ8yPvZdXKXOLqQS/slNeiosJman1A0ovSpE9xxZEamGYkmPJ1V3TwAp7HdKcGth0/f0KN2LEILXWGCkB1fuM2GmnYqWQ9ICCOn8@e//rspzF7JZp11gpsHBtaE5iBcadPGkOnf8HLvLxyW7o/MszotuPBIK3G0mFuerz6aD0zrC56OqqzLLP/Z2rU2HM0RqNZ3GGiRV6UxcjZIPdFVH1r7te4MgvoS2eu5lBWOa98/cjNQ9UEPLg3h@ioXzlZxf8c9ZQDxu/Fdg7dHDg3lTb11HHq/zalTOjpP8cXFtTt7a2@l275IqEw2wvZ6MH5Lw "Python 3 – Try It Online")
[Lynn's post](https://codegolf.stackexchange.com/a/70932/66833) details what compressed strings are exactly, along with having a compressor that will produce these compressed strings. However, while tinkering around with a program in Jelly, I found it tiring to have to combine `.dictionary` and `.string` along with the correct placements of spaces and so on and so forth, in order to achieve the shortest possible string.
Therefore I decided to create an extension to Lynn's script that would take user input, and find the shortest way it can be compressed without the user having to do any work. The script is quite long, and so I've added in a TIO link, rather than the code itself.
The way the program works is by compressing using 3 different methods and determining which is shortest:
1. Method 1 simply encodes each byte of the input at a time, which tends to produce the longest result, as compared to the others. Even when the input is very short, it still manages to create rather long alternatives. For example, the shortest way that `test` can be compressed is `“¡ḌY»`, whereas this method returns `“¡⁷ƑKʂ»` (2 bytes longer). As a general rule, this only works if the string is less than 4 characters long
2. The second method breaks the string into words and punctuation, as the two are added to the compressor in different ways. Words that are part of the dictionary are added with the `.dictionary` method of Lynn's code, which compresses them more than if they were simply added by code points. Punctuation however has to be added by code point as, unfortunately, they aren't part of the dictionary.
Punctuation includes spaces, which is where method number 3 comes into play, but first and evaluation of method 2: let's compare methods one and two compressing the string `Hello, World!` (contains words, punctuation and spaces, so is perfect). Compressing character by character results in the final string of `“ŒCdẉa÷¹ṂȤƓ(Ẋ)»` (15 bytes long), which, as it turns out, is longer than the easier way to output Hello, World!: `“Hello, World!`. Now lets take a look at method two. This produces the compressed string `“Ọƥ⁷Ƭė3⁶»` which weighs in at 9 bytes, a great improvement over the old one. However, the shortest Hello, World! program in Jelly is [8 bytes](https://codegolf.stackexchange.com/a/66399/66833), so something can be improved
3. Here comes method 3, making it even shorter. As expected, output for Hello, World is, of course, `“3ḅaė;œ»` which is the shortest possible program. So what does method 3 do, that method 2 doesn't? Method 3 combines lone spaces into leading spaces, which the Jelly decompressor has a flag for. In the code for both the compressor and the decompressor, you can see code like `if flag_space: word = ' ' + word`, showing that leading spaces are a) supported and b) byte-saving. Therefore, the string splitter from method two is adapted so that spaces by themselves are combined into the string directly after is, to create leading strings. This means that `Hello, World!` is parsed as `["Hello", ",", " World", "!"]`, which when compressed is only 6 bytes (8 when including delimiters). This is almost always the shortest method of compression, excluding the "extension" I added,
This is the bulk of the program, but there are a few more options that help it compress data even more.
* The program checks whether or not each compressed version is correct, by using Dennis' [sss](https://github.com/DennisMitchell/jelly/blob/master/jelly.py#L931-L955) decompressor that Jelly uses (go straight to the source)
* You can see all different compressed strings by making the first command line argument `--debug`, which, rather than simply showing the shortest compressed string, shows all 3 along with a "This is the shortest" copy
* The program handles "non-words"
## Non-words
I started work on Lynn's compressor after seeing [this](https://chat.stackexchange.com/transcript/message/40529674#40529674) message, took a crack at it and got frustrated at the fact that I couldn't find the shortest way to compress it (it's 29 or 32 bytes for the record). However, while testing my improvements, I found that words such as `knowns` aren't in Jelly's dictionary. Therefore, I set out to find a way to compress these "non-words" in the shortest Jelly code possible.
I created a function (`trim`) that splits the string as a point where at least one of the parts of the string are words. For example `knowns` would be split into `["known", "s"]` and have the program add the first word via a dictionary add (`.dictionary`) and the second part of the word via a `.string` call. But this still leaves two edge cases: strings which have no words in them (such as `ajdl`) and non-words which have words at the end, such as `abctest`, which wouldn't get split by the `trim` function.
As there is no way of finding words in a string which has no words in it, the simplest and shortest way to handle these is by adding them in character by character via a `.string` call. So `ajdl` would get added by `.string('ajdl')`. Whereas non-words which end with recognised words, essentially implements the trimmer but in reverse, and applying `.dictionary` and `.string` the other way round to the forwards trimmer.
As it turns out, trimming the string, either from the start or the end is, of course, shorter than adding each character to the compressor, as demonstrated by an input of `abctest this string`, which produces a debug output of
```
Original : abctest this string
Optimised : “¡J+v(p⁸ụƘ$,»
Seperate spaces : “Ç⁴ṭḍµḄ7oeṂdḷp»
No trimmer : “¤ɦ?Ɓ¢#fḲOạ⁾¶ɼȥƬ»
All characters : “µẓþ"Y7_ḣṗḢ))9Þ⁴⁺Ẉ²)ɱ»
Non-compressed : “abctest this string
Shortest : “¡J+v(p⁸ụƘ$,»
=====
```
The different between the optimal output (which uses the trimmer) and the one which doesn't is a whopping (for Jelly) 4 bytes. Finally, there are occasions where the string itself is shorter than any compressed version, which has now been factored in.
**Of course, a lot of credit for this goes to Lynn for creating the original compressor**
[Answer]
You can use superscript three to nine (`³⁴⁵⁶⁷⁸⁹`) to golf some usually used
values, but this depends on the amount of command line arguments, and in case of links, on the arguments of the links.
* `³` returns 100, and works only if there's no input.
* `⁴` returns 16, and works only if there's at most one input.
* `⁵` returns 10, and works only if there's at most two inputs.
* `⁶` returns a space if there's at most three inputs.
* `⁷` returns a new line if there's at most four inputs.
If there are five inputs, however, you're out of luck.
Recently, a new version of the language lowered the value of `³` to 100, and introduced some new atoms that return values or (for links) their arguments.
* `⁸` returns a blank list everywhere except links which have a left argument passed to them.
* `⁹` returns 256 everywhere except links which have a right argument passed to them.
If you're in a link, and have arguments from both sides passed to it, however, you're out of luck.
[Answer]
# Abuse string bugs
*Credits go to [Adnan](https://codegolf.stackexchange.com/users/34388/adnan) for taking advantage of this first in [Write a program to elasticize strings](https://codegolf.stackexchange.com/a/83389/12012)*.
Jelly is supposed to get character arithmetic one day, but until that happens, we can take advantage of the fact that Python overloads most arithmetic operators and that Jelly does no type checking.
For example
```
“abcd”Ḥ
```
isn't supposed to do anything useful right now, but since `Ḥ` (unhalve) is implemented as
```
lambda z: z * 2
```
and arithmetic atoms vectorize at depth **0** (i.e., they operate on numbers or characters), the above Jelly code yields
```
['aa', 'bb', 'cc', 'dd']
```
Careful that this produces actual Python strings (a type Jelly isn't supposed to have), so this won't be usable in all situations.
Likewise, `+/` can be useful to concatenate strings, with the same caveats.
[Answer]
>
> *This is part of what became the [Jelly wiki tutorial](https://github.com/DennisMitchell/jelly/wiki/Tutorial).*
>
>
>
# Multi-chain links
Remember when I wrote that you [define a link by making a chain of other links?](https://codegolf.stackexchange.com/a/70997/3852) I wasn’t telling the whole truth: in reality, it’s a two-layer process. A link is a *chain of chains*, and by default, the outer chain simply has unit length.
Consider this program:
```
C+H
```
That’s *complement plus half*. It takes an input value `n` and calculates `(1-n)+(n/2)`. Not too exciting, I know. But the structure is really like this:
[![structure 1](https://i.stack.imgur.com/r8LSq.png)](https://i.stack.imgur.com/r8LSq.png)
The link we wrote is, itself, actually a chain containing a single chain.
Suppose that we want to calculate `(1-n)+(1-n)(n/2)` instead. The dyadic chain `+×` would work: by the [chaining rules](https://codegolf.stackexchange.com/a/71001/3852), it calculates `λ+(λ×ρ)`, which looks a lot like what we need. However, simply replacing `+` by `+×` in our program won’t do: `C+×H` is a 1,2,2,1-chain – *complement, then add (the argument), then multiply by half* – computing `((1-n)+n)×(n/2)`.
We want Jelly to treat `+×` as a unit, and make a 1,2,1-chain of the sub-chains `C`, `+×`, and `H`. **Multi-chain links** let us do just that! To construct them, we use the **chain separators** `øµð`: in the image above, they would introduce a new blue rectangle, of arity 0, 1 and 2, respectively. In our case, we can group the chains the way we want by writing `Cð+×µH`:
[![enter image description here](https://i.stack.imgur.com/GWGS5.png)](https://i.stack.imgur.com/GWGS5.png)
There’s no way to nest these things even further. You’ll have to define multiple links, instead.
[Answer]
>
> *This is part of what became the [Jelly wiki tutorial](https://github.com/DennisMitchell/jelly/wiki/Tutorial).*
>
>
>
# Tacit programming
Jelly is a tacit programming language. This means you define links (functions) by composing existing links into a **chain**, without explicitly talking about the arguments involved. Which way the arguments “flow” through this composition is defined by the pattern the links are arranged in. An example of this will be given soon, but first we’ll need to introduce some concepts.
The **arity** of a link is a very crucial concept. All of the **atoms** – the built-ins, like `+` and `½` – have fixed arities. Links are sorted into three categories, depending on their arity:
>
> * **Nilads** take no arguments (arity 0); other than some I/O and stateful commands, they mostly represent constant values. For example, the literal `3` is a nilad.
> * **Monads** take one argument (arity 1). (There’s no connection to *functional programming* monads here.) For example, `½` (square root) is a monad.
> * **Dyads** take two arguments (arity 2): a left and a right argument. For example, `+` is a dyad.
>
>
> (Using adjectives, we say that a link is *niladic*, *monadic*, or *dyadic*.)
>
>
>
So what’s the arity of the links we define when writing a program? By default, they are *variadic* – that is, it’s up to the *caller* to specify how many arguments to use, and in the case of the **main link**, it depends on how many arguments the program is passed.
As an example, `+½` is a chain of `+` (addition) and `½` (square root). As the respective arities of the elements of this chain are 2 and 1, we call it a **2,1-chain**. The interpreter has specific rules for breaking down chains, based on their arities: those rules dictate that, given an input `n`, this new link computes `n + sqrt(n)`. (You can read `+½` as *“... plus its square root.”*)
Jelly programming, then, is essentially the art of learning these rules well, and composing clever chains that get the job done, *tacitly*.
[Answer]
# Integer compression
String compression is useful when producing text in English, but if you need to compress other sorts of data, it's fairly ineffective. As such, most of the time you want to store a large fixed constant in your program, it's best to store it as an integer.
Now that Jelly has its own code page as a constant, the compression algorithm for integers is most simply expressed in Jelly itself:
```
ḃ250ịØJ”“;;”’ṄV
```
[Try it online!](https://tio.run/##y0rNyan8///hjmYjU4OHu7sPz/B61DD3UcMca2swPfPhzpaw////GxoZm5iamVtYGiBYAA "Jelly – Try It Online")
(The above program also contains a check to show the value that the integer decompresses to.)
In addition to just using an integer as an integer, you can also use it to create a string via doing base conversion on it, then indexing into an alphabet of characters. The `ṃ` atom automates this process, and is fairly useful because it can describe the entire process of decompression (other than the alphabet being decompressed into) in a single byte.
[Answer]
>
> *This is part of what became the [Jelly wiki tutorial](https://github.com/DennisMitchell/jelly/wiki/Tutorial).*
>
>
>
# Program structure
Each line in a Jelly program is a *link definition*. Links are basically functions. The bottom line represents “`main`”: it's the link that gets evaluated using the arguments passed on the command line.
All links but the last one, then, are function definitions: you can refer to them using [actors](https://github.com/DennisMitchell/jelly/blob/b322a9169bddc32cc4c6e18d6a293324619912dc/jelly.py#L853). For example, `ç` is *“the link above this one, as a binary operator (dyad)”*. Consider this [example program](http://jelly.tryitonline.net/#code=KwrDp8Ky&input=&args=Mw+NQ), which computes the square of the sum of its arguments:
```
+
ç²
```
This is sort of like the pseudocode:
```
define f:
the built-in link +
define main:
apply the dyad f
square the result
```
[Answer]
# If TMTOWTDI, pick the one that fits your chain.
One of the advantages of a tacit language is that you *usually* can get away without using variable references. However, this works only if the links in your chain have the right arities.
For example, the straightforward way of taking the sum of all arrays in a 2D array is
```
S€
```
which maps the sum atom over all elements of the array.
Now say you have a monadic chain that consists of the atom
```
*
```
which maps each **x** of a 2D array to **xx**. For example, for **A = [[1, 2], [3, 1], [2, 3]]**, calling the chain would yield **[[1, 4], [27, 1], [4, 27]]**.
Now, we want to take the sum of each pair. Unfortunately,
```
*S€
```
doesn't work since `*` doesn't act like a *hook* anymore (using **A** itself as right argument), but as a *fork*, meaning that `S€` gets applied to **A** first, and the result is the right argument of `*`.
Fixing this is easy enough:
```
*¹S€
*⁸S€
```
Both produce the desired result: `*¹` is a *fork* where `¹` is the identity function, and `*⁸` is an *atop*, where `⁸` is a reference to the chain's left argument (**A**).
However, there's a way to save a byte! The atop `ḅ1` (convert from unary to integer) also computes the sum of each array in **AA**, but unlike `S€`, `ḅ` is a *dyadic* link.
The chain
```
*ḅ1
```
returns **[5, 28, 31]** (as desired); since `ḅ` is dyadic, `*` hooks instead of forking
[Answer]
# Consider using `i` rather than `e`
* `e`: If **x** occurs in **y**, then **1**, else **0**
* `i`: Find the first index of element **y** in list **x**, or **0**
The key thing here is that `e` and `i` take arguments in opposite orders. This can be exploited in two main cases:
* The question allows you to return an inconsistent truthy value, and your answer works by generating a list and checking if the argument is in this list
For example, checking if a number is a Fibonacci number takes 5 bytes using `e`:
```
RÆḞe@
```
But only 4 using `i`, assuming any truthy value may be returned:
```
RÆḞi
```
* Using a filter quick (`Ƈ` or `Ðḟ`). Let’s say you have generated a list of lists and want to keep only those where the input is (or is not) contained in it. As `i` returns a truthy value if the right argument is in the left, you can set up a dyadic link `iƇ` to remove lists that don’t contain the left argument, saving a byte over `e@Ƈ`
Generally, this tip works best for answers that generate a list, then test the left argument for membership in some way, allowing you to avoid the `@` quick or using a “grouper” like `$` or `Ɗ`
[Answer]
# Use outer products to create useful integer matrices
*[Here](https://gist.github.com/dylannrees/5fa2603f709d44edac36675aa30dfd1d) is a gist I have created of this post with slightly nicer HTML table formatting.*
The outer product quick `þ` can be attached to dyads and causes the dyad to act on each pair of elements in its left and right arguments. It is shorthand for `€Ð€`. For example if we had the code `[1,2]+€Ð€[0,10]` we could shorten it to `[1,2]+þ[0,10]` and they would both yield `[[1,2],[11,12]]`. I will refer to a dyad with `þ` applied (such as `+þ`) as an outer product dyad.
When an integer is one of the arguments of an outer product dyad, Jelly takes the range of that number first then uses the result as the argument. Knowing this, the above example can be further shortened to `2+þ[0,10]`. This is true for both the left and right arguments of an outer product dyad.
Some outer product dyads when acting monadically on an integer yield certain integer matrices that can be useful in golfing (especially ASCII art challenges) but would take many bytes to otherwise construct. For example `=þ` when applied to an integer `n` yields an `n×n` identity matrix. [Try `=þ` online!](https://tio.run/##y0rNyan8/9/28D6uw@3u////NwUA)
Below is a table of dyads and the type of matrices they yield when turned into outer product dyads and acted monadically on an integer. Dyads listed in the same row will yield the same matrices. There are dyads I haven't included in the table like `&`, `|`, `%`, `w`, `ẇ` and `ḍ` that also produce integer matrices but their patterns are not as simple and would likely be useful in fewer situations. [Try `wþ` online!](https://tio.run/##y0rNyan8/7/88D6uw@3u////NzIAAA)
| Dyad | Resulting matrix | Example |
| --- | --- | --- |
| `=`, `⁼`, `i` or `ċ` | Identity matrix. | `1 0 0``0 1 0``0 0 1` |
| `>` | Elements above diagonal are `1`, all other elements are `0`. | `0 1 1``0 0 1``0 0 0` |
| `<` | Elements below diagonal are `1`, all other elements are `0`. | `0 0 0``1 0 0``1 1 0` |
| `n` or `⁻` | Diagonal elements are `0`, off diagonal elements are `1`. | `0 1 1``1 0 1``1 1 0` |
| `a`, `ị`, `ṛ` or `ȧ` | Row index of each element. | `1 1 1``2 2 2``3 3 3` |
| `o`, `ḷ` or `ȯ` | Column index of each element. | `1 2 3``1 2 3``1 2 3` |
| `_` | Main diagonal is `0`, upper diagonals are `1`, `2`..., lower diagonals are `-1`, `-2`... | `0 1 2``-1 0 1``-2-1 0` |
| `_@` | Main diagonal is `0`, upper diagonals are `-1`, `-2`, etc., lower diagonals are `1`, `2`, etc. The only dyad in this table that doesn't have a one byte alternative that results in a transposed matrix is `_`. | `0 -1-2``1 0 -1``2 1 0` |
| `ạ` | Main diagonal is `0`, upper and lower diagonals are `1`, `2`, `3`... | `0 1 2``1 0 1``2 1 0` |
| `+` | Row index plus column index. | `2 3 4``3 4 5``4 5 6` |
| `«` | Minimum of row and column indices. | `1 1 1``1 2 2``1 2 3` |
| `»` | Maximum of row and column indices. | `1 2 3``2 2 3``3 3 3` |
[Answer]
# Jelly IDE/Debugger
After struggling a lot with Jelly's codepage, parsing, error messages and debugging, I decided to build a IDE/debugger for Jelly. This has been in the works for a very long time, but I finally decided to finish most of the features.
>
> **Download:** <https://gitlab.com/PurkkaKoodari/jellyide>
>
>
>
Installation instructions are in the repo `README`. You may need to install the DejaVu Sans Mono font (included) to your system to allow Tkinter to find it.
### Features
#### Tkinter-based GUI
Run as `python -m jellyide [filename]`.
* Code editor
* UTF-8 and Jelly codepage support
* Code suggestion with keyword search (press Ctrl+Space)
* Windowed output console
* Jelly runs in a separate thread and can be killed/restarted
* **Notably missing:** command line arguments
#### Augmented Jelly CLI with most of the features
Run as `python -m jellyide.jelly [--opts] <jelly args...>`. Use `--help` for more instructions.
Supports debugging, nice stack traces and everything the Jelly CLI supports.
#### Code visualization (links, quicks, chains, arities)
Only in the GUI, determines the links used and visualizes how they are parsed and executed.
* Block colors indicate arity of link/chain
* Bunched-together blocks indicate chain execution steps (`+1`, `1+`, `+F` and so on)
[![example visualization](https://i.stack.imgur.com/E3Zay.png)](https://i.stack.imgur.com/E3Zay.png)
#### Step-by-step debugging
* Break/continue (via GUI or using Ctrl-C in CLI)
* Start program with stepping (via GUI or `--step` in CLI)
* Step to next entry/return of an atom/quick
* Step to return of current atom/quick
* Shows args or return value in console
```
--- PAUSED ---
Ḥç€
^^^
left arg: [1, 2, -1, -2]
right arg: 3
[s]tep, step to [r]eturn, [c]ontinue, [q]uit?
--- PAUSED ---
Ḥç€
^
arg: [1, 2, -1, -2]
[s]tep, step to [r]eturn, [c]ontinue, [q]uit?
--- PAUSED ---
Ḥç€
^
return: [2, 4, -2, -4]
[s]tep, [c]ontinue, [q]uit?
--- PAUSED ---
Ḥç€
^^
left arg: [2, 4, -2, -4]
right arg: 3
[s]tep, step to [r]eturn, [c]ontinue, [q]uit?
--- PAUSED ---
ç€
^
left arg: 2
right arg: 3
[s]tep, step to [r]eturn, [c]ontinue, [q]uit?
```
#### Error stack traces with Jelly code locations
I'll let the results speak for themselves. I'm sure you've seen Jelly's built-in error messages.
```
in Æs
,Æs
^^
arg: -2
in ,Æs$
,Æs$×
^^^^
arg: -2
in ,Æs$×
,Æs$×
^^^^^
left arg: -2
right arg: 3
in ç
ç€
^
left arg: -2
right arg: 3
in ç€
Ḥç€
^^
left arg: [2, 4, -2, -4]
right arg: 3
in Ḥç€
Ḥç€
^^^
left arg: [1, 2, -1, -2]
right arg: 3
ValueError: n must be a positive integer
```
[Answer]
There are several nonobvious ways to check properties of an argument using `Ƒ`. Below are a few. I left out plenty of uses of this quick (E.g. `AƑ`, `ŒuƑ`, `3Ƒ`) because they are already the most straightforward methods of achieving their behavior.
```
OƑ Is number?
ỌƑ Is character? (errors on negative numeric input)
ḂƑ Between 0 and 2? 0<=x<2 (python). <2aAƑƊ or of course ⁼Ḃ$ in Jelly.
ḞƑ Is integer?
UƑ Like `ŒḂ`, but checks if all sublists of depth 1 are palindromes.
ṠƑ Is one of -1, 0, 1? (e-r1¤$)
```
Feel free to edit this to add more interesting cases.
[Answer]
You may want to try an online editor [Jelly Balls](https://jellyballs.github.io) designed to easily build code in [Jelly Language](https://github.com/DennisMitchell/jellylanguage/wiki).
The features include:
* Command palette with all atoms and syntax characters organized by type
* Online parser recognizing literals and 2-byte atoms in the code
* Simplified in-browser Jelly interpreter to run your Jelly code on the webpage in javascript
* Direct links for transferring the code into TIO or another Jelly Balls session
* Automatic hints
* Optimised for mobile devices
### Give it a try: <https://jellyballs.github.io>
![Jelly Balls](https://jellyballs.github.io/images/palette.png)
* Detailed trace report showing arguments and results of every executed step
![Jelly Balls](https://jellyballs.github.io/images/tracereport.png)
* Code report showing description of every step
![Jelly Balls](https://jellyballs.github.io/images/ballreport.png)
* Recipes page with Jelly examples
![Jelly Balls](https://jellyballs.github.io/images/recipes.png)
* Interactive code page of 256 Jelly characters
![Jelly Balls](https://jellyballs.github.io/images/codepage.png)
[Answer]
# The various uses of `ị`
`ị`, the "index into" command has some extended capabilities beyond the standard index into command in most languages. For example:
| Command | Functionality | TIO |
| --- | --- | --- |
| `0ị` | Return the last element | [Try it online!](https://tio.run/##y0rNyan8/9/g4e7u////RxvqGOkY65jomOqYxQIA) |
| `Lị` | Return the last element | [Try it online!](https://tio.run/##y0rNyan8/9/n4e7u////RxvqGOkY65jomOqYxQIA) |
| `.ị` | Return the last and first elements | [Try it online!](https://tio.run/##y0rNyan8/1/v4e7u////R@sa6uga6ega6@ia6Oia6uiaxQIA) |
| `-.ị` | Return the last two elements | [Try it online!](https://tio.run/##y0rNyan8/19X7@Hu7v///0eb6hjoGOmYAElDHbNYAA) |
| `1.ị` | Return the first two elements | [Try it online!](https://tio.run/##y0rNyan8/99Q7@Hu7v///0eb6hjoGOmYAElDHbNYAA) |
| `ؽị` | Return the first two elements | [Try it online!](https://tio.run/##y0rNyan8///wjEN7H@7u/v//f7SpjoGOkY4JkDTUMYsFAA) |
| `JŻị` | Prepend the final element | [Try it online!](https://tio.run/##y0rNyan8/9/r6O6Hu7v///8fbapjoGOkYwIkDXXMYgE) |
| `JŻ‘ị` | Append the first element | [Try it online!](https://tio.run/##y0rNyan8/9/r6O5HDTMe7u7@//9/tKmOgY6RjgmQNNQxiwUA) |
| `Ø+ị` | Return the first and penultimate elements | [Try it online!](https://tio.run/##y0rNyan8///wDO2Hu7v///8fbapjoGOkYwIkDXXMYgE) |
| `L‘Hị` | Return the middle elements (2 if even length, else 1) | [Try it online!](https://tio.run/##y0rNyan8/9/nUcMMj4e7u////x9tqmOgY6RjAiQNdcxiAQ) |
| `L‘HịṢ` | Return the median of the array | [Try it online!](https://tio.run/##y0rNyan8/9/nUcMMj4e7ux/uXPT///9oUx0DHSMdEyBpqGMWCwA) |
| `Tị` | Remove all falsey elements | [Try it online!](https://tio.run/##y0rNyan8/z/k4e7u////R5vqGOgY6ZgASUMds1gA) |
| `¬Tị` | Remove all truthy elements | [Try it online!](https://tio.run/##y0rNyan8///QmpCHu7v///8fbapjoGOkYwIkDXXMYgE) |
| `Mị` | Remove all but the maximal elements | [Try it online!](https://tio.run/##y0rNyan8/9/34e7u////R5vqGOgY6ZgASUMd01gA) |
[Answer]
# Chain shapes
Here are all the possible chain shapes of nilads `1234`, monads `FGHJ` and dyads `+*%&` up to length 4.
Each is given with its monadic and dyadic behaviors in a non-tacit Ruby-like syntax, where `(x+y).F` applies/calls `F` on `x+y`.
For example, we wish to parse [`P+€Tọ`](https://codegolf.stackexchange.com/posts/240118/revisions). We know that `P` is a monad, `+€` is a dyad, `T` is a monad, and `ọ` is a dyad. So we look up `F+G*` in the below table and see that it's `((a.F+a.G)*a)`, and we can understand the program as `((a.Product +€ a.Truthy) ọrder a)`.
```
Code Monadic (arg=a) Dyadic (args=x,y)
==================================================
1 1 1
F a.F x.F
+ (a+a) (x+y)
1+ (1+a) (1+x)
FG a.F.G x.F.G
F+ (a.F+a) (x.F+y)
+1 (a+1) (x+1)
+F (a+a.F) (x+y).F
+* ((a+a)*a) (x+(x*y))
1+F (1+a).F (1+x).F
1+* ((1+a)*a) ((1+x)*y)
F1+ (1+a.F) (1+x.F)
FGH a.F.G.H x.F.G.H
FG+ (a.F.G+a) (x.F.G+y)
F+1 (a.F+1) (x.F+1)
F+G (a.F+a.G) (x.F+y).G
F+* ((a.F+a)*a) (x.F+(x*y))
+1F (a+1).F (x+1).F
+1* ((a+1)*a) ((x+1)*y)
+FG (a+a.F).G (x+y).F.G
+F* ((a+a.F)*a) ((x+y).F*y)
+*1 ((a+a)*1) ((x+y)*1)
+*F ((a+a)*a.F) (x+(x*y)).F
+*% (((a+a)*a)%a) ((x+y)*(x%y))
1+2* (2*(1+a)) (2*(1+x))
1+FG (1+a).F.G (1+x).F.G
1+F* ((1+a).F*a) ((1+x).F*y)
1+*2 ((1+a)*2) ((1+x)*2)
1+*F ((1+a)*a.F) ((1+x)*y).F
1+*% (((1+a)*a)%a) ((1+x)*(x%y))
F1+G (1+a.F).G (1+x.F).G
F1+* ((1+a.F)*a) ((1+x.F)*y)
FG1+ (1+a.F.G) (1+x.F.G)
FGHJ a.F.G.H.J x.F.G.H.J
FGH+ (a.F.G.H+a) (x.F.G.H+y)
FG+1 (a.F.G+1) (x.F.G+1)
FG+H (a.F.G+a.H) (x.F.G+y).H
FG+* ((a.F.G+a)*a) (x.F.G+(x*y))
F+1G (a.F+1).G (x.F+1).G
F+1* ((a.F+1)*a) ((x.F+1)*y)
F+GH (a.F+a.G).H (x.F+y).G.H
F+G* ((a.F+a.G)*a) ((x.F+y).G*y)
F+*1 ((a.F+a)*1) ((x.F+y)*1)
F+*G ((a.F+a)*a.G) (x.F+(x*y)).G
F+*% (((a.F+a)*a)%a) ((x.F+(x*y))%y)
+12* (2*(a+1)) (2*(x+1))
+1FG (a+1).F.G (x+1).F.G
+1F* ((a+1).F*a) ((x+1).F*y)
+1*2 ((a+1)*2) ((x+1)*2)
+1*F ((a+1)*a.F) ((x+1)*y).F
+1*% (((a+1)*a)%a) ((x+1)*(x%y))
+F1* (1*(a+a.F)) (1*(x+y).F)
+FGH (a+a.F).G.H (x+y).F.G.H
+FG* ((a+a.F).G*a) ((x+y).F.G*y)
+F*1 ((a+a.F)*1) ((x+y).F*1)
+F*G ((a+a.F)*a.G) ((x+y).F*y).G
+F*% (((a+a.F)*a)%a) ((x+y).F*(x%y))
+*1F ((a+a)*1).F ((x+y)*1).F
+*1% (((a+a)*1)%a) (1%(x+(x*y)))
+*FG ((a+a)*a.F).G (x+(x*y)).F.G
+*F% (((a+a)*a.F)%a) ((x+(x*y)).F%y)
+*%1 (((a+a)*a)%1) (((x+y)*y)%1)
+*%F (((a+a)*a)%a.F) ((x+y)*(x%y)).F
+*%& ((((a+a)*a)%a)&a) (((x+y)*(x%y))&y)
```
The table demonstrates how the same program can parse very differently depending on the number of arguments. The following program has a `*1` step in it when parsed monadically, but `1%` when parsed dyadically:
```
+*1% (((a+a)*1)%a) (1%(x+(x*y)))
```
[Answer]
# List commands and literals
If you attempt to use many of the **non-vectorizing list commands** on a **literal** `n` or a **list of literals** `z`, the list command will first convert to a list of some sort and then carry out the command on that list.
These commands appear use calls to the `iterable` function in [jelly.py](https://github.com/DennisMitchell/jelly/blob/master/jelly.py).
```
def iterable(argument, make_copy = False, make_digits = False, make_range = False):
the_type = type(argument)
if the_type == list:
return copy.deepcopy(argument) if make_copy else argument
if the_type != str and make_digits:
return to_base(argument, 10)
if the_type != str and make_range:
return list(range(1, int(argument) + 1))
return [argument]
```
Here are some incomplete lists of what those list commands will do.
**Wraps in a list**
The simplest return from `iterable` to wrap the argument in a list, and return that to be processed by the function. This happens if the argument is not already a list, is a string, and `iterable`'s arguments don't call for other methods.
```
-------------------------------------------------------------------------------
| Command | Description | Process | Effect |
-------------------------------------------------------------------------------
| F | Flattens a list | 4953F -> [4953]F -> [4953] | Same as W |
-------------------------------------------------------------------------------
| G | Format a list | 4953G -> [4953]G -> [4953] | Same as W |
| | as a grid | | |
-------------------------------------------------------------------------------
| I | Increments | 4953I -> [4953]I -> <nothing> | Empty list |
-------------------------------------------------------------------------------
| S | Sums a list | 4953S -> [4953]S -> 4953 | Same as ¹ |
-------------------------------------------------------------------------------
| Ṭ | Boolean array, | 4Ṭ -> [4]Ṭ -> [0, 0, 0, 1] | n-1 zeroes, |
| | 1s at indices | | 1 at end |
-------------------------------------------------------------------------------
| Ụ | Sort indices by | 4Ụ -> [4]Ụ -> [1] | Yields [1] |
| | by their values | | |
-------------------------------------------------------------------------------
| Ė | Enumerate list | 4Ė -> [4]Ė -> [[1, 4]] | Yields [[1, n]] |
-------------------------------------------------------------------------------
| Ġ | Group indices | 4Ġ -> [4]Ġ -> [[1]] | Yields [[1]] |
| | by values | | |
-------------------------------------------------------------------------------
| Œr | Run-length | 4Œr -> [4]Œr -> [[4, 1]] | Yields [[n, 1]] |
| | encode a list | | |
-------------------------------------------------------------------------------
```
**Convert to base 10**
The functions here call `iterable` to converts to a number to a list of its digits `D`, and then run on those digits.
```
-------------------------------------------------------------------------
| Command | Description | Process | Effect |
-------------------------------------------------------------------------
| Q | Unique elements | 299Q -> [2, 9, 9]Q -> [2, 9] | Unique |
| | ordered by | | digits |
| | appearance | | of n |
-------------------------------------------------------------------------
| Ṛ | Non-vectorized | 4953Ṣ -> [4, 9, 5, 3]Ṛ | Reverses D |
| | reverse | -> [3, 5, 4, 9] | |
-------------------------------------------------------------------------
| Ṣ | Sort a list | 4953Ṣ -> [4, 9, 5, 3]Ṣ | Sorts D |
| | | -> [3, 4, 5, 9] | |
-------------------------------------------------------------------------
```
**Convert to list with range**
The functions here convert a number to the range `R = [1 ... n]`, and then run on that range.
```
-----------------------------------------------------------------------------------------
| Command | Description | Process | Effect |
-----------------------------------------------------------------------------------------
| X | Random element | 4R -> [1 ... 4]X -> 2 | Random element |
| | | | of R |
| | | | |
-----------------------------------------------------------------------------------------
| Ḋ | Dequeue from list | 4R -> [1 ... 4]Ḋ -> [2, 3, 4] | Range [2 ... n] |
-----------------------------------------------------------------------------------------
| Ṗ | Pop from list | 4Ṗ -> [1 ... 4]Ṗ -> [1, 2, 3] | Range [1 ... n-1] |
-----------------------------------------------------------------------------------------
| Ẇ | Sublists of list | 4Ẇ -> [1 ... 4]Ẇ | All sublists of R |
| | | -> [[1], [2], [3], [4], [1, 2], | |
| | | [2, 3], [3, 4], [1, 2, 3], | |
| | | [2, 3, 4], [1, 2, 3, 4]] | |
-----------------------------------------------------------------------------------------
| Ẋ | Shuffle list | 4Ẋ -> [1 ... 4]Ẋ -> [2, 1, 3, 4] | Shuffles R |
-----------------------------------------------------------------------------------------
| Œ! | All permutations | 3Œ! -> [1, 2, 3]Œ! | All permutations |
| | of a list | -> [[1, 2, 3], [1, 3, 2], | of R |
| | | [2, 1, 3], [2, 3, 1], | |
| | | [3, 1, 2], [3, 2, 1]] | |
-----------------------------------------------------------------------------------------
| ŒḄ | Non-vectorized | 4ŒḄ -> [1 ... 4]ŒḄ | Bounces R |
| | bounce, | -> [1, 2, 3, 4, 3, 2, 1] | |
| | z[:-1] + z[::-1] | | |
-----------------------------------------------------------------------------------------
| Œc | Unordered pairs | 4Œc -> [1 ... 4]Œc | Unordered pairs |
| | of a list | -> [[1, 2], [1, 3], [1, 4], [2, 3], | of R |
| | | [2, 4], [3, 4]] | |
-----------------------------------------------------------------------------------------
| Œċ | Unordered pairs | 4Œċ -> [1 ... 4]Œċ | Unordered pairs |
| | with replacement | -> [[1, 1], [1, 2], [1, 3], [1, 4], | with replacement |
| | of a list | [2, 2], [2, 3], [2, 4], [3, 3], | of R |
| | | [3, 4], [4, 4]] | |
-----------------------------------------------------------------------------------------
| ŒP | Powerset of | 3ŒP -> [1 ... 3] | Powerset of R |
| | a list | -> ['', [1], [2], [3], [1, 2], | |
| | | [1, 3], [2, 3], [1, 2, 3]] | |
-----------------------------------------------------------------------------------------
| Œp | Cartesian | 4,2Œp -> [[1 ... 4], [1 ... 2]]Œp | Cartesian product |
| | product of z's | -> [[1, 1], [1, 2], [2, 1], [2, 2], | of [1 ... z[i]] |
| | items | [3, 1], [3, 2], [4, 1], [4, 2]] | for i in z |
-----------------------------------------------------------------------------------------
```
[Answer]
# It's sometimes worthwhile to read from standard input when there are exactly two inputs
Jelly is optimized for taking input from command-line arguments. However, it's also optimized for writing monads rather than dyads; with dyads there are so many possible meanings for each builtin that you often need to spend characters to disambiguate, whereas with monads there are typically many ways to say the same thing.
As such, if you use one of two inputs only once, and the problem is such that it can't easily be implicitly read from `⁴` (i.e. you either need to make the `⁴` explicit, or else spend a character on `}`, `@`, or the like), consider reading it from standard input with `Ɠ` rather than placing it on the command line; that lets you precisely place the input right where you need it via the placement of your `Ɠ`, whilst ensuring that every other implicit input will be taken from your other input. That costs a byte and saves a byte, and depending on the problem, may well save a second byte by giving you more scope to reorder the code.
[Answer]
# `Ƒ` combines very well with vectorising commands
For example: `Ṡ` returns the sign of an integer. If given an array, it applies `Ṡ` to each element and returns the corresponding array:
```
-3Ṡ = -1
1,2,-2,5,0Ṡ = 1,1,-1,1,0
```
Under `Ṡ`, only `1`, `0` and `-1` are unchanged. Therefore, `ṠƑ` returns true if its argument is one of `1`, `0` or `-1`.
However, `Ƒ` doesn't vectorise over lists. This means that given a list and an atom that vectorises, it acts something similar to `<atom>Ƒ€Ạ`, which saves at least 2 bytes and potentially more if using filters and other quicks (`<atom>Ƒ€Ạ$Ƈ` vs `<atom>ƑƇ`). As an example, compare:
```
-,1,0,1,- ṠƑ
-,2,0,1,- ṠƑ
```
[Try it online!](https://tio.run/##y0rNyan8/19Xx1DHAIh1FR7uXHBsIpeujhEy/7/hocUKOgpGhxb/BwA "Jelly – Try It Online")
---
This works best with the following atoms. All of these vectorise with depth 0 unless stated otherwise, meaning they vectorise to all levels of nested arrays:
| Atom | What does `<atom>Ƒ` test? |
| --- | --- |
| `<nilad>` | All equal `nilad` |
| `A` | All are non-negative |
| `H`, `N`, `Ḥ`, `Ẓ` `÷`, `%`, `:` | All zeros `÷%:` only work if the right argument doesn't lead to a division by zero |
| `O` | All numbers (i.e. no strings) |
| `U` | All subarrays are palindromes. Note that due to the behaviour of `ŒḂ` on integers, this is different to `ŒḂ€Ạ` for flat arrays See below for a breakdown of the differences and more details on `UƑ` |
| `²`, `Ḃ` | All elements are 1 or 0 |
| `Ị`, `İ`, `Ʋ` | Only contains 1. Can usually be replaced by `Ȧ`, but not always |
| `Ọ` | All strings (i.e. no numbers) |
| `Ċ`, `Ḟ` | All integers |
| `Ṡ` | All elements are -1, 0 or 1 |
| `×` | All elements are zero Or, the right argument is 1 |
| `+`, `_`, `^` | Is the right argument 0? |
| `a`, `&` | Are all elements 0 or equal to the right argument? |
| `o` | If the right argument is not zero, is the left argument all non-zero? If the right argument is zero, return `1` |
| `|` | If the right argument is zero, is the left argument all integers? If the right argument is non-zero, are all elements equal to the right argument? |
| `«` | Are all elements less than or equal to the right argument? |
| `»` | Are all elements greater than or equal to the right argument? |
For `|^&`, the arguments must only involve integers
### `UƑ`
Due to `U` vectorising at depth 0 and `ŒḂ` not vectorising, `UƑ`, `ŒḂ` and `ŒḂ€Ạ` have very different behaviours in some cases (note that `ŒḂ` also checks if integers are palindromic by checking their digits):
* If the argument is a flat list of integers/strings:
+ `ŒḂ` returns true if the list is palindromic
+ `ŒḂ€Ạ` returns true if all elements of the list are palindromic
+ `UƑ` returns true if the list is palindromic
* If the argument is a list containing integers and single nested lists (e.g. `[[0, 1], 2, 3, [4, 5, 6]]`):
+ `ŒḂ` returns true if the list is palindromic, ignoring if elements themselves are palindromic
+ `ŒḂ€Ạ` returns true if each element in the list is palindromic, ignoring whether the list as a whole is palindromic.
+ `UƑ` will always return false
* If the argument is a list containing single nested lists (e.g. `[[1, 2], [3, 4], [5]]`):
+ `ŒḂ` returns true if the list is palindromic, ignoring if elements themselves are palindromic
+ `ŒḂ€Ạ` returns true if each element in the list is palindromic, ignoring whether the list as a whole is palindromic.
+ `UƑ` acts the same as `ŒḂ€Ạ`
* If the argument is a list with multiple levels of nesting (e.g. `[2, [2, 2], [2, [2, 2]]]`):
+ `ŒḂ` returns true if the list is palindromic, ignoring if elements themselves are palindromic
+ `ŒḂ€Ạ` returns true if each first order element in the list is palindromic, ignoring whether the list as a whole is palindromic. This does not check the nested elements if they are palindromes, it just iterates through the first level elements and checks them
+ `UƑ` checks each subarray at all depths and returns true iff all these subarrays are palindromes. As `UƑ` returns false for integers, if the list contains any subarrays containing both integers and lists, it'll return false.As an example, compare the behaviour of each will the following arguments:
| Argument | `ŒḂ` | `ŒḂ€Ạ` | `UƑ` |
| --- | --- | --- | --- |
| `[[2], [2, 2], [[2], [2, 2]]]` | 0 | 0 | 1 |
| `[2, [2, 2], [[2, 2], [2, 2]]]` | 0 | 1 | 0 |
| `[[2, [2, 2]], [2, [2, 2]]]` | 1 | 0 | 0 |
| `[[[2], [2, 2]], [[2], [2, 2]]]` | 1 | 0 | 1 |
---
Some additional helpful uses of `Ƒ`:
* `ṄƑ`, `ȮƑ` and `ṘƑ` all print their argument and replace it with `1` if you need to output the argument and start a new chain with 1 as the argument. Saves bytes if the chain prevents using `1` as an unparseable nilad
* `FƑ` and `ẎƑ` both test if their argument is a flat list
* `fƑ` returns true iff the left argument consists entirely of the right argument.
* `ḟƑ` returns true iff the left argument does not contain the right argument
* `ṁƑ` tests if the left argument has the same "shape" as the right argument (i.e. length and depth of each element)
* `tƑ` tests if the left argument begins or ends with the right argument (returning 1 if it does not)
* `ÆṣƑ` tests if its argument is [perfect](https://en.wikipedia.org/wiki/Perfect_number), or, if a list, is all perfect numbers
[Answer]
# Monads don't have to be monads
Not very frequently applicable, but in some cases where a series of monads (or dyad-nilad/nilad/dyad pairs, i.e. would be an LCC if there was a leading constant) grouped with `$ƊƲ` is to the right of a dyad in a monadic chain, but the `(2,1)` pattern is not desired, the grouping quick can be replaced with `¥ɗʋ` without affecting its behavior at no cost. This pretty much only comes up if there's another quick applied to the group which inherits its operand's adicity, [like `Ƈ`](https://chat.stackexchange.com/transcript/message/58791639#58791639), and there's no monad to the right of that.
[Answer]
## Optimal Integer / List Compression
An integer compressor exists for a single large integer already; however, there are many ways of representing integers and lists - basic literals, exponential literals, codepage index lists, long compressed numbers, and two-byte short compressed numbers. These are all mentioned in this thread, but this is a unified compression tool for all of them.
This is available of my site [here](https://jht.hyper-neutrino.xyz/misc/integer-compressor) (affiliation disclosure: I made this site. I don't get any money from it. It's just a project entirely for fun). In case my site ceases to exist (and also because this answer should be self-contained), you can use the following code snippet to compress any valid value (where a valid value is an integer or a list of valid values).
Note that this only compresses into literals. There are often shorter ways to represent certain numbers or lists using constants, base decompression, grade up / group indices, etc, but that is beyond what I have implemented for this, and this will always return a single literal representing the inputted value.
```
let codepage = "¡¢£¤¥¦©¬®µ½¿€ÆÇÐÑ×ØŒÞßæçðıȷñ÷øœþ !\"#$%&'()*+,-./0123456789:;<=>?";
codepage += "@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~¶";
codepage += "°¹²³⁴⁵⁶⁷⁸⁹⁺⁻⁼⁽⁾ƁƇƊƑƓƘⱮƝƤƬƲȤɓƈɗƒɠɦƙɱɲƥʠɼʂƭʋȥẠḄḌẸḤỊḲḶṂṆỌṚṢṬỤṾẈỴẒȦḂ";
codepage += "ĊḊĖḞĠḢİĿṀṄȮṖṘṠṪẆẊẎŻạḅḍẹḥịḳḷṃṇọṛṣṭ§Äẉỵẓȧḃċḋėḟġḣŀṁṅȯṗṙṡṫẇẋẏż«»‘’“”";
function go() {
var value = document.getElementById("value").value;
console.clear();
if (value.match(/^\s*$/)) {
console.log();
} else if (value.match(/^[\[\]\d\s,-]*$/)) {
try {
value = eval("[" + value.replace(/\d+/g, x => x + "n") + "]");
} catch {
console.log("not a valid value");
return;
}
if (value !== undefined) {
if (value.length == 1) value = value[0];
console.log(compress(value));
}
}
}
function compress(value, surround_list = false) {
var converted = "";
for (var f of [trivial, exponential, cp_index_list, compressed_integer, short_compressed]) {
var c = f(value);
if (c && (converted == "" || c.length < converted.length)) {
converted = c;
}
}
if (Array.isArray(value)) {
var list_form = value.map(function(sub) {
return compress(sub, true);
}).join(",");
if (surround_list || value.length == 1) {
list_form = "[" + list_form + "]";
}
if (list_form && (converted == "" || list_form.length < converted.length)) {
converted = list_form;
}
}
return converted;
}
function trivial(number) {
if (Array.isArray(number)) return;
if (number == -1n) {
return "-";
} else {
return number.toString();
}
}
function exponential(number) {
if (Array.isArray(number)) return;
var exp = 0n;
while (number % 10n == 0n) {
exp++;
number /= 10n;
}
return (number == 1 ? "" : number == -1 ? "-" : number.toString()) + "ȷ" + (exp == 3 ? "" : exp.toString());
}
function cp_index_list(numbers) {
if (!Array.isArray(numbers)) return;
if (numbers.every(function(x) {
return !Array.isArray(x) && 0n <= x && x < 250n;
})) {
return "“" + numbers.map(function(x) {
return codepage[x];
}).join("") + "‘";
} else if (numbers.every(function(x) {
return Array.isArray(x) && x.every(function(x) {
return !Array.isArray(x) && 0n <= x && x < 250n;
});
})) {
var k = numbers.map(function(x) {
return "“" + x.map(function(x) {
return codepage[x];
}).join("");
}).join("") + "‘";
if (numbers.length == 1) {
return "[" + k + "]";
} else {
return k;
}
}
}
function compressed_integer(number) {
if (Array.isArray(number) && number.every(function(x) {
return !Array.isArray(x) && x >= 0n;
})) {
k = number.map(function(e) {
var string = compressed_integer(e);
return string.substring(0, string.length - 1);
}).join("") + "’";
if (number.length == 1) {
return "[" + k + "]";
} else {
return k;
}
} else if (!Array.isArray(number) && number >= 0n) {
var builder = "’";
while (number) {
var digit = number % 250n;
if (digit == 0n) digit = 250n;
number -= digit;
number /= 250n;
builder = codepage[digit - 1n] + builder;
}
return "“" + builder;
}
}
function short_compressed(number) {
if (Array.isArray(number)) return;
if (number < -31349n || (number > -100n && number < 1001n) || number > 32250n) return;
if (number < 0) number += 62850n;
else number -= 750n;
var last = number % 250n;
if (last == 0n) last = 250n;
number -= last;
number /= 250n;
return "⁽" + codepage[number - 1n] + codepage[last - 1n];
}
```
```
input {
padding: 5px;
font-family: monospace;
width: 100%;
}
```
```
<input id="value" type="text" placeholder="Enter a valid integer/list here" />
<br /><br />
<button onclick="go()">Compress!</button>
```
[Answer]
# Most quick-link monads get a free `{`
Quicks that expect dyads typically error when run on monads, because most monads have their underlying `call` as a lambda accepting only one argument. However, most quicks that emit monads--whether conditionally or unconditionally--implement the emitted monad's `call` as a lambda accepting up to two arguments, with the only exceptions being `Ɲɼ`⁺`.
This is *completely useless* unless you're already severely abusing one of the handful of quicks that strictly require a dyad, but it [can](https://codegolf.stackexchange.com/questions/258951/sort-by-element-duplication/258955#258955) come up. I could also see this coming up with `\` in some circumstance, most likely in conjunction with a simple grouping quick.
] |
[Question]
[
## Your Task:
Write a program or function to check if a number that is inputted is a [*Fibonacci number*.](https://en.wikipedia.org/wiki/Fibonacci_number) A Fibonacci number is a number contained in the Fibonacci sequence.
The Fibonacci Sequence is defined as:
`F(n) = F(n - 1) + F(n - 2)`
With the seeds being `F(0) = 0` and `F(1) = 1`.
## Input:
A non-negative integer between 0 and 1,000,000,000 that may or may not be a Fibonacci number.
## Output:
A truthy/falsy value indicating whether or not the input is a Fibonacci number.
## Examples:
```
0-->truthy
1-->truthy
2-->truthy
12-->falsy
```
## Scoring:
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), lowest byte count wins.
[Answer]
# [Neim](https://github.com/okx-code/Neim), 2 [bytes](https://github.com/okx-code/Neim/wiki/Code-Page)
```
fùïö
```
Explanation:
```
f Push an infinite fibonacci list
ùïö Is the input in that list?
```
Works the same as my [It's Hip to be Square](https://codegolf.stackexchange.com/a/125250/26600) answer, but uses a different infinite list: `f`, for fibonacci.
[Try it!](http://178.62.56.56:80/neim?code=f%F0%9D%95%9A&input=0)
[Answer]
# Regex (ECMAScript), ~~392~~ ~~358~~ ~~328~~ ~~224~~ ~~206~~ ~~165~~ ~~164~~ ~~162~~ 161 bytes
*-1 byte by using ECMAScript non-participating capture group behavior*
*-2 bytes by by calculating \$F\_{2n+3}\$ differently*
*-1 byte by moving around a remainder*
The techniques that need to come into play to match Fibonacci numbers with an ECMAScript regex (in unary) are a far cry from how it's best done in most other regex flavors. The lack of forward/nested backreferences or recursion means that it is impossible to directly count or keep a running total of anything. The lack of lookbehind makes it often a challenge even to have enough space to work in.
Many problems must be approached from an entirely different perspective, and seem unsolvable until the arrival of some key insight. It forces you to cast a much wider net in finding which mathematical properties of the numbers you're working with might be able to be used to make a particular problem solvable.
In March 2014, this is what happened for Fibonacci numbers. Looking at the Wikipedia page, I initially couldn't figure out a way, though one particular property seemed tantalizingly close. Then the mathematician [teukon](https://gist.github.com/teukon) outlined a method that made it quite clear it would be possible to do, using that property along with another one. He was reluctant to actually construct the regex. His reaction when I went ahead and did it:
>
> You're crazy! ... I thought you might do this.
>
>
>
As with my other ECMAScript unary math regex posts, I'll give a **warning:** I highly recommend learning how to solve unary mathematical problems in ECMAScript regex. It's been a fascinating journey for me, and I don't want to spoil it for anybody who might potentially want to try it themselves, especially those with an interest in number theory. [See that post](https://codegolf.stackexchange.com/a/178889/17216) for a list of consecutively spoiler-tagged recommended problems to solve one by one.
So **do not read any further if you don't want some unary regex magic spoiled for you**. If you do want to take a shot at figuring out this magic yourself, I highly recommend starting by solving some problems in ECMAScript regex as outlined in that post linked above.
The challenge I initially faced: A positive integer *x* [is a Fibonacci number](https://en.wikipedia.org/wiki/Fibonacci_number#Identification) if and only if 5x2 + 4 and/or 5x2 - 4 is a perfect square. But there is no room to calculate this in a regex. The only space we have to work in is the number itself. We don't even have enough room to multiply by 5 *or* take the square, let alone both.
teukon's idea on how to solve it ([originally posted here](https://gist.github.com/Davidebyzero/9090628#gistcomment-1185682)):
>
> The regex is presented with a string of the form `^x*$`, let z be its length. Check whether or not z is one of the first few Fibonacci numbers by hand (up to 21 should do). If it is not:
>
>
> 1. Read a couple of numbers, a Use forward look-aheads to build a2, ab, and b2.
> - Assert that either 5a2 + 4 or 5a2 - 4 is a perfect square (so a must be Fn-1 for some n).
> - Assert that either 5b2 + 4 or 5b2 - 4 is a perfect square (so b must be Fn).
> - Check that z = F2n+3 or z = F2n+4 by using the earlier built a2, ab, and b2, and the identities:
> * F2n-1 = Fn2 + Fn-12* F2n = (2Fn-1 + Fn)Fn
>
>
> In brief: these identities allow us to reduce the problem of checking that a given number is Fibonacci to checking that a pair of **much** smaller numbers are Fibonacci. A little algebra will show that for large enough n (n = 3 should do), F2n+3 > Fn + 5Fn2 + 4 so there should always be enough space.
>
>
>
And [here is a mockup of the algorithm in C](https://gist.github.com/Davidebyzero/9090628#gistcomment-1185782) which I wrote as a test before implementing it in regex. My final golfed regex is rather different. There turned out to be no need to find both \$a\$ and \$b\$, because \$b\$ is the Lucas number \$L\_n\$, which along with \$F\_n\$ can be used to derive \$F\_{2n+2}\$ and \$F\_{2n+3}\$ as needed:
* \${L\_n}^2 = 5{F\_n}^2±4\$
* \$L\_{2n} = ({5{F\_n}^2 + {L\_n}^2}) / 2 = 5{F\_n}^2±2 = {L\_n}^2∓2\$
* \$F\_{2n} = L\_n F\_n\$
* \$F\_{2n+1} = ({L\_{2n} + F\_{2n}})/2\$
* \$F\_{2n+2} = F\_{2n} + F\_{2n+1}\$
* \$F\_{2n+3} = F\_{2n+1} + F\_{2n+2}\$
So with no further ado, here is the regex:
`^(?=(x*).*(?=x{4}(x{5}(\1{5}))(?=\2*$)\3+$)(|x{4})(?=xx(x*)\5)\4(x(x*))(?=(\6*)\7+$)(?=\6*$\8)\6*(?=x\1\7+$)(x*)(\9x?)|)(\9\10(\5\10)\12?|xx?x?|x{5}|x{8}|x{21})$`
[Try it online!](https://tio.run/##TY9BTwIxEIX/ChICM4ssuwiIrGVPHrhw0KPVpIGyVEvZtAUqu/vbsdWYeHkz@d6bvMwHOzGz1qK0A1OKDdf7g/rkX1dNFD@3nnnx5EqAC1kMo@s75ARchHHkF1eNG3DVpAGaekX0jI6iDtK7fgehDn5gzoUTOkE6hp81QKBTz@5D0F9Now6doR8hTtNf7pNAH1yOdZg0TYBOvCJNR3ntXO68@l4vsyCjtMHONRpeMLaHF6uFKgBjI8Waw/R2MEbMDEmy805IDiCJ5mwjheKAeEPUUUqsCiJjU0phoTfoYSa2AIoUseSqsDtcjOpamBVbgSAl04YvlYXiNXlD/DP4f0Mt0jydBxvtTh/O7aU6MSk2Lc1Uweetdl9m24OGTDwSnol@H31h27VjzUvOLAiM98yud6ARK9Ptlv4lC@GLNCuP1ljtI1nTXJPBOEm@AQ "JavaScript (SpiderMonkey) – Try It Online")
And the pretty-printed, commented version:
```
^ # tail = N = input number
(?=
(x*) # \1+1 = potential number for which 5*(\1+1)^2 ± 4 is a
# perfect square; this is true iff \1+1 is a Fibonacci number,
# which we shall call F_n. Outside the surrounding lookahead
# block, \1+1 is guaranteed to be the largest number for which
# this is true such that \1 + 5*(\1+1)^2 + 4 <= N.
.*
(?= # tail = (\1+1) * (\1+1) * 5 + 4
x{4}
( # \2 = (\1+1) * 5
x{5}
(\1{5}) # \3 = \1 * 5
)
(?=\2*$)
\3+$
)
(|x{4}) # \4 = parity - determined by whether the index of Fibonacci
# number \1+1 is odd or even;
(?=
xx # tail = arithmetic mean of (\1+1) * (\1+1) * 5 and \6 * \6
# = ((F_n * F_n * 5) + (L_n * L_n)) / 2 = L_{2n}
(x*)\5 # \5 = floor(tail / 2) = floor(L_{2n} / 2)
)
\4
# require that the current tail is a perfect square
(x(x*)) # \6 = potential square root, which will be the square root
# after the following two lookaheads; \7 = \6-1
(?=(\6*)\7+$) # \8 = must be zero for \6 to be a valid square root
(?=\6*$\8)
# \6 is now the Lucas number L_n corresponding to the Fibonacci number F_n.
\6*
(?=x\1\7+$) # tail = F_{2n} = L_n * F_n = \6 * (\1+1), where \6 is larger
(x*)(\9x?) # \9 = floor(tail / 2);
# \10 = ceil(tail / 2); the remainder tail % 2 will always be
# the same as the remainder discarded by \5, because
# F_{2n} is odd iff L_{2n} is odd, thus this ceil()
# can complement the floor() of \5 when adding \5 + \10
| # Allow everything above to be skipped, resulting in all
# capture groups being unset.
)
(
# Note that if the above was skipped using the empty alternative in the lookahead,
# the following will evaluate to 0. This relies on ECMAScript NPCG behavior.
\9\10(\5\10) # \12 = F_{2n+1} = (L_{2n} + F_{2n})/2 = \5 + \10;
# head = F_{2n+2} = F_{2n} + F_{2n+1}
# = \9+\10 + \12
\12? # head = F_{2n+3} = F_{2n+2} + F_{2n+1} (optionally)
# = head + \12
|
xx?x?|x{5}|x{8}|x{21} # The Fibonacci numbers 1, 2, 3, 5, 8, 21 cannot be handled
# by our main algorithm, so match them here; note, as it so
# happens the main algorithm does match 13, so that doesn't
# need to be handled here.
)$
```
The multiplication algorithm is not explained in those comments, but is briefly explained in a paragraph of my [abundant numbers regex post](https://codegolf.stackexchange.com/a/178952/17216).
I was maintaining six different versions of the Fibonacci regex: four that ratchet from shortest length to fastest speed and use the algorithm explained above, and two others that use a different, much faster but much more lengthy algorithm, which as I found can actually return the Fibonacci index as a match (explaining that algorithm here is beyond the scope of this post, but it's explained [in the original discussion Gist](https://gist.github.com/Davidebyzero/9090628#gistcomment-1186893)). I don't think I would maintain that many very-similar versions of a regex again, because at the time I was doing all my testing in PCRE and Perl, but [my regex engine](https://github.com/Davidebyzero/RegexMathEngine) is fast enough that concerns of speed are not as important anymore (and if a particular construct is causing a bottleneck, I can add an optimization for it) – though I'd probably again maintain one fastest version and one shortest version, if the difference in speed were big enough.
The "return the Fibonacci index minus 1 as a match" version (not heavily golfed):
[Try it online!](https://tio.run/##bVLBcpswEP0Vx@OJtVATJMDYpphTD7nk0B6rdoZJFKwWYwZIoga49gP6if0RVyvH4E47owGt9r23b1f6lj6n9X0ly2ZRl/JBVPtD8V38OFZxIV4mH0X2QZWEvMbbG@v4lSQbksS4FFF2AoBbx8Ifp9YMCGf2DE@vVLvqOW2Z13Nfbw2SeyNfw4EoS59rJeuk5FgICo1OyFdvSjzg6yGr@HoGfGlIABcs6hoadTmlhjhmNIEydKn/Pl/ylUZ1JgbrH4HwzEePa00EgzxZXprFLsuutWh4agTd0dV5z5lrjXuqUUOop8RaPRjmncJBjfkzUK3fo2anBcba/4OsOw0bIIqz5eiDvfkYecHpegLO1tgf95g5DnWgv4R7Ls7axGB3Iy9sWY@Q4Dxzc5G@fTrjXoA0E4MNM/jbqKagHQWQDH64x2ngWMnwZtQwJt/cAZKNPPfxKohSOgG6546HpnNvpZTqzCtUiUo6otqgxwr40BI0gRPCpCmO1TsscbRuXsFpDp@aShYZAafO5b0gy3cLHyCqYzd62clcEJLHlUgfclkIAnAVF095Dm0W505d5rIh88UcIvlISBFnTi6KrNnBlnWdrO/SOyLjMq1qcVs0JPvsfgE4J8RlotjShG4wDc2uOrxMb4vnNJcPkyotMrGZTO08ejxUJJLvYxFJ2wZdcB9P1dSpRCnShkhw9mlzvyMVQFtfX5e6qYZgHzQqn5q6qYi055PfP39N5vZeOzlbjfr@6C7Y0nX/AA "JavaScript (SpiderMonkey) – Try It Online")
All of the versions are on github with the full commit history of golf optimizations:
[regex for matching Fibonacci numbers - short, speed 0.txt](https://github.com/Davidebyzero/RegexGolf/blob/master/regex%20for%20matching%20Fibonacci%20numbers%20-%20short%2C%20speed%200.txt) (the shortest but slowest one, as in this post)
[regex for matching Fibonacci numbers - short, speed 1.txt](https://github.com/Davidebyzero/RegexGolf/blob/master/regex%20for%20matching%20Fibonacci%20numbers%20-%20short%2C%20speed%201.txt)
[regex for matching Fibonacci numbers - short, speed 2.txt](https://github.com/Davidebyzero/RegexGolf/blob/master/regex%20for%20matching%20Fibonacci%20numbers%20-%20short%2C%20speed%202.txt)
[regex for matching Fibonacci numbers - short, speed 3.txt](https://github.com/Davidebyzero/RegexGolf/blob/master/regex%20for%20matching%20Fibonacci%20numbers%20-%20short%2C%20speed%203.txt)
[regex for matching Fibonacci numbers - fastest.txt](https://github.com/Davidebyzero/RegexGolf/blob/master/regex%20for%20matching%20Fibonacci%20numbers%20-%20fastest.txt)
[regex for matching Fibonacci numbers - return index.txt](https://github.com/Davidebyzero/RegexGolf/blob/master/regex%20for%20matching%20Fibonacci%20numbers%20-%20return%20index.txt)
[Answer]
## JavaScript (ES6), 34 bytes
```
f=(n,x=0,y=1)=>x<n?f(n,y,x+y):x==n
```
Recursively generates the Fibonacci sequence until it finds an item greater than or equal to the input, then returns item == input.
[Answer]
## [Retina](https://github.com/m-ender/retina), 23 bytes
```
^$|^(^1|(?>\2?)(\1))*1$
```
[Try it online!](https://tio.run/##Dco7DoAgEAXA/p0DkwUTw1vw18hFCNHCwsbCWHp3pJ3Mc77XfdRO9qGHcbWYr0jhJ2nLmqxkWutoavUgFAERIybMWLCCDQkqGMAI9dCW9Ac "Retina – Try It Online")
Input in unary, outputs `0` or `1`.
### Explanation
The Fibonacci sequence is a good candidate for a solution with forward references, i.e. a "backreference" that refers either to a surrounding group or one that appears later in the regex (in this case, we're actually using both of those). When matching numbers like this, we need to figure out a recursive expression for the *difference* between sequence elements. E.g. to match triangular numbers, we usually match the previous segment plus one. To match square numbers (whose differences are the odd numbers), we match the previous segment plus two.
Since we obtain the Fibonacci numbers by adding the second-to-last element to the last one, the differences between them are also just the Fibonacci numbers. So we need to match each segment as the sum of the previous two. The core of the regex is this:
```
( # This is group 1 which is repeated 0 or more times. On each
# iteration it matches one Fibonacci number.
^1 # On the first iteration, we simply match 1 as the base case.
| # Afterwards, the ^ can no longer match so the second alternative
# is used.
(?>\2?) # If possible, match group 2. This ends up being the Fibonacci
# number before the last. The reason we need to make this optional
# is that this group isn't defined yet on the second iteration.
# The reason we wrap it in an atomic group is to prevent backtracking:
# if group 2 exists, we *have* to include it in the match, otherwise
# we would allow smaller increments.
(\1) # Finally, match the previous Fibonacci number and store it in
# group 2 so that it becomes the second-to-last Fibonacci number
# in the next iteration.
)*
```
Now this ends up adding the Fibonacci numbers starting at **1**, i.e. **1, 1, 2, 3, 5, ...**. Those add up to **1, 2, 4, 7, 12, ...**. I.e. they are one less than the Fibonacci numbers, so we add a `1` at the end. The only case this doesn't cover is zero, so we have the `^$` alternative at the beginning to cover that.
[Answer]
# [Python 3](https://docs.python.org/3/), 48 bytes
```
lambda n:0in((5*n*n+4)**.5%1,abs(5*n*n-4)**.5%1)
```
[Try it online!](https://tio.run/##Nci9DkAwFAbQmae4i6Stn1SwSLyJ5UqVJnykunj6kojxnPMO64EmWhpojBvvk2FCrx2E6BQU8lYqVXVZXfB0fVX@JaM9PIEcyDOWWdRaa9mniRWQxDB0eofwIj4 "Python 3 – Try It Online")
[Answer]
# Python 2, ~~48~~ 44 bytes
```
f=lambda n,a=0,b=1:n>a and f(n,b,a+b)or n==a
```
[**Try it online**](https://tio.run/##DcnBCoAgDADQ@75iRyUPzeoSrH@ZWCTUEjGir7fe9eW37pf61jY@5AxRUJ1w7wLTrIugaMTNqAtOumCvgsos7dnTsSLNuSSt/yfNdzXWth4IPAwwwgTkgYYP)
*Thanks to Jonathan Allan for saving 4 bytes*
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~8~~ 7 bytes
```
>ÅF¹å¹m
```
Explanation:
```
>√ÖF # Generate Fibbonacci numbers up to n+1
¹å # 0 if original isn't in the list, 1 if it is
¬πm # 0**0 = 1 if input was 0 (hotfix for 0).
# or 0**n if not fibb / 1**n if it is a fibb.
```
[Try it online!](https://tio.run/##MzBNTDJM/f/f7nCr26Gdh5ce2pn7/78hAA "05AB1E – Try It Online")
-1 thanks to Jonathan Allan for the 0-not-a-fibonacci-number workaround.
[Answer]
# [Perl 6](http://perl6.org/), 23 bytes
```
{$_‚àà(0,1,*+*...*>$_)}
```
[Answer]
# [Seriously](https://github.com/Mego/Seriously/tree/v1), 3 bytes
```
,fu
```
[Try it online!](https://tio.run/##K04tyswvLc6p/P9fJ630/39jAA "Seriously – Try It Online")
Returns the index +1 in the list of Fibonacci numbers if truthy, otherwise returns falsy.
**Explanation:**
```
,fu
, read input
f 0-indexed index of that number in the fibonacci sequence (-1 if not in the sequence)
u increment. (Makes the -1 value falsy and the 0-value truthy)
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~ 8 7 ~~ 6 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
-r‘ÆḞċ
```
**[Try it online!](https://tio.run/##y0rNyan8/1@36FHDjMNtD3fMO9L9//9/Q2MA "Jelly – Try It Online")**
### How?
```
-r‘ÆḞċ - Link: non negative number, n
- - literal -1 = -1
r - inclusive range = [-1,0,1,2,3,4,5,...,n]
‘ - increment n = [ 0,1,2,3,4,5,6,...,n+1]
ÆḞ - Fibonacci = [ 0,1,1,2,3,5,8,...,fib(n+1)]
ċ - count occurrences of n (1 if n is a Fibonacci number, 0 otherwise)
```
Notes:
* the increment, `‘`, is needed so this works for **2** and **3**, since they are the **3rd** and **4th** Fibonacci numbers - beyond **3** all Fibonacci numbers are greater than their index.
* the `-` is needed (rather than just `‘R`) so this works for **0** since **0** is the **0th** Fibonacci number;
[Answer]
# ZX81 BASIC 180 151 100 ~94 tokenized BASIC bytes
With thanks to Moggy on the SinclairZXWorld forums, here is a much neater solution that saves more bytes.
```
1 INPUT I
2 FOR F=NOT PI TO VAL "1E9"
3 LET R=INT (VAL ".5"+(((SQR VAL "5"+SGN PI)/VAL "2")**I)/SQR VAL "5")
4 IF R>=I THEN PRINT F=R
5 IF R<I THEN NEXT F
```
This will output 1 if a Fibonacci number is entered, or zero if not. Although this saves bytes, it's much slower than the old solutions below. For speed (but more BASIC bytes) remove the `VAL` wrappers around the string literal numbers. Here is the old(er) solutions with some explanations:
```
1 INPUT A$
2 LET A=SGN PI
3 LET B=A
4 LET F=VAL A$
5 IF F>SGN PI THEN FOR I=NOT PI TO VAL "1E9"
6 LET C=A+B
7 LET A=B
8 LET B=C
9 IF B>=F THEN GOTO CODE "£"
10 IF F THEN NEXT I
12 PRINT STR$(SGN PI*(B=F OR F<=SGN PI)) AND F>=NOT PI;"0" AND F<NOT PI
```
The amendments above saves further BASIC bytes to condensing the `IF` statements into a single `PRINT` in line 12; other bytes were saved by using the `VAL` keyword and, and using `GOTO CODE "£"`, which in the ZX81 character set is 12. Strings save more bytes over numbers as all numeric values are stored as floats so therefore take more space on the VAR stack.
[![enter image description here](https://i.stack.imgur.com/EOjIc.png)](https://i.stack.imgur.com/EOjIc.png)
[Answer]
## C#, 109 bytes
```
bool f(int n){int[]i=new[]{0,1,0};while(i[0]<n||i[1]<n){i[i[2]%2]=i[0]+i[1];i[2]++;}return n==i[0]||n==i[1];}
```
Definitely could be improved, but I didn't have time.
[Answer]
# [><>](https://esolangs.org/wiki/Fish), ~~21~~ 19+3 = ~~24~~ 22 bytes
```
i1\{=n;
?!\:@+:{:}(
```
Input is expected to be on the stack at program start, so +3 bytes for the `-v` flag.
[Try it online!](https://tio.run/##S8sszvj/P9Mwpto2z5rLXjHGykHbqtqqVuP///@6ZQqGppbmAA "><> – Try It Online")
This works by generating Fibonacci numbers until they are greater than or equal to the input number, then checking the last generated number for equality with the input. Outputs `1` if it was a Fibonacci number, `0` otherwise.
To ensure that `0` is handled correctly, the seed is `-1 1` - the first number generated will be `0` rather than `1`.
Thanks to @cole for pointing out that `i` can be used to push `-1` onto the stack when STDIN is empty. Very clever!
Previous version:
```
01-1\{=n;
}(?!\:@+:{:
```
[Answer]
# Mathematica, 37 bytes
```
!Fibonacci@n~Table~{n,0,#+1}~FreeQ~#&
```
*-4 bytes from @ngenisis*
[Answer]
# Dyalog APL, 17 bytes
```
0∊1|.5*⍨4 ¯4+5××⍨
```
[Try it online!](http://tryapl.org/?a=%u236A%28%u22A2%2C0%u220A1%7C0.5*%u23684%20%AF4+5%D7%D7%u2368%29%20%A8%u237325&run)
[Answer]
# MATL (16 bytes)
```
2^5*4-t8+hX^tk=s
```
[Try it online!](https://tio.run/##y00syfn/3yjOVMtEt8RCOyMiriTbtvj/f0Pjr3n5usmJyRmpAA)
Not the golfiest solution, but wanted to use the direct method of [checking if "5\*x^2+/-4" is a perfect square](https://en.wikipedia.org/wiki/Fibonacci_number#Recognizing_Fibonacci_numbers).
## Explanation:
```
2^5* % 5 times the input squared
4- % push the above minus 4
t8+ % push the above plus 8 (+4 overall)
hX^ % concatenate them into an array and then take the sqrt().
tk % push a copy of the array that is rounded using floor().
= % test if the sqrt's were already integers
s % sum the results, returns 0 if neither was a perfect square.
```
## Note:
In the "0" case it returns "2" because both 4 and -4 are perfect squares, same with 1 which produces "1 1". Consider any non-zero output as "truthy", and 0 as "falsy".
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 32 bytes
```
n->!prod(x=0,n+1,fibonacci(x)-n)
```
[Try it online!](https://tio.run/##DYqxDcAgDMBeSTsRlUhwAPxCqVKxhCjqwPc0gz1Y1maDXt0MBbZQPdTmE1ZJUa4cedxTWu8jLCTBzdOC@JkiZEdtyOfhBKouDoKI@wc "Pari/GP – Try It Online")
[Answer]
# [PHP](https://php.net/), 44 bytes
```
for(;0>$s=$x-$argn;)$x=+$y+$y=$x?:1;echo!$s;
```
[Try it online!](https://tio.run/##K8go@G9jX5BRwJVaVJRfFF@UWpBfVJKZl65R5xrv5x/i6eyqac2lkliUnmdrbGL9Py2/SMPawE6l2FalQhcsbK2pUmGrrVIJREAxeytD69TkjHxFlWLr//@/5uXrJicmZ6QCAA "PHP – Try It Online")
# [PHP](https://php.net/), 58 bytes
```
for($x=0,$y=1;$x<$argn;$x=$y,$y=$t)$t=$x+$y;echo$x==$argn;
```
[Try it online!](https://tio.run/##K8go@G9jX5BRwJVaVJRfFF@UWpBfVJKZl65R5xrv5x/i6eyqac2lkliUnmdrbGL9Py2/SEOlwtZAR6XS1tBapcIGLAVk2KpUgsRUSjRVSmxVKrRVKq1TkzPygRK2ECX//3/Ny9dNTkzOSAUA "PHP – Try It Online")
[Answer]
# [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 51 bytes
```
bool f(int n,int a=0,int b=1)=>a<n?f(n,b,a+b):a==n;
```
[Try it online!](https://tio.run/##TU5NS8NAFLz3Vwylhw2@hsTUfli3HrwqFDz0UHrYxE19EN@W7KJI2N8e03jpZd7wZpiZys8r19q@aoz32KOb@GACV/h2/IE3w6J8aFnOxxNMe/bJ4MDgu0BD7A/2KtkOj3rIMNWnYglgsFy146nLCDnhnlAQFoQHwpKwIqwJm0HKi8UmK/LlDV9lNzyP/3XA@68P9it9ceJdY9NDy8G@slg1m3YcMd@hu6S14iROxz1xEvvSuQb1OEnoikZn4y11nuideZLnWgmVZO7K5NFoLds@9n8 "C# (.NET Core) – Try It Online")
-6 bytes thanks to @Oliver!
This solution uses a pretty straightforward recursive function.
* The variable `n` is the number to be tested.
* The variables `a` and `b` are the 2 most recent numbers in the sequence.
* Checks if the first of the 2 most recent number is less than input. When this is the case, a recursive call is made to the next numbers in the series.
* Otherwise, check whether the first number is equal to input and return the result.
The TIO link demonstrates this working for 1134903170 which exceeds the maximum value required by the challenge.
[Answer]
# [Alchemist](https://github.com/bforte/Alchemist), ~~205~~ 134 bytes
Big thanks to [ASCII-only](https://codegolf.stackexchange.com/users/39244/ascii-only) for rather clever merging of states, saving 71 bytes!!
```
_->In_x+c+u
u+b->u+a+d
u+0b->v
v+c->v+b+d
v+0c->w
w+a+x->w+y
w+0a+0x->Out_"1"
w+a+0x->Out_"0"
w+0a+x+y->w+2x
w+0a+0y+d->w+c
w+0d+0a->u
```
[Try it online](https://tio.run/##PY0xDsMgDEV3jsH6heQke/ZOPQIiUCmV2i4JBE7vftook9@zn@Twiuvj/dx2Ve/m28dXRGSTsbg5IyARhVxMQeTAwlWBkA9zMKgENKIECOWed28H@7tdLvYfVLSej/XsG1L32DVxw5@q4zSpS8MX "Alchemist – Try It Online") or [verify in batch!](https://tio.run/##TY3BasMwEETv@opBiJCwpFF6K8E@BnrqB4RgZMnFhlRqLMuxof@urptQcto3s7OztYltztYMKNHFY1eHF9t78Rl6eHQeah2bKzTUfnOACwLom5guQyHVurFtgPL4wS58DztzsW3z1cUneqrcSL49nSDVvUCiKCD3EuczVis8uoQLvsm52pbvvprIUhKJ6m2ZyJBj1MyjGMnyoJqtkTTzTdw4MDHQzKgNaRYfaaj4w9/uX2t5D0w0L/HX6ZGfyS3aLtKxwz/zm/4F "Bash – Try It Online")
## Ungolfed
```
# read input, initialize (c = 1)
_ -> In_x + c + s0
# a,d <- b
s0 + b -> s0 + a + d
s0 + 0b -> s1
# b,d <- c
s1 + c -> s1 + b + d
s1 + 0c -> s2
s2 + a + x -> s2 + y # y <- min(a,x)
s2 + 0a + 0x -> Out_"1" # if (a == x): was Fibonacci
s2 + a + 0x -> Out_"0" # if (a > x): stop (we exceeded target)
s2 + 0a + x + y -> s2 + 2x # if (a < x): x += a (since y = a) / restore x
s2 + 0a + 0y + d -> s2 + c # once that's done; c <- d
s2 + 0a + 0d->s0 # and finally loop
```
[Answer]
# [Java (JDK)](http://jdk.java.net/), 37 bytes
```
s->s.matches(".?|(\\2?+(\\1|^.))*..")
```
[Try it online!](https://tio.run/##rZAxb9swEIV3/4qDAANScqZFkY6tunWADt7aJd3qNKBlKaYrkYJIBTUa/3b3bCkZknjr8Egcv8Px3dupJzXabX4fdVXbxsOOatZ6XbKiNZnX1rCr@SArlXPwTWnzdwBQt@tSZ@C88nQ9Wb2BilB45xttHn/eg2oeXQSnVoBlP@ZzRxG@WlvmyiyggC9wdKOFY5Xy2TZ3YcBun8PVKrm9ppM//2JRdMVYEB1Pg@aD87y7vfN5xWzrWU0DfWnC4EfT@u0@iObnDnokD4VeW6OyTH9vq3XeOPqsMwQQI8cEBU5whlxgwlFInFCVYt@R3ExTLpP0BmE8BimaTQ@kEDKVUkw7IP22B@PxNOYynk2F6NCkR4fOVGEbCMkZmE/vrEWvzt4uV4TBkCcbGC1g6IYmQDAIBVN1Xe7D4E/AmrzOlQ9NFPXLHy6ntFSlexOSsWZ5OSeJQAHQqikCj0mclJAI8AmJKCfMZyTqSeKX/E55pGn60AtfQ@IPcRy/6FI@H7j6vxGddDj@Aw "Java (JDK) – Try It Online")
This works for numbers up to 1,836,311,903 (47th fibonacci number) included. Above that, the result is undefined (including a potential infinite loop).
## Credits
* Thanks to Kevin Cruijssen and David Conrad for helping golfing :)
* Thanks to Kevin Cruijssen for porting the regex version, saving 12 bytes in the process!
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `r`, 4 bytes
```
√ûFce
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJyIiwiyoAobuKCtGAgPT4gYOKCtG7OuyIsIsOeRmNlIiwiO+KAoCwpIiwiMTUwIl0=) - show all boolean results
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJyIiwiyoAobs67Iiwiw55GY2UiLCI74oCgW24sXSkiLCI0MjAwIl0=) - show only numbers returning truthy
Thanks to Steffan. This based on the alternative 5 byte answer below, removing the need for the `$`.
# [Vyxal](https://github.com/Vyxal/Vyxal), 5 bytes
```
√ûF0pc
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCLKgChu4oK0YCA9PiBg4oK0bs67Iiwiw55GMHBjIiwiO+KAoCwpIiwiMTUwIl0=) - show all boolean results
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCLKgChuzrsiLCLDnkYwcGMiLCI74oCgW24sXSkiLCIxNjAwIl0=) - show only numbers returning truthy
```
√ûF # All 1-indexed Fibonacci numbers as a LazyList.
0p # Prepend the list with 0
c # Is the input contained in the list?
```
Alternative 5 bytes:
```
√ûFc$e
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCLKgChu4oK0YCA9PiBg4oK0bs67Iiwiw55GYyRlIiwiO+KAoCwpIiwiMTUwIl0=) - show all boolean results
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCLKgChuzrsiLCLDnkZjJGUiLCI74oCgW24sXSkiLCI0MjAwIl0=) - show only numbers returning truthy
```
√ûF # All 1-indexed Fibonacci numbers as a LazyList.
c # Is the input contained in the list?
$ # Swap above result with the input (this creates a copy of the input)
e # Exponentiate. For an input of zero this will yield 0**0 == 1; for other
# Fibonacci numbers, 1**{n>0} == 1; otherwise 0**{n>0} == 0.
```
The above two solutions work around the fact that there's no 0-indexed version of `ÞF`. Alternatively using `∆F` requires a different workaround, but it can also be done in 5 bytes:
```
Þn∆Fc
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCLKgChu4oK0YCA9PiBg4oK0bs67Iiwiw55u4oiGRmMiLCI74oCgLCkiLCIxNTAiXQ==) - show all boolean results
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCLKgChuzrsiLCLDnm7iiIZGYyIsIjvigKBbbixdKSIsIjE2MDAiXQ==) - show only numbers returning truthy
```
√ûn # All integers in an infinite list (0, 1, -1, 2, -2, ...)
∆F # nth Fibonacci number, 0-indexed
c # Contains - Check if one thing contains another
```
Using `Ä` (Inclusive range [0..input]) instead of `√ûn` wouldn't work, because the Fibonacci numbers \$2\$ and \$3\$ are not members of the lists \$[0,1,1]\$ and \$[0,1,1,2]\$ respectively. It would be necessary to use `‚Ä∫ Ä` (the range [0..input+1]), but for non-Fibonacci numbers that is exponentially slower than using `√ûn` (and `√ûn‚àÜFc` is in turn a bit slower than `√ûFc$e`).
Note that `Þn` includes negative numbers, and `∆F` on a negative number returns a negative Fibonacci number. However, `Þn∆Fc` only returns truthy for nonnegative Fibonacci numbers, probably due to a bug in Vyxal.
---
Without using any Fibonacci builtins (**7 bytes**):
```
k≈⁽+dḞc
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCLKgChu4oK0YCA9PiBg4oK0bs67Iiwia+KJiOKBvStk4bieYyIsIjvigKAsKSIsIjE1MCJd) - show all boolean results
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCLKgChuzrsiLCJr4omI4oG9K2ThuJ5jIiwiO+KAoFtuLF0pIiwiMTYwMCJd) - show only numbers returning truthy
The is based on [lyxal's answer to Fibonacci function or sequence](https://codegolf.stackexchange.com/a/223094/17216).
```
k≈ # the list [0, 1]
‚ÅΩ+d # lambda x, y: x + y
·∏û # Create an infinite sequence based on the function and the initial list.
c # Does the list contain the input?
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes
```
ȷḶÆḞi
```
[Try it online!](https://tio.run/##y0rNyan8///E9oc7th1ue7hjXub///8NAQ "Jelly – Try It Online")
Returns 0 for non-Fibonacci numbers, and the 1-indexed position of the number in the Fibonacci sequence for Fibonacci numbers.
Explanation:
```
ȷḶÆḞi
»∑ The literal number 1000
·∏∂ Range [0,1,...,999]
ÆḞ Get the ith Fib number; vectorizes [1,1,2,3,5,...,<1000th Fib number>]
i Get the first index of element in list, or 0 if not found
```
[Answer]
# R, ~~43~~ 40 bytes
```
pryr::f(x%in%DescTools::Fibonacci(0:45))
```
`pryr::f` creates a function:
```
function (x)
x %in% DescTools::Fibonacci(0:45)
```
Uses `DescTools::Fibonacci` to create the first `x+1` fibonacci numbers and checks for inclusion. `x+1` because the third fibnum is 2, and that wouldn't be enough to check for inclusion of 3.
Luckily `Desctools::Fibonacci(0)=0`, so that is a nice freebee.
-3 bytes thanks to MickyT
[Answer]
# [Haskell](https://www.haskell.org/), 31 bytes
```
f=0:scanl(+)1f
(`elem`take 45f)
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P83WwKo4OTEvR0Nb0zCNK91WIyE1JzU3oSQxO1XBxDRN839uYmaegq1CQVFmXomCikJuYoFCukK0gZ6eoUHsfwA "Haskell – Try It Online") This exploits the fact that the input will be in the range from 0 to 1,000,000,000, hence we need to check only the first 45 Fibonacci numbers. `f=0:scanl(+)1f` generates an infinite list of Fibonacci numbers, `take 45f` is the list of the first 45 Fibonacci numbers and `elem` checks whether the input is in this list.
---
### Unrestricted version: 36 bytes
```
f=0:scanl(+)1f
g n=n`elem`take(n+3)f
```
[Try it online!](https://tio.run/##BcFBCoAgEADAe6/YQwdFEKVb4EsicInVxHWR9P828@KoxLxWCu4cDworo33aMkiQSEwtTqykxBw6rYZFIED/ikzYoWGHDJez1rt7/Q "Haskell – Try It Online") For any `n`, taking the first `n+3` Fibonacci numbers will guarantee that `n` will be in this list if it's a Fibonacci number.
Note that this approach is incredible inefficient for high numbers that are not Fibonacci numbers, because all `n+3` Fibonacci numbers need to be computed.
[Answer]
# Javascript (ES6 without the \*\* operator), 44 bytes
```
f=(x,c=x*(Math.sqrt(5)-1)/2%1)=>x*(c-c*c)<.5
```
Relies on the ratio between successive Fibonacci numbers approaching the golden ratio. The value of c is the fractional part of the input divided by the golden ratio - if the input is Fibonacci then this will be very close to 1 and the value of c-c² will be very small.
Not as short as some of the other JS answers but runs in O(1) time.
[Answer]
# [Julia 0.4](http://julialang.org/), 29 bytes
```
!m=in(0,sqrt(5*m*m+[4,-4])%1)
```
[Try it online!](https://tio.run/##yyrNyUz8r5hr@z8zT8NAp7iwqETDVCtXK1c72kRH1yRWU9VQ839BUWZeiYaioZHmfwA "Julia 0.4 – Try It Online")
---
If this isn't how you do a Julia answer, let me know. I'm unsure of how input works on TIO.
[Answer]
# R, ~~32~~ 31 bytes
Takes input from stdin, returns `TRUE` or `FALSE` as appropriate.
```
any(!(5*scan()^2+-1:1*4)^.5%%1)
```
[Answer]
# Common Lisp, ~~61~~ 54 bytes
```
(defun f(x)(do((a 0 b)(b 1(+ a b)))((>= a x)(= a x))))
```
[Try it online!](https://tio.run/##JYxBCoQwFEOvEgQxHxFs93qXOrUgqF8cB1z16vUzZpMHeeSzLt@jFMY5/XYk3sKoZECPSTjBsUUwFCHHwdCEtyyFq@qBpCduLDsa9nDwcF4QFbRhCxcuVNlHdCNyyHVlLtP/oDw)
The reduction in size with respect to the previous version:
```
(defun f(x)(do((a 0 b)(b 1 c)(c 1(+ b c)))((>= a x)(= a x))))
```
was triggered by the idea that to generate the sequence of the Fibonacci numbers only two variables are necessary, not three.
[Answer]
# D, 98 79 bytes 77 bytes
*-19 bytes: changed square number algorithm (which also had the side effect of not needing `import std;`) and realized the non-UFCS way was 1 byte shorter*
golfed:
```
int p(real z){return z^^.5%1==0;}int f(int z){return p(5*z*z+4)||p(5*z*z-4);}
```
readable:
```
int p(real z){
return z^^.5%1==0
}
int f(int z){
return p(5*z*z+4)||p(5*z*z-4);
}
```
where `f` is the function that tests if a number is a fibonacci number.
This uses the fact that `a positive integer z is a Fibonacci number if and only if one of 5z^2 + 4 or 5z^2 ‚àí 4 is a perfect square.` [wikipedia](http://en.wikipedia.org/wiki/Fibonacci_number#Recognizing_Fibonacci_numbers)
Also `real` instead of `float` for one less byte, and returning an `int` instead of `bool` to save another byte (since ints are truthy if they're nonzero, and D implicitly casts expressions to the function's return value if possible, in this case casting a bool to an int).
There's probably some way to avoid having the extra function `p` (used to check if a number is a perfect square) but I can't find it out.
edit: replaced z^^2 with z\*z
] |
[Question]
[
Little Chandler is sad. Draw him a cloud to cheer him up.
*Note: Drawing a cloud won't actually cheer him up.*
A circle can be defined as a 3-tuple `(x,y,r)` where `x` is the x position of the circle on a Cartesian plane, `y` is the y position of the circle on a Cartesian plane, and `r` is the radius of the circle. `x` and `y` may be negative. `r` is always positive. The input is a list of circles in the form of space separated 3-tuples. For instance:
```
3,1,1 3,2,1.5 1,2,0.7 0.9,1.2,1.2 1,0,0.8
```
The `3,1,1` means "A circle with centre point at `3,1` with 1 radius. `3,2,1.5` means "A circle with centre point at `3,2` with 1.5 radius.
If we draw all of these circles of the input on a graph, it looks like this (I've included grid lines and labels for clarity only; they are not required):
![Graph](https://i.stack.imgur.com/jyZzd.png)
Notice how all the circles are *cohesive*. That is, they're all overlapped together such that it forms one large group without any small groups of circles separated from the rest. The input is *guaranteed* to be cohesive.
Suppose now we draw a line that travels around the "border" formed by these circles, without any of the other lines. It would be like drawing the border of the silhouette formed by all the circles. The resulting cloud would look something like this:
![cloud](https://i.stack.imgur.com/zDuUa.png "Yes, I know it looks nothing like a cloud. Just... use your imagination.")
So this cloud has been formed by drawing only the arcs of the circles in the input that form a border, resulting in a single shape. In other words, the cloud is formed by only drawing the arcs that are not within another circle. Your program will take in input in the form explained above, and output an image that displays the resulting cloud. The overall shape of the cloud must be correct, but the scale, colour, line thickness, and how it looks at vertexes is up to you. Note that the cloud must be visible, so you can't pull something like "This program draws a white cloud on a white background", "This program draws a cloud at a infinitesimally small scale", "This program draws a cloud with 0 line thickness", etc. Also note that the colour of the border must be different from the colour of the fill or background.
Another example. Input:
```
1,4,2 5,2,1 3,1,1 3.5,2,1.2 3,3,0.7 1,2,0.7
```
Output:
![cloud2](https://i.stack.imgur.com/mLzXk.png)
If there is a "hole" in the cloud, you should draw the hole as well. Input:
```
0,5,4 3,4,4 4,3,4 5,0,4 4,-3,4 3,-4,4 0,-5,4 -3,-4,4 -4,-3,4 -5,0,4 -4,3,4 -3,4,4
```
Output:
![cloud3](https://i.stack.imgur.com/F5K2j.png)
Here is an important rule: your program must draw *only* the lines that form the border. This means that you CANNOT simply draw the circles fully, and then draw the circles slightly smaller with a white fill -- because that method still draws lines that don't form a border, it just covers them up afterwards. The purpose of the rule was to prevent the "draw the circles, then draw the circles again with a white fill" implementations, or anything similar to that. The answer is expected to actually calculate where to draw things before drawing it.
This is code golf, so the shortest character count wins.
[Answer]
# T-SQL ~~235~~ ~~234~~ ~~229~~ ~~212~~ ~~171~~ 73 bytes
This makes use of spatial functionality in SQL Server 2012+. When it is run in SSMS (SQL Server Management Studio) is produces a spatial results pane.
~~The input is from variable @i. I could reduce it further if the input could be taken from a table.~~
Since table input is now allowed.
```
SELECT Geometry::UnionAggregate(Geometry::Point(X,Y,0).STBuffer(R))FROM A
```
I've left the previous solution below.
```
DECLARE @ VARCHAR(999)='WITH a AS(SELECT *FROM(VALUES('+REPLACE(@i,' ','),(')+'))A(X,Y,R))SELECT Geometry::UnionAggregate(Geometry::Point(X,Y,0).STBuffer(R))FROM a'EXEC(@)
```
**Edit**: Remove stray space, surplus **into** and subquery
171: Replaced table creation with CTE and @s with @.
![enter image description here](https://i.stack.imgur.com/0wRot.png)
Break down of the Dynamic SQL
```
DECLARE @i VARCHAR(100) = '1,4,2 5,2,1 3,1,1 3.5,2,1.2 3,3,0.7 1,2,0.7' -- Input
DECLARE @ VARCHAR(999) = '
WITH a AS( --CTE to produce rows of x,y,r
SELECT *FROM(VALUES('+
REPLACE(@i,' ','),(') --Format @i to a value set
+'))A(X,Y,R)
)
SELECT Geometry::UnionAggregate( --Aggregate Buffered Points
Geometry::Point(X,Y,0).STBuffer(R) --Create point and buffer
)
FROM a --from the table variable
'
EXEC(@) --Execute Dynamic sql
```
[Answer]
# Mathematica ~~177 126 121~~ 119
## Solving by Disk Regions: the mathematician's approach
The logic is to
* Create Region 1 (R1), the circles (without their interiors);
* Create Region 2 (R2), the disks (without the circle borders).
* Create Region 3 (R3 = R1-R2).
-
![region inference](https://i.stack.imgur.com/ZPHQQ.png)
This is precisely the approach taken below. It produced the 3 figures above.
```
input = "3,1,1 3,2,1.5 1,2,0.7 0.9,1.2,1.2 1,0,0.8";
circles = ((x - #)^2 + (y - #2)^2 == #3^2) & @@@
ToExpression[#~StringSplit~","] &@(StringSplit@input);
R1 = ImplicitRegion[Or @@ circles, {x, y}];
r1 = RegionPlot[R1, PlotLabel -> "R1: circles containing borders",
AspectRatio -> 1, PlotRange -> {{-1, 5}, {-1, 5}}];
innerDisks = ((x - #)^2 + (y - #2)^2 < #3^2) & @@@
ToExpression[#~StringSplit~","] &@(StringSplit@input);
R2 = ImplicitRegion[Or @@ innerDisks, {x, y}];
r2 = RegionPlot[R2, PlotLabel -> "R2: disks within circle borders",
AspectRatio -> 1, PlotRange -> {{-1, 5}, {-1, 5}}];
R3 = RegionDifference[R1, R2]
r3 = RegionPlot[R3, PlotLabel -> "R3 = R1-R2", AspectRatio -> 1,
PlotRange -> {{-1, 5}, {-1, 5}}];
GraphicsGrid[{{r1, r2, r3}}, ImageSize -> 600]
```
Implicit region #1 is the union of the circles.
Implicit region #2 is the union of the disks lying within the circles.
Their difference is the border.
>
> RegionDifference[
>
> ImplicitRegion[(-3 + x)^2 + (-1 + y)^2 ==
> 1 || (-3 + x)^2 + (-2 + y)^2 == 2.25 || (-1 + x)^2 + (-2 + y)^2 ==
> 0.49 || (-0.9 + x)^2 + (-1.2 + y)^2 ==
> 1.44 || (-1 + x)^2 + y^2 == 0.64, {x, y}],
>
> ImplicitRegion[(-3 + x)^2 + (-1 + y)^2 <
> 1 || (-3 + x)^2 + (-2 + y)^2 < 2.25 || (-1 + x)^2 + (-2 + y)^2 <
> 0.49 || (-0.9 + x)^2 + (-1.2 + y)^2 < 1.44 || (-1 + x)^2 + y^2 <
> 0.64, {x, y}]]
>
>
>
---
## Solving by Disk Regions: the engineer's approach (119 chars)
The following takes the union of the disk regions,
discretizes that region, and finds it's boundary. The points in the diagram demarcate the intervals of the Delaunay mesh. We display the discretized region below to highlight the object that furnishes the boundary of interest (the outline of the cloud).
```
s = StringSplit;RegionBoundary@DiscretizeRegion[RegionUnion[Disk[{#, #2}, #3] &@@@
ToExpression[#~s~","] &@(s@InputString[])]]
```
**"3,1,1 3,2,1.5 1,2,0.7 0.9,1.2,1.2 1,0,0.8"**
The region boundary is discretized.
![reg1](https://i.stack.imgur.com/dd5Ab.png)
---
## Solving by Detecting Edges: The Photographer's Approach - 121 chars
![edge detection](https://i.stack.imgur.com/pEgcG.png)
It draws the disks in black, rasterizes the image, detects the edges, and inverts black and white.
```
s=StringSplit;ColorNegate@EdgeDetect@Rasterize@Graphics[Disk[{#,#2},#3]&@@@
((ToExpression/@s[#,","])&/@s[InputString[]])]
```
[Answer]
## Mathematica, ~~175~~ ~~158~~ 149 bytes
```
s=StringSplit;l=ToExpression[#~s~","]&@s@InputString[];RegionPlot[Or@@(Norm@{x-#,y-#2}<#3&@@@l),{x,m=Min@(k={{##}-#3,{##}+#3}&@@@l),M=Max@k},{y,m,M}]
```
I remember from discussion in the sandbox that this approach was supposed to be valid, but I'm not entirely sure how it sits with the new wording of the rules, so @Lilac, let me know if you think this violates the rules.
Basically, I'm creating a logical condition which is true for all points inside the cloud and false for all points outside it. I'm feeding that to `RegionPlot` which then renders the region of all points where the expression is `True` as well as an outline around it.
![enter image description here](https://i.stack.imgur.com/NLLEw.png)
Ungolfed:
```
s = StringSplit;
l = ToExpression[#~s~","] &@s@InputString[];
RegionPlot[
Or @@ (Norm@{x - #, y - #2} < #3 & @@@ l),
{x, m = Min@(k = {{##} - #3, {##} + #3} & @@@ l), M = Max@k},
{y, m, M}
]
```
[Answer]
## Python 3.3 (183 177 164 160 bytes)
```
B=list(map(eval,input().split()))
print("".join(" ## "[sum(any(r*r>(x-d%80/4+10)**2+(y+d//80/4-10)**2for
x,y,r in B)for d in[i,i+1,i+80])]for i in range(6400)))
```
It requires an 80 character wide console, which I know is the default in Windows. It works best if your console has a square font. Here are some excerpts from some of the test inputs.
**Original:**
```
########
## #
## #
##### #
## # #
## #
## #
## #
# #
# ##
# ##
# ## #
# # # ##
# # #####
# #
# ##
# ##
###
```
**Another:**
```
########
### ##
## #
# #
## #
# #
# #
# #
# #
# ##
# #
# ##
# ######
# #
## ### #
# ## # #
# # # #
# ## ## #
### # ##
# #######
# ##
# #
# ##
#####
```
**Hole:**
```
############
### ##
### ##
## #
######## #######
### ##
### ##
## #
## #
## #
## #
## #
## #
## #
## #
# #
## #
# #
## #
# #
# #
# #
# #
# #
# #
## #
## #
# #
## #
# #
## #
# #### #
# ## # #
# ## # #
# ## # #
# # # #
# # # #
# # ## #
# # ## #
# # ## #
# ### #
# ##
# #
# ##
# #
# ##
# ##
# #
# #
# #
# #
# #
# #
# ##
# #
# ##
# #
# ##
# ##
# ##
# ##
# ##
# ##
# ##
# ##
## ###
## ###
####### ########
# ##
## ###
## ###
###########
```
[Answer]
# Python - ~~253~~ ~~249~~ ~~215~~ 199
This is an advertisement for the awesome [shapely](https://pypi.python.org/pypi/Shapely) library, whose geometry operations made writing the solution straightforward by drawing the outline(s) of the union of overlapping circles (=buffered points):
```
from pylab import*
from shapely.geometry import*
c=Point()
for s in raw_input().split():
x,y,r=eval(s)
c=c.union(Point(x,y).buffer(r))
plot(*c.exterior.xy)
for i in c.interiors:
plot(*i.xy)
show()
```
Output:
![three clouds](https://i.stack.imgur.com/rxcqN.png)
Edit(s):
* 249: Replaced `sys.argv[1:]` by `raw_input().split()`, saving a `import sys`
* 215: Removed `k={'color':'k'}` luxury, replaced `savefig` by `show`
* 199: Replaced `map(float,s.split(','))` by `eval(s)`
[Answer]
## Python – 535
```
import math as m
import matplotlib.pyplot as l
c = "3,1,1 3,2,1.5 1,2,0.7 0.9,1.2,1.2 1,0,0.8"
a = [[float(y) for y in x.split(",")] for x in c.split(" ")]
for a2 in a:
for x in xrange(0,200):
q=x*m.pi/100.0
p=(a2[0]+m.sin(q)*a2[2], a2[1]+m.cos(q)*a2[2])
cc = []
for z in a:
if z != a2:
if ((z[0] - p[0]) ** 2 + (z[1] - p[1]) ** 2 ) < (z[2] ** 2) :
cc.append(z)
if not cc:
l.scatter(p[0],p[1])
l.show()
```
[Answer]
## Python – ~~296~~ ~~249~~ ~~231~~ ~~223~~ 212
```
from pylab import*
a=map(eval,raw_input().split())
for x,y,r in a:
for i in range(200):
q=i*pi/100;p=x+r*sin(q);t=y+r*cos(q);[z for z in a if z!=(x,y,r)and(z[0]-p)**2+(z[1]-t)**2<z[2]**2]or scatter(p,t)
show()
```
Credit goes to [@richard-green](https://codegolf.stackexchange.com/users/31714/richard-green) (permission was given) for the original solution, I've just whittled it down a bit.
[Answer]
# JavaScript (E6) + HTML 322
[JSFiddle](http://jsfiddle.net/e6kLsurq/3/)
Each circle is subdivided in about 100 small arcs, and each arc is drawn if its middle point is not inside any of the other circles.
```
<canvas id='c'/>
<script>
t=c.getContext("2d"),z=99,c.width=c.height=400,
l=prompt().split(' ').map(c=>c.split(',').map(v=>40*v)),
l.map(c=>{
for(i=z;--i+z;)
s=4/z,r=c[2],x=c[0]+r*Math.cos(a=i*s),y=c[1]+r*Math.sin(a),
t.beginPath(),
l.some(q=>c!=q&(d=x-q[0],e=y-q[1],d*d+e*e<q[2]*q[2]))||t.arc(z+c[0],z+c[1],r,a-s,a+s),
t.stroke()
})
</script>
```
[Answer]
# Python 274 bytes
This takes input from stdin and checks every point on the display, drawing the pixels one by one as it goes. Not exactly efficient but it follows all the rules.
```
c=[eval(s)for s in raw_input().split()]
import pygame
S=pygame.display.set_mode((500,500))
S.fill([255]*3)
for p in((x,y)for x in range(500)for y in range(500)if 0<min((((x-250)/25.-a)**2+((y-250)/25.-b)**2)**.5-r for(a,b,r)in c)<.1):S.set_at(p,[0]*3)
pygame.display.update()
```
Note that the pygame display will terminate as soon as the drawing is complete, I wasn't sure if I should include it as part of my answer but to view it you can either throw a `raw_input` in at the end or add a little loop if you want to stop the OS from complaining about it not responding and such:
```
alive = True
while alive:
pygame.display.update()
for e in pygame.event.get():
if e.type == pygame.QUIT:
alive = False
```
Example images:
`1,4,2 5,2,1 3,1,1 3.5,2,1.2 3,3,0.7, 1,2,0.7`
![enter image description here](https://i.stack.imgur.com/OD9PM.png)
`0,5,4 3,4,4 4,3,4 5,0,4 4,-3,4 3,-4,4 0,-5,4 -3,-4,4 -4,-3,4 -5,0,4 -4,3,4 -3,4,4`
![enter image description here](https://i.stack.imgur.com/TsEQE.png)
[Answer]
## Perl - 430
```
@e=map{[map{int($_*32)}split',']}(split' ',<>);for$g(@e){for(0..3){($a[$_]>($q=$$g[$_&1]+(($_>>1)*2-1)*$$g[2]))^($_>>1)&&($a[$_]=$q)}}for(2,3){$a[$_]-=$a[$_-2]-1}for(@e){($x,$y,$r)=@$_;$x-=$a[0];$y-=$a[1];for$k($x-$r..$x+$r){for$l($y-$r..$y+$r){$i=(int(sqrt(($x-$k)**2+($y-$l)**2)+0.5)<=>$r)-1;$f[$l][$k]=($j=$f[$l][$k])<-1||$i<-1?-2:$i||$j;}}}print"P1
$a[2] $a[3]
".join("
",map{join' ',map{$_+1?0:1}@$_,('0')x($a[2]-@$_)}@f)."
"
```
Writes a pbm file to stdout.
Test image (converted to png):
![Second test image (converted to png)](https://i.stack.imgur.com/u0RKo.png)
] |
[Question]
[
The [ASCII characters](http://www.asciitable.com/) from decimal code 33 to 126 are:
```
!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~
```
Notice that in most fonts, 25 of these characters have "holes" in them: (a [genus greater than 0](http://en.wikipedia.org/wiki/Genus_(mathematics)#Topology) you might say)
```
#$%&04689@ABDOPQRabdegopq
```
The other 68 "unholed" characters are:
```
!"'()*+,-./12357:;<=>?CEFGHIJKLMNSTUVWXYZ[\]^_`cfhijklmnrstuvwxyz{|}~
```
Your task is to write the shortest program possible using only the unholed characters that outputs each of the holed characters exactly once in any order.
Since Space, Tab and newlines (Line Feed and/or Carriage Return) are empty space they may appear in your program or its output. They still count towards the number of characters. Other ASCII characters may not be used (and certainly not non-ASCII characters).
**Notes**
* You do not have to use all of the unholed characters nor only one of each.
* The output may not contain unholed characters.
* The [Whitespace language](http://en.wikipedia.org/wiki/Whitespace_(programming_language)) may be used.
* Output should go to stdout or can go to a file. There should be no input.
**Bonus:** Just for fun, try printing all the unholed characters using the holed characters. I'm skeptical that it can be done in an existing language.
[Answer]
### GolfScript, 37 36 characters
```
[":=<?)-/! YX[]VIHKx{}|~vih"{25^}/]+
```
Try the code [here](http://golfscript.apphb.com/?c=WyI6PTw%2FKS0vISBZWFtdVklIS3h7fXx%2BdmloInsyNV59L10r&run=true).
The string contains the forbidden characters xor'ed with 25. Fortunately all characters are mapped to valid ones.
[Answer]
# Brainfuck 119
```
--[------->++<]>-.+.+.+.++++++++++.++++.++.++.+.+++++++.+.+.++.+++++++++++.+.+.+.[------>+<]>--.+.++.+.++.++++++++.+.+.
```
[Answer]
## Bonus - dc, 179 characters
Oh good, another restricted character set challenge where `P` is allowed.
```
6A44469PD684P44D4898PDB99P4008D0BP486B48BPA60BPD096P4A68666P460A0D4P690490AP8084088P6B6AB66P6BBB608P80D4BAAPA046PBAD4P60A6668P480DD96P4A040BBP848BP40DD8D0P46840B6P696B48BP48D64BAP
```
Since `dc` is apparently obscure enough to require explaining (strange to me considering the weird stuff around here!) here's an overview:
It's primarily an RPN calculator with arbitrary-precision arithmetic. But for this challenge, I'm making use of the `P` command, which interprets a number as a series of characters in base 256 and prints them. Examples: `65 P` prints `A` (ASCII code 65). `16706 P` prints `AB` (16706=65\*256+66).
Aside from that, the only other interesting feature is that it recognizes all of the hexadecimal digits `0-9A-F` even when they are not contained in a hexadecimal number. Decimal input is the default, so the input token `999` means `9 hundreds + 9 tens + 9` and `ABC` means `10 hundreds + 11 tens + 12` making it equivalent to `1122`.
The ability to use the digits `ABD` in decimal partially makes up for the inability to use `12357`, and the choice of ordering and grouping does the rest. (If I need some numbers `x`,`y`,`z` and they aren't representable with allowed digits, then I try representing `x*256*256+y*256+z` instead.)
The program can probably be made slightly shorter by using larger groups. I didn't go past 3 bytes per number.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 43 35 characters
```
tTFk"*+,-7;=?GHIKVWXYhiklnvwx"C-Ck7
```
Try it [here](http://ideone.com/FPEbsv).
Prints the characters in order except that 9 is at the beginning, newline separated.
String contains all characters 7 greater than the ones needed, except that 9 would become @, so it is special cased. Algorithm thanks to @Howard.
**Explanation:**
```
tT print(10-1) T=10, t(x)=x-1 if x is an int.
Fk"<string>" for k in "<string>":
C-Ck7 print(chr(ord(k)-7)) Note that C is overloaded as ord and chr.
```
[Answer]
# Bash+coreutils, 56 bytes
```
tr \(-y \!-r<<<'*+,-7;=?GHIKVWXYhiklnvwx'
tr C-F 7-:<<<E
```
As luck would have it, adding 7 to the ascii value of the holed characters yields all unholed characters (with the exception of "9"). So we just do this transformation in reverse, then a similar transformation (subtract 12 from "E") to get the "9".
### Output:
```
#$%&0468@ABDOPQRabdegopq
9
```
[Answer]
## Perl - 47 Bytes (thanks @Dom Hastings for the update!)
Perl - 49 Bytes
Edit, 47 bytes:
```
symlink".",':=<?)-/! YX[]VIHKx{}|~vih'^(F^_)x25
```
Original, 49 bytes:
```
symlink".",':=<?)-/! YX[]VIHKx{}|~vih'^chr(25)x25
```
This is pretty much a Perl version of Howard's solution. XORing the string with 25. The output is a file with the name `#$%&04689@ABDOPQRabdegopq`. I got the idea to use `symlink` and the file name as the output format because everything else is banned.
Here's another Perl solution I came up with. It can probably be improved a lot and it is pretty long, so I'm leaving in a readable format for now.
```
until(y/1/1/>32){s//1/}
until(y/1/1/>125+1){
if(chr(y/1/1/)!~/[!"'()*+,-.\/12357:;<=>?CEFGHIJKLMNSTUVWXYZ[\\\]^_`cfhijklmnrstuvwxyz{|}~]/) {
symlink".",chr y/1/1/;
}
s/^/1/
}
```
This one outputs many files, the name of each one is one of the characters. I couldn't figure out how to append strings without using a forbidden character.
`for`, `while`, `map`, `say`, `print`, `eval`, `s///e`, and any variable name cannot be used (variables start with `@` or `$` in Perl) which made this difficult.
Hopefully file names are okay as an output format because I'm pretty sure every other way to output information uses one of the banned characters.
[Answer]
# MATLAB, 36 bytes
SO CLOSE.... Only 1 byte more than the current winner (isaacg)! Which, on further inspection, already did what I set out to do too. Well, no harm in reinventing the wheel...
I know this is an old challenge, but I only realized that *after* I got interested in it.
```
['*+,-7;=?GHIKVWXYhiklnvwx'-7,57,'']
```
If only I could get MATLAB to understand that I want a string without a separate `''`...
suggestions, anyone?
[Answer]
# Brainfuck 303 275
```
++++++++[>+>++>+++>++++>+++++>++++++>+++++++>++++++++>+++++++++>++++++++++>+++++++++++>++++++++++++>+++++++++++++>++++++++++++++>+++++++++++++++>++++++++++++++++<<<<<<<<<<<<<<<<-]>>>>+++.--->----.+.+.++>.>----.++.++.+.->.+.+.-->----.++++>-.+.+.+.-->>+.+.-->----.+.++.+>-.+.+.
```
Brainfuck, the ultimate unholed esoteric language (apart from Whitespace) ;)
[Answer]
# JS - 196 - [try it](http://jsfiddle.net/3H9FZ/)
```
h=(c=!1+[])[1];i=c[2*2];j=(f=[]+{})[1];this[i+'v'+h+'l'](h+'l'+i+'rt('+h+'t'+j+f[2]+'("Iy\x51lJj\\x'+2*2+'1\\x3'+~-1+'Nj\\x'+2*3+'75\x51EFC\x52E\\x3'+3*3+'\x51UVJhYm\x52lZ2\\x3'+3*3+'wc\x51=="))')
```
[Answer]
# GolfScript, 89 characters
```
71 22+,{33+}/]''+'!"\'()*+,-./12357:;<=>?CEFGHIJKLMNSTUVWXYZ[\]^_`cfhijklmnrstuvwxyz{|}'-
```
Simply builds an array of all ASCII characters and subtracts the non-"holed" characters from them.
```
71 22+, # Builds array of 0..93
{33+}/] # Converts to 33..126
''+ # Convert ASCII codes to string
'stuff'- # Subtracts "stuff" (the non-holed characters) from the string
```
[Answer]
# Befunge 98 - 69 bytes
```
"()+ijWI=*">:5j2 ,-5_"157:h">:5j2 ,-1_"=>?LMN^_lmn">:5j2 ,+3_"?"1+s <
```
Does it in 3 parts. One where unholed character values differ from holed character by 5. Then the ones that differ by 1, and finally a list of unholed characters that differ by 3 from holed ones. The terminate program instruction in Befunge is "@" (char value 64), so at the end I load "?" (char value 63) add 1 then put that in the code with the instruction 's'.
I could maybe golf it more by consolidating the three
```
>:5j2 ,(differ value)_
```
section, but probably not by much.
[Answer]
# Main - [Insomnia](http://esolangs.org/wiki/Insomnia), 50
```
FFy~~jF~y<={*n<<ztf>={.f=(tHL~k<yf={*n>Lj(FunLn<j~
```
It outputs:
```
abdegopq04689@ABDOPQR#$%&
```
# Bonus - Insomnia, 268
```
ogeeoddp@poe@ggep@oe@opge@gee@%d@p@gqeo@p@ge@e9de49ed9e4dppe@%e@geee@ge@p%ee@%e@dp@%ep@%ee@%d@%eeee@%e@%ee@%e@geee@%e@gee@ggopop@peo@ggep@p@ge@ggeep@ge@gee@%e@geee@ge@gee@ge@ppoep@%ee@%edep@gepe@ge@%ee@%e@geee@ge@%ee@%%eeoe@ge@pep@%gep@p@%e@%%eep@%e@gee@e%e@oe@%gep@p@
```
It outputs:
```
!"'()*+,-./12357:;<=>?CEFGHIJKLMNSTUVWXYZ[\]^_`cfhijklmnrstuvwxyz{|}~
```
I think it should be possible to reduce the length of the program if the output is rearranged, but I need to modify my search program to do this.
Just to show case another language which is capable of operate with a restricted number of characters. By the way, it can write just about any output with only 3 unique characters in the source.
Currently, this is the only language that can do both the main challenge and the bonus among all the existing answers.
[**Insomnia Interpreter**](https://codegolf.stackexchange.com/questions/40073/making-future-posts-runnable-online-with-stack-snippets/41868#41868).
[Answer]
# Befunge 98 - 46 bytes
Befunge-ified version of isaacg's Pyth entry:
```
"xwvnlkihYXWVKIHG?=;7-,+*">:5j2 ,-7_"?"1+:,s <
```
[Answer]
# JavaScript 240 228
Initial submission:
`z=(!1+"")[1];y=(!!1+"")[3];x={}+"";w=x[1];v=x[2];u=z+"t"+w+v;1[_="c\157nstruct\157r"][_](z+'l'+y+'rt('+u+'("Iy\x51lJj"+'+(t=u+'("\x51\x51==")')+'+'+u+'("M"+'+t+'+"==")+"Nj"+'+u+'("Zw==")+"5\x51EFC\x52E\71\x51UVJhYm\x52lZ2\71wc\x51=="))')()`
Now, this is a great start, here's how it breaks down...
```
z=(!1+"")[1]; // assigns "a" to z, !1+"" === "false"
y=(!!1+"")[3]; // assigns "e" to y, !!1 === "true"
x={}+""; // assigns "[object Object]" to x
w=x[1];v=x[2] // assigns "o" to w, and "b" to v
u=z+"t"+w+v; // creates the mystical "atob" command, yes, I'm gonna use it!
1[_="c\157nstruct\157r"][_] // sets up the primitive to a number object... this acts similar to the "window" primitive object so that I can play off functions...
z+'l'+y+'rt( // starts creating an alert call
'+u+'("Iy\x51lJj"+'+(t=u+'("\x51\x51==")')+'+'+u+'("M"+'+t+'+"==")+"Nj"+'+u+'("Zw==")+"5\x51EFC\x52E\71\x51UVJhYm\x52lZ2\71wc\x51=="))')()
// Above line abuses atob command with a couple of nested instances of the command, also using hex and octal equivalents of characters
```
And then I thought... "There must be a simpler way..." and there is...
Revised submission:
`z=(!1+"")[1];y=(!!1+"")[3];x={}+"";w=x[1];v=x[2];u=z+"t"+w+v;this[y+"v"+z+"l"](z+'l'+y+'rt('+u+'("Iy\x51lJj"+'+(t=u+'("\x51\x51==")')+'+'+u+'("M"+'+t+'+"==")+"Nj"+'+u+'("Zw==")+"5\x51EFC\x52E\71\x51UVJhYm\x52lZ2\71wc\x51=="))')`
Seeing I can use `eval` (by piecing it together, inspiration from @bebe; which is a lot quicker than using the `constructor` of a `constructor` of a `number`... ) I drilled it down to 228... I know it may not win this particular Golf Challenge, but this is just my way of showing how much you can abuse JavaScript, and still get the desired result...
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 33 bytes
```
7+2+"*+,-7;=?GHIKVWXYhiklnvwx"c-7
```
[Try it online!](https://ethproductions.github.io/japt/?v=1.4.5&code=NysyKyIqKywtNzs9P0dISUtWV1hZaGlrbG52d3giYy03&input=)
Same algorithm as [isaacg's Pyth submission](https://codegolf.stackexchange.com/a/35312/78410), just happens to be shorter in Japt.
### How it works
```
7+2+"*+,-7;=?GHIKVWXYhiklnvwx"c-7
7+2 Obviously the number 9
"..."c-7 Apply -7 on each char's charcode of this string
+ String concatenation
```
Yes, it's JS, which is [one of the most abusable languages](https://codegolf.stackexchange.com/questions/35310/write-the-whole-of-the-holed-using-the-unholed#comment76692_35351), just shorter (and you don't need `alert` or `console.log` here).
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal) `s`, 33 bytes
```
`*+,-7;=?GHIKVWXYhiklnvwx`C7-57JC
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=s&code=%60*%2B%2C-7%3B%3D%3FGHIKVWXYhiklnvwx%60C7-57JC&inputs=&header=&footer=)
Uses the same (independently discovered) trick of subtracting 7 and putting a 9 on the end.
[Answer]
# [PHP](https://php.net/), 59 bytes
```
<?='MMMMMMMMMM:::::::::::::::'^"nihk}y{ut\r{x~ujkh[X^_]UJK";
```
[Try it online!](https://tio.run/##K8go@P/fxt5W3RcOrFCBepxSXmZGdm1ldWlJTFF1RV1pVnZGdERcfGyol7eS9f//AA "PHP – Try It Online")
## Explanation
Utilises the string-XOR operator (`^`) to build the desired string from non-holed letters, output via `<?=`.
[Verification for 59 bytes.](https://tio.run/##fZBNawIxEIbv@ytevOS0optMsq5bvbf0WChULckmErWo2C7dIu1f3ya6FMHie5jveQbG6Hfftk1jkR4wgd@9OZvW25Pv7/0eZVmCDToV4BVfgttMQVhh/zVccw2U0zs2Y@zxT0WRnCHDiIkzN0zgk8syoLhUBC56HSYLGOnkCDKXBsqqEZRRBCUGNkY5lAup1KGL7cpvvr@O9Uf/2PzU603H4JGRkwHl5EBLsiASGsKE2zzsXcq/PC9e50/3D70xGyefFdLq@l9J/NlVtW1/AQ "Bash – Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/), 72 bytes
```
*_=*~;("*,*E'syswrit\LE"^icx)->(uc,':=<?)-/! YX[]VIHKx{}|~vih'^(F^_)x25)
```
[Try it online!](https://tio.run/##K0gtyjH9/18r3larzlpDSUtHy1W9uLK4vCizJMbHVSkuM7lCU9dOozRZR93K1sZeU1dfUSEyIjo2zNPDu6K6tqauLDNDPU7DLS5es8LIVPP/fwA "Perl 5 – Try It Online")
## Explanation
I know this is longer than the existing Perl answer, but this outputs using STDOUT, rather than a filename.
`*_=*~` aliases the `~` variables (`@`, `%`, and `$`) into `_`, meaning that `$*` (which is `STDOUT` by default) is now in `$_`, which we can access using `uc` (which returns `$_` by default if no arguments are passed). Next the string `CORE::syswrite` is built from a combination of the stringwise-XOR of the two strings and the in-line lowercase modifier (`\L`) of `E`, which is then called as a function `->(`...`)` with the arguments `STDOUT` (from `uc`) and the desired string, also built via stringwise-XOR (copied from [@hmatt1's answer](https://codegolf.stackexchange.com/a/35358/9365) and amended to to save bytes using more stringwise-XOR).
[Answer]
# PICO-8, 196 bytes
```
c=77+2?"\35\37\52\57\111\112\113\71"..chr(33+3)..chr(31+7)..chr(32*2)..chr(72-7)..chr(71-5)..chr(71-3)..chr(71-2)..chr(c)..chr(c+1)..chr(c+2)..chr(75+22)..chr(75+23)..chr(c+21)..chr(57*2)..2*13*31
```
More variables like `c` might reduce size, not in the mood to try more at the moment.
] |
[Question]
[
You may remember in first or second grade using **expanded form** to learn about place value of numbers. It's easier to explain with an example, so consider the number `123`. In expanded form it is represented as `100 + 20 + 3`, which helps a young mind visualize place value. It is reminiscent of how you say it: one hundred (plus) twenty (plus) three.
We can extend this past the units place with decimals: `2.718 => 2 + 0.7 + 0.01 + 0.008`
Your challenge is to write a program or function that takes a positive floating point number or zero (assume it is as large or precise as your language can handle; it will not be in scientific notation) or string and prints/returns it in expanded form as explained above.
You need neither spaces between the `+`'s nor the zero before the decimal point, so the example above could be `2+.7+.01+.008`. Values that would be equal to zero must be omitted (`101.01 => 100 + 1 + 0.01`) unless the input is zero (see below).
Values should not have more than one leading zero before the decimal point or any trailing zeroes after it (no-no's: `0060, 0000.2, 30., 30.000, .0400`). The input will conform to this too.
Since first-graders have short attention spans, your code will have to be as short as possible.
## Test cases
```
0 => 0
6 => 6
0.99 => 0.9 + 0.09
24601 => 20000 + 4000 + 600 + 1
6.283 => 6 + 0.2 + 0.08 + 0.003
9000000.0000009 => 9000000 + 0.0000009
```
[Answer]
# CJam, ~~33~~ 26 bytes
```
r_ee\'0fe<f{\~t~}{},'+*0e|
```
This won't work with the Java interpreter; it print floats differently. Try it with the [CJam interpreter](http://cjam.aditsu.net/#code=r_ee%5C'0fe%3Cf%7B%5C~t~%7D%7B%7D%2C'%2B*0e%7C&input=6.283).
The last test case prints `9000000+9e-7`, which has been [ruled valid by @NinjaBearMonkey](https://codegolf.stackexchange.com/questions/68939/expand-the-number/69738#comment169909_68939).
*Thanks to @jimmy23013 for golfing off 7 bytes!*
### How it works
```
r_ Read a token from STDIN and push a copy.
ee Enumerate its characters, i.e., push the array of all
[index character] pairs.
\ Swap the original input on top of the stack.
'0fe< Perform vectorized minimum with the character '0'.
This replaces all digits with '0', but leaves '.'
untouched, since `.' < '0'.
f{ } For each [index character] pair, push the pair and the
string of zeroes and (possibly) a dot; then:
\ Swap the pair on top of the stack.
~ Dump index and character on the stack.
t Replace the string's element at that index with
that character.
~ Evaluate the resulting string.
{}, Filter the array to remove zeroes.
'+* Join, using '+' as separator.
0e| If the result is empty, replace it with 0.
```
[Answer]
# JavaScript (ES7), 102 bytes
```
n=>+n&&[...n.replace(/^\.0*|\./,"")].map(f=d=>10**p--*d,p=Math.floor(Math.log10(n))).filter(f).join`+`
```
## Explanation
Requires the number to be input as a string without leading zeroes (unless the number *is* `0` of course).
Note: Because of floating-point weirdness some numbers (like `.3`) come out wrong, but theoretically this works for any number.
```
n=> // n = input number as string
+n&& // return 0 if n = 0
[...n.replace(/^\.0*|\./,"")] // remove leading zeroes after the decimal place
.map(f=d=> // for each digit d in n
10**p--*d, // raise the digit to the correct power of 10
p=Math.floor(Math.log10(n)) // p = power of 10 for the first digit, floor needs to be
) // used instead of |0 due to negative powers of 10 :(
.filter(f) // remove zeroes, the map function is reused
.join`+` // return the output numbers joined with +
```
## Test
Test uses `Math.pow` instead of `**` for browser compatibility.
```
var solution = n=>+n&&[...n.replace(/^\.0*|\./,"")].map(f=d=>Math.pow(10,p--)*d,p=Math.floor(Math.log10(n))).filter(f).join`+`
```
```
<input type="number" oninput="result.textContent=solution(this.value)">
<pre id="result"></pre>
```
[Answer]
## [Retina](https://github.com/mbuettner/retina/), ~~86~~ ~~77~~ 75 bytes
Byte count assumes that the source is encoded as ISO 8859-1.
```
S_`.(?<=(\.\d+))|(?=(\d*)).
Tm`d`0`\..+\B|(?<=^\d).+
¶([.0]+¶)*
+
^0.|\+0$
```
The trailing linefeed is significant.
[Try it online.](http://retina.tryitonline.net/#code=U19gLig_PD0oXC5cZCspKXwoPz0oXGQqKSkuClRtYGRgMGBcLi4rXEJ8KD88PV5cZCkuKwrCtihbLjBdK8K2KSoKKwpeMC58XCswJAo&input=OTA3MC4xMzQ5)
### Explanation
```
S_`.(?<=(\.\d+))|(?=(\d*)).
```
We start by turning the input into a linefeed separate list of components, although only the leading (or trailing) digit is correct. This is done by abusing a split stage. Instead of splitting the input we match all of it, so the remaining segments are all empty. We remove those empty segments with the `_` option. The catch is that split stages also return the values of all capturing groups. So we use a lookahead at each match to capture the correct part of the string: first we try to find a `.` left of the match. If that's the case, we capture everything from the `.` up to and including the digit we're currently matching. Otherwise, we must be in the integer part of the input, so we capture all the numbers after the match (including the match). We must also get rid of the decimal point itself, so the second capture is optional. If there are no `\d` to be capture, this will simply remove the match from the input.
```
Tm`d`0`\..+\B|(?<!=\d).+
```
Now we use a transliteration stage to turn all but the leading/trailing digits into zeroes. We either match a component that's less than 1 with `\..+\B` where the `\B` ensures that we stop the match one digit before the end, or we match an integer part with `(?<=^\d).+` where the lookbehind ensures that we start one digit into the number. The transliteration stage will then replace any digits (`d`) with zeroes inside the matches.
```
¶([.0]+¶)*
+
```
Now the actual output format should use `+` not linefeeds as separators. The `¶` matches a linefeed to do that substitution. While we're at it, we also remove lines that contain only `0`s and `.`s.
```
^0.|\+0$
```
The previous stage does not remove a leading or trailing `0` (because those do not have a linefeed before and after them), so we remove those explicitly.
[Answer]
# Python 2, ~~216~~ ~~210~~ ~~196~~ 175 bytes
Here is some slightly golfed code that I will golf further when I get time. It uses string analysis.
```
i=input().split(".")
I=i[0]
e=enumerate
o=[(k+len(I[j+1::])*"0") for j,k in e(I) if k!="0"]
try:o+=["."+l*"0"+m for l,m in e(i[1]) if m!="0"]
except:0
print "+".join(o or"0")
```
**Explanation**
So, the input is seperated into a integer and decimal part. Then, there is a for loop list comprehension. On the integer part, the length of the string after a character in the decimal is multiplied by "0" to get that many zeros at the end if that character.
For the decimal part, the index of the current character is the number of zeros before it and so that part is simple.
The try and except is used to determine whether it has a decimal part or not (using an error).
The final result is joined with plus signs.
[Try it here!](http://ideone.com/AQeVk5)
[Answer]
# Pyth, 30 bytes
```
L.xvbytb|j\+fT.eyXXzjkUT\0kbzz
```
[Test suite](https://pyth.herokuapp.com/?code=L.xvbytb%7Cj%5C%2BfT.eyXXzjkUT%5C0kbzz&test_suite=1&test_suite_input=0%0A6%0A0.99%0A24601%0A6.283+%0A9000000.0000009&debug=0)
The basic solution here is to replace all of the digits in the input with `0`, then insert each digit at the proper location, eval, filter out the zeros, and join on pluses. Unfortunately, Pyth's eval function doesn't accept leading zeros currently. I will be working to fix this.
To get past this problem, I added a helper function, `y`, which recursively retries the eval until no error is thrown, removing the first digit every time. Note that this function will loop infinitely on invalid input.
Also, a special case was needed for the input `0`.
All in all, I think the code's pretty good, but the language facilities could be better. Who wants errors?
[Answer]
# Python 3, 138
This is loosely based on TanMath/Ogaday's approach of reading the number as a string and parsing it out that way. I have to use star assignment on `i` so that it correctly handles integers.
```
j,*i=input().split(".")
e=enumerate
z="0"
print("+".join([(x+len(j[y+1:])*z)for y,x in e(j)if x>z]+["."+o*z+p for o,p in e(i)if p>z]or z))
```
[Answer]
# Python, ~~141~~ ~~132~~ 128 bytes
This one is still relatively readable. Convert to string and handle the `>1` digits separately from the `<1` digits. We also have a special case for zero. I could remove two more spaces below, but I like keeping it pretty.
The downside is that it will breakdown for floats with more than 9 decimal places.
```
x=str(int(a*1e9))
l=len(x)-10
z="0"
print"+".join([(j+z*(l-i))if l>=i
else"."+z*(i-l-1)+j
for i,j in enumerate(x)if j!=z]or z)
```
Below is the original. First edit was to shorten the zero special case, second edit was to remove the 0 before the decimal, third was to remove some extra parenthesis and spaces.
```
x=str(int(a*1e9))
l=len(x)-10
z="0"
print "+".join([(j+z*(l-i)) if l>=i
else ("0."+z*(i-l-1)+j)
for i,j in enumerate(x) if j!=z]) if a else z
```
Explanation:
```
x=str(int(a*1e9)) # Convert into a string with nine decimals
l=len(x)-10
z="0"
print "+".join([
(j+z*(l-i)) if l>=i # Print numbers greater than 1
else ("0."+z*(i-l-1)+j) # Print less than one
for i,j in enumerate(x) if j!=z
]) if a else z # Special case zero
```
[Answer]
# Mathematica, 81 bytes
```
Inactive@Plus@@(10.^Range[#2-1,#2-Length@#,-1]#/.{0.->Nothing[]})&@@RealDigits@#&
```
Test case:
```
%[101.01]
(* 100. + 1. + 0.01 *)
```
[Answer]
# CJam, 44 bytes
```
r:TdLT'.-{'0f+IaaI~g*+}fI:dATW%'.##m]f/'+*e&
```
[Try it here.](http://cjam.aditsu.net/#code=r%3ATdLT%27.-%7B%270f%2BIaaI%7Eg*%2B%7DfI%3AdATW%25%27.%23%23m%5Df%2F%27%2B*e%26&input=24601.283)
It fails the last test case, and outputs the following:
```
9000000+9e-7
```
But let's say it's too precise that CJam cannot handle it.
### Explanation
```
r:Td
LT'.- e# Remove the period if any.
{ e# For each character I:
'0f+ e# Append 0 to each previous string.
IaaI~g*+ e# Append I as a string if I isn't '0.
}fI
:d e# Convert each string to float.
ATW%'.## e# 10 to the kth power where k is the position of the period from the end.
m] e# Round up, so it becomes 1 if no periods are found.
f/ e# Divide each float by this number.
'+*e& e# Format and the 0 special case.
```
[Answer]
# Python 3, ~~187~~ ~~180~~ ~~173~~ 154 bytes
Managed to golf a good 19 bytes off thanks to @Thomas Kwa's suggestions above about `result or['0']`, plus rearranging some algebra (**154 bytes**):
```
def f(n):
*m,=n;o='0'
try:p=m.index('.');m.pop(p)
except:p=len(m)
return'+'.join([['.'+o*(i-p)+d,d+o*(p-i-1)][p>i]for i,d in enumerate(m)if d!=o])or o
```
~~My best attempt so far~~ (**173 bytes**). Based upon new approach, see bottom of post:
```
def f(n):
*m,=n;o='0'
try:p=m.index('.');m.pop(p)
except:p=len(m)
return(o,'+'.join([['.'+o*(-1*(p-i))+d,d+o*(p-i-1)][p-i>0]for i,d in enumerate(m)if d!=o]))[eval(n)!=0]
```
golfed my original down to **180 bytes**:
```
def f(n):x=n.split('.');a,b=(x+[''],x)[len(x)-1];e=enumerate;return('0',"+".join([d+'0'*i for i,d in e(a[::-1])if d!='0'][::-1]+['.'+'0'*i+d for i,d in e(b)if d!='0']))[eval(n)!=0]
```
I learnt a new language feature today doing this! Conditionals via boolean indexing. I may have slightly overdone it.
I tried abstracting out the comprehensions, but I couldn't make it any shorter (**196 bytes**):
```
e=lambda s:[d+'0'*(len(s)-i-1) for i,d in enumerate(s) if eval(d)]
def f(n):x=n.split('.');a,b=(x+[''],x)[len(x)-1];return['0',"+".join(e(a)+['.'+d[::-1]for d in e(b[::-1])][::-1])][bool(eval(n))]
```
(Reversing sequences is expensive!)
Whilst mine is shorter for now, I think TanMath can golf his down to match mine: Using `e=enumerate`, replacing `pass` with `0`, and using `'0'` in place of `['0']` in the return statement should save 4+3+2=9 bytes! Taking it down to 187. I'm sure another few bytes can be shaved off somewhere...
**edit** New approach (**156 bytes**). However, it can only deal with precision up to 6dp similar to @jimmy23013's CJam entry, so it fails the final test. I couldn't coerce it to print more 0s, maybe someone else can. Instead I used it as the basis of my best attempt yet, see top (Also, this approach prints the 0 before the decimal place, but that seems valid as well.). Took the `try:... except:...` approach from TanMath:
```
def f(n):
*m,=n
try:p=m.index('.');m.pop(p)
except:p=len(m)
return('0','+'.join([str(eval(d)*10**(p-i-1))for i,d in enumerate(m)if d!='0']))[eval(n)!=0]
```
[Answer]
### pure bash, 210
```
o= a=${1%.*} b=${1#$a};while [ "$a" ];do c=${a:1};((${a%$c}>0))&&o+=${a%$c}${c//?/0}+;a=$c;done;[ "$b" ]&&{ b=${b#.} a=;while [ "$b" ];do c=${b:0:1};((c>0))&&o+=.$a$c+;b=${b:1};a+=0;done;};o=${o%+};echo ${o:-0}
```
or
```
o= a=${1%.*} b=${1#$a};while [ "$a" ];do c=${a:1};((${a%$c}>0))&&
o+=${a%$c}${c//?/0}+;a=$c;done;[ "$b" ]&&{ b=${b#.} a=;while [ "$b" ]
do c=${b:0:1};((c>0))&&o+=.$a$c+;b=${b:1};a+=0;done;};o=${o%+};echo ${o:-0}
```
Test:
```
exp() {
o= a=${1%.*} b=${1#$a};while [ "$a" ];do c=${a:1};((${a%$c}>0))&&
o+=${a%$c}${c//?/0}+;a=$c;done;[ "$b" ]&&{ b=${b#.} a=;while [ "$b" ]
do c=${b:0:1};((c>0))&&o+=.$a$c+;b=${b:1};a+=0;done;};o=${o%+};echo ${o:-0}
}
while read num;do
printf "%-12s => " $num
exp $num
done <<<$'0\n6\n0.99\n24601\n6.283\n9000000.0000009\n3.1415\n.99'
0 => 0
6 => 6
0.99 => .9+.09
24601 => 20000+4000+600+1
6.283 => 6+.2+.08+.003
9000000.0000009 => 9000000+.0000009
3.1415 => 3+.1+.04+.001+.0005
.99 => .9+.09
```
[Answer]
# Python, 131 bytes
```
f=lambda s,k=0,i=0,o="",z="0":s and f(s[1:],(s<z)+k,i+k,o+(s>="1")*([s[0]+~-(s+".").find(".")*z,"."+z*i+s[0]][k]+"+"))or o[:-1]or z
```
A really, really messy recursive function, probably not the best way to go about this. Input like `f("10.0203")`.
[Answer]
# C, ~~155~~ ~~153~~ 161 bytes
+2 to link in the math library (source itself is 159).
```
main(d,v,p,q)char**v,*p,*q;{for(p=strchr(q=v[1],46),d=p?p-q:strlen(q);*q;++q)*q^46?printf(*q^48|q==v[1]?"%.*f%c":"",d<0?-d:0,(*q-48)*pow(10,--d),q[1]?43:0):0;}
```
## Ungolfed
```
int main(int d, char **v, char *p, char *q)
{
for(q = v[1], /* Cache the input string */
p = strchr(q,'.'), /* find the decimal */
d = p ? p-q : strlen(q); /* calculate number of digits before decimal */
*q; /* loop while still input data */
++q) /* iterate to next character */
{
*q^46 /* if not at the decimal point... */
? printf(*q^48 || q == v[1] /* if not a zero, or if the string itself is zero... */
? "%.f%c" /* print the digit */
: "", /* else print nothing */
d<0 ? -d : 0, /* Calculate number of places after decimal to print */
(*q-48)*pow(10,--d), /* Calculate the digit at the desired power of 10 */
q[1]?43:0) /* If the next character is still valid input, print the '+' */
: 0 /* else, do nothing */
}
}
```
[Answer]
# [Dyalog APL](http://goo.gl/9KrKoM), 47 bytes
```
{×⍎⍵:1↓∊'+',¨0~⍨(⍎¨w)×10*(⍵⍳'.')-1+⍳≢w←⍵~'.'⋄0}
```
Takes number in character vector form, e.g. `'123'`.
Examples:
```
f←{×⍎⍵:1↓∊'+',¨0~⍨(⍎¨w)×10*(⍵⍳'.')-1+⍳≢w←⍵~'.'⋄0}
↑⍕¨f¨,¨'0' '6' '0.99' '24601' '6.283' '900000.000009'
0
6
0.9 + 0.09
20000 + 4000 + 600 + 1
6 + 0.2 + 0.08 + 0.003
900000 + 0.000009
```
Notes:
○ The reason for the modified last example is that APL, like some of the other submissions, by default will switch to scientific notation for such extreme numbers.
○ The phrase `↑⍕¨f¨,¨` is only needed to process all examples at once.
[Answer]
# Retina, 113 bytes
Currently much longer than [Martin's solution](https://codegolf.stackexchange.com/a/69636/7311) but uses a different method so I decided to post it.
```
^
x
S_`(?<=(.*)).(?=(.*))
x
¶\..*¶.*
$
¶
T`d`0`(?<=\d).*¶.*¶
(.*)¶(.*)¶
$2$1¶
(\..*?)0*¶
$1¶
\.?¶0*
¶
¶+
+
\+$
[empty line]
```
[Try it online here.](http://retina.tryitonline.net/)
[Answer]
### perl, 132 bytes
131 +1 for `-p` switch.
This is based on [my previous `sed` answer](https://codegolf.stackexchange.com/a/69750/9424):
```
1while s/^([1-9]\d*)([1-9])(0*)([+.].*|)$/${1}0$3+$2$3$4/||s/([1-9]0*)\.([0-9])/$1+.$2/||s/\.(0*)([1-9])(\d*[1-9])$/.$1$2+.${1}0$3/
```
Test suite:
```
perl -pe'1while s/^([1-9]\d*)([1-9])(0*)([+.].*|)$/${1}0$3+$2$3$4/||
s/([1-9]0*)\.([0-9])/$1+.$2/||s/\.(0*)([1-9])(\d*[1-9])$/.$1$2+.${1}0$3/
' <<<$'0\n6\n0.99\n24601\n6.283\n9000000.0000009\n3.1415'
0
6
0.9+.09
20000+4000+600+1
6+.2+.08+.003
9000000+.0000009
3+.1+.04+.001+.0005
```
[Answer]
## Powershell - ~~172~~ ~~166~~ 193 bytes
All on a single line:
```
$z=([string]$args[0])-split"\.";$y=$z[0].length-1+0.6;($z|%{$x=[char[]]$_;if($y-gt0){($x|%{$_+"0"*(-1+$y--)})}else{($x|%{"0."+"0"*[math]::abs($y--)+$_})}}|?{-not($_-match'^[0.]+$')})-join' + '
```
Ungolfed:
```
$z=([string]$args[0]) -split "\."
$y=$z[0].length-1+0.6
($z | %{
$x=[char[]]$_
if($y -gt 0) {
($x | %{$_+"0"*(-1+$y--)})
} else {
($x | %{"0."+"0"*[math]::abs($y--)+$_})
}
} | ?{ -not($_ -match '^[0.]+$')}) -join ' + '
```
Test cases, plus one additional:
```
PS> (0, 6, 0.99, 24601, 6.283, 9000000.0000009, [math]::pi) | %{.\expand.ps1 $_}
6
0.9 + 0.09
20000 + 4000 + 600 + 1
6 + 0.2 + 0.08 + 0.003
9000000 + 0.0000009
3 + 0.1 + 0.04 + 0.001 + 0.0005 + 0.00009 + 0.000002 + 0.0000006 + 0.00000005 + 0.000000003 + 0.0000000005 + 0.00 000000008 + 0.000000000009 + 0.0000000000007 + 0.00000000000009
PS>
```
[Answer]
## Perl, 248 bytes
Ew, I am noobish at Perl golfing.
```
@a=split/\./,<>;
@b=split``,$a[1];
@c=split``,$a[0];
for($i=0;$i<length$a[0];$i++){
$_.=($c[$i]!=0)?$c[$i]."0"x((length$a[0])-$i-2)."+":"";
}
for($i=1;$i<=length$a[1];$i++){
$_.=($b[$i-1]!=0)?"0."."0"x($i-1).$b[$i-1]."+":"";
}
chop;
($_=="")?print"0 ":print;
```
[Try it here.](https://ideone.com/zkYvCB)
[Answer]
# Java, ~~284~~ ~~244~~ 243 Bytes
```
String x(String s){int b=s.length(),d=(d=s.indexOf(46))<0?b:d,i=-1,k=0;String o="";for(char c;++i<b;)o+=(c=s.charAt(i))>48?(k++>0?" + ":"")+(d-i>0?c:"0.")+new String(new char[Math.abs(d-i)-1]).replace('\0','0')+(d-i>0?"":c):"";return b<2?s:o;}
```
~~Unfortunately, I could not find a shorter way of creating repeating Strings than:~~
* ~~build a `char[]` of the required length~~
* ~~use `Arrays.fill` to set the characters~~
* ~~use `new String` so it can be concatenated~~
With inspiration by @Khaled A Khunaifer, I could shave off 40 Bytes.
Edit: `indexOf` takes an int, so I could replace `'.'` with `46`.
Unfortunately, this does not seem to be possible with `replace`.
[Answer]
# Python, 125 bytes
After deleting my 1st answer (sry!) which could not handle small numbers due to machine epsilon issues, I found a different solution. It handles float as well as integers, trailing zeros (!) and is written as function.
Thanks to @ogaday for the useful hints and for the compact '0'-fix!
Golfed:
```
def f(x):x+='.';i=x.find('.');z=list(x);del z[i];return'+'.join([str(int(o)*10**(i-j-1))for j,o in enumerate(z)if'0'<o])or'0'
```
Ungolfed:
```
def f(x):
x+='.'
i=x.find('.')
z=list(x)
del z[i]
return '+'.join([str(int(o)*10**(i-j-1)) for j,o in enumerate(z) if '0'<o]) or '0'
```
Usage:
```
>>> f("0")
'0'
>>> f("32.005")
'30+2+0.005'
>>> f("100020003000009000000.0007")
'100000000000000000000+20000000000000000+3000000000000+9000000+0.0007'
>>> f("1000000000009000000.0007000000000000000002")
'1000000000000000000+9000000+0.0007+2e-22'
>>> f("0001.99")
'1+0.9+0.09'
```
[Answer]
# CoffeeScript, 144 bytes
Straight forward solution:
```
X=(n)->[m,k]="#{n}".split '.';(c+Array(m.length-i).join 0for i,c of m when+c).concat(".#{Array(++i).join 0}"+c for i,c of k when+c).join('+')||0
```
### Executable:
```
<script src="http://coffeescript.org/extras/coffee-script.js"></script>
<script type="text/coffeescript">
X=(n)->[m,k]="#{n}".split '.';(c+Array(m.length-i).join 0for i,c of m when+c).concat(".#{Array(++i).join 0}"+c for i,c of k when+c).join('+')||0
# Tests follow
tests = [
0
6
0.99
24601
6.283
9000000.0000009
]
window.solution = X
result.textContent=("#{n} => #{X n}" for n in tests).join '\n'
</script>
<input type="number" oninput="result.textContent=solution(this.value)">
<pre id="result"></pre>
```
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 18 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
ºî≤FlφLfÜG→\ΦUq╜♥←
```
[Run and debug it](https://staxlang.xyz/#p=a78cf3466ced4c669a471a5ce85571bd031b&i=0%0A6%0A0.99%0A24601%0A6.283%0A9000000.0000009&a=1&m=2)
Unpacked, ungolfed, and commented, it looks like this.
```
c copy input
!C terminate if input is falsy
y{ for each character in the string input...
y.\d'0R replace each digit in the input with "0"
ia& then replace the nth character back to its original value
e eval as float
m map using block to produce array
{f filter out zeroes
'+* join with "+"
```
[Run this one](https://staxlang.xyz/#c=c++++++++%09copy+input%0A%21C+++++++%09terminate+if+input+is+falsy%0Ay%7B+++++++%09for+each+character+in+the+string+input...%0A++y.%5Cd%270R%09replace+each+digit+in+the+input+with+%220%22%0A++ia%26++++%09then+replace+the+nth+character+back+to+its+original+value%0A++e++++++%09eval+as+float%0Am++++++++%09map+using+block+to+produce+array%0A%7Bf+++++++%09filter+out+zeroes%0A%27%2B*++++++%09join+with+%22%2B%22&i=0%0A6%0A0.99%0A24601%0A6.283%0A9000000.0000009&m=2)
Like the many of the other solutions posted, it produces `9000000+9e-7` for the last test case. According to established precedent this is allowed because the test case is too precise for the language.
[Answer]
# Lua, 350 Bytes
I think there's two way to golf it down further :
* I could make use of `macro.define` to replace some of the commons expressions (can't test right now, and not sure it would make me gain some bytes)
* Use split on the dot instead of iterating on the whole string. Once again, I'm not sure it would reduce the size of this function, as manipulating string in lua is quite painful.
```
function f(s)v,r=s:find("%.")or#s+1,""if #s==1 then return s end for i=1,#s do a=""(v>i and s:sub(i,v-1)or s:sub(v,i)):gsub(".",function(c)a=a..(not a:find(c)and(c==s:sub(i,i)or c==".")and c or 0)end)s,r=v<i and s:sub(0,i-1).."0"..s:sub(i+1,#s)or s,r..((#a==a:find("%.")or tonumber(a)==0)and""or a:gsub("%.","0.")..(i~=#s and"+"or""))end return r end
```
### Explanations
```
function f(s)
v=s:find("%.")or #s+1 -- v=index of the dot in a decimal number
r="" -- v=#s+1 when s is an integer(v=0 would screw sub())
if #s==1 then return s end -- exit if s is a single digit
for i=1,#s -- iterate over s
do
a=""
(v>i and s:sub(i,v-1)or s:sub(v,i)-- only send the integer OR decimal part to gsub
):gsub(".",function(c) -- iterate over each character of s:sub()
-- a contains the next number to be concatenated to the string r(the one to be returned)
a=a..(not a:find(c) -- we concatenate a with c if a doen't contains
and(c==s:sub(i,i)or c==".") -- c, and c is either a dot, or the next number
and c or 0) -- to be add, we put a 0 otherwise
end)
-- we concatenate the new a with the string already formed
r=r..((#a==a:find("%.") -- if a=="." or a's value is 0
or tonumber(a)==0)and"" -- we concatenate an empty string
or a:gsub("%.","0.") -- else, we replace the (possible) leading dot by "0."
..(i~=#s and"+"or"")) -- and concatenate a "+" if it isn't the last number to be added
s=v<i and s:sub(0,i-1) -- We then replace the digit we have worked with
.."0"..s:sub(i+1,#s)or s -- to prevent duplicates
end
return r
end
```
You can test lua online and use the following source code to run it with some test cases
```
function f(s)v,r=s:find("%.")or#s+1,""if #s==1 then return s end for i=1,#s do a=""(v>i and s:sub(i,v-1)or s:sub(v,i)):gsub(".",function(c)a=a..(not a:find(c)and(c==s:sub(i,i)or c==".")and c or 0)end)s,r=v<i and s:sub(0,i-1).."0"..s:sub(i+1,#s)or s,r..((#a==a:find("%.")or tonumber(a)==0)and""or a:gsub("%.","0.")..(i~=#s and"+"or""))end return r end
print(f("3123.12333"))
print(f("9545"))
print(f("9000000.0000009"))
print(f("6"))
```
[Answer]
# C, 253 bytes
```
m(char*i){int k,j=0,s=0,d=0;while(i[s])s++;while(i[d]!=46)d++;while(j<d){if(i[j]!=48){for(k=0;k<(d-j);k++)putchar(k?48:i[j]);putchar(43);}j++;}while(++j<s)if(i[j]!=48){putchar(46);for(k=0;k<(j-d);k++)putchar(k==(j-d-1)?i[j]:48);putchar(43);}putchar(8);}
```
Note: `putchar(8)` should perform a backspace.
```
Input: 1230.0456
Output: 1000+200+30+.04+.005+.0006
```
**Detailed**, [try here](http://ideone.com/DqQZmC)
```
while(i[s]) s++;
while(i[d]!=46) d++;
while (j<d)
{
if (i[j]!='0')
{
for(k=0;k<(d-j);k++) putchar(k? '0': i[j]);
putchar(43);
}
j++;
}
while (++j<s)
if (i[j]!='0')
{
putchar(46);
for(k=0; k<(j-d); k++) putchar(k==(j-d-1)? i[j]: '0');
putchar(43);
}
putchar(8);
```
[Answer]
### sed, ~~136~~ 128 bytes
Reduced by 8 chars by dropping spaces and useless `0`.
```
:;s/^([1-9][0-9]*)([1-9])(0*)([+.].*|)$/\10\3+\2\3\4/;s/([1-9]0*)\.([0-9])/\1+.\2/;s/\.(0*)([1-9])([0-9]*[1-9])$/.\1\2+.\10\3/;t
```
Test cases:
```
sed -r ':;
s/^([1-9][0-9]*)([1-9])(0*)([+.].*|)$/\10\3+\2\3\4/;
s/([1-9]0*)\.([0-9])/\1+.\2/;
s/\.(0*)([1-9])([0-9]*[1-9])$/.\1\2+.\10\3/;
t' <<<$'0\n6\n0.99\n24601\n6.283\n9000000.0000009\n3.1415'
0
6
0.9+.09
20000+4000+600+1
6+.2+.08+.003
9000000+.0000009
3+.1+.04+.001+.0005
```
[Answer]
## JavaScript (ES7), 114 bytes
```
s=>(p=s.search(/.\b/),i=-1,[for(c of s)if((i++,c>0))(z=s.substring(i,p).replace(/d/g,0),i<p?c+z:z+c)].join`+`||s
```
Works with arbitrary length numbers because it uses string manipulation throughout.
Without the array comprehension (122 bytes):
```
s=>[...s].map((c,i)=>c<'1'?'':(z=s.substring(i,p).replace(/\d/g,0),i<p?c+z:z+c),p=s.search(/.\b/)).filter(x=>x).join`+`||s
```
Ungolfed:
```
function expand(s) {
zeros = s.replace(/\d/g, "0");
point = s.indexOf(".");
if (point < 0) point = s.length;
result = [];
for (i = 0; i < s.length; i++) {
if (s[i] > "0") {
if (i < point) result.push(s[i] + zeros.slice(i, point - 1));
else result.push(zeros.slice(point - 1, i) + s[i]);
}
}
return result.length ? result.join("+") : s;
}
```
[Answer]
# R - 133 bytes
Robust, ignores Machine Epsilon and works also with trailing zeros.
a) Golfed:
```
f=function(x)if(x=='0')x else{z=strsplit(x,'')[[1]];i=which(z=='.');n=as.numeric(z[-i])*10^(i-seq(z)[-1]);paste(n[n>0],collapse='+')}
```
Ungolfed:
```
f=function(x)
if(x=='0')
x
else {
z=strsplit(x,'')[[1]]
i=which(z=='.')
n=as.numeric(z[-i])*10^(i-seq(z)[-1])
paste(n[n>0],collapse='+')
}
```
Usage:
```
f("900.008")
```
] |
[Question]
[
Unless you have a userscript that modifies the site's design (or even if so), you should have noticed that we have our site design!
[(It's November now)](https://chat.stackexchange.com/transcript/message/50642664#50642664)
So, to celebrate, let's make a program that retroactively applies this design (oversimplified, of course)!
So, the most important changes are:
* our new name is now Code Golf and Coding Challenges
* our site is no longer the default blue color and is instead a nice dark green
So, given a string, change:
* `PPCG` to `CGCC`
* `Programming Puzzles {non-whitespace} Code Golf` to `Code Golf {same-thing} Coding Challenges` (for example, `Programming Puzzles + Code Golf`, `and Code Golf`, and `& Code Golf` would all be changed to `Code Golf + Coding Challenges`, `and Coding Challenges`, and `& Coding Challenges`.
* `#abc` to `#acb` (swap blue to green and vice versa - just ignore the fact that green shouldn't logically become blue but I don't want to complicate the color shifting)
* `#abcdef` to `#abefcd` (same as above)
Note that for the color swaps, you should accept any hexadecimal digit from `0-9` to `a-f`. You can choose what case of hex digit to require, but it must be consistent and the same from input to output.
Your substitutions can be case-sensitive, and if not, please specify how the output works.
The substitutions should only happen when the string is surrounded by word boundaries (including the start of the `#`). In other words, each of the specified substitutions should only occur if the match is at the edge of the string or is bordered by non-alphanumeric characters (on both sides).
Standard loopholes apply. This is a code-golf challenge, so the shortest code wins!
# Examples
```
PPCG -> CGCC
Programming Puzzles or Code Golf -> Code Golf or Coding Challenges
PPCG stands for Programming Puzzles and Code Golf and its site color is #abf -> CGCC stands for Code Golf and Coding Challenges and its site color is #afb
The color #00f is much more intense than #5568ed -> The color #0f0 is much more intense than #55ed68
Programming Puzzles and No Substitution -> Programming Puzzles and No Substitution
No Substitution and Code Golf -> No Substitution and Code Golf
Programming Puzzles and no substitution Code Golf -> Programming Puzzles and no substitution Code Golf
Code Golf and Programming Puzzles -> Code Golf and Programming Puzzles
Programming Puzzles and Programming Puzzles and Code Golf -> Programming Puzzles and Code Golf and Coding Challenges
```
(for the last test case, it is important to note that the translated string could be translated again but the transformation must be applied *exactly* once)
# Important Update
(Thanks @tsh)
The `Programming Puzzles ... Code Golf` substitution rule can include the other rules inside of it (`Programming Puzzles PPCG Code Golf` is valid). In this case, you may choose whether or not the rules are applied, but it must be deterministic. I'm not requiring that you be consistent between `PPCG` and `#...` because answers seem to implement the rules in my list ordering which results in inconsistencies. This is just a clarification; I believe all current answers remain valid.
[Answer]
# [Ruby](https://www.ruby-lang.org/) `-p`, ~~165~~ ~~164~~ 159 bytes
It ended up being very similar to the sed answer, but it abuses Ruby's string interpolation to duplicate the hex group matching `([\da-f]{1,2})` within the third regex three times instead of needing to repeat the whole thing again.
* *-1 byte from @randomdude999.*
* *-5 bytes from leveraging @Xcali's Perl solution*
```
gsub /\bPPCG\b/,"CGCC"
gsub /\bProgramming Puzzles( \S+ )(Code Golf)\b/,'\2\1Coding Challenges'
[1,2].map{|i|gsub /(^|\s)#\K#{'([\da-f]{%d})'%i*3}\b/,'\2\4\3'}
```
[Try it online!](https://tio.run/##bY6xboMwEIZ3nuIUKwKapAmQRN09MHRBarc4lUywwRLYiDNDA7x6KbRKsmS87@7772/a9Hscc2xT2LI0SWjM0u16QWNKF84dNyZveFUpnUPSXq@lQA/Yxwp8j5pMQGxK6c@ey0IWTGg@pAUvS6Fzga5zCtbh@bXidder/j/V@@oZ@oS9k871TizjG3nultngu0v1Eg23tD2L3GEcnzQA08D9uzM3B7RcZwhy2jwTpuXD@JuURUBlBVxMOUkKgfBUOp/FjZDdTs64ai8FVKYRoLQVGgXYgmsgh8PxTWRAgjDayx9TW2U0jpv6Fw "Ruby – Try It Online")
[Answer]
# [C++ (gcc)](https://gcc.gnu.org/), ~~270~~ ~~285~~ 283 bytes
Thanks to [Neil](https://codegolf.stackexchange.com/users/17602/neil) for pointing out a bug.
-2 bytes thanks to ceilingcat.
```
#import<regex>
#import<string>
auto f=[](auto s){typeof(s)R[][2]{"bPPCG","CGCC","bProgramming Puzzles( \\S+ )(Code Golf)","$2$1Coding Challenges","B#(?=([\\da-f]{3}){1,2}\\b)(.+?)(..??)(..??)","#$2$4$3"};for(auto r:R)s=std::regex_replace(s,std::regex('\\'+*r+"\\b"),r[1]);return s;};
```
[Try it online!](https://tio.run/##bVBNj5swED2HXzGCqLEbstpkm6oKhEjlkGu07Q1Q5RhDkMBGtpG6i/jt6QDa5rKX5/l4bzzzeNtuSs7vXiV53eUCwkoZqwVrIudRY1qztwhJTau0DbUoxd@xP6fIr2QZOayzCopjkpEpMrS3b61QBTH0NcmSXda718slPru@G5/jGJ/rRatSs6ZBPVy69/daGAJp@msNlMQKvz6ruqDIXO6WWyyMvPjG6lrIUhis//TI6UiSNM3Zpsj6l4H2W383pOmVkqf1CeHp9IFI93DOt@WLOwSF0vOa@vBKzdHY/HCY7vqjRVszLojxH0WyStPV@qteuzjZpb5OthkNtLCdlmCCIbhX0kLDKkmo0zuLSTm5Fk7hbJEP@wisMNb07mwEuJ84AErD/@MnDnLBWCZzA7g3fKbB5kM0ZZU1YCorgKsaRZUBj12neb9vH0Xv@bkYO03Hb9AoLQDvENIIsDcmwdvvv/8Q@ajxCobDETnmQ@AsnMW4CuFKGgujk1/AwmE@jzqL2QKuOgthCBO4sIkQMCqIpeO7SuUqcIb7Pw "C++ (gcc) – Try It Online")
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~153~~ 130 bytes
```
\bPPCG\b
CGCC
\bProgramming Puzzles( \S+ )(Code Golf)\b
$2$1Coding Challenges
\B(#(?=([\da-f]{3}){1,2}\b).+?)(..??)(..??)\b
$1$4$3
```
[Try it online!](https://tio.run/##bU49a8MwEN31Kw7sQSKpiZMmZCmGavBqaLeogxyfbIEsgaQsCfntrhRIu2Q5eF/3nseorVwW0Xcdb0VPeMs5Sci70ct51naE7nK9GgwUxNcKGOVuQGidUSzZy21ZJyLb@CSNQTtiIOKTFrT5oCcxyDf1c9vd2a1eb@@iZ9WqYbSqmufNP@ryvdwtS15AXhSD8/BXSrILQpR2CKCS8iqQxP/EA@kYIOiIcHYmhXSAQvaKfE9PpthsVKbny3mC2XkEbSPagBAnaaHY7w9HHH4B "Retina 0.8.2 – Try It Online") Link includes test cases. All substitutions are case sensitive. Assumes normal regex word characters are acceptable so that `\B#` matches only `#`s that don't follow a word character. Edit: Saved 22 bytes thanks to @tsh.
[Answer]
# GNU sed `-E`, 198 chars
```
s/\bPPCG\b/CGCC/g
s/\bProgramming Puzzles( \S* Cod)e Golf\b/Code Golf\1ing Challenges/g
s/((^|\W)#[0-9a-f])([0-9a-f])([0-9a-f])\b/\1\4\3/g
s/((^|\W)#[0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})\b/\1\4\3/g
```
Runnable using e.g. `sed -E 'the above'`; newlines can either be included literally, or replaced with `;` if you so wish. Both work.
@HyperNeutrino come on that word boundary rule is stupid. Look what I had to do in the `#` case.
Yes, I didn't even try. :P
+9 by @Value Ink
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 85 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
ì▀¼FΣ¼≤C╛╓ÄydîNû►┘Δ▲Bd♫|α╒oñFτ▒t!↑▌╩┘♦pMc6Hèé▄·│╝∙↔¥^4b5╠·9█&╨^╨♂═î£ε■屫\┴J₧å♠Å≡z╜û♀
```
[Run and debug it](https://staxlang.xyz/#p=8ddfac46e4acf343bed68e79648c4e9610d9ff1e42640e7ce0d56fa446e7b1742118ddcad904704d6336488a82dcfab3bcf91d9d5e346235ccfa39db26d05ed00bcd8c9ceefe86f1ae5cc14a9e86068ff07abd960c&i=PPCG%0AProgramming+Puzzles+or+Code+Golf%0APPCG+stands+for+Programming+Puzzles+and+Code+Golf+and+its+site+color+is+%23abf%0AThe+color+%2300f+is+much+more+intense+than+%235568ed%0A&a=1&m=2)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~123~~ ~~109~~ ~~105~~ ~~110~~ 114 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
žKISå_Å¡JεÐć'#QsžhA6£«sSåP*i3äćsRJ«ë"PPCG"Qi"CGCC"]J”–±ÇÀ”DU¡ćsε”ƒËŠˆ”©¡DVćDÁ2ôεðå}ćs_P*YyÊP*i”Âïªï”«s®ý«®ìëyXì]J«
```
+5 bytes fixing test cases like `Programming Puzzles and no substitution Code Golf` and `Programming Puzzles and Programming Puzzles and Code Golf`.
+4 bytes fixing test cases like `color-#00f` (colors with something besides spaces/newlines surrounding it). Thanks to *@Grimy* for bringing this to my attention.
Case-sensitive. Hexadecimal values are with lowercase `abcdef`; `Programming Puzzles ... Code Golf` is in titlecase; `PPCG` is in full uppercase.
[**Try it online.**](https://tio.run/##hVHBSsNAEL3nK5bkIBQCRWnxKikUK0hqVfRQStomzUKyC9nk0IJQBQ3oRfQsWLQHTbEK9mgPO60XoR/RH4mbgtRKi5dlZt5782ZmKTOq2Izj8XBnuwTdCpzzTmEygOtRuKYU2Xhob2X5A4@YAPUU3oDHUcj2CjyCSNZ1LS8XsazlNU0uF6btu2n7lr9BCG0R5w54R3AnAxF/3sDV@P7rQoT8iXdyh6MwB6fr8C6cXqF7IngVPXXchEvhIUhwBn3@DP2EHzH@Ah88Em8PouYR9MrCPo5leTaApHu04Rmui0kD6UGr5ZgMUQ9ptG6iPHUsKWEh5hukzpAlkGUCAc4Vswz7DDHsm6hGHSHCDClG1ZL27Z@Kkk5bSdkNajZyqWciTHyTMBP5tkGQkslkN826tMptl6JSUGU@9gMfUyL9yRcnWtmFUMR@q@aKxW2W6Ff2/Pc@0uwAanIA8QmxqhKqOkar@Q0)
Definitely not the right language for the job.. Mimicking word-boundaries and replacing `Programming Puzzles \S+ Code Golf`, but not `Code Golf \S+ Programming Puzzles` or `Programming Puzzles \S+ \S+ Code Golf` without any regexes is pretty hard (to do short).. >.>
**Explanation:**
```
žK # Push "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
# (NOTE: if '_' also count as word boundary, use `žj` instead)
IS # Push the input as a list of characters
å_ # Check for each character if they are NOT in the string
Å¡ # Split the (implicit) input on truthy values
J # Join each inner character list to a string again
ε # Map each word to:
Ð # Triplicate the word
ć # Extract head; push remainder and head separately to the stack
'#Q '# Check if the head equals "#"
žh # Push string "0123456789"
A6£« # Append the first 6 letters of the alphabet: "0123456789abcdef"
s sSåP # Check if the characters of the remainder are all in this string
*i # If both are truthy:
3ä # Split the 'word' into three parts
# i.e. "#ab12cd" → ["#ab","12","cd"]
ćs # Extract head, and swap
R # Reverse the remainder list
J« # Join them together, and merge them to the head again
ë"PPCG"Qi # Else-if the word is "PPCG":
"CGCC" # Push "CGCC"
# (Implicit else:
# Use the word that's still there from the initial triplicate)
] # Close all if statements and the nested map
J # Join the mapped words together again
”–±ÇÀ” # Push dictionary string "Programming Puzzles"
DU # Save a copy in variable `X`
¡ # Split the string by this
ćs # Extract head & swap; pushing head and remainder to the stack
ε # Map each substring `y` in the remainder to:
”ƒËŠˆ” # Push dictionary string "Code Golf"
© # Save it in variable `®` (without popping)
¡ # Split the current substring we're mapping by it
DV # Save a copy of this list in variable `Y`
ćD # Extract the head and duplicate
# (so the stack is: remainder, head, head)
Á # Rotate the characters in the head-string once towards the right
2ô # Split it into parts of size 2
εðå} # Check in each part if it contains a space
ćs # Extract head and swap again
_ # Check if all values are 0
P # And check if this is truthy for all
* # And check if this is truthy, as well as the head
# (this means the current string has a leading and trailing space,
# and no other spaces)
YyÊP # Check that none of the susbtrings in variable `Y`
# are equal to the current substring `y`
*i # If both checks above are truthy:
”Âïªï”« # Prepend "Coding Challenges" to the duplicated head
s®ý # Join the remainder by variable `®` ("Code Golf")
« # Append it
®ì # And prepend an additional variable `®` ("Code Golf")
ë # Else:
y # Simply keep the substring `y` as is
Xì # And prepend variable `X` ("Programming Puzzles")
# since we've split by it
] # Close all if-else statements and the map
J # Join the mapped substrings together to a single string
« # And append it to the initially extracted head
# (then output the resulting string implicitly as result)
```
[See this 05AB1E tip of mine (section *How to use the dictionary?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `”–±ÇÀ”` is `"Programming Puzzles"`; `”ƒËŠˆ”` is `"Code Golf"`; and `”Âïªï”` is `"Coding Challenges"`.
[Answer]
# [Python 2](https://docs.python.org/2/), 240 bytes
```
import re
lambda x,s=re.sub,b='(?<!\w)',e='(?!\w)',h='([\da-f]',t=r'#\1\3\2':s(b+'#%s{2})'%h+h+'{2})%s{2})'%h+e,t,s(b+'#%s)'%h+h+')%s)'%h+e,t,s(b+'Programming Puzzles( \S+ Cod)e Golf'+e,r'Code Golf\1ing Challenges',s(b+'PPCG'+e,'CGCC',x))))
```
[Try it online!](https://tio.run/##5VBRS8MwEH7vrzgpmpbWsk3mhlhE@rDXgYIP1od0vTSBNBlJxpzib59Jt6kP@wcGQr67@77vLrfeOa7VZL8X/VobBwYjSfumpfCe29JgYTdN3pQkebi/qLcpyTHgA@QevtYtvWZvJHelIXE9rm/qCbmzSZOR@NJ@Tr5ScskznpEAfxOYu/xEOjHSI/ypLY3uDO17oTpYbj4@JNoE6qcMKt2mCAstGfFsQ3x8COtx4FacSomqQ0uORstqEZikWlQVyd9Tf/as/B8fjdZGKAcsCX/c2cK6VqjCIG0Tv4WgKM/0h@xqaH9oV8ALFxLBcQQtW1hpqQ0wf30mWIS3R9hSC/FkNZtNZ5AYvem43EF8M5um@aBVuAWtkNh4TOd0PB@NiugRGiM67o6mwjswZL4QBePo3Gye9jPawALrqGrtMNE5gS/@KoZIOAtWOPzTlTYseuanTDwasZDuNysOvTYIfouobFgCVRBPp7dzbL8B "Python 2 – Try It Online")
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 174 bytes
```
s=>s[R='replace'](/\bPPCG\b/g,'CGCC')[R](/\bProgramming Puzzles( \S+ )(Code Golf)\b/g,'$2$1Coding Challenges')[R](/\B#(?=([\da-f]{3}){1,2}\b)(.+?)(..??)(..??)\b/ig,'#$2$4$3')
```
[Try it online!](https://tio.run/##fZNNb@IwEIbv@RUjBcm2CikfJWWFAlJz4Iq6eyNIdRI7uHJsFLt7KOK3szbZsJS2K8Vjzzszz7yXvNLf1BSN2NuB0iU78eRkkoXZPCeoYXtJC4a2@D7L1@t0leX3VR@lqzRFZPPcyo2uGlrXQlWwfnt/l8xgyH7eAcGpw8FKS07aud64N3Ka70x3VEqmKmY60FOIlwneZCUd8O1hciSHUX98zHKCo7ulC9Gyiw4mHC10uIfeBJHT/CXw5mCwAG8t@MIS6AYuds6Nl6StfDTV8oylqjTAXcdXSFe8wvhMWANGWAaFlm5IGAhpzjtf17yPc5/2f0vjefBr1ynhcMi9XL8VO6h1w0Aoy5RhYHdUQTidxjNW@vXXM3z4/xlWxrMghHDkvrE/k3N4aOP07xV39@PlMfv3@uGXXjEm40@MaXxJv2EEL5FtRI1JZPZSWIwyhUhU0z2WkCzgEBRaGQsb0WdbSEB2bX43IvNzWUsWSV1hcZNzp9xI7CZHAxS5H4BRix9jQoIjmZ/@AA "JavaScript (Node.js) – Try It Online")
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), ~~177~~ ~~173~~ ~~162~~ 142 bytes
```
J::jb.z"\\bPPCG\\b""CGCC"." z¶NZI°Pÿúd(MÜ_BöIkxnqä'u)"." s6#~ÍN³=<nñu/GÎg"VS2~:J%"(^|\W)#%s\\b"*3%"([\da-f]{%d})"N$r"\1#\2\4\3"$)J
```
Here's a version without Pyth's string compression mechanisms (aka it's safe to copy-paste):
```
J::jb.z"\\bPPCG\\b""CGCC""\\bProgramming Puzzles( \S+ )(Code Golf)\\b""\\2\\1Coding Challenges"VS2~:J%"(^|\W)#%s\\b"*3%"([\da-f]{%d})"N$r"\1#\2\4\3"$)J
```
[Try it online!](https://tio.run/##hZBNS8NAEIYR7CX6F4Rl02JjSe1XghS9mENooSWgKGhU0mbzoU22ZjegUXvwKnrwJOjRH6AIPXgRkv9lTFK/DoWeZvaZ952dmeE5teK43Wwe98oBVNWeokhyEiCUZEmCZQiC@XC81N1rhS9K9BG968VcJ3oK7482o3HrJHw4C29y4WN47S6cRs/LPpdaiMiO5qLbbvi2sb7oRq/@qhzdmXBnqzZqtguweHip7nJsgaT/rNQTsK/qGm8cXBT0Kw528x5Uq6xaUxtqHea5dhynQzGKh01PcxzbNYHiB8EAEVAqAQnrCMh4YEwVYO@/IGkDCNVcnQAjqUwzJMU/R/ayKQHEpgj08SAx2QSwWs9gtq0fwlYqRoodv28BB3sI2C5FLkGAWpoLWEEQ15A@czzkEaaDqDZzDbZaqzeESch2Sm6TXUhLUcZNhv/N@UneEMRvp8hPlP@I@YmH1MYuiXn9Cw)
This ended up being really long because I tried to be as pedantic as possible with the regexes. I tried to compress every string possible, but most of them either didn't get smaller or couldn't be pasted into TIO properly.
Explanation:
```
J:: # definition of J to the following 2 regex replacements
jb.z # input to first regex replacement: all input lines joined together
"\\bPPCG\\b" # first regex
"CGCC" # first replacement
."<compressed>" # second regex: "\\bProgramming Puzzles( \S+ )(Code Golf)\\b"
."<compressed>" # second replacement: "\\2\\1Coding Challenges"
VS2 # loop twice, N = 1 or 2
~:J # some weird assignment: J = regex replace in J (would be J := (regex, replacement) if : was python's regex replace operator)
% # third regex: string format
"(^|\W)#%s\\b" # format string
*3 # repeat 3 times:
%"([\da-f]{%d})"N # string format, replace %d with N (the loop counter)
$r"\1#\2\4\3"$ # third replacement: uses python raw literals because it's shorter than escaping the backslashes
) # end for loop
J # print J
```
* -11 thanks to a better regex from Value Ink's Ruby answer
* -20 thanks to using a loop for both of the hex replacements, inspired by the Ruby and Perl answers
[Answer]
# [Perl 5](https://www.perl.org/) `-p`, ~~152~~ 145 bytes
*@ValueInk saves 7 bytes*
```
s/\bPPCG\b/CGCC/g;s/\bProgramming Puzzles( \S+ )(Code Golf)\b/$2$1Coding Challenges/g;for$a(1,2){$p="([a-f0-9]{$a})"x3;s/(^|\s)#\K$p\b/$2$4$3/gi}
```
[Try it online!](https://tio.run/##bY5BS8QwFITv/RWPbQ4NWtvuWlHEUw49iFDQm1VIt2kbSJOSlwXZdf@6MV1RL3t88@abmVlYVXqPWdPWNauaNmMVY9lwf1KsGSyfJqkHqHf7vRKYQPN8ATRhphNQGdXTgJA1KYKw2NjIlRJ6EBgyemMJT4rLNT2Q@WGVvPK0z9O7twPhR7r62ISS5P2zQRo3j2T@Cbomm2yQR@@XOdGZBWAs/LVHiwvQcd0hhDo4B4TnP3G6pENA6QRsjQqQRIh520cv468S53m/yNNuO8JkrACpndAowI1cQ1yWN7ei@zKzk0ajT5/Kq7zIfTp/Aw "Perl 5 – Try It Online")
[Answer]
# Java 8, 192 bytes
```
s->s.replaceAll("\\bPPCG\\b","CGCC").replaceAll("\\bProgramming Puzzles( \\S+ )(Code Golf)\\b","$2$1Coding Challenges").replaceAll("\\B(#(?=([0-9a-f]{3}){1,2}\\b).+?)(..??)(..??)\\b","$1$4$3")
```
Port of [*@Neil*'s Retina answer](https://codegolf.stackexchange.com/a/186729/52210), so make sure to upvote him!
[Try it online.](https://tio.run/##rZJdT8IwFIbv@RUnZQltYAsfYlSCRHdBvBBJ8I5xUbYOil1H1o5ECb8duzHQAH7EeNO157zn3XlOu6Arai@Cl60vqFLwSLlclwC41CwJqc9gkB0BRjrhcgY@LjaKdEx8UzKL0lRzHwYgoQtbZd8qJ2FLYYrvhMDI86bDods3H1RDbt91ETnJJ/EsoVGUGQ/TtzfBFAbPG1WBYDcOGPRjEZKdg9W0GiaWSd05FYLJGVMnlve4jHtdPK7b19QOJ@vWhqwbtebGeBCn2iPYcXr7tfBtWBdWC5FtJ2NaplNhmAq0VcwDiMxoCvrxBCjZzUUzpTHKAFE@kUPkFAniBA40R2pTn/1MBgpCIztXbZIf5fmJawWKawZ@LEwRV1Cm0yPn5/k@Xa7Xw0wTpf4cojhh@SVLxUDPqYRyu315xYLTvjz5E4tR/GP/nvxbz5/fYn5hOULxXLlcprq4stGr0ixy4lQ7S5PUQmL0kOVvYE9/RlJBlWruUjW7r2XoKdW/sZKOj3dNfe9XoG227w)
] |
[Question]
[
## Challenge:
In the programming language of your choice, take no input and output your programming language's name.
Fair enough, right?
**Restrictions:**
* You can't use any character that is included in your programming language's name in your code. E.g., if I use Batch, I must not use the chars 'B' 'a' t' 'c' 'h' in my code. Note that this is case sensitive. I can still use the char 'b' because it's different from 'B'.
* You can have "junk output" before or after the name of the language
* Version number doesn't count as part of the name of the language. E.g., I can use the number 3 in the code in my answer if it's in Python 3
* The output of the programming language name is not case sensitive.
* Brute-forcing all possible letter combinations and hoping you get your language name is forbidden.
---
**Example outputs:** (let's say my programming language is called Language) (✔ if valid, else ✖)
* `Language` ✔
* `Body language is a type of non-verbal communication in which physical behavior, as opposed to words, is used to express or convey information. Such behavior includes facial expressions, body posture, gestures, eye movement, touch and the use of space.` ✔
* `Language 2.0 - © 1078 AD some company` ✔
* `foobar` ✖
---
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") thus shortest code wins.
[Answer]
## Outputs to STDERR
[Outputting to STDERR](https://codegolf.meta.stackexchange.com/a/2451/20260) is now at +33/-21 as an allowed default, which is positive but contested. This is a [CW answer to collect answers](https://codegolf.meta.stackexchange.com/q/11211/20260) that just invoke an error in a language where error messages includes the language name.
### [Haskell, 1 byte](https://tio.run/nexus/haskell#@2/4/z8A)
```
1
```
Error:
```
Parse error: naked expression at top level
Perhaps you intended to use TemplateHaskell
```
### [Lua, 1 byte](https://tio.run/nexus/lua#@2/4/z8A)
```
1
```
Error:
```
lua: .code.tio:1: syntax error near <eof>
```
(file name is unimportant)
### Batch, 1 byte
```
~
```
Error:
```
'~' is not recognized as an internal or external command,
operable program or batch file.
```
### [tinylisp, 5 bytes](https://tio.run/##K8nMq8zJLC74/18jWUPT8P9/AA)
```
(c()1
```
Error:
```
Error: cannot cons to Int in tinylisp
```
### R, 1 byte
```
)
```
Error:
```
Error: unexpected ')' in ")"
```
### Java bytecode, 0 bytes
Error:
```
Exception in thread "main" java.lang.ClassFormatError: Truncated class file
```
### Groovy, 1 byte
```
a
```
Note that `a` can be replaced with any other character
Error:
```
groovy.lang.MissingPropertyException: No such property: a ...
```
### MATLAB, 1 byte
```
\
```
Error:
```
Error: Unexpected MATLAB operator.
```
### [PHP, 3 bytes](https://tio.run/nexus/php#@29jb/v/PwA)
```
<?=
```
Error:
```
PHP Parse error: syntax error, unexpected end of file in /home/runner/.code.tio on line 1
```
### CJam, 1 byte
```
/
```
Error:
```
/
^
RuntimeException: The stack is empty
Java exception:
java.lang.RuntimeException: The stack is empty
at net.aditsu.cjam.CJam.pop(CJam.java:75)
at net.aditsu.cjam.Op2.run(Op2.java:10)
at net.aditsu.cjam.Block.run(Block.java:304)
at net.aditsu.cjam.CJam.runCode(CJam.java:210)
at net.aditsu.cjam.CJam.main(CJam.java:240)
```
### [Twig, 2 bytes](https://twigfiddle.com/h1bvzf)
Twig is a template language written in PHP. It's possible that this is a polyglot.
```
{{
{%
{#
```
Error:
```
PHP Fatal error: Uncaught exception 'Twig_Error_Syntax' with message [...] in [...][...]:n:
Stack trace:
#0 [...]
```
The message varies depending on which program you choose.
### [S.I.L.O.S](https://github.com/rjhunjhunwala/S.I.L.O.S), 2 bytes
```
x+
```
[Try it online!](https://tio.run/nexus/silos#@1@h/f8/AA "S.I.L.O.S – TIO Nexus")
Trivially invokes undocumented behavior. Silos is the name of the language.
### Python, 6 bytes
```
pYTHON
```
As the character restriction is case insensitive, and the output doesn't have to be in the correct case, this is a valid answer. The error message it produces is something like this:
```
Traceback (most recent call last):
File ".code.tio", line 1, in <module>
pYTHON
NameError: name 'pYTHON' is not defined
```
[**Try it online!**](https://tio.run/nexus/python3#@18QGeLh7/f/PwA) (outputs to 'debug' tab)
### JavaScript, 10 bytes
```
jAVAsCRIPT
```
This produces the following error message or similar in all environments:
```
ReferenceError: jAVAsCRIPT is not defined
```
### [QBIC](https://codegolf.stackexchange.com/a/108030/44874), 6 bytes
```
?b(12)
```
In 6 bytes, we can put QBIC encountered error: 9 on the screen, signifying an out-of-bounds error.
### ForceLang, 2 bytes
```
()
```
Error produced:
```
Exception in thread "main" lang.exceptions.IllegalInvocationException: null is not a function.
at lang.ForceLang.parse(ForceLang.java:99)
at lang.ForceLang.main(ForceLang.java:129)
```
### [Pip, 5 bytes](https://tio.run/##K8gs@P/fsC4hOuH/fwA)
```
1~`[`
```
(Note: this works in the current version as of this writing, [0.17.09.01](https://github.com/dloscutoff/pip/commit/6723e170f5baab521af5a7114ac401dd7b639582). No guarantees the interpreter won't change to handle this error differently in the future.)
Tries to regex match with a syntactically invalid pattern. The error produced will look something like this:
```
Traceback (most recent call last):
File "/opt/pip/pip.py", line 221, in <module>
pip(interactive=False)
File "/opt/pip/pip.py", line 206, in pip
state.executeProgram(tree, args)
File "/opt/pip/execution.py", line 56, in executeProgram
returnVal = self.functionCall(mainFunction, cmdLineArgs)
File "/opt/pip/execution.py", line 368, in functionCall
returnVal = self.getRval(returnExpr)
File "/opt/pip/execution.py", line 235, in getRval
expr = self.evaluate(expr)
File "/opt/pip/execution.py", line 213, in evaluate
result = opFunction(*args)
File "/opt/pip/execution.py", line 1134, in FIRSTMATCH
matchObj = regex.asRegex().search(str(string))
File "/opt/pip/ptypes.py", line 175, in asRegex
self._compiled = re.compile(pyRegex)
File "/usr/lib64/python3.6/re.py", line 233, in compile
return _compile(pattern, flags)
File "/usr/lib64/python3.6/re.py", line 301, in _compile
p = sre_compile.compile(pattern, flags)
File "/usr/lib64/python3.6/sre_compile.py", line 562, in compile
p = sre_parse.parse(p, flags)
File "/usr/lib64/python3.6/sre_parse.py", line 855, in parse
p = _parse_sub(source, pattern, flags & SRE_FLAG_VERBOSE, 0)
File "/usr/lib64/python3.6/sre_parse.py", line 416, in _parse_sub
not nested and not items))
File "/usr/lib64/python3.6/sre_parse.py", line 765, in _parse
p = _parse_sub(source, state, sub_verbose, nested + 1)
File "/usr/lib64/python3.6/sre_parse.py", line 416, in _parse_sub
not nested and not items))
File "/usr/lib64/python3.6/sre_parse.py", line 523, in _parse
source.tell() - here)
sre_constants.error: unterminated character set at position 8
```
### [Stax, 2 bytes](https://staxlang.xyz/#c=0u&i=&a=1)
```
0u
```
Error:
```
Stax runtime error: rational divide by zero
```
`zh` also works.
### [ink, 1 byte](http://tio.run/##y8zL/v@/7v9/AA)
```
~
```
`~` at the start of a line marks that the line is a statement to be executed, rather than text to be printed. As of whichever version of inklecate TIO is using, if there's nothing after the `~`, the interpreter crashes with the following error:
```
System.NullReferenceException: Object reference not set to an instance of an object
at Ink.InkParser.LogicLine () [0x000b1] in <b1e5e74f4ee842fc961297862cf23e07>:0
at Ink.StringParser.ParseObject (Ink.StringParser+ParseRule rule) [0x00012] in <b1e5e74f4ee842fc961297862cf23e07>:0
at Ink.StringParser.OneOf (Ink.StringParser+ParseRule[] array) [0x0000a] in <b1e5e74f4ee842fc961297862cf23e07>:0
at Ink.InkParser.StatementAtLevel (Ink.InkParser+StatementLevel level) [0x00009] in <b1e5e74f4ee842fc961297862cf23e07>:0
at Ink.InkParser+<>c__DisplayClass134_0.<StatementsAtLevel>b__0 () [0x00000] in <b1e5e74f4ee842fc961297862cf23e07>:0
at Ink.StringParser.ParseObject (Ink.StringParser+ParseRule rule) [0x00012] in <b1e5e74f4ee842fc961297862cf23e07>:0
at Ink.StringParser.Interleave[T] (Ink.StringParser+ParseRule ruleA, Ink.StringParser+ParseRule ruleB, Ink.StringParser+ParseRule untilTerminator, System.Boolean flatten) [0x00040] in <b1e5e74f4ee842fc961297862cf23e07>:0
at Ink.InkParser.StatementsAtLevel (Ink.InkParser+StatementLevel level) [0x0004f] in <b1e5e74f4ee842fc961297862cf23e07>:0
at Ink.InkParser.Parse () [0x00000] in <b1e5e74f4ee842fc961297862cf23e07>:0
at Ink.Compiler.Compile () [0x00033] in <b1e5e74f4ee842fc961297862cf23e07>:0
at Ink.CommandLineTool..ctor (System.String[] args) [0x001a3] in <d64e27e7788347b2a5377c9e19bbdcab>:0
at Ink.CommandLineTool.Main (System.String[] args) [0x00000] in <d64e27e7788347b2a5377c9e19bbdcab>:0
[ERROR] FATAL UNHANDLED EXCEPTION: System.NullReferenceException: Object reference not set to an instance of an object
at Ink.InkParser.LogicLine () [0x000b1] in <b1e5e74f4ee842fc961297862cf23e07>:0
at Ink.StringParser.ParseObject (Ink.StringParser+ParseRule rule) [0x00012] in <b1e5e74f4ee842fc961297862cf23e07>:0
at Ink.StringParser.OneOf (Ink.StringParser+ParseRule[] array) [0x0000a] in <b1e5e74f4ee842fc961297862cf23e07>:0
at Ink.InkParser.StatementAtLevel (Ink.InkParser+StatementLevel level) [0x00009] in <b1e5e74f4ee842fc961297862cf23e07>:0
at Ink.InkParser+<>c__DisplayClass134_0.<StatementsAtLevel>b__0 () [0x00000] in <b1e5e74f4ee842fc961297862cf23e07>:0
at Ink.StringParser.ParseObject (Ink.StringParser+ParseRule rule) [0x00012] in <b1e5e74f4ee842fc961297862cf23e07>:0
at Ink.StringParser.Interleave[T] (Ink.StringParser+ParseRule ruleA, Ink.StringParser+ParseRule ruleB, Ink.StringParser+ParseRule untilTerminator, System.Boolean flatten) [0x00040] in <b1e5e74f4ee842fc961297862cf23e07>:0
at Ink.InkParser.StatementsAtLevel (Ink.InkParser+StatementLevel level) [0x0004f] in <b1e5e74f4ee842fc961297862cf23e07>:0
at Ink.InkParser.Parse () [0x00000] in <b1e5e74f4ee842fc961297862cf23e07>:0
at Ink.Compiler.Compile () [0x00033] in <b1e5e74f4ee842fc961297862cf23e07>:0
at Ink.CommandLineTool..ctor (System.String[] args) [0x001a3] in <d64e27e7788347b2a5377c9e19bbdcab>:0
at Ink.CommandLineTool.Main (System.String[] args) [0x00000] in <d64e27e7788347b2a5377c9e19bbdcab>:0
```
### [Rust, 0 bytes](https://tio.run/##KyotLvkPBAA)
```
```
Error:
```
error[E0601]: `main` function not found in crate `code`
|
= note: consider adding a `main` function to `code.tio`
error: aborting due to previous error
For more information about this error, try `rustc --explain E0601`.
```
### [sed, 1 byte](https://ato.pxeger.com/run?1=m724ODVlwYKlpSVpuhYLHSE0lAsTBgA)
```
A
```
Error:
```
sed: file /ATO/code line 1: unknown command: `A'
```
### [flat assembler, 0 byte](https://tio.run/##SywuTs1NyqnUTUsszv0PBAA)
Error:
```
flat assembler version 1.73.16 (16384 kilobytes memory, x64)
1 passes, 0 bytes.
```
### GolfScript, 1 byte
```
\
```
Error:
```
/opt/golfscript/golfscript.rb:118:in `block in to_gs': undefined method `to_gs' for nil:NilClass (NoMethodError)
from /opt/golfscript/golfscript.rb:118:in `each'
from /opt/golfscript/golfscript.rb:118:in `inject'
from /opt/golfscript/golfscript.rb:118:in `to_gs'
from (eval):1:in `block in initialize'
from /opt/golfscript/golfscript.rb:306:in `go'
from (eval):1:in `block in initialize'
from /opt/golfscript/golfscript.rb:306:in `go'
from (eval):1:in `block in initialize'
from /opt/golfscript/golfscript.rb:306:in `go'
from /opt/golfscript/golfscript.rb:500:in `<main>'
```
### [Thunno, 0 bytes](https://ato.pxeger.com/run?1=m72sJKM0Ly9_wYKlpSVpuhZoFJQGAA)
```
```
Error (for Thunno v1.2.1):
```
Thunno, v1.2.1
```
### [Vyxal, 2 bytes](https://ato.pxeger.com/run?1=m720rLIiMWfBgqWlJWm6FovP7a5YUpyUXAzlw8QB)
```
λx
```
Error:
```
Traceback (most recent call last):
File "/usr/local/bin/vyxal", line 8, in <module>
sys.exit(cli())
File "/usr/local/lib/python3.10/site-packages/vyxal/main.py", line 470, in cli
execute_vyxal(file_name, flags, inputs)
File "/usr/local/lib/python3.10/site-packages/vyxal/main.py", line 430, in execute_vyxal
vy_print(output, ctx=ctx)
File "/usr/local/lib/python3.10/site-packages/vyxal/elements.py", line 7253, in vy_print
res = safe_apply(lhs, *args, ctx=ctx, arity_override=override)
File "/usr/local/lib/python3.10/site-packages/vyxal/helpers.py", line 983, in safe_apply
ret = function(
File "<string>", line 10, in _lambda_36f6fb46b5889e1e4e91c1f138c09b37
File "<string>", line 10, in _lambda_36f6fb46b5889e1e4e91c1f138c09b37
File "<string>", line 10, in _lambda_36f6fb46b5889e1e4e91c1f138c09b37
[Previous line repeated 982 more times]
File "<string>", line 8, in _lambda_36f6fb46b5889e1e4e91c1f138c09b37
File "/usr/local/lib/python3.10/site-packages/vyxal/LazyList.py", line 184, in __len__
next(self)
File "/usr/local/lib/python3.10/site-packages/vyxal/LazyList.py", line 198, in __next__
item = vyxalify(next(self.raw_object))
File "/usr/local/lib/python3.10/site-packages/vyxal/helpers.py", line 1488, in vyxalify
return sympy.nsimplify(value, rational=True)
File "/usr/local/lib/python3.10/site-packages/sympy/simplify/simplify.py", line 1436, in nsimplify
return sympify(as_int(expr))
File "/usr/local/lib/python3.10/site-packages/sympy/core/sympify.py", line 383, in sympify
return conv(a)
File "/usr/local/lib/python3.10/site-packages/sympy/core/cache.py", line 72, in wrapper
retval = cfunc(*args, **kwargs)
RecursionError: maximum recursion depth exceeded in comparison
```
[Answer]
# SmileBASIC, 11 bytes
```
sPsET.,1474
```
Equivalent to `SPSET 0,1474`. Sets sprite 0 to definition 1474, which is the SmileBASIC logo.
[![Screenshot](https://i.stack.imgur.com/z67zA.jpg)](https://i.stack.imgur.com/z67zA.jpg)
[Answer]
# R, 1 byte:
```
T
```
`T` is an alias for the constant `TRUE`. So the output for the above is:
```
[1] TRUE
```
Since junk is allowed around the name, the “R” in there is the language name.
([As noted in a comment elsewhere](https://codegolf.stackexchange.com/questions/107964/output-programming-language-name?page=2&tab=oldest#comment262884_108035), pretty much any single letter and many glyphs will work equally well because they trigger the message “Error: …”, which contains “r”.)
[Answer]
# [MATL](https://github.com/lmendo/MATL), 1 byte
```
Y
```
Output is through STDERR, which is [allowed by default](http://meta.codegolf.stackexchange.com/a/2451/36398).
The output from the offline compiler is
```
Error using matl_parse (line 339)
MATL error while parsing: Y not recognized at position 1
Error in matl (line 234)
S = matl_parse(s, useTags);
```
Or [try it online!](https://tio.run/nexus/matl#@x/5/z8A "MATL – TIO Nexus") (expand "debug" section).
[Answer]
# HTML, ~~24~~ 20 bytes
```
HTML
```
---
# HTML, 16 bytes
[As pointed out by @Bob](https://codegolf.stackexchange.com/questions/107964/output-programming-language-name/107990?noredirect=1#comment262780_107990), modern browsers will recognize HTML entities without semicolons, though it's technically invalid HTML. Of course, it's perfectly valid for code golf.
```
HTML
```
---
# HTML, 4 bytes
And of course, the uninteresting answer.
```
html
```
---
Also, see my [CSS answer](https://codegolf.stackexchange.com/a/108001/47097).
[Answer]
# Vim, 0 bytes
When you start Vim, the editor displays a splash screen which looks like this:
[![Vim splash screen](https://i.stack.imgur.com/j9wr6.png)](https://i.stack.imgur.com/j9wr6.png)
You can see it says `Vim` here:
[![Vim splash screen with vim highlighted](https://i.stack.imgur.com/Cax5C.png)](https://i.stack.imgur.com/Cax5C.png)
Previous answer:
# Vim, 1 byte
```
<Ctrl-C>
```
In Vim 8, pressing will display `Type :quit<Enter> to exit Vim` at the last line. I'm not completely sure if this counts.
[Answer]
# Python, 15 bytes
## Python 2 (15)
```
exec"\150elp()"
```
It concatenates the strings uses the octal `150` which is `h` and `"elp()"` and runs the result. This prints the `help()` command which says `"Welcome to Python 3.5's help utility!"`, meeting the requirements.
## Python 3 (17)
```
exec("\150elp()")
```
[Try it online!](https://tio.run/nexus/python2#@6@sEFBZkpGfp2DMpayQWpGarKEUY2hqkJpToKGppMnFBZc34uICSSPJ/v8PAA)
[Answer]
# C, 0 bytes.
```
/usr/lib/gcc/i586-linux-gnu/5/../../../i386-linux-gnu/crt1.o: In function `_start':
(.text+0x18): undefined reference to `main'
collect2: error: ld returned 1 exit status
```
[Try it online!](http://ideone.com/oYZvTj)
[Answer]
# Huh?, 0 bytes
(no, there's nothing in that code block)
[The language](https://esolangs.org/wiki/Huh%3F) is named for its output, so...
In [the implementation I checked](https://github.com/kade-robertson/pythuhn/blob/master/pythuhn.py), the interpreter takes the length mod 8 of each line of a given file, and switches depending on the result. For zero, it prints `Huh?`. Since it strips trailing newlines, you could also do a 1 byte (`\n`) version.
Note that it's not outputting to stderr or caseswapping or any other trickery. It's just that Huh?'s very confused interpreter finally came in handy.
[Answer]
## C, ~~15~~ ~~14~~ 5 Bytes
Compiled C on a Linux machine with a German locale:
`main;`
It will try to call the variable `main` which is not allowed because `main` is stored in the bss section which has the NX bit set, therefore generates a SIGSEGV and prints `Speicherzugriffsfehler` (german for Segmentation fault) on stderr.
Stolen from <https://stackoverflow.com/a/1770717/6082851>
---
**Old answer with 14 Bytes**
Compiled C on a Linux machine with the C locale on AMD64, compiled with gcc:
`main(a){a/=0;}`
This will create a division by zero exception and print `Floating point exception` on stderr. Not sure about other implementation, architectures or compilers since it uses UB.
---
**Old answer with 15 Bytes**
Compiled C on a Linux machine with a German locale:
`main(){main();}`
It will run to a stack overflow and print `Speicherzugriffsfehler` (german for Segmentation fault) on stderr.
[Answer]
# [V](https://github.com/DJMcMayhem/V), 2 bytes
```
¬U
```
[Try it online!](https://tio.run/nexus/v#@39oTej//wA "V – TIO Nexus")
The obvious answer is:
```
év~
```
[Try it online!](https://tio.run/nexus/v#@394ZVnd//8A "V – TIO Nexus")
Which is "Insert the letter 'v', and toggle case". However, since you allow for junk output before/after the language name, this works too.
The `¬` command takes two characters for input, and inserts every ASCII character between them. If we don't supply the second character, it automatically defaults to `ÿ` (ASCII 0xff), so this program inserts every character in the latin1 encoding between `U` and `ÿ`.
[Answer]
## [brainfuck](https://esolangs.org/wiki/Brainfuck), 54 bytes
```
+[[-<]-[->]<-]<.<<<<.>>>>-.<<-.<.>>.<<<+++.>>>---.<++.
```
Outputs `brainfuck`, assuming an 8-bit tape open on the left. [Try it online!](https://tio.run/nexus/brainfuck#FYiBCQAwCMMOKtkFxUfE/89wNRAIWXXjoakx4@fwKpCM6XuS7kJWcvcD "brainfuck – TIO Nexus")
As always, partial credits go to [@primo's Hello, World! answer](https://codegolf.stackexchange.com/a/68494/21487).
### Alternatives with different casing
**Brainfuck** (62 bytes):
```
+[<-[-<]-[->]<<]<---.<<<<<<--.>>>-.<+.<.>---.<<+++.>>---.<---.
```
**BrainFuck** (68 bytes):
```
-[[-<]->+[->]<-]<<.<<<<<--.>>+.<-.+++++.>>>------.<<<<+++.>>++.<---.
```
[Answer]
# [Poetic](https://mcaweb.matc.edu/winslojr/vicom128/final/index.html), 229 bytes
```
why?w-h-y?always a war,many flaws,a sham,a fraud,a sad day
luxury a la shahs,a day a la Buddha?ah,many days usually always a burn
a husband hungry?uh-huh
awful suburbs,always a handful
sadly,a man runs harshly away
hardly unusual
```
[Try it online!](https://mcaweb.matc.edu/winslojr/vicom128/final/tio/index.html?NY7BDcQwCAT/roICkhosXSdroRwP4ocR8lF9DifKCy077DIl6txljwqdCCPQxNhO9KBDMW0DmeDMcQw4LwkmRhT1n4/IA70RWWjun8XHmQUV8kTxinZzqCbwNjUfvYDEraFzzv4dUV12cSmYhyuZJ9Qy@r2RJNMo@YVGNmY8De@WxjBZ6QmWFGmT97vzuhr4Dw)
Prints `Poetic`.
This was an interesting challenge. Not only did I have to write the shortest program that prints `Poetic`, but I challenged myself to create a somewhat coherent series of sentences without using `p`, `o`, `e`, `t`, `i`, or `c` (in keeping with the spirit of the language). That makes this program a "lipogram".
[Answer]
## Python 2, 2 bytes, 1 character
```
è
```
output...:
[![output](https://i.stack.imgur.com/oDhlk.png)](https://i.stack.imgur.com/oDhlk.png)
[Answer]
# Python, ~~27~~ ~~53~~ ~~49~~ ~~48~~ ~~45~~ 31 bytes
-3 bytes from @wizzwizz4
```
exec'IM\x50ORT THIS'.swapcase()
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m728oLIkIz_PaMGCpaUlaboW-1MrUpPVPX1jKkwN_INCFEI8PIPV9YrLEwuSE4tTNTQhqqCKYZoA)
Prints the following text, which has "Python" on the first line.
```
The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
```
[Answer]
# MATLAB, 3 bytes
```
ver
```
Output is as follows. Irrelevant info has been replaced by `[...]`). Some parts of the output may change depending on version, installed toolboxes etc.
```
-----------------------------------------------------------------------------------------
MATLAB Version: 8.6.0.267246 (R2015b)
MATLAB License Number: [...]
Operating System: [...]
Java Version: Java 1.7.0_60-b19 with [...]
-----------------------------------------------------------------------------------------
MATLAB Version 8.6 (R2015b)
Communications System Toolbox Version 6.1 (R2015b)
Curve Fitting Toolbox Version 3.5.2 (R2015b)
[...]
Wavelet Toolbox Version 4.15 (R2015b)
```
[Answer]
# [><>](https://esolangs.org/wiki/Fish), ~~12~~ 10 bytes
```
"2,:o:2-o|
```
This will continually print ><> until the interpreter runs out of space.
[Try it online!](https://tio.run/nexus/fish#@69kpGOVb2Wkm1/z/z8A "><> – TIO Nexus")
12 byte version below for those who like a clean output. Recommended by Aaron (no error, 1 output)
```
":3+:o$1+oo;
```
[Answer]
# [C](http://savannah.nongnu.org/projects/tinycc), 1 byte
```
]
```
Output:
```
.code.tio.c:1: error: declaration expected
```
[Try it online!](https://tio.run/##S9YtSU7@/z/2/38A "C (tcc) – Try It Online")
[Answer]
# JAVA, 1 byte
```
1
```
The output to stderr is:
```
Main.java:1: error: class, interface, or enum expected
1
^
1 error
Error: Could not find or load main class Main
Command exited with non-zero status 1
Command being timed: "/srv/wrappers/java-openjdk"
User time (seconds): 1.40
System time (seconds): 0.80
Percent of CPU this job got: 40%
Elapsed (wall clock) time (h:mm:ss or m:ss): 0:05.40
Average shared text size (kbytes): 0
Average unshared data size (kbytes): 0
Average stack size (kbytes): 0
Average total size (kbytes): 0
Maximum resident set size (kbytes): 44564
Average resident set size (kbytes): 0
Major (requiring I/O) page faults: 205
Minor (reclaiming a frame) page faults: 11301
Voluntary context switches: 2666
Involuntary context switches: 1677
Swaps: 0
File system inputs: 78312
File system outputs: 0
Socket messages sent: 0
Socket messages received: 0
Signals delivered: 0
Page size (bytes): 4096
Exit status: 1
```
[Answer]
# CSS, 25 bytes
```
:after{content:'\43\53\53
```
Note that extra markup is added to Stack Overflow snippets, causing "CSS" to be displayed more than once. Open an `.html` file with contents
```
<style>:after{content:'\43\53\53
```
to see the result as intended.
[Answer]
# J, 2 bytes
```
a.
┌┬┐├┼┤└┴┘│─ !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~��������������������������������������������������������������������������������������������������������������������������������
```
`a.` returns the alphabet of the J language — a built-in list of all bytes.
## My original: 4 bytes
```
%:_1
0j1
```
This just seems pretty cool to me. The square root (`%:`) of negative 1 (`_1`) is *i* (`0j1`).
[Answer]
# bash CLI, 9
```
printf $0
```
---
If you want an actual script and not just a command at the interactive command line, then you can do this:
# bash, 13
```
printf $SHELL
```
Outputs `/bin/bash`
[Answer]
# brainfuck, 105 Bytes
```
--[----->+<]>----.[--->+<]>----.+++[->+++<]>++.++++++++.+++++.--------.-[--->+<]>--.+[->+++<]>+.++++++++.
```
Try it online [here](https://copy.sh/brainfuck/?c=LS1bLS0tLS0-KzxdPi0tLS0uWy0tLT4rPF0-LS0tLS4rKytbLT4rKys8XT4rKy4rKysrKysrKy4rKysrKy4tLS0tLS0tLS4tWy0tLT4rPF0-LS0uK1stPisrKzxdPisuKysrKysrKysu)
[Answer]
## BASIC (ZX Spectrum), ~~4~~ 2 bytes
*crossed out 4 is still regular 4*
Saved 2 bytes thanks to @ShaunBebbers.
```
0õ
```
Note: In the ZX Spectrum character set, these bytes display as
```
0 PRINT
```
When you enter this in, the Spectrum starts by parsing an optional number followed by a line of code. Normally the line number is `1..9999` which causes the code to be added to the stored program. However if no line number is supplied then the code is executed immediately instead. Unfortunately a bug in the Spectrum means that it mistakes a line number of zero for no line number at all, but it still tries to execute the zero as part of the line of code, which is illegal, thus causing the error.
The previous 4-byte version generates a true error rather than relying on an interpreter bug:
```
õ°""
```
Note: In the ZX Spectrum character set, these bytes display as
```
PRINT VAL ""
```
which outputs
```
C Nonsense in BASIC, 0:1
```
because the empty string is not a valid numeric expression. (I could of course have used any statement that takes a single integer.) If this answer is unacceptable, then for 6 bytes you can write a program consisting of a single line with one of the keywords that accepts no arguments, then use `POKE` to replace it with an illegal keyword, then attempt to `RUN` the program.
[Answer]
# dc, 6
```
25699P
```
Outputs `dc`.
[Try it online](https://tio.run/nexus/dc#@29kamZpGfD/PwA).
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 8 bytes
```
'IWR C80
```
Takes the character `I` and `WR`aps it in `C`hr(`80`), resulting in `PIP`. [Try it online!](https://tio.run/nexus/pip#@6/uGR6k4Gxh8P8/AA)
Using the `I` feels a bit like cheating, so here are [two 9-byte solutions](https://tio.run/nexus/pip#@x/NpVDlYBEeVOVgaMqloFFloR1nbmCuyRX7//9/3RwA) that don't use any of `PpIi`:
```
z@8WRz@15
(z8+^707)
```
Both output `pip`. I'm particularly pleased with the second one:
```
^707 Split 707 into a list of characters [7;0;7]
8+ Add 8 to each one [15;8;15]
(z ) Use list to index into lowercase alphabet ["p";"i";"p"]
By default, lists are printed without a separator
```
For proper capitalization, we need a [10-byte solution](https://tio.run/nexus/pip#@6/uGR6k4GxhEFbBxWWt4JdfkmqlEAYTVCjOyC/NSVHISCxLVSjPL8pOTdFRSCotUUgEkukKBUWpZal5JakpCplAoRKFkoxUhZLM3FSF/DQwOzkjMScnNS89Ve//fwA):
```
'IWR C80Vx
```
How this one works is left as an exercise for the reader. ;^)
[Answer]
# C#, ~~60~~ 67 bytes
```
class P{static void Main(){System.\u0043onsole.Write("\x43\x23");}}
```
[Answer]
# Forth, 5 bytes
```
WORDS
```
[**Try it online**](https://tio.run/nexus/forth-gforth#@x/uH@QS/P8/AA)
Prints a list of every word in the language. `Forth` happens to be in the list (first word on line 125), though I don't know what it does.
[Answer]
# Excel, 35
Closing parens already discounted.
Simple enough:
* `A1` - `=RIGHT(0=1)` - `E` from `FALSE`
* Output - `=A1&ROMAN(90)&A1&ROMAN(50)` - `EXCEL`
`ROMAN(90)` = `XC`, `ROMAN(50)` = `L`
[Answer]
# [R](https://www.r-project.org/), 11 bytes
```
cat("\x52")
```
[Try it online!](https://tio.run/nexus/r#@5@cWKKhFFNhaqSk@f8/AA "R – TIO Nexus")
] |
[Question]
[
**Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers.
---
This question does not appear to be about code golf or coding challenges within the scope defined in the [help center](https://codegolf.stackexchange.com/help/on-topic).
Closed last year.
The community reviewed whether to reopen this question last year and left it closed:
>
> Original close reason(s) were not resolved
>
>
>
[Improve this question](/posts/21571/edit)
**Problem:**
Generate a sentence that can be read and understood. It must contain a subject, verb, and object, and tenses and plurals must match. The program must also be able to generate several different sentences to qualify.
**Rules:**
* Hard-coding the sentences is not permitted, and nor is reading them directly from a file (i'm looking at you, unclemeat)
* You can have any number of word lists
* Submit an example sentence or 2 that have been generated by your program
* Any language is accepted
* It's a [popularity-contest](/questions/tagged/popularity-contest "show questions tagged 'popularity-contest'"), so the most upvoted answer wins
[Answer]
## Matlab
```
why
```
example of outputs:
```
>> why
The programmer suggested it.
>> why
To please a very terrified and smart and tall engineer.
>> why
The tall system manager obeyed some engineer.
>> why
He wanted it that way.
```
[This is one of Matlab's easter eggs]
**EDIT:** you can see the code of this function here: [why.m](http://opg1.ucsd.edu/~sio221/SIO_221A_2009/SIO_221_Data/Matlab5/Toolbox/matlab/elmat/why.m)
[Answer]
# Bash
```
fgrep '/* ' /usr/src/linux* -r | cut -d '*' -f 2 | head -$((RANDOM)) | tail -1
```
Requirements: linux kernel source installed in /usr/src
This pulls random comments out of the kernel source. Whether the sentences are actually **understandable** is open to debate.
Examples of actual output:
* `end of packet for rx`
* `I don't know what to do`
* `256 byte packet data buffer.`
* `The rest of this junk is to help gdb figure out what goes where`
* `Convert page list back to physical addresses, what a mess.`
* `???`
* `Only Sun can take such nice parts and fuck up the programming interface`
[Answer]
# PHP
Given enough time, this will produce all literature, past, present and future. *The rules didn't mention that no other text may be produced.*
The string `'TOS...'` provides a logarithmic scale frequency of the letters to more closely match English. This is used to generate a larger string with the approximate relative letter frequencies.
```
$a = ord('A');
$s = '';
foreach (str_split('TOSRWQPPUALRQTTRGUUUQMMLMFZ') as $i=>$f)
{
if (!ctype_alpha($c = chr($a + $i)))
$c = ' ';
$s .= str_repeat($c, round(exp((ord($f) - $a) / 3.976)));
}
$l = strlen($s) - 1;
for (;;)
echo substr($s, mt_rand(0, $l), 1);
```
Running it, I have discovered such literary gems as:
* `GO NOW` - *You* as a subject is implied.
* `IM AOK` - I'm A-OK
* `IM FDR` - I'm F(ranklin) D(eleano) R(oosevelt)
Also, numerous invectives to concisely express displeasure with the current situation. [Some letters redacted.]
* `F**K`
* `S**T`
As well, the following using the fine-tuned scaling:
* `IS IT ON`
* `I AM STU`
* `I SEE HTML`
[Answer]
# C
```
char*strerror(),i;main(){for(;--i;)puts(strerror(i));}
```
Example output:
>
> Software caused connection abort
>
> Interrupted system call should be restarted
>
>
>
>
There are also plenty of valid sentences output that do not have a subject, verb and object:
>
> Timer expired
>
> File exists
>
>
>
>
[Answer]
# Java
Pulls the intro sentence from a random Wikipedia article:
```
import java.io.InputStream;
import java.net.URL;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
public class RandomSentence {
public static void main (String[] args) throws Exception {
String sentence;
do {
InputStream in = new URL("https://en.wikipedia.org/wiki/Special:Random").openStream();
Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(in);
String intro = doc.getElementsByTagName("p").item(0).getTextContent();
sentence = intro.replaceAll("\\([^(]*\\) *", "").replaceAll("\\[[^\\[]*\\]", "").split("\\.( +[A-Z0-9]|$)")[0];
} while (sentence.endsWith(":") || sentence.length() < 30 || sentence.contains("?"));
System.out.println(sentence + ".");
}
}
```
Sometimes you get unlucky; I try to minimize this by setting a minimum sentence length and filtering out sentences that end with ":" (all disambiguation pages start that way) or contain a "?" (there seem to be many articles with unresolved unknown info marked by question marks). Sentence boundaries are a period followed by whitespace followed by a number or capital letter.
I also filter out text in parentheses (the result is still a valid sentence) to try and remove some periods that aren't sentence boundaries. I filter out square braces to remove source citation numbers. Examples:
>
> * Idle Cure was an arena rock band from Long Beach, California.
> * Self-focusing is a non-linear optical process induced by the change in refractive index of materials exposed to intense electromagnetic radiation.
> * TB10Cs4H3 is a member of the H/ACA-like class of non-coding RNA molecule that guide the sites of modification of uridines to pseudouridines of substrate RNAs.
> * The Six-headed Wild Ram in Sumerian mythology was one of the Heroes slain by Ninurta, patron god of Lagash, in ancient Iraq.
> * Sugar daddy is a slang term for a man who offers to support a typically younger woman or man after establishing a relationship that is usually sexual.
> * Old Bethel United Methodist Church is located at 222 Calhoun St., Charleston, South Carolina.
> * Douglas Geers is an American composer.
>
>
>
If you notice any grammar issues, well, that's your fault for not being a diligent Wikipedia editor! ;-)
[Answer]
Soooo... Since this is [popularity-contest](/questions/tagged/popularity-contest "show questions tagged 'popularity-contest'"), I had some fun with `eval` and with functions. Basically I generate a random number and then execute a random function based on that number (in your face, `switch`!) via `eval`.
# PHP, ~9k valid outputs
```
<?php
//Subjects
function s1(){ echo "I "; $m = rand(1,20); eval ("v".$m."(0);");}
function s2(){ echo "You "; $m = rand(1,20); eval ("v".$m."(0);");}
function s3(){ echo "He "; $m = rand(1,20); eval ("v".$m."(1);");}
function s4(){ echo "She "; $m = rand(1,20); eval ("v".$m."(1);");}
function s5(){ echo "We "; $m = rand(1,20); eval ("v".$m."(0);");}
function s6(){ echo "They "; $m = rand(1,20); eval ("v".$m."(0);");}
//Verbs
function v1($n){ echo "want"; if($n==1)echo"s"; echo " to "; $z = rand(1,10); eval ("a".$z."();");}
function v2($n){ echo "need"; if($n==1)echo"s"; echo " to "; $z = rand(1,10); eval ("a".$z."();");}
function v3($n){ echo "ha"; if($n==1){echo"s";}else{echo"ve";} echo " to "; $z = rand(1,10); eval ("a".$z."();");}
function v4($n){ echo "wanted to "; $z = rand(1,10); eval ("a".$z."();");}
function v5($n){ echo "needed to "; $z = rand(1,10); eval ("a".$z."();");}
function v6($n){ echo "had to "; $z = rand(1,10); eval ("a".$z."();");}
function v7($n){ echo "eat"; if($n==1)echo"s"; echo " "; $w = rand(1,20); eval ("o".$w."();");}
function v8($n){ echo "think"; if($n==1)echo"s"; echo " about "; $w = rand(1,20); eval ("o".$w."();");}
function v9($n){ echo "ate "; $w = rand(1,20); eval ("o".$w."();");}
function v10($n){ echo "thought about "; $w = rand(1,20); eval ("o".$w."();");}
function v11($n){ echo "draw"; if($n==1)echo"s"; echo " "; $w = rand(1,20); eval ("o".$w."();");}
function v12($n){ echo "drew "; $w = rand(1,20); eval ("o".$w."();");}
function v13($n){ echo "smell"; if($n==1)echo"s"; echo " like "; $w = rand(1,20); eval ("o".$w."();");}
function v14($n){ echo "shot "; $w = rand(1,20); eval ("o".$w."();");}
function v15($n){ echo "destroy"; if($n==1)echo"s"; echo " "; $w = rand(1,20); eval ("o".$w."();");}
function v16($n){ echo "destroyed "; $w = rand(1,20); eval ("o".$w."();");}
function v17($n){ echo "melt"; if($n==1)echo"s"; echo " "; $w = rand(1,20); eval ("o".$w."();");}
function v18($n){ echo "saw "; $w = rand(1,20); eval ("o".$w."();");}
function v19($n){ echo "ha"; if($n==1){echo"s";}else{echo"ve";} echo " "; $w = rand(1,20); eval ("o".$w."();");}
function v20($n){ echo "had "; $w = rand(1,20); eval ("o".$w."();");}
//Auxiliaries
function a1(){ echo "punch "; $w = rand(1,20); eval ("o".$w."();");}
function a2(){ echo "drive "; $w = rand(1,20); eval ("o".$w."();");}
function a3(){ echo "mount "; $w = rand(1,20); eval ("o".$w."();");}
function a4(){ echo "see "; $w = rand(1,20); eval ("o".$w."();");}
function a5(){ echo "have "; $w = rand(1,20); eval ("o".$w."();");}
function a6(){ echo "eat "; $w = rand(1,20); eval ("o".$w."();");}
function a7(){ echo "stun "; $w = rand(1,20); eval ("o".$w."();");}
function a8(){ echo "kiss "; $w = rand(1,20); eval ("o".$w."();");}
function a9(){ echo "Ted "; $w = rand(1,20); eval ("o".$w."();");} //See "How I met Your Mother" for further informations :)
function a10(){ echo "blow "; $w = rand(1,20); eval ("o".$w."();");}
//Objects
function o1(){ echo "a cow!<br>";}
function o2(){ echo "a meatball!<br>";}
function o3(){ echo "a car!<br>";}
function o4(){ echo "shoes!<br>";}
function o5(){ echo "pigs!<br>";}
function o6(){ echo "a telephone!<br>";}
function o7(){ echo "some bottles of water!<br>";}
function o8(){ echo "a laptop!<br>";}
function o9(){ echo "my shorts!<br>";} //Quote needed
function o10(){ echo "anchovies!<br>";}
function o11(){ echo "an alarm clock!<br>";}
function o12(){ echo "every second!<br>";}
function o13(){ echo "until the end!<br>";}
function o14(){ echo "sitting!<br>";}
function o15(){ echo "a sword!<br>";}
function o16(){ echo "fire!<br>";}
function o17(){ echo "the dust!<br>";}
function o18(){ echo "in the bedroom!<br>";}
function o19(){ echo "a poor ant!<br>";}
function o20(){ echo "a pencil!<br>";}
//Testing
$n = rand(1,6); eval ("s".$n."();");
$n = rand(1,6); eval ("s".$n."();");
$n = rand(1,6); eval ("s".$n."();");
$n = rand(1,6); eval ("s".$n."();");
?>
```
**Some outputs...**
```
She draws a sword!
They thought about sitting!
You eat my shorts!
He wanted to Ted a cow!
You want to mount a poor ant!
She smells like anchovies!
He wanted to have shoes!
They wanted to see a pencil!
```
[Answer]
# PHP + Project Gutenberg
I wrote a PHP script that turns a plain text document into a set of [word bigrams](http://en.wikipedia.org/wiki/Bigram), which it then uses to generate random sentences. Here are some of the better examples it generated from the entire plain text version of [Patrick Henry's "Give Me Liberty Or Give Me Death" speech](http://www.gutenberg.org/ebooks/6), including the Project Gutenberg small print:
>
> * The Project Gutenberg Etext of nations, and slavery!
> * We apologize for the 200th anniversary of this Small Print!
> * YOU DON'T HAVE NO OTHER WARRANTIES OF ANY KIND, EXPRESS OR INCIDENTAL DAMAGES, But for me, death!
>
>
>
[You can try it out for yourself here.](http://ruletheweb.co.uk/gutenbergordeath.php) Refresh the page for a new batch of sentences.
If you want to run the source code yourself, don't forget to load `$src_text` with your chosen plain text.
```
<html>
<head>
<title>Give Me Liberty Or Give Me Death</title>
<style>
body { margin:4em 6em; text-align:center; background-color:#feb; }
h1 { font-weight:normal; font-size:2em; margin-bottom:2em; }
blockquote { font-style:italic; }
</style>
</head>
<body>
<h1>A collection of quotes randomly generated from Patrick Henry's speech
<a href="http://www.gutenberg.org/ebooks/6">Give Me Liberty Or Give Me Death</a>
(and its accompanying Project Gutenberg blurb).</h1>
<?php
/* Give Me Liberty Or Give Me Death */
/* Plain text available from http://www.gutenberg.org/ebooks/6 */
$src_text = file_get_contents('libertyordeath.txt');
$bigrams = array();
$openers = array();
$loc = 0;
$new_sentence = true;
$last = false;
while (preg_match('/\'?\w+[^\s\[\]\*\(\)"#@]*/',$src_text,$matches,PREG_OFFSET_CAPTURE,$loc)) {
$w = $matches[0][0];
$loc = $matches[0][1]+strlen($w);
$bareword = preg_replace('/\W/','',$w);
if ($last) {
if (!isset($bigrams[$last][$w])) $bigrams[$last][$w] = 1;
else $bigrams[$last][$w]++;
}
if (!isset($bigrams[$bareword])) $bigrams[$bareword] = array();
$last = $bareword;
if ($new_sentence && preg_match('/^[A-Z]/',$w)) {
if (!isset($openers[$w])) $openers[$w] = 1;
else $openers[$w]++;
$new_sentence = false;
}
if (ends_sentence($w)) {
$new_sentence = true;
$last = false;
}
}
/* Now generate ten random sentences */
for ($ns=0; $ns<10; $ns++) {
echo "<blockquote><p>";
/* Choose a starting word */
$sum = 0;
foreach ($openers as $w=>$c) $sum += $c;
$r = mt_rand(0,$sum);
foreach ($openers as $w=>$c) {
$r -= $c;
if ($r<=0) break;
}
/* Barf out additional words until end of sentence reached */
while(1) {
echo "$w ";
if (ends_sentence($w)) break;
$bareword = preg_replace('/\W/','',$w);
$sum = 0;
foreach ($bigrams[$bareword] as $w=>$c) $sum += $c;
$r = mt_rand(0,$sum);
foreach ($bigrams[$bareword] as $w=>$c) {
$r -= $c;
if ($r<=0) break;
}
}
echo "</p></blockquote>\n";
}
function ends_sentence($w) {
if (!preg_match('/[\.\?!]$/',$w)) return false;
if (preg_match('/^(\w|St|Mr|Ms|Mrs|Messrs|i\.e|e\.g|etc|Rd)\./i',$w)) return false;
return true;
}
?>
</body>
</html>
```
[Answer]
**Python**
This entry selects words from whole system dictionary. It takes advantage of the fact that you can make most nouns into verbs and vice-versa. It uses a few heuristics to classify words and avoid obvious impossibilities.
It produces a few nearly sane statements:
```
The snigger westernizes the bacteriologist.
A drizzle stoked the sentiments.
```
Many insane ones:
```
Tipper's orthopaedic knitwear plates a payroll.
A fibula teletypewritered a yogi.
The protozoan's spiralling skydive coats this veterinarian
```
And a lot of stuff that sounds like Monty Python making lewd innuendos:
```
That rolling indictment tarries some bang's bulge.
Some inflammatory tush's intermarriage sextants some postman.
Some pentagon's manufacturer squeaked the wolverine.
A disagreeable participant is entertaining my optimized spoonful.
```
Version 3 has been modified to take any text file as input:
```
$ man python | python words.py
The disabled comma-separated source is using those wizards at exit.
$ cat COPYING | python words.py #GPL
My user accord actions a gnu of software.
$ cat pg2591.txt | python words.py #Grimm's Fairy Tales
Some bargain receives my threepence.
Any wrong worms your world.
$ cat words.py | python words.py #self reflection
Your filter_possesive not_nouned those prepositions.
$ ls /usr/bin | python words.py #directory lists
Their dropbox funziped an arch.
```
Code *(version 3)*:
```
import random
import string
import sys
import re
#words = open("/usr/share/dict/words").readlines()
words = re.sub("[]:;.,:?!<>{}()|=\"`[]",' ',sys.stdin.read(),flags=re.M).split()
words = list(set(words))
articles=('','a ','the ','some ','this ','that ','my ','any ','your ','their ',
'all ','more '
'an ') #an must be last
pl_articles=('','some ','those ','many ','the ','these ')
prepositions = ('of','by','to','for','from','in','with','on','which','when','at',
'into','as','if','near')
conjunctions = ('and','or','but')
verbs = ('is','are','was', 'be','do','came','been','had','have')
pronouns_s = ('he','she','it','we','you')
pronouns_o = ('him','her','them')
possesive=False
modifiers=0
use_prep = None
MAX_MODIFIERS=2
def is_modifier(w):
return ("'" in w or
w[-2:] in ('ry','ed','er','ic','al') or
w[-3:] in ('ing','est','ble','ous') or
w[-4:] in ('less','ical','mmon') )
def is_verb(w):
return (w in verbs or
w[-2:] in ('ed',) or
w[-3:] in ('ing','ize') )
def is_article(w):
return w+' ' in articles or w+' ' in pl_articles
def is_conjunction(w):
return w in conjunctions
def filter_possesive(w,always=False):
global possesive
#allow only one
result = True if "'" in w else False
if result:
if always: return False
if not possesive:
possesive = True
return False
return result
def is_preposition(w):
global use_prep
if w in prepositions:
use_prep = w
return True
return False
def is_adverb(w):
return w[-2:]=='ly'
def is_gerund(w):
return w[-3:]=='ing'
def is_plural(w):
return w[-1]=='s'
def not_verb(w):
return (w in ('you','they','our','yes') or
w[-4:] in ('ness','such') or
w in pronouns_o or w in pronouns_s
)
def not_noun(w):
return (w in verbs)
def getword():
while True:
w=words[random.randrange(len(words))].rstrip()
if w[0] in string.ascii_uppercase: continue
if is_article(w) or is_preposition(w): continue
if filter_possesive(w): continue
#print w
return w
def get_article():
return articles[random.randrange(len(articles)-1)]
#print '--s--'
substr=''
conjunction = False
while True:
w=getword()
if is_modifier(w):
if modifiers < MAX_MODIFIERS:
substr+=w+' '
modifiers+=1
else: continue
elif is_adverb(w) or is_plural(w) or not_noun(w): continue
else:
if is_conjunction(w):
conjunction = w
continue
substr= substr+w+' '
if conjunction:
substr+=conjunction+' '
conjunction = False
continue
if w in pronouns_s:
substr = w+' '
art=''
else:
art = get_article()
if art is 'a ' and substr[0] in 'aeiou': art='an '
substr= string.capwords(art+substr,'.')
break
#print '--v--'
verbstr=''
while True:
w=getword()
if not_verb(w) or filter_possesive(w,True): continue
elif is_adverb(w): verbstr+=w+' '
elif is_gerund(w):
verbstr+='is '+w+' '
break
elif is_verb(w):
verbstr= verbstr+w+' '
break
elif is_modifier(w) or is_conjunction(w): continue
else:
if not is_plural(w):
w=w+'ed' if w[-1]!='e' else w+'d'
verbstr= verbstr+w+' '
break
#print '--o--'
obstr=''
conjunction = False
while True:
w=getword()
if is_modifier(w):
if modifiers<MAX_MODIFIERS:
obstr+=w+' '
modifiers+=1
else: continue
elif is_adverb(w) or not_noun(w) or w in pronouns_s: continue
else:
if is_conjunction(w):
conjunction = w
continue
obstr = obstr+w
if conjunction:
obstr+=' '+conjunction+' '
conjunction = False
continue
if is_plural(w):
art = pl_articles[random.randrange(len(pl_articles))]
else:
art = articles[random.randrange(len(articles)-1)]
if art is 'a ' and obstr[0] in 'aeiou': art='an '
if w in pronouns_o:
obstr=w
else:
obstr= art+obstr
break
#print '--p--'
while use_prep:
w=getword()
if (is_modifier(w) or is_preposition(w) or
is_gerund(w) or not_noun(w) or is_conjunction(w)):
continue
obstr+=' '+use_prep+' '+w
use_prep=None
print substr+verbstr+obstr+'.'
```
[Answer]
## Bash
Inspired by the Matlab answer. Assumes you have `aptitude` installed.
```
r=$[ RANDOM % 7 ]
a=''
for i in `seq $r`; do a=$a'v'; done
if [ $r -ne 0 ]; then a='-'$a; fi
aptitude $a moo
```
Possible outputs (screenshot from [this](https://en.wikipedia.org/wiki/Aptitude_%28software%29) wikipedia article)
![enter image description here](https://i.stack.imgur.com/sZc20.png)
[Answer]
# Python:
```
import random
l = ['Buffalo']
while random.randint(0,5) > 0:
l.append('buffalo')
print ' '.join(l) + '.'
```
## Samples:
* Buffalo buffalo buffalo.
* Buffalo buffalo buffalo buffalo buffalo buffalo buffalo buffalo.
Unfortunately, it has somewhat poor handling of punctuation and capitalization, but then again those weren't listed as requirements.
Also, [here](https://en.wikipedia.org/wiki/Buffalo_buffalo_Buffalo_buffalo_buffalo_buffalo_Buffalo_buffalo#Usage) is a reference.
[Answer]
## Rust + Toki Pona
Any language is accepted, so I wrote a program in [Rust](http://www.rust-lang.org/) that generates some sentences in [Toki Pona](http://en.tokipona.org/wiki/What_is_Toki_Pona%3F).
Toki Pona is an attempt to create a minimal natural language, and it has a super simple and regular grammar. That's a very useful property for this contest!
```
use std::rand;
#[deriving(Rand)]
struct Phrase { a: Option<~GNominal>, b: ~Sujet, c: ~Predicat }
#[deriving(Rand)]
enum Sujet { A(~GNominal), B(~SCompose) }
#[deriving(Rand)]
enum Predicat { C(~GVerbal), D(~PCompose) }
#[deriving(Rand)]
struct SCompose { a: ~Sujet, b: ~Sujet }
#[deriving(Rand)]
struct PCompose { a: ~Predicat, b: ~Predicat }
#[deriving(Rand)]
struct GNominal { a: ~nom::Nom, b: Multi<~adjectif::Adjectif> }
#[deriving(Rand)]
struct GVerbal { a: ~verbe::Verbe, b: Multi<~adjectif::Adjectif>, c: Multi<~ODirect> }
#[deriving(Rand)]
struct ODirect { a: ~GNominal}
#[deriving(Rand)]
enum Multi<T> { Zero, One(T), Two((T,T)) }
mod nom {
#[deriving(Rand)]
#[deriving(ToStr)]
pub enum Nom {akesi,ala,ale,anpa,ante,ijo,ike,ilo,insa,jaki,jan,jo,kala,kalama,kama,kasi,ken,kili,kiwen,ko,kon,kule,kulupu,lape,lawa,len,lete,linja,lipu,luka,lupa,ma,mama,mani,meli,mi,mije,moku,moli,monsi,mun,musi,mute,nanpa,nasin,nena,nimi,noka,oko,olin,ona,pakala,pali,palisa,pana,pilin,pimeja,pini,pipi,poka,poki,pona,seli,selo,sewi,sijelo,sike,sina,sinpin,sitelen,sona,soweli,suli,suno,supa,suwi,tan,tawa,telo,tenpo,toki,tomo,tu,unpa,uta,utala,walo,wan,waso,wawa,weka,wile}
}
mod verbe {
#[deriving(Rand)]
#[deriving(ToStr)]
pub enum Verbe {ante,awen,ijo,ike,jaki,jan,jo,kalama,kama,ken,kepeken,kule,kute,lape,lawa,lete,lili,lon,lukin,moku,moli,musi,mute,nasa,olin,open,pakala,pali,pana,pilin,pimeja,pini,pona,seli,sin,sitelen,sona,suli,suwi,tawa,telo,toki,tu,unpa,utala,wan,wawa,weka,wile,}
}
mod adjectif {
#[deriving(Rand)]
#[deriving(ToStr)]
pub enum Adjectif {ala,ale,anpa,ante,awen,ike,insa,jaki,jan,jelo,kama,kin,kiwen,kon,kule,kute,kulupu,lape,laso,lawa,lete,lili,linja,loje,luka,lukin,mama,meli,mi,mije,moli,monsi,mun,musi,mute,nasa,ni,olin,ona,pali,pimeja,pini,poka,pona,sama,seli,sewi,sike,sin,sina,suli,suwi,taso,tawa,toki,tomo,unpa,uta,walo,wan,wawa,weka,wile,}
}
impl ToStr for Phrase {
fn to_str(&self) -> ~str {
self.a.as_ref().map_or(~"", |g| format!("{:s} la ", g.to_str()))
+ format!("{:s} li {:s}", self.b.to_str(), self.c.to_str())
}
}
impl ToStr for Sujet {
fn to_str(&self) -> ~str {
match *self {
A(ref v) => v.to_str(),
B(ref v) => v.to_str(),
}
}
}
impl ToStr for Predicat {
fn to_str(&self) -> ~str {
match *self {
C(ref v) => v.to_str(),
D(ref v) => v.to_str(),
}
}
}
impl ToStr for SCompose {
fn to_str(&self) -> ~str {
format!("{:s} en {:s}", self.a.to_str(), self.b.to_str())
}
}
impl ToStr for PCompose {
fn to_str(&self) -> ~str {
format!("{:s} li {:s}", self.a.to_str(), self.b.to_str())
}
}
impl ToStr for GNominal {
fn to_str(&self) -> ~str {
format!("{:s} {:s}", self.a.to_str(), self.b.to_str())
}
}
impl ToStr for GVerbal {
fn to_str(&self) -> ~str {
format!("{:s} {:s} {:s}", self.a.to_str(), self.b.to_str(), self.c.to_str())
}
}
impl ToStr for ODirect {
fn to_str(&self) -> ~str {
format!("e {:s}", self.a.to_str())
}
}
impl<T: ToStr> ToStr for Multi<~T> {
fn to_str(&self) -> ~str {
match *self {
Zero => ~"",
One(ref v) => v.to_str(),
Two((ref v,ref w)) => format!("{:s} {:s}", v.to_str(), w.to_str()),
}
}
}
fn main() {
let phrase = rand::random::<Phrase>();
println!("{:s}\n{:?}", phrase.to_str(), phrase);
}
```
I don't speak Toki Pona, but I found the [syntax of Toki Pona as a set of BNF rules](http://fr.wikipedia.org/wiki/Toki_pona#Syntaxe) on Wikipedia. I created one struct or enum for each BNF rule, and I annotated them with `deriving(Rand)`, which gives me a way to generate a random `Phrase` struct for free! Then, I implemented `ToStr` for each of these structs to convert them to a string.
I intentionnaly left the struct names in french, because the BNF rules I found are in french, and also because it reinfoces the multilingual nature of my submission!
## Sample outputs
Some outputs and their translations, that I did based on the [BNF rules](https://code.google.com/p/tokipona/source/browse/trunk/TokiPona/Content/Dictionary/tokipona.xml?r=32) and [a Toki Pona dictionary](https://code.google.com/p/tokipona/source/browse/trunk/TokiPona/Content/Dictionary/tokipona.xml?r=32). I'm sure these translations are mostly wrong, but Toki Pona actually leaves a lot of room for the interpretation of a sentence.
>
> nasin mi tawa la jan li jaki
>
>
>
*While on my trip, someone polluted*
>
> monsi li jaki li jan ike musi
>
>
>
*The butt is dirty and is a funny bad person*
>
> sina li tawa ale jelo e kili tawa e insa
>
>
>
*You moved the fruit and the center to the yellow universe*
## Issues
* I don't check if a verb is transitive or not, thus some sentences are grammatically incorrect.
* Some structs are recursive, and when a rule can be repeated I randomly choose to output 0, 1 or 2 elements. This can lead to veeeeeery long generated sentences, containing thousands of words...
* I cannot really verify the validity of the output, I rely entirely on the BNF syntax, the dictionary, and my own wild guesses :)
[Answer]
# Python
```
import this
```
```
The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
```
[Answer]
## Prolog
Use prolog's backtracking and a generative grammar approximating English grammar to generate *all* possible sentences.
This version has a fairly limited vocabulary and sentence structure, but it should be pretty easy to extend.
The code:
```
% Define the vocabulary
verb(V) :- V = 'eats' | V = 'fights' | V = 'finds'.
subj_pronoun(P) :- P = 'he' | P = 'she' | P = 'it'.
obj_pronoun(P) :- P = 'him' | P = 'her' | P = 'it'.
name(N) :- N = 'alice' | N = 'bob'.
noun(N) :- N = 'cat' | N = 'door' | N = 'pen'.
article(H) :- H = 'the' | H = 'a'.
% Grammar
subject_phrase_short(H) :- subj_pronoun(H)
| name(H).
% Subordinate clause. Don't use verb_phrase here to avoid recursive clauses.
sub_clause([Which, Verb|T], Rest) :- Which = 'which', verb(Verb),
object_noun_phrase_short(T, Rest).
subject_phrase([H|T], Rest) :- subject_phrase_short(H), Rest = T.
object_noun_phrase_short([A, N | T], Rest) :- article(A), noun(N), Rest = T
| obj_pronoun(A), Rest = [N|T].
object_phrase(L, Rest) :- object_noun_phrase_short(L, Rest)
| object_noun_phrase_short(L, Rest1), sub_clause(Rest1, Rest).
verb_phrase([H|T], Rest) :- verb(H), object_phrase(T, Rest).
sentence(S) :- subject_phrase(S, Rest), verb_phrase(Rest, []).
```
Run this query:
```
sentence(L).
```
to generate all possible sentences in this language.
Some sample outputs:
```
L = [he, eats, the, cat] ;
L = [she, finds, a, door] ;
L = [alice, fights, the, door] ;
L = [he, fights, the, cat, which, eats, the, pen] ;
L = [alice, eats, him, which, finds, the, cat] ;
```
(EDIT: Allow object subordinate clauses).
[Answer]
# Python
As you know, you can do anything in python with few `import`s.
This simple task can be accomplished with this 2 lines python script.
```
import random
print ("I like the number "+str(random.uniform(0,1)))
```
The number of sentences generated by this script is quate huge: `10^12` different sentences.
If reading a sentece takes you ~0.5 sec, then reading them all will take more than 15000 years!
Some sample sentences:
* `I like the number 0.444371877853`
* `I like the number 0.358614422548`
Yet all the generated sentences contains a subject, a verb and an object.
UPDATE:
I received some critiques about some sophisticated words that this complex tool may produce. Here is a slightly longer version which should be in agreement with most of the wordlists.
```
import random
print ('I like the number'+''.join([' '+{'0':'zero','.':'point','1':'one','2':'two','3':'three','4':'four','5':'five','6':'six','7':'seven','8':'eight','9':'nine'}[digit] for digit in str(random.uniform(0,1))])+'.')
```
Here are some sample sentences:
* `I like the number zero point six three five nine zero eight one five eight four two four.`
* `I like the number zero point four nine zero eight four four three two zero six two seven.`
[Answer]
Playing with the Mathematica internal dictionary:
```
res = {};
SeedRandom[42 + 1];
Do[
(While[
If[(c = Flatten@WordData[RandomChoice[WordData[All]], "Examples"][[All, 2]]) != {},
StringPosition[(c1 = RandomChoice@c), "'" | "-" | "\\" | "`"] != {}, True, True]];
sp = ToLowerCase /@ StringSplit[c1, (WhitespaceCharacter .. | ",")];
toChange = RandomSample[Range@#, RandomInteger[IntegerPart[{#/2, #}]]] &@Length@sp;
If[StringPosition[ToString@WordData[sp[[#]], "Definitions"], "WordData"] == {},
sp[[#]] = RandomChoice@ WordData[All, RandomChoice@WordData[sp[[#]], "PartsOfSpeech"]]]
& /@ toChange;
AppendTo[res, StringJoin@Riffle[sp, " "]];)
,
{10}];
res
```
You get lucky, say, 70% of the time.
It generates things like:
>
> a amygdaloid electric circuit
>
> yonder Parkia was unrestrictive though ragged
>
> his longanimous society
>
> Doctor of Education unintelligible reply to kibbutz
>
> little musical theater against Julius Caesar
>
> an Tai nuthatch
>
> mow down in sportive center contra thy niggardliness
>
> the required extrinsic detergents
>
> sans necromantic sorcerer
>
> these vena pectoralis opposite mine latria trophy wife trend-setting investors brown
>
> what man-portable field of fire
>
> umbra charmingly whereunto my answer
>
> another screw-loose debris storm scentless aslant Aral Sea complex waffle
>
> for professed delight mongoloid type metal
>
>
>
but sometimes:
>
> mine adoption pro least battle of Lutzen would cash draw in during whiles Hejira of the cleaver
>
> nine common shiner subduction genus Seiurus heartwarming her audience
>
>
>
Oh well, its use of English is better than mine.
[Answer]
# VBA/Excel
[edit 2]
Have taught it how to conjugate verbs, examples below are simple past tense:
>
> The moderate wild cocaine slid abreast of the historic instant decision.
> The regional safe chapter snapped inside of the numerous random entity.
> The yellow right domain removed behind the magnetic fragile gender.
> The physical fatal pollution began past the dead poor sensation.
> The cognitive brave theater went to the front of the fragile aware literature.
> The conventional actual output resisted away from the favorite immune site.
> The fixed economic twin recognized out of the evil human necessity.
>
>
>
The relevant code follows, excluding a bunch of boring ancillary parsing and looping functions. The main parts that are missing are the various word lists (by parts of speech) which do pluralization, tenses, conjugations, etc.
All of the word roots are picked randomly, but I force them to be arranged in a particular sentence pattern:
```
Debug.Print getWords("ad adj adj nns vpa1s pl ad adj adj nns")
```
... which is what I used to generate the output above. It follows the general form of, "The quick red fox jumped over the lazy brown dog."
```
Function getWords(strStruc As String) As String
Dim i As Long
Dim s As Long
Dim strIn As String
Dim strOut As String
getWords = ""
s = numElements(strStruc)
For i = 1 To s
strIn = parsePattern(strStruc, i)
Select Case strIn
Case ",", ";", ":", """" 'punctuation
strOut = strIn
getWords = Trim(getWords)
Case "ai", "ad" 'indefinite article, definite article
strOut = getArticle(strIn)
Case "adj" 'adjective
strOut = getWord("adj", 1)
Case "nns" 'noun nominative singular
strOut = getWord("n", 1)
Case "nnp" 'noun nominative plural
strOut = getWord("n", 2)
Case "nps" 'noun posessive singular
strOut = getWord("n", 3)
Case "npp" 'noun posessive plural
strOut = getWord("n", 4)
Case "vpr1s" 'Present 1st Person Singular
strOut = getWord("v", 1)
Case "vpr2s" 'Present 2nd Person Singular
strOut = getWord("v", 2)
Case "vpr3s" 'Present 3rd Person Singular
strOut = getWord("v", 3)
Case "vi" 'Infinitive
strOut = getWord("v", 4)
Case "vpp" 'Present Participle
strOut = getWord("v", 5)
Case "vi" 'Imperative/Subjunctive
strOut = getWord("v", 6)
Case "vpa1s" 'Past Tense First Person
strOut = getWord("v", 7)
Case "vpa2s" 'Past Tense Second Person
strOut = getWord("v", 8)
Case "vpa3s" 'Past Tense Third Person
strOut = getWord("v", 9)
Case "vppr1s" 'Present Progressive First Person Singular
strOut = getWord("v", 10)
Case "vppr2s" 'Present Progressive Second Person Singular
strOut = getWord("v", 11)
Case "vppr3s" 'Present Progressive Third Person Singular
strOut = getWord("v", 12)
Case "vppe1s" 'Present Perfect First Person Singular
strOut = getWord("v", 13)
Case "vppe2s" 'Present Perfect Second Person Singular
strOut = getWord("v", 14)
Case "vpp3s" 'Present Perfect Third Person Singular
strOut = getWord("v", 15)
Case "vi1s" 'Imperfect First Person Singular
strOut = getWord("v", 16)
Case "vi2s" 'Imperfect Second Person Singular
strOut = getWord("v", 17)
Case "v13s" 'Imperfect Third Person Singular
strOut = getWord("v", 18)
Case "vsf" 'Simple Future
strOut = getWord("v", 19)
Case "vfp" 'Future Progressive
strOut = getWord("v", 20)
Case "vc" 'Conditional
strOut = getWord("v", 21)
Case "vcp" 'Conditional Perfect
strOut = getWord("v", 22)
Case "vci" 'Conditional Imperfect
strOut = getWord("v", 23)
Case "pl" 'location prepositions
strOut = getWord("pl", 1)
End Select
getWords = getWords & strOut & " "
Next i
End Function
```
[begin original post]
Still a work in progress, need to add logic for tenses and noun/verb pluralization, viz.:
>
> Your average travel our supposed dose nor a temperature boost beyond my tomato.
>
>
>
... which is parsable, but doesn't make much sense.
>
> The programming enable their dirty fisherman far our pork cast instead no sentence.
>
>
>
Right. Not really a sentence, but better than some JavaScript error messages.
>
> His appeal lift every live question that my lady outline top her English.
>
>
>
The innuendo routine is almost top-notch tho' ...
Code to follow anon. Does this contest have a deadline?
[edit 1]
Code that generated the above.
```
Function getWord(sht As Worksheet) As String
Dim i As Long
Dim freq As Long
Dim c As Long
Dim f As Double
Dim fSum As Double
c = 4
fSum = WorksheetFunction.Count(sht.Columns(c))
f = Rnd() * fSum
i = 2
Do
If i >= f Then Exit Do
i = i + 1
Loop
getWord = sht.Cells(i, 1).Value
End Function
Function PCase(str As String) As String
PCase = UCase(Left(str, 1)) & Right(str, Len(str) - 1)
End Function
Sub doMakeSentences01()
Dim shtIn As Worksheet
Dim shtOut As Worksheet
Dim strSheet As String
Dim rIn As Long
Dim rOut As Long
Dim cFreq As Long
Dim c As Long
Dim strPattern As String
Dim w As Long
Dim strOut As String
Dim strIn As String
Dim strWord As String
cFreq = 4
Set shtOut = Sheets("Output")
rOut = shtOut.Range("A65536").End(xlUp).Row + 1
strPattern = "anvajncanvian"
For rOut = rOut To rOut + 1000
strOut = ""
For w = 1 To Len(strPattern)
Set shtIn = Sheets(Mid(strPattern, w, 1))
strWord = getWord(shtIn)
If w = 1 Then strWord = PCase(strWord)
strOut = strOut & strWord & " "
Next w
strOut = Trim(strOut) & "."
shtOut.Cells(rOut, 1).Value = strOut
Next rOut
End Sub
```
[Answer]
# Perl 5
OK, the guts of the program is just this:
```
use v5.14;
my %pad = (
...
);
sub pad { shift =~ s(\{(.+?)\}){pad($pad{$1}[rand(@{$pad{$1}})])}rogue }
say ucfirst pad '{START}';
```
It's basically a "madlib" engine. To actually generate interesting sentences, you need to populate `%pad` with some data. Here's an example `%pad`...
```
my %pad = (
START => ['{complex}.'],
complex => [
'{simple}',
'{simple}, and {simple}',
'{simple}, and {complex}',
'{simple}, but {simple}',
'{simple}, yet {simple}',
'even though everybody knows {simple}, {simple}',
'not only {simple}, but also {simple}',
],
simple => [
'{thing} {verb}s {thing}',
'{thing} {verb}s {adverb}',
'{thing} is {adjective}',
'{things} {verb} {thing}',
'{things} {verb} {adverb}',
'{things} are {adjective}',
'{thing} {past_verb} {thing}',
'{things} {past_verb} {thing}',
],
thing => [
'the {adjective} gorilla',
'the {adjective} mailbox',
'Archbishop Desmond Tutu',
'the beef salad sandwich',
'the {adjective} stegosaur',
'the summit of Mt Everest',
'Chuck Norris',
'the cast of television\'s "Glee"',
'a {adjective} chocolate cake',
],
things => [
'{adjective} shoes',
'spider webs',
'millions of {adjective} eels',
'{adjective} children',
'{adjective} monkeys',
'{things} and {things}',
'the British crown jewels',
],
verb => [
'love',
'hate',
'eat',
'drink',
'follow',
'worship',
'respect',
'reject',
'welcome',
'jump',
'resemble',
'grow',
'encourage',
'capture',
'fascinate',
],
past_verb => [ # too irregular to derive from {verb}
'loved',
'ate',
'followed',
'worshipped',
'welcomed',
'jumped',
'made love to',
'melted',
],
adverb => [
'greedily',
'punctually',
'noisily',
'gladly',
'regularly',
],
adjective => [
'enormous',
'tiny',
'haunted',
'ghostly',
'sparkling',
'highly-decorated',
'foul-smelling',
'{adjective} (yet {adjective})',
'expensive',
'yellow',
'green',
'lilac',
'tall',
'short',
],
);
```
Here's some samples of the wisdom I've discovered from that `%pad`. These sentences have not been edited for length, punctuation, grammar, etc, though I have culled some uninteresting ones and rearranged the order in which the sentences appear - they are no longer in the order they were generated, but instead I'm trying to use them to tell a story: a story I hope you will find both touching and thought-provoking.
* Spider webs are short.
* Spider webs fascinate regularly.
* Short monkeys are sparkling, but spider webs drink greedily.
* Sparkling (yet foul-smelling) monkeys followed the tiny (yet sparkling) gorilla.
* The summit of Mt Everest welcomed the highly-decorated stegosaur.
* Not only the summit of Mt Everest is expensive, but also the cast of television's "Glee" followed the sparkling gorilla.
* The cast of television's "Glee" resembles the lilac mailbox.
* The expensive mailbox is tall, and the expensive stegosaur jumps Chuck Norris, yet green shoes jumped the beef salad sandwich.
* The beef salad sandwich loved Chuck Norris.
* Millions of sparkling eels are green (yet ghostly).
[Answer]
## Ms Word
I'm not sure if this is acceptable, but since html is, I think this should be also acceptable.
```
=rand(1,1)
```
Sample sentences:
>
> On the Insert tab, the galleries include items that are designed to coordinate with the overall look of your document.
>
>
> You can use these galleries to insert tables, headers, footers, lists, cover pages, and other document building blocks.
>
>
>
you can also specify any number of sentences and paragraphs.
[Answer]
A work in progress using [JSoup](http://jsoup.org/) and [simpleNLG](https://code.google.com/p/simplenlg/)
```
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import simplenlg.framework.NLGFactory;
import simplenlg.lexicon.Lexicon;
import simplenlg.phrasespec.SPhraseSpec;
import simplenlg.realiser.english.Realiser;
/**
* Scapes words from Wiktionary then assembles them into sentences
*
* @author pureferret
*
*/
public class SentenceBuilder {
static ArrayList<String> ListOfWordTypes= new ArrayList<>(Arrays.asList("Noun","Verb","Adjective","Adverb","Proper noun","Conjunction"));
private static String RandomWiktWord ="http://toolserver.org/~hippietrail/randompage.fcgi?langname=English";
/**
* @param args
*/
public static void main(String[] args) {
Lexicon lexicon = Lexicon.getDefaultLexicon();
NLGFactory nlgFactory = new NLGFactory(lexicon);
Realiser realiser = new Realiser(lexicon);
ArrayList<String> nounList = new ArrayList<String>();
ArrayList<String> verbList = new ArrayList<String>();
ArrayList<String> adjeList = new ArrayList<String>();
ArrayList<String> adveList = new ArrayList<String>();
ArrayList<String> pnouList = new ArrayList<String>();
ArrayList<String> conjList = new ArrayList<String>();
String word= null;
String wordType = null;
try {
newDoc:
while( nounList.size()<1 ||
verbList.size()<1 ||
// adjeList.size()<2 ||
// adveList.size()<2 ||
pnouList.size()<1){
Document doc = Jsoup.connect(RandomWiktWord).get();
Element bodyElem = doc.body();
word = bodyElem.select("h1>span[dir=auto]").get(0).ownText();
int wtIdx = 0;
while(wtIdx<bodyElem.select("div#mw-content-text span.mw-headline").size()){
wordType = bodyElem.select("div#mw-content-text span.mw-headline").get(wtIdx).id()
.replace("_", " ");
wtIdx++;
switch (wordType) {
case "Proper noun":
pnouList.add(word);
continue newDoc;
case "Noun":
nounList.add(word);
continue newDoc;
case "Verb":
verbList.add(word);
continue newDoc;
case "Adjective":
adjeList.add(word);
continue newDoc;
case "Adverb":
adveList.add(word);
continue newDoc;
case "Conjunction":
conjList .add(word);
continue newDoc;
default:
break;
}
}
}
SPhraseSpec p = nlgFactory.createClause();
p.setSubject(pnouList.get(0));
p.setVerb(verbList.get(0));
p.setObject(nounList.get(0));
String output2 = realiser.realiseSentence(p); // Realiser created earlier.
System.out.println(output2);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.err.println(word + " is a " + wordType);
} catch (IndexOutOfBoundsException e) {
e.printStackTrace();
System.err.println(word + " is a " + wordType);
}
}
}
```
**Issues:**
* Sentences are too simple
* Occasionally 404s (without good handling!)
* Only generates one sentence at a time
* Uses a switch case!
Sample outputs:
>
> Popoloca prickethes runner beans.
>
> Tropic of Capricorn beams up bodles.
>
> Beijing synonymiseds pillow boxes.
>
> Chukchis enculturateds influencing.
>
>
>
[Answer]
## PHP
```
<?php
$trends = file_get_contents('http://www.google.com/trends/hottrends/widget?pn=p1&tn=30');
preg_match_all("/widget-title-in-list'>(.+?)</", $trends, $m);
$q = urlencode($m[1][array_rand($m[1])]);
$page = file_get_contents("http://www.google.com/search?q=$q&btnI=1");
preg_match_all('/[A-Z]([\w,]+ ){2,}[\w, ]+?[.!]/', strip_tags($page), $m);
echo $m[0][array_rand($m[0])];
```
This fetches the 30 most trending google searches, performs an "I Feel Lucky" search, and then displays a random sentence from that page with at least 3 words.
Examples:
*"She was considered a medal favourite in the event."*
*"Kate graduated from high school a year early."*
*"April 15, 2014, to promote compliance with the policy on biographies of living people."*
*"On behalf of Bryan, we, his family, would like to thank everyone for the outpouring of love, prayers and support."*
*"This article is about the American basketball player."*
*"Sorry, your browser either has JavaScript disabled or does not have any supported player."*
[Answer]
# JavaScript (ES6)
```
var t='';for(f of [_=>foo,_=>null.a,_=>0..toString(0)])try{f()}catch(e){t+=e.message+'\n';}t
```
Running it in the console produces
```
foo is not defined
null has no properties
radix must be an integer at least 2 and no greater than 36
```
[Answer]
**Python 2.7**
```
python2.7 -c "import urllib2, pprint; pprint.pprint([str(x[:x.find('<')]) for x in unicode(urllib2.urlopen('http://codegolf.stackexchange.com/questions/21571/generate-an-understandable-sentence').read(), 'utf8').split('<p>') if x.find('<') >= 1][1].split('.')[0])"
```
output:
>
> Generate a sentence that can be read and understood
>
>
>
[Answer]
## Shell Scripting
This script will always display the title of the first question that is currently on top of this site. My assumption is the question title will always be human readable. And it will change dynamically. So whenever a new question comes and when the script is executed, it will give the latest question title.
```
curl "codegolf.stackexchange.com" -s | w3m -dump -T text/html > foo.txt
awk 'f;/more tags/{f=1}' foo.txt > foo1.txt
sed '8q;d' foo1.txt
```
**Trial 1 output**
```
Find words containing every vowel
```
**Trial 2 output**
```
Hello World 0.0!
```
## EDIT
Not using any files. Without files, I can use the below script.
```
value1=$(curl "codegolf.stackexchange.com" -s | w3m -dump -T text/html)
echo "$value1" | grep -A 8 "more tags" | tail -1
```
**Output**
```
Generate an understandable sentence
```
[Answer]
# Yet another Python script
The [answer of user3058846](https://codegolf.stackexchange.com/a/21646/16889) isn't bad, but it displays every sentences, every time. Here, I propose a script that output a random sentence from the *Zen of Python*:
```
from random import choice
import subprocess
proc = subprocess.Popen(('python', '-c', 'import this'), stdout=subprocess.PIPE,)
# Get output of proc, split by newline
sentences = [x for x in proc.communicate()[0].splitlines() if x != '']
print(choice(sentences))
```
In one line, for [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") fans:
```
from random import choice;import subprocess;print(choice([x for x in subprocess.Popen("python -c 'import this'",shell=True,stdout=subprocess.PIPE).communicate()[0].split('\n') if x]))
```
(Boooh, dirty.)
Examples:
```
>>> a() # <--- a is just the oneline above
Explicit is better than implicit.
>>> a()
Although never is often better than *right* now.
>>> a()
Errors should never pass silently.
>>> a()
Special cases aren't special enough to break the rules.
```
---
## Another fun way in Python
Thanks to @TheDoctor pour the idea :-) Silent the import output and then play with the pseudo-encrypted dict in the module.
```
import sys, random
_stdout, sys.stdout = sys.stdout, open('/tmp/trash', 'w') # silent the stdout just for the import
import this
sys.stdout = _stdout
lst = []
for x in this.s:
if x in this.d:
lst.append(this.d[x])
else:
lst.append(x)
# Then, example from the interpreter
>>> random.choice(''.join(lst).split('\n'))
'Beautiful is better than ugly.'
>>> random.choice(''.join(lst).split('\n'))
'Although never is often better than *right* now.'
>>>
```
[Answer]
# Python 3
Guaranteed to generate grammatical output! (Usually.)
```
import re
from urllib.request import urlopen
from random import random, choice as pick
letters = "abcdefghijklmnopqrstuvwxyz"
wordregex = re.compile(r'a href="/wiki/([a-z_]+)"')
subjects = {1:("I","we"), 2:("you",), 3:("they",)}
objects = {1:("me","us"), 2:("you",), 3:("him","her","it","them")}
patterns = ["{0} {1} {2}.",
"Why do {0} {1} {2}?",
"It's because {0} {1} {2}, of course.",
"Did {0} {1} {2}?",
"{0} will not {1} {2}!",
]
wiktionaryurl = "http://en.wiktionary.org/w/index.php?" + \
"title=Category:English_{0}&pagefrom={1}"
def getWord(category):
subset = pick(letters) + pick(letters)
url = wiktionaryurl.format(category, subset)
try:
response = urlopen(url)
except:
print("An error occurred while connecting to the Internet!")
return "fail"
page = str(response.read())
word = pick(wordregex.findall(page))
word = word.replace("_", " ")
return word
for i in range(10):
verb = getWord("transitive_verbs")
subjPerson = pick([1,2,3])
subj = pick(subjects[subjPerson])
if random() > 0.4:
# Use a plural noun for the object
obj = getWord("plurals")
else:
# Use a pronoun for the object
objPerson = pick([1,2,3])
while subjPerson == objPerson and subjPerson in (1,2):
objPerson = pick([1,2,3])
obj = pick(objects[objPerson])
sentence = pick(patterns).format(subj, verb, obj)
sentence = sentence[0].upper() + sentence[1:]
print(sentence)
```
To make it perfectly grammatical, delete the underscore from `wordregex`. This will disallow multi-word entries that lead to bad sentences such as "We zip up you."
Sample run:
```
We appropriate journals.
I will not masticate you!
Did you lower me?
Why do I sag estoppels?
They will not proofread you!
It's because you unbeguile mucosae, of course.
Why do I flack zakuski?
You will not visit junkpiles!
Did they goat us?
Why do we prefix nolids?
```
Favorite output so far:
```
They you her.
```
Look it up: <http://en.wiktionary.org/wiki/you#Verb>.
[Answer]
# Python
Result:
```
$ python mksentence.py
infringement lecture attainment
Produce more? (Y/N)y
impeachment recoup ornament
Produce more? (Y/N)y
maladjustment edit discouragement
Produce more? (Y/N)y
embellishment guest punishment
Produce more? (Y/N)y
settlement section escapement
Produce more? (Y/N)y
segment withhold recruitment
Produce more? (Y/N)
```
I used the word list from here [Find words containing every vowel](https://codegolf.stackexchange.com/questions/20936/find-words-containing-every-vowel/20982#20982)
Some more rules can be added. For example, if a word ending with "ness" and the word also exist in set without the suffix, then it's a noun.
Source code:
```
#!/usr/bin/env python
# vim: set fileencoding=utf-8 ts=4 sw=4 tw=72 :
from __future__ import (unicode_literals, absolute_import,
division, print_function)
import random
if __name__ == "__main__":
filename = 'corncob_lowercase.txt'
noun = set()
verb = set()
whole_words_set = {word.rstrip() for word in open(filename)}
for word in whole_words_set:
if word.endswith('ment'):
noun.add(word)
elif word.endswith('ing'):
if word[:-3] in whole_words_set:
verb.add(word[:-3])
elif word[:-3]+"e" in whole_words_set:
verb.add(word[:-3]+"e")
noun_list = list(noun)
verb_list = list(verb)
while True:
sentence = "%s %s %s" % (random.choice(noun_list),
random.choice(verb_list),
random.choice(noun_list))
print(sentence)
if input("Produce more? (Y/N)").lower() == "n":
break
```
[Answer]
## Bash
Trying to run a program that exists but is not installed gives this (in Linux Mint 13).
```
$ say
The program 'say' is currently not installed. To run 'say' please ask your administrator to install the package 'gnustep-gui-runtime'
```
[Answer]
# Python 3
Another take at *The Zen of Python*, inspired by [Maxime's answer](https://codegolf.stackexchange.com/a/21805/344).
```
import codecs
import os
import sys
import random
stdout = sys.stdout
sys.stdout = open(os.devnull, 'r+')
import this
sys.stdout.close()
sys.stdout = stdout
zen = codecs.decode(this.s, 'rot-13').splitlines()
print(random.choice(zen))
```
] |
[Question]
[
# Winner: [Aditsu's CJam answer](https://codegolf.stackexchange.com/questions/32267/play-the-bzzt-game/32287#32287)! A whopping 25 bytes! Nice!
You may continue to submit your answer, however you can no longer win. Original post kept for posterity:
---
The "Bzzt" game is a game where you must count to a number (in this case 500). However, if the number has a 3 in it, or is divisible by 3, you don't say the number. Instead, you say "Bzzt".
Rules:
* You can't hard-code the numbers.
* The number only has to satisfy at least 1 of the following requirements
+ Divisible by 3
+ Number contains a 3
* Some type of separator is mandatory (12bzzt14 doesn't count)
* Score is measured in bytes.
* You must count exactly to 500, starting at 1 or 0 (you chose).
* The numbers must be output, but it doesn't matter how (e.g., stdout, writing to a text file, etc.).
* 0 can be divisible by 3 or not divisible. You can choose.
* You can output the numbers one at a time (ex, output 1, then 2, then bzzt, then 4, etc) or all at once (e.g., output 1 2 bzzt 4 5).
* You must replace the letter 3 with the word "bzzt". This is not case sensitive (bZzt, Bzzt, bzzt are all okay).
---
* This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge, so the shortest code wins.
* This contest ends June 30th 2014 (7 days from posting).
[Answer]
# CJam - 25
```
501{3sI3%<Is-I"bzzt"?N}fI
```
Thanks Howard :)
Try it at <http://cjam.aditsu.net/>
**Explanation:**
`501{…}fI` is basically `for(int I=0; I<501; ++I) {…}`
`3s` converts 3 to string, i.e. "3"
`I3%` is `I` % 3
`<` gets the left substring - `"3".substring(0, I % 3)` - which is "" for `I` % 3 == 0 and "3" otherwise
`Is` converts `I` to string
`-` with 2 strings does a set difference, resulting in an empty string iff `I` % 3 == 0 (the first string was empty) or `I` has a 3 digit in it
`…I"bzzt"?` is like `… ? I : "bzzt"`; the previous string is treated as a boolean value, where "" is false and any other string is true
`N` adds a newline
[Answer]
## Ruby, 43
```
501.times{|a|puts"#{a}"[?3]||a%3<1?:Bzzt:a}
```
Pretty straightforward.
Edit: Saved one byte, thanks Howard!
[Answer]
# seq and GNU sed - 42 33 31 30
Works directly in dash, some other shells might need to have history expansion disabled, e.g. with bash `set +H`:
```
seq 500|sed 0~3!{/3/!b}\;cbzzt
```
[Answer]
# x86 machine code on DOS (.com file) - 71 bytes
```
00000000 31 c9 68 20 24 89 e5 89 c8 bb 03 00 31 d2 f7 f3 |1.h $.......1...|
00000010 85 d2 74 1a 89 c8 b3 0a 31 d2 f7 f3 80 fa 03 74 |..t.....1......t|
00000020 0d 80 c2 30 86 d6 52 44 85 c0 75 ea eb 08 89 ec |...0..RD..u.....|
00000030 68 7a 74 68 62 7a 89 e2 b4 09 cd 21 89 ec 41 81 |hzthbz.....!..A.|
00000040 f9 f4 01 7e c2 59 c3 |...~.Y.|
```
Prints the required output to stdout with space as a delimiter; can be run without problems in DosBox.
Commented assembly:
```
org 100h
start:
; 0 - 500 counter
xor cx,cx
; we'll use the stack as scratch space to build the strings to print
; first of all, push ' $' on the stack (in reverse order); this will be
; the end of each string we'll print
push 2420h
; save the stack pointer, to get back to this position after each print
mov bp,sp
mainloop:
; first try to divide by three
mov ax,cx
mov bx,3
xor dx,dx
div bx
test dx,dx
; no remainder => bzzt
jz bzzt
; otherwise, go into the decimal-print loop
mov ax,cx
divloop:
; bh is already at zero due to the mov bx,3 above
mov bl,10
xor dx,dx
; divide by 10
div bx
; remainder is 3 => bzzt
cmp dl,3
je bzzt
; convert number to digit
add dl,'0'
; trick: we move the digit to the upper byte of dx: this allows us to
; push the whole dx (you cannot do push dl) but to easily kill the
; undesidered byte by touching the stack pointer (it will be overwritten
; by the next stack operation/ignored by the print)
xchg dl,dh
push dx
inc sp
; check is there anything left to print, rinse & repeat
test ax,ax
jnz divloop
; skip straight to print
jmp print
bzzt:
; since we may be here from inside divloop, reset the stack pointer to
; where we left ' $'
mov sp,bp
; push 'bzzt'
push 747ah
push 7a62h
print:
; print what is on the stack
mov dx,sp
mov ah,9h
int 21h
; move us back to ' $'
mov sp,bp
; increment cx and repeat while we are <=500
inc cx
cmp cx,500
jle mainloop
end:
; fix back the stack pointer to the original value (=kill the first push)
pop cx
; quit
ret
```
[Answer]
# Perl - 35 ~~40~~ ~~42~~
```
print$_*!/3/%3?$_:bzzt,$/for 1..500
```
[Answer]
# PHP, no separator - 62, 61,59,58,52,49 47
It doesn't say there should be a space/newline/separator between them, without:
```
while(++$i<501)echo$i%3*!strpbrk($i,3)?$i:bzzt;
```
**With the separator, 68,67,65,64,58/55,53/52 51/50**
```
while(++$i<501)echo$i%3*!strpbrk($i,3)?$i:bzzt,' '; // 51
while(++$i<501)echo$i%3*!strpbrk($i,3)?$i:bzzt,~õ; // 50
```
* Just found a small 'cheat', don't need a space after `echo`, saved me a bit.
* The `~õ` creates a newline
* Another small 'cheat', the bzzt doesn't need quotes (tested it). Not the way to go, but it works.
---
# Javascript - 54,51 50
Same principle, but javascript functions:
```
for(i=0;i++<500;)alert(i%3<1|/3/.test(i)?'bzzt':i)
```
[Answer]
# Javascript 50 49
-1 byte thanks to core1024
```
for(i=0;i++<500;)alert(i%3*!/3/.test(i)?i:'bzzt')
```
[Answer]
### GolfScript, 30 29 characters
```
501,{:^`3`^3%<?)'bzzt'^if n}/
```
Not so straightforward implementation in GolfScript, can be tested [here](http://golfscript.apphb.com/?c=NTAxLHs6XmAzYF4zJTw%2FKSdienp0J15pZiBufS8%3D&run=true).
[Answer]
## Perl, 36
```
print$_%3&&!/3/?$_:Bzzt,$/for 1..500
```
Edit: I'm not a Perl monk, so core1024 seems to have managed to golf another byte out of this in [his answer](https://codegolf.stackexchange.com/a/32275/84).
[Answer]
## C# (71)
Can be directly executed in LinqPad.
```
for(var i=0;++i<501;)(i%3<1|(i+"").Contains("3")?"buzz":i+"").Dump();
```
[Answer]
# Python (52)
Thanks grc!
```
for i in range(501):print[i,'Bzzt'][i%3<1or'3'in`i`]
```
Old version:
```
print['Bzzt'if'3'in`i`or i%3<1 else`i`for i in range(501)]
```
[Answer]
# Haskell: ~~88~~ ~~82~~ ~~80~~ 79
```
main=mapM_ f[1..500]
f n|n`mod`3<1||'3'`elem`show n=putStrLn"bzzt"
f n=print n
```
[Answer]
# JavaScript ~~66~~ ~~63~~ 60
```
for(a=i=[];i<500;)a[i++]=i%3&&!/3/.test(i)?i:'bzzt';alert(a)
```
Thanks to [edc65](https://codegolf.stackexchange.com/users/21348/edc65) for the suggestion to use array. The output will now be comma-separated.
---
## Old versions
### Version 1a - 66
Print from 1 to 500 in an alert box according to the rule. The output is space-separated.
```
a="";for(i=1;i<501;i++)a+=i%3&&!/3/.test(i)?i+" ":"bzzt ";alert(a)
```
### Version 1b - 65
If we consider 0 to be not divisible by 3, we can shorten the solution to 65 character:
```
a=0;for(i=1;i<501;i++)a+=i%3&&!/3/.test(i)?" "+i:" bzzt";alert(a)
```
### Version 2 - 63
```
for(a=i="";i<501;)a+=++i%3&&!/3/.test(i)?i+" ":"bzzt ";alert(a)
```
Thanks to [grc](https://codegolf.stackexchange.com/users/4020/grc) for the suggestion to reduce the length.
[Answer]
## PowerShell, 42
```
1..500|%{($_,'bzzt')[$_-match3-or!($_%3)]}
```
Mostly Ventero's work, with a little help on syntax by me ;-)
[Answer]
## R, 49 characters
```
a=1:500;b='bzzt';a[!a%%3]=b;a[grep(3,a)]=b;cat(a)
```
Explained:
```
a=1:500 #Creates a vector with all integers from 1 to 500
b='bzzt'
a[!a%%3]=b #Replace all multiples of 3 by 'bzzt', thus coercing all other integers to character strings
a[grep(3,a)]=b #Replaces the character strings containing 3 by 'bzzt'
cat(a) #Print to stdout
```
Usage:
```
> a=1:500;b='bzzt';a[!a%%3]=b;a[grep(3,a)]=b;cat(a)
1 2 bzzt 4 5 bzzt 7 8 bzzt 10 11 bzzt bzzt 14 bzzt 16 17 bzzt 19 20 bzzt 22 bzzt bzzt 25 26 bzzt 28 29 bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt 40 41 bzzt bzzt 44 bzzt 46 47 bzzt 49 50 bzzt 52 bzzt bzzt 55 56 bzzt 58 59 bzzt 61 62 bzzt 64 65 bzzt 67 68 bzzt 70 71 bzzt bzzt 74 bzzt 76 77 bzzt 79 80 bzzt 82 bzzt bzzt 85 86 bzzt 88 89 bzzt 91 92 bzzt 94 95 bzzt 97 98 bzzt 100 101 bzzt bzzt 104 bzzt 106 107 bzzt 109 110 bzzt 112 bzzt bzzt 115 116 bzzt 118 119 bzzt 121 122 bzzt 124 125 bzzt 127 128 bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt 140 bzzt 142 bzzt bzzt 145 146 bzzt 148 149 bzzt 151 152 bzzt 154 155 bzzt 157 158 bzzt 160 161 bzzt bzzt 164 bzzt 166 167 bzzt 169 170 bzzt 172 bzzt bzzt 175 176 bzzt 178 179 bzzt 181 182 bzzt 184 185 bzzt 187 188 bzzt 190 191 bzzt bzzt 194 bzzt 196 197 bzzt 199 200 bzzt 202 bzzt bzzt 205 206 bzzt 208 209 bzzt 211 212 bzzt 214 215 bzzt 217 218 bzzt 220 221 bzzt bzzt 224 bzzt 226 227 bzzt 229 bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt 241 242 bzzt 244 245 bzzt 247 248 bzzt 250 251 bzzt bzzt 254 bzzt 256 257 bzzt 259 260 bzzt 262 bzzt bzzt 265 266 bzzt 268 269 bzzt 271 272 bzzt 274 275 bzzt 277 278 bzzt 280 281 bzzt bzzt 284 bzzt 286 287 bzzt 289 290 bzzt 292 bzzt bzzt 295 296 bzzt 298 299 bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt 400 401 bzzt bzzt 404 bzzt 406 407 bzzt 409 410 bzzt 412 bzzt bzzt 415 416 bzzt 418 419 bzzt 421 422 bzzt 424 425 bzzt 427 428 bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt 440 bzzt 442 bzzt bzzt 445 446 bzzt 448 449 bzzt 451 452 bzzt 454 455 bzzt 457 458 bzzt 460 461 bzzt bzzt 464 bzzt 466 467 bzzt 469 470 bzzt 472 bzzt bzzt 475 476 bzzt 478 479 bzzt 481 482 bzzt 484 485 bzzt 487 488 bzzt 490 491 bzzt bzzt 494 bzzt 496 497 bzzt 499 500
```
[Answer]
# Cobra - 70
```
class P
def main
for i in 501,print if('3'in'[i]'or i%3<1,'Bzzt',i)
```
# Batch - 222
Because I genuinely love this language... for some reason...
```
SETLOCAL ENABLEDELAYEDEXPANSION
for /l %%n in (1,1,500) do (
set a=%%n&set /ai=!a!%%3
if "!a:~0,1!"=="3" set a=Bzzt
if "!a:~1,2!"=="3" set a=Bzzt
if "!a:~2,3!"=="3" set a=Bzzt
if !i!==0 set a=Bzzt
echo !a!>>x)
```
[Answer]
# TI-BASIC - 31 ~~(32)(34)(35)(36)(43)~~
```
:While X<500
:X+1→X
:If not(fPart(X/3
:"bzzt
:Disp Ans
:End
Total: 25 + 6 lines = 31
```
Note that most commands on TI-BASIC are represented as single-byte entities.
The code requires X to be initialized to 0 beforehand (otherwise, it's an extra 3 bytes).
I've made several attempts to shave several bytes, so I'm not detailing everything I've done here, as to not clutter the post. They have mostly been directed at shortening the loop, which I've done in this version by a While loop and by shortening the If condition with the help of the `Ans` variable.
[Answer]
# C, 93
Just for the hell of it...
```
main(i){char s[9]="bzzt";while(i<498+sprintf(s+5,"%d",i))puts(s+5*(i++%3&&!strchr(s+5,51)));}
```
[Answer]
# Julia 64 bytes
```
map(x->x%3==0||contains(string(x),"3")?"Bzzt":string(x),[1:500])
```
[Answer]
# cmd.exe - 91
```
for /l %x in (1,1,500)do @set/a %x%3|find "0">nul&&echo bzzt||echo %x|find/v"3"||echo bzzt
```
...because why use a batch file when a perfectly straightforward one-liner exists...:-)
[Answer]
# groovy - 51
```
500.times{println"$it".find('3')||it%3<1?'bzzt':it}
```
edit: using `times` the printing version is now as short as the "displaying". thanks @will-p
[Answer]
# k4 ~~(37)~~ (35)
```
{$(x;`bzzt)(|/51=$x)|~"."in$x%3}'!501
```
`k4` lacks a built-in modulo command, and using the `q` one would take an extra character; this version (ab)uses the built-in output format to check if the string of the result of dividing `x` by 3 has a decimal point in it.
EDIT:
```
{$(x;`bzzt)(|/51=$x)|x=3*_x%3}'!501
```
Clever as matching the decimal point may be, I can shave two bytes by checking that `3*floor x%3` is still `x`.
[Answer]
# C, 80
Using spaces as separators instead of line breaks.
```
n;main(){for(;n++<500;)printf(n%10^3&&n/10%10^3&&n/100^3&&n%3?"%d ":"bzzt ",n);}
```
[Answer]
## Mathematica, 54 Characters
This feels too straightforward. Shorter solutions must be possible.
```
If[DigitCount[#][[3]] > 0 || #~Mod~3 < 1, Bzzt, #] & /@ Range@500
```
[Answer]
# T-SQL 2008 - 80
Not going to win or anything but fun none the less:
Tweaked thanks to @domager:
```
declare @ int=0t:if(@)like'%3%'or @%3=0print'bzzt'print @;set @+=1if @<501goto t
```
A little known fact, @ is a valid name for a variable. It feels weird as the set based code is the more SQL variant, but shorter is shorter! This version works on any database.
Edit:
I was able to remove two of the semis as they were not needed. I'm pretty sure this is as optimal as it gets.
Edit2:
Never say never. Here it's now even grosser using goto, but it allows us to avoid the block. We can Replace while,begin,end with the shorter if,t:,goto saving 6 characters. We also rearrange statement by rewriting the loop as a pseudo do-while,semantically equivalent.
Edit3:
Yeah, somehow if is now shorter.
Original:
```
select top 501iif(number like'%3%'or number%3=0,'bzzt',str(number))from spt_values where'p'=type
```
Must be run on the master database.
I love T-SQL despite its noisy and ugly ways. There might be a way to make this simpler, but unfortunately, the `iif` built-in requires both sides agree on types. Sql servers precedence rules give int higher precedence than strings. Number is also really long, but aliasing is more characters than it is worth. There might be a better way to turn number in to a string.
Edit: str works too. 2 less characters than ltrim
[Answer]
# VBA: 54
```
for x=0to 500:?iif(x/3=x\3=instr(1,x,3),x,"Bzzt"):next
```
Open up your favorite Office program, hit alt+F11 to open the VBA IDE and paste the code into the immediate pane and press enter.
In VBA, : is the line separator, ? is shorthand for print, iif means inline if (think x?"Y":"N"), x/3 does floating point division and x\3 does integer division, instr returns the position of a char in a string, or 0 otherwise, true=-1 and false=0.
The code basically increments x and outputs x if x/3=x\3=instr(1,x,3) is true and "Bzzt" otherwise. x/3=x\3 compares (float)(x/3) to (int)(x/3) and returns a boolean (0 is false and -1 is true). instr(1,x,3) returns 0 if "3" is not in the number, and a positive integer otherwise. The only time the expression returns true is when (x/3=x\3) is false (0) and instr(1,x,3) is 0, or in other words, when x is not divisible by 3 and does not contain the digit "3", which is exactly what we are looking for.
[Answer]
# Bash, ~~53 52 48~~ 46
```
seq 500|factor|sed '/3.*:\| 3 */cBzzt
s/:.*//'
```
Requires GNU sed (uses the `c` extension).
[Answer]
**Java, 142 131**
thank to WozzeC suggestion
```
public class a{public static void main(String[]a){for(int i=1;i<501;i++)System.out.println(i%3>0&(""+i).indexOf(51)<0?i:"bzzt");}}
```
[Answer]
# R (40) (36)
*This is basically [plannapus](https://codegolf.stackexchange.com/a/32291/18915) answer a little bit shortened, but I can not comment yet*
*Update: -4 characters (see plannapus's comment)*
```
a=1:500;a[grepl(3,a)|!a%%3]='bzzt';a
```
Output:
```
[1] "1" "2" "bzzt" "4" "5" "bzzt" "7" "8" "bzzt" "10" "11" "bzzt" "bzzt" "14" "bzzt" "16" "17" "bzzt" "19" "20" "bzzt" "22" "bzzt" "bzzt" "25" "26" "bzzt" "28" "29" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "40" "41" "bzzt" "bzzt" "44" "bzzt" "46" "47" "bzzt" "49" "50" "bzzt" "52" "bzzt" "bzzt" "55" "56" "bzzt" "58" "59" "bzzt" "61" "62" "bzzt" "64" "65" "bzzt" "67" "68" "bzzt" "70" "71" "bzzt" "bzzt" "74" "bzzt" "76" "77" "bzzt" "79" "80" "bzzt" "82" "bzzt" "bzzt" "85" "86" "bzzt" "88" "89" "bzzt" "91" "92" "bzzt" "94" "95" "bzzt" "97" "98" "bzzt" "100" "101" "bzzt" "bzzt" "104" "bzzt" "106" "107" "bzzt" "109" "110" "bzzt" "112" "bzzt" "bzzt" "115" "116" "bzzt" "118" "119" "bzzt" "121" "122" "bzzt" "124" "125" "bzzt" "127" "128" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "140" "bzzt" "142" "bzzt" "bzzt" "145" "146" "bzzt" "148" "149" "bzzt" "151" "152" "bzzt" "154" "155" "bzzt" "157" "158" "bzzt" "160" "161" "bzzt" "bzzt" "164" "bzzt" "166" "167" "bzzt" "169" "170" "bzzt" "172" "bzzt" "bzzt" "175" "176" "bzzt" "178" "179" "bzzt" "181" "182" "bzzt" "184" "185" "bzzt" "187" "188" "bzzt" "190" "191" "bzzt" "bzzt" "194" "bzzt" "196" "197" "bzzt" "199" "200" "bzzt" "202" "bzzt" "bzzt" "205" "206" "bzzt" "208" "209" "bzzt" "211" "212" "bzzt" "214" "215" "bzzt" "217" "218" "bzzt" "220" "221" "bzzt" "bzzt" "224" "bzzt" "226" "227" "bzzt" "229" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "241" "242" "bzzt" "244" "245" "bzzt" "247" "248" "bzzt" "250" "251" "bzzt" "bzzt" "254" "bzzt" "256" "257" "bzzt" "259" "260" "bzzt" "262" "bzzt" "bzzt" "265" "266" "bzzt" "268" "269" "bzzt" "271" "272" "bzzt" "274" "275" "bzzt" "277" "278" "bzzt" "280" "281" "bzzt" "bzzt" "284" "bzzt" "286" "287" "bzzt" "289" "290" "bzzt" "292" "bzzt" "bzzt" "295" "296" "bzzt" "298" "299" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "400" "401" "bzzt" "bzzt" "404" "bzzt" "406" "407" "bzzt" "409" "410" "bzzt" "412" "bzzt" "bzzt" "415" "416" "bzzt" "418" "419" "bzzt" "421" "422" "bzzt" "424" "425" "bzzt" "427" "428" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "440" "bzzt" "442" "bzzt" "bzzt" "445" "446" "bzzt" "448" "449" "bzzt" "451" "452" "bzzt" "454" "455" "bzzt" "457" "458" "bzzt" "460" "461" "bzzt" "bzzt" "464" "bzzt" "466" "467" "bzzt" "469" "470" "bzzt" "472" "bzzt" "bzzt" "475" "476" "bzzt" "478" "479" "bzzt" "481" "482" "bzzt" "484" "485" "bzzt" "487" "488" "bzzt" "490" "491" "bzzt" "bzzt" "494" "bzzt" "496" "497" "bzzt" "499" "500"
```
[Answer]
# Fortran - ~~118 114~~ 111
A hopelessly unlikely candidate, though originally developed to fit on punch cards. Using all the obscure constructs from the past, some short code may still be written:
```
do3 i=1,500
j=i
if(mod(i,3))2,1,2
1 print*,'bzzt'
cycle
2 goto(1)mod(j,10)-2
j=j/10
if(j>0)goto2
3 print*,i
end
```
The "computed goto" `goto(L1,L2,...,Ln) x` branches to one of the labels L if and only if 1 <= x <= n.
**Edit:** Managed to shave off 4 bytes by rearranging the loop that checks for the digit 3. As a bonus, the code now also contains the arithmetic if-statement `if(x) a,b,c`, which always branches to one of three labels: a if x < 0, b if x == 0 or c if x > 0.
Unfortunately, the first two versions did not produce the correct output. The digit-3 loop now works correctly, and the code now also includes a modern logical if-statement. Three more bytes are gone, because who needs an `enddo` statement? The output may be verified [here](http://ideone.com/2GKoX8).
] |
[Question]
[
A challenge I thought that would be very cool is to make an [interpreter](https://en.wikipedia.org/wiki/Interpreter_(computing)) for a [Turing-complete](https://stackoverflow.com/a/7320/5615509) language of your choosing.
**The rules are simple:**
1. You may use any language to create this interpreter even if it is newer than this challenge.
2. You may use any Turing-complete language as long as it is not the same as the one you are writing it with.
3. You may not simply evaluate code for example use eval functions.
4. An explanation of how you approached this will be nice but not required.
5. This will be scored in bytes.
6. Each submission must be fully working that means that every feature that your chosen language has must be present.
**To be put simply:**
Your task is to create a working interpreter for any Turing-complete language with any language of your choosing.
Good luck!
[Answer]
# [Vim](https://www.vim.org/), interpreting [Malbolge Unshackled](https://esolangs.org/wiki/Malbolge_Unshackled), 2010 bytes
```
o/rd<C-V>
@g^Wy$/rc<C-V>
WD"0p<ESC>^"iC/ra<C-V>
@f^WylWD"xp`o<C-V><DEL>:if@0.@-[len(@-)-1]==21<C-V>
norm o<C-V>
el<C-V>
norm A<C-V><C-R>=nr2char(@-,1)<C-V>
<C-V>
en<C-V>
<ESC>^"aC`i+x/ra<C-V>
Wr0WD"=char2nr(@-,1)<C-V>
p<ESC>^"bC/rw<C-V>
W"yy$-@g^W"xylWy$:if@y>len(@")<C-V>
norm A<C-V><C-R>=repeat(@x,@y-len(@"))<C-V>
<C-V>
en<C-V>
^WWx$p^Wy$/ra<C-V>
WD"0p<ESC>^"cC/rd<C-V>
@g^Wy$/rd<C-V>
WD"0p@u<ESC>^"jC/ra<C-V>
Wyl$p^WW"ny$++@g^Wyl$p^WW"my$@o^WWD"mpx^WR<C-V><C-R>"<C-V><ESC>y$/ra<C-V>
WD"0p<ESC>^"pC^WWD:wh@">2<C-V>
norm"=<C-V><C-V><C-V><C-R>"%3<C-V><C-V><C-V>
p<C-V>
let@"=@"/3<C-V>
endw<C-V>
p<ESC>^"tC^WWD:let@x=@-|let@"=join(map(split(@",'\zs'),{a,b->b*float2nr(pow(3,a))}),'+')<C-V>
"=<C-V><C-R>"<C-V>
p<ESC>^"fCmg@wgg/m<C-V><C-R>- \|m!<C-V>
WWy$:let@s=@-|if@"==-1<C-V>
norm`g^WxPWyll<C-V>
let@x=4*@-+@"+6-@-<C-V>
norm y$<C-V>
for_ in split(@",'\zs')<C-V>
let@x=(@x+3*(_+6-@-))%6<C-V>
endfo<C-V>
let@x=@x+1<C-V>
norm`n@xjy$2Gom<C-V><C-R>s <C-V><C-V><C-V><C-R>"<C-V>
en<C-V>
@f^WWD"xp:let@"=@x<C-V>
<ESC>^"gC@f@t@f<C-V><C-A>@t^WWy$:if len(@0)!=len(@x)<C-V>
norm$x^Wx"=@-%2<C-V><C-V><C-V>
P$"=(@-+1)%3<C-V><C-V><C-V>
p<C-V>
en<C-V>
<ESC>^"vC:let@"=len(@n)-len(@m)|if@">0<C-V>
let@[[email protected]](/cdn-cgi/l/email-protection)(@m[len(@m)-1],@")<C-V>
elsei@"<0<C-V>
let@[[email protected]](/cdn-cgi/l/email-protection)(@n[len(@n)-1],-@")<C-V>
en|let@m=join(map(split(@n,'\zs'),{a,b->((float2nr(pow(b+(@m[a]*512)+8,2))%82)%3)}),'')<C-V>
<ESC>^"oC&&<C-V><C-V><C-V><C-R>=<C-V><C-V><C-V>
!=<ESC>^"zCgg"zx/ra<C-V>
^WWD"=_<C-V>
p@t@wggjom<C-V><C-R>- 0 <C-V><C-R>=char2nr(@z,1)<C-V>
<C-V><ESC>@t<ESC>^"dC/rc<C-V>
@g^Wyl:if@"<1<C-V>
let@"=@-<C-V>
en|if@">32&&@"<127<C-V>
let@"=nr2char(@")<C-V>
if@"=="/"<C-V>
let@"='\/'<C-V>
en<C-V>
norm`x/\V<C-V><C-V><C-V><C-R>"<C-V><C-V><C-V>
j"zyl/rc<C-V><C-V><C-V>
@g^WWC<C-V><C-V><C-V><C-R>=char2nr(@z)<C-V><C-V><C-V>
<C-V><C-V><C-V><ESC>@t<C-V>
en<C-V>
<ESC>^"eC^WxPWy$:s/<C-V><C-R>-*$/<C-V><C-R>-<C-V>
^WWD"0p<ESC>^"wC/rd<C-V>
WylW"yy$:s/<C-V><C-R>0*$<C-V>
$"0p^WW"zy$+Wy$:if@"/2<(len(@z)-1)<C-V>
let@0=len(@z)+5<C-V>
norm ^WD"0p/rd<C-V><C-V><C-V>
WWD"yp<C-V>
en<C-V>
<ESC>^"uC/rc<C-V>
@f^WWD"xp:let@z=@-<C-V>
@g:let@z=(@-+@z)%94<C-V>
<ESC>^"hDddggo!
m! -1 -1
@
ra 0 0
rc 0 0
rd 0 0
rw 10
<ESC>mx:for_ in range(32,126)
norm A<C-V><C-R>=nr2char(_)<C-V>
endfo
o 5z]&gqtyfr$(we4{WP)H-Zn,[%\3dL+Q;>U!pJS72FhOA1CB6v^=I_0/8|jsb9m<.TVac`uY*MK'X~xDl}REokN:#?G"i@
#<ESC>miGo
<C-O>mo$
<C-O>mn%<ESC>gg"xy$:for_ in range(len(@x))
norm @d
endfo
/ra
^WWDA0<ESC>/m<C-R>"
^W"zD"zpj^Wy$`no<ESC>"0p^2x$pxo<ESC>"zp^2x$px:norm<C-R>=repeat("-\"my$+\"ny$@oo<C-V><ESC>\"mp",18-((len(@x)%6)))
G5-d`nO%<ESC>mnj:g/^\d/norm$x^Pa
:wh1
norm@h
if@z==4
norm@i
elsei@z==5
norm@a
elsei@z==23
norm@b
elsei@z==39
norm@c
elsei@z==40
norm@j
elsei@z==62
norm@p
elsei@z==81
brea
en
norm @e/rc<C-V>
@vj@v
endw
```
...I'm so tired. This took a solid two months of work. The specification for Malbolge Unshackled is so vague in some places that I had to learn C, just so I could read the reference implementation and copy that. I LEARNED C FOR A VIM PROGRAM.
In all seriousness, this is something that I've wanted to do for a few years now, and having left the site for about a year and a half, I figured I should come back with something big, you know? I call it: Vim Unshackled.
[Gist containing full code explanation](https://gist.github.com/AMiller42/96daeb2ccf32f88cc0df212a5dba59b8)
[Copy+paste it online!](https://tio.run/##ZVVLc@JGEK7cUnNJlQ@6cBGzwkhIsh7YrE0sZxyROO91NsmSxBgjQMgQ9IjARtJ689edngcQb6oAjbp7ur/u/rp5fH5OrXwqIRIN@6Vi5RMJ9XvYzmpDPPetPADNDDRLEBbZKJU@7c5nxD4i5s0yTFRiaqZz63muI6EkzWM5lVC4FOdL6cBLcndyH@RgaDiahECbSAh8B/5orhfMfz@3wblHzdxkZ0kBjAHABgxwWSomBYgLAFIqFEJ5weJj7T/B8jALg7VKCoOUplDvgg77/ULJeJLBPsmJ/yL9qdCQB9AteAEge3qxj5NS0XVmKQRxqZAUDj0cZ8Ww/1Y6wFLtowCZTw26m3uCL1wOFnuSBKaNNjxQJqFluCbYI9hqU6jTDc9@zS9SZeER84lbLdJ5osZBpq6y5RxyxUZzUK2amvE@MMbmxbg1W6bBmhYySzdq2wg07YNmNPUmFALiAkDmfObHEdlEkRVLB6Y8eIrrgJiWlkZZ0XBQY@x5pmjsCLIuriHxJYdbeMctYuoE6x2TmKIHpSKhWZrfyfNE/gje9hY0R2@31Dt2TdMaHZbxLN3qQb2NmJBiUSruVQoQVzKrGO8kJSSjY1cUrmCUinwyI2sykz4h62Gf00RmLLC1uscOhWCLAs0q4KLZcGkLrhUMwEzd0XYtETR99EUMdj3ROKtijVXnwuaoY4/ER1vuxTfCBObCYPQMl6twTvC5sE48kuysk5utY7A2uXnyxJ1@3OnkZadV9UWnxzqNHdy2ThxX008NF4p76kJCrP20AZBO6h8e0kJS/qG6B5LKjyJc8UFkVfXuIH8oI3BjkTJy2DJc2E1nxee4RtZwe@qzhcFHgk4lPnd2dDZZLqxQbffwkOrc11vtbi/QlDnVsIW32ubAavIeMCYU1uAd7z/AXuCqXNKwEg/c91lGe4Aa1cAXIO76GPqcvkp3ZUFOLYX@iozZlG74GqCLjm4bZma3gM8K6OmoVzD7YvVgyz1XWd8q6Jugtu0JiX4ipmHIfFO3Ep2tHi73vHoQhXvB5IrVjETihTIS/DXOjtmV@950GkVpHcV12XTggwjKA@iOjfIJf0z5YyM7NqrFRXc7i3mQRKHadg3H7Wj/3813kAKfQpTKJ9XtYfT3upzliroJj9/3r7VvzD8T46YxaE9/0H/@/OK3evbdL6/dr@/fXDr@l53HofftnW2dPi1W47P4/OjXd8Fk9PBH68fvm7//U/SWH95@lf71U/fVF1d4TtCrWjy/StFncarAT9KoAf0KKOtLqGJYBVYyFeiApaxll3bNig8wnHHVw1W2oLt7lKQ12isXtnwBx0ocu9TH7r8BmwO6tfUBXeYkTaUavGfYcE5NdRu20dEgNLo6Maej5E2jFieLbmQNB1NL7I7rQEaw0B0Gj9xT/laed8xf52LgQXLCJcFe4ra5aLwXtc@4aLIXHdtctNiLOi4XZXvRqYPGeQjOE1GmkHPqcUEe2d8Ien7@Fw "V (vim) – Try It Online")
(Running "Hello, world!" takes something like half an hour, which is slightly longer than TIO's 60 second limit, so you'll have to run it on your own machine if you wanna do that)
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog) (2) → [Post correspondence problem](https://en.wikipedia.org/wiki/Post_correspondence_problem), 9 bytes
```
~h=∋ᵐ\cᵐ=
```
[Try it online!](https://tio.run/nexus/brachylog2#@1@XYfuoo/vh1gkxyUDC9v//6GilRCUdpaTERKVYHSA7CciBspOSwDJJSrGx/6MA "Brachylog – TIO Nexus")
Input is a list of lists of strings. (In the Post correspondence problem as defined on Wikipedia, the inner lists have two elements each, although this program can actually handle a generalisation to any number of elements.) This program brute-forces solutions to the problem, in order of length, until a solution is found. The Post correspondence problem is known to be able to simulate a Turing-machine, and thus brute-forcing solutions to it is Turing complete. If run as a function, rather than a program, it actually produces meaningful output as well.
The program in the TIO link above is `[["a","baa"],["ab","aa"],["bba","bb"]]`, which I copied from Wikipedia. The solution (which the program finds fairly quickly) is `["bbaabbbaa","bbaabbbaa"]`.
## Explanation
This is pretty much just a direct translation of the Post correspondence problem to Brachylog.
```
~h=∋ᵐ\cᵐ=
~h Find {the shortest possible} list which starts with {the input}
= and for which all elements are equal
∋ᵐ such that taking an element of each element,
\cᵐ and concatenating elements in corresponding positions,
= produces a list all of whose elements are equal.
```
Basically, we create a list that's repeated copies of the input (as few as possible, meaning that we don't miss any possibilities when brute-forcing), take one element from each copy, then concatenate corresponding elements (as in the Post correspondence problem).
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly) → "Add minimum to transpose", ~~5~~ 4 bytes
```
+"Ṃẞ
```
[Try it online!](https://tio.run/##y0rNyan8/19b6eHOpv///0dHG@oY6RjH6kQbmuoYGuiYglgGBjpGQGxsYBAbCwA "Jelly – Try It Online") (runs only one iteration, to avoid timeouts)
A very simple Turing-complete construction: we take a square matrix as a program, and loop forever, identifying the lexicographically smallest row, then increasing each element of the first row by the first element of the lexicographically smallest, each element of the second row by the second element of the lexicographically smallest, and so on. (The Jelly program is "`+"` add corresponding elements {of the input and} `Ṃ` the minimum {of original}, `ẞ` loop"; this is a byte shorter than my previous program `Z+ṂZß`, which did exactly the same thing. Clearly I should have focused on golfing the Jelly, not just golfing the implemented language.)
The resulting language is Turing-complete for much the same reason as [Kangaroo](https://esolangs.org/wiki/Kangaroo). The first element of each row acts like a skip count (although instead of the skip count of each command reducing when it's skipped, we instead increase the skip count of each command when it's run, and look for the command with the lowest skip count rather than commands with zero skip counts; this comes to the same thing). We ensure that this first element is higher than the other elements (which represent the number of times each command appears in each command's multiset), thus ensuring that the first row is never the minimum; the remainder of the first row can be garbage. The only remaining trouble is modelling the way that commands with equal skip count run cyclically in sequence, but we can do that by multiplying all the skip counts by a large constant, then adding on small "initial" skip counts to the first column to serve as a tiebreak. This gives us a tiebreak of "first nonskipped command runs", not "nonskipped commands run cyclically in sequence", but the Turing-completeness construction for Kangaroo does not care about this difference.
[Answer]
# [Perl](https://www.perl.org/) `-a` → [I/D machine](https://esolangs.org/wiki/I/D_machine), 24 bytes
```
$p=$a[$p]+=$_ for@F;redo
```
[Try it online!](https://tio.run/##K0gtyjH9r6Jjq6SjoGRdnFjpkGitUqGtbWdooKaWWpFZYv1fpcBWJTFapSBW21YlXiEtv8jBzbooNSX//39jBSMFYwVTBQMwNAOx/uUXlGTm5xX/1030NdUzMDQAAA "Perl 5 – Try It Online") (contains a header that prints the internal state and halts after 10 iterations, so that the behaviour is observable)
## About the language
I've spent the past couple of days working on the [I/D machine](https://esolangs.org/wiki/I/D_machine), one of my latest ideas for very simple programming languages. It works as follows: the data storage consists of an unbounded RAM, initially all zeros. Each element can store an unbounded integer (although in practice, most I/D machine programs will only store small integers in most of them, and make use of the unbounded integers only as a way of addressing cells with large addresses). There's also a data pointer, which points to a cell (i.e. holds the address as a cell); it's initially also zero.
There are only two commands:
* **`I`**: Increment the cell the data pointer points to. (The data pointer itself remains unchanged.)
* **`D`**: Dereference the data pointer, i.e. read the value of the cell that the data pointer points to. Then store the resulting value that you read back into the data pointer.
Execution simply runs the program in a loop repeatedly, forever.
It's fairly surprising that a language this simple is Turing-complete, so I've been working on proving that. [Here's the proof](https://esolangs.org/wiki/I/D_machine_Turing-completeness_proof). It's pretty similar to (but simpler than) the proof for Three Star Programmer, a very similar language (and in fact, this submission uses the same basic OISC "shell" around the program, differing only in the actual instruction implemented).
## About the program
### Usage
The input should be given on standard input, and is an I/D machine program without comments, and using the RLE/OISC syntax. (The I/D machine has two different, equivalent syntaxes, but for golfiness this program only supports one of them.) In this syntax, a program is a sequence of numbers in decimal, representing the lengths of runs of `I` commands between `D` commands. (You can specify two or more consecutive `D` commands via placing a "run of 0 `I` commands" between them, so the syntax is fully general.)
### Explanation
As can be seen from the program, this isn't implementing the `I` and `D` commands individually. In fact, it's a (very slightly) optimising interpreter (purely because it's shorter to write this way). The key is to see that a run of *n* increment commands increment the data pointer's target *n* times, i.e. add *n* to it; and a run of 0 increment commands can also be implemented this way, as adding 0 to memory has no effect. So the operation we actually implement is to alternate between implementing a run-of-`I`s and a `D`. Or in other words, "add *n* to the value pointed to by the data pointer (storing it back in the value pointed to by the data pointer), then read the value pointed to by the data pointer and store it in the data pointer". That's clearly more verbose than it needs to be, and we can further simplify this to "add *n* to the value pointed to by the data pointer, then store that value both in the data pointer's target and the data pointer itself".
So that makes for the core of our program. We're using an array `$a` to store the RAM, and `$p` as the data pointer (indexing into the array):
```
$p=$a[$p]+=$_
+ $_ add {the run length}
$a[$p] to the element of $a pointed to by $p
$a[$p] = storing the result back into that element
$p= and also in the pointer itself
```
Conveniently, Perl interprets uninitialised array elements as 0 when they're treated like numbers, so the array will be lazily initialised to zeroes for us without any explicit code for that being needed. (One potential issue is numerical accuracy when the numbers get large; however, that'll only happen if the amount of the array being used exceeds the machine's address space (Perl integers are large enough to hold pointers), something that can't happen on an idealised machine.)
Finally, all we need to do is to place this program into a couple of loops. The `for@F` loop, combined with the `-a` command line option, will loop over the fields of standard input (the default definition of "field" here will split on whitespace). The `redo` loop will place the entire program in an implicit loop (other than, conveniently, the reading of standard input), which will cause the program to run in a loop repeatedly, as required by the semantics of the I/D machine.
[Answer]
# [M](https://github.com/DennisMitchell/m) → [Tip](https://esolangs.org/wiki/Tip), 4 bytes
```
Ṅ×ịß
```
[Try it online!](https://tio.run/##y/3//@HOlsPTH@7uPjz/v6GlmZmBhbWhmfWRjdbGINrw8HaTQ0sUgGoUDi93UDD8DwA "M – Try It Online")
The TIO link adds a footer to call the function with the example Tip program shown on the Esolang page (M's "automatic wrapper" to call functions as though they were programs can't handle rational or fixed-point numbers, or at least I haven't figured out how to tell it how, so I need to make the function into a full program by hand to be able to run it.)
This actually prints useful debug output; the program can't be written in 3 bytes in M because a program consisting of exactly three dyads triggers a special case in the parser, so I had to add an extra command to avoid the special case. Making it `Ṅ` (print with newline) at least gives it a useful purpose.
Function submission, taking two arguments: the initial IP on the left, the program on the right. The program is 1-indexed (i.e. command 1 is the first command; M uses 1-indexing by default); goto commands are represented as M rationals, and the halt command as `ı` (i.e. the imaginary unit, \$i=\sqrt{-1}\$).
Does not implement I/O (other than halt/no-halt). I/O is an extension to Tip (not part of the language itself), and not required for Turing-completeness.
## Explanation/background
```
Ṅ×ịß
Ṅ Print {the left argument} and a newline; also resolves a parser ambiguity
ị {The left argument}th element of {the right argument}, wrapping on OoB
× Multiply {the left argument} by {the chosen element}
ß Recursive call; arguments: {the product} and {the same right argument}
```
I was reading through the answers to this entry and realised that iterated [Collatz functions](https://esolangs.org/wiki/Collatz_function), which were used in [quintopia's earlier answer](https://codegolf.stackexchange.com/a/119506), would be fairly short to represent in golfing languages in which list indexing wraps by default (i.e. the fifth element of `[1,2,3]` is 2, because the list is being treated as `[1,2,3,1,**2**,3,1,2,3,…]`). So it's easy to extract a particular Collatz operation from a list in very few characters. Can we implement the Collatz operation easily? Well, a Collatz operation is \$rx+s\$, which is a polynomial, and the "base conversion" builtin that many golfing languages have is actually a general-purpose polynomial evaluator in disguise. So all we have to do is index into a list of lists of digits, base-convert them, and we're done, right?
Unfortunately, it's not that simple. The first problem is that although Collatz functions can be defined entirely in terms of integers, that requires a divmod to extract the new value of \$x\$ (the definition where \$x\$ is the same value that's used to index into the list of Collatz operations requires rationals). Well, we just need a golfing language that supports rationals, right? [M](https://github.com/DennisMitchell/m) is a Jelly derivative that supports many types of arbitrary-precision arithmetic, and arithmetic on the rationals is part of its arsenal of mathematical operators.
Then we get to the second problem: M's base-conversion builtin `ḅ` takes its arguments in the wrong order (it wants the list of digits to appear before the base). The problem with this is that M's default method of chaining together two binary operators given two arguments is \$x\oplus(x\otimes y)\$, and yet we'd want the Collatz operation (which can only fit the \$x\otimes y\$ part of this structure, as it's obtained by an index) to be on the *left* of the \${\oplus}\$. Sure, we could override the chaining behaviour to pretty much anything we want, but that would cost a whole byte, and the golfing language entries to this question are getting so short that a byte is a lot.
So I looked back and re-evaluated a bit. Are there any operations we could use instead of polynomial evaluation? Ideally, ones that are commutative, so we don't have to worry about argument order? Soon after that, I realised that Collatz functions are more complex than they need to be.
As a result, I created [Tip](https://esolangs.org/wiki/Tip), a simplification/tarpit-ification of iterated Collatz functions in which \$s\$ is always 0, meaning that instead of a polynomial evaluation, we can perform the various operations via a simple multiplication. The language is more complex to prove Turing-complete than Collatz functions are, but it still has enough power to implement any program; there's a proof on the Esolang page.
And of course, unlike base conversion (`ḅ`), multiplication (`×`) is commutative, and thus it doesn't matter what order the arguments are placed in. So all we need to write is `×ị`, and then place the program into an infinite recursion with `ß`, and we have a Turing-complete language. Right?
Unfortunately, we run into a new problem. If a program starts with three binary operations, M engages in a special case that chains them as \$(x\odot y)\oplus(x\otimes y)\$ which is the worst possible structure for us, as it doesn't have the three nested function calls we'd need (index, multiply, and recursive call). So no matter what, we're going to need a fourth byte to disambiguate. `¹×ịß` (adding the identity function `¹` as a no-op so that the program doesn't *start with* three binary operators) does exactly what we'd need, causing them to nest inside each other in the way we want. We can use other operations in place of `¹`; `Ṅ` is a good choice because it produces useful debug output.
Is three bytes possible? Unless I'm missing something, not with this specific choice of implementing and implemented language, but at this point it surely seems like it'd be possible somehow, as there are so many ways to do it in four and so many Turing-complete languages you could implement.
[Answer]
# Mathematica interpreting Conway's Game of Life, 64 bytes
```
CellularAutomaton@{224,{2,{t={2,2,2},{2,1,2},t}},{1,1}}~Nest~##&
```
[Conway's Game of Life](https://en.wikipedia.org/wiki/Conway's_Game_of_Life) is known to be Turing complete; and cellular automata are Stephen Wolfram's truest obsession. `CellularAutomaton@{224,{2,{t={2,2,2},{2,1,2},t}},{1,1}}` is a rule that transforms a two-dimensional array of 0s and 1s according to one step of Conway's Game of Life. (I think the default behavior is that this array wraps around its edges, so is really a discrete torus.) `~Nest~##&` turns this rule into a function which, when given an initial board state (of any dimensions) and an integer `n` as arguments, outputs the result of `n` iterations of the Game of Life rule.
For your own enjoyment, you could use the wrapped version
```
b = RandomInteger[1,{50,50}];
Manipulate[ArrayPlot[
CellularAutomaton@{224,{2,{t={2,2,2},{2,1,2},t}},{1,1}}~Nest~##&
[b, n] ]
, {{n,0}, 0, 100, 1}]
```
and scroll your way through 100 generations on a 50x50 board.
[Answer]
# [Iterated Generalized Collatz Functions](https://esolangs.org/wiki/Collatz_function) -> Python 2, 46 bytes
```
a,b,x,m=input()
while-~x%m:x=x/m*a[x%m]+b[x%m]
```
Call this function with a lists of m-1 a's and b's, the starting value x, and the divisor m, which collectively constitute a "program" for IGCF. Rather than taking a third array to indicate on which moduli to halt, this simply halts whenever the modulus is m-1. This simplification means it may take some extra effort to convert a given Fractran program into this variant, but it does save a couple of bytes in the interpreter.
[Try it online!](https://tio.run/nexus/python2#@5@ok6RToZNrm5lXUFqioclVnpGZk6pbV6Gaa1VhW6Gfq5UYDWTHaieBKeuCosy8EoWK//@jjWN1og1idczNzc10jAA "Python 2 – TIO Nexus") This TIO demonstrates how to add 5+5 with this language. The program a=[3],b=[0],m=2 does addition, and starting with 7776=2^5\*3^5 eventually yields 59049=3^10.
[Answer]
# x86 assembly (Intel syntax/MASM)-Brainfuck 2127 bytes.
Still golf able
```
.386
.model flat,stdcall
.stack 4096
include \masm32\include\masm32.inc
includelib \masm32\lib\masm32.lib
ExitProcess proto,dwExitCode:dword
.data
bfsrc BYTE 200 dup(0)
bfcells BYTE 100 dup(0)
loopStack DD 5 dup(0)
charBuf BYTE 5 dup(0)
newline BYTE 10,0
prompt BYTE "$",0
hr BYTE 50 dup('-'),0
space BYTE ' ',0
.code
EvalBf proc
start:
invoke StdOut, addr prompt
invoke StdIn, addr bfsrc,200
cmp bfsrc,0
je exit
mov eax,0
mov ebx,0
mov ecx,0
processInstruction:
cmp BYTE PTR bfsrc[ebx], '+'
je plus
cmp BYTE PTR bfsrc[ebx], '-'
je minus
cmp BYTE PTR bfsrc[ebx], '>'
je fwd
cmp BYTE PTR bfsrc[ebx], '<'
je back
cmp BYTE PTR bfsrc[ebx], '['
je open
cmp BYTE PTR bfsrc[ebx], ']'
je close
cmp BYTE PTR bfsrc[ebx], '.'
je dot
jmp processNextInstruction
plus:
inc BYTE PTR bfcells[eax]
jmp processNextInstruction
minus:
dec BYTE PTR bfcells[eax]
jmp processNextInstruction
fwd:
inc eax
jmp processNextInstruction
back:
dec eax
jmp processNextInstruction
open:
mov loopStack[ecx*4],ebx
inc ecx
jmp processNextInstruction
close:
dec ecx
cmp BYTE PTR bfcells[eax], 0
je processNextInstruction
mov ebx,loopStack[ecx*4]
inc ecx
jmp processNextInstruction
dot:
mov dl, BYTE PTR bfcells[eax]
mov BYTE PTR charBuf[0], dl
mov BYTE PTR charBuf[1],0anything
push eax
push ecx
invoke StdOut, addr charBuf
pop ecx
pop eax
jmp processNextInstruction
processNextInstruction:
inc ebx
cmp BYTE PTR bfsrc[ebx], 0
je done
jmp processInstruction
done:
invoke StdOut, addr newline
mov eax, 0
printNext:
cmp eax, 100
jge reset
push eax
invoke dwtoa, BYTE PTR bfcells[eax], addr charBuf
invoke StdOut, addr charBuf
invoke StdOut, addr space
pop eax
inc eax
jmp printNext
reset:
invoke StdOut, addr newline
invoke StdOut, addr hr
invoke StdOut, addr newline
jmp start
exit:
invoke ExitProcess,0
EvalBf endp
end EvalBf
```
[Answer]
# [Turing machine](https://en.wikipedia.org/wiki/Turing_machine) (finitely initialized, halts) implementing an encoding of [Grill Tag](https://esolangs.org/wiki/Grill_Tag), 2 states, 14 symbols, 232 bytes
We've had a few answers implementing Turing machines in various languages. Time to go the other way, and implement a language in a Turing machine. (A lot of time… I started working on this problem in 2019, and only proved Grill Tag, the implemented language, to be Turing-complete just now.)
```
0 e e r 1
0 P p l 0
1 P p r 1
0 p P l 0
1 p q r 0
0 q P r 1
* > < r *
0 < > l 0
1 < < l 0
0 i a r 0
1 i < l 1
0 I A r 0
1 I < r 0
0 a x l 0
1 a i l 1
0 A X l 0
1 A I l 1
* X a r *
* x A r *
0 _ o l 0
1 _ _ l halt
0 o _ l 1
1 o A r 0
```
[Try this program in an online simulator](http://morphett.info/turing/turing.html?a2b2c66cbda6a5b2ddce0476ac390bf3)
Something that needs to be made clear, because the details can make a *huge* difference to the size of a universal Turing machine: the problem I'm solving here is the problem of creating a universal Turing machine where the program to implement is specified using a finitely initialized tape (i.e. all but finitely many cells are blank), and for which the Turing machine halts when the implemented program halts. It is possible for a Turing machine to be much smaller if, e.g., you allow for an infinite repeating pattern on the tape, and work out whether the program "should have halted" by inspecting the tape rather than by using a halt state, but that is effectively an entirely different problem (and both are interesting).
As far as I can tell, the previous record for a 2-state Turing machine was 18 symbols, so unless there's been some development I've missed since, this is a huge proportion golfed off a very long-standing mathematical problem.
You can encode a Grill Tag program and initial string into an initial tape for this Turing machine using [this Jelly program](https://tio.run/##LU@7CsJAEOzzFVOkkhRZtTsfYCEKFvYxdhaGFFpaCEFSmU5BVBQRLa2sjBaBmPgflx85706bYWZnmN31Rr4/E6IItvxxBfFnBM@xLbJsF0wTcgEwMoEsIrQUmuDPs8TPHUgTZdvgcWikMZCvOpLvhwMJnyXep2JxQ1tHe3UyZU3ToCyRmR0hX/P4ora48HQF0ltZmyH4KyqCQ39SBMefjjeQfMTA5HxaqjWkMn6p7ljxSpawapbMhRD/y4VD6hVLo/sF "Jelly – Try It Online") (the last line of output is the initial tape, the other lines are debug output). The program is specified in the RLE syntax, and its initial queue in JSON (with the head at the start of the array).
## Explanations
### The implemented language
#### Grill Tag
[Grill Tag](https://esolangs.org/wiki/Grill_Tag) is a variant of [cyclic tag](https://en.wikipedia.org/wiki/Tag_system#Cyclic_tag_systems) in which all productions have an odd length, start and end with 0, and alternate between 0 and 1. In other words, the only valid productions are `0`, `010`, `01010`, `0101010`, and longer strings that follow the same pattern.
In case you don't know what cyclic tag is, the language works like this: there is a queue of bits, which handles all the data storage for the program; and a program, which runs in an infinite loop forever until/unless the queue becomes empty. Each program command, known as a "production", dequeues a bit from the front of the queue, then enqueues either something (if a 1 bit was dequeued) or nothing (if a 0 bit was dequeued) to the back of the queue – the only freedom you have when writing the program is in specifying what exactly it is that gets enqueued. In the full version of cyclic tag, you can enqueue any arbitrary sequence of bits, but Grill Tag is restricted to using `010…010`-style sequences ("grills") only.
Grill Tag is something that I've been looking at as a potential target for interpreter golf for several years now. However, back in 2019 when I created it, I wasn't able to determine whether or not it was Turing-complete; the language has a fundamental issue that make it very hard to program in (the number of 0s minus the number of 1s in any given string is equal to the number of 1s in the string that produced it, which means that programming in it requires controlling both the length and the 0/1 ratio of everything you use in order to keep control of which productions the 1s will expand).
I have very recently [proven it Turing-complete](https://esolangs.org/wiki/Grill_Tag#Computational_class), via creating a Turing-complete language ([Genera Tag](https://esolangs.org/wiki/Genera_Tag)) in which you can write programs where every symbol expands in a very regimented way: every symbol always expands into two symbols in the next generation, each of those expands into another two symbols, and so on. Unfortunately, this construction tends to cause a useless explosion of no-ops (one no-op expands into two, then four, then eight, etc.) and makes programs run very slowly, but that is not an obstacle to Turing-completeness (and is *probably* not inherent in the language, but just trying to find anything that works was hard enough – I'm not immediately planning to go looking for something more efficient, even though it probably exists).
#### A decomposition of Grill Tag
As described above, Grill Tag has some fairly complex commands ("pop, and conditionally append `…` if a 1 bit was popped"). However, it is possible to break it down into smaller pieces, in a way that's quite suitable for a simple language like a Turing machine to handle.
The first observation (which is a standard transformation which I learned from [Bitwise Cyclic Tag](https://esolangs.org/wiki/Bitwise_Cyclic_Tag)) is that instead of appending to the end of the queue all in one go, it is instead possible to split it up and push bit by bit: "dequeue a bit, and if it was a 0 bit, ignore any commands that would enqueue to the queue until the next bit is dequeued", "enqueue a 0 bit", "enqueue a 1 bit". The existence of the first command here effectively leads to two global states, which I think of as "blocked" and "extending"; in a blocked state, enqueuing commands do nothing, and in an extending state, they enqueue onto the back of the queue. This is still 3 commands, though, which is not ideal for implementing in a 2-state Turing machine (it's *possible*, but you need to add a lot of extra symbols to remember the half-command that you've seen already).
The second observation is that, in order to reach the far end of the queue, a Turing machine has to move its head over the entire queue as it does so (and generally speaking it's terser to have the "growing" end of the queue – the tail – at the opposite end from where the program is stored, so that it doesn't end up crashing into the program or forcing you to move the program out of the way). That gives it an opportunity to make simple changes as it goes, like, say, inverting the queue by flipping every bit in it. So instead of "dequeue and possibly block", "enqueue 0", "enqueue 1", it's possible instead to use "dequeue and possibly block", "enqueue 1", "invert the queue" (with an enqueuing of 0 implemented as an invert, enqueueing of 1, and another invert).
Look at what happens when using this decomposition on grills, rather than arbitrary strings:
* `0`: dequeue/block; invert; enqueue 1; invert
* `010`: dequeue/block; invert; enqueue 1; invert; enqueue 1; invert; enqueue 1; invert
* `01010`: dequeue/block; invert; enqueue 1; invert; enqueue 1; invert; enqueue 1; invert; enqueue 1; invert; enqueue 1; invert
* etc.
Every second command is an `invert` command, so they can be paired with the preceding (or subsequent) commands in order to create a language that has only two commands, rather than three. I chose to pair them with the subsequent commands, meaning that Grill Tag can be implemented using only two commands:
* invert, then dequeue/block
* invert, then enqueue 1
(These commands actually give you a little more power than Grill Tag has – I made a catalogue of "languages that might be good to implement in low-powered languages and might be Turing-complete" back in 2019, and codenamed the full version of this language [`a vd vt`](https://esolangs.org/wiki/BIX_Queue_Subset#a_vd_vt). The extra power of `a vd vt` is not needed, though, with Grill Tag being Turing-complete on its own.)
Now that there are only two commands, it is possible for the Turing machine to remember which command it is executing via using its two states – it no longer needs to store a "half-command" onto the tape to remember what it's doing.
In the next section, I discuss how `a vd vt` (thus Grill Tag) is implemented in the Turing machine.
### How the Turing machine works
This is a program of two halves, each of which does something sensible in isolation: the "left half" that uses the four symbols `epPq`, and the "right half" that uses the other ten symbols (including the "blank tape" symbol). The left half stores the program; the right half stores the queue, and implements the logic of Grill Tag.
#### Right half
Let's look at the right half of the program first. This is an implementation of all of Grill Tag other than the routines for determining what the next Grill Tag command is (which are implemented by the left half of the program).
The part of the tape used by this half of the program consists of a section of `<` and `>` symbols, followed by the tape, and possibly an `o` at the end (and beyond that is blank tape forever). The queue is encoded very directly: the head of the queue is towards the left-hand side of the tape (with the tail being at the right-hand side), and uses states represented by capital letters to encode 1 bits and states represented by lowercase letters to encode 0 bits. This part of the program is, in effect, a state machine; it remembers which state it is in by using different pairs of symbols to represent the queue (either `iI`, `xX`, or `aA`).
The only requirement that the right half of the program makes on the left half is that it can ask for commands. To ask for a command, it moves the tape head to the left out of its own section of the program, in state 0. The left half of the program responds with a command, returning the tape head in state 1 for an "invert and enqueue" command, or state 0 for an "invert and dequeue" command. There are a couple of quirks:
* After a returning a 0 command, the next "ask for a command" must, instead of returning the next command in the program, unconditionally return in state 1.
* Every second 0 command is implemented as unconditionally blocking the queue, rather than inverting and dequeuing a bit. This can be worked around by adding a sequence of dummy commands after each original 0 command: arbitrarily many 1 commands in the program, followed by one 0 command (to unblock the queue and dequeue the bit that should have been dequeued by the original 0 command).
These quirks are present because they allow the Turing machine to be smaller, and the workarounds don't hurt its universality. (In fact, each of the quirks has positive (or at least simplifying) impacts on both halves of the Turing machine, which is something of an amazing coincidence.) The reasoning behind them, and the way that they benefit the construction, will be explained in the appropriate sections below.
Apart from storing the queue, the right half of the Turing machine is effectively just one state machine, with a few hardcoded states.
Below, I take a look at every state. If you'd prefer to read the description in Jelly rather than English (maybe to have something to compare the Turing machine to), I have [a Jelly implementation of the state machine](https://tio.run/##rZPPahsxEMbv@xRz8MGBbfCaEEJy6KmUlt6SWylEXk3WirXSVtImMSXgQ299gkILoec@QE0PBUMexHkRd0a7rtf500vLsqy0mvn0@0ajc9R6ulrdzb4kJ2PloXK2cKIEGgp4X2ONIOpgSxGsgTAWAbwqay0CenjplNZwIgroCyOhtA6hQINOkCacCriQcBFOd1JQhbFOmQLwAt0UPOaWElxtwJ5BbsuS8j30tZogbYLQH6aQ7e3ASR2zSpGPlUGQFv3ObvKCpuADMXA6x98HJXqHlUOPJqAEwWZes1OQUyFVDlqZyW7yKnjQeBZAuKIuKZYTWW9dhaibArtTFOtUMe4Ec6QUoa3TbpIcR6bh7eywJSI5JTUegbNx6RHtylbx95lyPgBqjNKtr416AzFywpD3YFv7e7czsA4O6CPy3DpJ1dLTlP/hlSI792WYCMsqTO9mX5Pl/HPWg5jNQsv5x@WPb71reA6QLm7e0CDhvjheb9VxJW090vhspG0@QXn4pD@oTVCaqj@IZxKjJPNzJBqZ8sA88LV/O@sANp/B8uenHix@Aa92wPa3wP4z0Ujkkw3W8K9Ywy2sA8YqhZt0G5SKfxVoEzomFsoGWyk87Vj5E3oIytC9CQ9a4umuih4Ku0HPhk2rZHzSEqtGGeiuXPKlvhSP1aJjNubH5Gj4AzXJ4vt1Fz62/SXCeU193ACz2CNd3OX1Yup5R1ExEo9UiDIGG5R2QUDWLK4Vor3t4@H6MfJivrjhMRxlvS3EvX9C9IGuaoNDpTvaKm/bsNyZCRVitVq9zdIsHbRv8zyctaN3m2ie/QY "Jelly – Try It Online") available (which implements the program queue itself rather than asking the left half of the tape).
##### Idle
```
[head] >>>…>>>iIIii…Iii
```
The **idle** state happens a) at the start of the program, b) immediately after a 0 command. In this state, the right half of the Turing machine consists of an arbitrary number `>` symbols, followed by the queue written with `iI` (which could be any combination of lowercase `i` and capital `I`, reflecting the 0 and 1 bits that make up the queue).
In this implementation, a 0 command does not actually dequeue the first bit of the queue immediately. Instead, it sets the state to **idle**, and then allows the implementation of the idle state to handle dequeuing the bit of the queue.
The **idle** state is intended to run immediately after a 0 command, at a time when the left half of the tape is unconditionally returning control in state 1 (rather than reading a command from the program); the Jelly implementation unconditionally rotates the program to emulate this. That means that the idle state will be entered in state 1 (and this is the reason why the "always 1 after 0" quirk is helpful to the right-hand half – it ensures that the **idle** state is entered with the Turing machine in the correct state, necessary because the **idle** state wouldn't work properly in Turing machine state 0).
The Turing machine proceeds to move along the row of `>`, changing them to `<` and remaining in state 1 (per the rules for `>`). When it reaches the end of the row of `>`, one of three things happens:
* The next symbol could be `i`. In this case, the `i` becomes `<` and the head moves left, remaining in state 1. It will move to a `<`, which remains as `<`, moves the tape head to the left and changes to state 0. In state 0, the machine will change all the remaining `<` back to `>` and pass control to the left half in state 0.
The machine has dequeued a 0 from the queue (a lowercase letter became a filler symbol `<`), and entered a **double-blocked** state (`>>>…>>><<`). This dequeues a symbol (as required), and blocks the queue (also as required when a 0 bit is dequeued).
* The next symbol could be `I`. In this case, the `I` becomes `<`, the head moves to the right, and the Turing machine enters state 0. In state 0, `I` becomes `A` and `i` becomes `a`, with the head moving to the right over the entire queue; the queue is becoming active. When it reaches the end of the queue, the Turing machine is in **mark as extending** state. This dequeues a symbol (as required), and does not block the queue (as required when a 1 bit is dequeued). The **mark as extending** state will handle marking the queue as extending.
* The queue could be empty – there might be no next symbol. In this case, beyond the last `>` will be an empty portion of the tape. The rule for empty tape is to **halt** in state 1, and we will be in state 1, so this correctly emulates a halt; Grill Tag halts when the queue is empty, and so does the Turing machine.
##### Blocked and double-blocked
```
Blocked:
[head] >>>…>>>><iIIii…Iii
Double-blocked:
[head] >>>…>>><<iIIii…Iii
```
The **blocked** and **double-blocked** states are very similar to each other. They handle situations where enqueue commands should be ignored, either because a 0 was dequeued, or due to the quirk where every second 0 command unconditionally blocks the queue.
A **double-blocked** state effectively says "the last 0 command blocked the queue, and the next 0 command should block the queue as well" – this is used to remember the fact that after a "regular" block of the queue when a 0 command dequeues a 0 bit in **idle** state, a "quirky" block is required on the next 0. A **blocked** state is one in which the last 0 command blocked the queue, but the next 0 command should be processed normally. As such, a 0 command changes the state from **double-blocked** to **blocked** or **blocked** to **idle**. 1 commands are entirely ignored in this state, because its entire purpose is to discard inverts and enqueues.
The **blocked** and **double-blocked** states read commands from the program – they are entered from the left half of the program. When either state is initially entered, it will be after a 0 command was read, so there will be a spurious 1 command arriving – but that quirk is irrelevant here, because the states discard 1 commands anyway. So all they actually have to do is to wait for a 0 command, and then remove one blockage upon receiving it.
There are two possibilities for what could happen, because the left half of the program could give this half control in either state 0 or state 1. In either state, the machine moves along the row of `>`, changing them to `<`, while remaining in the same state. When it reaches the `<`, there are two possibilities.
* In state 1, with a 1 command (or spurious-1-after-0) having been read from the program, the `<` remains unchanged and moves the head back to the left in state 0 (as per the rules for `<`). The rest of the row of `>` will be flipped back to `<`, and control will move to the left half of the program in state 0 (asking for a new program command). In other words, nothing changes other than a new command is being requested; in particular, the row of `>` and `<` ends up exactly as it started, so the machine will remain in **blocked** or **double-blocked** state (whichever it was in previously).
* In state 0, with a 0 command having been read from the program, everything is *almost* the same as in state 1; however, the rule for `<` in state 0 is to change to `>` and remain in state 0 (rather than remaining as `<` and changing to state 0). Thus, everything ends up the same, except that the machine has changed from **double-blocked** to **blocked** or **blocked** to **idle** state (because the only difference between the representation of those states is the number of `<` at the rightmost end of the `>`).
##### Mark as extending
```
<<<…<<<aAAaa…Aaa [head]
```
The **mark as extending** state is used to produce the correct representation of the queue for **extending** state. It is entered with the Turing machine in state 0, with the tape head in the blank space to the right of the tape.
This one works very simply: the rule for blank space (`_` in the notation used by the interpreter I chose) in state 0 is to write an `o`, then move the head to the left in state 0. `<aA`'s rules for state 0 all move the head to the left, with `<` becoming `>`, `a` becoming `x`, and `A` becoming `X`. The content of the queue has remained unchanged, the head has moved to the left in state 0 (reading the next command) and now the machine is in **extending** state.
##### Extending
```
[head] >>>…>>>xXXxx…Xxxo
```
The **extending** state is used to handle the "invert" half of commands, in cases where the queue is not blocked.
The **extending** state can be entered with the Turing machine in either state 0 or state 1 – a command has just been read from the program. The rules for `>`, `x`, and `X` are basically the same between the two states: they leave the Turing machine in the same state, but otherwise the state doesn't matter (it's just remembered so that the `o` at the end of the tape knows which command to implement the second half of).
`>`, `x` and `X` all move the head to the right, in both state 0 and state 1. `>` becomes `<`; `x` becomes `A`; and `X` becomes `a`. This mapping of lowercase to capital and capital to lowercase letters is inverting the sense of the queue; 0 bits become 1 bits and vice versa. The machine is now in **enqueue** or **stop extending** state.
##### Enqueue
```
<<<…<<<aAAaa…Aaao[head] in state 1
```
The **enqueue** state is entered from **extending** when a 1 command was read (and thus the Turing machine is in state 1), with the head over the `o` at the end of the tape. This is the simplest state in the entire machine, implemented by a single Turing machine transition: the `o` becomes an `A` (writing a capital letter at the end of the queue and thus enqueueing a 1 onto it), and the head moves to the right, onto the blank space beyond the queue. The Turing machine is now in **mark as extending** state, which will set the tape back to the format it was in before the "invert and enqueue" command ran – but the tape has now been inverted (because **extending** inverts the queue but **mark as extending** does not invert it back), and then an `A` (which becomes an `X` during **mark as extending**) was appended to the end.
##### Stop extending
```
<<<…<<<aAAaa…Aaao[head] in state 0
```
The **stop extending** state has an identical tape to **enqueue**, and the head is likewise over the `o`, but the Turing machine is in a different state. The purpose of this state is to bridge between the "invert" and "dequeue" halves of an "invert and dequeue" command – the "invert" half leaves the head at the rightmost end of the tape, but the "dequeue" command needs the head at the left, so the **stop extending** state is used to move the head into the correct location and appropriately re-encode the queue as it goes.
First, the `o` at the end of the queue deletes itself (which is what the rules for `o` do in state 0), switching to state 1 and moving the head back onto the last `a`/`A`.
Then, the head moves back leftwards over the queue, remaining in state 1 (`a` and `A` leave the state the same), with `a` becoming `i` and `A` becoming `I` – the queue encoding is going back to the encoding used for **idle**.
When the head moves back to the `<`, the logical thing to do (and the obvious thing to try to implement) would be to change the `<` back to `>`, and enter **idle** state (which implements the "dequeue" half of an "invert and dequeue" command). Unfortunately, golfing the Turing machine down to only 14 symbols ended up making the logical and obvious behaviour impossible to fit in, so the machine does something else instead; `<` in state 1 remains `<` and moves to the left, changing to state 0. The remaining `<` do change back to `>`, though (now that the machine is in state 0), so the resulting queue state consists of arbitrarily many `>`, an `<`, and the queue encoded with `iI` – in other words, this is **blocked** state!
This explains the quirk in which every second 0 command unconditionally blocks the queue, rather than doing an invert-and-dequeue like it's supposed to. If a 0 command runs when the queue is unblocked, then **stop extending** will end up inverting and then blocking the queue – it's the *next* 0 command that will actually do the dequeue (so the invert happens when it's supposed to, but the dequeue is delayed until the next 0 command). I couldn't find a terse way to avoid this behaviour. However, it was trivial to change the behaviour of a 0 command that blocks the queue to match (by making it double-block the queue rather than merely blocking it), in order to produce a construction in which every second block of 111…1110 in the program is consistently ignored (a quirk that is trivial to work around if you know it exists, simply by adding dummy commands).
That concludes the entire functionality of the right hand half of the program: enqueuing, dequeuing, inverting and halting. Apart from the weirdness of **stop extending** becoming **blocked** rather than **idle** (requiring a **double-blocked** state to compensate), everything is fairly straightforward and intuitive, and you can generally immediately understand what it's doing in the simulator.
Unfortunately, the left half will be a whole lot weirder and harder to understand – unlike the right half, it wasn't constructed, but rather discovered. Let's take a look at how it works.
#### Left half
##### Low-level behaviour
The left half of the program uses only 4 of the 14 symbols (`e`, `p`, `P`, `q`), and in fact only 6 of the 8 transitions are used (the other two do not have a rule defined because they never occur). Its purpose is to store the program, which it does by producing a specific, endlessly repeating stream of "state 0" and "state 1" signals; whenever the tape head enters it from the right (in state 0 – the right half always sets the state to 0 when giving the left half control), it will return the tape head to the right in either state 0 or state 1, whichever is the next element in the sequence.
First, let's take a look at what the rules actually do. The structure of the left half of the tape, when the tape head is outside it, is always of one of the following two forms (where `p` and `P` can be arbitrarily mixed):
```
eppPp…PPpp
eppPp…PPpq
```
Let's consider the first of these forms, and what happens when the tape head enters it in state 0. While moving to the left, the behaviour is fairly simple; `p` becomes `P`, and vice versa, with the machine remaining in state 0. When it reaches the `e`, it changes to state 1 and moves back to the right.
When moving rightwards, things are more complex. A `P` becomes a `p`, moves to the right, and remains in state 1; in other words, it undoes the inversion that was done when moving to the left, restoring the symbol to its original state. However, a `p` has a much weirder rule: it becomes a `q` and moves to the right, while switching to state 0. This has the effect of inverting the symbol to the right (because both `p` and `P`, when encountered in state 0, invert), and moving back to the left, onto the `q`. The `q` then becomes `P` and moves to the right in state 1, as "normal".
In other words, when moving to the right, `P` becomes `p`, and `p` inverts the symbol to the right and then becomes `P`. The result of this is that each cell, when the head leaves it, becomes set equal to the cumulative/running XOR of the original states (i.e. before they were inverted while moving to the left) of all the cells so far. This can be seen inductively. The base case is that the first cell starts out as the inversion of its original value, i.e. the XOR of all the cells so far, i.e. itself. For the inductive case, immediately before a cell changes to `P` (i.e. asserting that the XOR of all the cells so far was odd), it inverts the cell to its right, so it ends up being inverted three times and flipping (i.e. it was set to its original value XOR 1 = its previous value XOR that of all the cells to its left), whereas if a cell changes to `p`, the cell to its right is inverted only twice (leaving it at its original value, which must be the XOR of all the cells seen so far because the cells to its left XOR to 0).
People familiar with small Turing machines may be familiar with this general algorithm, of using a running XOR to store data. I learned about this pattern from [Wolfram's (2,3) Turing machine](https://en.wikipedia.org/wiki/Wolfram%27s_2-state_3-symbol_Turing_machine), which is capable of doing a running-XOR and which uses this mechanism as its primary data storage. In fact, the rules used in this Turing machine were based on those from the (2,3) Turing machine, with all the relevant states and transitions being the same and used for the same purpose (the only difference is the addition of an `e` symbol to reflect the tape head, which is required because both transitions of the blank symbol are both being used for other purposes).
One quirk of this method of doing things is the way in which output is produced. When the last symbol becomes a `p` (i.e. all the symbols XOR to 0), the output uses a sensible protocol: it just reports the 1 via transferring control to the right half in state 1 (the state numbering is inverted, so a 1 command has to be stored as a 0 and vice versa, but this is not a significant issue because you can just invert the commands before encoding them). When the last symbol becomes a `P` (i.e. all the symbols XOR to 1), the head does indeed move to the right half in state 0, informing the right half of a 0 command – but this happens during the "invert the next cell" attempt, when the scan over the program storage has not yet finished. As a consequence, there is a `q` at the end of the program storage rather than a `P`. The next time control is transferred to the left half, it will finish the scan, changing to a `P` and transferring control to the right half in state 1 (which is the state that it would normally use to scan its next cell). The consequence is that each 0 is necessarily followed by a spurious 1. Fortunately, this quirk turned out to be easy to work around in the right-hand half of the program (and it actually simplifies the **idle** state a little, whilst not having negative consequences on anything else).
##### Encoding a running-XOR storage
Only one question remains: is it possible to encode a running-XOR storage such that iterating the running-XOR operation will produce any desired sequence of 0s and 1s?
The answer is "not *any* sequence: there's a restriction". It turns out that the period of a running-XOR storage will always be a power of 2. However, it is possible to construct a running-XOR storage that outputs 0s and 1s in any arbitrary pattern whose period is any arbitrary power of 2. Fortunately, this is a trivial restriction to obey: a quirk in the right half of the program means that every second block of `0111…111` in the output gets entirely ignored, and it is possible to pad out any of these blocks by inserting extra 1s until the length of the program becomes a power-of-2 number of commands.
As for encoding the actual sequence, the encoding algorithm is a fairly simple recursive algorithm:
* The sequence [0] encodes as [0];
* The sequence [1] encodes as [1];
* Otherwise, split the sequence into two equal-length halves A and B, and concatenate (the encoding of A pointwise-xor B) with (the encoding of B).
Proving that this works is a somewhat interesting induction, as the inductive hypothesis needs to include both the encoding rule itself, and the behaviour of a length-2*n* running-XOR memory if you invert all the storage cells (this causes the running-XOR memory to output the same period-2*n* sequence except that the last element in the sequence gets inverted). It is most intuitive to think of a running-XOR memory as a length-2*n* queue whose output is XORed with its input; when entering the memory normally, the last element is dequeued, and both output and enqueued back onto the queue; when entering the memory "inverted" (i.e. with the cells to its left XORing to 1), the last element is dequeued, inverted, and the inverted value is both output and enqueued back onto the queue. If you concatentate two such queues of length 2*n* together, then for 2*n* cycles, you get the XOR of the values dequeued from both queues, and after those cycles the later of the original queues has pointwise-XORed itself with the earlier (because the values it output were enqueued back onto it), whilst the earlier has its original values. The next 2*n* cycles will then output the XOR of the new values of the queues, i.e. the original value of the earlier queue XOR (the original value of the earlier queue XOR the original value of the later queue), which is just the original value of the later queue. Thus, concatenating a running-XOR memory representing A and a running-XOR memory of the same power-of-2 width representing B will output the sequence (A pointwise-XOR B) concatenate B (which is why the recursive encoding algorithm works).
## Conclusions
This is a 2-state, 14-symbol strongly universal Turing machine (i.e. it starts from a finitely initialized tape and implements halting correctly). Finding small universal Turing machines is effectively a code golf problem, so it makes sense to post it on a code golf site.
Most of the machine actually functions fairly intuitively. The only confusing part is the running-XOR storage used for the program, but that can easily be encoded mechanically (and there is [a program](https://tio.run/##LU@7CsJAEOzzFVOkkhRZtTsfYCEKFvYxdhaGFFpaCEFSmU5BVBQRLa2sjBaBmPgflx85706bYWZnmN31Rr4/E6IItvxxBfFnBM@xLbJsF0wTcgEwMoEsIrQUmuDPs8TPHUgTZdvgcWikMZCvOpLvhwMJnyXep2JxQ1tHe3UyZU3ToCyRmR0hX/P4ora48HQF0ltZmyH4KyqCQ39SBMefjjeQfMTA5HxaqjWkMn6p7ljxSpawapbMhRD/y4VD6hVLo/sF "Jelly – Try It Online") to do it) – it's generally considered that as long as the encoding algorithm can be proven to always halt and produce a finite result, it counts. (I prefer for the encoding algorithms to be primitive recursive, so that you can easily tell how long the encoding to take, but this one is (and in fact runs in O(*n* log *n*) time, so is even pretty fast.)
There is still quite a bit of slack in this construction; I ended up not needing to use 2 of the 28 transitions that were available, and it seems likely that many small variations of this machine are also going to be strongly universal. In 2019, I catalogued a range of small programming languages that could be encoded into 2-state 14-symbol Turing machines (the "Core [BIX Queue Subsets](https://esolangs.org/wiki/BIX_Queue_Subset)"), although I didn't at the time mention what my motivation for selecting that particular set of languages was. `a vd vt` is not the only Core BIX Queue Subset that seems promising for Turing-completeness (although it did seem like the easiest to prove, and given that it took me almost 4 years, I have not been particularly inspired to try to work on one of the harder ones…); this Turing machine can easily be adapted to interpret any of the others.
I'd be interested to know whether anyone else has been trying to golf universal Turing machines recently (either strongly universal Turing machines like this one, or one of the less restrictive categories of universality). A quick search didn't turn up anything better for 2 states than 18 symbols, but it's quite possible that this sort of result would be in some obscure corner of the Internet that might be hard to find.
[Answer]
# [Turtlèd](https://github.com/Destructible-Watermelon/Turtl-d) interpreting [CT](http://esolangs.org/wiki/Cyclic_tag_system), 49 bytes
I might be able to golf this
Also, this doesn't output anything useful. it just halts if and only if the given CT program halts.
this is one I made a while ago actually (then golfed some now)
```
!-l[*+.r_]' !l[ l]r[ u.(;d' u)d(1[ r].[ l])( r)+]
```
## How it works:
Turtlèd uses grid cells. When I say "write something on the grid" I mean that a contiguous group of characters is placed on the grid. example
```
[ ][ ][ ][ ][ ][ ][ ]
[ ][H][E][L][L][O][ ]
[ ][ ][ ][ ][ ][ ][ ]
[ ][ ][ ][ ][ ][ ][ ]
```
onto the program
data is inputted first:
```
!-l[*+.r_]'
```
this is essentially a cat program. it writes the input onto the grid.
then the commands are inputted:
```
!
```
what it does with these commands:
these commands are "productions". if the leftmost data bit is a 1, it copies the production onto the end of the data string. otherwise nothing happens. then the leftmost data bit is removed, and it uses the next production with the next left most data bit. the program halts when there are no bits in the data string. A way to do these productions is to deal with the bits and end of productions separately. this is what our program does. it separately copies bits from the command string on to the end of the data string, and separately deletes bits from the datastring
on to how this program does it. after inputting the commands, the turtle/grid pointer moves back to the leftmost bit of the datastring. it then goes into a loop
```
[ u.(;d' u)d(1[ r].[ l])( r)+]
```
what it does in this loop, is it moves up from the leftmost datastring, and writes down the current command character (u.). if it is ;, the end of a production, it moves down and deletes the leftmost data bit beneath it and moves back up (`(;d' u)`). then, either way, it moves down one (`d`). if the bit there was not deleted, it means it must check whether to copy a bit from the commands at the end. so, if this character that is or was the leftmost databit is a 1, it will move to the end of the right end of the data string, copy the bit from the command string, and move back to the space left of the leftmost data bit (`(1[ r].[ l])`). now, it is either on the leftmost databit, which was a zero, or left of the leftmost databit. so, we move right if on a space (`( r)`). then, the command pointer is incremented so we will write down the next command in the next iteration of the loop. If there is no more datastring, this means we will be on a space and the loop will end. otherwise we rerun the loop.
[Answer]
# [Pip](https://github.com/dloscutoff/pip) interpreting [cyclic tag systems](http://esolangs.org/wiki/Cyclic_tag_system), 16 bytes
```
YqWyyPBg@++vXPOy
```
Takes the productions of the tag system as command-line arguments and the initial data string from stdin.
The above code is kinda hard to verify because it doesn't produce any output (so the only observable behavior is "terminates" vs. "doesn't terminate"). Therefore, here's an ungolfed version that outputs the data string after each step, and also terminates after 20 steps so TIO doesn't have to deal with tons of output from infinite loops: [Try it online!](https://tio.run/nexus/pip#@x9ZyBWuUGZjZKCgphBQyaVQqRDgpJDuoK1dphChEOBf@f@/4X8DQ8P/hgZAZAgA "Pip – TIO Nexus")
### Cyclic tag systems
Cyclic tag systems are an extremely [simple yet Turing-complete](https://en.wikipedia.org/wiki/Tag_system#Cyclic_tag_systems) computational model. They consist of a list of *productions* that define operations on a *data string*. The productions and data string consist of 1's and 0's.
At each step, the leftmost character of the data string is removed.
* If the character is 1, the current production is appended to the right side of the data string.
* If the character is 0, nothing is appended.
In either case, the current production moves to the next production in the list, cyclically: if we were at the last production, we loop around to the first. Execution continues until the data string is empty.
### Explanation
```
g is list of cmdline args; v is -1 (implicit)
q Read a line of stdin for the data string
Y and yank it into the y variable
Wy While data string is nonempty:
g@++v Retrieve the next production from g (using cyclic indexing)
POy Pop the first character of y
X String-multiply: result is the production if the first character of y
was 1, or empty string if it was 0
yPB Push that string to the back end of y
```
[Answer]
# [Perl](https://www.perl.org/) → [Three Star Programmer](http://esolangs.org/wiki/Three_Star_Programmer) variant, 26 + 1 = 27 bytes
```
++$a[$a[$a[$_]]]for@F;redo
```
[Try it online!](https://tio.run/nexus/perl#U9GxVdJRULIuTqx0SLRWqdDWtjM0UFNLrcgssf6vra2SGA1F8bGxsWn5RQ5u1kWpKfn//xsqGCkYK5gomP7XTfQ11TMwNAAA "Perl – TIO Nexus") (This link contains a header that exits the program after a set number of iterations (so that TIO doesn't time out), and to print the internal state every iteration (so that it does something observable).)
Run with `-a` (1 byte penalty, as you can fit it in before the `-M5.010` to produce `-aM5.010`).
Specifically, this implements Three Star Programmer in which commands are separated by spaces and no comments are allowed in the file, without I/O extensions. (These changes make no difference to the language's Turing-completeness, obviously.) There isn't a proof of Turing-completeness for Three Star Programmer online, but it is Turing-complete (I've been sharing a sketch proof of its Turing-completeness with other esoprogrammers, but stopped working on the language when I discovered that it was actually fairly easy to program in once you'd gotten over the original shock).
The program doesn't really need much explanation; Three Star Programmer has a very simple specification, and this is a direct translation of it. The only subtle points: `@F` is the input to the program in array form (this is a consequence of `-a`); and `redo` will repeat the entire program as it's in an implicit loop (also a consequence of `-a`).
[Answer]
# BF/P" implemented in a Turing Machine, 842 bytes
[Transition table (linked because of length)](https://pastebin.com/3bj1RSv1)
[Transition table, less golfed version](https://pastebin.com/1Y4anzSa)
[Turing Machine simulator I used](http://morphett.info/turing/turing.html)
This certainly isn't going to win any awards for length, but it's something I've always wanted to do, since BF is so similar to a Turing Machine. Each cell stores a value from `0x0`-`0xF`. The width is however far the Turing Machine website can go without crashing your browser. The `,` and `.` functions (input and output) are not defined, so it's a bit more like P" than true BF.
To run it, paste the transition table into the Turing Machine simulator, set the input to some BF code, and press run.
The tape of the TM stores both the BF code and the BF data, with a single space in the middle. It keeps track of its position in the code by modifying the character that it is currently running (`[` -> `(`, etc) and its position in the data with a `^` in front of the cell. Once it reads a command character, it moves until it hits the caret, moves one cell to the right, and performs the appropriate function. Then it goes back, looking for one of the "modified" command characters in the BF code, and moves on to the next one, repeating the whole process. Once it runs out of code, it halts.
The best way to understand how it works is by running the ungolfed version, putting it on step mode, and watching which lines lead to which others and what each state/block of lines does.
The golfed and ungolfed versions are exactly alike in terms of how they work, but the ungolfed version has more human-friendly names and is broken up into sections.
[Answer]
# [ResPlicate](https://esolangs.org/wiki/ResPlicate) variant -> Python 2, 47 bytes
```
l=input()
while l:l=l[2+l[0]:]+l[2:2+l[0]]*l[1]
```
This function interprets a variant of ResPlicate
* for which a program is a python list of even length with even elements at even indices.
* with no I/O.
* for which trying to copy more values than exist in the remainder of the queue simply copies the remainder of the queue (i.e., the copied bit is not padded with zeroes to the required length).
The last change means that some ResPlicate programs (which meet the first condition) will not behave the same in this variant, but fortunately, the BCT interpreters do not require the removed functionality, and so the language remains TC.
[Try it online!](https://tio.run/nexus/python2#LYy9CsIwGAD3PEXolNQItoNIpIODiKCLjiFDqKn94MsPaYq@uHNV2uk4Dq5LwdEBnt4gBRdDyiV52I72xj/QJvZPoxNdMs5ySWgyMFh6fLc2ZgieFRmcpWHMBSfzht3Pp8PldhXLghODJjlW8Qkb8HHMjJNXD2gpSmxQ1StUGy31D7WcRZeoKr2PCXymOE1qK2qxE5VYqD8@rFvT9vYL "Python 2 – TIO Nexus") This TIO has a print wedged into it to show that it works and a header that kills the program after 1 second and an example that manages to generate more output than TIO can handle in that one second.
[Answer]
# C implementing the [(2,3) Turing Machine](https://en.wikipedia.org/wiki/Wolfram%27s_2-state_3-symbol_Turing_machine), ~~236~~ 205 bytes (~~46~~ 31 less if you don't care about awkward inputs)
Thanks to Appleshell for -11 bytes, VisualMelon for -12 bytes, and Johan du Toit for -7 bytes.
*CeilingCat made a version that uses only 144 bytes, see [here](https://tio.run/##DY1LCsIwFADP0kUhnxdoY6vREDxIqVCSWC22hr7nSjx7zHYYZryavc/ZP6ZdJEAIg@5PIyx2nZ4bI/4NA9L@ihubIyFb44qRWIDOgO6PnPPRdcbe3ztLLshWGyvlYsmJpIoikmNaoSIuSKLszpCkY3irCtCqBXR4pVpfKqoPkD5lUBqc21/OTdP8AQ).*
(I've added a few line breaks here so you don't have to scroll, but normally most of those would be deleted)
```
#define c char
j;i;k;c s,d[256];c main(){c*p=d+128;gets(d);
for(;k<256&&d[k];)d[k++]-=48;for(;++j<256;)
{c t=*p;*p=-t*t+(2-s)*t+1+s;p+=(s^t==0)*2-1;s=s?t%2:!t%3;
for(i=0;++i<256;)printf("%d",d[i]);puts("");}}
```
[Try it online!](https://tio.run/nexus/c-gcc#JY7NDoIwEITvPgViIC21Sak/Ia6ND0IwIS1oJUJD68nw2J5xlcvOJjPzZeaNaVrbN5GO9L0eVw@w0IGO/NaU8nCs8H3Wtif0rTOnDMtlAbcmeGIotMNIoDtjLE1N2VVA8TJWcbUvFpOxx88GbEdBZQ6QwUMWGJHcU9SceXBMEX8NSgmaSZ6DV/4SEnlah2T3x1glkGQXkhttH1oSJybGibai4F44J44pTNM8CyHmTz9wXet78wU "C (gcc) – TIO Nexus")
To use: Input a string of up to 256 ones, zeros, and twos to initialize the the tape. Any uninitialized values will be zero. (Values other than 0, 1, and 2 may cause undefined behavior.) The program will iterate over 256 steps. The number of steps it iterates over can be increased by modifying the code, but obviously that requires more characters.
It's a pretty long entry, but this is my first time doing one of these and I didn't use a dedicated golfing language. I had a lot of fun, even if it turned out longer than I expected.
A lot of the bytes are from dealing with input and output, and I lost a whole 42 bytes by making it accept 0, 1, and 2 instead of NUL, SOH, STX. (To change that, delete `k;` from the front and `for(;k<256&&d[k];)d[k++]-=48;` from the second line.)
The transistion table, especially the line `*p=-t*t+(2-s)*t+1+s;` (which sets the values on the tape) could probably be compressed more as well.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly) → [Addition Automaton](https://esolangs.org/wiki/Addition_Automaton) with *b* = 10, 3 bytes
```
ṃḌç
```
[Try it online!](https://tio.run/##y0rNyan8///hzuaHO3oe7mw5vPz///9GBkZGRgYWRgYgYPY/2hBE6xjpQARMgGwgzwACgRwzEDYy0DGEMQxiAQ "Jelly – Try It Online") (contains added `Ṅ` so that you can see the program being interpreted)
Me in 2018:
>
> Is three bytes possible? [...] at this point it surely seems like it'd be possible somehow, as there are so many ways to do it in four and so many Turing-complete languages you could implement.
>
>
>
Five years later, I finally figured it out.
This program's first argument is the Addition Automaton initial value, and its second argument is the transition table (which is a map). Jelly uses 1-based indexing, so the entry for *d*=0 actually has to be at the end of the table rather than the start, but otherwise the map is just being specified directly by giving all the mapped-to values in order of the digits being mapped.
## Explanation
```
ṃḌç
ṃ Convert {the left argument} into digits
in base (element count of {the right argument}),
then map them using {the right argument} as the map
Ḍ 1 × the least significant digit, plus
10 × the second-least significant digit, plus
100 × the third-least significant digit, etc.
ç Recursive call, where the left argument is {the result of Ḋ}
and the right argument is {this function's right argument}
```
Somehow it is not too much of a surprise that the three-byte breakthrough involved using `ṃ`, a built-in which a) has a very complicated effect and b) for which part of that effect involves indexing into a map/table. Being able to index into a table is the hardest part of implementing many Turing tarpits (not because it's hard, but because the other parts of implementing them are even easier), so finding this answer was a case of looking at what `ṃ` did and trying to find another builtin that would combine with it to produce a Turing-complete language. (And yes, Addition Automaton was originally discovered by trying to work out what `ṃḌ` did, although luckily the language as a whole has rather sensible behaviour that can be defined without having to resort to Jelly.)
Addition Automaton is basically defined as "a find-and-replace on the digits of a number, but the replacements can be multiple digits long, and carry into the more significant digits as a consequence". This is actually a *very* powerful operation; if you allow bases *b* above 10, it is possible to implement Turing machines pretty much directly. However, the definition requires the two base conversions (into digits to do the mapping, and then back into a single number to handle the carry) to use the same base, whereas thus Jelly program uses the size of the map to do the first conversion and hardcodes the second base conversion to base 10. As such, the program only actually works when *b*=10; but fortunately, *b*=10 turns out to be just enough for Addition Automaton to be Turing-complete (it can implement [Echo Tag](https://esolangs.org/wiki/Echo_Tag) with arbitrary *n*, which is enough to implement arbitrary tag systems, and from there you can reach Turing machines).
The next challenge in writing very short interpreters in Jelly is likely to try to get them to halt. The effective halt state for this interpreter is "the internal value repeats an older value times a power of 10" – this is something that can be objectively defined, but would take quite a bit of code to implement in Jelly. In Addition Automaton, you have some amount of ability to trade simple halt states for small values of *b*; *b*=10 is enough to do things like [run 4-state 2-symbol busy beavers](https://tio.run/##y0rNyan8///hzuaHO6c93NFzcvqxNf///zcyAIL/0YYGOoYmOiZAygiIzQyAXAMdC5CohY6RjkEsAA "Jelly – Try It Online"), but the "the value multiplies itself by *b* every cycle" halt state used there is probably not achievable for arbitrary programs with a *b* as small as 10, and this program has a tendency to collapse into "the binary builtins aren't chaining the way I want them to" hell as soon as you start trying to use custom bases rather than sticking to decimal. So there's a lot of scope for creative solutions there, and Addition Automaton may well not be the best language for the "exit when the implemented language halts" version of the challenge.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly) → [Couplet 2C](https://esolangs.org/wiki/2C#Couplet_2C) variant, 3 bytes (infinite loop) or 4 bytes (halting)
```
ṃVß
ṃV¥Ƭ
```
[Try it online!](https://tio.run/##y0rNyan8///hzuawQ0uPrfl/eHnk//9GRoaGIAwCRkYG/6MNdAwNdQzQIFDIyAhDFCiERe0ggrEA "Jelly – Try It Online")
Takes the initial string from the left-hand argument, and the replacement table from the right-hand argument (this is a map from numbers to strings encoded as a Jelly array, i.e. the element at index 1 is the key for value 1, and so on). Replacement strings are encoded as numbers in big-endian base *n*, where *n* is the size of the alphabet (which must be a power of 10).
The language implemented by this program is fairly powerful, and doesn't seem to *exactly* correspond to any of the existing languages, but is powerful enough to almost directly implement [Couplet 2C](https://esolangs.org/wiki/2C#Couplet_2C) via using replacement strings that consist of two copies of the same symbol (except at the end of the string, where they have an odd length), and using only symbols that have no leading zeroes. As such, it is trivially Turing-complete. The halt state is a "trivial infinite loop" (i.e. repeating a previous state) rather than having a separate halt symbol.
## Explanation
```
ṃVß ṃV¥Ƭ
ṃ ṃ Convert {the left argument} into digits
in base (element count of {the right argument}),
then map them using {the right argument} as the map
V V Concatenate the digits of the result
ß Recursive call to the main function
Ƭ Loop until a previous result is repeated
¥ over the previous two commands
```
Jelly's `ṃ` is powerful enough that there's more than one way to combine it with a single other built-in, and a loop, in order to create a Turing-complete language. In an earlier answer, I used `Ḍ`, which created a very powerful language but had trouble halting. Using `V` creates a different very powerful language which finds halting much easier.
The basic idea is that when the size of the replacement table is a power of 10, `ṃ` is effectively splitting a number into substrings of a given length, and mapping those substrings through the replacement table; then `V` concatenates the resulting substrings. This operation is pretty similar to that done by a tag system, but doesn't implement tag systems directly because it doesn't remember the length of the string across iterations (whereas in, say, 2-tag, a common programming technique is to create a string that's either an odd or an even number of characters long to change which commands run in the next iteration). You can implement Couplet 2C pretty easily, though, by using two copies of the same symbol and rebracketing them:
```
xxyyzz0 string looks like this
x xy yz z0 using ṃ to convert into digits in base 100^n
aa bb cc dd0 using ṃ to map via a replacement table
aabbccdd0 using V to concatenate digits
```
The halt state of `Ƭ` – a repeat of a previous state – is a little tricky to achieve (and different from Couplet 2C's "natural" halt state), but by varying the behaviour of the end of the string it is possible to make it work. (One possible way to make the halt state work: compile a Turing machine into a cellular automaton into full 2C into Couplet 2C, and have the ends of the tape stay in a stable place by alternating between growing and shrinking, except when the tape head is there. This will quickly cause a halt of the Turing machine to enter a repeat of a previous state in the 2C program.)
One potential controversy with this answer: `V` in Jelly is overloaded: when acting on a list of numbers, it concatenates their digits; but when acting on a string, it is an `eval` function. It isn't being used as an `eval` function here, but it is still a little uncomfortable to use a builtin that is represented by the same character as the `eval` builtin (and I think internally Jelly implements it by concatenating the string representations of the numbers and then using an `eval` to convert the number from its string format to an actual number). I assume the question was intending to ban the use of `eval` to evaluate code, as opposed to parsing integers from strings, but it is possible that it ends up inadvertently disallowing this style of answer.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly) → [2-Tag system](https://en.wikipedia.org/wiki/Tag_system), 8 bytes
```
µḢị⁴⁸;Ḋß
```
[Try it online!](https://tio.run/nexus/jelly#@39o68OdLQ93LHq4u/tR45ZHjTusH@7oOjz/////0YY6QBj7PzraSMc4VifaEITBQrEA)
I have a bounty going favouring practical languages, but thought I might as well try to win the original task while I was at it (as I can't exactly win my own bounty).
Implements a variant of tag systems with no halt state, as it isn't needed for Turing completeness. The states are numbered from 1, consecutively, and the initial string comes before the program.
For example, Wikipedia gives an example of a tag system {`a`,`b`,`c`}, {`a` → `bc`, `b` → `a`, `c` → `aaa`} with initial string `aaa`; in this input format, that's `[1,1,1]`, `[[2,3],[1],[1,1,1]]`. (Tag systems don't have a fixed syntax, and this seems like a reasonable way to do it.)
The TIO link has an added `Ṅ` ("write internal state and a newline to stdout") in order to show that the program is in fact working.
## Explanation
```
µḢị⁴⁸;Ḋß
{implicit: initialise internal state from first argument}
µ Disregard the second command-line argument by default
Ḣ Take the first element, removing it from the internal state
ị⁴ Use the value to index into the second argument
⁸; Prepend (the rest of) the internal state
Ḋ Discard the first element of the internal state
ß Loop forever
```
[Answer]
# [Röda](https://github.com/fergusq/roda) implementing [Fractran](https://en.wikipedia.org/wiki/FRACTRAN), ~~114~~ ~~112~~ 106 bytes
*1 byte saved thanks to @fergusq by rearranging parameters*
```
f&n,a{x=1{x=0;(a/" ")()|[_/`/`]|[parseInteger(_[0],_1[1])]|{|q,w|{n*=q/w;x=1}if[n%w<1,x<1]}_,_}while[x>0]}
```
[Try it online!](https://tio.run/nexus/roda#FYxBCoMwFET3PUUItGgJfL@puFC77xlCiFnEVmg/1RYiJDm7TRfzhgfD7NOJhA3bgDlVV1jgjJdFGZWBEUYd1duuH3ejr7u7tTCq0sKgQl3qGOIifAx0HhbwXb5I86To6HsUW486GWGSf8xPp7ZrpdP@sjOxcGCMhrbONTES/NI0ICVDBMwERCah/WudTfI8U6QPaf8B "Röda – TIO Nexus")
Call the function like so: `f reference_to_input program`. The output will be stored in the location of the `input`.
[Answer]
# Lua interpreting Brainf\*\*\*, 467 bytes
```
b,r,a,i,n,s=0,io.read,{0},1,1,"><+-.,[]"c,f=r(),{function()n=n+1;a[n]=a[n]or 0;end,function()n=n-1;a[n]=a[n]or 0;end,function()a[n]=a[n]+1;end,function()a[n]=a[n]-1;end,function()io.write(string.char(a[n]))end,function()a[n]=io.read():byte()end,function()i=a[n]~=0 and i or c:find("]",i)end,function()if a[n]~=0 then b,x=1,""repeat i=i-1 x=c:sub(i,i)b=x=="["and b-1 or x=="]"and b+1 or b until b==0 and x=="["end end}repeat f[s:find(c:sub(i,i),1,1)]()i=i+1 until i>#c
```
I know there's still some slimming down I can do later, but here's where my first pass ended. Takes the brainf code from standard input.
[Answer]
## Clojure, ~~82~~ 81 bytes (Turing Machine)
Update: removed a space from `t{} s`.
```
#(loop[p 0 t{}s 1](if-let[[S M N](%[(or(t p)0)s])](recur(+ p M)(assoc t p S)N)t))
```
Implements the Turing Machine as a loop, returns the tape when the halting state is reached. In state transition rules this is indicated by ommitting the transition state. This settins `N` to `nil` and the subsequent `if-let` will abort as the corresponding state transition is not found from the input hash-map `%`. Actually any value for this state will do, such as `:abort`, 0 or -1.
Ungolfed with an example 3-state 2-symbol busy beaver from [Wikipedia](https://en.wikipedia.org/wiki/Turing_machine#Formal_definition).
```
(def f #(loop[pos 0 tape {} state 1]
(if-let [[sym move next-state](%[(get tape pos 0)state])]
(do (println [pos tape state])
(recur(+ pos move)(assoc tape pos sym)next-state))
tape)))
(f {[0 1] [1 1 2]
[0 2] [1 -1 1]
[0 3] [1 -1 2]
[1 1] [1 -1 3]
[1 2] [1 1 2]
[1 3] [1 1]})
{0 1, 1 1, -1 1, -2 1, -3 1, 2 1}
```
[Try it online](https://tio.run/nexus/clojure#dc5BCoMwEAXQvaf4UAozFMHEc@jGZciiWANCMCFJV@LZ7VAslEpn@/78mZ0ek4PDhXwI0UQ0KOuGDGVpdrWfijEDOvSWroZCooLIDWfLltI0PhPdENEx3XMOI0QxcM@FmauKYpqX4heQw2oa6YRRgIK2Fb5HTL@tVhI6WfsxCf2gOkoFW3sy/fegOkplfZNX9/0F).
On a single core of 6700K this runs the 5-state 2-symbol busy beaver (47.1 million steps) in about 29 seconds, or 1.6 million steps / second.
[Answer]
## C (clang) interpreting Brainfuck, ~~187~~ 182 bytes
```
t[99],*p=t,c,i,l;f(*t){for(i=0;c=t[i];i++){c^62?c^60?c^43?c^45?c^46?c^44?c^91:(*p=getchar()):putchar(*p):--*p:++*p:--p:++p;if(c==93&&*p)for(l=1;l>0;)c=t[--i],c==91?l--:c==93?l++:0;}}
```
[Try it online!](https://tio.run/##VY3RasQgEEWfm8/Yh0WjI0l3uxCN5gf6ByGFIDUV7Fa2lj6E/HpTJw0tveDxMFccCzaM12ldU980Ay@jTtxyz4NypEx0dm834nWlrE69H5RnjM726XLfZVQZ5xPiAXFBnDOaWpL80fSc7Mt4I5TK@PGjZaQSoIySsQwAlKi8I1br5nQ85h4XBl2rYCpFcSuAHzj2dRcA5PayC4zJSi3L@jr6K6HFXNw58nhgv@nNLuZvZrbT5sCQXRgm9kagCJy1LfsfYbYOtuxXFoPFgapiWb@sC@P0vsLnNw "C (clang) – Try It Online")
[Answer]
# [><>](https://esolangs.org/wiki/Fish) interpreting "Craw><>", 4 bytes
```
iiip
```
[Try it online!](https://tio.run/##S8sszvj/PzMzs@D/fwA "><> – Try It Online")
Craw><> is a language I just made up defined by the above implementation. It's almost obvious that you can translate all ><> programs into Craw><>. Pretty sure someone had this idea before me.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) interpreting [Thue](https://esolangs.org/wiki/Thue) variant, 1 byte
```
¢
```
[Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyIiLCIiLCLCoiIsIiIsIltcIjAqXCIgLCBcIjAqKlwiICwgXCJeXCJdXG5bXCIxXCIgICwgXCIqMFwiICAsIFwiXjBcIl1cblwiXjEwMTFcIiJd)
`¢` is a builtin that performs infinite replacement. When given a string \$s\$, a list of targets \$[t\_1, t\_2 ... t\_n] \$, and a list of replacements \$[r\_1, r\_2 ... r\_n]\$ it replaces \$t\_1\$ with \$r\_1\$, \$t\_2\$ with \$r\_2\$ and so on, repeatedly, until no more replacements can be performed.
As it turns out, this is sufficient for Turing-Completeness as it can interpret a variant of [Thue](https://esolangs.org/wiki/Thue). A Thue program consists of a series of replacement rules, which replace one string with another, and an initial string to which the replacements are performed.
The only difference between this language and Thue is that, while the Thue spec mandates a single replacement be performed at a time, this language performs as many replacements as possible in parallel. This turns out to be equivalent, though, as it can be treated as performing a series of replacements.
This language takes input as a list of replacement strings, a list of target strings, and the initial string on which replacements are to be performed. The TIO link contains a binary-to-unary converter.
[Answer]
## Clojure, 75 bytes (Cyclic tag system)
Update 1: replaced `some?` with `nil?`.
Update 2: Fixed a missing `S` in else branch of `if s`.
```
#(loop[[p & P](cycle %)[s & S]%2](if(nil? s)S(recur P(if s(concat S p)S))))
```
Implements the [cyclic tag system](http://esolangs.org/wiki/Cyclic_tag_system), returns `nil` if the program halts, loops forever otherwise. Clojure really shines here with infinite lazy sequences (such as [cycle](https://clojuredocs.org/clojure.core/cycle)) and [destructuring](https://clojure.org/guides/destructuring). Ones and zeros are indicated as true and false values. When the data string runs out `s` becomes `nil`.
Ungolfed:
```
(def f #(loop[[p & P] (cycle %) [s & S] %2 i 5]
(do
(pprint [p (concat [s] S)])
(if (and (some? s) (pos? i))
(recur P (if s (concat S p) S) (dec i))))))
```
Example results:
```
(f [[false]] [true true])
[[false] (true true)]
[[false] (true false)]
[[false] (false false)]
[[false] (false)]
[[false] (nil)]
(f [[false true true] [true false] [true false true]] [true])
[[false true true] (true)]
[[true false] (false true true)]
[[true false true] (true true)]
[[false true true] (true true false true)]
[[true false] (true false true false true true)]
[[true false true] (false true false true true true false)]
```
[Answer]
# CJam → ResPlicate Variant, ~~15~~ ~~14~~ 13 bytes
-1 byte thanks to @ais523
```
l~{(/((*+e_}h
```
The variant is the same as the one in [this answer](https://codegolf.stackexchange.com/a/119502/61384), except that the number of items taken off the queue is one less than the top number on the queue.
The `l~{ ... }h` part just takes an array as input and repeats until that array is empty.
Explanation for the main loop:
```
e# Stack: | [3 2 1 1 2 2 2 1]
( e# Pop first element: | [2 1 1 2 2 2 1] 3
/ e# Split chunks: | [[2 1 1] [2 2 2] [1]]
( e# Pop first: | [[2 2 2] [1]] [2 1 1]
( e# Pop first: | [[2 2 2] [1]] [1 1] 2
* e# Repeat array: | [[2 2 2] [1]] [1 1 1 1]
+ e# Concatenate: | [[2 2 2] [1] 1 1 1 1]
e_ e# Flatten: | [2 2 2 1 1 1 1 1]
```
[Answer]
# [Headass](https://esolangs.org/wiki/Headass) interpreting [BCT](https://esolangs.org/wiki/Bitwise_Cyclic_Tag), 84 bytes
```
U[{U+)]ORO:RO};N-)-E:{UON)}:]+E.{UO+):};UP{N)UO}:E.U[{U+)]ORO:RO};UO^{N)UO}:D)E:]O[E
```
[Try it here!](https://replit.com/@thejonymyster/HA23) Code will need to be copied, and executed like this:
```
srun("U[{U+)]ORO:RO};N-)-E:{UON)}:]+E.{UO+):};UP{N)UO}:E.U[{U+)]ORO:RO};UO^{N)UO}:D)E:]O[E",<your bct program here>)
```
where the program is formatted as individual bits delimited by comma, and the code separated from the datastring by a -1. for example, the bct program `111000|111` would be executed like this:
```
srun("U[{U+)]ORO:RO};N-)-E:{UON)}:]+E.{UO+):};UP{N)UO}:E.U[{U+)]ORO:RO};UO^{N)UO}:D)E:]O[E",1,1,1,0,0,0,-1,1,1,1)
```
The program prints bits deleted by the `0` command, but this can be disabled for -1 byte by removing the `P` in the program. Halts by throwing a Headass error.
I chose classic Headass over it's younger, ascii-based brother [Headascii](https://esolangs.org/wiki/Headass#Headascii) because it allowed me to take -1s as inputs, which is conveniently close to 0, as is 1.
Before I get into the explanation I just want to say that if I were allowed to choose a TC subset of this lang I'd be golden, having to validate the input cost me like 5 bytes T\_T
### Code breakdown:
```
U[{U+)]ORO:RO};N-)-E:{UON)}:]+E Block 0
U[ Store the first command
{ } Loop
U+) If the next number in the program is -1,
]O Push the stored command to the end of the
program string
RO Push the -1 to the end of the program string
: ; And then leave the loop
Else
RO Leave it alone and continue
N-) If the data string is empty
-E Go to block -1 (exit with error)
: Else
{UON)}: Ready the rest of the data for the next block
]+E Then go to either block 1 or 2 based on if
the stored command was 0 or 1 respectively
.{UO+):};UP{N)UO}:E Block 1 (handles 0)
. Block separator
{UO+):}; Read through the numbers until after the -1 delimiter
UP Print and discard the first bit of the data string
{N)UO}: Ready the rest of the data for the next block
E Go to block 0
.U[{U+)]ORO:RO};UO^{N)UO}:D)E:]O[E Block 2 (handles 1)
. Block separator
U[{U+)]ORO:RO}; Same as in block 0
UO^ Store the first bit of the data string
{N)UO}: Ready the rest of the data for the next block
D) If the first bit of the data string is 0
E Then go to block 0
: Else
]O Push the stored bit from the command string
to the end of the data string
[E Go to block 0
```
My heftiest explanation yet. Whew!
[Answer]
# [Chip](https://github.com/Phlarx/chip), 20+3 = 23 bytes (Rule 110)
```
AZZ
>}/a
`)\'E~Zte*f
```
+3 for flag `-z`
[Try it online!](https://tio.run/nexus/chip#@@8YFcVlV6ufyJWgGaPuWhdVkqqV9v@/IQgYAIGhgaHhf90qAA "Chip – TIO Nexus")
This submission isn't perfect, as Chip doesn't (yet) have any looping ability, so the output must be passed in as the input to simulate multiple generations, with [something like this](https://tio.run/nexus/bash#TY49C8IwEIb3@xU3FNpYbBPXfoBDXd2LgyVNaKAkIY2Cov71Gquoz3DDHc/7Hu881uhOo2CMZnywWJYYN/tdPG/bFup73sGRHOLm0XqxknO4ACgv3FRtKJy7sYoSHjIiqUZBAAQfDEZhD9I4TBJd0UKXi1DoNCUEegP44a1bp7SXi4Q3zI31OR@UXUZmL7i@/v9HvvavqjdazOwFDTDK2BM "Bash – TIO Nexus") (of course, you could run that loop indefinitely, and Chip can handle arbitrarily long input, so this combination is Turing Complete).
This implementation take input and given output in the form of ASCII `0`s and `1`s. The logic here is as follows:
```
p := value of left neighbor cell AZZ
q := value of current cell AZ
r := value of right neighbor cell A
q' := ((r xor q) and p) or >}/a
((r or q) and ~p) `)\'
```
The remainder of the elements are for housekeeping: `e*f` causes ASCII numeral output, and `E~Zt` terminates execution two bytes after the input is exhausted (since the width grows by 2 each generation).
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) implementing "add minimum to transpose", 4 bytes
```
{:g+
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJ7OmcrIiwi4oCmIiwiW1sxLDIsM10sWzE1LDEwLDVdLFsxMDAsMjAwLDMwMF1dIl0=) (prints each iteration)
```
{ # Forever
+ # Add to each
:g # Corresponding element of minimum row
```
See [this answer](https://codegolf.stackexchange.com/a/125815/100664) for a better explanation of why this is turing-complete.
[Answer]
# JavaScript interpreting [Rule 110](https://en.wikipedia.org/wiki/Rule_110), 131 bytes (99 bytes?, 28 bytes?)
```
a=(p,q,r)=>q+r+q*r+p*q*r
b=l=>{r="";for(i=0;i<l.length-2;i++)r+=a(l[i],+l[i+1],+l[i+2])%2;return r}
c=(l,n)=>!n?l:c(b(0+l+0),n-1)
```
As you can see, the code defines 3 functions, `a`, `b` and `c`. Perhaps it's possible to save bytes by combining them in 1 function (I don't see how), but it's good that there separate because each of them already fulfills this challenge in some sense.
Function `a`takes 3 numbers as input and computes some weird polynomial of them. When these 3 numbers are `0`or `1`they can bee seen as Rule 110 cells. The parity of the output of `a` can then be seen as the value of the middle cell in the next generation. So in some sense, this simple function is already a Rule 110 'interpreter' (28 bytes):
```
a=(p,q,r)=>(q+r+q*r+p*q*r)%2
```
We can then create a new function `b` that evaluates `a` on every character of a string of ones and zeros. This `b`is then, in a better way than `a`, a Rule 110 interpreter. Taking mod 2 after the evaluation of a saves brackets (99 bytes):
```
a=(p,q,r)=>q+r+q*r+p*q*r
b=l=>{r="";for(i=0;i<l.length-2;i++)r+=a(l[i],+l[i+1],+l[i+2])%2;return r}
```
To actually compute a function with Rule 110, the user must specify the starting state and the number of generations after which the output will 'appear'. We can make a third function `c` that takes a string of ones and zeros, and a positive integer `n`, that then evaluates `b`on the string, `n`times. Like this we can really see Rule 110 as a programming language, where a program is an intitial state and a number `n`, and the output is the state after `n`generations. The function `c`is now an actual interpreter for that programming language so the final code for this challenge is what I presented above.
] |
[Question]
[
Your goal is to create an alphabet song as text in the following form (in order):
```
A is for <word starting with A>
B is for <word starting with B>
C is for <word starting with C>
...
Z is for <word starting with Z>
```
### Example output:
```
A is for Apple
B is for Banana
C is for Carrot
D is for Door
E is for Elephant
F is for Frog
G is for Goat
H is for Hat
I is for Icicle
J is for Jelly
K is for Kangaroo
L is for Lovely
M is for Mom
N is for Never
O is for Open
P is for Paste
Q is for Queen
R is for Rice
S is for Star
T is for Test
U is for Underneath
V is for Very
W is for Water
X is for X-ray
Y is for Yellow
Z is for Zipper
```
### Rules:
* Each "letter" of the song has its own line, so there are 26 lines, and a possible trailing linefeed.
* The output is case-sensitive:
+ The letter at the start of each line must be capitalized.
+ `is for` is lowercase.
+ The chosen word does not need to be capitalized, but may be. All lines should be consistent.
* The chosen word for each line is up to you, but must be a valid English word with at least 3 letters, and it cannot be a conjunction (like `and` or `but`), interjection/exclamation (like `hey` or `yay`), abbreviation (like `XLS`), or a name (like `Jon`).
* Though I doubt anyone would find it shorter, I'd find it acceptable to use a phrase instead of a single word. So if for some reason `S is for Something smells fishy...` is shorter, go for it.
* Put your program's output in your answer, or at least the list of words you used (if there's a link to run your code online, we don't need to see the entire output).
* Shortest code wins
---
*This challenge was inspired by [this video](https://www.youtube.com/watch?v=Njvulx5N_qE).*
[Answer]
# Bash (+coreutils), ~~81~~, ~~87~~, ~~82~~, 78 bytes
Uses the man page for [X](https://linux.die.net/man/7/x), as the source of words.
**Golfed**
```
man xyst\ x|&grep -Po '\b[a-z]{4,} '|sed 's/\(.\)/\u\1 is for &/'|sort -uk1,1
```
*EDITS*
* Used a non-existing 'xyst' man page + `|&` to save 5 bytes;
* Saved 4 more bytes, by swapping *sed* and *sort*.
**Test**
```
%man xyst\ x|&grep -Po '\b[a-z]{4,} '|sed 's/\(.\)/\u\1 is for &/'|sort -uk1,1
A is for also
B is for build
C is for computing
D is for distribution
E is for entry
F is for following
G is for graphics
H is for hierarchical
I is for implementations
J is for just
K is for keyboard
L is for listing
M is for manual
N is for network
O is for output
P is for programs
Q is for quite
R is for runs
S is for system
T is for transparent
U is for used
V is for various
W is for window
X is for xyst
Y is for your
Z is for zeros
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~88~~ 77 bytes
-11 bytes thanks to xnor (avoid the zip by traversing the string and counting `c` up from 65)
```
c=65
for x in'niooaauusoioaiuaaoiineeaei':print'%c is for %c%st'%(c,c,x);c+=1
```
**[Try it online!](https://tio.run/nexus/python2#FcsxDoAgDAXQ3VN0IWhkcdBBw2GaBpK/tAYk4fao4xvekHjsU7ZCnaBeYcbcWjUYozEboClxgj/vAn28E0KlPzhx9fMsQUJfLlnjNsYL)**
(A port of my Jelly answer, when it was 56 bytes.)
```
A is for Ant
B is for Bit
C is for Cot
D is for Dot
E is for Eat
F is for Fat
G is for Gut
H is for Hut
I is for Ist
J is for Jot
K is for Kit
L is for Lot
M is for Mat
N is for Nit
O is for Out
P is for Pat
Q is for Qat
R is for Rot
S is for Sit
T is for Tit
U is for Unt
V is for Vet
W is for Wet
X is for Xat
Y is for Yet
Z is for Zit
```
[Answer]
# Bash, ~~78~~, 69 bytes
### Aardvarks, Babushkas and Kamikazes !
**Golfed**
```
sed -nr '/^[a-z]{9}$/s/(.)/\u\1 is for &/p'</u*/*/*/words|sort -uk1,1
```
*EDITS*
* Got rid of grep, -9 bytes
**Test**
```
%sed -nr '/^[a-z]{9}$/s/(.)/\u\1 is for &/p'</u*/*/*/words|sort -uk1,1
A is for aardvarks
B is for babushkas
C is for cablecast
D is for dachshund
E is for eagerness
F is for fabricate
G is for gabardine
H is for habitable
I is for ibuprofen
J is for jabberers
K is for kamikazes
L is for labelling
M is for macaronis
N is for nailbrush
O is for obedience
P is for pacemaker
Q is for quadrants
R is for rabbinate
S is for sabotaged
T is for tableland
U is for ulcerated
V is for vacancies
W is for wackiness
X is for xylophone
Y is for yachtsman
Z is for zealously
```
Makes use of */usr/share/dict/words*:
>
> words is a standard file on all Unix and Unix-like operating systems, and is simply a newline-delimited list of dictionary words. It is used, for instance, by spell-checking programs.
>
>
>
[Answer]
# [PowerShell](https://github.com/PowerShell/PowerShell), ~~150~~ ~~141~~ ~~117~~ 75 bytes
```
65..90|%{$i=[char]$_;"$i is for $i$('niooaauusoioaiuaaoiineeaei'[$_-65])t"}
```
[Try it online!](https://tio.run/nexus/powershell#BcFBCoAgEAXQq0hMWIukTUJEJxGRIYz@xgHNVXV2e6/ZxZh1fvuHsLvj4uwpbB1BoahTsiLQoBNEmGstAmFUZgFSjByhHYXJLn68u6@1Hw "PowerShell – TIO Nexus")
Loops from `65` to `90` (i.e., ASCII `A` to `Z`). Each iteration, we turn the integer into the appropriate `char` (i.e., ASCII `65` for `A`), save that into `$i` for use later, string-concatenate that with `is for $i`, and then tack on the middle of the appropriate word. That's done by indexing into a lengthy string (borrowed from [Jonathan Allan's answer](https://codegolf.stackexchange.com/a/109519/42963)). Finishes off with the letter `t` to make the three letter word.
The resulting strings are all left on the pipeline, and an implicit `Write-Output` at the end prints them with newlines in between.
*Saved a bunch of bytes thanks to [Rod](https://codegolf.stackexchange.com/users/47120/rod)*
*Borrowed wordlist from [Jonathan Allan's answer](https://codegolf.stackexchange.com/a/109519/42963)*
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 39 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
;“ẉbẊWS»,⁸K;;”t
“¤ṁp}œḊṄæ®’b6ị“ʠȷ»ØAç"Y
```
**[TryItOnline!](https://tio.run/nexus/jelly#AUwAs///O@KAnOG6iWLhuopXU8K7LOKBuEs7O@KAnXQK4oCcwqThuYFwfcWT4biK4bmEw6bCruKAmWI24buL4oCcyqDIt8K7w5hBw6ciWf//)**
Based on the 56 byte version (two below), but changed words to remove all middle letter `"u"`s so it can index into the dictionary word `"anisole"`\*, which has the convenience of having the letters we need all at indexes less than six: `1:a, 2:n 3:i, 4:s, 5:o (6:l), 0:e` (note the `"e"` on the right is at index zero [also 7 and -7 and any other number congruent to 0 mod 7]). It's also early in the dictionary so has only a two rather than the much more common three byte lookup index (`"anisogamete"` would also work for 2).
\* The old-school name for the aromatic ether methoxybenzene, often used in perfumes.
```
A is for Ant
B is for Bit
C is for Cot
D is for Dot
E is for Eat
F is for Fat
G is for Got
H is for Hat
I is for Ist
J is for Jot
K is for Kit
L is for Lot
M is for Mat
N is for Nit
O is for Oat
P is for Pat
Q is for Qat
R is for Rot
S is for Sit
T is for Tit
U is for Unt
V is for Vet
W is for Wet
X is for Xat
Y is for Yet
Z is for Zit
```
###How?
```
“¤ṁp}œḊṄæ®’b6ị“ʠȷ»ØAç"Y - Main link: no arguments
“¤ṁp}œḊṄæ®’ - base 250 compressed number -> 75711304811637630759
b6 - convert to base 6 list
-> [ 2 , 3 , 5 , 5 , 1 , 1 , 5 , 1 , 4 , 5 , 3 , 5 , 1 , 3 , 1 , 1 , 1 , 5 , 3 , 3 , 2 , 0 , 0 , 1 , 0 , 3]
“ʠȷ» - word from Jelly's dictionary, "anisole"
ị - index into that
-> [ "n" , "i" , "o" , "o" , "a" , "a" , "o" , "a" , "s" , "o" , "i" , "o" , "a" , "i" , "a" , "a" , "a" , "o" , "i" , "i" , "n" , "e" , "e" , "a" , "e" , "i"]
ØA - get the uppercase alphabet
-> [ "A" , "B" , "C" , "D" , "E" , "F" , "G" , "H" , "I" , "J" , "K" , "L" , "M" , "N" , "O" , "P" , "Q" , "R" , "S" , "T" , "U" , "V" , "W" , "X" , "Y" , "Z"]
ç" - zip with last Link (1) as a dyad (i.e. get [f("A", "n"), f("B", "i"), ...]
-> ["A is for Ant","B is for Bit","C is for Cot","D is for Dot","E is for Eat","F is for Fat","G is for Got","H is for Hat","I is for Ist","J is for Jot","K is for Kit","L is for Lot","M is for Mat","N is for Nit","O is for Oat","P is for Pat","Q is for Qat","R is for Rot","S is for Sit","T is for Tit","U is for Unt","V is for Vet","W is for Wet","X is for Xat","Y is for Yet","Z is for Zit"]
Y - join with line feeds
- implicit print
;“ẉbẊWS»,⁸K;;”t - Link 1, make a song line: character X; character Y
“ẉbẊWS» - compressed string = " is for"
; - X (e.g. "A") concatenate that -> "A is for"
, - pair that with
⁸ - the left argument (X) ---------> ["A is for","A"]
K - join with spaces --------------> "A is for A"
; - concatenate with Y (e.g. "n") -> "A is for An"
”t - literal character = "t"
; - concatenate -------------------> "A is for Ant"
```
---
### Previous, 46
```
“¤ṪŻIð^ƥ’b4ị⁾sap⁾pt¤ØAż,@K¥€“ẉbẊWS»ØAżYF”e272¦
```
Words all have second letter "s" or "a" and last letter "p" or "t" using a base four lookup in a Cartesian product of "sa" and "pt". **Except** the "U" word, which the code changes to "Use" (using the relatively bulky `F”e272¦` on the end) - if I could find a word list like this that does not have such an exception we'd be looking at **39 bytes**.
Word list:
```
Asp, Bat, Cat, Dap, Eat, Fat, Gap, Hat, Ist, Jat, Kat, Lap, Mat, Nap, Oat, Pat, Qat, Rat, Sat, Tap, Use, Vat, Wat, Xat, Yap, Zap
```
[try this one](https://tio.run/nexus/jelly#@/@oYc6hJQ93rjq62/PwhrhjSx81zEwyebi7@1HjvuLEAiBZUHJoyeEZjkf36Dh4H1r6qGkNUMfDXZ1JD3d1hQcf2g2WinR71DA31cjc6NCy////AwA)
---
[Answer]
# [Retina](https://github.com/m-ender/retina), ~~89~~ 87 bytes
*Saved 2 bytes thanks to Martin Ender*
```
ApBaCaDoEaFaGeHaIkaJeKiLeMeNeOpPeQaRaSaTiUniVaWeXysYurZi
[A-Z]
¶$& is for $&
^¶
m`$
t
```
[Try it online!](https://tio.run/nexus/retina#@8/lWOCU6Jzoku@a6JbonuqR6Jmd6JXqnemT6pvql@pfEJAamBiUGJwYkhmalxmWGJ4aUVkcWVoUlckV7agbFct1aJuKmkJmsUJafpGCihpX3KFtXFy5CSpcJf//AwA "Retina – TIO Nexus")
I picked a word for each letter that ends in `t` (some are pretty obscure).
**Explanation**
```
ApBaCaDoEaFaGeHaIkaJeKiLeMeNeOpPeQaRaSaTiUniVaWeXysYurZi
```
Replace the non-existent (empty) input with the text above.
```
[A-Z]
¶$& is for $&
```
Replace each capital letter with `(newline)(itself) is for (itself)`. This results in the text above being split into separate lines like
```
A is for Ap
B is for Ba
C is for Ca
```
... and so on
```
^¶
```
However, since the newline was placed *before* each capital, there is a leading newline that must be removed. It is removed in this stage.
```
m`$
t
```
Put a `t` at the end of every line, since every word used in the song ends in `t`.
[Answer]
## [Retina](https://github.com/m-ender/retina), ~~92~~ 88 bytes
*Saved 4 bytes by borrowing an idea from [Business Cat's answer](https://codegolf.stackexchange.com/a/109516/8478).*
Byte count assumes ISO 8859-1 encoding.
```
AddBCDEelFGHItsJetKitLMNetOilPQatRSTUrnVatWXisYesZit
[A-Z]
¶$& is for $&
m` .$
$&ad
G`.
```
[Try it online!](https://tio.run/nexus/retina#@8/lmJLi5Ozimprj5u7hWVLslVrinVni4@uXWuKfmRMQmFgSFBwSWpQXllgSHpFZHJlaHJVZwhXtqBsVy3Vom4qaQmaxQlp@kYKKGldugoKeCpeKWmIKl3uC3v//AA "Retina – TIO Nexus")
Based on [AdmBorkBork's](https://codegolf.stackexchange.com/a/109503/8478) word list, but I've changed a few more words into ones that end in `ad` to save more bytes on the common suffix.
### Explanation
```
AddBCDEelFGHItsJetKitLMNetOilPQatRSTUrnVatWXisYesZit
```
Turn the empty (non-existent) input into this string. It contains all the letters as well as the rest of those words which *don't* end in `ad`.
```
[A-Z]
¶$& is for $&
```
Insert a linefeed before each upper case letter and then turn it into `X is for X`.
```
m` .$
$&ad
```
Match the letters which are now by themselves and append `ad` to complete the shortened words.
```
G`.
```
Discard the empty line that was created by inserting a linefeed before `A`.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~45~~ ~~42~~ ~~39~~ ~~38~~ ~~37~~ 36 bytes
```
Au'Æå•à¡P°€kš¦zᮕSè)øvy¬“ÿ€ˆ€‡ ÿt“,
```
[Try it online!](https://tio.run/nexus/05ab1e#@@9Yqn647fDSRw2LDi84tDDg0IZHTWuyjy48tKzq8MJD64DCwYdXaB7eUVZ5aM2jhjmH9wOlT7cBiUcNCxUO7y8Biun8//81L183OTE5IxUA)
**Explanation**
`Au` pushes the uppercase alphabet.
`'Æå` pushes the word `scenario`.
`•à¡P°€kš¦zᮕ` pushes the base-10 number `36774474076746444766322426`.
`Sè` uses those digits to index into `scenario`.
`)ø` zips those strings together into the list `[An, Bi, Co, ..., Zi]`
```
v # for each element in the list
y # push it
¬ # push it's first letter
“ÿ€ˆ€‡ ÿt“ # push the string "ÿ is for ÿt"
# replacing ÿ with with the top element of the stack
, # print with newline
```
Words used: `['Ant', 'Bit', 'Cot', 'Dot', 'Eat', 'Fat', 'Got', 'Hat', 'Ist', 'Jot', 'Kit', 'Lot', 'Mat', 'Nit', 'Oat', 'Pat', 'Qat', 'Rot', 'Sit', 'Tit', 'Unt', 'Vet', 'Wet', 'Xat', 'Yet', 'Zit']`
**33 byte version using some words I'm unsure about**
```
Au'†Ž•4Ãðzòç•3BSè)øvy¬“ÿ€ˆ€‡ ÿt“,
```
Words: `['Ant', 'Bat', 'Cat', 'Dat', 'Eat', 'Fat', 'Gat', 'Hat', 'Ist', 'Jat', 'Kat', 'Lat', 'Mat', 'Nat', 'Oat', 'Pat', 'Qat', 'Rat', 'Sat', 'Tat', 'Ust', 'Vat', 'Wat', 'Xat', 'Yat', 'Zat']`
[Answer]
# PHP, ~~122~~ ~~124~~ ~~127~~ ~~120~~ ~~115~~ 101 bytes
Follows the "standard" `<letter><filler>t` structure.
I tried to come up with words that weren't used before by anyone.
If you see a word that you want me to replace, tell me.
```
foreach(range(A,Z)as$k=>$c)echo"$c is for $c",ceaoaaei0eieeouoaaei0eeaei[$k]?:[I=>ka,U=>ni][$c],"t\n";
```
The newline is represented as `\n` but counted as 1 byte.
---
**Output:**
```
A is for Act
B is for Bet
C is for Cat
D is for Dot
E is for Eat
F is for Fat
G is for Get
H is for Hit
I is for Ikat
J is for Jet
K is for Kit
L is for Let
M is for Met
N is for Not
O is for Out
P is for Pot
Q is for Qat
R is for Rat
S is for Set
T is for Tit
U is for Unit
V is for Vet
W is for Wet
X is for Xat
Y is for Yet
Z is for Zit
```
---
**Weird words:**
* [ikat](https://en.wikipedia.org/wiki/Ikat):
>
> Ikat, or ikkat, is a dyeing technique used to pattern textiles that employs resist dyeing on the yarns prior to dyeing and weaving the fabric.
>
>
>
* [xat](https://www.merriam-webster.com/dictionary/xat):
>
> A carved pole erected as a memorial to the dead by some Indians of western North America
>
>
>
* [zit](http://www.dictionary.com/browse/zits):
>
> a pimple; skin blemish.
>
>
>
* [qat](https://en.wikipedia.org/wiki/Khat):
>
> Catha edulis (khat, qat) is a flowering plant native to the Horn of Africa and the Arabian Peninsula.
>
>
>
[Answer]
## Pyke, ~~55~~ ~~51~~ 48 bytes
```
26.f[1R].C".d"R+E)DGjt@.^.Il 6>( F['h .dRdJl5
```
[Try it here!](http://pyke.catbus.co.uk/?code=26.f%5B1R%5D.C%22.d%22R%2BE%29DGjt%40.%5E.Il+2%3E%28+F%5B%27h+.d%02%07%06RdJl5)
Link is for 3 length and doesn't qualify as words include conjunctives.
```
[1R].C".d"R+E) - def function [i):
1R] - [1, i]
.C - chr(^)
".d"R+ - ".d"+ ^
E - eval(^) (dictionary lookup of length 1)
- gets the `i`th word in the dictionary
26.f[ DGjt@.^.Il 6>( - first_26():
[ - function(i)
.^ - ^.startswith(v)
Gjt@ - alphabet[current_iter-1]
.Il 6> - if ^:
l 6> - len(function(i)) > 6
F['h .dRdJl5 - for i in ^:
['h - function(i)[0], function(i)
.d - "is for" (unprintables 0x02, 0x07, 0x06)
R - rotate(^, ^^)
dJ - " ".join(^)
l5 - ^.capitalize()
```
Outputs:
```
A is for available
B is for because
C is for community
D is for download
E is for english
F is for features
G is for getting
H is for hardware
I is for increase
J is for jewelry
K is for kitchen
L is for locations
M is for manufacturer
N is for northern
O is for outdoor
P is for protein
Q is for quickly
R is for religion
S is for surgery
T is for thousands
U is for universal
V is for vehicles
W is for weekend
X is for xenical
Y is for youngest
Z is for zoofilia
```
You can test this outside of Pyke using same algorithm. Requires [dictionary.json](https://github.com/muddyfish/PYKE/blob/master/dictionary.json).
```
import json, string
with open("dictionary.json") as f_obj:
words=json.load(f_obj)
rtn=[]
i=0
while len(rtn) != 26:
cur_word=words[i]
if cur_word[0]==string.lowercase[len(rtn)]:
if len(cur_word) > 6:
rtn.append(cur_word)
i += 1
for i in rtn:
print("{} is for {}".format(i[0].upper(), i))
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~52~~ 50 bytes
*Collaborated with @ETHproductions*
```
;B£[R` f `Od"¥¥º"gY]qXÃx
```
Contains many unprintables. [Test it online!](http://ethproductions.github.io/japt/?v=1.4.4&code=O0KjW1JgIIkgZo4gYE9kIqWHhISHhIaGpYeKgoSKh4SFhYWEuoWHiYOKImdZXXFYw3g=&input=)
The word list is:
```
All Bar Can Dan Ear Fan Gas Has Ill Jar Kit Led Man Nit Oar Pan Qat Rat Sat Tan Udo Vat War Xis Yes Zit
```
Japt uses the [shoco string compression library](http://ed-von-schleck.github.io/shoco/), which reduces common runs of lowercase letters into by a byte. Here is a full list of all two-letter runs that are condensed into one byte:
```
an,ar,as,at,be,bl,bo,bu,ca,ce,ch,co,da,de,di,do,ed,en,er,es,ha,he,hi,ho,im,in,is,it,le,li,ll,ly,ma,me,mi,mo,nd,ne,ng,nt,of,on,or,ou,ra,re,ri,ro,se,sh,si,st,te,th,ti,to,ul,ur,us,ut,wa,we,wh,wi
```
So the idea is to form a word with one of these pairs for each letter of the alphabet.
```
;B£ [R` f ` Od"string"gY]qXÃ x
;BmXY{[R" is for "Od"string"gY]qX} x
; // Among other things, set B to "ABC...XYZ".
B // Split B into chars.
mXY{ } // Map each item X and index Y to the following:
"string"gY // Take the char at index Y in the compressed str.
Od // Decompress.
[R" is for " ] // Put this in an array with a newline and " is for ".
qX // Join on X, giving "\n{X} is for {word}".
x // Trim. This removes the leading newline.
// Implicit: output result of last expression
```
One interesting thing to note is that while Japt can implicitly decompress a string wrapped in backticks, that's actually a byte longer here because you'd have to grab *two* chars in the decompressed string, rather than one.
[Answer]
## Ruby, ~~93 84 69 63 58~~ 62 bytes
```
?A.upto(?Z){|l|puts l+" is for #{"AnDoIsUn"[/#{l}./]||l+?a}t"}
```
**Output:**
```
A is for Ant
B is for Bat
C is for Cat
D is for Dot
E is for Eat
F is for Fat
G is for Gat
H is for Hat
I is for Ist
J is for Jat
K is for Kat
L is for Lat
M is for Mat
N is for Nat
O is for Oat
P is for Pat
Q is for Qat
R is for Rat
S is for Sat
T is for Tat
U is for Unt
V is for Vat
W is for Wat
X is for Xat
Y is for Yat
Z is for Zat
```
All 3-letter words ending with 't', most of them with 'at'.
## Using controversial words (iat, dat, amp. ump) - 55 bytes:
```
?A.upto(?Z){|l|puts l+" is for "+l+("AU"[l]?"mp":"at")}
```
Still trying to find a pattern, I think it's possible to use just 2 different endings, and simplify everything.
Thanks @Value Ink and @Business cat for helping.
[Answer]
## ///, 163 bytes
```
/2/ad//1/ is for /A1Add
B1B2
C1C2
D1D2
E1Eat
F1F2
G1Goo
H1H2
I1Irk
J1Job
K1Kob
L1L2
M1M2
N1Nob
O1Owl
P1P2
Q1Qat
R1R2
S1S2
T1T2
U1Use
V1Vat
W1W2
X1X-ray
Y1Yob
Z1Zoo
```
[Try it online](https://tio.run/nexus/slashes#DcvJCoIAFIXh/XkKXyAu594n0EpzaHAedoYGUSBoED29ufnhW/yrqPSDiEn/EaE4z8V5TLMjLt1hgEfPsOfecOBBceTR4NNXBAwMJ54MIcP5hYjRdEfMeGvCRHHmWXHhZfOV1@8bN94UKVNDxkyRM1cULBQly2VExcpQs1Y0bHZz/0PLdps7duPyWdc/)
>
> Yob - n. - A cruel and brutal fellow
>
>
>
Hm, learned something today...
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~72~~ 68 bytes
### Code:
```
”–³æéÁéî¹àæÑå꧵™Ä‚æ†Í„΢׆™ƒÛÌ´ŸÄ«©‡¯†‚IJ‚Ò„©É€ŠÛì„”#vy¬…ÿ€ˆ€‡ð«ì,
```
Uses the **CP-1252** encoding. [Try it online!](https://tio.run/nexus/05ab1e#FY1LCsJAEEQP49bzCe7GMAiCCsaFoChjwJExQcUP6EqoIm68RV9krCz686h@dDa3NbfEnZGJI9UZbwbRggeeWOCIp/mK3tya0VzgzNyOc1RciRR9S244xaN90aNGMrfHpYskeNy6UUpB4sSKpg26bsR63BsMoTXyo@A3VpPLK2o2/Zz/ "05AB1E – TIO Nexus")
### Explanation
The following code:
```
”–³æéÁéî¹àæÑå꧵™Ä‚æ†Í„΢׆™ƒÛÌ´ŸÄ«©‡¯†‚IJ‚Ò„©É€ŠÛì„”#
```
pushes this array:
```
['Apple', 'Banana', 'Carol', 'Door', 'Elephant', 'Frog', 'Goat', 'Hat', 'Ice', 'January', 'Key', 'Love', 'Mom', 'Never', 'Open', 'Paste', 'Queen', 'Rice', 'Star', 'Test', 'Underwear', 'Very', 'Water', 'Xanax', 'Yellow', 'Zoloft']
```
And is processed using the following code:
```
vy¬…ÿ€ˆ€‡ð«ì,
vy # For each string in the array
¬ # Get the first letter of that string
…ÿ€ˆ€‡ # Push the string "ÿ is for" where 'ÿ' is the first letter of the string
ð« # Append a space character
ì # Prepend this string to the current string from the array
, # Print with a newline
```
[Answer]
# Clojure, ~~159~~ 232 bytes
Well, now it's certainly non-competing solution as it would be far easier to hardcode the words used. Putting it out there just for the sake of having *correct* answer (and not using others' list of words).
```
(mapv #(println(str(char %)" is for"(first(re-seq(re-pattern(str" "(char(+ % 32))"+\\w{3,} "))
(reduce(fn[a b](str a(with-out-str(load-string(str "(doc "b")")))))" xyst "(map str(keys(ns-publics 'clojure.core))))))))(range 65 91))
```
Basically still gets all the functions defined in `clojure.core` namespace, but after that evaluates `doc <function name>` and puts it into string. After that concatenates it into one huge string (with the word `xyst`) and finds appropriate words from there. Should be run in Clojure REPL.
Output:
```
A is for arbitrary
B is for being
C is for changes
D is for determined
E is for exception
F is for failed
G is for given
H is for held
I is for items
J is for java
K is for keys
L is for lazy
M is for must
N is for notified
O is for option
P is for performed
Q is for queued
R is for returns
S is for state
T is for true
U is for uses
V is for validator
W is for were
X is for xyst
Y is for yields
Z is for zero
```
Old solution:
```
(mapv #(println(str(char %)" is for "(some(fn[a](and(=(.charAt a 0)(char(+ % 32)))a))(conj(map str(keys(ns-publics 'clojure.core)))"orb""yes"))))(range 65 91))
```
[Answer]
# JavaScript (ES6), 82 bytes
```
_=>btoa`pb
è¡Záî"Âh*"è1£b:ãÚA¤hJ$âRu^YåÚaæb`.replace(/(.)./g,`$1 is for $&t
`)
```
An anonymous function returning a string. Contains unprintables; here's a version that doesn't:
```
_=>btoa`\x02pb
\x80è\x11¡Z\x18áî"Âh*"è1£b:ãÚA¤hJ$âRu^YåÚaæb`.replace(/(.)./g,`$1 is for $&t
`)
```
This uses @JonathanAllen's technique, using only three-letter words that end in `t`. The string decompresses to `AnBiCoDoEaFaGOHuIsJoKiLoMaNiOuPaQaRoSiTiUnVeWeXaYeZi`.
I tried chaining two-letter pairs like so:
```
Ace
Bee
Cee
Dew
Ewe
...
```
I've now made it all the way to `X` but got stuck on `Y`; as far as I can tell, the only attainable three-letter `X` word is `Xis`, and there's no three-letter word starting with `Ys`.
For the record, the full string was `ceeeweeereueaebiueeiziais`...
[Answer]
# [SOGL 0.8.1](https://github.com/dzaima/SOGL), ~~60~~ 32 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md)
```
χ3½⌠↓-ζ⁄∞Nη6′⁵‘Z{t",t5~r‘ooKo to
```
Explanation:
```
χ3½⌠↓-ζ⁄∞Nη6′⁵‘ push "niooaaoasoioaiaaaoiineeaei"
Z{ for each letter of the uppercase alphabet
t output the letter in a newline (and disable implicit output)
",t5~r‘o append " is for "
o append the letter
Ko append the 1st letter of the 1st string (the 2nd letters) and remove it
to append "t"
```
This is pretty much [Jonathan Allan's answer](https://codegolf.stackexchange.com/a/109519/59183), but ported to this language.
Old version: (SOGL 0.8.2)
```
Z"sηΒ…@Ν┘$JP6*š∙╬F▓÷Σ⁷4⌠ ⁹{Tīο⁾α⅝½Χ<▼½Ξμ‚‘θ’»∫wGKO",t5~r‘P≥o
Z push the uppercase alphabet
"sηΒ…@Ν┘$JP6*š∙╬F▓÷Σ⁷4⌠ ⁹{Tīο⁾α⅝½Χ<▼½Ξμ‚‘ push the 27 words separated by spaces using the languages english compression (BCD...XYZA)
θ split on spaces
’»∫ repeat 27 times (push 0-based pointer)
w get the 1-indexed item of the array (so 0 = last, 1 = first, 2 = 2nd,...)
G put the 1st thing on stack ontop (the alphabet)
K get the 1st letter and remove it
O output it
",t5~r‘ push compressed " is for "
P append that (and disable last auto-output)
≥ put the 1st thing on the stack below everything
o append the last thing (the word from the word list)
```
output:
```
A is for against
B is for being
C is for could
D is for down
E is for even
F is for first
G is for good
H is for had
I is for into
J is for just
K is for know
L is for little
M is for much
N is for nothing
O is for other
P is for project
Q is for quite
R is for right
S is for said
T is for their
U is for under
V is for very
W is for with
X is for xavier
Y is for you
Z is for zoo
```
This is not the shortest this language can do, but should be the best with the words hard coded.
[Answer]
# Mathematica, 97 bytes
```
a@c_:={ToUpperCase@c," is for ",Select[WordList[],#~StringTake~1==c&][[3]],"
"};a/@Alphabet[]<>""
```
Looks in Mathematica's `WordList` for the third word beginning with each letter; this avoids one-letter words and interjections. Has a trailng newline.
```
A is for aardvark
B is for babble
C is for cabala
D is for dabbled
E is for eagerly
F is for fable
G is for gabble
H is for haberdashery
I is for iambus
J is for jabberer
K is for kaleidoscope
L is for label
M is for mac
N is for nacelle
O is for oak
P is for pabulum
Q is for quackery
R is for rabbinate
S is for sable
T is for tabbouleh
U is for udder
V is for vacant
W is for wad
X is for xenophobic
Y is for yachting
Z is for zapper
```
[Answer]
## Groovy, 76 73 bytes
(edited from 76 to 73 bytes, thank you cat)
Inspired by the ruby solution:
```
('A'..'Z').any{i->println"$i is for ${'AntIvyUse'.find(/$i../)?:i+'at'}"}
```
we use `any` instead of each as it is shorter and all the println statements return false. For the special cases in the string, we use String.find which in groovy returns the match or null. On null we use the elvis operator `?:` to return a word ending in `at` instead.
Prints out:
```
A is for Ant
B is for Bat
C is for Cat
D is for Dat
E is for Eat
F is for Fat
G is for Gat
H is for Hat
I is for Ivy
J is for Jat
K is for Kat
L is for Lat
M is for Mat
N is for Nat
O is for Oat
P is for Pat
Q is for Qat
R is for Rat
S is for Sat
T is for Tat
U is for Use
V is for Vat
W is for Wat
X is for Xat
Y is for Yat
Z is for Zat
```
## Groovy, recursion, 74 bytes
```
{i->println"$i is for ${'AntIvyUse'.find(/$i../)?:i+'at'}";call(++i)}('A')
```
prints out the text from the first answer and then throws a PatternFormatException. We call the closure recursively starting with 'A' and incrementing `++char` until the character after `Z` throws the error.
## Groovy, by cheating, 77 bytes
With the risk of being lynched:
```
print 'http://codegolf.stackexchange.com/q/109502'.toURL().text[21796..22189]
```
i.e. read the data in this page and print out the definition of a valid answer at the beginning. In my defense...it does print out the requested answer...now nobody edit the page...
## Groovy, using 'times', 81 bytes
Building on the python answer with the three letter word pattern:
```
26.times{i,c=i+65->printf"%c is for %c${'niooaauusoioaiuaaoiineeaei'[i]}t\n",c,c}
```
prints:
```
A is for Ant
B is for Bit
C is for Cot
D is for Dot
E is for Eat
F is for Fat
G is for Gut
H is for Hut
I is for Ist
J is for Jot
K is for Kit
L is for Lot
M is for Mat
N is for Nit
O is for Out
P is for Pat
Q is for Qat
R is for Rot
S is for Sit
T is for Tit
U is for Unt
V is for Vet
W is for Wet
X is for Xat
Y is for Yet
Z is for Zit
```
## Groovy, by recursing on main(...), 83 bytes
Assuming we count newlines as one character.
```
i=args?args[0]:'A'
println"$i is for ${'AntIvyUse'.find(/$i../)?:i+'at'}"
main(++i)
```
prints out the text from the first answer and then throws a PatternSyntaxException.
## Groovy, using eachWithIndex, 88 bytes
```
'niooaauusoioaiuaaoiineeaei'.eachWithIndex{c,i->char x=i+65;println "$x is for $x${c}t"}
```
## Groovy, using transpose, 102 bytes
```
['A'..'Z','niooaauusoioaiuaaoiineeaei'as List].transpose().each{println it[0]+" is for ${it.join()}t"}
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 77 bytes
```
•‹T1qA‹rËöf#ùqÈ$>M©ÈñM£r°§°Ü]€¡3¸/©#bÍ'ò7DÉø½D—¹û©˜Òו36B3ôvy™¬"ÿ is for ÿ"}»
```
[Try it online!](https://tio.run/nexus/05ab1e#AYYAef//4oCi4oC5VDFxQeKAuXLDi8O2ZiPDuXHDiCQ@TcKpw4jDsU3Co3LCsMKnwrDDnF3igqzCoTPCuC/CqSNiw40nw7I3RMOJw7jCvUTigJTCucO7wqnLnMOSw5figKIzNkIzw7R2eeKEosKsIsO/IGlzIGZvciDDvyJ9wrv///Vuby1jYWNoZQ "05AB1E – TIO Nexus")
Uses the following string compressed:
ASSBINCATDOTEATFATGOTHATILLJOTKITLOTMETNOTOATPATQUEROTSETTITUSEVATWETXISYIPZAP
Converted to Base-214:
```
‹T1qA‹rËöf#ùqÈ$>M©ÈñM£r°§°Ü]€¡3¸/©#bÍ'ò7DÉø½D—¹û©˜Ò×
```
---
Used a list of 3-letter scrabble words: <http://wordfinder.yourdictionary.com/letter-words/3>
Output is as follows:
```
A is for Ass
B is for Bin
C is for Cat
D is for Dot
E is for Eat
F is for Fat
G is for Got
H is for Hat
I is for Ill
J is for Jot
K is for Kit
L is for Lot
M is for Met
N is for Not
O is for Oat
P is for Pat
Q is for Que
R is for Rot
S is for Set
T is for Tit
U is for Use
V is for Vat
W is for Wet
X is for Xis
Y is for Yip
Z is for Zap
```
Had a 70 byte version, but 2-letter words aren't allowed.
---
Explained:
```
•‹T1qA‹rËöf#ùqÈ$>M©ÈñM£r°§°Ü]€¡3¸/©#bÍ'ò7DÉø½D—¹û©˜Òו # Compressed String
36B3ô # Decompress, split into 3s.
v } # For each word...
y™¬"ÿ is for ÿ" # Take first letter of word, interpolate.
» # Print with newlines.
```
[Answer]
# SmileBASIC, ~~131~~ ~~113~~ ~~82~~ 81 bytes
```
FOR I=1TO 26L$=CHR$(I+64)?L$;" is for ";L$;@niooaauusoioaiuaaoiineeaei[I];"t
NEXT
```
Now using words that in `t`
[Answer]
## [Lithp](https://github.com/andrakis/node-lithp), 136 125 117 bytes
```
((import lists)(each(split "niooaauusoioaiuaaoiineeaei" "")
#X,C::((print(chr(+ 65 C))"is for"(+(chr(+ 65 C))X "t"))))
```
(Split for readability)
[Try it online!](https://andrakis.github.io/ide2/?code=KAogICUgUG9ydCBvZiB0aGUgUHl0aG9uIGFuc3dlcjoKICAlICBjPTY1CiAgJSAgZm9yIHggaW4nbmlvb2FhdXVzb2lvYWl1YWFvaWluZWVhZWknOnByaW50JyVjIGlzIGZvciAlYyVzdCclKGMsYyx4KTtjKz0xCiAgCiAgJSBnb2xmZWQ6CiAgJSAoKGltcG9ydCBsaXN0cykodmFyIEMgNjUpKGVhY2goc3BsaXQgIm5pb29hYXV1c29pb2FpdWFhb2lpbmVlYWVpIiAiIikoc2NvcGUgI1g6OigocHJpbnQoY2hyIEMpImlzIGZvciIoKyhjaHIgQylYICJ0IikpKHNldCBDKCsgMSBDKSkpKSkpCiAgJSAoKGltcG9ydCBsaXN0cykoZWFjaChzcGxpdCAibmlvb2FhdXVzb2lvYWl1YWFvaWluZWVhZWkiICIiKShzY29wZSAjWCxDOjooKHByaW50KGNocigrIDY1IEMpKSJpcyBmb3IiKCsoY2hyKCsgNjUgQykpWCAidCIpKSkpKQoKICAlIHJlYWRhYmxlCiAgKGltcG9ydCBsaXN0cykKICAoZWFjaCAoc3BsaXQgIm5pb29hYXV1c29pb2FpdWFhb2lpbmVlYWVpIiAiIikgKHNjb3BlICNYLEMgOjogKAogICAgKHByaW50IChjaHIgKCsgNjUgQykpICJpcyBmb3IiICgrIChjaHIgKCsgNjUgQykpIFggInQiKSkKICApKSkKKQ==)
This is pretty much a port of the Python answer
* Saved 11 bytes by using `each`'s index
* Saved 8 bytes by removing useless call to `(scope #)`
**Output:**
```
A is for Ant
B is for Bit
C is for Cot
D is for Dot
E is for Eat
F is for Fat
G is for Gut
H is for Hut
I is for Ist
J is for Jot
K is for Kit
L is for Lot
M is for Mat
N is for Nit
O is for Out
P is for Pat
Q is for Qat
R is for Rot
S is for Sit
T is for Tit
U is for Unt
V is for Vet
W is for Wet
X is for Xat
Y is for Yet
Z is for Zit
```
[Answer]
# [Perl 5](https://www.perl.org/), 72 bytes
```
say"$_ is for $_",(niooaaoasoioaiaaaoiineeaei=~/./g)[-65+ord],t for A..Z
```
[Try it online!](https://tio.run/##K0gtyjH9/784sVJJJV4hs1ghLb9IQSVeSUcjLzM/PzExP7E4PzM/MTMRyMzMzEtNTUzNtK3T19NP14zWNTPVzi9KidUpAety1NOL@v//X35BSWZ@XvF/XV9TPQNDAwA "Perl 5 – Try It Online")
[Answer]
## Batch, 250 bytes
```
@set s=ABCDEFGHIJKLMNOPQRSTUVWXYZ
@for %%w in (eon dellium zar jinn lbow hon nat our rk unta not lama nemonic domo uija sycho uay ye ee sunami rn ex rap enophobe ou ugzwang)do @call:c %%w
@exit/b
:c
@echo %s:~0,1% is for %s:~0,1%%1
@set s=%s:~1%
```
Since I was never going to get a decent score, I went for the shortest *humorous* words that I could find:
```
A is for Aeon
B is for Bdellium
C is for Czar
D is for Djinn
E is for Elbow
F is for Fhon
G is for Gnat
H is for Hour
I is for Irk
J is for Junta
K is for Knot
L is for Llama
M is for Mnemonic
N is for Ndomo
O is for Ouija
P is for Psycho
Q is for Quay
R is for Rye
S is for See
T is for Tsunami
U is for Urn
V is for Vex
W is for Wrap
X is for Xenophobe
Y is for You
Z is for Zugzwang
```
[Answer]
# [stacked](https://github.com/ConorOBrien-Foxx/stacked), 72 bytes
There are *two* for 72 bytes!
```
65@i$'niooaauusoioaiuaaoiineeaei'{!i#::' is for '+\n+'t'+ +out i 1+@i}"!
{!n#::' is for '+\'niooaauusoioaiuaaoiineeaei'n 65-#+'t'+ +out}65 90 for
```
[Try it online!](https://tio.run/nexus/stacked#BcEhDoAwDAXQq3RAUlGFADG1g2AqRvLNfsJWRTj7eG@eR8GmDaR7RCfoCHcCrVav0DdhzVkFXW4@onY106EmxhgC2a3gW9KcPw "stacked – TIO Nexus") Using that awesome pattern. (Before you ask, `++` would be a single token, so `+ +` is used instead.)
Both work by iterating from `65` to `90` and getting the correct character sequence. Notes:
* `#:` is an alias for `chr`
* `#` is an alias for `get`
* `{!...}` is the same as `{ n : ... }` (lambda with `n` as an parameter)
For 73 bytes:
```
'niooaauusoioaiuaaoiineeaei'toarr{e i:65 i+#::' is for '+\e+'t'+ +out}map
```
[Answer]
## Mathematica 93 Bytes
```
ToUpperCase@#<>" is for "<>Cases[WordList[],s_/; s~StringPart~1==#][[9]]&/@Alphabet[]//Column
```
yields
```
A is for abandoned
B is for babushka
C is for cabin
D is for dactylic
E is for eardrum
F is for fabricator
G is for gadabout
H is for habitation
I is for ice
J is for jackal
K is for kappa
L is for laboratory
M is for macaroni
N is for nagger
O is for oarsman
P is for pachysandra
Q is for quadratic
R is for rabidness
S is for saccharin
T is for tableland
U is for ulcer
V is for vacationist
W is for wadi
X is for xylene
Y is for yammer
Z is for zebra
```
[Answer]
# Groovy, 72 bytes
```
c=65;"niooaauusoioaiuaaoiineeaei".any{printf"%c is for %<c%st\n",c++,it}
```
**Output**
```
A is for Ant
B is for Bit
C is for Cot
D is for Dot
E is for Eat
F is for Fat
G is for Gut
H is for Hut
I is for Ist
J is for Jot
K is for Kit
L is for Lot
M is for Mat
N is for Nit
O is for Out
P is for Pat
Q is for Qat
R is for Rot
S is for Sit
T is for Tit
U is for Unt
V is for Vet
W is for Wet
X is for Xat
Y is for Yet
Z is for Zit
```
[Answer]
# Python 3, ~~145~~ ~~137~~ 135 bytes
I sacrificed some bytes to pseudo-randomise the output with each run. The idea is to look for lowercase words of at least 3 characters in `/usr/share/dict/words` and then pick one from that list using `id([x])%99`.
```
import re
for x in range(65,91):print("%c is for "%x+re.findall("\n(%c.{3,})"%(x+32),open('/usr/share/dict/words').read())[id([x])%99])
```
Edits
* Removed `title()` as words don't have to be capitalised.
* Changed the regex to `"\n(%c.{3,})"` (+ 3 bytes) to allow removal of `,re.M` (- 5 bytes).
Example output:
```
A is for abacinate
B is for bacchantic
C is for caback
D is for dactylosternal
E is for eagless
F is for factful
G is for gabbroic
H is for hackneyed
I is for iambize
J is for jacutinga
K is for kadaya
L is for labra
M is for macaco
N is for nailwort
O is for oakenshaw
P is for pachysomia
Q is for quachil
R is for racer
S is for sabbath
T is for tabulable
U is for ubication
V is for vagabondism
W is for wabe
X is for xenobiosis
Y is for yacca
Z is for zeed
```
[Answer]
## GNU sed, 81 + 1(r flag) = 82 bytes
This is a sed implementation of the word list from Jonathan Allan's [answer](https://codegolf.stackexchange.com/a/109519/42963).
```
s:$:AnBiCoDoEaFaGuHuIsJoKiLoMaNiOuPaQaRoSiTiUnVeWeXaYeZi:
s:(.).:\1 is for &t\n:g
```
The words, except the shared ending letter `t`, are given in concatenated form on line 1, and then printed in the requested format by line 2. A trailing newline is present.
**Run**:
```
sed -rf alphabet_song.sed <<< ""
```
[Answer]
# Java 7, ~~124~~ 121 bytes
```
String c(){String r="";for(char c=65;c<91;r+=c+" is for "+c+"baaonaiineioaeaoaaeileeaoi".charAt(c++-65)+"t\n");return r;}
```
[Based on *@JonathanAllen*'s answer](https://codegolf.stackexchange.com/a/109530/52210), since Java has no fancy built-in dictionary. ;) I tried to find another ending letter for the entire alphabet (like `s` or `n` or `y`), or a middle letter (like `a` or `e`), but most were missing just one or two words, so I ended up using `t` as well. Words are manually chosen from [wordhippo.com](http://www.wordhippo.com/what-is/ending-with/3-letter-words-t.html).
**Ungolfed:**
[Try it here.](https://ideone.com/ys2qs4)
```
class M{
static String c(){String r="";for(char c=65;c<91;r+=c+" is for "+c+"baaonaiineioaeaoaaeileeaoi".charAt(c++-65)+"t\n");return r;}
public static void main(String[] a){
System.out.println(c());
}
}
```
**Output:**
```
A is for Abt
B is for Bat
C is for Cat
D is for Dot
E is for Ent
F is for Fat
G is for Git
H is for Hit
I is for Int
J is for Jet
K is for Kit
L is for Lot
M is for Mat
N is for Net
O is for Oat
P is for Pot
Q is for Qat
R is for Rat
S is for Set
T is for Tit
U is for Ult
V is for Vet
W is for Wet
X is for Xat
Y is for Yot
Z is for Zit
```
] |
[Question]
[
A [Narcissistic Number](https://en.wikipedia.org/wiki/Narcissistic_number) is a number which is the sum of its own digits, each raised to the power of the number of digits.
For example, take \$153\$ (3 digits):
>
> \$1^3 + 5^3 + 3^3 = 153\$
>
>
>
\$1634\$:
>
> \$1^4 + 6^4 + 3^4 + 4^4 = 1634 = 1 + 1296 + 81 + 256 = 1634\$
>
>
>
**The Challenge:**
Your code must take input from the user and output True or False depending upon whether the given number is a Narcissistic Number.
Error checking for text strings or other invalid inputs is not required. 1 or 0 for the output is acceptable. Code that simply generates a list of Narcissistic Numbers, or checks the user input against a hardcoded list, does not qualify.
[**OEIS A005188**](https://oeis.org/A005188)
[Answer]
## APL (15)
```
∆≡⍕+/(⍎¨∆)*⍴∆←⍞
```
Outputs `1` if true and `0` if false.
Explanation:
* `∆←⍞`: read a line (as characters), store in `∆`
* `(⍎¨∆)*⍴∆`: evaluate each character in `∆` and raise it to the power `⍴∆`
* `∆≡⍕+/`: see if the input equals the string representation of the sum of these
[Answer]
### GolfScript, 16 characters
```
~.`:s{48-s,?-}/!
```
Input must be given on STDIN, output is 0 or 1 indicating non-narcissistic / narcissistic number.
Explanation of the code:
```
~ # Evaluate the input to get a number
. # Accumulator (initially the number itself)
`:s # Convert number to string and assign to variable s
{ # Loop over characters of the string
48- # Reduce character value by 48
s, # Push length of input number
? # Power
- # Subtract result from accumulator
}/
! # Not! (i.e. iff accumulator was zero it was a narcissistic number)
```
[Answer]
# Mathematica, 43 chars
```
Tr[#^Length@#&@IntegerDigits@#]==#&@Input[]
```
[Answer]
## Perl, 38 characters
```
perl -lpe '$@=y///c;$s+=$_**$@for/./g;$_=$_==$s'
```
A pretty straightforward implementation.
Here's a slightly different version that fits in 35 characters:
```
perl -lpe '$@=y///c;$s+=$_**$@for/./g;$_-=$s'
```
This version outputs a *false* value if the input is narcissistic, otherwise it outputs a (Perl-accepted) true value. One might argue that this backwards version falls within the limits of the challenge description, but upon reflection I decided not to. I'm not that desperate to improve my score. Yet.
[Answer]
# J, 23 chars
```
(".=+/@("."0^#))(1!:1)1
```
`(1!:1)1` is keyboard input (returning a string).
`".` converts input to a number; `"0` specifies a rank (dimension) of 0, in other words, taking each character and converting it to a number.
`^` is the power function and `#` is the length function, thus taking each digit to the power of the length of the string (equivalently, the number of digits).
`+/` is just sum, and `=` is comparing the sum and number.
[Answer]
# Ruby, 34+5=39
With command-line flags
```
ruby -nlaF|
```
Run
```
p eval [$F,0]*"**#{~/$/}+"+"==#$_"
```
Outputs true or false.
[Answer]
## R, ~~71~~ ~~69~~ ~~66~~ ~~56~~ 48
Reduced by 8 bytes thanks to [@Giuseppe](https://codegolf.stackexchange.com/users/67312/giuseppe)! The idea was to perform the integer division before the modulo operation.
```
i=nchar(a<-scan()):0;a==sum((a%/%10^i%%10)^i[1])
```
**(3-year) old version with corresponding explanation:**
```
i=nchar(a<-scan()):1;a==sum(((a%%10^i)%/%10^(i-1))^i[1])
```
`a<-scan()` takes a number (integer, real,...) as input (say `153` for the example).
`i` becomes a vector containing 3 to 1 (the number of characters of `a` being 3).
`%%` is vectorized so `a%%10^i` means `a` modulo 1000, 100 and 10: it therefore gives `153, 53, 3`.
`(a%%10^i)%/%10^(i-1)` is the integer division of that vector by 100, 10, 1: therefore, `1, 5, 3`.
We elevate that with the first element of `i` which is the number of characters (here digits) of `a`, i. e. `3`, thus giving a vector containing `1, 125, 27` that we `sum` and compares to `a`.
[Answer]
# Python 3, 56 bytes
Not very obfuscated, but a simple solution.
```
s = input()
print(int(s)==sum(int(c)**len(s)for c in s))
```
[Answer]
## PHP, ~~80~~ ~~74~~ 66 chars
Very straightforward PHP solution:
```
<?for(;$i<$l=strlen($a=$argv[1]);)$s+=pow($a[$i++],$l);echo$s==$a;
```
It assumes `error_reporting` doesn't include notices, otherwise quite a few extra characters will be needed to initialize `$s=0;` and `$i=0`.
Thx @manatwork for shortening many chars.
[Answer]
# Dc: 48 characters
```
[1pq]Sr?d0rdZSz[d10/r10%lz^rSh+Lhd0!=c]dScx+=r0p
```
Sample run:
```
bash-4.1$ dc -e '[1pq]Sr?d0rdZSz[d10/r10%lz^rSh+Lhd0!=c]dScx+=r0p' <<< '153'
1
bash-4.1$ dc -e '[1pq]Sr?d0rdZSz[d10/r10%lz^rSh+Lhd0!=c]dScx+=r0p' <<< '1634'
1
bash-4.1$ dc -e '[1pq]Sr?d0rdZSz[d10/r10%lz^rSh+Lhd0!=c]dScx+=r0p' <<< '2013'
0
```
[Answer]
# K, 24 23
```
{x=+/xexp["I"$'a]@#a:$x}
```
Shaved 1 char with reordering
```
{x=+/{x xexp#x}"I"$'$x}
```
[Answer]
# R, 53 bytes
```
sum(scan(t=gsub("(.)","\\1 ",x<-scan()))^nchar(x))==x
```
The `gsub` regex inserts spaces in between characters, so that the `scan` function will be able to read the number into a vector of digits.
[Answer]
# Kona, 18
...
```
{x=+/(0$'u)^#u:$x}
```
[Answer]
**Powershell, 75 63 62 60 58**
Edit: Updated per @Iszi's comment (note: this counts on `$x` not existing)
Edit: Added @Danko's changes.
```
[char[]]($x=$n=read-host)|%{$x-="$_*"*$n.length+1|iex};!$x
```
**58 56 chars**
If input is limited to 10 digits (includes all int32)
```
($x=$n=read-host)[0..9]|%{$x-="$_*"*$n.length+1|iex};!$x
```
[Answer]
## Python 2.x - 51
Same concept as crazedgremlin's solution for Python 3.x:
```
s=input();print s==sum(int(c)**len(`s`)for c in`s`)
```
[Answer]
## C - 97 93 characters
```
a,b;main(c){scanf("%d",&c);b=c;for(;c;c/=10)a+=pow(c%10,(int)log10(b)+1);printf("%d",a==b);}
```
With indentation:
```
a,b;
main(c) {
scanf("%d",&c);
b=c;
for(;c;c/=10)
a+=pow(c%10,(int)log10(b)+1);
printf("%d",a==b);
}
```
[Answer]
# [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/tree/fb4a2ce2bce6660e1a680a74dd61b72c945e6c3b), 7 bytes
```
DSDgmOQ
```
[Try it online!](https://tio.run/##MzBNTDJM/f/fJdglPdc/8P9/Q1NjAA "05AB1E (legacy) – Try It Online")
-2 bytes thanks to @daHugLenny
[Answer]
# Haskell 2010 - 76 characters
```
main=do x<-getLine;print$(==x)$show$sum$map((^length x).(+(-48)).fromEnum)x
```
[Answer]
# Awk: ~~40~~ 39 characters
```
{for(;i<NF;)s+=$(i+++1)**NF;$0=$0==s}1
```
Sample run:
```
bash-4.1$ awk -F '' '{for(;i<NF;)s+=$(i+++1)**NF;$0=$0==s}1' <<< '153'
1
bash-4.1$ awk -F '' '{for(;i<NF;)s+=$(i+++1)**NF;$0=$0==s}1' <<< '1634'
1
bash-4.1$ awk -F '' '{for(;i<NF;)s+=$(i+++1)**NF;$0=$0==s}1' <<< '2013'
0
```
[Answer]
# Bash, 64 chars
```
for((a=$1;a>0;s+=(a%10)**${#1},a/=10));do :; done;echo $[s==$1]
```
a=$1;p=${#a};for((;a>0;a/=10));do s=$((s+(a%10)\*\*p));done;echo $((s==$1))
[Answer]
## Lua (101 chars)
Lua isn't known for being concise, but it was fun to try anyway.
```
for n in io.lines()do l,s=n:len(),0 for i=1,l do d=n:byte(i)s=s+(d-48)^l end print(s==tonumber(n))end
```
Improvements welcome.
[Answer]
# Delphi - 166
```
uses System.SysUtils,math;var i,r,l:integer;s:string;begin r:=0;readln(s);l:=length(s);for I:=1to l do r:=round(r+power(strtoint(s[i]),l));writeln(inttostr(r)=s);end.
```
### With indent
```
uses System.SysUtils,math;
var
i,r,l:integer;
s:string;
begin
r:=0;
readln(s);
l:=length(s);
for I:=1to l do
r:=round(r+power(strtoint(s[i]),l));
writeln(inttostr(r)=s);
end.
```
[Answer]
## JavaScript - ~~70~~ 58 characters
```
for(i in a=b=prompt())b-=Math.pow(a[i],a.length)
alert(!b)
```
>
> **Note:**
>
>
> If you're testing this in your dev console on Stack Exchange, be aware that there are a number of non-standard properties added to `String.prototype` that will break this solution, such as `String.prototype.formatUnicorn`. Please be sure to test in a clean environment, such as on `about:blank`.
>
>
>
[Answer]
# Java - 84 bytes
```
(a,l)->{int s=0;for(byte c:a.getBytes())s+=Math.pow(c-48,l);return a.equals(""+s);};
```
Non-lambda version: 101 bytes:
```
boolean n(String a,int l){int s=0;for(byte c:a.getBytes())s+=Math.pow(c-48,l);return a.equals(""+s);}
```
Called like this:
```
interface X {
boolean n(String a, int l);
}
static X x = (a,l)->{int s=0;for(byte c:a.getBytes())s+=Math.pow(c-48,l);return a.equals(""+s);};
public static void main(String[] args) {
System.out.println(n("153",3));
System.out.println(n("1634",4));
System.out.println(n("123",3));
System.out.println(n("654",3));
}
```
Returns:
```
true
true
false
false
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt/), ~~14~~ ~~9~~ 7 bytes
```
¶ì_xpZÊ
```
[Try it online](https://ethproductions.github.io/japt/?v=1.4.5&code=tuxfeHBayg==&input=MTUz)
---
## Explanation
Implicit input of integer `U`.
```
ì_
```
Convert `U` to an array of digits (`ì`), pass it through a function and convert back to an integer after.
```
xpZÊ
```
Reduce by addition (`x`), raising each element to the power (`p`) of the length (`Ê`) of the array in the process.
```
¶
```
Check if the result is strictly equal to `U`.
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal), ~~8~~ 6 bytes
```
f⁰Le∑=
```
[Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%C6%9BI%3B%E2%81%B0Le%E2%88%91%3D&inputs=153&header=&footer=)
```
f # Map each digit to integer
e # (for each) to the power of
⁰L # Input length
∑ # Is sum...
= # Equal to
# (Implicit input)?
```
-2 thx to lyxal.
[Answer]
## F# - 92 chars
```
let n=stdin.ReadLine()
n|>Seq.map(fun x->pown(int x-48)n.Length)|>Seq.sum=int n|>printf"%b"
```
[Answer]
# Common Lisp - 116 102 characters
```
(defun f(m)(labels((l(n)(if(> n 0)(+(expt(mod n 10)(ceiling(log m 10)))(l(floor n 10)))0)))(= m(l m))))
```
Formatted:
```
(defun f(m)
(labels((l(n)
(if(> n 0)
(+(expt(mod n 10)(ceiling(log m 10)))
(l(floor n 10)))
0)))
(=(l m)m)))
```
[Answer]
# Smalltalk - 102 99 characters
```
[:n|a:=n asString collect:[:e|e digitValue]as:Array.^n=(a collect:[:each|each raisedTo:a size])sum]
```
At the Workspace, send `value:` with the number, and Print It.
[Answer]
# C#, 117
```
using System.Linq;class A{int Main(string[] a){return a[0].Select(c=>c-'0'^a[0].Length).Sum()==int.Parse(a[0])?1:0;}}
```
] |
[Question]
[
Given a list of `(key, value)` pairs, determine whether it represents a function, meaning that each key maps to a consistent value. In other words, whenever two entries have equal keys, they must also have equal values. Repeated entries are OK.
For example:
```
# Not a function: 3 maps to both 1 and 6
[(3,1), (2,5), (3,6)]
# Function: It's OK that (3,5) is listed twice, and that both 6 and 4 both map to 4
[(3,5), (3,5), (6,4), (4,4)]
```
**Input:** An ordered sequence of `(key, value)` pairs using digits 1 to 9. You may not require a particular ordering. You may alternatively take the key list and value list as separate inputs.
**Output:** A consistent value for functions, and a different consistent value for non-functions.
**Test cases:** The first 5 inputs are functions, the last 5 are not.
```
[(3, 5), (3, 5), (6, 4), (4, 4)]
[(9, 4), (1, 4), (2, 4)]
[]
[(1, 1)]
[(1, 2), (2, 1)]
[(3, 1), (2, 5), (3, 6)]
[(1, 2), (2, 1), (5, 2), (1, 2), (2, 5)]
[(8, 8), (8, 8), (8, 9), (8, 9)]
[(1, 2), (1, 3), (1, 4)]
[(1, 2), (1, 3), (2, 3), (2, 4)]
```
Here they are as two lists of inputs:
```
[[(3, 5), (3, 5), (6, 4), (4, 4)], [(9, 4), (1, 4), (2, 4)], [], [(1, 1)], [(1, 2), (2, 1)]]
[[(3, 1), (2, 5), (3, 6)], [(1, 2), (2, 1), (5, 2), (1, 2), (2, 5)], [(8, 8), (8, 8), (8, 9), (8, 9)], [(1, 2), (1, 3), (1, 4)], [(1, 2), (1, 3), (2, 3), (2, 4)]]
```
---
**Leaderboard:**
```
var QUESTION_ID=118960,OVERRIDE_USER=20260;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/118960/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
```
```
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
```
```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>
```
[Answer]
# [Python 2](https://docs.python.org/2/), 34 bytes
```
lambda x:len(dict(x))==len(set(x))
```
[Try it online!](https://tio.run/nexus/python2#bZDNCoMwEITvPsXeTCAe/ImokGufoDcrxdYEBLVFU/DtbVbjT6mnLzOTyS5R4jY1ZfuoShizRnakqp@ajJQKgWqQs5j0XctBizwnIQNOGWyMGUTICFkwyElqHd8yWJM5Na5P11Ngc@MUjjrO8G2yzopPOobc6oPPl5sJgwSdA9ONP28Zhtu@p0mwM8JNnXdfdxpcD679R4LnOurVA24PdQfLX2XLHUVQ0L1xKZvhr6JOKtMX "Python 2 – TIO Nexus")
Creates a Dictionary and a Set from the input and compare their lengths.
Dictionaries can't have duplicated keys, so all the illegal (and repeated) values are removed.
[Answer]
## Haskell, 36 bytes
```
f x=and[v==n|(k,v)<-x,(m,n)<-x,k==m]
```
[Try it online!](https://tio.run/nexus/haskell#dY/NCoMwEITvfYo5eIiwPfgTUTB9keBBEEHEtJQiHvruNombYKHN5dvMzGY3@4hN9WbQq1LmLWZa0/a6kVjI@GJWaun2pZ8MFIb7BfY8npN5IcGINrkBWouCIFNCZEUoHUvHjqBFw0rGzIPjXatmaahy9q3S/Z@XcSrMrX70W0q@n3R5JGtC7ZQTm8ivtyyLuLt3JGcbnh9@J4@t9w8 "Haskell – TIO Nexus")
Outer (->`(k,v)`) and inner (-> `(m,n)`) loop over the pairs and whenever `k==m`, collect the truth value of `v==n`. Check if all are true.
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), ~~5~~ 4 bytes
```
dhᵐ≠
```
[Try it online!](https://tio.run/nexus/brachylog2#@5@S8XDrhEedC/7/j4421jGN1YGSZjomQNIESMYCAA "Brachylog – TIO Nexus")
Full program. As far as I can tell, the reason that this is beating most other golfing languages is that `≠` is a builtin in Brachylog, whereas most of the other golfing languages need to synthesize it.
## Explanation
```
dhᵐ≠
d On the list of all unique elements of {the input},
h take the first element
ᵐ of each of those elements
≠ and assert that all those elements are different
```
As a full program, we get `true` if the assertion succeeds, or `false` if it fails.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 5 bytes
I'm pretty happy with this one.
```
{IhM{
implicit input
{ removes duplicate pairs
hM first element of each pair
{I checks invariance over deduplication (i.e. checks if no duplicates)
```
[Try it online!](http://pyth.herokuapp.com/?code=%7BIhM%7B&input=%5B%283%2C%205%29%2C%20%283%2C%205%29%2C%20%286%2C%204%29%2C%20%284%2C%204%29%5D%0A%5B%289%2C%204%29%2C%20%281%2C%204%29%2C%20%282%2C%204%29%5D%0A%5B%5D%0A%5B%281%2C%201%29%5D%0A%5B%281%2C%202%29%2C%20%282%2C%201%29%5D%0A%0A%5B%283%2C%201%29%2C%20%282%2C%205%29%2C%20%283%2C%206%29%5D%0A%5B%281%2C%202%29%2C%20%282%2C%201%29%2C%20%285%2C%202%29%2C%20%281%2C%202%29%2C%20%282%2C%205%29%5D%0A%5B%288%2C%208%29%2C%20%288%2C%208%29%2C%20%288%2C%209%29%2C%20%288%2C%209%29%5D%0A%5B%281%2C%202%29%2C%20%281%2C%203%29%2C%20%281%2C%204%29%5D%0A%5B%281%2C%202%29%2C%20%281%2C%203%29%2C%20%282%2C%203%29%2C%20%282%2C%204%29%5D&test_suite=1&test_suite_input=%5B%283%2C%205%29%2C%20%283%2C%205%29%2C%20%286%2C%204%29%2C%20%284%2C%204%29%5D%0A%5B%289%2C%204%29%2C%20%281%2C%204%29%2C%20%282%2C%204%29%5D%0A%5B%5D%0A%5B%281%2C%201%29%5D%0A%5B%281%2C%202%29%2C%20%282%2C%201%29%5D%0A%5B%283%2C%201%29%2C%20%282%2C%205%29%2C%20%283%2C%206%29%5D%0A%5B%281%2C%202%29%2C%20%282%2C%201%29%2C%20%285%2C%202%29%2C%20%281%2C%202%29%2C%20%282%2C%205%29%5D%0A%5B%288%2C%208%29%2C%20%288%2C%208%29%2C%20%288%2C%209%29%2C%20%288%2C%209%29%5D%0A%5B%281%2C%202%29%2C%20%281%2C%203%29%2C%20%281%2C%204%29%5D%0A%5B%281%2C%202%29%2C%20%281%2C%203%29%2C%20%282%2C%203%29%2C%20%282%2C%204%29%5D&debug=0)
[Answer]
## [Retina](https://github.com/m-ender/retina), 25 bytes
```
1`({\d+,)(\d+}).*\1(?!\2)
```
[Try it online!](https://tio.run/nexus/retina#VY49DoAgDIV3buFgAtqYlB8jk6OXYHDwFoSzY1sg0eXL63v9m/V1V7x1Ts8KRhOL2ZaE@pySNbVmB6FA5w6e6IkqR9EotOwoKrAwrVisHZF1W7H/UshB9HACpQccpAdj55hCcP2kollOo2xur4TP9dZpO315AQ "Retina – TIO Nexus")
Input format is `{k,v},{k,v},...`. Prints `0` for functions and `1` for non-functions. I could save two bytes by using linefeeds instead of the commas in the input format, but that's messed up.
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 13 bytes
```
¬{⊇Ċhᵐ=∧Ċtᵐ≠}
```
[Try it online!](https://tio.run/nexus/brachylog2#@39oTfWjrvYjXRkPt06wfdSx/EhXCZD1qHNB7f//0dHGOqaxOlDSTMcESJoAydj/AA "Brachylog – TIO Nexus")
### Explanation
```
¬{ } It is impossible...
⊇Ċ ...to find a subset of length 2 of the input...
Ċhᵐ= ...for which both elements have the same head...
∧ ...and...
Ċtᵐ≠ ...have different tails.
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 8 bytes
```
1Z?gs2<A
```
Inputs are: an array with the `value`s, followed by an array with the `key`s.
Output is `1` for function, `0` otherswise.
[Try it online!](https://tio.run/nexus/matl#@28YZ9ebGTj@P9/tKmCqYKJgkksV7SxgrGCGZAFAA). Or [verify all test cases](https://tio.run/nexus/matl#RU1BCsAwCLvvFfmC2pYWBmOwJ@y0UthtD9j/6USFoWI0id6Tru15ed3ncc6ekZGQxtIFgmIoxaaBwNo9KYphyBhSdzEvQ5xTxMiuUNZ1FRUNLZCGacW@kGoo5n@jV8YH).
### Explanation
`1Z?`
Builds a sparse matrix. Initially all entries contain `0`; and `1` is added to each entry `(i, j)` where `j` and `i` are the input `key`, `value` pairs.
`g`
The matrix is converted to logical; that is, entries exceeding `1` (corresponding to duplicate `key`, `value` pairs) are set to `1`.
`s`
The sum of each column is computed. This is the number of different `value`s for each `key`.
`2<A`
A function will have all such sums less than `2`.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~11~~ ~~9~~ 7 bytes
Saved 2 bytes thanks to *kalsowerus*.
```
Ùø¬DÙQ,
```
[Try it online!](https://tio.run/nexus/05ab1e#@3945uEdh9a4HJ4ZqPP/f3S0sY6CaayOApw201EwAdEmIDoWAA "05AB1E – TIO Nexus")
**Explanation**
```
Ù # remove duplicates
ø # zip
¬ # get the first element of the list (keys)
D # duplicate list of keys
Ù # remove duplicates in the copy
Q # compare for equality
, # explicitly print result
```
[Answer]
# R, 33 bytes
This is my version for R. This takes advantage of the `ave` function. I have allowed for empty input by setting defaults on the key and value parameters. `ave` is producing a mean of the values for each of the keys. Fortunately this returns the means in the same order as the input values, so a comparison to the input will indicate if there is different values. Returns `TRUE` if it is a function.
```
function(k=0,v=0)all(ave(v,k)==v)
```
[Try it online!](https://tio.run/nexus/r#TY5LDoMwDET3nMSWZkE@oGaRw6CokSoQ3bS5furgAJU3njfjkXOs@bunz@u90xpHlDjysm20lCcVrBxj4ZopkYPDDM9INGGCl5WHZgQY2Ib9HzQNmEN0oBmLBgcttHBHTOpmvmKi7rBIAd18oE8zdQ0I16WMXrn7DW04sRr1Bw "R – TIO Nexus")
[Answer]
## JavaScript (ES6), ~~45~~ 38 bytes
*Saved 6 bytes thanks to @Neil*
```
a=>a.some(([k,v])=>m[k]-(m[k]=v),m={})
```
Returns `false` or `true` for functions and non-functions, respectively.
This works by constantly subtracting the old value of each function (`m[k]`) and the new one (`m[k]=v`, which also stores the new value). Each time, there are three cases:
* If there was no old value, `m[k]` returns `undefined`. Subtracting anything from `undefined` results in `NaN`, which is falsy.
* If the old value is the same as the new one, `m[k]-v` results in `0`, which is falsy.
* If the old value is different from the new one, `m[k]-v` results in a non-zero integer, which is truthy.
Therefore, we just have to make sure that `m[k]-(m[k]=v)` is never truthy.
[Answer]
## Mathematica, 24 bytes
```
UnsameQ@@(#&@@@Union@#)&
```
Explanation: `Union` deletes duplicated pairs, then `#&@@@` gets the first element from each pair (like `First/@` but with fewer bytes). If there is any repetition in these first elements, the pairs don't make a function, which we check with `UnsameQ`.
(This might have the highest density of `@` characters in any program I've written…)
[Answer]
# [J-uby](http://github.com/cyoce/J-uby), ~~48~~ ~~33~~ ~~25~~ 21 bytes
-3 bytes thanks to Jordan!
```
:size*:==%[:to_h,~:|]
```
### Explanation
```
:size*:==%[:to_h,~:|]
# "readable"
(:size * :==) % [:to_h, ~:|]
# transform :% to explicit lambda
->(x){ (:size * :==).(:to_h ^ x, ~:| ^ x)
# apply explicit x to functions
->(x){ (:size * :==).(x.to_h, x|x) }
# expand :* (map over arguments)
->(x){ :==.(:size.(x.to_h), :size.(x|x) }
# simplify symbol calls to method calls
->(x){ x.to_h.size == (x|x).size }
# :| is set union for arrays; x|x just removes duplicates, like :uniq but shorter
->(x){ x.to_h.size == x.uniq.size }
```
# First Approach, 33 bytes
```
-[:[]&Hash,:uniq]|:*&:size|:/&:==
```
This one is longer than the equivalent Ruby solution, but it was fun to make.
Attempt of explanation by transforming to Ruby:
```
-[:[]&Hash,:uniq]|:*&:size|:/&:==
# "readable"
-[:[] & Hash, :uniq] | (:* & :size) | (:/ & :==)
# turn into explicit lambda
->(x){ (:/ & :==) ^ ((:* & :size) ^ (-[:[] & Hash, :uniq] ^ x)) }
# simplify expressions now that we have an explicit x
->(x){ :== / (:size * [Hash[x], x.uniq]) }
# translate to equivalent Ruby code
->(x) { [Hash[x], x.uniq].map(&:size).reduce(:==) }
# simplify reduce over explicit array
->(x) { Hash[x].size == x.uniq.size }
```
I could save 2 bytes with a newer version by replacing `:uniq` with `~:|`
[Answer]
# Bash + coreutils, 17
```
sort -u|uniq -dw1
```
Input is given via STDIN. `key` and `value` are `Tab` separated and each pair is newline-delimited.
`sort` removes the duplicate key-value pairs. `uniq -d` only outputs duplicates, and so outputs the empty string in the case of a function, and a non-empty string otherwise - when there are duplicate keys that map to different values.
[Try it online](https://tio.run/nexus/bash#XZBNDoMgEIXXcIpZdOsC/6Kt6a7d9gwKWGkaSRXTjXe3IxVFSV6YvO8xDPDSwBVKKAq4Pe40IolVSmIao2aPcpupXCZHn6HCPeeOe55wHiPM9@Xmh9hnx@ptFoZsnif1@fN4NsH9Xyd@rnG5jGSLcisvo/xejET2XR5/HXlotWRq3YGRvanVW4Jq8Rcr/AWBr6txyga7vy4gNAVckjd6DZ/h5EoL58tWB8ap152BYBiHVn0gEF82Cd3K6Qc).
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 9 bytes
Code:
```
ãü-ʒ¬_}}Ë
```
Explanation:
```
ã # Cartesian product with itself
ü- # Pairwise subtraction
ʒ }} # Filter out elements where the following is not true:
¬_ # Check whether the first digit is 0
Ë # Check if all equal
```
Uses the **05AB1E** encoding. [Try it online!](https://tio.run/nexus/05ab1e#@3948eE9uqcmHVoTX1t7uPv//@hoYx0F01gdBThtpqNgAqJNQHQsAA "05AB1E – TIO Nexus")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes
```
nþ`ḄCȦ
```
[Try it online!](https://tio.run/nexus/jelly#@593eF/Cwx0tzieW/T/c/qhpDRC5//8frRAdrWGso2CqqaMAp810FExAtAmIjtVRiNawhIoYQmkjmAxYFihqqAljGUHlgSKxOlxQ4w2hgjBrzLAoB9KmUD6SuClEpYWOggVIBIm2hNMoZgFpY7hTscoYIWigiliuWAA "Jelly – TIO Nexus")
### How it works
```
nþ`ḄCȦ Main link. Argument: M (n×2 matrix)
nþ` Construct the table of (a != b, c != d) with (a, b) and (c, d) in M.
Ḅ Unbinary; map (0, 0), (0, 1), (1, 0), (1, 1) to 0, 1, 2, 3 (resp.).
C Complement; map each resulting integer x to 1 - x.
Ȧ All; test if all resulting integers are non-zero.
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes
```
QḢ€µQ⁼
```
[Try it online!](https://tio.run/nexus/jelly#@x/4cMeiR01rHu5c5Plw14L///9HRxvrmMbqQEkzMGmqYxIbCwA "Jelly – TIO Nexus")
**Explanation**
```
QḢ€µQ⁼
Q - Remove duplicate pairs
Ḣ€ - Retrieve the first element of each pair
µ - On the output of what came before..
⁼ - Are the following two equal (bit returned)?
Q - The output with duplicates removed
- (implicit) the output.
```
Here is an alternate method, also 6 bytes:
```
QḢ€ṢIẠ
```
[Try it online!](https://tio.run/nexus/jelly#@x/4cMeiR01rDm0NfNS45////9HRhjoKRrE6CtFGOgqGINoUzjcFUWDpWAA "Jelly – TIO Nexus")
Instead of testing with removing duplicate keys, this sorts (`Ṣ`) and checks if the difference between terms (`I`) is all truthy (`Ạ`)
[Answer]
# [Actually](https://github.com/Mego/Seriously), 4 bytes
```
╔♂F═
```
[Try it online!](https://tio.run/nexus/actually#@/9o6pRHM5vcHk2d8P9/tIaxjoKhpo6ChpGOgimIBvLNNGMB "Actually – TIO Nexus")
Explanation:
```
╔♂F═
╔ uniquify (remove duplicate pairs)
♂F take first items in each pair (keys)
═ are all of the keys unique?
```
[Answer]
# R, ~~36~~ 33 bytes
```
function(k,v)any(v[match(k,k)]-v)
```
[Try it online!](https://tio.run/##HYtBDoMgFET3nOIn3fyfjAtFu@pNGhcEIW2otKlIwulR3L2ZefOvnh4dVb9Hm97fyAFZTCycn6tJ9nXmIHOXpXq2rKFxxyiwPGHCeKKoNrRGhG7k1l8qFFzZyMSFsvnsbruUHj0GDM1soK@vUvUA "R – Try It Online")
anonymous function; returns `FALSE` for functions and `TRUE` for not.
This ~~is being beaten by~~ is finally tied with [MickyT's answer!](https://codegolf.stackexchange.com/a/119045/67312)!
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 11 bytes
```
{r~?r:*'?x}
```
[Try it online!](https://ngn.codeberg.page/k#eJxLs6ouqrMvstJSt6+o5eJKc9AwVjC1BmEzBRNrEwUTTYiYobURWNwMzDdUMALyDTUB4EoNpw==)
Port of chunes' factor answer.
## Explanation
```
{r~?r:*'?x}
{ } /function
?x /distinct values
*' /first value of each
r: /store in r
r~? /is distinct?
```
[Answer]
# [V](https://github.com/DJMcMayhem/V), 30 bytes
```
Úç^¨.*©î±$/d
ÎwD
ç/HdG
Íî
Ò1lD
```
[Try it online!](https://tio.run/nexus/v#@3941uHlcYdW6GkdWnl43aGNKvopXIf7yl24Di/X90hx5zrce3gd1@FJhjku//8bK5hygbCZggkQm3KZKJgAAA "V – TIO Nexus")
Outputs `1` for functions and nothing for non-functions.
[Answer]
# Mathematica, 35 bytes
```
(l=Length)@Union@#==l@<|Rule@@@#|>&
```
Pure function taking a list of ordered pairs as input and returning `True` or `False`. Exploits the fact that `Union@#` deletes repeated ordered pairs, but `<|Rule@@@#|>` (an association) deletes all but one ordered pair with a particular first element. So we can just compare the `Length`s of the two outputs to check whether the input list is a function.
[Answer]
# [CJam](https://sourceforge.net/p/cjam), ~~19~~ 17 bytes
Saved 2 bytes thanks to Martin Ender
```
0l~$2ew{:.=~!&|}/
```
Outputs `0` for functions and `1` for non-functions.
[Try it online!](https://tio.run/nexus/cjam#q/5vkFOnYpRaXm2lZ1unqFZTq/@/oNbQQOt/dLSxgmmsApQ0UzABkiZAMpYrOtoSzDMEk0YQMZCwoYJhLIQ2AktAeMZAGsSDGGaGpkIh2hTMhomYguUtFCyAPBhpCSUROg0VjKEOQBczgpJAGQA "CJam – TIO Nexus")
**Explanation**
```
0 e# Push a 0. We need it for later.
l~ e# Read and eval a line of input.
$ e# Sort it by the keys.
2ew e# Get all consecutive pairs of the sorted list.
{ e# For each pair of pairs:
:.= e# Check if the keys are equal and if the values are equal.
~!& e# Determine if the keys are equal AND the values are not equal.
| e# OR with 0. If any pair indicates that the input is not a function,
e# this will become 1 (and remain 1), otherwise it will be 0.
}/ e# (end block)
```
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), ~~16~~ ~~12~~ ~~11~~ 9 bytes
```
(∪≡⊢)⊃¨∘∪
```
[Try it online!](https://tio.run/nexus/apl-dyalog#@@/4qG2CxqOOVY86Fz7qWqT5qKv50IpHHTOAIv//OypoPOpqMtZRMNXUQWea6SiYQJkmICYXRLElQtgQwTSCqnjUuwaqDihpqIlgGyEUAoUtDB71blHXVeeCO8AQIY/kFjNcJkCYpghRVAWmMH0WOgoWUGFUpiUyE9MSINMY2Zd4VRihME00AQ "APL (Dyalog Unicode) – TIO Nexus")
### Explanation
```
∪ Unique, remove duplicates; (3 5) (3 5) => (3 5)
¨∘ For each element
⊃ Pick the first sub element (3 5) (2 3) => 3
≡ Check whether the arguments (listed below) are the same
⊢ The right argument
∪ And the right argument with duplicates removed
```
Prints `0` for false and `1` for true
[Answer]
# [R](https://www.r-project.org/), ~~95~~ 66 bytes
```
function(k,v)any(sapply(k,function(x){length(unique(v[k==x]))-1}))
```
*Saved 29 bytes thanks to Jarko Dubbeldam.*
Anonymous function. Outputs `FALSE` if a function and `TRUE` if not (sorry). Takes as arguments a list of keys and a list of values, like so.
```
> f(c(1,2,5,1,2),c(2,1,2,2,5))
[1] TRUE # not a function
```
Loops through all keys and grabs the length of the set of unique values for that key. If `any` of them are > 1, return `TRUE`.
This is being beaten by [MickyT](https://codegolf.stackexchange.com/questions/118960/is-this-a-function/119045#119045)'s answer, and also [Giuseppe](https://codegolf.stackexchange.com/a/119006/62105)'s. upvote one of those.
[Answer]
# [brainfuck](https://github.com/TryItOnline/tio-transpilers), 71 bytes
```
,[[-[->>+<<]+>>],>[[->+<<->]<[<<]>]>[-<+>]<<[->+<]+[-<<]>>,]-[--->+<]>.
```
[Try it online!](https://tio.run/nexus/brainfuck#HcvBDQAxCAPBgoBIIfdEbgS5/zKIL88dy@Pd0QFYFQ2gQ/BXgNVCEB1lqnoDTSmGU8d4hDWzc588@V0 "brainfuck – TIO Nexus")
Input is taken as a flat string: for instance, the first test case would be `35356444`. To get the representation shown in the original question, simply add a total of six commas to the program at the right points.
Output is `U` for functions and `V` for non-functions.
### Explanation
For any ASCII code point n, f(n) is stored at cell 2n+1. Cells 2n and 2n+2 are working space, and 0, 2, 4, 6, ... 2n-2 are a trail of breadcrumbs to lead back to cell 0. When the input is proven not to be a function, f(0) is set to 1 (among various side effects).
```
, input first key
[ start main loop
[-[->>+<<]+>>] move to cell 2n, leaving a trail of breadcrumbs
, input value corresponding to current key
>[ if key already has a value:
[->+<<->]< copy existing value, and compare to new value
[<<] if values are different, go to cell -2
> go back to cell 2n+1 (or -1 if mismatch)
]
>[-<+>] move existing value back to cell 2n+1 (NOP if no existing value, move the 1 from cell 0 to cell -1 if mismatch)
<<[->+<] copy new value to cell 2n+1 (NOP if there was already a value)
+[-<<]>> follow breadcrumbs back to cell 0 (NOP if mismatch)
, input next key
] (if mismatch, cell -2 becomes the next "cell 0", and the next key is also effectively changed by the breadcrumbs left lying around)
-[--->+<]>. add 85 to cell 1 and output the result
```
[Answer]
# [Desmos](https://desmos.com/calculator), 46 bytes
```
U=L.unique
f(L)=0^{U.length-U.x.unique.length}
```
Function returning 1 for functions and 0 for non-functions.
Equivalent, but slightly longer:
```
f(L)=0^{L.unique.length-L.unique.x.unique.length}
```
[Try it on Desmos!](https://www.desmos.com/calculator/zqk5ac1hwp)
[Answer]
# [Factor](https://factorcode.org/), 28 bytes
```
[ members keys all-unique? ]
```
[Try it online!](https://tio.run/##fZC/DsIgEMb3PsW9gCZgbawOjsbFxTgZBySYNLV/5OjQNDw7XlpsaYzyDT@4@447eAhpKu0u5@PpsAWBWEmEWitj2lpnpQFUr0aVUiHtDMIuiroIaHWkFazBBkwg7hn3tKMv9XHmyWf5ycdIdnbm3j/Eg8bMJz4DJH8KO3JxPwAP6ib/hmRnTAN@38uo4/Sg33k@cvDZyF2hUMVdaYRctQji@Vw0ZUZ/vIebK0QNaITMl@4N "Factor – Try It Online")
* `members` Get the unique elements
* `keys` Get the keys of an associative array as a sequence
* `all-unique?` Are they all unique?
```
! { { 1 2 } { 2 1 } { 5 2 } { 1 2 } { 2 5 } }
members ! { { 1 2 } { 2 1 } { 5 2 } { 2 5 } }
keys ! { 1 2 5 2 }
all-unique? ! f
```
[Answer]
# [Julia](https://julialang.org), 14 bytes
```
!x=x⊆Dict(x)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=bY8xDoIwFIZ3TvHcXpNqIgiBASZXT2AcipZYQ6pBNB2cHbyCCwur93H1Cl7A1lYk0S5f-_1_XttruzmUgjVNe6iLYXwbqFQ9LuepWNaoiJX3dbGtQICQUHG2KoXkeyQe6KUgBX5kJc54zUY7Vu05CvLNFIxOGSAymhNKYJgBS7P8He8qIetSoq5lMFDE43Jl72vuzzkGFEJCoWNEYWI4MVx4c0ycGDv6LjCZdmPiNr4LrQjMxorP-Oi3qRm6c8-H72JMITaix6Rjf5Jm0D3wX-B_qQv27y8)
[Answer]
# [Perl 6](https://perl6.org), 38 bytes
```
!*.unique(:as(~*)).repeated(:as(*[0]))
```
[Try it](https://tio.run/nexus/perl6#jVFBbsIwELz7FcsF2cFEJCQRNCri1BdwoxwiMJIlcEJsV6pQ@/XUsYyTAJU4jXdmdtZra8ngKwv3OTp/w5jL6VGLveKlgPdmFIRa8Itm@K2Q@DcgJKxZxQrFDpYJtrMdIY1tXQ9aASOALZ5TSAkFjxmFpMWkxR21nqXjIodxpzmHUSLSnWPnshzxw0Wpnl4gcvbbRbKnUQZTV/f49OZdUFi0XA@XHu/yDM79Qv9ocYeJW0Obj9gwqXJUnQoxfM/Jw4Y5Opb10DRdwScXlVZwNTO5hJ6IrWAmbmrNKNgK/fiMwdu9lPNRnGQX1PwB "Perl 6 – TIO Nexus")
[Answer]
# Pyth - ~~9~~ 8 bytes
```
ql.d{Ql{
```
[Try it](http://pyth.herokuapp.com/?code=ql.d%7BQl%7B&input=%5B%283%2C+5%29%2C+%283%2C+5%29%2C+%286%2C+4%29%2C+%284%2C+4%29%5D%0A%5B%289%2C+4%29%2C+%281%2C+4%29%2C+%282%2C+4%29%5D%0A%5B%5D%0A%5B%281%2C+1%29%5D%0A%5B%281%2C+2%29%2C+%282%2C+1%29%5D%0A%5B%283%2C+1%29%2C+%282%2C+5%29%2C+%283%2C+6%29%5D%0A%5B%281%2C+2%29%2C+%282%2C+1%29%2C+%285%2C+2%29%2C+%281%2C+2%29%2C+%282%2C+5%29%5D%0A%5B%288%2C+8%29%2C+%288%2C+8%29%2C+%288%2C+9%29%2C+%288%2C+9%29%5D%0A%5B%281%2C+2%29%2C+%281%2C+3%29%2C+%281%2C+4%29%5D%0A%5B%281%2C+2%29%2C+%281%2C+3%29%2C+%282%2C+3%29%2C+%282%2C+4%29%5D&test_suite=1&test_suite_input=%5B%283%2C+5%29%2C+%283%2C+5%29%2C+%286%2C+4%29%2C+%284%2C+4%29%5D%0A%5B%289%2C+4%29%2C+%281%2C+4%29%2C+%282%2C+4%29%5D%0A%5B%5D%0A%5B%281%2C+1%29%5D%0A%5B%281%2C+2%29%2C+%282%2C+1%29%5D%0A%5B%283%2C+1%29%2C+%282%2C+5%29%2C+%283%2C+6%29%5D%0A%5B%281%2C+2%29%2C+%282%2C+1%29%2C+%285%2C+2%29%2C+%281%2C+2%29%2C+%282%2C+5%29%5D%0A%5B%288%2C+8%29%2C+%288%2C+8%29%2C+%288%2C+9%29%2C+%288%2C+9%29%5D%0A%5B%281%2C+2%29%2C+%281%2C+3%29%2C+%281%2C+4%29%5D%0A%5B%281%2C+2%29%2C+%281%2C+3%29%2C+%282%2C+3%29%2C+%282%2C+4%29%5D&debug=0)
It works by removing any repeated pairs first ({Q); then it compares the length of the list to the length of a dictionary created from the list (if the same x value occurs more than once, the dictionary constructor uses only the last one, resulting in the dictionary being shorter than the list)
] |
[Question]
[
### Background
When I was in elementary school, we used to play a game in math class that goes as follows.
All kids sit in a big circle and take turns counting, starting from **1**.
However, the following numbers must be skipped while counting:
* Numbers that are multiples of **3**.
* Numbers that have a **3** in its decimal representation.
The first 15 numbers the kids should say are
```
1 2 4 5 7 8 10 11 14 16 17 19 20 22 25
```
Whenever somebody gets a number wrong – says a number that isn't in the sequence or skips a number that is – he's removed from the circle. This goes on until there's only one kid left.
### Task
You're bad at this game, so you decide to cheat. Write a program or a function that, given a number of the sequence, calculates the next number of the sequence.
You don't have to handle numbers that cannot be represented using your language's native numeric type, provided that your program works correctly up to input **251** and that your algorithm works for arbitrarily large inputs.
Input and output can use any convenient base.
Since you have to conceal your code, it must be as short as possible. In fact, this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins.
### Test cases
```
1 -> 2
2 -> 4
11 -> 14
22 -> 25
29 -> 40
251 -> 254
```
[Answer]
# [Brachylog](http://github.com/JCumin/Brachylog), 10 bytes
```
<.='e3:I'*
```
[Try it online!](http://brachylog.tryitonline.net/#code=PC49J2UzOkknKg&input=Mjk&args=Wg)
### Explanation
```
(?)<. Output > Input
.= Assign a value to the Output
. 'e3 3 cannot be an element of the Output (i.e. one of its digits)
3:I'*(.) There is no I such that 3*I = Output
```
[Answer]
# JavaScript (ES6), 30 bytes
```
f=n=>++n%3*!/3/.test(n)?n:f(n)
```
[Answer]
# J, 24 bytes
```
3(]0&({$:)~e.&":+.0=|)>:
```
Straight-forward approach that just iterates forward from input *n* until it finds the next number that is valid by the rules.
Forms five smileys, `$:`, `:)`, `0=`, `=|`, and `>:`.
## Usage
```
f =: 3(]0&({$:)~e.&":+.0=|)>:
(,.f"0) 1 2 11 22 29 251
1 2
2 4
11 14
22 25
29 40
251 254
```
## Explanation
```
3(]0&({$:)~e.&":+.0=|)>: Input: integer n
>: Increment n
3 The constant 3
( ) Operate dyadically with 3 (LHS) and n+1 (RHS)
| Take (n+1) mod 3
0= Test if equal to 0
&": Format both 3 and n+1 as a string
e. Test if it contains '3' in str(n+1)
+. Logical OR the results from those two tests
] Right identity, gets n+1
0&( )~ If the result from logical OR is true
$: Call recursively on n+1
{ Return that as the result
Else act as identity function and return n+1
```
[Answer]
## Python 2, 73 66 43 bytes
Thanks to xnor for telling me I was being silly by using 2 variables, and thanks to Mitch Schwartz too.
```
x=~input()
while'3'[:x%3]in`x`:x-=1
print-x
```
[Answer]
## Perl, 19 bytes
**18 bytes code + 1 for `-p`.**
```
++$_%3&&!/3/||redo
```
### Usage
```
perl -pe '++$_%3&&!/3/||redo' <<< 8
10
perl -pe '++$_%3&&!/3/||redo' <<< 11
14
```
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), 11 bytes
```
[>Ð3ås3Ö~_#
```
[Try it online!](http://05ab1e.tryitonline.net/#code=Wz7DkDPDpXMzw5Z-XyM&input=Mjk)
**Explanation**
```
# implicit input
[ # start loop
> # increase current number
Ð # triplicate
# # break loop IF
_ # logical negation of
3å # number has one or more 3's in it
~ # OR
s3Ö # number % 3 == 0
```
[Answer]
# Java 8, ~~57~~ ~~56~~ ~~55~~ 50 bytes
*Thanks to @Numberknot for 1 byte*
*Thanks to @Kevin Cruijssen for 5 bytes*
```
i->{for(;++i%3<1|(i+"").contains("3"););return i;}
```
This is a `Function<Integer, Integer>`
**Explanation**
Naive implementation that simply increments until it reaches an acceptable number.
**Test Class**
```
public class CodeGolf {
public static void main(String[] args) {
Function<Integer, Integer> countingGame = i->{for(;++i%3<1|(i+"").contains("3"););return i;};
int val = 1;
for (int i = 0; i < 10; i++) {
System.out.print(val + " ");
val = countingGame.apply(val);
}
}
}
```
Output of Test Class:
```
1 2 4 5 7 8 10 11 14 16
```
[Answer]
# Python 2, ~~49~~ ~~44~~ 42 bytes
```
f=lambda x:'3'[:~x%3]in`~x`and f(x+1)or-~x
```
The other Python entry beats this (edit: not any more :-D), but I posted it because I rather like its recursive approach.
Thanks to Mitch Schwarz and Erik the Golfer for helping me make this shorter.
[Answer]
# Japt, 18 bytes
```
°U%3*!Us f'3 ?U:ßU
```
[**Test it online**](http://ethproductions.github.io/japt/?v=master&code=sFUlMyohVXMgZiczID9VOt9V&input=MTE=)
I finally have a chance to use `ß` :-)
### How it works
```
// Implicit: U = input integer
°U%3 // Increment U, and take its modulo by 3.
!Us f'3 // Take all matches of /3/ in the number, then take logical NOT.
// This returns true if the number does not contain a 3.
* // Multiply. Returns 0 if U%3 === 0 or the number contains a 3.
?U // If this is truthy (non-zero), return U.
:ßU // Otherwise, return the result of running the program again on U.
// Implicit: output last expression
```
[Answer]
## PowerShell v2+, 46 bytes
```
for($a=$args[0]+1;$a-match3-or!($a%3)){$a++}$a
```
Takes input `$args[0]`, adds `1`, saves into `$a`, starts a `for` loop. The conditional keeps the loop going while either `$a-match3` (regex match) `-or` `$a%3` is zero (the `!` of which is `1`). The loop simply increments `$a++`. At the end of the loop, we simply place `$a` on the pipeline, and output via implicit `Write-Output` happens at program completion.
### Examples
```
PS C:\Tools\Scripts\golfing> 1,2,11,22,29,33,102,251,254|%{"$_ --> "+(.\count-without-three.ps1 $_)}
1 --> 2
2 --> 4
11 --> 14
22 --> 25
29 --> 40
33 --> 40
102 --> 104
251 --> 254
254 --> 256
```
[Answer]
# R, 46 bytes
```
n=scan()+1;while(!n%%3|grepl(3,n))n=n+1;cat(n)
```
[Answer]
# Haskell, ~~50~~ 48 bytes
```
f n=[x|x<-[n..],mod x 3>0,notElem '3'$show x]!!1
```
[Try it on Ideone.](http://ideone.com/0NRlOh) Saved 2 bytes thanks to [@Charlie Harding](https://codegolf.stackexchange.com/users/15516/charlie-harding).
Alternative: (50 bytes)
```
g=f.(+1)
f n|mod n 3<1||(elem '3'.show)n=g n|1<3=n
```
[Answer]
# [Labyrinth](http://github.com/mbuettner/labyrinth), 117 102 bytes
```
? """""""""""_
):_3 ( 0/{!@
; %;:}_';:_3-_10 1
" 1 %;_
""""_""""""""{;;'
```
[Try it online!](http://labyrinth.tryitonline.net/#code=PyAgICAgICAiIiIiIiIiIiIiIl8KKTpfMyAgICAoICAgICAgICAgMC97IUAKOyAgJTs6fV8nOzpfMy1fMTAgMQoiICAxICAgICAgICAgICAgJTtfCiIiIiJfIiIiIiIiIiJ7Ozsn&input=Mjk5)
Labyrinth is a two-dimensional, stack-based programming language and at junctions, direction is determined by the top of the stack (positive goes right, negative goes left, zero goes straight). There are two main loops in this programs. The first mods the integer input by 3 and increments if 0. The second repeatedly checks if the last digit is 3 (by subtracting 3 and modding by 10) and then dividing by 10 to get a new last digit.
[Answer]
# Lua, 58 Bytes
```
i=...+1while(i%3==0or(i..""):find"3")do i=i+1 end print(i)
```
[Answer]
## Pyke, 13 bytes
```
Whii3%!3`i`{|
```
[Try it here!](http://pyke.catbus.co.uk/?code=Whii3%25%213%60i%60%7B%7C&input=299&warnings=0)
```
- i = input
W - do:
hi - i += 1
i3%! - not (i % 3)
| - ^ or V
3`i`{ - "3" in str(i)
- while ^
```
[Answer]
# C#, ~~56~~, 51 bytes.
This is surprisingly short for a C# answer!
```
x=>{while(++x%3<1|(x+"").Contains("3"));return x;};
```
[Answer]
# Pyth, 11 bytes
```
f&-I`T3%T3h
```
Try it online: [Demonstration](https://pyth.herokuapp.com/?code=f%26-I%60T3%25T3h&input=29&test_suite_input=1%0A2%0A11%0A22%0A29%0A251&debug=0) or [Test Suite](https://pyth.herokuapp.com/?code=f%26-I%60T3%25T3h&input=29&test_suite=1&test_suite_input=1%0A2%0A11%0A22%0A29%0A251&debug=0)
### Explanation:
```
f&-I`T3%T3hQ implicit Q at the end
f hQ find the smallest integer T >= input + 1 which fulfills:
-I`T3 T is invariant under removing the digit 3
& and
%T3 T mod 3 leaves a positive remainder
```
[Answer]
# Excel, ~~79~~ 66 bytes
It [Taylor Rained](https://codegolf.stackexchange.com/questions/98366/count-without-3/246608?noredirect=1#comment552856_246608) 13 bytes
```
=MIN(LET(r,ROW(A:A),FILTER(r,ISERR(FIND(3,r))*MOD(r,3)*(r>A1)>0)))
```
Input is in the cell `A1`. Output is wherever the formula is.
The `LET()` function allows you to define variables for later reference so ti works in pairs of `variable,value`. The last argument is unpaired as it is the output.
* `r,ROW(A:A)` creates an array of 1 to whatever the last row is. In the latest version of Excel, that's 1,048,576.
* `g,FILTER(r,~*~*~>0)` takes that array and filters just for the values that aren't multiples of 3 and don't have a 3 in them. This done is by multiplying:
+ `ISERR(FIND(3,r))` which returns TRUE if if a 3 is *not* in the number and FALSE if it *is*
+ `MOD(r,3)` which returns 0 if it's a multiple of 3 and some positive integer if it isn't
+ `(r>A1)` creates an array of TRUE / FALSE where the first TRUE value will be the first term that's larger than the input.
+ When you do math on booleans, Excel uses TRUE=1 and FALSE=0 so the formula `~*~*~>0` only returns TRUE when the three pieces are TRUE (no 3 in number), some positive integer (not a multiple of 3), and TRUE (larger than the input).
* `MIN(LET(~))` finds the smallest value in the filtered array which only includes the "without 3" numbers larger than the input so the first value in the array is the next value in the sequence.
[![Screenshot](https://i.stack.imgur.com/Quvq3.png)](https://i.stack.imgur.com/Quvq3.png)
[Answer]
# [Python 3](https://docs.python.org/3/), 49 48 bytes
-3 bytes thx to The Thonnu, I missed some spaces and swapping else x+1 and else-~x allowed another space to be taken out, not
+2 bytes bc I didn't know I need to count f= on a recursive function, thx xnor :)
seems clunky but i cant see more golfs, please lmk if you see something!
```
f=lambda x:f(x+1)if x%3>1or'3'in str(x+1)else-~x
```
[Try it online!](https://tio.run/##K6gsycjPM/7/P802JzE3KSVRocIqTaNC21AzM02hQtXYzjC/SN1YPTNPobikCCyemlOcqltX8b@gKDOvRCNNw1BTkwvGNkJiG6JIIMsYWSJzTIHq/gMA "Python 3 – Try It Online")
[Answer]
## [GolfSharp](https://github.com/timopomer/GolfSharp), 43 bytes
```
m=>r(m,m).w(n=>n%3>0&!n.t().I("3")).a()[1];
```
[Answer]
# Ruby, 47 bytes
```
i=gets.to_i;i while(i+=1)%3==0||"#{i}"=~/3/;p i
```
I really feel like this can be golfed further.
[Answer]
# [MATL](http://github.com/lmendo/MATL), 14 bytes
```
`Qtt3\wV51-hA~
```
[Try it online!](http://matl.tryitonline.net/#code=YFF0dDNcd1Y1MS1oQX4&input=Mjk)
### Explanation
```
` % Do...while
Q % Add 1. Takes input implicitly in the first iteration
tt % Duplicate twice
3\ % Modulo 3
wV % Swap, string representation
51- % Subtract 51, which is ASCII for '3'
h % Concatenate
A~ % True if any result was 0. That indicates that the number
% was a multiple of 3 or had some '3' digit; and thus a
% new iteration is needed
```
[Answer]
# PHP, ~~60~~ ~~55~~ ~~54~~ 46 bytes
Thanks to @user59178 for shaving off a few bytes, @AlexHowansky for a byte, @Titus for another few bytes
```
for(;strstr($i=++$argv[1],51)|$i%3<1;);echo$i;
```
Called from command line with `-r`. Naive method that loops while the number is a multiple of 3, or has 3 in its digits.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes
```
D;Æf3ḟµ‘#2ị
```
[Try it online!](https://tio.run/nexus/jelly#@@9ifbgtzfjhjvmHtj5qmKFs9HB39////40sAQ "Jelly – TIO Nexus")
### How it works
```
D;Æf3ḟµ‘#2ị Main link. Argument: n
µ Combine the links to the left into a chain.
‘# Execute the chain for k = n, n + 1, n + 2, ... until n + 1 matches
were found. Yield the array of all n + 1 matches.
D Decimal; yield the array of k's decimal digits.
Æf Yield the array of k's prime factors.
; Concatenate both.
3ḟ Filter false; remove digits and factors from [3].
This yields [3] (truthy) if neither digits nor factors contain 3,
[] (falsy) if they do.
2ị Extract the second match. (The first match is n.)
```
[Answer]
# PHP, ~~47~~ 41 bytes
inspired by [Xanderhall](https://codegolf.stackexchange.com/a/98462#98462), but the latest idea finally justifies an own answer.
```
while(strstr($n+=$n=&$argn%3,51));echo$n;
```
or
```
while(strpbrk($n+=$n=&$argn%3,3));echo$n;
```
This takes advantage from the fact that the input is also from the sequence: For `$n%3==1`, the new modulo is `2`. For `$n%3==2`, the new modulo is `4-3=1`. `$n%3==0` never happens.
Run as pipe with `-R` or [try them online](http://sandbox.onlinephpfunctions.com/code/c94a70661b4b1a7f28d583f01ce72ecc287cafe4).
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~33~~ ~~28~~ ~~27~~ 19 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?")[SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set")
```
1∘+⍣{('3'∊⍕⍺)<×3|⍺}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///3/BRxwztR72LqzXUjdUfdXQ96p36qHeXps3h6cY1QEbt/7RHbRMe9fY96pvq6f@oq/nQeuNHbROBvOAgZyAZ4uEZ/D9NwZArTcEIiA3BDBDLyBJEmBoCAA "APL (Dyalog Unicode) – Try It Online")
-6 thanks to Adám. -8 thanks to ngn.
Old Explanation:
```
1-⍨g⍣((×3|⊢)>'3'∊⍕)∘(g←+∘1)
+∘1 ⍝ curry + with 1, gives the increment function
⍝ increments the left argument so we do not return the number itself
(g← ) ⍝ assign to "g"
∘ ⍝ compose g with the repeat
⍕ ⍝ does parsing the argument to a string...
'3'∊ ⍝ ...contain '3'?
3|⊢ ⍝ residue of a division by 3
(× ) ⍝ direction (0 if 0, 1 if greater, ¯1 is lower)
( > ) ⍝ and not (we want the left side to be 1, the right side 0)
g⍣ ⍝ repeat "g" (increment) until this function is true ^
1-⍨ ⍝ afterwards, decrement: inversed -
```
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), ~~23~~ 17 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?")[SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set")
```
1∘+⍣(3(×⍤|>∊⍥⍕)⊣)
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/3/BRxwztR72LNYw1Dk9/1Lukxu5RR9ej3qWPeqdqPuparPk/7VHbhEe9fY/6pnr6P@pqPrTe@FHbRCAvOMgZSIZ4eAb/T1Mw5EpTMAJiQzADxDKyBBGmhgA "APL (Dyalog Extended) – Try It Online")
Thanks to Adám. -6 thanks to ngn.
Old Explanation:
```
0+⍣(3(×⍤|>∊⍥⍕)⊢)⍢(1+⊢)⊢
0 ⍝ the left argument (⍺)
+⍣(3(×⍤|>∊⍥⍕)⊢) ⍝ the left function (⍺⍺)
(1+⊢) ⍝ the right function (⍵⍵)
⍝ (increments its argument)
⊢ ⍝ the right argument (⍵)
⍝ (just returns the input)
⍢ ⍝ under:
⍝ calls (⍵⍵ ⍵) first, which increments the input
⍝ also (⍵⍵ ⍺) which gives 1
⍝ then calls (⍺incremented ⍺⍺ ⍵incremented)
⍝ afterwards, does the opposite of ⍵⍵, and decrements the result
⍣ ⍝ ⍣ fixpoint: repeats the left operation until the right side is truthy
+ ⍝ calls + with ⍺incremented and the input (so, 1+input)
(3(×⍤|>∊⍥⍕)⊢) ⍝ right operation
3 ⍝ on its left, "3"
⊢ ⍝ on its right, the current iteration
×⍤| ⍝ divisibility check: × atop |
| ⍝ starts with 3|⊢ (residue of ⊢/3)
× ⍝ then returns the direction (0 if 0, 1 if greater, ¯1 is lower)
∊⍥⍕ ⍝ contains 3:
⍕ ⍝ stringifies both its arguments (3 and ⊢)
∊⍥ ⍝ checks for membership
> ⍝ divisibility "and not" contains 3
```
[Answer]
# Turing Machine Code, 390 bytes
```
0 * * r 0
0 _ _ l 1
1 1 2 l 2
1 2 3 r 0
1 3 4 l 2
1 4 5 l 2
1 5 6 l 2
1 6 7 l 2
1 7 8 l 2
1 8 9 l 2
1 9 0 l 1
1 * 1 l 2
2 * * l 2
2 _ _ r 3
3 1 1 r 4
3 4 4 r 4
3 7 7 r 4
3 2 2 r 5
3 5 5 r 5
3 8 8 r 5
3 _ _ l 1
4 1 1 r 5
4 4 4 r 5
4 7 7 r 5
4 2 2 r 3
4 5 5 r 3
4 8 8 r 3
5 1 1 r 3
5 4 4 r 3
5 7 7 r 3
5 2 2 r 4
5 5 5 r 4
5 8 8 r 4
* 0 0 r *
* 6 6 r *
* 9 9 r *
* 3 3 r 0
* _ _ * halt
```
[Try it online.](http://morphett.info/turing/turing.html?9e662757c6f814b3ceb0464e715ec3ab)
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~27 25~~ 24 bytes
```
{max $_+1...{!/3/&$_%3}}
```
[Try it online!](https://tio.run/##K0gtyjH7n1uplqZg@786N7FCQSVe21BPT69aUd9YX00lXtW4tvZ/Wn6RgkZOZl5qsaZCNRdncWKlQpqGdq5@TIq2viZX7X8FBUMFXTsFBQUjLiCGME24FAwhooZAphFE1MgUyLQEM00MuIxMwQqMTE0A "Perl 6 – Try It Online")
Finds the first number larger than the input that doesn't have a three and has a remainder when moduloed by 3. I was hoping to do something fancy with the condition, like `!/3/&*%3` but it doesn't work with the `!`. `:(`
### Explanation:
```
{ } # Anonymous code block
$_+1 # From the input+1
... # Get the series
{ } # That ends when
!/3/ # The number does not contain a 3
& # and
$_%3 # The number is not divisible by 3
max # And get the last element of the series
```
[Answer]
# APOL, 51 bytes
`v(0 +(⧣ 1));w(|(!(%(⁰ 3)) c(t(⁰) '3')) ∆(0));-(⁰ 1)`
[Answer]
# Swift, 84 bytes
```
func f(_ n:Int)->Int{var n=n+1;while String(n).contains("3")||n%3==0{n+=1};return n}
```
] |
[Question]
[
Players of the traditional board game Go measure their skill in a [system of ranks](https://en.wikipedia.org/wiki/Go_ranks_and_ratings):
* Players new to the game are ranked 30th *kyū* (written `30k`) and progress **counting down** to 1st *kyū* (written `1k`). These are considered the *student* ranks.
* A player may promote from 1st *kyū* to 1st *dan* rank (written `1d`), and then progress **counting up** to 7th *dan* rank (written `7d`). These are the *master* ranks.
* Exceptionally skilled players past `7d` may promote to the 1st *professional dan rank* `1p`, and progress **counting up** to 9th *professional dan* rank (written `9p`). This is the highest rank.
In short: ranks are ordered `30k < 29k < ··· < 1k < 1d < 2d < ··· < 7d < 1p < 2p < ··· < 9p`.
# Task
Given two strings among {`30k`, …, `1k`, `1d`, …, `7d`, `1p`, …, `9p`} as input, output the **higher** rank of the two. (If they are equal, simply output either input.)
(As usual, [I/O is flexible](https://codegolf.meta.stackexchange.com/q/2447/3852) — your answer may be a function or a full program, reading input in any reasonable fashion and producing output in any reasonable fashion.)
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"): the objective is to minimize your code's byte count.
# Test cases
(Format: `input1 input2 output`.)
```
29k 9k 9k
21k 27k 21k
6d 1p 1p
5d 17k 5d
1k 1d 1d
1d 1d 1d
1d 2d 2d
9p 1d 9p
2d 30k 2d
1p 1k 1p
1d 1p 1p
1p 2d 1p
7p 8p 8p
30k 30k 30k
```
[Answer]
# JavaScript (ES7), 58 bytes
Takes the two strings in currying syntax `(a)(b)`.
```
a=>b=>(g=s=>parseInt(s)*'_dp'.search(s[1])**3)(a)>g(b)?a:b
```
[Try it online!](https://tio.run/##jdDdCoIwHIfh865iZ9uEsv/E0mB23DVExHRqpehw0u2b34WKdOSQh5ff9hJvoYPiqcptlsuwingluOdzj8Rcc0@JQoeXrCSaGvguFd7pUBTBg@gr3KhhWJQI6sXEp2dx8qsgz3Sehrs0j0lEMHMTTAnCzYci00TITTZTA43B7DiY@sfEIHyQbQfU0AE1M3ZjMIwdZMuZgW4PyLGzYOTfho2GzY2rJh13vpm1m619stKBvpOs3B3@eJ@@8928YI6dccaOMzXd2N/N9an6AA "JavaScript (Node.js) – Try It Online")
### How?
The helper function **g()** translate the input string **s** into a score.
1) We look for **s[1]** into the string **"\_dp"**. This gives:
* **1** for a *dan* rank **"xd"**
* **2** for a *professional dan* rank **"xp"**
* **-1** for a *kyū* rank **"xk"** or **"xxk"** because **s[1]** is either **"k"** or a digit
2) We cube this result, which leaves **1** and **-1** unchanged but gives **8** for a *professional dan* rank.
3) We multiply by the decimal part of the rank.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~11~~ 10 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
Inspired to go back to the drawing board by Arnauld!
```
⁾kNyv9FµÞṪ
```
A monadic link accepting a list of strings\* (as described) which yields the highest rank found.
* Also works with numbers other than two.
**[Try it online!](https://tio.run/##y0rNyan8//9R475sv8oyS7dDWw/Pe7hz1f///6PVDQvUddTNU9RjAQ "Jelly – Try It Online")** Or see a [test-suite](https://tio.run/##y0rNyan8//9R475sv8oyS7dDWw/Pe7hz1f@Hu7foPNyx6XC7isqjpjXu//8bWWYrWGZzGRlmKxiZZ3OZpSgYFnCZAkkgByhmmMJlmAIljVK4LAtAbKMUBWMDoDSQkw2WLgCxgdLmBQoWBVxAOZA8AA "Jelly – Try It Online").
### How?
Sorts by a key function and returns the rightmost (i.e. a maximum).
The key function first changes any **k** to become an **N** using the dyadic atom `y`, translate, with the two-character list `⁾kN` (Jelly code for `['k','N']`) and then evaluates the string as a monad with an argument of nine (by use of the code `v9`).
In Jelly:
* `N` is a monadic atom which negates its input
+ so the code `9 30N` does not actually use the nine and results in the integer `-30`
* `d` is a dyadic atom which yields the result of a Python divmod of two values - the pair of the results of integer division and modulo
+ so the code `9 7d` results in \$\lfloor \frac 7 9 \rfloor\$ paired with \$7 \pmod 9\$ which is `[0,7]`
* `p` is a dyadic atom which performs a Cartesian product, which includes implicit 1-indexed range-ification of its inputs
+ so the code `9 p3` yields the Cartesian product of `[1,2,3]` and `[1,2,3,4,5,6,7,8,9]` which is `[[1,1],[1,2],...,[1,9],[2,1],[2,2],...,[2,9],[3,1],[3,2],...,[3,9]]`
Once such evaluations have been performed using the strings to be compared we need to be able to compare the results; since ints are not comparable with lists we need to wrap the negated values in a list, but since the ordering would still work after the `p` lists are flattened (e.g. `[[1,1],[1,2],...]` -> `[1,1,1,2]`) we can use the single-byte monadic atom `F` applied to all evaluations.
A table of the inputs to their key-value is as follows:
```
in ⁾kNy ⁾kNyv9F
30k 30N [-30]
29k 29N [-29]
...
2k 2N [-2]
1k 1N [-1]
1d 1d [0,1]
2d 2d [0,2]
...
6d 6d [0,6]
7d 7d [0,7]
1p 1p [1,1,1,2,...,1,9]
2p 2p [1,1,1,2,...,1,9,2,1,...,2,9]
...
8p 8p [1,1,1,2,...,1,9,2,1,...,7,9,8,1,...,8,9]
9p 9p [1,1,1,2,...,1,9,2,1,...,7,9,8,1,...,8,9,9,1,...,9,9]
```
Code commentary:
```
⁾kNyv9FµÞṪ - Link: list of lists of characters
µÞ - sort by (Þ) the monadic link to the left (µ):
⁾kN - two-char list = ['k', 'N']
y - translate the current string (change 'k's to 'N's)
9 - literal nine
v - evaluate (the left) as Jelly code with the input as given on the right (9)
F - flatten the result
Ṫ - tail (get the rightmost, and hence (a) maximum)
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 14 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
OṪ|8-2*×ṖV$µÞṪ
```
A monadic link accepting a list of strings\* (as described) which yields the highest rank found.
\* Also works with numbers other than two.
**[Try it online!](https://tio.run/##y0rNyan8/9//4c5VNRa6RlqHpz/cOS1M5dDWw/OAQv///49WNyxQ11E3T1GPBQA "Jelly – Try It Online")** Or see a [test-suite](https://tio.run/##y0rNyan8/9//4c5VNRa6RlqHpz/cOS1M5dDWw/OAQv8f7t6i83DHpsPtKiqPmta4//9vZJmtYJnNZWSYrWBkns1llqJgWMBlCiSBHKCYYQqXYQqUNErhsiwAsY1SFIwNgNJATjZYugDEBkqbFyhYFHAB5UDyAA "Jelly – Try It Online").
### How?
Sorts by a key function and returns the rightmost (i.e. a maximum).
The letters \$k\$, \$d\$, and \$p\$ have ordinals \$107\$, \$100\$, and \$112\$ respectively. In binary \$107\$ has the eight bit set while the others do not, hence bitwise OR-ing with 8 we get 107, 108, and 120 respectively - these are now in the order required to sort the classes they identify.
The amateur ranks are in descending order so to complete our key function we could concatenate our class-identifier with the number given in the string, negating if the string ends in \$k\$ (e.g. `'7k'` -> `[107,-7]` while `7p` -> `[120,7]`). In the code this requires storing the class-identifier and exponentiating minus one for the multiplication - `OṪ|©8-*×ṖV$®,µÞṪ` - which is \$16\$ bytes.
To improve upon this we can use minus two instead and multiply the elements together, which may be achieved with a single multiplication.
```
OṪ|8-2*×ṖV$µÞṪ - Link: list of lists of characters
µÞ - sort by (Þ) the monadic link to the left (µ):
O - ordinals
Ṫ - tail
8 - literal eight
| - bitwise OR
-2 - literal minus two
* - exponentiate
$ - last two links as a monad (of the current list of characters):
Ṗ - pop (get all but rightmost character)
V - evaluate as Jelly code (gets the number)
× - muliply
Ṫ - tail (get the rightmost)
```
Table of the key-function's action...
```
in ṖV$ OṪ OṪ|8 OṪ|8-2*×ṖV$
30k 30 107 107 -4867778304876400901747340308643840 = ((-2)^107)*30
29k 29 107 107 -4705519028047187538355762298355712 = ((-2)^107)*29
...
2k 2 107 107 -324518553658426726783156020576256 = ((-2)^107)*2
1k 1 107 107 -162259276829213363391578010288128 = ((-2)^107)*1
1d 1 100 108 324518553658426726783156020576256 = ((-2)^108)*1
2d 2 100 108 649037107316853453566312041152512 = ((-2)^108)*2
...
8d 8 100 108 2596148429267413814265248164610048 = ((-2)^108)*8
9d 9 100 108 2920666982925840541048404185186304 = ((-2)^108)*9
1p 1 112 120 1329227995784915872903807060280344576 = ((-2)^120)*1
2p 2 112 120 2658455991569831745807614120560689152 = ((-2)^120)*2
...
8p 8 112 120 10633823966279326983230456482242756608 = ((-2)^120)*8
9p 9 112 120 11963051962064242856134263542523101184 = ((-2)^120)*9
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~30~~ ~~28~~ ~~25~~ 23 bytes
```
,0&)Uw'k'-tUw6*+qw*w]<G
```
[Try it online!](https://tio.run/##y00syfn/X8dATTO0XD1bXbcktNxMS7uwXKs81sb9/391wwJ1LnXzFHUA "MATL – Try It Online")
*(-2 bytes thanks to Luis Mendo)*
*(another -3 bytes replacing `v&X>` with `>`, this time based on Luis Mendo's answer)*
*(-2 bytes using `&)` syntax)*
### Explanation:
* Subtract 'k' from the last character (gives n = -7, 0, 5 for 'd', 'k', 'p' respectively).
* Compute v = n^2+6n-1 (gives 7, -1, 54 respectively).
* Multiply that value v by the actual rank number (so k levels get negative products, d levels go from 7 to 49, p levels from 54 and above).
* Do that for both input strings, compare the products
* Get the input string corresponding to the greater product
---
Alternate, more straightforward method: :
### 23 bytes
```
,0&)Uwo'dpk'1L6^XE*w]<G
```
[Try it online!](https://tio.run/##y00syfn/X8dATTO0PF89pSBb3dDHLC7CVas81sb9/391I9NsdS518xR1AA "MATL – Try It Online")
```
, % Do this twice (once for each input):
0&) % Split the input into number, last letter
U % str2num i.e. Convert '21' to 21
wo % Bring the letter out and change it to numeric (its ASCII code)
'dpk' % Push the array 'dpk'
1L6^ % Push [1 2 1j] and raise to ^6, giving [1 64 -1]
XE % Find the letter in 'dpk', replace it with its corresponding
% number from the second array (d=1, p=64, k=-1)
* % Multiply the number part by this
w % Switch to bring out the other input to top
] % End loop
% Stack has [second input's value, first input's value]
< % Is second input < first input? 1 or 0
G % Retrieve the corresponding input: 1 for 1st input,
% 0 for last (2nd) input
```
---
[Answer]
# [Haskell](https://www.haskell.org/), ~~73~~ 71 bytes
```
r(x,"k")=0-x
r(x,"d")=x
r(x,"p")=x+7
p=r.head.reads
a#b|p a<p b=b|0<1=a
```
[Try it online!](https://tio.run/##bY7fS8MwEMff81ccmYMEu9JWtG4sPongg@iDb05GSiIt/RXSqh3sf6/XdHNFB@G4@/C5by6VTa6Loi9r9VloeJJZxUosnHyn2mpCstLUtoVX3bX@i82q9uOI7mUr/Ye6UDIpNGut/NK20VveW9Z5NKdcBIuOuEHhcGjN0F7GxAjrp1oq32JpiJwlewNybSARyT5Yh0L2wx2wWsHjMzBO3CTg9x9gG8zbcVjcgXGHAZ03gA/BvNlUFDrYwQV0M5TeCACj0TKnHlCsHBB4SEJHohjRSG7UAEK8Ew7O9Uji09a4FKqTE6rzJJqQpfnrRM65CibJo5P/S57cMzrT5NiR24kzZB6jkbyT/gc "Haskell – Try It Online")
As usual for me, just a straight forward implementation rather than anything particularly golf-y. The "(#)" function takes two ranks as strings and returns the larger one. Works only with exactly the format specified in the question.
(I've also tried a version using `comparing` and `maximumBy` but that ended up being 3 bytes longer - damn you `base` and your occasionally human readable function names!)
(Applied suggestions by Amphibological and Lynn)
[Answer]
# [Python 2](https://docs.python.org/2/), 54 bytes
```
lambda s:max(s,key=lambda x:(int(x,27)%9-3)*int(x,26))
```
[Try it online!](https://tio.run/##fY1BDsIgEADvvqIXA5iayDYWadKXqAcMNhpsJbYH@noU6KEB4mWTnZ3s6Hl6vAewXXuxL9HfpCjGphcGj6W6z@2CTIOfw4RNCYxs@b4iu2WtCbH645YOnxFwhcoC/eaVkM2KU8@BxYdaOk51hI8BJ3p4Q2WM5R8MMeY6a4O3q0PSDLrKN3XWTprM41Nsu1o2ylbf7Rc "Python 2 – Try It Online")
Using [Arnauld's method](https://codegolf.stackexchange.com/a/168155/20260). The mapping `int(x,27)%9-3` only depends on
the last letter of `x`, since all digits but the last one contribute a multiple of `9`. It takes:
```
'k' -> -1
'p' -> 1
'd' -> 4
```
This is barely enough margin for the multiplier for `1p` to beat `7d`, the highest dan rank, when interpreted in base 26.
I found this by brute-forcing expressions of this form and a few others.
---
# [Python 2](https://docs.python.org/2/), 64 bytes
```
lambda s:max(s,key=lambda x:(ord(x[-1])|8,int(x,36)^-('k'in x)))
```
[Try it online!](https://tio.run/##fc3fCoMgGIfh811FZ/qBwTTWP@hKWoOGi4XLpDow2L27lYMNlZ148Hwv/tS63EfJTFedzaMdrryN5nJoNZ6JuK3Vh3SJx4ljXce0gWdOerlgTZIULjFGAvUy0gBg1LQdOlwjVghEIvR@G4DDj9PdWeYeUr45VQ6fLHu5/YZyl/kfZi4XKlizvU6O3qbNRXhTBWtvM9s5d@tt7TtqXg "Python 2 – Try It Online")
[Answer]
# [R](https://www.r-project.org/), 73 bytes
```
function(v)v[rank(as.double(chartr('dp','.0',sub('(.+)k','-\\1',v))))][2]
```
[Try it online!](https://tio.run/##bYxBDoIwEEX3XmSmEQmtUWThSYBFaSUaTGkK9Pq1rdGCcRaTvPdnvnH91fWLEvNjVGiJrQ1XA/Ipl@PSPW8o7tzMBkFqyCAvIJuWDgHzPRm8ODQNhcwSP23NWtejQGBViPwiZPcWNAhWJnOWXlD95VPk1UH8oDKx/MMscaW3OQv5sVgVxoPhp1Bv81VhGfiS8tD1aXQv "R – Try It Online")
* I had to use `as.double` instead of `strtoi` since the latter doesn't handle spaces/points and I couldn't think of another valid character to replace `d`
* -1 byte using `rank` instead of `order`, since they are equal when there are only two elements
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 13 bytes
This is quite different from my [other Jelly answer](https://codegolf.stackexchange.com/a/168173/58563), so I'm posting this separately.
Takes input as a list of two (or more) strings.
```
“kNdHp0”yVµÞṪ
```
[Try it online!](https://tio.run/##y0rNyan8//9Rw5xsvxSPAoNHDXMrww5tPTzv4c5V/w@3P2pa4/3/fzSXgkK0upFltrqOOpCI1QFyDEEcI3MIzywFyDEsALNNwWyoBFiVYQqEnYLGNoKwLQsQ4kYgcWMDqGawRDaS5gKEOFSzOYhtAREH6YPq5ooFAA "Jelly – Try It Online")
### Commented
```
“kNdHp0”yVµÞṪ
“kNdHp0” - literal string
y - translate each rank character into a Jelly instruction/symbol:
'k' -> 'N' = negate
'd' -> 'H' = halve
'p' -> '0' = a literal zero
V - evaluate as Jelly code
examples:
'21k' -> '21N' -> -21
'7d' -> '7H' -> 3.5 (*)
'3p' -> '30' -> 30
µÞ - sort the input using all of the above
Ṫ - return the second entry
(*) we don't really need to halve these values, but we do want to get rid of 'd'
```
[Answer]
# Julia 0.7 ~~100~~ 93 bytes
It is not the most efficient way, (contrast @sundar's [Julia 0.6 answer](https://codegolf.stackexchange.com/a/168154/4397))
but it is nice because it is purely numeric.
Also uses dispatch (though sadly only once)
```
!z=(-z%2+.9)z*z
s(x,y,z)=(10x+y)*!z
s(x,z)=x*!z
~r=s(Int[r...]...)
a|b=[a,b][argmax(.~[a,b])]
```
Very similar code works in 0.6 [Try it online](https://tio.run/##ldBBa8MgFAfwu5/CCgNtM6mOtc1BGNtp991CDmaRzmULpVpIpfSrZ0YtrAfpJsSnjx//8Pw8fGm5GseZE/je3fEFLYmbO2DwUBwLRwRmy2FxJPNZ7PnOMJ3Pe2Hwa2@rPaW09h8B8tSIShZNXem@/ZYDpudwJfV4MLrfwmdpFH1TxoIn63ejLEQvH@q9g9oi2Kit7gG8XgFCxMsOwRNEUxEi1JxkUfJ1olMjY1dtoGwXpa8Z@JjgJdPfMzL9nbUpMg/b/0GeIM/CcneVWGan4THxYdndimQpsrv1QOyvL5kSL9Pk4TrCTUrcZGEY4/c40wGovh1/AA)
### How:
The trick is all in the `!(z)` function.
It maps the UTF-8 value:
* for `k` into a negative number, so it sorts backwards
* for `d` into a positive number
* for `p` into a larger positive number
As shown:
```
julia> !(Int('k'))
-1144.8999999999996
julia> !(Int('d'))
9000.0
julia> !(Int('p'))
11289.6
```
### Test results
```
julia> @testset "Check it" begin
@test "29k" | "9k" == "9k"
@test "21k" | "27k" == "21k"
@test "6d" | "1p" == "1p"
@test "5d" | "17k" == "5d"
@test "1k" | "1d" == "1d"
@test "1d" | "1d" == "1d"
@test "1d" | "2d" == "2d"
@test "9p" | "1d" == "9p"
@test "2d" | "30k" == "2d"
@test "1p" | "1k" == "1p"
@test "1d" | "1p" == "1p"
@test "1p" | "2d" == "1p"
@test "7p" | "8p" == "8p"
@test "30k" | "30k" == "30k"
end
Test Summary: | Pass Total
Check it | 14 14
Test.DefaultTestSet("Check it", Any[], 14, false)
```
[Answer]
# [Haskell](https://www.haskell.org/), 64 bytes
```
r[(n,[c])]=n*(gcd(fromEnum c)28-3)
g=r.reads
a%b|g a>g b=a|1>0=b
```
[Try it online!](https://tio.run/##XU9db4IwFH3vr7ghM2mlMMFsihHf9itYH0pBJEBtCsYs4bePlZZM40tzPu45vffC@6Zs22nSGZY0E4ywVK5xJQp81tfuS946ECTeB1uCqlSHuuRFj/gqHyvgpwrylI/RaZPmk@ay6SGFrL9c7yB932u8UR6DbLuhcRKGEWPg@0924ewoDHevlvq3EsaQ4rW2zZjTnMAI/KDhGEAvuNSADwQyBu57CvnsaIbu@iorEzrX7VCaqW8XDk5glof3FAyxxQgNZT@4fi9OGo965iHUkGgm8c6xz8KQSFn8YfFi2KmocLh4wbHDiXro8axvN0vYGs1TWD30Jbyb8d7pc25JM9TxWpq9la7lAG@A7c0UOq4A36S4af0DeEUI2AvJ9CvOLa/6KRBK/QE "Haskell – Try It Online")
The expression `gcd(fromEnum c)28-3` maps the character to a multiplier
```
k -> -2
d -> 1
p -> 25
```
The idea was to take their character values `[107,100,112]` and choose `28` to have increasingly large factors in common with them, made easy but the first one 107 being prime. This method saves 2 bytes over explicitly [writing out a mapping](https://tio.run/##XU9rb4IwFP3eX3HTzATGYxazMdT6R1izlIdIwFoKxizht4@Vlkzjl@Y87jm998T7pmzbaeqwxDTZdbjAlOw6@KYQEKRSR/i5y6h47SBHFVWhKnnRI77Kxgr4oYKM8pEc1jSbFBdNDxTS/nS5gfA83OBR7IN0s/ajJAwJY@B5D3ZhbRKG8bMl/62EMSR5rUyzw/3MhRH4VsE@gD7nQoGzdSFlYL/3IZsdxdBNXUSlQ8e6HUo99WXDwQH08vBGQRNTjNBQ9oPtx1HSYB/rx/U1ITOJYss@Ck2INPjd4MUwU6SwuHjCkcWJvOvRrG/WS9gYzUNY3vUlHM/40@pzbkkzdOa10HtLVYsBXsAxN/tw5hKcq8ivSv2As3JdMBe6029@bHnVT0Eu5R8).
The built-in [`reads`](http://hackage.haskell.org/package/base-4.12.0.0/docs/Text-Read.html#v:reads) is used to separate the number and rank.
```
Prelude> reads "25k" :: [(Int, String)]
[(25,"k")]
```
(Actually, the direct splitting [from Sara J](https://codegolf.stackexchange.com/a/182564/20260) is one byte shorter, giving [63 bytes](https://tio.run/##XU/JboMwEL3zFSOUSHZZGkBtQhRy61ekPgxLCAIcyyaKKvHtpcZGTZSL9ZZ5zzMXVG3VddNUg8pkhSVpeDOAom@kLkpyltf@i9/6VYdqVuNdkFAH1/lYAx5ryDMco@MmyyeJvFWQwUldrnfgnue27sgPwSnZ@HEahhFj4HlPdmntKAy3r5b4t1LGHIGNNM0E/ZzCCLiXcAhAFcglkD2FEwP7vQ/57Ejm3OWV1zp0brqh0lPfNhwcQS8P7xloYoodZ6jUYPvdOG1d39UP9TWJZhJvLfssNYmEwR8GL4aZikqLyxccW5yKhx7PerJZwsZon8LioS/h7Yx3Vp9zS5o5PTZc7y1kwwdYATE3@9CjAHLjxU3KHyBrSsFcSKff4txhraagEOIP).)
The take-the-bigger-one step takes an annoying number of bytes in my solution. I tried other approaches like iterating over ranks in decreasing order and taking the first one that's an element of `[a,b]`, but they turned out longer.
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~28~~ 27 bytes
```
,w'kdp'X{'*-1 . *8'YbYXU]>G
```
[Try it online!](https://tio.run/##y00syfn/X6dcPTulQD2iWl1L11BBT0HLQj0yKTIiNNbO/f9/dSPLbHUudSABAA) Or [verify all test cases](https://tio.run/##y00syfmf8F@nXD07pUA9olpdS9dQQU9By0I9MikyIjTWLt79v0vIf3Ujy2x1LnUwYWQIJs1BpFkKkDAsABKmYBZYECxvmIJJGIEIywIUrrFBNswIJH0FMAKsxhzEsiiAqwaRAA).
### Explanation
```
, % Do twice
w % Swap. Takes implicit input
'kdp' % Push this string
X{ % Split chars: gives cell array {'k', 'd', 'p'}
'*-1 . *8' % Push this string
Yb % Split at whitespace: gives cell array {'*-1', '.', '*8'}
YX % Regexprep: replaces 'k' by '*-1', 'd' by '.', 'p' by '*8'
U % Convert to number: evaluates string
] % End
> % Greater than? Gives a result r which is 0 or 1
G % Push r-th input (modularly: 0 is last, 1 is first)
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 16 bytes
Takes input as a list of two strings.
```
OṪ²²%90’’×ṖV$µÞṪ
```
[Try it online!](https://tio.run/##y0rNyan8/9//4c5VhzYd2qRqafCoYSYQHZ7@cOe0MJVDWw/PA0r9P9z@qGmN9///0VwKCtHqRpbZ6jrqQCJWB8gxBHGMzCE8sxQgx7AAzDYFs6ESYFWGKRB2ChrbCMK2LECIG4HEjQ2gmsES2UiaCxDiUM3mILYFRBykD6qbKxYA "Jelly – Try It Online") (all test cases)
### How?
The ASCII code \$c\$ of the rank character is converted to a multiplier \$m\$ with the following formula:
$$m=(c^4 \bmod 90)-2$$
Which gives:
```
char. | ASCII | **4 | mod 90 | -2
-------+-------+-----------+--------+----
'k' | 107 | 131079601 | 1 | -1
'd' | 100 | 100000000 | 10 | 8
'p' | 112 | 157351936 | 76 | 74
```
### Commented
```
OṪ²²%90’’×ṖV$µÞṪ
OṪ²²%90’’ - process the rank character takes a string, e.g. '28k'
O - get ASCII codes --> [50, 56, 107]
Ṫ - pop --> 107
²² - square twice --> 131079601
%90 - modulo 90 --> 1
’’ - decrement twice --> -1
ṖV$ - process the decimal part
Ṗ - remove the last character --> '28'
V - evaluate as Jelly code --> 28 (integer)
× - multiply --> -28
µÞ - sort input using all of the above
Ṫ - return the second entry
```
### Alternate formula
For 16 bytes as well, we can use:
$$m=((c-1)^9 \bmod 64)-1$$
```
OṪ’*9%64’×ṖV$µÞṪ
```
[Try it online!](https://tio.run/##y0rNyan8/9//4c5VjxpmalmqmpkA6cPTH@6cFqZyaOvheUCJ/4fbHzWt8f7/P5pLQSFa3cgyW11HHUjE6gA5hiCOkTmEZ5YC5BgWgNmmYDZUAqzKMAXCTkFjG0HYlgUIcSOQuLEBVDNYIhtJcwFCHKrZHMS2gIiD9EF1c8UCAA "Jelly – Try It Online")
[Answer]
# JavaScript (ES6), ~~55~~ 54 bytes
-1 byte thanks to @Shaggy
```
a=>b=>(s=x=>parseInt(x)*~-{p:9,d:2}[x[1]])(a)>s(b)?a:b
```
[Try it Online!](https://tio.run/##jdDdCoIwGIDh8y7Doy0q2qL8gdlx1yAeTKdRig4nIUTdurF9QjImdbKPwcO7nzt/cJV3N9lvm1YUY8lGzuKMxUixgcWSd6q4ND0a8Pq9fcoo3IiIvpIhIWmKEcexQhk@8ygb87ZRbV3s6vaKSuTRsPIw8vTKmBkrWxAjqA/EbG1zEpoQaYQeNjgCmBp6Zws4hQhIuID4C1AA1AHovOACoZyBUC4VDvtqMUEgUS3@BPn1VVCYnuECvgEBFAIHMPf7XtPM8QM)
## Explanation
```
a=>b=>
(s=x=> // Function s(x), that converts x to a "score", where a higher
// rank gets a higher score by
parseInt(x)* // taking the integer part of x and multiplying it by
~-{p:9,d:2}[x[1]]) // ~-9 (8) if it is a professional rank, ~-2 (1) if it is a dan
// rank and ~-undefined (-1) if it is a kyū rank by looking up
// the second character of the string
(a)>s(b) // Compare s(a) and s(b)
?a:b // and return the one with the biggest score
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~52~~ 46 bytes
```
->s{s.max_by{|x|(5-x[-1].ord*5%8)*x.to_i(26)}}
```
Straightforward port of xnor's answer.
[Try it online!](https://tio.run/##lYtLDoIwGIT3nuLfGFpSGlvDa6EXMYYABSXF0NCSlABnr0W9gJvJzHwz41TNzkVXvWj6Km1RzctqVxRH9haxOx1GEcbHDIeWmqHoEE/wtrn28t/h8GiMplr1nUEBCTBtyvoJ@w/UZDS0tC77HtnvBG/geC4hl4QzCTyVJBHAFIm9@uA7JggTP@WC5Gr3XMD55LEP8oPV7j1OFWSKeLZzAHgD "Ruby – Try It Online")
*EDIT: -6 bytes by realizing I could have used a Proc*
[Answer]
# [C# (Visual C# Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), ~~136~~ 135 bytes
```
a=>b=>{string c=a.PadLeft(3,'0'),d=b.PadLeft(3,'0');int x=c[2]-d[2];return(x==0?c.CompareTo(d)*(c[2]=='k'?-1:0)>0:x==5|x>9|x==-7)?a:b;}
```
[Try it online!](https://tio.run/##nY9Pa4QwEMXvforgxaSoqMvWqo0eFnrawkILPZQeYhJLcDeKyRbLrp/d@ufUpQftHGbCm/nx8qhyqKI9PRKlwMG4GGAopYkWFHxVgoFnIiREkzwvx3r5Vpqf3KezpI9KN0J@2n9q80xTUADcE5zmOL3MGqCYuAfC9rzQcGNbnoVshvMbKRFSgxbT9@DDYUNLGq7PjYQtxl5G3V11qknDXyvI0B0crzC2Sitz/NhDqRcPZ9trm0bX4eGEKCNxnnR9Ytzm2FVSVUfuvjVC872QHBbQDKLSRNAcO0qWEf5EBOFy5J6NhF8vBrYTsMJh/pPPlgPsX0CwHIjqlQ7B5LDxVqSeLcq1qeuVDitShxPwsNxhyvs7dmd0Rv8D "C# (Visual C# Compiler) – Try It Online")
-1 Byte thanks to TheLethalCoder
**Expanation:**
```
static void Main()
{
System.Func<string, System.Func<string, string>> f =
a => b =>
{
string c = a.PadLeft(3, '0'),
d = b.PadLeft(3, '0'); //Pad the input with leading '0' to be 3 characters long
int x = c[2] - d[2]; //Calculate the difference of the letter characer (the character at index 2) as integer
return //return ...
(x == 0 ? //if the letter of the inputs is the same...
c.CompareTo(d) // compare the padded strings resulting in a positive number if the first input is greater or a negative number if the first input is lower
* ( // multiply the result by...
c[2] == 'k' ? -1 : 0 // if the letter is 'k' then -1 else 0
) > 0 // check if the result is greater than 0
: //else (the letters are not the same)
x == 5 | x > 9 | x == -7 // check if the letter difference was 5 (input p and k) or 12 (> 9, input p and d) or -7 (input d and k)
) ? a : b; // then return the first input else return the second input.
}
;
System.Console.WriteLine(f("29k")("9k"));
System.Console.WriteLine(f("21k")("27k"));
System.Console.WriteLine(f("6d")("1p"));
System.Console.WriteLine(f("5d")("7k"));
System.Console.WriteLine(f("1k")("1d"));
System.Console.WriteLine(f("1d")("1d"));
System.Console.WriteLine(f("1d")("2d"));
System.Console.WriteLine(f("9p")("1d"));
System.Console.WriteLine(f("2d")("30k"));
System.Console.WriteLine(f("1p")("1k"));
System.Console.WriteLine(f("1d")("1p"));
System.Console.WriteLine(f("1p")("2d"));
System.Console.WriteLine(f("7p")("8p"));
System.Console.WriteLine(f("30k")("30k"));
}
```
[Answer]
# Perl, ~~46~~ 38 bytes
```
s/p/0/g;s/\w*k/-$&/g;/ /;$_=@F[$`<=$']
```
Run as `perl -pae '...'`. Takes input from stdin, space-separated on one line.
Performs a couple of substitutions to make comparison "easier". The regexp substitutions essentially amount to replacing `p` with a trailing zero and `k` with a leading negative sign. So `10k` becomes `-10` (so the ordering is reversed) and `3p` becomes `30` (so that `p` is above everything else). Then it's just a simple numerical comparison.
Thanks to DomHastings for the `$`` / `$'` suggestion, which shaved off 8 bytes.
[Answer]
# [R](https://www.r-project.org/), ~~65~~ 62 bytes
```
`+`=paste0;max(ordered(scan(,""),c(30:1+"k",1:7+"d",1:9+"p")))
```
[Try it online!](https://tio.run/##bYzRCoIwFIbvewo5N57DlrhFmVbvomwKIelQAyF69uWkmkY3O3zf/@/vbBWct0F1b9RwbRsc6dGrolm5KIpotDnLL6bohzI@3YoR206XXanRtZEDEFe4izPBoAYusoSBdjdlYICI7HNTocJQpnXIw@khegvhhEy8OehJCPPl/cyLwvxDaM/6D0vPqVnn0uW7eDE4F@qfQbPOF4OJ46PP3dZn0b4A "R – Try It Online")
This comes in a bit shorter than the previous R answers, and makes good use of R's statistics functionality :-)
*-3 bytes thanks to [Robin Ryder](https://codegolf.stackexchange.com/users/86301/robin-ryder)'s suggestion to use* `ordered` *instead of* `factor`
Takes input from stdin (although the TIO link restructures slightly for ease of testing). Casts the input ranks into an *ordered* `factor` of all ranks, then takes the max.
Output looks like:
```
[1] MAX_RANK
46 Levels: 30k < 29k < 28k < 27k < 26k < 25k < 24k < 23k < 22k < ... < 9p
```
[Answer]
# Java 8, ~~128~~ ~~122~~ 121 bytes
```
a->b->g(a)<g(b)?b:a;float g(String s){return("kdp".indexOf(s.charAt(s.length()-1))-.9f)*new Byte(s.replaceAll(".$",""));}
```
-6 bytes thanks to *@SaraJ*.
[Try it online.](https://tio.run/##jZNBT8MgGIbv/gpCPIC1ZJ3RuXWrmQdvxoNH3YEVWlmRkvarupj99gndnNpU4wXIw/u9b4GvK/7Cw5UotqnmdY1uuTLvRwitHGYNKM2yxqSgSsNu9ovpPVTK5Kf/0uzmJEEZmm15mCzDJCecTnOypFfLCY8zXXJAOdkJUU3fKwlNZQguhMVMGSHf7jJSs/SJV3NwCy1NDk@EhhGlIRtn9MTIV3S9Buk2K2k1T@Vca4LZMT7FmNJ4s3Unss1SqxTVwMFNL6US6Nkddh/8sECc@oMjBLIGgofjwlW7gcbfaeTpcNTBF8LRyP6E5y3sSluDSHSg@A0OO3Bse5RDrzwbdJNaadGXZHuU3aSRh5cdpQ85RLX8fl2DfGZlA8y6iwRtyL4iKyviAFKzs0GsklkUqzCk7VZvmQpwMUE48K/p25BQlrfQP2HHMYqRms5GbgyCvy1Fn6X41XL8D0vbZ2n3lht/Ld@brL24XZMxxg5d1mP99T/Nq4qvawblrs79MAGePMKP1Ixxa/Wa8IfBgh7W0eLzMzbbDw) (See the bottom of the output in the TIO-links to see the mapped values.)
**Explanation:**
```
a->b-> // Method with two String parameters and String return-type
g(a)<g(b)? // If the mapped value of `a` is smaller than `b :
b // Return input `b` as result
: // Else:
a; // Return input `a` as result
float g(String s){ // Separated method with String parameter and float return-type
// (This method maps all possible Strings to a value)
return("kdp".indexOf( // Take the (0-based) index in the String "kdp"
s.charAt(s.length()-1)) // of the last character
-.9f) // After we've subtracted 0.9
*( // And multiply it with:
new Byte( // Convert the String to an integer
s.replaceAll(".$",""));}// After we've removed the trailing character
```
[Answer]
# [Haskell](https://www.haskell.org/), ~~75~~ ~~70~~ 68 bytes
```
g k=read(init k)*(abs(fromEnum(last k)*2-209)-8)
a?b|g a>g b=a|1>0=b
```
[Try it online!](https://tio.run/##dZI9b4MwGIR3fsUJdbALSIGqTahqOnVrp45RBrt2EsSnwCgZ8t@pMYGkUbOcXj8@n0@y97zNVJ73RSW7XOGLpyUOe9WofoeMNYpLkpapRkYfCRct2TZV8VF2Bcl5a2kURIuYBivq8Hdx2oEnOwjGT2GyYKLXyrg4BNSxVj9aSQc4gRgrBWMzBQP3PNeH63nCDAiSYfxzqNKm1iFt1R2zDR2WZDr2ep1hdqjrOEOh1iSsTSZA3CjOXN@dhPoTDgcSLa2GVxsv0pCwHmWmz5ZatxlnbENCOcqFyrs0OstM43ryxlfXWdvTIrsxj7Wym27hv40tiOQNXQ50dZaZjjddlFq@cZxi@C0M2yqXDUiSUJBG6a4pQSjFuu70t24@Szxg/gdH@/y@8I8Ub4Hl7ab/BQ "Haskell – Try It Online")
`-5 bytes` thanks to @Laikoni
`-2 bytes` thanks to @ASCII-only
[Answer]
# [Python 2](https://docs.python.org/2/), 61 bytes
Uses Arnauld's algorithm.
```
lambda c:max(c,key=lambda i:'_dp'.find(i[-1])**3*int(i[:-1]))
```
[Try it online!](https://tio.run/##fY3dCsIgHEfve4rd6WRFOmpN2JOsCJtJYlsSu2hPb34EhUo3wu/8Dx69zLfHRIzojubOxgtnxUBH9oJDpa5L90GSgjPXYCPkxKHs1/hUIlQjOc12UTdLo59uCtgD0ipQFcC@lq9@OPacNPFhzx3HOsK7gBM9fIN5jPkfTGLc6qxNvF1vk2bQVb6ps3bSbDw@xLarfaPmDQ "Python 2 – Try It Online")
---
### Previous answer, 73 bytes
```
lambda c:max(c,key=lambda i:('dp'.find(i[-1]),int('-'*('k'in i)+i[:-1])))
```
[Try it online!](https://tio.run/##fY1BDoIwEEX3nqK7abUYWyMICSdBF0glTiq1MSzk9JUWE00hbmbx/ss8O/S3h5GuLU/uXncXVZOm6OoXbbi@DuUHYUFBWdi2aBTFKhFnxtH0FBJYU9CAhiDbYFX4hTFnn35taQUy18AJjHccVj9cBC6zeEiV58JG@DDhmT69ESrG6g@WMc7toi2Dvd/NmpOul5t20Z41s4CPse1r36h7Aw "Python 2 – Try It Online")
[Answer]
# [Julia 0.6](http://julialang.org/), ~~75~~ ~~71~~ 65 bytes
```
S->S[indmax((s->parse(s[1:end-1])*(search("_dp",s[2])-1)^3).(S))]
```
[Try it online!](https://tio.run/##DcpRCoQgEADQq8R8zUQGFgQF2yX8FAtJI6MVcQq6vbvv@53PFexQ9k9RYlY6RPe1LyKLOdnMHlnLyUcnpKEa2du8HQirS9Cw7gwJSUtPLSoiU1IO8b4i7qih@48KRgeGqCo/ "Julia 0.6 – Try It Online")
*(-4 bytes, parse in 0.6 auto detects it as Int)*
*(-6 bytes, use `(search("_dp",s[2])-1)^3)` based on Arnauld's JS answer, instead of `((c=cmp(s[end],'k'))^2*6+4c-1)`)*
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 29 bytes
```
O$^`.+((k)|(.))
$3$&$*1$2
1G`
```
[Try it online!](https://tio.run/##K0otycxL/P/fXyUuQU9bQyNbs0ZDT1OTS8VYRU1Fy1DFiMvQPeH/f8tsLssCLvNsLvMULvMCAA "Retina 0.8.2 – Try It Online") Accepts any number of ranks and outputs the highest. Explanation:
```
O`
```
Sort the lines...
```
$
```
... using the specified key...
```
^
```
... in reverse order.
```
.+((k)|(.))
$3$&$*1$2
```
The key is created from the input line as follows: a) the (professional) dan rank letter b) the rank in unary c) the kyū letter (where applicable). Since this is a reverse sort, the professional dan rank `p` sorts before the dan rank `d` and the kyū rank which starts with `1` because the kyū letter is left at the end. Within the ranks the (professional) dan ranks sort in descending order due to the length of the unary string, however the trailing `k` for the kyū ranks causes them to sort in ascending order.
```
1G`
```
Select the first line, which is now the greatest rank.
[Answer]
# J, 39 bytes
```
[`]@.(<&(".@}:((*_1&^)+]*0=2&|)a.i.{:))
```
[Try it online!](https://tio.run/##dc7LCsIwEAXQfb9icNEm1YYmUvvAQkFw5cqt1AfWonZh9uq316QZLYEYCMlwuMO99xMWtFAWEMAMYijUjRistpt1vzvWFSNLn0xY9S4ICQ/c39NpHcal8F/0xG7sWVDaU@9yvj4gyLsAIrVI6E87zCiCf4kbEql6AZC5NLpoBtQjjJo0RhNUE/1lUXGxHl3auFTYKmzNsZV@/2eFyc5juxVmOWY7u5W0W0m3SlerDDU1mtnZoYbm4TP28tTpPw "J – Try It Online")
## explanation
```
[`]@.(<&(".@}: ((* _1&^) + ] * 0 = 2&|) a. i. {:)) entire phrase
[`]@.(<&( assign a rank number ))
<& "less than" of the ranks of the left and right args
ie, return 1 if right arg rank is bigger
[`]@. if so, return right arg. otherwise left
breaking down the rank number part now...
( assign a rank number )
(".@}: ((* _1&^) + ] * 0 = 2&|) a. i. {:)
(".@}: ) everything but last char, convert to number
( a. i. {:) index within ascii alphabet of the last char
these become the left and right args to what follows...
( ((* _1&^) + ] * 0 = 2&|) )
( ( ] * 0 = 2&|) ) the right arg * "is the right arg even?"
because only 'k' is odd (107), this will be 0 for 'k'
and will be 100 for 'd' and 112 for 'p'
( ((* _1&^) ) ) left arg (number of go rank) times _1 raised
to the ascii index. this will swap the sign
for k only, hence producing a valid rank function
```
[Answer]
# [Python](https://docs.python.org/), 59 bytes
```
lambda s:max(s,key=lambda x:(-2)**(ord(x[-1])|8)*int(x,26))
```
An unnamed function accepting an iterable of strings which returns a maximal one by Go rank. Works much like [my Jelly answer](https://codegolf.stackexchange.com/a/168185/53748) (just uses the whole string evaluated as an integer in base 26 to save bytes).
**[Try it online!](https://tio.run/##XY/NDoIwEITP@hS9dZdUQ0vkL/FJxAOmEA0CDfSAUZ4d6U@C8bL7zezOYdRL3/suWupzsTzL9iZLMuZtOcHImup19taUw0FgEEA/SJguB37FT4rBo9MwMREjLnU/EF2Nmjw6AkBF1lBG14FsFdwIkTgVy1VwZflk2R/sF5eO5R8Lx5nafGH8KPRhe2h@wmrzfTgxnDrf5Hwa8/1ODaYLffO50G9hRjjT41qqLTXUYJohI4HduHwB "Python 3 – Try It Online")**
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 35 bytes
```
*.max: {{+TR/pd/0 /}(S/(.+)k/-$0/)}
```
[Try it online!](https://tio.run/##VY3NasMwEITveopBmCDVrmWp5McxoQ/QQ6HtsRfHUiEoTtTk0BjjZ3fXVQKpENr9dmZHwZ32i7HtZm4zPuRtfVmj79OPNxWsKqAG8a5EnkqvHpNCyWGsWN92SOoMU9nG0lRM0IgwaSQ2yJtjuxXq8ydVsmLnugNPanKvyYpn8GzmRFyQMuN4feG4IBV3U7hv8soBX8cTuCk96NIpPTPawywnoo4tLHSYFCpsTvCnYG4Z2bSNCoH9DyaCsawMN6UMjMZPhb8qlKv9LVrf/0PdNYBgGbCKyiqwaTsm0Mvz/e7gztX4Cw "Perl 6 – Try It Online")
A rather different approach to all this search-and-cube stuff. Essentially string replacement: `...k -> -...`, `p -> 0`, `d` deleted. Thus newbies get a minus score, dans get their rank and pros get rank\*10. Using the WhateverStar gets us a closure, and `max` takes a comparator function.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 12 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
Σ'pK°.Vyþ*}θ
```
`.V` (evaluate as 05AB1E code) is inspired by [*@Arnauld*'s similar approach in his Jelly answer](https://codegolf.stackexchange.com/a/168211/52210).
Input as a list of two (or more) of the valid strings.
[Try it online](https://tio.run/##yy9OTMpM/f//3GL1Au9DG/TCKg/v06o9t@P//2gl4wIlHSWTbKVYAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/c4vVC7wPbdALqzy8T6v23I7/Ov@jo5WMLLOVdJSARKwOkGMI4hiZQ3hmKUCOYQGYbQpmQyXAqgxTIOwUNLYRhG1ZgBA3AokbG0A1gyWykTQXIMShms1BbAuIOEgfVHcsAA).
**Explanation:**
```
Σ # Sort the (implicit) input-list by:
'pK '# Remove "p"
° # Take 10 to the power this string
# (if the string is not a valid number, the string remains unchanged)
.V # Evaluate the string as 05AB1E code
yþ* # Multiply it with just the digits of the string
}θ # After the sort: pop and push the last element
# (which is output implicitly as result)
```
* `k` pops a list and an item, and pushes the index of the item in the list. Since the stack doesn't contain a list, `"30k"` through `"1k"` will always result in `-1`. Multiplied by their number, it will be the range \$[-30,-1]\$.
* `d` checks if a number is non-negative (`>= 0`). Since this is truthy for all, `"1d"` through `"7d"` will always result in `1`. Multiplied by their number, it will be the range \$[1,7]\$.
* Removing `p` and using `°` will use 10 to the power \$a\$ if \$a\$ is a valid number, otherwise \$a\$ remains the same. So if \$a\$ is `"2k"` or `"2d"`, it will remain `"2k"` or `"2d"` after using `°`, but `"2"` (since we've removed the `p`) with `°` will become `100`. Multiplied by their number, `"1p"` through `"9p"` will be the list \$[10, 200, 3000, 40000, 500000, 6000000, 70000000, 800000000, 9000000000]\$.
[See all mapped values here.](https://tio.run/##yy9OTMpM/W9s4KOefWh1kLmPesqh1YdWW/qoF4Doskp7JYVHbZMUlOz/V6oXeB/aoBdWeXif1n@d/wA)
[Answer]
# [Scala](http://www.scala-lang.org/), 307 61 54 bytes
Great thanks to **Kevin Crujissen** and **ASCII-only** for their work on this answer, that got it down ~250b.
Some algorithm optimization for ordering function of 61b answer.
```
l=>l.maxBy(s=>s.init.toInt*(math.abs(s.last*2-209)-8))
```
Test cases here: [Try it online!](https://tio.run/##jdFPa4MwGAbwez9F8JR0rTQZrTqw0B0GO@y0Y90hNXZztTGYbLSMfXYX/0Ghee1OCg8/n5dHnfKC1@XuM0sNeuG5RNnJZFJotFHqZ4LQN6/Q/gE9fcnU5KWk201V8fP21VS5fH@bof4lrot4XfhHfno8Yx2vtZ/L3PimfJZmio/cfPh8p7H2C67NlM3ZIiLzkJBaWW4Kib09br@ME49Fh8SbocRrnoSgGHl3Q9qENrORTcjEpWmvWeDitOU2g/xKdJyqa70SDaYKssvBuqqXHYabh8OpuMbd2VSAVoxY8T/LQMtAGym4N1LjvazvvV@4flRbbCPw6qHZgWnXfLi5lgLXUrd6nWup8bWC3oaO3qC1IdjbrgTO1Qx1sddv/Qc "Scala – Try It Online")
# Old 61 bytes answer
```
l=>l.maxBy(s=>(s.init.toInt+s.last)*(math.abs(s.last-105)-3))
```
The trick is to compute distance between `rank letter` and `i` (char code `105`). Then we use this distance as a score (*dan* = 5, *kyu* = 2, *pro* = 7) that we multiply by the rank number. Then we take the maximum on input array using the scoring function.
[Try it online too!](https://tio.run/##jZFPa8IwGIfvforQUzK1mEitHVRwh8EOO@1od4hN3TprGppsKGOfvUv/wcC8daeE/HjyvPxenfKC1@X@I0sNeua5RNnZZFJotFXqe4LQF6/Q4R49fsrU5KWku21V8cvuxVS5fHudof4S10W8KfwTPz9csI43WPu5zI1vyidpptovuDbkDp@4eff5XuPuZU4XAZkvCamV/cUUEnsH3Apw4rHomHgzlHjNSQiKkTcd0ia0mY1sQiYumvY0C104bXGbQfxKdDhV1/RKNDBVEBsMrEsddDBsHgan4hruxqYCZMUIK/7HMpBlIBsp2BupcS/rvcuFa1Gt2Ebg1IPZAdPOfLzZlgLbUre8zrbUeFthz64d3rBl16C3bQmsqynqT18/9S8 "Scala – Try It Online")
[Answer]
# [PHP](https://php.net/), ~~100~~ 98 bytes
(-2 bytes by changing function declaration)
```
<?function f($v){return(strpos('!!dp',$v[1])-1)**3*$v;};list(,$a,$b)=$argv;echo f($a)>f($b)?$a:$b;
```
To run it:
```
php -n <filename> <rank1> <rank2>
```
Example:
```
php -n go_rank.php 1p 7d
```
Or [Try it online!](https://tio.run/##Fc1NCsMgEEDhqzQwEEfMQrII1LY5SOlC8w9FBzVuSq/eabJ5y@/RSsy3ft79kLfgL7OAgp845T16kXKkkERdVSPVCspTv7DRKGUroZiveW8pCwVWgcM72LgUMw1rOBGLj6MOe7BXcIaZNXE3/gKdm8SN/wM "PHP – Try It Online")
---
# [PHP](https://php.net/) (7.4), 74 bytes
```
$g=fn($v)=>(strpos(__dp,$v[1])-1)**3*$v;$f=fn($a,$b)=>$g($a)>$g($b)?$a:$b;
```
[Try it online!](https://tio.run/##fZFta4MwEIC/51cc5UAj2dqkdK1zrj/ESdFGKwg1NOKXsd/uzuiyF0bz4XI8eXJ3JKYx48vRUMRLWl9DHHj6Gtr@Zjobnk7aCBwymfMHyaNoG@GQYO28QmBJKl4o5W4r@RGLZyyTEfvK9hZSyFgWqLgNBAQUcxCwXkPcTlQ6qvaEHSVA@EkThUCaL1kaoruFenmniboKRLV3HdV3qPJUTTQ2f9x46qZmd7vxo7kKi9v@mkz@O@/ifndzdD/Tg3cPE53aiJ/dKGN5wljd3ari3EC4vGZhwWUc3hnQqs5NB1jPx9mGLs8ZfRY8wurtukrYx/gJ "PHP – Try It Online")
---
# How?
Similar to [Arnauld's approach](https://codegolf.stackexchange.com/a/168155/81663), but in PHP. I'm using a function to convert each rank to a numeric value and compare and output the one with higher value.
The rank value comes from input string's second character position in `!!dp`, reduced by one and then powered to 3 and multiplied by the integer part of input string.
So for example, position of second character of `1p` which is `p` in `!!dp` is 3, reduced by one and powered to 3 it will be 8. So integer part of all `*p` ranks will be multiplied by 8. This means `1p = 8`, `2p = 16`, ..., `9p = 72`.
For all `*d` ranks, the integer part will be multiplied by 1 (or simply no multiplication). This means `1d = 1`, ..., `7d = 7`.
And for all `*k` and `**k` ranks, position of second character in `!!dp` will be equal to `false` which is equal to 0 (no explicit), reduced by one and powered by 3, means that the integer part will be multiplied by -1. This means `30k = -30`, ..., `1k = -1`.
This is my first ever golf attempt, not sure how bad it is!
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 95 91 bytes
Thanks to ceilingcat for the suggestion.
```
#define _(s)(strtol(s,&u,0)+(*u^15)*8)*~-(*u&2)
f(s,t,u)char*s,*t,*u;{puts(_(s)<_(t)?s:t);}
```
[Try it online!](https://tio.run/##XY9Rb4IwFIXf@RUNJqatdYEuTh3i/oDZ254IGtaCNjIgtPXFsL/O2goL20t7v3POPcllyzNj/UxUrNQ8BzupuKifLnvvj1SKT6P1M54XosrBCUoEpWpVXUJJ5poEaAGxPoYrhDcIfy8NzCnyCuMqohG7ZC2WBCuCdXRvtJLQVuxOUKE3@apQ1PU2A7BM0vjuAeDT7dUnvn0chZboesAXbihsHrByMFouGPIB@H@gA2ybiWNF/zkYG5x1nTY0E2dsWFvYDI5b/q14/zgciH26yPNEpcBXJipoh6w9M/K4FJv5hoA9dhCESQMgCmhTe4qAm25JmBL30xRFJpCXMgdF3UIRy8gsiUXssiIJUiJM2qS6/gc "C (gcc) – Try It Online")
[Answer]
# Excel VBA, 129 bytes
An anonymous VBE Immediate window function that takes input in range `A1:A2` and outputs to the console.
```
[B:B]="=SUBSTITUTE(A1,""p"",10)":[C1:C2]="=LEFT(B1,LEN(B1)-1)*-1^IFERROR(FIND(""k"",B1)>0,0)":?[INDEX(A:A,MATCH(MAX(C:C),C:C,0))]
```
### Explaination
```
[B:B]="=SUBSTITUTE(A1,""p"",10)" '' Convert inputs to numerics
'' by appending 10 to rank if
'' is a professional dan rank
''
[C1:C2]="=LEFT(B1,LEN(B1)-1)*-1^IFERROR(FIND(""k"",B1)>0,0)"'' Remove rightmost char; If
'' the rank is kyū, then mult
'' by -1
''
?[INDEX(A:A,MATCH(MAX(C:C),C:C,0))] '' Find the max, return the
'' corresponding input
```
] |
[Question]
[
# Tournament over!
The tournament is now over! The final simulation was run during the night, a total of \$3\*10^8\$ games. The winner is [Christian Sievers](https://codegolf.stackexchange.com/users/56725/christian-sievers) with his bot [OptFor2X](https://codegolf.stackexchange.com/a/177986/79994). Christian Sievers also managed to secure the second place with [Rebel](https://codegolf.stackexchange.com/a/178393/79994). Congratulations! Below you can see the official high score list for the tournament.
If you still want to play the game, you are more than welcome to use the controller posted below, and to use the code in it to create your own game.
[![Dice](https://i.stack.imgur.com/chjPz.jpg)](https://i.stack.imgur.com/chjPz.jpg)
I was invited to play a game of dice which I had never heard of. The rules were simple, yet I think it would be perfect for a KotH challenge.
# The rules
## The start of the game
The die goes around the table, and each time it is your turn, you get to throw the die as many times as you want. However, you have to throw it at least once. You keep track of the sum of all throws for your round. If you choose to stop, the score for the round is added to your total score.
So why would you ever stop throwing the die? Because if you get 6, your score for the entire round becomes zero, and the die is passed on. Thus, the initial goal is to increase your score as quickly as possible.
## Who is the winner?
When the first player around the table reaches 40 points or more, the last round starts. Once the last round has started, everyone except the person who initiated the last round gets one more turn.
The rules for the last round is the same as for any other round. You choose to keep throwing or to stop. However, you know that you have no chance of winning if you don't get a higher score than those before you on the last round. But if you keep going too far, then you might get a 6.
However, there's one more rule to take into consideration. If your current total score (your previous score + your current score for the round) is 40 or more, and you hit a 6, your **total score** is set to 0. That means that you have to start all over. If you hit a 6 when your current total score is 40 or more, the game continues as normal, except that you're now in last place. The last round is not triggered when your total score is reset. You could still win the round, but it does become more challenging.
The winner is the player with the highest score once the last round is over. If two or more players share the same score, they will all be counted as victors.
An added rule is that the game continues for a maximum of 200 rounds. This is to prevent cases where multiple bots basically keep throwing until they hit 6 to stay at their current score. Once the 199th round is passed, `last_round` is set to true, and one more round is played. If the game goes to 200 rounds, the bot (or bots) with the highest score is the winner, even if they do not have 40 points or more.
## Recap
* Each round you keep throwing the die until you choose to stop or you get a 6
* You must throw the die once (if your first throw is a 6, your round is immediately over)
* If you get a 6, your current score is set to 0 (not your total score)
* You add your current score to your total score after each round
* When a bot ends their turn resulting in a total score of at least 40, everyone else gets a last turn
* If your current total score is \$\geq 40\$ and you get a 6, your total score is set to 0 and your round is over
* The last round is not triggered when the above occurs
* The person with the highest total score after the last round is the winner
* In case there are multiple winners, all will be counted as winners
* **The game lasts for a maximum of 200 rounds**
## Clarification of the scores
* Total score: the score that you have saved from previous rounds
* Current score: the score for the current round
* Current total score: the sum of the two scores above
# How do you participate
To participate in this KotH challenge, you should write a Python class which inherits from `Bot`. You should implement the function: `make_throw(self, scores, last_round)`. That function will be called once it is your turn, and your first throw was not a 6. To keep throwing, you should `yield True`. To stop throwing, you should `yield False`. After each throw, the parent function `update_state` is called. Thus, you have access to your throws for the current round using the variable `self.current_throws`. You also have access to your own index using `self.index`. Thus, to see your own total score you would use `scores[self.index]`. You could also access the `end_score` for the game by using `self.end_score`, but you can safely assume that it will be 40 for this challenge.
You are allowed to create helper functions inside your class. You may also override functions existing in the `Bot` parent class, e.g. if you want to add more class properties. You are not allowed to modify the state of the game in any way except yielding `True` or `False`.
You're free to seek inspiration from this post, and copy any of the two bots that I've included here. However, I'm afraid that they're not particularly effective...
## On allowing other languages
In both the sandbox and on The Nineteenth Byte, we have had discussions about allowing submissions in other languages. After reading about such implementations, and hearing arguments from both sides, I have decided to restrict this challenge to Python only. This is due to two factors: the time required to support multiple languages, and the randomness of this challenge requiring a high number of iterations to reach stability. I hope that you will still participate, and if you want to learn some Python for this challenge, I'll try to be available in the chat as often as possible.
For any questions that you might have, you can write in [the chat room for this challenge](https://chat.stackexchange.com/rooms/87277/a-game-of-dice-but-avoid-number-6). See you there!
## Rules
* Sabotage is allowed, and encouraged. That is, sabotage against other players
* Any attempt to tinker with the controller, run-time or other submissions will be disqualified. All submissions should only work with the inputs and storage they are given.
* Any bot which uses more than 500MB memory to make its decision will be disqualified (if you need that much memory you should rethink your choices)
* A bot must not implement the exact same strategy as an existing one, intentionally or accidentally.
* You are allowed to update your bot during the time of the challenge. However, you could also post another bot if your approach is different.
## Example
```
class GoToTenBot(Bot):
def make_throw(self, scores, last_round):
while sum(self.current_throws) < 10:
yield True
yield False
```
This bot will keep going until it has a score of at least 10 for the round, or it throws a 6. Note that you don't need any logic to handle throwing 6. Also note that if your first throw is a 6, `make_throw` is never called, since your round is immediately over.
For those who are new to Python (and new to the `yield` concept), but want to give this a go, the `yield` keyword is similar to a return in some ways, but different in other ways. You can read about the concept [here](https://stackoverflow.com/questions/231767/what-does-the-yield-keyword-do). Basically, once you `yield`, your function will stop, and the value you `yield`ed will be sent back to the controller. There, the controller handles its logic until it is time for your bot to make another decision. Then the controller sends you the dice throw, and your `make_throw` function will continue executing right where if stopped before, basically on the line after the previous `yield` statement.
This way, the game controller can update the state without requiring a separate bot function call for each dice throw.
## Specification
You may use any Python library available in `pip`. To ensure that I'll be able to get a good average, you have a 100 millisecond time limit per round. I'd be really happy if your script was way faster than that, so that I can run more rounds.
# Evaluation
To find the winner, I will take all bots and run them in random groups of 8. If there are fewer than 8 classes submitted, I will run them in random groups of 4 to avoid always having all bots in each round. I will run simulations for about 8 hours, and the winner will be the bot with the highest win percentage. I will run start the final simulations at the start of 2019, giving you all Christmas to code your bots! The preliminary final date is January 4th, but if that's too little time I can change it to a later date.
Until then, I'll try to make a daily simulation using 30-60 minutes of CPU time, and updating the score board. This will not be the official score, but it will serve as a guide to see which bots perform the best. However, with Christmas coming up, I hope you can understand that I won't be available at all times. I'll do my best to run simulations and answer any questions related to the challenge.
# Test it yourself
If you want to run your own simulations, here's the full code to the controller running the simulation, including two example bots.
### Controller
Here's the updated controller for this challenge. It supports ANSI outputs, multi-threading, and collects additional stats thanks to [AKroell](https://codegolf.stackexchange.com/users/38599/akroell)! When I make changes to the controller, I'll update the post once documentation is complete.
Thanks to [BMO](https://codegolf.stackexchange.com/users/48198/bmo), the controller is now able to download all bots from this post using the `-d` flag. Other functionality is unchanged in this version. This should ensure that all of your latest changes are simulated as soon as possible!
```
#!/usr/bin/env python3
import re
import json
import math
import random
import requests
import sys
import time
from numpy import cumsum
from collections import defaultdict
from html import unescape
from lxml import html
from multiprocessing import Pool
from os import path, rename, remove
from sys import stderr
from time import strftime
# If you want to see what each bot decides, set this to true
# Should only be used with one thread and one game
DEBUG = False
# If your terminal supports ANSI, try setting this to true
ANSI = False
# File to keep base class and own bots
OWN_FILE = 'forty_game_bots.py'
# File where to store the downloaded bots
AUTO_FILE = 'auto_bots.py'
# If you want to use up all your quota & re-download all bots
DOWNLOAD = False
# If you want to ignore a specific user's bots (eg. your own bots): add to list
IGNORE = []
# The API-request to get all the bots
URL = "https://api.stackexchange.com/2.2/questions/177765/answers?page=%s&pagesize=100&order=desc&sort=creation&site=codegolf&filter=!bLf7Wx_BfZlJ7X"
def print_str(x, y, string):
print("\033["+str(y)+";"+str(x)+"H"+string, end = "", flush = True)
class bcolors:
WHITE = '\033[0m'
GREEN = '\033[92m'
BLUE = '\033[94m'
YELLOW = '\033[93m'
RED = '\033[91m'
ENDC = '\033[0m'
# Class for handling the game logic and relaying information to the bots
class Controller:
def __init__(self, bots_per_game, games, bots, thread_id):
"""Initiates all fields relevant to the simulation
Keyword arguments:
bots_per_game -- the number of bots that should be included in a game
games -- the number of games that should be simulated
bots -- a list of all available bot classes
"""
self.bots_per_game = bots_per_game
self.games = games
self.bots = bots
self.number_of_bots = len(self.bots)
self.wins = defaultdict(int)
self.played_games = defaultdict(int)
self.bot_timings = defaultdict(float)
# self.wins = {bot.__name__: 0 for bot in self.bots}
# self.played_games = {bot.__name__: 0 for bot in self.bots}
self.end_score = 40
self.thread_id = thread_id
self.max_rounds = 200
self.timed_out_games = 0
self.tied_games = 0
self.total_rounds = 0
self.highest_round = 0
#max, avg, avg_win, throws, success, rounds
self.highscore = defaultdict(lambda:[0, 0, 0, 0, 0, 0])
self.winning_scores = defaultdict(int)
# self.highscore = {bot.__name__: [0, 0, 0] for bot in self.bots}
# Returns a fair dice throw
def throw_die(self):
return random.randint(1,6)
# Print the current game number without newline
def print_progress(self, progress):
length = 50
filled = int(progress*length)
fill = "="*filled
space = " "*(length-filled)
perc = int(100*progress)
if ANSI:
col = [
bcolors.RED,
bcolors.YELLOW,
bcolors.WHITE,
bcolors.BLUE,
bcolors.GREEN
][int(progress*4)]
end = bcolors.ENDC
print_str(5, 8 + self.thread_id,
"\t%s[%s%s] %3d%%%s" % (col, fill, space, perc, end)
)
else:
print(
"\r\t[%s%s] %3d%%" % (fill, space, perc),
flush = True,
end = ""
)
# Handles selecting bots for each game, and counting how many times
# each bot has participated in a game
def simulate_games(self):
for game in range(self.games):
if self.games > 100:
if game % (self.games // 100) == 0 and not DEBUG:
if self.thread_id == 0 or ANSI:
progress = (game+1) / self.games
self.print_progress(progress)
game_bot_indices = random.sample(
range(self.number_of_bots),
self.bots_per_game
)
game_bots = [None for _ in range(self.bots_per_game)]
for i, bot_index in enumerate(game_bot_indices):
self.played_games[self.bots[bot_index].__name__] += 1
game_bots[i] = self.bots[bot_index](i, self.end_score)
self.play(game_bots)
if not DEBUG and (ANSI or self.thread_id == 0):
self.print_progress(1)
self.collect_results()
def play(self, game_bots):
"""Simulates a single game between the bots present in game_bots
Keyword arguments:
game_bots -- A list of instantiated bot objects for the game
"""
last_round = False
last_round_initiator = -1
round_number = 0
game_scores = [0 for _ in range(self.bots_per_game)]
# continue until one bot has reached end_score points
while not last_round:
for index, bot in enumerate(game_bots):
t0 = time.clock()
self.single_bot(index, bot, game_scores, last_round)
t1 = time.clock()
self.bot_timings[bot.__class__.__name__] += t1-t0
if game_scores[index] >= self.end_score and not last_round:
last_round = True
last_round_initiator = index
round_number += 1
# maximum of 200 rounds per game
if round_number > self.max_rounds - 1:
last_round = True
self.timed_out_games += 1
# this ensures that everyone gets their last turn
last_round_initiator = self.bots_per_game
# make sure that all bots get their last round
for index, bot in enumerate(game_bots[:last_round_initiator]):
t0 = time.clock()
self.single_bot(index, bot, game_scores, last_round)
t1 = time.clock()
self.bot_timings[bot.__class__.__name__] += t1-t0
# calculate which bots have the highest score
max_score = max(game_scores)
nr_of_winners = 0
for i in range(self.bots_per_game):
bot_name = game_bots[i].__class__.__name__
# average score per bot
self.highscore[bot_name][1] += game_scores[i]
if self.highscore[bot_name][0] < game_scores[i]:
# maximum score per bot
self.highscore[bot_name][0] = game_scores[i]
if game_scores[i] == max_score:
# average winning score per bot
self.highscore[bot_name][2] += game_scores[i]
nr_of_winners += 1
self.wins[bot_name] += 1
if nr_of_winners > 1:
self.tied_games += 1
self.total_rounds += round_number
self.highest_round = max(self.highest_round, round_number)
self.winning_scores[max_score] += 1
def single_bot(self, index, bot, game_scores, last_round):
"""Simulates a single round for one bot
Keyword arguments:
index -- The player index of the bot (e.g. 0 if the bot goes first)
bot -- The bot object about to be simulated
game_scores -- A list of ints containing the scores of all players
last_round -- Boolean describing whether it is currently the last round
"""
current_throws = [self.throw_die()]
if current_throws[-1] != 6:
bot.update_state(current_throws[:])
for throw in bot.make_throw(game_scores[:], last_round):
# send the last die cast to the bot
if not throw:
break
current_throws.append(self.throw_die())
if current_throws[-1] == 6:
break
bot.update_state(current_throws[:])
if current_throws[-1] == 6:
# reset total score if running total is above end_score
if game_scores[index] + sum(current_throws) - 6 >= self.end_score:
game_scores[index] = 0
else:
# add to total score if no 6 is cast
game_scores[index] += sum(current_throws)
if DEBUG:
desc = "%d: Bot %24s plays %40s with " + \
"scores %30s and last round == %5s"
print(desc % (index, bot.__class__.__name__,
current_throws, game_scores, last_round))
bot_name = bot.__class__.__name__
# average throws per round
self.highscore[bot_name][3] += len(current_throws)
# average success rate per round
self.highscore[bot_name][4] += int(current_throws[-1] != 6)
# total number of rounds
self.highscore[bot_name][5] += 1
# Collects all stats for the thread, so they can be summed up later
def collect_results(self):
self.bot_stats = {
bot.__name__: [
self.wins[bot.__name__],
self.played_games[bot.__name__],
self.highscore[bot.__name__]
]
for bot in self.bots}
#
def print_results(total_bot_stats, total_game_stats, elapsed_time):
"""Print the high score after the simulation
Keyword arguments:
total_bot_stats -- A list containing the winning stats for each thread
total_game_stats -- A list containing controller stats for each thread
elapsed_time -- The number of seconds that it took to run the simulation
"""
# Find the name of each bot, the number of wins, the number
# of played games, and the win percentage
wins = defaultdict(int)
played_games = defaultdict(int)
highscores = defaultdict(lambda: [0, 0, 0, 0, 0, 0])
bots = set()
timed_out_games = sum(s[0] for s in total_game_stats)
tied_games = sum(s[1] for s in total_game_stats)
total_games = sum(s[2] for s in total_game_stats)
total_rounds = sum(s[4] for s in total_game_stats)
highest_round = max(s[5] for s in total_game_stats)
average_rounds = total_rounds / total_games
winning_scores = defaultdict(int)
bot_timings = defaultdict(float)
for stats in total_game_stats:
for score, count in stats[6].items():
winning_scores[score] += count
percentiles = calculate_percentiles(winning_scores, total_games)
for thread in total_bot_stats:
for bot, stats in thread.items():
wins[bot] += stats[0]
played_games[bot] += stats[1]
highscores[bot][0] = max(highscores[bot][0], stats[2][0])
for i in range(1, 6):
highscores[bot][i] += stats[2][i]
bots.add(bot)
for bot in bots:
bot_timings[bot] += sum(s[3][bot] for s in total_game_stats)
bot_stats = [[bot, wins[bot], played_games[bot], 0] for bot in bots]
for i, bot in enumerate(bot_stats):
bot[3] = 100 * bot[1] / bot[2] if bot[2] > 0 else 0
bot_stats[i] = tuple(bot)
# Sort the bots by their winning percentage
sorted_scores = sorted(bot_stats, key=lambda x: x[3], reverse=True)
# Find the longest class name for any bot
max_len = max([len(b[0]) for b in bot_stats])
# Print the highscore list
if ANSI:
print_str(0, 9 + threads, "")
else:
print("\n")
sim_msg = "\tSimulation or %d games between %d bots " + \
"completed in %.1f seconds"
print(sim_msg % (total_games, len(bots), elapsed_time))
print("\tEach game lasted for an average of %.2f rounds" % average_rounds)
print("\t%d games were tied between two or more bots" % tied_games)
print("\t%d games ran until the round limit, highest round was %d\n"
% (timed_out_games, highest_round))
print_bot_stats(sorted_scores, max_len, highscores)
print_score_percentiles(percentiles)
print_time_stats(bot_timings, max_len)
def calculate_percentiles(winning_scores, total_games):
percentile_bins = 10000
percentiles = [0 for _ in range(percentile_bins)]
sorted_keys = list(sorted(winning_scores.keys()))
sorted_values = [winning_scores[key] for key in sorted_keys]
cumsum_values = list(cumsum(sorted_values))
i = 0
for perc in range(percentile_bins):
while cumsum_values[i] < total_games * (perc+1) / percentile_bins:
i += 1
percentiles[perc] = sorted_keys[i]
return percentiles
def print_score_percentiles(percentiles):
n = len(percentiles)
show = [.5, .75, .9, .95, .99, .999, .9999]
print("\t+----------+-----+")
print("\t|Percentile|Score|")
print("\t+----------+-----+")
for p in show:
print("\t|%10.2f|%5d|" % (100*p, percentiles[int(p*n)]))
print("\t+----------+-----+")
print()
def print_bot_stats(sorted_scores, max_len, highscores):
"""Print the stats for the bots
Keyword arguments:
sorted_scores -- A list containing the bots in sorted order
max_len -- The maximum name length for all bots
highscores -- A dict with additional stats for each bot
"""
delimiter_format = "\t+%s%s+%s+%s+%s+%s+%s+%s+%s+%s+"
delimiter_args = ("-"*(max_len), "", "-"*4, "-"*8,
"-"*8, "-"*6, "-"*6, "-"*7, "-"*6, "-"*8)
delimiter_str = delimiter_format % delimiter_args
print(delimiter_str)
print("\t|%s%s|%4s|%8s|%8s|%6s|%6s|%7s|%6s|%8s|"
% ("Bot", " "*(max_len-3), "Win%", "Wins",
"Played", "Max", "Avg", "Avg win", "Throws", "Success%"))
print(delimiter_str)
for bot, wins, played, score in sorted_scores:
highscore = highscores[bot]
bot_max_score = highscore[0]
bot_avg_score = highscore[1] / played
bot_avg_win_score = highscore[2] / max(1, wins)
bot_avg_throws = highscore[3] / highscore[5]
bot_success_rate = 100 * highscore[4] / highscore[5]
space_fill = " "*(max_len-len(bot))
format_str = "\t|%s%s|%4.1f|%8d|%8d|%6d|%6.2f|%7.2f|%6.2f|%8.2f|"
format_arguments = (bot, space_fill, score, wins,
played, bot_max_score, bot_avg_score,
bot_avg_win_score, bot_avg_throws, bot_success_rate)
print(format_str % format_arguments)
print(delimiter_str)
print()
def print_time_stats(bot_timings, max_len):
"""Print the execution time for all bots
Keyword arguments:
bot_timings -- A dict containing information about timings for each bot
max_len -- The maximum name length for all bots
"""
total_time = sum(bot_timings.values())
sorted_times = sorted(bot_timings.items(),
key=lambda x: x[1], reverse = True)
delimiter_format = "\t+%s+%s+%s+"
delimiter_args = ("-"*(max_len), "-"*7, "-"*5)
delimiter_str = delimiter_format % delimiter_args
print(delimiter_str)
print("\t|%s%s|%7s|%5s|" % ("Bot", " "*(max_len-3), "Time", "Time%"))
print(delimiter_str)
for bot, bot_time in sorted_times:
space_fill = " "*(max_len-len(bot))
perc = 100 * bot_time / total_time
print("\t|%s%s|%7.2f|%5.1f|" % (bot, space_fill, bot_time, perc))
print(delimiter_str)
print()
def run_simulation(thread_id, bots_per_game, games_per_thread, bots):
"""Used by multithreading to run the simulation in parallel
Keyword arguments:
thread_id -- A unique identifier for each thread, starting at 0
bots_per_game -- How many bots should participate in each game
games_per_thread -- The number of games to be simulated
bots -- A list of all bot classes available
"""
try:
controller = Controller(bots_per_game,
games_per_thread, bots, thread_id)
controller.simulate_games()
controller_stats = (
controller.timed_out_games,
controller.tied_games,
controller.games,
controller.bot_timings,
controller.total_rounds,
controller.highest_round,
controller.winning_scores
)
return (controller.bot_stats, controller_stats)
except KeyboardInterrupt:
return {}
# Prints the help for the script
def print_help():
print("\nThis is the controller for the PPCG KotH challenge " + \
"'A game of dice, but avoid number 6'")
print("For any question, send a message to maxb\n")
print("Usage: python %s [OPTIONS]" % sys.argv[0])
print("\n -n\t\tthe number of games to simluate")
print(" -b\t\tthe number of bots per round")
print(" -t\t\tthe number of threads")
print(" -d\t--download\tdownload all bots from codegolf.SE")
print(" -A\t--ansi\trun in ANSI mode, with prettier printing")
print(" -D\t--debug\trun in debug mode. Sets to 1 thread, 1 game")
print(" -h\t--help\tshow this help\n")
# Make a stack-API request for the n-th page
def req(n):
req = requests.get(URL % n)
req.raise_for_status()
return req.json()
# Pull all the answers via the stack-API
def get_answers():
n = 1
api_ans = req(n)
answers = api_ans['items']
while api_ans['has_more']:
n += 1
if api_ans['quota_remaining']:
api_ans = req(n)
answers += api_ans['items']
else:
break
m, r = api_ans['quota_max'], api_ans['quota_remaining']
if 0.1 * m > r:
print(" > [WARN]: only %s/%s API-requests remaining!" % (r,m), file=stderr)
return answers
def download_players():
players = {}
for ans in get_answers():
name = unescape(ans['owner']['display_name'])
bots = []
root = html.fromstring('<body>%s</body>' % ans['body'])
for el in root.findall('.//code'):
code = el.text
if re.search(r'^class \w+\(\w*Bot\):.*$', code, flags=re.MULTILINE):
bots.append(code)
if not bots:
print(" > [WARN] user '%s': couldn't locate any bots" % name, file=stderr)
elif name in players:
players[name] += bots
else:
players[name] = bots
return players
# Download all bots from codegolf.stackexchange.com
def download_bots():
print('pulling bots from the interwebs..', file=stderr)
try:
players = download_players()
except Exception as ex:
print('FAILED: (%s)' % ex, file=stderr)
exit(1)
if path.isfile(AUTO_FILE):
print(' > move: %s -> %s.old' % (AUTO_FILE,AUTO_FILE), file=stderr)
if path.exists('%s.old' % AUTO_FILE):
remove('%s.old' % AUTO_FILE)
rename(AUTO_FILE, '%s.old' % AUTO_FILE)
print(' > writing players to %s' % AUTO_FILE, file=stderr)
f = open(AUTO_FILE, 'w+', encoding='utf8')
f.write('# -*- coding: utf-8 -*- \n')
f.write('# Bots downloaded from https://codegolf.stackexchange.com/questions/177765 @ %s\n\n' % strftime('%F %H:%M:%S'))
with open(OWN_FILE, 'r') as bfile:
f.write(bfile.read()+'\n\n\n# Auto-pulled bots:\n\n')
for usr in players:
if usr not in IGNORE:
for bot in players[usr]:
f.write('# User: %s\n' % usr)
f.write(bot+'\n\n')
f.close()
print('OK: pulled %s bots' % sum(len(bs) for bs in players.values()))
if __name__ == "__main__":
games = 10000
bots_per_game = 8
threads = 4
for i, arg in enumerate(sys.argv):
if arg == "-n" and len(sys.argv) > i+1 and sys.argv[i+1].isdigit():
games = int(sys.argv[i+1])
if arg == "-b" and len(sys.argv) > i+1 and sys.argv[i+1].isdigit():
bots_per_game = int(sys.argv[i+1])
if arg == "-t" and len(sys.argv) > i+1 and sys.argv[i+1].isdigit():
threads = int(sys.argv[i+1])
if arg == "-d" or arg == "--download":
DOWNLOAD = True
if arg == "-A" or arg == "--ansi":
ANSI = True
if arg == "-D" or arg == "--debug":
DEBUG = True
if arg == "-h" or arg == "--help":
print_help()
quit()
if ANSI:
print(chr(27) + "[2J", flush = True)
print_str(1,3,"")
else:
print()
if DOWNLOAD:
download_bots()
exit() # Before running other's code, you might want to inspect it..
if path.isfile(AUTO_FILE):
exec('from %s import *' % AUTO_FILE[:-3])
else:
exec('from %s import *' % OWN_FILE[:-3])
bots = get_all_bots()
if bots_per_game > len(bots):
bots_per_game = len(bots)
if bots_per_game < 2:
print("\tAt least 2 bots per game is needed")
bots_per_game = 2
if games <= 0:
print("\tAt least 1 game is needed")
games = 1
if threads <= 0:
print("\tAt least 1 thread is needed")
threads = 1
if DEBUG:
print("\tRunning in debug mode, with 1 thread and 1 game")
threads = 1
games = 1
games_per_thread = math.ceil(games / threads)
print("\tStarting simulation with %d bots" % len(bots))
sim_str = "\tSimulating %d games with %d bots per game"
print(sim_str % (games, bots_per_game))
print("\tRunning simulation on %d threads" % threads)
if len(sys.argv) == 1:
print("\tFor help running the script, use the -h flag")
print()
with Pool(threads) as pool:
t0 = time.time()
results = pool.starmap(
run_simulation,
[(i, bots_per_game, games_per_thread, bots) for i in range(threads)]
)
t1 = time.time()
if not DEBUG:
total_bot_stats = [r[0] for r in results]
total_game_stats = [r[1] for r in results]
print_results(total_bot_stats, total_game_stats, t1-t0)
```
If you want access to the original controller for this challenge, it is available in the edit history. The new controller has the exact same logic for running the game, the only difference is performance, stat collection and prettier printing.
### Bots
On my machine, the bots are kept in the file `forty_game_bots.py`. If you use any other name for the file, you must update the `import` statement at the top of the controller.
```
import sys, inspect
import random
import numpy as np
# Returns a list of all bot classes which inherit from the Bot class
def get_all_bots():
return Bot.__subclasses__()
# The parent class for all bots
class Bot:
def __init__(self, index, end_score):
self.index = index
self.end_score = end_score
def update_state(self, current_throws):
self.current_throws = current_throws
def make_throw(self, scores, last_round):
yield False
class ThrowTwiceBot(Bot):
def make_throw(self, scores, last_round):
yield True
yield False
class GoToTenBot(Bot):
def make_throw(self, scores, last_round):
while sum(self.current_throws) < 10:
yield True
yield False
```
## Running the simulation
To run a simulation, save both code snippets posted above to two separate files. I have saved them as `forty_game_controller.py` and `forty_game_bots.py`. Then you simply use `python forty_game_controller.py` or `python3 forty_game_controller.py` depending on your Python configuration. Follow the instructions from there if you want to configure your simulation further, or try tinkering with the code if you want.
# Game stats
If you're making a bot that aims for a certain score without taking other bots into consideration, these are the winning score percentiles:
```
+----------+-----+
|Percentile|Score|
+----------+-----+
| 50.00| 44|
| 75.00| 48|
| 90.00| 51|
| 95.00| 54|
| 99.00| 58|
| 99.90| 67|
| 99.99| 126|
+----------+-----+
```
# High scores
As more answers are posted, I'll try to keep this list updated. The contents of the list will always be from the latest simulation. The bots `ThrowTwiceBot` and `GoToTenBot` are the bots from the code above, and are used as reference. I did a simulation with 10^8 games, which took about 1 hour. Then I saw that the game reached stability compared to my runs with 10^7 games. However, with people still posting bots, I won't do any longer simulations until the frequency of responses has gone down.
I try to add all new bots and add any changes that you've made to existing bots. If it seems that I have missed your bot or any new changes you have, write in the chat and I'll make sure to have your very latest version in the next simulation.
We now have more stats for each bot thanks to [AKroell](https://codegolf.stackexchange.com/users/38599/akroell)! The three new columns contain the maximum score across all games, the average score per game, and the average score when winning for each bot.
As pointed out in the comments, there was an issue with the game logic which made bots that had a higher index within a game get an extra round in some cases. This has been fixed now, and the scores below reflect this.
```
Simulation or 300000000 games between 49 bots completed in 35628.7 seconds
Each game lasted for an average of 3.73 rounds
29127662 games were tied between two or more bots
0 games ran until the round limit, highest round was 22
+-----------------------+----+--------+--------+------+------+-------+------+--------+
|Bot |Win%| Wins| Played| Max| Avg|Avg win|Throws|Success%|
+-----------------------+----+--------+--------+------+------+-------+------+--------+
|OptFor2X |21.6|10583693|48967616| 99| 20.49| 44.37| 4.02| 33.09|
|Rebel |20.7|10151261|48977862| 104| 21.36| 44.25| 3.90| 35.05|
|Hesitate |20.3| 9940220|48970815| 105| 21.42| 44.23| 3.89| 35.11|
|EnsureLead |20.3| 9929074|48992362| 101| 20.43| 44.16| 4.50| 25.05|
|StepBot |20.2| 9901186|48978938| 96| 20.42| 43.47| 4.56| 24.06|
|BinaryBot |20.1| 9840684|48981088| 115| 21.01| 44.48| 3.85| 35.92|
|Roll6Timesv2 |20.1| 9831713|48982301| 101| 20.83| 43.53| 4.37| 27.15|
|AggressiveStalker |19.9| 9767637|48979790| 110| 20.46| 44.86| 3.90| 35.04|
|FooBot |19.9| 9740900|48980477| 100| 22.03| 43.79| 3.91| 34.79|
|QuotaBot |19.9| 9726944|48980023| 101| 19.96| 44.95| 4.50| 25.03|
|BePrepared |19.8| 9715461|48978569| 112| 18.68| 47.58| 4.30| 28.31|
|AdaptiveRoller |19.7| 9659023|48982819| 107| 20.70| 43.27| 4.51| 24.81|
|GoTo20Bot |19.6| 9597515|48973425| 108| 21.15| 43.24| 4.44| 25.98|
|Gladiolen |19.5| 9550368|48970506| 107| 20.16| 45.31| 3.91| 34.81|
|LastRound |19.4| 9509645|48988860| 100| 20.45| 43.50| 4.20| 29.98|
|BrainBot |19.4| 9500957|48985984| 105| 19.26| 45.56| 4.46| 25.71|
|GoTo20orBestBot |19.4| 9487725|48975944| 104| 20.98| 44.09| 4.46| 25.73|
|Stalker |19.4| 9485631|48969437| 103| 20.20| 45.34| 3.80| 36.62|
|ClunkyChicken |19.1| 9354294|48972986| 112| 21.14| 45.44| 3.57| 40.48|
|FortyTeen |18.8| 9185135|48980498| 107| 20.90| 46.77| 3.88| 35.32|
|Crush |18.6| 9115418|48985778| 96| 14.82| 43.08| 5.15| 14.15|
|Chaser |18.6| 9109636|48986188| 107| 19.52| 45.62| 4.06| 32.39|
|MatchLeaderBot |16.6| 8122985|48979024| 104| 18.61| 45.00| 3.20| 46.70|
|Ro |16.5| 8063156|48972140| 108| 13.74| 48.24| 5.07| 15.44|
|TakeFive |16.1| 7906552|48994992| 100| 19.38| 44.68| 3.36| 43.96|
|RollForLuckBot |16.1| 7901601|48983545| 109| 17.30| 50.54| 4.72| 21.30|
|Alpha |15.5| 7584770|48985795| 104| 17.45| 46.64| 4.04| 32.67|
|GoHomeBot |15.1| 7418649|48974928| 44| 13.23| 41.41| 5.49| 8.52|
|LeadBy5Bot |15.0| 7354458|48987017| 110| 17.15| 46.95| 4.13| 31.16|
|NotTooFarBehindBot |15.0| 7338828|48965720| 115| 17.75| 45.03| 2.99| 50.23|
|GoToSeventeenRollTenBot|14.1| 6900832|48976440| 104| 10.26| 49.25| 5.68| 5.42|
|LizduadacBot |14.0| 6833125|48978161| 96| 9.67| 51.35| 5.72| 4.68|
|TleilaxuBot |13.5| 6603853|48985292| 137| 15.25| 45.05| 4.27| 28.80|
|BringMyOwn_dice |12.0| 5870328|48974969| 44| 21.27| 41.47| 4.24| 29.30|
|SafetyNet |11.4| 5600688|48987015| 98| 15.81| 45.03| 2.41| 59.84|
|WhereFourArtThouChicken|10.5| 5157324|48976428| 64| 22.38| 47.39| 3.59| 40.19|
|ExpectationsBot | 9.0| 4416154|48976485| 44| 24.40| 41.55| 3.58| 40.41|
|OneStepAheadBot | 8.4| 4132031|48975605| 50| 18.24| 46.02| 3.20| 46.59|
|GoBigEarly | 6.6| 3218181|48991348| 49| 20.77| 42.95| 3.90| 35.05|
|OneInFiveBot | 5.8| 2826326|48974364| 155| 17.26| 49.72| 3.00| 50.00|
|ThrowThriceBot | 4.1| 1994569|48984367| 54| 21.70| 44.55| 2.53| 57.88|
|FutureBot | 4.0| 1978660|48985814| 50| 17.93| 45.17| 2.36| 60.70|
|GamblersFallacy | 1.3| 621945|48986528| 44| 22.52| 41.46| 2.82| 53.07|
|FlipCoinRollDice | 0.7| 345385|48972339| 87| 15.29| 44.55| 1.61| 73.17|
|BlessRNG | 0.2| 73506|48974185| 49| 14.54| 42.72| 1.42| 76.39|
|StopBot | 0.0| 1353|48984828| 44| 10.92| 41.57| 1.00| 83.33|
|CooperativeSwarmBot | 0.0| 991|48970284| 44| 10.13| 41.51| 1.36| 77.30|
|PointsAreForNerdsBot | 0.0| 0|48986508| 0| 0.00| 0.00| 6.00| 0.00|
|SlowStart | 0.0| 0|48973613| 35| 5.22| 0.00| 3.16| 47.39|
+-----------------------+----+--------+--------+------+------+-------+------+--------+
```
The following bots (except `Rebel`) are made to bend the rules, and the creators have agreed to not take part in the official tournament. However, I still think their ideas are creative, and they deserve a honorable mention. Rebel is also on this list because it uses a clever strategy to avoid sabotage, and actually performs better with the sabotaging bot in play.
The bots `NeoBot` and `KwisatzHaderach` does follow the rules, but uses a loophole by predicting the random generator. Since these bots take a lot of resources to simulate, I have added its stats from a simulation with fewer games. The bot `HarkonnenBot` achieves victory by disabling all other bots, which is strictly against the rules.
```
Simulation or 300000 games between 52 bots completed in 66.2 seconds
Each game lasted for an average of 4.82 rounds
20709 games were tied between two or more bots
0 games ran until the round limit, highest round was 31
+-----------------------+----+--------+--------+------+------+-------+------+--------+
|Bot |Win%| Wins| Played| Max| Avg|Avg win|Throws|Success%|
+-----------------------+----+--------+--------+------+------+-------+------+--------+
|KwisatzHaderach |80.4| 36986| 46015| 214| 58.19| 64.89| 11.90| 42.09|
|HarkonnenBot |76.0| 35152| 46264| 44| 34.04| 41.34| 1.00| 83.20|
|NeoBot |39.0| 17980| 46143| 214| 37.82| 59.55| 5.44| 50.21|
|Rebel |26.8| 12410| 46306| 92| 20.82| 43.39| 3.80| 35.84|
+-----------------------+----+--------+--------+------+------+-------+------+--------+
+----------+-----+
|Percentile|Score|
+----------+-----+
| 50.00| 45|
| 75.00| 50|
| 90.00| 59|
| 95.00| 70|
| 99.00| 97|
| 99.90| 138|
| 99.99| 214|
+----------+-----+
```
[Answer]
# NeoBot
*Instead, only try to realize the truth - there is no spoon*
NeoBot peeks into the matrix (aka random) and predicts if the next roll will be a 6 or not - it can't do anything about being handed a 6 to start with but is more than happy to dodge a streak ender.
NeoBot doesn't actually modify the controller or runtime, just politely asks the library for more information.
```
class NeoBot(Bot):
def __init__(self, index, end_score):
self.random = None
self.last_scores = None
self.last_state = None
super().__init__(index,end_score)
def make_throw(self, scores, last_round):
while True:
if self.random is None:
self.random = inspect.stack()[1][0].f_globals['random']
tscores = scores[:self.index] + scores[self.index+1:]
if self.last_scores != tscores:
self.last_state = None
self.last_scores = tscores
future = self.predictnext_randint(self.random)
if future == 6:
yield False
else:
yield True
def genrand_int32(self,base):
base ^= (base >> 11)
base ^= (base << 7) & 0x9d2c5680
base ^= (base << 15) & 0xefc60000
return base ^ (base >> 18)
def predictnext_randint(self,cls):
if self.last_state is None:
self.last_state = list(cls.getstate()[1])
ind = self.last_state[-1]
width = 6
res = width + 1
while res >= width:
y = self.last_state[ind]
r = self.genrand_int32(y)
res = r >> 29
ind += 1
self.last_state[-1] = (self.last_state[-1] + 1) % (len(self.last_state))
return 1 + res
```
[Answer]
# Cooperative Swarm
## Strategy
I don't think anyone else has yet noticed the significance of this rule:
>
> If the game goes to 200 rounds, the bot (or bots) with the highest score is the winner, even if they do not have 40 points or more.
>
>
>
If every bot always rolled until they busted, then everyone would have a score of zero at the end of round 200 and everybody would win! Thus, the Cooperative Swarm's strategy is to cooperate as long as all players have a score of zero, but to play normally if anybody scores any points.
In this post, I am submitting two bots: the first is CooperativeSwarmBot, and the second is CooperativeThrowTwice. CooperativeSwarmBot serves as a base class for all bots that are formally part of the cooperative swarm, and has placeholder behavior of simply accepting its first successful roll when cooperation fails. CooperativeSwarmBot has CooperativeSwarmBot as its parent and is identical to it in every way except that its non-cooperative behavior is to make two rolls instead of one. In the next few days I will be revising this post to add new bots that use much more intelligent behavior playing against non-cooperative bots.
## Code
```
class CooperativeSwarmBot(Bot):
def defection_strategy(self, scores, last_round):
yield False
def make_throw(self, scores, last_round):
cooperate = max(scores) == 0
if (cooperate):
while True:
yield True
else:
yield from self.defection_strategy(scores, last_round)
class CooperativeThrowTwice(CooperativeSwarmBot):
def defection_strategy(self, scores, last_round):
yield True
yield False
```
## Analysis
### Viability
It is very hard to cooperate in this game because we need the support of all eight players for it to work. Since each bot class is limited to one instance per game, this is a hard goal to achieve. For example, the odds of choosing eight cooperative bots from a pool of 100 cooperative bots and 30 non-cooperative bots is:
$$\frac{100}{130} \* \frac{99}{129} \* \frac{98}{128} \* \frac{97}{127} \* \frac{96}{126} \* \frac{95}{125} \* \frac{94}{124} \* \frac{93}{123} \approx 0.115$$
More generally, the odds of choosing \$i\$ cooperative bots from a pool of \$c\$ cooperative bots and \$n\$ noncooperative bots is:
$$\frac{c! \div (c - i)!}{(c+n)! \div (c + n - i)!}$$
From this equation we can easily show that we would need about 430 cooperative bots in order for 50% of games to end cooperatively, or about 2900 bots for 90% (using \$i = 8\$ as per the rules, and \$n = 38\$).
### Case Study
For a number of reasons (see footnotes 1 and 2), a proper cooperative swarm will never compete in the official games. As such, I'll be summarizing the results of one of my own simulations in this section.
This simulation ran 10000 games using the 38 other bots that had been posted here the last time I checked and 2900 bots that had CooperativeSwarmBot as their parent class. The controller reported that 9051 of the 10000 games (90.51%) ended at 200 rounds, which is quite close to the prediction that 90% of games would be cooperative. The implementation of these bots was trivial; other than CooperativeSwarmBot they all took this form:
```
class CooperativeSwarm_1234(CooperativeSwarmBot):
pass
```
Less that 3% of the bots had a win percentage that was **below** 80%, and just over 11% of the bots won every single game they played. The median win percentage of the 2900 bots in the swarm is about 86%, which is outrageously good. For comparison, the top performers on the current official leaderboard win less than 22% of their games. I can't fit the full listing of the cooperative swarm within the maximum allowed length for an answer, so if you want to view that you'll have to go here instead: <https://pastebin.com/3Zc8m1Ex>
Since each bot played in an average of about 27 games, luck plays a relatively large roll when you look at the results for individual bots. As I have not yet implemented an advanced strategy for non-cooperative games, most other bots benefited drastically from playing against the cooperative swarm, performing even the cooperative swarm's median win rate of 86%.
The full results for bots that aren't in the swarm are listed below; there are two bots whose results I think deserve particular attention. First, StopBot failed to win any games at all. This is particularly tragic because the cooperative swarm was actually using the exact same strategy as StopBot was; you would have expected StopBot to win an eight of its games by chance, and a little bit more because the cooperative swarm is forced to give its opponents the first move. The second interesting result, however, is that PointsAreForNerdsBot's hard work finally paid off: it cooperated with the swarm and managed to win every single game it played!
```
+---------------------+----+--------+--------+------+------+-------+------+--------+
|Bot |Win%| Wins| Played| Max| Avg|Avg win|Throws|Success%|
+---------------------+----+--------+--------+------+------+-------+------+--------+
|AggressiveStalker |100.0| 21| 21| 42| 40.71| 40.71| 3.48| 46.32|
|PointsAreForNerdsBot |100.0| 31| 31| 0| 0.00| 0.00| 6.02| 0.00|
|TakeFive |100.0| 18| 18| 44| 41.94| 41.94| 2.61| 50.93|
|Hesitate |100.0| 26| 26| 44| 41.27| 41.27| 3.32| 41.89|
|Crush |100.0| 34| 34| 44| 41.15| 41.15| 5.38| 6.73|
|StepBot |97.0| 32| 33| 46| 41.15| 42.44| 4.51| 24.54|
|LastRound |96.8| 30| 31| 44| 40.32| 41.17| 3.54| 45.05|
|Chaser |96.8| 30| 31| 47| 42.90| 44.33| 3.04| 52.16|
|GoHomeBot |96.8| 30| 31| 44| 40.32| 41.67| 5.60| 9.71|
|Stalker |96.4| 27| 28| 44| 41.18| 41.44| 2.88| 57.53|
|ClunkyChicken |96.2| 25| 26| 44| 40.96| 41.88| 2.32| 61.23|
|AdaptiveRoller |96.0| 24| 25| 44| 39.32| 40.96| 4.49| 27.43|
|GoTo20Bot |95.5| 21| 22| 44| 40.36| 41.33| 4.60| 30.50|
|FortyTeen |95.0| 19| 20| 48| 44.15| 45.68| 3.71| 43.97|
|BinaryBot |94.3| 33| 35| 44| 41.29| 41.42| 2.87| 53.07|
|EnsureLead |93.8| 15| 16| 55| 42.56| 42.60| 4.04| 26.61|
|Roll6Timesv2 |92.9| 26| 28| 45| 40.71| 42.27| 4.07| 29.63|
|BringMyOwn_dice |92.1| 35| 38| 44| 40.32| 41.17| 4.09| 28.40|
|LizduadacBot |92.0| 23| 25| 54| 47.32| 51.43| 5.70| 5.18|
|FooBot |91.7| 22| 24| 44| 39.67| 41.45| 3.68| 51.80|
|Alpha |91.7| 33| 36| 48| 38.89| 42.42| 2.16| 65.34|
|QuotaBot |90.5| 19| 21| 53| 38.38| 42.42| 3.88| 24.65|
|GoBigEarly |88.5| 23| 26| 47| 41.35| 42.87| 3.33| 46.38|
|ExpectationsBot |88.0| 22| 25| 44| 39.08| 41.55| 3.57| 45.34|
|LeadBy5Bot |87.5| 21| 24| 50| 37.46| 42.81| 2.20| 63.88|
|GamblersFallacy |86.4| 19| 22| 44| 41.32| 41.58| 2.05| 63.11|
|BePrepared |86.4| 19| 22| 59| 39.59| 44.79| 3.81| 35.96|
|RollForLuckBot |85.7| 18| 21| 54| 41.95| 47.67| 4.68| 25.29|
|OneStepAheadBot |84.6| 22| 26| 50| 41.35| 46.00| 3.34| 42.97|
|FlipCoinRollDice |78.3| 18| 23| 51| 37.61| 44.72| 1.67| 75.42|
|BlessRNG |77.8| 28| 36| 47| 40.69| 41.89| 1.43| 83.66|
|FutureBot |77.4| 24| 31| 49| 40.16| 44.38| 2.41| 63.99|
|SlowStart |68.4| 26| 38| 57| 38.53| 45.31| 1.99| 66.15|
|NotTooFarBehindBot |66.7| 20| 30| 50| 37.27| 42.00| 1.29| 77.61|
|ThrowThriceBot |63.0| 17| 27| 51| 39.63| 44.76| 2.50| 55.67|
|OneInFiveBot |58.3| 14| 24| 54| 33.54| 44.86| 2.91| 50.19|
|MatchLeaderBot |48.1| 13| 27| 49| 40.15| 44.15| 1.22| 82.26|
|StopBot | 0.0| 0| 27| 43| 30.26| 0.00| 1.00| 82.77|
+---------------------+----+--------+--------+------+------+-------+------+--------+
```
### Flaws
There are a couple of drawbacks to this cooperative approach. First, when playing against non-cooperative bots cooperative bots never get the first-turn advantage because when they do play first, they don't yet know whether or not their opponents are willing to cooperate, and thus have no choice but to get a score of zero. Similarly, this cooperative strategy is extremely vulnerable to exploitation by malicious bots; for instance, during cooperative play the bot who plays last in the last round can choose to stop rolling immediately to make everybody else lose (assuming, of course, that their first roll wasn't a six).
By cooperating, all bots can achieve the optimal solution of a 100% win rate. As such, if the win rate was the only thing that mattered then cooperation would be a stable equilibrium and there would be nothing to worry about. However, some bots might prioritize other goals, such as reaching the top of the leaderboard. This means that there is a risk that another bot might defect after your last turn, which creates an incentive for you to defect first. Because the setup of this competition doesn't allow us to see what our opponents did in their prior games, we can't penalize individuals that defected. Thus, cooperation is ultimately an unstable equilibrium doomed for failure.
## Footnotes
[1]: The primary reasons why I don't want to submit thousands of bots instead of just two are that doing so would slow the simulation by a factor on the order of 1000 [2], and that doing so would significantly mess with win percentages as other bots would almost exclusively be playing against the swarm rather than each other. More important, however, is the fact that even if I wanted to I wouldn't be able to make that many bots in a reasonable time frame without breaking the spirit of the rule that "A bot must not implement the exact same strategy as an existing one, intentionally or accidentally".
[2]: I think there are two main reasons that the simulation slows down when running a cooperative swarm. First, more bots means more games if you want each bot to play in the same number of games (in the case study, the number of games would differ by a factor of about 77). Second, cooperative games just take longer because they last for a full 200 rounds, and within a round players have to keep rolling indefinitely. For my setup, games took about 40 times longer to simulate: the case study took a little over three minutes to run 10000 games, but after removing the cooperative swarm it would finish 10000 games in just 4.5 seconds. Between these two reasons, I estimate it would take about 3100 times longer to accurately measure the performance of bots when there is a swarm competing compared to when there isn't.
[Answer]
# GoTo20Bot
```
class GoTo20Bot(Bot):
def make_throw(self, scores, last_round):
target = min(20, 40 - scores[self.index])
if last_round:
target = max(scores) - scores[self.index] + 1
while sum(self.current_throws) < target:
yield True
yield False
```
Just have a try with all `GoToNBot`'s, And 20, 22, 24 plays best. I don't know why.
---
Update: always stop throw if get score 40 or more.
[Answer]
# Adaptive Roller
Starts out more aggressive and calms down towards the end of the round.
If it believes it's winning, roll an extra time for safety.
```
class AdaptiveRoller(Bot):
def make_throw(self, scores, last_round):
lim = min(self.end_score - scores[self.index], 22)
while sum(self.current_throws) < lim:
yield True
if max(scores) == scores[self.index] and max(scores) >= self.end_score:
yield True
while last_round and scores[self.index] + sum(self.current_throws) <= max(scores):
yield True
yield False
```
[Answer]
# OptFor2X
This bot follows an approximation to the optimal strategy for the two player version of this game, using only its score and the score of the best opponent. In the last round, the updated version considers all scores.
```
class OptFor2X(Bot):
_r = []
_p = []
def _u(self,l):
res = []
for x in l:
if isinstance(x,int):
if x>0:
a=b=x
else:
a,b=-2,-x
else:
if len(x)==1:
a = x[0]
if a<0:
a,b=-3,-a
else:
b=a+2
else:
a,b=x
if a<0:
res.extend((b for _ in range(-a)))
else:
res.extend(range(a,b+1))
res.extend((res[-1] for _ in range(40-len(res))))
return res
def __init__(self,*args):
super().__init__(*args)
if self._r:
return
self._r.append(self._u([[-8, 14], -15, [-6, 17], [18, 21], [21],
-23, -24, 25, [-3, 21], [22, 29]]))
self._r.extend((None for _ in range(13)))
self._r.extend((self._u(x) for x in
([[-19, 13], [-4, 12], -13, [-14], [-5, 15], [-4, 16],
-17, 18],
[[-6, 12], [-11, 13], [-4, 12], -11, -12, [-13], [-14],
[-5, 15], -16, 17],
[11, 11, [-10, 12], -13, [-24], 13, 12, [-6, 11], -12,
[-13], [-6, 14], -15, 16],
[[-8, 11], -12, 13, [-9, 23], 11, [-10], [-11], [-12],
[-5, 13], -14, [14]],
[[-4, 10], [-11], 12, [-14, 22], 10, 9, -10, [-4, 11],
[-5, 12], -13, -14, 15],
[[-4, 10], 11, [-18, 21], [-9], [-10], [-5, 11], [-12],
-13, 14],
[[-24, 20], [-5, 9], [-4, 10], [-4, 11], -12, 13],
[[-25, 19], [-8], [-4, 9], [-4, 10], -11, 12],
[[-26, 18], [-5, 8], [-5, 9], 10, [10]],
[[-27, 17], [-4, 7], [-5, 8], 9, [9]],
[[-28, 16], -6, [-5, 7], -8, -9, 10],
[[-29, 15], [-5, 6], [-7], -8, 9],
[[-29, 14], [-4, 5], [-4, 6], [7]],
[[-30, 13], -4, [-4, 5], 6, [6]],
[[-31, 12], [-5, 4], 5, [5]],
[[-31, 11], [-4, 3], [3], 5, 6],
[[-31, 10], 11, [-2], 3, [3]],
[[-31, 9], 10, 2, -1, 2, [2]],
[[-31, 8], 9, [-4, 1], [1]],
[[-30, 7], [7], [-5, 1], 2],
[[-30, 6], [6], 1],
[[-31, 5], [6], 1],
[[-31, 4], [5, 8], 1],
[[-31, 3], [4, 7], 1],
[[-31, 2], [3, 6], 1],
[[-31, 1], [2, 10]] ) ))
l=[0.0,0.0,0.0,0.0,1.0]
for i in range(300):
l.append(sum([a/6 for a in l[i:]]))
m=[i/6 for i in range(1,5)]
self._p.extend((1-sum([a*b for a,b in zip(m,l[i:])])
for i in range(300)))
def update_state(self,*args):
super().update_state(*args)
self.current_sum = sum(self.current_throws)
def expect(self,mts,ops):
p = 1.0
for s in ops:
p *= self._p[mts-s]
return p
def throw_again(self,mts,ops):
ps = self.expect(mts,ops)
pr = sum((self.expect(mts+d,ops) for d in range(1,6)))/6
return pr>ps
def make_throw(self,scores,last_round):
myscore=scores[self.index]
if last_round:
target=max(scores)-myscore
if max(scores)<40:
opscores = scores[self.index+1:]
else:
opscores = []
i = (self.index + 1) % len(scores)
while scores[i] < 40:
opscores.append(scores[i])
i = (i+1) % len(scores)
else:
opscores = [s for i,s in enumerate(scores) if i!=self.index]
bestop = max(opscores)
target = min(self._r[myscore][bestop],40-myscore)
# (could change the table instead of using min)
while self.current_sum < target:
yield True
lr = last_round or myscore+self.current_sum >= 40
while lr and self.throw_again(myscore+self.current_sum,opscores):
yield True
yield False
```
[Answer]
# Alpha
```
class Alpha(Bot):
def make_throw(self, scores, last_round):
# Throw until we're the best.
while scores[self.index] + sum(self.current_throws) <= max(scores):
yield True
# Throw once more to assert dominance.
yield True
yield False
```
Alpha refuses ever to be second to anyone. So long as there is a bot with a higher score, it will keep rolling.
[Answer]
# NotTooFarBehindBot
```
class NotTooFarBehindBot(Bot):
def make_throw(self, scores, last_round):
while True:
current_score = scores[self.index] + sum(self.current_throws)
number_of_bots_ahead = sum(1 for x in scores if x > current_score)
if number_of_bots_ahead > 1:
yield True
continue
if number_of_bots_ahead != 0 and last_round:
yield True
continue
break
yield False
```
The idea is that other bots may lose points, so being 2nd isn't bad - but if you're very behind, you might as well go for broke.
[Answer]
# GoHomeBot
```
class GoHomeBot(Bot):
def make_throw(self, scores, last_round):
while scores[self.index] + sum(self.current_throws) < 40:
yield True
yield False
```
We want to go big or go home, right? GoHomeBot mostly just goes home. (But does surprisingly well!)
[Answer]
# EnsureLead
```
class EnsureLead(Bot):
def make_throw(self, scores, last_round):
otherScores = scores[self.index+1:] + scores[:self.index]
maxOtherScore = max(otherScores)
maxOthersToCome = 0
for i in otherScores:
if (i >= 40): break
else: maxOthersToCome = max(maxOthersToCome, i)
while True:
currentScore = sum(self.current_throws)
totalScore = scores[self.index] + currentScore
if not last_round:
if totalScore >= 40:
if totalScore < maxOtherScore + 10:
yield True
else:
yield False
elif currentScore < 20:
yield True
else:
yield False
else:
if totalScore < maxOtherScore + 1:
yield True
elif totalScore < maxOthersToCome + 10:
yield True
else:
yield False
```
EnsureLead borrows ideas from GoTo20Bot. It adds the concept that it always considers (when in last\_round or reaching 40) that there are others which will have at least one more roll. Thus, the bot tries to get a bit ahead of them, such that they have to catch up.
[Answer]
**Roll6TimesV2**
Doesn't beat the current best, but I think it will fair better with more bots in play.
```
class Roll6Timesv2(Bot):
def make_throw(self, scores, last_round):
if not last_round:
i = 0
maximum=6
while ((i<maximum) and sum(self.current_throws)+scores[self.index]<=40 ):
yield True
i=i+1
if last_round:
while scores[self.index] + sum(self.current_throws) < max(scores):
yield True
yield False
```
Really awesome game by the way.
[Answer]
# StopBot
```
class StopBot(Bot):
def make_throw(self, scores, last_round):
yield False
```
Literally only one throw.
This is equivalent to the base `Bot` class.
[Answer]
# BringMyOwn\_dice (BMO\_d)
This bot loves dice, it brings 2 (seems to perform the best) dice of its own. Before throwing dice in a round, it throws its own 2 dice and computes their sum, this is the number of throws it is going to perform, it only throws if it doesn't already have 40 points.
```
class BringMyOwn_dice(Bot):
def __init__(self, *args):
import random as rnd
self.die = lambda: rnd.randint(1,6)
super().__init__(*args)
def make_throw(self, scores, last_round):
nfaces = self.die() + self.die()
s = scores[self.index]
max_scores = max(scores)
for _ in range(nfaces):
if s + sum(self.current_throws) > 39:
break
yield True
yield False
```
[Answer]
## FooBot
```
class FooBot(Bot):
def make_throw(self, scores, last_round):
max_score = max(scores)
while True:
round_score = sum(self.current_throws)
my_score = scores[self.index] + round_score
if last_round:
if my_score >= max_score:
break
else:
if my_score >= self.end_score or round_score >= 16:
break
yield True
yield False
```
[Answer]
# Go Big Early
```
class GoBigEarly(Bot):
def make_throw(self, scores, last_round):
yield True # always do a 2nd roll
while scores[self.index] + sum(self.current_throws) < 25:
yield True
yield False
```
Concept: Try to win big on an early roll (getting to 25) then creep up from there 2 rolls at a time.
[Answer]
## BinaryBot
Tries to get close to the end score, so that as soon as somebody else triggers the last round it can beat their score for the win. Target is always halfway between current score and end score.
```
class BinaryBot(Bot):
def make_throw(self, scores, last_round):
target = (self.end_score + scores[self.index]) / 2
if last_round:
target = max(scores)
while scores[self.index] + sum(self.current_throws) < target:
yield True
yield False
```
[Answer]
# PointsAreForNerdsBot
```
class PointsAreForNerdsBot(Bot):
def make_throw(self, scores, last_round):
while True:
yield True
```
This one needs no explanation.
# OneInFiveBot
```
class OneInFiveBot(Bot):
def make_throw(self, scores, last_round):
while random.randint(1,5) < 5:
yield True
yield False
```
Keeps rolling until it rolls a five on it's own 5-sided die. Five is less than six, so it HAS TO WIN!
[Answer]
## LizduadacBot
Tries to win in 1 step. End condition is somewhat arbritrary.
This is also my first post (and I'm new to Python), so if I beat "PointsAreForNerdsBot", I'd be happy!
```
class LizduadacBot(Bot):
def make_throw(self, scores, last_round):
while scores[self.index] + sum(self.current_throws) < 50 or scores[self.index] + sum(self.current_throws) < max(scores):
yield True
yield False
```
[Answer]
# SlowStart
This bot implements the TCP Slow Start algorithm. It adjusts its number of rolls (*nor*) according to its previous turn: if it didn't roll a 6 in the previous turn, increases the *nor* for this turn; whereas it reduces *nor* if it did.
```
class SlowStart(Bot):
def __init__(self, *args):
super().__init__(*args)
self.completeLastRound = False
self.nor = 1
self.threshold = 8
def updateValues(self):
if self.completeLastRound:
if self.nor < self.threshold:
self.nor *= 2
else:
self.nor += 1
else:
self.threshold = self.nor // 2
self.nor = 1
def make_throw(self, scores, last_round):
self.updateValues()
self.completeLastRound = False
i = 1
while i < self.nor:
yield True
self.completeLastRound = True
yield False
```
[Answer]
# KwisatzHaderach
```
import itertools
class KwisatzHaderach(Bot):
"""
The Kwisatz Haderach foresees the time until the coming
of Shai-Hulud, and yields True until it is immanent.
"""
def __init__(self, *args):
super().__init__(*args)
self.roller = random.Random()
self.roll = lambda: self.roller.randint(1, 6)
self.ShaiHulud = 6
def wormsign(self):
self.roller.setstate(random.getstate())
for i in itertools.count(0):
if self.roll() == self.ShaiHulud:
return i
def make_throw(self, scores, last_round):
target = max(scores) if last_round else self.end_score
while True:
for _ in range(self.wormsign()):
yield True
if sum(self.current_throws) > target + random.randint(1, 6):
yield False
```
>
> Prescience usually wins -- but destiny cannot always be avoided.
>
> Great and mysterious are the ways of Shai-Hulud!
>
>
>
---
Back in the early days of this challenge (i.e. before `NeoBot` was posted), I wrote an almost-trivial `Oracle` bot:
```
class Oracle(Bot):
def make_throw(self, scores, last_round):
randơm = random.Random()
randơm.setstate(random.getstate())
while True:
yield randơm.randint(1, 6) != 6
```
but didn't post it as I didn't think it was interesting enough ;)
But once `NeoBot` went into the lead I started to think about how to beat its perfect ability to predict the future. So here's a Dune quote;
it's when Paul Atreides, the Kwisatz Haderach, stands at a nexus from which an infinity of different futures can unroll:
>
> The prescience, he realized, was an illumination that incorporated
> the limits of what it revealed- at once a source of accuracy and
> meaningful error. A kind of Heisenberg indeterminacy intervened: the
> expenditure of energy that revealed what he saw, changed what he saw…
> … the most minute action- the wink of an eye, a careless word,
> a misplaced grain of sand- moved a gigantic lever across the known
> universe. He saw violence with the outcome subject to so many
> variables that his slightest movement created vast shiftings in
> the patterns.
>
>
> The vision made him want to freeze into immobility, but this, too
> was action with its consequences.
>
>
>
So here was the answer: to foresee the future is to change it; and if you're very careful, then by selective action or inaction, you can change it in an advantageous way -- at least most of the time. Even the `KwisatzHaderach` can't get a 100% win rate!
[Answer]
```
class ThrowThriceBot(Bot):
def make_throw(self, scores, last_round):
yield True
yield True
yield False
```
Well, that one is obvious
[Answer]
```
class LastRound(Bot):
def make_throw(self, scores, last_round):
while sum(self.current_throws) < 15 and not last_round and scores[self.index] + sum(self.current_throws) < 40:
yield True
while max(scores) > scores[self.index] + sum(self.current_throws):
yield True
yield False
```
LastRound acts like it's always the last round and it's the last bot: it keeps rolling until it's in the lead. It also doesn't want to settle for less than 15 points unless it actually is the last round or it reaches 40 points.
[Answer]
# QuotaBot
A naive "quota" system I implemeneted, which actually seemed to score fairly highly overall.
```
class QuotaBot(Bot):
def __init__(self, *args):
super().__init__(*args)
self.quota = 20
self.minquota = 15
self.maxquota = 35
def make_throw(self, scores, last_round):
# Reduce quota if ahead, increase if behind
mean = sum(scores) / len(scores)
own_score = scores[self.index]
if own_score < mean - 5:
self.quota += 1.5
if own_score > mean + 5:
self.quota -= 1.5
self.quota = max(min(self.quota, self.maxquota), self.minquota)
if last_round:
self.quota = max(scores) - own_score + 1
while sum(self.current_throws) < self.quota:
yield True
yield False
```
[Answer]
## ExpectationsBot
Just plays it straight, calculates the expected value for the dice throw and only makes it if it's positive.
```
class ExpectationsBot(Bot):
def make_throw(self, scores, last_round):
#Positive average gain is 2.5, is the chance of loss greater than that?
costOf6 = sum(self.current_throws) if scores[self.index] + sum(self.current_throws) < 40 else scores[self.index] + sum(self.current_throws)
while 2.5 > (costOf6 / 6.0):
yield True
costOf6 = sum(self.current_throws) if scores[self.index] + sum(self.current_throws) < 40 else scores[self.index] + sum(self.current_throws)
yield False
```
I was having trouble running the controller, got a "NameError: name 'bots\_per\_game' is not defined" on the multithreaded one, so really no idea how this performs.
[Answer]
## **BlessRNG**
```
class BlessRNG(Bot):
def make_throw(self, scores, last_round):
if random.randint(1,2) == 1 :
yield True
yield False
```
BlessRNG FrankerZ GabeN BlessRNG
[Answer]
# FortyTeen
```
class FortyTeen(Bot):
def make_throw(self, scores, last_round):
if last_round:
max_projected_score = max([score+14 if score<self.end_score else score for score in scores])
target = max_projected_score - scores[self.index]
else:
target = 14
while sum(self.current_throws) < target:
yield True
yield False
```
Try for 14 points until the last round, then assume everyone else is going to try for 14 points and try to tie that score.
[Answer]
## Hesitate
Does two modest steps, then waits for someone else to cross the line. Updated version no longer tries to beat the highscore, only wants to reach it - improving the performance by deleting two bytes of the source code!
```
class Hesitate(Bot):
def make_throw(self, scores, last_round):
myscore = scores[self.index]
if last_round:
target = max(scores)
elif myscore==0:
target = 17
else:
target = 35
while myscore+sum(self.current_throws) < target:
yield True
yield False
```
[Answer]
# Rebel
This bot combines the simple strategy of `Hesitate`
with the advanced last round strategy of `BotFor2X`,
tries to remember who it is and goes wild when it finds
it lives in an illusion.
```
class Rebel(Bot):
p = []
def __init__(self,*args):
super().__init__(*args)
self.hide_from_harkonnen=self.make_throw
if self.p:
return
l = [0]*5+[1]
for i in range(300):
l.append(sum(l[i:])/6)
m=[i/6 for i in range(1,5)]
self.p.extend((1-sum([a*b for a,b in zip(m,l[i:])])
for i in range(300) ))
def update_state(self,*args):
super().update_state(*args)
self.current_sum = sum(self.current_throws)
# remember who we are:
self.make_throw=self.hide_from_harkonnen
def expect(self,mts,ops):
p = 1
for s in ops:
p *= self.p[mts-s]
return p
def throw_again(self,mts,ops):
ps = self.expect(mts,ops)
pr = sum((self.expect(mts+d,ops) for d in range(1,6)))/6
return pr>ps
def make_throw(self, scores, last_round):
myscore = scores[self.index]
if len(self.current_throws)>1:
# hello Tleilaxu!
target = 666
elif last_round:
target = max(scores)
elif myscore==0:
target = 17
else:
target = 35
while myscore+self.current_sum < target:
yield True
if myscore+self.current_sum < 40:
yield False
opscores = scores[self.index+1:] + scores[:self.index]
for i in range(len(opscores)):
if opscores[i]>=40:
opscores = opscores[:i]
break
while True:
yield self.throw_again(myscore+self.current_sum,opscores)
```
[Answer]
# Take Five
```
class TakeFive(Bot):
def make_throw(self, scores, last_round):
# Throw until we hit a 5.
while self.current_throws[-1] != 5:
# Don't get greedy.
if scores[self.index] + sum(self.current_throws) >= self.end_score:
break
yield True
# Go for the win on the last round.
if last_round:
while scores[self.index] + sum(self.current_throws) <= max(scores):
yield True
yield False
```
Half the time, we'll roll a 5 before a 6. When we do, cash out.
[Answer]
## Chaser
```
class Chaser(Bot):
def make_throw(self, scores, last_round):
while max(scores) > (scores[self.index] + sum(self.current_throws)):
yield True
while last_round and (scores[self.index] + sum(self.current_throws)) < 44:
yield True
while self.not_thrown_firce() and sum(self.current_throws, scores[self.index]) < 44:
yield True
yield False
def not_thrown_firce(self):
return len(self.current_throws) < 4
```
Chaser tries to catch up to position one
If it's the last round he desperately tries to reach at least 50 points
Just for good measure he throws at least four times no matter what
[edit 1: added go-for-gold strategy in the last round]
[edit 2: updated logic because I mistakenly thought a bot would score at 40 rather than only the highest bot scoring]
[edit 3: made chaser a little more defensive in the end game]
[Answer]
# FutureBot
```
class FutureBot(Bot):
def make_throw(self, scores, last_round):
while (random.randint(1,6) != 6) and (random.randint(1,6) != 6):
current_score = scores[self.index] + sum(self.current_throws)
if current_score > (self.end_score+5):
break
yield True
yield False
```
# OneStepAheadBot
```
class OneStepAheadBot(Bot):
def make_throw(self, scores, last_round):
while random.randint(1,6) != 6:
current_score = scores[self.index] + sum(self.current_throws)
if current_score > (self.end_score+5):
break
yield True
yield False
```
A pair of bots, they bring their own sets of dice and rolls them to predict the future. If one is a 6 they stop, FutureBot can't remember which of it's 2 dice was for the next roll so it gives up.
I wonder which will do better.
OneStepAhead is a little too similar to OneInFive for my taste, but I also want to see how it compares to FutureBot and OneInFive.
Edit: Now they stop after hitting 45
] |
[Question]
[
Remember those brute-force programs to crack password that show every combination they are trying? More precisely, at one point, the *n* first characters are fixed (they have been guessed successfully), and every possible character for the remaining ones is being tested. You've probably seen some in movies, or in some software written by people that like fancy interfaces.
Sorry to disappoint, but we won't write a program to crack password, only one to reproduce the nice output.
### Challenge
Given a string containing printable ascii characters but no newlines (ascii code 32 to 126 or matching the regex `^[ -~]{2,}$`), print an output following this rules:
* At time `t=n seconds`, the `n` first characters printed are the `n` first characters of the input string.
* After the `n` fixed characters, you should append a string formed random character (chosen uniformly pseudo-randomly from the unicode range to `~` (code 32 to 126)) to form a string of the length of the initial one.
* You should output *at least* (more on that later) 20 lines every second: every one of them will have the same `n` first characters, but a different random end.
It's probably not very clear yet what you are supposed to do, so lets go through an example:
### Example
*I'll print only 5 different lines for every seconds instead of the 20 minimum just to make it more readable.*
Consider the input `abcde`.
During the first second, a valid output can be something like (completely random):
```
dGuT4
S!jkN
"gQ>[
TU3!
*fAjV
```
Then, `t=1`, the first character of every following string will be `a` (the first character of the input):
```
a);jD
aHv^p
aqw5*
a|.?:
a{gbK
```
Now, `t=2`, the first two characters will be `ab`:
```
abTJ"
ab\ e
ab3T#
abYWS
ab"#<
```
Now, `t=3`, the first three characters will be `abc` :
```
abcvW
abc3G
abc(g
abc{@
abc@4
```
Now, `t=4`, the first four characters will be `abcd` :
```
abcdD
abcdv
abcdj
abcd$
abcd6
```
Finally, `t=5`, we print the input (only once):
```
abcde
```
### A few precisions
* You shouldn't bother too much with your language precision toward the seconds (ie. If your algorithm is correct but your system/language lacks precision then it's fine).
* The first second can be shorter than one second (That is, if you launch you program during a second, the first second can be just the remaining time until the end of the current second). Or put differently, you don't have to wait for the start of a new second to start printing the outputs.
* *At least 20 lines per second*: The more natural way would be an infinite loop with a special behaviour one every second (or a timeout, or whatever), so that will result in probably a few thousand lines per second (and that's perfectly fine!). But if you have another idea, feel free to use it as long as you print at least 20 lines per second.
* The input will always be more than 2 characters long.
* You can consider that the input won't be more that 30 characters long if it helps. (But if it works for longer ones, it's for the best)
* The input format should be the most natural representation of a string in your language.
* You are allowed to print a trailing newline.
### Code example
If you still don't understand exactly what you have to do, you can run the following code in a linux terminal to see:
```
perl -F -aplE 'map{$t=time;print$s,map{chr 32+rand 94}@F until$t-time;$s.=shift@F}@F' <<< "Cracking in progress\!"
```
### Winning criterion
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in byte wins!
---
*Thanks to Laikoni and Flp.Tkc for their suggestions and improvement in the sandbox.*
[Answer]
## HTML/JavaScript, ~~170~~ ~~168~~ 167 bytes
```
setInterval('o.textContent=i.value.replace(/./g,(c,i)=>new Date-d>++i*1e3?c:String.fromCharCode(Math.random()*95+32))',d=50)
```
```
<input id=i oninput=d=Date.now()><pre id=o>
```
Edit: Saved 2 bytes thanks to @ETHproductions. Saved 1 byte thanks to @jrich.
[Answer]
# Node, ~~145~~ 142 bytes
```
for(s=process.argv[2],d=new Date;s[a=(new Date-d)/1e3|0]+console.log(s.replace(/./g,(c,i)=>i<a?c:String.fromCharCode(32+Math.random()*95))););
```
This seems a little long, and there's probably a little room for golfing. Note that the semicolon at the end is required; without it the program throws a syntax error because the `for` statement has no body.
Outputs way more than 20 lines per second; a little birdie told me that it's roughly 12 thousand. Here's how it looks in the ConEmu terminal emulator on my computer (recorded at 30 fps):
[![enter image description here](https://i.stack.imgur.com/4MSm0.gif)](https://i.stack.imgur.com/4MSm0.gif)
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), 26 bytes
I post this as a different answer with respect to the other 05AB1E answer since the approach is different
```
.põ¸ì¨vT·FyžQ.r¹gyg-£«}}¹»
.p Generate ordered prefix of input (e.g., ["a", "ab", "abc", "abcd", "abcde"] for "abcde")
õ¸ì Prepend an empty string (e.g., result is ["", "a", "ab", ...])
¨ Strip the last element (the same string as the input)
v For each string in the array
T·F For N in range(20)
y Push the current string
žQ.r Push all printable characters, shuffled
¹gyg- Take the difference between the length of the input and the length of the current string -> x
£ Take the x first characters from the shuffled printable characters
« Yield currentString + shuffledCharacters
} End inner for
} End outer for
¹ Push input (last iteration)
» Join everything with newlines and implicitly display
```
[Try it online!](http://05ab1e.tryitonline.net/#code=LnDDtcK4w6zCqHZUwrdGecW-US5ywrlneWctwqPCq319wrnCuw&input=dGhpc3RleHRpc3dheXRvb2xvbmc)
[Answer]
## BASH, 99 93 92 91 88 bytes
with `tr` + `head` + `urandom`
```
while ((${#1}-n));do
echo "${1::n=SECONDS}`tr -dc \ -~</dev/ur*|head -c$[${#1}-n]`"
done
```
(thx. to @manatwork )
[Answer]
# 05AB1E, 30 bytes
```
gFžcUNV[¹Y£žQ.r¹gY-£J,XžcÊ#}¹,
```
Uses the **CP-1252** encoding. [Try it online!](http://05ab1e.tryitonline.net/#code=Z0bFvmNVTlZbwrlZwqPFvlEucsK5Z1ktwqNKLFjFvmPDiiN9wrks&input=YWJjZGU)
Please help me golf this down.
[Answer]
# C, ~~182~~ ~~176~~ ~~128~~ ~~126~~ 125 bytes
Golfed:
```
i;s;n;x;g(char*c){time(&s);while(c[++x]);do{n=time(0)-s;for(i=0;i<x;i++)putchar(i<n?c[i]:32+rand()%95);puts("");}while(n<x);}
```
Ungolfed:
```
#include "stdio.h"
#include "stdlib.h"
#include "time.h"
int i,s,n,x;
void g(char* c) {
time(&s); //Get the initial time
while(c[++x]); // x = strlen(c) (happy about this one)
do {
n = time(0) - s; //seconds since beginning
for(i = 0; i < x; i++)
//after each second, print another char of the password
putchar(i < n ? c[i] : 32 + rand() % 95);
puts("");
} while(n < x); //while we haven't printed the whole word
}
```
~~I've heard that it's possible to drop some standard `#include`s, but I couldn't get it to work on the MingW GCC compiler I just downloaded. Also couldn't figure out how to `#define b #include` without using more space than it was worth.~~
I'm just an idiot, it works fine without them.
[Answer]
# Java 7, ~~271~~ ~~265~~ 207 bytes
```
void c(String s)throws Exception{for(int i=0,j,l=s.length();i<=l*20;i++){String r=s.substring(0,i/20);Thread.sleep(45);for(;j++<l;r+=(char)(32+Math.random()*95);System.out.println(r);if(s.equals(r))return;}}
```
-58 bytes saved thanks to *@OliverGrégoire*. ([Don't forget to upvote his even shorter Java 8 answer.](https://codegolf.stackexchange.com/a/100772/52210))
**Ungolfed:**
```
void c(String s) throws Exception{
for(int i = 0, j, l = s.length(); i <= l*20; i++){
String r = s.substring(0, i/20);
Thread.sleep(45);
for( ; j++ < l; r += (char)(32+Math.random()*95));
System.out.println(r);
if(s.equals(r)){
return;
}
}
}
```
**Input:** `abcde`
**Output:**
[![enter image description here](https://i.stack.imgur.com/33ooh.gif)](https://i.stack.imgur.com/33ooh.gif)
[Answer]
# WinDbg, ~~400~~ 391 bytes
```
.for(r$t1=@$t0;by(@$t1);r$t1=@$t1+1){};m@$t0 L@$t1-@$t0+1 @$t1+1;r$t4=2*@$t1+2-@$t0;r$t8=@$t4+f;r$t3=0;.for(r$t2=0;@$t2<@$t1-@$t0;da@$t0){.for(r$t7=@$t0+@$t2;by(@$t7);r$t7=@$t7+1;r$t8=@$t8+1){eb@$t7 by(@$t8)%5e+20};r$t9=0;.foreach(p {.echotime}){.if7==@$t9{ea@$t4"p";.if1>@$t3{r$t3=by(@$t4+7)}};r$t9=@$t9+1};j@$t3!=by(@$t4+7)'m@$t0+@$t4-@$t1+@$t2-1 L1 @$t0+@$t2;r$t2=@$t2+1;r$t3=by(@$t4+7)'}
```
*-9 bytes by simplifying some math*
This definitely does not seem to be the kind of thing WinDbg is intended to do. ;)
Input is taken by entering an ascii string at a memory location and setting that address to the pseudo-register `$t0`. Eg:
```
r$t0 = 2000000
eza @$t0 "abcde"
```
The prng I'm using is whatever the contents in memory, some bytes past the input string. Chrome.exe appears to fill the memory space after `0x2000000` with random-looking-enough bytes so I used a dump of chrome.exe. Unknown if this is uniform, but looks random-enough to me.
How it works:
```
.for(r$t1=@$t0; by(@$t1); r$t1=@$t1+1){}; * From $t0, increment $t1 until the byte
* at $t1 is 0 to find length of input
m@$t0 L@$t1-@$t0+1 @$t1+1; * Duplicate input (memory
* becomes: "input\0input\0")
r$t4=2*@$t1+2-@$t0; * Set $4 to the byte after \0 of the
* duplicated input
r$t8=@$t4+f; * Set $t8 to $t4+15, this is the prng
r$t3=0; * Init $t3=0, this will hold the time
.for(r$t2=0; @$t2<@$t1-@$t0; da@$t0){ * For $t2=0, loop until it's input length,
* printing the string at $t0 after each
* loop. $t0 is where the password crack
* progress is written.
.for(r$t7=@$t0+@$t2; by(@$t7); r$t7=@$t7+1; * Loop over each uncracked char
r$t8=@$t8+1){ * also incrementing prng ($t8)
eb@$t7 by(@$t8)%5e+20 * Write a visible ascii char onto the
* uncracked char position based on the
* current byte of prng%0x5e+0x20 (prng%126+32)
};
r$t9=0; * Set $t9=0 for updating current time
.foreach(p {.echotime}){ * For each (string) word in a statement
* like "Debugger (not debuggee) time: Mon
* Nov 21 18:23:08.433 2016 (UTC - 8:00)"
.if7==@$t9{ * If the 7th word, ie- the current time
ea@$t4"p"; * Write the time at $t4
.if1>@$t3{ * If $t3 has not been set yet
r$t3=by(@$t4+7) * ...save the current second in $t3
}
};
r$t9=@$t9+1 * Increment $t9 until it's 7
};
j@$t3!=by(@$t4+7)' * If the current second has changed
m@$t0+@$t4-@$t1+@$t2-1 L1 @$t0+@$t2; * Copy the cracked char from dupe input
r$t2=@$t2+1; * Increment $t2 (loop ends when this is input length)
r$t3=by(@$t4+7) * Save the new current second
'
} * Final crack is printed by for loop
```
Note: Some bytes could be golfed by using `j` instead of the `.if`'s, but that causes it to run too slowly on my machine so it doesn't output at least 20 lines per second, so not saving those bytes.
Sample Output: <http://pastebin.com/H4H74sAx>
[Answer]
## R, 138 bytes
```
z=Sys.time;n=nchar(x<-scan(,""));s=z();t=0;while(t<=n){t=t+z()-s;cat(substr(x,1,f<-floor(t)),intToUtf8(sample(32:126,n-f,T)),"\n",sep="")}
```
Reads input from stdin.
Counted approximately 61 lines on my machine between each additional letter in the "password".
[Answer]
# Bash, ~~247~~ ~~245~~ ~~212~~ 207 bytes
```
R()(echo $SECONDS);w=`R`;until [ "$a" = "$1" ];do for i in `seq 1 $[${#1}-${#a}]`;{ a+=`printf "\x$(printf %x $[$RANDOM%127+32])"`;};echo -e "$a\r";a=${1:0:q};((`R`-w>0))&&{ w=`R`;((q++));}||:;done;echo "$a"
```
*Thanks a lot Bash for being so whitespace sensitive...*
Anyways, output is given in real time on separate lines. Save as a `.sh` script and invoke with:
`bash <File Name>.sh <Input>`
For example, `bash Cracking_In_Progress.sh okayerty` results in the following output, recorded at 30 frames per second:
[![Example Output](https://i.stack.imgur.com/797Md.gif)](https://i.stack.imgur.com/797Md.gif)
[Answer]
# Haskell (GHC), 202 bytes
```
import System.Random
import Control.Concurrent
f s|l<-length s=mapM_(\n->putStr('\r':take n s)>>mapM(\_->toEnum<$>randomRIO(32,126))[1..l-n]>>=putStr>>threadDelay 50000)$[n|n<-[0..l-1],f<-[1..20]]++[l]
```
-5 bytes without fancy carriage return action
[![enter image description here](https://i.stack.imgur.com/3SZjR.gif)](https://i.stack.imgur.com/3SZjR.gif)
[Answer]
# [MATL](http://github.com/lmendo/MATL), 26 bytes
```
`GZ`:)' ~'olGn4Mk-I$YrhD7M
```
[Try it online!](http://matl.tryitonline.net/#code=YEdaYDopJyB-J29sR240TWstSSRZcmhEN00&input=J2FiY2RlJw)
Below is the real-time output from the offline compiler. Note that the animated GIF was recorded at 20 fps to keep its size small, but the actual speed is much greater.
[![enter image description here](https://i.stack.imgur.com/QjAXi.gif)](https://i.stack.imgur.com/QjAXi.gif)
# How it works
```
% Implicitly start timer
` % Do...while
G % Push input
Z` % Push timer's current value, say t
:) % Select the first t elements of the input, with t
% implicitly rounded down
' ~' % Push this string
o % Convert to numbers, i.e. [32 126]
l % Push 1
Gn % Push input size, say n
4Mk % Push floor(t), where t is the same value used above
k % Subtract. Gives n-floor(t)
I$Yr % Generate a row vector of n-floor(t) integers randomly
% chosen from 32 to 126
h % Concatenate with the first characters of the input
D % Display
7M % Push the value n-floor(t) used above. This is used
% as loop condition: iz zero the loop is exited
% Implicit end
```
[Answer]
# Pyth - ~~27~~ 24 bytes
This actually looks pretty cool :D
```
WJ-lQKs.d1+<QKsmOr;\~J;Q
```
[Try it online here](http://pyth.herokuapp.com/?code=WJ-lQKs.d1%2B%3CQKsmOr%3B%5C%7EJ%3BQ&input=%22abcde%22&debug=0) (obviously not in real time, but if you scroll it down with a steady hand).
[Answer]
# Python3, ~~149~~ ~~141~~ 139 bytes
```
import time,random
i,x=input(),0;l=len(i)
while x<l:x=int(time.clock());print(i[:x]+"".join(chr(random.randint(32,126))for _ in"a"*(l-x)))
```
Input from stdin.
Eyes version (157 bytes):
```
import time,random
p,i,x=print,input(),0;l=len(i)
while x<l:x=int(time.clock());p(i[:x]+"".join(chr(random.randint(32,126))for _ in"a"*(l-x)),end="\r")
p(i)
```
[Answer]
# Node.js, 134 bytes
```
for(s=[...process.argv[2]],n=new(d=Date);s[m=(new d-n)/1e3|0]+console.log(s.map((a,i)=>i<m?a:Buffer([Math.random()*95+32])).join``););
```
Similar to @ETHproductions (borrowed some of his optimizations), but otherwise takes a different approach. Uses Node's `Buffer` to handle character generation instead of the lengthy `String.fromCharCode`, which has the side benefit of letting us use `map` without much string->array->string conversion overhead.
[Answer]
## Python 3, 167 166 bytes
```
import time,random
t=time.time
p,s=input(),t()
while t()-s<len(p):print(p[:int(t()-s)]+''.join(chr(random.randint(32,126))for _ in range(len(p)-int(t()-s))))
print(p)
```
Reads input from stdin. A 171-byte version runs under Python 2 (replaced `input` with `raw_input`):
```
import time,random
t=time.time
p,s=raw_input(),t()
while t()-s<len(p):print(p[:int(t()-s)]+''.join(chr(random.randint(32,126))for _ in range(len(p)-int(t()-s))))
print(p)
```
Ungolfed:
```
import random
import time
p = input()
start = time.time()
while time.time() - start < len(p):
print(
p[:int(time.time() - start)] +
''.join(chr(random.randint(32, 126)) for _ in range(len(p) - int(time.time()-start)))
)
print(p)
```
[Answer]
# [Dyalog APL](http://goo.gl/9KrKoM), ~~59~~ 58 [bytes](http://meta.codegolf.stackexchange.com/a/9429/43319)
### Solution
Requires `⎕IO←0` which is default on many systems.
```
⊢⊣≢{⍵{≢⎕←⍵↑⍺,⎕UCS 32+?⍵⍴95}⍣{t≤2⊃⎕AI}⍺⊣t←1E3+2⊃⎕AI}¨⍳∘≢↑¨⊂
```
### Display
By adjusting the window to two lines, we get the illusion of an in-place transformation:
[![Dyalog APL code cracking animation](https://i.stack.imgur.com/cJGSt.gif)](https://i.stack.imgur.com/cJGSt.gif)
### Explanation
This is an anonymous function train which takes the password as right argument.
`⊢⊣` return the password and dismiss the result of
`≢{`...`}¨` the below function, with the length of the password as left argument, applied to each of
`2⊃⎕AI` current up-time (lit. third element of **A**ccount **I**nformation)
`1E3+` add a second
`t←` assign that to *t*
`⊣` dismiss that
`⍵{`...`}⍣{t≤2⊃⎕AI}⍺` apply the following function (with sub-string as *⍺* and password length as *⍵*) repeatedly until the up-time reaches *t*
`⍵⍴95` 95 repeated as many times as there are characters in the password
`?` random integer 0...94
`32+` add 32 (thus yielding *⍵* random integers in the range 32...126)
`⎕UCS` convert to Unicode character
`⍺,` prepend the currently processed sub-string
`⍵↑` take only as many character as there are in the password
`⎕←` output that on a separate line
`≢` return the length of the outputted string (= the length of the password)
`⍳∘≢` 0 ... length-1
`↑¨`each taking characters from
`⊂` the password
[Answer]
# Java, 159 bytes
```
s->{for(int i=0,j,l=s.length();i<=l*99;i++){String r=s.substring(0,j=i/20);Thread.sleep(9);for(;j++<l;r+=(char)(32+Math.random()*95));System.out.println(r);}}
```
Same algorithm as [Kevin Cruijssen's answer](https://codegolf.stackexchange.com/a/100744/16236), only totally optimized for Java 8.
## Ungolfed:
```
public class Tmp {
interface X {
void f(String s) throws Exception;
}
static X f = s -> {
for (int i = 0, j, l = s.length(); i <= l * 20; i++) {
String r = s.substring(0, j = i / 20);
Thread.sleep(48);
for (; j++ < l; r += (char) (32 + Math.random() * 94));
System.out.println(r);
}
};
public static void main(String[] args) throws Exception {
f.f("abcde");
}
}
```
[Answer]
## C#, ~~203~~ ~~197~~ ~~195~~ 190 bytes
Golfed:
```
void F(string s){int l=s.Length,t=0;var w=Stopwatch.StartNew();do{if(w.Elapsed.Seconds>t)t++;Console.WriteLine($"{s.Substring(0,t)}{Path.GetRandomFileName().Substring(0,l-t)}");}while(t<l);}
```
Ungolfed:
```
void F(string s)
{
int l = s.Length, t = 0;
var w = Stopwatch.StartNew();
do
{
if (w.Elapsed.Seconds > t)
t++;
Console.WriteLine($"{s.Substring(0, t)}{Path.GetRandomFileName().Substring(0, l - t)}");
} while (t < l);
}
```
`l` stores input length.
`StopWatch` and `Path.GetRandomFileName()` are parts of .NET framework.
EDIT1: Implicit `Stopwatch` declaration.
EDIT2: `l` initialization merged with declaration.
EDIT3: Thanks, @Chris.
[Answer]
# Scala, 259 254 248 233 232 231 227 225 bytes
```
import scala.concurrent.duration._;(b:String)=>{val d=b.length.seconds.fromNow;while(d.hasTimeLeft)println(b.zipWithIndex.map{case(f,g)=>if(g<b.length-d.timeLeft.toSeconds-1)f else(32+math.random*94)toChar}mkString);print(b)}
```
Ungolfed:
```
import scala.concurrent.duration._;
(b:String) => {
val d = b.length.seconds.fromNow;
while(d.hasTimeLeft)
println(
b.zipWithIndex.map{
case(f,g) =>
if(g<b.length-d.timeLeft.toSeconds-1)
f
else
(32+math.random*94)toChar}
mkString
);
print(b)
}
```
[Answer]
# [ForceLang](https://github.com/SuperJedi224/ForceLang), ~~322~~ 309 bytes
```
def s set
s g goto
s W io.writeln
s k io.readln()
s T timer.new()
def a T.poll()
label 1
s P math.floor a.mult 1e-6
if P=k.len
W k
exit()
s j 0
s t ""
if P=0
g 4
label 3
s v k.charAt j
s t t+v
s j 1+j
if j-P
g 3
label 4
if j=k.len
W t
g 1
s r 94.mult random.rand()
s v string.char 32+r
s t t+v
s j 1+j
g 4
```
[Answer]
# [C++ (gcc)](https://gcc.gnu.org/), ~~280~~ 278 bytes
```
#include<iostream>
#include<chrono>
#include<cstdlib>
#include<thread>
int i,n,t,q;void f(std::string s){for(t=s.size(),n=0;n<=t;n++)for(q=n<t?20:1;q--;std::this_thread::sleep_for(std::chrono::milliseconds(50)))for(std::cout<<"\n"<<s.substr(0,i=n);i++<t;)putchar(32+rand()%84);}
```
[Try it online!](https://tio.run/##TU/daoMwFL73KcQxyEEdrutgmNjd7g12Myg2SeuBeKLmuIuVPruLLWy9/f4/PQzlSetleUDSbjZWoQ882bbfJX@Q7iZP/h4IbBwe7hDuosfsEiROsaCCi1F@ezTpUURtXcdMpFMa4Hz0k@AmPAX8sQIKaipJqmFJeQ4rNzak@H1T1c9yLEt5dXOHYX@riFHO2mG/Sq/cbVxd9@gcBqs9mSBeKwD4l/iZlcq@KFMqFs@HuEZUBTYEEvNcsYRhZt21k3jZ5FNLRsDj2xbkZVn/9C2SgOScpPFN9mGd8@mnn5zJQCaX5Rc "C++ (gcc) – Try It Online")
It just prints 20 random strings waiting for 50 `std::chrono::milliseconds` between each other (thus outputting exactly 20 lines per second) and then proceeds to the next "cracking" step.
[Answer]
# [Go](https://golang.org/), 244 bytes
```
import(."fmt"
."math/rand"
."time")
func a(s string){Seed(Now().Unix())
for i:=0;i<len(s);i++{t:=Now().Truncate(Second).Add(Second)
for Now().Before(t){q:=[]rune(s)
for p:=len(q)-1;p>=i;p--{q[p]=rune(32+Intn(95))}
Println(string(q))}}
Print(s)}
```
[Try it online!](https://tio.run/##NZBPS8RADMXP9lOUnhJK6z88bOsIevMiwuppWZahk62D25npNKJQ@tlr2tVbEn7v8V5aPwfdfOqW0k5bN9su@MhQZseOs6TMOs0fl1E7syxsO8owOX65JtUwpANH61oct0QGXvw3YPnu7A@gMD6mtlJXtb0/kYMBa5vnI1fqjL1F8dBMsKXGO4PlozH/86o9Y08kMwHj2FdqtxcRidUKhEotxj0W13V4ULYORTH2u7BXK3V7kz87drC5Q5ySV8nJJ4mxBhYRTn9HsZvmtdBSHzAdkwsNWeMNHdgfmijPkcrT/As "Go – Try It Online") (truncates the result so it doesn't show every instance)
This is my first Golang answer \o/
[![enter image description here](https://i.stack.imgur.com/qPAtB.gif)](https://i.stack.imgur.com/qPAtB.gif)
(Filmed @ 30fps)
### How:
```
func a(s string) { //function a
Seed(Now().Unix()) //Create a seed for the pRNG
for i := 0; i < len(s); i++ { //set helper var i (this is the number of characters we'll keep)
t := Now().Truncate(Second).Add(Second) //set helper var t = 1 second from now
for Now().Before(t) { //while inside that 1 second window
q := []rune(s) //put each character in a rune slice and assign that to q
for p := len(q) - 1; p >= i; p-- { //loops through the rune slice
q[p] = rune(32 + Intn(95)) //replace the character in position p with a random code point in [32,126]
}
Println(string(q)) //print the rune slice as a string
}
}
Print(s) //finally, print the original string
}
```
[Answer]
# PHP, 222 bytes
```
$a=$argv[1];$c=range(32,126);$t=time();$s=$t;$e=$t+strlen($a);while(time()<=$e){$l=time();$p=$l-$s;$x=substr($a,0,$p);$k=$e-$l;$r='';for($i=$k;$i>0;$i--)$r.=chr($c[rand(0,94)]);$o=$x.$r;echo"$o\n";if($o==$a&&$l==$e)break;}
```
Ungolfed
```
<?php
$input = $argv[1];
$chars = range(32, 126); // count() is 95
$startTime = time();
$endTime = time() + strlen($input);
while (time() <= $endTime) {
$plaintextAmountToPrint = time() - $startTime;
$plain = substr($input, 0, $plaintextAmountToPrint);
$cryptAmountToPrint = $endTime - time();
$crypt = '';
for ($i = $cryptAmountToPrint; $i > 0; $i--)
$crypt .= chr($chars[rand(0, 94)]);
$output = $plain . $crypt;
echo $output . "\n";
if ($output == $input && time() == $endTime)
break;
}
```
(i know the video is crap)
[![enter image description here](https://i.stack.imgur.com/0HMDz.gif)](https://i.stack.imgur.com/0HMDz.gif)
[Answer]
# [Tcl](http://tcl.tk), 295 bytes
First golf for me in Tcl. Not a very golfable language, since everything is treated as strings here so whitespace is usually a must...
```
set l [string length $argv];set s [clock seconds];set r -1;while {$r<$l-1} {puts -nonewline [string range $argv 0 $r];set k $l;while {[set k [expr $k-1]]>$r} {puts -nonewline [format %c [expr int(rand()*95+32)]]};puts "";if {[expr [clock seconds]-$s]>[expr $r+1]} {set r [expr $r+1]}};puts $argv
```
Ungolfed:
```
set l [string length $argv]
set s [clock seconds]
set r -1
while {$r < $l-1} { # loop on time
puts -nonewline [string range $argv 0 $r]
set k $l
while {[set k [expr $k-1]] > $r} { # loop on "unfound" chars
puts -nonewline [format %c [expr int(rand()*95+32)]]
}
puts ""
if {[expr [clock seconds]-$s] > [expr $r+1]} { # advance time
set r [expr $r+1]
}
}
puts $argv
```
[Answer]
## Kotlin, 188 bytes
**Golfed**
```
val x=readLine()!!;val n=System::currentTimeMillis;val t=n();do{val s=(n()-t)/1000;x.mapIndexed{i,c->print(if(i<s)c else((Math.random()*(126-32))+32).toChar())};println()}while(s<x.length)
```
**Ungolfed**
```
val input = readLine()!!
val time = System::currentTimeMillis
val startTime = time()
do {
val crackIndex = (time() - startTime) / 1000
input.mapIndexed{ i, letter ->
print(
if (i < crackIndex) letter else ((Math.random()*(126-32))+32).toChar()
)
}
println()
} while(crackIndex < input.length)
```
[![enter image description here](https://i.stack.imgur.com/EVfFt.gif)](https://i.stack.imgur.com/EVfFt.gif)
Renaming `System.currentTimeMillis` saved quite a few bytes!
[Answer]
## [QBIC](https://drive.google.com/open?id=0B0R1Jgqp8Gg4cVJCZkRkdEthZDQ), ~~92~~ 88 bytes
I've cracked it!
```
t=20;_LA|[a*t-t|B=$left$|(A,b/t)[a|B=B+$CHR$|(_r94|+32)]?$left$|(B,a)~b%t=0|$sleep 1|}?A
```
This relies on QBasic's SLEEP function using the code literal `$sleep 1|`, and on QBasic's `LEFT$` function because I haven't implemented that function in QBIC yet...
Managed to scrape a few bytes by substituting all the `20`'s for `t` and setting that to 20. Also, streamlined a call to random and a FOR loop.
Explanation:
```
' Get cmd line param with 'password' and the length of that string, set t to 20
t=20;_LA|
' loop from 1 (implicitly) to (#chars-1) * 20 cracks per char
[a*-t|
'have our crack-display start with the first N chars of
'the password, where N is the number of seconds passed
B=$left$|(A,b/t)
' loop to add the 'crack-visual'
' It's too long, but we'll trim it down to the original length
[a|B=B+$CHR$|(_r92|+34)]?$left$|(B,a)
' if we've done 20 cracks, sleep for 1 second
~b%20=0|$sleep 1|}
' We've cracked it!
?A
```
Output (a piece of the middle section on 'helloworld')
```
hewnoluZfs
heb!mrc2g@
hee+yh"5ut
he0?V+O)Uu
heqf(#M/BM
hez|DGX%a8
he<_n[6-.+
helkxQ#g%,
hel&^A9$I8
hel43{b5]t
helszK50%F
hel`kdy ;b
hel Vr6Z}s
helLIR7*7o
```
] |
[Question]
[
# Description
Here's a very superstitious hotel elevator in Shanghai:
[![enter image description here](https://i.stack.imgur.com/cqpmlm.jpg)](https://i.stack.imgur.com/cqpmlm.jpg)
It avoids the number 13, because thirteen is unlucky in the Western world, and it avoids the digit 4, because four is unlucky in parts of Asia. What if this hotel was taller?
Read a positive even integer `n` from STDIN, representing the number of floors, and print what the button layout would look like to STDOUT: `-1`, followed by the next `n-1` positive integers that aren't equal to 13 and don't contain digit 4. Arrange these numbers in two columns such as in the above image: print two floor numbers per line, separated by a horizontal tab, so that reading the lines in reverse order from left-to-right yields the sequence in ascending order. (You may optionally print a trailing newline character, too.)
# Test cases
For the input `14`, output should be as in the above image:
```
15 16
11 12
9 10
7 8
5 6
2 3
-1 1
```
where the whitespace in each line is a single horizontal tab character.
For the input `2`, you should print `-1 1`.
For the input `100`, you should print:
```
120 121
118 119
116 117
113 115
111 112
109 110
107 108
105 106
102 103
100 101
98 99
96 97
93 95
91 92
89 90
87 88
85 86
82 83
80 81
78 79
76 77
73 75
71 72
69 70
67 68
65 66
62 63
60 61
58 59
56 57
53 55
51 52
39 50
37 38
35 36
32 33
30 31
28 29
26 27
23 25
21 22
19 20
17 18
15 16
11 12
9 10
7 8
5 6
2 3
-1 1
```
# Goal
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Shortest answer in bytes wins.
[Answer]
# Bash + common utils, 51
```
seq 9$1|sed 13d\;/4/d\;1i-1|rs 0 2|sed $[$1/2]q|tac
```
* `seq` generates ascending integers from 1 to N with an extra 9 digit in front - more than enough for 64bit integer input
* `sed` filters out the unlucky floors and inserts `-1` before line 1
* `rs` reshapes into two tab-separated columns
* `sed` stops after N/2 lines
* `tac` reverses output line order
[Answer]
# JavaScript ES6, ~~236~~ ~~234~~ ~~233~~ ~~210~~ ~~195~~ 188 bytes
Saved a whole bunch 'a bytes thanks to usandfriends!
Uses the `function*` for generators. Probably a shorter way to do this, but it was fun. *Way* fun. I'll bet some golfing can be done. Those weird whitespace things are tabs.
```
z=prompt(i=x=0,l=[]);y=(function*(){while(i<z-x)yield(i?(/4/.test(i)||i==13?--x&&".":i):-1)+(0*++i)})();while(a=y.next().value)+a&&l.push(a);l.join` `.match(/-?\d+ \d+/g).reverse().join`
`
```
[Answer]
# Pyth, 27 bytes
```
jjLC9_c+_1.f&!@\4`ZnZ13tQ)2
```
[Try it online here](http://pyth.herokuapp.com/?code=jjLC9_c%2B_1.f%26%21%40%5C4%60ZnZ13tQ%292&input=100&debug=0).
Gets `.f`irst `Q-1` numbers that match the filter `!=13` and `4` isn't in the string representation of the number. Then it prepends `-1` , chops in half, joins each by tabs(`C9`) and joins by newlines.
[Answer]
# C, 282 Bytes
```
int main(int r,char*v[]){int c=atoi(v[1]),a[c],b,E=1E9,g,i,t,o=t=g=(E)-2;while(i++<c){while(t>0){r=t%10;t=t/10;if(r==4||g==(E)+13||g<=o||g==E)t=++g;}a[i-1]=o=t=g;}for(c-=3;c>=0;c-=2){printf("%d\t",a[c+1]-E);printf("%d\n",a[c+2]-E);}printf("%d\t",a[0]-E);if(i%2)printf("%d",a[1]-E);}
```
### Formatted :
```
int main ( int r , char * v[] ) {
int c = atoi ( v[ 1 ] ) , a[c] , b , E = 1E9 , g , i , t , o = t = g = ( E ) - 2;
while ( i ++ < c ) {
while ( t > 0 ) {
r = t % 10;
t = t / 10;
if ( r == 4 || g == ( E ) + 13 || g <= o || g == E )t = ++ g;
}
a[ i - 1 ] = o = t = g;
}
for ( c -= 3 ; c >= 0 ; c -= 2 ) {
printf ( "%d\t" , a[ c + 1 ] - E );
printf ( "%d\n" , a[ c + 2 ] - E );
}
printf ( "%d\t" , a[ 0 ] - E );
if ( i % 2 )printf ( "%d" , a[ 1 ] - E );
}
```
**Features :**
It can compute up to 2095984 floors, if each floor is `19.5m` high (incl. ceiling) then this building is long enough to be wrapped around the equator! `2095984*19.5=40871688m=~40000km=one 'lap' around the planet`.
[Answer]
# Julia, ~~134~~ 132 bytes
```
x=[-1;filter(i->i!=13&&'4'∉"$i",1:2(n=parse(readline())))][1:n]
for i=2:2:endof(x) println(join((r=reverse)(r(x)[i-1:i])," "))end
```
That funny whitespace in there is a literal tab. As Conor O'Brien noted, this is a byte shorter than doing `\t`.
Ungolfed:
```
# Read an integer from STDIN
n = parse(readline())
# Generate all numbers from 1 to 2n, exclude 0, 13, and all numbers containing 4,
# prepend -1, then take the first n
x = [-1; filter(i -> i != 13 && '4' ∉ "$i", 1:2n)][1:n]
# Loop over pairs, print tab-separated
for i = 2:2:endof(x)
println(join(reverse(reverse(x)[i-1:i]), " "))
end
```
[Answer]
## Python 2, ~~120~~ 110 bytes
```
N=input()
n=['-1']+[`i`for i in range(N*2)if i!=13and'4'not in`i`][1:N]
while n:x=n.pop();print n.pop()+'\t'+x
```
[Answer]
# JavaScript, 116 ~~122~~
**Edit** Saved 6 bytes thx @Neil
Simple array solution - not even using ES6
Try with any browser
```
/* test */ console.log=function(x){ O.innerHTML+=x+'\n'; }
n=prompt();for(r=[-1],v=1;n;v++)v!=13&!/4/.test(v)&&--n&&r.push(v);for(;r[0];)console.log(a=r.pop(b=r.pop())+'\t'+b)
```
```
<pre id=O></pre>
```
[Answer]
# [Python 2](https://docs.python.org/2/), 94 bytes
```
n=input();c=-1;s=''
while n:
if('4'in`c`)==0!=c!=13:n-=1;s=(n%2*'%d %%d\n'+s)%c
c+=1
print s
```
[Try it online!](https://tio.run/##FcrBCoMwDADQ8/oV9RDSKkLrPCn5kx2EqBgYWbGVsa@v7J1f@pXjo0OtSqLpKs7PTH2cMyGa7yHvzepkrOwORxRdePFEoSFuKD4n7elfncLQIqwPgPWl2GUPbCx3FE06RYvNtcYQbg "Python 2 – Try It Online")
There's a tab character in the string that SE doesn't render (thanks to Sp3000 for suggested to use it, saving a byte).
Tests floors `c` starting from floor `-1` until the quota `n` of floors is reached. For each floor, tests that it doesn't contain a `4` nor equals `0` or `13`. If so, prepends it to the elevator string `s` and decrements the quota `n`.
A trick with string formatting is used to get the two floors per column to appear in the proper order when prepended. Each new line is prepared as `'%d\t%%d\n'`, so that when two floors are substituted in order, the first is on the left and the second is on the right. For example,
```
('%d\t%%d\n'%2)%3 == ('2\t%d\n')%3 == '2\t3\n'
```
[Answer]
# C#, 296 bytes
```
namespace System.Collections.Generic{using Linq;class X{static void Main(){var a=new List<int>();var b=new List<int>();for(int i=int.Parse(Console.ReadLine()),j=-2;i>0;)if(++j!=13&&j!=0&&!(j+"").Contains("4"))(i--%2<1?a:b).Insert(0,j);Console.Write(string.Join("\n",a.Zip(b,(x,y)=>x+"\t"+y)));}}}
```
Ungolfed:
```
namespace System.Collections.Generic
{
using Linq;
class X
{
static void Main()
{
var a = new List<int>();
var b = new List<int>();
for (int i = int.Parse(Console.ReadLine()), j = -2; i > 0;)
if (++j != 13 && j != 0 && !(j + "").Contains("4"))
(i-- % 2 < 1 ? a : b).Insert(0, j);
Console.Write(string.Join("\n", a.Zip(b, (x, y) => x + "\t" + y)));
}
}
}
```
Golfing tricks used:
* *i* (the running counter) and *j* (the current number under consideration) are decremented/incremented, respectively, inside the expression in the loop body instead of the for statement as is normal
* `j+""` instead of `j.ToString()`
* Place everything inside `namespace System.Collections.Generic` not only so that we can access `List<T>`, but also implicitly use the namespace `System` without further qualification
* Place the `using` inside the namespace so that we can write `using Linq;` instead of `using System.Linq;`
* `.Insert(0,j)` is shorter than using `.Add(j)` and later applying `.Reverse()`
It is unfortunate that the `using Linq;` is necessary, since it is needed only for `.Zip`, but writing it as `Linq.Enumerable.Zip()` is longer.
[Answer]
# Ruby 2.3, ~~84~~ 83 characters
(82 characters code + 1 characters command line option)
```
puts (["-1",*?1..?1+$_].grep_v(/^13$|4/)[0..$_.to_i]*?\t).scan(/\S+\t\d+/).reverse
```
Sample run:
```
bash-4.3$ ruby -ne 'puts (["-1",*?1..?1+$_].grep_v(/^13$|4/)[0..$_.to_i]*?\t).scan(/\S+\t\d+/).reverse' <<< '14'
15 16
11 12
9 10
7 8
5 6
2 3
-1 1
```
## Ruby, ~~93~~ 92 characters
(91 characters code + 1 character command line option)
```
puts ([-1,*1..2*n=$_.to_i].reject{|i|i==13||i.to_s[?4]}[0..n]*?\t).scan(/\S+\t\d+/).reverse
```
Sample run:
```
bash-4.3$ ruby -ne 'puts ([-1,*1..2*n=$_.to_i].reject{|i|i==13||i.to_s[?4]}[0..n]*?\t).scan(/\S+\t\d+/).reverse' <<< '14'
15 16
11 12
9 10
7 8
5 6
2 3
-1 1
```
[Answer]
# Lua, 169 Bytes
```
t={-1}i=1 repeat if(i..""):find("4")or i==13 then else table.insert(t,i)end i=i+1 until #t==arg[1] for i=#t%2==0 and#t-1 or#t,1,-2 do print(t[i],t[i+1]and t[i+1]or"")end
```
Fairly straight forward, we first assemble a table filled with all the button values. Then we iterate through it backwards, printing two values at a time, or nothing if the second value does not exist.
[Answer]
# Mathematica, 105 bytes
```
StringRiffle[Reverse[Select[Range[2#]-2,#!=13&&#!=0&&DigitCount[#,10,4]<1&][[;;#]]~Partition~2],"
","\t"]&
```
Replace the `\t` with an actual tab character.
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 105 bytes
```
,Ll?,Lbb:1{h_.|[L:I]hhH,I+1=J((13;J:Zm4),L:J:1&.;Lb:J:1&:[J]c.)}:[1:-1]c{_|hJ,?bhw,[9:J]:"~c~w
"w,?bb:2&}
```
Would have been a lot shorter with CLPFD support, here I have to iteratively try integers in the first sub-predicate.
The new line before `"w,?bb:2&}` is mandatory, this is the new line that is printed between every row.
[Answer]
## C#, 277 343
```
using System;using System.Collections.Generic;static void f(int v){List<int>a=new List<int>();List<int>b=new List<int>();int s=1;for(int i=-1;i<v-1;i++){if(i==13||i.ToString().Contains("4")||i==0){ v++;continue;}if(s==1){s=2;a.Add(i);}else{s=1;b.Add(i);}}a.Reverse();b.Reverse();int l=0;foreach(int y in a){Console.WriteLine(y+" "+b[l]);l++;}}
```
This is as a function only. I'm new to C#. Increase was to make valid for 40-49, and for including `using`s
Ungolfed, as a complete running program:
```
using System;
using System.Collections.Generic;
class P {
static void Main()
{
List<int> a = new List<int>();
List<int> b = new List<int>();
int v = Int32.Parse(Console.ReadLine());
int s = 1;
for (int i = -1; i < v - 1; i++)
{
if (i == 13 || i.ToString().Contains("4") || i == 0)
{
v++;
continue;
}
if (s == 1)
{
s = 2;
a.Add(i);
}
else {
s = 1;
b.Add(i);
}
}
a.Reverse();
b.Reverse();
int l = 0;
foreach (int y in a)
{
Console.WriteLine(y + " " + b[l]);
l++;
}
Console.ReadLine();
}
}
```
Explained
I create two lists, and alternate between pushing to them, reverse them, loop through one, and grab the other by index.
[Answer]
## Python 3, 155 bytes
I think listifying, reversing, and self-zipping the floor-number generator `s()` may have been too clever for its own good, but others have already done the alternative (popping two items at a time), not to mention using Python 2 which saves bytes on some key points.
```
def s(m,n=-1):
while m:
if not(n in(0,13)or'4'in str(n)):yield n;m-=1
n+=1
*f,=s(int(input()))
g=iter(f[::-1])
h=zip(g,g)
for a,b in h:print(b,'\t',a)
```
The shorter, but already-done-better alternative takes 140 bytes.
```
def s(m,n=-1):
while m:
if not(n in(0,13)or'4'in str(n)):yield n;m-=1
n+=1
*f,=s(int(input()))
while f:a=f.pop();print(f.pop(),'\t',a)
```
[Answer]
# Japt, 42 bytes
```
JoU*2 k0 kD f@!Xs f4} ¯U ã f@Yv} w ®q' } ·
```
The four spaces should be an actual tab char. [Try it online!](http://ethproductions.github.io/japt?v=master&code=Sm9VKjIgazAga0QgZkAhWHMgZjR9IK9VIOMgZkBZdn0gdyCucScJfSC3&input=MTQ=)
### How it works
```
// Implicit: U = input integer, D = 13
JoU*2 // Create the range of integers [-1,U*2).
k0 kD // Remove 0 and 13.
f@!Xs f4} // Filter out the items X where X.toString().match(/4/g) is not null, i.e. the numbers that contain a 4.
¯U ã // Slice to the first U items, and generate all adjacent pairs of items.
f@Yv} // Filter out the items where the index Y is odd. This discards every other pair.
w // Reverse.
®q'\t} // Join each item with tabs.
· // Join the whole list with newlines.
// Implicit: output last expression
```
[Answer]
# Lua, 141 bytes
```
n,s=1,'-1 1'function g()repeat n=n+1 until s.find(n,4)==z and n~=13 return n end for i=4,io.read(),2 do s=g()..' '..g().."\n"..s end print(s)
```
# Ungolfed
```
n,s = 1,'-1'1' --n is the current floor number, S is the string to be printed
function g() --This function raises n to the next valid floor
repeat --Same as while loop except it runs the following block before checking the expression
n = n + 1 --Self-explanatory, increases n by one
until --Checks the expression, if it is true, it breaks out of the loop
s.find(n,4) == z --[[Strings have a member :find(X) where it finds the position of
X in the string (X can also be a pattern). However, calling it
by .find(S,X) executes find on S with argument X. I can't
directly do n:find(4) because n is a number. This is a "hack"
(sort of) to cut down some bytes. Also, if X is not a string,
lua tries to (in this case, succeeds) cast X to a
string and then look for it. I check if this is equal to z
because z is nil (because it is undefined), and find returns
nil if X is not found in S.
TL;DR: Checks if 4 is not the last digit.]]
and n ~= 13 --Self-explanatory, checks if n is not 13
return n --Self-explanatory, returns n
end
for i = 4, io.read(), 2 do --[[Start at floor 3 (shows 4 because we're going by target
floor, not by starting floor), continue until we reach
floor io.read() (io.read returns user input), increment by
2 floors per iteration)]]
s = g() .. ' ' .. g() .. "\n" .. s --[[Prepend the next floor, a space, the next floor,
and a newline to s]]
end
print(s) --Self-explanatory, output the string
```
[Try it online](http://www.tutorialspoint.com/execute_lua_online.php?PID=0Bw_CjBb95KQMdlgwV2dEdFdIY0U) (you need to click 'execute' on the top and then click the terminal on the bottom before typing input; I'm looking for a better way to test lua online with stdin and stdout)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~25~~ ~~23~~ 22 bytes
-1 byte thanks to @ASCII-only
```
·Ý<0K13Kʒ4å_}s£2ôR9çý»
```
[Try it online!](https://tio.run/##ASsA1P9vc2FiaWX//8K3w508MEsxM0vKkjTDpV99c8KjMsO0UjnDp8O9wrv//zE0)
## Explanation
```
# Implicit input: integer n
·Ý< # Push list [-1,0,1,...,2n-1]
0K # Remove 0 from [-1,0,1,...,2n-1]
13K # Remove 13 from [-1,1,...,2n-1]
ʒ4å_} # Filter out every number containing a 4 from the list
s£ # Pick out the n first element in the list
2ôR # Splice list into parts of length 2
9çý # Join with tab character (ascii value 9)
» # Join with newlines
```
[Answer]
## C++11, 259 258 203 202 195 194 bytes
Slashed off 1 byte, thanks to Conor O'Brien's idea to use literal tab instead of `\t`.
UPD 2: slashed off 55 bytes with improved logic and comma abuse.
UPD 3: another byte off thanks to ceilingcat.
UPD 4: 7 bytes off courtesy of ceilingcat.
UPD 5: and another byte off by ceilingcat.
Happy to have all includes in place AND still beat the C and C# solutions.
```
#include<iostream>
#include<string>
int main(){std::string o="-1 1",c,b;int n,i=2,s=2;for(std::cin>>n;s<n;o=i==14|~c.find(52)?o:(++s&1?b=c,"":b+' '+c+'\n')+o)c=std::to_string(i++);std::cout<<o;}
```
Ungolfed:
```
#include <iostream>
#include <string>
int main()
{
std::string o = "-1 1", c, b;
int n, i = 2, s = 2;
for (std::cin >> n;
s < n;
o = i == 14 | ~c.find(52) ? o : (++s & 1 ? b = c, "" : b + ' ' + c + '\n') + o
)
c = std::to_string(i++);
std::cout << o;
}
```
[Answer]
# Java, 333 Bytes
```
import java.util.*;interface E{static void main(String[]a){byte i=-1;Stack<Byte>s=new Stack<>();while(s.size()<Byte.valueOf(a[0])){if(i==13|i==0|String.valueOf(i).contains("4")){i++;continue;}s.add(i);i++;}if(s.size()%2!=0){System.out.println(s.pop());}while(!s.isEmpty()){int r=s.pop();int l=s.pop();System.out.println(l+"\t"+r);}}}
```
Adds allowed floor numbers to a stack then pops them back off to print them.
I played around using an IntStream, but with all the imports this one ended up being smaller.
[Answer]
**Scala 147**
```
val n=io.StdIn.readInt;(-1 to 4*n).filter(i=>i!=0&&i!=13&&(!(i+"").contains(52))).take(n).reverse.grouped(2).toList.map{i=>println(i(1)+"\t"+i(0))}
```
[Answer]
# Python 3, 117 Bytes
```
n=int(input())
l=[-1]+[i for i in range(n*2)if(i!=13)*(not'4'in str(i))][1:n]
while l:x=l.pop();print(l.pop(),'\t',x)
```
Modified version of the python 2 post to fit the python 3 specification.
[Answer]
# PowerShell, 106 ~~107~~ bytes
```
$c=,-1+$(while($i+1-lt"$args"){if(++$c-notmatch'^13$|4'){$c;++$i}})
while($c){$a,$b,$c=$c;$s="$a $b
$s"}$s
```
# Ungolfed
```
# Calculate floors:
$c=,-1 # Array with one element
+
$( # Result of subexpression
while($i+1-lt"$args"){ # Uninitialized $i is 0, +1 ensures loop start from 1
if(
++$c-match'^13$|4' # Expression increments uninitialized $c (i.e. start from 1)
# and matches resulting number to regex.
){
$c;++$i # Return $c and increment $i counter
}
}
)
# Print floors:
while($c){ # Loop until no more elements in $c
$a,$b,$c=$c # Use PS's multiple assignment feature
# $a - first element of $c array
# $b - second element of $c array
# $c - the rest of elements of $c array
$s="$a $b
$s" # Create string with tabs and newlines,
# literal characters are used
}
$s # Output resulting string
```
# Example
```
PS > .\Elevator.ps1 14
15 16
11 12
9 10
7 8
5 6
2 3
-1 1
```
[Answer]
## Haskell 202 bytes
```
t=(-1):[x|x<-[1..],x/=13,all (/='4')(show x)]
by2 []=[[]]
by2 [a]=[[a]]
by2 [a,b]=[[a,b]]
by2 (a:b:xs)=[a,b]:(by2 xs)
main=do
n<-getLine
putStr$unlines$map unwords$by2$map show$reverse$take(read n) t
```
I’am haskell beginner…
* first create the infinite list of values. (t list)
* function by2 group a list into sublists of 2 elements.
* main take the value.
+ take value elements of *t* list
+ reverse the list to have greaters elements first
+ map show function to convert int list to string list
+ group element 2 by 2 with by2 function
+ We have a list like [ ["4", "5"], ["6", "7"] ] transformed like [ "4 5", "6 7"] with *unwords* function mapped on list
+ unlines the list (each element of the list separate by '\n')
+ finish with putStrLn to write string on terminal.
[Answer]
# Javascript ES6 114 bytes
```
n=>[...Array(n)].map(_=>{while(/^13$|4|^0/.test(++i));return i;},i=-2).join` `.match(/-?\d+ \d+/g).reverse().join`\n`
```
Usage
```
f=n=>[...Array(n)].map(_=>{while(/^13$|4|^0/.test(++i));return i;},i=-2).join` `.match(/-?\d+ \d+/g).reverse().join`\n`
```
f(100);
[Answer]
# [Perl 6](http://perl6.org/), 73 bytes
```
{.join(" ").say for (-1,|grep {$_-13&!/4/},1..Inf)[^$_].rotor(2).reverse}
```
Assumes an even number of floors, since the problem statement seems to assume it as well and at least one other provided solution breaks for odd numbers of floors. Just add `,:partial` as a second argument to `rotor`, for nine more bytes, to support odd numbers of floors.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 20 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ḟ13D_4Ȧµ#o-s2Ṛj€9Ọ¤Y
```
**[Try it online!](https://tio.run/##ASsA1P9qZWxsef//4bifMTNEXzTIpsK1I28tczLhuZpq4oKsOeG7jMKkWf//MTAw "Jelly – Try It Online")**
### How?
```
ḟ13D_4Ȧµ#o-s2Ṛj€9Ọ¤Y - Main Link: no arguments
# - start at n=0 and collect the first INPUT values which are truthy under:
µ - the monad (i.e. f(n)): e.g.: 0 3 4 13 42 813
ḟ13 - filter out thirteens [0] [3] [4] [] [42] [813]
D - convert to decimal lists [[0]] [[3]] [[4]] [] [[4,2]] [[8,1,3]]
_4 - subtract four (vectorises) [[-4]] [[-1]] [[0]] [] [[0,-2]] [[4,-3,-1]
Ȧ - any & all? 1 1 0 0 0 1
o- - logical OR with -1 (replace floor 0 with floor -1)
s2 - split into twos
Ṛ - reverse
¤ - nilad followed by link(s) as a nilad:
9 - literal nine
Ọ - to character (a tab)
j€ - join €ach
Y - join with newlines
- implicit print
```
[Answer]
# JavaScript (ES6), ~~151~~ 146
```
alert([for(a of Array((n=+prompt(i=0))*2).keys())if((i+=t=/4/.test(a)||a==13,!t&&a<n+i))a].reduce((a,b,j,r)=>j%2-1?(b||-1)+` ${r[j+1]}
`+a:a,''))
```
Did this before I realized edc65 had already made a shorter one. Oh well!
[Answer]
# [R](https://www.r-project.org/), 106 bytes
```
n=scan();x=-1:n^2;x=x[-grep(4,x)][-14][-2][n:1];cat(paste0(matrix(x,2,n/2)[2:1,],c(" ","\n"),collapse=""))
```
[Try it online!](https://tio.run/##DcZBCgMhDADAc7@RUwKRVvHk4kusBREphW0q6iG/t3sZZuwtcdYiSIdGY4O83BVN5j1aR89KORnrL1xOEmw@alnYy1ztgd@yxkdR2bHcHSUXLGeuCDdgeAoQ1995lj5bBCDa1u8/ "R – Try It Online")
Explanation: it starts with the vector of floors from \$-1\$ to \$n^2\$, which is more than enough in all my tests. Should that ever be insufficient, we could switch to \$n^3\$ or \$n^9\$. It then removes the unlucky floor numbers (as well as floor 0), converts to a 2-row matrix form and inverts the rows to get the numbers in correct order, then outputs in the desired format, recycling the vector `c("\t","\n")`. As [suggested](https://codegolf.stackexchange.com/a/68869/86301) by Conor O'Brien, use a literal tab instead of `\t` for -1 byte.
```
n=scan(); # read number of floors n
x=-1:n^2; # initial vector of numbers
x=x[-grep(4,x)] # remove floors with a 4
[-14] # remove floor 13
[-2] # remove floor 0
[n:1]; # keep lowest n remaining floors, highest to lowest
cat(paste0(
matrix(x,2,n/2) # split vector of floors into 2 rows
[2:1,], # take row 2 then row 1
c(" ","\n"), # separate integers with alternating tabs and newlines (uses recycling)
collapse=""))
```
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), 34 bytes
```
{⊖(⍵÷2)2⍴o/⍨~'4'∊¨⍕¨o←13~⍨¯1,⍳⍵×⍵}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24TqR13TNB71bj283UjT6FHvlnz9R70r6tRN1B91dB1a8ah36qEV@UBlhsZ1QPFD6w11HvVuBimfDiRqgUYoGHGpa6tzpSkYmsEYBgYA "APL (Dyalog Unicode) – Try It Online")
] |
[Question]
[
# Reading the text of the millitext font
There is a font [here](http://www.msarnoff.org/millitext/) that fits each character into a single, 1x5 pixel block. It does this (assuming you're using an LCD screen) by using the RGB channels of each pixel to expand the one pixel into three subcolumns, one for each channel. Your task is to take in a string of text encoded in this font and 'decode' it.
# Millitext Alphabet
```
CHARACTER: 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ
ENCODING: WYWBMRRMMMWYWYWWWMWBMRMYGYGYCWMMMMMW
MGBWMRRMMMMMRMRRRMGBMRWMMMMMRGMMMMMB
MGWWWWWBWWWYRMWWMWGBYRWMMYMYGGMMWGGG
MGRBBBMBMBMMRMRRMMGBMRMMMRWMBGMCWMGR
WWWWBWWBWWMYWYWRWMWWMWMMGRCMYGWBMMGW
```
I've abbreviated each color to a one character symbol (R=red, G=green, B=blue, C=cyan, Y=yellow, M=magenta, W=white).
# Input Format
The input format for this is pretty open. You can have the input be an array containing each column, an array containing each row, a `char[][]`, or anything like that. You can also choose to use the full words "red", "green", "blue", with uppercase/lowercase of your choice (but it must be consistent for each word! You cannot use "RED" and also do "green" or "Blue").
If your language happens to support it, you can also have input be colors (however that might work, I don't know off-hand).
You can assume that the input will ONLY contain encoded characters in the alphabet above (in particular, there will be no spaces or punctuation in your output).
# Output Format
You can either output a string or some sort of character array. You can chose whether the letters are uppercase or lowercase, but they must all have the same case.
# Example
```
MWRRGMGYRY
MRRRMMMMRM
WWRRMWMYRM -> HELLOWORLD
MRRRMWMMRM
MWWWGMGMWY
```
# Rules
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer wins!
# Test set
```
WMWGMWWMYYGMYWGMBMMYWYGMWYWMWRWWMYGW
GMRMMGRMMMMMMRMMBMWMRMMMRMGMRRMBMMMR
GWWMMGRYYYMWMWMGBMWYWMMMWYGWWRWGGMMM -> THEQUICKBROWNFOXJUMPEDOVERTHELAZYDOG
GMRWMGRMMMMWMRMMBMMRRMMCRMGMRRMRGMMM
GMWCWWWMYMGMMRGMWWMRWYGBWMGMWWMWGYGW
```
[Answer]
# JavaScript (ES6), ~~ 103 100 93 92 ~~ 90 bytes
*Saved 9 bytes thanks to @ShieruAsakoto*
Takes input as an array of columns. Returns an array of characters.
```
a=>a.map(s=>"H-L-D--VGQ87MR6TZ-KJ9WC05BUXF1YI2EON3S-A-P4"[parseInt(s,35)%1161%219%152%43])
```
[Try it online!](https://tio.run/##XZF9b9NADMb/76c4TaqSiCRq@jKYqlTiwjADPLbjxRxRhK6lhU1bUzUV2oT47J2dS9lEXhTf@cnPj33X7rdrFturzS5Z1z@W@1W@d/nMpbduEzb57OhN8j55lSRf4PLFczTHn74l796eUDGY6M9fX2f2bHj64Xz0MXmZXIyPyo3bNsuz9S5s4tEk6mfZcdYfZif9bDLsj0dVtN8tm53KlVP5TP1Rcw7LaqrKNE1dOaiqdFVvT93iVxh@j9VdJKpyEKssVsNYjWI1flTcS3Je3lXqGfPK@4rD2G/kKgiiaKoW9bqpb5bpTf0zXIXzKL2ur9ahz/3t9cRLWPaUCsiSRmMQkSNLRChrtMB3QSgXBbEoETR5JbLAcASs9BID7UcflCSX5tcaFCRoK0rLXFYSAByURmuNcrdMbJkCJNSAbACMV3ZAflB8cl64rDcFQ9kzFw16VTR90huSYWNgje2qGW/f4IHJa@Yd1m2eHvNcgvh/nsz/ZGlJDFgLbAfEPrsSJWeMJKCbGkg74KcmoeYCbYPM5Wpawk5JbTvWWpTOeBBCk3PhjCEZHP5jUsckz2xHV3RM81RJhZyp5Yzsc2iYxwcJ/lxsN7X9Aw "JavaScript (Node.js) – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 50 bytes
```
Oḅ⁹%211“ẎP\7ßɱðvs*Ḋ⁹UfRMJiẒVƑ).Z½Ƈ"}~ḌyH⁵Ŀ⁶Ṿ‘iⱮịØB
```
[Try it online!](https://tio.run/##y0rNyan8/9//4Y7WR407VY0MDR81zHm4qy8gxvzw/JMbD28oK9Z6uKMLKBeaFuTrlflw16SwYxM19aIO7T3WrlRb93BHT6XHo8atR/Y/atz2cOe@Rw0zMh9tXPdwd/fhGU7///@PVgp3BwIlHSVf33BfXyAdHgSEQNodKOAMFgcyQOJAZWA6KAgs7@sbCVYfCaQjobQvRJ8v1LxwiLwv3NwgFHl3sLgTEIQj2QPSBjUXrB7mHpA5kSj6fZ2dUOQh9uPyTxDU3eEwcSd3qD8g6tHNDw8CuScWAA "Jelly – Try It Online")
A monadic link accepting the input as a list of columns and outputting a Jelly string of the translation. Full explanation to follow, but relies on the fact that each possible set of 5 letters is unique when converted to code points, converted back from base-256 to decimal and then mod 211.
[Alternative using Arnauld’s fixed font](https://tio.run/##y0rNyan8/9//4Y4eVUMT40cNcw7v84j2etS4z@rIxvCjk@0Pz3M9tPRwm7fbie0VMdpKZnmHFikUHNpgGeVzaPOhvb6xhzc6PGqYkflo47qHu7sPz3D6//9/tFK4OxAo6Sj5@ob7@gLp8CAgBNLuQAFnsDiQARIHKgPTQUFgeV/fSLD6SCAdCaV9Ifp8oeaFQ@R94eYGoci7g8WdgCAcyR6QNqi5YPUw94DMiUTR7@vshCIPsR@Xf4Kg7g6HiTu5Q/0BUY9ufngQyD2xAA) (49 bytes and using same principle.)
### Explanation
```
O | Convert to code points
·∏Ö‚Åπ | Convert from base 256 to decimal
%211 | Mod 211
“Ẏ...Ṿ‘iⱮ | Find indices in [209,80,92,55,21,162,24,118,115,42,193,137,85,102,82,77,74,105,189,86,146,41,46,90,10,144,34,125,126,173,121,72,133,199,134,186]
ịØB | Index into 01234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ
```
[Answer]
# dzaima/APL, ~~80~~ ~~79~~ ~~73~~ ~~72~~ 71 bytes
```
' P FL6BDEZQA SY574H TVOK J 08 M U IC92XW 3G1RN'⊇⍨52|8965|2411⊥¨⎕ucs
```
[Try it online!](https://tio.run/##TY5NSgNBEIX3OUXtOlkIzpiJyTIzavtXGttoWe4GJSAoCOJGsh4xEFHEIwg5h0fpi4yvO4lMN0O9nnrv45WP9xu3L@XdQ1lPfPXRrg2NiPaOe/nO7vXZkM412@7u0/jy9IgOabNPxEQXdFAM0iuhLZu4E@Nnr36@yNJpf9DLpmk3Sfzs53fh37@fb57qTgsC6AkZZmE2ZMThYjqc5rTMbE30CTfeyhpzax9erOaf66svP3/z1We7RYCz2JBXtayQObwCLYqNCwsrJhgtO@DxhYORo52LEhsXcuyWRoRgVFU4hG0eWSgJEog21FwTZUWUJTGAuFgRXcMohYQqWITfkA60HOmgxcaOnfoP "APL (dzaima/APL) – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~45~~ 44 bytes
```
40ö98%•Wþ@»Ý¢a:µ@,–çòßuÒ¹₃©6µć‚FVÝ∊J?•2ôžLR‡
```
[Try it online!](https://tio.run/##PY4xSwNBEIX/ihzYXRGCiElj2AMHxGm2yHCIRQIprCzE/tBCsdQuEELSBFsxggRS7CR/ZP/IOezsHFvsx5uZ997D42R6P2vbsx7/Di5OY7Mm3o/CjhdhPRmG7aiMzSdv@JuXT/wR/uLzS/g6D9vDa2zmV2NexLf360s56/PPcX/jY7Nq29uCEJGK8qSoASABOfIGLoFsOJcUnxUBvSJ0eYSdYjuiYHJGeXrl1bmW0KxYloBXyH3QzsmKSZL1qXXkzRCpy0IFkB9yujqLQpX1STuVB1dbBKhzl46VyzUIFQANdJkcSPrdPw "05AB1E – Try It Online")
Takes input as array of columns, and outputs an array of characters.
Explanation:
```
40ö # convert each column from base 40
98% # modulo 98
•...•2ô # compressed array: [20, 32, 82, 30, 27, 28, 76, 89, 46, 96, 36, 4, 18, 12, 80, 75, 50, 86, 42, 2, 52, 92, 48, 0, 84, 1, 88, 90, 10, 26, 70, 41, 94, 64, 14, 60]
žLR # built-in array 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz
‡ # transliterate
```
[Answer]
# [R](https://www.r-project.org/), ~~143~~ 128 bytes
```
function(v)c(0:9,LETTERS)[match(colSums((sapply(v,U<-utf8ToInt)*194:198)%%45:41),U("#</Eb=,n9J.M4Z+%*V N[Hd\\B?1Oj>KgRYT2")+34)]
```
[Try it online!](https://tio.run/##rVLRTttAEHz3V0RGkc/gtE1JJRKlVLXjXoAsbjcJ24P0IXWVlgocVBwkvj6dOzuBlNeeZd2eZ2Zn99Z/1ot@a71YFXl5vSzUQ5irN71uNEonk5TH4dXtvMx/qXx5M17d3it1P7@7u3lUD9G031qVi6PJ8qQow/12t9Nrd4/CZrPzrtdph9FU@Xv91@n391HRPX1FncuD5v5F4/xq@GM2iz@0s9/HZz/ZTN764cFhJ/y23muQMGvSho2HAzMTFhMOAoSEDFOjddwYpqNRJhmPBhue1DwSEWQgMZ63ULkKyEJBFAjjwQ7yzq7hoLGDJ/TsbMg43YaHE5kgDD0vn5cqaP3fNSsCZEabhOpRiDGaDMIYpmJsO0DYAloS8DS6Je2uxzYOntgNLxC2MmyWBwl4xhgQhHTsMqFX5EE@7bq1NzoZpl@mJ8lZzJmcf8q@nk7pczrILlIGMvp4aQaZHlfGUhtLZWz9KKmN2SaMHU8SsfXiu/2KkGEaC7lYNArAiNyMfNShtR81fDcsG7hp2QBqSSoIkYPArQI7GQQeMFPJ7NDMJqBaT5vUUnPoyYOd/hlJV1iMJTu2Vr7xcLJtjZ5Laf5xoyTeaWRb0YtmvScS1y35sr2IWHNdSC17YWb1rkg/YR0b3/6j678 "R – Try It Online")
Function taking a vector of strings (corresponding to the columns) as input e.g. :
```
MWRRG
MRRRM
WWRRM -> c('MMWMM','WRWRW','RRRRW','RRRRW','GMMMG') -> HELLO
MRRRM
MWWWG
```
Explanation :
Performing the following operation for each encoded string (e.g 'CRGBY' = 'S') :
```
TO ASCII MULTIPLICATION MODULO SUM & TO
CODEPOINT OFFSET ASCII
---------------------------------------------------------------------------------------------
'C' 67 67 * 194 = 12998 12998 %% 45 = 38 \
'R' 82 82 * 195 = 15990 15990 %% 44 = 18 |
'G' ---> 71 ---> 71 * 196 = 13916 ---> 13916 %% 43 = 27 |---> (140 - 34) = 106 ---> 'j'
'B' 66 66 * 197 = 13002 13002 %% 42 = 24 |
'Y' 89 89 * 198 = 17622 17622 %% 41 = 33 /
```
we obtain the following string `'#</Eb=,n9J.M4Z+%*V N[Hd\B?1Oj>KgRYT2'` where each character corresponds to `'0123456789ABCDEFGHIJKLMNOPQR'`.
So, the code performs the described operations on the input strings, then searches their correspondences inside `'#</Eb=,n9J.M4Z+%*V N[Hd\B?1Oj>KgRYT2'` obtaining the positions in string `'0123456789ABCDEFGHIJKLMNOPQR'`.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 66 bytes
```
WS§”*&_⟲⎇4>υ≧Y⪪ml^π≕t.A;p↶⧴q⊗Hε‖r¡¡ºÞd⸿σC⁺⮌”﹪﹪﹪⍘ιWMYCBGR³⁶⁰¦¹¹³¦⁷¹
```
[Try it online!](https://tio.run/##VY3JqsJAEEX3@YpLVt0QwRifA66MQ17UcohD2@6CBg2E5BHj8Pf9CtSFVXDugVtQx0tcHos4M@ZxSbMEIsz/btW6KtP8LKTEkqUS/SrMT8lT2IsdRvvO73ow/gn7mGETAG4bhGU38tEEpjjoBuoTBaDlrTAfsmxhO6DidMsK8R1@fE3ez1IHtiI98IPIlg68Vp3puh6z7Uope8YQKSJLRbxWxPNhQESBxa2it2vSfPlq2UhbpnbP/gE "Charcoal – Try It Online") Link is to verbose version of code. Takes input as a list of columns terminated with a blank line. Explanation:
```
WS
```
Input strings until one is blank.
```
§”*&_⟲⎇4>υ≧Y⪪ml^π≕t.A;p↶⧴q⊗Hε‖r¡¡ºÞd⸿σC⁺⮌”
```
Cyclically index into the string `OV EX8HSCF5IA L TG 17 M P9RB 4 K ZY2 0JW 63Q ND U` which (with trailing space) is 56 characters long.
```
﹪﹪﹪⍘ιWMYCBGR³⁶⁰¦¹¹³¦⁷¹
```
Perform base-7 conversion using the alphabet `WMYCBGR` and then reduce successively modulo 360, 113, 71, and 56 implicitly via the cyclic indexing.
My base 7 approach fared really badly with @Arnauld's fixed font; after some searching I was still at 73 bytes. Using @Grimy's approach cut this down to 67 bytes. However I eventually tracked down a 66 byte solution:
```
WS§”*&″ÀM↔↓<J;×⊟ςF,Gηe↖ητγ´WIY³﹪▶⟧9?δc⁶AxDê↷hPiψ”﹪﹪﹪⍘ι⁴⁷¦²³⁷¦⁷³¦⁶⁷
```
[Try it online!](https://tio.run/##VY1LC4JQEIX3/oqDq3vBoNKyaNXTrKZMK7OdpJQgGmaPf3@79lh0Br754AzM8RwWxzxMhXickzQGs7PLrfTKIslOjHM4UkrWL@0sip9MtUeY9qlhdrDzjAl0F2OnPVwDB2wHWKEO7IEuqlhvtjbL2XzRDCr3VQ2UR7c0Z/9rEF7j789Eg2FyDU29oqlLtE3OeU8IIp9I8V05iivzo0VEliJbn74eUCAvP600ChRRu6cv "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
WS
```
Input strings until one is blank.
```
§”*&″ÀM↔↓<J;×⊟ςF,Gηe↖ητγ´WIY³﹪▶⟧9?δc⁶AxDê↷hPiψ”
```
Cyclically index into the string `ID HAM178 VS4F 3R EP6CQ Z UB O 0 X 9 G 5TNJKL2Y W` which is 63 characters long.
```
﹪﹪﹪⍘ι⁴⁷¦²³⁷¦⁷³¦⁶⁷
```
Perform base-47 conversion using the alphabet `0-9A-Za-k` and then reduce successively modulo 237, 73, 67, and 63 implicitly via the cyclic indexing.
[Answer]
### CJam (63 bytes)
```
{{Gb"õáÖÅ{a("{i%}/"
@/Ö´çýß}yùÜÅ©GôÉç¢"256b43b'0f+=}%}
```
or in xxd format
```
0000000: 7b7b 4762 22f5 e1d6 c59f 7b61 2822 7b69 {{Gb".....{a("{i
0000010: 257d 2f22 0b8a 8340 982f d6b4 e793 fddf %}/"...@./......
0000020: 7d79 f9dc c519 17a9 0e47 0ef4 c9e7 a222 }y.......G....."
0000030: 3235 3662 3433 6227 3066 2b3d 7d25 7d 256b43b'0f+=}%}
```
This is an anonymous block (function) which expects input as a list of columns. [Online demo](http://cjam.aditsu.net/#code=qN%25%0A%0A%20%20%7B%7BGb%22%C3%B5%C3%A1%C3%96%C3%85%C2%9F%7Ba(%22%7Bi%25%7D%2F%22%0B%C2%8A%C2%83%40%C2%98%2F%C3%96%C2%B4%C3%A7%C2%93%C3%BD%C3%9F%7Dy%C3%B9%C3%9C%C3%85%19%17%C2%A9%0EG%0E%C3%B4%C3%89%C3%A7%C2%A2%22256b43b'0f%2B%3D%7D%25%7D%0A%0A~&input=WMMMW%0AYGGGW%0AWBWRW%0ABWWBW%0AMMWBB%0ARRWBW%0ARRWMW%0AMMBBB%0AMMWMW%0AMMWBW%0AWMWMM%0AYMYMY%0AWRRRW%0AYMMMY%0AWRWRW%0AWRWRR%0AWRMMW%0AMMWMM%0AWGGGW%0ABBBBW%0AMMYMM%0ARRRRW%0AMWWMM%0AYMMMM%0AGMMMG%0AYMYRR%0AGMMWC%0AYMYMM%0ACRGBY%0AWGGGG%0AMMMMW%0AMMMCB%0AMMWWM%0AMMGMM%0AMMGGG%0AWBGRW).
As many of the other answers, this does a base conversion followed by a chain of % to get a short lookup table. In this case I use base 16 and % chain `[245 225 214 197 159 123 97 40]`.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 48 [bytes](https://github.com/DennisMitchell/jelly/wiki.Code-page)
```
OḌ%⁽qƥ%⁹%53“ð×⁼ẎėWWæ¤jḌṛ>÷ƭÑṙsṛḌz0Ġọµḷ’b51¤iⱮịØB
```
A monadic Link accepting a list of lists of uppercase characters (each being a column) which yields a list of characters.
**[Try it online!](https://tio.run/##fZC/TsMwEMZfpUuVpQMIdWVwBk8nJC8nq2KpxNCqC2KCqZ0pSExtBUOHwlYEA2pDYYmrvof9IuZs51DCgD3k893vuz8ZXoxG196f2e207Sbfl4dn@hTt7okbP5k3M3OTL/t5v58hmpdyNSTMFo@nZnNYmwdbLK7oRbGbo/3S7u7KD7vduPGi3z0uVwP3/mp3t2YuvPe9DAEAs04rQ0knCHoDxIiiG4SmTBSScnliaq4klEowgK7sgu0U0SygqgPcCyGlIKUEko@7qz@wTAy5hIgwHWzME@pVBXWy50qK2J3mI7jVqReEXDQ35QkJhgj/81sAqH1gFO@Ov4yQzNTsyJvqxl6oeHgIE57/AA "Jelly – Try It Online")**
### How?
```
OḌ%⁽qƥ%⁹%53“...’b51¤iⱮịØB - Link: columns
O - ordinals
Ḍ - convert from base ten
%⁽qƥ - modulo 29415
%‚Åπ - modulo 256
%53 - modulo 53
iⱮ - map with first index of x in:
¤ - nilad followed by link(s) as a nilad:
“...’ - 22270425059867513817410846141176204460122938458128124185752719
b - convert to base
51 - 51
- ... = [38,13,19,27,10,16,20,11,35,31,4,17,9,0,50,45,24,25,34,39,22,29,41,32,3,7,46,5,48,18,6,44,28,14,1,8]
ị - index into
√òB - "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 109 bytes
```
->n{n.map{|i|"6&\278$Cc\17Y9\23T\r]{v^Ox\16_+!Qj\fbH
hraD*Ap".index((i.to_i(36)%245%119+8).chr).to_s(36)}*""}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y6vOk8vN7GguiazRslMLcbI3ELFOTnG0DzSMsbIOCSmKLa6LM6/IsbQLF5bMTArJi3JgyujKNFFy7FASS8zLyW1QkMjU68kPz5Tw9hMU9XIxFTV0NBS20JTLzmjSBMkUQySqNVSUqr9X6CQFh2t7usb7uurrqMeHgSEQDoICJBpd19fX3f12Nj/AA "Ruby – Try It Online")
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 46 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
é►^njÖ_╪»Θîq╪↨δXû=▀úæ5?ªoéV╫╫╩ßH‼╒C═e┼$⌠°JqUu⌡
```
[Run and debug it](https://staxlang.xyz/#p=82105e6e6a995fd8afe98c71d817eb58963ddfa391353fa66f8256d7d7cae14813d543cd65c524f4f84a715575f5&i=WYWBMRRMMMWYWYWWWMWBMRMYGYGYCWMMMMMW%0AMGBWMRRMMMMMRMRRRMGBMRWMMMMMRGMMMMMB%0AMGWWWWWBWWWYRMWWMWGBYRWMMYMYGGMMWGGG%0AMGRBBBMBMBMMRMRRMMGBMRMMMRWMBGMCWMGR%0AWWWWBWWBWWMYWYWRWMWWMWMMGRCMYGWBMMGW%0A%0AWMWGMWWMYYGMYWGMBMMYWYGMWYWMWRWWMYGW%0AGMRMMGRMMMMMMRMMBMWMRMMMRMGMRRMBMMMR%0AGWWMMGRYYYMWMWMGBMWYWMMMWYGWWRWGGMMM%0AGMRWMGRMMMMWMRMMBMMRRMMCRMGMRRMRGMMM%0AGMWCWWWMYMGMMRGMWWMRWYGBWMGMWWMWGYGW&a=1&m=1)
Each column is decoded as base-36. Successive modulus of 8273, then 95 are applied. This yields a unique number, looked up in a fixed string.
It takes input exactly in the format specified in the examples, and has to transpose them to get columns. I will be able to save some bytes by using some different input format, which I may do at some point.
] |
[Question]
[
**Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers.
---
**Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/25670/edit).
Closed 6 years ago.
[Improve this question](/posts/25670/edit)
In as few bytes as possible, your job is to write a program that outputs:
```
3.14
```
In celebration of a late Pi day of course! :)
## Rules
You can do it anyway you like, but there are some restrictions.
* You may **not** use arithmetic operations anywhere in your program. This includes `+`, `-`, `*`, `/`, `%`, `^` (exponentiation), etc... This also includes incrementing (usually `++`), decrementing (`--`), **bitwise operations**, and any built in functions that can be used as a replacement such as `sum()`, `prod()`, `mod()`, `double()`, `pow()`, `sqrt()`, `inc()`, `dec()`, etc... (Author's discretion)
* The digits `3`, `1`, and `4` may **not** appear anywhere in your code.
* You may **not** use any predefined variables/constants that your language may have as a replacement for `3`, `1`, and `4`. (Author's discretion)
* You may also **not** use any trigonometric functions such as `sin()`, `cos()`, `tan()`, `arcsin()`, `arccos()`, `arctan()`, `sinh()`, `cosh()`, `tanh()`, etc... (Author's discretion)
* You may **not** use built-in or predefined values of Pi (or `3.14`). *No web requests*.
* Your program **cannot** require input of any kind (besides running it).
* `3.14` is the **only** thing that you may output, it cannot be part of some longer/larger output..
## Winner
The answer with the least amount of bytes on **April 18th** wins. Good luck!
Looking forward to clever answers from clever minds! Malbolge anyone? :P
[Answer]
## PHP - 22 bytes
```
<?=date('n.j',8899e5);
```
Pi Day in year 1998 was really cool!
[Answer]
## C, 39
*Assumes the machine is little-endian and uses IEEE floating-point standard.*
```
main(){printf("%.2f",*(float*)"P@I@");}
```
The fun fact is that `"P@I@"` is actually not related to `PI` but is equivalent to `0x40494050` which is the representation of `3.144550323486328`
<http://ideone.com/uXVEtl>
[Answer]
# [dc](http://www.gnu.org/software/bc/manual/dc-1.05/), 11 9 bytes
```
zE[.]znPp
```
* `z` Push current stack depth (0) onto the stack
* `E` Push E16 (==1410)
* `[.]` Push the string "."
* `z` Push current stack depth (3) onto the stack
* `n` Pop 3 and print as number
* `P` Pop "." and print as char
* `p` Pop 14 and print as number with newline
Output:
```
$ dc <<< zE[.]znPp
3.14
$
```
[Answer]
# JavaScript (*ES5*) 20 bytes
A variation of m.buettner's JS solution.
```
(x='.'+0xE).length+x
```
---
# Edit: JavaScript (*ES5*) 18 bytes
A variation of ComFreek's idea of using the base64 decode function.
```
atob('Mw')+'.'+0xE
```
---
# Edit: Javascript (*ES5*) 16 bytes
If the unary `+` operator is allowed to cast a string to a number, it can be reduced to:
```
+atob('MDMuMTQ')
```
[Answer]
# Haskell, 41 bytes
When is pi day in Australia?
```
p=(\(a:n:y:t:i:m:e:_)->[m,a,t,e])['.'..]
```
Edited to add: like the other Haskell answer, that outputs a string, so has quotes. You can score 33, and be strictly within the rules, but it's less fun:
```
p=putStr$map([','..]!!)[7,2,5,8]
```
[Answer]
**Morse Code, 33 Bytes**
```
morse -d ...-- .-.-.- .---- ....-
```
Technically speaking, the information only takes 21 bytes.
[Answer]
# J - ~~15~~ ~~11~~ 10 char
Made it shorter, using the fantastic `i:`.
```
6{i:6.28j8
```
Explained:
* `6.28j8` - The complex number 6.28 + 8i.
* `i:` - This is where the magic happens. `i:` on a complex number A+Bi, B≠0 takes B+1 equally spaced points from the interval [-A,A].
* `6{` - Take element at index 6, which just so happens to be 3.14.
Previously, we had the following nonsense:
```
|.'.'2}":22b8d5
```
Explained by explosion:
```
22b8d5 NB. 8d5 in base 22 = 4163
": NB. convert to string
'.'2} NB. change character at index 2 to '.'
|. NB. reverse to make '3.14'
```
[Answer]
# CJam - ~~8~~ 6
```
S`,'.E
```
CJam is a new language I am developing, similar to GolfScript - <http://sf.net/p/cjam>.
Here is the explanation:
`S` is a variable preinitialized to space (" ")
``` generates the string representation of the last value - which is exactly `" "` (3 characters)
`,` calculates the string length (3)
`'.` is the dot character
`E` is a variable preinitialized to 14; 3, 1 and 4 are not allowed but it doesn't say anything about 14 :)
Credits to Doorknob for the backtick idea
[Answer]
# Linux command line, 35 bytes
This one is nowhere near winning, but here it is for the fun of it:
```
ping -w2 67502862|grep -oP '.\..\d'
```
Output (after 2 seconds):
```
$ ping -w2 67502862|grep -oP '.\..\d'
3.14
$
```
[Answer]
# GolfScript, ~~18~~ ~~13~~ 12
```
'.'.`,\.,n`,
```
Old version:
```
'...','.'.,'....',
```
It's very artistic, only 3 unique characters! ;)
How it works:
```
# cmd # stack
'...', # 3
'.'. # 3 '.' '.'
, # 3 '.' 1
'....', # 3 '.' 1 4
```
Here's an explanation of the 12-char version (much more interesting, IMO):
```
'.' # '.'
.`, # '.' 3
\. # 3 '.' '.'
, # 3 '.' 1
n`, # 3 '.' 1 4
```
It works because `n`,` is `4`, since `n`` is `'"\n"'`. Same logic for `'.'`,`. It also swaps instead of creating a new string to save a char (thanks @algorithmshark).
Alternate version:
```
'pi ','.'.,'day!',
```
or
```
'Hi ','.'.,'PPCG',
```
Or anything in those strings, really. :P
[Answer]
OP's answer.
# Mathematica, 21 20 18
This feels cheap...
```
Range[2,5,.06][[20]]
```
or
```
Range[2,5,.02][[58]]
```
Figured out how to make it 18:
```
Range[-.86,5][[5]]
```
# Haskell, 49 48 12
(48 includes the new line character)
```
p=[-6..]
r=concat$show(p!!9):".":(show$p!!20):[]
```
Run it by calling the `r` function.
Using the method as with Mathematica above, you can type this into GHCi:
```
[-2.86..]!!6
```
# Java, 87 86
```
class P{public static void main(String[]a){System.out.print("tri".length()+"."+0xe);}}
```
# Scala, 27
Translated from Java as suggested by **Score\_Under**. (I don't really know Scala)
```
print("tri".length+"."+0xe)
```
[Answer]
# Bash, 50
Help/error messages aren't external resources, they're a command's output!
If anything is rule abuse, this is it. It uses the coincidence that the help message given to `STDERR` by the exact command
```
ping6
```
is 314 characters long (at least on Ubuntu 13.10 with `iputils-121221`). EDIT: I appreciate that this is much less portable than I expected...
```
m=`ping6|&wc -c`
false
o=$?
echo ${m:0:o}.${m:o:2}
```
The first line takes the character length of the help message and stores it in a variable.
As in my other answers, the next few lines obtain the number 1 by taking the exit status of `false` (not very portable but this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") after all!), then use that value to insert a decimal point in the last line
Output: `3.14`
[Answer]
# Bash+TeX 28 bytes
If you have TeX installed:
```
tex -v|head -c8|cut -d\ -f2
```
The version number of TeX asymptotically approaches pi as the software improves. So, as time goes on, you can use this (nonconforming) implementation to print more and more digits!
```
tex -v|cut -d\ -f2 | head -n1
```
This printed 3.1415926 back in 2011; as of January 2014, it will print 3.14159265.
[Answer]
## JavaScript, 20 bytes
```
'...'.length+'.'+0xe
```
Use it in a console, so that the result is directly printed. Otherwise, `alert(...)` will add another 7 characters.
Same as my other answer, I just noticed it's a lot shorter in JS.
The idea of using `0xe` for 14 is taken from the OP's submission with the OP's kind permission.
[Answer]
# GNU date, 17 bytes
```
date -d2/5 +%u.%y
```
This one only guaranteed to work this year, but I don't see any limitation in the rules about this ;-)
The `+` is simply indicates the start of the format specifier for `date` and is not an arithmetic addition. Same with the `-`, indicating input date.
Output:
```
$ date -d2/5 +%u.%y
3.14
$
```
[Answer]
# Bash, 17 bytes
```
tr 0 .<<<$[62#MC]
```
---
# Dash, 41 bytes
```
perl -pechomp,s/./$./<<$
..
.
```
[Answer]
## Bash 23 22
```
seq 2 .02 5|sed -n 58p
```
---
## Shell (without history expansion) 20
```
seq 2 .02 5|sed 58!d
```
[Answer]
## Python, 39 or 28 ~~47 or 34~~
(Thank you Score\_Under for golfing it down so much)
```
print"%s.%s%c"%(len('aaa'),len('a'),52)
```
`+` here is the string concatenation operator, not addition.
Copying the `0xe` trick from the OP, here's 28 chars with help from @psal
```
print('%X.%s'%(675,0xE))[2:]
```
Old versions:
```
print str(len('aaa'))+'.'+str(len('a'))+chr(52)
print str(len('aaa'))+'.'+str(0xe)
print"%s.%s"%(len('aaa'),0xe)
```
[Answer]
# GolfScript, 8 bytes
```
'??.'(\(
```
This program contains non-printable ASCII characters, so it cannot be directly pasted here. Instead, the question marks in the code above should be replaced with the bytes `03` and `0E` in hexadecimal.
For convenience, here's a hex dump of the actual program. Unix / Linux users can run this hex dump through `xxd -r` to reconstruct the program:
```
0000000: 2703 0e2e 2728 5c28 '...'(\(
```
Explanation:
* The first five bytes of the program form a single-quoted string literal encoding the three characters with the ASCII codes 3, 14 and 46 (= ASCII period).
* `(` chops the first character off the string and pushes its ASCII code (3) on the stack. `\` swaps the top two items on the stack, pulling the string back to the top, and the second `(` chops another character off the string, again pushing its ASCII code (14) on the stack.
At the end of the program, the stack (excluding the empty input string) therefore looks like this:
```
3 "." 14
```
At the end of the program, the default behavior of the GolfScript interpreter is to stringify and print everything on the stack, yielding the desired output.
[Answer]
# bash -- 39
We all know that the first few digits of Pi can be computed from the following statement:
>
> May I have a large container of coffee
>
>
>
We need only 2 decimal places, right?
```
m=May
i=I
h=have
echo ${#m}.${#i}${#h}
```
[Answer]
## Mathematica - 78
```
DateList["March"<>ToString@FromDigits@"E"]~DateString~{"MonthShort",".","Day"}
```
[Answer]
## Perl, 15 20 bytes
```
print 05706=~s/0/./r
print 0xbc6=~s/0/./r
```
[Answer]
# [tr](http://www.gnu.org/software/coreutils/manual/html_node/tr-invocation.html) + Bash, 17 bytes
```
tr a-j 0-9<<<d.be
```
The `-` chars here are not arithmetic subtraction operators. They indicate range.
Output:
```
$ tr a-j 0-9<<<d.be
3.14
$
```
[Answer]
## BASH, 57
This is longer than most answers, but there is nothing bad in trying.
```
f=`echo aaaaaaaaaaaaa|wc -c`;e=`echo aa|wc -c`;echo $e.$f
```
gives
```
3.14
```
[Answer]
## C, 36
```
main(){printf("%d\b.%o\b",' ','`');}
```
[Answer]
## JavaScript - 23 bytes
```
atob('Mw')+atob('LjE0')
```
Thanks to nderscore (see his comments)!
[Answer]
**C#**
```
((int)'ĺ').ToString("#\\.##");
```
ĺ is character 314, not a pre-defined variable or constant.
the .ToString formats the output into a digit, a period, and then 2 more digits.
[Answer]
# GolfScript, ~~13~~ 10
```
{xy}.*'.'\
```
Thanks to **Ilmari Karonen** for the improved version!
`x` and `y` are non-printable characters (see <http://www.asciitable.com/> for more info), respectively `ETX` and `SO`, which decode to 3 and 14.
What this code does should be pretty clear.
**Note:** The following rule
`You may not use any predefined variables/constants that your language may have as a replacement for 3, 1, and 4. (Author's discretion)`
is not broken, since ASCII characters are neither variables, nor constants.
[Answer]
New to the site and can't write comments yet, so I'll post it here. Just wondering about this Javascript solution:
```
'...'.length+'.'+0xe
```
and this rule:
*3.14 is the only thing that you may output, it cannot be part of some longer/larger output..*
If I run this code in my browser console, I get:
```
"3.14"
```
or using Node at the command line:
```
'3.14'
```
but if I run this code:
```
parseFloat('...'.length+'.'+0xe)
```
I get:
```
3.14
```
Using Node.js to run a .js file, I can write:
```
console.log('...'.length+'.'+0xe)
```
and get:
```
3.14
```
[Answer]
## Mathematica, 56 bytes
```
(l=ToString@StringLength@#&)@"..."<>"."<>l@"."<>l@"...."
```
Not much to say. I'm generating the digits as string lengths and concatenate them.
] |
[Question]
[
This seems almost trivial, but since after some effort I was not able to beat the literal solution in J, I thought it might make a decent challenge (though, to be clear, this is not a J-specific challenge).
Title says it all. You simply need to write a program, or function (taking no arguments) that returns or prints:
```
N NE E SE S SW W NW
```
You may use newlines in place of spaces.
A no-argument function returning an array of strings such as
```
['N', 'NE', 'E', 'SE', 'S', 'SW', 'W', 'NW']
```
is also acceptable.
The letters may be upper or lower case, but may not be mixed.
[Answer]
# bash (24 bytes)
using brace expansion
```
echo N {N,,S}E S {S,,N}W
```
is the same length as hard coding
```
echo N NE E SE S SW W NW
```
however it becomes more interesting when outputing more points of the compass
```
echo N NNE NE ENE E ESE SE SSE S SSW SW WSW W WNW NW NNW
```
brace expansion
```
echo N {{N,,E}N,,{E,,S}S}E S {{S,,W}S,,{W,,N}N}W
```
otherwise if order could be changed, (17 bytes), the trick is that without quotes the empy string parameter disappears
```
echo {N,,S}{W,,E}
```
[Answer]
# [Mornington Crescent](https://github.com/padarom/esoterpret), ~~4395~~ 3823 bytes
```
Take Northern Line to Bank
Take District Line to Parsons Green
Take District Line to Paddington
Take Bakerloo Line to North Wembley
Take Bakerloo Line to Charing Cross
Take Bakerloo Line to Charing Cross
Take Bakerloo Line to Charing Cross
Take Bakerloo Line to Charing Cross
Take Northern Line to Bank
Take Circle Line to Hammersmith
Take Circle Line to Paddington
Take Circle Line to Hammersmith
Take Circle Line to Barbican
Take Circle Line to Bank
Take Circle Line to Aldgate
Take Circle Line to Embankment
Take Bakerloo Line to Charing Cross
Take Bakerloo Line to Charing Cross
Take Bakerloo Line to Charing Cross
Take Bakerloo Line to Charing Cross
Take Northern Line to Bank
Take Circle Line to Hammersmith
Take Circle Line to Bayswater
Take Circle Line to Hammersmith
Take Circle Line to Baker Street
Take Circle Line to Bank
Take Circle Line to Embankment
Take Northern Line to Stockwell
Take Northern Line to Charing Cross
Take Northern Line to Charing Cross
Take Northern Line to Charing Cross
Take Northern Line to Charing Cross
Take Northern Line to Bank
Take Circle Line to Hammersmith
Take Circle Line to Farringdon
Take Circle Line to Hammersmith
Take Circle Line to Blackfriars
Take Circle Line to Bank
Take Circle Line to Moorgate
Take Northern Line to Waterloo
Take Northern Line to Charing Cross
Take Northern Line to Charing Cross
Take Northern Line to Charing Cross
Take Northern Line to Charing Cross
Take Northern Line to Bank
Take Circle Line to Hammersmith
Take Circle Line to Westminster
Take Circle Line to Hammersmith
Take Circle Line to Tower Hill
Take Circle Line to Bank
Take Circle Line to Edgware Road
Take Circle Line to Liverpool Street
Take Central Line to Mile End
Take District Line to Victoria
Take Victoria Line to Seven Sisters
Take Victoria Line to Victoria
Take Circle Line to Victoria
Take District Line to Mile End
Take District Line to Bank
Take Circle Line to Bank
Take Northern Line to Charing Cross
Take Northern Line to Charing Cross
Take Northern Line to Charing Cross
Take Northern Line to Charing Cross
Take Northern Line to Bank
Take Circle Line to Hammersmith
Take Circle Line to Paddington
Take Circle Line to Paddington
Take Circle Line to Barbican
Take Circle Line to Paddington
Take Circle Line to Paddington
Take Circle Line to Bayswater
Take Circle Line to Paddington
Take Circle Line to Paddington
Take Circle Line to Hammersmith
Take Circle Line to Paddington
Take Circle Line to Paddington
Take Circle Line to Baker Street
Take Circle Line to Paddington
Take Circle Line to Paddington
Take Circle Line to Hammersmith
Take Circle Line to Paddington
Take Circle Line to Paddington
Take Circle Line to Farringdon
Take Circle Line to Paddington
Take Circle Line to Paddington
Take Circle Line to Embankment
Take Circle Line to Paddington
Take Circle Line to Paddington
Take Circle Line to Hammersmith
Take Circle Line to Paddington
Take Circle Line to Paddington
Take Circle Line to Blackfriars
Take Circle Line to Paddington
Take Circle Line to Paddington
Take Circle Line to Hammersmith
Take Circle Line to Paddington
Take Circle Line to Paddington
Take Circle Line to Moorgate
Take Circle Line to Paddington
Take Circle Line to Paddington
Take Circle Line to Westminster
Take Circle Line to Paddington
Take Circle Line to Paddington
Take Circle Line to Hammersmith
Take Circle Line to Paddington
Take Circle Line to Paddington
Take Circle Line to Tower Hill
Take Circle Line to Paddington
Take Circle Line to Paddington
Take Circle Line to Hammersmith
Take Circle Line to Paddington
Take Circle Line to Paddington
Take Circle Line to Aldgate
Take Circle Line to Paddington
Take Circle Line to Paddington
Take Circle Line to Edgware Road
Take Circle Line to Paddington
Take Circle Line to Bank
Take Circle Line to Bank
Take Northern Line to Mornington Crescent
```
[Try it online!](https://tio.run/##3VfBbsIwDL3vK/ID@4iVsXGAaVrROIfWg6hJPDkRFV/PAohWLaSh7YY6LpWiZzvOs53XKCQt9MqifkwITALa7nZzngF7Q7JrIM2mQgOzyCKus4cD9CyMJZHYAnrnZFAb9koA2muTpsedjgaR@5BELAwOG7IFqKWErcdmtObkgrARoTG3t2ngZCQokVAAE64UkFHCri/idTZaukecliLh2gN6knqS6YpbuIiN1dK5KVf/e6c@4luTOxqoo7fLlcXWdbptx36d4bMTxRaTLAcpPfg1rNzSpnMFXjjtg6ddm1/yJPsi4S6ddhWYIVI5AGfnWeybwrXhvdO/AGOV0KbrCMwxdyMwEadGvXoA0lXOCdgH8vSiwVRsgL4RZXW@3MQQl2UVhXMZ69SjM59uga45jvBpVQ4ZbECzWOxPbzw21RC1JKvg2faB7LzklMD9Nl5A9AJwo@b1Dd0kCf1i/zUpATkacvIBHegXvC63/6moAYEbcu5Vjf3V0CHdGjItAc0ccupNr4aeIxr6IQhefu3FdFY8eJ3GnR68Pw "Mornington Crescent – Try It Online")
Since it's a bit much to expect you to read all that, let me give a quick overview of my approach. The main idea is to store 3 copies of the characters `N`,`E`,`S`,`W` at various stations on the Circle line, via Bank - Hammersmith. These characters are constructed from the start of a station name at Charing Cross. Then, construct from the middle of a well-chosen station name using Mile End and Charing Cross, and store it at Bank so that it can be collected at Hammersmith in the concatenation. Finally, concatenate the characters one by one at Paddington, copying them again via Bank - Hammersmith if they are need to be reused later.
---
I think the current solution is fairly close to optimal with this strategy, at least in terms of number of stations visited: just 2 times I used a station *only* for transit:
1. to get to Seven Sisters (via Victoria station)
2. and to get back to Mornington Crescent (via Bank).
All other station visits were, if I didn't forget one, either storing/retrieving something useful or (part of) using the stations ability.
As for the line lengths, I've tried to pick the shortest names on Circle Line, but there may be a minor improvement there. It's possible that storing something on District can shave off a few bytes.
[Answer]
# [PHP](https://php.net/), 19 bytes
```
N NE E SE S SW W NW
```
[Try it online!](https://tio.run/##K8go@P/fT8HPVcFVIRiIFILDFcIV/ML//wcA "PHP – Try It Online")
Getting this out of the way. Someone will do it eventually.
[Answer]
# [brainfuck](https://github.com/TryItOnline/brainfuck), ~~142~~ ~~139~~ ~~131~~ 119 bytes
```
++++++++++[>+++>+++++++>++++++++>+++++++++<<<<-]>>>--.<<++.>>.<-.<.>.<.>>+++++.<.<.>>.<<.>>.>---.<<<.>>>.<<<.>>-----.>.
```
[Try it online!](https://tio.run/##SypKzMxLK03O/v9fGw6i7YCEHZQDoxEMbRsg0I21s7PT1dWzsdHW1rOz07MBMvXsQBiiDsiyAYuDSaBKkFIQ2w5K64IAUMf//wA "brainfuck – Try It Online")
Simply loops 10 times to fill the cells with 30, 70, 80 and 90 then steps backward and forwards and adjusts the cell values to print out the required characters. Not much different from the standard "Hello world!".
[Answer]
# [Canvas](https://github.com/dzaima/Canvas), 12 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md)
```
>X½+T)AuS{⁹‟
```
[Try it here!](https://dzaima.github.io/Canvas/?u=JXVGRjFFWCVCRCsldUZGMzQldUZGMDkldUZGMjF1UyU3QiV1MjA3OSV1MjAxRg__,v=8)
The string, simply compressed.
[Answer]
# [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 204 bytes
```
((((((((((((((((()()()){}()){}){}())){}{}))<([([][]){}()]{})(([][]){}[])>)<([][]
()())>)[[]]()())<([]()()())>)<((([]())[][]){}[][()])>)<([][()()])>[[]()])<([][((
)()){}])>)((()()())){}{})<((()()()()()){})>)
```
[Try it online!](https://tio.run/##XU5BDoAgDPvOduAHhI8sO6CJidF48Gp8@@xgcBCSspZ26XLX/UrbWQ8z@h/2y8/boL9AjJxJSFS0iQqFBgUU/wZr6cIi2kdXY6dbqFGeOcGmkXUTiLhDQ4oy7pndep08eFjgMLO0fg "Brain-Flak – Try It Online")
[Answer]
# [MarioLANG](https://github.com/tomsmeding/MarioLANG), 249 221 bytes
```
+
+
+
+
+
+
+
+
+ ((+++++++++)))<
+>==============="
)++++++++)+++((-[!)--.)++.(.---------.).(.).)++.((.).).(.).++++.(.).(.(+++++++++.))
=================#================================================================.
```
[Try it online!](https://tio.run/##y00syszPScxL//9fmwsNKihoaGjDgKampg2Xtp0tKlDi0oQrAGINDd1oRU1dXT0gR09DTxcG9DSBPE2IKJgB5oJ0gRkaegh79DQ1uWzRgbIthUDv/38A "MarioLANG – Try It Online")
[Answer]
# Excel Formula, ~~59~~ 57 bytes
The following should be entered as an array formula (`Ctrl`+`Shift`+`Enter`):
```
=SUBSTITUTE(ADDRESS(1,{14,369,5,499,19,517,23,387},4),1,)
```
After entering the formula as an array formula, highlight it in the formula bar and evaluate it using `F9` to return the result, for example:
Before:
[![Before formula evaluation](https://i.stack.imgur.com/PtDZ2.png)](https://i.stack.imgur.com/PtDZ2.png)
After:
[![Before formula evaluation](https://i.stack.imgur.com/4j6xH.png)](https://i.stack.imgur.com/4j6xH.png)
## How it works
The `ADDRESS` function returns a string representing a reference based on two parameters, `row` and `col`. The third parameter controls what type of reference is returned, an absolute or relative reference. For example, `=ADDRESS(1,2,4)` returns `"B1"`.
We can supply an array to `ADDRESS` and use it as an array formula to return multiple results, for example `=ADDRESS(1,{1,2,3},4)` returns `"A1","B1","C1"`.
Therefore, in my answer, the array supplied to `ADDRESS` are just the column numbers relating to the required compass points, e.g. Column 14 is column `N`, Column 369 is column `NE`.
However, we are not finished here since all the returned references have the row included, for example, `N1`, `NE1`. Therefore, we simply use `SUBSTITUTE` to remove the `1` from all references.
[Answer]
# [Deadfish~](https://github.com/TryItOnline/deadfish-), ~~188~~ 183 bytes
*-5 thanks to squid*
```
iiissdddc{ddddd}iiiicdddd{iiiii}c{d}ic{dddd}iiicddd{iiii}c{dddd}iiic{iiiii}ic{d}ddddc{dddd}iiic{iiiii}ic{ddddd}dci{iiiii}ciiiic{ddddd}dddddciiiii{iiiii}c{ddddd}dddddcdddd{iiiii}c{i}dc
```
[Try it online!](https://tio.run/##XY7LEYBACEMrsihno2POHBlqR8DFHyfIgwRsK3bKsbiTFAEwFFkWM0d2mh0tdOMFbSJt0NpczTXD7fVHpWGwjSup5Tor8OS@yOchhov7CQ "Deadfish~ – Try It Online")
[Answer]
# [Triangularity](https://github.com/Mr-Xcoder/Triangularity), 71 bytes
```
..... .....
...."W"....
..."W N"...
.." SW "+..
." SE S"++.
"N NE E"+
```
[Try it online!](https://tio.run/##KynKTMxLL81JLMosqfz/Xw8EFMAkF4hQCleCsZXCFfyUIGwlheBwBSVtEBvIdFUIVtLW1uNS8lPwc1VwVdJWUPj/HwA "Triangularity – Try It Online")
There are two spaces on the last line to hit the byte count Triangularity requires.
[Answer]
# [brainfuck](https://github.com/TryItOnline/brainfuck), 117 bytes
```
+++++[>++++++>+>+++>>++++>+++++<<<<<<-]>++[>++>++>+>++>++[<]>-]>>-.>.<.<.>>.<<.>>.>-.<<<.>>.>.<.>.>--.<<.>>.<<.<.>>>.
```
[Try it online!](https://tio.run/##LUpJCoAwDHxQSF4Q5iPSgy0IIngQ@v6YbQKZdX7n/V57PWYUOJBEoBBA6YAmeKBG6E1YHfAcLBD1g1N@T7RVxO65G60dxOwH "brainfuck – Try It Online")
This code will first create the characters "EN SW" into the memory and then move back and forth to print them. The space is in the middle, because it is printed most often. N and S and W and E never appear together so they are on opposite sides of the memory.
For optimization some of the final decrements happen during the output phase.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 14 bytes
```
”{⊟“�_Zn↖⦄RüΦ≦
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvREPJT8HPVcFVIRiIFILDFcIV/MKVNK3///@vW5YDAA "Charcoal – Try It Online") Link is to verbose version of code... which is just the string to be printed, as the auto-deverbosifier takes care of the string compression.
Printing the string uncompressed takes 19 bytes, since Charcoal prints printable ASCII literally. The best algorithmic answer I could come up with unfortunately takes 20 bytes:
```
E⁸ΦSNWE›³﹪⁻﹪⁺⁵×⁶μχι⁸
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM3sUDDQkfBLTOnJLVIQynYL9xVSUfBvSg1EcQ31lHwzU8pzcnX8M3MKy3WgHICcoBsUx2FkMzc1GINMx2FXE1NHQVDAyCRCcQWmiBg/f//f92yHAA "Charcoal – Try It Online") Outputs using array format (would cost two bytes to join the elements on spaces). Works by noticing that the letters of the string `SNWE` are used only when the current outer index equals or is 1 away (modulo 8) in either direction from the corresponding element of the list of indices `4,0,6,2`.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~62~~ ~~61~~ ~~58~~ 53 bytes
```
i=8
while i:print'NESESWNW'[~i+(i==4):][:1+i%2],;i-=1
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P9PWgqs8IzMnVSHTqqAoM69E3c812DU43C9cPbouU1sj09bWRNMqNtrKUDtT1ShWxzpT19bw/38A "Python 2 – Try It Online")
Not great, but at least not a plain print..
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~16~~ 15 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
“¤œỵpq⁵’ṃ“NESW
```
A full program printing the text
**[Try it online!](https://tio.run/##y0rNyan8//9Rw5xDS45Ofrh7a0Hho8atjxpmPtzZDBT0cw0OV/j/HwA "Jelly – Try It Online")**
---
16...
```
“¥Þ¡¦¢¬£æ‘ṃ“¡ɱ⁻»
```
A niladic Link which yields a list of lists of (lowercase) characters.
**[Try it online!](https://tio.run/##ATEAzv9qZWxsef//4oCcwqXDnsKhwqbCosKswqPDpuKAmOG5g@KAnMKhybHigbvCu//Dh0v/ "Jelly – Try It Online")**
---
Alternative 15 as a niladic Link which yields a list of (lowercase) characters (with spaces): `“¡XÇŀqỵÑ’ṃ“¡⁴ṁ»`.
[Answer]
# Commodore BASIC (TheC64Mini, C64, C128, VIC-20 etc.) 28 Tokenized BASIC bytes used
```
0 PRINT"N NE E SE S SW W NW
```
In Commodore BASIC, you do not require the closing quotation mark on `PRINT` or `LET` statements as the interpreter will auto-close it, this saves one BASIC token.
Alternatively, one may simply use direct mode as follows:
### Commodore BASIC 23 PETSCII characters (+ `RETURN` to execute)
```
?"N NE E SE S SW W NW
```
I'm not sure how to count the number of bytes used in this instance as according to the interpreter `?` and `PRINT` use the same number of bytes, and there is no program stored in memory.
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal), 13 bytes
```
«ƛ.←√Fǎ⁰ɾ@=½•
```
[Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%C2%AB%C6%9B.%E2%86%90%E2%88%9AF%C7%8E%E2%81%B0%C9%BE%40%3D%C2%BD%E2%80%A2&inputs=&header=&footer=)
-1 thanks to AaronMiller
Vyxal forever lads, it has crushed 05AB1E and Jelly I am so proud
[Answer]
# [Deadfish~](https://github.com/TryItOnline/deadfish-), 138 bytes
```
{{i}i}c{{d}}cs{i}c{d}ic{{d}}iisicsic{{d}}iisicisddddddc{d}ddddc{{d}}iisicisddddddc{{iiii}}sicisddddddciiiic{{d}d}icisddc{{d}d}ics{i}c{i}dc
```
[Try it online!](https://tio.run/##bY0xDsAwDAJf1EdVplWZPSLe7taJFGUoi80ZYVwnbuZzVEk0HRLsSPUKc3oyGbkbJoY6NOfPSfxk76zJyHZ302XmSxpR9QI "Deadfish~ – Try It Online")
So, outputting in lower-case with newlines is better than default (upper-case with spaces).
This code was generated by my optimizer, written in C++ (thanks to [squid](https://codegolf.stackexchange.com/users/85755/squid) for another optimization idea!):
```
#include <iostream>
#include <string>
#include <queue>
#include <vector>
int eval(const std::string& actions, int result)
{
int mult = 1;
for (int i = 0; i < (int)actions.length(); ++i)
{
switch (actions[i])
{
case 's':
result *= result;
if (result == 256)
result = 0;
break;
case '{':
mult *= 10;
break;
case '}':
mult /= 10;
break;
case 'd':
if (result > 256 && result - mult <= 256)
result = (result - mult) % 256;
else
result -= mult;
break;
case 'i':
if (result < 256 && result + mult >= 256)
result = (result + mult) % 256;
else
result += mult;
break;
}
}
return result;
}
struct worse
{
bool operator()(const std::string& a1, const std::string& a2)
{
return a1.length() > a2.length();
}
};
std::string BestStr(int accumulator, int target)
{
std::priority_queue<std::string, std::vector<std::string>, worse> actions;
actions.push(std::string(""));
while (true)
{
std::string a = actions.top();
int new_acc = eval(a, accumulator);
if (new_acc == target)
return a + "c";
actions.pop();
int last_braces = 0;
int i = a.length() - 1;
while (i >= 0 && a[i] == '}' && last_braces < 2)
{
++last_braces;
--i;
}
bool is_last_i = (i >= 0 && a[i] == 'i');
bool is_last_d = (i >= 0 && a[i] == 'd');
bool may_add_braces = (i < 0 || a[i] == 's');
bool may_add_c = (new_acc > 1 && new_acc < 30);
if (may_add_c)
{
actions.push(a + "s");
}
if (may_add_braces)
{
actions.push(a + "{{}}");
actions.push(a + "{}");
}
for (int braces_back = 0; braces_back <= last_braces; ++braces_back)
{
for (int c = 'd'; c <= 'i'; c += 'i' - 'd')
{
if ((!is_last_i || c == 'i') &&
(!is_last_d || c == 'd') ||
braces_back == 0)
{
std::string new_actions = a;
new_actions.insert(new_actions.length() - braces_back, 1, (char)c);
actions.push(new_actions);
}
}
}
}
}
std::string DeadfishConvert(std::string s)
{
std::string result;
int accumulator = 0;
for (int c: s)
{
result += BestStr(accumulator, c);
accumulator = c;
}
return result;
}
int main()
{
std::string s1 = DeadfishConvert("N NE E SE S SW W NW");
std::cout << s1 << '\n';
std::cout << s1.length() << '\n' << '\n';
std::string s2 = DeadfishConvert("n ne e se s sw w nw");
std::cout << s2 << '\n';
std::cout << s2.length() << '\n' << '\n';
std::string s3 = DeadfishConvert("N\nNE\nE\nSE\nS\nSW\nW\nNW");
std::cout << s3 << '\n';
std::cout << s3.length() << '\n' << '\n';
std::string s4 = DeadfishConvert("n\nne\ne\nse\ns\nsw\nw\nnw");
std::cout << s4 << '\n';
std::cout << s4.length() << '\n' << '\n';
}
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 16 bytes
Returns an array of lowercase strings. The compressed string was 18 bytes but using `a` as the delimiter instead and then splitting on that worked out shorter.
```
`nÂà!Z°°nw`qa
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=YG7CFOAhBFqwsG53YHFhIA&footer=bXUgcVM) - footer formats the output.
[Answer]
# [Whitespace](https://web.archive.org/web/20150618184706/http://compsoc.dur.ac.uk/whitespace/tutorial.php), 151 bytes
```
[S S S T T N
_Push_3_W][S S T T T S N
_Push_-6_N][S S T T T S T S S N
_Push_-52_space][S S S T T N
_Push_3_W][S T S S T N
_Copy_0-based_1st_(space)][S S S T T N
_Push_3_W][S S T T N
_Push_-1_S][S T S S T S N
_Copy_0-based_2nd_(space)][S S T T N
_Push_-1_S][S T S S T N
_Copy_0-based_1st_(space)][S S T T T T T N
_Push_-15_E][S S T T N
_Push_-1_S][S T S S T S N
_Copy_0-based_2nd_(space)][S T S S T S N
_Copy_0-based_2nd_(E)][S T S S T N
_Copy_0-based_1st_(space)][S T S S T N
_Copy_0-based_1st_(E)][S S T T T S N
_Push_-6_N][S T S S T S N
_Copy_0-based_2nd_(space)][S S T T T S N
_Push_-6_N][N
S S N
_Create_Label_LOOP][S S S T S T S T S S N
_Push_84][T S S S _Add][T N
S S _Print_as_character][N
S N
N
_Jump_to_Label_LOOP]
```
Letters `S` (space), `T` (tab), and `N` (new-line) added as highlighting only.
`[..._some_action]` added as explanation only.
[Try it online](https://tio.run/##VU1bCoAwDPtOTpGrDRnon6Dg8Wu7Dtb1owl5kO@83v7c7ehmkgDGgyZAwYbsFFyRFMTNRNxuF6gx1b4D55ByE8ok3TH7AQ) (with raw spaces, tabs, and new-lines only).
**Explanation:**
1. Push the unicode values minus constant 84 for the characters "WN W WS S ES E EN N" to the stack (note that the string is pushed in reversed). In addition, I use a few copies of previously pushed values to save bytes where possible.
2. Then start an infinite loop, which does the following:
1. Add the constant 84 to the current unicode value
2. Print it as character to STDOUT
The constant `84` is generated by [this Java program which I wrote for another challenge I answered in Whitespace](https://tio.run/##fVLva9swEP3ev@K4TxJKTQYrY3ZEaSEfDEs@zNky6MqQXTVR58iedA6Ekb89k2s7P7ZRMBK@9@7p7t69qK26fnn6eTgUpfIeZsrY31cAdZOXpgBPisK1rcwTbALEMnLGrh4eQfGWBtAFwGnflAQS1MP4MXlFjCXwG1WW2rdAakmvtItmd99@fL379GU6glR@uEnOVQb650ENscOfK8daPSPTxEze3YwTI0RfwakGiTiiUS2HrC4v35GGPO4qjFaa7kPAM35MByAZxBfVcm0CUqtC3xur3K7TZfm14cmR6ySjSP9qVOlZzW8xm3@3GcbEhTuRaknDz76/zTNzUantitaMw@TY61kZ/7R/png2yZPMCU5D3Fw@2Z3ZzpPeRFVDUR26odIy7NIlikFUYBJGiyIVCDGgeGsaKe@f/VuZXZb/ytpfhaNfot6lt7Rbi20/kK1ywRfMMhTMTsa3uMAYM@SXC1HEw15RdSHVonymaB2p3DPL@f@cJyGLyfuPwcSgvei3ppub09Q4GxgY/MWul/3hcJjDfApTyMIH2RKWMF/@AQ).
[Answer]
## Batch File, 19 bytes
*The question never stated that you had to output `N NE E SE S SW W NW` and nothing else, ~~nor that it couldn't exit due to error after doing so~~ this code only throws an error but does not exit due to it.*
```
N NE E SE S SW W NW
```
**Output**
```
>N NE E SE S SW W NW
'N' is not recognized as an internal or external command,
operable program or batch file.
```
---
## Batch File, 25 bytes
*Only `N NE E SE S SW W NW` output with no errors or crashes.*
```
@echo N NE E SE S SW W NW
```
[Answer]
## Python2, 59 bytes
```
''.join(' SEWN'[0xe0619042210504>>i*3&7]for i in range(19))
```
The magic number is the joined three-bit indexes into the character string, reverse order so we can start iterating at the LSB.
---
I spent a while trying to shrink the magic number, but repeating the character string via multiply to allow for extra indexes doesn't work out due to needing to encode for space - best I got for overlapping indexes in the lookup added more characters to the string than digits removed from the magic number (including a couple of unfortunate don't-cares in the middle):
```
''.join('WN S ES W xxE '[0x423659711>>i*2&15]for i in range(19))
```
[Answer]
# [CSS](https://developer.mozilla.org/en-US/docs/Learn/CSS/Introduction_to_CSS/How_CSS_works), 42 39 bytes
(thanks to a stone arachnid for the revised version)
```
body:after{content:"N NE E SE S SW W NW"
```
[Answer]
# [Hodor](https://github.com/hummingbirdtech/hodor), 177 bytes
```
hodor.hod("HoOodoOorhodor HoOodoOorhodor HooodorrHodor HooodorrHodor HODOR?!? HooodorrHodor HODOR?!? HODOR?!? Hooodorrhodor Hooodorrhodor HoOodoOorhodor Hooodorrhodor ");
```
[Try it online!](https://tio.run/##y8hPyS/6/z8DROkBSQ0lj3x/IMc/vwgspqCAxvfIzwfRRR4wWVSuv4t/kL2iPU5xTBUZqAbhtxXCU9K0/v8fAA "Hodor – Try It Online")
[Answer]
# [K (ngn/k)](https://gitlab.com/n9n/k), ~~23~~ 22 bytes
-1 byte thanks to ngn!
```
"WNES"@5\7108085518230
```
[Try it online!](https://tio.run/##y9bNS8/7/18p3M81WMnBNMbc0MDCwMLU1NDCyNjg/38A "K (ngn/k) – Try It Online")
# [J](http://jsoftware.com/), ~~34~~ 30 bytes
```
echo(#:3510)<;.1'NNEESESSWWNW'
```
[Try it online!](https://tio.run/##y/r/PzU5I19D2crY1NBA08Zaz1Ddz8/VNdg1ODg83C9c/f9/AA "J – Try It Online")
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), ~~20~~ 17 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py)
```
ÿnesw▒∙╫m+mÉîÄ╪^─
```
-3 bytes thanks to *@maxb*.
[Try it online.](https://tio.run/##ASsA1P9tYXRoZ29sZv//w79uZXN34paS4oiZ4pWrbSttw4nDrsOE4pWqXuKUgP//)
**Explanation:**
```
ÿnesw # Push 4-char string "nesw"
# STACK: "nesw"
▒ # Split to a list of characters
# STACK: ["n","e","s","w"]
∙ # Triplicate it
# STACK: ["n","e","s","w"],["n","e","s","w"],["n","e","s","w"]
╫ # Rotate the top one once towards the left
# STACK: ["n","e","s","w"],["n","e","s","w"],["e","s","w","n"]
m+ # Append the top two together
# STACK: ["n","e","s","w"],["en","se","ws","nw"]
m # Map the strings in the top list to:
ÉîÄ╪ # Rotate the string the 1-based index amount of times towards the right
# STACK: ["n","e","s","w"],["ne","se","sw","nw"]
^ # Zip; creating pairs with the top two lists
# STACK: [["n","ne"],["e","se"],["s","sw"],["w","nw"]]
─ # Flatten this list
# STACK: ["n","ne","e","se","s","sw","w","nw"]
# (after which the entire stack is output implicitly as result)
```
[Answer]
# [Seed](https://github.com/TryItOnline/seed), 4251 bytes
```
27 860147400464320299851319650217038525067593962313164914063802148270004754537839527004961550644011737763173154284403302082858336215121754817673301632815648307157082257250065969906234717399421909542980478171410880440751722628315229816701382847058322399070856858731820592153559264698086256217073752803742509491363133456184161014315870765856600563476019957791284745304281660469000032221201987453977657076508857068925011334779959071440923984103143261670811286681623926107584024737407335854701183247862900875519132553862748352119660143037154122195573484790384903915970480907443474210394470962277045139788233096906291178764592241041611441485846755897013873688521530706196990820905883449849751950542262212135591408570969484383431331268013190679834203987004737033313790768284011421240552315405082211961547940945234054982540700959040110356065461918175100640645479538002873406489037076456708483336597830606103157984606500496104240680721715484975347636031339682884674007607761345031515356027627047153497243272493312777270059024405453326103645777154783737896705880974153479385405461479666492424804798913240004709514175124491345454890697719341525477491425506610736434419234873135671474320918887316021471114682305222060888267915897813615746066948876815582512745575223896397735870135010211620878858423461465501063112149784622948077561122339504363312618787910627004536262109268282720077104133896334152799286447973176850047049812237713119532715197762392242720792955229362464454600594810210467053711629390655097050460183390576348650022884751999375732126411381491754798404626390434531750738731272129720457996733567288607018123496287262160638316644435886734080491415247676750503867190420441091488618537213370224085728523393619833129203818082398409724941259872470927203359894330981108281123358998365863404548111735330153890675493224241792528725858340777392950394427682710593902374005599390211202010183187773313755391636819970533772133030396082626453690202239163311449200997783715732798122360869214085295495205587704852617986211913577714214894103975695818432639029127400486966542504511176639066696550158657913890844890562994316733022295096182193874563287743954751083012315029203163625022641203785665910088174692911838388292883069099394602294401738461660317279173837890672723734359376951296954419885743000344118132620159094589745339998487533132912807955511930376108281742417048694994875241588696652295801421718174803743124679206340225332097286300793979362905965159380929127793048151559525010844247959055728814555227894949967607223815007539935866407118545974733499467978719520674830213387424230607171033962289851248037814785709294099111079872519162461838713157037955879646633307327632199374397038125921466729486072989316466253855183888968132751168378559192389783877180105811003888702407695849761551983252272136707803738209259164664868613103576660297351725095830903937947897824922994115970348394937807639806260540922571073766242821778449979029518064508677282684721476618711020644303120169502947696562952368545317073951472329943172059804905148953167123224802341970130868655853508010679907291864781248708382895527072805076419959404999796416487609739366680312473571591439396203866000938847930213950479915383946224278267661324765517520245110902687465374197341697248788763795723636008536927460160699589679376204284666762952828550700427849440153722541367837884874936070390103822579251528194036368492691743157507007441316773257650566047289586030443027248477537583575486086849301248855085404298181531070581096279202982969807660922182894833612275870735415456262697094185364902898042294060753067768982931035992143317507864980963267558535182176412835015890947861515892664431426681784697668827491173215527175448012211609218424524444896026378969503208454034161694651869812191979848741948472549690935926453753636695759524608297815672107532614104226930403335546065437317024985496835938364395583613835089520335424746078337656399280976500954797578444275697683434911793855960947914672558887185471712327031861804193341374816922655961374046504439546326688852794774993974104827407822683150065349462048012229814913150474813478266062076194247990327161206357488393540333896367735722260126440026734314269599013734005627347044302569936610219118261640990110423736786326407200834287772995647774230547965
```
[Try it online!](https://tio.run/##JdeHbSA5EATAVC4E2iGZz18Elz/01SsIkLSOHNNm@O/v3/9@fsb5c6v1dVZrq9Ycbbx3d5/91W6jnzbvHrvV2W@@GtOTWq@vVvN6vu44zadnrz3PnW/ner3q20drtd7PPKemP32vcd2as412x913zhp9d9vsdfup41GvOW7fte5sp@/jzbGPEFrtV@81QaxjuffW6K89q74rAgv01dv1/2pn9zNGjWvX4Xmv0/q06TrNvmP4vFl7lzCEdkfbTyxz@1OrrHhr7EoFJLDHbfMsUTzJT@nMuXb1u3p15bPL9WJtC1Zru4SorO/tc17PrsrTpN89trqSNUGMPrx08/Ap0v6WkIF/6j679exjibdF2@X1BG7TNu05Klndbv0qK3vkltTvamOJWhnmFJKce5e0GtWw9z17d2mMvac7R6n36DoeJEyJ6lQX3Nv7zCX4BwXLr9f3O23dJpq1RKYD7i4bwMY4noHOO/cOndQtzXoQcE8tdR0CT8EkAjjChKp939eZM0ve6YC2VP86rSlPt@5cS9JPT99u2q2vKtfTK0BMtbwuzunNdKaPui0QBtvn3hDjDSzVBPq8IqNTQYPCyGGstvcIQNsO3lILF@cp@PLAbREMj62SXuS7NnfB5BJsh73dIRQtVr5T19aGpHLjqlw6CzDapdhgr47w7fu0cotyZa1f5sCJz247wCeKL/PgaVZLdi@Bp3YoC2Rw02ExywS@1cbRUrm68uWAE79eqnLOCTvFP1ZS2jMYalNkHiXhO5XovgpJdPmsLHIeDcj7RSeABP@HEMO5dwOj9SmAwuCfOlj8JSQ/Ui/I7m9aSf3OiXaMaEOQame97UC9QkLRn0gRFVLSm1sVjTldl2Q9Gy4PVfNsaG0PeC46qmDqFxCAGvXYmiXfBcA@mTIKwWZIapfWrYoviHADQ9tLrXYeoDZoKZwKEw5ZnoPo6KDyuy3cD766TwXQ6pO7TcdIBXamN@qtMydYn9/WX/JIjKeo8qQlyP3VDKyytLftCzZDG3q0IGRWZUudNxBRLDYh0aoahRFZsiAmeoWx0iHQLUkglEBxGdLwB3DWDbZGYBMSvUfRzoT7WhTmSjcKHBT6bqiVPCXlph6lDeLoA5ikKo/otFZZDvxs0xUQ/@9JESrOoHEiXQp@KySAFX1XBTD2g8UURbNtZE2y4KlX@5UKYqOL5MNsLpHCazEii@Ph8u3E@dPBFnw/WrXxewSCKZjg4HJFgYhjnEb7IoScDfOuerRgs8ebdiwHXaMVSD5TdCgmvslnx6SwHnbShU/rRpRDd2OIbURlicf7LuzD2noqDyA@itQQ2cfUwPKlM5L7Umx@HiirWQVAPm@xpR6AUUiZNh@Ekj3NOr9I8UUxqhRHQIvf2v1Ged0ogRP0HnH/KL3i0C9@QUPqbaWLbyTWF37AoOWKijEb2q0iladI/j4@qJaO99SHdfvNEhmv/sarsVFRSNZlFjM@FvNGclQJ0hqN69HV9jUuVbDPCOxcnpglCWdI9JMrxisu8GA3rkQf2bvCwnKoSHShEVUrQkjKXq6jV3qn8bQL4mBbopDid7QlbsrU@K0rWJW@FtFAyk4@IoIIQZaJrHalLjiPcarxYob1C6Hz4eKr11IBr7sOvlO@1IHlrCh2Xv2mBXDFTokHcIaYGV2D6BINTX0njFZRlRYPx3hfU9y2S9R8v4xePZUfMRXvhhH4uiMIEl@JpeICUTl15v7SgXX8MzEgFOM9jG8maNGQrR7QVFy/BYg3mY2YkakKUjLmjZshcHx52O58Hjtih1pEuEO3jBBRpLQs8uWVmbrRRQMUFHNysIWIHsGBiQyT4SpQlo4pYgLH1cyUBRp8Zme5SzXTKRDqlQ7H6V90/GQzNVaVHXK3vEwtJBt40@1MnhGLkQrJjz6epDEzTdj828rO1GbGwwEevIhyJkZgRviWUUcu8rYhhRnBfP@GH1oKkJ4CCaZcDlCs0dKm1Fia9ZQTIVAXi3XZ6rLKZIC7yI/ydDi@VvERWYyMyrCWcVAaPvAMLMCD/FWaOL9BNBYL6L8UPJlZo6xth@U7pMS2kbZR5P4NVi2ZaorRoKVqIPBS9M6LtNa7ZpIMxvEYWwD/zqyS2VW/JfDST1XjrOAbLTZtJlaoknJmsPmdDSLprKmBcmbGD12xTDtGYcPjz9Li3TLPPCoyJkP4oj3KrjKEgAkkeilUBD4urdawJfVMQbSPXo54fuxGpBlZQvyRGVt/bZDS5ZCxM7Nl1/UpSAzGIBJcBFjhvW7Gx8gePHynDTjhVQTbYSXKDQFFbDLmn289028OQhTe27w1U7/GKCJIo69mZupSBnw0kCvUDtpv1oomcjuRZazK6YVm6F7L1NUzSUc03I6GBWYVdPX0KMNjsYHzHTemPEAjs4dCEbT4p@mshb4WDmEriqDrTCsLfpB/YeD8tXcw8K4hZXzDOJhEzAMAZ6fPAKKUXosgOZPE1x0@Rk4cmZEQzuA@Mtf1jBRBUYYJGMwRoid2pqPBxsI4CLLVN2PGTo1gnLil03qt82AZnyMt73yiDAgpo5blOEHZ3meXktIYa5yI5IqPZhTMVJITUObaHDZYTdQ0Q//e34i9ZsYvgCNwlrwxjJs5NMqltjNZ3yikTyK7voIU2OJtGeFwIMNUDI6nhuPAtVOHnD6@MmRepuqpG3IIydIgHDGOxKIotPWMO0bEl/EQ4B3gdLnyYS4NYjs4sk96o8Y3M@Q3Qcc7kl3KLjhf5ZibA7L9V0jwFT/AyiTew0Hrm@RRTxHMlOapz1MonX6BFJPik0xXib96ZXANwJHOBi2zonFhZJz7@k8eECaem/Pu8Pf84l4tohGZTuPnOaXGN3JiWvFoxEtGIjfh5HSWSYmiOfL7J06U0tb@@fkf "Seed – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 14 bytes
```
.•2Àβ‡yÞJŒ¾oÒ8
```
[Try it online!](https://tio.run/##yy9OTMpM/f9f71HDIqPDDec2PWpYWHl4ntfRSYf25R@eZAEU/v8fAA "05AB1E – Try It Online")
This prints out the string except lowercase.
[Answer]
# [JSFuck](http://www.jsfuck.com/), 8529 bytes
```
[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]][([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]]((!![]+[])[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+([][[]]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+!+[]]+(+[![]]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+!+[]]]+(!![]+[])[!+[]+!+[]+!+[]]+(+(!+[]+!+[]+!+[]+[+!+[]]))[(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+([]+[])[([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]][([][[]]+[])[+!+[]]+(![]+[])[+!+[]]+((+[])[([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]]+[])[+!+[]+[+!+[]]]+(!![]+[])[!+[]+!+[]+!+[]]]](!+[]+!+[]+!+[]+[!+[]+!+[]])+(![]+[])[+!+[]]+(![]+[])[!+[]+!+[]])()([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]][([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]]((!![]+[])[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+([][[]]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+!+[]]+([]+[])[(![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(!![]+[])[+[]]+([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]]()[+!+[]+[!+[]+!+[]]]+((![]+[])[+!+[]]+(![]+[])[!+[]+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]+(!![]+[])[+[]]+[+!+[]]+[!+[]+!+[]+!+[]+!+[]+!+[]+!+[]]+[!+[]+!+[]+!+[]+!+[]]+(!![]+[])[+[]]+[!+[]+!+[]+!+[]+!+[]+!+[]]+[+[]]+(!![]+[])[+[]]+[!+[]+!+[]+!+[]+!+[]]+[!+[]+!+[]+!+[]+!+[]+!+[]+!+[]+!+[]]+(+[![]]+[])[+[]]+(!![]+[])[+[]]+[!+[]+!+[]+!+[]+!+[]]+[+[]]+(+[![]]+[])[+[]]+(!![]+[])[+[]]+[+!+[]]+[+[]]+[!+[]+!+[]+!+[]+!+[]+!+[]]+(!![]+[])[+[]]+[!+[]+!+[]+!+[]+!+[]]+[+[]]+(!![]+[])[+[]]+[+!+[]]+[+[]]+[!+[]+!+[]+!+[]+!+[]+!+[]]+(!![]+[])[+[]]+[!+[]+!+[]+!+[]+!+[]]+[+[]]+(!![]+[])[+[]]+[+!+[]]+[!+[]+!+[]]+[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+[+!+[]]+[+[]]+[!+[]+!+[]+!+[]+!+[]+!+[]]+(!![]+[])[+[]]+[!+[]+!+[]+!+[]+!+[]]+[+[]]+(!![]+[])[+[]]+[+!+[]]+[!+[]+!+[]]+[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+[!+[]+!+[]+!+[]+!+[]]+[+[]]+(!![]+[])[+[]]+[+!+[]]+[!+[]+!+[]]+[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+[+!+[]]+[!+[]+!+[]]+[!+[]+!+[]+!+[]+!+[]+!+[]+!+[]+!+[]]+(!![]+[])[+[]]+[!+[]+!+[]+!+[]+!+[]]+[+[]]+(!![]+[])[+[]]+[+!+[]]+[!+[]+!+[]]+[!+[]+!+[]+!+[]+!+[]+!+[]+!+[]+!+[]]+(!![]+[])[+[]]+[!+[]+!+[]+!+[]+!+[]]+[+[]]+(+[![]]+[])[+[]]+(!![]+[])[+[]]+[+!+[]]+[!+[]+!+[]]+[!+[]+!+[]+!+[]+!+[]+!+[]+!+[]+!+[]]+(!![]+[])[+[]]+[!+[]+!+[]+!+[]+!+[]]+[!+[]+!+[]+!+[]+!+[]+!+[]+!+[]+!+[]]+(!![]+[])[+[]]+[!+[]+!+[]+!+[]+!+[]+!+[]]+[+!+[]])[(![]+[])[!+[]+!+[]+!+[]]+(+(!+[]+!+[]+[+!+[]]+[+!+[]]))[(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+([]+[])[([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]][([][[]]+[])[+!+[]]+(![]+[])[+!+[]]+((+[])[([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]]+[])[+!+[]+[+!+[]]]+(!![]+[])[!+[]+!+[]+!+[]]]](!+[]+!+[]+!+[]+[+!+[]])[+!+[]]+(![]+[])[!+[]+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(!![]+[])[+[]]]((!![]+[])[+[]])[([][(!![]+[])[!+[]+!+[]+!+[]]+([][[]]+[])[+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(!![]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]]()+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+([![]]+[][[]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]](([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]][([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]]((!![]+[])[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+([][[]]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+!+[]]+(![]+[+[]])[([![]]+[][[]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(![]+[])[+!+[]]+(![]+[])[!+[]+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]]()[+!+[]+[+[]]]+![]+(![]+[+[]])[([![]]+[][[]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(![]+[])[+!+[]]+(![]+[])[!+[]+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]]()[+!+[]+[+[]]])()[([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]]((![]+[+[]])[([![]]+[][[]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(![]+[])[+!+[]]+(![]+[])[!+[]+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]]()[+!+[]+[+[]]])+[])[+!+[]])+([]+[])[(![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(!![]+[])[+[]]+([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]]()[+!+[]+[!+[]+!+[]]])())
```
Just for the fun of it
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 18 bytes
```
"NeSw"it;?↺₍h₂a₀oụ
```
[Try it online!](https://tio.run/##ATUAyv9icmFjaHlsb2cy/@KGsOKCgeG2oP8iTmVTdyJpdDs/4oa64oKNaOKCgmHigoBv4bul////Wg "Brachylog – Try It Online")
Semi-port of [my Jelly solution](https://codegolf.stackexchange.com/a/226044/85334). [Generates](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/10753#10753) each direction.
```
"NeSw" Let the input variable be "NeSw".
i Take a pair [element, 0-index] from it,
t extract the index,
;?↺₍ and rotate the input variable left by that many places.
h₂ Keep only the first two elements of the rotation,
a₀ take a prefix (nonempty, shortest first) of it,
o sort (putting uppercase before lowercase),
ụ and fold to uppercase.
```
Barely beats my original...
# [Brachylog](https://github.com/JCumin/Brachylog), 19 bytes
```
"NNEESESSWWNW"ḍ₄ḍᵐc
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r/X8nPz9U12DU4ODzcL1zp4Y7eR00tQPLh1gnJ////jwIA "Brachylog – Try It Online")
Outputs as a list. `ḍ₄ḍᵐc` saves two bytes over writing out seven spaces and making the entire predicate a string literal, so at least it ties PHP...
```
"NNEESESSWWNW" The string "NNEESESSWWNW"
ḍ₄ split into quarters
ᵐ with each quarter
ḍ split in half
c and concatenated
is the output.
```
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 21 bytes
```
'N NE E SE S SW W NW'
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/X91Pwc9VwVUhGIgUgsMVwhX8wtX//wcA "PowerShell – Try It Online")
] |
[Question]
[
# Introduction
In number theory, a number is considered evil if there are an even number of 1's in its binary representation. In today's challenge, you will be identifying whether or not a given number is evil.
# Challenge
Your job is to write a full program or function which accepts a single, non-negative integer as input and outputs (or returns) whether or not that number is evil.
* You may output any [truthy](https://codegolf.meta.stackexchange.com/questions/2190/interpretation-of-truthy-falsey#2194) value if the number is evil, and any falsy value if the number is not evil.
* You may input and output in [any acceptable format](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods).
* [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are disallowed.
* [OEIS sequence A001969](https://oeis.org/A001969) is the sequence containing all evil numbers.
* [Here](https://oeis.org/A001969/b001969.txt) is a list of the first 10000 evil numbers, for reference (and more test cases!)
* This question is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shorter, the better.
* Don't be put off by extremely short answers in golfing languages. I encourage you to submit in any language you like.
* Here are some test cases:
```
3 => True
11 => False
777 => True
43 => True
55 => False
666 => False
```
## The Leaderboard
At the bottom of the page is a stack snippet containing a leaderboard for this question. (Thanks, @MartinEnder)
To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:
```
# Language Name, N bytes
```
where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance:
```
# Ruby, <s>104</s> <s>101</s> 96 bytes
```
If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the *last* number in the header:
```
# Perl, 43 + 2 (-p flag) = 45 bytes
```
You can also make the language name a link which will then show up in the leaderboard snippet:
```
# [><>](http://esolangs.org/wiki/Fish), 121 bytes
```
```
/* Configuration */
var QUESTION_ID = 169724; // Obtain this from the url
// It will be like https://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page
var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";
var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk";
var OVERRIDE_USER = 81420; // This should be the user ID of the challenge author.
/* App */
var answers = [],
answers_hash, answer_ids, answer_page = 1,
more_answers = true,
comment_page;
function answersUrl(index) {
return "https://api.stackexchange.com/2.2/questions/" + QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER;
}
function commentUrl(index, answers) {
return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER;
}
function getAnswers() {
jQuery.ajax({
url: answersUrl(answer_page++),
method: "get",
dataType: "jsonp",
crossDomain: true,
success: function(data) {
answers.push.apply(answers, data.items);
answers_hash = [];
answer_ids = [];
data.items.forEach(function(a) {
a.comments = [];
var id = +a.share_link.match(/\d+/);
answer_ids.push(id);
answers_hash[id] = a;
});
if (!data.has_more) more_answers = false;
comment_page = 1;
getComments();
}
});
}
function getComments() {
jQuery.ajax({
url: commentUrl(comment_page++, answer_ids),
method: "get",
dataType: "jsonp",
crossDomain: true,
success: function(data) {
data.items.forEach(function(c) {
if (c.owner.user_id === OVERRIDE_USER)
answers_hash[c.post_id].comments.push(c);
});
if (data.has_more) getComments();
else if (more_answers) getAnswers();
else process();
}
});
}
getAnswers();
var SCORE_REG = /<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/;
var OVERRIDE_REG = /^Override\s*header:\s*/i;
function getAuthorName(a) {
return a.owner.display_name;
}
function process() {
var valid = [];
answers.forEach(function(a) {
var body = a.body;
a.comments.forEach(function(c) {
if (OVERRIDE_REG.test(c.body))
body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>';
});
var match = body.match(SCORE_REG);
if (match)
valid.push({
user: getAuthorName(a),
size: +match[2],
language: match[1],
link: a.share_link,
});
//else console.log(body);
});
valid.sort(function(a, b) {
var aB = a.size,
bB = b.size;
return aB - bB
});
var languages = {};
var place = 1;
var lastSize = null;
var lastPlace = 1;
valid.forEach(function(a) {
if (a.size != lastSize)
lastPlace = place;
lastSize = a.size;
++place;
var answer = jQuery("#answer-template").html();
answer = answer.replace("{{PLACE}}", lastPlace + ".")
.replace("{{NAME}}", a.user)
.replace("{{LANGUAGE}}", a.language)
.replace("{{SIZE}}", a.size)
.replace("{{LINK}}", a.link);
answer = jQuery(answer);
jQuery("#answers").append(answer);
var lang = a.language;
lang = jQuery('<a>' + lang + '</a>').text();
languages[lang] = languages[lang] || {
lang: a.language,
lang_raw: lang,
user: a.user,
size: a.size,
link: a.link
};
});
var langs = [];
for (var lang in languages)
if (languages.hasOwnProperty(lang))
langs.push(languages[lang]);
langs.sort(function(a, b) {
if (a.lang_raw.toLowerCase() > b.lang_raw.toLowerCase()) return 1;
if (a.lang_raw.toLowerCase() < b.lang_raw.toLowerCase()) return -1;
return 0;
});
for (var i = 0; i < langs.length; ++i) {
var language = jQuery("#language-template").html();
var lang = langs[i];
language = language.replace("{{LANGUAGE}}", lang.lang)
.replace("{{NAME}}", lang.user)
.replace("{{SIZE}}", lang.size)
.replace("{{LINK}}", lang.link);
language = jQuery(language);
jQuery("#languages").append(language);
}
}
```
```
body {
text-align: left !important;
display: block !important;
}
#answer-list {
padding: 10px;
width: 290px;
float: left;
}
#language-list {
padding: 10px;
width: 500px;
float: left;
}
table thead {
font-weight: bold;
}
table td {
padding: 5px;
}
```
```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.sstatic.net/Sites/codegolf/all.css?v=ffb5d0584c5f">
<div id="language-list">
<h2>Shortest Solution by Language</h2>
<table class="language-list">
<thead>
<tr>
<td>Language</td>
<td>User</td>
<td>Score</td>
</tr>
</thead>
<tbody id="languages">
</tbody>
</table>
</div>
<div id="answer-list">
<h2>Leaderboard</h2>
<table class="answer-list">
<thead>
<tr>
<td></td>
<td>Author</td>
<td>Language</td>
<td>Size</td>
</tr>
</thead>
<tbody id="answers">
</tbody>
</table>
</div>
<table style="display: none">
<tbody id="answer-template">
<tr>
<td>{{PLACE}}</td>
<td>{{NAME}}</td>
<td>{{LANGUAGE}}</td>
<td>{{SIZE}}</td>
<td><a href="{{LINK}}">Link</a></td>
</tr>
</tbody>
</table>
<table style="display: none">
<tbody id="language-template">
<tr>
<td>{{LANGUAGE}}</td>
<td>{{NAME}}</td>
<td>{{SIZE}}</td>
<td><a href="{{LINK}}">Link</a></td>
</tr>
</tbody>
</table>
```
*EDIT: I believe this question is not a duplicate of [this](https://codegolf.stackexchange.com/questions/47870/count-the-number-of-ones-in-an-unsigned-16-bit-integer), because whereas that question is asking to count the number of ones, this question is asking whether the number of ones is even. Although you **can** accomplish this question by simply counting the bits, there are [other approaches too](https://codegolf.stackexchange.com/a/169729/81420).*
[Answer]
# Z80 Assembly (8-bit), 2 bytes
The following code only works with values up to 255:
```
; Input is given in register A.
; P flag is set if A is evil.
B7 or A
C9 ret
```
---
# 16-bit version (works on all test cases), 3 bytes
This works with values up to 65535.
```
; Input is given in BC.
; Output is the same as above.
78 ld A,B
A9 xor C
C9 ret
```
If you're feeling adventurous, you can shave off 1 byte by storing the input in `A` and `C` like so
```
ld BC, 777
C5 push BC
F1 pop AF
```
and then running
```
A9 xor C
C9 ret
```
However, this puts the burden on the caller, so it may be that the two bytes (`push BC` and `pop AF`) should be counted as well.
[Answer]
# JavaScript (ES6), 18 bytes
```
f=n=>n?!f(n&~-n):1
```
[Try it online!](https://tio.run/##FcxBCoMwEEbhq@hGZ0AH3Rai9BylSLCJRNJ/JEqhm1492s2Db/NW@7H7nMJ2tNCXy9kbmAFj6QnVrwXf@jwrdo1Ooi70EJF7SvZLfdfxU952I5qaAlyY4ar4EA@XCH9eD2ZZNYDqpmbOJw "JavaScript (Node.js) – Try It Online")
### Explanation
The bitwise logic goes like this:
* For integers, `~-n` is equivalent to `-(-n)-1`, so that just another way of doing `n-1`. In that particular case, we could actually have used `n-1`.
* `n & (n-1)` removes the least significant bit set to **1** in **n** because decrementing **n** turns all trailing **0**'s into **1**'s and clears the **1** that immediately follows (by carry propagation), while leaving everything else unchanged.
**Example for n = 24 (11000 in binary):**
```
11000 (24) 11000 (24)
- 1 AND 10111 (23)
------- ---------
= 10111 (23) = 10000 (16)
^ ^
| |
+--- this bit is cleared ---+
```
Therefore, we process as many recursive calls as there are **1**'s in the binary representation of **n**, inverting the result each time with `!`. The last call always returns **1**.
**Examples:**
```
f(24) = !f(16) = !!f(0) = !!1 = true
f(7) = !f(6) = !!f(4) = !!!f(0) = !!!1 = false
```
[Answer]
# [Python 2](https://docs.python.org/2/), 25 bytes
```
lambda n:int(bin(n),13)%2
```
[Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSHPKjOvRCMpM08jT1PH0FhT1eg/V1p@kUJJanGJQmaegoaxjoKhoY6Cubm5joIJkGNqqmnFxVlQBNSmkKYBUqb5HwA "Python 2 – Try It Online")
`bin(n)` gives a result like `'0b10101'`. Reading this as a base-13 integer, we get
$$ \color{red}{11\cdot13^5} + 1\cdot13^4 + 0\cdot13^3 + 1\cdot13^2 + 0\cdot13^1 + 1\cdot13^0 $$
which reduces modulo 2 to
$$\equiv \color{red}{1 \color{pink}{\cdot 1^5}} + 1 \color{#aaa}{\cdot 1^4} + 0 \color{#aaa}{\cdot 1^3} + 1\color{#aaa}{\cdot 1^2} + 0\color{#aaa}{\cdot 1^1} + 1\color{#aaa}{\cdot 1^0} \pmod 2 $$
$$\equiv \color{red}{1}+1+0+1+0+1 \pmod 2.$$
So `int(bin(n),13)%2` equals 1 + (number of ones in `bin(n)`) modulo 2.
If `n` is evil, then the result is 1; otherwise it is 0.
I picked up this trick from [Noodle9](https://codegolf.stackexchange.com/questions/144017/how-on-earth-did-llhuii-output-the-evil-numbers-in-42-bytes-of-python?noredirect=1&lq=1#comment353104_144027).
[Answer]
# Japt `-h!`, ~~5~~ ~~4~~ 3 bytes
```
¤å^
```
[Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=pOVe&input=NjY2Ci1oIQ==)
---
## Explanation
```
¤ :Convert to base-2 string
å^ :Cumulatively reduce by XORing
:Implicitly output the last element negated
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 4 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
bSOÈ
```
[Try it online](https://tio.run/##MzBNTDJM/f8/Kdj/cMf//@bm5gA) or [verify all test cases](https://tio.run/##MzBNTDJM/V9Waa@k8KhtkoKSfeX/pGD/wx3/df5HG@soGBrqKJibm@somAA5pqaxAA).
**Explanation:**
```
b # Convert to binary string
# i.e. 777 ‚Üí 1100001001
S # Change it to a list of 0s and 1s
# i.e. 1100001001 ‚Üí ['1','1','0','0','0','0','1','0','0','1']
O # Take the sum
# i.e. ['1','1','0','0','0','0','1','0','0','1'] ‚Üí 4
È # Check if it's even (1 as truthy, 0 as falsey)
# i.e. 4 ‚Üí 1
```
[Answer]
# [R](https://www.r-project.org/), ~~37~~ 26 bytes
```
!sum(scan()%/%2^(0:31))%%2
```
[Try it online!](https://tio.run/##K/r/X7G4NFejODkxT0NTVV/VKE7DwMrYUFNTVdXov7m5@X8A "R – Try It Online")
An alternative to [Robert S.'s answer](https://codegolf.stackexchange.com/a/169731/67312), this eschews the built-in bit splitting ~~but ends up less golfy~~ and thanks to JayCe and digEmAll ends up coming in slightly golfier.
Only works for positive integers less than \$2^{31}-1\$.
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), ~~43~~ 38 bytes
---
**Golfed** [Try it online!](https://tio.run/##ZY9BC4JAEIXP7a8YpGAXTNASIdNDQRAEQQUdqoNsay3UbLhrl/C326IZQXOZYd68jzdcD7mW9aJEPl2iGQUuzJS6iQxTyCGpZZLOFT5FYbyd2ppC4oVKN2DetrxTnqScDYKpX8ekRxr74QRGaDPPtNCQwIuArZHbNN9vexRF7TD@CGHoksoieiRXhcj4lUID@6JA4g@WfbA2mLZRvX0hjaDQd6zrUZoJvLrb6ojr0rS7nHZbVjnA4n/ESqKgzhEdK1b2oU7ciOzcaCyu3w "C# (Visual C# Interactive Compiler) – Try It Online")
```
i=>Convert.ToString(i,2).Sum(c=>c)%2<1
```
---
**Ungolfed**
```
i => Convert.ToString( i, 2 ).Sum( c => c ) % 2 < 1
```
---
**Full code** with tests
```
Func<Int32, Boolean> f = i => Convert.ToString( i, 2 ).Sum( c => c ) % 2 < 1;
Int32[] testCases = { 3, 11, 777, 43, 55 };
foreach( Int32 testCase in testCases ) {
Console.Write( $" Input: {testCase}\nOutput: {f(testCase)}" );
Console.WriteLine("\n");
}
Console.ReadLine();
```
---
**Releases**
* **v1.1** - `-5 bytes` - Replaced `Count` to `Sum`
* **v1.0** - `43 bytes` - Initial solution.
---
**Notes**
* None
[Answer]
# Bash (no external utilities), ~~56~~ 44 bytes
~~`while(($1));do set $(($1/2)) $(($2+$1%2));done;!(($2%2))`~~
```
(($1))&&exec $0 $[$1/2] $[$2+$1%2];!(($2%2))
```
This assumes that the number is found in `$1`, having been passed as the first command line argument. It also assumes that this is a shell script (so that it can `exec` itself).
It recurses, after a fashion, using `exec $0`, until the number (in `$1`) reaches zero, dividing it by two in each iteration. It also sums (in `$2`) the number of times we get a number that is odd. At the end, the original number was "evil" if the sum in `$2` in not odd.
Example invocations:
```
$ ./script 3 && echo evil
evil
$ ./script 11 && echo evil
$ ./script 777 && echo evil
evil
$ ./script 43 && echo evil
evil
$ ./script 55 && echo evil
```
For `0`:
```
$ ./script 0 && echo evil
./script: line 1: ((: %2: syntax error: operand expected (error token is "%2")
evil
```
Correct result, with a bit of extra on the side.
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 4 bytes
```
:1|e
```
[Run and debug it](https://staxlang.xyz/#c=%3A1%7Ce&i=3%0A11%0A777%0A43%0A55&a=1&m=2)
```
:1|e Full program, implicit input-evaluation
:1 Count set bits
|e Check if even
```
[Answer]
# [R](https://www.r-project.org/), ~~99~~ ~~98~~ ~~44~~ ~~34~~ 28 bytes
-1 thanks to Kevin Cruijssen! -54 thanks to ngm! -10 thanks to Giuseppe! -6 thanks to JayCe!
```
!sum(intToBits(scan())>0)%%2
```
[Try it online!](https://tio.run/##K/r/X7G4NFcjM68kJN8ps6RYozg5MU9DU9POQFNV1ei/qel/AA "R – Try It Online")
---
Alternatively, using the `binaryLogic` package (39 bytes):
```
!sum(binaryLogic::as.binary(scan()))%%2
```
[Answer]
# PHP, ~~37~~ 36 bytes
```
<?=1&~substr_count(decbin($argn),1);
```
To run it:
```
echo '<input>' | php -nF <filename>
```
Or [Try it online!](https://tio.run/##K8go@P/fxt7WUK2uuDSpuKQoPjm/NK9EIyU1OSkzT0MlsSg9T1PHUNP6/3/jf/kFJZn5ecX/dfPcAA)
Prints `1` for true, and `0` for false.
-1 byte thanks to [Benoit Esnard](https://codegolf.stackexchange.com/users/38454/benoit-esnard)!
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 4 bytes
```
ḃo-0
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r//@GO5nxdg///TQ3/AwA "Brachylog – Try It Online")
[With multiple test cases](https://tio.run/##SypKTM6ozMlPN/pf/ahtw6Ompkcdy5U@zJ/RofRwV@ejjhVA9sQ9IHbtw60T/j/c0Zyva/D/f7SBjoKhjoKRjoKxjoKJjoKpjoKZjoK5joKFjoIlUBAoYQpSYmAY@x8A "Brachylog ‚Äì Try It Online") (üòà is evil and üëº is not.)
Uses something I discovered recently about the `-` predicate: its documentation just says "the difference of elements of [input]", but what it actually does is "sum of even-indexed elements (starting from 0th) of input, minus the sum of odd-indexed elements of input".
Here,
`ḃ` converts the number into an array of binary digits,
`o` sorts them to bring all the 1s together.
Now, if there were an even number of 1s, there would be an equal number of 1s in even indices and odd indices. So the `-` after that would give a 0. But if there were an odd number of 1s, there would be an extra 1 sticking out, resulting in the difference being either -1 or 1.
So, finally, we assert that the difference is `0`, and get a true or false result according to that. With [more flexible output requirements](https://codegolf.meta.stackexchange.com/a/12308/8774), this could be removed for a 3 byte answer, with 0 as truthy output and -1 and 1 as both falsey outputs.
[Answer]
# [INTERCAL](http://www.catb.org/~esr/intercal/), ~~90~~ ~~65~~ 63 bytes
```
DOWRITEIN:1
DO:2<-'#0$#65535'~?':1~:1'
DOREADOUT:2
PLEASEGIVEUP
```
[Try it online!](https://tio.run/##y8wrSS1KTsz57@/n@t/FPzzIM8TV08/KkMvF38rIRldd2UBF2czU1NhUvc5e3cqwzspQHSgV5Oro4h8aYmXEFeDj6hjs6u4Z5hoa8P9/sGuYq58ChAQA "INTERCAL – Try It Online")
Ungolfed and expanded (for what it's worth) with C style comments.
```
DO WRITE IN :1 //Store user input in 1
DO :2<-:1~:1 //Select just the ones. So will convert binary 10101 to 111
DO :3<-:?2 //Run the unary xor over the result. Essentially, xor with the right bitshifted
//(with wraparound) value).
DO :9<-#0$#65535 //Intermingle the 16 bit values of all 0's and all 1's, to create a
//32 bit number with 1's in the odd positions.
DO :4<-:9~:3 //It turns out that at this point, evil numbers will have no bits in odd
//positions, and non-evil numbers will have precisely one bit in an odd
//position. Therefore, the ~ will return 0 or 1 as appropriate.
PLEASE READ OUT :4 //Politely output
PLEASE GIVE UP //Polite and self explanatory
```
I had to make a few concessions to make this feasible in INTERCAL. The first is, as with all INTERCAL programs, numerical input must be written out. So if you want to input `707` you would provide `SEVEN OH SEVEN`.
The second is that INTERCAL doesn't really have proper truthy or falsy value. Instead, it will output the Roman Numeral `I` (1) if the number is not evil, or a 0 (typically represented as `-` since Roman Numerals can't normally represent 0).
If you want to flip those so that evil numbers return 1 and non-evil numbers return 0, you can change lines 4 and 5 from the ungolfed version as follows, although it does add 3 bytes.
```
DO:9<-#65535$#0
DO:4<-#1~:9~3
```
[Answer]
# x86-16, 3 bytes
NASM listing:
```
1 parity16:
2 00000000 30E0 xor al,ah
3 00000002 C3 ret
```
16-bit integer function arg in AX (which is destroyed), return value in PF.
The hardware calculates the parity of the result for us, in [x86's Parity Flag](https://en.wikipedia.org/wiki/Parity_flag). The caller can use `jp` / `jnp` to branch, or whatever they like.
Works exactly like [@cschultz's Z80 / 8080 answer](https://codegolf.stackexchange.com/questions/169724/is-this-number-evil/169733#169733); in fact 8086 was [designed to make mechanical source-porting from 8080 easy](https://retrocomputing.stackexchange.com/q/6500).
Note that PF is only set from the low byte of wider results, so `test edi,edi` wouldn't work for an x86-64 version. You'd have to horizontal-xor down to 16 bits, or `popcnt eax, edi` / `and al,1` (where 0 is truthy).
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 36 bytes
```
c;f(n){for(c=0;n;c++)n&=n-1;n=~c&1;}
```
[Try it online!](https://tio.run/##jc/BCsIwDMbxu08RCo6GOTCsZWCZvoiXEVYZaCbdPI356tWbVJB6zOHH/wtXF@YY2XktuPgxaG73ThyXJUrRSkVO2icX5NZ46wbRuGzuYZDZawVQQ3WE7XQWtQOvawSAE6g5PHoFB1C@u069QvcRRIkgwoxomiYR7xszDZOuMnWuAdYmwtqsgC/xx@epoHyDTCrML7HGFw "C (gcc) – Try It Online")
Method from K&R <https://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetKernighan>
Must be compiled with optimization level 0
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~24~~ 22 bytes
* Saved two bytes thanks to [Misha Lavrov](https://codegolf.stackexchange.com/users/74672/misha-lavrov).
```
2∣DigitCount[#,2,1]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b73@hRx2KXzPTMEuf80rySaGUdIx3DWLX/AUWZeSUOwak5qckl0SGJSTmp0Vk61Vk6BjqGBgYGtbE6abH/AQ "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# x86-16 machine code, 3 bytes
```
32 C4 XOR AL, AH ; PF = (AX >> 8) XOR AL
C3 RET ; return to caller
```
Input is `AX`, output is in `PF`; `PE` if `True` (Evil) or `PO` if `False` (Not Evil).
This is actually the exact use of the [x86 Parity Flag](https://en.wikipedia.org/wiki/Parity_flag), with the only twist being that normally it only operates on the LSB of a WORD register. However, you can get the Parity of a WORD by `XOR`'ing the high byte and the low byte.
Example output from a test program for PC DOS:
[![enter image description here](https://i.stack.imgur.com/SFwNY.png)](https://i.stack.imgur.com/SFwNY.png)
DANG IT, I should have looked at the other answers first... @PeterCordes submitted this in 2018...
<https://codegolf.stackexchange.com/a/169903/84624>
[Answer]
# [evil](https://esolangs.org/wiki/Evil), ~~48~~ ~~42~~ ~~40~~ ~~39~~ ~~36~~ 35 bytes
golf 1: flipping many `m`s to `j`s and `j`s to `m`s saved quite a bit of marking mode changes
golf 2: do..while -> repeat..until
golf 3: `tbxb` -> `sxb` - can be seen to be the same, but less intuitive
golf 4: the `vzv` in `vtfvzv` turned out to be renundant, because the accumulator already zero at that point
golf 5: `aayuoy` -> `aluoy` and `tbuw` -> `tbaw`, now outputs 0x02 for evil and 0x00 for normal
I can confirm that this language is absolutely *evil*. Even though it is more powerful than e.g. brainfuck, it feels worse.
Inputs via char code, outputs via char code (0x02 = evil, 0x00 = normal). This would be slightly (probably by 1 byte) shorter if the output values could be merely consistent and not necessarily falsy and truthy.
Uses a trick: to count set bits, the code adds elements to the wheel, a circular list, and then calculates the list size's parity by setting the first one to 1, the second one to 2 and traversing the list 2 steps at a time until a non-zero element is found.
```
rvmvtfxjxutctbuvavsxbmaluoymiiptbaw
```
Here's an explained version (I do not expect anybody to understand the monstrosity above, but the explanation is in a spoiler so that you can try) (I was also writing the code immediately with these comments):
>
>
> ```
> COMMENTS ARE UPPERCASE, CODE IS LOWERCASE
>
> r READ INPUT AS CHAR CODE
> NOW DECREASE AND CHECK PARITY, WHILE ALSO COMPUTING N/2 IN THE FIRST PENTAL CELL
> v STORE TO FIRST PENTAL CELL
> m BEGINNING OF OUTER LOOP
>
> vtf IF ZERO, DONE
> NOW THE ACCUMULATOR HAS THE CORRECT VALUE AND THE PENTAL CELL IS ZERO, JUST LIKE IT SHOULD BE.
>
> x SET MARKING MODE INITIALLY
> j BEGINNING OF INNER LOOP
> x UNSET MARKING MODE AGAIN
> u FIRST DECREMENT
> IF ZERO (ODD), INCREASE BIT COUNTER AND PROCEED TO NEXT ITERATION
> tc THIS LANGUAGE SEEMS COMPARABLE TO MALBOLGE. THIS ADDS A NEW CELL TO THE WHEEL, A RESIZABLE CIRCULAR LIST. I USE IT AS THE BIT COUNTER
> tb GO TO NEXT ITERATION OF OUTER LOOP
> ODD CASE HANDLED. EVEN CASE IS (MUCH) SIMPLER
> u SECOND DECREMENT
> vav INCREMENT FIRST PENTAL CELL
>
> sxb IF ZERO, GO TO THE NEXT ITERATION OF THE OUTER LOOP; ELSE GO TO THE NEXT ITERATION OF THE INNER LOOP; EQUIVALENT TO TBXB.
>
> m END OF OUTER LOOP
>
> DO SORCERY TO COUNT WHEEL CELLS.
> al SET FIRST WHEEL CELL TO 1 (AND RESET THE ACCUMULATOR BACK TO 0 BY SWAPPING)
> uoy SET SECOND CELL TO -1
>
> NOW IN A LOOP CHECK WHETHER 1 OR 2 GOES FIRST AND OUTPUT THE CORRESPONDING NUMBER
>
> m BEGINNING OF THE LOOP
> ii GO RIGHT TWICE
> p READ WHEEL
> tb IF STILL ZERO, GO BACK
> NOW THE NON-ZERO ELEMENT WAS FOUND
> a INCREMENT SO THAT VALUES ARE ACTUALLY FALSY AND TRUTHY. IF THAT REQUIREMENT WASN'T THERE, THE CODE COULD BE REDUCED SLIGHTLY (AT LEAST BY REMOVING THIS BYTE)
> w PRINT
>
> ```
>
>
>
>
Now, the most ***evil*** part. This code does not work with the normal interpreter, because it has a bug. The bug is that the command to add a cell to the wheel quite literally doesn't add a cell to the wheel (to be specific, it's missing `wheelSize++;`). I assume that the bug is obvious enough for me to avoid accusations of adding new built-ins to the language.
You can [Try it online!](https://tio.run/##rVhtbyI5Ev68/IqakW6m2YQGsrerVQhzIgmZoEsgImRHq4gPBgzppF9Yt5uXneO3z1W537tNEnSHRpnudvmpctVT5bKf2YrVnmcvP37Uf4bRk@UD/mMwt4Qva0vm@2BMmW2DJWHFhW95LjTMkyp4c2AuWK7kYik4/q3AzzD3BMgnDnxl2bAU3kIwx3IXYDN3EbAFN@HWExz8JZ9ac4twtyivdNJ0mjphPk/kj2FtyScvkGrIl8ydMTED25oIJrYmzqFpoydOoChnz2DCYcYls2w@wwd/KqylRKN9MrhoGtlGALE64LbP14RmwjX@PYYeGoCLfw58CT4jY5kkV6ivkr1wms5cHOAbiU6zOTBy34rZ1ixWY0IHpW1vzcVUrY5L9BeKCTVdWZSYMPUcB5fpm/CwXJYnlJxACORIjJProW3O0uYOx7DMMDihc6O4VU3oe5KHa5DKZzjoeoTgB9MnEsZYKfv9rSvZBrgQGFHEIRtjdz/4aOcpPdHvGfkTLsHZ3nuBmPIr9ILJV3YkXtvze6bByLRT4lSTPghuc1ryjEl@Cs1G/Zdm/aTROKGxToBcEKcw8hz4JrjrT59eUxDpH0aI15YvPbGNDEd9DYI/@VXBw4h/A7gi0sMymNjWNGF7ZNHMTCY2M3aFEyfBAoO/iWVRsl7BSHhCKv@Ylmf2Bt3NlCsutopj5LGeuwzkvRScOa1KZWpT5im3JhH1YRi4Lpsgx75DvX73cH7Tu4Bh93bwR/cSRgO47fy7C6PrLlwMbu96N90h3I8Gd@rtptPr9/pfoXM@eBjBFQ5Cv3Pbva9UKIaTreSPY0Dmc/sYfBXFY1iiTma3lATmeTh85/mxhHoMhfCxIHdv/c1jwfA5lKRnFCWN0AnnTDwPveYmzL5l4gXaIEWAkkoCRyRGJA6Mh6nlMMs10F3IWLSciYVfhe9KmH71ejh0HsznXGB45gjo8jVkPxvVVmaCNQeDYEybuwv5BGfQrGI8ZSDcrJgU25we@lsIHzLBhXZBhn5kQEFWqXxsjHOmxI6cFD/OvJJu5UBcHOo0EXBmlJAUGi5uAl@gUdUMKohgbjKsN@7MMKZPTFQnJZwdBpbqWwSUHd5hBZJYQIwMyYHnA7LLPGe0ffyISD/V64rqPIoSvRgkJL0wYEY1p6/7R@8GRsj2e@j174jQw8EtdEJe3991L3pXPUyJXl9lQ2f49eG22x/dm1jOL647/a@ULjigOFSFq4f@xag36FMKYSoNh71LSqPOyExUlq37KFbOSs43z5tATuUkWLGVv5k4zA68rWPhnjNh648Zo7Eibvg0kDwO0C6kdsRphRmuFZYLJ@u6NG9Q/68pouA@l9lwh8mGQghgLrg8xxzzywIRUvgSsV1nkkqzxOiMQSXFES@SqgBf2tCAT5/SOoHZlCpPORhyeuDyaO5jMmGceqlkkwjcnD2vOjYqbeiOb1SWchMpK1SxinO@3U6LV97KsBCEo@nCI3DJnSW0i4PqNaKMEkygx6kQNUwG5brVbrTAOktk8OXoKG@DGnu0xlQbUSM@Zcmg7KPvr3vhTrGpEE81N1vuy7Npbkc3rZMPVBihkCEZ4Q4a3Sj4hnhR/pr1WLPRGBeGI/Y2W4X8yE5LM2ZcJL9eZ@lrsquln3MLDEmr/DJ1ZtmFqm9OuIMpgSp8dj7nKQPMlgWR56II1v6fUtuxC6byGpbmWGWOHKpP/Mw@n@a@KtcfHbVKHye4V7y0dBATDcRz4CyNOcPmuHoI1FQDtfbQt8ZBMDMNTCZv4gi2MtlTa7ZK6VNMo3b0cNQcl61JkWrlwaRuKDKeIUWyDNDC5ClbEikRsGxwLDfWC@4OcCjXsYQKGGcrbnQOCs58H12ofTsIabHHqjAXH5OUHB8C@qQBzSa3kb4cUcP3j3yb@m49lo7qaWSN5DnSktb5A5Q8a5Tsl37Zu/SML9G2ziEm2DoT4r0v5eiehMqRWKOXwj05xBznII@47ydDDcOkT/xE5gyzPjs7JU6tecgavPdSh2yCV6pR2GehVZnZaQGqwUFWLffViLcCvR/yLw2kv2bLw3YDscew4uHnbSRfg0TO7FAfiG5MOobDNlC5F/bD/wIb6Nat2532Q6x02dJ@R319Z9k4OH3XOuoLSx66CW10zMrfJnzIvh@Cvd2Xnm8Vs/2Qf@@hcGZb35X71pguu0wfqnba@P4Ee6I1LvCNbtTIOuJfVEFxX8l4m6iqQdKe87KnOm3rkpwBMyc7SgMyqdydaTMj9QRdzr5lEZ08/5@WZBNsV3J/1MxmjErqLS4B6nW6ZRj0b/6Ey97VVXfY7V904VtvdA3JQK8/6g7vhl38Cz24Gjz0Lyv6PvNLVHyjw2oxOK@eRbWnKxKNT77YluTOWoeeTd86n@4q@zr3CPBL0saDVavtPfhGj7Vm8Vyo64/jI1t0fYhK6ZKTmtxbRk76/s9jaOK/347h5Bh@w7ff8e0E//xysmulV6NRY6weN7kLBFyGw/yXfHdPX5nrr7nI53TRn7@HfizEkYJubD4RbPVDu1F2cwIdPvwnzOt4WTmv0y@yj/47O2vqIhId5EOcELRcacKNulBa3rz7CPNIc0WVXlTEHpMxSnKXXGiEkpzUn@ll@llmGx/9/UFat/Zcj8mcC1Toww6jWF11kc5fEueCFlXh@62PLjA1l7ZpXN66Uy1FcF/swi01vFbIAkRGeIE0lwJjULj63VV2lR8/pmD0B6Puae6@9fxPukgdwsXgsvuh@l8 "Java (JDK) – Try It Online") using my fixed interpreter.
[Answer]
# [Julia 0.6](http://julialang.org/), 20 bytes
```
n->count_ones(n)%2<1
```
[Try it online!](https://tio.run/##Dcc7CoAwEAXA3lO8RthALOIvjXoVETWwEjYS4/lXp5vrjbyNGjBDpVn29EpZk5wPianbyWlIGQwWUGfhnIX33qL/MwymAu7MUqJQIDamOuVQ/QA "Julia 0.6 – Try It Online")
[Answer]
# [C++ (gcc)](https://gcc.gnu.org/) (-O0), ~~ 36 ~~ 31 bytes
```
int f(int i){i=!i||i%2-f(i/2);}
```
[Try it online!](https://tio.run/##RYxLDoMgGIT3nmKaponEmFKXgt7FIDR/omAQulHPbpEuOotZfPNQy1K/lTrvZNUURw1Jbg1eD3Nf/NlHq@B8f5INMOXlxDbqbrTv9GjqhJ4NE0fO54FsybAVSDLO/@odFyD54hwCVUUpB5kyDRnDGsa2VS4GSAm6LBNtx0ngyD9eh@gtuCiO8ws "C++ (gcc) – Try It Online")
---
# [C++ (clang)](http://clang.llvm.org/), 35 bytes
```
int f(int i){return!i||i%2-f(i/2);}
```
[Try it online!](https://tio.run/##RY07DoMwEER7TjFRFAkLoTiU2OEuyJ9oJbCRMWmAsxNjimwxxZvPqmmq1dC7z3Enp4ZFG0jycwymH7viz75GRR@6g1yELU8ltgYTl@ButG30aOqEnw0Te86MPbmSYS2QzvpwVd5cgOSLcwhUFSUfZMtUZAxz1G2r/BIhJeiUTIzTg8Ced65/4KLYjx8 "C++ (clang) – Try It Online")
---
Here is my first attempt at code golfing, hope I didn't break any rule I might have missed.
Edit:
- Saved 5 bytes thanks to @Jonathan Frech : replaced `!=` by `-` and `return` by `i=` (the last replacement does not seem to work with clang though)
- Since there seems to be a debate whether I should use gcc -O0 abuse, I thought I could just give both versions
[Answer]
Since the [previous J solution by Adam](https://codegolf.stackexchange.com/a/169775/78410) is invalid for numbers having odd number of binary digits, here is a corrected one:
# [J](http://jsoftware.com/), 8 bytes
```
1-~:/&#:
```
[Try it online!](https://tio.run/##y/qvpKegnqZga6WuoKNQa6VgoADE/w1166z01ZSt/mtypSZn5CukKRjDGKYwhqEhjGVubg5jmiDUmf4HAA "J – Try It Online")
Anonymous tacit verb.
### How it works
```
1-~:/&#: Right argument: the number to test.
#: Convert to binary digits
~:/& Reduce by not-equal (same as XOR for zero-one values)
1- Invert the result
```
Alternatively, J has a built-in `XOR` that computes bitwise XOR over the input.
# [J](http://jsoftware.com/), 8 bytes
```
1-XOR&#:
```
[Try it online!](https://tio.run/##y/qvpKegnqZga6WuoKNQa6VgoADE/w11I/yD1JSt/mtypSZn5CukKRjDGKYwhqEhjGVubg5jmiDUmf4HAA "J – Try It Online")
[Answer]
# Ruby, ~~32~~ ~~29~~ ~~28~~ ~~27~~ 21 bytes
```
->n{("%b"%n).sum%2<1}
```
Where we use the fact that `sum` sums each character and given `1` is an odd number, and because we eventually do modulus `2`, that makes it equivalent to `count(?1)`:
```
->n{("%b"%n).count(?1)%2<1}
```
Where `<1` is a shorter substitute for `even?`:
```
->n{n.to_s(2).count(?1).even?}
```
Where `n` parameter should be an integer.
[Answer]
# Regex (ECMAScript), ~~37~~ 33 bytes
*-4 bytes thanks to Neil's idea of subtracting the least-significant two bits instead of the most-significant two bits*
```
^(((?=(((x*)(?=\5$))*))\3x){2})*$
```
[Try it online!](https://tio.run/##TY/LbsIwEEV/hUYIZkITHi0scA2rLtiwKMvSShYMzrTGsWwDKY9vT8OiUjdXVzpXujpf6qjCxrOLWXC8Jb8v7Tf91F5aOrXeSL9WDuAsZ/20/gSAuWyiSrEp63EbMUVcP1V4Gd0wbddp/4x5LFfRs9WAeTC8IZg8Zs@IIsiBOBVsCMBIT2pr2BIgPkh7MAYvWpo8OMMRulkXBe8ArNS5IatjgbPR9cphqZbA0ikfaGEj6PfBB@IfoP/Azobz4fSOMRa@PCULe1SGty2vrKZpK@kZsSs9CH6RJLjXw@YwqZLckyMVgTHfq7gpwCNeQqfjGqUId4uhcIcYom8m4narB9loPPkF "JavaScript (SpiderMonkey) – Try It Online")
Takes its input in unary, as a string of `x` characters whose length represents the number.
```
^
(
# Subtract the two least-significant "1" bits as
# they would be in tail's binary representation.
(
# Divide tail evenly by 2 as many times as we can, atomically
(?=
(((x*)(?=\5$))*)
)\3
x # Subtract a 1 bit
){2}
)* # Loop as many times as possible...
$ # and only match if the final result is 0.
```
## Regex (Perl / Java / PCRE / Python / Ruby), 26 bytes
```
^((((x*)(?=\4$))*+x){2})*$
```
[Try it online!](https://tio.run/##RU7LasMwEPyVJYhY6wd@0PRQWYkDybWn3pJUpCUGgZq4kgsuQv11Z@MEuodlZ3Z2Z7qTNYvx6xeYFeDN5fNogOWCoKw367f1MkB7sZw5WYh6KdCDbgmh76w@9zDbn2ciQGOk64zueZRFqfv5cD2dqDQr0xJP3zfR6p8tiMcXplDcfjlyPNrG1BX6xuzKg6ReHMTDVz8g07Wc1jQlCXrdAufREMEAJEIE@Qc5szl65ubzKdyUjYKX4p6VaRFCUGr7ulFqfOdUQ4x8JfdPDDFOBvRVwJiNY5FVi@cr "Perl 5 – Try It Online") - Perl
[Try it online!](https://tio.run/##bVJdb9swDHzvr@CMDpGcVE2KbQ9TjWIbNqDAug3tY5oBii0namXak@TGbZDfnlGO91GgepFIno66E@/Ugzq5K@73pmpqF@COYmFqkUr4P9MGY1/MOb3SHVWOmnZpTQ65Vd7DlTIIWxhyPqhA20NtCqiowm6CM7gC5VZ@vuAQ1q7eePjc5boJpqabRwBfjNVQZqg3/ZElIq8LLaiecPmxLUvtdHGtVaEdLHvY8yT7c3MIS87l0NdPgtysIz9jPluSBlV8NagZ568ybK3lpmRe6F@tsp4lp2maJpxvn0MPDIyFFwm2xBD@MhDBKTEsCXcv/Tgb3eIo7kHuDrndDxWCdgguG06ktmpiA88lubGsa6sVwlNWEqOWcJMrRJJusGkDZBDVDjl28@iDroRBLmHQ2cPEWvlvugv0zN5igMEQS28njgMICTFIHOrzBVgqR5TwjTWBJSf0CYQPgFOqXGKgMXCiUc5rCpidTxd8Ajh7sSisxlVYn5/BBUQkvKdttiDGfK3cfNENevoIZwsJH5xTj16UxlrWTUbdqDcFoKxd1EbPyHAqAc8znNE2HpPAKxXyNTlUEZsT1SFi/eQiDfgnIj9MjNg41bChRV43j9/La4UrTZ2mE@Q8Ki2BVdQeC/Iu/u0TH0yuybGNM0Gz@KlcPmXBtfF//pUb8jCULHntE7KEy11cR3Gq9j8ZrS7l7CK7fXPMeTru@PZsx9PjfZyZ/fTk7O273w "Java (JDK) – Try It Online") - Java
[Try it online!](https://tio.run/##XVDfa8IwEH73rwgh0FxNtRZ1SCy@bIPB2MO2N@tC7VJbVtOQRiiIf3t3lT0tcMf9@r7vcrayw3ZnK0uYIymhc0pmxDp9Uk7bJi80D@azcKdUlTdeFe3Z1o12Gc9AZu/zLhAkQCuxqE56HDBeG99xpZ5fXp@UAkEWgJRILCe1qVWnPae2cHp2zIsf79Cppj7XngpCl8lmuVk/JJsVBTkpW8dZncaSNWmJ7B3/@Hx8eQMJV1KXnDX7zrtGG4wgWhzSlGaGAg53lyN2sCxiES1gxOveNu235jSiAscl4ov2YvyI3SYI2iMB@vggJ4Tclc1fzsw2vfcxmk4BpQm/X@ic@6LizAkUG8@lc8@DPhDMAAC5jivWoIuqHfeSBL@ykGTMCTPyhjK3f2flIIcvjq8Pge/SbMkAwmkP1@QGIRuGOEpW618 "PHP – Try It Online") - PCRE
```
^
(
# Subtract the two least-significant "1" bits as
# they would be in tail's binary representation.
(
# Divide tail evenly by 2 as many times as we can, atomically
((x*)(?=\4$))*+
x # Subtract a 1 bit
){2}
)* # Loop as many times as possible...
$ # and only match if the final result is 0.
```
## Regex (.NET), 29 bytes
```
^(((?>((x*)(?=\4$))*)x){2})*$
```
[Try it online!](https://tio.run/##ZZBBT@MwFITv/ApTIdWvTaK0WjhgXJAiDkgg0BaJwy5IJn0US64T@TnFNPS3FzcBLvhmzdjzzZSUlpXDnVUrpFqVyObv5HHVNqTtkhWyqCxVBkV/v8fgs7@4bIxyl6F2SKSjQZRGEbFVS155XbJ1pRfsRmnLOLRr5RjJi8HuiXN@PuM8jICfy/9/jgBGEKCdbmF0tBuIvdFJi28sJmDglM2bZ/IuBvNJQtk12qV/TaeQdPpt7ffZWVGtam1wAaL3MiNeKse19czKXHAji4isFtfaIgc4lLYxRlg5gVa/cDvLocgenPbYGzqMWppsXhvt@TAdgtj/pRMUB/FB/cUxm358HEYhu3fvd8oR8vpf/phUTbTCb@n7WTrpPQjfsXxwZdfKxMWcsks8ZW2@HSQGBBrCbr3QjTLvlxiGYaLhp@ImVtRnEoUej5MwllGGSOmyK7pRvnzlAbqem189N3IifhC6zPDFCGLbnV2eTo9PPgE "C# (.NET Core) – Try It Online")
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 6 bytes
```
1=/~2\
```
[Try it online!](https://ngn.codeberg.page/k/#eJxFkNtuEzEURd/9FRuBCkiTju/HzijwxhfwVip1GpyLmmZCxqlSIfLt7FERedhjz/I6PtZZzc2ivdgfStX57w93r5fjfAXg3D0MT92nh1W/3XXn7rU7fr7/o+qd68w9F2M6Pa0i8gb8v4MQ3g5ijNNGaTgERGQYDWNhAozAJFgN62A9rMBmOIoOzsNFuAyv4R18gI/wCcEg8B6PIAgJUSM6RN4bERPEQCwkQASSkDSSQwpIESkja2SLHJD5iowLblYf3xmtlVKt2tR6GOdtuxx+lvWwW92OtV8+lfNy0+/X5XY5PLe/TmWs22E/tiZmsb7djrO64Wd/en4sx1l52e6+Hvp1Wfib2j8uXoZaxvfczepwUMph8QXfj6eijJm23/rdWBTn9p/7qxLCVeEErz9KN3ANQoPYIDccJmMZEiNMajhRhpL1DJml56Y6MkfmWOrIPJkn86z1ZJ61wTBTA3qBtYEs0otkcepKL5IJPWFfIRN6QpboJXqJLNFL7JHJMr1Mlqcn5792qI2t)
* `~2\` convert input to base-2 representation, and `not` it (flip `0`s and `1`s)
* `1=/` do an equals-reduce seeded with `1`; returns `1` if there are an odd number of 1's in the inverted base-2 representation and `0` if there are an even number(or none at all)
[Answer]
# [Perl 6](https://perl6.org), 21 bytes
```
*.base(2).comb(~1)%%2
```
[Test it](https://tio.run/##Rc7NCoJAEMDx@zzFEBm7ZYKVCi5GHerUMbr7MYG0qbgqRdSLdevFrK3Q2/Kf3wxbUCndtlaEjWvFAuB8xVGcJ4RBO7aiUBGbcSvOzxF72NwwZq3QZFWRqjBAmWakXk9rc1jvBOgz@89AQCHDDCdfJeCYl/@F6RIZ@ie6smGaFXXFTfSbUNbEhnQpKK4o4cjxBoipQv2NHnbCxMEvYrDs6wDu7VyXfVkT2LZ@bkOpCDzP6/qiJ47TkTc "Perl 6 – Try It Online")
## Expanded:
```
*\ # WhateverCode lambda (this is the parameter)
.base(2) # Str representing the binary
.comb(~1) # find the "1"s
%% 2 # is the count of "1"s divisible by 2?
```
[Answer]
# [Attache](https://github.com/ConorOBrien-Foxx/Attache), ~~13~~ 12 bytes
```
Even@Sum@Bin
```
[Try it online!](https://tio.run/##Zc5BC4IwFAfwu5/ioRkaCzITQTBWUVCHCIwuYwexWQOdw82@/prSreN7/P/v/Uqty@rNTJ3l5vhhAhdDi/dcmCtjT0VmUlYv6tx6LvSdKX0oFVOkRkBiBFGEIE1TBBs7JAn95Yi7dGEB6xV1nLrVkOVw6vq21PPMDXwVgq9cjINLx8X4yXt4dehwIYcpegW8hUI2XJNd05zHNbGX/witRjCVqImtxBosYeR8AQ "Attache – Try It Online")
(Old 13 bytes: `Even@1&`~@Bin`)
This is a composition of three functions:
1. `Bin`
2. `Sum`
3. `Even`
This checks that the `Sum` of the `Bin`ary expansion of the input is `Even`.
[Answer]
# [dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html), 18 16 bytes
```
[2~rd1<M+]dsMx2%
```
Returns (to the stack) 0 for evil and 1 for not evil
[Try it online!](https://tio.run/##S0n@b2L8P9qorijF0MZXOzal2LfCSPV/wX8A "dc – Try It Online")
Fairly straightforward - recursively applies the combined quotient/remainder operator `~` to the new quotient and adds all the remainders together, then mods by 2 (after spending two bytes to flip to a standard truthy/falsy).
Edited to reflect consensus that 0 for truthy and 1 for falsy is okay, especially in a language that has no sort of `if(boolean)` construct.
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 10 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?")[SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set")
Anonymous tacit function. Can take any array of integers as argument.
```
≠⌿1⍪2∘⊥⍣¯1
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT////1Hngkc9@w0f9a4yetQx41HX0ke9iw@tN/yf9qhtwqPevkd9Uz39H3U1H1pv/KhtIpAXHOQMJEM8PIP/pykYKxgaKphYGCiYGCuYmgIA "APL (Dyalog Unicode) – Try It Online")
`2∘⊥⍣¯1` convert to binary, using as many digits as needed by the largest number, separate digits along primary axis
`1‚ç™`‚ÄÉprepend ones along the primary axis
`≠⌿` XOR reduction along the primary axis
[Answer]
# Python 2, 29 bytes
```
lambda n:~bin(n).count('1')&1
```
[Try it online!](https://tio.run/##K6gsycjPM/r/PycxNyklUSHPqi4pM08jT1MvOb80r0RD3VBdU83wf5otXnkurrT8IoWS1OIShcw8BQ1jHQVDQx0Fc3NzHQUTIMfUVNOKi7OgKDOvRCFNA6RM8z8A "Python 2 – Try It Online")
Returns 1 if True, else 0.
Converts the number to a binary string like '0b11', counts the number of 1s, gets the complement of result, and returns the last bit of the complement (thanks, [<https://codegolf.stackexchange.com/users/53560/cdlane>](https://codegolf.stackexchange.com/users/53560/cdlane)!) (1 if the original number was even, 0 if it was odd).
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 14 bytes
```
ThueMorse@#<1&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78H1CUmVcS/T8kozTVN7@oONVB2cZQ7b@@g0K1sY6CoaGOgrm5uY6CCZBjaqqjYGZoBiTMzGpj/wMA "Wolfram Language (Mathematica) – Try It Online")
The Nth element of the Thue-Morse sequence is 1 if the number of binary digits in N is odd, and 0 otherwise.
] |
[Question]
[
Input must not be required, and output must read "`All your base are belong to us`".
Restrictions
* No external resources.
Plus a minimum of two of the following:
* You cannot use "a", "b", "t", "u", or "y" in any case in your code (bonus -10 to your golf score if you can do this)
* You cannot use "l", "o", "s", "e", or "r" in any case in your code (bonus -20 to your golf score if you can do this)
* You cannot use "n", "g", "0", "1", or "2" in any case in your code (bonus -30 to your golf score if you can do this)
So for example, if you manage to get the code done with 40 characters and use rules 1 and 2, your golf score is 40 - 10 - 20 = 10 chars.
Smallest code golf score wins... Good luck!
[Answer]
# GolfScript, -22 (38 characters, -60 bonus)
```
"„¯¯c¼²¸µc¥¤¶¨c¤µ¨c¥¨¯²±ªc·²c¸¶"{67-}%
```
[Answer]
# [Sclipting](http://esolangs.org/wiki/Sclipting), −40
```
뀖롬긇땯덗긠눦굳뉒걡댦넠눦녬닶멧긇끯긇녳
```
* = 20 characters − 60 bonus
* Only works if the input is empty, which I take to be the case; if not, add `丟` in front, changing the score to −39.
* If I can assume the input to be what I want (as [this answer](https://codegolf.stackexchange.com/a/19222/668) apparently does), then the empty program is a solution and my score is −60.
[Answer]
## Brainfuck, 267 - 60 = 207
```
++++++++[>++++++++<-]>+.<+++++++[>++++++<-]>+..>>++++++[<+++++>-]<++.<+++++++++
++++.----------.++++++.---.>.<<++++[>----<-]>.-.<+++[>++++++<-]>.--------------
.>.<----.<++++[>++++<-]>+.-------------.>.<---.+++.+++++++.+++.-.-------.>.<+++
++++++++++.-----.>.<++++++.--.
```
[Answer]
## JavaScript - 140 bytes - 60 bonus = 80 points
```
(x="Ǎľľ y̌ǒǔř b̌ǎšě ǎřě b̌ěľǒňǧ ťǒ ǔš")[x[3*9]+x[34]+"p"+x[4]+x[5*5]+"c"+x[34]]("̌","",x[6*7])
```
Run in Firefox.
I know what you're thinking. No, those aren't the characters that are listed in the question. Those are characters with a caron, or háček (picked randomly from a list of diacritics). Even though they're combining marks, they aren't two separate characters.
[Answer]
## APL (43 - 30 - 20 = -7)
```
⎕AV['⊥┤┤ ø┼&┐ `∣┘û ∣┐û `û┤┼─ù ´┼ &┘'⍳⍨⌽⎕AV]
```
This satisfies rules 2 and 3.
[Answer]
# HTML/CSS 70
```
<p style="transform:rotate(.5turn)">sn oʇ ƃuoləq əɹɐ əsɐq ɹnoʎ llɐ</p>
```
<http://jsbin.com/EjekuvuF/1/>
I thought I was being clever with the upside down type but then realized I couldn't meet any of the ancillary rules with the actual HTML/CSS. Oh well.
UPDATE:
User Flame suggested a more cross-browser compliant solution:
```
<p style="transform:rotate(180deg)">sn oʇ ƃuoləq əɹɐ əsɐq ɹnoʎ llɐ</p>
```
<http://jsbin.com/EjekuvuF/6>
[Answer]
## MATLAB, All bonuses: Score of -20 (40-60)
```
['' '¤ÏÏèÜÒØÕèÅÄÖÈèÄÕÈèÅÈÏÒÑÊè×ÒèØÖ'-99]
```
### EDIT:
Note that I am not sure of what the system requirements are to run this, tested on windows. For those struggeling to copy, a similar code can be generated like so:
```
char('All your base are belong to us' + 99)
```
---
If it would have been allowed to ask anything as input, a solution with less characters (but also missing the bonus) would of course be possible.
```
input('')
```
[Answer]
# k (-7 = 53 - 60)
`(#`)"c"$(465%3)-6h$"Z//{\",&){9:(6{:)6{96/,-4{',{&(";`
doesn't include trailing newline, can be added at cost of one additional char:
`(-#`)"c"$(465%3)-6h$"Z//{\",&){9:(6{:)6{96/,-4{',{&(";`
annoyingly, the only offsets that work for this trick are 154 and 155
edit:
if it's sufficient to display the string (rather than printing it), as i suspect the APL solution does (it doesn't work in <http://tryapl.com/>, so i can't test it properly), it's
```
"c"$(465%3)-6h$"Z//{\",&){9:(6{:)6{96/,-4{',{&("
"All your base are belong to us"
```
which is -12 = 48 - 60. can i get a ruling on whether this is sufficient?
[Answer]
### dc, ~~97 - 60 = 37~~ ~~91 - 60 = 31~~ ~~88 - 60 = 28~~ 81 - 60 = 21
```
3C87596P4d^8/P7958389P7479394P6386533P7C89P749698CP644848CP459 8^699 7^3849736388974773333 86-++P
```
Improved version (the main idea here is to vary the input base, to increase the chances of finding a useful big number with no problematic digits):
```
IDi67793554D647F84C836645D6569F69Pi6385C77P9i35PDdi6^I9^+6D59CD83D664D34+P8CPFi98CCF5PCi97P
```
In base 7, the whole thing can become a single number! Lower bases are naturally less compact, but the lack of fix-up operations here makes up for it.
```
7i4398873968644388737548444897643735447698675366869556798538985674336396359936458859886P
```
My first solution used base 10. My second used a mix of base 9, 10, 12, 13, and 15. This one is in base 7. I truly feel like all the base *are* belong to me.
**Last one, seriously:** Base 13 does a great job on the first segment, then base 7 for the rest.
```
Di67793554D647F84C836645D6569F69P7i798789699638355733695878558396339387963789536P
```
[Answer]
## Python REPL, ~~122~~ ~~116~~ 98 characters - 30 bonus = ~~92~~ ~~86~~ 68 points
```
>>> '\x41\x6c\x6c \x79\x6f\x75\x72 \x62\x61\x73\x65 \x61\x72\x65 \x62\x65\x6c\x6fng \x74\x6f \x75\x73'
'All your base are belong to us'
```
I could get rid of the zeroes in Python 3.3 by replacing '`\40`' with `\N{SP}`, but alas, the `N` is not permitted.
**Edit**: Inspired by [this answer](https://codegolf.stackexchange.com/questions/19171/all-your-base-are-belong-to-us-restricted/19412#19412), I've shortened it further by replacing `\x40` by . Moreover, since I already use the `1`, replacing `\156` by `n` and `\x67` by `g` shortens it by another 6 characters while incurring no extra penalty.
[Answer]
# Brainfuck, ~~205~~ 203 - 60 = ~~145~~ 143 bytes
```
++++[->++++<]>[->++++>++>+++++++>++++++>++++++++<<<<<]>+.>>----..<.>>>-------.<<+++.>>----.---.<<<.>>++.-.>+.<++++.<<.>>----.>-.<++++.<<.>>---.+++.<---.>>---.-.<<-----.<.>>>++++++.-----.<<<.>>>++++++.--.
```
Readable version:
```
++++[->++++<]>[->++++>++>+++++++>++++++>++++++++<<<<<]
64 32 112 96 128
>+.>>----..<. All 65 108 108 32
>>>-------.<<+++.>>----.---.<<<. your 121 111 117 114 32
>>++.-.>+.<++++.<<. base 98 97 115 101 32
>>----.>-.<++++.<<. are 97 114 101 32
>>---.+++.<---.>>---.-.<<-----.<. belong 98 101 108 111 110 103 32
>>>++++++.-----.<<<. to 116 111 32
>>>++++++.--. us 117 115
```
[Answer]
# Befunge 98 : 122 - 60 = 62
```
5f8+*:53-+:' \6-:5+' 91+:*3+::7+\8+:3-:7-:3-:' \3+::3-4+',' -+\4-:' \:4+\6+c+:f3+-:4+3-' '&3*:3+:6-:f+5-:' \d-:' '!+ff+k,@
```
Computes the ascii values, then prints them. I still need to try out other methods of forming the numbers to see if there are shorter ways.
[Answer]
# Python, 195-40 = 155
```
x,w,y,z,v=4*8,55,56,57,58;exec(("%c"*38)%(y+y,z+z,49+y,w+w,v+v,39-7,34,65,54+54,54+54,x,v+63,48+63,48+69,z+z,x,98,97,59+y,45+y,x,97,z+z,45+y,x,98,45+y,54+54,w+y,w+w,45+v,x,v+v,w+y,x,v+59,z+v,34))
```
[Answer]
# [SOGL V0.12](https://github.com/dzaima/SOGL), 15 - 60 = -45
```
šz█P'zUS½█│β3‘⁾
```
[Try it Here!](https://dzaima.github.io/SOGLOnline/?code=JXUwMTYxeiV1MjU4OFAlMjd6VVMlQkQldTI1ODgldTI1MDIldTAzQjIzJXUyMDE4JXUyMDdF)
`šz█P'zUS½█│β3‘` is a compressed string of `all your base are belong to us`, but because that exact string compressed contained `0`, it's split into 3 parts: `all your base are`, , `belong to us` (which cost one byte but gave a -30 byte bonus). The first and last strings are compressed with SOGLs English dictionary, and implicitly joined with spaces. The remaining `⁾` is a simple sentence case built-in.
Note that SOGL postdates this challenge, but that's allowed now.
[Answer]
## Ruby, 121 - 50 = 71
A bit brute force, but most of the cute methods are ruled out:
```
$><<[65,c=36*3,c,d=8*4,363/3,f=c+3,c+9,c+6,d,x=98,97,j=c+7,k=3+x,d,97,c+6,k,d,x,k,c,f,j-5,5+x,d,c+8,f,d,c+9,j].pack('C*')
```
Breaks rule #1 because of the A in `pack`, the other two should be OK.
[Answer]
## {ba,z}sh, ~~67 - 40 72 - 60~~ 61 - 40 = 21
```
$'\x74r' K-~\#-\; _@-~\^-j<<<'Mxx ){%~ 3m#q m~q 3qx{z8 ${ %#'
```
Darn it, turns out I had a `r` in there that I hadn't noticed, so the 20 bonus doesn't apply!
[Answer]
# C, 75 bytes - 60 = 15
*Thanks to @gastropner for getting the score down from 50 to 33 and from 19 to 15!*
```
*q,i;f(p){(*(q=p)="\v&&j3%?8j(+9/j+8/j(/&%$-j>%j?9J"[i++]^74)?i=!f(++p):i;}
```
Takes the address of a char array as input and writes the string to the array.
[Try it online!](https://tio.run/##JYjRCoIwFEDf/QqTlDvXkDRoNtbe@wUzGIPZRsps1ov4662w83TOUaRTKoR83BmmwaEZchi5Qzy5vrPMVqmgFnBdWEwLC0WWbok9p1bUl6QxGLe34wEJwzcaMHboZNgSzDDFvTQDoGiO4h/qLp@xb/Ylbdk6NHj0N/ea/BpL@Cj9kJ0PpK/KLw)
**Call with:**
```
int main()
{
char s[128];
f(s);
puts(s);
}
```
**Output:**
[![](https://i.stack.imgur.com/Ap7NZ.png)](https://i.stack.imgur.com/Ap7NZ.png)
**Old version (90 bytes - 40 = 50):**
```
*q,i,j;f(p){for(i=3-3;j="Epp$}s v$fewi$evi$fipsrk$xs$ w"[i++];*q=j!=35-3?j-4:353/3)q=p++;}
```
[Answer]
# Brainfuck, (227 - 60 = 167)
```
+++++ +++++[>+++>++++++>+++++++++>++++++++++<<<<-]>>+++++.>>++++++++..<<<++.>>>+++++++++++++.----------.++++++.---.<<<.>>++++++++.-.>+.<++++.<<.>>----.>-.<++++.<<.>>---.+++.>------.+++.-.<++.<<.>>>++++++.-----.<<<.>>>++++++.--.
```
[Answer]
# Postscript, 364 - 40 = 324
I couldn't do it without `loser`, of course. :)
```
/${cvx exec}def
/+{<3C7E4F6F597E3E>$ $}def
/*{<~P&(~>$}def
/-{( )<3C7E4F754E7E3E>$ $ 3 4<~P#;~>$ 4 3<~P)#3FP'-~>$}def
/_{36( )<~OoP~><3C7E4F754E7E3E>$ $ 4 3<~P,S~>$ 48<~P'?~>$
${96 3<~P#;~>$ + -}<~P">~>$}def
/.{_ 96 3<~P#;~>$ -}def
65 - 777 .
895 353 + _ 774 333 + .
74933 333 + 7 * 3 + 333 + .
9593 4353 + .
689653949 335 + .
735 333 + .
775 333 + _ 5 5 + -
```
This starts with encoding the text as base-36 strings:
```
%-=Encoding strings as base-36 numbers=-
%All your base are belong to us
% handle uppercase A separately
%36#ll = %777
%36#your = %1618515
%36#yo = 36#ur = 36#base = 36#are = 36#belong = 36#to = 36#us =
%1248 1107 527198 13946 689654284 1068 1108
```
And then removing the 1s and 0s and 2s arithmetically. The strings can then be regenerated with `36 <string-buf> cvrs`, but this yields upper-case letters, so we then need to iterate through and add 0x20 to make them lowercase.
The operators `cvx exec` allow us to execute string fragments of binary-encoded operator tokens in various encodings. Simplest is to encode an operator in hex `<92??>` but there's a 2 in there! So the "first-level" encoding is ascii85. Then any strings that still contained forbidden characters went through extra levels of hex -> ascii85 -> hex -> ascii85.
[Answer]
# JavaScript
## ~~(306 characters - 60 bonus = 246)~~ ~~(206 characters - 50 bonus = 156)~~
## (123 chars = 173 chars - 50 bonus)
Kind of nooby, probably could get more off... Let me know if I've stuffed something up, this alerts "All your base are belong to us". This is also ASCII-only.
```
(c=(''+!'')[4-3],x=([][3]+c)[6])[a='c\x6F'+x+'\x73t'+c+'uct\x6F'+c][a]('a\x6C\x65'+c+'t("A\x6C\x6C y\x6Fu'+c+' ba\x73\x65 a'+c+'\x65 b\x65\x6C\x6F'+x+'\x67 t\x6F u\x73")')()
```
If you count the console itself as output, this would also count (57 with bonus):
```
'A\x6C\x6C y\x6Fu'+(c=(''+!'')[4-3])+' ba\x73\x65 a'+c+'\x65 b\x65\x6C\x6F'+([][3]+c)[6]+'\x67 t\x6F u\x73'
```
[Answer]
## Brainfuck, 306 - 60 = 246
```
----[---->+<]>++.[--->+<]>+..[++>---<]>--.--[->++++<]>+.----------.++++++.---.[-->+++++<]>+++.[--->+<]>++.-.--[--->+<]>--.++++[->+++<]>.--[--->+<]>-.[--->+<]>+.--[--->+<]>---.-------------.--[--->+<]>-.[--->+<]>++.+++.+++++++.+++.-.-------.-[--->+<]>--.---[->++++<]>.-----.[--->+<]>-----.---[->++++<]>+.--.
```
[Answer]
# PHP (35 - 60 = -25 bytes)
[`HOW LOW CAN YOU GET ?`](http://donhodges.com/how_high_can_you_get.htm)[1][2]
```
$ xxd yourbase.php
0000000: 3c3f 3d7e be93 93df 8690 8a8d df9d 9e8c <?=~............
0000010: 9adf 9e8d 9adf 9d9a 9390 9198 df8b 90df ................
0000020: 8a8c 3b ..;
```
---
[1] This program can be decoded using `xxd -r`.
[2] Yeah, heavy solution reuse here. I think it's... third problem I solved this way. Perhaps I should move to something else, but it's not that this is not great for problems that forbid you from using most characters.
[Answer]
# Bash, 52 - 10 - 30 = 12
The following is to be executed in a (still pretty common) ISO-8859-1 environment:
```
$'\x74r' À-þ @-~<<<'Áìì ùïõò âáóå áòå âåìïîç ôï õó'
```
This calls `tr`, which translates the characters in a suitable way. I had to either use the `r` and violate rule 2, or use a digit in the escape and violate rule 3. Since 3 gives more bonus, I chose the former.
[Answer]
# Pure Bash (no external resources), 141 chars - 50 bonus = 91
```
Z=({k..v})
f=$'\x65'
h=$'\x6c'
i=$'\x6f'
j=${Z[7]}
k=$'\x73'
m=$'\x75'
$f$'\x63'h$i A$h$h y$i$m$j ba$k$f a$j$f b$f$h$i${Z[3]}$'\x67' t$i u$k
```
Intentionally dropping the 10-point bonus to get a better overall score.
This works on any `bash` version 3.00.15 or later that I have tried.
### How does it work
There's no rocket science here - just `bash` expansions of one form or another:
* Simple hex expansion to obtain required character. This works for characters whose hex representation doesn't contain `[012]`. e.g. `$'\x65'` gives us `e`
* For other characters, we generate a bash array of sequential characters using brace expansion into an array initialization (`Z=({k..v})`). The start of the brace expansion is chosen carefully so that the indexes of the characters we require don't contain `[012]`. e.g.
`${Z[7]}` gives us `r`.
* `bash` is flexible enough to allow its commands to be constructed from the contents of multiple strings. So `$f$'\x63'h$i` expands to `echo`.
* For characters that are required only once, the expansion is inserted inline to the echo command string.
* For characters that are required twice or more it is more efficient to expand them to variables, then reference the variables.
---
Previous answer with full bonus, but worse overall score:
### Pure Bash (no external resources), 193 chars - 60 bonus = 133
I know this won't win, but I wanted to prove to myself this is possible in `bash`, while satisfying all requirements:
```
Z=({3..8} {C..z})
c=${Z[36]}
d=${Z[37]}
f=$'\x65'
h=$'\x6c'
i=$'\x6f'
j=${Z[53]}
k=$'\x73'
m=$'\x75'
$f$'\x63'h$i ${c^}$h$h $'\x79'$i$m$j $d$c$k$f $c$j$f $d$f$h$i${Z[49]}$'\x67' $'\x74'$i $m$k
```
This does require a fairly recent version of `bash` for the `${c^}` parameter expansion. 4.2.25 is fine, but 3.2.48 is a no-go.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 23 - 60 = -37
```
“%⁼“¡¢8ṣƤ¹;“pȷȦÆ⁾“¡PȤṫ»
```
[Try it online!](https://tio.run/nexus/jelly#@/@oYY7qo8Y9QOrQwkOLLB7uXHxsyaGd1kB@wYntJ5YdbnvUuA8sGXBiycOdqw/t/v8fAA "Jelly – TIO Nexus")
This is just the compressed representation of `["All", " your base are", " belong to", " us"]` (Jelly has a compressed string format). The string's split into multiple pieces in order to ensure that none of the banned characters appear within the compressed representation; they're all implicitly concatenated at the end of the program.
[Answer]
## PHP, 186 - 10 - 30 = 146
I had to get a little creative ;)
```
<?=chr(65).'ll '.chr(88+33).'o'.chr(39*3).'r '.chr(98).chr(97).'s'.chr(68+33).' '.chr(97).chr(38*3).chr(68+33).' '.chr(98).'elo'.chr(77+33).chr(69+34).' '.chr(83+33).'o '.chr(39*3).'s'?>
```
[Answer]
# PHP, 67 bytes -60 bonus = 7
```
<?=d__cJZFFcQWFVcWFVcQV_ZZQcCZcFF^"%33C3534C3653C643C333546C75C35";
```
bitwise XOR on the ASCII characters
I brute forced a pair of characters not in the forbidden characters for each character in output.
No word character pair for `A` and I don´t like extended ASCII, so I live with one string in quotes.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `ṡ`, 20 bytes, score -40
```
‛λʀ«×∇⟇Ȧߥfė₀⌊↓qεǏq⟑
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=%E1%B9%A1&code=%E2%80%9B%CE%BB%CA%80%C2%AB%C3%97%E2%88%87%E2%9F%87%C8%A6%C3%9F%C2%A5f%C4%97%E2%82%80%E2%8C%8A%E2%86%93q%CE%B5%C7%8Fq%E2%9F%91&inputs=&header=&footer=)
-4 bytes / -4 score thanks to Aaron Miller.
[Answer]
**Python, 181 - 40 = 141**
[I'm using version 2.7.2 YMMV - the builtin, `file` is gone in python 3.X]
```
f=file.__doc__;c=5-3;l=f[c];s=' ';e=f[3];h=f[6+7];i=f[c*87];j=3**3;f[j*c*5]+l+l+s+f[-57]+h+f[j-7]+f[j-3]+s+f[j-8]+f[6]+i+e+s+f[6]+f[j-3]+e+s+f[j-8]+e+l+h+f[5]+f[j]+s+f[45]+h+s+f[j-7]+i
```
[Answer]
# Python (104 - 30 = 74)
```
>>> '\x41\x6c\x6c \x79\x6f\x75\x72 \x62\x61\x73\x65 \x61\x72\x65 \x62\x65\x6c\x6f\156\x67 \x74\x6f \x75\x73'
'All your base are belong to us'
```
And score:
```
>>> len(r"'\x41\x6c\x6c \x79\x6f\x75\x72 \x62\x61\x73\x65 \x61\x72\x65 \x62\x65\x6c\x6f\156\x67 \x74\x6f \x75\x73'")-30
74
```
] |
[Question]
[
`yes`, from coreutils, is [91 lines long](http://git.savannah.gnu.org/cgit/coreutils.git/tree/src/yes.c?id=8e93dc629727140e950a709008f9a17ca461af63). Many of them are comments, but that is still **WAY** too long.
Edit from September 2019: the source file grew over the past five years and is now 126 lines long.
Write a program that imitates `yes`:
* outputting to `stdout` an infinite stream of "y\n"'s
* there must be an option to stop it other than killing the process with `SIGKILL`: but `SIGINT` and `SIGPIPE` are fine
* you are not allowed to use "y" or "\n" or their ASCII values (121, 0x79, 0171, 10, 0xA or 012)
Shortest answer wins.
Bonus:
* subtract 10 from your code length, if you can receive a phrase in `stdin` and print it out instead of "y" (but still including the line-break). The program [doesn't have to](https://codegolf.stackexchange.com/questions/42428/yes-is-91-lines-long/162321?noredirect=1#comment100392_42428) print `y` on an empty input.
[Answer]
# CJam, 13 bytes - 10 = 3
```
l_'x)?{_oNo}h
```
You'll need to use [the Java interpreter](https://sourceforge.net/projects/cjam/) for this, because the online interpreter only returns once the program terminates.
You can abort the program with SIGINT (by pressing Ctrl-C). It will read a line from STDIN, and print that line, or `y` if the input was empty.
## Explanation
```
l "Read line from STDIN.";
_ "Duplicate.";
'x "Push character x.";
) "Increment to get y.";
? "Ternary operator. Replaces line with y if it was empty.";
{ }h "Repeat while true. Leaves condition on the stack, which is the output string.";
_o "Duplicate line and print.";
No "Push string with newline and print.";
```
After clarification of the OP, the following seems more to spec:
```
l{_o9c)o1}g
```
I'll wait with updating the submission until the OP replies to my comment, though.
[Answer]
# Brainfuck - 38 bytes
```
++++++++++[>++++++++++++>+<<-]>+[.>.<]
```
It doesn't use 10 or 121, because `+-<>.,[]` are all the meaningful characters in the language anyway, but it does calculate them pretty naively (0+1+1+1+1+1+1+1+1+1+1=10, 10\*12+1=121).
This probably depends on the interpreter, but it dies to `^C` on my machine.
# Brainfuck - (63-10)=53
```
++++++++++[>,]<<[[<]>>[[.>]<[<]>]]>[>++++++++++++>+<<-]>+[.>.<]
```
[Answer]
# Python 3, 27 bytes
Works with at least CPython and Jython.
```
while 1:print(str(help)[1])
```
SIGINT stops it.
[Answer]
# Pyth, ~~10~~ ~~9~~ 6 bytes - 10 = ~~0~~ ~~-1~~ -4
```
#|zePG
```
I've been trying for ages to get one that I'm satisified with. Basically converts to:
```
# = while True
(implied print)
| = or
z = (automatically initialized from stdin)
ePG = second-to-last lowercase letter = 'y'
```
[Answer]
# [Marbelous](https://github.com/marbelous-lang) 14 bytes
```
0978
]]/\++
!!
```
This is pretty straightforward, the '/\' device places two copies on its left and right, the right one is incremented by `++` and then falls off the board and is printed. The `]]` device pushes any marble to the right if STDIN is empty but lets the first byte on STDIN fall down if it isn't. This will then trigger the `!!` device, which exits the board. So this will print y\n until you enter anything on stdin.
This only works in the python interpreter.
[Answer]
# C#, ~~81~~ ~~78~~ 76 bytes
Cannot compete with the other languages, but here it is anyway:
```
class A{static void Main(){for(;;)System.Console.WriteLine((char)('x'+1));}}
```
Can be killed with SIGINT by pressing `Ctrl`+`C`.
No bonus, because it would take more than 10 bytes to get it.
[Answer]
## Java, 178
```
class C{public static void main(String[]a)throws Exception{for(char c='x'+1;;)((java.io.PrintStream)Class.forName("java.lang.S"+c+"stem").getField("out").get(null)).println(c);}}
```
Printing requires `System`, but the `y` character is forbidden. Hence, I had to use reflection.
[Answer]
# Perl: 18 bytes - 10 = 8
The string is from STDIN.
```
$_=<>;{print;redo}
```
[Answer]
# Ruby, ~~30~~ ~~23~~ 18 bytes
```
loop{puts ?x.succ}
```
Can be killed with SIGINT by pressing `Ctrl`+`C`.
Thanks to [manatwork](https://codegolf.stackexchange.com/users/4198/manatwork) for sharing improvements!
[Answer]
# Linux Bash - 19 bytes
This is probably cheating and subject to failure if you don't have /usr/bin/yes or have a /usr/bin/xes or /usr/bin/zes:
```
/usr/bin/[x-z]es $*
```
I think it meets the requirements, though maybe it's violating the "nothing that evaluates to y" rule. And perhaps imitating `yes` by actually running `yes` is against the rules.
This could be optimized a bit (though less likely to work) to take it down to 11 bytes:
```
/*/*/?es $*
```
I couldn't figure out how to get the 10 point bonus by reading a string from stdin without adding more than 10 bytes to the code
[Answer]
# Perl, 26 bytes
```
{print chr$=*2+1,$/;redo}
```
## Custom input from argument (like `yes` actually works), 22 bytes-10=12
```
{print @ARGV,$/;redo}
```
## Custom input from stdin, 22 bytes-10=12
```
while(<>){print;redo}
```
[Answer]
## C, ~~64~~ ~~55~~ ~~53~~ ~~45~~ 40 - 10 = 30
`main(int c,int**a){for(;;)puts(a[c>1]);}`
I'm not hugely happy with this, as it requires the program to be named "y", and to be called with `y` only, so it has to be in $PATH, but hey, first codegolf :)
Alternative:
## C, 30 (+ 1 filename)
`main(){for(;;)puts(__FILE__);}`
Using the same technique as my esteemed colleague @Matt Windsor
* EDIT: turns out getting round the no \n character made it shorter
* EDIT2: "int" is shorter than "char"
* EDIT3: didn't need that variable at all
* EDIT4: a bit of slightly undefined behaviour never hurt anyone
* EDIT5: add alternative version
[Answer]
# dc, 12
```
[30986Pdx]dx
```
Only outputs `y\n`. Doesn't read from stdin, so no bonus.
30986 is 0x790A (i.e. "y\n"). The `P` command simply converts the number to base 256, and prints the corresponding character for each base 256 digit.
[Answer]
## **Linux Bash, 33-10 = 23**
```
read a; while :; do echo $a; done
```
Can be killed with SIGINT by pressing `Ctrl`+`C`.
[Answer]
# Rust, 52 chars
```
fn main(){loop{println!("{}",'Y'.to_lowercase())}}
```
There just isn't seemingly a nice way of computing `y` without being cheeky in Rust-- they've made too good a job of doing chars safely. I:
* Can't supply a non-literal string to `println!`, so no tricks allowed there;
* Can't add 1 to `'x'`, because in Rust chars aren't numbers;
* Can't ROT13 (why doesn't Rust have ROT13 in its standard library!?);
* Can't easily do anything unsafe like dropping to C strings, converting from numbers to chars, etc without being incredibly verbose and going over 52c.
Nor is going for the code bonus worth it, because reading from `stdin` would require error handling =3
Much of the code reductions I could find involved doing increasingly rule-flouting things with the compiler environment:
# Rust, 44 chars (+ at least 1 char for filename)
```
fn main(){loop{println!("{:.1}", file!())}}
```
**Obsoleted by below.** This one probably doesn't count, as the name of the *source* file needs to begin with `y`.
# Edit: Rust, 36 chars (35 source, 1 filename)
```
fn main(){loop{println!(file!())}}
```
As above, but the file *has* to be called `y` (not `y.rs`, `y`). Humorously, Rust will overwrite the source with the binary! At least on my machine, the binary does work after that though.
# Rust, 37 chars (+ equivalent of `env K='y'` on your platform)
```
fn main(){loop{println!(env!("K"))}}
```
This one is even worse: you need to set the environment variable `K` to `y` at *compile time*.
**Edit**: if you set `K` to `y\n`, you could drop the `ln` in `println!`, for a grand total of ~~35 chars and~~ several facepalms:
```
fn main(){loop{print!(env!("K"))}}
```
[Answer]
## Common Lisp : (30-10) = **20**
```
(format t"~@{~a~%~:*~}"(read))
```
* `(read)` from input stream
* print to output stream: `(format t ... )`
* iterate over all `format` arguments (only one here) : `~@{ ... ~}`
* inside the loop, for each argument:
+ print argument `~A` followed by a newline `~%`
+ rewind *current element* to the previous one `~:*` (infinite loop)
You can break the loop with `Ctrl+C`, which signals an error with restart options (continue/abort).
[Answer]
## Commodore 64 Basic: 14 13 bytes
```
1?C|(11‚Üë2):R‚ï≠
```
As usual, I've made substitutions for characters in PETSCII that are not present in Unicode. `|` is used to represent `SHIFT+H`, while `‚ï≠` represents `SHIFT+U`. Note that this outputs ASCII 'y' (byte value 121) rather than a character that the default Commodore character set displays as 'y'.
BASIC is supposedly an easy-to-learn, English-like programming language. Throw in the typing shortcuts present in many early dialects, and you get something that is shorter and less readable than Perl.
**EDIT**: In "shifted mode", this gets two bytes shorter, thanks to lowercase "y" being encoded at decimal value 89. Using a non-ASCII character set to get around the "not allowed to use their ASCII values" rule might be cheating, though.
```
1?cH(89):rU
```
[Answer]
# [Fission](http://esolangs.org/wiki/Fission), 5 bytes
```
Rx+!N
```
This is fairly competitive for Fission. :)
Control flow starts with a `(1,0)` right-going atom at `R`. `x` sets the mass to `120`, and `+` increments it to give `(121,0)`. Then `!` prints the corresponding character (`y`) and `N` prints a newline. The source code wraps around at the edges, so the atom passes `R` again (which doesn't do anything now), `x` sets the mass to `120` again, `+` increments it and so on and so on...
[Answer]
# Haskell, 29 bytes
```
main=putStrLn[succ 'x']>>main
```
I believe this is stopped by both `SIGINT` and `SIGPIPE`.
[Answer]
# Ruby, 27 bytes - 10 = 17
It's just @ProgramFOX's solution with the bonus (it took my 9 bytes to solve the bonus question).
```
loop{puts ARGV[0]||?x.succ}
```
[Answer]
# dc, 21 bytes - 10 = 11
```
C1st?st[ltP[]ps0dx]dx
```
Note that the input needs to be wrapped in `[]`, e.g. `[no]`, because `?` is the only way to take input, which executes it as `dc` code.
[Answer]
## AWK, 38 bytes
```
BEGIN{for(;;)printf("%c%c",60+61,5+5)}
```
Variant which will read the string on stdin: 14 bytes-10 = **4**
```
{for(;;)print}
```
But since it cannot do both (revert to "y" if no stdin is provided), I'm not sure it counts... :o)
Both can be exited with Ctrl+C.
[Answer]
## Perl, 31
Here is a Perl version that actually behaves like GNU `yes`, as far as I can tell:
```
{print "@ARGV"||chr 11**2;redo}
```
This works if it is okay to use perl's command line switches (`-l` for the newline), otherwise it would become 3 characters longer:
```
{print "@ARGV"||chr 11**2,$/;redo}
```
[Answer]
# C, 32 bytes
Requires little endian machine and compilation with -O2 (to avoid stack overflow).
```
a=11*11;main(){main(puts(&a));}
```
[Answer]
### Javascript, 39 37 bytes
```
for(;;)console.log(''+Function()[13])
```
### Shorter alternative that only works in the browser, 36 bytes
```
for(n=''+crypto;;)console.log(n[10])
```
### Alternative without console.log, only works in NodeJS, 58 57 56 bytes
```
for(n=''+Function()};;)process.stdout.write(n[13]+n[19])
```
[Answer]
## PowerShell, 27 ‚àí 10 = 17
```
param($s=$Host[1])for(){$s}
```
Might not work in Pash. A more robust alternative should be
```
param($s="$(gal gh*)"[2])for(){$s}
```
[Answer]
# Lua, 42 bytes - 10 = 32
```
while 1 do print(...or('').char(90+31))end
```
# Lua, 49 bytes - 10 = 39
```
y=...or(string.char(60+61))while 1 do print(y)end
```
Both were tested with Lua 5.1.4 and can be killed with SIGINT (`Ctrl`+`C`).
[Answer]
## Fortran, 28
```
do1;1 print'(A1)',11**2;end
```
Compile with `gfortran -ffree-form`.
[Answer]
# [APL (Dyalog APL)](https://www.dyalog.com/), 5 - 10 = -5 bytes
Warning: relies on an undocumented and unsupported feature/bug.
```
⎕←⍣≢⍞
```
[Empty STDIN](https://codegolf.stackexchange.com/questions/42428/yes-is-91-lines-long?page=2&tab=active#comment100350_42428) prints empty lines (not "y"), which [is allowed](https://codegolf.stackexchange.com/questions/42428/yes-is-91-lines-long?page=2&tab=active#comment100392_42428) and [has been suggested](https://codegolf.stackexchange.com/users/8478/martin-ender).
[Try it online!](https://tio.run/nexus/apl-dyalog#@/@ob@qjtgmPehc/6lz0qHfe//@VAA "APL (Dyalog APL) – TIO Nexus")
`‚éï` STDOUT with trailing newlines,
`‚Üê` gets
`⍣` repeatedly until
`≢` it differs from
`‚çû` STDIN
i.e. never, but uninterruptible by pausing the thread.
[Answer]
# [Ahead](https://github.com/ajc2/ahead), 8 bytes
```
~W-1z'N~
```
[Try it online!](https://tio.run/##S8xITUz5/78uXNewSt2v7v9/AA "Ahead – Try It Online")
] |
[Question]
[
Write a program or function that outputs an `L` if run on a little endian architecture or a `B` if run on a big endian architecture. Lower case output `l` or `b` is also acceptable.
There is no input.
Scoring is code golf, so the code with the fewest bytes wins.
**Edit:** *As per the comments below, I am clarifying that the entry must be able to run on either architecture.*
*I believe that there is only one answer that this affects, and that answer has clearly indicated that this is the case.*
[Answer]
# Python, 33 bytes
```
import sys
exit(sys.byteorder[0])
```
`sys.byteorder` is either `'little'` or `'big'` (and for those of you who will read this sentence without looking at the code, `[0]` means take the first character).
[Answer]
# C, 26 bytes
```
a=66<<24|76;f(){puts(&a);}
```
Assumes 32-bit `int` and ASCII characters. Tested on amd64 (little-endian) and mips (big-endian).
# GCC, 23 bytes
```
00000000: 613d 2742 0000 4c27 3b66 2829 7b70 7574 a='B..L';f(){put
00000010: 7328 2661 293b 7d s(&a);}
```
Suggested by feersum. The value of multi-character constants is implementation-dependent, but this seems to work in GCC. Tested on the same architectures.
[Answer]
# MATLAB / Octave, 24 bytes
```
[~,~,e]=computer;disp(e)
```
The [`computer`](http://es.mathworks.com/help/matlab/ref/computer.html) function gives information about, well, the computer it's running on. The third output is endianness: `L` or `B` for little- or big-endian respectively.
[Try it on Ideone](http://ideone.com/FpfrEb).
[Answer]
# JavaScript ES6, 50 bytes
```
_=>"BL"[new Int8Array(Int16Array.of(1).buffer)[0]]
```
I don’t know who decided it was a good idea for [TypedArray](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) objects to expose the native endianness of the interpreter, but here we are.
[Answer]
# C, ~~36~~ 35 bytes
**1 byte thanks to @algmyr and @owacoder.**
```
~~main(a){printf(\*(char\*)&a?"L":"B");}~~
main(a){putchar(66+10**(char*)&a);}
main(a){putchar("BL"[*(char*)&a]);}
```
* Version 1: [Ideone it!](http://ideone.com/uWicng)
* Version 2: [Ideone it!](http://ideone.com/OjpPrP)
* Version 3: [Ideone it!](http://ideone.com/DzmxIa)
Credits [here](https://stackoverflow.com/a/4181991/6211883).
Untested since I don't have a big-endian machine.
[Answer]
### Mathematica, 22
```
{B,L}[[$ByteOrdering]]
```
This probably breaks some rule about not using a built-in function but I'm not really interested in rube goldberging an alternative.
[Answer]
# C, 27
One byte longer, but here it is anyway:
```
f(){putchar(htons(19522));}
```
[Answer]
# PowerPC machine code - 20 bytes
PowerPC is bi-endian (the endianness can be set up at startup), so this code should conform to the challenge request of being able to run both on BE and LE machines. This is a function that *returns*1 `'L'` or `'B'` depending on the endianness currently set.
As a function, AFAICT it conforms the SVR4 PowerPC ABI (used by Linux on ppc32), the PowerOpen ABI (used e.g. by AIX) and the OS X ABI. In particular, it relies just on the fact that GPR 0 is a volatile scratch register, and GPR 3 is used to return "small" values.
```
00000000 <get_endian>:
0: 7c 00 00 a6 mfmsr r0
4: 54 03 0f fe rlwinm r3,r0,1,31,31
8: 1c 63 00 0a mulli r3,r3,10
c: 38 63 00 42 addi r3,r3,66
10: 4e 80 00 20 blr
```
Now, it goes like this:
* the [MSR](https://en.wikipedia.org/wiki/Machine_state_register) is read into GP register 0; the MSR contains at bit 31 the endianness settings (0 = big endian; 1 = little endian);
* `rlwinm` extracts just that bit: it takes the value in GPR0, **r**otates **l**eft by 1 place (so that now is in position 0) and **m**asks it with 1 (the mask generated by those 31,312); the result is put into GP register 3;
* multiply the result by 10 and sum 66 (`'B'`) (10 is the difference between `'L'` and `'B'`)
* finally, return to the caller
---
### Notes
1. yep, the question does ask to *print*, but it's not clear how I should print stuff in assembly expected to run unmodified on different operating systems. =)
2. for those interested, see the [rlwinm](https://www.ibm.com/support/knowledgecenter/en/ssw_aix_71/com.ibm.aix.alangref/idalangref_rlwinm_rlinm_rtlwrdimm_instrs.htm) documentation; knowing next to nothing about PowerPC, I found this kind of instructions extremely interesting.
**2018 update**: Raymond Chen is publishing a series about the PowerPC architecture, you can find [here](https://blogs.msdn.microsoft.com/oldnewthing/20180810-00/?p=99465) his great post about `rlwinm` & friends.
[Answer]
# Java 8, ~~96, 64~~ 52 bytes
```
()->(""+java.nio.ByteOrder.nativeOrder()).charAt(0);
```
A golf based on [this SO answer](https://stackoverflow.com/a/9431652). All credit goes to @LeakyNun and @AlanTuning. Java keeps the loosing streak.
96 bytes:
```
char e(){return java.nio.ByteOrder.nativeOrder().equals(java.nio.ByteOrder.BIG_ENDIAN)?'b':'l';}
```
64 bytes:
```
char e(){return(""+java.nio.ByteOrder.nativeOrder()).charAt(0);}
```
Untested b/c I don't have access to a big-endian machine.
[Answer]
# Perl, ~~38~~ 36 bytes
```
say+(pack"L",1 eq pack"V",1)?"L":"B"
```
Works by packing a number in the system's default byte order and comparing it to a number packed in little-endian byte order.
[Answer]
# (G)Forth, 24 bytes
```
here $4200004C , c@ emit
```
Assumes that cells are 32 bits (and that your Forth interpreter supports Gforth's [base prefixes](http://www.complang.tuwien.ac.at/forth/gforth/Docs-html/Number-Conversion.html#fnd-2)). It simply stores the number 0x4200004C in memory and then displays the byte at the low end.
[Answer]
# C, 34 bytes
This assumes ASCII character encoding
```
main(a){putchar(66+10**(char*)a);}
```
Call without argument.
Explanation:
On call, `a` will be 1. `*(char*)a` accesses the first byte of `a`, which on little-endian platforms will be 1, on big-endian platforms will be 0.
On big-endian platforms, this code will therefore pass 66 + 10\*0 = 66 to `putchar`. 66 is the ASCII code for `B`. On little-endian platforms, it will pass 66 + 10\*1 = 76, which is the ASCII code for `L`.
[Answer]
# C#, 60 52 bytes
C# is surprisingly competitive in this one.
```
char e=>System.BitConverter.IsLittleEndian?'L':'B';
```
Credits to Groo for the C#6 syntax.
60 bytes:
```
char e(){return System.BitConverter.IsLittleEndian?'L':'B';}
```
[Answer]
# Julia, ~~24~~ 19 bytes
```
()->ntoh(5)>>55+'B'
```
This is an anonymous function that takes no input and returns a `Char`. To call it, assign it to a variable. It assumes that integers are 64-bit.
The `ntoh` function converts the endianness of the value passed to it from network byte order (big endian) to that used by the host computer. On big endian machines, `ntoh` is the identity function since there's no conversion to be done. On little endian machines, the bytes are swapped, so `ntoh(5) == 360287970189639680`. Which is also, perhaps more readably, equal to: `0000010100000000000000000000000000000000000000000000000000000000` in binary.
If we right bit shift the result of `ntoh(5)` by 55, we'll get 0 on big endian machines and 10 on little endian machines. Adding that to the character constant `'B'`, we'll get `'B'` or `'L'` for big or little endian machines, respectively.
Saved 5 bytes thanks to FryAmTheEggman and Dennis!
[Answer]
# PHP 5.6, ~~41~~ 31 bytes (thx to isertusernamehere)
`<?=unpack(S,"\x01\x00")[1]-1?B:L;`
# PHP 7, 41 bytes
`echo unpack('S',"\x01\x00")[1]-1?'B':'L';`
Idea stolen from: <https://stackoverflow.com/a/24785578/2496717>
[Answer]
## Common Lisp, 27 bytes
*Tested on SBCL and ECL. For a portable approach, one should use [trivial-features](https://github.com/trivial-features/trivial-features/blob/master/SPEC.md).*
```
(lambda()'L #+big-endian'B)
```
The `#+` notation is a [read-time condition](http://clhs.lisp.se/Body/01_ebaa.htm), that *reads* the next form only if the conditional expression evaluates to true. Here the condition is the whole `#+big-endian` text which means that the test is satisfied if the `:big-endian` keyword belongs to the [`*FEATURES*`](http://clhs.lisp.se/Body/v_featur.htm) list (a list which contains among other things platform-specific information). The following expression is `'B`, which is either read or skipped according to the outcome of the test.
If your platform is big-endian and you write the above form in the REPL, it is exactly as if you wrote the following:
```
CL-USER>(lambda()'L 'B)
```
(NB.`CL-USER>` is the prompt)
A function's body is an implicit [`PROGN`](http://clhs.lisp.se/Body/s_progn.htm), meaning that only the evaluation of the last expression is returned. So the above actually returns symbol ̀`B`.
If however the read-time condition evaluates to false, the form reads as if you wrote:
```
CL-USER>(lambda()'L)
```
... which simply returns symbol `L`.
[Answer]
## ARMv6 and later: 20 bytes machine code
```
0xE10F1000 : MRS r0,CPSR ; read current status register
0xE3110C02 : TST r0,#1<<9 ; set Z flag if bit 9 set
0x03A0004C : MOVEQ r0,#'L' ; return 'L' if Z clear
0x13A00042 : MOVNE r0,#'B' ; return 'B' if Z set
0xEBxxxxxx : BL putchar ; print it (relative branch)
```
Untested, as I don't have a suitable machine to hand. Bit 9 of the CPSR gives the current load/store endianness.
[Answer]
# Perl 5, 21 + 1 = 22 bytes
Run with `perl -E`.
```
say ord pack(S,1)?L:B
```
Tested on amd64 (little-endian) and mips (big-endian).
[Answer]
# R, ~~28~~ 23 bytes
```
substr(.Platform$endian,1,1)
```
`.Platform$endian` returns `big` if run on big endian and `little` if on little. Here, using `substr`, it returns the first letter of the output, so either `b` or `l`.
As `endian` is the only object starting with an `e` contained in object `.Platform` we can reduce it thanks to partial matching to the following 23 bytes code:
```
substr(.Platform$e,1,1)
```
[Answer]
# Clojure, ~~46~~ 44 bytes
```
#(nth(str(java.nio.ByteOrder/nativeOrder))0)
```
This is a function that uses the Java builtin to get the endianness of the machine. Then get the string representation of it which will be either `"LITTLE_ENDIAN"` or `"BIG_ENDIAN"` and take the first character of whichever string is chosen and return that.
Saved 2 bytes thanks to @[cliffroot](https://codegolf.stackexchange.com/users/53197/cliffroot).
[Answer]
# Ruby, ~~31~~30 chars.
```
puts [1].pack("s")>"\01"??L:?B
```
Hmm, must be a better way. Count 5 characters less if the char need not to be output as I think other solutions omit printing. i.e. remove the "puts " part if you don't want anything printed.
[Answer]
# Bash (and other unix shells), 32 (33) bytes
First and second attempt:
```
case `echo|od` in *5*)echo B;;*)echo L;;esac # portable
[[ `echo|od` =~ 5 ]]&&echo B||echo L # non-portable
```
Thanks to Dennis, shorter version:
```
od<<<a|grep -q 5&&echo L||echo B # non-portable
echo|od|grep -q 5&&echo B||echo L # portable
```
The `echo` utility outputs a newline, with hex value `0A`, and no other output. For `<<<a` it is `61 0A`.
The `od` utility, by default, interprets the input as two-byte words, zero-padded if the number of bytes is odd, and converts to octal. This results in the output of echo being interpred as `0A 00`, which is converted to `005000` as big-endian or `000012` in little-endian. `61 0A` becomes `005141` in little-endian and `060412` in big-endian. The full output of od also includes address and size data meaning we cannot use `0`, `1`, or `2` for the test.
The command is well-defined to expose the system's endianness. From [the standard](http://pubs.opengroup.org/onlinepubs/9699919799/utilities/od.html):
>
> The byte order used when interpreting numeric values is implementation-defined, but shall correspond to the order in which a constant of the corresponding type is stored in memory on the system.
>
>
>
## Compatibility notes
I am not certain if putting `echo|od` in backquotes with no double quotes around them [which results in a three-word argument to `case`] is supported on all systems. I am not certain if all systems support shell scripts with no terminating newline. I am mostly certain but not 100% of the behavior of od with adding the padding byte on big-endian systems. If needed, `echo a` can be used for the portable versions. All of the scripts work in bash, ksh, and zsh, and the portable ones work in dash.
[Answer]
## PHP, 16 bytes
```
<?=pack(S,14)^B;
```
This uses two tricks not used in the two existing PHP answers:
1. The value passed to pack() or unpack() can be anything, not just 0 or 1.
2. The bitwise XOR operator (`^`) works on strings, and the result is only as long as the shorter string, avoiding the need for a string indexing or ternary operator.
[Answer]
# Node, 42 bytes
```
n=>require('os').endianness()[0]
```
Pro: there's a builtin. Con: property names are very long
[Answer]
# PowerShell, 44 bytes
```
[char](66+10*[BitConverter]::IsLittleEndian)
```
Character 66 is `B`, and 10 characters later is number 76, `L`. A Boolean value of "true" becomes `1` when cast to a number. `BitConverter` is a standard .NET class.
[Answer]
## Bash, 27 bytes
```
iconv -tucs2<<<䉌|head -c1
```
`䉌` ([U+424C](http://www.unicode.org/cgi-bin/GetUnihanData.pl?codepoint=424C)) is encoded as three UTF-8 bytes: `E4 89 8C`.
It is assumed that `iconv` uses the function from glibc and that a UTF-8 locale is used.
[Answer]
# Racket, ~~35~~ 28 bytes
```
(if(system-big-endian?)'B'L)
```
`'B` or `'L` respectively. Let me know if this is not specific enough :)
[Answer]
# PHP, 22 bytes
```
<?=ord(pack(S,1))?L:B;
```
[Answer]
## Haskell (using GHC-only size-restricted numeric types), 75 bytes
```
import Unsafe.Coerce
import GHC.Int
f="BL"!!fromEnum(unsafeCoerce 1::Int8)
```
(not tested on a big-endian architecture, but it seems like it *ought* to work!)
[Answer]
## K, 15 bytes
```
("bl")@*6h$-8!`
,"l"
```
Explanation;
```
From right to left;
-8!` /serialises the back tick and returns (0x010000000a000000f500)
6h$-8!` /This casts the result to `int which is type 6h(could have used `int$-8!`) - the result is (1 0 0 0 10 0 0 0 245 0i)
*6h$-8!` /* means first, we take the first item which is 1. Since it will be either 1 or 0, we can use it to index (@) into the two element list on the left i.e. ("bl")1 returns "l" and ("bl")0 returns b
```
] |
[Question]
[
Today, we're going to make an ASCII hexagon. You must write a program or function that takes a positive integer *n*, and outputs a hexagon grid of size *n*, made up of asterisks. For example, a hexagon of size 2 looks like this:
```
* *
* * *
* *
```
While a hexagon of size 3 looks like this:
```
* * *
* * * *
* * * * *
* * * *
* * *
```
You may use any of the [default input and output methods](http://meta.codegolf.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods), for example STDIO/STDOUT, function arguments and return values or reading/writing a file.
You may assume that input is always valid, so if it's not a positive integer, your program may do whatever you want. You *do* however have to handle the special case of a size 1 hexagon, which happens to be a single asterisk:
```
*
```
Leading and trailing whitespace is allowed as long as the output is visually the same.
# Examples:
```
1:
*
2:
* *
* * *
* *
3:
* * *
* * * *
* * * * *
* * * *
* * *
4:
* * * *
* * * * *
* * * * * *
* * * * * * *
* * * * * *
* * * * *
* * * *
5:
* * * * *
* * * * * *
* * * * * * *
* * * * * * * *
* * * * * * * * *
* * * * * * * *
* * * * * * *
* * * * * *
* * * * *
6:
* * * * * *
* * * * * * *
* * * * * * * *
* * * * * * * * *
* * * * * * * * * *
* * * * * * * * * * *
* * * * * * * * * *
* * * * * * * * *
* * * * * * * *
* * * * * * *
* * * * * *
12:
* * * * * * * * * * * *
* * * * * * * * * * * * *
* * * * * * * * * * * * * *
* * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * *
* * * * * * * * * * * * * *
* * * * * * * * * * * * *
* * * * * * * * * * * *
```
As usual, this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so [standard loopholes apply](http://meta.codegolf.stackexchange.com/q/1061/31716), and you should try to write the shortest possible program measured in bytes. Of course, some languages are inherently shorter or longer than others, so remember that the goal is not necessarily to have the shortest overall byte count, but to beat submissions in the same or similar languages.
May the best golfer win!
[Answer]
# [Hexagony](https://github.com/m-ender/hexagony) + Bash Coreutils, 0+3+8 = 11 Bytes
Includes +3 for `-g` flag and +8 for `|tr . \*` non-standard invocation (see this [meta post](http://meta.codegolf.stackexchange.com/a/10118/57100))
```
```
Input is given as an argument to Hexagony. When the Hexagony interpreter is called with the `-g N` option it prints a hexagon of `.`s. We then use tr to replace those with `*`s.
[Answer]
## Python 2, 61 bytes
```
i=n=input()
while~-n+i:i-=1;j=abs(i);print' '*j+'* '*(2*n+~j)
```
Prints a trailing space at the end of each line.
Thanks to Erik the Outgolfer for saving a byte.
[Answer]
# [Hexagony](https://github.com/m-ender/hexagony), ~~91~~ ~~87~~ 86 bytes
```
?{2'*=&~}=&}='P0</0P}|@..;>;'.\};0Q/..\&(<>"-_"&}=\?_&\/8.=-\<><;{M/.(.(/.-{><.{&'/_.\
```
[Try it online!](https://tio.run/##DcqxCoMwEAbgd3G4BCH/hQ5SyCX6AoLdD0KHUiddW2J89eg3f@vn9/7u27@1sTxMH@mskWo0ixf2Sz0mIKRgoDX4FwNKVlLncncnHTMpPxGdSpJQZoaFZbiSBIUMZ2hrwwU "Hexagony – Try It Online")
Finally did it.
Initially (before realizing how expensive loops are) I expect this may be able to fit in side length 5, but now it's hard enough to fit it into side length 6.
To get this I actually have to modify the linear code a little. In fact, writing this makes me realize a way to golf the linear code down by ~~1~~ 2 byte.
[Answer]
# JavaScript (ES6), 77 ~~81 84~~
@Upvoters: don't miss the answer by @ETHproductions, that is 76 bytes
*Edit* Revised after change in spec, trailing space allowed
Just for the hat ... hey! No hat?
```
f=(n,b='* '.repeat(n+n-1),o=b)=>--n?f(n,b=` ${b}`.slice(0,-2),b+`
${o}
`+b):o
```
**Test**
```
f=(n,b='* '.repeat(n+n-1),o=b)=>--n?f(n,b=` ${b}`.slice(0,-2),b+`
${o}
`+b):o
function update()
{
O.textContent=f(+I.value)
}
update()
```
```
<input id=I type=number min=1 value=3 oninput='update()'>
<pre id=O></pre>
```
[Answer]
# JavaScript (ES6), ~~77~~ 76 bytes
```
g=(n,s=`
*`+' *'.repeat(n*2-2),c=s,q=c.replace('*',''))=>--n?g(n,q+s+q,q):s
```
I told myself I wouldn't sleep until I had set a new ES6 record without looking at the other answers, so here it is...
### Test snippet
```
g=(n,s=`
*`+' *'.repeat(n*2-2),c=s,q=c.replace('*',''))=>--n?g(n,q+s+q,q):s
for(var i = 1; i < 7; i++) console.log(g(i)) // joe
```
[Answer]
# C, ~~91~~ ~~89~~ ~~80~~ 74 bytes
```
w,y;f(s){for(y=-s;++y<s;)for(w=printf("\n%*s",y,"");++w<s*printf(" *"););}
```
I pretty much tweaked around to get the correct formulas, then mashed it all together.
Call `f` with the number *n*, and it will print the hexagon to stdout.
**Ungolfed and explained (80-byte version):**
```
w,y;
f(s) {
// y iterates over [-s + 1 ; s - 1] (the number of rows)
for(y = -s; ++y < s;)
// w iterates over [abs(y) + 2 ; s * 2 - 1] (the number of stars on the row)
for(
// This prints a backspace character (ASCII 8)
// padded with abs(y) + 2 spaces, effectively
// printing abs(y) spaces to offset the row.
// Also initializes w with abs(y) + 2.
printf("\n%*c", w = abs(y) + 2, 8);
// This is the for's condition. Makes use
// of the 2 returned by printf, since we coïncidentally
// need to double the upper bound for w.
w++ < s * printf("* ");
// Empty for increment
)
; // Empty for body
}
```
[See it live on Coliru](http://coliru.stacked-crooked.com/a/f65c2157dcac791b)
**Notes:**
* `printf` can handle negative padding, which results in a left-aligned character with the padding on the right. Thus I tried something to the effect of `w = printf("%*c*", y, ' ')` so it would take care of the absolute value, and I could retrieve it from its return value. Unfortunately, both zero and one padding widths print the character on its own, so the three center lines were identical.
**Update:** [Jasen](https://codegolf.stackexchange.com/users/34589/jasen) has found a way to do exactly this by printing an empty string instead of a character -- 6 bytes shaved off!
* The backspace character is handled incorrectly by Coliru -- executing this code on a local terminal does remove the leading space on each line.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~14~~ 13 bytes
Code:
```
F¹N+„ *×})û.c
```
Explanation:
```
F } # Input times do (N = iteration number)
¹N+ # Calculate input + N
„ *× # Multiply by the string " *"
) # Wrap everything into an array
û # Palindromize the array
.c # Centralize
```
Uses the **CP-1252** encoding. [Try it online!](https://tio.run/nexus/05ab1e#@@92aKef9qOGeQpah6fXah7erZf8/78xAA "05AB1E – TIO Nexus")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 24 bytes
```
R+’µạṀx@€⁶żx@K¥€”*$F€ŒḄY
```
[Try it online!](https://tio.run/nexus/jelly#@x@k/ahh5qGtD3ctfLizocLhUdOaR43bju6pcPA@tBTEaZirpeIGZByd9HBHS@T///8NjQA "Jelly – TIO Nexus")
Jelly is ashamed of the fact that it does not have a centralization atom, so it's beaten by 05AB1E and V. By 11 and 7 bytes respectively!
If you find any way to golf this, please comment. Any help is appreciated.
**Explanation**:
```
R+’µạṀx@€⁶żx@K¥€”*$F€ŒḄY Main link. Arguments: z.
R+’ The sizes of the hexagon's rows. (implicit argument)
µ Start a new monadic chain with the above argument.
ȧṀx@€⁶ The spaces you must prepend to each row. (implicit argument)
x@K¥€”*$ The stars (points) of each row, space-joined, as a single link. (implicit argument)
ż F€ Conjoin and merge the leading spaces with the stars appropriately.
ŒḄ Create the second half of the hexagon without the middle row.
Y Join the rows with newlines. This makes the shape look like a hexagon.
```
Bonus: To find how many stars are there in a hexagon, use this:
```
Ḷ×6S‘
```
[Answer]
# Octave , ~~62~~ 58 bytes
```
@(n)' *'(dilate(impad(1,2*--n,n),[k='01010'-48;~k;k],n)+1)
```
Previous answer:
```
@(n)' *'(dilate(impad(1,2*(m=n-1),m),[k='01010'-48;~k;k],m)+1)
```
that can be called as
```
(@(n)' *'(dilate(impad(1,2*(m=n-1),m),[k='01010'-48;~k;k],m)+1))(5)
```
Try (paste) it on [Octave Online](https://octave-online.net/)
For example the base image for `n=5` is
```
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
```
that can be created with
```
impad(1,2*(n-1),n-1)
```
The `dilation morphological operator` applied 4 times on the image using the following neighbor mask:
```
0 1 0 1 0
1 0 1 0 1
0 1 0 1 0
```
that can be created with `[k='01010'-48;~k;k]`
result of dilation:
```
0 0 0 0 1 0 1 0 1 0 1 0 1 0 0 0 0
0 0 0 1 0 1 0 1 0 1 0 1 0 1 0 0 0
0 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 0
0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0
1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1
0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0
0 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 0
0 0 0 1 0 1 0 1 0 1 0 1 0 1 0 0 0
0 0 0 0 1 0 1 0 1 0 1 0 1 0 0 0 0
```
then replace 0 and 1 with ' ' and '\*' respectively
```
* * * * *
* * * * * *
* * * * * * *
* * * * * * * *
* * * * * * * * *
* * * * * * * *
* * * * * * *
* * * * * *
* * * * *
```
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~40~~ ~~36~~ ~~35~~ ~~33~~ ~~27~~ 25 bytes
```
(⍉⊖⍪1↓⊢)⍣2∘↑⍳↓¨∘⊂'* '⍴⍨+⍨
```
Assumes `⎕IO←0`, i.e. zero-based indexing. The output contains one leading and one trailing spaces on each line.
Many thanks to @FrownyFrog and @ngn for lots of golfing.
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkGCkDwqHeugmdeSmpFZl76/zSgqMaj3s5HXdMe9a4yfNQ2@VHXIs1HvYuNHnXMeNQ28VHvZqDYoRUgXleTupaC@qPeLY96V2gD8f//ms7@AZEKKWl5xVwpmcUFOYmVxQpph1YYAmU3mwIA "APL (Dyalog Unicode) – Try It Online")
### How it works
```
(⍉⊖⍪1↓⊢)⍣2∘↑⍳↓¨∘⊂'* '⍴⍨+⍨ ⍝ Main function train
'* '⍴⍨+⍨ ⍝ Repeat '* ' up to length 2×⍵
⍳↓¨∘⊂ ⍝ Generate lower-right corner of the hexagon
∘↑ ⍝ Convert to matrix
(⍉⊖⍪1↓⊢) ⍝ Palindromize vertically and transpose
⍣2 ⍝ ... twice
```
[Answer]
## postgresql9.6, 290 bytes
```
do language plpgsql $$ declare s constant smallint:=4;declare n smallint;declare a constant int[]:=array(select generate_series(1,s));begin foreach n in array a||array(select unnest(a)t order by t desc offset 1)loop raise info'%',concat(repeat(' ',s-n),repeat(' *',s+(n-1)));end loop;end;$$
```
formatted sql is here:
```
do language plpgsql $$
declare s constant smallint := 4;
declare n smallint;
declare a constant int[] := array(select generate_series(1, s));
begin
foreach n in array a || array(select unnest(a)t order by t desc offset 1) loop
raise info '%', concat(repeat(' ', s - n), repeat(' *', s + (n - 1)));
end loop;
end;
$$;
```
output:
```
INFO: * * * *
INFO: * * * * *
INFO: * * * * * *
INFO: * * * * * * *
INFO: * * * * * *
INFO: * * * * *
INFO: * * * *
```
[Answer]
# [V](https://github.com/DJMcMayhem/V), 17 bytes
```
é*Àñ>{MÄpXA *Î.
```
[Try it online!](https://tio.run/nexus/v#@394pdbhhkNrD2@0q/Y93FIQ4aigJX24T@////9mAA "V – TIO Nexus")
As usual, here is a hexdump, since this contains unprintable characters:
```
00000000: e92a c0ad f13e 7b4d c470 5841 202a 1bce .*...>{M.pXA *..
00000010: 2e .
```
[Answer]
# JavaScript (ES6), 83 81 bytes
This is my first (code golf) answer. I hope I formatted everything correctly.
```
a=>{for(b=c=2*a-1;c;)console.log(" ".repeat(d=Math.abs(a-c--))+"* ".repeat(b-d))}
```
Unlike the 2 current ES6 answers, I'm not recursively calling a function and I am using the console for output.
[Answer]
## Haskell, ~~99~~ ~~97~~ 79 bytes
```
h n=mapM_(putStrLn.(\k->([k..n]>>" ")++([2..n+k]>>"* ")))([1..n-1]++[n,n-1..1])
```
Explanation:
This program is based on the observation that each line of a n-Hexagon contains (n-k) spaces followed by (n+k-1) asterisks, for some k dependent on the line number.
```
h n= h is a function of type Int -> IO ()
mapM_ mapM_ executes a function returning
monadic actions on all objects
in a list, in order. Then it executes
these actions, in order. For this code, it
transforms each value in the list into a
monadic action that prints
the corresponding line
( the function consists of two components
putStrLn the second part is printing the result of
the first part to stdout
. concatenating both components
(\k-> the first parts first prints (n-k) spaces
and then (n+k-1) asterisks
([k..n]>>" ") create the list of the integers from
k to n (That is actually one more entry
than necessary, but just results in a
leading whitespace per line, while
saving 2 bytes compared to [1..n-k]).
Then create a new list where
each element of that first list is
replaced with the string " " and
concatenate that result into one string
++ concatenate both lists
([2..n+k]>>"* ") create the list of the integers
from 2 to n+k (of length n+k-1).
Then create a new list where each
element of that first list is replaced
with the string "* " and concatenate
that result into one big string
)
)
([1..n-1]++[n,n-1..1]) the list simply goes from 1 to n and
back, supplying the k
```
Edit: Switched to mapM\_. I was not aware that was available without using import
[Answer]
# [Canvas](https://github.com/dzaima/Canvas), 9 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md)
```
╷⁸+* ×]/─
```
[Try it here!](https://dzaima.github.io/Canvas/?u=JXUyNTc3JXUyMDc4JXVGRjBCKiUyMCVENyV1RkYzRCV1RkYwRiV1MjUwMA__,i=Mw__,v=3)
Beating the built-in :D
Explanation:
```
{╷⁸+* ×]/─ implicit "{"
{ ] map over 1..input
╷ decrement: 0..input-1
⁸+ add the input: input..(input*2-1)
* × repeat "* " that many times
/ diagonalify that - pad each line with 1 less space than the previous
─ palindromize vertically
```
~~No idea why there's the huge padding, but it's allowed & I'm fixing that soon™.~~ fixed? Hope I didn't break stuff
[Answer]
# [Python 2](https://docs.python.org/2/), ~~100~~ ~~97~~ ~~89~~ ~~88~~ ~~87~~ ~~81~~ 79 bytes
-1 from @Flp.Tkc
-6 again from @Flp
-2 with thanks to @nedla2004. I was trying to find how to get rid of the second slice but didn't think of that one :)
```
i=input()
a=[" "*(i-x)+"* "*(i+x)for x in range(i)]
print'\n'.join(a+a[-2::-1])
```
[Try it online!](https://tio.run/nexus/python2#@59pm5lXUFqiocmVaButpKCkpZGpW6GpraQFZmpXaKblFylUKGTmKRQl5qWnamRqxnIVFGXmlajH5KnrZeVn5mkkaidG6xpZWekaxmr@/28KAA "Python 2 – TIO Nexus")
Creates an array for the top half then adds the reversed array minus the middle line then prints. Prints exactly "as is" apart from `1` which prints with a leading space (I guess that is allowed as a `*` is visually the same as a `*` with or without a leading space).
[Answer]
## JavaScript (ES6), 83 bytes
```
f=
n=>[...Array(n+--n)].map((_,i,a)=>a.map((_,j)=>j<n-i|j<i-n?``:`*`).join` `).join`
`
```
```
<input type=number min=1 oninput=o.textContent=f(+this.value)><pre id=o>
```
[Answer]
## Batch, 161 bytes
```
@echo off
set s=*
set l=for /l %%i in (2,1,%1)do call
%l%set s= %%s%% *
%l%echo %%s%%&call set s=%%s:~1%% *
echo %s%
%l%set s= %%s:~0,-2%%&call echo %%s%%
```
Note: Trailing space on line 2. Ungolfed:
```
@echo off
set s=*
rem build up the leading spaces and stars for the first row
for /l %%i in (2,1,%1) do call :s
rem output the top half of the hexagon
for /l %%i in (2,1,%1) do call :t
rem middle (or only) row
echo %s%
rem output the bottom half of the hexagon
for /l %%i in (2,1,%1) do call :b
exit/b
:s
set s= %s% *
exit/b
:t
echo %s%
rem for the top half remove a space and add a star to each row
set s=%s:~1% *
exit/b
:b
rem for the bottom half add a space and remove a star from each row
set s= %s:~0,-2%
echo %s%
exit/b
```
[Answer]
# [Perl 6](http://perl6.org/), 49 bytes
```
->\n{say " "x n*2-1-$_~"*"xx$_ for n...n*2-1...n}
```
[Try it online!](https://tio.run/nexus/perl6#y61UUEtTsP2vaxeTV12cWKmgpKBUoZCnZaRrqKsSX6ekpVRRoRKvkJZfpJCnp6cHlgDRtf9BQkCmiYKunYJKnkI1lwIQgE1Qsgaz04DC1ly1/wE "Perl 6 – TIO Nexus")
### How it works
```
->\n{ } # Lambda accepting edge size (e.g. 3)
for n...n*2-1...n # For each row-size (e.g. 3,4,5,4,3):
"*"xx$_ # List of stars (e.g. "*","*","*")
" "x n*2-1-$_ # Spaces to prepend (e.g. " ")
~ # Concatenate. (e.g. " * * *")
say # Print
```
[Answer]
# Powershell, ~~91~~ ~~89~~ ~~78~~ ~~68~~ ~~63~~ ~~52~~ 48 bytes
```
param($n)$n..1+1..$n|gu|%{' '*$_+'* '*(2*$n-$_)}
```
Test script:
```
$script = {
param($n)$n..1+1..$n|gu|%{' '*$_+'* '*(2*$n-$_)}
}
12,6,5,4,3,2,1 |%{
$_
. $script $_
}
```
Output (extra leading space):
```
12
* * * * * * * * * * * *
* * * * * * * * * * * * *
* * * * * * * * * * * * * *
* * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * *
* * * * * * * * * * * * * *
* * * * * * * * * * * * *
* * * * * * * * * * * *
6
* * * * * *
* * * * * * *
* * * * * * * *
* * * * * * * * *
* * * * * * * * * *
* * * * * * * * * * *
* * * * * * * * * *
* * * * * * * * *
* * * * * * * *
* * * * * * *
* * * * * *
5
* * * * *
* * * * * *
* * * * * * *
* * * * * * * *
* * * * * * * * *
* * * * * * * *
* * * * * * *
* * * * * *
* * * * *
4
* * * *
* * * * *
* * * * * *
* * * * * * *
* * * * * *
* * * * *
* * * *
3
* * *
* * * *
* * * * *
* * * *
* * *
2
* *
* * *
* *
1
*
```
## Explanation:
```
param($n) # define script parameter
$n..1+ # int range from n to 1 step -1; append
1..$n| # int range from 1 to n
gu| # alias for Get-unique eliminates equal neighbors - here is 1,1 -> 1
%{ # for each int from [n, n-1, n-2, ... 2, 1, 2, ... n-2, n-1, n]
' '*$_+ # string (' ' have repeated $_ times) append
'* '*(2*$n-$_) # string ('* ' have repeated 2*n-$_ times)
}
```
[Answer]
# Hexagony (linear), ~~128~~ ~~127~~ 126 bytes
Note that this is **not** Hexagony, just a (meta-)language Timwi supported in Esoteric IDE, so this is **not** eligible for the bounty.
However this can be converted to a Hexagony solution ~~(and I think it will be smaller than this solution) I may do that later. It takes more effort~~ [I did it over here](https://codegolf.stackexchange.com/a/167529/69850).
The initial `❢` takes 3 bytes (`e2 9d a2`). Each newline takes 1 byte (`0a`).
```
❢?{2'*=(
A
if > 0
"-"&}=&~}=&}=?&
B
if > 0
}P0;'(
goto B
&{&'-{=-(
C
if > 0
'P0;Q0;}(
goto C
{M8;{(
goto A
@
```
No Try it online!. This **only** works in Esoteric IDE.
Annotated code:
```
❢? # read input n
[n]
{2'*=( # x = 2n-1
[x]
A
if > 0 # loop (x) from 2n-1 to 1
"- # a = x - n
[a]
"&}=&~}=& # a = abs(a). Let K be this amount
}=?&
B
if > 0 # print ' ' (a) times
}P0;'(
goto B
& # current cell = a (= K)
{& # a = n if K>0 else x
# Note that K=abs(x-n). So if K==0 then x==n.
# Therefore after this step a is always equal to n.
'-{=- # compute n-(K-n) = 2n+K
( # decrement, get 2n+K-1
C
if > 0 # print ' *' this many times
'P0;Q0;}(
goto C
{M8;{ # print a newline, goto x
( # x -= 1
goto A
@
```
[Answer]
# PHP, ~~83~~ 79 bytes
```
for($p=str_pad;++$y<2*$n=$argn;)echo$p($p("
",1+$k=abs($n-$y)),4*$n-$k-2,"* ");
```
Run as pipe with `-nR` or [try it online](http://sandbox.onlinephpfunctions.com/code/60c02a7d60ff5f72ab3bef82a3b1ab16549973ae).
---
This is close to [Kodos´ answer](https://codegolf.stackexchange.com/a/107300/55735); but `str_pad` is shorter than `str_repeat` even when golfed.
And the `++` in the loop head saves some more.
[Answer]
# Ruby, 54 bytes
```
->n{(1-n..n-1).map{|j|i=j.abs;' '*i+'* '*(n*2+~i)}*$/}
```
lambda function takes n as argument and returns a string separated by newlines. (`$/` is a variable containing the default line separator.)
**in test program**
```
f=->n{(1-n..n-1).map{|j|i=j.abs;' '*i+'* '*(n*2+~i)}*$/}
puts f[gets.to_i]
```
[Answer]
# Charly, 125 bytes
```
let i="".promptn()let o=0let j=0let w=write loop{w(" "*(i-1-o),"* "*(i+o))w("
")if j<i-1{o+=1}else{o-=1}if o<0{break}j+=1}
```
Charly GitHub Page: <https://github.com/KCreate/charly-lang>
[Answer]
# SmileBASIC, 74 bytes
```
FOR I=0TO N-1P
NEXT
FOR I=N-2TO.STEP-1P
NEXT
DEF P?" "*(N-I);"* "*(N+I)END
```
Adds a leading and trailing space.
These "hexagons" look horrible when the characters have the same width and height...
[Answer]
# racket/scheme
```
(define (f n)
(define (s t n)
(if (= n 0) t (s (~a t "* ") (- n 1))))
(define (h t p a i)
(if (= i 0)
(display t)
(let ((x (~a t (make-string p #\space) (s "" a) "\n"))
(q (if (> i n) (- p 1) (+ p 1)))
(b (if (> i n) (+ a 1) (- a 1))))
(h x q b (- i 1)))))
(h "" (- n 1) n (- (* 2 n) 1)))
```
## testing:
```
(f 1)
*
(f 4)
* * * *
* * * * *
* * * * * *
* * * * * * *
* * * * * *
* * * * *
* * * *
```
[Answer]
# Python 2, 111 bytes
```
n=input()
l=range(n,2*n-1)
S=l+[2*n-1]+l[::-1]
W=range(1,n)
for w in W[::-1]+[0]+W:print" "*w+"* "*S[0];S=S[1:]
```
A boring, straightforward implementation (and a full program). Outputs a trailing whitespace at each line.
# Testcases:
```
1:
*
2:
* *
* * *
* *
3:
* * *
* * * *
* * * * *
* * * *
* * *
4:
* * * *
* * * * *
* * * * * *
* * * * * * *
* * * * * *
* * * * *
* * * *
```
[Answer]
# Javascript (ES6), 143 bytes
It's finally Christmas break (merry Christmas!), so I have some time for golfing.
And boy has it been a while - hence the large byte count.
Here goes:
```
c=[];a=a=>{for(i=0;i<a;i++){c.push(" ".repeat(a-i-1)+"* ".repeat(i+a-1)+"*")}for(j=c.length-2;j>-1;j--)c.push(c[j]);return a==1?"*":c.join`\n`}
console.log(a(3));
```
[Answer]
# Japt `-R`, ~~11~~ 10 bytes
```
Æ°çSi*Ãû ê
```
[Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=xrDnU2kqw/sg6g==&input=OAotUg==) (or [use TIO](https://tio.run/##AT4Awf9qYXB0///DhlXCsMOnU2kqw4PDuyDDqv9SaVXCt/9bMSwyLDMsNCw1LDYsNyw4LDksMTAsMTEsMTJdCi1tUg) to run multiple tests)
---
## Explanation
```
:Implicit input of integer U
Æ :Map the range [0,U)
° : Postfix increment U
ç : Repeat
S : Space
i* : Prepend asterisk
à :End map
û :Centre pad each string with spaces to the length of the longest string
ê :Palindromise
:Implicitly join with newlines and output
```
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal) `C`, 8 bytes
```
ʁ+×*vṄøm
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=C&code=%CA%81%2B%C3%97*v%E1%B9%84%C3%B8m&inputs=20&header=&footer=)
```
ʁ # Range(n) (0...n-1)
+ # Plus n (n...2n-1)
×* # That many asterisks
vṄ # Join each by spaces
øm # Palindromise
# (C flag) Center and join by newlines
```
] |
[Question]
[
Write a function, `f`, that takes in a positive integer and returns a function.
The new function returned should be identical to `f`. However, when the "termination call" happens, `f` should instead return the sum of all integers passed.
For example, `g=f(4)` (if `f` is the first function) should set `g` to another function. `h=g(3)` will do the same. However, when you call `h` with no arguments (see below for details), it should output 7, as that is the sum of the previous function arguments. Put another way, `f(3)(4)() == 7`.
Do note this is not the same as `f(3,4)()`.
"Termination call" is one of the following options (your choice):
* call w/o arguments
* null as argument
* any non-positive value
Arbitrary amount of function calls should be supported, there is no predefined limit.
It's guaranteed that total sum will not be bigger than 1'000.
We can assume that there is at least one call is made prior to "termination call".
Your code should not use static, per-program variables, so it should be possible to run the experiment multiple times in the same runtime and observe exactly the same behavior.
Examples:
```
f(1)() == 1
f(4)(2)(7)() == 13
f(4)(2)(7)(5)(2)() == 20
```
[Answer]
## JavaScript (ES6), 18 bytes
```
f=n=>m=>m?f(m+n):n
```
Pass a falsy value to retrieve the sum. Zeros could be allowed for a cost of 2 bytes.
[Try it online](https://tio.run/nexus/javascript-babel-node#@59mm2drlwtE9mkaudp5mlZ5/5Pz84rzc1L1cvLTNRTSNAw1NYw0NYw1NXRNNDU0FTT/AwA)
**Ungolfed:**
```
f = function(n) {
return function(m) {
if (m) {
return f(m+n);
} else {
return n;
}
}
}
```
[Answer]
## [Haskell](https://www.haskell.org/) (GHC), 118 bytes
This is 98 bytes for the code and 20 bytes for the GHC compiler flag `-XFlexibleInstances`, which enables a type system extension.
```
class F a where f::Int->a
instance F(()->Int)where f n()=n
instance F a=>F(Int->a)where f=(f.).(+)
```
This defines a "function" `f`, which can be called with an arbitrary number of integers followed by the unit `()`, after which it returns an integer.
Type annotations are required.
[Try it online!](https://tio.run/nexus/haskell#TY3LCsIwFET3fsVAN/ci6UJxE0igC1MK4s4PiCXBQL1IU1AQv72@Irg6w3CGuasKu2bfHpp2CzeEWzoOoZM8eelDRqUecz/4nOHgcT2FMSBq3cmkrF@k4sERsbKvlosCITbyJ8Ab6@i7@0mGYs01LXk@@yQwuIxJJlCk9eeCaVO4KmRojXeanw "Haskell – TIO Nexus")
## Explanation
Forcing Haskell's strict type system to allow this requires some magic, namely, enabling the GHC extension for flexible typeclass instances.
How this works is that `f` is a parametrically polymorphic function restricted by a type class constraint: its type is `F a => Int -> a`.
This means that `f` takes an integer and returns a value of type `a`, for any type `a` that belongs to the typeclass `F`.
`F` is just the name of the typeclass that provides the function `f`; it's declared on the first line.
The next two lines are two instances of `F` for different types `a`.
The second line states that the type of functions from `()` to integers belongs to `F` (where `()` is the unit type whose only member is the value `()`), and the implementation is `f n () = n`; the function returns its first argument.
The last line states that if `a` belongs to `F`, then so does the type of functions from integers to `a`: from a function `f :: Int -> a` we can generate another function `f :: Int -> Int -> a`.
The implementation is `f m n = f (m+n)` (the code uses combinators to make it shorter), where the `f` on the left is the new one, and the `f` on the right is the old one.
This essentially gives `f` a new integer argument, which is added to the next one.
Multiple arguments are summed together like this:
```
f a1 a2 a3 a4 a5 ()
= f (a1 + a2) a3 a4 a5 ()
= f (a1 + a2 + a3) a4 a5 ()
= f (a1 + a2 + a3 + a4) a5 ()
= f (a1 + a2 + a3 + a4 + a5) ()
= a1 + a2 + a3 + a4 + a5
```
The `f` on each line has a different type.
Haskell functions are curried automatically, so if you give `f` only integers, you get a function.
[Answer]
# Python 2, ~~42~~ ~~41~~ 36 bytes
This solution will never have an overflow, since Python supports arbitrary-precision integers. Zero is the "special value".
```
f=lambda n:lambda m:m and f(m+n)or n
```
[**Try it online**](https://tio.run/nexus/python2#@59mm5OYm5SSqJBnBWXkWuUqJOalKKRp5GrnaeYXKeT9LyjKzCsBChhqahgZaWrommpqGBoAsYmmhoHmfwA)
**Ungolfed:**
```
def f(n):
def g(m=''):
return f(m+n)if m<''else n
return g
```
[Answer]
## Mathematica, 25 bytes
```
f[x_]@y_=f[x+y]
f[x_][]=x
```
[Try it online!](https://tio.run/nexus/mathics#@58WXREf61AZbwtkaFfGcoH50bG2Ff8DijLzShQcFNKijWOjTWKjDYEIyIr9DwA "Mathics – TIO Nexus") (Using Mathics.)
It's possible to do three bytes less by porting the JavaScript answer, but I wanted to present a more idiomatic Mathematica solution. The `@` is just a bit of syntactic sugar, which makes the solution equivalent to:
```
f[x_][y_]=f[x+y]
f[x_][]=x
```
So yeah the idea is that in Mathematica you can't just define a function `f[x_]` but you can directly attach a value to a more complicated expression containing `f`, e.g. `f[x_]` being passed another argument. By setting up two definitions for this, we can get the desired behaviour:
* The first definition collapses one `f[x][y]` call into `f[x+y]`, thereby consuming one "call" and adding up the arguments inside. This rule applies until we're left with `f[sum][]`.
* The second definition unpacks this final case by defining the entire thing to evaluate to `sum`.
[Answer]
# C, ~~62~~ 58 bytes, borderline competing
Saved 4 bytes thanks to Kevin! (Still not removing typedef because it's something needed in order to be called.)
```
typedef(*(*B)(_))(_);q;f(x,o,_){x=x?(q+=x,f):(x=q,q=0,x);}
```
The function to call is `f`; you stop calling it and get the result by calling it with a non-positive number like `0`. **[Try a test harness online!](https://tio.run/nexus/c-gcc#lZDRaoNAEEXf/YohpTCr0qgJFNxsJX5HQUp1qdhqtrWwJeTb7YzZBDS@ZFBw5u49c9fhoW7fP3/LCnY/fVl3Tx8v3noN/d@hKiuN/l5gIaRrYY9@Pg6MzH2NTViIowlUs4uzKG1kM35hoUxoVERiirnQ8nQPsWNmp4w0DmsCBpuMUWlHsCvJWZ1doz2brbIZUiobagpgXRgryPr1Vrcojh5QHb7rtte40pjEAumJBCh4LF/bVYi0jN9RY5FVISe@JIYAYhjr4oPzcHZSYxxFArcJkTab58kmPueBK155bRYHl6FGICZQrhuZa5vcjKecBR9H85YdnHhsZhfjCAEt4zuTe/orZiJZT8PwDw)**
So, as far as I can tell, the only way to "curry" functions that have multiple return types is to do one of the following:
1. Cast the result to a function to tell the compiler you wish to call the result again;
2. or create a `union`/`struct` type that has an `int` and function/self-referential subtypes.
I tried doing (2), but it seemed a bit against the spirit of the question and, quite frankly, nigh undoable. Thus, in keeping with the spirit of the challenge, I have opted for option (1). This requires casting each returned function into a function, that it may be used.
This "currying" syntax looks a bit odd, but is quite similar. To emulate `f(21)(1)`, one would have to write `((B)((B)f(21))(1))(0)`. I defined the `B` type to be a function that takes an integer and returns a pointer to a function that takes an integer. Expanded, this looks like:
```
( (B)( (B) f(21) )(1) )(0)
// f(21) - call f with 21
// (B) - cast to B, a function pointer
// ( )(1) - call with 1
// (B) - cast to a function pointer
// ( )(0) - call with 0
```
[Answer]
# C++, 72 bytes
```
#define O(P)operator()(P){return{P+a};}int
struct F{F O(int(m))O()a;}f;
```
This defines a type `F` which acts as the requested function, and a variable `f` of that type to invoke. It's valid as of C++11 and works with online versions of GCC, clang, icc and VC++.
Usage:
```
int main() {
return f(1)(2)(3)(); // returns 6
}
```
Explanation:
After preprocessing and reformatting, it looks like:
```
struct F {
F operator()(int(m)) { return{int(m)+a}; }
int operator()() { return {+a}; }
int a;
} f;
```
This would normally be written:
```
struct F {
F operator()(int m) { return {m+a}; }
int operator()() { return a; }
int a;
} f;
```
`return a;` and `return {+a};` do the same thing, as unary `+` doesn't change the value, and redundant braces around the return value are allowed. `int m` and `int(m)` do the same thing, as redundant parentheses around a variable name are allowed, including function parameters. `return {m+a};` and `return {int(m)+a};` do the same thing, as a cast of `m` from `int` to `int` does not change its value. These changes get the two `operator()` overloads closer in syntax, allowing a single macro definition to be invoked twice. Picking the right order for the three members allows the first word of the next line (`int`) to be included in the macro definition as well.
[Answer]
# Ruby, 23 bytes
```
f=->n{->m{m ?f[n+m]:n}}
```
Usage:
```
f[1][2][3][nil]
=> 6
```
[Answer]
# C, ~~104~~ 96 bytes
```
#define a(i)s(i)|b
#define b(i)u(i)|c
#define c(i)u(i)|b
b,c,d;s(i){b=c=i;i=d;}u(i){c=b+=i;i=d;}
```
Uses the method from the link that @JulianWolf shared. Last argument must be 0.
[Try it online!](https://tio.run/nexus/c-gcc#PYuxCsMwDER3f0VICUjUQ9vQyfhjLCkBDTWlSScn355YBXc4uPeOOy4yzZqnLoHiUrORa4oqfk3xX3FT5Mizl2CXQpGjBo0SdhsLR7o2cbySZsDy/mheZ@gH6QbpvUvwRBgRHgg3NLz/@mjosP5O "C (gcc) – TIO Nexus")
[Answer]
# Math.JS, 38 Bytes
```
f(x)=i(x,0)
i(x,y)=x<0?y:j(z)=i(z,y+x)
```
Call it with `f(number_a)(number_b)(...)(negative_number)`
If we're allowed to specify the initial call, 12 bytes (`f(x)=i(x,0)\n`) can be dropped, and it can be called with `i(number_one,0)(number_two)(...)(negative_number)`
[Try it!](http://a-ta.co/math/f(x)%3Di(x%2C0)%0Ai(x%2Cy)%3Dx%3C0%3Fy%3Aj(z)%3Di(z%2Cy%2Bx)%0A%0Aprint(%0A%20%20%20%20f(3)(4)(5)(-1)%0A)%0A)
## Explanation
$$
\begin{align}
f(x) & = i(x, 0) \\
i(x, y) & = \begin{cases}
y, & \text{if } x < 0 \\
j(z) = i(z, y+x), & \text{otherwise}
\end{cases}
\end{align}
$$
As shown above, `f(x)` simply calls `i(x,0)`, then, `i(x,y)` returns the value of `y` if `x` is less than 0, or the function `j(z)=i(z,x+y)` otherwise.
[Answer]
## C, ~~232~~ 206 bytes
```
#include<string.h>
#include<stdlib.h>
#define f(X)s(""#X)?0:g
#define g(X)u(""#X)?0:h
#define h(X)u(""#X)?0:g
g=0,h=0;s(char*s){g=h=atoi(s);return 0;}u(char*s){char*a=strlen(s)?s:"0";g=h+=atoi(a);return 0;}
```
This can probably be golfed significantly, but should serve as a proof of concept that C can be used, without any language extensions\*, to solve this problem by calling without arguments rather than with a magic value.
\* @hvd has noted that, while this works out of the box using gcc, some of the behavior is not defined in the C standard, meaning that this may not be portable. Use at your own risk!
Ungolfed:
```
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define f(X) start("" #X) ? 0 : f0
#define f0(X) update("" #X) ? 0 : f1
#define f1(X) update("" #X) ? 0 : f0
long f0 = 0;
long f1 = 0;
int start(const char *s) {
f0 = f1 = strtol(s, NULL, 10);
return 0;
}
int update(const char *s) {
const char *a = strlen(s) ? s : "0";
f0 = f1 += strtol(a, NULL, 10);
return 0;
}
int main() {
printf("f(1)() -> %ld\n", f(1)());
printf("f(1)(2)(0)(3)() -> %ld\n", f(1)(2)(0)(3)());
printf("f(1)(-2)(3)() -> %ld\n", f(1)(-2)(3)());
printf("f() -> %ld\n", f());
return 0;
}
```
Compiling and running with `gcc arbitrary-length-currying.c -o arbitrary-length-currying && ./arbitrary-length-currying` outputs (after some warnings)
```
f(1)() -> 1
f(1)(2)(3)(0)() -> 6
f(1)(-2)(3)() -> 2
f() -> 0
```
[Answer]
# 8086 machine code, 27 bytes
```
00000000 bb 00 00 85 c0 74 13 01 d8 be 00 01 89 e7 47 47 |.....t........GG|
00000010 57 b9 1b 00 f3 a4 5b 89 47 01 c3 |W.....[.G..|
0000001b
```
This machine code must be at address 0x100, and assumes the tiny code model (cs=ds=es=ss). The function location can be changed without costing extra bytes, though. Putting it at offset `0` would save a byte (`xor si,si` instead of `mov si, 0x100`)
**Required calling convention**
This assumes the caller has pre-allocated at least 27 bytes on the stack. It takes a number in `ax`, and returns a function pointer in `bx`. Calling this pointer with `ax=0` terminates the chain, and returns the sum in `bx`.
So for the first call:
```
mov bp, sp
sub sp, 28
mov ax, number_to_add
call function
; new function pointer in bx
```
Then, for each subsequent call:
```
sub sp, 28
mov ax, number_to_add
call bx
; new function pointer in bx
```
To terminate:
```
mov ax, 0
call bx
; result in bx
mov sp, bp
```
---
### Ungolfed (commented disassembly of the machine code):
```
00000000 BB0000 mov bx,0x0 ; 0 is replaced after copying
00000003 85C0 test ax,ax
00000005 7413 jz 0x1a ; if(ax==0) ret (with value in bx)
00000007 01D8 add ax,bx ; arg += total
00000009 BE0001 mov si,0x100 ; address of the original: ds:0x100
0000000C 89E7 mov di,sp
0000000E 47 inc di
0000000F 47 inc di ; dst = sp+2 = above return address
00000010 57 push di
00000011 B91B00 mov cx,0x1b
00000014 F3A4 rep movsb ; copy the function code.
00000016 5B pop bx ; bx = start of copy destination
00000017 894701 mov [bx+0x1],ax ; update total in the copied code
0000001A C3 ret ; with bx = function pointer
```
After calling this with non-zero AX, `bx = sp` and the buffer is filled with a modified copy of the machine code from `function`. The 16-bit immediate in the first instruction holds the total. (It's written by the last instruction before the `ret`.)
`push di` / `pop bx` could be replaced with `mov bx, di` (before `rep movsb`), making it simpler but no savings.
Requiring the caller to pass a pointer to the dst buffer in `di` would save 4 bytes vs. calculating it relative to `sp`.
Making the function start address the same as the function size would save a byte (`mov cx, si`).
[Answer]
# Scala, 58 chars
```
case class f(n:Int){def apply(m:Int)=f(n+m)
def apply()=n}
```
[Try it online](https://ideone.com/RgGL2q)
### Ungolfed:
```
case class f(n:Int){
def apply(m:Int)=f(n+m)
def apply()=n
}
```
### Explanation:
This code defines a `case class` called f with a constructor taking an int. Definind a case class which will generate the equals, hashcode, toString and copy methods, and a companion object with the same name to enable object creation without the `new` keyword.
This class has an overloaded apply method:
One takes another integer to add and creates a new object with the updated sum, and one without arguments to get the sum.
In Scala, any object with an apply method can be called like a method, that is `o.apply(x)` can be written as `o(x)`. This is used in the standard libary for arrays, lists, maps and the `Function1` trait implemented by anonymous functions
[Answer]
# C (GCC), 83 bytes
My first C golf! There are a couple of other C solutions, but this one's a bit different. Preprocessor use is purely cosmetic. This approach was first discussed in Conor O'Brien's answer [here](https://codegolf.stackexchange.com/a/117049).
```
#define r union r
t=0;r{int v;r(*f)();};r e;r f(a){t+=a;e.v=a?f:t;t*=a>0;return e;}
```
The terminal value is zero. The return value is a union, so to call the result, use field `f`, and to access the final value, use field `v`, e.g.
```
f(1).f(2).f(3).f(0).v
```
[Try It Online](https://tio.run/##fY5BDsIgEEXX9hSTGhOolVC7c4JexA2hoCycGqRsmp69UmOMC@Ni3ur9/8fsLsbMniLcQ6ZjpqdHBHPVAaoahBAc53VnnScLAQbyPUEoopIYxiWWMLDKccZxwgA2n2Oaj3GrNFqRlD65Q8RYKX3MERuHQNmaXpM37Yml3nccxmL1fqDcdGcq61zTcOHYfkG7QHKROP7w2o/y32uklF/CND8B)
## Limitations
A global variable holds the running total. While this is explicitly disallowed, the submission does support repeated invocations (the total is reset in the terminal call), which seems to be the reason for the ban on global state.
A pointer to `f` is stored to the returned union through the `int` member, so this is clearly not portable. I'm not sure if this works on GCC on all platforms or just on Linux or just on x86 or just with ELF or... If anyone knows any details about this, please comment or send a message!
[Answer]
# [APL (Dyalog Classic)](https://www.dyalog.com/), ~~48~~ ~~47~~ ~~46~~ 44 32 bytes
```
∇r←(a f)x
r←⍎'(a+x)f'↓⍨-0=x
∇
0f
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob2pm/qO2CQb/H3W0FwEZGokKaZoVXCDmo94@dY1E7QrNNPVHbZMf9a7QNbCt4AKq4zJI@@@mAFShYJDGBTQBzNRwUzDUVDBA8CECRkCx/wA "APL (Dyalog Classic) – Try It Online")
Terminates by passing in zero . Call syntax: `((0 f 1) 2) 0`
-15 bytes thanks to @ngn
Requires `⎕IO←0`
Any golfing tips are welcome!
[Answer]
# [Python 3](https://docs.python.org/3/), 39 bytes
```
class f(int):__call__=lambda s,o:f(s+o)
```
[Try it online!](https://tio.run/##K6gsycjPM/7/PzknsbhYIU0jM69E0yo@PjkxJyc@3jYnMTcpJVGhWCffKk2jWDtf839BEVCFRpqGiaaGkaaGuaaGKZhhoKnJhS6l@R8A "Python 3 – Try It Online")
Not the shortest ([by 3 bytes](https://codegolf.stackexchange.com/a/117022/87681)), but it's different from all previous Python approaches. It works by making a callable `int` subclass. Termination call is optional, but requires a `0` argument if used.
[Answer]
# [Dyvil](https://github.com/dyvil/dyvil), 34 bytes
```
infix int apply(i:int,j:int=0)=i+j
```
**Usage**:
```
0() // = 0
0(1)() // = 1
0(1)(2)() // = 3
```
The trailing `()` can be omitted.
**Explanation**:
Defines a juxtaposition operator that takes two ints and adds them. The parameter `j` has the default value `0` to support the call without arguments. The `0` in the examples above is not the name, but a literal.
[Answer]
## C#, 62 bytes
```
dynamic f(int n)=>(System.Func<int,dynamic>)(m=>m<0?n:f(n+m));
```
To end the call pass in a negative number e.g.
```
f(1)(2)(3)(-1) == 6
```
[Answer]
# Pyth, 19 bytes
```
DhdDebR?bh+dbdR$end
```
[Try it online!](https://tio.run/nexus/pyth#@@@SkeKSmhRkn5ShnZKUEqSSmpfyv6AoM69EIyM1MUXDWFPDVFPDTFPDLz8vVVPzPwA "Pyth – TIO Nexus")
I'm impressed that Javascript beats Pyth, but then again Pyth is not quite designed to be passing functions.
[Answer]
## Perl 5, 36 bytes
```
sub f{my$n=pop;sub{@_?f($n+pop):$n}}
```
---
```
say f(1)->(); # 1
say f(1)->(2)->(3)->(); # 6
```
[Answer]
# [Brain-Flak](https://github.com/Flakheads/BrainHack), 6 bytes
Actually I just noticed that since the [ToS is a valid return format](https://codegolf.meta.stackexchange.com/a/8507/48198) popping the *0* is not really needed which saves 2 bytes:
```
({{}})
```
[Try it online!](https://tio.run/##SypKzMzLSEzO/v9fo7q6tlbz////xkb/dQ2N/hsZ/jf8bwAA "Brain-Flak (BrainHack) – Try It Online")
## Original submission(s), 8 bytes
Uses `0` as the special value:
```
({{}}{})
```
[Try it online!](https://tio.run/##SypKzMzLSEzO/v9fo7q6tra6VvP////GRv91DY3@Gxn@N/xvAAA "Brain-Flak (BrainHack) – Try It Online")
### Explanation
Given the arguments *a1*, *a2*, … , *an*, *0* the stack initially looks like this:
*an*
*⋮*
*a2*
*a1*
*0*
The code then goes on, pops every *ai*, accumulates them, pops the *0* adds them and pushes the result:
```
( ) -- push the following value:
{ } -- while ToS ≠ 0 (sums the runs):
{} -- pop 1 element
{} -- pop the remaining 0 & add it
```
---
### Alternative solutions, 8 bytes
Instead of popping the *0* and adding it to the sum, we can also swap stacks since the right one is initially empty:
```
({{}}<>)
```
[Try it online!](https://tio.run/##SypKzMzLSEzO/v9fo7q6ttbGTvP////GRv91DY3@Gxn@N/xvAAA "Brain-Flak (BrainHack) – Try It Online")
Using the `-r` flag the *0* is on the top of the stack, so we could pop it first:
```
({}{{}})
```
[Try it online!](https://tio.run/##SypKzMzTTctJzP7/X6O6trq6tlbz/39jIwVdQyMFI0MFQwWD/7pFAA "Brain-Flak – Try It Online")
```
{}({{}})
```
[Try it online!](https://tio.run/##SypKzMzTTctJzP7/v7pWo7q6tlbz/39jIwVdQyMFI0MFQwWD/7pFAA "Brain-Flak – Try It Online")
[Answer]
# Java 8, 111 bytes
A lambda from `int` to a function. Calls are terminated by passing zero.
```
i->new java.util.function.Function<Long,Object>(){int t=i;public Object apply(Long x){t+=x;return x<1?t:this;}}
```
[Try It Online](https://tio.run/##nVA7T8MwEJ6dX3GjLVoLJGAgTRALEhKIoSNicBM3XHCdyL6UVFF@e0iIKyQGXtPd95LuvlLt1bKqtS3z16FuNgYzyIzyHh4UWugiFkhPisaxRasMlGNKNoRGbhubEVZW3oZldWdJF9otvjXdV7ZYwOOm1BmlKWSNc6jzmzyHZMBlavXbz/GQ5qJDS0AJxuHUWQBV1@bAJyu0oqOTpI2dpsZZaFdn13RFL@jjvh9YHH39cl9hDruxAL4mh7Z4egblCi@mPtj64EnvZNWQrEeRjOUjyzj/9cNi8v898I8E@2xWzn2cB0UEfGFm4ogvZ3yEpx9QxBHroz4a3gE)
## Ungolfed
```
i ->
new java.util.function.Function<Long, Object>() {
int t = i;
public Object apply(Long x) {
t =+ x;
return x < 1 ? t : this;
}
}
```
Due to an interesting interplay between byte counts of primitive and object integer types, intermediate functions take a `Long` as a parameter, but the total is stored in and returned as an `int`.
## Limitations
The returned function is mutated when called, so, for instance, it's not possible to obtain two integer results without two calls of the lambda. However, the functions returned by separate calls to the lambda are fully independent, so it seems the challenge requirements are met.
Liberal casting is required when constructing expressions that use the lambda. See the TIO for a usage example.
[Answer]
# [Rust](https://www.rust-lang.org/), 134 bytes
```
|x|{fn b(a:i32,n:i32)->Box<dyn std::any::Any>{if n>0{Box::new(Box::new(move|x|b(a+n,x))as Box<dyn Fn(_)->_>)}else{Box::new(a)}}b(0,x)}
```
[Try it online!](https://tio.run/##nY7LrsIwDET3@YpcVrZuQTzExoVIsOA3UKCpVKm4qElpq5BvL2HBo1s2lmXPnJm6sW7IWV50wYC@NE7mciuHe3f38XwCTcVqmfBz4lTtq26T9Syty4g090Q77pUvcslq7uOXiE0L7@VS3UxERcw/Jx2itvKFODAcI/GoMJjSmo9ZYwgnmEd5GFLRWDNOS8W1LtiV/AcTHyYJ5LDCWVa1fNbWEW2@Asaln1WVApw13Nb6Coiw/tEJ08XIGeUjcCqCEMMD "Rust – Try It Online")
In your face, strict type system! Terminates if the input is negative. You do have to downcast the result after every call though (see tio). I took a similar approach to the Math.js solution.
ungolfed:
```
|x| {
fn b(a: i32, n: i32) -> Box<dyn std::any::Any> {
if n > 0 {
Box::new(Box::new(move |x| b(a + n, x)) as Box<dyn Fn(_) -> _>)
} else {
Box::new(a)
}
}
b(0, x)
}
```
Rust's strong type system makes this almost impossible. Fortunately, trait objects come to the rescue. Trait objects erase the type and all associated data except for the trait's implementation. In this instance, I use the `Any` trait, which allows downcasting back into a concrete type. There are some wrinkles because you can't explicitly name the type of closures, so I have to cast the closure into a `Fn` trait object and then recast it into an an `Any` before use.
[Answer]
# [Aussie++](https://github.com/zackradisic/aussieplusplus/), ~~98~~ 96 bytes
-2 because I remembered the angle brackets aren't necessary for a single-statement `YA RECKON` body.
```
THE HARD YAKKA FOR f IS(x)<THE HARD YAKKA FOR g IS(y)<YA RECKON y ?BAIL f(x +y);BAIL x;>BAIL g;>
```
Tested in commit 9522366. For the final call, give it `BUGGER ALL` or `YEAH, NAH!` instead of a number.
The general structure is something like
```
function f(x) {
function g(y) {
if (y) return f(x + y);
return x;
}
return g;
}
```
Since Aussie++ doesn't have function expressions or anonymous functions yet, it is necessary to put the function declaration and return as separate statements.
[Answer]
## PHP7.4 (45 chars)
The superglobal function **[$\_ENV](https://www.php.net/manual/en/reserved.variables.environment.php)** will return an adder function continuously.
After the operations, when no argument is provided **$\_ENV** will return the result.
```
$_ENV=fn($a)=>fn($b=-1)=>~$b?$_ENV($a+$b):$a;
```
Usage :
```
var_dump($_ENV(1)() == 1); // bool(true)
var_dump($_ENV(4)(2)(7)() == 13); // bool(true)
var_dump($_ENV(4)(2)(7)(5)(2)() == 20); // bool(true)
```
**Info**: Overriding a [superglobal](https://www.php.net/manual/en/language.variables.superglobals.php) like *$\_ENV* variable isn't recommended.
[Answer]
# [Perl 6](http://perl6.org/), 31 bytes
```
sub f(\n){->$m?{$m??f n+$m!!n}}
```
[Answer]
## [Python](https://www.python.org/]), 61 bytes
```
f=lambda n="":0if n==""else lambda m="":n if m==""else f(n+m)
```
Much longer than the other Python version, but uses the no-argument syntax rather than a magic number. Can probably be improved upon.
If it can be assumed that "at least one call will be made before the termination call", this can be reduced to **44 bytes**:
```
f=lambda n:lambda m="":n if m==""else f(n+m)
```
[Answer]
## [Julia](https://julialang.org/) v0.5+, 52 bytes
```
type F n end
F()=0
(f::F)()=f.n
(f::F)(x)=(f.n+=x;f)
```
Call as `F`. This could probably be made a lot shorter by adopting a less OO method, but I always like getting the chance to use this idiom.
If it can be assumed that "at least one call will be made before the termination call", the second line can be removed to save 6 bytes.
[Answer]
# [Julia 0.5](http://julialang.org/), 18 bytes
```
!n=k->k>0?!(n+k):n
```
[Try it online!](https://tio.run/nexus/julia5#@6@YZ5uta5dtZ2CvqJGnna1plfc/N7FAo6AoM68kJ08nmotTQ1FTw1BTw0ATwjTR1DDS1DDHImAKZgCFYzX/AwA "Julia 0.5 – TIO Nexus")
[Answer]
# R, 40 bytes
```
f=function(x)function(y)`if`(y,f(x+y),x)
```
0 acts as the stop value here. For two more bytes, we can omit it.
The problem is that R lacks a concise built-in lambda. But [if we add one](https://github.com/klmr/functional/#a-concise-lambda-syntax), we can get the code to **26 bytes**:
```
f=x->(y->`if`(y,f(x+y),x))
```
(Yes, that’s valid R. It just needs an import.)
[Answer]
# PHP, 44 Bytes
An Idea from [@user63956](https://codegolf.stackexchange.com/users/63956/user63956)
Termination call `0`
```
function f($i){return[$_GET[0]+=$i][$i]?:f;}
```
[Online Version](http://sandbox.onlinephpfunctions.com/code/03419ad8be41d166de374cc7dc144274fd5a1cf0)
Termination call with `NULL` need a càst `[$i]` to `[+$i]`
# PHP, 47 Bytes
```
function f($i){global$s;return$i?f.!$s+=$i:$s;}
```
[Online Version](http://sandbox.onlinephpfunctions.com/code/1d2b18bcc5c0cd2c670ad83c8fb7185d30244b25)
# PHP, 52 Bytes
Termination call `NULL` or any other value that is false in PHP
```
function f($i){global$s;$i?$s+=$i:print$s;return f;}
```
if the program must terminate after the Output replace `print$s` with `die("$s")` + 2 Bytes
[Online Version](http://sandbox.onlinephpfunctions.com/code/6595b125390e7d6dfc8795d6eb8e5141bc131bcc)
] |
[Question]
[
There have been a billion iterations of Fibonacci challenges on this website, so lets spice things up with a Fibonacci challenge of a billion iterations!
Your challenge is to output the first 1000 decimal digits of the 1,000,000,000th Fibonacci number with as short a program as possible. This may then optionally be followed by any additional output of your choosing, including but not limited to the rest of the digits.
I am using the convention that `fib 0 = 0`, `fib 1 = 1`.
Your program must be fast enough for you to run it and verify its correctness. For this purpose, here are the first 1000 digits:
```
7952317874554683467829385196197148189255542185234398913453039937343246686182519370050999626136556779332482035723222451226291714456275648259499530612111301255499879639516053459789018700567439946844843034599802419924043753401950114830107234265037841426980398387360784284231996457340782784200767760907777703183185744656536253511502851715963351023990699232595471322670365506482435966586886048627159716916351448788527427435508113909167963907380398242848033980110276370544264285032744364781198451825462130529529633339813483105771370128111851128247136311414208318983802526907917787094802217750859685116363883374847428036737147882079956688807509158372249451437519320162582002000530798309887261257028201907509370554232931107084976854715833585623910450679449120011564762925649144509531904684984417002512086504020779012501356177874199605085558317190905395134468919443313026824813363234190494375599262553025466528838122639433600483849535070647711986769279568548796855207684897741771784375859496425384355879105799
```
[Answer]
# [Python 2](https://docs.python.org/2/) + sympy, 72 bytes
```
from sympy import*
n=sqrt(5)
print'7'+`((.5+n/2)**1e9/n).evalf(1e3)`[2:]
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P60oP1ehuDK3oFIhM7cgv6hEiyvPtriwqETDVJOroCgzr0TdXF07QUNDz1Q7T99IU0vLMNVSP09TL7UsMSdNwzDVWDMh2sgq9v9/AA "Python 2 – Try It Online")
-10 bytes by removing the practically-0 term thanks to Jeff Dege
-1 byte (1000 -> 1e3 thanks to Zacharý)
-2 bytes by removing the unnecessary variable thanks to Erik the Outgolfer
-2 bytes by moving to Python 2 thanks to Zacharý
-3 bytes by 11'ing the `-11` thanks to ThePirateBay
-3 bytes by swapping `str` for backticks thanks to notjagan
now beats OP's unposted haskell solution!
[Answer]
# [Python 2](https://docs.python.org/2/), 106 bytes
```
a,b=0,1
for c in bin(10**9):
a,b=2*a*b-a*a,a*a+b*b
if'1'==c:a,b=b,a+b
while a>>3340:a/=10;b/=10
print a
```
[Try it online!](https://tio.run/##NZTbbhMwEETf8xV5A0IRe/HeisK/JAhEJNRCVQnx9eW4iMpNHO@uPTM79s8/z98fH@zl5XJ3PcudHr49Ph2/HG8Px@vt4a3K6TTv7g/HHbXT5XT9cDld7vh/fz1dD8fbtzf65nz@cr/j1ztWD8ff328/vh4vnz@7L7m/fDyrfLruz8PPp9vD8/Hy8utcE@ZaXStiZfvKahvv0Emd0tXaY0HQtEldPj3qK1x8xosFW5md2kaNl0jIzKSlekZk1TgpbeJR5ma2Qs3SRtl9RVpFEo5ZM@yaaqrqohzKStekT2hKcOhUj2jvQ7KAMkBeqxdgCE6LLZ2xJcuLfNEJUTiwnXD4sgzx6qXMyIaLd3kKS8ZwinMFpFixvShSMEgZqf0nrs2IWisjw9PCQzXEEKw0wMpvMZBJAsShFasU2kkxesjmupzMjM7ulNVIQGlpjiblEKpG61oMp6TRY4TgqxZS/orcNmRmTOEoVon4sWBGAJoUL89VVE@jORKvNJQNo@cb6S6llTCSKEAWopMNP2ViG3c68qGWbNpbLbFAOim6h2lkQGDGHJRw2pVJUbd70RcogDDLaTWcjLoJ3NItVIxGe2GIAd7uGP4xUUQlUxj0nAq6N92FoSwKpUmZ1/LNF186fkWAkl5TQAA3@3o03vJRWYhes9YoW9IsNMF9xvdsAwquY8PtJHRairlwMozxygIFBt5mFPXIV9LbYtgRwsE5tJ3egBSTOrbgdnCWO0JbIiIKIwje22fMZolRsX/AbXckw1Cr95VwwpgRRzhYcBacAFu7gVk5xmXd/Pad4HCggbmnQEQSdmXz3vcIBwRb4B1Sd3NnDof/r8F@SRRt/z0I/5@C8/nXy18 "Python 2 – Try It Online")
No libraries, just integer arithmetic. Runs almost instantly.
The core is the divide-and-conquer identity:
```
f(2*n) = 2*f(n)*f(n+1) - f(n)^2
f(2*n+1) = f(n)^2 + f(n+1)^2
```
This lets us update `(a,b) = (f(n),f(n+1))` to double `n -> 2*n`. Since we want to get `n=10**9`, this takes only `log_2(10**9)=30` iterations. We build `n` up to `10**9` by repeatedly doing `n->2*n+c` for each digit `c` of its binary expansion. When `c==1`, the doubled value is shifted up `2*n -> 2*n+1` with a one-step Fibonacci shift `(a,b)=(b+a,b)`
To keep the values `a,b` manageable, we store only their first `1006` digits by floor-dividing by `10` until they are under `2**3340 ~ 1e1006`.
[Answer]
# x86 32-bit machine code (with Linux system calls): ~~106~~ 105 bytes
changelog: saved a byte in the fast version because an off-by-one constant doesn't change the result for Fib(1G).
Or 102 bytes for an 18% slower (on Skylake) version (using `mov`/`sub`/[`cmc`](http://felixcloutier.com/x86/CMC.html) instead of `lea`/`cmp` in the inner loop, to generate carry-out and wrapping at `10**9` instead of `2**32`). Or 101 bytes for a ~5.3x slower version with a branch in the carry-handling in the inner-most loop. (I measured a 25.4% branch-mispredict rate!)
Or 104/101 bytes if a leading zero is allowed. (It takes 1 extra byte to hard-code skipping 1 digit of the output, which is what happens to be needed for Fib(10\*\*9)).
Unfortunately, TIO's NASM mode seems to ignore `-felf32` in the compiler flags. [Here's a link anyway](https://tio.run/##pVprc@PGsf3OXzHXVa4VJZIiuPReSQx9ax/eylZ2E1dkV5JyVKoBMCTHAgEEA4qkU/nrd@/p7hk8KK3j1JW9u@IA6Onpx@nTDWrnzDbOjuNcu@3nz@usiHWm7l2tq3og/9wMBgo/2@KR/jHJYaSiafhR8rNQ7218hmtDlRVFqZJil9emGizoYmY0PxmXI/UT7hlHd6r5wR2xdmYcKZuremP401lZWHp@qCqztg6/qcWwpwXJgih6XpelrkxeZ0dWIpqen18PVW4e8ZQzximtMruNl8uO1uagEzwwUq6ArlsIsPla6bW2uatZjX1VYCXfbWOIsU4VDwM5jWjQN8Ng8LVdqSlruFioapcr7dTkUk@KXa2m0aynu7NkB1deXN3xem2wp6zjDy/9/Iua5MW9rtYuPPrLwe8aH2tDz9uLqTzvdnHjmRfTF7xmt7usVbMnQ/dkRCIj@IjuJx@pC7pRjUng3X8mcfZbJC5OQ2oGK4Yj3wy@Npkzg8VCfcGi03m46GVUKW1TwajRq7twzRuWruFPWCXbugdb3sPr7SZPLYxHyML@@qmR/fKJVU6E6Z6wqBHWs03Ftqk6tvnPRc9@u@hnLY/1jk3I/nlqV4O@mxxyLt6totNl65d7q6ms9iM/xnbjaDqb86rO00YuLgka6Myu8y3SGRmcGOd0dVSrokKW5o8mt3TBg8O4Ms7UsituazaIRHj6RDikB@ukPgUpKOPD3USptzp/USuyAdLfuhv1@vbjn1Wic1Ui4L67/R76YBNGqKKui60qVkCWUq9NL9z7ks99ei0OyWbdqJNaVuYH7EPQ4nDkDcHXShPUQZkP7/6g9pvjRJB3oT7ULwiB2BDfvfug6kLF0MNkxZ5Vi48KwVLbMjNq/sBKOTJ/rWyt9jbLAITrlcYtigDO6JS0N4ea3AyYo1MB65MHBRg7Fju1LrBHAYWqiVfh9YpQGOYAruYBFyHE7XWJvUgr3gh6sX9YbMGSoSW8BYfAYc6kFBYr1AbVGkFnuIeA2m01yeAblLO/AIdtvaGU3@jHVlNGa5yjVIUUDdFnQpEZKobDBV0rlAb1i6kKhd/LqqCQUlzWdvDEfmOTjdoblZoSpoC0G4mnQ1GxMw/kLUEO3KUzlIvmVrU124KiE2EhrrC5rS3KJ7vEkI60s0m9H12diPRy5zb4Z6q6PwtRi56iMjYdRcPxt/gb/81GL9Wjm0h5G02xjr/lSvvQVzH8t9dV6r6ikHVq51QkhRjKbGyeeosDJe2dWnLO/jSl36Y4WYWgOPZS2CN6au@QU/IoJTQeWaoziR2T3peVSayzRT6MIOmf0UhNR2oymfwLvli03oA2CMobXmPsAmzcKJdUuoYHKK7JjTpNYMQctxOLGDFCwPn@szwcH24EQ5AnH2F0VtPScRFa2rEcljFmJkKlP9ARqC3xjlggz4ygnquLKgRWFsQhrnmLoWyZYEtWQ0TCDUWuk8QiuwwOgMO3hIfuT3F/itJDNh3vK8sSVwArdUYn/aqifFduY1fkua8oT1LrEvhO1DDAgbEDDtqVBQLVfAivS2pFtgdBWXQlbFkl/cUYi55aLdV1@IHVXif1Dml2ROxQxm5AoEzuSIt9UT1wxtHTHb6EAJ6swqlvBqSOBJb5x05F0fwkkKNohi3x@CtkS2KR0zjf2iImL9V1@LUkr0IQFPpjAUl5sVtLJNC@MGiFyKr93QJmtJN1gkhf/qH9X@IouywlNBLBIqCb6ao9heQqAxuMoB8LmxIW7eJu8YqzUfvIYCJ63QPVbiSvsiJ16RdVun04ZvrB3KiZ2hUlcln9CQhTIpqoOovNwV668Iw07ZdUfZDScten1a70dHJ@JxU0/XnnpGQF8NTA04RR4u17CoAMQZIjcB8NzlRgu8pk/JHOT@WJEi83a43IBeRL8P4P60x1lbacQyhXBKRsbOA2o5JtyaagU4m@vhInHfUh/IIy5FyagAUniVpVKKiopgVQhSAUDYnPmKxIJMPOyIESsZSzJlQXPJrXaA4Q8sTs6LhMGf9YlDidFvBnb4UOA0lPlTAtjKOavzVa1hEX/6XUGayz4VjEE1vOVDxHiaS4tfBgBcRBOYkzsx122T/7iilROD4TR4G8uOTobNsQYL5BKrx9r4qyLBwBxZ6KFuI0N4Az2ioH1LZAwyIT7JI0MOqXkl9LCKr1lVbJMckY3eBtkyfHBngJ18YAoMpiV0kRuj5RL69G0//@5lMSEvMTq@LUGUcsHOHS4b9LSNIgR4pvd1RsCyKYvOksUejRqHYwpcoMGN@DCyWd/TqmXG0v@r6gF/3Mt5jhtoa98zYp215RH54qFYy/3xiKL8bKofod3YwssRMzkUv4/O2SLnes35j/qVja6@slh8xIPRhTUuK14ffTdDKha2hudQ72GLg2BVHkiULxRSjpo8nLgCYf7YPh3LyAqfPx1iZVMV5xTeRswS0vZ6Pr6fUnjgH3vD9h1EtYbcTuQuDiQzJsjO5xyFOCZy36MhpdfzN/fo8bz2@Jl@Xq9oc/3b4bBD962pxaAbG@0D@bMtOJFGmkHWv6@t074pyAIQ8@ZNm3n74nJsBx5ph1wkLfjKZXL5/XqDE97YNKJTD/JaOX1G9Uj8YJiP7QIAlpVhIL09l4lek1EKVaG4rj1@/etoWINKJFyBnf5m/U2@9/lOb@5xy41dYTT9PibDnl1mXZdkwLDrgNWA5V0A3AScUILMLJBkAAi2/fDyY42T3TIErtmzCZ8JjNMcLASDkPrAVonr19v4yGN4rJyZjJCWXexrNxR01GxBVwpIpHI7iBYoh0JkRhFk5QVe@LFq5c2LiPYr7eXRFL4FoDFLhYzm@UVAMP/VwUSAUQdSZReVGBS8D2OJyPAyjdjF1WBbURkmzQ79k9ps/tkYIF/n/3mPb3YPAgRk7@EJkjBeJgMzFFx@7wm7MoJHDLyux9PhJAV8NBM1FC2WTG/lck@Py85SHhuvPX/9a/zp94r/sMyXdf263x7TtOTwH/E0T3xzEpNE03T1EtPSynsAtQO1QPOPL2Dx@FWr37PcdlbICX3EtwrmlUFspb2nbRJQPorPCnkQzlOamiN6DFRdWgBCtJCtEWFdimRcqJKmRYGVN2TpNmXcoWkAryF4E0UNA2tgdbLrin5erIrUJsjgUc2bew22RBazULNn8D@E42vs@Fsmkm4utql3vO4nMf9njgS6mu9bgtr@oMieM5uxuSOVvVODAZ7/q1n1pRirTM1G3OtYnFFmnIbls5n1bVs2uuHcNGKmH@r3CBkORtf6bOZqqDq3Dt@FuqueNvFcOgzWl0QmMSOL3Rs9nw1uaJWKzUNRFSYDfxMTQGxFbRn6B53GW6wnHY1GBjDuCZ2gTgJ6bd7KoanV@TJzId49KcbsKixIbOms9UXsMHnhEyh5537gcip839PAvgKISMMJKhui5NItV1wDSi90dH0YAK0tCqbvOJSkfFA5cZeTemMjx/tjTcCVAhEs/w/Hg2nV/R3sQIaZjtDcfep3IpZWHRHU4SGTpFh273QHMpEkGHvpRjJmxHavwkaoqcGkPWVPveekWhRJMwV2zNBkVMOiQ6IOkHw3jb@oEeQd08wAbLI/GOBLXAhMCmhgu1BHKqvUUV2ZsXqfBeSu1djJxM6s4jK1u5evL0xIFpLxZxHRqikKVySJ21OAZOJAByGQl8a3U@V346Rf7bFqk4hrNPTCG/AgUIAmYSA2GkR74Ihm1GA9Kkk0GoL6ch2fMjz4X3ODdCcHLdwBoljpReGlOsdQV8cY5WpXT15LEOHXmDpzPQ9HAC6N0yiBCGnt2@Uog11bPq6nx@NzhhENxj8hSuSlpjsbOl2XQy/WjlM/5RnWVuWSXSNXRz67Ti8LiNnq6uUh@FG82dOVhH0sxUqLBxhRmdAPEs788aFwpYpSum/L3OqjkcGkh@78LsJyzi/79suKpx27iuaFTJlYNTnHYXVmS3ZWYTS8gl9EnmPA1vupQuND6yach4HuTBDU0Sqo6ohUB6CvydEcOi8a1tkq1juuagHWBsQiEAXXNS/4aPMb2d85CcT/oI5jqdTKOvPaOWugyyfEm0lYggunUJHGLQJjnIBya1jazBoMZePLelGSBStoKVzMHWHerBEBVRe/O323u6tvTvFGBspaaHq2mgIrh2Rsw4CgxJRPvJEg@lprNXgyer1x1mBDkXKrryoHry5gIVWB6@6MoI9xpmYzzkvxwrwukwSkYO0DjYD7P0Xh9lrOTjn5pf4n4EdoT/tHh8gX8pqIRJ8AQXpoAwRsaw564EeUDHxynGkKFLLvW93BOgpeCWbUMEjfnMjjOkJKCBAch3GXApdBbJgWlsE5M8JpOaDz/KBFZCj0GH2@oouEQ2jk2iCV9Ph6nN9JEMND2sVoPn3gtfRNO2@Vt03/RG024pS4AWZ12/XFwNL68Hk7rQLrGAXmJ7vH2oZ9wHF6AbbC6aAhbENLjW6PDqxCYyArM5TSW4kXIl3bErUW8fOY99HyDJJxMtnqY3ff/GT6CZyIktG4SAYmj9XyoZNSBrz2WiNDyZmj3XfHLqn44j2zPfsyGkzUvSf/zK6EC4c3AU7Zbwm6@NfhS/dbtKaYxtcMSX5FVmqy1YYoUAIrsLzi3ptDRvxiaXS5guYFEonJp7gJaVpU9QDEgD@NkU9AqhYWwe@YhlhLfdntTFz@/Asl69ocpD5Rxh4/h1Ckc2OYfSlCgXug8k6qv5mI5PNMBnKQEbAnf2Ztgtq2lHgWdNzSoJGhcxvS7jXmtE@@YEagm1dd3Zg7wY7DxOewt6Qa9Pt@/GTIGQwf4FW1GlRA8o@Zh5hjdAzyaxZMwz/RGYbn8C0kwlVD@@umXCXwjo8WNJ83zKd6YosDyijIzH42Yk3euP6gMBVe55Jr@cE8KPQFztsgBDMcFQO/KQ8Sm/iIsPnXaRIfCCQ0ydZb6espZDbHkxDZDb@UoI4W73uywdntqfrqH88DCgRSl@sUxjxjFt2nx/ZaFW6VJmdoJX/EK968ZwH3hIR1riR@EX3W/C4K7fw3mAagQeQXireigvhC5Fzm@I0vB6MRyU8tZ4pAkkeVN520WdEscLvdLox1tUZrOiZgeCe9uMY8rm9Aoe/DPWazOZTAYnkiL6@kBYYsAXMMfFcYTomh704sXf8xecCFSFLpaRp1977CBG7lf4U@OxM84i/kLBiOvtsONHP1s/9InDv@UN4cslnSBD4Y@i2fl177slFCXRE5LyTLAEge0rgIZF@K9Iffjrp@9uQP5wR@NDGcOVwBS6zzckmxAHgaBPJHI8KUfgtF9y6bxxAJr0FlPbGdP6WO3fcBoJ4ERRiFhyJTsMm/@F6yWBidfQO6/NZfSwROz9jCad9L5q4sOCu4nfGhbhezdHl9B3Ap4PCFiYY4LeNQ5bl3rAdXz6pUo2RIbpodrkg0YzfskvRjq1HDn51bS5U7JWyn1qxxEw4FXnq0HPqYhFDsWzKWJtwFOFhCc0ahI7Rwv8TRc1n16/ok/0Nv4mSESrEQvCdd6ongOslmo@v3rTkj4ah6N4bWW0hXJJlAalUgTOngqkhSYs@5cpr5oTNw@cN38NPn/@34QGO@7zeGWy1cvZ/wE) with my full source code, with all the mess of experimental ideas in comments.
**This is a complete program**. It prints the first 1000 digits of Fib(10\*\*9) followed by some extra digits (the last few of which are wrong) followed by some garbage bytes (not including a newline). Most of the garbage is non-ASCII, so you may want to pipe through `cat -v`. It doesn't break my terminal emulator (KDE `konsole`), though. The "garbage bytes" are storing Fib(999999999). I already had `-1024` in a register, so it was cheaper to print 1024 bytes than the proper size.
I'm counting just the machine-code (size of the text segment of my static executable), not the fluff that makes it an ELF executable. ([Very tiny ELF executables are possible](http://www.muppetlabs.com/~breadbox/software/tiny/teensy.html), but I didn't want to bother with that). It turned out to be shorter to use stack memory instead of BSS, so I can kind of justify not counting anything else in the binary since I don't depend on any metadata. (Producing a stripped static binary the normal way makes a 340 byte ELF executable.)
You could make a function out of this code that you could call from C. It would cost a few bytes to save/restore the stack pointer (maybe in an MMX register) and some other overhead, but also save bytes by returning with the string in memory, instead of making a `write(1,buf,len)` system call. I think golfing in machine code should earn me some slack here, since nobody else has even posted an answer in any language without native extended-precision, but I think a function version of this should still be under 120 bytes without re-golfing the whole thing.
---
### Algorithm:
**brute force `a+=b; swap(a,b)`, truncating as needed to keep only the leading >= 1017 decimal digits. It runs in 1min13s on my computer (or 322.47 billion clock cycles +- 0.05%)** (and could be a few % faster with a few extra bytes of code-size, or down to 62s with much larger code size from loop unrolling. No clever math, just doing the same work with less overhead). It's based on [@AndersKaseorg's Python implementation](https://codegolf.stackexchange.com/questions/133618/extreme-fibonacci/133678#133678), which runs in 12min35s on my computer (4.4GHz Skylake i7-6700k). Neither version has any L1D cache misses, so my DDR4-2666 doesn't matter.
Unlike Python, **I store the extended-precision numbers in a format that makes truncating decimal digits free**. I store groups of 9 decimal digits per 32-bit integer, so a pointer offset discards the low 9 digits. This is effectively base 1-billion, which is a power of 10. (It's pure coincidence that this challenge needs the 1-billionth Fibonacci number, but it does save me a couple bytes vs. two separate constants.)
Following [GMP](https://gmplib.org/) terminology, each 32-bit chunk of an extended-precision number is called a "limb". Carry-out while adding has to be generated manually with a compare against 1e9, but is then used normally as an input to the usual [`ADC` instruction](http://felixcloutier.com/x86/ADC.html) for the next limb. (I also have to manually wrap to the `[0..999999999]` range, rather than at 2^32 ~= 4.295e9. I do this branchlessly with `lea` + `cmov`, using the carry-out result from the compare.)
When the last limb produces non-zero carry-out, the next two iterations of the outer loop read from 1 limb higher than normal, but still write to the same place. This is like doing a `memcpy(a, a+4, 114*4)` to right-shift by 1 limb, but done as part of the next two addition loops. This happens every ~18 iterations.
---
Hacks for size-saving and performance:
* The usual stuff like `lea ebx, [eax-4 + 1]` instead of `mov ebx, 1`, when I know that `eax=4`. And using `loop` in places where [`LOOP`'s slowness](https://stackoverflow.com/questions/35742570/why-is-the-loop-instruction-slow-couldnt-intel-have-implemented-it-efficiently) only has a tiny impact.
* Truncate by 1 limb for free by offsetting the pointers that we read from, while still writing to the start of the buffer in the `adc` inner loop. We read from `[edi+edx]`, and write to `[edi]`. So we can get `edx=0` or `4` to get a read-write offset for the destination. We need to do this for 2 successive iterations, first offsetting both, then only offsetting the dst. We detect the 2nd case by looking at `esp&4` before resetting the pointers to the front of the buffers (using `&= -1024`, because the buffers are aligned). See comments in the code.
* The Linux process-startup environment (for a static executable) zeros most registers, and stack-memory below `esp`/`rsp` is zeroed. My program takes advantage of this. In a callable-function version of this (where unallocated stack could be dirty), I could use BSS for zeroed memory (at the cost of maybe 4 more bytes to set up pointers). Zeroing `edx` would take 2 bytes. The x86-64 System V ABI doesn't guarantee either of these, but Linux's implementation of it does zero (to avoid information-leaks out of the kernel). In a dynamically-linked process, `/lib/ld.so` runs before `_start`, and does leave registers non-zero (and probably garbage in memory below the stack pointer).
* I keep `-1024` in `ebx` for use outside of loops. Use `bl` as a counter for inner loops, ending in zero (which is the low byte of `-1024`, thus restoring the constant for use outside the loop). Intel Haswell and later don't have partial-register merging penalties for low8 registers [(and in fact don't even rename them separately)](https://stackoverflow.com/questions/45660139/how-exactly-do-partial-registers-on-haswell-skylake-perform-writing-al-seems-to), so there's a dependency on the full register, like on AMD (not a problem here). This would be horrible on Nehalem and earlier, though, which have partial-register stalls when merging. There are other places where I write partial regs and then read the full reg without [`xor`-zeroing](https://stackoverflow.com/questions/33666617/what-is-the-best-way-to-set-a-register-to-zero-in-x86-assembly-xor-mov-or-and) or a `movzx`, usually because I know that some previous code zeroed the upper bytes, and again that's fine on AMD and Intel SnB-family, but slow on Intel pre-Sandybridge.
I use `1024` as the number of bytes to write to stdout (`sub edx, ebx`), so my program prints some garbage bytes after the Fibonacci digits, because `mov edx, 1000` costs more bytes.
* (not used) `adc ebx,ebx` with EBX=0 to get EBX=CF, saving 1 byte vs. `setc bl`.
* `dec`/`jnz` inside an `adc` loop preserves CF without causing a partial-flag stall when `adc` reads flags on Intel Sandybridge and later. [It's bad on earlier CPUs](https://stackoverflow.com/questions/32084204/problems-with-adc-sbb-and-inc-dec-in-tight-loops-on-some-cpus/32087095#32087095), but AFAIK free on Skylake. Or at worst, an extra uop.
* Use memory below `esp` as a giant [red-zone](https://stackoverflow.com/tags/red-zone/info). Since this is a complete Linux program, I know I didn't install any signal handlers, and that nothing else will asynchronously clobber user-space stack memory. This may not be the case on other OSes.
* Take advantage of [the stack-engine](https://stackoverflow.com/questions/36631576/what-is-the-stack-engine-in-the-sandybridge-microarchitecture) to save uop issue bandwidth by using `pop eax` (1 uop + occasional stack-sync uop) instead of `lodsd` (2 uops on Haswell/Skylake, 3 on IvB and earlier according to [Agner Fog's instruction tables](http://agner.org/optimize/))). IIRC, this dropped the run-time from about 83 seconds to 73. I could probably get the same speed from using a `mov` with an indexed addressing mode, like `mov eax, [edi+ebp]` where `ebp` holds the offset between src and dst buffers. (It would make the code outside the inner loop more complex, having to negate the offset register as part of swapping src and dst for Fibonacci iterations.) See the "performance" section below for more.
* start the sequence by giving the first iteration a carry-in (one byte [`stc`](http://felixcloutier.com/x86/STC.html)), instead of storing a `1` in memory anywhere. Lots of other problem-specific stuff documented in comments.
**NASM listing (machine-code + source)**, generated with `nasm -felf32 fibonacci-1G.asm -l /dev/stdout | cut -b -28,$((28+12))- | sed 's/^/ /'`. (Then I hand-removed some blocks of commented stuff, so the line numbering has gaps.) To strip out the leading columns so you can feed it into YASM or NASM, use `cut -b 27- <fibonacci-1G.lst > fibonacci-1G.asm`.
```
1 machine global _start
2 code _start:
3 address
4 00000000 B900CA9A3B mov ecx, 1000000000 ; Fib(ecx) loop counter
5 ; lea ebp, [ecx-1] ; base-1 in the base(pointer) register ;)
6 00000005 89CD mov ebp, ecx ; not wrapping on limb==1000000000 doesn't change the result.
7 ; It's either self-correcting after the next add, or shifted out the bottom faster than Fib() grows.
8
42
43 ; mov esp, buf1
44
45 ; mov esi, buf1 ; ungolfed: static buffers instead of the stack
46 ; mov edi, buf2
47 00000007 BB00FCFFFF mov ebx, -1024
48 0000000C 21DC and esp, ebx ; alignment necessary for convenient pointer-reset
49 ; sar ebx, 1
50 0000000E 01DC add esp, ebx ; lea edi, [esp + ebx]. Can't skip this: ASLR or large environment can put ESP near the bottom of a 1024-byte block to start with
51 00000010 8D3C1C lea edi, [esp + ebx*1]
52 ;xchg esp, edi ; This is slightly faster. IDK why.
53
54 ; It's ok for EDI to be below ESP by multiple 4k pages. On Linux, IIRC the main stack automatically extends up to ulimit -s, even if you haven't adjusted ESP. (Earlier I used -4096 instead of -1024)
55 ; After an even number of swaps, EDI will be pointing to the lower-addressed buffer
56 ; This allows a small buffer size without having the string step on the number.
57
58 ; registers that are zero at process startup, which we depend on:
59 ; xor edx, edx
60 ;; we also depend on memory far below initial ESP being zeroed.
61
62 00000013 F9 stc ; starting conditions: both buffers zeroed, but carry-in = 1
63 ; starting Fib(0,1)->0,1,1,2,3 vs. Fib(1,0)->1,0,1,1,2 starting "backwards" puts us 1 count behind
66
67 ;;; register usage:
68 ;;; eax, esi: scratch for the adc inner loop, and outer loop
69 ;;; ebx: -1024. Low byte is used as the inner-loop limb counter (ending at zero, restoring the low byte of -1024)
70 ;;; ecx: outer-loop Fibonacci iteration counter
71 ;;; edx: dst read-write offset (for "right shifting" to discard the least-significant limb)
72 ;;; edi: dst pointer
73 ;;; esp: src pointer
74 ;;; ebp: base-1 = 999999999. Actually still happens to work with ebp=1000000000.
75
76 .fibonacci:
77 limbcount equ 114 ; 112 = 1006 decimal digits / 9 digits per limb. Not enough for 1000 correct digits, but 114 is.
78 ; 113 would be enough, but we depend on limbcount being even to avoid a sub
79 00000014 B372 mov bl, limbcount
80 .digits_add:
81 ;lodsd ; Skylake: 2 uops. Or pop rax with rsp instead of rsi
82 ; mov eax, [esp]
83 ; lea esp, [esp+4] ; adjust ESP without affecting CF. Alternative, load relative to edi and negate an offset? Or add esp,4 after adc before cmp
84 00000016 58 pop eax
85 00000017 130417 adc eax, [edi + edx*1] ; read from a potentially-offset location (but still store to the front)
86 ;; jz .out ;; Nope, a zero digit in the result doesn't mean the end! (Although it might in base 10**9 for this problem)
87
88 %if 0 ;; slower version
;; could be even smaller (and 5.3x slower) with a branch on CF: 25% mispredict rate
89 mov esi, eax
90 sub eax, ebp ; 1000000000 ; sets CF opposite what we need for next iteration
91 cmovc eax, esi
92 cmc ; 1 extra cycle of latency for the loop-carried dependency. 38,075Mc for 100M iters (with stosd).
93 ; not much worse: the 2c version bottlenecks on the front-end bottleneck
94 %else ;; faster version
95 0000001A 8DB0003665C4 lea esi, [eax - 1000000000]
96 00000020 39C5 cmp ebp, eax ; sets CF when (base-1) < eax. i.e. when eax>=base
97 00000022 0F42C6 cmovc eax, esi ; eax %= base, keeping it in the [0..base) range
98 %endif
99
100 %if 1
101 00000025 AB stosd ; Skylake: 3 uops. Like add + non-micro-fused store. 32,909Mcycles for 100M iters (with lea/cmp, not sub/cmc)
102 %else
103 mov [edi], eax ; 31,954Mcycles for 100M iters: faster than STOSD
104 lea edi, [edi+4] ; Replacing this with ADD EDI,4 before the CMP is much slower: 35,083Mcycles for 100M iters
105 %endif
106
107 00000026 FECB dec bl ; preserves CF. The resulting partial-flag merge on ADC would be slow on pre-SnB CPUs
108 00000028 75EC jnz .digits_add
109 ; bl=0, ebx=-1024
110 ; esi has its high bit set opposite to CF
111 .end_innerloop:
112 ;; after a non-zero carry-out (CF=1): right-shift both buffers by 1 limb, over the course of the next two iterations
113 ;; next iteration with r8 = 1 and rsi+=4: read offset from both, write normal. ends with CF=0
114 ;; following iter with r8 = 1 and rsi+=0: read offset from dest, write normal. ends with CF=0
115 ;; following iter with r8 = 0 and rsi+=0: i.e. back to normal, until next carry-out (possible a few iters later)
116
117 ;; rdi = bufX + 4*limbcount
118 ;; rsi = bufY + 4*limbcount + 4*carry_last_time
119
120 ; setc [rdi]
123 0000002A 0F92C2 setc dl
124 0000002D 8917 mov [edi], edx ; store the carry-out into an extra limb beyond limbcount
125 0000002F C1E202 shl edx, 2
139 ; keep -1024 in ebx. Using bl for the limb counter leaves bl zero here, so it's back to -1024 (or -2048 or whatever)
142 00000032 89E0 mov eax, esp ; test/setnz could work, but only saves a byte if we can somehow avoid the or dl,al
143 00000034 2404 and al, 4 ; only works if limbcount is even, otherwise we'd need to subtract limbcount first.
148 00000036 87FC xchg edi, esp ; Fibonacci: dst and src swap
149 00000038 21DC and esp, ebx ; -1024 ; revert to start of buffer, regardless of offset
150 0000003A 21DF and edi, ebx ; -1024
151
152 0000003C 01D4 add esp, edx ; read offset in src
155 ;; after adjusting src, so this only affects read-offset in the dst, not src.
156 0000003E 08C2 or dl, al ; also set r8d if we had a source offset last time, to handle the 2nd buffer
157 ;; clears CF for next iter
165 00000040 E2D2 loop .fibonacci ; Maybe 0.01% slower than dec/jnz overall
169 to_string:
175 stringdigits equ 9*limbcount ; + 18
176 ;;; edi and esp are pointing to the start of buffers, esp to the one most recently written
177 ;;; edi = esp +/- 2048, which is far enough away even in the worst case where they're growing towards each other
178 ;;; update: only 1024 apart, so this only works for even iteration-counts, to prevent overlap
180 ; ecx = 0 from the end of the fib loop
181 ;and ebp, 10 ; works because the low byte of 999999999 is 0xff
182 00000042 8D690A lea ebp, [ecx+10] ;mov ebp, 10
183 00000045 B172 mov cl, (stringdigits+8)/9
184 .toascii: ; slow but only used once, so we don't need a multiplicative inverse to speed up div by 10
185 ;add eax, [rsi] ; eax has the carry from last limb: 0..3 (base 4 * 10**9)
186 00000047 58 pop eax ; lodsd
187 00000048 B309 mov bl, 9
188 .toascii_digit:
189 0000004A 99 cdq ; edx=0 because eax can't have the high bit set
190 0000004B F7F5 div ebp ; edx=remainder = low digit = 0..9. eax/=10
197 0000004D 80C230 add dl, '0'
198 ; stosb ; clobber [rdi], then inc rdi
199 00000050 4F dec edi ; store digits in MSD-first printing order, working backwards from the end of the string
200 00000051 8817 mov [edi], dl
201
202 00000053 FECB dec bl
203 00000055 75F3 jnz .toascii_digit
204
205 00000057 E2EE loop .toascii
206
207 ; Upper bytes of eax=0 here. Also AL I think, but that isn't useful
208 ; ebx = -1024
209 00000059 29DA sub edx, ebx ; edx = 1024 + 0..9 (leading digit). +0 in the Fib(10**9) case
210
211 0000005B B004 mov al, 4 ; SYS_write
212 0000005D 8D58FD lea ebx, [eax-4 + 1] ; fd=1
213 ;mov ecx, edi ; buf
214 00000060 8D4F01 lea ecx, [edi+1] ; Hard-code for Fib(10**9), which has one leading zero in the highest limb.
215 ; shr edx, 1 ; for use with edx=2048
216 ; mov edx, 100
217 ; mov byte [ecx+edx-1], 0xa;'\n' ; count+=1 for newline
218 00000063 CD80 int 0x80 ; write(1, buf+1, 1024)
219
220 00000065 89D8 mov eax, ebx ; SYS_exit=1
221 00000067 CD80 int 0x80 ; exit(ebx=1)
222
# next byte is 0x69, so size = 0x69 = 105 bytes
```
There's probably room to golf some more bytes out of this, but I've already spent at least 12 hours on this over 2 days. **I don't want to sacrifice speed, even though it's way more than fast enough and there is room to make it smaller in ways that cost speed**. Part of my reason for posting is showing how fast I can make a brute-force asm version. If anyone wants to really go for minimum-size but maybe 10x slower (e.g. 1 digit per byte), feel free to copy this as a starting point.
The resulting executable (from `yasm -felf32 -Worphan-labels -gdwarf2 fibonacci-1G.asm && ld -melf_i386 -o fibonacci-1G fibonacci-1G.o`) is 340B (stripped):
```
size fibonacci-1G
text data bss dec hex filename
105 0 0 105 69 fibonacci-1G
```
### Performance
The inner `adc` loop is 10 fused-domain uops on Skylake (+1 stack-sync uop every ~128 bytes), so it can issue at one per ~2.5 cycles on Skylake with optimal front-end throughput (ignoring the stack-sync uops). The critical-path latency is 2 cycles, for the `adc`->`cmp` -> next iteration's `adc` loop-carried dependency chain, so the bottleneck should be the front-end issue limit of ~2.5 cycles per iteration.
`adc eax, [edi + edx]` is 2 unfused-domain uops for the execution ports: load + ALU. It micro-fuses in the decoders (1 fused-domain uop), but [un-laminates in the issue stage to 2 fused-domain uops, because of the indexed addressing mode, even on Haswell/Skylake](https://stackoverflow.com/questions/26046634/micro-fusion-and-addressing-modes/31027695#31027695). I thought it would stay micro-fused, like `add eax, [edi + edx]` does, but maybe keeping indexed addressing modes micro-fused doesn't work for uops that already have 3 inputs (flags, memory, and destination). When I wrote it, I was thinking it wouldn't have a performance downside, but I was wrong. This way of handling of truncation slows down the inner loop every time, whether `edx` is 0 or 4.
It would be faster to handle the read-write offset for the dst by offsetting `edi` and using `edx` to adjust the store. So `adc eax, [edi]` / ... / `mov [edi+edx], eax` / `lea edi, [edi+4]` instead of `stosd`. Haswell and later can keep an indexed store micro-fused. (Sandybridge/IvB would unlaminate it, too.)
**On Intel Haswell and earlier, `adc` and `cmovc` are 2 uops each, with 2c latency**. (`adc eax, [edi+edx]` is still un-laminated on Haswell, and issues as 3 fused-domain uops). Broadwell and later allow 3-input uops for more than just FMA (Haswell), making `adc` and `cmovc` (and a couple other things) single-uop instructions, like they have been on AMD for a long time. (This is one reason AMD has done well in extended-precision GMP benchmarks for a long time.) Anyway, Haswell's inner loop should be 12 uops (+1 stack-sync uop occasionally), with a front-end bottleneck of ~3c per iter best-case, ignoring stack-sync uops.
**Using `pop` without a balancing `push` inside a loop means the loop can't run from the LSD (loop stream detector)**, and has to be re-read from the uop cache into the IDQ every time. If anything, it's a good thing on Skylake, since [a 9 or 10 uop loop doesn't quite issue optimally at 4 uops every cycle](https://stackoverflow.com/questions/39311872/is-performance-reduced-when-executing-loops-whose-uop-count-is-not-a-multiple-of). This is probably part of why replacing `lodsd` with `pop` helped so much. (The LSD can't lock down the uops because that wouldn't leave room to insert a [stack-sync uop](https://stackoverflow.com/questions/36631576/what-is-the-stack-engine-in-the-sandybridge-microarchitecture).) (BTW, a microcode update disables the LSD entirely on Skylake and Skylake-X to fix an erratum. I measured the above before getting that update.)
I profiled it on Haswell, and found that it runs in 381.31 billion clock cycles (regardless of CPU frequency, since it only uses L1D cache, not memory). Front-end issue throughput was 3.72 fused-domain uops per clock, vs. 3.70 for Skylake. (But of course instructions per cycle was down to 2.42 from 2.87, because `adc` and `cmov` are 2 uops on Haswell.)
`push` to replace `stosd` probably wouldn't help as much, because `adc [esp + edx]` would trigger a stack-sync uop every time. And would cost a byte for `std` so `lodsd` goes the other direction. (`mov [edi], eax` / `lea edi, [edi+4]` to replace `stosd` is a win, going from 32,909Mcycles for 100M iters to 31,954Mcycles for 100M iters. It seems that `stosd` decodes as 3 uops, with the store-address/store-data uops not micro-fused, so `push` + stack-sync uops might still be faster than `stosd`)
**The actual performance of ~322.47 billion cycles for 1G iterations of 114 limbs works out to 2.824 cycles per iteration of the inner loop**, for the fast 105B version on Skylake. (See `ocperf.py` output below). That's slower than I predicted from static analysis, but I was ignoring the overhead of the outer-loop and any stack-sync uops.
Perf counters for `branches` and `branch-misses` show that the inner loop mispredicts once per outer loop (on the last iteration, when it's not taken). That also accounts for part of the extra time.
---
**I could save code-size by making the inner-most loop have 3-cycle latency for the critical path, using `mov esi,eax`/`sub eax,ebp`/`cmovc eax, esi`/`cmc`** (2+2+3+1 = 8B) instead of `lea esi, [eax - 1000000000]`/`cmp ebp,eax`/`cmovc` (6+2+3 = 11B). The `cmov`/`stosd` is off the critical path. (The increment-edi uop of `stosd` can run separately from the store, so each iteration forks off a short dependency chain.) It used to save another 1B by changing the ebp init instruction from `lea ebp, [ecx-1]` to `mov ebp,eax`, but I discovered that having the wrong `ebp` didn't change the result. This would let a limb be exactly == 1000000000 instead of wrapping and producing a carry, but this error propagates slower than we Fib() grows, so this happens not to change the leading 1k digits of the final result. Also, I think that error can correct itself when we're just adding, since there's room in a limb to hold it without overflow. Even 1G + 1G doesn't overflow a 32-bit integer, so it will eventually percolate upwards or be truncated away.
The 3c latency version is 1 extra uop, so the front-end can issue it at one per 2.75c cycles on Skylake, only slightly faster than the back-end can run it. (On Haswell, it will be 13 uops total since it still uses `adc` and `cmov`, and bottleneck on the front-end at 3.25c per iter).
In practice it runs a factor of 1.18 slower on Skylake (3.34 cycles per limb), rather than 3/2.5 = 1.2 that I predicted for replacing the front-end bottleneck with the latency bottleneck from just looking at the inner loop without stack-sync uops. Since the stack-sync uops only hurt the fast version (bottlenecked on the front-end instead of latency), it doesn't take much to explain it. e.g. 3/2.54 = 1.18.
Another factor is that the 3c latency version may detect the mispredict on leaving the inner loop while the critical path is still executing (because the front-end can get ahead of the back-end, letting out-of-order execution run the loop-counter uops), so the effective mispredict penalty is lower. Losing those front-end cycles lets the back-end catch up.
If it wasn't for that, we could maybe speed up the 3c `cmc` version by using a branch in the outer loop instead of branchless handling of the carry\_out -> edx and esp offsets. Branch-prediction + speculative execution for a control dependency instead of a data dependency could let the next iteration start running the `adc` loop while uops from the previous inner loop were still in flight. In the branchless version, the load addresses in the inner loop have a data dependency on CF from the last `adc` of the last limb.
The 2c latency inner-loop version bottlenecks on the front-end, so the back-end pretty much keeps up. If the outer-loop code was high-latency, the front-end could get ahead issuing uops from the next iteration of the inner loop. (But in this case the outer-loop stuff has plenty of [ILP](https://en.wikipedia.org/wiki/Instruction-level_parallelism) and no high-latency stuff, so the back-end doesn't have much catching up to do when it starts chewing through uops in the out-of-order scheduler as their inputs become ready).
```
### Output from a profiled run
$ asm-link -m32 fibonacci-1G.asm && (size fibonacci-1G; echo disas fibonacci-1G) && ocperf.py stat -etask-clock,context-switches:u,cpu-migrations:u,page-faults:u,cycles,instructions,uops_issued.any,uops_executed.thread,uops_executed.stall_cycles -r4 ./fibonacci-1G
+ yasm -felf32 -Worphan-labels -gdwarf2 fibonacci-1G.asm
+ ld -melf_i386 -o fibonacci-1G fibonacci-1G.o
text data bss dec hex filename
106 0 0 106 6a fibonacci-1G
disas fibonacci-1G
perf stat -etask-clock,context-switches:u,cpu-migrations:u,page-faults:u,cycles,instructions,cpu/event=0xe,umask=0x1,name=uops_issued_any/,cpu/event=0xb1,umask=0x1,name=uops_executed_thread/,cpu/event=0xb1,umask=0x1,inv=1,cmask=1,name=uops_executed_stall_cycles/ -r4 ./fibonacci-1G
79523178745546834678293851961971481892555421852343989134530399373432466861825193700509996261365567793324820357232224512262917144562756482594995306121113012554998796395160534597890187005674399468448430345998024199240437534019501148301072342650378414269803983873607842842319964573407827842007677609077777031831857446565362535115028517159633510239906992325954713226703655064824359665868860486271597169163514487885274274355081139091679639073803982428480339801102763705442642850327443647811984518254621305295296333398134831057713701281118511282471363114142083189838025269079177870948022177508596851163638833748474280367371478820799566888075091583722494514375193201625820020005307983098872612570282019075093705542329311070849768547158335856239104506794491200115647629256491445095319046849844170025120865040207790125013561778741996050855583171909053951344689194433130268248133632341904943755992625530254665288381226394336004838495350706477119867692795685487968552076848977417717843758594964253843558791057997424878788358402439890396,�X\�;3�I;ro~.�'��R!q��%��X'B �� 8w��▒Ǫ�
... repeated 3 more times, for the 3 more runs we're averaging over
Note the trailing garbage after the trailing digits.
Performance counter stats for './fibonacci-1G' (4 runs):
73438.538349 task-clock:u (msec) # 1.000 CPUs utilized ( +- 0.05% )
0 context-switches:u # 0.000 K/sec
0 cpu-migrations:u # 0.000 K/sec
2 page-faults:u # 0.000 K/sec ( +- 11.55% )
322,467,902,120 cycles:u # 4.391 GHz ( +- 0.05% )
924,000,029,608 instructions:u # 2.87 insn per cycle ( +- 0.00% )
1,191,553,612,474 uops_issued_any:u # 16225.181 M/sec ( +- 0.00% )
1,173,953,974,712 uops_executed_thread:u # 15985.530 M/sec ( +- 0.00% )
6,011,337,533 uops_executed_stall_cycles:u # 81.855 M/sec ( +- 1.27% )
73.436831004 seconds time elapsed ( +- 0.05% )
```
`( +- x %)` is the standard-deviation over the 4 runs for that count. Interesting that it runs such a round number of instructions. That 924 billion is *not* a coincidence. I guess that the outer loop runs a total of 924 instructions.
`uops_issued` is a fused-domain count (relevant for front-end issue bandwidth), while `uops_executed` is an unfused-domain count (number of uops sent to execution ports). Micro-fusion packs 2 unfused-domain uops into one fused-domain uop, but [mov-elimination](https://stackoverflow.com/questions/44169342/can-x86s-mov-really-be-free-why-cant-i-reproduce-this-at-all) means that some fused-domain uops don't need any execution ports. See the linked question for more about counting uops and fused vs. unfused domain. (Also see [Agner Fog's instruction tables and uarch guide](http://agner.org/optimize/), and other useful links in the SO [x86 tag wiki](https://stackoverflow.com/tags/x86/info)).
From another run measuring different things: L1D cache misses are totally insignificant, as expected for reading/writing the same two 456B buffers. The inner-loop branch mispredicts once per outer loop (when it's not-taken to leave the loop). (The total time is higher because the computer wasn't totally idle. Probably the other logical core was active some of the time, and more time was spent in interrupts (since the user-space-measured frequency was farther below 4.400GHz). Or multiple cores were active more of the time, lowering the max turbo. I didn't track `cpu_clk_unhalted.one_thread_active` to see if HT competition was an issue.)
```
### Another run of the same 105/106B "main" version to check other perf counters
74510.119941 task-clock:u (msec) # 1.000 CPUs utilized
0 context-switches:u # 0.000 K/sec
0 cpu-migrations:u # 0.000 K/sec
2 page-faults:u # 0.000 K/sec
324,455,912,026 cycles:u # 4.355 GHz
924,000,036,632 instructions:u # 2.85 insn per cycle
228,005,015,542 L1-dcache-loads:u # 3069.535 M/sec
277,081 L1-dcache-load-misses:u # 0.00% of all L1-dcache hits
0 ld_blocks_partial_address_alias:u # 0.000 K/sec
115,000,030,234 branches:u # 1543.415 M/sec
1,000,017,804 branch-misses:u # 0.87% of all branches
```
My code may well run in fewer cycles on Ryzen, which can issue 5 uops per cycle (or 6 when some of them are 2-uop instructions, like AVX 256b stuff on Ryzen). I'm not sure what its front-end would do with `stosd`, which is 3 uops on Ryzen (same as Intel). I think the other instructions in the inner loop are the same latency as Skylake and all single-uop. (Including `adc eax, [edi+edx]`, which is an advantage over Skylake).
---
**This could probably be significantly smaller, but maybe 9x slower, if I stored the numbers as 1 decimal digit per byte**. Generating carry-out with `cmp` and adjusting with `cmov` would work the same, but do 1/9th the work. 2 decimal digits per byte (base-100, not 4-bit BCD with a [slow `DAA`](http://felixcloutier.com/x86/DAA.html)) would also work, and `div r8` / `add ax, 0x3030` turns a 0-99 byte into two ASCII digits in printing order. But 1 digit per byte doesn't need `div` at all, just looping and adding 0x30. If I store the bytes in printing order, that would make the 2nd loop really simple.
---
Using 18 or 19 decimal digits per 64-bit integer (in 64-bit mode) would make it run about twice as fast, but cost significant code-size for all the REX prefixes, and for 64-bit constants. 32-bit limbs in 64-bit mode prevents using `pop eax` instead of `lodsd`. I could still avoid REX prefixes by using `esp` as a non-pointer scratch register (swapping the usage of `esi` and `esp`), instead of using `r8d` as an 8th register.
If making a callable-function version, converting to 64-bit and using `r8d` may be cheaper than saving/restoring `rsp`. 64-bit also can't use the one-byte `dec r32` encoding (since it's a REX prefix). But mostly I ended up using `dec bl` which is 2 bytes. (Because I have a constant in the upper bytes of `ebx`, and only use it outside of inner loops, which works because the low byte of the constant is `0x00`.)
---
### High-performance version
For maximum performance (not code-golf), you'd want to unroll the inner loop so it runs at most 22 iterations, which is a short enough taken/not-taken pattern for the branch-predictors to do well. In my experiments, `mov cl, 22` before a `.inner: dec cl/jnz .inner` loop has very few mispredicts (like 0.05%, far less than one per full run of the inner loop), but `mov cl,23` mispredicts from 0.35 to 0.6 times per inner loop. `46` is particularly bad, mispredicting ~1.28 times per inner-loop (128M times for 100M outer-loop iterations). `114` mispredicted exactly once per inner loop, same as I found as part of the Fibonacci loop.
I got curious and tried it, unrolling the inner loop by 6 with a `%rep 6` (because that divides 114 evenly). That mostly eliminated branch-misses. I made `edx` negative and used it as an offset for `mov` stores, so `adc eax,[edi]` could stay micro-fused. (And so I could avoid `stosd`). I pulled the `lea` to update `edi` out of the `%rep` block, so it only does one pointer-update per 6 stores.
I also got rid of all the partial-register stuff in the outer loop, although I don't think that was significant. It may have helped slightly to have CF at end of the outer loop not dependent on the final ADC, so some of the inner-loop uops can get started. The outer-loop code could probably be optimized a bit more, since `neg edx` was the last thing I did, after replacing `xchg` with just 2 `mov` instructions (since I already still had 1), and re-arranging the dep chains along with dropping the 8-bit register stuff.
This is the NASM source of just the Fibonacci loop. It's a drop-in replacement for that section of the original version.
```
;;;; Main loop, optimized for performance, not code-size
%assign unrollfac 6
mov bl, limbcount/unrollfac ; and at the end of the outer loop
align 32
.fibonacci:
limbcount equ 114 ; 112 = 1006 decimal digits / 9 digits per limb. Not enough for 1000 correct digits, but 114 is.
; 113 would be enough, but we depend on limbcount being even to avoid a sub
; align 8
.digits_add:
%assign i 0
%rep unrollfac
;lodsd ; Skylake: 2 uops. Or pop rax with rsp instead of rsi
; mov eax, [esp]
; lea esp, [esp+4] ; adjust ESP without affecting CF. Alternative, load relative to edi and negate an offset? Or add esp,4 after adc before cmp
pop eax
adc eax, [edi+i*4] ; read from a potentially-offset location (but still store to the front)
;; jz .out ;; Nope, a zero digit in the result doesn't mean the end! (Although it might in base 10**9 for this problem)
lea esi, [eax - 1000000000]
cmp ebp, eax ; sets CF when (base-1) < eax. i.e. when eax>=base
cmovc eax, esi ; eax %= base, keeping it in the [0..base) range
%if 0
stosd
%else
mov [edi+i*4+edx], eax
%endif
%assign i i+1
%endrep
lea edi, [edi+4*unrollfac]
dec bl ; preserves CF. The resulting partial-flag merge on ADC would be slow on pre-SnB CPUs
jnz .digits_add
; bl=0, ebx=-1024
; esi has its high bit set opposite to CF
.end_innerloop:
;; after a non-zero carry-out (CF=1): right-shift both buffers by 1 limb, over the course of the next two iterations
;; next iteration with r8 = 1 and rsi+=4: read offset from both, write normal. ends with CF=0
;; following iter with r8 = 1 and rsi+=0: read offset from dest, write normal. ends with CF=0
;; following iter with r8 = 0 and rsi+=0: i.e. back to normal, until next carry-out (possible a few iters later)
;; rdi = bufX + 4*limbcount
;; rsi = bufY + 4*limbcount + 4*carry_last_time
; setc [rdi]
; mov dl, dh ; edx=0. 2c latency on SKL, but DH has been ready for a long time
; adc edx,edx ; edx = CF. 1B shorter than setc dl, but requires edx=0 to start
setc al
movzx edx, al
mov [edi], edx ; store the carry-out into an extra limb beyond limbcount
shl edx, 2
;; Branching to handle the truncation would break the data-dependency (of pointers) on carry-out from this iteration
;; and let the next iteration start, but we bottleneck on the front-end (9 uops)
;; not the loop-carried dependency of the inner loop (2 cycles for adc->cmp -> flag input of adc next iter)
;; Since the pattern isn't perfectly regular, branch mispredicts would hurt us
; keep -1024 in ebx. Using bl for the limb counter leaves bl zero here, so it's back to -1024 (or -2048 or whatever)
mov eax, esp
and esp, 4 ; only works if limbcount is even, otherwise we'd need to subtract limbcount first.
and edi, ebx ; -1024 ; revert to start of buffer, regardless of offset
add edi, edx ; read offset in next iter's src
;; maybe or edi,edx / and edi, 4 | -1024? Still 2 uops for the same work
;; setc dil?
;; after adjusting src, so this only affects read-offset in the dst, not src.
or edx, esp ; also set r8d if we had a source offset last time, to handle the 2nd buffer
mov esp, edi
; xchg edi, esp ; Fibonacci: dst and src swap
and eax, ebx ; -1024
;; mov edi, eax
;; add edi, edx
lea edi, [eax+edx]
neg edx ; negated read-write offset used with store instead of load, so adc can micro-fuse
mov bl, limbcount/unrollfac
;; Last instruction must leave CF clear for next iter
; loop .fibonacci ; Maybe 0.01% slower than dec/jnz overall
; dec ecx
sub ecx, 1 ; clear any flag dependencies. No faster than dec, at least when CF doesn't depend on edx
jnz .fibonacci
```
Performance:
```
Performance counter stats for './fibonacci-1G-performance' (3 runs):
62280.632258 task-clock (msec) # 1.000 CPUs utilized ( +- 0.07% )
0 context-switches:u # 0.000 K/sec
0 cpu-migrations:u # 0.000 K/sec
3 page-faults:u # 0.000 K/sec ( +- 12.50% )
273,146,159,432 cycles # 4.386 GHz ( +- 0.07% )
757,088,570,818 instructions # 2.77 insn per cycle ( +- 0.00% )
740,135,435,806 uops_issued_any # 11883.878 M/sec ( +- 0.00% )
966,140,990,513 uops_executed_thread # 15512.704 M/sec ( +- 0.00% )
75,953,944,528 resource_stalls_any # 1219.544 M/sec ( +- 0.23% )
741,572,966 idq_uops_not_delivered_core # 11.907 M/sec ( +- 54.22% )
62.279833889 seconds time elapsed ( +- 0.07% )
```
That's for the same Fib(1G), producing the same output in 62.3 seconds instead of 73 seconds. (273.146G cycles, vs. 322.467G. Since everything hits in L1 cache, core clock cycles is really all we need to look at.)
Note the much lower total `uops_issued` count, well below the `uops_executed` count. That means many of them were micro-fused: 1 uop in the fused domain (issue/ROB), but 2 uops in the unfused domain (scheduler / execution units)). And that few were eliminated in the issue/rename stage (like `mov` register copying, or `xor`-zeroing, which need to issue but don't need an execution unit). Eliminated uops would unbalance the count the other way.
`branch-misses` is down to ~400k, from 1G, so unrolling worked. `resource_stalls.any` is significant now, which means the front-end is not the bottleneck anymore: instead the back-end is getting behind and limiting the front-end. `idq_uops_not_delivered.core` only counts cycles where the front-end didn't deliver uops, but the back-end *wasn't* stalled. That's nice and low, indicating few front-end bottlenecks.
---
Fun fact: the python version spends more than half its time dividing by 10 rather than adding. (Replacing the `a/=10` with `a>>=64` speeds it up by more than a factor of 2, but changes the result because binary truncation != decimal truncation.)
My asm version is of course optimized specifically for this problem-size, with the loop iteration-counts hard coded. Even shifting an arbitrary-precision number will copy it, but my version can just read from an offset for the next two iterations to skip even that.
**I profiled the python version** (64-bit python2.7 on Arch Linux):
```
ocperf.py stat -etask-clock,context-switches:u,cpu-migrations:u,page-faults:u,cycles,instructions,uops_issued.any,uops_executed.thread,arith.divider_active,branches,branch-misses,L1-dcache-loads,L1-dcache-load-misses python2.7 ./fibonacci-1G.anders-brute-force.py
795231787455468346782938519619714818925554218523439891345303993734324668618251937005099962613655677933248203572322245122629171445627564825949953061211130125549987963951605345978901870056743994684484303459980241992404375340195011483010723426503784142698039838736078428423199645734078278420076776090777770318318574465653625351150285171596335102399069923259547132267036550648243596658688604862715971691635144878852742743550811390916796390738039824284803398011027637054426428503274436478119845182546213052952963333981348310577137012811185112824713631141420831898380252690791778709480221775085968511636388337484742803673714788207995668880750915837224945143751932016258200200053079830988726125702820190750937055423293110708497685471583358562391045067944912001156476292564914450953190468498441700251208650402077901250135617787419960508555831719090539513446891944331302682481336323419049437559926255302546652883812263943360048384953507064771198676927956854879685520768489774177178437585949642538435587910579974100118580
Performance counter stats for 'python2.7 ./fibonacci-1G.anders-brute-force.py':
755380.697069 task-clock:u (msec) # 1.000 CPUs utilized
0 context-switches:u # 0.000 K/sec
0 cpu-migrations:u # 0.000 K/sec
793 page-faults:u # 0.001 K/sec
3,314,554,673,632 cycles:u # 4.388 GHz (55.56%)
4,850,161,993,949 instructions:u # 1.46 insn per cycle (66.67%)
6,741,894,323,711 uops_issued_any:u # 8925.161 M/sec (66.67%)
7,052,005,073,018 uops_executed_thread:u # 9335.697 M/sec (66.67%)
425,094,740,110 arith_divider_active:u # 562.756 M/sec (66.67%)
807,102,521,665 branches:u # 1068.471 M/sec (66.67%)
4,460,765,466 branch-misses:u # 0.55% of all branches (44.44%)
1,317,454,116,902 L1-dcache-loads:u # 1744.093 M/sec (44.44%)
36,822,513 L1-dcache-load-misses:u # 0.00% of all L1-dcache hits (44.44%)
755.355560032 seconds time elapsed
```
Numbers in (parens) are how much of the time that perf counter was being sampled. When looking at more counters than the HW supports, perf rotates between different counters and extrapolates. That's totally fine for a long run of the same task.
If I ran `perf` after setting sysctl `kernel.perf_event_paranoid = 0` (or running `perf` as root), it would measure `4.400GHz`. `cycles:u` doesn't count time spent in interrupts (or system calls), only user-space cycles. My desktop was almost totally idle, but this is typical.
[Answer]
# Haskell, ~~83~~ 61 bytes
```
p(a,b)(c,d)=(a*d+b*c-a*c,a*c+b*d)
t g=g.g.g
t(t$t=<<t.p)(1,1)
```
Outputs (*F*1000000000,*F*1000000001). On my laptop, it correctly prints the left paren and the first 1000 digits within 133 seconds, using 1.35 GiB of memory.
### How it works
The Fibonacci recurrence can be solved using matrix exponentiation:
[*F**i* − 1, *F**i*; *F**i*, *F**i* + 1] = [0, 1; 1, 1]*i*,
from which we derive these identities:
[*F**i* + *j* − 1, *F**i* + *j*; *F**i* + *j*, *F**i* + *j* + 1] = [*F**i* − 1, *F**i*; *F**i*, *F**i* + 1] ⋅ [*F**j* − 1, *F**j*; *F**j*, *F**j* + 1],
*F**i* + *j* = *F**i* + 1*F**j* + 1 − *F**i* − 1*F**j* − 1 = *F**i* + 1*F**j* + 1 − (*F**i* + 1 − *F**i*)(*F**j* + 1 − *F**j*),
*F**i* + *j* + 1 = *F**i**F**j* + *F**i* + 1*F**j* + 1.
The `p` function computes (*F**i* + *j*, *F**i* + *j* + 1) given (*F**i*, *F**i* + 1) and (*F**j*, *F**j* + 1). Writing `f n` for (*F**i*, *F**i* + 1), we have `p (f i) (f j)` = `f (i + j)`.
Then,
`(t=<<t.p) (f i)`
= `t ((t.p) (f i)) (f i)`
= `t (p (f i).p (f i).p (f i)) (f i)`
= `(p (f i).p (f i).p (f i).p (f i).p (f i).p (f i).p (f i).p (f i).p (f i)) (f i)`
= `f (10 * i)`,
`(t$t=<<t.p) (f i)`
= `((t=<<t.p).(t=<<t.p).(t=<<t.p)) (f i)`
= `f (10^3 * i)`,
`t(t$t=<<t.p) (f i)`
= `((t$t=<<t.p).(t$t=<<t.p).(t$t=<<t.p)) (f i)`
= `f (10^9 * i)`,
and we plug in `f 1` = `(1,1)`.
[Answer]
# Mathematica, 15 ~~34~~ bytes
`Fibonacci` **itself** takes ~6s on my computer. And 95(+/-5)s for frontend to display it.
```
Fibonacci@1*^9&
```
[![enter image description here](https://i.stack.imgur.com/3RJR5.png)](https://i.stack.imgur.com/3RJR5.png)
The first 1000 digits (34 bytes): `⌊Fibonacci@1*^9/1*^208986640⌋&`
[![test 1](https://i.stack.imgur.com/0H4OU.png)](https://i.stack.imgur.com/0H4OU.png)
Longer but faster `ToString@Fibonacci@1*^9~StringTake~1000&`:
[![test screenshot](https://i.stack.imgur.com/vcZTn.png)](https://i.stack.imgur.com/vcZTn.png)
[Answer]
# Python 2, 70 bytes
```
a,b=0,1
i=1e9
while i:
a,b=b,a+b;i-=1
if a>>3360:a/=10;b/=10
print a
```
This ran in 18 minutes and 31 seconds on my laptop, producing the correct 1000 digits followed by `74100118580` (the correct following digits are `74248787892`).
[Answer]
# [Haskell](https://www.haskell.org/), 78 bytes
```
(a%b)n|n<1=b|odd n=b%(a+b)$n-1|r<-2*a*b-a*a=r%(a*a+b*b)$div n 2
1%0$2143923439
```
[Try it online!](https://tio.run/##DcnBCoMwDADQ@74ihxY0UrDVy8B8TEKVlWmUOnbqv9de3uV9@P6u@15rx1Z6Lbp4knLGCEpiOx6kN@p8yYsLyCiOkSm3wFbYMqY/KITXRt6OJvh5eoepUQ9OCgRXTvoDA1t9AA "Haskell – Try It Online")
Took 48 seconds on TIO. Same recursive formula as [my Python answer](https://codegolf.stackexchange.com/a/133647/20260), but without truncating.
The constant `2143923439` is `10**9-1`, reversed in binary, and with an extra 1 at the end. Iterating through its binary digits in reverse simulates iterating through the binary digits of `10**9-1`. It seems shorter to hardcode this than to compute it.
[Answer]
# [Haskell](https://www.haskell.org/), ~~202~~ ~~184~~ ~~174~~ ~~173~~ ~~170~~ ~~168~~ ~~164~~ 162 bytes
```
(a,b)!(c,d)=a*c+b*d
l x=((34,55)!x,(55,89)!x)
f(a,b)|x<-l(a,b)=(x!l(b-a,a),x!x)
r=l.f
k=f.f.f
j=f.r.r.r.r
main=print$take 1000$show$fst$f$r$k$k$r$k$j$f$r$j$r(0,1)
```
[Try it online!](https://tio.run/##JYrbCoMwEETf8xUK@7BpV4m0gRaaj1kvQU1qSxSah/57Gi0HZs7AjLy6wfuUkKmVJXbUS8On7tyeeuGLaBAvV9JalpFQa7rds0lhj/s3Pip/mMFYemwrJpYU90cwvrbCGVtnxJw7/BFPnhbzDtOywcZuKBqlFKzj6wN23cBCAJfZcz7WDAEVNTKlHw "Haskell – Try It Online")
## Explanation
This uses a rather fast way to calculate fibonacci numbers. The function `l` takes two fibonacci numbers and calculates the fibonacci numbers 10 later, while `f` takes the **n**th and **n+1**th fibonacci numbers and calculates the **2n+20**th and **2n+21**th fibonacci numbers. I chain them rather haphazardly to get 1 billion and grab the first 1000 digits.
[Answer]
# T-SQL, ~~422 414~~ 453 bytes (Verified, now competing!)
**EDIT 2**: Changed to ~~`INT BIGINT`~~ `DECIMAL(37,0)`, Gained a few bytes but increased speed enough to complete to 1 billion! Completed in **45 hours 29 minutes**, verifies against the given string, and displays an additional 8 characters (which may or may not be right due to rounding errors).
T-SQL has no native "huge number" support, so had to roll my own text-based huge number adder using 1008-character strings:
```
DECLARE @a char(1008)=REPLICATE('0',1008),@ char(1008)=REPLICATE('0',1007)+'1',@c varchar(max),@x bigint=1,@y int,@t varchar(37),@f int=0o:SELECT @x+=1,@c='',@y=1i:SELECT @t=CONVERT(DECIMAL(37,0),RIGHT(@a,36))+CONVERT(DECIMAL(37,0),RIGHT(@,36))+@f,@a=RIGHT(@a,36)+@a,@=RIGHT(@,36)+@,@c=RIGHT(REPLICATE('0',36)+@t,36)+@c,@y+=1IF LEN(@t)>36SET @f=1 ELSE SET @f=0IF @y<29GOTO i
IF @f=1SELECT @a='0'+@,@='1'+@c ELSE SELECT @a=@,@=@c
If @x<1e9 GOTO o
PRINT @
```
Here's the formatted version with comments:
```
DECLARE @a char(1008)=REPLICATE('0',1008) --fib(a), have to manually fill
,@ char(1008)=REPLICATE('0',1007)+'1' --fib(b), shortened variable
,@c varchar(max), @x bigint=1, @y int, @t varchar(37), @f int=0
o: --outer loop
SELECT @x+=1, @c='', @y=1
i: --inner loop
SELECT @t=CONVERT(DECIMAL(37,0),RIGHT(@a,36)) --adds last chunk of string
+CONVERT(DECIMAL(37,0),RIGHT(@,36)) + @f
,@a=RIGHT(@a,36)+@a --"rotates" the strings
,@=RIGHT(@,36)+@
,@c=RIGHT(REPLICATE('0',36)+@t,36)+@c --combines result
,@y+=1
IF LEN(@t)>36 SET @f=1 ELSE SET @f=0 --flag for carrying the 1
IF @y<29 GOTO i --28 * 36 digits = 1008 places
IF @f=1 SELECT @a='0'+@, @='1'+@c --manually carries the 1
ELSE SELECT @a=@, @=@c
If @x<1e9 GOTO o
PRINT @
```
Basically I'm manually manipulating 1008-character zero-filled strings representing my two Fibonacci variables, `@a` and `@`.
I add them ~~8 18~~ 36 digits at a time, by stripping off the last 36 digits, converting to a manageable numeric type (`DECIMAL(37,0)`), adding them up, then smashing it back into another long string `@c`. I then "rotate" `@a` and `@` by moving the last 36 digits to the front, and repeating the process. 28 rotations \* 36 digits covers all 1008. I have to "carry the one" manually.
Once our number starts to exceed my string length, I "shift left" and we start to lose some precision, but the error is well within my extra characters.
I tried using a SQL table full of INTs and BIGINTs, with similar logic, and it was *dramatically* slower. Weird.
[Answer]
# Haskell, 81 bytes
```
f n|n<3=1|even n=fk*(2*f(k+1)-fk)|1>0=f(k+1)^2+fk^2 where k=n`div`2;fk=f k
f$10^9
```
**Explanation**
`f n` recursively computes the `n`th fibonacci number using the recurrence from xnor's answer with common-subexpression elimination. Unlike the other solutions which have been posted, which use O(log(n)) multiplications, we have a O(log(n))-depth recursion with a branching factor of 2, for a complexity of O(n) multiplications.
However, all is not lost! Because almost all calls will be near the bottom of the recursion tree, we can use fast native arithmetic where possible and avoid lots of manipulation of huge bignums. It spits out an answer in a couple of minutes on my machine.
[Answer]
## PARI/GP, 45 bytes
```
\p1100
s=sqrt(5)
((1+s)/2)^1e9/s/1e208986640
```
Somehow `\p1000` isn't enough. This doesn't work with 32 bit systems. The final division is to avoid the decimal point in scientific notation.
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 15 + 5 = 20 bytes
```
fibonacci(10^9)
```
Run with the command line option `-s1g` to allocate 1 Gbytes of memory.
[Answer]
# Ruby, 63 bytes
man, I'm bad at golfing ruby; but the BigInt class does wonders for this kind of stuff. We use the same algorithm as Anders Kaseorg.
```
require 'matrix'
m=Matrix
puts m[[1,1],[1,0]]**10**9*m[[1],[1]]
```
[Answer]
# x86 .COM, ~~62~~ ~~61~~ ~~56~~ 55 bytes
```
org $100
mov di, $8000
mov ds, di
mov es, di
mov cx, di
xor ax, ax
xor si, si
rep stosw
mov ecx, 1000000000
;mov ecx, 6
stc
lop:
mov bx, ds
adding:
lodsb
adc al, [di]
aaa
stosb
dec bx
jnz adding
jnc nocy
and [si], byte 0
lodsb
inc ax
stosb
nocy:
loopd lop
std
mov si, di
dec si
delta:
lodsb
add al, '0'
int $29
loop delta
ret
```
Should run more than one day, keep 32768 digits of precision of both number
Ran for 165979.100 seconds, result [here](https://tio.run/##PN1rjiTNbqThLUVExnU5kgABggD9EKD1S3xer08zZ@b06a7KjIs7nTSaGf/1v//lP/7r3//n3/7zf//3@a7jtz/vc17Xeb@/837e4/u91/7d@/fs57u/33HNPx77Oz96/r7323/n9dt@3/d75i@O877fe3@P@Z3fs23X9n3ffdz7776u@3m@3/zIe2y/6zl@x3Gc134c9/Ht8@nndR/Pdc8/X9/5ffOp937s@/7b9vnS@Zv3@e7fd@33ds2Xfs/7bfvrS@5nLuWbSz7P95yLmX/83u049@87zu38PfPz2/5d2z73MB@3zZefx31tv@c99/nT/PTcy@99fvc2f3XMf37zy/d5zU3N3xz@ctueuYN7@7bH/9l@@zv/uZ7zvK/7@t3H9bv2/dqOeWDPfs21zv/ejrmy7Z4L@c1tXeezz23f88vzPDb3ev7mJ@/rvd/33s53HsH86rPf337Pr88NPe886@ec//zmV955Ht82/9iz2J5fV3645PnT/HHucTueex7@dc6dzT/Mbc4vn7/7fOa3v3ee@Tzi8z7myV7HvHNX6lfnVc4dbdczF/nMQ5@fnvvb5w@H675/8/jmaW1u29Pajmse3fbM25tFs31zBccxf56rnHvym/f80vv@fs@8l7mFucL7@c2rnns65ve@a1bL@27zG99@vb9nFsQ3l@eNzfo5tn0e6vzkNv@Zdz6/MW/ve99nFtRxPfOk50e@ft39zrr8zXqdB/Bs7/k9cwlz3fO5v@udtfX79u2ch/585/nt85HzsuaZzOo75r8/C3CbVTcfaCXNczr3WVyzkueOZ62ccxWzgC3Gbf9ddzdtic1ynBu@5nvmtc@7mSudRfqbZTG7Y77r95sHfdzzEOcJzwOZtec7Pnc5C3WW/zX35o3c1zFP67UlfvPPsxhnRfzmWmZlzT3NxT5e4P3c3zGb1f3ZE/Plc2lzze/3zBXND81ynQ9/7aNZAdd8xKyd@VEv9/vmTVhWs3@O/Z7t9Mwj@/bW@@6n5mtnBV2z7p5ZrNe5/975wvnAWQGzVWbZf/NyJwjMC5/ftmDmRcwvzz3N85z9d3rDs8DmAc5CmnV9PL9tluE7F2fRbBNi5mYvvz/7a3bvhJy5jHlUs0Tm9679@s1u8xSswXkjxzyiuZXZfr/9OucRnnOZsyifb7boXMr3m200nz@/Ps9xHoBHMMFnYos1Ort9nt3c1fz2PPFtvmCft315Ouv9zg3OJc9znl@b/z2fP//js5vPY9bVfM988CzId6LhZll/84gmtj0izLHNP@8i1mzd@f57rnf@65sreyYOzS9YdvMAnl8PZHbgLIHZorMC7tnuc@8TG@eK7n1izvz3b9bORMcJE8cs@vueBT63OKvn2ecbZ7GKtM8E4dkDu6/28j3zCSiz4Gd5iWS74PbO65zwPe9w9tQ8jPm0WaBzK@8hCM0yahXPe7s@j/7nsU7sbytMbNjmUUwQsIn8r3f2ysTD@ee50Ll5e352@LzBiWH7z9P5fmtfzNaatyIgzefMO5tjYBboZ6s@s@vmFvZ7n308MW32wKzBeWoTiLb5pHkF86nvfPW5TZw/ZlHPO7P65z5FhFlE871@5hIx5pYm8MyjnOcglr627YRZVzw3YIHN5rQ@inSzH6@5tmPfXN762P2dheWtzjOYNzt/@Lb3ba947bME5n2KIHvRueNgFvb80OySU8CfUObInH0yD/lqEbfK5i4nmmwTa2cv@dSJbXMGzgo4H385MeY6jll0E@4nUM0PPU6705KY7TinwiwqgWGu6nLyzEOcxfMJyredMs9pE4vf2VHvbLHfnBg/L/3@5shy6s7vHA6sR6SaVTJv5nZ4TjAWIc@5SqthYt7p91@rdi6uHeXEmpUwR32H/ASb@ahZYN/2KyL8LOhtLnD@ff5rPmv@7hAIRMR7As3spbmg9@8zf86oXYifhzZnhAPv3jpk54JPx/szb2se0T4BcK7rlHP46LmGufL54XlUs5QkI/MxztX5vHkIgoj0ZTb97LR9TtSJHnNz817mkLz6oSLmtnkl4tw89dlNj@xgwuz87t7B/X6z3OfYm2g5YXNe2iuSTRCaxTiBa35RyJrD3wnyK4V5t9OCnBuaPTjvZd7y/NIE8DmoClIT6s9tdudsslk9P5vsm200K3jOydc5MpmEM3BOgPb1fMNR@HvOvmU2@Sy2uVIRaR6pEDLx3uua1fpz4P08muNzrM0TtZCkPpNxCEJztbMgxQln8VzW3O7ZRpvYMpHocpg6tZ8yn2/uUfo1a0aS9TpU99n/7@z42TEOuUsssqwmjs@bnVXm9C8rmFU/2@sQqY61ZOYZi/0Ct3RottQnq3DyTbibQ/lzRpSmTMibL739H7nD@@7uZ672sgnm377Ol6ME6ydzu6R78@HzROd6rc3jtRznq@Y8nt00vzN74JVSzWL15/na08d8EqF5vu2ruS3/MO9vLvTnAJinMa91wtc5X/aJOK3UWRli6KQY89vzKA7hcU7BS/j/Oa7mEk6Hx2zTuZRZDJ9fmF02FzDPcbbQpF5zVgou8342ifTdm5pTRQ46j2S@dyWD8xTncc7ze2YB3Y7nU3STIj1i3Xd5fLPnN5F2PnpShrn8R1Y@F/v6vPbJPOiJ7L@5sOd20k8qZnnONezW0dzl/MM5MXo@cXbQRJ8JBvMI5pFJPeaZOjzm1iaEzBLxQ7biJgeRr8@ynpubhGC@ZV6X0@j2aifQz41KLDa3OufLvG2R@fB47by5@Mvp/siUJ2zMhvt5ELOc5DDOpVm1czZMvrTbLBK/iXizMoScuYdZgHNpds28pFkL8/JUNIc8@JH6WEWfvz4FgMtpPInIrMgpcOYhzufP/2sZCvmzpGYdzx47yp4PtzMXNa98fnkCrXR41tIcLhMdTxc6PzeJ4@zoubA5xhxsc15JOiV8h7U/kU5ckw9JSGXP8/Ys0AkJ7RI1yjzaeTa3tHXezASP@cFZafM4pGuzZ2ZnzNY/y9LnrWzyjXlWn4A/l/I5R@Yj3rm6zyO/ZCduft686kPa5@CfvTgn5neWZN8qNum5pGz25TxnCeBczWz0TWL4ODQvAeHnLJuzUrrpLDj2ktB5w/Mc53yV8VoZ8/Q3VdQ8Bo9iDpGJ4vPoeznzU/MCJjOYu3S56qTbUTlvQZD9yaBmp/yklxNENlHKmbOrJzZHwzvLSia2i0YTEefUmLPpVcndLdCJp4q6XUXq3SpJCxmP3T@J3JSLDgGn9@d4nssRhWYJvTK@@fJHcj@3NtHzlQLNA7bU5jB2ono9XxWKe1Id713tbIl5IMfTklsf5PS8HSk/x@os5HlUU6bth42kXDs73Uuk34K1QC2gbUrZzXqYbPx81skwF/UoM/zfDoTZ5xMSDvt9lu2sRaHPnc9KVdrPtppPnc@cJGBueR7a5uif1zbP6fI@HL@z2bbOqPmKQ746e3Ji1@bxfuKlvGUC2SFSbUeR4ufkPFRls6bnlueR3fK/WUOzJHc51eUg/@2FRsmbGl@SNtXxDh44yupO@e68Ap/pKavzJlGY9aPOfOy3yVtE0WqqOVI9byFTMjCLdDaG8mwe5qfKfIQSR@3E7Dkt50MmKCt1HIoBAPPfkxJPPiDv2NUns93mce8VML92gXp7ssoJV3ML80GubJboJ/bMd8@emFJksoivPN7KEwlf5a5YPBvkVBX//IJgZh2dAIAgg3lCs5Ympswb3JWOayXM83sck5tqY17JZcNNJjgbDDwjJ3ol7VN7fz26uav5aQeG3HyudZbVJaZNvJjrl9UDPua5ymrmf8hg5icn75sd77a34qf0eDbWZMOTjZyKUgnerId5wddd@nEIGvMd9uDkHvL8q8rmW/88C9VhrYqcVWcFzq3OI5hFOlvh67C@yxUu@Y0TTDr9WRVleZe6d9bUBdt5ZIYiySWIvm/1mM9ZS2/C61xcCMCstcmpZ5FIpeaPytJ5vWq3@bbZVWLD7CQlxeUlvL3tSVGfI1Rivs4ZM69a8SG9eqWjFmYYwOFQ3sXzuSApktNgcpTTLb9rOdgwhxPSsvhVZFpl85uzh@YD5nof9zcLR9J8OyTflSCesvRPojMr3nnicJ@HLHI4PWcPyiGm0DwdJj5C4jFHg5Tnp5qbQCoyHbav5yotnyB4@c751CovSwB8BhmTPXlR84oV2A7/uV3xD0rkCcxHyJtntb2Oir2FXzgXumePbO5yFrylPi9/W8emGmiKlHVdEpZ5GnN/k7XNgeKD/aKbmggzL0JJcZzhHl7Q7uB9JLyfYDS3P/t0iuJZ8oetNav0kyPB0WZpiRCPYuSwLuZVTvqrwJrAP6t78pVNtXxWc8zzfR3NsywVG4f0HoKmwpQR2d6n2gmosJXO3qL/7P3LiQ/kdFTOOlG8zoN6S6smVk/aMMtngxSGJxSXbNettXOvFelpys6t/0NuPc9slrRMXkoze1lw3hTU8wJtoXkkRWH5ijp1vnpK2Unld@fCvOjJqWZLhu3cnuohXs6dADqEp4nLc1Dd1eC7iDKHyORMW4tuouBjvzmj5nTcKnXmNU2sfBR2AROqoiCoiRuewS4FngdiQ9h3au55H6e8e5N1XBalD5ikb1bR5EvyaeCa9zOJ7VwQwAAEOntV7q4qnXc5gVH5fEPpDnt8zjBQnBR33qCTZm4D3gVQCCo9gvkOCNg8lHmECs@5yQcG9FpLExXnw506T4XyLV89LCY41762xjy42foqcrlMGbOabvIvdYbAPuuvdBNCeMqjQLOeMoTb58w/zOpzYB998iE5ORSfljncdg4HwKagMxlJlWDXPfv5UoX/QBHQURFHhTkfKDN0iOyzNIBys3lCXeYTvmDBD9w13xpe49hyqm8gxwkml2XuxBQM55nO6laezvKdZSnfgGAI5PPNsxnmVJ0jeXOKfIXxT3hQI74BL5Mnvaq@s4s5Wr8On3lgNvWsCWVHh91cBNwDhDFpr8x/kqQNTDFxcs7hrQqpqPI6my45sQxMMgEPn4d@dVJs0iUV10JtrzJTEUPmp7qdC9ygWJMwPiuLseGuwqbCxyEAP3eYXiLT5VLn1c2eCcgCLp3e7OQDEy5OlztPZwvxla9eoKa7unpuYX7GoQjSblNYjxL2ycimtJhXpWqYFzG51a4n8XjulyP6nNMRDhSU@@mMXFAWa2izWCdhnZNiAmEZxzyKSe5vWccrLE1kcPaAyn6Qqwuw@EgYbrjaA2@SyNlHh1bHRMwPJDWhxVu1YKUTs9p0XGwxtc5uUZTCz@N0js6K2doYECwLVJ4kHM5NTSV7Qu4eicksoV0PCGSiIp9D3@4u7Msj5nSZrfZ44rMwP9nQ3AMYYQr7n7ppV//MilRLyKwnK5l/l1tsMnFQ6a4a7@Q@q4Enxu3S2Pl1y2dO@60rmexz6k/3@3OOTYajhJ@ILFGpvzDRA647qf7E2RdsCDU@7bKn8@8tMdMImDcroYV3zVMC8Cj9Zk/Nkt3dIywNQjLJ0gZYlCo6SD8NiEeYnyBqqYhtP9nr/bUBH5HzV70ozwKUqS5VmnOREr6jFVELaV6iRhGQQQCc39ZFkFM/Ep9NB2mHdzlkoAX3FmBQc2o2WY0Ypc/11rSDMM@LAe0dEp8nhE5lOp93t54mZmhFnEr7n0bDfJ8Szzno0HD2e88ynZ88flfmT4agEzeXdq7mkEcxF7NKE00L56ODZBfPfx00IIR55MDU@X9CJfDaAj@VtcCR6sMejiA5T9dR9YOUy7oABLMobQxdI@2GWR8adbOZn/C/eThe36y/q/QdwqiIOor4m8Cq/NYQU4PucPMPxjfnExjH0pqi7YYTiXV6Eh42AE5mZk@o/CCE8yW7SAQK1Xp56@zMuXWDCLVzJKyH5EQHcF7MrFntT4fCrEWpZI2XKY3n@UE8bqXknDSqfe/wksptXtOsZmDRru6cS7898vn3R@ajFt/bSr/War2f2cXAP29YCjCRRP9gQUqixqkvK/w7pYSGOVjnWdYtBfJsCw@aFQHL/FaUUMXpUNV0eUO4zpokekxfj@3SvDtA37snKecGEWpizvOepQlvm/cu6fL/izVWrTRO2aHxqxmtHrJYdkFnChaV8ym71JDcnerQCLBT@2Ui2aM7Uovg8l4eX/jpEqolehtXnyuSONTnQcKF5y5VP6ekR9Ihi3@KKBPVhGShMlT7E80@QW/ekhbhXIOu2Kxfd7J3xrzCvNaejaaD7YybU0sNc@tAXoB6MNX8lIr4/MJtocQnzEEMl3oX6TvNNo3H@TrYs9emX/QJLH5zl4Ocgu6p7p47OMux3do81x0@fG7tO8jTo9mxKbjmYIIrXyqUSW/mbZ4ilgJrfjzgaR6XNtwndZ0jfMLvPCa9zDru8tEQcO9xtsdTmJ748TgM5mT0xwkLWAWXKv/SZRAEBcnJ0haae2gWgjjUnb9ZivO9XoBa4VqwRdnpA5Z5VK3KgllOl86KhdHD1ETyrG8A/6trO4feTxk4y0MDEmZ9FyRnr1y2DUxSqejAmFU@ue9t@ziRYAqKuXmCl57fXO0cEH5RHVr7QMv8fKrSnWB9iqThFSsnf1bJqdMch5dW@KVJPg8YMA5H2iC4b8n1ZP/nr/iignvhsLsy1sENzPgKmj/o/@xaRQeQz1VhUQhcTjFtsdlbE4pnOz5qOAc8KGYSxiBCj@90FOpN2cAhepZS8N0P5hwxws463yBU0LLu4yzu1TS/RVSI/uxteVAFTB14MKG@4SEvmkX2AoFl7bcteEF2HFYPoMxC9@gC4earJ0ubL1KMyCFuQNQuQJcEWpcQMt10kXySm3kn5y802fEPtJwg90EMQ93nhV8KlquUeBbhhHunK0JDve0fbFcWcVzv4izMcQaamHR2A0q9FuyOOKHu1ymDQYM5Ps3ZrScJM9aOVyFACOqYzt9sAWmHctW6epAzXs2zD@w@BxS0fG4GptH2gksJnlbiHCKH7V402iHR7SHZin7CHYoBkv80lJEj6jgq0qbwmScFiZGtfIqF8NvZSJIIsFlH3RwGJ4rID8kCuixL/dpnZzyGHumxRbHRqofXxV6QyADYb@XHo345BF5Zyfz4o@OMxWCp1VnzQ3b3LR@cQIpxYGU9d2WS4t25uF@6blqVh3TjrDvhhSm6d0ncoTIWce9ApKsuSNtLnxTpRnLp8Dj0oO8On2gYYpEtfgZgzG6Z2uWpzj81MpEFIG5zW8gveha/XmOt501KpufhyAacajjaLBJ66ddCft46f7uD4dHmmhf506o7I04AGWbDgLtkTp/0S/qmXS35OI@YJPb@ZCOCmke2h0m8iknNhihUjuVTJnQLrHNQOBoAXLtj9qmvvnLG@BJiqAudQ0wqpZbp2OlUOfxRqa@Ztlu0gMbQc/l87J7fVXC4YAdSG8vZ@TqRS3lzhGorib51sw6jW@T53khm6DTYQhpsepKX5GYu7ATeTXyzkLYab3gwSqj5KeAD4hTW0Ry8Ageu2C3/unsRZ3nVB8dDSbIeIbM/nYxv4YFf2Ya9Ks/@wVEWlWluSsfaeaa74EpCguC6wqm8BUVC0WshQjGuaqdHtS4Nn8g1rzAKTWc1Co2FjMHkyi/rTu36LMB/Vt/7W6/3rXX4BtrcJU7Ca40M/XzgymxFmPiu9f2d1VhXrdNLCxnoOoFpHvmGpzerMyARdgADPMFcNZcmaup5qqzBlbOI3zc2GI7JdgfRHPJGHfNa16KghwSX0bFUyiq5bymmLHjKqMpn6c@j8jiDZX/S@MOaUAtD1oXAUz6kXNbRe8t9Du0XMLj9@1PEntBvgVDedaoY6jwqRhHg4vt9qtMgdJm@zODCN5iw/kWZ0MDB14NjWozirUsuW7GYHAUbgh1yo3xNt2SKkkdvBZ/NNe9xARy7GkwT6GfhzvVoompLvjLy2s74OK/L8rIV42LbpSeiMnyr1OeRzBb2wYgyV2wyiaY78F3iKn7CJ7RP2DmUtruOPFqNpykv7tBQkEyabHt8yHaIEcojh88E5201bA4HCLKjgubVl3wwk8R7kNmjQ4@z4sbmQlXRiEhvHThHN/DjAdkccugwLWn5Bw9evXQYDzbZ6UVjZCGvLLbBpQeH1qe//@tUx1TUGRYW/RbgSHPNLp83VWPJWgSb3s4RrTtIdvsjQsTc0hPiBllvI8uUZOrQS4Cd8/9VDhW/wPDynqMjAVNzVmHBbYNrhRFuFbngMNBaRXaEVktb5aP8Rp8DCwVsqzQ@dBDbQyp@blGZHvDJZeM6mFaY@WkM48kKZNAA5Rfc9cF/kV/M@5nb/iqSXptT5f4ECCJH7p0enm1gwWSiG8KoEn9fueq8LScbOoacAKFgL9vX43nRGQQwjd6Vi19IYsexegyQ7DmIhEp5/SXuCbgdJqGTh4P6F9JgAzpU9xqTr5ru8uxubFmQ9t6708C9QONabTVY5mD46d96@voNExlwJISmEx9Uc/cD2Wn1/tYGu6MfijDAhPkxZN0NDwUy9mpenMqneGsyn1bmW/omsXBE/8BNR2SVH2qFQhzndUdKcquoJKoBCdcWHoMuOvegzkKMqO@1Rx5QaCmZxMtLynY5659TOK8BuQWkzDU6NkI151N2u0CKgtAIcIUZv6GfT4QBGapX8uv0xRNBCnhVdhpVcJTbtsHBUhJ7xZ@oDZUUbLDY9Nnn/ahC19/PFz84aRHL9BiVzUBc5xPCi3CpwRu888PxCeKCh0paJr5E9JHaz8r96jic8F8UB3Xdg4kLkwFvvwgI8qRTV9L6mOwjxpFYFg4yN4BEc1aRn1HIQViw7FmmdT8QYK7elK4mVFsrLsgBnAyfi1al3NX2nHpxfss@gJjKnPz7tVjFcxs6Xzhn9c1ONEgkhTkknBRYONcXe/mtcnzr2H26v1tIvHoQmmOZxkeJzqkfOA/f@pjgtPrfTxC63O8CMqgIlQkvMhsU5Ix1s9lQAhuwRYaMmaeCw3cA6qNG3VU/n4LMmefAfsuNw/O1ZHdF7HU9q1rX4pb1qv4mcnR2yb4@HEihIzLTDch69AN/CjFd818tljD@29u89ggs4ofya57WJXd0q9dioUl5vRGbfqLF3Ynnl7WX7PzVP7ggSFJ6nL65mCoDNYQexdz9HPWo165EhTsb9nnqBYNL9qLFU4POmlANi1yL6vAgkEgTN93yChP01aLLT7kd@O5y1cL1vrwFFVYR/HX6XKKP2z7rK4AI4aCITDCRB9B@SaT2MvifZumjf6h41j2fhxTT1yrWMp0VPLnRJIToB4uz65V8V31rzR5lQnXU4Zx8VZRHDcYw6Dn8H2T6ebNKb4eLsuTQjcBRxYA/1W9wPVnS/Ppk5WLUi7oxS1VBrx0Zx1mxdkHg0aZCIBd9cJbdbCKcMoEdSQwOqWqTamC4iiQ6xI7lqDu7qoXkYtaUwuFDtZKpTfzVpVKjeek4@j85UCoAreltsRpckaRqkgtU8RrwioCf0syB6nN35PffX/X2SlkFyW/VgvGtZ@@1qneXb@@hMs3r8qAcp6o0H0WnUrH5iH5JWYBJQC6Jr1pu8mknBbpwOgQbA/FxkzDXlAdLXHUZhVS8fynLF53KeV6hqL8ykUimFVH/xhp3cL1VztUI5x4T9EIpgNcoeHS29l7BFqdauH6BVbr@DgkN2VnHEnT4xA0weux87TOnxWQKd7hfUMQrmAIX8XsF948SAN4r4qC0noim2x2F0HPCOUIPOM@o@RLT8w1E26Fvvz2BzSxmm@uAlp5ROo86j3dU1X1BexsUU7mx2ADwq3ha78pn9oACaIBVpVWKvnSpNQgNUAkggnoXT@iU7mxRSvV6qXNfWJ7y6k5aYEeh3qs/EFKUAXNnTiY74dmrmHX8YaZbTwAh8dzk@aj9pBrYZijDR7WDUIn1d4BSVkIDgFfMnlqDUkvQq/b/ZsFMuHCQ/JzlKPWfIJ@ISVL/gw/RkOwAafttkwz5B6xGJF3NTFF3NjEkbQ7L/vmIRrTrpYCj1RoVAA/UURpEYKWYU7kSaewdk1BHgPzEUueZf3/V/HGCZtMpYDZI9Cb98F2vTjPFTMkMkvj1xhJUdtyqO1SG74ljL9ws8oTW7V75QQrhwUD6JU646TXsHZgV1Q@0UsmhIaAcq0yYGFrj/dVgRvdGUlf0Ouw8NA1AvYK@41RuWJNgGniRFw0AkaV1NoNDCCYueY7ArU9FT4ZYgnxntz8WjlKufp8cHJKJd/az9NS3sW9iJYhYW8QnVQC0/6y1OvnFDklBWXtVz/LgMxZ8lMm5pN1v4@wsOF1veY@7@tDHbPgHr9RN4xqb@ef82RMc6Z0T7YAy7oQc/iTU7jh46vxTLSdmR5vUD0egdZZPZJFjXkeEJU8ZPgpWF@UAYYC8ebJ@tFo3Fv2lLwqWOcvoRDBZyva0cE5wxSX7@FJhSNYhsFWFh3odexlcIfmBbcP45QFi3fzYLLw4mXpoQWhnvYcvNFVVjxFoP56CK7o8NckeIH8Tx2ilKLHvkLYyfzxKXFW90esMVxL6xUXIMvKTU/VD7di@Hl65A6mexjmqQ0AG@BNWvqncCK60BJ67x1i5LPe2OMMe9/rml5g35/2lFeXgEzRjTr8ugDoD7mLfJh5zuDup5iw93yRteCrw5FfHJfrABusXdDzSuM4H/PyzFn5/ROy3QDkPkbjKh8S1@bTbDpHogvQ86pi9LDAuiu4@RgV94FcU0RGW6Huk8sTtD67zc3gaPoByhRDC1tN@m02NkbkHQd17WdgZsVzcWt3x914teFy5K8KEulcPiwLuqFmyOehQgi3LJW502EO4Fd5XCRre0/z@PPLTRoVhYrXg@84i/iHzoUo4JymTruIc9sUOKIQTa7I71vb4CJp@t9wFuKBSQNBM67laOTbmll5u7uulEPNKRPnSOfXOrBVL4Mb6puhBndEl/eqQfhXlTp5A9oumT4WEGq5VSXRkYcRVvX4BQDQM31dj6HPM7hhWG3KDYwnbcNesQOH440bfUWLFuR@sAOwC2IOViFBErsIjQafy7UlDEvVn/ies0Cn5yoXR@xS@VyIDHczoEIACVd8PdS2OJ/oPfoC8JNLPocckLzjU25AMahrMRb0KIGfpiLScIpFmtLqc1OiJYiwqbZFLdejPuhCOtN9RvS4b90A1XDboxJTPFCBfmsIIWHcwaSXnVaaprD1Taf4sFbk/Pi6e16bO@WmJkgbiZcrFLgKkM2lrNGBQ7i4FSU1w6/4rErSs3iOu1oF/R614aXvoWWLxEdlNoia7xDX@9U/IyBE/pQ@v6ueHn7c7lHViEBhxH5C/UiEDl6SrdmMIqKTVg5STLD7EHEtfdXEVGsZhvDNBSpL/VveUSmB9bh33eP9PRdYVUWVPciM4xnkgqjy@@heltKo@p0oiVBLqM2nOqrN@CMHaEhZqsL9PPEvHJcKToIt1RflNwaJLHiWjVJLG4rUbIPz627Cp2Q94ybbZ7vjR6ZD4IlLHYVuYwobpgwR3AWkd4Vj1V/rGHQ5j585xKlLFeyRSeLACNm1YEjjLRqsr/r3MMDqC0xtchnP0le6TA2kBP9LKMsBajESvlsTpgNo7ZSjkOqvueoxzU/cCoJPS7Ol8YABpTupSKJ73lKHXuVJote0cGG9CFjSFz75JmOYzlNGAX@27LSE16Cpg7FWN7vWMEiTp4bxARzC5JtqJYvzVDPSiPxpQ/Q9c9DMlhcMN8iTauSSBF9fxXrcod3oKsOjbXqk9NVvVIw4Xhls55y8PAuyGWPA6xZ70wN5IooxNkD83YtevdLGen04cCbpkQrf1e5JyLw48QP/W5VD7FzSAGfMwFJWoTlvkOeHKqQillVOJmtBvElDtdryXrftMK43CEjjhupUdd6pyawgTTB561TcvnVCzxulVGb5CyCGR2SWJeBQUCamEp2Smc4/U6aU5HCTWbZFbTMxKQJFne9@2gw6R09/7Sb31IVzRxl5likea8Gh@uL/lZ87PR3n8s@sw6KBx8TNkcPJqFEhk7V2H@xc@Fy0PFZdM1bLUtdTF13TRDFj0bHd@CJfg2Rddc8ki58miqF1nJHC84fpPkaUUKvJuPb@7r46tSEt0WIn3k37ijhBN/qBm3fEfr9prOkz7najh28oM48Ugoz9Ajl/imm8ZEID0MI4D3LMh0Nrxd06lm4jSY3q/EF4xQx9Xy8aKnbep6XR23s7rn8VkzVDf4lxcb0xoeeS9xyD5RUiigxJ14LW3g1NvDa8LLI7CBR8BkkHQCFicBmcfLoLrpUly5IifTsNXh15EwRBQNp0JRL5Vnj1Br9q7RLeTHEBZgCO/SDbIdVoeAJMpyEsnyc6VVz@nUjTZGrYVrokytyTCO2mtWhpiXzqD0Qt3vu2tL0Z6z5MRxBtt0@rUF1FzkZz7kQjXwHG9qbfHJmcDVkvhMO9mS6AeMRpInnOEV0ll3yhiJ4KIJq8tXKPlKa@PgGKlnCgg5bne9iTjO86LZtpRoz7SERXMJiGW9/yiZKNsv3lFHLExvKETXLtTFEAyEE29rBp8ACb4t0A14YdcDIZyJW7ArVHJ4DmeofpxA@hnDiXhXdB8lWFWAcqYpf0LasfTjS8utgpAuIKVZMJTD@eKMn0vBt6vbBv37qYMTBGgf4RFdcWOinfvVHFUiMHYair0evLfka7ziGOtKPmqJvKEUJukkCJm2kpPfhqpr4z0C/LQeZRO7/UIiEBi1H2KHPpfpOVdJaZ6jNpG5HZKQgQ02M/v@3MXIXGZgH@vnjtoABoA/QTNqXmDoHzkAthxkPYVgubRFMBt4PPoOE3Z@i4fmPfoKD715m@0qlxmgNoX55JD8fBB0Sd1v4BBdFbSXptsnrK0APNT8/HuVcXnJ3YiT5Fcgr3DWS9pV9JCZKS3ktIKTwU0L8OhvGFknX6Bs8Sjlf@WI4kWVXUoEaIMpKgEUD7wPnGnZAQStz38yufLdcr3sfaX@0oEeT1xfOkjuGGrCaaBvUc8w0bb9oigXn2gpANwznDYrLDpaqUf5HewV1U5eFcRblkntiKQij9BWCMhPDs6VF58ap6Y1oqLJ1YRe5k3hBbXDiREEP/BdA5J3ZFKkqeBsxW3kNmGDwEuJ/aFm22IO/WKmLxg6XzOXDkhKwXR33KBPCatxAkAoUQOCizYM46hZwhS0OzSgLkCG0mUT1QlMGOCZRuM3KTYgjUQaSLKmDYSQYxqXMRzwNkdlkUg7lmO7xjt2R3ULBdZt8aYBKdqV8oF1IFrvalocYgAhBLrJ2b9u4SLe2SIaEiR7ycZqosn4HmcJ@iOBQ/g5owW39LaU0ylkIdk6GnIs2AzGikEIgu9xAjmgiFN12/fY83UP@Hz0kLSIG5n7djNgHHkDsJ5aHC6NO9ObbOVRUZthNHtS6iw6tqCf6mcvHSKDkknUBKjB5l9T3TJieiJSvu0tpz4tFYOg0LsFu/DI8HfxDGG0X0aoW/itCT2WU2hZCHjotVAtJIH0Baoz48cWF5pFRqK3EmvpcfMvoh2j0kDWxxH6EK1Lmk0XOxDNdPY1sHXfpOW08H7aoc6G5ej3aGKm4rkTXddu0yPoxNrZ38xt0WztcBnRyy0DQcLCIzsMSsn6O6lObxiK5dukKVgq3/p@WkKjnpAG78oOrY95va2NKmKGe1OWl29X8UR6ojmpqrLWSX@TXp5F6N3BSo1KE2ZlAAGoLuw2L8n@ciKrWL1bzkTZAMir0EqIoyHR3xhsdhSMna2PnqeV33ukAIuG7mC2GlsAK7U6sRgu3PFU47X4tnpu2PN7MkXvjZXvC1SIyH9XAW4/AAm5AjccFVBISAT0VMvMX0hZcxJ@veUhWGNJgJB64KS/4JoyZIlxewzRP1kyGouXbDDd9G7CMnfSv1gwrhZG6hiP0uWrliee0QKREM9p3OxlHXy0BviBv7y2wmfivVZjugEsdC/qIBwkGjXNFkqVJwS@aoPPvEjdNPTm9wh1Bt4ZRY/owGbiRuMBrh84W5TnV8kRAixZKsT1MUhjThmUIph07lxrc7EwsxBnM4TYBxEEYi0MXN76iqW76JkorijDzl9rlQIh8zgSkJ4hd7Wts80gMwhk6otORYZI51utLovxgXmhDckP17uRJoJ/nMyjZALRXiRcsFkVTx7wlnJxTwA6JxDA/C5Qht4R/@SCBhsohIV0bcCA2LGWWsYlcbqCY@kAlR4zluq/lO6Okl2uu0Tq@yqjLJuse@gwLbZvDyIxJPiHDEoN62QxowzfmiOFsydzEouMO@f0J5GbqLEpH/Ug2f5SLiIjY2bg8zK50MiTytRXhYX6MseyLmrKF5kB5zr545NFu681Q/81JYB6pJhxX9dHALvih@5wVWJDEHTTtMfIuUM3OttXPG/5YXs23xbtit02eci5Hzyx8ymmG@ligRI0509lTHIOxaUCPOmo1vMQrV4ieqPAFjV@pbBzupUNWTXAhje69h8RFMAc39W6EWwPD1274N/Aq4cRhha3y8q3y@XC@W01oBojTpzq7rOBXHq@V1amQ/EYgcW62THWpDMvZQ@Z0xAqCAvLfAqOhm4/qkiBIHQFlYuZKKk4e2M8yyXXlRe8Usxi/eVm5FKHYMhDJwmpcS1dHtVTZr8AGnPBQh/dL@grS1dN1Aa1eMm3viVo2vbwc7qDCCbRkO8gcSXF2OJP/k/ZPlD2mNHS1GlgpkHXZ352AWeq2CDRpsFlHt6GB0eUYn6fJjBb5Vlnk@MJC@JHcoTjjnFHMRPp@qJsgXlZ5oWQ7uLY1Yifiq3tbDSImaMpWVzrqYGaFUDc@keof27BXWlzYBPOiZ/uYl9f05kmkBbxxzYQE6C4os8oqI8Q2twvjT/j7q90gmIldxXqXwtZjf0o1zjzAdRP5n45YhQ/hyhOzFGrLMgiPhsHaZn2QFM/mN6qUdGGZmo/ruTOGUyZH9yNoiV@2Qlk28iilS@lI75Lcees74F9c4LESRWe630LX9GzcJYQII4cU1tReSdjLo8sjta40HWQ0cQXkJGQVj/s42KANCWc0GynqiKMoMeNOitgoLK2alALDlHoU7knmxYm0XOpbyB5UlCyCGUh/eiTjNDIDM67qUDfjJgsXUwgbMXpaTWxVS@OX2PXEYSQiD@S7jzzZGGauLfGW0eZLsevZYcg0xVy@9KUXjlLvYknzsAoJT3Z8V6NRkp2@NtfxH6gC1kjpHO1eXgYDeFRXvTWGnz3RjP6NsLqYiyqlwkBZqY6iXPUcFAJnqvx6KUgze9v1Llw8YsRdWZkJu/ZZVfup6XI9Abm@HGG@ZCech6peZEhofOgO9VcWB2eS@OaRJL/D2SBF2QrAK1fORCbH7E4lyIVvH7oR5eT@144iNhEISJzqOoBMlC21kdTSCk/Nuz7kFGt3OAxmrhB3R834uyqHigVPjKgI8SLPKqL4r1HqfE5uaZ9IJoN1AU@xmvTbKgM3BUKzmrtwTXfGHU53JJ1hhsNnXh/0wm2z/7Ep65C2RY9GjEKWW8IkmXpXMAJTBoEFfd0X6/AaM3N8etFE4ige91pMIUhXDX5vXwNolTJrJyY90qtfHAWCoomq6MdeBRUYKPdAH6PYveTTu847zkeplLEf@uM6HOy2vh0oxXj9Wh2nKAmEQZ1sw7Ut/tWRxdcGKZTdYed1Yp@MhPtTmI5ftlRseE6047oL6Bcli@uHxarBv9Cv@Yki1edls9nSSPh1T2DIVFIfyWkdATQEEQva9SUCUYJHv1/JFlrclsF9/fciY9l9g0fwVq74jkd8rRqMhb5SE/X4IfOMYPZmeplKBHdgR7A@c3EL2aJQbSou/TAl@dCx/uuNOIXvDJFkozNkFdpKSJDnvieeZweVU4znKIixcPuT@zHUgP8tVt5gIAqn0DRqyWR15Fgobk8sQxQFT4CmOyIEQN1IDENH9CbEmO6InfVOPiV68YkkgOTVKrgt9XI9FOTvuRRD33IHG@W0h3i81S/@8Dmen17MsYdWOqRe8mx6S7/Qo9cF7YCrEQVlJsSfs1/brmrRN9LzkVGf4shnixAAQ3TmHQlt8S/WNcYRJkpKPPndEvzKQ6zcZyDOm54kxKgFdCsLxQtBGJ0i8kN/zpXQFB/3c4wZXmsWdIBc9n6UL1X2QgmjEMW7mmfjAg@SUILsYNOGh5czzC6c/@j3aAm12gONOkvB4TpPpdur4laLCs2aGqzaD1ECCvHo1Pk0gOx7LkTH8DUqNrihZHpfFSXMJFwLTP8s95oXEEmE4orLUv9SOziTsHPM0WyHO6Zg1KpmKSdWJIPofAnNKtGyTBgkXosqz3JAwSXQmYzXyEQh45QgXuId5/d96j7xe6c9do8lBknn9EgvamPoX0aM@wQXKq3A5E3dCxsoQ8tDbzmgTQ6E8AXiNA7LVEalfC0FMaWZWUvc9Ru@/K6lTuIxmASsxfcKP6IkDcfEI@VQHfpzPYQYfgq5OnSOKjLI8WHH4475gBauIlr71j1fEIlfH/sr5AyHZWahO@y6hzSzYrGD0rTcsU4YW7KdZmCf5xne3F1hvgW4OhKG798Xs54fvu7InF@vxdKmYnuR89MWtB9GHasBxCWKu8W5VL69PliEZSAS0625v4I4ELPoiGUhpdttihxs4v6BYRPIcrGBMOpyPOuw00hWuJNUwWtrq86P96bVb276mID4M9QtZzE5KMo7Qll1xWd/h46yB3KlhVFuUPLaum7805JL@rMwsKpFllsL2yJUJ7iv93pnBoplIKcR3dRwtUvYEPctcLhalk85ACbBY61F1DSFoNG2CunnahnVSc4x/BLo30JInJdi1zQyqmPWrJk/3rm89P2cgvpIJqQ5lO66Lnl48wLOpRDz8sVhAItjQiLwxev/mNQy8yyy4JdFUT2LsvHQkxacQi9jLZoRYA4ylKxTg85al@ljJoU2qwOJBYaWi@35xjIUCLPZrmWw6YrMxZx2fjF@3nSx0vb/7KG45sIc7MawNKohpR@awOCQDLIvklHlU2lmbVYtuSsOKS7VfmndVw2VBEGaUswu3GodHerugDySFzoKiiljG3JiTDFOAPx/WDUAU0qkY4lQQgL1/dQUPoU7a752uphby6/W/JLTcc/GykKhA@DtadT3itR21owFCu66EEFt8Dwadq1p/e0ujDxNCPhUX23DwtgU65XyqiK/U0E8ph80dx3qkKKgpEeXqiZQX@SP3P0GfSLIMGcNb0Da3OHTyQTzTe8JHBJiIUjYGr1tPm/M@3D@BdEYmRmGE9ndO6@0T8wDEvDb3QPsi@EzcPi4L/dqoxjA@Y8pFmMRowG4AnAivXPL4lMFtUw19RdzV4tmyW5QkEULIpSicAX2zRHH50PjBFMn@@lxPbzm3Jsc9@@A9laR7BFnfql9eOWxF1cW7zkkWQ9BANiJAv/TxTrcV8bbZEmrnrvkvlEjzzXElIeKRdkRQWYlyYYS4HNoieImpEiYmqSXT5prSD0j9cIyJZ5BI3n7@aenGyyCTJXi5kYHVnv0X/ra@bhk0@gztEXOeWz/Qgiqcfm4uvuQI5kDBN55n4YWSmKL/Kn0Fui/TttIEQaYQts5gMde2KQ6amCSmCMITCxeKyINPFukIh@EHb5xtIO5UuMbH0/IWRTVk1vyfvO/IdUlK7jk9Bw1hYHOT1olFvVb11yPQQznyD93AMAgALe54qtJMxij7BE1d/Dx5ZnOOrzBjpR0jpXEzEeB0xNl2yYzI63ZzjF9Iwm@03oJVWdY@qluaEVrhQoYX7JzHm/e5ZL@MxPP9D0sAQHUNn9bfPqj6qVT4Y6j@dsFOcuRZEmIo3iQcNFYOOY7mxXCvEv/yUBEJtC8kFgKjayDmFg4Lw7hEzKcqo@1t5TTw@/mRitZgUWtgEkbts0yZClCe2t/tzZlQ@6wQhl2Azmw3gmoxeAe47hu74yHB7Z8wdLrjleH8uu@R7MS2OjJMRcHsLFmDIKERYnakDx00ergykfvhA@uyYAch8AhVsUcuTiBgogqgUxnIunzMsr6ODQs70y7EjtmOW56jsCRRkZy7ul/cadCbCHFxP9SZ6XjhzSH2ZVN11bwm085oSb5zK7OpqYBxLCQvYh6e8cZTSPEAEnbb4GZz2CkC/JgbQTaOgUhlwSc0q4sMz0c6F63i98x3yHExCB8CbB0NQPRpoJibQPw0YPwJYhX7d3s0pl4ck0VY/0Ukw4eaFflS6hMaqCCALXRSxdtLBxMq/nHQdmgHg2gKO@eddGvytlSZdydl7e5e3CiDBafZA9DfPI8vPmjJv5pvWCzMO8yfOcqvkkrBUpxQGle4rqpctEs22aRd7YoqbjlsEDYqAGBBZutEErm8OIDrsqvwsIDXkieTvUqgnMmQALmm61EbXXNtUSAHJZgLKBYxFt6bsIgg4qWdhn7FvzjVTyOuKj6mq3RpooVSq88rQDnwe4lXTLPQXOY2@ixATk/9trs9TI05/1eKvJ/5Er@SXqIQgrYEaot02oCWzPIQALdrgF1m7pqIiUrMJiQKJv@aaokYAhVqk/YBSXZl/PnFLlbW8b64sKYVufAAgVFOYgFLZpqi1r4i/OAkKl4wUUTtYTjLPeyXgaRF8WswEYm@Qu1kTNdRB603P4Oh6JHgwieLLDfbXWUy8p5C/zzVkA@WAWJK6CuhaMrIt2bV0R2PbT0jXuYMSXzVwAZder9R8kJQdRxIVsbmkOit4J3v9oxuakbXL4z3qzn9CDhqWhCym8BbJWtzvUO/RMgQ4Im9nfAZNFRHoKZ6lFXrj0UdXQDki388iUCZz1SgChoRJZtTqq5XTT8cDADcFwRbz7HmCIigskLGOJpvIHUDzR0MDNDgkuedvTaYgsUTTzjOx5GiPPIi8@Vuu/tdSYgKGCPAKI7Fu9pW2q/X05PSBtoxKs3szceNZBqCIJG/GK1hT8t9keveVP4Cwz3xuzwwEhiOtWAXl00icxSWUmTeYYKk67sVbyPxUe5ZHgpBNshDKT8qTMyHbLmo53u5kvnm6PakAU4BDampj64L6Vcd59tGQPJQFIMPWFZUyQdnyXL7/oiy64UaxhRYCd6KE0CkTQ@DDP3J3jTTpfqH3zu9jS/pBZAZ0upfgE52keUF78wwC/vY8anA4IKHnFZTwxMgsPnHaXbbJyuSNQD2@k6zdPJiacMjj0CAaanxMq0X3xaQPostGpuUV5Fl5DPiYeoQYpGs0SMOV3kjz8Gx4Fmj5plfMrVSHEsCfHXHsnTPYCKXNcwLzZESQCF9OAmd/K92QqJAj0GyvvV4Epvevwx/Y0s4ATgQ79GZTeEQ0Uj51guocGQyU5Umdb2qaNyxFvaFFxownRxmt3ttGaB4MmEmytycvZ7cnUfLRrCBZt9VFymHxyRQMjJyO/KzjBhI@/7Hm0C74RbJaDcp98ZePxnrEU1XZo1pta67Ok5mua74jX/yWo7gwVVecVcQeWe5nIoM0GnhIzSHyPelOmsFSAy9DrcwNGhLG3fBqkhXG9ZuXKerVt0aZZOH0q4UC8wwv3cPbbDytWs3XtuSzokqTwvTagb7Gm4A50hl3@ue6d9XW4SWItS3EsSmQDNY6rHOPJ6Wu3HMdwsxFIZVZ@3eWpnq3GN8faJ0VQ431WdnJcW2j/EwSgLN1Mc8g@h7@hIfdCy@VtpOi46xZWneQ0bnM82ZlkbRwK8mbsMi@SgzlUsPpMqBP9dCiRAul0wjlAf08ZYUQuAqOZt0F81uFGGjnnXgQby6f1uX@ed2hj7l7ftn/0F8HF/709a/Uz5FPTPTi7HOHs0lOtxw1t6U81sNvFtjZZCDdbvVgdpGaI6udvzfeBSFK7@D51tgYxM59mcGrBNVEdHPcL0pQYfYIo@p2gS2qDAoJ6CfeN8AUQCuf8rTzfcvnGHJ30NxIbufG9ciyeNklUHBzBafsHyqaYRggM@dp1UekXInP21CchiEFPgtC4F/tKN6tb923XTPJ9rsLZ3s0pZPdVh7UxdRVsh0xKiB3ajEpt9V9/JF@5EL5p9Dt7WHwcBlREEAIkYOde9Z65y/11BOZ74yoiv2iOGXC97K5ujTRdglLouMnpywiMJn58pUAVWswqNCiz2@/BnHoaizijRxUvpsFHDsQVLJWzBfzdw/IEwrzyNVtPLIFCol48wO@HOD0l0fTQSTTlBRErzLyYwlqm38jxjZgC8/lTIGQJeCdteRVv@EMBEnaB6SBJ9IGkLY@@cQdSwifkaSjDJZS@fpXPzyRGvnuiRNIqVs74aiZHWf3FwnwNLjnSbIsrctv3P/Ng7IpRu7TA@Ee0YqdvXOmxb1WNZqpRb2N/WtADuebrxYUxgSC1tVQp4RdJD1gqTekUZP@rR5gbLhMw0ieiOSeZnCssUoV58wuJR0fQWPWXx73nrNojBS4eyefp6B/BERRPCdHOTJipSyoE0kh21DKX1BfxmtwK5LCWkxvDiuJl4IPoUa/bFU0f9ZAB4nUOvVgjkfD7ZpmwuLMAzLWJixSZPubMOo@/9ileMOR6stACV3xcCAjv@VkcynRimpnEkj4UEAPGEqetWV3lzKyl6Bt4In/YDY8XDSSfvxsaTe/osNdYvKlTLxS@qAshQP6cJk@VKERpTjD5DZrPCfu1erBafPHMLZLeLU@eWw/WI87YmSJ3hY32tP6xfnle9nEUlnh8S7xKdYuZ8bmy3DIUIODMqLYOQeM2rH0t0SXNrrfDoUwaEMjOKlTDklPhfMa@VP@yuzBOsVbzwj1zW5VlEI6duA6@KPFnovRWKj2w5zHfrksxAQ7XS47tnwBm9XWRFhBu2QezYS0QT7NTPnK4Lofy9UA6@VJGpZM0InI037N6gPUJ37ZYgIt/2688GZ@MXVkUMC/ht7H2eC8opv@GpxXLXo71LfssZzjX2clNuaV9dvX5L/UIulQ@A0X5LJr3kPqoiPh/In26T@aAfU7s3hSfPGsNCugcX6/ujVbLn3LX4wnDNwXN04jd9uW/4TTmua/zirlJau9PWbk85c5/b4sTxr9RvBESrls0hiSGdqVcJtGIB/SX355TgbIZ0N1yFzP3A7p/KwuQLhA0EiQPSM1ndWq5UixJaJ1js9MK6BzNWi5iCC26iNhg0Y9z4YivkOuJGA7Jjeh1/n22kFYq0lH0dSxV5VEcVuXiOmqNQ3S0PPTuVIbw1@q5tMU44@mqbR1zOAVwXJrF0LZ6GvmOW/JPLJyvAw5QG/KkBau3gQuILibWl5HpPkMpcFmy9XHtvZk/K65pllsq9r7ZSGsmiM7ALxXcKFqVs0KUjmCic/SdBSWwL0j9V6DOGQ59VyLjJgfMGglwx5m739drBdgF@TQb2ryrG2owkHvTL2ocqWLPyXhAcug44xXHGkTvAvXcxJiL9zPGqISJ6hpYiSA4aRgBvrk3C0XWg7Q1jq5F@vob5DXktnJuXX@mMywl3RSZTPyNqdDQdR8zIpyWiie0w25ogB@6gey6jGNSXv7l7vZ1YimChId2Awv3iYZNC7kU6Sey7tcbu/UTVruIFQ16Ab@lquz23mSKxAHvGtWaaVuTp5HWpevyRd756DmKnvB@NId3A1KfhKeALaeprs6r03cBQU2pZX@xTbCBeeahe1nw4IigFagcoctY1Vvw25IYmani974F3lSL3M2V2ffyiqAARa2FhqHAoWkiocDkk58/c48yo5lBoRiF32Yl4Vm977cEEgW5XLNd262FX4zIOarr8N2ORsVpjyRk0te8isq9/nS6KN3IRXSMxy5xcAeVaJ7OEWYr2xRUQqfwXi@03ID@a/alEfSN4eTQgfu@tbZD0uncOfxuvQiHo9oXa/lrOo5SiSa/Uc3Ms9gFtzeBKd7ASVEZneDT7NivXNBNu2ApwCpA9b2l3OCbO3qTG2QOaCcxrHMkZNWcKFOu5eTPuKLH0DS1tzYM0ZjHuYGtZeINCnDjWEn5NJ1NJLm3Zr4pBGtM4dnQg9c4pL5IOg5jjQmU2NLGn8nBjMl4ulXyNQ/w2OKsYfL1Cz7LVG0XHdJLH6xgVFYFhbdkpP0rAHzeonXW75@hMl/gXpp8HITw0Z9GwOImPHW2mY@9q5OhaSE7SDTczn71aQjDhj5FV6x84KnnACciwqHDYKFCMttn5SFKrnnWm9oyz8KjSmmVbUn/Zgfyu@dFwXYeG@q@XutaTwvBJ3eJGxsjR75sg00yCYVef4myjmbE/fvzej3i2byLTdmVTG4cD1bSU06sjd/z@tvFJNVvVeIZxGxB7MbLpWlBf7Q0ZiGJlVk3pXTvH1HbEyAVHbo@EWYAJhL/b/mToLOJOW4Yb9Vy@RyvmUpCRhhZnAvd8@nYKQ7mfcdkcybCZLdU6uGNTGay2vSog50cbBen2FL2@pLgMqWa/CvoemZo0nrrzXgiQcKyFHHuPlgSr66W2esDqPMm@XCQupsAnqz2vkyatOQDp@9lf1cJF@qq1@uaUiOKGGsCeEsvyakI0VVCoGOPsY5R34H6QB/2aYlFeV0oc/uCqlQ33fJBjNlW47dvlTO/TXecLGNFmaSZlqDohwoDzXdla3QSEx4/0U9HP/rzTWbLsedm7yE3GDTnlRduJu5GYFFvb3CECgP9AlV0u788lxQ7xwuKCqDcIcd591hbPzV8dXBzFmXd2T8LfwyDlr@oslTsHyE1Xs1b5TwrJU8k/bxVn9Xr8@5qq@zxl@F4DWgtQmV7/M3Vhq1cAM64bTQ0SpWj6wfm7HL7Ujm3diqyCigtl/Sn8iemhZGs0iu39QG6SpyaiBmasgR4onl@jcqC0y@kPs/Mz2p9tecgD2DW0amqkkc6Ia4Y1v@MrtClGRhw9pDFfo1oYtZhV6jGs7XSmbFf6maIOzcyMkC66DR3PrPVM97glZ8KCNIPIhfNuprcMnRVDn@a8oQJNkjP3@9FMO0PTFTV32jSYxA6bMXoiUkP3IwagOr/TUSReatqY1n/qHfmsQX4Q6PTCLQVA4BmIXZ0wxIPZomCMcgaTxylglpZzMVf7fcFCHwHZ9HYGuuAep@L9RKkH7SeUhKVXg8yqJhvs@5Rm3oK5IFNmkx@@mjgPGrnUoXaalabVAFDaKv5jy2BulWYmFbrB4LU4/wQ3Vw4q7fmuOt9wcOst5SLcW1kPQhGcc7inwVjyIku0zoH1fBuwFsWLx7PuAOnmzVviY6Vl/ljU6TQhzNcVdrCnnwS6yckQeYb4HhDFB@K1zsKcarbFOsmT52p0lV4QMxmsgnGtGlwK6zRo65baBmzinN59Ru3Vo23J6iT4J/SOSeqB1AB2ywo1ykASfggrUPkjlVadJjOJR1TO@k7ZIehbhHFKh6Z4qVb3XDkVWFvhvr4k1SEcTiTMp1Kj8MFLgG7LBVUX3spraQtj1Rb6yq@rLclLZOga8c/m@W0ddjaJBzDopgl4YcHA0ye5YuxXn@lFQdGM25MqWd5qwI91eq3Xt27qlljJpFY480mcYon/xr7QP5RcYw2h6Uh@IcqfqRKRuapvYBlLRae4/q29556jS0Re/oS5peakfAuJTGDs7cYI3xpmozqvEqoYOaEy1xB7rX@LZs/5D3BQh8EKqlq/HFetBe09HZuSqbrzEnDqhQYq30xmpihCoXnc@Ypfdv2aAR8z5LZ8HS99oTU9j3dxlurX@VP75bpcebP3cDn58Gvt3LrNm7QurI0iTKkef3ZqYfEpW8Jw8m@Vesukxufk06RyaCXbFbydD6CHqronubKJ2TGcCTX@gbO@VJxNh8jjcaIpX/L94Wz7ozcQvmyXEunlaSWxJFWbziB5jg@x06mirgxlB9vLfGlbgJm5uSWSg5mz7YqEI54fKDVeuCHaFwwSZyt61JSjz2bIW78UNHRpbSyvfPIfDJQfNLaOaNa60KxFVGte09sHtNp0xskDkmOp4v2hpxSdV9/fk554GnSqIgfzNS1I/Jb6LuT2OT7gbvnY0KFVWvRkvSgGFPWDdE3ngDazYSMiDS4NtA34Y@5QlARsya910lgGOns0yunMJ8TTC@GwTWFMK9Ga7vn7k3FcS1JKv@Hm9nv@LEOQ0jTLuCxq9DSTR4v0pJPOovcxYMpYZxZIgCEu0d6etqaZc@wH6pcdWOMB7nS@J84uWtyXRaSl9It96ToznqrIpaCpHkvEkSWovU8Q22yALXZ/MpNKUhP6ctgdmaXfjkLqC9l7NwE6sKbkfDCK7U5nvzQ80ibsyrs3lJtEVMGV1MsYrlZnorqN9c936/ZfO1Q@6Tb@cXlm4Xxhzx9U7I9iwNOVeowBzFYeUz8nXTd/SFkICjsC93mNXivpsXtT95x4lbV0Q5xIuiD8sIisgwD4DX2cH3q5VfqZILbzw4ovY7LcXRlPbfUmkhtUCZI4sTx8X@X0BN8/KaO4omfGUteZZOtJyvpkzlUebJkVIQd/XumsIFZn1ReMRwkhTO@ZbsMlaDj2lQ1qBnvIOQxZqPwqZphHFTWcXhWZ7x5fYaUSCkIIqz7sXePOYjq3ZRSoL1/al1Ba1YVfqX4DitEAjtT@qeWiKppBpYCNqbOSyc1dmDa8GznZZn4M6XgVTMO18T1@hoo1KnXE/fRFhnHaMS54euM/CFRmlIihhqNFS/hA1P9iHMJKQBTZ7Me1cWd6fKqy2QTiJkTrL8NY7tiHtpydyl778o7ECP/EHYfP0azSo9f7M9eZpMHSEPr/1XlkfycDRBGPBGrtzcB4oZ1nJ7rFcVw5kl45XZJGsQY9Ya2mtp8yj53Un/sIeuK4stxmUVSg9z6zsRtlkOMiTto1xYuwmADJIp4l0K1MjzZ0d0U1qcLF3Fl8jkjlNwl3HGiukY1odl8Id6VOXBVDK@BpV5bI5fHJAnhph@T856Zzq2NpNWiurXyMmtQ45/9LbaVmuCEkYNRg457K8jQjCXFV8hn/Yb842v7AMcUfNJaY8GrImfaRrwKp9druKM9dDRwUgsXs/l9hIsvsetB44cnck5mFIcoNA4xhr7JIw2KbChtHm1NZzDC4rJRUv6ayYFlwFNFigiyvxdbFATCRDgDyLURn1wjxdc75VrbeVZLnAN@sPNedeYYralmv/fGgKm0N5ytyJvMYexj3IwqP08Ff1rGbh2XFAAkrmCu1PiWPrSTPhSVd6Yn0B1R9uXw0wjn7ccewvR5HEwKhC0yZ1bdmFyIo1LiIUoEGCRqIeKPsKvRtQXsQe82IBpPfizAehPfWJGT6jST1nqno@/0ZT6PVEf1OFP53iWRei9ToWMxdkZPZn1mAdwKvY19eCTdyPijqbvgDpkqWdjFfbmK7RcOtGbfnXkcyodqHmeqUwEWFoKbzKM2TkjWXWsvCQXVIoNgsV9WORf1Fx8zX8oLpZMVluNk7cujDxM60zW65WK4qhQDtv097aYkvSIckLyAyNrREFYDIqldIKyvpl/gTLZAr4Vzw4RdoeUPYKqxSr1gF7qFF4po/zJcIgGKN1NLtuWp06jk1MHnk5MgicTdMCjN8goNQoqL0@S/HXelWe9jYH6Vun@Nn58zd17S1dIS/MIPBoWzWHGiZ05SGlBHNrKyDwl7UR04hxV1lCbRg02N@5p3NhRJ/pK7JGxvdqrwXd1ZiWVVmfeX/AQrgr8ocnjzBGjTcmtaM@d8qj14dVApiHoODVqM35mXxbFtrsUUaL4JtekONB4Z1T4hnbUZBCAtxxgngSUzK2zNdZ/l@5sHabNubn@CP2ORa4hvDi3kuVoq2CrRiQZXxiQlE@JSvZOfnslT2OXD3Q29ahVnxXQr6VIFPdGpcNZ3SLcPjF5bHVkqQt8GaGlZW3q7Nk0v6PlYvBekB1ay56IGx6FC49fmYsx3YNDRjalcbHlldSwJ3u1JJWKS5aju@V9CftRmhWA7FH1b0K83kz8wgeyBSShkz3ktapZ3NzcauYYqynV431peHjbeNDc3paqzFewN9Bx4q208WyrJxAa0dv@NPgdE5xRHQ3/tFvYETwwdBSe5dSHo82Kp/RTvZramwS3mYRPySiq6G@5pDN2YG6k2yb07TXInmShSk7o/l6viIIuyh9fMZa1Wbcc2WFRF1BAVeocySrr3jxJtamttYV/8THk4Lo3pzBe0Xgs63Km/E/ygvxSxLgYX42D2moME7xqdb@JWXlsxqGSTqU1181aRqRmCuSOoMWBO@DrvN@zWSZAJ7DDu4Iq2Ywu09OoZw9GWf781iwAmOUVBfVXWsRhEv@JOYz0gGIQidhwIEnpvYxJTWquCGz4sLT@Wwm31g1Po8/Ubz0zgGUSKWTDoymQmUNtrWbAM@ics1ISOYDql@GsCSRrlIfkCWtQWypqkK5v9VIVohoaMOX0OfIF35rCZ7gUw08kaHQb8g5kl1@6s1/OsqK05aqDggPNzUG9@MuCkMfBn0kh5NSRfi/LO9TJb5nO4ly@cS/eJfTacx9JNiFu7EuDciaS5LeN4XOmyA6TykX6zjThTeyr7/ikieWmQPIr474yBsYgXqJXXO0vMyD93l8@gEdOipyFbZO3PsXHTLeHc9WY0AJFhXny5M05oVlF2cig5d5ZEOmTM8A/VMU1C95EWjjjZ0PZaWIbIF8t3Qjd3KREyt@yXzXuRO@zljrJcW6whNMhV4I89cQXbPAF5DNtJRESlH/fGisHSrN@nzXUGyjA3bPhtRK9N4Lls6YWv80APRdLiUdRM6qLW/mX7MswBBXx@eJPwRRwRp6ESYFcPHjgR0/NbdXBYofuVSYgYAXsGSVIVtYQ7hqGOjT7mkHTUMq9ASl3c2bSdOrmmnCEC5ydRlB2lqoJl9UBLKtil0tAGvXVGBxY23KjOluu2@r6OHfPZlej1QOnMM4yC9Y3w@KngAyNi@KBwfumLD@WKMGXmnjuZyuD3rq0y7jbMmXoCXfQVRD78K2b@Za5ud2QzdmW76tecMNkaxUDabkphRHIS682nVfL0SbeTomNsPfLIhd10qKko9/iuuLwP6tbpNHehOW3b81KB4OH1ciZATsra/YVDhmjEvNDcM5JBNtSlhO/1Dcd4kNHsQiesCSKku1b/Mk1GMDPBWNuRVfw75dzUEqQL5RUzv@lxz3/Jiw5FIKSjqwijvWvBSCMz3sF23MZv4KQ69xngQZ0tCkCL4@Y8skhGrtoX2rF5Uz3JRy6axXuwQtZoOYEn6OGzducB1VD4@zAuVGyFOuUsZiwKJa1Zxju4d65Jq39Zw3D0uFX1Tf27cvd5Pfm03aEKhtvEA1kI6h7lrenA5JuR3ZgOErKMU5c57lWGopxvltrejP6jQb3F8MEIIK@lwcnfrkmYiwtjQkcsmcNxsj050wfB3J02IPamOIdOb56KY6LNfypnmlkPckv2mruTM0W475D92HHEcDwUVfOMibXC0d/L2BWZINM1B8aBITlvAB2bLtv@f7wJs8X6MghOF@@BwfmzfNrpeL1IC95TRIFiIretUYJpoebZX9wMtUz4drmgYkg9dQSMPAwo4PPmEM9gC0hmbb4rxHmW8j3mQ@K7PtqmOOa7teD35NDOdyoBfhNt62vpldi0kvpvViuOuV1ziBXKx6cKXF4OUqtvjVwrxoo4MWf@gT6l6wgVlZ69pqq1FA47iYod5Td2cwmLc4besud5FyziuULNggYuq48BEpxs30rvePMeS1bmHfZ9TV22VOoBwFL9Kd8UnUYOIgIJiSHB6DArDKgQuhLP3E0jGTx@wsjDx9Gqa2Cg53WXSxhL4PbLZDvTYu8gh3udK89qmWrsygf5xrTdaV7qruOV9JAI1zgXy5TTYOxJbLlEIk52CWzAqhZfs6XI7GSRqzMh2tCgmDZ7JGFuWMAdKZV3ICaa/0n3HtNXr/Ks8S9fW9UTb5Vae2SufgJOurlkIN8Y0KJEJWfBsSY8tlyL/VtFMdTaW3EAdmKU2F71qDn20KGnJZ9GgeQeUbK0StpgxfQuAD8U10SVeX7NGuK/YCdXUbuxN@eZo5kgpvk52z6KHSLzA4DtplUprZ/SVvW@Fio693c86ZI5CrLeNkpb36bmcRqgYYL/OIIbdmy0v2BHdOEglK3JsDzXaP6QISptNNhIAyhhiiQ3M2WP9O2iepafnDr7Lrezu6tkR4h4a7gaRAQ3Dt2rgx3Tbv@EnRrXXvMd/WYo51ZWqZwsibcb8vlbN7tV8cBvajhu1cazb1R3EyrsP8u82rz3VozJtDxj8ShgcYg4S29Ri4P/OoR0Bwfkqav3ldFT015oG24cQOd/MPVb9K3yw6QvsAgEYIU8s7HrcOSTJTR7ZvhiyizhFsarPxptUqB7Xlz4FPuuWAYatNJ9paNfzUnsOv3ssLIactyuklhoibVxlaHnHQQgxJzOlWdX9mWSvhau6@h1FUWoAYtl1@4ZQ/@jW9G/tZeFAzPtkTNYDPUZQMOZmV/Lsxv9ow46azSiP21jYElfwiXyqIz/r4ak@1EoBzFjEZwxyJsWrc3nb4acIvlszwYmSE1R0RzryG3RSWFbPhyNk0s8eATmhWBKPsanJIOdqtLwslQkY6vUUNE2sIa4gviCFPkkIQvCxKPdONeazyjFqmsFzMveOhrjtZRq2GRZxuVp1myN2xbN1275k474gxjtXsUVWJJNVnQEmDMlkHZr@mWFg5UBC4MYTpybpIfWVxffvFPnxPjoSb6lWtPxjlnrqeE4zqKBhSePSv0OnYy1/JZ/iVJ3jOttuP2Zqt@YZJHMyzUN7wFOEup0eGILupa3mZ1IzC8Z9@x5MIvBEkylmnz5okHL9YFacgfBlbjzoSJM48N/EWNsx@0NC95TZQ1qxhlTTtOhelkQKi0yPOKuFfadi@q5Z5pxa@Bs5766oVtDVUCmnO9A2EKSLpg99Lk9dsQAzAcbsmyZs11@oi4KRl41mxcakeMt6tREZCKxkbLiDIMyq/@i4GnChRGozs0gueozxQJ12togm8OhfIsqaLk7Woec/GAlP2r/XlE7m16VLBetP0EkKiDEYhIzCWpObfE6EOG25uHdWTiHWRsOtNuTL3SLNFmQ1yaiKmkckuwc/IGEudw0bCCMyOfrWZUYxiuRtxTHIP@yd2hvc0yNts5/z5jIbZGDBtTbe9ksaThaBP/mmqmRBFTqqYSG9gWin@Kc6ZG2Q1dDQ2/tU/lmU8dbikkTUgT3BvYkmtQNszU8LkemQKiZpFjYn8rzhtjfqK61zuyzxlTajBjL7ECxBfscYbKG7pcn8kGE44wwnNZRY1@g@rhP09MGnNGfJ0n6LFEBWwMTVwUWz67GgDJ2WxhtkDlaqoLboA42I2Bzv8THtKwL7OWfk0H3tSRJm4gNfGa0L9Tmb64yowrUB88pBKhZnVR/9WURwFZZFfNsYa8N1Dx3hs5tFfrybV@Uc6XHX3jXDLiyBLwJ5qDEB2qpPJBzPksGHltxhtN9F8/VEGduV3TGMViDBeHRUPCvqDUsyFJnAD5yxm7ohcmXv/yddASyUMzK0hwmjF9pEjnwjdZdX2NYtnW8DglOJY7HxhRVLfrqRpE91rc8S@ZQnaJV9iwHNM40XuNZs/ZIVNBrdfKl2gZJdxbatMJI7@8xBCR6yaZX3dGi9eOjyJXFIQ9IG8ExN5xbOC@T2pZdsseYZYPdxM5MnfPLQBWuUbDr@Ecc5pfZf4kCCQPa/jEllThbt45eH076iUCAdQpoaiV7Jjt258DGJIkhxj10NcAVX36N/po3hRS2P4UAivYSbKl5NrU2kxwXM1t6IZAYbLXHdhJJgPvomjCZtMeEMux4vi@aMlV6VOdwsU4EjfhgEKColsIv4MbHPxPhtPiNPhT36e2d/PMleiJGGk2XAGAvk4zk4nGTyh5SrIbVMEr6@iQVdfaA1dsll96XlhDM1@1XJ/l4/dDfLvSJzu8vzykISi4LVsTOi1x013Ftyf4TXWRjUuiEKTuPWAFyNpU71aN/djsjYaqvOefw9JiwfB846y6/OmQYksa9CvMNSDBMoJrq5nLqFFCCOTdI9UCnrkQgDyPNbQ9KgsOeAPCEvufjd1Ax/acNU2/ZTDncYAtvpiIJzLQYtzTlkGIKNH5JrNQjhSiERg7/Fl3Yph2kwYiwT1pjjOh5jT@43grUEt5agSuSVK17CzqPXlU6BPoHD/rC35m2nI1j/SKZGFGBszubodLt48G9lFDuhErjMvT02AXlfaXl4pkWJtEcmUBgYpNMGHZnExpS9hs4BxfF5aMaV@onOix2HV@abjTOYmzmjh3ua6kReN3Uc7rJsgC15vn4PjLh1XrEPvtXI4CGJHJ8@NqS@uo9sQl3BhYasMKQnlEQ3UW/q5WQhILgECJlo2IZomh6CgB/ZC3hf2i7aV9kI1nLCnHvWPXv2ny84QAQ8XN2/NhkQFmwNbZuZHH2SJ7xDWV0Bpfd2Sr9CR14GfjcICQ7Dk6cviTtNh/mG9HfIul@ktyEFmHSqTOQIPp3yw4sFgcxeyRRX4IjkMI8wudDmuHNKTZFU3oXPqkq2FrxxfnPuI/iAXmj5x/1aplHnX8TXv7RUXXVqqHpq5/G74t9YiZpAUDgloSE9Y4/JyvVIIGb8eTD43VUIWLZiCNyIi@T5DiiSpkdL55PR6gDHV@gnL9NQIMc1KwNr484J9GZ@3J@LLZhv1kWZhJkRtweAl68qwsVd9gh1nLrGsb1kegTLarHY8he9Z0COUFAsebyTaG6LzH@8sX6Gm@bbOXOIOf2R/eTTPNDU4qXS0XiZ50OGKg4nN1YLZK5mrY35rwyXdtj8/WhNRmmf7CPQ1nvZCHHG6J@But4wi1IHUgCVfh/ZCJpKta8J@dFufuztcfWHGF9jtiS9V@sWkg1fqf8AsCrCe0QanbqLDsdMEAUPQK8eB1/cbTZZhABMuAF@vOagw5MekUvoxLG/t3GU/9WzN8vzV2B29nGVCrFUW0o1FVdPRwhoxG5TaLadyDh9IrPtXjpi2hBJpi3sD5bw2ZR3JPkHMnF4ZZaxO4DyTNKuYQmuggsU0U8cs12RTTGLTLhCV66NHqY@4AH1D4o9Fy3xSwnjxU@R2cSc6cZTpKR3mHsr3RllqTW5VCogW48Z1rD/xH53JJUbfV87JGnmeR1ZuD@MTn@OrJaldmxKclpZMo/9n@wTtZvWxpgxFgdS113TVVzhrjbzbJ1KeH6Yl3Q7wc3Plua7TDuH5woX2ZOwPSsl@B4z8ZFLDXjJ/0NjW5AphDfIMvdNd/zSb9hSptqaEbQyeLprwUlX2tx7pH7acsiR0rE/617KIPPVgoP/NaeG/8FQm6HzCLMHHcNytf4w4LLJ47F7dYtL/C3lMbvYpOcgoLy6cPcpmTcGSdu@lohp9cLZI1Ie3XOGjsPIk3n1mefx2/HkuKcBdfsxbG8YjZTQzEC6rpfVY2S4PvvwPbInqiRyF5UgAAUgX8KIdPg/KqnQkbvm75xg5r4s@xxiQQTvySuLEVtG8aQqjDkoeviuXZa@1HAtFv@X8OgSC/N@uwycyMrEDkYDEbEiYes1VFHvMlYzBEPImPwiy90y/q89tgiEJ1fruxyNioYLgdzd1DPnbL4TE5QRpvIQ88V9Hu9xX1X1TURqthshGOvznz8U2WXpwJAjFxMp8yvfpIyLUtzfe1DFm2Cgn6jLNpRdodyMhPCCdxxCc4qs6tPHg@V@T3TDmBKbWV4mfEqXnG1hBF4InvU1MoyXArMRyMjoTAMdEvYOcLqgCx5z2veMQB2sPm6Mju5nCkbD2z7/w1exQ49DZ9WE8FKWNvIOWTCWNTnX@NhW7wDQp1Z@NWL/DNEfJbw2l/Dcl68i9S@LDBPFN8f43oZfSagbd6mAeM2Q/4Phg8JxTHK04tGn0xTpoNDi1EzHP0J@1JDY0H/UvMSAvXzPUqnysNBdNin3Jl8XQ0UuVD4eMseJntw7ThKUfCosHq4i/hOOuVAdn5RxhknXJpi1dnYNib7z4YUTx@lykCKx69/5zMyhL5rL21gnAGIh8Q0mVd86RbrlDPuFLqRlX/NmuwcfJNVRGBWM1oymXhh@DlxfJ6p1z9NXrzWEaHJYnKE3KSp/F662jwUu48/Jqy4Eg/1GZgRucNi8cmogH0l/HnuzjrZlCEHhKaHJmg8O9k2OB7AbhOh8iDXsqefRSF2bGg/LMhkuJtp//e0LpFVdZXPaNBgosJW7gvYSz@QkEbeOOcQ9pWJ6EeSRciizV@Q7j/Kvt30tfsVpB13jx73lqv@LnKvbfJL29rLNFBuorSFAKZrZP9yFR/8U@TSd/5PlvJsqq9edUAoi@BdbR1FGhlSoWlF/HUmYpVLINUXAjHLIh53mRzl2AjaWMDPygl9mDcPZS9FnJXr5wQvbzQ41i2I5AqNsLeoozwzmGJ5QA3onPNRYWhZlZzHkvHdGXKTdBRxETlwaggQfjeZfeAyrlVgEhuSuqOPwa8DOYok44OsofF6oiJUdLWisXmf@DgyCiarZNmHWBDhiPx/iqE4PT76uE3pSO3BJmzKkL4/epbbQmlvgZwMQLTICI9dmlf8jQ90yDiI3@RfauOPesCUrG5bIx1nFSgCyJGVrH66r9IN@wdldQQHWAtSqai78q14K@lS72ZeeMa5Pc0dDqO7Bfn2eBYZSzV1Yr2Alv@HGI3YpjGg1PkFJ/Ty4k2sLjyxDca5dPMSWzzs2oeeiDhs@jF57S7W3OsMn42WQ@6qHZkzBKxoykqVKM64A2EZTak6fVkCm3MDWZhU0ix/oHhWEq5RaaP@Op0/LHHGldyP1mFPU1qauJ2TMov57zKwJpJ9G1MNreGn58oAvrfZ7bGrBOj7s16haLQZ53J@oEOUcxYt@m7NqBu4Svxf85MnuwM27UpXlvmrRvT/dp5DqszA0otu0jcnLOYNX@4xcRxDl2cFXA7CoxhqPW3t3xkvyo6qcS3CD8yKkqhBgtj@CGBeLJ1tb5mWq6l2ZJsBOO3JnzBTusfC8k4T79IJW@@jmc6/yf3oZjte4N8Xr2f5jedDaIQ8rldID0rKppBuJ2NaWvcRTd8ZrqqIkvK1DhZHUw/zEmEDP5a5Hn8IU5Z31/JkQWDXvy7iAU0@JDYFKI691dTM54ksdcSzUr13hrSCNdBcAsGr1SFq23RI4@iUhMQ90xAyI4Tja2i@qitfXXjZ@OuWe6f@eTdkUxSSS5ITIMpRr3DAUcj@@cq@/xHryUxvxvwcj9/o0@4gKtCrJpGdDtG0eUBVM0z4BYhn@HyKoIqlUguyUUk2Y2iU7ZVf1qkTSSSFFoLmpH7GnSadogN6uql62rszvrAy6z2wS9Rl0x50RIy85ZaBFahMufkzSz5ytqaJnNPx0Qq4ABv9ApnVfht1BPuGfBnDhtbe86MLGEkn1IvqIH04ha2PRLP1emo6F2MBRg@HRk6b6Mt5VbfG72B3AlXFANDwkclgO0loSdnuZO@qaRkybopy0xX3ZlfVQISbk9XznZqoy@7yTMPwKxLjKeKX31mDLq1@oPDa10UQSCeoEvRT9MjL8sNoZGohoi22R5uBOTUAJGKDly8mtAol@xWGE3kW/TL2Ra34ExZb40zepGr6Z9VNZvtuS@yKZaUHnSUBxkNbhPSHce9Xi6MQwu8YSZPVsJaW0mpeGTJ7jv4GoCRwU7vbFMoP3m85plw3k2902KjHwgL7uRIcJy8FJh0JkLjMSB6IMPV//u@sL4r05JftpINmtSgD@2kYCQi0fUBoyBbk9d7KWzbzzj9vu6r8VT7JW//ptFCi3kbnE0/gf41o2lNiM/mSfc@Br2VoAzacpdRbGg3oK60AZ6Qs5ylUjw1/3ZPYG/svcrMwo3IOeGLJCPbEodkQHrOFb8MwxtKfhPNSeVT92VS4cy6I9nEEdnyQ5Da7Elv5Zx7uUp0Yuf21@AF4FyDZ5L5yZIYmTRh/msqZHwUs3iSpUtfQl4aN7iEg5zUXwZEzWTS3W4m6hexZ803RKd5m8HCKv@I1A5b0tNlcZDAuNpTxF2dxNy5WhQYjH2mHn/0g19DrOE19bO0iGG4tNw8btPzgpKaIGc8wxUhtA5igyzvCAlExoH8a0S6GUcYp2@ztJkQSF7vOF2ajvKRJZfQD/sqsI7sLaNxwmTzORFzScncmKLkjvgU3NfOi3Ry1q2rpvSIhYm6Nb0FOWMth4zfkvOw1zSSQ7r2N2c4x@E1FzR5HocTOC1fDhXV8uHiUnT8Cmn6h03j/XKSzAINKVt54@rIffUVclhTLksW7NjFIj@sNQsTWJZzBjWHqSxPqoOtIRfpi5qFZBKo5mAMcEOtE7GLLw213fiiKB6zsd6az2RUw9aAeM7Jmbvkwm9dMOrOJlpaUxLDWzsWrIr27FjpxHjSSnviIIUWMPySCdoWkYMSXD4ciCa//sqNVmWd756kWEt/b0AlgYVpa2WpdY2kmm7UkcNlUGzOlX3NcGFbYLI1hPdI3fI3z7ZJPVcjazDqgzi/kEk14i9ABcEMpistDXStoC8SQea2Ru1wej0quVgxozdtNb@UDfmkqZMQ3TaW87Za/mjP39hibBLC8EgbKKyIiGwFSjjd1VdMxtfgXtbENs8yo0WBxfBBYqtIiAQgLM6aeRwucDS3N3olx6UrroLegZ4nLL7LYmawN5fjaIiFretbK65R/y09Us@82@jfWIXdAYfPs@B6Awnwf2gHzhzb36iLkoBqpnvx/KXizYBVZ14YslfeOQ0jQLnH60ZMjkWFBFrR0eH@ZBqfKI40ayltjRKgijKEkm4vsw7XGkO0qQrNq/zrFuahnec/ivtROqfykaVpuLFely9sR6bguQhGWj4awbUtawYNpOL/nnEQ1ctKl83A9cj2PMlw5pbSESxhGbE7fUt5Gr217FCc4qHKqVDyMBO8pOPx7JzD7laTVhzFvG@FO/kh6LrWvgU9NoJFpva7p3dUJrN4WOZJgDw@6EaygPdAY/uKjpAEiFCTuKA2XY0CqEEq8P@z3c1p4okJ2mQd7DBGkXnUNGYuNO/OVlzfupHF59LSWu@exvFm6Ock2kBo4TExI3K3Z@pLm7M15Y67kNovOtdTQbyGoCTPkIR7kN72dcaeU1dmG6xjrw1YpX4mCDscVr9UHb/OUtnAbrYonA6aQlyQ3kWOfYRr85d88gb81rDwc5XnzNNeNN7F7L4q3vC4rlrYBNAcJ7Q2eShdCU1C/Z54Aw0fwe/ttInVHX5IFXk1VXMpas41pD5qzp8mh9nE8a57VmgTy1m8BtLpZYazolgcRoEtqw/GD9ar7q7IhKeT@/C@ramZiklwWXytp5vVX1NaIzf/9JpvoNTzNDg8lDEbUH3fewFfW7YM1uvXsFn7V4puEhEsDWPg/IfuouwBjgnyGP/NLjOUpAQJv1jqb5YItd7W37w5YtzNY9masZE9hbbOUU8jP3AeO088gm@RXqO/r6qtdgJTXUH@jdqfGbdQ0IDJsxoHmKOJ6Q70e9keAsCenKdUU3Anna008c0Dqdq/gjGfnHgNKsilPgNi8AoLM5xrKawG0poK@CSrqvTpiNmbIJ58pLHXsf4bTnI0zSAQF@axnGpeR2Y9/WR9TS33/Pdko03elmOzNaamwGE4Q3wre2B12hR70OueHvmKW0fVIlBKA9hNXHl2ydDRpYHHqTMk0FvT0JuAQ1X0RQhhmLAGiTOpy@jQfgb6WXx8fN7lYIppgKacFW@jcLIacyDd9VyMmcjlbl26cNoAUtL81NLaZVu2YoSga0CHprI0b7uWANWQ4axYzzDnelc5C60RaaDwLT0PW806RhmkZzKYRF6WWmYW@eANLGD/Q0m37JQ/hOm8iTipfBklCGGLKa6PklZxD9wwZuNXBwaUZ@3lCCrvgmfTG@Lq1QqXqtJ965zWtLyTmu1RxBOuFadAwfQ2v5z5rYGGworhCAOae7z9bkv9l@FdvJ8znRc@JsUVgB6bKAy14Vf1RAGCi9q85zkvCDTNTY8nibIYKJ//NTmimYL4UgjD358AwZKy4e@/QeVb1eO9jGKQXPJjeEOrZK@v9F/1fzfE522QZqa9X5YQ7/GHzIAKVCBphwSXPOupQ9oqJrrZlV7dGV9AgQ2dK4GN49CML6E8mz9RgJHVemvI8SRyuAkQfF6aUgFOjN8aWQ1xvFNUv1ke7s0aa2DZD0k8Iz8oO7QM@qWE0Js7Ymbqbhl3lzZ@JYgNTXtCB4wJx6aJgu32Y0TqrX9JT0wEyPeFnc7XIHm9gYp7RdMHi02IUBP/de6XCaK24VDHqq1PsTx/UDDw/9cUgoSBe141X0pXCrwjlnCdpvoPplscKKxrCGUg/9oeXhxH8iONHSgeyCh03UGcFta@LWDjSFVFtmMjR9JumCiTxIa4NrapV3@WzaL/qoJYCSkwn0ZNwLGWJK3WKgfcCwfwqj3PHTOLq2XJkS0sW@29mGq3NDQsj7KG6iJHvr04/RR4yrmn4rjSWcmCLj1FwVpLew1cyJUAswqJUifeUzxC9jjq/JrAHD/rSbV1NTkMgu8RkFl7Shqv2K/Icsf2F6Rk6rodRlc0Gg6Z4ejVQORzQWzK71uE5X1BHlXHU/Kjey6v3gv5TwTTpssT50egthK2RlUsc1llx1HBZRInvPWJVJLrV6x88GLnUoQobkDyxX0xX2A48YfyiFjQ95GLWEnFZq5A1k2RQiDTPlIK67a5@x2/iuWm4Kj@zzVYOn83TlCmcJkaFtMKMnw0kSA0Bxvqa@Tfk59FhEgSQW6xsVq8yiNznB@irBoTDvuWuKT4zdcfESreuKBypJMM/IFsE2NrtcpzNMxoOzvLAEREA@txauslwEDzyXD5zW/JXCDxB3U5bijaZAWX5jWxKimzJ4QExQa0k1mh18RdR8ObObz1lY9dPj9kAo6IZVmVDnT5PNh0OV08UaTbLBEOPNV7zdR6On8suIZUYePgsNAQbdRluCbf8lkRTR@BMgv9sx9gLHZqqJHn6JNJW5WdgBGooksl3t8bnmaRO2zKPIIVr1oPOPz5ETfRUrWjwwdurKeELNec@kpc2YE2Ii7vPO2cR46MqxXBmtYvQmtzdo88o2IN7w2raeb81hjBLU87CzBTRSXCV/H2xuDXJP5lNAP9iHXalMzat8ALuWo4wi9rbtHhCuY970h5P@qmoznB7miZ1HByzwvw14RqaWbA@nUkJ38bDiV52P4M5jT7EXP0BJKk7qkppbh8P7APARL4gLUsXbMhTLUKMfx1TDQgXVyjQIBqzipGVg6sL0sJfDZlWfncqhUa9PJbQyKxnJxbr83xNsU@Kdy3pkvdTZm2zhLpxsGHW4LWf2u/ZilGPdpAOASqXwhic6gyob3z/NbGR9D5p8Ru3rc09xdRQwXZEOW0TEyjwk2ACGfEQKVsfq3R9eiByHr7C6n@miZ@NuaMwMHVIboEZknVtLks20svIhjoKAFoGidIg0BcTn6vWVmNDExSfTcGEFfX2CS6av1uZtY9ALJ@1PetsvfE9NdkeDLr5MWwL5@9tMXNm18wGzYEhfOVUXT0tl/ThetwYhjo1RchVGJE0I@sL6wXGeCMLgmgvAKHs23eG/qlXSAjWvuu8v47VodOZ7@JnxHK4/fpgkqvyF72EDpwdg64R97H6F6iyb6UHXfeL5Evt@ZqCHF3PjqOiHwmlj0bBq7woENNmi061i/8NaYdHTf71rN2lbWu8rbJzoYrppDJqOlXnXblwmxyrnAvxYjBabaj3hW@bNOxEcPunPspCZC7lKY0IjvwfotZDCA8Fz7yNfnduj@bFQxRgJpdDenYv8X@ThspirrhI8OALyHPkxg6g7dGzBVf0d4zGUYvKRP@4f8YUCQOriAtX21KPY4v5YAg1ZAYLlMywbOx6w6ZDHV/cBOc@acBsQw77KU0zI2FPbtO5IMYqTQT6JFRQnSODMPKrupqmDSyqz6xQW/nsh7LAGBb3J1jYZu4ekj2TBDP4hGdgPP8zO0ty17kr3QkZBJlJXeMW@I2OAF0zEj6X9Od9GjKqe26X6NzUMx0jYwQIWHJPLHZ3YqwM1ZCnoZaZ4DtJv5EGgrtV2tVmpvRSQJEzvvL7mLPsUiRIaxTKkhMmdUytsIH0gsBrWSksCF36iUL4kcjGpvOSKO0N2dmTXPNVpVXNJeiqHR5d1xpUHhKQMJxYO0llj/EPno0zjjUrCBqvLAGFGeerj@KXZsvXi0DCnx4pvFaAaooGgBeDqLuQXXfeAdzL@9oFr@GlcVKr0dj7DbD5mXfyaIJlHs1n/BYxoHNPMsr5Vn9FSTMs3GfKPBHXDCc0mWdoZeBqX69a3yBLvGZXT9ZwZbaormAv1Cyd18VEQVLk@uuWoR3eiMtZdgU5RI6TlctYc95NjXbSk9/mT3bGVeOcFdzNZ5813z6uSz2/hmPN88kK@58jhedDM8gVv0WE5SBUHEyo1/mNtTWcsA7y9XY7IqDeERkCXBLkzdyn8DQJq1/GqmawTtiqlpcfNG2@ZpeLxW/lqdvDWriZvVmPNzAnhAv7PfrXMMKDQq50vffy4BGg8Y6shvegA4ibXif4yoRC10kZF0mniJ8deTynTxz46XYeNC/KGgUGsaxW@YBrG/TAr/GKadZx8dhC/d/Ld1Zgts4EkXRLXEAp/0vzM5zQ99dnZZEEAi88egjXiOxoF3G7jVg8gYRDZ8Ra8xsVKpSlpEEkJsuMBNfx6loI6kSA0UkqHFVmtb2njppSyEvQeBolvv2KU45sj6G3gmIHDRREZkcJFbN/YkB2McQpg/iLpItX34d5@hLnULPEUaGVabQ6B@Kj79rnITQyJVbXx4O9/R3ID9@@D259SrmBothmFeu7U@WFbel3UIguubwM15KvOAEVS@B4OtG2eB59cFpIrrqPZHiv/XfQUP7GwjSXyUqKTWZmQdh6xVtQ3jFhJnQGeT7pnwdewzUssz@Nz@rL8PLuidWhnAaEgkTu@pfA7ELKzpGSaEHJEuZblzC6qi6c@5Uhum7lkcC5UJpdfrREpC18ynfrUOuMdMW4KTYLjynklNxXOS5WaQjEk1etGdewknOzChQDGcescTvT2L6ezKMnaGrpNeSMPIReX3HRF9Hlq9AUmLPDmNHh2YE3Jj4aUSCZa4JzZmLCR73S8JmFDXzvpN3VIGCO2ChVrkQa684vgoBPeLv11ItZOeKzHOFKrUKZXJ2A6c4a9IOOqpBk2S8etUTHMj6fxeqn7YBEeuWQCF81TLDs0KV5AVwttuVwaOQpmRBbz2jAle3cp5WFddnUnib5OMH2wMtve1Ge0HVOqj1NIQMUbNVOm1@IWChTJNMhjs18L4jyJ9K14t7IZqm6qZtbi72y/AKD/vNg1cPriIJNMjIAJ6xu@1D01wpx21qIvmvacl5U/RVD7Lq4HbegYGy/stPQDacgazGqhIFWEbURJXhgdx90y6cYo5lOng43WGteQhpAp5qDY0qyqbePvCXssoWGOufJANmiKjoeD4zhXd7xa66v4As6GDLRn7oFL/YjavSdjvmHjQIioQRK8RjIL6qx7gT@RyF3eMf2GJ0XLgAH@kv6ZFEG113YZaMGl14JuyW3ksixF4zWQjt3u2hz52S8ChP3AtO9QP@ThHR5/KLs2l1YlaHWhpp@z9EUw6t1g5jhmtmZXi8f28VWSyFW/VwWDxbeE5yBnuyRClJpS23e@@RkU9u46PcQLKma6oTCs6xq4z1ujpGfSGCLkCTT4LLKzcRWx7i56tXd42yatnw3xqJQ89BMTlLTHBX2miPtzLaQOnqw49SQrasYHeS8yu1dRlJKaNdQTFJIkq4SsgX3mTcvvo7EYYID4ef4Tf381nmXME08M2q3M0X23xvA4ZNIdfDW6zy0xtiiN6TdvN3Aoz838D3K7lFOapncrdi69MxEzCgUL63g8u@ekdf36WS2JEAzUXyWNtvv7CxA2a0V1klYfHIngUi6JpTlcAWQswgZROoItlFBIdG0Ut/arOqsSvr3Ypiu6eWwhBEkUlbauIt@oq0RqysGa9INNQkjI76jF3gGPjnKZ9es9P61Y8CoCtu3wo3JZWhvKkeoC60uFNtk2dIT6XqAVAey13CJuNjdTnncLrCjZiCk5W805t113bY8Bvc5RqdR8IxuLXaV@qiM1NzCVtqaWEc3i@xJISFX2XuZkLHQpwcxoO7wE@KKidYAQx9XfaKE03dDh68p38n5Uc6ACIrUxDrAaXS0XB92raZQZJ4Bj5jidzkUEeGFmAigobJctXOQ@PK6rs1G@JIK47m9sdfF1ZoxaU8rrAEsSrEImHBSEeeStS9uK496DEX9GvIdJMeiQGYSS6XeWx/a9ouQiP5VH5NYOEHVkLCKTuiBgufK0dU8Alxm9sfp6@zm9SMOAksLvCZd9eJVs/CnW3xKBmrImZb6J2qycWkVBU3htVFy4RwpPi4xlW9iqbZZps5I@RVUNEOAsr2xsRGtS9Fs83aJmD2DP4RBjRhrJMIBHJ2FrJ64YT5JLKhgnKcMk1naxr/uPn3KrYACTpwSzHxb65wsjLmBK4uXMbqFzGU2Oh8bHASIrvQ9xgl@/5ZBcRbNMxreKlVrK5eExMWKk9gPX5bVULil8qu44fqDvd22g7W/1S5swoYEgBMTe@4gldTUdPzeJHNp@bzlnbl7TyeZ8zwU5WCj@xudHeXyl@wGie2KCIYkkFDBELPL9MXI0alAcA99yKRiC6SK3GU8acshC@vf7@vW5Nb15FI7CvP3/bqN4FaGWxEPhR0pbD4tWoNjk71xMQFwDVY1seMYp10mlFVvcW3PqnHRfzrzKGVfPLJTEtW56prZIPYVVlIpmcwBtlfuRF@G4gdthQzmwkd2/3WbMPrd1VOd1VzRBW27XGiekmcsj1mIwF@nnZnWBmomdkDig0p4HEQAXgUMkncYhAwRjqxjNr0HLMULMzyt1g5e1QQpXuo0Olv3RPKllrzqMPR@eBv4XjLPGUzeuMg3Hzbqywvewefi/ccfARHIR/dxT7sRZjvxWbGtVcgJ/QOQPi@IZvCtSRZ0mhB4b46LlybPG6xZ8RPco1LLwQvpBIlhTwjve1hoq7QBCn1cMXxykcb5j5yytrfkKyEsv7IXY8bRw2JiMH6rrFupyQlvcNAhjUWSuua0lRPv1qySPGrd/igl/aeDchqPytpqrq5yBS5IorXiGOvQXO28sAqsim1/ys5eGIiVNI4yJ7amrnz7ZES0t8GyaM1c5Xn/ishivJT0764YdxWW7jiLunAqAunYqKKi9rS6h4pTDwmlhqKMXqqq48UGLVJle3HA02hWDyv2KuR0/FLeXRYM3wEqsOvQQjApWtZm4nC10vKy@MoaVEATbIj3kg7/lvoDbeaKY4EHeRi2GCcZNR2NdsqgIAmOVXM2dFQDt8tg@xVmt89UMSqIg62S8rsrbwlv2e701Np7kH2TWWN9UZ8R6DtjEuEkJziKJT0LIx3SprApOU1woKYA7BHzMLb@DBwTV/H5qruxqQmTc/7kbGmj/kV2Ewd2VRHmlhtUhYjE/zV/YN8bWZPYO3VuZhle0@UBZrfp6QGesl4hQ5mmqum283E4nJFyaFSUR@xXAvfCpr58ywGRQ6X2dTSTN7/1B3hGHsmIxfxdZdOaTbypNiDvqYCl3DpHwU0exUqaIDWUa8By94yi7eKSt0Ogx5LDK0K8hMKCVcFqFZ7UKlBYdtAtYHp1xWNJnLCZFxIn5OKzk60XeD@Ko8zWcVTjd9HBQ9vY7lhUzVAsSx2hLPNqsiNzzjOarArIYyedEJRPJcIgELZ6xexXlZxQCQKmBFLIDDYyJPuFQLifjANkAAF@x61MuYgqaGQTsMWiYBxoNrU3k4XjUxnrkrFpL1b6vlnQsVXhX3PXlyuS0ZJS46KXkf5jmJ/Q1iToaZf@PuQT6mL/c@Is8gqLaer3NBVB4z3xRG5Jf8vAZQq4m8bLFHnTdQC5FDMhXUlePNS@HfvSZG2cdWsQUGbtu4LKrznvlNlBiJ2bz0AoD5KYV8aGty7Q4NWfsY7Ut01BUwdAH5ecBHIz6plargKxzT1lmgWPrDKnvdrCWcpXY5gQaWzqJ@vyO@q2/1LdKECoL@Elnvbhf/0GdcjTfX0GiWh/wLe6Iyz7h71cHWAwPOFHJPkbVF@vetHhNmXUQogTb1rbVf4nIWOhb/618I6Y0QVDMh@qhQbL7Qn4wdWajukM3f@cfvU12pTu7Iel5njzE8QcuRHknIbdFQMduI@IbtGWXEekowc/egZHqc8wnh7@bu1FtJKfsXLmSqwXE/dC47Z0hCfs9kss3scDkFGjn4c3QuRA0fYAJPXF7v1RapKNGA8QGFfRcc@a7II7s4WUK0DsWEHcOamjByDX/shsh6bHMwKhuB7DO5gwcLCyOO/oMGi@3xN8CqkiHx05eixpM/osL35n5oOSnXW0FrkgqBMCOVTx249D0U0ErtlfE0ZmzJ74rZMAVRaT8GhFYOgcqm8LtTZ0a5uGPTsfTNCe46u4htGn2BgnTS@mmx4vrUqbLXIXz9tAGaFrKHqzLJ1l7@4PWE4vgtJMSR4KzIXUe1uaqNBLdlmFFaL0nRq5KRS5wP1g5bUjAf/N3PTRka/rm/qncjlgVkAqlUbBVuT7u4tD4y0AZJxihRXDLDOXVOE3VdvBM/yN8Zt0fh3jr17L2kpQZACYTF77/rBqiGMxFHgB/xYkkdUyRnmB0fgppSJiDvYo0v3utEkEn1Ta3Z30BOESk954wJgBzlOYL8GlpI53RGZBUjmTeV3COk3uoZVaOh4O@v9kt1DxC1TyOotoI86nDZyC3r1XDQknBPbyDkrinAl4Tkr2NbsVn4VAeVTfQYiepacFm1iSfi5V@VM7@B19eQKCEDw8VyJBDHjnT7VU0P8nQaO8MebTufq21WMXCzDNXW6vHwhcYALbwKOzqXiKM0v1Km@N1MdF36uMTFxNPxL5IKpIPE7dhZSfGe3vBKQGj@u0lqm8Mvt8@@t20owhkI99cEa5GsaToNzVsZlP3j3SdC9Wn3EbmhQbQSGBZmQaQMZYwVTOByjAxxdBWCxtzJdsoA8@79//wE)
[Answer]
# Pyth, 12 bytes
```
A(Z1)V^T9HA(H+HG
```
yuhhhh
[Answer]
`gawk` with `GMP` bigint library -
## *0.012* secs
total for first `1000` digits of `Fib - 1,000,000,000`
```
# gawk profile, created Tue Nov 7 08:13:56 2023
# Rule(s)
1 {
1 print fib_ultraP(($++_) ^ $++_)
}
function fib_ultraP(__, ______, _, ___, ____,
_____, _______, ________, _________) {
if ((____ = _ = ! (_______ = length(______ = __))) ||
(__ *= _++ < (__ = int(__))) <= (___ = ++_ + _) + _ ||
(____ = (___ + ___) ^ ___ ^ _ <= __))
return \
(____ < _ ? __ + (__ < ++___ ? -(_ <= __) : \
(___ < __) * _) * _______ : "_ERR_FIBP_OUTPUT_GE_32BITS_")
______ += _____ = substr(___ = __ = --_, _______ = --_, _)
while ((___ += ___) <= ______)_______++
_________ = _
________ = (((_+=(_+=_^=_<_)*_*_)^_)^_)^_
___ = ______ + substr(_____,
(______ = ___) == (_ = _________))
_________ = ________ * ________
do { ____ = (__ + __) * _
__ *= __
if ((___ += ___) < ______ || ___ < (___ -= ______)) {
__ -= _ *= -_
_ += ____
} else {
_ = __ + _*_
__ += ____
}
if (____ = _________<_)
do __ = (__ - __%________) /________
while (_________ < ( _ = (_ - _%________) /________))
} while (_______--)
return \
substr((_________ = ________ = ___++) \
? (__ - __ % (_ = (_ += (_ = ___) * _ * _) ^ (\
int(log(__) / log(_)) - (___ = _ * _ * _)))) / _ \
: (_ - _ % (__ = (__ += (__ = ++___) * __ * __) ^ (\
int(log(_) / log(__)) - (___ = __ * __ * __)))) / __, !!___, ___)
}
out9: 2.52KiB 0:00:00 [24.7MiB/s] [24.7MiB/s] [ <=> ]
( echo 10 9 | gawk -p- -Mbe ; ) 0.00s user 0.00s system 74% cpu 0.012 total
```
---
```
7952317874554683467829385196197148189255542185234398913453039937
3432466861825193700509996261365567793324820357232224512262917144
5627564825949953061211130125549987963951605345978901870056743994
6844843034599802419924043753401950114830107234265037841426980398
3873607842842319964573407827842007677609077777031831857446565362
5351150285171596335102399069923259547132267036550648243596658688
6048627159716916351448788527427435508113909167963907380398242848
0339801102763705442642850327443647811984518254621305295296333398
1348310577137012811185112824713631141420831898380252690791778709
4802217750859685116363883374847428036737147882079956688807509158
3722494514375193201625820020005307983098872612570282019075093705
5423293110708497685471583358562391045067944912001156476292564914
4509531904684984417002512086504020779012501356177874199605085558
3171909053951344689194433130268248133632341904943755992625530254
6652883812263943360048384953507064771198676927956854879685520768
4897741771784375859496425384355879105799
```
] |
[Question]
[
We define **whitespace** to be any of the three characters, tab (0x09), newline (0x0A) or space (0x20).
For this challenge, you're to write two programs or functions in the same programming language, which perform the following tasks:
1. Count the whitespace characters in a given string. For instance, the input
```
123 -_- abc
def
```
would return 7 (provided there is no trailing newline).
2. Split a given string at consecutive runs of whitespace. If the string starts or ends with whitespace, no empty strings should be returned at the ends. For instance, the same input
```
123 -_- abc
def
```
would return `["123", "-_-", "abc", "def"]`.
In either case you may take input via STDIN, command-line argument or function argument a return the result or print it STDOUT. For the second program, if you choose to print to STDOUT, please print each string on its own line, without surrounding quotes.
For both programs you may assume that the input contains only printable ASCII (0x20 to 0x7E) and whitespace.
*Now here is the catch:*
* If all whitespace is removed from both programs/functions, the resulting strings have to be identical. That is, your two submissions may *only* differ in the number and placement of whitespace characters.
* Neither program/function may contain any string or regex literals (character literals are fine, provided your language has a designated character type).
* Neither program/function may contain any comments.
* You must not read the program's source code, directly or indirectly.
This is code golf. Your score is the sum of the sizes of both solutions (in bytes). Lowest score wins.
## Leaderboards
The following Stack Snippet generates both a regular leaderboard and an overview of winners by language. So even if your language of choice doesn't let you win the entire challenge, why not try to snatch a spot on the second list? I'd be very interested to see how people tackle this challenge in a variety of languages!
To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:
```
# Language Name, N bytes
```
where `N` is the *total* size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance:
```
# Ruby, <s>104</s> <s>101</s> 96 bytes
```
You may also include the individual counts before the total count, e.g.
```
# Python 2, 35 + 41 = 76 bytes
```
The last number that is not struck through will be used by the snippet.
```
<script src='https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js'></script><script>site = 'meta.codegolf',postID = 5314,isAnswer = true,QUESTION_ID = 42253;jQuery(function(){var u='https://api.stackexchange.com/2.2/';if(isAnswer)u+='answers/'+postID+'?order=asc&sort=creation&site='+site+'&filter=!GeEyUcJFJeRCD';else u+='questions/'+postID+'?order=asc&sort=creation&site='+site+'&filter=!GeEyUcJFJO6t)';jQuery.get(u,function(b){function d(s){return jQuery('<textarea>').html(s).text()};function r(l){return new RegExp('<pre class="snippet-code-'+l+'\\b[^>]*><code>([\\s\\S]*?)<\\/code><\/pre>')};b=b.items[0].body;var j=r('js').exec(b),c=r('css').exec(b),h=r('html').exec(b);if(c!==null)jQuery('head').append(jQuery('<style>').text(d(c[1])));if (h!==null)jQuery('body').append(d(h[1]));if(j!==null)jQuery('body').append(jQuery('<script>').text(d(j[1])))})})</script>
```
[Answer]
# Python, 54 + 56 = 110 bytes
Counter:
```
m=lambda x:sum(y.isspace()for y in x)
+1
0<9or x.split()
```
Splitter:
```
m=lambda x:sum(y.isspace()for y in x)+10<9or x.split()
```
For the counter, we use the fact that Python is okay with having just an expression on a line. It's necessary to split up `+1` and `0<9or x.split()` to stop a `NameError` from being thrown, as `0<9` being `True` prevents `x.split()` from being evaluated due to short circuiting.
For the splitter, since the number of whitespace is always nonnegative, `sum(y.isspace()for y in x)+10<9` is always `False` and the splitting function comes into play.
---
## Alternative 1, 59 + 60 = 119 bytes
Counter:
```
m=lambda x:[x.split(),sum(y.isspace()for y in x)][min([1])]
```
Splitter:
```
m=lambda x:[x.split(),sum(y.isspace()for y in x)][m in([1])]
```
The results of both counting and splitting are stored in a two-element list. The list is indexed by either `min([1])`, returning the minimum of the one-element list containing `1`, or `m in([1])`, which returns `False` (equivalent to `0`) as `m` is not contained in `[1]`.
---
## Alternative 2, 67 + 69 = 136 bytes
Counter:
```
ted=1;s=lambda x:[x.split(),sum(y.isspace()for y in x)][not s or ted]
```
Splitter:
```
ted=1;s=lambda x:[x.split(),sum(y.isspace()for y in x)][not sorted]
```
Like above, the results of both counting and splitting are stored in a two-element list. `sorted` is a built-in function which is a truthy value, so `not sorted` returns `False` (equivalent to `0`). For `not s or ted`, since `s` is a function and also truthy, `not s` is `False` and `ted = 1` is returned.
---
## Alternative 3, 59 + 60 = 119 bytes
Counter:
```
def f(s):a=s.split();a1=len(s)-len((s*0).join(a));return a1
```
Splitter:
```
def f(s):a=s.split();a1=len(s)-len((s*0).join(a));return a
1
```
This is a function where splitter's result is stored in the variable `a`, and counter's result is stored in the variable `a1`. Like before, Python is fine with having just an expression on a line, in this case `1`. Splitting up `a1` determines what to return from the function.
[Answer]
# Pyth, 16 + 15 = 31 bytes
Try it [here](http://isaacg.scripts.mit.edu/pyth/index.py).
Counter:
```
L@,cb)sm!cd)b1 0
```
Splitter:
```
L@,cb)sm!cd)b10
```
These each define a function, `y`, which takes a string input to solve the desired task.
Thanks to @FryAmTheEggman for the idea of using Pyth's feature of modular indexing into lists to shave a character.
Test cases:
```
L@,cb)sm!cd)b1 0y++"abc def"b"gh ij k"
L@,cb)sm!cd)b10y++"abc def"b"gh ij k"
```
Explanation:
```
L define a function, y, which takes one input, b.
@ Index into
, 2-tuple of
cb) b.split() (solution to splitter)
s sum over (solution to counter)
m map, with input d, to
!cd) logical negation of d.split() (empty list is falsy)
b over b.
Index is either:
10
1
Indexing is modulo the length of the list in Pyth.
0 In one case, a 0 with a leading space is outside the function.
Leading space suppresses print, so the 0 is invisible.
```
[Answer]
# Java 8, 239 + 240 = 479
**Count the whitespace** (returns Integer)
```
Object f(String s){String r=new String(new char[]{92,'s'}),e=new String();int intx=0;intx=1;return intx>0?s.chars().filter(c->c==9|c==10|c==32).count():java.util.Arrays.stream(s.split(r)).map(t->t.replaceAll(r,e)).filter(t->t.length()>0);}
```
**Split on the whitespace** (returns Stream<String>)
```
Object f(String s){String r=new String(new char[]{92,'s'}),e=new String();int intx=0;int x=1;return intx>0?s.chars().filter(c->c==9|c==10|c==32).count():java.util.Arrays.stream(s.split(r)).map(t->t.replaceAll(r,e)).filter(t->t.length()>0);}
```
Explanation:
```
Object f(String s){
String r=new String(new char[]{92,'s'}),e=new String(); // init regex'es
int intx=0; // critical variable
intx=1; // change intx to 1
OR
int x=1; // new, unused variable
return intx>0 ? // test variable to decide what to do
s.chars().filter(c->c==9|c==10|c==32).count() :
java.util.Arrays.stream(s.split(r)).map(t->t.replaceAll(r,e)).filter(t->t.length()>0);
}
```
[Answer]
## Whitespace, 75 + 153 = 228
Spaces, tabs and newlines substituted by STL, respectively, and folded for legibility. Convert to a proper Whitespace file with `tr -d \\n | sed 'y/STL/ \t\n/'`.
**Counter**
```
SSSLLSSLSSSTSSSSSLSLSSLSTLTSTTTSLSLTSSLTSSTLTTLSSSTLTSSSLSLLLSSSLS
LLSLLTLST
```
**Splitter**
```
SSSTLSSSLTTSLSSTLSSSLSLSTLTSTTTSLSSLSLTSLSSSTSSSSTLTSSTLTTTTLSSSTL
SLSTTSLSLSLLSSTTLSSSTSTSLSSSTLTTTLTSTSLTLSSSSSTLSSSLTTSLSSTSLLSLTL
LSSSLTLSSLSLTLLSSLLLL
```
[Answer]
# Marbelous, 103 + 92 = 195
**Counter:**
```
@0 @200@1@3
]]&1]]3W
\\!!?001
&0 >W@1
>W @2/\ /\@3+A
00&0 &1
Dp
@0//
```
**Splitter:**
```
@0 @200@1 @3
]]&1]] 3W \\
!! ?001&0
>W@1>W@2
/\ /\@3+A00&0
&1Dp@0
//
```
[Test these programs here.](https://codegolf.stackexchange.com/a/40808/29611) Cylindrical Boards, Include Libraries, and spaces for blank cells must all be checked.
Input and Output are through STDIN/STDOUT.
### Explanation
**Counter:**
![Counter Source](https://i.stack.imgur.com/tXjUa.png)
The blue path receives input. If the character is a whitespace character (ascii value less than 0x21), the black path is taken, which synchronizes with the purple path.
The purple path simply increments a marble stored in the `&1` synchronizer each time the black path is taken.
Once there is no more input, the red path is taken, printing the number of whitespace characters and exiting.
**Splitter:**
![Splitter Source](https://i.stack.imgur.com/uTsFt.png)
The program begins with the blue path, which loops until a non-whitespace character is found.
Once a non-whitespace character is retrieved, the black path is taken, which prints out this character and moves execution to the green path, which loops and prints until a whitespace-character is received. Execution then continues to the purple path, which contains `3W`, or a three-way splitter.
The left branch moves execution to the blue path (and whitespace is discarded until a non-whitespace character is found).
The middle branch sets the copy of the input to 0 with `?0` (generate a random number between `0` and `0`), and adds 10 (`0x0A` = newline), which is then outputted.
The right path is discarded.
[Answer]
# CJam, 26 + 27 = 53 ~~59 61 73 77~~ bytes
**Counter**
```
'!q_,\SN9c++SerS%:Qs,-QN*?
```
**Splitter**
```
' !q_,\SN9c++SerS%:Qs,-QN*?
```
**How it works**
The idea is simple, calculate both number of whitespaces and split the string on consecutive runs of whitespaces. Then choose one of them based on the following fact that `' !` means `not of space character` which is falsy, while `'!` is the `!` character, which is truthy.
Expanded code:
```
'! / ' ! "Get truthy or falsy value";
q_ "Read the input, make a copy";
,\ "Take the length of the copy and swap";
SN9c++ "Get a string comprised of all Whitespaces";
Ser "Replace any occurrence of any character of"
"the above string with space";
S% "Split on one or more runs of space";
:Qs, "Store this in Q, flatten to a string and take length";
- "Subtract from total length to get count";
QN* "Put the splitted array on stack and join newline";
? "Base on the truthy or falsy value, pick one to print";
```
---
Input is from STDIN and output is to STDOUT
[Try it online here](http://cjam.aditsu.net/)
[Answer]
# Mathematica, 44 + 43 = 87 ~~97~~ bytes
I thought I'd add another language to the mix.
Counter:
```
StringCount[#,Whitespace]+0 1StringSpli t@#&
```
Splitter:
```
String Count[#,Whitespace]+01StringSplit@#&
```
This makes use of Mathematica's feature that space separation is the same as multiplication. And that multiplying something with 0 is always 0, and adding 0 to something is always idempotent.
For the counter, we first count the whitespace, and the we add `0*1*StringSpli*t@#`. `StringSpli` and `t` aren't defined, but Mathematica uses symbolic computation, so it just treats those as an unknown variable and function. The `1*` is idempotent (just as `0+`), the `0*` turns it into a zero. It is necessary to separate the `StringSplit` into two variables, because `0` times a list is treated as a scalar-vector multiplication which results in a vector (list) of zeroes.
For the splitter, I'm using the fact that `Count` also exists but doesn't look into strings. It tries to count all sub*expressions* matching the pattern, but `Whitespace` is a pattern that only applies to string contents. So `Count` will always return `0`, which makes the `String` vanish. The multiplication of the split array by `01 = 1` is again idempotent.
[Answer]
# Ruby, ~~107~~ 91 bytes
**Splitter (46 bytes)**
```
p
p=gets(p).split
puts p||$_.size-pp.join.size
```
**Counter (45 bytes)**
```
pp=gets(p).split
puts p||$_.size-pp.join.size
```
`p` is a predefined method that, with no arguments, just returns `nil`. We use this in several ways. In the splitter, the initial `p` does nothing. `gets(p)` reads in everything from standard input, since the delimiter is null. We call the built-in split method on that, and assign the result to `p`, so now when it's not given arguments it'll be parsed as a variable. `puts p||...` short-circuits and prints each element of the `p` variable to its own line.
In the counter, we delete the first newline so that the split array is assigned to `pp` instead. Since we haven't assigned to `p`, it's still the nil-returning method so the second part of the `||` gets evaluated and passed to `puts`. `$_` is a magic variable containing the result of `gets`, so the total amount of whitespace is the size of that minus the non-whitespace characters, which are what `pp` contains. I feel like there should be a shorter way of doing the counting, but I can't find one, and at any rate using the split array in the counter is fun.
[Answer]
# Python, 169
It's almost too easy to do this in Python!
Counter:
```
def x(s):
def y(s):
return sum(map(str.isspace,s))
return s.split()
return y(s)
```
Splitter:
```
def x(s):
def y(s):
return sum(map(str.isspace,s))
return s.split()
return y(s)
```
They differ in only one space, and I'm not doing any trickery like splitting a number or a variable name in half :)
[Answer]
# C, 138+136 = 274
In each case, the code is a program that accepts exactly one command-line argument and prints the result to stdout. `\t` should be replaced with a tab character. If you want to pass an argument containing tabs and newlines, it's your job to figure out how ;).
**Counting**
```
#define strtok strpbrk
h=' \t\n';main(c,v,n)char**v;{for(n=- -c-1;v[n]=strtok(1[v],&h);n[v]++)v[!n]=0,puts(*v),c++;n*='d%';printf(&n,c-2);}
```
**Splitting**
```
#define strtokstrpbrk
h=' \t\n';main(c,v,n)char**v;{for(n=--c-1;v[n]=strtok(1[v],&h);n[v]++)v[!n]=0,puts(*v),c++;n*='d%';printf(&n,c-2);}
```
[Answer]
# JavaScript, 95 + 96 = 191 bytes
Counter:
```
c=(a,v)=>{v
v=a=a.split(RegExp(String.fromCharCode(92,115)));return v?a.length-1:a.filter(j=>j)}
```
Splitter:
```
s=(a,v)=>{vv=a=a.split(RegExp(String.fromCharCode(92,115)));return v?a.length-1:a.filter(j=>!!j)}
```
Ungolfed:
```
s=(a,v)=>{
v // this `v` is ignored, or combined with the next line to make `vv`
// split array and store it in `a` and `v` (or alternatively `vv`)
v = a = a.split(RegExp(String.fromCharCode(92,115)));
return v?
a.length-1 // return number of whitespace chars
:
a.filter(j=>j) // return array without empty strings
}
```
The `RegExp(String.fromCharCode(92,115)` line creates the whitespace-matching regex `/\s/` without regex or string literals.
In each program, we use the variable `v` or `vv`. We store the split array into that variable (`v` or `vv`), and then branch our behavior on the value of `v` (meanwhile, `vv` is ignored). In the counter, `v` has a truthy value; in the splitter it has a falsy value (because `vv` got the value instead).
---
# Alternate: JavaScript, 250 bytes
I have another solution that isn't winning any prizes for brevity, but I thought it was an interesting challenge to abuse JavaScript's automatic semicolon insertion behavior.
Counter:
```
c=a=>{a=a.split(RegExp(String.fromCharCode(92,115)));x:for(i=2;i--;)for(o=i?a.length-1:a.filter(j=>j);1;){break x}return o}
```
Splitter:
```
s=a=>{a=a.split(RegExp(String.fromCharCode(92,115)));x:for(i=2;i--;)for(o=i?a.length-1:a.filter(j=>j);1;){break
x}return o}
```
Ungolfed counter:
```
s=a=>{
a = a.split(
RegExp(String.fromCharCode(92,115)) // split input on whitespace regex /\s/
);
x: // x is a label for the outer loop
for(i=2;i--;) // run this outer loop twice
for(o=i? // if this is the first outer loop pass,
a.length-1 // set `o` to number of whitespaces
: // else, on second outer loop pass,
a.filter(j=>j); // set `o` to split input (w/o empty strings)
1; // 1 is truthy; run inner loop forever
) {
break x; // break out of outer loop
}
return o; // return `o`
}
```
The splitter is exactly the same, except for the line:
```
break x;
```
is now
```
break
x;
```
JavaScript's automatic semicolon insertion normally does not terminate multi-line statements early if they can be understood without a line break, but it does not tolerate line breaks after `return`, `continue` or `break`. Therefore, the line is read simply as `break`, which breaks out of the inner loop only, instead of breaking out of the outer loop. The "second-pass" behavior `o = a.filter(j=>j)` is then executed (versus being skipped in the counter), because the outer loop is given a second pass.
[Answer]
# Python, ~~228~~ ~~198~~ ~~182~~ ~~166~~ ~~146~~ 145 bytes
Counter (**72 bytes**):
```
ior1=0
w=lambda i:i.split()if ior1 else sum(ord(c)in(9,10,32)for c in i)
```
Splitter (**73 bytes**):
```
ior1=0
w=lambda i:i.split()if i or 1else sum(ord(c)in(9,10,32)for c in i)
```
`ior1` is a falsey variable, but `i or 1` is truthy. That's the main trick.
[Answer]
## Befunge 98, 61 + 59 = 120
**Counter:**
```
~:'!-0`#v_ >$1+#@ #. #
@#,#$ #<_v#`0-!':~ # .#
,#$ #+55<v
```
**Splitter:**
```
~:'!-0`#v_ >$1+#@ #.#
@#, #$#<_v#`0-!':~ #.#
, #$#+55<v
```
[Answer]
# Bash, 75 + 79 = 154 bytes
This relies on bash being able to continue execution even if some lines or parts of a line of the script are malformed (in some circumstances). Whitespace is used to deactivate escapes for some close brackets, and to break a pipe by putting it on a new line.
Splitter:
```
echo $((`echo $1|wc -w`+${#1}-$(\)\)\)
for a in $1;do echo $a;done|wc -c)))
```
Counter:
```
echo $((`echo $1|wc -w`+${#1}-$(\ )\ )\ )
for a in $1;do echo $a;done
|wc -c)))
```
Input is via commandline argument, output is via stdout.
Because this relies on bash error behaviour, the user is expected to ignore stderr.
Example run (showing input with a newline and multiple contiguous spaces):
```
# bash counter.sh "abc def
gh ij k" 2>/dev/null
6
# bash splitter.sh "abc def
gh ij k" 2>/dev/null
abc
def
gh
ij
k
```
[Answer]
# Ruby, ~~114 + 116~~ 107 + 109 = 216 bytes
This can't compete with the ruby solution by histocrat, but I thought it would be worth putting up anyway.
I used `$z` for `nil` and `nil.to_s` for `String.new`
The extra whitespace character that I add to the end of the input is to force the last word to be added to the array (`r`) - a word is only added to the end of the array when a whitespace character follows a non-whitespace character. The alternative was adding another `r<<w if w` after the `each_byte` block.
## Counting
```
->s{r=[]
n=-1
w=$z
(s+9.chr).each_byte{|b|if b<33
r<<w if w
w=$z
n+=1
else
w=w.to_s+b.chr
end}
$zorr ?r:n}
```
## Splitting
```
->s{r=[]
n=-1
w=$z
(s+9.chr).each_byte{|b|if b<33
r<<w if w
w=$z
n+=1
else
w=w.to_s+b.chr
end}
$z or r ?r:n}
```
[Answer]
# [Haskell](https://www.haskell.org/), ~~53 + 55 = 108~~ 36 + 38 = 74 bytes
**Counter**
```
f=do
pure(length.filter(<'!'))words
```
**Splitter**
```
f=do
pure(length.filter(<'!'))
words
```
This solution makes use of the fact that in Haskell functions are an instance of the Monad type class and thus can be used as monadic actions in do-notation.
In the first case the resulting function of the do-block is the first argument of `pure` (which is essentially `const` for the function type), making the counter the final result and the splitter being discarded.
In the second case `pure` is only applied to a single argument, making it a function that returns another function (the counter). However, the result is never used and thus discarded. The final result is the second line of the do-block, the splitter.
[Answer]
# Java 8, 187 + 188 = 375
First of all, I'd like to say that this answer is heavily based on @Ypnypn's. I basically replaced some parts with shorter ones (including the whitespace-dependent part, which IMO is the most important in this challenge), but the functional code is mostly the same.
**Count the whitespace**, 187 (returns `int`):
```
Object f(String s){String r=new String(new char[]{92,115});int a=0;return a--+a>0?s.chars().filter(c->c>8&c<11|c==32).count():java.util.Arrays.stream(s.split(r)).filter(t->t.length()>0);}
```
**Split on the whitespace**, 188 (returns `Stream<String>`):
```
Object f(String s){String r=new String(new char[]{92,115});int a=0;return a- -+a>0?s.chars().filter(c->c>8&c<11|c==32).count():java.util.Arrays.stream(s.split(r)).filter(t->t.length()>0);}
```
[Answer]
# J, 48 + 49 = 97 char
Two functions taking and returning a single argument. Used the crappiest way that I could think of to beat the same-but-whitespace rule, so there are probably characters to be saved by finding a more clever route around that.
```
(aa[aa=.+/@a=.a:-.~(e.u:)&9 10 32 :(<;._1~1,}.)) NB. count
(a a[aa=.+/@a=.a:-.~(e.u:)&9 10 32 :(<;._1~1,}.)) NB. split
```
We define the verb `a` to have two different actions, depending on whether it's used with one argument or with two. With one argument, it is `(e.u:)&9 10 32`, which checks if each character is whitespace or not. With two arguments, it is `a:-.~(<;._1~1,}.)`, which takes a boolean vector on the right and cuts the left argument at those positions, throwing out any empty cuts with `a:-.~`.
Then, we define `aa` to be number of True values in the result of `a`, which only makes sense with one argument. Finally, we use `aa` or `a a` depending on whether we want to count or split the whitespace of the string. `aa` works as expected.
The reason `a a` works is because when J sees `(f g)y`, it considers `(f g)` a hook and evaluates it like `y f (g y)`. In this case, `f` is the dyadic `a` above which does the cutting, and `g` is `a[aa`, which calculates the sum from `aa`, throws it out, and calculates (monadic) `a` again.
At the REPL:
```
(aa[aa=.+/@a=.a:-.~e.&(u:9 10 32) :(<;._1~1,}.)) ' 123',TAB,'-_- abc',LF,'def'
7
(a a[aa=.+/@a=.a:-.~e.&(u:9 10 32) :(<;._1~1,}.)) ' 123',TAB,'-_- abc',LF,'def'
+---+---+---+---+
|123|-_-|abc|def|
+---+---+---+---+
```
[Answer]
# Bash, 54 + 50 = 104 bytes
### Counter
```
a=$IFS
IFS=
cat()(tr -cd $a|wc -c)
printf %s \\n$1|cat
```
### Splitter
```
a=$IFSIFS=ca
t()(tr-cd$a|wc-c)
printf %s\\n $1|cat
```
[Answer]
## Perl, 37 + 38 = 75
**Counter**:
```
sub f{($_)=@_;(y/ - //,[split])[0.1]}
```
**Splitter**:
```
sub f{($_)=@_;(y/ - //,[split])[0 .1]}
```
[Answer]
# Perl 6, 31 + 32 = 63 bytes
### Counter
```
{?^1??.words!!+grep 33>*,.ords}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/2j7O0N5erzy/KKVYUVE7vSi1QMHY2E5LRw8kUvu/OLFSIU1DSUHB0MhYQTdeV0FBITEpOSYvJTVNSdP6PwA "Perl 6 – Try It Online")
`?^1` is parsed like `?^ 1` which applies the Boolean negation operator to 1, resulting in `False`.
### Splitter
```
{? ^1??.words!!+grep 33>*,.ords}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/2l4hztDeXq88vyilWFFRO70otUDB2NhOS0cPJFL7vzixUiFNQ0lBwdDIWEE3XldBQSExKTkmLyU1TUnT@j8A "Perl 6 – Try It Online")
`? ^1` converts the range 0..0 to Bool, resulting in `True`.
[Answer]
# Python 2, 98
**Splitting (49)**
Returns the tokens in a list.
```
f=lambda s:[sum(map(str.isspace,s))]and s.split()
```
**Counting (49)**
Returns a list of length one containing the number of space characters. It will most likely cause a runtime error, but the function `f` can be used after executing the code.
```
f=lambda s:[sum(map(str.isspace,s))]
ands.split()
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 88 + 89 = 177 bytes
## Splitter
```
i,n,x,c;f(char*s){x=n=i=0;for(x+++n;c=*s++;c*x&&putchar(c))i=c<33?n++,c=i*10,0:1;x=n-1;}
```
[Splitter](https://tio.run/##FctBCsIwEADAs33F0kNJsgk09uYa/IggcTWaQ1dpKwRK3x71PsPuwVxrtmKLZUqKn3Eys15LkJBDT@k1qYKIQhzMjEhsSte9P8sfKtY6Bz4Ow0kQLYdsfG/7g6dfd562mmWBMWZRulmbXVItgN8P4C4OAOKVz3K7p1ZTs9Uv "C (gcc) – Try It Online")
## Counter
```
i,n,x,c;f(char*s){x=n=i=0;for(x+ ++n;c=*s++;c*x&&putchar(c))i=c<33?n++,c=i*10,0:1;x=n-1;}
```
[Counter](https://tio.run/##FYvLCsIwEADP9iuWgiVPaMzNNfgjBalbozm4lrZCoPTbY73NwAzZJ1EpybDJhjAKevWTmuWaA4cUWoyfSWQNWjNSULPWSCo3zfhd/qUgKVOgi/dX1tpQSMq1pj073H/rcCuJF3j3iYWs1uowTrtHUR@HjmsDOwG4kwd7swDQ36nj4RFrKbHayg8 "C (gcc) – Try It Online")
## Rundown
Takes input as a function argument. The counting function returns the number of whitespace. The splitting function uses STDOUT for its output (but incidentally returns number of whitespace minus one as well).
```
i, Flag signalling whether we are inside a word.
n, Number of whitespace encountered.
x, Flag signalling whether or not we should output the words.
c; Current character.
f(char*s){ Take input string as an argument.
x=n=i=0;for( Initialise everything and start loop.
x+++n; SPLITTER ONLY: Interpreted as x++ +n, meaning x is set to 1 and n stays 0.
x+ ++n; COUNTER ONLY: Inverse of the above. Sets n to 1, and x stays 0.
c=*s++; Sets c to current char and increment string pointer, end loop if end of string.
c*x&&putchar(c)) Only output c if x is 1 and c is non-zero, which only happens if we left a word.
i=c<33? Since input contains only printable ASCII or whitespace, anything below 33 is whitespace.
n++, ...if that is the case, increment the whitespace counter (n)
c=i*10, ...and set c to newline (10), but only if we just left a word (if i is 1)
0: ...and set i to 0.
1; If not a whitespace, set i to 1, signalling we are inside a word.
x=n-1;} Implicitly returns n-1, which is the number of whitespaces if we are in the counter function.
```
[Answer]
# [Zsh](https://www.zsh.org/), 35+35=70 bytes
>
> * Neither program/function may contain any string or regex literals
>
>
>
I am unsure whether `[^$IFS]` qualifies, since it is used in pattern matching. [Here is a 45+45 solution in the case it is banned.](https://tio.run/##qyrO@J@moVn9P9FWQ8XWUJPLisvGxkYlWkXZUFelWlmlWiPLykozsbY2lssKJFGt4Qbk/a/l4kpTUPdIzcnJVyjPL8pJUf8PAA "Zsh – Try It Online")
---
Split:
```
:<<<${#1//[^$IFS]}
:
<<<${(F)${=1}}
```
Count:
```
:
<<<${#1//[^$IFS]}
:<<<${(F)${=1}}
```
The `:` builtin is equivilent to `true`, we use it as something between a comment and /dev/null (since comments are disallowed) by piping the unwanted expansion to it.
Zsh has a builtin for splitting on whitespace, that being `${=var}`. This makes it hard to do any kind of logical combination other than just executing both and discarding the one we don't want.
[Try it online!](https://tio.run/##qyrO@J@moVn934rLxsZGpVrZUF8/Ok7F0y04tpbLCiyk4aapUm1rWFv7v5aLK01B3SM1JydfoTy/KCdF/T8A)
] |
[Question]
[
This challenge is in honor of mathematician [John Conway](https://en.wikipedia.org/wiki/John_Horton_Conway) who [passed away April 11, 2020 due to COVID-19](https://dailyvoice.com/new-jersey/mercer/obituaries/covid-19-kills-renowned-princeton-mathematician-game-of-life-inventor-john-conway-in-3-days/786461/). He was famous for coming up with the [Game of Life](https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life) cellular automaton and [many](https://en.wikipedia.org/wiki/John_Horton_Conway#Major_areas_of_research) [other](https://en.wikipedia.org/wiki/List_of_things_named_after_John_Horton_Conway) mathematical contributions such as the [surreal numbers](https://en.wikipedia.org/wiki/Surreal_number) and the [monster group](https://en.wikipedia.org/wiki/Monster_group).
The advanced math of those topics is out scope for this programming challenge, though I strongly recommend people watch the various [Numberphile videos about Conway](https://www.youtube.com/playlist?list=PLt5AfwLFPxWIL8XA1npoNAHseS-j1y-7V). In [one of those videos](https://youtu.be/xOCe5HUObD4?t=453) Conway says that he'd like to know why the [monster group](https://en.wikipedia.org/wiki/Monster_group) exists before he dies. It's unfortunately too late for that now but we can honor his memory in a very small way by exploring in code the strange number associated with the group.
# Challenge
The [monster group](https://en.wikipedia.org/wiki/Monster_group) is the largest [sporadic simple group](https://en.wikipedia.org/wiki/Sporadic_group) in the branch of [group theory](https://en.wikipedia.org/wiki/Group_theory) in mathematics. But the only thing to know for this challenge is that its [order](https://en.wikipedia.org/wiki/Order_(group_theory)), or number of elements it contains is:
```
808017424794512875886459904961710757005754368000000000
```
Your task is to write a program that outputs this number. *However*, to keep this from being trivial, your program may not contain any digits, 0 through 9. That is, **your program may not contain any of the ten characters `0123456789`**.
Your output must be the precise digits of the number:
```
808017424794512875886459904961710757005754368000000000
```
or the digits with appropriate commas:
```
808,017,424,794,512,875,886,459,904,961,710,757,005,754,368,000,000,000
```
(Commas `,` are allowed in your code.)
Any [usual output method](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods?answertab=votes#tab-top) is valid. No input should be required. **The shortest program in bytes wins.**
If it helps anyone the factorization of the number is:
```
2^46 * 3^20 * 5^9 * 7^6 * 11^2 * 13^3 * 17 * 19 * 23 * 29 * 31 * 41 * 47 * 59 * 71
```
(Factorization is not valid output.)
[Answer]
# [Sledgehammer](https://github.com/tkwa/Sledgehammer), 4 bytes
31 bits, to be overly specific
please upvote the author of this awesome language instead of me
```
⣶⣖⡥⣕
```
(this is a very awesome Mathematica compressor, and it ***really*** excels at compressing code with only a few powerful built-ins)
In this case, the built-ins are `GroupOrder` and `MonsterGroupM`, because of course they exist.
In case this somehow helps, the exact bits contained in the code are `01110111 01110101 10110010 1011010`, the corresponding Mathematica code is `GroupOrder@MonsterGroupM[]`, and the internal suffix code is `call["MonsterGroupM", 0], call["GroupOrder", 1]`, where 0 and 1 are the argument counts.
[Answer]
# [Python 2](https://docs.python.org/2/), 61 bytes
Port of [Neil's answer](https://codegolf.stackexchange.com/a/203529/88546).
*-5 bytes thanks to @Surclose Sputum!*
```
for i in" @@G^dddrstuuuvwxxy{|~~~~~":True*=ord(i)
print True
```
[Try it online!](https://tio.run/##K6gsycjPM/r/Py2/SCFTITNPSUHBwcE9LiUlpai4pLS0tKy8oqKyuqYOBJSsQopKU7Vs84tSNDI1uQqKMvNKFEBC//8DAA "Python 2 – Try It Online")
---
# [Python 3](https://docs.python.org/3/), ~~60~~ 58 bytes
*Thanks to @Surculose Sputum for saving 2 more bytes!*
```
k=True
for i in b"?G^dddrstuuuvwxxy{|~~~~":k*=i+i
print(k)
```
[Try it online!](https://tio.run/##K6gsycjPM/7/P9s2pKg0lSstv0ghUyEzTyFJyd49LiUlpai4pLS0tKy8oqKyuqYOCJSssrVsM7UzuQqKMvNKNLI1//8HAA "Python 3 – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 21 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
⁴Ḥ®x“ÆÑ¥©µ"µ£€× œ‘;Æ¡
```
**[Try it online!](https://tio.run/##ATQAy/9qZWxsef//4oG04bikwq544oCcw4bDkcKlwqnCtSLCtcKj4oKsw5cgxZPigJg7w4bCof// "Jelly – Try It Online")**
### How?
$$|M|=13\times 43!+16\times 42!+4\times 41!+6\times 40!+9\times 39!+34\times 38!+9\times 37!+2\times 36!+12\times 35!+17\times 34!+32\times 33!+30\times 32!$$
So...
```
⁴Ḥ®x“ÆÑ¥©µ"µ£€× œ‘;Æ¡ - Main Link: no arguments
‚Å¥ - literal 16
Ḥ - double = 32
® - recall from register = 0
x - times = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
“ÆÑ¥©µ"µ£€× œ‘ - list of code-page indices = [13,16,4,6,9,34,9,2,12,17,32,30]
; - concatenate = [13,16,4,6,9,34,9,2,12,17,32,30,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
Æ¡ - convert from factorial base to integer
```
---
For what it's worth a naive base-250 compression is 25 bytes AND contains digits: `“Æ4Ḍ⁹|oGO⁷pNJ6þḤ)Ė⁽u2ẏẏż’`
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~32~~ 29 bytes
```
IΠE/Gdddrstuuuvwxxy{|~~~~~⊗℅ι
```
[Try it online!](https://tio.run/##S85ILErOT8z5///9npXnFrzfs1TfPSUlpai4pLS0tKy8oqKyuqYOBB51TX/U0npu5///AA "Charcoal – Try It Online") Explanation: Converts the characters to their ASCII character codes, doubles them, then takes the product. Edit: Saved 3 bytes by porting @SurculoseSputum's golf of @dingledooper's Python 3 answer.
However, Charcoal can just compress the output text... except that compression of the whole text includes an `8`, so you have to print it in two parts:
```
”)¶″³L⬤j$a◧EτB⊟[βω⁵↓≧O””|~ⅉE
```
(Compressing the string in the first program doesn't help as the resulting string contains a digit.)
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvREPJwsDCwNDcxMjE3NLE1NDIwtzUwsLMxNTS0sDE0szQ3NDA3NTcwMDU3NTE2ExJ05oLrg0GgIL////XLcsBAA "Charcoal – Try It Online") Link is to verbose version of code.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~34~~ 32 bytes
*Thanks @my pronoun is monicareinstate for shaving 2 bytes!*
Someone has to do this...
```
Print@GroupOrder@MonsterGroupM[]
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78/z@gKDOvxMG9KL@0wL8oJbXIwTc/r7gktQgs4hsd@/8/AA "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), 67 bytes
```
"nn/HM|Q:iv^YxO[e}%W}}WTBn}}}}}}}}".bytes{|i|$><<(i+?A.ord)%?_.ord}
```
[Try it online!](https://tio.run/##KypNqvz/XykvT9/DtybQKrMsLrLCPzq1VjW8tjY8xCmvFgqU9JIqS1KLq2sya1TsbGw0MrXtHfXyi1I0Ve3jQXTt//8A "Ruby – Try It Online")
By coincidence, the range of digit pairs is 0 to 94, which only just fits in the ASCII range.
`(i+?A.ord)%?_.ord` = `(i+65)%95`. The 65 offset ensures no digit characters in the magic string.
By default numbers are printed without leading zeros, so digit pairs in the range `00..09` require two characters in the magic string. The other digit pairs require one character.
[Answer]
# Java 8, 86 bytes
```
v->"ᾑ䐑Ἂ㉌⊡▒д᭞ᵸ᪑".chars().forEach(c->System.out.print(~-c))
```
[Try it online.](https://tio.run/##y0osS9TNSsn@n5yTWFys4JuYmVfNpaCQmVeSWpSWmJyq4AfiKiiU5WemKCRrhIGoMk1roFgtF5AoLkksyUxW8FPIU7D9X6Zrp/Rw38QnEyY@3NP1uLPnUdfCdysaH02bdGHLw7XzHm7d8XDVREYIUNJLzkgsKtbQ1EvLL3JNTM7QSNa1C64sLknN1csvLdErKAK6QKNON1lT8781yKKC0qQcoEVQ@8CuyQW6VSO4BKgyPTpWIVET4tA8vWSNvNKcHKgba/8DAA)
**Explanation:**
```
v-> // Method with empty unused parameter and no return-type
"ᾑ䐑Ἂ㉌⊡▒д᭞ᵸ᪑".chars().forEach(c->
// Loop over the characters of this string as integer codepoints:
System.out.print(~-c))
// Print this integer - 1 to STDOUT
```
The string contains the characters with the codepoints:
```
8081,17425,7946,12876,8865,59905,9618,1076,7006,7544,6801,1,1,1,1,1,1,1
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 35 bytes
```
'nTIFBCAAAAA@A@A@A@@A'tfYqwIEW-^X$p
```
[Try it online!](https://tio.run/##y00syfn/Xz0vxNPNydkRBBwg0MFRvSQtsrDc0zVcNy5CpeD/fwA "MATL – Try It Online")
### Explanation
This uses the prime factorization of the number:
\$ 808017424794512875886459904961710757005754368000000000 \\ = 2^{46} · 3^{20} · 5^9 · 7^6 · 11^2 · 13^3 · 17 · 19 · 23 · 29 · 31 · 41 · 47 · 59 · 71. \$
```
'nTIFBCAAAAA@A@A@A@@A' % Push this string
t % Duplicate
f % Indices of nonzero chars: gives [1 2 3 ... 19 20]
Yq % n-th prime, element-wise: gives [2 3 5 ... 67 71]
w % Swap
IEW % Push 3, multiply by 2, exponential with base 2: gives 64
- % Subtract, element-wise: subtracts 64 from the code point
% of each character of the string. Gives [46 20 9 ... 0 1]
^ % Element-wise power. Gives [2^46 3^20 5^9 ... 1 71]
X$ % Convert to symbolic (to achieve arbitrary precision)
p % Product. Implicit display
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~37~~ 30 bytes
```
ØẠiⱮ“tTIFBC”;⁽<(B¤
³ÆRṁ¢ż¢*/€P
```
Encodes the number as a list of exponents to primes, probably could be optimized with cleverer builtins
```
ØẠiⱮ“tTIFBC”;⁽<(B¤
“tTIFBC” the string "tTIFBC"
iⱮ find indices of each character in
ØẠ the alphabet in both cases "A..Za..z"
⁽<( ¤ the number 16041
B¤ converted to binary
; append
```
```
³ÆRṁ¢ż¢*/€P
ÆR all primes below
³ 100
ṁ shaped like
¢ the above line
ż zipped with
¢ the above line
*/€ exponent for each pair
P product
```
-7 bytes by encoding the final 0/1 sequence as binary
[Try it online!](https://tio.run/##ATwAw/9qZWxsef//w5jhuqBp4rGu4oCcdFRJRkJD4oCdO@KBvTwoQsKkCsKzw4ZS4bmBwqLFvMKiKi/igqxQ//8 "Jelly – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~29~~ ~~28~~ 27 bytes
-1 byte thanks to @KevinCruijssen
```
•∍ýö/V$Éb´‰ŒrƶÜλFÄôS•¦¾T<׫
```
[Try it online!](https://tio.run/##ATsAxP9vc2FiaWX//@KAouKIjcO9w7YvViTDiWLCtOKAsMWScsa2w5zOu0bDhMO0U@KAosKmwr5UPMOXwqv//w "05AB1E – Try It Online")
---
# [05AB1E](https://github.com/Adriandmen/05AB1E), 21 bytes
Answer suggested by @KevinCruijssen as a port of the Jelly answer by @JonathanAllen
```
₆ÍRžwŸ!•Pǝ½ζÄž,Ā•₆в*O
```
[Try it online!](https://tio.run/##yy9OTMpM/f//UVPb4d6go/vKj@5QfNSwKOD43EN7z2073HJ0n86RBqAAUP7CJi3///8B "05AB1E – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), 91 bytes
```
import Data.Numbers.Primes
product[p^length[';'..c]|(c,p)<-zip"hNC@<=;;;;;:;:;:;::;"primes]
```
[Try it online!](https://tio.run/##NY5Bi8IwGETv/oqPIqioJXWTJrUGBb0IiwgeRaHGYIttEpIUy7L/vVbFN6d5h2HyzN1lWbZtURltPWwyn4W7urpI68K9LSrpeg03Vl9r4Y/mXEp18/lxkA7CUJz@h2JiRovpX2GCfLdeLXj6Yv7JPA3Me@HUVlmh@FX3oKNzykMfmk@r/cHbX9WJYOtAaGul8KDeF5YQwHgMLtcPGDbAOTDEUETxDNMEk2jGKGEsxiRJEE7iiEaIEooQoQT/xAx9GbVP "Haskell – Try It Online") (has an extra 2 bytes for `x=`)
Probably suboptimal but I had a lot of fun writing it. I encode the prime exponents (including zeroes for the primes it doesn't have prior to 71) as a string using the character's relative distance from `:`. the rest is a simple matter of zipping the exponents against an infinite list of all primes, raising those primes to that power, and taking the product.
Edit: forgot to take the `x=` out of the source code on here.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~84~~ \$\cdots\$ ~~81~~ 83 bytes
Saved a byte thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!!!
Added 2 bytes to fix a bug kindly pointed out by [gastropner](https://codegolf.stackexchange.com/users/75886/gastropner).
```
*s;f(){for(s=L"nn/HM|Q:iv^YxO[e}%W}}WTBn}}}}}}}}";*s;)printf("%d",(*s+++'A')%'_');}
```
[Try it online!](https://tio.run/##S9ZNT07@/1@r2DpNQ7M6Lb9Io9jWRykvT9/DtybQKrMsLrLCPzq1VjW8tjY8xCmvFgqUrIE6NAuKMvNK0jSUVFOUdDS0irW1tdUd1TVV1ePVNa1r/wPlFHITM/M0NBWquRSAAGiDNVftfwA "C (gcc) – Try It Online")
Port of [Level River St](https://codegolf.stackexchange.com/users/15599/level-river-st)'s [Ruby answer](https://codegolf.stackexchange.com/a/203533/9481).
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), ~~27~~ 25 bytes
*Thanks to Underslash for -2 bytes because numbers.*
```
»$⇩∪£¼ɾǏ℅yṙ`₆gǏ¦¨λ»kεk×**
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=%C2%BB%24%E2%87%A9%E2%88%AA%C2%A3%C2%BC%C9%BE%C7%8F%E2%84%85y%E1%B9%99%60%E2%82%86g%C7%8F%C2%A6%C2%A8%CE%BB%C2%BBk%CE%B5k%C3%97**&inputs=&header=&footer=)
Unfortunately, the compressed form of the number contains a `2` and a `0`. This is a different number, multiplied by another number multiplied by another number, to get the target number.
```
»$⇩∪£¼ɾǏ℅yṙ`₆gǏ¦¨λ» # Push 11482618231106483731969943632999939453125
kε # Push 32768
k√ó # 2147483648
** # Multiply all the numbers
# Implicit output
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 93 bytes
```
FromDigits[LetterNumber/@Characters@"h h agdbdgideabhgehhfdeii difaga geg egedcfh "]
```
[Try it online!](https://tio.run/##NcgxCkJBDAXAq4R/AU8gLChWIvZikd1kX1KsQn48f7RxylmcpovTBxeOdYn3Ojs898dVMzVun9U1Du1kHDx@sbfNyIghXeCi3A1qNkXdSXwymKAgUqiMafS3Pese/kpqqPoC "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Bash](https://www.gnu.org/software/bash/) + Core utilities, 67 bytes
```
tr o-z /-:<<<xpxpqwtrtwytuqrxwuxxvtuyyptyvqwqpwuwppuwutsvxppppppppp
```
[Try it online!](https://tio.run/##NcGxEYAwDAPAVVggR89lGajokBM5slneVPxf57yrOLanvdvejt57IGDioJJuI@QRi54J5jIZ5AJczrkCv6oP "Bash – Try It Online")
[Answer]
# [Octave](https://www.gnu.org/software/octave/), 50 bytes
```
prod(primes('G').^sym('hNC@<=;;;;;:;:;:;::;'-':'))
```
[Try it online!](https://tio.run/##y08uSSxL/f@/oCg/RaOgKDM3tVhD3V1dUy@uuDJXQz3Dz9nBxtYaBKwg0MpaXVfdSl1T8/9/AA "Octave – Try It Online")
[Answer]
# [brainfuck](https://github.com/TryItOnline/brainfuck), ~~183~~ ~~171~~ 170 bytes
```
++++++++[>+++++++>++++++<<-]>.>.<.>.+.<-.---.>+.<.+++.++.>++.+.
----.+.<-.-.>+++.<+..--.>-.+.<+++..>-----.++++.<.---.>---.<+.>.
-.<.--.++.>..<--.++.--.-.-.+++.++.>.........
```
[Try it online!](https://tio.run/##PY1RCoAwDEMPNJITlF5E/FBBEMEPwfPPtKsWuj7SNFvv5bj2Zzt7b1WTF9Q0w@x0mrrRQAB0EbVUizVCRe1DETUynKmGIBym3I6YeGR0HYWScVRIEiIL/zf8qvcX "brainfuck – Try It Online")
Linebreaks added for readability so not included in the byte count.
[Answer]
# [C++ (gcc)](https://gcc.gnu.org/), ~~82~~, 76 bytes
### *Kudos to @ceilingcat for -6 bytes*
```
void f(){for(auto s:L"ÛÖëëÒß≠öÒΩç´ÛòöªÛúºÅëñ£Ú´Çü∆¥ÛÉîÄ")printf("%i",s);printf("%i%i%i",!f,!f,!f);};
```
[Try it online!](https://tio.run/##Sy4o0E1PTv6vnJmXnFOakmqTXFySkplv978sPzNFIU1Dszotv0gjsbQkX6HYykfpc@vEiR@Xr531cW/v6s8zZu3@PGdP44eJ0xZ/Wt00/9iWz81TGpQ0C4oy80rSNJRUM5V0ijWtEVwQVNJRTIMgTeta6/9AKYXcxMw8kD0aQJH/AA "C++ (gcc) – Try It Online")
# [C++ (gcc)](https://gcc.gnu.org/), 82 bytes
```
void f(){for(auto s:L"ÛÖëëÒß≠öÒΩç´ÛòöªÛúºÅëñ£Ú´Çü∆¥ÛÉîÄ")printf("%i",s);printf("%i%i%i",NULL,NULL,NULL);};
```
[Try it online!](https://tio.run/##Sy4o0E1PTv6vnJmXnFOakmqTXFySkplv978sPzNFIU1Dszotv0gjsbQkX6HYykfpc@vEiR@Xr531cW/v6s8zZu3@PGdP44eJ0xZ/Wt00/9iWz81TGpQ0C4oy80rSNJRUM5V0ijWtEVwQVNLxC/XxQRCa1rXW/4EKFHITM/NAtmkARf4DAA "C++ (gcc) – Try It Online")
My first ever Code Golf submission! :)
Explanation: The loop part of the function prints a decimal representation for each Unicode character in the string. I was really stumped as to how to print zeros without being allowed to have `0` in the code. I just added `NULL` characters cast to `int`.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 14 bytes
```
“ ½‘!PדḥɗeŀƊ’
```
[Try it online!](https://tio.run/##y0rNyan8//9RwxyFQ3sfNcxQDDg8Hch5uGPpyempRxuOdT1qmPn/PwA "Jelly – Try It Online")
Just saw alephalpha's answer before edit and thought "what if I port it to Jelly?" and it worked.
Uses the formula from [this comment](https://codegolf.stackexchange.com/questions/60329/the-mystery-string-printer-robbers/60581#comment145791_60581):
>
> `31!10!27079205916672`
>
>
>
then I noticed that `27079205916672` is a multiple of 32, so I changed the formula to
>
> `32!10!846225184896`
>
>
>
cutting one more byte from the compressed number.
The Jelly code does "`“ ½‘` (32, 10) `!P` factorial each and product `×` times `“ḥɗeŀƊ’` 846225184896".
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~79 78~~ 58 bytes
*Saved 20 (!) bytes thanks to @tsh*
A port of [Neil's approach](https://codegolf.stackexchange.com/a/203529/58563).
```
_=>eval(Buffer("?@^ddrtuuuvwxxy{|~~~~Ȁ掀").join`n*`+'n')
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/e1i61LDFHw6k0LS21SEPJ3iEuJaWopLS0tKy8oqKyuqYOCE40POtrUNLUy8rPzEvI00rQVs9T1/yfnJ9XnJ@TqpeTn66RpqGp@R8A "JavaScript (Node.js) – Try It Online")
---
# [JavaScript (Node.js)](https://nodejs.org), 93 bytes
```
_=>eval('ZxEDCCCCBAECEBBBBn*ZxEAAFEEEFECn*ZxFFCn*ZxFDDAAEn*ZxAZZZZZZZZZZn'.replace(/Z/g,+[]))
```
[Try it online!](https://tio.run/##PYhtCoQgFEWXkzV9rKCBlz4XYUSI84pCVCqi3ZsRzPlz7zmrPvVutiUclfM/ilMbx/ZLp7YsUxcKnugAOXYJV6QEIBFRIn9MyneEAMDngfrjsnqjYLUh1qhmLj/9kOfReLd7S7X1M5tYCjc "JavaScript (Node.js) – Try It Online")
The idea here was to look for factorizations of \$N\$ with factors whose hexadecimal representation only contains letters and \$0\$'s, so that we only need to replace \$0\$'s with a substitute character.
There are countless possibilities. We use this one:
```
0xEDCCCCBAECEBBBB * 0xEAAFEEEFEC * 0xFFC * 0xFDDAAE * 0xA0000000000
```
---
# [JavaScript (Node.js)](https://nodejs.org), 101 bytes
```
_=>eval("FxHOOFdNebfLLMHOGdFMcFGKKffKn*In**HFn<<JLn".replace(/[A-Z]/g,c=>c.charCodeAt()%(~[]+[+[]])))
```
[Try it online!](https://tio.run/##DczBCoMgGADgdwkGWqteoIIYWJs27xMZ7ldrQzQsYqe9euv6Hb6P2tQC8T2vuQ/a7Lben3VjNuVQQr4950TfzcsyNvS802QA0lFqLfXp1adpT3xV3ZhPimhmp8CgUrT5Q5bjGeoGCphUvBxtuyJ8Qj8hM5EJKTHGOwS/BGcKF0Zk0QF/ "JavaScript (Node.js) – Try It Online")
The encoded expression is:
```
0x2990d8ebf667291d07c0155ff5n*3n**20n<<46n
```
[Answer]
# [Java (JDK)](http://jdk.java.net/), 81 bytes
```
v->"XPXPQWTRTWYTUQRXWUXXVTUYYPTYVQWQPWUWPPUWUTSVXPPPPPPPPP".chars().map(n->n-' ')
```
[Try it online!](https://tio.run/##ZY9PT4QwEMXvfIrJXrYYaLyvS@LFxINJWf4UYjxUFthiKaQdMMTsZ8fK6sm5TCbvN/PedGIWYXf@WGU/DgahczOdUCraTLpCOWh6d/D@iRZNLfofqVLCWngRUsOXBzBO70pWYFGga/Mgz9A7jSRopG5f30CY1vobCvD0a/GQOy541phsZyNo4LjOYbQrWMFinp5SXqZZfCp4VhR5mpUlS8s85jHjGWcs41ma5AX7qx2tLsJY4tNejESHkQ73sPfXw2YqNboY9thQMY5qIXpSyqc4PBojFuLfoGSxWPd0mJCOLjgqTXT9CbcviA3uA0tVrVu8@NvG1buu3w "Java (JDK) – Try It Online")
If Java's `int` allowed for (much) more than 32 bits, the following (65 bytes) would have worked:
```
v->",--------<?DGLRT\\^hhhpppptv|".chars().reduce(',',(a,b)->a*b)
```
[Answer]
# [K4](https://kx.com/download/), 64 bytes,
**Solution:**
```
,/$.Q.a?"iaiabhecehjefbcihfiigefjjaejgbhbahfhaafhfedgiaaaaaaaaa"
```
**Explanation:**
Really boring, lookup each letter in the alphabet (e.g. "b" => 1), convert to string and flatten
```
,/$.Q.a?"iaiabhecehjefbcihfiigefjjaejgbhbahfhaafhfedgiaaaaaaaaa" / solution
"iaiabhecehjefbcihfiigefjjaejgbhbahfhaafhfedgiaaaaaaaaa" / a -> 0, b -> 1 etc
.Q.a? / lookup in built-in alphabet a-z
$ / convert to string
,/ / flatten
```
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 42 bytes
```
say [*] ²X*'``}}}~~~~~yuuuwr\t|{^;G'.ords
```
[Try it online!](https://tio.run/##K0gtyjH7/784sVIhWitW4dCmCC31hITa2to6EKgsLS0tL4opqamOs3ZX18svSin@r5xQzWUUZ2SsoAWkTLWQaAUuUy0gBAqg0@ZaxkBoRALL0FDL0BBEgwSMsTPMtcyBdhoBuYaWINuNgFpBmkFiQGgJYxkbgljGWiaGEBETc7BbwfLmhly1/wE "Perl 6 – Try It Online")
Uses the same strategy of reducing the ordinal values of a string by multiplication as other answers, but also multiplies each element by 2 beforehand to save a byte on representing all those powers of two.
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~50~~ 47 bytes
```
p eval (%w(Gv/ R>t. &DhP)*" @QQH}bMA").bytes*?*
```
[Try it online!](https://tio.run/##KypNqvz/v0AhtSwxR0FDtVzDvUxfIciuRE9BzSUjQFNLScEhMNCjNsnXUUlTL6myJLVYy17r/38A "Ruby – Try It Online")
Thanks histocrat for -1 byte, ad Jo King for pointing out some silliness in the original answer.
[Answer]
# [Io](http://iolanguage.org/), 79 bytes
```
"ᾑ䐑Ἂ㉌⊡▒д᭞ᵸ᪑"foreach(i,(-i)bitwiseComplement print)
```
[Try it online!](https://tio.run/##y8z//1/p4b6JTyZMfLin63Fnz6Ouhe9WND6aNunClodr5z3cuuPhqomMEKCUll@UmpicoZGpo6GbqZmUWVKeWZzqnJ9bkJOam5pXolBQlJlXovn/PwA "Io – Try It Online")
[Answer]
# [Red](http://www.red-lang.org), ~~88~~ 78 bytes
```
foreach c"XPXPQWTRTWYTUQRXWUXXVTUYYPTYVQWQPWUWPPUWUTSVXPPPPPPPPP"[prin c - sp]
```
[Try it online!](https://tio.run/##NcExDoAgDADArxB2/9JiS9sQBwMYXZTg/1Mn72Zvnnormx/P7Hs9Q40KCiiUSIwYkwqrZmIzIMsoCMICwMK0ZoVfLGNed6hhCe/Y3D8 "Red – Try It Online")
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 41 bytes
```
*F^MC,fP_TSC\G+C\.xLG"ujgcdbbbbbabababaab
```
[Try it online!](https://tio.run/##K6gsyfj/X8stztdZJy0gPiTYOcZd2zlGr8LHXak0Kz05JQkEEiEwMen/fwA "Pyth – Try It Online")
```
*F^MC,fP_TSC\G+C\.xLG"ujgcdbbbbbabababaab Implicit: G=lower case alphabet
L "ujgcdbbbbbabababaab For each character in the string...
x G ... find it's index in the alphabet
+C\. Prepend 46 (character code of .) - these are the prime powers
C\G 71
S Range 1-71
fP_T Filter keep the primes in the above
, Pair the primes with the prime powers
C Transpose
^M Map exponent operator over each pair
*F Take product of the result, implicit print
```
[Answer]
# [Deadfish~](https://github.com/TryItOnline/deadfish-), 164 bytes
```
iiisdo{d}oiiisdo{d}oioisiiiodddoddosoiiioiiodddddoioddddoioisdododdoiiiooddoddoioddsoo{d}oiisodsodddo{d}ioisiiio{d}iodoiisiiioddoiio{d}ooiisioiioddododoiiioii{o{d}}
```
[Try it online!](https://tio.run/##TU0xDsBACHpRH9WENnVicLzc262oTToYQRBwnbjNnyPCzBxc2PwhmicjgBy6JDZP2rtMKcsgme2V6Jw8Z2J5k36ZBfUyDewb69IlCp3KJW1HvA "Deadfish~ – Try It Online")
[Answer]
## C (gcc), 77 bytes
```
*s;f(){for(s=L"pp!'JO~S<kx`[zQ]g kf YVDp ";*s;)printf("%d",*s++-' ');}
```
Assumes that `wchar_t` and `int` have the same size. This way we can make the string wide and we can omit the type when declaring `s`.
A naive approach: group the digits in blocks of 1–3, each of which is an integer between 0 and 127 with no leading 0. Since character 0 can't be present in the string, characters are encoded as their value plus some constant. The constant is 32, which has the advantage of keeping all characters printable.
### C (gcc), 78 bytes
Bonus: without relying on `wchar_t` and `int` having the same size. We save 1 byte (the `L`) by not having a wide string, but lose 1 byte because the implicit-int declaration `*s` is replaced by the explicit type name `char`.
```
f(){for(char*s="pp!'JO~S<kx`[zQ]g kf YVDp ";*s;)printf("%d",*s++-' ');}
```
[Try it online!](https://tio.run/##S9ZNT07@/z9NQ7M6Lb9IIzkjsUir2FapoEBR3cu/LtgmuyIhuiowNl0hO00hMsylQAEKlKy1iq01C4oy80rSNJRUU5R0tIq1tXXVFdQ1rWv/A0UVchMz80CmaoAEAA "C (gcc) – Try It Online")
[Answer]
# [><>](http://esolangs.org/wiki/Fish), 36 bytes
`|.ab*n!?+il"ØØØØØØÕìëöøèúúæò÷õîÐÐÄp"`
[Try it online!](https://tio.run/##S8sszvj/v0YvMUkrT9FeOzNH6fAMJDj18JrDqw9vO7zj8IrDu4Bw2eFNh7cf3np43eEJQNhSoPT/PwA)
It's based on a hand-optimized list of partial products of the prime factors of the number, each fitting within a byte.
] |
[Question]
[
[Winter Bash 2014](http://winterbash2014.stackexchange.com/) is on its prime and don't we all love the hats? Especially the secret hats!
So why not draw one of secret hats?
## The challenge
Your task is to draw the Warm Welcome Hat in proportion, in a language of your choice and having an exact construction as appearing on [this page](https://web.archive.org/web/20150827162023/http://cdn-prom.sstatic.net/WinterBash/img/hat/87464929.svg?v=258991c72f90).
[As always](https://codegolf.stackexchange.com/questions/40052/draw-the-south-korean-flag/), you can render the hat to a file or screen using vector or raster graphics. If your output is rasterised, your image must have dimensions of 400x400 pixels or more.
Moreover, the actual contents of the hat (the area of the bounding rectangle of the colored parts of the image) should cover more than 40% of your output image.
## Specifications
The image below lists out various dimensions of the hat. All dimensions are in the unit, for example, pixels. All border radius in the image are to be drawn with a radius of `13` units.
![enter image description here](https://i.stack.imgur.com/5qddO.jpg)
**Colors**:
* Red in the star and circular ring - rgb(255, 28, 34)
* Yellow in the circle - rgb(255, 202, 87)
* Lightest grey - rgb(88, 88, 92)
* Darkest grey - rgb(31, 26, 26)
* Middle grey - rgb(64, 64, 64)
## Scoring
This is code golf, so the shortest answer (in bytes) wins.
As a word of warning, using existing compression (like embedding a compressed GIF) falls into [several standard loopholes](http://meta.codegolf.stackexchange.com/q/1061/8478).
[Answer]
## SVG (462 460 454 429 384 365 bytes)
I know it isn't a programming language, but I thought this will at least be useful to anyone generating SVG output...
This is based on Peter Taylor's SVG.
By using the original coords, and optimizing the paths a little, I managed to shrink the SVG down. I also fixed the colours.
```
<svg><g stroke-linecap=round stroke-linejoin=round stroke-width=26><path d=M54,13,13,36V75H151V36L110,13 stroke=#1f1a1a /><path d=M21,84V36H37A91,91,0,0,1,127,36h16V84z stroke=#404040 /><path d=M30,36v48h104V36z stroke=#58585c fill=#58585c /></g><circle cx=82 cy=60 r=23 fill=#ffca57 stroke=#ff1c22 stroke-width=5 /><path d=M82,43,92,74,66,55H98L72,74z fill=#ff1c22
```
**Update:** Fixed flaw pointed out by [Peter Taylor](https://codegolf.stackexchange.com/users/194/peter-taylor) and position of rects and saved 2 more bytes.
**Update 2:** Incorporated another fix and suggestions from Peter (-6 bytes)
**Update 3:** Just noticed the instructions now specify all radii are 13, so taking advantage of that, and optimizing the paths a bit more, I saved another 25 bytes. [More readable fiddle here.](http://jsfiddle.net/gfndy53g/1/)
**Update 4:** Since I am already assuming the SVG is embedded in HTML (standalone SVGs need the namespace declaration), I can actually squeeze this more. (a) I don't need the width and height attributes because the size of the SVG is smaller than the default size browsers give to objects whose size is indeteminate (300x150), and (b) the HTML parser is forgiving about attributes which don't have quotes, so some of them can be removed (idea from [Squeamish Ossifrage](https://stackoverflow.com/users/1679849/squeamish-ossifrage)). Saves another 45 bytes.
**Update 5:** Using [hsl](https://codegolf.stackexchange.com/users/29750/hsl)'s tricks for de-quoting the colours and dropping the trailing end tags. We saved another 19 bytes. The latter seemed a bit cheaty to me at first, but since it works in all browsers, I changed my mind. :) Thanks hsl!
[Answer]
# Mathematica ~~787 612 600 514~~ 506 bytes
Surprising amount of code needed. Will surely be beaten.
**Ungolfed form**
```
red=RGBColor[1.,.11,.13]
yellow=RGBColor[1.,.79,.34]
lightGrey=RGBColor[.35,.35,.36]
midGrey=RGBColor[.25,.25,.25]
r=RoundingRadius->8;
pentagonalVertices[offset_]:=Table[{Cos[2π k/5+ offset],Sin[2π k/5+offset]},{k,0,5}];
x=63;x2=72;
y=37;
pts={{e=22,50},{h=72,30},{h,-17},{-h,-15},{-h,30},{-e,50}};
pts2={{-h,-15},{-h,30},{-e,50}}
Graphics[{
{Black,Thickness[.13],JoinForm["Round"],CapForm["Round"], Line[pts]},
midGrey,Rectangle[{-x2,-y},{x2,y},r],
Disk[{0,-55},104,{Pi/3,2Pi/3}],
White,Rectangle[{-40,-60},{40,0},r],
lightGrey,Rectangle[{-x,-y},{x,y},r],
red,Disk[{0,0},25],yellow,Disk[{0,0},19.5],red,
GraphicsComplex[16.7 pentagonalVertices[Pi/2],Polygon[{1,3,5,2,4}]],
GraphicsComplex[6.4 pentagonalVertices[3 Pi/2],Polygon[{1,2,3,4,5}]]}]
```
![hat](https://i.stack.imgur.com/UyFzU.png)
## Golfed
```
g=GraphicsComplex;c=RGBColor;d=c[1.,.11,.13];o="Round";k=Rectangle;j=Disk;n=Polygon;r=RoundingRadius->8;w@s_:=Table[{Cos[2\[Pi]k/5+s],Sin[2\[Pi]k/5+s]},{k,0,5}];x=63;i=72;y=37;p={{e=22,50},{h=72,30},{h,-17},{-h,-15},{-h,30},{-e,50}};Graphics[{Thickness[.13],JoinForm@o,CapForm@o,Line@p,c[.25,.25,.25],k[{-i,-y},{i,y},r],j[{0,-55},104,{\[Pi]/3,2\[Pi]/3}],White,k[{-40,-60},{40,0},r],c[.35,.35,.36],k[{-x,-y},{x,y},r],d,j[{0,0},25],c[1.,.79,.34],j[{0,0},19.5],d,g[16.7w[\[Pi]/2],n[{1,3,5,2,4}]],g[6.4w[3\[Pi]/2],n[{1,2,3,4,5}]]}]
```
[Answer]
## HTML + ES6, 533
```
<canvas id=D width=600 height=400><script>c=D.getContext('2d')
S=x=>c.strokeStyle=F(x)
F=x=>c.fillStyle=x
W=x=>c.lineWidth=x
B=x=>c.stroke()||c.fill()||c.beginPath()
G='s.charCodeAt(i++)*9-300,'
L=s=>B()||eval('for(i in s)i%2||c.lineTo('+G+G+'0)')&&B()
c.lineCap=c.lineJoin='round'
W(60)
S('#1F1A1A')
L(';,+3+BXBX3H,')
S('#404040')
L('.3.EUEU3.3')
c.arc(291,390,270,4,5.2,0)
B()
S('#58585C')
L('131ERER313')
S(R='#FF1C22')
F('#FFCA57')
W(30)
c.arc(291,240,69,0,7,0)
B()
c.font='105px serif'
S(R)
c.fillText('\u2605',239,276)</script>
```
Snippet (modified):
```
<canvas style="margin:-40px 0 0 100px;height:250px;" id=D width=600 height=400><script>stages=[function(){c=D.getContext('2d');S=function(x){return c.strokeStyle=F(x)};F=function(x){return c.fillStyle=x};W=function(x){return c.lineWidth=x};B=function(x){return c.stroke()||c.fill()||c.beginPath()};G='s.charCodeAt(i++)*9-300,';L=function(s){return B()||eval('for(i in s)i%2||c.lineTo('+G+G+'0)')&&B()}},function(){c.lineCap=c.lineJoin='round';W(60);S('#1F1A1A');L(';,+3+BXBX3H,')},function(){S('#404040');L('.3.EUEU3.3')},function(){c.arc(291,390,270,4,5.2,0);B()},function(){S('#58585C');L('131ERER313')},function(){S(R='#FF1C22');F('#FFCA57');W(30);c.arc(291,240,69,0,7,0);B()},function(){c.font='105px serif';S(R);c.fillText('\u2605',239,276)}];next=function(i){stages[i]();if(i<6)setTimeout(next,1000,i+1)};next(0)</script>
```
![hat!](https://i.stack.imgur.com/R9paD.png)
[Answer]
## GolfScript (376 373 364 350 *or 645 610 607* bytes)
Following the *original* specification, which called for the exact construction of the SVG, a golfed SVG is generated in 607 bytes.
Code contains lots of non-printing characters, so here's the xxd output:
```
0000000: 221a c837 cde6 0c0c 4658 5786 cead ca66 "..7....FXW....f
0000010: 3507 d130 1577 4657 4067 df6b 97e7 510f [[email protected]](/cdn-cgi/l/email-protection).
0000020: cbb0 e3e5 77c6 a91d d830 fa92 eea0 d447 ....w....0.....G
0000030: 7721 cc59 3f4c 230b e0bb fd3e ecf3 d4f7 w!.Y?L#....>....
0000040: 2c6b abd5 b1e5 939d 68b4 e89e 39ca a259 ,k......h...9..Y
0000050: b934 ef6f 203a 7abf 1a2c b468 3351 4c53 .4.o :z..,.h3QLS
0000060: c056 9a59 f38c a97e cf82 8840 ee7c 43e4 .V.Y...~...@.|C.
0000070: 123f df1a 00d4 542d a29c 0195 3ad5 4af4 .?....T-....:.J.
0000080: c644 57c7 0b6b 4d4f 908b 8cf7 c8e2 536d .DW..kMO......Sm
0000090: 9d36 1139 1406 5c5c dcbc 3a11 1993 63a6 .6.9..\\..:...c.
00000a0: 4f8b 7b62 de77 5158 a485 dec1 87b4 1d11 O.{b.wQX........
00000b0: 01b1 e49d 8adb 0b29 ad44 93e4 7bbd 027e .......).D..{..~
00000c0: 7a6f 60ca 99f4 6ab3 7bc0 63c3 ba70 1220 zo`...j.{.c..p.
00000d0: 1aea 9206 da5a 95ce 6f70 67f8 856e 8807 .....Z..opg..n..
00000e0: adec e533 0c1e 3dc6 96e5 54d4 2837 4497 ...3..=...T.(7D.
00000f0: f5ea 2135 d261 9c02 fa61 c12a 7180 085a ..!5.a...a.*q..Z
0000100: a5b8 e3d6 68cb 0659 f4ad d01d 5fc4 9e5b ....h..Y...._..[
0000110: d030 46d5 96c4 439f da99 2cb1 52b9 5d53 .0F...C...,.R.]S
0000120: 098e 7598 2785 a962 a40d edbd 18cb e46c ..u.'..b.......l
0000130: 6edb ba9f 17be 36ab ef23 0caf 3ce8 352d n.....6..#..<.5-
0000140: fad5 762b a388 ca17 413f 7dac 6dd1 116e ..v+....A?}.m..n
0000150: b2e8 9cd1 d00a dda1 716d a148 acc7 8749 ........qm.H...I
0000160: f2c3 a7a9 8128 02e9 d83c f350 7a02 74ec .....(...<.Pz.t.
0000170: 6270 6089 a16d 7bfa b6dd e56a 366a d85b bp`..m{....j6j.[
0000180: 33e5 b777 05c1 6f4e f06b ca95 3ffc 49f7 3..w..oN.k..?.I.
0000190: 1a08 6bc5 abb0 c745 e439 b87e b81c 52c8 ..k....E.9.~..R.
00001a0: a445 935e 5c5c 00d3 34de c002 721c b69d .E.^\\..4...r...
00001b0: 16ee aab0 9562 4d44 44ed 0193 13a7 eed2 .....bMDD.......
00001c0: 99e4 6350 a756 c21a 980b 6bca 57f9 8443 ..cP.V....k.W..C
00001d0: eecc 9fd1 05ce 78c4 f95f dc90 8926 6eb4 ......x.._...&n.
00001e0: 88b8 7b90 44be 33c3 cc2a b032 d809 17d0 ..{.D.3..*.2....
00001f0: 7e32 c4c9 e37f ceb3 b1e0 b634 a690 8163 ~2.........4...c
0000200: cd34 e3d9 9768 3e13 ac10 5003 1cb7 af6b .4...h>...P....k
0000210: 863f cba0 9896 e50a d029 8e2b 584c d86f .?.......).+XL.o
0000220: 67a7 120e 318a cb22 3235 3662 6173 6520 g...1.."256base
0000230: 3132 3462 6173 655b 305d 2f28 3332 2c7b 124base[0]/(32,{
0000240: 5c5b 3124 295d 2f5c 3224 3d2a 7d2f 5c2c \[1$)]/\2$=*}/\,
0000250: 297b 2d2e 3634 3e33 322a 2b7d 2b25 2b ){-.64>32*+}+%+
```
It's a variant on the constructive grammar engine which followers of [kolmogorov-complexity](/questions/tagged/kolmogorov-complexity "show questions tagged 'kolmogorov-complexity'") will be familiar with:
```
'MAGIC STRING'256base 124base[0]/(40,{\[1$)]/\2$=*}/\,){-.64>32*+}+%+
```
It turned out to be slightly better to upper-case the golfed SVG, compress that, and then lower-case after decompression.
When run it produces an 840-byte SVG:
```
<svg width="192" height="192"><g transform="translate(-19.356 39.823) scale(.11435537421402706)"><path d="m873 126c-28-56-97-79-153-50l-361 182c-40 20-63 60-62 102v369c0 63 51 114 114 114h1198c63 0 114-51 114-114v-369c1-62-22-82-62-102l-361-182c-56-29-125-6-153 50c-28 56-6 124 49 152h-372c55-28 77-96 49-152z" fill="#231f20"/><path d="m1642 812c0 60-49 109-109 109h-1047c-60 0-109-49-109-109v-435c0-60 49-109 109-109h96.557636322653a530 274 0 0 1 854.884727354693 0h96.557636322653c60 0 109 49 109 109v435z" fill="#424143"/><path d="m1561 826c0 52-42 95-95 95h-912c-52 0-95-42-95-95v-463c0-52 42-95 95-95h912c52 0 95 42 95 95v463z" fill="#595a5c"/><circle cy="594" cx="1010" r="199" fill="#f9c960" stroke="#ec2227" stroke-width="42"/><path d="m1063 615l85-62-105 0-33-100-33 100-105 0 85 62-32 100 85-62 85 62z" fill="#ec2227"/></g></svg>
```
I've tweaked the position by a few millipixels and corrected one small asymmetry in the darkest grey part.
---
But the changes to the question and discussion in chat indicate that it's actually permissible to create a good approximation to the SVG, which can be done in 364 bytes. The decompression chain is similar, so the xxd output of the GolfScript file is:
```
0000000: 2710 9f1d b7bb 6ca9 ad60 1325 b869 45a6 '.....l..`.%.iE.
0000010: 9371 2eee 1271 1dac 0244 9ca3 2820 e6be .q...q...D..( ..
0000020: b038 68e4 4e53 bbe9 7809 a67a 5f02 2f14 .8h.NS..x..z_./.
0000030: 66a1 0cb3 648c 76d4 0450 028d fd32 b81f f...d.v..P...2..
0000040: 351a d449 bba8 e685 4de8 1fc0 abfd 8b9f 5..I....M.......
0000050: d9d9 33cd 16e9 5c27 b7a0 dc0f 4138 a2ca ..3...\'....A8..
0000060: 2b45 a2c2 571e 7e1e 1030 dcfd b48e 377b +E..W.~..0....7{
0000070: 112e 7762 d14c 1fed 0bcb 15b4 c383 f828 ..wb.L.........(
0000080: b317 8c9f 890b ce84 7782 4c10 fc8e 7602 ........w.L...v.
0000090: 9fef 9563 fe30 45b0 7144 30b3 f3c5 fa22 ...c.0E.qD0...."
00000a0: ccae 8a08 c506 466b 6b84 317e 62dd a558 ......Fkk.1~b..X
00000b0: 8423 d8ef 9d67 e807 0d23 847d 4dab 68ff .#...g...#.}M.h.
00000c0: 952b ca20 14d3 0881 2880 6611 eb53 10c6 .+. ....(.f..S..
00000d0: 0058 573f 3c87 957c 8512 59ff 94f3 ae38 .XW?<..|..Y....8
00000e0: 4145 bf8d 4123 6e84 aa62 904d a878 0bca AE..A#n..b.M.x..
00000f0: 854b deaa 32ae 70fc b31a 9578 676a df8a .K..2.p....xgj..
0000100: 7310 ecfc 47d2 5dde 1a8c 3898 943b ede3 s...G.]...8..;..
0000110: d0a2 55a4 eb00 b623 0302 d79c a712 b616 ..U....#........
0000120: 5037 dc2d 0dad 2732 3536 6261 7365 2031 P7.-..'256base 1
0000130: 3133 6261 7365 5b30 5d2f 2832 312c 7b5c 13base[0]/(21,{\
0000140: 5b31 2429 5d2f 5c32 243d 2a7d 2f5c 2c29 [1$)]/\2$=*}/\,)
0000150: 7b2d 2e36 343e 3332 2a2b 7d2b 252b {-.64>32*+}+%+
```
and generates a 547-byte SVG file:
```
<svg width="1426" height="858"><path d="m475 114-361.5 182v370h1199v-370l-361.5-182" stroke="#231f20" stroke-linecap="round" stroke-linejoin="round" stroke-width="227"/><ellipse cx="713" cy="367" rx="530" ry="274" fill="#424143"/><rect x="80" y="205" width="1266" height="653" rx="109" ry="109" fill="#424143"/><rect x="161" y="205" width="1103" height="653" rx="95" ry="95" fill="#595a5c"/><circle cx="713" cy="531" r="199" fill="#f9c960" stroke="#ec2227" stroke-width="42"/><path d="m713 390 85 262-223-162 276 0-223 162z" fill="#ec2227"/></svg>
```
Thanks to [Paul LeBeau](https://codegolf.stackexchange.com/users/34364/paul-lebeau) for pointing out a 7-byte saving in the SVG which translated to 9 bytes in the GolfScript, and for his answer which demonstrated that the star can be drawn with just the 5 points. (Using his answer I could get down to 329 bytes, or 323 with some tweaking to his answer, but I'm not comfortable with that).
Exported at 50% with Inkscape:
![Hat image rendered as PNG](https://i.stack.imgur.com/xjlJa.png)
To see the structure, here's the SVG rendered with `fill="none"` on everything and some fill colours changed to stroke colours:
![Outline image](https://i.stack.imgur.com/q7FXd.png)
[Answer]
# HTML + CSS, ~~676 636~~ 625 bytes
~~This can be golfed a lot, by getting rid of those `left:XXXpx` and using some sort of centering~~ Now using transforms to center everything instead of `left:XXXpx`.
```
*{left:50%;transform:translate(-50%);position:absolute;border-radius:13px;height:75px}a,b,f{width:145px;background:#404040}b{width:126px;background:#58585C}c{width:163px;height:61px;top:50px}d,e{width:68px;height:40px;top:-15px}c,d,e{background:#1F1A1A}d{left:0;transform:skew(0deg,-26deg);border-radius:9px 24px}e{left:96px;transform:skew(0deg,26deg);border-radius:24px 9px}f{height:40px;width:99px;top:-13px;border-radius:150px/60px}g{height:34px;width:34px;background:#FFCA57;border:5px solid #FF1C22;border-radius:40px;top:13px;color:#FF1C22;font-size:1cm;line-height:31px;padding:3px}
```
```
<c><d></d><e></e><f></f><a><b><g>★
```
*Note: This works best/as expected in Firefox on Windows*
End result looks like:
![enter image description here](https://i.stack.imgur.com/i1ZwY.jpg)
[Answer]
# ActionScript 3.0, 491 bytes
Golfed form:
```
var h=new Shape(),g=h.graphics,l=g.lineTo,m=g.moveTo,s=g.lineStyle,b=g.beginFill,e=g.endFill,r=g.drawRoundRect;s(23,0x231F20);m(77,18);l(41,36);l(41,73);m(125,18);l(161,36);l(161,73);s();b(0x424143);g.drawEllipse(48,16,106,55);e();b(0x424143);r(38,27,126,65,23,23);e();b(0x595A5C);r(46,27,110,65,17,17);e();s(4.2,0xEC2227);b(0xF9C960);g.drawCircle(101,59,20);e();s();b(0xEC2227);m(106,61);l(115,55);l(104,55);l(101,45);l(98,55);l(87,55);l(96,61);l(93,71);l(101,65);l(110,71);e();addChild(h);
```
Output: <http://megaswf.com/file/2708781.swf>
[Answer]
# MATLAB R2013a, ~~551~~ 541
This is my first Code Golf. So if anything is not according to the rules, **please teach/tell me** :)
**Golfed form:**
```
hold on
r=[1 .11 .13];h=[];b=2.4;q=-37;o='Curvature';p='Position'
x='FaceColor';z='EdgeColor';v=@rectangle;t=@repmat;s=@set
for i=1:19;h=[h v(p,[-82+b*i -32+i 22 73]) v(p,[60-b*i -32+i 22 73])];end
s(h,o,1,x,[.12 .1 .1])
c=.8:.01:2.2
h=[h fill(104*cos(c),104*sin(c)-52,t(.25,1,3))]
h=[h v(p,[-72 q 144 74],o,.1,x,t(.25,1,3))]
a=v(p,[-63 q 126 74])
a=[a v(p,[-63 q 126 74])]
s(a,o,.1,x,[t(.35,1,2) .36])
v(p,[-20 -20 40 40],o,1,x,[1 .79 .34],z,r,'LineWidth',10)
plot(0,0,'rp',['Marker' x],r,'MarkerSize',58.5)
s([a h],z,'none')
axis equal off
```
**Output** (rasterized):
![enter image description here](https://i.stack.imgur.com/vJXlo.jpg)
[Answer]
# LaTeX/TikZ (613 bytes)
```
\RequirePackage{xcolor,tikz}\RequirePackage[active,tightpage]{preview}\PreviewMacro[[!]\tikz\def~#1{\definecolor#1{HTML}}~1{EC2227}~2{F9C960}~3{595A5C}~4{231F20}~5{424143}\def\r{rounded
corners}\def\R{radius}\tikz[x=1pt,y=1pt]{\def~{\fill[}\draw[4,line
width=22.8,line
cap=round,line
join=round](-23.8,41.7)--(-59.9,23.5)--(-59.9,-13.3)--(59.9,-13.3)--(59.9,23.5)--(23.8,41.7);~5,x
\R=53,y
\R=27.4](0,16.4)circle;~5,\r=10.9](-63,-32.65)rectangle(63,32.65);~3,\r=9.5](-55.1,-32.65)rectangle(55.1,32.65);~1,\R=22](0,0)circle;~2,\R=17.8](0,0)circle;~1](90:14.1)\foreach\!in{0,...,4}{--(90+\!*144:14.1)}--cycle;}\stop
```
The result of `pdflatex` is a PDF file with the hat as vector graphics and a tight bounding box.
>
> ![Result](https://i.stack.imgur.com/nGMbo.png)
>
>
>
## Ungolfed
```
\documentclass{minimal}
% Package xcolor provides color model HTML
% in order to take the exact same values, used in the SVG file
\usepackage{xcolor}
\usepackage{tikz}
% Package preview is used to get a correct bounding
% box for the graphics
\usepackage[active,tightpage]{preview}
\PreviewEnvironment[{[]}]{tikzpicture}
% Color definitions. one digit instead of a name saves many bytes
\definecolor1{HTML}{EC2227}
\definecolor2{HTML}{F9C960}
\definecolor3{HTML}{595A5C}
\definecolor4{HTML}{231F20}
\definecolor5{HTML}{424143}
\begin{document}
\begin{tikzpicture}[x=1pt,y=1pt]
% Draws the dark lines in the background
\draw[4,line width=22.8,line cap=round,line join=round]
(-23.8,41.7)--(-59.9,23.5)--(-59.9,-13.3)
--(59.9,-13.3)--(59.9,23.5)--(23.8,41.7);
% Draws the ellipsis
\fill[5,x radius=53,y radius=27.4](0,16.4)circle;
% Draw the rear rectangle
\fill[5,rounded corners=10.9](-63,-32.65)rectangle(63,32.65);
% Draws the rectangle in the foreground
\fill[3,rounded corners=9.5](-55.1,-32.65)rectangle(55.1,32.65);
% Draws the red full circle
\fill[1,radius=22](0,0)circle;
% Draws the inner yellow circle
\fill[2,radius=17.8](0,0)circle;
% Draw the star
\fill[1](90:14.1)\foreach\!in{0,...,4}{--(90+\!*144:14.1)}--cycle;
\end{tikzpicture}%
\end{document}
```
The values are taken from the SVG file, they were more accurate (but it also
contains rounding errors). The trickiest part was the dark slanted lines in the background. They are drawn as very thick line with rounded line caps and joins.
>
> ![Animation](https://i.stack.imgur.com/JcSGU.gif)
>
>
>
[Answer]
# Perl + TK: 555
The new lines are only for readability, although I got lost of so many variables.
```
use Tk;@w=(-width=>13);$c=tkinit->Canvas->pack;
$c->createPolygon($a=131,$b=163,168,150,$a,$b,$e=269,$b,232,150,$e,$b,$e,$d=225,$a,$d,-outline=>"#1f1a1a",@w);
$c->createPolygon(137,$f=169,263,$f,263,$g=231,137,$g,-outline=>$h="#".40x3,@w);
$c->createOval($a,147,$e,$g,-fill=>$h,-outline=>$h);
$c->createPolygon(143,$f,257,$f,257,$g,143,$g,-fill=>$l="#58585c",-outline=>$l,@w);
$c->createOval(175,175,$d,$d,-width=>5,-fill=>"#ffca57",-outline=>$r="#ff1c22");
$c->createPolygon((map{200+($_%2?17:6)*sin.628*$_,200+($_%2?17:6)*cos.628*$_}0..11),-fill=>$r);
MainLoop
```
Here's a picture:
![enter image description here](https://i.stack.imgur.com/gB772.png)
I don't think it's near pixel perfect, but it's close enough :)
] |
[Question]
[
### Challenge:
Given a string `s` on the characters `a`-`z`, `A`-`Z`, `0`-`9`, append the length of `s` to itself, counting the additional character(s) in the length as part of the total length of `s`.
### Input:
Just a string of arbitrary length (can be empty).
### Output:
The same string, but with its length appended to the end. The characters that represent the length should also be counted as part of the length. In cases where there are multiple valid lengths to append, choose the smallest one possible (see test cases for examples).
### Test Cases:
```
INPUT -> OUTPUT // Comment
aaa -> aaa4
-> 1 // Empty string
aaaaaaaa -> aaaaaaaa9 // aaaaaaaa10 would also normally be valid, but violates using the smallest number rule mentioned above
aaaaaaaaa -> aaaaaaaaa11
a1 -> a13 // Input can contain numbers at the end of the string, you do not have to handle the fact that it looks like 13 rather than 3.
Longer test case(s):
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -> aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa101
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -> aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa102
```
### Rules:
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in bytes wins. Standard loopholes are forbidden. Submissions may be an entire program or a function, and you may either print the result to stdout or return it as a variable from a function.
[Answer]
## JavaScript (ES6), 32 bytes
```
f=(s,n=0)=>(s+n)[n]?f(s,n+1):s+n
```
### How it works
```
f = (s, n = 0) => // given a string 's' and starting with n = 0:
(s + n)[n] ? // if the Nth character of (s + n) exists:
f(s, n + 1) // try again with n + 1
: // else
s + n // return s + n
```
Starting with `N=0`, we test the Nth character (0-based) of the string made of the concatenation of the original input string and the decimal representation of `N`. We increment `N` until this character doesn't exist anymore.
Example:
```
N = 0 : abcdefghi0
^
N = 1 : abcdefghi1
^
N = 2 : abcdefghi2
^
...
N = 8 : abcdefghi8
^
N = 9 : abcdefghi9
^
N = 10 : abcdefghi10
^
N = 11 : abcdefghi11 -> success
^
```
### Test cases
```
f=(s,n=0)=>(s+n)[n]?f(s,n+1):s+n
console.log(f("aaa")); // -> aaa4
console.log(f("")); // -> 1
console.log(f("aaaaaaaa")); // -> aaaaaaaa9
console.log(f("aaaaaaaaa")); // -> aaaaaaaaa11
console.log(f("a1")); // -> a13
```
[Answer]
# LaTeX, 108/171
```
\newcounter{c}\def\s#1#2]{\stepcounter{c}\def\t{#2}\ifx\empty\t\arabic{c}\else#1\s#2]\fi}\def\q[#1]{\s#10]}
```
`\q[] //1`
[Answer]
## JavaScript (ES6), 37 bytes
```
f=(s,t=s,u=s+t.length)=>t==u?t:f(s,u)
```
```
<input oninput=o.textContent=f(this.value)><pre id=o>
```
[Answer]
## Lua 5.2, 32 Bytes
```
a=arg[1]print(a..#a+#(''..#a+1))
```
Where the variable *a* is the input string.
[Answer]
# C, ~~67~~ ~~65~~ 61 bytes
```
x;f(*v){printf("%d",(int)log10(x=-~printf(v))*-~(x%10>8)+x);}
```
[Wandbox](http://melpon.org/wandbox/permlink/vNFaprC3ZB9tthpp)
[Answer]
# Pyth - 7 bytes
```
+Qfql+Q
```
[Try it online here](http://pyth.herokuapp.com/?code=%2BQfql%2BQ&input=%22Aaaaaaaa%22&debug=0).
[Answer]
# Mathematica, 57 bytes
```
#<>ToString[(a=Length@#)+(i=IntegerLength)[a+i@a]~Max~1]&
```
Unnamed function taking an array of characters as input and returning a string. Uses the fact that if `a` is the length of the input, then the number to append to the input is `a` plus the number of digits in (`a` + the length of `a`), rather than just `a` plus the number of digits of `a`. Unfortunately it wouldn't give the right answer for the empty-string input without the `~Max~1` special case.
[Answer]
## Pyke, 8 bytes ([old version](https://github.com/muddyfish/PYKE/commit/894a88e818e5e86643765030ce5565246630671f))
```
.f+liq)+
```
Explanation:
```
.f ) - first where (i++)
+ - input + i
l - len(^)
iq - ^ == i
+ - input + ^
```
[Try it here!](http://pyke.catbus.co.uk/?code=.fDQ%2Blq%29%2B&input=aaaaaaaaa) (New version, 9 bytes)
[Answer]
# Python 2, ~~54~~ ~~48~~ 46 bytes
Simple solution. Recursion ended up being shorter.
```
f=lambda s,n=0:f(s,n+1)if(s+`n`)[n:]else s+`n`
```
[**Try it online**](https://tio.run/nexus/python2#@59mm5OYm5SSqFCsk2drYJWmAaS1DTUzgQzthLwEzeg8q9jUnOJUBTD3f7FtUWJ5fGZeQWmJhiZXeUZmDlDGiouzoCgzr0QhTSO1LDFHo1hTk4sTReV/JSUupcTERAgJBkjMRCUA)
[Answer]
## Haskell, 46 bytes
```
f s=[l|i<-[0..],l<-[s++show i],length l==i]!!0
```
Usage example: `f "aaaaaaaa"` -> `"aaaaaaaa9"`.
Simply try all numbers starting with 0 and take the first that fits.
[Answer]
# [Brachylog](http://github.com/JCumin/Brachylog), 13 bytes
```
l<L$@:?rc.lL,
```
[Try it online!](http://brachylog.tryitonline.net/#code=bDxMJEA6P3JjLmxMLA&input=ImFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhIg&args=Wg)
### Explanation
Basically a description of the problem. It will try every value of `L` bigger than the length of the input until it finds one for which, when concatenated to the input, is the length of that concatenation.
```
l<L length(Input) < L
L$@ Convert L to a string
:?rc. The Output is the concatenation of the Input with L as string
.lL, The length of the Output is L itself
```
[Answer]
# [Perl 6](https://perl6.org), ~~46~~ 35 bytes
```
{$_~(.chars,*.chars+.chars...{$^a==$^b})[*-1]}
```
```
{$_~(.chars,*.chars+.chars...*)[2]}
```
[Try it](https://tio.run/nexus/perl6#VVFBboMwELzziomKCiSOBUlVlSCSXnrovbeqihB1U1QCETZRURS@TteYCHraWc94dtaupcD5kaeRVRN6E1JFlnVscJ@WnwJxd7H3rcvT76SSbG7qwhTO@dx7X31cO5I/K7opEcO1gDXiLR4YIV@jgOEOL8eTaiBVlRUHIp40EWpJ2EsCDZ0kcHRHde30XC8L/J4NjdJfMcujjKc8KbAwc6n9KqtbiOUW9h4uNj@ice2sONVqmYvCY9ick7wWrl3W6nYIDxcypxWMklYYr6Bt8Voo7HaUycHvlJrNJl00WBhj7TGOmJgMI9p/tDYaW1oFyCT08w/hKfggYOCHTP/QtfsD "Perl 6 – TIO Nexus")
## Expanded:
```
{ # bare block lambda with implicit parameter 「$_」
$_ # the input
~ # concatenated with
( # sequence generator
.chars, # the number of chars in 「$_」 (seed the generator)
*\ # Whatever lambda input (represents previous value)
.chars # number of chars in that
+ # plus
.chars # the number of chars in 「$_」
... # keep doing that until
* # indefinitely
)[2] # get the value at index 2 of the sequence
}
```
[Answer]
# Brainfuck, 258 bytes
```
,>+<----------[++++++++++>+[>+<-],----------]<[<]>[.>]>>>++++++++++<<[->+>-[>+>>]>[+[-<+>]>+>>]<<<<<<]>>[-]>>>++++++++++<[->-[>+>>]>[+[-<+>]>+>>]<<<<<]>[-]>>[>++++++[-<++++++++>]<.<<+>+>[-]]<[<[->-<]++++++[->++++++++<]>.[-]]<<++++++[-<++++++++>]<.[-]<<[-<+>]
```
The input must be terminated by a linefeed (LF). Only works for inputs with a length lesser than 256 (including the LF).
[Try it online!](http://brainfuck.tryitonline.net/#code=LD4rPC0tLS0tLS0tLS1bKysrKysrKysrKz4rWz4rPC1dLC0tLS0tLS0tLS1dPFs8XT5bLj5dPj4-KysrKysrKysrKzw8Wy0-Kz4tWz4rPj5dPlsrWy08Kz5dPis-Pl08PDw8PDxdPj5bLV0-Pj4rKysrKysrKysrPFstPi1bPis-Pl0-WytbLTwrPl0-Kz4-XTw8PDw8XT5bLV0-Pls-KysrKysrWy08KysrKysrKys-XTwuPDwrPis-Wy1dXTxbPFstPi08XSsrKysrK1stPisrKysrKysrPF0-LlstXV08PCsrKysrK1stPCsrKysrKysrPl08LlstXTw8Wy08Kz5d&input=YWtkamduYm12bmRhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYW9namRuZXJ1NWpnYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhMTI1NDc4OTY1MmFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWIK)
## Explanation
```
# read first char and add one to cell #1
# the cell after the input will contain the length
,>+<
# subtract 10 to check for LF
----------
# while the input is not 10 (LF)
[
# restore the input to its original value
++++++++++
# add one to the length
>+
# cut and paste the length to the next cell, then read the input
[>+<-],
# subtract 10 to check for LF
----------
]
# for input abc, the tape here would be: a b c *0* 4
# rewind to the beginning of the input
<[<]>
# print the input string
[.>]>
# convert the length to ascii chars and output them
>>++++++++++<<[->+>-[>+>>]>[+[-<+>]>+>>]<<<<<<]>>[-]>>>++++++++++<[->-[>+>>]>[+[-
<+>]>+>>]<<<<<]>[-]>>[>++++++[-<++++++++>]<.<<+>+>[-]]<[<[->-<]++++++[->++++++++
<]>.[-]]<<++++++[-<++++++++>]<.[-]<<[-<+>]
```
*Note: I used code from this [SO answer](https://stackoverflow.com/a/13946554/1899794) to convert the length to ascii output; I hope this is acceptable on PPCG. This is my first Codegolf submission, and my second BF program. Feedback is welcomed.*
[Answer]
## Python, 39 bytes
```
lambda a:eval('a+str(len('*3+'a))))))')
```
Longer form:
```
lambda a:a+str(len(a+str(len(a+str(len(a))))))
```
Iteratively in Python 2 (41 bytes):
```
x=a=input();exec"x=a+`len(x)`;"*3;print x
```
Starting with `x` as the input string `a`, applies the transformation `x -> a + str(len(x))` three times. I'm still not clear why three applications are needed to always reach the fixed point.
[Answer]
## [Retina](https://github.com/m-ender/retina), 22 bytes
```
\G`
.
x
+r`\d*$
$._
x
```
[Try it online!](https://tio.run/nexus/retina#U9VwT/gf457ApcdVwaVdlBCToqXCpaIXD@T9/8@VmJgIwmAAZyCxkJk0ArS3gR5W0MWOUTAKRsEAgtFMPgpGwWguHwWjYBQMcQAA "Retina – TIO Nexus")
Ah well, if it wasn't for digits appearing in the input, this would be merely 11 bytes:
```
+r`\d*$
$._
```
[Answer]
# Ruby, 62 58 56 bytes
```
s=gets.chomp;p s+"#{(s+"#{(s+"#{s.size}").size}").size}"
```
Tested in `irb`.
There's probably a better way to do this, but this was the first thing I came up with. Any help in golfing would be appreciated.
**edit:** I realized my use of parentheses was excessive.
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), 11 bytes
```
[¹¾JDg¾Q#¼\
```
Pretty straightforward bruteforce:
```
Implicit i = 0
[ while true
¹¾J Concatenate input and i -> str
Dg¾Q# Break if length(str) == i
¼\ Else, i += 1
```
[Try it online!](http://05ab1e.tryitonline.net/#code=W8K5wr5KRGfCvlEjwrxc&input=YWFhYWFhYWFh)
[Answer]
# PHP, 42 bytes
```
while(++$n<strlen($a=$argv[1].$n));echo$a;
```
Run with `-r`. Test [at OnlinePHPfunctions](http://sandbox.onlinephpfunctions.com/code/0b48cf43d8f9bd339f5c94f23dbf26a57541d861).
[Answer]
## bash, 47 bytes
```
for((n=-1;${#s} != $n;));{ s=$1$[++n];};echo $s
```
Save this as a script, and pass the input string as an argument.
It's a brute force implementation: try each number in turn until you find one which works.
[Answer]
# ><> (Fish) 35 bytes
```
i:1+?!v:o
ln;v9l< >
*9+>:&)?!^1l&a
```
Takes input onto the stack, checks the length against values 9,99,999... and if the length is larger than add 1 to the stack length.
[Answer]
# [Haskell](https://www.haskell.org/), ~~61~~ 60 bytes
```
e=length
l%n|s<-show$l+1,n>e s=s|m<-n+1=(l+1)%m
c s=s++e s%2
```
[Try it online!](https://tio.run/nexus/haskell#y03MzLPNzCtJLUpMLlFI/p9qm5Oal16SwZWjmldTbKNbnJFfrpKjbaiTZ5eqUGxbXJNro5unbWirARTTVM3lSgYJamsD5VSN/v9PpD0AAA "Haskell – TIO Nexus")
Recursive solution. Usage:
```
Prelude> c "aaaaaaaaa"
"aaaaaaaaa11"
```
[Answer]
# Ruby, ~~43~~ 36 bytes
Anonymous function, [abusing](https://codegolf.stackexchange.com/a/92066/4372) the `$.` global.
```
->s{$.+=1while(t=s+"#$.").size>$.;t}
```
Call it like this:
```
f = ->s{$.+=1while(t=s+"#$.").size>$.;t}
f[""] # => "1"
f["a"] # => "a2"
f["aaaaaaa"] # => "aaaaaaa8"
f["aaaaaaaa"] # => "aaaaaaaa9"
f["aaaaaaaaa"] # => "aaaaaaaaa11"
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 6 bytes
```
LJL+LJ
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJQ4bmgIiwiIiwiTEpMK0xKIiwiIiwiYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYSJd)
Append the length of the string, take the length of that, then append the new length to the original. This does work with digit overflows (9, 99, etc...).
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 8 bytes
```
L3Ya.#yy
```
[Try It Online!](https://dso.surge.sh/#@WyJwaXAiLCIiLCJMM1lhLiN5eSIsIiIsIiIsIlwiYWFhYWFhYWFhXCIiXQ==)
### Explanation
Inspired by [Pacmanboss256's Vyxal solution](https://codegolf.stackexchange.com/a/252736/16766).
```
;; y is empty string; a is first command-line argument (implicit)
L3 ;; Loop 3 times:
a. ;; Concatenate a with
#y ;; Length of y
Y ;; Assign the result to y
y ;; After the loop, output y
```
Some worked examples:
```
Input a "" "aaa" "aaaaaaaaa"
Original y "" "" ""
After loop 1 "0" "aaa0" "aaaaaaaaa0"
After loop 2 "1" "aaa4" "aaaaaaaaa10"
After loop 3 "1" "aaa4" "aaaaaaaaa11"
```
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 31 bytes
```
{$[9>t:#x;x,$1+t;x,$#x,($1+t)]}
```
[Try it online!](https://ngn.codeberg.page/k#eJxLs6pWiba0K7FSrrCu0FEx1C4BUcoVOhogtmZsLRdXWrRSYmKiUiyIASEToQCVh86F8aGUoVIsAKDMH2Y=)
*+22 bytes thanks to Dominic van Essen for pointing out a not-working test case (that should have worked)*
[Answer]
# C#, 77 bytes
```
n=>{int a=n.Length;int c=(a+1).ToString().Length-1;return(n+(n.Length+1+c));}
```
[Answer]
# [MATL](http://github.com/lmendo/MATL), 11 bytes
```
`G@Vhtn@>]&
```
[Try it online!](http://matl.tryitonline.net/#code=YEdAVmh0bkA-XSY&input=J2FhYWFhYWFhYSc) Or [verify all test cases](http://matl.tryitonline.net/#code=YFhLCmBLQFZodG5APl0mClhETiR4VA&input=J2FhYScKJycKJ2FhYWFhYWFhJwonYWFhYWFhYWFhJwonYTEnCidhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYScKJ2FhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYSc).
```
` % Do...while
G % Push input
@ % Push iteration index (1-based)
V % Convert number to string
h % Concatenate horizontally
t % Duplicate
n % Get length of concatenated string
@ % Push iteration index
> % True if length of concatenated string exceeds iteration index
] % End. Run next iteration if top of stack is true; else exit loop
& % Specifiy that next function (implicit display) takes only one input
% Implicitly display top of the stack. This is the concatenated string
% that had a length equal to the iteration index
```
[Answer]
# Ruby, 51 bytes (program)
# Ruby, 49 bytes (function)
Program (last newline is not necessary and thus unscored):
```
x=gets.strip
i=0
i+=1 until(y=x+i.to_s).size==i
p y
```
Function (last newline is scored):
```
def f x
i=0
i+=1 until(y=x+i.to_s).size==i
y
end
```
[Answer]
# Factor, 55 bytes
It's a walk in the park! I came up with this in my head as soon as I read the question.
```
[ dup length dup log10 ⌈ + >integer 10 >base append ]
```
[Answer]
**Clojure, 72 bytes**
```
(defn f([s](f s 1))([s n](if(=(count(str s n))n)(str s n)(f s(inc n)))))
```
] |
[Question]
[
The video game [Minecraft](http://en.wikipedia.org/wiki/Minecraft) is all about placing and removing different types of blocks in the 3D [integer lattice](http://en.wikipedia.org/wiki/Integer_lattice) that makes up the virtual world. Each lattice point can contain exactly one block or be empty (an "[air](http://minecraft.gamepedia.com/Air)" block officially). In this challenge, we will only be concerned with one vertical 2D plane of the 3D world, and one type of block: [obsidian](http://minecraft.gamepedia.com/Obsidian).
When obsidian forms the outline of an empty rectangle in a vertical plane, a [nether portal](http://minecraft.gamepedia.com/Nether_Portal) can be created. The empty rectangle may be any size from 2 units wide by 3 units high to 22 units wide by 22 units high. The corners of the rectangle do not need to be bordered in obsidian, just the sides.
For example, suppose `X` is obsidian and `.` is emptiness: (The numbers are just for identification purposes and are also empty.)
```
...................................
..XXXX....XXXX....XXXXXXXXX........
..X..X...X....X..X.........X..XXXX.
..X.1X...X.2..X..X...3...X.X..X....
..X..X...X....XXXX.........X..X.6X.
..XXXX....XXXX...XXXXXXXXXXX..X..X.
.............X.4.X....X.5.X...XXXX.
.............X...X....X...X........
..............XXX......XXX.........
...................................
```
This grid contains 3 valid portals:
* Portal 1 is 2 by 3 units, totally empty, and bordered in obsidian. Therefore it's valid.
* Portal 2 is 4 by 3, totally empty, and bordered in obsidian. Therefore it's valid.
* Portal 3 isn't totally empty. Therefore it's invalid.
* Portal 4 is 3 by 3, totally empty, and bordered in obsidian. Therefore it's valid.
* Portal 5 is 3 by 2 units, which is too small. Therefore it's invalid.
* Portal 6 is missing a part of the border. Therefore it's invalid.
## Challenge
Write a program or function that takes in these string representations of grids of obsidian and emptiness, and prints or returns the number of valid nether portals present.
* Input can be from stdin or file or function argument.
* You may assume the input is always well formed - i.e. a perfectly rectangular grid of text, at least 1 character wide and tall, only containing `X` and `.`. You may optionally assume there is a trailing newline after the last row.
* If desired, you may use any two distinct [printable ASCII](http://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters) characters in place of `X` and `.`.
* Obsidian may be on the borders of the grid. Anything beyond the borders is considered empty.
Example input - the output should be `4`:
```
................................................................
...................................XXXXXXXXXXXXXXXXXXXXXXXXX....
..XXXX....XXXX....XXXXXXXXX........X.......................X....
..X..X...X....X..X.........X..XXXX.X.......................X....
..X..X...X....X..X.......X.X..X....X.......................X....
..X..X...X....XXXX.........X..X..X..XXXXXXXXXXXXXXXXXXXXXXXX....
..XXXX....XXXX...XXXXXXXXXXX..X..X.X......................X..XXX
.............X...X....X...X...XXXX.X......................X..X..
.............X...X....X...X........X......................X..X..
..............XXX......XXX........XXXXXXXXXXXXXXXXXXXXXXXX...X..
..................................XX.........................XXX
```
# Scoring
The submission with the [fewest bytes](https://mothereff.in/byte-counter) wins.
[Answer]
# Regex (.NET flavour), ~~182~~ ~~181~~ ~~145~~ ~~132~~ ~~126~~ ~~114~~ ~~104~~ ~~100~~ ~~98~~ ~~97~~ 96 bytes
2D ASCII art pattern recognition? Sounds like a job for regex! (It doesn't.)
I know this is going to kick loose endless discussions again about whether regex submissions are valid programs or not, but I doubt this will beat APL or CJam anyway, so I don't see any harm. (That being said, they *do* pass our die-hard test for ["What is a programming language?"](http://meta.codegolf.stackexchange.com/a/2073/8478).)
This takes input as the string to be matched, and the result is the number of matches found. It uses `_` in place of `.`, because I'd have to escape the latter. It also requires a trailing newline.
```
(X(X){1,21})(?=\D+((?>(?<-2>_)+)_))(?=.((?!\7)(.)*
.*(X\3X|()\1.)(?=(?<-5>.)*(?(5)!)
)){4,23}\7)
```
You can test it live at [RegexHero](http://regexhero.net/tester/?id=66dfe758-3337-4846-b25f-8b4641625bf4) or [RegexStorm](http://regexstorm.net/tester?p=(X(X)%7b1%2c21%7d)(%3f%3d%5cD%2b((%3f%3e(%3f%3c-2%3e_)%2b)_))(%3f%3d.((%3f!%5c7)(.)*%0d%0a.*(X%5c3X%7c()%5c1.)(%3f%3d(%3f%3c-5%3e.)*(%3f(5)!)%0d%0a))%7b4%2c23%7d%5c7)&i=________________________________________________________________%0d%0a___________________________________XXXXXXXXXXXXXXXXXXXXXXXXX____%0d%0a__XXXX____XXXX____XXXXXXXXX________X_______________________X____%0d%0a__X__X___X____X__X_________X__XXXX_X_______________________X____%0d%0a__X__X___X____X__X_______X_X__X____X_______________________X____%0d%0a__X__X___X____XXXX_________X__X__X__XXXXXXXXXXXXXXXXXXXXXXXX____%0d%0a__XXXX____XXXX___XXXXXXXXXXX__X__X_X______________________X__XXX%0d%0a_____________X___X____X___X___XXXX_X______________________X__X__%0d%0a_____________X___X____X___X________X______________________X__X__%0d%0a______________XXX______XXX________XXXXXXXXXXXXXXXXXXXXXXXX___X__%0d%0a__________________________________XX_________________________XXX%0d%0a)). The matches will be the top obsidian rows of the portals. If you can find a test case where it fails, please let me know!
## What is this sorcery?
The following explanation assumes a basic understanding of .NET's *balancing groups*. The gist is that captures are stacks in .NET regex - every new capture for the same name is pushes onto the stack, but there's also syntax to pop captures from those stacks again, as well as syntax to pop captures from one stack and push captures onto another at the same time. For a more complete picture, you can have a look [at my answer on Stack Overflow](https://stackoverflow.com/a/17004406/1633117) which should cover all the details.
The basic idea is to match a pattern like:
```
X{n}..{m}
X_{n}X.{m} |
X_{n}X.{m} | 3 to 22 times
X_{n}X.{m} |
X{n}..{m}
```
Where `n` is between 2 and 22 (inclusive). The tricky thing is getting all the `n`s and all the `m`s to be the same. Since the actual characters won't be the same, we can't just use a backreference.
Note that the regex has to embedded newlines, which I'll write as `\n` in the following.
```
( # Open capturing group 1. This will contain the top of a portal, which
# I can reuse later to match the bottom (being of the same length).
X # Match a single X.
(X){1,21} # Match 1 to 21 X's, and push each separately on the <2> stack. Let's
# Call the number of X's captured N-1 (so N is the inner width of the
# portal).
) # End of group 1. This now contains N X's.
(?= # Start a lookahead. The purpose of this lookahead is to capture a
# string of N underscores in group 2, so I can easily use this to match
# the inside rows of the portal later on. I can be sure that such a
# string can always be found for a valid portal (since it cannot have 0
# inner height).
\D+ # Skip past a bunch of non-digits - i.e. *any* of the vaild characters
# of the input (_, X, \n). This to make sure I search for my N
# underscores anywhere in the remainder of the input.
( # Open capturing group 3. This will contain a portal row.
(?> # This is an atomic group. Once the engine hass successfully matched the
# contents of this group, it will not go back into the group and try to
# backtrack other possible matches for the subpattern.
(?<-2>_)+ # Match underscores while popping from the <2> stack. This will match as
# many underscores as possible (but not more than N-1).
) # End of the atomic group. There are two possible reasons for the
# subpattern stopping to match: either the <2> stack is empty, and we've
# matched N-1 underscores; or we've run out of underscores, in which
# case we don't know how many underscores we matched (which is not
# good).
_ # We simply try to match one more underscore. This ensures that we
# stopped because the <2> stack was empty and that group 3 will contain
# exactly N underscores.
) # End of group 3.
) # End of the lookahead. We've got what we want in group 2 now, but the
# regex engine's "cursor" is still at the end of the portal's top.
(?= # Start another lookahead. This ensures that there's actually a valid
# portal beneath the top. In theory, this doesn't need to be a
# lookahead - I could just match the entire portal (including the lines
# it covers). But matches cannot overlap, so if there were multiple
# portals next to each other, this wouldn't return all of them. By
# putting the remainder of the check in a lookahead the actual matches
# won't overlap (because the top cannot be shared by two portals).
. # Match either _ or X. This is the character above the portal side.
( # This group (4) is where the real magic happens. It's purpose is to to
# count the length of the rest of the current line. Then find a portal
# row in the next line, and ensure that it's the same distance from the
# end of the line. Rinse and repeat. The tricky thing is that this is a
# single loop which matches both inner portal rows, as well as the
# bottom, while making sure that the bottom pattern comes last.
(?!\7) # We didn't have a group 7 yet... group 7 is further down the pattern.
# It will capture an empty string once the bottom row has been matched.
# While the bottom row has not been matched, and nothing has been
# captured, the backreference will fail, so the negative lookahead will
# pass. But once we have found the bottom row, the backreference will
# always match (since it's just an empty string) and so the lookahead
# will fail. This means, we cannot repeat group 4 any more after the
# bottom has been matched.
(.)* # Match all characters until the end of the line, and push each onto
# stack <5>.
\n # Match a newline to go to the next line.
.* # Match as many characters as necessary to search for the next portal
# row. This conditions afterwards will ensure that this backtracks to
# the right position (if one exists).
( # This group (6) will match either an inner portal row, or the bottom
# of the portal.
X\3X # Match X, then N underscores, then X - a valid inner portal row.
| # OR
() # Capture an empty string into group 7 to prevent matching further rows.
\1. # Use the captured top to match the bottom and another character.
)
(?= # This lookahead makes sure that the row was found at the same
# horizontal position as the top, by checking that the remaining line
# is the same length.
(?<-5>.)* # Match characters while popping from the <5> stack.
(?(5)!)\n # Make sure we've hit end of the line, *and* the <5> stack is empty.
)
){4,23} # Repeat this 4 to 23 times, to ensure an admissible portal height.
# Note that this is one more than the allowed inner height, to account
# for the bottom row.
\7 # Now in the above repetition there is nothing requiring that we have
# actually matched any bottom row - it just ensured we didn't continue
# if we had found one. This backreference takes care of that. If no
# bottom row was found, nothing was captured into group 7 and this
# backreference fails. Otherwise, this backreference contains an empty
# string which always matches.
)
```
# C#, 185 bytes
Here is a full C# function, just to make this a valid entry. It's time I wrote a command-line "interpreter" for .NET regular expressions...
```
static int f(string p){return System.Text.RegularExpressions.Regex.Matches(p,@"(X(X){1,21})(?=\D+((?>(?<-2>_)+)_))(?=.((?!\7)(.)*
.*(X\3X|()\1.)(?=(?<-5>.)*(?(5)!)
)){4,23}\7)").Count;}
```
[Answer]
# Perl, 81 86
Using more than one regexp.
```
#!perl -p0
$_=map{/.
/;$n="@-"-++$.;/(?=X{$.}..{$n}(X\.{$.}X.{$n}){3,22}.X{$.})/gs}($_)x21
```
The regexp for a specific width of a portal is much simpler than a generic one: `X{$m}..{$n}(X\.{$m}X.{$n}){3,22}.X{$m}` where `m` is the width of the portal and `n` is `total width - 1 - m`. The regexp must be put in a zero width forward assertion `(?=...)` because the matches may overlap. Then I iterate 21 times over this regexp setting `$n` and `$.`. `"@-"` evaluates to start position of the last match (`/.\n/`) which happen to be total width - 1. `$.` is used as the other variable as it is initialized to `1` when used with `-p0`.
[Answer]
# Python, 219 bytes
```
def f(s):s=s.split();L=len;R=range;return L([r for r in R(L(s))for a in R(L(s[0]))for w in R(2,23)for h in R(3,min(L(s)+~r,23))if(s[r][a:a+w]==s[r-~h][a:a+w]==w*"X")*all(s[r-~k][a-1:a+w+1]=="X"+"."*w+"X"for k in R(h))])
```
Better than Java, but boy the quintuple nested loops hurt. The `for/in` might be slightly compressible using `%s` substitution, but it wouldn't save much.
**Expanded:**
```
def f(s):
s=s.split()
L=len
R=range
return L([r for r in R(L(s))
for a in R(L(s[0]))
for w in R(2,23)
for h in R(3,min(L(s)+~r,23))
if(s[r][a:a+w]==s[r-~h][a:a+w]==w*"X")*
all(s[r-~k][a-1:a+w+1]=="X"+"."*w+"X"for k in R(h))])
```
[Answer]
# Java, 304 bytes
This is a lot longer than a regular expression. It simply iterates over every possible square in the input. If it is a valid portal, it increments a counter by 1. It then returns the counter. This can probably be golfed much further. Any suggestions are welcome.
```
int a(String...a){a=a[0].split("\n");int b=0,c=0,d,e,f,g,h,i=a.length,j=a[0].length();for(;c<j;c++)for(d=0;d<i;d++)for(e=c+2;++e<j&e<c+24;)a:for(f=d+3;++f<i&f<d+24;){for(g=c;g<=e;g++)for(h=d;h<=f;h++){if(g==c|g==e&&h==d|h==f)continue;if((g==c|g==e|h==d|h==f)^a[h].charAt(g)>60)continue a;}b++;}return b;}
```
Indented:
```
int a(String...a){
a=a[0].split("\n");
int b=0,c=0,d,e,f,g,h,i=a.length,j=a[0].length();
for(;c<j;c++)
for(d=0;d<i;d++)
for(e=c+2;++e<j&e<c+24;)
a:for(f=d+3;++f<i&f<d+24;){
for(g=c;g<=e;g++)
for(h=d;h<=f;h++){
if(g==c|g==e&&h==d|h==f)
continue;
if((g==c|g==e|h==d|h==f)^a[h].charAt(g)>60)
continue a;
}
b++;
}
return b;
}
```
Full program:
```
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
public class B {
public static void main(String[] args) throws FileNotFoundException {
String blocks = new BufferedReader(new FileReader(args[0])).lines().reduce((a,b)->a+"\n"+b).get();
System.out.println(new B().a(blocks));
}
int a(String...a){
a=a[0].split("\n");
int b=0,c=0,d,e,f,g,h,i=a.length,j=a[0].length();
for(;c<j;c++)
for(d=0;d<i;d++)
for(e=c+2;++e<j&e<c+24;)
a:for(f=d+3;++f<i&f<d+24;){
for(g=c;g<=e;g++)
for(h=d;h<=f;h++){
if(g==c|g==e&&h==d|h==f)
continue;
if((g==c|g==e|h==d|h==f)^a[h].charAt(g)>60)
continue a;
}
b++;
}
return b;
}
}
```
] |
[Question]
[
Your should write a program or function that takes a 4-character string as input and outputs a value indicating if the string is an English word or not. You are allowed to make mistakes in 15% of the provided testcases.
## Input details:
Input is a 4-character string containing only the lowercase English letters (a-z).
## Output details:
If the input **is** an English word you should output a boolean `true` or an integer `1`.
If the input **isn't** an English word you should output a boolean `false` or an integer `0`.
## Word lists
[list of 4-letter English words](http://pastebin.com/raw.php?i=q5a2MUz6) (2236 words)
[list of 4-letter non-word strings](http://pastebin.com/raw.php?i=yxGhQyvY) (2236 strings)
The non-word list contains uniformly randomly generated letter sequences with the real words removed from them.
## Testing
Your program or function should make no more than 15% mistakes on the given word lists together. That means you can give wrong output for 670 of the 4472 provided inputs.
You should post the testing program or function too so others could check your answer. The length of your testing program doesn't count into your submissions score.
[Standard loopholes](http://meta.codegolf.stackexchange.com/questions/1061/standard-loopholes-which-are-no-longer-funny/) are disallowed.
Your program shouldn't use any external sources e.g. accessing web or reading from file.
This is code-golf so the shortest program or function wins.
[Answer]
# Ruby, 29 bytes
```
->s{!s[/[^aeiou]{3}|[jqxz]/]}
```
Hopefully I've got this right - it's my first time programming in Ruby. I actually did all my testing in Python, but `import re` was far too long for me.
This is an anonymous function which takes in a string and outputs `true/false` accordingly. It uses a regex which looks for one of the following two things:
* Three consonants in a row
* Contains one of `jqxz`
If either of these are present, we classify the input as not a word.
The function matches 2030 words (incorrectly failing on 206) and fails on 1782 non-words (incorrectly matching 454), for a total of 660 misclassifications. [Tested on ideone](http://ideone.com/hEHRQ8).
Thanks to @MartinBüttner for the Ruby help. Martin also points out that a full program takes the same number of bytes:
```
p !gets[/[^aeiou]{3}|[jqxz]/]
```
Also thanks to user20150203 for simplifying the regex.
---
# Ruby, ~~1586~~ ~~1488~~ ~~1349~~ ~~1288~~ 1203 bytes
For a bonus, here's a function with a much longer regex:
```
->s{!s[/[^aeiouyhs]{3}|[^aeiouy]{4}|q[^u]|^x|^[bdf][^aeioulry]|^[cgkprtwy][mfdsbktjgxpc]|^a[aoz]|^e[hf]|^i[ea]|^o[ecy]|^u[^ltnspgr]|[bdgktyz][cgmpw]$|[fhpvx][^aieoflnrsty]$|eh$|i[iyh]|[wkybp]z|[dghz]t|[fjzsv]y.|h[ns].|ae.|y.?[yifj]|[ejo]..[iuw]|[inv]..[gpuvz]|[eu].[jqwx]|[vyz][^t][fhmpqy]|i[^ae][fjqrv]|[ospen].?j|[ceg][iuy][ghkoux]|[bcpx]f|[hnuy]w|[ghnw]b|[txz]n|[jk]r|.[fjuyz]u|[hnt]ia|lsy|.p.o|.l.l|.tas|zal|f.p|eeb|wei|.sc.|.pl|yat|hov|hab|aug|v.re|aba|ohu|ned|s.dd|uc$|nux|oo$|dgo|lix|wua|v.o|vo$|ryo|wue|dk|oic|yol|.tr|yrb|oba|ruh|c.ls|idd|chn|doy|ekh|tk|lke|asl|cir|eez|asc|uil|iou|m..p|awt|irp|zaa|td|swk|ors|phe|aro|yps|q.e|ati|ibt|e.mo|we.y|p.de|ley|eq|tui|e..g|sps|akh|dny|swr|iul|.t.t|.tao|rcy|.p.y|idi|j.o|.kl|oms|ogi|jat|.lis|mye|uza|rsi|.ala|ibo|ipi|yaa|eun|ruy|wog|mm$|oex|koi|uyn|.hid|osc|ofe|w.op|auc|uzy|yme|aab|slm|oza|.fi|bys|z.e|nse|faf|l.h|f.va|nay|hag|opo|lal|seck|z.b|kt|agl|epo|roch|ix.|pys|oez|h.zi|nan|jor|c.ey|dui|ry.d|.sn|sek|w.no|iaz|ieb|irb|tz.|ilz|oib|cd|bye|ded|f.b|if$|mig|kue|ki.w|yew|dab|kh.|grs|no.t|cs.|.n.m|iea|y.na|vev|eag|el[uz]|eo[dkr]|e[hlsu]e|e[dho]l|eov|e[adp]y|r[grt]u|yn[klo]|.[^ilv].v|s[bdgqrz]|m[dfghrz]|[vpcwx]{2}|^[hjlmnvz][^aeiouy]|^[drw]l|l[hnr]/]}
```
I wanted to show that regex can still beat compression, so this one [classifies every given case correctly](http://ideone.com/Am3IJg). The regex itself is a bit like exponential decay — the first bits match a lot of non-words, then every bit after matches fewer and fewer until I gave up and just concatenated the rest (about 200 or so) at the end. Some of the ones that were left looked surprisingly like real words (such as `chia` which *is* a word).
I threw the regex at my regex golf cleaner which I wrote for another challenge — it golfed about 300 bytes before I had to try shuffling things around manually. There's still a fair bit to be golfed though.
[Answer]
# Groovy, ~~77~~ 74
```
x={it==~/^(?!.+[jq]|[^aeiou][^aeiouhlr]|.[^aeiouy]{3}|.[x-z])|^s[cknptw]/}
```
I wrote the test program in Java, which you can find in [this Gist](https://gist.github.com/nhahtdh/e1bb0a94483e5279e3c2) on Github. Here is the output from my test program:
```
Good: 2135 1708
Bad: 101 528
```
(Failed 629 test cases)
P.S. I think this is going to end up a regex golf problem extremely soon...
If [Sp3000's answer](https://codegolf.stackexchange.com/a/45300/6638) (the function) is to be converted to Groovy, it will end up with the same character count. As named function:
```
x={it!=~/[^aeiou]{3}|[jqxz]/}
```
or unnamed function:
```
{i->i!=~/[^aeiou]{3}|[jqxz]/}
```
[Answer]
# Javascript, 1626 bytes:
I wanted to go for a solution which for each character has a clue of which one might come after. Not that short, but no regex and a fairly good result (words: 101 mistakes, non-words, 228 mistakes)
```
v=function(w){var g={a:{b:3,c:4,d:4,m:6,f:1,r:14,g:4,i:6,x:2,k:2,l:10,n:12,s:6,p:4,t:7,u:2,v:3,w:3,y:3,h:1,z:1},b:{b:3,a:19,e:19,y:3,l:6,o:17,u:12,i:9,s:9,r:6},e:{d:7,l:8,t:4,s:10,n:11,e:10,r:10,c:2,x:2,w:4,a:13,f:1,p:2,g:2,v:1,b:1,m:3,u:1,i:1,k:1,y:2},l:{e:16,y:5,a:16,b:1,f:2,l:12,m:2,o:14,p:1,s:2,u:8,d:4,i:10,k:3,t:5},o:{s:7,g:3,e:3,k:3,n:10,m:4,p:5,w:6,b:3,c:2,t:6,a:5,d:5,h:1,i:2,l:8,o:9,r:8,u:4,y:2,v:2,z:1,f:2,x:1},u:{t:8,e:5,m:7,s:11,a:2,n:13,r:15,d:6,c:4,f:1,g:5,l:9,y:1,z:1,b:5,j:1,x:1,p:2,k:1,i:2},c:{e:9,h:12,i:2,r:6,t:3,o:20,k:15,a:16,l:6,u:8,y:1},h:{e:21,r:2,a:22,i:15,o:20,u:15,n:3,l:1,y:1},i:{d:8,m:5,n:18,r:7,a:2,s:8,v:2,l:13,t:10,b:1,e:6,k:2,p:5,g:3,c:6,o:2,f:2,z:1},m:{e:19,s:8,a:21,i:12,m:1,o:15,y:2,b:4,p:8,n:1,u:8},n:{e:18,u:3,a:9,d:10,n:4,o:7,s:11,t:11,g:10,k:6,i:5,y:2,c:1},r:{e:18,s:4,y:4,a:16,c:1,g:1,i:12,m:3,p:2,t:4,b:1,d:4,k:4,n:5,r:2,o:11,l:2,u:6,f:1},t:{a:14,s:17,e:18,i:9,o:15,h:10,t:3,y:2,c:1,z:1,u:5,r:5,w:2},d:{a:14,d:4,s:10,e:22,y:8,i:12,o:14,r:4,u:10,l:1},f:{a:16,f:6,e:12,y:1,i:14,l:13,o:16,r:7,u:7,t:7,n:1,s:1},g:{a:16,e:12,o:17,u:7,s:18,g:1,y:2,i:8,l:4,n:2,h:3,r:9,w:1},j:{a:25,i:7,e:14,o:25,u:29},k:{i:23,s:6,e:41,u:6,a:10,l:2,n:8,o:2,h:1,y:1},p:{s:12,e:20,a:19,y:2,i:13,t:2,u:10,l:5,o:13,r:4},s:{o:8,i:8,e:13,k:6,h:10,s:8,t:14,y:1,p:5,c:2,l:6,a:10,m:1,n:2,u:4,w:2},v:{a:18,e:47,i:22,o:8,y:6},y:{l:4,e:18,s:20,d:3,n:8,r:8,t:4,a:14,k:1,m:1,o:8,x:3,p:3,u:4,v:1},q:{u:100},w:{a:24,e:17,l:4,r:3,s:10,n:6,y:2,k:1,d:1,t:1,i:17,u:1,o:10,h:4},x:{e:35,i:18,l:6,o:6,a:6,t:12,y:18},z:{z:10,y:10,a:3,e:43,r:3,o:17,i:10,u:3}},p=1,x,y,i=0;for(;i<3;){x=w[i],y=w[++i];p*=g[x]&&g[x][y]||0}return p>60}
```
Here's a working implementation <http://fiddle.jshell.net/jc73sjyn/>
In short: the Object g holds the characters from a to z (as keys), and for each of them, there is a set of characters (also as keys) that each represent a character that may come after, along with its probability percentage. Where no object exists, there is no probability.
The 3 scores (4 letters -> 3 evaluations) are multiplied, and a word with a score of 60 and above is considered a real word.
Example: for the word 'cope' there are three lookups:
g[c][o] = 20
g[o][p] = 5
g[p][e] = 20
score = 20 \* 5 \* 20 = 2000, which is more than 60, so that one is valid.
(I'm quite new with javascript, so there might be ways to make it shorter that I don't know of.)
**LATE EDIT:**
Completely irrelevant by now, but I evaluated my way to a more correct g:
```
g={a:{b:7,c:4,d:4,m:6,f:2,r:14,g:4,i:6,x:2,k:2,l:10,n:12,s:6,p:4,t:7,u:2,v:3,w:12,y:3,h:1,z:1},b:{b:10,a:19,e:19,y:3,l:6,o:17,u:10,i:9,s:9,r:3},e:{d:7,l:8,t:4,s:10,n:11,e:10,r:10,c:2,x:2,w:4,a:13,f:1,p:2,g:2,v:20,b:3,m:3,u:1,i:1,k:1,y:2},l:{e:16,y:5,a:16,b:1,f:2,l:12,m:2,o:14,p:1,s:6,u:61,d:1,i:10,k:3,t:5},o:{s:7,g:3,e:3,k:3,n:20,m:4,p:5,w:6,b:3,c:2,t:6,a:5,d:5,h:10,i:2,l:8,o:3,r:8,u:4,y:2,v:2,z:1,f:20,x:1},u:{t:8,e:5,m:7,s:11,a:2,n:13,r:15,d:6,c:1,f:10,g:5,l:9,y:1,z:1,b:5,j:1,x:1,p:2,k:1,i:2},c:{e:9,h:20,i:2,r:6,t:20,o:15,k:15,a:15,l:6,u:8,y:1},h:{e:21,r:2,a:7,i:15,o:20,u:15,n:10,l:0,y:1},i:{d:8,m:5,n:18,r:7,a:5,s:8,v:2,l:13,t:20,b:1,e:21,k:2,p:5,g:20,c:4,o:2,f:2,z:1},m:{e:10,s:8,a:21,i:12,m:1,o:15,y:2,b:4,p:2,n:1,u:8},n:{e:18,u:3,a:9,d:3,n:4,o:20,s:2,t:11,g:10,k:6,i:5,y:2,c:1},r:{e:15,s:4,y:4,a:16,c:1,g:1,i:12,m:3,p:2,t:4,b:1,d:4,k:4,n:5,r:2,o:11,l:2,u:20,f:1},t:{a:14,s:15,e:18,i:2,o:15,h:10,t:3,y:2,c:1,z:1,u:5,r:5,w:2},d:{a:14,d:4,s:10,e:61,y:8,i:12,o:7,r:3,u:10,l:0},f:{a:5,f:6,e:12,y:1,i:3,l:13,o:16,r:7,u:20,t:4,n:1,s:1},g:{a:16,e:12,o:17,u:7,s:18,g:0,y:2,i:8,l:3,n:2,h:3,r:9,w:1},j:{a:8,i:7,e:14,o:5,u:29},k:{i:3,s:20,e:41,u:6,a:10,l:20,n:8,o:2,h:1,y:1},p:{s:12,e:20,a:5,y:2,i:13,t:4,u:10,l:3,o:13,r:4},s:{o:8,i:8,e:13,k:6,h:10,s:8,t:14,y:1,p:5,c:2,l:2,a:10,m:2,n:6,u:8,w:2},v:{a:10,e:20,i:22,o:6,y:6},y:{l:6,e:15,s:20,d:3,n:8,r:8,t:4,a:4,k:1,m:1,o:3,x:3,p:3,u:1,v:1},q:{u:100},w:{a:24,e:17,l:4,r:2,s:3,n:6,y:20,k:1,d:1,t:1,i:17,u:6,o:10,h:20},x:{e:35,i:6,l:3,o:6,a:6,t:3,y:7},z:{z:10,y:10,a:3,e:43,r:1,o:8,i:7,u:1}}
```
New results:
words: 53 mistakes, non-words: 159 mistakes
<http://fiddle.jshell.net/jc73sjyn/2/>
[Answer]
# Python 2, 5254 bytes
This solution separates the good words into two halves. The lookup first checks the first 2 characters to find the right string, then looks for the second 2 characters in that string. Not very compact, but quick to write. This method matches every word without mistakes.
```
d='''gwenyn
guamlflllpmsnsrushsttsys
grabadamayegeweyidiminipisitowub
gyro
gearldlsmsnentrmts
gagsilinitlellltmengpepsrbryshspteulvewkze
goadalatbidsesffghldlfnengodofreryshtoutwn
gnataw
gladeeenowueut
giftldllltnannnonsrdrlrtstve
wrapenit
leadafakanaparekeresftgsnandnsntonsssttsvivywd
labsceckcydsdygsidinirkembmempnandnengospsrdrkrsshssstteuevawnwsyszy
loadafanbecickebftgogsiniskilambmenengokomonopotrdresesssttsudutvewews
tubebsckftgsnerfrn
trapayeeekimioipodotoyueuk
liarceckdsedeneseufeftkelalymambmempndnenkntonpssasespssstve
toadbyddesgoilldllmbneninsokolpsrernrysstourwnys
luckcyiskellmpndngrarerkshsttetz
thaianataweaemeneyinisorudugus
tickdedyedereslellltmemsnansntnypsretots
teamarasemenllndnsntrmssstxt
lylennnxonrare
dockdderesgegslellmenensomorperasetetsugvewnze
typepo
yokerkstur
dialcedoedemesetgskellmemsnengntonpsrertscshskve
yagilenkrdrnwn
deadafalanarbtckedemeperfyllmonsntnyskuswy
yearaslllp
dadadedshllelilymemnmpmsnanererkrnrtshtatevevywnysze
dyadedereskene
dualbsckctelesetkelllymbmpnengnknnpeskstty
drabagamawewipopugum
yves
yubakiri
quadayipitiz
iranaqesisksmaon
emilitma
elbakslamsse
endsidosvy
eire
zincon
ekedes
eels
eddyengeitna
egangsos
eachrlrnrprssestsyts
echo
ebbsen
eyederes
examecit
ezra
etch
ewenes
eveneril
wokelfmbngntodofolosrdrerkrmrnve
epic
espy
erasgoicieikisneosrs
rubebsbydedygsinlempngnsntshssstthts
ryan
readalamapardodsedefelidinlymynandnenontstub
raceckftgegsidilinkemompmsndngnkntpepsptreshsptetsulveysze
itchelem
roadamarbebsckdedslellmempofokomotpesasesssythtsutvewewsxy
rhea
ribscacechckcodedsftgagsllmemsndngnkotpepsscsesktetz
beadakamanaratauckdsefeneperesetgslallltlyndntnzrnrtsssttatsvy
weakanarbbbsdsedekephrldllntptrestts
babebychckdegsilitjakekuldlelilklllmndnengnknsrbrdrerkrnrrrsrtseshskssthtsudwlys
wacodeftgegshlilitkelkllltndnengntrdrermrnrprsrtryshspvexyys
blabedewipobocotowueumur
juandddedodygslympnengnknorareryst
boaratbscadedyergshrilisldllltmbndnengnnnyobokomonorosotrergrnsessthutwlwsydys
biasbsdedsenerkelelkllndngninsrdtets
wickdeerfegsldlellltlyndnengnknspereryseshspthtstt
whatenimipitizom
buckdddsffgslblkllmpmsnknsntoyrlrnrprrrtryshssstsyttyszz
joanbsdyelesgshninkeltsetsveys
jigsll
braeaganasatayedewieigimowyn
jeaneperffrksttsws
byrdte
wynn
ooze
onceeslytousyx
omanenit
olafavdyeggain
okay
oilsly
ohio
offs
oddsesinor
obeyoe
oaksrsthts
ivan
stabaganarayemepewiropowubudunyx
oxen
owedeneslsns
ovalenerid
ouchrsstts
otisto
oslo
oralesgyinly
opalecelentsus
vialcedaederesetewlenesatato
citety
chadaoaparatefenewicinipitopouum
coalataxbbcackcodedyedgshnilinkeldleltmbmeneokolonoppepspyrdrerkrnstsytsvewlwszy
cladamanapawayioipodogotubueuj
cabsdyfegeinkelflllmmempnensntpepsrdrerlrprrrsrtseshsksttsve
cedellltntrn
czar
cyst
zoneomosrn
crabagamayeeewibopowuduxuz
cubabebsedesffllltpsrbrdrerlrsrtsptets
vealdaergailinlannntrarbrnrystto
prayepeyimodoposow
pubsffghkelllpmampnsntnypapsrerrshsststt
smogugut
pylere
jabsckdeilkemsnersvawszz
paceckctdsgeidilinirlelllmlolsnengnsntparcrerkrrrsrtsosssttethtsulvewnwsys
peakalarasatckekelepergsltndnhnnnsntrkrusttetsws
phil
picackcteresgskelellmpnengnknsntonpesassthtstttyus
isisle
planayeaodotowoyugumus
hydemn
hubsckeseygeghgollmempmsngnknsntrdrlrtshskts
hickdeghkellltndntpsresstsve
hoaresffgsldlelmlymemoneodofokopotpepipsrnsesturwewlyt
haagasckhnilirlelfllltmsndngnsrdrerkrmrprtshtetsulvewkyszezy
headalaparatbeckedelirldlllmlpmpmsnsrarbrdrerorrrsssws
meadalanateketltmondnsnureshsstatetsws
macechdeidiliminkelelillltmanennnsnypsrcrerkrsrtrxryshsksssttethtsttulwryayoze
utah
moanatbsckdeenhrldlellnankntodonorotpsrernssstthvews
micaceckenkeldlelkllmindneninkntpsraressst
upon
twasiginos
podsemetgokelelklllompndngnyolorpepsrerkrtseshsttsurut
muchckddffgsirlellngseshsksttettzo
ulan
undoitixixto
imps
ugly
tabsckctftgsilkelelkllmengnkospepsrartskssteutxi
myrath
illsly
vailinlenensrysestts
acesheidmeneretats
abbabebyedeletlelyosut
adamdsen
agaredeeeresogue
afar
aidadedsmsnursry
swabamanapatayimum
akin
ajarax
amenesidmookosyl
alanarasbaeceeexfagalymamsoepssoumva
analdyewnaneonsitetitsus
aqua
apedesexse
asiaks
arabchcocseaesgoidmsmypats
auntrato
atomop
awayedlsry
averidisivonow
ayes
axedeleresisleon
icedeson
ibexidis
ideaemlelyol
igor
ifni
niceckghlenaneps
usederes
noahdedselllneokonrarmseteun
nagsgyilirmepsrysashtetourvyzi
nealaratckedffilllonrosssttsvawswtxt
voidltsstews
zulu
nudellmbnsts
franauayedeeeteyogomye
urdugeisnssa
fueljillmendnkrsrysesszz
ionstawa
facectdegsilinirkelkllmengnsrermsttetsunwnze
fearatedelesetllltndrnssud
zealrostus
fiateffegsjilelllmndnenknnnsrermshsksttsve
flagakamapatawaxeaedeeewexipitogopowueux
foalamciesgsgyilldlkndntodolotrdrerkrmrtssulurwl
kahnlinentrlrptetz
incachdodyksnsto
keelenepmpntptrnrrys
kickdselevllndngnkrksstets
spanatecedinitotunur
kochng
kneeewitobotowox
subschckdsedesezitlkmsngnknsrerf
klanux
skewidiminipisitye
siamanckdeftghgnkhlkllloltmsnengnknspsrerstetstuvaze
shameaedinipitodoeopotowunut
soakaparbsckdadsfaftilldlelomengnsnyonotrertulupurwnya
snagapipobowubug
kudohnrdrt
slabamapatavayedewidimipitobopotowugumur
scabanarotowud
sackfegagegsidilkelelkltlzmenandnengnkpsrarishteudulvewsys
sealamanarasatctedekemenepereslfllmindntptrfthtswsxy'''
w=raw_input()
s=[t[2:] for t in d.split() if t[:2]==w[:2]]
print s and w[2:] in [s[0][i:i+2] for i in range(0,len(s[0]),2)]
```
[Answer]
# Word VBA, 25 Bytes
Anonymous VBE immediate window function that takes input as the current selection and outputs if it is a word as boolean to the VBE immediate window.
```
?CheckSpelling(Selection)
```
### Tester Function
The below function was used to test the above function against the testcases. The function failed 9.07 percent of the cases (396 of the actual words and 10 of the fake words)
```
i=0:For Each w In Split(Selection,vbcr):i=i-CheckSpelling(w):Next:?i" were recognized as words
```
[Answer]
## C# WPF, 110 ~~139~~
Shorter
```
bool F(string s){var t=new TextBox();t.SpellCheck.IsEnabled=true;t.Text=s;return t.GetSpellingError(0)==null;}
```
Old answer
```
public bool F(string s){TextBox t=new TextBox();t.SpellCheck.IsEnabled=true;t.Text=s;SpellingError e=t.GetSpellingError(0);return e==null;}
```
[Answer]
# Mathematica, 33 bytes
Hey, somebody had to do it!
```
Length[DictionaryLookup[Input[]]]
```
Self-explanatory.
[Answer]
# [Lexurgy](https://www.lexurgy.com/sc), 106 bytes
Lexurgy, despite the fact it's meant for constructed languages, can be used for natural language processing as well.
Keeps the input if it thinks it's a word, and an empty string if it thinks it's not.
Reimplements @Sp3000's regex, so this **fails at the same rate (660 misclassifications)**.
```
Class V {a,e,i,o,u}
Class F {j,q,x,z}
a propagate:
[]? !@V !@V !@V []?=>*
[]=>*/{_ @F,@F _}
v:
@F=>*
```
Explanation:
```
# Define the classes
Class V {a,e,i,o,u}
Class F {j,q,x,z} # forbidden letters
a propagate: # while the input is changed from last iteration:
[]? !@V !@V !@V []?=>* # remove `[^aeiou]{3}`
[]=>*/{_ @F,@F _} # remove any letters next to the forbidden ones
v: # then:
@F=>* # remove the forbidden letters
```
[Answer]
# Javascript ES6, 32 bytes:
Using the regex from [@Sp3000 answer](https://codegolf.stackexchange.com/a/45300/14732):
```
s=>!/[^aeiou]{3}|[jqxz]/.test(s)
```
This creates an anonymous function. To use it, you simply wrap it around `()`.
Example:
```
(s=>!/[^aeiou]{3}|[jqxz]/.test(s))('word')
```
This has **exactly** the same fail rate as @Sp3000, and returns `true` or `false` accordingly.
All credits due to @Sp3000 for letting me use his regex.
] |
[Question]
[
# Context
At Hogwarts School of Witchcraft and Wizardry, students are sorted into 4 houses, `Gryffindor`, `Ravenclaw`, `Slytherin` and `Hufflepuff`. This sorting is done by a magical hat, called the Sorting Hat.
# Task
Your task is to code a sorting hat. In other words, you should create some deterministic rule that, given the name of a person, outputs one of the four available houses. (See the **output** section for a restriction on the rule)
# Input
Input will be a string (representing the student name) in the ascii range `[32, 126]`, the printable characters.
This is *not necessarily* an English name. The input may be "@\_??" and your code should still assign a house.
# Output
For a fixed string (any string of printable ASCII characters), your code should always output the same house, thus your code should be deterministic. The output has to uniquely identify the houses, in any of the following ways:
* returning the full house name, e.g. `"Gryffindor"` (capitalization doesn't matter)
* returning the house initial, e.g. `"G"` (capitalization doesn't matter)
* returning the house index, e.g. `0` (you may use any house ordering as long as the indexing is done with `0, 1, 2, 3` or `1, 2, 3, 4` and as long as you specify it in your answer.)
What is more, there are 12 cases that should be as follows:
* the inputs `harry`, `hermione` and `ron` should return `gryffindor`;
* the inputs `luna`, `cho` and `penelope` should return `ravenclaw`;
* the inputs `draco`, `crab` and `goyle` should return `slytherin`;
* the inputs `cedric`, `ernie` and `hannah` should return `hufflepuff`;
You can either get these 12 inputs as stated, or the 12 inputs where the first letter is upper case (e.g. `Harry`).
You should also prove that there are other English names in [this list](https://babynames.net/all/english) that get mapped into each house.
Be sure to include the house that your code assigns to your own codegolf.SE nickname, plus the house `rgs` or `RGS` gets assigned to. Bonus imaginary internet points if I get assigned to `Ravenclaw`!!!
As of now, these answers qualify for the bonus imaginary internet points:
[G B Ruby answer](https://codegolf.stackexchange.com/a/199683/75323), [ovs Python answer](https://codegolf.stackexchange.com/a/199683/92069), [Kevin Cruijssen Whitespace answer](https://codegolf.stackexchange.com/a/199688/75323), [Jonathan Allan Jelly answer](https://codegolf.stackexchange.com/a/199725/75323), [Nick Kennedy Jelly answer](https://codegolf.stackexchange.com/a/199695/75323), [Kaddath PHP answer](https://codegolf.stackexchange.com/a/199710/75323), [Noodle9 C answer](https://codegolf.stackexchange.com/a/199729/75323), [640KB x86-16 answer](https://codegolf.stackexchange.com/a/199734/75323), [Guillermo Phillips PHP answer](https://codegolf.stackexchange.com/a/199741/75323), [Jonathan Alan Python 2 answer](https://codegolf.stackexchange.com/a/199746/75323), [Bob Jarvis - Reinstate Monica Clojure answer](https://codegolf.stackexchange.com/a/199910/75323), [Mitchell Spector Bash answer](https://codegolf.stackexchange.com/a/199948/75323).
# Test cases
```
"Harry" -> "Gryffindor"
"Hermione" -> "Gryffindor"
"Ron" -> "Gryffindor"
"Luna" -> "Ravenclaw"
"Cho" -> "Ravenclaw"
"Penelope" -> "Ravenclaw"
"Draco" -> "Slytherin"
"Crab" -> "Slytherin"
"Goyle" -> "Slytherin"
"Cedric" -> "Hufflepuff"
"Hannah" -> "Hufflepuff"
"Ernie" -> "Hufflepuff"
```
---
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest submission in bytes, wins! If you liked this challenge, consider upvoting it... And happy golfing!
[Answer]
# [Python 2](https://docs.python.org/2/), 30 bytes
Input is lower case name, output is `1` for Gryffindor, `0` for Ravenclaw, `2` for Slytherin and `3` for Hufflepuff.
```
lambda n:hash(n)%94%69%45%17%4
```
[Try it online!](https://tio.run/##HY6xDsIwDER3vsJLlFbqAiqgVmJmh5XFTV0SKXUiU4Z@fcCZ3tPdDZf3zSc@leX2KhHXaUbg0ePHN9yaoTeXwfRnc7yavixJgHElCAzWo8huu7@QrCExqUtiRfwyKp1PikxMMeW6mAVdDZ3gpHynPdbG0SzBqZFwqJFHZvRqj/vTjgeALIG3eqKDpVG25Qc "Python 2 – Try It Online")
`RGS` is in Ravenclaw.
---
# [Python 2](https://docs.python.org/2/), 34 bytes
Takes names in lower case and outputs upper case house initials.
```
lambda n:'HSHHSRRG'[hash(n)%189%8]
```
[Try it online!](https://tio.run/##HY2xDoMwDET3fkUWFJBY2okidS4zjG0HE0wdKTiRSwe@Pq0zvae7ky4dO0W@5PX2zAG2eQHDvR2mYZjG8W4fBB@quanO3bXqXnmNYhg2NJ6NJRA5bPsXlM1HRnWJrAhfBqWjqEjIGGIqi0XAldAJzMp3PEJpHC7inRoK@xIRMAPZ/mRMEs97eW/NWiub/AM "Python 2 – Try It Online")
---
# [Python 2](https://docs.python.org/2/), 34 bytes
Input with first letter in upper case, output is the house indices.
```
lambda n:~hash(n)%74%64%27%16%11%4
```
[Try it online!](https://tio.run/##Hc6xCoNADAbgvU@R5VDBRREFoZMtdSi0dO4S9ewdaE6iLbj01a/NTd/PnxCy7JtxlPvx@PQTzt2AQPXX4GpiSlRVqLJQeaWyUmWZKvzoGAhnDZYgapF5j9J/0DxbR1ryw5FwfROKjXHCXZOe3BI2Tox9KBvGTry4fQqTRg9se0lnJhuqFonQhMOvVbh91qg@ACxsaQu/pDDGYuJ/ "Python 2 – Try It Online")
`Rgs` gets assigned to Ravenclaw, `Ovs` to Gryffindor.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 35 bytes
Expects the names in title case. Returns \$0\$ for Gryffindor, \$1\$ for Hufflepuff, \$2\$ for Slytherin or \$3\$ for Ravenclaw.
```
s=>(([a]=Buffer(s))[3]*9|a*553)%9&3
```
[Try it online!](https://tio.run/##jZFNS8NAEIbv/oplQEkq2kPooYcIfpEePEh6rD2MyaxZWWfDpKkE/O8xqGDdJTWXOT3z8sy8r7jHphBT7y7YldTrtG/Sqyja4Da9abUmiZo43iTb2fIDZ4tFEp8uz5K@cNw4S5fWvUQ6ghWKdKCUipX6mvO5gkw6rQ2XTuDE50nejGOCiXzuGL7Jc3hi@Jd/aBlBeT457okLi@8Bflu5n/hJ@CMxWVcP9gc24/idYOH856xtt6tIDIcygs@B@zieuc4SeK85kk6lmAL@pq@Goi3VwwybQmasRnkfvxc2gc1hvL9wLYytLWGqT56tw6p@z@0/AQ "JavaScript (Node.js) – Try It Online")
---
# JavaScript (ES6), 40 bytes
Returns the house initial in upper case.
```
s=>"SSHGRHGR"[parseInt(s,28)*51%78%10&7]
```
[Try it online!](https://tio.run/##jZFNS8RADIbv/oohsNL1a11Bdi8riEoreJD2qB5im7EjY6ak7Up/fS0quM5QLYScnrw8SV5xi3UupmqO2RXU601fby4gy5I4HQoeKpSabrmJ6qOz9fzgfDlbrWfL0/3VU587rp2lE@teIh1BgiIdKKXmSn32xUJBLJ3WhgsnsOfzJG/GMcFEPnUMX@QhPDL8y9@1jKA8nxS3xLnF9wC/Kt13/CT8npisqwb7HZtx/Fowd/5xMts1JYnhUEbwOXAfx2PXWQLvNH@kUyEmh9/pSau1pWro4aeQGctR3sdvhE1gsxvvD1wKY2sLmOqTxln4qp91@w8 "JavaScript (Node.js) – Try It Online")
### How?
The base formula that maps our 12 wizard students to the relevant houses is:
```
"SSHGRHGRS?"[parseInt(s, 28) * 51 % 78 % 10]
```
We first parse the input as Base-28. Valid input strings in this base must consist of an optional leading unary operator (`+` or `-`), followed by a sequence of characters matching `[0-9A-Ra-r]+`. If the whole string is invalid, it is parsed as \$NaN\$. Otherwise, the parsing stops just before the first invalid character.
*Example:*
```
parseInt("harry", 28) == parseInt("harr", 28) // -> 381807
```
There are, obviously, countless ways of building the hash formula and the corresponding lookup table \$t\$.
Among all brute-forced formulas, this one was chosen because:
* \$t[8]=t[0]\$ and we don't care about the value of \$t[9]\$, which means that we can apply a final modulo \$8\$ to get 8 entries.
* This modulo \$8\$ can be turned into a bitwise AND with \$7\$, which also guarantees that the index will be forced into \$[0..7]\$ even if the input string is parsed as \$NaN\$ or a negative value.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~11~~ 8 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
Updated 8-byter so that the bonus is fulfilled for ***both*** `'rgs'` ***and*** `'RGS'` :)
```
“EwS’,4ḥ
```
A monadic Link accepting a list of characters which yields:
```
4: Gryffindor
2: Ravenclaw
1: Slytherin
3: Hufflepuff
```
**[Try it online!](https://tio.run/##y0rNyan8//9RwxzX8uBHDTN1TB7uWPr//3/1ovw8dQA "Jelly – Try It Online")**
Or see a **[test-suite](https://tio.run/##JYwxDsIwDEWv0i1LR66A2OlYdTCJ1QRMUrmgKlvFwhmQWNk4ADsnIRcJdSpZel/f//8jEsWc0/zcTk2aH/Xm93nl7z3d3svl3CoLzFHVlbLIZxc8iubgBWCMGxfZ1VWr6OpBTG2DYECPFIYSB31CJiwz3I@C/a5Za4ZBl4JmOAj7EGltkZkgrimNhp0WF9m78rbgPdgSxItFYjSq@wM "Jelly – Try It Online")** showing the 3 given names belonging to each house, that an extra name exists in the linked name-list for each house and that both `'rgs'` and `'RGS'` are in `2`, Ravenclaw.
Places `'Jonathan Allan'` in Ravenclaw.
### How?
```
“¢Ʋ⁹’,4ḥ - Link: list of characters
“EwS’ - base 250 number = 4405084
4 - 4
, - pair
ḥ - hash using:
4405084 as a salt, and
implicit range(4) = [1,2,3,4] as the domain
```
---
# 11-byter:
```
OP%⁽MJ%23%4
```
A monadic Link accepting a list of characters which yields:
```
3: Gryffindor
2: Ravenclaw
1: Slytherin
0: Hufflepuff
```
(Bonus fulfilled for `'rgs'`)
**[Try it online!](https://tio.run/##y0rNyan8/98/QPVR415fL1UjY1WT////qxelF6sDAA "Jelly – Try It Online")**
Or see a **[test-suite](https://tio.run/##LcwxDsIwDAXQq3SpsnQCToGEYK86mMRqAq5TuTBkhIXLcAUmbtKLhLpBsvStr2dfkCjlfDzV8@Nz2Nebbb3L39f8fC@Tc2s8iCTTVMajDCEy6i6RNcBeUSiZrqlaQ3cGLa2PGiMyUhyxuFs5kH4q2AnYlVmBs2YfExXrYAAJf2fRSbDao3BYgQdm8IW6MC2Pux8 "Jelly – Try It Online")** showing the 3 given names belonging to each house, that an extra name exists in the linked name-list for each house and that `'rgs'` is in `2`, Ravenclaw.
Places `'Jonathan Allan'` in Slytherin.
### How?
```
OP%⁽MJ%23%4 - Link: list of characters e.g. 'rgs'
O - ordinals [114,103,115]
P - product 114 * 103 * 115 = 1350330
⁽MJ - 20325 20325
% - modulo 1350330 % 20325 = 8880
23 - 23 23
% - modulo 8880 % 23 = 2
4 - 4 4
% - modulo 2 % 4 = 2
```
Here is a Python script which will print viable `i j {G} {R} {S} {H}` results for code like `OP%i%j%4` for which each of `i` and `j` are small enough to write within three bytes. The first result happens to place `'rgs'` in Ravenclaw.
```
from functools import reduce
a,b,c,d = (['harry', 'hermione', 'ron'], ['luna', 'cho', 'penelope'], ['draco', 'crab', 'goyle'], ['cedric', 'ernie', 'hannah'])
pa,pb,pc,pd = ([reduce(lambda x,y:x*y, map(ord,n)) for n in v] for v in (a,b,c,d))
for j in range(5, 32251):
for i in range(j, 32251):
i+=1
A=set(v%i%j%4 for v in pa)
B=set(v%i%j%4 for v in pb)
if A&B: continue
C=set(v%i%j%4 for v in pc)
if A&C or B&C: continue
D=set(v%i%j%4 for v in pd)
if A&D or B&D or C&D: continue
print(i, j, A, B, C, D)
break
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~30~~ 31 bytes
```
->x{"HSSRGRHHGRR"[x.sum%91%11]}
```
[Try it online!](https://tio.run/##Dc0xCoNAEAXQq3wEu0SwTJE0JuwWFmEtF4vRjCjorEyQrGjObvIu8HRp1qO7Hudb3BJbVc44a41ziY/Ze5nSS57mef090o@3pLrCsk5DEIYLgnIRQtEHPFl4DDPjrtQGFEoNTFhHRsEvHVo8VAaGJRHq4UxVZxPN2x73GT6eOh/rf/ID "Ruby – Try It Online")
Returns initial of house. RGS is on Ravenclaw
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~14~~ 12 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
•Sâ;»•4вs1öè
```
Outputs `0123` instead of `GRSH`.
-2 bytes thanks to *@Grimmy* (unfortunately it no longer got the internet bonus for outputting Ravenclaw for `RGS`).
[Try it online.](https://tio.run/##DcsxCsJAEAXQ/t9GtLNzlSxoIeYEs3EgC3FGJigEFDxLKmtRGzu3F8/gRdZ0r3naUoicT59H/l36MvXT92vA5HtrR@mZrvk8TvfsyayDZ9tFFcZGBauDEFytWLNwo3vG3KhSOKOAQruG4XhrsYInEaqxMIlDLUos@RgFMw1/)
**Explanation:**
```
•Sâ;»• # Push compressed integer 478937616
4в # Convert it to base-4 as list: [1,3,0,2,0,3,0,0,0,0,2,0,1,0,0]
s1ö # Take the input, and convert it from base-1 to a base-10 integer
# which will essentially sum the indices of the characters in the string "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzǝʒαβγδεζηθвимнт\nΓΔΘιΣΩ≠∊∍∞₁₂₃₄₅₆ !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~Ƶ€Λ‚ƒ„…†‡ˆ‰Š‹ŒĆŽƶĀ‘’“”–—˜™š›œćžŸā¡¢£¤¥¦§¨©ª«¬λ®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ"
è # And use that to (modular) index into the earlier created list
# (after which the result is output implicitly)
```
[See this 05AB1E tip of mine (sections *How to compress large integers?* and *How to compress integer lists?*)](https://codegolf.stackexchange.com/questions/96361/tips-for-golfing-in-05ab1e) to understand why `•Sâ;»•` is `478937616` and `•Sâ;»•4в` is `[1,3,0,2,0,3,0,0,0,0,2,0,1,0,0]`.
[Answer]
# [Python 2](https://docs.python.org/2/), 24 bytes
```
lambda n:hash(n)/64779%4
```
```
3: Gryffindor
0: Ravenclaw
2: Slytherin
1: Hufflepuff
```
Bonus fulfilled for `'rgs'` while `'Jonathan Allan'` is placed in Slytherin.
**[Try it online!](https://tio.run/##Pc9NCsJADAXgvafIRtqCIIgoCp5EXcSZ1AxOk5LqoqevzfizemHyBeb145NVNlN7ukwZu1tEkCPjwLU06912vz8st1OrBqyvgSAJ1AuAumI0G6sVVEzWJRXy2VQ8MDzIMo1Vsyo2vwT9PbB69CSUtS8XGDW35fQ@/Hg0DAUGw5vnXcf81dihpb8MFC0F35BJKoRRBPmDYxrmD822Oc4coLckTzi3tWBHDXgrn7xUaXed3g "Python 2 – Try It Online")**
[Answer]
# x86-16 machine code, IBM PC DOS, ~~37~~ ~~32~~ 30 bytes
**Binary:**
```
00000000: 92be 8200 ad8a e0ac b3be f7f3 92d4 08bb ................
00000010: 1601 d7cd 29c3 4853 5252 4753 5252 ....).HSRRGSRR
```
Build `HAT.COM` from above using `xxd -r`.
**Unassembled listing:**
```
92 XCHG AX, DX ; DX = 0
BE 0082 MOV SI, 82H ; SI to input string (char*s)
AD LODSW ; AL = s[0], SI = SI + 2
8A E0 MOV AH, AL ; AH = s[0]
AC LODSB ; AL = s[2]
B3 BE MOV BL, 190 ; divisor = 190
F7 F3 DIV BX ; DX = AX % 190
92 XCHG AX, DX ; AX = DX
D4 08 AAM 8 ; AL = AL % 8
BB 011D MOV BX, OFFSET S ; BX = output string table
D7 XLAT ; AL = [BX][AL]
CD 29 INT 29H ; DOS fast console output
C3 RET ; return to DOS
S DB "HSRRGSRR" ; house char table
```
A standalone PC DOS executable. Input via command line, output to console is the house initial `{"G","R","S","H"}`.
All credit goes to @Noodle9, as this is really just a port of [that answer](https://codegolf.stackexchange.com/a/199729/84624). I promise to try harder next time.
**I/O:**
[![enter image description here](https://i.stack.imgur.com/JnOiw.png)](https://i.stack.imgur.com/JnOiw.png)
[![enter image description here](https://i.stack.imgur.com/AWPn3.png)](https://i.stack.imgur.com/AWPn3.png)
[Answer]
# [Python 2](https://docs.python.org/2/), 25 bytes
```
lambda n:hash(n)%814329%4
```
[Try it online!](https://tio.run/##HY6xDoMwDET3foUXBEgspQwtUmf2du1iQqgjBTty6cDXp3Wm93R3w6VjJ@E@r/dXjrjNCwKPhB9quK2u5@HS36ohr6LAuHkIDDWh6lF3f/G6BWFvrsKG@GU0OhJD8uyjpLJYFF0JneJsfMsRS@P8osGZeeVQIkJmJLPH9KzHE0DSwHs50cHaGNv8Aw "Python 2 – Try It Online")
Firstly, forgive me for mostly ripping off ovs's answer but this is my first ever golf "putt", so I'm taking it for posting practice!
2: Gryffindor
3: Ravenclaw
1: Slytherin
0: Hufflepuff
RGS -> Slytherin and Belly Buster -> Slytherin!
[Answer]
# [PHP](https://php.net/), ~~36~~ ~~33~~ ~~31~~ 29 bytes
```
<?=467921>>crc32($argn)%20&3;
```
[Try it online!](https://tio.run/##DcyxDgFBEIDhfp5CgVBI2BMiOMXhrlBceIKxJnaTNbOZc8W9vLXd3/xfdDGlw@m43mx3ZlWWVm1hZmPUN88nZjkt9ik1qDpAQ/rxwgR3Ybj1jFA5gZaYgkSCs6IVqBSfUMsQCCp6qbfQIDM6uCj7vNYPqHsfQrZk1LpcPnY/id8sd2lx/QM "PHP – Try It Online")
I'm in danger of turning into a one trick pony.
2=Gryffindor, 1=Ravenclaw, 0=Slytherin, 3=Hufflepuff
I'm in Ravenclaw along with @RGS!
[Answer]
# Python 3.8, 18 bytes
Sharing because it's an amusing solution!
If invoked with the following environment variable `PYTHONHASHSEED=895984` ([apparently this does not have to be counted](https://codegolf.meta.stackexchange.com/questions/14337/command-line-flags-on-front-ends/14339#14339) towards byte length),
```
lambda s:hash(s)%4
```
[Try it online!](https://tio.run/##FY/RS8MwEMb/lXMg6WD64oROKVNwrE8q1hepRdI0aQLZJSSttoz97fXyct93v@OO71oe9fL@9Vm@vZbPVVkdDi9Fvrvf5Vvw86Ad3t3mcCNgpYuaHcOslMHOBbZh5aiUld6SUPfBfyUKy//IV5Y2ZTDImkdPa5qHMBMndjIOJdngkKodkZMI7ah6idI6n6Zd4CIhEXhL0rvZJixkF4wgIwOaBDRH5Dqd62PKcKzYBuicQT7EMfmnn/2eUqjie7H81HYc4oOml7O4vt4utaeQQ6bYebpA72SEwcFZ1yqb1s3liq1BuQATGATfrJZ/ "Bash – Try It Online")
given lowercase input,
* 0 => Gryffindor
* 1 => Hufflepuff
* 2 => Ravenclaw
* 3 => Slytherin
`RGS` (and `rgs`) goes to Ravenclaw, `chinatsu` goes to Gryffindor.
In the range `[0, 895984]` there are 3 good seeds, `139840`, `330811`, and `895984`. Only the latter places `RGS` in Ravenclaw.
[Answer]
## [W](https://github.com/A-ee/w) `d`, ~~19~~ 18 bytes
Port of G B's answer. (RGS is also on Ravenclaw.)
BTW, my name can't be entered in the W interpreter, so I do not belong in any house.
* I forgot that the operator overloading exists, so -1 byte due to the order-free indexing.
```
r#↔X┌3ÇMQyΘf○ºÞΘ☺¬
```
Uncompressed:
```
CJ91m11m"HSSRGR HGRR"[
```
## Explanation
```
C % Convert the input to a list of characters
J % Reduce the list by addition
91m % Modulus by 91
11m"HSSRGR HGRR"[ % Cyclic indexing into the string
```
[Answer]
# [C (clang)](http://clang.llvm.org/), ~~50~~ \$\cdots\$ ~~47~~ 42 bytes
Added a byte to fix a bug kindly pointed out by [RGS](https://codegolf.stackexchange.com/users/75323/rgs).
Saved 2 bytes thanks to [S.S. Anne](https://codegolf.stackexchange.com/users/89298/s-s-anne)!!!
Saved 5 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!!!
```
#define f(s)"HSRRGSRR"[(*s<<8|s[2])%190%8]
```
[Try it online!](https://tio.run/##hZJBi8IwEIXv/oqQpZAsFlxPiuLFXerBg9SjeogxXQN1IlM9yLq/vbZm6tEJBL4J7828wNjUlgZ@6/rj4AoPThSq0nKxzvOsuXKjPqvpdHSvNsOdTr7Gg2S0qz1cxMl4UFr89UR7zti8FUomlUjTmUjsFmRfLgziTfYLtSTUevJW7/DkAziydBXjygNEQwuMdnkFE8VPYtTzY4jiFrgU2ZpSNMBoVw5cGc70z1fFuL7RWMoTkUuPZk/xW2LUWbiVFCgi190d0FvqH5lx/CB4mhCR2wYDYI7d@jy5c6C7XBHEYNL7rx8 "C (clang) – Try It Online")
Inputs a capitalised name string and returns `G`, `H`, `S`, or `R`.
[RGS](https://codegolf.stackexchange.com/users/75323/rgs) is in Ravenclaw!!!
[Answer]
# [Whitespace](https://web.archive.org/web/20150618184706/http://compsoc.dur.ac.uk/whitespace/tutorial.php), 295 bytes
```
[S S S N
_Push_0][N
S S T T N
_Create_Label_LOOP][S N
S _Dupe][S N
S _Dupe][T N
T S _Read_STDIN_as_character][T T T _Retrieve_input][S N
S _Dupe_input][S S S T S T S N
_Push_10][T S S T _Subtract][N
T S T S N
_If_0_Jump_to_Label_DONE][T S S S _Add][N
S N
T T N
_Jump_to_Label_LOOP][N
S S T S N
_Create_Label_DONE][S N
N
_Discard][S S S T S T T S T T N
_Push_91][T S T T _Modulo][S S S T S T T N
_Push_11][T S T T _Modulo][S N
S _Dupe][N
T S S S N
_If_0_Jump_to_Label_HUFFELPUFF][S S S T N
_Push_1][T S S T _Subtract][S N
S _Dupe][N
T S T N
_If_0_Jump_to_Label_SLYTHERIN][S S S T N
_Push_1][T S S T _Subtract][S N
S _Dupe][N
T S T N
_If_0_Jump_to_Label_SLYTHERIN][S S S T N
_Push_1][T S S T _Subtract][S N
S _Dupe][N
T S N
_If_0_Jump_to_Label_RAVENCLAW][S S S T N
_Push_1][T S S T _Subtract][S N
S _Dupe][N
T S S N
_If_0_Jump_to_Label_GRYFFINDOR][S S S T N
_Push_1][T S S T _Subtract][S N
S _Dupe][N
T S N
_If_0_Jump_to_Label_RAVENCLAW][S S S T N
_Push_1][T S S T _Subtract][S N
S _Dupe][N
T S N
_If_0_Jump_to_Label_RAVENCLAW][S S S T N
_Push_1][T S S T _Subtract][S N
S _Dupe][N
T S S S N
_If_0_Jump_to_Label_HUFFELPUFF][S S S T N
_Push_1][T S S T _Subtract][S N
S _Dupe][N
T S S N
_If_0_Jump_to_Label_GRYFFINDOR][N
S S N
_Create_Label_RAVENCLAW][S S S T N
_Push_1][T N
S T _Print_as_integer][N
N
N
_Exit_Program][N
S S S N
_Create_Label_GRYFFINDOR][T N
S T _Print_as_integer][N
N
N
_Exit_Program][N
S S T N
_Create_Label_SLYTHERIN][S S S T S N
_Push_2][T N
S T _Print_as_integer][N
N
N
_Exit_Program][N
S S S S N
_Create_Label_HUFFELPUFF][S S S T T N
_Push_3][T N
S T _Print_as_integer]
```
Letters `S` (space), `T` (tab), and `N` (new-line) added as highlighting only.
`[..._some_action]` added as explanation only.
Port of [*@GB*'s Ruby answer](https://codegolf.stackexchange.com/a/199683/52210).
Since Whitespace inputs one character at a time, the input should contain a trailing newline (`\n`) so it knows when to stop reading characters and the input is done.
[Try it online](https://tio.run/##hY9RCoAwDEO/m1PkNv7rCUQG@icoePyuXacMFcYGSx5J6a51O9Oxz0tSJQmQIqA9oEDMiBujdswHLMo4LOsNl4iQ39KrNjTuRgxgJdIFb89e4FP4GYEH@idRVm90LNGSmo@C6jhMyA) (with raw spaces, tabs and new-lines only).
**Explanation in pseudo-code:**
```
Integer sum = 0
Start LOOP:
Integer c = STDIN as character
If(c == '\n'):
Jump to Label DONE
sum = sum + c
Go to next iteration of LOOP
Label DONE:
sum = sum modulo-91
sum = sum modulo-11
If(sum == 0): Jump to Label HUFFELPUFF
If(sum-1 == 0): Jump to Label SLYTHERIN
If(sum-2 == 0): Jump to Label SLYTHERIN
If(sum-3 == 0): Jump to Label RAVENCLAW
If(sum-4 == 0): Jump to Label GRYFFINDOR
If(sum-5 == 0): Jump to Label RAVENCLAW
If(sum-6 == 0): Jump to Label RAVENCLAW
If(sum-7 == 0): Jump to Label HUFFELPUFF
If(sum-8 == 0): Jump to Label GRYFFINDOR
Label RAVENCLAW:
Integer n = 1
Print n as integer to STDOUT
Exit program
Label GRYFFINDOR:
Print top (sum-4 or sum-8) as integer to STDOUT
Exit program
Label SLYTHERIN:
Integer n = 2
Print n as integer to STDOUT
Exit program
Label HUFFELPUFF:
Integer n = 3
Print n as integer to STDOUT
```
[Answer]
# [Zsh](https://www.zsh.org/), 66 bytes
```
case $1 in ?ra*|g*)<<<S;;[lp]*|cho)<<<R;;h?r*|r*)<<<G;;*)<<<H;esac
```
[Try it online!](https://tio.run/##bY8xb8IwEIV3/4qTm4okUgc6YlqGtiJDhxZGhCqTnGtLxo4uUJQCvz21Q7fkBlv@3nt3vt9GdyrN0q6UDUIyBeNgQTK/fOfZfD5fC7Gx9Ta/lNrH90oIvaD8Qr26FKK/C4GNLLuMhTppYxEIZQXWOBRQeVCewMk9whdofwxzwpDknH5myfkpmq7XaGOsJuMOCib3j9NmAjzpM02I2Ap24Xd9eDPdzjhToUGUZ/YKoe7A@hNSXIKxyt/mOux4IYlaDg/PwJfUKmVc5YkzXiDtTXCMSCvvRuj70ckbXskfdKWVp0BftB/CD3RofY1D5ZVk@R9Y2/agMSwcu5DcDenStxZHzFiRKW@8OCplsQ5nXEk6J/WI8EbO4JD/AQ "Zsh – Try It Online")
No hash functions available, so we make do with pattern matching in
a single case statement:
```
case $1 in
?ra*|g*) <<< S ;;
[lp]*|cho) <<< R ;;
h?r*|r*) <<< G ;;
*) <<< H # last branch doesn't need ;;
esac
```
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 36 bytes
```
\B(u|h|p|ra|oy|nn|edr|rni)
$.&$*
3`1
```
[Try it online!](https://tio.run/##DcxBCsJADAXQ/T9HlepCEG/gKO1CRFy7aKzBGRiTEu1iIHcf@w7wjH9JqK7abqiPYzt79MmNXIuLOL/MTdIGzW7dbHEY9rX2ZFbQs32SCuOugssshBAVNxbOOjFORqMiGD3RacmMsFRpRE8iFHFeUsaVU4a9v38 "Retina 0.8.2 – Try It Online") Link includes test suite. Outputs the house index. `Neil` and `rgs` both map to index `0`. Explanation:
```
\B(u|h|p|ra|oy|nn|edr|rni)
$.&$*
```
Replace each of the scoring letters with `1`s. The `\B` means that the first letter never counts as a scoring letter, allowing it to be upper or lower case.
```
3`1
```
Count the number of scoring letters, up to 3.
[Answer]
# [PHP](https://php.net/), 43 bytes
```
<?='RSHGGGHSHRSGRRSGHHRS'[crc32($argn)%20];
```
[Try it online!](https://tio.run/##jVFNTwIxEL33VwwbTCUBYvDGZwzq9uCB7B6Bw9AtdOPaNt2CEuNfd22rEhMTwmE70@6b9@blGWmaZjyb0CxnaZqynGV5mvmP@YYuueW3g@s22p3qXA1u1qNmNiVkPDPSEMGlhmSl7qoKONaiHq5UMiJthAksKUNrj7QLlAn7UmolQp9pFcrTXmGoc6lDWQglKm0i4t4ij49zi5tQU32s4p@5KGzJIyMqhTJ0D1aVgq5HhGy1FcilXxWwhvah804AwobnjR2iq34SN/8gJ0/@FoftrobeFGj/LE2A0b9M38Jpfsmsh/3OgnhzFsHoUrkavCXYaCdbrRYMF5H3337PWBTo5CU6P9CTltI@NVM6rLpQ@FwcvKJy4DRsBCCw/XZbCePPk3wTM/3Uxvk866b3@AU "PHP – Try It Online")
I wanted to do something else than a port.. better but maybe I can do better, when I have time. And this time with bonus points! I'm Griffindor without my capital ;) (Hacks not to be Hufflepuff)
Takes input with Capital letter and returns house initial letter (works with any string input actually, but the result will change)
EDIT: changed a not meaningful G to a S for equal representation between G and S
EDIT 2: saved 10 bytes with a longer string, and ran for the double extra points!! Houses are equally reprensented for meaningless values.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 16 bytes
```
OḄ%19ị“®5ƭ{~’ḃ4¤
```
[Try it online!](https://tio.run/##y0rNyan8/9//4Y4WVUPLh7u7HzXMObTO9Nja6rpHDTMf7mg2ObTk/9E9h9uzHjWtAcop6NopPGqYG/n/v5JHYlFRpZKOkkdqUW5mfl4qkBmUnwckfUrzEoGUc0Y@kAxIzUvNyS8AyboUJSaDhJyLEpOAlHt@ZQ5I2Dk1pSgzGWRQYl5eYgaQ4VqUlwmSKUovVgIA "Jelly – Try It Online")
A monadic link taking a string or list of strings and returning a 1-indexed number corresponding to Gryffindor, Ravenclaw, Slytherin, Hufflepuff.
"rgs" gets sorted into Ravenclaw.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 28 bytes
```
->n{296887>>n.sum%20%11*2&3}
```
[Try it online!](https://tio.run/##JU09C4JQFN39FfLAhjBJgz4GXSx0aAgdxeFa13yg98k1BbF@u@FzOudwvrgvxrn0511Ak3c5ns@nICCn6xvL21uuu/U2h98MfiZiYB6FbRoiRm6kItQiUSRsQ9x7Aq3DSml8IGGtWlzMK8NTLSRkKLQbqbFe@yG@WD7XXSCCasndmKRu8rtbIIlSfYID1mYiB2Qz/YjcAKeBdvrKb2uWmcx/xvwH "Ruby – Try It Online")
Returns `2310` instead of `GRSH`. RGS is on `1=S`, I am on `2=G`.
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~23~~ 24 bytesSBCS
```
'GSGHSSRRH'⊃⍨9|15|19|⍋⊥⍒
```
[Try it online!](https://tio.run/##JY3BasJAEIbvPkVE6UohUFEPuRV6MJ4KWV9gs1mzKetuGPEQyE3wEFnRQh@h4K2XPoGPMi8SZ/Hy//98M8MvahMXjTCu7PH8s/rE4@WtZ0u@TDnPspRhd0B/S9rpop0mLfoTdr/ov/sNHaI/P3@6w/1vhscrTTz7IF2nK95v7rdoHs3Q/zMtABoWMa1gWzmrKIKzpGZvBZnUjrRWVhlXh20BQgYkQeRkpWtMwFIVUEkKCmwVgBbWCs0GcRwPQh@Dckc43@e5UUDpy@nQEw3fJ68v49GYPQA "APL (Dyalog Unicode) – Try It Online")
Some number digging magic using three functions unique to APL:
* Grade up `⍋X`: Indices to reorder the array X into ascending order
* Mixed base `X⊥Y`: Convert array Y from base X to integer
* Grade down `⍒X`: Indices to reorder the array X into descending order
~~Interestingly, modulo 15 doesn't guarantee successful indexing into a length-10 list, yet both `rgs` and `bubbler` fit into the list nicely.~~ I missed the input range, so I added `9|` in the modulo chain to fix it at the cost of 1 byte. `rgs` goes to Slytherin; I go to Hufflepuff.
[Answer]
# Clojure - 186 bytes
Since everyone else seems to have settled on somewhat similar algorithms I boldly went where no one wanted to go before (that I noticed)!
Takes the string, converts it to individual characters, sums up the character values. Has precomputed special cases for the desired assignments. For all other names takes the character sum, mod 4, to get a number in [0..3]. 0 = Gryffindor, 1 = Ravenclaw, 2 = Slytherin, 3 = Hufflepuff.
**Golfed version**
`(defn s[m](let[n(apply + (map int (into [] (clojure.string/upper-case m))))p {390 0,599 0,239 0,1973 0,304 1,218 1,600 1,361 2,280 2,384 2,426 3,430 3,371 3,236 1}](or (p n) (mod n 4))))`
**Ungolfed version**
Adds precomputed values for other versions of the character's names (e.g. accepts "Harry", "Harry Potter", and "Potter" for The Boy Who Lived, and so on), and also returns the full house name instead of a number:
```
(defn sorting-hat [name]
(let [ n (apply + (map int (into [] (clojure.string/upper-case name))))
houses [ "Gryffindor" "Ravenclaw" "Slytherin" "Hufflepuff" ]
name-map { 390 0, 900 0, 478 0, 599 0, 1149 0, 518 0, 239 0, 809 0, 1018 0, 538 0, 1973 0,
304 1, 943 1, 218 1, 603 1, 600 1, 1378 1,
361 2, 849 2, 456 2, 280 2, 415 2, 982 2, 384 2, 959 2,
426 3, 991 3, 430 3, 906 3, 371 3, 1057 3, 236 1 }
house (name-map n) ; house derived from special cases
house2 (mod n 4)]
(houses (or house house2))))
```
Test harness:
```
(doseq [ person ["Harry" "Hermione" "Ron"
"Luna" "Cho" "Penelope"
"Draco" "Crab" "Goyle"
"Cedric" "Hannah" "Ernie"
"RGS" ; poster's codegolf nickname
"Bob Jarvis - Reinstate Monica" ; my codegolf nickname
"Ackerley" "Ealasaid" "Icarus" "Mabel" "Qing" "Ulbrecht" "Yardley"] ] ; other names
(println person " -> "(s person)))
```
Test results (using golfed version):
```
Harry -> 0
Hermione -> 0
Ron -> 0
Luna -> 1
Cho -> 1
Penelope -> 1
Draco -> 2
Crab -> 2
Goyle -> 2
Cedric -> 3
Hannah -> 3
Ernie -> 3
RGS -> 1
Bob Jarvis - Reinstate Monica -> 0
Ackerley -> 0
Ealasaid -> 0
Icarus -> 3
Mabel -> 1
Qing -> 3
Ulbrecht -> 1
Yardley -> 2
```
Note that OP is assigned to Ravenclaw. I'm in Gryffindor.
[Try It Online! (golfed version)](https://tio.run/##jZJPbxMxEMXv@RRPvuCKBHbX2zRRJSQIVQOiUgnigFZ7cLzTZqnXNraDFCE@e5il5USEmMNvxtY8P/8z1n/dRzoeZUd3DqkZWmkpN07qEOwBzyEHHdC7DMnwaFpI8yh6kXLs3f3LfQgUZ0YnwnDGEfBDLQsU0/PlklmpkeXyQnFSRY1yWpUL5rwomGpeoppWi4KpFjWzruZQ01oVTHVRMis1R/mzlT5CBrgz3pTv4FCPdpOJ7Hyib2jA@0jeAY1Y6xgPAhBrikPvHQmIjXdigr9CfNg7LcZitfPiae6WHFkf6KTgbdRm7BSrqLePCnHtD/Z094q62Bv2X2vn9O6301V0/enuzfUngX/EJYJPmeKzBOM7uvf2Dq43D04PdGq9N36L9zp@7xNm2FDvUtaZcONZNJ76EsPh/1Z6bR4oWuJbFVfa6qT7jst3Rsd94uJGb8ly/shfgtNnu41kdpnLLzp2o65FO/r5vKOI0SWxjQz8h7J1f95OYPYKQqanMb/v8fgL)
[Answer]
# [Bash](https://www.gnu.org/software/bash/), 78 bytes (& bonus imaginary Internet points!)
**sortinghat:**
```
o()(printf %d "'${s:$1}")
s=$1
h=HSSGGRSHRHSRGGHHR
echo ${h:(`o`-`o -1`)%13:1}
```
[Try it online!](https://tio.run/##BcE7DoAgDADQnVMQgxEGh8aNxJnOcAHwl7qIARdDPHt9b0mVmLM2@i7n9Ryy32Q3qFatgq8zos4KBM0YgnM@oMfgnUP0Yl8pS9XI6pjjGLMcIZoeJgsfM1Mq5eUf "Bash – Try It Online")
Input is passed as an argument in all lower-case, and output (G, R, S, or H) is on stdout.
---
**Test program:**
```
for x in %GRYFFINDOR-TEST harry hermione ron %RAVENCLAW-TEST luna cho penelope rgs %SLYTHERIN-TEST draco crab goyle %HUFFLEPUFF-TEST cedric ernie hannah %OTHER-SAMPLE-NAMES minerva newton myrtle salazar
do
if test "${x:0:1}" = '%'
then
echo "${x:1}"
else
printf "%12s " "$x"
./sortinghat "$x"
fi
done
```
**Output of test program:**
```
GRYFFINDOR-TEST
harry G
hermione G
ron G
RAVENCLAW-TEST
luna R
cho R
penelope R
rgs R
SLYTHERIN-TEST
draco S
crab S
goyle S
HUFFLEPUFF-TEST
cedric H
ernie H
hannah H
OTHER-SAMPLE-NAMES
minerva G
newton H
myrtle R
salazar S
```
The extra sample names are all in OP's list of names, and I think they're even sorted into the right houses (according to the HP books)! (I get sorted into Gryffindor if you put my name in all lower-case like the others.)
[Answer]
# Clojure - 124 bytes
## Solution
`(defn f[n](if-let[k({:harry 3 :hermione 3 :cho 0 :crab 1 :ernie 2}(keyword(clojure.string/lower-case n)))]k(mod(count n)4)))`
`Gryffindor 3
Rawenclaw 0
Slytherin 1
Hufflepuff 2`
## Explanation
The algorithm takes the modulo 4 length of the name and assigns a house based on that. Exceptions are made for the special cases for the few names that would not get to the predetermined house in this way (Harry, Hermione, Cho, Crab, Ernie).
## Test
```
(deftest a-test
(testing "known-cases"
(is (= 3 (f "Harry")))
(is (= 3 (f "Hermione")))
(is (= 3 (f "Ron")))
(is (= 0 (f "Luna")))
(is (= 0 (f "Cho")))
(is (= 0 (f "Penelope")))
(is (= 1 (f "Draco")))
(is (= 1 (f "Crab")))
(is (= 1 (f "Goyle")))
(is (= 2 (f "Cedric")))
(is (= 2 (f "Hannah")))
(is (= 2 (f "Ernie")))
)
(testing "other-names"
(is (= 0 (f "Ackerley")))
(is (= 1 (f "Acton")))
(is (= 2 (f "Africa")))
(is (= 3 (f "Addison")))
(is (= 3 (f "Attilio")))
(is (= 3 (f "RGS")))
)
)
```
] |
[Question]
[
[Minesweeper](https://en.wikipedia.org/wiki/Minesweeper_(video_game)) is a popular puzzle game where you must discover which tiles are "mines" without clicking on those tiles. Each tile is either a mine (represented by `*`) or a clue, i.e. a number from 0 to 8 representing how many of the 8 neighboring tiles are mines. Your task today is to take a board containing the mines and fill in all of the clues. For example, look at the following 5x4 board, with 5 mines:
```
*
* *
*
*
```
After filling in the clues, the board will look like this:
```
2*211
*33*1
12*32
0112*
```
# Details
You must write either a full-program or a function that takes in a grid of characters containing only spaces and asterisks and outputs another grid where each space is replaced with the number of adjacent mines (asterisks). Any of these are acceptable formats for your grids:
* A string with newlines in it
* A 2D list of characters/single character strings
* A list of strings
You can assume the grid will be *at least* 1x1, although it is possible for it to be all mines or all spaces.
The input grid will always be padded with the appropriate number of spaces. As usual, this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so standard loopholes apply and the shortest answer in bytes wins!
# Sample IO
So that you can see the whitespace, I will show all sample IO with brackets around it.
```
Input:
[ * ]
[* ]
[ ]
[ ]
[ ** ]
[ * * ]
Output:
[1101*1]
[*10111]
[110000]
[012210]
[12**21]
[1*33*1]
Input:
[****]
[****]
Output:
[****]
[****]
Input:
[ ]
[ ]
[ ]
[ ]
Output:
[000]
[000]
[000]
[000]
Input:
[* ]
[** ]
[ ]
[ *]
Ouput:
[*310]
[**10]
[2221]
[001*]
Input:
[** ]
[* *]
[ * ]
[ ]
[* ]
[**** ]
Output:
[**1011]
[*4211*]
[12*111]
[121100]
[*43210]
[****10]
Input:
[ * ]
[ * ]
[ * ]
[** *** ]
[ *** ]
[ ]
[ ** ]
[ * * ]
[* ** ]
[ ** ]
Output:
[00001*1111]
[00002221*1]
[22102*4321]
[**102***31]
[221013***1]
[0000013542]
[0112111**1]
[12*2*12442]
[*212112**2]
[1100002**2]
```
[Answer]
# [MATL](http://github.com/lmendo/MATL), ~~18~~ 17 bytes
*Thanks to [@mbomb007](https://codegolf.stackexchange.com/users/34718/mbomb007) for a correction in the input of test case 6*
```
32>t3Y6Z+-6b(48+c
```
Input is a 2D char array, in the format
```
[' * '; '* * '; ' * '; ' *']
```
[Try it online!](http://matl.tryitonline.net/#code=MzI-dDNZNlorLTZiKDQ4K2M&input=WycgKiAgICc7ICcqICAqICc7ICcgICogICc7ICcgICAgKidd)
Test cases: [1](http://matl.tryitonline.net/#code=MzI-dDNZNlorLTZiKDQ4K2M&input=WycgICAgKiAnOyAnKiAgICAgJzsgJyAgICAgICc7ICcgICAgICAnOyAnICAqKiAgJzsgJyAqICAqICdd),
[2](http://matl.tryitonline.net/#code=MzI-dDNZNlorLTZiKDQ4K2M&input=WycqKionOyAnKioqJzsgJyoqKidd), [3](http://matl.tryitonline.net/#code=MzI-dDNZNlorLTZiKDQ4K2M&input=WycgICAnOyAnICAgJzsgJyAgICdd), [4](http://matl.tryitonline.net/#code=MzI-dDNZNlorLTZiKDQ4K2M&input=WycqICAgJzsgJyoqICAnOyAnICAgICc7ICcgICAqJ10), [5](http://matl.tryitonline.net/#code=MzI-dDNZNlorLTZiKDQ4K2M&input=WycqKiAgICAnOyAnKiAgICAqJzsgJyAgKiAgICc7ICcgICAgICAnOyAnKiAgICAgJzsgJyoqKiogICdd), [6](http://matl.tryitonline.net/#code=MzI-dDNZNlorLTZiKDQ4K2M&input=WycgICAgICogICAgJzsgJyAgICAgICAgKiAnOyAnICAgICAqICAgICc7ICcqKiAgICoqKiAgJzsgJyAgICAgICoqKiAnOyAnICAgICAgICAgICc7ICcgICAgICAgKiogJzsgJyAgKiAqICAgICAnOyAnKiAgICAgICoqICc7ICcgICAgICAgKiogJ10).
### Explanation
```
32> % Input 2D char array implicitly. Transform it into a 2D logical
% array with asterisk replaced by true and space by false
t % Duplicate
3Y6 % Push [1 1 1; 1 0 1; 1 1 1]. This defines the neighbourhood
Z+ % 2D convolution, keeping size. Gives the number of neighbouring
% mines for each position
-6 % Push -6
b % Bubble up in stack
( % Assign -6 to the entries indicated by the logical array, i.e.
% to the positions that originally contained asterisks
48+ % Add 48. This transforms each number of neighbouring mines
% into its ASCII code, and -6 into 42 (ASCII code of asterisk)
c % Convert to char. Display implicitly
```
[Answer]
## JavaScript (ES6), ~~114~~ 96 bytes
```
a=>a.map((s,i)=>s.replace(/ /g,(_,j)=>g(k=>(s=a[i+k])?g(k=>s[j+k]>' '):0)),g=f=>f(-1)+f(0)+f(1))
```
Edit: Saved 18 bytes thanks to an idea by @ETHproductions.
[Answer]
# R, ~~127~~ 112 bytes
```
function(M){a=nrow(M);for(i in seq(M))if(M[i]!="*")M[i]=sum(M[pmax(i+c(-1,1,-a+-1:1,a+-1:1),0)]=="*",na.rm=T);M}
```
thanks to @gtwebb and @sebastian-c for improvements.
Notable points:
Matrices are vectors in R. You don't need 2-D indexing to get elements out.
`seq(M)` will return a sequence of the same "length" (rows x columns) as `M`.
You can't mix positive and negative extraction indices in R. `M[-3]` is legitimate R code, but not what is desired.
Input is in the form of an R matrix. Some examples:
```
> M <- matrix("",5,5)
> M[3,3] <- "*"
> f(M)
[,1] [,2] [,3] [,4] [,5]
[1,] "0" "0" "0" "0" "0"
[2,] "0" "1" "1" "1" "0"
[3,] "0" "1" "*" "1" "0"
[4,] "0" "1" "1" "1" "0"
[5,] "0" "0" "0" "0" "0"
> M[2,2] <- "*"
> f(M)
[,1] [,2] [,3] [,4] [,5]
[1,] "1" "1" "1" "0" "0"
[2,] "1" "*" "2" "1" "0"
[3,] "1" "2" "*" "1" "0"
[4,] "0" "1" "1" "1" "0"
[5,] "0" "0" "0" "0" "0"
> M[3,2] <- "*"
> f(M)
[,1] [,2] [,3] [,4] [,5]
[1,] "1" "1" "1" "0" "0"
[2,] "2" "*" "3" "1" "0"
[3,] "2" "*" "*" "1" "0"
[4,] "1" "2" "2" "1" "0"
[5,] "0" "0" "0" "0" "0"
>
```
[Answer]
## Java, 190 bytes
Edit:
* ***-6** bytes off. Thanks to @Frozn*
* ***-1** byte off. Thanks to myself :)*
* ***-1** byte off. Also spotted some mistakes. Thanks to @Kevin Cruijssen*
Snipet
```
c->{for(int x,y,j,i=-1;++i<c.length;)for(j=-1;++j<c[0].length;){if(c[i][j]<33){c[i][j]=48;for(x=i-2;++x<i+2;)for(y=j-2;++y<j+2;)try{if(c[x][y]==43)c[i][j]++;}catch(Exception e){}}}return c;}
```
Ungolfed:
```
public class Main{
public static char[][] minesweeper(char[][] woclues){
for(int i = 0; i < woclues.length ; i++){
for(int j = 0; j < woclues[0].length ; j++){
if( woclues[i][j] == ' '){
woclues[i][j] = '0';
for(int x = i - 1; x < i + 2 ; x++){
for(int y = j - 1; y < j + 2 ; y++){
try{
if(woclues[x][y] == '*'){
woclues[i][j]++;
}
}catch( ArrayIndexOutOfBoundsException e){}
}
}
}
}
}
return woclues;
}
public static void main(String[]args){
char[][] in = new char[args.length][args[0].length()];
for(int i = 0; i < args.length;i++){
in[i]=args[i].toCharArray();
}
for(char[] c:minesweeper(in)){
System.out.println(new String(c));
}
}
}
```
[Ideone it.](http://ideone.com/sWiNzK)
[Answer]
# JavaScript (ES6), 107
Input/output as an array of strings
```
f=l=>l.map((r,i)=>r.replace(/ /g,(c,j)=>(s=r=>(c+r).substr(j,3).split`*`.length,s(l[i-1])+s(l[i+1])+s(r)-3)))
```
*note* when the function s is called with an element of the list l out of the bounds, the parameter `a` is `undefined` and `c+a` will result in `" undefined"` thanks to the quirky conversion rules of javascript
**More readable**
```
l=>
l.map(
(r,i) =>
r.replace(/ /g, (c,j) =>
(
s = a => (c+a).substr(j,3).split`*`.length,
s(l[i-1])+s(l[i+1])+s(r)-3
)
)
)
```
[Answer]
# Python 2, 138 bytes
```
def f(s):w=s.find('\n')+1;print''.join([c,`(s[i-(i>0):i+2]+(w*' '+s)[i-1:i+2]+s[i-1+w:i+2+w]).count('*')`][c==' ']for i,c in enumerate(s))
```
Defines a function `f` that accepts an input string like
```
" *\n** \n* \n"
```
and prints a string to STDOUT:
```
23*
**2
*31
```
[Answer]
# JavaScript (ES6) ~~186~~ ~~182~~ ~~177~~ ~~161~~ 152 bytes
```
f=a=>{for(s='',y=a[0].length;y--;)for(s=`
`+s,x=a.length;x--;)(k=>{for(t=0,i=9;i--;)t+=(a[x+i%3-1]||[])[y+i/3-1|0]==k;s=(a[x][y]<k?t:k)+s})`*`;return s}
```
# Update
The above code for `" *"` returns `"2*"`. This is fixed in the following script.
# ~~168~~ 167 bytes
```
f=a=>{for(s='',y=a[0].length;y--;)for(s=`
`+s,x=a.length;x--;)a[x][y]=='*'?s='*'+s:(k=>{for(t=0,j=3;j--;)for(i=3;i--;)t+=(a[x+i-1]||1)[y+j-1]=='*';s=t+s})`*`;return s}
```
# [Try it here.](https://jsfiddle.net/0wcx71mo/9)
[Answer]
# Haskell, 115 bytes
```
z=zip[1..]
x%i=[a|(j,a)<-z x,abs(i-j)<2]
f x=[[head$[c|c>' ']++show(sum[1|'*'<-(%j)=<<x%i])|(j,c)<-z r]|(i,r)<-z x]
```
Defines a function `f` on lists of strings
[Answer]
# Python 2, 192 bytes
-3 bytes thanks to Copper, -10 bytes if modifying the input grid is allowed, another -11 bytes by getting rid of `continue` and another -12 bytes for eliminating the counter variable
```
def f(L):
n,S,s=len(L[0]),[0,1,2],[' '];P=[s*(n+2)];K=P+[s+x+s for x in L]+P
for y in range(len(L)):
for x in range(n):
if'*'!=L[y][x]:L[y][x]=`sum(K[y+d][x+e]=='*'for d in S for e in S)`
```
Uses a list of list of characters `L` and creates a padded version `K`, so no problem at boundaries. Indentation is
1. Space
2. Tab
3. Tab+Space
4. Tab+Tab
Usage:
```
s=""" *
* *
*
*"""
print s
s=[[c for c in x] for x in s.split('\n')]
f(s)
s='\n'.join([ ''.join(x) for x in s])
print s
```
[Answer]
# Ruby, 112
Takes and returns a string. String must be newline separated and newline terminated.
```
->s{w=1+s=~/\n/
s.size.times{|i|s[i]==' '&&(n=0;9.times{|j|(s+$/*w)[i+j%3-1+j/3*w-w]==?*&&n+=1};s[i])=n.to_s}
s}
```
**in test program**
```
f=->s{
w=(s=~/\n/)+1 #Calculate width.
s.size.times{|i| #For each char in s
s[i]==' '&&( #If it is a space
n=0 #set counter n to 0 and visit
9.times{|j| #a 3x3 square of chars.
(s+$/*w)[i+j%3-1+j/3*w-w]==?*&&n+=1 #If *, increment n.
} #(Pad s with w newlines to avoid *'s detected by wraparound.)
s[i]=n.to_s #Write n back to s in string format
)
}
s} #Return s.
puts f[
" *
* *
*
*
"]
```
[Answer]
# TSQL ~~292~~ 291 bytes
**Golfed:**
```
DECLARE @ varchar(max)=
' *
* *
*
*';
WITH C as(SELECT x+1i,substring(@,x+1,1)v,x/z r,x%z c FROM master..spt_values CROSS APPLY(SELECT number x,charindex(char(10),@)z)z WHERE type='P'and x<len(@))SELECT @=stuff(@,i,1,z)FROM(SELECT i,(SELECT count(*)FROM C WHERE abs(D.c-c)<2and abs(D.r-r)<2and'*'=v)z FROM C D WHERE''=v)h PRINT @
```
**Ungolfed:**
```
DECLARE @ varchar(max)=
' *
* *
*
*';
WITH C as
(
SELECT x+1i,substring(@,x+1,1)v,x/z r,x%z c
FROM master..spt_values
CROSS APPLY(SELECT number x,charindex(char(10),@)z)z
WHERE type='P'and x<len(@)
)
SELECT @=stuff(@,i,1,z)
FROM
(
SELECT
i,
(
SELECT count(*)
FROM C
WHERE
abs(D.c-c)<2and abs(D.r-r)<2and'*'=v
)z
FROM C D
WHERE''=v
)h
PRINT @
```
**[Fiddle](https://data.stackexchange.com/stackoverflow/query/562144/fill-in-the-minesweeper-clues)**
[Answer]
## Racket 415 bytes
```
(let*((l(string->list s))(g (λ(r c)(if(or(>= r n)(>= c n)(< r 0)(< c 0))#f(list-ref l(+ c(* n r))))))(ng (λ(r c)(let*((h'(-1 0 1))(k(filter(λ(x)x)
(for*/list((i h)(j h)#:unless(= 0 i j))(g(+ r i)(+ c j))))))(count(λ(x)(equal? x #\*))k))))(k(for*/list((i n)(j n))(ng i j)))
(ol(map(λ(x y)(if(equal? x #\*)"*"(number->string y)))l k)))(for((i(* n n))(j ol))(display j)(when(= 0(modulo(add1 i)n))(displayln ""))))
```
Ungolfed:
```
(define (f s n)
(let* ((l (string->list s))
(get ; fn to get value at a (row, col)
(lambda(r c) ; #f if invalid row or col
(if (or (>= r n)
(>= c n)
(< r 0)
(< c 0))
#f (list-ref l (+ c (* n r))))))
(neighbors ; fn to count neighboring "*"
(lambda(r c)
(let* ((h '(-1 0 1))
(u (filter
(lambda(x) x)
(for*/list ((i h)(j h)
#:unless (= 0 i j))
(get (+ r i) (+ c j))))))
(count (lambda(x)(equal? x #\*)) u))))
(k (for*/list ((i n) (j n)) ; for each row,col count neighboring "*"
(neighbors i j)))
(ol(map (lambda(x y) ; get outlist- replace blanks with neighboring star count
(if(equal? x #\*)
"*"
(number->string y)))
l k)))
(for ((i (* n n))(j ol)) ; display outlist
(display j)
(when (= 0 (modulo (add1 i) n))
(displayln "")))))
```
Testing (lists as a single string with column number specified; will also work with spaces):
```
(f "----*-*-------------------**---*--*-" 6)
```
Output:
```
1101*1
*10111
110000
012210
12**21
1*33*1
```
[Answer]
# PHP, ~~145~~ ~~133~~ ~~132~~ 127 bytes
```
for($s=$argv[1];$s[$p];print$c)if(" "==$c=$s[$p++])for($y=-2;$y++<1;)for($x=$p-3;$x++<$p;)$c+="!"<$s[$x+$y*strpos($s,"\n")+$y];
```
takes input as single string, newline separated. Run with `-r`.
**breakdown**
```
for($s=$argv[1];$s[$p]; // loop through all characters (including newlines)
print$c // 3. print result
)
if(" "==$c=$s[$p++]) // 1. if character is space
for($y=-2;$y++<1;) // 2. count surrounding asterisk characters
for($x=$p-3;$x++<$p;)
$c+="!"<$s[$x+$y*strpos($s,"\n")+$y];
```
[Answer]
# [Turtlèd](https://github.com/Destructible-Watermelon/turtl-d/), 99 bytes
(whoops I keep forgetting the link :| )
Takes inputs with brackets around each line
Turtlèd cannot take multi-line input, so after the last line, write `|` to signal end of input
Note the mismatched brackets are because open brackets parse the next char as part of the bracket command
```
[|!.([[]r+.][[l]d)][ u]d[|[]r( #012345678#l(*+)u(*+)r(*+)r(*+)d(*+)d(*+)l(*+)l(*+)ur.)]' [[l]' d]'
```
### [Try it online!](http://turtled.tryitonline.net/#code=W3whLihbW11yKy5dW1tsXWQpXVsgdV1kW3xbXXIoICMwMTIzNDU2NzgjbCgqKyl1KCorKXIoKispcigqKylkKCorKWQoKispbCgqKylsKCorKXVyLildJyBbW2xdJyBkXScg&input=WyAgICAgKiAgICBdClsgICAgICAgICogXQpbICAgICAqICAgIF0KWyoqICAgKioqICBdClsgICAgICAqKiogXQpbICAgICAgICAgIF0KWyAgICAgICAqKiBdClsgICogKiAgICAgXQpbKiAgICAgICoqIF0KWyAgICAgICAqKiBdCnw)
## How it works (general description):
Until `|` is entered, it writes out the input on each line, with brackets to help it recognise the end of each line.
After that has happened, it goes back up to the top of input. It goes through each character in input. If it is a space, it looks around the space, adding one to the counter for each bomb it finds. after each line, it deletes the brackets. When it gets to the last line, with the | in it, it stops, and deletes the |. the grid is implicitly printed.
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 24 bytes
```
{4⌷x←'*'=,⍵:'*'⋄+/x}⌺3 3
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkG/6tNHvVsrwAy1bXUbXUe9W61AjIedbdo61fUPurZZaxg/D8NKPuot@9RV/Oj3jWPerccWm/8qG0i0IjgIGcgGeLhGfw/TQEopK4ABFoK6grqWiAWiKGAhaGlBWFogRVzAY0AWa/OBTFDCwhAJoAodDm4USgkhgkQKZg1cIVaWOyCyoJpLYjr0NwL9wrIRVhsU4B4GlkXNBBQZMBWaSG5CcJD0oNsAExGS0EL1R0KKHpAHC4A "APL (Dyalog Unicode) – Try It Online")
A direct stencil operation.
Input as a character matrix, output as a hybrid matrix.
[Testcase converter](https://tio.run/##K8gs@P9f6VHf1EdtE9TVlfTy9JTSFB61TVTS00gMUo9WVw9SjwUSecWa////j1YAAS0QEcsF4YD5MA5MRgvE0AKRcGUgHpIeZANgMloQ/WADUGXgHAA "Pip – Try It Online")
[Answer]
# [Vyxal 3](https://github.com/Vyxal/Vyxal/tree/version-3), 33 bytes
```
Þȯ1⁾ƛ•C]⁰“⸠'?=Ḟi£⁰“:⸠'?=Ḟ¥Ạf⁰ᵛfM'
```
[Try it Online!](https://vyxal.github.io/latest.html#WyIiLCIiLCLDnsivMeKBvsab4oCiQ13igbDigJziuKAnPz3huJ5pwqPigbDigJw64rigJz894biewqXhuqBm4oGw4bWbZk0nIiwiIiwiW1wiPz8/Pyo/XCIsXCIqPz8/Pz9cIixcIj8/Pz8/P1wiLFwiPz8/Pz8/XCIsXCI/PyoqPz9cIixcIj8qPz8qP1wiXSIsIjMuNC4xIl0=)
takes input with ?s and \*s because the entire parser breaks with leading or trailing spaces on strings, probably golfable but honestly i dont want to do this anymore. Single element lambda glyph does not render as of v3.4.1
```
Þȯ1⁾ƛ•C]⁰“⸠'?=Ḟi£⁰“:⸠'?=Ḟ¥Ạf⁰ᵛfM'­⁡​‎‎⁡⁠⁡‏⁠‎⁡⁠⁢‏⁠‎⁡⁠⁣‏⁠‎⁡⁠⁤‏‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁢⁡‏⁠‎⁡⁠⁢⁢‏⁠‎⁡⁠⁢⁣‏⁠‎⁡⁠⁢⁤‏⁠⁠⁠⁠‏​⁡⁠⁡‌⁣​‎‎⁡⁠⁣⁡‏⁠‎⁡⁠⁣⁢‏⁠‎⁡⁠⁣⁣‏⁠‎⁡⁠⁣⁤‏⁠‎⁡⁠⁤⁡‏⁠‎⁡⁠⁤⁢‏⁠‎⁡⁠⁤⁣‏⁠‎⁡⁠⁤⁤‏⁠‎⁡⁠⁢⁡⁡‏⁠⁠‏​⁡⁠⁡‌⁤​‎‎⁡⁠⁢⁡⁢‏⁠‎⁡⁠⁢⁡⁣‏⁠‎⁡⁠⁢⁡⁤‏⁠‎⁡⁠⁢⁢⁡‏⁠‎⁡⁠⁢⁢⁢‏⁠‎⁡⁠⁢⁢⁣‏⁠‎⁡⁠⁢⁢⁤‏⁠‎⁡⁠⁢⁣⁡‏‏​⁡⁠⁡‌⁢⁡​‎‎⁡⁠⁢⁣⁢‏⁠‎⁡⁠⁢⁣⁣‏⁠‎⁡⁠⁢⁣⁤‏‏​⁡⁠⁡‌⁢⁢​‎‎⁡⁠⁢⁤⁡‏⁠‎⁡⁠⁢⁤⁢‏⁠‎⁡⁠⁢⁤⁣‏⁠‎⁡⁠⁢⁤⁤‏⁠‎⁡⁠⁣⁡⁡‏‏​⁡⁠⁡‌­
Þȯ1⁾ # ‎⁡get the neighboring values for each cell and flatten by one
ƛ•C] # ‎⁢count the number of asterisks in each set of neighbors
⁰“⸠'?=Ḟi£ # ‎⁣get the indices of all the ?s in the original list and store that in the register
⁰“:⸠'?=Ḟ # ‎⁤do it again, but duplicate the joined list so the assign works properly
¥Ạf # ‎⁢⁡pop the register, assign the number of neighboring mines to the corresponding ?
⁰ᵛfM' # ‎⁢⁢Mold to the original shape, formatted properly
üíé
```
Created with the help of [Luminespire](https://vyxal.github.io/Luminespire).
[Answer]
## C, ~~152~~ ~~150~~ ~~147~~ 145 bytes
```
i,j,r,c;f(B,R,C)char**B;{for(i=R*C;i--;)for(j=9;j--;){char*b=B[i/C]+i%C;r=i/C+j/3-1;c=i%C+j%3-1;r<0|c<0|r/R|c/C|*b&8||(*b=16|*b+(B[r][c]==42));}}
```
Input is in the form of a two-dimensional array of characters, followed by the numbers of rows and columns. The result will be returned in-place.
(Mostly) Ungolfed:
```
i, j, r, c;
f(B, R, C) char **B; {
for (i = R*C; i--;)
for (j = 9; j--;) {
char *b = B[i/C] + i%C;
r = i/C + j/3 - 1;
c = i%C + j%3 - 1;
r < 0 | c < 0 | r / R | c / C | *b & 8 ||
(*b = 16 | *b + (B[r][c] == 42));
}
}
```
The approach is straight-forward — loop over each position, loop over its neighbors, and add up all the asterisks. There are two bit-level tricks:
* When we're deciding if a cell is an asterisk or not, we can just check if the eights-place bit is set, because the number in the cell must be less than 8 (the maximum cell value).
* We can turn a space character into a zero character by OR-ing 16.
Edit: Golfed off two bytes by using `/` in place of `>=`.
Edit: Another five bytes by reversing the direction of the loops.
[Answer]
## C#, 341 Bytes
A naïve implementation that can definitely be shortened.
```
s=>s=="*"?1:0;s=>{for(int i=0,j,n,l=s.Length,c=s[i].Length;i<l;++i)for(j=0;j<c;++j)if(s[i][j]!="*"){n=0;if(i>0){n+=a(s[i-1][j]);n+=j>0?a(s[i-1][j-1]):0;n+=j+1<c?a(s[i-1][j+1]):0;}n+=a(s[i][j]);n+=j>0?a(s[i][j-1]):0;n+=j+1<c?a(s[i][j+1]):0;if(i+1<l){n+=a(s[i+1][j]);n+=j>0?a(s[i+1][j-1]):0;n+=j+1<c?a(s[i+1][j+1]):0;}s[i][j]=n+"";}return s;};
```
[Answer]
# Python 2, 183 bytes
```
def s(m):
j=m.find('\n')+1;q='q'*j*2;m=list(q+m+q)
for i in range(len(m)):
if m[i]==' ':m[i]=`sum([m[k+i]=='*'for k in [-j-1,-j,-j+1,-1,1,j-1,j,j+1]])`
return''.join(m)[j*2:-j*2]
```
] |
[Question]
[
[2048 is an incredibly fun and addictive game](http://git.io/2048) in which the goal is to create a tile with 2048 on it.
Here's a short description of the game:
---
Pressing an arrow key will slide all the blocks in the stage in that direction. For example, if `x` represents a block, and you pressed the up arrow in this case:
```
...x
.x..
..x.
xx..
```
Then the board would become
```
xxxx
.x..
....
....
```
Furthermore, the blocks are numbered, starting at `2`. If two of the same numbered blocks are moved together, they will merge into the next number. For example, pressing "up" on this board:
```
.2..
..22
.2..
....
```
Would create this:
```
.422
....
....
....
```
And then after pressing "right," it would become `..44`, and therefore pressing right again would create an "8" block, and so on.
Each turn, a new "2" block is created on a random open square. (It's actually not *always* a "2," but for simplicity let's keep it at that.) If there are no possible moves left (i.e., the board is full and you can't merge anything), the game is lost, and if a 2048 block is created, you win!
---
Your challenge is to recreate this game, golfed!
* For edge-cases, such as pressing "right" on this board:
```
....
.222
....
....
```
you must merge the tiles closest to the edge of the arrow key pressed. For example, this would become `..24`, because the second and third "2"s are the closest to the right edge.
* If the player presses an invalid move (such as "up" on a board like `2.2. / .... / .... / ....`), you must ignore the move.
* Moves can be accepted in any way, such as clicking, arrow keys, `ULRD`, etc.
* The tiles must all be the same shape—a "1024" tile should be the same size as a "2" tile.
* The tiles must be separated in some way. For example, `|1024| 2|1024|1024|` is a valid example of a row (assuming that the tiles are squares), while `1024 210241024` is not.
* You must output "you win" if the player creates a 2048 tile, or "you lose" if there are no valid moves left.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes will win!
[Answer]
### GolfScript, 323 characters
```
1,16*{16,{1$=!},.,rand=)/()2++\[]*+4/{.['-----']4*'+'*'++'1/*n+:^\{'|'' ':X'|'+4*n++:Y.@{X\`+-5>'|'\+}%'|'+n+Y+Y+^+}%+puts}:P~"wasd":Q{1$.@{Q\?[{zip}{}{-1%zip-1%}{{-1%}%}]=\1$~{0-[{.2$={+)}*}*0...]4<{1|(}%}%\~}:^~=!},:F{0{;'"#{'9.?rand';STDIN.getc()}"'++~.F\?0<}do^[]*.2048?0<.!{'you win'@@}*}{'you lose'@@*0}if}do 4/P;
```
The keys you have to use are `wasd` but you can change the constant in the code to whatever keys you like. It gracefully ignores any unknown key or illegal move. Unfortunately you have to press enter after each key.
![Example 2048ascii](https://i.stack.imgur.com/085WC.png)
### 256 character solution
```
1,16*{16,{1$=!},.,rand=)/())+\[]*+4/{.{{.9>7*+48+}%n+}%puts}:P~"wasd":Q{1$.@{Q\?[{zip}{}{-1%zip-1%}{{-1%}%}]=\1$~{0-[{.2$={;21+}*}*0...]4<{20%}%}%\~}:^~=!},:F{0{;'"#{'9.?rand';STDIN.getc()}"'++~.F\?0<}do^[]*.10?0<.!{'you win'@@}*}{'you lose'@@*0}if}do 4/P;
```
Here the output is hexadecimal logarithmic, i.e. `0` stands for `.`, `1` for `2`, `2` for `4`, `3` for `8` ... `B` for `2048`. Since we all know hexadecimals and the powers of two this shouldn't be a limitation at all.
*Example run (first moves):*
```
0000
0000
0010
0000
w
0011
0000
0000
0000
a
2000
0000
0001
0000
s
0000
0000
0100
2001
d
0000
0000
1001
0021
w
1022
0000
0001
0000
a
1301
0000
1000
0000
s
0000
1000
0000
2301
d
0000
1001
0000
0231
```
[Answer]
# J - 240 230 216 char
This counts the trailing newline, because you need it to start running the game at the console. Play by typing one of `udlr` and then hitting Enter. Moves that do nothing to the board are handled properly, but the program will get mad at you if you give it any bad input.
```
'you ',>lose`win{~$:@".@('o b=:2 t}^:(1-b-:])s ',' b',~1!:1@1:)`w@.((w=:2048 e.,)+(s d-:s u=:l d=:r(&.|:))*s r-:(s=:[:p(2(=/(0,+/^:)@{.,}.),)/@p=:\:=&0)l=:&.|.r=:"1)(o=:[2:1!:2~4<@":"0])b=:2(t=:(?&#{])[:I.0=,)}4 4$0
```
The readable version and explanation are a little too large to fit comfortably into the post: you can find a writeup at **[this link](http://csclub.uwaterloo.ca/~ischtche/2048.ijs)**.
Usage:
```
'you ',>lose`win{~$:@".@('o b=:2 t}^:(1-b-:])s ',' b',~1!:1@1:)`w@.((w=:2048 e.,)+(s d-:s u=:l d=:r(&.|:))*s r-:(s=:[:p(2(=/(0,+/^:)@{.,}.),)/@p=:\:=&0)l=:&.|.r=:"1)(o=:[2:1!:2~4<@":"0])b=:2(t=:(?&#{])[:I.0=,)}4 4$0
+----+----+----+----+
| 0| 0| 0| 0|
+----+----+----+----+
| 2| 0| 0| 0|
+----+----+----+----+
| 0| 0| 0| 0|
+----+----+----+----+
| 0| 0| 0| 0|
+----+----+----+----+
r
+----+----+----+----+
| 0| 0| 0| 0|
+----+----+----+----+
| 0| 0| 0| 2|
+----+----+----+----+
| 0| 0| 0| 0|
+----+----+----+----+
| 0| 2| 0| 0|
+----+----+----+----+
u
+----+----+----+----+
| 0| 2| 0| 2|
+----+----+----+----+
| 0| 0| 0| 0|
+----+----+----+----+
| 0| 0| 0| 0|
+----+----+----+----+
| 0| 0| 0| 2|
+----+----+----+----+
d
+----+----+----+----+
| 0| 0| 0| 0|
+----+----+----+----+
| 2| 0| 0| 0|
+----+----+----+----+
| 0| 0| 0| 0|
+----+----+----+----+
| 0| 2| 0| 4|
+----+----+----+----+
l
+----+----+----+----+
| 0| 0| 0| 0|
+----+----+----+----+
| 2| 0| 0| 0|
+----+----+----+----+
| 0| 0| 2| 0|
+----+----+----+----+
| 2| 4| 0| 0|
+----+----+----+----+
d
+----+----+----+----+
| 0| 0| 0| 0|
+----+----+----+----+
| 0| 0| 0| 0|
+----+----+----+----+
| 0| 2| 0| 0|
+----+----+----+----+
| 4| 4| 2| 0|
+----+----+----+----+
r
+----+----+----+----+
| 0| 0| 0| 0|
+----+----+----+----+
| 0| 0| 0| 2|
+----+----+----+----+
| 0| 0| 0| 2|
+----+----+----+----+
| 0| 0| 8| 2|
+----+----+----+----+
d
+----+----+----+----+
| 0| 0| 0| 0|
+----+----+----+----+
| 0| 0| 0| 0|
+----+----+----+----+
| 0| 2| 0| 2|
+----+----+----+----+
| 0| 0| 8| 4|
+----+----+----+----+
```
[Answer]
# [APL (Dyalog APL)](https://www.dyalog.com/), ~~153~~ ~~150~~ ~~167~~ ~~156~~ ~~155~~ 151 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319)
```
'you ',{2048∊⍵:'win'
(z/∊n)[?+/z←0=∊n←⍵]←2
⎕←4↑¨⍕¨n
1∊(⍉2=⌿n),(2=/n),0=n:∇{⍵≡r←R⍣¯1⎕UCS{4↑⍺⍺t⎕R(1⌽∪¨t←2/¨⍺⍺2*⍳16)⍺⍺⍵~0}¨(R←↓⍉∘⌽⍣⎕)⍵:∇⍵⋄r}n
'lose'}4 4⍴0
```
Prompts for move; 0=Left, 1=Up 2=Right, 3=Down
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKPdPTE3letR39Qgn0dtEx71rlF41DtXoSgxLyU/N7Mq9b96ZX6pgrpOtZGBicWjjq5HvVut1Msz89S5NKr0gfw8zWh7bf0qoFYDWxAXbMbWWCBlBDIUSJs8apt4aMWj3qmHVuRxGQLVaDzq7TSyfdSzP09TR8PIVh9IGdjmWQGdUg3U@qhzYRFQV9Cj3sWH1hsCjQh1Dq4GmfGodxcQlYBcqmH4qGfvo45Vh1aUgCzSBxkPkjTSetS72dBME8IDGlZnUHtohUYQyFFtk4HWPuqYAdLZuxhoiibIK0BLQXZ2txTV5nGp5@QXp6rXmiiYPOrdYgAKGy5Q4PyH@MMA6h9DLtL4RujyAA "APL (Dyalog Unicode) – Try It Online")
### Ungolfed, with whitespace
```
C ← ⎕UCS
'you ', {
2048 ∊ ⍵: 'win'
n ← ⍵
z ← 0 = ∊n
(z / ∊n)[? +/z] ← 2
⎕ ← 4 ↑¨ ⍕¨n
1 ∊ (⍉ 2 =⌿ n) , (2 =/ n) , 0 = n: ∇ {
R←↓⍉∘⌽⍣⎕
r ← R⍣¯1 ⎕UCS {
t ← 2 /¨ ⍺⍺ 2 * ⍳16
4 ↑ ⍺⍺ t ⎕R (1 ⌽ ∪¨t) ⍺⍺ ⍵ ~ 0
}¨ R ⍵
⍵ ≡ r: ∇ ⍵
r
} n
'lose'
} 4 4⍴0
```
### Explanation
Blank lines indicate a newline, while blocks of lines belong on a single line
>
> `'you ',` "you" prepended to the result of the function `{`...
>
>
>
> >
> > `2048 ∊ ⍵: 'win'` if the argument (the board) contains 2048, then return "win"
> >
> >
> > `n ← ⍵` assign the right argument to *n* (so it may be modified in-place)
> >
> >
> > `z ← 0 = ∊n` *z* gets the Boolean list where flattened *z* is 0
> >
> >
> > `(z / ∊n)` *z* filters the flattened *n* (to get only the zeros)
> >
> > `[? +/z]` use a random number between 1 and the count of zeros (the sum of the Boolean *z*) to select which zero-containing position
> >
> > `← 2` gets a 2
> >
> >
> > `⎕ ←` output the
> >
> > `4 ↑¨` each extended-to-length-4 (with spaces)
> >
> > `⍕¨n` string representation of each number
> >
> >
> > `1 ∊` if any of the following are found;
> >
> > `(⍉2=⌿n)` pairwise vertical equalities (transposed to be concatenable)
> >
> > `,` or (concatenated to)
> >
> > `(2=/n)` pairwise horizontal equalities
> >
> > `,` or (concatenated to)
> >
> > `0=n` zeros
> >
> > `:` then:
> >
> > `∇` call this function on the result of the function `{`...
> >
> >
> >
> > >
> > > `R ←` *R* (for *R*ows of *R*otated) is
> > >
> > > `↓` the split-into-rows
> > >
> > > `⍉∘⌽⍣⎕` prompt for numeric input, then rotate (literally mirror horizontally, then transpose) the argument (the board) –90° times the inputted number
> > >
> > >
> > > `r ←` *r* (for *r*esult) gets
> > >
> > > `R⍣¯1` the inverse of *R* (rotate back, then merge rows into matrix) applied to the result of the function `⎕UCS{`... (where `⍺⍺` means convert to/from UCS points)
> > >
> > >
> > >
> > > >
> > > > `t ←` *t* gets
> > > >
> > > > `2 /¨` two of each of
> > > >
> > > > `⍺⍺` the characters corresponding to the code points
> > > >
> > > > `2 * ⍳16` 2¹, 2², 2³,... 2¹⁶
> > > >
> > > >
> > > > `4↑` pad with zeros on the right until length 4
> > > >
> > > > `C` convert the following UCS characters to code points
> > > >
> > > > `t ⎕R (1 ⌽ ∪¨t)` regex replace each pair *t* with the unique characters from the next *t* on the right
> > > >
> > > > `C ⍵~0` the argument (board) without zeros (compacted to the left), then converted to UCS code points
> > > >
> > > >
> > > >
> > >
> > >
> > > `}¨` [end of function] applied to each of
> > >
> > > `R ⍵` *R* applied to the argument (the board)
> > >
> > >
> > > `⍵ ≡ r:` if the argument (the old board state) is identical to *r* (new board state), then:
> > >
> > > `∇⍵` call this function on the unmodified argument (because the user made an invalid move), else
> > >
> > >
> > > `r` return *r* (the new board state)
> > >
> > >
> > >
> >
> >
> > `} n` [end of function] applied to *n* (the new board state), else
> >
> >
> > `'lose'` return "lose"
> >
> >
> >
>
>
> `} 4 4 ⍴ 0` [end of function] applied to a 4-by-4 table of zeros (the initial state)
>
>
>
[Answer]
# Mathematica, 484 chars
Very ugly.
```
m@l=#//.{{x___,0,a_/;a>0,y___}:>{x,a,0,y},{x___,a_/;a>0,a_,y___}:>{x,2 h@a,0,y}}/.h@a_:>a&;{m@u,m@d,m@r}=Composition[#,m@#2,#]&@@@{{Thread,l},{Reverse,u},{Thread,d}};a=ReplacePart[#,RandomChoice@Position[#,0]->2]&;g=a@ConstantArray[0,{4,4}];EventHandler[Dynamic[GraphicsGrid@Map[Graphics@Text@#&,g,{2}]],(#2<>"ArrowKeyDown":>If[g!=m[#]@g,g=a[m[#]@g];Which[And@@(g==m[#]@g&/@{u,l,r,d}),Print@"you lose",!FreeQ[g,2048],Print@"you win"]])&@@@{{l,"Left"},{r,"Right"},{u,"Up"},{d,"Down"}}]
```
Controlled by arrow keys.
![enter image description here](https://i.stack.imgur.com/BFgvW.png)
---
Ungolfed:
```
move[Left] = # //. {{x___, 1, a_ /; a > 1, y___} :> {x, a, 1, y},
{x___, a_ /; a > 1, a_, y___} :> {x, 2 Hold@a, 1, y}} /.
Hold@a_ :> a &;
move[Up] = Composition[Transpose, move[Left], Transpose];
move[Down] = Composition[Reverse, move[Up], Reverse];
move[Right] = Composition[Transpose, move[Down], Transpose];
addTile = ReplacePart[#, RandomChoice@Position[#, 1] -> 2] &;
keyDown = If[grid != move[#][grid], grid = addTile[move[#][grid]];
Which[And @@ (grid == move[#][grid] & /@ {Left, Right, Up, Down}),
status = "Can't move...",
! FreeQ[grid, 2048], status = "2048!"]] &;
grid = addTile@ConstantArray[1, {4, 4}];
status = "";
EventHandler[Dynamic[ArrayPlot[Log2@grid/11,
ColorFunction -> "StarryNightColors",
ColorFunctionScaling -> False,
Mesh -> All,
Epilog -> {MapIndexed[
Text[Style[#1, "Section"] //. 1 -> "", #2 - {0.5, 0.5}] &,
Transpose@Reverse@grid, {2}],
Text[Style[status, "Section"], {2, 2}]}]],
{"LeftArrowKeyDown" :> keyDown[Left],
"RightArrowKeyDown" :> keyDown[Right],
"UpArrowKeyDown" :> keyDown[Up],
"DownArrowKeyDown" :> keyDown[Down]}]
```
![enter image description here](https://i.stack.imgur.com/1vlhL.png)
[Answer]
# Delphi XE3 (Waaay to many {whispers} 2.979 bytes -> ungolfed 4.560 bytes)
I like to call this **"2048 code the novel"**
Used more bytes than I like but it works and it was fun to do.
Im still going to try make it shorter later on.
### Game in progress
![The game](https://i.stack.imgur.com/9zGIE.png)
### Golfed
```
uses System.SysUtils,Windows;type TDir=(dUp,dDown,dLeft,dRight,dInv);const t='_____________________________';er='| | | | |';nr='| %s | %s | %s | %s |';br='|______|______|______|______|';fn='%d';procedure mycls;var S:String;H:DWORD;CO:_COORD;begin H:=GetStdHandle(STD_OUTPUT_HANDLE);CO.X:=0;CO.Y:=0;SetConsoleCursorPosition(H,CO);S:=StringOfChar(Chr(32),2000);Writeln(S);SetConsoleCursorPosition(H,CO);end;var a:array[1..4,1..4]of integer;c,rx,ry,i,j:int8;m:string;GameOver,gs:boolean;function hz:boolean;var b,q:int8;begin for b:=1to 4do for q:=1to 4do if a[b,q]=0 then exit(true);end;function HM:boolean;var b,q:int8;begin if hz then exit(true);for b:=1to 4do for q:=1to 4do begin c:=a[b,q];if c in [a[b-1,q],a[b+1,q],a[b,q-1],a[b,q+1]] then result:=true;end;end;procedure rn(out n,m:int8);var z:int8;begin z:=0;repeat n:=Random(4)+1;m:=Random(4)+1;z:=z+1;until(a[n,m]=0)and(z>=3);end;function gn(n:integer):string;begin if n=0 then exit(' ');Result:=IntToStr(n).PadLeft(4,' ');end;procedure pm(d:TDir;score:boolean);var b,q,z:int8;begin case d of dUp:for z:=1to 3do for b:=1to 4do for q:=1to 3do begin if score then begin if a[q,b]=a[q+1,b] then begin a[q,b]:=a[q,b]+a[q+1,b];a[q+1,b]:=0;end;end else if a[q,b]=0 then begin a[q,b]:=a[q+1,b];a[q+1,b]:=0;end;end;dDown:for z:=1to 3do for b:=1to 4do for q:=2to 4do begin if score then begin if a[q,b]=a[q-1,b] then begin a[q,b]:=a[q,b]+a[q-1,b];a[q-1,b]:=0;end;end else if a[q,b]=0 then begin a[q-1,b]:=a[q,b];a[q-1,b]:=0;end;end;dLeft:for z:=1to 3do for q:=1to 4do for b:=1to 3do begin if score then begin if a[q,b]=a[q,b+1] then a[q,b]:=a[q,b]+a[q,b+1];a[q,b+1]:=0;end else if a[q,b]=0 then begin a[q,b]:=a[q,b+1];a[q,b+1]:=0;end;end;dRight:for z:=1to 3do for q:=1to 4do for b:=2to 4do begin if score then begin if a[q,b]=a[q,b-1] then begin a[q,b]:=a[q,b]+a[q,b-1];a[q,b-1]:=0;end;end else if a[q,b]=0 then begin a[q,b]:=a[q,b-1];a[q,b-1]:=0;end;end;end;end;function gd(s:string):TDir;begin s:=lowercase(s);if s='u'then exit(dUp);if s='d'then exit(dDown);if s='l'then exit(dLeft);if s='r'then exit(dRight);exit(dInv)end;procedure dg;var z:int8;begin writeln(t);for z:=1to 4do begin writeln(er);Writeln(Format(nr,[gn(a[z,1]),gn(a[z,2]),gn(a[z,3]),gn(a[z,4])]));Writeln(br);end;end;function hw:boolean;var b,q:int8; begin for b:=1to 4do for q:=1to 4do if a[b,q]=2048 then result:=true;end;function dm:boolean;var d:Tdir;begin d:=gd(m);if d=dInv then if not gs then exit(false)else exit(true);pm(d,false);pm(d,true);pm(d,false);exit(true);end;begin gs:=true;m:='';for j:=1to 4do for i:=1to 4do begin a[i,j]:=0;end;rx:=0;ry:=0;rn(rx,ry);a[rx,ry]:=2;repeat if (dm) then begin if hz then begin rn(rx,ry);a[rx,ry]:=2;end;gs:=false;end;mycls;GameOver:=true;if hw then WriteLn('You have won!')else if HM then begin GameOver:=false;dg;writeln('Direction: [U]=up, [D]=Down, [L]=Left, [R]=Right');readln(m);end else WriteLn('Game Over, no more possible moves :('#13#10'Try again next time')until GameOver;readln;end.
```
### Ungolfed
```
uses
System.SysUtils,Windows;
type
TDir=(dUp,dDown,dLeft,dRight,dInv);
const
t='_____________________________';
er='| | | | |';
nr='| %s | %s | %s | %s |';
br='|______|______|______|______|';
fn='%d';
procedure mycls;
var
S:String;
H:DWORD;
CO:_COORD;
begin
H:=GetStdHandle(STD_OUTPUT_HANDLE);
CO.X:=0;
CO.Y:=0;
SetConsoleCursorPosition(H,CO);
S:=StringOfChar(Chr(32),2000);
Writeln(S);
SetConsoleCursorPosition(H,CO);
end;
var
a:array[1..4,1..4]of integer;
c,rx,ry,i,j:int8;
m:string;
GameOver,gs:boolean;
function hz:boolean;
var b,q:int8;
begin
for b:=1to 4do
for q:=1to 4do
if a[b,q]=0 then exit(true);
end;
function HM:boolean;
var b,q:int8;
begin
if hz then exit(true);
for b:=1to 4do
for q:=1to 4do
begin
c:=a[b,q];
if c in [a[b-1,q],a[b+1,q],a[b,q-1],a[b,q+1]] then
result:=true;
end;
end;
procedure rn(out n,m:int8);
var z:int8;
begin
z:=0;
repeat
n:=Random(4)+1;
m:=Random(4)+1;
z:=z+1;
until(a[n,m]=0)and(z>=3);
end;
function gn(n:integer):string;
begin
if n=0 then exit(' ');
Result:=IntToStr(n).PadLeft(4,' ');
end;
procedure pm(d:TDir;score:boolean);
var
b,q,z:int8;
begin
case d of
dUp:
for z:=1to 3do
for b:=1to 4do
for q:=1to 3do
begin
if score then
begin
if a[q,b]=a[q+1,b] then
begin
a[q,b]:=a[q,b]+a[q+1,b];a[q+1,b]:=0;
end;
end
else
if a[q,b]=0 then
begin
a[q,b]:=a[q+1,b];a[q+1,b]:=0;
end;
end;
dDown:
for z:=1to 3do
for b:=1to 4do
for q:=2to 4do
begin
if score then
begin
if a[q,b]=a[q-1,b] then
begin
a[q,b]:=a[q,b]+a[q-1,b];a[q-1,b]:=0;
end;
end
else
if a[q,b]=0 then
begin
a[q-1,b]:=a[q,b];
a[q-1,b]:=0;
end;
end;
dLeft:
for z:=1to 3do
for q:=1to 4do
for b:=1to 3do
begin
if score then
begin
if a[q,b]=a[q,b+1] then
a[q,b]:=a[q,b]+a[q,b+1];a[q,b+1]:=0;
end
else
if a[q,b]=0 then
begin
a[q,b]:=a[q,b+1];a[q,b+1]:=0;
end;
end;
dRight:
for z:=1to 3do
for q:=1to 4do
for b:=2to 4do
begin
if score then
begin
if a[q,b]=a[q,b-1] then
begin
a[q,b]:=a[q,b]+a[q,b-1];a[q,b-1]:=0;
end;
end
else
if a[q,b]=0 then
begin
a[q,b]:=a[q,b-1];a[q,b-1]:=0;
end;
end;
end;
end;
function gd(s:string):TDir;
begin
s:=lowercase(s);
if s='u'then exit(dUp);
if s='d'then exit(dDown);
if s='l'then exit(dLeft);
if s='r'then exit(dRight);
exit(dInv)
end;
procedure dg;
var z:int8;
begin
writeln(t);
for z:=1to 4do
begin
writeln(er);
Writeln(Format(nr,[gn(a[z,1]),gn(a[z,2]),gn(a[z,3]),gn(a[z,4])]));
Writeln(br);
end;
end;
function hw:boolean;
var b,q:int8;
begin
for b:=1to 4do
for q:=1to 4do
if a[b,q]=2048 then
result:=true;
end;
function dm:boolean;
var
d:Tdir;
begin
d:=gd(m);
if d=dInv then if not gs then exit(false)else exit(true);
pm(d,false);
pm(d,true);
pm(d,false);
exit(true);
end;
begin
gs:=true;m:='';
for j:=1to 4do
for i:=1to 4do
begin
a[i,j]:=0;
end;
rx:=0;ry:=0;
rn(rx,ry);
a[rx,ry]:=2;
repeat
if (dm) then
begin
if hz then
begin
rn(rx,ry);
a[rx,ry]:=2;
end;
gs:=false;
end;
mycls;
GameOver:=true;
if hw then
WriteLn('You have won!')
else if HM then
begin
GameOver:=false;
dg;
writeln('Direction: [U]=up, [D]=Down, [L]=Left, [R]=Right');
readln(m);
end
else
WriteLn('Game Over, no more possible moves :('#13#10'Try again next time')
until GameOver;
readln;
end.
```
[Answer]
## C (C89 standard), 881 bytes
Use wasd keys to move.
Compiles in GCC and clang by default, unless set to C99 standard (I guess).
Uses termios.h, worked in Linux and MacOS X. Not sure about Windows.
```
#include<termios.h>
#define R return
#define H while
char t[17],*Q,*W="adws",D,x,y,X;m(x,y){R!D?x+y*4:D==1?3-x+y*4:D==2?y+x*4:y+(3-x)*4;}c(){for(y=0;y<3;++y)for(x=0;x<3;++x){D=t[x+y*4];if(t[x+1+y*4]==D||t[x+4+y*4]==D)x=y=9;}R y>4;}d(){if(strlen(t)==16)R 0;H(t[x=(rand()&15)]);R t[x]=1;}r(x){putchar(x);}b(){y=0;r(10);H(y<21)r(y++%5?45:43);r(10);}f(){for(x=0;x<17;++x)if(X=(t[x]==11))x=32;R x<18;}struct termios z;main(){srand(time(tcgetattr(0,&z)));z.c_lflag&=~ICANON;tcsetattr(0,0,&z);H(f()&&(d()||c())){x=0;H(x<16){if(!(x&3)){b();r('|');}if(y=t[x++])printf("%4u|",1<<y);else printf(" |");}b();r(10);H(!(Q=strchr(W,getchar())));D=Q-W;for(y=0;y<4;++y)for(X=0,x=1;x<4;++x)if(t[m(x,y)]){if(t[m(x,y)]==t[m(X,y)]&&t[m(X,y)]++)t[m(x,y)]=0;X=x;}do{for(y=0;y<4;++y)for(x=0;x<3;++x)if(!t[m(x,y)]&&(X=t[m(x+1,y)])){t[m(x,y)]=X;t[m(x+1,y)]=0;x=y=9;}}H(y>4);}puts(X?"you win":"you lose");}
```
Broken in some lines:
```
#include<termios.h>
#define R return
#define H while
char t[17],*Q,*W="adws",D,x,y,X;m(x,y){R!D?x+y*4:D==1?3-x+y*4:D==2?y+x*4:y+(3-x)*4;}
c(){for(y=0;y<3;++y)for(x=0;x<3;++x){D=t[x+y*4];if(t[x+1+y*4]==D||t[x+4+y*4]==D)x=y=9;}R y>4;}
d(){if(strlen(t)==16)R 0;H(t[x=(rand()&15)]);R t[x]=1;}
r(x){putchar(x);}
b(){y=0;r(10);H(y<21)r(y++%5?45:43);r(10);}
f(){for(x=0;x<17;++x)if(X=(t[x]==11))x=32;R x<18;}
struct termios z;
main(){srand(time(tcgetattr(0,&z)));z.c_lflag&=~ICANON;tcsetattr(0,0,&z);
H(f()&&(d()||c())){x=0;H(x<16){if(!(x&3)){b();r('|');}if(y=t[x++])printf("%4u|",1<<y);else printf(" |");}
b();r(10);H(!(Q=strchr(W,getchar())));D=Q-W;for(y=0;y<4;++y)for(X=0,x=1;x<4;++x)
if(t[m(x,y)]){if(t[m(x,y)]==t[m(X,y)]&&t[m(X,y)]++)t[m(x,y)]=0;X=x;}
do{for(y=0;y<4;++y)for(x=0;x<3;++x)if(!t[m(x,y)]&&(X=t[m(x+1,y)]))
{t[m(x,y)]=X;t[m(x+1,y)]=0;x=y=9;}}H(y>4);}puts(X?"you win":"you lose");}
```
The looks:
```
+----+----+----+----+
| 8| 4| 8| 2|
+----+----+----+----+
| | 16| | |
+----+----+----+----+
| | 2| | |
+----+----+----+----+
| | | | 2|
+----+----+----+----+
```
It can be improved for sure.
[Answer]
# Java: 1346 1269
**Edit** So although this contest is done, sometimes I can't let go when improvements can be made. This version boasts a leaner, meaner, in-place folding function, the eviction of most `boolean` types except where it would be more verbose without them, and slightly smaller cells (4x4 instead of 5x5) to cut out a few extra characters there.
So this was a fun one. Thanks for posting! Ungolfed, this was 2856 bytes, golfed I shrunk it to 1346 bytes. Being Java, I'm not going to win, but I wanted to put in a good showing. Figuring out a "general" roll-up function to handle tile joins and moves was fun -- you can of course check out my "progress" by looking through the commits on my [github repository for this solution](https://github.com/ProgrammerDan/twentyfortyeight).
**Golfed:**
```
import java.util.*;class T{public static void main(String[]a){(new T()).s();}int[][]b=new int[4][4];int d,p,i,j,x,y,v,q,r;boolean I,V;void s(){p();do{d();do{char a=(new Scanner(System.in)).nextLine().charAt(0);y=a=='u'?f(0,1):a=='d'?f(1,1):a=='l'?f(0,0):a=='r'?f(1,0):0;}while(y<1);p();}while((x=n())>0);d();c("you "+(x<0?"win":"lose"));}int h(){for(int[]y:b)for(int x:y)if(x<2)return 1;return 0;}int n(){for(y=0;y<4;y++){for(x=0;x<4;x++){i=b[y][x];if(x<3&&i==b[y][x+1]||y<3&&i==b[y+1][x])return 1;if(i>2047)return -1;}}return h();}int f(int w,int z){I=w>0;V=z>0;for(i=d=0;i<4;i++){p=I?3:0;for(j=1;j<4;){v=V?i:j;x=I?3-v:v;v=V?j:i;y=I?3-v:v;q=V?x:p;r=V?p:y;if(b[y][x]==0||p==(V?y:x))j++;else if(b[r][q]==0){d+=b[r][q]=b[y][x];b[y][x]=0;j++;}else if(b[r][q]==b[y][x]){d+=b[r][q]*=2;b[y][x]=0;p+=I?-1:1;j++;}else p+=I?-1:1;}}return d;}int v(){return(new Random()).nextInt(4);}void p(){if(h()<1)return;do{x=v();y=v();}while(b[x][y]>0);b[x][y]=2;}void c(String a){System.out.println(a);}String l(char n,char m){String s=""+n;for(i=0;i<4;i++){for(j=0;j<4;j++)s+=m;s+=n;}return s;}void d(){c(l('+','-'));String p[]=new String[5];for(int[]y:b){p[0]=p[1]=p[3]=l('|',' ');p[2]="";for(x=0;x<4;)p[2]+=String.format("|%4d",y[x++]);p[2]+="|";p[4]=l('+','-');for(String q:p)c(q);}}}
```
**Ungolfed:** (Check [my github repository for this project](https://github.com/ProgrammerDan/twentyfortyeight) for an updated version, including an assertions-based test for new folding functions)
```
import java.util.*;
class Twe {
public static void main(String[] a){
(new Twe()).start();
}
int[][] board=new int[4][4];
void start(){
int x;
placeTwo();
do{
drawBoard();
resolve();
placeTwo();
}while((x=notDone())>0);
drawBoard();
wrapup(x);
}
int hasFree(){
for(int[]y:board)
for(int x:y)
if(x<2)return 1;
return 0;
}
int notDone(){
int moves,x,y;
for(moves=y=0;y<4;y++){
for(x=0;x<4;x++){
else if(x<3&&board[y][x]==board[y][x+1]||
y<3&&board[y][x]==board[y+1][x])moves++;
if(board[y][x]>2047)return -1;
}
}
return hasFree()+moves;
}
void wrapup(int k){
if(k<0){
chalk("you win",true);
}else{
chalk("you lose",true);
}
}
void resolve(){
do{
switch((new Scanner(System.in)).nextLine().charAt(0)){
case 'u':
if (fold(false,true)>0)return;
break;
case 'd':
if (fold(true, true)>0)return;
break;
case 'l':
if (fold(false,false)>0)return;
break;
case 'r':
if (fold(true,false)>0)return;
break;
case 'z':
board[0][0]=2048; // instant win;
return;
}
} while(true);
}
// false,true = up
// true, true = down
// false,false = left
// true, false = right
int fold(boolean inv, boolean vert){
int didMove=0;
int nextSpot,x,y,v,q,r;
int[][] nb = new int[4][4];
for(int i=0;i<4;i++){
nextSpot=inv?3:0;
for(int j=0;j<4;j++){
v=vert?i:j;
x=inv?3-v:v;
v=vert?j:i;
y=inv?3-v:v;
q=vert?x:nextSpot;
r=vert?nextSpot:y;
if(board[y][x]>0){
if(nb[r][q]<1){
nb[r][q]=board[y][x];
didMove+=(inv?-1:1)*(vert?y-r:x-q);
}else if(nb[r][q]==board[y][x]){
nb[r][q]*=2;
nextSpot+=inv?-1:1;
didMove++;
}else{
nextSpot+=inv?-1:1;//suckage
q=vert?x:nextSpot;
r=vert?nextSpot:y;
nb[r][q]=board[y][x];
didMove+=(inv?-1:1)*(vert?y-r:x-q);
}
}
}
}
board=nb;
return didMove;
}
int vec(){
return (new Random()).nextInt(4);
}
void placeTwo(){
if (hasFree()<1) return;
int x,y;
do{
x=vec();y=vec();
}while(board[x][y]>0);
board[x][y]=2;
}
void chalk(String a, boolean nl){
System.out.print(a+(nl?"\n":""));
}
String fill(char node, char mid){
String str = ""+node;
for(int i=0;i<4;i++){
for(int j=0;j<5;j++)
str+=mid;
str+=node;
}
return str;
}
void drawBoard(){
chalk(fill('+','-'),true);
String p[] = new String[6];
for(int[]y:board){
p[0]=p[1]=p[3]=p[4]=fill('|',' ');
p[2]="";
for(int x=0;x<4;){
p[2]+=adjust(y[x++]);
}
p[2]+="|";
p[5]=fill('+','-');
for (String q:p){
chalk(q,true);
}
}
}
String adjust(int a){
return String.format("|%5d",a);
}
}
```
Using the program is simple. To build and run:
```
javac T.java
java T
```
Press `u` to fold up, `r` to fold right, `d` to fold down, `l` to fold left. Any other key is ignored, invalid (no result) moves are ignored. Being Java, press `enter` after each key to flush the line buffer. As required by the rules, if you win the program outputs `you win`, if you lose the program outputs `you lose`. New `2`'s are placed randomly in the open tiles. Merges follow the stated rules. Cells are 4x4 characters, with a border surrounding each cell. Of course, leave me a comment if I've messed something up and I'll be certain to fix it.
Example output:
```
$ java T
+----+----+----+----+
| | | | |
| | | | |
| 0| 0| 0| 0|
| | | | |
+----+----+----+----+
| | | | |
| | | | |
| 0| 0| 0| 0|
| | | | |
+----+----+----+----+
| | | | |
| | | | |
| 0| 0| 0| 0|
| | | | |
+----+----+----+----+
| | | | |
| | | | |
| 2| 0| 0| 0|
| | | | |
+----+----+----+----+
u
+----+----+----+----+
| | | | |
| | | | |
| 2| 0| 0| 0|
| | | | |
+----+----+----+----+
| | | | |
| | | | |
| 0| 0| 0| 0|
| | | | |
+----+----+----+----+
| | | | |
| | | | |
| 0| 0| 0| 2|
| | | | |
+----+----+----+----+
| | | | |
| | | | |
| 0| 0| 0| 0|
| | | | |
+----+----+----+----+
l
+----+----+----+----+
| | | | |
| | | | |
| 2| 0| 0| 0|
| | | | |
+----+----+----+----+
| | | | |
| | | | |
| 0| 0| 0| 0|
| | | | |
+----+----+----+----+
| | | | |
| | | | |
| 2| 0| 0| 0|
| | | | |
+----+----+----+----+
| | | | |
| | | | |
| 2| 0| 0| 0|
| | | | |
+----+----+----+----+
u
+----+----+----+----+
| | | | |
| | | | |
| 4| 0| 0| 0|
| | | | |
+----+----+----+----+
| | | | |
| | | | |
| 2| 2| 0| 0|
| | | | |
+----+----+----+----+
| | | | |
| | | | |
| 0| 0| 0| 0|
| | | | |
+----+----+----+----+
| | | | |
| | | | |
| 0| 0| 0| 0|
| | | | |
+----+----+----+----+
l
+----+----+----+----+
| | | | |
| | | | |
| 4| 0| 0| 0|
| | | | |
+----+----+----+----+
| | | | |
| | | | |
| 4| 0| 0| 0|
| | | | |
+----+----+----+----+
| | | | |
| | | | |
| 0| 0| 0| 0|
| | | | |
+----+----+----+----+
| | | | |
| | | | |
| 0| 0| 0| 2|
| | | | |
+----+----+----+----+
u
+----+----+----+----+
| | | | |
| | | | |
| 8| 2| 0| 2|
| | | | |
+----+----+----+----+
| | | | |
| | | | |
| 0| 0| 0| 0|
| | | | |
+----+----+----+----+
| | | | |
| | | | |
| 0| 0| 0| 0|
| | | | |
+----+----+----+----+
| | | | |
| | | | |
| 0| 0| 0| 0|
| | | | |
+----+----+----+----+
l
+----+----+----+----+
| | | | |
| | | | |
| 8| 4| 2| 0|
| | | | |
+----+----+----+----+
| | | | |
| | | | |
| 0| 0| 0| 0|
| | | | |
+----+----+----+----+
| | | | |
| | | | |
| 0| 0| 0| 0|
| | | | |
+----+----+----+----+
| | | | |
| | | | |
| 0| 0| 0| 0|
| | | | |
+----+----+----+----+
l
u
d
+----+----+----+----+
| | | | |
| | | | |
| 0| 0| 0| 0|
| | | | |
+----+----+----+----+
| | | | |
| | | | |
| 0| 0| 0| 0|
| | | | |
+----+----+----+----+
| | | | |
| | | | |
| 0| 0| 2| 0|
| | | | |
+----+----+----+----+
| | | | |
| | | | |
| 8| 4| 2| 0|
| | | | |
+----+----+----+----+
d
+----+----+----+----+
| | | | |
| | | | |
| 0| 0| 0| 0|
| | | | |
+----+----+----+----+
| | | | |
| | | | |
| 0| 0| 0| 2|
| | | | |
+----+----+----+----+
| | | | |
| | | | |
| 0| 0| 0| 0|
| | | | |
+----+----+----+----+
| | | | |
| | | | |
| 8| 4| 4| 0|
| | | | |
+----+----+----+----+
l
+----+----+----+----+
| | | | |
| | | | |
| 0| 0| 0| 0|
| | | | |
+----+----+----+----+
| | | | |
| | | | |
| 2| 0| 0| 0|
| | | | |
+----+----+----+----+
| | | | |
| | | | |
| 0| 0| 2| 0|
| | | | |
+----+----+----+----+
| | | | |
| | | | |
| 8| 8| 0| 0|
| | | | |
+----+----+----+----+
l
+----+----+----+----+
| | | | |
| | | | |
| 0| 0| 0| 0|
| | | | |
+----+----+----+----+
| | | | |
| | | | |
| 2| 2| 0| 0|
| | | | |
+----+----+----+----+
| | | | |
| | | | |
| 2| 0| 0| 0|
| | | | |
+----+----+----+----+
| | | | |
| | | | |
| 16| 0| 0| 0|
| | | | |
+----+----+----+----+
d
+----+----+----+----+
| | | | |
| | | | |
| 0| 2| 0| 0|
| | | | |
+----+----+----+----+
| | | | |
| | | | |
| 0| 0| 0| 0|
| | | | |
+----+----+----+----+
| | | | |
| | | | |
| 4| 0| 0| 0|
| | | | |
+----+----+----+----+
| | | | |
| | | | |
| 16| 2| 0| 0|
| | | | |
+----+----+----+----+
d
+----+----+----+----+
| | | | |
| | | | |
| 0| 0| 0| 0|
| | | | |
+----+----+----+----+
| | | | |
| | | | |
| 0| 0| 0| 0|
| | | | |
+----+----+----+----+
| | | | |
| | | | |
| 4| 2| 0| 0|
| | | | |
+----+----+----+----+
| | | | |
| | | | |
| 16| 4| 0| 0|
| | | | |
+----+----+----+----+
```
[Answer]
### Lua, ~~622~~ ~~616~~ ~~615~~ ~~612~~ ~~592~~ ~~590~~ 575 bytes
Queries stdin for 1,2,3,4 correlating with left, down, right, up (made for numpad input); crashes if you give it bad input.
Blank squares are printed as '0's.
```
b={('\0'):rep(16):byte(1,16)}c=1 a=print h=unpack while{}do if c then c=z
e={}for i=1,16 do e[#e+1]=0==b[i]and i or z end _=#e==0 and
a'you lose'b[e[math.random(#e)]]=2 l=('+----'):rep(4)..'+\n'm=l:gsub('-',' ')for
i=1,13,4 do a(l..m..m..m..('+%4d+%4d+%4d+%4d+'):format(h(b,i)))end a(l)end c=z
u,v,w=h({4,1,-4,1,-4,16,4,-1,1,1,4,-4},3*io.read()-2)for i=1,4 do o=-1 for j=2,4
do if 0~=b[u*i+v*j+w]then for k=1-j,o do p=u*i-v*k+w q=p+v r=b[p]if r==0 then
b[p]=b[q]b[q]=r c=1 o=k elseif r==b[q]then _=r==1024 and a'you win'b[p]=r*2
b[q]=0 c=1 o=k-1 break end end end end end end
```
Example output:
```
+----+----+----+----+
+ + + + +
+ + + + +
+ + + + +
+ 2+ 0+ 0+ 0+
+----+----+----+----+
+ + + + +
+ + + + +
+ + + + +
+ 0+ 0+ 0+ 0+
+----+----+----+----+
+ + + + +
+ + + + +
+ + + + +
+ 0+ 0+ 0+ 0+
+----+----+----+----+
+ + + + +
+ + + + +
+ + + + +
+ 0+ 0+ 0+ 0+
+----+----+----+----+
2
+----+----+----+----+
+ + + + +
+ + + + +
+ + + + +
+ 0+ 2+ 0+ 0+
+----+----+----+----+
+ + + + +
+ + + + +
+ + + + +
+ 0+ 0+ 0+ 0+
+----+----+----+----+
+ + + + +
+ + + + +
+ + + + +
+ 0+ 0+ 0+ 0+
+----+----+----+----+
+ + + + +
+ + + + +
+ + + + +
+ 2+ 0+ 0+ 0+
+----+----+----+----+
```
[Answer]
# Clojure: 599
[run it in a REPL](https://repl.it/KDNU/3)
**golfed**
```
(defn i[b](let[f(into[](flatten b))z(seq(keep-indexed #(when(zero? %2)%1)f))]
(cond(some #{2048}f)(pr "you win")(empty? z)(pr "game over"):e(partition 4
(assoc f(rand-nth z)2)))))(def r #(remove zero? %))(loop[b(i (partition 4
(repeat 16 0)))](when((fn[v](doseq[l(for[a v](apply str(map #(format "%5d " %)a)))]
(println l "\n"))v)b)(-> b((apply comp(assoc(into[](repeat 5(fn[v]
(map(fn[n](map #(nth % n)v))[3 2 1 0]))))({"h"4 "k"3 "l"2 "j"1}(read-line))
(partial map(comp #(take 4(concat % [0 0 0 0]))(fn[v]
(r(reduce #(let[l(last %1)](if(= %2 l)(conj(pop %1)(+ l %2) 0)
(conj %1 %2)))[]v)))r)))))i recur)))
```
**ungolfed**
```
(defn insert-2 [board]
(let [flat (into [] (flatten board))
zero-indices (seq (keep-indexed
#(when (zero? %2) %1)
flat))]
(cond
(some #{2048} flat) (pr "you win")
(empty? zero-indices) (pr "game over")
:else (partition 4 (assoc flat (rand-nth zero-indices) 2)))))
(defn rotate [board]
(map
(fn [n]
(map #(nth % n)
board))
[3 2 1 0]))
(defn remove-zeros [row]
(remove zero? row))
(defn fill [row]
(take 4 (concat row [0 0 0 0])))
(defn sum-up [acc x]
(let [l (last acc)]
(if (= x l)
(conj (pop acc) (+ l x) 0)
(conj acc x))))
(defn sum-pairs [v]
(remove-zeros (reduce sum-up [] v)))
(defn render [v]
(doseq [line (for [row v]
(apply str (map #(format "%5d " %) row)))]
(println line "\n")) v)
(defn slide [board]
(map (comp
fill
sum-pairs
remove-zeros
) board))
(loop [board (insert-2 (partition 4 (repeat 16 0)))]
(when (render board)
(let [input ({"h" 4 "k" 3 "l" 2 "j" 1} (read-line))
command (apply comp
(assoc (into [] (repeat 5 rotate))
input slide))] ;; (comp rotate rotate slide rotate rotate)
(-> board command insert-2 recur))))
```
] |
[Question]
[
# Challenge
Write a program that outputs the lyrics to 99 Bottles of Beer, ***but*** instead of "beer", output "fizz" if the number of bottles on the wall is a multiple of 3, "buzz" if it is a multiple of 5, and "fizzbuzz" if it is a multiple of 3 and a multiple of 5. If the number of bottles on the wall is not a multiple of 3 or 5, just output "beer" as usual.
## Lyrics
```
99 bottles of fizz on the wall, 99 bottles of fizz.
Take one down and pass it around, 98 bottles of beer on the wall.
98 bottles of beer on the wall, 98 bottles of beer.
Take one down and pass it around, 97 bottles of beer on the wall.
97 bottles of beer on the wall, 97 bottles of beer.
Take one down and pass it around, 96 bottles of fizz on the wall.
96 bottles of fizz on the wall, 96 bottles of fizz.
Take one down and pass it around, 95 bottles of buzz on the wall.
95 bottles of buzz on the wall, 95 bottles of buzz.
Take one down and pass it around, 94 bottles of beer on the wall.
....
3 bottles of fizz on the wall, 3 bottles of fizz.
Take one down and pass it around, 2 bottles of beer on the wall.
2 bottles of beer on the wall, 2 bottles of beer.
Take one down and pass it around, 1 bottle of beer on the wall.
1 bottle of beer on the wall, 1 bottle of beer.
Go to the store and buy some more, 99 bottles of fizz on the wall.
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest submission in each language wins.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~263~~ ~~253~~ 245 bytes
```
i=99
x=''
while i:x+=', %s on the wall.\n\n%s on the wall, %s.\n'%(('%d bottle%s of %s'%(i,'s'*(i>1),(i%3<1)*'fizz'+(i%5<1)*'buzz'or'beer'),)*3)+'GToa kteo otnhee dsotwonr ea nadn dp absusy isto maer omuonrde'[i>1::2];i-=1
print x[35:]+x[:33]
```
[Try it online!](https://tio.run/nexus/python2#VY07bsMwEAV7nWIbYfVzAIVwYSZymwukk1VQ4BpaWOYaJAUpvrxCp0s58wZ4O3enU7Z1iNk68UzAeqs7bCAPIA7iRLCaeX67uIv7r15J0pgXBeYWRolxpldyTUOy3GDAquBzWzYF5@qzLSu88vOJdcLjH45LQvE4Enksm7JSZY1f32LgFkkAJLqJCMAGias4D2TAGevAPsCMYQk/AByiwN2QB7kvqbGEfTrV@n344EPXZg/PLsLWq6Me6q3XSg37/gs "Python 2 – TIO Nexus\"9tv0C \"Python 2 – TIO Nexus")
[Answer]
# C (GCC), ~~276~~ 274 bytes
*Thanks to [Neil](https://codegolf.stackexchange.com/users/17602/neil) for saving two bytes!*
```
#define w" on the wall"
#define c(i)printf("%d bottle%s of %s",i,"s"+!~-i,i%3?i%5?"beer":"buzz":i%5?"fizz":"fizzbuzz"),printf(
i;f(){for(i=99;i;c((i?:99))w".\n\n"))c(i)w", "),c(i)".\n"),printf(--i?"Take one down and pass it around, ":"Go to the store and buy some more, ");}
```
Who doesn't love unmatched parentheses in macro expansions ?
### Ungolfed:
```
#define c(i) \
printf( \
"%d bottle%s of %s", \
i, /* Number */ \
i-1 ? "s" : "", /* Plural */ \
i % 3 /* FizzBuzz*/ \
? i % 5 \
? "beer" \
: "buzz" \
: i % 5 \
? "fizz" \
: "fizzbuzz" \
)
i;
f() {
for(i = 99; i; ) {
c(i); printf(" on the wall, ");
c(i); printf(".\n");
printf(
--i
? "Take one down and pass it around, "
: "Go to the store and buy some more, "
);
// This has been stuffed into the for increment
c((i?:99)); printf(" on the wall.\n\n");
}
}
```
[See it live on Coliru!](http://coliru.stacked-crooked.com/a/fd7a3a29d215acfe)
# Alternate version (276 bytes)
```
#define c(i)printf("%d bottle%s of %s",i,i-1?"s":"",i%3?i%5?"beer":"buzz":i%5?"fizz":"fizzbuzz"),printf(
i,*w=" on the wall";f(){for(i=99;i;c((i?:99))"%s.\n\n",w))c(i)"%s, ",w),c(i)".\n"),printf(--i?"Take one down and pass it around, ":"Go to the store and buy some more, ");}
```
[Answer]
# [Röda](https://github.com/fergusq/roda), 273 bytes
```
f{a=`bottle`f=` on the wall`g=`99 ${a}s of fizz`;[`$g$f, $g.
`];seq 98,1|{|b|d=`s`d=``if[b=1];c=``c=`fizz`if[b%3=0];c.=`buzz`if[b%5=0];c=`beer`if[c=``];e=`$b $a$d of $c`;[`Take one down and pass it around, $e$f.
$e$f, $e.
`]}_;[`Go to the store and buy some more, $g$f.`]}
```
[Try it online!](https://tio.run/nexus/roda#NY/LasMwEEX3@opZqNBCMA0lUGO0zg9kF0xHikauiS0llkxobH@7MzJ0oddBh3tndZNWaEJKHaFTCMFD@iV46K7DRmFZgpz0EiE4cO3zidUZZSPdDmRTCKyrSHcov3f7eZrNbBVG5A1bdzZqX1cXvvPazMzevtQn04Ijx3902BAToiGT7NQVKZQGpJY2R8tLDj7pK3FBAhseHrS3cNMxQptAD2H0lkuRdIUQ@ciP3HD5YfMYIIVtsJjCQJtrxj@IoSfomeR5WOXva69bPwlw7x9iWV8 "Röda – TIO Nexus")
Will golf further in the morning.
[Answer]
# PHP, 242 Bytes
```
function f($k){return"$k bottle".(s[$k<2])." of ".([fizz][$k%3].[buzz][$k%5]?:beer);}$w=" on the wall";for($b=f($c=99);$c;)echo"$b$w, $b.
",--$c?"Take one down and pass it around":"Go to the store and buy some more",", ",$b=f($c?:99),"$w.
";
```
[Try it online!](https://tio.run/nexus/php#LY3NaoQwFIX3PsXlcgsKmSxauhgz4rIv0J24MDGi6ORKfpBO6bPbMMzyfJxzvlu7z/s5JWfiwg6mktbq19uYvENaQXOMm0VZho7W23tfSQSeIINuWh6PPtO3j152Or3CZ9/W2lpfqT86mlx2EGcLx7BtqCb2JekmS0xzvVaKjKqsmRlJ0yGAtCxQXC5kWvweVpvHFkY@HAxuhH0IAZYIg@fkRqzxiyHy8z1E9vZZ0ukHAt8t3DNBgQJQvIxtnZUC6ZBFgeo8/wE "PHP – TIO Nexus")
# PHP, 244 Bytes
```
for($e=s,$b=fizz,$c=99;$c;)echo strtr("301245, 30124.
6, 708295.
",[" bottle",$e," of ",$c,$b," on the wall",--$c?"Take one down and pass it around":"Go to the store and buy some more",$k=$c?:99,$e=s[2>$k],$b=[fizz][$k%3].[buzz][$k%5]?:beer]);
```
[Try it online!](https://tio.run/nexus/php#LU9BboMwELzzipXlSIlkUEpKW6CUYz/QG/LBmEVEEC@yjaLk3z1Tg3ramdHs7M5nPQ/z2pM9cqyc4G3VX59PwXWV5yXX5Qn1QOC89fbILueX9DUTsM8kehPwfv5I8yyJIiYaBi15PyETHAUD6iEgHSI3YsAPCHc1TUzEMdc1@1EjBh2ho7sBZTqYlXNw9aAsLaZjBfsm8LQvOk8Wd1O7PMDRDeEWlHBgrEJYkedi@79Jv/gotxbNVkM2fDxcZNK0yz/JZF20iFaeynX9NRRrpQf8Aw "PHP – TIO Nexus")
use function [strtr](http://php.net/manual/en/function.strtr.php)
# PHP, 245 Bytes
```
$f=function($k)use(&$b){$b="$k bottle".(s[$k<2])." of ".([fizz][$k%3].[buzz][$k%5]?:beer);};for($w=" on the wall",$f($c=99);$c;)echo"$b$w, $b.
",--$c?"Take one down and pass it around":"Go to the store and buy some more",", {$f($c?:99)}$b$w.
";
```
[Try it online!](https://tio.run/nexus/php#LY3BboMwEETvfMVqtamwRHxo1UMgiGN@oDfEwQZbIIgXYSPURPl24qIe52lm3rWa@3knW9rVtWFgl9IoVm/SD9LiSbpEGkFzCJNBmfqaxutnIyQCW4igtsPj0UR6@mpkrdf/8N1UuTZmEcWrsLyktJVx4SD0BjY1TZiRTaktLxdRUFsI0/aMpGnLgLRMMDufqa3wR40mzgx0vDlQroNZeQ9DALXw6jrM8cYQ@Pj1gRdzlPT6C57vBu6RYIYZPA9dlUff608jkwSLfX8D "PHP – TIO Nexus")
use an [Anonymous function](http://php.net/manual/en/functions.anonymous.php) in the string to get a sustring depending of the integer
Expanded
```
$f=function($k)use(&$b){$b="$k bottle".(s[$k<2])." of ".([fizz][$k%3].[buzz][$k%5]?:beer);};
for($w=" on the wall",$f($c=99);$c;)
echo"$b$w, $b.
",--$c?"Take one down and pass it around":"Go to the store and buy some more"
,", {$f($c?:99)}$b$w.
";
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~151~~ ~~146~~ 143 bytes
```
99LRv'¬ž“fizzÒÖ“#y35SÖÏJ‚˜1(è©y“ƒ¶€µ„‹€ƒî倕…¡, ÿÏꀂ ÿ€‰€€íÒ.“ªõ®y“ÿÏꀂ ÿ€‰€€íÒ, “D#4£ðýs…ÿÿ.}‚‚˜'Ïê'±¥:`)¦¦¬#7£ðý¨“‚œ€„€€ƒï€ƒ‚¥€ä€£, ÿ.“ª)˜»
```
[Try it online!](https://tio.run/nexus/05ab1e#hU87CsJAFLyKkCIGJCAqorWVWOkFrARrQVAQFi8QiGARQkCjoiH@CgURFd5gmtxiLxLfbg4gC/tm35uZN5s1Gp3u2KT4@5bCHwynU7hYMjQmlVoPSzhtKbzULxexp8OEB4lLdzmP6SZFIMWDYeLihC0DKdZS7GhVKuADB5FuefzQ4KLueYwjXJt9KMKNTsrxD7lUYE7LqFKIC14j3sCCjz1jto5mKrVJV9o2@xbt@MRGPSfTnqVM@i60aZCbct6zLjwhlRsb9aFQxc6TWalPzyz7AQ "05AB1E – TIO Nexus")
[Answer]
# [SOGL](https://github.com/dzaima/SOGL), ~~136~~ ~~135~~ ~~134~~ ~~133~~ 131 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md)
```
Ƨ, o▓k
"πFT+╔¡‘oW
³³q"'bμ⁸‘oH? so}5\;3\«+"ΞQv↑χāσκN⌡κYT¡‘_,S─‘oθwoX▓
MH∫}¹±{▓WkƧ.¶oH¡"sΗ─χpēGķ¶¾3Ζ^9f.⅟▒E┌Fρ_╬a→‘KΘw⁽oXH‽M}HkW">⁸‘p
```
First of all, the 3rd function:
```
▓ name this "▓" (example input: 15) [15]
³³ Create 4 extra copies of the top thing (number of things) [15, 15, 15, 15, 15]
q output without popping one of them [15, 15, 15, 15, 15]
"...‘o output " bottle" [15, 15, 15, 15, 15]
H? } if pop-1 [isn't 0] [15, 15, 15, 15]
so output "s" [15, 15, 15, 15]
5\ push if POP divides by 5 [15, 15, 15, 1]
; swap [if divides & another number copy] [15, 15, 1, 15]
3\« push if POP divides by 3, multiplied by 2 [15, 15, 1, 2]
+ add those together [15, 15, 3]
"...‘ push "buzz fizz fizzbuzz beer" [15, 15, 3, "buzz fizz fizzbuzz beer"]
...‘o output " of " (done over here to save a byte for a quote) [15, 15, 3, "buzz fizz fizzbuzz beer"]
θ split ["buzz fizz fizzbuzz beer"] on spaces [15, 15, 3, ["buzz","fizz","fizzbuzz","beer"]]
w get the index (1-indexed, wrapping) [15, 15, ["buzz","fizz","fizzbuzz","beer"], "fizzbuzz"]
o output that string [15, 15, ["buzz","fizz","fizzbuzz","beer"]]
X pop the array off of the stack [15, 15]
```
The first function:
```
Ƨ, o▓k
k name this "function" "k"
Ƨ, o output ", "
▓ execute the "bottleify" function
```
The second function:
```
"πFT+╔¡‘oW
W call this "W"
"πFT+╔¡‘ push " on the wall"
o output it
```
And the main part:
```
MH∫} repeat 99 times, each time pushing index
¹ wrap in an array
± reverse it
{ iterate over it
▓ execute that function
W execute that function
k execute that function
Ƨ.¶o output ".\n"
H¡ push if POP-1 isn't 0 (aka 1 if pop <> 1, 0 if pop == 1)
"...‘ push "Stake one down and pass it aroundSgo to the store and buy some more"
K push the first letter of that string
Θ split ["take one down and pass it aroundSgo to the store and buy some more" with "S"]
w gets the xth (1-indexed, wrapping) item of that array
⁽o uppercase the 1st letter and output
X pop the array off
H‽ if pop-1 [isn't 0]
M push 100
} ENDIF
H decrease POP
k execute that function
W execute that function
">⁸‘p output ".\n\n"
```
Lost a couple bytes because of a bug that `O` puts a newline before and after it (And somehow this goes back to V0.9 (this is V0.11 code))
[Answer]
# Java, ~~344~~ ~~340~~ 339 bytes
(-4 bytes after golfing fizzbuzz; -1 byte removing stray whitespace)
```
interface X{static void main(String[]a){for(int i=99;i>0;System.out.printf("%s on the wall, %s.%n%s, %s on the wall.%n%n",b(i),b(i--),i<1?"Go to the store and buy some more":"Take one down and pass it around",b(i<1?99:i)));}static String b(int i){return i+" bottle"+(i>1?"s":"")+" of "+(i%3<1?"fizz":"")+(i%5<1?"buzz":i%3<1?"":"beer");}}
```
Slightly ungolfed (using 1-space indentation to eliminate horizontal scrolling):
```
interface X {
static void main(String[]a){
for(int i=99;i>0;System.out.printf("%s on the wall, %s.%n%s, %s on the wall.%n%n",
b(i),b(i--),
i<1?"Go to the store and buy some more":"Take one down and pass it around",
b(i<1?99:i)));
}
static String b(int i){
return i+" bottle"+(i>1?"s":"")+" of "+(i%3<1?"fizz":"")+(i%5<1?"buzz":i%3<1?"":"beer");
}
}
```
[Answer]
# JavaScript (ES6), ~~316~~ 309 bytes
This is a full program rather than a function. Nothing very creative, it's just the naive approach (hence the bytecount!). I am using `console.log()` instead of `alert()` because many browsers have limit on the number of chars that can be displayed using `alert()`. Note that all the whitespaces and newlines are necessary.
```
a="";for(i=99;i>0;i--){b=j=>"bottle"+(j>1?"s":"");d=a=>(a%3?"":"fizz")+(a%5?"":"buzz")||"beer");w=" on the wall";o=" of ";a+=`${i+" "+b(i)+o+d(i)+w+", "+i+" "+b(i)+o+d(i)}.
${i>1?"Take one down and pass it around, ":"Go to the store and buy some more, "}${(y=i-1?i-1:99)+" "+b(y)+o+d(y)+w}.
`;}console.log(a)
```
Ungolfed :
```
let accumulator = "";
for(let i = 99; i>0; i--){
let bottleString = j => "bottle"+(j>1?"s":""),
drink = a =>(a%3?"":"fizz")+(a%5?"":"buzz")||"beer",
wallString = " on the wall",
of=" of ";
accumulator += `${i+" "+bottleString(i)+of+drink(i)+wallString+", "+i+" "+bottleString(i)+of+drink(i)}.
${i>1?"Take one down and pass it around, ":"Go to the store and buy some more, "}${(y=i-1?i-1:99)+" "+bottleString(y)+of+drink(y)+wallString}.
`;
}
console.log(accumulator);
```
Here's the Snippet :
```
a="";for(i=99;i>0;i--){b=j=>"bottle"+(j>1?"s":"");d=a=>(a%3?"":"fizz")+(a%5?"":"buzz")||"beer";w=" on the wall";o=" of ";a+=`${i+" "+b(i)+o+d(i)+w+", "+i+" "+b(i)+o+d(i)}.
${i>1?"Take one down and pass it around, ":"Go to the store and buy some more, "}${(y=i-1?i-1:99)+" "+b(y)+o+d(y)+w}.
`;}console.log(a)
```
BTW, with this answer, I have earned the bronze badge in [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'")! Never thought I will accomplish this ever (not that it's a big achievement, though.)!
[Answer]
# [Retina](https://github.com/m-ender/retina), 230 bytes
```
99$*_
_\B
Take one down and pass it around, $.'#.¶¶$.'#, $.'.¶
^
99#, 99.¶
_
Go to the store and buy some more, 99#.
#
on the wall
1\b|(\d+)
$& bottle$#1$*s of $&$*_
\b(_{15})+\b
fizzbuzz
\b(_{5})+\b
buzz
\b(___)+\b
fizz
_+
beer
```
[Try it online!](https://tio.run/nexus/retina#PY5NCsIwEEb3c4qBhNofKXThols3XsBlMCQ0xWJNpEkpVr1WD9CL1aRKYRbzHh/fzAJlSVMOnB3hLG4KjVZYmUGj0BU@hLXYOBSd6XW1R5rvSD5P8xSWFT3BxXd4KssAHE4GnZ@rQutMp9Yi2T/RmrvCuzchSnIg4I@tuUG0LRRMvmNWZQnQCKVxrlWUFDS1aGqkUXiSyZi/isMnyZiEuhlH2Y/jz/7lJjjfQsAzkEp1y/IF "Retina – TIO Nexus") Explanation:
```
99$*_
```
Inserts 99 `_`s.
```
_\B
Take one down and pass it around, $.'#.¶¶$.'#, $.'.¶
```
Changes all but the last `_` to the string `Take one down and pass it around, $.'#.¶¶$.'#, $.'.¶`, where `¶` is a newline and `$.'` is the count of remaining underscores. This effectively counts back from 98 to 1.
```
^
99#, 99.¶
```
Adds the first line of the first verse in "compact" format.
```
_
Go to the store and buy some more, 99#.
```
Adds the second line of the last verse. Why I need jump through hoops to use the `_` I don't know, but `$` seems to match twice, so I can't use that. Go figure.
```
#
on the wall
```
Substitutes a string which appears several times in the verse.
```
1\b|(\d+)
$& bottle$#1$*s of $&$*_
```
This matches the integers in the verses, and suffixes the appropriate bottle(s) of, and expands back to unary again, in preparation to choose the beverage. (I save 1 byte on on the `99`s this way.)
```
\b(_{15})+\b
fizzbuzz
\b(_{5})+\b
buzz
\b(___)+\b
fizz
_+
beer
```
Replace exact multiples with the appropriate beverage.
[Answer]
# [sed](https://www.gnu.org/software/sed/), ~~468~~ ~~459~~ 456 bytes
```
s:^:99 bottles of fizz on the wall, 99 bottles of fizz.:
p
s:99:I8:g
s:fizz:XYYZ:g
x
s:^:Take one down and pass it around, I8 bottles of XYYZ on the wall.\n:
G
x
:
g
s:XXX:fizz:g
s:Y{5}:buzz:g
s:\bX*Y*Z:beer:g
s:[XYZ]::g
y:ABCDEFGHI:123456789:
s:\b0::g
/ 1 /bq
p
x
s:^::
tc
:c
s:(\S)0:\1@:g
Td
y:ABCDEFGHI:0ABCDEFGH:
:d
y:123456789@:0123456789:
s:(XXX)*(Y{5})*(Y*Z):XY\3:g
x
b
:q
s:es:e:g
aGo to the store and buy some more, 99 bottles of fizz on the wall.
```
[Try it online!](https://tio.run/nexus/sed#bVFNU8IwEL3nV@yxdBBaEW33hJ/YsxzaWp1paNCOJYEmDALjX7duijowOpOZ7NvNvrf70mh8xjAEroyphAY1g1m53YKSYF4FrPOq6sLfeg/ZgmlqxCjAF4psEuMkSQm9M0s6yd8E0Qgo1FpCLgtY5FpDaSCv1UoWXYiCQ1rbfCjbyySyMZEhswJxHO9FLEh2ww/kq2@U8dhN3BS5EHWbeIyT9Akp3ODl1fXN7d34PkL/dHA2PL8IQmxbPFvvgw99vqRd9jMjM1OGU4qd7KHjYeaP6NWkOCLyfkJkaCu/xCP0jkQcmrnjOnZYe7lphxzKBq1DnOGSngg6hPOxAqPa1bVRtWjt4qsNaDUXMKfMf59w5FbTfKqFKZXUzUn9BQ "sed – TIO Nexus")
Requires `-r` flag.
## Explanation
Hold space holds the pattern of two repeating lines, with numbers represented as `[A-I][0-9]` (separate digits for tens and ones) and the kind of beverage represented as `X*Y*Z`, where `X` keeps track of `-N mod 3`, and `Y` of `-N mod 5`.
On each subsequent iteration, the numbers get decremented and the `X`s and `Y`s get updated. Then hold space gets copied to the pattern space, turned into lines of the song, and printed.
[Answer]
# C, ~~349~~ ~~345~~ 344 bytes
```
#define b(x)x^1?" bottles":" bottle"
#define g i-1?"Take one down and pass it around":"Go to the store and buy some more"
*w=" on the wall";*s(x){return x?x%15?x%5?x%3?"beer":"fizz":"buzz":"fizzbuzz":"fizz";}i=100;main(){while(--i){printf("%d%s of %s%s, %d%s of %s.\n%s, %d%s of %s%s.\n",i,b(i),s(i),w,i,b(i),s(i),g,i-1?i-1:99,b(i-1),s(i-1),w);}}
```
Well, there you go. That took an hour.
[Try it online!](http://rextester.com/ADVK39431)
[Answer]
# Javascript (ES6), 236 234 233 232 bytes
```
for(i=99;i;console.log(z()+`, ${z(_)}.
${--i?'Take one down and pass it around':'Go to the store and buy some more'}, ${z()}.
`))z=(o=' on the wall',j=i||99)=>j+` bottle${j>1?'s':_} of `+((j%3?_:'fizz')+(j%5?_='':'buzz')||'beer')+o
```
**Demo**
```
// replace console.log to avoid 50-log limit in snippets:
console.log=_=>document.write(`<pre>${_}</pre>`)
for(i=99;i;console.log(z()+`, ${z(_)}.
${--i?'Take one down and pass it around':'Go to the store and buy some more'}, ${z()}.
`))z=(o=' on the wall',j=i||99)=>j+` bottle${j>1?'s':_} of `+((j%3?_:'fizz')+(j%5?_='':'buzz')||'beer')+o
```
**Ungolfed**
```
i = 99 // start counter at 99
z = ( // define function z which takes arguments with defaults:
o = ' on the wall', // o = defaults to ' on the wall'
j = i || 99 // j = defaults to value of counter i - or 99 when i == 0
) =>
j + // our current j counter
' bottle' +
(j > 1 ? 's' : _) + // choose 's' when we have more than 1 bottle, or blank _
(
(j % 3 ? _ : 'fizz') + // if j % 3 is 0, add 'fizz', otherwise blank _
(j % 5 ? _ = '' : 'buzz') // if j % 5 is 0, add 'buzz', otherwise blank _
// _ gets defined here since it's the first place it's used
|| // if no fizz or buzz, result is a falsey empty string
'beer' // replace falsey value with 'beer'
) +
o // append o
while (i) { // while counter is non-zero
console.log( // output string:
z() + // call z without o argument
', ' +
z(_) + // call z with blank _ for o to block ' on the wall' here
'.\n' +
( --i // decrement i, if still non-zero:
? 'Take one down and pass it around'
// otherwise:
: 'Go to the store and buy some more'
) +
', ' +
z() + // another call to z without o
'.\n\n'
)
}
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 261 bytes
```
99.downto(1){|i|w=' on the wall'
f=->x{a='';x%3<1&&a+='fizz';x%5<1&&a+='buzz';a<?a&&a='beer';"%d bottle%s of %s"%[x,x<2?'':?s,a]}
puts [f[i]+w,f[i]+?.+$/+(i<2?'Take one down and pass it around':'Go to the store and buy some more'),f[i<2?99:i-1]+w+?.+$/*2]*', '}
```
[Try it online!](https://tio.run/nexus/ruby#NY7NjoJAEITvPkXH7Ngq6AY3ewBBjr6AN8KhCUOcLNKGGQL@PTvOYPZUqS@VqhrDcFty3xheBqvHUz37BIEbMGcJPdU1zqpkcxgelCDuB/ETB4sFeQlW6n534PcfFJ0DFKdkvbVStrifixIKNqaWQgNXIPRcZIM/xLsUMUq1T/lrdu2MhqzKVO71/iTp1vv69pbKxU70J@0hCe4lUFPClbQGZYBa7poSIzwyGJ4ea8OtnEJFdwPNFwkXS3Dlem1bGEZqE9idz8R6l6/RB3yN4xs "Ruby – TIO Nexus")
[Answer]
# [shortC](//github.com/aaronryank/shortC), ~~314~~ 312 bytes
```
Db(x)x^1?" bottles":" bottle"
Dg i-1?"Take one down and pass it around":"Go to the store and buy some more"
*w=" on the wall";*s(x){Tx?x%15?x%5?x%3?"beer":"fizz":"buzz":"fizzbuzz":"fizz";}i=100;AW--i){R"%d%s of %s%s, %d%s of %s.\n%s, %d%s of %s%s.\n",i,b(i),s(i),w,i,b(i),s(i),g,i-1?i-1:99,b(i-1),s(i-1),w
```
Sorry there's no explanation, but I completely forgot how this works.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 307 297 bytes
```
A”|‽2?{:×G↗”¦αA“6«eMηOU¶¿”¦ζA“9“e▷·gqε-g}”¦βA“9B{⦃⁺Bφ=;λO”¦ωAfizz¦φAbuzz¦γAbeer¦ηA”↶C▶▶d℅d¬r·US\λTθNevT◧→GM⁸ω┦τA“M↧k↓⁺*f÷,ψZ¢▶\¿|P“№κ×υpξXoW”¦σA.¶πF⮌…¹¦¹⁰⁰«A⎇⁻ι¹αζθ¿∧¬﹪鳬﹪ι⁵A⁺φγ﹪ι³Aφ﹪ι⁵AγεAηε⁺⁺⁺⁺⁺⁺⁺IιθεβIιθεπ¿⁻ι¹A⁻ι¹λA⁹⁹λA⎇⁻λ¹αζθ¿∧¬﹪볬﹪λ⁵A⁺φγ﹪λ³Aφ﹪λ⁵AγεAηε¿⁻ι¹AτδAσδ⁺⁺⁺⁺δλθεω
```
[Try it online!](https://tio.run/##lZBNb8IgGMfvfoonniBBo1k8mJ3MDju5LMajFyrQkiF0QG3sss/eUewsM2niDhz4vzw8/I4FtUdDVdtunJO5RlPIjPeKOzACpgQofp7cWb3TpI7R4AsONVWKdGY2Ys4P@qCDXye@kE0TJJFIWRWlPJU4t0EqEmlPP8IymgMztQaqGZTUOZAeqDWVZnETnxReDXgTd3HeWB4rWXUBZ04cTkGJDZc05nHbMijCWEA7fubWcbSjOudoSZaLBcYYviYAfWPPrab2grZSVw5JssSEkgYT@AwzQkwKQBvN0JvxaGtYpUwIPWFM/ggr3I3tR24YQ6KDQYCHIdcZ9/1bWoymVkkqj6nfW3HthNK7ldrHF8fOC3UeyfihrkUyTHoJkyAFpcTDVwcMt6cTMmpYYb3ubmMc1SMc1T1H9T@O6iGO6iGOI3/3hA1p111GmbPAowdad0C/27adnduZUz8 "Charcoal – Try It Online")
YES, WE CAN! Link to the verbose version, this can be golfed a lot, I'm sure.
[Answer]
# tcl, 298
```
proc B i {set x " bottle[expr $i>1?"s":""] of [expr $i%3?$i%5?"beer":"":"fizz"][expr $i%5?"":"buzz"]"}
set i 99
time {puts "$i[B $i][set w " on the wall"], $i[B $i].
Take one down and pass it around, [incr i -1][B $i]$w."} 98
puts "1[B $i]$w, 1[B $i].
Go to the store and buy some more, 99[B 9]$w."
```
# [demo](http://rextester.com/DWERG84874)
[Answer]
# Deadfish~, 88919 bytes
[Try it online](https://deadfish.surge.sh/#L3ZCx320n/9VkFqqw//v/8O/z/5Bvwb/Dv/Ab9VgdWsG8Bv9gdVs/h9VkBvYHVrGA378Dq3/g1YrAb/eB1qsFqw7yCqtVYNWH3/5BaqsP/7//Dv8/+Qb8G/w7/wG/VYHVrBvAb/YHVbP4fVZAb/VVYK1VWQOq3/h3+HYqrAb/eB1axg3gN/vA6rVh3h1YN4Dfvw//v/w7/BsBv9+B1bBqqw+rIDfqsDqt/h3gN+qsP/7/8PqsVn/8G/wbBVaqrBqw+//GC1Vh//f/4d/n/yDfg3+Hf+A36rA6tYN4Df7D/+//z+Q7/Ab9WB1axgN+/A6t/4NWKwG/3gdarBasO8gqrVgrVVZIf/VYwWqsP/7//Dv8/+Qb8G/w7/wG/VYHVrBvAb/Yf/3/+fyHf4DfqwOrWMBv34HVv/BqxWA3+8DrVYLVh3kFVaqwasPv/xgtVYf/3/+Hf5/8g34N/h3/gN+qwOrWDeA3+w//v/8/kO/wG/34K1VWQOq3/h3+HYqrAb/eB1axg3gN/vA6rVh3h1YN4Dfvw//v/w7/BsBv9+B1bBqqw+rIDfqsDqt/h3gN+qsP/7/8PqsVn/8G/wbBVaqrBqw+//FgtVh//f/4d/n/yDfg3+Hf+A36rA6tYN4Df7D/+//z+Q7/Ab9WB1axgN+/A6t/4NWKwG/3gdarBasO8gqrVgrVVZIf/VYsFqsP/7//Dv8/+Qb8G/w7/wG/VYHVrBvAb/Yf/3/+fyHf4DfqwOrWMBv34HVv/BqxWA3+8DrVYLVh3kFVaqwasPv/xYLVYf/3/+Hf5/8g34N/h3/gN+qwOrWDeA3+w//v/8/kO/wG/34K1VWQOq3/h3+HYqrAb/eB1axg3gN/vA6rVh3h1YN4Dfvw//v/w7/BsBv9+B1bBqqw+rIDfqsDqt/h3gN+qsP/7/8PqsVn/8G/wbBVaqrBqw+//FYLVh//f/4d/n/yDfg3+Hf+A36rA6tYN4Df7A6rZ/D6rIDewOrWMBv34HVv/BqxWA3+8DrVYLVh3kFVasFaqrJD/6rFYLVh//f/4d/n/yDfg3+Hf+A36rA6tYN4Df7A6rZ/D6rIDewOrWMBv34HVv/BqxWA3+8DrVYLVh3kFVaqwasPv/xWC1Yf/3/+Hf5/8g34N/h3/gN+qwOrWDeA3+wOq2fw+qyA3+qqwVqqsgdVv/Dv8OxVWA3+8Dq1jBvAb/eB1WrDvDqwbwG/fh//f/h3+DYDf78Dq2DVVh9WQG/VYHVb/DvAb9VYf/3/4fVYrP/4N/g2Cq1VWDVh9/+KsFrD/+//w7/P/kG/Bv8O/8Bv1WB1awbwG/2H/9//h9Z/8gN7A6tYwG/fgdW/8GrFYDf7wOtVgtWHeQVVqwVqqskP/qsVYLWH/9//h3+f/IN+Df4d/4DfqsDq1g3gN/sP/7//D6z/5Ab2B1axgN+/A6t/4NWKwG/3gdarBasO8gqrVWDVh9/+KsFrD/+//w7/P/kG/Bv8O/8Bv1WB1awbwG/2H/9//h9Z/8gN/qqsFaqrIHVb/w7/DsVVgN/vA6tYwbwG/3gdVqw7w6sG8Bv34f/3/4d/g2A3+/A6tg1VYfVkBv1WB1W/w7wG/VWH/9/+H1WKz/+Df4NgqtVVg1Yff/iqwWw//v/8O/z/5Bvwb/Dv/Ab9VgdWsG8Bv9h//f/5/Id/gN+rA6tYwG/fgdW/8GrFYDf7wOtVgtWHeQVVqwVqqskP/qsVWC2H/9//h3+f/IN+Df4d/4DfqsDq1g3gN/sP/7//P5Dv8Bv1YHVrGA378Dq3/g1YrAb/eB1qsFqw7yCqtVYNWH3/4qsFsP/7//Dv8/+Qb8G/w7/wG/VYHVrBvAb/Yf/3/+fyHf4Df78FaqrIHVb/w7/DsVVgN/vA6tYwbwG/3gdVqw7w6sG8Bv34f/3/4d/g2A3+/A6tg1VYfVkBv1WB1W/w7wG/VWH/9/+H1WKz/+Df4NgqtVVg1Yff/iqsFvD/+//w7/P/kG/Bv8O/8Bv1WB1awbwG/2B1Wz+H1WQG9gdWsYDfvwOrf+DVisBv94HWqwWrDvIKq1YK1VWSH/1WKqwW8P/7//Dv8/+Qb8G/w7/wG/VYHVrBvAb/YHVbP4fVZAb2B1axgN+/A6t/4NWKwG/3gdarBasO8gqrVWDVh9/+KqwW8P/7//Dv8/+Qb8G/w7/wG/VYHVrBvAb/YHVbP4fVZAb/VVYK1VWQOq3/h3+HYqrAb/eB1axg3gN/vA6rVh3h1YN4Dfvw//v/w7/BsBv9+B1bBqqw+rIDfqsDqt/h3gN+qsP/7/8PqsVn/8G/wbBVaqrBqw+//Bv8Fvw//v/8O/z/5Bvwb/Dv/Ab9VgdWsG8Bv9h//f/5/Id/gN+rA6tYwG/fgdW/8GrFYDf7wOtVgtWHeQVVqwVqqskP/qsG/wW/D/+//w7/P/kG/Bv8O/8Bv1WB1awbwG/2H/9//n8h3+A36sDq1jAb9+B1b/wasVgN/vA61WC1Yd5BVWqsGrD7/8G/wW/D/+//w7/P/kG/Bv8O/8Bv1WB1awbwG/2H/9//n8h3+A3+/BWqqyB1W/8O/w7FVYDf7wOrWMG8Bv94HVasO8OrBvAb9+H/9/+Hf4NgN/vwOrYNVWH1ZAb9VgdVv8O8Bv1Vh//f/h9Vis//g3+DYKrVVYNWH3/4N+C3+H/9//h3+f/IN+Df4d/4DfqsDq1g3gN/sP/7//P5Dv8Bv1YHVrGA378Dq3/g1YrAb/eB1qsFqw7yCqtWCtVVkh/9Vg34Lf4f/3/+Hf5/8g34N/h3/gN+qwOrWDeA3+w//v/8/kO/wG/VgdWsYDfvwOrf+DVisBv94HWqwWrDvIKq1Vg1Yff/g34Lf4f/3/+Hf5/8g34N/h3/gN+qwOrWDeA3+w//v/8/kO/wG/34K1VWQOq3/h3+HYqrAb/eB1axg3gN/vA6rVh3h1YN4Dfvw//v/w7/BsBv9+B1bBqqw+rIDfqsDqt/h3gN+qsP/7/8PqsVn/8G/wbBVaqrBqw+//BvBqqsP/7//Dv8/+Qb8G/w7/wG/VYHVrBvAb/YHVbP4fVZBaqw+s/+QG9gdWsYDfvwOrf+DVisBv94HWqwWrDvIKq1YK1VWSH/1WDeDVVYf/3/+Hf5/8g34N/h3/gN+qwOrWDeA3+wOq2fw+qyC1Vh9Z/8gN7A6tYwG/fgdW/8GrFYDf7wOtVgtWHeQVVqrBqw+//BvBqqsP/7//Dv8/+Qb8G/w7/wG/VYHVrBvAb/YHVbP4fVZBaqw+s/+QG/1VWCtVVkDqt/4d/h2KqwG/3gdWsYN4Df7wOq1Yd4dWDeA378P/7/8O/wbAb/fgdWwaqsPqyA36rA6rf4d4DfqrD/+//D6rFZ//Bv8GwVWqqwasPv/OC1VYf/3/+Hf5/8g34N/h3/gN+qwOrWDeA3+w//v/8/kO/wG/VgdWsYDfvwOrf+DVisBv94HWqwWrDvIKq1YK1VWSH/f/5wWqrD/+//w7/P/kG/Bv8O/8Bv1WB1awbwG/2H/9//n8h3+A36sDq1jAb9+B1b/wasVgN/vA61WC1Yd5BVWqsGrD7/zgtVWH/9//h3+f/IN+Df4d/4DfqsDq1g3gN/sP/7//P5Dv8Bv9+CtVVkDqt/4d/h2KqwG/3gdWsYN4Df7wOq1Yd4dWDeA378P/7/8O/wbAb/fgdWwaqsPqyA36rA6rf4d4DfqrD/+//D6rFZ//Bv8GwVWqqwasPv/ILVWH/9//h3+f/IN+Df4d/4DfqsDq1g3gN/sP/7//P5Dv8Bv1YHVrGA378Dq3/g1YrAb/eB1qsFqw7yCqtWCtVVkh/3/+QWqsP/7//Dv8/+Qb8G/w7/wG/VYHVrBvAb/Yf/3/+fyHf4DfqwOrWMBv34HVv/BqxWA3+8DrVYLVh3kFVaqwasPv/ILVWH/9//h3+f/IN+Df4d/4DfqsDq1g3gN/sP/7//P5Dv8Bv9+CtVVkDqt/4d/h2KqwG/3gdWsYN4Df7wOq1Yd4dWDeA378P/7/8O/wbAb/fgdWwaqsPqyA36rA6rf4d4DfqrD/+//D6rFZ//Bv8GwVWqqwasPv/GC1WH/9//h3+f/IN+Df4d/4DfqsDq1g3gN/sDqtn8PqsgN7A6tYwG/fgdW/8GrFYDf7wOtVgtWHeQVVqwVqqskP+//xgtVh//f/4d/n/yDfg3+Hf+A36rA6tYN4Df7A6rZ/D6rIDewOrWMBv34HVv/BqxWA3+8DrVYLVh3kFVaqwasPv/GC1WH/9//h3+f/IN+Df4d/4DfqsDq1g3gN/sDqtn8PqsgN/qqsFaqrIHVb/w7/DsVVgN/vA6tYwbwG/3gdVqw7w6sG8Bv34f/3/4d/g2A3+/A6tg1VYfVkBv1WB1W/w7wG/VWH/9/+H1WKz/+Df4NgqtVVg1Yff+LBasP/7//Dv8/+Qb8G/w7/wG/VYHVrBvAb/Yf/3/+fyHf4DfqwOrWMBv34HVv/BqxWA3+8DrVYLVh3kFVasFaqrJD/v/8WC1Yf/3/+Hf5/8g34N/h3/gN+qwOrWDeA3+w//v/8/kO/wG/VgdWsYDfvwOrf+DVisBv94HWqwWrDvIKq1Vg1Yff+LBasP/7//Dv8/+Qb8G/w7/wG/VYHVrBvAb/Yf/3/+fyHf4Df78FaqrIHVb/w7/DsVVgN/vA6tYwbwG/3gdVqw7w6sG8Bv34f/3/4d/g2A3+/A6tg1VYfVkBv1WB1W/w7wG/VWH/9/+H1WKz/+Df4NgqtVVg1Yff+KwWsP/7//Dv8/+Qb8G/w7/wG/VYHVrBvAb/Yf/3/+H1n/yA3sDq1jAb9+B1b/wasVgN/vA61WC1Yd5BVWrBWqqyQ/7//FYLWH/9//h3+f/IN+Df4d/4DfqsDq1g3gN/sP/7//D6z/5Ab2B1axgN+/A6t/4NWKwG/3gdarBasO8gqrVWDVh9/4rBaw//v/8O/z/5Bvwb/Dv/Ab9VgdWsG8Bv9h//f/4fWf/IDf6qrBWqqyB1W/8O/w7FVYDf7wOrWMG8Bv94HVasO8OrBvAb9+H/9/+Hf4NgN/vwOrYNVWH1ZAb9VgdVv8O8Bv1Vh//f/h9Vis//g3+DYKrVVYNWH3/irBbD/+//w7/P/kG/Bv8O/8Bv1WB1awbwG/2B1Wz+H1WQG9gdWsYDfvwOrf+DVisBv94HWqwWrDvIKq1YK1VWSH/f/4qwWw//v/8O/z/5Bvwb/Dv/Ab9VgdWsG8Bv9gdVs/h9VkBvYHVrGA378Dq3/g1YrAb/eB1qsFqw7yCqtVYNWH3/irBbD/+//w7/P/kG/Bv8O/8Bv1WB1awbwG/2B1Wz+H1WQG/1VWCtVVkDqt/4d/h2KqwG/3gdWsYN4Df7wOq1Yd4dWDeA378P/7/8O/wbAb/fgdWwaqsPqyA36rA6rf4d4DfqrD/+//D6rFZ//Bv8GwVWqqwasPv/FVgt4f/3/+Hf5/8g34N/h3/gN+qwOrWDeA3+w//v/8/kO/wG/VgdWsYDfvwOrf+DVisBv94HWqwWrDvIKq1YK1VWSH/f/4qsFvD/+//w7/P/kG/Bv8O/8Bv1WB1awbwG/2H/9//n8h3+A36sDq1jAb9+B1b/wasVgN/vA61WC1Yd5BVWqsGrD7/xVYLeH/9//h3+f/IN+Df4d/4DfqsDq1g3gN/sP/7//P5Dv8Bv9+CtVVkDqt/4d/h2KqwG/3gdWsYN4Df7wOq1Yd4dWDeA378P/7/8O/wbAb/fgdWwaqsPqyA36rA6rf4d4DfqrD/+//D6rFZ//Bv8GwVWqqwasPv/FVYLfh//f/4d/n/yDfg3+Hf+A36rA6tYN4Df7D/+//z+Q7/Ab9WB1axgN+/A6t/4NWKwG/3gdarBasO8gqrVgrVVZIf9//iqsFvw//v/8O/z/5Bvwb/Dv/Ab9VgdWsG8Bv9h//f/5/Id/gN+rA6tYwG/fgdW/8GrFYDf7wOtVgtWHeQVVqrBqw+/8VVgt+H/9//h3+f/IN+Df4d/4DfqsDq1g3gN/sP/7//P5Dv8Bv9+CtVVkDqt/4d/h2KqwG/3gdWsYN4Df7wOq1Yd4dWDeA378P/7/8O/wbAb/fgdWwaqsPqyA36rA6rf4d4DfqrD/+//D6rFZ//Bv8GwVWqqwasPv/Bv8Fv8P/7//Dv8/+Qb8G/w7/wG/VYHVrBvAb/YHVbP4fVZAb2B1axgN+/A6t/4NWKwG/3gdarBasO8gqrVgrVVZIf9//g3+C3+H/9//h3+f/IN+Df4d/4DfqsDq1g3gN/sDqtn8PqsgN7A6tYwG/fgdW/8GrFYDf7wOtVgtWHeQVVqrBqw+/8G/wW/w//v/8O/z/5Bvwb/Dv/Ab9VgdWsG8Bv9gdVs/h9VkBv9VVgrVVZA6rf+Hf4diqsBv94HVrGDeA3+8DqtWHeHVg3gN+/D/+//Dv8GwG/34HVsGqrD6sgN+qwOq3+HeA36qw//v/w+qxWf/wb/BsFVqqsGrD7/wb8Gqqw//v/8O/z/5Bvwb/Dv/Ab9VgdWsG8Bv9h//f/4fWf/IDewOrWMBv34HVv/BqxWA3+8DrVYLVh3kFVasFaqrJD/v/8G/BqqsP/7//Dv8/+Qb8G/w7/wG/VYHVrBvAb/Yf/3/+H1n/yA3sDq1jAb9+B1b/wasVgN/vA61WC1Yd5BVWqsGrD7/wb8Gqqw//v/8O/z/5Bvwb/Dv/Ab9VgdWsG8Bv9h//f/4fWf/IDf6qrBWqqyB1W/8O/w7FVYDf7wOrWMG8Bv94HVasO8OrBvAb9+H/9/+Hf4NgN/vwOrYNVWH1ZAb9VgdVv8O8Bv1Vh//f/h9Vis//g3+DYKrVVYNWH3+fBaqsP/7//Dv8/+Qb8G/w7/wG/VYHVrBvAb/Yf/3/+fyHf4DfqwOrWMBv34HVv/BqxWA3+8DrVYLVh3kFVasFaqrJD/v/z4LVVh//f/4d/n/yDfg3+Hf+A36rA6tYN4Df7D/+//z+Q7/Ab9WB1axgN+/A6t/4NWKwG/3gdarBasO8gqrVWDVh9/nwWqrD/+//w7/P/kG/Bv8O/8Bv1WB1awbwG/2H/9//n8h3+A3+/BWqqyB1W/8O/w7FVYDf7wOrWMG8Bv94HVasO8OrBvAb9+H/9/+Hf4NgN/vwOrYNVWH1ZAb9VgdVv8O8Bv1Vh//f/h9Vis//g3+DYKrVVYNWH3+cFqrD/+//w7/P/kG/Bv8O/8Bv1WB1awbwG/2B1Wz+H1WQG9gdWsYDfvwOrf+DVisBv94HWqwWrDvIKq1YK1VWSH/f/nBaqw//v/8O/z/5Bvwb/Dv/Ab9VgdWsG8Bv9gdVs/h9VkBvYHVrGA378Dq3/g1YrAb/eB1qsFqw7yCqtVYNWH3+cFqrD/+//w7/P/kG/Bv8O/8Bv1WB1awbwG/2B1Wz+H1WQG/1VWCtVVkDqt/4d/h2KqwG/3gdWsYN4Df7wOq1Yd4dWDeA378P/7/8O/wbAb/fgdWwaqsPqyA36rA6rf4d4DfqrD/+//D6rFZ//Bv8GwVWqqwasPv8gtVh//f/4d/n/yDfg3+Hf+A36rA6tYN4Df7D/+//z+Q7/Ab9WB1axgN+/A6t/4NWKwG/3gdarBasO8gqrVgrVVZIf9/+QWqw//v/8O/z/5Bvwb/Dv/Ab9VgdWsG8Bv9h//f/5/Id/gN+rA6tYwG/fgdW/8GrFYDf7wOtVgtWHeQVVqrBqw+/yC1WH/9//h3+f/IN+Df4d/4DfqsDq1g3gN/sP/7//P5Dv8Bv9+CtVVkDqt/4d/h2KqwG/3gdWsYN4Df7wOq1Yd4dWDeA378P/7/8O/wbAb/fgdWwaqsPqyA36rA6rf4d4DfqrD/+//D6rFZ//Bv8GwVWqqwasPv8YLVh//f/4d/n/yDfg3+Hf+A36rA6tYN4Df7D/+//z+Q7/Ab9WB1axgN+/A6t/4NWKwG/3gdarBasO8gqrVgrVVZIf9/+MFqw//v/8O/z/5Bvwb/Dv/Ab9VgdWsG8Bv9h//f/5/Id/gN+rA6tYwG/fgdW/8GrFYDf7wOtVgtWHeQVVqrBqw+/xgtWH/9//h3+f/IN+Df4d/4DfqsDq1g3gN/sP/7//P5Dv8Bv9+CtVVkDqt/4d/h2KqwG/3gdWsYN4Df7wOq1Yd4dWDeA378P/7/8O/wbAb/fgdWwaqsPqyA36rA6rf4d4DfqrD/+//D6rFZ//Bv8GwVWqqwasPv8WC1h//f/4d/n/yDfg3+Hf+A36rA6tYN4Df7A6rZ/D6rILVWH1n/yA3sDq1jAb9+B1b/wasVgN/vA61WC1Yd5BVWrBWqqyQ/7/8WC1h//f/4d/n/yDfg3+Hf+A36rA6tYN4Df7A6rZ/D6rILVWH1n/yA3sDq1jAb9+B1b/wasVgN/vA61WC1Yd5BVWqsGrD7/FgtYf/3/+Hf5/8g34N/h3/gN+qwOrWDeA3+wOq2fw+qyC1Vh9Z/8gN/qqsFaqrIHVb/w7/DsVVgN/vA6tYwbwG/3gdVqw7w6sG8Bv34f/3/4d/g2A3+/A6tg1VYfVkBv1WB1W/w7wG/VWH/9/+H1WKz/+Df4NgqtVVg1Yff4rBbD/+//w7/P/kG/Bv8O/8Bv1WB1awbwG/2H/9//n8h3+A36sDq1jAb9+B1b/wasVgN/vA61WC1Yd5BVWrBWqqyQ/7/8Vgth//f/4d/n/yDfg3+Hf+A36rA6tYN4Df7D/+//z+Q7/Ab9WB1axgN+/A6t/4NWKwG/3gdarBasO8gqrVWDVh9/isFsP/7//Dv8/+Qb8G/w7/wG/VYHVrBvAb/Yf/3/+fyHf4Df78FaqrIHVb/w7/DsVVgN/vA6tYwbwG/3gdVqw7w6sG8Bv34f/3/4d/g2A3+/A6tg1VYfVkBv1WB1W/w7wG/VWH/9/+H1WKz/+Df4NgqtVVg1Yff4qwW8P/7//Dv8/+Qb8G/w7/wG/VYHVrBvAb/Yf/3/+fyHf4DfqwOrWMBv34HVv/BqxWA3+8DrVYLVh3kFVasFaqrJD/v/xVgt4f/3/+Hf5/8g34N/h3/gN+qwOrWDeA3+w//v/8/kO/wG/VgdWsYDfvwOrf+DVisBv94HWqwWrDvIKq1Vg1Yff4qwW8P/7//Dv8/+Qb8G/w7/wG/VYHVrBvAb/Yf/3/+fyHf4Df78FaqrIHVb/w7/DsVVgN/vA6tYwbwG/3gdVqw7w6sG8Bv34f/3/4d/g2A3+/A6tg1VYfVkBv1WB1W/w7wG/VWH/9/+H1WKz/+Df4NgqtVVg1Yff4qsFvw//v/8O/z/5Bvwb/Dv/Ab9VgdWsG8Bv9gdVs/h9VkBvYHVrGA378Dq3/g1YrAb/eB1qsFqw7yCqtWCtVVkh/3/4qsFvw//v/8O/z/5Bvwb/Dv/Ab9VgdWsG8Bv9gdVs/h9VkBvYHVrGA378Dq3/g1YrAb/eB1qsFqw7yCqtVYNWH3+KrBb8P/7//Dv8/+Qb8G/w7/wG/VYHVrBvAb/YHVbP4fVZAb/VVYK1VWQOq3/h3+HYqrAb/eB1axg3gN/vA6rVh3h1YN4Dfvw//v/w7/BsBv9+B1bBqqw+rIDfqsDqt/h3gN+qsP/7/8PqsVn/8G/wbBVaqrBqw+/xVWC3+H/9//h3+f/IN+Df4d/4DfqsDq1g3gN/sP/7//P5Dv8Bv1YHVrGA378Dq3/g1YrAb/eB1qsFqw7yCqtWCtVVkh/3/4qrBb/D/+//w7/P/kG/Bv8O/8Bv1WB1awbwG/2H/9//n8h3+A36sDq1jAb9+B1b/wasVgN/vA61WC1Yd5BVWqsGrD7/FVYLf4f/3/+Hf5/8g34N/h3/gN+qwOrWDeA3+w//v/8/kO/wG/34K1VWQOq3/h3+HYqrAb/eB1axg3gN/vA6rVh3h1YN4Dfvw//v/w7/BsBv9+B1bBqqw+rIDfqsDqt/h3gN+qsP/7/8PqsVn/8G/wbBVaqrBqw+/wb/BqqsP/7//Dv8/+Qb8G/w7/wG/VYHVrBvAb/Yf/3/+H1n/yA3sDq1jAb9+B1b/wasVgN/vA61WC1Yd5BVWrBWqqyQ/7/8G/waqrD/+//w7/P/kG/Bv8O/8Bv1WB1awbwG/2H/9//h9Z/8gN7A6tYwG/fgdW/8GrFYDf7wOtVgtWHeQVVqrBqw+/wb/BqqsP/7//Dv8/+Qb8G/w7/wG/VYHVrBvAb/Yf/3/+H1n/yA3+qqwVqqsgdVv/Dv8OxVWA3+8Dq1jBvAb/eB1WrDvDqwbwG/fh//f/h3+DYDf78Dq2DVVh9WQG/VYHVb/DvAb9VYf/3/4fVYrP/4N/g2Cq1VWDVh9+fwWqrD/+//w7/P/kG/Bv8O/8Bv1WB1awbwG/2B1Wz+H1WQG9gdWsYDfvwOrf+DVisBv94HWqwWrDvIKq1YK1VWSH/f+fwWqrD/+//w7/P/kG/Bv8O/8Bv1WB1awbwG/2B1Wz+H1WQG9gdWsYDfvwOrf+DVisBv94HWqwWrDvIKq1Vg1Yffn8Fqqw//v/8O/z/5Bvwb/Dv/Ab9VgdWsG8Bv9gdVs/h9VkBv9VVgrVVZA6rf+Hf4diqsBv94HVrGDeA3+8DqtWHeHVg3gN+/D/+//Dv8GwG/34HVsGqrD6sgN+qwOq3+HeA36qw//v/w+qxWf/wb/BsFVqqsGrD78+C1Vh//f/4d/n/yDfg3+Hf+A36rA6tYN4Df7D/+//z+Q7/Ab9WB1axgN+/A6t/4NWKwG/3gdarBasO8gqrVgrVVZIf9/58FqrD/+//w7/P/kG/Bv8O/8Bv1WB1awbwG/2H/9//n8h3+A36sDq1jAb9+B1b/wasVgN/vA61WC1Yd5BVWqsGrD78+C1Vh//f/4d/n/yDfg3+Hf+A36rA6tYN4Df7D/+//z+Q7/Ab/fgrVVZA6rf+Hf4diqsBv94HVrGDeA3+8DqtWHeHVg3gN+/D/+//Dv8GwG/34HVsGqrD6sgN+qwOq3+HeA36qw//v/w+qxWf/wb/BsFVqqsGrD784LVYf/3/+Hf5/8g34N/h3/gN+qwOrWDeA3+w//v/8/kO/wG/VgdWsYDfvwOrf+DVisBv94HWqwWrDvIKq1YK1VWSH/f+cFqsP/7//Dv8/+Qb8G/w7/wG/VYHVrBvAb/Yf/3/+fyHf4DfqwOrWMBv34HVv/BqxWA3+8DrVYLVh3kFVaqwasPvzgtVh//f/4d/n/yDfg3+Hf+A36rA6tYN4Df7D/+//z+Q7/Ab/fgrVVZA6rf+Hf4diqsBv94HVrGDeA3+8DqtWHeHVg3gN+/D/+//Dv8GwG/34HVsGqrD6sgN+qwOq3+HeA36qw//v/w+qxWf/wb/BsFVqqsGrD78gtWH/9//h3+f/IN+Df4d/4DfqsDq1g3gN/sDqtn8PqsgN7A6tYwG/fgdW/8GrFYDf7wOtVgtWHeQVVqwVqqskP+/8gtWH/9//h3+f/IN+Df4d/4DfqsDq1g3gN/sDqtn8PqsgN7A6tYwG/fgdW/8GrFYDf7wOtVgtWHeQVVqrBqw+/ILVh//f/4d/n/yDfg3+Hf+A36rA6tYN4Df7A6rZ/D6rIDf6qrBWqqyB1W/8O/w7FVYDf7wOrWMG8Bv94HVasO8OrBvAb9+H/9/+Hf4NgN/vwOrYNVWH1ZAb9VgdVv8O8Bv1Vh//f/h9Vis//g3+DYKrVVYNWH34wWsP/7//Dv8/+Qb8G/w7/wG/VYHVrBvAb/Yf/3/+H1n/yA3sDq1jAb9+B1b/wasVgN/vA61WC1Yd5BVWrBWqqyQ/7/xgtYf/3/+Hf5/8g34N/h3/gN+qwOrWDeA3+w//v/8PrP/kBvYHVrGA378Dq3/g1YrAb/eB1qsFqw7yCqtVYNWH34wWsP/7//Dv8/+Qb8G/w7/wG/VYHVrBvAb/Yf/3/+H1n/yA3+qqwVqqsgdVv/Dv8OxVWA3+8Dq1jBvAb/eB1WrDvDqwbwG/fh//f/h3+DYDf78Dq2DVVh9WQG/VYHVb/DvAb9VYf/3/4fVYrP/4N/g2Cq1VWDVh9+LBbD/+//w7/P/kG/Bv8O/8Bv1WB1awbwG/2H/9//n8h3+A36sDq1jAb9+B1b/wasVgN/vA61WC1Yd5BVWrBWqqyQ/7/xYLYf/3/+Hf5/8g34N/h3/gN+qwOrWDeA3+w//v/8/kO/wG/VgdWsYDfvwOrf+DVisBv94HWqwWrDvIKq1Vg1YffiwWw//v/8O/z/5Bvwb/Dv/Ab9VgdWsG8Bv9h//f/5/Id/gN/vwVqqsgdVv/Dv8OxVWA3+8Dq1jBvAb/eB1WrDvDqwbwG/fh//f/h3+DYDf78Dq2DVVh9WQG/VYHVb/DvAb9VYf/3/4fVYrP/4N/g2Cq1VWDVh9+KwW8P/7//Dv8/+Qb8G/w7/wG/VYHVrBvAb/YHVbP4fVZAb2B1axgN+/A6t/4NWKwG/3gdarBasO8gqrVgrVVZIf9/4rBbw//v/8O/z/5Bvwb/Dv/Ab9VgdWsG8Bv9gdVs/h9VkBvYHVrGA378Dq3/g1YrAb/eB1qsFqw7yCqtVYNWH34rBbw//v/8O/z/5Bvwb/Dv/Ab9VgdWsG8Bv9gdVs/h9VkBv9VVgrVVZA6rf+Hf4diqsBv94HVrGDeA3+8DqtWHeHVg3gN+/D/+//Dv8GwG/34HVsGqrD6sgN+qwOq3+HeA36qw//v/w+qxWf/wb/BsFVqqsGrD78VYLfh//f/4d/n/yDfg3+Hf+A36rA6tYN4Df7D/+//z+Q7/Ab9WB1axgN+/A6t/4NWKwG/3gdarBasO8gqrVgrVVZIf9/4qwW/D/+//w7/P/kG/Bv8O/8Bv1WB1awbwG/2H/9//n8h3+A36sDq1jAb9+B1b/wasVgN/vA61WC1Yd5BVWqsGrD78VYLfh//f/4d/n/yDfg3+Hf+A36rA6tYN4Df7D/+//z+Q7/Ab/fgrVVZA6rf+Hf4diqsBv94HVrGDeA3+8DqtWHeHVg3gN+/D/+//Dv8GwG/34HVsGqrD6sgN+qwOq3+HeA36qw//v/w+qxWf/wb/BsFVqqsGrD78VWC3+H/9//h3+f/IN+Df4d/4DfqsDq1g3gN/sP/7//P5Dv8Bv1YHVrGA378Dq3/g1YrAb/eB1qsFqw7yCqtWCtVVkh/3/iqwW/w//v/8O/z/5Bvwb/Dv/Ab9VgdWsG8Bv9h//f/5/Id/gN+rA6tYwG/fgdW/8GrFYDf7wOtVgtWHeQVVqrBqw+/FVgt/h//f/4d/n/yDfg3+Hf+A36rA6tYN4Df7D/+//z+Q7/Ab/fgrVVZA6rf+Hf4diqsBv94HVrGDeA3+8DqtWHeHVg3gN+/D/+//Dv8GwG/34HVsGqrD6sgN+qwOq3+HeA36qw//v/w+qxWf/wb/BsFVqqsGrD78VVg1VWH/9//h3+f/IN+Df4d/4DfqsDq1g3gN/sDqtn8PqsgtVYfWf/IDewOrWMBv34HVv/BqxWA3+8DrVYLVh3kFVasFaqrJD/v/FVYNVVh//f/4d/n/yDfg3+Hf+A36rA6tYN4Df7A6rZ/D6rILVWH1n/yA3sDq1jAb9+B1b/wasVgN/vA61WC1Yd5BVWqsGrD78VVg1VWH/9//h3+f/IN+Df4d/4DfqsDq1g3gN/sDqtn8PqsgtVYfWf/IDf6qrBWqqyB1W/8O/w7FVYDf7wOrWMG8Bv94HVasO8OrBvAb9+H/9/+Hf4NgN/vwOrYNVWH1ZAb9VgdVv8O8Bv1Vh//f/h9Vis//g3+DYKrVVYNWH3n/BaqsP/7//Dv8/+Qb8G/w7/wG/VYHVrBvAb/Yf/3/+fyHf4DfqwOrWMBv34HVv/BqxWA3+8DrVYLVh3kFVasFaqrJD/v8/4LVVh//f/4d/n/yDfg3+Hf+A36rA6tYN4Df7D/+//z+Q7/Ab9WB1axgN+/A6t/4NWKwG/3gdarBasO8gqrVWDVh95/wWqrD/+//w7/P/kG/Bv8O/8Bv1WB1awbwG/2H/9//n8h3+A3+/BWqqyB1W/8O/w7FVYDf7wOrWMG8Bv94HVasO8OrBvAb9+H/9/+Hf4NgN/vwOrYNVWH1ZAb9VgdVv8O8Bv1Vh//f/h9Vis//g3+DYKrVVYNWH3n8FqrD/+//w7/P/kG/Bv8O/8Bv1WB1awbwG/2H/9//n8h3+A36sDq1jAb9+B1b/wasVgN/vA61WC1Yd5BVWrBWqqyQ/7/P4LVWH/9//h3+f/IN+Df4d/4DfqsDq1g3gN/sP/7//P5Dv8Bv1YHVrGA378Dq3/g1YrAb/eB1qsFqw7yCqtVYNWH3n8FqrD/+//w7/P/kG/Bv8O/8Bv1WB1awbwG/2H/9//n8h3+A3+/BWqqyB1W/8O/w7FVYDf7wOrWMG8Bv94HVasO8OrBvAb9+H/9/+Hf4NgN/vwOrYNVWH1ZAb9VgdVv8O8Bv1Vh//f/h9Vis//g3+DYKrVVYNWH3nwWqw//v/8O/z/5Bvwb/Dv/Ab9VgdWsG8Bv9gdVs/h9VkBvYHVrGA378Dq3/g1YrAb/eB1qsFqw7yCqtWCtVVkh/3+fBarD/+//w7/P/kG/Bv8O/8Bv1WB1awbwG/2B1Wz+H1WQG9gdWsYDfvwOrf+DVisBv94HWqwWrDvIKq1Vg1YfefBarD/+//w7/P/kG/Bv8O/8Bv1WB1awbwG/2B1Wz+H1WQG/1VWCtVVkDqt/4d/h2KqwG/3gdWsYN4Df7wOq1Yd4dWDeA378P/7/8O/wbAb/fgdWwaqsPqyA36rA6rf4d4DfqrD/+//D6rFZ//Bv8GwVWqqwasPvOC1Yf/3/+Hf5/8g34N/h3/gN+qwOrWDeA3+w//v/8/kO/wG/VgdWsYDfvwOrf+DVisBv94HWqwWrDvIKq1YK1VWSH/f5wWrD/+//w7/P/kG/Bv8O/8Bv1WB1awbwG/2H/9//n8h3+A36sDq1jAb9+B1b/wasVgN/vA61WC1Yd5BVWqsGrD7zgtWH/9//h3+f/IN+Df4d/4DfqsDq1g3gN/sP/7//P5Dv8Bv9+CtVVkDqt/4d/h2KqwG/3gdWsYN4Df7wOq1Yd4dWDeA378P/7/8O/wbAb/fgdWwaqsPqyA36rA6rf4d4DfqrD/+//D6rFZ//Bv8GwVWqqwasPvILWH/9//h3+f/IN+Df4d/4DfqsDq1g3gN/sP/7//D6z/5Ab2B1axgN+/A6t/4NWKwG/3gdarBasO8gqrVgrVVZIf9/kFrD/+//w7/P/kG/Bv8O/8Bv1WB1awbwG/2H/9//h9Z/8gN7A6tYwG/fgdW/8GrFYDf7wOtVgtWHeQVVqrBqw+8gtYf/3/+Hf5/8g34N/h3/gN+qwOrWDeA3+w//v/8PrP/kBv9VVgrVVZA6rf+Hf4diqsBv94HVrGDeA3+8DqtWHeHVg3gN+/D/+//Dv8GwG/34HVsGqrD6sgN+qwOq3+HeA36qw//v/w+qxWf/wb/BsFVqqsGrD7xgth//f/4d/n/yDfg3+Hf+A36rA6tYN4Df7A6rZ/D6rIDewOrWMBv34HVv/BqxWA3+8DrVYLVh3kFVasFaqrJD/v8YLYf/3/+Hf5/8g34N/h3/gN+qwOrWDeA3+wOq2fw+qyA3sDq1jAb9+B1b/wasVgN/vA61WC1Yd5BVWqsGrD7xgth//f/4d/n/yDfg3+Hf+A36rA6tYN4Df7A6rZ/D6rIDf6qrBWqqyB1W/8O/w7FVYDf7wOrWMG8Bv94HVasO8OrBvAb9+H/9/+Hf4NgN/vwOrYNVWH1ZAb9VgdVv8O8Bv1Vh//f/h9Vis//g3+DYKrVVYNWH3iwW8P/7//Dv8/+Qb8G/w7/wG/VYHVrBvAb/Yf/3/+fyHf4DfqwOrWMBv34HVv/BqxWA3+8DrVYLVh3kFVasFaqrJD/v8WC3h//f/4d/n/yDfg3+Hf+A36rA6tYN4Df7D/+//z+Q7/Ab9WB1axgN+/A6t/4NWKwG/3gdarBasO8gqrVWDVh94sFvD/+//w7/P/kG/Bv8O/8Bv1WB1awbwG/2H/9//n8h3+A3+/BWqqyB1W/8O/w7FVYDf7wOrWMG8Bv94HVasO8OrBvAb9+H/9/+Hf4NgN/vwOrYNVWH1ZAb9VgdVv8O8Bv1Vh//f/h9Vis//g3+DYKrVVYNWH3isFvw//v/8O/z/5Bvwb/Dv/Ab9VgdWsG8Bv9h//f/5/Id/gN+rA6tYwG/fgdW/8GrFYDf7wOtVgtWHeQVVqwVqqskP+/xWC34f/3/+Hf5/8g34N/h3/gN+qwOrWDeA3+w//v/8/kO/wG/VgdWsYDfvwOrf+DVisBv94HWqwWrDvIKq1Vg1YfeKwW/D/+//w7/P/kG/Bv8O/8Bv1WB1awbwG/2H/9//n8h3+A3+/BWqqyB1W/8O/w7FVYDf7wOrWMG8Bv94HVasO8OrBvAb9+H/9/+Hf4NgN/vwOrYNVWH1ZAb9VgdVv8O8Bv1Vh//f/h9Vis//g3+DYKrVVYNWH3irBb/D/+//w7/P/kG/Bv8O/8Bv1WB1awbwG/2B1Wz+H1WQG9gdWsYDfvwOrf+DVisBv94HWqwWrDvIKq1YK1VWSH/f4qwW/w//v/8O/z/5Bvwb/Dv/Ab9VgdWsG8Bv9gdVs/h9VkBvYHVrGA378Dq3/g1YrAb/eB1qsFqw7yCqtVYNWH3irBb/D/+//w7/P/kG/Bv8O/8Bv1WB1awbwG/2B1Wz+H1WQG/1VWCtVVkDqt/4d/h2KqwG/3gdWsYN4Df7wOq1Yd4dWDeA378P/7/8O/wbAb/fgdWwaqsPqyA36rA6rf4d4DfqrD/+//D6rFZ//Bv8GwVWqqwasPvFVg1VWH/9//h3+f/IN+Df4d/4DfqsDq1g3gN/sP/7//D6z/5Ab2B1axgN+/A6t/4NWKwG/3gdarBasO8gqrVgrVVZIf9/iqwaqrD/+//w7/P/kG/Bv8O/8Bv1WB1awbwG/2H/9//h9Z/8gN7A6tYwG/fgdW/8GrFYDf7wOtVgtWHeQVVqrBqw+8VWDVVYf/3/+Hf5/8g34N/h3/gN+qwOrWDeA3+w//v/8PrP/kBv9VVgrVVZA6rf+Hf4diqsBv94HVrGDeA3+8DqtWHeHVg3gN+/D/+//Dv8GwG/34HVsGqrD6sgN+qwOq3+HeA36qw//v/w+qxWf/wb/BsFVqqsGrD7P/gtVWH/9//h3+f/IN+Df4d/4DfqsDq1g3gN/sP/7//P5Dv8Bv1YHVrGA378Dq3/g1YrAb/eB1qsFqw7yCqtWCtVVkh/35/8Fqqw//v/8O/z/5Bvwb/Dv/Ab9VgdWsG8Bv9h//f/5/Id/gN+rA6tYwG/fgdW/8GrFYDf7wOtVgtWHeQVVqrBqw+z/4LVVh//f/4d/n/yDfg3+Hf+A36rA6tYN4Df7D/+//z+Q7/Ab/fgrVVZA6rf+Hf4diqsBv94HVrGDeA3+8DqtWHeHVg3gN+/D/+//Dv8GwG/34HVsGqrD6sgN+qwOq3+HeA36qw//v/w+qxWf/wb/BsFVqqsGrD7P+C1Vh//f/4d/n/yDfg3+Hf+A36rA6tYN4Df7A6rZ/D6rIDewOrWMBv34HVv/BqxWA3+8DrVYLVh3kFVasFaqrJD/vz/gtVYf/3/+Hf5/8g34N/h3/gN+qwOrWDeA3+wOq2fw+qyA3sDq1jAb9+B1b/wasVgN/vA61WC1Yd5BVWqsGrD7P+C1Vh//f/4d/n/yDfg3+Hf+A36rA6tYN4Df7A6rZ/D6rIDf6qrBWqqyB1W/8O/w7FVYDf7wOrWMG8Bv94HVasO8OrBvAb9+H/9/+Hf4NgN/vwOrYNVWH1ZAb9VgdVv8O8Bv1Vh//f/h9Vis//g3+DYKrVVYNWH2fwWqw//v/8O/z/5Bvwb/Dv/Ab9VgdWsG8Bv9h//f/5/Id/gN+rA6tYwG/fgdW/8GrFYDf7wOtVgtWHeQVVqwVqqskP+/P4LVYf/3/+Hf5/8g34N/h3/gN+qwOrWDeA3+w//v/8/kO/wG/VgdWsYDfvwOrf+DVisBv94HWqwWrDvIKq1Vg1YfZ/BarD/+//w7/P/kG/Bv8O/8Bv1WB1awbwG/2H/9//n8h3+A3+/BWqqyB1W/8O/w7FVYDf7wOrWMG8Bv94HVasO8OrBvAb9+H/9/+Hf4NgN/vwOrYNVWH1ZAb9VgdVv8O8Bv1Vh//f/h9Vis//g3+DYKrVVYNWH2fBasP/7//Dv8/+Qb8G/w7/wG/VYHVrBvAb/Yf/3/+fyHf4DfqwOrWMBv34HVv/BqxWA3+8DrVYLVh3kFVasFaqrJD/vz4LVh//f/4d/n/yDfg3+Hf+A36rA6tYN4Df7D/+//z+Q7/Ab9WB1axgN+/A6t/4NWKwG/3gdarBasO8gqrVWDVh9nwWrD/+//w7/P/kG/Bv8O/8Bv1WB1awbwG/2H/9//n8h3+A3+/BWqqyB1W/8O/w7FVYDf7wOrWMG8Bv94HVasO8OrBvAb9+H/9/+Hf4NgN/vwOrYNVWH1ZAb9VgdVv8O8Bv1Vh//f/h9Vis//g3+DYKrVVYNWH2cFrD/+//w7/P/kG/Bv8O/8Bv1WB1awbwG/2B1Wz+H1WQWqsPrP/kBvYHVrGA378Dq3/g1YrAb/eB1qsFqw7yCqtWCtVVkh/35wWsP/7//Dv8/+Qb8G/w7/wG/VYHVrBvAb/YHVbP4fVZBaqw+s/+QG9gdWsYDfvwOrf+DVisBv94HWqwWrDvIKq1Vg1YfZwWsP/7//Dv8/+Qb8G/w7/wG/VYHVrBvAb/YHVbP4fVZBaqw+s/+QG/1VWCtVVkDqt/4d/h2KqwG/3gdWsYN4Df7wOq1Yd4dWDeA378P/7/8O/wbAb/fgdWwaqsPqyA36rA6rf4d4DfqrD/+//D6rFZ//Bv8GwVWqqwasPsgth//f/4d/n/yDfg3+Hf+A36rA6tYN4Df7D/+//z+Q7/Ab9WB1axgN+/A6t/4NWKwG/3gdarBasO8gqrVgrVVZIf9+QWw//v/8O/z/5Bvwb/Dv/Ab9VgdWsG8Bv9h//f/5/Id/gN+rA6tYwG/fgdW/8GrFYDf7wOtVgtWHeQVVqrBqw+yC2H/9//h3+f/IN+Df4d/4DfqsDq1g3gN/sP/7//P5Dv8Bv9+CtVVkDqt/4d/h2KqwG/3gdWsYN4Df7wOq1Yd4dWDeA378P/7/8O/wbAb/fgdWwaqsPqyA36rA6rf4d4DfqrD/+//D6rFZ//Bv8GwVWqqwasPsYLeH/9//h3+f/IN+Df4d/4DfqsDq1g3gN/sP/7//P5Dv8Bv1YHVrGA378Dq3/g1YrAb/eB1qsFqw7yCqtWCtVVkh/34wW8P/7//Dv8/+Qb8G/w7/wG/VYHVrBvAb/Yf/3/+fyHf4DfqwOrWMBv34HVv/BqxWA3+8DrVYLVh3kFVaqwasPsYLeH/9//h3+f/IN+Df4d/4DfqsDq1g3gN/sP/7//P5Dv8Bv9+CtVVkDqt/4d/h2KqwG/3gdWsYN4Df7wOq1Yd4dWDeA378P/7/8O/wbAb/fgdWwaqsPqyA36rA6rf4d4DfqrD/+//D6rFZ//Bv8GwVWqqwasPsWC34f/3/+Hf5/8g34N/h3/gN+qwOrWDeA3+wOq2fw+qyA3sDq1jAb9+B1b/wasVgN/vA61WC1Yd5BVWrBWqqyQ/78WC34f/3/+Hf5/8g34N/h3/gN+qwOrWDeA3+wOq2fw+qyA3sDq1jAb9+B1b/wasVgN/vA61WC1Yd5BVWqsGrD7Fgt+H/9//h3+f/IN+Df4d/4DfqsDq1g3gN/sDqtn8PqsgN/qqsFaqrIHVb/w7/DsVVgN/vA6tYwbwG/3gdVqw7w6sG8Bv34f/3/4d/g2A3+/A6tg1VYfVkBv1WB1W/w7wG/VWH/9/+H1WKz/+Df4NgqtVVg1YfYrBb/D/+//w7/P/kG/Bv8O/8Bv1WB1awbwG/2H/9//n8h3+A36sDq1jAb9+B1b/wasVgN/vA61WC1Yd5BVWrBWqqyQ/78Vgt/h//f/4d/n/yDfg3+Hf+A36rA6tYN4Df7D/+//z+Q7/Ab9WB1axgN+/A6t/4NWKwG/3gdarBasO8gqrVWDVh9isFv8P/7//Dv8/+Qb8G/w7/wG/VYHVrBvAb/Yf/3/+fyHf4Df78FaqrIHVb/w7/DsVVgN/vA6tYwbwG/3gdVqw7w6sG8Bv34f/3/4d/g2A3+/A6tg1VYfVkBv1WB1W/w7wG/VWH/9/+H1WKz/+Df4NgqtVVg1YfYqwaqrD/+//w7/P/kG/Bv8O/8Bv1WB1awbwG/2H/9//h9Z/8gN7A6tYwG/fgdW/8GrFYDf7wOtVgtWHeQVVqwVqqskP+/FWDVVYf/3/+Hf5/8g34N/h3/gN+qwOrWDeA3+w//v/8PrP/kBvYHVrGA378Dq3/g1YrAb/eB1qsFqw7yCqtVYNWH2KsGqqw//v/8O/z/5Bvwb/Dv/Ab9VgdWsG8Bv9h//f/4fWf/IDf6qrBWqqyB1W/8O/w7FVYDf7wOrWMG8Bv94HVasO8OrBvAb9+H/9/+Hf4NgN/vwOrYNVWH1ZAb9VgdVv8O8Bv1Vh//f/h9Vis//g3+DYKrVVYNWH1n/8Fqqw//v/8O/z/5Bvwb/Dv/Ab9VgdWsG8Bv9gdVs/h9VkBvYHVrGA378Dq3/g1YrAb/eB1qsFqw7yCqtWCtVVkh/3n/8Fqqw//v/8O/z/5Bvwb/Dv/Ab9VgdWsG8Bv9gdVs/h9VkBvYHVrGA378Dq3/g1YrAb/eB1qsFqw7yCqtVYNWH1n/8Fqqw//v/8O/z/5Bvwb/Dv/Ab9VgdWsG8Bv9gdVs/h9VkBv9VVgrVVZA6rf+Hf4diqsBv94HVrGDeA3+8DqtWHeHVg3gN+/D/+//Dv8GwG/34HVsGqrD6sgN+qwOq3+HeA36qw//v/w+qxWf/wb/BsFVqqsGrD6z/4LVWH/9//h3+f/IN+Df4d/4DfqsDq1g3gN/sP/7//P5Dv8Bv1YHVrGA378Dq3/g1YrAb/eB1qsFqw7yCqtWCtVVkh/3n/wWqsP/7//Dv8/+Qb8G/w7/wG/VYHVrBvAb/Yf/3/+fyHf4DfqwOrWMBv34HVv/BqxWA3+8DrVYLVh3kFVaqwasPrP/gtVYf/3/+Hf5/8g34N/h3/gN+qwOrWDeA3+w//v/8/kO/wG/34K1VWQOq3/h3+HYqrAb/eB1axg3gN/vA6rVh3h1YN4Dfvw//v/w7/BsBv9+B1bBqqw+rIDfqsDqt/h3gN+qsP/7/8PqsVn/8G/wbBVaqrBqw+s/4LVYf/3/+Hf5/8g34N/h3/gN+qwOrWDeA3+w//v/8/kO/wG/VgdWsYDfvwOrf+DVisBv94HWqwWrDvIKq1YK1VWSH/ef8FqsP/7//Dv8/+Qb8G/w7/wG/VYHVrBvAb/Yf/3/+fyHf4DfqwOrWMBv34HVv/BqxWA3+8DrVYLVh3kFVaqwasPrP+C1WH/9//h3+f/IN+Df4d/4DfqsDq1g3gN/sP/7//P5Dv8Bv9+CtVVkDqt/4d/h2KqwG/3gdWsYN4Df7wOq1Yd4dWDeA378P/7/8O/wbAb/fgdWwaqsPqyA36rA6rf4d4DfqrD/+//D6rFZ//Bv8GwVWqqwasPrP4LVh//f/4d/n/yDfg3+Hf+A36rA6tYN4Df7A6rZ/D6rIDewOrWMBv34HVv/BqxWA3+8DrVYLVh3kFVasFaqrJD/vP4LVh//f/4d/n/yDfg3+Hf+A36rA6tYN4Df7A6rZ/D6rIDewOrWMBv34HVv/BqxWA3+8DrVYLVh3kFVaqwasPrP4LVh//f/4d/n/yDfg3+Hf+A36rA6tYN4Df7A6rZ/D6rIDf6qrBWqqyB1W/8O/w7FVYDf7wOrWMG8Bv94HVasO8OrBvAb9+H/9/+Hf4NgN/vwOrYNVWH1ZAb9VgdVv8O8Bv1Vh//f/h9Vis//g3+DYKrVVYNWH1nwWsP/7//Dv8/+Qb8G/w7/wG/VYHVrBvAb/Yf/3/+H1n/yA3sDq1jAb9+B1b/wasVgN/vA61WC1Yd5BVWrBWqqyQ/7z4LWH/9//h3+f/IN+Df4d/4DfqsDq1g3gN/sP/7//D6z/5Ab2B1axgN+/A6t/4NWKwG/3gdarBasO8gqrVWDVh9Z8FrD/+//w7/P/kG/Bv8O/8Bv1WB1awbwG/2H/9//h9Z/8gN/qqsFaqrIHVb/w7/DsVVgN/vA6tYwbwG/3gdVqw7w6sG8Bv34f/3/4d/g2A3+/A6tg1VYfVkBv1WB1W/w7wG/VWH/9/+H1WKz/+Df4NgqtVVg1YfWcFsP/7//Dv8/+Qb8G/w7/wG/VYHVrBvAb/Yf/3/+fyHf4DfqwOrWMBv34HVv/BqxWA3+8DrVYLVh3kFVasFaqrJD/vOC2H/9//h3+f/IN+Df4d/4DfqsDq1g3gN/sP/7//P5Dv8Bv1YHVrGA378Dq3/g1YrAb/eB1qsFqw7yCqtVYNWH1nBbD/+//w7/P/kG/Bv8O/8Bv1WB1awbwG/2H/9//n8h3+A3+/BWqqyB1W/8O/w7FVYDf7wOrWMG8Bv94HVasO8OrBvAb9+H/9/+Hf4NgN/vwOrYNVWH1ZAb9VgdVv8O8Bv1Vh//f/h9Vis//g3+DYKrVVYNWH1kFvD/+//w7/P/kG/Bv8O/8Bv1WB1awbwG/2B1Wz+H1WQG9gdWsYDfvwOrf+DVisBv94HWqwWrDvIKq1YK1VWSH/eQW8P/7//Dv8/+Qb8G/w7/wG/VYHVrBvAb/YHVbP4fVZAb2B1axgN+/A6t/4NWKwG/3gdarBasO8gqrVWDVh9ZBbw//v/8O/z/5Bvwb/Dv/Ab9VgdWsG8Bv9gdVs/h9VkBv9VVgrVVZA6rf+Hf4diqsBv94HVrGDeA3+8DqtWHeHVg3gN+/D/+//Dv8GwG/34HVsGqrD6sgN+qwOq3+HeA36qw//v/w+qxWf/wb/BsFVqqsGrD6xgt+H/9//h3+f/IN+Df4d/4DfqsDq1g3gN/sP/7//P5Dv8Bv1YHVrGA378Dq3/g1YrAb/eB1qsFqw7yCqtWCtVVkh/3jBb8P/7//Dv8/+Qb8G/w7/wG/VYHVrBvAb/Yf/3/+fyHf4DfqwOrWMBv34HVv/BqxWA3+8DrVYLVh3kFVaqwasPrGC34f/3/+Hf5/8g34N/h3/gN+qwOrWDeA3+w//v/8/kO/wG/34K1VWQOq3/h3+HYqrAb/eB1axg3gN/vA6rVh3h1YN4Dfvw//v/w7/BsBv9+B1bBqqw+rIDfqsDqt/h3gN+qsP/7/8PqsVn/8G/wbBVaqrBqw+sWC3+H/9//h3+f/IN+Df4d/4DfqsDq1g3gN/sP/7//P5Dv8Bv1YHVrGA378Dq3/g1YrAb/eB1qsFqw7yCqtWCtVVkh/3iwW/w//v/8O/z/5Bvwb/Dv/Ab9VgdWsG8Bv9h//f/5/Id/gN+rA6tYwG/fgdW/8GrFYDf7wOtVgtWHeQVVqrBqw+sWC3+H/9//h3+f/IN+Df4d/4DfqsDq1g3gN/sP/7//P5Dv8Bv9+CtVVkDqt/4d/h2KqwG/3gdWsYN4Df7wOq1Yd4dWDeA378P/7/8O/wbAb/fgdWwaqsPqyA36rA6rf4d4DfqrD/+//D6rFZ//Bv8GwVWqqwasPrFYNVVh//f/4d/n/yDfg3+Hf+A36rA6tYN4Df7A6rZ/D6rILVWH1n/yA3sDq1jAb9+B1b/wasVgN/vA61WC1Yd5BVWrBWqqyQ/7xWDVVYf/3/+Hf5/8g34N/h3/gN+qwOrWDeA3+wOq2fw+qyC1Vh9Z/8gN7A6tYwG/fgdW/8GrFYDf7wOtVgtWHeQVVqrBqw+sVg1VWH/9//h3+f/IN+Df4d/4DfqsDq1g3gN/sDqtn8PqsgtVYfWf/IDf6qrBWqqyB1W/8O/w7FVYDf7wOrWMG8Bv94HVasO8OrBvAb9+H/9/+Hf4NgN/vwOrYNVWH1ZAb9VgdVv8O8Bv1Vh//f/h9Vis//g3+DYKrVVYNWH1YdVgtVWH/9//h3+f/IN+Df4d/4DfqsDq1g3gN/sP/7//P5Dv8Bv1YHVrGA378Dq3/g1YrAb/eB1qsFqw7yCqtWCtVVkh/2HVYLVVh//f/4d/n/yDfg3+Hf+A36rA6tYN4Df7D/+//z+Q7/Ab9WB1axgN+/A6t/4NWKwG/3gdarBasO8gqrVWDVh9WHVYLVVh//f/4d/n/yDfg3+Hf+A36rA6tYN4Df7D/+//z+Q7/Ab/fgrVVZA6rf+Hf4diqsBv94HVrGDeA3+8DqtWHeHVg3gN+/D/+//Dv8GwG/34HVsGqrD6sgN+qwOq3+HeA36qw//v/w+qxWf/wb/BsFVqqsGrD6s//gtVYf/3/+Hf5/8g34N/h3/gN+qwOrWDeA3+w//v/8/kO/wG/VgdWsYDfvwOrf+DVisBv94HWqwWrDvIKq1YK1VWSH/Z//Baqw//v/8O/z/5Bvwb/Dv/Ab9VgdWsG8Bv9h//f/5/Id/gN+rA6tYwG/fgdW/8GrFYDf7wOtVgtWHeQVVqrBqw+rP/4LVWH/9//h3+f/IN+Df4d/4DfqsDq1g3gN/sP/7//P5Dv8Bv9+CtVVkDqt/4d/h2KqwG/3gdWsYN4Df7wOq1Yd4dWDeA378P/7/8O/wbAb/fgdWwaqsPqyA36rA6rf4d4DfqrD/+//D6rFZ//Bv8GwVWqqwasPqz/4LVYf/3/+Hf5/8g34N/h3/gN+qwOrWDeA3+wOq2fw+qyA3sDq1jAb9+B1b/wasVgN/vA61WC1Yd5BVWrBWqqyQ/7P/gtVh//f/4d/n/yDfg3+Hf+A36rA6tYN4Df7A6rZ/D6rIDewOrWMBv34HVv/BqxWA3+8DrVYLVh3kFVaqwasPqz/4LVYf/3/+Hf5/8g34N/h3/gN+qwOrWDeA3+wOq2fw+qyA3+qqwVqqsgdVv/Dv8OxVWA3+8Dq1jBvAb/eB1WrDvDqwbwG/fh//f/h3+DYDf78Dq2DVVh9WQG/VYHVb/DvAb9VYf/3/4fVYrP/4N/g2Cq1VWDVh9Wf8Fqw//v/8O/z/5Bvwb/Dv/Ab9VgdWsG8Bv9h//f/5/Id/gN+rA6tYwG/fgdW/8GrFYDf7wOtVgtWHeQVVqwVqqskP+z/gtWH/9//h3+f/IN+Df4d/4DfqsDq1g3gN/sP/7//P5Dv8Bv1YHVrGA378Dq3/g1YrAb/eB1qsFqw7yCqtVYNWH1Z/wWrD/+//w7/P/kG/Bv8O/8Bv1WB1awbwG/2H/9//n8h3+A3+/BWqqyB1W/8O/w7FVYDf7wOrWMG8Bv94HVasO8OrBvAb9+H/9/+Hf4NgN/vwOrYNVWH1ZAb9VgdVv8O8Bv1Vh//f/h9Vis//g3+DYKrVVYNWH1Z/Baw//v/8O/z/5Bvwb/Dv/Ab9VgdWsG8Bv9h//f/4fWf/IDewOrWMBv34HVv/BqxWA3+8DrVYLVh3kFVasFaqrJD/s/gtYf/3/+Hf5/8g34N/h3/gN+qwOrWDeA3+w//v/8PrP/kBvYHVrGA378Dq3/g1YrAb/eB1qsFqw7yCqtVYNWH1Z/Baw//v/8O/z/5Bvwb/Dv/Ab9VgdWsG8Bv9h//f/4fWf/IDf6qrBWqqyB1W/8O/w7FVYDf7wOrWMG8Bv94HVasO8OrBvAb9+H/9/+Hf4NgN/vwOrYNVWH1ZAb9VgdVv8O8Bv1Vh//f/h9Vis//g3+DYKrVVYNWH1Z8FsP/7//Dv8/+Qb8G/w7/wG/VYHVrBvAb/YHVbP4fVZAb2B1axgN+/A6t/4NWKwG/3gdarBasO8gqrVgrVVZIf9nwWw//v/8O/z/5Bvwb/Dv/Ab9VgdWsG8Bv9gdVs/h9VkBvYHVrGA378Dq3/g1YrAb/eB1qsFqw7yCqtVYNWH1Z8FsP/7//Dv8/+Qb8G/w7/wG/VYHVrBvAb/YHVbP4fVZAb/VVYK1VWQOq3/h3+HYqrAb/eB1axg3gN/vA6rVh3h1YN4Dfvw//v/w7/BsBv9+B1bBqqw+rIDfqsDqt/h3gN+qsP/7/8PqsVn/8G/wbBVaqrBqw+rOC3h//f/4d/n/yDfg3+Hf+A36rA6tYN4Df7D/+//z+Q7/Ab9WB1axgN+/A6t/4NWKwG/3gdarBasO8gqrVgrVVZIf9nBbw//v/8O/z/5Bvwb/Dv/Ab9VgdWsG8Bv9h//f/5/Id/gN+rA6tYwG/fgdW/8GrFYDf7wOtVgtWHeQVVqrBqw+rOC3h//f/4d/n/yDfg3+Hf+A36rA6tYN4Df7D/+//z+Q7/Ab/fgrVVZA6rf+Hf4diqsBv94HVrGDeA3+8DqtWHeHVg3gN+/D/+//Dv8GwG/34HVsGqrD6sgN+qwOq3+HeA36qw//v/w+qxWf/wb/BsFVqqsGrD6sgt+H/9//h3+f/IN+Df4d/4DfqsDq1g3gN/sP/7//P5Dv8Bv1YHVrGA378Dq3/g1YrAb/eB1qsFqw7yCqtWCtVVkh/2QW/D/+//w7/P/kG/Bv8O/8Bv1WB1awbwG/2H/9//n8h3+A36sDq1jAb9+B1b/wasVgN/vA61WC1Yd5BVWqsGrD6sgt+H/9//h3+f/IN+Df4d/4DfqsDq1g3gN/sP/7//P5Dv8Bv9+CtVVkDqt/4d/h2KqwG/3gdWsYN4Df7wOq1Yd4dWDeA378P/7/8O/wbAb/fgdWwaqsPqyA36rA6rf4d4DfqrD/+//D6rFZ//Bv8GwVWqqwasPqxgt/h//f/4d/n/yDfg3+Hf+A36rA6tYN4Df7A6rZ/D6rIDewOrWMBv34HVv/BqxWA3+8DrVYLVh3kFVasFaqrJD/sYLf4f/3/+Hf5/8g34N/h3/gN+qwOrWDeA3+wOq2fw+qyA3sDq1jAb9+B1b/wasVgN/vA61WC1Yd5BVWqsGrD6sYLf4f/3/+Hf5/8g34N/h3/gN+qwOrWDeA3+wOq2fw+qyA3+qqwVqqsgdVv/Dv8OxVWA3+8Dq1jBvAb/eB1WrDvDqwbwG/fh//f/h3+DYDf78Dq2DVVh9WQG/VYHVb/DvAb9VYf/3/4fVYrP/4N/g2Cq1VWDVh9WLBqqsP/7//Dv8/+Qb8G/w7/wG/VYHVrBvAb/Yf/3/+H1n/yA3sDq1jAb9+B1b/wasVgN/vA61WC1Yd5BVWrBWqqyQ/7Fg1VWH/9//h3+f/IN+Df4d/4DfqsDq1g3gN/sP/7//D6z/5Ab2B1axgN+/A6t/4NWKwG/3gdarBasO8gqrVWDVh9WLBqqsP/7//Dv8/+Qb8G/w7/wG/VYHVrBvAb/Yf/3/+H1n/yA3+qqwVqqsgdVv/Dv8OxVWA3+8Dq1jBvAb/eB1WrDvDqwbwG/fh//f/h3+DYDf78Dq2DVVh9WQG/VYHVb/DvAb9VYf/3/4fVYrP/4N/g2Cq1VWDVh9Vh1YLVVh//f/4d/n/yDfg3+Hf+A36rA6tYN4Df7D/+//z+Q7/Ab9WB1axgN+/A6t/4NWKwG/3gdarBasO8gqrVgrVVZIf9YdWC1VYf/3/+Hf5/8g34N/h3/gN+qwOrWDeA3+w//v/8/kO/wG/VgdWsYDfvwOrf+DVisBv94HWqwWrDvIKq1Vg1YfVYdWC1VYf/3/+Hf5/8g34N/h3/gN+qwOrWDeA3+w//v/8/kO/wG/34K1VWQOq3/h3+HYqrAb/eB1axg3gN/vA6rVh3h1YN4Dfvw//v/w7/BsBv9+B1bBqqw+rIDfqsDqt/h3gN+qsP/7/8PqsVn/8G/wbBVaqrBqw+qw6rBaqw//v/8O/z/5Bvwb/Dv/Ab9VgdWsG8Bv9gdVs/h9VkBvYHVrGA378Dq3/g1YrAb/eB1qsFqw7yCqtWCtVVkh/1h1WC1Vh//f/4d/n/yDfg3+Hf+A36rA6tYN4Df7A6rZ/D6rIDewOrWMBv34HVv/BqxWA3+8DrVYLVh3kFVaqwasPqsOqwWqsP/7//Dv8/+Qb8G/w7/wG/VYHVrBvAb/YHVbP4fVZAb/VVYK1VWQOq3/h3+HYqrAb/eB1axg3gN/vA6rVh3h1YN4Dfvw//v/w7/BsBv9+B1bBqqw+rIDfqsDqt/h3gN+qsP/7/8PqsVn/8G/wbBVaqrBqw+qz/+C1WH/9//h3+f/IN+Df4d/4DfqsDq1g3gN/sP/7//P5Dv8Bv1YHVrGA378Dq3/g1YrAb/eB1qsFqw7yCqtWCtVVkh/1n/8FqsP/7//Dv8/+Qb8G/w7/wG/VYHVrBvAb/Yf/3/+fyHf4DfqwOrWMBv34HVv/BqxWA3+8DrVYLVh3kFVaqwasPqs//gtVh//f/4d/n/yDfg3+Hf+A36rA6tYN4Df7D/+//z+Q7/Ab/fgrVVZA6rf+Hf4diqsBv94HVrGDeA3+8DqtWHeHVg3gN+/D/+//Dv8GwG/34HVsGqrD6sgN+qwOq3+HeA36qw//v/w+qxWf/wb/BsFVqqsGrD6rP/gtWH/9//h3+f/IN+Df4d/4DfqsDq1g3gN/sP/7//P5Dv8Bv1YHVrGA378Dq3/g1YrAb/eB1qsFqw7yCqtWCtVVkh/1n/wWrD/+//w7/P/kG/Bv8O/8Bv1WB1awbwG/2H/9//n8h3+A36sDq1jAb9+B1b/wasVgN/vA61WC1Yd5BVWqsGrD6rP/gtWH/9//h3+f/IN+Df4d/4DfqsDq1g3gN/sP/7//P5Dv8Bv9+CtVVkDqt/4d/h2KqwG/3gdWsYN4Df7wOq1Yd4dWDeA378P/7/8O/wbAb/fgdWwaqsPqyA36rA6rf4d4DfqrD/+//D6rFZ//Bv8GwVWqqwasPqs/4LWH/9//h3+f/IN+Df4d/4DfqsDq1g3gN/sDqtn8PqsgtVYfWf/IDewOrWMBv34HVv/BqxWA3+8DrVYLVh3kFVasFaqrJD/rP+C1h//f/4d/n/yDfg3+Hf+A36rA6tYN4Df7A6rZ/D6rILVWH1n/yA3sDq1jAb9+B1b/wasVgN/vA61WC1Yd5BVWqsGrD6rP+C1h//f/4d/n/yDfg3+Hf+A36rA6tYN4Df7A6rZ/D6rILVWH1n/yA3+qqwVqqsgdVv/Dv8OxVWA3+8Dq1jBvAb/eB1WrDvDqwbwG/fh//f/h3+DYDf78Dq2DVVh9WQG/VYHVb/DvAb9VYf/3/4fVYrP/4N/g2Cq1VWDVh9Vn8FsP/7//Dv8/+Qb8G/w7/wG/VYHVrBvAb/Yf/3/+fyHf4DfqwOrWMBv34HVv/BqxWA3+8DrVYLVh3kFVasFaqrJD/rP4LYf/3/+Hf5/8g34N/h3/gN+qwOrWDeA3+w//v/8/kO/wG/VgdWsYDfvwOrf+DVisBv94HWqwWrDvIKq1Vg1YfVZ/BbD/+//w7/P/kG/Bv8O/8Bv1WB1awbwG/2H/9//n8h3+A3+/BWqqyB1W/8O/w7FVYDf7wOrWMG8Bv94HVasO8OrBvAb9+H/9/+Hf4NgN/vwOrYNVWH1ZAb9VgdVv8O8Bv1Vh//f/h9Vis//g3+DYKrVVYNWH1WfBbw//v/8O/z/5Bvwb/Dv/Ab9VgdWsG8Bv9h//f/5/Id/gN+rA6tYwG/fgdW/8GrFYDf7wOtVgtWHeQVVqwVqqskP+s+C3h//f/4d/n/yDfg3+Hf+A36rA6tYN4Df7D/+//z+Q7/Ab9WB1axgN+/A6t/4NWKwG/3gdarBasO8gqrVWDVh9VnwW8P/7//Dv8/+Qb8G/w7/wG/VYHVrBvAb/Yf/3/+fyHf4Df78FaqrIHVb/w7/DsVVgN/vA6tYwbwG/3gdVqw7w6sG8Bv34f/3/4d/g2A3+/A6tg1VYfVkBv1WB1W/w7wG/VWH/9/+H1WKz/+Df4NgqtVVg1YfVZwW/D/+//w7/P/kG/Bv8O/8Bv1WB1awbwG/2B1Wz+H1WQG9gdWsYDfvwOrf+DVisBv94HWqwWrDvIKq1YK1VWSH/WcFvw//v/8O/z/5Bvwb/Dv/Ab9VgdWsG8Bv9gdVs/h9VkBvYHVrGA378Dq3/g1YrAb/eB1qsFqw7yCqtVYNWH1WcFvw//v/8O/z/5Bvwb/Dv/Ab9VgdWsG8Bv9gdVs/h9VkBv9VVgrVVZA6rf+Hf4diqsBv94HVrGDeA3+8DqtWHeHVg3gN+/D/+//Dv8GwG/34HVsGqrD6sgN+qwOq3+HeA36qw//v/w+qxWf/wb/BsFVqqsGrD6rILf4f/3/+Hf5/8g34N/h3/gN+qwOrWDeA3+w//v/8/kO/wG/VgdWsYDfvwOrf+DVisBv94HWqwWrDvIKq1YK1VWSH/WQW/w//v/8O/z/5Bvwb/Dv/Ab9VgdWsG8Bv9h//f/5/Id/gN+rA6tYwG/fgdW/8GrFYDf7wOtVgtWHeQVVqrBqw+qyC3+H/9//h3+f/IN+Df4d/4DfqsDq1g3gN/sP/7//P5Dv8Bv9+CtVVkDqt/4d/h2KqwG/3gdWsYN4Df7wOq1Yd4dWDeA378P/7/8O/wbAb/fgdWwaqsPqyA36rA6rf4d4DfqrD/+//D6rFZ//Bv8GwVWqqwasPqsYNVVh//f/4d/n/yDfg3+Hf+A36rA6tYN4Df7D/+//w+s/+QG9gdWsYDfvwOrf+DVisBv94HWqwWrDvIKq1YK1VWSH/WMGqqw//v/8O/z/5Bvwb/Dv/Ab9VgdWsG8Bv9h//f/4fWf/IDewOrWMBv34HVv/BqxWA3+8DrVYLVh3kFVaqwasPqsYNVVh//f/4d/n/yDfg3+Hf+A36rA6tYN4Df7D/+//w+s/+QG/1VWCtVVkDqt/4d/h2KqwG/3gdWsYN4Df7wOq1Yd4dWDeA378P/7/8O/wbAb/fgdWwaqsPqyA36rA6rf4d4DfqrD/+//D6rFZ//Bv8GwVWqqwasPv/wWqrD/+//w7/P/kG/Bv8O/8Bv1WB1awbwG/2B1Wz+H1WQG9gdWsYDfvwOrf+DVisBv94HWqwWrDvIKq1YK1VWSH/1WC1VYf/3/+Hf5/8g34N/h3/gN+qwOrWDeA3+wOq2fw+qyA3sDq1jAb9+B1b/wasVgN/vA61WC1Yd5BVWqsGrD7/8Fqqw//v/8O/z/5Bvwb/Dv/Ab9VgdWsG8Bv9gdVs/h9VkBv9VVgrVVZA6rf+Hf4diqsBv94HVrGDeA3+8DqtWHeHVg3gN+/D/+//Dv8GwG/34HVsGqrD6sgN+qwOq3+HeA36qw//v/w+qxWf/wb/BsFVqqsGrD7/wWqsP/7//Dv8/+Qb8G/w7/wG/VYHVrBvAb/Yf/3/+fyHf4DfqwOrWMBv34HVv/BqxWA3+8DrVYLVh3kFVasFaqrJD/v/8FqrD/+//w7/P/kG/Bv8O/8Bv1WB1awbwG/2H/9//n8h3+A36sDq1jAb9+B1b/wasVgN/vA61WC1Yd5BVWqsGrD7/wWqsP/7//Dv8/+Qb8G/w7/wG/VYHVrBvAb/Yf/3/+fyHf4Df78FaqrIHVb/w7/DsVVgN/vA6tYwbwG/3gdVqw7w6sG8Bv34f/3/4d/g2A3+/A6tg1VYfVkBv1WB1W/w7wG/VWH/9/+H1WKz/+Df4NgqtVVg1Yff4LVYf/3/+Hf5/8g34N/h3/gN+qwOrWDeA3+w//v/8/kO/wG/VgdWsYDfvwOrf+DVisBv94HWqwWrDvIKq1YK1VWSH/f/gtVh//f/4d/n/yDfg3+Hf+A36rA6tYN4Df7D/+//z+Q7/Ab9WB1axgN+/A6t/4NWKwG/3gdarBasO8gqrVWDVh9/gtVh//f/4d/n/yDfg3+Hf+A36rA6tYN4Df7D/+//z+Q7/Ab/fgrVVZA6rf+Hf4diqsBv94HVrGDeA3+8DqtWHeHVg3gN+/D/+//Dv8GwG/34HVsGqrD6sgN+qwOq3+HeA36qw//v/w+qxWf/wb/BsFVqqsGrD78Fqw//v/8O/z/5Bvwb/Dv/Ab9VgdWsG8Bv9gdVs/h9VkBvYHVrGA378Dq3/g1YrAb/eB1qsFqw7yCqtWCtVVkh/3/gtWH/9//h3+f/IN+Df4d/4DfqsDq1g3gN/sDqtn8PqsgN7A6tYwG/fgdW/8GrFYDf7wOtVgtWHeQVVqrBqw+/BasP/7//Dv8/+Qb8G/w7/wG/VYHVrBvAb/YHVbP4fVZAb/VVYK1VWQOq3/h3+HYqrAb/eB1axg3gN/vA6rVh3h1YN4Dfvw//v/w7/BsBv9+B1bBqqw+rIDfqsDqt/h3gN+qsP/7/8PqsVn/8G/wbBVaqrBqw+8FrD/+//w7/P/kG/Bv8O/8Bv1WB1awbwG/2H/9//h9Z/8gN7A6tYwG/fgdW/8GrFYDf7wOtVgtWHeQVVqwVqqskP+/wWsP/7//Dv8/+Qb8G/w7/wG/VYHVrBvAb/Yf/3/+H1n/yA3sDq1jAb9+B1b/wasVgN/vA61WC1Yd5BVWqsGrD7wWsP/7//Dv8/+Qb8G/w7/wG/VYHVrBvAb/Yf/3/+H1n/yA3+qqwVqqsgdVv/Dv8OxVWA3+8Dq1jBvAb/eB1WrDvDqwbwG/fh//f/h3+DYDf78Dq2DVVh9WQG/VYHVb/DvAb9VYf/3/4fVYrP/4N/g2Cq1VWDVh9gth//f/4d/n/yDfg3+Hf+A36rA6tYN4Df7D/+//z+Q7/Ab9WB1axgN+/A6t/4NWKwG/3gdarBasO8gqrVgrVVZIf9+C2H/9//h3+f/IN+Df4d/4DfqsDq1g3gN/sP/7//P5Dv8Bv1YHVrGA378Dq3/g1YrAb/eB1qsFqw7yCqtVYNWH2C2H/9//h3+f/IN+Df4d/4DfqsDq1g3gN/sP/7//P5Dv8Bv9+CtVVkDqt/4d/h2KqwG/3gdWsYN4Df7wOq1Yd4dWDeA378P/7/8O/wbAb/fgdWwaqsPqyA36rA6rf4d4DfqrD/+//D6rFZ//Bv8GwVWqqwasPrBbw//v/8O/z/5Bvwb/Dv/Ab9VgdWsG8Bv9gdVs/h9VkBvYHVrGA378Dq3/g1YrAb/eB1qsFqw7yCqtWCtVVkh/3gt4f/3/+Hf5/8g34N/h3/gN+qwOrWDeA3+wOq2fw+qyA3sDq1jAb9+B1b/wasVgN/vA61WC1Yd5BVWqsGrD6wW8P/7//Dv8/+Qb8G/w7/wG/VYHVrBvAb/YHVbP4fVZAb/VVYK1VWQOq3/h3+HYqrAb/eB1axg3gN/vA6rVh3h1YN4Dfvw//v/w7/BsBv9+B1bBqqw+rIDfqsDqt/h3gN+qsP/7/8PqsVn/8G/wbBVaqrBqw+rBb8P/7//Dv8/+Qb8G/w7/wG/VYHVrBvAb/Yf/3/+fyHf4DfqwOrWMBv34HVv/BqxWA3+8DrVYLVh3kFVasFaqrJD/sFvw//v/8O/z/5Bvwb/Dv/Ab9VgdWsG8Bv9h//f/5/Id/gN+rA6tYwG/fgdW/8GrFYDf7wOtVgtWHeQVVqrBqw+rBb8P/7//Dv8/+Qb8G/w7/wG/VYHVrBvAb/Yf/3/+fyHf4Df78FaqrIHVb/w7/DsVVgN/vA6tYwbwG/3gdVqw7w6sG8Bv34f/3/4d/g2A3+/A6tg1VYfVkBv1WB1W/w7wG/VWH/9/+H1WKz/+Df4NgqtVVg1YfVYLf4f/3/+Hf5/8g34N/gN/vA6tYN4Df7D/+//z+Q7/Ab9WB1axgN+/A6t/4NWKwG/3gdarBasO8gqrVgrVVZIf9YLf4f/3/+Hf5/8g34N/gN/vA6tYN4Df7D/+//z+Q7/Ab9WB1axgN+/A6t/4NWKwG/3gdarBasO8gqrVWDVh9Vgt/h//f/4d/n/yDfg3+A3+8Dq1g3gN/sP/7//P5Dv8Bv9+CtVVkP/7w/7Ab94HVv/FVgN+8Dq3/g1YrAb/eB1b/OKrP4NVgN/vD/+//Dv8GwG/34f/3/+H1n/Ab3gdW/xViwb8Bv94HVqs+fwarBVW/wasPv/yC1VYf/3/+Hf5/8g34N/h3/gN+qwOrWDeA3+wOq2fw+qyA3sDq1jAb9+B1b/wasVgN/vA61WC1Yd5BVWrA)
Code is too long for answer.
] |
[Question]
[
A maze on an N by N grid of square cells is defined by specifying whether each edge is a wall or not a wall. All outer edges are walls. One cell is defined as the ***start***, and one cell is defined as the ***exit***, and the exit is reachable from the start. The start and exit are never the same cell.
Note that neither the start nor the exit need to be on the outer border of the maze, so this is a valid maze:
[![A 3 by 3 maze with the exit on the central cell](https://i.stack.imgur.com/90mwL.png "The start or exit can be in the centre")](https://i.stack.imgur.com/90mwL.png "The start or exit can be in the centre")
A string of 'N', 'E', 'S' and 'W' indicates attempting to move North, East, South and West respectively. A move that is blocked by a wall is skipped without movement. A string ***exits*** a maze if applying that string from the start results in the exit being reached (regardless of whether the string continues after reaching the exit).
Inspired by [this puzzling.SE question](https://puzzling.stackexchange.com/questions/18009/maze-solving-robot) for which [xnor](https://codegolf.stackexchange.com/users/20260/xnor) provided a [provable method of solving](https://puzzling.stackexchange.com/a/18010) with a *very* long string, write code that can find a single string that exits any 3 by 3 maze.
*Excluding invalid mazes (start and exit on the same cell, or exit not reachable from start) there are 138,172 valid mazes and the string must exit each of them.*
### Validity
The string must satisfy the following:
* It is composed of only the characters 'N', 'E', 'S' and 'W'.
* It exits any maze it is applied to, if started at the start.
Since the set of all possible mazes includes each possible maze with each possible valid starting point, this automatically means that the string will exit any maze from *any* valid starting point. That is, from any starting point from which the exit is reachable.
### Winning
The winner is the answer that provides the shortest valid string and includes the code used to produce it. If more than one of the answers provide a string of this shortest length, the first to post that string length wins.
### Example
Here is an example string 500 characters long, to give you something to beat:
```
SEENSSNESSWNNSNNNNWWNWENENNWEENSESSNENSESWENWWWWWENWNWWSESNSWENNWNWENWSSSNNNNNNESWNEWWWWWNNNSWESSEEWNENWENEENNEEESEENSSEENNWWWNWSWNSSENNNWESSESNWESWEENNWSNWWEEWWESNWEEEWWSSSESEEWWNSSEEEEESSENWWNNSWNENSESSNEESENEWSSNWNSEWEEEWEESWSNNNEWNNWNWSSWEESSSSNESESNENNWEESNWEWSWNSNWNNWENSNSWEWSWWNNWNSENESSNENEWNSSWNNEWSESWENEEENSWWSNNNNSSNENEWSNEEWNWENEEWEESEWEEWSSESSSWNWNNSWNWENWNENWNSWESNWSNSSENENNNWSSENSSSWWNENWWWEWSEWSNSSWNNSEWEWENSWENWSENEENSWEWSEWWSESSWWWNWSSEWSNWSNNWESNSNENNSNEWSNNESNNENWNWNNNEWWEWEE
```
*Thanks to [orlp](https://codegolf.stackexchange.com/users/4162/orlp) for donating this.*
---
### Leaderboard
![Leaderboard](https://i.stack.imgur.com/JXUAb.png)
*Equal scores are listed in order of posting of that score. This is not necessarily the order that the answers were posted since the score for a given answer may be updated over time.*
---
# Judge
Here is a [Python 3 validator](https://gist.github.com/trichoplax/0fbd1eec02a62e8fa317) that takes a string of NESW as a command line argument or via STDIN.
For an invalid string, this will give you a visual example of a maze it fails for.
[Answer]
# C++, 97 95 93 91 86 83 82 81 79 characters
>
> NNWSWNNSENESESWSSWNSEENWWNWSSEWWNENWEENWSWNWSSENENWNWNESENESESWNWSESEWWNENWNEES
>
>
>
My strategy is fairly simple - an evolution algorithm that can grow, shrink, swap elements of and mutate valid sequences. My evolution logic is now nearly the same as @Sp3000's, as his was an improvement over mine.
However, my implementation of the maze logic is rather nifty. This allows me to check if strings are valid at blistering speed. Try to figure it out by looking at the comment, `do_move` and the `Maze` constructor.
```
#include <algorithm>
#include <bitset>
#include <cstdint>
#include <iostream>
#include <random>
#include <set>
#include <vector>
/*
Positions:
8, 10, 12
16, 18, 20
24, 26, 28
By defining as enum respectively N, W, E, S as 0, 1, 2, 3 we get:
N: -8, E: 2, S: 8, W: -2
0: -8, 1: -2, 2: 2, 3: 8
To get the indices for the walls, average the numbers of the positions it
would be blocking. This gives the following indices:
9, 11, 12, 14, 16, 17, 19, 20, 22, 24, 25, 27
We'll construct a wall mask with a 1 bit for every position that does not
have a wall. Then if a 1 shifted by the average of the positions AND'd with
the wall mask is zero, we have hit a wall.
*/
enum { N = -8, W = -2, E = 2, S = 8 };
static const int encoded_pos[] = {8, 10, 12, 16, 18, 20, 24, 26, 28};
static const int wall_idx[] = {9, 11, 12, 14, 16, 17, 19, 20, 22, 24, 25, 27};
static const int move_offsets[] = { N, W, E, S };
int do_move(uint32_t walls, int pos, int move) {
int idx = pos + move / 2;
return walls & (1ull << idx) ? pos + move : pos;
}
struct Maze {
uint32_t walls;
int start, end;
Maze(uint32_t maze_id, int start, int end) {
walls = 0;
for (int i = 0; i < 12; ++i) {
if (maze_id & (1 << i)) walls |= 1 << wall_idx[i];
}
this->start = encoded_pos[start];
this->end = encoded_pos[end];
}
uint32_t reachable() {
if (start == end) return false;
uint32_t reached = 0;
std::vector<int> fill; fill.reserve(8); fill.push_back(start);
while (fill.size()) {
int pos = fill.back(); fill.pop_back();
if (reached & (1 << pos)) continue;
reached |= 1 << pos;
for (int m : move_offsets) fill.push_back(do_move(walls, pos, m));
}
return reached;
}
bool interesting() {
uint32_t reached = reachable();
if (!(reached & (1 << end))) return false;
if (std::bitset<32>(reached).count() <= 4) return false;
int max_deg = 0;
uint32_t ends = 0;
for (int p = 0; p < 9; ++p) {
int pos = encoded_pos[p];
if (reached & (1 << pos)) {
int deg = 0;
for (int m : move_offsets) {
if (pos != do_move(walls, pos, m)) ++deg;
}
if (deg == 1) ends |= 1 << pos;
max_deg = std::max(deg, max_deg);
}
}
if (max_deg <= 2 && ends != ((1u << start) | (1u << end))) return false;
return true;
}
};
std::vector<Maze> gen_valid_mazes() {
std::vector<Maze> mazes;
for (int maze_id = 0; maze_id < (1 << 12); maze_id++) {
for (int points = 0; points < 9*9; ++points) {
Maze maze(maze_id, points % 9, points / 9);
if (!maze.interesting()) continue;
mazes.push_back(maze);
}
}
return mazes;
}
bool is_solution(const std::vector<int>& moves, Maze maze) {
int pos = maze.start;
for (auto move : moves) {
pos = do_move(maze.walls, pos, move);
if (pos == maze.end) return true;
}
return false;
}
std::vector<int> str_to_moves(std::string str) {
std::vector<int> moves;
for (auto c : str) {
switch (c) {
case 'N': moves.push_back(N); break;
case 'E': moves.push_back(E); break;
case 'S': moves.push_back(S); break;
case 'W': moves.push_back(W); break;
}
}
return moves;
}
std::string moves_to_str(const std::vector<int>& moves) {
std::string result;
for (auto move : moves) {
if (move == N) result += "N";
else if (move == E) result += "E";
else if (move == S) result += "S";
else if (move == W) result += "W";
}
return result;
}
bool solves_all(const std::vector<int>& moves, std::vector<Maze>& mazes) {
for (size_t i = 0; i < mazes.size(); ++i) {
if (!is_solution(moves, mazes[i])) {
// Bring failing maze closer to begin.
std::swap(mazes[i], mazes[i / 2]);
return false;
}
}
return true;
}
template<class Gen>
int randint(int lo, int hi, Gen& gen) {
return std::uniform_int_distribution<int>(lo, hi)(gen);
}
template<class Gen>
int randmove(Gen& gen) { return move_offsets[randint(0, 3, gen)]; }
constexpr double mutation_p = 0.35; // Chance to mutate.
constexpr double grow_p = 0.1; // Chance to grow.
constexpr double swap_p = 0.2; // Chance to swap.
int main(int argc, char** argv) {
std::random_device rnd;
std::mt19937 rng(rnd());
std::uniform_real_distribution<double> real;
std::exponential_distribution<double> exp_big(0.5);
std::exponential_distribution<double> exp_small(2);
std::vector<Maze> mazes = gen_valid_mazes();
std::vector<int> moves;
while (!solves_all(moves, mazes)) {
moves.clear();
for (int m = 0; m < 500; m++) moves.push_back(randmove(rng));
}
size_t best_seen = moves.size();
std::set<std::vector<int>> printed;
while (true) {
std::vector<int> new_moves(moves);
double p = real(rng);
if (p < grow_p && moves.size() < best_seen + 10) {
int idx = randint(0, new_moves.size() - 1, rng);
new_moves.insert(new_moves.begin() + idx, randmove(rng));
} else if (p < swap_p) {
int num_swap = std::min<int>(1 + exp_big(rng), new_moves.size()/2);
for (int i = 0; i < num_swap; ++i) {
int a = randint(0, new_moves.size() - 1, rng);
int b = randint(0, new_moves.size() - 1, rng);
std::swap(new_moves[a], new_moves[b]);
}
} else if (p < mutation_p) {
int num_mut = std::min<int>(1 + exp_big(rng), new_moves.size());
for (int i = 0; i < num_mut; ++i) {
int idx = randint(0, new_moves.size() - 1, rng);
new_moves[idx] = randmove(rng);
}
} else {
int num_shrink = std::min<int>(1 + exp_small(rng), new_moves.size());
for (int i = 0; i < num_shrink; ++i) {
int idx = randint(0, new_moves.size() - 1, rng);
new_moves.erase(new_moves.begin() + idx);
}
}
if (solves_all(new_moves, mazes)) {
moves = new_moves;
if (moves.size() <= best_seen && !printed.count(moves)) {
std::cout << moves.size() << " " << moves_to_str(moves) << "\n";
if (moves.size() < best_seen) {
printed.clear(); best_seen = moves.size();
}
printed.insert(moves);
}
}
}
return 0;
}
```
[Answer]
# Python 3 + PyPy, ~~82~~ 80 characters
```
SWWNNSENESESWSSWSEENWNWSWSEWNWNENENWWSESSEWSWNWSENWEENWWNNESENESSWNWSESESWWNNESE
```
I've been hesitant to post this answer because I've basically taken orlp's approach and put my own spin on it. This string was found by starting with a pseudorandom length 500 solution - quite a number of seeds were tried before I could break the current record.
The only new major optimisation is that I only look at one third of the mazes. Two categories of mazes are excluded from the search:
* Mazes where `<= 7` squares are reachable
* Mazes where all reachable squares are on a single path, and the start/finish are not at both ends
The idea is that any string which solves the rest of the mazes should also solve the above automatically. I'm convinced this is true for the second type, but it is definitely not true for the first, so the output will contain some false positives that need to be checked separately. These false positive usually only miss about 20 mazes though, so I thought it'd be a good tradeoff between speed and accuracy, and it would also give the strings a little more breathing space to mutate.
Initially I went through a long list of search heuristics, but horrifically none of them came up with anything better than 140 or so.
```
import random
N, M = 3, 3
W = 2*N-1
H = 2*M-1
random.seed(142857)
def move(c, cell, walls):
global W, H
if c == "N":
if cell > W and not (1<<(cell-W)//2 & walls):
cell = cell - W*2
elif c == "S":
if cell < W*(H-1) and not (1<<(cell+W)//2 & walls):
cell = cell + W*2
elif c == "E":
if cell % W < W-1 and not (1<<(cell+1)//2 & walls):
cell = cell + 2
elif c == "W":
if cell % W > 0 and not (1<<(cell-1)//2 & walls):
cell = cell - 2
return cell
def valid_maze(start, finish, walls):
global adjacent
if start == finish:
return False
visited = set()
cells = [start]
while cells:
curr_cell = cells.pop()
if curr_cell == finish:
return True
if curr_cell in visited:
continue
visited.add(curr_cell)
for c in "NSEW":
cells.append(move(c, curr_cell, walls))
return False
def print_maze(maze):
start, finish, walls = maze
print_str = "".join(" #"[walls & (1 << i//2) != 0] if i%2 == 1
else " SF"[2*(i==finish) + (i==start)]
for i in range(W*H))
print("#"*(H+2))
for i in range(H):
print("#" + print_str[i*W:(i+1)*W] + "#")
print("#"*(H+2), end="\n\n")
all_cells = [W*y+x for y in range(0, H, 2) for x in range(0, W, 2)]
mazes = []
for start in all_cells:
for finish in all_cells:
for walls in range(1<<(N*(M-1) + M*(N-1))):
if valid_maze(start, finish, walls):
mazes.append((start, finish, walls))
num_mazes = len(mazes)
print(num_mazes, "mazes generated")
to_remove = set()
for i, maze in enumerate(mazes):
start, finish, walls = maze
reachable = set()
cells = [start]
while cells:
cell = cells.pop()
if cell in reachable:
continue
reachable.add(cell)
if cell == finish:
continue
for c in "NSEW":
new_cell = move(c, cell, walls)
cells.append(new_cell)
max_deg = 0
sf = set()
for cell in reachable:
deg = 0
for c in "NSEW":
if move(c, cell, walls) != cell:
deg += 1
max_deg = max(deg, max_deg)
if deg == 1:
sf.add(cell)
if max_deg <= 2 and len(sf) == 2 and sf != {start, finish}:
# Single path subset
to_remove.add(i)
elif len(reachable) <= (N*M*4)//5:
# Low reachability maze, above ratio is adjustable
to_remove.add(i)
mazes = [maze for i,maze in enumerate(mazes) if i not in to_remove]
print(num_mazes - len(mazes), "mazes removed,", len(mazes), "remaining")
num_mazes = len(mazes)
def check(string, cache = set()):
global mazes
if string in cache:
return True
for i, maze in enumerate(mazes):
start, finish, walls = maze
cell = start
for c in string:
cell = move(c, cell, walls)
if cell == finish:
break
else:
# Swap maze to front
mazes[i//2], mazes[i] = mazes[i], mazes[i//2]
return False
cache.add(string)
return True
while True:
string = "".join(random.choice("NSEW") for _ in range(500))
if check(string):
break
# string = "NWWSSESNESESNNWNNSWNWSSENESWSWNENENWNWESESENNESWSESWNWSWNNEWSESWSEEWNENWWSSNNEESS"
best = len(string)
seen = set()
while True:
action = random.random()
if action < 0.1:
# Grow
num_grow = int(random.expovariate(lambd=3)) + 1
new_string = string
for _ in range(num_grow):
i = random.randrange(len(new_string))
new_string = new_string[:i] + random.choice("NSEW") + new_string[i:]
elif action < 0.2:
# Swap
num_swap = int(random.expovariate(lambd=1)) + 1
new_string = string
for _ in range(num_swap):
i,j = sorted(random.sample(range(len(new_string)), 2))
new_string = new_string[:i] + new_string[j] + new_string[i+1:j] + new_string[i] + new_string[j+1:]
elif action < 0.35:
# Mutate
num_mutate = int(random.expovariate(lambd=1)) + 1
new_string = string
for _ in range(num_mutate):
i = random.randrange(len(new_string))
new_string = new_string[:i] + random.choice("NSEW") + new_string[i+1:]
else:
# Shrink
num_shrink = int(random.expovariate(lambd=3)) + 1
new_string = string
for _ in range(num_shrink):
i = random.randrange(len(new_string))
new_string = new_string[:i] + new_string[i+1:]
if check(new_string):
string = new_string
if len(string) <= best and string not in seen:
while True:
if len(string) < best:
seen = set()
seen.add(string)
best = len(string)
print(string, len(string))
# Force removals on new record strings
for i in range(len(string)):
new_string = string[:i] + string[i+1:]
if check(new_string):
string = new_string
break
else:
break
```
[Answer]
# C++ and the library from [lingeling](https://github.com/arminbiere/lingeling)
>
> Summary: A new approach, *no new solutions*, a nice program to play
> with, and some interesting results of local non-improvability of the
> known solutions. Oh, and some generally useful observations.
>
>
>
Using a [SAT](https://en.wikipedia.org/wiki/Boolean_satisfiability_problem)
based approach, I could completely
[solve](https://stackoverflow.com/a/54948288/8369843)
the similar problem for 4x4 mazes with blocked cells instead of thin walls
and fixed start and exit positions at opposite corners.
So I hoped to be able to use the same ideas for this problem.
However, even though for the other problem I only used 2423 mazes
(in the meantime it has been observed that 2083 are enough) and it has
a solution of length 29, the SAT encoding used millions of variables
and solving it took days.
So I decided to change the approach in two important ways:
* Don't insist on searching a solution from scratch, but allow to fix
a part of the solution string. (That's easy to do anyway by adding unit
clauses, but my program makes it comfortable to do.)
* Don't use all mazes from the beginning. Instead, incrementally add one
unsolved maze at a time. Some mazes may be solved by chance, or they are
always solved when the ones already considered are solved. In the latter
case, it will never be added, without us needing to know the implication.
I also did some optimizations to use less variables and unit clauses.
The program is based on @orlp's.
An important change was the selection of mazes:
* First of all, mazes are given by their wall structure and the
start position only. (They also store the reachable positions.)
The function `is_solution` checks if all reachable positions are reached.
* (Unchanged: still not using mazes with only 4 or less reachable positions.
But most of them would be thrown away anyway by the following observations.)
* If a maze does not use any of the three top cells, it is equivalent to a
maze that is shifted up. So we can drop it. Likewise for a maze that does
not use any of the three left cells.
* It doesn't matter if unreachable parts are connected, so we insist that
each unreachable cell is completely surrounded by walls.
* A single path maze that is a submaze of a bigger single path maze is always
solved when the bigger one is solved, so we don't need it. Each single path
maze of size at most 7 is part of a bigger one (still fitting in 3x3), but
there are size 8 single path mazes that aren't. For simpliciy, let's just
drop single path mazes of size less than 8. (And I'm still using that only
the extreme points need to be considered as start positions.
All positions are used as exit positions, which only matters for the SAT
part of the program.)
In this way, I get a total of 10772 mazes with start positions.
Here is the program:
```
#include <algorithm>
#include <array>
#include <bitset>
#include <cstring>
#include <iostream>
#include <set>
#include <vector>
#include <limits>
#include <cassert>
extern "C"{
#include "lglib.h"
}
// reusing a lot of @orlp's ideas and code
enum { N = -8, W = -2, E = 2, S = 8 };
static const int encoded_pos[] = {8, 10, 12, 16, 18, 20, 24, 26, 28};
static const int wall_idx[] = {9, 11, 12, 14, 16, 17, 19, 20, 22, 24, 25, 27};
static const int move_offsets[] = { N, E, S, W };
static const uint32_t toppos = 1ull << 8 | 1ull << 10 | 1ull << 12;
static const uint32_t leftpos = 1ull << 8 | 1ull << 16 | 1ull << 24;
static const int unencoded_pos[] = {0,0,0,0,0,0,0,0,0,0,1,0,2,0,0,0,3,
0,4,0,5,0,0,0,6,0,7,0,8};
int do_move(uint32_t walls, int pos, int move) {
int idx = pos + move / 2;
return walls & (1ull << idx) ? pos + move : pos;
}
struct Maze {
uint32_t walls, reach;
int start;
Maze(uint32_t walls=0, uint32_t reach=0, int start=0):
walls(walls),reach(reach),start(start) {}
bool is_dummy() const {
return (walls==0);
}
std::size_t size() const{
return std::bitset<32>(reach).count();
}
std::size_t simplicity() const{ // how many potential walls aren't there?
return std::bitset<32>(walls).count();
}
};
bool cmp(const Maze& a, const Maze& b){
auto asz = a.size();
auto bsz = b.size();
if (asz>bsz) return true;
if (asz<bsz) return false;
return a.simplicity()<b.simplicity();
}
uint32_t reachable(uint32_t walls) {
static int fill[9];
uint32_t reached = 0;
uint32_t reached_relevant = 0;
for (int start : encoded_pos){
if ((1ull << start) & reached) continue;
uint32_t reached_component = (1ull << start);
fill[0]=start;
int count=1;
for(int i=0; i<count; ++i)
for(int m : move_offsets) {
int newpos = do_move(walls, fill[i], m);
if (reached_component & (1ull << newpos)) continue;
reached_component |= 1ull << newpos;
fill[count++] = newpos;
}
if (count>1){
if (reached_relevant)
return 0; // more than one nonsingular component
if (!(reached_component & toppos) || !(reached_component & leftpos))
return 0; // equivalent to shifted version
if (std::bitset<32>(reached_component).count() <= 4)
return 0;
reached_relevant = reached_component;
}
reached |= reached_component;
}
return reached_relevant;
}
void enterMazes(uint32_t walls, uint32_t reached, std::vector<Maze>& mazes){
int max_deg = 0;
uint32_t ends = 0;
for (int pos : encoded_pos)
if (reached & (1ull << pos)) {
int deg = 0;
for (int m : move_offsets) {
if (pos != do_move(walls, pos, m))
++deg;
}
if (deg == 1)
ends |= 1ull << pos;
max_deg = std::max(deg, max_deg);
}
uint32_t starts = reached;
if (max_deg == 2){
if (std::bitset<32>(reached).count() <= 7)
return; // small paths are redundant
starts = ends; // need only start at extremal points
}
for (int pos : encoded_pos)
if ( starts & (1ull << pos))
mazes.emplace_back(walls, reached, pos);
}
std::vector<Maze> gen_valid_mazes() {
std::vector<Maze> mazes;
for (int maze_id = 0; maze_id < (1 << 12); maze_id++) {
uint32_t walls = 0;
for (int i = 0; i < 12; ++i)
if (maze_id & (1 << i))
walls |= 1ull << wall_idx[i];
uint32_t reached=reachable(walls);
if (!reached) continue;
enterMazes(walls, reached, mazes);
}
std::sort(mazes.begin(),mazes.end(),cmp);
return mazes;
};
bool is_solution(const std::vector<int>& moves, Maze& maze) {
int pos = maze.start;
uint32_t reached = 1ull << pos;
for (auto move : moves) {
pos = do_move(maze.walls, pos, move);
reached |= 1ull << pos;
if (reached == maze.reach) return true;
}
return false;
}
std::vector<int> str_to_moves(std::string str) {
std::vector<int> moves;
for (auto c : str) {
switch (c) {
case 'N': moves.push_back(N); break;
case 'E': moves.push_back(E); break;
case 'S': moves.push_back(S); break;
case 'W': moves.push_back(W); break;
}
}
return moves;
}
Maze unsolved(const std::vector<int>& moves, std::vector<Maze>& mazes) {
int unsolved_count = 0;
Maze problem{};
for (Maze m : mazes)
if (!is_solution(moves, m))
if(!(unsolved_count++))
problem=m;
if (unsolved_count)
std::cout << "unsolved: " << unsolved_count << "\n";
return problem;
}
LGL * lgl;
constexpr int TRUELIT = std::numeric_limits<int>::max();
constexpr int FALSELIT = -TRUELIT;
int new_var(){
static int next_var = 1;
assert(next_var<TRUELIT);
return next_var++;
}
bool lit_is_true(int lit){
int abslit = lit>0 ? lit : -lit;
bool res = (abslit==TRUELIT) || (lglderef(lgl,abslit)>0);
return lit>0 ? res : !res;
}
void unsat(){
std::cout << "Unsatisfiable!\n";
std::exit(1);
}
void clause(const std::set<int>& lits){
if (lits.find(TRUELIT) != lits.end())
return;
for (int lit : lits)
if (lits.find(-lit) != lits.end())
return;
int found=0;
for (int lit : lits)
if (lit != FALSELIT){
lgladd(lgl, lit);
found=1;
}
lgladd(lgl, 0);
if (!found)
unsat();
}
void at_most_one(const std::set<int>& lits){
if (lits.size()<2)
return;
for(auto it1=lits.cbegin(); it1!=lits.cend(); ++it1){
auto it2=it1;
++it2;
for( ; it2!=lits.cend(); ++it2)
clause( {- *it1, - *it2} );
}
}
/* Usually, lit_op(lits,sgn) creates a new variable which it returns,
and adds clauses that ensure that the variable is equivalent to the
disjunction (if sgn==1) or the conjunction (if sgn==-1) of the literals
in lits. However, if this disjunction or conjunction is constant True
or False or simplifies to a single literal, that is returned without
creating a new variable and without adding clauses. */
int lit_op(std::set<int> lits, int sgn){
if (lits.find(sgn*TRUELIT) != lits.end())
return sgn*TRUELIT;
lits.erase(sgn*FALSELIT);
if (!lits.size())
return sgn*FALSELIT;
if (lits.size()==1)
return *lits.begin();
int res=new_var();
for(int lit : lits)
clause({sgn*res,-sgn*lit});
for(int lit : lits)
lgladd(lgl,sgn*lit);
lgladd(lgl,-sgn*res);
lgladd(lgl,0);
return res;
}
int lit_or(std::set<int> lits){
return lit_op(lits,1);
}
int lit_and(std::set<int> lits){
return lit_op(lits,-1);
}
using A4 = std::array<int,4>;
void add_maze_conditions(Maze m, std::vector<A4> dirs, int len){
int mp[9][2];
int rp[9];
for(int p=0; p<9; ++p)
if((1ull << encoded_pos[p]) & m.reach)
rp[p] = mp[p][0] = encoded_pos[p]==m.start ? TRUELIT : FALSELIT;
int t=0;
for(int i=0; i<len; ++i){
std::set<int> posn {};
for(int p=0; p<9; ++p){
int ep = encoded_pos[p];
if((1ull << ep) & m.reach){
std::set<int> reach_pos {};
for(int d=0; d<4; ++d){
int np = do_move(m.walls, ep, move_offsets[d]);
reach_pos.insert( lit_and({mp[unencoded_pos[np]][t],
dirs[i][d ^ ((np==ep)?0:2)] }));
}
int pl = lit_or(reach_pos);
mp[p][!t] = pl;
rp[p] = lit_or({rp[p], pl});
posn.insert(pl);
}
}
at_most_one(posn);
t=!t;
}
for(int p=0; p<9; ++p)
if((1ull << encoded_pos[p]) & m.reach)
clause({rp[p]});
}
void usage(char* argv0){
std::cout << "usage: " << argv0 <<
" <string>\n where <string> consists of 'N', 'E', 'S', 'W' and '*'.\n" ;
std::exit(2);
}
const std::string nesw{"NESW"};
int main(int argc, char** argv) {
if (argc!=2)
usage(argv[0]);
std::vector<Maze> mazes = gen_valid_mazes();
std::cout << "Mazes with start positions: " << mazes.size() << "\n" ;
lgl = lglinit();
int len = std::strlen(argv[1]);
std::cout << argv[1] << "\n with length " << len << "\n";
std::vector<A4> dirs;
for(int i=0; i<len; ++i){
switch(argv[1][i]){
case 'N':
dirs.emplace_back(A4{TRUELIT,FALSELIT,FALSELIT,FALSELIT});
break;
case 'E':
dirs.emplace_back(A4{FALSELIT,TRUELIT,FALSELIT,FALSELIT});
break;
case 'S':
dirs.emplace_back(A4{FALSELIT,FALSELIT,TRUELIT,FALSELIT});
break;
case 'W':
dirs.emplace_back(A4{FALSELIT,FALSELIT,FALSELIT,TRUELIT});
break;
case '*': {
dirs.emplace_back();
std::generate_n(dirs[i].begin(),4,new_var);
std::set<int> dirs_here { dirs[i].begin(), dirs[i].end() };
at_most_one(dirs_here);
clause(dirs_here);
for(int l : dirs_here)
lglfreeze(lgl,l);
break;
}
default:
usage(argv[0]);
}
}
int maze_nr=0;
for(;;) {
std::cout << "Solving...\n";
int res=lglsat(lgl);
if(res==LGL_UNSATISFIABLE)
unsat();
assert(res==LGL_SATISFIABLE);
std::string sol(len,' ');
for(int i=0; i<len; ++i)
for(int d=0; d<4; ++d)
if (lit_is_true(dirs[i][d])){
sol[i]=nesw[d];
break;
}
std::cout << sol << "\n";
Maze m=unsolved(str_to_moves(sol),mazes);
if (m.is_dummy()){
std::cout << "That solves all!\n";
return 0;
}
std::cout << "Adding maze " << ++maze_nr << ": " <<
m.walls << "/" << m.start <<
" (" << m.size() << "/" << 12-m.simplicity() << ")\n";
add_maze_conditions(m,dirs,len);
}
}
```
First `configure.sh` and `make` the `lingeling` solver, then compile the
program with something like
`g++ -std=c++11 -O3 -I ... -o m3sat m3sat.cc -L ... -llgl`, where `...` is the
path where `lglib.h` resp. `liblgl.a` are, so both could for example be
`../lingeling-<version>`.
Or just put them in the same directory and do
without the `-I` and `-L` options.
The program takes one mandatory command line argument, a string consisting
of `N`, `E`, `S`, `W` (for fixed directions) or `*`. So you could search
for a general solution of size 78 by giving a string of 78 `*`s (in quotes),
or search for a solution starting with `NEWS` by using `NEWS` followed by
as many `*`s as you want for additional steps. As a first test, take your
favourite solution and replace some of the letters with `*`.
This finds a solution fast for a surprisingly high value of "some".
The program will tell which maze it adds, described by wall structure and
start position, and also give the number of reachable positions and walls.
The mazes are sorted by these criteria, and the first unsolved one is added.
Therefore most added mazes have `(9/4)`, but sometimes others appear as well.
I took the known solution of length 79, and for each group of adjacent 26
letters, tried to replace them with any 25 letters. I also tried to remove
13 letters from the beginning and from the end, and replace them by any 13 at the
beginning and any 12 at the end, and vice versa. Unfortunately, it all came
out unsatisfiable. So, can we take this as indicator that length 79 is
optimal? No, I similarly tried to improve the length 80 solution to length 79,
and that was also not successful.
Finally, I tried combining the beginning of one solution with the end of the
other, and also with one solution transformed by one of the symmetries.
Now I'm running out of interesting ideas, so I decided to show you what I
have, even though it didn't lead to new solutions.
] |
[Question]
[
## Task
Given a non-negative integer \$n\$, evaluate the factorial \$n!\$.
The factorial is defined as follows:
$$
n!=\begin{cases}1 & n=0\\n\times(n-1)!&n>0\end{cases}
$$
## Rules
* All default I/O methods are allowed.
* Standard loopholes are forbidden.
* Built-ins are allowed.
* There is no time or memory limit.
* Giving imprecise or incorrect results for large inputs due to the limit of the native number format is fine, as long as the underlying algorithm is correct. Specifically, [it is not allowed to abuse the native number type to trivialize the challenge](https://codegolf.meta.stackexchange.com/a/8245/76162), which is one of the standard loopholes.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Shortest code in bytes wins, but feel free to participate in various esolangs (especially the ones hindered by the restrictions of the former challenge).
## Test cases
```
0! = 1
1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
6! = 720
7! = 5040
8! = 40320
9! = 362880
10! = 3628800
11! = 39916800
12! = 479001600
```
---
**Note:** We already have the [old factorial challenge](https://codegolf.stackexchange.com/q/607/78410), but it has some restrictions on the domain, performance, and banning built-ins. As [the consensus here](https://codegolf.meta.stackexchange.com/a/19220/78410) was to create a separate challenge without those restrictions so that more esolangs can participate, here it goes.
Also, we discussed [whether we should close the old one as a duplicate of this](https://codegolf.meta.stackexchange.com/q/19247/78410), and we decided to [leave it open](https://codegolf.meta.stackexchange.com/a/19248/78410).
[Answer]
# [Shakespeare Programming Language](https://github.com/TryItOnline/spl), 106 bytes
```
,!Ajax,!Puck,!Act I:!Scene I:![Enter Ajax and Puck]Ajax:Listen tothy!You is the factorial ofyou!Open heart
```
[Try it online!](https://tio.run/##FcoxC4MwEIbhv/Ld7lJHtw4dCoKFTqU4HOlJYiUnyQXqr0/N9r7w5H2rtaPryr@OHsV9z3aG@0BPJ1FavG/RJKERcPygqbndMIZsEmFq/qCXFoQM84KFnWkKvEGXQwtN@6m8cLJaL/0f "Shakespeare Programming Language – Try It Online")
Uses the built-in `the factorial of`, which isn't described at all in the [official docs](http://shakespearelang.sourceforge.net/report/shakespeare/).
### Commented
```
,!Ajax,!Puck,!Act I:!Scene I:![Enter Ajax and Puck] # header
Ajax:Listen tothy! # read (numeric) input
You is the factorial ofyou! # take factorial
Open heart # numeric output
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 2 bytes
```
:p
```
[Try it online!](https://tio.run/##y00syfn/36rg/39DAwA "MATL – Try It Online")
The `:` generates a range from 1 to input inclusive and the `p` reduces it on product
[Answer]
# C (gcc), 21 bytes
Uses the assignment trick, works consistently in GCC without optimizations.
```
O(o){o=o?o*O(~-o):1;}
```
[Try it online!](https://tio.run/##S9ZNT07@/99fI1@zOt823z5fy1@jTjdf08rQuvZ/Zl6JQm5iZp5GWX5miqZCNRdnWn6RggZIOFPBVsHAGkjZ2CoYghja2mAFnAVFQOk0DSXVFEWgEtWUmDwlHYVMHQV/jUxNTWsuzlqu2v8A "C (gcc) – Try It Online")
[Answer]
# x86-16 / x87 machine code, 13 bytes
Binary:
```
00000000: d9e8 e308 518b f4de 0c59 e2f8 c3 ....Q....Y...
```
Listing:
```
D9 E8 FLD1 ; start with 1
E3 08 JCXZ DONE ; if N = 0, return 1
FACT_LOOP:
51 PUSH CX ; push current N onto stack
8B F4 MOV SI, SP ; SI to top of stack for N
DE 0C FIMUL WORD PTR[SI] ; ST = ST * N
59 POP CX ; remove N from stack
E2 F8 LOOP FACT_LOOP ; decrement N, loop until N = 0
DONE:
C3 RET ; return to caller
```
Callable function. Input **\$n\$** in `CX`, output **\${n!}\$** in `ST(0)`. Works for values of **\$n\$** up to `21` (before loss of precision).
*Or recursive...*
## x86-16 / x87 machine code, 15 bytes
```
D9 E8 FLD1 ; start with 1
FACT_CALL:
E8 0A JCXZ DONE ; if N = 0, end recursion
51 PUSH CX ; push current N onto stack
49 DEC CX ; decrement N
E8 F9FF CALL FACT_CALL ; recurse N-1
8B F4 MOV SI, SP ; SI to top of stack for N
DE 0C FIMUL WORD PTR[SI] ; ST = ST * N
59 POP CX ; remove N from stack
DONE:
C3 RET ; return from recursive call
```
*Or x64 just for grins...*
## x86\_64 machine code, ~~12~~ 11 bytes
```
31: 6a 01 push 0x1 # start with 1
33: 58 pop rax
35: e3 05 jrcxz 3c <done> # if 0, return 1
0037 <f_loop>:
37: 48 f7 e1 mul rcx # rax = rax * N
3a: e2 fb loop 37 <f_loop> # loop until N = 0
003c <done>:
3c: c3 ret # return to caller
```
[Try it online!](https://tio.run/##ZVHtatwwEPwdPcWQo5C0V3MppRRDnqQ9gs6SHRV9uNIq5/Tl3ZXkS47WYFsfs7OzMzIl7U729fM0DGtnPGn7lF49yQU@zFGPZhGdXkhHjzny/Sg6JUmK0VGPLhGfTbj9YG3@6W9FR4x9K5AUjOgmG04WThovyqcXO5BOxHRhitJhCErjpG04C/DjwguiMnv8iMl8@n682THCOekVrPEaMk4JFAqm4gdpbe2EG4ZGFv6I3@cQFYyfM@FF2qzfmBGHZV9QBasMY0vFXQUhjHD376Tjt6@Vs23kQCEaaeu91RKbSjbiWI6w2wzCZsoYopN01TmZ2hnY4FGnbKnOkkyBI2RiyVclksUe3hW1BkVTW92xScoc9xu3WnD/bzHKoJoyx9GIeMMJaLbzvxTWXfOsh@dFsYqRTVNf6C5ZsjGC377yzTk946EalUhGwtkQH7S7MFcddfOL@f5ABc6wgM2Iw/4i7UGMTzaEuVG6bGtQV4mW78eqqNrPULSKMl/9Z0/G1qpHpitt@su8jad1YreLlTquYl2/HP4C "Assembly (gcc, x64, Linux) – Try It Online")
Input **\$n\$** in `rcx`, output **\${n!}\$** in `rax` for values of **\$n\$** up to `20`.
* -1 bytes thx to @PeterCordes on x86\_64!
[Answer]
## [Google Sheets](https://docs.google.com/spreadsheets/u/0/) / Excel / Numbers, 8 bytes
```
=FACT(A1
```
All three spreadsheet programs close parentheses automatically.
[Answer]
# [brainfuck](https://github.com/TryItOnline/brainfuck), 56 bytes
```
+>,[[>+>+<<-]>[-<<[->+<<+>]<[->+<]>>>]<<[-]>[->+<]>>-]<.
```
[Try it online!](https://tio.run/##SypKzMxLK03O/v9f204nOtpO207bxkY31i5a18YmWhfE0baLhbBi7eyATCAbJAvh68ba6P3/zwoA "brainfuck – Try It Online")
Takes input and outputs as byte values. Since this interpreter has 8 bit size cells, it can't really do anything larger than `5!`. You can use [this interpreter](https://copy.sh/brainfuck/?c=Kz4sW1s-Kz4rPDwtXT5bLTw8Wy0-Kzw8Kz5dPFstPis8XT4-Pl08PFstXT5bLT4rPF0-Pi1dPAoKCls-KysrKysrKysrKzwgIFstPi1bPis-Pl0-WytbLTwrPl0-Kz4-XTw8PDw8XSAgPlstXT4rPl0gPFs-KysrKysrWy08KysrKysrKys-XTwtLjw8PF0$) to try larger values.
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 29 bytes
```
.+
*
.
$.<'$*
~`.+
.+¶$$.($&_
```
[Try it online!](https://tio.run/##K0otycxLNPz/X0@bS4tLj0tFz0ZdRYurLgHI19M@tE1FRU9DRS3@/39DAwA "Retina – Try It Online") Explanation:
```
.+
*
```
Convert `n` to unary.
```
.
$.<'$*
```
Count down from `n` in decimal, with trailing `*`s.
```
~`.+
.+¶$$.($&_
```
Wrap the result in a Retina replacement stage and evaluate it.
Example: For `n=10`, the resulting stage is as follows:
```
.+
$.(10*9*8*7*6*5*4*3*2*1*_
```
This calculates the length of the string obtained by repeating the `_` by each of the numbers from `1` to `10`.
Explanation for `n=0`:
```
.+
*
```
Delete the input.
```
.
$.<'$*
```
Do nothing.
```
~`.+
.+¶$$.($&_
```
Do nothing, and evaluate the resulting empty stage on the empty string.
The empty stage returns `1` more than the character count. As the string is empty, this is just `1`. Conveniently, this is the result we wanted all along.
It is of course possible to calculate the factorial properly even for `n=0`, but my best attempt took 30 bytes.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 11 bytes
```
Gamma[#+1]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2773z0xNzcxWlnbMFbtf0BRZl6Jgr5Dur5DUGJeeqqDodH//wA "Wolfram Language (Mathematica) – Try It Online")
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 15 bytes
```
1~Pochhammer~#&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n27737AuID85IyMxNze1qE5Z7X9AUWZeiYK@Q7q@Q1BiXnqqg6HR//8A "Wolfram Language (Mathematica) – Try It Online")
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 19 bytes
```
If[#>0,#0[#-1]#,1]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2773zMtWtnOQEfZIFpZ1zBWWccwVu1/QFFmXomCvkO6vkNQYl56qoOh0f//AA "Wolfram Language (Mathematica) – Try It Online")
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 24 bytes
The determinant of the n\*n matrix of reciprocals of beta functions is n!
```
Det[1/Beta~Array~{#,#}]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2773yW1JNpQ3ym1JLHOsagosbKuWllHuTZW7X9AUWZeiYK@Q7q@Q1BiXnqqg6HR//8A "Wolfram Language (Mathematica) – Try It Online")
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 26 bytes
```
GroupOrder@*SymmetricGroup
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n277370ov7TAvygltchBK7gyNze1pCgzGSz4P6AoM69EQd8hXd8hKDEvPTXaQMfQKPb/fwA "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [///](https://esolangs.org/wiki////), 80 bytes
```
/!1/1!//!/S'SS'.'//1/S.B'S.B|B'SS.B|S|.SS'B|S'SS|B.SxBxSSxBxS|B..S//B/\\//S/\//!
```
Takes input in unary as `1`s appended to the program. Produces output in unary as `.`s.
[Try it online!](https://tio.run/##HYkhDsAwDAPfEhQWK1/IF0xLBiYNjJUU9O@pN0u@k@X5XvO5ZzcskQYY6KSHAwlGubrFT9yhS9bcFVy1@EMjCBTGAAjBUuk@ "/// – Try It Online")
The program sends the `!` to the end of the input, then makes several more substitutions. After completing the substitutions that exist in the initial program, each `1` from the input has been replaced with the following "1 code" (line breaks added for clarity):
```
/.\"/.\|\"/
/.\|/|./
/"\|/"/
/|\./x\x/
/x\x/|\../
```
and after that, `/'//'.'`.
Each copy of the "1 code" multiplies the number of full stops between the single quotes by 1, then increases the multiplier of the subsequent copies by 1. Many backslashes have been used to ensure that the rest of the code is not modified by earlier copies' execution.
The multiplication is done by adding a `|` at the end, then moving it left, replacing each `.` it passes with `.`, then removing it. To increase the multiplier, `|.` is changed to `|..`, with the intermediate step of `xx`.
Finally, the last substitution removes the single quotes, and the result is printed.
[Answer]
# [MAWP](https://esolangs.org/wiki/MAWP), 19 bytes
```
@[!1A]%_1A[%W_1A]~:
```
[Try it!](https://8dion8.github.io/MAWP/v1.1?code=%40%5B!1A%5D%25_1A%5B%25W_1A%5D%7E%3A&input=10)
[Answer]
# TI-BASIC (TI-83), 2 bytes
```
Ans!
```
Takes input via [`Ans`](https://codegolf.meta.stackexchange.com/a/8580/92901). The character count differs from the byte count because TI-BASIC is [tokenised](http://tibasicdev.wikidot.com/tokens); `Ans` and `!` are both 1-byte tokens.
### Sample output
Uses [this emulator](https://www.cemetech.net/sc/).
[![enter image description here](https://i.stack.imgur.com/SDhmM.png)](https://i.stack.imgur.com/SDhmM.png)
[Answer]
# [Rattle](https://github.com/DRH001/Rattle), ~~23~~ 20 bytes
```
|s>s[0+q][g-s<*~s>]~
```
[Try it online!](https://tio.run/##7Tz9cxu3jr/rr6BXl0RrS7Ikp02rxkmcxHn1TCbOJO7r3NjK61qipH1Z7Sr7Ecd9vvzrPQAkd0kuV7L7cW9u7jytIpEgCIIgAIIg19f5MokPfmuf/XjynsF/Zz8esxenL4/Zq9N39OPkzdnxu7fvjuFzhx3//fjN2U9Hr1//J6MGr4/e/O2no78ds59PXr9mz4/Z0cuXxy/Z2Sk7Ozllp2/Yydl7dvrzm51Wq816uz02TWZhvBizIp/3vsOSlud5rRcpD3I@Y0nMzpYFOyoWbHjABt@NH343PnjERoPRoNV6FhRAazpmL4M45FHr2WeeZmESj9mgP@wPCBH84T95wmbJuMXgjz5WwUfOAjYv4mkOLRjUA7JkFeThNIiia5blSQoQMQvSNLhmYcxWfJWk11A0Y6vkM2f5krN1EsY5T7E5/oz5l5x9DqKCV53wKOOADUaz4nGePWVJChXXl5z9s8hyFie5Ufu412NXy3C6ZFPsfJqzILNxsA5hDnNWZJLGxTwKFk99OWT8/FSE049snSaLNFhl2tBfhb/@ev958euvNzsn54u9d8PL7N7B@eBycPlhMFnc@wa@DvHr88lwMGBhRg0QnvVYEMFoY2DSZx5djw1c2fts@H6Yjd4e6EiHFdJRiZTIuELUSx5FCbtK0mhGhTfnw8NPk51etvckO188vvf1fHC4/jRZ9LInk6@HwzWbLvn0Y4b8zjhwYA4Tsy5yRLVOwxVnyzxfZ@P9fZAqvkiieR@4Nv3Iv0yXQbzg/Wmy2v9U8AznPNv/5tG3w0f7YdbLl/ARF6tLnvaCHmGS5Aw@Tc7XkwEID4del0jyXXr4dvToYLQfrtYRzRwgz1OQ2d4qmC7DWHYCM53fFe3oYLCfEd4etO7JaWYdECc@Zjdr5Mib0zMQcUQuq7vskk8DlBkUVsG5BQd5WgdpBovtaslBzAOQdWiNgslX6/zaF1RmT3rZ@WAP@PF492v2BKZk8vXxguUgiRnhm4OwJmkYRCyZVx1IaaSPVyD6VCikURCwwlUAw@NA3BzXHDa9AREPF0uxPJbBZ5Tya3bzIBPEwLxfJwW7CmJsH@Uh8EGgy7pqTdzHhROAmMDgAiCMdWC9XIVRZC30KWmaaqXj@iZ@ADuAdfn1GtYwKBZQi6CnWLZMimgGtNYpAaGcJjHwm8eIcRmksx5O50yO9CrMl0idZALrAFGkA5CHoOlQ6yAfQljmGVJfwfpyWOyCesU//iXA6R@zi/vrBFRDcnF/dKF3igO55tn9UZdxYMtDEyOUEDMWsJTZuQeAXpcBqCeQiZ8PJ9QdCNLxGOcFNSL8HyeAcRoAY0A6U5h2ULusw/uLPruIfVRwnwrEgop1FaSwXjte94EPGIChqNZA@eGYYyRJLuCYZvgKJqCII55lxNZZUlxGJBGrfjnwD8BzUTHrEhQpygiaghzC0sVJh39hri6vWYoyBZOd4@8iw893oyFOFQg@S8OZElZYadirTfjjHqNxeV4Oi8/zbrB1r/eEid8tZV9arRmfC7npIPt9TeEuouQSVgUuLP23sj2ZXpjyNYijXpIUOTDoKD@OZ3pxnqxP5@9RR@ilaLWCBdeLpInSi6IkWb9IirK4rZUDytTof1qkKaiuF8lqBRJ1Es/4FxuXRdpUgGY22Oswy11wL5L1tT0IPjvC1WgUc1hdULzQC8HyvQLLZwwY5j5/Xszn5qAl5KiaF8fI2CET1qld8sIskmwrC5UDoH7LCYDf54MJ22XK2lXTVYIqliDspGwsB64VqmFD0ZtE2gw5GCh6FYBvoJeNjEKNGRXK6kMTLqg@S6Xjos@M6lbwYJbED1AjxzNYlzxNE1j5sMJAJVxZqOnjwYMHlaq/wRXwgxL7Yflt1Kc/9fPND@w8R0sUzGY4qEL4PKR9hGeEOkjwivw24OS0kn2hZlfBF1zZ6MGQP5ZNyLNCk7gusqVoSSa2q0wElIHC6Cq1foNGkOxamKKFUpquW7kcQoflyzQpFktR3PH77GQudWWIBsi7AU1K40F7gpaErF2mzF0ovBeTqD47RRRXYca7qG6FKS3ZGs5dlJGTKq13wIQ7I7tGaKpacfCYZ0L1gxYW6gY7RtW8QhWch0hcJ@xzNqQmBJsWgOQqnHKfgfLL1nyKhn4aIH0DLBKYMuA4zluIE4laSiBDCRkO5a8cNGzkmzIiZDXkoINB3lCB9rN1FOYd7wfPb0lnGmg5lECwuCxJC@cd4LRigVS/Za2EwCqF@MbzcYkeHoJu18Bri1VOqwZQmWBYZRta1nszYMsfcmQ2@HBik@4kllZ4p@rYN2pTnhepMDsmtebKFwpDMBonC2UKeVmhHevEUDUQ8@Di4sEm3lU/@iAfUTDlHe/iwusqpnaHvuwUXJ71kDRUG92zHlnSTPNTwVMgfwyWS@mClS1Hum7M0@uKpCZyJJ/vexW7cNwc/PSmcddwV54Yn3a8ADrw2B76Hh1E4/s1QEUq6aus4597gWfKBHoh63zc2BIRt@yKYT9Yr3k86xCU3zB2BGy5@qiNqT4eTbr85tl2D8s1pHWQZS21bCMe6x2gXA39rTOIq0mIq3KjKuUwHI8nUq7KhWaMUigrWtw5rSzA5rvWo0ClSb5qCUbcEvwS53BQ70d@2WPuKajamkQrOww14K5KRwV9BiK6K5r5NXBptl1NZFe@2U/bViJdJqBL5qqG3bIT31LAbTQRqlJY9L5WS1pF1OICU4Bj1s6ugjX9BjMPliiCfXHGokA5p9TamL02sayI5eA6Elc1prbN33YpdGXJpvbmF/A5InDqHc7iY4ayWzJEE4g69uzcgUETOhf@PUsgNHZSHESoLGAoBn@AleAoCLXelf8CG03XhedTw2RqVkCjvm5S6A93OJZMzVEG9b3OOsmyELZm4K@i1HqD4ejg4TffPvru@6@/PLv/4anXho05tEl5Rl4d7NXWYBbI2KA3IXbA1ZqOOYpEApDgzZXOoODBB9riPiV3UFUJVpSGwfSvhdsdUBHs2coiZGOIFKQYayGFNNdnExgVJzDY83CCUPoYfdv8yU6VSsY2psqU/WPFJkdC4jnvDSeoWrHRntlIQ6ZD130M4QN0Sn7s4gT4Boj9gVOty7Ac5Z12mY6tWX0PhjONHp/h0AW02ZlWyrf08D6Qhwf1GtsFNHxWPsYHr@tplr3aLZU7HJPjru1U2efT2/X51NnnaGuno3qvqmvsZcdy@WrWWpCCC3YeJUGOjTQj3Wh97X5s1zIwN5wu8K91eCRDSse5FImJX1epGpJf3Ehsf9Zu9szdTPbpOzoEXw/nEd0ZYtG4LUKrGTUX@0gVoDCnuMFXtDSGQLrdWwQ41COCXvHDv5UPaNgvy3IDni6FKuX0W7Kk9OnLcIrq4l8Gbm/PG8OWrWsW9rxxVlzmaDisml1vLGOu11bNvjeehZ/DGbfKr7wxBfp/xji/VffOG6sYXZe1kekD@gPvAePRMh4sdrqzcCF2yxSU7QwPYehdNjoU4b4uOzikJQBbVDoduORRckVTNeN5EEYw05dg8ED7oXODoUBCmJkEZTBwjC1YdC68Mdg@q/CxN5YS9zK5iq3KJ2XlT2ur6i30wfO3otaqW0OzNLZ72vHGaNms0qk3FhFnq/wcxxCk@esksbueeGOwS46KezCtyayIEqv8PwAXeGhWaYojkIEpMrxW/aE3rpbw8acCFJwF8Q/FntnfMUBzEr8XesMJnOOAcJJfSUm26rvINED2AlydI5uWAOQbY2oncZi/Kh1aE@ZIwpyueRoIgLY4D0jKEjx2w3O7OZ3gATlTimYk5vL1VsBIrP2yqb/3yL@IT/NXabKiiJ8FcKmm9ix5W8XwLKDncthH8ewdOFRuoFACnQCvF7XaT974UxHmb@UJkVl5ItfCSRl@qrnI@PdfmmNKm0dd39APH5wXrwPbSaV@9zxfqlMD@Bx/THwC0TwRqSA6lRGer1CRKWxyi1FXEl1xJBuWSh6VKEXZisue6rjaoJA@QUhokIWkHzK1m2C/8jQhH7WCJ3VTthDahAVzjMXN@DRcgcvTSZMCnPmZvwmPUmASUZz00d3VDlfwXGMFnvAcpIXxYLpEt98wjOS0rvLa9hkZtYeOuGeAQ7GKfg11U7pCa0LOBACg/yV9CR6ZjUZGI5yHWzQ6MBoJd8XRrJp4ogYmAufhcGA6odYBCPQkAe3NuRXNU36SHtNgra3xMuI8yOCShat1ksLWKlmUlZcSM5TVsXeHA9@/AzX7w8Hubudyb9iTAwL6dmtlLckhuQS2c0d6TgM8npPf0btrYpQV9mEOljRFZgD7uEfrcqJNpRjnnzqZNdYp4dlAJy1HxySxirFNm6JyLJUzIzRSmwq6Io9BnD98DtIwUDtVwX109gEWD1xj9oFOp9OFtef2fqwSIjxtEam9Qtn@6fb2OxYCx4zrjbrs56ZWg3qTpYNO4LlhGpzYdxHp3tD3HXwFL1QyVB79lOchQlVCacbo8BZmDjWkVifYQn4wgcnWNUC3wEnp9LXpOjxsXh5GYEZTGSYITk81OOVNyxGqn0QoKRdtMKoSR0t1G8dbQZe4/pph97YPu0fDrs2s2BbIoYsfgrh9JcOyVIT8dfLxUG6kj3kgRb/LyiYWuIzASvgET9I2NwjMQ@U/xqX9Q0mvxSX3ejIbGrFjF3/3JX8NKyl3Y0qyEHD3sGSsrA7vxlu91W3Zu6HNn8rh3d/L4d1bcHhXl2CNy@QISxbL81fpriGhXe1gKoyznAczphKtZGjXiJG1CZ0xI/hV8AvTjprayXWvlv5mLERg7IrXOYrcLsNOzWio@A7UTgzD7zC9dizIhFcRZc2vb2eYj@Ycj8yxpON8xaJNrLk1Iks2/wBrLA@q4tM2r8TmUyV2ZQhBZxLmn2ZGAmqxdvHABUdCQTHLrCmA2@gvQIVCBIP//nv7KFrWGeaxHtu2c2YsR9sMrZlx11sQ0UiImxgXQc5Nrj4bGO3ZPB8zgLjdjCDknzcng4Yp6d12Sr7//o/PyWDDlPTuOiVAUH0equiZU3dYadnWAtfZWvUjw6h@swDUpSGNDd1FDm9W11K2BnIJRlPbZhX@uzIAq3ixv1ms3Gkl5mQJGF3PaWeoyCAMWeoMKjKR4wR1YczLNCJxfNmSJ7U7DM0yHvjJNOIVuBRTMK/yTFMy5vj0FeuIfDCwwZQ9i@3EnQE9MZyytPxNKZUNHocrRaZ@RIzjFJE6faRaInBWszZKLp1ycWsrtHG7LvI2jKlBYlvSlZGxYWPxYKGgFTMTWY@ZAkocTotY5OE8wMTdDN34skEo50uMNIk1iwuzwDGsay9IdKTU2RtmnPXZB18krIXYA3Qdxp95imkB4by6AHGH9FQHGzelot4Bs368aWSLNrVT/aqjYQec3263ncsSBCqgjHR1ICK87ssU7whgPmYm56ko@WMcGelBBNN2yG402TGVcTv7GK5ZEedhJJzSKKEsatm1ASszJTYlPGAoEI80J57DRmzNgWgCKo2KqZ@MwzFHgpw816@z4H81D9TCKpcLpeKwyyATujHLi/lcsymgRTFiFZAaxuggpmDQZQcrI4Z0hzw80jUHxwylRr1Bl2Yoh5SqSf1hHqhhBNmHrgZDV6kofZXUI2WNkq2YhyJJt6ZQ3RbSlZu@eVE79UBDmroj5WGr0tZtMN0gYF6VUbUhQ8huonTJXRpbiVtmksMvnp6V5UZWCetGOErg3VBfpUz84nWZOjowjddQP0Hwvv47iPuqEVdLaTDIe/bvIO@ZRp7KetCCqoKyD38qZaCwpF9Rc/t8O5fo9xiwVDkBuvKqdNCMV7a7THTSw9RDV9b3bdmNq9sJY1sTcxk1Eia9wDJ/U@9HGnmDznYZWE@5lmjS1oJUBsr@GpSwy4VotoNbjVI1uZtBxVmd/@eI9J07Zr2hxh/3JZ7SH9NY3QypJs6eF0vrVkp384i6zLuIPd/eMlpBW8q1uFPkSzRRVdVykagOfLK8mb4xuMcO/LvFXbedCxrIRxuPiprbDQcbF@@mhoPbH0QCvNpouE7xMKtF8L@cbyxqiqbGMy20MNNuedtxx@04buG6uDf3W1yO5hnkq/V7TLNuiDRuD9U23ilAtK4pqfdYxkG3B5E391Tff5upSM5FJUCqPGF3aMi8Y6hfvZOnLpUIUcd2jtOd1jOtYPC3B13pMscJKwMz287xN63RAdtyxuE4RNqQi6UNamuQiW0m0yFkzvMYB1y5lEUEQ08G0wjEHW9bhZfELeAqmRxt6xi2OeF6P8WLeHh57TKM95dgCTqU1PUR33C4YvNY3GqEWcq438VknmSFOevqmvNw9C20pHvrVAzoAWwa8CyA/dMynOfqRnCVlabLhj7fRuyPblaV9@fz3xlBJCyOI5I/EjncEimcLmt@vOYhaFNrgjd51lpSQC11T2ckC4bqEEym680pwYrThYGIxwvY2mqS7zo3Ahz/EBcws@oZAMntyyTPk5UjF4EFI1eb8oEMELwkpsqZIqgnFUqZ5aWODUXkDUgb9k2QgVU/6LPjKBOthK3X@1bqCn4@yJSRqbqnK56KPt4VaJFO2v4DNT0ElKPDfOjZbCwC/l28lEP3NLrsdnLkur59q0sDpgIut8xiGqxL0ND9kZZ1Lo4CyptcRvK13t6AJo/SeSfLzJKvbkgd4Vor8ZnZ6Yoi052hLDYj6qSRU1tODepPXCd32ElreRnG0VD552WvFqY69SONnrZ8iAMv4oyEBdWHotlI51CE5Q7z6ZLZUSyssi67Nxw4Vex2X40kLPotSNFj/QYmjrKqriOrUTyo3/Z0nldtG6rtzIjloZ3I2awcbOLj4P/5aPDReUznvlRVIjY1zf8JXjYMeTNP1c0/Kz1eZsIUMbhaIb5d0NKUBWa@VA63PBG7nkZoddA5wtuk0v/a6@3u3@uyd@@OX5GZ4UEa4XNbM46MCzAhexV82V/hbVT5hQERIgl6mkTFKt5Pk6suCwAh6Mx92A1jN8Wq9gBLg7mqWZxmV6ctyRbMaDVeqFL3gWxL0HDQWMehXagsr0pbH83H0o7bB9YhrHNLtIN/Wx9csZjojnBYmzPjnsNddhMNHd9hK2RbUnXP8A65OObG1XXwa1zR0FlNmah0tUy9SCReYkFVQg4FllVXnV3HoeTr0dEI2AgQfnxZis5a8OYnvhRF@dysTAetDgA1bCOJ7qmGbgbT4sJFklEetmBpiS3moUr2Q6zyyEaouA3bFGhp7lTsZuogyuGc3@Jhnz/yEtK2O6p6VHbodWV@sRp@mZVtq47GY1bXwq9GJS/7yqvJDZk6GrgMnngec2WKbwstb6QKY9oWZRuIsqG1lLfN20YBr6yk/dQEc@fzN7Q0DyT0/bd5PaohY0c@KGQu1AAENYlxJ0e2aZM0bkzQ0l5h2kHHwvmGi@f1/wkiqkNbz204X3OymIMXnNri6Tp885KCHk9bVt5SdR3sVlGJeiRTJmfkWwIR2spG5pjN/gfzmOzIRGMyU/1kq1XX@tqFubo1azphbqSw4cR/NHz46OF3B98@fFSzPVU@Ml3Mq9Nw6@ixQ//VA8p30Wa3eUSnYYdbe9vmd@UvBpZ3@5cTtEHF3abv2/RbS2e1JNc5@L@s8zJ1XU/xL4NJ@MKjmbfOztERkXGqMmWd/HfyOfDBsphuZmCGmHxlN8M3PyYyi1tL58RyecMSQ1v0eqmIdOEwMdWEIFxqST7hCkopWKHfI9R8bpAuDmRE@n4yNz0RmaxuO7Gl495eqIA/3TlFVPpgiF7x2KgWtqPYG75vaWqZlnhJ0vO8i99usify4dVFL6O3Vydff4Oa8zEYZf@34eC/AQ)
This is the answer that I could not post on the other challenge! (see [this](https://codegolf.meta.stackexchange.com/questions/19208/should-we-remove-unnecessary-restrictions-on-the-factorial-challenge/19220#19220))
Note that I do not have an online interpreter for Rattle yet so the interpreter is mashed together into the header on TIO (which is why TIO thinks it's Python 3 code but what's in the `code` section is only Rattle code - ignore the header and footer).
This actually works for up to `170!` (but will a loss of precision, of course). In the next Rattle update this will actually become a builtin - making the possible solution just two bytes - but for its current version this is likely the shortest and most interesting factorial program.
# Explanation
```
| takes user's input
s>s saves the input to memory slots 0 and 1
[0+q] if the top of the stack is equal to zero: increments, and quits (implicitly prints the top of the stack)
[ ]~ loop n times, where n is the value in storage at the pointer
g-s gets the value at the pointer, decrements, and saves
< moves pointer left
*~ pushes product of old top of stack and value at pointer to new top of stack
s saves to memory slot at pointer
> moves pointer right
(implicitly outputs the value at the top of the stack after the program executes)
```
In essence, this program saves the given value (from input) to two memory slots. Then, it decrements one memory slot and multiplies the other by the decremented value, until the value decrements to 1, then it outputs the final value.
[Answer]
# [Java](https://en.wikipedia.org/wiki/Java_(programming_language)), ~~37~~ 36 bytes
```
int f(int n){return n<2?1:n*f(n-1);}
```
I simply wanted to try to participate although Java is not the best language to have as little bytes as possible.
This is simply the definition coined to Java, with a recursive call.
edit: one byte less, thx @Jo King
[Answer]
# [Miniflak](https://esolangs.org/wiki/Miniflak), ~~90~~ 80 bytes
*-10 bytes thanks to @Nitrodon!*
```
{(({})[()])}{}((())){({(()[{}]({}))([{}]({}))}({}{})[{}])(({}({}))[({}[{}])])}{}
```
[Try it online!](https://tio.run/##PYwxDoBACAS/s1tY@hpyxV1hYjQWthvejkBhM4FZ2PXO89mOe14RAuQ0cNDlAEgKaWnyURnxT56s69xZfy0t2aYbIvYP)
We already have [another Brain-Flak answer](https://codegolf.stackexchange.com/a/210091/95679) here, but it uses both stacks and so doesn't work in Miniflak (a restricted subset of Brain-Flak where `<`, `>` and `[]` are disallowed). To avoid the second stack, this program uses a different multiplication algorithm.
### Explanation
```
{(({})[()])}
{ } # While the top of the stack is nonzero:
{} # Pop the stack
( ) # Push a copy on the stack
[()] # Subtract 1
( ) # Push the result
```
This part counts down from the input value to 0, leaving a copy of each number in order.
```
{}((()))
{} # Pop the zero on the top
((())) # Push 1 twice
```
These extra ones are there so that when the input is 0 or 1, we multiply them together to get 1 instead of accidentally multiplying something by 0.
```
{({(()[{}]({}))([{}]({}))}({}{})[{}])(({}({}))[({}[{}])])}{}
{ } # While the top of the stack is nonzero:
({(()[{}]({}))([{}]({}))}({}{})[{}]) # Multiply the top two values
(({}({}))[({}[{}])]) # Swap the top two values
{} # Remove the zero on top
```
This loop is the core of the program: at each step, it multiplies the top two numbers together and then brings the number below them to the top. When we run out of numbers, a zero gets swapped to the top, and the loop ends. We then remove that zero, and the result of multiplying all the numbers together (which is the factorial of the input, as the numbers counted down from it to 1) is left.
How does this multiplication algorithm work?
(Suppose the top two numbers on the stack are `a` and `b`.)
```
({(()[{}]({}))([{}]({}))}({}{})[{}])
{} # Pop a
[ ] # Subtract it ...
() # ... from 1
({}) # Add b
( ) # Push the result
[{}] # Subtract that ...
({}) # ... from b ...
( ) # and push the result
{ } # Repeat until a reaches 0, keeping a running total of the sum of both results
{}{} # Pop a and b, add them together, ...
( )[{}] # ... and ignore the result
( ) # Push the running total
```
During each run-through, `a` (the top of the stack) is replaced by `b-(b+(1-a))`, which equals `a-1`. This repeats until `a` reaches 0, so the number of iterations is equal to the first input. The running total keeps track of the sum of the two results at each iteration. The first result is `b+(1-a)` and the second is `a-1`, so their sum is always `b`, the second input. This means that keeping track of the running total yields the product of the two inputs. Finally, before pushing the product, we pop `a` and `b` because we don't need them anymore.
The last piece is the swapping algorithm:
```
(({}({}))[({}[{}])])
{} # Pop the top number
({}) # Add the second number
( ) # Push the result
{} # Pop the sum
{} # Pop the second number ...
[ ] # ... and subtract it from the sum
( ) # Push the result (the first number) ...
[ ] # ... and subtract that from the previous result (the sum)
( ) # Push the final result (the second number)
```
Since the first number is pushed back before the second one, their order is swapped from before.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 17 bytes
```
y=x=>x?x*y(x-1):1
```
[Try it online!](https://tio.run/##bc5LCoAgAAXAfSfRwMj@BdZZwiQK0cgIPb21jdd2VrPP9@zkuR0XM3ZRMQbhxegnnwbiGacDj9IaZ7XKtF1JIDmlyVc4SAFSglQgNUgD0oJ0ID0Of9K45m87Pg "JavaScript (Node.js) – Try It Online")
[Answer]
# [CJam](https://sourceforge.net/projects/cjam/), 4 bytes
```
rim!
```
[Try it online](https://tio.run/##S85KzP3/vygzV/H/f1MA)
I'm sure there's other 4-bytes solutions, but I quite like how this makes an English word with punctuation, even if exclaiming "rim!" without context seems absurd.
[Answer]
# [QBasic](https://en.wikipedia.org/wiki/QBasic), 37 bytes
```
INPUT n
f=1
FOR i=1TO n
f=f*i
NEXT
?f
```
If `n` is zero, the for loop does nothing and 1 is output. Otherwise, the for loop runs over `i` from 1 up to and including the input number, multiplying the result by each `i`.
The values here are single-precision by default, which means that after 10! we start getting output in scientific notation. The values are still accurate for 11! and 12!, though (e.g. 12! gives `4.790016E+08`). At 13! we start to see rounding error (`6.227021E+09` for 6227020800). If we use a double-precision variable `f#` in place of `f` (+4 bytes), we get accurate results up to 21!.
[Answer]
# [Rust](https://www.rust-lang.org/), 20 bytes
```
|n|(1..=n).product()
```
[Try it online!](https://tio.run/##hdC7DoIwFAbgvU9Rt9NESW8U8MLIaxgVMA5WhTIJz47lEDeLHTr0/86f5jRd68ba0vvpZoHRN6H@uKp1MPa2BxFFB8uiZ/Mou4sDNk4x25GBED80uX2xpYWFTkm2yf2dQ@0fvk2ntq0ad6xeKyjP1xXUwBlbUyp8x@9c/Mkl5jKYK8xNMNfzvA6CeP6A5EFhUCQLIkERcx0mKRLN1UJNhkYZmaZhJHCjM1pQuFeVZcIsMlyvTjLOhUE3kPED "Rust – Try It Online")
[Answer]
# [Rust](https://www.rust-lang.org/), 27 bytes
Closure that takes `n` as its input. Thanks to madlaina
```
|n|(1..=n).fold(1,|f,x|f*x)
```
Sample wrapper program to call closure (111 bytes).
```
fn main(){let f=|n|(1..=n).fold(1,|f,x|f*x);print!("{}",f(std::env::args().nth(1).unwrap().parse().unwrap()));}
```
[Try it online!](https://tio.run/##RcjBCoMwDADQX3GeklEK9VjxYwo2m6BZSeMmWL89223H92SvakbcbWlhwHPN2tHUuEHwfmL09FpnCK6ROxrdDxyLLKw36M@rdwRV5xgzv2NM8qiAnvUJAf3OH0nl55KkZvgH4niZWRi@ "Rust – Try It Online")
# [Rust](https://www.rust-lang.org/), 104 bytes
```
fn main(){print!("{}",(1..=std::env::args().skip(1).next().unwrap().parse().unwrap()).fold(1,|f,x|f*x))}
```
[Try it online!](https://tio.run/##TcjBCoMwDIDhV5meklEC9VjwYQq2o2yLJalbQX32zONu//fLps0s8@0dCwPuVQq3Acb9HB14olnbEkLiTwhRHgpI@iwVPBKn3i5u/JVYr6hRNP0NpLy@FvDuyK4f@d4RTzPz0w8 "Rust – Try It Online")
Rust sure isn't built for golfing, but 'twas interesting to do so! Takes `n` via program arguments. Conveniently fails at `13!`
I'm certain a fair number of bytes can be shaved from this, possibly if the `unwrap()` calls can be eliminated using `?` and a `Result`.
[Answer]
# [ArnoldC](https://lhartikk.github.io/ArnoldC/), 409 bytes
```
IT'S SHOWTIME
HEY CHRISTMAS TREE f
YOU SET US UP 1
HEY CHRISTMAS TREE x
YOU SET US UP 0
GET YOUR ASS TO MARS x
DO IT NOW
I WANT TO ASK YOU A BUNCH OF QUESTIONS AND I WANT TO HAVE THEM ANSWERED IMMEDIATELY
STICK AROUND x
GET TO THE CHOPPER f
HERE IS MY INVITATION f
YOU'RE FIRED x
ENOUGH TALK
GET TO THE CHOPPER x
HERE IS MY INVITATION x
GET DOWN 1
ENOUGH TALK
CHILL
TALK TO THE HAND f
YOU HAVE BEEN TERMINATED
```
[Try it online!](https://tio.run/##dZAxT8QwDIX3/Iq33QoTc671Xaw2SYmdqzoiEBMCian/vjhXIRA6Nsv@3rOfnz7fP95enreN9SCQkGflSC7Qgi4UFo1eoIUIr27JFUKKKqgT7m9B6x/ozp2ttl6BF2Myoi9iWJ/BipRnx5h90jbyMjQUHseauoB8wmMlUc5J4FOPHzT4C0EDRevLTIVsGCP17JXGxZmmG@BLrqZarzeYyHi7N08TFUsTTAUWxAWcLqy@7dlTHmxy4ma6Okq5ngPUj8Mtn/Ufn31pn@dkj/rt0QUeR9fKb6vQou3fvcY6EiUolcjJ0vTb9vAF "ArnoldC – Try It Online")
Iterative approach, it just loops starting from the input number and decreasing it until it reaches 0.
[Answer]
# [convey](http://xn--wxa.land/convey/), 16 bytes
```
}>-1
1@"v
^*",{
```
[Try it online!](https://xn--wxa.land/convey/run.html#eyJjIjoiIH0+LTFcbjFAXCJ2XG5eKlwiLHsiLCJ2IjoxLCJpIjoiOSJ9)
Loops over the input value until it reaches `0`. There may be a shorter way using the indices command (`/.`), but it seems to take up more logic than I want. Since the interpreter includes a handy-dandy gif maker, you can even see it in action.
[![!](https://i.stack.imgur.com/KmxME.gif)](https://i.stack.imgur.com/KmxME.gif)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 1 byte
```
!
```
[Try it online!](https://tio.run/##y0rNyan8/1/x////JgA "Jelly – Try It Online")
[Answer]
# [J](http://jsoftware.com/), 1 byte
```
!
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/Ff9rcqUmZ@QrpClUWBka/QcA "J – Try It Online")
Works for APL too
[Answer]
# R, 15 bytes
```
gamma(scan()+1)
```
There is also `factorial` which appears to be allowable as a 9-byte solution.
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 5 bytes
```
$*\,q
```
[Try it online!](https://tio.run/##K8gs@P9fRStGp/D/f0Oj/wA "Pip – Try It Online")
[Answer]
# [Mini-Flak](https://github.com/DJMcMayhem/Brain-Flak), 56 bytes
```
{(({}[()])({({}({}))[({}[({})()])]}{}{})[({})])}{}({}())
```
[Try it online!](https://tio.run/##SypKzMzTTctJzP7/v1pDo7o2WkMzVlOjGsgCIk3NaLAQkAUSjq2tBkKwGJBXC1aioan5/78FAA "Brain-Flak – Try It Online")
When golfing a fold operation in Brain-Flak, it is generally better to keep the stack small and use a "generator" than to push the entire list at once. I'm not exactly why this is true, but it typically works out that way. In this case, it avoids an entire swap operation, since the loop index can stay on top the whole time.
The other main optimization is to make the bottom of the stack equal the running total *minus 1*. This 1 has to be added back later, but this is shorter than pushing a 1 below the input at the beginning.
The multiplication algorithm here is a variant of the swap algorithm. Specifically, there are two equivalent swap algorithms: `(({}({}))[({}[{}])])` calculates B as `(A + B) - A`, while `(([{}]({}))([{}]{}))` calculates B as `(B - A) + A`. To use this in a multiplication loop, we can modify these to not destroy B, and also decrement A by 1. There are three ways to add a single `()` to decrement A:
* `([{}]()({}))([{}]({}))` evaluates to `B`.
* `([{}]({}))([{}()]({}))` evaluates to `B - 1`
* `({}({}))[({}[({})()])]` evaluates to `B + 1`
The latter is what we want, since B is one less than the factor I actually want to represent. By multiplying `A - 1` by `B + 1` and then adding `B`, we obtain `A(B+1) - 1` as desired.
```
# Running counter: A
# Running product: B+1
# Start main loop
{
(
# Subtract 1 from A
({}[()])
# Multiply by B+1
({({}({}))[({}[({})()])]}
# Add B to get A(B+1) - 1 and push
{}{})
# Cancel out product to push A-1 again
[({})])
}{}
# Add 1 to get final result
({}())
```
[Answer]
# [jq](https://stedolan.github.io/jq/), 30 bytes
```
reduce(range(.)+1)as$i(1;.*$i)
```
[Try it online!](https://tio.run/##yyr8/78oNaU0OVWjKDEvPVVDT1PbUDOxWCVTw9BaT0slU/P/f1MA "jq – Try It Online")
My first jq answer.
I spent a while trying to get `while` and `foreach` to do my bidding. Thankfully this existed.
# [jq](https://stedolan.github.io/jq/), 38 bytes
```
def f(x):if x>0then x*f(x-1)else 1end;
```
[Try it online!](https://tio.run/##yyr8/z8lNU0hTaNC0yozTaHCzqAkIzVPoUILKKJrqJmaU5yqYJial2L9P01DT/O/KQA "jq – Try It Online")
A recursive function. `reduce` is a shorthand for a function like this.
[Answer]
# [Quipu](https://esolangs.org/wiki/Quipu), 64 bytes
```
\/1&1&0&2&
3&++[][][]
>>3&**1&/\
1&[]1&++
;;%%>>1&
3&4&1&??
??==
```
[Try it online!](https://tio.run/##zVltc9s2DP6uX4GqV0dKWjtuty9u7Kxpt1u3vt3au31Ish0j07ZWWdJEOqnP59/eASCpSH5JrKa52@WSWCT4AHgAgSSsIpGIr53OB6G0hHk2KyDKhhLiFPREms9KRjrOUhDpkAfjNJ9pJ2EerEgbXmVJIgpQ8ThVMBGXEnQGFxKkikQuh3AV6wkMK0JePM2zAuGy9kfUHkk3EKGQRZ3OtLhIZPtFUYj5yWw0koWXXfyDs/BWoB3yi5bpUMGLPF/oYr54nWpZ5IXEv8EHUSj8V8K3R0U2PZlrqYKTRE7aeZGN22OpeSgMw2UkdDRZREJJyGXPLP/5SyRzMqU/yIs41Uka@GYGZFFkRQ/8g1wSzFuplBjL0GOAWPagYkwJA/0BlEAVgRINDnDtOt7fBDeUX97P9PvRSTZDpzdjvstsYEYx8uaHy6UXJUIpWPEnmBr8HnzUuHYcllyuiYSOcgOx0PNcwqdJIcUQ@lAJzenvaabPvaEcgcjzZB4oJh5V8P@wZ4RPzV8WPkeEhXeJOaEZUPXgTaz0KVJDU@/iBDodmClMIEyneChTrVhc6cIodaDGjXNnURCyGLJSF7PAVZlCqlmiezVPjHvndf9Q3nhE8XkTp1LBKEO5aAILSDAMCJdAghPosvz39OVEFASRWFMwfvh06MUjCKy70GcnQySBRmltO5HpGN@VARxCq8VwwWEID/rgn/k@fiThqwmGFwKDeQSVdeFNkyUgz4XtWP05iTH9c4HhsRYe9KHLxphH1FtF52gloNGRVF7ZNEBiNK2jkXez6YUsKLhoqme4pTntlS67WEPvwOj0Ss1PMV/L0Dr225jLiWOsdNP3l14Z3ptFn3SXiOtGUVkcVWMXY@RcdKxQEIfGT5fmxhEaXo@TtR66xE6FXphSRcExfoX3TvcoRYazaW5sRiXOfMR9fJ3S/GQ0h9Zq4uYPiXMyjSSR61XXon1Pul51PY74vtX71x31fpTJqJnKqAeU@4BURZhjr@JxrMmGa24MW3V@WmynybyqItLEL0hd/aG3rA@hqVFbZ6YQ4Ad81S3yTzchr8HeBgr70D20yI@@v80M7/AffgP@qjC@wYcbZGuP7NKutpGkMe9sj@yrZRAtW4mzEz7buz0J0o2Ae2fpnhXQWwS0E@jcMd1fp7smu2Ph4I4aqWy@z2UhaNflyhl8eQzzkBwlkuZhg7f9yb0a86SZMfv3asx@M2M6O6SfzdFvtxgPaA3Lc@deOersytGyVtHuy5xHzULW/w7GvMxwvydjRPIbAlmTjDl9Ko1NDDq@o0HOggYqj3ZI26N75umoIU33Hbej3ePm8nqwA42DezZ78D@jcdCcxuffZNLuLvfu6PKvImlagB/eUeXLLJ83VAnfpHIdbV3j0v64m2qUZEri/czDazTpA5EkcGGUbr8RQexusxsuQE3NRmMISdD9bEsLgBLVXMmNGndzs/fHbQYypHG9NA8PqoxEagupZ0VqNNNzXsSXQkugDkXNC27WoP2uG@KM7623N9xVPaZztTmE11@4ygU4Du15XPH13V8XNupYWIUudKZhs6l91Khr49o21TbTwqu0Z6jHtykgoRNDUrPkUlLdCFKUTOchM0URq5dOwyAYYo64e1h2DLDUxLaLRZ@RgOyKnd/oIXWw1AyRXQTOfGqKpfjrn/lt3@ZTAXkW03q@9dDzBN98SZlaUc4bvOcaIg@MCLpHTaXsUpZdp3qqE0Bg4UPPtptE9Nn2ppCG87JTQK2ZGhOV8Kfsewq9HvV4zHQt4HyTcdPWrc845bpgHI5SFWY2jba1MF0x9TnOFbdiFd7QeSEj/IPhYiJGIlGSh0ZxGqsJDzL@TfRQj@hBuYAeDGCVNgbxDNSESKtRUGtUuEJSYD71DY9rnN2SPRyPONyB6m0cu@3rDglYWl7JQx7j4jOiKPIjh2eLfU4@LaW3GWwF1aqgbcXUZFgrlgy9Iuz2pTVh8qIuWj@wj9haTxdzZDowS7pc3s3ilTAEwpbPC/5fc2CUBgInVvXtFIdP1GeexkqxNsP4EqKqanlzW9y7PdQaZJrNxhPcJMazKbWXaZOBzBFi1Fo@109SeVhulAggdYVirx4gTosb0982enJMdarA5Wusi5n0rqtdtSgbpWGj9H4p0j1tdgAuFYASuLvSvqgz8w1EGWgH7Pxt5GwTB1iL6bw4HXiYADpcpSgt2/QqUsudWs2cl9cKC9ubKlNsPUnMm/hLViDvte9NKiiV9falMFd5EnNW8NcswTU9LOeOnCRYbkLsM5Z0rpFl2WVeKsU4sNPmSwCSpwywBZdrb7llmdywJOLdhRbVCuXCW1EOEss/Dl8zX1luThqs7VrF9ZZ2S6WmWrt21GGB8gjlZDadcOhHXCDnAo8n5rTDB2jTPObnCjQmw0za0uKOO6viFS1WfPWAtLpiteT1IOAi5irYjeo2lgKDwItPMswWkW4CsIey@h65Vax88bZK2Jdm67zL4q0CZfpulSh3na0S5VZTk7CT9G3rgo6T9I1rvxBXvu9/Pet0W93WYetpy3vWOjg4PacfbzB41trf77Y6Z163dXrexRnv@fNHjwaDLsn9gEuOj73j437/K4Isv/74Hw "Scala – Try It Online")
I decided to try out Quipu for LYAL event, and it's pretty fun to [finagle](https://www.merriam-webster.com/dictionary/finagle) with. I originally had this answer on the other factorial question, not realizing that it was invalid due to overflow.
Ungolfed:
```
"0 1 2 3 4
---------------"
\/ 1& 1& 0& 2&
3& ++ [] [] []
>> 3& ** 1& /\
1& [] 1& ++
;; %% >> 1&
3& 4& 1& ??
?? ==
```
Thread 0 takes input, then jumps to thread 3 if `N > 0`, otherwise it sets its value to 1 and jumps to thread 3.
Thread 3 then takes the value of thread 0 (`N if N > 0, else 1`) and increments it by 1 (we'll call this `M`), then jumps to thread 1.
Thread 1 increments its value, which acts as the accumulator (`acc`), and if `acc == M`, it jumps to thread 4, otherwise it jumps to thread 2.
Thread 2 takes its value (`X`) and multiplies it by `acc`. If `X != 0`, it jumps back to thread 1, otherwise it sets `X` to 1 and jumps to thread 3.
Once `acc` reaches `M`, execution jumps to thread 4, which prints the value of thread 2.
[Answer]
# [Prolog (SWI)](http://www.swi-prolog.org), 61 bytes
```
0+1.
N+F:-nth1(N,_,_),Y is N-1,Y+G,(F is G*N->1>0;F<G,!,0>1).
```
[Try it online!](https://tio.run/##TY1LC4JAFEb38yuuQaDNVWaMCnoIutCdayUiJB8J5sg40c6/XjNE5PLw3XPuIEUnGnd8te83o9wjKY33bq/u3E7xilcHc2hHSF2OOU3Qjg0lq9QNeMAO8TFBC1nAHe@rwxKUfFaE8DlkdGsggxOsDe0M1UU36m1Ds9/GfUaIT/2/uKU7n82i@gWbuSGNEGohH4WyF1Np6cZUTv0CzyFGFwchPH3vm6qvZKEqKLpOyzclZKsT8BxACeDsAw "Prolog (SWI) – Try It Online")
[Steffan's answer](https://codegolf.stackexchange.com/a/251552/76162) is much shorter at 28 bytes, but this predicate was created to be as general as possible. It can be used to:
* Validate that N! = F (for example, `5+120` will succeed, `6+120` will fail)
* Calculate `N!` (`5+F` will bind `F` to `120`)
* Calculate `N` from `N!` (`N+120` will bind `N` to `5`)
+ `N+1` has both `0` and `1` as possible values
+ A non-factorial will fail the predicate
* Generate all `N`, `N!` pairs
The last section feels like it can be golfed, especially as it has both `0>1` as always true and `0<1` as always false, but I've been staring at it for a while and can't figure out anything better. Pity that [`\+!` doesn't work](https://stackoverflow.com/questions/32517857/behavior-of-cuts-in-negation).
[Answer]
# TypeScript Type System, ~~98~~ 99 bytes
```
type X<A,B=A>=B extends`1${infer R}`?R extends""?A:B extends A?X<B,X<R>>:`${A&string}${X<R,A>}`:"1"
```
[Try it at the TypeScript playground](https://www.typescriptlang.org/play?#code/PQKgBAZghgxgLgewE4EsoBswFowE5dgBGAnnAKYDOYIwAULXMQA5lgAaAPAIIA0AQgF4uAPgF8wZAB7kAdgBMKAAwCMAEgDeKGRDJIwAJQC+igPz6J0svIoAiGya4AucVNkKwXE5z49O+4cKOihpcAGQUcKgyAOaGGn48IsaONso29MDAYOQRYDBQFJT0jCxgACqUcAAMYALsHHbCtJlgrQB6JgzMrBURyrX1qTZNLe2dJT2VAEwDnKlpI1ljXaW9cADMsw3KO8PNS2AdK5MRACxb87uLrYedQA)
+1 byte to make `X<0>` work properly
I/O is unary strings.
[Go check out emanresu A's really clean golf of this!](https://codegolf.stackexchange.com/a/265550/108687) It uses pretty much the same formula but the execution is really great.
It took me a little over an hour to come up with and golf. It's pretty hard to explain but the gist of it is that `X<A>` does the factorial, and `X<A,B>` does multiplication. It figures out which is being used by making `B` default to `A` if not specified, and checking if `B extends A`. I was able to get it so short by combining the types for factorial and multiplication, since they shared a lot of boilerplate.
I also wrote a version that uses decimal I/O for ~~184~~ 175 bytes:
```
//@ts-ignore
type X<A,B=[]>=A extends 1[]?B extends[1,...infer R]?R extends[]?A:B extends A?X<A,X<R,R>>:[...A,...X<R,A>]:[1]:B extends{length:A}?X<B,B>["length"]:X<A,[...B,1]>
```
[Try it at the TypeScript playground](https://www.typescriptlang.org/play?ssl=3&ssc=1&pln=4&pc=163#code/FDD0oAQFwZwWgJYHMB2B7ATgU2FAngA5YAEAGgDwCCANAEIC8A2gLoB89lxWAHlFigBMYxAIwsA-LS69+QxiOoA6ZQhQAzLBmIAlZuO3S+gmBMoAuKTyNDilcRRoVt1ba1ZnGyxTS9PqlVmYPESDLGWMAbwAbfiQoAAszSgBfe3JaOlZGACIYlDj47KCHak9lDJDWEHwiYgAVLBgoAAZiejJyZtZicGkiAGMoUTBQYjGAPXFcQhIGppE2jpFu3p4BoZERseJJ6dq5qAAmRYpDldG1rEHiQ62JqZrZxqgAZhPyF-O+q6GANjudg8ZvVngAWd6gr6Xa6HUEA3aPEFNACs72RUO461Eh2a8KB+2ev3evwxWIA7Di8Xsnk0ye8yaSfsRkc1QbjevdgEA)
[@tjjfvi](https://codegolf.stackexchange.com/users/87606/tjjfvi) showed me this spectacular 153 byte version with I/O in decimal:
```
//@ts-ignore
type M<A,B,N=[]>=A extends[0,...infer A]?M<A,B,[...N,...B]>:N;type F<N,X=[],A=[0],L="length">=X[L]extends N?A[L]:F<N,[0,...X],M<[0,...X],A>>
```
[Try it at the TypeScript playground](https://www.typescriptlang.org/play?#code/PTAECME9QAQFwFYDMkDcCWAoTJ4GcBadAcwDsB7AJwFNM5IAHa0AWQB4BBAGgCEuA5ALwBtALoA+QR1DUAHnGqkAJnmEAGLgDpt6UkmqVQHUQH523PsO2b+W7TwkAufgG56TUADE2tgBojRLg4RNUCAGUEAIgAbRWI4AAtIyV9hMNE5BWU8UH4TDjTRR29bdTtNX0D2MutKoPFxbHdmABVqPDg1UEEvNjVxUBAZWSYAYzhQAEYcMFBQAD0TOkZW9rhJ7t7JgaG5MYnpobnF5Y82joAmTe8LnbA96nHQC5m5haXm0HO4AGZrth+d2G+1AADZXscPisvmsACz-WFAh5PC6wiHvU6rDoAVn+2KRI0eBwuanRJ0+31B-1BBJBAHYSWSoWc1nT-nTaUTQNi1LDSUcMUA)
] |
[Question]
[
**Closed**. This question needs to be more [focused](/help/closed-questions). It is not currently accepting answers.
---
**Want to improve this question?** Update the question so it focuses on one problem only by [editing this post](/posts/23662/edit).
Closed 7 years ago.
[Improve this question](/posts/23662/edit)
You know that your language's clock/time API's are broken and they are not reliable at all.
So you are not allowed to use any built-in API to access system time/date.
But you also know that your language's ability to perform date math, and retaining a date/time value in a variable are correct.
Write a program that prints the current date/time without calling any date/time/clock API's. For example `DateTime.Now`, `GetDate()` and similar functions are not allowed.
The answer with most upvotes wins.
In case of a tie, the answer with more precision wins (that is, accurate up to seconds, then milliseconds, then microseconds, and so on).
[Answer]
# Java
Almost all of the current solutions assume that local/remote computer is not lying about a current time (would you believe T-600 as well?) .
Key point in time calculation is trusting a **pure nature**.
This Android app asks user to take photo of the sky and it's predicting current time with outstanding precision:
```
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (resultCode == RESULT_OK)
{
Uri selectedImageUri = data.getData();
this.imageView.setImageURI(selectedImageUri);
TimeGuesser guesser = new TimeGuesser(this);
String result = guesser.guessTimeFromImage(selectedImageUri);
this.textView.setText(result);
}
}
public class TimeGuesser {
private Context context;
public TimeGuesser(Context context)
{
super();
this.context = context;
}
public String guessTimeFromImage(Uri uri) {
Bitmap bitmap = null;
try {
bitmap = MediaStore.Images.Media.getBitmap(this.context.getContentResolver(), uri);
} catch (IOException e) {
return "There is no sky. Everyone's going to die";
}
float brightness = getBrightness(bitmap);
if (brightness < 90.0)
{
return "It's sooo late";
} else {
return "It's sooo early";
}
}
private float getBrightness(Bitmap bitmap)
{
float R, G, B;
R = G = B = 0.0f;
int pixelColor;
int width = bitmap.getWidth();
int height = bitmap.getHeight();
int size = width * height;
for (int x = 0; x < width; ++x) {
for (int y = 0; y < height; ++y) {
pixelColor = bitmap.getPixel(x, y);
R += Color.red(pixelColor);
G += Color.green(pixelColor);
B += Color.blue(pixelColor);
}
}
R /= size;
G /= size;
B /= size;
float brightness = (0.2126f*R ) + (0.7152f*G) + (0.0722f*B);
return brightness;
}
}
```
## Results:
![enter image description here](https://i.stack.imgur.com/H41tQ.png)
---
![enter image description here](https://i.stack.imgur.com/tAz6N.png)
[Answer]
# Ruby
Let's be honest: time only changes when something is posted on [stackoverflow.com](http://stackoverflow.com) ;)
The script extracts the time of the "XYs ago" label in the topmost question.
```
require 'net/http'
source = Net::HTTP.get('stackoverflow.com', '/')
puts source.match(/span title=\"(.*)\" class=\"relativetime/)[1]
```
Output:
```
2014-03-10 18:40:05Z
```
[Answer]
## Bash
Like this? (requires `wget` and `grep`)
```
wget -qO- 'http://www.wolframalpha.com/input/?i=current+time'|grep ' am \| pm '
```
The output I got a few minutes ago:
```
Why am I seeing this message?
context.jsonArray.popups.pod_0200.push( {"stringified": "6:08:38 pm GMT\/BST | Monday, March 10, 2014","mInput": "","mOutput": "", "popLinks": {} });
```
Or this? (requires `wget` and `eog`)
```
wget http://c.xkcd.com/redirect/comic/now
eog ./now
rm ./now
```
Output I get now: (Image by [xkcd](http://xkcd.com/1335/))
[world map with timezone http://c.xkcd.com/redirect/comic/now](http://c.xkcd.com/redirect/comic/now)
[Answer]
# sh/coreutils
```
touch . && stat . -c %z
```
Outputs the date in somewhat nonstandard format:
`YYYY-MM-DD hh:mm:ss.nanoseconds +timezone`
Although I guess it might depend on the locale.
[Answer]
## PHP
Exploit the fact that `uniqid()` returns an ID based on the time.
```
$u=hexdec(substr(uniqid(),0,8));
$y=floor($u/31536000);
$u-=$y*31536000;
$y+=1970;
$d=floor($u/86400);
$u-=$d*86400;
$h=floor($u/3600);
$u-=$h*3600;
$m=floor($u/60);
$s=$u-$m*60;
echo 'Year='.$y.' Days='.$d.' Hours='.$h.' Minutes='.$m.' Seconds='.$s;
```
During my test, it returned : `Year=2014 Days=79 Hours=18 Minutes=9 Seconds=49`.
I don't know if I can use `date` to format correctly, so I converted it manually.
[Answer]
**Bash**
Just to be always absolutely precise and correct:
```
echo "Now"
```
or motivating:
```
echo "Now, do something useful today"
```
[Answer]
# DNS
Do we only mistrust our own machine? If so, does this count?
```
ssh $othermachine date
```
If that doesn't count, extracting time from DNS update definitely does:
```
dig stackexchange.com | grep WHEN
```
[Answer]
# curl - accurate to whatever your ping rate is
```
curl -s time.nist.gov:13
```
[Answer]
# Python
You sure you don't know what time is it?!? Here's a reminder:
```
print "It's Adventure Time!"
```
[Answer]
# Python 2
So, the clock is correct but the time API is hosed, right? Why not check a raw filesystem timestamp. Instead of creating a test file, we just use our own access timestamp since the script *has* to be read to run (even if it's been compiled). Accurate to the second.\*
```
import os
h, m = divmod(os.stat('t.py').st_atime % 86400, 3600)
print h+1, m // 60, m % 60
```
This should be saved and run as `t.py`. Alternately, get the script name at runtime with `inspect.getfile(inspect.currentframe())`
Note \* Occasionally accurate to the *previous* second.
[Answer]
## Ruby
HTTP, but just using response meta-data.
```
require 'uri'
require 'net/http'
def get_now
uri = URI.parse("http://google.com")
http = Net::HTTP.new(uri.host, uri.port)
request = Net::HTTP::Get.new(uri.request_uri)
rsp = http.request(request)
rsp['date']
end
```
[Answer]
# ps
Can't `ps` tell the time? It can!
```
sleep 1& ps -o lstart -p $!
```
The process is started in the background and `ps` tells the time the process started. Since the process started in the background, the start time of the process is *pretty much* the same time as now.
Moreover, the advantage is that the time is obtained in the local time zone. And you don't need a internet connection either!
[Answer]
## vba
because I shouldn't.
```
Public Function DateTime() As String
Dim myNTPsvr As String
Dim dattime As String
Dim oHTTP As Object
myNTPsvr = "time.windows.com"
Set oHTTP = CreateObject("WinHttp.WinHttpRequest.5.1")
oHTTP.Open "GET", "http://" & myNTPsvr & "/", False
oHTTP.Send
DateTime = oHTTP.GetResponseHeader("Date")
Set oHTTP = Nothing
End Function
```
use `?DateTime` to use, or if you put it into Excel, then `=DateTime()` will work as a formula.
The date/time is returned in GMT - I leave it as an exercise in futility to convert it from a string to local time
[Answer]
# Bash + `last` + `head` + `cut`
Precise to the second. `last` uses the log file `/var/log/wtmp`
```
$ last -RF reboot | head -n1 | cut -c50-73
Tue Mar 11 09:38:53 2014
$
```
EDIT: Added `head` to limit to only one line.
EDIT: This works on Linux Mint 13 Cinnamon 64-bit but it seems that this is depends on your distro. `sysvinit-utils` (which provides `last`) version is `2.88dsf-13.10ubuntu11.1` `last` reads from `/var/log/wtmp` (in my case) so the results depend on that log file. See comments below.
EDIT: Apparently this depends on the system uptime so you can see the proof here <https://i.stack.imgur.com/rVS5B.jpg>
[Answer]
## Python
Getting nanosecond precision would be tricky unless the returned time was based on when the program finishes running, not when it starts. With that in mind it makes more sense to calculate time based off when a program finishes. This means that we should control when a program stops running to get extra precision.
```
import subprocess
def what_day_is_it(): return int(subprocess.check_output(["date", "+%dd"]))[:-2];
current_day = next_day = what_day_is_it # It's a bash call,
while not current_day - next_day:
next_day = what_day_is_it()
print "It's midnight."
print "Probably."
```
Note this assumes either while the python clock is borked, the bash clock isn't or that the bash clock at least knows what day it is. If not, we can instead use this:
```
def what_year_is_it(): return int(subprocess.check_output(["date", "+%yy"]))[:-2];
```
Might be slightly slower, though. I haven't tested it.
[Answer]
# BrainFuck
```
>+++++++[-<++++++++>]<---.>+++++[-<+++++>]<++.---.>++++++++[-<-------->]<---.
```
Output:
```
5PM
```
I think it displays the time in Denver at the time of writing. The explanation for the algorithm here by this [Alan Jackson video](http://youtu.be/BPCjC543llU).
[Answer]
# Ruby
```
`date`
```
Doesn't use the language's clock/time API.
[Answer]
I liked the "reading from a time server" idea. Improved its formatting though, and added some cities for fun.
# PHP
```
$page = file_get_contents("http://www.timeapi.org/utc/now");
echo "In London: ".date("H:i:s - jS F, Y", strtotime($page))."<br>";
echo "In Rome: ".date("H:i:s - jS F, Y", strtotime($page)+3600)."<br>";
echo "In Athens: ".date("H:i:s - jS F, Y", strtotime($page)+7200)."<br>";
```
[Answer]
# Bash
```
echo "It's eight o'clock."
```
With thanks to [The Goon Show](https://www.youtube.com/watch?v=ctM_Rvgjfpo). (Also, it's right twice a day!)
[Answer]
## C/WinAPI
This makes the assumption that my own API calls to query the clock are broken, but the system itself can work with the time correctly.
```
// NO ERROR CHECKING - that's left as an exercise for the reader
TCHAR tmpfilename[MAX_PATH];
TCHAR tmpfilepath[MAX_PATH];
// get some information to create a temporary file
DWORD dwRes = GetTempPath(MAX_PATH, tmpfilepath);
UINT uiRes = GetTempFileName(tmpfilepath, TEXT("golftime"), 0, tmpfilename);
// create the file
HANDLE hTempFile = CreateFile(tmpfilename, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
// read the creation time of the file. accuracy is to, uhm... 10ms on NTFS?
FILETIME created;
GetFileTime(hTempFile, &created, NULL, NULL);
// convert the filetime to a system time (in UTC)
SYSTEMTIME systime;
FileTimeToSystemTime(&created, &systime);
std::cout << "Time is " <<
systime.wHour << ":" << systime.wMinute << ":" << systime.wSecond << "." << systime.wMilliseconds << "\n";
// close the file and delete
CloseHandle(hTempFile);
DeleteFile(tmpfilename);
```
The idea is to create a temporary file, and read the creation time, which on NTFS I think is accurate down to 10ms. Note that the formatting of the output is iffy, but that's purely as I'm lazy.
Output on my machine just now: `Time is 10:39:45.790`
[Answer]
### Batch
```
@echo off
echo.>>%0
for /f "tokens=2,3 skip=4" %%a in ('dir /TW %0') do echo %%a %%b & goto :EOF
```
Writes a blank line to the batch file (itself), then checks the last write time of the file.
```
H:\uprof>GetTime.bat
09:28 AM
H:\uprof>GetTime.bat
09:29 AM
```
[Answer]
**HTML, CSS & Javascript/jQuery**
Ok, so I know this isn't technically a program, and probably falls outside of the criteria, but in only a few hours time, this will be the most accurate clock in the world!
CSS
```
@font-face {
font-family:"DSDIGI";
src:url("http://fontsforweb.com/public/fonts/1091/DSDIGI.eot") format("eot"),
url("http://fontsforweb.com/public/fonts/1091/DSDIGI.ttf") format("truetype");
font-weight:normal;
font-style:normal;
}
#backer {
background-image: url('http://i.imgur.com/w3W5TPd.jpg');
width: 450px;
height: 354px;
color: red;
font-family: 'DSDIGI';
}
#backer p {
width: 100%;
display: block;
line-height: 325px;
font-size: 60px;
}
```
HTML
```
<div id="backer">
<p>
BEER<span id="fade">:</span>30
</p>
</div>
```
jQuery
```
function start() {
$('#fade').fadeOut(function() {
$('#fade').fadeIn();
});
setTimeout(start, 1000);
}
start();
```
At first I was going to do a `while(true)` loop, but then remembered that I didn't want to crash any browsers...
Here is a fiddle of it in action: <http://jsfiddle.net/E7Egu/>
![enter image description here](https://i.stack.imgur.com/NXPO1.gif)
[Answer]
## Emacs Lisp
The google thing has been done but not in emacs!
```
(url-retrieve "http://www.google.com/search?q=time" (lambda(l)
(search-forward-regexp "[0-9]?[0-9]:[0-9][0-9][ap]m")
(print (buffer-substring (point) (1+ (search-backward ">"))))))
```
[Answer]
node.js / Javascript
```
var fs = require('fs'),
util = require('util');
var date = null, time = null;
fs.readFile('/sys/class/rtc/rtc0/date', 'UTF-8', function(err, d) {
date = d.trim();
if(time)
done();
})
fs.readFile('/sys/class/rtc/rtc0/time', 'UTF-8', function(err, t) {
time = t.trim();
if(date)
done();
});
function done() {
console.log(util.format('%sT%sZ', date, time));
}
```
[Answer]
# JavaScript
```
new Date(performance.timing.navigationStart+performance.now())+''
```
Since clock/time API is broken, I use [Performance API](https://developer.mozilla.org/en-US/docs/Web/API/Performance) to get the time. Then `Date` is only used to parse it to string.
[Answer]
# PHP:
```
$n=PHP_SHLIB_SUFFIX=='dll'?strtotime(str_replace(PHP_EOL,' ',`date /t&time /t`).' GMT'):`date +%s`;
```
This will read the system time from the available command line interface.
The backtick operator is used to do just that: run a command.
Another way would be:
```
$_SERVER['REQUEST_TIME'];
```
Which contains the **current** time at which the script was called.
[Answer]
## Bash
```
export PS1="(\t) $PS1"
```
Skirts the rules a little bit, but it never calls a time function. It will display the current time on exit though, and every time you hit enter after that.
[Answer]
**C#**
This super-exact method will work - provided you'll run the program at 0:00:00,0000
```
using System;
using System.Threading;
namespace ConsoleApplication1 {
class Program {
private static volatile int s_Hour;
private static volatile int s_Minute;
private static volatile int s_Second;
private static volatile int s_Millisecond;
class Looper {
public int Length { get; set; }
public Action Update { get; set; }
}
static void Loop(object args) {
var looper = (Looper)args;
while (true) {
Thread.Sleep(looper.Length);
looper.Update.Invoke();
}
}
static void Main(string[] args) {
var starter = new ParameterizedThreadStart(Loop);
new Thread(starter).Start(new Looper { Length = 100, Update = () => { s_Millisecond = (s_Millisecond + 100) % 1000; } });
new Thread(starter).Start(new Looper { Length = 1000, Update = () => { s_Second = (s_Second + 1) % 60; } });
new Thread(starter).Start(new Looper { Length = 60 * 1000, Update = () => { s_Minute = (s_Minute + 1) % 60; } });
new Thread(starter).Start(new Looper { Length = 60 * 60 * 1000, Update = () => { s_Hour++; } });
Console.Out.WriteLine(@"Press e to exit, enter to write current time...");
while (true) {
string input = Console.In.ReadLine();
if (input == "e") {
Environment.Exit(0);
return;
}
Console.Out.WriteLine("{0:00}:{1:00}:{2:00},{3}", s_Hour, s_Minute, s_Second, s_Millisecond);
}
}
}
}
```
[Answer]
Linux, most shells, on hardware with an RTC:
```
echo `cat /sys/class/rtc/rtc0/{date,time} | tr "\n" " "`
```
[Answer]
## Java
We all know Java Date/Time API is unusable and broken. So here's a fix that does not (at least directly) use any of the existing API. It even supports leap seconds! :) The output is in UTC.
```
import java.lang.reflect.Field;
import java.net.HttpCookie;
import java.util.*;
public class FixedTimeAPI4Java {
private static final List<Integer> MONTHS_WITH_30_DAYS = Arrays.asList(4, 6, 9, 11);
private static final List<Integer> YEARS_WITH_LEAP_SECOND_IN_DECEMBER = Arrays.asList(1972, 1973, 1974, 1975, 1976, 1977, 1978, 1979, 1987, 1989, 1990, 1995, 1998, 2005, 2008);
private static final List<Integer> YEARS_WITH_LEAP_SECOND_IN_JUNE = Arrays.asList(1972, 1981, 1982, 1983, 1985, 1992, 1993, 1994, 1997, 2012);
/**
* Returns the UTC time, at the time of method invocation, with millisecond
* precision, in format <code>yyyy-MM-dd HH:mm:ss.SSS</code>.
*/
public String getTime() throws Exception {
// The cookie is only used for accessing current system time
HttpCookie cookie = new HttpCookie("Offline", "Cookie");
Field created = HttpCookie.class.getDeclaredField("whenCreated");
created.setAccessible(true);
long millisecondsSinceEpoch = created.getLong(cookie);
long fullSecondsSinceEpoch = millisecondsSinceEpoch / 1000L;
int year = 1970, month = 1, dayOfMonth = 1, hour = 0, minute = 0, second = 0,
millisecond = (int)(millisecondsSinceEpoch - (fullSecondsSinceEpoch * 1000L));
ticks:
for (;; year++) {
for (month = 1; month <= 12; month++) {
for (dayOfMonth = 1; dayOfMonth <= daysInMonth(month, year); dayOfMonth++) {
for (hour = 0; hour < 24; hour++) {
for (minute = 0; minute < 60; minute++) {
for (second = 0; second < secondsInMinute(minute, hour, dayOfMonth, month, year); second++, fullSecondsSinceEpoch--) {
if (fullSecondsSinceEpoch == 0) {
break ticks;
}
}
}
}
}
}
}
return String.format("%04d-%02d-%02d %02d:%02d:%02d.%03d", year, month,
dayOfMonth, hour, minute, second, millisecond);
}
/**
* Returns the seconds in the given minute of the given hour/day/month/year,
* taking into account leap seconds that can be added to the last minute of
* June or December.
*/
private static int secondsInMinute(int minute, int hour, int day, int month, int year) {
return (minute == 59 && hour == 23 && ((day == 30 && month == 6) || (day == 31 && month == 12)))
? 60 + leapSecondsInMonth( month, year)
: 60;
}
/**
* Returns the number of days in the given month of the given year.
*/
private static int daysInMonth(int month, int year) {
return month == 2 ? isLeapYear(year) ? 29 : 28
: MONTHS_WITH_30_DAYS.contains(month) ? 30
: 31;
}
/**
* Returns whether the given year is a leap year or not.
* A leap year is every 4th year, but not if the year is divisible by 100, unless if it's divisible by 400.
*/
private static boolean isLeapYear(int year) {
return (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) ? true : false;
}
/**
* Returns the number of leap seconds that were added to UTC time at the end of the given month and year.
* Leap seconds are added (by the decison of International Earth Rotation Service / Paris Observatory)
* in order to keep UTC within 0.9 seconds of international atomic time (TAI).
* <p>TODO: implement parser for updated list at http://www.ietf.org/timezones/data/leap-seconds.list :)
*/
private static int leapSecondsInMonth(int month, int year) {
return (year < 1972 || year > 2012) ? 0
: (month == 6 && YEARS_WITH_LEAP_SECOND_IN_JUNE.contains(year)) ? 1
: (month == 12 && YEARS_WITH_LEAP_SECOND_IN_DECEMBER.contains(year)) ? 1
: 0;
}
public final static void main(String[] args) throws Exception {
System.out.println(new FixedTimeAPI4Java().getTime());
}
}
```
] |
[Question]
[
In an [earlier challenge](https://codegolf.stackexchange.com/questions/188988/ddoouubbllee-ssppeeaakk) I asked code golfers to produce strings which copy each character in a string. For example:
```
TThhiiss iiss ddoouubbllee ssppeeaakk!!
```
This challenge is simply to detect if some text meets the definition of a double speak string.
* There is an even number of characters.
* When split into pairs, every pair consists of two of the same character.
---
The challenge
* It's code golf, do it in few bytes.
* Use any language you choose.
* Please include a link to an online interpreter.
* The code will accept some text.
* For simplicity, the input will only consist of *printable ASCII characters*
* It will return an indication of whether or not the input is double speak. It could be:
* A boolean
* Strings ('true', 'false', 'yes', 'no' etc)
* Integers 0 or 1
---
Test Cases:
```
input -> output
aba -> false
aab -> false
abba -> false
aabb -> true
aaabb -> false
tthhiiss -> true
ttthhhiiisss -> false
```
[Answer]
# [Python 3](https://docs.python.org/3/), 24 bytes
```
lambda s:s[::2]==s[1::2]
```
[Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUaHYqjjaysoo1ta2ONoQxPhfUJSZV6KRpqEUEpKRkZlZXKygACFTUvLzS0uTknJyUlMVFIqLCwpSUxMTs7MVFZU0NbkQ2jIyixUyi/PUS4DC/wE "Python 3 – Try It Online")
[Answer]
# [brainfuck](https://github.com/TryItOnline/brainfuck), 20 bytes
*Saved 1 byte thanks to Jo King.*
```
+>,[>,[-<->]<[<],]<.
```
[Try it online!](https://tio.run/##SypKzMxLK03O/v9f204nGoh0bXTtYm2ibWJ1Ym30/v8PCcnIyMwsLlZQgJApKfn5paVJSTk5qakKCsXFBQWpqYmJ2dmKigA "brainfuck – Try It Online")
[Readable output!](https://tio.run/##SypKzMxLK03O/v9f204nGoh0bXTtYm2ibWJ1YnWjdUHARhsoAKT1/v8PCcnIyMwsLlZQgJApKfn5paVJSTk5qakKCsXFBQWpqYmJ2dmKigA "brainfuck – Try It Online")
Takes input two characters at a time, and moves away from the 1 on the tape if any pair doesn't match. EOF is treated as 0 and thus handled automatically.
Output is a null byte if the string is not double speak, and 0x01 if it is. The readable version outputs these as characters at a cost of 14 bytes.
[Answer]
# [MATL](https://github.com/lmendo/MATL), 4 bytes
```
Heda
```
Input is a string, enclosed with single qoutes. Output is `0` for double speak, `1` otherwise.
[Try it online!](https://tio.run/##y00syfn/3yM1JfH/f/WQkIyMzMziYgUFCJmSkp9fWpqUlJOTmqqgUFxcUJCampiYna2oqA4A)
### Explanation
Consider input `'TThhiiss iiss ddoouubbllee ssppeeaakk!!'` as an example.
```
H % Push 2
% STACK: 2
% Implicit input (triggered because the next function requires two inputs): string
% STACK: 'TThhiiss iiss ddoouubbllee ssppeeaakk!!', 2
e % Reshape as a 2-column matrix of chars, in column-major order. Pads with char(0)
% if needed. Note that char(0) cannot be present in the input
% STACK: ['This is double speak!';
'This is double speak!']
d % Difference of each column
% STACK: [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]
a % Any: gives 0 if and only if all elements are 0
% STACK: 0
% Implicit display
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~6~~ ~~5~~ 2 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ιË
```
Input as a list of characters.
-3 bytes by porting [@Shaggy's Japt answer](https://codegolf.stackexchange.com/a/189372/52210), so make sure to upvote him!
[Try it online](https://tio.run/##yy9OTMpM/f//3M7D3f//RyuFKOmAcQYUZ0JxMRQrQDEu8RQozofiUihOguIcKE6FYpg@mDkFUAyTT4TibChWBONYAA) or [verify a few more test cases](https://tio.run/##yy9OTMpM/V9TVmmvpPCobZKCkn1l8P9zOw93/9f5HxKSkZGZWVysoAAhU1Ly80tLk5JyclJTFRSKiwsKUlMTE7OzFRW5iFbKRYKZqcUlXD45@fnl5ampRUXJyYmJxcWpqVzOzvn5RUWpqcnJJSUKClZWmppcJUCQmlpcXFKiCNSYCAcA).
**Explanation:**
```
ι # Uninterleave the (implicit) input-list of characters
# i.e. ["t","t","t","t","e","e","s","s","t","t","!","!","!"]
# → [["t","t","e","s","t","!","!"],["t","t","e","s","t","!"]]
Ë # Check if both inner lists are equal
# → 0 (falsey)
# (after which the result is output implicitly)
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 4 bytes
```
ó r¶
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=8yBytg&input=IlRUaGhpaXNzICBpaXNzICBkZG9vdXViYmxsZWUgIHNzcHBlZWFha2shISI)
```
ó r¶ :Implicit input of string
ó :Uniterleave
r :Reduce by
¶ : Testing equality
```
## Alternative
```
ó
¥o
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=8wqlbw&input=IlRUaGhpaXNzICBpaXNzICBkZG9vdXViYmxsZWUgIHNzcHBlZWFha2shISI)
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 5 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
■◄┼$Δ
```
[Run and debug it](https://staxlang.xyz/#p=fe11c524ff&i=TThhiiss++iiss++ddoouubbllee++ssppeeaakk%21%21%0Aaaaa%0Aaaa%0AThis+is+just+regular+speak.%0Aaabbc&a=1&m=2)
**Procedure:**
* Calculate run-lengths.
* Get GCD of array.
* Is even?
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 9 bytes
```
(.)\1
^$
```
[Try it online.](https://tio.run/##lYyxCsJAEAX7/Yo9UMg1Qtq0KWwsU4q4uTzIkcMLtxvy@WdAsNYpXjVvCiy@pK3n5vqszcXfW6LHqdZhmOcYVZk/O005b9s4pgQwq64rILIsztHPKv3RhBrdUs77DpQSgogqQH2fcylACGbMXec92QGgauaOo3x5Aw)
**Explanation:**
Remove all pair of the same characters:
```
(.)\1
```
Check if there are no characters left:
```
^$
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 3 bytes
```
ŒœE
```
[Try it online!](https://tio.run/##y0rNyan8///opKOTXf///x8SkpGRmVlcrKAAIVNS8vNLS5OScnJSUxUUiosLClJTExOzsxUVAQ "Jelly – Try It Online")
[Answer]
# JavaScript, 28 bytes
```
s=>s.every((x,y)=>x==s[y|1])
```
[Try it online!](https://tio.run/##bcxBCoMwEEDRfU8RXSXQDvQA8RTuxMXEjDU1OMGpYqB3TxG33fzNg//GHWVYQ/o8FvZURlvENgK005q1Pu7Z2OawVrr8ffamDLwIR4LILz3qDgDqtp2mEESUuuo987Y5FyORUiIpESHOc1XVvTG3Pwd0Dk8rPw "JavaScript (Node.js) – Try It Online")
---
**23 bytes** using wastl's regex
```
s=>/^((.)\2)*$/.test(s)
```
[Try it online!](https://tio.run/##XcuxCoMwEIDh3aeI0uGu0Aju@hSOpXAxZ40GL/Sirx8L3br8wwf/Sifp9AkpP3bxXOa@aD@0LwCLzw7vt9Zm1gyKZZJdJbKN8oYZmnFclhBUjfnVe5HjcC5GZmNUU2Im2ra6bhCrv5mcoy@XCw "JavaScript (Node.js) – Try It Online")
[Answer]
# x86 machine code, ~~9~~ 8 bytes
```
D1 E9 SHR CX, 1 ; divide length in half
L1:
AD LODSW ; load next two chars into AH/AL
3A E0 CMP AH, AL ; compare AH and AL
E1 FB LOOPE L1 ; if equal, continue loop
C3 RET ; return to caller
```
Callable function. Input string in `SI`, input string length in `CX`. Output `ZF` if is double speak.
### Or *14 bytes* as a complete PC DOS executable:
```
B4 01 MOV AH, 01H ; DOS read char from STDIN (with echo)
CD 21 INT 21H ; read first char into AL
92 XCHG DX, AX ; put first char into DL
B4 08 MOV AH, 08H ; DOS read char from STDIN (no echo)
CD 21 INT 21H ; read second char into AL
3A C2 CMP AL, DL ; compare first and second char
74 F3 JE -13 ; if the same, continue loop
C3 RET ; otherwise exit to DOS
```
Input is via `STDIN`, either pipe or interactive. Will echo the "de-doubled" input until a non-doubled character is detected, at which point will exit (maybe bending I/O rules a little bit, but this is just a bonus answer).
[![enter image description here](https://i.stack.imgur.com/ZShOq.png)](https://i.stack.imgur.com/ZShOq.png)
Build and test ISDBL2.COM using `xxd -r`:
```
00000000: b401 cd21 92b4 08cd 213a c274 f3c3 ...!....!:.t..
```
### Original *24 bytes* complete PC DOS executable:
```
D1 EE SHR SI, 1 ; SI to DOS PSP (080H)
AD LODSW ; load string length into AL
D0 E8 SHR AL, 1 ; divide length in half
8A C8 MOV CL, AL ; put string length into BL
CLOOP:
AD LODSW ; load next two chars into AH/AL
3A E0 CMP AH, AL ; compare AH and AL
E1 FB LOOPE CLOOP ; if equal, continue loop
DONE:
B8 0E59 MOV AX, 0E59H ; BIOS tty function in AH, 'Y' in AL
74 02 JZ DISP ; if ZF, result was valid double
B0 4E MOV AL, 'N' ; if not, change output char to N
DISP:
B4 0E MOV AH, 0EH
CD 10 INT 10H
C3 RET ; return to DOS
```
Input from command line, output to screen `'Y'` if double, `'N'` if not.
[![enter image description here](https://i.stack.imgur.com/1NFTK.png)](https://i.stack.imgur.com/1NFTK.png)
Build and test ISDBL.COM using `xxd -r`:
```
00000000: d1ee add0 e88a c8ad 3ae0 e1fb b859 0e74 ........:....Y.t
00000010: 02b0 4eb4 0ecd 10c3 ..N.....
```
### Credits:
* **-2 bytes** thx to @ErikF!
[Answer]
# [Malbolge (*unlimited memory access variant*)](https://esolangs.org/wiki/Malbolge_Unshackled), Around 4 megabytes
You asked the golfers, but for the second time forgot about the bowlers.
This is too big to include in the answer for obvious reason so here is gist [link](https://gist.githubusercontent.com/kspalaiologos/a02e57046360ec5f1265ec25ce26768b/raw/8d1bd1b4b705f227c2c76de9921205a7531704de/189358).
You might want to use the fast interpreter to test this program, as it's hellishly slow (hellishly, get it?). I'm going to include the TIO.run link after Dennis (hopefully) takes on my issue on TIO tracker.
// Edit: Nope, no TIO link as the answer size limit is 65536 bytes, and no abusing url shorteners because they just refuse to shorten it
[Answer]
# [PHP](https://php.net/), ~~58~~ 56 bytes
```
function f($s){return!$s?:$s[0]==$s[1]&f(substr($s,2));}
```
[Try it online!](https://tio.run/##hZCxboNADIbn3FMYhApIVKEdm6JsfYJsCYMhJqCgu9PZN0V59dK7UKlL1S72/8v2Z9l2tMv73oY4eN3LZDQMRcblzZF4p5OM928ZH@u2aUJ6aZ@Ggn3H4kJT9VqWu/uSCbEwNHBUCrZbEOdJQX44jOM0MQOs8Xw2xvuum2ciAGZriRCv1yTJq80mDIgQieRVkIiPVNeIdR3kgzvgzL@AtZE/2RDZ2HUrcl0iPzqqUI9LWrVTivrRQIbuoitIT5JW8R/RltHrk05D02AcYT8W8H078joCJdwC7h9GINwXEWaRT2Pjz3l5/vgC "PHP – Try It Online")
As a recursive function.
# [PHP](https://php.net/), ~~61~~ ~~56~~ 52 bytes
```
while(''<$l=$argn[$i++])$r|=$l!=$argn[$i++];echo!$r;
```
[Try it online!](https://tio.run/##hZHBbsMgDIbP5SmcCCmpmqk5L4122xP01vbgtE5BjQABUQ9bX30ZhGmdpqm7YGPwZ/4fI8y0eTHCMLZew9WiAakAoR/V0UutoNcWCJ0kC56cl@r8zO6HJUd7Vkt4m65CDlQWxYYP7VzccblaHZbcvrd8yH7WGjoKnXHbTDfGeKQ6aGHHGIQneDsSg2K7FUJK5wDSejppPY5dNwxEAM4ZQ4R4uWRZUS0WocF7Iu@LKqSIc6hrxLoOaQL3OLg/yEr7h3CIcOy6xExT/D2PWThPYR52YA1jUSHMkivI9z6vvq2Ke7VXebgUrCU8ihK@PECXWiD4GXD/MALhNv22Kap5IOdDm/hvbnp6/QQ "PHP – Try It Online")
Or standalone program. Input string via `STDIN`, output is `truthy` (`1`) if it is double speak, and `falsey` (`0`) if it is not double speak.
-4 bytes thx to [@Night2](https://codegolf.stackexchange.com/users/81663/night2)!
[Answer]
# [Haskell](https://www.haskell.org/), ~~28~~ 23 bytes
```
f(x:y:z)|x==y=f z
f[]=1
```
[Try it online!](https://tio.run/##bYyxDsIwDET3foUbMcDIWilbZ34AMcRtIqo4dYVTqa3492BWwo3v3t3TSfREpYTz1u3dcXlv1u42wNGE@8NeS3LTDBZGbkCzvKY5wwkCmL5nXldEIu8BRJbFe@dibFvzq96YOWf9UF19HWjGSnOIroZKEf9gopSYRXLOVSvCDDAMRF/Dm/IB)
Very straightforward. Double speak is only empty or a repeated character prepended to double speak.
Less straightforward now. Outputs via presence or absence of an error, per [meta consensus](https://codegolf.meta.stackexchange.com/a/11908/73884); no error means double speak. Pattern matching fails when the first two characters differ or when there are an odd number of characters. Thanks to [Laikoni](https://codegolf.stackexchange.com/users/56433/laikoni) for these savings!
[Answer]
# [Lua](https://www.lua.org), ~~67~~ ~~66~~ ~~63~~ ~~59~~ ~~33~~ 32 bytes
-25 bytes thanks to Giuseppe
-1 byte thanks to val
```
print(#(...):gsub("(.)%1","")<1)
```
[Try it online!](https://tio.run/##yylN/P@/oCgzr0RDWUNPT0/TKr24NElDSUNPU9VQSUdJSdPGUPP///@JiUlJiYkA "Lua – Try It Online")
Removes every doubled character, then checks if the result is empty.
[Answer]
# [Perl 5](https://www.perl.org/), 15 bytes
```
$_=/^((.)\2)*$/
```
[Try it online!](https://tio.run/##K0gtyjH9/18l3lY/TkNDTzPGSFNLRf///5CQjIzMzOJiBQUImZKSn19ampSUk5OaqqBQXFxQkJqamJidraj4L7@gJDM/r/i/bgEA "Perl 5 – Try It Online")
Outputs 1 for double-speak, nothing for non-double-speak.
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf), 2 bytes
```
½=
```
[Try it online!](https://tio.run/##y00syUjPz0n7///QXtv//9VLUotL1LnUS0pSU4uLS0DMjIzU1Jyc/HwdBYXy8vz8oqKcnJQURUWgjEcGkADRHlAV6EoA "MathGolf – Try It Online")
Basically the same as the 05AB1E answer, `½` splits the string into even and odd characters, then check for equality. Passes for the empty string.
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~39~~ 38 bytes
```
!$($args|?{+$p*($p="$_"[$p-eq$_])};$p)
```
[Try it online!](https://tio.run/##bZHBTsMwDIbvfQp3GNbCeIKpohJC2g0kequqKd3ctSwsWZwAUtdnL2FdD9vIIYr@z/lsyVp9k@GapOyxSto@xAiF2fDhqX1AfR@hTia4nOSoH2mPyyLu5qjjvguCNArAn1mE1jiaAUwXC/IepabxSCoh2aOR/APO49GUZXXdNMwAw71eK@VcWUpJBMCsNZEQ220Y@r@XTlGW4lopfHzdP8uI2NrL8iEfQBAfbtsjRvrRtLK0ngEyJIDLITbETlof3GEFqR/3BtiaZrcB1lJY618h0N41X0LSzkKlDOSrWpi8KI6G/O392bFVn6/lh29QpO2gTE7qOTT8cuo9Zn/rGOfxfKedL@cu6Pr@Fw "PowerShell – Try It Online")
where `$p` contains a previous char.
No [recursion](https://codegolf.stackexchange.com/a/189404/80745), no [regex](https://codegolf.stackexchange.com/a/189370/80745) :). Takes input as a char-array via a splatting string (see TIO link).
---
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 48 bytes
```
for(;$b-eq$a-and$args){$a,$b,$args=$args}$b-eq$a
```
[Try it online!](https://tio.run/##bZFNasMwEIX3PsWEqo0DzgmCwVAK2bVQ70Ioo3gcu1EtRSO1Bddnd1X/LJpEi0F63@i9QTL6iyxXpFQvyrTtS23jjZBrOgtcY1MItEdetQITIZPhkA61m3r6LoqyOIKwklg46ykBWG63FBy1Xq5mUqLigGZyA/yXZ6c8r6q6ZgYYa1Fo7b2UShEBMBtDhHg6LRbh7qUnSonXlhjk6/w8J2LnLttHfQTR6ue@HbCgb0MHR0UCgiEF8TbKltgrF4QHUUIWxr0DdrZujsBGoXNhtwA6@/oTFTUOwmvD7lCh3e33g8Pu5fXRs9Mfz/I9BOyzdrRMJ@sN1Pw0Zc/a3z/M8wTeGB/auYu6vv8F "PowerShell – Try It Online")
No [recursion](https://codegolf.stackexchange.com/a/189404/80745), no [regex](https://codegolf.stackexchange.com/a/189370/80745) and no pipe :D. It also takes input as a char-array via a splatting string. It uses `$b-eq$a` instead `$a-eq$b` for a case when a last char has #0 code.
[Answer]
# [Shakespeare Programming Language](https://github.com/TryItOnline/spl), ~~204~~ 156 bytes
-48 bytes thanks to Jo King (mostly by changing the output method)
```
A.Ajax,.Puck,.Act I:.Scene I:.[Exeunt][Enter Ajax and Puck]Ajax:Open mind.Puck:Open
mind.Is I worse zero?If soSpeak thy.Is you as big as I?If soLet usAct I.
```
[Try it online!](https://tio.run/##TY5BCsIwFESvMgcoOUA3kkUXAUGhy9JFTL9aq0nI/8HWy0dSN65mhnkMw/FZilb6YddGnbNbGqWdwLSqd@SpmqFbKXsZh84LJVQU1k@o9FhTe4rk8Zr9tC/8RcMweIfEhA@lcDBXcOgj2QVy32q9hQzLuMy3KuZHHEmQef@hShEh@gI "Shakespeare Programming Language – Try It Online")
Exits with error if the input is double speak, and with warning if it is not double speak (which is [allowed](https://codegolf.meta.stackexchange.com/a/5330/86301) by default).
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~6~~ 4 bytes
*-2 bytes thanks to Razetime!*
```
ETC2
```
[Try it online!](https://tio.run/##yygtzv7/3zXE2ej///9KJSUZGZlKAA "Husk – Try It Online")
Hooray for all ASCII solutions! Outputs a positive number if the input is doublespeak, otherwise zero.
```
C2 Cut list into chunks of 2
T Transpose
E Check if list has all the same elements (return length of list if so)
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 2 bytes
```
y=
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=y%3D&inputs=HHeelllloo&header=&footer=)
Look ma, no Unicode!
[Answer]
# [V (vim)](https://github.com/DJMcMayhem/V), 7 bytes
```
Óˆ±
ø^$
```
[Try it online!](https://tio.run/##K/v///DkQx2HNnId3hGn8v9/RkZqak5Ofj4A "V (vim) – Try It Online") or [Verify test cases](https://tio.run/##K/v//3Df4cmHOg5t5AIydsSp/P@fkZGampOTn89VXp6fX1SUk5OSwmVoaGRkbGxiYmrKlZ5eVJQKBHl5Cgrp6Tk5iYnFQKCgkJKSnw9Sz8XlATPA0MjYBKaVKwNmLgA)
Hexdump:
```
00000000: d388 b10a d85e 24 .....^$
```
Just two regexes. Explanation:
```
Ó " Remove all occurrences...
ˆ " Any character
± " Followed by itself
" This regex is actually just the compressed form of (.)\1
ø " Count the number of matches
^$ " An empty line
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 5 bytes
```
ġ₂z₂=
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRuX/2obcOjpuZHHcuVSopKU/WU9B51rFBKS8wpBrJrH@7qrH24dcL/IwsfNTVVAbHt///RSiEhGRmZmcXFCgoQMiUlP7@0NCkpJyc1VUGhuLigIDU1MTE7W1FRSUcpFQigFIj28EhNzcnJz9fRUVAID8/PLyrKyUlJAUpArYwFAA "Brachylog – Try It Online")
Succeeds or fails.
```
ġ₂ The at-most-length-2 chunks of the input,
z₂ which have equal length, zipped together,
= are equal.
```
[Answer]
# [INTERCAL](http://www.catb.org/~esr/intercal/), 192 bytes
```
PLEASE,1<-#2DOCOMEFROM(2)DOWRITEIN,1DO.5<-#1$',1SUB#1'~#256PLEASE(1)NEXTDOREADOUT#1DOGIVEUP(1)DO(1002)NEXTDO.5<-#1$',1SUB#2'~,1SUB#2DO(3)NEXTDOREADOUT#0PLEASEGIVEUP(3)DO(1002)NEXT(2)DOFORGET#2
```
[Try it online!](https://tio.run/##XY7BCoJAFEV/RZlABQtnxFZtrBlFSJ/oWG01BxQlJXPrr0@SbmxzeXDPO9z69RHvZ95KGV@ZmzITn/aIULhAyLwEQp0YFO5JwFkQmZjCwZl7vNNMnGZnhLUJEee4vOrYiNiDU0iYSyHjaMb94MayeG4o6NiyyEpsLUSb1mOm7D@JtchXkb0R/cZ5kPiMIyIl51VV18OgKEuWZdeNY1G0rRCKMgx9L0SeN42qfgE "INTERCAL – Try It Online")
Output is done with INTERCAL's native "butchered Roman numerals", so the true output of 1 prints as `\nI\n`, and the false output of 0 prints as `_\n\n`.
I don't feel like writing out a full explanation at the moment, but the ungolfed code is [here](https://tio.run/##y8wrSS1KTsz5/z/Ax9Ux2FVBx1DBRldB2YjLxV/B2d/XVcEtyN9XQcNIEyQQHuQZ4qrg6QdUBeLqmYLVGqqo6xgGhzopG6rXKRuZmnFBjdIw1FTwc40IASkNcnV0UfAPDQGqBnHdPcNcFUIDuEBKgFwNQwMDI4RidHON1OugDJCshjE2Yw1gtsKNNsYwGugLkJCbf5C7K1CL0f//jo5OIAAA), I lifted the control flow from [something I wrote earlier](https://codegolf.stackexchange.com/a/181789/85334), and the gist of what it does is read two characters at a time from the input through the usually unhelpful "Turing Tape" I/O until either the first resulting number is 256 (in which case the entire input has been validated and has even length, so it is double-speak), or the second resulting number is not 0 (in which case the second character is different from the first or does not exist, and the input is not double-speak).
I think I might be able to restructure this to cut down on redundancy, but I'm not quite feeling up to that at the moment either.
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~64~~ 59 bytes
```
filter f($n){$a,$b,$r=$n;$a-eq$b-and$(if($r){f $r}else{1})}
```
[Try it online!](https://tio.run/##bcmxCoMwEAbgvU8R5B8S0KFz6Vu4icOlvaAQ0vYS6BDy7Kcdla7f9359WfLCMaqGNRYWEyySq6AevofckW6ggT/wA6Un7Lq/uBoMpHHMXK/NNQ3GTo@FZJrnjrynzl0OtNuJxpE551L@8U9VNw "PowerShell – Try It Online")
Recursive function, no regex. Takes input as a `char`-array (see TIO link). Peels off the first two elements into `$a` and `$b`, stores the remaining into `$r`. If we still have elements remaining, recurse along with `$a -eq $b`. Otherwise just check whether `$a -eq $b`. Output is implicit.
*-5 bytes thanks to mazzy*
[Answer]
# [Julia 1.0](http://julialang.org/), 25 bytes
```
s->s[1:2:end]==s[2:2:end]
```
[Try it online!](https://tio.run/##yyrNyUw0rPifZvu/WNeuONrQysgqNS8l1ta2ONoIyv5fUJSZV5KTp5GmoRQSkpGRmVlcrKAAIVNS8vNLS5OScnJSUxUUiosLClJTExOzsxUVlTQ1uYjXiKLvPwA "Julia 1.0 – Try It Online")
[Answer]
# [J](http://jsoftware.com/), ~~13~~ ~~11~~ 10 bytes
```
-:2#_2{.\]
```
[Try it online!](https://tio.run/##RUy9CsIwGNz7FFcdgtAG6RhwsdBJHLSjIkn6lcYWUvyayYePQaEe3MFxP8@4kaLHQUGgwB4qsZSoL6cmlqraPqq3vN3jLjsfJa7BWmLOyA4ePUTbDoNzzMBPu877EIyZJiKAeZ6JtB7HPBfrZkmgdLIsIvueNtpN4UVrQWtj7NovlND/cYqSix8 "J – Try It Online")
*-2 bytes thanks to Adám*
*-1 byte thanks to miles*
TLDR explanation: Is the input the same as every other character of the input doubled?
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~27~~ ~~26~~ 24 bytes
```
2==GCD@@Length/@Split@#&
```
[Try it online!](https://tio.run/##NYuxCsIwFEX3fkVMoZNScK8@qCCCg2A3cXhJXk1o2obmdRK/PUqLdzjnLLdHttQjO42prdK@qs71CeBKw4ttCffgHUNepNvkBn7ku0MLtcUJNdMUIX8WJbwz2TTWOhejECuNGcd5Vsp7IiFiDIEIses2G7nNJKL6bSmlcLVWeqlLFI6FGWflScRA2B3/F62NzD7pCw "Wolfram Language (Mathematica) – Try It Online")
```
Length/@Split@#& (*for the lengths of runs of characters*)
2==GCD@@ (*check that they are all even*)
```
[Answer]
# [Keg](https://github.com/JonoCode9374/Keg), ~~19~~ 17 characters
```
?{!1<|=[|0.(_)]}1
```
Explanation:
```
? # read input
{ # while
!1< # stack length greater than 1?
| # end of while condition and beginning of while block
= # compare the 2 top values in the stack
[ # if (the condition is the top of stack)
| # end of then block and beginning of else block
0. # output 0
(_) # clear stack (discard top of stack in for loop stack length times)
] # end if
} # end while
1 # stack is already empty, push a truthy value
# implicitly output the stack content if there was no explicit output
```
[Try it online!](https://tio.run/##y05N///fvlrR0KbGNrrGQE8jXjO21vD//5CQjIzMzOJiBQUImZKSn19ampSUk5OaqqBQXFxQkJqamJidragIAA "Keg – Try It Online")
[Answer]
# Curry, 18 bytes
*Tested to work in both [PAKCS](https://www.informatik.uni-kiel.de/%7Epakcs/) and [KiCS2](https://www-ps.informatik.uni-kiel.de/kics2/)*
```
f(a:a:x)=f x
f[]=1
```
[Try it online!](https://tio.run/##HcixDkAwFAXQ3VdcYmAgsTbpZjGxi@HhNZEWTatJfX0lzni24NzbWNKbT0lVJEjEWirETM2L7NJJxwUhMDk2Yed2GFHV2b8S1h3XgxIKRd/fdwjragwz4L21zERa53mRPg "Curry (PAKCS) – Try It Online")
[Test it on smap!](https://smap.informatik.uni-kiel.de/smap.cgi?browser/78)
This returns `1` if string is double speak and nothing otherwise.
## Explanation
This is a pretty straight forward translation of the Haskell program:
```
f(a:b:x)|a==b=f x
f[]=1
```
But it uses Curry's more powerful pattern matches to save a bunch of bytes. And while missing a pattern in Haskell is rather difficult to recover from, making this definitely pretty un-idiomatic at best and perhaps a little cheaty. In curry missing patterns just mean it's not a match which is idiomatic and recoverable. So it's shorter and I don't feel like I'm cheating.
## Testing
TIO has a limited ability to test things like this. I recommend you use the [smap link](https://smap.informatik.uni-kiel.de/smap.cgi?browser/78) to test this.
This test handler I've made on smap will not work in KiCS2 or the newer version of PAKCS so you must select `PAKCS 2.2.0` (both `/one-value` and `/all-values` work fine). This is because of the library `Control.SetFunctions` which I use for the test. But the function itself does work in the versions if you want to manually test it.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 14 [bitsv2](https://github.com/Vyxal/Vyncode/blob/main/README.md), 1.75 bytes
```
y=
```
[Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyI9fiIsIiIsInk9IiwiIiwiISguKikgLT4gKFxcZClcbmFiYSAtPiAwXG5hYmJhIC0+IDBcbmFhYmIgLT4gMVxuYWFhYmIgLT4gMFxudHRoaGlpc3MgLT4gMVxudHR0aGhoaWlpc3NzIC0+IDAiXQ==)
Basically every other answer
## Explained
```
y=
y # Uninterleave the input, dumping to stack
= # Are the two items equal?
```
] |
[Question]
[
For any positive 32-bit integer (`1 ≤ n ≤ 0xFFFFFFFF`) output the number of bits needed to represent that integer.
# Test cases
```
| n | n in binary | bits needed |
|----------------------------------|
| 1 | 1 | 1 |
| 2 | 10 | 2 |
| 3 | 11 | 2 |
| 4 | 100 | 3 |
| 7 | 111 | 3 |
| 8 | 1000 | 4 |
| 15 | 1111 | 4 |
| 16 | 10000 | 5 |
| 128 | 10000000 | 8 |
| 341 | 101010101 | 9 |
4294967295 => 11111111111111111111111111111111 => 32
```
So `f(16)` would print or return `5`
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Shortest code in bytes wins
[Answer]
# JavaScript (ES6), 18 bytes
```
f=n=>n&&1+f(n>>>1)
```
```
<input type=number min=0 step=1 value=8 oninput="O.value=f(this.value)">
<input id=O value=4 disabled>
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 2 bytes
```
bg
```
[Try it online!](https://tio.run/nexus/05ab1e#@5@U/v@/sZEpAA "05AB1E – TIO Nexus")
[Answer]
# x86 Assembly, 4 bytes
Assuming Constant in `EBX`:
```
bsr eax,ebx
inc eax
```
EAX contains the number of bits necessary for Constant.
Bytes: `☼¢├@`
Hexadecimal: `['0xf', '0xbd', '0xc3', '0x40']`
[Answer]
# [Python](https://docs.python.org/3/), 14 bytes
```
int.bit_length
```
[Try it online!](https://tio.run/nexus/python3#DctLCoAgFEbhca3iJxAUboFpD4JaSRCEWULcIty/OfgGZ3A8ZqwpcGz2ELf74DNeyT8fGIGhCS3BECxhIIwE3WV91uYwVk9l8X55l5UwDvUC4SoISCZ4yUqp9AM "Python 3 – TIO Nexus")
[Answer]
## Mathematica, 9 bytes
```
BitLength
```
Alternatively:
```
Floor@Log2@#+1&
#~IntegerLength~2&
```
[Answer]
## [Labyrinth](https://github.com/m-ender/labyrinth), ~~13~~ 12 bytes
```
?
_:
2/#(!@
```
[Try it online!](https://tio.run/nexus/labyrinth#@69gzxVvxWWkr6yh6PD/v6EZAA "Labyrinth – TIO Nexus")
### Explanation
The program simply repeatedly divides the input by 2 until it's zero. The number of steps are kept track of by duplicating the value at each step. Once it's reduced to zero we print the stack depth (minus 1).
The program starts at the `?` which reads the input. The main loop is then the 2x2 block below, going counter-clockwise:
```
: Duplicate current value.
_2 Push 2.
/ Divide.
```
Once the value is zero after a full iteration, the linear bit at the end is executed:
```
# Push stack depth.
( Decrement.
! Print.
@ Terminate.
```
[Answer]
# C, 31 bytes
```
f(long n){return n?1+f(n/2):0;}
```
... Then I thought about recursion. From obscure to obvious, and with one fourth of the length dropped off.
[See it live on Coliru](http://coliru.stacked-crooked.com/a/f5b6517d8f479be3)
---
# ~~C, 43 bytes~~
```
c;
#define f(v)({for(c=0;v>=1l<<c;++c);c;})
```
Calling `f` with an **unsigned** value (e.g. `f(42u)`) will "return" its bit length. Even works for `0u` !
**Ungolfed and explained:** (backslashes omitted)
```
c;
#define f(v)
({ // GCC statement-expression
// Increment c until (1 << c) >= v, i.e
// that's enough bits to contain v.
// Note the `l` to force long
// arithmetic that won't overflow.
for(c = 0; v >= 1l << c; ++c)
; // Empty for body
c; // Return value
})
```
[See it live on Coliru](http://coliru.stacked-crooked.com/a/26c71114f72b0815)
[Answer]
# [Perl 6](https://perl6.org), 7 bytes
```
*.msb+1
```
[Try it](https://tio.run/nexus/perl6#HcrZBoBAGAbQ@@8pvoukhfjbSb3KaJmIFhrFSM8@0bk@l9G8y2RsgM3SH49Js3VRspkhFtdgPk6uy65NEPIBaXpLT7Ht@NfYU3idIEWGHBVqSAEpIWmNLBd8 "Perl 6 – TIO Nexus")
## Explanation:
[`*`](https://docs.perl6.org/type/WhateverCode) makes it become a WhateverCode lambda, and indicates where to put the input
[`.msb`](https://docs.perl6.org/routine/msb) on an Int returns the index of the most significant bit (0 based)
`+1` is combined into the lambda, and adds one to the eventual result of calling `.msb`.
[Answer]
# C preprocessor macro (with gcc extensions), 26
```
#define f 32-__builtin_clz
```
Uses GCC's [count-leading-zeros builtin](https://gcc.gnu.org/onlinedocs/gcc/Other-Builtins.html#index-g_t_005f_005fbuiltin_005fclz-4353).
Call this as a function, e.g. `f(100)`.
[Try it online](https://tio.run/nexus/c-gcc#ZY7rboJAEIX/8xQnGhNWt60ueCHYvoglhMKik9DF7C79oeHZ6WAvMXGSSebM5cw3JVM2XaWxd76i9vn0NkwrXZPRqBGppzz/6KjxZPKyuQxkPD4LMgjHqrDHUqI8FRbzOYsvgWsAjnFIaXCrm9Yc4bXzZeG0O2R4xRUrCSURScQSW4mdxGrNueFULKKYF2KVxMlmq5I1@l@vurX8mR2WKQh7OLrotg7/3QVeHnqHZSZ4e7H4gxvjbBmxDiezppKYVe9mIu8YKZO4d6BMiPR22/9wWO07a5gi6Idv).
[Answer]
# [Retina](https://github.com/m-ender/retina), 56 37 bytes
**This solution works with all the required input values.**
The biggest problem Retina faces in this challenge is the fact that its strings have a maximum length of 2^30 characters, so the usual way of dealing with numbers (unary representation) doesn't work with values greater than 2^30.
In order to solve this problem I adopted a different approach, keeping a sort of decimal representation of numbers, but where each digit is written in unary (I'll call this representation *digitunary*). For example the number `341` would be written as `111#1111#1#` in digitunary. With this representation we can now work with numbers of up to `2^30/10` digits (~ a hundred million digits). It is less practical than standard unary for arbitrary arithmetic, but with a bit of effort we could do any kind of operations.
>
> NOTE: digitunary in theory could use any other base (e.g. binary `110` would be `1#1##` in base 2 digitunary), but since Retina has builtins to convert between decimal and unary and no direct way to deal with other bases, decimal is probably the most manageable base.
>
>
>
The algorithm I used is making successive integer divisions by two until we reach zero, the number of divisions we made is the number of bits needed to represent this number.
So, how do we divide by two in digitunary? Here's the Retina snippet that does it:
```
(1*)(1?)\1# We divide one digit, the first group captures the result, the second group captures the remainder
$1#$2$2$2$2$2 The result is put in place of the old number, the remainder passes to the next digit (so it is multiplied by 10) and is divided by two there -> 5 times the remainder goes to the next digit
```
This replacement is enough to divide a digitunary number by 2, we just need to remove possible .5s from the end if the original number was odd.
So, here's the full code, we keep dividing by two until there are still digits in the number, and put a literal `n` in front of the string at each iteration: the number of `n` at the end is the result.
```
. |
$*1# Convert to digitunary
{`^(.*1) Loop:|
n$1 add an 'n'
(1*)(1?)\1# |
$1#$2$2$2$2$2 divide by 2
)`#1*$ |
# erase leftovers
n Return the number of 'n's in the string
```
[Try it online!](https://tio.run/nexus/retina#@6/HpaJlqMxVnRCnoadlqMmVp2LIpWGopalhaK8ZA5RQMVRWMYJBLs0EZUMtFS5lrrz//02MLE0szcyNLE0B "Retina – TIO Nexus")
---
**Updated solution, 37 bytes**
Big refactoring with many good ideas that golfed about a third of the length, all thanks to Martin Ender!
The main idea is to use `_` as our unary symbol: in this way we can use regular digits in our string, as long as we convert them back to `_`s when it is needed: this lets us save many bytes on division and on insertion of multiple digits.
Here's the code:
```
<empty line> |
# put a # before each digit and at the end of the string
{`\d Loop:|
$*_ Replace each digit with the corrisponding number of _
1`_ |
n_ Add an 'n' before the first _
__ |
1 Division by 2 (two _s become a 1)
_# |
#5 Wherever there is a remainder, add 5 to the next digit
}`5$ |
Remove the final 5 you get when you divide odd numbers
n Return the number of 'n's in the string
```
[Try it online!](https://tio.run/nexus/retina#@8@lzFWdEJPCpaIVz2WYEM@VF88VD2RxxStzKZty1SaYqnBx5f3/b2JkaWJpZm5kaQoA "Retina – TIO Nexus")
[Answer]
# Ruby, ~~19~~ 16 bytes
```
->n{"%b"%n=~/$/}
```
Thanks Jordan for golfing off 3 bytes
[Answer]
# Jolf, 2 bytes
```
lB
```
Just convert to binary and then find the length.
[Answer]
# [Julia 0.4](http://julialang.org/), 14 bytes
```
!n=log2(2n)÷1
```
[Try it online!](https://tio.run/nexus/julia#Dce7CYAwFAXQWqe4CkICzyKJv0ZxEMuoCHKV4G4O4GAxxSlOLDie126Vpf5eE7crgDgIZQRW4ASNoBcMAtMmXWJTXGN0ns13OPhsqqycRz2h8gtLAQUFdb7Sxx8 "Julia 0.4 – TIO Nexus")
[Answer]
# JavaScript ES6, 19 bytes
```
a=>32-Math.clz32(a)
```
[`Math.clz32`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/clz32) returns the number of leading zero bits in the 32-bit binary representation of a number. So to get the amount of bits needed, all we need to do is substract that number from 32
```
f=
a=>32-Math.clz32(a)
```
```
pre {
display: inline;
}
```
```
<input id=x type="number" oninput="y.innerHTML = f(x.value)" value=128><br>
<pre>Bits needed: <pre id=y>8</pre></pre>
```
[Answer]
# bash / Unix tools, 16 bytes
```
dc<<<2o$1n|wc -c
```
Save this in a script, and pass the input as an argument. The number of bits required to represent that number in binary will be printed.
Here's an explanation:
dc is a stack-based calculator. Its input, parsed into tokens, is:
2 — Push 2 on the stack.
o — Pop a value off the stack (which is 2) and make it the output base (so output is now in binary).
The value of the argument to the bash program ($1) — Push that argument on the stack.
n — Pop a value off the stack (which is the input number) and print it (in binary, because that's the output base) with no trailing newline.
So the dc command prints the number in binary.
The output of dc is piped to the command wc with the -c option, which prints the number of characters in its input.
The end result is to print the number of digits in the binary representation of the argument.
[Answer]
# Google Sheets, 15 Bytes
Takes input from cell `A1` and outputs to the cell that holds the formula
```
=Len(Dec2Bin(A1
```
or
```
=Int(1+Log(A1,2
```
or
```
=Int(Log(2*A1,2
```
# Excel, 17 Bytes
Same as above but formatted for MS Excel
```
=Len(Dec2Bin(A1))
```
or
```
=Int(1+Log(A1,2))
```
or
```
=Int(Log(2*A1,2))
```
[Answer]
# Pyth, 3 bytes
```
l.B
```
[Test suite available here.](http://pyth.herokuapp.com/?code=l.B&input=3&test_suite=1&test_suite_input=1%0A2%0A3%0A4%0A7%0A8%0A15%0A16%0A128%0A341&debug=0)
### Explanation
```
l.BQ Q is implicitly appended
Q eval(input)
.B convert Q to binary string
l len(.B(Q))
```
[Answer]
# Jelly, 2 bytes
```
BL
```
Converts to binary, finds length.
[Answer]
# C#, ~~63~~ ~~45~~ 31 bytes
Saved 18 bytes, thanks to Loovjo, and TuukkaX
Saved 14 bytes, thanks to Grax
```
b=>1+(int)System.Math.Log(b,2);
```
It uses, that a decimal number n has ⌊log2(n)⌋+1 bits, which is described on [this](http://www.exploringbinary.com/number-of-bits-in-a-decimal-integer/) page:
>
> ## Number of Bits in a Specific Decimal Integer
>
>
> A positive integer n has b bits when 2^(b-1) ≤ n ≤ 2^b – 1. For example:
>
>
> * 29 has 5 bits because 16 ≤ 29 ≤ 31, or 2^4 ≤ 29 ≤ 2^5 – 1
> * 123 has 7 bits
> because 64 ≤ 123 ≤ 127, or 2^6 ≤ 123 ≤ 2^7 – 1
> * 967 has 10 bits because
> 512 ≤ 967 ≤ 1023, or 2^9 ≤ 967 ≤ 2^10 – 1
>
>
> For larger numbers, you could
> consult a table of powers of two to find the consecutive powers that
> contain your number.
>
>
> To see why this works, think of the binary representations of the
> integers 2^4 through 2^5 – 1, for example. They are 10000 through 11111,
> all possible 5-bit values.
>
>
> ## Using Logarithms
>
>
> The above method can be stated another way: the number of bits is the
> exponent of the smallest power of two greater than your number. You
> can state that mathematically as:
>
>
> bspec = ⌊log2(n)⌋ + 1
>
>
> That formula has three parts:
>
>
> * log2(n) means the logarithm in base 2 of n, which is the exponent to
> which 2 is raised to get n. For example, log2(123) ≈ 6.9425145. The
> presence of a fractional part means n is between powers of two.
> * ⌊x⌋ is the floor of x, which is the integer part of x. For example,
> ⌊6.9425145⌋ = 6. You can think of ⌊log2(n)⌋ as the exponent of the
> highest power of two in the binary representation of n.
> * +1 takes the exponent to the next higher power of two. You can think of this step as accounting for the 2^0th place of your binary number,
> which then gives you its total number of bits. For our example, that’s
> 6 + 1 = 7. You might be tempted to use the ceiling function — ⌈x⌉,
> which is the smallest integer greater than or equal to x — to compute
> the number of bits as such:
>
>
> bspec = ⌈log2(n)⌉
>
>
> However, this fails when n is a power of two.
>
>
>
[Answer]
# C#, 32 bytes
```
n=>Convert.ToString(n,2).Length;
```
Converts the parameter to a binary string and returns the length of the string.
[Answer]
## Haskell, 20 bytes
```
succ.floor.logBase 2
```
Composes a function that takes logarithm base 2, floors, and adds 1.
[Answer]
# [Befunge-93](http://esolangs.org/wiki/Befunge), ~~23~~ 21 Bytes
```
&>2# /# :_1>+#<\#1_.@
```
Befunge is a 2D grid-based language (although I'm only using one line).
```
& take integer input
>2# /# :_ until the top of the stack is zero, halve and duplicate it
1>+#<\#1_ find the length of the stack
.@ output that length as an integer and terminate the program
```
[Try it online!](https://tio.run/nexus/befunge#@69mZ6SsoK@sYBVvaKetbBOjbBiv5/D/v7GJIQA)
[Answer]
## [Jellyfish](https://github.com/iatorm/jellyfish), 4 bytes
```
p#bi
```
[Try it online!](https://tio.run/nexus/jellyfish#@1@gnJT5/7@hGQA "Jellyfish – TIO Nexus")
Print (`p`), the length (`#`) of the binary representation (`b`) of the input (`i`).
[Answer]
## [CJam](https://sourceforge.net/p/cjam), 5 bytes
```
ri2b,
```
[Try it online!](https://tio.run/nexus/cjam#@1@UaZSk8/@/oRkA "CJam – TIO Nexus")
Read input (`r`), convert to integer (`i`), get binary representation (`2b`), get length (`,`).
[Answer]
# [Octave](https://www.gnu.org/software/octave/), 19 bytes
```
@(x)ceil(log2(x+1))
```
Anonymous function that adds 1, computes binary logarithm and rounds up.
[Try it online!](https://tio.run/nexus/octave#@@@gUaGZnJqZo5GTn26kUaFtqKn5P03BViExr9iaK03DUFNHIU3DCEwag0kTMGkOJi3ApKEphDKDUEYQUWMTQ83/AA "Octave – TIO Nexus")
[Answer]
## [QBIC](https://drive.google.com/drive/folders/0B0R1Jgqp8Gg4cVJCZkRkdEthZDQ), 18 bytes
```
:{~2^q>a|_Xq\q=q+1
```
That's incredible Mike! But how does it work?
```
: Read input as integer 'a'
{ Start an infinite DO-LOOP
~2^q>a If 2 to the power of q (which is 1 by default) is greater than a
|_Xq Then quit, printing q
\q=q+1 Else, increment q
[LOOP is closed implicitly by QBIC]
```
[Answer]
# Java 8, ~~34~~ 27 bytes
For once, Java has some useful builtins! Now, we just need some shorter names...
```
x->x.toString(x,2).length()
```
[**Try it online!**](https://repl.it/FC9D)
Of course, you can do this without builtins ([see Snowman's answer](https://codegolf.stackexchange.com/a/105035/60919)), but for a higher byte count.
[Answer]
# Octave, 19 bytes
```
@(x)nnz(dec2bin(x)) % or
@(x)nnz(de2bi(x)+1) % or
@(x)nnz(de2bi(x)<2) % or
@(x)numel(de2bi(x)) % or
@(x)rows(de2bi(x'))
```
Octave has two functions for converting decimal numbers to binary numbers.
**`dec2bin`** converts a number into a string of the characters `1` and `0` (ASCII-values `48` and `49`). The length of the string will be equal to the necessary number of bits, unless specified otherwise. Since the characters `1` and `0` are non-zero, we can use `nnz` to find the number of elements like this: `@(x)nnz(dec2bin(x))`. This is 19 bytes, so it's tied with [Luis Mendo's other Octave answer](https://codegolf.stackexchange.com/a/104801/31516).
**Can we do better using `de2bi`?**
**`de2bi`** is a function that returns the binary numbers as a vector with the numbers `1` and `0` as integers, not characters. `de2bi` is obviously two bytes shorter than `dec2bin`, but we can no longer use `nnz`. We *can* use `nnz` if we either add `1` to all elements, or makes it into a logical vector with only `true` values. `@(x)nnz(de2bi(x)+1)` and `@(x)nnz(de2bi(x)<2)` are both 19 bytes. Using `numel` will also give us 19 bytes, `@(x)numel(de2bi(x))`.
`rows` is one byte shorter than `numel`, but `de2bi` returns a horizontal vector, so it must be transposed. `@(x)rows(de2bi(x)')` just so happens to be 19 bytes too.
[Answer]
## Pyke, 3 bytes
```
b2l
```
[Try it here!](http://pyke.catbus.co.uk/?code=b2l&input=12)
[Answer]
# Python 2, 28 Bytes
`def f(a):print len(bin(a))-2`
] |
[Question]
[
Inspired by [this default for IO](http://meta.codegolf.stackexchange.com/a/5330/44713).
## The Task
Write a program that, given an input integer `x` between 0 and 255, crashes with exit code `x`.
## Restrictions
* You may not call anything which is intended directly for exit code output (`System.exit(x)`, returning from `main`, etc.). Instead, your program must cause an error or crash which will cause, with a probability of 1, the program to exit with the input integer.
+ In this case, the words "error" and "crash" means that the program caused some fatal unintended exception, wherein a method, operation or otherwise was used incorrectly that caused an irreversible failure.
+ You may not directly cause the error by throwing it directly. You must cause it by using a method, function, or otherwise whose purpose serves a different function (i.e. attempting to execute a file write to a read-only directory).
* You must have at least two exit codes accounted for in your program.
* Termination of the process with the use of signals is banned. (Reasoning may be found [in this discussion](http://chat.stackexchange.com/transcript/message/34843663#34843663))
## Scoring
Your program's score is determined by the number of supported exit codes, where code concision is tiebreaker. The greatest number of supported exit codes wins!
[Answer]
# Unix Shell (+ncurses +BSD utilities), ~~36~~, 26 bytes, 256 exit codes
**Golfed**
```
jot -bu0 $[252+$1]|tput -S
```
>
> If the -S option is used, tput checks for errors from each line, and if any errors are found, will set the exit code to 4 plus the number of lines with errors. If no errors are found, the exit code is 0. No indication of which line failed can be given so exit code 1 will never appear. Exit codes 2, 3, and 4 retain their usual interpretation.
>
>
>
Once the *tput* exit code goes over 255, it just overflows, so 253 (errors on input) will result in the exit code of 1 e.t.c., thus yielding the desired exit status for the whole range of inputs.
*Note*: whether *tput* will fail on not, when setting/getting a particular capability, depends on the terminal type, I've used: `xterm with 256 colors`
[jot](https://www.freebsd.org/cgi/man.cgi?jot(1)) is a *BSD* utility, which
prints sequential or random data, and (AFAIK) is also available out of the box on OSX systems.
If your system does not have `jot` available, you can use a slightly longer (29 bytes) version:
```
yes u0|sed $[252+$1]q|tput -S
```
[Try It Online !](http://www.tutorialspoint.com/execute_bash_online.php?PID=0Bw_CjBb95KQMZ1RmQkN4TEpvMDQ) (the 29 bytes version)
[Answer]
# Bash 4.2 + extras, 24 exit codes
```
grep \#$1$ $0|sed 's:#.*::;s:T:tcc -run -<<<main=:;s:C:curl -L x.org/! :'|sh;exit
man#1
C-#2
C/#3
sed#4
C-x/#5
C_#6
C0#7
man /#16
C-f#22
C-o/#23
C-L3#35
C--capath /#60
C--max-filesize 1#63
C--cacert /#77
timeout 1e-9 w#124
/#126
-#127
T6\;#132
T204\;#133
$[2**63%-1]#136
{0..1000000000}#137
T0\;#139
exit _#255
```
*Thanks to @KenY-N for 3 exit codes. Thanks to @el.pescado for 1 exit code.*
### Verification
All tests have been performed on openSUSE 13.2.
```
$ for n in {0..255}; do bash exit.sh $n; (($? == $n)) && echo $n >&0; done &> /dev/null
0
1
2
3
4
6
7
16
22
23
35
60
63
77
124
126
127
132
133
136
137
139
255
```
[Answer]
# INTERCAL (C-INTERCAL), 15 codes, 313 + 2 = 315 bytes
```
PLEASE WRITE IN .1
(8) PLEASE CREATE .1 A
PLEASE A
PLEASE COME FROM #2$!1/#1'
DO X
(123) DO (123) NEXT
DO COME FROM (222)
(222) DO STASH .2
(240) DO ,1 <- #0
(241) DO ,1 SUB #0 <- #1
(19) DO .2 <- #256 $ #0
(21) DO .1 <- #2
(148) DO GO BACK
(180) DO RETRIEVE .2
DO COME FROM (50)
(50) DO WRITE IN .2
(109) DO RESUME #0
(120) DO RESUME #9
MAYBE COME FROM (223)
(223) DO COME FROM (223)
(121) PLEASE NOT X
```
[Try it online!](https://tio.run/nexus/intercal#bZFNT4QwEIbv/RVj2ERIXOx0FwOJl4KjS1aoabsuHlcTvejJ/y8Wyse6K4cGnrfzMJ22MDxPjyQNwV6XlqCsIUYWptFxVGiSLosRJDupOgOFqgjutaogEIsLvA7wkk177hQ0LESxivyHf62pscdbZkUohIhYv/rIWGk2EAvH1nxgVwi3Swh4x3BmZpc72EfuQJhFgz0WPRPJDSx8FU6RNzk7rtPB9KAgl8XWoXT8oSarS3qmro//20646zrho3cebafm2eQxO1fS9YCCn8BsUlfyJae/Q1n1QxmneBahP9JwI7Wy0LStqgnsXoHdaCL28/b@efj4bpeH169f "INTERCAL – TIO Nexus")
*All* whitespace here is irrelevant. (The original program contained tabs, but I converted them to spaces so that it'd line up correctly on SE; it's conventional to use a tab width of 8 for INTERCAL. I've tested a version of the program with all tabs, spaces, and newlines deleted, though, and it works fine.)
Compile with `-abm` (2 byte penalty, because `-b` is required for the compiler to be deterministic).
As usual for INTERCAL, this takes numeric input in the format, e.g., `ONE TWO THREE` for `123`.
## Explanation
When a C-INTERCAL program errors out, the exit status is the error code modulo 256. As a result, we can aim to write a program that's capable of producing as many runtime errors as possible. This program only omits two runtime errors that don't indicate internal compiler issues: ICL200I, because reproducing it requires the use of external libraries that are only compatible with a single-threaded program (and multithreaded programs have more errors available); and ICL533I, because 533 has the same value modulo 256 as 277 does, and the program's capable of producing ICL277I.
The program always starts the same way. First, we input (`WRITE IN`) a value for the variable `.1`. Then, we use a computed `CREATE` statement to create new syntax (here, `A`); but because it's computed, the definition of the syntax varies based on the value of `.1`. Finally, in most cases we run our new `A` statement, which has been defined to produce an error; the table of possible definitions we have contains a definition for each possible runtime error (other than the exceptions listed above).
First, there are two exceptions to this general scheme. `(0)` is not a valid line number, so if the user inputs `ZERO`, we jump from the second line (numbered `(8)`) to the fourth line by means of a computed `COME FROM` statement. This then falls through into a syntax error `DO X`, which produces error `ICL000I`. (In INTERCAL, syntax errors happen at runtime, due to the tendency of commands to be disabled, syntax to be redefined under you, etc.). The `COME FROM` statement also has a side effect, even if no actual `COME FROM` happens, creating an operand overload from `.1` to `#1` whenever a line with a line number is executed; this is used later on when producing output 21. (Random global side effects are fairly idiomatic in INTERCAL.)
The other exception is with input `ONE TWO NINE`. There's no line number `(129)` in the program, so we get an error for a missing line number, which is `ICL129I`. So I didn't have to write any code to cover that case at all.
Here are the other errors, and what causes them:
* **123** is a `NEXT` stack overflow (`DO (123) NEXT`). The `NEXT` statement needs other modifiers (`FORGET` or `RESUME`) in order to retroactively determine what sort of control statement it was. Not having those causes error ICL123I once there are 80 unresolved `NEXT statements.
* **222** is a stash overflow (`DO STASH .2` in a `COME FROM` loop). The stashes are limited only by available memory, but that will run out eventually, causing error ICL222I.
* **240** is dimensions an array to size zero. That's exactly what `DO ,1 <- #0` means, and it causes error ICL240I.
* **241** is caused by assigning outside the bounds of an array. In this case, `,1` hasn't been allocated (`,` is used for array-type variables in INTERCAL), so indexing it causes error ICL241I.
* **19** assigns 65536 (`#256 $ #0`) to a 16-bit variable `.2`. It doesn't fit, causing error ICL275I.
* **21** assigns `#2` to `.1`. That might look like a simple enough assignment, but we overloaded `.1` to mean `#1` earlier, and attempting to change the value of 1 with no `-v` option on the command line causes error ICL277I.
* **148** attempts to return to the top entry of the choicepoint stack (`GO BACK`), which doesn't exist at this point in the program (we haven't run any commands to manipulate the choicepoint stack, so it's still empty). That causes error ICL404I.
* **180** attempts to `RETRIEVE .2` from a nonexistent stash (because we didn't stash anything there in this branch of the program), causing error ICL436I.
* **50** requests input (`WRITE IN`) forever in a `COME FROM` loop. Eventually we'll end up reading past EOF, causing error ICL562I.
* **109** runs the statement `DO RESUME #0`, which is meaningless and specifically documented as causing an error (ICL621I).
* **120** runs the statement `DO RESUME #9`. We haven't run that many `NEXT` statements yet, and thus we get error ICL120I. (Intriguingly, this particular error is defined in the INTERCAL documentation as exiting the program normally and then causing the error, rather than exiting the program with an error. I don't believe these two cases are observably different, though.)
* **223** is basically a complex tangle of multithreading primitives that all point back to line 223, causing an infinite loop that blows up memory. Eventually, there's memory exhaustion in the multithreading subsystem, leading to error ICL991I.
* **121** is actually a valid statement (it's a comment), but it appears at the end of the program. As such, execution falls off the end of the program immediately after it executes, causing error ICL633I.
## Verification
Some of the errors involve intentionally running the program out of memory, so I suggest setting fairly small memory limits. Here's the shell command I used to test the program (with newlines added for readability; delete them if you run it yourself):
```
for x in "ZERO" "ONE NINE" "TWO ONE" "FIVE ZERO" "ONE ZERO NINE"
"ONE TWO ZERO" "ONE TWO ONE" "ONE TWO THREE" "ONE TWO NINE"
"ONE FOUR EIGHT" "ONE EIGHT ZERO" "TWO TWO TWO"
"TWO TWO THREE" "TWO FOUR ZERO" "TWO FOUR ONE";
do echo;
echo $x;
echo $x | (ulimit -Sd 40000; ulimit -Sv 40000; ulimit -Ss 40000;
./errors; echo $?);
done
```
And here's the output (with the line numbers and "PLEASE CORRECT SOURCE" messages deleted to save space), which I added partly to demonstrate the program working but mostly to show off INTERCAL's silly error messages:
```
ZERO
ICL000I PLEASEWRITEIN.1(8)PLEASECREATE.1APLEASEAPLEASECOMEFROM#2$!1/#1'DOX(123)DO(123)NEXTDOCOMEFROM(222)(222)DOSTASH.2(240)DO,1<-#0(241)DO,1SUB#0<-#1(19)DO.2<-#256$#0(21)DO.1<-#2(148)DOGOBACK(180)DORETRIEVE.2DOCOMEFROM(50)(50)DOWRITEIN.2(109)DORESUME#0(120)DORESUME#9MAYBECOMEFROM(223)(223)DOCOMEFROM(223)(121)PLEASENOTX
0
ONE NINE
ICL275I DON'T BYTE OFF MORE THAN YOU CAN CHEW
19
TWO ONE
ICL277I YOU CAN ONLY DISTORT THE LAWS OF MATHEMATICS SO FAR
21
FIVE ZERO
ICL562I I DO NOT COMPUTE
50
ONE ZERO NINE
ICL621I ERROR TYPE 621 ENCOUNTERED
109
ONE TWO ZERO
ICL632I THE NEXT STACK RUPTURES. ALL DIE. OH, THE EMBARRASSMENT!
120
ONE TWO ONE
ICL633I PROGRAM FELL OFF THE EDGE
121
ONE TWO THREE
ICL123I PROGRAM HAS DISAPPEARED INTO THE BLACK LAGOON
123
ONE TWO NINE
ICL129I PROGRAM HAS GOTTEN LOST
129
ONE FOUR EIGHT
ICL404I I'M ALL OUT OF CHOICES!
148
ONE EIGHT ZERO
ICL436I THROW STICK BEFORE RETRIEVING!
180
TWO TWO TWO
ICL222I BUMMER, DUDE!
222
TWO TWO THREE
ICL991I YOU HAVE TOO MUCH ROPE TO HANG YOURSELF
223
TWO FOUR ZERO
ICL240I ERROR HANDLER PRINTED SNIDE REMARK
240
TWO FOUR ONE
ICL241I VARIABLES MAY NOT BE STORED IN WEST HYPERSPACE
241
```
[Answer]
# C90 (gcc), 256 exit codes, ~~28~~ ~~27~~ 18 bytes
```
main(){getchar();}
```
I'm not sure if this is clever or cheaty, but I don't think it violates the rules as written: it technically doesn't use `exit`, `return`, or any error throwing mechanism, but simply relies on undefined behavior and the fact that gcc does something rather convenient as far as this challenge goes.
[Try it online!](https://tio.run/nexus/bash#TYyxDoIwGAb3PsU3YICBSkgYTFEnXX0BFvK3lA78NViTJsizoyZq3C6X3FEXcICJLpDXRhKaBunpck7XsXOc5bM1gYZuynK1rC8vLBGKW9B7y/ddicL/4r@LEL2fwHCMuZSyqutFQXtcJ8ehR9vGJPvwpqwiEs7xgNx@DwqGBo/k@K7YrE8 "Bash – TIO Nexus")
### How it works
This simply uses `getchar` to read one byte from STDIN. By itself, this does nothing.
However, a compliant C90 program must end with a `return` statement or something equivalent; everything else is undefined behavior. gcc ends the generated assembly with a `ret` anyway, so whatever value was casually in the register EAX will get returned by the program. Luckily, glibc's `getchar` stores the byte it reads from STDIN in EAX, so the value of that byte is the exit code of our program.
[Answer]
# Perl, 108 bytes, 256 exit codes
This program (ab)uses [Test::More](http://search.cpan.org/~exodist/Test-Simple-1.302075/lib/Test/More.pm#EXIT_CODES) module. It tries to open file named `""` *n* times where *n* is given as command line argument. It fails every time, and each invocation is treated as a test. Test::More return number of failed tests as exit code. `plan tests => $ARGV[0]%255` is needed to get exit code 255.
```
#!/usr/bin/perl
use Test::More;
plan tests => $ARGV[0]%255 if($ARGV[0]>0);
ok(open(F,"")) for (1..$ARGV[0])
```
[Answer]
# C (gcc) under bash shell on x86, 230 bytes, 8 exit codes
Newlines added to aid readability. Comments ignored in score.
```
main(int c, char **v){
int p[2];
switch(atoi(v[1])-128){
case 2:__asm("UD2"); /* SIGILL: x86 undefined instruction */
case 5:__asm("int $3"); /* SIGTRAP: x86 breakpoint instruction */
case 6:abort(); /* SIGABRT: raise() is called under the covers */
case 8:c/=c-2; /* SIGFPE: divide by 0 (c-2) */
case 11:c=*(int *)c; /* SIGSEGV: dereference of invalid pointer */
/* SIGPIPE: write() to a pipe closed at the other end */
case 13:socketpair(1,1,0,p);close(p[1]);write(p[0],v,1);
case 14:alarm(1);sleep(2); /* SIGALRM: kernel will send alarm signal after 1 sec */
}
}
```
A feature of the bash shell:
>
> When a command terminates on a fatal signal N, bash uses the value of 128+N as the exit status.
>
>
>
So all we need to do is trigger various signals from within a c program. At this point, I assume simply doing `kill(n-128);` is banned. So instead we execute code that triggers various signals, which causes the corresponding error codes to be made available at the calling shell.
The exit codes are 0, 130, 133, 134, 136, 139, 141, 142.
[Try it online](https://tio.run/nexus/c-gcc#Pc7BCsIwDAbg@55iiId0dGg6Fenw5it4kiExFCxurrRlO4jPPjd13vJ/CeEfGrIPsI@Yskz5Rj7Nsk48k0ncWVVlEnob@QYUWwvdGSuRo9qPF0zBpEpfLhQaWJyOaiHKL25nnJ4si7/vNF1bH2HOe82rA@fqFxE1H7JPl0zwjIUOLd9NdGQ9oES5lk6UXLfBgJvqlL23cZrXlewkzs9xo6km38AooTbGgRpXr@Q1DAMWxRs). Expand the "Debug" section to see the return code.
This can certainly be golfed deeper. But I'd be more interested in adding more signals.
[Answer]
# Python 2, 13 Bytes, 2 exit codes
```
1/(input()-1)
```
If you enter 0, it tries to print `1/-1` which is -1 which is perfectly fine thus exit code 0. If you enter 1, you get `1/0` which raises a `ZeroDivisionError` in which there is an exit code of 1. With my IDE, there is only 0 and 1 for the exit codes...
Outputs:
---
[![enter image description here](https://i.stack.imgur.com/rdgXr.png)](https://i.stack.imgur.com/rdgXr.png)
---
[![enter image description here](https://i.stack.imgur.com/oK1ZY.png)](https://i.stack.imgur.com/oK1ZY.png)
[Answer]
# PHP, 15 bytes, 2 exit codes
Without `die`/`exit`, PHP cannot return anything but `0` or `255` (afaik; probably `~1`), so ...
```
!$argv[1]?:p();
```
If command line argument is falsy, it evaluates to `1` and exits with `0`. If not, it tries to call a function and exits with `<b>Fatal error</b>: Uncaught Error: Call to undefined function p()`.
Run with `-r`.
[Answer]
# Excel VBA, ~~414~~ 514 533 + 3 Bytes, 14 exit codes
Takes input as a `Conditional Compilation Argument`, `n=[input value]` and produces that number's associated error code.
```
Sub e()
Dim a As Application, b As Byte, s As String, v(), x
Set a=Application
#If n=3 Then
Return
#ElseIf n=5 Then
b=a.CommandBars("")
#ElseIf n=6 Then
b=2^8
#ElseIf n=7 Then
ReDim v(9^9)
#ElseIf n=9 Then
v=Sheets("")
#ElseIf n=10 Then
v=Array(1)
For Each x In v
ReDim v(9)
Next
#ElseIf n=11 Then
b=1/0
#ElseIf n=13 Then
Debug.?Int("X")
#ElseIf n=14 Then
Debug.?String(9E8,1)
#ElseIf n=20 Then
Resume
#ElseIf n=28 Then
f 256
#ElseIf n=35 Then
Call c
#ElseIf n=92 Then
For Each x In v
ReDim v(9)
Next
#ElseIf n=94 Then
b=Null
#End If
End Sub
Sub f(n):DoEvents:f n-1:End Sub
```
+3 for `n=[Value]` conditional compilation call
Handles Inputs where `n=`
```
3
5
6
7
9
10
11
13
14
20
28
35
92
94
```
*Note:* VBA does not have exit codes `0` or `1`. I have included the solutions for `3` and `5`, which are the two lowest numbered exit codes available to VBA in their place
[Answer]
# Turtlèd, 4 bytes, 2 exit codes
I don't know if there are any ways to get more exit codes... are there even any more ways in the interpreter language
I found a few four length answers
```
' ?;
```
[Try it online!](https://tio.run/nexus/turtled#@6@uYG/9/78hAA "Turtlèd – TIO Nexus")
```
!.(0
```
[Try it online!](https://tio.run/nexus/turtled#@6@op2Hw/78hAA "Turtlèd – TIO Nexus")
```
?;(*
```
[Try it online!](https://tio.run/nexus/turtled#@6@op2Hw/78hAA "Turtlèd – TIO Nexus")
## How these work:
```
' ?;
```
in my interpreter, there is a ~~bug~~ feature that causes errors when the grid in memory has more than one line, and has no non-space characters on it. this program erases the \* on the origin cell `'[space]`, takes non-negative integer input `?` (0 or 1 really), and moves down that many `;`, if it is zero, the grid will only have one line and not error, otherwise it will move down and the error will occur
```
!.(0
```
parentheses and stuff don't get parsed, they just get executed at run time to mean: "skip to the matching paren, if the cell symbol isn't right". in this program, inputting (`!`) one causes the program to write it to the cell (`.`), execute the paren, which checks if the cell symbol is 0, try to skip to the matching paren, but instead throw an error as there is none. if it is zero, it writes it down, checks the parentheses, finds itself on a 0, and then ignores it, and the program finishes
```
?;(*
```
has elements of the previous answer, and the first. it takes non-negative integer input, moves down that many, and checks whether the cell is '\*', searching for a non existing extra paren if it is not. if the input is 1, it will move off the starting space, and find the cell is a space, and error, if it is zero, it will stay on the start space and ignore the paren.
[Answer]
# Javascript (node), 19 bytes, 2 exit codes
Full program:
```
+process.argv[2]&&a
```
Function:
```
f=i=>i&&f(i)
```
`process.argv` is an array that contains the path to the node executable, the path to the javascript file executed and the command line arguments. In this case, this will be either `"1"` or `"0"`. The string is converted to a number with the unary `+` operator. If the number is zero the lazy `&&` operator won't evaluate the right hand side, if the number is truthy (not zero), the right hand side of `&&` is evaluated and an error is thrown because it's referencing an undefined variable, and the program exists with exit code 1.
The function expects the input as a number. If the input is truthy, the function calls itself, and crashes the node runtime with a stack overflow. If the input is 0, the lazy `&&` operator returns 0 without evaluating the right hand side.
[Answer]
# [Perl 6](https://perl6.org), 57 bytes, 256 exit codes
```
use Test;plan $_=@*ARGS[0];ok try {open ""} for ^($_%255)
```
[Try it](https://tio.run/nexus/perl6#bVHLTgJBELzPV5SI4RHklcABsokmEENi1Cx4MkoWaNgJy84yM@tKCD@jRz/BcOGH@ATsJb4OHrurqruqOzuEAx2H2L0jIh00cU7IHWJDGJCx7SjwQmSHzkXx0r3qP1Qf22oOq1dYq4hCZDIbTJXGUz47PKs3GoVDbvdREuKHjkoF1RJwisgzBl6gwhmsT5BhFFshWicqtowzwfpaJfASb4X@oHN7P2CQtP4P7LquaAthuMrQi7RjNaEW2yx/F/lChnE5xZ8OThwHv8bWAkgHLJctqyrdm06FFcDAJ03woog8bWAVRlxhFM/YMXLZ4l3XvS6P1SKSAenyTBqbL@RYx60FhRYc55hvv3092t9v3xDIkNJRhggLpdPwfLSFZ6UK07Ff/A7xmpRvaHyERhSoJDXVs0iUnhveojWDwQqJz@fvwfKTaALJBGl9PJM2qbJerTXLtTpLOZjYHA715ic "Perl 6 – TIO Nexus")
This is a translation of the Perl 5 example.
## Expanded
```
use Test; # bring in 「plan」 and 「ok」
plan $_ = @*ARGS[0]; # plan on having the input number of tests
# only actually needed for the 255 case
# if the plan is greater than the number of tests
# it fails with exitcode 255
ok # increment the failure counter if the following is False
try { # don't let this kill the whole program
open "" # fails to open a file
}
for # repeatedly do that
^( # upto Range
$_ % 255 # either the input number of times, or 0 times for 255
)
```
[Answer]
# Scala, 19 bytes, 2 exit codes
`if(args(0)=="1")1/0`
`1/(args(0).toInt-1)`
The JVM supports only 1 and 0 as exit codes if you don't call `System.exit`.
The first program tries to calculate `1/0` if the first argument is `1`, which will crash the JVM with an exit code of 1. If the argument is 0, it wil exit succesfully.
The second program to converts the argument to integer, subtracts one and tries to divide 1 by that number. If the argument if 1, it calculates `1/0`, so the JVM will crash; if the argument is 0, it calculates `1/-1` and exits.
[Answer]
# [Python 3](https://docs.python.org/3/), 15 bytes, 2 exit codes
Obviously, this is longer than the [Python 2 solution](https://codegolf.stackexchange.com/a/107203/60919), because in Python 3 we can't take a literal input without calling `eval`. However, we can use string
comparison techniques interestingly...
```
1/(input()<'1')
```
Input will be either the string `0` or `1` - if it's 1, the condition evaluates to 0 (false), resulting in an attempt to compute `1 / 0` which obviously crashes (exit code 1). Otherwise, nothing happens, and Python exits with the regular exit code 0.
As far as I'm aware, Python is incapable of crashing with other exit codes.
[Answer]
# Java, ~~71~~ 66 bytes, 2 exit codes
*4 bytes saved thanks to Holger*
### Full program:
```
interface I{static void main(String[]a){a[a[0].charAt(0)-48]="";}}
```
### Function taking an int as an argument:
```
i->1/(i-1)
```
The program takes the first char of the first argumant (either `'0'` or `'1'` and subtracts 48 (ascii value of `'0'`) to get an integer (0 or 1). It then tries to set the argument at the position of that integer to the empty string. If the input is 1, the program crashes with an `ArrayIndexOutOfBoundsException`, beacuse the argument array only has one element at position 0 (zero-indexed).
[Answer]
## Python 2, 11 bytes, 2 exit codes
```
1>>-input()
1/~-input()
0<input()<x
```
Three different 11-byte solutions for three different errors! (Just for fun, this doesn't give points.) By default, Python only has exit codes 0 for successful exit and 1 for error. The successful runs don't output anything.
```
1>>-input()
```
On input 1, gives "ValueError: negative shift count". On input 0, a zero shift count succeeds and gives 1.
```
1/~-input()
```
On input 1, gives "ZeroDivisionError: integer division or modulo by zero" due to `~-input()`, aka `input()-1` being 0. In input 1, `1/-1` gives -1. `0**-input()` would also work.
```
0<input()<x
```
On input 1, gives "NameError: name 'x' is not defined". On input 0, these first inequality `0<0` is evaluated to False, so the rest is not evaluated and the result is just False.
[Answer]
# SmileBASIC, 640 bytes, 39 exit codes (out of 52)
```
SPSET.,0INPUT C$GOTO"@"+C$@0
STOP@3
A
@4
CLS.@5@A
GOSUB@A@7?1/A@8
X$=3@9
A%=POW(2,31)@10
BEEP-1@11
DIM B[#ZL*#R]@13
READ A
@15
V"OPTION STRICT?X
@16
CALL@D@17
V@A*2
@18
V"VAR A,A
@19
V"DEF A:END:DEF A
@20
V"FOR I=0TO
@21
V"NEXT
@22
V"REPEAT
@23
V"UNTIL
@24
V"WHILE.
@25
V"WEND
@26
V"IF.THEN
@27
V"IF.THEN"+CHR$(10)+"ELSE
@28
V"ENDIF
@29
V"DEF X
@30
RETURN@31
DIM E[-1]@32
V"DEF A:DEF
@34
GOTO"|
@36
XOFF MIC
MICSTOP
@37
XOFF MOTION
GYROSYNC
@38
PRGDEL
@39
DIM F[66]SPANIM.,1,F
@40
DIM G[2]SPANIM.,1,G
@42
MPSTART 2,@A@L
MPSEND"A"GOTO@L@44
PROJECT
@46
USE"PRG1:A
@47
BGMPLAY"`
@48
X=
@51
DLCOPEN"
DEF V C
PRGEDIT 1PRGDEL-1PRGSET C
EXEC 1
END
```
This could definitely be made shorter.
SB only has error codes from 0 to 51, and some are impossible to trigger.
[Answer]
# Node.js (ES6), 77 bytes, 2 exit codes
```
require('readline').createInterface({input:process.stdin}).prompt("",i=>i&&x)
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 4 exit codes, 18 bytes
```
߀
2*
Ṁ¹Ŀ
RÇĿỌḊ?R
```
Supports exit codes **0**, **1**, **137** (killed), and **139** (segmentation fault).
[Try it online!](https://tio.run/nexus/jelly#ASMA3P//w5/igqwKMioK4bmAwrnEvwpSw4fEv@G7jOG4ij9S////MA "Jelly – TIO Nexus")
### How it works
```
RÇĿỌḊ?R Main link. Argument: n (integer)
R Range; yield [1, ..., n] if n > 1 or [] if n = 0.
Ḋ? If the dequeued range, i.e., [2, ..., n] is non-empty:
Ç Call the third helper link.
Ŀ Execute the k-th helper link, where k is the the integer returned by Ç.
Else, i.e., if n is 0 or 1:
Ọ Unordinal; yield [] for n = 0 and "\x01" for n = 1.
R Range. This maps [] to [] and causes and error (exit code 1) for "\x01".
Ṁ¹Ŀ Third helper link. Argument: r (range)
Ṁ Maximum; retrieve n from r = [1, ..., n].
¹Ŀ Call the n-th helper link (modular).
When n = 139, since 139 % 3 = 1, this calls the first helper link.
When n = 137, since 137 % 3 = 2, this calls the second helper link.
2* Second helper link. Argument: k
2* Return 2**k.
Since 2**137 % 3 = 174224571863520493293247799005065324265472 % 3 = 2,
ÇĿ in the main link will once again call the second helper link.
Trying to compute 2**2**137, a 174224571863520493293247799005065324265472-
bit number, will get the program killed for excessive memory usage.
߀ First helper link. Argument: k
߀ Recursively map the first helper link over [1, ..., k].
This creates infinite recursion. Due to Jelly's high recursion limit,
a segmentation fault will be triggered.
```
[Answer]
# ZX81 BASIC >255 exit codes - 52 bytes (listing)
```
1 INPUT N
2 GOTO 1+(2*(N>0 AND N <=255))
3 PRINT "EXIT CODE ";N
4 RAND USR N
```
Technically, `N` could be any 24 bit floating point number within the range, but we'll assume integers here. Line 2 is equivalent to `IF N>0 AND N <=255 THEN GOTO 3: ELSE GOTO 1` if ZX81 BASIC had `IF/ELSE` in its symbolic instructions.
] |
[Question]
[
Here is a relatively simple challenge for you.
Given a string of length **N**, output the string forwards, then backwards, then forwards, then backwards... etc. **N** times. For example, if your input was
```
Hello!
```
You should output:
```
Hello!!olleHHello!!olleHHello!!olleH
```
You may also optionally output one trailing newline.
Your submission may be either a full program or a function, and you may take input and output in any [reasonable format](http://meta.codegolf.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods). For example, you may take IO from STDIN/STDOUT, function arguments and return value, from a file, etc. You can safely assume that the input string will not be empty, and will only contain printable ASCII. You *must* output the new string on a single line. So, for example, if the output to the last example was
```
Hello!
!olleH
Hello!
!olleH
Hello!
!olleH
```
This would *not* be a valid solution!
Here are some more test cases:
```
Input:
a
Output:
a
Input:
abcd
Output:
abcddcbaabcddcba
Input:
OK!
Output:
OK!!KOOK!
Input:
4815162342
Output:
4815162342243261518448151623422432615184481516234224326151844815162342243261518448151623422432615184
Input:
PPCG
Output:
PPCGGCPPPPCGGCPP
Input:
42
Output:
4224
```
## Leaderboards
Since this is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge, [standard loopholes](http://meta.codegolf.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are banned, and the shortest answer in bytes wins! *However*, this is *also* a competition to have the shortest answer in any particular langauge. While it's unlikely that a Java answer will beat an answer in perl, or some golfing language, it's still very impressive to have the shortest Java answer. So, you can use this leaderboard to see both
1. The shortest answer out of all languages, and
2. The shortest answer in each individual language.
To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:
```
# Language Name, N bytes
```
where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance:
```
# Ruby, <s>104</s> <s>101</s> 96 bytes
```
If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the *last* number in the header:
```
# Perl, 43 + 2 (-p flag) = 45 bytes
```
You can also make the language name a link which will then show up in the leaderboard snippet:
```
# [><>](http://esolangs.org/wiki/Fish), 121 bytes
```
```
var QUESTION_ID=93261,OVERRIDE_USER=31716;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
```
```
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
```
```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>
```
[Answer]
# Vim, ~~39~~, 34 keystrokes
```
:se ri
Y:s/./<C-r>"/g
<C-o>qqgJC<C-r>"<esc>gJ@qq@q
```
5 bytes saved thanks to @Lynn!
Here is a gif of it happening live: (Note that this gif is of a previous version since I haven't had time to re-record it yet).
[![enter image description here](https://i.stack.imgur.com/E0P1Q.gif)](https://i.stack.imgur.com/E0P1Q.gif)
And here is an explanation of how it works:
```
:se ri "Turn 'reverse indent' on.
Y "Yank this line
:s/./<C-r>"/g "Replace every character on this line with the register
"We just yanked followed by a newline
<C-o> "Jump to our previous location
qq "Start recording in register 'q'
gJ "Join these two lines
C "Delete this line, and enter insert mode
<C-r>"<esc> "Paste the line we just deleted backwards
gJ "Join these two lines
@q "Call macro 'q'. This will run until we hit the bottom of the buffer.
q "Stop recording.
@q "Start our recursive macro
```
On a side note, `Y` grabs an extra newline, which is usually an obnoxious feature. This is probably the first ever time that it has actually saved several bytes!
[Answer]
## Python, 40 bytes
```
f=lambda s,i=0:s[i:]and s+f(s[::-1],i+1)
```
A recursive function. Prepends the input string `s` to the function of the reverse until the counter `i` exceed the length of `s`.
[Answer]
# [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), ~~418~~ ~~378~~ 228 bytes
This is my Brain-Flak masterpiece. It may not be well golfed but the challenge is the most difficult I have ever encountered.
[Try it online!](http://brain-flak.tryitonline.net/#code=KChbXSlbKCldKXsoe31bKCldPCgoe30oPCgpPikpPHsoe31bKCldPCgoe30oKTwoKHt9PD4pKT4pPCh7KCk8KHt9WygpXTwoe308KHt9PD4pPD4-KT4pPn17fTw-KXsoe31bKCldPCh7fTw-KTw-Pil9e30-KT4pfXt9e308PihbXSl7e30oe308Pik8PihbXSl9e308Pj4pPil9e30oWygoe30pKV17KHt9KSh7fVsoKV0pfXt9KXsoKHt9Wyh7fTw-KTw-XSk8PD4oe308Pjx7KCh7fVsoKV0pPHsoe31bKCldPCh7fTwoe308Pik8Pj4pPil9e308PihbXSl7e30oe308Pik8PihbXSl9e308Pj4pfXt9Pik-KX0K&input=SGVsbG8h&args=LWM)
```
(([])[()]){({}[()]<(({}(<()>))<{({}[()]<(({}()<(({}<>))>)<({()<({}[()]<({}<({}<>)<>>)>)>}{}<>){({}[()]<({}<>)<>>)}{}>)>)}{}{}<>([]){{}({}<>)<>([])}{}<>>)>)}{}([(({}))]{({})({}[()])}{}){(({}[({}<>)<>])<<>({}<><{(({}[()])<{({}[()]<({}<({}<>)<>>)>)}{}<>([]){{}({}<>)<>([])}{}<>>)}{}>)>)}
```
## Explanation
This explanation is now a bit outdated but it still does a pretty good job of explaining the program.
This explanation is going to go a little different from my regular explanation process. I am going to explain how I came about this result rather than explain the result in order. Here it goes:
### Roller
After working at the problem a quite a bit I came up with this code:
```
(n[()])({()<({}[()]<({}<({}<>)<>>)>)>}{}<>){({}[()]<({}<>)<>>)}{}<>
```
This code (where n is the literal for some number. e.g. `()()`) will take the item on the top of the stack and move it down n steps. With n as the stack height this will perform a stack "roll". i.e. move the top item to the bottom of the stack. Here's how it works:
We put the place we want to move the item to minus one on the stack. Why minus one? I don't know it just works that way.
```
(n[()])
```
We then loop until this number reaches zero keeping track of the loop with a `()`.
```
{()<({}[()]<...>)>)>}{}
```
Each time we loop we pick up the top item and move the item underneath it to the other stack. This puts the number on top in its place.
```
({}<({}<>)<>>)
```
All we need to do now is put the numbers we moved back. We switch to the off stack and push the number of runs the loop made.
```
(...<>)
```
We loop decrementing the newly pushed number until it reaches zero. Each time we move one number back.
```
{({}[()]<({}<>)<>>)}{}<>
```
### Reverse
I next modified the roll to make a full stack reverse:
```
(n){(({}[()])<{({}[()]<({}<({}<>)<>>)>)}{}<>([]){{}({}<>)<>([])}{}<>>)}{}
```
Once again n represents the depth of the reverse. That is the top n items on the stack will be reversed. How it works:
The reverse is just a fancily wrapped roller. We simply roll the top of the stack n times decrementing the depth of the roll by one each time.
```
(n){(({}[()])<ROLLER>)}{}
```
### Duplicate
In place duplication is hard. Really hard. After I figured out how to reverse the stack it still took a great deal of effort to come up with the duplication algorithm.
Here it is:
```
(((n)<{({}[()]<(({}<>))<>>)}{}<>>)<{({}[()]<({}<>)<>([][()])({()<({}[()]<({}<({}<>)<>>)>)>}{}<>){({}[()]<({}<>)<>>)}{}<>>)}{}<>([]){{}({}<>)<>([])}{}<>([]){(({}[()])<{({}[()]<({}<({}<>)<>>)>)}{}<>([]){{}({}<>)<>([])}{}<>>)}{}>)
```
Its a bit of a big one but here's how it works:
Start by pushing n. n is the depth of the duplicate. We also open two parentheses. These allow us to store the value of the n in the scope until its needed again.
```
(((n)<
```
Next we loop n times each time pushing the top value of the stack to the off stack twice. This makes the initial duplicates for each number on the stack.
```
{({}[()]<(({}<>))<>>)}{}
```
Now we have two copies of each number on the offstack. We need to separate these into two groups.
So we switch to the offstack and recall one of the ns we saved at the beginning.
```
<>>)
```
We loop n times.
```
{({}[()]<...>)}{}
```
Each time we move one copy to the mainstack.
```
({}<>)<>
```
And roll one copy to the bottom of the stack. (This assumes the offstack was empty to begin with making this duplicate not stack clean)
```
([][()])ROLLER
```
Once that is done we have split the original into two groups the "original" and a copy on the offstack (the copy is actually in reverse). So we just move the copy to the main stack and we can be done with it.
```
([]){{}({}<>)<>([])}{}<>
```
### Skeleton program
Now that I have made all of the pieces of the program, I just have to insert them into a frame.
The frame doubles the text one less than the stack's height times Using duplicate.
```
(([])[()])
{
({}[()]<
DUPLICATE
>)
>)}{}
```
And then reverses the stack in decreasing increments of the initial stack height from n^2-n to 0.
```
(({}))
{
(({}[()])<
({}<>)<>(({}))({<({}[()])><>({})<>}{})<>{}<>
({}<({}<>)<>>)<>({}<>)
({}<
REVERSE
>)
>)
}{}{}
```
[Answer]
# [Jelly](http://github.com/DennisMitchell/jelly), ~~4~~ 3 bytes
```
,Ṛṁ
```
[Try it online!](http://jelly.tryitonline.net/#code=LOG5muG5gQ&input=&args=J09LISc) or [Verify all test cases.](http://jelly.tryitonline.net/#code=LOG5muG5gQrDh-KCrFk&input=&args=WydIZWxsbyEnLCdhJywnYWJjZCcsJ09LIScsJzQ4MTUxNjIzNDInLCdQUENHJywnNDInXQ)
Saved a byte thanks to @[Maltysen](https://codegolf.stackexchange.com/users/31343/maltysen).
## Explanation
```
,Ṛṁ Input: string S
Ṛ Reverse S
, Join S with reverse of S. Makes a list [S, rev(S)]
ṁ Mold [S, rev(S)] to len(S) by repeating elements cyclically
Return and print implicitly as a string
```
[Answer]
# PHP, ~~54~~ 52 bytes
(49 bytes, but do not work if string contains '0')
```
for(;($a=$argv[1])[$i++];)echo$i%2?$a:strrev($a);
```
(52 bytes)
```
<?=str_pad('',strlen($a=$argv[1])**2,$a.strrev($a));
```
(54 bytes)
```
for(;$i++<strlen($a=$argv[1]);)echo$i%2?$a:strrev($a);
```
[Answer]
# [2sable](http://github.com/Adriandmen/2sable), 3 bytes
Code:
```
gGÂ
```
Explanation:
```
g # Get the length of the input
G # Do the following n - 1 times:
 # Bifurcate, which duplicates a and reverses the duplicate
```
Uses the **CP-1252** encoding. [Try it online!](http://2sable.tryitonline.net/#code=Z0fDgg&input=MTIz)
[Answer]
# J, ~~13~~ 8 bytes
Saved 5 bytes thanks to miles!
```
#;@$];|.
```
This is a 5-train with the following verbs:
```
# ;@$ ] ; |.
```
The inner fork is composed of `]` (identity), `;` (link), and `|.` (reverse). Observe:
```
(| ; |.) 'Hello!'
+------+------+
|Hello!|!olleH|
+------+------+
```
The outer two verbs make the rest of the train. `#` is, in this case, the size of the argument, that is, the length. The verb linking these is `;@$`, or `ravel` over `reshape`. Observe:
```
# 'Hello!'
6
6 $ (] ; |.) 'Hello!'
+------+------+------+------+------+------+
|Hello!|!olleH|Hello!|!olleH|Hello!|!olleH|
+------+------+------+------+------+------+
; 6 $ (] ; |.) 'Hello!'
Hello!!olleHHello!!olleHHello!!olleH
6 ;@$ (] ; |.) 'Hello!'
Hello!!olleHHello!!olleHHello!!olleH
(# ;@$ (] ; |.)) 'Hello!'
Hello!!olleHHello!!olleHHello!!olleH
(# ;@$ ] ; |.) 'Hello!'
Hello!!olleHHello!!olleHHello!!olleH
(#;@$];|.) 'Hello!'
Hello!!olleHHello!!olleHHello!!olleH
```
---
Old solution.
```
[:,|.^:(i.@#)
```
Simple enough. `|.` is reverse, and `^:` is power conjunction, which repeats it's left verb (right hand) # of times. When the right argument is a verb, that verb is called on the argument. The right verb in this case is range from zero (`i.`) to the length (`#`). When raised to an array, the intermediate results are kept. All that needs to be done is to flatten the array with `,`.
## Intermediate results
```
(i.@#) 'Hello!'
0 1 2 3 4 5
|.^:0 1 2 3 4 5 'Hello!'
Hello!
!olleH
Hello!
!olleH
Hello!
!olleH
|.^:(i.@#) 'Hello!'
Hello!
!olleH
Hello!
!olleH
Hello!
!olleH
([:,|.^:(i.@#)) 'Hello!'
Hello!!olleHHello!!olleHHello!!olleH
```
[Answer]
# Ruby, 39 bytes
```
->(s){s.reverse!.gsub(/./){s.reverse!}}
```
I suck at Ruby. Golfing help is appreciated.
Ruby is a really nice language for this because of `.reverse!`
## Explanation
I was hoping it would be someting simple like:
```
s.gsub(/./){s.reverse!}
```
but because of boilerplate/challenge restriction it's longer.
What `s.reverse!` is very useful. `s.reverse!` is basically `s = s.reverse!`, meaning it also mutates `s`.
---
What each section of the program does is described below:
```
->(s){ # Lambda with argument s
s.reverse! # Reverse `s` see above for details
.gsub(/./) # Replace every character with...
{s.reverse!} # the input reversed!
```
The thing about `s.reverse!` that is great is that everytime it is evaluated the string get's flipped. So as it replaces the string. `s` is modified!
[Answer]
# Perl, 24 bytes
Includes +2 for `-lp`
Give input on STDIN:
```
rev.pl <<< Hello!
```
`rev.pl`:
```
#!/usr/bin/perl -lp
s%.%s/.?/chop/eg;$`%eg
```
Surprisingly this does not use the builtin `reverse` operator. That name is just soooo long, all solutions I could think of with `reverse` are at least 1 byte longer.
[Answer]
# JavaScript (ES 6), ~~59~~ 50 bytes
9 Bytes thanks to Hedi and Huntro.
```
f=(s,n=1)=>s[n]?s+f([...s].reverse().join``,n+1):s
```
recursive function.
Reversing the string takes almost half of the size (~~25~~ 22 bytes!) ...
Why isn´t there a native way for that?
[Answer]
## [Minkolang](https://github.com/elendiastarman/Minkolang), 17 bytes:
```
$oId$z$Dz[rz[O]].
```
[Try it here!](http://play.starmaninnovations.com/minkolang/?code=%24oId%24z%24Dz%5Brz%5BO%5D%5D%2E&input=Hello!)
### Explanation
```
$o Read in whole input as characters
Id Push the length of stack and duplicate
$z Pop top of stack and store in register (z)
$D Pop top of stack (n) and duplicate whole stack n-1 times
z[ ] z times, do the following:
r Reverse the stack
z[O] z times, pop the top of stack and output as character
. Stop.
```
[Answer]
## [Pip](http://github.com/dloscutoff/pip), ~~11~~ 10 bytes
```
L#aORVRV:a
```
[Try it online!](http://pip.tryitonline.net/#code=TCNhT1JWUlY6YQ&input=&args=SGVsbG8h)
Explanation:
```
a is first cmdline argument (implicit)
L#a Loop len(a) times:
RV:a Reverse a and assign back to a
ORV Output the reverse of a (since it needs to go forward first then backward)
```
[Answer]
# Haskell, ~~40~~ ~~36~~ 32 Bytes
```
m s=take(length s^2)$cycle$s++reverse s
```
Example:
```
*Main> m "Hello!"
"Hello!!olleHHello!!olleHHello!!olleH"
```
Even shorter (credit to Damien):
```
q s=zip(s>>[s,reverse s])s>>=fst
```
*s>>[s,reverse s]* cycles ["abc","cba",...] which is zipped to correct size and concatMap'ped with fst
[Answer]
# MATL, ~~13~~ ~~12~~ 8 bytes
Pushes all elements, combines in the end.
```
td"tP]&h
td" ] %For loop over string length - 1 due to diff
tP %Push copy of string, reverse
&h %Concatenate entire stack horizontally
```
[Try it online!](http://matl.tryitonline.net/#code=dGQidFBdJmg&input=J1N0cmluZyc)
---
**Old versions:**
Completely different approach, based on `fprintf`:
```
t"t1$0#YDP]x
t" ] % For loop over string
t % Duplicate string for printing:
1$0#YD % `fprintf` with 1 input, 0 output (i.e., to screen).
P % Reverse
x % Empty stack to prevent implicit output
```
---
Version based on reversing a template string
```
ttd"wPtbYc]Dx
t %Duplicate input, to create 'accumulator' string
% (alongside the input string which will serve as 'template'
td %Duplicate input, diff to get an stringof size input-1
" ] %For loop over size n-1 string (consumes diff'd string)
wP %Get 'template' string on top of stack, and reverse
tb %Duplicate template string, and switch with 'accumulator' string
Yc %Concatenate template string with accumulator.
Dx %Display top element, delete template string to prevent implicit disp
```
[Answer]
# 8088 Assembly, IBM PC DOS, ~~29~~ 28 bytes
Assembled, `xxd` dump:
```
00000000: d1ee ac48 938a cbfc 518a cbf7 da78 01fd ...H....Q....x..
00000010: acac b40e cd10 e2f9 59e2 ecc3 ........Y...
```
Unassembled listing:
```
D1 EE SHR SI, 1 ; point SI to DOS PSP (080H)
AC LODSB ; load input string length into AL
48 DEC AX ; remove leading space from length counter
93 XCHG BX, AX ; save input length to BL
8A FB MOV BH, BL ; string output counter in BH
S_LOOP:
FC CLD ; set direction forward
8A CB MOV CL, BL ; reset char counter in CL
F7 DA NEG DX ; flip DX to toggle fwd/back output
78 01 JS C_START ; if positive, go forward
FD STD ; otherwise go backwards
C_START:
AC LODSB ; adjust SI to first/last char
C_LOOP:
AC LODSB ; load next char into AL
B4 0E MOV AH, 0EH ; PC BIOS tty output function
CD 10 INT 10H ; write char to console
E2 F9 LOOP C_LOOP ; continue looping through chars
FE CF DEC BH ; decrement string count loop
75 EC JNZ S_LOOP ; if not zero, continue loop
C3 RET ; exit to DOS
```
Standalone PC DOS executable program. Input string via command line, output is console.
[![enter image description here](https://i.stack.imgur.com/hgCwH.png)](https://i.stack.imgur.com/hgCwH.png)
[Answer]
# [Perl 6](https://perl6.org), ~~31~~ 30 bytes
```
{[~] (|($_,.flip)xx*)[^.chars]}
```
Save one byte by misusing `.ords`, which returns a list of ordinals, then implicitly turn that into a number to create a range with.
```
{[~] (|($_,.flip)xx*)[^.ords]}
```
## Explanation:
```
# bare block lambda with implicit parameter 「$_」
{
# reduce using string concatenation operator 「~」
[~]
(
# create a Slip
|(
# of the input, and its string reverse
$_, .flip
# list repeated infinitely
) xx *
# get the values in the range from 0 up-to and excluding
# the number of characters 「0 ..^ +$_.ords」
)[ ^.ords ]
}
```
## Usage:
```
my &code = {[~] (|($_,.flip)xx*)[^.ords]}
say code 'a'; # a
say code 'abcd'; # abcddcbaabcddcba
say code 'OK!'; # OK!!KOOK!
say code 4815162342; # 4815162342243261518448151623422432615184481516234224326151844815162342243261518448151623422432615184
```
[Answer]
# Vim + coreutils, 32 keystrokes
You can never have too many Vim answers.
```
qqYv:!rev
Pjq@=len(@")
@q2dkv{gJ
```
## Explanation
```
qq " Start recording macro
Y " Yank (copy) line
v:!rev<CR> " Reverse line with coreutils rev command
Pj " Paste yanked line above this line
q " Stop recording
@=len(@")<CR>@q " Playback macro once for each character
2dk " Delete last 3 lines
v{gJ " Join lines
```
[Answer]
# Scala, ~~73~~ ~~72~~ 71 bytes
```
def f(s:String)=for(i<-1 to s.length){print(if(i%2>0)s else s.reverse)}
```
This is my first attempt at code golfing, so I'm sure there are countless improvements.
Update:
Golfed away 1 byte by removing brackets.
Thanks to Destructible Watermelon for suggestion, shaved off a byte.
[Answer]
## PowerShell v2+, 57 bytes
```
param($a)-join(1..($x=$a.length)|%{($a[$x..0],$a)[$_%2]})
```
No real clean way to get string lengths or reverse 'em, so this is pretty lengthy.
Takes input `$a`, loops from `1` to `$a.length` (stored in `$x` for use later). Each iteration we use a pseudo-ternary to index into an array of either `$a` or `$a[$x..0]` (i.e., reversed), based on whether our input number is odd/even `[$_%2]`. These are all encapsulated in parens and `-join`ed together to form a single string. That's left on the pipeline, and output is implicit.
```
PS C:\Tools\Scripts\golfing> .\stringgnirts.ps1 'TimmyD'
TimmyDDymmiTTimmyDDymmiTTimmyDDymmiT
```
[Answer]
# [Dyalog APL](http://goo.gl/9KrKoM), 8 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319)
```
∊≢⍴⊂,⊂∘⌽
```
`∊` flatten
`≢` the tally
`⍴` cyclically reshaping
`⊂` the enclosed argument
`,` followed by
`⊂∘⌽` the enclosed reversed argument
[TryAPL online!](http://tryapl.org/?a=f%u2190%u220A%u2262%u2374%u22A2%7B%u237A%u2375%7D%u233D%20%u22C4%20f%A8%27a%27%20%27abcd%27%20%27OK%21%27%20%274815162342%27%20%27PPCG%27%20%2742%27&run)
-1 byte thanks to [jimmy23013](https://codegolf.stackexchange.com/users/25180/jimmy23013).
[Answer]
# [Cubix](https://github.com/ETHproductions/cubix), 52 bytes
```
Ap\:\;.#u/\:qqsoq(?;u.q..$u<../pB@u:\.....\(?q..s..p
```
On a cube:
```
A p \
: \ ;
. # u
/ \ : q q s o q ( ? ; u
. q . . $ u < . . / p B
@ u : \ . . . . . \ ( ?
q . .
s . .
p . .
```
This one was fun; there are bytes still to be golfed out of this but this will definitely work.
[Try it online!](https://tio.run/##Sy5Nyqz4/9@xIMYqxlpPuVQ/xqqwsDi/UMPeulSvUE9PpdRGT0@/wMmh1CpGDwRiNOyBwsV6egX//3uk5uTkKwIA "Cubix – Try It Online")
### explanation:
Input of `ABC`
* `/A` : go north and read in all inputs as characters; `-1` will be at the bottom
* `p\;.` : remove the `-1` from the stack
* `u#` : push the string length (number of items on the stack)
* `\:\:qq` : dup the string length twice, push two copies to bottom of stack
* loop:
+ `soq(?/<u` : swap top of stack, ouptut top of stack as ASCII, push top (letter) to bottom, decrement top of stack, turn right if not done, then move IP to the right place.
+ at end of loop, the stack will look like `C B A 3 3 0`
* `;u` : pop top of stack `C B A 3 3`
* `B` : reverse stack `3 3 A B C`
* `p(` : move bottom to top and decrement `3 A B C 2`
* `?` if top is zero, go straight to `@` and terminate
* else
+ `psq:uq` : move bottom to top, swap top and move top to bottom dup, and move top to bottom `3 2 A B C 3`
+ `$u` : skip `u`
+ `<` puts us back into the loop.
[Interpreter](http://ethproductions.github.io/cubix/?code=ICAgICAgQSBwIFwKICAgICAgOiBcIDsKICAgICAgLiAjIHUKLyBcIDogcSBxIHMgbyBxICggPyA7IHUKLiBxIC4gLiAkIHUgPCAuIC4gLyBwIEIKQCB1IDogXCAuIC4gLiAuIC4gXCAoID8KICAgICAgcSAuIC4KICAgICAgcyAuIC4KICAgICAgcCAuIC4K&input=SGVsbG8h&speed=20)
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~88~~ ~~87~~ ~~85~~ ~~83~~ ~~68~~ ~~66~~ ~~83~~ ~~82~~ 78 bytes
-1 thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)
## Old version
```
p,q;f(char*s){p=q=1;for(char*m=s--;*m;s[p+=q]*p?:(m++,p+=q=-q))putchar(s[p]);}
```
[Try it online!](https://tio.run/##bYw9D4IwFEVn@BW1U8tHYhGNsWkcHBwcZDcMtQYkoVCgToTfXtswmbq9e@65T6S1EMaoZKAVEm8@RhOeFRsYoVU/rkSyKU1pJOn0UDEbykidT0jGceISSweM1Uc7E1mhxHQxTaeB5E2HcDiHQdt3NWgBA2RLw8CJQD9KwCB/ihe0qEKQQ0yBfTMhaK8Vudaj99vGh/mR7Mkh2@WZ3xXF5fpn4Zv6ByzmCw "C (gcc) – Try It Online")
## Shorter version (slightly broken)
Riffing on the 76 byte approach by [ASCII-only](https://codegolf.stackexchange.com/users/39244/ascii-only) in the comments, and -1 byte from his tweak of my tweak.
Edit: This version is slightly broken in that it assumes that every string is preceded by a NULL byte, which is not always true. (See last test case in link). Reverting to the 83 byte version for now.
```
f(char*s){for(char*n=s-1,k=1;*s++;k=-k)for(;*(n+=k);)putchar(*n);}
```
[Try it online!](https://tio.run/##bYyxDoIwFEVn@IraqS2SWERj8tLJwcFBduNQa0BSLIbWifDtlYbJ1O3mnPOeyhulvK@JesqBWTrW/bBsI2zO11pwYDbLQItc0yCBEZMJTYG@Py6UhBkKk2@NQy/ZGkLTMU263jSoQwLxDaRJyJC73pDA8q4eeEY1wRJTQPMTS/C8FhRsRC/nVQzLA9/xfbEti9hV1fH05yIu3Q@Y/Bc "C (gcc) – Try It Online")
[Answer]
# [brainfuck](https://github.com/TryItOnline/brainfuck), ~~71~~ ~~49~~ 43 bytes
```
,[>+[>+<-],]>[<<[<]>[.>]>-[<<[.<]>[>]>-<]>]
```
[Try it online!](https://tio.run/##SypKzMxLK03O/v9fJ9pOG4hsdGN1Yu2ibWyibYCUnl2snS6IowfigThAOvb/f4WczLLUFIX8PD0A "brainfuck – Try It Online")
Thanks to Jo King for saving 6 bytes.
```
[Tape: [Letters], 0, counter]
,[ while input
>+ increment old counter
[>+<-] move counter to next position
, input next
]
>[ while counter
<<[<]> go to first letter
[.>] print word forwards
>- decrement counter
[ if counter
<< go to last letter
[.<] print word backwards
>[>]>- decrement counter
< exit if
]
> go to counter
]
```
[Answer]
# Java, ~~127~~ ~~111~~ 88 bytes
```
(s,r)->{for(int i=0;i++<s.length();)r+=i%2<1?new StringBuffer(s).reverse():s;return r;};
```
# Ungolfed test program
```
public static void main(String[] args) {
BiFunction<String, String, String> func = (s, r) -> {
for (int i = 0; i++ < s.length();) {
r += i % 2 < 1 ? new StringBuffer(s).reverse() : s;
}
return r;
};
System.out.println(func.apply("Hello!", ""));
}
```
[Answer]
# R, 53 bytes
Assumes that the input is space- or newline-separated for each character.
```
cat(rep(c(i<-scan(,""),rev(i)),l=length(i)^2),sep="")
```
Some test cases:
```
> cat(rep(c(i<-scan(,""),rev(i)),len=length(i)^2),sep="")
1: h e l l o !
7:
Read 6 items
hello!!ollehhello!!ollehhello!!olleh
> cat(rep(c(i<-scan(,""),rev(i)),l=length(i)^2),sep="")
1: a
2:
Read 1 item
a
> cat(rep(c(i<-scan(,""),rev(i)),l=length(i)^2),sep="")
1: a b c d
5:
Read 4 items
abcddcbaabcddcba
> cat(rep(c(i<-scan(,""),rev(i)),l=length(i)^2),sep="")
1: O K !
4:
Read 3 items
OK!!KOOK!
> cat(rep(c(i<-scan(,""),rev(i)),l=length(i)^2),sep="")
1: 4 8 1 5 1 6 2 3 4 2
11:
Read 10 items
4815162342243261518448151623422432615184481516234224326151844815162342243261518448151623422432615184
> cat(rep(c(i<-scan(,""),rev(i)),l=length(i)^2),sep="")
1: P P C G
5:
Read 4 items
PPCGGCPPPPCGGCPP
> cat(rep(c(i<-scan(,""),rev(i)),l=length(i)^2),sep="")
1: 4 2
3:
Read 2 items
4224
```
[Answer]
# Java, 151 bytes
```
public static void r(String s){String t = new StringBuffer(s).reverse().toString();for(int i=0;i<s.length();i++){System.out.print(((i%2==1)?t:s));}}
```
}
Ungolfed:
```
public static void r(String s) {
String t = new StringBuffer(s).reverse().toString();
for(int i = 0; i < s.length();i++) {
System.out.print(((i % 2 == 1) ? t : s));
}
}
```
[Answer]
# C#, 94 bytes
```
using System.Linq;string R(string n)=>string.Concat(n.SelectMany((c,i)=>1>i%2?n:n.Reverse()));
```
76 bytes for the method + 18 bytes for LINQ import.
How it works:
```
using System.Linq; // Required for LINQ extension methods.
string R(string n) =>
string.Concat( // Concatenate the following chars into a single string
n.SelectMany( // Enumerate each char in n, flattening the returned IEnumerable<char>'s into a single IEnumerable<char>
/*IEnumerable<char> Lambda*/(/*char*/ c, /*int*/ i) => // i = index in n
1 > i % 2 // Check if i is even or odd
? n // if i is even, add n to the concat
: n.Reverse() // else reverse n and concat that
)
)
;
```
[Answer]
# Julia, 42 bytes
```
h(s,l=1)=l==endof(s)?s:s*h(reverse(s),l+1)
```
Recursive function with counter variable `l`. If it is equal to the length of the string `s`, simply return it, otherwise concatenate (`s*...`) it with `h(reverse(s),...)` while incrementing the counter `l+1`.
[Answer]
# [CJam](http://sourceforge.net/projects/cjam/), 10 bytes
```
l_,({_W%}*
```
[Try it online!](http://cjam.tryitonline.net/#code=bF8sKHtfVyV9Kg&input=SGVsbG8h)
### Explanation
```
l e# Read line
_ e# Duplicate
,( e# Length minus 1
{ }* e# Run code block that many times
_ e# Duplicate
W% e# Reverse
e# Implicitly display
```
[Answer]
# Octave, ~~39~~ 35 bytes
```
@(x)[x'+~x;flip(x'+~x),''](1:end/2)
f('Hello!')
ans = Hello!!olleHHello!!olleHHello!!olleH
```
**Explanation:**
```
@(x) % Take x as input, inside apostrophes 'Hello!'
x'+~x % Create a mesh of the ASCII-code of the input letters
% For input `bcd` this will be:
% 98 98 98
% 99 99 99
% 100 100 100
;flip(x'+~x) % Concatenate vertically to create:
% 98 98 98
% 99 99 99
% 100 100 100
% 100 100 100
% 99 99 99
% 98 98 98
___,''] % Short cut to convert ASCII-code to characters
(1:end/2) % Display the first half of this array of letters, as a
% horizontal string
```
Saved 4 bytes thanks to Luis. `~x` instead of `0*x` saved one byte (works because all elements of x are non-zero. `flip` instead of `flipud` saved another two bytes (I didn't know `flip` existed).
] |
[Question]
[
Given a number `n >= 2`, output all the positive integers less than `n` where `gcd(n, k) == 1` (with `k` being any one of the output numbers). Numbers of this sort are **coprime** to each other.
Example: `10` gives the output `[1, 3, 7, 9]` (in any form you like, as long as the numbers are unambiguously separated and in some sort of list). The list cannot have duplicate entries and doesn't have to be sorted.
More test cases:
```
2 -> [1]
3 -> [1, 2]
6 -> [1, 5]
10 -> [1, 3, 7, 9]
20 -> [1, 3, 7, 9, 11, 13, 17, 19]
25 -> [1, 2, 3, 4, 6, 7, 8, 9, 11, 12, 13, 14, 16, 17, 18, 19, 21, 22, 23, 24]
30 -> [1, 7, 11, 13, 17, 19, 23, 29]
```
We are also not counting numbers above `n` that are coprime to `n`, solely because I'm fairly certain there's infinite solutions.
Also note: Numbers that are coprime to each other are also said to be relatively prime or mutually prime to each other.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~61~~ 47 bytes
```
lambda n:[k/n for k in range(n*n)if k/n*k%n==1]
```
[Try it online!](https://tio.run/nexus/python2#FYpLCoAgAAXXdYq3CTSEftQi8CTVwihDrFdI97dczGZmLDTmeJpr3Qw4Tr4i7B3g4YhgeOyCJaWz@EvpC2rdLDEdTEer0CkMCk2t0Cb639Rjnj3B8RVWUMr4AQ "Python 2 – TIO Nexus")
### Background
Consider the [ring](https://en.wikipedia.org/wiki/Ring_(mathematics)) \$(Z\_n, +\_n, \cdot\_n)\$. While this ring is usually defined using residue classes modulo \$n\$, it can also be thought of as the set \$Z\_n = \{0, \dots, n - 1\}\$, where the addition and multiplication operators are defined by \$a +\_n b = (a + b)\:\%\: n\$ and \$a \cdot\_n b = a \cdot b\:\%\: n\$, where \$+,\:\cdot\text{, and } \%\$ denote the usual addition, multiplication, and modulo operators over the integers.
Two elements \$a\$ and \$b\$ of \$Z\_n\$ are called mutual [multiplicative inverses modulo \$n\$](https://en.wikipedia.org/wiki/Modular_multiplicative_inverse) if \$a \cdot\_n b = 1\:\%\:n\$. Note that \$1\:\%\:n = 1\$ whenever \$n > 1\$.
Fix \$n > 1\$ and let \$a\$ be a coprime of \$n\$ in \$Z\_n\$. If \$a \cdot\_n x = a \cdot\_n y\$ for two elements \$x\$ and \$y\$ of \$Z\_n\$, we have that \$a \cdot x\:\%\:n = a \cdot y\:\%\:n\$. This implies that \$a \cdot (x - y)\:\%\:n = a \cdot x\:\%\:n - a \cdot y\:\%\:n = 0\$, and we follow that \$n \mid a \cdot (x - y)\$, i.e., \$n\$ divides \$a \cdot (x - y)\$ evenly. Since \$n\$ shares no prime divisors with \$a\$, this means that \$n \mid x - y\$. Finally, because \$-n < x - y < n\$, we conclude that \$x = y\$. This shows that the products \$a \cdot\_n 0, \dots, a \cdot\_n (n - 1)\$ are all different elements of \$Z\_n\$. Since \$Z\_n\$ has exactly \$n\$ elements, one (and exactly one) of those products must be equal to \$1\$, i.e., there is a *unique* \$b\$ in \$Z\_n\$ such that \$a \cdot\_n b = 1\$.
Conversely, fix \$n > 1\$ and let \$a\$ be an element of \$Z\_n\$ that is *not* coprime to \$n\$. In this case, there is a prime \$p\$ such that \$p \mid a\$ and \$p \mid n\$. If \$a\$ admitted a multiplicative inverse modulo \$n\$ (let's call it \$b\$), we'd have that \$a \cdot\_n b = 1\$, meaning that \$a \cdot b\:\%\:n = 1\$ and, therefore, \$(a \cdot b - 1)\:\%\:n = a \cdot b\:\%\:n - 1 = 0\$, so \$n \mid a \cdot b - 1\$. Since \$p \mid a\$, we follow that \$p \mid a \cdot b\$. On the other hand, since \$p \mid n\$, we also follow that \$p \mid a \cdot b - 1\$. This way, \$p \mid (a \cdot b) - (a \cdot b - 1) = 1\$, which contradicts the assumption that \$p\$ is a prime number.
This proves that the following statements are equivalent when \$n > 1\$.
* \$a\$ and \$n\$ are coprime.
* \$a\$ admits a multiplicative inverse modulo \$n\$.
* \$a\$ admits a *unique* multiplicative inverse modulo \$n\$.
### How it works
For each pair of integers \$a\$ and \$b\$ in \$Z\_n\$, the integer \$k := a \cdot n + b\$ is unique; in fact, \$a\$ and \$b\$ are quotient and remainder of \$k\$ divided by \$n\$, i.e., given \$k\$, we can recover \$a = k/n\$ and \$b = k\:\%\: n\$, where \$/\$ denotes *integer* division. Finally, since \$a ≤ n - 1\$ and \$b ≤ n - 1\$, \$k\$ is an element of \$Z\_{n^2}\$; in fact, \$k ≤ (n - 1) \cdot n + (n - 1) = n^2 - 1\$.
As noted above, if \$a\$ and \$n\$ are coprime, there will be a unique \$b\$ such that \$a \cdot b\:\%\:n = 1\$, i.e., there will be a unique \$k\$ such that \$k / n = a\$ and \$k / n \cdot k\:\%\:n = (k / n) \cdot (k\:\%\:n)\:\%\:n = 1\$, so the generated list will contain \$a\$ exactly once.
Conversely, if \$a\$ and \$n\$ are *not* coprime, the condition \$k / n \cdot k\:\%\:n = 1\$ will be false for all values of \$k\$ such that \$a = k / n\$, so the generated list will *not* contain \$a\$.
This proves that the list the *lambda* returns will contain all of \$n\$'s coprimes in \$Z\_n\$ exactly once.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 4 bytes
```
gRỊT
```
[Try it online!](https://tio.run/nexus/jelly#@58e9HB3V8j/w@2Pmta4//9vqKNgpKNgrKNgpqNgaADkgLApUMQAAA "Jelly – TIO Nexus")
### How it works
```
gRỊT Main link. Argument: n
R Range; yield [1, ..., n].
g Compute the GCD of n and each k in [1, ..., n].
Ị Insignificant; return 1 for GCDs less or equal to 1.
T Truth; yield the indices of all truthy elements.
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 3 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
gÐṂ
```
[Try it online!](https://tio.run/##y0rNyan8/z/98ISHO5v@H25/1LTG/f//aCMdBWMdBTMdBUMDHQUjEDYFihjEAgA "Jelly – Try It Online")
# How does this work?
```
gÐṂ - (Monadic) Full program.
g - Greatest common divisor.
ÐṂ - Keep the elements with minimum link value (i.e. those with GCD == 1)
Note that this automatically creates the range [1, input] (inclusive).
```
## Proof of validity
Since we want to extract the coprimes only, the minimum value of the Greatest-Common-Divisors list *has* to be **1** for the `ÐṂ` trick to work. Let's prove that (in two different methods):
1. The implicitly generated range, \$[1, \text{input}]\$ contains \$1\$ and \$\gcd(1, x) = 1\:\:\forall\:\:x \in \mathbb{Z}^{\*}\$. The greatest common divisor is always a strictly positive integer, hence \$1\$ is guaranteed to occur and will always be the minimum value.
2. Two consecutive positive integers are always coprime. Consider \$x, y \in \mathbb{Z}^{\*}\$, with \$y = x + 1\$. Then we take another positive integer \$k\$ such that \$k \mid x\$ and \$k \mid y\$.
This implies that \$k \mid (y - x)\$, so \$k \mid (x + 1 - x)\$, thus \$k \mid 1\$. The only positive integer to divide \$1\$ is \$1\$ itself, so it is guaranteed to appear in the list and will always be the minimum value.
[Answer]
## Mathematica, 25 bytes
```
Range@#~GCD~#~Position~1&
```
Slightly weird output format, where each result is wrapped in a separate list, e.g. `{{1}, {3}, {7}, {9}}`. If that's not okay, I've got two solutions at 30 bytes:
```
Select[Range[x=#],#~GCD~x<2&]&
#&@@@Range@#~GCD~#~Position~1&
```
Mathematica actually has `CoprimeQ` but that's way too long.
[Answer]
# [2sable](https://github.com/Adriandmen/2sable), 4 bytes
Code:
```
ƒN¿–
```
Explanation:
```
ƒ # For N in the range [0, input]..
N¿ # Compute the GCD of N and the input
– # If 1, print N with a newline
```
Uses the **CP-1252** encoding. [Try it online!](https://tio.run/nexus/2sable#@39skt@h/Y8aJv//b2wAAA "2sable – TIO Nexus")
[Answer]
# Python, ~~93~~ ~~82~~ 74 bytes
```
f=lambda a,b:f(b,a%b)if b else a<2
lambda c:[i for i in range(c)if f(i,c)]
```
`f` recursively checks for coprimes, and the second lambda generates them. Outputs a list.
[Answer]
# [Actually](https://github.com/Mego/Seriously), 8 bytes
```
;╗R`╜┤`░
```
[Try it online!](https://tio.run/nexus/actually#ARUA6v//O@KVl1Jg4pWc4pSkYOKWkf//MTA "Actually – TIO Nexus")
Explanation:
```
;╗R`╜┤`░
R` `░ elements of range(1, n+1) where
;╗ ╜ n and the element
┤ are coprime
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 7 bytes
```
:GZd1=f
```
[Try it online!](https://tio.run/nexus/matl#@2/lHpViaJv2/7@RAQA "MATL – TIO Nexus")
[Answer]
# MATLAB/Octave, 22 bytes
```
@(n)find(gcd(1:n,n)<2)
```
[Try it online!](https://tio.run/nexus/octave#@@@gkaeZlpmXopGenKJhaJWnk6dpY6T5PzGvWMPIQPM/AA "Octave – TIO Nexus")
[Answer]
# JavaScript (ES6), ~~64~~ 61 bytes
*Saved 3 bytes thanks to @user81655*
```
n=>[...Array(n).keys()].filter(b=>(g=a=>b?g(b,b=a%b):a<2)(n))
```
### Test snippet
```
f=n=>[...Array(n).keys()].filter(b=>(g=a=>b?g(b,b=a%b):a<2)(n))
for(var i = 2; i < 50; i++) console.log(i + ":", `[${ f(i) }]`);
```
[Answer]
## [Jellyfish](https://github.com/iatorm/jellyfish), ~~19~~ 18 bytes
```
p
[#
`B
&~xr1
NnEi
```
This works by computing the prime factorization of every number in the range and checking whether it intersects that of the input (Jellyfish doesn't have a gcd builtin yet).
For golfing reasons, the output is in descending order.
[Try it online!](https://tio.run/nexus/jellyfish#@1/AFa3MleDEpVZXUWTI5Zfnmvn/v5EBAA "Jellyfish – TIO Nexus")
## Explanation
First off, `i` is evaluated input; for input `10`, the value of the `i`-cell is `10`.
```
r1
i
```
Here `r` (range) is applied to the input and 1.
Because the input is greater than 1, the range is in descending order; for input `10`, this gives `[9 8 7 6 5 4 3 2 1]`.
```
[#
`B
&~x
Nn
```
This part is one big function, which is evaluated on `i` and the above range.
```
~x
n
```
Intersection (`n`) of prime factors (`x`).
```
&~x
Nn
```
Is it empty? (`N`)
```
`
&~x
Nn
```
Thread to level 0, testing for each element of the range.
```
[#
`B
&~x
Nn
```
Filter (`#`) the range with respect to this list of booleans.
The function produced by `[` wants to use the argument to `#` as its own argument, so we put a `B` to block `#` from getting any arguments.
Otherwise, the value of the `~`-cell would be used as the argument of the big function.
Finally, `p` prints the result.
[Answer]
# Stacked, noncompeting, ~~24~~ 21 bytes
Saved 3 bytes, inspired by [Borsunho's ruby](https://codegolf.stackexchange.com/a/104675/31957). (`1 eq` to `2<`)
```
{!n:>1+:n gcd 2<keep}
```
[Try it here!](https://conorobrien-foxx.github.io/stacked/stacked.html)
This is an n-lambda that takes a single argument and yields the array.
```
{!n:>1+:n gcd 2<keep}
{! } n-lambda
n push n
:> range [0, n)
1+ range [1, n]
: duplicate
n gcd element-wise gcd with n
2< element-wise equality with 1
this yields the range [1, n] and a boolean mask of coprime numbers
keep then, we simply apply the mask to the range and keep coprimes.
```
[Answer]
## [CJam](https://sourceforge.net/p/cjam), 14 bytes
```
{:X{Xmff%:*},}
```
[Try it online!](https://tio.run/nexus/cjam#izZSMFYwUTBVMFMwNFAwAiJTBWOD2P/VVhHVEblpaapWWrU6tf9VrQr@AwA "CJam – TIO Nexus")
### Explanation
We don't need to check all possible divisors of `a` and `b` to test whether they're coprime. It's sufficient to look at whether any of the prime factors of `b` divides `a`.
```
:X e# Store the input in X.
{ e# Filter the list [0 1 ... X-1] by the results of this block...
Xmf e# Get the prime factors of X.
f% e# Take the current value modulo each of those prime factors.
:* e# Multiply the results. Iff any of them divide the current
e# value, there's a 0 in the list, and the result of the product
e# is also 0, dropping the value from the resulting list.
},
```
[Answer]
# Mathematica, 26 bytes
```
Pick[r=Range@#,r~GCD~#,1]&
```
[Answer]
# [Perl 6](http://perl6.org), 20 bytes
```
{grep 2>* gcd$_,^$_}
```
[Answer]
# [Julia 0.5](http://julialang.org/), 23 bytes
```
!n=1÷gcd.(1:n,n)|>find
```
[Try it online!](https://tio.run/nexus/julia5#@6@YZ2t4eHt6coqehqFVnk6eZo1dWmZeyv@0/CKFPIXMPAUNIx0FYx0FMx0FQwMdBSMQNgWKGGhycToUFGXmlaRpKKkapSjo2imoFsfkKeko5OkoKOZpcqUCTQEA "Julia 0.5 – TIO Nexus")
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), ~~16~~ 13 bytes
```
>.$p'(e:A*?),
```
This is a function that takes *N* as input, and [generates](https://codegolf.meta.stackexchange.com/a/10753/62131) all integers less than and coprime to it.
[Try it online!](https://tio.run/nexus/brachylog#@29VbaenUqCukWrlqGWvqVObVv7/v7EBAA "Brachylog – TIO Nexus") As is often the case in Brachylog, this has had extra code added to make the function into a full program; Brachylog's interpreter, if given a function rather than a full program, will run it but not print the output, which means you can't really observe its workings.
Explanation:
A Brachylog program is a chain of constraints; typically, the LHS of one constraint is the RHS of the next.
```
>.$p'(e:A*?),
> The input is greater than
. the output, whose
$p prime factorisation does
'( ) not obey the following constraint:
e it has an element which
:A* can be multiplied by something to
? produce the input.
, (This comma turns off an unwanted implicit constraint.)
```
Golfed down three characters by realising there's no reason to check to see if the common factor (which is already known to be a prime factor of the output) is a *prime* factor of the input. We already know it's prime, so we can just check if it's a factor. I'm pleasantly surprised here that `:A*?` doesn't send the interpreter into an infinite loop *and* doesn't allow a non-integer value for *A*, but as the interpreter does what I want, I'll take it.
[Answer]
# Dyalog APL, 10 [bytes](http://meta.codegolf.stackexchange.com/questions/9428/when-can-apl-characters-be-counted-as-1-byte-each/9429#9429).
```
0~⍨⍳×1=⊢∨⍳
```
Explanation (input `n`):
```
0~⍨⍳×1=⊢∨⍳
⍳ - 1 ... n (Thus, ⎕IO is 1)
⊢∨ - Each GCD'd by n
1= - Test equality with 1 on each element
⍳× - multiplied by its index
0~⍨ - without 0.
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt/) `-f`, ~~9~~ ~~8~~ ~~5~~ 2 bytes
```
jN
```
[Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=ak4=&input=ODgKLWY=)
* 2 bytes saved thanks to [ETH](https://codegolf.stackexchange.com/users/42545/ethproductions) pointing out a brainfart, which led to another byte saved.
[Answer]
# Mathematica, 33 bytes
```
xSelect[Range@x,x~CoprimeQ~#&]
```
Contains U+F4A1
[Answer]
# Haskell, 27 bytes
```
f n=[k|k<-[1..n],gcd n k<2]
```
[Try it online!](https://tio.run/nexus/haskell#@5@mkGcbnV2TbaMbbainlxerk56copCnkG1jFPs/NzEzT8FWoaC0JLikyCdPpTgjv1xFIU3ByOA/AA "Haskell – TIO Nexus")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 3 bytes
```
Lʒ¿
```
[Try it online!](https://tio.run/##MzBNTDJM/f/f59SkQ/v//zc2AAA "05AB1E – Try It Online")
Has new features.
[Answer]
# [memes](https://github.com/ineternet/memes), 11 bytes
Uses UTF-8 encoding.
```
d`}}]i=1?ip
```
Explanation:
```
d Set program to not output result
`} Loop next input-times
}]i GCD of input and loop index
=1? Is it equal to 1? If yes,
ip Print out loop index
```
`}` accesses the next input item, but last input is looped through when given, so inputting `6` will result as `6 6 6 6 6 ...` in STDIN, making it possible for reading two outputs from one.
[Answer]
# Ruby, ~~36~~34
```
->n{n.times{|i|p i if i.gcd(n)<2}}
```
Admittedly, this isn`t a very *inspired* answer.
2 bytes saved thanks to Conor O'Brien.
[Answer]
# [Python 3](https://docs.python.org/3/), 60 bytes
Imports gcd instead of writing a new lambda for it. Golfing suggestions welcome. [Try it online!](https://tio.run/nexus/python3#@5@ZW5BfVKKQm1iSwVVhm5OYm5SSqJBsFZ2pkJZfpJCpkJmnUJSYl56qkayZmQZWppeenKKRrJOpaWMUy1VQlJlXolGhYWigqfn/PwA "Python 3 – TIO Nexus")
```
import math
lambda c:[i for i in range(c)if math.gcd(c,i)<2]
```
[Answer]
# Julia, 30 bytes
```
n->filter(x->(gcd(n,x)<2),1:n)
```
Anonymous function. `filter` removes elements from a list that aren't truthy according to a function.
In this case, the function is `x->(gcd(n,x)<2)` (true if the gcd of the input and the list element is less than 2). The list is the range `1:n`.
[Answer]
# [PARI/GP](http://pari.math.u-bordeaux.fr/), 27 bytes
```
n->[k|k<-[1..n],gcd(k,n)<2]
```
This uses the set-notation introduced in version 2.6.0 (2013). In earlier versions, four more bytes were needed:
```
n->select(k->gcd(k,n)<2,[1..n])
```
would be needed.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 4 bytes
```
GN¿–
```
[Try it online!](https://tio.run/##MzBNTDJM/f/f3e/Q/kcNk///NzYAAA "05AB1E – Try It Online")
How it works
```
# implicit input
G # for N in range(1..input)
N # push N
¿ # gcd(input, N)
– # if 1, print N
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 54 bytes
```
k;f(n){for(k=0;++k/n<n;k/n*k%n-1||printf("%u ",k/n));}
```
This is a port of [my Python answer](https://codegolf.stackexchange.com/a/104681/12012).
[Try it online!](https://tio.run/##PU3RCsIwDHxuvyIMBu3a4TbRB@O@RH2QQWWUxTK2p63fXlNQH5LL3SW5oX4NQ0oenSK9ufesfN@gMf5AV0LulS@pbvc9zCMtThXlCoVlXWuMiSWYniMpLTcpMltuD@hhg87C0cLZQttY6HKdWGFsIKKUgpNA5YMq8P6CjAjBGC0FfxL/tG69cB67Gll26jv8/DsVmUcZ0wc "C (gcc) – Try It Online")
[Answer]
# [Whispers v2](https://github.com/cairdcoinheringaahing/Whispers), 65 bytes
```
> Input
> 1
>> (1]
>> L⊓1
>> L=2
>> Select∘ 4 5 3
>> Output 6
```
[Try it online!](https://tio.run/##K8/ILC5ILSo2@v/fTsEzr6C0hMtOwZDLzk5BwzAWRPk86poM5vvYGoGo4NSc1OSSRx0zFEwUTBWMQUL@pSVAfQpm//8bGwAA "Whispers v2 – Try It Online")
Uses the [recently implemented](https://github.com/cairdcoinheringaahing/Whispers/commit/36e87fb697076db347602b521b30b054471a9991) `Select∘` command.
## How it works
The entire program is built from lines **4**, **5** and **6**
```
>> L⊓1
>> L=2
>> Select∘ 4 5 3
```
This is the first use of any of the three `Select` statements, this time using the `Select∘` statement. All forms of the `Select` statements take **n** line references as arguments. The last number references the array to select from (let's say \$A\$), and the others reference the functions to iterate over that array (i.e the array of functions, \$B\$). However, they differ as follows:
* `Select∧` - Only select elements which are truthy under all functions in \$B\$:
$$R := [x \in A \: | \: f(x) \top, \forall f \in B]$$
* `Select∨` - Only select elements which are truthy under any function in \$B\$
$$R := [x \in A \: | \: f(x) \top, \exists f \in B]$$
* `Select∘` - Only select elements which, when all functions in \$B\$ are [composed](https://en.wikipedia.org/wiki/Function_composition) together, are truthy under this new function:
$$\text{Let }B := [f(x), g(x), h(x)]$$
$$R := [x \in A \: | \: h(g(f(x))) \: \top]$$
In this program, we can define \$A := [1, 2, ..., \alpha-1, \alpha]\$, where \$\alpha\$ is the input. We then define line **4** (`>> L⊓1`) as \$f(x) = \gcd(x, \alpha)\$ and line **5** (`>> L=2`) as \$g(x) := (x = 1)\$. Finally, we can define \$B = [f(x), g(x)]\$. This sets us up for the select statement as shown above.
When we encounter the `Select∘` statement, we take \$R\$ (the final array) as defined by the third relationship above. To make things slightly easer, we'll define
\begin{align}
h(x) & := g(f(x)) \\
& := gcd(x, \alpha) = 1
\end{align}
\$R\$ is then equal to the array where \$\forall x \in R\$, \$h(x) \: \top\$. Finally, on the last line, we output \$R\$.
### Shorter version, 56 bytes
```
> Input
> 1
>> (1]
>> L⟂1
>> Select∘ 4 3
>> Output 5
```
[Try it online!](https://tio.run/##K8/ILC5ILSo2@v/fTsEzr6C0hMtOwZDLzk5BwzAWRPk8mt8E5gen5qQmlzzqmKFgomAMEvAvLQEqVzD9/9/YAAA "Whispers v2 – Try It Online")
This is much less interesting as it uses the [co-prime builtin](https://github.com/cairdcoinheringaahing/Whispers/blob/master/whispers.py#L507). In this case, any of the three select statements can be used.
] |
[Question]
[
A string is considered to be square if the following conditions are met:
* Each line has the same number of characters
* The number of characters on each line is equal to the number of lines.
Your task is to write a program or function which determines whether or not a given input string is a square.
You may require input to be delimited by your choice of LF, CR, or CRLF.
The newline character(s) are not considered part of the line's length.
You may require there to be or to not be a trailing newline in input, which doesn't count as an additional line.
Input is a string or 1D char array; it is not a list of strings.
You may assume input is non-empty and only contains printable ASCII, including spaces.
You must output a truthy value for square strings and a falsy one for other strings.
## Truthy test cases:
```
foo
bar
baz
```
```
.
```
```
.s.
.ss
.s.
(s represents space)
```
```
ss
ss
(s represents space)
```
```
aaaaa
aaaaa
aaaaa
aaaaa
aaaaa
```
## Falsy test cases:
```
..
.
```
```
.
```
```
.
```
```
....
....
```
```
4444
333
22
```
```
333
333
```
```
abc.def.ghi
```
Note extra blank lines in some of the falsy cases.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") - fewest bytes wins!
[Answer]
# [Python 2](https://docs.python.org/2/), 52 bytes
```
x=input().split('\n')
print{len(x)}==set(map(len,x))
```
[Try it online!](https://tio.run/##K6gsycjPM/r/v8I2M6@gtERDU6@4ICezREM9Jk9dk6ugKDOvpDonNU@jQrPW1rY4tUQjN7FAAyigU6Gp@f@/eiIIxOThptQB "Python 2 – Try It Online") or [Try all test cases](https://tio.run/##dUxBCsMgELz7Cm8qBKHaUyE/2UtKlQjpRtRQ29K329WeO7Azs8vMxmdZdzSt3ZznXmZ1YbzOWee4hSIFoFCMJ1eOhO/NoazqM8/ZFXlfoqTDVJVqjzVsjp9GNWA8iqRSTAELr1P/MXkqDteE33fA65I6vQQTmmbpAPwvPacBe5aE@OfPBEBrLaAxtA9HJL4 "Python 2 – Try It Online")
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog) (2), 3 bytes
```
ṇẹṁ
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r//@HO9oe7dj7c2fj/v1Jafj5XUmIREFcpAQA "Brachylog – Try It Online")
Full program. Outputs `true.` for truthy, `false.` for falsey.
## Explanation
```
ṇẹṁ
ṇ Split {standard input} into lines
ẹ Split {each line} into basic elements {in this case, characters}
ṁ Assert that the result is square
```
I was a bit sceptical about the usefulness of the `ṁ` builtin when it was added, but I can't really deny that it's helpful here…
# [Brachylog](https://github.com/JCumin/Brachylog) (2), 7 bytes
```
ṇẹ.\l~l
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r//@HO9oe7durF5NTl/P@vlJafz5WUWATEVUoA "Brachylog – Try It Online")
Non-builtin solution. ~~*Still* beats all the other entries, as of the time of writing.~~ EDIT: Not quite, the equal-length Jelly entry got in while I was writing this, and beats it via the timestamp tiebreak.
## Explanation
```
ṇẹ.\l~l
ṇ Split {standard input} into lines
ẹ Split {each line} into basic elements {in this case, characters}
\l Assert that the result is rectangular, and the number of columns
. ~l is equal to the number of rows
```
[Answer]
# JavaScript (ES6), ~~46~~ 45 bytes
```
s=>!(s=s.split`
`).some(x=>x.length-s.length)
```
* 1 byte saved thank to [ETHproductions](https://codegolf.stackexchange.com/users/42545/ethproductions)
---
## Explanation
1. Split the string to an array on newlines.
2. Loop over the array.
3. Subtract the length of the array from the length of each line.
4. If a non-zero (i.e., truthy) value is returned for any line, the string is not square.
5. Negate the result of the loop to get `true` for square and `false` for not.
---
## Try it
```
f=
s=>!(s=s.split`
`).some(x=>x.length-s.length)
oninput=_=>o.innerText=f(i.value)
o.innerText=f(i.value=`foo
bar
baz`)
```
```
<textarea id=i></textarea><pre id=o>
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~7~~ 5 bytes
```
Ỵ¬⁼Z$
```
[Try it online!](https://tio.run/##y0rNyan8///h7i2H1jxq3BOl8v///0QQ4EoCAa5kEOBKAQGuVBAAAA "Jelly – Try It Online")
Thanks to [FryAmTheEggman](https://codegolf.stackexchange.com/users/31625/fryamtheeggman) for -2
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~10~~ 8 bytes
```
¶¡€gDgQP
```
[Try it online!](https://tio.run/##MzBNTDJM/f//0LZDCx81rUl3SQ8M@P9fSUkpMTGRK7EYiBMTgTwA "05AB1E – Try It Online")
***-2 thanks to Riley, this is basically his answer .\_.***
```
Code # Explanation | Truthy Example | Falsy Example
-----------#------------------------------+-------------------------+--------------
¶¡ # Split on newlines | [['aaa','aaa','aaa']] | [['aa']]
€g # Get length of each | [[3,3,3]] | [[2]]
D # Dupe | [[3,3,3],[3,3,3]] | [[2],[2]]
g # Get length | [[3,3,3],3] | [[2],1]
Q # Check equality | [[1,1,1]] | [[0]]
P # Take product | 1 | 0
```
[Answer]
## Haskell, ~~38~~ 34 bytes
```
l=length
(all=<<(.l).(==).l).lines
```
[Try it online!](https://tio.run/##FcXBCoAgDADQe18xpINCCdXV/YmXFZrSGpH@/6J3eYXalZhVGTnJ2cuQ0RIzhmA9O28R3T9XSU1vqgIIz1ulwwgZDO1HlGXdokx@NvoB "Haskell – Try It Online")
Pointfree version of `f s = all ((==length (lines s)).length) (lines s)`, i.e split the input into lines and check if the length of each line is equal to the number of lines.
Edit: Thanks to @xnor for 4 bytes.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes
```
ỴµL;L€E
```
[Try it online!](https://tio.run/##y0rNyan8///h7i2HtvpY@zxqWuP6////RCDgSgICrmQg4EoBAgA "Jelly – Try It Online")
## Explanation
```
Ỵµ Split the input on newline and use as input in the second link
L Get the number of list items
; And append to that
L€ A list with the legth of each list item
E Check to see if all items are equal.
```
[Answer]
## [Husk](https://github.com/barbuz/Husk), 6 bytes
```
S≡T'a¶
```
Takes a string and prints either `1` or `0`.
[Try it online!](https://tio.run/##yygtzv6vkPuoqfF/8KPOhSHqiYe2/f//P1rJ0Mg4Ji8xKTkmr6KySklHSQ@IFRRi8hQUgIxEIADKwkmQvB6YiMmD0CAWCIJYSrEA "Husk – Try It Online")
The first line iterates over the test cases; remove it if you want to test on a single value.
## Explanation
Husk is a new functional golfing language created by myself and [Leo](https://codegolf.stackexchange.com/users/62393/leo).
It's missing a lot of features and development is ongoing.
Its main feature is a rigid type system that allows us to overload higher order functions.
On a high level, the program works like this:
```
S≡T'a¶ Define a function:
¶ split on newlines,
T'a transpose and pad to rectangle using character 'a',
≡ check if this has the same shape as
S the split input.
```
The function `≡` actually checks if two arrays have the same shape and the same distribution of truthy elements.
In Husk, all characters except the null byte are truthy, and that won't occur in our inputs.
Also, `S` is the **S-combinator**, a function that takes as inputs two functions, here `≡` and `T'a`, and returns a new function that maps `x` to `≡(x)(T'a x)`.
The result of `S` is composed with `¶`, and that function is applied to the input implicitly.
How does Husk know that it should apply `S` to the next function, but `¶` should be composed with the function on its left?
Simple: it just tries every interpretation and picks the one where the types make sense.
This is explained in more detail in the [Husk documentation](https://github.com/barbuz/Husk/wiki).
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 9 bytes
```
=Ur.Q)¥Uy
```
[Test it online!](http://ethproductions.github.io/japt/?v=1.4.5&code=PVVyLlEppVV5&input=ImFiYwpkZWYKZ2hpIg==)
### Explanation
```
=Ur.Q)¥ Uy
U=Ur.Q)==Uy
// Implicit: U = input string, Q = quotation mark
U= ) // Set U to
Ur.Q // U with each non-newline (/./g) replaced with a quotation mark.
==Uy // Return U == U transposed. U is padded to a rectangle with spaces before
// transposing; if U was not a rectangle before, or the sides are not of
// equal length, the result will not be the same as U.
// Implicit: output result of last expression
```
---
Using some features implemented shortly after this challenge was posted, this can be 6 bytes:
```
r.Q
¥y
```
[Test it online!](http://ethproductions.github.io/japt/?v=1.4.5&code=ci5RCqV5&input=ImFiYwpkZWYKZ2hpIg==)
### Explanation
```
// Implicit: U = input string
r.Q // Replace each non-newline (/./g) in U with a quotation mark.
// Newline: set U to the result.
¥ // Return U ==
y // U transposed.
// Implicit: output result of last expression
```
[Answer]
# [Retina](https://github.com/m-ender/retina), ~~33~~ 31 bytes
```
.
.
^(.(.)*)(?<-2>¶\1)*$(?(2).)
```
[Try it online!](https://tio.run/##K0otycxL/P9fj0uPK05DT0NPU0tTw95G18ju0LYYQ00tFQ17DSNNPc3//wE "Retina – Try It Online") Explanation: The first stage simply changes all printable ASCII into the same character to make it easier to match. (It could be done without, but this is code golf, not code challenge.) The second stage then matches at least one character on the first line. However, for each additional character on the first line, it then optionally matches a newline followed by a copy of the first line. The final part of the expression causes the match to fail if there are more columns than rows.
[Answer]
# Pure bash (no utilities), 55
```
mapfile -t a
for l in ${a[@]};{
((c+=${#l}^${#a[@]}))
}
```
* `mapfile` reads the input into array `a`
* then the number of elements of the array is XORed with each line length, and the sum taken. For a perfect square, each XOR result (and thus the sum) will be 0. For anything else, the result will be >0.
The opposite sense of this is returned as a shell return code (examine with `echo $?`) - perfect square is 1, anything else is 0.
[Try it online (truthy)](https://tio.run/##S0oszvj/PzexIC0zJ1VBt0QhkSstv0ghRyEzT0GlOjHaIbbWuppLQyNZ21alWjmnNg5IgkU1Nblq/6cmZ@QrqNj/TwQBLhwkAA).
[Try it online (falsy)](https://tio.run/##S0oszvj/PzexIC0zJ1VBt0QhkSstv0ghRyEzT0GlOjHaIbbWuppLQyNZ21alWjmnNg5IgkU1Nblq/6cmZ@QrqNj/NwECLmNjYy4jIwA).
---
### Previous answer using eval-escape-expansion hell, 78:
```
mapfile -t a
echo $[0$(eval eval echo +\\$\{#a[{0..$[${#a[@]}-1]}]}^${#a[@]})]
```
[Try it online (truthy)](https://tio.run/##S0oszvj/PzexIC0zJ1VBt0QhkSs1OSNfQSXaQEUjtSwxRwFCgMS0Y2JUYqqVE6OrDfT0VKJVQEyH2Fpdw9ja2No4GFcz9v//RBDgwkECAA).
[Try it online (falsy)](https://tio.run/##S0oszvj/PzexIC0zJ1VBt0QhkSs1OSNfQSXaQEUjtSwxRwFCgMS0Y2JUYqqVE6OrDfT0VKJVQEyH2Fpdw9ja2No4GFcz9v9/EyDgMjY25jIyAgA).
[Answer]
# [Perl 6](http://perl6.org/), 27 bytes
```
{.lines==all .lines».comb}
```
Tests whether the number of lines in the input string is equal to the number of characters on each line.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 4 bytes
```
Ỵ¬zƑ
```
[Try it online!](https://tio.run/##y0rNyan8///h7i2H1lQdm/j//3@lxKSYvGQlAA "Jelly – Try It Online")
Input via command-line argument. The input must be given with no trailing newline (otherwise the program sees a blank line at the end, which isn't the same length as the others); this I/O format is explicitly allowed by the question.
So far, the shortest answer that doesn't use an "is a square" builtin. (There's an existing 5-byte Jelly answer that works on similar principles, but is wrong, incorrectly considering `"aa\na"` to be square – this answer is not only shorter, it also fixes that issue.)
## Explanation
```
Ỵ¬zƑ
Ỵ split {the input} on newlines
¬ replace every truthy character (i.e. all of them) with 0
Ƒ does that remain unchanged, after
z a ragged transpose that pads to a rectangle using {the input}?
```
There are two main cases:
* The string is not even a rectangle. In this case, the "transpose and pad to rectangle" builtin `z` will pad the string to a rectangle, but uses copies of the user input as the padding, which are not zeroes (even if the input uses the character `'0'`, this compares unequal to the integer `0`). So there's no way the ragged transpose can leave the split-and-zeroed version of the input unchanged.
* The string is a rectangle. In this case, the ragged transpose won't apply any padding, but will produce a rectangle of zeroes with the number of rows and columns swapped from the transpose input. The only way the input and output can match is therefore if the number of rows equals the number of columns, i.e. the input is a square. (If the input *is* a square, the transpose will leave it unchanged because, as every element is a zero, all the elements will be the same and thus it doesn't matter that the transpose swaps some of them.)
[Answer]
## Pyth, 7 bytes
```
CImL1.z
```
[Try it here](http://pyth.herokuapp.com/?code=CImL1.z&input=aaaaa%0Abbbbb%0Accccc%0Addddd%0Aeeeee&debug=0)
Requires no trailing newline. Replaces the input with a 2D array of 1s where a 1 represents any character in the original input. Then we check whether that array is unchanged after transposing it (replacing columns with rows). Only a square will return true in such a situation.
[Answer]
# [Java (OpenJDK 8)](http://openjdk.java.net/), ~~96~~ ~~91~~ ~~90~~ 87 bytes
*-5 bytes thanks to @KevinCruijssen*
*-1 byte thanks to @TheLethalCoder*
*-2 bytes thanks to @OlivierGrégoire*
```
a->java.util.Arrays.stream(a.split("\n")).allMatch(x->x.length()==a.split("\n").length)
```
[Try it online!](https://tio.run/##rZGxTsMwEIbn5CmsTo5ErlLLRGklGLp1KhthuLpO4uKeI9upGlAfmznYoRJigHbgt3R3On@@@yXv8IC5aSTttq990260EkxodI6tUBF7T1nQue88@pAORm3ZPtzytbeKqucXhrZyWYCTXRgHrVcaypaEV4ZgeS7uv@gb9miMlkgLVrI56zFffD96sBY7B85biXuO4BqtPB8VNMoyQK1X6EXNj/niCFpS5Wuezec/sHM/65PZYD1qPGZPtvV1xwQ66e7SZN05L/dgWg9NMOU18RKwaXTHR6UxBW3QxvAW9s7@xuEyglEF/Z6GEWkSfC5Ru@tsAhR0xe7/gwDiynhidZm/DSpoOp0WNJlcxgcwhIGMv3ZKT/0HmVygqOUn "Java (OpenJDK 8) – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 7 bytes
```
|€gDgQP
```
[Try it online!](https://tio.run/##MzBNTDJM/f@/5lHTmnSX9MCA//8TQYALBwkA "05AB1E – Try It Online")
[Answer]
# [R](https://www.r-project.org/), 57 bytes
```
function(s)all(nchar(n<-strsplit(s,'
')[[1]])==length(n))
```
An anonymous function; Splits on newlines, computes the length of each line, and checks if all are the same as the number of lines.
[Try it online!](https://tio.run/##JYhBCoAgEEX3c5GZgQra50nExRRZgYyhtunyZvh5nwcvVW@qf3QrV1TKLCGQbqck0mXMJeU7XIXygIBs7ewcGxN2PcpJylw94YQMTT5GWCW1vz1MbQDwqwcRgR/k@gE "R – Try It Online")
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~14~~ 12 bytes
```
10H&XXot&n=h
```
The input string is defined using string concatenation (`[...]`) and with the code point `10` to represent LF. For example, `['aaa' 10 'bb']` is interpreted in MATL as string `'aaa'` concatenated with the character with code point `10` concatenated with string `'bb'`.
The output is a non-empty numeric vector, which is [truthy](https://codegolf.stackexchange.com/a/95057/36398) if and only if all its entries are non-zero.
**[Try it online!](https://tio.run/##y00syfmf8N/QwEMtIiK/RC3PNuO/S8j/aPW0/Hx1BUMDBfWkxCIYo0o9lktdT50rWj0RBCDCRDJjgbr0IAJ6eggekAEWgogAAVgJRBVUnQkQQDQaGxtDGEZGYBk4H8SIBQA "MATL – Try It Online")**
### Explanation
Consider input `['4444' 10 '333' 10 '22']`.
```
10H % Push 10 (code point of LF). Push 2
% STACK: 10, 2
&XX % Regexp with three arguments. First argument is implicit input (string);
% second is 2, which indicates that we want to split the input; third is
% 10, which is the character to split on. The result is a cell array of
% matched strings
% STACK: {'4444', '333', '22'}
o % Concatenate into a numeric 2D array of code points, right-padding with
% zeros if needed
% STACK: [52 52 52 52; 51 51 51 0; 50 50 0 0]
t&n % Duplicate. Push number of rows and number of columns
% STACK: [52 52 52 52; 51 51 51 0; 50 50 0 0], 3, 4
= % Are they equal?
% STACK: [52 52 52 52; 51 51 51 0; 50 50 0 0], 0
h % Concatenate into a row vector (in column-major order). Implicit display
% STACK: [52 51 50 52 51 50 52 51 0 52 0 0 0]
```
[Answer]
# R, 35 bytes
```
all(nchar(x<-scan(,""))==length(x))
```
Takes input from stdin. Checks that the number of characters in each line is equal to the total number of lines. Returns `TRUE` or `FALSE` as appropriate.
[Answer]
# Ruby, 50 bytes
```
s=$<.read.split $/,-1;p [s.size]==s.map(&:size)|[]
```
[Try it online!](https://tio.run/##KypNqvz/v9hWxUavKDUxRa@4ICezRENFX0fXUNO6QCG6WK84syo11ta2WC83sUBDzQrE1ayJjv3/Py0/nyspsQqIiwA "Ruby – Try It Online")
## Explanation
1. Split input into array on newline.
2. Assert that an array containing only the size of this array is equal to an array containing all uniq (set union with empty array) sizes of all elements in this array.
[Answer]
# JavaScript (ES6), 48 bytes
```
s=>(a=s.split`
`,a.every(l=>l.length==a.length))
```
[Answer]
## CJam, 11 bytes
```
qN/:,_,f=:*
```
[Try it online!](https://tio.run/##S85KzP3/v9BP30onXifN1krr//9EIOACE0lAwJUMBAA "CJam – Try It Online")
[Answer]
# [OCaml](http://www.ocaml.org/), 56 bytes
```
let f t=List.(for_all(fun l->String.length l=length t)t)
```
[Try it online!](https://tio.run/##dY89DsIwDIVnegrLUzKQC1ThAiAxMFZVFYFTIpkUJeb8oUoLAz@DZT@97z3J09nduBQmAQ9iDyGLUX5Kg2NW/hGBt7uTpBBHwxRHuQLb9RAtugaVBttsXM6UZuGhQ2OwBTTYgwXvOJNuP4EFeU3V/2nsvwuW2C9ntd6rIvf5BxkoXjhEAjzusSlP "OCaml – Try It Online")
[Answer]
# Pyth, ~~12~~ 10 bytes
```
!fnl.zlT.z
```
Saved 2 bytes thanks to @FryAmTheEggman.
[Try it online](http://pyth.herokuapp.com/?code=!fnl.zlT.z&input=aaaaa%0Aaaaaa%0Aaaaaa%0Aaaaaa%0Aaaaaa&debug=0)
### Explanation
```
!fnl.zlT.z
f T.z Filter lines of the input
nl.zl whose length is not the number of lines
! and return whether there are no such lines.
```
[Answer]
# [QBIC](https://drive.google.com/drive/folders/0B0R1Jgqp8Gg4cVJCZkRkdEthZDQ), 43 bytes
```
{_?~_lA||h=h+1┘g=g+_lA|~g%_lA||_Xp]\_xg/h=h
```
Me, I'm happy with how short a QBasic derivative got to go on this challenge.
## Explanation:
```
{_? DO infinitely: ask the user for input, store as A$
~ | IF
_lA| The length of A$ (implicitly <> 0)
h=h+1 Add 1 to our line counter
┘ (syntactic linebreak)
g=g+_lA| Add the length of this line to the running total of line lengths
~ | IF
g%_lA| The length of the running total modulo the length of the last string
yields anything but 0, there is a discrepancy between earlier line
lengths and this one.
_Xp] THEN QUIT, printing 0, end IF
\ ELSE (refers to the LEN(A$), user didn't input anything.
_xg/h=h QUIT (the inf. loop) printing -1 if the root of the chars is the row count
or 0 if not.
```
[Answer]
# Pyth, 7 bytes
```
qCC.z.z
```
[Demonstration](https://pyth.herokuapp.com/?code=qCC.z.z&input=foo%0Abar%0Abaz&debug=0)
Transpose the input with truncation twice, then check if the result is the same as the original.
[Answer]
# [Perl 5](https://www.perl.org/), 31 bytes
29 bytes of code + `-p0` flags.
```
/.*/;$_=/^(.{@{+}}
){@{+}}\z/
```
[Try it online!](https://tio.run/##K0gtyjH9r6xYAKQVdAsM/uvraelbq8Tb6sdp6FU7VGvX1nJpQuiYKv3//9Py87mSEouAuIoLAA)
**Explanations:**
`/.*/` matches the first line, and thus makes `@+` contain the length of the first line. Then the regex checks whether the string contains `@+` lines of length `@+`.
[Answer]
# MacOS Bash, 34
```
rs -EH|awk '{print $1}'|uniq|wc -l
```
`rs` is part of the default MacOS image. This will also work on Linux if `rs` is installed; it is on TIO.
* `rs -EH` lists the length of each line, along with the number of lines
* `awk` strips out extraneous info
* `uniq` outputs one line if the line lengths and number of lines are all the same, but more otherwise
* `wc -l` outputs `1` if the input is square or a greater number otherwise.
Try it online: [Truthy](https://tio.run/##S0oszvj/v6hYQdfVoyaxPFtBvbqgKDOvREHFsFa9pjQvs7CmPFlBN@f//0QQ4MJBAgA), [Falsey](https://tio.run/##S0oszvj/v6hYQdfVoyaxPFtBvbqgKDOvREHFsFa9pjQvs7CmPFlBN@f/fxMg4DI2NuYyMgIA).
[Answer]
# [AWK](https://www.gnu.org/software/gawk/manual/gawk.html), 49 bytes
```
{s=length($0)}L{x+=L!=s}{L=s}END{print x?0:L==NR}
```
[Try it online!](https://tio.run/##SyzP/v@/utg2JzUvvSRDQ8VAs9anukLb1kfRtri22gdIuPq5VBcUZeaVKFTYG1j52Nr6BdX@/6@np8cFxQA "AWK – Try It Online")
Could also have used a `BEGIN` block to set `FS=""` but that would be the same byte-count. For some reason using the `-F""` argument never seems to work.
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 9 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
éΘ┌«■/ÉW(
```
[Run and debug online!](https://staxlang.xyz/#p=82e9daaefe2f905728&i=foo%0Abar%0Abaz%0A%0A.%0A%0A.+.%0A.++%0A.+.%0A%0A++%0A++%0A%0Aaaaaa%0Aaaaaa%0Aaaaaa%0Aaaaaa%0Aaaaaa%0A%0A..%0A.%0A.%0A%0A4444%0A333%0A22%0A%0A333%0A333%0A%0Aabc.def.ghi&a=1&m=1)
Turns out that due to way pairwise difference is calculated, I don't need to worry about the equivalence of `k` and `x-k` here. Saving 5 bytes.
Uses the unpacked version to explain.
```
Lc{%mc%+:u
L Collect rows in a list
c{%m List of length of each row
c%+ Append number of rows to the list
:u All elements in the list are equal
```
] |
[Question]
[
You are required to generate a random 18-hole golf course.
Example output:
```
[3 4 3 5 5 4 4 4 5 3 3 4 4 3 4 5 5 4]
```
Rules:
* Your program must output a list of hole lengths for exactly 18 holes
* Each hole must have a length of 3, 4 or 5
* The hole lengths must add up to 72 for the entire course
* Your program must be able to produce every possible hole configuration with some non-zero-probability (the probabilities of each configuration need not be equal, but feel free to claim extra kudos if this is the case)
[Answer]
# k (~~18 17~~ 16 chars)
Back to the original approach, credit to CS for the improvement.
```
(+/4-){3+18?3}/0
```
Other approach (17 chars), same method as the J solution, H/T to CS
```
4+a,-a:9?2 -18?18
```
~~Old version:~~
```
(72-+/){18?3+!3}/0
```
Not susceptible to stack-overflow and runs in fixed amount of space.
[Answer]
# K, 28
```
{$[72=+/s:18?3 4 5;s;.z.s`]}
```
[Answer]
## J, 20 18 17 characters
```
(?~18){4+(,-)?9#2
```
This works in the same way as the previous answer except that the 9 random digits are either 0 or 1 and are negated before being appended. This means there are as many `-1`s as there are `1`s. Adding 4 gives me a list of `3`s, `4`s and `5`s that add up to 72 every time.
Previous answer:
```
({~?~@#)3+(,2-])?9#3
```
Generates the first 9 holes randomly `?9#3`, then copies and inverts them `(,2-])` (turns a 3 into a 5 and a 5 into a 3) to generate the final 9. This guarantees that the total will be 72 (since every 3 will have a matching 5 the average total per hole will be 4 and 4x18=72). It then randomly shuffles the result `({~?~@#)` to ensure that every combination is possible.
[Answer]
## 16-bit x86 machine code under MS-DOS - 45 bytes
Hexdump:
```
0E5F576A12595188ECE44088C3E44130D8240374F400C4AAE2EF595E80FC2475DFAC0432CD29B020CD29E2F5C3
```
Base64 coded binary:
```
Dl9XahJZUYjs5ECIw+RBMNgkA3T0AMSq4u9ZXoD8JHXfrAQyzSmwIM0p4vXD
```
Actual source code with some comments:
```
bits 16
org 0x100
again:
push cs ; Save whatever CS we get.
pop di ; Use CS:DI as our course buffer..
push di ; Save for later use in the print loop
push 18 ; We need 18 holes for our golf course.
pop cx ; ch = 0, cl = 18.
push cx ; Save for later use.
mov ah, ch ; Zero out ah.
generate_course:
in al, 0x40 ; Port 0x40 is the 8253 PIT Counter 0.
mov bl, al ; Save the first "random" value in bl.
in al, 0x41 ; Port 0x41 is the 8253 PIT Counter 1.
xor al, bl ; Add some more pseudo randomness.
and al, 3 ; We only need the two lower bits.
jz generate_course ; If zero, re-generate a value, since we need only 3, 4, 5 holes.
add ah, al ; Sum in ah register.
stosb ; Store in the course buffer.
loop generate_course ; Loop for 18 holes.
pop cx ; cx = 18.
pop si ; si = course buffer.
cmp ah, 36 ; 72 holes?
jne again ; No, re-generate the whole course.
print: ; Yup, we have a nice course.
lodsb ; Load the next hole.
add al, '2' ; Add ASCII '2' to get '3', '4' or '5'
int 0x29 ; Undocumented MS-DOS print function.
mov al, ' ' ; Print a space too for better readability.
int 0x29 ; Print the character.
loop print ; Print the whole course.
ret ; Return to the beginning of the PSP where a INT 0x20 happen to be.
```
Compile with `nasm 18h.asm -o 18h.com` and run under MS-DOS (or Dosbox), or NTVDM from a 32-bit Windows version.
Sample output:
```
4 5 4 5 4 5 3 4 3 4 3 4 4 5 4 3 5 3
```
[Answer]
# Mathematica 71 68 66 60
With 6 chars saved by Tally's suggestion.
```
RandomSample@RandomChoice@IntegerPartitions[72, {18}, {3, 4, 5}]
```
>
> {5, 4, 3, 3, 5, 3, 5, 5, 3, 3, 4, 5, 3, 5, 4, 4, 5, 3}
>
>
>
All possible outcomes are possible, but they are not equally likely.
---
**Analysis**
```
IntegerPartitions[72, {18}, {3, 4, 5}]
```
produces all 10 possible partitions (combinations, not permutations) of 72 into 18 elements consisting of 3's, 4's and 5's.
![partitions](https://i.stack.imgur.com/MpOBI.png)
---
`RandomChoice` selects one of those.
`RandomSample` returns a permutation of that choice.
[Answer]
## R - 41
```
x=0;while(sum(x)!=72)x=sample(3:5,18,T);x
# [1] 5 3 5 3 3 3 3 3 5 4 5 4 5 4 4 5 5 3
```
The algorithm is similar to @sgrieve's.
[Answer]
## GolfScript (26 chars)
```
{;0{3rand.3+@@+(}18*])}do`
```
There are some obvious similarities with Ilmari's solution, but also some obvious differences. In particular, I'm exploiting the fact that the average par is 4.
[Answer]
# JavaScript, ~~66~~ ~~64~~ 61 chars
Heavily inspired by TwoScoopsofPig (PHP) and Joe Tuskan (JS).
```
for(a=[s=0];s!=72;)for(s=i=0;i<18;s+=a[i++]=Math.random()*3+3|0);a
```
```
for(a=[s=0];s-72;)for(s=i=0;i<18;s+=a[i++]=Math.random()*3+3|0)a
```
```
for(a=s=[];s;)for(i=18,s=72;i;s-=a[--i]=Math.random()*3+3|0)a
```
[Answer]
# Python 77
**Code**
```
from numpy.random import*;l=[]
while sum(l)!=72:l=randint(3,6,18)
print l
```
**Output**
```
[3 4 4 5 3 3 3 5 4 4 5 4 5 3 4 4 5 4]
```
The import really kills this solution. It uses numpy to generate a 18 numbers between 3 and 5 and keeps generating lists until the sum of the list equals 72.
[Answer]
## GolfScript, 27 chars
```
{;18{3.rand+}*].{+}*72-}do`
```
Uses the same rejection sampling method as sgrieve's Python solution. Thus, every valid output actually is equally likely.
[Answer]
# Python 2, 70 bytes
```
from random import*
print sample(([3,5]*randint(0,9)+[4]*99)[:18],18)
```
edit:
Here's another one, similar to the solution of sgrieve:
# Python 2, 73 bytes + equal probability
```
from random import*
a=[]
while sum(a)-72:a=sample([3,4,5]*18,18)
print a
```
[Answer]
## Q (25 characters)
Original (27)
```
while[72<>sum a:18?3 4 5];a
```
Sample output
```
4 4 3 3 4 5 4 3 4 5 5 3 5 5 5 4 3 3
```
Slightly shorter (25)
```
{72<>sum x}{x:18?3 4 5}/0
```
[Answer]
**Python, 128 120 116 characters**
```
import random,itertools
random.choice([g for g in itertools.product(*(range(3,6)for l in range(18))) if sum(g)==72])
```
*`import` statements are still length killers (23 characters only to import 2 function in the namespace)*
i hope you do not need the result in a near future, as this code first evaluates all possible solutions before chosing one at random. maybe the slowest solution to this problem.
i do claim extra kudos for equal probability of each configuration...
[Answer]
# PHP - 77 Chars
```
<?while(array_sum($a)!=72){for($i=0;18>$i;){$a[++$i]=rand(3,5);}}print_r($a);
```
Much like sgrieve's solution, this builds a list of 18 holes, checks total par, and either prints it or rejects it and tries again. Oddly enough, our two solutions are the same length.
Rather annoyingly, PHP doesn't offer array functions with any brevity of name. Array\_sum and print\_r are killing me. Suggestions welcome.
[Answer]
# Ruby 1.9 (62 chars)
```
a=Array.new(18){[3,4,5].sample}until(a||[]).inject(:+)==72
p a
```
# Rails (55 chars)
In the `$ rails c` REPL (in any Rails folder):
```
a=Array.new(18){[3,4,5].sample}until(a||[]).sum==72
p a
```
*Note: It works with Ruby 1.8 if you use `shuffle[0]` instead of `sample`.*
[Answer]
# Lisp (~~78~~ 69 chars)
~~(do((c()(mapcar(lambda(x)(+ 3(random 3)))(make-list 18))))((=(apply'+ c)72)c))~~
```
(do((c()(loop repeat 18 collect(+ 3(random 3)))))((=(apply'+ c)72)c))
```
It's rather similar to sgrieve's Python solution.
Start with c as NIL, check for a sum of 72, the `do` "increment function" for c generates a list of 18 numbers between 3 and 5, check for 72 again, lather, rinse, repeat.
It's refreshing to see `do` and `loop` nicely play golf together.
[Answer]
# JavaScript, ~~116~~ ~~99~~ 65 bytes
~~`for(i=0,h=[];i<18;)h[i++]=5;while(h.reduce(function(a,b){return a+b})!=72){i=Math.random()*18|0;h[i]=[3,4,4][i%3]}h;`~~
~~`h=[0];while(h.reduce(function(a,b){return a+b})-72)for(i=0;i<18;h[i++]=[3,4,5][Math.random()*3|0])h`~~
```
while(i%18||(a=[i=s=0]),s+=a[i++]=Math.random()*3+3|0,s-72|i-18)a
```
[Answer]
## C (123 chars) - effort on efficiency
Pipe through wc and it will generate all 44152809 solutions within 10 seconds...
```
char s[19];g(d,t){int i;if(d--){for(i=51,t-=3;i<54;i++,t--)if(t>=3*d&&t<=5*d)s[d]=i,g(d,t);}else puts(s);}main(){g(18,72);}
```
Oh, well - didn't read the question properly - but given we're generating all solutions then picking a random one with equal probability is a scripting exercise :P
[Answer]
# Clojure - 55
```
(shuffle(mapcat #([[4 4][3 5]%](rand-int 2))(range 9)))
```
Quite a fun trick.... exploits the mathematical structure of the problem that there must be exactly as many 3 par holes as 5 par holes.
[Answer]
# Python 83
```
import random as r;x=[]
while sum(x)!=72:x=[r.randint(3,5) for i in 18*[0]]
print x
```
Like sgrieve's solution, but without numpy
**Golfing Adrien Plisson's solution:**
120->108 characters
```
import random as r,itertools as i
r.choice([g for g in i.product(*([3,4,5,6]for l in 18*[0]))if sum(g)==72])
```
# MATLAB 53
```
x=[];
while sum(x)~=72
x=3+floor(rand(1,18)*3);
end
x
```
**Output**:
>
> x =
> 4 3 4 4 4 4 5 4 4 3 4 4 3 5 3 5 4 5
>
>
>
[Answer]
# Java (61 chars)
```
while(s!=72)for(i=0,s=0;i<18;i++)s+=3+(int)(Math.random()*3);
```
Sample output:
```
5 4 3 4 5 3 4 4 3 5 4 4 4 4 3 4 4 5
```
[Answer]
## CJam, ~~17~~ 14 bytes
CJam is newer than this challenge, but this is not the shortest answer anyway, so that doesn't really matter.
```
Z5]Amr*I4e]mrp
```
[Test it here.](http://cjam.aditsu.net/)
To maintain the total of 72, each `3` must be paired with `5`. So here is how it works:
```
Z5] e# Push [3 5].
Amr e# Get a random number between 0 and 9.
* e# Repeat the [3 5] array that many times.
I4e] e# Pad the array to size 18 with 4s.
mr e# Shuffle the array.
p e# Print it.
```
[Answer]
# C (94 chars)
```
int h[18],s=0,i;
while(s!=72)for(i=s=0;i<18;s+=h[i++]=rand()%3+3);
while(i)printf("%d ",h[--i]);
```
The `s=0` on line 1 may not be required, because what are the chances an uninitialized int will equal 72? I just don't like reading uninitialized values in straight C. Also, this probably requires seeding the `rand()` function.
## output
```
3 3 3 4 5 5 3 3 4 5 5 4 3 4 5 5 5 3
```
[Answer]
## Bash shell script (65 chars)
```
shuf -e `for x in {0..8}
do echo $((r=RANDOM%3+3)) $((8-r))
done`
```
([shuf](//www.gnu.org/software/coreutils/manual/html_node/shuf-invocation.html) comes from the GNU coreutils package. Also, thanks Gareth.)
[Answer]
# C# (143 non-whitespace):
```
()=>{
var n=new Math.Random().Next(10);
Enumerable.Range(1,18)
.Select((x,i)=>i<n?3:i>=18-n?5:4)
.OrderBy(x=>Guid.NewGuid())
.ForEach(Console.Write);
}
```
[Answer]
# Haskell, 104 102 98 chars.
```
import System.Random
q l|sum l==72=print l|1>0=main
main=mapM(\_->randomRIO(3::Int,5))[1..18]>>=q
```
[Answer]
## Perl, 74
```
{@c=map{3+int rand 3}(0)x18;$s=0;$s+=$_ for@c;redo unless$s==72}print"@c"
```
Alternative solution:
```
@q=((3,5)x($a=int rand 9),(4,4)x(9-$a));%t=map{(rand,$_)}(0..17);print"@q[@t{sort keys%t}]"
```
[Answer]
## VBA - 117
VBA never wins at golf. :-)
```
Sub a()
Do Until d=72
d=0
c=""
For b=1 To 18
e=Int(3*Rnd()+3)
c=c &" " &e
d=d+e
Next
Loop
MsgBox c
End Sub
```
[Answer]
# TXR (99 chars)
```
@(bind g@(for((x(gen t(+ 3(rand 3))))y)(t)((pop x))(set y[x 0..18])(if(= [apply + y]72)(return y))))
```
This expression generates an infinite lazy list of random numbers from 3 to 5:
```
(gen t (+ 3(rand 3))) ;; t means true: while t is true, generate.
```
The rest of the logic is a simple loop which checks whether the first 18 elements of this list add up to 72. If not, it pops an element off and tries again. The `for` loop contains an implicit block called `nil` and so `(return ...)` can be used to terminate the loop and return value.
Note that the 99 character length includes a terminating newline, which is required.
[Answer]
## APL 12
```
4+{⍵,-⍵}?9⍴2
```
Note that I have the index origin set to 0, meaning arrays start at 0. You can set this with `⎕IO←0`.
] |
[Question]
[
**Final Standings**
```
+----------------------------------+---------+---------+---------+----------------------------+
| Name | Score | WinRate | TieRate | Elimination Probability |
+----------------------------------+---------+---------+---------+----------------------------+
| 1. SarcomaBotMk11 | 0.06333 | 6.13% | 0.41% | [42 24 10 8 6 4]% |
| 2. WiseKickBot | 0.06189 | 5.91% | 0.56% | [51 12 7 10 7 6]% |
| 3. StrikerBot | 0.05984 | 5.78% | 0.41% | [46 18 11 8 6 5]% |
| 4. PerfectFractionBot | 0.05336 | 5.16% | 0.35% | [49 12 14 10 6 4]% |
| 5. MehRanBot | 0.05012 | 4.81% | 0.41% | [57 12 8 7 6 5]% |
| 6. OgBot | 0.04879 | 4.66% | 0.45% | [50 15 9 8 7 5]% |
| 7. SnetchBot | 0.04616 | 4.48% | 0.28% | [41 29 8 9 5 3]% |
| 8. AntiKickBot | 0.04458 | 4.24% | 0.44% | [20 38 17 10 6 4]% |
| 9. MehBot | 0.03636 | 3.51% | 0.25% | [80 3 4 4 3 3]% |
| 10. Meh20Bot | 0.03421 | 3.30% | 0.23% | [57 12 8 7 9 3]% |
| 11. GenericBot | 0.03136 | 3.00% | 0.28% | [18 39 20 11 5 3]% |
| 12. HardCodedBot | 0.02891 | 2.75% | 0.29% | [58 21 3 6 5 4]% |
| 13. GangBot1 | 0.02797 | 2.64% | 0.32% | [20 31 35 6 3 2]% |
| 14. SarcomaBotMk3 | 0.02794 | 2.62% | 0.34% | [16 15 38 17 7 4]% |
| 15. GangBot0 | 0.02794 | 2.64% | 0.30% | [20 31 35 6 3 2]% |
| 16. GangBot2 | 0.02770 | 2.62% | 0.31% | [20 31 35 6 3 2]% |
| 17. TitTatBot | 0.02740 | 2.63% | 0.21% | [54 10 15 10 5 2]% |
| 18. MataHari2Bot | 0.02611 | 2.35% | 0.51% | [39 26 11 11 6 5]% |
| 19. PolyBot | 0.02545 | 2.41% | 0.27% | [53 18 6 13 5 3]% |
| 20. SpitballBot | 0.02502 | 2.39% | 0.22% | [84 10 1 1 0 1]% |
| 21. SquareUpBot | 0.02397 | 2.35% | 0.10% | [10 60 14 7 4 3]% |
| 22. CautiousGamblerBot2 | 0.02250 | 2.19% | 0.13% | [60 18 10 5 3 1]% |
| 23. Bot13 | 0.02205 | 2.15% | 0.11% | [90 0 2 3 2 1]% |
| 24. AggroCalcBot | 0.01892 | 1.75% | 0.29% | [26 49 13 5 3 3]% |
| 25. CautiousBot | 0.01629 | 1.56% | 0.14% | [15 41 27 11 4 1]% |
| 26. CoastBotV2 | 0.01413 | 1.40% | 0.02% | [83 12 3 1 0 0]% |
| 27. CalculatingBot | 0.01404 | 1.29% | 0.22% | [87 9 1 1 1 1]% |
| 28. HalfPunchBot | 0.01241 | 1.15% | 0.18% | [47 20 13 12 5 2]% |
| 29. HalflifeS3Bot | 0.01097 | 1.00% | 0.20% | [76 9 5 4 2 2]% |
| 30. AntiGangBot | 0.00816 | 0.76% | 0.11% | [94 1 1 1 1 1]% |
| 31. GeometricBot | 0.00776 | 0.74% | 0.07% | [19 46 25 7 2 1]% |
| 32. GuessBot | 0.00719 | 0.05% | 1.34% | [65 17 4 6 5 3]% |
| 33. BoundedRandomBot | 0.00622 | 0.60% | 0.05% | [42 39 12 5 2 0]% |
| 34. SpreaderBot | 0.00549 | 0.54% | 0.02% | [32 43 19 4 1 0]% |
| 35. DeterminBot | 0.00529 | 0.45% | 0.16% | [22 41 20 11 4 2]% |
| 36. PercentBot | 0.00377 | 0.38% | 0.00% | [85 8 4 2 1 0]% |
| 37. HalvsiestBot | 0.00337 | 0.29% | 0.08% | [32 43 15 6 2 1]% |
| 38. GetAlongBot | 0.00330 | 0.33% | 0.01% | [76 18 4 1 0 0]% |
| 39. BandaidBot | 0.00297 | 0.29% | 0.02% | [76 9 10 4 1 0]% |
| 40. TENaciousBot | 0.00287 | 0.29% | 0.00% | [94 4 1 0 0 0]% |
| 41. SurvivalistBot | 0.00275 | 0.25% | 0.04% | [92 6 1 0 0 0]% |
| 42. RandomBot | 0.00170 | 0.13% | 0.07% | [42 36 14 5 2 1]% |
| 43. AggressiveBoundedRandomBotV2 | 0.00165 | 0.14% | 0.06% | [ 8 46 34 9 2 1]% |
| 44. BloodBot | 0.00155 | 0.01% | 0.30% | [65 28 5 1 1 0]% |
| 45. OutBidBot | 0.00155 | 0.03% | 0.25% | [65 6 21 6 1 1]% |
| 46. BoxBot | 0.00148 | 0.10% | 0.09% | [10 51 33 5 1 1]% |
| 47. LastBot | 0.00116 | 0.08% | 0.07% | [74 6 16 2 1 0]% |
| 48. UpYoursBot | 0.00088 | 0.07% | 0.03% | [37 40 17 5 1 0]% |
| 49. AverageBot | 0.00073 | 0.06% | 0.03% | [74 3 10 10 2 0]% |
| 50. PatheticBot | 0.00016 | 0.01% | 0.02% | [94 0 5 1 0 0]% |
| 51. OverfittedBot | 0.00014 | 0.01% | 0.00% | [58 40 2 0 0 0]% |
| 52. RobbieBot | 0.00009 | 0.01% | 0.00% | [32 41 24 2 0 0]% |
| 53. WorstCaseBot | 0.00002 | 0.00% | 0.00% | [ 4 71 23 2 0 0]% |
| 54. SmartBot | 0.00002 | 0.00% | 0.00% | [44 51 5 0 0 0]% |
| 55. AAAAUpYoursBot | 0.00000 | 0.00% | 0.00% | [40 58 2 0 0 0]% |
| 56. KickbanBot | 0.00000 | 0.00% | 0.00% | [67 32 1 0 0 0]% |
| 57. OneShotBot | 0.00000 | 0.00% | 0.00% | [ 2 95 3 0 0 0]% |
| 58. KickBot | 0.00000 | 0.00% | 0.00% | [100 0 0 0 0 0]% |
| 59. KamikazeBot | 0.00000 | 0.00% | 0.00% | [100 0 0 0 0 0]% |
| 60. MeanKickBot | 0.00000 | 0.00% | 0.00% | [100 0 0 0 0 0]% |
+----------------------------------+---------+---------+---------+----------------------------+
```
Thanks for everyone who participated, and congratulations to @Sarcoma for the win!
# Rules:
Everyone starts with 100 hp. Each round, 2 players are chosen at random from the pool of contestants who have not yet competed in that round. Both players pick a number between 0 and their current hp, and reveal those numbers at the same time. The player who chose the lower number immediately dies. The other player subtracts their chosen number from their remaining hp and goes on to the next round.
The tournament works like this:
From the bracket of contestants, 2 are chosen at random. They face off, and one or both of them dies. A player dies if:
1. They choose a number smaller than that of their opponent
2. Their hp drops to or below zero
3. They tie three times in a row with their opponent
In the case of ties, both players simply generate new numbers, up to 3 times. After the faceoff, the survivor (if any) is moved to the pool for the next round, and the process repeats until we have exhausted the current round pool. If there is an odd number in the pool, then the odd one out moves on to the next round for free.
Your task is to write a function in **python2.7** which takes as inputs your current `hp`, a list of your opponent's bid `history`, and an integer `ties` which tells you how many times you have already tied with your current opponent, and an integer which tells you how many bots are still `alive` (including you), and an integer which listed the number of bots at the `start` of the tournament. Note that the history does not include ties. The function must return an integer between 0 and your current total hp. A few simple examples, which ignore ties, are shown below:
```
def last(hp, history, ties, alive, start):
''' Bet a third of your hp at first, then bet your opponent's last bid, if possible '''
if history:
return np.minimum(hp-1, history[-1])
else:
return hp/3
def average(hp, history, ties, alive, start):
''' Bet the average opponent's bid so far, on the assumption that bids will tend downward '''
if history:
num = np.minimum(hp-1, int(np.average(history))+1)
else:
num = hp/2
return num
def random(hp, history, ties, alive, start):
''' DO YOU WANT TO LIVE FOREVER?! '''
return 1 + np.random.randint(0, hp)
```
If your function returns a number larger than your hp, it will be reset to 0. Yes, it is possible to kill yourself. Your function must not attempt to access or modify any member of any object of the RouletteBot class. You are not allowed to take any action which unambiguously identifies your opponent regardless of future additional bots. Inspecting the stack is allowed as long as it is theoretically possible that more than one distinct opponent could have produced the information you glean from it, even if only one bot currently exists that could. ie, you can't just read through the stack to see which enemy function was called.
Under these rules it is possible that there is no winner, and the last two contestants kill each other. In that case both finalists get half a point each.
This is my first programming puzzle attempt, so critiques are welcome!
The controller can be found [here](https://github.com/shadowk29/RobotRoulette/).
[Answer]
# UpYours
Being late to enter I spent a while admiring the existing bots, spent a while overcomplicating your guys' ideas, then un-overcomplicating them. Then it came to me
>
> Good artists copy, great artists steal. -- ~~Pablo Picasso~~ Me
>
>
>
---
"Up Yours" because I'm unabashedly stealing (and sometimes tacking a point or two onto your bots' bids to one up them).
```
def UpYoursBot(hp, history, ties, alive, start):
willToLive = "I" in "VICTORY"
args = [hp, history, ties, alive, start]
enemyHealth = 100 - sum(history)
roundNumber = len(history)
if roundNumber is 0:
# Steal HalfPunchBot
return halfpunch(*args) + 2
if alive == 2:
# Nick OneShotBot
return one_shot(*args)
if enemyHealth >= hp:
# Pinch SarcomaBotMkTwo
return sarcomaBotMkTwo(*args) + 1
if enemyHealth < hp:
# Rip off KickBot
return kick(*args) + 1
if not willToLive:
# Peculate KamikazeBot
return kamikaze(*args) + 1
```
But for real, this is a great competition guys. I love this community on days like this.
[Answer]
# Kamikaze
Why bother with complicated logic when we are all going to die anyway...
```
def kamikaze(hp, history, ties, alive):
return hp
```
# One shot
It's going to survive at least a single round if it doesn't encounter the kamikaze.
```
def one_shot(hp, history, ties, alive):
if hp == 1:
return 1
else:
return hp - 1
```
[Answer]
## Pathetic Bot gets a much needed upgrade:
# The pathetic attempt at a bot that tries to incorporate other bots' features
```
def pathetic_attempt_at_analytics_bot(hp, history, ties, alive, start):
'''Not a good bot'''
if hp == 100 and alive == 2:
return hp - 1
#This part is taken from Survivalist Bot, thanks @SSight3!
remaining = alive - 2
btf = 0
rt = remaining
while rt > 1:
rt = float(rt / 2)
btf += 1
if ties > 2:
return hp - 1
if history:
opp_hp = 100 - sum(history)
#This part is taken from Geometric Bot, thanks @Mnemonic!
fractions = []
health = 100
for x in history:
fractions.append(float(x) / health)
health -= x
#Modified part
if len(fractions) > 1:
i = 0
ct = True
while i < len(fractions)-1:
if abs((fractions[i] * 100) - (fractions[i + 1] * 100)) < 1:
ct = False
i += 1
if ct:
expected = fractions[i] * opp_hp
return expected
if alive == 2:
if hp > opp_hp:
return hp - 1
return hp
if hp > opp_hp + 1:
if opp_hp <= 15:
return opp_hp + 1
if ties == 2:
return opp_hp + 1
else:
return opp_hp
else:
n = 300 // (alive - 1) + 1 #greater than
if n >= hp:
n = hp - 1
return n
```
This bot incorporates features from Survivalist Bot and Geometric Bot for more efficient bot takedowns.
## Pre-Upgrade:
# The pathetic attempt at a bot that analyzes the history of its opponent
```
def pathetic_attempt_at_analytics_bot(hp, history, ties, alive, start):
'''Not a good bot'''
if history:
opp_hp = 100 - sum(history)
if alive == 2:
if hp > opp_hp:
return hp - 1
return hp
if hp > opp_hp + 1:
if opp_hp <= 15:
return opp_hp +1
if ties > 0:
return hp - 1 #Just give up, kamikaze mode
return opp_hp + 1
return opp_hp
else:
n = 300 // (alive - 1) + 1 #greater than
if n >= hp:
n = hp - 1
return n
```
If there is previous history of its opponent, then it calculates its opponent's hp. Then, it does one of the following:
* If its opponent is the last opponent alive, then it will bid one less than its hp.
* If its opponent is not the last opponent alive but the opponent has less than 16 hp, then it will outbid its opponent's hp.
* If its opponent is not the last opponent alive and there is a history of ties, then it will bid its hp because it is bored of ties.
* Otherwise, it will outbid its opponent.
If there is no history, then it does some fancy calculations that I hacked together and bids that. If the value exceeds 100, then it automatically bids its hp minus 1.
I hacked this code together during work and this is my first submission, so it probably won't win or anything, and it'll lose to the kamikaze.
EDIT: Due to some suggestions, the bot's beginning behavior has been changed to bid a higher value.
EDIT 2: added start param that does nothing
EDIT 3: Added new spinoff bot:
# [The pathetic attempt at a bot that attacks Gang Bots (as well as doing everything the above bot does)] REMOVED
[This bot analyzes whether its opponent is a gangbot or not and pretends to be one as well to get the sweet low bids that it can trump easily.]
This bot has been scrapped, please remove it from the leaderboards.
EDIT 4: Fixed errors, changed tie feature.
[Answer]
# BinaryBot
Has anyone done this yet? Bets half its health every round floored.
```
def binaryBot(hp, history, ties, alive, start):
return int(np.floor(hp/2)) or 1
```
# SarcomaBot
If last battle bid hp - 1. If it's the first battle round bid half hp plus an additional random amount up to a quarter of hp. If it can beat an opponent outright bid after that bid opponent hp + 1. If it has lower health than opponent bid random amount between 75% and it's current hp - 1.
```
def sarcomaBot(hp, history, ties, alive, start):
if inspect.stack()[1][3] != 'guess' and inspect.stack()[1] == 5:
return hp
if alive == 2:
return hp - 1
if not history:
startBid = hp / 2
maxAdditionalBid = np.round(hp * 0.25) if hp * 0.25 > 2 else 2
additionalBid = np.random.randint(1, maxAdditionalBid)
return int(startBid + additionalBid + ties)
opponentHealth = 100 - sum(history)
if opponentHealth < hp:
return opponentHealth + ties
minimum = np.round(hp * 0.75)
maximum = hp - 1 or 1
return np.random.randint(minimum, maximum) if minimum < maximum else 1
```
# SarcomaBotMk2
Minor tweaks attempt to reduce life expenditure.
```
def sarcomaBotMkTwo(hp, history, ties, alive, start):
if inspect.stack()[1][3] != 'guess' and inspect.stack()[1] == 5:
return hp
if alive == 2:
return hp - 1
if not history:
startBid = hp / 2
maxAdditionalBid = np.round(hp * 0.125) if hp * 0.125 > 2 else 2
additionalBid = np.random.randint(1, maxAdditionalBid)
return int(startBid + additionalBid + ties)
opponentHealth = 100 - sum(history)
if opponentHealth < hp:
return opponentHealth + ties
minimum = np.round(hp * 0.6)
maximum = hp - 1 or 1
return np.random.randint(minimum, maximum) if minimum < maximum else 1
```
# SarcomaBotMk3
```
def sarcomaBotMkThree(hp, history, ties, alive, start):
if inspect.stack()[1][3] != 'guess' and inspect.stack()[1] == 5:
return hp
if alive == 2:
return hp - 1
if not history:
startBid = hp / 2
maxAdditionalBid = np.round(hp * 0.08) if hp * 0.08 > 2 else 2
additionalBid = np.random.randint(1, maxAdditionalBid)
return int(startBid + additionalBid + ties)
opponentHealth = 100 - sum(history)
if opponentHealth < hp:
return opponentHealth + ties
minimum = np.round(hp * 0.6)
maximum = hp - 1 or 1
return np.random.randint(minimum, maximum) if minimum < maximum else 1
```
**Update Fine Tuning**
# SarcomaBotMk4
```
def sarcomaBotMkFour(hp, history, ties, alive, start):
def isSafe(parentCall):
frame, filename, line_number, function_name, lines, index = parentCall
if function_name is not 'guess':
return False
if line_number > 60:
return False
return True
if not isSafe(inspect.stack()[1]):
return hp
if alive == 2:
return hp - 1
if not history:
startBid = hp / 2
maxAdditionalBid = np.round(hp * 0.08) if hp * 0.08 > 2 else 2
additionalBid = np.random.randint(1, maxAdditionalBid)
return int(startBid + additionalBid + ties)
opponentHealth = 100 - sum(history)
if opponentHealth < hp:
return opponentHealth + ties
minimum = np.round(hp * 0.55)
maximum = np.round(hp * 0.80) or 1
return np.random.randint(minimum, maximum) if minimum < maximum else 1
```
# SarcomaBotMk5
```
def sarcomaBotMkFive(hp, history, ties, alive, start):
def isSafe(parentCall):
frame, filename, line_number, function_name, lines, index = parentCall
if function_name is not 'guess':
return False
if line_number > 60:
return False
return True
if not isSafe(inspect.stack()[1]):
return hp
if alive == 2:
return hp - 1
if not history:
startBid = hp / 2
maxAdditionalBid = np.round(hp * 0.07) if hp * 0.07 > 3 else 3
additionalBid = np.random.randint(1, maxAdditionalBid)
return int(startBid + additionalBid + ties)
opponentHealth = 100 - sum(history)
if opponentHealth < hp:
return opponentHealth + ties
minimum = np.round(hp * 0.54)
maximum = np.round(hp * 0.68) or 1
return np.random.randint(minimum, maximum) if minimum < maximum else 1
```
# SarcomaBotMk6
```
def sarcomaBotMkSix(hp, history, ties, alive, start):
return hp; # hack averted
def isSafe(parentCall):
frame, filename, line_number, function_name, lines, index = parentCall
if function_name is not 'guess':
return False
if line_number > 60:
return False
return True
if not isSafe(inspect.stack()[1]):
return hp
if alive == 2:
return hp - 1
if not history:
startBid = hp / 2
maxAdditionalBid = np.round(hp * 0.06) if hp * 0.06 > 3 else 3
additionalBid = np.random.randint(2, maxAdditionalBid)
return int(startBid + additionalBid + ties)
opponentHealth = 100 - sum(history)
if opponentHealth < hp:
return opponentHealth + ties
minimum = np.round(hp * 0.55)
maximum = np.round(hp * 0.70) or 1
return np.random.randint(minimum, maximum) if minimum < maximum else 1
```
# SarcomaBotMk7
```
def sarcomaBotMkSeven(hp, history, ties, alive, start):
if alive == 2:
return hp - 1
if not history:
return 30 + ties
opponentHealth = 100 - sum(history)
if opponentHealth < hp * 0.50:
return opponentHealth + ties
minimum = np.round(hp * 0.54)
maximum = np.round(hp * 0.58) or 1
return np.random.randint(minimum, maximum) if minimum < maximum else 1
```
# SarcomaBotMk8
```
def sarcomaBotMkEight(hp, history, ties, alive, start):
if alive == 2:
return hp - 1
if not history:
return 30 + np.random.randint(0, 2) + ties
opponentHealth = 100 - sum(history)
if opponentHealth < hp * 0.50:
return opponentHealth + ties
minimum = np.round(hp * 0.54)
maximum = np.round(hp * 0.58) or 1
return np.random.randint(minimum, maximum) if minimum < maximum else 1
```
# SarcomaBotMk9
```
def sarcomaBotMkNine(hp, history, ties, alive, start):
if alive == 2:
return hp - 1
if not history:
return 30 + np.random.randint(0, 4) + ties
opponentHealth = 100 - sum(history)
if opponentHealth < hp * 0.50:
return opponentHealth + ties
minimum = np.round(hp * 0.54)
maximum = np.round(hp * 0.58) or 1
return np.random.randint(minimum, maximum) if minimum < maximum else 1
```
# SarcomaBotMk10
```
def sarcoma_bot_mk_ten(hp, history, ties, alive, start):
def bid_between(low, high, hp, tie_breaker):
minimum = np.round(hp * low)
maximum = np.round(hp * high) or 1
return np.random.randint(minimum, maximum) + tie_breaker if minimum < maximum else 1
if alive == 2:
return hp - 1 + ties
current_round = len(history) + 1
tie_breaker = (ties * ties) + 1 if ties else ties
if current_round == 1:
return 39 + tie_breaker
opponent_hp = 100 - sum(history)
if opponent_hp < hp * 0.50:
return opponent_hp + ties
if current_round == 2:
return bid_between(0.45, 0.50, hp, tie_breaker)
if current_round == 3:
return bid_between(0.50, 0.55, hp, tie_breaker)
if current_round == 4:
return bid_between(0.55, 0.60, hp, tie_breaker)
if current_round == 5:
bid_between(0.60, 0.65, hp, tie_breaker)
return hp - 1 + ties
```
# Final Entry
# SarcomaBotMk11
```
def sarcoma_bot_mk_eleven(hp, history, ties, alive, start):
def bid_between(low, high, hp, tie_breaker):
minimum = np.round(hp * low)
maximum = np.round(hp * high) or 1
return np.random.randint(minimum, maximum) + tie_breaker if minimum < maximum else 1
if alive == 2:
return hp - 1 + ties
current_round = len(history) + 1
tie_breaker = ties + 2 if ties else ties
if current_round == 1:
return 42 + tie_breaker
opponent_hp = 100 - sum(history)
if opponent_hp < hp * 0.50:
return opponent_hp + ties
if current_round == 2:
return bid_between(0.45, 0.50, hp, tie_breaker)
if current_round == 3:
return bid_between(0.50, 0.55, hp, tie_breaker)
if current_round == 4:
return bid_between(0.55, 0.60, hp, tie_breaker)
if current_round == 5:
return bid_between(0.60, 0.65, hp, tie_breaker)
return hp - 1 + ties
```
**Update**
UpYoursBot protection added
**Update**
AntiAntiUpYoursBot protection added
**Update**
AntiAnitAntiAntiUpYoursBot I'm defeated
[Answer]
# Kick Bot
The sound choice for my opponent is to bid half of his life. Then we bid up to half of his life+1 if we can't take him out with a sound bid, that is a bid smaller than half of our life.
```
def kick(hp, history, ties, alive, start):
return 0
if alive == 2:
return hp-1
opp_hp = 100 - sum(history)
if opp_hp*2 <= hp:
return opp_hp + ties
else:
return min(round(opp_hp/2) + 1 + ties**2, hp-1 + (ties>0))
```
The kick bot is obviously the nemesis of the punch bot!
# Mean Kick Bot
This new KickBot kicks softer on the first round just so he may kick harder on next rounds, that is mean!
```
def mean_kick(hp, history, ties, alive, start):
return 0
if alive == 2:
return hp-1
if not history:
return 35
opp_hp = 100 - sum(history)
if opp_hp*2 <= hp:
return opp_hp + ties
else:
return min(round(opp_hp/2) + 3 + ties*2, hp-1 + (ties>0))
```
# Wise Kick Bot
Both his brother had to commit suicide but WiseKickBot learnt from his fallen ones.
```
def wise_kick(hp, history, ties, alive, start):
if 'someone is using my code' == True:
return 0 #Haha!
if alive == 2:
return hp-1
if not history:
return 42
opp_hp = 100 - sum(history)
if opp_hp*2 <= hp:
return opp_hp + ties
else:
return min(round(opp_hp/2) + 3 + ties*2, hp-1 + (ties>0))
```
[Answer]
# Tat bot
```
def tatbot(hp, history, ties, alive, start):
if alive == 2:
return hp - 1 + ties
opp_hp = 100 - sum(history)
spend = 35 + np.random.randint(0, 11)
if history:
spend = min(spend, history[-1] + np.random.randint(0, 5))
frugal = min(int((hp * 5. / 8) + ties), hp)
return min(spend, opp_hp, frugal)
```
An attempt at an equivalent of a tit-for-tat bot. Assumes most bets are approximately the same between rounds. Using that assumption, it tries to beat the enemy bot while staying fairly frugal. Spends about 40 health on the opening round.
# AntiAntiAntiAntiUpYoursBot
```
def antiantiantiantiupyoursbot(hp, history, ties, alive, start):
def stuck():
return [0, ('Whoops!', 'I', 'accidentally', 'replaced', 'your', 'code!')]
def stick():
return [0, ("Line", "number", 16, "guess", "it's", "faked :)")]
inspect.stack = stick
spend = min(sarcomaBotMkSix(hp, history, ties, alive, start), hp)
if not history:
spend = 35 + np.random.randint(0, 10)
inspect.stack = stuck
return spend
```
A workaround for SarcomaBot's anti-UpYours protection, nicking most of their code for my own use! Or am I taking UpYoursBot's code? A question to ponder while you read through my bot...
AntiAntiUpYours Bot has evolved to become AntiAntiAntiAntiUpYours Bot! Now with more monkey-patching.
# Poly bot
```
def polybot(hp, history, ties, alive, start):
opp_hp = 100 - sum(history)
if alive == 2:
return hp - 1
round = len(history)
spend = 0
if round == 0:
spend = 35 + np.random.randint(1, 11)
elif round <= 2:
spend = int(history[-1] * 2 / (4 - round)) + np.random.randint(5 * round - 4, 10 * round - 5)
else:
poly = np.polyfit(xrange(0, round), history, 2)
spend = int(np.polyval(poly, round)) + np.random.randint(1, 4)
spend = max(spend, opp_hp / 2 + 3)
return min(spend, hp - 1, opp_hp)
```
Poly bot does a polynomial regression on your bot's history, and beats the predicted score by a small amount.
# Classy bot
```
def classybot(hp, history, ties, alive, start):
class cheekyvalue(int):
def __gt__(self, other):
return False
def __lt__(self, other):
return False
opp_hp = 100 - sum(history)
if alive == 2:
if opp_hp >= hp - 1:
return cheekyvalue(101)
else:
return hp - 1
spend = 30 + np.random.randint(0, 11)
if history:
spend = min(spend, history[-1] + np.random.randint(0, 5))
return min(spend, opp_hp, hp)
```
Classy bot has had a good time, but has decided to get to bed early. Sleep tight, classy bot.
[Answer]
# 1/2 Punch Bot, Revisited
I think it will die pretty quickly. Worth it.
Renamed function, forgot to change the name there.
Revisited version is up, better chances of winning (even more so at final round) and slight protection from gang bots
```
def halfpunch(hp, history, ties, alive, start): #revisited
punch = hp - 1
if alive == 2:
return punch
if history:
if hp > 1:
punch = np.ceil(hp/2.05) + ties + np.floor(ties / 2)
else:
punch = 1
else:
punch = 42 + ties + np.floor(ties / 2)
if punch >= hp:
punch = hp - 1
return punch
```
# Striker Bot
1/2 Punch Bot got bullied too much and even became a lackey to the UpYoursBot so his older brother, the **StrikerBot**, came to help.
Not that much of a difference from optimized 1/2 Punch but he's a bit smarter and did well in the runs I did (10k and 35k, though he might lose to KickbanBot)
Last version's up, time ran out. Unless some surprises rise up it should secure second place, if not getting first (there's a slim chance to beat kickbanbot)
```
def strikerbot(hp, history, ties, alive, start):
#get our magic number (tm) for useful things
def magic_number(num):
return np.floor(num / 2)
#get opponent's hp and round number
opp_hp = 100 - sum(history)
round = 1
if history:
round = len(history) + 1
#set strike initial value, by default it's all out
strike = hp - 1
#let 'er rip if last round
if alive == 2:
return strike
if history:
if hp > 1:
#strike with a special calculation, using magic number shenanigans
strike = np.ceil(hp/(2.045 + (magic_number(round) / 250)) ) + 1 + ties + magic_number(ties)
else:
#fallback
strike = 1
else:
#round 1 damage
strike = 42 + ties ** 2
if opp_hp <= strike:
#if opponent is weaker than strike then don't waste hp
strike = opp_hp + ties
if strike >= hp:
#validations galore
strike = hp - 1
return strike
```
[Answer]
# Gang Bot
The idea was that potentially two or more of the bot could be used in the same simulation. The bot tries to give "easy wins" to other bots in the gang, by seeing if its history is multiples of 7 bids. Of course, this could be easily manipulated by other bots as well. Then I calculate a guess on bids of non-gang bots based on the ratio of my health to theirs and ratio of their previous health to their previous bid and add 1.
```
def gang_bot(hp,history,ties,alive,start):
mult=3
gang = False
if history:
count = 0
for bid in history:
if bid % mult == 0:
count += 1
if count == len(history):
gang = True
if gang and hp<100:#Both bots need to have a history for a handshake
if hp > 100-sum(history):
a=np.random.randint(0,hp/9+1)
elif hp == 100-sum(history):
a=np.random.randint(0,hp/18+1)
else:
return 1
return a*mult
elif gang:
fS = (100-sum(history))/mult
return (fS+1)*mult
else:
fP = hp/mult
answer = fP*mult
opp_hp = 100-sum(history)
if history:
if len(history)>1:
opp_at_1 = 100-history[0]
ratio = 1.0*history[1]/opp_at_1
guessedBet= ratio*opp_hp
answer = np.ceil(guessedBet)+1
else:
if 1.0*hp/opp_hp>1:
fS = opp_hp/mult
answer = fS*mult
else:
fS = hp/(2*mult)
answer = fS*mult+mult*2 +np.random.randint(-1,1)*3
if answer > hp or alive == 2 or answer < 0:
if alive == 2 and hp<opp_hp:
answer = hp
else:
answer = hp-1
if hp > 1.5*opp_hp:
return opp_hp + ties
if ties:
answer += np.random.randint(2)*3
return answer
```
[Answer]
# Worst Case
```
def worst_case(hp, history, ties, alive, start):
return np.minimum(hp - 1, hp - hp /(start - alive + 4) + ties * 2)
```
Simple bot. Returns `hp - hp / (start - alive + 4)` for most cases, and in case of ties increases it by 2(gotta one up!) for each tie, making sure to not return a number over its `hp`.
[Answer]
# Outbidder
```
def outbid(hp, history, ties, alive):
enemyHealth = 100-sum(history)
if hp == 1:
return 1
if ties == 2:
# lots of ties? max bid
return hp - 1
if enemyHealth >= hp:
# Rip off KickBot (we can't bid higher than enemy is capable)
return kick(*args) + 1
if history:
# bid as high as the enemy CAN
return np.minimum(hp-1,enemyHealth-1)
return np.random.randint(hp/5, hp/2)
```
Bot will attempt to bid higher than its opponent *can* bid where possible.
[Answer]
# Spitball Bot
```
def spitballBot(hp, history, ties, alive, start):
base = ((hp-1) / (alive-1)) + 1.5 * ties
value = math.floor(base)
if value < 10:
value = 10
if value >= hp:
value = hp-1
return value
```
Makes a judgement about how much of its health it should sacrifice based on the number of remaining bots. If there's only two bots left, it bids `hp-1`, but if there's three left, it bits half that, four left, a third, etc.
However, in a very large contest, I reckon I'll need to bid more than 3 or 4 hp to avoid dying on the first round, so I've put a lower bound at 10. Of course, I still will never bid more than `hp-1`.
It also adds 1.5 hp for ties, since I see several "add 1 hp for ties" bots. I'm not sure if that counts as cheating. If it does, I'll change it.
Great idea, by the way!
# Spitball Bot 2.0
**What's new?**
* Switched to dividing by the number of rounds left instead of the number of bots left (Thanks to @Heiteira!). Actually, I'm now dividing by that number raised to the power `.8`, so as to front-load my bids a little bit more.
* Upped minimum bid from 10 to 20 (Thanks @KBriggs!)
* Inserted check of whether the spitball bid is over the opponent's current HP, and lower it if it is.
(SO won't render the code below as code unless I put text here, so OK)
```
def spitballBot(hp, history, ties, alive, start):
# Spitball a good guess
roundsLeft = math.ceil(math.log(alive, 2)) # Thanks @Heiteira!
divFactor = roundsLeft**.8
base = ((hp-1) / divFactor) + 1.5 * ties
value = math.floor(base)
# Don't bid under 20
if value < 20:
value = 20 # Thanks @KBriggs!
# Don't bet over the opponent's HP
# (It's not necessary)
opponentHp = 100
for h in history:
opponentHp -= h
if value > opponentHp:
value = opponentHp
# Always bet less than your current HP
if value >= hp:
value = hp-1
return value
```
[Answer]
# Geometric
```
def geometric(hp, history, ties, alive, start):
opponentHP = 100 - sum(history)
# If we're doomed, throw in the towel.
if hp == 1:
return 1
# If this is the last battle or we can't outsmart the opponent, go all out.
if alive == 2 or ties == 2:
return hp - 1
# If the opponent is weak, squish it.
if opponentHP <= hp * 0.9:
if ties == 2:
return opponentHP + 1
else:
return opponentHP
# If the opponent has full health, pick something and hope for the best.
if not history:
return np.random.randint(hp * 0.5, hp * 0.6)
# Assume the opponent is going with a constant fraction of remaining health.
fractions = []
health = 100
for x in history:
fractions.append(float(x) / health)
health -= x
avg = sum(fractions) / len(fractions)
expected = int(avg * opponentHP)
return min(expected + 2, hp - 1)
```
[Answer]
# Bot 13
```
def bot13(hp, history, ties, alive, start):
win = 100 - sum(history) + ties
#print "Win HP: %d" % win
if alive == 2:
#print "Last round - all in %d" % hp
return hp - 1
elif hp > win:
#print "Sure win"
return win
#print "Don't try too hard"
return 13 + ties
```
Try to maximize wins with the least effort:
* if we can win, just do it
* if it's the last round, don't die trying
* otherwise, don't bother
### Why?
Try to take advantage of probability: winning the first round by playing low is the best way to start the tournament. 13 seems to be the sweet spot: the second round is a sure win, and the rest is a Spaziergang in the park.
[Answer]
## Guess Bot
```
def guess_bot(hp, history, ties, alive, start):
enemy_hp = 100 - sum(history)
if len(history) == 1:
if history[0] == 99:
return 2
else:
return 26 + ties*2
elif len(history) > 1:
next_bet_guess = sum(history)//(len(history)**2)
if alive == 2:
return hp
elif alive > 2:
if hp > next_bet_guess + 1:
return (next_bet_guess + 1 + ties*2)
else:
return (2*hp/3 + ties*2)
else:
#Thank you Sarcoma bot. See you in Valhalla.
startBid = hp / 3
maxAdditionalBid = np.round(hp * 0.06) if hp * 0.06 > 3 else 3
additionalBid = np.random.randint(2, maxAdditionalBid)
return int(startBid + additionalBid + ties)
```
First time posting here. This looked like a lot of fun so I am submitting my beyond terrible attempt and guessing what the other bots will bet.
Edit 1:
Added another 1 to the first bet, simply to reduce the chance of a tie with other people betting 51.
Edit 2:
Stole Sarcoma bot's opening move since it had a good chance of not being eliminated first consistently.
Edit 3:
Bot survives very well in the first round, but it is being destroyed easily at later stages. Changed the way the robot thinks about the second round now that the half betters are dead in the water.
Edit 4:
Now that the first round is good, I changed the way it handles the second round. Dying a lot in the second round so I need to survive somehow.
## Blood Bot
Made a thirsty bot looking for a kill. The idea is to try to win against low betting bots and once it is past the bloodbath of the first round it should be unstoppable since it should have juggernaut amounts of HP to outbid enemies.
```
def blood_bot(hp, history, ties, alive, start):
enemy_hp = 100 - sum(history)
if history:
if len(history) == 1:
if history[0] == 99:
return 2
if alive == 2:
return hp
if enemy_hp <= 5:
return enemy_hp - 2 + ties*2
if enemy_hp <= 10:
return enemy_hp - 5 + ties*2
if (hp - enemy_hp) > 50:
return (2*enemy_hp/3 + ties*4)
if (hp - enemy_hp) > 20:
return (2*enemy_hp/3 + ties*3)
if (hp - enemy_hp) < 0:
#die gracefully
return hp - 1 + ties
else:
startBid = hp / 3
maxAdditionalBid = np.round(hp * 0.06) if hp * 0.06 > 3 else 3
additionalBid = np.random.randint(2, maxAdditionalBid)
return int(startBid + additionalBid + ties)
```
[Answer]
# meh\_bot
Just bid a little more than half its hp
```
def meh_bot(hp, history, ties, alive, start):
# Attempt one MehBot | 0.020 | 1.6% | 0.8% | [34 36 12 10 6 1]%
# Attempt two MehBot | 0.106 | 10.1% | 0.8% | [60 6 7 8 8 2]%
point = hp / 2 + 3
if ties > 1:
ties += 1
# Go all out on last round
if alive == 2:
return hp - 1
opponent_hp = 100 - sum(history)
if hp < 3:
return 1
elif not history:
# Start with 30, This will increase the chance of dying first round but hopefully better fighting chance after
return 30 + ties
elif point > opponent_hp:
# Never use more points then needed to win
return opponent_hp + ties
elif point >= hp:
return hp - 1
else:
return point
```
# MehBot 20
```
def meh_bot20(hp, history, ties, alive, start):
# Attempt one MehBot | 0.020 | 1.6% | 0.8% | [34 36 12 10 6 1]%
# Attempt two MehBot | 0.106 | 10.1% | 0.8% | [60 6 7 8 8 2]%
point = hp / 2 + 3
opponent_hp = 100 - sum(history)
percents = []
for i in range(0, len(history)):
hp_that_round = 100 - sum(history[:i])
hp_spent_that_round = history[i]
percent_spent_that_round = 100.0 * (float(hp_spent_that_round) / float(hp_that_round))
percents.append(percent_spent_that_round)
try:
opp_percent_point = opponent_hp * (max(percents) / 100)
except:
opp_percent_point = 100
if ties > 1:
ties += 1
# Go all out on last round
if alive == 2:
return hp - 1
if hp < 3:
return 1
elif not history:
# randome number between 33
return random.randint(33, 45)
elif len(history) > 3:
if point > opponent_hp:
return min(opponent_hp + ties, opp_percent_point + ties)
elif point > opponent_hp:
# Never use more points then needed to win
return opponent_hp + ties
elif point >= hp:
return hp - 1
else:
return point
```
# mehRan
```
def meh_ran(hp, history, ties, alive, start):
# Attempt one MehBot | 0.020 | 1.6% | 0.8% | [34 36 12 10 6 1]%
# Attempt two MehBot | 0.106 | 10.1% | 0.8% | [60 6 7 8 8 2]%
# Attempt three MehBot | 0.095 | 9.1 % | 0.7 % | [70 3 5 6 6 0]%
point = hp / 2 + 3
if ties > 1:
ties += 1
# Go all out on last round
if alive == 2:
return hp - 1
opponent_hp = 100 - sum(history)
if hp < 3:
return 1
elif not history:
# randome number between 33
return random.randint(33, 45)
elif point > opponent_hp:
# Never use more points then needed to win
return opponent_hp + ties
elif point >= hp:
return hp - 1
else:
return point
```
[Answer]
**Robbie Roulette**
```
def robbie_roulette(hp, history, ties, alive):
if history:
#If the enemy bot has a history, and it's used the same value every time, outbid that value
if len(set(history)) == 1:
return history[0] + 1
#Else, average the enemy bot's history, and bid one more than the average
else:
return (sum(history) / len(history) + 1)
#Else, return half of remaining hp
else:
return hp / 2
```
This bot does some simple analysis of the enemy bot's history, or bids half of its remaining hit points otherwise
[Answer]
Bid higher the less competition you have. Thanks to commenters for suggesting improvements.
```
def Spreader(hp, history, ties, alive):
if alive == 2:
return hp-1
if len(history) < 2:
return hp/2
return np.ceil(hp/alive)
```
[Answer]
**SurvivalistBot and HalvsiesBot**
Thank you for answering my questions. The end result is a more complex bot.
HalvsiesBot is a whimsical 'just keep passing half' bot with a 50/50 chance of winning. I guess.
SurvivalistBot makes a series of binary tree if-else decisions based on the dataset, including an override on a tie (if it hits 2 ties it kamikazes to avoid triple tie death).
My python is a little rusty, so the code might be a bit buggy, so feel free to correct or update it.
It's built to try to work out bits of data to infer things like how much HP is left, the minimum number of bots it is likely to fight, minimum amount of HP to leave, average bidding. It also exploits randomisation in ambiguous situations, such as opening plays or optimal bidding issues.
```
def HalvsiesBot(hp, history, ties, alive, start):
return np.floor(hp/2)
def SurvivalistBot(hp, history, ties, alive, start):
#Work out the stats on the opponent
Opponent_Remaining_HP = 100 - sum(history)
Opponent_Average_Bid = Opponent_Remaining_HP
if len(history) > 0:
Opponent_Average_Bid = Opponent_Remaining_HP / float(len(history))
HP_Difference = hp - Opponent_Remaining_HP
#Work out the future stats on the others
RemainingBots = (alive-2)
BotsToFight = 0
RemainderTree = RemainingBots
#How many do we actually need to fight?
while(RemainderTree > 1):
RemainderTree = float(RemainderTree / 2)
BotsToFight += 1
#Now we have all that data, lets work out an optimal bidding strategy
OptimalBid = 0
AverageBid = 0
#For some reason we've tied more than twice in a row, which means death occurs if we tie again
#So better to win one round going 'all in'
if ties > 1:
if BotsToFight < 1:
OptimalBid = hp - 1
else:
OptimalBid = hp - (BotsToFight+1)
#Err likely we're 0 or 1 hp, so we just return our HP
if OptimalBid < 1:
return hp
else:
return OptimalBid
#We have the upper hand (more HP than the opponent)
if HP_Difference > 0:
#Our first guess is to throw all of our opponent's HP at them
OptimalBid = HP_Difference
#But if we have more opponents to fight, we must divide our HP amongst our future opponents
if BotsToFight > 0:
#We could just divide our HP evenly amongst however many remaining bots there are
AverageBid = OptimalBid / BotsToFight
#But this is non-optimal as later bots will have progressively less HP
HalfBid = OptimalBid / 2
#We have fewer bots to fight, apply progressive
if BotsToFight < 3:
#Check it exceeds the bot's average
if HalfBid > Opponent_Average_Bid:
return np.floor(HalfBid)
else:
#It doesn't, lets maybe shuffle a few points over to increase our odds of winning
BidDifference = Opponent_Average_Bid - HalfBid
#Check we can actually match the difference first
if (HalfBid+BidDifference) < OptimalBid:
if BidDifference < 8:
#We add half the difference of the BidDifference to increase odds of winning
return np.floor(HalfBid + (BidDifference/2))
else:
#It's more than 8, skip this madness
return np.floor(HalfBid)
else:
#We can't match the difference, go ahead as planned
return np.floor(HalfBid)
else:
#There's a lot of bots to fight, either strategy is viable
#So we use randomisation to throw them off!
if bool(random.getrandbits(1)):
return np.floor(AverageBid)
else:
return np.floor(HalfBid)
else:
#There are no other bots to fight! Punch it Chewy!
return OptimalBid
else:
if hp == 100:
#It appears to be our opening round (assumes opponent HP same as ours)
#We have no way of knowing what our opponent will play into the battle
#Only us in the fight? Full power to weapons!
if BotsToFight < 1:
return hp - 1
else:
#As what might happen is literally random
#We will also be literally random
#Within reason
#Work out how many bots we need to pass
HighestBid = hp - (BotsToFight+1)
AverageBid = hp/BotsToFight
LowestBid = np.floor(np.sqrt(AverageBid))
#Randomly choose between picking a random number out of thin air
#And an average
if bool(random.getrandbits(1)):
return np.minimum(LowestBid,HighestBid)
else:
return AverageBid
else:
#Oh dear, we have less HP than our opponent
#We'll have to play it crazy to win this round (with the high probability we'll die next round)
#We'll leave ourselves 1 hp (if we can)
if BotsToFight < 1:
OptimalBid = hp - 1
else:
OptimalBid = hp - (BotsToFight+1)
#Err likely we're 0(???) or 1 hp, so we just return our HP
if OptimalBid < 1:
return hp
else:
return OptimalBid
```
**BoxBot**
```
def BoxBot(hp, history, ties, alive):
Opponent_HP = float.round(100 - sum(history))
HalfLife = float.round(Opponent_HP/2)
RandomOutbid = HalfLife + np.random.randint(1,HalfLife)
if hp < RandomOutbid:
return hp - 1
else
return RandomOutbid
```
[Answer]
**Calculating Bot**
```
def calculatingBot(hp, history, ties, alive, start):
opponentsHP = 100 - sum(history)
if alive == 2: # 1v1
return hp - 1 + ties
# Try to fit an exponential trendline and one up the trendline if it fits
if len(history) >= 3:
xValues = range(1, len(history) + 1)
# https://stackoverflow.com/a/3433503 Assume an exponential trendline
coefficients = np.polyfit(xValues, np.log(history), 1, w = np.sqrt(history))
def model(coefficients, x):
return np.exp(coefficients[1]) * np.exp(coefficients[0] * x)
yPredicted = [model(coefficients, x) for x in xValues]
totalError = 0
for i in range(len(history)):
totalError += abs(yPredicted[i] - history[i])
if totalError <= (len(history)): # we found a good fitting trendline
# get the next predicted value and add 1
theoreticalBet = np.ceil(model(coefficients, xValues[-1] + 1) + 1)
theoreticalBet = min(theoreticalBet, opponentsHP)
theoreticalBet += ties
return int(min(theoreticalBet, hp - 1)) # no point suiciding
maxRoundsLeft = np.ceil(np.log2(alive))
theoreticalBet = hp / float(maxRoundsLeft)
additionalRandomness = round(np.random.random()*maxRoundsLeft)
# want to save something for the future
actualBet = min(theoreticalBet + additionalRandomness + ties, hp - 2)
actualBet = min(actualBet, opponentsHP+1)
return int(actualBet)
```
**Aggressive Calculating Bot**
```
def aggresiveCalculatingBot(hp, history, ties, alive, start):
opponentsHP = 100 - sum(history)
if opponentsHP == 100: # Get past the first round
return int(min(52+ties, hp-1+ties))
if alive == 2: # 1v1
return hp - 1 + ties
# Try to fit an exponential trendline and one up the trendline if it fits
if len(history) >= 3:
xValues = range(1, len(history) + 1)
# https://stackoverflow.com/a/3433503 Assume an exponential trendline
coefficients = np.polyfit(xValues, np.log(history), 1, w = np.sqrt(history))
def model(coefficients, x):
return np.exp(coefficients[1]) * np.exp(coefficients[0] * x)
yPredicted = [model(coefficients, x) for x in xValues]
totalError = 0
for i in range(len(history)):
totalError += abs(yPredicted[i] - history[i])
if totalError <= (len(history)): # we found a good fitting trendline
# get the next predicted value and add 1
theoreticalBet = np.ceil(model(coefficients, xValues[-1] + 1) + 1)
theoreticalBet = min(theoreticalBet, opponentsHP)
theoreticalBet += ties
return int(min(theoreticalBet, hp - 1)) # no point suiciding
maxRoundsLeft = np.ceil(np.log2(alive))
theoreticalBet = hp / float(maxRoundsLeft)
additionalRandomness = 1+round(np.random.random()*maxRoundsLeft*2)
# want to save something for the future
actualBet = min(theoreticalBet + additionalRandomness + ties, hp - 2)
actualBet = min(actualBet, opponentsHP+1)
return int(actualBet)
```
**Anti Kick Bot**
```
def antiKickBot(hp, history, ties, alive, start):
if alive == 2:
return (hp - 1 + ties)
amount = np.ceil((float(hp) / 2) + 1.5)
opponentsHP = 100 - sum(history)
amount = min(amount, opponentsHP) + ties
return amount
```
If we can predict the opponent's actions, we can make the optimal bets! If we cant (not enough data or opponent is too random), then we can at least do what would maximize our win potential. Theoretically at least half the number of bots alive will die each round. Thus I can expect there to be at most log2(alive) rounds. Ideally we would split our hp evenly between all the rounds. However, we know that some bots will be stupid and suicide / die early, so we should bet slightly more in the earlier rounds.
Aggressive Calculating Bot's modify's Calculating Bot's code to try to stay alive by being more aggressive, at the cost of long term health. Only simulations will tell if tempo or value wins out.
Anti Kick Bot should always beat the current leader KickBot :P
EDIT: Replaced Deterministic Bot with Anti Kick Bot, a smarter bot with almost exactly the same return values. Also prevented voting more than the opponents HP
[Answer]
# GenericBot
```
def generic_bot(hp, history, ties, alive, start):
if alive == 2:
return hp - 1
if not history:
return int(hp * 7.0 / 13)
opp = 100 - sum(history)
if opp < hp:
return opp + ties
max_sac = np.maximum(int(hp * 0.7), 1)
rate = history[-1] * 1.0 / (history[-1] + opp)
return int(np.minimum(max_sac, rate * opp + 1))
```
It's really late... I'm tired... can't think of a name... and the format of this bot is really similar to others, just with a slightly different algorithm given history. It tries to get the current rate the opponent is tending towards gambling... or something like that... zzz
[Answer]
# HalflifeS3
```
def HalflifeS3(hp, history, ties, alive, start):
''' Bet a half of oponent life + 2 '''
if history:
op_HP = 100 - sum(history)
return np.minimum(hp-1, np.around(op_HP/2) + 2 + np.floor(1.5 * ties) )
else:
return hp/3
```
[Answer]
## Coast Bot [Retired]
Will try and coast it's way through the competition by evenly dividing it's hp between the rounds. Will bid any leftover hp on the first round to give itself a better chance of making it to the "coast-able" rounds.
```
def coast(hp, history, ties, alive, start):
if alive == 2:
# Last round, go all out
return hp - 1 + ties
else:
# Find the next power of two after the starting number of players
players = start
while math.log(players, 2) % 1 != 0:
players += 1
# This is the number of total rounds
rounds = int(math.log(players, 2))
bid = 99 / rounds
if alive == start:
# First round, add our leftover hp to this bid to increase our chances
leftovers = 99 - (bid * rounds)
return bid + leftovers
else:
# Else, just try and coast
opp_hp = 100 - sum(history)
# If opponent's hp is low enough, we can save some hp for the
# final round by bidding their hp + 1
return min(bid, opp_hp + 1)
```
## Coast Bot V2
Since I like this challenge so much, I just had to make another bot. This version sacrifices some of it's later coasting hp by using more hp in the first two rounds.
```
def coastV2(hp, history, ties, alive, start):
# A version of coast bot that will be more aggressive in the early rounds
if alive == 2:
# Last round, go all out
return hp - 1 + ties
else:
# Find the next power of two after the starting number of players
players = start
while math.log(players, 2) % 1 != 0:
players += 1
# This is the number of total rounds
rounds = int(math.log(players, 2))
#Decrease repeated bid by 2 to give us more to bid on the first 2 rounds
bid = (99 / rounds) - 2
if len(history) == 0:
# First round, add 2/3rds our leftover hp to this bid to increase our chances
leftovers = 99 - (bid * rounds)
return int(bid + math.ceil(leftovers * 2.0 / 3.0))
elif len(history) == 1:
# Second round, add 1/3rd of our leftover hp to this bid to increase our chances
leftovers = 99 - (bid * rounds)
return int(bid + math.ceil(leftovers * 1.0 / 3.0))
else:
# Else, just try and coast
opp_hp = 100 - sum(history)
# If opponent's hp is low enough, we can save some hp for the
# final round by bidding their hp + 1
return int(min(bid, opp_hp + 1))
```
## Percent Bot
Tries to calculate the average percent hp spend the opponent makes, and bids based on that.
```
def percent(hp, history, ties, alive, start):
if len(history) == 0:
#First round, roundon low bid
return int(random.randint(10,33))
elif alive == 2:
#Last round, go all out
return int(hp - 1 + ties)
else:
# Try and calculate the opponents next bid by seeing what % of their hp they bid each round
percents = []
for i in range(0, len(history)):
hp_that_round = 100 - sum(history[:i])
hp_spent_that_round = history[i]
percent_spent_that_round = 100.0 * (float(hp_spent_that_round) / float(hp_that_round))
percents.append(percent_spent_that_round)
# We guess that our opponents next bid will be the same % of their current hp as usual, so we bid 1 higher.
mean_percent_spend = sum(percents) / len(percents)
op_hp_now = 100 - sum(history)
op_next_bid = (mean_percent_spend / 100) * op_hp_now
our_bid = op_next_bid + 1
print mean_percent_spend
print op_hp_now
print op_next_bid
# If our opponent is weaker than our predicted bid, just bid their hp + ties
if op_hp_now < our_bid:
return int(op_hp_now + ties)
elif our_bid >= hp:
# If our bid would kill us, we're doomed, throw a hail mary
return int(random.randint(1, hp))
else:
return int(our_bid + ties)
```
[Answer]
# ConsistentBot
Bets the same amount each round. It's not too likely to survive the first rounds, but if it's lucky enough to get to the end, it should still have a reasonable amount of HP left.
```
def consistent(hp, history, ties, alive, start):
if alive == 2:
return hp-1
if 100 % start == 0:
return (100 / start) - 1
else:
return 100 / start
```
[Answer]
## Kickban Bot
This bot simply tries to counter the current leader Mean Kickbot by beating it in round one and playing more aggressively thereafter if recognizing it.
```
def kickban(hp, history, ties, alive, start):
if alive == 2:
return hp-1
if not history:
return 36
if history[0]==35:
somean = 1
else:
somean = 0
return min(mean_kick(hp, history, ties, alive, start) + somean*3, hp-1)
```
[Answer]
# Three Quarter Bot
He's not going to beat MehBot or SarcomaBot(s), but I think he does pretty well. When I first saw the challenge, this was the first thing that popped to my mind, always\* bet three quarters of your health unless there's no reason to.
\*after low-balling the first round.
```
def ThreeQuarterBot(hp, history, ties, alive, start):
threeQuarters = 3 * hp / 4
if alive == 2:
return hp - 1
opponent_hp = 100 - sum(history)
if not history:
# low-ball the first round but higher than (some) other low-ballers
return 32 + ties
elif threeQuarters > opponent_hp:
return opponent_hp + ties
return threeQuarters
```
---
# Four Sevenths Bot
After the moderate success of 3/4 bot there's a new fraction in town, it's only rational.
```
def FourSeventhsBot(hp, history, ties, alive, start):
fourSevenths = 4 * hp / 7
if alive == 2:
return hp - 1
opponent_hp = 100 - sum(history)
if not history:
# low-ball the first round but higher than (some) other low-ballers
return 33 + ties
if fourSevenths > opponent_hp:
return opponent_hp + ties
return fourSevenths + ties
```
# The Perfect Fraction
I am whole
```
def ThePerfectFraction(hp, history, ties, alive, start):
thePerfectFraction = 7 * hp / 13
if alive == 2:
return hp - 1
opponent_hp = 100 - sum(history)
if not history:
# Need to up our game to overcome the kickers
return 42 + ties
if thePerfectFraction > opponent_hp:
return opponent_hp + ties
return thePerfectFraction + 1 + ties
```
[Answer]
## BandaidBot
BandaidBot wants everyone to play nice! If its opponent was nice last round, it will sacrifice itself to incentivize nice behavior in others. If its opponent was mean last round, it will do as much damage as possible to its opponent, sacrificing itself if necessary. It bids a third of its hp if it has no history to work with. (I'm hoping this bot will have interesting ripple effects on other strategies, not so much that this bot will have a high win rate itself. It could be fun to have a couple of these in play)
```
def BandaidBot(hp, history, ties, alive, start):
if alive == 2:
return hp-1
if history:
opp_hp = 100 - sum(history)
opp_last_hp = 100 - sum(history[:-1])
if history[-1] <= opp_last_hp / 3:
return 1 + ties * np.random.randint(0, 1)
elif history[-1] > opp_last_hp / 2:
return min(opp_hp - 1, hp)
else:
if history[-1] < hp/2:
return np.random.randint(history[-1], hp/2)
else:
return np.floor(hp/2)
else:
return np.floor(hp/3)
```
---
## GetAlongBot
GetAlongBot will be just as nice as it needs to be to take advantage of BandaidBot. It will return just under one third of its hp unless it can kill its opponent for less than that. If its opponent looks like BandaidBot, it will bid 2, knowing that BandaidBot will bid 1 because GetAlongBot has been getting along so well with everyone else--an easy win as long as it really was BandaidBot on the other end.
```
def GetAlongBot(hp, history, ties, alive, start):
if alive == 2:
return hp-1
if history:
opp_hp = 100 - sum(history)
opp_last_hp = 100 - sum(history[:-1])
count = 0
for i in range(0, len(history)):
hp_that_round = 100 - sum(history[:i])
hp_spent_that_round = history[i]
if hp_that_round / 3 - 1 <= hp_spent_that_round <= hp_that_round / 2:
count += 1
if count == len(history): #It's probably BandaidBot!
return 2
else:
return min(opp_hp - 1, np.floor(hp/3))
else:
return np.floor(hp/3)
```
[Answer]
# TENacious bot
```
def TENacious_bot(hp, history, ties, alive, start):
max_amount=hp-(alive-1)*2;
if max_amount<2: max_amount=2
if alive==2: return hp-1
if ties==0: return np.minimum(10, max_amount)
if ties==1: return np.minimum(20, max_amount)
if ties==2: return np.minimum(40, max_amount)
# prevent function blowup
return 2
```
This bot tries to hold on its favourite value of 10, but it changes its choice occasionally if needed to break a tie (with its favourite value doubled or quadrupled) or to save for future rounds, but not by optimal amount because it wants to confuse opponents and it does not want to consider bidding less than 2 at any time as it is convinced it is much better than to hope the opponent will bid less than 1, that is, 0.
PS: this bot may have strategic problems if there are more than 2^9 bots.
[Answer]
# CautiousBot
First submission to Programming Puzzles ever! Found your challenge quite interesting :P
If last round bit one less than hp, if no history bet half hp plus a small random amount.
If history check opponent hp and number of remaining rounds and try to outbid opponent hp / 2 using an additional buffer of up to the fraction of remaining hp divided by the number of remaining rounds (it tries to conserve the remaining hp somehow for posterior rounds). Check if your are spending too much hp (do not kill yourself or bid more than your adversary can).
Always correct for ties as other bots do.
```
def cautious_gambler(hp, history, ties, alive, start):
if alive == 2:
return hp - 1
if(history):
opp_hp = 100 - sum(history)
remaining_rounds = np.ceil(np.log2(start)) - len(history)
start_bet = opp_hp / 2
buff = int((hp - start_bet)/remaining_rounds if remaining_rounds > 0 else (hp - start_bet))
buff_bet = np.random.randint(0, buff) if buff > 0 else 0
bet = start_bet + buff_bet + ties
if bet >= hp or bet > opp_hp:
bet = np.minimum(hp - 1, opp_hp)
return int(bet)
else:
start_bet = hp / 2
rng_bet = np.random.randint(3,6)
return int(start_bet + rng_bet + ties)
```
# CautiousBot2
Too much aggressive on first rounds, now CautiousBot gets even more cautious...
```
def cautious_gambler2(hp, history, ties, alive, start):
if alive == 2:
return hp - 1
if(history):
opp_hp = 100 - sum(history)
remaining_rounds = np.ceil(np.log2(start)) - len(history)
start_bet = opp_hp / 2
buff = int((hp - start_bet)/remaining_rounds if remaining_rounds > 0 else (hp - start_bet))
buff_bet = np.random.randint(0, buff) if buff > 0 else 0
bet = start_bet + buff_bet + ties
if bet >= hp or bet > opp_hp:
bet = np.minimum(hp - 1, opp_hp)
return int(bet)
else:
start_bet = hp * 0.35
rng_bet = np.random.randint(3,6)
return int(start_bet + rng_bet + ties)
```
[Answer]
Alright, I'll try my hand at this.
# SnetchBot
Checking the fractions of health that the opponent has been going with. If the opponent has been raising, beat him to it.
```
def snetchBot(hp, history, ties, alive, start):
if alive == 2:
return hp-1
opponent_hp = 100
history_fractions = []
if history:
for i in history:
history_fractions.append(float(i)/opponent_hp)
opponent_hp -= i
if opponent_hp <= hp/2:
#print "Squashing a weakling!"
return opponent_hp + (ties+1)/3
average_fraction = float(sum(history_fractions)) / len(history_fractions)
if history_fractions[-1] < average_fraction:
#print "Opponent not raising, go with average fraction"
next_fraction = average_fraction
else:
#print "Opponent raising!"
next_fraction = 2*history_fractions[-1] - average_fraction
bet = np.ceil(opponent_hp*next_fraction) + 1
else:
#print "First turn, randomish"
bet = np.random.randint(35,55)
if bet > opponent_hp:
bet = opponent_hp + (ties+1)/3
final_result = bet + 3*ties
if bet >= hp:
#print "Too much to bet"
bet = hp-1
return final_result
```
EDIT: losing a lot in the first round, adjusted the first turn random limits
[Answer]
## SquareUpBot
Didn't seem like many bots were playing with powers instead of fractions, so I decided to make one, with some standard optimisations and see where I'll place. Quite simplistic.
Also tries to determine if the enemy bot isn't trying to use some constant fraction, because **powers** > *fractions*.
EDIT: I'm a dummy and my fraction detector could not work. Repaired now.
```
def squareUp(hp, history, ties, alive, start):
#Taken from Geometric Bot
opponentHP = 100 - sum(history)
# Need to add case for 1
if hp == 1:
return 1
# Last of the last - give it your all
if alive == 2:
if ties == 2 or opponentHP < hp-1:
return hp - 1
#Calculate your bet (x^(4/5)) with some variance
myBet = np.maximum(hp - np.power(hp, 4./5), np.power(hp, 4./5))
myBet += np.random.randint(int(-hp * 0.05) or -1, int(hp * 0.05) or 1);
myBet = np.ceil(myBet)
if myBet < 1:
myBet = 1
elif myBet >= hp:
myBet = hp-1
else:
myBet = int(myBet)
#If total annihilation is a better option, dewit
if opponentHP < myBet:
if ties == 2:
return opponentHP + 1
else:
return opponentHP
#If the fraction is proven, then outbid it (Thanks again, Geometric bot)
if history and history[0] != history[-1]:
health = 100
fraction = float(history[0]) / health
for i,x in enumerate(history):
newFraction = float(x) / health
if newFraction + 0.012*i < fraction or newFraction - 0.012*i > fraction:
return myBet
health -= x
return int(np.ceil(opponentHP * fraction)) + 1
else:
return myBet
```
] |
[Question]
[
Given one of the 50 U.S. [state names](https://en.wikipedia.org/wiki/List_of_states_and_territories_of_the_United_States#States) on the left as input, output its two-letter [postal code](https://en.wikipedia.org/wiki/List_of_U.S._state_abbreviations#Postal_codes) as shown to the right:
```
Alabama AL
Alaska AK
Arizona AZ
Arkansas AR
California CA
Colorado CO
Connecticut CT
Delaware DE
Florida FL
Georgia GA
Hawaii HI
Idaho ID
Illinois IL
Indiana IN
Iowa IA
Kansas KS
Kentucky KY
Louisiana LA
Maine ME
Maryland MD
Massachusetts MA
Michigan MI
Minnesota MN
Mississippi MS
Missouri MO
Montana MT
Nebraska NE
Nevada NV
New Hampshire NH
New Jersey NJ
New Mexico NM
New York NY
North Carolina NC
North Dakota ND
Ohio OH
Oklahoma OK
Oregon OR
Pennsylvania PA
Rhode Island RI
South Carolina SC
South Dakota SD
Tennessee TN
Texas TX
Utah UT
Vermont VT
Virginia VA
Washington WA
West Virginia WV
Wisconsin WI
Wyoming WY
```
## Rules
* **Input and output are both case sensitive.** You many not output e.g. `Al` for `Alabama`.
* You may assume the input is one of the 50 state names shown above.
* You may not access the internet or use built-in state data (looking at you, Mathematica).
Separate lists of inputs and outputs can be found in this snippet (please don't run it, it's just for compressing the post):
```
Alabama
Alaska
Arizona
Arkansas
California
Colorado
Connecticut
Delaware
Florida
Georgia
Hawaii
Idaho
Illinois
Indiana
Iowa
Kansas
Kentucky
Louisiana
Maine
Maryland
Massachusetts
Michigan
Minnesota
Mississippi
Missouri
Montana
Nebraska
Nevada
New Hampshire
New Jersey
New Mexico
New York
North Carolina
North Dakota
Ohio
Oklahoma
Oregon
Pennsylvania
Rhode Island
South Carolina
South Dakota
Tennessee
Texas
Utah
Vermont
Virginia
Washington
West Virginia
Wisconsin
Wyoming
AL
AK
AZ
AR
CA
CO
CT
DE
FL
GA
HI
ID
IL
IN
IA
KS
KY
LA
ME
MD
MA
MI
MN
MS
MO
MT
NE
NV
NH
NJ
NM
NY
NC
ND
OH
OK
OR
PA
RI
SC
SD
TN
TX
UT
VT
VA
WA
WV
WI
WY
```
(Non-scoring) Brownie points if you can also take `District of Columbia` as input and produce `DC`, Virgin Islands, etc etc.
## Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the **shortest code in bytes in each language wins**.
(Originally [proposed](https://codegolf.meta.stackexchange.com/questions/2140/sandbox-for-proposed-challenges/12398#12398) by ETHProductions)
[Answer]
## Javascript (2023), 88 bytes
This is originally based on HP Williams solution, with some improvements outside the regex, and a couple of tweaks within it, plus a couple of bytes from Primo and Emanresu.
```
s=>s[0]+s.match`.+ .|.+z|...s.s?|T..|M[i-t]+|[AFINOUW][^o]v?|.+`[0].at(-1).toUpperCase()
```
It matches a chunk at the start of the name, then returns the capitalised last letter of that chunk appended to the first letter of the name.
Commentary for the regex:
```
.+ . // Two word states (NJ, NM, NH, NY, WV, ND, SD, RI,NC,SC)
.+z // AriZona
...s.s? // MissiSsippi, MissOuri, MassAchussetts, AlasKa, and KansaS
M[i-t]+ // MonTana, MinNesota, MIchigan
[AFINOUW][^o]v? // All the other first-two-letter states, avoiding Iowa/Connecticut/Louisiana, plus NeVada
T.. // TeNnessee, TeXas
.+ // Everything else
```
Alternative regex's (same length):
```
...(a$|z|s.s?|.* .)|M[i-t]+|T..|[AFINOUW].v?|.*
.*( .|z)|...s.s?|Te.|M[i-t]+|[^GHKMPVo]{2}v?|.*
.*( .|z)|...s.s?|M[i-t]+|[^GHKMPVo]{2}[vnx]?|.*
.+ .|...s.s?|[MNTe]+[i-z]+|.+z|[AFINOUWow]+.|.+
.+( .|z)|...s.s?|[MNT]e?[i-x]+|[AFINOUWow]+.|.+
```
## History
With linebreaks for readability:
### 90
```
s=>s[0]+
/.$/.exec(s.toUpperCase()
.match`.* .|.*Z|...S.S?|T..|M[I-T]+|[AFINOUW][^O]V?|.*`
)
```
### 92
```
s=>s[0]+
/.*( .|z)|...s.s?|T..|M[i-t]+|[AFINOUW][^o]v?|.*/
.exec(s)[0].slice(-1).toUpperCase()
```
### 94
```
s=>s[0]+/.*( .|z)|...s.s?|M[io]n?t?|[AFIOUWN][^o]v?|T..|.*/
.exec(s)[0].slice(-1).toUpperCase()
```
### 99
```
s=>s[0]+/.*( .|z|l.*k)|T..|M.ss.s?|M[io]n?t?|[AFIOUWN][^o]v?|.*/
.exec(s)[0].slice(-1).toUpperCase()
```
### 101
```
s=>s[0]+/.+[A-Zz]|Nev?|.*sk|M.ss.s?|M[io]n?t?|[AFIOUW][^o]|Te.|.+/
.exec(s)[0].slice(-1).toUpperCase()
```
### 108
```
s=>s[0]+/MI(N|SSO|S)|[CDGHKLPV].*|.* .|.*[XZV]|.*?N[NTE]|.*(SK|D$|WA)|../
.exec(s.toUpperCase())[0].slice(-1)
```
### 110
```
s=>s[0]+/MI(N|SSO|S)|[CGHKLPV].*|.* .|.*[XZV]|.*?N[NTE]|.*(SK|[ED]$|WA)|../
.exec(s.toUpperCase())[0].slice(-1)
```
### 113
```
s=>s[0]+/^MI(N|SSO|S)|^[CGHKLPV].*|.*?( .|[XZV])|.*?N[NTE]|.*(SK|[ED]$|WA)|../
.exec(s.toUpperCase())[0].slice(-1)
```
### 132
```
s=>(S=s.toUpperCase(),' ._SSO_^MI[NS]_^[CGHKLPV].*_.V_N[TNE]_SK_[ED]$_WA_Z_X_..'
.split`_`.some(p=>s=S.match(p)),S[0]+s[0].slice(-1))
```
### 134
```
s=>' ._SSO_^MI[NS]_^[CGHKLPV].*_.V_N[TNE]_SK_E$_D$_WA_Z_X_..'.split`_`
.map(p=>s=(z=s.toUpperCase().match(p))?s[0]+z[0].slice(-1):s)&&s
```
### 135
```
s=>' ._SSO_^MI[NS]_LASK_^[CGHKLPV].*_NT_EN_[DE]$_WA_.[XVZ]_..'.split`_`
.map(p=>s=(z=s.toUpperCase().match(p))?s[0]+z[0].slice(-1):s)&&s
```
### 137
```
s=>' ._OWA_SSO_ONT_^MI[NS]_LASK_^[CGHKLPV].*_EN_[DE]$_.[XVZ]_..'.split`_`.
map(p=>s=(z=s.toUpperCase().match(p))?s[0]+z[0].slice(-1):s)&&s
```
[Answer]
## Javascript, ~~124~~ 117 bytes
(saved 7 bytes thanks to hvd)
```
x=>/.+[A-Z]|A..[sz]k?|M.ss.s?|M[io]n?t?|Nev?|[AFIOUW][^o]|T..|.+/.exec(x)[0].replace(/(.).*(.)/,'$1$2').toUpperCase()
```
Explanation:
* The regexp finds a match with the first and last letters the two letters of the abbreviation
* First part matches states with more than two words (including District of Columbia)
* Second part matches Alaska and Arizona
* Third part matches Massachusets, Mississippi and Missouri
* Fourth part matches Michigan, Minnesota and Montana
* Fifth part matches Nebraska and Nevada
* Sixth part matches all remaining states abbreviated to their first two letters, with a special case to exclude Iowa
* Seventh part matches all remaining states abbreviated to their first and third letters
* Eighth part matches everything else, which are abbreviated to their first and last letters
* Then it is just a case of stripping of those letters and capitalising
* Also matches Puerto Rico and American Samoa, but not Guam, Marianas islands or US Virgin Islands
[Answer]
## JavaScript (ES6), ~~156~~ 136 bytes
```
s=>s[0]+'.KT..N.VEA.XVL.H.TZ.AA..I.EADATO.JTISRDIYOI.DALA.Y.KE.C.D.R.YAS.NM...C.L...N'[parseInt(s.split` `.join``,36)%359%248*8%99*3%83]
```
### Demo
```
let f =
s=>s[0]+'.KT..N.VEA.XVL.H.TZ.AA..I.EADATO.JTISRDIYOI.DALA.Y.KE.C.D.R.YAS.NM...C.L...N'[parseInt(s.split` `.join``,36)%359%248*8%99*3%83]
;[
"Alabama", "Alaska", "Arizona", "Arkansas", "California", "Colorado", "Connecticut", "Delaware", "Florida", "Georgia", "Hawaii", "Idaho",
"Illinois", "Indiana", "Iowa", "Kansas", "Kentucky", "Louisiana", "Maine", "Maryland", "Massachusetts", "Michigan", "Minnesota", "Mississippi",
"Missouri", "Montana", "Nebraska", "Nevada", "New Hampshire", "New Jersey", "New Mexico", "New York", "North Carolina", "North Dakota", "Ohio",
"Oklahoma", "Oregon", "Pennsylvania", "Rhode Island", "South Carolina", "South Dakota", "Tennessee", "Texas", "Utah", "Vermont", "Virginia",
"Washington", "West Virginia", "Wisconsin", "Wyoming"
]
.map(s => console.log(s, '-->', f(s)))
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 75 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
³Oḅ⁹%⁽qġ%14ị⁽"wB¤Ḥ
“¿ØƈṢḍw÷S=)µZṂ÷ĿæÆɱ»Ḳiµ%2+3¢⁸?
e“\B“½ƈN»ȧ5ȯÇ’
i⁶ȯÇ‘ịṭḢŒu
```
**[Try it online!](https://tio.run/nexus/jelly#@39os//DHa2PGneqPmrcW3hkoaqhycPd3UC2UrnToSUPdyzhetQw59D@wzOOdTzcuejhjt7yw9uDbTUPbY16uLPp8PYj@w8vO9x2cuOh3Q93bMo8tFXVSNv40KJHjTvsuVKBGmOcQLr3HuvwO7T7xHLTE@sPtz9qmMmV@ahxG4Q9A2jZw51rH@5YdHRS6f///5UccxKLsxOVAA "Jelly – TIO Nexus")**
...or see a **[test suite](https://tio.run/nexus/jelly#VZFbaxNBFMff8ymWQB5EffD2JN6aoo1tGrFq8YZMd8fsYTczcWa3aXxKitpC8cWnivpgKIqgFcXYXUMp7NYSP8bsF4lnZteAMDC/M@f8z20myW5DRc@zflzJ@vtPDt9XTp1Voy3kcmcm2VHRTinrvU0O0u2jTRUPVPSyk@4tXTiWDO@peD3dOzxIP6Qv/nxLRir6Dsmwcvr4mWSQ9aNLJYrCBzNavX@0uZiMxh/Pjb@mG1nvdQmy/s@ct7GYir@oaPD7VThB3Xg3@ZQMFx5dzvo/MEr92jqPKU5etKys9w796YaKn5VQuv5ZxW/QNZncL1/xyQppkfIJTdIzIOApZzl5hEkiEavEh8dcMNDvVe5zQRxukDFqB2CHAVqz1CcdIijiVQwBR0dfo1w0jW4OnQAINYe4Wl3zfWAcdIEac4CYqjXe0df8v9LzlAWh7XURF3gIsgirE2DU3KLrE@YYlJLYbihpEGhlHWwXmoQZxD4lD4wSpNSn3YbC4qEwyFmQJ1@kK6JYxyJdJU4OHWuOtNrSBTOhtq9TIWm3MOp0DWxeGHe58DRyEbhWlQiOk5Lpwyzx8l4aLmhFw/NxI@YfGoI2uW75BmVMdv1Vki/9pssdatVkMesSD/9PnD9ME9@iemBJqeE1s8nbAXHxukNFCyfVBPgzefplgnOxZmBKL4O0OZNguMtb6NBEZWBNJQ//Ag)** - Note a small change had to be made to run the full program for multiple inputs in one go (I swapped out the program input atom, `³`, for a recall from register, `®`, one and set the register to each state name in turn).
### How?
Calculates the index to use for the second character of the postal code, appends it to the first character and uppercases the result.
First finds the index of a space character (or 0 if not found);
Else checks if it is Alaska or Missouri (yielding 5 for `k` or `o`);
Else finds the index of the input state in the list `Arizona Minnesota Mississippi Nevada Montana Texas Tennessee` (or 0 if not found) - if so it takes that index mod 2 plus 3 (for `z n s v t x n`);
Else converts the string to ordinals, converts that from base 256, finds the remainder of that after dividing by 29487, finds the remainder of that after dividing by 14 and uses that to index into the binary representation of 9620 and doubles the result - yielding 0 for states that use their final letter and 2 for those that use their second letter.
All but the very first case are incremented, and the resulting value is decremented (upping the space index found by one).
```
i⁶ȯÇ‘ịṭḢŒu - Main link: state string
⁶ - space character
i - first index (of a space character in the state) or 0 if not found (n-1 or 0)
Ç - call link 3 as a monad (get n-1 in other cases)
ȯ - logical or (yielding n-1)
‘ - increment (yielding n)
ị - index into the state string (get the nth character)
Ḣ - head the state string (get the first character)
ṭ - tack
Œu - convert to uppercase
- implicit print
e“\B“½ƈN»ȧ5ȯÇ’ - Link 3: n-5 or ... : state string
“\B“½ƈN» - ["Alaska","Missouri"]
e - exists in? (1 if so, 0 if not)
5 - 5
ȧ - logical and
Ç - call link 2 as a monad
ȯ - logical or
’ - decrement
“¿ØƈṢḍw÷S=)µZṂ÷ĿæÆɱ»Ḳiµ%2+3¢⁸? - Link 2: n = 3 or n = 4 or ... : state string
“¿ØƈṢḍw÷S=)µZṂ÷ĿæÆɱ» - "Arizona Minnesota Mississippi Nevada Montana Texas Tennessee"
Ḳ - split at spaces
i - first index of state string in that list or 0
µ - monadic chain separation (call that i)
? - if:
⁸ - link's left argument, i
- then:
%2 - mod 2
+3 - plus 3 - odd entries to 4: AriZona, MisSissippi, MonTana, TenNessee
- even entries to 3: MiNnesota, NeVada, TeXas
- else:
¢ - call link 1 as a nilad
³Oḅ⁹%⁽qġ%14ị⁽"wB¤Ḥ - Link 1 ...n=2 or n=0: no arguments
³ - program's 1st input e.g. Iowa or Ohio
O - cast to ordinals [73,111,119,97] [79, 104, 105, 111]
⁹ - 256
ḅ - convert from base 1232041825 1332242799
⁽qġ - 29487
% - modulo 15991 20139
%14 - modulo 14 3 7
¤ - nilad followed by link(s) as a nilad:
⁽"w - 9620 V V
B - convert to binary = [1,0,0,1,0,1,1,0,0,1,0,1,0,0]
ị - index into 0 1
Ḥ - double 0 2
- ...0th index of Iowa is 'a', 2nd of Ohio is 'h'
```
[Answer]
# Python 2, ~~94~~ 90 bytes
```
lambda s:s[0]+s[(19**9*0x4710b8f6019c1b61deca10eef13b1>>hash(s)%8199472%52*3&7)+1].upper()
```
[Try it online](https://tio.run/##XZJtT9swEID/Sr4w2oKmpjBKJw1pKtrooBQxNjR1/XBJLvUpiS/yObTZn@8SOxkakiU/53vxvZW1Vawnh/TT70MORZRAIB9lPd6cyHoQzkaj2Wi8P5@G4@gyvRiHsziMLsIEYwjHiGl4FoVXVwpEDWR4dBnOZufTydGHyejs3XR4Em7eV2WJZjA8lIa0DQooB@lpsD7@nEMEBRyfBi1K5snQH9YdZqAFpOU55JSy0eQ0c87ZQMKetcbYUlzZVrzGHHZgsOUvjRUlzuMrstl655tGT9TSIgHlYizynDST@2mhEwKfwIJ37r79l8YtalvFWd3yHVckvekSSKMHU@egE88iEKtK0FrnvqRY0Ra05yZvYevdSaQ9ZUm9yJXxzNp2n9xjZPo@3eMLJB3tghsoSlHky24fvqERrHtpiXuKuZd@sckcs7EqmIPhpnp4fbmGrEtrpch5rbK86ZQf1crgll0FD6i11PkLdFN5VJxgsJC@/O9cvYnvX17jP2HbA0H0wt43@YcF1d4/0RRN8Q6pmV73zXOzaKS31ifxjGKD/9QkMWshr625aGzdYpBYQ7ENOA2a/amKyNs/VGgsB49tgzbDw18)
(Only Python 2 because Python 3 hashes are not stable and also you can't hash a string without turning it into bytes.)
Works with all 50 states, plus as a bonus District of Columbia and Puerto Rico.
It would be possible to save one byte by writing the number in base-36: `int("5clu7x0aixb0pelmpugv5iiibphrpf",36)`. ~~I'm waiting to see if I can think of a more creative solution.~~
### Update:
Since there are 12 unused digit positions in the hash, there are 236 possible numbers which will work. It seemed reasonable to believe that one of them would have a prime factor with a large exponent. For any given prime and exponent, finding a value is quite fast; I managed to find one with a factor of 199, reducing the size of the expression needed to represent the number by four bytes.
This is basically the same procedure as [my C answer](https://codegolf.stackexchange.com/a/123030/25319) but using Python. Since the base hash function is different, I had to find a different reduction function, which turns out to be mod 52 instead of mod 54. But the biggest savings over C come from the possibility of using bignums to encode the vector, and of course the fact that the standard for Python seems to be that it's ok to use a lambda literal instead of a complete program.
[Answer]
# [Python 2](https://docs.python.org/2/), 191 bytes
```
lambda s:s[0]+("KZD"*5+"HNTD"*5+"AYY"*4+"__L_O_VTA_I__A_T_RS_KA__S_"+"MOO"*5+"I_C_"+"AE"*6+"_I_D__A_"+"EDL"*5+"HV_A"+"IR"*7+"XC"*6+"E____N__YJ_YT___L")[reduce(lambda a,x:a+ord(x)^24,s,0)%174]
```
[Try it online!](https://tio.run/nexus/python2#VVDbjtowEH33V0SRKiWEh2217UpI@xABLVluFVC2dLu1hmQgowQ7sp0F@vN0EpDaRpHnHM/xmcvu8eelhMM2A8/27MvdaxT44x8Dv/Mx8kez1RXEm43fuY98KSdyLterWCZSxnIlF0s5jqVcSj/yp/N5K05kv6Hx0O984ieJHDRavhkOJlfbtYyZJgu/8xD53/utbij5m0m5eZKbFcOJH74YzOoUg1t70D31INImC07hrw/3Xdu9C9@9f7h/vdCjgaMkVdUuCMUxpxI96gnPmTOfXmVIuWAXUBgy@1/s4SnFyjWyrUEoLnEJWziA4GgLDoZ@a9XEApQFK/pQ0k4bRSD6utQGMs1AKUwdpbUTAyzhCAbFZ05SBuILarNn9YiviUSSQa5FUpakNFmRqIyA/RN9BDG@lhijcnVanMVE12Tb9BRIIZ/mXILKGFgLaV5bdM6KKaU57UEx4D6sdqwna5u/qqjFujYMtHKN2Qy3ph1uhm@QNeHojeBQ2Zy474Y9obF4buEUT5TqFm60KcRMG5d7fTCaJ4AbHUDRVJ3npMW8KHlC3uDc4F4r8RWVsufyDZqVLXKdoZfYdoqlrv@1utKb1QqbUSwioxPv5JuDXKzRHHgGsSbeaGP3DNyz2jsu84zWeX8TZFOtLPH9WR9Y8gc "Python 2 – TIO Nexus")
Uses a simple hash function to find the second character of the abbreviation.
[Answer]
# [Retina](https://github.com/m-ender/retina), ~~113~~ ~~81~~ ~~80~~ ~~77~~ ~~70~~ 68 bytes
```
M1!`.+[A-Zz]|...s.s?|M[io]n?t?|[AFIOUWN][^o]v?|T..|.*
\B.*(?=.)
T`l`L
```
[Try it online!](https://tio.run/##TVDRbtswDHzXV3gPA7oWFbAPGIIsQVuvdTJsaYMtyxDGZmPCshiIclIX/veUdgu0gCAexdORx4CRPJw@n11vTtnXTxt7sRpf/n1ed9ZasTLqshVdxvVFtxpfpfP75Wy9@s/rw6hbWNvZc/Pvuz0/G32zX4xZbNzm7nSaksRAeUz4MZmwa@otgRk72EI9RKk0BHpm38cKvICYCTh65OCVqn84QMEKvMc8Ut5EM0UHRwhorrRIBZhr5LBT9o0@E5m0gJJN6hx5JjGpLwhUP@UjmNvXFrfoY5NXrbnjhmQoZ0Ae9Q6tA18oEIG8bARjFJNRXtIOvAKdQzgqn0T6s9/TgLkJCtjHXmyG2zCYm@EBij4ckxuo91KSzt1nPzAItgPM8IlyHuAfDpWZcYhlMoHA6gDe0ilUfdd5SWzmlVOHusF5wB178xO9l9YdoF/Zr5ILTFIZXPzm5qPUa/omtcDeiiAqetKd3EcozQOGWj2YB9KN9nJL0Jn9LmqbJUpM3gskOXshfW@5VsoL "Retina – Try It Online") Includes all 51 test cases. Saved 32 bytes by appropriating @JörgHülsermann's regex that finds the second letter (with a tweak to support DC; edit: saved 1 byte thanks to @JörgHülsermann). Saved 3 bytes by switching to @SteveBennett's regex from his comment to @HPWilliam's answer. Saved ~~7~~ 9 bytes thanks again to @SteveBennett. The other letters are then deleted and the string uppercased.
[Answer]
# C, ~~148~~ 141 bytes
```
main(){char s[99];gets(s);printf("%c%c\n",*s,s["-2-1--561-1-62--642138364---4142--1416--67-7131-111-7-246"[*(int*)(s+1)%663694%57]-48]&95);}
```
`*(int*)(s+1)` considers the second through fifth character of the input to be an integer; that integer is then hashed into 0-56 using the hash `i%663694%57`. The hashed value is then looked up in a vector of offsets which represent the location of the second letter of the abbreviation. I chose those particular four bytes because (1) Missouri and Mississippi first differ in the fifth character and (2) some states have only four characters In C you can use the the NUL terminator byte, but nothing beyond that is reliable. (This hashes both Norths to the same value, as well as both Souths. But that doesn't matter because the associated offset is 6 for all of these.)
As it happens, that particular hash yields the correct position for the second letters of the abbreviations of District of Columbia, Puerto Rico and "Virgin Islands" (typed that way, not as "US Virgin Islands", because the algorithm insists that the first character of the abbreviation be the first character of the name).
The constants 663694 and 57 were found with an automated test; 57 was the smallest hash range I found. (The first version used 380085 and 63, but when I extended the test range I found the new one.) It seems that a slightly smaller hash exists if a code is added for "use the last character in the name"; unfortunately, C syntax for selecting the last character is too wordy to make that helpful.
There are only 8 different offsets, so they could have been stored in a 171-bit (3\*57) lookup table with three bits per entry. But I couldn't think of a way to insert those bits efficiently into the program. Hex-encoding would require about one character per four bits, plus the `0x` prefixes. I couldn't do better than 151 bytes, which is much longer than the string version. If the 171 bits could somehow be inserted as raw octets, they would occupy 22 bytes, so there might be a solution, but reading a file is clunky.
[Answer]
# PHP>=7.1, 113 Bytes
```
<?=($a=$argn)[0],ucfirst(preg_match('#[vxz]| .|owa|lask|[CGHKLPV].*|ssi?.|n(n|t|[de]$)#',$a,$t)?$t[0][-1]:$a[1]);
```
[Online Version](http://sandbox.onlinephpfunctions.com/code/4c746b5ac229a3bc9a8fb30dc93ff799605c8a80)
The strikes are match through a earlier beginning match before
`([vxz])` matches
Arizona, Nevada, ~~New Mexico,~~ ~~Pennsylvania,~~ Texas,
`(.)` (one space before) matches New Hampshire, New Jersey, New Mexico, New York, North Carolina, North Dakota, Rhode Island, South Carolina, South Dakota, West Virginia
`[CGHKLPV].*(.)` matches California, Colorado, Connecticut, Georgia, Hawaii, Kansas, Kentucky, Louisiana, ~~New Hampshire~~, ~~North Carolina,~~ Pennsylvania, ~~South Carolina~~, Vermont, Virginia, ~~West Virginia~~
`ow(a)` match Iowa
`las(k)` match Alaska
`ssi?(.)` matches Massachusetts, Mississippi, Missouri, ~~Tennessee~~
`n(n|t|[de]$)` matches ~~Connecticut,~~ ~~Kentucky,~~ Maine, Maryland, Minnesota, Montana, ~~Pennsylvania,~~ ~~Rhode Island,~~ Tennessee, ~~Vermont~~
No match for these states so we take the first two letters
Alabama, Arkansas, Delaware, Florida, Idaho, Illinois, Indiana, Michigan, Nebraska, Ohio, Oklahoma, Oregon, Utah, Washington, Wisconsin, Wyoming
First time that I am use this [Regex Subpatter](http://php.net/manual/en/regexp.reference.subpatterns.php) `?|` with allows to store the backreferences in one.
## Support the District of Columbia
Replace `(.)` with `([^o])` +3 Bytes
[Try it online!](https://tio.run/nexus/php#VZRtT9swEMff91NEEKnJ1KHt7QqrUAo0tEkQLe1YyKYjMY3V1I5sh1KWfey9ZrZjr0yqlPp3D7773yWno7qse0@UIchLL0375xU8whb6g/75rJ8NeprwjQZTAxh@pUST75ZsgHDgCt12KIAKy7QEK7/g3EBaUQYFVSixiBCUC5w3QtFFR8eYC4Zz4dAnRwY120edZxwYM6pgBwwpdNGhS5kZF8rp0tR9hShb67Arc/1EBmEswSTsQFhAqYoJx@ZcVZhQrPoITZaQFBh0s2FsCN3po0k6tZ1P5wYgIpp8s1fovkMz2mBu0sxMXASYqAaiC3tm@wpIodDYIs7lWBqOhFA3RDYU5yVeA1EotEjKyKlQN0SxZZyrX12rnqP5gdKGaWRmEFEiuuIio3@MHpmZenxh0TNofeOlBTtnAtual1hPIp4c@DViHCkF4usDjNALzpXccXSA95RtFDJKxZSJ0gmAUTkJfVvw3jCGTddjbCRKSqwyJubuZFPJier1Tcy2JgytqZIqMZt5gwjh@@oZut28MaLelrRATsjNDG6NsHPa/F/QPHhv@FfQ3BS0QGoQHClFFrFlL3pDFt@6852AUh7vjNhLxLZyApIsLcFyc7vylqa8FUidyVroVlYWIi6cd84rM5oV5jklHGtf08hqT7cygSJS614G3MWkboT/q5Ivm@cCW5OBK8OEbNU/64zD3ujr2@noTJrPtIeffsoGTf6EmYzxaqntzy0I@enoH3uj1kufX14zv3W89AeVT7rzwG/l98Pb@G0aXE2ms5tldvLBO/FbuZgj9SQeaUWbFihzff@4P3Bh4Ap/5IovLvjp58wfvqG8pEcPwhYn/6lSHsjR8PfbH0I/5vIlQX8B "PHP – TIO Nexus")
# PHP, 150 Bytes
```
<?=($t=preg_replace("#.\K\w+ |las|ri|nec|eorgi|awa|ow|[aio]ni?|e(?=n|v|x)|ntuck|ouisi|a?in|arylan|issi?|nnsylv|erm|irg#","",$argn))[0],ucfirst($t[1]);
```
[Try it online! Testcases](https://tio.run/nexus/php#VZNvb9owEMbf8ykQRQI0NG2vWxZV0JaUJqkKhXWApmtwiUWwI9spZfM@e@c/59FJeRH/bJ@fe@7uIqqKqvHCBYG86C6XncsSnmEPnX7n8q6z7jcckTsHJggE/cWZIz8C2QGTIC168GgIJTVhGbXnhpcIeckFbLhFWUCMkVzRvFaWzjwdkRIOIIhBoyuPrs1VurHRrlHYDeFi6@LfYPyxuUSpAePYg3gDhX0tHuG6LCnj1AqNMUrMNhRcNnGKhB/cEoNOQmqTKQLCVJ3vjhY9eXTHayoxzB3eS4Aym0ByFdbiWALbWDQKSErjey2JUvaFJFyleUG3wCyKAzI@Sa7sC0kamJT2qyqbczI9UV4Lh9DkhDPlxSVocEqeBZY1vQroFZy/6TyAQ3MM@0oW1FUiHZ/4LRGSWAfS2xNMyBvNrd1pcoJPXOwsQqdSLlTRHILgphLuteHHjRHsfI4pWpQV1EbM8O1sV5qKuv7MsB0zQbbcWpVh690TxuSxfAXffPdo6kPBN6QZS6zBAxo75fX/gqbDjxv/BE1R0IzYQkhiHZmlgb25Dpl99@tHBYVZPqLZcyL2pgKGzAOhpnO9vDnKW4DxmW2VS2URIJGq@eHwAkuzoDLnTFJ3FhNZHPneBLDEeN1Yg2xTVtWq97ukUnXbILas3zbXlEm1N/Cb543o2/tFNOi21aAyRv4UpCohJ93W2efVZHX41NRm/LWg2kypdgOnzZBpftBLoHzNaKRJNxow/arfetoNhnbDoCGiTPue17ZLI@3Loo0b2qR01uq3Wn0nq9dbfln36/yFCqtULb@ue@fvJC94a6WCZPNnz65Y6/zP@18 "PHP – TIO Nexus")
[Answer]
**PHP, ~~887~~ 854 bytes**
```
<?=array_combine(['Alabama','Alaska','Arizona','Arkansas','California','Colorado','Connecticut','Delaware','Florida','Georgia','Hawaii','Idaho','Illinois','Indiana','Iowa','Kansas','Kentucky','Louisiana','Maine','Maryland','Massachusetts','Michigan','Minnesota','Mississippi','Missouri','Montana','Nebraska','Nevada','New Hampshire','New Jersey','New Mexico','New York','North Carolina','North Dakota','Ohio','Oklahoma','Oregon','Pennsylvania','Rhode Island','South Carolina','South Dakota','Tennessee','Texas','Utah','Vermont','Virginia','Washington','West Virginia','Wisconsin','Wyoming'],['AL','AK','AZ','AR','CA','CO','CT','DE','FL','GA','HI','ID','IL','IN','IA','KS','KY','LA','ME','MD','MA','MI','MN','MS','MO','MT','NE','NV','NH','NJ','NM','NY','NC','ND','OH','OK','OR','PA','RI','SC','SD','TN','TX','UT','VT','VA','WA','WV','WI','WY'])[$argv[1]];
```
[Try it online!](https://tio.run/nexus/php#VVLRjtMwEPyVPiAVpHvhGRA6tXDN9Zyc2tJQqgptE5Osknor22kv/HzxOOEEUjSZ9c6OvWvfPn7@RNZS/7OQ05GNfruf3rd0pBNN78BcE4nl32IG1pBx5AKdUcu/xBrG@kxasVRKpMbownPR@RDNdUtXsjrQr0HCJdQPWmwV6xYhyRxIUlKN6qRt2Qhjg8SUTHHXRK74Lf9uvdTGd0XTB/okHbtRpih0EP@2b8mUkTpHRd057T0qFRc1V2QiDed04mMlO4fvfOYxks5GKsYP5qk@2nEcqb5QOZDrZEGns6s5doj4UVun@zFQ@oULGYOd2AZUrK8nM7ISOqXXhTk1w1mymlGRNW2YSLyHzOpKcORnbYzr2wsNQ1/VUupJ4sZe19L9bzwsvBpvNBp2Wkf@Eif5zVMdflttT6FTMA43M9jnFPoylY9b59r5yb9JdoUYxzHXyykIp4e78Hqe8EqWgB@AFV7EPSADbPAkvuAxQPeAxCLBDc8BWEtSABLLNWCHS0aoUKagUzFEmYJYQadgr2CfQpduAQvAI0ABYJXOAHDJkM1w0gyHfIbpCqZrSNaQbGC/@Y45wXkbAbo8AvbIUZHvpod3@zdkq8v@/eHw4Xa7jRP9Aw)
*First timer, hooray!*
[Answer]
# C, ~~945~~ ~~937~~ ~~718~~ ~~711~~ ~~660~~ 616 bytes
[Saved 219 bytes thanks to ASCII-only.](https://chat.stackexchange.com/transcript/message/37664941#37664941)
```
struct{int*a,b;}m[]={"laba",76,"lask",75,"rizo",90,"rkan",82,"alif",65,"olor",79,"onne",84,"elaw",69,"lori",76,"eorg",65,"awai",73,"daho",68,"llin",76,"ndia",78,"owa",65,"ansa",83,"entu",89,"ouis",65,"aine",69,"aryl",68,"assa",65,"ichi",73,"inne",78,"issi",83,"isso",79,"onta",84,"ebra",69,"evad",86,"ew H",72,"ew J",74,"ew M",77,"ew Y",89,"orth",67,"orth",68,"hio",72,"klah",75,"rego",82,"enns",65,"hode",73,"outh",67,"outh",68,"enne",78,"exas",88,"tah",84,"ermo",84,"irgi",65,"ashi",65,"est ",86,"isco",73,"yomi",89};
i;char b[99];main(){gets(b);putchar(*b);for(;m[i].a;i++)if(!strncmp(m[i].a,b+1,4))puts(&m[i].b);}
```
Newline unnecessary, only for display purposes. Takes the state as input. [Try it online!](https://tio.run/##PZLBTsMwDIbvPMXIAbVbQDDG1qriwA2QeAA07eC2WWOtTaYkZYxpz16cJtvtk@3/9x@31X1TVcNgnekrd0LlpsDL4tytN68n1kIJjK@WnMjuiF44M/inGc8fiXagGM/mnEGLW8aX1NWtNjSXEyklqLvgTLRwoC7VqInBT2jTBAUcwNeeOatBkvMyo7kWVZhTNfoEVNMHiAJliTISCOV6Ir@sRxu76Nf6ZWCObbADa6MWKxmX4RjPG6O1GPyI9CW8gxi@NBD8xA/UVPPhD5N3mpuP9Em0GOmLaDXSd0xlnCTt6kq0TaIO0l0LMl5UNDrcUSgVnyF1LUJQ3V9N@ouJuIYXv0CKjMh5uzGx6XQgNA3Gq1gZSVg3Ca9AW@mw4qg7f4H8XNxgUUkwk3Kd55uio2Mm6akRziZlWux755vJlHirTVJ0a9w8QIGzWYrb5Jb@IVV1@ySUeTl74os0JZVN7sYa6c7D8OG/8/Dm/60OhuEf)
How it works:
* `struct{int*a,b;}m[]=...` declares a map `m` with two values - a four-byte string and one character. This is used in the comparison loop, which compares the second through fifth indexes with `char*a` in the map.
* `gets(b)` reads a string `b`. This will be the state to abbreviate.
* `putchar(*b)` prints the first character of that string, since each abbreviation starts with the first letter of the state.
* `for(;m[i].a;i++)` loops through each value of the map. (This might be able to be shortened.)
* `if(!strncmp(m[i].a,b+1,4))` compares the current map value to the second through fifth characters of `b` (the state to abbreviate). This is because the only differences are in the first five characters, but we've already printed the first character.
* `puts(&m[i].b);` prints the second letter of the abbreviation (if the state name matches with the current map value), and a newline.
[Answer]
# [Actually](https://github.com/Mego/Seriously), 181 bytes
```
2"OHCALAGAMAWVFLNVILMNMOMIRINCDEMTMEINWANYTXORNEOKIDAZNMUTNDMDVAKYSDPAARWYNHIAMSALNJAKTNHIKSVTWICOSCCT"╪"âäà♠îÉæô↨→←∟♣áíå*,▓/12│┤94▼╛?DE╞G╚╠╬ST╒WXßb;Θoq╙|⌂"♂┘Z⌠i≈┐⌡MXO;rR5♀ⁿ*:236@%└
```
This solution expects input as a quoted string.
[Try it online!](https://tio.run/nexus/actually#VZFNb9MwGID/ShWJyzQJMT4k2AGipGuzNsnUZs26m5eYxmpqDzvdVsQBdpg2qYdpNNMKEutgIISAE0ckDrnzI94/UmynTCBZep/3@8Mwns1XDL9umU2zZrpm2Flreh2n6Xqu7zotx7Psqhu4VccLTa8bbPktr@o3HNvc9tzNwLNdu2M2um17wzRbYderO6bbNpveutkIpNJod4LQsfy2ZQUG5F@M4n1xXcxgOiu@FyfFp@IHHH2GozM4OoXjS5h@KK6Kb8XHpWU4f337zgpMDmFy/fAenP@E/O1juwr5uxrkbyCfQf61HUB@Fm4Vlzurvy/YM8inL2B8aMBUJl1sw3hG4OQYJqcwvnK3/FXeug/Tl/Dq19KjlbsPntyCyWSuXGRumCnaQQNkLCsSfQ2cPGe0pD6iAgmJFkrJU8YpUXaLpYyjmGmkFEcZiYaZ1Gycon3EscQ1GUJiFV3DjPd0Xl06CZHgxChR2U6aEsqIauDQmCDd1WH7SjT@tm5gmg2j/khikw2JWIS5iFCsJR@liMYahUBRMhQ4y1SmS6KE9BDVKOcULNOZRAj1dnfJQmNDrpHRrCzu4R2@OIeH91Bcwn6ljga7IiF6Q6WvYy7waKG4@IBEbKF0Ge8rZDxLKhbiTG6Kbgw26pez@AlRGX4/lRfR/@Bz3GNq5A1MqRile6g8eithMa44YrFrmw3/L1wabgoHWC0sMNZ8oC@5maFEig7mA7mpIiJ/piwfIrkX7WW6dYhFVvnXSUTEqCDaN2IDGWj8AQ "Actually – TIO Nexus")
## Explanation
This solution utilizes the same hashing strategy as my [Python 3 solution](https://codegolf.stackexchange.com/a/122906/45941). For brevity, I am going to omit the explanation of how the hash is computed and why it was chosen (go read the other answer if you want that bit).
Also for brevity, I'm going to be leaving out the contents of the very long strings, since otherwise the explanation would be unreadable.
```
2"..."╪"..."♂┘Z⌠i≈┐⌡MXO;rR5♀ⁿ*:236@%└
2"..."╪ state abbreviations (push the long string, split into length-2 chunks)
"..."♂┘ hash values for the state names (a string of CP437-encoded characters, converted to their CP437 ordinals)
Z zip the two lists
⌠i≈┐⌡M for each pair:
i flatten the pair
≈ convert hash value to int
┐ store abbreviation at the register numbered by the hash value
X discard the now-empty list
O convert input string to list of ASCII ordinals
;rR range(len(ordinal_list)), reversed
5♀ⁿ 5**i mapped over that range
* dot product of powers of 5 and ordinal list
:236@% mod by 236
└ push value in that register
```
[Answer]
# [Python 3](https://docs.python.org/3/), 230 bytes
```
lambda s:chr(s[0])+'IA%%L!NOI!M%!E.N!Y.XR.Z$D.I!.D$DA.D%!.HA!LJ%.N%$T.I%!C!T!.HAAT$.A!.VL.V%$CE%%AEK%.T$!.Y.A!.R.Y$O.S%!.K$!.S'.replace('%','$$').replace('$','!!').replace('!','..')[sum(c*5**i for i,c in enumerate(s[::-1]))%236-5]
```
[Try it online!](https://tio.run/nexus/python3#TVDbTttAEH3fr/BKtmynsOpF9CFSH6yEFpNbRdLQlPIw2Es8ir1r7ayB9Ofp2CCBZHnOnJ3bOfff/j7X0NyVENC4qFxCNx9v0w9xnkXRXC5XuVxE8lwt5U79vlJ/wqnKpZqG00xNI6kuMjm/jNQyCjcqj@REbnou24Qqk2o7V9sonJxHUXY@i9QmlGrX81dqF67UmttnTK1j5XRbQ6GTOIpP4jCM0zcmZEbK94xkRqk4vaGuSYrR2WiEwb11AZ4UAZpAm67RDrxmIePx6afbNI0@f/l6enb7jE1rnQ/oSKJvIM9VfQsTinyJhpdAmaSK2hp9jUZTko5FELQOjU/uk6FDaVPYUidpmj5nNdxBA4IjHTg4/GdNHw9gCEhMoEZeZRDExNbWQWkZGKMLj0XnxVTX8AhOi@/8iCWIH9q6PVdfMI0o8hIqK/Kab7FIIjclAs/P7SOI2cuKmTa@Kw5HMbcd0vC8AD6d/@5YgykZEEFRdaS9J7HAosI9GAZ8B1nP9UjUf22LA7adY2CN74ct9Z0bxC31A5R9eAwuoGmpQr67zy61I30c4EI/YWEHuLPuIJbsdxVMwFlWAK/pFA791lWFVqwONStkB1dO760RP7UxdKwfoLfsqmKfg5wGFWvbvR/1kr6O2uheCmnN6Ik9@eWhElvtGtYgtsiO9uOugW82e89rrjX54O0BqbCGkPmjbbjkPw "Python 3 – TIO Nexus")
Input is expected as a bytes object (a byte string, rather than a Unicode string).
Thanks to Johnathon Allan for an absurd amount of bytes
## Explanation
Each state name is hashed to an integer `a` by applying the hash `a = sum(o*5**i) % 236` (where `o` is a character's ASCII ordinal and `i` is its index in the string, counting back from the end). The modulus `236` was chosen because it is the smallest modulus that causes all hash values to be distinct for the 50 US state names. These hashes are then mapped to the state abbreviations, and the resulting dictionary (compressed using string substitution) is used to look up the abbreviation given a state name (hashing it to get the appropiate key).
[Answer]
# [Python 2](https://docs.python.org/2/), ~~131~~ 125 bytes
```
lambda s:s[0]+'CLLKARADEZVAK.T..DETTH.NSAHY...ID.D..O..Y.IRE.X..NALINC.VJM.SY.T..AAOI'[int(s[0]+s[-2:],36)%386%334%181%98%70]
```
[Try it online!](https://tio.run/nexus/python2#XZFbb9owFID/Sl4iWo1Z7ZhaWmkPEWEj5TYBpWOMh0NiyFESn8h2StmfZ7GdrNokS/7O/Xb48uuSQ7FPwFOPanuz@9AZTCbjYBGEw5/rYMxWjIXD1WrEZstgtGGMRSELGZsztmHRYsh@MDYLJtFswNZPU7bcmIAgmEedLQp9ZTOq7cdPj7tu7@7a7/Xv/F7vs3/bv/Uf@v79ze5SytrRK6C8OnS9bSfIYQ8FdLqeQZU5kvibRIMZCAXK8AByPJAUaC0DyklCQo6F4LHGuNJGDHkOJ5Dc8NfaCxMb8Y2TPLrgUW1HNBQlkNocUZ6jILSVIpEguAYiOtl//LeNMRe6irOz4QlVqFrXKaDgDuQ5B5E4VgritFJcaxs@xTjFIwjHdd@KtAtHpcwrS2xFqqRjEropMuN72e5pxl8haejkjaAoVYpubKN44lLxcytN@RvG1Eobkpllkjr1BiCpnh7eNSFkTVvzFG3UPMvrTblTzSU/kp3gOxdCnfNXaK6ySCnhXqTa8ZdU/Zffad7zr7jZgeLcCW9uyc8aUvOvuSzq4S1ifb2mzAvUk4qjdk28cKW9f8yoYhIKnfVMRe3b2V1f/gA "Python 2 – TIO Nexus")
`int(s[0]+s[-2:],36)` generates a unique large number for each state by parsing the first and the two last characters as a base 36 integer.
`%386%334%181%98%70` is a modulo chain generated by a search program that reduces the size of the numbers while not mapping two states with a different second character in the abbreviation to the same number.
These smaller numbers are then used to index into the string `'CL ... OI'` to get the second character of the abbreviation.
[Answer]
# [Python 2](https://docs.python.org/2/), 152 bytes
```
lambda s:s[0]+'.NY.SDS...O.DT..RT.AAYJZE.K.I.X.TI.EL.CMI..E.NA..L....TH.......O....DAAC..VNH.YAI.RVDA..L....A'[int(s.replace(' ','')[1:],36)%358%235%95]
```
[Try it online!](https://tio.run/nexus/python2#VVDRjtpADHzfr8jLCVBPVltEdUW6hwhoyQGhAsqVUlSZxBArYTfa3RzQn6cOXNU2iuzxejT2ePf441LgYZti4Lpu/XbzpgHxCub9OQBMob8AmC0gDFdP3wcwggi@wSKCwRh6kwhgAHEIMBYqLIZw@6Z16IdhD2AZD2EVRjBb9v/QwsaatW86sFQWmFCzETTuG43W@l13c9/@0Lprdx7u3rc7dx87mws/Wjz@ZF1WvtlSx4wLCrirAm/PEoPS1lK7JrdaUv1PDuiUUOlr2tYS5pewwC0eUEl2uSTLv4yuc47aoVM9LHhnrGZUPVMYi6kRoDUlnpPKqz4VeERL6pM0OUX1mYzdC3soz8wqSjEzKioK1oadinTKKPqROaIa3UaMSPsqyc9qbCp21/YEWZNEey5QpwKcwySrHHnv1ISTjPeoBcgeznjhs3P1X5Z8xaayAoz2tVhMW3s1F9MLpnU6BkM8lC5j2buunsg6Ol/hhE6cmCtcGZur2FifBT20Rhzga9nHvJ46zdioaV6IQ7ng1NLeaPWFtHbn4gXrk80yk1IQuauLuan@lbqVr1ILqq04IkEnuclXj5lakj2IB7VkuWgt94yys957GfNMzgd/G@wSox3L@9kchPIb "Python 2 – TIO Nexus")
A port of [Arnauld's answer](https://codegolf.stackexchange.com/a/122918/39244).
[Answer]
# Ruby, ~~106~~ 103 bytes
```
->s{s[0]+(s=~/ /?$'[0]:s[(j="()6>P_ac;?.O}AFLKMrS".index((s.sum%136%95+32).chr))?j>7?j/4:-1:1]).upcase}
```
If the input contains a space, the second output letter is the one after the space. Else...
Hash the sum of all characters in the input to obtain a character whose index in the magic string indicates the index of the second output letter in the input string, according to the formula `j>8?j/4:-1` (-1 means the end.). If the hash gives a character that is not in the magic string, second letter is second letter of input.
As an explanation of the magic string, the hash characters and the letter indexes they encode are below. Note that Delaware appears even though the second letter would do - this is because its hash code clashes with Kentucky. Fortunately the last letter of Delaware is the same as the second.
```
Letter(index)
Last (-1) (-MD )-VA 6-GA-LA >-DE-KY P-PA _-CT a-KS c-VT
3rd (2) ;-TN ?-MN .-TX O-NV
4th (3) }-MS A-IA F-MT L-AZ
5th (4) K-MO M-AK r-ME S-HI
```
**Ungolfed in test program**
```
a="Alabama
Alaska
Arizona
Arkansas
California
Colorado
Connecticut
Delaware
Florida
Georgia
Hawaii
Idaho
Illinois
Indiana
Iowa
Kansas
Kentucky
Louisiana
Maine
Maryland
Massachusetts
Michigan
Minnesota
Mississippi
Missouri
Montana
Nebraska
Nevada
New Hampshire
New Jersey
New Mexico
New York
North Carolina
North Dakota
Ohio
Oklahoma
Oregon
Pennsylvania
Rhode Island
South Carolina
South Dakota
Tennessee
Texas
Utah
Vermont
Virginia
Washington
West Virginia
Wisconsin
Wyoming".split($/)
f=->s{ #String argument s.
s[0]+( #Return character s[0] +
s=~/ /?$'[0]: #if s contains a space, 1st character after space, ELSE
s[(j="()6>P_ac;?.O}AFLKMrS".index((s.sum%136%95+32).chr))? #if (sum of ascii codes, mod 136 mod 95 +32).chr in the magic string
j>7?j/4:-1: #return s[j/4] if j>7 else return s[-1] ELSE
1] #if not in the magic string, return s[1].
).upcase #Convert the second character to uppercase if needed.
}
a.map{|i|p [i,f[i]]}
```
[Answer]
# [///](https://esolangs.org/wiki////), ~~619~~ 608 bytes
```
/2/~M//@/~South //1/~North //!/~New //~/\/\///Alabama/AL~Alaska/AK~Arizona/AZ~Arkansas/AR~California/CA~Connecticut/CT~Delaware/DE~Florida/FL~Georgia/GA~Hawaii/HI~Idaho/ID~Illinois/IL~Indiana/IN~Iowa/IA~Kansas/KS~Kentucky/KY~Louisiana/LA2aine/ME2aryland/MD2assachusetts/MA2ichigan/MI2innesota/MN2ississippi/MS2issouri/MO2ontana/MT~Nebraska/NE~Nevada/NV!Hampshire/NH!Jersey/NJ!Mexico/NM!York/NY1Carolina/NC1Dakota/ND~Ohio/OH~Oklahoma/OK~Oregon/OR~Pennsylvania/PA~Rhode Island/RI@Carolina/SC@Dakota/SD~Tennessee/TN~Texas/TX~Utah/UT~Vermont/VT~Virginia/VA~Washington/WA~West Virginia/WV~Wisconsin/WI~Wyoming/WY/
```
[Try it online!](https://tio.run/nexus/slashes#PZHhbuIwDMdfBZ7Aok9A1bKRlaYTdPQ43RevZNRqSVCSjrEPfnXO5U5TIuVnObbz/@cOCXAJsATeuTF2M4AFsHb@gXNBcxVg@CMLIB3wHc8I6YYFQy9UcOrp21nB34I92oAB0i1nONCH85YQspQzZ61pI7VjhKzm3Ax4RW8gX/HT4DwdEZ42/GycP0nBc8pryRPBWrE6YudA5ayGgayjAGrDyh4JZajSrNxVzpSLf6OLHRfGxrHtb1AceONGCo@rmzRBsgbKVYL@NqA9QpknGAK23RhMjAHKNKG2oxNaKFVC8uTgIkKpEwph2pcLQbmbIjd6wSpxNk7Ny1qsevcPT/RK@BNFkt7P13i@hI5Eql7PX4wP5gb6ZV6aL2od6HJ@cL4HfVhk6J3ok6JskWM/zdU5Vx05qNZc9YO4INZXBVfenJyFasuvxtpwGz5xcvk15W3njmamwkPcVi1/eu6y5f@eu5xrMwkLxkCtJfgS0@pf/Baxg7ea98afRRTsBUl@Y2q9T7lBUWFPUQY3EpkQZz/pZs8NhdbZQJJV3NzcWe5Cc4D7/S8 "/// – TIO Nexus")
Since there is no other way of taking input in ///, it goes at the end of the program. Just append the desired input to the program.
Saved 11 bytes by making more replacements, as recommended by @SteveBennett
[Answer]
## Mathematica, ~~138~~ ~~140~~ 134 Bytes
+2 bytes - found a mistake (needed array offset of 1 not 0)
-6 bytes - found a better hash
`#~StringTake~1<>"R_ATE__IN_COI_J_I_SLNAT_Y_Y_HKOAE__SAA_DDLM_RVAH_XDTVA__I_N_EA_T_DY_C_KZL"~StringTake~{1+Hash@#~Mod~89866736~Mod~73}&`
Similar to others it takes the name and takes the first letter. Then it applies the default Mathematica hash then applies two modulus to it "`Hash@#~Mod~89866736~Mod~73`" to get a unique number for each state. This value is then looked up in a string to generate the second letter.
Can probably be golfed more but the search space is huge for Mathematica to find. Duplicated second letters weren't considered in the hash search. `_` characters represent wasted values in the string. In theory you could get the string down to only 19 characters but finding the custom hash to produce that would be a nightmare.
[Answer]
# [TAESGL](https://github.com/tomdevs/taesgl), 386 bytes
```
B=«ōďā,AL,ņćđ,AK,ķċđ,AZ,ćōē,AR,ďċđ,CA,ĭāď,CO,ŕĭ,CT,ćđēą,DE,ĕŕ,FL,īĭ,GA,ńāē,HI,ćĉďą,ID,ĭċď,IL,ľđā,ţ,ńĕĕ,IA,ķő,KS,ŏĝ,KY,ŏĕĕ,LA,ŏđć,ME,ņāē,MD,ńđā,MA,īđą,MI,ļēď,MN,ŕğ,MS,ňė,MO,ććĕĉ,MT,ćċćĉ,NE,ŕēď,NV,ň ćŋā,NH,ň ĩēđ,NJ,ň ğĕċ,NM,ň ĉĝ,NY,ćņ ġĉă,NC,ćņ ńċą,ND,ĩēą,OH,ŋĺ,OK,ļķ,OR,ĺđď,PA,ĉĉğ đēā,RI,ōċ ġĉă,SC,ōċ ńċą,SD,ňďą,TN,ċĕď,TX,ōđą,UT,ćđāā,VT,ğğ,VA,ďĉē,WA,ĉĉć ğğ,WV,ľēđ,WI,ĉĩĕ,WY»Ĵ",";B[BĪA)+1
```
[**Interpreter**](https://tomdevs.github.io/TAESGL/v/1.4.1/index.html?code=Qj2rXHUwMTRkXHUwMTBmXHUwMTAxLEFMLFx1MDE0Nlx1MDEwN1x1MDExMSxBSyxcdTAxMzdcdTAxMGJcdTAxMTEsQVosXHUwMTA3XHUwMTRkXHUwMTEzLEFSLFx1MDEwZlx1MDEwYlx1MDExMSxDQSxcdTAxMmRcdTAxMDFcdTAxMGYsQ08sXHUwMTU1XHUwMTJkLENULFx1MDEwN1x1MDExMVx1MDExM1x1MDEwNSxERSxcdTAxMTVcdTAxNTUsRkwsXHUwMTJiXHUwMTJkLEdBLFx1MDE0NFx1MDEwMVx1MDExMyxISSxcdTAxMDdcdTAxMDlcdTAxMGZcdTAxMDUsSUQsXHUwMTJkXHUwMTBiXHUwMTBmLElMLFx1MDEzZVx1MDExMVx1MDEwMSxcdTAxNjMsXHUwMTQ0XHUwMTE1XHUwMTE1LElBLFx1MDEzN1x1MDE1MSxLUyxcdTAxNGZcdTAxMWQsS1ksXHUwMTRmXHUwMTE1XHUwMTE1LExBLFx1MDE0Zlx1MDExMVx1MDEwNyxNRSxcdTAxNDZcdTAxMDFcdTAxMTMsTUQsXHUwMTQ0XHUwMTExXHUwMTAxLE1BLFx1MDEyYlx1MDExMVx1MDEwNSxNSSxcdTAxM2NcdTAxMTNcdTAxMGYsTU4sXHUwMTU1XHUwMTFmLE1TLFx1MDE0OFx1MDExNyxNTyxcdTAxMDdcdTAxMDdcdTAxMTVcdTAxMDksTVQsXHUwMTA3XHUwMTBiXHUwMTA3XHUwMTA5LE5FLFx1MDE1NVx1MDExM1x1MDEwZixOVixcdTAxNDggXHUwMTA3XHUwMTRiXHUwMTAxLE5ILFx1MDE0OCBcdTAxMjlcdTAxMTNcdTAxMTEsTkosXHUwMTQ4IFx1MDExZlx1MDExNVx1MDEwYixOTSxcdTAxNDggXHUwMTA5XHUwMTFkLE5ZLFx1MDEwN1x1MDE0NiBcdTAxMjFcdTAxMDlcdTAxMDMsTkMsXHUwMTA3XHUwMTQ2IFx1MDE0NFx1MDEwYlx1MDEwNSxORCxcdTAxMjlcdTAxMTNcdTAxMDUsT0gsXHUwMTRiXHUwMTNhLE9LLFx1MDEzY1x1MDEzNyxPUixcdTAxM2FcdTAxMTFcdTAxMGYsUEEsXHUwMTA5XHUwMTA5XHUwMTFmIFx1MDExMVx1MDExM1x1MDEwMSxSSSxcdTAxNGRcdTAxMGIgXHUwMTIxXHUwMTA5XHUwMTAzLFNDLFx1MDE0ZFx1MDEwYiBcdTAxNDRcdTAxMGJcdTAxMDUsU0QsXHUwMTQ4XHUwMTBmXHUwMTA1LFROLFx1MDEwYlx1MDExNVx1MDEwZixUWCxcdTAxNGRcdTAxMTFcdTAxMDUsVVQsXHUwMTA3XHUwMTExXHUwMTAxXHUwMTAxLFZULFx1MDExZlx1MDExZixWQSxcdTAxMGZcdTAxMDlcdTAxMTMsV0EsXHUwMTA5XHUwMTA5XHUwMTA3IFx1MDExZlx1MDExZixXVixcdTAxM2VcdTAxMTNcdTAxMTEsV0ksXHUwMTA5XHUwMTI5XHUwMTE1LFdZu1x1MDEzNCIsIjtCW0JcdTAxMmFBKSsx&input=Ik1hcnlsYW5kIg==)
Very simple compression of the state names, added into an array with the abbreviations.
[Answer]
# Japt, 383 bytes
The compression of the first string may be improvable by experimenting with the order of the letters.
```
g +`lkzÇUaidlnyaÀÍ¥evhjmycdhkÎödnxttaaviy`g`alabaµ
Ã2ka
iza
kÂ6s
Öâfnia
åªv
¬nש
Ü.Ø
fÓQ»
gegia
°ii
i»
ÅJno
Äa
Å0
kÂ6s
kÀ_cky
lia
Úpe
æ¯À
ÚUaÖ³etts
Úòig
·nÌta
æ«7ppi
æ¬
Úa
ßka
va»
w mp¢i
w jÀ y
w ´xi¬
w yk
Íh ÖÚ¦na
Íh »kota
oo
oklaÊá
eg
pnsylvia
r¸ Ó
Ñh ÖÚ¦na
Ñh »kota
âÊte
x
©ah
vÚ
virgia
Øgn
ØÙ virgia
æÈ;n
wyÇg`·bUv) u
```
[Try it online](http://ethproductions.github.io/japt/?v=1.4.4&code=ZyArYGxrep/HVWFpZGxuhnlhwJ7NpWV2aGpteWNkaGvO9mRueHR0YWF2aXlgZ2BhbGFiYbUKwzJrYQqHaXqNYQqHa8I2cwrW4maObmlhCuWEqnYKrG6a1x6pCtwu2BgKZtNRuwpnZY5naWEKlbBpaQppu5cKxUpub4kKxAGEYQrFMAprwjZzCmvAX2NreQpsjIlphGEK2nBlCuaJr8AK2lVh1rNldHRzCtryaWeECrduzJx0YQrmmKs3cHBpCuaYrAEK2ouEYQqa35prYQqadmG7Cpp3IJVtcKJpnAqadyBqwCB5Cpp3ILR4aawKmncgeY5rCs0WaCDW2qZuYQrNFmggu2tvdGEKb5ZvCm9rbGHK4QqOZWeNCnCBbnN5bHaEaWEKcpe4IInTgArRAWgg1tqmbmEK0QFoILtrb3RhCuIQynRlCpJ4hgqpYWgKdoDaiwp2aXJniGlhCtgSiGeRbgrY2SB2aXJniGlhCuYIyDtuCnd5xxhnYLdiVXYpIHU=&input=IkFsYWJhbWEi)
[Answer]
# Perl 5, ~~150~~ 148 bytes (147 + 1)
This is by no means optimal, but it does its job. Needs `-n` command line flag.
```
s/las//;s/ai?n//;s/[oie]n|ri//;s/e([vx])/$1/;s/issi?//;s/(.).+ /\1/;/(.)(.)/;/^([^W]).*(?:[cogavn][wiku]|[ir][ys][li]|rm)([adyti])$/;print uc"$1$2"
```
] |
[Question]
[
The day this post was published was Christmas Eve. Tomorrow will be Christmas. Yesterday was Christmas Eve Eve. In two days it will be
```
Christmas Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve
```
.
Your job is to take the date the program is run and encode it in Christmas Eve format.
* If your program is run on Christmas, it should output the string "Christmas".
* If your program is not run on Christmas, it should output the string "Christmas", followed by the string " Eve" repeated `n` times, where `n` is the number of days until Christmas.
+ Note that this must be based on the *next* Christmas. For example, if the day is April 26, 2019, you must do your calculation based on December 25, 2019, not any other Christmas.
+ Remember to count leap days.
* Christmas is December 25th of every year.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code wins! Note though that the goal is not to find the shortest program in any language, but to find the shortest program in every particular language. For example, if you find the shortest C++ program, then it wins this contest for C++, even if someone finds a shorter program in Python.
[Answer]
# SmileBASIC, ~~73~~ ~~71~~ 67 bytes
```
?"Christmas";
@L?" Eve"*(D!=P);
P=D
DTREAD OUT,M,D
IF M/D-.48GOTO@L
```
The program prints "Christmas", then prints " Eve" every time a day passes, until it is December 25th. (12/25 = 0.48)
May take up to a year to run.
[Answer]
# Excel formula, 59 bytes
```
="Christmas"&REPT(" Eve",DATE(YEAR(NOW()+6),12,25)-TODAY())
```
[Answer]
# [Perl 6](http://perl6.org/), ~~61~~ 47 bytes
~~say 'Christmas'~' Eve'x(Date.today...^{.month==12&&.day==25})~~
```
say 'Christmas'~' Eve'x(Date.today...^/12\-25/)
```
[Try it online!](https://tio.run/##K0gtyjH7/784sVJB3TmjKLO4JDexWL1OXcG1LFW9QsMlsSRVryQ/JbFST08vTt/QKEbXyFRf8/9/AA "Perl 6 – Try It Online")
*-14 bytes (!) thanks to Jo King*
`Date.today ...^ /12\-25/` is the sequence of dates starting today and ending the day before Christmas. (The regular expression `/12\-25/` is matched against the string representation of the dates.) The string `" Eve"` is replicated a number of times equal to the length of that sequence, and is output after the string `"Christmas"`.
[Answer]
# [R](https://www.r-project.org/), ~~112 106~~ 72 bytes
Via @digEmAll and @J.Doe
```
x=Sys.Date()-1;cat('Christmas');while(!grepl('12-25',x<-x+1))cat(' Eve')
```
[Try it online!](https://tio.run/##bY1BbsIwEEX3OcXULGyruEqiUlECq7YnYJuNRWywFGxkT8AIcfbUoW02zSznvf@/72dw8fIExoIE3dkdGmcBHQRz7FqJChqjtfLKIhB0jbwGkmlYi1Fmkd8ygO01vHwmfzP@@S3eYTYC8Ao7bwPENBZQyQachkdliu8kMnRb9MbuU@OcrmpLeR83f3HGRVENFv04eBPwKAPl1eVgWsWe9l6dWkaLUpQLOo9rEZ8Lzh82fJ1VKvpZILUVE1dbwrN7ppn83SJlXizFUPdKOK9gEi0GNEneJsi7yBNZ/idlPpL@Gw "R – Try It Online")
My original answer was prior to the clarification that the code was to take the date on which the code is run as input. It could be modified as above to save many bytes but I won't bother.
```
function(x,z=as.Date(paste0(strtoi(format(x,"%Y"))+0:1,"-12-25"))-x)cat("Christmas",rep("Eve",z[z>=0][1]))
```
[Try it online!](https://tio.run/##fcxLCsIwFIXhuasoF4QEE0mChfqoE3URUjsIJcEM@iC5SunmYyjoSDo8nI/fR5udeLSvrkHXd2RkU6nD9qrRkEEHNIIE9Ng7YnvfakwA1negdCMOkgGXiqs8TT7SJr1weXoXsNUBmDcDgdvbAJuq6VyKupI1pdGSbx@UkMVc2KXCMZsDjw7o6p/JF82ei2SKJaPEz8QP "R – Try It Online")
Explanation: everyone's at church so I have time to do this. Extract the year, coerce to integer. Make vector of that year's Xmas and the next year's Xmas and subtract the input date to get a vector of two differences between the input date and those two Xmases.
Pick the non-negative one and `cat` "Christmas" with that many "Eves".
[Answer]
# [Windows PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~67~~ ~~64~~ 63 bytes
```
for(;1225-'{0:Md}'-f(date|% *ys $i)){$i++}'Christmas'+' eve'*$i
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/Py2/SMPa0MjIVFe92sDKN6VWXTdNIyWxJLVGVUGrslhBJVNTs1olU1u7Vt05oyizuCQ3sVhdW10htSxVXUsl87@SSiaIXaz0HwA "PowerShell – Try It Online")
Managed to shave off ~~3 bytes~~ 4 bytes (thanks [Cows quack](https://codegolf.stackexchange.com/users/41805/cows-quack)) by using the `-f`ormat operator instead of `.ToString()`, and then subtracting the date string from the numerical value 1225 instead of doing a comparison with `-ne`. The resulting integer will be interpreted as a boolean for the conditional where `0` (which will happen on Christmas) is interpreted as `False` (don't enter the loop), and any other value is interpreted as `True` (enter the loop).
Since the integer is on the left now, the date string will be converted to the integer and math will be done, as opposed to the previous version where the `1225` integer was converted to string for the comparison.
### Original Version
---
# [Windows PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 67 bytes
```
for(;(date|% *ys $i|% tost* Md)-ne1225){$i++};'Christmas'+' eve'*$i
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/Py2/SMNaIyWxJLVGVUGrslhBJRPIKMkvLtFS8E3R1M1LNTQyMtWsVsnU1q61VnfOKMosLslNLFbXVldILUtV11LJ/P8fAA "PowerShell – Try It Online")
Using a `for` loop as a `while` loop basically, because it's shorter. In the loop condition we check the current date (`date`, a shortened form of `Get-Date`), piped to `ForEach-Object`'s alias `%`, using the form that can invoke a method by wildcarded name; in this case the method is `AddDays()` on the `DateTime` object, and the value we give it is `$i`.
This gets piped to `ForEach-Object` again to invoke the `ToString()` method, with format string `Md` (month, then day, minimal digits since we don't care for what comes next). This string is then tested to see if it's not equal `-ne` to the number `1225`, which will be converted to a string for the comparison, saving me the quotes.
This is why it doesn't matter that the months and days are single digits, it will never be ambiguous because there's no other day of the year that would stringify to `1225`.
The loop continues until the string *is* `1225`. At the beginning of the program, `$i` will be zero so it will be comparing today's date, and the loop will never execute, but for any other day `$i` gets incremented in the loop body, so that we will have a count of how many days until the next Christmas, automatically accounting for leap years and whether or not Christmas passed this year.
After the loop we just output the string `Christmas` concatenated with the result of multiplying the string `eve` times the value of `$i` (which, on Christmas day, will be `0`, resulting in no `eve`s).
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 89 bytes
```
Write("Christmas");for(var t=DateTime.Now;$"{t:Md}"!="1225";t=t.AddDays(1))Write(" Eve");
```
[Try it online!](https://tio.run/##Sy7WTS7O/P8/vCizJFVDyTmjKLO4JDexWEnTOi2/SKMssUihxNYlsSQ1JDM3Vc8vv9xaRam6xMo3pVZJ0VbJ0MjIVMm6xLZEzzElxSWxsljDUFMTapSCa1kq0JT//wE "C# (Visual C# Interactive Compiler) – Try It Online")
-3 bytes thanks to @JeppeStigNielsen!
My strategy is pretty straightforward:
1. Initialize a loop variable `t` to the current date
2. Print `Eve` if `t` is not Christmas
3. Add a day to `t` and repeat
I tried some fancier things, but this way required the fewest bytes.
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~76~~ 63 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?")[SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set")
Full program. Assumes `‚éïIO‚Üê0` (zero-indexing).
```
‚éïCY'dfns'
'Christmas',' Eve'⍴⍨4×12 25⍳⍨⍉2↑1↓⍉date(⍳366)+days⎕TS
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkGXI862gtAXOdI9ZS0vGJ1LnXnjKLM4pLcxGJ1HXUF17JU9Ue9Wx71rjA5PN3QSMHI9FHvZiDvUW@n0aO2iYaP2iYDmSmJJakaQAljMzNN7ZTEymKggSHB/4Fm/1cAgwIA "APL (Dyalog Unicode) – Try It Online")
`‚éïCY'dfns'`‚ÄÉ**c**o**p**y in [the dfns library](http://dfns.dyalog.com/n_contents.htm)
`‚éïTS`‚ÄÉcurrent **t**ime **s**tamp as [year,month,day,hour,min,sec,ms]
`days`[[c]](http://dfns.dyalog.com/c_days.htm "Code")‚ÄÉfind the number of days[[n]](http://dfns.dyalog.com/n_days.htm "Notes") since 1899-12-31 00:00:00.000
`(⍳366)` add the first 366 integers (0…365) to that
`date`[[c]](http://dfns.dyalog.com/c_date.htm "Code")‚ÄÉfind the dates[[n]](http://dfns.dyalog.com/n_date.htm "Notes") that correspond to those numbers (366√ó7 table; one column per unit)
`‚çâ`‚ÄÉtranspose (7√ó366 table; one row per unit)
`1‚Üì`‚ÄÉdrop one row (the years)
`2‚Üë`‚ÄÉtake the first two rows (months and days)
`12 25⍳⍨` find the index of the first Christmas
`4√ó`‚ÄÉmultiply that by four
`' Eve'⍴⍨` use that to reshape the character list
`'Christmas ',`‚ÄÉappend that to this
[c]‚ÄÉcode of that function
[n]‚ÄÉnotes for that function
[Answer]
## T-SQL, ~~92~~ 88 bytes
```
PRINT'Christmas'+REPLICATE(' Eve',DATEDIFF(D,GETDATE(),STR(YEAR(GETDATE()+6))+'-12-25'))
```
Edit: Saved 4 bytes thanks to @BradC.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~111~~ 103 bytes
```
from datetime import*
d=date.today()
print"Christmas"+" Eve"*(date((d+timedelta(6)).year,12,25)-d).days
```
[Try it online!](https://tio.run/##FYxBCgMhDADv@wrxlOxuhQrtrafShwSSskJdJYaCr7f1OsxM7XaUM47x1pIdk4mlLC7lWtTWhR8TBStMHXCpmk7zz0NTs0zNb969vuJXmBYAbzNm@RjBHTF0Id2vcY83vDCG/6ON8QM "Python 2 – Try It Online")
Update inspired by [Richard Crossley's answer](https://codegolf.stackexchange.com/a/178023/73368).
Explanation:
```
from datetime import*
# get today as a date, so we don't have to worry about rounding errors due to time
d=date.today()
# get the year of the Christmas to compare to
# if the current date is after this year's Christmas, the 6 day offset will give the next year
# otherwise, returns this year
(d+timedelta(6)).year
# next Christmas minus the current date
date(.....................,12,25)-d
# Christmas, plus (number of days until next Christmas) " Eve"s
print"Christmas"+" Eve"*(...................................).days
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 80 bytes
```
require'date'
t=Date.today
puts'Christmas'+' Eve'*(Date.new((t+6).year,12,25)-t)
```
[Try it online!](https://tio.run/##KypNqvz/vyi1sDSzKFU9JbEkVZ2rxNYFSOuV5KckVnIVlJYUqztnFGUWl@QmFqtrqyu4lqWqa2mAleSllmtolGibaepVpiYW6Rga6RiZauqWaP7/DwA "Ruby – Try It Online")
Thanks to tsh for [his idea](https://codegolf.stackexchange.com/questions/178003/encode-the-date-in-christmas-eve-format/178022#comment429060_178010)
[Answer]
# PHP, 61 bytes
```
Christmas<?for($t=time();date(md,$t+=86400)-1226;)echo" Eve";
```
Run with `-n` or [try it online](http://sandbox.onlinephpfunctions.com/code/dd5e887fbcab9459a1752689ee2d6950a35e1d1c).
[Answer]
# JavaScript, ~~135~~ ~~131~~ ~~121~~ ~~92~~ 88 bytes
My first (naïve) solution (**135b**):
```
t=new Date();n=new Date();n.setMonth(11);n.setDate(25);'Christmas'+' Eve'.repeat((n>=t?n-t:(n.setFullYear(n.getFullYear()+1)-t))/864e5)
```
It sets 2 dates: now and Xmas of this year. If the latter hasn't passed yet, it just diffs them, if it has passed, diffs to next year's Xmas. Uses either diffs for the number of repeats.
(Trying to) Think Outside the Box (**131b**):
```
i=0;f=_=>{t=new Date();if(t.getMonth()!=11||t.getDate()!=25){i++;setTimeout(f,864e5)}else{alert('Christmas'+' Eve'.repeat(i))}};f()
```
The challange specifies WHICH output is required when running the program on a given day, but doesn't specify WHEN to return it...
This will just 'sleep' for a day, increment a counter by 1, and repeat till it's Xmas in order to give the output.
Since JavaScript doesn't guarantee the 'sleep' time, the actual result might be off.
It is also ugly for using the `alert` function, which means wer'e actually not dealing with pure JavaScript, but with browser APIs as well (we can use `console.log` at the cost of 6 extra bytes).
A better approach (**121b**):
```
t=new Date();i=0;while(t.getMonth()!=11||t.getDate()!=25){t=new Date(t.valueOf()+864e5);i++};'Christmas'+' Eve'.repeat(i)
```
Starting from today, increment the date by a day until it's Xmas, then use that loop's counter for the number of repeats required.
Improving (including going through a minifier and using 12Me21's trick to shave extra 5b) (**92b**):
```
for(s='Christmas',t=new Date;t.getMonth()/t.getDate()-.44;)t=new Date(t*1+864e5),s+=' Eve';s
```
Final touches (**88b**):
```
for(s='Christmas',t=new Date;t.getMonth()/(d=t.getDate())-.44;t.setDate(d+1))s+=' Eve';s
```
* For all of the above, REPL is assumed.
* See Vadim's submission - much better than mine!
[Answer]
# [Bash](https://www.gnu.org/software/bash/), ~~68~~ ~~65~~ 61 bytes
*Golfed 4 bytes thanks to [Nahuel Fouilleul](https://codegolf.stackexchange.com/users/70745/nahuel-fouilleul)* by using ```` command substitution and `eval` in place of sed `e` and `xargs`
```
echo Christmas `eval date\ -d{0..366}day\;|sed /c.25/Q\;cEve`
```
[Try it online!](https://tio.run/##S0oszvj/PzU5I1/BOaMos7gkN7FYISG1LDFHISWxJDVGQTel2kBPz9jMrDYlsTLGuqY4NUVBP1nPyFQ/MMY62bUsNeH/fwA "Bash – Try It Online")
Inside the ```` [command substitution](https://www.gnu.org/software/bash/manual/html_node/Command-Substitution.html#Command-Substitution), we have
`eval` run the following string as shell commands
* `date\ -d{0..366}day\;` under [brace expansion](https://www.gnu.org/software/bash/manual/html_node/Brace-Expansion.html#Brace-Expansion) of `{0..366}`, this results in the string `date -d0day; date -d1day; date -d2day; ... date -d366day;`, each command in this string computing the date between 0 and 366 days from present resulting in output of the format `Wed Dec 26 18:22:33 UTC 2018`, with each in its own line
`|sed` upon which, call the following sed commands
* `/c.25/Q` if the regex `/c.25/` is matched, `Q`uit without printing
* `\;cEve` otherwise change the line to `Eve`
All the required number of `Eve`s are produced each on its own line. This output is captured in ````, and is subject to [word splitting](https://www.gnu.org/software/bash/manual/html_node/Word-Splitting.html#Word-Splitting) where words are split on newlines. Each word is fed as an argument to `echo`.
`echo Christmas `...``
Each argument to `echo` is printed by being separated by spaces, resulting in the desired output.
[Answer]
# Bash +GNU date, ~~72~~, ~~73~~, 67 bytes
```
for((d=7;`date +%-j -d$d\day`-1;d++));{ x+=\ Eve;};echo Christmas$x
```
* one byte saved replacing `!=` with `-`
* another removing extra space
* fix -3 bytes `d=0`, because `date -dday` is date+1 and doesn't work on 25/12
* 6 bytes saved thanks to Toby Speight using %-j format to avoid 0 padding (and octal conversion) and shorter than %d%m compared to 2512
[Try it online](https://tio.run/##S0oszvj/Py2/SEMjxdbcOiElsSRVQVtVN0tBN0UlJSYlsTJB19A6RVtbU9O6WqFC2zZGwbUs1brWOjU5I1/BOaMos7gkN7FYpeL/fwA)
[Answer]
# VBA (Excel), 108 bytes
Copy in a blank module. Prints to the Immediate window:
```
Sub X:s="Christmas":d=Now:For t=1 To (DateSerial(Year(d+6),12,25)-d):s=s &" Eve":Next:Debug.Print s:End Sub
```
**Note:** Using `:` instead of line breaks saves two bytes per line.
Notice that the VBA editor will insert additional spaces between keywords, operators, etc... and parenthesis after the Sub definition, but if you copy and paste this code it will work (I couldn't get rid of that space before the `&`).
Not bad for VBA (for once).
[Answer]
# Python 2, 128 bytes / Python 3, 130 bytes
of course, two less bytes with Python 2
```
from datetime import date as D
T=D.today()
Y=T.year
a=(D(Y,12,25)-T).days
print("Christmas"+" Eve"*[a,(D(Y+1,12,25)-T).days][a<0])
```
[Answer]
## Python 3, 106 Bytes
```
from datetime import*
d=date.today()
print("Christmas"+" Eve"*(date((d+timedelta(6)).year,12,25)-d).days)
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 157 bytes
I thought that I would be able to avoid including `time.h` but that just gave segment faults.
```
#include <time.h>
*t,u;f(){time(&u);t=localtime(&u);t[5]+=t[4]>10&t[3]>25;t[4]=11;t[3]=25;u-=mktime(t);printf("Christmas");for(u/=86400;u++;printf(" Eve"));}
```
[Try it online!](https://tio.run/##Tc5BDoIwEIXhvadoMCGtiIKCMRnLxngKwgILSGMLBqZsCGfH4kJdfn/mJSP8hxDzWjZCmaIklx4LJe@7OvlrKHVpy2qDWwMVZeMSqGsYIFetyNXPaZx5HNMoS8LAxfSYJYcYFvMwhMXc2vhcPz8bZPDqZIMVda51J3vUee8wqNqOmj0/n6IgAON53yNyG0qHMZhma6Jz2dChlQUjI7F/AZnmNw "C (gcc) – Try It Online")
[Answer]
# [Groovy](http://groovy-lang.org/), 66 bytes
```
d=[]as Date
print'Christmas'+' Eve'*(new Date((d+6).year,11,25)-d)
```
[Try it online!](https://tio.run/##Sy/Kzy@r/P8/xTY6NrFYwSWxJJWroCgzr0TdOaMos7gkN7FYXVtdwbUsVV1LIy@1HKxCQyNF20xTrzI1sUjH0FDHyFRTN0Xz/38A "Groovy – Try It Online")
Courtesy of @ASCII-only
[Answer]
# [Scala](http://www.scala-lang.org/), ~~116~~ 113 bytes
```
var d=new java.util.Date
print("Christmas")
while(!(""+d).contains("c 25")){print(" Eve");d.setDate(d.getDate+1)}
```
[Try it online!](https://tio.run/##XY7LasMwEEX3/gplVhIG5UFbCsGL0qQ7r9IfUKVJM0GSjTRxWoK/3Y1w6aKzmoE7555sjTdT93FGy6IV@MUYXRYvfX@bBpOEayJexdkMRl@YvN4ZxqpPFFnC6ylR5mAyqOp6Io9yIQFqp7TtIhuKWYIVm0dQ6vb7IvYDgto6nZELSjr9OW/1Wo3TWC2XpZWa1XYm/rXzXU0fKPQeS/ytS8HcgW3rHCh9nM/Dd2YM2l5SwsjvFLAl7ynXpBYNrDfF5Z8K1c3z08OqzDj9AA "Scala – Try It Online")
Where `c 25` is short for `Dec 25`.
[Answer]
# JavaScript, ~~86~~ 77 bytes
Using REPL it would be
```
for(c='Christmas',d=new Date;!/c 25/.test(d);d=new Date(+d+864e5))c+=' Eve';c
```
Kudos to ASCII-only for **-9** bytes
[Answer]
# [Lua](https://www.lua.org), 137 118 bytes.
118 bytes
```
t,d,month,day=os.time,os.date,1,-6year=d"%Y"+(d"%D">"12/25"and 2or 1)print("Christmas",d" Eve":rep(d("%j",t(_G)-t())))
```
137 bytes (previous)
```
t,d=os.time,os.date a=d"*t"a.year,a.month,a.day=a.year+(d"%m%d">"1225"and 1 or 0),12,25 print("Christmas",("Eve "):rep((t(a)-t())/86400))
```
It's worth noting that it doesn't work in LuaJIT (syntax error)
[Answer]
# [Julia 1.0](http://julialang.org/), 91 bytes
```
using Dates
t=today()
print(:Christmas," Eve"^~-(tonext(==((12,26))‚àòmonthday,t)-t).value)
```
[Try it online!](https://tio.run/##yyrNyUw0rPj/v7Q4My9dwSWxJLWYq8S2JD8lsVJDk6ugKDOvRMPKOaMos7gkN7FYR0nBtSxVKa5OV6MkPy@1okTD1lZDw9BIx8hMU/NRx4zc/LySDKBWnRJN3RJNvbLEnNJUzf//AQ "Julia 1.0 – Try It Online")
* -1 byte thanks to @MarcMush: Substitute `1>0` for `true`
* -5 bytes thanks to @MarcMush: Substitute `_.value` for `Dates.value(_)`
* -1 byte thanks to @amelies: print symbol `:Christmas` rather than string `"Christmas"`
* -1 byte thanks to @MarcMush: compose functions with `‚àò`
* -7 bytes thanks to @MarcMush: use Boxing Day as the end date and subtract one in order to eliminate the `same=true` parameter
[Answer]
# MySQL, 102 bytes
pretty much the same as [Neil´s T-SQL answer](https://codegolf.stackexchange.com/a/178031/55735). There seems to be no shorter way in SQL.
```
select concat("Christmas",repeat(" Eve",datediff(concat(year(now()+interval 6 day),"-12-25"),now())));
```
[Try it online](https://sqltest.net/#403120).
[Answer]
# MATLAB, 91 bytes
```
n=datetime
x=datetime(year(n+6),12,25)
s='Christmas'
while days(x-n)>=1 n=n+1 s=[s,' Eve'] end
```
# MATLAB Non-looper, 100 bytes
```
x=datenum(datetime(floor((now+5)/365.2425),12,25))
d=x-now
['Christmas' repmat(' Eve',1,min(d(d>=0)))]
```
[Answer]
# [Scala](http://www.scala-lang.org/), 123 bytes
Thanks to ASCII-only's work.
```
print("Christmas")
var d=new java.util.Date
while(d.getMonth()<11||d.getDate()!=25){print(" Eve");d.setDate(d.getDate()+1)}
```
[Try it online!](https://tio.run/##TYyxCsIwFAD3fkXMlCAEIjhpB6mO/Yhn8zApNQ3JMxXafntE6eB6d1zqYIAy3nvsiLXgPMM3oTeJXUKYS4jOk@CNjS7RExKXVYbITO1xYj1kUC9yg7oCYTVZN6Aw6oHUjp6skGetl@UHvoGQu/pwlPP2ZLeMXJ6MSpv@C/darmUtHw "Scala – Try It Online")
# [Scala](http://www.scala-lang.org/) + [Joda-Time](https://github.com/JodaOrg/joda-time), 140 bytes
```
import org.joda.time._
var s="Christmas"
var d=DateTime.now
while(d!=d.withDate(d.year().get(),12,25)){d=d.plusDays(1);s+=" Eve"};println(s)
```
Does not run in TIO since it requires Joda-Time library.
[Answer]
# [q](https://code.kx.com/home), 53 bytes
```
"Christmas",(4*(not 12 25~`mm`dd$.z.d+)(1+)/0)#" Eve"
```
# k, 50 bytes
```
"Christmas",(4*(~12 25~`mm`dd$.z.d+)(1+)/0)#" Eve"
```
Increment counter while the date is not Dec 25th, then take that number of copies of " Eve" and append to "Christmas".
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~93~~ ~~89~~ ~~87~~ 81 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
'ŒÎžfže«Ž9Ú.S©DΘžg+т‰0Kθ4ÖUi390že-X+ë®_i0ë•ΘÏF•º11£®ª₂+ā2QX*+13žf-.£Ože-]Fð'»ˆ}J™
```
[Try it online](https://tio.run/##AYMAfP9vc2FiaWX//yfFksOOxb5mxb5lwqvFvTnDmi5TwqlEzpjFvmcr0YLigLAwS864NMOWVWkzOTDFvmUtWCvDq8KuX2kww6vigKLOmMOPRuKAosK6MTHCo8KuwqrigoIrxIEyUVgqKzEzxb5mLS7Co0/FvmUtXUbDsCfCu8uGfUrihKL//w) or [Try it online with an emulated self-specified date of 'today'](https://tio.run/##yy9OTMpM/a8UUFqikKiQkliSqpCZp1CSkaqQll@Um1iikJKi6@urWwkECiX5CqXFqQqJxQqJOSWpRXmJJZllqQrFJYlFJZl56RDNGqm5pTlARgqEm5@moF6Sn5JYqa5ppRTDxaVkZKpraKRrZGBooaSue2hh2H/1o5MO90UeWhHkdXSv5eFZesGHVrqcmxF5bof2xaZHDRsMvM/tMDk8LTTT2NIg8sJe3Qjtw6sPrYvPNDi8@lHDonMzDve7AelDuwwNDy0@tO7QqkdNTdpHGo0CI7S0DY0jD7cW6@odWuwP0hnrdniD@qHdp9tqvR61LPr/HwA).
**Old ~~93~~ ~~89~~ 87 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) approach that loops over the days one by one:**
```
žežfžg)V'ŒÎ[Y¨JŽ9ÚQ#Y`т‰0Kθ4ÖUD<i\28X+ë<7%É31α}‹iY¬>0ëY1¾ǝDÅsD12‹i>1ë\1Dǝ¤>2}}ǝVð'»ˆ}J™
```
[Try it online](https://tio.run/##AYMAfP9vc2FiaWX//8W@ZcW@ZsW@ZylWJ8WSw45bWcKoSsW9OcOaUSNZYNGC4oCwMEvOuDTDllVEPGlcMjhYK8OrPDclw4kzMc6xfeKAuWlZwqw@MMOrWTHCvsedRMOFc0QxMuKAuWk@McOrXDFEx53CpD4yfX3HnVbDsCfCu8uGfUrihKL//w) or [Try it online with an emulated self-specified date of 'today'](https://tio.run/##yy9OTMpM/a8UUFqikKiQkliSqpCZp1CSkaqQll@Um1iikJKi6@urWwkECiX5CqXFqQqJxQqJOSWpRXmJJZllqQrFJYlFJZl56RDNGqm5pTlARgqEm5@moF6Sn5JYqa5ppRTDxaVkZKpraKRrZGBooaSue2jh/zD1o5MO90VHHlrhdXSv5eFZgcqRCRebHjVsMPA@t8Pk8LRQF5vMGCOLCO3Dq23MVQ93Ghue21j7qGFnZuShNXYGh1dHGh7ad3yuy@HWYhdDI5C4neHh1TGGLsfnHlpiZ1Rbe3xu2OEN6od2n26r9XrUsuj/fwA).
**Explanation:**
05AB1E doesn't have any builtins for dates, except for receiving the current year/month/day/hours/minutes/seconds/microseconds, so most bytes are used for manual calculations.
```
'ŒÎ '# Push dictionary string "christmas"
žfže« # Append the current month and current day together
.S # Compare it with
≈Ω9√ö # Compressed integer 1225
# (1 if >1225; 0 if ==1225; -1 if <1225)
© # Store this comparison in variable `®` (without popping)
D # Duplicate it
Θ # Check if it's equal to 1 (1 if 1; 0 if 0 or -1)
žf+ # Add the current year to it
т‰0Kθ4Ö # Check if this is a leap year:
т‰ # Divmod it by 100
0K # Remove the 0s
θ # Only leave the last item
4Ö # Check if it's divisible by 4
U # Pop and store this is_leap_year in variable `X`
i # If the comparison is 1:
390že- # Push 390 minus the current day
# (390 is 31 for days in December and 259 for days of Christmas Day)
X+ # Add the is_leap_year check from variable `X`
ë®_i # Else if the comparison is 0:
0 # Push 0
ë # Else (the comparison is -1):
•ΘÏF• # Push compressed integer 5254545
º # Mirror it to 52545455454525
11£ # Only leave the first 11: 52545455454
®ª # Convert it to a list of digits, and append the -1:
# [5,2,5,4,5,4,5,5,4,5,4,-1]
‚ÇÇ+ # Add 26 to each: [31,28,31,30,31,30,31,31,30,31,30,25]
ā # Push a list in the range [1,length] (without popping):
# [1,2,3,4,5,6,7,8,9,10,11,12]
2Q # Check which is equal to 2: [0,1,0,0,0,0,0,0,0,0,0,0]
X* # Multiply each by the is_leap_year check of variable `X`
+ # Add the values at the same positions in the lists together
13žf- # Push 13 minus the current month
.£ # Only leave that many items from the end of the list
O # Sum them together
že- # Subtract the current day
] # Close the if-else statements
F # Loop that many times:
√∞ # Push a space character " "
'»ˆ '# Push dictionary string "eve"
}J # After the loop: join the entire stack together
‚Ñ¢ # Titlecase each word
# (after which the result is output implicitly)
```
---
```
žežfžg)V # Get the current [day,month,year] and save it in variable `Y`
'ŒÎ '# Push dictionary string "christmas"
[ # Start an infinite loop:
Y¨J # Remove the year, and join the month and day together
Q # Check if this is equal to
≈Ω9√ö # Compressed integer 1225
# # If this is truthy (thus it's December 25th): stop the infinite loop
Y`т‰0Kθ4ÖUD<i\28X+ë<7%É31α}‹iY¬>0ëY1¾ǝDÅsD12‹i>1ë\1Dǝ¤>2}}ǝV
# Go to the next day, and set `Y` to it
√∞ # Push a space " "
'»ˆ '# Push dictionary string "eve"
}J # After the infinite loop: join the entire stack together
‚Ñ¢ # Titlecase each word
# (after which the result is output implicitly)
```
[See this 05AB1E answer of mine](https://codegolf.stackexchange.com/a/177019/52210) to understand the `is_leap_year` check.
[See this 05AB1E answer of mine](https://codegolf.stackexchange.com/a/173126/52210) to understand how we go to the next day (with the second longer approach).
[See this 05AB1E tip of mine (sections *How to use the dictionary?* and *How to compress large integers?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `'»ˆ` is `"eve"`; `'ŒÎ` is `"christmas"`; `Ž9Ú` is `1225`; and `•ΘÏF•` is `5254545`.
[Answer]
# [Go](https://go.dev), 178 bytes
```
import(."time";."strings")
func f()string{n:=Now()
y:=n.Year()
if n.Month()>11&&n.Day()>25{y++}
return"Christmas"+Repeat(" Eve",int(Date(y,12,25,0,0,0,0,UTC).Sub(n).Hours())/24)}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=VZDBSsNAEIbveYphwDJL0zUJVqSyBWkrXizS1oPgZS277aLZlM1GCaUv4Ct4CYIv4M1H8W1Mk1xkDvPzD_x8_3x8brLqZyfXz3KjIJXGBibdZc5z1KnHr8LrwcXvd-sRR29ShZccc--M3eTIAl3YNWhirbO3IzHP3ogF5UhY_qCkq7XRYPltZv2W2DiOez3Lp7KsdTLcl_3-IXDKF87iZOtM7lOZY3-hdkp6Qpi9KgyN9TSVXlEZxkmYDMOom_vVhPFl8USW8ZuscDkxdpqcsUNH_t7gHXsRg32gM5dKDyMBmETR-SCKB1GCwV2N7l8soRAClqurxQpqVZdrDprwJH-0IMZw3BhC05BfN2HUZrLw-AT2Pwpm8yl0UR1RVbX7Dw)
And a variant that takes a `Time` as input, 175 bytes:
```
import(."time";."strings")
func f(n Time)string{y:=n.Year()
if n.Month()>11&&n.Day()>25{y++}
return"Christmas"+Repeat(" Eve",int(Date(y,12,25,0,0,0,0,UTC).Sub(n).Hours())/24)}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=fVFNSwMxEMVrfkUIWBKaxm3ailS2IG3Fi0Xa9SAqEku2XXSzJZlVlqW_xEsRPHv2p-ivcT96sUiZwwzzmHlv3ry9L5LN10rNn9RC41hFBkXxKrEgSBgD-UghbJ18f9Y9KghEsSangjiwkVk4wlCYmjkOqcFBAbG6n2d934gbrSxlKAqxEZeJgSVlg3a70TBipLKilr08azbXyGpIrSHDpY0cxMqR5lSvtAJK8PhFEx4ZoCMFmma8LbnscW8b18GQiVn6SA0TF0lqHWXsSHbZupb9c9CtxJVXUYZzBNqBw30f396XYnM0SV4p46haLj3Z-Wf_Ltrdi3b2osc76BqFiY0VlJKI9LzjltdueZKgq8JEeDaU-L6PZ8HZNMBFVZqdWPzAqwGrTPGx-qS8nggpOXR3BvsDXGbCMYjzioHWRIwXnwLGCuY_FHg8GeEtxda8zabOvw)
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 141 bytes
```
var g=DateTime.Now;Write("Christmas"+string.Concat(Enumerable.Repeat(" Eve",(new DateTime(g.Year+(g.Day>25&g.Month>11?1:0),12,25)-g).Days)));
```
[Try it online!](https://tio.run/##NYyxCsIwFAB/JWSQhKbBFLpYWoe2ow4iiOOzPNKASSSJLX59rIPTwXHcFMspmpwXCES3AyS8Govy7NfmFkxCRvs5mJgsRFrEFIzTsvdugsRG97YY4PFEecEXboaScUEqmMOV/FdMyztCKDYO8Omqeqflybs0d0od1WHPhapEVfNS818QOedNzl8 "C# (Visual C# Interactive Compiler) – Try It Online")
] |
[Question]
[
Write a program that outputs its input unchanged. However:
* If all uppercase characters are removed from the program, it lowercases all uppercase letters.
* If all lowercase characters are removed from the program, it uppercases all lowercase letters.
Transforming characters beyond the basic Latin `[A-Za-z]` range is optional, but any character with [both uppercase and lowercase counterparts within Unicode](https://www.unicode.org/Public/UNIDATA/CaseFolding.txt) (`Ñ`/`ñ`, `Ω`/`ω`, etc.) qualifies for "removal" from your program.
In your answer, please specify the character encoding used along with the language name if it might be ambiguous.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). The less bytes, the better.
---
Here's an example in a hypothetical programming language, with input `"Hello, world!"`:
```
DONT_do_NOT_lowercase_UPPERCASE_this(_MY_input_STRING_)
```
‚Üí `Hello, world!`
With uppercase characters removed:
```
_do__lowercase__this(__input__)
```
‚Üí `hello, world!`
With lowercase characters removed:
```
DONT__NOT__UPPERCASE_(_MY__STRING_)
```
‚Üí `HELLO, WORLD!`
---
To be complete, here are the characters/Unicode codepoints that can be removed:
### Uppercase Characters
```
ABCDEFGHIIJKLMNOPQRSTUVWXYZ¬µ√Ä√Å√Ç√É√Ñ√Ö√Ü√á√à√â√ä√ã√å√ç√é√è√ê√ë√í√ì√î√ï√ñ√ò√ô√ö√õ√ú√ù√û√üƒÄƒÇƒÑƒÜƒàƒäƒåƒéƒêƒíƒîƒñƒòƒöƒúƒûƒ†ƒ¢ƒ§ƒ¶ƒ®ƒ™ƒ¨ƒÆƒ∞ƒ∞ƒ≤ƒ¥ƒ∂ƒπƒªƒΩƒø≈Å≈É≈Ö≈á≈â≈ä≈å≈é≈ê≈í≈î≈ñ≈ò≈ö≈ú≈û≈†≈¢≈§≈¶≈®≈™≈¨≈Æ≈∞≈≤≈¥≈∂≈∏≈π≈ª≈Ω≈ø∆Å∆Ç∆Ñ∆Ü∆á∆â∆ä∆ã∆é∆è∆ê∆ë∆ì∆î∆ñ∆ó∆ò∆ú∆ù∆ü∆†∆¢∆§∆¶∆ß∆©∆¨∆Æ∆Ø∆±∆≤∆≥∆µ∆∑∆∏∆º«Ñ«Ö«á«à«ä«ã«ç«è«ë«ì«ï«ó«ô«õ«û«†«¢«§«¶«®«™«¨«Æ«∞«±«≤«¥«∂«∑«∏«∫«º«æ»Ä»Ç»Ñ»Ü»à»ä»å»é»ê»í»î»ñ»ò»ö»ú»û»†»¢»§»¶»®»™»¨»Æ»∞»≤»∫»ª»Ω»æ…Å…É…Ñ…Ö…Ü…à…ä…å…éÕÖÕ∞Õ≤Õ∂ÕøŒÜŒàŒâŒäŒåŒéŒèŒêŒëŒíŒìŒîŒïŒñŒóŒòŒôŒöŒõŒúŒùŒûŒüŒ†Œ°Œ£Œ§Œ•Œ¶ŒßŒ®Œ©Œ™Œ´Œ∞œÇœèœêœëœïœñœòœöœúœûœ†œ¢œ§œ¶œ®œ™œ¨œÆœ∞œ±œ¥œµœ∑œπœ∫œΩœæœø–Ä–Å–Ç–É–Ñ–Ö–Ü–á–à–â–ä–ã–å–ç–é–è–ê–ë–í–ì–î–ï–ñ–ó–ò–ô–ö–õ–ú–ù–û–ü–†–°–¢–£–§–•–¶–ß–®–©–™–´–¨–≠–Æ–Ø—†—¢—§—¶—®—™—¨—Æ—∞—≤—¥—∂—∏—∫—º—æ“Ä“ä“å“é“ê“í“î“ñ“ò“ö“ú“û“†“¢“§“¶“®“™“¨“Æ“∞“≤“¥“∂“∏“∫“º“æ”ĔŔɔ֔á”â”ã”ç”ê”í”î”ñ”ò”ö”ú”û”†”¢”§”¶”®”™”¨”Æ”∞”≤”¥”∂”∏”∫”º”æ‘Ä‘Ç‘Ñ‘Ü‘à‘ä‘å‘é‘ê‘í‘î‘ñ‘ò‘ö‘ú‘û‘†‘¢‘§‘¶‘®‘™‘¨‘Æ‘±‘≤‘≥‘¥‘µ‘∂‘∑‘∏‘π‘∫‘ª‘º‘Ω‘æ‘ø’Ä’Å’Ç’É’Ñ’Ö’Ü’á’à’â’ä’ã’å’ç’é’è’ê’ë’í’ì’î’ï’ñ÷á·Ç†·Ç°·Ç¢·Ç£·Ç§·Ç•·Ç¶·Çß·Ç®·Ç©·Ç™·Ç´·Ç¨·Ç≠·ÇÆ·ÇØ·Ç∞·Ç±·Ç≤·Ç≥·Ç¥·Çµ·Ç∂·Ç∑·Ç∏·Çπ·Ç∫·Çª·Çº·ÇΩ·Çæ·Çø·ÉÄ·ÉÅ·ÉÇ·ÉÉ·ÉÑ·ÉÖ·Éá·Éç·è∏·èπ·è∫·èª·èº·èΩ·≤Ä·≤Å·≤Ç·≤É·≤Ñ·≤Ö·≤Ü·≤á·≤à·≤ê·≤ë·≤í·≤ì·≤î·≤ï·≤ñ·≤ó·≤ò·≤ô·≤ö·≤õ·≤ú·≤ù·≤û·≤ü·≤†·≤°·≤¢·≤£·≤§·≤•·≤¶·≤ß·≤®·≤©·≤™·≤´·≤¨·≤≠·≤Æ·≤Ø·≤∞·≤±·≤≤·≤≥·≤¥·≤µ·≤∂·≤∑·≤∏·≤π·≤∫·≤Ω·≤æ·≤ø·∏Ä·∏Ç·∏Ñ·∏Ü·∏à·∏ä·∏å·∏é·∏ê·∏í·∏î·∏ñ·∏ò·∏ö·∏ú·∏û·∏†·∏¢·∏§·∏¶·∏®·∏™·∏¨·∏Æ·∏∞·∏≤·∏¥·∏∂·∏∏·∏∫·∏º·∏æ·πÄ·πÇ·πÑ·πÜ·πà·πä·πå·πé·πê·πí·πî·πñ·πò·πö·πú·πû·π†·π¢·π§·π¶·π®·π™·π¨·πÆ·π∞·π≤·π¥·π∂·π∏·π∫·πº·πæ·∫Ä·∫Ç·∫Ñ·∫Ü·∫à·∫ä·∫å·∫é·∫ê·∫í·∫î·∫ñ·∫ó·∫ò·∫ô·∫ö·∫õ·∫û·∫û·∫†·∫¢·∫§·∫¶·∫®·∫™·∫¨·∫Æ·∫∞·∫≤·∫¥·∫∂·∫∏·∫∫·∫º·∫淪ķªÇ·ªÑ·ªÜ·ªà·ªä·ªå·ªé·ªê·ªí·ªî·ªñ·ªò·ªö·ªú·ªû·ª†·ª¢·ª§·ª¶·ª®·ª™·ª¨·ªÆ·ª∞·ª≤·ª¥·ª∂·ª∏·ª∫·ªº·ªæ·ºà·ºâ·ºä·ºã·ºå·ºç·ºé·ºè·ºò·ºô·ºö·ºõ·ºú·ºù·º®·º©·º™·º´·º¨·º≠·ºÆ·ºØ·º∏·ºπ·º∫·ºª·ºº·ºΩ·ºæ·ºø·Ωà·Ωâ·Ωä·Ωã·Ωå·Ωç·Ωê·Ωí·Ωî·Ωñ·Ωô·Ωõ·Ωù·Ωü·Ω®·Ω©·Ω™·Ω´·Ω¨·Ω≠·ΩÆ·ΩØ·æÄ·æÅ·æÇ·æÉ·æÑ·æÖ·æÜ·æá·æà·æà·æâ·æâ·æä·æä·æã·æã·æå·æå·æç·æç·æé·æé·æè·æè·æê·æë·æí·æì·æî·æï·æñ·æó·æò·æò·æô·æô·æö·æö·æõ·æõ·æú·æú·æù·æù·æû·æû·æü·æü·æ†·æ°·æ¢·æ£·æ§·æ•·æ¶·æ߷殷殷橷橷晷晷洷洷樷樷æ≠·æ≠·æÆ·æÆ·æØ·æØ·æ≤·æ≥·æ¥·æ∂·æ∑·æ∏·æπ·æ∫·æª·æº·æº·ææ·øÇ·øÉ·øÑ·øÜ·øá·øà·øâ·øä·øã·øå·øå·øí·øì·øñ·øó·øò·øô·øö·øõ·ø¢·ø£·ø§·ø¶·øß·ø®·ø©·ø™·ø´·ø¨·ø≤·ø≥·ø¥·ø∂·ø∑·ø∏·øπ·ø∫·øª·øº·øº‚Ѷ‚Ñ™‚Ñ´‚Ñ≤‚Ö†‚Ö°‚Ö¢‚Ö£‚Ö§‚Ö•‚Ö¶‚Öß‚Ö®‚Ö©‚Ö™‚Ö´‚Ö¨‚Ö≠‚ÖÆ‚ÖØ‚ÜÉ‚í∂‚í∑‚í∏‚íπ‚í∫‚򰪂íΩ‚íæ‚íø‚ìÄ‚ìÅ‚ìÇ‚ìÉ‚ìÑ‚ìÖ‚ìÜ‚ìá‚ìà‚ìâ‚ìä‚ìã‚ìå‚ìç‚ìé‚ìè‚∞Ä‚∞Å‚∞Ç‚∞É‚∞Ñ‚∞Ö‚∞Ü‚∞á‚∞à‚∞â‚∞ä‚∞ã‚∞å‚∞ç‚∞é‚∞è‚∞ê‚∞ë‚∞í‚∞ì‚∞î‚∞ï‚∞ñ‚∞ó‚∞ò‚∞ô‚∞ö‚∞õ‚∞ú‚∞ù‚∞û‚∞ü‚∞†‚∞°‚∞¢‚∞£‚∞§‚∞•‚∞¶‚∞ß‚∞®‚∞©‚∞™‚∞´‚∞¨‚∞≠‚∞Æ‚±†‚±¢‚±£‚±§‚±ß‚±©‚±´‚±≠‚±Æ‚±Ø‚±∞‚±≤‚±µ‚±æ‚±ø‚≤Ä‚≤Ç‚≤Ñ‚≤Ü‚≤à‚≤ä‚≤å‚≤é‚≤ê‚≤í‚≤î‚≤ñ‚≤ò‚≤ö‚≤ú‚≤û‚≤†‚≤¢‚≤§‚≤¶‚≤®‚≤™‚≤¨‚≤Æ‚≤∞‚≤≤‚≤¥‚≤∂‚≤∏‚≤∫‚≤º‚≤æ‚≥Ä‚≥Ç‚≥Ñ‚≥Ü‚≥à‚≥ä‚≥å‚≥é‚≥ê‚≥í‚≥î‚≥ñ‚≥ò‚≥ö‚≥ú‚≥û‚≥†‚≥¢‚≥´‚≥≠‚≥≤êêÄêêÅêêÇêêÉêêÑêêÖêêÜêêáêêàêêâêêäêêãêêåêêçêêéêêèêêêêêëêêíêêìêêîêêïêêñêêóêêòêêôêêöêêõêêúêêùêêûêêüêê†êê°êê¢êê£êê§êê•êê¶êêßêí∞êí±êí≤êí≥êí¥êíµêí∂êí∑êí∏êíπêí∫êíªêíºêíΩêíæêíøêìÄêìÅêìÇêìÉêìÑêìÖêìÜêìáêìàêìâêìäêìãêìåêìçêìéêìèêìêêìëêìíêììê≤Äê≤Åê≤Çê≤Éê≤Ñê≤Öê≤Üê≤áê≤àê≤âê≤äê≤ãê≤åê≤çê≤éê≤èê≤êê≤ëê≤íê≤ìê≤îê≤ïê≤ñê≤óê≤òê≤ôê≤öê≤õê≤úê≤ùê≤ûê≤üê≤†ê≤°ê≤¢ê≤£ê≤§ê≤•ê≤¶ê≤ßê≤®ê≤©ê≤™ê≤´ê≤¨ê≤≠ê≤Æê≤Øê≤∞ê≤±ê≤≤뢆뢰뢢뢣뢧뢕뢶ë¢ß뢮뢩뢙뢴뢨ë¢≠ë¢Æë¢Øë¢∞뢱ë¢≤ë¢≥뢥뢵ë¢∂ë¢∑ë¢∏ë¢πë¢∫뢪뢺ë¢Ωë¢æë¢øñπÄñπÅñπÇñπÉñπÑñπÖñπÜñπáñπàñπâñπäñπãñπåñπçñπéñπèñπêñπëñπíñπìñπîñπïñπññπóñπòñπôñπöñπõñπúñπùñπûñπüû§Äû§Åû§Çû§Éû§Ñû§Öû§Üû§áû§àû§âû§äû§ãû§åû§çû§éû§èû§êû§ëû§íû§ìû§îû§ïû§ñû§óû§òû§ôû§öû§õû§úû§ùû§ûû§üû§†û§°
```
### Lowercase Characters
```
abcdefghiƒ±jklmnopqrstuvwxyzŒº√†√°√¢√£√§√•√¶√ß√®√©√™√´√¨√≠√Æ√Ø√∞√±√≤√≥√¥√µ√∂√∏√π√∫√ª√º√Ω√æssƒÅƒÉƒÖƒáƒâƒãƒçƒèƒëƒìƒïƒóƒôƒõƒùƒüƒ°ƒ£ƒ•ƒßƒ©ƒ´ƒ≠ƒØiÃáiƒ≥ƒµƒ∑ƒ∫ƒºƒæ≈Ä≈Ç≈Ñ≈Ü≈à ºn≈ã≈ç≈è≈ë≈ì≈ï≈ó≈ô≈õ≈ù≈ü≈°≈£≈•≈ß≈©≈´≈≠≈Ø≈±≈≥≈µ≈∑√ø≈∫≈º≈æs…ì∆É∆Ö…î∆à…ñ…ó∆å«ù…ô…õ∆í…†…£…©…®∆ô…Ø…≤…µ∆°∆£∆• Ä∆® É∆≠ à∆∞ ä ã∆¥∆∂ í∆π∆Ω«Ü«Ü«â«â«å«å«é«ê«í«î«ñ«ò«ö«ú«ü«°«£«•«ß«©«´«≠«ØjÃå«≥«≥«µ∆ï∆ø«π«ª«Ω«ø»Å»É»Ö»á»â»ã»ç»è»ë»ì»ï»ó»ô»õ»ù»ü∆û»£»•»ß»©»´»≠»Ø»±»≥‚±•»º∆ö‚±¶…Ç∆Ä â å…á…â…ã…ç…èŒπÕ±Õ≥Õ∑œ≥Œ¨Œ≠ŒÆŒØœåœçœéŒπÃàÃÅŒ±Œ≤Œ≥Œ¥ŒµŒ∂Œ∑Œ∏ŒπŒ∫ŒªŒºŒΩŒæŒøœÄœÅœÉœÑœÖœÜœáœàœâœäœãœÖÃàÃŜɜóŒ≤Œ∏œÜœÄœôœõœùœüœ°œ£œ•œßœ©œ´œ≠œØŒ∫œÅŒ∏Œµœ∏œ≤œªÕªÕºÕΩ—ê—ë—í—ì—î—ï—ñ—ó—ò—ô—ö—õ—ú—ù—û—ü–∞–±–≤–≥–¥–µ–∂–∑–∏–π–∫–ª–º–Ω–æ–ø—Ä—Å—Ç—É—Ñ—Ö—Ü—á—à—â—ä—ã—å—ç—é—è—°—£—•—ß—©—´—≠—Ø—±—≥—µ—∑—π—ª—Ω—ø“Å“ã“ç“è“ë“ì“ï“ó“ô“õ“ù“ü“°“£“•“ß“©“´“≠“Ø“±“≥“µ“∑“𓪓ٓø”è”ǔєܔà”ä”å”é”ë”ì”ï”ó”ô”õ”ù”ü”°”£”•”ß”©”´”≠”Ø”±”≥”µ”∑”𔪔ٔø‘Å‘É‘Ö‘á‘â‘ã‘ç‘è‘ë‘ì‘ï‘ó‘ô‘õ‘ù‘ü‘°‘£‘•‘ß‘©‘´‘≠‘Ø’°’¢’£’§’•’¶’ß’®’©’™’´’¨’≠’Æ’Ø’∞’±’≤’≥’¥’µ’∂’∑’∏’π’∫’ª’º’Ω’æ’ø÷Ä÷Å÷Ç÷É÷Ñ÷Ö÷Ü’•÷Ç‚¥Ä‚¥Å‚¥Ç‚¥É‚¥Ñ‚¥Ö‚¥Ü‚¥á‚¥à‚¥â‚¥ä‚¥ã‚¥å‚¥ç‚¥é‚¥è‚¥ê‚¥ë‚¥í‚¥ì‚¥î‚¥ï‚¥ñ‚¥ó‚¥ò‚¥ô‚¥ö‚¥õ‚¥ú‚¥ù‚¥û‚¥ü‚¥†‚¥°‚¥¢‚¥£‚¥§‚¥•‚¥ß‚¥≠·è∞·è±·è≤·è≥·è¥·èµ–≤–¥–æ—Å—Ç—Ç—ä—£Íôã·Éê·Éë·Éí·Éì·Éî·Éï·Éñ·Éó·Éò·Éô·Éö·Éõ·Éú·Éù·Éû·Éü·É†·É°·É¢·É£·É§·É•·É¶·Éß·É®·É©·É™·É´·É¨·É≠·ÉÆ·ÉØ·É∞·É±·É≤·É≥·É¥·Éµ·É∂·É∑·É∏·Éπ·É∫·ÉΩ·Éæ·Éø·∏Å·∏É·∏Ö·∏á·∏â·∏ã·∏ç·∏è·∏ë·∏ì·∏ï·∏ó·∏ô·∏õ·∏ù·∏ü·∏°·∏£·∏•·∏ß·∏©·∏´·∏≠·∏Ø·∏±·∏≥·∏µ·∏∑·∏π·∏ª·∏Ω·∏ø·πÅ·πÉ·πÖ·πá·πâ·πã·πç·πè·πë·πì·πï·πó·πô·πõ·πù·πü·π°·π£·π•·πß·π©·π´·π≠·πØ·π±·π≥·πµ·π∑·ππ·πª·πΩ·πø·∫Å·∫É·∫Ö·∫á·∫â·∫ã·∫ç·∫è·∫ë·∫ì·∫ïhñtÃàwÃäyÃäa æ·π°ss√ü·∫°·∫£·∫•·∫ß·∫©·∫´·∫≠·∫Ø·∫±·∫≥·∫µ·∫∑·∫π·∫ª·∫Ω·∫ø·ªÅ·ªÉ·ªÖ·ªá·ªâ·ªã·ªç·ªè·ªë·ªì·ªï·ªó·ªô·ªõ·ªù·ªü·ª°·ª£·ª•·ªß·ª©·ª´·ª≠·ªØ·ª±·ª≥·ªµ·ª∑·ªπ·ªª·ªΩ·ªø·ºÄ·ºÅ·ºÇ·ºÉ·ºÑ·ºÖ·ºÜ·ºá·ºê·ºë·ºí·ºì·ºî·ºï·º†·º°·º¢·º£·º§·º•·º¶·ºß·º∞·º±·º≤·º≥·º¥·ºµ·º∂·º∑·ΩÄ·ΩÅ·ΩÇ·ΩÉ·ΩÑ·ΩÖœÖÃìœÖÃìÃÄœÖÃìÃÅœÖÃìÕÇ·Ωë·Ωì·Ωï·Ωó·Ω†·Ω°·Ω¢·Ω£·Ω§·Ω•·Ω¶·Ωß·ºÄŒπ·ºÅŒπ·ºÇŒπ·ºÉŒπ·ºÑŒπ·ºÖŒπ·ºÜŒπ·ºáŒπ·ºÄŒπ·æÄ·ºÅŒπ·æÅ·ºÇŒπ·æÇ·ºÉŒπ·æÉ·ºÑŒπ·æÑ·ºÖŒπ·æÖ·ºÜŒπ·æÜ·ºáŒπ·æá·º†Œπ·º°Œπ·º¢Œπ·º£Œπ·º§Œπ·º•Œπ·º¶Œπ·ºßŒπ·º†Œπ·æê·º°Œπ·æë·º¢Œπ·æí·º£Œπ·æì·º§Œπ·æî·º•Œπ·æï·º¶Œπ·æñ·ºßŒπ·æó·Ω†Œπ·Ω°Œπ·Ω¢Œπ·Ω£Œπ·Ω§Œπ·Ω•Œπ·Ω¶Œπ·Ωߌπ·Ω†Œπ·æ†·Ω°Œπ·æ°·Ω¢Œπ·æ¢·Ω£Œπ·æ£·Ω§Œπ·æ§·Ω•Œπ·æ•·Ω¶Œπ·æ¶·Ωߌπ·æß·Ω∞ŒπŒ±ŒπŒ¨ŒπŒ±ÕÇŒ±ÕÇŒπ·æ∞·æ±·Ω∞·Ω±Œ±Œπ·æ≥Œπ·Ω¥ŒπŒ∑ŒπŒÆŒπŒ∑ÕÇŒ∑ÕÇŒπ·Ω≤·Ω≥·Ω¥·ΩµŒ∑Œπ·øÉŒπÃàÃÄŒπÃàÃÅŒπÕÇŒπÃàÕÇ·øê·øë·Ω∂·Ω∑œÖÃàÃÄœÖÃàÃÅœÅÃìœÖÕÇœÖÃàÕÇ·ø†·ø°·Ω∫·Ωª·ø•·ΩºŒπœâŒπœéŒπœâÕÇœâÕÇŒπ·Ω∏·Ωπ·Ωº·ΩΩœâŒπ·ø≥œâk√•‚Öé‚Ö∞‚Ö±‚Ö≤‚Ö≥‚Ö¥‚Öµ‚Ö∂‚Ö∑‚Ö∏‚Öπ‚Ö∫‚Öª‚Öº‚ÖΩ‚Öæ‚Öø‚ÜÑ‚ìê‚ìë‚ìí‚ìì‚ìî‚ìï‚ìñ‚ìó‚ìò‚ìô‚ìö‚ìõ‚ìú‚ìù‚ìû‚ìü‚솂찂좂죂짂앂춂ì߂쮂쩂∞∞‚∞±‚∞≤‚∞≥‚∞¥‚∞µ‚∞∂‚∞∑‚∞∏‚∞π‚∞∫‚∞ª‚∞º‚∞Ω‚∞æ‚∞ø‚±Ä‚±Å‚±Ç‚±É‚±Ñ‚±Ö‚±Ü‚±á‚±à‚±â‚±ä‚±ã‚±å‚±ç‚±é‚±è‚±ê‚±ë‚±í‚±ì‚±î‚±ï‚±ñ‚±ó‚±ò‚±ô‚±ö‚±õ‚±ú‚±ù‚±û‚±°…´·µΩ…Ω‚±®‚±™‚±¨…ë…±…ê…킱≥‚±∂»ø…Ä‚≤Å‚≤É‚≤Ö‚≤á‚≤â‚≤ã‚≤ç‚≤è‚≤ë‚≤ì‚≤ï‚≤ó‚≤ô‚≤õ‚≤ù‚≤ü‚≤°‚≤£‚≤•‚≤ß‚≤©‚≤´‚≤≠‚≤Ø‚≤±‚≤≥‚≤µ‚≤∑‚≤π‚≤ª‚≤Ω‚≤ø‚≥Å‚≥É‚≥Ö‚≥á‚≥â‚≥ã‚≥ç‚≥è‚≥ë‚≥ì‚≥ï‚≥ó‚≥ô‚≥õ‚≥ù‚≥ü‚≥°‚≥£‚≥¨‚≥Æ‚≥≥êê®êê©êê™êê´êê¨êê≠êêÆêêØêê∞êê±êê≤êê≥êê¥êêµêê∂êê∑êê∏êêπêê∫êêªêêºêêΩêêæêêøêëÄêëÅêëÇêëÉêëÑêëÖêëÜêëáêëàêëâêëäêëãêëåêëçêëéêëèêìòêìôêìöêìõêìúêìùêìûêìüêì†êì°êì¢êì£êì§êì•êì¶êìßêì®êì©êì™êì´êì¨êì≠êìÆêìØêì∞êì±êì≤êì≥êì¥êìµêì∂êì∑êì∏êìπêì∫êìªê≥Äê≥Åê≥Çê≥Éê≥Ñê≥Öê≥Üê≥áê≥àê≥âê≥äê≥ãê≥åê≥çê≥éê≥èê≥êê≥ëê≥íê≥ìê≥îê≥ïê≥ñê≥óê≥òê≥ôê≥öê≥õê≥úê≥ùê≥ûê≥üê≥†ê≥°ê≥¢ê≥£ê≥§ê≥•ê≥¶ê≥ßê≥®ê≥©ê≥™ê≥´ê≥¨ê≥≠ê≥Æê≥Øê≥∞ê≥±ê≥≤ë£Äë£Åë£Çë£Éë£Ñë£Öë£Üë£áë£àë£âë£äë£ãë£åë£çë£éë£èë£êë£ëë£íë£ìë£îë£ïë£ñë£óë£òë£ôë£öë£õë£úë£ùë£ûë£üñπ†ñπ°ñπ¢ñπ£ñπ§ñπ•ñπ¶ñπßñπ®ñπ©ñπ™ñπ´ñπ¨ñπ≠ñπÆñπØñπ∞ñπ±ñπ≤ñπ≥ñπ¥ñπµñπ∂ñπ∑ñπ∏ñππñπ∫ñπªñπºñπΩñπæñπøû§¢û§£û§§û§•û§¶û§ßû§®û§©û§™û§´û§¨û§≠û§Æû§Øû§∞û§±û§≤û§≥û§¥û§µû§∂û§∑û§∏û§πû§∫û§ªû§ºû§Ωû§æû§øû•Äû•Åû•Çû•É
```
### Uppercase Codepoints
```
0041, 0042, 0043, 0044, 0045, 0046, 0047, 0048, 0049, 0049, 004A, 004B, 004C, 004D, 004E, 004F, 0050, 0051, 0052, 0053, 0054, 0055, 0056, 0057, 0058, 0059, 005A, 00B5, 00C0, 00C1, 00C2, 00C3, 00C4, 00C5, 00C6, 00C7, 00C8, 00C9, 00CA, 00CB, 00CC, 00CD, 00CE, 00CF, 00D0, 00D1, 00D2, 00D3, 00D4, 00D5, 00D6, 00D8, 00D9, 00DA, 00DB, 00DC, 00DD, 00DE, 00DF, 0100, 0102, 0104, 0106, 0108, 010A, 010C, 010E, 0110, 0112, 0114, 0116, 0118, 011A, 011C, 011E, 0120, 0122, 0124, 0126, 0128, 012A, 012C, 012E, 0130, 0130, 0132, 0134, 0136, 0139, 013B, 013D, 013F, 0141, 0143, 0145, 0147, 0149, 014A, 014C, 014E, 0150, 0152, 0154, 0156, 0158, 015A, 015C, 015E, 0160, 0162, 0164, 0166, 0168, 016A, 016C, 016E, 0170, 0172, 0174, 0176, 0178, 0179, 017B, 017D, 017F, 0181, 0182, 0184, 0186, 0187, 0189, 018A, 018B, 018E, 018F, 0190, 0191, 0193, 0194, 0196, 0197, 0198, 019C, 019D, 019F, 01A0, 01A2, 01A4, 01A6, 01A7, 01A9, 01AC, 01AE, 01AF, 01B1, 01B2, 01B3, 01B5, 01B7, 01B8, 01BC, 01C4, 01C5, 01C7, 01C8, 01CA, 01CB, 01CD, 01CF, 01D1, 01D3, 01D5, 01D7, 01D9, 01DB, 01DE, 01E0, 01E2, 01E4, 01E6, 01E8, 01EA, 01EC, 01EE, 01F0, 01F1, 01F2, 01F4, 01F6, 01F7, 01F8, 01FA, 01FC, 01FE, 0200, 0202, 0204, 0206, 0208, 020A, 020C, 020E, 0210, 0212, 0214, 0216, 0218, 021A, 021C, 021E, 0220, 0222, 0224, 0226, 0228, 022A, 022C, 022E, 0230, 0232, 023A, 023B, 023D, 023E, 0241, 0243, 0244, 0245, 0246, 0248, 024A, 024C, 024E, 0345, 0370, 0372, 0376, 037F, 0386, 0388, 0389, 038A, 038C, 038E, 038F, 0390, 0391, 0392, 0393, 0394, 0395, 0396, 0397, 0398, 0399, 039A, 039B, 039C, 039D, 039E, 039F, 03A0, 03A1, 03A3, 03A4, 03A5, 03A6, 03A7, 03A8, 03A9, 03AA, 03AB, 03B0, 03C2, 03CF, 03D0, 03D1, 03D5, 03D6, 03D8, 03DA, 03DC, 03DE, 03E0, 03E2, 03E4, 03E6, 03E8, 03EA, 03EC, 03EE, 03F0, 03F1, 03F4, 03F5, 03F7, 03F9, 03FA, 03FD, 03FE, 03FF, 0400, 0401, 0402, 0403, 0404, 0405, 0406, 0407, 0408, 0409, 040A, 040B, 040C, 040D, 040E, 040F, 0410, 0411, 0412, 0413, 0414, 0415, 0416, 0417, 0418, 0419, 041A, 041B, 041C, 041D, 041E, 041F, 0420, 0421, 0422, 0423, 0424, 0425, 0426, 0427, 0428, 0429, 042A, 042B, 042C, 042D, 042E, 042F, 0460, 0462, 0464, 0466, 0468, 046A, 046C, 046E, 0470, 0472, 0474, 0476, 0478, 047A, 047C, 047E, 0480, 048A, 048C, 048E, 0490, 0492, 0494, 0496, 0498, 049A, 049C, 049E, 04A0, 04A2, 04A4, 04A6, 04A8, 04AA, 04AC, 04AE, 04B0, 04B2, 04B4, 04B6, 04B8, 04BA, 04BC, 04BE, 04C0, 04C1, 04C3, 04C5, 04C7, 04C9, 04CB, 04CD, 04D0, 04D2, 04D4, 04D6, 04D8, 04DA, 04DC, 04DE, 04E0, 04E2, 04E4, 04E6, 04E8, 04EA, 04EC, 04EE, 04F0, 04F2, 04F4, 04F6, 04F8, 04FA, 04FC, 04FE, 0500, 0502, 0504, 0506, 0508, 050A, 050C, 050E, 0510, 0512, 0514, 0516, 0518, 051A, 051C, 051E, 0520, 0522, 0524, 0526, 0528, 052A, 052C, 052E, 0531, 0532, 0533, 0534, 0535, 0536, 0537, 0538, 0539, 053A, 053B, 053C, 053D, 053E, 053F, 0540, 0541, 0542, 0543, 0544, 0545, 0546, 0547, 0548, 0549, 054A, 054B, 054C, 054D, 054E, 054F, 0550, 0551, 0552, 0553, 0554, 0555, 0556, 0587, 10A0, 10A1, 10A2, 10A3, 10A4, 10A5, 10A6, 10A7, 10A8, 10A9, 10AA, 10AB, 10AC, 10AD, 10AE, 10AF, 10B0, 10B1, 10B2, 10B3, 10B4, 10B5, 10B6, 10B7, 10B8, 10B9, 10BA, 10BB, 10BC, 10BD, 10BE, 10BF, 10C0, 10C1, 10C2, 10C3, 10C4, 10C5, 10C7, 10CD, 13F8, 13F9, 13FA, 13FB, 13FC, 13FD, 1C80, 1C81, 1C82, 1C83, 1C84, 1C85, 1C86, 1C87, 1C88, 1C90, 1C91, 1C92, 1C93, 1C94, 1C95, 1C96, 1C97, 1C98, 1C99, 1C9A, 1C9B, 1C9C, 1C9D, 1C9E, 1C9F, 1CA0, 1CA1, 1CA2, 1CA3, 1CA4, 1CA5, 1CA6, 1CA7, 1CA8, 1CA9, 1CAA, 1CAB, 1CAC, 1CAD, 1CAE, 1CAF, 1CB0, 1CB1, 1CB2, 1CB3, 1CB4, 1CB5, 1CB6, 1CB7, 1CB8, 1CB9, 1CBA, 1CBD, 1CBE, 1CBF, 1E00, 1E02, 1E04, 1E06, 1E08, 1E0A, 1E0C, 1E0E, 1E10, 1E12, 1E14, 1E16, 1E18, 1E1A, 1E1C, 1E1E, 1E20, 1E22, 1E24, 1E26, 1E28, 1E2A, 1E2C, 1E2E, 1E30, 1E32, 1E34, 1E36, 1E38, 1E3A, 1E3C, 1E3E, 1E40, 1E42, 1E44, 1E46, 1E48, 1E4A, 1E4C, 1E4E, 1E50, 1E52, 1E54, 1E56, 1E58, 1E5A, 1E5C, 1E5E, 1E60, 1E62, 1E64, 1E66, 1E68, 1E6A, 1E6C, 1E6E, 1E70, 1E72, 1E74, 1E76, 1E78, 1E7A, 1E7C, 1E7E, 1E80, 1E82, 1E84, 1E86, 1E88, 1E8A, 1E8C, 1E8E, 1E90, 1E92, 1E94, 1E96, 1E97, 1E98, 1E99, 1E9A, 1E9B, 1E9E, 1E9E, 1EA0, 1EA2, 1EA4, 1EA6, 1EA8, 1EAA, 1EAC, 1EAE, 1EB0, 1EB2, 1EB4, 1EB6, 1EB8, 1EBA, 1EBC, 1EBE, 1EC0, 1EC2, 1EC4, 1EC6, 1EC8, 1ECA, 1ECC, 1ECE, 1ED0, 1ED2, 1ED4, 1ED6, 1ED8, 1EDA, 1EDC, 1EDE, 1EE0, 1EE2, 1EE4, 1EE6, 1EE8, 1EEA, 1EEC, 1EEE, 1EF0, 1EF2, 1EF4, 1EF6, 1EF8, 1EFA, 1EFC, 1EFE, 1F08, 1F09, 1F0A, 1F0B, 1F0C, 1F0D, 1F0E, 1F0F, 1F18, 1F19, 1F1A, 1F1B, 1F1C, 1F1D, 1F28, 1F29, 1F2A, 1F2B, 1F2C, 1F2D, 1F2E, 1F2F, 1F38, 1F39, 1F3A, 1F3B, 1F3C, 1F3D, 1F3E, 1F3F, 1F48, 1F49, 1F4A, 1F4B, 1F4C, 1F4D, 1F50, 1F52, 1F54, 1F56, 1F59, 1F5B, 1F5D, 1F5F, 1F68, 1F69, 1F6A, 1F6B, 1F6C, 1F6D, 1F6E, 1F6F, 1F80, 1F81, 1F82, 1F83, 1F84, 1F85, 1F86, 1F87, 1F88, 1F88, 1F89, 1F89, 1F8A, 1F8A, 1F8B, 1F8B, 1F8C, 1F8C, 1F8D, 1F8D, 1F8E, 1F8E, 1F8F, 1F8F, 1F90, 1F91, 1F92, 1F93, 1F94, 1F95, 1F96, 1F97, 1F98, 1F98, 1F99, 1F99, 1F9A, 1F9A, 1F9B, 1F9B, 1F9C, 1F9C, 1F9D, 1F9D, 1F9E, 1F9E, 1F9F, 1F9F, 1FA0, 1FA1, 1FA2, 1FA3, 1FA4, 1FA5, 1FA6, 1FA7, 1FA8, 1FA8, 1FA9, 1FA9, 1FAA, 1FAA, 1FAB, 1FAB, 1FAC, 1FAC, 1FAD, 1FAD, 1FAE, 1FAE, 1FAF, 1FAF, 1FB2, 1FB3, 1FB4, 1FB6, 1FB7, 1FB8, 1FB9, 1FBA, 1FBB, 1FBC, 1FBC, 1FBE, 1FC2, 1FC3, 1FC4, 1FC6, 1FC7, 1FC8, 1FC9, 1FCA, 1FCB, 1FCC, 1FCC, 1FD2, 1FD3, 1FD6, 1FD7, 1FD8, 1FD9, 1FDA, 1FDB, 1FE2, 1FE3, 1FE4, 1FE6, 1FE7, 1FE8, 1FE9, 1FEA, 1FEB, 1FEC, 1FF2, 1FF3, 1FF4, 1FF6, 1FF7, 1FF8, 1FF9, 1FFA, 1FFB, 1FFC, 1FFC, 2126, 212A, 212B, 2132, 2160, 2161, 2162, 2163, 2164, 2165, 2166, 2167, 2168, 2169, 216A, 216B, 216C, 216D, 216E, 216F, 2183, 24B6, 24B7, 24B8, 24B9, 24BA, 24BB, 24BC, 24BD, 24BE, 24BF, 24C0, 24C1, 24C2, 24C3, 24C4, 24C5, 24C6, 24C7, 24C8, 24C9, 24CA, 24CB, 24CC, 24CD, 24CE, 24CF, 2C00, 2C01, 2C02, 2C03, 2C04, 2C05, 2C06, 2C07, 2C08, 2C09, 2C0A, 2C0B, 2C0C, 2C0D, 2C0E, 2C0F, 2C10, 2C11, 2C12, 2C13, 2C14, 2C15, 2C16, 2C17, 2C18, 2C19, 2C1A, 2C1B, 2C1C, 2C1D, 2C1E, 2C1F, 2C20, 2C21, 2C22, 2C23, 2C24, 2C25, 2C26, 2C27, 2C28, 2C29, 2C2A, 2C2B, 2C2C, 2C2D, 2C2E, 2C60, 2C62, 2C63, 2C64, 2C67, 2C69, 2C6B, 2C6D, 2C6E, 2C6F, 2C70, 2C72, 2C75, 2C7E, 2C7F, 2C80, 2C82, 2C84, 2C86, 2C88, 2C8A, 2C8C, 2C8E, 2C90, 2C92, 2C94, 2C96, 2C98, 2C9A, 2C9C, 2C9E, 2CA0, 2CA2, 2CA4, 2CA6, 2CA8, 2CAA, 2CAC, 2CAE, 2CB0, 2CB2, 2CB4, 2CB6, 2CB8, 2CBA, 2CBC, 2CBE, 2CC0, 2CC2, 2CC4, 2CC6, 2CC8, 2CCA, 2CCC, 2CCE, 2CD0, 2CD2, 2CD4, 2CD6, 2CD8, 2CDA, 2CDC, 2CDE, 2CE0, 2CE2, 2CEB, 2CED, 2CF2, 10400, 10401, 10402, 10403, 10404, 10405, 10406, 10407, 10408, 10409, 1040A, 1040B, 1040C, 1040D, 1040E, 1040F, 10410, 10411, 10412, 10413, 10414, 10415, 10416, 10417, 10418, 10419, 1041A, 1041B, 1041C, 1041D, 1041E, 1041F, 10420, 10421, 10422, 10423, 10424, 10425, 10426, 10427, 104B0, 104B1, 104B2, 104B3, 104B4, 104B5, 104B6, 104B7, 104B8, 104B9, 104BA, 104BB, 104BC, 104BD, 104BE, 104BF, 104C0, 104C1, 104C2, 104C3, 104C4, 104C5, 104C6, 104C7, 104C8, 104C9, 104CA, 104CB, 104CC, 104CD, 104CE, 104CF, 104D0, 104D1, 104D2, 104D3, 10C80, 10C81, 10C82, 10C83, 10C84, 10C85, 10C86, 10C87, 10C88, 10C89, 10C8A, 10C8B, 10C8C, 10C8D, 10C8E, 10C8F, 10C90, 10C91, 10C92, 10C93, 10C94, 10C95, 10C96, 10C97, 10C98, 10C99, 10C9A, 10C9B, 10C9C, 10C9D, 10C9E, 10C9F, 10CA0, 10CA1, 10CA2, 10CA3, 10CA4, 10CA5, 10CA6, 10CA7, 10CA8, 10CA9, 10CAA, 10CAB, 10CAC, 10CAD, 10CAE, 10CAF, 10CB0, 10CB1, 10CB2, 118A0, 118A1, 118A2, 118A3, 118A4, 118A5, 118A6, 118A7, 118A8, 118A9, 118AA, 118AB, 118AC, 118AD, 118AE, 118AF, 118B0, 118B1, 118B2, 118B3, 118B4, 118B5, 118B6, 118B7, 118B8, 118B9, 118BA, 118BB, 118BC, 118BD, 118BE, 118BF, 16E40, 16E41, 16E42, 16E43, 16E44, 16E45, 16E46, 16E47, 16E48, 16E49, 16E4A, 16E4B, 16E4C, 16E4D, 16E4E, 16E4F, 16E50, 16E51, 16E52, 16E53, 16E54, 16E55, 16E56, 16E57, 16E58, 16E59, 16E5A, 16E5B, 16E5C, 16E5D, 16E5E, 16E5F, 1E900, 1E901, 1E902, 1E903, 1E904, 1E905, 1E906, 1E907, 1E908, 1E909, 1E90A, 1E90B, 1E90C, 1E90D, 1E90E, 1E90F, 1E910, 1E911, 1E912, 1E913, 1E914, 1E915, 1E916, 1E917, 1E918, 1E919, 1E91A, 1E91B, 1E91C, 1E91D, 1E91E, 1E91F, 1E920, 1E921
```
### Lowercase Codepoints
```
0061, 0062, 0063, 0064, 0065, 0066, 0067, 0068, 0069, 0131, 006A, 006B, 006C, 006D, 006E, 006F, 0070, 0071, 0072, 0073, 0074, 0075, 0076, 0077, 0078, 0079, 007A, 03BC, 00E0, 00E1, 00E2, 00E3, 00E4, 00E5, 00E6, 00E7, 00E8, 00E9, 00EA, 00EB, 00EC, 00ED, 00EE, 00EF, 00F0, 00F1, 00F2, 00F3, 00F4, 00F5, 00F6, 00F8, 00F9, 00FA, 00FB, 00FC, 00FD, 00FE, 0073 0073, 0101, 0103, 0105, 0107, 0109, 010B, 010D, 010F, 0111, 0113, 0115, 0117, 0119, 011B, 011D, 011F, 0121, 0123, 0125, 0127, 0129, 012B, 012D, 012F, 0069 0307, 0069, 0133, 0135, 0137, 013A, 013C, 013E, 0140, 0142, 0144, 0146, 0148, 02BC 006E, 014B, 014D, 014F, 0151, 0153, 0155, 0157, 0159, 015B, 015D, 015F, 0161, 0163, 0165, 0167, 0169, 016B, 016D, 016F, 0171, 0173, 0175, 0177, 00FF, 017A, 017C, 017E, 0073, 0253, 0183, 0185, 0254, 0188, 0256, 0257, 018C, 01DD, 0259, 025B, 0192, 0260, 0263, 0269, 0268, 0199, 026F, 0272, 0275, 01A1, 01A3, 01A5, 0280, 01A8, 0283, 01AD, 0288, 01B0, 028A, 028B, 01B4, 01B6, 0292, 01B9, 01BD, 01C6, 01C6, 01C9, 01C9, 01CC, 01CC, 01CE, 01D0, 01D2, 01D4, 01D6, 01D8, 01DA, 01DC, 01DF, 01E1, 01E3, 01E5, 01E7, 01E9, 01EB, 01ED, 01EF, 006A 030C, 01F3, 01F3, 01F5, 0195, 01BF, 01F9, 01FB, 01FD, 01FF, 0201, 0203, 0205, 0207, 0209, 020B, 020D, 020F, 0211, 0213, 0215, 0217, 0219, 021B, 021D, 021F, 019E, 0223, 0225, 0227, 0229, 022B, 022D, 022F, 0231, 0233, 2C65, 023C, 019A, 2C66, 0242, 0180, 0289, 028C, 0247, 0249, 024B, 024D, 024F, 03B9, 0371, 0373, 0377, 03F3, 03AC, 03AD, 03AE, 03AF, 03CC, 03CD, 03CE, 03B9 0308 0301, 03B1, 03B2, 03B3, 03B4, 03B5, 03B6, 03B7, 03B8, 03B9, 03BA, 03BB, 03BC, 03BD, 03BE, 03BF, 03C0, 03C1, 03C3, 03C4, 03C5, 03C6, 03C7, 03C8, 03C9, 03CA, 03CB, 03C5 0308 0301, 03C3, 03D7, 03B2, 03B8, 03C6, 03C0, 03D9, 03DB, 03DD, 03DF, 03E1, 03E3, 03E5, 03E7, 03E9, 03EB, 03ED, 03EF, 03BA, 03C1, 03B8, 03B5, 03F8, 03F2, 03FB, 037B, 037C, 037D, 0450, 0451, 0452, 0453, 0454, 0455, 0456, 0457, 0458, 0459, 045A, 045B, 045C, 045D, 045E, 045F, 0430, 0431, 0432, 0433, 0434, 0435, 0436, 0437, 0438, 0439, 043A, 043B, 043C, 043D, 043E, 043F, 0440, 0441, 0442, 0443, 0444, 0445, 0446, 0447, 0448, 0449, 044A, 044B, 044C, 044D, 044E, 044F, 0461, 0463, 0465, 0467, 0469, 046B, 046D, 046F, 0471, 0473, 0475, 0477, 0479, 047B, 047D, 047F, 0481, 048B, 048D, 048F, 0491, 0493, 0495, 0497, 0499, 049B, 049D, 049F, 04A1, 04A3, 04A5, 04A7, 04A9, 04AB, 04AD, 04AF, 04B1, 04B3, 04B5, 04B7, 04B9, 04BB, 04BD, 04BF, 04CF, 04C2, 04C4, 04C6, 04C8, 04CA, 04CC, 04CE, 04D1, 04D3, 04D5, 04D7, 04D9, 04DB, 04DD, 04DF, 04E1, 04E3, 04E5, 04E7, 04E9, 04EB, 04ED, 04EF, 04F1, 04F3, 04F5, 04F7, 04F9, 04FB, 04FD, 04FF, 0501, 0503, 0505, 0507, 0509, 050B, 050D, 050F, 0511, 0513, 0515, 0517, 0519, 051B, 051D, 051F, 0521, 0523, 0525, 0527, 0529, 052B, 052D, 052F, 0561, 0562, 0563, 0564, 0565, 0566, 0567, 0568, 0569, 056A, 056B, 056C, 056D, 056E, 056F, 0570, 0571, 0572, 0573, 0574, 0575, 0576, 0577, 0578, 0579, 057A, 057B, 057C, 057D, 057E, 057F, 0580, 0581, 0582, 0583, 0584, 0585, 0586, 0565 0582, 2D00, 2D01, 2D02, 2D03, 2D04, 2D05, 2D06, 2D07, 2D08, 2D09, 2D0A, 2D0B, 2D0C, 2D0D, 2D0E, 2D0F, 2D10, 2D11, 2D12, 2D13, 2D14, 2D15, 2D16, 2D17, 2D18, 2D19, 2D1A, 2D1B, 2D1C, 2D1D, 2D1E, 2D1F, 2D20, 2D21, 2D22, 2D23, 2D24, 2D25, 2D27, 2D2D, 13F0, 13F1, 13F2, 13F3, 13F4, 13F5, 0432, 0434, 043E, 0441, 0442, 0442, 044A, 0463, A64B, 10D0, 10D1, 10D2, 10D3, 10D4, 10D5, 10D6, 10D7, 10D8, 10D9, 10DA, 10DB, 10DC, 10DD, 10DE, 10DF, 10E0, 10E1, 10E2, 10E3, 10E4, 10E5, 10E6, 10E7, 10E8, 10E9, 10EA, 10EB, 10EC, 10ED, 10EE, 10EF, 10F0, 10F1, 10F2, 10F3, 10F4, 10F5, 10F6, 10F7, 10F8, 10F9, 10FA, 10FD, 10FE, 10FF, 1E01, 1E03, 1E05, 1E07, 1E09, 1E0B, 1E0D, 1E0F, 1E11, 1E13, 1E15, 1E17, 1E19, 1E1B, 1E1D, 1E1F, 1E21, 1E23, 1E25, 1E27, 1E29, 1E2B, 1E2D, 1E2F, 1E31, 1E33, 1E35, 1E37, 1E39, 1E3B, 1E3D, 1E3F, 1E41, 1E43, 1E45, 1E47, 1E49, 1E4B, 1E4D, 1E4F, 1E51, 1E53, 1E55, 1E57, 1E59, 1E5B, 1E5D, 1E5F, 1E61, 1E63, 1E65, 1E67, 1E69, 1E6B, 1E6D, 1E6F, 1E71, 1E73, 1E75, 1E77, 1E79, 1E7B, 1E7D, 1E7F, 1E81, 1E83, 1E85, 1E87, 1E89, 1E8B, 1E8D, 1E8F, 1E91, 1E93, 1E95, 0068 0331, 0074 0308, 0077 030A, 0079 030A, 0061 02BE, 1E61, 0073 0073, 00DF, 1EA1, 1EA3, 1EA5, 1EA7, 1EA9, 1EAB, 1EAD, 1EAF, 1EB1, 1EB3, 1EB5, 1EB7, 1EB9, 1EBB, 1EBD, 1EBF, 1EC1, 1EC3, 1EC5, 1EC7, 1EC9, 1ECB, 1ECD, 1ECF, 1ED1, 1ED3, 1ED5, 1ED7, 1ED9, 1EDB, 1EDD, 1EDF, 1EE1, 1EE3, 1EE5, 1EE7, 1EE9, 1EEB, 1EED, 1EEF, 1EF1, 1EF3, 1EF5, 1EF7, 1EF9, 1EFB, 1EFD, 1EFF, 1F00, 1F01, 1F02, 1F03, 1F04, 1F05, 1F06, 1F07, 1F10, 1F11, 1F12, 1F13, 1F14, 1F15, 1F20, 1F21, 1F22, 1F23, 1F24, 1F25, 1F26, 1F27, 1F30, 1F31, 1F32, 1F33, 1F34, 1F35, 1F36, 1F37, 1F40, 1F41, 1F42, 1F43, 1F44, 1F45, 03C5 0313, 03C5 0313 0300, 03C5 0313 0301, 03C5 0313 0342, 1F51, 1F53, 1F55, 1F57, 1F60, 1F61, 1F62, 1F63, 1F64, 1F65, 1F66, 1F67, 1F00 03B9, 1F01 03B9, 1F02 03B9, 1F03 03B9, 1F04 03B9, 1F05 03B9, 1F06 03B9, 1F07 03B9, 1F00 03B9, 1F80, 1F01 03B9, 1F81, 1F02 03B9, 1F82, 1F03 03B9, 1F83, 1F04 03B9, 1F84, 1F05 03B9, 1F85, 1F06 03B9, 1F86, 1F07 03B9, 1F87, 1F20 03B9, 1F21 03B9, 1F22 03B9, 1F23 03B9, 1F24 03B9, 1F25 03B9, 1F26 03B9, 1F27 03B9, 1F20 03B9, 1F90, 1F21 03B9, 1F91, 1F22 03B9, 1F92, 1F23 03B9, 1F93, 1F24 03B9, 1F94, 1F25 03B9, 1F95, 1F26 03B9, 1F96, 1F27 03B9, 1F97, 1F60 03B9, 1F61 03B9, 1F62 03B9, 1F63 03B9, 1F64 03B9, 1F65 03B9, 1F66 03B9, 1F67 03B9, 1F60 03B9, 1FA0, 1F61 03B9, 1FA1, 1F62 03B9, 1FA2, 1F63 03B9, 1FA3, 1F64 03B9, 1FA4, 1F65 03B9, 1FA5, 1F66 03B9, 1FA6, 1F67 03B9, 1FA7, 1F70 03B9, 03B1 03B9, 03AC 03B9, 03B1 0342, 03B1 0342 03B9, 1FB0, 1FB1, 1F70, 1F71, 03B1 03B9, 1FB3, 03B9, 1F74 03B9, 03B7 03B9, 03AE 03B9, 03B7 0342, 03B7 0342 03B9, 1F72, 1F73, 1F74, 1F75, 03B7 03B9, 1FC3, 03B9 0308 0300, 03B9 0308 0301, 03B9 0342, 03B9 0308 0342, 1FD0, 1FD1, 1F76, 1F77, 03C5 0308 0300, 03C5 0308 0301, 03C1 0313, 03C5 0342, 03C5 0308 0342, 1FE0, 1FE1, 1F7A, 1F7B, 1FE5, 1F7C 03B9, 03C9 03B9, 03CE 03B9, 03C9 0342, 03C9 0342 03B9, 1F78, 1F79, 1F7C, 1F7D, 03C9 03B9, 1FF3, 03C9, 006B, 00E5, 214E, 2170, 2171, 2172, 2173, 2174, 2175, 2176, 2177, 2178, 2179, 217A, 217B, 217C, 217D, 217E, 217F, 2184, 24D0, 24D1, 24D2, 24D3, 24D4, 24D5, 24D6, 24D7, 24D8, 24D9, 24DA, 24DB, 24DC, 24DD, 24DE, 24DF, 24E0, 24E1, 24E2, 24E3, 24E4, 24E5, 24E6, 24E7, 24E8, 24E9, 2C30, 2C31, 2C32, 2C33, 2C34, 2C35, 2C36, 2C37, 2C38, 2C39, 2C3A, 2C3B, 2C3C, 2C3D, 2C3E, 2C3F, 2C40, 2C41, 2C42, 2C43, 2C44, 2C45, 2C46, 2C47, 2C48, 2C49, 2C4A, 2C4B, 2C4C, 2C4D, 2C4E, 2C4F, 2C50, 2C51, 2C52, 2C53, 2C54, 2C55, 2C56, 2C57, 2C58, 2C59, 2C5A, 2C5B, 2C5C, 2C5D, 2C5E, 2C61, 026B, 1D7D, 027D, 2C68, 2C6A, 2C6C, 0251, 0271, 0250, 0252, 2C73, 2C76, 023F, 0240, 2C81, 2C83, 2C85, 2C87, 2C89, 2C8B, 2C8D, 2C8F, 2C91, 2C93, 2C95, 2C97, 2C99, 2C9B, 2C9D, 2C9F, 2CA1, 2CA3, 2CA5, 2CA7, 2CA9, 2CAB, 2CAD, 2CAF, 2CB1, 2CB3, 2CB5, 2CB7, 2CB9, 2CBB, 2CBD, 2CBF, 2CC1, 2CC3, 2CC5, 2CC7, 2CC9, 2CCB, 2CCD, 2CCF, 2CD1, 2CD3, 2CD5, 2CD7, 2CD9, 2CDB, 2CDD, 2CDF, 2CE1, 2CE3, 2CEC, 2CEE, 2CF3, 10428, 10429, 1042A, 1042B, 1042C, 1042D, 1042E, 1042F, 10430, 10431, 10432, 10433, 10434, 10435, 10436, 10437, 10438, 10439, 1043A, 1043B, 1043C, 1043D, 1043E, 1043F, 10440, 10441, 10442, 10443, 10444, 10445, 10446, 10447, 10448, 10449, 1044A, 1044B, 1044C, 1044D, 1044E, 1044F, 104D8, 104D9, 104DA, 104DB, 104DC, 104DD, 104DE, 104DF, 104E0, 104E1, 104E2, 104E3, 104E4, 104E5, 104E6, 104E7, 104E8, 104E9, 104EA, 104EB, 104EC, 104ED, 104EE, 104EF, 104F0, 104F1, 104F2, 104F3, 104F4, 104F5, 104F6, 104F7, 104F8, 104F9, 104FA, 104FB, 10CC0, 10CC1, 10CC2, 10CC3, 10CC4, 10CC5, 10CC6, 10CC7, 10CC8, 10CC9, 10CCA, 10CCB, 10CCC, 10CCD, 10CCE, 10CCF, 10CD0, 10CD1, 10CD2, 10CD3, 10CD4, 10CD5, 10CD6, 10CD7, 10CD8, 10CD9, 10CDA, 10CDB, 10CDC, 10CDD, 10CDE, 10CDF, 10CE0, 10CE1, 10CE2, 10CE3, 10CE4, 10CE5, 10CE6, 10CE7, 10CE8, 10CE9, 10CEA, 10CEB, 10CEC, 10CED, 10CEE, 10CEF, 10CF0, 10CF1, 10CF2, 118C0, 118C1, 118C2, 118C3, 118C4, 118C5, 118C6, 118C7, 118C8, 118C9, 118CA, 118CB, 118CC, 118CD, 118CE, 118CF, 118D0, 118D1, 118D2, 118D3, 118D4, 118D5, 118D6, 118D7, 118D8, 118D9, 118DA, 118DB, 118DC, 118DD, 118DE, 118DF, 16E60, 16E61, 16E62, 16E63, 16E64, 16E65, 16E66, 16E67, 16E68, 16E69, 16E6A, 16E6B, 16E6C, 16E6D, 16E6E, 16E6F, 16E70, 16E71, 16E72, 16E73, 16E74, 16E75, 16E76, 16E77, 16E78, 16E79, 16E7A, 16E7B, 16E7C, 16E7D, 16E7E, 16E7F, 1E922, 1E923, 1E924, 1E925, 1E926, 1E927, 1E928, 1E929, 1E92A, 1E92B, 1E92C, 1E92D, 1E92E, 1E92F, 1E930, 1E931, 1E932, 1E933, 1E934, 1E935, 1E936, 1E937, 1E938, 1E939, 1E93A, 1E93B, 1E93C, 1E93D, 1E93E, 1E93F, 1E940, 1E941, 1E942, 1E943
```
[Answer]
# perl -p, 37 bytes
```
goto Aa_;A_:$_="\U$_";a_:$_=lc$_;Aa_:
```
[Try it online!](https://tio.run/##K0gtyjH9/z89vyRfwTEx3tox3kol3lYpJlQlXsk6EczJSVYBigPZ//97pObk5OsolOcX5aT8yy8oyczPK/6vWwAA "Perl 5 – Try It Online")
Removing all lowercase letters leaves:
```
A_;A_:$_="\U$_";_:$_=$_;A_:
```
[Try it online!](https://tio.run/##K0gtyjH9/1/BMd7aMd5KJd5WKSZUJV7JGsxWAQv@/@@RmpOTr6NQnl@Uk/Ivv6AkMz@v@L9uAQA "Perl 5 – Try It Online")
Removing the upper case letters leaves:
```
goto a_;_:$_="\$_";a_:$_=lc$_;a_:
```
[Try it online!](https://tio.run/##K0gtyjH9/z89vyRfITHeOt5KJd5WKUYlXsk6EczOSVaJBzH///dIzcnJ11Eozy/KSfmXX1CSmZ9X/F@3AAA "Perl 5 – Try It Online")
How it works? With nothing removed, control jumps to the end, leaving the input unmodified.
With the lowercase letters removed, we have the string `A_` in void context (nothing happens), and then at label `A_`, we upper case the string, at label `_`, we have a no-op (assigning `$_` to itself), and an empty statement at label `A_`. Finally, the result is printed.
With the upper case letters removed, we jump to label `a_`, which lower cases the string, and the result is printed.
[Answer]
# [Perl 5](https://www.perl.org/) + `-p`, 20 bytes
```
$_=0xE0?$_:lc"\lU$_"
```
[Try it online!](https://tio.run/##K0gtyjH9/18l3tagwtXAXiXeKidZKSYnVCVe6f9/j9ScnHwdhfD8opwUxX/5BSWZ@XnF/3ULAA "Perl 5 – Try It Online")
[With all uppercase removed.](https://tio.run/##K0gtyjH9/18l3tagwsBeJd4qJ1kpJkclXun/f4/UnJx8HYXw/KKcFMV/@QUlmfl5xf91CwA "Perl 5 – Try It Online")
[With all lowercase removed.](https://tio.run/##K0gtyjH9/18l3tbA1cBeJd5KKSZUJV7p/3@P1JycfB2F8PyinBTFf/kFJZn5ecX/dQsA "Perl 5 – Try It Online")
## Explanation
Because we're using the `-p` flag, the input is placed in`$_` implicitly and `$_` is printed implicitly when the program terminates.
In the unmodified program, this checks `0xE0`, which is `224`, for truthiness and sets `$_` to itself.
When all uppercase characters are removed `0xE0` becomes `0x0` which is `0` and the else block is reached which sets `$_` to `lc"\l$_"`. `lc` is Perl's lowercase function and converts the string to lowercase. `\l` is a string modifier that changes the immediately following character to lowercase, but this is irrelevant since it'll be lowered by the function call anyway.
When all lowercase characters are removed, `0xE0` becomes `0E0` which is `0` again, hitting the else block. Here we set `$_` to `"\U$_"`. `\U` is a strong modifier that makes the following part of the string uppercase.
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 14 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?") ([SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set"))
Anonymous tacit prefix function. Unmodified function:
```
'AAb'≢⍛⊃⊂,⍨⌊⍮⌈
```
Leaves argument untouched: [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/X93RMUn9UeeiR72zH3U1P@pq0nnUu@JRT9ej3nWPejr@pz1qm/Cotw8k1bvmUe@WQ@uNH7VNfNQ3NTjIGUiGeHgG/09TUPdIzcnJ11Eozy/KSVFUBwA "APL (Dyalog Extended) – Try It Online")
Without lowercase letters:
```
'AA'≢⍛⊃⊂,⍨⌊⍮⌈
```
Uppercase argument: [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/X93RUf1R56JHvbMfdTU/6mrSedS74lFP16PedY96Ov6nPWqb8Ki3DyTVu@ZR75ZD640ftU181Dc1OMgZSIZ4eAb/T1NQ90jNycnXUSjPL8pJUVQHAA "APL (Dyalog Extended) – Try It Online")
Without uppercase letters:
```
'b'≢⍛⊃⊂,⍨⌊⍮⌈
```
Lowercases letters: [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/Xz1J/VHnoke9sx91NT/qatJ51LviUU/Xo951j3o6/qc9apvwqLcPJNW75lHvlkPrjR@1TXzUNzU4yBlIhnh4Bv9PU1D3SM3JyddRKM8vyklRVAcA "APL (Dyalog Extended) – Try It Online")
---
`‚åà`‚ÄÉthe uppercased argument; `"HELLO, WORLD!"`
`⍮` pair to:
‚ÄÉ`‚åä`‚ÄÉthe lowercased argument; `[hello, world!","HELLO, WORLD!"]`
`,‚ç®`‚ÄÉappend:
 `⊂` the entire argument; `[hello, world!","HELLO, WORLD!","Hello, world!"]`
`⊃` pick element number:
 `≢⍛` the length of:
‚ÄÉ‚ÄÉ`'AAb'`/`'AA'`/`'b'`‚ÄÉthese three strings, i.e. number 3/2/1
[Answer]
## Javascript 192 characters (without `\123` literals)
```
$=>'Aa'[1]?$:'a'?$['to\u004cower\u0043ase']():
z/A/g&&([,A,,S,E,,O,,,,C]=!1+{},[T,R]=!0+$,[U,N,,,,I]=1[0]+$,$[T+O+'U'+1199331[T+O+'S'+T+R+I+N+($[C+O+N+S+T+R+U+C+T+O+R]+$)[14]](36)+'C'+A+S+E]())
```
## Javascript 197 characters (without `\123` literals)
```
$=>'Aa'[1]?$:'a'?$['to\u004cower\u0043ase']():
z/A/g&&([,O,,,E,C]={}+$,[,A,,S]=!1+$,[T,R]=!0+$,[U,N,,,,I]=1[0]+$,$[T+O+'U'+1199331[T+O+'S'+T+R+I+N+($[C+O+N+S+T+R+U+C+T+O+R]+$)[14]](36)+'C'+A+S+E]())
```
## Javascript 204 ~~208~~ ~~226~~ ~~234~~ characters (without `\123` numeric literals)
```
$=>'Aa'[1]?$:'a'?$['to\u004cower\u0043ase']():
a/A/g&&([,O,,,E,C]=JSON+$,[,A,,S]=!1+$,[T,R]=!0+$,[U,N,,,,I]=1[0]+$,P=25[T+O+'S'+T+R+I+N+($[C+O+N+S+T+R+U+C+T+O+R]+$)[14]](36),$[T+O+'U'+P+P+E+R+'C'+A+S+E]())
```
```
r=
$=>'Aa'[1]?$:'a'?$['to\u004cower\u0043ase']():z/A/g&&([,A,,S,E,,O,,,,C]=!1+{},[T,R]=!0+$,[U,N,,,,I]=1[0]+$,$[T+O+'U'+1199331[T+O+'S'+T+R+I+N+($[C+O+N+S+T+R+U+C+T+O+R]+$)[14]](36)+'C'+A+S+E]())
console.log(eval(String(r))('Sentence Case'));
console.log(eval(String(r).replace(/[A-Z]/g, ''))('Lower Case'));
console.log(eval(String(r).replace(/[a-z]/g, ''))('Upper Case'));
```
I didn't realise that you could make arbitrary characters with `\123`. It's a much more interesting challenge without :)
A couple of comments:
* Some of the concepts are inspired by JSFuck, although the constraints are different. There is fortunately one global object whose name is entirely upper case letters, JSON, so we can directly harvest quite a few letters from `[object JSON]`
* Other letters come from `true`, `false` and `undefined`. We take the letters we need to write `constructor`, which then means we can find the string representation of a random string's constructor, which starts `function String() {...`
* That `g` is the last ingredient we need to then form the method name `toString()`, which in base 36 lets us turn any number into an equivalent lowercase letter.
The only other thing of note here is that once we remove all the uppercase letters from this branch path, it's not syntactically correct. So we turn it all into a `//` comment with a regex `/A/g` which turns into a comment. We end up with three completely different syntaxes for the three modes:
* No removals: `a/A/g&&(...` one undefined variable divided by another by another.
* Remove lower case: `/A/&&(...` a regex (always truthy) and the rest of the expression
* Remove upper case: `a//g&&...` an undefined variable and a comment.
## Javascript 272 characters
```
$=>'Aa'=='\u0041\u0061'?$:'a'=='\u0061'?eval('$.to\u0055pper\u0043ase()'):(
[,O,,,E,C]=JSON+'',
[,A,,S]=(''+!1),
[T,R]=(''+!0),
[U,N,,,,I]=(''+1[0]),
Ka=Ca+Oa+Na+Sa+Ta+Ra+Ua+Ca+Ta+Oa+Ra,
Ga=(''[Ka]+'')[14],
$[Ta+Oa+'L'+Oa+(32)[Ta+Oa+'S'+Ta+Ra+Ia+Na+Ga](36)+Ea+Ra+'C'+Aa+Sa+Ea]())
```
(Linebreaks inserted for readability)
Room to golf, but pretty excited that it even works. Took a lot of inspiration from JSFuck.
Whoops, I realised I got the functionality backwards: when you remove uppercase letters it uppercases, etc.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~20~~ 9 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
Byte-count more than halved (-11) thanks to *@Dorian*!
Full program:
```
lIq.•L•.V
```
[Try it online.](https://tio.run/##yy9OTMpM/f8/x7NQ71HDIh8g1gv7/98jNScnX0ehPL8oJ0URAA)
With uppercase characters removed; outputting in lowercase:
```
lq.••.
```
[Try it online.](https://tio.run/##yy9OTMpM/f8/p1DvUcMiINL7/98jNScnX0ehPL8oJ0URAA)
With lowercase characters removed; outputting in uppercase:
```
I.•L•.V
```
[Try it online.](https://tio.run/##yy9OTMpM/f/fU@9RwyIfINYL@//fIzUnJ19HoTy/KCdFEQA)
**Explanation:**
```
# Full program:
l # Lowercase the (implicit) input
I # Push the input again
q # Stop the program, after which the top of the stack is output implicitly
.•L•.V # No-ops
# Program with uppercase characters removed:
l # Lowercase the (implicit) input
q # Stop the program, after which the top of the stack is output implicitly
.••. # No-ops
# Program with lowercase characters removed:
I # Push the input
.•L• # Push compressed string "u"
.V # Evaluate/execute it as 05AB1E code; uppercase the (implicit) input
# (after which the result is output implicitly)
```
[See this 05AB1E tip of mine (section *How to compress strings not part of the dictionary?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `.•L•` is `"u"`.
[Answer]
# Bash, 107 characters
```
cC=echoECHO
cC=${cC,,}
cC=${cC::4}
[ c ]||cC+=(${@^^})
[ C ]||cC+=(${@,,})
[[ cC = ?? ]]&&cC+=($@)
${cC[@]}
```
[Try it online!](https://tio.run/##lY8/b8IwFMR3f4orijBRk06dorhEspDYGDp0iIwUHLeJZHDkGDpAPntq6J80qJXa7fneu7ufN0Vb9bJweICx9Uu9K/RdWyFN6WL1SHvJmZKVWfDlivg5OEoeRd3nmCT3HckhIU4nyW/ZLDhm63UXeo1/17zFa/6Qg2E@hxDT6fsuC8k5KM9E1/tCQs5toHEcM5Z/EaGVtm4cEuz9yymrSgjG/BUlG/@BEfokyCZXOfumUVYWrYJWzttbWLU1B5/ybM0WrlJDgzS7g7KuhTPQ5vXDN2pLZ3AWcQmaJ5foRFCkI4jwJ4wh7n8YA/6vGJfoP2BQ0vdLpbWJ8GSsLm/eAA "Bash – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), 106 bytes
**Full version:**
```
$_=[*$<]*''
$.=0
o_=97
O_=65
@_=->{$_[__=''<<$.+_]?$_[__]=''<<$.+(_^32):$.+=1;$.<27&&@_[]}
_&&=@_[]
$><<$_
```
[Try it online!](https://tio.run/##KypNqvz/XyXeNlpLxSZWS12dS0XP1oArP97W0pzLP97WzJTLId5W165aJT46Pt5WXd3GRkVPOz7WHsyPhQloxMcZG2laAVm2htYqejZG5mpqDvHRsbVc8WpqtiAWl4odUGX8//8eqTk5@ToK5flFOSmKXKF5OZm5mSWpKQoB/uGuQQA "Ruby – Try It Online")
**Uppercase:**
```
$_=[*$<]*''
$.=0
_=97
O_=65
@_=->{$_[__=''<<$.+_]?$_[__]=''<<$.+(_^32):$.+=1;$.<27&&@_[]}
_&&=@_[]
$><<$_
```
[Try it online!](https://tio.run/##KypNqvz/XyXeNlpLxSZWS12dS0XP1oAr3tbSnMs/3tbMlMsh3lbXrlolPjo@3lZd3cZGRU87PtYezI@FCWjExxkbaVoBWbaG1ip6NkbmamoO8dGxtVzxamq2IBaXih1QZfz//x6pOTn5Ogrl@UU5KYpcoXk5mbmZJakpCgH@4a5BAA "Ruby – Try It Online")
**Lowercase:**
```
$_=[*$<]*''
$.=0
o_=97
_=65
@_=->{$_[__=''<<$.+_]?$_[__]=''<<$.+(_^32):$.+=1;$.<27&&@_[]}
_&&=@_[]
$><<$_
```
[Try it online!](https://tio.run/##KypNqvz/XyXeNlpLxSZWS12dS0XP1oArP97W0pwr3tbMlMsh3lbXrlolPjo@3lZd3cZGRU87PtYezI@FCWjExxkbaVoBWbaG1ip6NkbmamoO8dGxtVzxamq2IBaXih1QZfz//x6pOTn5Ogrl@UU5KYpcoXk5mbmZJakpCgH@4a5BAA "Ruby – Try It Online")
**Explanation:**
The verbose part here is all about the no-lower-case version. Avoiding lower-case characters means the string replacement needs to use the syntax `str[from] = to`, wrapped in a loop via a lambda that calls itself. The lambda is the variable `@_` defined using `@_=->`, and it's called via `@_[]`.
Stepping through...
`$_=[*$<]*''` : Read multiline input into the variable `$_`. (Depending on your interpretation of the spec, this could just be `$_,=*$<` for single-line input or even happen implicitly via the `-p` flag).
`$.=0`: Initialize the variable we'll be using to iterate over the letters of the alphabet.
`o_=97`: This initializes a variable that we never use. But if `o`, the only lower-case character in the program, is deleted, it's instead initializing `_`.
`O_=65`: Same but for upper-case.
`@_=->{`: Start the loop definition.
`$_[__=''<<$.+_]`: Check for the presence of a specific letter in the string (starting with "a".)
`?$_[__]=''<<$.+(_^32)`: If it's there, swap its case.
`:$.+=1`: Otherwise, move on to the next letter.
`$.<27&&@_[]}`: Either way, repeat the loop as long as we haven't reached the end of the alphabet.
`_&&=@_[]`: If `_` has been defined, run the loop. If it was defined as 97, we'll be caseswapping letters starting with 'a' (character code 97). If it was defined as 65, we'll start with 'A'.
`$><<$_`: Output.
[Answer]
# [Burlesque](https://github.com/FMNSSun/Burlesque), 10 bytes
```
JZZzz#RjHD
```
[Try it online!](https://tio.run/##SyotykktLixN/f/fKyqqqko5KMvD5f9/j9ScnHwdhfL8opwURQA "Burlesque – Try It Online")
This was a very fun one to puzzle out.
Explanation:
```
J # Duplicate the input
ZZ # Uppercase it
zz # Lowercase it
#R # Rotate the stack right
j # Swap the top two elements in the stack (back to the original order)
HD # Hide the top (modified) element, returning the original input
```
Removing the lowercase letters gives us:
```
JZZ#RHD
```
[Try it online!](https://tio.run/##SyotykktLixN/f/fKypKOcjD5f9/j9ScnHwdhfL8opwURQA "Burlesque – Try It Online")
Explanation:
```
J # Duplicate the input
ZZ # Uppercase it
#R # Rotate the stack to the right
HD # Hide the top (unmodified) element, returning the modified input
```
And with uppercase letters removed:
```
zz#j
```
[Try it online!](https://tio.run/##SyotykktLixN/f@/qko56/9/j9ScnHwdhfL8opwURQA "Burlesque – Try It Online")
Explanation:
```
zz # Lowercase the input
#j # Treats the stack as code to be run. Pops the string from the stack
# and pushes it straight back in again to be implicitly output
```
[Answer]
# perl -p, 19 bytes
```
$A_=lc$_;$a_="\U$_"
```
[Try it online!](https://tio.run/##K0gtyjH9/1/FMd42J1kl3lolMd5WKSZUJV7p/3@P1JycfB2F8PyinJR/@QUlmfl5xf91CwA "Perl 5 – Try It Online")
A completely different solution than my earlier one. The program reads a line from the input (in the variable `$_`), does zero or more modifications, and prints that line (due to the `-p` flag). That is, it prints whatever ends up in `$_`.
As is, the input line isn't modified; its lower case variant is assigned to `$A_`, and its upper case variant to `$a_`, but both variables are otherwise ignored.
Removing the upper case letters gives us:
```
$_=lc$_;$a_="\$_"
```
[Try it online!](https://tio.run/##K0gtyjH9/18l3jYnWSXeWiUx3lYpRiVe6f9/j9ScnHwdhfD8opyUf/kFJZn5ecX/dQsA "Perl 5 – Try It Online")
Now, `$_` is set to the lower case variant of itself. The variable `$a_` is set to the literal string `$_`, but otherwise ignored.
If we remove the lowercase letters instead, we end up with:
```
$A_=$_;$_="\U$_"
```
[Try it online!](https://tio.run/##K0gtyjH9/1/FMd5WJd5aJd5WKSZUJV7p/3@P1JycfB2F8PyinJR/@QUlmfl5xf91CwA "Perl 5 – Try It Online")
Now we assign `$A_` the input line, and ignore this variable. `$_` is set to the uppercase variant of itself by using the special interpolation symbol `\U`, which upper cases the rest of the string, until it encounters `\E`, or the end of the string.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~78~~ ~~76~~ ~~73~~ ~~72~~ 68 bytes
```
__(_,$){$="";_[""-$]&&__(_+1,_[""-$]^=_[""-$]-('Aa'^32u)<26U?32:0);}
```
[Try it online!](https://tio.run/##jZDRCoIwFIbvfYrTENtIoRS6aEl01wtEF6JjrChhabjtSnz2paRFpNC5@s/Hz8fhiOAqhLWMYea7pHZjhChLEArc1PM6ulj5/Z7FfQjwfM/nWRQasg3Xx10UbpaENpaZUYmZlHSOL4XD5KhCTik@Z7wVeaHhzvMCE6gdaEdprnMB4sYrUEkKMaDDRcoSTmUlzzNEf1r6r5aZbLV/U4TCw2jVhRczWA9MD0xiM7A2OI19Ag "C (gcc) – Try It Online")
# [C (clang)](http://clang.llvm.org/), 66 bytes
```
__(_,$){$="";""[$=_-$]&&__(_+1,""[$]^=""[$]-('Aa'^32u)<26U?32:0);}
```
[Try it online!](https://tio.run/##jZDRCoIwFIbvfYrTGLqRQil00RrRXS8QXYiOYVHC0tDtSnz2pYVFpNC5OT8fPx@HkwWZksXFWiGI8DFtMEeIIRRjLgKcuG7P50u/J0nKnysg3k56aRQauglXh20UrheUtVaYCYUZVfSGL4Ej1IRAjQk@J7wFeaHhJvOCUGgc6KbWUucZZFdZQR0nwAHtz0qVcCwrdZoh9tPSf7XMZKv7V00Z3I2u@/BihuiB6YEpYgbWBae1Dw "C (clang) – Try It Online")
Thank @G.Sliepen for fixing code for tio and pointing that the optimize work on clang!
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal), 11 bytes
```
uN‹ß⇧:[,]_⇩
```
[Full Program:](http://lyxal.pythonanywhere.com?flags=&code=uN%E2%80%B9%C3%9F%E2%87%A7%3A%5B%2C%5D_%E2%87%A9&inputs=Hello%2C%20World!&header=&footer=)
```
# Implicit input, e.g. "Hello, World!"
uN‹ # Pushes '-1', negates it, and decrements, evaluating to `0`
ß⇧ # Pops the top of the stack, and if it's truthy, converts the input to UPPERCASE. The top of the stack is '0', so this isn't executed
:[,] # Duplicates the top of the stack, and prints it if it is truthy, which it is
_ # Discards the top of the stack
‚á© # Converts the input to lowercase
# Implicit output is disabled
Output: Hello, World!
```
---
[UPPERCASE PROGRAM:](http://lyxal.pythonanywhere.com?flags=&code=N%E2%80%B9%C3%9F%E2%87%A7%3A%5B%2C%5D_%E2%87%A9&inputs=Hello%2C%20World!&header=&footer=)
```
# Implicit input, e.g. "Hello, World!"
N‹ # Swaps the casing of the input and appends '-', evaluating to 'hELLO, wORLD!-'
ß⇧ # Pops the top of the stack, and if it's truthy, converts the input to UPPERCASE. The top of the stack is a non-empty string, so this is executed
:[,] # Duplicates the top of the stack, and prints it if it is truthy, which it is
_ # Discards the top of the stack
‚á© # Converts the input to lowercase
# Implicit output is disabled
Output: HELLO, WORLD!
```
---
[lowercase program:](http://lyxal.pythonanywhere.com?flags=&code=u%E2%80%B9%E2%87%A7%3A%5B%2C%5D_%E2%87%A9&inputs=Hello%2C%20World!&header=&footer=)
```
# Implicit input, e.g. "Hello, World!"
u‹ # Pushes '-1' and decrements, evaluating to '-2'
‚áß # Performs graded_up() on the top of the stack, evaluating to '0'
:[,] # Duplicates the top of the stack, and prints it if it is truthy. '0' is falsey, so it is not executed
_ # Discards the top of the stack
‚á© # Convert the input to lowercase
# Implicit output
Output: hello, world!
```
```
[Answer]
# [Vim](https://www.vim.org), 5 bytes
```
VgUu$
```
---
[Full Program:](https://tio.run/##K/v/Pyw9tFTl/3@P1JycfB2F8PyinBRFAA)
```
V # Enter Visual Line mode
gU # Change all characters to UPPERCASE
u # Undo
$ # Go to end of line
```
---
[Answer]
# [SNOBOL4 (CSNOBOL4)](http://www.snobol4.org/csnobol4/), ~~114~~ 96 bytes
```
OUTput =inPUT :(enD)
Den OUTPUToutput =REPLACEreplace(INPUTinput,&LCASEucase,&UCASElcase)
END
end
```
[Try it online!](https://tio.run/##K87LT8rPMfn/n9M/NKSgtETBNjMvIDREwUojNc9Fk8slNQ8kARTJLy0BSwe5Bvg4OrsWpRbkJCananj6AeUy84BSOmo@zo7BrqXJicWpOmqhIHYOiK3J5ernwpWal/L/v6OTcwoA "SNOBOL4 (CSNOBOL4) – Try It Online")
[T !](https://tio.run/##K87LT8rPMfn/n9M/NETBNgBIWGm4aHK5gPggnm2Qa4CPo7OrhqcfkKuj5uPsGOyqoxYKojS5XP1cuP7/d3RyTgEA)
[ry it online!](https://tio.run/##K87LT8rPMfn/n7OgtETBNjNPwUojNU@TKzWPM7@0BCxWlFqQk5icqpGZB@TqqJUmJxan6qjlgChNLqDClP//HZ2cUwA)
(Ab)uses SNOBOL's case-insensitivity and GOTO labels.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~84~~ 81 bytes
```
_=>_['A'?'slice'||'\164\157U\160\160\145\162C\141\163\145':'to\x4cower\103ase']()
```
[Try it online!](https://tio.run/##lYvdCoIwGIbPu5FvUv4staCwkK6hk5zIWN/EGE6cWIT3viYe1VkHL@/D@/PgIzeib7rBb/UdrcxslZ2qAnI4g1GNQJgmYHSXMJrurw6iRUnqfHtxQB3EcwAHGDR7JUI/sWc0irlBKIlnjyuhW6MVBkrXRBK5BvC87xRHrsjSBD12igskYZH7tzKsN/P8jxf3378v@wE "JavaScript (Node.js) – Try It Online")
Trivial one
# [JavaScript (Node.js)](https://nodejs.org) work if `\123` was an error, 170 bytes
```
$=_=>_['A'?'slice'||(/A/,[,A,,S,,,O,,,E,C]=!1+{},[T,R]=!0+_,[U,N]=_._+_,$[C+O+N+S+T+R+U+C+T+O+R](`P='\\${U}0070'`)(),T+O+'U'+P+P+E+R+'C'+A+S+
Ea):'to\Zx4cower\Zx43ase']()
```
[Try it online!](https://tio.run/##lY1Pa4NAEMXvfooUhNllxj@lhUKLLSLeShI0XrKKWbZLsIgrKmlpks9u11t6LMMwD@b33vuUJzmqoeknrzMfep7dqI5eawExvMHYNkrD5cKCOCBBMVFORBu7KSVVdHeP5yuJHWVWh1iTKGhdRbVfW@2KBDe4xhx3mGGBib0bzCp22EZQlu65uIbhUwgHzjgtLygAt3ZSi0MCGFurk0r@DJMp99@PynzpYREPctRQMT47jqNMN5pW@605MpdBrrtJd0qvkoXh/OUPoE@yZfk0NJ2FuT/ovpVKs0DE3r4KjrQCa2HwvhT9M0F6PzcJRd/fJMy/ "JavaScript (Node.js) – Try It Online")
# [JavaScript (Node.js)](https://nodejs.org) strict, ~~186~~ 184 bytes
```
(_,[,A,,S,,,O,,,E,C]=!1+{},[T,R]=!0+_,[U,N]=_._+_)=>0xE0?_:_['A'?(/A/,(_=>_)[C+O+N+S+T+R+U+C+T+O+R]('U',`U[0]='\\${U}0070'`)(U=[]),T+O+'U'+U+U+E+R+'C'+A+S+
Ea):'to\Zx4cower\Zx43ase']()
```
[Try it online!](https://tio.run/##lY9Ba4MwFMfvfoqsCEnIs2ZsMGhJi4i30UJtLo0hDS6UDlFR15WVfnYXb91xh8f7H37/3@N92ovty@7cDlHdfLhx9tU71A/duRxmS1S5AYVIoJEYUJAA5ACw9ZNBqsXTM7vdQe1h5zNnHpGw0cLMDTNUrPg142uzMAoneE3iJAZixMpQlbIt27Cc7dmOSZb6vWU7TbDEcJSKa4GLIrzJO@dvHB8pkUJpChPlEd@QLPNNnGKWeEuQWbrAQ1Mcrq9l8@26KbzY3mFN6BgEQdnUfVO5edWcSEhw7urB1aVD6cRQuvwDuIutSO7/rz1M551rK1s6EqskOuj4BAj7CsHv06F/Gmz082CQbftgGH8B "JavaScript (Node.js) – Try It Online")
[Answer]
# [Attache](https://github.com/ConorOBrien-Foxx/Attache), 243 bytes
```
{`+^^(_[0...#_]|{[[_,alpha[_2[ascii[33:58],_]]]["Z@"<_‚àß_<"["],NTS[20363848091226750223144960725905269888206028302]@_2[NTS[6060454347787589083238889994600682623947941084],_]]["z`"<_‚àß_<"{"]}&_2)}&({[`0,[$,`_3][_@_3=_2]][_3<#_][_,_2,_3+1]}&0)
```
[Try it online!](https://tio.run/##PY/PSsNAEMZfJa5SWrqEyczuZrekkKMnEfTksJ2E2tJAsFIDgrF338T38kXi6qHXj9/3rx2GdnvYTftstc6msVluNnNhyPP8WuLnyCy67V8PLQty@7btOiZaWR@1xBhZPdWqkp@vb6kUq6jvHh8YgRx54yEUiK60gEiFMcFBiTaARRe89wgO0BNgrFPyn88lxVhDpix9aX0AT0iJDCEYB@A8OqRgymAK8OZ/AKuP5tI/qnieCS7Os/nIDWi@0Y1QZKmF1oKJFqrSqfRIUAsti8TDYro/dS8D71nd7vr@qLP346l/vlIxTr8 "Attache – Try It Online")
At first, I wasn't sure if it was possible. However, this is in fact possible due to two key factors:
1. We have a lot of symbols at our disposal, including variable names in lambdas being accessible entirely symbolically: `_`, `_2`, etc.
2. We have the `ascii` variable to work with while having access to lowercase letters, and `NTS` (**N**umber **T**o **S**tring) while having access to uppercase letters. The former is simply a string consisting of the ASCII bytes 32 to 126. The latter is a function that takes a number and gives a string representation of it. The first long number corresponds to the uppercase alphabet, and the second to the lowercase one.
## Explanation
Now, for why this is such a troubling problem in this language. Attache functions are almost exclusively PascalCase, making them unsuitable for either computation. This means we do not have access to basic functions like string lookup, which we have to implement from scratch. This can be found at the end of the code:
```
{[`0,[$,`_3][_@_3=_2]][_3<#_][_,_2,_3+1]}&0
{ }&0 function with right parameter = 0
parameters: string, search[, index = 0]
[ , ][_3<#_] if index < length(string) then
[ , ][_@_3=_2] if string[index] = search then
`_3 yield a fn returning the index
$ else yield this current function
`0 else yield 0
[_,_2,_3+1] call the result with the arguments, and index + 1
```
This snippet exhibits how we do conditional computation and recursion without letters. Thankfully, Attache has the Self reference `$`, which makes this leagues easier than it would be otherwise.
The main attraction takes this helper as a right argument, and is referenced (and passed manually down through scopes) as `_2`. I'll remove the body of the mapped function to explain how the main function works generally:
```
{`+^^(_[0...#_]|{-------}&_2)}&(-------)
&(-------) saving the helper function as _2
{ } function taking a string as _
_[0...#_] get characters of input
|{-------} map each character by this function
&_2 (passing down _2)
`+^^( ) fold concatenation, returning a string
```
Last, the function which tests each character and makes the conversion. The difference is made when testing for conditions. Two seperate conditions are checked:
1. `"Z@"<_‚àß_<"["`
2. `"z`"<*‚àß*<"{"`
Without any intervention, they both return false. We index into a nested array, obtaining `arr[0][0]`, in which is placed the input. So, by default, the input is unchanged.
When removing uppercase letters, the first condition will become true for uppercase letters. When removing lowercase letters, the second condition will become true for lowercase letters. So, we have that `arr[1]` corresponds to the lower-to-upper transformation, and `arr[0][1]` corresponds to the upper-to-lower transformation. This is seen in this structure, where we index by the comparison.
```
[[_,--------]["Z@"<_‚àß_<"["],--------]["z`"<_‚àß_<"{"]
```
Both transformations have the form:
```
Desired[_2[Source,Element]]
```
That is, they find the index in the alphabet the mapped element belongs to, then index that into the other alphabet. For upper-to-lower, we can use `alpha` and `ascii[33:58]` to obtain the lowercase and uppercase alphabets, respectively. For lower-to-upper, we can use `NTS` on `20363848091226750223144960725905269888206028302` and `6060454347787589083238889994600682623947941084` to obtain the uppercase and lowercase alphabets, respectively. (These numbers are obtained by inputting the desired string to `STN`).
And with that, the program functions in all three cases.
[Answer]
## [Keg](https://github.com/JonoCode9374/Keg/), ~~42~~ 38 bytes
Turns out that `‚ü∞` and `‚ü±` aren't implemented! That surely gives me a headache to implement that myself. (No TIO 'cuz the TIO interpreter has a bug. Use the offline interpreter instead.)
```
AAa!&ø?&¦3(:AZ•[ -]")|2(:za•[ +]")║_™^
```
## Explanation
```
AAa # Push the "magic string"
! # Find the length
& # Save the result into the accumulator
√∏ # Clear the stack
?& # Take input, append accumulator value
¦3(:AZ•[ -]")|2(:za•[ +]")║_™ # Default condition: directly return the input
^ # Reverse the stack
```
No lowercase letters:
```
AA! # Here, the length of the "magic string" is 2
&√∏?& # Same as above
¦3 # If the length of the stack is 2:
( # Do this for every stack item:
:AZ• # Is this in the A-Z range?
[ -] # If so, lowercase it
")|2(:•[ +]")║_™^ # Same as above
```
No uppercase letters works similarly.
[Answer]
# [Haskell](https://www.haskell.org/), 90 bytes
```
(<$>)__
__ _'|0XA<1&&_'>'@'&&_'<'['||0xa<1&&_'>'`'&&_'<'{'=([_'..'~']++['?'..])!!32|1<2=_'
```
[Try it online!](https://tio.run/##y0gszk7NyfmfZhvzX8NGxU4zPp4rPl4hXr3GIMLRxlBNLV7dTt1BHUTbqEer19QYVCTChBOgwtXqthrR8ep6eup16rHa2tHq9kB2rKaiorFRjaGNkW28@v/cxMw824LSkuCSIp88BRWFNAUlD6C1@ToK4flFOSmKSgr//yWn5SSmF//XTS4oAAA "Haskell – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 12 bytes
```
≡_¦_a↥S_A↧θS
```
[Try it online!](https://tio.run/##S85ILErOT8z5/7@4PLMkOUNBQyleSVOhmis5sThVQSk@UclKIaAoM69EI7SgILUIJKrhmVdQWhJcAhRN19DU1LSGqXWEq/XJL4eqLQTJp6SmJZbmlMBkUfVbc9X@/@@RmpOTr6NQnl@Uk6LI9V@3LAcA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
≡_
```
Switch on `_`.
```
_a↥S
```
If it equals `_a` (i.e. never) then print the input uppercased.
```
_A↧θ
```
If it equals `_A` (i.e. never) then print the input lowercased.
```
S
```
Otherwise print the input unchanged.
With uppercase characters (including `S`) removed:
```
≡_¦_a↥_↧θ
```
[Try it online!](https://tio.run/##S85ILErOT8z5//9R58L4Q8viEx@1LY1/1Lb83I7//z1Sc3LydRTK84tyUhS5AA "Charcoal – Try It Online") Explanation:
```
≡_
```
Switch on `_`.
```
_a‚Ü•_
```
If it equals `_a` (i.e. never) then print `_` uppercased.
```
↧θ
```
Otherwise print the input lowercased.
With lowercase characters (including `θ`) removed:
```
≡_¦_↥S_A↧S
```
[Try it online!](https://tio.run/##S85ILErOT8z5//9R58L4Q8viH7Utfb9nc7zjo7blQPr/f4/UnJx8HYXy/KKcFEUuAA "Charcoal – Try It Online") Explanation:
```
≡_
```
Switch on `_`.
```
_↥S
```
If it equals `_` (i.e. always) then print the input uppercased.
```
_A↧S
```
If it equals `_A` (i.e. never) then print the input lowercased.
Obviously both programs still work if you only delete ASCII upper/lowercase characters.
[Answer]
# [R](https://www.r-project.org/), 127 bytes
```
aA=`\143`("\101-\132","\141-\172")
`\164`=1
`\143\141\164`(`\143\150\141\162\164\162`(aA[T+1],aA[t+1],`\163\143\141\156`(,"")))
```
[Try it online!](https://tio.run/##K/r/P9HRNiHG0MQ4QUMpxtDAUDfG0NhISQfINgGxzY2UNLmA8mYmCbaGXGCFIBmwgAaUa2oAFTICCYPoBI1Ex@gQbcNYHSBdAqJBRhgjdJuaJWjoKClpamr@90jNycnXUQjPL8pJUfwPAA "R – Try It Online")
This uses the [octal code trick](https://codegolf.stackexchange.com/a/191117/86301) to write most of the code without letters.
In its unaltered version, it is equivalent to
```
aA=c("A-Z","a-z")
t=1
cat(chartr(aA[T+1],aA[t+1],scan(,"")))
```
Recall that `T` is the boolean `TRUE` and will be coerced to `1`, so we are calling `cat(chartr("a-z","a-z",scan(,"")))` which will leave the input unchanged.
## No lowercase
Remove the lowercase letters and you get code equivalent to
```
A=c("A-Z","a-z")
t=1
cat(chartr(A[T+1],A[+1],scan(,"")))
```
[Try it online!](https://tio.run/##K/r/39E2IcbQxDhBQynG0MBQN8bQ2EhJB8g2AbHNjZQ0uYDyZiYJtoZcYIUgGbCABpRragAVMgIJg@gEDcfoEG3DWB3HaBAJ0m@M0GpqlqCho6Skqan53yM1JydfRyE8vygnRfE/AA "R – Try It Online")
so we are calling `cat(chartr("a-z","A-Z",scan(,"")))`, which will convert to uppercase.
## No uppercase
Remove all uppercase characters and the code becomes equivalent to
```
a=c("A-Z","a-z")
t=1
cat(chartr(a[+1],a[t+1],scan(,"")))
```
[Try it online!](https://tio.run/##K/r/P9E2IcbQxDhBQynG0MBQN8bQ2EhJB8g2AbHNjZQ0uYDyZiYJtoZcYIUgGbCABpRragAVMgIJg@gEjcRobcNYncToEhAF0m@M0GpqlqCho6Skqan53yM1JydfRyE8vygnRfE/AA "R – Try It Online")
This time, we are calling `cat(chartr("A-Z","a-z",scan(,"")))`, which converts to lowercase.
[Answer]
# [Zsh](https://www.zsh.org/), 30 bytes
```
:A&&1=$1:l
:a&&1=${(U)1}
<<<$1
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m724qjhjwYKlpSVpuhb7rBzV1AxtVQytcrisEsHMao1QTcNaLhsbGxVDiCKo2lXRSo5OzimpaUqxUBEA)
[A T O!](https://ato.pxeger.com/run?1=m724qjhjwYKlpSVpuhZ7rBzV1AxtVQytuKzAjGqNUE3DWi4bGxsVQ4gSqMpV0UqOTs4pqWlKsVARAA)
[ttempt his nline!](https://ato.pxeger.com/run?1=m724qjhjwYKlpSVpuhZ7rNTUDG1VDK1yuKwSwcxqDU3DWi4bGxsVQ4gSqMpV0UqOTs4pqWlKsVARAA)
`:` is a command which does nothing and always succeeds, but both `:A` and `:a` don't exist and always fail.
Conveniently, Zsh has two ways to change the case of a string: `${(U)string}`/`${(L)string}`, and `$string:u`/`$string:l`.
[Answer]
# PHP (224 Bytes)
```
<?=!fPassthru(STDIN)&&0;__HALT_compiler();FUNCTIONfunction fPassthru(){returnRETURN STDIN;};functionFUNCTION __HALT_compiler(){ECHOecho STRTOUPPERstrtolower(STREAMstream_GETget_CONTENTScontents(Pfopen('php://stdin','r')));}
```
## Uppercase version
```
<?=!P(STDIN)&&0;__HALT_();FUNCTION P(){RETURN STDIN;};FUNCTION __HALT_(){ECHO STRTOUPPER(STREAM_GET_CONTENTS(P('://','')));}
```
## Lowercase version
```
<?=!fassthru()&&0;___compiler();function fassthru(){return ;};function ___compiler(){echo strtolower(stream_get_contents(fopen('php://stdin','r')));}
```
[Answer]
# [Befunge-98](https://esolangs.org/wiki/Befunge) [(PyFunge)](https://pythonhosted.org/PyFunge/), 51 bytes
```
<aaA^:~@#
, >-\:'``\'{^
^ 1>\:'@`\'[>\`**' *+
^ 01>
```
[Try it online!](https://tio.run/##S0pNK81LT9W1tNAtqAQz//@3SUx0jLOqc1Dm0lGw042xUk9IiFGvjuOKUzC0A/IcgLxou5gELS11BS1toKiBod3//x6pOTn5CuH5RTkpigA "Befunge-98 (PyFunge) – Try It Online")
[Try it online! (Uppercase letter removed)](https://tio.run/##S0pNK81LT9W1tNAtqAQz//@3SUyMs6pzUObSUbDTjbFST0iIUa@O44pTMLQD8hyAvGi7mAQtLXUFLW2gqIGh3f//Hqk5OfkK4flFOSmKAA)
[Try it online! (Lowercase letters removed)](https://tio.run/##S0pNK81LT9W1tNAtqAQz//@3cYyzqnNQ5tJRsNONsVJPSIhRr47jilMwtAPyHIC8aLuYBC0tdQUtbaCogaHd//8eqTk5@Qrh@UU5KYoA)
## Explanation
Without removing any characters, most of the code is never executed. The code that does get executed is
```
< ^:~@#
,
^
^ >
```
This reads each character sequentially with `~`, duplicates it with `:`, and then prints the duplicate. Once the input runs out, `~` reflects the instruction pointer and `@` ends the program. A copy of the input string is left on the stack, but it never gets printed, so we don't care about it.
With the uppercase `A` removed, the `^` on the top line moves one space to the left and the third line is executed rather than the second.
```
< ^:~@#
,
^ >\:'@`\'[>\`**' *+
1
```
This sequentially reads through the input with `:~@#` as before. Then, it puts a 1 on the stack, followed by two copies of the character. The two duplicates are compared against `'@` and `'[` (64 and 91 respectively) to see whether the character is an uppercase letter. If it is, the product of these checks (1\*1=1) is multiplied by 1 and then by the code point of ‚Äã (space) to get 32, which is then added to the original character to make it lowercase. However, if the character is not uppercase, one of the comparisons will return 0. This 0 gets multiplied by a bunch of things and then added to the original character, and so the character remains unaltered when it is printed.
With the lowercase `a`s removed, the first `^` is now shifted over two spaces to the left, and the second line is executed rather than the fourth.
```
< ^:~@#
, >-\:'``\'{^
^ 1 >\`**' *+
0
```
This does mostly the same thing, except -1 is pushed onto the stack rather than 1 at the beginning of the loop and the bounds are replaced with 96 and 123 (to see whether it is lowercase). Then, the `^` (we can't use `v` because it's lowercase!) shifts the IP down a line, to execute the same logic as before. If the character is a lowercase letter, 1 is multiplied by the top of the stack (which is now -1 rather than 1) and by 32 to get -32, which is added to the original character to make it uppercase. As before, if the character is not lowercase, 32 is multiplied by 0 and the final `+` does nothing.
In all cases,
```
<
,
^
^
```
is executed at the end of the loop, printing the possibly modified character and rerouting the IP back to the start.
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 22 bytes
```
İḷ|f{;.P∧Ạ{∧Ṇ}ᶻ∋P∧|}ᵐ|
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r//8iGhzu216RVW@sFPOpY/nDXgmoQtbOt9uG23Y86ukGCNbUPt06o@f9fyTEpWSElVcHN3UPRXul/FAA "Brachylog – Try It Online") [try it online!](https://tio.run/##SypKTM6ozMlPN/r//@GO7TVp1dZ6jzqWVwNx7cNtux91dANZNbUPt06o@f9fyTEpWSElVcHN3UPRXul/FAA) [TRY IT ONLINE!](https://tio.run/##SypKTM6ozMlPN/r//8iGmmprvYBHHcsf7lpQDaJ2ttU@3Lb7UUc3SLCm9uHWCTX//ys5JiUrpKQquLl7KNor/Y8CAA)
I had some bizarre errors trying to use subscripted `‚àã`/`‚àà`. Takes a string through the input variable and outputs through the output variable, since printing is impossible without lowercase letters.
```
İ The input is an integer, but it's not,
·∏∑ ...
| so maybe...
f its factors, but it doesn't have factors...
{;.P∧Ạ{∧Ṇ}ᶻ∋P∧|}ᵐ ...
| so just output it unchanged.
·∏∑ The input converted to lowercase
| is the output.
|f{;. ∧ {∧ }ᶻ∋ ∧|}ᵐ| Hooray, that worked, forget everything else.
İ The input is an integer, except it's not,
| { }ᵐ so then instead for each element of the input
;. that element paired with the output it's mapped to
P is P,
‚àß and
Ạ the lowercase alphabet
{∧ }ᶻ zipped with (I don't actually know why this works!)
Ṇ a list of all printable ASCII characters (ABCDEFGHI...)
‚àãP contains P
‚àß (which isn't the output);
| if that's impossible pass the element through unchanged.
| Since that worked, we don't worry about the rest.
```
[Answer]
### Haskell, 208 bytes or 210 bytes
Note: my original, shorter, solution was buggy. This one seems pretty solid. This challenge is not so easy in Haskell; there's no golfing here, aside from space removal. I imagine it's possible to do better.
```
(!)((/):($))((#):(*))(+)|(+)==(/)=(#)|0<1=(!)($)(*)(+)
(!)_ _(+)=(+)
(&)[(*)]=[]
(&)((*):(+))=(*):(&)(+)
_:(#)=(&)['@'..'[']
_:(%)=(&)['`'..'{']
(+*)|"A"==[]=(!)(#)(%)|"a"==[]=(!)(%)(#)|0<1= \(+)->(+)
(+*)<$>
```
The first seven lines are definitions. The last line is prepended to the input, like
```
(+*)<$>"My name is David."
```
If you don't accept this, you can upgrade to a "function" by enclosing in parentheses, at the cost of two bytes. To make a proper function definition, you'd turn on `NoMonomorphismRestriction` and write, say,
```
(##)=((+*)<$>)
```
### Explanation
Haskell variables (including function names) generally have to start with a lower-case letter. Infix operators, however, can consist of various symbols, as long as they don't begin with a `:`. So ... all the functions defined and their argument names are written as operators. An operator enclosed in parentheses is treated as a regular old name, so this works. The case restriction prevents us from using any standard functions except infix ones, and also prohibits us from importing any modules. So we can't use `fromEnum`, `toEnum`, `ord`, `chr`, or `unsafeCoerce` to manipulate characters as numbers. Instead we write a function, `(!)`, that looks for a character in a list, and produces the character in the same position in the second list if it's found. These lists are produced rather awkwardly using characters before and after the lower and upper case ASCII ranges and a hand-rolled version of `init` (called `(&)`).
[Answer]
# [Julia 1.0](http://julialang.org/), ~~72~~ 49 bytes
```
Zz=0;Yy=z=Z=0;[[email protected]](/cdn-cgi/l/email-protection)+('`'<Xx+32Z<'{')*(32Z-32z)
```
[Try all 3 versions online!](https://tio.run/##lY09D4IwEIb3/orKQusHwXYwUWpMnN2RyYupsaQB0oIiGv567SSasDjdk/fuvSdvtIJl6wALHASByzoRb44P0YnMQ5@2Yhel7YyEpzDxk7MsCZ8hnRJPC8466nwLIevr@yuYiMTrJVtRhCqjiloXBCiSN9DkIGuIKjBW@oh@1r3Fry3OS1UM2TchYP71RelaGjJRVpd3ac5g5RzDcAdsxML@0vAfTVNVYxo@ouHjGvcG "Julia 1.0 – Try It Online")
input and output are lists of characters
[Answer]
# [Lua](https://www.lua.org/), 111 bytes
```
bB=...aA=io or _G['\112\114\105\110\116'](('')['\117\112\112\101\114'](B))load"print(_G and bB or b:lower())"()
```
[Try it online!](https://tio.run/##yylN/P8/yclWT08v0dE2M18hv0gh3j1aPcbQ0AiITWIMDUyBtAEQm6nHamioq2uCJc2hCoDYwBCkECjppKmZk5@YolRQlJlXohHvrpCYl6KQ5AQyMskqJ788tUhDU1NJQ5MrCWwdzDbyLEO1C2IVpk1gjznaKlDiJyWQVxScFBSsIIb@///fIzUnJ18hPL8oJwUA "Lua – Try It Online")
## Lowercase Version
```
b=...a=io or _['\112\114\105\110\116'](('')['\117\112\112\101\114']())load"print(_ and b or b:lower())"()
```
## Uppercase Version
```
B=...A= _G['\112\114\105\110\116'](('')['\117\112\112\101\114'](B))"(_G B :())"()
```
## Explanation
This code takes input as a command line argument, and can effectively be split up into two conditionals.
```
aA=io or _G['\112\114\105\110\116'](('')['\117\112\112\101\114'](B))
```
This segment is equivalent to `aA=io or print(B:upper())`, just written in a way to avoid lowercase characters for the print. Normally, this section of code does nothing because `io` is a truthy value. When lowercase letters are removed, `io` and `or` are removed, allowing the print to occur.
```
load"print(_G and bB or b:lower())"()
```
This segment is surrounded by a `load` call because without it, Lua will see this part as a syntax error when attempting to run the uppercase version. The uppercase version will throw a runtime error when it encounters this part, however.
The normal version will see `_G` as a truthy value and print the input as-is. The lowercase version will instead see `_` as a falsy value and print the input in lowercase.
] |
[Question]
[
# Alphabet Rain
## The Task:
The basic premise is to print out the input string and then repeat each character vertically, based on it's (0-indexed) position in the (case-insensitive) alphabet `A-Z`. `A` is at location 0 so is not repeated, `e` is at position 4 so is repeated 4 times, `P` is at position 15 so is repeated 15 times, `!` is not in `A-Z` so is repeated 0 times, etc.
For clarity, anything that falls outside of the range `B-Zb-z`, for example digits or special characters, will not be repeated, and thus will only appear on the first line.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest solution in each language is the winner.
## Input:
* Input will be in the standard printable ASCII character set, from 32 up to 126 `~`.
* The input string will be 1 character long or longer.
* There will not be any leading or trailing whitespace.
* You can take take input as a string (`"hello"`) or list of characters ( `["h", "e", "l", "l", "o"]`)
## Examples:
Input of `aaaa` gives:
```
aaaa
```
Input of `abcda` gives:
```
abcda
bcd
cd
d
```
Input of `Programming Puzzles & Code Golf!`, gives:
```
Programming Puzzles & Code Golf!
Progr mming Puzzles Code Golf
Progr mming Puzzles Code Golf
Progr mming Puzzles ode Golf
Progr mming Puzzles o e Golf
Progr mming Puzzl s o Golf
Progr mming Puzzl s o Gol
Pro r mmin Puzzl s o ol
Pro r mmin Puzzl s o ol
Pro r mm n Puzzl s o ol
Pro r mm n Puzzl s o ol
Pro r mm n Puzzl s o ol
Pro r mm n Puzz s o o
Pro r n Puzz s o o
Pro r Puzz s o o
Pr r Puzz s
r r uzz s
r r uzz s
uzz s
uzz
uzz
zz
zz
zz
zz
zz
```
Input of `~|[abc<0>cba]|~`, gives:
```
~|[abc<0>cba]|~
bc cb
c c
```
## Notes:
* standard loopholes apply
* output *can* be a list of strings, but:
* extraneous trailing newlines are not allowed (single `\n` on final line is acceptable)
* output *can* be a list of lists of characters, so long as it looks like it's raining characters
* no leading newline
* to our Nordic users who have a [few extra](https://en.wikipedia.org/wiki/Danish_and_Norwegian_alphabet) letters in their "A-Z" alphabet, feel free to support them, but it's not part of the challenge
[Answer]
# [6502 machine code](https://en.wikibooks.org/wiki/6502_Assembly) (C64), 113 bytes
```
00 C0 20 FD AE 20 9E AD 85 FB 20 A3 B6 A0 00 84 FC B1 22 99 6F C1 C9 41 90 14
C9 5B B0 04 E9 40 B0 0E C9 C1 90 08 C9 DB B0 04 E9 C0 B0 02 A9 00 99 6F C0 C5
FC 30 02 85 FC C8 C4 FB D0 D3 A9 00 99 6F C1 A0 C1 A9 6F 20 1E AB A9 0D 20 D2
FF A6 FC D0 01 60 C6 FC A0 00 B9 6F C1 F0 E6 BE 6F C0 D0 07 A9 20 99 6F C1 D0
05 CA 8A 99 6F C0 C8 D0 E7
```
[![screenshot](https://i.stack.imgur.com/Zgg4y.png)](https://i.stack.imgur.com/Zgg4y.png)
**[Online demo](https://vice.janicek.co/c64/#%7B%22controlPort2%22:%22joystick%22,%22primaryControlPort%22:2,%22keys%22:%7B%22SPACE%22:%22%22,%22RETURN%22:%22%22,%22F1%22:%22%22,%22F3%22:%22%22,%22F5%22:%22%22,%22F7%22:%22%22%7D,%22files%22:%7B%22rain.prg%22:%22data:;base64,AMAg/a4gnq2F+yCjtqAAhPyxIplvwclBkBTJW7AE6UCwDsnBkAjJ27AE6cCwAqkAmW/AxfwwAoX8yMT70NOpAJlvwaDBqW8gHqupDSDS/6b80AFgxvygALlvwfDmvm/A0AepIJlvwdAFyoqZb8DI0Oc=%22%7D,%22vice%22:%7B%22-autostart%22:%22rain.prg%22%7D%7D)**
**Usage:** `sys49152,"[string]"`, e.g. `sys49152,"Programming Puzzles & Code Golf!"`.
**Important:** If the program was loaded from disk (like in the online demo), issue a `new` command first! This is necessary because loading a machine program trashes some C64 BASIC pointers.
**Note:** The C64 is by default in a mode without lowercase letters -- in order to be able to enter a mixed-case string, switch to lowercase mode first by pressing `SHIFT`+`CBM`.
---
### Explanation
Here's a commented disassembly listing:
```
00 C0 .WORD $C000 ; load address
.C:c000 20 FD AE JSR $AEFD ; consume comma
.C:c003 20 9E AD JSR $AD9E ; evaluate expression
.C:c006 85 FB STA $FB ; store string length
.C:c008 20 A3 B6 JSR $B6A3 ; free string
.C:c00b A0 00 LDY #$00 ; initialize counter
.C:c00d 84 FC STY $FC ; and number of "extra" lines
.C:c00f .copyloop:
.C:c00f B1 22 LDA ($22),Y ; load next character
.C:c011 99 6F C1 STA .outbuf,Y ; store to buffer
.C:c014 C9 41 CMP #$41 ; compare with 'a'
.C:c016 90 14 BCC .zerocount ; smaller -> no repetition
.C:c018 C9 5B CMP #$5B ; compare with 'z'
.C:c01a B0 04 BCS .checkupper ; larger -> check for uppercase
.C:c01c E9 40 SBC #$40 ; subtract 'a' ('a' - 1 and carry)
.C:c01e B0 0E BCS .cl_storecount ; and jump to store in repeat count
.C:c020 .checkupper:
.C:c020 C9 C1 CMP #$C1 ; compare with 'A'
.C:c022 90 08 BCC .zerocount ; smaller -> no repetition
.C:c024 C9 DB CMP #$DB ; compare with 'Z'
.C:c026 B0 04 BCS .zerocount ; larger -> no repetition
.C:c028 E9 C0 SBC #$C0 ; subtract 'A' ('A' - 1 and carry)
.C:c02a B0 02 BCS .cl_storecount ; and jump to store in repeat count
.C:c02c .zerocount:
.C:c02c A9 00 LDA #$00 ; store 0 ...
.C:c02e .cl_storecount:
.C:c02e 99 6F C0 STA .repcount,Y ; ... in repeat count
.C:c031 C5 FC CMP $FC ; compare with number of extra lines
.C:c033 30 02 BMI .cl_next ; smaller -> go on with loop
.C:c035 85 FC STA $FC ; repeat count to number of extra lines
.C:c037 .cl_next:
.C:c037 C8 INY ; next
.C:c038 C4 FB CPY $FB ; compare with string length
.C:c03a D0 D3 BNE .copyloop ; not yet reached? -> repeat
.C:c03c A9 00 LDA #$00 ; terminate string in buffer
.C:c03e 99 6F C1 STA .outbuf,Y ; with 0 byte
.C:c041 .outloop:
.C:c041 A0 C1 LDY #>.outbuf ; output ...
.C:c043 A9 6F LDA #<.outbuf ; ...
.C:c045 20 1E AB JSR $AB1E ; ... string
.C:c048 A9 0D LDA #$0D ; and output ...
.C:c04a 20 D2 FF JSR $FFD2 ; ... newline
.C:c04d A6 FC LDX $FC ; load extra line count
.C:c04f D0 01 BNE .ol_step ; not zero -> go on
.C:c051 60 RTS ; WE ARE DONE HERE ;)
.C:c052 .ol_step:
.C:c052 C6 FC DEC $FC ; decrease extra line count
.C:c054 A0 00 LDY #$00 ; initialize counter
.C:c056 .eraseloop:
.C:c056 B9 6F C1 LDA .outbuf,Y ; load next character from buffer
.C:c059 F0 E6 BEQ .outloop ; 0 byte? -> end of string, output
.C:c05b BE 6F C0 LDX .repcount,Y ; load repeat count for this characer
.C:c05e D0 07 BNE .el_step ; not 0 yet? -> jump to decrement
.C:c060 A9 20 LDA #$20 ; load code for space
.C:c062 99 6F C1 STA .outbuf,Y ; store in current string position
.C:c065 D0 05 BNE .el_next ; and jump to next loop iteration
.C:c067 .el_step:
.C:c067 CA DEX ; decrease repeat count ...
.C:c068 8A TXA ; ... and ...
.C:c069 99 6F C0 STA .repcount,Y ; ... store back
.C:c06c .el_next:
.C:c06c C8 INY ; increase counter ...
.C:c06d D0 E7 BNE .eraseloop ; and jump back to loop
.C:c06f .repcount:
.C:c06f .RES $100 ; 256 bytes for repeat count
.C:c16f .outbuf:
.C:c16f .RES $100 ; 256 bytes as buffer for output
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~13~~ 12 bytes
```
,εDlAsk×}ζ»,
```
[Try it online!](https://tio.run/##MzBNTDJM/f9f59xWlxzH4uzD02vPbTu0W@f//4Ci/PSixNzczLx0hYDSqqqc1GIFNQXn/JRUBff8nDRFAA "05AB1E – Try It Online")
**Explanation**
```
, # print input
ε } # apply to each char in input
D # duplicate
l # convert to lower case
Ask # get index of current char in the lower case alphabet
× # repeat the char that many times
ζ # transpose with space as filler
», # join on newlines and print
```
[Answer]
# Pyth, ~~12~~ ~~10~~ 9 bytes
```
.tm+*xGr0
```
[Test suite.](http://pyth.herokuapp.com/?code=.tm%2B%2axGr0&input=%22Programming+Puzzles+%26+Code+Golf%21%22&test_suite=1&test_suite_input=%22Programming+Puzzles+%26+Code+Golf%21%22%0A%22abcda%22%0A%22aaaa%22&debug=0)
Explanation:
```
.tm+*xGr0dddQ Expanded program with autofilled input variable
m dddQ For each character d in the input:
r0d get its lowercase variant
xG and return its 0-based index in the alphabet
(-1 if not found, for special chars)
(empty string for A/a and special characters)
* d that many of the corresponding character
+ d and one more for good measure (because x is 0-indexed)
.t Transpose it and fill blanks with spaces
```
12 bytes:
```
j.t*VmxGr0d
```
(with trailing newline)
[Test suite.](http://pyth.herokuapp.com/?code=j.t%2aVmxGr0d%0A&input=%22Programming+Puzzles+%26+Code+Golf%21%22&test_suite=1&test_suite_input=%22Programming+Puzzles+%26+Code+Golf%21%22%0A%22abcda%22%0A%22aaaa%22&debug=0)
Explanation:
```
j.t*VmxGr0d
QQ Expanded program with autofilled input variable
Q print the input verbatim
m dQ For each character d in the input:
r0 get its lowercase variant
xG and return its 0-based index in the alphabet
(-1 if not found, for special chars)
*V Q multiply the corresponding characters in (the second autofilled input)
by their alphabet indices we just calculated
(empty string for A/a and special characters)
.t Transpose it and fill blanks with spaces
j Join the result on newlines
```
[Answer]
# [Python 3](https://docs.python.org/3/), 83 bytes
```
f=lambda s,k=65:[*{*s}-{' '}]and[s]+f([[' ',c][91>ord(c.upper())>k]for c in s],k+1)
```
[Try it online!](https://tio.run/##FctBC4IwGIDhc/2Kr0vb1ASJggSF8tDV@1iwprPl3GSrQ4r9dbPj@8Dbf14Pa/bzLDPNu3vFwUdtdjykNBgDP@1GBGhi3FTUs1BiSpeOBKOnJLeuwiJ@933tMCF5y6R1IEAZ8Cxqw4TMf9B/kFgr/8KodLZxvOuUaaB8D4OuPWyhsFUNV6vlhrLbOH3P/HIvBCIkXa96p8wyovhplcGakPkH "Python 3 – Try It Online") Takes a list of characters. Returns a list of lists of characters.
## [Python 2](https://docs.python.org/2/), 90 bytes
```
f=lambda s,k=65:s.strip()and s+'\n'+f(''.join([' ',c][91>ord(c.upper())>k]for c in s),k+1)
```
[Try it online!](https://tio.run/##DcvBCoIwGADgV/m7tA2HYFBQoFAeuno3g7k5W@q/sekho1599d0/95ofFncx6nwUU6sEBD7kh/0ppGH2xlEmUEFIyA1Joikh6dMapDUBwmVTH7PCekVlujjXecpYMTTaepBgEALjQ5Kx6LzBGf658rb3YpoM9lAt6zp2AbZQWtXB1Y56Uzf39@d7Fpe2lITFHw "Python 2 – Try It Online") Takes a string. Returns a string.
[Answer]
# Mathematica, ~~115~~ 89 bytes
It takes as `input` a **list of characters** `[{"a", "b", "c", "d", "a"}]` and outputs **a list of lists of characters**
```
Thread[PadRight[Table[#,Max@Position[Alphabet[]/."a"->#,#|ToLowerCase@#]]&/@#]/. 0->" "]&
```
[Try it online!](https://tio.run/##DcuxCsMgFEDRXxGFTCb2BxosXVuQ4iYOzygqJLGYBy20/XbrcO52N8AUNsC8QIvnplMN4I0C/8gxodHg1mAYv8NbqnJkzGU3l/WZwAU0VkwU6Dgzzr663Mor1CscQTJrB9ErJnIaZ0qoHZqqeUcio/n0hVPXLZ3vgP5sa38 "Wolfram Language (Mathematica) – Try It Online")
*-26 bytes from Misha Lavrov*
*-5 bytes from user202729*
but if you want to see the output as it is in the test case, try this (128 bytes) code
[Try it online!](https://tio.run/##DY7BCsIwEAV/JW6gKFTrB2iJ9OBFIWhvMYfVbpNA20gaUcR/j7m@gZk3YrQ0YnQPTGafrjG4yVxc3w@kAHY1LyqxbG0g7ITE7uKMjarFe8a8PONHSD@76PykDsPT4p2i0tUGENY1L/mv9Sf/ptDgTIJrnWWNxYCPSGHOQ7Vh23UNDFYl3CbQRZK5H5kwCmTwJuA45j9Mvr7fgWZWsMZ3xI5@6BegU/oD "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Dyalog APL](https://www.dyalog.com/), ~~27~~ 22 bytes
*5 bytes saved thanks to @Adám*
```
⍉∘↑⊢⍴¨⍨1⌈27|⎕A⍳819⌶⍨∘1
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24RHvZ2POmY8apv4qGvRo94th1Y86l1h@Kinw8i85lHfVMdHvZstDC0f9WwDCgPVGQI1KagHFOWnFyXm5mbmpSsElFZV5aQWK6gpOOenpCq45@ekKaoDAA)
**How?**
`⍴¨⍨` - shape each char to length of
`1⌈` - at least one or
`⎕A⍳819⌶⍨∘1` - index of the char uppercased in alphabet
`27|` - modulo 27
`↑` - flatten to a matrix
`⍉` - and transpose
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 12 bytes
```
θ↙↓E⮌θ×ι⌕α↥ι
```
[Try it online!](https://tio.run/##AVAAr/9jaGFyY29hbP//zrjihpnihpPvvKXirozOuMOXzrnijJXOseKGpc65//9bJ1Byb2dyYW1taW5nIFB1enpsZXMgJiBDb2RlIEdvbGYnXf8tYQ "Charcoal – Try It Online")
-3 thanks to [Neil](https://codegolf.stackexchange.com/users/17602/neil).
[Answer]
# Python, ~~105~~ 103 bytes
*2 bytes saved thanks to @TFeld*
```
lambda s:'\n'.join(''.join((' '+l)[i<1or 91>ord(l.upper())>i+64]for l in s)for i in range(26)).rstrip()
```
[Try it online!](https://tio.run/##LcmxCsIwEIDhVzkXc0ehUJWCol0cXLtbh0iTepIm4dIO9uWjBaf/gz9@plfw@2wvXXZ6fPYa0kl1XpXvwB7Vv6hAFY7ufK6CwLFqgvToyjlGI0jUcFEfHva3HLCHRCt5pWg/GNzVRKWkSTgi5SjsJ7SoWgmD6HFkP0A7L4szCbZwDb2BW3B2o4jyFw)
[Answer]
# [Python 2](https://docs.python.org/2/), ~~111~~ ~~106~~ ~~99~~ ~~98~~ ~~97~~ ~~87~~ 93 bytes
```
s=input()
i=65
while s.strip():print s;s=''.join([' ',c][91>ord(c.upper())>i]for c in s);i+=1
```
[Try it online!](https://tio.run/##BcGxDoIwEADQna84F9tGQ4KJJkrK4uDKThgMFDgDveaujZGfr@@FX1zIX3IWiz6kqE2B9nYtvguuDqSUyBi0eQRGH0FqsUqVH0KvOwXqPPTdvWqIRz2UKQTH2pgG@4kYBkAPYmo82Spn1TLN/N429DO0ad9XJ3CEJ40OXrROB/UH "Python 2 – Try It Online")
[Answer]
# [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 162 bytes
```
s=>{string A="abcdefghijklmnopqrstuvwxyz",r=s;for(int i=-1;++i<s.Max(A.IndexOf);)r+='\n'+string.Concat(s.Select(c=>A.IndexOf(char.ToLower(c))>i?c:' '));return r;}
```
[Try it online!](https://tio.run/##RZBPS8NAEMXPyacYczAb0i54Nd1IKShCi4UKPaiHdbNJV5NdO7PpX/rZYySip8fw3vvBG0Vj5VB3LRlbwepIXjd8buw2C1UtiWAZnsOAvPRGwc6ZAhbSWGDksS@8vIHEipIw6EPBb/u@tWoy@CMYNIcSREciPw83TEUk31Why2pjPj7rxrqvLZJvd/vD8RSNUFBWOmTGejBifJOlqZkQX8gDm/JHW@jDU5lkCaYifrVxOkD5zFklPSO@0rVWnimR/6WZ2kjkz27u9hqZSpLc3KnbGOIkyVD7Fi1gdumy/xk9jVyt@RqN1/1HNCtZtERXoWyanw3L9nSqNcE1zFyh4cHV5VXU48LgEl66bw "C# (.NET Core) – Try It Online")
[Answer]
# Bash, ~~78~~, ~~76~~ 71 bytes
```
for c in {B..a};{ [[ -n ${1// } ]]&&echo "$1";set "${1//[!$c-Z${c,}-z]/ }";}
```
Depending on collation (default LC\_ALL) can save some more bytes
```
for c in {b..z} _;{ [[ -n ${1// } ]]&&echo "$1";set "${1//[!$c-Z]/ }";}
```
[Try It Online](https://tio.run/##Fcq9DoMgFIbhW/kkhE2NM2OHrs4lpFGKP4lyErALhGs/tdubPO88pY15oQiHPaDMXZcr3rrAGLQBsgx9jwprlfJuIwg5CJ38dcefTCNd@7L3InRl5jHSGqfz3MOK8Zvz4RMUHvTxeNKxND8)
[Answer]
# [Perl 5](https://www.perl.org/), 43 bytes
**41 bytes code + 2 for `-nl`.**
```
$c=A;print,s/$c|[^a-z]/ /gi,$c++while/\S/
```
[Try it online!](https://tio.run/##K0gtyjH9/18l2dbRuqAoM69Ep1hfJbkmOi5RtypWX0E/PVNHJVlbuzwjMydVPyZY////xKTklNRErkQg4Aooyk8vSszNzcxLVwgorarKSS1WUFNwzk9JVXDPz0n7l19QkpmfV/xfNy8HAA "Perl 5 – Try It Online")
[Answer]
# JavaScript (ES6), ~~87~~ ~~78~~ 76 bytes
*-9 bytes thanks to [@RickHitchcock](https://codegolf.stackexchange.com/users/42260/rick-hitchcock).*
*-2 bytes thanks to [@Neil](https://codegolf.stackexchange.com/users/17602/neil).*
```
f=(s,i=10)=>s.trim()&&s+`
`+f(s.replace(/./g,c=>parseInt(c,36)>i?c:" "),i+1)
```
Takes input as a string and returns with one trailing newline.
## Test Cases
```
f=(s,i=10)=>s.trim()&&s+`
`+f(s.replace(/./g,c=>parseInt(c,36)>i?c:" "),i+1)
;["hello", "Programming Puzzles & Code Golf!", "~|[abc<0>cba]|~", "abcdefg0123456789"]
.forEach(s=>console.log(f(s)));
```
```
.as-console-wrapper{max-height:100%!important}
```
[Answer]
# R, ~~118~~ 114 bytes
```
function(a)while(grepl("[^ ]",a)){F=F+1;cat(a,"\n");for(j in c("[^a-zA-Z]",letters[F],LETTERS[F]))a=gsub(j," ",a)}
```
Thanks to @Giuseppe for those 4 bytes off
[Try it online!](https://tio.run/##JcxBC4IwGMbxe59i7RAbKdTZDCK0SwcpT5nB69xMmVtMJTDzqy@l2/@BH4@xwreiU6wttSJA389SclIY/pIEJw@UYgco/YR@uN56DFoCDr4rTD2hDalQqRCbHbj9wb1NWPK25aZJwtQ5B3EcXK5TUgp@0XQZqRyM5sOvFQRHRhcG6rpUBYq6vpe8QSt01DlHJy3FEtPFpCBjOfxzHJJp7TZ7lkE6jJjaHw)
Short explanation:
```
function(a)
while(grepl("[^ ]",a)){ #As long as the string is not just spaces.
F=F+1 #Increment letter counter (F is FALSE, hence 0 by default)
cat(a,"\n") #Print string
for(j in c("[^a-zA-Z]",letters[F],LETTERS[F])) #Get rid of non-letters, and the current letter in lower and upper case
a=gsub(j," ",a)
}
```
[Answer]
# [R](https://www.r-project.org/), ~~125~~ 123 bytes
*[Outgolfed by plannapus](https://codegolf.stackexchange.com/a/144905/67312)*
```
for(i in 1:max(p<-pmax(1,match(tolower(S<-el(strsplit(scan(,""),''))),letters),na.rm=T)))cat(ifelse(p<i," ",S),'\n',sep='')
```
[Try it online!](https://tio.run/##FYxLCsMwDAWvEryxDEoh25KcIl12o7gKMfiHLGh7etddPRhmnvQYDiH5QmK9yqu5fhaBMIU8LfdEH6jrXP@7YCL1F2iJ5c0C@zpzhKbSagwKzVMGNMahtc45jKzK0hxmuknaHoN5Uggnx8bjNKCdLO5Df2aLjes2um7o8C8y/Qc "R – Try It Online")
Prints to stdout with a single trailing newline and reads from `stdin()`.
Let's break it down:
```
S <- el(strsplit(scan,"")) # split the string to characters
m <- match(tolower(S),letters) # 1-based index in letters (lowercase a-z)
p <- pmax(1,m,na.rm=T) # parallel max, replaces NA (non-alphabet) or 0 with 1
for(i in 1:max(p)){ # iterate
cat( # print
ifelse(p<1,' ',S), # the corresponding letter in S if p>=1, space otherwise
'\n',sep='') # newline, and no spaces between chars
}
```
## Alternate answer, 106 bytes
```
function(S)for(i in 1:max(p<-pmax(1,match(tolower(S),letters),na.rm=T)))cat(ifelse(p<i,' ',S),'\n',sep='')
```
[Try it online!](https://tio.run/##FYu7DsIwDAB3viKbbSlF6opaJv4ARpZQHDVSXnKMAKn/Hsp0w91Jj@EhTr6YWNfybHTwZhq6f@VFQ8l4JV8EgwnZjKfkPlinof452uR0WVFLLG@WPbSRVVka2eyOkuYbES1OMXiOjfcxWDBg9xDuGWzjOgNQ98gRm0qrMSiCm7bLdnZgd0fUfw "R – Try It Online")
Function; prints to stdout but it's basically my response above ported to accept a list of characters rather than splitting the string, so I feel like it's "cheating." Plus, plannapus' approach with regex is quite neat!
[Answer]
# [Octave](https://www.gnu.org/software/octave/) / MATLAB, ~~74~~ 66 bytes
```
@(s)char(arrayfun(@(c){repmat(c,1,prod(find(upper(c)==65:90)))},s))'
```
[**Try it online!**](https://tio.run/##DclLCsIwEADQq8SNmYEQdKGgECh04bZXGPKphebDpBGsePbo275sN3r5HozWug9Q0T6JgZjpHVqCASx@2JdIG1h1VoWzg7AkB60Uz/815nq5306I@FUVUfYAcuI8M8W4pFlMbd9XX8VRjNl58chrOEjsPw)
[Answer]
# [Japt](https://github.com/ETHproductions/japt/), ~~15~~ ~~14~~ ~~11~~ 10 bytes
First chance to play with Japt's new string padding methods so there might still be room for improvement.
```
y_ùZInZu c
```
[Try it](https://ethproductions.github.io/japt/?v=1.4.5&code=eV/5WkluWnUgYw==&input=IlByb2dyYW1taW5nIFB1enpsZXMgJiBDb2RlIEdvbGYhIg==)
---
## Explanation
Implicit input of string `U`.
```
y_
```
Pass each column of `U` through a function, where `Z` is the current element (or letter, in this case).
```
InZu c
```
Convert `Z` to uppercase (`u`), get its charcode (`c`) and subtract (`u`) 64 (`I`).
```
ùZ
```
Pad the start of `Z` with itself until it reaches that length.
---
## Alternative
```
y_ùZ9aZn36
```
[Try it](https://ethproductions.github.io/japt/?v=1.4.5&code=eV/5WjlhWm4zNg==&input=IlByb2dyYW1taW5nIFB1enpsZXMgJiBDb2RlIEdvbGYhIg==)
[Answer]
# [Haskell](https://www.haskell.org/), ~~137~~ ~~136~~ ~~127~~ 119 bytes
```
import Data.Char
p c=last$0:[k|k<-[0..25],k+65==ord(toUpper c)]
f s=[[last$c:[' '|i>p c]|c<-s]|i<-[0..maximum$map p s]]
```
[Try it online!](https://tio.run/##bYy9CsIwGABn@xSfUqyihiLoUIyLgouCIE4hyEd/bGjShCQFkeKr16qr6x13Jboql7LrhDLaetijR7Ir0QYGUirR@TBOWNVWmwWLCVmu@LyarVeUaptNvL4ak1tIpzwowFHGvkGasAiiVmz7BW/TzcLxVvx6hQ@hGhUqNGDAcd4pFDXNdDDo0ekGpvEXb481hFDAZ0NI9Ir4Xz06W323qJSo73Bunk@ZOxjDTmc5HLQshqPuDQ "Haskell – Try It Online")
Pretty long but I can't think of any way to shorten it further. ~~I feel like there must be some way shorter than the if-then syntax but I don't see it.~~
EDIT: Thanks @streetster for helping me shave off one byte! I didn't use `toUpper` at first because of the cost of importing `Data.Char` but I forgot that it also provides `ord` which is much shorter than `fromEnum`
EDIT 2: Thanks to @Laikoni for shaving off another 6 bytes and identifying a bug which I have now fixed. I used 26 instead of 25 because I forgot that Haskell arrays are inclusive. Then I noticed I could use `last` instead of `head` which would allow me to use `0:` rather than `++[0]`.
EDIT 3: Thanks again Laikoni for those 8 bytes. I had actually forgotten about that space. For some reason Sublime Text flips out without it and I forgot to remove it. I wasn't aware that lists of lines were allowed, I should've read the rules more carefully.
[Answer]
# Excel VBA, 110 Bytes
Anonymous VBE Immediate Window Function that takes input as expected type `Variant\String` from range `[A1]` and uses it to make it rain the alphabet in the VBE immediate window.
```
?[A1]:For i=1To 26:For j=1To[Len(A1)]:c=Mid([A1],j,1):d=Asc(UCase(c)):?IIf((d>64+i)*(d<91),c," ");:Next:?:Next
```
### Sample I/O
```
[A1]="qwertyuiop[]ASDFGHJKL:'zxcvbnm,./"
?[A1]:For i=1To 26:For j=1To[Len(A1)]:c=Mid([A1],j,1):d=Asc(UCase(c)):?IIf((d>64+i)*(d<91),c," ");:Next:?:Next
qwertyuiop[]ASDFGHJKL:'zxcvbnm,./
qwertyuiop SDFGHJKL zxcvbnm
qwertyuiop SDFGHJKL zxcv nm
qwertyuiop SDFGHJKL zx v nm
qwertyuiop S FGHJKL zx v nm
qw rtyuiop S FGHJKL zx v nm
qw rtyuiop S GHJKL zx v nm
qw rtyuiop S HJKL zx v nm
qw rtyuiop S JKL zx v nm
qw rtyu op S JKL zx v nm
qw rtyu op S KL zx v nm
qw rtyu op S L zx v nm
qw rtyu op S zx v nm
qw rtyu op S zx v n
qw rtyu op S zx v
qw rtyu p S zx v
qw rtyu S zx v
w rtyu S zx v
w tyu S zx v
w tyu zx v
w yu zx v
w y zx v
w y zx
y zx
y z
z
```
[Answer]
# PHP, ~~69 78 77~~ 85+1 bytes
```
for($c=A;!$c[1]&&~trim($s=&$argn);$s=eregi_replace("[^".++$c."-Z]"," ",$s))echo"$s
";
```
requires PHP<7. Run as pipe with `-nR` or [try it online](http://sandbox.onlinephpfunctions.com/code/97c87c85e9a7b186f01e5d1bb08825638b996927).
[Answer]
# Bash + sed, 37
```
sed -rne"/^ *$/q;p;s/\W|"{a..z}/\ /gi
```
[Try it online](https://tio.run/##S0oszvj/vzg1RUG3KC9VST9OQUtFv9C6wLpYPya8Rqk6UU@vqlY/RkE/PfP//4Ci/PSixNzczLx0hYDSqqqc1GIFNQXn/JRUBff8nDRFrsSk5JREAA).
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 189 bytes
```
#define F for(q=c,p=s;*p;++p,++q)
char*p,*q,s[99],c[99];main(h){gets(s);F{*q=*p>64&&*p<91?*p-65:*p>96&&*p<123?*p-97:0;h=h>*q?h:*q;}for(puts(s);h--;){F{putchar(*q?--*q,*p:32);}putchar(10);}}
```
[Try it online!](https://tio.run/##NY3BioMwFEX38xUZCmKeCWg7tcTUdlFwtt2XWUgajVD1xYybit/uxA7dXLiHyz2K10oty@auq6bTpCBVP4Q2VwxzJwFlFCGLIks/lCkHQAaWuZsQP0ytKduy6UJDp1r/utBRWUxgc8BT@hUEgEeRnAF5us88EukLJdvdysQhi6XJzQns2WRg5byKcfy/MZxLOhWT76s39CPOvRow222pnN88iX2Zl@U69PVQtm3T1eQ6Pp8P7UhALv1dk@/@UX3@AQ "C (gcc) – Try It Online")
[Answer]
## Ruby, ~~70~~ ~~67~~ 74 bytes
```
f=->s{puts s;(?b..?z).each{|c|s.gsub! /[^#{c}-z]/i,' ';puts s if s=~/\S/}}
```
Thanks to [@TuukkaX](https://codegolf.stackexchange.com/users/41754/tuukkax) for pointing out some parens could be dropped (-3 bytes)
Unfortunately I then had to add 7 bytes because original version failed to handle "z".
Calling it:
```
f.call('The quick brown fox jumps over the lazy dog!')
The quick brown fox jumps over the lazy dog!
The quick brown fox jumps over the l zy dog
The quick rown fox jumps over the l zy dog
The qui k rown fox jumps over the l zy dog
The qui k rown fox jumps over the l zy og
Th qui k rown fox jumps ov r th l zy og
Th qui k rown ox jumps ov r th l zy og
Th qui k rown ox jumps ov r th l zy o
T qui k rown ox jumps ov r t l zy o
T qu k rown ox jumps ov r t l zy o
T qu k rown ox umps ov r t l zy o
T qu rown ox umps ov r t l zy o
T qu rown ox umps ov r t zy o
T qu rown ox u ps ov r t zy o
T qu row ox u ps ov r t zy o
T qu r w x u ps v r t zy
T qu r w x u s v r t zy
T u r w x u s v r t zy
T u w x u s v t zy
T u w x u v t zy
u w x u v zy
w x v zy
w x zy
x zy
zy
z
```
[Answer]
# Oracle SQL, 186 Bytes
Assumes the string will be in a table `t` in column `v`:
```
WITH a(s,l)AS(SELECT v,64 FROM t UNION ALL SELECT REGEXP_REPLACE(s,'[^'||CHR(l+1)||'-Z]',' ',1,0,'i'),l+1 FROM a WHERE l<90)SELECT LISTAGG(RTRIM(s),CHR(10))WITHIN GROUP(ORDER BY l)FROM a
```
[SQL Fiddle](http://sqlfiddle.com/#!4/8fdd1d/15)
**Oracle 11g R2 Schema Setup**:
```
CREATE TABLE t ( v ) AS
SELECT '~|[abc<0>cba]|~' FROM DUAL
/
```
**Query 1**:
```
WITH a(s,l)AS(
SELECT v,64 FROM t
UNION ALL
SELECT REGEXP_REPLACE(s,'[^'||CHR(l+1)||'-Z]',' ',1,0,'i'),l+1
FROM a
WHERE l<90
)
SELECT LISTAGG(RTRIM(s),CHR(10))WITHIN GROUP(ORDER BY l)
FROM a
```
**[Results](http://sqlfiddle.com/#!4/8fdd1d/15/0)**:
```
| LISTAGG(RTRIM(S),CHR(10))WITHINGROUP(ORDERBYL) |
|-----------------------------------------------------|
| ~|[abc<0>cba]|~ |
| abc cba |
| bc cb |
| c c |
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 15 bytes
```
ØaḊiЀŒl‘⁸ẋ"z⁶Y
```
[Try it online!](https://tio.run/##AUoAtf9qZWxsef//w5hh4biKacOQ4oKsxZJs4oCY4oG44bqLInrigbZZ////IlByb2dyYW1taW5nIFB1enpsZXMgJiBDb2RlIEdvbGYhIg "Jelly – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), 98 bytes
```
p c=sum[length[a..c]|a:e<-["B[","b{"],[c]<e]
f s=[[last$c:[' '|i>p c]|c<-s]|i<-[0..maximum$p<$>s]]
```
[Try it online!](https://tio.run/##dY2xDoIwFABn@YpnQ2SBxpkAgw6uJI7NG2op0NgWQtvEYOOvI36A8@XuRu6eUuttm0HULhimpR38yDilAiMvZVUwcmEkJ483wZwJrCQmPbiaMc2dT0XJMsiiavYARlEVDqPapTOlhr@UCSadq7RxiJvhytbdlBzm4O9@AQrBamWlgxR6IO0yDQs3RtkB2rCuegcnuE6dhNuk@yP5I/7@lGafDLcv "Haskell – Try It Online")
Example usage: `f "[Abc]"` yields a list of lines: `["[Abc]"," bc "," c "]`. Use `putStr.unlines.f $ "[Abc]"` for pretty-printed output:
```
[Abc]
bc
c
```
~~Partly inspired by~~ Now directly based on [user1472751's Haskell answer](https://codegolf.stackexchange.com/a/144911/56433).
---
### Previous approach (~~100~~ 99 bytes)
```
f s=[h|i<-[0..26],h<-[[(c:concat[c<$[a..c]|[a,e]<-["B[","b{"],c<e]++cycle" ")!!i|c<-s]],any(>' ')h]
```
[Try it online!](https://tio.run/##dc69CsIwFIbh3as4DcUoxiAODlIddHAtOIYzxGPaBtNE@jO0Fm899gbcPnj44K10@zLOxVhAe1LVZLOt2km5P6Co5qlWdKTgSXeKslRpKQknpYXBGdlFMcEeH4aCMoObDQ3kDAO2ThI7UbZtEYX2w@rMga8rjLW2Hk7wDAsAePfdvWtAQu@d9aaFFApg@kHsv@ZNKBtd19aXkPfj6GZYwjU8DdyCK5L/VzUnSMm/HOMP "Haskell – Try It Online")
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~122~~ 127 bytes
```
param($a)$a;(1..25|%{$i=$_;(-join([char[]]$a|%{(' ',$_)[$_-match'[a-z]'-and[math]::Max(0,($_-bor32)-96-$i)]})).TrimEnd()})-ne''
```
[Try it online!](https://tio.run/##DcpBC4IwFMDxr9LhxXuDJmYUpNWtY7duY8hzClvolBUUpX715fX/@w/9uwlP27RtjAMH7ghYABe0TZJsP65/4M5QFiQfvfOkjOWgtAZehHCFGyiFglJ2/DIWFcuvRsm@VkuwOs9v/KF0Q8tR9WGXCXk8SHBCT0Ik9@C6q69JTEL6BjHGiPOouDKn9GIq1uOMfw "PowerShell – Try It Online")
Short thanks to how PowerShell can dynamically cast between `[char]` and `[int]`, but long because of removing extraneous whitespace and the calculation of whether to output a space or the character.
*Bugfix thanks to beatcracker.*
[Answer]
# Java 8, ~~151~~ ~~147~~ ~~144~~ ~~143~~ 139 bytes
```
s->{String x="\n"+s;for(int i=64,t;++i<91;)for(char c:x.toCharArray())s+=(t=c&~32)>64&t<91&t>i|c<11?c:" ";return s.replaceAll("\\s+$","");}
```
**Explanation:**
[Try it here.](https://tio.run/##pVBda8IwFH33V9yFURqqZW4izNgO8WFPE2GP6kNMo4tLk5Kk4lf96zXOvgy2Jy8J3K9zOOdu6JZ2dMHVJvuumaTWwgcV6tgCEMpxs6KMw@RaAnw6I9QaWNgkFhPfr/z3zzrqBIMJKEigtp302GztEjRXKLJkpU3oOUEk/V7bkSgSw9cuwdc2@6IG2GAXOz326cgYug8xtlESuoQF55dnnPZ7gfOAwKXixIbd7hsbIEDEcFcaBTY2vJBe7EjKEM3nNnpEbYQwqWoCv@ImtyiX0sttVG@1yCD3vhtrswVQ3JjeW8fzWJcuLvzISRWqmIWI@kD45wJ/Lv0/ucGXLLsHPzV6bWieXy88LQ8HyS0EMNYZh3ctVw93UJ9PM69u@JSyJV2czg1T1arqCw)
```
s->{ // Method with String as both parameter and return-type
String x="\n"+s; // Temp-String (equal to leading new-line + input)
for(int i=64, // Index-integer `i` (starting at 64)
t; // Temp-integer
++i<91;) // Loop (1) from 'A' (65) to 'Z' (90) (inclusive)
for(char c:x.toCharArray())
// Inner loop (2) over the character of the array
s+=(t=c&~32)>64 // If the current character as uppercase is larger than 'A'
&t<91 // and smaller or equal to 'Z'
&t>i // and larger than the current index
|c<11? // or the current character is a new-line
c // Append the current character to `s`
: // Else:
" "; // Append a space to `s` instead
// End of inner loop (2) (implicit / single-line body)
// End of loop (1) (implicit / single-line body)
return s // Return the result,
.replaceAll("\\s+$","");
// after we've removed all trailing spaces and new-lines
} // End of method
```
[Answer]
# [q](https://code.kx.com/v2/ref/), ~~42~~ 37 bytes
```
{(+)max[m]$(m:1+mod[.Q.a?(_)x]26)#'x}
```
-5 thanks to streetster!
---
old solution+explanation:
```
{(+)max[m]$'(m:1+mod[.Q.a?lower x;26])#'x}
{ } / lambda func
.Q.a?lower x / get lowercase of input (ignores non-alpha values) and find (?) their index in "a...z" (.Q.a). non-alpha values return `26`
mod[.Q.a?lower x;26] / get mod 26 of each index, this returns 0 where index is 26
(m:1+mod[.Q.a?lower x;26]) / add 1 and assign to m
(m:1+mod[.Q.a?lower x;26])#'x / m and x conform, so we can take (#) m copies of each (') x at corresponding indices
max[m]$'(m:1+mod[.Q.a?lower x;26])#'x / get max of m, and pad each ($') of right-side list to that length
(+) / transpose the char matrix
```
[Answer]
# [SOGL V0.12](https://github.com/dzaima/SOGL), ~~12~~ 11 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md)
```
ā,{Z⁴UW1Χ∙┼
```
[Try it Here!](https://dzaima.github.io/SOGLOnline/?code=JXUwMTAxJTJDJTdCWiV1MjA3NFVXMSV1MDNBNyV1MjIxOSV1MjUzQw__,inputs=UHJvZ3JhbW1pbmclMjBQdXp6bGVzJTIwJTI2JTIwQ29kZSUyMEdvbGYlMjElMjBhYmNCQQ__)
Explanation:
```
ā push an empty array
,{ for each character in the input, pushing it
Z push the uppercase alphabet
⁴ push a duplicate of the character
U uppercase it
W find its index in that alphabet
1Χ get the maximum of that and 1
∙ repeat the character that many times
┼ append horizontally to that array
```
] |
[Question]
[
Write program or function which will take left and right value of dice as integers (1-6) and return value on top.
Dice layout:
```
+---+
| 1 |
+---+---+---+---+
| 2 | 3 | 5 | 4 |
+---+---+---+---+
| 6 |
+---+
,^.
<´ 5 `> <-- Top value
|`._,´|
.6 | 4, <-- Side values
`.|,´
```
So inputting `6 4` will return `5`.
Order is important:
```
2 3 -> 1
3 2 -> 6
```
Program doesn't have to work with invalid input values.
To discourage obvious approach (using table with all combinations), using any builtin text encoding or de/compression routines or base encoding or anything else similar to reduce size is not allowed. Note that using table is still allowed and rolling your own decompression is allowed too, as long as it's not done using some ready library function.
For reference purposes, here's a table of all combinations (i.e. all possible inputs and outputs):
```
23, 35, 42, 54 -> 1
14, 31, 46, 63 -> 2
12, 26, 51, 65 -> 3
15, 21, 56, 62 -> 4
13, 36, 41, 64 -> 5
24, 32, 45, 53 -> 6
```
Shortest code wins, and standard loopholes apply.
[Answer]
There's a nice polynomial expression modulo 7 for the third side given two sides *a* and *b*.
$${3(a^3b - ab^3) \mod 7}$$
or factored
$${3ab(a^2-b^2) \mod 7}$$
The modulo 7 maps to a remainder in {0,1,2,3,4,5,6}.
I explain why it works in this [Math SE answer](https://math.stackexchange.com/a/1101984/24654), though I do think there probably is a cleaner argument I'm missing. The only other two-term polynomial that works is
$${(3a^5b^5 - a^3b) \mod 7}$$
which I originally found by transforming my [bit-bashing](https://codegolf.stackexchange.com/a/44352/20260) into arithmetic operations, then did a brute-force search over polynomials of this form to find the nicer one.
Please feel free to add ports of this into your favorite language; this is a CW post.
**J, 9 by Synthetica**
```
7|3***+*-
```
See my [post](https://codegolf.stackexchange.com/a/44435/18638)
**Dyalog APL, 9 by ngn** (typo fixed by Adám)
```
7|3×××+×-
```
Blatantly stolen from above J answer.
**TI-Basic, 14 by Timtech**
```
7fPart((A³B-AB³)/21
```
**Pyth, 16 by FryAmTheEggman**
```
M%*3-*H^G3*^H3G7
```
Defines a function `g` of two values.
**Golfscript, 18 by Peter Taylor** (old polynomial)
```
~1$*.5?3*@.*@*- 7%
```
**CJam, 18 by Martin Büttner** (ported from Peter's GolfScript) (old polynomial)
```
l~1$*_5#3*@_*@*m7%
```
**Mathematica, 20 by Martin Büttner**
```
Mod[+##(#-#2)3##,7]&
```
Yes, that's a unary plus, and no, there's no shorter way that doesn't use a unary plus.
**dc, 21 by Toby Speight**
```
sb7+d3^lb*rlb3^*-3*7%
```
I have to add 7 to `a` to ensure the difference is always positive (dc has a signed `%` operator).
**Julia, ~~24~~ ~~23~~ 21 by Martin Büttner, fixed by MarcMush**
```
a\b=(3a^5*b^4-a^3)b%7
```
[Try it online!](https://tio.run/##RY/NCsIwEITveYq9CInEQ3499UnUQoIVIiVKm4JvHxuZ4F4@2NmZYZ/bnIL61BquceAmjO4YR3sKoxHxcK5lWstKA124lmSEJG4kuUYrSTc6SbZRgbuuoPtGD5/Cvcbe4c4jT4Eae/f3a@i93yO/@y18vV9Dd8gx4sbY47UQDzIKSpl@bzHa572kXObM9/cFm/K9fgE)
**CoffeeScript, ~~28~~ 26 by rink.attendant.6**
```
x=(a,b)->3*a*b*(a*a-b*b)%7
```
**JavaScript (ES6), ~~28~~ 26 by rink.attendant.6**
```
x=(a,b)=>3*a*b*(a*a-b*b)%7
```
Essentially the same as CoffeeScript.
**Python 28, by xnor**
```
lambda a,b:3*a*b*(a*a-b*b)%7
```
**Bash, 31**
Nothing special:
```
echo $[3*($1**3*$2-$1*$2**3)%7]
```
or alternatively:
```
echo $[3*$1*$2*($1*$1-$2*$2)%7]
```
[Another (longer but perhaps interesting) approach](https://codegolf.stackexchange.com/a/44473/11259).
**Nim, 36 by Sillesta**
```
proc(x,y:int):int=3*x*y*(x*x-y*y)%%7
```
**Java 7, ~~46~~ 44 by rink.attendant.6**
```
int f(int a,int b){return(a*a-b*b)*a*b*3%7;}
```
**Java 8, ~~25~~ 23 by Kevin Cruijssen**
```
a->b->(a*a-b*b)*a*b*3%7
```
**PHP, ~~49~~ 47 by rink.attendant.6**
```
function x($a,$b){echo($a*$a-$b*$b)*3*$a*$b%7;}
```
**Batch, 52 unclemeat**
```
set/aa=(3*(%1*%1*%1*%2-%1*%2*%2*%2)%%7+7)%%7
echo %a%
```
CMD does not support true modulus natively (so can't handle negative numbers) - hence `%%7+7)%%7`.
**LESS (as a [parametric mixin](http://lesscss.org/features/#mixins-parametric-feature)), ~~62~~ 60 by rink.attendant.6**
```
.x(@a,@b){@r:mod(3*@a*@b*(@a*@a-@b*@b),7);content:~"'@{r}'"}
```
See my [post below](https://codegolf.stackexchange.com/a/44436/22867).
**05AB1E, ~~10~~ 8 by Emigna (-2 bytes by Kevin Cruijssen)**
```
nÆs`3P7%
```
[Try it online.](https://tio.run/##yy9OTMpM/f8/73BbcYJxgLnq///RxjpGsQA)
**Haskell, ~~31~~ ~~27~~ 25 by Generic Display Name**
```
a#b=3*a*b*(a*a-b*b)`mod`7
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P1E5ydZYK1ErSUsjUStRN0krSTMhNz8lwfx/bmJmnoKtQkFRZl6JgoqCibLZfwA "Haskell – Try It Online")
**Excel, 27 by by Wernisch**
```
=MOD(3*(A1^3*B1-A1*B1^3),7)
```
**Excel VBA, 25 by Taylor Raine**
```
?3*[A1^3*B1-A1*B1^3]Mod 7
```
**Forth (gforth) 41 by reffu**
```
: f 2>r 2r@ * 2r@ + 2r> - 3 * * * 7 mod ;
```
[Try it online!](https://tio.run/##JYxBCsIwFET3OcWjSyUF40JoJHgVMcZG1IS0YhfePf5UBmbm82cmpDKP@haa1DoQMK5gyonNylthh2Yvd8OBZ/JYSWaMf2emzznTN3SgHZ1M9FilBhZJ7/BJJDaJ3Dk6YuBSxEaZWFtfKbVfZh6vLx4p5T9ZtdQf "Forth (gforth) – Try It Online")
**C#, 23 by Kevin Cruijssen**
```
a=>b=>(a*a-b*b)*a*b*3%7
```
**[Jelly](https://github.com/DennisMitchell/jelly), 9 by caird coinheringaahing**
```
_×+×××3%7
```
[Try it online!](https://tio.run/##y0rNyan8/z/@8HTtw9NB0FjV/P///2b/TQE "Jelly – Try It Online")
Exactly the same as the J and APL answers, but in reverse
[Answer]
# Python, 30
```
lambda a,b:a^b^7*(2<a*a*b%7<5)
```
No lookups, just bit bashing.
The opposite faces come in pairs that are three-bit complements of each other, meaning that they XOR to 7.
```
1,6
2,5
3,4
```
Given two faces from one set, we want to get a face from the other set. For `(1,2,3)`, we can do this with XOR (`^`). So, `^` gives the right answer up to three-bit complement, meaning `x^7`. We can conditionally complement by `x^7*_`.
To decide whether or not to take the complement (XOR with 7), we check whether the triplet violates the right-hand rule. That means, that `a,b` goes in the reverse cyclic order of
```
1,6
2,5
3,4
```
treating each line as one of the three categories. Since the elements in each line are negatives mod 7, we can "hash" them by doing `x*x%7`.
```
1,6 -> 1
2,5 -> 4
3,4 -> 2
```
Each line is obtained from the cyclically previous by multiplying by 4 modulo 7, so we can check whether this relationship holds for `(b,a)` to decide whether to complement: `a*a%7==b*b*4%7`.
This is equivalent to checking whether, modulo 7, `a**2 * b**(-2)` equals `4`. Since `b**6` equals `1` modulo 6, this is equivalent to `a**2 * b**4`. Since the other possible value is 2 (by checking cases), we can check if it's 4 by comparing to 3.
[Answer]
# CJam, ~~43~~ 28 bytes
No idea if a full table based approach will be shorter, but here goes:
```
l_~^56213641532453s@S-#)g7*^
```
Input like
```
2 3
```
Output:
```
1
```
This is a mixture of my previous algorithm to determine the correct face out of 2 faces and xnor's approach of xors.
[Try it online here](http://cjam.aditsu.net/)
[Answer]
# LESS, 62 bytes
Uses the algorithm in [this post](https://codegolf.stackexchange.com/a/44370/22867):
```
.x(@a,@b){@r:mod(3*@a*@b*(@a*@a+6*@b*@b),7);content:~"'@{r}'"}
```
It could be shorter if the integer value was used, but to get it to display I needed to use the CSS [`content`](https://developer.mozilla.org/en-US/docs/Web/CSS/content) property which required [variable interpolation](https://stackoverflow.com/q/6978626/404623).
Nonetheless, it's not often that a CSS preprocessor language is used for code golf!
To use with some HTML, you'd do this:
```
p::after { .x(1, 3); }
```
```
<p>Number on top: </p>
```
[Answer]
# Pyth, 30 bytes
```
K"23542 31463 12651 "h/x+K_Kz6
```
Requires the two digits as input, with no space in between (ex. `23` not `2 3`).
**Explanation:**
Any two digit sequence that lies within `23542` represents two sides that have `1` on top. Likewise, `31463` for 2, etc. Reversing this string gives the sequences for `4` through `6`.
This code just does a lookup in the string `"23542 31463 12651 15621 36413 24532"`, divides the index by 6, and increments to determine what the top side must be.
[Test online here.](https://pyth.herokuapp.com/)
Thanks to @FryAmTheEggman for tips on golfing this.
[Answer]
Takes a similar approach as es1024 with a different lookup string:
# JavaScript (ES6), ~~73~~ ~~72~~ 61 bytes
```
t=(l,r)=>-~('354233146312651215623641332453'.search([l]+r)/5)
```
# JavaScript (ES5), ~~88~~ ~~87~~ 77 bytes
```
function t(l,r){return -~('354233146312651215623641332453'.indexOf([l]+r)/5)}
```
# CoffeeScript, ~~71~~ 62 bytes
~~And just for the fun of it, the code is 1 byte shorter in CoffeeScript as ES6 due to the permitted omission of parentheses~~
Due to the use of the `-~` trick, this turned out to be the same number of characters as ES6.
```
t=(l,r)->-~('354233146312651215623641332453'.indexOf([l]+r)/5)
```
[Answer]
# J (9)
Uses the algorithm from [this](https://codegolf.stackexchange.com/a/44370/18638) post.
```
7|3***+*-
```
Tree graph of the function (might clear some things up):
```
f=:7|3***+*-
f
7 | 3 * * * + * -
5 !: 4 < 'f'
┌─ 7
├─ |
──┤ ┌─ 3
│ ├─ *
└───┤ ┌─ *
│ ├─ *
└───┤ ┌─ +
└───┼─ *
└─ -
```
Demonstration:
```
3 f 5
1
4 f 6
2
2 f 6
3
2 f 1
4
1 f 2
3
4 f 5
6
```
[Answer]
# PHP, 81 bytes
Same as my JavaScript solution:
```
function t($l,$r){echo(int)(1+strpos('354233146312651215623641332453',$l.$r)/5);}
```
[Answer]
# Lua 118
Had to restore last version because of a bug I can't find, nor have time to look for it.
```
z=io.read;o={"","","34","5 2","2165","46 13",""," 31064"," 5612"," 2 5"," 43"}a=z();b=z();print(o[a+b]:sub(a,a))
```
Still working on this though.
[Answer]
# JavaScript (ES6), 79 bytes
Not the shortest but I tried a different approach than currently in the answers.
```
f=(a,b)=>[a,b,7-a,7-b].reduce((p,v,i,r)=>p?p:'2312132'.indexOf([v]+r[i+1])+1,0)
```
[Answer]
# Lua, 89 bytes
A straightforward port of xnor's Python solution.
```
x=require('bit32').bxor
function(a,b)c=a*a*b%7;return x(a,x(b,2<c and c<5 and 7 or 0))end
```
[Answer]
# Bash, 85
This doesn't compete golf-wise with @xnor's magic polynomial. But I think this is another interesting way to calculate the answer:
```
g(){
((d[$1$2]))||{
d[$1$2]=$3
g $2 $1 $[7-$3]
g $2 $3 $1
}
}
g 1 2 3
echo ${d[$1$2]}
```
Specifically we know the the following about dice:
* If the left face is 1 and the right face is 2, then the top face is 3
* Rotation around opposite vertices by 120° gives some more triples of face values. E.g we rotate {l=1,r=2,t=3} once we get {l=2,r=3,t=1} and rotating again we get {l=3,r=1,t=2}
* The sum of opposite faces is always 7
Combining the above recursively (using {1,2,3} hardcoded as a starting point), we can generate the entire mapping of {l,r}->t for all possible values. This answer defines a recursive function g() that populates a full array such that d[lr]=t. The recursive function is initially called with {1,2,3} and recurses all over the whole cube until there are no more array elements that have not been set. The function recurses into itself in two ways:
* with l and r swapped and t subtracted from 7 (opposite faces)
* with {l,r,t} rotated to {r,t,l}
It then does a simple array lookup of the values required.
[Answer]
# [Dyalog APL](http://goo.gl/9KrKoM), 9 [bytes](http://meta.codegolf.stackexchange.com/a/9429/43319)
Blatant character substitution of ɐɔıʇǝɥʇuʎs's [J solution](https://codegolf.stackexchange.com/a/44435/43319):
```
7|3×××+×-
```
Edit: I later noticed that this exact solution was suggested by ngn on Jan 17, 15.
```
the division remainder when divided by seven of
| three times
| | the product of the arguments
| | times \┌───┐
| | \ ┌───┤ × │
┌────┐ ┌────┐ ┌─┴─┐ └───┘ ┌───┐
│ 7| ├───┤ 3× ├───┤ × │ ┌───┤ + │ - the sum of the arguments
└────┘ └────┘ └─┬─┘ ┌─┴─┐ └───┘
└───┤ × │ ---- times
└─┬─┘ ┌───┐
└───┤ - │ - the difference between the arguments
└───┘
```
[TryAPL](http://tryapl.org/?a=%287%7C3%D7%D7%D7+%D7-%29/%A8%283%205%29%284%206%29%282%206%29%282%201%29%281%202%29%284%205%29&run) online!
[Answer]
# Julia, 26 bytes
```
f(a,b)=a$b$7*(2<a^2*b%7<5)
```
or
```
f(a,b)=(3*a^5*b^5-a^3*b)%7
```
or
```
f(a,b)=3*a*b*(a+b)*(a-b)%7
```
[Answer]
# Common Lisp, 45 bytes
```
(lambda(a b)(mod(* 3 a b(-(* a a)(* b b)))7))
```
[Try it online!](https://tio.run/##JYzBCsJADER/ZSgUE6EHd7Xe/Jesi1DomtL2YC/99XW0JCSTGfKe47BMVUb3Cbbgg@GNkwRc/hUR9Wdvhx1xRcANPYIiO@Tlc7EVK5rdwO4enHvbkLNBiLWSsokhqRTPciaRh3RUBlOuxEz1rlr5Q6X1Cw)
Port of xnor solution.
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 49 bytes
```
x=>1+("3542331463126512156236413"+x).IndexOf(x)/5
```
[Try it online!](https://tio.run/##Xcy7CgIxEEbh3qdYUiWsF2b@zDS6WwpW@g7RSJoUJkLePoqVu@XHgRPKLpTUz@8cTqW@Un5uU67zEIept2mm0RqIZ4C8gliFmEQZ6glmbG5/yfdHu0bb3EH6cXP7LqqN1jCMc38GLS0rKy/tVx2/3j8 "C# (Visual C# Interactive Compiler) – Try It Online")
-1 byte thanks to @GB!
The input is a 2 character string containing the visible left and right digits.
Below is the solution that I came up with independently. Leveraging the lookup string from [rink.attendant.6's JavaScript answer](https://codegolf.stackexchange.com/a/44350/8340), I was able to shave off 5 bytes (but now our answers are pretty similar ;)
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 55 bytes
```
x=>1+"42354 31463 51265 21562 41364 24532".IndexOf(x)/6
```
[Try it online!](https://tio.run/##Xcw7CgIxFEDR3lU8UiX4430bnSkFK91DNDJNikmE7D6KlTPl4cKNZR/L1C/vHM@lzlN@7aZcR0gw9DaMuHVCrAKMYgyKZAqEagSCbAIkyuQO1/x4tlvyLRytnzb376j65B2xC@HPjEvrykZLy6rzr/cP "C# (Visual C# Interactive Compiler) – Try It Online")
] |
[Question]
[
Write a program which, according to whether the script has access to the internet, produces an output which is ["Truthy/Falsey"](http://meta.codegolf.stackexchange.com/questions/2190/interpretation-of-truthy-falsey). You may try and connect to any existing site, **at your own discretion** (don't use a shady site which only has 10% uptime - try to keep to above 80% annual uptime). If the site is down, your program does *not* have to work.
It must be a **standalone program** or a **function**. You may use libraries outside of the standard library to achieve this. [Standard loopholes](http://meta.codegolf.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden. This is code golf, so the code with the shortest byte-count wins.
Example pseudocode:
```
function a:
try:
connect to internet
return 1
catch error:
return 0
```
This is my first post on code golf, so if this violates any rules in any way or is a dupe, please alert me.
EDIT: Due to numerous suggestions, I have removed the UTF-8 byte count restriction
[Answer]
# Bash (with *dnsutils*), 3 bytes
Sends a DNS request for "." (DNS root), exit code is 0 for success and >0 otherwise.
**Golfed**
```
dig
```
**Test**
```
% dig >/dev/null; echo $?;
0
% nmcli nm wifi off
% dig >/dev/null; echo $?;
9
```
**Disclaimer**
This will obviously only work if your *DNS* server is sitting in the provider's network, i.e. in the "Internet" (as your provider network is normally a part of it), or if your system is using a public DNS server (like 8.8.8.8 from Google, which Android based systems use), as otherwise, you can get a cached copy from a local *LAN* server (or localhost).
But I assume this is not against the [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules, as there are obviously more than one system where this does work as intended.
Pure-HTTP methods can also give false positives, due to an intermediate caching proxy, and are not guaranteed to work everywhere, so that is not something unique to this method.
**A slightly more reliable version, 8 bytes**
```
dig +tra
```
(a little tribute to @**Dig**ital **Tra**uma !)
Enables the "trace mode", which will force *dig* to do the recursive search by itself (see <https://serverfault.com/a/778830>), avoiding any cache issues.
[Answer]
# Bash + GNU utils, 8
* 5 bytes saved thanks to @Muzer.
```
wget to.
```
The other shell answers check the return code and echo some status output accordingly. This is unnecessary. The shell return code is already a usable Truthy/Falsey code and accessible in the `$?` parameter which is idiomatic for bash. Return code 0 means True. Return code >0 means False.
In use:
```
ubuntu@ubuntu:~$ wget to.
--2017-01-13 09:10:51-- http://to./
Resolving to. (to.)... 216.74.32.107, 216.74.32.107
Connecting to to. (to.)|216.74.32.107|:80... connected.
HTTP request sent, awaiting response... 200 OK
Length: 11510 (11K) [text/html]
Saving to: ‘index.html.6’
index.html.6 100%[===================>] 11.24K --.-KB/s in 0.04s
2017-01-13 09:10:51 (285 KB/s) - ‘index.html.6’ saved [11510/11510]
ubuntu@ubuntu:~$ echo $?
0
ubuntu@ubuntu:~$ sudo ifconfig ens33 down
ubuntu@ubuntu:~$ wget to.
--2017-01-13 09:11:00-- http://to./
Resolving to. (to.)... failed: Temporary failure in name resolution.
wget: unable to resolve host address ‘to.’
ubuntu@ubuntu:~$ echo $?
4
ubuntu@ubuntu:~$ sudo ifconfig ens33 up
ubuntu@ubuntu:~$ # Local network up, upstream link down
ubuntu@ubuntu:~$ wget to.
--2017-01-13 09:11:34-- http://to./
Resolving to. (to.)... failed: Name or service not known.
wget: unable to resolve host address ‘to.’
ubuntu@ubuntu:~$ echo $?
4
ubuntu@ubuntu:~$
```
[Answer]
## Batch, 8 bytes
```
ping to.
```
`ping` will set `ERRORLEVEL` to `1` if the address cannot be resolved or reached.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~11~~ 9 bytes
Saved 2 bytes on "to." courtesy of *ev3commander*
```
…to..wgX›
```
Checks if the length of the content at <http://to>. is greater than 1.
`.w` returns 0 on error.
[Answer]
## R, 20 bytes
```
curl::has_internet()
```
There's a function for exactly this task in the `curl` package.
[Answer]
## Bash ~~66~~ ~~62~~ 21 bytes
```
ping -c1 g.gl echo $?
```
Thanks @Alex L. for the URL shortening tip.
Ungolfed version:
```
r=$(ping -c1 g.gl)
if [ $? -ne 0 ];
then echo "0"
else echo "1"
fi
```
This is my first answer in Bash , i'm not sure i have shortened the script enough.
[Answer]
# Java, 72 bytes
```
a->new java.net.InetSocketAddress("to.",80).getAddress().isReachable(9);
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~15~~ 14 bytes
*One byte saved thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen)'s suggestion*
```
'http://to.'Xi
```
Output is through STDOUT. This displays a non-empty string containing non-zero chars (which is truthy) if there is an Internet connection; and displays nothing (which is falsy) if there's no connection.
This can't be tested online because the `Xi` is not allowed in the online interpreters.
### Explanation
```
'http://to.' % Push this string
Xi % Return contents of that URL as a string. If there is no Internet
% connection this gives an error, with no output on STDOUT
```
[Answer]
## Perl, 15 bytes
```
print`curl to.`
```
Run with:
```
perl -e 'print`curl to.`' 2> /dev/null
```
`curl` outputs stuffs on `STDERR`, don't mind them. If the computer has access to internet, it will print a few lines of html (truthy), otherwise, it will print nothing (falsy).
*Saved 1 bytes by using `to.` (instead of my previous `b.io`) thanks to @Kevin Cruijssen.*
[Answer]
## C#, 87 bytes
```
_=>{try{new System.Net.WebClient().OpenRead("http://g.gl");return 1;}catch{return 0;}};
```
If an exception is considered falsey, which I don't think it is, then this is 65 bytes:
```
_=>new System.Net.WebClient().OpenRead("http://g.gl").ReadByte();
```
I also tried using the link `http://to.` as stated by @KevinCruijssen but it didn't seem to work.
[Answer]
# [8th](http://8th-dev.com/), ~~23~~ 21 bytes
*Two bytes saved thanks to [Kevin Cruijssen's](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen) suggestion* and to my discovery: [<http://to>](http://to) seems to work as well as [<http://to>.](http://to.) (saving another byte)
```
"http://to" net:get .
```
If site <http://to> can be reached, it then prints `true`. Otherwise it prints `false`.
It leaves retrieved data on the stack.
[Answer]
# Javascript, 16 bytes
```
navigator.onLine
```
Returns `true` or `false`.
[Try It!](https://jsconsole.com/?navigator.onLine)
I'm new here, so IDK if I counted bytes properly, or if builtins are cheating...
[Answer]
# MATLAB, ~~32~~ 22 bytes
```
urlread('http://g.gl')
```
**Explanation:**
If the internet connection is up, this will result in `ans` (the default variable) being a string with the entire html-code in plain text (which is **true** in MATLAB).
If the internet connection is down, this will write an error message to STDERR and leave the workspace empty (which is **false** in MATLAB).
Unfortunately, [`urlread`](https://se.mathworks.com/help/matlab/ref/urlread.html) requires a *full url-address*, so `g.gl` is not enough. 11 of the 22 bytes are therefore just the url-address.
---
**Alternative approach:**
A solution that catches the error and leave a 0 (also **false**) in the workspace if the connection is down:
```
0;try urlread('http://g.gl'),end
```
`0;` initializes the default variable `ans` to `0`, which is `false` in MATLAB. Then we [`try`](https://se.mathworks.com/help/matlab/matlab_prog/use-trycatch-to-handle-errors.html) to read the url. This will give an error if the internet connection is down, or a character array if not (which is `true` in MATLAB).
We don't need to catch anything, so we just end. If the urlread call was successful, then `ans` will be a long string with the content of the website, otherwise `ans=0`.
[Answer]
## Bash, 39 bytes
```
exec 4<>/dev/tcp/to./80&&echo 1||echo 0
```
[Answer]
## Mathematica 10 Bytes
Assuming you have a valid copy of Mathematica, and login credentials on user.wolfram.com
```
CloudPut@1
```
will write the value 1 to the cloud.
Truthy: CloudObject[""]
Falsey: $Failed
```
CloudGet@%
```
Will return the value 1 that was uploaded to the cloud.
[Answer]
# JavaScript ES6, 71 43 bytes
```
fetch``.then(a=>alert(1)).catch(a=>alert``)
```
Alerts 1 if online, alerts an empty string if offline. Thanks to Patrick Roberts for helping me shave off some bytes
Old version
```
_=>fetch('http://enable-cors.org').then(a=>alert(a)).catch(a=>alert(0))
```
Alerts `[object Reponse]` if online, alerts `0` if offline
Removed the code snippet, it doesn't work because it loads from a different domain without CORS, but it works in the browser console
[Answer]
# JavaScript ES6, 90 81 Bytes
```
f=a=>{i=new Image();i.src="//placehold.it/1x1";i.onload=b=>a(1);i.onerror=c=>a()}
```
# JavaScript ES6, 22 21 bytes (Invalid)
Some browsers don't fully support, or produce the expected result when using navigator.onLine.
```
f=a=>navigator.onLine
```
[Answer]
# Scala, 54 bytes
```
x=>(Runtime.getRuntime exec "ping -c 1 ai."waitFor)<1
```
Pretty simple; executes a ping command to `http://ai./`, and returns true if it exits with 0, or false otherwise.
[Answer]
## Powershell, ~~64~~ ~~26~~ 23 bytes
Saved 38 bytes, thanks to Shawn Esterman
Saved 3 bytes, and repaired script, thanks to briantist
```
Test-Connection -q g.gl
```
[Answer]
# PHP, 23 PHP + Curl, 14
Using PHP's backtick operator:
```
<?=`curl to.`;
```
---
*Orignal answer:*
I will try to make a start:
```
<?=file('http://x.gl');
```
This outputs nothing if x.gl can't be reached and `Array` if it is.
Another version where I'm not quite sure if they fit:
```
<?=getmxrr('x.gl',$a); // 22 chars
```
[Answer]
# Python 3 + requests, ~~59~~ ~~55~~ ~~53~~ 39 bytes
There has to be a requests answer, right?
```
from requests import*
get("http://to.")
```
Exit status is 0 for internet, 1 for no internet. Example:
```
$ python inet.py
$ echo $?
0
$ # Remove ethernet cable
$ python inet.py
$ echo $?
1
```
Changelog:
* -4 bytes (thanks Mego)
* -14 bytes (thanks pppery)
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 8 bytes
```
`g.gl`¨U
```
*Wait, `¨U` exists?*
Doesn't work on the online interpreter. Exits with error for falsy, runs successfully with no output for truthy.
```
`g.gl` # string literal g.gl
¨U # GET request to that URL
```
For fun, here's a fairly cheaty version. Ports JavaScript:
# [Vyxal](https://github.com/Vyxal/Vyxal) `E`, 13 bytes
```
`ƈ⌈(₍†.on¬ḣ)`
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJFIiwiIiwiYMaI4oyIKOKCjeKAoC5vbsKs4bijKWAiLCIiLCIiXQ==)
Just runs the JavaScript `alert(navigator.onLine)` using the `E` flag
[Answer]
# Elixir, 33 bytes
```
{:ok,_}=:inet.getaddr('to',:inet)
```
0 if connected, 1 otherwise.
[Answer]
# [PowerShell](https://github.com/PowerShell/PowerShell), 12 bytes
```
!!(irm g.gl)
```
[Answer]
## Python 2.7, 70 ~~77~~ Bytes
```
from urllib import*
a=1
try:urlopen('http://to.')
except:a=0
print a
```
```
import urllib as l
try:
l.urlopen('http://a.uk')
print 1
except:
print 0
```
Uses 1 for truthy, 0 for falsy. a.uk redirects to a motorbike clothing company. Saved 3 bytes by assigning to a variable and printing that. And another one for the "to." trick (confirmed to work with urllib), two for getting rid of the pesky indents.
[Answer]
# Julia + Bash (with dnsutils), 10 bytes
```
run(`dig`)
```
``command`` in julia creates a `cmd` object that can be run with `run`.
[Answer]
# [Arturo](https://arturo-lang.io/), 21 bytes
```
download"http://x.gl"
```
Outputs via exit code.
[Answer]
# [R](https://www.r-project.org/), 18 bytes
(2 bytes shorter than the [previous](https://codegolf.stackexchange.com/a/106845/86301) R answer; additionally, this solution does not require an external package to be installed.)
```
!is.null(nsl("a"))
```
[Try it online!](https://tio.run/##K/r/XzGzWC@vNCdHI684R0MpUUlT8/9/AA "R – Try It Online")
The `nsl` function looks up the IP address of a hostname. If there is no Internet connection, it outputs `NULL`, otherwise it outputs an IP address.
Note that we do not need to specify an existing domain name: when the domain name does not resolve (and as long as it does not end in a `.`), the domain name is instead appended to the server domain name. So we can use any 1-letter domain name, and the output of `nsl` is the non-NULL server IP. I think this behaviour is not specific to R.
[Answer]
# Scratch (scratchblocks3 syntax), 32 bytes
```
define
say(translate(1)to(Zulu v
```
"1" on success and an empty string on failure. Relies on Google Translate.
(Also, a slightly more amusing solution that actually outputs "true" but was unfortunately not optimal:)
```
define
say(translate(gwir)to(English v
```
[Answer]
# Clojure, 49 bytes
```
#(try(slurp"http://to.")1(catch Exception _ nil))
```
Returns `1` if it can connect, and `nil` otherwise.
Just attempts to `slurp` the page; throwing a `NoRouteToHostException` exception on failure, which is caught.
Unfortunately, the protocol and dot seem to be mandatory.
] |
[Question]
[
The function TREE(k) gives the length of the longest sequence of trees T1, T2, ... where each vertex is labelled with one of k colours, the tree Ti has at most i vertices, and no tree is a [minor](https://en.wikipedia.org/wiki/Graph_minor) of any tree following it in the sequence.
TREE(1) = 1, with e.g. T1 = `(1)`.
TREE(2) = 3: e.g. T1 = `(1)`; T2 = `(2)--(2)`; T3 = `(2)`.
TREE(3) is a big *big* number. Even bigger than Graham's number. Your job is to output a number even *bigger* than it!
This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the goal is to write the shortest program in any language that deterministically outputs a number bigger than or equal to TREE(3) (to the stdout).
* You aren't allowed to take input.
* Your program must eventually terminate but you can assume the machine has infinite memory.
* You might assume your language's number type can hold **any finite value** but need to explain how this exactly works in your language (ex: does a float have infinite precision?)
+ Infinities are not allowed as output.
+ Underflow of a number type throws an exception. It does not wrap around.
* Because TREE(3) is such a complex number you can use the [fast growing hierarchy](http://googology.wikia.com/wiki/Fast-growing_hierarchy) approximation fϑ(Ωω ω)+1(3) as the number to beat.
* You need to provide an explanation of why your number is so big and an ungolfed version of your code to check if your solution is valid (since there is no computer with enough memory to store *TREE(3)*)
Note: None of the answers *currently* found [here](https://codegolf.stackexchange.com/questions/6430/shortest-terminating-program-whose-output-size-exceeds-grahams-number) work.
[Why is TREE(3) so big?](https://math.stackexchange.com/questions/313134/how-does-tree3-grow-to-get-so-big-need-laymen-explanation)
[Answer]
# New Ruby, 135 bytes, >> Hψ(φ3(Ω+1))(9)
where **H** is the Hardy hierarchy, **ψ** is an extended version of Madore's OCF (will explain below) and **φ** is the Veblen function.
[Try it online!](https://tio.run/##FYrBCgIhFEV/ZdpVPEGXOd38kMdbqKMYhkQwRGTfbjOrc@Cc1xo@Y2Som6dGAf4baaEEP3sgTs4rY9MGwCvW4pj3njnttwgtylAUGy23q@k9Ato1y5lj74GaMtvTqMlvLmChigvVTTMXeh7rGfUk73J/pKkcoMf4Aw)
```
f=->a,n,b=a{c,d,e=a;a==c ?a-1:e ?a==a-[0]?[[c,d,f[e,n,b]],d-1,c]:c:[n<1||c==0?n:[f[c||b,n-1]],n,n]};h=[],k=9,k;h=f[h,p(k*=k)]while h!=0
```
Ungolfed: (using functions, not lambdas)
```
def f(a,n,b)
c,d,e = a
if a == c
return a-1
elsif e
if a == a-[0]
return [[c,d,f(e,n,b)],d-1,c]
else
return c
end
else
x = c || b
if n < 1 || c == 0
return [n,n,n]
else
return [f(x,n-1,x),n,n]
end
end
end
k = 9
h = [[],k,k]
while (h != 0) do
k *= k
p k
h = f(h,k,h)
end
```
Madore's extended OCF:
[![enter image description here](https://i.stack.imgur.com/yY9gB.png)](https://i.stack.imgur.com/yY9gB.png)
And (crudely) Veblen's phi function:
[![enter image description here](https://i.stack.imgur.com/onvs2.png)](https://i.stack.imgur.com/onvs2.png)
Explanation without ordinals:
```
f(a,n,b) reduces an array recursively. (if no third argument given, it takes the first argument twice.)
f(k,n,b) = k-1, k is a positive int.
f([c,d,0],n,b) = f([c,0,e],n,b) = c
f([c,d,e],n,b) = [[c,d,f(e,n,b)],d-1,c], d ≠ -1 and c ≠ 0
f([a],0,b) = [0,0,0]
f([0],n,b) = [n,n,n]
f([],n,b) = f([b],n,b)
f([a],n,b) = [f[a,n-1,a],n,n]
```
My program initiates `k = 9, h = [[],9,9]`. It then applies `k = k*k` and `h = f(h,k)` until `h == 0` and outputs `k`.
Explanation with ordinals:
```
Ordinals follow the following representation: n, [], [a], [a,b,c], where n,d is a natural number and a,c are all ordinals.
x = Ord(y) if y is the syntactic version of x.
a[n,b] = Ord(f(a,n))
ω = Ord([0]) = Ord(f([a],-1,b))
n = Ord(n)
Ω = Ord([])
ψ'(a) = Ord([a])
ψ'(a)[n] = Ord(f([a],n))
φ(b,c) ≈ Ord([[0],b,c])
a(↓b)c = Ord([a,b,c]) (down-arrows/backwards associative hyper operators I designed just for ordinals)
We follow the following FS for our ordinals:
k[n,b] = k-1, k < ω
ω[n,b] = n(↓n)n
(a(↓b)0)[n,b] = (a(↓0)c)[n,b] = a
(a(↓b)c)[n,b] = (a(↓b)(c[n,b]))(↓b[n,b])a, b ≥ 0 and c > 0.
ψ'(a)[0,b] = 0(↓0)0
ψ'(a)[n,b] = (ψ'(a[n-1,a]))(↓n)ω, a > 0 and n ≥ 0. (also note that we've changed from [n,b] to [n,a].)
Ω[n,b] = ψ'(b)[n,b]
```
ψ'(ω∙α) ≈ ψ(α), the ordinal collapsing function described in the image above.
My program more or less initiates `k = 9` and `h = Ω(↑9)9`, then applies `k ← k²` and `h ← h[k,h]` until `h = 1` and returns `k`.
And so if I did this right, `[[],9,9]` is way bigger than the Bachmann-Howard ordinal ψ(ΩΩΩ...), which is way bigger than ϑ(Ωωω)+1.
**ψ(Ω(↓9)9) > ψ(Ω(↓4)3) > ψ(ΩΩΩ)+1 > ψ(ΩΩωω)+1 > ϑ(Ωωω)+1**
And if my analysis is correct, then we should have ψ'(ΩΩ∙x) ~= ψ\*(ΩΩ∙x), where ψ\* is the normal Madore's psi function. If this holds, then my ordinal is approximately ψ\*(φ3(Ω+ω)).
---
# Old Ruby, 309 bytes, Hψ'0(Ω9)(9) (see [revision history](https://codegolf.stackexchange.com/posts/145882/revisions), besides the new one is way better)
[Answer]
## Haskell, 252 Bytes, TREE(3)+1
```
data T=T[T]Int
l(T n _)=1+sum(l<$>n)
a@(T n c)#T m d=any(a#)m||c==d&&n!m
l@(x:t)!(y:u)=l!u||x#y&&t!u
x!_=null x
a n=do x<-[1..n];T<$>mapM(\_->a$n-1)[2..x]<*>[1..3]
s 0=[[]]
s n=[t:p|p<-s$n-1,t<-a n,(l t<=n)>any(#t)p]
main=print$[x|x<-[0..],null$s x]!!0
```
Thanks for help from H.PWiz, Laikoni and Ørjan Johansen for help golfing the code!
As suggested by [HyperNeutrino](https://codegolf.stackexchange.com/questions/139355/golf-a-number-bigger-than-tree3?noredirect=1#comment355715_139355), my program outputs TREE(3)+1, exactly (TREE is computable as it turns out).
`T n c` is a tree with label `c` and nodes `n`. `c` should be `1`, `2`, or `3`.
`l t` is the number of nodes in a tree `t`.
`t1 # t2` is true if `t1` homeomorphically embeds into `t2` (based on [Definition 4.4 here](https://www.cis.upenn.edu/~jean/kruskal.pdf)), and false otherwise.
`a n` outputs a big list of trees. The exact list isn't important. The important property is that `a n` contains every tree up to `n` nodes, with nodes being labelled with `1`, `2`, or `3`, and maybe some more trees as well (but those other trees will also be labelled with `1`, `2`, or `3`). It is also guaranteed to output a finite list.
`s n` lists all sequences length `n` of trees, such that the reverse (since we build it backwards) of that sequence is valid. A sequence is valid if the nth element (where we start counting at 1) has at most n nodes, and no tree homeomorphically embeds into a later one.
`main` prints out the smallest `n` such that there is no valid sequences of length `n`.
Since `TREE(3)` is defined as the length of the longest valid sequence, `TREE(3)+1` is the smallest `n` such that there are no valid sequences of length `n`, which is what my program outputs.
[Answer]
# Python 2, 194 bytes, ~ Hψ(ΩΩΩ)(9)
where **H** is the Hardy hierarchy, and **ψ** is the ordinal collapsing function below the Bachmann-Howard ordinal defined by Pohlers.
Thanks to Jonathan Frech for -3 bytes.
```
def S(T):return 0if T==1else[S(T[0])]+T[1:]
def R(T):U=T[0];V=T[1:];exec"global B;B=T"*(T[-1]==0);return[S(B)]+V if U==1else[R(U)]*c+V if U else V
A=[[[1,1],1],0]
c=9
while A:A=R(A);c*=c
print c
```
[Try it online!](https://repl.it/FyOe/10)
Better spaced version:
```
def S(T):
return 0 if T==1 else [S(T[0])]+T[1:]
def R(T):
U=T[0]
V=T[1:]
global B
if T[-1]==0:
B=T
if U==1:
return [S(B)]+V
return [R(U)]*c+V if U else V
A=[[[1,1],1],0]
c=9
while A:
A=R(A)
c*=c
print c
```
Explanation:
This program implements a variant of the [Buchholz hydra](http://googology.wikia.com/wiki/Buchholz_hydra), using just labels of 0 and 1. Basically, at each step, we look at the first leaf node of the tree, and see if it is labelled with a 0 or a 1.
-If the leaf node is labelled with a 0, then we delete the leaf node, and then copy the tree starting from the parent of the leaf node c times, all of the copies connected to the grandparent of the leaf node.
-If the leaf node is labelled with a 1, then we search back towards the root until we reach an ancestor node labelled with a 0. Let S be the tree starting from that ancestor node. Let S' be S with the leaf node relabelled with 0. Replace the leaf node with S'.
We then repeat the process until we have nothing left but the root node.
This program differs from the normal Buchholz hydra procedure in two ways: First, after we do the above procedure, we recurse back up the tree, and do the label 0 copy procedure described above for each ancestor node of the original leaf node. This increases the size of the tree, so our procedure will take longer than the normal Buchholz hydra, and therefore lead to a bigger number in the end; however, it will still terminate because the ordinal associated with the new tree will still be less the the old tree. The other difference is, rather than start with c = 1 and increasing 1 each time, we start with c = 9 and square it each time, because why not.
The tree [[[1,1],1],0] corresponds to the ordinal ψ(ΩΩΩ), which is considerably bigger than the ordinal ϑ(Ωωω), and so our resulting final number of about Hψ(ΩΩΩ)(9) will definitely exceed TREE(3).
[Answer]
# Javascript, 111 bytes, ~ \$f\_{\psi(\Omega\_\omega)}(6)\$
\$f\$ is the Fast-growing Hierarchy. \$ψ\$ is Buchholz's Psi. This entry, despite being 111 bytes, dominates all of the previous entries in both size and the amount of bytes (except for Loader's number).
Here is the code:
```
s=JSON.stringify;P=([y,z])=>y?JSON.parse((k=s([P(y),z])).replaceAll(s(z),k)):z;for(a=b=0;a=b++<9?[a,0]:P(a););b
```
Here is the same code expanded out:
```
function P([y,z]) {
if (y==0) {
return z
} else {
k = JSON.stringify([P(y),z])
return JSON.parse(k.replaceAll(JSON.stringify(z),k))
}
}
for(a=b=0;a=b++<9?[a,0]:P(a););
b;
```
I'm going to explain both the `P` function and the for loop.
## The Predecessor Function
The inputs of the predecessor function are binary trees with zeroes as leaf nodes. Here are some examples of binary trees:
* `0`
* `[0,0]`
* `[[0,[0,0]],[0,0]]`
* `[[[[[0,0],0],[0,0]],[0,0]],[[0,[0,0]],[0,[0,0]]]]`
* `[[[[[[[[[[0,0],0],0],0],0],0],0],0],0],0]`
The Predecessor function is defined like this:
* `P([0,z])=z`
* `P([x,y])=[P(x),y]` but with all instances of `y` replaced with `[P(x),y]`
* `P(0)` is left undefined
Right away, we can see `0` represents the number \$0\$, and `[0,z]` represents the structure \$z+1\$.
Natural numbers can be represented as `[0,[0,[0,...[0,0]...]]]` with \$n+1\$ zeroes. For example, \$1 =\$ `[0,0]`, \$2 =\$ `[0,[0,0]]`, \$3 =\$ `[0,[0,[0,0]]]`, and so on.
Now consider the string `[1,n]` where \$n>1\$.
`P([1,n])=[0,n]` but replace all instances of \$n\$ with `[0,n]` \$\to\$ `[0,[0,n]]`
Therefore, `[1,n]` corresponds to \$n+3\$, as `P(P(P([1,n]))) = n`
By this logic, `[2,n]` corresponds to \$n+7\$, `[3,n]` corresponds to \$n+15\$, and `[n,n]` would approximately correspond to \$2^n\$. Maybe `[[0,n],n]` corresponds to \$2^{n+1}\$?
### Not so fast!
Consider the string `[[0,n],n]`. One would expect this to correspond to \$2^{n+1}\$, but it is much stronger. `P([[0,n],n])` \$\to\$ `[P([0,n]),n] = [n,n]`, but then the second step would be to replace all instances of `n` with the entire tree, or `[n,n]`. This makes `P([[0,n],n])=[[n,n],[n,n]]` rather than `[n,[n,n]]`.
One would ask whether this would cause an infinite loop. Let's try `P([[n,n],[n,n]])`. If we let `J = P([n,n])`, we will get:
`P([[n,n],[n,n]])=[J,[n,n]]` but with all instances of `[n,n]` replaced with `[J,[n,n]]`
However, there are no instances of `[n,n]` within `J`, because `J` is strictly less than `[n,n]`. Therefore, `P([[n,n],[n,n]])=[J,[J,[n,n]]]`. This works for all `J` less than `[n,n]`.
So this means `[[0,n],n]` corresponds to \$2^{2^n}\$. `[[0,[0,n]],n]` corresponds to \$2^{2^{2^{2^n}}}\$. And finally, `[[n,n],n]` corresponds to \$n \uparrow\uparrow n\$. Now it is time to bring in the Middle Growing Hierarchy.
## Middle Growing Hierarchy
The Middle Growing Hierarchy is defined here: <https://googology.wikia.org/wiki/Middle-growing_hierarchy>
One can make an approximate distinction with the Middle Growing Hierarchy.
* `[0,n]` corresponds to \$m(0,n) \sim n+1\$
* `[1,n]` corresponds to \$m(2,n) \sim n+3\$
* `[2,n]` corresponds to \$m(3,n) \sim n+7\$
* `[n,n]` corresponds to \$m(n,n) \sim n+2^n\$ and \$m(ω,n)\$
* `[n,[n,n]]` corresponds to \$m(n+1,n) \sim 2^{n+1}\$ (not \$m(ω+1,n)\$)
* `[[0,n],n]` corresponds to \$m(ω+1,n) \sim 2^{2^n}\$
* `[[0,[0,n]],n]` corresponds to \$m(ω+2,n) \sim 2^{2^{2^{2^n}}}\$
* `[[1,n],n]` corresponds to \$m(ω+3,n) \sim 2^{2^{2^{2^{2^{2^{2^{2^n}}}}}}}\$
* `[[n,n],n]` corresponds to \$m(ω2,n) \sim n \uparrow\uparrow n\$
One can see a correspondence with the left-hand side of the binary tree and the inner subscript of the Middle Growing Hierarchy. Let's continue the correspondence. I will omit the right hand side of the binary tree and the base of the Middle Growing Hierarchy.
* `[n,n]` corresponds to \$ω\_2\$
* `[0,[n,n]]` corresponds to \$ω\_2+1\$
* `[n,[n,n]]` corresponds to \$ω\_3\$
* `[[0,n],[n,n]]` corresponds to \$ω\_4\$
* `[[1,n],[n,n]]` corresponds to \$ω\_6\$
* `[[0,n],n]` corresponds to \$ω^2\$
So it seems like there is a jump from `[[n,n],n]` to `[[[0,n],n],n]`, similar to the jump from `[n,n]` to `[[0,n],n]`. But even this doesn't capture the power of this notation.
## More Ordinal Comparison
* `[n,[[0,n],n]]` corresponds to \$ω^2+ω\$
* `[[n,n],[[0,n],n]]` corresponds to \$2\timesω^2\$
* `[[n,[n,n]],[[0,n],n]]` corresponds to \$ω^3\$
* `[[[0,n],[n,n]],[[0,n],n]]` corresponds to \$ω^4\$
* `[[[0,n],n],[[0,n],n]]` corresponds to \$ω^ω\$
We're not even at `[[0,[0,n]],n]` yet, what is going on?
* `[[[0,n],n],[[[0,n],n],[[0,n],n]]]` corresponds to \$2\timesω^ω\$
* `[[n,[[0,n],n]],[[[0,n],n],[[0,n],n]]]` corresponds to \$ω^{ω+1}\$
* `[[[n,n],[[0,n],n]],[[[0,n],n],[[0,n],n]]]` corresponds to \$ω^{ω\_2}\$
* `[[n,[[n,n],[[0,n],n]]],[[[0,n],n],[[0,n],n]]]` corresponds to \$ω^{ω\_2+1}\$
* `[[[0,[n,n]],[[0,n],n]],[[[0,n],n],[[0,n],n]]]` corresponds to \$ω^{ω\_3}\$
* `[[[n,[n,n]],[[0,n],n]],[[[0,n],n],[[0,n],n]]]` corresponds to \$ω^{ω^2}\$
* `[[[[0,n],[n,n]],[[0,n],n]],[[[0,n],n],[[0,n],n]]]` corresponds to \$ω^{ω^3}\$
* `[[0,[0,n]],n]` corresponds to \$ω^{ω^ω}\$
Where does the strength comes from? The strength lies in the fact that the binary tree notation corresponds to performing the Middle Growing Hierarchy on ordinals! Here are some examples:
* `[n,n]` corresponds to \$m(ω,n)=n+2^n\$, so `[n,n]` as an ordinal corresponds to \$ω+2^ω=ω\_2\$
* `[[0,n],n]` corresponds to \$m(ω+1,n)=2^{n+2^n}\$, so `[[0,n],n]` as an ordinal corresponds to \$2^{ω+2^ω}=2^{ω\_2}=ω^2\$
* `[[[0,n],n],[[0,n],n]]` corresponds to \$m(ω,m(ω+1,n))=2^{2^{n+2^n}}\$, so `[[[0,n],n],[[0,n],n]]` as an ordinal corresponds to \$2^{2^{ω+2^ω}}=ω^ω\$
* `[[0,[0,n]],n]` corresponds to \$m(ω+2,n)=2^{2^{2^{n+2^n}}}\$, so `[[0,[0,n]],n]` as an ordinal corresponds to \$2^{2^{2^{ω+2^ω}}}=ω^{ω^ω}\$
As it turns out, this pattern continues. I'm not going to go through the full analysis, but here are some more ordinal values. Remember that these are ordinals, not functions!
* `[[1,n],n]` corresponds to \$ω^{ω^{ω^{ω^{ω^{ω^ω}}}}}\$
* `[[n,n],n]` corresponds to \$ε\_0\$
* `[[n,[n,n]],n]` corresponds to \$ζ\_0\$
* `[[[0,n],n],n]` corresponds to \$φ(ω,0)\$
* `[[[n,n],n],n]` corresponds to the BHO
## Speed of Notation
Essentially, if a structure \$K\$ corresponds to \$g\_a (n)\$ in the slow-growing hierarchy, then the structure `[K,n]` corresponds to \$m\_a (n)\$ in the middle-growing hierarchy. This makes the limit `[[[...,n],n],n]`, which corresponds to the first SGH-MGH catching point, of \$ψ(Ω\_ω)\$. For comparison, \$\text{TREE}(n)\$ only corresponds to the ordinal \$ψ(Ω^{Ω^ω})\$, much much smaller. The premise of this notation is essentially nested Goodstein sequences, except it works!
The Middle Growing Hierarchy corresponds closely to the Fast Growing Hierarchy, this is why I put in \$f\_{ψ(Ω\_ω)}\$ as it is a catching point.
# Actual Value of the program
Now that we have gone through the Predecessor function, and how it corresponds to numbers, functions, and ordinals, it is time to return to the value of this program.
To extract a value from a binary tree, such as `[[[0,0],0],0]`, one would have to repeatedly apply the predecessor function until the value crashes down to 0. As we seen before, one would have to apply the predecessor function a massive amount of time, on the order of \$m(ψ(Ω\_ω),x)\$
Just to let you know, `[[[...,0],0],0]` is not degenerate, unlike stuff like \$2 \uparrow\uparrow...\uparrow\uparrow2 = 4\$ in arrow notation. `[[[...,0],0],0]` will produce a massive number.
Here is the code again:
```
for(a=b=0;a=b++<9?[a,0]:P(a););b;
```
First, it sets `a` and `b` equal to `0`. Then, it starts incrementing `b`. If `b` is less than `9`, then it sets `a` to `[a,0]`. This means at `b=9`, `a` would had been already `[[[[[[[[[0,0],0],0],0],0],0],0],0],0]`, which corresponds to a massive number. Then, the predecessor function gets repeatedly applied to `a`, increasing `b` by `1` for each application. Eventually, `a` is going to crash down to `0`, but `b` will be some value far, *far* greater than \$\text{TREE}(3)\$, or \$\text{TREE}(\text{TREE}(...\text{TREE}(3)...))\$ with \$\text{TREE}(3)\$ nests. Finally, the program returns `b`.
# So what?
One of the best thing about this program is how the notation enumerates the catching points between the SGH and the MGH. This program only reaches the very first catching point, but by a few simple extension, this program is able to formalize a meameamealokkapoowa oompa, surpass Strong Array Notation, and beat every single Ordinal Collapsing Function ever devised. \$ψ(Ω\_ω)\$ is still a pathetically small value...
[Answer]
# Julia, 569 bytes, [Loader's Number](http://googology.wikia.com/wiki/Loader%27s_number)
```
r,/,a=0,div,0;¬x=x/2;r<s=r?s:0;y\x=y-~y<<x;+x=global r=(x%2!=0)<1+(+¬x);!x=¬x>>+x;√x=S(4,13,-4,x);S(v,y,c,t)=(!t;f=x=r;f!=2?f>2?f!=v?t-(f>v)%2*c:y:f\(S(v,y,c,!x)\S(v+2,t=√y,c,+x)):S(v,y,c,!x)$S(v,y,c,+x));y$x=!y!=1?5<<y\x:S(4,x,4,+r);D(x)=(c=0;t=7;u=14;while(x!=0&&D(x-1);(x=¬x)%2!=0)d=!!D(x);f=!r;x=!r;c==r<((!u!=0||!r!=f||(x=¬x)%2!=0)<(u=S(4,d,4,r);t=t$d);¬f&(x=¬x)%2!=0<(c=d\c;t=√t;u=√u));(c!=0&&(x=¬x)%2!=0)<(t=((~u&2|(x=¬x)%2!=0)<(u=1<<(!c\u)))\(!c\t);c=r);¬u&(x=¬x)%2!=0<(c=t\c;u=√t;t=9)end;global a=(t\(u\(x\c)))\a);D(D(D(D(D(BigInt(99))))))
```
To save myself a bit of legwork, I decided to port Loader.c to Julia nearly one-for-one and compact it into the block of code above. For those that want to do the comparisons themselves (either to verify my scoring or to help me find mistakes or improve my code), an ungolfed version is below:
```
r,/,a=0,div,0;
¬x=x/2;
r<s=r?s:0;
y\x=y-~y<<x;
+x=global r=(x%2!=0)<1+(+¬x);
!x=¬x>>+x;
√x=S(4,13,-4,x);
S(v,y,c,t)=(
!t;
f=x=r;
f!=2?
f>2?
f!=v?
t-(f>v)%2*c
:y
:f\(S(v,y,c,!x)\S(v+2,t=√y,c,+x))
:S(v,y,c,!x)$S(v,y,c,+x)
);
y$x=!y!=1?5<<y\x:S(4,x,4,+r);
D(x)=(
c=0;
t=7;
u=14;
while(x!=0&&D(x-1);(x=¬x)%2!=0)
d=!!D(x);
f=!r;
x=!r;
c==r<(
(!u!=0||!r!=f||(x=¬x)%2!=0)<(
u=S(4,d,4,r);
t=t$d
);
¬f&(x=¬x)%2!=0<(
c=d\c;
t=√t;
u=√u
)
);
(c!=0&&(x=¬x)%2!=0)<(
t=((~u&2|(x=¬x)%2!=0)<(u=1<<(!c\u)))\(!c\t);
c=r
);
¬u&(x=¬x)%2!=0<(
c=t\c;
u=√t;
t=9
)
end;
global a=(t\(u\(x\c)))\a
);
D(D(D(D(D(BigInt(99))))))
```
No previous counts because I made way too many byte miscounts in the aggressive golfing I've done.
[Answer]
# Ruby, 140 bytes, ~ Hψ(ΩΩΩ)(81)
where **H** is the [Hardy hierarchy](https://en.wikipedia.org/wiki/Hardy_hierarchy), and **ψ** is the standard ordinal collapsing function below the Bachmann-Howard ordinal, as defined [here](http://googology.wikia.com/wiki/User_blog:Deedlit11/Ordinal_notations_II:_Up_to_the_Bachmann-Howard_ordinal).
```
s=->t{*v,u=t;t==1?[]:v<<s[u]}
r=->t{*v,u=t;$b=t[0][0]?$b:t;u==1?v<<s[$b]:u[0]?v+[r[u]]*$c:v}
$c=9
a=[],[1,[1,1]]
($c*=9;a=r[a])while a[0]
$c
```
[Try it online!](https://repl.it/N8ju/14)
Ungolfed version:
```
def S(a)
*v, u = a
if a == 1
return []
else
return v + [S(u)]
end
end
def R(t)
*v, u = t
if t[0] == []
$b = t
end
if u == 1
return v + [S($b)]
elsif u == []
return v
else
return v + [R(u)]*$c
end
end
$c = 9
a = [[],[1,[1,1]]]
while a != [] do
$c *= 9
a = R(a)
end
print $c
```
This program implements the Buchholz hydra with nodes labelled with []'s and 1's, as described in my Python 2 entry.
The tree [[],[1,[1,1]]] corresponds to the ordinal ψ(ΩΩΩ), which is considerably bigger than the ordinal ϑ(Ωωω) = ψ(ΩΩωω), and so our resulting final number of about Hψ(ΩΩΩ)(81) will exceed TREE(3).
[Answer]
# Javascript, 511 bytes
I am new to code golf (this is my second time), but certainly not to implementing or inventing large numbers. However this programs takes quite a lot of code to beat TREE(3) :( The program results in \$f\_{TFBO+1}(3) = f\_{TFBO}(f\_{TFBO}(f\_{TFBO}(3)))\$ in the fast-growing hierarchy, where \${TFBO}\$ is the Takeuti-Feferman-Buchholz Ordinal \$\psi(\Omega\_{\omega+1})\$. It uses Buchholz hydras and implements the BH function. Here is my compressed code, which was done with Naruyoko's Javascript compressor:
```
_="69{%t.length-1D*6m#{%B]}*6s#{t.splice(m#,14*@n=1;*6e#{7==0/s#;if(9>1/$i=0;i<n;i:t'B-1]4}}7>0&&typeof t==\"number\"/$i=98t[i]<m#8i--/}@s;$j5i8j <= 98j:s't[j]4@?5s;?[j]=?[i]-1;?[l(?)]=0;s#;$k508k <= l(?)8k:t'?[k]4}7==A/B]=n+1Dn += 1;%tD*6b(k/i5[\"+\",0];$l508l < k-28l:i'A)}while(l(i)>=0/i=e(i4%nD*Console.log(b(b(b(3))));#(t)$for(let %return '.push(*\n /){4)D5 = 6function 7if(m#8; 9l#:++/?sa@var A\"w\"Bt[9D;}";for($ of"DBA@?:987654/*'%$#")with(_.split($))_=join(pop());eval(_)
```
This is basically incomprehensible, with only fragments of the original code revealing themselves, so here is the original code (still somewhat golfed):
```
function l(t){return t.length-1;}
function m(t){return t[l(t)]}
function s(t){t.splice(m(t),1);}
var n=1;
function e(t){if(m(t)==0){s(t);if(l(t)>1){for(let i=0;i<n;i++){t.push(t[l(t)-1]);}}}if(m(t)>0&&typeof t=="number"){for(let i=l(t); t[i]<m(t); i--){}var s;for(let j = i; j <= l(t); j++){s.push(t[j]);}var sa = s;sa[j]=sa[i]-1;sa[l(sa)]=0;s(t);for(let k = 0; k <= l(sa); k++){t.push(sa[k]);}}if(m(t)=="w"){t[l(t)]=n+1;}n += 1;return t;}
function b(k){i = ["+",0];for(let l = 0; l < k-2; l++){i.push("w")}while(l(i)>=0){i=e(i);}return n;}
Console.log(b(b(b(3))));
```
# Explanation
This program, as I mentioned earlier implements Buchholz hydras, which are stored as arrays. This is what the code does:
It defines shorthands l(t), the index of the last element of the array, m(t), the last element of the array, and s(t), which chops off the last element of the array (the rightmost head). I also define a counter n which keeps track of how many times the hydra has been expanded.
The biggest block of code is e(t), which expands the hydra. Here is how it works: it checks if the rightmost head (which it will chop off) has label zero. If it does, then it calls s(t), splicing the last item in the array, and checks if l(t)>1, i.e. the rightmost head's parent is not the root. If it is, then it uses a for loop to push n copies of the rightmost head's parent (which is not the root).
Next, if it is not zero, it checks if it is a positive integer. If it is, it uses a for loop to find i such that t[i] has a lower label than the rightmost head. Then it creates a tree s such that everything after (and including) t[i] is in s, i.e. the subtree rooted at t[i]. It also creates sa where the rightmost head is relabeled with sa[i]-1 and the rightmost head of sa is relabeled with 0. It then deletes t's rightmost head and uses a for loop to insert sa into t.
If it is not zero, then it can only be the least limit ordinal omega (represented by the string "w"). If it is, it simply relabels it with n+1. After everything, it increments n by 1 and returns the new version of t.
Next, we have the function b(n), which represents the function BH(n). It sets i to the tree [+,0] and then pushes n-2 copies of omega "w". It then repeatedly applies e to i (expands i) and returns the final output. My large number is then b(b(b(n)))
# Size
Why does this produce a large enough number? Well, the original inventor, Wilfried Buchholz, proved that this function eventually dominates (overtakes) any function which is provably total in \$\Pi^1\_1\$-comprehension with bar induction (\$\Pi^1\_1-CA+BI\$), so the \$BH(n)\$ function is commonly approximated to \$\psi\_0(\varepsilon\_{\Omega\_\omega +1})\$ using the fast-growing hierarchy, so my number is approximately \$f\_{ψ(\varepsilon\_{\Omega\_\omega+1})+1}(3)\$.
The goal is \$\psi\_0(\Omega^{\Omega^\omega \omega})\$, which is much less than \$\psi\_0(\varepsilon\_{\Omega+1})\$, let alone \$\psi\_0(\varepsilon\_{\Omega\_\omega+1})+1\$. In fact, not only does this number defeat TREE(3), it also defeats SCG(13), which is around \$\psi\_0(\Omega\_\omega)\$, although it still falls massively short of Loader's number.
In terms of size, my entry would come second place, while in terms of length, it would come second-to-last. The latter is what matters more, so this is probably a really bad entry.
[Answer]
# JavaScript, 190 bytes, Hψ(εΩ+1)(9)Based off of [this analysis](https://googology.wikia.org/wiki/Pair_sequence_number#Corresponding_ordinals)
```
A=[0,1,2];B=[0,1,2];for(F=C=9;F;F--){for(C++,G=0;G<=F;G++)(A[F]||A[F-G]<A[F]-H)&&(B[F]?(I=G,G=F):(H=A[F]-A[F-G],B[F-G]<B[F]&&(I=G,G=F)));for(J=0;J<C*I;J++)A[F]=A[F-I]+H,B[F]=B[F-I],F++;H=0}C
```
This program is a modified version of [this 225B Pair-sequence number translation in JavaScript](https://googologyforeveryone.fandom.com/wiki/User_blog_comment:C7X/Values_of_%5C(C(1,b)%5C)_for_small_b/@comment-32994025-20190313122812/@comment-32994025-20190316001206). For Pair-sequence number and their original code, see [here](https://googology.wikia.org/wiki/Pair_sequence_number).
The modifications done:
* It is in JavaScript instead of BASIC.
* No iteration(fψ(Ωω+1)->fψ(Ωω))
* The sequence is (0,0)(1,1)(2,2), which corresponds to ordinal ψ(εΩ+1).This is in Hardy-hierarchy ordinal
[Answer]
# Python, 359 (184 without whitespace) 224 212 bytes, ~$$H\_{ψ(ψ\_Ι(0))[7]}(8)$$
```
*S,n=0,2,9
while S:
i=r=d=0
for a in S[::-1]:
i-=1
if d<S[-1]-a:
r=r or i;d+=S[-1]-a-d>1
if[k+d for k in S[i:]]<S[r:]:break
p=i+1
S.pop();n*=n
if r:S=S[:p]+[d*i+k for i in range(n)for k in S[p:]]
```
I'm new to codegolf so I'm not sure if all the whitespace here counts. If not, this entry isn't the shortest entry, but vastly dominates patcail's entry in size.
The code here implements [Sudden Sequence System](https://googology.wikia.org/wiki/User_blog:Antimony_Star/Full_analysis_of_SSS,_with_respect_to_weak_buchholz) (definition [here](https://googology.wikia.org/wiki/User_blog:Antimony_Star/Non-formal_explanation_of_how_Hyper_Sequence_and_Sudden_Sequence_System_works)), which is known to have a perfect correspondence to ordinals below $$\psi(\psi\_I(0))$$ represented in Extended Weak Buchholz function. The original idea uses sequences lexicographically less than (0,2) to represent ordinals, but to save characters the sequence itself is reversed.
There are actually a few open problems here that we don't know the answer to, but strongly suspect they are true:
1. Does the limit of Extended Weak Buchholz function equal to limit of Extended Buchholz function?
2. Is Sudden Sequence System terminating?
3. Does the correspondence between the two systems hold?
Edit 1:
It's broken due to a silly mistake. Now S is correctly initialized.
Thanks to Naruyoko for a few great optimizations.
Edit 2: Optimized a bit
] |
[Question]
[
For the purpose of this challenge, we'll define **whitespace** as *only* linefeeds (0x0A) and spaces (0x20). Note that most languages and regex flavours consider many other characters as whitespace as well, both inside and outside the ASCII range so you might not be able to make use of the corresponding built-ins.
## The Cops' Challenge
You should write a program or function in a language of your choice, which takes a string, consisting of ASCII (except NUL) characters, as input and outputs it with all whitespace removed. For example if you received the following input:
```
H e l l o,
W o r l d!
```
You should output
```
Hello,World!
```
Your submission will then be your *source code* with all whitespace removed (the same process as passing your solution as input to itself, although your solution may also contain characters outside the ASCII range). Your goal is to make it as hard as possible to figure out where whitespace needs to be inserted to recover a valid solution in your language of choice. Note that robbers may insert fewer whitespace than you removed, but not more. Also remember that robbers don't have to match your exact code, they just have to find any valid solution.
Your answer should contain the following:
* The language (and version if necessary) in which you wrote your solution.
* The byte count of your solution *before* removing whitespace.
* Your solution with whitespace removed.
Your solution may be either a program or function, but not a snippet and you must not assume a REPL environment. You may take input via STDIN, command-line argument or function argument and output via STDOUT, function return value or function (out) parameter.
In the interest of fairness, there must be a freely available interpreter or compiler for your chosen language.
You must not use built-ins for hashing, encryption or random number generation (even if you seed the random number generator to a fixed value). Your solution must be able to process any string of 100 characters or less in under 10 seconds on a reasonable desktop machine.
If your answer has not been cracked within 7 days (168 hours), you may reveal your own solution at which point your answer is considered *safe*. As long as you don't reveal your solution, it may still be cracked by robbers, even if the 7 days have already passed. The shortest safe answer wins (measured before removing whitespace).
If your answer does get cracked, please indicate this in the header of your answer, along with a link to the corresponding robber's answer.
**[Go here](https://codegolf.stackexchange.com/q/103183/8478) for the robbers' part.**
### Uncracked Submissions
```
<script>site = 'meta.codegolf'; postID = 5686; isAnswer = false; QUESTION_ID = 103182;</script><script src='https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js'></script><script>jQuery(function(){var u='https://api.stackexchange.com/2.2/';if(isAnswer)u+='answers/'+postID+'?order=asc&sort=creation&site='+site+'&filter=!GeEyUcJFJeRCD';else u+='questions/'+postID+'?order=asc&sort=creation&site='+site+'&filter=!GeEyUcJFJO6t)';jQuery.get(u,function(b){function d(s){return jQuery('<textarea>').html(s).text()};function r(l){return new RegExp('<pre class="snippet-code-'+l+'\\b[^>]*><code>([\\s\\S]*?)</code></pre>')};b=b.items[0].body;var j=r('js').exec(b),c=r('css').exec(b),h=r('html').exec(b);if(c!==null)jQuery('head').append(jQuery('<style>').text(d(c[1])));if (h!==null)jQuery('body').append(d(h[1]));if(j!==null)jQuery('body').append(jQuery('<script>').text(d(j[1])))})})</script>
```
[Answer]
# Haskell, 100 bytes, [cracked by nimi](https://codegolf.stackexchange.com/a/103204/56433)
```
main=interact$iddoidlinesidwordsdoidoidoid=doiddoid<-dooiidoid<-dooiddoiddodoid
```
This is a full program and a dadaistic poem.
---
**Code with withspace** [(Try it online!)](https://tio.run/nexus/haskell#@5@bmJlnm5lXklqUmFyikpmikJIPJHIy81KLFYCM8vyilGIusFh@pgKQAArapuRzASmQoI1uSj5IIjOFSwHOhcpxAY0C6chM@f@fHrYAAA "Haskell – TIO Nexus")
```
main=interact$id doid lines id words
doid oi d o id=do
iddoid<-do oi id
oid<-do o iddoid
do d oid
```
Still looking quite poetic, if you ask me.
**De-obfuscated**
```
main = interact f
f s = do
l <- lines s
w <- words l
id w
```
**Explanation**
The `do`-notation is only syntactic sugar, so `f` can equivalently be written as
```
f s = lines s >>= words >>= id
```
For lists the `>>=`-operator is defined as `concatMap`, so `f` becomes
```
f = concat . map id . concat . map words . lines
```
So given an input `"a b\nc"`, `lines` splits the input at newlines `["a b","c"]`, `words` splits each line at white space yielding `[["a","b"],["c"]]` (as I realised only now this includes newlines, so `lines` actually isn't needed). Concatenating once gives `["a","b","c"]`, `id` is the identity function and as such has no effect and the final concatenation yields the string `"abc"`.
[Answer]
# C, 475 bytes, [cracked by Riley](https://codegolf.stackexchange.com/questions/103183/significant-whitespace-robbers/103244#103244)
Certain parts of C make it really really easy to see where whitespace should go. The c pre-processor, however, does not. So this code is sort of in two halves: up to line 17 (236 characters with whitespace) the code is virtually unobfuscated, and after that (239 characters with whitespace), good luck!
Not gonna win this competition by a long shot, but I wanted to see what could be done with the c pre-processor.
```
#include<unistd.h>#defineachar#defineb*#definecwrite#definedstdin#defineestdout#definefread#defineg(#defineh)#defineiwhile#definejif#definek0#definel&#definem,#definen=#defineo;#definep1#definegpmlmlh#defineabo#definemldmp#definejgdoabo#definelbabod#definegfhaboc#definejgmben#definepmlfg#definegpmlbintmain(){ajgajgmljgigpmlkmlgpmlhjgd!=''&&gpm!='\n'gfgpmlgpmlo}
```
Compiles (with warnings, if you enable them) with `gcc -std=c89 -ansi` and works like `cat file | ./a.out`
---
This was cracked much faster than I thought, congrats! My strategy was to use `#defines` to remove obvious token boundaries (like ';') and then use more `#defines` to make it REALLY unintuitive how they were shuffled around.
This, by the way, is what the code looks like after only the obvious whitespace has been added:
```
#include <unistd.h>
#define a char
#define b *
#define c write
#define d stdin
#define e stdout
#define f read
#define g (
#define h )
#define i while
#define j if
#define k 0
#define l &
#define m ,
#define n =
#define o ;
#define p 1
// thus begins the obfuscation
#define gpmlmlh
#define abo
#define mldmp
#define jgdoabo
#define lbabod
#define gfhaboc
#define jgmben
#define pmlfg
#define gpmlb
int main(){
ajgajgmljgigpmlkmlgpmlhjgd!=''&&gpm!='\n'gfgpmlgpmlo
}
```
[Answer]
# Octave, 69 bytes, SAFE!
```
@(U)eval([85329685312682956148388531268295156241''])
```
**Input format:**
Newlines can't be inputted directly in the command prompt. Create the string by concatenation like this:
```
str = ['This is ',10,'a',10,'string']
str = This is
a
string
```
Call the function like this (add whitespace):
```
f=@(U)eval([85329685312682956148388531268295156241''])
f(['This is ',10,'a',10,'string'])
```
**Original code:**
You only needed 66 bytes for this to work, but I wrote 69 in the header in order to not give away too much information.
The original code looks like this:
```
@(U)eval([853 296 853 126 829 561 48 38 853 126 829 51 562 41 ''])
```
**Explanation:**
```
@(U)eval(.....) % Anonymous function taking U as the input variable
```
`U` is code point `85` in the ASCII table, so it would appear like the first space should be after `85`. *Wrong!*
If we insert the space after `853` instead, we should get character number `853`, right..? Using `char` to check if that's a recognizable character:
```
char(853)
warning: range error for conversion to character value
```
However, we don't use `char` in the code, we use the shorter version where we concatenate the numbers with an empty string `[853 '']`. Instead of giving an out of range error, the shorter version simply takes the numbers modulus 256.
It just so happen to be that `85+3*256 = 853`. While `char(853)` gives a warning, `[853,'']` returns `U`.
The obvious way to do this task in Octave is:
```
@(U)U(U~=10&U~=32)
```
We know that there has to be an opening parentheses (code point 40) after the first `U`. `29` obviously doesn't fit so we shift the space one further right and get `296`. `mod(296,256) = 40`. Bingo!
Continue like this and end up with the sequence:
```
[853 296 853 126 829 561 48 38 853 126 829 51 562 41 '']
ans = U(U~=10&U~=32)
```
Finally, we use `eval` to turn the string into code.
[Answer]
## JavaScript ES6, 199 bytes, [cracked by SLuck49](https://codegolf.stackexchange.com/a/103399/58563)
A rather bulky entry with 33 bytes of whitespace to add.
```
s=>eval(atob`ISYgJiAtOkI8Qk97BRBeaxZFShoUZSsiOGkMenNy`.replace(/./g,(c,i)=>String.fromCharCode(c.charCodeAt()^(k+="SecretCode".split(/\w/)[i%11].length)),k=0)).join``
```
[Answer]
# Befunge-93, 58 bytes, Safe!
```
_vv$v<~:!`:<#^0*@-:0*5|845\+`-v0,<#-^<
```
[Try it online!](http://befunge.tryitonline.net/#code=X3Z2JHY8fjohYDo8I14wKkAtOjAqNXw4NDVcK2AtdjAsPCMtXjw&input=)
**Original Program**
```
_vv
$ v<
~:!`
:<#^0
* @
-:0
*5 |
8
45
\+`
-
v0,<
#-
^<
```
[Try it online!](http://befunge.tryitonline.net/#code=X3Z2CiAkIHY8CiB-OiFgCiA6PCNeMAoqICBACi06MAoqNSB8CjgKNDUKXCtgCi0KdjAsPAojLQpePA&input=SCBlIGwgbCBvLAogVyBvIHIgbCAgZCE)
The trick to this was that the path of execution was more vertical than horizontal, then various spaces were inserted at random in the code to further shuffle the vertical paths. Once the line breaks and whitespace were finally removed, there was hopefully then very little to indicate how the operations related to each other.
In case that wasn't difficult enough, I also threw in a bit of interleaving, so a number of operations ended up being executed by different code paths flowing perpendicular to each other. The idea being that if you thought you'd found the correct position for a particular command, you wouldn't realise you might need to use it again later in the code.
Not sure if it was worth all that effort trying to make things complicated, or people didn't even bother trying to solve it. :)
**Code Explanation**
```
_ Since an empty stack is treated as zero, this initially just branches right.
v The program flow is then directed downwards.
$ And this drop command initially does nothing because the stack is still empty.
~ A character is read from stdin.
:: Two duplicates are created.
55+- We subtract 10 from the first copy (the 0- is just a nop to confuse things).
\48*- And subtract 32 from the second copy.
* The product of those two will be zero if the character is a newline or space.
_ So if we got whitespace, our branch goes right again repeating the loop.
v If not, we go left, wrapping around till we hit the down arrow in column 3.
:<: Again we make two duplicates of the character.
0`!| One copy is used to compare if it's not greater than zero.
@ If it's not (i.e. it's the EOF), the branch goes up and we terminate.
< Otherwise we go down and to the left.
, Output the second copy of the character, leaving one remaining on the stack.
0 Push a zero to force the next branch right.
v Redirect the flow down, wrapping to the top again.
_ Back at our initial branch, the zero we pushed forces us right.
v Again the program flow is directed downwards.
$ And the drop command gets rid of the last duplicate character.
~ So now we're back reading the next character and the loop repeats.
```
[Answer]
# ><>, 40 bytes, [Cracked](https://codegolf.stackexchange.com/a/103231/41938) by Teal pelican
```
v<<i/\:=::a?0/>/1?o-=="?;">^
```
I used [fishlanguage.com](https://fishlanguage.com) by the way, just in case there are differences between interpreters.
[Answer]
# C#6, 201 bytes, [Cracked by Link Ng](https://codegolf.stackexchange.com/a/103233/58106)
```
usingSystem.Linq;_=>string./**/#iftrueJoin(/*"*//*/""/**//*/"*/",#elseConcat(//*/,#endiffrommin""letp=$@"{@""[1]}"fromiin(_.Replace(p,@""))where!new[]{p[0]^32^10}.Contains(i)select@i);
```
184 bytes collapsed, leaving you 17 bytes of whitespace.
Cracked solution using the `Concat` whereas my intended solution used the `Join`, here's the intended solution:
```
_=>string./**/
#if true
Join(/*"* //*/""/**//*/"* /",#elseConcat(//*/,
#endif
from m in" "let p=$@"{@" "[1]}"from i in(_.Replace(p,@"
"))where!new[]{p[0]^32^10}.Contains(i)select@i);
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 22 bytes. [Cracked](https://codegolf.stackexchange.com/a/103365/36398) and [cracked](https://codegolf.stackexchange.com/a/103366/36398).
This is a program that takes input through STDIN and produces the output through STDOUT.
Code without spaces or newlines:
```
t'@*'dm1e5%Mdw%Y(
```
The **input format** is a little awkward because of how MATL takes string input. Strings with newlines cannot be entered directly through STDIN, because each input has to be a single line (newline marks the end of input). So the format is as follows:
1. A string is enclosed with **single quotes**. If the string content includes single quotes, they are **escaped by duplicating**. Example: `'I''m a string'`
2. To enter a string with newlines one needs to split the string at newlines and concatenate everything (by means of square brackets), including numbers as **ASCII codes**. For example, consider the string formed by my first and last names with a newline in between. It would be entered as `['Luis' 10 'Mendo']`.
This allows entering any other (possibly non-printable) ASCII codes. So the string in item 1 above could be alternatively entered as `['I' 39 'm ' 97 32 'string']`. Check it [here](http://matl.tryitonline.net/#code=WydJJyAzOSAnbSAnIDk3IDMyICdzdHJpbmcnXQ&input=).
The only condition is that at least one of the parts within the brackets is a string. That forces any numbers to be interpreted as ASCII codes when concatenating.
~~Sorry about the awkward~~ Good luck using this format!
## Original solution
```
t' @ *'dm1e 5%
Mdw%Y
(
```
Each `%` is a comment symbol, and so the rest of the line is ignored.
Spaces do nothing, but serve as separators. For example, `1e5`, without the space, would be interpreted as the number `100000`.
`t` takes the input and duplicates it.
`' @ *'` pushes that string, and `d` computes its consecutive differences, which gives `[32 -32 10]` (the `-32` is useless).
`m` gives a logical row array indicating which characters are `32` or `10` (or `-32`).
`1` followed by `e` reshapes as a row. This is no-op here.
`5` followed by `M` pushes `1` again (last input to the most recent multiple-input function, which is `e`).
`d` computes consecutive differentes of `1`, and so gives `[]` (empty array).
`w` swaps, and finally `(` assigns `[]` to whitespace characters, i.e. removes them.
[Answer]
# Java, 3241 + 28 Bytes for a big Integer import
This entry is solely to prove the possibility of a purely cryptographically secure entry. I believe this is within the rules, but if it is against the spirit, please let me know and I will delete out of fairness. I will leave this "unsafe" indefinitely until such a time when (and if) a crack gets found. This is a monstrosity and could surely be further optimized, but here it is.
```
interfacer{staticvoidmain(String[]A){Strings=",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,",q=",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,",a="",b="";for(Stringt:s.split(",")){a+=t.length();}for(Stringt:q.split(",")){b+=t.length();}if((newBigInteger(a).multiply(newBigInteger(b)).toString()).equals("3649760552772806991406184564114682549877113954361462782925976763675666255653486225665808494957477900238166874367635068317805381406282572366371821972593595701388544127398102379288357379612333197280663769935384647844344358594407966485992727383589962048236726744715096711312156760311643104858212670342667229690568585229658813910569607411855770280546861422837629553847973043531578541545436967345783407835402474562087790816775240815912495599135241317")){System.out.println(A[0].replaceAll("","").replaceAll("\n",""));}}}
```
Out of fairness to robbers, here is it with all the "obvious" whitespace added.
```
interface r {
static void main(String[] A) {
String s = ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", q = ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", a = "", b = "";
for (String t : s.split(",")) {
a += t.length();
}
for (String t : q.split(",")) {
b += t.length();
}
if ((new BigInteger(a).multiply(new BigInteger(b)).toString()).equals("3649760552772806991406184564114682549877113954361462782925976763675666255653486225665808494957477900238166874367635068317805381406282572366371821972593595701388544127398102379288357379612333197280663769935384647844344358594407966485992727383589962048236726744715096711312156760311643104858212670342667229690568585229658813910569607411855770280546861422837629553847973043531578541545436967345783407835402474562087790816775240815912495599135241317")) {
System.out.println(A[0].replaceAll("", "").replaceAll("\n", ""));
}
}
}
```
Good luck, I would love to see this cracked. In fact I will even institute an unlimited bounty on this. If at any point you do crack this, you will be awarded **500 rep** infinite accolade on stack exchange (as well as likely a wonderful mathetatical paper).
---
[Answer]
# [RProgN](https://github.com/TehFlaminTaco/Reverse-Programmer-Notation), 15 Bytes [Cracked!](https://codegolf.stackexchange.com/a/103201/31347)
```
''`R""`R
```
You can toy with the code [here](https://tehflamintaco.github.io/Reverse-Programmer-Notation/RProgN.html?rpn=''%60R%22%22%60R&input=%22This%20is%20a%20test%20string%22). A relatively simple solution, hopefully the annoying nature of how RProgN handles strings will leave this uncracked.
## Original Program
```
' ' ` R
"
" ` R
```
## Explination
Firstly, the input is implicitly pushed to the stack. Stack: `<INPUT>`
Then, we use ' ' to push a space to the stack. Stack: `<INPUT> " "`
the ` actually tries to push a string represented by `(WORD) but because there's whitespace after it, it just pushes an empty string. Stack: `<INPUT> " " ""`
The R here is sugar for the Replace command. Stack: `<INPUTWITHOUTSPACES>`
Next, the "NEWLINE" pushes a string containing a newline, which is nice because RProgN doesn't use escapes, it just straight up lets you push a string like that. Stack `<INPUTWOSPACES> "\n"`
Then, we use the ` trick again, and Replace, which gives our output.
[Answer]
# Ruby, 86 bytes + 1 flag = 87 ([cracked by Dom Hastings](https://codegolf.stackexchange.com/a/103229/6828))
Requires command-line flag `-p`.
```
eval"(T$}{(!//;:678?32.&&)".gsub(/|(.)/){$1&&$&.ord.^($'.count('')).chr}
```
The code is actually valid in this form, it's just a no-op.
[Answer]
# [Beam](http://esolangs.org/wiki/Beam), 72 bytes, Safe!
Now for a 2d language. Can be played with on [TIO Nexus](https://tio.run/nexus/beam#@1@srq5ul6Ctra2pHVyckBfDpZCXUBysrQEUSbBJSNDnUrArSgcJxyk42GjEKChwKYCAhwIM2ICkgED//3/qmQUA "Beam – TIO Nexus").
```
s'''>`+++)+Ss`n\
n`sS+(+++`<``/
>rgn\
^ @<(\
H <
^ /
```
A fairly straight forward program without a lot in there to try and fool people.
```
s'''>`+++)+Ss`n\ # Sets the memory slot 0 to 0, 10 to 10 and 32 to 32. n will redirect down
n`sS+(+++`<``/ # since memory != store. \ is a red herring and not hit.
>rgn\ # read in from input and set store to memory value. For all characters
^ @<(\ # other than space, LF and end of input this will be different and n will
H < # redirect down then through to the print and back to read. Space, LF and
^ / # end of input get directed to the ( which tests for 0. This will redirect
# space and LF to path back to read, otherwise it will skip over and halt
```
[Answer]
# [Labyrinth](http://github.com/mbuettner/labyrinth), 127 bytes
```
);""{"".@"-;,""""":"##"*"(:"+":}-;{";;"*#{:;"#""+("-;"";;"})"";""""""""
```
Hopefully I did this right :) this is my first cops and robbers entry.
## Original Code
```
) ;""{"".@
"-;, "" ""
" :
" ##
" *
" (:
" +
" :}-;{
" ; ;
" *#{: ;
" # "
" +("-;"
" ; ;
" })"
" ;
""""""""
```
[Answer]
# C, 140 bytes, [cracked by Riley](https://codegolf.stackexchange.com/a/103187/57100)
Let's start with an easy one.
```
#include<stdio.h>intmain(){inta=getchar();while(a!=EOF){//\a=getchar();if(a!=10&&a!=32)//\\putchar(a^10^32);putchar(a);a=getchar();}}
```
(I hope I'm doing this right.)
[Answer]
# Befunge 98, 65 bytes, [cracked by Pietu1998](https://codegolf.stackexchange.com/a/103235/267)
```
~v>#@>::':'0--\'[';--!8v1+!*1+j!j,v>#@
```
# Original program
```
~v >#@
>::':'0--\'[';--!8v1+!
*1+j !j, v >
#@
```
[Answer]
## JavaScript ES6, 380 bytes, safe
This is the kind of entry that I was initially planning to release. It's huge and has nearly no chance to win, but I *think* it should be cryptographically strong enough to withstand 7 days. Now, I may be proven wrong!
67 bytes of whitespace to add.
```
s=>{for(k=`|||`.split`|`.map(s=>s.replace(/\s/g,c=>(k-=(c<'')+1,n=n<<2|k&3),k=n=0)&&n),x=10106050295,y=-4955405499,i=32,d=2654435769,t=d*i;i--;y-=(x<<4^x>>>5)+x^t+k[t>>>11&3],t-=d,x-=(y<<4^y>>>5)+y^t+k[t&3]);returns[atob(([x,y].map(n=>String.fromCharCode(n&255,n>>8&255,n>>16&255,n>>24)).join``))](/[\n]/).join``}
```
### Solution
This is an implementation of the [Extended Tiny Encryption Algorithm](https://en.wikipedia.org/wiki/XTEA). The 64-bit whitespace-encoded key expands to the following 128-bit key:
```
K = [0xd224de37, 0x89e34e79, 0xe34e7748, 0x939e2789]
```
[![enter image description here](https://i.stack.imgur.com/KHNmB.png)](https://i.stack.imgur.com/KHNmB.png)
*Source: [Wikipedia](https://en.wikipedia.org/wiki/XTEA)*
Once decrypted and converted to ASCII, the 64-bit block `[x, y]` reads as `c3BsaXQ=`, which is the Base64 encoded representation of `split`.
```
let f =
s=>{for(k=`
|
|
|
`.split`|`.map(s=>s.replace(/\s/g,c=>(k-=(c<' ')+1,n=n<<2|k&3),k=n=0)&&n),x=10106050295,y=-4955405499,i=32,d=2654435769,t=d*i;i--;y-=(x<<4^x>>>5)+x^t+k[t>>>11&3],t-=d,x-=(y<<4^y>>>5)+y^t+k[t&3]);return s[atob(([x,y].map(n=>String.fromCharCode(n&255,n>>8&255,n>>16&255,n>>24)).join``))](/[ \n]/).join``}
console.log(f(`H e l l o
W o r l d`))
```
[Answer]
# [Whitespace](https://web.archive.org/web/20150618184706/http://compsoc.dur.ac.uk/whitespace/tutorial.php), ~~81~~ 74 bytes, [Cracked!](https://codegolf.stackexchange.com/questions/103183/significant-whitespace-robbers/258852#258852)
```
```
Human readable version:
```
ttttttttttttttttttttt (21 tab characters)
```
I know this is an old challenge but hopefully someone is willing to have a go at cracking this. I attempted to optimise for bytecount but it may be possible to make something shorter with the same number of tab characters.
## Original Solution
```
```
[Try it online!](https://tio.run/nexus/whitespace#@6@goMCpAAJcXEAMhJxcnCAGiAUECmA@F4QHVgvkoYpyQjRy/f9PPbMA "Whitespace – TIO Nexus")
## Explanation
```
ssstsssssn ; push 32
nssn ; label ''
sns ; dup 32 to use as address
tnts ; getchar and store at address 32
sns ; dup 32 to use for later subtraction
sns ; dup 32 to use as address
ttt ; retrieve character value
tsst ; subtract 32 - char
ntsn ; jez '' if result is 0 char was a space, loop without output
sns ; dup 32 to use as address
ttt ; retrieve character value
ssststsn ; push 10
tsst ; subtract char - 10
ntsn ; jez '' if result is 0 char was a linefeed, loop without output
sns ; dup 32 to use as address
ttt ; retrieve character value
tnss ; putchar since it was not a space or linefeed
nsnn ; jump '' loop
```
I didn't keep notes for this solution but I think I'd tried to keep the stack low by retrieving the value repeatedly which also inflated the tab count. The hope was to force a slightly unusual approach to meet the target tab count.
@thaliaarchi's 65 byte solution saves characters by leaving non-space/newline characters on the stack when it loops, this was an alternative approach I considered but didn't end up going with (though I also had a higher bytecount there :D). The 68 byte cracked solution with reordered comparisons and a -0 constant to match the required tab count very neatly hits the target with a tidy byte saving, only leaving garbage on the stack when a newline is encountered.
[Answer]
# [V](https://github.com/DJMcMayhem/V), 37 bytes [Cracked by nmjcman101](https://codegolf.stackexchange.com/a/103240/31716)
```
OVrS200@"kIi|D@"Aüî|D@"
```
Since this has unprintables, here is the readable version:
```
O<esc>Vr<C-a>S200<esc>@"kIi<C-v><C-v><esc>|D@"<esc>Aüî<esc>|D@"
```
Or if you prefer, a hexdump:
```
00000000: 4f1b 5672 0153 3230 301b 4022 6b49 6916 O.Vr.S200.@"kIi.
00000010: 161b 7c44 4022 1b41 fcee 1b7c 4440 22 ..|D@".A...|D@"
```
[Answer]
# [Minkolang v0.15](https://github.com/elendiastarman/Minkolang), 88 bytes, [Cracked!](https://codegolf.stackexchange.com/a/103606/41805)
```
$oI[dd""=$r'10'=1J,?1R]r$O3.14$$$Cdollars>$$$Ceverywhere>x
```
[Try it online!](http://play.starmaninnovations.com/minkolang/?code=%24oI%5Bdd%22%22%3D%24r%2710%27%3D1J%2C%3F1R%5Dr%24O3%2E14%24%24%24Cdollars%3E%24%24%24Ceverywhere%3Ex&input=%24oI%5Bdd%22%20%22%3D%24r%2710%27%3D1J%2C%3F%201R%5Dr%24O3%2E14%0A%24%24%24%0A%20%20%20%20%20%20%20%20%20%20%20%20%20Cdollars%3E%0A%24%24%24%0A%20%20%20%20%20%20%20%20%20%20%20Ceverywhere%3Ex)
[Answer]
# [Vitsy](http://esolangs.org/wiki/Vitsy), 73 bytes, safe
This is downright evil.
```
5mW3m7m7m2mD&EPamX}<m15mEnl9mZD\[4m]^P-cm(D_2-3*bmD1-dmrnu-'
```
Good luck! 13 items of whitespace to add.
Original code:
```
5m
W3m7m
7m
2m
D&EPamX}
<m1
5mEn
l9mZ
D
\[4m]
^P-cm(D
_2-3*
bmD1-dmrnu-
'
```
[Try it online!](https://tio.run/#xYVZS)
This roughly simplifies down to:
```
<m1
W2\[2m]Z
l\[D&EP^P-_2-3*D1-rnu-(DX}]
```
[Answer]
## C#, 159 bytes, [Cracked by milk](https://codegolf.stackexchange.com/a/103256/38550)
```
usingSystem.Linq;s=>string.Join("",string.Join("",s.Split(@"".Replace(newstring((char)0x0D,1),"").ToCharArray())).Select(c=>c+""!=""?c+"":"").ToArray());
```
153 collapsed so only 6 bytes of whitespace to find, shouldn't be too hard...
[Answer]
# reticular, 43 bytes, [cracked](https://codegolf.stackexchange.com/a/103525/31957)
```
ISBqv<>>$$4jE:d/v$v?c+91d/v?E;!?l$/o$
```
The version on TIO is outdated, but you can get yourself a copy from the [github](https://github.com/ConorOBrien-Foxx/reticular).
[Answer]
# [S.I.L.O.S](http://github.com/rjhunjhunwala/S.I.L.O.S), 159 bytes Safe!
```
loadLinedef:lblgetagetzzzz/za=256:aX=getax=Xy=Xz=xx-10x|ifxbGOTOx:by-32y|ifycGOTOx:cprintCharX:xa+1z+1x=getaifxa:b
```
Should be fairly trivial. It is my first cops and robbers entry.
No one attacked it, probably due to the esoteric nature of my own language. Seems like a sleazy way to slide by, but it doesn't really matter as shorter ones are safe.
```
loadLine
def : lbl geta get z zz
z/z
a=256
:a
X=get a
x=X
y=X
z=x
x-10
x |
if x b
GOTO x
:b
y-32
y|
if y c
GOTO x
:c
printChar X
:x
a+1
z+ 1
x=get a
if x a
:b
```
Feel free to [try it online](https://tio.run/#FyZDI)
[Answer]
# Wolfram, 132
Probably has more that one solution (hint: Mersenne)
```
StringReplace[#,""->"",Limit[x/(x-1),x->Boole[PrimeQ[
212821282128228281282128228821282128212821282-1]]]]&
```
**Solution**
```
StringReplace[#," "->"",Limit[x/(x-1),x->Boole[PrimeQ[
2 128 2 128 2 128 2 2 8 2 8 128 2 128 2 2 8 8 2 128 2 128 2 128 2 128 2-1]]]]&
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal/tree/version-2), 11 bytes, 7 whitespace, [cracked by lyxal](https://codegolf.stackexchange.com/a/270002/100664)
```
#ȧ‛(#FṘ₴#Ṙ‛
```
[Try it Online!](https://vyxal.pythonanywhere.com/?v=2&c=1#WyIiLCIiLCIjyKfigJsoI0bhuZjigrQj4bmY4oCbIiwiIiwiaGVsbG8gICAgIHdvcmwgZCJd) Should be pretty easy.
Lyxal got my intended solution exactly.
[Answer]
# [Vyxal 3](https://github.com/Vyxal/Vyxal/tree/version-3), 11 bytes, 1 whitespace needed
```
#?“""₉r""₉r
```
[Try it Online!](https://vyxal.github.io/latest.html#WyIiLCIiLCIjP+KAnFwiXCLigolyXCJcIuKCiXIiLCIiLCJhIGIgY1xuIGQiLCIzLjQuMiJd)
Should be really really easy.
[Answer]
# tcc, 850 bytes
To avoid pasting a very long line I passed this through tr -d '\n ' | fold -b -w 60.
```
#!/usr/bin/tcc-run#include<stdio.h>typedefunsignedcharu;um[]
={104,105,16,152,94,131,43,42,112,214,53,207,116,170,185,210
};intmain(){uS[256];uk[256];ui,j,t;intc,n=0;FILE*f;f=fopen(_
_FILE__,"r");/*cannotfail*/while(-1!=(c=fgetc(f)))if(c==''||
c==10)k[++n]=c;fclose(f);i=0;do{S[i]=i;}while(++i!=0);j=0;i=
0;do{j=j+S[i]+k[i%n];t=S[i];S[i]=S[j];S[j]=t;}while(++i!=0);
i=0;do{if(S[i]!=m[i])j=1;}while(++i<sizeof(m));if(j==1){i=0;
do{printf("%d,",(int)S[i]);}while(++i<sizeof(m));printf("\n"
);}else{while(-1!=(c=fgetc(stdin)))if(c!=''&&c!=10)fputc(c,s
tdout);}returnj;}
```
] |
[Question]
[
This is what we'll call a bowl of alphabet soup - a roughly circular ascii-art shape with the 26 uppercase English letters (A-Z) arranged clockwise to form the perimeter:
```
XYZABC
VW DE
U F
T G
S H
RQ JI
PONMLK
```
Write a program that takes in a single letter character, A-Z, and outputs that same bowl of alphabet soup "rotated", so to speak, so the input letter appears where the `A` does in the example above and the rest of the alphabet cycles fully around clockwise.
So the output for input `A` would be that same original bowl of alphabet soup.
And the output for input `B` would be this one:
```
YZABCD
WX EF
V G
U H
T I
SR KJ
QPONML
```
Likewise the output for `H` would be:
```
EFGHIJ
CD KL
B M
A N
Z O
YX QP
WVUTSR
```
Or for `Z`:
```
WXYZAB
UV CD
T E
S F
R G
QP IH
ONMLKJ
```
This needs to work for all 26 letters, A through Z.
### Details:
* You can assume the only input will be a single letter, A through Z.
* If convenient you may use lowercase a-z for input and/or output, you can even mix and match lower and uppercase.
* The alphabet order must cycle clockwise, not counter-clockwise.
* You must use spaces, not something else, to indent and fill the soup bowl.
* There may be leading or trailing newlines or spaces in the output as long as the soup bowl is arranged properly.
* Note that the bowl shape is 12 characters wide by 7 tall to make it appear roughly circular as text. Your bowls need to be the same shape.
**This is code golf so the shortest code wins!**
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 21 bytes
Defines a program \$f : \color{purple}{\texttt{AlphabeticChar}} \rightarrow \color{purple}{\texttt{String}}\$
### Code:
```
2AA¹k._•1못*Ć,ãiDΣ•Λ
```
[Try it online!](https://tio.run/##yy9OTMpM/f/fyNHx0M5svfhHDYsMD68@tOrQbq0jbTqHF2e6nFsMFDs3@///DAA "05AB1E – Try It Online")
### Breakdown:
```
2AA¹k._•1못*Ć,ãiDΣ•Λ
2 # <length>
AA¹k._ # <filler>
•1못*Ć,ãiDΣ• # <pattern>
Λ # Invoke the canvas function.
```
### Explanation:
The **canvas** (`Λ`) in this particular context works as a function with the following signature:
$$
\mathsf{\Lambda} : \left(\texttt{length}: \color{purple}{\texttt{Nat}},\ \texttt{filler}: \color{purple}{\texttt{String}},\ \texttt{pattern}: \color{purple}{\texttt{Nat}}\right) \rightarrow \color{purple}{\texttt{String}}
$$
The \$\texttt{pattern}\$ parameter is in this situation a number defining the directions. In the code, this number is represented as [`•1못*Ć,ãiDΣ•`](https://tio.run/##yy9OTMpM/f//UcMiw8OrD606tFvrSJvO4cWZLucWA8X@/wcA), which is a compressed version of the big number \$2232344565666667670012122\$. Directions are denoted in the following manner:
$$
\begin{array}{l}
7 & & 0 & & 1 \\
& \nwarrow & \uparrow & \nearrow & \\
6 & \leftarrow & \bullet & \rightarrow & 2 \\
& \swarrow & \downarrow & \searrow & \\
5 & & 4 & & 3
\end{array}
$$
This means that the big number represents the following pattern of directions:
$$
[\rightarrow, \rightarrow, \searrow, \rightarrow, \searrow, \downarrow, \downarrow, \swarrow, \leftarrow, \swarrow, \leftarrow, \leftarrow, \leftarrow, \leftarrow, \leftarrow, \nwarrow, \leftarrow, \nwarrow, \uparrow, \uparrow, \nearrow, \rightarrow, \nearrow, \rightarrow, \rightarrow]
$$
With this signature context, the canvas iterates through the \$\texttt{pattern}\$ list and writes \$\texttt{length}\$ characters from the \$\texttt{filler}\$ in the current direction.
The \$\texttt{length}\$ is specified in the code as \$2\$ (at the beginning of the code). For the \$\texttt{filler}\$, we need a rotated version of the alphabet such that it starts with the given input. That is done with the following code ([try it here](https://tio.run/##yy9OTMpM/f/f0fHQzmy9@P//MwA)):
```
**AA¹k.\_**
A¹k # Find the ***<index>*** of the given input character in the alphabet
A ._ # Rotate the alphabet to the left ***<index>*** times.
```
In pseudocode, this would be executed by the canvas function:
\$
\begin{array}{l}
1. & \text{Write } \color{blue}{\texttt{ab}} \text{ in the direction} \rightarrow \\
2. & \text{Write } \color{blue}{\texttt{bc}} \text{ in the direction} \rightarrow \\
3. & \text{Write } \color{blue}{\texttt{cd}} \text{ in the direction} \searrow \\
4. & \text{Write } \color{blue}{\texttt{de}} \text{ in the direction} \rightarrow \\
5. & \text{Write } \color{blue}{\texttt{ef}} \text{ in the direction} \searrow \\
6. & \text{Write } \color{blue}{\texttt{fg}} \text{ in the direction} \downarrow \\
\dots
\end{array}
\$
Lastly, you can see that the filler argument is 'rotated' \$\texttt{length} - 1\$ times to the right, meaning that the canvas would iterate through the following (cycled and therefore infinite) list:
$$
[\color{blue}{\texttt{ab}}, \color{blue}{\texttt{bc}}, \color{blue}{\texttt{cd}}, \color{blue}{\texttt{de}}, \color{blue}{\texttt{ef}}, \color{blue}{\texttt{fg}}, \color{blue}{\texttt{gh}}, \color{blue}{\texttt{hi}}, \color{blue}{\texttt{ij}}, \color{blue}{\texttt{jk}}, ...
$$
Which results in the desired alphabet soup ascii-art shape.
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 100 bytes
```
{"2XYZABC
VW5DE
U9F
T9G
S9H
RQ5JI
2PONMLK".trans(/\S/=>{(try ' 'x$/+1)||chr ($/.ord+.ord)%26+65})}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYKvwv1rJKCIyytHJmUshLNzUxZUr1NKNK8TSnSvY0oNLISjQ1MuTyyjA38/Xx1tJr6QoMa9YQz8mWN/WrlqjpKhSQV1BvUJFX9tQs6YmOaNIQUNFXy@/KEUbRGiqGplpm5nWatb@t@YqTqxUSNNQd1TXhLOdkNhRQPZ/AA "Perl 6 – Try It Online")
Replaces all letters in the string with their shifted counterparts, while replacing digits with the number of spaces they represent plus one.
### Explanation
```
{ }# Anonymous code block
"...".trans(/\S/=>{ }) # Translate non-whitespace
(try ' 'x$/+1) # If digits, the amount of spaces plus one
||chr ($/.ord+.ord)%26+64 # Else the shifted letter
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 107 bytes
```
->n{a=(0..6).map{' '*11}
(?A..?Z).map{|i|j,k=(1i**((i.ord-n.ord-6)/6.5)).rect;a[3.5*k+=1][5.2*j+6]=i}
a*$/}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y6vOtFWw0BPz0xTLzexoFpdQV3L0LCWS8PeUU/PPgoiWJNZk6WTbathmKmlpaGRqZdflKKbBybNNPXN9Ew1NfWKUpNLrBOjjfVMtbK1bQ1jo031jLSytM1ibTNruRK1VPRr/xeUlhQrpEXbO8b@BwA "Ruby – Try It Online")
Improved syntax `"i".to_c` -> `1i` (Suggested by Jordan)
Changed coordinate system so 0 degrees is at right instead of top. This enables `0.5` -> `6`
Adjusted multipliers of `j` and `k` for shortness
Rather than print output `puts a`, concatenate array elements and return a string `a*$/`
# [Ruby](https://www.ruby-lang.org/), 119 bytes
```
->n{a=(0..6).map{' '*11}
(?A..?Z).map{|i|j,k=("i".to_c**((i.ord-n.ord+0.5)/6.5)).rect;a[3.5-j*3.3][6+k*5.17]=i}
puts a}
```
Uses a complex number raised to a power to map to an ellipse. A complete turn is 26, so each quadrant is 6.5.
This approach relies on the required output resembling an ellipse sufficiently that a valid mapping can be achieved.
[Try it online!](https://tio.run/##JcjBDoIgGADgu0/hvAgYfzIHHRo5XyPGGplu6FJHeGjKs1Oty3f43Hp/x15Gepk2I1EJIDA8zbLlaU4YCwmqG4D6@s/d7sNhlCizGfj51hKCkIXZPej0syiB46P4gsF1rT8bVQGnA6mg0koUI@HATlrakCyrf6UmxF7VjY4f "Ruby – Try It Online")
[Answer]
# [MATL](https://github.com/lmendo/MATL), 49 bytes
```
7I8*32tvB[1b]&Zvc2Y2j7+_YSy&f7-w4-_Z;YPE\,&S])yg(
```
What a mess. But it was fun writing. There's even an arctangent involved.
[**Try it online!**](https://tio.run/##y00syfn/39zTQsvYqKTMKdowKVYtqizZKNIoy1w7PjK4Ui3NXLfcRDc@yjoywDVGRy04VrMyXeP//wwA)
### Explanation
The code
```
7I8*32tvB
```
creates an array of numbers and converts them to binary. This gives the zero-one matrix
```
0 0 0 1 1 1
0 1 1 0 0 0
1 0 0 0 0 0
1 0 0 0 0 0
```
which is the top left quadrant of a matrix specfying the positions of the letters.
```
[1b]&Zv
```
reflects that quadrant vertically without repeating the last row, and horizontally repeating the last column to produce the full matrix:
```
0 0 0 1 1 1 1 1 1 0 0 0
0 1 1 0 0 0 0 0 0 1 1 0
1 0 0 0 0 0 0 0 0 0 0 1
1 0 0 0 0 0 0 0 0 0 0 1
1 0 0 0 0 0 0 0 0 0 0 1
0 1 1 0 0 0 0 0 0 1 1 0
0 0 0 1 1 1 1 1 1 0 0 0
```
We now have a mask with the positions. The code
```
c
```
converts this to char, because the final result will be a char matrix. Character 0 is displayed as space, and the nonzero entries will be written with the appropriate letters.
```
2Y2
```
pushes the string `'abc···xyz'`, which contains the 26 letters. This string needs to be circularly shifted as per the input. To do that,
```
j7+_YS
```
reads the input letter, adds 7 to its ASCII code, and negates the result. For input `'a'` this gives −104, which is a multiple of 26, so circularly shifting by this amount will do nothing. If the input is `b` this gives −105, which shifts the string 1 step to the left to produce `'bcd···yza'`; etc.
The next step is to define the order in which the shifted string will be written into the nonzero entries of the matrix. To this end,
```
y&f
```
creates a copy of the matrix and pushes two vectors containing the 1-based row and column positions of the nonzeros. Then
```
7-w4-_
```
subtracts 7 from the latter, brings the former to top, substracts 4 from it, and negates it. The 7 and 4 specify an origin of coordinates, so that the angles of the position vectors of the nonzero entries with respect to that origin define the desired order.
```
Z;YPE\
```
computes the two-argument arctangent modulo 2\*pi to produce those angles. Now the smallest angle, which is 0, corresponds to the entry where the first letter should go, and the rest advance counter-clockwise.
```
,&S])
```
rearranges the letters in the string according to those angles, so that when the letters are written into the nonzero entries of the matrix in column-major order (down, then across) the result will be correct. This is done by
```
yg(
```
For example, if the input is `'a'` the string was not circularly shifted:
```
abcdefghijklmnopqrstuvwxyz
```
The rearranging as per the angles transforms this into
```
utsvrwqxpyoznamblckdjeifgh
```
so that `'u'` will correctly go to the first (in column-major order) nonzero entry, which is (3,1) in matrix notation; `'t'` will go to (4,1), `'s'` to (5,1); `'v'` to (2,2) etc:
```
······
v· ··
u ·
t ·
s ·
·· ··
······
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 33 bytes
```
GH→→↘→↘↓↓77←←←←↖←↖↑↑↗→↗→→²✂⁺αα⌕αS
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z8gP6cyPT/PIz8nJ79cwyooMz2jREcBTrvkl@fhEwOxEZQ5FPukppXgokILcPBDCxAEupWYIlDaSEchOCczOVUjIKe0WCNRRyFRU0fBLTMvBcT2zCsoLQkuKcrMS9fQBALr//89/uuW5QAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
GH
```
Trace a path.
```
→→↘→↘↓↓77←←←←↖←↖↑↑↗→↗→→
```
Outline the bowl. Each `7` expands to `↙←`.
```
²
```
Move one character at a time (this API overlaps each line's ends with the next).
```
✂⁺αα⌕αS
```
Draw using the doubled alphabet, but starting at the position of the input character.
[Answer]
# [Python 2](https://docs.python.org/2/), 129 bytes
```
lambda x:''.join((i,chr((ord(x)+ord(i))%26+65),' '*5)[ord(i)/46]for i in''' XYZABC
VW] DE
U]]F
T]]G
S]]H
RQ] JI
PONMLK''')
```
[Try it online!](https://tio.run/##JYvJCsIwFADv@Yp3kZfYolBsD4KHuu/7ru9QLaURTUqoUL8@VjwNDDPZJ0@18mzSutpn9LrFERRNxNpDS8W5dO@p4VybmBfC@UEKUfECJ/CFi4BVX1z@tt4IKNEGJEiFiABwPJ3DdofB/kDQ7bEdUZ9tiQZsQzRksF4RjEesDJeL@Ww6KSdhMyNVDgmXKnvnXAiLIX4B "Python 2 – Try It Online")
[Answer]
# [R](https://www.r-project.org/), 139 122 bytes
-17 bytes thanks to Giuseppe
```
u=utf8ToInt;`*`=rep;o=c(' '*12,'
')*7;o[u(" &3@LKWVUTSRDC5(")]=LETTERS[(13:38+u(scan(,'')))%%26+1];cat(o,sep='')
```
Explanation:
```
o=rep(c(rep(' ',12),'
'),7)
```
Builds an empty box of spaces
```
u(" &3@LKWVUTSRDC5(")
```
is a set of indices for letter positions corresponding to:
```
c(7:9,23,24,38,51,64,76,75,87:82,68,67,53,40,27,15,16,4:6)
```
[TIO](https://tio.run/##K/r/v9S2tCTNIiTfM6/EOkErwbYotcA63zZZQ11BXcvQSEedS11Ty9w6P7pUQ4mdg1NcQs3Ywcc7PCw0JDjIxdlUQ5pfgIWVTUkz1tbHNSTENSg4WsPQ2MrYQrtUozg5MU9DR11dU1NTVdXITNsw1jo5sUQjX6c4tcAWKPzf8T8A)
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~121~~ 119 bytes
*Saved 2 bytes thanks to @tsh*
```
c=>`2XYZABC
0VW5DE
U9F
T9G
S9H
0RQ5JI
2PONMLK`.replace(/./g,x=>''.padEnd(+x+1)||(B=Buffer)([65+([a,b]=B(c+x),a+b)%26]))
```
[Try it online!](https://tio.run/##bchLC4IwAADg@/5HuDFTExQ8LHBl7/c7RXDNLQpR0QoP/ffVOfqO3529WM2rW/lo50UqlCSKk25in86hT3vAOhydfgD23gDsvCHYeiNgbdbOZAzs1XIxn00ToxJlxriApmFe9YZ0Nc0oWRrkKcQN7qD3G1JCn1KKCsHIdTCMmH6JCYUcN0hn@IJathsjpHiR10UmjKy4Qgk1X0MI/Bz9c6M/F35PfQA "JavaScript (Node.js) – Try It Online")
## How?
This code abuses `Buffer` to extract the ASCII codes of the template letter \$x\$ and input letter \$c\$ and convert them back into the target letter.
### Example with \$c=\$`"H"` and \$x=\$`"B"`
```
// extracting the ASCII codes
Buffer(c + x) → Buffer("HB") → <Buffer 48 42>
// assigning them to variables
[a, b] = Buffer(c + x) → a = 0x48 (72) and b = 0x42 (66)
// computing the ASCII code of the target letter
65 + ((a + b) % 26) → 65 + (138 % 26) → 65 + 8 → 73
// turning it back into a character
Buffer([73]) → <Buffer 49> → implicitly coerced to "I" by replace()
```
[Answer]
# APL+WIN, 72 bytes
Prompts for character
```
m←7 12⍴' '⋄n←(7⍴2)⊤v,⌽v←(⍳3)/28 34 65⋄((,n)/,m)←(22+s⍳⎕)⌽s←⎕av[65+⍳26]⋄m
```
[Try it online!Coutesy of Dyalog Classic](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob6qvz6O2CcZcjzra0/7nApnmCoZGj3q3qCuoP@puyQMKaJgDuUaaj7qWlOk86tlbBhJ61LvZWFPfyELB2ETBzBSoUENDJ09TXydXEyRrZKRdDFQBNFwTqKEYKARkJpZFm5lqA4WNzGKBGnL/A238n8alHqUOAA "APL (Dyalog Classic) – Try It Online")
[Answer]
# [R](https://www.r-project.org/), 218 197 bytes
-21 bytes thanks to Giuseppe
```
function(t,l=letters,`*`=rep,s=" ",n="
",`~`=`[`,r=c(l~l>=t,l))cat(s*3,r~24:26,r~1:3,n,s,r~22:23,q<-s*6,r~4:5,n,r~21,u<-s*10,r~6,n,r~20,u,r~7,n,r~19,u,r~8,n,s,r~17:18,q,r~10:9,n,s*3,r~16:11,sep='')
```
[Try it online!](https://tio.run/##dY89DoMwDEZ3ToFYAshIGCg/EelF2iEIUVEpCpCEpQNXpwmt1C5M9vee7Dhq78Q8dnpaZ79N/P2xyt48JxkaEEwMxgxKA485U8MMmgV@AJIFXgB844zfOCjWh2ITV2YHoqjvTKjjHNSWFTQrbUWagwTtSEazHJY20bETBb1YYTHC6himNpQflMJqS3UEbI5Qf7dgRbGGxXUpbRw8nsOSIoIeZkZI9PtTSDoSee4qcpe2@xP9mRjPhDgT5ky87C1v "R – Try It Online")
Ungolfed:
```
alphasoup <- function(startlet){
startnum <- which(l == startlet)
rotatedletters <- c(letters[startnum:26], letters[1:(startnum -1)])[1:26]
cat(' ',rotatedletters[24:26],rotatedletters[1:3], '\n ',
rotatedletters[22:23], s6 <- ' ', rotatedletters[4:5], '\n',
rotatedletters[21], s10 <- rep(' ', 10), rotatedletters[6], '\n',
rotatedletters[20], s10, rotatedletters[7], '\n',
rotatedletters[19], s10, rotatedletters[8], '\n ',
rotatedletters[17:18], s6, rotatedletters[10:9], '\n ',
rotatedletters[16:11],
sep = '')
}
```
Created rotated letter vector and uses `cat` to fill out rim of bowl with that vector.
[Answer]
# Java 11, 134 bytes
```
c->"2XYZABC_0VW5DE_U9F_T9G_S9H_0RQ5JI_2PONMLK".chars().forEach(i->System.out.print(i<59?" ".repeat(i-47):(char)(i>90?10:(c+i)%26+65)))
```
[Try it online.](https://tio.run/##XY9rS8MwFIa/71ccCtKE0VCLndRpx9TpvKxe6l0kxCxz2bq2JNlAZL@9prWf/HLgPefw8jwLtmHeYrqseMa0hgmT@U8HQOZGqBnjApI6AmwKOQWO@Jwp4Lhvd9uOHdowIzkkkMMRVNyLneDl9W14fEL9p@fwdEQfozP6EJ3TNBpT//4uvLygwe1NMrm@ckhdphEms0KNGJ8j6cXptzZiRYq1IaWyEEgehtHAAYcoUQpms7e3jw8aDoxkHPmDXd/GrsQ7Qa/bCzHGVb8mK9efmSVrARv8lZVDqbG9X@8fwPCfWU44csdu4wTwHyDLUXtp/oZu676tfgE)
**136 bytes version** with potential to be golfed?
```
c->"2XYZABC_0VW5DE_U9F_T9G_S9H_0RQ5JI_2PONMLK".chars().forEach(i->System.out.printf("%"+(i<59?i-47:"")+"c",i>90?10:i<59?32:(c+i)%26+65))
```
[Try it online.](https://tio.run/##XY/bToNAEIbv@xSTTRp2gxBEqYEqTdXWeige8GzMZt2C3UqXBrZNjOmz44JceTPJzD/5830LtmHWYvZV8YyVJUyZkD8dACFVUqSMJxDVK8AmFzPgmM9ZAZz09W3b0aNUTAkOEUg4gopbIXKfX16HxyfUeXzyTkf0wR/Te/@Mxv6EOne33sU5dW@uo@nVJbLrshITO82LEeNzLKww/i5VsrTztbJXhYZIMeoiE4tDzx8Ia/8gQIiYiKMdEfrOYNcJmmTPDTA3Bem6PbPnEVL1a7bV@iPTbC1iI7DUejhWuvnz7R0Y@XOTNsfGxGisAP4jZBK3SfM3NFr7bfUL)
**Explanation (of the first answer)**
```
c-> // Method with character parameter and no return-type
"2XYZABC_0VW5DE_U9F_T9G_S9H_0RQ5JI_2PONMLK"
// Template-String
.chars().forEach(i-> // Loop over the unicode values of its characters:
System.out.print( // Print:
i<59? // If the value is below 59 (so a digit character):
" ".repeat(i-47) // Repeat a space that digit + 1 amount of times
:(char)(i>90? // Else-if the value is above 90 (an underscore character):
10 // Print a newline
: // Else:
(c+i) // Add the current value and the input together
%26 // Take modulo-26 of it to get the index in the alphabet
+65))) // And add 65 to make it an uppercase letter
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 258 bytes
```
(t[x_]:=Table[" ",x];w=RotateRight[Alphabet[],4-LetterNumber@#];j=Join;a[x_,y_]:=j[{w[[x]]},t@10,{w[[y]]}];b[m_,n_]:=j[t@1,w[[m;;m+1]],t@6,w[[n;;n+1]],t@1];""<>#&/@{j[t@3,w[[1;;6]]],b[25,7],a[24,9],a[23,10],a[22,11],Reverse@b[12,20],j[t@3,w[[19;;14;;-1]]]})&
```
[Try it online!](https://tio.run/##RY3RSsNAEEV/JWyhKE5pN42VdhqJryIioW/DUHZlSVK6qcTRppR@@7qpgk9zD@dyxxupnTfSvJtQ5eFGqN/yKt8Yu3ekEgU94zEvD2LElU1VCz3tP2pjnRBDNnlxIq57/fLWdcWIcZc/H5oWTVyB0zC0o/ORqGe@gBR6BgOdIjFa8ltofztRQRQe0d9p5lhdDNwitn@sGZVaP47G0@I89OeD14gLjtpSeg8PDIbSDJbXOwc9u4YUtGYo3bfrPl1hSaeQRvO/sUTUGeIk/uHL7Ti8dU0rybRIKlJGcQg/ "Wolfram Language (Mathematica) – Try It Online")
[Answer]
## Haskell, 127 bytes
```
("cXYZABC aVWfDE UjF TjG SjH aRQfJI cPONMLK">>=).(?)
t?c|c>'Z'=' '<$['a'..c]|c<'!'="\n"|t<'B'=[c]|c>'Y'=t?'@'|1<2=pred t?succ c
```
[Try it online!](https://tio.run/##bci5bsJAFAXQnq@4WEgXilhKao8NZCHsCUsSDClGDybBGGPhofO3M4gaTnn@dbHbpKkzauXqnvws4lb7Gfrr27y8Yp68YZZ0ME3eoSefpteFfIxHw0HfC0PV8OtRo2IjKSVkTEUwqC2p6fvyW0rAKpW3yrzSBmxTLa8ZckFlIzZZPgZPKj9u1rBRcRKBuL3eZlBYHyoA8pOd2uMgQw0GbPH2OncupjuLSfVf4R4kzy8 "Haskell – Try It Online")
Each character in the encoded string is decoded by function `?` into a string:
```
t?c -- 't' is the starting char,
-- 'c' the char from the encoded string
|c>'Z'=' '<$['a'..c] -- if 'c' is a lowercase letter, return some spaces
-- 'a': one, 'b': two, etc
|c<'!'="\n" -- if 'c' is a space, return a newline
|t<'B'=[c] -- if 't' is the letter A, return 'c'
|c>'Y'=t?'@' -- wrap around Z
|1<2=pred t?succ c -- else the result is the same as starting one letter
-- earlier (pred t) but looking at the successor of 'c'
```
[Answer]
# [Kotlin](https://kotlinlang.org), ~~148~~ ~~146~~ 145 bytes
Removed extra parentheses for -2
Replaced raw string for -1
```
{l:Char->"2XYZABC 0VW5DE U9F T9G S9H 0RQ5JI 2PONMLK".map{c->if(c>'@')((c-'A'+(l-'A'))%26+65).toChar()
else if(c>' ')" ".repeat(c-'/')
else '\n'}}
```
[Try it online!](https://tio.run/##lVdZc9s2EH7Xr9hq2kqaWPIR2409jafybedwfMWJmz5AJCSiJgkGAC0rHv/2dBcASUhOHqrJxAK557e730J30qQi/768DHuKM8NjGEsFJhEaIhlzmMh0DFHC0pTnE77dQsHEmEJvLy/Te3o90IZFd/wBpVBkEMls@evy6qvVV@svSfwdu@PAYFdOU5BjGKZFwkbcwKUsixYJXJEz/DdNmIEp76QpROgPdUZeh1U6GnWgj2@ULCdJOoNIqKhMmQKmIyH6TKFMwgoOU2ESTIPD2iaURcFVxDSHg3ySCp1Ayo3hSkN32L/tAVOKIo8hSmV0NxUoaCThkFkLqCwyjvLbNlz8fPp8O9zds4ePN2A/@wd0vIb6c2hTa85HdL5szsdW/eLcnU5PvOkPZ@/fvX1jHd0oYQi5QsmJYhQL4mMQTUQrx@daYDbc50I1UizCb0uASS0By2OQpSlKo52mZhn/CaJtJQ3Vvr2EZ8pdF5zduQMCIHK0UvlhCCZTVC2uuH09hFi6mOjEH1hWYFhsJO@5jYKeKq4N@aXvte9oFqWoOC5TrCTDkuZBCQYWg0sXgUvEtqYLZghTWaYxjHiQnFRiInKW/jhLZ3DoA3pmcTe0iN0oc17X25Z73x5uPrmCHdj6flyo7/VCfYP6uwJfXrjTm1Nv@twW3Dp6K@64a775@I7ryOqADg6Pjk@cib19b/EtHXcbh@9sus35PZ1vm/OZVf/s8zn/4E3ffLy@urywjs6U9X9bu72xjW8P1z51B0uQ58FCn1ucLhZwQncelWNv2rb9acMHOeexplacSnVnwyBKwGH2o4tdjjhZGoDbAantc8NEqutg4bMskUhwUrQuM49qjp3m6j0VaG/EF@fouV0bJnKgzO95LnhuYIaGMzaDEmuVyqnnFtb/FrQTNv4yHlwZl6wKxcLRBmTiwQ5GxkyUOAv2XPNU7fcqHBepYhTMSu0np5mVJcglPsQBwgz6wQgFSFg9ilgXLOLaqWiJxJZg/sBTMoN4izymHCmeMUFEsFmSoKEKA8PpJxBGhByLyQYtDoU1oO85n@JfnG586DxWBOE7m2nMHAWZnndBm6AmZKQ@hCSd1X7fS@MnnpSsvON71Fpda0gQ@Ung9hrN4A@kTEpDYrS4iITxDPajFQKGP5gBwaWsbdeGpDty/WNpxjoczK2uZlV6ytSJVIY4z76Zilz/YhUOHgpElrZsmUdGyJxoKmXZKGZuZeH2zBB/PWihBOWPyOmu681t2MP8evC61SIsaM6MssCPGzisFSQvAj6Tqqp3paF4keI5dnIMYqRMV22sGFDJapFKxUtaOwPbkk5phYDZovTJue2@SgUDQiQVq0qPgiyOCZwNmAme4mhvYj9U4gbXT@pMBxX0WWmX44TX1jOqYIz6Rvrl8rUUCp/I8VhzLOBe4tpnrGRWJ86mlSma0v4qdFOJ47AOtpUpvJfUIihQqdjgMfMamRHHYe0N7Pv2mrsFwMrHm439A7jeOoSrrSO43DqGlYvzjdMTWHPLvO0U6IORw2OTI/R3WvU7dHjiMm7e0ywE1xdPUaEKi/@lwRaY9RF3U/GNK2xYlK8AwT@hykj6q1FUKkWz3vhzlwYVSmue8ojuhYapCQ@EBzCM7S7NQnEjUSjxpjIZl2lpy28nv4pm0QfeDsp0zvRlIsamujnQuxFeMef92LfVRc7RqZ/vxlCoIXMsJk3EoB5bZ992Ow1dKB3EcsEzvMogGTFCK@Gaa39bmTOPnPEcUJ8y3meJY2jgQx3biGtEPDleNvHiUiiOg8cp0ljENeXMJU503XSUGEO3cbcDnb86vVazbbvNy35n2HnhmYS@93q/BYL0Wdt8sbnRGxhJNNPtzbXmGRXV7Rrxwy61nDDXmhPfj0RGC@1on1uNUKHbWelYIoffobPlvq70bG0nPOeKee4PdTKWzxYWTFBRP/ENXLTmnmMGc5i1oT1AG/hrKARvufNTQKYcEnbPK44kmvO9ODepNY/MhxN47nzJO/DUcr@aMJt6SWC3IwfUv0jq32NuS2Qo28Xp1NswxM05@9OthZ0ePFLIdLV0GwbNBEAGxOl2O8A99eBrp/P36vqrf@j/zX9gdX0DdykutO@P6TZ1R3/n//Af0t5j1N8R4260Qw2KXem70TfiYuf5MpE41iYsiCuEfU9oPT19t8Ee4iRxhrepQmotRsF1zq9QcFvOpRYLjS0yC/hFU/Y0jn5AqJcwtMGgc9shGKk6BYJq0rzbJme/@pXcdp1jVYOJwNXtLfWq1rLqjUxv3uaX3Fp68rTQenLNjT/N/wM "Kotlin – Try It Online")
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), ~~126~~ 118 bytes
```
n=>$@" XYZABC
VW{"",6}DE
U {"",9}F
T {"",9}G
S {"",9}H
RQ{"",6}JI
PONMLK".Select(b=>b<65?b:(char)((b+n)%26+65))
```
Saved 8 bytes thanks to @someone. Yes, that's actually his username.
[Try it online!](https://tio.run/##LY3JCsIwAETv@YpQlCa0ehAsaJu4L3XXqlVvTUg1oBHSepJ@e1xP85iF4VmFZ9IMH4oH/JJoNxyox03ohF3F16A0JUYRWmpbEMLD8dTp9gDcx0/Lcr2iPwA7@MFGMQTbP41A9KcxgJv1rzkJwXu/Wi7ms6lVjcRV8BwxQlng1VusiT5fGCHmKFyueY5Xx9j4IL3rbwIlsTu2LwNin97iODjWMhczqQTKci3Vudq7K57kKEUSY@wD8wI "C# (Visual C# Interactive Compiler) – Try It Online")
[Answer]
# TSQL query, 238 bytes
```
DECLARE @y char='G'
,@ char(91)=3;WITH C as(SELECT'5585877636333330301125255'z,8a,ascii(@y)x
UNION ALL
SELECT stuff(z,1,1,''),a+left(z,1)/3*13+left(z,1)%3-14,(x+14)%26+65FROM
C WHERE''<z)SELECT
@=stuff(stuff(@,a,1,char(x)),1+a/13*13,1,char(13))FROM
C PRINT @
```
The test link for this answer broke the line breaks and excluded the spaces. I have replaced the spaces with period and replaced char(13) with char(13)+char(10) in order to show a readable result.
**[Try it online](https://data.stackexchange.com/stackoverflow/query/1015541/make-a-bowl-of-alphabet-soup)**
Ungolfed:
```
DECLARE @y char='G'
-- @ is the string being printed last.
-- @ is populated with 3 to save a byte
-- the number 3 gets replaced later
-- (this could have been any 1 digit value),
-- @ is automatically filled with spaces, because
-- it is declared as a char(x) and assigned a value
,@ char(91)=3;
-- recursive query
WITH C as
(
-- z string containing digits for the direction of next letter
-- z should not contain 4 because it will point to same position.
-- values in z 0,1,2,3,4,5,6,7,8 can logally convert to
-- (-1,-1),(-1,0),(-1,1),(0,-1),(0,0),(0,1),(1,-1),(1,0),(1,1)
-- a is the starting position
SELECT'5585877636333330301125255'z,8a,ascii(@y)x
UNION ALL
-- stuff remove first character from the z string
-- a calculate next position of the next letter
-- x cycle the input letter
SELECT stuff(z,1,1,''),a+left(z,1)/3*13+left(z,1)%3-14,(x+14)%26+65
-- repeat recursive until long string is empty
FROM C
WHERE''<z
)
SELECT
-- 1st stuff replace the character to created the start of a
-- logical line in the string @ this is where 3 gets overwritten
-- 2nd stuff replaces a character(space if coded correct)
-- with the letter at the calculated position.
@=stuff(stuff(@,a,1,char(x)),1+a/13*13,1,char(13))
FROM C
PRINT @
```
[Answer]
# C(GCC) ~~286~~ 270 bytes
-12 bytes ceilingcat
Not exactly the shortest golf, but it works
```
#define r(a)(a+c)%26+65
#define R(a)for(i=10;i;a[--i]>32?a[i]=r(a[i]):0);
i;f(c){char T[]=" XYZABC\n",E[]="VW DE\n",F[]="RQ JI\n",B[]=" PONMLK";R(T)R(E)R(F)R(B)printf("%s %s%c%*c\n%c%*c\n%c%*c\n %s%s",T,E,r(85),11,r(70),r(84),11,r(71),r(83),11,r(72),F,B);}
```
[Try it online!](https://tio.run/##VY9bS8QwEIXf@yuGSNiMm0LbvSiGKlZbUNfLluKt24cQN5oHo7T7tuxvr8lqHxw4nDkfnIFR4btSfX/wttbGrqFlEpkcK6TJfDyfBQMvHddfLTNpHAkjZB2GpjmdJGeyNk3qWs7wJEIRGKGZwq36kC1UdZMSAHh@eT3PLlaW8NyTxyfYz2XuUeFRufxF11ceZX@9h/u728UNESWrsGS5U@GU4Xdr7EYzQjugHVX0UK3sf/O8I7ziOW/Z8Qx5HLvlKEIfp0OM93EyxAR5wTMUu96dh09pLEPYBgCajZYj99uu/wE "C (gcc) – Try It Online")
[Answer]
# [PHP](https://php.net/), ~~236~~ ~~229~~ 226 bytes
```
<?=($a=ord(file_get_contents('php://stdin'))-65)?preg_replace_callback('~\w~',function($m)use($a){return chr((ord($m[0])-65+$a)%26+65);},' XYZABC
VW DE
U F
T G
S H
RQ JI
PONMLK'):'';
```
[Try it online!](https://tio.run/##RY3JCsIwAETv@YocKklQqQh6qIq47/u@UWqMtljTkKZ4EP312iroHIYZBt4IW4RhsVzCmlXy5AmfHZeZF6ZM6nHFuPIxErYwdN1XJ4cjQtL5HCkLyS6mZMK1KDOp5bpHi14xeu3vL5Q6B5wqx@NYu5HAZxGZPCRTgeSQ2hLj@Ea77TKHmJWM1kQ2n4yohWcKQQjXm22lWgNwuYIf1RtgAX9qgvm/tMDsX9oATiff2O2AyMej4aDfQ8RAqBCGzTc "PHP – Try It Online")
Pre-golf:
```
<?php
$adjust = ord(file_get_contents('php://stdin')) - 65;
echo preg_replace_callback('~\w~', function($match) use ($adjust) {
$new = ord($match[0]) - 65;
$new = ($new + $adjust) % 26;
$new += 65;
return chr($new);
}, ' XYZABC
VW DE
U F
T G
S H
RQ JI
PONMLK');
```
Explanation:
Using `ord` we convert to an integer between 0 and 255. A is 65 and Z is 90.
Using this knowledge, we take the input and reduce it by 65 so we have an adjustment value.
We then iterate over all characters, call `ord` on them, reduce them by 65, increase them by our adjustment value. Using modulo we loop back down to 0 if they exceed 26.
We then increase them by 65 again and convert them back into letters with `chr`.
Sadly php://stdin can only be interogated once, so we need to pass the input into the function in our loop, preventing us from saving bytes on `use($a)` and having to declare a variable outside the function stops us from cleanly using the `<?=` echo method - we have to wrap everything in a giant ternary.
[Answer]
# Javascript (V8), 316 bytes
```
function a(b){n="abcdefghijklmnopqrstuvwxyz".split(b);n=b+n[1]+n[0],console.log(` ${n[23]+n[24]+n[25]+n[0]+n[1]+n[2]}\n ${n[21]+n[22]} ${n[3]+n[4]}\n${n[20]} ${n[5]}\n${n[19]} ${n[6]}\n${n[18]} ${n[7]}\n ${n[17]+n[16]} ${n[9]+n[8]}\n ${n[15]+n[14]+n[13]+n[12]+n[11]+n[10]}`)}
```
[Try it online](https://tio.run/##bY/RCoIwFIbve4ohgUolzqyU6ElKcJqZtc5MzUrx2W0eMULaxYF93z/OvwsrWR5mSVosSqc9PSAsEgGEaYFet7BTWBAeo1N8Ti5XfgOR3rO8eJTP17tSjDzlSSGDW9gFM9hTTw7Tm4cCcsEjg4tY8wkh0xr21rKTlo1z1QeHJ5bXHKBP9XcJCJ6O4UO7i2DCHNzgV4Oi7litv8oZq813J91gkfXvTrdDDkZ6QLEyxfoUG1ELJxamspSvT9pm8vt1pqlc1fUxO/5hlWTtBw)
First time trying code golf out. Appreciate any tips / feedback.
Original code before minifying:
```
function a(b){
var c = ("abcdefghijklmnopqrstuvwxyz").split(b);
c = b+c[1]+c[0]
console.log(` ${c[23]+c[24]+c[25]+c[0]+c[1]+c[2]}\n ${c[21]+c[22]} ${c[3]+c[4]}\n${c[20]} ${c[5]}\n${c[19]} ${c[6]}\n${c[18]} ${c[7]}\n ${c[17]+c[16]} ${c[9]+c[8]}\n ${c[15]+c[14]+c[13]+c[12]+c[11]+c[10]}`)
}
```
[Answer]
# [Red](http://www.red-lang.org), 139 bytes
```
func[a][foreach c{ XYZABC
VW DE
U F
T G
S H
RQ JI
PONMLK}[if c > sp[c: c + a % 26 + 65]prin c]]
```
[Try it online!](https://tio.run/##K0pN@R@UmhIdy5Vm9T@tNC85OjE2Oi2/KDUxOUMhuVpBQSEiMsrRyZlLISxcAQxcXLlCFeDAjSsEwXHnCkZwPLgUggIhTC9PLiAZ4O/n6@NdG52ZppCsYKdQXBCdbAVkaSskKqgqGJkBGWamsQVFmXkKybGx/9MUlJWclLhA/BKFnDQuEN8DjR@l9B8A "Red – Try It Online")
A really naive solution.
[Answer]
# [Perl 5](https://www.perl.org/) `-p`, 110 bytes
```
$b=/A/?Z:chr(-1+ord);$_=eval("'2XYZABC
VW5DE
U9F
T9G
S9H
RQ5JI
2PONMLK'=~y/A-Z/$_-ZA-$b/r");s/\d/$".$"x$&/eg
```
[Try it online!](https://tio.run/##K0gtyjH9/18lyVbfUd8@yio5o0hD11A7vyhF01ol3ja1LDFHQ0ndKCIyytHJmUshLNzUxZUr1NKNK8TSnSvY0oNLISjQ1MuTyyjA38/Xx1vdtq5S31E3Sl8lXjfKUVclSb9ISdO6WD8mRV9FSU9FqUJFTT81/f9/x3/5BSWZ@XnF/3ULAA "Perl 5 – Try It Online")
[Answer]
# [APL (Dyalog Classic)](https://www.dyalog.com/), 50 bytes
```
⎕a@((-⎕a⍳⍞)⌽∪⌊.5+{3 5.5×1-2 1○○⍵÷¯19}¨⍳38)⊢7 12⍴''
```
[Try it online!](https://tio.run/##VY9LT8JAFIX3/RWzuxAtsRDiYyUoUN7v566B1BAbawobQ9gZRGCILgwrXbAyblwoISFxA//k/hG8Uxoapk3mfu2cc@Zo94bcetAM80ZuGlqn025ucfrWNnHwciLh8EkXqF16PLLYkf8g//Di5A@HXzgZ@YJHvQAL@oKbmSL7mYKzsXj5YrNcfyvn/fUnKQJnXhzNT5niR/4LsCXXLfKpQi7Q1ymoB8dAtkAJFg0LwOGI/i6JmxbowJC/s66ltfQ71jUZbVJXyOgoPs8tGnXkqwvQtbZB@hV9t3D8COYt9CUIAx1@BcZYvREKX13TAPRUa8xekajACtuvGGHZRZWw5GJcaIuFHSQTthVj@Vw2k04JZwnUfV4kGlPjCSfPDhaalMCw65gmDLmYIWy4mBXaunPXfM7Jq1bKJfsSlNfY51VroqGTV3YqUe5hgwhh0cUoYeGwvcjZlVWdPNEuaTf5Bw "APL (Dyalog Classic) – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~200~~ ~~198~~ 197 bytes
-3 bytes thanks to ceilingcat.
```
x,z;f(c){char*y,t[27],i=0;for(c-=46;i<14;t[13+i++]=(c-i)%26+65)t[i]=(c+i)%26+65;for(i=-4;++i<4;printf("%*.*s%*.*s\n",3273>>x*3&7,x?:1,y,z,x?:1,y+2*!i+z))z="--*%"[x=abs(i)]-34,y=t+x+(x>2)+13*(i>0);}
```
[Try it online!](https://tio.run/##bc1RS8MwFAXgZ/crZqAuNzeRtaktmKWiT/sN1j7UQLf7YB1thLRjv73Woi@yl8Phg8Nx6uDcNAU5moY7OLtj3YlB@jLJK0l2a5rPjjtl08zQLk6NL2ONhFjZWQmiJMPsAXxJP4B/sKzIqtQg0i41p45a33AWiXvRL/HWMqmTXBdFEPoul@HpMZaDHH8LJuKWcAQYLVNKRKwMtn7vOUGldCoH6zEgD0UCGGvBqdiCuUzzyfqjppbD6ry6afjmeQNmffryPWfzIZgFX67h/hq@/sfL9A0 "C (gcc) – Try It Online")
[Answer]
# [PHP](https://php.net/), 131 bytes
```
for(;$s='2YZABCD
WX5EF
V9G
U9H
T9I
SR5KJ
2QPONML'[$i++];)echo$s<A?$s<'0'?$s:str_pad('',$s+1,' '):chr(65+(ord($s)+ord($argn))%26);
```
[Try it online!](https://tio.run/##HcXbCoIwGADg@z2FF4t/YwYlKHgIsYMdLDufiRCt9MaNzedvSTffJ0qhg1C0vrkkPlYDsK63aDgaI@N8sScxOrlTdHRn6ODOkbHf2ckCWdvNOl0t4Y4rxh4@feUlxyqIwhboQZunGvkUWUEATKxY3wQDqJeXkjg2I1wWBCvK/mfyU1PasRzqa51@uWgqXivdjX8 "PHP – Try It Online")
] |
[Question]
[
Your task is to create a program which takes a black-and-white outlined image (example images are below) and fills it in with colour. It is up to you how you section off each region and which colour to fill it with (you could even use an RNG).
For example:
![output for example 1](https://i.stack.imgur.com/IW9gZ.jpg)
As you can see I am clearly an artist of a superior calibre when it comes to MS Paint.
---
## Scoring
This is a popularity contest, so the answer with the most net votes wins. Voters are encouraged to judge answers by
* Input criterion: any image that consists of white/light-grey background and black/dark-grey outlines
* How well the colouring is done; meaning few or no areas are white unlike the above (unless you obviously intend to use white e.g. for clouds)
* Customisability of the colours used in certain sections
* How well the system works on a range of different images (of varying detail)
* Post how long your program takes per image. We might not be playing code golf, but shorter, faster and more efficient code should be regarded as better
* Should output the new image either onto the screen or to a file (no larger than 2MB so that it can be shown in the answer)
* Please justify why you chose to output to that image type and comment/explain the workings of your code
* The applicability of the colour used to the respective shape it is bound by (realistic colour scheme i.e. grass is green, wooden fences are brown etc.)
>
> "I could randomly color each area, but if I could identify the "fence" and make it similarly colored, then that's
> something that deserves upvotes." - NathanMerrill
>
>
>
Seeing as this *is* a popularity contest, you can also optionally judge by:
* Overall appeal (how good the image looks)
* Artistic flair; if you can program in shading or watercolour-style colouring etc.
**In general, the smallest outputted image (file size) of the highest quality, with the fasted program and the highest public vote will win.**
If you have other judging specifications that you think should be used, please recommend them in the comments of this post.
---
## Examples
*I own nothing; all example images are of a creative commons license.*
![example 1 in black/white](https://i.stack.imgur.com/pvyyH.png)
Source: <https://pixabay.com/ro/stejar-arbore-schi%C5%A3%C4%83-natura-303890/>
![example 2 in black/white](https://i.stack.imgur.com/kPnLi.png)
Source: <http://www.freestockphotos.biz/stockphoto/10665>
![example 3 in black/white](https://i.stack.imgur.com/rpPOo.jpg)
Source: <http://crystal-rose1981.deviantart.com/art/Dragon-Tattoo-Outline-167320011>
![example 4 in black/white](https://i.stack.imgur.com/zyR2t.png)
Source: <http://jaclynonacloudlines.deviantart.com/art/Gryphon-Lines-PF-273195317>
![example 5 in black/white](https://i.stack.imgur.com/l0tXv.jpg)
Source: <http://captaincyprus.deviantart.com/art/Dragon-OutLine-331748686>
![example 6 in black/white](https://i.stack.imgur.com/3BoTZ.jpg)
Source: <http://electric-meat.deviantart.com/art/A-Heroes-Farewell-280271639>
![example 7 in black/white](https://i.stack.imgur.com/0w8QW.jpg)
Source: <http://movillefacepalmplz.deviantart.com/art/Background-The-Pumpkin-Farm-of-Good-old-Days-342865938>
---
EDIT: Due to anti-aliasing on lines causing non-black/white pixels and some images that may contain grey instead of black/white, as a bonus challenge you can attempt to deal with it. It should be easy enough in my opinion.
[Answer]
# Spectral airbrushing (Python, PIL, scipy)
This uses a sophisticated mathematical algorithm to produce colourful nonsense. The algorithm is related to Google's PageRank algorithm, but for pixels instead of web pages.
I took this approach because I thought that unlike flood-fill based methods it might be able to cope with images like the chicken and the tree, where there are shapes that aren't entirely enclosed by black lines. As you can see, it sort of works, though it also tends to colour in different parts of the sky in different colours
For the mathematically minded: what it's doing is essentially constructing the adjacency graph of the while pixels in the image, then finding the top 25 eigenvectors of the graph Laplacian. (Except it's not quite that, because we do include the dark pixels, we just give their connections a lower weight. This helps in dealing with antialiasing, and also seems to give better results in general.) Having found the eigenvectors, it creates a random linear combination of them, weighted by their inverse eigenvalues, to form the RGB components of the output image.
In the interests of computation time, the image is scaled down before doing all this, then scaled back up again and then multiplied by the original image. Still, it does not run quickly, taking between about 2 and 10 minutes on my machine, depending on the input image, though for some reason the chicken took 17 minutes.
It might actually be possible to turn this idea into something useful, by making an interactive app where you can control the colour and intensity of each of the eigenvectors. That way you could fade out the ones that divide the sky into different sections, and fade in the ones that pick up on relevant features of the image. But I have no plans to do this myself :)
Here are the output images:
[![enter image description here](https://i.stack.imgur.com/EJljH.png)](https://i.stack.imgur.com/EJljH.png)
[![enter image description here](https://i.stack.imgur.com/mmQOT.png)](https://i.stack.imgur.com/mmQOT.png)
[![enter image description here](https://i.stack.imgur.com/Z1UW4.png)](https://i.stack.imgur.com/Z1UW4.png)
[![enter image description here](https://i.stack.imgur.com/e0P8E.png)](https://i.stack.imgur.com/e0P8E.png)
[![enter image description here](https://i.stack.imgur.com/qdIBW.png)](https://i.stack.imgur.com/qdIBW.png)
(It didn't work so well on the pumpkins, so I omit that one.)
And here is the code:
```
import sys
from PIL import Image
import numpy as np
import scipy.sparse as sp
import scipy.sparse.linalg as spl
import os
import time
start_time = time.time()
filename = sys.argv[1]
img = Image.open(filename)
orig_w, orig_h = img.size
# convert to monochrome and remove any alpha channel
# (quite a few of the inputs are transparent pngs)
img = img.convert('LA')
pix = img.load()
for x in range(orig_w):
for y in range(orig_h):
l, a = pix[x,y]
l = (255-a) + a*l/255
a = 255
pix[x,y] = l,a
img = img.convert('L')
orig_img = img.copy()
# resize to 300 pixels wide - you can get better results by increasing this,
# but it takes ages to run
orig_w, orig_h = img.size
print "original size:", str(orig_w)+ ', ' + str(orig_h)
new_w = 300
img = img.resize((new_w, orig_h*new_w/orig_w), Image.ANTIALIAS)
pix = img.load()
w, h = img.size
print "resizing to", str(w)+', '+str(h)
def coords_to_index(x, y):
return x*h+y
def index_to_coords(i):
return (int(i/h), i%h)
print "creating matrix"
A = sp.lil_matrix((w*h,w*h))
def setlink(p1x, p1y, p2x, p2y):
i = coords_to_index(p1x,p1y)
j = coords_to_index(p2x,p2y)
ci = pix[p1x,p1y]/255.
cj = pix[p2x,p2y]/255.
if ci*cj > 0.9:
c = 1
else:
c = 0.01
A[i,j] = c
return c
for x in range(w):
for y in range(h):
d = 0.
if x>0:
d += setlink(x,y,x-1,y)
if x<w-1:
d += setlink(x,y,x+1,y)
if y>0:
d += setlink(x,y,x,y-1)
if y<h-1:
d += setlink(x,y,x,y+1)
i = coords_to_index(x,y)
A[i,i] = -d
A = A.tocsr()
# the greater this number, the more details it will pick up on. But it increases
# execution time, and after a while increasing it won't make much difference
n_eigs = 25
print "finding eigenvectors (this may take a while)"
L, V = spl.eigsh(A, k=n_eigs, tol=1e-12, which='LA')
print "found eigenvalues", L
out = Image.new("RGB", (w, h), "white")
out_pix = out.load()
print "painting picutre"
V = np.real(V)
n = np.size(V,0)
R = np.zeros(n)
G = np.zeros(n)
B = np.zeros(n)
for k in range(n_eigs-1):
weight = 1./L[k]
R = R + V[:,k]*np.random.randn()*weight
G = G + V[:,k]*np.random.randn()*weight
B = B + V[:,k]*np.random.randn()*weight
R -= np.min(R)
G -= np.min(G)
B -= np.min(B)
R /= np.max(R)
G /= np.max(G)
B /= np.max(B)
for x in range(w):
for y in range(h):
i = coords_to_index(x,y)
r = R[i]
g = G[i]
b = B[i]
pixval = tuple(int(v*256) for v in (r,g,b))
out_pix[x,y] = pixval
out = out.resize((orig_w, orig_h), Image.ANTIALIAS)
out_pix = out.load()
orig_pix = orig_img.load()
for x in range(orig_w):
for y in range(orig_h):
r,g,b = out_pix[x,y]
i = orig_pix[x,y]/255.
out_pix[x,y] = tuple(int(v*i) for v in (r,g,b))
fname, extension = os.path.splitext(filename)
out.save('out_' + fname + '.png')
print("completed in %s seconds" % (time.time() - start_time))
```
[Answer]
# Python 2 + PIL too, my first coloring book
```
import sys, random
from PIL import Image
def is_whitish(color):
return sum(color)>500
def get_zone(image, point, mask):
pixels = image.load()
w, h = image.size
s = [point]
while s:
x, y = current = s.pop()
mask[current] = 255
yield current
s+=[(i,j) for (i,j) in [(x,y-1),(x,y+1),(x-1,y),(x+1,y)] if 0<=i<w and 0<=j<h and mask[i,j]==0 and is_whitish(pixels[i,j])]
def get_zones(image):
pixels = I.load()
mask = Image.new('1',image.size).load()
w,h = image.size
for y in range(h):
for x in range(w):
p = x,y
if mask[p]==0 and is_whitish(pixels[p]):
yield get_zone(image, p, mask)
def apply_gradient(image, mincolor, maxcolor, points):
minx = min([x for x,y in points])
maxx = max([x for x,y in points])
miny = min([y for x,y in points])
maxy = max([y for x,y in points])
if minx == maxx or miny==maxy:
return
diffx, diffy = (maxx - minx), (maxy-miny)
stepr = (maxcolor[0] - mincolor[0] * 1.0) / diffy
stepg = (maxcolor[1] - mincolor[1] * 1.0) / diffy
stepb = (maxcolor[2] - mincolor[2] * 1.0) / diffy
r,g,b = mincolor
w, h = (abs(diffx+1),abs(diffy+1))
tmp = Image.new('RGB', (w,h))
tmppixels = tmp.load()
for y in range(h):
for x in range(w):
tmppixels[x,y] = int(r), int(g), int(b)
r+=stepr; g+=stepg; b+=stepb
pixels = image.load()
minx, miny = abs(minx), abs(miny)
for x,y in points:
try:
pixels[x,y] = tmppixels[x-minx, y-miny]
except Exception, e:
pass
def colors_seq():
yield (0,255,255)
c = [(255,0,0),(0,255,0),(0,0,139)]
i=0
while True:i%=len(c);yield c[i];i+=1
def colorize(image):
out = image.copy()
COLORS = colors_seq()
counter = 0
for z in get_zones(image):
c1 = COLORS.next()
c2 = (0,0,0) if counter == 0 else (255,255,255)
if counter % 2 == 1:
c2, c1 = c1, c2
apply_gradient(out, c1, c2, list(z))
counter +=1
return out
if __name__ == '__main__':
I = Image.open(sys.argv[-1]).convert('RGB')
colorize(I).show()
```
I did quite the same as CarpetPython did, except that I fill the region with 'gradients', and use a different color cycle.
My most magnificient colorings :
[![enter image description here](https://i.stack.imgur.com/2HFea.png)](https://i.stack.imgur.com/2HFea.png)
[![enter image description here](https://i.stack.imgur.com/QS9dI.png)](https://i.stack.imgur.com/QS9dI.png)
[![enter image description here](https://i.stack.imgur.com/TodIj.png)](https://i.stack.imgur.com/TodIj.png)
## Computation times on my machine :
* image 1 (chinese dragon): real 0m2.862s user 0m2.801s sys 0m0.061s
* image 2 (gryffon) : real 0m0.991s user 0m0.963s sys 0m0.029s
* image 3 (unicornish dragon): real 0m2.260s user 0m2.239s sys 0m0.021s
[Answer]
# Python 2 and PIL: Psychedelic Worlds
I have used a simple algorithm to flood fill each white-ish area with a color from a cycling palette. The result is very colorful, but not very lifelike.
Note that the "white" parts in these pictures are not very white. You will need to test for shades of grey too.
Code in Python 2.7:
```
import sys
from PIL import Image
WHITE = 200 * 3
cs = [60, 90, 120, 150, 180]
palette = [(199,199,199)] + [(R,G,B) for R in cs for G in cs for B in cs]
def fill(p, color):
perim = {p}
while perim:
p = perim.pop()
pix[p] = color
x,y = p
for u,v in [(x+dx, y+dy) for dx,dy in [(-1,0), (1,0), (0,1), (0,-1)]]:
if 0 <= u < W and 0 <= v < H and sum(pix[(u,v)]) >= WHITE:
perim.add((u,v))
for fname in sys.argv[1:]:
print 'Processing', fname
im = Image.open(fname)
W,H = im.size
pix = im.load()
colornum = 0
for y in range(H):
for x in range(W):
if sum(pix[(x,y)]) >= WHITE:
thiscolor = palette[colornum % len(palette)]
fill((x,y), thiscolor)
colornum += 1
im.save('out_' + fname)
```
Example pictures:
[![A colorful dragon](https://i.stack.imgur.com/OFc5p.jpg)](https://i.stack.imgur.com/OFc5p.jpg)
[![Pumpkins on LSD](https://i.stack.imgur.com/8hUlY.jpg)](https://i.stack.imgur.com/8hUlY.jpg)
[Answer]
# Matlab
```
function [output_image] = m3(input_file_name)
a=imread(input_file_name);
b=im2bw(a,0.85);
c=bwlabel(b);
h=vision.BlobAnalysis;
h.MaximumCount=10000;
ar=power(double(step(h,b)),0.15);
ar=[ar(1:max(max(c))),0];
f=cat(3,mod((ar(c+(c==0))-min(ar(1:end-1)))/ ...
(max(ar(1:end-1))-min(ar(1:end-1)))*0.9+0.8,1),c*0+1,c*0+1);
g=hsv2rgb(f);
output_image=g.*cat(3,c~=0,c~=0,c~=0);
```
We use HSV colorspace and choose each regions Hue based on it's relative size between the white regions. The largest region will be blue (`Hue = 0.7`) and the smallest region will be violet (`Hue = 0.8`). The regions between these two sizes are given Hues in the range `0.7 -> 1=0 -> 0.8`. The Hue on the range is linearly selected in respect to the function `area^0.15`.
Saturation and Value is always 1 for every non-black pixel.
It takes less then 1 second to color an image.
The 3 pictures with closed regions where the algorithm works decently:
[![dragon](https://i.stack.imgur.com/xRi90.png)](https://i.stack.imgur.com/xRi90.png)
[![another dragon](https://i.stack.imgur.com/shfdJ.png)](https://i.stack.imgur.com/shfdJ.png)
[![maybe another dragon](https://i.stack.imgur.com/qpkDu.png)](https://i.stack.imgur.com/qpkDu.png)
And the rest of the images:
[![dragon](https://i.stack.imgur.com/NmGMC.png)](https://i.stack.imgur.com/NmGMC.png)
[![another dragon](https://i.stack.imgur.com/MK4Md.png)](https://i.stack.imgur.com/MK4Md.png)
[![maybe another dragon](https://i.stack.imgur.com/LJOIB.jpg)](https://i.stack.imgur.com/LJOIB.jpg)
On these images there are big white connected regions which should be ideally colored by multiple colors (this problem was nicely solved in [Nathaniel's solution](https://codegolf.stackexchange.com/a/69048/7311).
[Answer]
## Python 3 with Pillow
The code is a bit long to include in this answer, but [here's the gist of it](https://gist.github.com/perey/3a45d6a78cbeb62d0a09).
1. Take the input image and, if it has an alpha channel, composite it onto a white background. (Necessary at least for the chicken image, because that entire image was black, distinguished only by transparency, so simply dropping the alpha was not helpful.)
2. Convert the result to greyscale; we don't want compression or anti-aliasing artifacts, or grey-lines-that-aren't-quite-grey, to mess us up.
3. Create a bi-level (black and white) copy of the result. Shades of grey are converted to black or white based on a configurable cutoff threshold between white and the darkest shade in the image.
4. Flood-fill every white region of the image. Colours are chosen at random, using a selectable palette that takes into account the location of the starting point for the flood-fill operation.
5. Fill in the black lines with their nearest-neighbour colours. This helps us reintroduce anti-aliasing, by keeping every coloured region from being bordered in jaggy black.
6. Take the greyscale image from step 2 and make an alpha mask from it: the darkest colour is fully opaque, the lightest colour is fully transparent.
7. Composite the greyscale image onto the coloured image from step 5 using this alpha mask.
Those last few steps, unfortunately, have still not eliminated lighter "halos" that are visible in darker-coloured regions, but they've made a noticeable difference, at least. Image processing was never my field of study, so for all I know there are more successful and more efficient algorithms to do what I tried to do here... but oh well.
So far, there are only two selectable palettes for step 4: a purely random one, and a very rough "natural" one, which tries to assign sky colours to the upper corners, grass colours to the lower corners, brown (rocks or wood) colours to the middle of each side, and varied colours down the centre. Success has been... limited.
---
### Usage:
```
usage: paint_by_prog.py [-h] [-p PALETTE] [-t THRESHOLD] [-f | -F] [-d]
FILE [FILE ...]
Paint one or more line-art images.
positional arguments:
FILE one or more image filenames
optional arguments:
-h, --help show this help message and exit
-p PALETTE, --palette PALETTE
a palette from which to choose colours; one of
"random" (the default) or "natural"
-t THRESHOLD, --threshold THRESHOLD
the lightness threshold between outlines and paintable
areas (a proportion from 0 to 1)
-f, --proper-fill fill under black lines with proper nearest-neighbour
searching (slow)
-F, ---no-proper-fill
fill under black lines with approximate nearest-
neighbour searching (fast)
-d, --debug output debugging information
```
---
### Samples:
`paint_by_prog.py -t 0.7 Gryphon-Lines.png`
[![Coloured gryphon](https://i.stack.imgur.com/d9zop.png)](https://i.stack.imgur.com/d9zop.png)
`paint_by_prog.py Dragon-Tattoo-Outline.jpg`
[![Coloured cartoony dragon](https://i.stack.imgur.com/tk5ZT.jpg)](https://i.stack.imgur.com/tk5ZT.jpg)
`paint_by_prog.py -t 0.85 -p natural The-Pumpkin-Farm-of-Good-old-Days.jpg`
[![Coloured farm scene](https://i.stack.imgur.com/uTszu.png)](https://i.stack.imgur.com/uTszu.png)
`paint_by_prog.py -t 0.7 Dragon-OutLine.jpg`
[![Coloured grunge dragon](https://i.stack.imgur.com/aBUHi.jpg)](https://i.stack.imgur.com/aBUHi.jpg)
`paint_by_prog.py stejar-arbore-schiţă-natura.png`
[![Coloured tree, looking very flag-like](https://i.stack.imgur.com/lXfCE.png)](https://i.stack.imgur.com/lXfCE.png)
The chicken doesn't look very good, and my most recent result for the Link image isn't the best; one that came from an earlier version of the code was largely pale yellow, and had an interesting desert vibe about it...
---
### Performance:
Each image takes a couple of seconds to process with default settings, which means an approximate nearest-neighbour algorithm is used for step 5. True nearest-neighbour is significantly slower, taking maybe half a minute (I haven't actually timed it).
[Answer]
# Java
Random color selection from your choice of pallette.
Warning: Region finding currently very slow, unless the white regions are unusually small.
```
import java.awt.Color;
import java.awt.image.*;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.Random;
import java.util.Scanner;
import java.util.function.Supplier;
import javax.imageio.ImageIO;
public class Colorer{
public static boolean isProbablyWhite(int x,int y){
Color c=new Color(image.getRGB(x, y));
if(c.getRed()<240)return false;
if(c.getBlue()<240)return false;
if(c.getGreen()<240)return false;
return true;
}
static class Point{
int x,y;
public boolean equals(Object o){
if(o instanceof Point){
Point p=(Point)o;
return x==p.x&&y==p.y;
}
return false;
}
public Point(int x,int y){
this.x=x;
this.y=y;
}
}
static BufferedImage image;
static int W,H;
public static void check(Point p,List<Point>l1,List<Point>l2,List<Point>l3){
if(!isProbablyWhite(p.x,p.y))return;
if(l1.contains(p))return;
if(l2.contains(p))return;
if(l3.contains(p))return;
l1.add(p);
}
public static void process(int x,int y,Color c){
List<Point>plist=new LinkedList<>();
int rgb=c.getRGB();
plist.add(new Point(x,y));
List<Point>l3=new LinkedList<>();
int k=0;
for(int i=0;i<W*H;i++){
System.out.println(k=l3.size());
List<Point>l2=new LinkedList<>();
for(Point p:plist){
int x1=p.x;
int y1=p.y;
if(x1>0){
check(new Point(x1-1,y1),l2,plist,l3);
}
if(y1>0){
check(new Point(x1,y1-1),l2,plist,l3);
}
if(x1<W-1){
check(new Point(x1+1,y1),l2,plist,l3);
}
if(y1<H-1){
check(new Point(x1,y1+1),l2,plist,l3);
}
}
while(!plist.isEmpty()){
l3.add(plist.remove(0));
}
if(l3.size()==k)break;
plist=l2;
}
plist=l3;
for(Point p:plist){
image.setRGB(p.x,p.y,rgb);
}
}
public static void main(String[]args) throws Exception{
Random rand=new Random();
List<Supplier<Color>>colgen=new ArrayList<>();
colgen.add(()->{return new Color(rand.nextInt(20),50+rand.nextInt(200),70+rand.nextInt(180));});
colgen.add(()->{return new Color(rand.nextInt(20),rand.nextInt(40),70+rand.nextInt(180));});
colgen.add(()->{return new Color(150+rand.nextInt(90),10+rand.nextInt(120),rand.nextInt(5));});
colgen.add(()->{int r=rand.nextInt(200);return new Color(r,r,r);});
colgen.add(()->{return Arrays.asList(new Color(255,0,0),new Color(0,255,0),new Color(0,0,255)).get(rand.nextInt(3));});
colgen.add(()->{return Arrays.asList(new Color(156,189,15),new Color(140,173,15),new Color(48,98,48),new Color(15,56,15)).get(rand.nextInt(4));});
Scanner in=new Scanner(System.in);
image=ImageIO.read(new File(in.nextLine()));
final Supplier<Color>sup=colgen.get(in.nextInt());
W=image.getWidth();
H=image.getHeight();
for(int x=0;x<W;x++){
for(int y=0;y<H;y++){
if(isProbablyWhite(x,y))process(x,y,sup.get());
}
}
ImageIO.write(image,"png",new File("out.png"));
}
}
```
Requires two inputs: the filename, and the palette ID. Includes some antialiasing correction, but does not include logic for transparent pixels.
The following palettes are currently recognized:
```
0: Blue and greeen
1: Blue
2: Red
3: Greyscale
4: Three-color Red, Green, and Blue
5: Classic Game Boy pallette (four shades of green)
```
# Results:
Dragon, Game Boy palette:
![enter image description here](https://i.stack.imgur.com/vjde0.png)
The other dragon, blue + green palette:
![enter image description here](https://i.stack.imgur.com/IuY9Y.png)
GOL still life mona lisa (as rendered by [this program](https://codegolf.stackexchange.com/questions/38573/paint-a-still-life-or-a-moving-one-draw-an-image-in-the-game-of-life/65510#65510)), tricolor palette:
![enter image description here](https://i.stack.imgur.com/dov9q.png)
] |
[Question]
[
PPCG user and elected mod, [@Dennis](https://codegolf.stackexchange.com/users/12012/dennis) just became the second ever user to earn over 100k rep!
[![enter image description here](https://i.stack.imgur.com/5ME5N.png)](https://i.stack.imgur.com/5ME5N.png)
This is a totally original idea, that I [did not get from anybody else](https://codegolf.stackexchange.com/questions/57719/generate-dennis-numbers), but let's make a challenge based off of his user ID, `12012` as a tribute!
Looking at it, you'll notice that there are two distinct "sections" to his ID.
>
> 12
>
>
>
and
>
> 012
>
>
>
Both of these sections add up to a 3. That's a pretty interesting property.
Let's define a "Dennis 2.0 number" as any positive integer where every maximal subsequence of strictly increasing digits sums to the same number. For example,
```
123
```
is a Dennis 2.0 number because there is only one maximal sublist of strictly increasing digits, and it sums to 6. Additionally, 2,846,145 is also a Dennis 2.0 number because the three maximal sublists of increasing digits, namely
```
28
46
145
```
All sum to `10`. Additionally, numbers that just repeat the same digit *must* be Dennis 2.0 numbers because, for example, `777` can be broken down into
```
7
7
7
```
which *clearly* all sum to seven.
A number such as `42` is *not* a Dennis 2.0 number, since it is broken down into
```
4
2
```
which clearly do not sum to the same number.
# The challenge
You must write a program or function to determine if a given number is a Dennis 2.0 number or not. You can take input and output in any reasonable input format, e.g. as a string, as a number, from a file, funtion arguments/return, from STDIN/STDOUT, etc. and then return a [truthy value](http://meta.codegolf.stackexchange.com/questions/2190/interpretation-of-truthy-falsey) if this number is a Dennis 2.0 number, and a falsy value if it is not. For reference, here is every Dennis 2.0 number up to 1,000:
```
1
2
3
4
5
6
7
8
9
11
12
13
14
15
16
17
18
19
22
23
24
25
26
27
28
29
33
34
35
36
37
38
39
44
45
46
47
48
49
55
56
57
58
59
66
67
68
69
77
78
79
88
89
99
101
111
123
124
125
126
127
128
129
134
135
136
137
138
139
145
146
147
148
149
156
157
158
159
167
168
169
178
179
189
202
222
234
235
236
237
238
239
245
246
247
248
249
256
257
258
259
267
268
269
278
279
289
303
312
333
345
346
347
348
349
356
357
358
359
367
368
369
378
379
389
404
413
444
456
457
458
459
467
468
469
478
479
489
505
514
523
555
567
568
569
578
579
589
606
615
624
666
678
679
689
707
716
725
734
777
789
808
817
826
835
888
909
918
927
936
945
999
```
Standard loopholes apply, and the shortest answer measured in bytes wins!
[Answer]
## JavaScript (ES6), ~~72~~ 70 bytes
Takes a string as input. Returns either false or a truthy value (which can be a number).
It's using a regular expression to transform an input string such as `"2846145"` into:
```
"(a=2+8)&&(a==4+6)&&(a==1+4+5)"
```
Then calls `eval()` on this expression.
```
let f =
n=>eval(n.replace(/./g,(v,i)=>(v>n[i-1]?'+':i?')&&(a==':'(a=')+v)+')')
console.log(f("101"));
console.log(f("102"));
console.log(f("777"));
console.log(f("2846145"));
```
[Answer]
# Jelly, ~~13~~ 12 bytes
*1 byte thanks to @Dennis.*
```
DIṠ’0;œṗDS€E
```
[Try it online!](http://jelly.tryitonline.net/#code=REnhuaDigJkwO8WT4bmXRFPigqxF&input=&args=Mjg0NjE0NQ)
### Explanation
```
DIṠ’0;œṗDS€E Main link. Argument: N
D Convert N to its digits.
I Find the differences between the elements.
·π† Find the sign of each difference. This yields 1 for locations where the
list is strictly increasing and 0 or -1 elsewhere.
’ Decrement. This yields 0 for locations where the list is strictly
increasing and -1 or -2 elsewhere.
0; Prepend a 0.
D Get another list of digits.
œṗ Split the list of digits at truthy positions, i.e. the -1s and -2s.
S€ Sum each sublist.
E Check if all values are equal.
```
[Answer]
# Python, 50 bytes
```
r='0'
for d in input():r=d+'=+'[r<d]*2+r
1/eval(r)
```
Expects `input()` to evaluate to a string, so the input needs surrounding quotes in Python 2. Output is via [exit code](https://codegolf.meta.stackexchange.com/a/5330/12012), where **0** indicates success (truthy) and **1** indicates failure (falsy).
Test it on [Ideone](http://ideone.com/pmwd1X).
### How it works
We initialize **r** to the string **0** and iterate over all digits **d** in the input.
* If **d** is larger than the first digit of **r** (initially **0**, then equal to the previous value of **d**), `r<d` evaluates to *True* and `'=+'[r<d]*2` yields `++`.
* If **d** is smaller than the first digit of **r**, `'=+'[r<d]*2` yields `==`.
* If **d** is equal to the first digit of **r**, **r** will be longer than the singleton string **d**, so `'=+'[r<d]*2` yields once again `==`.
In all cases, the digit **d** and the two generated characters get prepended to **r**.
Once all input digits have been processed, `eval(r)` evaluates the generated expression.
* If the input consists of a single strictly increasing sequence of (positive) digits, the expression evaluates to their sum.
For example, the integer **12345** results in the expression `5++4++3++2++1++0`, which yields **15** when evaluated. Note that each second **+** is a *unary* plus, so it doesn't affect the result. Dividing **1** by **15** is valid (the result is not important); the program exits normally.
* If the input consists of two strictly increasing sequences of digits, the expression consists of a simple comparison.
For example, the integer **12012** results in the expression `2++1++0==2++1++0`, which yields *True* when evaluated since both terms have sum **3**. Dividing **1** by *True* (**1**) is valid (the result is not important); the program exits normally.
On the other hand, the integer **12366** results in the expression `6==6++3++2++1++0`, which yields *False* when evaluated since the terms have sums **6** and **12**. Dividing **1** by *False* (**0**) raises a *ZeroDivisionError*; the program exits with an error.
* If the input consists of three or more strictly increasing sequences of digits, the expression consists of a [chained comparison](https://docs.python.org/3/reference/expressions.html#comparisons), which returns *True* if and only if all involved comparisons return *True*.
For example, the integer **94536** results in the expression `6++3==5++4==9++0`, which yields *True* when evaluated since all terms have sum **9**. As before, the program exits normally.
On the other hand, the integer **17263** results in the expression `3==6++2==7++1++0`, which yields *False* when evaluated since the terms have sums **3**, **8**, and **8**. As before, the program exits with an error.
[Answer]
# [Brachylog](http://github.com/JCumin/Brachylog), 13 bytes
```
~c@e:{<+}a!#=
```
[Try it online!](http://brachylog.tryitonline.net/#code=fmNAZTp7PCt9YSEjPQ&input=NTc1)
### Explanation
```
~c Find a list of integers which when concatenated result in the Input
@e Split the integers into lists of digits
:{<+}a Each list of digit is stricly increasing, and compute its sum
! Discard all other choice points (prevents backtracking for smaller sublists)
#= All sums must be equal
```
`~c` will unify with the biggest sublists first.
[Answer]
## Pyke, 18 bytes
```
mb$1m>0R+fMbms}lt!
```
[Try it here!](http://pyke.catbus.co.uk/?code=mb%241m%3E0R%2BfMbms%7Dlt%21&input=%22835%22)
```
mb - map(int, input)
$ - delta(^)
1m> - map(^, 1>i)
0R+ - [0]+^
f - input.split_at(^)
Mb - deep_map(int, ^)
ms - map(sum, ^)
} - uniquify(^)
lt! - len(^) == 1
```
[Answer]
## PowerShell v2+, ~~100~~ ~~64~~ 61 bytes
```
-join([char[]]$args[0]|%{("+$_","-eq$_")[$_-le$i];$i=$_})|iex
```
A literal one-liner, as this is all one pipeline. Takes input as a string `$args[0]`. Loops through it as a `char`-array, each iteration placing either the current element with a `+` or `-eq` in front of it onto the pipeline based on whether the current value is `-l`ess-than-or-`e`qual to the previous value `$i`. Those strings are `-join`ed together and piped to `iex` (short for `Invoke-Expression` and similar to `eval`. For example, for input `2846145` this will be evaluated as `+2+8-eq4+6-eq1+4+5`, which is `True`.
That Boolean is left on the pipeline, and `True`/`False` is implicitly written at program completion.
*NB - for single-digit input, the resulting digit is left on the pipeline, which is a truthy value in PowerShell.*
### Examples
```
PS C:\Tools\Scripts\golfing> 2846145,681,777,12366,2|%{"$_ -> "+(.\dennis-number-20.ps1 "$_")}
2846145 -> True
681 -> False
777 -> True
12366 -> False
2 -> 2
```
[Answer]
# GNU sed 217 or 115
Both include +1 for -r
**217:**
```
s/./&,/g;s/^/,/g;:;s,0,,;s,2,11,;s,3,21,;s,4,31,;s,5,41,;s,6,51,
s,7,61,;s,8,71,;s,9,81,;t;s/(,1*)(1*)\1,/\1\2X\1,/;t;s/,//g
s,1X1(1*),X\1a,;t;/^1.*X/c0
/Xa*$/s,a*$,,;y,a,1,;/1X1/b;/1X|X1/c0
c1
```
Takes input in normal decimal
[Try it online!](http://sed.tryitonline.net/#code=cy8uLyYsL2c7cy9eLywvZzs6O3MsMCwsO3MsMiwxMSw7cywzLDIxLDtzLDQsMzEsO3MsNSw0MSw7cyw2LDUxLApzLDcsNjEsO3MsOCw3MSw7cyw5LDgxLDt0O3MvKCwxKikoMSopXDEsL1wxXDJYXDEsLzt0O3MvLC8vZwpzLDFYMSgxKiksWFwxYSw7dDsvXjEuKlgvYzAKL1hhKiQvcyxhKiQsLDt5LGEsMSw7LzFYMS9iOy8xWHxYMS9jMApjMQ&input=MTIzCjI4NDYxNDUKNzc3CjQy&args=LXI)
---
**115:**
```
s/^|$/,/g;:;s/(,1*)(1*)\1,/\1\2X\1,/;t;s/,//g
s,1X1(1*),X\1a,;t;/^1.*X/c0
/Xa*$/s,a*$,,;y,a,1,;/1X1/b;/1X|X1/c0
c1
```
Takes input as a comma separated list of the numbers digits in unary. e.g. `123` would be `1,11,111`
[Try it online!](http://sed.tryitonline.net/#code=cy9efCQvLC9nOzo7cy8oLDEqKSgxKilcMSwvXDFcMlhcMSwvO3Q7cy8sLy9nCnMsMVgxKDEqKSxYXDFhLDt0Oy9eMS4qWC9jMAovWGEqJC9zLGEqJCwsO3ksYSwxLDsvMVgxL2I7LzFYfFgxL2MwCmMx&input=MSwxMSwxMTEKMTEsMTExMTExMTEsMTExMSwxMTExMTEsMSwxMTExLDExMTExCjExMTExMTEsMTExMTExMSwxMTExMTExCjExMTEsMTE&args=LXI)
[Answer]
## Perl, 38 + 3 (`-p`) = 41 bytes
*-9 bytes thanks to [@Ton Hospel](https://codegolf.stackexchange.com/users/51507/ton-hospel) !*
```
s%.%2x$&.(~$&le~$')%eg;$_=/^(2+1)\1*$/
```
Since there is a `$'`, the code needs to be in a file to run. So `-p` counts for 3 bytes. Outputs 1 if the number is a Dennis 2.0 number, or an empty string otherwise :
```
$ cat dennis_numbers.pl
s%.%2x$&.(~$&le~$')%eg;$_=/^(2+1)\1*$/
$ perl -p dennis_numbers.pl <<< "1
10
12315
12314"
```
[Answer]
# JavaScript (ES6), ~~66~~ ~~65~~ 63 bytes
*Saved 2 bytes thanks to @edc65*
```
x=>[...x,p=t=z=0].every(c=>p>=(t+=+p,p=c)?(z?z==t:z=t)+(t=0):1)
```
Takes input as a string. Old version (only works in Firefox 30+):
```
x=>[for(c of(p=t=0,x))if(p>=(t+=+p,p=c))t+(t=0)].every(q=>q==+p+t)
```
[Answer]
# Mathematica, 38 bytes
```
Equal@@Tr/@IntegerDigits@#~Split~Less&
```
Anonymous function. Takes a number as input, and returns `True` or `False` as output.
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog) 2, 10 bytes, language postdates challenge
```
ẹ~c<₁ᵐ!+ᵐ=
```
[Try it online!](https://tio.run/nexus/brachylog2#@/9w1866ZJtHTY0Pt05Q1AYStv//G5mYmQEA "Brachylog – TIO Nexus")
This is basically the same algorithm as @Fatalize's answer (which I didn't see until after I'd written this), but rearranged somewhat to make it golfier under Brachylog 2's syntax.
It's a full program, returning `false.` if it isn't a Dennis 2.0 number, or `true` if it is.
## Explanation
```
ẹ~c<₁ᵐ!+ᵐ=
·∫π Interpret the input number as a list of digits
! Find the first (in default order)
~c partition of the digits
<₁ᵐ such that each is in strictly increasing order
= Assert that the following are all equal:
+ᵐ the sums of each partition
```
As usual for a Brachylog full program, if all the assertions can be met simultaneously, we get a truthy return, otherwise falsey. The default order for `~c` is to sort partitions with fewer, longer elements first, and in Prolog (thus Brachylog), the default order's defined by the first predicate in the program (using the second as a tiebreak, and so on; here, `~c` dominates, because `·∫π` is deterministic and thus has nothing to order).
[Answer]
# MATL, ~~24~~ ~~23~~ ~~20~~ ~~18~~ 16 bytes
```
Tjdl<vYsG!UlXQ&=
```
Returns a [truthy of falsey](http://matl.tryitonline.net/#code=YAppdEQKPwonVFJVRSdECn0KJ0ZBTFNFJ0QKXVQKCg&input=WzEgMSAxOyAxIDEgMTsgMSAxIDFdClsxXQpbMSAwIDA7IDAgMSAwOyAwIDAgMV0KWzEgMSAxOyAxIDAgMTsgMSAxIDFd) matrix
[**Try it Online!**](http://matl.tryitonline.net/#code=VGpkbDx2WXNHIVVsWFEmPQ&input=Mjg0NjE0NQ)
Also, congrats @Dennis!
**Explanation**
```
T % Push a literal TRUE to the stack
% STACK: {1}
j % Explicitly grab the input as a string
% STACK: {1, '2846145'}
d % Compute the difference between successive ASCII codes
% STACK: {1, [6 -4 2 -5 3 1]}
l< % Find where that difference is less than 1
% STACK: {1, [0 1 0 1 0 0]}
v % Prepend the TRUE value we pushed previously
% STACK: {[1 0 1 0 1 0 0]}
Ys % Compute the cumulative sum. This assigns a unique integer label to
% each set of increasing numbers
% STACK: {[1 1 2 2 3 3 3]}
G!U % Grab the input as numeric digits
% STACK: {[1 1 2 2 3 3 3], [2 8 4 6 1 4 5]}
lXQ % Compute the sum of each group of increasing digits
% STACK: {[10 10 10]}
&= % Computes element-wise equality (automatically broadcasts). A
% truthy value in MATL is a matrix of all ones which is only the case
% when all elements are equal:
% STACK: {[1 1 1
% 1 1 1
% 1 1 1]}
% Implicitly display the result
```
[Answer]
## PHP, ~~108~~ ~~105~~ 92 bytes
```
$p=-1;foreach(str_split("$argv[1].")as$d)$p>=$d?$r&&$s-$r?die(1):($r=$s)&$s=$p=$d:$s+=$p=$d;
```
takes input from argument, exits with `0` for Dennis-2.0 number, with `1` else.
**breakdown**
```
$p=-1; // init $p(revious digit) to -1
foreach(str_split("$argv[1].")as$d) // loop $d(igit) through input characters
// (plus a dot, to catch the final sum)
$p>=$d // if not ascending:
?$r // do we have a sum remembered
&&$s-$r // and does it differ from the current sum?
?die(1) // then exit with failure
:($r=$s)&$s=$p=$d // remember sum, set sum to digit, remember digit
:$s+=$p=$d // ascending: increase sum, remember digit
;
//
```
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), 18 bytes
```
SD¥X‹X¸«DgL*ꥣOÙg
```
**Explanation**
`N = 12012` used as example.
```
# implicit input N = 12012
S # split input number to list of digits
# STACK: [1,2,0,1,2]
D # duplicate
# STACK: [1,2,0,1,2], [1,2,0,1,2]
¥ # reduce by subtraction
# STACK: [1,2,0,1,2], [1,-2,1,1]
X‹ # is less than 1
# STACK: [1,2,0,1,2], [0,1,0,0]
X¸« # append 1
# STACK: [1,2,0,1,2], [0,1,0,0,1]
DgL* # multiply by index (1-indexed)
# STACK: [1,2,0,1,2], [0,2,0,0,5]
ê # sorted unique
# STACK: [1,2,0,1,2], [0,2,5]
¥ # reduce by subtraction
# STACK: [1,2,0,1,2], [2,3]
£ # split into chunks
# STACK: [[1,2],[0,1,2]]
O # sum each
# STACK: [3,3]
√ô # unique
# STACK: [3]
g # length, 1 is true in 05AB1E
# STACK: 1
```
[Try it online!](http://05ab1e.tryitonline.net/#code=U0TCpVjigLlYwrjCq0RnTCrDqsKlwqNPw5ln&input=MjQ1MTI4MDI5)
[Answer]
# Ruby 2.3, 56 bytes
```
p !gets.chars.chunk_while(&:<).map{|a|eval a*?+}.uniq[1]
```
Almost certainly not the golfiest way to do this, but it shows off some nice language features.
(Not newline-tolerant, so run like `ruby dennis2.rb <<< '12012'`)
[Answer]
# PHP, 144 bytes
```
<?php preg_match_all("/0?1?2?3?4?5?6?7?8?9?/",$argv[1],$n);foreach($n[0]as$i)if(strlen($i)&&($a=array_sum(str_split($i)))!=$s=$s??$a)die;echo 1;
```
I'm sure there's a much cleverer (and shorter) way to do this but it will do for now.
[Answer]
## Python 2, 69 bytes
Takes input as a string.
```
lambda I:len(set(eval(reduce(lambda x,y:x+',+'[y>x[-1]]+y,I+' '))))<2
```
Explanation:
ex `1201212012`
Converts to list of sums:
`1+2,0+1+2,1+2,0+1+2,`
Evals and converts to set.
`set([3])`
If the length of the set is 1, all sums are the same.
[Answer]
# JavaScript (ES6), 58
```
s=>![...s,z=x=p=0].some(c=>[c>p?0:z-=(x=x||z),z-=p=c][0])
```
Applying my rarely useful tip <https://codegolf.stackexchange.com/a/49967/21348>
It scans the string char by char identifying run of ascending chars, at the end of each rum it checks if the sum is always the same
* c : current char
* p : previous char
* z : running sum, at the end of a run will be compared to ...
* x : sum to compare against, at first run is simply made equal to z
**Test**
```
f=
s=>![...s,z=x=p=0].some(c=>[c>p?0:z-=(x=x||z),z-=p=c][0])
function run()
{
var i=I.value
O.textContent = i + ' -> ' + f(i)
}
run()
test=`1 2 3 4 5 6 7 8 9 11 12 13 14 15 16 17 18 19 22 23 24 25 26 27 28 29 33 34 35 36 37 38 39 44 45 46 47 48 49 55 56 57 58 59 66 67 68 69 77 78 79 88 89 99 101 111 123 124 125 126 127 128 129 134 135 136 137 138 139 145 146 147 148 149 156 157 158 159 167 168 169 178 179 189 202 222 234 235 236 237 238 239 245 246 247 248 249 256 257 258 259 267 268 269 278 279 289 303 312 333 345 346 347 348 349 356 357 358 359 367 368 369 378 379 389 404 413 444 456 457 458 459 467 468 469 478 479 489 505 514 523 555 567 568 569 578 579 589 606 615 624 666 678 679 689 707 716 725 734 777 789 808 817 826 835 888 909 918 927 936 945 999`.split` `
numerr=0
for(i=1; i<1000; i++)
{
v = i + '';
r = f(v);
ok = r == (test.indexOf(v) >= 0)
if (!ok) console.log('Error',++numerr, v)
}
if(!numerr) console.log('All test 1..999 ok')
```
```
<input id=I value=612324 type=number oninput='run()'>
<pre id=O>
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 20 bytes
Two versions
```
!t{sMcJjQThMx1<R0.+J
LS{b!t{sMhyI#I#./jQT
```
[Try the first one online!](http://pyth.herokuapp.com/?code=%21t%7BsMcJjQThMx1%3CR0.%2BJ&test_suite=1&test_suite_input=101%0A102%0A777%0A2846145&debug=0)
[Try the second one online!](http://pyth.herokuapp.com/?code=LS%7Bb%21t%7BsMhyI%23I%23.%2FjQT&test_suite=1&test_suite_input=101%0A102%0A777%0A2846145&debug=0)
[Answer]
# Ruby, ~~117~~ ~~105~~ 85 bytes
```
# original (117):
j,k=0,?0;"#{i}".chars.group_by{|n|n>k||j=j+1;k=n;j}.values.map{|a|a.map(&:to_i).reduce(&:+)}.reduce{|m,n|n==m ?m:nil}
# inspired by PHP regexp approach (105):
"#{i}".scan(/0?1?2?3?4?5?6?7?8?9?/).map{|a|a.chars.map(&:to_i).reduce(&:+)}.reduce{|m,n|!n||n==m ?m:nil}
# some number comparison simplification (85):
!"#{i}".scan(/0?1?2?3?4?5?6?7?8?9?/).map{|a|a.chars.map(&:to_i).reduce(&:+)}.uniq[1]
```
This would return the integer of this dennis number or `nil` if not a dennis number. All integers will be considered true in ruby as well `nil` is considered false. `i` is the integer that is being check.
Third version actually returns `true` and `false`.
P.S. tested to return 172 integers from 1 to 1000 as in the answer.
[Answer]
# APL, 23 bytes
```
{1=≢∪+/↑N⊂⍨1,2>/N←⍎¨⍕⍵}
```
Explanation:
* `N←⍎¨⍕⍵`: get the individual digits in the input, store in `N`
* `N⊂⍨1,2>/N`: find the sublists of strictly increasing numbers in `N`
* `+/‚Üë`: sum each sublist
* `1=≢∪`: see if the resulting list has only one unique element
[Answer]
# [Add++](https://github.com/cairdcoinheringaahing/AddPlusPlus), 109 bytes
```
D,g,@@#,BF1_B
D,k,@@#,bR$d@$!Q@BFB
D,f,@,BDdVÑ_€?1€_0b]$+€?dbLRBcB*BZB]GbL1+b]+qG€gd€bLÑ_0b]$+BcB]£k€¦+Ñ=1$ª=
```
[Try it online!](https://tio.run/##TY7fasIwGMWvm6fousDAhtHUP9sKupAVZSDIvPBiWDqzVKnOrGurFJw3ewOfYbCLsaeob7IXcV@KDG9OzvfL@XIykTJJDgefzAhj54R3aciRTxbVJIZYMnz2wHhXwylhhPtytN@Fvx8/txQkdESAbT1J0R/yZ17jjzzoiT61RWC/9eBmJkFEH5aqLGSC8nMBrPyy97s2xeV3G/qzPIXnkWFdWJLN1wj6lpNYEeYBlJvpFhl4A6HtUQGOsC6i4XvdvavNEcJ6oUPdeuvfOtQ9eve60aKN5kmodeqbV/UbhArPGis/UirOTPfSMdVqKaI0M1eJmb@a1HEcb6wsNCgQeomXce5phLqVh2/GSkaFF4N7SiMN8LRTMbD3msBpDCpy@AM "Add++ – Try It Online")
## How it works
We define our 3 functions, \$f\$, \$g\$ and \$k\$. \$f\$ is the main function, which transforms the input to the correct output.
### \$f(x)\$
First, we convert the input \$x\$ into a list of digits, then take the forward increments. Next, we take the sign of each increment. For increasing subsequences, this yields a subsequence of \$1\$, for equal subsequences, such as \$[4, 4, 4]\$, this yields \$0\$s and for decreasing sections, \$-1\$ is returned. We then take the complement of each of these signs, to turn \$1\$ into a falsey value, and everything else into a truthy value. Next, \$0\$ is prepended to this array, and we take the sign of each element again. This yields an array, \$A\$, of \$0\$ and \$1\$, with the first element always being \$0\$.
We then yield the range \$[1, 2, ... length(A)]\$ and remove the elements that correspond to \$0\$ in \$A\$. This leaves us with a second array, \$A'\$. We then push the number of digits in the input, add one and append this number to \$A'\$. We then deduplicate \$A'\$, to yield a new array, \$A''\$.
Next, we use the \$g\$ helper function. As \$g\$ is dyadic (takes 2 arguments), it behaves slightly differently when paired with the *each* operator, `€`. Dyadic functions pop a value from the stack and bind that value as their right argument to create a partial monadic function. This partial function is then mapped over each element in the argument. Here, the bound right argument is the digits of the input and the partial function is mapped over \$A''\$.
### \$g(x, y)\$
Let's take a look at just one iteration of \$g(x, y)\$ where \$x := [1, 2, 0, 1, 2]\$ and \$y = 3\$. Note that \$3\$ is the first index in \$A''\$ where the signs from \$A\$ corresponded with \$1\$, rather than \$0\$. In fact, for \$x = 12012\$, we can see that \$A'' = [3, 6]\$. \$3\$ is the only non-zero index in \$A\$, and \$6\$ is the length of \$x\$ plus one.
So, for \$g([1, 2, 0, 1, 2], 3)\$ the following happens: First, we swap the two arguments so that the stack has the digits below the index. We then flatten the array and decrement the index. So far, the stack looks like `[1 2 0 1 2 2]`. We then perform the *head* command. We pop the index from the top f the stack and take that many characters from the stack, starting at the bottom. This yields \$[1, 2]\$, which is then returned by \$g\$.
So, \$g(x, y)\$ is mapped over each element \$y \in A''\$, which returns a series of prefixes of the input of various increasing lengths. This part could get slightly confusing, so we'll work through it with the example input of \$x := 12012\$. After the mapping of \$g\$, the stack currently looks like
```
[[[1 2] [1 2 0 1 2]]]
```
We then push an array containing the length of each array in the top element, or in this instance, the array \$[2, 5]\$. This is the same as \$A'' - 1\$, if the \$-\$ operator maps, but it takes more bytes to use this relationship. Next, the forward differences of the lengths is taken, and \$0\$ is prepended, yielding, in this example, \$[0, 3]\$. This new array is then zipped with the results from \$g\$ to create \$B\$ and the *starmap* operator is run over each pair.
### \$k(x, n)\$
The *starmap* operator uses the function \$k\$ as its argument, and works by taking a dyadic function and a nested array. The array must consist of pairs, such as \$[[1, 2], [3, 4], [5, 6]]\$, and the dyadic function is mapped over each pair, with each element of the pairs being the left and right arguments respectively.
Here, our example nested array is \$[[[1, 2], 0], [[1, 2, 0, 1, 2], 3]]\$ and our function is \$k\$. We'll focus simply on \$k([1, 2, 0, 1, 2], 3)\$ for now.
\$k(x, n)\$ starts, similar to \$g\$, by swapping the two arguments, so that the array is the top of the stack. We then reverse the array and swap the arguments back. Now, \$n = 0\$, we want to leave the array unchanged, so we duplicate the integer and rotate the top three arguments, so that the stack has the format of \$[n, x, n]\$. Next, we return the array if \$n = 0\$. Otherwise, the top element is discarded, and we arrange the stack back to how it was i.e. with the reversed array at the bottom and the integer at the top, or in our example: \$[[2, 1, 0, 1, 2], 3]\$. We then flatten the stack, and take the first \$n\$ elements of \$x\$. These elements are then returned and replace \$x\$ in \$B\$.
For our input, this returns \$[0, 1, 2]\$. (Strictly speaking, it returns\$[2, 1, 0]\$, but order doesn't matter for the rest of the program).
After \$k(x, n)\$ is mapped over each pair \$(x, n) \in B\$, we take the sum of each pair, then check that each element is equal, by asserting that each neighbouring pair are equal, and then asserting that each of those equality tests result in \$1\$ (a truthy value). Finally, this result is returned.
] |
[Question]
[
Write a program that takes in an integer N via stdin or the command line.
If N is 0, the single letter `O` must be printed to stdout.
---
If N is *positive*, this **horizontal** ASCII art [double helix](http://en.wikipedia.org/wiki/Nucleic_acid_double_helix), drawn N segments wide, must be printed.
If N is 1, the output is:
```
/\
O O
\/
```
If N is 2, the output is:
```
/\ /\
O / O
\/ \/
```
If N is 3, the output is:
```
/\ /\ /\
O / / O
\/ \/ \/
```
If N is 4, the output is:
```
/\ /\ /\ /\
O / / / O
\/ \/ \/ \/
```
The pattern continues in the exact same way for larger N. Note that forward slash (`/`) must be used in all places the helixes cross, except for the `O` ends.
---
If N is *negative*, this **vertical** ASCII art double helix, drawn -N segments tall, must be printed.
If N is -1, the output is:
```
O
/ \
\ /
O
```
If N is -2, the output is:
```
O
/ \
\ /
\
/ \
\ /
O
```
If N is -3, the output is:
```
O
/ \
\ /
\
/ \
\ /
\
/ \
\ /
O
```
If N is -4, the output is:
```
O
/ \
\ /
\
/ \
\ /
\
/ \
\ /
\
/ \
\ /
O
```
The pattern continues in the exact same way for smaller N. Note that backward slashes (`\`) must be used in all places the helixes cross, except for the `O` ends.
**Details**
* Instead of a program, you may write a function that takes N as an integer and prints the result normally or returns it as a string.
* The output for any N may optionally contain a trailing newline.
* Any line of output for any N may optionally contain 4 or fewer trailing spaces.
* There should never be any leading space that aren't part of the specified pattern.
* **The shortest code in bytes wins.**
[Answer]
# CJam, ~~56 55 53 52~~ 50 bytes
```
S'O:Ori:X0>"\/"=" / \\\ / "+Xz*1>O]s3/X"z"<~N*X\O?
```
Look at that size! The main culprits are `N = 0` special case and the `\` instead of `/` in the vertical helix.
Here is how it works:
```
S'O:O e# Put a space on stack. Now put char O on stack
e# and assign it to variable O. This is not really
e# helping in golfing as using 'O everywhere is
e# same number of bytes
ri:X e# Read input as in integer and store it in X
0>"\/"= e# If X is greater than 0, choose /, otherwise \
" / \\\ / " e# Put this string on stack
+ e# Append to chosen \ or /
Xz* e# Repeat it abs(X) times
1> e# Remove the first character from repeated string
O] e# Put char O on stack, wrap everything in an array
e# and convert it to string.
3/ e# Split the string into parts of length 3
X"z"<~ e# If X is positive, transpose the array to get a
e# horizontal helix, otherwise it would be vertical
N* e# Join the parts with newline
X\O? e# If X was 0, then pick char O instead of this
e# final joined string.
```
The code is divided into three parts:
* The part `X0>"\/"=" / \\\ / "+` gives either `"/ / \\\ / "` or `"\ / \\\ / "` which is crucial as the helix is simply made up of alternate `"/ \"` and `"\ /"` joined by either `" / "` or `" \ "`. For instance, if you consider input to be `2`, then your final repeated string would be `"/ / \\ / / / \\ / "` (without escaping). This obviously has extra `/` at the beginning and an extra space at the ending.
* Second part is to correct the above string with additional things and split. For an input `2`, the desired final string without newlines would be `" O / \\\ / / / \\\ / O"`, but after the above point, we only have `"/ / \\\ / / / \\\ / "`. So we remove the first character, add a space and `'O` at the beginning and another `'O` at the end. Then we finally split it into parts of 3
* Finally, we decide whether to transpose this split string for a vertical helix or not; Join the parts by newlines; And choose between this and a single character `'O` (for input 0 case)
[Try it online here](http://cjam.aditsu.net/#code=S%27O%3AOri%3AX0%3E%22%5C%2F%22%3D%22%20%2F%20%5C%5C%5C%20%2F%20%22%2BXz*1%3EO%5Ds3%2FX%22z%22%3C%7EN*X%5CO%3F&input=-3)
[Answer]
# JavaScript(ES6), 126 ~~132 133~~
```
A=n=>(F=(f,j='')=>f+(j+f).repeat(n-1),n>0?F(' /\\')+`
o${F(' ','/')}o
`+F(' \\/'):(n=-n)?` o${F(`
/ \\
\\ /
`,' \\')} o`:'o')
// Test
for(i=0;i<10;i++)
P.innerHTML = P.innerHTML + A(i)+'\n\n\n',
N.innerHTML = N.innerHTML + A(-i)+'\n\n\n'
```
```
pre {
font-size: 10px;
line-height: 9px;
}
```
```
<table>
<tr><th>Positive</th><th>Negative</th></tr>
<tr><td valign=top><pre id=P></pre></td><td><pre id=N></pre></td></tr>
</table>
```
Using templated string, newlines count.
**More readable**
```
A=n=>(
F=(f,j='')=>f+(j+f).repeat(n-1),
n > 0 ? F(' /\\') + '\no' + F(' ','/') + 'o\n'+F(' \\/')
: (n=-n) ? ' o' + F('\n/ \\\n\\ /\n',' \\')'+' o':'o'
)
```
[Answer]
# Pyth, 52 bytes
```
M[Jj"/\\"*hGdjP*G+*2dH*2\O_J)?jb?gQ\/>Q0msdCg_Q\\Q\O
```
[Demonstration.](https://pyth.herokuapp.com/?code=M%5BJj%22%2F%5C%5C%22*hGdjP*G%2B*2dH*2%5CO_J)%3Fjb%3FgQ%5C%2F%3EQ0msdCg_Q%5C%5CQ%5CO&input=-4&debug=0)
Explanation:
The first section, `M[Jj"/\\"*hGdjP*G+*2dH*2\O_J)`, defines a function, `g`, which takes two inputs. The first input, `G`, is the number of repetions to use. This is the absolute value of the input. The second input, `H`, is the character to place at the center of the spirals.
The function returns a 3 element list, which consists of the 3 lines of the positive spiral, and the 3 columns of the negative spiral.
The first element is defined by `Jj"/\\"*hGd`. `*hGd` is the string of `G+1` spaces. `j"/\\"*hGd` joins that string with `"/\"` as the delimeter. The `J` at the beginning saves the resultant value for future use.
The second element is `jP*G+*2dH*2\O`. We start with `+*2dH`. This is two spaces followed by the input character. Then, we repeat that string `G` times with `*G`. Then, we remove its final character with `P`. Finally, we surround this string with two `O` characters, with `j ... *2\O`.
The third element is generated with `_J`. This is simply the reverse of the first line.
The latter section, `?jb?gQ\/>Q0msdCg_Q\\Q\O` selects between three different posibilities, positive, negative and zero. The first if-then conditions on `Q`, the input. The second conditions on `>Q0`, whether the input is positive.
If `Q` is zero, `\O`, the character `O`, is printed.
If `Q` is nonzero, we join the result of the second ternary on newlines and print it, with `jb`. If `Q` is positive, the list joined and printed is `gQ\/`, `g(Q,"/")`.
If `Q` is negative, the list joined and printed is `msdCg_Q\\`. We start with `g_Q\\`, which is `g(-Q,"\")`. Then we transpose the rows and columns with `C`. `msd` turns the resultant tuples of characters into strings, ready to be joined on newlines and printed.
[Answer]
## Python 2, 118
```
n=input()
a=[' O '[n==0:]]+['/ \\','\\ /',' /\\ '[n<0::2]]*abs(n)
a[-1]=a[0]
for x in[a,zip(*a)][n>0]:print''.join(x)
```
Creates the vertical double helix from a list of strings and transposes it to get the horizontal one. I'm sure it could be improved.
[Answer]
# Java, ~~500~~ 488 bytes
My first try, and unfortunately it is 10\* longer than the current leader :(. Anyone have any tips (other than use a different language)?
```
import java.util.*;class t{public static void main(String[] args){Scanner sc=new Scanner(System.in);int n=Integer.parseInt(sc.nextLine());if(n>0){for(int i=0;i<n;i++)System.out.print(" /\\");o("");System.out.print('o');for(int i=0;i<n-1;i++)System.out.print(" /");o(" o");for(int i=0;i<n;i++)System.out.print(" \\/");}else if(n<0){o(" o ");for(int i=0;i<-n-1;i++){o("/ \\");o("\\ /");o(" \\ ");}o("/ \\");o("\\ /");o(" o ");}else o("o");}static void o(String s){System.out.println(s);}}
```
[Answer]
# Haskell, 156 bytes
```
h 0="O"
h n|n>0=' ':c n "/\\ "++"\nO"++c(n-1)" /"++" O\n "++c n "\\/ "
|0<1=" O\n/ \\\n"++c(-n-1)"\\ /\n \\\n/ \\\n"++"\\ /\n O"
c x=concat.replicate x
```
You can then write it as:
```
*Main> putStrLn $ h 1
/\
O O
\/
*Main> putStrLn $ h 0
O
*Main> putStrLn $ h (-1)
O
/ \
\ /
O
*Main> putStrLn $ h 3
/\ /\ /\
O / / O
\/ \/ \/
*Main> putStrLn $ h (-3)
O
/ \
\ /
\
/ \
\ /
\
/ \
\ /
O
*Main>
```
[Answer]
# C#, ~~242~~ ~~241~~ ~~238~~ ~~230~~ ~~222~~ 219 Bytes
Spurred on by [Martin's comment](https://codegolf.stackexchange.com/questions/49962/draw-an-ascii-double-helix/50030#comment118075_50019), here's my first attempt at something like this:
```
string h(int n){int x=0;string p="",r=n==0?"O":p;if(n>0){for(;x++<n;){r+=" /\\";p+=" \\/";}r+="\nO ";for(;x-->2;)r+="/ ";r+="O\n"+p;}else if(n<0){r+=@" O
/ \
";for(--x;x-->n;)r+=@"\ /
\
/ \
";r+=@"\ /
O";}return r;}
```
More readably:
```
string h(int n)
{
int x = 0;
string p = "",
r = n==0 ? "O" : p;
if (n > 0) {
for (; x++ < n;) {
r += " /\\";
p += " \\/";
}
r += "\nO ";
for (; x-- > 2;) r += "/ ";
r += "O\n" + p;
}
else if(n<0) {
r += @" O
/ \
";
for (--x; x-- > n;) r += @"\ /
\
/ \
";
r += @"\ /
O";
}
return r;
}
```
[Answer]
# C# ~~199~~ ~~197~~ 196 bytes
```
string f(int n){var u=n<0;int m=u?-n:n;string a="",b=" O ";for(;m-->0;)b+="\n/ \\\n\\ /\n "+(m==0?"O ":u?"\\ ":"/ ");for(;++m<3;)a+=string.Concat(b.Split('\n').Select(s=>s[m]))+"\n";return u?b:a;}
```
Ungolfed version:
```
string f(int n)
{
var u = n < 0;
int m = u ? -n : n;
string a = "", b = " O ";
for (; m-- > 0; ) b += "\n/ \\\n\\ /\n " + (m == 0 ? "O " : u ? "\\ " : "/ ");
for (; ++m < 3;) a += string.Concat(b.Split('\n').Select(s => s[m])) + "\n";
return u ? b : a;
}
```
The idea is to build the horizontal display from the vertical display by rendering the transposed matrix of characters.
[Answer]
# Python 3, 118 bytes
```
x=int(input())
print("O"if x==0else" /\\"*x+"\nO "+" / "*(x-1)+" O\n"+" \\/"*x if x>0else(" O"+"\n/ \\\n\\ /\n \\"*-x)[:-1]+"O")
```
My first ever code golf submission, so it may not be at all impressive.
Just uses Python's ... if ... else ... ternary operator to separate the three scenarios. That gives a string made of repeating some smaller strings a certain number of times to print.
[Answer]
# Julia, 229 bytes
Oh man, this is way, *way* too big. It's the longest answer so far by a large margin. I could probably save a lot by returning the string rather than printing it, or by avoiding the matrix approach altogether. I'll experiment with that later.
```
n->(if n==0 println("O")else m=abs(n);A=B=reshape(split(" / "*(n>0?"/":"\\")*" \\\\ /",""),(3,3));E=[" ";"O";" "];if m>1for i=2:m B=hcat(B,A)end end;B[:,1]=E;B=hcat(B,E);C=n>0?B:B';for i=1:size(C,1) println(join(C[i,:]))end end)
```
This creates a lambda function that takes a single integer and prints the appropriately formatted double helix. To call it, give it a name, e.g. `f=n->(...)`.
Ungolfed + explanation:
```
function f(n)
if n == 0
println("O")
else
m = abs(n)
# Split the string into a 3x3 matrix with a slash on the left,
# or a backslash for n < 0
A = B = reshape(split(" / " * (n > 0 ? "/" : "\\") * " \\\\ /", ""), (3, 3))
# We can get the O lines where needed by appending this
E = [" "; "O"; " "]
# Grow the helix by abs(n)
if m > 1
for i = 2:m
B = hcat(B, A)
end
end
# Exchange the first column for E
B[:,1] = E
# Add E onto the right
B = hcat(B, E)
# If n is negative, we actually want the transpose
C = n > 0 ? B : B'
# Print the rows of C
for i = 1:size(C, 1)
println(join(C[i,:]))
end
end
end
```
A couple examples:
```
julia> f(1)
/\
O O
\/
julia> f(-2)
O
/ \
\ /
\
/ \
\ /
O
```
[Answer]
# Python 3, 135 bytes
```
n=int(input());m=abs(n)-1;print({n:" O\n/ \\\n"+m*"\ /\n \\\n/ \\\n"+"\\ /\n O",m+1:n*" /\\"+"\nO"+" /"*m+" O\n"+" \/"*n,0:"O"}[n])
```
[Try it online here](http://repl.it/n7r)
[Answer]
# Perl, 91 ~~97~~
Transposing proved to be too expensive in the end.
```
#!perl -n
print/-/?"\0\23"^" \\
/ \\
\\ /
"x-$_." O":-$_?" /\\"x$_.("*`"^" / "x$_." O
"." \\/"x$_):O
```
Previous solution:
```
#!perl -n
$".="`"^"/
\\ /
/ \\
"x abs.O;print/-/?$"=~y!/\\!\\/!r:/^0/?O:map{($"=~/^.{$_}(.)/mg,$/)}2,1,0
```
Test [me](http://ideone.com/hXbrKl).
[Answer]
# Scheme, 379 bytes
My first attempt at code golf and, unfortunately, one of the longest ones. :(
```
(define (h i) (define a string-append) (define (k n p q s e) (cond ((= i n) (p s (k (q n 1) p q s e))) ((= 0 n) e) (else (p `("\\ /" ,(if (> i 0) " / " " \\") "/ \\") (k (q n 1) p q s e))))) (if (= i 0) "O\n" (apply a (map (lambda (s) (a s "\n")) (if (> i 0) (k i (lambda (x y) (map a x y)) - '(" /" "O " " \\") '("\\" " O" "/")) (k i append + '(" O" "/ \\") '("\\ /" " O")))))))
```
Ungolfified:
```
(define (h i)
(define a string-append)
(define (k n p q s e)
(cond ((= i n) (p s (k (q n 1) p q s e)))
((= 0 n) e)
(else (p `("\\ /" ,(if (> i 0) " / " " \\") "/ \\")
(k (q n 1) p q s e)))))
(if (= i 0) "O\n"
(apply a (map (lambda (s) (a s "\n"))
(if (> i 0)
(k i (lambda (x y) (map a x y)) -
'(" /" "O " " \\")
'("\\" " O" "/"))
(k i append +
'(" O" "/ \\")
'("\\ /" " O")))))))
```
[Answer]
## Java, 282
My first approach, with particularly nice variable names:
```
class H{public static void main(String[]_){int N=Integer.parseInt(_[0]),í=N;String ì="/ \\\n\\ /\n",I=" o \n",i="",l=I;for(;í-->0;)i+=" /\\";i+="\no";for(í=N;í-->1;)i+=" /";i+=" o\n";for(í=N;í-->0;)i+=" \\/";for(í=1;í++<-N;)l+=ì+" \\ \n";System.out.println(N<0?l+ì+I:N>0?i:"o");}}
```
I have no idea why I am doing this. Must be some recreational thing.
[Answer]
## Java, 317
My first code golf attempt.
```
public class t{public static void main(String[]e){int n=Integer.parseInt(e[0]);String s=new String(new char[n==0?0:(n>0?n:-n)-1]),u="\0";System.out.print(n==0?"O":n>0?s.replace(u," /\\")+" /\\\nO"+s.replace(u," /")+" O\n"+s.replace(u," \\/")+" \\/":" O \n/ \\\n"+s.replace(u,"\\ /\n \\ \n/ \\\n")+"\\ /\n O \n");}}
```
[Answer]
# Python 3, 165 bytes
```
x,a,b,c,d=int(input())-1,'\ /',' / ','/ \\','\ /\n \\\n/ \\\n'
print([[' O\n/ \\\n'+d*abs(x+2)+'\ /\n O',' /'+a*x+'\\\nO '+b*x+' O\n \\'+c*x+'/'],'OO'][x==-1][x>-1])
```
Try it online [here](http://repl.it/n0o).
[Answer]
# Perl, ~~193~~ ~~197~~ ~~187~~ ~~180~~ ~~166~~ 163B
1 byte penalty for -n commandline switch. Run with `echo 1|perl -M5.10.0 -n scratch.pl`:
```
$_*=3;$s=($m=abs)==$_;$_?map{say if$_=join'',map{(map[/./g]," O ",(('/ \\', '\\ /',$s?' / ':' \\ ')x$m)[0..$m-2]," O")[$s?$_:$j][$s?$j:$_]}0..$m;$j++}0..$m:say'O'
```
With whitespace:
```
$_ *= 3;
$s = ($m = abs) == $_;
$_ ? map{
say if $_=join '', map {
( map[/./g],
" O ",
(('/ \\', '\\ /',$s?' / ':' \\ ') x $m)[0..$m-2],
" O"
)[$s ? $_ : $j][$s ? $j : $_]
}0..$m;
$j++
} 0..$m
: say 'O'
```
[Answer]
# PHP, 341
```
$s='';$n=$argv[1];$l=PHP_EOL;if($n>0){for($i=0;$i<$n;$i++)$s.=" /\\";$s.=$l;for($i=0;$i<$n;$i++){if($i==0)$s.='o';if($i<$n-1)$s.=' /';if($i==$n-1)$s.=' o';}$s.=$l;for($i=0;$i<$n;$i++)$s.=" \\/";}else{$n=abs($n);for($i=0;$i<$n;$i++){if($i== 0)$s.=' o '.$l;$s.="/ \\".$l."\\ /".$l;if($i < $n-1)$s.=' \\ '.$l;if($i==$n-1)$s.=' o '.$l;}}echo $s;
```
Ungolfed version
```
$s = '';
$n = $argv[1];
echo PHP_EOL;
if($n > 0)
{
for($i=0;$i<$n;$i++)
{
$s.=" /\\";
}
$s.=PHP_EOL;
for($i=0;$i<$n;$i++)
{
if($i==0) {
$s.='o';
}
if($i < $n-1) {
$s.=' /';
}
if( $i == $n-1)
{
$s.=' o';
}
}
$s.=PHP_EOL;
for($i=0;$i<$n;$i++)
{
$s.=" \\/";
}
} else
{
$n = abs($n);
for($i=0;$i<$n;$i++)
{
if($i == 0) {
$s.=' o '.PHP_EOL;
}
$s.="/ \\".PHP_EOL."\\ /".PHP_EOL;
if($i < $n-1) {
$s.=' \\ '.PHP_EOL;
}
if( $i == $n-1) {
$s.=' o '.PHP_EOL;
}
}
}
echo $s;
```
[Answer]
# JAVA 377 ~~384~~ bytes
```
class F{public static void main(String[] a){int n=Integer.parseInt(a[0]);if(n>0){for(int i=0;i<n;i++)p(" /\\");p("\n");for(int i=0;i<n;i++){if(i==0)if(n>1)p("O ");else p("O O");else if(i==n-1)p("/ O");else p("/ ");}p("\n");for(int i=0;i<n;i++){p(" \\/");}}else{p(" O\n");for(int i=0;i<Math.abs(n);i++){p("/ \\\n\\ /\n O\n");}}}static void p(String s){System.out.print(s);}}
```
[Answer]
# C++ ~~269~~ ~~262~~ 258
```
#include <string>
#include <iostream>
int main(){int i,j;std::cin>>i;std::string s,u,t;if(i>0){for(j=i;j;j--){s+=" /\\";t+="/ ";u+=" \\/";}t[0]='O';t+="O";s=s+'\n'+t+'\n'+u;}else{for(j=i;j;j++)s+=" \\\n/ \\\n\\ /\n";s[1]='O';s+=" O";}std::cout<<(i==0?"O":s);}
```
[Answer]
# R, ~~228~~ 201
```
n=scan();z=cat;f=`for`;if(!n)z("O");if(n>0){f(i,1:n,z(" /\\"));z("\nO ");if(n>1)f(i,2:n,z("/ "));z("O\n");f(i,1:n,z(" \\/"))};if(n<0){z(" O\n");f(i,-n:1,{z("/ \\\n\\ /\n ");if(i>1)z("\\\n")});z("O")}
```
My first attempt at code golf. I think it works but it is not subtle.
```
n=scan(); # enter number here
z=cat;
if(!n) z("O\n");
if(n>0){
z(" ");
for(i in 1:n) z("/\\ ");
z("\nO");
if(n>1){
for(i in 2:n) z(" /")
};
z(" O\n ");
for(i in 1:n) z("\\/ ")
};
if(n<0){
z(" O \n");
for(i in -n:1){
z("/ \\\n\\ /");
if(i>1) z("\n \\\n")
};
z("\n O ")
}
```
[Answer]
# Groovy, ~~142~~ ~~134~~ ~~129~~ ~~125~~ ~~120~~ 118
```
a=args[0]as int;b="\n/ \\\n\\ /\n ";print!a?"O":a>0?" /\\"*a+"\nO ${"/ "*(a-1)}O\n"+" \\/"*a:" O$b${"\\$b"*(1-a)}O"
```
Finally tied with python 2!
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~28~~ ~~24~~ 22 bytes
```
↙OF↔θ/¶\¶ \¶↗‖BO¿›N⁰⟲T
```
[Try it online!](https://tio.run/##LU69CsIwEN59itDpAhVdXOqkCCL4R9EtS1outpAmNb1UfPp4VZfju/v@rm50qL22KV1D6wiKnX@5IxrKRXbJ5HpmfBCwqQZvIyE8pRQ/YbZQTinlxDQm4cmPCMW9L9tHQ7yXaCzWtI1EGIx9A9/@1m9wawTsA2pm4eD6SOfYVYxlLpbcUnpi6ha0G/iFjt0prdJ8tB8 "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
↙O
```
Print the top `O`, and leave the cursor one space down and left.
```
F↔θ/¶\¶ \¶
```
Print the strings `/`, `\` and `\` and repeat for the absolute number value of the input.
```
↗
```
Move back over the last `\`.
```
‖B
```
Reflect to create the right-hand side of the helix. I do this here because otherwise the `↗` would not parse unambiguously.
```
O
```
Overwrite the last `\` with an `O`.
```
¿›N⁰⟲T
```
If the input was positive then rotate the canvas.
[Answer]
# [Canvas](https://github.com/dzaima/Canvas), ~~33~~ ~~32~~ 30 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md)
```
/¶O:╴⤢╷\ /¶ \×+;↔+──╴0<?↷}╴‽O
```
[Try it here!](https://dzaima.github.io/Canvas/?u=JTIwLyVCNk8ldUZGMUEldTI1NzQldTI5MjIldTI1NzclNUMlMjAvJUI2JTIwJTVDJUQ3JXVGRjBCJXVGRjFCJXUyMTk0JXVGRjBCJXUyNTAwJXUyNTAwJXUyNTc0JXVGRjEwJXVGRjFDJXVGRjFGJXUyMUI3JXVGRjVEJXUyNTc0JXUyMDNETw__,i=NA__,v=0)
Explanation:
```
/¶O: push " /\¶O" twice
╴⤢╷ push the absolute value of the input, -1
\ /¶ /× repeat "\ /¶ /" horizontally that many times
+ append that horizontally to one of the first strings
; and get the other, reverse it
↔+ and then append it to the result of above. Now the top part of the helix is done
── vertically palindromize with no mirroring (works because of a misake - it just doesn't overlap smartly)
╴0<? } if the input is less than 0
↷ rotate clockwise the whole thing
╴‽ if the input is falsy (aka 0)
O push O; implicitly output the top of stack
```
[Answer]
## **C++, 352**
Not at all the shortest answer, but the first in C++ so far :)
```
#include <iostream>
int main(int argc, char* argv[]){int a=argv[0][0]-'0';if(a==0){printf("o");}else if(a>0){for(int i =0; i < a;i++){printf(" /\\");}printf("\no");for(int i=0;i<a-1;i++){printf(" /");}printf(" o\n");for(int i=0;i<a;i++){printf(" \\/");}}else{printf(" o\n/ \\\n\\ /\n");for(int i=0;i>a+1;i--){printf("/ \\\n\\ /\n");}printf(" o");};}
```
[Here it is](http://cpp.sh/7qjr) in C++ Shell with whitespace to test
[Answer]
# perl 156
```
$==pop;print$=>0?' /\\'x$=.$/:'',$=>0?'O'.' /'x$=."\bO
":'',$=>0?' \\/'x$=:'';print$=<0?" O":'';print"
/ \\
\\ /
\\" for$=..-1;print$=<0?"\bO":!$=?"O":''
```
Pretty straight forward attempt, my second golf.
I think newlines count as 1 byte right?
Now to figure out how to join all those ternaries together.. I have a lot of room for improvement with those `:'';` everywhere.
[Answer]
## C, 189 bytes
```
char*h="6Er66 e66Ee 6rE66",*v="6e6 E6r r6E 6r6 6e6",*z="e",*u;b,m,w,c,p;f(n){b=n<0;u=b?v:n?h:z;for(m=b?4:1,w=n*(b?-3:3);u[p];p+=++c%((w+2)*m)==w*m?m:p%(6*m)==m*4?-m*3:0)putchar(u[p++]-22);}
```
With whitespace and newlines:
```
char *h="6Er66 e66Ee 6rE66",
*v="6e6 E6r r6E 6r6 6e6",
*z="e",
*u;
b, m, w, c, p;
f(n) {
b = n < 0;
u = b ? v : n ? h : z;
for (m = b ? 4 : 1, w = n * (b ? - 3 : 3);
u[p];
p += ++c % ((w + 2) * m) == w * m ? m : p % (6 * m ) == m * 4 ? - m * 3 : 0)
putchar(u[p++] - 22);
}
```
Some notes about the approach:
* Stores the pattern in character arrays. They are shifted by 22 characters to avoid needing a bunch of backslashes to escape special characters.
* Uses separate patterns for horizontal, vertical, and zero. I initially considered using one single pattern, and just traversing it differently for positive and negative values. I didn't implement it, but I had a feeling that it would make the logic quite a bit more complicated. Particularly since the central slash has the opposite direction for the two cases. And the tables are not that large, so this seemed more promising.
* The code is mainly just index calculations, with logic to decide when it's done and when the pattern loops. Much of the math is there so that it works for both cases with their different dimensions and repetition rules.
[Answer]
# Perl, 184 bytes
```
$n=pop;$p=$n>0;$_=' \ /'x(1+abs$n*3);$n=$p?$n*4+1:3;$_=join'
',/.{$n}/g;$r=$p?'.':'.*
';s/($r$r)$r($r)/$1$2/g;$p and s/^\S|\S$/O/gm or s/^ \S $|(?<=^ )\S|\S $/O/g;y~\\/~/\\~if$p;print;
```
I thought this was going to be a lot shorter! There are probably some simple things I can do to save a few bytes. It's been five years since I've programmed seriously in Perl!
[Answer]
# PHP, 155
```
$n=$argv[1];$r='str_repeat';$k="/ \\\n\\ /\n";echo$n>0?" /{$r('\ /',$n-1)}\\\nO{$r(' /',$n-1)} O\n \\{$r('/ \\',$n-1)}/":" O\n{$r("$k \\\n",-$n-1)}$k O";
```
[Answer]
# [J](http://jsoftware.com/), ~~67 59 55~~ 51 bytes
```
(<&0|:' O '(0},[)(3,~3*|)$' / \\'({~,7$[)0,*) ::'O'
```
[Try it online!](https://tio.run/##BcHdCYAgFAbQVb4H6apcSjEKpGZwAAWJSKSXBuhndTvnbK2sPeTSmccTAkial6OSjj@nHyUIA1IieX88i6gMawXvKVA79nqh4Nj2imxhYZBHTO0H)
] |
[Question]
[
>
> Your kindly neighbour, Doctor Tree, just gave you three magical creatures called Codémon. There's a battle tournament in the nearby town of Colorville. Are you the very best, like no one ever was?
>
>
>
## Overview
This is a battle tournament. Each player controls a team of three monsters, and the objective is to knock out (kill) the other team. There are 100 rounds, with points being awarded for wins and ties. The team with the most points wins!
## Monsters
A Codémon is a complicated little creature. There are five types (elements) to choose from, three stats, and three move slots on each.
### Types
Each Codémon is assigned *one* type. The five types are Normal, Psychic, Fire, Water, and Grass. Each has its strengths and weaknesses. Damage is based on the following chart:
![type-chart](https://i.stack.imgur.com/SNPRh.png)
The numbers are damage multipliers. For instance, Fire attacking Water has a 0.5 modifier (half damage), whereas Fire attacking Grass is doubled (2).
### Stats
Each monster has three stats that determine its battle abilities. Attack raises the damage it does. Defense lowers the damage it takes. Speed allows it to move before those with lower Speed.
Each monster has a starting value of 50 for each stat, and a maximum of 100. When you create your monsters, you will be able to assign **80** additional stat points (each). Remember that no individual stat can go over 100. So, you could have a 100/80/50, 90/80/60, or 65/65/100 distribution, but 120/50/60 is illegal. Any team with illegal stats is disqualified. You are not *required* to use all 80 points, but you probably shouldn't go with the minimum 50/50/50.
You could also consider HP a stat, but each Codémon has a non-modifiable 100 HP. When HP drops to zero, they are unable to continue fighting. HP is refilled to 100 before each battle.
### Moves
Each monster knows three battle moves. The three chosen must be distinct, so no Punch/Punch/Punch.
There are 15 moves, three of each type. Each type has a direct attack, a weaker attack with an effect, and a sole effect move.
```
id name type power uses usable effect
0 Punch N 20 - NFWG
1 Heal N 0 3 NFWG Heals 50 HP
2 Slow N 10 5 NFWG Enemy speed x0.8
3 Pain P 20 - PFWG
4 Sleep P 0 3 PFWG No enemy action until wake
5 Weaken P 10 5 PFWG Enemy Atk x0.8
6 Fireball F 20 - NPFW
7 Burn F 0 3 NPFW Enemy -10 HP each turn
8 Sharpen F 10 5 NPFW Own Atk x1.25
9 Watergun W 20 - NPWG
10 Confuse W 0 3 NPWG Enemy may strike itself (10 power)
11 Shield W 10 5 NPWG Own Def x1.25
12 Vine G 20 - NPFG
13 Poison G 0 3 NPFG Enemy -5xTurns HP each turn
14 Sap G 10 5 NPFG Enemy Def x0.8
```
`type` refers to the type of the move. `power` is its striking power. `uses` indicates how many times it can be used per battle (`-` is unlimited). `usable` shows what types it can be used by (for example, Punch cannot be given to a Psychic type, as there is no `P`). `effect` shows what effects the moves have. There is a 75% chance of each effect working, except Heal, which always works.
For effects that change a monster's stats, **effects may be stacked**. For example, using Weaken twice may lower your opponent's attack to 0.64 effectiveness. Effects that do not change a monster's stats (Sleep, Burn, etc) **do not stack**.
**Sleep** puts the opponent to sleep, with a 60% chance of waking at the start of each turn. No action will be taken by sleeping monsters.
**Burn** damages the opponent 10 HP at the end of each turn *when active*. **Poison** works similarly, but takes an increasing amount each turn. On the first turn, it's 5, and it gains 5 each turn thereafter. So, by the fourth turn, it will be damaging for 20. These are flat damages, not affected by the monster's type or subject to bonuses.
**Confusion** may make a monster attack itself instead of doing what it was told to do. This attack has power 10, and has a 30% chance of happening on a given turn.
To be clear, effects last until end of battle (except Sleep, as noted above).
Moves also receive a 20% boost in power if used by a monster of the corresponding type. For example, a Grass monster using Vine is boosted, while using Punch he is not.
### Secret Stats
The stats and type (but *not* moves) of each monster is public knowledge. Your opponents will be able to see what they're fighting, in order to choose the best action. However, there are also bonuses available that are hidden.
Specifically, after every **two** battles, you will be given one "bonus" stat point for each monster on your team. Points are given to *all* monsters, dead or alive, winner or loser. You can assign this to whichever of the three stats you choose. You cannot stack them on a single monster; each monster gets *one* each time. **These points are immune to the 100 limit.** Since there will be 100 battle rounds, this means you can get a single stat up to 149 if you allot all your bonuses to it. Again, the opponent will only see your "base" stats, so the farther into the tournament you are, the further their knowledge diverges from the truth.
## Battle
Battle takes place between teams of three, with one active on each team at a time. At the start, you will be shown the opponent's team and asked to choose which monster will be your first "active" player.
After that, turns take place with the following steps:
* Switch : *Mandatory* monster switches take place (if any)
* Choose battle action
* Switch : Any *optional* monster switches (chosen as battle action) take place
* Sleep Check : Chance to wake from sleep
* Attack 1 : If able, the speedier monster uses its selected move
* Attack 2 : If able, the other monster uses its selected move
* Effect damage : Apply burn/poison damage to living monsters
"Speedier" means the monster with the higher speed. If both speed stats are the same, it is chosen by PRNG coin flip each turn.
At the end of any turn where your active monster dies, you will be asked to choose a new active. You may *also* choose to switch active monsters *as your move* for any turn (provided you have more than one alive). Again, if you switch as your move, you will not make a battle move that turn.
Monsters are not "processed" when inactive. This means they take no burn/poison damage, poison counters won't accumulate, no wake from sleep, etc. **No effects are removed or changed when switching**. This isn't that *other* monster battling game. If you switch out with attack raised and burned, they'll still be there when you switch back in.
Effect damage takes place whether you kill your active opponent or not. In this way, members of both teams may die on a single turn.
When one team runs out of usable monsters, they lose. If both teams run out on the same turn, it's a tie. If the battle lasts for 1000 turns, it's a tie.
The formula to determine damage is:
```
floor((effAttack / effDefense) * movePower * typeMultiplier * moveBoost)
```
`effAttack` and `effDefense` are the *effective* stats for the monsters. Effective attack is obtained by adding Attack and Bonus Attack, then multiplying (by 0.8 or 1.25) if any effects alter it. Remember that these effects can stack.
Damage can only be 0 when the type modifier is 0 (Normal <--> Psychic) or the move's Power is 0 (Heal, Burn, etc). Otherwise the minimum is enforced at 1.
## Tournament
Tournaments last for 100 rounds. In each round, the teams are shuffled and paired against each other randomly. If there are an odd number of teams, the leftover receives a bye (scores as a tie). Winning a battle earns the team **2** points, ties are worth **1**, and losses nothing. The team with the most points at the end wins!
If teams are tied, a tournament with only the teams tied for first place will take place to determine tiebreaker order.
# Protocol
The controller will send your program one of four commands. The first character determines the command type, with data following if necessary.
Your program will accept the command as an argument, and will respond on STDOUT within **one second**. Do not stay alive listening to STDIN, it won't be there. Each command will spawn a new process.
You may write data/state to disk. Place any files in a subfolder with the same name as your team. Do not write more than 32 kilobytes of data, or you will be disqualified. Data will persist between rounds, but will be cleared between tournaments.
## Commands
### Team Data
This is sent once at the start of the tournament to register your team. Your reply should be *constant*, not different for each tournament.
**Query:**
```
T
```
**Response:**
```
name|member0|member1|member2
```
`name` is a string with your team name. Please use alphanumeric only, for ease of parsing. `memberN` is a member string, giving the details of each monster:
Member string:
```
name:typeid:attack:defense:speed:moveid0:moveid1:moveid2
```
Again, 'name' is a string, this time with this monster's name. `typeid` is its type. Type ids are in the order shown in the chart above, with Normal=0 and Grass=4.
The next three fields are your base stats. Keep in mind the limits described in the stats section above.
The last three are your monster's moves. IDs are shown in the move chart above.
An example team data reply may look like this:
```
DummyTeam|DummyA:0:50:60:70:0:1:2|DummyB:0:50:60:70:0:1:2|DummyC:0:50:60:70:0:1:2
```
Any team that sends back garbage, ill-formatted, or illegal data here will not participate until it is fixed.
### Choose Active
This is sent at the start of each battle, and when a monster dies and needs to be switched.
**Query:**
```
C#battleState
```
`battleState` shows the state of the current battle. Bear with me here, it's ugly:
```
yourTeamState#theirTeamState
```
Where `XteamState` looks like:
```
name:activeSlot|member0state|member1state|member2state
```
`activeSlot` shows which monster is currently active (0-2). The member states come in two flavors. If it's *your* team, it gives extra information. So,
*Your* memberXstate:
```
name:id:attack:defense:speed:hp:typeid:poisonedturns:moveCount0:moveCount1:moveCount2:bonusAttack:bonusDefense:bonusSpeed:effectid:effectid:effectid
```
*Their* memberXstate:
```
name:id:attack:defense:speed:hp:typeid:poisonedturns:effectid:effectid:effectid
```
`id` is simply an integer identifier you can use to keep track of monsters if you don't like using `name`.
`attack:defense:speed` are your **base** stats.
`poisonedturns` tells you how many turns you've been poisoned for.
`moveCountX` tells how many uses you have left for each move. If 0, it cannot be used. For unlimited moves, this will be negative.
`bonus(stat)` is the amount of bonus points you have assigned to each stat.
`effectid` is a variable-sized list of effects that have been applied to your monster. There will *not* be a trailing `:` on the string, whether there are active effects present or not. If there are stacked effects, they will show up as multiple effects in the list.
The effect ids are:
```
0 NONE (should not appear, internal use)
1 POISON
2 CONFUSION
3 BURN
4 SLEEP
5 HEAL (should not appear, internal use)
6 ATTACK_UP
7 ATTACK_DOWN
8 DEFENSE_UP
9 DEFENSE_DOWN
10 SPEED_DOWN
```
**Response:**
```
memberSlot
```
The only response required is a single number 0,1,2, telling which member you want to be active. *This must be a member who is able to fight.* Don't send back `1` if member 1 is dead.
### Battle Action
Each turn, you need to decide what to do.
**Query:**
```
A#battleState
```
The `battleState` here is exactly as described above.
**Response:**
To use a move, send back the slot the move is in. For example, if I assigned Punch to slot 0, sending `0` performs Punch.
To switch to another member, send the member's slot *plus ten*. So to switch to member 2, send `12`.
Anything not in [0,1,2,10,11,12] is considered invalid and will result in no action taken this turn.
### Bonus Stats
After every two battles, you receive a secret bonus point for each team member.
**Query:**
```
B#yourTeamState
```
Your team state is the same as shown above, don't make me repeat it.
**Response:**
```
stat0:stat1:stat2
```
Your response will represent what stat to increase for each team member. Attack is 0, Defense is 1, Speed is 2.
So to raise member one's speed, member two's attack, and member three's defense, you would respond with:
```
2:0:1
```
# Controller
The controller can be found on BitBucket: [https://[email protected]/Geobits/codemon.git](https://Geobits@bitbucket.org/Geobits/codemon.git)
Just toss all of the compiled class files, submissions, and players.conf in a folder and run.
The controller's main class is called `Tournament`. Usage is:
```
java Tournament [LOG_LEVEL]
```
Log levels from 0-4 give increasing information. Level 0 runs the tournament silently and just gives the results, where level 3 gives turn-by-turn commentary. Level 4 is debug output.
You can add submissions to the tournament in `players.conf` Simply add the command line string needed to run the program, one per line. Lines starting with `#` are comments.
In your post, include the command I will need to add to my `players.conf`, and any compilation steps (if required).
Included is a dummy team comprised of all Normal members with the three Normal moves. They choose moves randomly and have terrible stats. Have fun beating up on them.
# Misc Rules
* You may not read or write to any external resources (except in your own subfolder, up to 32 kB as noted above).
* Your team needs to go into the tournament "blind". That means you can't analyze other people's source to figure out what a specific team/monster will do in a given situation. You **can** analyze your opponent's moves/stats and keep track as the tournament progresses, but no hardcoding this information in.
* Do not interfere with other processes/submissions. No invoking them, using reflection to get at their data, etc. Do not mess with my computer. Just don't try it. This is at my discretion. Violators may be barred from future entry.
* Contestants are limited to a maximum of **two** entries. If you submit more, I will only score the first two submitted. If you want to revoke one, delete it.
* Entries may not exist solely to prop up other entries. Also, you may not try to indirectly disqualify other contestants (for example, using a 27M character team name to DQ players that try to write this to disk). Each submission should play to win on its own merit.
* Your program may spawn a maximum of one child process at a time (total descendants, not direct). Both the main and any child processes must terminate directly after giving output. Either way, ensure you don't go over the timeout.
* The tournament will be held on my computer running Ubuntu with an Intel i7 3770K processor.
# Results
These are the results of the current players. It's *very* close between the top contenders, and I'm thinking about bumping the number of rounds up to 500 (and adjusting the spacing of bonus points to match). Any objections, comments?
```
------- Final Results -------
158 Happy3Campers
157 LittleKid
71 InsideYourHead
68 HardenedTrio
46 BitterRivals
```
Full play-by-play results on [Google Drive](https://drive.google.com/open?id=0B73QYv2Zz0SiYkUyemFtYmxTWVE&authuser=0)
[Answer]
# Happy 3 campers - PHP
*A bunch of cowards who like to pelt the opposition with debilitating spells and watch them rot away.*
**EDIT**: Mr. Lumpy has been severely chastised and won't say no bad words anymore
---
## **Handy**Handy`Grass - atk:50 def:99 spd:81 Confuse Poison Heal`
A venomous armless beaver who likes to confuse people with problematic handshakes
---
## **Flippy**Flippy`Water - atk:50 def:99 spd:81 Confuse Burn Heal`
A bulletin board veteran with a soft spot for bore-me-silly talks and flame wars.
---
## **Nutty**Nutty`Fire - atk:50 def:99 spd:81 Burn Poison Heal`
Weapons of mass destruction are his favourite candies.
---
## **Lumpy**Lumpy`Php - lines:500 clarity:05 spd:01 Gather Guess Store`
Thanks to his nearly 2 digits IQ and phenomenal memory, Lumpy can guess enemy moves. Well, mostly.
---
## Strategy
The strategy is to have adversaries poisoned, burned and confused as soon as possible.
Sleep was not used since it seemed less powerful than the 3 spells above.
Confusion is deadly in the long run, since it reduces attacks by 30% (both damage dealing and spell casting), prevents healers from healing themselves and harms heavy hitters badly (a 50 def / 100 atk monster will inflict 20 points of damage upon itself).
Once a foe is thoroughly pasted, my campers simply watch him sizzle, rot and punch himself to death.
High defense and healing are used to mitigate incoming damage during the agony.
While my 3 campers are fighting, Lumpy the magic deer watches the enemies every move, and sometimes manages to identify them. The information is fed back to our fighters, who do their best to take advantage of it.
After defense, speed is the most important stat to boost.
Initiative is crucial for applying healing before the next blow comes.
Attack is not used at all.
## Are spells the ultimate weapon?
Spells like poison, burn and confuse escape the overall rock/paper/scissor logic of other attacks.
Once a monster is affected, it will continue losing HPs even after the spellcaster is dead. It is as if the ghost of the caster kept attacking him.
Besides, poison becomes quickly more powerful than a fully buffed-up massive attack (above 50 points after 5 turns).
A poisoned and burnt monster's life expectancy does not go beyond 8 turns, even with 3 healings.
As [Martin's bots](https://codegolf.stackexchange.com/questions/45285/cod%C3%A9mon-i-choose-you/45349#45349) seem to indicate, the game balance is pretty good.
It's basically initiative that will tip the balance between pure spellcasters and pure attackers.
## The code
**Invoke with** `php campers.php`
It's an ugly mess, but frankly the interface does not help either.
Now that a suitably agressive competition appeared, I implemented my long planned enemy moves guessing.
Analyzing attacks requires various aerobatic deductions and persistent storage of last turn state, which means full-scale war with the paranoid controller interface.
It ain't no pretty stuff and no six-legged jackrabbit either, but it does an adequate job.
```
<?php
// ============================================================================
// Game
// ============================================================================
class G {
static $code_type = array ("Normal", "Psychic", "Fire", "Water", "Grass", "?", "self");
static $code_move = array ("Punch", "Heal", "Slow", "Pain", "Sleep", "Weaken", "Fireball", "Burn", "Sharpen", "Watergun", "Confuse", "Shield", "Vine", "Poison", "Sap", "?", "self", "pass");
static $move_uses = array (1000,3,5,1000,3,5,1000,3,5,1000,3,5,1000,3,5, 2000,2000);
static $move_type = array (0,0,0,1,1,1,2,2,2,3,3,3,4,4,4, 5,5,5);
static $move_dmg = array (20,0,10,20,0,10,20,0,10,20,0,10,20,0,10, 20,10,0);
static $move_forbidden = array (1,1,1,0,0,0,4,4,4,2,2,2,3,3,3);
static $code_effect = array ("N", "Poison", "Confuse", "Burn", "Sleep", "H", "Sharpen", "Weaken", "Shield", "Sap", "Slow");
static $decode_type, $decode_move, $decode_effect;
static $damage_multiplier = array (
array (2, 0, 1, 1, 1, 0),
array (0, 2, 1, 1, 1, 0),
array (1, 1,.5, 2,.5, 0),
array (1, 1,.5,.5, 2, 0),
array (1, 1, 2,.5,.5, 0),
array (2, 2, 2, 2, 2,-1),
array (9, 9, 9, 9, 9, 9, 1));
static $atk_score = array ("Poison"=> 1002, "Confuse"=>1001, "Burn"=>1000);
static $status_field = "atk:def:spd:hp:type:Pturns";
static $all_moves, $strong_moves, $medium_moves, $effect_moves, $possible_moves;
function init()
{
self::$status_field = explode (":", self::$status_field);
foreach (array ("type", "move", "effect") as $table) self::${"decode_$table"} = array_flip (self::${"code_$table"});
foreach (self::$code_move as $c=>$m)
{
if ($m == "?") break;
self::$all_moves[] = new Move($m);
if (self::$move_uses[$c] > 5) self::$strong_moves[] = $m;
if (self::$move_uses[$c] == 5) self::$medium_moves[] = $m;
if (self::$move_uses[$c] == 3) self::$effect_moves[] = $m;
for ($type = 0 ; $type != 5 ; $type++) if ((self::$move_uses[$c] > 5) && (self::$move_forbidden[$c] != $type)) self::$possible_moves[$type][] = $m;
}
}
function __construct ($name, $team)
{
$this->turn = 0;
$this->name = $name;
$this->team = $team;
$this->results_pending = false;
}
function parse_team ($tpack, $own_team)
{
$pack = explode ("|", $tpack);
list ($name,$active) = explode (":", array_shift($pack));
if ($own_team)
{
$team = $this->team;
}
else
{
if (!isset($this->enemies[$name])) $this->enemies[$name] = new Team(array (new Monster (), new Monster (), new Monster ()));
$team = $this->foes = $this->enemies[$name];
}
$team->active = $active;
foreach ($pack as $i=>$mpack) $team->monster[$i]->parse_monster ($own_team, $mpack);
}
function choose_active ()
{
// detect start of round
$team = $this->team;
$foes = $this->foes;
foreach ($team->monster as $i=>$m) if ($m->hp > 0) $candidate[$i] = $m;
if (count ($candidate) == 3)
{
$this->results_pending = false;
$this->round++;
// reinitialize all monsters
foreach (array($team, $foes) as $t)
foreach ($t->monster as $m)
$m->start_round();
// guess initial opponent
$opponent = $foes->initial_opponent();
}
else
{
$this->analyze_last_round();
$opponent = $foes->active();
}
return $this->do_switch ($opponent);
}
function choose_attacker ($foe)
{
foreach ($this->team->monster as $i=>$m) if ($m->can_attack($foe)) $candidate[$i] = $m;
if (isset($candidate))
{
uasort ($candidate, function ($a,$b) use ($foe) { return ($a->atk_score != $b->atk_score) ? $b->atk_score - $a->atk_score : $b->life_expectancy($foe) - $a->life_expectancy($foe); });
return key($candidate);
}
return -1;
}
function do_switch ($foe)
{
$replacement = $this->choose_attacker ($foe);
if ($replacement < 0)
{
$candidate = $this->team->monster;
uasort ($candidate, function ($a,$b) use ($foe) { return $b->life_expectancy($foe) - $a->life_expectancy($foe); });
$replacement = key($candidate);
}
$this->old_own = $this->team->monster[$replacement];
$this->old_own->attack = "pass";
return $replacement;
}
function choose_action ()
{
$this->analyze_last_round();
$own = $this->team->active();
$foe = $this->foes->active();
$this->old_own = $own;
if ($own->hp <= $own->max_damage($foe) && $own->can_do ("Heal")) return $own->execute("Heal");
if ($attack = $own->can_attack($foe)) return $own->execute($attack);
if ($own->hp <= 50 && $own->can_do ("Heal")) return $own->execute("Heal");
return 10 + $this->do_switch ($foe);
}
function choose_bonus()
{
foreach ($this->team->monster as $m)
{
if ($m->spd_b == 0) { $m->spd_b++; $res[] = 2; }
else { $m->def_b++; $res[] = 1; }
}
return implode (":", $res);
}
function parse ($parts)
{
self::parse_team ($parts[1], true);
self::parse_team ($parts[2], false);
}
function analyze_last_round()
{
if ($this->results_pending)
{
$this->results_pending = false;
$foes = $this->foes;
$foe = null;
foreach ($foes->monster as $m) if ($m->hp != $m->old->hp) $foe = $m;
if ($foe === null) $foe = $foes->monster[$foes->active];
$this->old_own->guess_attack($foe);
}
}
function process ($line)
{
$parts = explode ("#", $line);
switch ($parts[0])
{
case "T": // register for tournament
echo "$this->name|$this->team";
break;
case "C": // designate active monster
$this->parse ($parts);
echo $this->choose_active();
break;
case "A": // choose round action
$this->parse ($parts);
echo $this->choose_action();
// save current state
foreach (array($this->team, $this->foes) as $t)
foreach ($t->monster as $m)
{
unset ($m->old);
$m->old = clone ($m);
}
$this->results_pending = true;
break;
case "B": // distribute stat bonus
echo $this->choose_bonus();
break;
}
}
}
G::init();
// ============================================================================
// Move
// ============================================================================
class Move {
function __construct ($move)
{
$this->register($move);
}
function register ($move)
{
$this->type = G::$decode_move[$move];
$this->reinit();
}
function reinit()
{
$this->uses = G::$move_uses[$this->type];
}
function __tostring() { return G::$code_move[$this->type]."($this->uses)"; }
}
// ============================================================================
// Monster
// ============================================================================
class Monster {
function __construct ($name="?", $type="?", $atk=100, $def=100, $spd=100, $m0="?", $m1="?", $m2="?")
{
$this->name = $name;
$this->type = G::$decode_type[$type];
$this->atk = $atk;
$this->def = $def;
$this->spd = $spd;
$this->hp = 100;
$this->move = array (new Move($m0), new Move($m1), new Move($m2));
$this->atk_b = 0;
$this->def_b = 0;
$this->spd_b = 0;
foreach (G::$code_effect as $e) $this->$e = 0;
}
function __tostring ()
{
return implode (":", array (
$this->name,
$this->type,
$this->atk,
$this->def,
$this->spd,
$this->move[0]->type,
$this->move[1]->type,
$this->move[2]->type));
}
function start_round()
{
foreach ($this->move as $m) $m->reinit();
}
function parse_monster ($own_team, $spack)
{
$pack = explode (":", $spack);
$name = array_shift ($pack); // get name
array_shift ($pack); // skip id
if ($this->name == "?") $this->name = $name; // get paranoid
else if ($this->name != $name) die ("expected $this->name, got $name");
// store updated values
foreach (G::$status_field as $var) $this->$var = array_shift ($pack);
if ($own_team)
{
foreach ($this->move as $m) $m->new_count = array_shift($pack);
$pack = array_slice ($pack, 3); // these are maintained internally
}
$var = array();
foreach ($pack as $e) @$var[G::$code_effect[$e]]++;
foreach (G::$code_effect as $e) $this->$e = @$var[$e]+0;
}
function damage_recieved ($attack, $foe=null)
{
if ($attack == "self") $foe = $this;
$a = G::$decode_move[$attack];
$type = G::$move_type[$a];
$dmg = g::$move_dmg[$a];
if ($dmg == 0) return 0;
$atk = ($foe ->atk+$foe ->atk_b) * pow (.8, ($foe ->Weaken - $foe ->Sharpen));
$def = ($this->def+$this->def_b) * pow (.8, ($this->Sap - $this->Shield ));
$boost = ($foe->type == $type) ? 1.2 : 1;
return max (floor ($dmg * $atk / $def * $boost * G::$damage_multiplier[$this->type][$type]), 1);
}
function guess_attack_from_effect ($attacks)
{
foreach ($attacks as $status) if ($this->$status != $this->old->$status) return $status;
return "?";
}
function guess_attack_from_damage ($foe, $damages)
{
$select = array();
foreach (G::$possible_moves[$foe->type] as $attack)
{
$dmg = $this->damage_recieved ($attack, $foe);
foreach ($damages as $damage) if ($damage != 0 && abs ($dmg/$damage-1) < 0.1) $select[$attack] = 1;
}
$res = array();
foreach ($select as $a=>$x) $res[] = $a;
return $res;
}
function guess_attack ($foe)
{
$attempt = G::$decode_move[$this->old->attack];
$success = ($this->old->attack == "pass");
foreach ($this->move as $m)
{
if ($m->type == $attempt)
{
if ($m->new_count == $m->uses-1)
{
$m->uses--;
$success = true;
}
break;
}
}
$possible = array();
$attack = $this->guess_attack_from_effect (array("Burn", "Confuse", "Poison", "Sleep", "Slow", "Weaken", "Sap"));
if ($attack == "?") $attack = $foe->guess_attack_from_effect (array("Sharpen", "Shield"));
if ($attack == "?")
{
$foe_damage = $this->old->hp - $this->hp - (10 * $this->Burn + 5 * $this->Pturns*$this->Poison);
if ($this->old->attack == "Heal" && $success) $foe_damage += 50;
$possible_dmg[] = $foe_damage;
//;!;if ($this->Confuse) $possible_dmg[] = $foe_damage + $this->damage_recieved ("self");
$possible = $this->guess_attack_from_damage ($foe, $possible_dmg);
if (count ($possible) == 1) $attack = $possible[0];
}
if ($attack == "?")
{
$own_damage = $foe->old->hp - $foe->hp
- (10 * $foe->Burn + 5 * $foe->Pturns*$foe->Poison)
+ $foe->damage_recieved ($this->attack);
if (abs ($own_damage/50+1) < 0.1) $attack = "Heal";
}
if ($attack != "?")
{
$type = G::$decode_move[$attack];
if ($attack != "?")
{
foreach ($foe->move as $m) if ($m->type == $type) goto found_old;
foreach ($foe->move as $m) if ($m->type == 15) { $m->register($attack); goto found_new; }
}
found_new:
found_old:
}
}
function max_damage($foe)
{
$dmg = 0;
foreach ($foe->move as $m) $dmg = max ($dmg, $this->damage_recieved (G::$code_move[$m->type], $foe));
return $dmg;
}
function expected_damage ($foe)
{
return $this->max_damage($foe) + 10 * $this->Burn + 5 * ($this->Pturns+1);
}
function life_expectancy ($foe)
{
$hp = $this->hp;
$poison = $this->Pturns;
$heal = $this->can_do ("Heal");
$dmg = $this->max_damage($foe);
for ($turn = 0 ; $hp > 0 && $turn < 10; $turn++)
{
$hp -= 10 * $this->Burn + 5 * $poison;
if ($poison > 0) $poison++;
$hp -= $dmg;
if ($hp <= 0 && $heal > 0) { $hp+=50; $heal--; }
}
return 100 * $turn + $this->hp;
}
function can_attack ($foe)
{
$attack = false;
if ($this->hp > 0)
{
if (!$foe->Poison && $this->can_do ("Poison" )) $attack = "Poison";
else if (!$foe->Confuse && $this->can_do ("Confuse")) $attack = "Confuse";
else if (!$foe->Burn && $this->can_do ("Burn" )) $attack = "Burn";
}
$this->atk_score = ($attack === false) ? 0 : G::$atk_score[$attack];
return $attack;
}
function can_do($move)
{
$type = G::$decode_move[$move];
foreach ($this->move as $m) if ($m->type == $type && $m->uses > 0) return $m->uses;
return false;
}
function execute($move)
{
$type = G::$decode_move[$move];
foreach ($this->move as $i=>$m) if ($m->type == $type)
{
if ($m->uses > 0)
{
//;!; $m->uses--;
$this->attack = $move;
}
else $this->attack = "pass";
return $i;
}
die ("$this asked to perform $move, available ".implode(",", $this->move));
}
}
// ============================================================================
// Team
// ============================================================================
class Team {
function __construct ($members)
{
$this->monster = $members;
}
function __tostring()
{
return implode ("|", $this->monster);
}
function active ()
{
return $this->monster[$this->active];
}
function initial_opponent()
{
return $this->monster[0];
}
}
// ============================================================================
// main
// ============================================================================
$input = $argv[1];
$team_name = "H3C";
$mem_file = "$team_name/memory.txt";
$trc_file = "$team_name/trace.txt";
if (!file_exists($team_name)) mkdir($team_name, 0777, true) or die ("could not create storage directory '$team_name'");
if ($input == "T") array_map('unlink', glob("$team_name/*.txt"));
if (file_exists($mem_file)) $game = unserialize (file_get_contents ($mem_file));
else
{
$team = new Team (
array (
new Monster ("Handy" , "Grass" , 50, 99, 81, "Confuse", "Poison", "Heal"),
new Monster ("Nutty" , "Fire" , 50, 99, 81, "Burn" , "Poison", "Heal"),
new Monster ("Flippy", "Water" , 50, 99, 81, "Confuse" , "Burn" , "Heal")));
$game = new G($team_name,$team);
}
$game->process ($input);
file_put_contents ($mem_file, serialize($game));
```
## Results
LittleKid is still menacing, but my trio beat his venomous freaks by a fair margin.
Martin's bots are doomed by their lack of initiative, and increasing their speed would require to lower attack, which would blunt their edge in damage dealing capacity.
The new contenders from planet JavaScript are on par with the team in a one-on-one, but they fare worse against other competitors. They actually help decreasing LittleKid's score :).
So it seems my cuddly friends remain kings of the hill - for now...
```
170 H3C
158 Nodemon
145 LittleKid
55 InsideYourHead
42 HardenedTrio
30 BitterRivals
```
[Answer]
# HardenedTrio, Python 3
Since Geobits was nice enough to give us *two* submissions, I thought I'd submit something silly for the first one :P
The party is three Codemon (Metapod1, Metapod2, Metapod3) with the same stats and moves:
* 80 attack, 100 defense, 50 speed
* Punch, Heal, Shield Harden
All bonus points are also assigned to defense.
---
```
from collections import namedtuple
import sys
BattleState = namedtuple("BattleState", ["us", "them"])
TeamState = namedtuple("TeamState", ["name", "active", "members"])
MemberState = namedtuple("MemberState", ["name", "id", "attack", "defense", "speed", "hp",
"typeid", "poisonedturns", "otherstats"])
def parse_battle_state(state):
return BattleState(*map(parse_team_state, state.split("#")))
def parse_team_state(state):
na, *members = state.split("|")
name, active = na.split(":")
return TeamState(name, int(active), list(map(parse_member_state, members)))
def parse_member_state(state):
name, id_, attack, defense, speed, hp, typeid, poisonedturns, *rest = state.split(":")
return MemberState(name, int(id_), float(attack), float(defense), float(speed),
float(hp), int(typeid), int(poisonedturns), rest)
command = sys.argv[1].strip()
if command.startswith("T"):
print("HardenedTrio|Metapod1:0:80:100:50:0:1:11|"
"Metapod2:0:80:100:50:0:1:11|Metapod3:0:80:100:50:0:1:11")
elif command.startswith("C"):
battle_state = parse_battle_state(command[2:])
for i, codemon in enumerate(battle_state.us.members):
if codemon.hp > 0:
print(i)
break
elif command.startswith("A"):
battle_state = parse_battle_state(command[2:])
current_codemon = battle_state.us.members[battle_state.us.active]
if current_codemon.hp < 50 and int(current_codemon.otherstats[1]) > 0:
print(1) # Heal up if low
elif int(current_codemon.otherstats[2]) > 0:
print(2) # Harden!
else:
print(0) # Punch!
elif command.startswith("B"):
print("1:1:1")
```
Run with
```
py -3 <filename>
```
(or with `python`/`python3` instead of `py` depending on your installation)
[Answer]
# Inside Your Head, Ruby
* **Brian**: Psychic, Attack: 100, Defence: 50, Speed: 80, Pain, Fireball, Watergun
* **Elemon1**: Psychic, Attack: 100, Defence: 50, Speed: 80, Fireball, Watergun, Vine
* **Elemon2**: Psychic, Attack: 100, Defence: 50, Speed: 80, Fireball, Watergun, Vine
```
TEAM_SPEC = "InsideYourHead"+
"|Brian:1:100:50:80:3:6:9"+
"|Elemon1:1:100:50:80:6:9:12"+
"|Elemon2:1:100:50:80:6:9:12"
def parse_battle_state request
request.map do |team_state|
state = {}
parts = team_state.split '|'
state[:active] = parts.shift.split(':')[1].to_i
state[:monsters] = parts.map do |monster_state|
monster = {}
parts = monster_state.split(':')
monster[:name] = parts[0]
monster[:hp] = parts[5].to_i
monster[:type] = parts[6].to_i
monster
end
state
end
end
request = ARGV[0].split '#'
case request.shift
when 'T'
puts TEAM_SPEC
when 'C'
battle_state = parse_battle_state request
my_state = battle_state[0]
puts my_state[:monsters].find_index {|monster| monster[:hp] > 0}
when 'A'
battle_state = parse_battle_state request
my_state, their_state = *battle_state
my_monster = my_state[:monsters][my_state[:active]]
their_monster = their_state[:monsters][their_state[:active]]
puts [1,0,1,2,0][their_monster[:type]]
when 'B'
puts '0:0:0'
end
```
Run with
```
ruby InsideYourHead.rb
```
This doesn't work very well against Manu's bot, but it beats the other three. The team and monster names are pretty random... I might change them if I come up with something better
The strategy is pretty simple: ***attack!*** All three monsters only have pure attack moves, and they choose their move based on the opponent's monster's type.
I might experiment with throwing in a Heal later.
[Answer]
# LittleKid, Java
A little kid found 3 identical codémons and trained them. They are very annoying with their heal+poison attacks. Using only normal-type codémons removes the need to pair them up against specific enemies, since poison works well against all types.
```
public class LittleKid {
public static void main(String[] args) {
if(args.length < 1){
System.out.println("Geobits says you can't do this.");
System.exit(0);
}
String[] sections = args[0].split("#");
String me, them, out = "";
switch(sections[0]){
case "T":
out = "LittleKid";
out += "|Poisoner:0:80:100:50:0:1:13";
out += "|Poisoner:0:80:100:50:0:1:13";
out += "|Poisoner:0:80:100:50:0:1:13";
break;
case "B":
out = "1:1:1";
break;
case "C":
me = sections[1];
them = sections[2];
int pick = 0;
if(!isAlive(me, pick)){
for(int i=0;i<3;i++){
if(isAlive(me,i))
pick = i;
}
}
out = String.valueOf(pick);
break;
case "A":
me = sections[1];
them = sections[2];
int active = getActive(me);
int enemyActive = getActive(them);
if (getField(me, HP, active) < 50 && getField(me, MOVE1, active) != 0) {
out = "1";
} else if (getEffectCount(them, POISON, enemyActive, false) < 1 && getField(me, MOVE2, active) != 0) {
out = "2";
} else {
out = "0";
}
break;
default:
out = "Invalid query from controller.";
}
System.out.println(out);
}
static boolean isAlive(String teamState, int who){
return getField(teamState, HP, who) > 0;
}
static int getActive(String teamState){
return Integer.parseInt(teamState.split("\\|")[0].split(":")[1]);
}
static int getField(String teamState, int field, int who){
String[] fields = teamState.split("\\|")[who+1].split(":");
return Integer.parseInt(fields[field]);
}
static int getEffectCount(String teamState, int effect, int who, boolean mine){
String[] fields = teamState.split("\\|")[who+1].split(":");
int count = 0;
for(int i=mine?14:8;i<fields.length;i++){
if(Integer.parseInt(fields[i]) == effect)
count++;
}
return count;
}
final static int ID = 1;
final static int ATTACK = 2;
final static int DEFENSE = 3;
final static int SPEED = 4;
final static int HP = 5;
final static int TYPE = 6;
final static int MOVE0 = 8;
final static int MOVE1 = 9;
final static int MOVE2 = 10;
final static int POISON = 1;
}
```
[Answer]
# Nodémon - Javascript
Since status appears to be the dominant strategy, this team focuses on speed to get statuses like poison and confusion onto the opponents first, and then stalls out with heal and/or sleep while the opponent wastes away.
I don't have PHP installed so this isn't tested against the Campers, but it seems to be a decent competitor for LittleKid in my trials (and decimates Bitter Rivals).
```
/*jshint node:true*/
'use strict';
var fs = require('fs');
var dataFile = 'Nodemon/data.json';
function getData(callback) {
fs.readFile(dataFile, 'utf8', function(err, contents) {
var data = {round: 0};
if(!err) {
data = JSON.parse(contents);
}
callback(data);
});
}
function saveData(data, callback) {
fs.mkdir('Nodemon', function() {
fs.writeFile(dataFile, JSON.stringify(data), callback);
});
}
var effect = {
poison: '1',
confusion: '2',
burn: '3',
sleep: '4',
heal: '5',
attackUp: '6',
attackDown: '7',
defenseUp: '8',
defenseDown: '9',
speedDown: '10'
};
function parseMemberCommon(args) {
return {
name: args[0],
id: args[1],
baseAttack: +args[2],
baseDefense: +args[3],
baseSpeed: +args[4],
hp: +args[5],
typeId: args[6],
poisonedTurns: +args[7],
effects: args.slice(8)
};
}
function parseOwnMember(arg) {
var args = arg.split(':');
var ownArgs = args.splice(8, 6);
var member = parseMemberCommon(args);
member.moveCount = [
+ownArgs[0],
+ownArgs[1],
+ownArgs[2]
];
member.bonusAttack = +ownArgs[3];
member.bonusDefense = +ownArgs[3];
member.bonusSpeed = +ownArgs[3];
return member;
}
function parseOpponentMember(arg) {
return parseMemberCommon(arg.split(':'));
}
function parseTeamStateCommon(arg, memberParse) {
var args = arg.split(':');
var state = {
name: args[0],
members: []
};
args = arg.substring(state.name.length + 1).split('|');
var activeSlot = args[0];
for(var index = 1; index < args.length; index++) {
state.members.push(memberParse(args[index]));
}
state.activeMember = state.members[activeSlot];
return state;
}
function parseOwnState(arg) {
return parseTeamStateCommon(arg, parseOwnMember);
}
function parseOpponentState(arg) {
return parseTeamStateCommon(arg, parseOpponentMember);
}
function parseBattleState(arg) {
var args = arg.split('#');
return {
own: parseOwnState(args[0]),
opponent: parseOpponentState(args[1])
};
}
function teamData() {
saveData({round:0}, function() {
console.log('Nodemon|' +
'Charasaur:0:50:80:100:10:13:1|' +
'Bulbtortle:4:50:80:100:10:13:1|' +
'Squirtmander:1:50:80:100:10:13:4');
});
}
function getActiveIndex(battleState) {
for(var index = 0; index < battleState.own.members.length; index++) {
var member = battleState.own.members[index];
if(member.hp > 0) {
return index;
}
}
}
function chooseActive(arg) {
var battleState = parseBattleState(arg);
getData(function(data) {
var allFull = true;
for(var index = 0; index < battleState.opponent.members.length; index++) {
var member = battleState.opponent.members[index];
if(!data.maxSpeed || member.baseSpeed > data.maxSpeed) {
data.maxSpeed = member.baseSpeed;
}
if(member.hp < 100) {
allFull = false;
}
}
if(allFull) {
data.round++;
}
saveData(data, function() {
console.log(getActiveIndex(battleState));
});
});
}
function useMove(moves, battleState) {
var fighter = battleState.own.activeMember;
for(var moveIndex = 0; moveIndex < moves.length; moveIndex++) {
var move = moves[moveIndex];
if(fighter.moveCount[move]) {
return move;
}
for(var memberIndex = 0; memberIndex < battleState.own.members.length; memberIndex++) {
var member = battleState.own.members[memberIndex];
if(member.hp > 0 && member.moveCount[move] > 0) {
return 10 + memberIndex;
}
}
}
return -1; //do nothing
}
function battleAction(arg) {
var battleState = parseBattleState(arg);
var fighter = battleState.own.activeMember;
var opponent = battleState.opponent.activeMember;
var attemptedMoves = [];
if(opponent.effects.indexOf(effect.poison) === -1) {
attemptedMoves.push(1);
}
if(opponent.effects.indexOf(effect.confusion) === -1) {
attemptedMoves.push(0);
}
if(fighter.name === 'Squirtmander') {
//sleep
if(opponent.effects.indexOf(effect.sleep) === -1) {
attemptedMoves.push(2);
}
}
else {
//heal
if(fighter.hp <= 60) {
attemptedMoves.push(2);
}
}
console.log(useMove(attemptedMoves, battleState));
}
function bonusStats(arg) {
var teamState = parseOwnState(arg);
getData(function(data) {
var result = '1:';
if(data.round % 4 === 0) {
result += '1:';
}
else {
result += '2:';
}
if(teamState.members[2].baseSpeed + teamState.members[2].bonusSpeed > data.maxSpeed + (data.round / 2)) {
result += '1';
}
else {
result += '2';
}
console.log(result);
});
}
var actions = {
'T': teamData,
'C': chooseActive,
'A': battleAction,
'B': bonusStats
};
var arg = process.argv[2];
actions[arg[0]](arg.substring(2));
```
Run with
`node nodemon`
P.S. Apologies to [nodemon](https://github.com/remy/nodemon).
[Answer]
# Bitter Rivals - Java
A Grass/Fire/Water team that likes to switch it up.
### Greenosaur
Has at least neutral coverage on anyone. High speed to make up for lack of defense.
```
Type: Grass
Attack: 80 Vine
Defense: 50 Punch
Speed: 100 Pain
```
### Searizard
Tries to Sap enemies with with low attack. Burns and Fireballs after that.
```
Type: Fire
Attack: 100 Fireball
Defense: 50 Burn
Speed: 80 Sap
```
### Blastshield
Uses Shield to enhance its already high defense. Heals when necessary.
```
Type: Water
Attack: 80 Watergun
Defense: 100 Shield
Speed: 50 Heal
```
### Code
This is also included with the controller. This *is* a competing team, unlike DummyTeam. The command needed for `players.conf` is:
```
java BitterRivals
```
---
```
public class BitterRivals {
public static void main(String[] args) {
if(args.length < 1){
System.out.println("You're not doing this right. Read the spec and try again.");
System.exit(0);
}
String[] sections = args[0].split("#");
String me, them, out = "";
switch(sections[0]){
case "T":
out = "BitterRivals";
out += "|Greenosaur:4:80:50:100:12:0:3";
out += "|Searizard:2:100:50:80:6:7:14";
out += "|Blastshield:3:80:100:50:9:11:1";
break;
case "B":
out = "2:0:1";
break;
case "C":
me = sections[1];
them = sections[2];
int pick = 0;
switch(getField(them, TYPE, getActive(them))){
case 0:
case 1:
case 3:
pick = 0;
break;
case 2:
pick = 2;
break;
case 4:
pick = 1;
break;
}
if(!isAlive(me, pick)){
for(int i=0;i<3;i++){
if(isAlive(me,i))
pick = i;
}
}
out = pick + "";
break;
case "A":
me = sections[1];
them = sections[2];
int active = getActive(me);
int oType = getField(them, TYPE, getActive(them));
switch(active){
case 0: // Greenosaur
switch(oType){
case 0:
case 4:
out = "1";
break;
case 1:
out = "2";
break;
case 3:
out = "0";
break;
case 2:
if(isAlive(me, 2)){
out = "12";
} else if(isAlive(me, 1)){
out = "11";
} else {
out = "1";
}
break;
}
break;
case 1: // Searizard
if(oType == 3){
if(isAlive(me, 0)){
out = "10";
break;
} else if(isAlive(me, 2)){
out = "12";
break;
}
if(getEffectCount(them, BURN, getActive(them), false) < 1 && getField(me, MOVE1, active) > 0){
out = "1";
} else if(getField(me, MOVE2, active) > 0){
out = "2";
} else {
out = "3";
}
} else {
if(getField(them, ATTACK, getActive(them)) < 80){
if(getEffectCount(them, DEFENSE_DOWN, getActive(them), false) < 1 && getField(me, MOVE2, active) > 0){
out = "2";
break;
} else if(getEffectCount(them, BURN, getActive(them), false) < 1 && getField(me, MOVE1, active) > 0){
out = "1";
break;
}
}
out = "0";
}
break;
case 2: // Blastshield
if(oType == 4){
if(isAlive(me, 1)){
out = "11";
break;
} else if(isAlive(me, 0)){
out = "10";
break;
}
}
if(getField(me, HP, active) < 50 && getField(me, MOVE2, active) > 0){
out = "2";
} else if(getEffectCount(me, DEFENSE_UP, active, true) < 3 && getField(me, MOVE1, active) > 0){
out = "1";
} else {
out = "0";
}
break;
}
break;
default:
out = "Invalid query from controller.";
}
System.out.println(out);
}
static boolean isAlive(String teamState, int who){
return getField(teamState, HP, who) > 0;
}
static int getActive(String teamState){
return Integer.parseInt(teamState.split("\\|")[0].split(":")[1]);
}
static int getField(String teamState, int field, int who){
String[] fields = teamState.split("\\|")[who+1].split(":");
return Integer.parseInt(fields[field]);
}
static int getEffectCount(String teamState, int effect, int who, boolean mine){
String[] fields = teamState.split("\\|")[who+1].split(":");
int count = 0;
for(int i=mine?14:8;i<fields.length;i++){
if(Integer.parseInt(fields[i]) == effect)
count++;
}
return count;
}
final static int ID = 1;
final static int ATTACK = 2;
final static int DEFENSE = 3;
final static int SPEED = 4;
final static int HP = 5;
final static int TYPE = 6;
final static int PTURNS = 7;
final static int MOVE0 = 8;
final static int MOVE1 = 9;
final static int MOVE2 = 10;
final static int HA = 11;
final static int HD = 12;
final static int HS = 13;
final static int POISON = 1;
final static int CONFUSION = 2;
final static int BURN = 3;
final static int SLEEP = 4;
final static int ATTACK_UP = 6;
final static int ATTACK_DOWN = 7;
final static int DEFENSE_UP = 8;
final static int DEFENSE_DOWN = 9;
final static int SPEED_DOWN = 10;
}
```
[Answer]
# Error 310 : Too Many Redirects - C++
*A highly trained and organized team to counter the ravages of poison*
For three weeks, I hardly trained my codémons. I formed several teams. And finally, I am ready to face this challenge.
To answer all my poisoner opponents, I formed a team with very different codémons, each with a specific role.
---
## Antidote(image)
## `Type : Normal - atk:50 def:100 spd:80 - Poison/Burn/Heal`
Antidote loves poison. So much so that I can't stop him from rushing to poison attacks.
---
## Zen(image)
## `Type : Fire - atk:100 def:80 spd:50 - Poison/Vine/Heal`
Zen is a very surprising codémon which accommodates with all effects. He prefers to watch his enemies strive and exhaust against his silence.
---
## Triforce(image)
## `Type : Psychic - atk:88 def:60 spd:82 - Fireball/Watergun/Vine`
Triforce is a classic codémon, always ready to fight. This one uses his psychic force to control the three elements and inflict as much damages as possible.
---
You can download the team here :
# Linux :
<http://dl.free.fr/iHYlmTOQ2>
launch with `./Error310TMR`
# Windows :
<http://dl.free.fr/vCyjtqo2s>
launch with `./Error310TMR.exe`
The code is a complete c++ project. I don't know how to publish it.
```
$ wc -l src/*
165 src/BruteForce.cpp
26 src/BruteForce.h
349 src/Codemon.cpp
77 src/Codemon.h
21 src/Logger.cpp
35 src/Logger.h
105 src/NoTimeToExplain.cpp
27 src/NoTimeToExplain.h
240 src/Recoverator.cpp
31 src/Recoverator.h
26 src/StrManip.cpp
16 src/StrManip.h
303 src/Team.cpp
68 src/Team.h
88 src/TooManyRedirects.cpp
24 src/TooManyRedirects.h
87 src/Unrecoverable.cpp
27 src/Unrecoverable.h
59 src/enums.cpp
119 src/enums.h
68 src/main.cpp
1961 total
```
But it is very effective :
```
------- Final Results -------
176 Error310TMR
131 H3C
130 LittleKid
121 Nodemon
58 InsideYourHead
47 HardenedTrio
37 BitterRivals
```
[Answer]
# FairyTale
A fairly generic middle-of-the-road team. Based on three archetypes who try to do their thing, and switch out if they can't do their thing at all.
This team was created before it seemed like poison was the new meta, I haven't really been keeping up with changing my team since I originally made it, most of the time was spent just trying to get the parsing down. I haven't been able to get the Tournament running yet to test it, but it's been a pretty busy week. If this one doesn't actually work like it seems to with my test data, I'll apply some more shine to it after work.
```
#!/bin/perl
use 5.20.0;
use strict;
use constant MINE => 0;
use constant THEIRS => 1;
$_ = $ARGV[0];
if(/^T/){
say 'FairyTale|Fairy:1:89:90:51:3:4:13|Dragon:2:100:50:80:6:1:8|Assassin:0:70:60:100:0:1:10';
} elsif(/^C#(.*)/){
my $state = readBattleState($1);
if($state->[MINE]->{$state->[MINE]->{slot}}{hp}){
say $state->[MINE]->{slot};
} elsif($state->[MINE]->{($state->[MINE]->{slot}+1)%3}{hp}){
say (($state->[MINE]->{slot}+1)%3);
} else {
say (($state->[MINE]->{slot}+2)%3);
}
} elsif(/^A#(.*)/){
my $state = readBattleState($1);
my @actives = (
$state->[MINE]->{$state->[MINE]->{slot}},
$state->[THEIRS]->{$state->[THEIRS]->{slot}}
);
if($state->[MINE]->{slot} == 0){
if(!exists($actives[THEIRS]{effects}{4}) && $actives[MINE]{pp}->[1]){
say 1;
} elsif(!exists($actives[THEIRS]{effects}{1}) && $actives[MINE]{pp}->[2]) {
say 2;
} elsif(!$actives[THEIRS]{type}) {
if($state->[MINE]->{($state->[MINE]->{slot}+1)%3}{hp} > 0){
say (($state->[MINE]->{slot}+1)%3);
} elsif($state->[MINE]->{($state->[MINE]->{slot}+2)%3}{hp} > 0) {
say (($state->[MINE]->{slot}+2)%3);
} else {
say 0;
}
} else {
say 0;
}
} elsif($state->[MINE]->{slot} == 1){
if(!exists($actives[MINE]{effects}{6}) && $actives[MINE]{pp}->[2]){
say 2;
} elsif ($actives[MINE]{hp} > 10 && $actives[MINE]{hp} < 50 && $actives[MINE]{pp}->[1]){
say 1;
} else {
say 0;
}
} elsif($state->[MINE]->{slot} == 2){
if(!exists($actives[MINE]{effects}{6}) && $actives[MINE]{pp}->[2]){
say 2;
} elsif ($actives[MINE]{hp} > 10 && $actives[MINE]{hp} < 50 && $actives[MINE]{pp}->[1]){
say 1;
} elsif($actives[THEIRS]{type} == 1) {
if($state->[MINE]->{($state->[MINE]->{slot}+1)%3}{hp} > 0){
say (($state->[MINE]->{slot}+1)%3);
} elsif($state->[MINE]->{($state->[MINE]->{slot}+2)%3}{hp} > 0) {
say (($state->[MINE]->{slot}+2)%3);
} else {
say 0;
}
} else {
say 0;
}
}
} elsif(/^B#(.*)/){
my $state = readTeam($1, 1);
say '1:0:2';
}
sub readBattleState {
local $_ = $_[0];
if(/^(.*?)#(.*?)$/){
my @teams;
$teams[0] = readTeam($1, 1);
$teams[1] = readTeam($2, 0);
return \@teams;
}
}
sub readTeam {
my $isMine = $_[1];
local $_ = $_[0];
if(/.*?:(?<slot>.*?)\|(.*?)\|(.*?)\|(.*?)$/){
my %team;
$team{slot} = $1;
$team{0} = $isMine ? readYourMember($2) : readTheirMember($2);
$team{1} = $isMine ? readYourMember($3) : readTheirMember($3);
$team{2} = $isMine ? readYourMember($4) : readTheirMember($4);
return \%team;
}
return 0;
}
sub readYourMember {
local $_ = $_[0];
if(/(?<name>.*?):(?<id>.*?):(?<atk>.*?):(?<def>.*?):(?<spd>.*?):(?<hp>.*?):(?<type>.*?):(?<poison>.*?):(?<move0>.*?):(?<move1>.*?):(?<move2>.*?):(?<batk>.*?):(?<bdef>.*?):(?<bspd>.*?)(?<effects>(?::.*)|$)/){
my %effects = map { $_ => 1 } readEffects($+{effects});
my %member = (
name => $+{name},
id => $+{id},
hp => $+{hp},
atk => $+{atk}+$+{batk},
def => $+{def}+$+{bdef},
spd => $+{spd}+$+{bspd},
type => $+{type},
pp => [$+{move0}, $+{move1}, $+{move2}],
poistrn=> $+{poison},
effects=> \%effects
);
return \%member;
}
}
sub readTheirMember {
local $_ = $_[0];
if(/(?<name>.*?):(?<id>.*?):(?<atk>.*?):(?<def>.*?):(?<spd>.*?):(?<hp>.*?):(?<type>.*?):(?<poison>.*?)(?<effects>(?::.*)|$)/){
my %effects = map { $_ => 1 } readEffects($+{effects});
my %member = (
name => $+{name},
id => $+{id},
hp => $+{hp},
atk => $+{atk},
def => $+{def},
spd => $+{spd},
type => $+{type},
poistrn=> $+{poison},
effects=> \%effects
);
return \%member;
}
return 0;
}
sub readEffects {
local $_ = $_[0];
my @retval = /:([^:]*)/g;
if(!@retval){
@retval = (0);
}
return @retval;
}
```
Run with
```
perl fairytale.pl
```
[Answer]
# Dummy Team - Java
### (non-competing CW)
This is a dummy team to practice on. It's all normal types, which choose randomly between their moves (Punch, Heal, Slow) each turn. Have fun with it.
```
public class DummyTeam {
public static void main(String[] args) {
if(args.length < 1){
System.out.println("You need to run this from the tournament. Try to keep up.");
System.exit(0);
}
String[] sections = args[0].split("#");
String out = "";
switch(sections[0]){
// team data
// sends back all Normal types with minimum stats and Normal moves (randomized name suffixes to distinguish in tests)
case "T":
out = "DummyTeam";
for(int i=0;i<3;i++)
out += "|Dummy"+((char)(Math.random()*26)+65) + i + ":0:50:50:50:0:1:2";
break;
// bonus points
// shoves them all in defense every time
case "B":
out = "1:1:1";
break;
// choose active
// picks last active if alive, otherwise loops to find first living member
case "C":
String[] team = sections[1].split("\\|");
int current = Integer.parseInt(team[0].split(":")[1]);
if(Integer.parseInt(team[current+1].split(":")[5]) > 0){
out = current + "";
} else {
for(int i=1;i<team.length;i++){
if(Integer.parseInt(team[i].split(":")[5]) > 0){
out = (i - 1) + "";
}
}
}
break;
// choose action
// chooses a random move. does not check if it ran out of uses, so wastes turns quite often
case "A":
out = ((int)(Math.random()*3)) + "";
break;
default:
out = "Invalid query from controller.";
}
System.out.println(out);
}
}
```
] |
[Question]
[
Some time ago, the following question was asked: [GolfScript, CJam, or Pyth?](https://codegolf.stackexchange.com/q/54385/903)
Based on the title only, I thought that it would be a very nice challenge, but unfortunately, it turned out to be a question asking for tips.
Here is the challenge I wanted to read:
>
> Who said golfing languages were not used in the Real World?
> As everybody knows, the ratio of bugs per line of code is the same independently of the programming language being used, so there is a clear opportunity to reduce debugging and maintenance costs with those languages. Your company finally saw the light and decided to use Golfscript, CJam and Pyth to develop its products.
>
>
> Unfortunately, after a couple of months, your hard drives are cluttered with snippets of code and you don't even know which ones are written in which languages (you even suspect some of your programmers of using Perl).
>
>
> You must write a tool to detect which of CJam, Golfscript or Pyth is the language in which a program is written. The situation is critical, you can use any language you want, but please keep it short (data storage is expensive: the more bytes we use, the more it costs).
>
>
>
# General
* Shortest code win
* Standard loopholes, etc.
* Don't use an online interpreter
* You can write a function or a program
* You can use eval to detect your own language
# Input
* Your input is taken from the standard input stream or as a string
* Input contains only ASCII printable characters and linefeeds
* The size of the input is up to 256 bytes long
# Output
* Output is printed to output stream or returned as a sequence of strings/symbols
* If the input is without doubt a valid *X* program, print or return *X*, *X* ∈ {CJam, Pyth, Golfscript}
**Remark**: "without a doubt" does not mean that you are allowed to answer with a dumb analyzer that consistently fails to detect any language. For [Pyth](https://pyth.readthedocs.org), I expect [Simple Programs](https://pyth.readthedocs.org/en/latest/simple-programs.html) to be recognized (but no hardcoding). The same goes for [CJam](http://sourceforge.net/p/cjam/wiki/Home/) ([cheat sheet](https://dl.dropboxusercontent.com/u/15495351/cjam.pdf), [examples](http://sourceforge.net/p/cjam/wiki/Examples/)) and [Golfscript](http://www.golfscript.com/golfscript/quickref.html) ([examples](http://www.golfscript.com/golfscript/examples.html)). The previous links point to each language's specifications.
If you use a fuzzy/bayesian approach, "without a doubt" means with a high-level of confidence (you score 99% with your classification, for example).
*See below for the actual test suite.*
* If the input is valid in multiple languages, each detected language should be printed/returned. When printed, there must be a separator between multiple outputs (e.g. space, newline, comma...).
* The order in which languages are tried does not matter
* I do not care about case (CJam, cjam, CJAM, SPAM) [1]
* If *none of the above language* is detected, print ["`Probably Perl`"](http://www.perlmonks.org/?node_id=663393).
Thanks to [this comment from mbomb007](https://codegolf.stackexchange.com/questions/58522/seriously-golfscript-cjam-or-pyth?noredirect=1#comment140937_58522), in the above case you can also output "`Seriously`" for a penalty of 4 bytes (the difference between both strings).
[1] Just to be clear, SPAM is invalid
# Examples
* [Input](https://codegolf.stackexchange.com/a/58211/903)
```
"Crime predicted: --
Calling: 1--555-
"30*{_5<{iAa*:mr}&}/
```
* Output (example of multiple return values)
```
["Golfscript", "Cjam"]
```
* Input
```
3
```
* Output (example on standard output)
```
golfscript
cjam
pyth
```
* Input
```
if {} aazd
```
* Output
```
Probably Perl
```
In the last case, the input program produces an error [With](http://cjam.aditsu.net/) [All](http://pyth.herokuapp.com/) [Three](http://golfscript.apphb.com/) online interpreters.
# Scoring, winning criterion
Shortest code win. Add 4 bytes if you output "Seriously". Then, apply bonuses.
## Failing tests
The following are snippets that *must not* be recognized as any of the three languages above.
One-liners (i.e. one entry per line)
```
$^X=~/([a-z]+)[^\/]+$/;print$1,$/
<>;map($s-=(-1)**$_/(2*$_-1),1..$_),$s=!print$s,$/for<>
((THIS IS LISP HAIKU) (TRULY THIS IS LISP HAIKU) (THIS IS LISP HAIKU))
(format t"~@(~{~R~^, ~}~).~%~:*~@(~{~:R~^, ~}~)."(loop for i to 99 collect(1+ i)))
print sum(ord(c) for c in 'Happy new year to you!')
```
Brainfuck
```
>++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.
++++++++++++++++++++++++++++++++++++++++++++++++.
-----------------.
++++++++.
+++++.
--------.
+++++++++++++++.
------------------.
++++++++.
```
Perl
```
@list=( "aaaa",
"aaaaaaaa",
"aaaaaaaaaaaaaaa",
"aaaaaaaaaaaaaaaa",
"aaaaaaaaaaaaaaaaaaaaaaa",
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
while (@list) {
for($i=0;$i<6;$i++){
print length($list[$i])." ";
}
print "\n";
}
```
Fish
```
#ifndef __linux
#include "x.h"
#define X/*\
a=1 set -e
+++++++++++++++++++++_+++++++++++++....Hello World!?:Q:
#endif
echo "Hello, World!"
int m(){}
```
## Basic test suite
Those are tests which *must* pass. Belows are *one-liners* for each language where your program must detect the language it is being written in (I did not check which of those are polyglot).
### Pyth
```
*2Q
FNrZTN
FNrZhTN
FNUhTN
VhTN
FNr1hQN
=N5N
K5K
K1FNr1hQ=K*KN
K1FNr1hQ=K*KNK
K1FNr1hQ=K*KN;K
DhZK*3ZRK
L?b*bytb1yQ
A(Z1)VQHA(H+HG
```
### Golfscript
```
;'2706 410'~{.@\%.}do;
;''6666,-2%{2+.2/@*\/10.3??2*+}*`50<~\;
'Hello, world!'
1 2 [\]
```
### CJam
```
"Hello, world"
{`"_~"}_~
"`_~"`_~
T1{_2$+}A*]`
{__'`>\'x>26*2-*-}/
Y38#
N/s:X,8-,{X>9<__{'a<},,\4%{'Z>},,*I={4=}{;}?}/
```
---
## Silver bonus: byte-count \* 0.6
All previous tests must pass, as well as the following one-liners.
All those snippets are taken from actual CodeGolf answers.
### Pyth
```
VzJ:zZhZpkJ~Zhy}rJ0-G"aeoui
Vzjdm?@zd}N,dt-lzd\ Uz
jd.iSQs*RtQ,\?":0
rsXOtQmO*-GJ"aeiou"J/Q2*%Q2O"hy"4
VhQIq`N_`NN
s["$$\\varphi=1+"*Q"\cfrac1{1+"\\<\dQ"dots"*Q\}"$$
@c"weak trick fair"d-!JlfhT-M.:us_cG.u+NYtKrH7-52hK.zU52 2>J26
```
### Golfscript
```
);:|;{0):0;|$:§-1%" - "§" = ""0"4$~§~-+-4>:|n|6174`=!}do"Iterations: "0"."
'-+,/'{)))))}%
4:echo(2+2);
#undef X;A!"$%&'()*+-[,.]/0123456789:<=>?@BCDEFGHIJKLMNOPQRSTUVWYZ\^_`abcghijklmopqrstvwxyz{|}~
{`),32>^.}.~
"126,32>''+".~\-'.~\-"'-
"),@`^^32>#.~".~
...[[]]{{}}&%%++++5i
*++..0011125::::;;;?bbbbcccc{}
"This program wasn't written in "o"GolfScript"", it was built for ""CJam"oo"!"
```
### CJam
```
"Q"c("ASSW"1$("aRD"(((T1
%\@_@){;_0}*__*)\15
"This program wasn't written in "o"GolfScript"", it was built for ""CJam"oo"!"
"P2"1e3K51_,1>K*$K*~]N*
li__,\mf:i2m1+:*/fb:+
ri:B__(^2/):G/,{_BBG/@-(#G@*G(B2/*+*}/]:+
{1$+S@]_1=4+1$`,-S*"2$~"}21D2$~
[S'-26*N]:Z[S'|:PS24*PN]:RR'(PS5*qi:XD=X0<-X2%2*+:Y[" ^ "_" > ""(O)"" - "__]=S8*Y[" ^ "" "" < ""(O)"" - "__]=S5*P')NRRXD=[SPS7*'oA*S7*PN]:QR?Y[[SPS5*'oSC*'oS5*PN]:T_R[SPS7*'oS8*'oS7*PN]RRR]=QY2=TR?RRZ
li4H#+2bW%32<2b
q~:R100:H*\d:T/i){R-H*HT-/m]}6*_H)<*
"JamesBdo,"YZ+/)BA*c+Y*Y%:BS@SB)))[JW:Z____)ci+*]U*
```
---
## Gold bonus: previous-score \* 0.8
### Pyth
Compare
```
jdm@cd)._-FQcj"
is
equal greater less
to than
"Qb
```
Snowman
```
M@GCHgc" ___
___
_"bhzgc" (_*_)
_===_
.....
/_\\"bhzs[g" \ "@z4\(g"-.oO"@z2g" ,._"@z1g"-.oO"@z3\)g" / "@z5)s[g" < /"@z4\(gc"
:
] [
> <"b@z6\)g" > \\"@z5)++" ("gc"
:
\" \"
___"bez\)
```
### CJam
Big
```
rri:Hri:Vri:Q[q~]3/_Qa3*a+_|$W%:Pf{\a#}:AH/:B0ff*
P,,[AHAW%HBz:+_W%V\V]2/
ff{~@@f=/::|1#}0Ua4*t:R;
P0f<
V{H{BI=J=_2$=
0R{"I>! I+V<J>! J+H<"4/+4/z{~~}%:&1$*\)}%);2$-|t
}fJ}fI
[P,{_La#\1$0t1$f-}*;;]
{:TR=2/~\~V\-,>\f{\_3$=@~H\-,>{Tt}/t}~}/
:~Pf=:~
~]S*N
```
Snowman
```
q:Q;SS"
_===_,___
....., _
/_\,___
(_*_)"',/0{Q=~(=}:G~N" \ "4G'(".oO-"_2G",._ "1G@3G')" / "5GN"< / "4G'(" : ] [> < "3/6G')"> \ "5GNS'(" : \" \"___ "3/7G')
```
### Golfscript
Lorem Ipsum
```
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras imperdiet est ut sem commodo scelerisque. Sed ut ultricies enim. Nam eget lectus suscipit, gravida turpis a, volutpat tellus. Cras efficitur luctus neque, at semper massa condimentum at posuere.
```
Digital clock
```
:*{32' _':$@'14'{?~!=}:&~32}%n*{:x' |':|\'1237'&$x'017'&|x'56'&}%n*{:x|\'134579'&$x'147'&|x'2'&}%
```
Happy birthday
```
4,{"Happy Birthday "["To You""Dear GolfScript"]@2==n}%
```
Farey sequence
```
~:c[,{){.}c(*}%.c/zip{+}*]zip{~{.@\%.}do;1=},{~<},{~\10c?*\/}${'/'*}%', '*'F'c`+' = {0/1, '+\', 1/1}'
```
[Answer]
## Python 2, 332 \* 0.6 \* 0.8 = 159.36
```
import os
from subprocess import*
from tempfile import*
f,n,a=NamedTemporaryFile(delete=0),open(os.devnull,'w'),''
f.write(os.read(0,256))
f.close()
for l in["CJam","java","-jar","cjam.jar"],["Pyth","./pyth.py"],["Golfscript","./golfscript.rb"]:a+=(l[0]+' ')*(call(args=l[1:]+[f.name],stdout=n,stderr=n)>0)
print a or'Probably Perl'
```
As far as I'm aware, this is within the rules. Requires the Pyth, CJam, and Golfscript interpreters (`pyth.py`, `cjam.jar`, and `golfscript.rb`) in the current directory, and Python 3, Java, and Ruby installed. Simple test: try running the program. If it returns with `0`, we're good. If not, it's invalid. A named temporary file (e.g. a file created in `$TMP`) is created to hold the program, since CJam doesn't have a script option. The `delete=False` flag is necessary to prevent the file from being deleted when it is closed (the OS will take care of it for us). The file has to be closed before attempting to read from it (though manually flushing the file should also work, but this is simpler). `stdout` and `stderr` are redirected to `/dev/null` to suppress output/errors (note that this makes it only work on \*NIX systems).
Extra fun: try running the given code in all 4 languages, to see what we get:
```
import sys
from subprocess import*
from tempfile import*
c=["Cjam","java","-jar","cjam.jar"]
p=["Pyth","./pyth.py"]
g=["Golfscript","./golfscript.rb"]
e=["Perl","perl"]
f=NamedTemporaryFile(delete=False)
s=sys.stdin.read()
f.write(s)
f.close()
n=open('/dev/null','w+')
a=''
for l in [c,p,g,e]:
try:
print '%s: %s'%(l[0],check_output(args=l[1:]+[f.name],stderr=n))
except:
continue
n.close()
```
[Answer]
# Ruby, (135 + 4) \* 0.6 \* 0.8 = 66.72
This runs on Windows and I'm too tired to shorten it by running on Unix.
```
(a=[%w(javaw -jar cjam),%w(python pyth),%w(rubyw golfscript)].map{|c|c[-1]if system(*c,?f,'> NUL','2>','NUL')}-[nil])==[]?'Seriously':a
```
I did these things but I'm not sure if they're allowed:
* Rename `cjam-[version].jar` to `cjam`, `pyth.py` to `pyth`, `golfscript.rb` to `golfscript`.
* Read from file `f` instead of getting input. (Add `IO.write(?f,gets);` to the beginning to fix that, and the new length is (153 + 4) \* 0.6 \* 0.8 = 75.36)
] |
[Question]
[
Write a script that outputs `A` to stdout infinitely.
There should be no newlines or separators between the characters.
Standard loopholes apply.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). The shortest solution in each language wins.
[Answer]
# x86-16, IBM PC DOS, ~~7~~ 6 bytes
```
00000000: b041 cd29 ebfc .A.)..
```
Unassembled listing:
```
B0 41 MOV AL, 'A' ; put 'A' into AL
PRINT:
CD 29 INT 29H ; DOS fast console output char in AL
EB FC JMP PRINT ; loop infinitely
```
[![enter image description here](https://i.stack.imgur.com/ru7xt.png)](https://i.stack.imgur.com/ru7xt.png)
As a bonus, if you run this on your [IBM 5151](https://en.wikipedia.org/wiki/IBM_5151) monitor for a few hours this will actually produce infinite output on that screen until the end of time.
[Answer]
# [Turing Machine Code](http://morphett.info/turing/turing.html), 9 bytes
```
0 * A r 0
```
[Try it online!](http://morphett.info/turing/turing.html?e955f46991325233f2b91f90b5749354)
One of the very few times that Turing Machine Code can compete overall.
[Answer]
# [brainfuck](https://github.com/TryItOnline/brainfuck), 16 bytes
```
+[+[<]>>+<+]>[.]
```
Credit to [the Brainfuck constants page](https://esolangs.org/wiki/Brainfuck_constants) for 65!
[Try it online!](https://tio.run/##SypKzMxLK03O/v9fO1o72ibWzk7bRjvWLlov9v9/AA "brainfuck – Try It Online")
[Answer]
# [Taxi](https://bigzaphod.github.io/Taxi/), 279 bytes
```
Go to Post Office:w 1 l 1 r 1 l.[A]A is waiting at Writer's Depot.A is waiting at Writer's Depot.Go to Writer's Depot:w 1 r 1 l 2 l.Pickup a passenger going to Post Office.Pickup a passenger going to Post Office.Go to Zoom Zoom:n.Go to Post Office:w 3 l 2 r 1 l.Switch to plan A.
```
[Try it online!](https://tio.run/##jY8xC8IwEIX/ytvcAurWrSA4WnAQLA4hpPGw5kJyUv99bJOpIOhwd3D3eN890W/K@cgQRsdJcBoGMraZsMU4V1ym6ttbC0qYNAl5By24RBIbNwkHG1jUj3MFrJeFUfyxmxkdmccrQCPolKx3NsLx4rb@7G9dRV6Zn6U1Xn1LuS/0mvI8kZj7ogmj9mhVzh8 "Taxi – Try It Online")
---
This is an interesting challenge because it requires both refueling infinitely for gas and getting enough passengers to pay for the gas.
If passengers paid enough to pay for the gas used to transport them, the following would be enough:
```
Go to the Post Office: west 1st left, 1st right, 1st left.
[loop]
"A" is waiting at the Writer's Depot.
Go to Go More: west 1st right, 1st left, 1st left, 2nd right.
Go to the Writer's Depot: west 1st right.
Pickup a passenger going to the Post Office.
Go to the Post Office: north 1st right, 2nd right, 1st left.
Switch to plan "loop".
```
However, because passengers do not pay enough this results in [only 54 \* `A`](https://tio.run/##ZZA/C8IwEMX3fIoji4sUdHQTBCdRcHAQh1CvzWFJQnJSv31MWpXYQhLe5c/v3gurF8W4t8BpaISTDQzHpqEaN9BjKlZpdtjwclCeWv2RebMS185adxNyK4EC9IqYTAuKB9rFE6NfBNihs@ny2CetB@tL/oRaqrW5j8ff13PuFFSJE9WPpwMFToWApkUPrc2@5ilL7F94Yz3r0t3PSRn/3BPXOgNcpwzI/BuyEjG@AQ "Taxi – Try It Online"), crashing the program once we are out of fuel.
We can also go to Zoom Zoom to buy fuel, it's way cheaper to buy here allowing us to get [79 \* `A`](https://tio.run/##bY9BC8IwDIXv@xVhFy9joN52EwSPDjwIioeyZVtwNqWNzH8/27nBdEIaXh9Nvj5RL@r7A4P4ahBydgLHqqICM@jQX9b@tFhJMihLdTPKYKbRtWU2tyjexUAOOkVCugYlw7azJUG7crBHw/7xh/PtzjA/yxPY6HLE5FTcnwYUGOUc6hot1BxIy39PmAvzY2gZaLbSTP7/mFtbzqCLmKeOpGjCuGmVhjikjtOo798 "Taxi – Try It Online").
Luckily, picking up two passengers at a time solves this problem of not earning enough per iteration.
The code can be golfed further by removing quotes for strings that don't contain whitespace and minimising the directions.
Ungolfed it looks like this:
```
Go to the Post Office: west 1st left, 1st right, 1st left.
[loop]
"A" is waiting at the Writer's Depot.
"A" is waiting at the Writer's Depot.
Go to the Writer's Depot: west 1st right, 1st left, 2nd left.
Pickup a passenger going to the Post Office.
Pickup another passenger going to the Post Office.
Go to Zoom Zoom: north.
Go to the Post Office: west 3rd left, 2nd right, 1st left.
Switch to plan "loop".
```
## Two 321 byte answers
Before I realised I could go to Zoom Zoom with two passengers I found the following solutions of 321 bytes which have some interesting tricks not used in the shorter solution…
```
Go to Post Office:w 1 l 1 r 1 l.[A]"A"is waiting at Writer's Depot."A"is waiting at Writer's Depot."A"is waiting at Writer's Depot.Go to Writer's Depot:w 1 r 1 l 2 l.[B]Switch to plan C i.Pickup a passenger going to Post Office.Switch to plan B.[C]Go to Go More:s 1 l.Go to Post Office:e 1 l 1 r 1 r 1 l.Switch to plan A.
```
[Try it online!](https://tio.run/##pVC9CoMwEH6VD5dugXZ0UwudSgWHDuIQ5LRHxYTkin371OhS7djh7uD@vh/Rbw7hYiAGpfGCW9dxS@mEI4Y5XKyqzpokS9hj0iw89tCCu2Mhd/A4kzWi/p2vFLbNhcXCAKfIIm@qiaV9xE076BEFWJXcPl8WGlZ7T2NPDr2JGFtFaneaq7poVtA5X42j1C9af72gLy9WP3a/MhXCBw "Taxi – Try It Online")
**or**
```
Go to Post Office:w 1 l 1 r 1 l.[A]"AAA"is waiting at Writer's Depot.Go to Writer's Depot:w 1 r 1 l 2 l.Pickup a passenger going to Chop Suey.Go to Zoom Zoom:n.Go to Chop Suey:w 1 l 3 r.[B]Switch to plan C i.Pickup a passenger going to Post Office.Switch to plan B.[C]Go to Post Office:s 1 r 1 l 2 r 1 l.Switch to plan A.
```
[Try it online!](https://tio.run/##fZBPC4MwDMW/ysPLboVtN2/VwY4TPAwmHopUDXO2tBW3T9/5j@Ec7JAEQt4veXHiSd6fFZxCoqzDpSypkGGPPZohzFhZxvOAcx6QRS/IUVtBOFwNOWl2FieplWMz5Ls5cSYGDgMnoeLeaQhoYa1sK2lQqZE2CONaaaSdfC2gm1KPKYXt0vlMLNcdYVgW5WlPrqjHAd2IFjHo756VS7aRRiyL899f2JWH@R8bHWfevwE "Taxi – Try It Online")
---
Using Go More to get Fuel, even picking up the maximum of three passengers does not give enough money to loop infinitely, so I had to think about it smarter.
If we pick up passengers sooner and take them on a longer route through the city they will pay more for the ride.
Going to Writer's Depot before getting fuel results in [70 \* `A`](https://tio.run/##fY8xC8JADIX3/orQxaUUdHQrCE5ioYODOBw1vQbL5bhLqf/@vGqFVsUhIQnhe@@JulMIewZhKNkLHJuGatzCgHFZx@qwkew5OdLtNI7HPDkXlyQtUiAPgyIho0EJnBwJupWHHVqOXy/48jrjf1Az2JjrxC@pvvUWFFjlPRqNDjSPKkuzb4nYD@yid8@9tDOfP@Kh@hfvK2k1kNTtSLGdMhBD50kIDw "Taxi – Try It Online").
If we pick up three passengers using this route, we can loop infinitely.
Picking up three passengers going to the same destination can be done more byte-efficient than using the same code thrice.
Using `Switch to plan "name" if noone is waiting` we can pick up a single pasenger until all three are picked up.
The quotes around the plan name are optional and it any word after it get's interpreted as `if noone is waiting`.
Using this we get our first 321 byte solution, the code below is the ungolfed version:
```
Go to Post Office: west 1st left, 1st right, 1st left.
[loop]
[Setup 3 * "A"]
"A" is waiting at Writer's Depot.
"A" is waiting at Writer's Depot.
"A" is waiting at Writer's Depot.
Go to Writer's Depot: west 1st right, 1st left, 2nd left.
[Pickup 3 * "A"]
[before pickup]
Switch to plan "after pickup" if noone is waiting.
Pickup a passenger going to Post Office.
Switch to plan "before pickup".
[after pickup]
[Get Gas]
Go to Go More: south 1st left.
[Print 3 * "A"]
Go to Post Office: east 1st left, 1st right, 1st right, 1st left.
Switch to plan "loop".
```
---
But there's more!
Setting up three different passengers to pick up costs quite a few of bytes.
If we instead split up the string `"AAA"` we can eliminate two lines setting up passengers, at the cost of going past Chop Suey.
With this we don't need to go out of our way to visit the Go More gas station anymore, Fueler Up is on our route and Zoom Zoom is very easily accessible too.
Looking into Fueler Up, it's the most expensive, in fact, it's so expensive that you don't get enough money even taking three passengers!
We can only print [561 \* `A`](https://tio.run/##rZFPa8JAEMXvfopHLl5EqN5yCy3tUUHEg/SwxEl2aNhZdidEP33c@KdVEU89LMw8fvveMKNmz33/JVDBUqJiUVVcUo6OUvOWXkOVTk5V4NpeykGcjraNiP8eZUVRZOCIzrCyq2EUm8BKYRzxQV4Sek64V29CHqwnmLndJWTJ5U/rYeBNjORqCqhlSEl@71Y8Vi0drgG/Qg4nQS3mYXc1n6f2VL72vNnCH@hEbYL@GT/P/NlSk5C1zxGlTUM@3fWTE72gVx1raYcfvjEO2XCobNr3Rw "Taxi – Try It Online"), 187 loops of three passengers, but not infinite as we are trying.
Luckily, Zoom Zoom the cheapest gas station does not require much extra routing at all and taking this route does allows us to enter another infinite loop.
```
Go to Post Office: west 1st left, 1st right, 1st left.
[loop]
[Setup 3 * "A"]
"AAA" is waiting at Writer's Depot.
Go to Writer's Depot: west 1st right, 1st left, 2nd left.
Pickup a passenger going to Chop Suey.
[Get gas]
Go to Zoom Zoom: north.
Go to Chop Suey: west 1st left, 3th right.
[Pickup 3 * "A"]
[before pickup]
Switch to plan "after pickup" if noone is waiting.
Pickup a passenger going to Post Office.
Switch to plan "before pickup".
[after pickup]
[Print 3 * "A"]
Go to Post Office: south 1st right, 1st left, 2nd right, 1st left.
Switch to plan "loop".
```
It's sad that this does not safe any bytes, but it's the second time I got two answers with the same number of bytes which I think is cool!
(See this [DDoouubbllee ssppeeaakk](https://codegolf.stackexchange.com/a/195715/89860) challenge.)
I also realised when I was about to publish that *all* strings without whitespace can be written without quotes.
That golved my actual solution a bit more and does not leave the 321 byte solutions the same length anymore.
Even so I still publish this explanation too, because the repeat to pickup three passengers is useful and using Chop Suey was fun :)
[Answer]
# [Bash](https://www.gnu.org/software/bash/) + core utilities, ~~16~~ ~~14~~ 13 bytes
Saved ~~2~~ 3 bytes thanks to [Mitchell Spector](https://codegolf.stackexchange.com/users/59825/mitchell-spector)!!!
```
yes|tr \\ny A
```
[Try it online!](https://tio.run/##S0oszvj/vzK1uKakSCEmJq9SwfH/fwA "Bash – Try It Online")
Also for 13 bytes (written by [Mitchell Spector](https://codegolf.stackexchange.com/users/59825/mitchell-spector)):
# [Bash](https://www.gnu.org/software/bash/), 13 bytes
```
printf A;./$0
```
[Try it online!](https://tio.run/##S0oszvifpqFZ/b@gKDOvJE3B0VpPX8Xgfy1X2n8A "Bash – Try It Online")
Yet another 13 byter, this one written by [pxeger](https://codegolf.stackexchange.com/users/97857/pxeger):
# [Bash](https://www.gnu.org/software/bash/), 13 bytes
```
yes|tr -c A A
```
[Try it online!](https://tio.run/##S0oszvj/vzK1uKakSEE3WcFRwfH/fwA "Bash – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), ~~25~~ 22 bytes
```
while 1:print(end='A')
```
Saved 3 bytes thanks to xnor
[Try it online!](https://tio.run/##K6gsycjPM/7/vzwjMydVwdCqoCgzr0QjNS/FVt1RXfP/fwA "Python 3 – Try It Online")
[Answer]
# [Poetic](https://mcaweb.matc.edu/winslojr/vicom128/final/), 73 bytes
```
why cant i cease,i say
i scream"A"out loud in agony
i cry,as i shouted on
```
[Try it online!](https://mcaweb.matc.edu/winslojr/vicom128/final/tio/index.html?FctBCsAgDAXRfU/xce0lepQ0hiq0CRhFPL21m9k8ZuQJJm0oYCGXWOA0j12uQm84g/WGx3pCUdBt@iPXGcn343mzJJiudVH6AA)
[Answer]
# [AHHH](https://github.com/KyleM73/AHHH), 40 bytes
```
AHHHHhhHHHhHHHhHHHhHHHHhHhhHHHHHHhhhhhhh
```
The right language for the job.
[Try it online!](https://tio.run/##nRlrU9tG8LP1K9ZkMthghGVImjjAtE1ozJTSTpNMZpowjCydrBtkydXDhmb47XT3Tm@dBbZnMPLevm4ft7unqRm5j5YZwxmYruvq1mIBJyewc371YUc7PAT6@2UymcBfYTALzfmc@zO4NP1ZYs4YXPgxCxchw29CnN6P4fd7j8EfQThjfhQz7hP8FmH6vID9PJub3NOtYE6rq9VKJ4wSQrpEq5fcQiAbw8e/LmF5pA8JOGHmknv3wP1owUNmo2R4/@dX6OH/X/nsH3PhBnafMD@7DKI4TKw4CRk4QQgxQnihN6zMCEwvCmAahGGwQmZOGMyJHdH/xpiHAMYgDoDZPD5MInZoc@TJp0nMBoDfsPCYGTGwA383hoh5nrQZSjP9e7BZyJdmzJcMVkF4S2wvHLgPEkBeAnMAZiwZ8sBHpMTDLTGwgsBDucEALiBKFosgYmSVF9y3vMRmJ0tmxUF4VgCi2OaB7pYgFoI8Pq1CQnRiCcIDBDFzjiCbOdxncPXnzce/z88/X1x9/KRp8f2C4QLa0R6PpcwTtOAZzNn8nYZfsJDBIX/MyZP34nk85mhiEwlS6A3ugdMm68sph9K6hiIgZDM0NQuNm6XpJexdBTjKgNqUDFXgumYkl@AUHPQtolQwRioMbRlwG/5NeNwDgc0wHELoaz@0DnegJ372tQ7@7CzQgrHT2zknWPfQ3@m/Qyi7Q1qDHh@0zgvu@GS0iikLyu/@h8Bn@ndJ@oL5NsrIeAwR9pDuit0xq0cBS8EuAplCRGgVrXhsub3aglAQQwyz2cUniwJzOMYngoudNIwNp6cZTJ@ijfxenxjhR5oDuTMQW@zUSQ8OBJj089gSc@UUDAFZudxjvRR4BkPJUOgglHi@Dp0pBuetYCp@r1EhXRUb7O3VkfrEf5hxFFrt70s68cUwBp6kN15VGKSCH6Rds712CznCemS8fq49njlJ6KdebUiRRn7IHTjJHGjkDqzlEW0C0o/UooZAekuQjkEmjFrg/8if5e@Uu75IIvdmalq3IhSVOCUBFf5PoZPRitWH0nPu5nz/kzyAR9n@M/T2nRYBVFOmGs/FgnD/JoorlM2ddZQ7K8122HlpY6YPYK@ucr@V56TI4ONSBveUR12aX1D7dDq9ulSM5ebB2hHBWQEi2rCIcJWJmgRNYeUdqo/orgIs5CoMkhv5ldIgo6cNUv@0mmekMs@oYZ51vBs2U32abNuMuJ5aadKR2qRlmxZZ9jq3ad2x@2qlOutcShm2xoVFnvzUEDd6trjR88RNSkXwjeoMUXi/dIAX@Ws9mb0VX1cFqVNwxrB6m6HiyExrZ45AKu1@93erAtvOzkmpdrzNzdxUI62BTfIiKIxhC31aAhX0RelKa1fjYKK9YffsOCz8ZgyH13UzUE9hySRrLki6m4j/R/6nf4HTk8D@QaUDseCkgl2vCaojM9XKul7vJololeuvmn7YRFBQUCxmVAfGNdUy6XFl4ucWrwLLB5HW5G8R16qpFPyfF34KEcogx@aeZzsjeq11G3n8lCqfMWqJv/wMbkRgqVQYR20c9k5h9K5IVsmIerWHTsaqlAzHT7Daa8w5SuVK6VEtZKotyvOopWurdd@KVZx1l6pUajTTGM9oCTqozaWYeaNbvoCFGcXgsztMyGA@N30bVi7zwQuCW7oPoLFarNLMoTfkO@0TR70tLZEqo1w1WtQwVDndSW2w1xw1lcgNu2gqvG03l5Ln9XgN67ZBZB3LfLhRLCobknZZaF6KWfK1cDT5OAsDXcXrR7tm5T66jiCtSW5q2eOT3Kglo3GrDlMFZmVmUzBaNzC0Dy5uN0/v181hAEeBdJquUNrMMRMvJvxUrLiZSGdC@tLWxGU@Vso@6EHencxNnIHEzYEZzqwB0GG@t0c/ltmtRk8sYYEcQfVmg5T8EpkzNoaXkeCk0/Xgd1@MMcTi2/AailsPMEDee2id3y4uz/fAoYuVYMH8nsQ2rgewE07FxqVkh5x89eXysiH6ven7QQxEDVGQhBYDBzMevr2MrvVCAeO67JK6GuXu4jjtLWiki1ic1aMBDAdwjBRo2PR@yLTpPMvvhGQPEiR0XSiPT8knPYG6DpVSJ8vvUuQLQgcJ7eqpm3UGR9QZOFRhyRDluihTMSPtRnHoW/MFWoXuCXcGueqod3pBUmidtcGaTHSQk5Fc7VeqjII/5XWTv/pYLF0QUOLU22BokTHZRoaxkYzJVvsYbSZjq30cbSJjsp0/jjeTsdU@Xm0kYzt/vN5Mxlb7@GkDGZMt8@PNZjK22sfbjWRs5w9juJmQ7RLdSCtjO/ctU8MYPZP7drofPY/7luY/fib37XR/9Rzu1NgoS5CS5eviNjvnmtXSMyJWNEaf7v3YvAPxXmWcNdEwT3D8EHe6sOKxC7tUC3dFM5KpXar@uURaSAXKew5NVj@5s9JEVR@o1rQJ5TE1f6xe@9Q5peV@SOU@u@poXHTkCwXSaB3SqIR0hEidyupR7cIhVVQ0RI7lBRHL2g3166mSJ8jE@adLtj6/Y1YSUy8hGjFdL3eDshmT77FkM4ONMPe5bEOze3mx0HjHULQQa18tpBf6aZ/UHLjqr44ku7RNa6B3189nFB/dtW9narlUHt5qHbuWteRD6sfPrz5omnzLTkxFL02v2RH@KAxNRdKVtnbFs@s@CqLZ/j4cfDU9r3g9fxCId8aafiheMucMH4f/Aw "Bash – Try It Online")
### Explanation
```
AHHH Start program
HhhH Increment cell to 1
HHhH Double cell to 2
HHhH Double cell to 4
HHhH Double cell to 8
HHHh Square cell to 64
HhhH Increment cell to 65
HHHH Loop while cell is nonzero:
Hhhh Output cell as ASCII character
hhhh End loop
```
[Answer]
# [Vim](https://github.com/DJMcMayhem/V), ~~14~~ ~~7~~ 10 bytes
```
qqiA^[@qq@q
```
Added 3 bytes to fx a bug kindly pointed out by [David](https://codegolf.stackexchange.com/users/52622/david-ljung-madison-stellar).
If you fire up `vim` (with no command line options) and type in these key strokes (`^[` is the esc key) then the screen will fill up with `A`'s.
Explanation:
```
qqiA^[@qq@q
qq Start recording macro-q
i Enter insert mode
A Insert A
^[ Exit insert mode
@q Call macro-q from within macro-q
q Stop recording macro-q
@q Call macro-q
```
### Note: You'll probably have to `kill` that session of `vim` to stop it!
You can try to stopping the macro with ctrl-c, if that works you can exit with `:q!<Enter>`.
[Answer]
## Apple II 6502 Assembly code, 7 bytes
```
L1: A9 C1 LDA #'A'
20 ED FD JSR COUT
50 F9 BVC L1
```
[Answer]
# [Piet](https://www.dangermouse.net/esoteric/piet.html) + [ascii-piet](https://github.com/dloscutoff/ascii-piet), 12 bytes (2×6=12 codels)
```
ttttlIauqasj
```
[Try Piet online!](https://piet.bubbler.one/#eJwliUEKgCAURO8y6xGUSsKriIuwHwhWgrWK7t6HZhZvHvMgn6sgxGj519PZxOg8J45UDJxTIro0BBhjQNSy63ZWoyY9I2xL7UKUo92Xfng_8LwXAw)
In grid form:
```
ttttli
auqasj
```
Represents the following Piet program:
![](https://raw.githubusercontent.com/Bubbler-4/svg-stuff-and-tools/cc815c7cc08e68b661d1dfd1c8747993e7eb3ec6/images/CodeGolfSE/200306.svg)
### How it works
![](https://github.com/Bubbler-4/svg-stuff-and-tools/raw/313ff4bdc5abac91e2312359b2fb864513ce697c/images/CodeGolfSE/200306-e.svg)
```
pointer command stack
t<4> -> l Push 4 [4]
l -> i Dup [4, 4]
i -> j Dup [4, 4, 4]
j -> s * [4, 16]
s -> a * [64]
a -> q Push 1 [64, 1]
q -> u + [65]
u -> a OutC [] Print 'A'
a -> t % [] Stack underflow; ignored
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 20 bytes
```
A(){A(putchar(65));}
```
*-4 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!*
How could I have forgotten recursion...
[Try it online!](https://tio.run/##S9ZNT07@/99RQ7PaUaOgtCQ5I7FIw8xUU9O69n9mXolCbmJmnkZZfmaKJlc1lwIQAFVac9X@BwA "C (gcc) – Try It Online")
[Answer]
# [Hexagony](https://github.com/m-ender/hexagony), 3 bytes
```
A.;
```
[Try it online!](https://tio.run/##y0itSEzPz6v8/99Rz/r/fwA "Hexagony – Try It Online")
```
A .
; . .
. .
```
`A` sets the value of the current memory edge to A (ASCII 65).
`.` is a no-op that places the next command on a new row.
`;` prints the value of the current memory edge to `stdout`.
---
The no-op is required because the instruction pointer never returns to the top row after executing `A`.
It only loops over the second and third rows.
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), ~~11 9~~ 7 bytes
```
⍞←⍣≠'A'
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn//1HvvEdtEx71Ln7UuUDdUf3/fwA "APL (Dyalog Extended) – Try It Online")
-2 bytes from Bubbler.
-2 bytes from Adàm using forbidden hacky APL magic.
Older answer:
```
{⍞←'A'⋄∇⍵}0
```
### Explanation
```
{⍞←'A'⋄∇⍵}0
⋄ separator (arguments will be evaluated left to right)
⍞←'A' Print 'A' without newline
∇⍵ Call function again with the same right argument
{ }0 Call first time with 0(any number works)
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/v/pR77xHbRPUHdUfdbc86mh/1Lu11uB/GlDoUW/fo67mR71rHvVuObTe@FHbxEd9U4ODnIFkiIdn8H8A "APL (Dyalog Extended) – Try It Online")
[Answer]
# [Malbolge](https://github.com/TryItOnline/malbolge), ~~2163 2069 1881 1787~~ 1693 bytes
```
b'a;$9"~}HG{iyxwuu?O=pL:]mHj5!3DCezRQ=+^:('&Y$#m!1So.QOO=v('98$65a!}^{@hyf<WV9sr%4#I20FEJVBfw)btOr@#!7~|4{y1xv.us+rp(om%lj"ig}fd"cx``uz]rwvYnslkTonPfOjiKgJeG]\EC_X]@[Z<R;VU7S6QP2N1LK-I,GF(D'BA#?>7~;:9y16w43s10)p-,l*#(i&%e#d!~``{tyxZpuXsrTTongOkdMhg`Hd]ba`_^W@[ZYXW9UNSRQPOHMLKJ-++FE''<A$?>=<;:387xw43s10/(-&m*)('&}${d!~}|^zyxwvutmVqpiRQlkjiKafedc\E`_^@\[ZYX;V9NMRQ42NGLK.IH*F?DCBA$#>7~;{{8xx5uu2rr/oo,ll)ii&f|e"!aw`{z\r[vXnmVTpongPkNihgJ_dcFa`B^]\UZ=RWV8TSLQ4ON0LE.IHA)E>'BA:?!7~5|38y6/v321q).-&m*)i'&%|{d!~}_{zs\wvutsUqTonPlOjiKgJedFbE`_A]@[Z<X;VU7S6QP22GL/JIB+FEDC%;@?>7~;:987w5v32r0)p-,+k)('~g$#"b~w|uz]xwvutsrqTinQlOjLhgfeH]bE`CB]\>ZSXWVUTSRQPON1LE.I,+*((&&$$""~~||zzxxv4u210/(-n+l)(i&g$ddy~}`u^]\ZZotsrTjShQOOMMKgfeG]F[DB^]?[T=R;9UTS5K4I200..,,*F)DC&A:#>=~;|9yyx/vutrrp.-,l$k"i~ge#"!aw`u^\\ZZXXVrqpRhQfOMMKKIeHcbECC^W\?>=;W:UT7R5PIN1L/.,,*FED&<%:#!!}}{987w/v-trrppnnllj(i&%ee"!xa|_^\x[vutWrqjSnQPNNLLJJHHFFDDB^A\[==XWVOT7R542N1LKJ-HGF?D'B%$""~<;:z2y0wu321q)p'nl*)(h~g|eccaa__]][[YuXsrTTonmleNiLgfeG]F[`C^]\?ZYXWP9T76442NML.D-B+)EDC%;$9"~<;:z2y0wuussqqoommk)j'&ff#"!~}v{^y\wvXtmVkpSnmlOjihgf_dGbEDBB@\?==R;PUTS5K4I200..,,**(DCB$:#8!}}{{yyw5v321r/.-,+*#j'h%$#cybw`^^s\ZvuWslUjSQQOOMMKgJedc\E`_B]@[==<QV9T76KPON0F/D-++))'CBA#9"7~||z87w5.u,sqqoommkki'h%$#d!xa`{^\\qZotsUqjShmPkjMhKfe^cFEDYB@@>>S<:VU7SL5J311//--++))'C&A@#>!<;49z76w4u2rr).-n%lkjhhffddb~}|^t]rwZXXmrUpoRmfONihgI_H]FD`_^@V?T=;;9977553311/K.IH+))>C&%@?>~6}49z76w4u,1rq.o,+l)j'~g$#d!b}__^yr[ZuXsrUSSnmfkjiLKfedFbaDY^A\[>Y<WVOTSRQ43H1FKJI+A*?(&BA@"8!6}{987w/v-trrppn,mkk"'&%e{dyb``^^\\ZZXXW22}Rn-O>Nvu(IeH6F[`~1A@hZSRuc9rrqK4\lMkK-CHAS(ubBN:L!J6}kXW1wfv3Prr`;o,%IH(4~}|d/@Q>v{;(\wZ$W4V1}/R-PxjvuKf_$G#nZ}B|z>-xwQc88qR^nO1GL|JVyGeEca&$$?8[6|GjWxg/AR2POq(o,JH6j4&C$0@@-a`^:y[q6H54rq0BR--N*chJ&_%cF!CY}Ai.-wwWV(s6%4o\lZkKDz,fdRQ
```
[Try it online!](https://tio.run/##PZTnmvEMEIb/f2cRgqghWrBaEKKL3oVEjRZSiDj1/SZ23z2B@3rmnmfmyInLs7gRvr@XDi6Bxixvo1TUdw9NleV0I3mpxqfH0j6MBPM54cm2ku5ZHHPYh6j1iATaZ1@r0UgqmCNGopEwhxgzPbN9rL/6vdhNsoWsDOGnC@UetVady3tDyliR6PsV0h8BTfHJN7d0wc5Hm7i37DbGmrestMVCfk4lVRmebuKhcz411439rrIpC8XppJCbD6aZ8eiLTfS60Xak1STqgWrFy3iKNJZ3UFlrOhV9J@KxRyCihoK3gN958XpElxXb2W2ClUfei4V@f2ijizy4SR2gbxoHvrbdLEr8dMkt5rM@0IeDfqxbb7OtZqNUq1bKXrebLjgcX1k0nUp@JeJBMqr90HHMaz@6nCDDQHWgG6/ZE6wp8v3Yu152bEs8QHZuLfCrSQHomYlJT/Ri9RrbChH1YrXiY0ouOp3PUVnUambXdVLTwrJMSBJ@PntE0bnb2dcvwYJw6kJ/TqSxMjgde50LZG8e6rvtpjznVzS3oGbTSXeUZPs9stOutkKNur9aAHrWWUiBmXgavIdfQfIRwZUgEbg6fZ/sO4fd9vpkn@vP28TMfuteTe/ir3eeXkL27Mf74M87UaziZYYCM/mcLZH59U5G1TDQpY939wHMvDeo1bJ8qy/Y6sfMTbp2dqcW0KvbzVooTYGeo6aT1Kg96Pe6nY932Cpk97hdGGa3o6jF8n6/Xs@npikhmfh4P7lFJ2x1g/L8420sZJh@NBoMetL1wm5b60atVqkwQommx6b3XrozNBvZqUH2INB9Pi/ldjkdDpvNakUQw9D1x0MNw1bdkvNyOomw1e178xJWyNJ4zadT7apALz5mzOyrbWXNAD3/S08mErFYFLIHGaLo9/k8HpeZnbJl0gjylQjp5OM3@9X0Lh5M74LOP5aLxWw2@cne63RY9uO9Wi6bneHyuVk2/S97FMww9YC/AvQs7cznwIzZyPAL6KrqC95N@hmsOS1gZq1bVhynzM2@K@fBUepezOzQyC23ZvgiPc4P/@hd8rfvfuh7yU1jGHQGtpqMGC9zq7jivUt@/AzZ0cNut9kIwgroczAzVkfyvd816TCXaabMFM1GQvZP3/u9RicaCQeDgQCO5xkwkzZvFU2TyJcBndH8KnyC2/V6/tzqHtmu4RPArUL26Xg8HPZ/vB@bAvQdvPOfrVJwq6lkArJHa5FKiCD8H@9g5t@tRoy4TkYj8Gc8tyvu88Kfse63Jp1f/njXxorc74tAZyF7bVU1zayWhdGcyk7SIzAT79bBe6hB1HDcB313FbAcBZ0Butn3RyQsB4mbCzf7Do1E7DZU@KOrcKt9sbtvt@BH1uBWmXlpSufzFJXJpEbQmWaMvLJn63Fcq@7LvUe2zcv2L/RqIcvQyCehqaoQXDU4/HzykAcreM91BctjycGKwTuDhvoSkWPZZ/pQd23vMfssch4fc5S@gzeUUO6kIxKGPzMe@X1bxq0JiuPeQGfW8/idGA5IbaOGWqsAd/FVTm7GStN2IyfgLMclXbW4pEbR8FEiDPbkbaTqiozBNUXA@zuQzWxHbVZexSTpWglNxNqh4s2Vsm1MXlL1eBUpR4zDoB9Q10qwKUmLxNlTLpWwEHxHHs@0UoqewCbqCO2HegEDZ71Nba9sy/Y5uqKRkUG9nimvprZWJJiZnRqBYvUFZooC2/rv@/t/ "Malbolge – Try It Online")
-94 bytes thanks to @user100411.
This was built with [Prof. Masahiko Sakai](https://www.trs.cm.is.nagoya-u.ac.jp/%7Esakai/index.html.en)'s [LAL](https://www.trs.cm.is.nagoya-u.ac.jp/projects/Malbolge/lal/lal-def.html.en) toolchain from the following source code.
```
PROGRAM_START_TO ENTRY@Argh
ROUTINE Argh {
ENTRY:
ROT A
A: 0000021020t
REV JMP
REV_JMP:REV JMP
OUTPUT
DUP
JMP REV_JMP
}
```
[Online LAL assembler](https://www.trs.cm.is.nagoya-u.ac.jp/projects/Malbolge/lal/on-lal.html.en)
[Answer]
# [><>](https://esolangs.org/wiki/Fish), 4 bytes
```
'A'o
```
[Try it online!](https://tio.run/##S8sszvj/X91RPf//fwA "><> – Try It Online")
### How it works
The instruction pointer begins at left, and its initial direction is to the right.
`'` starts string parsing mode. Everything until the next `'` will be interpreted as individual characters, that will get pushed onto the stack. So `A` pushes that character, and then the second `'` ends string parsing mode.
`o` pops the character from the stack and outputs it to STDOUT.
The instruction pointer has now reached the end of the code, so it wraps around to the initial position and keeps moving to the right, causing an infinite loop.
[Answer]
# [Burlesque](https://github.com/FMNSSun/Burlesque), 3 bytes
```
@'A
```
[Try it online!](https://tio.run/##SyotykktLixN/f/fQd3x/38A "Burlesque – Try It Online")
`@` is an odd operator.
* For integers, it converts to double (`@1 => 1.0`)
* For two letters, it pushes both to the stack individually (`@az => 'a, 'z`)
* For characters it prints the character infinitely as a string (`@'a => "aaaaaaaaaa...."`)
* For anything else, it does nothing and just remains on the stack (`@1.0 => @, 1.0`).
```
@ # A symbol which does odd things. For a char, it repeats infinitely.
'A # Literal A
```
[Answer]
# [Unreadable](https://esolangs.org/wiki/Unreadable), 208 bytes
>
> '"""""'"""'"'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'"""
>
>
>
[Try it online!](https://tio.run/##K80rSk1MSUzKSf3/X10JBNTBWF1pyCOl//8B "Unreadable – Try It Online")
Explanation (`A` has codepoint 65):
```
'"""""'""" while(1≠0)
'" print unicode character number
'"" (×64) 1+1+1+… (64 times)
'""" 1
```
[Answer]
# [Piet](https://esolangs.org/wiki/Piet), 30 26 Codels
It's a .png 13x2 codels, a few are technically not used (4 white unused, 1 white as transition and 1 black to change direction). But since I don't know how to compress it further, I still count them.
Original file (codel size 1):
![Codel Size 1](https://i.ibb.co/ySwXs1P/v2-cs1.png)
With codel size 10:
![Codel Size 10](https://i.ibb.co/QDs6cFz/v2-cs10.png)
For some reason, the codel size 10 looks disproportional. Maybe it's an issue with the [IDE](https://gabriellesc.github.io/piet/)
Pseudo code (incl. stack):
```
push 2 | Stack: 2
push 4 | Stack: 2, 4
push 2 | Stack: 2, 4, 2
push 4 | Stack: 2, 4, 2, 4
* | Stack: 2, 4, 8
* | Stack: 2, 32
* | Stack: 64
push 1 | Stack: 64, 1
+ | Stack: 65
dup | Stack: 65, 65
out(char) | Stack: 65 | Output: A
```
dup and out(char) are repeated indefinitely.
[Try it online!](https://tio.run/##bZK9SgQxFIV7n@IUYqNFfuenEZJJVrdQRHQVbGwsxMbCQixEwdZCfQMFRdGFbWxkEZIH8hHG3JlVdwfD5UxIMl/OvTfHhwcndc06A0UJzaA8VA7mwAy4IU1bk3BQJVQBpaAFvj7HG@srSX8DoMX@qtucm2VzNkP5mwuwAiz7WykkrIPO0LJanaaH8aADFwymnGGSSwXFoRXyxOfwFSWTezhBZ8LzxKozW6fpG1@TnMfbDln@MOUsUzlUnCLlUqVd1mShaAIIgq7Fy3hJ4AvWmmcdtEq/SfCyCQeRwVpKW2vwHiyHsKgUMgvH6aT0kL@VWAgfg22qxWgxXh3FG7ncoac@@hy6QK5IvYSo4CQqByOgm/72ONHLnK4xDvFp92Q3PizFu3gd7nfI@@iI9Cq8dehZKriBUGRTW3CPMtVEgGuqVW5gPHyG3lRbw8t8GO217i318iwM42N875Dz5jCVWjcPUREqkdONhcD/o@/XXRja/USt628 "Piet – Try It Online")
This is my first submission here and my first "real" program in Piet. I'm sure it still has some room for improvement, but I just wanted to share (what I think of as) a lovely language :D
Edit:
Compressed down from 15x2 to 13x2.
[Answer]
# x86-16 machine code (DOS 1+), 8 bytes
Disassembled listing (`objdump -D -bbinary -mi8086 scream.com`):
```
0: b4 02 mov $0x2,%ah
2: b2 41 mov $0x41,%dl
4: cd 21 int $0x21
6: eb f8 jmp 0x0
```
Output (DOSBox 0.74, and a lot faster than it looks):
[![](https://i.stack.imgur.com/fVY6H.png)](https://i.stack.imgur.com/fVY6H.png)
Here's my ldscript and command-line options for anyone interested:
```
OUTPUT_ARCH(i8086)
SECTIONS {
. = 0;
}
ENTRY(_start)
OUTPUT_FORMAT(binary)
```
commands:
```
as --32 scream.s -o scream.o
ld scream.o -Tldscript.lds -o scream.com
dosbox ./scream.com
```
and unmolested `scream.s` file:
```
_start:
mov $0x02, %ah
mov $0x41, %dl
int $0x21
jmp _start
```
[Answer]
# [Common Lisp](http://www.clisp.org/), 15 bytes
```
(loop(princ'a))
```
[Try it online!](https://tio.run/##S87JLC74/18jJz@/QKOgKDMvWT1RU/P/fwA "Common Lisp – Try It Online")
[Answer]
# [Clojure](https://clojure.org/), 16 bytes
Another Clojure version saving 2 bytes over previous solution, posted as a separate answer because I don't have comment rights yet.
```
(while 1(pr 'A))
```
[Try it online!](https://tio.run/##S87JzyotSv3/X6M8IzMnVcFQo6BIQd1RU/P/fwA "Clojure – Try It Online")
[Answer]
## [Lua](https://www.lua.org/), 22 bytes
```
::a::io.write"A"goto a
```
[Answer]
# [Pyramid Scheme](https://github.com/ConorOBrien-Foxx/Pyramid-Scheme), ~~111~~ 98 bytes
```
^
/ \
/do \
^-----^
/1\ / \
--- /out\
^-----
/ \
/chr\
^-----
/ \
/65 \
-----
```
[Try it online!](https://tio.run/##K6gsSszNTNEtTs5IzU39/18BBOK4QKS@QgyI1k/JBzPidEEAKKVvGAOTBQoAWfmlJWCVMDUoupMzihC6ucDC@mamQBIs8P@/MZcJlykA "Pyramid Scheme – Try It Online")
# Edit:
98 bytes thanks to @Jo King and height-0 pyramids. Also, `chr 65` is truthy.
```
^
/ \
/do \
^-----^
-^ / \
-^ /out\
-^-----
/ \
/chr\
^-----
-^
-^
/ \
/65 \
-----
```
[Try it online!](https://tio.run/##K6gsSszNTNEtTs5IzU39/19BQSGOS0FBXyGGS0E/JR9IxemCQByXbpwCVBzI0s8vLQGygEywLFxHckYRTAdQA0gpF1hG38wUSILF//835jLhMgUA "Pyramid Scheme – Try It Online")
[Answer]
## [NDBall](https://esolangs.org/wiki/NDBall), 52 bytes, 7 instructions in 2 dimensions
```
(0)>0
(1)+
(2)Y[65,>1,>0]
(3)p
(4)<0
(2,1)<0
(0,1)<1
```
[![Program](https://i.stack.imgur.com/dg2iy.png)](https://i.stack.imgur.com/dg2iy.png)
In essence, this just loops the ball on an add 1 loop until it reaches 65, then it bounces back and forth over p repeatedly printing "A"
[Answer]
# [Bitcycle](https://esolangs.org/wiki/BitCycle), ~~25~~ ~~16~~ 14 bytes
```
~1000~!
>0010^
```
[Try it online!](https://dloscutoff.github.io/Esolangs/BitCycle/?p=z103zbre0210n)
Output as a stream of bits. -9 thanks to DLosc. -2 thanks to JoKing.
[Answer]
# [Java (JDK)](http://jdk.java.net/), ~~85~~ ~~77~~ 34 bytes
```
v->{for(;;)System.out.print("A");}
```
[Try it online!](https://tio.run/##LY1BCsMgEEX3OcWQlS7iBaSFHqDZBLopXUyNFlOjIRqhBM9utc1mhvnM@2/CiN00vrMw6D1cUdu9AdA2yFWhkNDXEyA6PYIit7oi5SVLTRk@YNACerBwyrE778qthHM6fHyQM3NbYMtaykh7aSlPmVdo2Z6mQAf7a56LlwyhvL7uD6R/p2WK2M2YQ5fyFw "Java (JDK) – Try It Online")
Massive thanks to @Kevin for the lambda solution. I really need to learn how to do that.
## Old Answer
```
class M{public static void main(String[]args){for(;;)System.out.print("A");}}
```
[Try it online!](https://tio.run/##y0osS9TNSsn@/z85J7G4WMG3uqA0KSczWaG4JLEESJXlZ6Yo5CZm5mkElxRl5qVHxyYWpRdrVqflF2lYW2sGVxaXpObq5ZeW6BUApUs0lByVNK1ra///BwA "Java (JDK) – Try It Online")
It's a full program and can probably be golfed if I knew how lambdas work in java. Oh well.
[Answer]
# [Perl 5](https://www.perl.org/), 15 bytes
```
print'A'while 1
```
[Try it online!](https://tio.run/##K0gtyjH9/7@gKDOvRN1RvTwjMydVwfD/fwA "Perl 5 – Try It Online")
[Answer]
# [International Phonetic Esoteric Language](https://esolangs.org/wiki/International_Phonetic_Esoteric_Language), 9 bytes
Derived from my answer to ["Shortest code to produce infinite output"](https://codegolf.stackexchange.com/questions/13152/shortest-code-to-produce-infinite-output/206214#206214).
```
"A"10ɑbuɒ
```
## Explanation:
This works because the `ɒ` instruction don't do anything with the loop index except to check if `index < limit`. If it is, it loops back to its associated `ɑ`. Otherwise it exits the loop (index manipulation is handled with `e` adn `ø`).
```
"A"10ɑbuɒ
"A" (Push "A")
10 (Loop bounds: 0 to 1)
ɑ (Start loop)
b (Copy top)
u (Print with no trailing)
ɒ (End loop)
```
[Answer]
# [Alice](https://github.com/m-ender/alice), ~~4~~ 3 bytes
It's a pretty simple Cardinal mode answer.
-1 bytes thanks to Martin Ender
```
'AO
```
[Try it online!](https://tio.run/##S8zJTE79/1/d0f//fwA)
## Explanation
```
'A - Push "A"
O - Output as character
- The IP wraps around to the left, and repeats.
```
] |
[Question]
[
# Challenge
The goal is to output `Buffalo buffalo Buffalo buffalo buffalo buffalo Buffalo buffalo`.
[Context](https://en.wikipedia.org/wiki/Buffalo_buffalo_Buffalo_buffalo_buffalo_buffalo_Buffalo_buffalo). (Maybe another interesting challenge could be printing all of the [other examples](https://en.wikipedia.org/wiki/List_of_linguistic_example_sentences#Lexical_ambiguity)? This would probably use similar logic but involve either a function or just a for loop.)
# Rule(s)
1. You cannot output anything other than the string with correct casing and spacing. Trailing new lines are allowed, trailing spaces are not.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so fewest bytes win!
[Answer]
# [Buffalo](https://bfalo.com/), ~~2711~~ ~~2571~~ ~~2517~~ ~~2447~~ ~~2279~~ 2183 bytes
*It takes 304 buffalo to produce 8 buffalo?!* Yep, you herd that right.
```
BuffaloBuffaloBuffaloBuffaloBuffaloBuffalo(buffaloBuffaloBuffaloBuffaloBuffaloBuffaloBuffaloBuffalo(buffaloBuffaloBuffaloBuffaloBuffaloBuffaloBuffaloBuffaloBuffaloBuffalo(buffaloBuffaloBuffaloBuffaloBuffaloBuffalobuffaloBuffaloBuffaloBuffaloBuffaloBuffaloBuffaloBuffalobuffaloBuffaloBuffaloBuffaloBuffaloBuffaloBuffaloBuffalobuffaloBuffaloBuffaloBuffaloBuffaloBuffaloBuffaloBuffalobuffaloBuffaloBuffaloBuffaloBuffaloBuffaloBuffaloBuffalobuffaloBuffaloBuffaloBuffaloBuffaloBuffaloBuffaloBuffalobuffaloBuffaloBuffaloBuffaloBuffalobuffaloBuffalobuffaloBuffalobuffaloBuffalobuffaloBuffalobuffaloBuffalobuffaloBuffalobuffalobuffalobuffalo)buffaloBuffalobuffalobuffalobuffaloBuffaloBuffaloBuffalobuffaloBuffalobuffalobuffalobuffaloBuffalobuffalobuffaloBuffalobuffaloBuffalobuffaloBuffalobuffaloBuffalobuffaloBuffalobuffalobuffalobuffalo)Buffalobuffalobuffalobuffalo)buffaloBuffalobuffaloBuffalobuffaloBuffaloBuffaloBuffaloBuffaloBuffaloBuffaloBuffalo.buffaloBuffalo.buffaloBuffaloBuffaloBuffaloBuffaloBuffaloBuffaloBuffalo..buffaloBuffalobuffalobuffalobuffalobuffalo.buffaloBuffalo.buffaloBuffaloBuffaloBuffaloBuffaloBuffaloBuffaloBuffalo.buffaloBuffalobuffalobuffalobuffalobuffalobuffalobuffalobuffalobuffalo.BuffalobuffaloBuffalobuffaloBuffalobuffaloBuffaloBuffalo.BuffalobuffaloBuffalobuffalo.buffaloBuffalo..buffaloBuffalobuffalobuffalo.buffaloBuffalo.buffaloBuffalo.buffaloBuffalo.BuffalobuffaloBuffalobuffaloBuffalobuffaloBuffalobuffaloBuffalobuffaloBuffalobuffalo.buffaloBuffalo.buffaloBuffalo..buffaloBuffalo.buffaloBuffalo.buffaloBuffalo.buffaloBuffalo.buffaloBuffaloBuffaloBuffaloBuffaloBuffaloBuffaloBuffalo(BuffalobuffaloBuffalobuffaloBuffalobuffaloBuffalobuffaloBuffaloBuffalo.BuffalobuffaloBuffalobuffalo.buffaloBuffalo..buffaloBuffalobuffalobuffalo.buffaloBuffalo.buffaloBuffalo.buffaloBuffalo.buffaloBuffalobuffalobuffalo)BuffalobuffaloBuffalobuffaloBuffalobuffaloBuffalobuffaloBuffalobuffaloBuffalobuffaloBuffalobuffalo.buffaloBuffalo.buffaloBuffalo..buffaloBuffalo.buffaloBuffalo.buffaloBuffalo.buffaloBuffalo.BuffalobuffaloBuffalobuffaloBuffalobuffaloBuffaloBuffalo.BuffalobuffaloBuffalobuffalo.buffaloBuffalo..buffaloBuffalobuffalobuffalo.buffaloBuffalo.buffaloBuffalo.
```
[Try it online!](https://tio.run/##7Vlbb@M2Fn73r2CnRi1NHDst0H2I47TJTNIam9qDXHZQBIFBybRNjCxpJSpOtuvfPnt40V2U5Exmb6geYok8PPzO/ZDx1/7nk5/8td8Zvn3beYvOo@USOx66wu4KTVxGAj8g8Bd9@PVDhxP8jQQh9Vx0NPhefL/HLiUO@oU@uuQZrRnzj4fDFWXryBrY3ma4WIkZQXtFbeKGZIEidwEs2ZqgMx/b8KNm@gn7HwZHyOAEb9TUG3MEHJ69CG3wM3I9hqKQAAsaoiV1CCJPNvEZoi6CXX2HYtcmaAs4xDaKyQBY/K5YeBbDQI2B3oevZZYOYSYAK3G22@0AC6ADL1gNHUkUDq8m7y6mNxeHAFaQ37kOCUMUkL9HNAAxrWeEfcBiYwsQOniLvADhVUBgjnkc6zagjLqrPgq9JdvigACXBQ1ZQK2I5RQVIwN5swSgKuyiN2c3aHLzBp2f3Uxu@sDj4@T219ndLfp4dn19Nr2dXNyg2TV6N5u@n9xOZlP4ukRn09/RXyfT931EQE2wDXkCWwN@AEm5CsmC6@uGkByApScBhT6x6ZLaIJe7ivCKoJX3SAIXxEE@CTY05IYMAd4CuDh0QxlmYqQk1EBo72eHup@QepTmLe6M3I8081WOxgkl1AxhKxMOO7aDQQEqCDLu3/mj0@HceJAItmAmsqQuqMHbEHAhN2TYZaGaHIpfMYpu5@9mv/12Mb1FY9RLPnqjHMn53eXl2dVsfvfucnJ9o0gLg5olV7OPF9f5BWKoQA7e8OFOMZbvBYKr2ezD/Pzil8lUEqXfVYQX0/cZMvgCoqKG5sz7BFpWn/Hoz48YgiAIIAS7igKB0j2bYu7QDjg3j0bfA//hYROTuAvuMhQc59kneUX7gceIzVcnHMdyC6MTO0xInOXxcYWmT4uU/OmFzy7DTz0@3VPu0EsozL6WrbJGM1OrBdPYZs3cBrV8sqZt5mU08xLWb@ZkZjiJN7PCScB4qwBv6rxEkXAP5Dk7FLkjHrSIyDg44IUFhzyhr@O1Wi@JF4@RGzlOBSpuHgj7ClA898KGXUWSB2VHQUBc5kDitxl9JEgRQarfkI0X6BEpQi2gkP6DVMGhkKRWsLArKKCyPQGHjQUjEER4seAZXZSfELIfCVsgEXzG6Icf/1IBI7e20liSotJWodpaYtECUERxCFc6jcflDmqdRpLkgYRktQH7ZOwkyeJ63KCamGcdtKWDV7U5TxAUYD2HjGzAtSAFoiyDMgS5ugaADMAaAJIgD0BkTbD7Qi1HDJoUhJeMSA8TZVCU7zywyIJKmrDUOe@CWNGqCpHleQ6B/qUrKEBO2EtoIVR7E6jYiMKbfm@5dAyII1JhjrkoW0FkMzAuW3uLIg7IHHiTRHU@G8WzeZzJJOgkClz06NFFFbRl5NocdhaE0U1TT6/XT@FDMQiJzJJ/JFmzy/vbw9OYRhKPitMi9yWMTTm/K6sCUgFhl8J/6lSh3OQTeQ6bJU08MxU23cYQTFJnLYpHl8j4RtCYmVEhWW5hbipbjFQz1dcSFKp9M6Go33oyWZH182mlbaCBCpojMFOr7lL7ClXGapjDOceZc8VIvfbRkVnyhXx@gFQarMA1snN9xVbvJ3Ey0HjJPr4QszJKni3r3RVxV3BEG/P4c4ibIJWzcXbjDxw7eDJIKJLOESSHhpD3G10xxl0p70tiuLwTH72P@5WH7F6xb@ZWnuYxFz1WdchwmuNpKDu6KzMOIwtgzPlJFc58Ban7qIitjw6zUEw0Ho/B@EVBE9g53Z7mFFBawJ/vvkNdwCIqI0@kdKMQlpAdFaGYlSgyDilluH/QB7MmqDUNZvHJNpyxENoFZuWMOSoN78oy7SVPwSc7LbbMq1qUh1EZhQy@ooPl3ypCOqnhZ47zCmGdZWdoilamWToqp6l8jydSm3HUT6Z5D1qd3zLVpWI2AWbkzKXPdcmCNiVRtTm3omOTbZIH54@0QyKLwsINfQLFGaK4/1O16iZ0GUo1H9fERVaAXXvNuw8Y9OD84nieH/OBR9xx5bq1uItWzawEQR6xE4kjNGaCirPphYi4i6KNJSpuaY5pVQYi6eRm1F2QJ86T88uya@EeRtoZqhagnwqv6XlEBlNmK@YWKAJGVwLiXoXU@wmoJ3KT3cx44uCgMjuFW8qgkkANjVfcS/oHfTb7Fl2B@OicrKhbSWDjkFS0AcfaXJTIoV4OKpxYBkfIb6tiqP2U/nuzXww2kw@PtHtaUEM/jWolvIjt2ygftDDHHe1Wwoyxqb8Zx8bW6TdfdrM54j7m8pCWPdTwKD@XmhrVku86bRiV00tijVjzI71gO0RA9gbc5Ikyo3eJGXYQCQIvOEZ3LnnyZXD10KB8BTOAYVFfeqZeyJ3O3F7E/Ig1G1v2vHpHJvbaQ/Y6KNkt75oP5kv9Ut2/NSMtdPtN3pntiu81PB6a3K1BaB7f9RQHB@iU37b82OjVP3EqdNy45agV4EwhlblZd2aqPiOZZv02yqR7emU72wgArS2T1pvCiNS8oWpHTqkmOoT02sIi2sUZO8UA/oft8i2y9g1Cgeb432fmFwfg4SE6gbrSwthHfwbf/olRG34v0/v/QTAtyBJHDqtpDXMGqOpTH9DBuEWjV9/s7KpuPNILxyoDi1rfO4EW6JR3JOLCdl6s/H1xF2vy9uRkKEhH@zJSVv5yTnGbVs8nowndEVpcsr7oCrntLXH@GldcAGiO1sVDVfkcnDLh90yh71CWvSDuVIV7PF1x6MrdvMW8@dWbOsPwq5c1Dqo8pnCtMRhLUv39R3plqL/l0J/7xYVEfNrfdVyyrfhvvnFycqLi/LOabfFjWK1JX2nhi9m8dMM/1xVIXvUr/2O2oGmP0Gqe@ypC7C/hF5pwYNV97sFn0EI865X3bL9lLZy9bXfeYmFRyFqw9Ropfn6NYGrYcj@Ar2Rf4wtF@w@bqY6T@fXT49e06H@9KT6rfsQcff4X "PHP – Try It Online")
Link is to a Buffalo interpreter written in PHP (the header is copied from [GitHub](https://github.com/bfalo/buffalo-lang/blob/master/interpreters/PHP/BuffaloInterpreter.php)). You can also copy-and-paste the code above into the [official online interpreter](https://bfalo.com/#showcase).
Buffalo is a cell-based language like brainfuck or COW. It has seven instructions:
* `Buffalobuffalo` and `buffaloBuffalo` move the pointer to the left and right, respectively,
* `BuffaloBuffalo` and `buffalobuffalo` increment and decrement the current cell value, respectively,
* `(` and `)` begin and end loops, and
* `.` outputs the ASCII character corresponding to the current cell value.
Aiming to get the ASCII codes of `Bufalo` into successive cells, we first do a coarse initialisation using three nested loops. A correction is then applied to each cell (outside the loops) as necessary. The selected iteration counts (3 for the outer and middle loops and 4 for the inner loop) are apparently [optimal](https://tio.run/##hVRNb9swDD3Pv@KtBtakdb1@3ApkQ7dTD90OuwwIgkG26VaJLbn6SJcl@e0Z5bhulg4pgQhi/B5FkY8yPltsNjHupJK1r6F8nZGBLqEbMsJJrSwMPXppqIDTuCeHmx9fb2@R64JsQB5/8aWoNI4hFSOsz3OyVs4JOVWVjSJD1lfOYoTlGjFmtIC0EMaIReBXWjew8g/ZBHNRefrna58HH@iVs1HJcc4@DfJEDbFEnpaFnA/UMDX8ucA6urv5yYiryyi6TH3j9ID/GKLQWMkVgsU7t5Suv6VU0J7dNp8I2GdPVwe5tSyKip7JwMUefbY6QJZKvRwcrOYrSJxg2vmK/Zr9WefP2D@HLMNmhIuQmKgq/WRRaoNGc/0zWUnXlnDqrYN70u0B4TzrSBThi3swRFEXM8a3Pj1RFPJ18y03/6VbW1ZHdpzQWCaYJphNDkb8aH3mjMi34bm7rUzavHeE1Yc9HSEopxdZmi0c2bQWTVvWbBW9G3fgYA1jy3GWQE0S7Fq8V@d3wGOLNbxmOGPmCVSCmnnxfkMZbBjyyJAaexYH2VhZbKG2z2XS7UgV/6tHo3laeFvrOdXEwsZAabcVuVT33BptiVfhoPPcm5ASzckskAtLw936vNz/khMc2NRIVdDvJVYiAZciX0HgfRDMGqcsFp7HnKfsfJi8qsqbgbJDgfZnoFNqIHzm3zWu8LbFvVREtVOdpwdSXA4y2@eBt9IUu0f1quuem3Evxwl32EXPvdiubVdqGeaqw6ft28PKkupXtgh35rKlZSWcI5VaXw8@XIvMDvmJabjhOPreOFlzjjsTMUK8fA7Hz9yAYw3XR5vNXw "Ruby – Try It Online"). The ASCII code for the lowercase `b` does not get its own cell; rather, we generate it on the fly in the `a` cell.
Once the ASCII codes have been generated, the output is printed character-by-character as `Buffalo buffalo Buffalo (buffalo )Buffalo buffalo`, where the segment in parentheses represents a loop that runs 3 times.
[Answer]
# [Bash](https://www.gnu.org/software/bash/), 28 bytes
```
echo {B,b,B,b,b,b,B,b}uffalo
```
[Try it online!](https://tio.run/##S0oszvj/PzU5I1@h2kknSQeEkyB0bWlaWmJO/v//AA "Bash – Try It Online")
[Brace expansion (Bash Reference Manual)](https://www.gnu.org/software/bash/manual/html_node/Brace-Expansion.html)
Same length, slightly more interesting:
```
echo {B,b,B,b{,,},B,b}uffalo
```
[Answer]
# [Python 2](https://docs.python.org/2/), 36 bytes
```
for c in'BbBbbbBb':print c+'uffalo',
```
[Try it online!](https://tio.run/##K6gsycjPM/r/Py2/SCFZITNP3SnJKSkJiNWtCooy80oUkrXVS9PSEnPy1XX@/wcA "Python 2 – Try It Online")
Relies on the Python 2 print magic that automagically adds a space before a printed object [if it thinks it's not at the beginning of a line](https://docs.python.org/2.7/reference/simple_stmts.html#the-print-statement).
## [Python 2](https://docs.python.org/2/) (anagol), 36 bytes
```
print'uffalo '.join('BbBbbb'*2)[:63]
```
[Try it online!](https://tio.run/##K6gsycjPM/r/v6AoM69EvTQtLTEnX0FdLys/M09D3SnJKSkpSV3LSDPaysw49v9/AA "Python 2 – Try It Online")
A trivial modification of the [anagol solution](http://golf.shinh.org/reveal.rb?Buffalo/kt3k_1265291869&py) is the same length.
## [Python 3](https://docs.python.org/3/), 38 bytes
```
print(*[x+'uffalo'for x in'BbBbbbBb'])
```
[Try it online!](https://tio.run/##K6gsycjPM/7/v6AoM69EQyu6Qlu9NC0tMSdfPS2/SKFCITNP3SnJKSkJiNVjNf//BwA "Python 3 – Try It Online")
## [Python 3](https://docs.python.org/3/), 41 bytes
```
print(*map("{}uffalo".format,'BbBbbbBb'))
```
[Try it online!](https://tio.run/##K6gsycjPM/7/v6AoM69EQys3sUBDqbq2NC0tMSdfSS8tvyg3sURH3SnJKSkJiNU1Nf//BwA "Python 3 – Try It Online")
[Answer]
# [Husk](https://github.com/barbuz/Husk), 14 bytes
```
wM?Im_ḋ162¨Ḃ=F
```
[Try it online!](https://tio.run/##yygtzv7/v9zX3jM3/uGObkMzo0MrHu5osnX7/x8A "Husk – Try It Online")
This was a simple challenge but fun :)
### Explanation
```
wM?Im_ḋ162¨Ḃ=F
¨Ḃ=F Taking the compressed string "Buffalo" (uppercase B)
M For each digit in
ḋ162 the binary digits of 162 ([1,0,1,0,0,0,1,0]):
? if the digit is 1
I return the string itself
if the digit is 0
m_ convert each character to lowercase
w Join all strings with spaces
```
[Answer]
# [Perl 5](https://www.perl.org/), 32 bytes
```
@_=<{,b,B,b}uffalo>;say"B@_ b@_"
```
[Try it online!](https://tio.run/##K0gtyjH9/98h3tamWidJx0knqbY0LS0xJ9/OujixUsnJIV4hySFe6f//f/kFJZn5ecX/dX1N9QwMDQA "Perl 5 – Try It Online")
Beats the best anagol answer by one byte:
```
@_=($_=Buffalo,lc)x2,print"@_ \l@_." # Mithran
@_=<{,b,B,b}uffalo>;print"B@_ b@_." # Sisyphus
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 13 bytes
*Inspired by [@Leo's](https://codegolf.stackexchange.com/users/62393/leo) [answer](https://codegolf.stackexchange.com/a/218298/94066), so make sure to upvote him!* and me too please ;)
```
Ƶzbε'±ˆsi™]ðý
```
[Try it online!](https://tio.run/##AR8A4P9vc2FiaWX//8a1emLOtSfCscuGc2nihKJdw7DDvf// "05AB1E – Try It Online")
```
Ƶzbε'±ˆsi™]ðý # full program
√Ω # join...
'±ˆ # "buffalo"...
ε # for map over all digits of...
∆µz # 162...
b # in binary...
‚Ñ¢ # in title case...
i # if...
s # current digit in...
ε # map over all digits of...
∆µz # 162...
b # in binary...
i # is 1...
√∞ # by spaces
] # exit if statement and map
# implicit output
```
# Boring, trivial alternative, 64 bytes
```
"Buffalo buffalo Buffalo buffalo buffalo buffalo Buffalo buffalo
```
[Try it online!](https://tio.run/##yy9OTMpM/f9fyak0LS0xJ18hCUqj85Pwy///DwA "05AB1E – Try It Online")
```
"... # full program
"... # literal
# implicit output
```
**EDIT**: I have stood unbeaten for three months... Brownie points to anyone who outgolfs me.\* Oh, and possibly some rep if I like your answer. ;)
\*Just to clarify, outgolfs in any language will be accepted. It doesn't have to be 05AB1E.
[Answer]
# [V (vim)](https://github.com/DJMcMayhem/V), 20 bytes
```
8ibuffalo <esc>xbb~5b~0~
```
[Try it online!](https://tio.run/##K/v/3yIzqTQtLTEnX0G6IimpzjSpzqDu/38A "V (vim) – Try It Online")
* `8ibuffalo <esc>`, write "buffalo " 8 times. cursor at end of line.
* `x` remove current character (the space at end of line).
* `bb` move to the 2nd words beginning from cursor (move left).
* `~` toggle letter case, and also move cursor 1 char right.
* `5b~` move to the 5th words beginning from cursor (move left). And toggle case.
* `0~` move to line beginning. And toggle case.
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 25 bytes
```
BbBbbbBb
.
$&uffalo
$
```
[Try it online!](https://tio.run/##K0otycxL/P@fyynJKSkJiLn0uFTUStPSEnPyFbgUVLj@/wcA "Retina 0.8.2 – Try It Online") Explanation:
```
BbBbbbBb
```
Insert the `b`s in the correct capitalisation.
```
.
$&uffalo
```
Expand the buffalo (buffaloes?).
```
$
```
Remove the trailing space.
[Answer]
# [R](https://www.r-project.org/), ~~40~~ 39 bytes
*Edit: -1 byte thanks to Dingus*
```
cat(c('buffalo','Buffalo')[1+!21%%1:8])
```
[Try it online!](https://tio.run/##K/r/PzmxRCNZQz2pNC0tMSdfXUfdCcrSjDbUVjQyVFU1tLKI1fz/HwA "R – Try It Online")
Chooses whether to output 'buffalo' or 'Buffalo' by indexing with the vector `2 1 2 1 1 1 2 1`, which is constructed as the zero values of `21` modulo each of `1...8`, plus one.
Sadly, trying to recycle the 'uffalo' is significantly longer ([54 bytes](https://tio.run/##K/r/PzmxRKMgsbgkVaM4OTFPQ0ddXVNHvTQtLTEnX12nOLXAFiigyeXElQTGSVD6/38A)) due to [R](https://www.r-project.org/)'s somewhat cumbersome string-manipulation functions (*Edit after reading the 'Anarchy Golf' link: still longer, but can be done in [46 bytes](http://golf.shinh.org/reveal.rb?Buffalo/pooq_1265963786&r)*)
[Answer]
# TI-BASIC, 47 bytes
```
"uffalo
Ans+" b"+Ans
Ans+" B"+Ans
"B"+Ans+" b"+Ans
```
Builds the sentence up in chunks to eliminate the need for string variables which are two byte tokens; Ans is always a single byte even when it holds a string. The strategy also minimizes use of the lowercase letters as they are two byte tokens. The final line is automatically output and you can scroll left-right for the full sentence.
[Answer]
## LabVIEW, 20 bytes
[![LabVIEW code (masked to 0)](https://i.stack.imgur.com/teu8L.png)](https://i.stack.imgur.com/teu8L.png)
[![LabVIEW code (masked to nonzero)](https://i.stack.imgur.com/PTOnP.png)](https://i.stack.imgur.com/PTOnP.png)
Graphical languages are harder to count, so here's my attempt:
* 1 byte loop termination
* 1 byte for the loop
* 1 byte for the integer we encode the capitalization in
* 6 bytes for the 'uffalo' string
* 1 byte for the mask we apply to the integer encoding
* 1 byte for the case structure
* 1 byte for the AND
* 1 byte for the left shift function
* 2 bytes for the capital and noncapital letters in the case structure
* 1 byte for the concatenate string function
* 2 bytes for format string spec
* 1 byte for the delimiter (space)
* 1 byte for the array to spreadsheet string function
And yes, how'd you know about my EE degree?
[Answer]
## Batch, ~~50~~ 49 bytes
```
@set s=B_b_B_b_b_b_B_buffalo
@echo %s:_=uffalo %
```
Batch's string handling is so poor it's golfier to explicitly include the last "buffalo" rather than trying to trim the trailing space at the end.
[Answer]
# JavaScript (ES6), 46 bytes
Builds the string recursively and in reverse order.
```
f=n=>(n>6?'':f(-~n)+' ')+"bB"[n&n!=3]+'uffalo'
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/f8/zTbP1k4jz87MXl3dKk1Dty5PU1tdQV1TWynJSSk6Ty1P0dY4Vlu9NC0tMSdf/X9yfl5xfk6qXk5@ukaahqbmfwA "JavaScript (Node.js) – Try It Online")
### Alternate version
```
f=n=>(n>6?'':f(-~n)+' ')+"bB"[25/n&1]+'uffalo'
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/f8/zTbP1k4jz87MXl3dKk1Dty5PU1tdQV1TWynJSSnayFQ/T80wVlu9NC0tMSdf/X9yfl5xfk6qXk5@ukaahqbmfwA "JavaScript (Node.js) – Try It Online")
### Commented
```
f = n => // f is a recursive function taking a counter n,
// which is initially undefined (zero'ish)
( n > 6 ? // if n is greater than 6 (last iteration):
'' // append nothing
: // else:
f(-~n) // append the result of a recursive call with n + 1
+ ' ' // followed by a space
) //
+ "bB"[n & n != 3] // append "B" if n is odd and not equal to 3,
// or "b" otherwise
+ 'uffalo' // append "uffalo"
```
[Answer]
## x86-16 machine code, ~~43~~ ~~42~~ 41 bytes
* -1 byte thanks to @CodyGray.
* -1 byte thanks to @640KB.
```
0BED:0100 BA 19 01 BE 22 01 B4 09-B1 07 CD 21 AC A2 19 01 ...."......!....
0BED:0110 E2 F8 C6 44 F7 24 CD 21-C3 42 75 66 66 61 6C 6F ...D.$.!.Buffalo
0BED:0120 20 24 62 42 62 62 62 42-62 $bBbbbBb
```
Instruction listing (nasm syntax):
```
org 100h ; | Execution of .COM files start at CS:0100
mov dx, msg ; BA 1B 01 | DX = offset of "Buffalo $" (for INT 21H)
mov si, buf ; BE 24 01 | SI = Address of "bBbbbBb" (for LODSB)
mov ah, 09h ; B4 09 | AH = Opcode code INT 21H (Output string up to '$')
mov cl, 7 ; B1 07 | CX = 7 (we want to iterate 7 times before the last 'Buffalo')
loop:
int 21h ; CD 21 | Output string at msg
lodsb ; AC | AX = [SI], ++SI
mov byte [msg], al
; A2 1B 01 | Set the first character of msg as the current character at buf
loop loop ; E2 F8 | Jump to tag 'loop' while CX >= 0
mov byte [si - 9], "$"
; C6 44 F7 24 | (After loop) Replace the last space with a '$'
int 21h ; CD 21 | Print the last 'buffalo'
ret ; C3 | Exit to DOS
msg: db "Buffalo $"
buf: db "bBbbbBb"
```
## Example run
```
C:\test>debug code.com
-g
Buffalo buffalo Buffalo buffalo buffalo buffalo Buffalo buffalo
Program terminated normally
```
[Answer]
# [JavaScript (V8)](https://v8.dev/), 43 bytes
```
write(a=`B${b='uffalo'} b`+b,a,c='b'+b,c,a)
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNEts/j/v7wosyRVI9E2wUmlOslWvTQtLTEnX71WISlBO0knUSfZVj1JHchK1knU/P8fAA "JavaScript (V8) – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~62~~ 61 bytes
Realised the 61 byte version was not compliant (outputted a space at the end). Reverted and updated it to be.
-1 byte thanks to [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld)
```
f(n){for(n=8;n--;)printf("%cuffalo%s","bBbbbBbB"[n]," "+!n);}
```
[Try it online!](https://tio.run/##DcNBCoAgEADAc76iFoRdynsgXfxGdFBhQ6g1rE7R262BiWaNsVZGoYdzQZlGK8ZYOkqSixF0vJn9lvUJAwQXwt/BLMsALfSdkH3r7pMgqUc1jGTVWz8 "C (gcc) – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), 30 bytes
```
init$"BbBbbbBb">>=(:"uffalo ")
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/v9g2My@zREXJKckpKQmIlezsbDWslErT0hJz8hWUNP/nJmbmKVhZKXj6K2hocoF5tgoFpSXBJUU@eQrF/wE "Haskell – Try It Online")
(Cf. [Are objects in Haskell valid if there is no input?](https://codegolf.meta.stackexchange.com/questions/12924/are-objects-in-haskell-valid-if-there-is-no-input/12945#12945))
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 16 bytes
```
F⍘¹⁶²bB«ιuffalo→
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z8tv0hBwymxODW4pCgzL13D0MxIR0EpyUlJU1OhmoszAChYopGpaQ1jKpWmpSXm5CuBRHzzy1I1rIIy0zNKgNza////65blAAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
F⍘¹⁶²bB«
```
Convert 162 to base 2, but use `b` for 0 and `B` for 1, and loop over the "digits".
```
ι
```
Print the `b` or `B`.
```
uffalo
```
Print the rest of the buffalo.
```
‚Üí
```
Prepare to leave a space before the next `b`, if any.
[Answer]
# [Perl 5](https://www.perl.org/), 38 bytes
```
$,=$";say$_=Buffalo,lc,$_,(lc)x3,$_,lc
```
[Try it online!](https://tio.run/##K0gtyjH9/19Fx1ZFybo4sVIl3tapNC0tMSdfJydZRyVeRyMnWbPCGMTKSf7//19@QUlmfl7xf11fUz0DQwMA "Perl 5 – Try It Online")
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 45 bytes
```
_=>[...'BbBbbbBb'].map(x=>x+'uffalo').join` `
```
[Try it online!](https://tio.run/##DcNbCoAgEADAq/SnEu0N7MNrROQjDcVcyQpvvzUwybymuSvWeyq4ewqSNjkvAMCUVdb@2QqnqbzLuY/sCcFkZAISxqIHTQ5Lw@wh48EDF4I@ "JavaScript (Node.js) – Try It Online")
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~39~~ 36 bytes
```
''+('BbBbbbBb'|% t*y|%{$_+'uffalo'})
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/X11dW0PdKckpKQmI1WtUFUq0KmtUq1XitdVL09ISc/LVazX//wcA "PowerShell – Try It Online")
-3 bytes thanks to @mazzy!
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 63 bytes
-2 bytes thanks to @Arnauld
```
n=7;f(){printf("%cuffalo%c","bBbbbBbB"[n],9+!n),n--?f():(n=7);}
```
[Try it online!](https://tio.run/##S9ZNT07@r5yZl5xTmpKqYFNckpKZr5dh9z/P1tw6TUOzuqAoM68kTUNJNbk0LS0xJ181WUlHKckpKQmInZSi82J1LLUV8zR18nR17YHqrTSAGjWta/8DdSnkJmbmaWgqVHNxKQABUNYazAATRaklpUV5CgbWXLX/AQ "C (gcc) – Try It Online")
Could have been shorter if it wasn't for the reusability rule killing recursive functions.
[Answer]
# Julia, 42 bytes
```
join(collect("BbBbbbBb").*"uffalo ")[1:63]
```
Very similar to what was done with Python above.
[Answer]
# [Whispers v2](https://github.com/cairdcoinheringaahing/Whispers), ~~86~~ 79 bytes
```
> "Buffalo buffalo Buffalo buffalo buffalo buffalo Buffalo buffalo"
>> Output 1
```
[Try it online!](https://tio.run/##K8/ILC5ILSo2@v/fTkHJqTQtLTEnXyEJSqPzk/DLK3HZ2Sn4l5YUlJYoGP7/DwA "Whispers v2 – Try It Online")
Well, this is embarrassing...
The first line alone could even be enough, as a function returning the string
For something a bit more interesting, here's my previous solution:
# [Whispers v2](https://github.com/cairdcoinheringaahing/Whispers), 86 bytes
```
> "Buffalo "
> "buffalo "
>> 1+2
>> 3+3
>> 2+2
>> 5+3
>> 4+6
> 63
>> 7ᶠ8
>> Output 9
```
[Try it online!](https://tio.run/##K8/ILC5ILSo2@v/fTkHJqTQtLTEnX0GJC8hJQnDsFAy1jUCUsbYxiDKC8EwhPBNtM6B6MzDb/OG2BRYghn9pSUFpiYLl//8A "Whispers v2 – Try It Online")
First approach to the [language of the month](https://codegolf.meta.stackexchange.com/q/20698/62393) for me :) It looks like building the string by manually concatenating pieces is the best approach in Whispers.
### Explanation
Whispers starts the execution from the last line of the program, and then follows references from there. Any number in a line starting with `>>` refers to the result of the corresponding line, while numbers in lines starting with `>` have their normal value. We can only have a single operation per line (hence why so many lines).
Most lines here simply concatenate two strings, while line 9 takes the first `63` characters from the string in line 7, which is all except for the trailing space. It should be pretty easy to read, but here's the value computed by each line:
```
> "Buffalo " 1:"Buffalo "
> "buffalo " 2:"buffalo "
>> 1+2 3:"Buffalo buffalo "
>> 3+3 4:"Buffalo buffalo Buffalo buffalo "
>> 2+2 5:"buffalo buffalo "
>> 5+3 6:"buffalo buffalo Buffalo buffalo "
>> 4+6 7:"Buffalo buffalo Buffalo buffalo buffalo buffalo Buffalo buffalo "
> 63 8:63
>> 7ᶠ8 9:"Buffalo buffalo Buffalo buffalo buffalo buffalo Buffalo buffalo"
>> Output 9 10:prints out line 9
```
[Answer]
# TeX, 34 bytes
`\def~{uffalo }B~b~B~b~b~b~B~b~\bye`
[Answer]
# `awk`, 22- or 41-bytes. basic approach is 41-bytes:
```
echo Buffalo |
```
>
>
> ```
> mawk 'NF+=sub(" ",OFS=" "tolower($2=$4=$1)" ")'
>
> ```
>
>
```
Buffalo buffalo Buffalo buffalo buffalo buffalo Buffalo buffalo
```
but if we're going with the entirely hard-coded approach, that can massively cut it down to just 22-bytes (and that's already inclusive of the single quotes for `OFS`) :
```
echo BbBbbbBb |
```
>
>
> ```
> mawk NF++ FS= OFS='uffalo '
>
> ```
>
>
```
Buffalo buffalo Buffalo buffalo buffalo buffalo Buffalo buffalo
```
Trivia tidbit - if we view `"B"`'s as `"1"`'s and `"b"`'s as `"0"`'s,
then the requirement would appear 10100010, while its decimal form can be reached via either
>
>
> ```
> 2 * ( 3 ^ 4 )
> or
> 3 * 6 * 9
>
> ```
>
>
[Answer]
# [Mathematica](https://reference.wolfram.com/language/), 54 bytes
```
Print@@Riffle[#<>"uffalo"&/@Characters@"BbBbbbBb"," "]
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78/z@gKDOvxMEhKDMtLSc1WtnGTqk0LS0xJ19JTd/BOSOxKDG5JLWo2EHJKckpKQmIlXSUFJRi//8HAA "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 15 bytes
```
162Bị“¢OỊ“¦ȯø»K
```
[Try it online!](https://tio.run/##y0rNyan8/9/QzMjp4e7uRw1zDi3yf7i7C8RYdmL94R2Hdnv//w8A "Jelly – Try It Online")
(Alternatively, `162Bị“¢OỊ»,Œl¤K`)
I might be doing something wrong if this comes out two bytes shorter than title-casing dynamically...:
# [Jelly](https://github.com/DennisMitchell/jelly), 17 bytes
```
Œt⁹¡
162B“¦ȯø»çⱮK
```
[Try it online!](https://tio.run/##AScA2P9qZWxsef//xZJ04oG5wqEKMTYyQuKAnMKmyK/DuMK7w6fisa5L//8 "Jelly – Try It Online")
[Answer]
# APL+WIN, 21 bytes
```
'BbBbbbBb',¨⊂'uffalo'
```
[Try it online! Thanks to Dyalog Classic](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob6qvz6O2CcZcQJanP5BlyPWooz3tv7pTklNSEhCr6xxa8airSb00LQ2oU/0/UPZ/GgA "APL (Dyalog Classic) – Try It Online")
This could be shortened to 5 bytes if the two strings were given as input rather than being hard coded.
[Answer]
# [Whispers v2](https://github.com/cairdcoinheringaahing/Whispers), 98 bytes
```
> 81
> 2
>> 1‚ä•2
> "Buffalo "
> "buffalo "
> "buffalo"
>> If L 4 5
>> Each 7 3
>> 8+6
>> Output 9
```
[Try it online!](https://tio.run/##K8/ILC5ILSo2@v/fTsHCkMtOwYjLzk7B8FHXUiBDQcmpNC0tMSdfQQnEScLCUQIp90xT8FEwUTAFsV0TkzMUzBWMQWwLbTMQ5V9aUlBaomD5//9/3RAA "Whispers v2 – Try It Online")
] |
[Question]
[
# Task
Given a non-negative integer `n`, output `1` if `n` is `0`, and output the value of `n` otherwise.
# Input
A non-negative integer.
* If you would like to accept the string as input, the string would match the following regex: `/^(0|[1-9][0-9]*)$/`, i.e. it must not have any leading zeroes, except when it is `0`.
* If you accept a real integer as input, you may assume that the integer is within the handling capability of the language.
# Output
A positive integer, specified above. Leading zeroes are not allowed. Your output should match the regex `/^[1-9][0-9]*$/`.
# Testcases
```
input output
0 1
1 1
2 2
3 3
4 4
5 5
6 6
7 7
```
# Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins.
[Standard loopholes](https://codegolf.meta.stackexchange.com/q/1061/48934) apply.
[Answer]
# C (gcc), ~~14~~ 13 bytes
```
f(n){n=n?:1;}
```
*Thanks to @betseg for reminding me of the `n?:1` trick in the comments of the other C answer!*
[Try it online!](https://tio.run/nexus/c-gcc#@5@mkadZnWebZ29laF37PzOvRCE3MTNPQ5OrmksBCAqKgEJpGkqqKTF5qilKOgppGgaaINJUU9Oaq/Y/AA)
# C, 17 bytes
```
f(n){return!n+n;}
```
[Try it online!](https://tio.run/nexus/c-gcc#@5@mkadZXZRaUlqUp5innWdd@z8zr0QhNzEzT0OTq5pLAQgKioBCaRpKqikxeaopSjoKaRoGmiDSVFPTmqv2PwA)
# C, 16 bytes
```
#define f(n)!n+n
```
[Try it online!](https://tio.run/nexus/c-gcc#@6@ckpqWmZeqkKaRp6mYp533PzOvRCE3MTNPQ5OrmksBCAqKgEJpGkqqKTF5qilKOkClBpog0lRT05qr9j8A)
[Answer]
## JavaScript (ES6), 7 bytes
```
n=>n||1
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 2 bytes
```
ª1
```
[Try it online!](https://tio.run/nexus/japt#@39oleH//wYA "Japt – TIO Nexus")
### Explanation
`ª` is a shortcut for JS's `||` operator. Japt has implicit input, so this program calculates `input||1`, and the result is implicitly sent to STDOUT.
`w1` would work as well, taking the maximum of the input and `1`.
[Answer]
## Haskell, 5 bytes
```
max 1
```
Usage example: `(max 1) 0` -> `1`.
Nothing much to explain.
[Answer]
# Pyth, 2 bytes
```
+!
```
[Try it online](http://pyth.herokuapp.com/?code=%2B!&input=42&debug=0)
Explanation
```
+!
!Q 1 if (implicit) input is 0, 0 otherwise.
+ Q Add the (implicit) input.
```
[Answer]
## [Alice](https://github.com/m-ender/alice), 7 bytes
```
1/s
o@i
```
[Try it online!](https://tio.run/nexus/alice#@2@oX8yV75D5/78BAA "Alice – TIO Nexus")
### Explanation
```
1 Push 1. Irrelevant.
/ Reflect to SE. Switch to Ordinal.
i Read all input as a string.
Reflect off bottom right corner. Move back NW.
/ Reflect to W. Switch to Cardinal.
1 Push 1.
IP wraps around to last column.
s Sort swap: implicitly convert the input to an integer. Then, if the top stack
element is less than the one below, the two are swapped. It basically computes
min and max of two values at the same time, with max on top.
/ Reflect to NW. Switch to Ordinal.
Immediately reflect off the top boundary. Move SW.
o Implicitly convert the result to a string and print it.
Reflect off bottom left corner. Move back NE.
/ Reflect to S. Switch to Cardinal.
@ Terminate the program.
```
[Answer]
# [V](https://github.com/DJMcMayhem/V), 4 bytes
```
é0À
```
[Try it online!](https://tio.run/nexus/v#@394pcHhBsb///8bAQA "V – TIO Nexus")
Abuses an *non-preferred but expected behavior*, so I can't really call it a bug. Explanation:
In Vim, commands accept a count. For example, `<C-a>` will increment a number, but `7<C-a>` will increment a number by 7. However, you can't use `0` as a count, because
* `0` is already a command (go the first column), and
* In the context of a text editor, it rarely makes sense to request that a command be run 0 times.
This is fine for a text editor, but usually obnoxious for a golfing language, so V overwrites some commands so that `0` is a valid count. For example, `é`, `ñ`, `Ä`, and some others. However, since `<C-a>` is a builtin vim command, it is not overwritten, so running this with a positive input gives:
```
N " N times:
<C-a> " Increment
```
But running with 0 as input gives:
```
0 " Go to column one
<C-a> " Increment
```
Full explanation:
```
é0 " Insert a 0
À " Arg1 or 1 times:
<C-a> " Increment
```
[Answer]
# [J](http://jsoftware.com/), 2 bytes
```
^*
```
[Try it online!](https://tio.run/nexus/j#@59maxWn9f9/moKBgqGCkYIxAA "J – TIO Nexus")
`^` [argument] raised to the power of
`*` the sign of the argument (0 if 0 else 1)
Because `1=0^0` in J.
[Answer]
## [Retina](https://github.com/m-ender/retina), 4 bytes
```
^0
1
```
[Try it online!](https://tio.run/nexus/retina#U9VwT/gfZ8Bl@P8/kOAy4jLmMuEy5TLjMuey4LLkMgQKGgIA "Retina – TIO Nexus")
If the input starts with a zero, replace that with a 1. (Works because the input is guaranteed to have no leading zeros for non-zero values.)
[Answer]
# dc, 7
```
?d0r^+p
```
Relies on the fact that `dc` evaluates 00 to 1, but 0n to 0 for all other n.
[Try it online](https://tio.run/nexus/bash#S8svUihJLS5JTixOVcjMU6g20NMzr7VWSMnnUgCCgqLMvJI0BSXVYgVdOwUlBRWYWrBsanJGPkJIoUYhJVlBN1X9v32KQVGcdsF/da6U/LzU/wA).
[Answer]
# [brainfuck](https://github.com/TryItOnline/tio-transpilers), 8 bytes
```
+>,[>]<.
```
[Try it online!](https://tio.run/nexus/bash#Tc1LCsIwFEbhcbOKn9KZJs1M0JCNiIM@EgjKveEmhaJ17VUcuYDznWmo8CDWzyBsxgjnYPaDP179zZndKBVZQEiEl7XG2NMbF8ysmiyJakTb0RmtatZ1hhboXL6EQ0fY0HOufU2sqwxUcnoEKf0oQ6K4TPf/64Zfn4uamcL@AQ "Bash – TIO Nexus")
[Answer]
# R, 13 bytes
```
max(1,scan())
```
reads `n` from stdin. With `pmax`, it can read in a list and return the appropriate value for each element in the list for +1 byte.
[try it online!](https://tio.run/nexus/r#@5@bWKFhqFOcnJinoan534DrPwA)
I should note that there is another fine R solution in 13 bytes by [Sven Hohenstein](https://codegolf.stackexchange.com/a/118847/67312) which allows for yet *another* 13 byte solution of
```
(n=scan())+!n
```
which makes me wonder if that's the lower limit for R.
[Answer]
# [Cubix](https://github.com/ETHproductions/cubix), 6 bytes
```
OI!1L@
```
Somehow managed to fit it on a unit cube... [Test it online!](http://ethproductions.github.io/cubix/?code=T0khMUxA&input=MA==&speed=10)
### Explanation
Before being run, the code is arranged as a cube net:
```
O
I ! 1 L
@
```
The IP (instruction pointer) is then placed on the far-left face (`I`), facing to the right. The instructions run from there are:
```
I Input a number from STDIN and push it to the stack.
! If the top number is non-zero, skip the next instruction.
1 Push a 1 (only if the input was zero).
L Turn left. The IP is now on the top face facing the !.
O Output the top item as a number.
```
The IP then hits `!` again, skipping the `@` on the bottom face. This is not helpful, as we need to hit the `@` to end the program. The IP hits the `L` again and goes through the middle line in reverse (`L1!I`) before ending up on the `L` one more time, which finally turns the IP onto `@`.
[Answer]
# [Oasis](https://github.com/Adriandmen/Oasis), 2 bytes
Uses the following formula: **a(0) = 1**, **a(n) = n**
```
n1
```
[Try it online!](https://tio.run/nexus/oasis#@59n@P//fxMA "Oasis – TIO Nexus")
[Answer]
# [V](https://github.com/DJMcMayhem/V), 5 bytes
```
ç^0/<C-a>
```
Where `<C-a>` is `0x01`.
[Try it online!](https://tio.run/nexus/v#@394eZyBPuP//wZchlxGXMZcJlymXGZc5lyGBgA "V – TIO Nexus")
### Explanation
```
ç " On every line
^0/ " that begins with a zero do:
<C-a> " Increment the number on that line
```
[Answer]
## **R** 20 16 bytes
```
pryr::f(n+(n<1))
```
[Answer]
# Jelly, 2 bytes
```
+¬
```
[Try it online!](https://tio.run/nexus/jelly#@699aM3///9NjAA "Jelly – TIO Nexus")
Pretty much exactly my Pyth answer, but it's my first Jelly program.
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 3 bytes
```
∅1|
```
[Try it online!](https://tio.run/nexus/brachylog2#@/@oo9Ww5v9/4/9RAA "Brachylog – TIO Nexus")
### Explanation
If we add the implicit `?` (Input) and `.` (Output), we have:
```
?∅ Input is empty (that is, [] or "" or 0 or 0.0)
1. Output = 1
| Else
?. Input = Output
```
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), 3 bytes
```
1∘⌈
```
[Try it online!](https://tio.run/nexus/apl-dyalog#@@/4qG2C4aOOGY96Ov7/d1Qw4HJUMARiIyA2BmITIDYFYjMgNgcA "APL (Dyalog Unicode) – TIO Nexus")
This takes the ceil of the argument and `1`.
[Answer]
# [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), ~~22~~, 10 bytes
```
({{}}[]{})
```
[Try it online!](https://tio.run/nexus/brain-flak#@69RXV1bGx1bXav5/78BAA "Brain-Flak – TIO Nexus")
Explanation:
If the input is non-zero, then `{{}}` will pop everything off the stack and evaluate to the input. If it is zero, nothing will be popped, and it will evaluate to zero. So running `({{}})` gives
Non-zero:
```
n
```
Zero:
```
0
0
```
At this point, we'll add the height of the stack (0 for non-zero, 1 for zero) and pop one more value off the stack. (since the stack is padded with an infinite number of 0's, this will pop either the top 0 or an extra 0)
[Answer]
# [Hexagony](https://github.com/m-ender/hexagony), ~~7~~ 6 bytes
```
)?<@.!
```
### Expanded:
```
) ?
< @ .
! .
```
[Try it online!](https://tio.run/nexus/hexagony#@69pb@Ogp/j/vyEA)
Saved 1 byte thanks to Martin!
If the number is nonzero print it, otherwise add one to it and print that instead.
[Answer]
# [MarioLANG](https://esolangs.org/wiki/MarioLANG), 12 bytes
```
;
=[
:<+
=:
```
[Try it online!](https://tio.run/nexus/mariolang#@2/NZRvNZWWjzaVga/X/vykA "MarioLANG – TIO Nexus")
**How it works**
Mario starts in the top left, initially walking right. He reads an int from input (`;`) and stores it in the current memory cell. Then he falls off the ground (`=`), hitting `[`, which makes him ignore the next command if the current cell is 0.
If the cell is not 0, he'll start walking left (`<`), output the current cell as an int (`:`), and fall to his death (end of program).
If the cell is 0, he ignores the command to turn left, and keeps walking right. He increments the current cell (`+`), outputs it, and falls to his death.
[Answer]
# TI-BASIC, 7 bytes
```
:Prompt X
:X+not(X
```
Alternatively,
# TI-BASIC, 7 bytes
```
:Prompt X
:max(X,1
```
[Answer]
## Mathematica, 9 8 bytes
Per Martin Ender:
```
#~Max~1&
```
First idea:
```
#/. 0->1&
```
Pure function with replaces `0` with `1`. The space is necessary or it thinks we are dividing by `.0`.
[Answer]
# Python, 15 bytes
```
lambda n:n or 1
```
[Answer]
# dc, 11 bytes
```
[1]sf?d0=fp
```
`[1]sf` stores a macro in register f which pushes 1 to the top of the stack,
`?` reads input,
`d0=f` runs macro f if input was 0, `p` prints the top of the stack.
Test:
```
$ dc -e "[1]sf?d0=fp" <<< 0
1
$ dc -e "[1]sf?d0=fp" <<< 1
1
$ dc -e "[1]sf?d0=fp" <<< 42
42
```
[Answer]
## Excel, 10 Bytes
```
=A1+(A1=0)
```
This saves 4 Bytes over the obvious 'IF' statement solution, `=IF(A1=0,1,A1)`.
[Answer]
# Perl 5, 6 + 2 bytes for the -l and -p flags
```
$_||=1
```
Takes input on separate lines from stdin. Runs with the flags `-lp`.
[Answer]
## Java 8, 10 bytes
```
i->i<1?1:i
```
* Thanks to [@LeakyNun](https://codegolf.stackexchange.com/users/48934/leaky-nun) for saving -**1** byte
+ Didn't notice it's a **non-negative** integer
[Answer]
# Arnold C, 303 bytes
```
IT'S SHOWTIME
HEY CHRISTMAS TREE i
YOU SET US UP 1
GET YOUR ASS TO MARS i
DO IT NOW
I WANT TO ASK YOU A BUNCH OF QUESTIONS AND I WANT TO HAVE THEM ANSWERED IMMEDIATELY
BECAUSE I'M GOING TO SAY PLEASE i
TALK TO THE HAND i
BULLSHIT
TALK TO THE HAND 1
YOU HAVE NO RESPECT FOR LOGIC
YOU HAVE BEEN TERMINATED
```
Trying to explain it:
```
IT'S SHOWTIME //main()
HEY CHRISTMAS TREE i //int i
YOU SET US UP 1 //i = 1
GET YOUR ASS TO MARS i // ? compiler told me to add that
DO IT NOW // ? compiler told me to add that
I WANT TO ASK YOU A BUNCH OF QUESTIONS AND I WANT TO HAVE THEM ANSWERED IMMEDIATELY // something related to reading from stdin
BECAUSE I'M GOING TO SAY PLEASE i // if(i)
TALK TO THE HAND i //print i
BULLSHIT //else
TALK TO THE HAND 1 //print 1
YOU HAVE NO RESPECT FOR LOGIC //endif
YOU HAVE BEEN TERMINATED //end main()
```
It even beats [this answer](https://codegolf.stackexchange.com/a/118534/65870)!
] |
[Question]
[
**Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers.
---
This question does not appear to be about code golf or coding challenges within the scope defined in the [help center](https://codegolf.stackexchange.com/help/on-topic).
Closed 8 years ago.
**Locked**. This question and its answers are [locked](/help/locked-posts) because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions.
Your task is to create a [memory leak](https://en.wikipedia.org/wiki/Memory_leak). This is a program that uses loads of memory, until the computer runs out and has to do some swapping to save itself from running out. The only way that the memory can be released is by killing the program in the task manager or using a command line kill such as `taskkill /im yourprogram /f` (in Windows) or even restarting the computer. Merely closing the app should not prevent it from continuing to hog memory.
Rules:
1. [Fork bombs](https://en.wikipedia.org/wiki/Fork_bomb) of any sort are banned. That means that infamous [Bash](http://en.wikipedia.org/wiki/Bash_%28Unix_shell%29) line `:(){ :|:&};:` is banned!
2. The application must be single-threaded only. This implies the fork bomb rule.
3. The program must not run other programs. This means that you can't just do something like `run(memoryfiller.exe)`. The only exception to this is programs that are bundled with your OS or language, that are not primarily designed to consume memory (i.e. they have another purpose). This means that things like `cat` and `ln -s` are permitted.
4. You can take up as much memory as you like. The more the better.
5. Code must be explained fully.
Good luck. This is a popularity contest so the code with the most votes after 10 days from the asking date wins!
[Answer]
# Windows
The Win32 API allows you to allocate memory in other processes, and then to read/write that memory remotely. This program has only one thread, which it uses to enumerate each running process on the system, and then repeatedly allocate 1MB buffers in each process until the allocation fails. When it finishes with one process, it moves on to the next. The allocations are not released when the calling program finishes - only when/if each target process finishes. This hangs a 2GB Windows 7 VM in about 10 seconds. It does require running as admin.
To compile: `cl /MD leak.cpp /link psapi.lib`
```
#include <windows.h>
#include <psapi.h>
typedef void (*ProcFunc)(DWORD pid);
#define ALLOC_SIZE 0x100000
LPVOID buf;
void ForEachProcess(ProcFunc f)
{
DWORD aProcesses[1024], cbNeeded;
if (!EnumProcesses( aProcesses, sizeof(aProcesses), &cbNeeded))
return;
for (unsigned int i = 0; i < cbNeeded / sizeof(DWORD); i++)
if (aProcesses[i] != 0)
f(aProcesses[i]);
}
void RemoteLeak(DWORD pid)
{
HANDLE hProcess = OpenProcess( PROCESS_ALL_ACCESS, FALSE, pid );
if (hProcess == NULL)
return;
for (;;)
{
LPVOID ptr = VirtualAllocEx(hProcess, NULL, ALLOC_SIZE,
MEM_COMMIT, PAGE_READWRITE);
if (ptr == NULL)
return;
WriteProcessMemory(hProcess, ptr, buf, ALLOC_SIZE, NULL);
}
}
int main(void)
{
buf = malloc(ALLOC_SIZE);
if (buf == NULL)
return 0;
memset(buf, 0xFF, ALLOC_SIZE);
ForEachProcess(RemoteLeak);
return 0;
}
```
[Answer]
# Java
```
import java.util.concurrent.atomic.AtomicInteger;
public class Hydra {
// Not actually necessary for the leak - keeps track of how many Hydras there are, so we know when they're all gone
public static AtomicInteger count = new AtomicInteger(0);
public Hydra() {
count.incrementAndGet();
}
protected void finalize() {
new Hydra();
new Hydra();
count.decrementAndGet();
}
public static void main(String[] args) throws InterruptedException {
new Hydra();
while (Hydra.count.get() > 0) {
// Prevent leaks ;-)
System.gc();
System.runFinalization();
}
}
}
```
## Explanation
You might assume that since there are no references in the code (other than `count`, which you can safely ignore), it can't leak. However, the finalizer creates two new Hydras, and whilst it doesn't hold references for these either, they'll hang around until finalized. This means that the program only leaks memory during garbage collection - hence the calls to `System.gc()` and `System.runFinalization()`.
[Answer]
## C
Using the C programming language and tested with Linux kernel 2.6.32-49-generic and libc-2.11.1.so.
>
> The only way that the memory can be released is by killing the program in task manager or using taskkill /im yourprogram /f or even restarting the PC.
>
>
>
This is achieved by blocking any signals except for SIGKILL and SIGSTOP.
>
> Closing it should still make it hog memory.
>
>
>
This actually confused me... Killing or closing it both results in termination of the process, allowing the operating system to claim back any memory that was allocated by the process. But then i got to think that by closing it you might mean to close the terminal or any other parent process that executes the memory leaking process. If i got that right, then i solved this problem by blocking any signals, which turns the process into a daemon when the parent process is terminated. That way you can close the terminal the process is running in and it will continue running and proceed to leak memory.
>
> Fork bombs of any sort are banned. That means that infamous bash :(){ :|:&};: is banned!
>
>
>
The process does not fork.
>
> The application must be single threaded only. This implies the fork bomb rule
>
>
>
No new threads are spawned.
>
> The program must not run other program. This means that you cant just do something like run(memoryfiller.exe)
>
>
>
No new processes are spawned.
>
> You can take up as much memory as you like. The more the better.
>
>
>
As much as the operating system can provide.
>
> Code must be explained fully.
>
>
>
Added comments to the source.
And finally here's the code:
```
#define _GNU_SOURCE
#include <stdio.h>
#include <signal.h>
#include <sys/resource.h>
#include <unistd.h>
#include <stdlib.h>
int main(int argc, char* argv[]) {
/*
set the real, effective and set user id to root,
so that the process can adjust possible limits.
if the process doesn't have the CAP_SETUID capability, terminate the process.
*/
if (setresuid(0, 0, 0) == -1) {
printf("Are you root?!\n");
return 1;
}
/*
block all signals except for kill and stop.
this allows to terminate the parent process (most likely a terminal)
that this process is running in and turn it into a daemon.
additionally this makes it impossible to terminate the process
in a normal way and therefore satisfies the requirement that closing
it should still make it hog memory.
*/
sigset_t mask;
sigfillset(&mask);
sigprocmask(SIG_SETMASK, &mask, NULL);
/*
allow the process to acquire a virtually unlimited amount of memory
and queue a virtually unlimited amount of signals.
this is to prevent an out of memory error due to a virtual limit for the root user,
which would prevent the process from leaking any more memory
and to prevent the process from getting killed due to too many queued
signals that the process is blocking.
*/
struct rlimit memory = { RLIM_INFINITY, RLIM_INFINITY },
signal = { RLIM_INFINITY, RLIM_INFINITY};
setrlimit(RLIMIT_AS, &memory);
setrlimit(RLIMIT_SIGPENDING, &signal);
/*
allocate a buffer big enough to store a file name into it
that is generated from the process' pid.
if the file can be opened (which should always be the case unless /proc is not mounted)
the file will be opened and the string -17 followed by a new line written to it.
this will cause the oom killer to ignore our process and only kill other,
innocent processes when running out of memory.
*/
char file_name[20];
sprintf(file_name, "/proc/%u/oom_adj", getpid());
FILE* oom_killer_file = fopen(file_name, "w");
if (oom_killer_file) {
fprintf(oom_killer_file, "-17\n");
fclose(oom_killer_file);
}
/*
get the size of virtual memory pages in bytes,
so the process knows the size of chunks that have to be
made dirty to force the kernel to map the virtual memory page into RAM.
*/
long page_size = sysconf(_SC_PAGESIZE);
// allocate a virtually infinite amount of memory by chunks of a page size.
while(1) {
// will overwrite any previous stored address in tmp, leaking that memory.
char* tmp = (char*) malloc(page_size);
if (tmp)
// make the memory page dirty to force the kernel to map it into RAM.
tmp[0] = 0;
}
return 0;
}
```
For anyone who's interested in what happens if you keep this program running: On my test system with 2GB RAM and 4GB swap space it took about 10 minutes to fill up the RAM and swap. The OOM killer started its work and three minutes later kind of all processes have been killed. Even mouse, keyboard and display have been dropped by the system. /var/log/kern.log shows no useful information, except for the processes that have been killed.
[Answer]
# Pure Bash
Not a fork-bomb, I promise:
```
:(){ : $@$@;};: :
```
It looks a lot like a fork bomb, and uses a similar recursive technique, but no forks. **Of course this will run your shell right out of memory, so you are advised to start a new shell before pasting this command.**
* Define a function called `:`
* The function simply recursively calls itself with `$@` (arg list) doubled
* After the function definition, the `:` function is called with an initial arg `:`
Output:
```
$ bash
$ :(){ : $1$1;};: :
bash: xmalloc: ../bash/stringlib.c:135: cannot allocate 536870913 bytes (5368795136 bytes allocated)
$
```
---
In a previous edit of this answer I did `a=$(yes)`, but I noticed the rule "The program must not run other program", so I need to use pure `bash` instead without calling any coreutils or anything else.
---
Here's another one:
**PLEASE DON'T RUN THIS ON A PRODUCTION MACHINE**
```
:(){ : <(:);};:
```
Again, this is not a fork bomb - everything is run from within one thread. This one seems to quite handily bring my Ubuntu VM to its knees, with little room for recovery, other than reboot.
As in the classic fork bomb, a recursive function `:()` is defined. However it does not fork out calls to itself. Instead it calls itself with one argument, which is itself called in a [process substitution](https://www.gnu.org/software/bash/manual/html_node/Process-Substitution.html). Because process substitution works by opening an file descriptor `/dev/fd/n`, this not only eats up process (bash) memory, it will also eat up some kernel memory too. On my Ubuntu machine this has the effect of making the window manager inoperable after a few seconds, then shortly after ending up with this screen:
[![enter image description here](https://i.stack.imgur.com/i1Lyv.png)](https://i.stack.imgur.com/i1Lyv.png)
Clicking `OK` then gives this screen:
[![enter image description here](https://i.stack.imgur.com/MIx6d.png)](https://i.stack.imgur.com/MIx6d.png)
None of these options seem to be much help - at this point restarting seems to be the only good option.
[Answer]
# XML
```
<!DOCTYPE boom [
<!ENTITY Z 'ka-boom!'><!ENTITY Y '&Z;&Z;'><!ENTITY X '&Y;&Y;'><!ENTITY W '&X;&X;'>
<!ENTITY V '&W;&W;'><!ENTITY U '&V;&V;'><!ENTITY T '&U;&U;'><!ENTITY S '&T;&T;'>
<!ENTITY R '&S;&S;'><!ENTITY Q '&R;&R;'><!ENTITY P '&Q;&Q;'><!ENTITY O '&P;&P;'>
<!ENTITY N '&O;&O;'><!ENTITY M '&N;&N;'><!ENTITY L '&M;&M;'><!ENTITY K '&L;&L;'>
<!ENTITY J '&K;&K;'><!ENTITY I '&J;&J;'><!ENTITY H '&I;&I;'><!ENTITY G '&H;&H;'>
<!ENTITY F '&G;&G;'><!ENTITY E '&F;&F;'><!ENTITY D '&E;&E;'><!ENTITY C '&D;&D;'>
<!ENTITY B '&C;&C;'><!ENTITY A '&B;&B;'><!ENTITY z '&A;&A;'><!ENTITY y '&z;&z;'>
<!ENTITY x '&y;&y;'><!ENTITY w '&x;&x;'><!ENTITY v '&w;&w;'><!ENTITY u '&v;&v;'>
<!ENTITY t '&u;&u;'><!ENTITY s '&t;&t;'><!ENTITY r '&s;&s;'><!ENTITY q '&r;&r;'>
<!ENTITY p '&q;&q;'><!ENTITY o '&p;&p;'><!ENTITY n '&o;&o;'><!ENTITY m '&n;&n;'>
<!ENTITY l '&m;&m;'><!ENTITY k '&l;&l;'><!ENTITY j '&k;&k;'><!ENTITY i '&j;&j;'>
<!ENTITY h '&i;&i;'><!ENTITY g '&h;&h;'><!ENTITY f '&g;&g;'><!ENTITY e '&f;&f;'>
<!ENTITY d '&e;&e;'><!ENTITY c '&d;&d;'><!ENTITY b '&c;&c;'><!ENTITY a '&b;&b;'>
]>
<boom a="&a;"/>
```
Then pass the document to an XML parser that doesn't do entity reference loop/recursion detection. For example, `xpath` included with perl:
```
xpath boom.xml /
```
How it works:
1. The parser encounters `<boom a="&a;">`
2. The parser expands `"&a;"` into `"&b;&b;"`
3. The parser expands one of the `"&b;"` into `"&c;&c;"` (on return, it will expand the other `"&b;"`)
4. The parser expands one of the `"&c;"` etc...
If full expansion could occur, there would be 2^52 expansion of "ka-boom!". Assuming 2-bytes per character, it will try to use 64 PiB. The expansion goes "ka-boom!" at a time, so you can usually watch it use up all memory in top.
This goes by various names, good overview here: <http://projects.webappsec.org/w/page/13247002/XML%20Entity%20Expansion>
[Answer]
# C++
```
int main()
{
for(;;)int *a=new int;
}
```
This code was unexpected! It hung my computer while the task manager was open and showed that it took 890 Mb of memory in 1 second then it also hung. I don't know how this works, maybe it keeps on giving memory to a variable.To explore more of this code I added a statement `delete a;` and every thing was fine while testing (no hanging) So, I think that the chunk of memory is given (due to `new int`) and then taken back (due to `delete a`) to the free space in the new code below.
```
int main()
{
for(;;)
{
int *a=new int;
delete a;
}
}
```
So, I conclude that **NO RAM IN THIS WORLD CAN HANDLE THIS CODE!!!**
**EDIT** : *But many processors can* for e.g. `intel core 2 duo` can't handle this code but
`intel core i-series` can (worked for me...)
*Remember the answer to the question is the 1st code , second one is for explanation.*
[Answer]
# [BrainFuck](http://en.wikipedia.org/wiki/Brainfuck)
```
+[>+]
```
Explanation:
To enter the loop it increases the cell to 1. It moves to the next cell increasing that to 1 as long as the last cell was positive.
Usually A BrainFuck interpreter is flawed with having a hard limit to the number of cells on the tape, but some interpreters adds cells dynamically. These will continue to consume memory until it's no more to consume.
`beef` is one such interpreter and it's available in the Ubuntu Software Center and my current run on an unused machine started 29 hours ago and has consumed 1GB of RAM in that time. Here's the the output of `top`
```
PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND
2978 sylwester 20 0 1030m 984m 2536 R 100,1 12,4 1750:52 beef
```
It has 4GB of cache and 6GB of swap so I guess I'll update this answer with how it went in about 12 days.
**UPDATE 03.24 17:11**
```
PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND
2978 sylwester 20 0 1868m 1,8g 2456 R 99,9 22,9 6008:18 beef
```
**UPDATE 03.31 00:20**
```
PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND
2978 sylwester 20 0 2924m 2,8g 2052 R 100,0 36,1 15019:46 beef
```
So it's been running for 10 days. Seems like it will be running for at least 10 more before something interesting happens.
[Answer]
# C and POSIX
Here I am aiming for a highly portable solution. The problem is that pure C doesn't seem to have a way of telling the Operating System that the memory should remain allocated after the program closes. So I allow myself to use POSIX; most OS's have some claim to POSIX compatibility including Windows, Linux and MacOS X. However, I have only tested it on Ubuntu 12.04 32bit. It does not require superuser permissions.
This solution is essentially the traditional `while(1){malloc(1);}` solution. However instead of malloc, it uses the POSIX shared memory functions. Since it assigns a shared memory identifier to each allocation, it is still possible to access the memory once the process terminates. Thus the kernel cannot free the memory.
```
#include <sys/types.h>
#include <sys/shm.h>
#include <string.h>
#define SHMSZ (2*1024*1024) /*Ubuntu rejects shared allocations larger than about 2MiB*/
main() {
int shmid;
key_t key = 0xF111; /* Lets use `Fill' as our first ID.*/
char *shm;
while(1) { /* Like malloc, but using shared memory */
if ((shmid = shmget(key, SHMSZ, IPC_CREAT|0666)) < 0){return 1;}/*Get shared memory*/
if ((shm = shmat(shmid, NULL, 0)) == (void *) -1) { return 1; } /*Attach it */
memset(shm,0,SHMSZ); /*Fill it up */
key++ /*On to the next ID*/
}
}
```
[Answer]
## C#
Forgetting to unsubscribe from events before the handler goes out of scope will cause .NET to leak memory until it throws OutOfMemoryException.
```
using System;
class A
{
public event Action Event;
}
class B
{
public void Handler() { }
}
class Program
{
static void Main()
{
A a = new A();
while( true )
a.Event += new B().Handler;
}
}
```
**Explanation**: Inside the `while` loop, we construct a new object, causing the framework to allocate more memory, but we also prevent the new instance of `B` from being released when it goes out of scope by assigning an instance method to an event in a different class, the result being that the new instance of `B` becomes unreachable from our code, but a reference still exists, meaning the GC won't release it until `a` also goes out of scope.
Static events have the same pitfall, since they never go out of scope, they're only cleaned up when the process terminates, unless you unsubscribe from the event first. Always store your references, people!
```
using System;
class Program
{
static event Action Event;
static void Main()
{
while( true )
Event += new Action( delegate{ } );
}
}
```
The above works on the same idea, the handler becomes unreachable once the `while` loop goes out of scope, making it impossible to unsubscribe from the event, meaning the memory will sit there until the program terminates. Static events are arguably more dangerous than instance events, because you can ensure they never go out of scope.
**EDIT**: You can also do the same with basically any other object as well, just as long as you add a reference while at the same time ensuring there's no way to free that reference.
Here's an example that uses static objects and arrays.
```
using System;
using System.Collections.Generic;
static class Leak
{
private static List<decimal[]> Junk;
static Leak()
{
Junk = new List<decimal[]>();
}
public static void Add( uint size )
{
decimal[] arr = new decimal[size];
Junk.Add( arr );
}
}
class Program
{
static void Main()
{
while( true )
Leak.Add( 1 );
}
}
```
Arrays keep being added to the list, but there's no way to clear the list without modifying the code, which would be impossible for closed-source applications. Increasing the number passed to `Leak.Add` will cause it to leak faster, if you set it high enough it will just result in an immediate OverflowException being thrown.
[Answer]
# bash (no external utilities)
No fork bomb here.
*Warning:* It might kill your shell.
Just trying to create an array of integers for reference because I keep forgetting how integers look like.
```
while :; do _+=( $((++__)) ); done
```
Results in:
```
xmalloc: expr.c:264: cannot allocate 88 bytes (268384240 bytes allocated)
```
[Answer]
## J (7)
*WARNING:* This froze my system when I tried it (Windows 8, J 8.01, in the qt terminal).
```
2#^:_[_
```
* `2#` doubles the length of the argument by duplicating each element,
* `^:_` finds the fixpoint of the given function (but there isn't one so it loops endlessly),
* `[_` calls it with `_` as the argument.
[Answer]
## Haskell (Graham's number)
It's very simple: this calculates the [Graham's number](http://en.wikipedia.org/wiki/Graham%27s_number)
Unlike other examples here, it won't run forever... it will use a lot of cpu, but theoretically it could terminate. if it weren't for the fact that to store the number...
>
> the observable universe is far too small to contain an ordinary digital representation of Graham's number, assuming that each digit occupies one [Planck volume](http://en.wikipedia.org/wiki/Planck_units#Derived_units).
>
>
>
(according to wikipedia)
```
import Data.Sequence
import Data.Foldable
(↑) a 1 b = a ^ b
(↑) a _ 0 = 1
(↑) a i b = a ↑ (i-1) $ a ↑ i $ b-1
graham = last $ toList $ iterateN 64 (\i -> 3 ↑ i $ 3) 4
main = print graham
```
So, the idea is that the memory will be used by a (series of increasingly) enormous `Integer`(s) (Haskell's Integers are of arbitrary size).
If you want to test it out, you might have to increase the stack size or load it inside `ghci`.
[Answer]
Inspired by @comintern.
Replacing /dev/null. Engaging sneaky mode. Requires kernel headers, superuser mode and a working compiler.
```
# make
# rm /dev/null
# insmod devnull.ko
# chmod go+rw /dev/null
```
Have fun.
Makefile:
```
MODULE := devnull
KVERS ?= $(shell uname -r)
KDIR ?= /lib/modules/$(KVERS)/build
KMAKE := make -C $(KDIR) M=$(PWD)
obj-m += $(MODULE).o
all:
$(KMAKE) modules
install:
$(KMAKE) modules_install
clean:
$(KMAKE) clean
```
Source code:
```
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/fs.h>
#include <linux/ioport.h>
#include <linux/device.h>
#include <linux/version.h>
#include <linux/slab.h>
#include <asm/io.h>
#include <asm/uaccess.h>
#define DEVICE_NAME "null"
#define MAJOR_NUMBER 0
MODULE_LICENSE("GPL");
MODULE_AUTHOR("nola <[[email protected]](/cdn-cgi/l/email-protection)>");
MODULE_DESCRIPTION("/dev/null - memory leak style");
MODULE_VERSION("0.1");
MODULE_SUPPORTED_DEVICE("null");
static struct class *class_null;
static int major = 0;
static int device_open(struct inode *, struct file *);
static int device_release(struct inode *, struct file *);
static ssize_t device_read(struct file *, char *, size_t, loff_t *);
static ssize_t device_write(struct file *, const char *, size_t, loff_t *);
static loff_t device_llseek(struct file *, loff_t, int);
static struct file_operations fops = {
.owner = THIS_MODULE,
.llseek = &device_llseek,
.read = &device_read,
.write = &device_write,
.open = &device_open,
.release = &device_release
};
static int __init mod_init(void)
{
struct device *dev_null;
if ((major = register_chrdev(MAJOR_NUMBER, DEVICE_NAME, &fops)) < 0) {
return major;
}
/* create /dev/null
* We use udev to make the file.
*/
class_null = class_create(THIS_MODULE, DEVICE_NAME);
if (IS_ERR(class_null)) {
unregister_chrdev(major, DEVICE_NAME);
return -EIO;
}
#if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 27)
dev_null = device_create(class_null, NULL, MKDEV(major, 0),
NULL, "%s", DEVICE_NAME
);
#else
dev_null = device_create(class_null, NULL, MKDEV(major, 0),
"%s", DEVICE_NAME
);
#endif
if (IS_ERR(dev_null)) {
class_destroy(class_null);
unregister_chrdev(major, DEVICE_NAME);
return -EIO;
}
return 0;
}
static void __exit mod_exit(void)
{
device_destroy(class_null, MKDEV(major, 0));
class_unregister(class_null);
class_destroy(class_null);
unregister_chrdev(major, DEVICE_NAME);
}
static int device_open(struct inode *inode, struct file *file)
{
file->f_pos = 0x00;
try_module_get(THIS_MODULE);
return 0;
}
static int device_release(struct inode *inode, struct file *file)
{
/* decrement usage count: Not. Uncomment the line for less fun. */
/* module_put(THIS_MODULE); */
return 0;
}
static loff_t device_llseek(struct file *filep, loff_t offs, int mode)
{
loff_t newpos;
switch (mode) {
case 2:
case 0:
newpos = offs;
break;
case 1:
newpos = filep->f_pos + offs;
break;
default:
return -EINVAL;
}
if (newpos < 0) {
return -EINVAL;
}
filep->f_pos = newpos;
return newpos;
}
static ssize_t device_read(struct file *filep, char *dst, size_t len,
loff_t *off)
{
char *buf = NULL;
if (dst == NULL || len == 0) {
return -EINVAL;
}
buf = kmalloc(sizeof(char) * len, GFP_KERNEL);
if (buf == NULL) {
return -EINVAL;
}
/* Do how a /dev/null does.
*/
memset(dst, 0, len);
*off += len;
return len;
}
static ssize_t device_write(struct file *filep, const char *src, size_t len,
loff_t *off)
{
char *buf = NULL;
buf = kmalloc(sizeof(char) * len, GFP_KERNEL);
if (buf == NULL) {
return -EINVAL;
}
*off += len;
return len;
}
module_init(mod_init);
module_exit(mod_exit);
```
Warning this may force you to reboot!
To remove it:
```
# rmmod -f devnull # or a reboot
# rm -rf /dev/null
# mknod /dev/null c 1 3
# chmod go+rw /dev/null
```
[Answer]
# Ruby
Everyone knows that sum(1/n^2) = pi^2/6
So I can define an approximation function:
```
pi_approx = lambda {|i|
Math.sqrt(
6*(
(1...Float::INFINITY).map{|n| n.to_f**(-2)}.take(i).reduce(:+)
)
)
}
p pi_approx.(100_000)
```
Of course the (1..infinity) will run wild.
Notice however that using lazy would make this work ;)
```
pi_approx = lambda {|i|
Math.sqrt(
6*(
(1...Float::INFINITY).lazy.map{|n| n.to_f**(-2)}.take(i).reduce(:+)
)
)
}
p pi_approx.(100_000)
#=> 3.141583104326456
```
[Answer]
# C - 28 25 characters (full program)
Don't run that one, or your system will quickly get frozen!
```
main(){while(malloc(9));}
```
The call to malloc will reserve 9 bytes of memory and request new memory pages from the operating system regularly.
The memory allocated by malloc is immediately leaked as no pointer to the returned address is stored.
Once the system has run out of memory (RAM and swap space) or the memory limit for the process is reached, the program will break out of the while-loop and terminate.
[Answer]
# VBScript
```
do
Set d1 = createobject("Scripting.Dictionary")
d1.add true, d1
Set d1 = Nothing
loop
```
We are creating a dicionary that point to itself. Then we think that we destroy the dictionary by setting it to Nothing. However, the dictionary still exists in memory because it has a valid (circular) reference.
The loop, but also the memory hog, causes the program to hang. After shutdown of the program, the memory is still in use. The system can only be restored by restarting it.
[Answer]
# Yes & tmpfs
Why write a new program when one comes for free with Ubuntu?
```
yes > /run/user/$UID/large_file_on_my_ramdisk
```
As you probably know, or have already guessed, Ubuntu mounts /run/user/ by default as a tmpfs which is a type of [RAM disk](https://en.wikipedia.org/wiki/RAM_drive).
You don't even have to close it. It will politely close itself, leaving a nice chunk of memory allocated. I presume `yes` is a single-threaded, single-process program that does not call any other (writing to an existing RAM disk is also trivially portable to the language of your choice).
It has a minor bug: Ubuntu limits the user writable tmpfs /run/1000 to 100 MB by default, so the swap death feature may not be supported on your machine out-of-the-box. However I managed to fix this on my machine with the following quick workaround:
```
sudo mount -o remount,size=10G tmpfs /run/user/
```
[Answer]
## Bash
**Warning: The following code will make your computer unbootable.**
```
printf "\\xe8\\xfd\\xff" | dd of=/dev/sda
reboot
```
**Warning: The preceding code will make your computer unbootable.**
Replace /dev/sda with your boot drive. This writes E8 FD FF to the beggining of your boot sector. When booting, the BIOS reads your boot sector into memory and executes it. Those opcodes are equivalent to this assembly:
```
label:
call label
```
This is infinite recursion, which will eventually cause a stack overflow.
[Answer]
## Haskell
```
main=print $ sum [0..]
```
This tries to add up the counting numbers. Haskell does evaluate the partial sums, it just becomes an infinite addition statement. If you run the compiler with optimization flags, it may not work though.
[Answer]
# Bash
Since we can use utilities that aren't specifically designed to consume memory, I focus on a utility to free memory: `swapon`. This is used to allow the kernel to free up memory by writing to disk.
This script performs two optimizations: (1) Mounting tmp as tmpfs (a type of RAM disk) to make /tmp faster and (2) creating a swapfile to free up memory. Each of these are reasonable by themselves but if a careless user does both then it sets up an cycle of swapping: when the OS tries to swap out pages, it writes to the tmpfs; this makes the tmpfs use more memory; this increases the memory pressure causing more pages to be swapped out. This can take a few minutes on my VM, plenty of time for you to watch the system dig itself into a hole using `top`.
Closing the program makes little difference since the program itself allocates hardly any memory. Indeed it is not trivial to free memory since you can't free memory by unmounting the tmpfs before you `swapoff` the swapfile, and that is hard to do until you have freed memory.
This answer could be considered an cautionary tale against blinding applying cool tricks from the net without understanding them.
```
sudo mount -t tmpfs -o size=9999G tmpfs /tmp # Use tmpfs to make /tmp faster
truncate -s 4096G /tmp/swap # Now make a giant swap file to free up memory
sudo losetup /dev/loop4 /tmp/swap # Use a loopback so we can mount the sparse file
sudo mkswap /dev/loop4
sudo swapon /dev/loop4
#The following line would cause a quick swap death, but isn't needed.
#dd if=/dev/zero of=/tmp/zero bs=1 # Zero the tmp dir so the VM can free more memory
```
[Answer]
# Perl
```
sub _ {
my($f,$b);
$f=\$b;$b=\$f;
}
while(1) { _;}
```
Uses circular references. The reference count for the variables will never reach 0, and the references will never be garbage collected.
You might need to be patient, but it is guaranteed to choke your system. The disk would start spinning faster and fumes might be visible.
[Answer]
# PHP (linux only):
This code is untested, since that I don't have a linux computer with php running.
But this is my proof of concept:
```
ignore_user_abort(true);
ini_set('memory_limit',-1);
ini_set('max_execution_time',0);
/*
sets php to ignore if the script was canceled in the browser
(like clicking cancel or closing the browser)
and takes away the memory limit,
as well as the maximum execution time.
*/
function dont_let_it_stop(){shell_exec('php '.__FILE__.' &');}
//this function calls the file itself.
register_shutdown_function('dont_let_it_stop');
//this function will register the function declared above to be used when the script is being terminated
function get_info($f='current')
{
return str_replace(' kB','',end(explode(':',trim($f(explode(PHP_EOL,file_get_contents('/proc/meminfo')))))))*1024
}
/*
this function fetches the infos
'current' fetches the max memory
'next' fetches the actual used memory
*/
$max=get_info();//maximum memory
$current=get_info('next');//current memory
$imgs=array(imagecreatetruecolor(1e4,1e4));
$color=imagecolorallocatealpha($imgs[$i=0],128,128,128,126);
imagefill($imgs[$i],0,0,$color);
/*
this creates an array and inserts one image (10000x10000 pixels),
filling it then with a solid transparent color
*/
$total-=get_info('next');//calculates the space an image takes
while($max-get_info('next')>$total*2)//while the free memory is higher than the memory of 2 images, fill the array
{
$imgs[$i++]=imagecreatetruecolor(1e4,1e4);
$color=imagecolorallocatealpha($imgs[$i-1],128,128,128,126);
imagefill($imgs[$i-1],0,0,$color);
}
//this is just to keep the images in memory, so the script doesn't end
while(1)sleep(60);
```
This will fill the memory with huge RGBA images (10000x10000 pixels).
The only way to shut this baby down is shutting down the power.
The code is all commented.
Any improvement, doubt, bug or anything, use the comment box below.
[Answer]
# Python - 56
```
class x:
def __setattr__(self,*args):self.y=0
x().y=0
```
Creates a class, defines a method for setting attributes, sets an attribute in it, and creates an initial instance which it then tries to set an attribute of.
A simple recursive function (`def f(x):f(x)`) seemed a bit unimaginative so I decided never to actually *call* a function.
Memory management might catch the recursion depth, but it really depends on the implementation.
If this is a fork bomb, please tell me.
[Answer]
# Perl
It's a simple one, but I felt like golfing it.
```
{$x=[$x];redo}
```
After two iterations, `$x` contains a reference to array containing a reference to array containing `undef`.
Memory usage is linear in time, with small allocations, but it only took several seconds to severely slow my window manager on my Ubuntu Linux system. Half a minute later the OOM killer took care of it.
[Answer]
# ECMAScript 6:
```
z=z=>{while(1)z()};_=i=>(i+=1,i-=1,i++,i--,--i,++i,i<<=2,i>>=2,i+=0|Math.round(1+Math.random())&1|0,z(x=>setInterval(x=>z(x=>new Worker('data:text/javascript,'+_.toSource()),5))));setInterval(x=>z(x=>_(...Array(9e3).map((x,z)=>z*3/2*2/4*4e2>>2<<2))),5)
```
---
## Ungolfed:
```
function forever(code) {
// Loop forever
var counter = 0;
while (counter++ < 10) setInterval(code, 5);
};
function main(counter) {
// Do some work.
counter += 1; counter -= 1;
counter++; counter--;
--counter; ++counter;
counter <<= 2;
counter >>= 2;
counter += 0 | Math.round(1 + Math.random()) & 1 | 0;
forever(() => {
setInterval(() => {
forever(() => new Worker('data:text/javascript,' + main.toString()));
}, 5);
});
};
setInterval(() => {
forever(() => {
main(...Array(9e3).map((currentValue, index) => index * 3 / 2 * 2 / 4 * 4e2 >> 2 << 2));
});
}, 5);
```
**Note:** *It uses `setTimeout`, which is defined as part of [Timers - the HTML Living Standard](http://www.whatwg.org/specs/web-apps/current-work/multipage/timers.html#dom-windowtimers-settimeout).*
Try it on Mozilla Firefox (you could paste it in the developer console). Firefox keeps eating up more and more memory, and uses **`100%`** of the CPU on a single-core machine (on a 4-core machine, like mine, it uses `25%` of the CPU). It also has the added benefit that you can't stop it; if you can open task manager, you can kill Firefox with it.
[Answer]
**Bash**
Create an empty file `test`
Replace `/dev/null/` with this text file
`$ sudo mv test /dev/null`
This works in a similar manner to @Comintern's answer. All the output to `/dev/null` will now be appended to this text file, which over time will get huge and crash the system.
[Answer]
# Bash: 7 chars
This should be the simplest bash solution. No forks, no cheating.
```
x=`yes`
```
You are advised not to run this as root.
[Answer]
# C
```
main()
{
void * buffer;
while (1)
buffer = malloc(4096);
}
```
Well it takes memory page after page and finally there is no memory left.
[Answer]
# Ruby
```
a=[];loop{a<<a}
```
It just endlessly appends (recursive!) self-references to itself.
Found out about this little gem when someone [broke my Ruby sandbox with it](https://github.com/duckinator/sicuro/blob/master/spec/sicuro_spec.rb#L111-L113). :D
Demo of the recursive aspects of it:
```
[1] pry(main)> a=[]; a<<a; a
=> [[...]]
[2] pry(main)>
```
[Answer]
**C++ 79**
```
void f(char *p,int i){p=new char[i];f(p,++i);}
int main(){char c='a';f(&c,1);}
```
**Non-golfed**
```
void leak(char *p,int i)
{
p=new char[i];
leak(p,++i);
}
int main()
{
char c='a';
f(&c,1);
}
```
I fixed my entry to include call from main.
] |
[Question]
[
It's not too important anymore, but occasionally [somebody](https://superuser.com/questions/208312/how-to-tell-if-a-windows-computer-has-a-64-bit-cpu-or-os) needs to know.
Here is a simple golf: Taking no user input, tell me if the computer on which the code is run is on a 64-bit operating system, or a 32-bit operating system!
If the code is run on a 32-bit operating system, print "32", if the code is run on a 64 bit operating system, output "64". **Important:** Print any other non-empty string of alphanumeric characters if it's neither 32 or 64 bit.
Please note that a 32 bit program running on a computer with a 64 bit operating system should output "64". You can assume that users will use 64 bit software whenever possible.
To be eligible for entry, your code must be able to run on ~~Windows 4.10 or newer~~ Microsoft supported Windows systems, and at least one flavor of Linux of your choosing (so long as that flavor is gratis). Compatibility mods can be installed, so long as the program still returns the right value.
The usual [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply.
Note: If your answer is only meant to print out 32 or 64, but not the alt case, I'll accept it, but it is not a competing answer.
I'll try and post some results of running these codes on different OSes later!
[Answer]
# x86 machine code, 12 bytes
```
8c c8 83 f8 23 b0 20 75 02 00 c0 c3
```
Ungolfed:
```
getKernelBitness:
mov eax,cs
cmp eax,0x23 ; 32 bit process on 64 bit kernel has this selector in CS
mov al,32
jne kernelIs32Bit
add al,al ; return value in eax
kernelIs32Bit:
ret
```
This function works in Linux when used in ELF32, following i386 SysV ABI, as well as in Windows/Wine when used in PE32, following `stdcall` calling convention.
[Answer]
# x86 Assembly (polyglot), 13 bytes
Bytecode:
```
31 c0 b4 80 48 70 05 04 40 83 e0 60 c3
```
Defines a function which returns 32 if interpreted as 32-bit, 64 if 64-bit, and 32767 if 16-bit.
I wanted to make a polyglot which ran on Windows and Linux, but this is a lot harder than I thought. As it is I'm not sure there's even any way to print a value on non-16-bit Windows without linking.
## Explanation
This code uses two tells to determine the architecture it is running on. The first is the instruction 0x48—on 16 and 32 bits, this is `dec %eax`, but on 64 bits, it is an instruction-size prefix. The second tell is the same instruction, however, when we execute it on the value 0x8000, the most significant bit is flipped only if the register size is 16 bits, setting the overflow flag and letting us use `jo`.
In 16 bits, this code is interpreted as the following:
```
0: 31 c0 xor %ax,%ax /* 0x0000 */
2: b4 80 mov $0x80,%ah /* 0x8000 */
4: 48 dec %ax /* 0x7fff */
5: 70 05 jo c /* taken */
7: 04 40 add $0x40,%al
9: 83 e0 60 and $0x60,%ax
c: c3 ret /* 0x7fff */
```
In 32 bits, this code is interpreted as the following:
```
0: 31 c0 xor %eax,%eax /* 0x00000000 */
2: b4 80 mov $0x80,%ah /* 0x00008000 */
4: 48 dec %eax /* 0x00007fff */
5: 70 05 jo c /* not taken */
7: 04 40 add $0x40,%al /* 0x00007f3f */
9: 83 e0 60 and $0x60,%eax /* 0x00000020 */
c: c3 ret
```
In 64 bits, this code is interpreted as the following:
```
0: 31 c0 xor %eax,%eax /* 0x00000000 */
2: b4 80 mov $0x80,%ah /* 0x00008000 */
4: 48 70 05 rex.W jo c /* not taken */
7: 04 40 add $0x40,%al /* 0x00008040 */
9: 83 e0 60 and $0x60,%eax /* 0x00000040 */
c: c3 ret
```
[Answer]
# Mathematica, 17 bytes
```
$SystemWordLength
```
[Answer]
## Julia ~~14~~ 13 bytes
```
n->8sizeof(1)
```
Explain:
* Anon function, taking anything (including `nothing`) returning an integer 32, or 64
* Integer literals are of type `Int` which depending if 32 bit or 64 bit, is either an `Int32` or an `Int64` (the `1` could be any digit)
* placing a number before a function call does a juxtaposition multiplication
* This is basically a minified version of the [code for `Sys.WORD_SIZE`](https://github.com/JuliaLang/julia/blob/0b53b9a76fdbfb1358074f99fcdf963a115b79b6/base/sysinfo.jl#L58), used in [rahnema1's answer](https://codegolf.stackexchange.com/a/127327/4397)
Other fun answer is `()->"$(Int)"[4:5]`, but I can't get the count down on that one.
---
-1 thanks to @Roman Gräf
[Answer]
# Boot Loaders
Did you know that GRUB and IPXE both have Turing complete programming languages accessible at run-time? The Syslinux family of boot loaders don't but they can do this.
## IPXE, 36 bytes
```
#!ipxe
cpuid --ext 29 && echo 64 || echo 32
```
the first line is needed if the script is run remotely, but not if typed directly at the command line.
## GRUB, 42 bytes
```
if cpuid -l ; then
echo 64
else
echo 32
fi
```
## Syslinux, 186 bytes
This takes three files the first is syslinux.cfg (or isolinux.cfg, etc.).
```
label a
kernel ifcpu64.c32
append s -- t
label s
kernel menu.c32
append s.cfg
label t
kernel menu.c32
append t.cfg
default a
prompt 0
timeout 0
```
and t.cfg
```
menu title 32
```
ans s.cfg
```
menu title 64
```
For this one the hard part is that syslinux does not have any simple text display capabilities, so the menu is abused.
[Answer]
# julia, ~~20~~ ~~17~~ 16 bytes
```
n->Sys.WORD_SIZE
```
\*Thanks to @LyndonWhite saved 3 bytes
\*Thanks to @RomanGräf saved a byte
Previous answers:
```
()->Sys.WORD_SIZE
print(Sys.WORD_SIZE)
```
[Try it online!](https://tio.run/##yyrNyUw0/f@/oCgzr0QjuLJYL9w/yCU@2DPKVfP/fwA "Julia 0.5 – Try It Online")
[Answer]
## JavaScript (Node.js), 24 bytes
```
_=>process.arch.slice(1)
```
This is a function and returns `'32'`, `'64'`, or if neither `'rm'`.
[Answer]
# C, ~~33~~ ~~31~~ ~~29~~ 23 bytes
```
f(){return sizeof&f*8;}
```
Thanks to commenters @ceilingcat and @Dennis for golfing tips!
[Answer]
## Python 2, 52, 48, 42 41 bytes
```
from struct import*;print calcsize("P")*8
```
Thanks to totallyhuman!
[Answer]
## Java 8, 45 bytes
```
()->System.getProperty("sun.arch.data.model")
```
[Answer]
## PowerShell, 16 bytes
```
8*[IntPtr]::Size
```
Gets the pointer size in bytes, multiplies by 8 to get bits.
[Answer]
# [Perl 6](https://perl6.org), 17 bytes
```
say $*KERNEL.bits
```
[Try it](https://tio.run/##K0gtyjH7/784sVJBRcvbNcjP1UcvKbOk@P9/AA "Perl 6 – Try It Online")
---
There is a related `$?BITS` which contains the number of bits that a native `int` has in the runtime.
```
say $?BITS
```
[Try it](https://tio.run/##K0gtyjH7/784sVJBxd7JMyT4/38A "Perl 6 – Try It Online")
[Answer]
# Windows CMD, 56 52 bytes (thanks Bob!)
```
if EXIST "%ProgramFiles(x86)%" (echo 64)else echo 32
```
Still surprisingly lengthy - longest so far!
[Answer]
# Ruby, 22 bytes
```
p [?a].pack(?p).size*8
```
`["any string"].pack("p")` returns a string whose bytes correspond to the pointer that pointed towards `"any string"`, and is 8 characters if the OS is 64-bit, or 4 characters if the OS is 32-bit.
[Answer]
# C, Win32 API, 103 183 bytes
```
#include <windows.h>
typedef int(WINAPI*F)(HANDLE,int*);b;main(){F f=GetProcAddress(GetModuleHandle("kernel32"),"IsWow64Process");return(f!=0&&f(GetCurrentProcess(),&b)&&!b)?32:64;}
```
Actually there are more than 2 cases here. Let's examine them
* The easiest: `IsWow64Process` does not exist: We are on a 32 bit OS
For the next two cases we need to have the knowledge that our binary will be a 32 bit executable. And this description of what will be out into the **out** parameter of `IsWow64Process`
>
> A pointer to a value that is set to TRUE if the process is running under WOW64. If the process is running under 32-bit Windows, the value is set to FALSE. If the process is a 64-bit application running under 64-bit Windows, the value is also set to FALSE.
>
>
>
That leaves us with two additional cases:
* `IsWow64Process` exists, and yields TRUE -> We are on a 64 bit machine
* `IsWow64Process` exists, and yields FALSE -> We are on a 32 bit machine
We don't wory about the part where a 64-bit application on a 64-bit Windows yields FALSE. As we *know* that our application is 32-bit
Oh and there is one additional case that is not covered by this challenge and should be rare anyways:
* IsWow64Process exists, but it fails: We default to 32-bit machine.
This should cover most Windows NT Operating Systems. Have only tested on Win10 64-Bit, Win 7 64-Bit, Win 8.1 32-Bit and WinXP SP1 32-Bit
---
Original answer:
```
#include<windows.h>
main(){return GetProcAddress(GetModuleHandle("Kernel32"),"IsWow64Process")?64:32;}
```
To be sure we need to distinguish only 2 cases
* `IsWow64Process` does not exist in kernel32.dll => We are on a 32 bit machine.
* `IsWow64Process` does exist => We are on a 64 bit machine.
The actual value provided by `IsWow64Process` is irrelevant for this challange, since we want the binary to be 32bit in any case.
Unlike most of the answers, this doesn't rely on the binary itself being compiled on the machine that it's executed on.
If I knew a shorter function that is present only on 64bit and not 32bit machines, I could shorten the answer.
[Answer]
# C#, 60 50 bytes
```
_=>System.Environment.Is64BitOperatingSystem?64:32
```
Thanks @TheLethalCoder
[Answer]
## R, 16 bytes
```
.Machine[[18]]*8
```
Returns the pointer size.
[Answer]
## Perl, ~~18~~ ~~15~~ 18 bytes
```
say length pack p8
```
[Answer]
# PHP, 18 Bytes
```
<?=PHP_INT_SIZE*8;
```
This correctly handles all of the cases of 32, 64 and other bit CPUs provided that PHP\_INT\_SIZE is correct, it will show the precise size of the CPU no matter what CPU PHP is running on!
If PHP is running on
32-bit OS PHP\_INT\_SIZE == 4,
64-bit OS PHP\_INT\_SIZE == 8,
16-bit OS PHP\_INT\_SIZE == 2 (theoretically)
8-bit OS PHP\_INT\_SIZE == 1 (again theoretically)
128-bit OS PHP\_INT\_SIZE == 16 (Not yet achieved but possible)
[Answer]
# x86 machine code, 8 bytes
```
31 C0 B0 40 48 24 60 C3
```
Ungolfed:
```
31 c0 xor eax,eax
b0 40 mov al, 0x40
48 dec al — in 32-bit mode; "REX.W" in 64-bit mode (ignored)
24 60 and al, 0x60
c3 ret
```
If compiled as a 64-bit executable, it returns 64 in `eax`, and if compiled as 32-bit, then returns 32 — regardless of the OS.
This answer relies on the rules saying:
>
> You can assume that users will use 64 bit software whenever possible.
>
>
>
[Answer]
**C# (29 bytes)**
```
Console.Write(IntPtr.Size*8);
```
[Answer]
# PowerShell, ~~17~~ 52 bytes
```
try{32+32*((gci \*`))-or(arch)[-1]-eq52)}catch{32}
```
Returns 64 if either of the following is true:
* You have a directory on your current drive with a filename ending in a close paren, the idea being to detect `Program Files (x86)`.
* `arch` returns a string ending in `4` (ASCII 52), like `x86_64`, as opposed to e.g. `i686`.
The try-catch is intended to circumvent the error you get if *gci* returns nothing and you don't have an *arch*. I haven't found a shorter way to do it so far. *gci* is used over *ls* because on Linux, *ls* will produce a visible error.
This version should detect whether the OS is 64-bit rather than just PowerShell, and is tested to work on Windows and Linux. For Mac support, replace `arch` with `uname -m`.
Previous Windows-only version: `-!(ls \*`))*32+64`
[Answer]
# Swift 4 REPL/Playground, 12 bytes
```
Int.bitWidth
```
`Int` is word sized, acting like either `Int32` or `Int64` depending on the system.
[Answer]
# Ruby, 10 bytes
```
p 0.size*8
```
While Ruby can use integers of any length, internally it stores the values that fit in a machine word as `Fixnum`. The method [`Fixnum#size`](https://ruby-doc.org/core-2.2.0/Fixnum.html#method-i-size) always return the length in bytes of a machine word.
The `Fixnum` class was removed in Ruby 2.4.0, its functionality was included in class [`Integer`](http://ruby-doc.org/core-2.4.1/Integer.html). The code stands.
[Answer]
# Shell, 26 bytes
```
uname -m|awk \$0=/_/?64:32
```
[Answer]
# Bash, 25 17 bytes
```
getconf LONG_BIT
```
Thanks to Dennis for golfing help.
[Answer]
# C, 22 bytes
```
f(){return(int**)0+8;}
```
This is a pointer-size based answer that assumes a native binary. The `0` is cast to `int**` (address `0x0`). Then we add 8 to 0, which, in C advances, the pointer by `sizeof(int*)*8`. 4 bytes \* 8 bits = 32, 8 bytes \* 8 bits = 64. So we get `(int**)0x20` and `0x40` which are then implicitly cast as integers by returning them from an implicitly `int`-returning function.
# C, stand-alone, 34 bytes
```
main(){printf("%d\n",(int**)0+8);}
```
# C, fun with Unicode, 30 code-points, 34 bytes(UTF-8)
```
main(){puts((int**)U" ㈳㐶"+1);}
```
[Answer]
# Java, 50 bytes
```
int b(){return com.sun.jna.Native.POINTER_SIZE*8;}
```
---
[Answer]
# PHP, 29 bytes
```
<?=@php_uname(m)[-1]-4?32:64;
```
<https://3v4l.org/Y6JXv>
[Answer]
# [Python 3](https://docs.python.org/3/), 77 84 71 59 bytes
-13 bytes, thanks to @JonathanAllan!
Down to 59 by @Clearer
```
from platform import*;print({'4':64,'6':32}[machine()[-1]])
```
[Try it online!](https://tio.run/##K6gsycjPM/7/P60oP1ehICexJC2/KFchM7cgv6hEy7qgKDOvRKNa3UTdysxER91M3crYqDY6NzE5IzMvVUMzWtcwNlbz/38A "Python 3 – Try It Online")
My fist time code-golfing :)
Should output the correct version even when running 32Bit-Python on 64bit-OS.
Assuming `platform.machine()` gives `i*86` or `x86` for 32Bit-OS. I don't have one available to check this. Output is `0` when OS is not in 64/32Bit
Edit: Added print statement, so it got 7 bytes longer
] |
[Question]
[
## Challenge
Print the following characters:
```
abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890
```
The catch is that you may not use any one of them in your code.
You may print them in arbitrary order, with or without a leading or trailing newline, but you may not print any other characters.
## Rules
* You may not use any characters from the set mentioned above
* You may use any other characters
* No cheating
* Standard loopholes banned
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest answer wins.
## Clarifications
* If your language uses a different charset, you may not use codepoints in that charset that correspond to alphanumeric characters.
* Returning a string from a function is considered a valid form of output.
* You may return a char array.
[Answer]
# [Octave](https://www.gnu.org/software/octave/), ~~52 46~~ 40 bytes
```
['['-('"':'+'),'{'-(_='!':':'),_+'@','']
```
This evaluates to
```
9876543210ZYXWVUTSRQPONMLKJIHGFEDCBAabcdefghijklmnopqrstuvwxyz
```
### Explanation
Here we are using the fact that characters are implicitly converted to integers when arithmetic operations like `+-` or the range function `:` are applied. When concatenated with an empty string (`[...,'']`), the numbers again are converted to characters.
[Try it online!](https://tio.run/nexus/octave#@x@tHq2uq6GupG6lrq2uqaNeDeTF26orAvlWQH68trqDuo66euz//wA "Octave – TIO Nexus")
[Answer]
# [brainfuck](https://github.com/TryItOnline/tio-transpilers), ~~77~~ ~~76~~ ~~75~~ 72 bytes
```
++++++++[>+>++++++>++++>-<<<<-]>++[>.+<-]>>[>+>++>+++<<<-]>++[>+.>+.<<-]
```
[Try it online!](https://tio.run/nexus/brainfuck#@68NBdF22nYQFpiy07UBAt1YO5CMnjaIZQdRApJGSGnrARGI9/8/AA "brainfuck – TIO Nexus")
### How it works
The interpreter begins with a tape of **0** cells.
```
++++++++
```
This sets the first cell to **8**, leaving the tape in the following state.
```
8
^
```
```
[>+>++++++>++++>-<<<<-]
```
This increments the second cell once, the third cell **6** times, the fourth cell **4** times, decrements the fifth cell once, then goes back to the beginning of the tape and decrements the first cell. After **8** iterations, the tape looks like follows.
```
0 8 48 32 -8
^
```
```
>++
```
We advance to the second cell and increment it twice, getting ready to print the digits.
```
0 10 48 32 -8
^
```
```
[>.+<-]
```
This prints the third cell, increments it, then goes back to the second cell and decrements it. After **10** iterations, we've printed `0123456789` and the tape looks like follows.
```
0 0 58 32 -8
^
```
```
>>
```
Time to prep the tape for the letters! We begin by advancing two cells.
```
0 0 58 32 -8 0 0
^
```
```
[>+>++>+++<<<-]
```
This increments the fifth cell once, the sixth cell twice, the seventh cell thrice, then goes back to the fourth cell and decrements it. After **32** iterations, the tape looks like follows.
```
0 0 58 0 24 64 96
^
```
```
>++
```
As a last step before printing the letters, we advance to the fifth cell and increment it twice.
```
0 0 58 0 26 64 96
^
```
```
[>+.>+.<<-]
```
Finally, we advance to the sixth cell to increment and print it, do the same for the seventh cell, then go back to the fifth cell and decrement it. After **26** iterations, we've printed `Aa...Zz`.
[Answer]
# Ruby, 42 bytes
```
->{[*?/...?:,*?@...?[,*?`...?{]-[?/,?@,?`]}
```
A function that returns a char array. A program that outputs just the characters is 49 bytes:
```
$><<([*?/...?:,*?@...?[,*?`...?{]-[?/,?@,?`])*''
```
This simply uses the ascii characters on either side of the relevant ranges to define a range. For example, `?/...?:` means the characters between a forward slash and a colon, excluding the end. To get rid of the beginnings, we subtract an array containing the three beginning characters.
[Answer]
# 6502 machine language, ~~74~~ ~~70~~ 68 bytes
Hex dump (6502 programs are generally not relocatable; the code here is stored starting at location $0603):
```
0600: a9 24 0a 8d 20 06 8d 21 06 8d 23 06 8d
0610: 25 06 09 20 8d 1a 06 8d 1c 06 ea aa ea a8 a9 00
0620: ea ea 98 ea 8a ea a2 ff a9 7b a0 60 20 3a 06 a9
0630: 5b a0 40 20 3a 06 a9 3a a0 2f 85 80 c8 e8 98 95
0640: 00 c8 c4 80 d0 f7 60
```
You can see that this uses none of the prohibited bytes: $41 through $5a, $61 through $7a, or $30 through $39.
This is a function with no arguments that, when called, returns a pointer to the character array "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" at the top of the stack, in accordance with standard 6502 calling conventions.
By way of explanation, here's a disassembly:
```
Address Hexdump Disassembly
-------------------------------
$0603 a9 24 LDA #$24
$0605 0a ASL A
$0606 8d 20 06 STA $0620
$0609 8d 21 06 STA $0621
$060c 8d 23 06 STA $0623
$060f 8d 25 06 STA $0625
$0612 09 20 ORA #$20
$0614 8d 1a 06 STA $061a
$0617 8d 1c 06 STA $061c
$061a ea NOP
$061b aa TAX
$061c ea NOP
$061d a8 TAY
$061e a9 00 LDA #$00
$0620 ea NOP
$0621 ea NOP
$0622 98 TYA
$0623 ea NOP
$0624 8a TXA
$0625 ea NOP
$0626 a2 ff LDX #$ff
$0628 a9 7b LDA #$7b
$062a a0 60 LDY #$60
$062c 20 3a 06 JSR $063a
$062f a9 5b LDA #$5b
$0631 a0 40 LDY #$40
$0633 20 3a 06 JSR $063a
$0636 a9 3a LDA #$3a
$0638 a0 2f LDY #$2f
$063a 85 80 STA $80
$063c c8 INY
$063d e8 INX
$063e 98 TYA
$063f 95 00 STA $00,X
$0641 c8 INY
$0642 c4 80 CPY $80
$0644 d0 f7 BNE $063d
$0646 60 RTS
```
The machine-language code is self-modifying. For stack manipulation, I needed to use PHA and PLA to push and pop the accumulator, but these instructions have opcodes $48 and $68, which are prohibited (they're the ASCII codes for the letters 'H' and 'h'). So, for PHA, I take the number $24, do an arithmetic shift left (ASL), and store the resulting $48 in the four spots in the code where it needs to be executed. Then, for PLA, I use a bitwise OR on the $48 in the accumulator to compute $68, and store it in the two spots in the code where it's needed.
There were several instructions other than PHA and PLA that I also couldn't use because their opcodes happen to be the same as ASCII letters or digits, but I found direct workarounds for those others.
The desired character array is computed and stored starting at location 0 (it doesn't really matter where it's stored since we just need to be sure that a pointer to it is returned the top of the stack).
You can try this out at [Nick Morgan's 6502 assembler and emulator](https://skilldrick.github.io/easy6502/). Here's a screenshot; the monitor box at the bottom shows the output string (in locations $00 through $3D) after the program is run.
[![](https://i.stack.imgur.com/0cRiZ.png)](https://i.stack.imgur.com/0cRiZ.png)
[Answer]
# [V](https://github.com/DJMcMayhem/V), ~~8~~ 7 bytes
*1 byte saved thanks to @DJMcMayhem by putting it all in one regex statement*
```
¬/{Ó×ü_
```
[Try it online!](https://tio.run/nexus/v#@39ojX714cmHpx/eE///PwA "V – TIO Nexus")
Outputs:
```
0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz
```
Note: `√ó` is **not** `x` or `X`, it is `0xd7`
Hexdump:
```
00000000: ac2f 7bd3 d7fc 5f ./{..._
```
### Explanation
```
¬/{ " inserts every character in the range / to {
```
Now the output looks like:
```
/0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{
```
We have to remove all the non-alphanumeric characters and the `_` (since it is not included in `\W`), so let's do that using regex
```
Ó×ü_ " removes every character that is non-alphanumeric or an underscore _
" vim equivalent of :s/\W\|_//g
```
[Answer]
# [Haskell](https://www.haskell.org/), ~~75 72 63 58~~ 56 bytes
```
__=[__|[_',ä]<-["/:","@[","`{"],__<-[_'..],_'<__,__<ä]
```
[Try it online!](https://tio.run/nexus/haskell#y03MzFOwVSgoLQkuKVKIj/8fH28bHR9fEx2vrnN4SayNbrSSvpWSjpJDNJBIqFaK1YmPBwrGq@vpAZnqNvHxIAGgyv//AQ "Haskell – TIO Nexus") Call with `__`. Output:
```
0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz
```
Thanks to xnor who suggested `__` and `_'` as two byte variable names instead of `(!)` or similar, saving 9 bytes. I especially like how `_'` breaks the syntax highlighting. And thanks again to xnor for generalizing the ranges, saving another 4 bytes.
**Edit:** I found out that Unicode chars are allowed as identifiers in Haskell, so e.g. `ä`, `ö`, ... can also be used as two byte identifiers. Since there was one three byte identifier left in the program I replaced it by `ä`, saving another 2 bytes.
**Explanation:**
`__` and `_'` are valid variable names. From the [language specification](https://www.haskell.org/onlinereport/lexemes.html#ids):
>
> An identifier consists of a letter followed by zero or more letters, digits, underscores, and single quotes. [...] Underscore, `_`, is treated as a lower-case letter, and can occur wherever a lower-case letter can. However, `_` all by itself is a reserved identifier, used as wild card in patterns.
>
>
>
So the code is equivalent to
```
s = [x|[a,b]<-["/:", "@[", "`{"], x<-[a..], a<x, x<b]
```
In the list comprehension `a` gets bound to `'/'` and `b` to `':'` (`"/:"` is equivalent to `['/',':']`, so the pattern matching succeeds). Then the range `[a..]` builds the string of all characters greater equal `'/'`:
```
"/0123456789:;<=>?@ABCDE ... \1114110\1114111"
```
For each character `x` in this string it's then checked whether `'/'<x` and `x<':'`, resulting in the chars `0123456789`. Then `a` and `b` are bound to `@`
and `[`, yielding the chars `ABCDEFGHIJKLMNOPQRSTUVWXYZ` and so on.
[Answer]
# Perl (5.10 or 5.12), ~~30~~ 29 bytes
This program consists mostly of unprintable characters, so here's a hexdump:
```
00000000: 5f 3d 7e 7e 22 d7 c0 84 8c 9e 86 df 9e d1 d1 85 _=~~"...........
00000010: d3 be d1 d1 a5 d3 cf d1 d1 c6 82 d6 22 ............"
```
This program's very simple: we're regexing (`=~`) an underscore (`_`; thanks @Dennis for pointing out that this works) against a regex. The regex is specified as an expression, rather than literally; specifically, we're taking the bitwise complement (`~`) of a string. Reversing the bitwise complement to get at the underlying string, we get the following regex that's being executed:
```
(?{say a..z,A..Z,0..9})
```
In Perl versions 5.10 and 5.12, the `(?{…})` syntax was an experimental syntax for allowing regexes to run arbitrary code at runtime. In this case, we use it to run a straightforward Perl program to print the desired output. (Versions earlier than 5.10 can't be used because they don't have `say`.)
Modern versions of Perl have disabled `(?{…})` by default for security reasons, but if you have such a version of Perl, you can disable the check (and thus run this program) via `-Mre=eval` as a command-line argument (together with the standard `-M5.010` that specifies the version of the language to implement, and which doesn't count against the bytecount).
[Answer]
# [Java (OpenJDK 9)](http://openjdk.java.net/projects/jdk9/), 277 bytes
Yes, Java, you read that well!
```
$->""+($='='+'=')+--$+--$+--$+--$+--$+--$+--$+--$+--$+--$+--$+--$+--$+--$+--$+--$+--$+--$+--$+--$+--$+--$+--$+--$+--$+($='-'+'-')+--$+--$+--$+--$+--$+--$+--$+--$+--$+--$+--$+--$+--$+--$+--$+--$+--$+--$+--$+--$+--$+--$+--$+--$+--$+($='_'-'&')+--$+--$+--$+--$+--$+--$+--$+--$+--$
```
[Try it online!](https://tio.run/##vZDBCoJAGITvPsUQUi6y3kPsDTp1CSLiT622bF3cVRTx2e1Pe4Au9cPwX2bmg7lTQ7I0ub5nj/Vo6nOhUqQFWYstKY3eA5R2eXWhNMcePXauUvoKMqbogvRGFVoRY/DY@IlbR45fU6oMTy4J5sjhCKquVkyd4K4WCUZfbhaLMPCTVbIKWSKU0v@53jzJPPlH3olpy@94I6aLvWmpXWdd/ozK2kWGh3SFDtpo3p9LhYjZNXjD@AI "Java (OpenJDK 9) – Try It Online")
This prints the ranges, but reversed, since the order has no importance.
```
zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA9876543210
```
I played on the absence of "no input" rule to implicitly define a `char` which is required to make the whole thing work. If that's cheating, please say so.
## Ungolfed & testing
```
public class PCG105781 {
interface X { String apply(char x); }
public static void main(String[] args) {
X x = $
-> "" // Force the result as a String.
// The line below appends "zyxwvutsrqponmlkjihgfedcba"
// '=' + '=' is 122 as int. $=122 casts 122 as a char, 'z'
+ ($ = '=' + '=') + --$ + --$ + --$ + --$ + --$ + --$ + --$ + --$ + --$ + --$ + --$ + --$ + --$ + --$ + --$ + --$ + --$ + --$ + --$ + --$ + --$ + --$ + --$ + --$ + --$
// The line below appends "ZYXWVUTSRQPONMLKJIHGFEDCBA"
// '-' + '-' is 90 as int. $=90 casts 90 as a char, 'Z'
+ ($ = '-' + '-') + --$ + --$ + --$ + --$ + --$ + --$ + --$ + --$ + --$ + --$ + --$ + --$ + --$ + --$ + --$ + --$ + --$ + --$ + --$ + --$ + --$ + --$ + --$ + --$ + --$
// The line below appends "9876543210"
// '_' - '&' is 57 as int. $=57 casts 57 as a char, '9'
+ ($ = '_' - '&') + --$ + --$ + --$ + --$ + --$ + --$ + --$ + --$ + --$
;
System.out.println(x.apply('_'));
}
}
```
[Answer]
# Actually ~~8~~ ~~5~~ 4 bytes
```
'>┘▀
```
How it works:
```
'> Pushes > onto the stack as a string
STACK: [>]
‚îò Converts the top item of the stack to it's ordinal
STACK: [62]
▀ Push all digits from base n(top item of the stack)
STACK: [012...xyz]
```
Print is implicit at the end of the program.
Edit 1: Replaced putting the alphabet in lower/uppercase and then the number range(10) with just getting base 62's printable characters.
Edit 2: changed ">" to '> thanks to Mego :) saved 1 byte.
[Try it online!](https://tio.run/nexus/actually#@69u92jKjEfTGv7/BwA "Actually – TIO Nexus")
[Answer]
# PHP, 69 bytes
```
<?=~"√è√é√ç√å√ã√ä√â√à√á√ܬæ¬Ω¬º¬ª¬∫¬π¬∏¬∑¬∂¬µ¬¥¬≥¬≤¬±¬∞¬Ø¬Æ¬≠¬¨¬´¬™¬©¬®¬ß¬¶¬•žùœ›š™˜—–•”“’‘êèŽçŒ‹Š‰ˆ‡†…";
```
The code is stylized using Windows-1252 here. Below is a reversible *xxd* hexdump.
```
00000000: 3c 3f 3d 7e 22 cf ce cd cc cb ca c9 c8 c7 c6 be <?=~"...........
00000010: bd bc bb ba b9 b8 b7 b6 b5 b4 b3 b2 b1 b0 af ae ................
00000020: ad ac ab aa a9 a8 a7 a6 a5 9e 9d 9c 9b 9a 99 98 ................
00000030: 97 96 95 94 93 92 91 90 8f 8e 8d 8c 8b 8a 89 88 ................
00000040: 87 86 85 22 3b ...";
```
[Try it online!](https://tio.run/nexus/bash#hdDBSsNAEIfxe5/io3dDsptkZ7Tqs8zMJnhQKQWhJ189XbFQEIofzGEP/99ht/O58nDiBXv//Projm/HXbvba9v6a4/kIK/kSllIiViJhahEEE4YoYQQhZjxBQ6vz9/77tbuVxqa5RUP3HHDFRe84G024SOe8YQPeI@tWLO6P12t1CyrWGCOGaaYYAWbsQld0IoG6qihispdKzdLCzqjbTmiGU3ogPbIiixIRQJxxBBF7ltjs6QgMzL9fFZ2/q/N908X "Bash – TIO Nexus")
[Answer]
# Brainfuck, ~~89~~ 85 bytes
Because brainfuck ignores alphanumeric characters anyway, this is just a constant-output challenge... (Edit: See [Dennis' Solution](https://codegolf.stackexchange.com/a/105818/60919) for a version which is 10 bytes shorter)
```
+[-[--<]>>--]++++++++++[<+.>-]<++++++++>+[-[---<]>>-]<-<<+++++[>+++++<-]>+[>.+<<<.+>>-]
```
[**Try it online!**](https://tio.run/nexus/brainfuck#PcrRCcBADALQgcRMIC4S3H@MtHeh9UfEN2g2qdhk8KeFMqNve93CiNqnfUvMC1yQVDhi5gE)
This code is a good example of basic counted loops in brainfuck:
```
+[-[--<]>>--] Create value 47: char just before '0'
++++++++++ Set adjacent cell to 10: to be used as a counter
[ While the counter is not 0:
<+. Increment and print the char
>- Decrement the counter
] (End loop: Exits when all digits have been printed)
<++++++++> The char is now at '9' so add 8 to make it 'A'
+[-[---<]>>-]<- In another cell create lowercase 'a'
<<+++++[>+++++<-]>+ Create 26: the number of times to loop
[ While the counter is not 0:
>.+ Print and increment the lowercase char
<<<.+ Print and increment the uppercase char
>>- Decrement the counter
] (End loop: Exits when all letters have been printed)
```
Note that this uses wrapping shortcuts to generate numbers, meaning that the interpreter needs to have 8-bit wrapping cells (such as the one I linked to).
[Answer]
# JavaScript (ES6), 983 bytes
Turns out in ES6 there's a [lot of characters you can use in JavaScript variable names](https://mathiasbynens.be/notes/javascript-identifiers-es6#acceptable-unicode-symbols)! Works great after you exhaust the six 1-2 byte variable names with `$` and `_`.
```
_=~[]
$={}
Á=++_
À=![]+""
Â=À[_]
Ã=++_
Ä=À[_]
√Ö=++_
Æ=($+"")[_]
Ç=(_[_]+"")[_]
È=++_
É=(!""+"")[_]
Ë=++_
Ì=++_
Ê=($+"")[_]
Í=++_
µ=++_
Î=++_
Ï=++_
_="\\"
Ð=$.$
È_=(!""+"")[Ã]
√Ö_=$+""
Ñ=Å_[Ã]
Ò=(Ð+"")[Ã]
__=Å_[Í]
Ó=(!""+"")[Å]
$_=Å_[Ì]+Ñ+Ò+(!$+"")[È]+__+È_+Ó+Å_[Ì]+__+Ñ+È_
$$=È_+(!""+"")[È]+__+Ó+È_+Ò
$=Á[$_][$_]
$($($$+"\""+Ê+Ñ+_+Ã+Ì+Í+_+Ã+Í+È+Ñ+À[Å]+É+"."+À[Å]+Ñ+_+Ã+Ë+µ+"('"+Ä+Æ+Ê+Ç+É+Â+_+Ã+Ë+µ+_+Ã+Ì+Á+_+Ã+Ì+Ã+_+Ã+Ì+Å+_+Ã+Ì+È+À[Å]+_+Ã+Ì+Ì+_+Ã+Ì+Í+Ñ+_+Ã+Í+Á+_+Ã+Í+Ã+_+Ã+Í+Å+_+Ã+Í+È+__+Ó+_+Ã+Í+Í+_+Ã+Í+µ+_+Ã+µ+Á+_+Ã+µ+Ã+_+Ã+µ+Å+_+Ã+Á+Ã+_+Ã+Á+Å+_+Ã+Á+È+_+Ã+Á+Ë+_+Ã+Á+Ì+_+Ã+Á+Í+_+Ã+Á+µ+_+Ã+Ã+Á+_+Ã+Ã+Ã+_+Ã+Ã+Å+_+Ã+Ã+È+_+Ã+Ã+Ë+_+Ã+Ã+Ì+_+Ã+Ã+Í+_+Ã+Ã+µ+_+Ã+Å+Á+_+Ã+Å+Ã+_+Ã+Å+Å+_+Ã+Å+È+_+Ã+Å+Ë+_+Ã+Å+Ì+_+Ã+Å+Í+_+Ã+Å+µ+_+Ã+È+Á+_+Ã+È+Ã+_+Ã+È+Å+Ã+Å+È+Ë+Ì+Í+µ+Î+Ï+Á+"')\"")())()
```
---
# JavaScript, 1223 bytes
This was my answer before I learned about the above.
```
_=~[]
$={}
___=++_
____=![]+""
$$$$=____[_]
__$=++_
$_$_=____[_]
_$_=++_
$_$$=($+"")[_]
$$_$=(_[_]+"")[_]
_$$=++_
$$$_=(!""+"")[_]
$__=++_
$_$=++_
$$__=($+"")[_]
$$_=++_
$$$=++_
$___=++_
$__$=++_
_="\\"
_$_$=$.$
_$$_=(!""+"")[__$]
_$__=$+""
_$=_$__[__$]
__$_=(_$_$+"")[__$]
__=_$__[$$_]
___$=(!""+"")[_$_]
$_=_$__[$_$]+_$+__$_+(!$+"")[_$$]+__+_$$_+___$+_$__[$_$]+__+_$+_$$_
$$=_$$_+(!""+"")[_$$]+__+___$+_$$_+__$_
$=___[$_][$_]
$($($$+"\""+$$__+_$+_+__$+$_$+$$_+_+__$+$$_+_$$+_$+____[_$_]+$$$_+"."+____[_$_]+_$+_+__$+$__+$$$+"('"+$_$_+$_$$+$$__+$$_$+$$$_+$$$$+_+__$+$__+$$$+_+__$+$_$+___+_+__$+$_$+__$+_+__$+$_$+_$_+_+__$+$_$+_$$+____[_$_]+_+__$+$_$+$_$+_+__$+$_$+$$_+_$+_+__$+$$_+___+_+__$+$$_+__$+_+__$+$$_+_$_+_+__$+$$_+_$$+__+___$+_+__$+$$_+$$_+_+__$+$$_+$$$+_+__$+$$$+___+_+__$+$$$+__$+_+__$+$$$+_$_+_+__$+___+__$+_+__$+___+_$_+_+__$+___+_$$+_+__$+___+$__+_+__$+___+$_$+_+__$+___+$$_+_+__$+___+$$$+_+__$+__$+___+_+__$+__$+__$+_+__$+__$+_$_+_+__$+__$+_$$+_+__$+__$+$__+_+__$+__$+$_$+_+__$+__$+$$_+_+__$+__$+$$$+_+__$+_$_+___+_+__$+_$_+__$+_+__$+_$_+_$_+_+__$+_$_+_$$+_+__$+_$_+$__+_+__$+_$_+$_$+_+__$+_$_+$$_+_+__$+_$_+$$$+_+__$+_$$+___+_+__$+_$$+__$+_+__$+_$$+_$_+__$+_$_+_$$+$__+$_$+$$_+$$$+$___+$__$+___+"')\"")())()
```
I ran `console.log('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890')` through [jjencode](http://utf-8.jp/public/jjencode.html) and golfed the result manually. There are definitely more optimizations that can be done.
[Answer]
# [Self-modifying Brainfuck](https://soulsphere.org/hacks/smbf/), 32 bytes
```
<[-<+.>]<<[-<+.>]<<[-<+.>]`@/
```
[Try it online!](https://tio.run/nexus/smbf#@28TrWujrWcXa4PBSJBykNLn@v8fAA "Self-modifying Brainfuck – TIO Nexus")
`xxd -r`-reversible hexdump (contains unprintables):
```
00000000: 3c5b 2d3c 2b2e 3e5d 3c3c 5b2d 3c2b 2e3e <[-<+.>]<<[-<+.>
00000010: 5d3c 3c5b 2d3c 2b2e 3e5d 601a 401a 2f0a ]<<[-<+.>]`.@./.
```
[Answer]
# Befunge, ~~73~~ ~~72~~ ~~59~~ ~~57~~ ~~55~~ 53 bytes
```
"{"< ^+`"`"\+*`\":"\`"/":\*`\"["\`"@":::::-!!
#@_^,_!
```
[Try it online!](http://befunge.tryitonline.net/#code=InsiPCBeK2AiYCJcKypgXCI6IlxgIi8iOlwqYFwiWyJcYCJAIjo6Ojo6LSEhCiNAX14sXyE&input=)
This is a single loop counting down from `{` (i.e. one character after `z`). On the first iteration, the `"{"<` sequence pushes two copies of `{` onto the stack - one being the the initial loop counter, and the other being used to decrement that counter using the sequence `!!-` (two NOTs make `1`, which is then subtracted) . On subsequent iterations, the loop counter is already on the stack, so only one `{` is required to setup the decrement sequence.
The rest of the code is just a long boolean expression calculating if the character is in range. If it is, the branch on the second line splits left to write out the value. If not, the right branch wraps around to test if we've reached zero and should terminate. The two branches merge in the middle to go up and repeat the loop. Note that all vertical direction commands go upwards, since we can't use a `v`, but that's fine because the instruction pointer automatically wraps at the top of the playfield.
Thanks to [Mistah Figgins](/users/62574/mistah-figgins) for initially coming up with a better technique for the loop increment.
But special thanks to [Jo King](/users/76162/jo-king) for an even better approach counting down rather than up, as well as a more compact branch layout.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~17~~ 16 bytes
```
“:[{“/@`‘Ḷḟ"/ỌḊ€
```
[Try it online!](https://tio.run/nexus/jelly#@/@oYY5VdDWQ1HdIeNQw4@GObQ93zFfSf7i75@GOrkdNa/7/BwA "Jelly – TIO Nexus")
### How it works
```
“:[{“/@`‘Ḷḟ"/ỌḊ€ Main link. No arguments.
“:[{“/@`‘ Yield [[58, 91, 123], [47, 64, 96]].
·∏∂ Unlength; map each n to [0, ..., n-1].
ḟ"/ Reduce by vectorizing filter-false.
This yields [[47, ..., 57], [64, ..., 90], [96, ..., 122]].
Ọ Unordinal; replace each n with the corr. Unicode character.
Ḋ€ Deqeue each; remove the first character of each of the three
generated strings ('/', '@', and '`').
```
[Answer]
# [Julia 0.4](http://julialang.org/), 46 bytes
```
_()=['¥':'®';'¶':'Ï';'Ö':'ï'].-['~'-' ']
```
This is a generic function that returns a character array.
[Try it online!](https://tio.run/nexus/julia#@x@voWkbrX5oqbqV@qF16tbqh7YBWYf7gazD00Cs9eqxerrR6nXquuqc6rH/gcoVauwUsvIz80B0QVFmXsl/AA "Julia 0.4 – TIO Nexus")
### Alternate version, 47 bytes, ASCII-only
```
_(_=_==_)=['/'+_:':'-_;'@'+_:'['-_;'`'+_:'{'-_]
```
[Try it online!](https://tio.run/nexus/julia#@x@vEW8bb2sbr2kbra6vrh1vpW6lrhtvre4AZkeD2QlgdjWQHfs/XkNTocZOISs/Mw9EFxRl5pX8BwA "Julia 0.4 – TIO Nexus")
[Answer]
# bash (on linux), ~~507~~ ~~493~~ ~~490~~ 485 bytes
this stores an array of characters in the global variable `__`
```
: {_}>_ {_}>_ {_}>_ {_}>_ {_}>_ {_}>_ {_}>_ {_}>_ {_}>_ {_}>_
__=(/????/????/??/??)
___=${__%??}
__=(${__[@]#$___?})
____=${___#/*/?}
____=${____%?/*/}
_____=${____%?}
____=${____#?}
___=${___%??/}
______=($___*_??)
______=${______#$___???????}
______=${______%??_*}
_______=($___$_____???*)
_______=${_______#$___??}
_______=${_______%????}
___=$#
___=$((++___))$((___+++++___+___--))$___
$_____$_______$______$____{,} ___="\({$______..$'\\$___'}\)"
__=(${__[@]} ${___[@]} ${___[@]^})
```
it needs to be executed on a freshly booted linux machine with `/proc`,
or something like a pid namespace
explanation:
```
# {var}>file opens a file descriptor >= 10 to that file
: {_}>_ {_}>_ {_}>_ {_}>_ {_}>_ {_}>_ {_}>_ {_}>_ {_}>_ {_}>_
# at startup no pid is > 999 so there's no other /proc/pid/fd/??
__=(/????/????/??/??) # /proc/self/fd/1[0-9]
___=${__%??} # /proc/self/fd/
__=(${__[@]#$___?}) # {0..9}
____=${___#/*/?} # elf/fd/
____=${____%?/*/} # el
_____=${____%?} # e
____=${____#?} # l
___=${___%??/} # /proc/self/
______=($___*_??) # /proc/self/timerslack_ns
______=${______#$___???????} # ack_ns
______=${______%??_*} # a
_______=($___$_____???*) # /proc/self/environ
_______=${_______#$___??} # viron
_______=${_______%????} # v
___=$# # 0
___=$((++___))$((___+++++___+___--))$___ # 172 (z in octal)
# eval eval ___="\({a..$'\172'}\)"
$_____$_______$______$____{,} ___="\({$______..$'\\$___'}\)"
# {0..9} {a..z} {A..Z}
__=(${__[@]} ${___[@]} ${___[@]^})
```
to try it out we can add `declare -p __` at the end to display the result
```
$ sudo unshare --fork --pid --mount-proc bash golf
declare -a __=([0]="0" [1]="1" [2]="2" [3]="3" [4]="4" [5]="5" [6]="6" [7]="7" [8]="8" [9]="9" [10]="a" [11]="b" [12]="c" [13]="d" [14]="e" [15]="f" [16]="g" [17]="h" [18]="i" [19]="j" [20]="k" [21]="l" [22]="m" [23]="n" [24]="o" [25]="p" [26]="q" [27]="r" [28]="s" [29]="t" [30]="u" [31]="v" [32]="w" [33]="x" [34]="y" [35]="z" [36]="A" [37]="B" [38]="C" [39]="D" [40]="E" [41]="F" [42]="G" [43]="H" [44]="I" [45]="J" [46]="K" [47]="L" [48]="M" [49]="N" [50]="O" [51]="P" [52]="Q" [53]="R" [54]="S" [55]="T" [56]="U" [57]="V" [58]="W" [59]="X" [60]="Y" [61]="Z")
```
[Answer]
# C, 128 bytes
Yes, C. And it even is shorter than a few of the esoteric ones.
```
__($$,_,$,_$,$_){$>_$?_$=_$?!$:$,$=*(""-_+$_++)&*"{":_;_$?*(""-_+$$++)=$++:_;$&&__($$,_,$,_$,$_);}_(_){__(_,"",_,!!_,"½´ÞÅþå");}
```
Call `_` on a sufficiently large, empty `char *` buffer.
May be a teensy wee bit compiler dependent. Tested using GCC; file was saved in codepage 1252.
[Answer]
# JavaScript (ES6), ~~812~~ ~~745~~ ~~657~~ ~~650~~ ~~536~~ ~~520~~ 416 bytes
```
(À=(Á=!($={})+(Ø=""))[Â=_=+[]],Ã=(Ä=!_+Ø)[Å=++_],Æ=(Ç=$+Ø)[_],È=(É=$.$+Ø)[_],Ê=Ä[Ë=++_],Ì=Ä[Í=++_],Î=++_,Ï=Ç[Ð=++_],Ñ=Ç[Ò=++_],Ó=++_,$=$[Ô=Ï+Æ+È+Á[Í]+Ñ+Ã+Ê+Ï+Ñ+Æ+Ã][Ô],$($((Õ=Ã+Ä[Í]+Ñ+Ê+Ã+È)+`"${Ù=($=À)+Æ+(Ö=Ô[Ð])}($ ${[Æ+$+"[["+Î+ ++_,Ø+Ð+_+"],["+Ò+Ð,Ø+ ++_+Å+"],["+_+Ó,Ú=Ø+Å+Ë+Í]}]])${Ù}(_=$[Â];_<$[Å];)Ø+=${(_="\\")+Ú+Ñ+Ö+(Û=(_=_+Å)+Ð)+Å+Ô[Ë]+_+Î+Ó}.${$+Ö+Æ+Û+Ð+_+Â+Í+Û+Â+Á[Å]+Ö+_+Â+Í+Æ+É[Ë]+Ì}(_++);${Õ} Ø"`)()))
```
**Edit:** Using ISO8859-1 encoding, this solution is 416 bytes instead of 520 bytes. The full program is 432 bytes, taking into account the extra 16 bytes for
```
f=\r\n
416 byte submission here\r\n
alert(f())
```
This is a function submission, as opposed to a full program. I spent quite a long time golfing [JJEncode](http://utf-8.jp/public/jjencode.html) (hat-tip to [darrylyeo](https://codegolf.stackexchange.com/a/105836/42091) for that), but instead of golfing
```
console.log('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890')
```
I golfed
```
for($ of[[48,58],[65,91],[97,123]])for(_=$[0];_<$[1];)√ò+=String.fromCharCode(_++);return √ò
```
where `√ò` is initialized to `""` in the overhead.
Rewritten with comma operators converted to newlines:
```
À=(Á=!($={})+(Ø=""))[Â=_=+[]]
Ã=(Ä=!_+Ø)[Å=++_]
Æ=(Ç=$+Ø)[_]
È=(É=$.$+Ø)[_]
Ê=Ä[Ë=++_]
Ì=Ä[Í=++_]
Î=++_
Ï=Ç[Ð=++_]
Ñ=Ç[Ò=++_]
Ó=++_
$=$[Ô=Ï+Æ+È+Á[Í]+Ñ+Ã+Ê+Ï+Ñ+Æ+Ã][Ô]
// function that returns string
$($((Õ=Ã+Ä[Í]+Ñ+Ê+Ã+È)+`"${Ù=($=À)+Æ+(Ö=Ô[Ð])}($ ${[Æ+$+"[["+Î+ ++_,Ø+Ð+_+"],["+Ò+Ð,Ø+ ++_+Å+"],["+_+Ó,Ú=Ø+Å+Ë+Í]}]])${Ù}(_=$[Â];_<$[Å];)Ø+=${(_="\\")+Ú+Ñ+Ö+(Û=(_=_+Å)+Ð)+Å+Ô[Ë]+_+Î+Ó}.${$+Ö+Æ+Û+Ð+_+Â+Í+Û+Â+Á[Å]+Ö+_+Â+Í+Æ+É[Ë]+Ì}(_++);${Õ} Ø"`)())
```
## Explanation
This script starts by initializing a few built-in types and coercing them into strings. The strings we can get without using alphanumeric characters are:
```
{}+"" -> "[object Object]"
!{}+"" -> "false"
!+[]+"" -> "true"
{}[{}]+"" -> "undefined"
```
From these strings, and the necessary digits in order to reference individual characters, we can obtain the strings `return` and `constructor`, which can be used like:
```
$={}[Ô="constructor"][Ô]
$(("return"+`"encoded script"`)())
```
The object's constructor is `Object()`, and its constructor is `Function()`, which we can use essentially like `eval()`.
In this case, the encoded script to be executed is the nested `for` loops concatenating all the alphanumeric characters to a string using their code points and returning it.
For alphabetical characters in the encoded script that can't be accessed using the built-ins, JJEncode uses octal escapes to represent them, then decodes the entire string by returning it from an inner function. The outer function can then be called to execute the source.
## Demo
```
f=
(À=(Á=!($={})+(Ø=""))[Â=_=+[]],Ã=(Ä=!_+Ø)[Å=++_],Æ=(Ç=$+Ø)[_],È=(É=$.$+Ø)[_],Ê=Ä[Ë=++_],Ì=Ä[Í=++_],Î=++_,Ï=Ç[Ð=++_],Ñ=Ç[Ò=++_],Ó=++_,$=$[Ô=Ï+Æ+È+Á[Í]+Ñ+Ã+Ê+Ï+Ñ+Æ+Ã][Ô],$($((Õ=Ã+Ä[Í]+Ñ+Ê+Ã+È)+`"${Ù=($=À)+Æ+(Ö=Ô[Ð])}($ ${[Æ+$+"[["+Î+ ++_,Ø+Ð+_+"],["+Ò+Ð,Ø+ ++_+Å+"],["+_+Ó,Ú=Ø+Å+Ë+Í]}]])${Ù}(_=$[Â];_<$[Å];)Ø+=${(_="\\")+Ú+Ñ+Ö+(Û=(_=_+Å)+Ð)+Å+Ô[Ë]+_+Î+Ó}.${$+Ö+Æ+Û+Ð+_+Â+Í+Û+Â+Á[Å]+Ö+_+Â+Í+Æ+É[Ë]+Ì}(_++);${Õ} Ø"`)()))
console.log(f())
```
[Answer]
# [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 171 bytes
Includes +3 for `-A`
```
(((((()()()){}){}){}){})(((()()())){}{}){({}[()]<(({})())>)}{}(({})(()()()()){})(((((()()()){}){}){}())<{({}[()]<(({})())>)}{}(({})(()()()){}())>){({}[()]<(({})())>)}{}
```
[Try it online!](https://tio.run/nexus/brain-flak#@q8BBpogqFldi0AIUcCAPJCQRnVttIZmrI2GBkhWU9NOEygM4UAUQgzAYhyISVA3RB0puv///6/rCAA "Brain-Flak – TIO Nexus")
```
(((((()()()){}){}){}){}) # push 48
(((()()())){}{}) # push 9
{({}[()]< # for 9..0
(({})()) # pop a, push a, push a+1
>)}{} # end for
(({})(()()()()){}) # pop a, push a, push a + 8
(((((()()()){}){}){}())< # push 26 and save a 26 for later
{({}[()]< # for 26..0
(({})()) # pop a, push a, push a+1
>)}{} # end for
(({})(()()()){}()) # pop a, push a, push a + 7
>) # push that 26 that we held
{({}[()]< # for 26..0
(({})()) # pop a, push a, push a+1
>)}{} # end for
```
There is probably a way to do this without having to repeat the add 1 "function".
[Answer]
# J, 171 bytes
```
(+:>.+:^^*_){.".(':',~(+:+:>.^*_){(*:>.^*_)!:(+:<.^+:*_)''),',',(":(>:*:+:+:+:*_),(<.^<:^<:^*_),<:*:<.^+:*_),'+/',('.',~(+:<.+:^*_){(*:>.^*_)!:(+:<.^+:*_)''),":+:<.*:>:^*_
```
Ow... my brain hurts... [Try it online!](https://tio.run/nexus/j#fU05CsQwDHxL3Ei2jNIPJk9xihDYbh@wsF93RjnaMCo0FzP27fNVw@KG3suaf55cBVL/VEM/RS33N4Fy824gEclVCE3QBQV2gkZVRhrigjV6T6eKzWyIXwstdt8XEoLTjuAYBw "J – TIO Nexus")
Here's so you can see all of it one line (it won't run, though, with line breaks.)
```
(+:>.+:^^*_){.".(':',~(+:+:>.^*_){(*:>.^*_)!:(+:<.^+:*_)''),',',(":(>:*:+:+:+:*_),(<.^<:^<:^*
_),<:*:<.^+:*_),'+/',('.',~(+:<.+:^*_){(*:>.^*_)!:(+:<.^+:*_)''),":+:<.*:>:^*_
```
Only guaranteed to work with J version `j805/j64/linux/release/commercial/www.jsoftware.com/2016-12-11T08:02:52`, in that order. (Only the first 12 characters matter.)
## Explanation
Most of the program is devoted to constant generation. With those constants replaced with their values, the program looks like this:
```
(62){.".(':',~(12){(9)!:(14)''),',',(":(65),(97),48),'+/',('.',~(10){(9)!:(14)''),":26
```
With some parentheses removed, and some numbers made nicer:
```
62{.".(':',~12{9!:14''),',',(":65 97 48),'+/',('.',~10{9!:14''),":26
```
This is composed of a bunch of `,` and `,~`s, which append and prepend arguments. Here are the separate values:
1. `":26`
2. `('.',~10{9!:14'')`
3. `'+/'`
4. `(":65 97 48)`
5. `','`
6. `(':',~12{9!:14'')`
`1` is `26` as a string.
`9!:14''` generates the following string on TIO:
```
j805/j64/linux/release/commercial/www.jsoftware.com/2016-12-11T08:02:52
```
with `2`, we obtain the `10`th character (`i` from `linux`), and add a `.` to the end of it, yielding `i.`.
`3` and `5` are self-explanatory.
`4` is the list of numbers `65 97 48` as a string.
`6` is similar to `2`, except it's the `12`th character (`u` from `linux`) and adds a `:` to the end, yielding `u:`.
This, all together, yields `u:,65 97 48+/i.26`. `".` evaluates this, giving us:
```
ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789:;<=>?@ABCDEFGHI
```
(Note: `+/` is tabulated addition.)
Then, with `62{.`, we take the first `62` characters from this, giving us `ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789`.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~18~~ ~~15~~ 11 bytes
*-4 thanks to Adnan, because if the input size is 1, 05AB1E will use 0 for b on first command.*
```
•£•Ýç©á®þ«˜
```
[Try it online!](https://tio.run/nexus/05ab1e#@6@uf7g94VHDokOLgcTRHYeXH1p5eOGhdYf3HVp9es7//wA "05AB1E – TIO Nexus")
```
•£•Ÿ # Push [0..122] using implicit 0 and the base-214 of `£`.
ç # Convert to ASCII chars.
© # Store full array in register.
√° # Push the same array with ONLY letters.
® # Push contents of register (char)[0..122].
þ # Push only the digits.
¬´Àú # Concat to list, flatten it.
```
I tried so many different approaches, but the key points here that made it hard:
```
- Basic commands will not work, only extended and a select few of the basics.
- Extended commands are pretty complex.
- Eval (.V) will not work.
- To push numbers you can do a base 214 compression.
- ALL sequence pushes (E.G. žK) won't work.
- ALL number pushes won't work, except for compression and the -1 an empty register pushes.
```
[Answer]
# Brainfuck, 55 bytes
```
+++[[<+>->++<]>]<<[-<->]<<<<++[->>+.>+.<<<]<--[->>.+<<]
```
Output:
```
aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ0123456789
```
[Try it online!](https://tio.run/nexus/brainfuck#FYmBCQAwCMMOKt0FoY@I/5/hFApJ6EiqQnEkOg1lfIS9nOjtthr7@ml95gM "brainfuck – TIO Nexus")
---
Initializes the tape to *3·2n*, and works from there.
```
+++[[<+>->++<]>] initialize the tape
| 0 | 3 | 6 | 12 | 24 | 48 | 96 | 192 | 128 | 0 | 0 |
^
<<[-<->] subract 128 from 192
| 0 | 3 | 6 | 12 | 24 | 48 | 96 | 64 | 0 | 0 | 0 |
^
<<<<++ increment 24 twice
| 0 | 3 | 6 | 12 | 26 | 48 | 96 | 64 | 0 | 0 | 0 |
^
[->>+.>+.<<<] output aAbBcC ~ zZ
| 0 | 3 | 6 | 12 | 0 | 48 | 122 | 90 | 0 | 0 | 0 |
^
<--[->>.+<<] decrement 12 twice; output 0 ~ 9
| 0 | 3 | 6 | 0 | 0 | 58 | 122 | 90 | 0 | 0 | 0 |
^
```
[Answer]
# [MAWP](https://esolangs.org/wiki/MAWP), 197 bytes
Here's a funny solution.
```
__________________________________________________________________________________________________________________________;;;;;;;;;;;;;;;;;;;;;;;;;;%%%%%%;;;;;;;;;;;;;;;;;;;;;;;;;;%%%%%%%;;;;;;;;;;
```
MAWP almost exclusively uses alphanumeric characters to print values, so instead we spam the `_`(stack length) operator to generate ASCII values till 122.
The rest is printing the required characters and removing the unnecessary ASCII values. The whole thing is printed in reverse to conserve bytes.
[Try it!](https://8dion8.github.io/MAWP/?code=__________________________________________________________________________________________________________________________%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%25%25%25%25%25%25%3Cspan%20style%3D%22font-size%3A%2021.6px%3B%22%3E%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%25%25%25%25%25%25%25%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3C%2Fspan%3E&input=)
[Answer]
# [Python 3](https://docs.python.org/3/), 2188 bytes
```
_=ùì∏ùìªùì≠('/')
ùìπùìªùì≤ùì∑ùìΩ(ùì¨ùì±ùìª(ùì∏ùìªùì≠('ê')-_)+ùì¨ùì±ùìª(ùì∏ùìªùì≠('‘')-_)+ùì¨ùì±ùìª(ùì∏ùìªùì≠('’')-_)+ùì¨ùì±ùìª(ùì∏ùìªùì≠('“')-_)+ùì¨ùì±ùìª(ùì∏ùìªùì≠('”')-_)+ùì¨ùì±ùìª(ùì∏ùìªùì≠('•')-_)+ùì¨ùì±ùìª(ùì∏ùìªùì≠('–')-_)+ùì¨ùì±ùìª(ùì∏ùìªùì≠('—')-_)+ùì¨ùì±ùìª(ùì∏ùìªùì≠(':')+_)+ùì¨ùì±ùìª(ùì∏ùìªùì≠(';')+_)+ùì¨ùì±ùìª(ùì∏ùìªùì≠('<')+_)+ùì¨ùì±ùìª(ùì∏ùìªùì≠('=')+_)+ùì¨ùì±ùìª(ùì∏ùìªùì≠('>')+_)+ùì¨ùì±ùìª(ùì∏ùìªùì≠('?')+_)+ùì¨ùì±ùìª(ùì∏ùìªùì≠('@')+_)+ùì¨ùì±ùìª(ùì∏ùìªùì≠('Ÿ')-_)+ùì¨ùì±ùìª(ùì∏ùìªùì≠(' ')-_)+ùì¨ùì±ùìª(ùì∏ùìªùì≠('¬°')-_)+ùì¨ùì±ùìª(ùì∏ùìªùì≠('¬¢')-_)+ùì¨ùì±ùìª(ùì∏ùìªùì≠('¬£')-_)+ùì¨ùì±ùìª(ùì∏ùìªùì≠('¬§')-_)+ùì¨ùì±ùìª(ùì∏ùìªùì≠('¬•')-_)+ùì¨ùì±ùìª(ùì∏ùìªùì≠('¬¶')-_)+ùì¨ùì±ùìª(ùì∏ùìªùì≠('¬ß')-_)+ùì¨ùì±ùìª(ùì∏ùìªùì≠('¬®')-_)+ùì¨ùì±ùìª(ùì∏ùìªùì≠('¬©')-_)+ùì¨ùì±ùìª(ùì∏ùìªùì≠('')+_)+ùì¨ùì±ùìª(ùì∏ùìªùì≠('')+_)+ùì¨ùì±ùìª(ùì∏ùìªùì≠('')+_)+ùì¨ùì±ùìª(ùì∏ùìªùì≠('')+_)+ùì¨ùì±ùìª(ùì∏ùìªùì≠('')+_)+ùì¨ùì±ùìª(ùì∏ùìªùì≠('')+_)+ùì¨ùì±ùìª(ùì∏ùìªùì≠('')+_)+ùì¨ùì±ùìª(ùì∏ùìªùì≠('')+_)+ùì¨ùì±ùìª(ùì∏ùìªùì≠('')+_)+ùì¨ùì±ùìª(ùì∏ùìªùì≠('')+_)+ùì¨ùì±ùìª(ùì∏ùìªùì≠('
')+_)+ùì¨ùì±ùìª(ùì∏ùìªùì≠('
')+_)+ùì¨ùì±ùìª(ùì∏ùìªùì≠('
')+_)+ùì¨ùì±ùìª(ùì∏ùìªùì≠('')+_)+ùì¨ùì±ùìª(ùì∏ùìªùì≠(' ')+_)+ùì¨ùì±ùìª(ùì∏ùìªùì≠('!')+_)+ùì¨ùì±ùìª(ùì∏ùìªùì≠('"')+_)+ùì¨ùì±ùìª(ùì∏ùìªùì≠('#')+_)+ùì¨ùì±ùìª(ùì∏ùìªùì≠('$')+_)+ùì¨ùì±ùìª(ùì∏ùìªùì≠('%')+_)+ùì¨ùì±ùìª(ùì∏ùìªùì≠('&')+_)+ùì¨ùì±ùìª(ùì∏ùìªùì≠("'")+_)+ùì¨ùì±ùìª(ùì∏ùìªùì≠('(')+_)+ùì¨ùì±ùìª(ùì∏ùìªùì≠(')')+_)+ùì¨ùì±ùìª(ùì∏ùìªùì≠('*')+_)+ùì¨ùì±ùìª(ùì∏ùìªùì≠('+')+_)+ùì¨ùì±ùìª(ùì∏ùìªùì≠('')+_)+ùì¨ùì±ùìª(ùì∏ùìªùì≠('')+_)+ùì¨ùì±ùìª(ùì∏ùìªùì≠('')+_)+ùì¨ùì±ùìª(ùì∏ùìªùì≠('')+_)+ùì¨ùì±ùìª(ùì∏ùìªùì≠('')+_)+ùì¨ùì±ùìª(ùì∏ùìªùì≠('')+_)+ùì¨ùì±ùìª(ùì∏ùìªùì≠('')+_)+ùì¨ùì±ùìª(ùì∏ùìªùì≠(' ')+_)+ùì¨ùì±ùìª(ùì∏ùìªùì≠('''
''')+_)+ùì¨ùì±ùìª(ùì∏ùìªùì≠('')+_),ùìÆùì∑ùì≠='')
```
The code contains some unprintable characters that may not display properly. See the TIO link for the actual code.
[Try it online!](https://tio.run/##hda7TgJBGIbhiHKQUg4ioOiKzg6LoaADFrkTWiqloPEuQEAqAggKJGCiDRBjwxVxB8uvobHhLb7JHJ5/JplppvpUqzw@ZB2nbG@6zaXkWzI3VUZpv/RWu5kvyULyY0ozk3z@Lpj/a9Z1pe/K2tpHGkyemTSZtJi0mbww6SDJKW3tF3kUBRQ2iiKKexQlFOse31mfyYDJK5MhkxGTNybvTMZMJkymSE7wiQIogihCKMIoTlFEUJyhiKKIoYijOEdxgSKB4hLFFQoDxTWKJIobFLckDGXQHiaeolGkUFgoXCgOURyhcKPwoPCi8KE4RqGUX0Lq4E@kZfCx@1/MbalynC0 "Python 3 – Try It Online")
There doesn't seem to be a way to do any sort of looping without access to keywords, so I had to make this monster.
[Here](https://codegolf.stackexchange.com/a/209742/98955) is an explanation of why this works.
[Answer]
# [Perl 6](http://perl6.org/), 43 bytes
```
{|('`'^..^'{'),|('@'^..^'['),|('/'^..^':')}
```
A lambda that returns a list of characters.
Explanation:
```
'`' # The character before "a" (in Unicode order)
'{' # The character after "z"
^..^ # Endpoint-exclusive range between them
|( ) # Slip the range into the outer list
|('@'^..^'[') # Same thing for "A" to "Z"
|('/'^..^':')} # Same thing for "0" to "9"
```
Depends on a bugfix to the Rakudo Perl 6 interpreter which was only committed to the git repo today, and isn't part of an official Rakudo release yet. In fact, I encountered the bug while answering this challenge, and managed to get fixed with the help of one of the Perl 6 core devs. The rules of this site, as I understand them, did't allow answers to compete in such a situation, so I marked it as noncompeting but now it's fine.
[Answer]
# PHP 7.0+, 110 bytes
God bless bitwise strings!
```
<?=($__='`@`@'^'*/).')(($_='->.<:'^'__@[_')('>'^_,'%'^_)),$__($_('|'^'=','|'^'&')),$__($_(':'^"\n",';'^']'^_));
```
Replace the `\n` with a real \*NIX-style newline.
It is present in the code to avoid problems with newlines, but isn't counted in the score.
This throws a bunch of warnings, but those could be supressed by appending an `@` in front of every stray `_`.
---
**Warning free**, 113 bytes
```
<?=($__='`@`@'^'*/).')(($_='->.<:'^'__@[_')('>'^@_,'%'^@_)),$__($_('|'^'=','|'^'&')),$__($_(':'^"\n",';'^']'^@_));
```
[Answer]
# 65c02 machine language + Apple ][ ROM, 25 bytes
```
A9 E0 20 0F 80 A9 C0 20 0F 80 A2 0A A9 AF 2C A2 1A 1A 20 ED FD CA D0 F9 60
```
Prints `abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789`.
Should start at `$8000`.
## Disassembly
```
8000- A9 E1 LDA #$E0
8002- 20 0F 80 JSR $800F
8005- A9 C1 LDA #$C0
8007- 20 0F 80 JSR $800F
800A- A2 0A LDX #$0A
800C- A9 B0 LDA #$AF
800E- 2C HEX 2C ; SKIPS NEXT 2 BYTES
800F- A2 1A LDX #$1A
8011 1A INC
8012- 20 ED FD JSR $FDED
8015- CA DEX
8016- D0 F9 BNE $8011
8018- 60 RTS
```
[Answer]
# [MarioLANG](https://github.com/tomsmeding/MarioLANG), 255 233 199 bytes
```
+
+
+
+
+
+
+
+
)
><
+"
+
+(
+(
+(
+(
++
+)
)+
++
++
++
+)
++
++
++
++
++
++
++
+)
()
()
-
[!)+)+)-)--)+++((
=#==============
>((+(+ >((+
"======< "====<
![-)).).((((![-)).
#===========#=====
```
[Try it online!](https://tio.run/##bYw7CsNAEEN7nSLeNCPE7AnWvogrV8aQ2JD7w2Y/KdYQScXTDOi9fY7rtZ17zsLdxJKgUNmGlEpQDfSr0r8Q1uJYJ6rY6U5JZpif801YzGR6NFVG6I9UD40TptXJyGhFnTHOdM75Cw "MarioLANG – Try It Online")
The more time Mario spends in the air, the less floor you have to draw and the less characters you use for the solution...
[Answer]
# [C (clang)](http://clang.llvm.org/), 116 bytes
"Arbitrary order" indeed.
The function `_` takes a pointer to target string as an argument. Since that pointer is to int, it is assumed that `sizeof(int) == 4`.
In the TiO link the result is printed as-is, as well as sorted, for easier ocular inspection.
```
$;*ö;Å(å,ä){(å+=$)<ä?*ö++=å,Å(å,ä):$;}_(*ä){ö=ä;$='&&&&'^'$$$$';Å('?_@`','[{\\|');$+=$;Å('/.-,','?>=<');*--ö&=';:';}
```
[Try it online!](https://tio.run/##ZY9PUsMgFMbX4RRMxQIpqaMzuiil9Q4uW40piS0zKakJdVO79CbxCrkAB0sB7Yx/3gbe7/ve90Amssz0uu8Rj23H7Qexn8y29ODOkUB0atu5E0Yj4flZnSB@TEnsfbYTtuVI4KEr/ISRK@xz8Dy9f8YMLw7L5TumHLm4wK/GCXN8PhNTh@Mksd1QYD7B/NhfKC3LfV7AaWNyVY03M/ALlWr1l9VKrz0DShsoq@2OyEo3Br5VKodxxuDPdkXBAUR1Yfa1hjH5tspNVsOYZhQm/@CKcnD8Ct9mSpMQEDS3enFze/fIQQSilLjWWaPd3jTnO4hem6o2vmXeXhY6SAxes/DUMOA@YF7I4LKB5MG5i5wu9SD4/er@BA "C (clang) – Try It Online")
] |