93
\$\begingroup\$

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.


Leaderboard

<style>body { text-align: left !important} #answer-list { padding: 10px; width: 290px; float: left; } #language-list { padding: 10px; width: 290px; float: left; } table thead { font-weight: bold; } table td { padding: 5px; }</style><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="language-list"> <h2>Shortest Solution by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr> </thead> <tbody id="languages"> </tbody> </table> </div> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr> </thead> <tbody id="answers"> </tbody> </table> </div> <table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table><script>var QUESTION_ID = 65641; var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe"; var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk"; var OVERRIDE_USER = 31516; var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page; function answersUrl(index) { return "https://api.stackexchange.com/2.2/questions/" + QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER; } function commentUrl(index, answers) { return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER; } function getAnswers() { jQuery.ajax({ url: answersUrl(answer_page++), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { answers.push.apply(answers, data.items); answers_hash = []; answer_ids = []; data.items.forEach(function(a) { a.comments = []; var id = +a.share_link.match(/\d+/); answer_ids.push(id); answers_hash[id] = a; }); if (!data.has_more) more_answers = false; comment_page = 1; getComments(); } }); } function getComments() { jQuery.ajax({ url: commentUrl(comment_page++, answer_ids), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { data.items.forEach(function(c) { if (c.owner.user_id === OVERRIDE_USER) answers_hash[c.post_id].comments.push(c); }); if (data.has_more) getComments(); else if (more_answers) getAnswers(); else process(); } }); } getAnswers(); var SCORE_REG = /<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\d?\.?\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/; var OVERRIDE_REG = /^Override\s*header:\s*/i; function getAuthorName(a) { return a.owner.display_name; } function process() { var valid = []; answers.forEach(function(a) { var body = a.body; a.comments.forEach(function(c) { if(OVERRIDE_REG.test(c.body)) body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>'; }); var match = body.match(SCORE_REG); if (match) valid.push({ user: getAuthorName(a), size: +match[2], language: match[1], link: a.share_link, }); else console.log(body); }); valid.sort(function (a, b) { var aB = a.size, bB = b.size; return aB - bB }); var languages = {}; var place = 1; var lastSize = null; var lastPlace = 1; valid.forEach(function (a) { if (a.size != lastSize) lastPlace = place; lastSize = a.size; ++place; var answer = jQuery("#answer-template").html(); answer = answer.replace("{{PLACE}}", lastPlace + ".") .replace("{{NAME}}", a.user) .replace("{{LANGUAGE}}", a.language) .replace("{{SIZE}}", a.size) .replace("{{LINK}}", a.link); answer = jQuery(answer); jQuery("#answers").append(answer); var lang = a.language; lang = jQuery('<a>'+lang+'</a>').text(); languages[lang] = languages[lang] || {lang: a.language, lang_raw: lang.toLowerCase(), user: a.user, size: a.size, link: a.link}; }); var langs = []; for (var lang in languages) if (languages.hasOwnProperty(lang)) langs.push(languages[lang]); langs.sort(function (a, b) { if (a.lang_raw > b.lang_raw) return 1; if (a.lang_raw < b.lang_raw) return -1; return 0; }); for (var i = 0; i < langs.length; ++i) { var language = jQuery("#language-template").html(); var lang = langs[i]; language = language.replace("{{LANGUAGE}}", lang.lang) .replace("{{NAME}}", lang.user) .replace("{{SIZE}}", lang.size) .replace("{{LINK}}", lang.link); language = jQuery(language); jQuery("#languages").append(language); } }</script>

\$\endgroup\$
  • 6
    \$\begingroup\$ @muddyfish You might be able to fetch the minor version within the code, which would then give you free solutions for all 2.7.1 to 2.7.n. (Actually, sweerpotato does just that with major versions.) \$\endgroup\$ – Martin Ender Dec 3 '15 at 17:04
  • 14
    \$\begingroup\$ I think maybe shortest solution by language doesn't make sense here... :P \$\endgroup\$ – FryAmTheEggman Dec 3 '15 at 20:44
  • 3
    \$\begingroup\$ @Mego Neither am I, that's why I leave sarcastic comments about the problem so that other people find out about it :P \$\endgroup\$ – FryAmTheEggman Dec 4 '15 at 3:50
  • 12
    \$\begingroup\$ I just wanted to congratulate you on how well-balanced your scoring is. When code challenges mix two quantities into one score the balance is almost always off such that the best answer will just optimise one of the scores without having to consider the other one at all. The cubic weight of the number of languages was perfect here... while it was always possible to add another language it was always a very nice (but doable) challenge to do so in the number of bytes available. :) \$\endgroup\$ – Martin Ender Dec 5 '15 at 23:49
  • 20
    \$\begingroup\$ In this PPCG challenge we've been collaboratively building a polyglot. It now has a better score on this challenge than the leading entries submitted to this challenge, but it wouldn't make sense to copy a group effort that's constantly being improved over, so I'm just dropping a mention in the comments here. \$\endgroup\$ – user62131 Mar 17 '17 at 23:56

36 Answers 36

90
+500
\$\begingroup\$

30 languages, 248 bytes, 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 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 printed.

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!

Restrictions introduced: No instructions before the Axo program which change the direction of the IP

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!

Restrictions introduced: All +s must have at least one preceding space

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!

Introduced restrictions: No . before the first [

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.

\$\endgroup\$
  • 12
    \$\begingroup\$ Daaaaaaaaaang... \$\endgroup\$ – AdmBorkBork Apr 22 '16 at 20:52
  • 9
    \$\begingroup\$ I suspect this may be the lowest non-zero score on any question here. \$\endgroup\$ – Morgan Thrapp Apr 22 '16 at 20:53
  • \$\begingroup\$ This is... incredible. I am in awe. \$\endgroup\$ – Fund Monica's Lawsuit Apr 22 '16 at 20:54
  • 2
    \$\begingroup\$ *positive, there are a few negative scores for short answers with bonuses. \$\endgroup\$ – CalculatorFeline Apr 26 '17 at 16:18
  • \$\begingroup\$ Pro-tip from the future: your tabs won't be messed up if you surround your code in pre tags instead of using a Markdown-style code block. \$\endgroup\$ – Jakob Aug 11 '17 at 2:39
148
\$\begingroup\$

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 0s 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 TTSSs 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.

\$\endgroup\$
  • 34
    \$\begingroup\$ This is really impressive! \$\endgroup\$ – sweerpotato Dec 3 '15 at 16:16
  • 1
    \$\begingroup\$ @YassinHajaj Thanks, corrected. \$\endgroup\$ – Martin Ender Dec 3 '15 at 21:00
  • 2
    \$\begingroup\$ Niiice. Great job for 15 languages! \$\endgroup\$ – ev3commander Dec 5 '15 at 22:51
  • 1
    \$\begingroup\$ @SnoringFrog Well, there you go. \$\endgroup\$ – Martin Ender Dec 5 '15 at 22:52
  • 1
    \$\begingroup\$ @Eumel Thanks, but the bounty is specifically for the "normal" languages listed in its description, so the bounty should go to such an answer (like Sp3000's very nice solution). I think I got enough rep from this anyway. ;) \$\endgroup\$ – Martin Ender Dec 7 '15 at 12:09
42
\$\begingroup\$

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!

:~)!

\$\endgroup\$
  • 10
    \$\begingroup\$ From chat: Yes, this is both cheap and valid =) This is part of the reason why only major versions were considered unique enough. I don't know how many Python versions there are, but you could probably get your score pretty darn low using something like this... It's one of the few solutions where I actually understand what is happening, so +1 from me ;-) \$\endgroup\$ – Stewie Griffin Dec 3 '15 at 17:32
  • 6
    \$\begingroup\$ In python 10.x (when it exists) wouldn't it print 1 because it's the first character of the string "10.whatever"? \$\endgroup\$ – ev3commander Dec 4 '15 at 20:15
  • 1
    \$\begingroup\$ @ev3commander However, this submission isn't spec'd to produce a correct output in python10. \$\endgroup\$ – Tyzoid Dec 8 '15 at 12:26
  • \$\begingroup\$ Fixed! Working on a future-proof version, but Python 1.x isn't as user-friendly as the others :~)! \$\endgroup\$ – sweerpotato Dec 8 '15 at 17:08
  • 1
    \$\begingroup\$ All I need to do is create a language that has three major versions. In those three major versions, when running an empty file returns the major version number. The result would be 0 / 3^3 = 0 Perfect. \$\endgroup\$ – Braden Steffaniak Dec 9 '15 at 21:55
32
\$\begingroup\$

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 :/

\$\endgroup\$
20
\$\begingroup\$

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
\$\endgroup\$
  • 1
    \$\begingroup\$ More languages is definitely the way to go I think... the cubic denominator is really generous, so that it shouldn't be too hard to beat my score once you have 5 or 6 languages. \$\endgroup\$ – Martin Ender Dec 3 '15 at 14:22
  • \$\begingroup\$ @MartinBüttner, Yes, although I can't see how to add a new language \$\endgroup\$ – Adnan Dec 3 '15 at 14:25
  • 2
    \$\begingroup\$ @Martin yes, it's generous. The point of the cubic denominator was to strongly encourage more languages. I think 6 languages in 50 bytes should be worth the same as 5 languages in 30 bytes. :-) it will definitely get harder the more languages you use. \$\endgroup\$ – Stewie Griffin Dec 3 '15 at 14:36
  • \$\begingroup\$ Your Whitespace code could be reduced a bit (and I don't think it'll affect any of your other languages. (Using L for linefeed), instead of the SSSSSSSSSSTTSTSTLTLSS you have now, you can do SSSTSTLTLST. This pushes a literal 5 on the stack, then prints as integer. \$\endgroup\$ – SnoringFrog Dec 4 '15 at 15:04
  • \$\begingroup\$ @SnoringFrog Thanks! I have edited it \$\endgroup\$ – Adnan Dec 4 '15 at 15:18
14
\$\begingroup\$

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.

\$\endgroup\$
13
\$\begingroup\$

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 #defines 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.

\$\endgroup\$
12
+100
\$\begingroup\$

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 :)

\$\endgroup\$
  • \$\begingroup\$ Would 2^(0 or 1) work? \$\endgroup\$ – xnor Dec 7 '15 at 11:09
  • \$\begingroup\$ @xnor Ah yes it would, thanks :) \$\endgroup\$ – Sp3000 Dec 7 '15 at 11:11
8
\$\begingroup\$

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
\$\endgroup\$
8
\$\begingroup\$

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, prints it, and errors. Stolen inspired by Sp3000's answer.

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

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 $.

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

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

\$\endgroup\$
  • \$\begingroup\$ How about $p=$PSVersionTable;($p.PSVersion.Major,1)[!$p]? That works on my Powershell, but maybe not on all previous versions. \$\endgroup\$ – Lynn Dec 3 '15 at 22:34
7
\$\begingroup\$

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!)

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

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

\$\endgroup\$
6
\$\begingroup\$

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)

\$\endgroup\$
6
\$\begingroup\$

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.

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

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

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

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)

spacespacespacetabenter: push a 1 onto the stack

tabenterspacetab: 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
\$\endgroup\$
5
\$\begingroup\$

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.

\$\endgroup\$
  • 1
    \$\begingroup\$ You know, I've never found a good use for mirror. xD \$\endgroup\$ – Addison Crump Dec 4 '15 at 23:47
5
+50
\$\begingroup\$

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.

\$\endgroup\$
4
\$\begingroup\$

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.

\$\endgroup\$
4
\$\begingroup\$

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.

\$\endgroup\$
  • \$\begingroup\$ foo.tryitonline.net/#code=MT8zJ0BuIjQiKCky&input= \$\endgroup\$ – Dennis Apr 21 '16 at 4:12
  • \$\begingroup\$ @Dennis Thanks! The Esolangs page didn't have a link to that interpreter. \$\endgroup\$ – DLosc Apr 21 '16 at 4:30
  • \$\begingroup\$ Here's the index of the currently available languages. If you ever want me to add one, just ping me in chat. \$\endgroup\$ – Dennis Apr 21 '16 at 4:34
4
\$\begingroup\$

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)

\$\endgroup\$
  • \$\begingroup\$ Nice answer, I like answers in conventional languages :-) hope you'll have fun golfing on ppcg :-) please try out any of my previous challenges if you think they are interesting :-) some are a bit tricky and some are more basic :-) \$\endgroup\$ – Stewie Griffin Apr 24 '16 at 21:16
  • \$\begingroup\$ You might be interested in the open 100 rep bounty described in the challenge. Outgolf Sp3000 (28 bytes, 4 languages) using only conventional languages (defined in the link) and it's yours :-) unfortunately python 2 and 3 are not considered unique in the bounty challenge. \$\endgroup\$ – Stewie Griffin Apr 24 '16 at 21:22
3
\$\begingroup\$

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
\$\endgroup\$
2
\$\begingroup\$

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.

\$\endgroup\$
  • 2
    \$\begingroup\$ 3^3=27 ==> 82 / 27 = 3.037037037037037... \$\endgroup\$ – AdmBorkBork Dec 4 '15 at 20:20
  • 1
    \$\begingroup\$ Your Whitespace code prints 0, not 2. Tested here and here. \$\endgroup\$ – Dennis Dec 5 '15 at 5:40
  • \$\begingroup\$ @Dennis Thanks, I had omitted the sign bit. \$\endgroup\$ – Mike Bufardeci Dec 5 '15 at 16:55
2
\$\begingroup\$

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
\$\endgroup\$
2
\$\begingroup\$

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.

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

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 prints 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 printing 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;"/, prints 4 and the rest of the string is masked behind the __DATA__ identifier.

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

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
\$\endgroup\$
  • 1
    \$\begingroup\$ I think you want to cube the number of languages in your score (ie. 18 / (3^3) ) \$\endgroup\$ – math junkie Mar 24 '17 at 18:28
1
\$\begingroup\$

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.

\$\endgroup\$
  • 1
    \$\begingroup\$ Welcome to PPCG.SE! Great first post! Two things: we don't usually like REPL-based answers (the Javascript program). Additionally, the PHP code does not seem to run when I put it into an online interpreter, how exactly does the PHP work? \$\endgroup\$ – GamrCorps Dec 4 '15 at 22:56
  • \$\begingroup\$ Thanks! Well, it's technically PHP + HTML (ie. if this is the source code for code.php, visiting site/code.php in a browser displays 3. \$\endgroup\$ – cuniculus Dec 5 '15 at 0:21
  • \$\begingroup\$ Try it here: mowbl.com/se.php. \$\endgroup\$ – cuniculus Dec 5 '15 at 0:23

Your Answer

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

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