title: The Versatile Integer Printer

text:
# Question
Title: The Versatile Integer Printer
Write a piece of code that is executable in at least three different languages. The code must output the integer `1` in language number one, `2` in language number two, `3` in language number three etc.

Rules:

* The output must be only the integer, but trailing newlines are OK.
* The code can't take input of any kind
* Different major versions of the same language are considered unique. So, your code can be executable in Python 2 and Python 3, however Python 2.5 and Python 2.7 are not considered unique.
* You may use a new language if and only if it has an esolang/wiki article, available interpreter and documentation, and has been used by at least two users on PPCG prior to using it in this challenge. It must also adhere to these 4 rules.

The score of your submission is the number of bytes in your code divided by the number of languages it can run in cubed. So, a 54 byte solution that is executable in 3 languages will have a score of 2:

```
54 / 3^3 = 2

```

Lower score is better.

# Answer
# 30 languages, 248 bytes, \\$\frac {248} {30^3} = 0.009185\\$

```
#|#?15g,@   	    kkmNmSaIeoe99+{\#/-;n@0ea
#[9!@>.>.eeaww#-1@*"12"	L
#{
###
#`{
25
print(4^2 +7)/2

"""
Jo is here.
$'main'MoO OOM
 7
>Jo, 30
>X Jo
f::=~27
::=]##}#(prin 29)
print (7/6*24)###;alert 2#-[>+<-----]>-.|#(write(if(= 1/5 .2)26 3))"""

```

**Edit:** Beatnik removed since primality testing in Beatnik might not be possible.

The code has tabs in it (which can get mangled by Stack Exchange) and a trailing newline, so here's the `xxd`:

```
00000000: 237c 233f 3135 672c 4020 2020 0920 2020  #|#?15g,@   .
00000010: 206b 6b6d 4e6d 5361 4965 6f65 3939 2b7b   kkmNmSaIeoe99+{
00000020: 5c23 2f2d 3b6e 4030 6561 0a23 5b39 2140  \#/-;n@0ea.#[9!@
00000030: 3e2e 3e2e 6565 6177 7723 2d31 402a 2231  >.>.eeaww#-1@*"1
00000040: 3222 094c 0a23 7b20 090a 2323 230a 2360  2".L.#{ ..###.#`
00000050: 7b0a 3235 0a70 7269 6e74 2834 5e32 202b  {.25.print(4^2 +
00000060: 3729 2f32 0a0a 0a22 2222 0a4a 6f20 6973  7)/2...""".Jo is
00000070: 2068 6572 652e 0a24 276d 6169 6e27 4d6f   here..$'main'Mo
00000080: 4f20 4f4f 4d0a 2037 0a3e 4a6f 2c20 3330  O OOM. 7.>Jo, 30
00000090: 0a3e 5820 4a6f 0a66 3a3a 3d7e 3237 0a3a  .>X Jo.f::=~27.:
000000a0: 3a3d 5d23 237d 2328 7072 696e 2032 3929  :=]##}#(prin 29)
000000b0: 0a70 7269 6e74 2028 372f 362a 3234 2923  .print (7/6*24)#
000000c0: 2323 3b61 6c65 7274 2032 232d 5b3e 2b3c  ##;alert 2#-[>+<
000000d0: 2d2d 2d2d 2d5d 3e2d 2e7c 2328 7772 6974  -----]>-.|#(writ
000000e0: 6528 6966 283d 2031 2f35 202e 3229 3236  e(if(= 1/5 .2)26
000000f0: 2033 2929 2222 220a                       3))""".

```

Alternatively, you can copy and paste the code from this "Try it online!" link.

This is pretty badly golfed, but I wanted to play off the idea that, once you have enough languages, byte count doesn't matter as much any more. Having said that there are some languages I could still easily add (e.g. Objeck) but are currently too long to be useful. I'm running out of good languages though, so I might stop here for now.

Run all programs with `</dev/null 2>/dev/null` (i.e. empty input, surpressed STDERR).

The explanation's quite long, so here's an executive summary:

| No. | Lang. | Non-esolang? | 2D esolang? | BF/BF-deriv? |
| --- | --- | --- | --- | --- |
| 1 | COW |  |  |  |
| 2 | CoffeeScript |  |  |  |
| 3 | Common Lisp |  |  |  |
| 4 | Retina |  |  |  |
| 5 | Befunge-93 |  |  |  |
| 6 | Python 2 |  |  |  |
| 7 | Rail |  |  |  |
| 8 | ETA |  |  |  |
| 9 | Prelude |  |  |  |
| 10 | Gol\>\<\> |  |  |  |
| 11 | evil |  |  |  |
| 12 | Foo |  |  |  |
| 13 | Ruby |  |  |  |
| 14 | \>\<\> |  |  |  |
| 15 | Brian & Chuck |  |  |  |
| 16 | Whitespace |  |  |  |
| 17 | 3var |  |  |  |
| 18 | Axo |  |  |  |
| 19 | Labyrinth |  |  |  |
| 20 | Starry |  |  |  |
| 21 | Fission |  |  |  |
| 22 | Brainfuck |  |  |  |
| 23 | Julia |  |  |  |
| 24 | Lily |  |  |  |
| 25 | GolfScript |  |  |  |
| 26 | Chicken Scheme |  |  |  |
| 27 | Thue |  |  |  |
| 28 | Perl 6 |  |  |  |
| 29 | Picolisp |  |  |  |
| 30 | TRANSCRIPT |  |  |  |

---

## 1. COW

COW is a Brainfuck derivative with additional commands, one of which is numeric output. Anything invalid is ignored, so the executed program is merely

```
MoO OOM

```

which increments the cell to 1 then prints it as a number.

## 2. CoffeeScript (includes interpreter)

CoffeeScript sees:

```
# comments
###
multiline comment
###;alert 2# comment

```

which simply alerts 2.

*(Yes, it'd probably be better if another language took this slot, but I'm too lazy to reshuffle at this point :P)*

## 3. Common Lisp | ideone

Common Lisp (clisp) sees:

```
#|
multiline comment
|#(write(if(= 1/5 .2)26 3))"""

```

`1/5` is a rational and not equal to `0.2`, so 3 is printed. The proceeding `"""` is a syntax error.

Note that `print` seems to output a preceding newline and trailing space in Common Lisp. However, luckily, `write` works in both Common Lisp and Chicken Scheme.

## 4. Retina | Try it online!

**Restrictions introduced**: Every second line starting from the first needs to be a valid regex.

Every pair of lines form a replacement stage, replacing instances of matches of the first line's regex with the second line. In the middle, we have the pair

```

"""

```

which replaces the initial empty string with `"""`. The final empty line, not part of any pair, is treated as a match stage, counting the number of matches of the regex. There are four instances of empty string in `"""`, namely `1"2"3"4`.

## 5. Befunge-93 | Interpreter

Befunge is a 2D language, and the relevant instructions are

```
# # 15g,@

```

in the first line, and the `5` in the `25` line. `#` skips the next instruction, `15g` gets the char at position `(1, 5)` in the code (the `5` in the `25` line), `,` outputs the char and `@` halts.

## 6. Python 2 | ideone

Python sees:

```
# comments
25
print(4^2 +7)/2

"""
multiline string
"""

```

`(4^2+7)/2 = (xor(4,2)+7)/2 = (6+7)/2 = 13/2 = 6`, which gets `print`ed.

## 7. Rail | Try it online!

Rail is a 2D language, and execution start from the `$` of the main function, heading southeast. Thus, the relevant portion of code is

```
$'main'
 7
  o
   J

```

with the `o` and `J` coming from lines used by TRANSCRIPT. After outputting 7, the train hits an unrecognised `J` instruction, which crashes the program.

## 8. ETA | Try it online!

**Restrictions introduced:** Chars before the ETA program should not be in `etaoinsh`.

ETA only recognises the letters `etaoinsh` and their uppercase versions, meaning the code starts off with

```
NSaIeoe

```

`n...e` pushes a base 7 number based on what's within the delimiters, which for `SaI` is `624`, or 312 in decimal. `o` then outputs as char, apparently after modulo 256, giving the char `8` (code point 56). `e` then tries to divide with an empty stack, which fails.

## 9. Prelude | Try it online!

**Restrictions introduced:** No more than one of `()` in any column, `()` matched reading a column at a time, no infinite loops caused by `()`.

This requires the Python interpreter to have `NUMERIC_OUTPUT = True` set.

Prelude is a language where each line is executed separately. A lot of chars get executed, but the important part is the

```
9!

```

on the second line, which outputs 9. `()` in Prelude denote a loop, but thanks to the prominence of `#`s (which pop from the stack), the tops of the stacks are always 0 by the time a loop is hit, so none of them are run. Prelude's source code restrictions regarding `()` introduced some extraneous spaces though.

## 10. Gol\>\<\> | Interpreter

This part (and \>\<\>) work like Martin's answer. The relevant code is

```
#                                      ;n@0ea

```

Gol\>\<\> is a 2D language and `#` reflects the IP, making it travel leftwards. It wraps around, push 10, 14 and 0 to the stack. `@` then rotates the stack, bringing 10 to the top, `n` outputs it and `;` halts the program.

## 11. evil | Try it online!

This part's also similar to Martin's answer.

evil ignores everything except lowercase letters. Ignoring a few more characters, the relevant part is

```
aeeeaeeaww

```

where `a` increments the variable `A`, `e` is evil's weave function which shuffles the bits of `A`, and `w` outputs `A`. Hence we output `1` twice, giving `11`.

But what about the rest of the instructions, and especially that `w` on the last line? Let's just say that sometimes it's easiest to just mess with the code and pray it still works in everything which, here, it somehow did...

## 12. Foo | Try it online!

Foo outputs anything between double quotes, so the relevant part is the

```
"12"

```

on the second line. However, since we need double quotes later we use a method similar to Martin's answer to make Foo error out, namely the preceding `#-1@`. It's unclear why that works in a language which soldiers on in the face of empty stack and division by zero errors, but I'm glad it does.

## 13. Ruby | ideone

Like Python, Ruby sees:

```
# comments
25
print(4^2 +7)/2

"""
multiline string
"""

```

However, it's worth noting that the multiline string is actually three separate strings (`""`, `"..."`, `""`) concatenated together. The print line outputs `(4^2+7) = xor(4,2)+7 = 6+7 = 13`, before erroring out trying to divide `nil` by 2.

## 14. \>\<\> | Try it online!

This part's the same as the Gol\>\<\> part, except `@` brings the 14 up to the top instead, which gets outputted.

## 15. Brian & Chuck | Try it online!

Brian & Chuck is a BF derivative with two tapes, where one tape's instruction pointer is the other tape's memory pointer. In the absence of `````, the first two lines of the source code are used to initialise the tapes.

The relevant chars in the first two lines are:

```
   ?15
#     >.>.

```

The `?` in Brian's tape passes control over to Chuck in the cell being pointed to (the `#`) is nonzero. Chuck then executes `>.>.`, outputting the two chars after the question mark.

## 16. Whitespace | Interpreter

Using `STL` for space, tab and line feed respectively, the start of the program is:

```
SSSTSSSSL
TL
STL
L
L

```

The first line pushes 16 (`+10000` base 2), the preceding `TLST` prints it as a number. The next three newlines halt the program.

Note, however, that this program is interpreter specific. The rest of the code syntax errors in most interpreters, so a more lenient interpreter is required, like the one linked above.

## 17. 3var | Try it online!

Of the first line, a slew of instructions get executed, but the relevant ones are

```
kkmmao#/

```

Due to ETA's restriction, we use `k` to decrement the variable B rather than `a` to increment it. `kk` decrements B to -2 and `mm` squares B twice to 16, which is incremented to 17 with `a`. This is then outputted with `o`.

`#` is then used to reset B to 0, and `/` causes the program to error out via division by 0.

## 18. Axo | Try it online!

<sup>**Restrictions introduced:** No instructions before the Axo program which change the direction of the IP</sup>

Once again, a slew of instructions get executed in the first line, but the relevant ones are

```
# # 15 ,@            9 9  + {   \

```

Axo is a 2D language like Befunge, and `#` is similarly a bridge that skips the next instruction, but only if the top of the stack is zero. `15,` push to the stack, but the stack is emptied with `@`. `99+` then pushes 18, `{` outputs and `\` halts.

## 19. Labyrinth | Try it online!

Labyrinth is another 2D language, and the executed instructions are

```
#|#
 [9!@

```

`#` pushes the length of the stack, which is 0 the first time. `|` is bitwise OR, not changing anything since the stack just has 0s at this point, and the second `#` now pushes 1 due to the lone zero. We turn right due to the 1, `9` converts this 1 to `1*10+9 = 19`, `!` prints it and `@` halts.

This program relies on the fact that `[` is not currently a recognised instruction, and hence is treated as a wall.

## 20. Starry | Try it online!

<sup>**Restrictions introduced:** All `+`s must have at least one preceding space</sup>

If we strip away unrecognised characters, the relevant part of the code is

```
,       +.. +

```

`,` is input, but since we pipe from `/dev/null` there is none, pushing 0 to the stack. A `+` with `n >= 5` preceding spaces pushes `n-5`, so the next instruction pushes 2. `..` then outputs these two digits in reverse order.

Next we have a `+` with a single preceding space, which duplicates. However, the stack is empty, so we error out.

## 21. Fission | Try it online!

The only relevant part for Fission is

```
*"12"L

```

`L` spawns an atom moving leftward, `"21"` prints 21 and `*` halts.

## 22. Brainfuck | Try it online!

<sup>**Introduced restrictions:** No `.` before the first `[`</sup>

This requires an interpreter which gives 0 on EOF and has 8-bit cells. The relevant code is

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

```

The inital `-` is to offset the `+`, and the first `[...]` is not executed since the cell is 0. The following `-[>+<-----]>-` sets the cell to the char code of `2`, and `..` outputs it twice.

## 23. Julia | Try it online!

Julia sees:

```
# comments
25
print(4^2 +7)/2

```

What's printed is `4^2+7 = pow(4,2)+7 = 16+7 = 23`, and the program errors out trying to divide `nothing` by 2. Note that Julia doesn't seem to mind the fact that the rest of the code would cause a syntax error anyway.

## 24. Lily | Interpreter

Lily sees:

```
# comment
#[
multiline comment
]## comment
print (7/6*24)# comment

```

`7/6*24 = 1*24 = 24` is printed.

## 25. GolfScript | Try it online!

GolfScript sees:

```
# comments
25
print(

```

GolfScript is stack-based, so 25 is pushed to the stack, then popped and printed with `print`. `(` then tries to decrement the implicit empty string on the stack, which fails and errors out the program.

## 26. Chicken Scheme | ideone

Chicken Scheme has the same `#| ... |#` multiline comment syntax as Common Lisp. However, in

```
(write(if(= 1/5 .2)26 3))

```

`1/5` is a float which *is* equal to `0.2`, so 26 is outputted instead.

## 27. Thue | Try it online!

Thue is a language based on string rewriting. The first relevant part is

```
f::=~27
::=

```

which defines a substitution `f -> 27` then denotes the end of substitutions with `::=`. The lone `f` in `if` is then replaced with `27`, which is outputted.

## 28. Perl 6 | ideone

Perl 6 has a new comment syntax, namely `#`(some bracket)` which is a multiline comment all the way to the matching bracket. Thus, Perl 6 sees:

```
# comments
#`{
multiline comment
}# comment
print (7/6*24)# comment

```

which prints `7/6*24 = 28`.

## 29. Picolisp | ideone

Picolisp sees:

```
# comment
#{
multiline comment
}#(prin 29)

```

which prints 29. The line afterwards then causes a syntax error.

## 30. TRANSCRIPT | Try it online!

TRANSCRIPT is a thematic esolang modelled after text adventures. Unrecognised lines are ignored (which allows you to add extra story/flavour text amongst the actual code instructions), so the relevant lines are:

```
Jo is here.
>Jo, 30
>X Jo

```

The first line declares a string variable `Jo`, using a two-letter name since one-letter names seem to fail. The second line sets this string to `"30"`, which is outputted by `X` ("examine") in the third line.
> 100 votes

# Answer
## 15 languages, ~~68~~ ~~66~~ 65 bytes / 15^3 = 0.019...

**Retina**, **Starry**, **Prelude**, **ETA**, **Axo**, **Labyrinth**, **Hexagony**, **Foo**, **Brian & Chuck**, **Gol\>\<\>**, **evil**, **Whitespace**, **Fission**, **\>\<\>** and **GolfScript**.

After a massive rewrite, I managed to fit in four more languages. The code contains the few tabs for Whitespace. Since Stack Exchange converts them to spaces, I've represented them with `\t` below:

```
#I5aeeNTH{\?      \t\t + +3;n@"8"ea9
15}7'`--~!@<"31"LSOe.\t
 \teaww`

```

I think I'm done adding languages (although adding only one might save some bytes in what I already have). I wonder if it's golfable though... 65 bytes for 15 languages is quite a jump from 32 bytes for 11 languages, and I've now got at least one useless character in there to make Foo work..

### Retina prints `1`

Try it online.

Luckily, the first line is a valid regex. However that regex obviously doesn't match the empty input, so the first stage (consisting of the first two lines) doesn't do anything.

The third line is on its own, so it's treated as a Match stage which, by default, counts the number of matches. However, the ``` is a separator which tells Retina that the part in front of it is a configuration string (it doesn't happen to know any of the options given there) and the part after it is the regex. So the regex is empty and Retina finds exactly one match.

### Starry prints `2`

Try it online.

Starry ignores everything except spaces and `+*,'`.`. Each command is one of those characters in conjunction with the spaces since the last of those characters. So let's remove all the extraneous code:

```
       + +'`. `

```

Seven spaces followed by `+` pushes a `2`. One space followed by a `+` duplicates it. `'` is a conditional jump. It pops the top of the stack, which is truthy (positive), so it jumps to the corresponding label (where labels are indicated by ``` and "corresponding" means "with the same number of leading spaces"), which is the first ```. `.` without spaces in front of it then prints the top of the stack as a number.

### Prelude prints `3`

Try it online.

This assumes the Python interpreter which uses numeric output. Let's remove all the no-ops:

```
# 5        ?         + +3    8   9
15 7  -- !   31

```

The first voice does a bunch of stuff, but nothing of it matters, because there is no `!` to print any of the results. The second voice pushes a `1`, then a `5`, then a `7`. We take the difference of the last two to get `-2`, and then subtract that from the `1` to get `3`. `!` prints it. The third voice has only no-ops.

### ETA prints `4`

Try it online.

ETA ignores everything except the characters `ETAOINSH` (in any case). So the code as seen by ETA is:

```
IaeeNTHneaSOeea

```

`I` tries to read input but can't, so it pushes `-1`. `a` pushes the current line number plus 1, which is `2`. `e` is *divmod*, which replaces those with `0` and `1` (or `-1`, I don't actually know, but it doesn't matter). The next `e` replaces both of them with `0`.

Now the interesting part. `NTHne` is a base-7 number literal. `N` and `e` are just the delimiters, and the three digits are `THN`. That is `54` (where `T` is digit `1`, `H` is `0` and `n` is `5`). `a` pushes `2` once more. `S` subtracts it, resulting in `52` and `O` outputs it as a character (`4`). Now `e` tries divmod again, but the stack contains two zeroes, so the program terminates with an error (but doesn't pollute STDOUT while doing so).

### Axo prints `5`

Try it online.

This language was pretty much single-handedly responsible for the rewrite. I couldn't have the `}` on the first line because it would block for input in Axo (see revision history for what I'm talking about). For Axo, only this part of the code is relevant:

```
#I5aeeNTH{\

```

Luckily, Axo also has implicit `0`s at the bottom of its stack, because `#` pops the top of the stack (to check if the next instruction should be skipped or not). The letters are all no-ops. Then `5` pushes a `5`, `{` prints it, `\` terminates the program. Quite simple, really.

### Labyrinth prints `6`

Try it online.

I'm truncating the code a bit, because the right half is never reached, and I'm also using `t` in place of `\t`, so that the columns line up correctly:

```
#I5aeeNTH{\
15}7'`--~!@
 teaww`

```

Now that letters, spaces and tabs are walls in Labyrinth, so the accessible code actually looks like this:

```
# 5      {\
15}7'`--~!@
      `

```

The instruction pointer will automatically follow that path. `#` pushes the depth of the main stack (`0`) and `15` turns it into a `15`. `}` moves it off to the auxiliary stack, and we're not going to use it any more. That conveniently makes the top of the stack zero, so that the IP does not turn left onto the `5`. `7` turns the zero into a `7`, `'` is a no-op. The ``` is unary negation, so we get `-7`. Now `-` subtracts the `-7` from the implicit `0` underneath making it `7`. This time, the IP does turn right to the ```, which is unary negation, so we get `7` again. The IP hits a dead end a turns around. The `-` does the same thing as before, so we get `7` once more. As the top of the stack is now positive, the IP turns right. There's another `-` which gives `-7` again. Then `~` is bitwise NOT, which gives `6` and `!` prints it. That's just the right moment to do so, because now the stack is empty again such that the IP won't turn left onto the `{` but instead continues straight ahead into the `@` which terminates the program.

### Hexagony prints `7`

Try it online.

The unfolded code looks like this:

```
     # I 5 a e
    e N T H { \
   ? + + 3 ; n @
  " 8 " e a 9 1 5
 } 7 ' - - ~ ! @ <
  " 3 1 " L S O e
   . e a w w . .
    . . . . . .
     . . . . .

```

Normally, that would be a terrifying Hexagony program, but the characters actually in use are not too many. In fact they are pretty much the same as those used by Labyrinth and I think the way I differentiate between `5` and `6` is quite nice. :)

The top row can basically be ignored. `#` would normally switch to a different IP, but the current memory edge is `0`, so it doesn't. The letters just set a fixed memory value, but we're not going to use it. After the end of the first row, control flow continues in the middle row (starting from the `}`, going right). The `}` moves to another memory edge. `7` sets that edge to `7`. `'` moves back to where we came from. `-` subtracts the memory edge we've just set to `7` from an unused memory edge (`0`), so we get `-7`. The next `-` does the same thing again, so it's a no-op. So far, quite similar to Labyrinth (apart from the memory layout). But now `~` is not bitwise NOT but unary negation in Hexagony. So this gives `7` instead of `6`. `!@`, like in Labyrinth prints the value and terminates the program.

### Foo prints `8`

Try it online.

As we all know since The Programming Language Quiz printing things is quite trivial in Foo, even if most of the code is a random jumble of characters. None of the characters affect the output except the `"8"` which prints `8`. Well, there is the `"31"` later on, but Foo terminates with an error at the end of the first line. I'm not exactly sure why that happens, but it requires that `3` (or any other digit) on the top row, which isn't used anywhere else.

### Brian & Chuck prints `9`

Try it online.

Let's do this thing again where we remove the third line (it's never parsed) and replace all irrelevant characters (i.e. no-ops, or cells that aren't read) with spaces:

```
         { ?         + +         9
  }   --   <        .

```

Just as a reminder, each line is a Brainfuck-like whose tape is the source code of the other program. Control flow starts on the first line (called Brian).

The `{` moves the tape head all the way to the left (where it already is), and `?` hands control flow over to Chuck (the second line). There, `}` moves the tape head to the right until it finds a zero cell. That doesn't happen until the end of the program, so the tape head ends up one cell after the `9`. `-` decrements that cell, but that's irrelevant. `<` moves the tape head onto the `9` and `.` prints it. Chuck runs out of program and terminates.

### Gol\>\<\> prints `10`

Tested here.

`#` is a mirror, so the IP immediately skips to the end of the first line (and goes left). The `9` can be ignored. `a` pushes `10`, `e` pushes `14`, `"8"` pushes the character code of `8`, `@` rotates the top three stack elements (pulling up the `10`), such that `n` prints the `10` and `;` terminates the program.

Thanks to Sp3000 for suggesting to use `@` instead of `!` (which saved a byte).

### evil prints `11`

*Thanks to Sp3000 for sending me some brute-forced command-lists to generate single-digit numbers.*

Try it online.

evil ignores everything except lower case letters so the code looks like this:

```
aeeneaeeaww

```

Also, `n` affects some state we don't care about so let's ignore that as well. Now `a` increments the register (which starts at `0`), and `e` is evil's magic "weave" operation which permutes the bits in a particular way. `aeeeaeea` happens to yield the value `49` which is the character code of `1`. `ww` prints it twice.

### Whitespace prints `12`

Try it online.

Okay, we know Whitespace only reads spaces, tabs and linefeeds, so let write the code as seen by Whitespace with `STL`:

```
SSSSSSTTSSLTLST

```

That's two commands:

```
SSSSSSTTSSL
TLST

```

The first one pushes the number `12`. Specifically, `SS` starts a number literal. The next `S` is the sign bit (positive). Then everything up to the `L` is a binary representation of the number. There's a ton of leading zeroes, which we need for Starry, but they don't affect the number. Then the `TTSS`s is `12` in binary. Fun fact: if I added a 16th language, I could save a byte here, because Starry could use the four `S` in the binary represtation of `16`. I doubt I will though...

The `TLST` just prints the top of the stack as a number. (`TL` marks the command as an I/O command, and `ST` is printing numbers.)

### Fission prints `13`

Try it online.

Fission only sees this part of the code:

```
           <"31"L

```

`L` starts control flow with a left-going atom. `"` toggles print mode, so that `31` just prints `13`. Then the atom is captured in the wedge of the `<`, which terminates the program.

### \>\<\> prints `14`

Tested here.

Distinguishing between \>\<\> and Gol\>\<\> isn't as easy as I thought, because Gol\>\<\> almost always does the same thing as \>\<\> for commands that exist in both, and commands that only exist in Gol\>\<\> cause \>\<\> to crash. However, `@` rotates the other way round in \>\<\>, such that it pushes down the `7` instead of pulling up the `10`, and then the `14` gets printed instead of the `10`.

### GolfScript prints `15`

Try it online.

This one is simplest: `#` comments out the first line. Then `15` pushes itself and `}` is a "super comment", which ignores the entire rest of the program. So the `15` is printed at the end of the program.
> 153 votes

# Answer
# Python 1.x, 2.x and 3.x, 32 bytes / 3^3 = 1.1851...

```
import sys
print(sys.version[0])

```

Prints the first number of the version, which is `1` in Python 1.x, `2` in Python 2.x and `3` in Python 3.x.

By the time we get Python 9.x my score will be a glorious `0.04389`!

:~)!
> 44 votes

# Answer
## 3 languages, 2 bytes / 27 = 0.074

```
1P

```

Well, it beats half the submissions at least :P

### 1. GolfScript

GolfScript ignores the `P`, outputting just the 1. Try it online.

### 2. Par

`P` is 2-to-the-power-of, so `1P = 2^1 = 2`. Try it online.

### 3. Seriously

`P` gives the nth prime, zero indexed. We get 3 since that's the second prime. Try it online.

---

### Notes

My inital goal was to find a valid answer in 1 byte. My first try was `\x12` which works in Bubblegum and gs2, but the challenge requires a minimum of three languages. `\x13` would work if there's a language in which that outputs 1.

Giving up on a 1 byte answer, I moved to two bytes. `3u` is a close call, outputting 1 in Japt, 3 in GolfScript and 4 in Seriously, but it was hard to find a language which outputted 2 to fill the gap.

All of this took me way too long :/
> 33 votes

# Answer
# 6 Languages - 44 bytes / 6^3 = 0.204...

Thanks to SnoringFrog for saving 10 bytes!

Works in:

* Befunge
* Pyth
* Brainfuck
* Hexagony
* Whitespace
* AniRad v0.2

---

```
2# "1",@"-[----->+<]>.*@@@!4<SSTST
T
ST
 >6=

```

***Note: Before trying it online, make sure to replace S with spaces and T with tabs, or convert the following hexdump to ASCII***

```
32 23 20 22 31 22 2c 40 22 2d 5b 2d 2d 2d 2d 2d 3e 2b 3c 5d 3e 2e 2a 40 40 40 21 34 3c 20 20 09 20 09 0d 0a 09 0d 0a 20 09 0d 0a 20 3e 36 3d

```

I am going to try to use more programming languages :)

### Befunge (prints `1`):

Try it online

```
2# "1",@"-[----->+<]>.*@@@!4<
2                             # This puts 2 onto the stack
 #                            # Skips the next op (the space)
   "1"                        # Sets the ASCII value of 1 onto the stack
      ,                       # Pop the last item (1)
       @                      # Terminate program

```

### Pyth (prints `2`):

Try it online

```
2# "1",@"-[----->+<]>.*@@@!4<
2                             # Prints 2
 #                            # Infinite while loop until an error occurs
   "1"                        # String
      ,@                      # This gives the error and terminates the program

```

### Brainfuck (prints `3`):

Try it online

```
2# "1",@"-[----->+<]>.*@@@!4<
2# "1",@"                     # Since these are not brainfuck ops, these will be ignored
         -[----->+<]>         # Puts "3" on the stack
                     .        # Prints the last item (3)

```

### Hexagony (prints `4`):

Try it online

```
2# "1",@"-[----->+<]>.*@@@!4<

```

A more readable version:

```
   2 # " 1       # The steps:
  " , @ " -      # 1 (2) - Hexagony starts at the top-left of the hexagon
 [ - - - - -     #       - This immediately puts 2 onto the stack
> + < ] > . *    # 2 (#) - Since the stack is 2, this makes the 2nd pointer the
 @ @ @ ! 4 <     #       - new current pointer
  > 6 = . .      # 3 (*) - The position of the 2nd pointer is in the left-most
   . . . .       #       - position. This sets the stack to the product
                         - of the two neighbours which is zero
                 # 4 (<) - Changes the pointer direction to west
                 # 5 (4) - Sets the stack to 4
                 # 6 (!) - Outputs the decimal 4
                 # 7 (@) - Terminates the program

```

### Whitespace (prints `5`):

Try it online

Since other characters are ignored but whitespaces and tabs, we are left with the following:

```
SSTST                 # This pushes 5 onto the stack
T                     #
ST                    # This prints the decimal

```

### AniRad version 0.2 (prints `6`):

Somehow this works for version 0.2, but gives an error for version 0.4. I have no clue why. You can find version 0.2 here. In order to run this, you can copy and paste the interpreter's code to repl.it and run it. After that, you only need to paste the program to STDIN and run it.

```
2# "1",@"-[----->+<]>.*@@@!4<      # (#)  Starts at the hashtag (starting point)
                                   #      Direction is down
                                   # (>)  When the pointer gets to the '>', it changes
 >6=                               #      its direction
                                   # (6) Puts 6 onto the stack
                                   # (=) Pushes the result and terminates

```
> 20 votes

# Answer
## JavaC++C, 363/27 = 13.4....

Java prints 1, C++ prints 2, C prints 3. Not breaking any records here (because Java), but I really like the clever, abusive way of making a polyglot in these languages that I discovered.

```
//\u000a/*
#include<stdio.h>
#ifdef __cplusplus
#define o "2"
#else
#define o "3"
#endif
int p(int a){printf(o);}
struct{int(*print)(int);}out;
//*/
/*\u002a/
import static java.lang.System.out;
public class P{//*/
/*\u002a/public static void//*/
main(/*\u002a/String[] args//*/
){//\u000a/*
out.print=p;
//\u002a/
out.print(1);}
/*\u002a/}//*/

```

This is a mess. Here's a breakdown of how it works. The Unicode literals (`\u000a`, otherwise known as a linefeed, and `\u002a`, otherwise known as `*`) are expanded by the Java compiler into their actual characters. So, here is what the Java compiler sees:

```
//
/*
#include<stdio.h>
#ifdef __cplusplus
#define o "2"
#else
#define o "3"
#endif
int p(int a){printf(o);}
struct{int(*print)(int);}out;
//*/
/**/
import static java.lang.System.out;
public class P{//*/
/**/public static void//*/
main(/**/String[] args//*/
){//
/*
out.print=p;
//*/
out.print(1);}
/**/}//*/

```

All that stuff in the beginning is ignored because it's all wrapped in a multi-line comment (`/* ... */`). Later on, we see that mixing single-line and multi-line comments allows us to control exactly which parts are commented out in each language. In the main method, we start a multi-line comment, and then have `//*/`. Ordinarily, this would be a single-line comment, but since we are in a multi-line comment, the `//` doesn't do anything, allowing the `*/` to close it.

This is the equivalent Java code, with comments removed:

```
import static java.lang.System.out;
public class P{
public static void
main(String[] args
){
out.print(1);}
}

```

Here is what the C/C++ compiler sees (I've removed the Unicode literals, since they are not expanded by the compiler and thus don't do anything):

```
///*
#include<stdio.h>
#ifdef __cplusplus
#define o "2"
#else
#define o "3"
#endif
int p(int a){printf(o);}
struct{int(*print)(int);}out;
//*/
/*/
import static java.lang.System.out;
public class P{//*/
/*/public static void//*/
main(/*/String[] args//*/
){//\/*
out.print=p;
///
out.print(1);}
/*/}//*/

```

Here, the single-line comments override the multi-line comment delimiters in the beginning, so all of the `#define`s and the `#include` get preprocessed. Next, multi-line comments are used to comment out the boiletplate code for Java. This is the equivalent code, with comments removed:

```
#include<stdio.h>
#ifdef __cplusplus
#define o "2"
#else
#define o "3"
#endif
int p(int a){printf(o);}
struct{int(*print)(int);}out;
main(
){
out.print=p;
out.print(1);}

```

A standard C/C++ polyglot trick (the `#ifdef __cplusplus`) is utilized to define a token `o` as either `"2"` or `"3"`, depending on if it's a C++ or a C compiler that is compiling the code. Next, we define a funtion `p` that takes a single (ignored) `int` argument and calls `printf`, using our newly-defined `o` token. As per usual, the return value is left out, since we're not in strict mode. Next, we define a `struct` with a single member, a function pointer whose signature matches `p`'s, and construct a single instance named `out`. In the main method (we leave off the `int` as usual), the address of `p` is assigned to `out.print` (so calling `out.print` calls `p`), and it is called.

If C++ wasn't included in the languages, we could drop all of the preprocessor code, and define `p` as `int p(int a){puts("2");}`. Unfortunately, C++ requires an `#include` to do I/O. If C wasn't included, we could drop the definition of `p` and the `#ifdef` preprocessor macro, and directly define a member function in the `struct` instead of needing a function pointer. Unfortunately, C does not support member functions.
> 14 votes

# Answer
## 4 languages, 28 bytes / 64 = 0.4375

```
print((0 and 3^1or 1/2>0)+1)

```

### 1. Python 2

`0` is falsy and `/` is integer division, so

```
(0 and 3^1 or 1/2 > 0) + 1 = (1/2 > 0) + 1 = (0 > 0) + 1 = False + 1 = 1

```

### 2. Perl (also Python 3)

`0` is falsy and `/` is float division, so

```
(0 and 3^1 or 1/2 > 0) + 1 = (1/2 > 0) + 1 = (0.5 > 0) + 1 = 1 + 1 = 2

```

### 3. Ruby

`0` is truthy and `^` is bitwise xor, so

```
(0 and 3^1 or 1/2 > 0) + 1 = xor(3,1) + 1 = 2 + 1 = 3

```

### 4. Lua

`0` is truthy and `^` is exponentiation, so

```
(0 and 3^1 or 1/2 > 0) + 1 = pow(3,1) + 1 = 3 + 1 = 4

```

Note that Lua and Ruby can't add booleans as though they are integers, hence the grouping of them together. Unfortunately `0and` doesn't work in Lua, so we can't save a byte there.

---

**Previous 17 byte version which prints 1 (Lua), 2 (Ruby), 3 (Python/Perl):**

```
print(2^(0 or 1))

```

-3 bytes thanks to @xnor for this version, making it a lot neater :)
> 14 votes

# Answer
# ~~6~~ 7 languages, ~~32~~ 37 bytes, score ~~0.148...~~ 37/73 ≈ 0.107872...

```
#7+!"@\"6.@;n5
print(4--int(-3/2)#"
)

```

### Brainfuck-ng

`+` increments current cell, `!` prints as integer, `@` exits. `#` and `"` are NOPs.

### Python 2

First line is comment. Using integer division, calculates `4 - -int(-3 / 2) = 4 - -int(-2) = 4 - -(-2) = 4 - 2 = 2` and prints the result.

### Python 3

Same as previous, but with float division. `4 - -int(-3 / 2) = 4 - -int(-1.5) = 4 - -(-1) = 4 - 1 = 3`.

### Lua

`--` starts a comment, and `#` on the first line is a comment, so basically `print(4)`.

### \>\<\>

`#` reflects IP, `5` pushes 5, `n` prints a number and `;` quits.

### Befunge

`#` skips over the `+`, `!` logically negates the top of the stack, `"@\"` pushes the string `@\`, `6` pushes 6, `.` prints a number and `@` quits.

### Pyth

`#` starts an infinite loop, dismissing any errors. `7` prints 7, then follows `+!"string")` which basically causes an error for not having two operands for `+`, terminating the program.
> 13 votes

# Answer
# 14 languages, 73 bytes, score = (73/14^3) = 0.02660349854

```
#Y2(3`5n~thneo e        ;n@0d c
#   -[>+<"9"L-----]>+.
14
print(int(15/2))+3

```

I can add some more langs, but I think I'll add what I have here.

## 1. Brainbool ; Try it online!

The relevant code:

```
    [>+<         ]>+.

               +

```

This is really just `+.+`, which outputs 1.

## 2. Jolf ; Try it here!

The `(` char stops interpreting the source code, so the relavent code is:

```
#Y2

```

This is equivalent to (in JavaScript)

```
var Y = []; toHex(Y); alert(2);

```

Which outputs 2.

## 3. Element ; Try it online!

The relevant code:

```
    3`

```

This captures `3` and prints it.

## 4. Brainfuck ; Try it online!

The relevant code is:

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

  -    -      +

```

Which is the standard way of generating 4's char code and outputting it, and some other stuff after it.

## 5. Reng ; Try it here!

`~` terminates the program, so the relevant code here is:

```
#Y2(3`5n~

```

`#` redefines `Y` to be the TOS, in this case, `0`. `2` pushes 2; `(` rotates the stack N times, popping N from the stack; `3`` pushes -3; and finally, `5n` prints `5`.

## 6. ETA ; Try it online!

ETA only reads the letters E, T, A, O, I, N, S, H, so the code only executed is this:

```
       n thneo e         n

  int int

```

Super-relevant code:

```
       n thneo

```

Or, equivalently: `nthne o`. `n...e` is a base-7 literal, and `thn` is the base-7 number for 54. `o` outputs this character. The submission errors out, but I don't know why.

## 7. Python 3

What it sees:

```
# comment
# comment
14
print(int(15/2))+3

```

`15/2` yields 7.5, as `/` is float division. `int(...)` makes the number an int, which is then printed. The program errors out when `+3` is encountered.

## 8. Julia

Julia sees:

```
# comment
# comment
14
print(int(15/2))+3

```

Instead of truncating 15/2, Julia rounds it up, yielding 8. It prints this, then errors out on encountering +3.

## 9. Fission ; Try it online!

Relevant code:

```
        <"9"L

```

I got this idea from Martin's Fission portion (more like stole it). `L` begins a left-facing thing, captures `9`, and ends with `<`.

## 10. Whitespace ; Try it here!

The relevant code, translating spaces into `S` and tabs into `T`:

```
SSSTSTS
T
ST

```

It pushes 10 to the stack and outputs it as a number (`T\nST`).

## 11. Python 2

Python 2 sees this:

```
# comment
# comment
14
print(int(15/2))+3

```

`(int(15/2))+3` is evaluated to be 11, and that's printed.

## 12. Gol\>\<\> ; Try it here!

Relevant code:

```
#                      ;n@0d c

```

This uses the trick used in Martin's answer that `@` rotates different directions in \>\<\> and Gol\>\<\>. `#` mirrors, `c` pushes 12, `d` pushes 13, `0` pushes 0, and `@` brings `c` to the top of the stack, then being outted and printed with `;n`.

## 13. \>\<\> ; Try it online!

Relevant code:

```
#                      ;n@0d c

```

Again using that `@` rotates different directions in \>\<\> and Gol\>\<\>. `#` mirrors, `c` pushes 12, `d` pushes 13, `0` pushes 0, and `@` brings `d` to the top of the stack, then being outted and printed with `;n`.

## 14. Golfscript ; Try it online!

What it sees:

```
# comment
# comment
    14
print(-int(-15/2))+3

```

It pushes `14`, `print`s it, and errors. ~~Stolen~~ inspired by Sp3000's answer.
> 9 votes

# Answer
## BFSRS\>\<\>funge93thon123, 73/343 ≈ 0.212827...

Brainfuck, Seriously, \>\<\>, Befunge-93, Python 1, Python 2, Python 3

```
# 4['.]@kX21z-[>+<-----]>--.<;n3
import sys;print(3+int(sys.version[0]))

```

Contains unprintables, hexdump (reversible with `xxd -ps -r`):

```
2320345b272e5d406b5832317a7f2d5b3e2b3c2d2d2d2d2d5d3e2d2d2e3c
3b6e330a696d706f7274207379733b7072696e7428332b696e7428737973
2e76657273696f6e5b305d2929

```

I'll be adding more languages (and probably bytes) over time. Languages in the header are listed in order of what they print. Assumes 8-bit wrapping cells and a tape that won't complain about going left of the initial position (wrapping or infinite) for Brainfuck.

Brainfuck:

```
[.]   initial value of first cell is 0, so loop is skipped
-[>+<-----]>--  push 49 (ASCII ordinal of 1)
.     print "1"
<     move to blank cell
[0]   skip loop because cell is 0
      everything else is ignored

```

Seriously:

```
# 4['.]@  does some stuff we don't care about
kX        pop entire stack, push as list, discard (essentially the same as é, but is ASCII so we can use Python)
2         push 2
1z        pop 1 item from stack and print (used instead of . so Brainfuck doesn't print here; same as ü in this scenario, but is ASCII so we can use Python)
0x7f      terminate program
          everything else is ignored

```

`><>`:

```
#    mirror, reverse direction
3n;  push 3, print "3", end (reversed because IP is scanning RTL at this point)
     everything else is ignored

```

Befunge-93:

```
#     jump over the space
4['.] push 4, print 4 (brackets and ' do nothing)
@     end program
      everything else is ignored

```

Python 1 (thanks muddyfish):

```
# 4['.]@kX21z-[>+<-----]>--.<;n3         comment; ignored
import sys;print(4+int(sys.version[0]))  prints 4+1=5

```

Python 2:

```
# 4['.]@kX21z-[>+<-----]>--.<;n3         comment; ignored
import sys;print(4+int(sys.version[0]))  prints 4+2=6

```

Python 3:

```
# 4['.]@kX21z-[>+<-----]>--.<;n3         comment; ignored
import sys;print(4+int(sys.version[0]))  prints 4+3=7

```
> 8 votes

# Answer
# 4 Languages (Befunge-93, Microscript II, Microscript, and Foo), score 7/64=0.109

```
"4"1.@2

```

Befunge: Push 4, push 1, print 1, and terminate.

Microscript II: Produce the string "4", discard it, take the square root of one, discard that, and finally set x to 2. This is then printed implicitly.

Microscript: Push 52 to the stack (which will never actually be used for the remainder of the program), increment the register (initially zero) by one, then increment the register by two. This is then printed implicitly.

Foo: Print the string "4", then push 2
> 8 votes

# Answer
## 7 languages, 287 / 7^3 = 0.836

~~Probably the lowest score that gets in, anyway I like this 3 versions of C polyglot.~~

Added the boring Python solution to at least qualify for the "3 unique" languages bounty.

Added Java by abusing C trigraphs for different comment intepretations.

Works in:

* Python 1
* Python 2
* Python 3
* C89
* C99
* C++
* Java

golfed version:

```
/*
*??/
/
#include <stdio.h>
#ifndef __cplusplus
#define true 8/*
import sys
print(sys.version[0])
'''
#*??/
/
#endif
int main(){int a=(true>1)?-6:3;printf("%d",(true//*
+a
//**??/
/+2));}
#define a \
'''
/**\u002f
public class p{public static void main(){System.out.println("7");}}
/**/

```

Ungolfed:

```
/*
*??/
/

#include <stdio.h>

#ifndef __cplusplus
#define true 8/*

import sys
print(sys.version[0])
'''
#*??/
/
#endif

int main()
{
    int a = (true > 1) ? -6 : 3;
    printf ("%d", (true//*
    +a
    //**??/
/
    +2));
}
#define a \
'''

/**\u002f
public class p
{
    public static void main()
    {
        System.out.println("7");
    }
}
/**/

```

Ok this is probably getting kinda weired and I hope my english skills are good enough to explain it ordinary.

First of all I'll explain the different kinds of comments I used to encapsulate the language structures each for its own.

So lets take the first block:

```
/*
*??/
/

```

For Java this is just the beginning of an multi line comment. But... in C99/89/++ this evaluates to

```
/*
*/

```

Since `??/` is a trigraph for `\` while in C the `\` character is kind of consistent and even consumes line breaks in its commandfunctionality. This causes the result of an `\n` to be just "displayed" instead of beeing line breaks. that means, given this byte array representing the first block: \[`/`\]\[`*`\]\[`\n`\]\[`*`\]\[`?`\]\[`?`\]\[`/`\]\[`\n`\]\[`/`\] would be after trigraph evaluation: \[`/`\]\[`*`\]\[`\n`\]\[`*`\]\[`\`\]\[`\n`\]\[`/`\] Where the consistent functionality of the `\` triggers and "consumes" the `\n` so the remaining and finaly in C langs evaluated bytes are: \[`/`\]\[`*`\]\[`\n`\]\[`*`\]\[`/`\]

But about all this java doesn't know anything and treats all that follows as an comment untill this trick gets reverted.

(to be continued!)
> 7 votes

# Answer
# Subskin, Brainfuck and Fob 27 bytes / 3^3 = 1

```
0#>&$3#<>$-[----->+<]>-.
31

```

### Subskin

```
0
31

```

We set the instruction pointer (doesn't matter here) to `0` and the output register to `31`. If the contents of the output register is `>= 0`, we output the contained value as a `char`. All other code is ignored.

### Brainfuck

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

```

Puts `3` in the register, decrements the value once with `-` and finally outputs with `.`.

### Fob

```
#>&$3#<>$

```

This is a little bit more tricky, since Brainfuck also reads the `<` and `>` instructions in Fob. We enter execution mode with `#` and increment Brainfuck's pointer by one which makes it easier on us later. We have nothing to execute yet, so nothing is executed.

We enter the accumulator mode with `$`, throw in a `3`, enter execution mode again, push the accumulator contents to the stack with `<` and finally we output the content with `>`.

To prevent Brainfuck from screwing with the program we enter accumulation mode again with `$`.
> 6 votes

# Answer
## 7 Languages, 55 / 7^3 ≈ 0.16035

Runs in PowerShell v1, v2, v3, v4, and v5, Foo, and Pyth

```
#7.q"6""
$p=$PSVersionTable;($p.PSVersion.Major,1)[!$p]

```

Digits 1-5 use similar logic to sweerpotato's answer. The `$PSVersionTable` special variable was introduced in PowerShell v2, and contains a full build list, revisions, etc. Here's an example output of the variable:

```
PS C:\Tools\Scripts> $PSVersionTable

Name                           Value
----                           -----
PSVersion                      4.0
WSManStackVersion              3.0
SerializationVersion           1.1.0.1
CLRVersion                     4.0.30319.34209
BuildVersion                   6.3.9600.17400
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0}
PSRemotingProtocolVersion      2.2

```

In this code, we first store it into `$p` so that the code length is shorter. Then, we check for its existence by leveraging the variable as an index into a two-item array:

* If the variable doesn't exist, PowerShell will dynamically create it and assign it `$NULL`, the `!` of which is `$TRUE`, or `1`, which corresponds to the second element in the array, which outputs `1`.
* If the variable does exist (as is the case in v2+), then the `!` of the variable results in `$FALSE` or `0`, which indexes to the first element, which outputs the version number.

Using Foo for 6, we leverage that `#` is a comment in PowerShell, so that's ignored when executing it in a PS environment. However, Foo will happily spit out the number `6` and then proceed through the rest of the program, which does nothing.

Using Pyth for 7, we return `7`, then immediately quit with `.q`, so the infinite while-true loop that started with `#` doesn't matter. Since we have something left that gets implicitly printed. Thanks to @FryAmTheEggman for this addition.

Edit - Golfed a handful of bytes thanks to Mauris Edit - clarified Pyth explanation thanks to Sp3000
> 6 votes

# Answer
# Python 3, Ruby, Perl, C, C++, Objective-C 202 bytes / 6^3 = 0.935...

This was quite fun actually, and a lot of playing with booleans.

You can all versions of the code at the following site, by copy-and-pasting the code into the interpreter.

```
#include <stdio.h> /*
print ((("0"+"0"==0)and 3) or (0and 2or 1));
__DATA__ = 1
"""""
*/
int main(){putchar(
#ifdef __OBJC__
'6'
#else
#ifdef __cplusplus
'5'
#else
'4'
#endif
#endif
);return 0;}/*
"""
#*/

```

### Python 3, prints `1`

The trick is the following:

```
print ((("0"+"0"==0)and 3) or (0and 2or 1));

```

This will print `1`

### Ruby, prints `2`

The interpreted code for Ruby is:

```
print ((("0"+"0"==0)and 3) or (0and 2or 1));

```

So this prints `2`

### Perl, prints `3`

The interpreted code for Perl is:

```
print ((("0"+"0"==0)and 3) or (0and 2or 1));
__DATA__ = 1

```

First of all, the `__DATA__` token tells the Perl compiler that the compilation is finished. Everything after is ignored.

```
print ((("0"+"0"==0)and 3) or (0and 2or 1));

```

And prints `3`

### C, prints `4`

The interpreted code is quite different from the others:

```
#include <stdio.h>
int main(){putchar(
#ifdef __OBJC__
'6'
#else
#ifdef __cplusplus
'5'
#else
'4'
#endif
#endif
);return 0;}

```

This will simply print the char `4`.

### C++, prints `5`

The same as the C code

This will print the char `5`.

### Objective-C, prints `6`

The same as the C code

This will print the char `6`.
> 6 votes

# Answer
## Python 1|2|3, 27 bytes / 27 = 1

```
print(len("\xabc")+(1/2>0))

```

@sweerpotato's use of version numbers made me wonder whether it was possible to distinguish the Pythons in less. Here's the best I've found.

### Explanation

To distinguish Python 3 from the earlier versions, we make use of the standard integer division vs. floating point division trick. `(1/2>0) == (0>0)` returns 0 pre-Python 2.3 or `False` from Python 2.3 onwards, and `(1/2>0) == (0.5>0)` returns `True` for Python 3.

To distinguish Python 1 from the rest, we take the length of the string `"\xabc"`, which is length one in Python 1 and length two from Python 2 onwards. Why? Because

> The \x escape in string literals now takes exactly 2 hex digits. Previously it would consume all the hex digits following the ‘x’ and take the lowest 8 bits of the result, so \x123456 was equivalent to \x56.

(From What's New in Python 2.0)
> 6 votes

# Answer
# Craneflak, Brain-Flak Classic, Rain-Flak, BrainHack, Brain-Flueue, miniflak, miniHack: .1020

```
(([]()()()<()()()>)()()){}#{}({}())

```

Try it online!

## Explanation

The first thing going on here is that there is a difference in the way comments are read between the BrainHack, CraneFlak and Rain-Flak interpreters. Craneflak has no comments, in Rain-Flak `#` comments out the rest of the line and in BrainHack `#{...}` comments out the insides.

So here's what each language reads:

```
Rain-Flak: (([]()()()<()()()>)()()){}         -> 3
BrainHack: (([]()()()<()()()>)()()){}({}())   -> 4
Craneflak: (([]()()()<()()()>)()()){}{}({}()) -> 1

```

The next thing is the difference between the brain-flaks and the miniflaks. Both Rain-Flak and BrainHack support miniflak, where all of the extra operations are simply removed. This means that they lose the `[]` and `<...>`

```
Rain-Flak: (()()()()()())         -> 6
BrainHack: (()()()()()())({}())   -> 7

```

Next we have the difference between Brain-Flak and Brain-Flak Classic. In Classic `[]` is `-1` instead of the stack height, which means that our result is 1 less than in regular Rain-Flak, making it 2.

Lastly we have the difference between brain-Flak and brain-flueue. In brain-flueue a queue is used instead of a stack. Normally brain-flak pushes 3 then 5 and pops the 5 away, however in brain-flueue the pop gets rid of the 3 and not the 5.
> 6 votes

# Answer
# 6 Languages, 38 / 6^3 = 0.17592̅5̅9̅

### Whitespace, Brainfuck, Ruby, Labyrinth, Foo, Seriously

Legend:

`£`: tab

: space

`§`: 0x7f

```
puts•2;#4!@•-[>+<-----]>6.§"5"•£
£
•£

```

This contains unprintable characters, so here's the hexdump:

`7075747320323b23342140202d5b3e2b3c2d2d2d2d2d5d3e362e7f22352220090a090a20090a`

## Explanation:

### Whitespace

Try it online. (Note: my program omits the closing three linefeeds to terminate the program, I wrote/tested this on Whitelips and that produces the proper output there, but does not on Try It Online, so the linked program has those two characters added. As far as I can tell, some interpreters let you do that, others get stuck in an infinite loop without the explicit termination)

(omitting ignored characters)

`space``space``space``tab``enter`: push a 1 onto the stack

`tab``enter``space``tab`: output the top of the stack

### Ruby

Shouldn't need explaining. Prints 2, treats the rest of that line (ergo, the brainfuck program) as a comment, treats the rest of the file as empty.

### Brainfuck

Try it online.

Requires an interpreter that supports underflow. Underflows the first cell to 255 then uses that for a loop counter to generate 51, which is the ascii code for 3.

### Labyrinth

Try it online.

(omitting the last two lines for legibility because they are never reached)

```
puts•2;#4!@ -[>+<-----]>6.§"5"•£
puts•                            skipped
     2                           push 2 onto stack
      ;                          pop 2 from stack
       #                         push current stack depth (0) to stack
        4                        push 4 to stack
         !                       print top of stack as integer
          @                      program terminates

```

### Foo

Try it online.

The only thing that affects output is "5", which prints 5.

### Seriously

Try it online.

```
puts•2;#4!@ -[>+<-----]>6.§"5"•£
puts•2;#4!@ -[>+<-----]>           assorted stack manipulation that doesn't affect this program
                        6          push 6 to the stack
                         .         output top of the stack
                          §        (0x7f) terminate program

```
> 5 votes

# Answer
# 5 languages, Chaîne, Minkolang, Foo, Brainf\**k-ng, and Vitsy, 21 / 5^3 = 0.168

```
2|<«+!@"3".N+m

5N»

```

# Brainf\**k-ng

```
2|<«+!@"3".N+m

5N»
  <            go left (should still be ok)
    +!         output 1
      @        halt execution

```

# Chaîne

```
2|<«+!@"3".N+m

5N»
2              «add 2 to the current string»
 |<            «take off and put on the string (no op)»
   «           «comment»

  »
               «implicit output»

```

# Foo

```
2|<«+!@"3".N+m

5N»
       "3"     print three

```

# Minkolang

```
2|<«+!@"3".N+m

5N»
2              C push 2 to the stack [2] C
 |             C mirror C
2              C push 2 to the stack [2,2] C
             m C ignored C
            +  C add top two [4] C
           N   C output C
          .    C terminate program C

```

# Vitsy

```
2|<«+!@"3".N+m

5N»
2              push 2
 |             mirror
2              push 2
             m pop 2, goto line 2
5              push 5
 N             output 5
  »            ignored

```

---

I can probably add \>\<\> or something.
> 5 votes

# Answer
# Milky Way 1.0.2, CJam and STXTRM, 20 bytes / 3^3 = 0.741

I imagine there is at least one other language that I could add.

```
'2"3""1"1<<1>;;"2"3;

```

---

## Explanation

---

### Milky Way, `1`

In Milky Way, strings are only denoted by pairs of double quotes. A single quote reads input from the command line; if there is none, it pushes an empty string. Greater than and less than signs will rotate the entire stack rightward and leftward, respectively. Finally, a semicolon swaps the top two stack elements.

Here is a stack visualization (stack shown is the result of the listed operation after it has occurred):

```
["", 0]                                             #  default stack

["", 0, ""]                                 #   '   #  read input from command line
["", 0, "", 2]                              #   2   #  push 2 to the stack
["", 0, "", 2, "3"]                         #  "3"  #  push "3" to the stack
["", 0, "", 2, "3", "1"]                    #  "1"  #  push "1" to the stack
["", 0, "", 2, "3", "1", 1]                 #   1   #  push 1 to the stack
[0, "", 2, "3", "1", 1, ""]                 #   <   #  rotate the stack leftwards
["", 2, "3", "1", 1, "", 0]                 #   <   #  rotate the stack leftwards
["", 2, "3", "1", 1, "", 0, 1]              #   1   #  push 1 to the stack
[1, "", 2, "3", "1", 1, "", 0]              #   >   #  rotate the stack rightward
[1, "", 2, "3", "1", 1, 0, ""]              #   ;   #  swap the top two stack elements
[1, "", 2, "3", "1", 1, "", 0]              #   ;   #  swap the top two stack elements
[1, "", 2, "3", "1", 1, "", 0, "", 2]       #  "2"  #  push 2 to the stack
[1, "", 2, "3", "1", 1, "", 0, "", 2, "3"]  #   3   #  push "3" to the stack
[1, "", 2, "3", "1", 1, "", 0, "", "3", 2]  #   ;   #  swap the top two stack elements

```

---

### CJam, `2`

In CJam, strings are also denoted by double quote pairs. A single quote pushes the character code of the following character. When a character code is output, it is output as its corresponding character. Greater-than and less-than signs act as expected, evaluating the order of the top two stack elements. Finally, a semicolon discards the top stack element. On termination of the program, the contents of the stack are output.

Here is a stack visualization (stack shown is the result of the listed operation after it has occurred):

```
[]                         #  default stack

['2]               #  '2   #  push the character code of "2" to the stack
['2, "3"]          #  "3"  #  push "3" to the stack
['2, "3", "1"]     #  "1"  #  push "1" to the stack
['2, "3", "1", 1]  #   1   #  push 1 to the stack
['2, "3", "1"]     #   <   #  leave the greater of the top two stack elements on the stack
['2, 0]            #   <   #  leave the greater of the top two stack elements on the stack
['2, 0, 1]         #   1   #  push 1 to the stack
['2, 1]            #   >   #  leave the lesser of the top two stack elements on the stack
['2]               #   ;   #  pop the top stack value
[]                 #   ;   #  pop the top stack value
['2]               #  "2"  #  push the character code of "2" to the stack
['2, "3"]          #   3   #  push "3" to the stack
['2]               #   ;   #  pop the top stack item

```

---

### STXTRM, `3`

In MSM, anything that is not an operator is pushed to the stack as a character. A semicolon duplicates the top stack element. The program continues until there are no more operators, or there is a single element on the stack.

The final character on the stack is `3`, which is duplicated by the final operator. `3` is the topmost element at the end of the program, so it is output.
> 4 votes

# Answer
# 5 Languages, 18 bytes / 5^3 = 0.144

Runs in Brainbool, Mathematica, Foo, \>\<\> and Befunge-93.

```
4!<n;+Print@2"3".5

```

### Brainbool

Brainbool is like Brainfuck, but it operates only on bits, and its input and output consists solely of `0` and `1`.

```
4!<n;+Print@2"3".5
  <                   move the pointer to the left
     +                logic not
                .     print the current cell

```

### Mathematica

In Mathematica, everything is an expression and has a value. `Print@2` prints `2` and returns the symbol `Null`. After that, the code does some symbolic calculations, but doesn't print anything.

### Foo

`"3"` prints 3. I don't know what the other parts do.

### \>\<\>

```
4!<n;+Print@2"3".5
4                     push 4
 !                    skip the next command
   n                  pop and print it as a number
    ;                 end the program

```

### Befunge

```
4!<n;+Print@2"3".5
4                     push 4
 !                    logical not
  <                   makes the program counter travel to the right
 !                    logical not
4                     push 4
                 5    push 5
                .     pop and print it as a number
             "3"      push the string "3"
            2         push 2
           @          end the program

```

---

~~12 Languages, 35 bytes / 12^3 = 0.0202546... Using sweerpotato's trick, cheap but powerful.
Runs in Brainbool, Mathematica 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0 and 10.0, Foo and \>\<\>.
```
cn;+"11".Print@Floor@$VersionNumber

```~~
> 4 votes

# Answer
# 5 languages, 18 bytes / 5^3 = 0.144

**Ouroboros, Pip, QBasic, Foo, and Pyth**

```
5'"4"()"
1?3'@n()2

```

### 1. Ouroboros

Each line of the program represents a snake eating its tail.

**Snake 1**

Push `5`, `'` is a no-op, push `52` (ASCII code of `"4"`). `(` causes the snake to pop a number and eat that many characters of its tail. Since this results in swallowing the instruction pointer (and the entire snake), execution halts.

**Snake 2**

Push `1`, push a random number (`?`), push `3`, `'` is a no-op. `@` rotates the `1` to the top of the stack and `n` outputs it as a number, leaving the `3` on top of the stack. Then `(` eats this many characters from the end of the snake, swallowing the instruction pointer and halting.

You can run this program online in the Stack Snippet interpreter here.

### 2. Pip

Most of the program consists of expressions which are evaluated and discarded:

* `5`
* `'"` (character literal)
* `4`
* `"()"`
* `1?3'@` (ternary expression)
* `n` (variable, = newline)
* `()` (nil)

Finally, the last expression, `2`, is printed.

### 3. QBasic

Everything after `'` is a comment. The first line thus boils down to `5`, a line number. On the second line, `1` is a line number and `?3` is a shortcut for `PRINT 3`.

(Apparently having line numbers out of order isn't a problem, though it would be easy to fix if it were.)

### 4. Foo

Almost everything is no-ops. `"4"` prints `4`. The parentheses (x2) are a loop that runs until the current array cell is zero, which is true immediately and the loop exits. `@`, when not followed by a number, takes the value of the current array cell (initialized to 0) and pushes it to the stack.

I'm not entirely sure how the second, unmatched `"` is supposed to be handled. The online version seems to add a newline to the output, which the rules of the challenge allow.

### 5. Pyth

`5` is output. Then the program encounters `'"4"`, which tries to read from a file named `4`. As long as no such file exists, I think this should terminate the program with an error. (The online version says `name 'open' is not defined`--I assume because opening files isn't allowed online.)

The stray `"` at the end of line 1 ensures that line 2 doesn't cause a syntax error before execution.
> 4 votes

# Answer
## 4 languages, 24 bytes, 24/4^3=0.375

```
print(1//0.5--1+1/2*2
);

```

## 1. PHP

PHP executes `print(1);` which equals 1

## 2. Lua

Lua executes `print(1//0.5);` which equals 2

## 3. Python 2

Python 2 executes `print(1//0.5--1+1/2*2);` which equals 3 (integer division)

## 4. Python 3

Python 3 executes `print(1//0.5--1+1/2*2);` which equals 4 (float division)
> 4 votes

# Answer
# Brainfuck-ng, Foo, \>\<\>, 9 bytes / 3^3 = 0.333...

```
#+!"2";n3

```

### Brainfuck-ng

The only characters it recognizes are `+` and `!`:

```
+ Increment cell by one
! Print as integer

```

Prints `1`

### Foo

Prints everything in quotes.

```
"2"

```

Prints `2`

### \>\<\>

`#` Mirrors the point to the left, `3` pushes *3* to the stack, `n` outputs it as an integer, `;` stops the program.

```
#      ;n3

```
> 3 votes

# Answer
# Alphapolyglot, 8 languages, 37 bytes, score 0.072265625

```
8
"6";;7iiiio hkaeeeaeaeawxzz ax zaCM

```

Features AlphaBeta, Beatnik, Commentator, Deadfish~, evil, Foo, Golfscript, and Husk. Thanks to Leo for helping with Husk.

## Explanation

### AlphaBeta

```
8"6";;7iiiio hkaeeeaeaeawxzz a       # Garbage
                              x z    # Clear register 1 and 3
                                 a   # Add 1 to register 1
                                  C  # Set register 3 to register 1
                                   M # Output register 3 as a number

```

### Beatnik

`iiiio hkaeeeaeaeawxzz ax zaCM` is `5 50 9 17`.

`5 50` pushes 50 (2 in ASCII) `9` outputs the top of the stack as a character. `17` exits the program.

### Commentator

There are 3 spaces in the program, each one increments the active accumulator.

### Deadfish~

```
8"6";;7iiii                          # Increment 4 times
           o                         # Output as a number
             h                       # End program
              kaeeeaeaeawxzz ax zaCM # Garbage

```

### evil

```
8"6";;7iiiio hk                      # Garbage
               aeeeaeaea             # Increment and weave the accumulator to 53 (5 in ASCII)
                        w            # Output accumulator as a character
                         xzz ax zaCM # More garbage

```

### Foo

```
8                                    # Garbage
 "6"                                 # Output 6
    ;;7iiiio hkaeeeaeaeawxzz ax zaCM # Garbage

```

### Golfscript

```
8                                    # Push 8
 "6"                                 # Push the string 6
    ;;                               # Pop and discard twice
      7                              # Push 7
       iiiio hkaeeeaeaeawxzz ax zaCM # Garbage

```

### Husk

The first line is executed first.

```
8 # Return 8

```

The second line isn't executed.
> 3 votes

# Answer
# 3 Languages, ~~82~~ 83 / 3^3 = 3.074...

Works in ???, Whitespace, and Beatnik. Or rather, it *should* work in those languages but I am not going to be able to test them for a few days. Anyway, here is the code:

```
K... Jax... Jy... Jy...   ...
My...    My...
... ...     ......................XO!

```

**1. *???***

```
.................................................!

```

??? is basically brainfuck but it uses common punctuation as commands instead of the traditional characters. `.` increments the current memory cell, which is done 49 times. `!` takes the current memory cell and prints it as a character, here `1`.

**2. *Whitespace***

```
[Space][Space][Space][Tab][Line Feed]
[Tab][Line Feed]
[Space][Tab]

```

Whitespace is a language that ignores all non-whitespace characters. Here I've converted it to an easily readable form. The first line pushes `2` onto the stack, and the second two lines print the top of the stack as a number, here `2`.
Note that in the combined code, I have substituted tabs with four spaces due to technical limitations.

**3. *Beatnik***

```
K Jax
Jy Jy
My My
XO

```

Beatnik is a language where each word is converted to its Scrabble score, then those scores are interpreted as commands. The first line pushes `17` onto the stack. The second line duplicates the top of the stack twice and the third line adds the top to elements of the stack together twice, effectively tripling `17` into `51`. The last line prints the character on the top of the stack, here `3`.
Note that I am using Beatnik at Face Value, assuming there is not an error in the original Beatnik specification. Also note that I am using the North American English Scrabble scoring system.

If it is not clear by now, each of these languages only accepts a certain type of character (punctuation, whitespace, and letters, respectively) so writing this polyglot was as easy as writing the individual programs. The only real "trick" is using the Whitespace code to separate the words from Beatnik. Beyond that, the individual programs do not overlap whatsoever.
> 2 votes

# Answer
## 5 languages, 175 / 5^3 = 1.4

I decided to post a different answer since the bounty is changing the requirements in a way that made me feel unsaitsfyed with my first answer (but which is still satisfying me in the way of the generall challange!)

So here is my solution that qualifys for the bounty challange:

It compiles in

* C99
* objC90
* C++0x
* Ruby
* Perl

```
#if __cplusplus
#define x\
=begin\
=pod
#endif
int a=
#ifndef x
1//**/
+1
#else
3
#endif
;int main(){printf("%d",a);}
#ifdef f
=end
puts 5;
=begin
=cut
print"4";
=end
#endif

```
> 2 votes

# Answer
# 3 languages, 15 bytes, score 0.555...

Gonna add more languages later.

```
2//1+1#

```

### 1. Emotinomicon

Emotinomicon pretty much ignores any text that isn't a string.  pushes 1 to stack and  outputs the TOS as a number.

### 2. Javascript

Comments in Javascript start with `//`, so only the `2` part gets executed.

### 3. Python 2/3 REPL

Comments in Python start with `#`, so only the `2//1+1` part gets executed. `//` is integer division in Python 3, and it is the same as `/` in Python 2. 2 divided by 1 is 2, plus 1 is 3.
> 2 votes

# Answer
## 4 languages, 97 bytes, 0.37890625

```
s="1";s=~-3;2//2;'''/.to_s.ord;"=;print 4;
__DATA__
=1;
";#'''#";print=s=>console.log(3)
print(s)

```

### Ruby

This sets `s` to `"1"`, compares using `=~` against `-3` in a void context, tries to divide `2` by `/2;'''/.to_s.ord` then starts a new string containing `=;print 4; __DATA__ =1;`, hits a comment, then `print`s `s` which is still `1`.

### Python

Sets `s` to `"1"` as per above, then sets it again to `~-3` which is `2`. We run an integer division of `2//2`, then there's a docstring containing `/.to_s.ord;"=;print 4; __DATA__ =1; ";#`, followed by a comment, finally `print`ing `s`, which is still `2`.

### JavaScript

Sets `s` to `"1"` then sets it again to `~-3` as per above, then there's `2` on the line followed by a comment. Then we set the variable `__DATA__` to `1`. There's a short string containing `;#'''#` followed by a definition of the function `print` which hardcodes the output to be 3, which is called on the next line.

### Perl

Runs a substitution equivalent to `s/"1";s/~-3;2\/\/2;'''\/.to_s.ord;"/`, `print`s `4` and the rest of the string is masked behind the `__DATA__` identifier.
> 2 votes

# Answer
## QBasic, QBIC and \>\<\>, 18 bytes / 3^3 languages = 0.66666 points

```
1:?v+1'-5`
''`>3n;

```

Breakdown:

### 1. QBasic (Get the IDE)

```
1:          Line number 1
  ?         Print
   v+1      undefined var v = 0 + 1 = 1
'-5`        The rest of theis code is a QBasic comment
''`>3n;     As is this

```

### 2. QBIC (Get the interpreter)

```
1     inserts a 1 in the code - mostly harmless
:     Reads from the cmd line. Nothing there, creates an empty variable a
?     Print
v+1   v is initialised to 6, +1 = 7
'     Code Literal: everything till the ` is passed to QBasic without processing
 -5`  7-5 = 2

''`>3n; Code literal with the first literal being a ': comment in QBasic

```

### 3. \>\<\> (Try it online)

```
1:  Push a 1 on the stack, duplicate stack
?   Pop top off the stack and skip next instruction if that's a 0
v   Move downwards - rest of the line is ignored

>   move to the right
3   Push 3 onto the stack
n   Print the top of the stack as a number
;   End the program

```
> 2 votes

# Answer
# Jelly / 05AB1E / Whitespace, 14 bytes, score \\$0.\overline{518}\\$

```
[S][S][S][T][T][LF]
[T][LF]
[S][T]1o

```

\[S\], \[T\], and \[LF\] added for visual clarity only.

I was going to add naz to the chain, but I guess it doesn't handle whitespace very well.

**Jelly explanation**

```
[S][S][S][T][T][LF]
[T][LF]
[S][T]
1                   # Literal 1
 o
# ...after which the result is output implicitly

```

Try it online!

**05AB1E explanation**

```
[S][S][S][T][T][LF]
[T][LF]
[S][T]
1                   # Push 1
 o                  # Push 2 ** 1
# ...after which the result is output implicitly

```

Try it online!

**Whitespace explanation**

```
[S][S][S][T][T][LF] # Push 3 to the stack
[T][LF][S][T]       # Output the top of the stack
1o                  # Ignored

```

Try it online!

I'm not very good with these languages — if you spot anything wrong with these explanations, *please* feel free to improve this post!
> 2 votes

# Answer
## JavaScript, HTML and PHP, 72 bytes / 3^3 = 2.67

```
1<!top?2:2//><!--<?='--'.'><script>document.body.innerHTML=3</script>'?>

```

In HTML, this will print the leading 1, ignore the `<!window?2:2//>` tag, and the rest is an HTML comment.

In JavaScript, it evaluates `1<!window?2:2` and outputs 2 (this must be run in a console) and the rest is a comment.

In PHP, the following is output from the server: `1<!top?2:2//><!----><script>document.body.innerHTML=3</script>` which replaces HTML's `1` with `3`.
> 1 votes

# Answer
# Python 1,2,3, Pyth, Seriously 40 bytes/5^3 = 0.32

```
#4X.q5
import sys
print(sys.version[0])

```

**Python 1,2,3 prints their version**

This is based on the same code by sweerpotato. The # starts a comment so the first line is not compiled.

**Pyth prints `4`**

`#4X.q` starts a while loop, X does something unnecessary, and .q quits the program.

**Seriously prints `5`**

`#4X.q5` starts out with # which does nothing, then 4 is pushed to the stack, X clears the stack, .q does nothing, and 5 is pushed on the stack and an invisible character (hex code `7f`) quits the program and prints what is on the stack.
> 1 votes

# Answer
# 16 languages, 149 bytes, score 0.03637695312

```
1` FSR3U3%3&(()())#5➡MoOMoOMoOMoOMoOMoOOOM++++++++.$:H@@@@@@@.   {-   !*/}(10)aeeeaeeawaaaaaw> 11
➕⎚14»R"15"*
print 13
[ [

```

WIP, I plan to add a lot more.

1. Element
2. Brain-Flak
3. SimpleStack
4. Cubically
5. Emoji
6. COW
7. Agony (outputs via raw ASCII)
8. Beam
9. Commentator (currently broken but according to the language spec should work fine)
10. Straw
11. RProgN
12. Emotinomicon
13. S.I.L.O.S
14. Charcoal
15. Fission
16. evil
> 1 votes

# Answer
# Brainglot, score 20/4^3 = 0.3125

```
-[>+<-----]>(-)$-!+.

```

## 1. brainbool

Brainbool only sees `[>+<]>+.`. The loop never runs, and the `>` just moves the pointer, so it's basically just `+.`. The `+` flips the bit, and the `.` outputs the current bit, which is 1.

## 2. brainfuck

Brainfuck only sees `-[>+<-----]>--+.`. The `-+` can be removed, which results in `-[>+<-----]>-.`. The part before the `.` is just the wrapping program for 50 on the esolangs wiki.

## 3. Extended Brainfuck Type I

Extended Brainfuck Type I only sees `-[>+<-----]>-$-!+.` The `$-!` can be removed, leaving `-[>+<-----]>-+.`, where the `-+` can be removed which turns it into `-[>+<-----]>.`. The part before the `.` is just the wrapping program for 51 on the esolangs wiki.

## 4. Brainlove

Brainlove sees the full program. The `(-)` and `$-!` can be removed, leaving `-[>+<-----]>+.`. The part before the `.` is just the wrapping program for 52 on the esolangs wiki.
> 1 votes

# Answer
## C C++ Python Ruby, 163 bytes

Score = 163/4^3 = 2.55

```
#include <stdio.h>
#if 0
C = 3
""" "
C = 4;\
" """
#endif
#ifdef __cplusplus
#define A 49
#else
#define A 50
#endif
#define print(X) main(){putchar(A);}
print(C);

```
> 0 votes

# Answer
# C, Python 2, Python 3, 99 bytes / 3 languages ^ 3 = 3.666677 points

Python 2 and 3 both use a version string, and the first character is the major version number. C prints `1`, Python 2 prints `2`, and Python 3 prints `3`.

```
#include <stdio.h>/*
import sys
print(sys.version[0])
#*/
#define pass main(){printf("%d",1);}
pass

```
> 0 votes

# Answer
# 6 languages, 31 bytes, 31/6^3 = 0.1435

As soon as I add another language to it the score gets worse, here is what gave me the best result so far:

```
kill -l|wc|dc -e\?58%8/1+p#^[cc6

```

## 1-5: Various shells + dc

The shells see this, the rest of the line is a comment:

```
kill -l|wc|dc -e\?58%8/1+p

```

The shell's output for `kill -L` is different, their output gets piped to `wc` to count the number of bytes (**N**) and compute (**N** % 58)/8 + 1 which coincidentally gives the right result.

1. Dash: Try it online!
2. ksh: Try it online!
3. tcsh: Try it online!
4. Bash: Try it online!
5. Zsh: Try it online!

## 6: Vim

The key `k` doesn't do anything with the buffer, `i` switches to insert mode and the following characters get typed. After `#` there's an `^[` character so Vim switches back to normal mode. `cc` deletes the line and switches to insert mode where we insert `6`.

Here's how it looks in Vim:

Try it online!
> 0 votes

# Answer
# ∞-ish, ~~12~~ 7 bytes

```
B3+0-8%

```

Non-competing as language postdates challenge and this is rather cheap. This prints:

```
 B3+0-8%
 B3       set top face sum to Cubically version
   +0     add top face sum to notepad
     -8   subtract !issolved(cube) from notepad
       %  print notepad

```

Basically, B3 gets the cube state to this in 3x3x3:

```
   111
   000
   000
511222330444
511222330444
511222330444
   555
   555
   333

```

As you can see, the top face sum is 3. As the smallest possible cube is a 2x2x2, we have to subtract 1. In Cubically 4x4x4, the cube would look like this:

```
    1111
    0000
    0000
    0000
5111222233304444
5111222233304444
5111222233304444
5111222233304444
    5555
    5555
    5555
    3333

```
> 0 votes

# Answer
# Javascript (spidermonkey), PHP CLI, Perl

### 41 bytes, 41/(3\**3) = 1.52

```
$x="5y";print("".$x?$x=="5"?"3":"2":"1");

```

If you try to execute it using normal Javascript rather than spidermonkey, it will do `ctrl+p`.
> 0 votes

# Answer
not so much 6 "languages" as peculiarities between 6 ways of using `awk`

```
for __ in 'nawk' 'gawk -M' 'mawk1' 'mawk2' 'gawk -b' 'gawk'; do

   $( printf '%s' "$__" ) 'BEGIN { print match(sprintf("%x%u%c%x%c",
                ((_+=++_)^(_+=_))^(_^=_),-!!_,_,_,!_),/$/)%25%13%7 }'
done

```

---

```
1
2
3
4
5
6

```

---

```
nawk 20200816
gawk 5.2.2 (GMP mode)
mawk 1.3.4 20230808
mawk 2
gawk 5.2.2 (byte mode)
gawk 5.2.2 (UTF8 mode)

```
> 0 votes

---
Tags: code-challenge, number, polyglot
---


# Question
Title: What is the shortest regular expression (REGEX) you can create for file extensions for image formats?
What is the shortest regular expression (REGEX) you can create for file extensions for all of the following image file formats (photographs, paintings, sketches, and drawings)?

```
.ACAD
.AFD
.AFP
.AOM
.AOMA
.APNG
.ASCII
.AVIF
.AVIFAV
.BMP
.BPG
.CABAC
.CDEC
.CDR
.CDRAW
.CGM
.CHEVC
.CIEC
.CIPA
.CMYK
.COLLADA
.CRT
.CWC
.DEEP
.DGN
.DML
.DRAW
.DXFDXF
.DXML
.ECW
.EMF
.EPS
.ERDAS
.EXIF
.FAMF
.FCCBY
.FDRW
.FIFF
.FITS
.FLIF
.FPGF
.FRIFF
.FVRML
.FXD
.GEM
.GIF
.GIMP
.GLE
.GMNG
.GMPEG
.GPNG
.GSVG
.HDR
.HEIF
.HEIFFAVIFAVHEIFAV
.HEVC
.HPGL
.HSF
.HVIF
.ICC
.ICO
.IESC
.IESCD
.IGES
.ILBM
.IMAGINE
.IMAGINEIMG
.IMG
.IMML
.INDD
.IPA
.ISGI
.ISO
.JFIF
.JFIFJPEG
.JPEG
.JPEGHDR
.JPEGJPEG
.JPG
.JPL
.JPS
.KKRA
.LCM
.LPCL
.LXAML
.LZW
.LZWLZW
.MANIAC
.MDP
.MEMF
.MML
.MOV
.MPO
.MSID
.MSIDSID
.MWMF
.NAPLPS
.NASA
.OBJ
.OCR
.ODG
.OGEX
.OGL
.PAM
.PBM
.PCB
.PCLIP
.PCPT
.PCX
.PDF
.PGFTZ
.PGM
.PGML
.PICT
.PLBM
.PLY
.PNG
.PNM
.PNS
.POVR
.PPDN
.PPM
.PPSP
.PRC
.PSD
.PST
.PXMP
.QCC
.RAW
.RGBE
.RGIS
.RIFF
.RISCOS
.RSX
.SAI
.SAISAI
.SISO
.STEP
.STL
.SUSKP
.SVG
.SVGC
.SWF
.SXML
.TARGA
.TGATGA
.TIF
.TIFF
.TVG
.TVP
.VDI
.VICAR
.VML
.VRML
.WEBP
.WMF
.WPM
.XCF
.XGL
.XISF
.XML
.XMP
.XPS
.XVL

```

---

# Scoring Function

The scoring function will be the number of ASCII characters in your regex

Note: only ASCII characters are allowed in this competition.

---

May the best **regex** win!

# Answer
# 752 bytes

```
^\.((HEIFFAVIFAVHE|AV)IFAV|(IMAGINEIM|J(PEG|FIF)JPE|GMPE|APN|G([MP]N|SV)|BP)G|I(MAGINE|ESC)|M(SIDSID|OV)|((JPEG)?HD|POV|OC)R|(C(OLLAD|IP)|T(GAT|AR)G|KKR|IP)A|(MANIA|C(HEV|DE|IE|W)|CABA|HEV|PR)C|(LZWLZ|C?DRA|FDR|EC)W|(SAISA|ASCI|ISG)I|(DXFDX|F(RIF|IF|PG)|(EX|FL)I|H(VI|S)|FAM|M[EW]M|RIF|EM|PD|SW|WM)F|(R(ISCO|GI)|E(RDA|P)|FIT|IGE|XP)S|NA(PLPS|SA)|FCCBY|I(ESCD|C[CO]|MG|SO)|P(G(FTZ|ML)|P(DN|M)|CPT|ICT|C[BX]|LY|N[GMS]|S[DT])|V(ICAR|DI)|(P(CLI|PS|XM)|S(USK|TE)|DEE|GIM|BM|MD)P|((FVR|LXA|SX)M|DX?M|HPG|IMM|LPC|VR?M|MM)L|A(VIF|OM)|HEIF|J(PEG|FIF)|MSID|A(OMA|F[DP])|CMYK|(ACA|IND|FX)D|OGEX|R(GBE|AW|SX)|S(VGC|ISO|TL)|T(IFF|V[GP])|(ILB|P(LB|[AB])|CG|GE|LC)M|W(EBP|PM)|X(ISF|M[LP]|[GV]L|CF)|CDR|LZW|PGM|S(AI|VG)|[TG]IF|JP[GLS]|O(BJ|DG|GL)|DGN|CRT|QCC|GLE|MPO)$

```

Naïve impementation, created with the help of this tool
> 1 votes

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


title: Generate Matching Regexes

text:
# Question
Title: Generate Matching Regexes
Write a program that takes two lists of strings and generates a javascript regex that fully matches all the strings in the first list and matches none of the strings in the second list.

To be specific when for all stings in the first list `str.match(/[your-output]/)` must produce a match for the full string and for all strings in the second list `str.match(/[your-output]/)` must produce no matches.

# Scoring

Your score is the average length of the regexes you produce not the length of your program. Your regexes should be tested against this file: https://pastebin.com/9iNZvGJC. Take the file in blocks of 20 lines and run your program with the first ten lines to match and the second ten to not match. Average the lengths of your program's output for all of the blocks in the file. This is your score.

# Rules

Do not output the / for the regex

# Answer
# JavaScript (ES7), Score: 767 / 50 = 15.34

This code is rather ugly and implements only one strategy. (I did try negative lookaheads, but it was not worth the effort and is disabled here.)

It could probably shave off a few more bytes with a higher maximum branching factor and/or a more clever pattern scoring function. For instance, `/.*[LObcln]o.*/` and `/.*(Y|o[otvy]).*/` are better solutions for the first 2 test cases which are currently not found.

The TIO link only includes the first 40 lines.

```
const MAX_PAT_LEN = 2;
const MAX_BF = 8;
const ESC = ".^$*+?()[{\\|";

let list = require("fs").readFileSync(0).toString().split("\n");
let block = [];

for(let n = 0; list[n]; n += 20) {
  block.push([list.slice(n, n + 10), list.slice(n + 10, n + 20)]);
}

let score = 0;

block.forEach(([A, B]) => {
  let res = process(A, B, false);

  console.log(res.length.toString().padStart(2) + " /" + res + "/");

  if(
    A.some(s => (s.match(RegExp(res)) || [])[0] != s) ||
    B.some(s => s.match(RegExp(res)))
  ) {
    throw "Failed";
  }

  score += res.length;
});

console.log(score);

function process(A, B, neg) {
  let chr = [...new Set([...A, ...B].join(''))]
            .map(c => ~ESC.indexOf(c) ? "\\" + c : c);
  let set = new Set;

  A.forEach(s => {
    for(let n = 1; n <= MAX_PAT_LEN; n++) {
      choose(chr, n).forEach(a => {
        let pat = a.join(''),
            regex = RegExp(pat);

        if(regex.test(s) && !B.some(s => regex.test(s))) {
          set.add(pat.toString());
        }
      });
    }
  });

  function score(A, pat) {
    return A.reduce((p, s) => p + RegExp(pat).test(s), 0);
  }

  let solution = [];

  function search(A, expr) {
    if(!A.length) {
      let c = compress(expr);

      solution.push(neg ? "^(?!.*" + c + ").*" : ".*" + c + ".*");
      return;
    }

    let patList = [...set].filter(a => score(A, a))
                  .sort((a, b) => score(A, b) - score(A, a));

    patList.slice(0, MAX_BF).forEach(pat => {
      search(A.filter(s => !RegExp(pat).test(s)), [...expr, pat]);
    });
  }

  search(A, []);

  return solution.sort((a, b) => a.length - b.length)[0];
}

function choose(list, n) {
  let sz = list.length;
  let max = sz ** n;
  let res = [];

  for(let k = 0; k < max; k++) {
    let sel = [];

    for(let i = 0; i < n; i++) {
      sel.push(list[Math.floor(k / sz ** i) % sz]);
    }
    res.push(sel);
  }
  return res;
}

function compress(list) {
  let maxW = Math.max(...list.map(s => s.length)),
      res = [];

  list.sort();

  for(let w = 1; w <= maxW; w++) {
    let subList = list.filter(s => s.length == w);

    for(let i = 0; i < w; i++) {
      let trunc = {};

      subList.forEach(s => {
        let key = s.slice(0, i) + s.slice(i + 1);
        trunc[key] = (trunc[key] || '') + s[i];
      });

      Object.keys(trunc).forEach(k => {
        let s0 = trunc[k].length + 2 + w,
            s1 = trunc[k].length * (w + 1);

        if(s0 <= s1) {
          res.push(k.slice(0, i) + '[' + trunc[k] + ']' + k.slice(i));
          list = list.filter(s =>
            s.length != w || s.slice(0, i) + s.slice(i + 1) != k
          );
        }
      });
    }
  }

  list = [...list, ...res];

  return list.length > 1 ? "(" + list.join('|') + ")" : list.join('|');
}

```

Try it online!

### Full output

```
14 /.*(an|la|ts).*/
17 /.*( n|Y|o[otv]).*/
19 /.*(J|ca|go|e[dy]).*/
16 /.*(j|ns|s,|t').*/
19 /.*(ke|wh|i[,dgl]).*/
12 /.*( c|W|p).*/
16 /.*(e'|j|nn|ve).*/
18 /.*(B|T|op|r,|un).*/
12 /.*a[ btuy].*/
16 /.*('s|3|r[ i]).*/
13 /.*(H|ar|po).*/
14 /.*(I |ie|nd).*/
16 /.*(sa|[nrs]\.).*/
17 /.*(Ye|ay|it|wh).*/
13 /.*("|nt|we).*/
16 /.*( f|A|He|am).*/
17 /.*(ce|id|ma|r ).*/
16 /.*(nk|o[bfpw]).*/
13 /.*( r|T|fl).*/
14 /.*(y |[1SW]).*/
18 /.*('l|un|[btw]e).*/
14 /.*(L| [Obe]).*/
15 /.*( p|-|eb|j).*/
13 /.*(H|ma|se).*/
10 /.*[clt]e.*/
15 /.*(G|ne|ry|x).*/
16 /.*(J|S|o[dos]).*/
16 /.*(Al|W|oo|w ).*/
16 /.*(T|j|['cn]t).*/
16 /.*(s\.|r[osy]).*/
18 /.*(E|il|[Inrs]s).*/
16 /.*(S|n'|su|uc).*/
16 /.*( w|s[!emo]).*/
15 /.*(!|K|ea|rr).*/
16 /.*(D|Yo|h,|si).*/
11 /.*[dhlr]i.*/
17 /.*(ll|st| [rv]).*/
15 /.*(!|H|a[ds]).*/
16 /.*( f|F|ic|wa).*/
16 /.*(ev|[abgu]r).*/
17 /.*(ti|ul|[AFS]).*/
16 /.*(ed| [RYly]).*/
14 /.*(ea|a[ b]).*/
18 /.*(Oa|k |['be]l).*/
15 /.*(\? |ni|ot).*/
13 /.*("|al|ta).*/
11 /.*(f |pa).*/
15 /.*(L|Re|W|nk).*/
18 /.*(fl|ly|[enr]t).*/
17 /.*('t|om|[dt]e).*/

```
> 2 votes

# Answer
# Python3, Score: 762/50 = 15.24 in ~30.51 seconds

```
import collections, re, random

def test_data():
    with open('inp_d.txt') as f:
        while True:
            l1 = [j.strip('\n') for _ in range(10) if (j:=next(f, None))]
            l2 = [j.strip('\n') for _ in range(10) if (j:=next(f, None))]
            if len(l1) < 10: return
            yield l1, l2
            if len(l2) < 10: return

def substrings(l1, l2):
    C = collections.defaultdict(set)
    C1 = collections.defaultdict(set)
    for I, l in enumerate(l1):
        for i in range(len(l)):
            for j in range(i+1, len(l)):
                L = l[i:j]
                if all(L not in k for k in l2):
                    C[j-i].add(L)
                    C1[L].add(I)

    return {a:sorted(b) for a,b in C.items()}, {a:sorted(b) for a, b in C1.items()}

def to_regexp(k):
    return ['', '['+''.join(k[0])+']'][k[0]!=tuple()]+k[1]+['', '['+''.join(k[2])+']'][k[2]!=tuple()]

def full_regexp(regexp):
    return regexp[0] if len(regexp) == 1 else '('+'|'.join(regexp)+')'

def merges(d, d1, depth = 2):
    for D in range(1, depth + 1):
        b = d[D]
        results = collections.defaultdict(dict)
        for x in range(D+1):
            for y in range(x+1, D+1):
                for i, a in enumerate(b):
                    if a[x:y] not in results[(x, y)]:
                        results[(x, y)][a[x:y]] = [i]
                    else:
                        results[(x, y)][a[x:y]].append(i)

        for (x, y), vals in results.items():
            for base, options in vals.items():
                for i, a in enumerate(options):
                    queue = [(options[i+1:], {*b[a][:x]}, base, {*b[a][y:]}, d1[b[a]])]
                    while queue:
                        r_options, l, base, r, o = queue.pop(0)
                        yield (tuple(sorted(filter(None, l))), base, tuple(sorted(filter(None, r)))), o
                        if r_options:
                            queue.append((r_options[1:], l, base, r, o))
                            n_b = b[r_options[0]]
                            if any(j not in o for j in d1[n_b]):
                                queue.append((r_options[1:], {*l, n_b[:x]}, base, {*r, n_b[y:]}, {*o, *d1[n_b]}))

def solutions(l1, l2, depth = 2):
    d, d1 = substrings(l1, l2)
    merge = dict(merges(d, d1))

    scores = collections.defaultdict(dict)
    for a, b in merge.items():
        T = to_regexp(a)
        if tuple(b) not in scores[10 - len(b)]:
            scores[10 - len(b)][tuple(b)] = [T]
        else:
            scores[10 - len(b)][tuple(b)].append(T)

    new_scores = {}
    vals = []
    for a, b in scores.items():
        subscores = {}
        for j, k in b.items():
            subscores[j] = min(k, key=len)
            vals.append((j, min(k, key=len)))
        new_scores[a] = subscores

    def contains(j, k, nj, nk):
        if nj == nk:
            return False

        return all(J in nj for J in j) and len(k) > len(nk)

    scores = {a:{j:k for j, k in b.items() if not any(contains(j, k, nj, nk) for nj, nk in vals)} for a, b in new_scores.items()}
    r_score, r_regexp = None, None
    queue = [(score, {*vals}, [regexp]) for score, container in sorted(scores.items(), key=lambda x:x[0]) for vals, regexp in container.items()]
    seen = []
    while queue:
        score, vals, regexp = queue.pop(0)
        if r_score is not None:
            if len(full_regexp(regexp)) >= r_score:
                continue

        if not score:
            if r_score is None:
                r_score, r_regexp = len(T:=full_regexp(regexp)), T

            elif len(T:=full_regexp(regexp)) < r_score:
                r_score, r_regexp = len(T), T

            continue

        remainder_vals = {*range(10)} - vals
        full_options = []
        for score, options in scores.items():
            for _vals, r_o in options.items():
                if any(i in remainder_vals for i in _vals) and len(r_o) <= len(regexp[-1]) and tuple(P:=sorted(regexp + [r_o])) not in seen:
                    if r_score is None or len(full_regexp(regexp + [r_o])) < r_score:
                        full_options.append(({*_vals} - {*vals}, _vals, r_o))

        for _, _vals, r_o in sorted(full_options, key=lambda x:len(x[0]), reverse=True)[:5]:
            seen.append(tuple(P:=sorted(regexp + [r_o])))
            queue.append((len(remainder_vals - {*_vals}), {*vals, *_vals}, regexp + [r_o]))

    return r_score + 4, '.*'+r_regexp+'.*'

if __name__ == '__main__':
    import time
    T = time.time()
    s, c = 0, 0
    for l1, l2 in test_data():
        a, b = solutions(l1, l2)
        s += a
        c += 1
        print(b)

    print(time.time() - T)
    print(s, c, s/c)

```

Rather long solution, but more optimized for speed and regexp length minimization.
> 1 votes

---
Tags: code-challenge, regular-expression, test-battery
---