title: The infinite power tower

text:
# Question
Title: The infinite power tower
# The challenge

Quite simple, given an input `x`, calculate it's infinite power tower!

```
x^x^x^x^x^x...

```

*For you math-lovers out there, this is `x`'s infinite tetration.*

Keep in mind the following:

```
x^x^x^x^x^x... = x^(x^(x^(x^(x...)))) != (((((x)^x)^x)^x)^x...)

```

Surprised we haven't had a "simple" math challenge involving this!\*

# Assumptions

* `x` will **always** converge.
* **Negative and complex** numbers should be able to be handled
* This is , so **lowest bytes** wins!
* Your answers should be correct to at least **5** decimal places

# Examples

```
Input >> Output

1.4 >> 1.8866633062463325
1.414 >> 1.9980364085457847
[Square root of 2] >> 2
-1 >> -1
i >> 0.4382829367270323 + 0.3605924718713857i
1 >> 1
0.5 >> 0.641185744504986
0.333... >> 0.5478086216540975
1 + i >> 0.6410264788204891 + 0.5236284612571633i
-i >> 0.4382829367270323 -0.3605924718713857i
[4th root of 2] >> 1.239627729522762

```

---

*\*(Other than a more complicated challenge here)*

# Answer
> 16 votes
# APL (Dyalog), 4 bytes

```
*⍣≡⍨

```

Try it online!

`*` power

until

stable

selfie

# Answer
> 12 votes
# Pyth,  ~~4~~  3 bytes

crossed out 4 is still regular 4 ;(

```
u^Q

```

Try it online

### How it works

```
u       first repeated value under repeated application of G ↦
 ^QG        input ** G
    Q   starting at input

```

# Answer
> 7 votes
# Haskell, ~~100~~ 63 bytes

For inputs that don't converge (eg. `-2`) this won't terminate:

```
import Data.Complex
f x=until(\a->magnitude(a-x**a)<1e-6)(x**)x

```

Thanks a lot @ØrjanJohansen for teaching me about `until` and saving me `37` bytes!

Try it online!

# Answer
> 7 votes
# Python 3, ~~40 39~~ 35 bytes

* Thanks @Ørjan Johansen for a byte: `d>99` instead of `d==99`: 1 more iteration for a lesser byte-count
* Thanks @Uriel for 4 bytes: wise utilization of the fact that `x**True` evaluates to x in `x**(d>99or g(x,d+1))`. The expression in the term evaluates to True for depth greater than 99 and thus returns the passed value.

Recursive lambda with a max-depth 100 i.e. for a depth 100 returns the same value. Actually is convergency-agnostic, so expect the unexpected for numbers with non-converging values for the function.

```
g=lambda x,d=0:x**(d>99or g(x,d+1))

```

Try it online!

# Answer
> 6 votes
# Python 3, ~~37~~ ~~30~~ 27 bytes

-7 bytes from @FelipeNardiBatista.
-3 bytes from from @xnor

I don't remember much of Python anymore, but I managed to port my Ruby answer and beat the other Python 3 answer :D

```
lambda x:eval('x**'*99+'1')

```

Try it online!

# Answer
> 4 votes
# Mathematica, 12 bytes

```
#//.x_:>#^x&

```

Takes a floating‐point number as input.

# Answer
> 4 votes
# , 5 bytes

```
^^:_~

```

Try it online!

## Explanation

First, I'll show what command is being executed after parsing the `~` at the end, and the walk-through will be for the new verb.

```
(^^:_~) x = ((x&^)^:_) x

((x&^)^:_) x  |  Input: x
      ^:_     |  Execute starting with y = x until the result converges
  x&^         |    Compute y = x^y

```

# Answer
> 4 votes
# C# (.NET Core), 79 78 bytes

```
x=>{var a=x;for(int i=0;i++<999;)a=System.Numerics.Complex.Pow(x,a);return a;}

```

Try it online!

I chose to iterate until `i`=999 because if I iterated until 99 some examples did not reach the required precision. Example:

```
Input:                      (0, 1)
Expected output:            (0.4382829367270323, 0.3605924718713857)
Output after 99 iterations: (0.438288569331222,  0.360588154553794)
Output after 999 iter.:     (0.438282936727032,  0.360592471871385)

```

As you can see, after 99 iterations the imaginary part failed in the 5th decimal place.

```
Input:                      (1, 1)
Expected output:            (0.6410264788204891, 0.5236284612571633)
Output after 99 iterations: (0.64102647882049,   0.523628461257164)
Output after 999 iter.:     (0.641026478820489,  0.523628461257163)

```

In this case after 99 iterations we get the expected precision. In fact, I could iterate until `i`=1e9 with the same byte count, but that would make the code considerably slower

* 1 byte saved thanks to an anonymous user.

# Answer
> 3 votes
# Jelly, 5 bytes

```
³*$ÐL

```

Try it online!

# Answer
> 2 votes
# Ruby, ~~21~~ 20 bytes

```
->n{eval'n**'*99+?1}

```

~~**Disclaimer**: It seems that Ruby returns some weird values when raising a complex number to a power. I assume it's out of scope for this challenge to fix Ruby's entire math module, but otherwise the results of this function should be correct.~~ **Edit**: Applied the latest changes from my Python 3 answer and suddenly it somehow gives the same, expected results :)

Try it online!

# Answer
> 2 votes
# TI-BASIC, 16 bytes

The input and output are stored in `Ans`.

```
Ans→X
While Ans≠X^Ans
X^Ans
End

```

# Answer
> 1 votes
# , ~~36~~ 33 bytes

-*3 bytes thanks to Jarko Dubbeldam*

```
Reduce(`^`,rep(scan(,1i),999),,T)

```

Reads from stdin. `Reduce`s from the right to get the exponents applied in the correct order.

Try it (function)

Try it (stdin)

# Answer
> 1 votes
# Javascript, 33 bytes

```
f=(x,y=x)=>(x**y===y)?y:f(x,x**y)

```

# Answer
> 1 votes
# MATL, ~~20~~ 10 bytes

cut down to half thanks to @LuisMendo

```
t^`Gw^t5M-

```

Try it online!

This is my first and my first time using MATL so i'm sure it could be easily outgolfed.

# Answer
> 1 votes
# Vyxal `r`, 4 bytes

```
‡?eẊ

```

Try it Online!

# Answer
> 1 votes
# PowerShell Core, ~~165~~ 140 bytes

```
param($a)$u=1;for($r=$a;$u-join'+'|iex){$r=[Numerics.Complex]::Pow($a,($p=$r))
$u=($p.Real,($p|% I*),-$r.Real,-($r|% I*))|% *g '.0000000'}$r

```

Try it online!

*-7 bytes* thanks to mazzy!

55 bytes without complex numbers

# Answer
> 0 votes
# Perl 6, 17 bytes

```
{[R**] $_ xx 999}

```

Try it online!

`R**` is the reverse-exponentiation operator; `x R** y` is equal to `y ** x`. `[R**]` reduces a list of 999 copies of the input argument with reverse exponentiation.

---
Tags: code-golf, math
---


title: Arithmetic Sequences

text:
# Question
Title: Arithmetic Sequences
An arithmetic sequence is a sequence of numbers of the form `a`,`a+n`,`a+2n`,`a+3n`, etc. In this case, `a` and `n` will both be either integers or decimals.

Given two inputs, `a`, `n`, and a top number value, return a list of numbers where the last term is **less than or equal to** the top number value.

The input can be formatted in any way, as well as the output.

***The catch to this problem is dealing with floating point arithmetic errors.***
For example, `0.1 + 0.3 * 3` is 1, however this will display `0.99999999999...` if you simply go `0.1 + 0.3 * 3`. We want `1`, not `0.99999999999...`

# Test Cases

`a=2, n=3, top=10: [2, 5, 8]`
`a=3, n=1.5, top=12: [3, 4.5, 6, 7.5, 9, 10.5, 12]`
`a=3.14159, n=2.71828, top=10: [3.14159, 5.85987, 8.57815]`
`a=0.1, n=0.3, top=2: [0.1, 0.4, 0.7, 1, 1.3, 1.6, 1.9]`

Shortest code wins. Good luck!

# Answer
> 5 votes
## APL (22)

```
{⍵≤T:⍵,∇⍵+N⋄⍬}⊃A N T←⎕

```

Reads input from stdin as three whitespace-separated numbers.

This is actually shorter than using the index generator.

# Answer
> 6 votes
## Non-golfed haskell, 32

```
f a n t=takeWhile(<=t)[a,a+n..]

```

I'd love to change takeWhile to take, but integer division can't be done with /, it needs to be done with `div`. If I go with / then I need to do implicit conversion which makes it that much longer.

# Answer
> 5 votes
## J, 34 33 31 characters

```
({.+i.@>:@([:<.1{[%~{:-{.)*1{[)

```

I'm sure there's room for improvement here.

Usage:

```
   ({.+i.@>:@([:<.1{[%~{:-{.)*1{[)2 3 10
2 5 8

```

We can give the verb a name for an extra three characters:

```
   s=.({.+i.@>:@([:<.1{[%~{:-{.)*1{[)
   s 2 3 10
2 5 8

```

Previously:

```
((0-.~]*]<:2{[)(((i.100)*1{[)+{.))

```

Thought I'd have a go at doing this in Golfscript and got as far as `.3$- 2$/1+,{2$*}%{3$+}%` before realising Golfscript doesn't seem to do floats. Bugger.

# Answer
> 4 votes
### bash 12:

```
seq $1 $2 $3

```

Haha - who would have thought that? Silly'o'bash which normally just handles Integer arithmetic (9/10 = 0) can handle floating points that way:

```
./cg-6228-arithmetic-sequences.sh 2 3 10
2
5
8
./cg-6228-arithmetic-sequences.sh 3 1.5 12
3,0
4,5
6,0
7,5
9,0
10,5
12,0

```

Other test-cases omitted for brevity. I have to mention that you can change the locale, if you're irritated by 10,5 which is the continental way to say 10.5. ;)

# Answer
> 3 votes
### Ruby 34

```
s=->a,n,t{p a;s[a+n,n,t]if a+n<=t}

```

*Input:* the three function parameters

*Output:* the sequence numbers are printed, one per line

Ideone link: http://ideone.com/SahPs

# Answer
> 3 votes
## , 26

```
s=:1 :']+u*[:i.@<.@>:u%~-'

```

There's some interesting syntax to use this definition.

```
   10(2 s)1
1 3 5 7 9

```

# Answer
> 3 votes
# Ruby - 28

```
((t-a)/n).times{|i|p(a+i*n)}

```

# Answer
> 3 votes
# Mathematica, 5 bytes

```
Range

```

Arguments are a,top,n in that order. I'm assuming that decimal points at the end are okay.

# Answer
> 2 votes
### Scala 52

```
val x,?,z=BigDecimal(readLine)
x to z by?map println

```

Give inputs `a`,`n` and `top` in the separate line. Each entry of the output will be listed in the separate line.

# Answer
> 2 votes
# Mathematica ~~39~~ 37

```
Table[#+#2 k,{k,0,Quotient[#3-#,#2]}]&

```

**Usage**

```
Table[#1 + #2 k, {k, 0, Quotient[#3 - #1, #2]}] &[2, 3, 10]
Table[#1 + #2 k, {k, 0, Quotient[#3 - #1, #2]}] &[3, 1.5, 12]
Table[#1 + #2 k, {k, 0, Quotient[#3 - #1, #2]}] &[3.14159, 2.71828, 10]
Table[#1 + #2 k, {k, 0, Quotient[#3 - #1, #2]}] &[0.1, 0.3, 2]

```

# Answer
> 2 votes
## Swift, 90

Not quite as short as the other ones here but this doesn't use a builtin to compute the sequence, nor does it operate on a standard float type. It declares a function `f(a:n:t:)` that takes the numbers in and prints the sequence to stdout.

```
import Foundation
func f(a:Decimal,n:Decimal,t:Decimal){var x=a
while x<=t{print(x)
x+=n}}

```

Try it Online! (with hardcoded test case)

I learned a few things while doing this that surprised me:

* Swift's range builtin is only iterable for integers, unlike in Python where you can specify the step size.
* Assignment operators in Swift return Void, so I couldn't abbreviate the body of the while loop to `print(x+=n)`. I tried it; it just printed `()` a bunch of times.
* `Decimal` values are not converted to `Double` when printing. If you replace `Decimal` in the declaration with `Double`, it prints `1.0` and `1.9000000000000001` rather than `1` and `1.9`. On the other hand, this proves that it is avoiding floating-point rounding errors, as the question specified.
* There is no version of the `<=` operator that lets you compare a `Decimal` to any other number type, so I can't make the function declaration shorter by changing `t`'s type.

You could shave off two bytes by allowing the input to be mutated (changing the function signature to `f(a:inout Decimal,n:Decimal,t:Decimal)`, as this eliminates the need for the variable `x`.

# Answer
> 1 votes
# JavaScript 70

```
s=prompt().split(",");for(n=0;(p=s[0]-0+n*s[1]-0)<=s[2]-0;n++)alert(p)

```

input in the form `a,n,top`

# Answer
> 1 votes
## Perl, 37 chars

```
for(($_,$n,$t)=<>;$_<=$t;$_+=$n){say}

```

Input a, n, and top, each number on a separate line. The list is output with newlines separating the values. Run with `perl -M5.010` (or `perl -E`).

# Answer
> 1 votes
# Python (245)

Input should be given with a space in between, e.x. `0.1 0.3 0.5`

```
a=raw_input().split()
I,F=int,float
D='.'
b=[[I(i.replace(D,'')),len(i.split(D)[1:])]for i in a[:2]]
a=map(F,a)
c=max(b,key=lambda x:x[1])[1]
for i in b:i[0]*=10**(c-i[1])
print [(b[0][0]+i*b[1][0])/10.0**c for i in range(I((a[2]-a[0])/a[1]+1))]

```

It avoids floating point errors by turning each floating point into a list containing two values: the number without the decimal point, and the number of significant digits. `example: 1.34 -> [134, 2]`

# Answer
> 0 votes
## Python, 37

```
a,n,t=input()
while a<=t:print a;a+=n

```

Grabs input in the form `a, n, top`, and prints out the numbers on separate lines.

# Answer
> 0 votes
### C# ~~120~~ 74

```
void A(float a,float n,int t){Console.Write(a+" ");a+=n;if(a<=t)A(a,n,t);}

```

**Edit:** New version - recursive and a lot shorter than using LINQ :)

*Input:* the three parameters of method `A`

*Output:* the numbers in the sequence are printed to console, separated by spaces.

Test link: http://ideone.com/o7g6k

> *Previous version (using LINQ):*

```
IEnumerable<float>A(float a,float n,int t){return Enumerable.Range(0,int.MaxValue).Select(i=>a+n*i).TakeWhile(s=>s<=t);}

```

# Answer
> 0 votes
# PHP 83

```
<?function a($x,$i,$t){while($r<$t){$r=$x+$i*$g++;$s.=($r<$t?$r." ":"");}echo$s;}?>

```

Wish I could remove "function" but there's no shorter declaration for that in PHP. Handy that PHP uses untyped variables!

Usage: a(2,3,10); Returns: 2 5 8

# Answer
> 0 votes
## PHP, 53

```
<?for(list(,$a,$n,$x)=$argv;$a<=$x;$a+=$n)echo"$a ";

```

# Answer
> 0 votes
# R, 3 bytes

```
seq

```

Built in function with arguments from (`a`), to `(top`) and by (`n`)

usage `seq(a,top,n)` eg

```
seq(2,10,3)

```

output numeric vector

```
2 5 8

```

# Answer
> 0 votes
# TI-Basic, 20

```
Prompt A,N,T:For(I,A,T,N:Disp I:End

```

# Answer
> 0 votes
# Husk, 7 bytes

```
↑≤⁰¡+⁴²

```

Try it online!

---
Tags: code-golf, math, sequence, arithmetic
---


title: Overcoming cluster size

text:
# Question
Title: Overcoming cluster size
Fed up with the reliability of flash storage, you decided to store all your programs on one of those good old 1,440 KiB floppies. However, after copying not even 3,000 programs, the disk was full. How's that even possible? Skilled in the art of code golf as you are, most of your programs aren't even 100 bytes long, so there should be plenty of room left...

After asking about it on Super User, you discover that you have been wronged by the file system's cluster size, an evil plot of the designers of FAT12 that leaves a significant portion of your floppy unused and forces you to buy more than you actually need.

Buy more floppies? Never! Cluster size will be less of an issue if we simply save multiple programs in one file, which is possible because different compilers/interpreters will behave differently for the same source code.

### Task

Write a polyglot that fits in a single cluster (512 bytes or less) and solves as many of the following tasks as possible.

1. Read all input and print it.
2. Print **Hello, World!**.
3. Read a line/argument (**name**) as input and print **Happy Birthday, \[name\]!**.
4. Read all input and print **I love tabs!** if it contains one or more tabulators (0x09) and **I hate spaces!** if it doesn't.
5. Read two lines/arguments and print a truthy value if the second is a substring of the first and a falsy value if not.
6. Read a line/argument and print a truthy value if its characters are in strictly ascending order and a falsy value if not.
7. Read a line/argument and a character and print the indexes of all occurrences of that character.
8. Read a line/argument and print any of the characters with the highest number of occurrences.

9. Read two integers between **0** and **255** and print their sum.
10. Read a single integer between **0** and **255** and print the quotient and residue of its division by **7**.
11. Read a single integer between **1** and **255** and print a truthy value if it is a composite number (neither 1 nor prime) and a falsy value if not.
12. Read a single integer between **1** and **255** and print a truthy value if it is a power of 2 and a falsy value if not.
13. Read two integers between **0** and **255** and print the larger one.
14. Read a decimal integer between **0** and **255** print its hexadecimal representation.
15. Read a single integer between **0** and **255** and print its Hamming weight (number of 1-bits).
16. Read a single integer **n** between **1** and **13** and print the **Fn**, the **n**th Fibonacci number.

For example, for the input `13`, print `233`.

17. Read a line/argument of input and frame it.

For example, for the input `Programming Puzzles & Code Golf`, print this:

```
+---------------------------------+
| Programming Puzzles & Code Golf |
+---------------------------------+

```
18. Read a rectangular block of characters and rotate it a quarter turn clockwise.

For example, for the input

```
 tye
 xll
 epb
 tma
  id
  sa
 s e
 i r
 hsn
 Tiu

```

print this:

```
 This  text
 is  simply
 unreadable

```
19. Read an integer between **1** and **40** and print a diamond of that side length.

For example, for the input `3`, print this:

```
   /\
  /  \
 /    \
 \    /
  \  /
   \/

```
20. Print this:

```
 ....@@@@....@@@@....@@@@....@@@@
 ....@@@@....@@@@....@@@@....@@@@
 ....@@@@....@@@@....@@@@....@@@@
 @@@@....@@@@....@@@@....@@@@....
 @@@@....@@@@....@@@@....@@@@....
 @@@@....@@@@....@@@@....@@@@....
 ....@@@@....@@@@....@@@@....@@@@
 ....@@@@....@@@@....@@@@....@@@@
 ....@@@@....@@@@....@@@@....@@@@
 @@@@....@@@@....@@@@....@@@@....
 @@@@....@@@@....@@@@....@@@@....
 @@@@....@@@@....@@@@....@@@@....
 ....@@@@....@@@@....@@@@....@@@@
 ....@@@@....@@@@....@@@@....@@@@
 ....@@@@....@@@@....@@@@....@@@@
 @@@@....@@@@....@@@@....@@@@....
 @@@@....@@@@....@@@@....@@@@....
 @@@@....@@@@....@@@@....@@@@....
 ....@@@@....@@@@....@@@@....@@@@
 ....@@@@....@@@@....@@@@....@@@@
 ....@@@@....@@@@....@@@@....@@@@
 @@@@....@@@@....@@@@....@@@@....
 @@@@....@@@@....@@@@....@@@@....
 @@@@....@@@@....@@@@....@@@@....

```

### Scoring

The answer that manages to incorporate the highest number of programs in a single file that fits in a single 512-byte cluster wins. Ties are broken by byte count (lower is better).

### Additional rules

* For each task you claim for your score, the same file (byte per byte) must constitute a full program – in a language of your choice – that solves this particular task.
* Each task has to be solved in a different language.

Languages count as different if they are not different versions of the same language. For example, there's only one JavaScript, one Python and one TI-BASIC, but C, C++, Octave and MATLAB are four different languages.
* The selected language for each task has to satisfy our usual definition of programming language.

In addition, the language must have been published and implemented before September 9, 2015.
* Your compiler/interpreter may not require any non-standard flags to produce the expected behavior.

Exceptions to this rule include flags required to specify a particular language, to read the program from a (single) file or to suppress a banner.
* The input for each task will consist of printable ASCII characters (0x20 to 0x7E), tabs (0x09), and linefeeds (0x0A), and it will not exceed **255** bytes in length.
* All *integers* can be read in decimal or unary, unless stated otherwise in the task.
* Behavior for invalid input is undefined.
* You may read input from STDIN (or its closest alternative) or as command-line arguments.

If a task requires reading two pieces of input, you can read them – in any order – separated by a one-byte delimiter of your choice, as separate command-line arguments or one from STDIN and the other as command-line argument.

If one of the input pieces is a line, the only possible delimiter is a linefeed.
* Print the output to STDOUT (or closest alternative). All output to STDERR will be ignored.
* For each task, standard rules apply.

In particular, this includes the http://meta.codegolf.stackexchange.com/q/1061, with the exception of *hard-coding the output*, which is explicitly allowed for this challenge.

# Answer
> 20 votes
# 12 languages, 418 bytes

```
"1\"# &&+.@\""" "" "
#=
''''
<<s
""'("']0=~2base{+}*}
 ?
 :_7/!\_7%!@
"
R"Happy Birthday, "[?S"!"*"
>0[0>i:0(?v:{)?v0n;\!/
$'main';n1< .95<
 \@-[I love tabs!]o#
  \ >qi---@
( @-[ ]e<''';print hex(
input())#-[I hate spaces!]o#"]];ri:X{_~X+S*'/@S*_'\4$N}%_sW%1>"))?(!?)
'''=#print(([1 1;1 0]^int(readline()))[1,2])
#=
Tr is here.
>Tr, Hello, World!
>X Tr
s
l=gets
a='+-'+?-*~/$/+'-+'
puts a+'
| %s |
'%l+a#=#.91<0#'''#";

```

This is a fun challenge. It's getting hard to fit more languages in, but with this many bytes left I could probably do about one more.

Makes gratuitous use of 2D languages. Note that the char on between the `[ ]` on the `@-[ ]e<` line is a tab. Also, this requires `\n` line endings for TRANSCRIPT to work.

## Prelude (Task 1 / Cat)

```
(
      )?(!?)

```

`?(!?)` is just a direct translation of `,[.,]` in BF. Prelude `()` loops act like BF `[]` loops, so everything from the `(` in the leftmost column to the `)` before the core program is unexecuted.

Prelude's syntax rules mean that parentheses need to be matched (reading left-to-right column-wise), and there can only be one parenthesis per column. Other than that, it's a pretty easy language to fit in.

Make sure `NUMERIC_OUTPUT` is set to `False` if you're using the Python interpreter.

## TRANSCRIPT (Task 2 / Hello world)

```
Tr is here.
>Tr, Hello, World!
>X Tr

```

TRANSCRIPT is a thematic esolang based on interactive fiction. Lines not recognised by TRANSCRIPT are ignored, making it easy to fit in.

`Tr is here.` declares a `Tr` string variable, and the second line sets the contents of the variable to `Hello, World!`. `X Tr` (`X` for examine) then outputs the string.

Although TRANSCRIPT is very easy to fit in, it's a pretty verbose language, so I made it take the easiest challenge.

## Fission (Task 3 / Birthday message)

```
R"Happy Birthday, "[?S"!"*
                   \!/

```

which prints the first part, cats the input with a small 2D loop, then outputs the trailing exclamation mark. The `R` signifies that an atom starts here moving rightward, which is useful because this program can be moved around anywhere.

## Rail (Task 4 / Tabs)

```
$'main'
 \@-[I love tabs!]o#
  \ >qi---@
  @-[ ]e<
         -[I hate spaces!]o#

```

Like Fission, Rail is a 2D language which has the advantage of being able to be moved around anywhere. Execution starts from the `$` of the `main` function, heading southeast.

First we head down the `\`s, turn left at `-`, hitting `[<tab>]` which pushes a tab. `e<` then branches based on EOF – if EOF, we head down and print `"I hate spaces!"` before halting, else we head up. If we headed upwards, we read the next char and compare it with the tab, once again branching – if tab, head up and print `"I love tabs!"` before halting, else head down and continue the input loop.

This program is pretty expensive, but since TRANSCRIPT took Hello World it was hard to pick and appropriate task for Rail.

## \>\<\> (Task 6 / Ascending input)

```
"1\"#      \""" "" "

>0[0>i:0(?v:{)?v0n;
       ;n1< .95<

        .91<

```

Prints `1` if strictly ascending, `0` otherwise.

\>\<\> is another 2D language, and execution starts from the top left. `"..."` is string mode, pushing the inner chars one at a time. After the first string we hit `#`, which reflects the IP leftward, pushing more strings and wrapping around (\>\<\> is toroidal) before hitting `\`, a mirror which reflects us upwards.

At the bottom of the program is `.91<`, which teleports us to `(9, 1)`, where the core program is. After this `0[` removes all the junk from the strings, `0` pushes a zero to represent the last char read, and after this it's just reading chars one at a time, making sure we're still ascending.

It's probably better to move the core program down instead of teleporting, but I'll deal with that later if necessary.

## Befunge (Task 9 / Addition)

```
"1\"# &&+.@

```

Tested with the interpreter found here. This is a pretty straightforward program, with the start pushing a useless string and `#` jumping over the space. After that it's just the core program `&&+.@`.

## Labyrinth (Task 10 / Divmod by 7)

```
"1
 =
 '
 <
""'("']
 ?
 :_7/!\_7%!@

```

Conveniently, `'` and `"` are NOPs in Labyrinth which act like a walkable path in the maze. I'll skip the messy navigation, but basically there's a lot of turning and wandering around going on before we hit the `?`, which is the start of the core program.

The program is not quite flush left to account for Prelude (e.g. `?` is read input in Prelude).

## Python 2 (Task 14 / Hexadecimal)

```
"1\"# &&+.@\""" "" "
#=
''''
xxx
xxx''';print hex(
input())#xxx
'''
xxx
xxx'''#";

```

The `xxx`s represent irrelevant portions commented out by multiline strings or comments. In between is `print hex(input())`, the core progam. This outputs with a leading `0x`, but I'm assuming that's okay (if not, then it's an easy fix anyway).

The first line is a string `"1\"# &&+.@\""` followed by two `" "`s. These three strings are concatenated by the parser, and left unused (this first line works similarly for Ruby and Julia later).

## GolfScript (Task 15 / Hamming weight)

```
"1\"# &&+.@\""" "" "
#=
''''
<<s
""'("']0=~2base{+}*}

```

The first line pushes three strings, and the second line is a comment. `''''` pushes two more strings, then `<<` does two comparisons (`s` is ignored). Finally, `""'("'` pushes another two strings.

All of this is junk is then removed by wrapping it in an array and getting the first element (`]0=`), which is the input initially on the stack. We then evaluate the input with `~`, turn into binary with `2base` then sum the bits with `{+}*`. The next `}` is unmatched, and super-comments the rest of the program.

## Julia (Task 16, Fibonacci)

```
"1\"# &&+.@\""" "" "
#=
xxx
xxx=#print(([1 1;1 0]^int(readline()))[1,2])
#=
xxx
xxx=#.91<0#xxx

```

`#=` starts a multiline comment and `=#` ends a multiline comment. The core program uses matrix exponentiation to calculate Fibonacci numbers (taken from Rosetta).

## Ruby (Task 17 / ASCII frame)

```
"1\"# &&+.@\""" "" "
#=
''''
<<s
xxx
s
l=gets
a='+-'+?-*~/$/+'-+'
puts a+'
| %s |
'%l+a#xxx

```

This program assumes that the input does not end with a trailing newline.

We have a useless string, a comment, another useless string then a heredoc which comments out most of the program. After that is the core program, followed by a single line `#` comment.

## CJam (Task 19 / Diamond)

```
"1\"# &&+.@\""" "" "
#=
''''
<<s
""'("xxx
"
R"xxx"[?S"!"*"
xxx
xxx"ri:X{_~X+S*'/@S*_'\4$N}%_sW%1>"xxx
xxx
xxx";

```

The two space strings at the end of the first line are to satisfy CJam, since `#=` are two binary operators. I won't go into too much detail with this one, but basically it's a mess, with the core program being the mere

```
ri:X{_~X+S*'/@S*_'\4$N}%_sW%1>

```

in between.

The key differentiator between GolfScript and CJam is that, in CJam, a single quote `'` doesn't start and end strings, but instead pushes the next character to the stack. This means that in CJam

```
'("'

```

pushes a `(` then starts a string with `"` (the first char of which is `'`), whereas the above is just a straight single string in GolfScript.

Try it online. `1>` is used instead of `(` to account for Prelude.

---

Here's **12 languages, 373 bytes**. Some tasks have moved around, TRANSCRIPT has been removed (it made Rail too expensive) and Scheme (chicken) has been added. This is just my golfing ground for to-be updates since updating the main post takes forever.

```
"1\"09!#.&&+.@"" "" "#|"
#=
''''
<<s
11]0=~2base{+}*}
 ?
 :_7/!\_7%!@
"
R"Happy Birthday, "[?S"!"*"
>0[0>i:0(?v:{)?v0n;\!/
$'main';n1< .95<
(-[Hello, World!]o#''';print(input()in input());'''"]];ri:X{_~X+S*'/@S*_'\4$N}%_sW%1>"=#print(([1 1;1 0]^int(readline()))[1,2])#=)?(!?)
s
l=gets
a='+-'+?-*~/$/+'-+'
puts a+'
| %s |
'%l+a# =##'''#";e# |#(print(format"~x"(eval(read))))

```

I could save a few bytes for Julia since unterminated multiline comments raise an error to STDERR.

# Answer
> 26 votes
# ~~7~~ ~~8~~ ~~9~~ 10 languages, ~~398~~ ~~431~~ ~~447~~ 507 bytes

This is probably the most I can fit in the current solution.

```
#if      + 0+0/*^",v  +- '[.,][[" ,yadhtrib yppaH"l?!;offf4+ + +0.0 +aa<*/
a=0--0;b=input();print(sorted(set(b))==list(b));[[""""                 ^ <
print("Hello, World!")--[[vv? +<
#endif/*  >.!0 + +1ffr"!"~< */
#include<stdio.h>/*>:1 +?!^>i:1^*/
int main(){int a=1,b=1,c,i;scanf("%d",&i);if(1//**/1==2
){printf("%x",/*>&:7/.7%.@*/i);}else{for(;--i-1>0;a=b,b=c)c=a +b;printf("%d",b);}}/*]]--"""]];#@;_J + + \+*\-hhlz \+s[\|dzd\|)J "` + +,*.]]]*/SSSTNSSNSNSTNTTTTTSSSTNSNSTNTTTTTTSSTNTTSNSSNNSSSNTTTTNSTNNNN

```

The last line contains Whitespace code encoded so that SE doesn't eat it. To run the code, replace all `S` with spaces, `T` with tabs and `N` with newlines.

## C89, task 16

Here's what the compiler sees:

```
int main(){int a=1,b=1,c,i;scanf("%d",&i);if(1/ 1==2
){printf("%x",i);}else{for(;--i-1>0;a=b,b=c)c=a+b;printf("%d",b);}}

```

Everything else is stripped as comments or inside the `#if 0`.

## C++, task 14

I used a trick stolen from here to differentiate between C89 and C++.

```
int main(){int a=1,b=1,c,i;scanf("%d",&i);if(1
){printf("%x",i);}else{for(;--i-1>0;a=b,b=c)c=a+b;printf("%d",b);}}

```

## Lua, task 2

Here's the basic structure.

```
#comment
a=0--comment
print("Hello, World!")--[[
... multiline comment ...
]]--comment

```

## Brainfuck, task 1

I just had to ensure no infinite loops or stray `.,`s are found. Lua's multiline comments also double as BF comments. Everything apart from the first 2 characters is a large NOP loop.

```
++,+-[.,][[,+++.+<--[[<,--[[+<>.++<<.>>+>,,,,,>..--->,+,]]--]]+++-+[++,.]]]

```

## Python, task 6

Again, I'm using language-specific features to NOP or comment out the other code.

```
#comment
a=0--0;b=input();print(sorted(b)==list(b));[["""
... multiline string ...
"""]];#comment

```

## Pyth, task 17

Pyth is nice for this thing. It takes the first `#` as a `while True:` loop *that exits silently on error*. So, I just make most of the code a string (as to avoid `;`s ending the loop early), then just end the loop, exit another created by the Python comment and do the task. Here's it with all non-empty strings replaced with `" string "`, it's still functionally equivalent:

```
#if      + 0+0/*^" string " ,yadhtrib yppaH" string """" string "Hello, World!" string "!"  string "%d"  string "%x" string "%d" string """]];#@;_J + + \+*\-hhlz \+s[\|dzd\|)J " string

```

## \>\<\>, task 3

This one is very interesting. The execution bounces around in the code, using jumps where necessary to get around obstacles. The relevant parts:

```
#                  v            " ,yadhtrib yppaH"l?!;offf4+ + +0.0 +aa<*/
                   i                                                   ^ <
                   !      vv? +<
          >.!0 + +1ffr"!"~<
                   >:1 +?!^>i:1^

```

## Starry, task 9

Here I had to start going into the "discard all characters except " languages. Anything else stripped out, it looks like:

```
      + +*,  + '., , + + +. +*                  ,  +*  . + + *.* +*  ,,,,**,*..*, +,* + + +* + ` + +,*.*

```

The code skips most of the punctuation with a jump to avoid a hard time, just using the start and end of the code. The code is functionally equivalent to

```
      + +*,  + + +,*.*

```

## Befunge-98, task 10

Works similarly to the \>\<\> one. Luckily, `#` is a mirror in \>\<\> and a skip in Befunge, so we can implement different behavior. Also, `0/0 == 0`.

```
#if      + 0+0/*^
                >&:7/.7%.@

```

## Whitespace, task 13

This was the last thing I fit in. The first few lines are just pushing zeroes onto the stack, as they only contain spaces and newlines from the "normal" code. The code is encoded; replace all `S` with space, `T` with tabs and `N` with newlines.

```
SSSSSSSSSSSSSSSN
SSSSSSSSSSSSSSSSSSN
SSN
SSSSSN
SN
SSN
SSSSSSSSSSSTN
SSN
SN
STN
TTTTTSSSTN
SN
STN
TTTTTTSSTN
TTSN
SSN
N
SSSN
TTTTN
STN
N
N

```

# Answer
> 12 votes
# 17 different versions of Pip, 383 bytes (invalid)

While this question was sandboxed, I combed through all the revisions of my language Pip and came up with a polyglot using 17 of them. Sadly, versions of the same language are disallowed by the challenge rules now, but with Dennis's permission and a disclaimer I'm posting my work anyway.

### The raw code

```
I!ga:0m@0:0v:uIN[(oTM0,0i)EN1N1Y1RCkw(hR`1.+0``&2o`)@>3@AB0`u`rZ4AB6({a}V7)BN8AZ9@m]Iv<2W##YqlPByc:((J['.'@]X4)X4RL3)Jnc.:n.RVcc:cRL4|0Iv=3{d:sXaRLaFj,ad@j@j:'\d:(RVdR'\'/).d|0dJ:n}m:'+.'-X#a+2.'+.n."| "Iv=5La{i+:oSio}j:ak:bPv=11?a>1&0INa%(2,a)[((J_M ZRVl)|0)Jnl?lJnlcJnd.n.RVdm.a.RVmih:$+TBa({j@aEQk}FI0,#a).saTB16a>b?abh=1ua//7.s.a%7a+bbINa"Happy Birthday, ".a.'!"Hello, World!"]@v

```

### The strategy

In Pip, lowercase letters are variables. Uppercase letters are more complicated: they are broken into runs of at most two characters, which can be operators or variables. If an uppercase token isn't specifically defined as a variable or operator, it is assumed to be an undefined variable, which evaluates to nil.

So, to distinguish between two versions of Pip, I just have to find some variable or alphabetic operator that was added in the newer of the two. In the older one, it will be nil instead. The code `v:uIN[...]` puts together a big list containing one of these checks for each version I want to test, finds out how many nils are in that list (the `u` variable is explicitly initialized to nil), and stores the number in `v` (for "version").

After some other calculations, there's another big list that calculates the results for 17 of the tasks from the challenge and uses `v` to select one based on what version this is.

### Versions and tasks

**0.15.09.04**

Diagnostic: `(oTM0,0i)` (fixed a bug with `T`ri`M` operator where trimming 0 characters from each end of a string would give the empty string instead; indexing into empty string gives nil)

Task 18: `Iv<2W##YqlPBy` (setup: read all lines from stdin if `v` is less than 2) followed by `((J_M ZRVl)|0)Jn` (reverse list of lines, transpose, and join back into string)

**0.15.08.06**

Diagnostic: `EN1` (added `EN`umerate operator)

Task 1: `Iv<2W##YqlPBy` (same setup code as above) followed by `l?lJnl` (join on newlines)

**0.15.08.03**

Diagnostic: `1N1` (added `N` as short version of `IN` operator)

Task 20: `c:((J['.'@]X4)X4RL3)Jnc.:n.RVcc:cRL4|0` (setup: generate list containing upper and lower halves of chessboard and store in `c`) followed by `cJn` (join on newline)

**0.15.08.01**

Diagnostic: `Y1` (added `Y`ank operator)

Task 19: `Iv=3{d:sXaRLaFj,ad@j@j:'\d:(RVdR'\'/).d|0dJ:n}` (setup: if `v` is 3, build top half of diamond in `d`) followed by `d.n.RVd` (reverse for bottom half and join on newline)

**0.15.06.19**

Diagnostic: `RCk` (added `R`andom `C`hoice operator)

Task 17: `m:'+.'-X#a+2.'+.n."| "` (setup: build `+----+\n|`  string in `m`) followed by `m.a.RVm` (wrap input in `m` and reverse of `m`)

**0.15.06.12**

Diagnostic: `k` (preinitialized `k` variable to `", "`; previously it was undefined and thus nil)

Task 16: `Iv=5La{i+:oSio}` (if `v` is 5, generate Fibonacci number in `i`) followed by `i`

**0.15.06.08** (note: version number wasn't changed till the following commit)

Diagnostic: `w` (preinitialized `w` variable to ``\s+``)

Task 15: `h:$+TBa` (convert input to binary and sum digits; save result in `h` for task 12 later)

**0.15.05.29**

Diagnostic: `(hR`1.+0``&2o`)@>3@AB0`

This version added `&` as a replacement pattern for the whole matched string in a regex replacement (inspired by sed). The code above takes `h` (`100`) and replaces it with ``&2o`` (i.e. `"1002o"` in newer versions but simply `"&2o"` in older versions). It then slices all characters after the 3rd (`"2o"` in newer versions, `""` in older versions) and attempts to index into that string. Indexing into an empty string gives nil.

Task 7: `j:ak:b` (setup: copies local vars `a`,`b` to global vars `j`,`k` so they'll be available inside a function) followed by `({j@aEQk}FI0,#a).s` (filter for indices in `a` where the corresponding character equals `b`, and join on space)

**0.15.05.26**

Diagnostic: ``u`` (added Pattern type; in previous versions, backticks are ignored as unrecognized characters, and the expression evaluates to `u`, which is nil)

Task 14: `aTB16` (convert `T`o `B`ase 16)

**0.15.05.24**

Diagnostic: `rZ4` (created `r` special variable which returns a random value between 0 and 1 each time it is referenced; previously it was undefined and thus the expression evaluated to nil)

Task 13: `a>b?ab` (ternary expression)

**0.15.05.12**

Diagnostic: `rZ4` (added `Z`ip operator)

Task 12: `h=1` (sum of bits from task 15 must equal 1)

**0.15.05.11**

Diagnostic: `AB6` (added `AB`solute value operator)

Task 11: `Pv=11?a>1&0INa%(2,a)[...]@v` (if `v` is 11, output `1` if input is greater than 1 and a smaller number divides it exactly, `0` otherwise; if `v` is anything else, use `v` as an index to the list to decide what to output)

**0.15.05.02**

Diagnostic: `({a}V7)` (added `V` operator; when `V` was undefined, this sent arguments nil and 7 to a function `{a}` that returns its first argument)

Task 10: `a//7.s.a%7` (input int-divided by 7 and mod 7, space-separated)

**0.15.04.26**

Diagnostic: `BN8` (added `B`itwise `N`egation operator)

Task 9: `a+b`

**0.15.04.23**

Diagnostic: `AZ` (preinitialized `AZ` variable to uppercase alphabet)

Task 5: `bINa` (`IN` gives count of occurrences)

**0.15.04.20**

Diagnostic: `m@0:0` followed by `9@m`

The `m` variable is preinitialized to 1000. In this commit, the `@` operator was fixed to return lvalues; previously, assigning to `m@0` gave a warning and did nothing. Thus, post-bugfix, the first statement sets `m` to `0000`, which is a legal index for `9`; pre-bugfix, `m` stays `1000`, which is not a legal index. (Indices were not yet cyclical.)

Task 3: `"Happy Birthday, ".a.'!`

**0.15.04.18**

All previous diagnostics result in a nil being added to the diagnostic list.

Task 2: `"Hello, World!"`

---

Most of the other code is tweaks I had to make to avoid errors in various versions. This post is already far too long, so if you want to know about anything I haven't explained, let's take the discussion to the esoteric languages chatroom.

# Answer
> 6 votes
# ~~14~~ 15 languages, 487 bytes

### brainfuck, Thue, Fission, Rail, Perl, \>\<\>, Surface, Whitespace, Gol\>\<\>, Befunge-93, Hexagony, Python 3, PingPong, Cardinal, Ruby

```
#\&v/,[.,][   	.hzPSIv?:<
#!oan-2l.1*8=;?(1:i::<
# :< /2_0#!x%x2$:_.#-@#1:
#>,>, 	\
#	o->+o
#/o?  </
#>:@

#.....\?{?'-~^!@0!;J$?0J$ " ,yadhtriB yppaH"L
print	([]and(0and("#{a=$<.map(&:chars);a[-1].zip(*a).map{|z|z[1,10].reverse*''}*$/}")or"@{[1+index<>,<>]} ")or	0x0or'%x'%(0x0+int(input())))
__DATA__=1
+1;"""
@.<x
v: %+v
>-\*<<
^?/~^
m::=~Hello, World!
::=
$'main'-\
@-[	]e</i-@
 x>qfq--[I hate spaces!]o
@-[I love tabs!]o
 '+`\@:+/=
2% ^/*;#\
]"""

```

Lots of 2D languages. I'm pretty sure I could fit at least ~~two~~ one more languages in here, but a few of the ones I was thinking of ended up being newer than 2015, plus this is fast approaching the size limit.

### 1. brainfuck

This is a simple cat program on the first line, followed by wrapping most of the rest of the program in a non-executing loop to prevent anymore printing.

```
    ,[.,][

]

```

Try it online!

### 2. Thue

This executes the lines with `::=` towards the end of the program, ignoring any other lines. This simply looks for any `m`s in the rest of the program after `::=` and prints "Hello, World!" for each of them.

```
m::=~Hello, World!
::=
  m

```

Try it online!

### 3. Fission

This starts execution from the `L` on the tenth line (it also starts from the `D` in `__DATA__`, but we immediately kill that). This first prints "Happy Birthday, ", then does a cat program.

```
#0!;J$?0J$ " ,yadhtriB yppaH"L

```

Try it online!

### 4. Rail

This starts from the line that starts with `$'main'`. This is essentially a golfed version of SP3000's Rail program, compressed to four lines and about 15 bytes shorter. It essentially has the same logic, but crosses over itself a couple extra times.

```
$'main'-\
@-[ ]e</i-@
  >qfq--[I hate spaces!]o
@-[I love tabs!]o

```

Try it online!

### 5. Perl

This is part of a smaller polyglot with Python and Ruby. Generally, `[]` is truthy in Perl and Ruby but not Python, and `0` is truthy in Ruby but not Perl. This checks the index of one input in another, and adds one to the result to make it 0 for falsey and a positive number for truthy. This is enclosed in a string interpolation to avoid syntax errors with Ruby and Python. We also have the `__DATA__=1` line to prevent it from parsing further than that.

```
print "@{[1+index<>,<>]} "

```

Try it online!

### ~~6:~~

### 7: \>\<\>

This takes input of the character through the command line and the string through STDIN. This first reflects of the first `#`, then uses `v?:` to distinguish between this and Gol\>\<\>. This goes down to the second line and loops over the input, checking each character against the command argument, printing the stack height if so.

```
#                    v?:<
 !oan-2l.1*8=;?(1:i::<

```

Try it online!

### ~~8.~~

### 9. Surface

Surface is a 2D language ignoring characters it doesn't recognise. It reflects off the `\` and reads the input numbers into two cells with `>,>,`. Next it enters a loop, decrementing one number and incrementing the other, exiting once one reaches zero. Finally it prints the resulting cell as number.

```
 \

 >,>,  \
  o->+o
 /o?  </
 >:@

```

Try it online!

### 10. Whitespace

This one is rather hard to see, but it essentially executes the instructions:

```
push 32  (SSSTSSSSSL)
dup      (SLS)
dup      (SLS)
readi    (TLTT) (saves to heap at 32)
retrieve (TTT) (retrieves from 32)
dup      (SLS)
push 7   (SSSTTTL)
div      (TSTS)
printi   (TLST)
swap     (SLT)
printc   (TLSS)
push 7   (SSSTTTL)
mod      (TSTT)
printi   (TLST)

```

Try it online!

### 11. Gol\>\<\>

This follows a similar path to \>\<\>, diverging at the behaviour of `?:`, since popping the stack results in `0`. It then executes read input as number (`I`), is it prime (`SP`), is it zero (`z`), halt and output (`h`).

```
#              hzPSI ?:<

```

Try it online!

### 12. Befunge-93

This interprets `#` as a skip instead of a reflect, taking input (`&`) and going down at the `v` then to the third line. This interpreter ignores invalid characters, skipping past the `a` and the pair of `x`s later. This divides the input by two until either it is odd or it is one, and then outputs accordingly (I could probably simplify this check couldn't I?).

```
# &v

# :< /2_0#! % 2$:_.#-@#1:

```

Try it online!

### 13. Hexagony

Hexagony has a strange path, with the second character being a `\`, but it eventually ends up at after the `.....` on the tenth line. Here it gets the inputs into adjacent edges (`?{?`), then subtracts one from the other (`'-~`), and then navigates based on whether that is negative, printing the larger one and terminating (`^!@`). Note that Hexagony appears to have a bug where a number cannot be the first input without a space before it.

```
 \

          \?{?'-~^!@

```

Try it online!

### 14. Python 3

This is pretty a simple task in Python (`'%x'%int(input())`), but made more complicated by the `%`s spawning Cardinal pointers. We compensate for these with `x`s sprinkled in liberally.

```
print(0x0or'%x'%(0x0+int(input())))

```

Try it online!

### 15. PingPong

PingPong skips over the `\` with the initial `#`, wrapping to the bottom at the `/`. This goes to the bottom of the code, and enters the loop there, continuly integer dividing by two and summing the modulo by 2 until the input reaches `0`. Then it outputs the sum it has collected.

```
#  v/

...

 '+`\@:+/=
2% ^/*;#\

```

Try it online!

### 16. Cardinal

Cardinal is a bit of a pain, since it initially spawns pointers at all `%`s, which usually need to be squashed with `x`s. The one we do use in near the bottom, in the string literal. This spawns two pointers, one which collects the input and decrements until it reaches zero, and one that is continually generating the fibonacci numbers by flipping its two values and adding them. Once the first pointer reaches zero it is destroyed by the `?`, leading to the second pointer being reflected upwards into the `. <` to be printed.

```
. <x
v: %+v
>-\*<<
^?/~^

```

Try it online!

### ~~17.~~

### 18. Ruby

Probably the language with the most code, this takes place in a string interpolation as usual. This splits up the input into a 2D array, then zips and joins them together in reverse to produce the transposed output.

```
print "#{a=$<.map(&:chars);a[-1].zip(*a).map{|z|z[1,10].reverse*''}*$/}"

```

Try it online!

### ~~19.~~

### ~~20.~~

## Future work

I'll need to find some new languages to work in there, hopefully 2D languages with arbitrary starting points. Challenge 6 should be pretty easy for any simple language, 8 is a bit tougher. 17 should be achievable with a practical language, 19 and 20 may have to use a golfing lang of some sort to be able to fit within the remaining space. To add more than just challenge 6, I might have to replace some of the longer languages and shuffle them around.

# Answer
> 5 votes
# 6 languages, ~~450~~ 404 bytes

### bash, brainfuck, C, gawk4, JavaScript and Minimal-2D

```
/*\t/#[R,+/D
/\t/ # UL.-L<script>var s=prompt().split(' ');alert(+s.pop()+ +s.pop())</script>
sed "s/^\(.*\)$/Happy Birthday, &!/;q"&&0
/\t/#*/
#define func
func main(){puts("Hello, World!");}
//{split($0,b,_);for(i in b)a[NR][i]=b[i++]}END{for(;j++<i;print"")for(k=NR;k;)printf a[k--][j]}
#//]++++++++[>+>+>++++++>++++++++<<<<-]>>++>--<<[>>>>>+++[<++++[<<....>....>-]<<<.>>>>-]<<<[>>+<<-]<[[>+<-]<]>>-]

```

Update: Golfed it down a little. Still not sure what else to add, and I'm not sure how the competing members would think about me using their languages for different tasks. Trying to explain the brainfuck algorithm.

Well this is/was my first polyglot experience, so I had to learn everything from scratch. Starting with awk was not the smartest idea I think, because it is relatively unforgiving. Because the number of completed tasks is relevant I started with the easiest tasks first. Not sure if that was a smart move. This is not very much golfed, because I had enought trouble getting these six working together, but I did what I could to keep it short.

Here are the languages and what they do in alphabetical order. I'll show an easy way to test them all further down. Because some of this might be version specific I'll give you the version numbers of the tools I used.

## bash, task 3

Well, its obvious that I used sed. I tried to put a sed script in this somehow, but I couldn't get it to work, so I went the bash route. The way I dit it, it is inside a C comment and awk evaluates it to `False`.

`sed --version` gives `sed (GNU sed) 4.2.2`

`bash --version` gives `GNU bash, Version 4.3.30(1)-release (x86_64-pc-linux-gnu)`

So the sed part comes down to

```
sed "s/^\(.*\)$/Happy Birthday, &!/;q"

```

It groups the input, pastes it into a new string and prints the result. Pretty common stuff.

## brainfuck, task 20

Well this is always pretty easy to hide I guess. A line starting with `#//` is ignored by C and awk. Or at least they can live with rubbish behind that.

`bf` gives `bf - a Brainfuck interpreter version 20041219`

This is the condensed code. The first line is only the garbage from the other languages.

```
[,+.-<>.+.++.<>.,,,,[][][++]++<[--][]]
++++++++[>+>+>++++++>++++++++<<<<-]>>++>--<<
[>>>>>+++[<++++[<<....>....>-]<<<.>>>>-]<<<[>>+<<-]<[[>+<-]<]>>-]

```

### I'll try to explain how it works

```
++++++++[>+>+>++++++>++++++++<<<<-]>>++>--<<

```

this arranges the tape and pointer to this

```
0 8 10 46 64 C2 C1
  ^

```

the cell holding 8 is the global counter for the following loop
it's the number of times 3 same lines are printed

```
[>>>>>+++

```

sets `C1` to 3, the number of same lines

```
    [<++++

```

sets `C2` to 4, the number of "`....@@@@`" in a line (in the beginning)

```
        [<<....>....>-]<<<.>>>
    >-]

```

prints a complete line decrementing `C2` in the process
when `C2` is zero it prints a newline and decrements `C1`.

if `C1` is zero the magic happens

```
    <<<[>>+<<-]
    <[[>+<-]<]

```

the 46 is moved behind the 64
the 10 and the global counter are moved one to the right

```
>>-]

```

then the global counter is decremented
if it's zero the program exits

## C, task 2

I exhaust every last little ability of C here by printing "Hello, World!". Well, somebody had to do the job...

`gcc --version` gives `gcc (Ubuntu 4.9.2-10ubuntu13) 4.9.2`

The actual C code

```
#define func
func main(){puts("Hello, World!");}
#

```

The `#define func` is to make awk okay with this. It thinks this is an awk function. Abbreviation to func is a gawk feature.

## gawk4, task 18

Since I have used awk for pretty much everything on here, I decided, that it had to be in this.

`awk --version` gives `GNU Awk 4.1.1, API: 1.1 (GNU MPFR 3.1.2-p11, GNU MP 6.0.0)`

awk sees this

```
/*\t/
/\t/
sed "s/^\(.*\)$/Happy Birthday, &!/;q"&&0
/\t/
func main(){puts("Hello, World!");}
//{split($0,b,_);for(i in b)a[NR][i]=b[i++]}END{for(;j++<i;print"")for(k=NR;k;)printf a[k--][j]}
#

```

The search patterns including `\t` evaluate to `false`. I chose tab here, because I think it can't be in the input. `sed` evaluates to `false`. `"the string"&&0` evaluates to false. The function is okay. The program is executed if an empty pattern is matched, which it is for any input.

It does this

### Input

```
elaic
parli
ucfit
srigs

```

### Output

```
supe
rcal
ifra
gili
stic

```

You have to make sure all the input lines have the same length. Use spaces to fill them up.

## JavaScript, task 9

I'm not sure if this is legit, because this was too easy. If you give the program file a html ending, and open it in a browser (I used Firefox 40.0.3 and chrome 45.0.2454.85) it prompts you for an input. You have to enter two numbers separated by space, and it will alert the sum of those.

```
<script>var s=prompt().split(' ');alert(+s.pop()+ +s.pop())</script>

```

## Minimal-2D, task 1

This was pretty easy to fit into comment lines. I used the interpreter, who runs in python, to test this. It prints the input to the output. The program looks like this

```
R,+/D
UL.-L

```

R U D L are right, up, down and left. So it starts going right, reads a character from stdin into memory and adds one. The slash skips the next command if the memory has the value 0. This is to end this. If a character with value -1 is read, the input has ended. So if -1 is read it skips the D and terminates. If something else is read it goes down an left, adds that 1 back to the memory and prints the character to stdout. Then it goes left and up and starts over.

# Testing

*Disclaimer:* I won't take any responsibility for any damages you do to your system with this.

This is assuming you have bash & co, gawk (at least version 4, because this uses multidimensional arrays), gcc, python, bf as a brainfuck interpreter and Firefox installed.

To make it easy, copy the program source to a file named `cluster.html`. Make that file executable for the bash task. Copy and paste the interpreter for Minimal-2d into a file named `minimal2D.py` in the same directory. Then copy and paste the following script to a script file and put it into the same directory, make it executable and run it... well, who am I talking to. If you read this you probably don't need that much explanation and are gonna get it to run somehow anyway.

```
#!/bin/bash
# Task  3: bash
echo "Dr. Hfuhruhurr" | ./cluster.html 2>/dev/null;echo
# Task 18: awk
printf "elaic\nparli\nucfit\nsrigs\n" | awk -f cluster.html 2>/dev/null;echo
# Task  2: C
cp ./cluster.html ./cluster.c;gcc -w -o cluster cluster.c;./cluster;rm cluster cluster.c;echo
# Task  1: Minimal-2D
python minimal2D.py cluster.html <<<"This
has
to be
copied     !!!";echo
# Task 20: brainfuck
bf cluster.html;echo
# Task  9: JavaScript
firefox cluster.html 2>/dev/null
#google-chrome cluster.html 2>/dev/null

```

In there you also find the command for running the tests individually.

Have fun!

# Answer
> 5 votes
# 6 languages, 226 bytes (229 depending on how `\x1b` is accepted!)

```
/&&#[+.#]@>>+[>,]<[<]>>[.>]>\[/;//;#<?die("\x1bc".max($argv[1],$argv[2]));/*
$a=['Hello','World'];//;printf"%s, %s!
",$a[0]||'Happy Birthday',$a[1]||pop;#";$a="\
#";alert(prompt().match("\t")?"I hate tabs!":"I love spaces!");/\]/

```

So, I don't think I made the best choice of languages and I imagine this isn't particularly competetive but I found this an interesting challenge nonetheless! Overall, not many challenges complete, but I could probably shoehorn a challenge in whitespace or something similar, but this is what I have so far:

---

### 1. Brainfuck

```
[+.]>>+[>,]<[<]>>[.>]>[<.[],[][,],,[],[].]

```

Tested on http://copy.sh/brainfuck/ and http://brainfuck.tk/.

After stripping out all ignored chars, the above program is all we're left with, which is just the example cat program with some extra empty loops to bypass the other languages use of the symbols.

### 2. Ruby

```
/&&#[+.#]@>>+[>,]<[<]>>[.>]>\[/;//;
$a=['Hello','World'];//;printf"%s, %s!
",$a[0]||'Happy Birthday',$a[1]||pop;

```

Usage:

```
ruby cluster

```

The above is the code after all comments are removed. The first line is entirely useless in Ruby as we define some regular expressions to contain the Befunge-93 and brainfuck code, then we create an array to contain `Hello` and `World` and print it using `printf` (to add the `,` and `!`).

### 3. Perl

```
/&&#[+.#]@>>+[>,]<[<]>>[.>]>\[/;//;
$a=['Hello','World'];//;printf"%s, %s!
",$a[0]||'Happy Birthday',$a[1]||pop;

```

Usage:

```
perl cluster <name>

```

Very similar to Ruby, except that since we're storing an array reference in `$a`, when we try to access `$a[0]` it's empty, so we can replace it with the text for challenge 3, `Happy Birthday` and `pop` (which shows the last argument to the command-line program).

### 4. JavaScript

```
/&&#[+.#]@>>+[>,]<[<]>>[.>]>\[/;
$a=['Hello','World'];
",$a[0]||'Happy Birthday',$a[1]||pop;#";$a="\
#";alert(prompt().match("\t")?"I hate tabs!":"I love spaces!");/\]/

```

Usage: paste into browser console and run.

Same as Ruby and Perl, the first line essentially creates useless `RegExp` objects, we then store a useless array in `$a` and instantiate two useless strings, one containing the Ruby/Perl code and one containing a newline and a `#`, then we `prompt()` for input and `alert()` the result expected by most humans for challenge 4. We end with another useless `RegExp` object to close off the brainfuck loop.

### 9. Befunge-93

```
/&&#[+.#]@

```

Tested on http://www.quirkster.com/iano/js/befunge.html.

As I understand it, `/` divides the stack and pushes the result which has no ill-effects except pushing `NaN` on the above site, `&` asks for input of an integer so we read both numbers required by challenge 9 onto the stack, the `#` ensures we skip over the `[` which is there for brainfuck, `+` then adds the top two numbers on the stack, `.` outputs them, `#]` for brainfuck again and `@` exits.

### 13. PHP (running in Bash)

```
/&&#[+.#]@>>+[>,]<[<]>>[.>]>\[/;//;#<?die("\x1bc".max($argv[1],$argv[2]));

```

Usage:

```
php cluster <x> <y>

```

In PHP, anything not included within the `<?` tags is output verbatim, so this outputs the Befunge-93 and brainfuck code so we `die()` immediately in the code, output a screen clear (`\x1bc`) then the `max()` of the first two arguments.

---
Tags: code-challenge, math, ascii-art, string, polyglot
---


title: The Roly-Poly, Square-Wheeled Quine

text:
# Question
Title: The Roly-Poly, Square-Wheeled Quine
Code-Golf caddy Eddie Brackets was getting tired of quine challenges, which appeared to be much too easy for the grand poobahs. He has this idea to spice up things and is sending quines to the car crusher.

**Challenge**: Write a quine that prints itself "squeezed" for output purposes into an n x n square followed by that same square three more times, each time rotated **90 degrees to the right**, for a total of **4 squares**. (By *squeezed* quine, Eddie means one that has all its printable characters but has all the white space (spaces, tabs, line feeds) removed. Of course, it may or may not work as a real quine after being squeezed, but it's what Eddie is talking about for his output.)

Example: If a solution quine in some language were: `A%C~?5 F$G &G52[/<`

its **Output** must be:

```
A%C~
?5F$
G7G5
2[/<

2G?A
[75%
/GFC
<5$~

</[2
5G7G
$F5?
~C%A

~$5<
CFG/
%57[
A?G2

```

**Rules**

1. All *whitespace* in the code **counts** toward the final byte count, but must be *removed* in the output squares. There must be at least 4 printable (i.e. visible, non whitespace) characters in the quine, i.e. a minimum of 16 printable characters output.
2. The four squares may be printed **either** horizontally **or** vertically, but **must** be separated by at least one space or delineating character(s) (horizontally) or at least one blank line or delineating character(s) (vertically). The first square is the "squeezed" program code (whitespace removed) printed n characters to a line. Nothing should appear *between* the output characters in each output square, which should each be a solid block of characters. Each square must contain all the printable characters of the quine.
3. Orientation of all characters in the rotated output remains just as it is in the code, e.g. \< remains \< and never changes to \> or ^.
4. Code golf: shortest code in bytes wins.

In summary, your quine will have n^2 printable characters, and each of the four output squares will be n x n.

# Answer
# Jelly, 25 bytes

```
“Ṿ;⁾v`s5ṚZ$3Ð¡YY¹¹¹¹¹¹”v`

```

Try it online!

A full program that takes no arguments and prints itself formatted as a 5x5 square with its three 90° rotations. Note the 5 `¹` are just padding - the program would work without them but would give a 5x4 rectangle.

## Explanation

```
“Ṿ…¹”v` | Evaluate the string as Jelly code, supplying itself as an argument

```

### Code within string

```
Ṿ                     | Uneval (wraps argument in “”
 ;⁾v`                 | Append "v`"
     s5               | Split into pieces of length 5
         $3Ð¡         | Do the following three times, keeing all intermediate results as well as the start:
       Ṛ              | - Reverse
        Z             | - Transpose
             Y        | Join with newlines
              Y       | Join with newlines
               ¹¹¹¹¹¹ | Identity function (repeated 6 times)

```

Implicit print at the end.
> 3 votes

# Answer
# , 49 bytes

```
apply~'][:echo[:|:@|.^:(<4),~@7$''apply~'',quote'

```

Try it online!

The standard J quine (26 bytes plus newline) is required to have even length because it is a string repeated twice. The square formatting and rotating 4 times do not fit into 36 bytes and therefore must be lengthened to 64 bytes.

This quine circumvents this even-length problem by using a built-in that works just like Jelly's `v` built-in: eval the string as a verb and feed one argument. The basis then becomes the following at **30 bytes**. (technically 29 because `[:` can be shortened to `@`, but we need to do something more on that string after all)

```
apply~'[:echo''apply~'',quote'

```

Try it online!

Now we just need to insert **one** copy of the string manipulation code, which barely fits in 49 bytes without whitespace.

```
][:echo[:|:@|.^:(<4),~@7$'apply~',quote  NB. the eval-ed string
quote      NB. uneval the string; double each quote and surround with quotes
'apply~',  NB. prepend this string
,~@7$      NB. equal to `7 7$`; format into a square (`_7]\` also works)
[:|:@|.^:(<4)    NB. generate four rotations
[:echo     NB. print the resulting 3d array of chars
           NB. each matrix is printed with an empty line between them
]          NB. a no-op padding to make 49 bytes

```
> 3 votes

# Answer
# 05AB1E (legacy), 36 bytes

```
00"D34çý6ô4FD»,¶?øí"D34çý6ô4FD»,¶?øí

```

Try it online.

**Explanation:**

```
00                   # Push 00
  "D34çý6ô4FD»,¶?øí" # Push this string
   D                 # Duplicate this string
    34               # Push 34
      ç              # Convert it to a character: '"'
       ý             # Join the stack with this character as delimiter:
                     #  '00"D34çý6ô4FD»,¶?øí"D34çý6ô4FD»,¶?øí'
        6ô           # Split it into parts of size 6
          4F         # Loop 4 times:
            D        #  Duplicate the current list of strings
             »       #  Join it by newlines
              ,      #  Print it with trailing newline
               ¶?    #  And also print an empty line
                     #  Then rotate it around 90 degrees clockwise, by:
             ø       #   Zipping/transposing; swapping rows/columns
              í      #   And then reverting each row

```
> 1 votes

# Answer
# Python 3, ~~147~~ 121 bytes

```
s="a='s=%r;exec(s*4)'%s;*map(print,map(''.join,[*zip(*[iter(a)]*11),''])),;a=(11*('_'+a))[-11:0:-11];aaaaaaaaa";exec(s*4)

```

Try it online!

prints in a 11x11 square.

## How it works:

* start from the quine `s="print('s=%r;exec(s)'%s)";exec(s)`
* `a='s=%r;exec(s*4)'%s` store our string in `a`
* `zip(*[iter(a)]*11)` split the string `a` in rows of 11 chars
* `*map(print,map(j,[* <...> ,''])),` display each row plus a newline
* `a=(11*('_'+a))[-11:0:-11]` rotates `a` and store the new value in `a`
* `;aaaaaaaaa` adjust the size of the square
* `exec(s*4)` execute the code 4 times, the `;aaaaaaaaa` transform the initialisation of `a` to avoid overriding `a` and keep it rotated

because of `a` is 121 char long, the result fits in a 11x11 box
> 0 votes

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


title: Code golf edit distance 2

text:
# Question
Title: Code golf edit distance 2
The **edit distance** between two strings is the minimum number of single character insertions, deletions and substitutions needed to transform one string into the other.

This task is simply to write code that determines if two strings have edit distance exactly 2 from each other. The twist is that your code must run in **linear time**. That is if the sum of the lengths of the two strings is n then your code should run in O(n) time.

# Example of strings with edit distance 2.

```
elephant elepanto
elephant elephapntv
elephant elephapntt
elephant lephapnt
elephant blemphant
elephant lmphant
elephant velepphant

```

# Examples where the edit distance is not 2. The last number in each row is the edit distance.

```
elephant elephant 0
elephant lephant 1
elephant leowan 4
elephant leowanb 4
elephant mleowanb 4
elephant leowanb 4
elephant leolanb 4
elephant lgeolanb 5
elephant lgeodanb 5
elephant lgeodawb 6
elephant mgeodawb 6
elephant mgeodawb 6
elephant mgeodawm 6
elephant mygeodawm 7
elephant myeodawm 6
elephant myeodapwm 7
elephant myeoapwm 7
elephant myoapwm 8

```

You can assume the input strings have only lower case ASCII letters (a-z).

Your code should output something Truthy if the edit distance is 2 and Falsey otherwise.

If you are not sure if your code is linear time, try timing it with pairs of strings of increasing length where the first is all 0s and the second string is one shorter with one of the 0s changed to a 1. These all have edit distance 2. This is not a good test of correctness of course but a quadratic time solution will timeout for strings of length 100,000 or more where a linear time solution should still be fast.

# Answer
> 7 votes
# Retina 0.8.2, ~~76~~ 58 bytes

```
^(.*)(.*¶)\1
$2
(.*)(¶.*)\1$
$2
^.?¶.?$

^.?(.*).?¶.?\1.?$

```

Try it online! Takes the two strings on separate lines, but link includes test suite which takes space-separated strings instead, so that I can easily use the test cases. Explanation:

```
^(.*)(.*¶)\1
$2

```

Delete the common prefix.

```
(.*)(¶.*)\1$
$2

```

Delete the common suffix.

```
^.?¶.?$

```

Ignore an edit distance of less than two.

```
^.?(.*).?¶.?\1.?$

```

Check that only the first and last characters have been edited, so that the edit distance cannot be greater than two in this case.

From a code golf point of view this can be done in 51 bytes but then the regex becomes unbearably slow to execute for longer strings:

```
^(?!(.*).?(.*)¶\1.?\2$)(.*).?(.*).?(.*)¶\3.?\4.?\5$

```

Try it online! Takes the two strings on separate lines, but link includes test suite which takes space-separated strings instead, so that I can easily use the test cases. Explanation:

```
^

```

Match the whole input.

```
(?!(.*).?(.*)¶\1.?\2$)

```

Don't match strings with an edit distance less than two.

```
(.*).?(.*).?(.*)¶\3.?\4.?\5$

```

Match strings with an edit distance less than three.

# Answer
> 7 votes
# Haskell, ~~124~~ ~~121~~ ~~99~~ 88 bytes

*3 bytes saved by Bubbler*

```
x%y=[0,0]==x#y
u@(a:b)#v@(c:d)|a==c=b#d|k<-zipWith(+)=0:k(d#u)(k(b#v)$b#d)
a#b=a++b>>[0]

```

Try it online!

This is a modification of the below algorithm which uses a bit of complex short-circuiting to accomplish the task.

I owe much to xnor's comment that initially proposed the idea, and to Noughtmare's SO answer which explained why xnor's initial version didn't work.

## 99 Bytes

```
x%y=2==(x#y)0
(u@(a:b)#v@(c:d))x|a==c=b#d$x|x<2=minimum$[d#u,b#v,b#d]<*>[x+1]
(a#b)x=x+length(a++b)

```

Try it online!

We start by looking at a naive version of edit distance:

```
lDistance :: ( Eq a ) => [a] -> [a] -> Int
lDistance [] t = length t   -- If s is empty the distance is the number of characters in t
lDistance s [] = length s   -- If t is empty the distance is the number of characters in s
lDistance (a:s') (b:t') =
  if
    a == b
  then
    lDistance s' t'         -- If the first characters are the same they can be ignored
  else
    1 + minimum             -- Otherwise try all three possible actions and select the best one
      [ lDistance (a:s') t' -- Character is inserted (b inserted)
      , lDistance s' (b:t') -- Character is deleted  (a deleted)
      , lDistance s' t'     -- Character is replaced (a replaced with b)
      ]

```

(I wrote this program for Wikipedia here)

This is pretty bad because every time it finds a discrepancy between the two strings it branches into 3 options (insert, delete or replace) so in the worst case it will have the time complexity of \\$O(3^n)\\$.

The thing to notice though is that whenever we branch we increase the total distance by 1. So if we are on a particular search path that has already branched 2 times and we would branch another time, we can just stop there and say return the total we have for the branch. All values above 2 are the same as far as we are concerned.

Now there is a hard limit on the number of branches that can occur, \\$3^2 = 9\\$, so our computation is \\$O(n)\\$.

In general this strategy has a complexity of \\$O(3^mn)\\$ where \\$m\\$ is the limiting distance and \\$m \< n\\$.

# Answer
> 3 votes
# Python 3.8, <sup>~~273~~ \\$\cdots\\$~~316~~</sup> 312 bytes

Added 30 bytes to fix bugs kindly pointed out by Bubbler.
Added 12 bytes to fix a bug kindly pointed out by ovs.
Saved 9 bytes thanks to ovs!!!

```
def f(*x,i=0):
 b,a=w=sorted(x,key=len);d,c=map(len,w)
 while a[i]==b[i]:
  if(i:=i+1)==d:return i==c-2
 while a[c-1]==b[d-1]:
  if d==1:return c==3
  c-=1;d-=1
 a=a[i:c]
 b=b[i:d]
 return c-i>1and((x:=a[1:-1])==(y:=b[1:-1])or a[:-1]==y or a[1:]==y or a[:-1]==b[1:]or a[1:]==b[:-1]or x==b[:-1]or x==b[1:]or x==b)

```

Try it online!

# Answer
> 3 votes
# JavaScript, 120 bytes

```
a=>b=>a.reduce((t,c,i)=>t.map((n,j)=>p=Math.min(n-(c==b[i+j-2]),p,t[j+1]||4)+1,p=4),[4,4,1,2,3])[b.length-a.length+2]==3

```

Try it online!

Try a large one!

Traditional DP solution, with modification the formula by \\$dp\_{i,k}=\infty \text{ if } \left|i-k\right|\>2 \\$. And we use \\$ k=i+j-2 \\$ here.

`t` is initialed to `[4,4,1,2,3]` which means (the edit distance of an empty string and first `j-2` characters of `b`) plus 1. Any number greater than 3 here means `Infinity`. After `i`-th iteration, `t[j]` is (the edit distance of substring `a[0..i]`, and, `b[0..(i+j-2)]`) plus 1; Or anything greater than 3 if the edit distance is greater than 2.

---
Tags: code-golf, restricted-complexity, edit-distance
---