32
\$\begingroup\$

Produce a program A such that running it in language A produces Program B, and running program A in language B produces program C.

Program B, when run in language B produces Program A, and running program B in language A produces program C.

Program C, when run in language A or language B, prints "Wrong language!".

Program | Language | Result
--------|----------|----------
A       | A        | Program B
B       | B        | Program A
A       | B        | Program C
B       | A        | Program C
C       | A        | "Wrong language!" 
C       | B        | "Wrong language!" 

Your answer should use this template:


Language A/Language B, {a bytes} + {b bytes} = {total bytes} bytes

Program A:

a code

Program B:

b code

Program C:

c code 

Source:

# Language A/Language B, <a bytes> + <b bytes> = <total bytes> bytes

Program A:

    a code
Program B:

    b code
Program C:

    c code

  • None of these programs should take input.
  • Different versions of the same language do count as different languages. (although this is discouraged because it leads to boring solutions)
  • Languages A and B must be distinct.
  • You must not read your own source code from a file. Programs may not be empty
  • Standard loopholes apply.

Hints

  • C++ and [Python/Bash/other # commented languages] are good combos because you can define macros that one language can ignore

This is , so the smallest sum of the byte counts Program A and B wins.

\$\endgroup\$
  • \$\begingroup\$ I'm working on this... \$\endgroup\$ – Oliver Ni Nov 17 '16 at 20:32
  • 6
    \$\begingroup\$ @CrazyPython Don't do penalties or percentages. Simply allow it, or don't. Percentages make scoring no longer [code-golf]. meta.codegolf.stackexchange.com/a/8106/34718 \$\endgroup\$ – mbomb007 Nov 17 '16 at 22:12
  • 1
    \$\begingroup\$ @ais523n I removed it, it makes the challenge too easy. \$\endgroup\$ – noɥʇʎԀʎzɐɹƆ Nov 18 '16 at 17:06
  • 1
    \$\begingroup\$ @CrazyPython Finished. I started over from scratch yesterday with a different strategy. It ended up being a LOT shorter and easier. \$\endgroup\$ – mbomb007 Dec 8 '16 at 16:44
  • 1
    \$\begingroup\$ Can Wrong language! be output in any form (i.e. all caps, all lowercase, etc.)? \$\endgroup\$ – R. Kap Dec 22 '16 at 4:37
16
\$\begingroup\$

JavaScript (ES6) / Python 3, 264 + 258 = 522 bytes

Program A:

a="a=%r;b=%r;c=%r;1//2;print(c);'''\nconsole.log(b,...[a,b,c].map(uneval))//'''";b="a=%s;b=%s;c=%s;1//2;'''\nprint=_=>console.log(c)//'''\nprint(a%(a,b,c))";c="1//2;alert=print\nalert('Wrong language!')";1//2;print(c);'''
console.log(b,...[a,b,c].map(uneval))//'''

Program B:

a="a=%r;b=%r;c=%r;1//2;print(c);'''\nconsole.log(b,...[a,b,c].map(uneval))//'''";b="a=%s;b=%s;c=%s;1//2;'''\nprint=_=>console.log(c)//'''\nprint(a%(a,b,c))";c="1//2;alert=print\nalert('Wrong language!')";1//2;'''
print=_=>console.log(c)//'''
print(a%(a,b,c))

Program C:

1//2;alert=print
alert('Wrong language!')

Probably golfable...

JavaScript explanation

Program A:

// Set a, b, and c to these strings:
a="a=%r;b=%r;c=%r;1//2;print(c);'''\nconsole.log(b,...[a,b,c].map(uneval))//'''";
b="a=%s;b=%s;c=%s;1//2;'''\nprint=_=>console.log(c)//'''\nprint(a%(a,b,c))";
c="1//2;alert=print\nalert('Wrong language!')";

// Ignore this line:
1//2;print(c);'''

// Print the Python program (b), replacing the "%s"s with the raw forms of a, b, and c:
console.log(b,...[a,b,c].map(uneval))//'''

Program B:

// Set a, b, and c to these strings:
a="a=%r;b=%r;c=%r;1//2;print(c);'''\nconsole.log(b,...[a,b,c].map(uneval))//'''";
b="a=%s;b=%s;c=%s;1//2;'''\nprint=_=>console.log(c)//'''\nprint(a%(a,b,c))";
c="1//2;alert=print\nalert('Wrong language!')";

// Ignore this line:
1//2;'''

// Define a function `print` which prints `c` (the "Wrong language!" program):
print=_=>console.log(c)//'''

// Call `print`, ignoring the argument (which is NaN):
print(a%(a,b,c))

Program C:

// Ignore this line:
1//2;alert=print

// Alert "Wrong language!":
alert('Wrong language!')

Python explanation

Program A:

# Set a, b, and c to these strings:
a="a=%r;b=%r;c=%r;1//2;print(c);'''\nconsole.log(b,...[a,b,c].map(uneval))//'''";
b="a=%s;b=%s;c=%s;1//2;'''\nprint=_=>console.log(c)//'''\nprint(a%(a,b,c))";
c="1//2;alert=print\nalert('Wrong language!')";

# Print `c` (the "Wrong language!" program):
1//2;print(c);

# Ignore this part:
'''
console.log(b,...[a,b,c].map(uneval))//'''

Program B:

# Set a, b, and c to these strings:
a="a=%r;b=%r;c=%r;1//2;print(c);'''\nconsole.log(b,...[a,b,c].map(uneval))//'''";
b="a=%s;b=%s;c=%s;1//2;'''\nprint=_=>console.log(c)//'''\nprint(a%(a,b,c))";
c="1//2;alert=print\nalert('Wrong language!')";

# Ignore this part:
1//2;'''
print=_=>console.log(c)//'''

# Print the JS program (a), replacing the "%r"s with the raw forms of a, b, and c:
print(a%(a,b,c))

Program C:

# Set `alert` to the function `print`:
1//2;alert=print

# Call this function on "Wrong language!":
alert('Wrong language!')
\$\endgroup\$
  • \$\begingroup\$ Care to add an explanation of how it works? \$\endgroup\$ – noɥʇʎԀʎzɐɹƆ Nov 19 '16 at 14:31
  • \$\begingroup\$ @CrazyPython Done :-) \$\endgroup\$ – ETHproductions Nov 19 '16 at 15:09
  • \$\begingroup\$ Very creative, well done. \$\endgroup\$ – noɥʇʎԀʎzɐɹƆ Nov 20 '16 at 1:04
10
+400
\$\begingroup\$

Befunge-98 (PyFunge)/><>, 123 + 123 = 266 250 246 bytes

Program A:
"81!#.#vp00g>:#,_j+4<.=1l5v!o#!g00
g00<<<<<>0!#[f8+1!#.48*k'Wrong language!<o>[f@,kep.#!0a'00g!#o# \!gff+k,@,k*8ba$$ #o#!a"

Try it in Befunge-98!, Try it in ><>!

Program B:
"00g!#o!v5l1=.<4+j_,#:>g00pv#.#!18
g00<<<<<>0!#[f8+1!#.48*k'Wrong language!<o>[f@,kep.#!0a'00g!#o# \!gff+k,@,k*8ba$$ #o#!a"

Try it in ><>!, Try it in Befunge-98!

Program C:
"a0!#.pek,@f[>o<!egaugnal gnorW

Try it in Befunge-98! Try it in ><>!

How it Works:

The second line in both programs is identical and serves the same function for both language. When entered leftwards from the <<<<, it prints the entire second line. When entering to the right of those, print program C.

When the first line is run in the wrong language, it enters through the program C producing section. Otherwise, it prints the top line backwards with the " at the front and enters the second line producing section.

First line

Program A:
"81!#.#vp00g>:#,_j+4<.=1l5v!o#!g00

><>:
" Wrapping string literal over the first line
 81!#.  Jumps the pointer to the Program C producer

Befunge-98:
" Wrapping string literal
 81!#.  Pushes 8,0 (! inverts number, # skips over .)
      #v Skip over the exit
        p00g Pops the excess 8,0 and space and gets the " from 0,0
            >:#,_ Classic print until stack is empty
       v         j+4< Skips back to the exit and goes to the second line
Program B:
"00g!#o!v5l1=.<4+j_,#:>g00pv#.#!18

><>:
" Wrapping string literal
 00g!# Gets the " from 0,0
      o!v5l1=. Print until the stack is empty and jump to the second line

Befunge-98:

" Wrapping string literal
 00g Gets the " from 0,0
    !#o!v Skip the instruction o and go to Program C producer

Second Line:

g00<<<<<>0!#[f8+1!#.48*k'Wrong language!<o>[f@,kep.#!0a'00g!#o# $$00gff+k,@,k*9aa$$ #o#!a"

><>: Second line producer
g00<<<<< Get the " from cell 0,0
        ......      " Wrapping string literal over the stack
               #o#!a  Print newline and the stack and exit
Program C producer:
       >0!#[        Clear stack
            f8+1!#. Jump to cell 22,1
                   .....'...'   Push program C to the stack
                             00g Get " from cell 0,0
                                !#o# Print stack until empty

Befunge-98: Second line producer

g00<<<<< Get the " from cell 0,0
        ......              " Wrapping string literal
                       #o#!a  Skip over instruction o
                     $$       Pop the excess characters
                  90a Push a newline and 90
               @,k      Execute , instruction (print) 90+1 times, printing second line

Program C producer:
        >0!#[ Push 1 and skip [
             f8+1!#. Push 22, 0 and skip .
                    48*k'...' Execute ' instruction 32 times, pushing program C
                         ...'00g!#o# Push 0 and skip the instruction o
                                     \! Convert excess values to two 0s
                                       g Get " from cell 0,0
                                          ff+ Push 30
                                             k, Execute , 30+1 times, printing program C
                                               @ Exit program

Program C

"a0!#.pek,@f[>o<!egaugnal gnorW

><>:
" Wrapping string literal
 a0!#. Jump to cell 10,0
           f[ Create a new stack with only the top 15 elements
             >o< Print stack

Befunge-98:
" Wrapping string literal
 a0!#. Push 10,1
      p Pop 10,1 and excess space
       ek,@ Push 14 and execute , 14+1 times and exit the program
\$\endgroup\$
  • 2
    \$\begingroup\$ Save 1 byte and you get a 400 bounty lol. \$\endgroup\$ – Magic Octopus Urn Feb 6 '18 at 15:29
  • \$\begingroup\$ @MagicOctopusUrn I think the OP forgot to say "otherwise Jo King gets it" \$\endgroup\$ – Jo King Feb 6 '18 at 23:53
  • \$\begingroup\$ @JoKing Not necessarily. If the bounty is not awarded, it is automatically given to the highest-voted answer with half the rep. \$\endgroup\$ – mbomb007 Feb 8 '18 at 22:47
  • 1
    \$\begingroup\$ @MagicOctopusUrn Okay, there. Happy? :P \$\endgroup\$ – Jo King Feb 11 '18 at 22:58
  • \$\begingroup\$ 4x over-joyed ;P. \$\endgroup\$ – Magic Octopus Urn Feb 13 '18 at 12:57
9
+100
\$\begingroup\$

Python 3 + JavaScript (Rhino), 171 + 171 = 342 bytes

Program A (outputs program B in Python 3, program C in JavaScript; note trailing newline):

s="'";d='"';r=['print("s="+d+s+d+";d="+s+d+s+";r=["+s+r[1]+s+","+s+r[0]+s+"];eval(r[([11]+[0])[1]])")','print("print("+d+"Wrong language!"+d+")")'];eval(r[([11]+[0])[1]])

Program B (outputs program A in JavaScript, program C in Python; note trailing newline):

s="'";d='"';r=['print("print("+d+"Wrong language!"+d+")")','print("s="+d+s+d+";d="+s+d+s+";r=["+s+r[1]+s+","+s+r[0]+s+"];eval(r[([11]+[0])[1]])")'];eval(r[([11]+[0])[1]])

Program C (outputs "Wrong language!" in either language; also has a trailing newline, which doesn't count in the score):

print("Wrong language!")

Note that I'm using an unusual dialect of JavaScript here. People normally use browser implementations, but those have issues with output, doing it in a weird way (using alert). I'm using the Ubuntu package rhino which is an "offline" JavaScript implementation with a different set of libraries implemented to a typical browser (it's intended as an embeddable scripting language); this is notable in that it provides a print statement in the same style as, for example, Python 3.

This is a "true polyglot" in the sense that both languages are running the same calculations, in the same order, giving them the same meaning. They both have the same AST (and it's fairly trivial to create a Python 3 + JavaScript polyglot quine via reducing this program). There's no code that's specific to one language, which helps me bring the length way down. Incidentally, you have to use Python 3 so that you can use semicolons to separate statements (if you used newlines you'd have to escape the newlines).

The program starts by defining strings s and d which hold a single quote and double quote respectively. This makes it possible to output quotes without having to mention them later in the source code, avoiding issues with escaping (which frequently seem to be a problem with quines; the main reason I answer so many quine problems in Underload is that its strings nest).

The heart of the program is the array r which holds the main body of the two programs used by the challenge; one of the programs (the one that comes first in program A, and second in program B) is an almost-quine that simply outputs the original program via concatenating together pieces (taken mostly from r itself, with a few string literals), and the other prints program C. In order to make the program not a true quine (which would make it impossible to detect that we were running in the wrong language), the elements of r are printed in reverse order; r[0] in program A is r[1] in program B, and vice versa.

Finally, all that's necessary is to evaluate the correct element of r. This is accomplished using the expression ([11]+[0])[1] that produces a different value in Python 3 and in JavaScript. Both languages parse it identically, but they have different ideas of what addition does to lists:

  • When Python 3 adds [11] to [0], it gets [11, 0] (concatenating the lists), and then taking the second element of the list ([1]) gives us the integer 0.

  • When JavaScript adds [11] to [0], it gets "110" (concatenating the string representations of the lists), and then taking the second character of the string ([1]) gives us the string "1", which JavaScript is quite happy to use as an index into a list.

Therefore, Python 3 runs the first element of r in both programs (producing the almost-a-quine when running program A, and printing program C when running program B); JavaScript runs the second element, and thus treats program A and program B the opposite way around.

Incidentally, if you run program A in Ruby, it will print program B except without a trailing newline. If you run program B in Ruby, it will print program C except without a trailing newline. In other words, this solution very nearly works with a different set of languages, swapping Python 3 for Ruby (the only reason I don't just delete the newline from program B to get a score of 341 is that the newline inconsistency in program C would disqualify the submission).

(I was working on a "true polyglot" like this for a different reason, which I've now posted as a challenge, and realised that the techniques could be adapted to this one as well.)

\$\endgroup\$
  • \$\begingroup\$ Should be 170 each, not 171... \$\endgroup\$ – noɥʇʎԀʎzɐɹƆ Nov 22 '16 at 0:02
  • 1
    \$\begingroup\$ It's 171, you have to count the newline too. (Normally you never leave on newlines in code-golf questions, but in quines, often having a newline at the end makes things easier.) \$\endgroup\$ – user62131 Nov 22 '16 at 0:53
  • \$\begingroup\$ I added the trailing newlines for you. You have to use <pre><code>...</code></pre> for them to show up. \$\endgroup\$ – mbomb007 Nov 22 '16 at 16:36
  • \$\begingroup\$ You can literally use anything to index into a list; JS actually converts whatever it is into a string first. "a"[0], "a"["0"], and "a"[[[[[[[["0"]]]]]]]] all accomplish the same thing. \$\endgroup\$ – ETHproductions Nov 26 '16 at 16:47
8
\$\begingroup\$

C/Python, 733 bytes + 733 bytes = 1466 bytes

Program A:

#define int char*
int
a1="#define print(X) main(){printf(d,13,13,34,a1,34,13,13,34,a2,34,13,13,34,b1,34,13,13,34,b2,34,13,13,34,c,34,13,13,34,d,34,13,b1,13,b2);}";
int
a2="print(c%(13,34,34))";
int
b1="#define print(X) main(){printf(c,13,34,34);};";
int
b2="print(d%(13,13,34,a1,34,13,13,34,a2,34,13,13,34,b1,34,13,13,34,b2,34,13,13,34,c,34,13,13,34,d,34,13,a1,13,a2))";
int
c="#define print(a) main(){puts(a);}%cprint(%cWrong language!%c)";
int
d="#define int char*%cint%ca1=%c%s%c;%cint%ca2=%c%s%c;%cint%cb1=%c%s%c;%cint%cb2=%c%s%c;%cint%cc=%c%s%c;%cint%cd=%c%s%c;%c%s%c%s";
#define print(X) main(){printf(d,13,13,34,a1,34,13,13,34,a2,34,13,13,34,b1,34,13,13,34,b2,34,13,13,34,c,34,13,13,34,d,34,13,b1,13,b2);}
print(c%(13,34,34))

Program B:

#define int char*
int
a1="#define print(X) main(){printf(d,13,13,34,a1,34,13,13,34,a2,34,13,13,34,b1,34,13,13,34,b2,34,13,13,34,c,34,13,13,34,d,34,13,b1,13,b2);}";
int
a2="print(c%(13,34,34))";
int
b1="#define print(X) main(){printf(c,13,34,34);};";
int
b2="print(d%(13,13,34,a1,34,13,13,34,a2,34,13,13,34,b1,34,13,13,34,b2,34,13,13,34,c,34,13,13,34,d,34,13,a1,13,a2))";
int
c="#define print(a) main(){puts(a);}%cprint(%cWrong language!%c)";
int
d="#define int char*%cint%ca1=%c%s%c;%cint%ca2=%c%s%c;%cint%cb1=%c%s%c;%cint%cb2=%c%s%c;%cint%cc=%c%s%c;%cint%cd=%c%s%c;%c%s%c%s";
#define print(X) main(){printf(c,13,34,34);};
print(d%(13,13,34,a1,34,13,13,34,a2,34,13,13,34,b1,34,13,13,34,b2,34,13,13,34,c,34,13,13,34,d,34,13,a1,13,a2))

Program C:

#define print(a) main(){puts(a);}
print("Wrong language!")

I used your hint of using C/C++ with Python. Not very concise, but still qualifying I suppose.

\$\endgroup\$
  • 3
    \$\begingroup\$ Why did you delete your account!? Why not stay here? \$\endgroup\$ – noɥʇʎԀʎzɐɹƆ Nov 20 '16 at 1:02
  • 1
    \$\begingroup\$ Explanation, please? \$\endgroup\$ – noɥʇʎԀʎzɐɹƆ Nov 20 '16 at 1:24
  • 2
    \$\begingroup\$ @CrazyPython If s?he deleted his/her account, how would they explain the code? \$\endgroup\$ – NoOneIsHere Dec 22 '16 at 17:09
8
+200
\$\begingroup\$

Python 2 / Retina, 550 + 645 = 1373 1254 1221 1195 bytes

I'm not quite sure if the unichr and replace parts can be golfed more. I tried using Python 3, but a lot is lost by having to add parentheses and handle them. I tried setting R=unicode.replace and using that, but the output gets messed up.

Note that Retina has a trailing newline in its output by default, and this is not included in the programs. If someone says I need to remove it, that can be done trivially. Also, the Python code works in repl.it, but is not guaranteed to work on Ideone.com.

Also note that leading and trailing newlines are significant in the code below.

Program A (Python 2): 638 587 566 550 bytes (UTF-8)

Python 2, Retina

U=unichr;s=U(39)*3;_=u'''\n#U=unichr;s=U(39)*3;_=u%s.replace(U(9),U(96));print _%%(s+_+s).replace(U(10),U(92)+'n').replace(U(96),U(9)).replace(U(178),U(179)).replace(U(183),U(184)).replace(U(182),U(183))#|¶#·print"Wrong language!"·#?.*t|"·¶#{2}|^.¶\n#1 #\n\n#T ²-¹ _o  [^¹]\nn=chr(10);print n+n.join(['print"Wrong language!"','#?.*t|"'])+n\n'''.replace(U(9),U(96));print _%(s+_+s).replace(U(10),U(92)+'n').replace(U(96),U(9)).replace(U(178),U(179)).replace(U(183),U(184)).replace(U(182),U(183))#|
#¶print"Wrong language!"¶#?.*t|"¶
#{2}|^.

Program B (Retina): 735 667 655 645 bytes (ISO 8859-1)

Retina, Python 2


#U=unichr;s=U(39)*3;_=u'''\n#U=unichr;s=U(39)*3;_=u%s.replace(U(9),U(96));print _%%(s+_+s).replace(U(10),U(92)+'n').replace(U(96),U(9)).replace(U(178),U(179)).replace(U(183),U(184)).replace(U(182),U(183))#|·#¸print"Wrong language!"¸#?.*t|"¸·#{2}|^.·\n#1   #\n\n#T ³-¹ _o  [^¹]\nn=chr(10);print n+n.join(['print"Wrong language!"','#?.*t|"'])+n\n'''.replace(U(9),U(96));print _%(s+_+s).replace(U(10),U(92)+'n').replace(U(96),U(9)).replace(U(178),U(179)).replace(U(183),U(184)).replace(U(182),U(183))#|¶#·print"Wrong language!"·#?.*t|"·¶#{2}|^.¶
#1`#

#T`²-¹`_o`[^¹]
n=chr(10);print n+n.join(['print"Wrong language!"','#?.*t|"'])+n

Program C:

Python 2, Retina

This can actually be made shorter using #!`W.*! instead of the last two lines, but this makes A and B longer, because having ` in a line where there wasn't one means I need to handle it differently (because the first backtick in a line in Retina is a configuration delimiter).


print"Wrong language!"
#?.*t|"




Explanation:

Program C:

                        # Retina: replace nothing with the Python code string
print"Wrong language!"  # >> code is executed if run in Python
#?.*t|"                 # Comment w/ '?' for Retina to skip, then replace up to the 't',
                        #    as well as any quotation marks, with nothing

I wrote Program C first during my first attempt and kept it mostly the same. In Python, it prints the string and ignores the comment. In Retina, it replaces nothing with print"Wrong language!" and then removes the parts around Wrong language!.

To better understand the complex programs, let's look at simplified versions:

Program A (simplified):

print"\n#PYTHON\n#1`#\n\n#T`²-¹`_o`[^¹]\nn=chr(10);print n+n.join(['print"Wrong language!"','#?.*t|"'])+n\n"#|
#¶print"Wrong language!"¶#?.*t|"¶
#{2}|^.

When I started over from scratch, I used the PYTHON bit as a placeholder for the code that should print Program A. This simpler version made it easier to explain how both Program B and Program C would be printed.

The print and everything inside is what prints Program B, but first, lets see how Program C is printed, because that's simple. After the print"..." is #|. This trick saved LOADS of difficulty that I experienced in my first attempt. This allows Retina to replace nothing with the 2nd line, which will be Program C, except there's a # in front. The last 2 lines remove that first #. I used #{2} to prevent the stage from removing all occurrences of #. I cannot use #1`# like I used in Program B, because it causes problems to have that backtick in the first line of Program A.

Which brings me to my next task, printing Program B. You may have noticed another difference from the actual code. There aren't backticks in the actual code, since I replaced them with tabs. I had to substitute a character, because any backtick would make the earlier code a configuration string in Retina, causing the syntax to be invalid. I chose tabs because they're visible and the code point is a single digit (9). The code prints Program B as shown in the simplified version below.

Program B:


#PYTHON
#1`#

#T`²-¹`_o`[^¹]
n=chr(10);print n+n.join(['print"Wrong language!"','#?.*t|"'])+n

The first two lines will replace nothing with the Python code, but with a # in front and some characters slightly different. This part is omitted for clarity. The next stage removes that first #. Then, I use a Transliteration (T) stage #T`²-¹`_o`[^¹] to undo some of the replace operations seen in the complete Program A. Using this stage is a way to output a literal pilcrow in Retina, which might otherwise be impossible.¹ It replaces · with , and ³ with ². Occurrences of ¹ will stay the same due to them being ignored with [^¹].

Program A:

Newlines and tabs have been added for readability.

U=unichr;s=U(39)*3;

_=u'''
    \n#U=unichr;s=U(39)*3;

    _=u%s.replace(U(9),U(96));

    print _%%(s+_+s)
    .replace(U(10),U(92)+'n').replace(U(96),U(9)).replace(U(178),U(179))
    .replace(U(183),U(184)).replace(U(182),U(183))#|

    ¶#·print"Wrong language!"·#?.*t|"·
    ¶#{2}|^.
    ¶

    \n#1    #\n\n#T ²-¹ _o  [^¹]\nn=chr(10);print n+n.join(['print"Wrong language!"','#?.*t|"'])+n\n'''

.replace(U(9),U(96));

print _%(s+_+s)
.replace(U(10),U(92)+'n').replace(U(96),U(9)).replace(U(178),U(179))
.replace(U(183),U(184)).replace(U(182),U(183))#|

#¶print"Wrong language!"¶#?.*t|"¶
#{2}|^.


This follows the general structure of the following Python quine:

_='_=%r;print _%%_';print _%_

When you add things before or after, you have to put them in the string, too.

U=unichr;_='U=unichr;_=%r;print(_%%_).replace('','')';print(_%_).replace('','')

I wanted to use a triple-quoted string to make it easy to include quotation marks (avoiding the use of backslashes). s=U(39)*3; is the string '''. I also used %s instead of %r, in order to avoid some problems with newlines or other characters being escaped with backslashes.

U=unichr;s=U(39)*3;_='''U=unichr;s=U(39)*3;_=%s;print(s+_%%_+s).replace('','')''';print(s+_%_+s).replace('','')

So now, the replacements. The first replacement .replace(U(9),U(96)); is there to replace tabs with the backticks that we see in Program B. This replacement is done before string formatting, because the tabs need to remain tabs in Program A. The other replacements are simply to avoid using certain characters in the 2nd line of Program B:

.replace(U(10),U(92)+'n')   # Replace newlines with a backslash and 'n', for B to print A.
.replace(U(96),U(9))        # Replace backticks with tabs for the first part of B.
.replace(U(178),U(179))     # Replace '²' with '³', which will be undone with B's T stage
.replace(U(183),U(184))     # Replace '·' with '¸', which will be undone with B's T stage
.replace(U(182),U(183))     # Replace '¶' with '·', which will be undone with B's T stage

These last three replacements anticipate the Transliteration stage in Program B, in order to prevent those characters from being either removed or transliterated when they shouldn't be.

The only other part of the code is the code from Program B that is essentially copied character-for-character, except for the changes due to the replacements.



¹ Thanks to Martin for his tip on how to output a literal in Retina. It made everything so much easier.

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

Befunge/Python, 381+485 259+345 229+304 = 533 bytes

Program A: Try in Befunge | Try in Python

#>21g::35*:*::":"%\>:#$":"%#\ \#%":"/#::$#-g#1\_#+\#5:#5_v
#v"50g"g12"'<:#>!#,_@<'tnirp"g12">:#,_@"+55"print "::g12$<
#>21g"Wrong language!"21g"g05"21g"[+5+5:]"21g"+55>#">:#,_@
print'''print'<@_,#!>#:<'"Wrong language!"[+5+5:]'''

Program B: Try in Python | Try in Befunge

#>55+"]:5+5+["50g"!egaugnal gnorW"50g"'<:#>!#,_@<'tnirp">:#,_@
print """#>21g::35*:*::":"%\>:#$":"%#\ \#%":"/#::$#-g#1\_#+\#5:#5_v
#v"50g"g12"'<:#>!#,_@<'tnirp"g12">:#,_@"+55"print "::g12$<
#>21g"Wrong language!"21g"g05"21g"[+5+5:]"21g"+55>#">:#,_@
print'''print'<@_,#!>#:<'"Wrong language!"[+5+5:]'''"""

Program C: Try in Befunge | Try in Python

print'<@_,#!>#:<'"Wrong language!"[+5+5:]

Explanation

Program C: This relies on the fact that Befunge-93 ignores unsupported instructions, so while the p harmlessly write a zero at 0;0, the rest of the print is ignored up until the < instruction which reverse the direction. Then flowing from right to left, the +5+5 pushes a 10 (linefeed) on to the stack followed by the message string, and then a standard output sequence is executed to write out the string. In Python it's just printing two string literals that are concatenated together, but the first one (containing the Befunge code) is sliced off by the array reference at the end ([+5+5:]).

Program B: The first line is a fairly basic Befunge sequence to print out Program C. The only interesting thing is the way it generates quote characters using 50g (i.e. reading the character from memory) which is more efficient than calculating the ASCII code. The #> (a bridge over the direction instruction) is essentially a nop that prevents the code being seen by Python since # is the Python comment character. The Python interpretation starts on line two and is simply printing a multiline string containing the source code of Program A.

Program A: In Python the first three lines are again ignored because they start with #, while the last line simply prints out Program C. The Befunge code snakes back and forth across the first three lines, building up the source for Program B on the stack in reverse order. It starts with three quotes, then a sequence that makes a copy of Program A's source, and finally what is essentially a hard coded string with the opening print """ and the first line of Befunge code. It's then just a matter of writing it out with a standard output sequence.

Some points of contention:

  1. I've been told that a quine using the g command is not considered a proper quine as far as this community is concerned. I'm not sure if that rule would apply to this challenge as well, but if so, this answer might not be considered a proper solution either.

  2. While I've said that Befunge-93 ignores unsupported instructions, that's not technically defined in the specification, and you'll need to use the -q (quiet) command line option in the reference interpreter to avoid warnings in Program C. Most other interpreters will be fine, though, but some of the flakier ones could potentially crash. Also note that Befunge-98 reflects on unsupported instructions, so a 98 interpreter will just loop indefinitely.

\$\endgroup\$
  • \$\begingroup\$ Explanation, please? \$\endgroup\$ – noɥʇʎԀʎzɐɹƆ Nov 20 '16 at 1:24
  • \$\begingroup\$ Is the -q flag actually "quite", or did you mean "quiet"? Mm-yes, this flag is quite useful. \$\endgroup\$ – mbomb007 Feb 8 '18 at 22:48
  • \$\begingroup\$ @mbomb007 Yes, that was a typo. Thanks for spotting that. \$\endgroup\$ – James Holderness Feb 11 '18 at 14:29
  • 1
    \$\begingroup\$ Funnily enough, -98 isn't bouncing off an unknown instruction. It's bouncing off the reflect instruction and the 0 that was put in the first cell \$\endgroup\$ – Jo King Feb 11 '18 at 23:02
1
\$\begingroup\$

Perl/JavaScript, 176 bytes + 176 bytes = 352 bytes

Don't think I can share 52 bytes off the underlying mechanism for the bounty, but I enjoyed building this. I think what I've produced meets the criteria...

Program A:

$P=1;$_='$L=eval("printf=console.log;J=``;q=_=>_+J;2")||1;$P?printf(q`$P=%s;$_=%s%s%s;eval($_)`,$P=$P==$L?J?2:1:0,$q=J?h^O:atob("Jw"),$_,$q):printf("Wrong language!")';eval($_)

Program B:

$P=2;$_='$L=eval("printf=console.log;J=``;q=_=>_+J;2")||1;$P?printf(q`$P=%s;$_=%s%s%s;eval($_)`,$P=$P==$L?J?2:1:0,$q=J?h^O:atob("Jw"),$_,$q):printf("Wrong language!")';eval($_)

Program C:

$P=0;$_='$L=eval("printf=console.log;J=``;q=_=>_+J;2")||1;$P?printf(q`$P=%s;$_=%s%s%s;eval($_)`,$P=$P==$L?J?2:1:0,$q=J?h^O:atob("Jw"),$_,$q):printf("Wrong language!")';eval($_)

Explanation

Uses my Perl/JavaScript polyquine as a basis but sets an additional variable $P which controls which program to generate. Uses the check that +[] is truthy in Perl, but falsy in JavaScript.

\$\endgroup\$

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.