title: Hunt the Wumpus

text:
# Question
Title: Hunt the Wumpus
When I was a lad, kids would wander into computer stores and play Hunt the Wumpus until the staff kicked us out. It was a simple game, programmable on the home computers of the mid-1970s, machines so rudimentary that instead of chicklet-sized microprocessors, I think some of them probably had real chicklets in there.

Let's evoke that bygone era by reproducing the game on modern hardware.

1. The player starts in a random room on an icosahedral map (thus there are 20 rooms in total, connected to each other like the faces of an icosahedron, and every room has exactly three exits).
2. The wumpus starts in a randomly selected different room. The wumpus stinks, and its odor can be detected in any of the three rooms adjacent to its location, though the direction of the odor is impossible for the player to determine. The game reports only "you smell a wumpus."
3. The player carries a bow and an infinite number of arrows, which he may shoot at any time into the room in front of him. If the wumpus is in that room, it dies and the player wins. If the wumpus was not in that room, it is startled and moves randomly into any of the three rooms connected to its current location.
4. One, randomly selected room (guaranteed not to be the room in which the player starts) contains a bottomless pit. If the player is in any room adjacent to the pit, he feels a breeze, but gets no clue as to which door the breeze came from. If he walks into the room with the pit, he dies and wumpus wins. The wumpus is unaffected by the pit.
5. If the player walks into the wumpus's room, or if the wumpus walks into the player's room, the wumpus wins.
6. The player specifies the direction he is facing with a number (1 = right, 2 = left, 3 = back), and then an action (4 = shoot an arrow, 5 = walk in the specified direction).
7. For the sake of scoring, each game string ("You feel a breeze," "You smell a wumpus," "Your arrow didn't hit anything", etc.) can be considered one byte. No abusing this to hide game code in text; this is just for interacting with the player.
8. Deduct 10% of your byte count for implementing megabats, which start in a random room different from the player (though they can share a room with the wumpus and/or the pit). If the player walks into the room with the bats, the bats will carry the player to another randomly selected room (guaranteed not to be the room with the pit or the wumpus in it), before flying off to their own, new random location. In the three rooms adjacent to the bats, they can be heard squeaking, but the player is given no information about which room the sound comes from.
9. Deduct 35% of your byte count for implementing a graphical interface that shows the icosahedral map and some kind of indication of the information the player has so far about the location of the pit, the wumpus, and the bats (if applicable), relative to the player. Obviously, if the wumpus moves or the player gets moved by the bats, the map needs to reset accordingly.
10. Lowest byte count, as adjusted, wins.

BASIC source code for a version of the game (not necessarily conforming to the rules above and, in any case, utterly ungolfed) can be found at this website and probably others.

# Answer
# GolfScript, 163

```
:n;:`"You shot the wumpus.
""The wumpus ate you.
""The pit swallowed you.
"{19:|rand}2*0|{[:,~,4%"ftvh"=.,+,@-]{20%}%}:^{;.^.+.3$?>"You feel a breeze.
"1$6"You smell a wumpus.
"4$8{$?-1>*p}2*'"#{'|):|';`head -1`}"'++~{3%}/={=3$=|{"Your shot missed.
"p@^3rand=@@}if}{=@;}if.[|4$6$]?.)!}do])=

```

The score is obtained by taking the byte count (290), adding the number of strings used for interaction with the user (6) and subtracting the combined length of those strings (133). The linefeeds are part of the strings and contribute to the byte count.

### Milestones

1. Ported professorfish's answer from Bash to GolfScript. **Score: 269**
2. Acted on Peter Taylor's suggestions in the comments. **Score: 250**
3. Peter Taylor refactored my entire code and helped me to compress the lookup table. **Score: 202**
4. Replaced the lookup table of adjacent rooms with a mathematical approach. **Score: 182**
5. Refactored input, output and the function supporting the mathematical approach. **Score: 163**

A big “Thank you!” goes to Peter Taylor for all his help.

### How it works

The 20 rooms are represented as the vertexes of a dodecahedron, which have been assigned numbers from 0 to 19 in the following fashion:

To find the rooms which are adjacent to room *N* and order them in clockwise fashion, we have to consider four cases:

* If *N ≡ 0 mod 4* (blue vertexes), the adjacent room are *19 - N*, *N + 2 mod 20* and *N - 2 mod 20*.
* If *N ≡ 1 mod 4* (green vertexes), the adjacent room are *19 - N*, *N - 4 mod 20* and *N + 4 mod 20*.
* If *N ≡ 2 mod 4* (yellow vertexes), the adjacent room are *19 - N*, *N - 2 mod 20* and *N + 2 mod 20*.
* If *N ≡ 3 mod 4* (red vertexes), the adjacent room are, *19 - N*, *N + 4 mod 20* and *N - 4 mod 20*.

```
# The function “p” is implemented as “{`print n print}”. By storing an empty string in
# “n” and nullifying “`”, “p” becomes an alias for “print”.

:n;:`

# Push the messages corresponding to the three possible outcomes of the game.

"You shot the wumpus.\n""The wumpus ate you.\n""The pit swallowed you.\n"

# Place the wumpus and the pit in randomly selected rooms different from room 19; place
# the player in room 19, with his back to room 0.

{19:|rand}2*0|

# Function “^” takes a single number as its argument and returns an array of all the
# adjacent rooms to the room that number corresponds to.

{

  [

    :,~       # Store the room number in “,” and negate it ( ~N ≡ 19 - N mod 20 )

    ,4%       # Push the room number modulus 4.

    "ftvh"=   # If it is equal to 0|1|2|3, push 102|116|118|104 ≡ 2|-4|-2|4 mod 20.

    .,+,@-    # Determine the room number plus and minus the integer from above.

  ]{20%}%     # Take all three room numbers modulus 20.

 }:^

{             # STACK: Strings Pit Wumpus Previous Current Function|Index

  ;           # STACK: Strings Pit Wumpus Previous Current

  # Find the adjacent rooms to the current room, duplicate them and remove the rooms
  # before the first occurrence of the previous room. Since the rooms are ordered in
  # clockwise fashion, the array of adjacent rooms will begin with the rooms
  # corresponding to the following directions: “Back Left Right”

  .^.+.3$?>   # STACK: Strings Pit Wumpus Previous Current Adjacent

  # Push two more messages and their respective triggers.

  "You feel a breeze.\n"1$6"You smell a wumpus.\n"4$8

  # STACK: ... Pit Wumpus Previous Current Adjacent String Adjacent 6 String Adjacent 8

  # Do the following twice: Duplicate the nth stack element and check if it's present in
  # the array of adjacent rooms. If so, print the string below it.

  {$?-1>*p}2*

  # Read one line (direction, action, LF) from STDIN. The counter “|” is needed so the
  # result won't get cached.

  '"#{'|):|';`head -1`}"'++~

  {3%}/       # Replace 1|2|3|4|5|LF with their character codes modulus 3 (1|2|0|1|2|1).

  ={          # If the player shoots an arrow:

    =3$=      # Determine the specified room and check if it corresponds to the wumpus.

      |       # If it does, push and invalid room number ( | > 19 ).

      # If it does not, say so and move the wumpus to a randomly selected adjacent room.

      {"Your shot missed."p@^3rand=@@}

    if

  }{           # If the player moves:

    =@;        # Place him into the selected room.

  }if

  # STACK: Pit Wumpus Previous Current Invalid?

  # Determine if the player's current room number is either invalid, the wumpus's room
  # number or the pit's room number (first match).

  .[|4$6$]?

  # If there is no match, the index is -1 and incrementing and negating it yields “true”.

  # STACK: Strings Pit Wumpus Precious Current Invalid? Index Boolean

# Repeat loop is the boolean is falsy. If repeated, the first instruction of the loop
# will pop the index.

}do

# Consolidate the entire stack into an array. And pop its last element: the index.
# Replace the array with the element corresponding to that index.

])=

# GolfScript will execute “print n print”.

```
> 22 votes

# Answer
# ~~REV0 C++ (Visual Studio on Windows) 405~~

```
#include"stdafx.h"
#include<stdlib.h>
#include<time.h>
int main(){srand(time(NULL));char i,h=rand()%19,w=rand()%19,p=19,d=0,q,e,m[]="e@LwQMQOSOLT";while(p-h&&p-w){for(i=3;i--;){q=(p+m[p%4*3+i])%20;if(q==w)puts("you smell a wumpus");if(q==h)puts("you feel a breeze");}scanf_s("%d",&i);e=(d+i/10)*m[p%4]%3;q=(p+m[p%4*3+e])%20;if(i%5){if(q==w){puts("YOU KILLED THE WUMPUS!");h=p;}else{puts("arrow missed");w=(w+m[w%4*3+rand()%3])%20;}}else{p=q;d=e;if(p==h)puts("YOU FELL IN A HOLE!");}if(p==w)puts("THE WUMPUS GOT YOU!");}}

```

Below is a playthrough, demonstrating that (provided you don't start right next to a hazard) with correct play you can always win. The player feels a breeze, turns back and does a complete counterclockwise loop. As it takes him exactly 5 moves to feel a breeze again, he knows the hole to his right, and gets as far away as possible. Similarly, when he smells the wumpus, not knowing whether it is right or left, he turns back and does a clockwise loop. It takes him 5 moves to smell the wumpus again, so he knows it is to the left and shoots with certainty.

If he had looped the other way he would have found the wumpus sooner and known it was in the same direction he was turning.

# ~~REV1 C (GCC on Cygwin), 431-35% bonus = 280.15~~

```
#define u(t,s,c) if(t){puts(s);c;}
i,d,e,a,b;main(){srand(time(0));char q,p=19,h=rand()%p,w=rand()%p,*m="e@LwQMQOSOLT-\\/\n \v ";
while(p-h&&p-w){
  for(i=3;i--;){q=(p+m[p%4*3+i])%20;u(q==w,"you smell a wumpus",a|=2<<p)u(q==h,"you feel a breeze",b|=1<<p)}
  for(i=20;i--;)printf("%c%c",i==p?m[d+12]:48+(a>>i&2)+(b>>i&1),m[i%4+15]);
  scanf("%d",&i);e=(d+i/10)*m[p%4]%3;q=(p+m[p%4*3+e])%20;
  if(i%5){u(q-w,"arrow missed",w=(w+m[w%4*3+rand()%3])%20;a=0)else u(1,"YOU KILLED THE WUMPUS!",h=p)}
  else{p=q;d=e;u(p==h,"YOU FELL IN A HOLE!",)}
  u(p==w,"THE WUMPUS GOT YOU!",)}}

```

Newlines added for clarity. The changes from Rev 0 are as follows:

A big thankyou to @Dennis for recommending GCC compiler on Cygwin Linux emulator for Windows. This compiler does not require the `include`s in the rev 0 program, and it allows default `int` type for variables and `main.` This is a life-changing golfing tip!

Additionally running in Linux means that `\f` does cause the cursor to move down without doing a carriage return (unlike in Windows where it just produces a printable symbol.) This has allowed considerable shortening of the printf statement that prints the board

Several additional tips from Dennis in the comments, and one of my own: change of condition when checking if arrow hit the wumpus: `if(q==w)`\>`if(q-w)` (..else.. is reversed)

Addition of graphic display showing the information the player knows about where a wumpus is smelt / a breeze is felt to claim the 35% bonus. (I deleted the old debug version of this which showed the exact position of the wumpus and hole. It can be seen in the edit history.)

# REV2 C (GCC on Cygwin), 389-35% bonus = 252.85

```
#define Q(N) (N+"QTLOQMQOSOLT"[N%4*3+e])%20
#define P printf(
i,d,e,a,b;main(){int p=19,q=srand(&p),h=rand()%p,w=rand()%p;
while(p-h&&p-w){
  for(e=3;e--;){q=Q(p);q-w||P"You smell a wumpus\n",a|=2<<p);q-h||P"You feel a breeze\n",b|=1<<p);}
  for(i=20;i--;)P"%c%c",i-p?48+(a>>i&2)+(b>>i&1):"-\\/"[d],"\n \v "[i%4]);
  scanf("%d",&i);e=(d+i/9)*"edde"[p%4]%3;q=Q(p);
  if(i%5){e=rand()%3;w=q-w?P"Your arrow didn't hit anything\n",a=0)&Q(w):(p=20);}
  else p=q,d=e;
}
P p-20?p-w?"YOU FELL IN A HOLE!\n":"THE WUMPUS GOT YOU!\n":"YOU KILLED THE WUMPUS!\n");}

```

Thanks again to Dennis for refactoring my code:

Char constant `m[]` replaced with literals (I didn't know you could index a literal.)

Seeding of random numbers with stack variable (system dependent, some systems randomise memory allocation as a security measure.)

Macro with `puts` replaced with a macro with `printf` and additional code which must be executed when the message displayed placed inside `printf` arguments (advantage taken of the face that printf does not print the last few arguments if there aren't enough format specfiers in the format string.) `if` replaced by `||`

Calculation of new position of player/wumpus placed inside new macro.

Win/lose messages placed outside `while` loop. `if` replaced by conditional operator.

Use of conditional operator in line for shooting arrow. If the player misses, this requires both printing a message and adjusting wumpus position. Dennis offered a couple of ways of combining `printf` and the calculation of wumpus position into a single expression, but I have gone with one of my own. `printf` returns the number of characters printed, which for `Your arrow didn't hit anything\n` is 31 (11111 binary.) So, `31&Q(w)==Q(w)`.

My other contribution to this edit has been elimination of some unnecessary brackets.

**Output**

Here the player has already found where the Wumpus is, but chooses to do a thorough explore to find out exactly where the pit is, too. Unlike my old debug version which showed where the wumpus and pit were throughout the game, this shows only the rooms where the player has visited and felt a breeze (1) smelt the wumpus (2) or both (3). (If the player shoots an arrow and misses, the variable `a` containing the wumpus position info is reset.)

**ICOSAHEDRON REPRESENTATION**

*Note: this section is based on rev 1*

My star feature! There is no graph in my code. To explain how it works, see the world map below. Any point on the icosahedron can be represented by a latitude 0-3 and a longitude 0-4 (or a single number, `long*4+lat`.) The longitude line marked on the map passes only through those faces with longitude zero, and the latitude line passes through the centre of the faces with latitude zero.

The player can be oriented on 3 possible axes, represented by the symbols as follows: north-south`-` northeast-southwest`\` northwest-southeast `/`. In any given room he has exactly one exit on each of these axes available to him. In the display shown the player makes a complete clockwise loop. It is generally easy to identify from the player marking where he came from, and therefore where he is allowed to go to.

*The one case that is a little difficult for the uninitiated eye is the fourth one. When you see a slant in one of these polar rows, the player has come from the polar cell nearest the outside end of the slant and is facing generally towards the equator. Thus the player is facing southeast and his options are: 15(SOUTH, the cell to the right) 25(northEAST, the cell above) or 35(northWEST, the cell below.)*

So, basically I map the icosahedron to a 5x4 grid, with cells numbered 19 to 0 in the order they are printed. The move is made by adding or subtracting from the current position, depending on the player's latitude and direction, per the table below.

If the player goes off the bottom (west) of the board, he comes back on the top (east) side and vice versa, so his position is taken modulo 20. Generally the moves are coded into m\[\] by adding ascii 80 (`P`) to the raw value giving the characters shown below, but principle any multiple of 20 can be added without affecting the operation.

```
Table of addition values for moves

Direction Symbol Latitude 0  1  2  3     Latitude 0 1 2 3

0, N-S      -             1 -1  1 -1              Q O Q O
1, NE-SW    \            -4  1 -1  4              L Q O T
2, NW-SE    /             4 -3  3 -4              T M S L

```

The player's input (divided by 10 to remove the second digit) is added to his current direction and taken modulo 3 to get his new direction. This works fine in the majority of cases. However there is an issue when he is in a polar room and moves toward the pole. It will be clear when folding the map below that if he leaves the room facing "northeast" he will enter the new square facing "southeast" so a correction must be made. This is done in the line `e=(d+i/10)*m[p%4]%3;` by the multiplication by `m[p%4]`. The first four values of m\[\] are selected such that, in addition to their function above, they also have the characteristic `m[1]%3==m[2]%3==1` and `m[0]%3==m[3]%3==2`. This leaves the direction alone for the equatorial rooms and applies the necessary correction for polar rooms.

The logical time to do the correction would be after the move. However to save characters it is done before the move. Therefore certain values in m\[\] must be transposed. So the last 2 characters are `LT` instead of `TL` per the table above for example.

**UNGOLFED CODE**

*this is rev 1 code, which is less obfuscated than rev 2.*

This will run on GCC / Linux. I have included in the comments the extra code needed to make it run on Visual studio / Windows. It's a big difference!

```
//Runs on gcc/linux. For visual studio / windows, change printf(...)
//to printf(" %c%c%c",9*(i%4==1),i==p?m[d+12]:48+(a>>i&2)+(b>>i&1),10*!(i%2)) and uncomment the following lines
//#include"stdafx.h"
//#include<stdlib.h>
//#include<time.h>
//#pragma warning(once:996;once:430) //allow the use of scanf instead of scanf_s, allow default type=int.
//Though rather than using the pragma, it is shorter to follow compiler recommendation and use scanf_s and int.

#define u(t,s,c) if(t){puts(s);c;}  //if(test){puts(string);additional code;}

i,     //player input, loop counter
d,e,   //current and proposed direction
a,b;   //bit flags for where wumpus smelt / breeze felt

main(){
    srand(time(0));
    char q,p=19,h=rand()%p,w=rand()%p,  //Initialise player, hole and wumpus. q stores proposed player position.
    *m="e@LwQMQOSOLT-\\/\n \f ";        //Chars 0-11: movetable. Chars 12-14:symbol for player. Chars 15-18: graphics format.

    while(p-h&&p-w){

        // Print warnings
        for(i=3;i--;){q=(p+m[p%4*3+i])%20;u(q==w,"you smell a wumpus",a|=2<<p)u(q==h,"you feel a breeze",b|=1<<p)}

        // graphic display
        for(i=20;i--;)printf("%c%c",i==p?m[d+12]:48+(a>>i&2)+(b>>i&1),m[i%4+15]);

        // Get player input and work out direction and room
        scanf("%d",&i);
        e=(d+i/10)*m[p%4]%3;
        q=(p+m[p%4*3+e])%20;

        // i%5 is false if player inputs 5 (move player) otherwise true (shoot arrow)
        if(i%5)
        {u(q-w,"arrow missed",w=(w+m[w%4*3+rand()%3])%20;a=0)else u(1,"YOU KILLED THE WUMPUS!",h=p)}
        else{p=q;d=e;u(p==h,"YOU FELL IN A HOLE!",)}
        u(p==w,"THE WUMPUS GOT YOU!",)
    }

}

```

**ISSUES AND CURIOISITIES**

I have taken advantage of the point mentioned by @professorfish, if the wumpus and pit start in random places, there is no need for the player to start in a random place. The player always starts in room 19 facing north.

I understand that as the wumpus is "unaffected by the pit" the wumpus can start in, or enter the room where the pit is. In general this simplifies things except for one point. I have no specific variable to indicate the game is over; it is over when the player coincides with the wumpus or pit. So when the player wins I display the winning message but move the pit to the player to kludge out of the loop! I can't put the player in the pit as the wumpus might be there and I would get a message about the wumpus that I don't want.

The rev0program worked perfectly in visual studio, but the IDE said "stack corrupted around variable i" on exit. This is because scanf is trying to put an `int` into a `char.` Dennis reported incorrect behaviour on his Linux machine because of this. *Anyway it is fixed by use of the correct type in rev 1.*

The line for displaying the board in rev 0 is clumsy and appears slightly different on other platforms. In `printf(" %c%c%c")` the middle %c is the printable character displayed. The last %c is either ASCII 0 or ASCII 10 (\n, newline with carriage return in Windows.) There appears to be no character in Windows that works in the console, that will go down a line without giving a carriage return. If there was I wouldn't need the first c% (ASCII 0, or ASCII 9 tab before latitude 1 character. Tabs are notoriously undefined in their behaviour.) The leading space improves formatting (puts latitude 3 & 2 characters nearer latitude 1 character.) *Rev 1 has a revison of this line which uses a \f formfeed character and therefore needs no format character at the start of the printf. This makes it shorter, but the \f does not work in Windows.*
> 15 votes

# Answer
### GolfScript, 269 characters

```
{puts}:|;20,{;9{rand}:r~}$3<(:>"B:%d`w85>2n+Fup`y/>@D-=J7ldnx/W5XsLAb8~"{32-}%"`\24"{base}/3/{[.[~@].[~@]]}%:A=3r=0=:F;~:W;:P;{>A={0=F=}?:^P&!!{"You feel a breeze"|}*^W&!!{"You smell a wumpus"|}*'"#{'9.?r';STDIN.gets()}"'++~);(3%^=\4`={W={"Your arrow hit the wumpus"|0}{"Your arrow didn't hit anything"|W A=0=3r=:W>=.!\{"The wumpus catches you"|}*}if}{>:F;:>W=.!\{"You ran into the wumpus"|}*>P=.!\{"You fell into the pit"|}*&}if}do

```

Note that 163 was subtracted from the character count for the hard-coded strings. If you want debug output indicating the room numbers add the following line right after the first occurence of `^`:

```
'  YOU 'F'->'>+++puts'  DIRECTIONS [BRL] '^`+puts'  PIT 'P+puts'  WUMPUS 'W+puts

```

An example session (with additional debug output):

```
  YOU 6->11
  DIRECTIONS [BRL] [6 7 16]
  PIT 7
  WUMPUS 5
You feel a breeze
25
  YOU 11->16
  DIRECTIONS [BRL] [11 17 15]
  PIT 7
  WUMPUS 5
35
  YOU 16->11
  DIRECTIONS [BRL] [16 6 7]
  PIT 7
  WUMPUS 5
You feel a breeze
15
  YOU 11->6
  DIRECTIONS [BRL] [11 10 1]
  PIT 7
  WUMPUS 5
15
  YOU 6->10
  DIRECTIONS [BRL] [6 15 5]
  PIT 7
  WUMPUS 5
You smell a wumpus
14
Your arrow didn't hit anything
  YOU 6->10
  DIRECTIONS [BRL] [6 15 5]
  PIT 7
  WUMPUS 0
25
  YOU 10->5
  DIRECTIONS [BRL] [10 14 0]
  PIT 7
  WUMPUS 0
You smell a wumpus
24
Your arrow hit the wumpus

```
> 9 votes

# Answer
# Bash, 365 (first working version 726!)

CATCHING UP WITH GOLFSCRIPT?

**@Dennis has basically done all the golfing for me. Thanks!**

The program assumes valid input. Valid input is the direction you choose (1 for right, 2 for left, 3 for back) followed by your action (4 to shoot, 5 to walk).

## Some Explanation

I normally do big verbose explanations, but this is probably a bit too complicated for me to be bothered.

Each vertex on the dodecahedron graph is encoded as a letter (a=1, b=2, ... t=20).

The player's starting position is always 20 (and they are standing with their back to 18), since that doesn't matter in itself, only the relative positions of the player, pit and wumpus matter.

The variable `$p` stores the player's location. `$r` stores the player's previous location. `$w` is the wumpus and `$h` (H for hole) is the pit.

## Code

```
p=t
r=r
j=echo
Z=npoemfsgnohtksblbtpckdpljqnriogelfhkbqrcaiadjhagimsmjtqecrdf
q(){ $j ${Z:RANDOM%19*3:1};}
C(){ [[ ${!1} =~ ${!2} ]];}
d(){ s=${Z:30#$1*3-30:3};}
w=`q`
h=`q`
for((;;));{
b=$p
d $p
u=u${s#*$r}$s
C w p&&$j The wumpus ate you&&exit
C h p&&$j You fell in the pit&&exit
C u w&&$j You smell the wumpus
C u h&&$j You feel a breeze from a pit
read i
F=5
y=${u:i/10:1};C i F&&p=$y&&r=$b||{ d $w;C y w&&$j You killed the wumpus&&exit;$j You missed;w=${s:RANDOM%3:1};};}

```

## Version History

1. Initial release, 698 chars
2. Fixed bug where "You feel a breeze" and "You smell the wumpus" can't display at the same time; saved 39 chars by making the random number generation a function.
3. Remembered that the wumpus moves if you shoot and miss. 726 chars.
4. Made `grep -oE` a variable. Saved 5 chars.
5. Made `[a-z]{3}` a variable. Saved 3 chars.
6. Made `echo` a variable. Saved 5 chars.
7. Acted on most of @Dennis 's suggestions. Saved 72 chars.
8. Added all remaining suggestions. Saved 68 chars.
9. Saved 2 chars from @DigitalTrauma 's suggestion.
10. Fixed a major bug where you can only shoot the wumpus if it is on the right. Same character count.
11. Used parameter expansion to shave off 2 chars using `$m`.
12. Shaved off a lot of chars by ditching `grep` and being slightly more sensible.
13. Defined `C` as a regexp search function to use in if statements, and `E` as a function printing "You killed the wumpus" and exiting.
14. Saved 1 char by "if statement" rearrangement.
15. Saved a lot of chars by getting rid of `d`, and removed unnecessary brackets.
16. Fixed bugs. Added lots of chars :(
17. MOARR SAVINGS (http://xkcd.com/1296/)
18. Another of @Dennis 's ideas (saving a few chars), and my crafty (ab)use of indirection (saving 1 char).
19. Style fix for q().
20. re-added proper output

## Sample run

"In:" is input, "Out: is output".

The player wanders around for a bit, smells the wumpus and shoots. They miss, and the wumpus comes into their room and eats them.

> In: 15
>
> In: 15
>
> In: 25
>
> In: 25
>
> In: 15
>
> Out: You smell the wumpus
>
> In: 14
>
> Out: You missed
>
> Out: The wumpus ate you
> 9 votes

# Answer
# JavaScript (ECMAScript 6) - ~~2197~~ 1759 -45% = 967.45 Characters

Nearly finished golfing this...

Includes a GUI with an Icosahedral Map and Mega-Bats for the full bonuses.

* Each room has 4 buttons: `X` (the Pit); `B` (the Mega-Bat); `W` (the Wumpus); and `P` (You).
* Your current location is coloured blue.
* The buttons are coloured red if the object it represents could be in that location and green if it is definitely not in that location.
* The `W` and `P` buttons can be clicked only in the rooms adjacent to your current location.
* If you win the background turns green and if you die the background turns red.

**Code:**

```
P=x=>parseInt(x,36);Q=(y,a=4)=>[P(x)<<a for(x of y)];e=Q("def45c6di7ej1ai1bj2af3bf9dg8eh46b57a1gh0280390678ci9cj24g35h",0);X=Q("o6fl6afnik27bloscfaf");Y=Q("icp8i8t4jej4encjjan6");A='appendChild';C='createElement';W='width';H='height';G='background-color';L='disabled';I='innerHTML';N='className';D=document;R=Math.random;B=D.body;E=[];F=1<0;T=!F;Z="XBWP";s=D[C]('style');s.type='text/css';t='.A{position:absolute;left:25px;top:25px}.D{'+W+':50px;'+H+':50px}.D button{'+W+':25px;'+H+':25px;float:left}.R{'+G+':red}.G{'+G+':green}.B{'+G+':blue}';for(i in X)t+='#D'+i+'{left:'+X[i]+'px;top:'+Y[i]+'px}';s[A](D.createTextNode(t));D.head[A](s);c=D[C]('canvas');c[N]='A';c[W]=c[H]=500;B[A](c);x=c.getContext('2d');x.beginPath();d=(i,b,v)=>{for(j=0;j<3;j++){E[e[3*i+j]][b][L]=v}};a=(i,l,v)=>{t=F;for(j=0;j<3;j++)t=e[3*i+j]==l?T:t;if(t)M[v]++;b=E[i][v];b.c=-1;for(j=0;j<3;j++)E[e[3*i+j]][v].c+=t?1:-1;for(j of E)j[v][N]=j[v].c==M[v]?'R':'G';};M=[0,0,0];S=v=>{M[v]=0;for(i of E){i[v][N]='';i[v].c=0}};for(i in X){for(j=3*i;j<3*i+3;j++)x.moveTo(X[i],Y[i])|x.lineTo(X[e[j]],Y[e[j]]);B[A](v=D[C]('div'));v[N]='A D';v.id='D'+i;E[i]=[];for(j in Z){b=E[i][j]=v[A](D[C]('button'));b[L]=T;b.i=i;b.c=0;b[I]=Z[j];}E[i][4][O='onclick']=function(){d(P,2,T);d(P,3,T);if(this.i==W)c[N]+=' G';else{S(2);W=e[3*W+R()*3|0];if(W==P)c[N]+=' R';else{a(P,W,2);d(P,2,F);d(P,3,F)}}};E[i][3][O]=function(){d(P,2,T);d(P,3,T);E[P][3][N]='';P=this.i;if(W==P||Q==P){c[N]+=' R';return}else if(Z==P){j=P;do{P=R()*20|0}while(P==W||P==Q||P==j);do{Z=R()*20|0}while(Z==j||Z==P);S(1)}d(P,2,F);d(P,3,F);E[P][3][N]='B';a(P,Q,0);a(P,Z,1);a(P,W,2)}}x.stroke();P=R()*20|0;do{W=R()*20|0}while(W==P);do{Q=R()*20|0}while(Q==P);do{Z=R()*20|0}while(Z==P);E[P][3][N]='B';a(P,Q,0);a(P,Z,1);a(P,W,2);d(P,2,F);d(P,3,F)

```
> 9 votes

# Answer
## GolfScript (206 198)

```
[5:C,]{{.{[~@]}:>~.{-1%}:<~}%.&}8*({[.<><.<><]}:F~-{99rand}$~5,{.<{>.'You smell a wumpus.\n'4{$F@?~!!*}:Q~{print}:,~}3*{>.'You feel a breeze.\n'5Q,}3*'"#{'C):C';STDIN.gets()}"'++~~:&9/{>}*&5%{'You killed the wumpus.'3Q{\<{>}3rand*\"Your arrow didn't hit anything.\n",0}or}{\;.'You fell into the pit.'4Q}if\.'You were killed by the wumpus.'4Q@or:n!}do];

```

Finally caught up with Dennis' lookup table version, from which it borrows quite a bit. The interesting thing about this version is that it doesn't have a lookup table for the room layout.

The 60 rotational symmetries of an icosahedron are isomorphic to the alternating group on 5 letters, A\_5. After trying all kinds of approaches to representing the group compactly, I've come back to the simplest one: each element is a permutation of even parity. The group can be generated from two generators in more than one way: the approach I'm taking uses the generators `3` and `3 1`. These allow us to generate `1 = 3 3 1`, `2 = 3 3 1 3 1`, and `3 = 3`.

Observe that direction `3` corresponds to an element of order 2, because after going through the door behind you, that door is behind you again. Direction `1` corresponds to an element of order 5, walking around a vertex of the icosahedron. (Similarly element `2`). And the combination `3 1` is of order 3, as it cycles round the rooms adjacent to the one which starts out behind you.

So we're looking for a permutation of order 2 to represent direction `3` and a permutation of order 5 to represent direction `1` such that `3 1` is of order 3.

There are 15 permutations of order 2 in A\_5, and for each one there are 8 candidate permutations for `1` (and hence for `3 1`). There's an obvious attraction to `[4 3 2 1 0]` for `3`: reversing an array is just `-1%`. Of its possible companion permutations `3 1` I've chosen `[0 1 3 4 2]`, which admits a fairly short implementation as `[~@]`.

### Ungolfed

```
# Generate the 60 permutations by repeated application of `3 1` and `3`
[5:C,]{{.{[~@]}:>~.{-1%}:<~}%.&}8*
# Remove [0 1 2 3 4] and its equivalence class (apply 3 (3 1)^n 3 for n in 0,1,2)
({[.<><.<><]}:F~-
# Shuffle the remaining 57 options to select random starting points for wumpus and pit
# Note that this introduces a slight bias against them being in the same room,
# but it's still possible.
{99rand}$~
# Start player at [0 1 2 3 4]
5,
{
    # Stack: Pit Wumpus Player
    .<
    # The adjacent rooms to the player are Player<> , Player<>> , and Player<>>>
    # If the wumpus is in one of those rooms, say so.
    {
        >."You smell a wumpus.\n"4
        {
            # ... X str off
            $F@?~!!*
            # ... str off$F X ?~!! *
            # Which means that we leave either str (if off$ and X are equivalent)
            # or the empty string on the stack
        }:Q~
        {print}:,~
    }3*
    # Ditto for the pit
    {>."You feel a breeze.\n"5Q,}3*
    # Read one line from STDIN.
    '"#{'C):C';STDIN.gets()}"'++~~
    # Stack: Pit Wumpus Player Player< Input
    # Find the room corresponding to the specified direction.
    :&9/{>}*&
    # Stack: Pit Wumpus Player TargetRoom Input
    5%{
        # Shoots:
        "You killed the wumpus."3Q
        {
            \<{>}3rand*\ # Move the wumpus to an adjacent room
            "Your arrow didn't hit anything.\n", # Inform
            0 # Continue
        }
        or
    }{
        # Moves:
        \;
        # If player and pit share a room, say so.
        ."You fell into the pit."4Q
    }if
    # If player and wumpus share a room, say so.
    # NB If the player walks into a room with the pit and the wumpus,
    # the `or` favours the pit death.
    \."You were killed by the wumpus."4Q@or
    # Save the topmost element of the stack for output if we break the loop. Loop if it's falsy.
    :n!
}do
# Ditch the junk.
];

```
> 6 votes

# Answer
## Wumpus, 384 - 129 (strings) = 255 bytes

```
1SDL2vSD70L?.;;3AL1a!?,9)".supmuw a llems uoY"99+1.
II5x?,&WC2.           L2a!?,9)".ezeerb a leef uoY"93*2.
L1a!,FCFC[&WCL1a!?,"!supm",AW#16#[(=]?.;;l(&o1.
    ?,".uoy eta ",".gnih","uw eht dellik uoY"#22&oN@
     #15#L2a!?. ,"supmu","tyna tih t'ndid worra ruoY"#31&oND";"4L1a!?.;;L1xSUL1xSD=F-#81~4~?.;;;CCWC=F-#97~4~?.;;;2.
 ,"nto the pit."|       "w ehT"l&oN@
 |"i llef uoY"l2-&oN@

```

Try it online! (Of course, TIO doesn't make a lot of sense, because you can't use the program interactively there, and once the program runs out of instructions on STDIN it will read `0 0`, which is equivalent to `3 4`, so you'll end up shooting arrows until the Wumpus moves there or kills you.)

When running this locally, make sure that the linefeed after the second number of each input gets flushed (because Wumpus needs it to determine that the number is over). In Powershell, I somehow need to enter one more character after the linefeed to make it work (doesn't matter which character, but I just used double linefeeds for testing).

There's a lot of room for golfing this further, but trying completely new layouts takes a while. The final score also depends a lot on the actual strings I use, because in a 2D language, a string of N bytes tends to cost you more than N bytes of source code, because it puts significant constraints on the code layout, and you often need to split it into multiple sections (incurring additional double quotes). At the extreme end, if I reduced every string to a single letter (and the -129 to -12), I'd probably be saving a ton of bytes.

### Explanation

First a disclaimer: despite the language's name, it was *not* designed to make implementing *Hunt the Wumpus* particularly easy. Instead, I first designed the language around the theme of triangles, ended up with an icosahedral data structure, and decided to call it Wumpus because of that.

So yeah, while Wumpus is mainly stack-based, it also has 20 registers which are arranged around the faces of an icosahedron. That means, we get a data structure to represent the map for free. The only thing we can't do easily is find specific faces on the icosahedron, so to search for them, we need to "roll the d20" until we end up on the face we're looking for. (It's possible to do this in a deterministic way, but that would take a lot more bytes.) Searching for faces like this terminates almost surely (i.e. with probability 1), so the search running forever is not a concern in practice).

The above code is a golfed version of this first implementation with a saner layout:

```
1SDL2vSD70L?.;;2.  < Setup; jumps to third line which starts the main loop

3AL1a! ?,".supmuw a llems uoY"#19&oN03.          < This section checks the player's surroundings.
        L2a!?,".ezeerb a leef uoY"#18&oN04.
             AW(=12[?.;;7.

    }&WC#11.                                     < This section reads the input. The top branch moves, the bottom branch shoots
II5x^                                              and kills or moves the wumpus.
     {FCFC[&WCL1a !?,"!supmuw eht dellik uoY"#22&oN@
                    ".gnihtyna tih t'ndid worra ruoY"#31&oND#59 9L1a!?.;;L1xSUL1xSD=F-#82~9~?.;;;CCWC=F-#98~9~?.;;;#11.

L1a!?,".uoy eta supmuw ehT"#19&oN@               < This section checks whether the player dies.
     L2a!?,".tip eht otni llef uoY"#22&oN@         Otherwise, we return back to the third line.
          2.

```

Since the golfing mostly involved compressing the layout, I'll just explain this version for now (until I add any golfing tricks that go beyond restructuring the code).

Let's start with the setup code:

```
1SDL2vSD70L?.;;2.

```

Initially, all faces are set to **0**. We'll encode the wumpus by setting the 1-bit of the corresponding face, and the pit by setting the 2-bit. This way, they can both be in the same room. The player's position will not be recorded on the icosahedron at all, instead it will always be active face (only one of the 20 registers is active at a time).

```
1S     Store a 1 in the initially active face to put the wumpus there.
D      Roll the d20. Applies a uniformly random rotation to the icosahedron.
L2vS   Load the value of that face (in case it's the wumpus's), set the 2-bit
       and store the result back on that face.

```

Now we need to find a random empty face to put the player in.

```
D      Roll the D20.
70     Push 7 and 0 which are the coordinates of the D in the program.
L      Load the value of the current face.
?.     If that value is non-zero (i.e. the active face has either the
       wumpus or the pit), jump back to the D to reroll the die.
;;2.   Otherwise, discard the 0 and the 7 and jump to (0, 2), which is
       the beginning of the main loop.

```

This next section checks the player's surroundings and prints the appropriate warnings:

```
3AL1a! ?,".supmuw a llems uoY"#19&oN03.
        L2a!?,".ezeerb a leef uoY"#18&oN04.
             AW(=12[?.;;7.

```

This is a loop which we run through 3 times. Each time, we look at the right neighbour, print the appropriate string(s) if there's a hazard and then rotate the icosahedron by 120°.

```
3    Push a 3 as a loop counter.
A    Tip the icosahedron onto the NW neighbour of the active face, which
     will be used to represent the right-hand room.
L1a  Extract the 1-bit of the value on that face.
!?,  If that value is zero, strafe to the next line, otherwise continue.

  ".supmuw a llems uoY"#19&oN03.
     Print "You smell a wumpus.", a linefeed and then jump to the next line.

L2a  Extract the 2-bit of the value on that face.
!?,  If that value is zero, strafe to the next line, otherwise continue.

  ".ezeerb a leef uoY"#18&oN04.
     Print "You feel a breeze.", a linefeed and then jump to the next line.
A    Tip back to the original active room (where the player is).
W    Rotate the icosahedron by 120°, so that the next iteration checks
     another neighbour.
(=   Decrement the loop counter and duplicate it.
12   Push 1, 2, the coordinates of the cell after the 3 (the loop counter).
[    Pull up one copy of the loop counter.
?.   If it's non-zero, jump to the beginning of the loop, otherwise continue.
;;7. Discard the 2 and the 1 and jump to (0, 7), which reads the player's
     input for this turn.

```

The next section reads two numbers from the player and then either moves the player or shoots an arrow. The former is trivial, the latter less so. The main issue for shooting the arrow is the case where it misses. In that case we a) need to go looking for the wumpus to move it, and then b) return to the player's room *and* the correct orientation of the icosahedron (so that "back" remains "back"). This is the most expensive part of the entire program.

```
    }&WC#11.
II5x^
     {FCFC[&WCL1a !?,"!supmuw eht dellik uoY"#22&oN@
                    ".gnihtyna tih t'ndid worra ruoY"#31&oND#59 9L1a!?.;;L1xSUL1xSD=F-#82~9~?.;;;CCWC=F-#98~9~?.;;;#11.

```

The entry point to this section is the `I` on the left.

```
II   Read the integers from STDIN.
5x   XOR the second one with 5.
^    Turn either left or right, depending on the previous result. If the
     second input is 4, XORing with 5 gives 1 and the IP turns right.
     Otherwise, we get 0 and the IP turns left.

If the player entered 5, move:

}    Turn right so that the IP moves east again.
&W   If the room indicator is X, rotate the icosahedron by X*120°. This
     puts the target room south of the active face (where the back room
     normally is).
C    Tip the icosahedron onto the southern face. This moves the player there.
     Due to the way tipping works, the formerly active face will now be
     the southern neighbour, i.e. correctly at the back of the player.
#11. Jump to (0, 11), the final section which checks whether the player
     stepped into the pit or onto the wumpus.

If the player entered 4, move:

{    Turn left so that the IP moves east again.
F    Store the active face index (the player's position) on the stack.
CFC  Also store the face index of the southern neighbour (the back room)
     on the stack, so that we can recover the correct orientation if
     we need to.
[    Pull up the player's room choice.
&WC  Tip the icosahedron onto the corresponding face (same as for the move action)
L1a  Extract the 1-bit of the value on that face to check whether the arrow
     hit the wumpus.
!?,  If that value is zero, strafe to the next line, otherwise continue.

  "!supmuw eht dellik uoY"#22&oN@
     Print "You killed the wumpus.", a linefeed, and terminate the program.

".gnihtyna tih t'ndid worra ruoY"#31&oN
     Print "Your arrow didn't hit anything." and a linefeed.

This next bit is a loop which searches for the wumpus:

D    Roll the d20. The easiest way to search for the wumpus is to look at
     random faces.
#59 9
     Push 59 and 9, the coordinates of the beginning of this loop.
L1a  Extract the 1-bit of the value on the current face.
!?.  If that value is zero, jump back to the beginning of this loop to
     try another face, otherwise continue.
;;   Discard the 9 and the 59.
L1xS Unset the 1-bit of the current face to remove the wumpus there.
U    Tip the icosahedron onto a random neighbouring face. This moves us
     to a random adjacent room.
L1xS Set the 1-bit of the current face to put the wumpus there.

This next bit contains two loops which get us back to the player's room
with the correct orientation. We do this by first searching for the room
at the player's back, and then looking through its neighbours to find the
player's room.

D    Roll the d20.
=F-  Duplicate the back room index and subtract the current face index.
#82~9~
     Push 82 and 9 and pull up the difference we just computed.
?.   If the difference is non-zero (we've got the wrong room), jump back
     to the D to try again. Otherwise continue.
;;;  We've found the back room. Discard the 9, the 82 and the back room index.
C    Tip the icosahedron onto the southern face (one of the candidate
     neighbours which might be the player's room).
CWC  This begins the loop that searches for the player's room. Tip onto
     the back room, rotate by 120°, tip back. This cycles through the
     neighbours of the back room, while keeping the active face on those
     neighbours.
=F-  Duplicate the player's room index and subtract the current face index.
#98~9~
     Push 98 and 9 and pull up the difference we just computed.
?.   If the difference is non-zero (we've got the wrong room), jump back
     to the CWC to try again. Otherwise continue.
;;;  We've found the player's room and since we entered from the back room
     via C, we've also got the correct orientation. Discard the 9, the 98
     and the player's room index.
#11. Jump to (0, 11), the final section which checks whether the player
     stepped into the pit or onto the wumpus.

```

Phew, that was the hard part. Now we just need to check whether the player dies and otherwise start over the main loop:

```
L1a!?,".uoy eta supmuw ehT"#19&oN@
     L2a!?,".tip eht otni llef uoY"#22&oN@
          2.

```

The structure of this section is essentially identical to the structure we used when checking the player's surroundings: we check the 1-bit of the current face (the player's room) and if it's set we print `The wumpus ate you.` and terminate the program. Otherwise, we check the 2-bit and it's set we print `You fell into the pit.` and terminate the program. Otherwise we reach the `2.` which jumps back to the beginning of the main loop (at coordinates `(0, 2)`).
> 6 votes

# Answer
# awk - big

This didn't turn out as short as I had hoped, but I took a slightly different approach to dealing with the graph, so I'm posting the ungolfed version anyway.

I took advantage of the fact that an icosahedron (20 sided polyhedron) under rotations preserving orientation is isomorphic to the alternating group of degree 5 (5 element permutations having an even number of even length cycles). I then choose two permutations with cycle length 5 as "left" and "right", and I choose one permutation with cycle length 2 as "back". Using these, I build up the graph from one room by walking the Hamiltonian path (2xRRRLLLRLRL, using 3xRB in each room to capture the 3 possible directions).

```
function meta(z,a,b,c,d) {
    if(z==COMPOSE) {
        split(a,c,"");
        split(b,d,"");
        return c[d[1]]c[d[2]]c[d[3]]c[d[4]]c[d[5]];
    }
    if(z==WALK) {
        split(R" "R" "R" "L" "L" "L" "R" "L" "R" "L,c);
        for(b = 1; b <= 20; b++) {
            map[a] = b;
            a = meta(COMPOSE,meta(COMPOSE,a,R),B);
            map[a] = b;
            a = meta(COMPOSE,meta(COMPOSE,a,R),B);
            map[a] = b;
            a = meta(COMPOSE,meta(COMPOSE,a,R),B);
            a = meta(COMPOSE, a, c[b % 10 + 1]);
        }
    }
    if(z==TEST) {
        a = map[meta(COMPOSE,U,L)];
        b = map[meta(COMPOSE,U,R)];
        c = map[meta(COMPOSE,U,B)];
        if(a==W||b==W||c==W) print "You smell the wumpus";
        if(a==P||b==P||c==P) print "You feel a breeze";
        if(map[U]==W) {
            print "You have been eaten by the wumpus";
            exit;
        }
        if(map[U]==P) {
            print "You have fallen into a bottomless pit";
            exit;
        }
    }
    if(z==ARROWTEST) {
        if(A==W) {
            print "You have slain the wumpus!";
            exit;
        } else {
            for(a in p) if(map[a]==W) break;
            W=map[meta(COMPOSE,a,v[int(rand()*3)+1])];
        }
    }
}

BEGIN {
    COMPOSE = 0;
    WALK = 1;
    TEST = 2;
    ARROWTEST = 3;
    L = 35214;
    R = 35421;
    B = 35142;
    split(R" "L" "B,V);
    meta(WALK,L);
    W = int(rand()*19)+2;
    P = int(rand()*19)+2;
    U = L;
    meta(TEST);
}

{
    d=int($0/10);
    m=$0%10;
    if(m==5) U = meta(COMPOSE,U,V[d]);
    else if(m==4) {
        A = map[meta(COMPOSE,U,V[d])];
        meta(ARROWTEST);
    }
    meta(TEST);
}

```
> 1 votes

---
Tags: code-challenge, game
---


# Question
Title: Three polyglots, two period-two quines, and one code-golf challenge
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.

# Answer
# 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

```
> 10 votes

# Answer
# 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!')

```
> 16 votes

# Answer
# 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 `eval`uate 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.)
> 9 votes

# Answer
# 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.
> 8 votes

# Answer
# 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.*
> 7 votes

# Answer
# 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.
> 4 votes

# Answer
# 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.
> 1 votes

---
Tags: code-golf, quine, code-generation, polyglot
---


# Question
Title: Length of the Longest Palindromic Substring
A palindrome is a string which is the same when read forwards and backwards. For example "racecar" is a palindrome, but "Racecar" is not. A substring is a contiguous set of characters in a larger string. Your task is to write a program or method which takes a string or character array as input and outputs the length of the longest substring of that string which is a palindrome.

**Examples**

Input

```
banana

```

Ouput

```
5

```

This is because "anana" is a 5 character substring of "banana"

Input

```
abracadabra

```

Output

```
3

```

This is because both "aca" and "ada" are 3 characters.

Input

```
True

```

Output

```
1

```

This string has no palindromes that are more than 1 character.

If the input is the empty string the output must be 0.

This is code-golf so the shortest submission in any language wins.

Note: There have been slight variations of this question in the past, which have all had wording issues or been asking a variation of this question. You can see these:

Find the Longest Palindrome in a String by Removing Characters

Longest reverse palindromic DNA substring

How do I find the longest palindrome in a string?

Finding "sub-palindromes". \- The purpose of this challenge is to print *all* palindromic substring, rather than the length of the longest. As such many of the answers to this question do not have close analogues.

# Answer
> 4 votes
# Brachylog, 9 bytes

```
{s.↔}ᶠlᵐ⌉

```

Try it online!

### Explanation

```
{   }ᶠ       Find all…
 s.            …substrings of the input…
  .↔           …which are their own reverse
      lᵐ     Map length
        ⌉    Max

```

# Answer
> 3 votes
# Jelly, 6 bytes

Saved 1 byte thanks to Dennis (pointing out that `Þ` is stable and thus works instead of `Ðf`).

```
ẆŒḂÞṪL

```

Try it online!

### How?

```
ẆŒḂÞṪL – Full program.

Ẇ      – All contiguous non-empty subsequences.
   Þ   – Stable sort by...
 ŒḂ    – 1 if the element is palindrome, 0 otherwise.
    Ṫ  – Get the last element.
     L – And take its length.

```

Note that the substrings are ordered by length, in Jelly.

# Answer
> 3 votes
# Pyth, 7 bytes

```
le_I#.:

```

Try it online!

### How?

```
le_I#.: – Full program.

     .: – All contiguous non-empty subsequences.
    #   – Keep those...
  _I    – That are invariant under reversal.
 e      – Get the last element.
l       – And take its length.

```

Note that the substrings are ordered by length, in Pyth.

# Answer
> 3 votes
# 05AB1E, ~~9~~ 8 bytes

```
ŒʒÂQ}€gM

```

Try it online!

# Answer
> 2 votes
# Java 8, 163 bytes

```
s->{int r=0,l=s.length(),i=0,j,T;for(String t;i<l;i++)for(j=i;++j<=l;r=t.contains(new StringBuffer(t).reverse())&(T=t.length())>r?T:r)t=s.substring(i,j);return r;}

```

**Explanation:**

Try it online.

```
s->{                 // Method with String parameter and integer return-type
  int r=0,           //  Result-String, starting empty
      l=s.length(),  //  The length of the input-String
      i=0,j,         //  Index-integers
      T;             //  Temp integer
  for(String t;      //  Temp String
      i<l;i++)       //  Loop `i` over the String
    for(j=i;++j<=l;  //   Inner loop `j` over the String
        r=           //     After every iteration, set the result to:
          t.contains(new StringBuffer(t).reverse())
                     //      If the temp-String is a palindrome,
          &(T=t.length())>r?
                     //      and the length of the substring is larger than the result
           T         //       Set this length as the new result
          :          //      Else:
           r)        //       Keep the result the same
      t=s.substring(i,j);
                     //    Set the temp String to the substring from index `i` to `j`
  return r;}         //  Return the result

```

# Answer
> 2 votes
# Husk, 8 bytes

```
L►LfS=↔Q

```

Try it online!

### How?

```
L►LfS=↔Q – Full program.

       Q – All contiguous non-empty subsequences.
   f     – Keep those...
    S=   – That are equal to themselves when...
      ↔  – Reversed.
 ►L      – Get the maximum element, sorted by length.
L        – Take its length.

```

Alternative: `▲mLfS=↔Q`. Note that the substrings are **not** ordered by length, in Husk.

# Answer
> 1 votes
# Retina, 42 bytes

```
Lv`(.)*.?(?<-1>\1)*(?(1)(?!))
N$^`
$.&
\G.

```

Try it online! Link includes test cases. Explanation:

```
Lv`(.)*.?(?<-1>\1)*(?(1)(?!))

```

For each character in the string, find the longest palindrome that starts at that point.

```
N$^`
$.&

```

Sort the found palindromes in reverse order of length.

```
\G.

```

Count the length of the first (i.e. longest) palindrome.

# Answer
> 0 votes
# Python 3, 58 bytes

```
f=lambda s:len(s)if s==s[::-1]else max(f(s[1:]),f(s[:-1]))

```

Try it online!

# Answer
> 0 votes
# , 20 bytes

```
[:>./@,#\(#*]-:|.)\]

```

Try it online!

---
Tags: code-golf, string, palindrome
---


title: Wanna See a Card Trick? (Part I)

text:
# Question
Title: Wanna See a Card Trick? (Part I)
Amazingly, this is the easier of the three card tricks I know off the top of my head...

The aim of this is to have your compiler perform a specific card trick. There's no slight of hand, and the compiler won't be memorizing the choice and saying "Voila, this is your card!" The code will basically manipulate a stack of cards and the final card drawn from this stack will be the card chosen at random:

If you want to understand this trick further, feel free to follow this with an actual deck of cards so that you can learn the trick. I will be displaying the order of the cards in the face-down stack in my example in curly braces `{}` so that you can see what's happening.

The standards set in this trick:

1. A standard deck of cards is generated, 52 cards (no jokers required). From this deck, nine cards will be chosen at random to form our trick's card stack.
2. The backs of the cards will be displayed as `@@`.
3. The face-size of the cards will be displayed in the format `XY` where `X` is the value, `A-9`,`T`,`J`,`Q`,`K` (`T` = 10); and `Y` is the suit, `S`pades, `C`lubs, `D`iamonds, `H`earts. So `AS` for the Ace of Spades, `TC` for 10 of Clubs, `8H` for the 8 of Hearts, etc.
4. In displaying the stack of cards, from left to right, the left-most card will be located on the bottom of the stack, and the right-most card will be at the top of the stack. Similarly, if cards are in smaller sets, left-most = bottom card, right-most = top card.

Given these standards, my randomly chosen stack for this example looks like this: `@@ @@ @@ @@ @@ @@ @@ @@ @@` (cards facing down)

...And when facing up: `TD JD 8C 7D 8S 3C QH 9S 3S`

Note, this means my facing up stack has the ten of diamonds on the bottom, and the three of spades at the top.

Your deck may vary from mine (see Standards 1 above re random generated stack)

I will go through this trick step-by-step, and how the code needs to work:

* Accept a number between 1 and 9 as input, to be used later on:

`2`

* Generate your nine-card stack and display the cards face down first, in sets of 3, four spaces in between each set. This is so that the user can see they've chosen a specific card out of a specific set:

`@@ @@ @@ @@ @@ @@ @@ @@ @@`

* Flip the cards over, so that the user can see which card they chose:

`TD JD 8C 7D 8S 3C QH 9S 3S`

* Announce the card chosen, full wording of the card, e.g. the second card (derived from our input of `2` earlier on):

`JACK OF DIAMONDS`

* Take the chosen card and place it on top of that specific set, facing up; remembering that the right-most card in each set is the top-most in each set facing up:

`TD 8C JD 7D 8S 3C QH 9S 3S`

* Put the other two sets on top of the set with the chosen card, also facing up, to form one stack. It does not matter which of the two sets goes first:

`TD 8C JD 7D 8S 3C QH 9S 3S`

* Flip the stack over so that the cards are facing down:

`@@ @@ @@ @@ @@ @@ @@ @@ @@`

*Note: At this point, the stack of cards will have now reversed in order:*

`{3S 9S QH 3C 8S 7D JD 8C TD}`

* Our ten of diamonds is on the top of the pile now... And our chosen card is third from the top... The chosen card will ***ALWAYS*** be third from the top at this point.
* Now, we have to spell out the card in question, in our case the `JACK OF DIAMONDS`. Cards are dealt from the top of the deck to another pile, spelling out the card as we go. After the spelling of each word, the rest of the pile goes straight on top with each word. I've shown how the cards in the face-down stack are ordered after each word in curly braces:

`J @@ A @@ C @@ K @@, @@ @@ @@ @@ @@ {TD 8C JD 7D 3S 9S QH 3C 8S}`

`O @@ F @@, @@ @@ @@ @@ @@ @@ @@ {8S 3C TD 8C JD 7D 3S 9S QH}`

`D @@ I @@ A @@ M @@ O @@ N @@ D @@ S @@, @@ {QH 9S 3S 7D JD 8C TD 3C 8S}`

* Here's what they call the *prestige*, the final part of the trick. Deal out the first five cards from the top of the stack, face down to the words `HERE'S THE <NUMBER> OF <SUIT>! <FIFTH CARD FACE UP>`, flipping the final card to show face up...

`HERE'S @@ THE @@ JACK @@ OF @@ DIAMONDS! JD`

The fifth card from the stack should now be the card originally chosen.

Example output, using a new randomly chosen stack, and `4` as the input.

```
@@ @@ @@    @@ @@ @@    @@ @@ @@
3D AD JS    TH KD QS    JC 6D 4S
TEN OF HEARTS
3D AD JS    KD QS TH    JC 6D 4S
KD QS TH 3D AD JS JC 6D 4S
@@ @@ @@ @@ @@ @@ @@ @@ @@
T @@ E @@ N @@, @@ @@ @@ @@ @@ @@
O @@ F @@, @@ @@ @@ @@ @@ @@ @@
H @@ E @@ A @@ R @@ T @@ S @@, @@ @@ @@
HERE'S @@ THE @@ TEN @@ OF @@ HEARTS! TH

```

Please note, the final *card* you are producing at the end is pulled from the card stack (array), and will always be the fifth card in the stack, not from some assigned variable; and the code needs to reflect this. Note, that if you're dealing with a zero-based array language that this would mean, element 4, as opposed to element 5 in a one-based array language.

The key to this code-golf (yes, this is going to be code-golf, muahahahahaha!) is through the manipulation of the nine-card stack. With each word spelled out, the affected cards at the top of the stack will be reversed, thrust to the bottom of the stack and the remaining cards will be placed on top; refer to the examples above to see how that works. Run through the logic with nine playing cards if you have to in order to understand how it works.

**Rules**

1. This is code-golf. Lowest byte-count will win; in the event of a tie in byte count, highest votes will win.
2. No silly loopholes.
3. The input can be implemented in whatever way you see fit: STDIN, an array, a parameter in a function, whatever takes your fancy...
4. Please provide a link to your executing code on an online IDE like TIO so that we can marvel at your work. Learning from one another is something I encourage, and I'd love to see how you all can code this up!
5. The chosen card is drawn correctly at the end providing you have the array/stack manipulations worked out. Please do not simply assign the chosen card into a variable and pull it out in the end... This will be regarded as an invalid answer.

# Answer
# Perl 5, ~~551~~ ~~549~~ ~~547~~ 546 + 1 (`-p`) = 547 bytes

```
%r=(T,TEN,J,JACK,Q,QUEEN,K,KING,A,ACE);map$r{++$.}=$_,TWO,THREE,FOUR,FIVE,SIX,SEVEN,EIGHT,NINE;map{/./;$u{$_.$&}=[$r{$_},OF,$&.$']for keys%r}DIAMONDS,HEARTS,SPADES,CLUBS;@0=(keys%u)[0..8];$x.="@0[$_..$_+2]   ",print'@@ 'x3,$"x2for@z=(0,3,6);@w=@{$u{$0[$_]}};say"
$x
@w";@t=@0[($l=$_-$_%3)..$l+2];splice@t,$_%3,1;push@t,$0[$_];@0[$l..$l+2]=@t;print"@0[$_..$_+2]   "for@z;@t=splice@0,$l,3;say"
@t @0
".'@@ 'x9;@0=reverse@t,@0;map{@t=();push@t,pop@0for/./g;say+(join$q=' @@ ',/./g),' @@,',' @@'x@0;@0=(@t,@0)}@w;$_=(join$q,"HERE'S",THE,@w)."! $0[4]"

```

Try it online!

Uses 0-based counting, so the cards are numbered 0-8.
> 1 votes

# Answer
# Python 2, ~~593~~ 589 bytes

```
from random import*
N=input()-1
n='\n';A='@@ ';V='A23456789TJQK';Z='SCDH'
J=' '.join
j='    '.join
s=sample(map(''.join,zip(V*4,Z*13)),9)
x,y=s[N]
S=[s[:3],s[3:6],s[6:]]
x,y=dict(zip(V,'ACE TWO THREE FOUR FIVE SIX SEVEN EIGHT NINE TEN JACK QUEEN KING'.split()))[x],dict(zip(Z,'SPADES CLUBS DIAMONDS HEARTS'.split()))[y]
print(A*3+'   ')*3+n+j(map(J,S))+n+x,'OF',y
S[N/3]+=S[N/3].pop(N%3),
print j(map(J,S))
s=S.pop(N/3)+S[0]+S[1]
print J(s)+n+A*9;s=s[::-1]
for w in x,'OF',y:l=len(w);s=s[:~l:-1]+s[:-l];print' @@ '.join(w)+' @@, '+-l%9*A
print"HERE'S @@ THE %s @@ OF %s! %s"%(A+x,A+y,s[4])

```

Try it online!

-4 bytes thanks to ovs
> 7 votes

# Answer
# Clean, ~~764~~ ... 686 bytes

```
import StdEnv,Math.Random,System._Unsafe,Text,System.Time
f=["","","   ":f]
w=" "
^ ="@@"
$s=g[hd u+t\\u<-s&t<-f]
d=reverse
r=repeatn 9
j=join
g=j w
s=split w
?n#n=n-1
#!a=removeDup[[[w<+y.[0],x,"OF",y]\\w<-:"A123456789TJQK"&x<-s"ACE ONE TWO THREE FOUR FIVE SIX SEVEN EIGHT NINE TEN JACK QUEEN KING",y<-s"CLUBS HEARTS DIAMONDS SPADES"]!!(i rem 52)\\i<-genRandInt(toInt(accUnsafe time))]%(0,8)
#v=a!!n
#b=insertAt(n/3*3+2)v(removeAt n a)
#c=b%(n/3,n/3+2)
#c=c++removeMembers b c
#v=tl v
#(z,s)=foldl(\(c,s)k=let(p,q)=splitAt(9-size k)c in(d q++p,[j"@@ "[e<+w\\e<-:k]+j^["@@, ":[w\\_<-p]]:s]))(d c,[g(r^),g(map hd c),$b,g v,$a,$(r[^])])v
#[x:y]=z!!4
=d[j" @@ "["HERE'S","THE":y]+"! "+x:s]

```

Try it online!

Defines the function `? :: Int -> [String]`, taking the card number and returning a list of lines.

**Explanation coming when answer is finalized so I don't need to keep retyping it**
> 1 votes

---
Tags: code-golf, math, array, card-games
---


title: The modulo parity party

text:
# Question
Title: The modulo parity party
You are given an array **A** of **n** strictly positive integers, with **n ≥ 2**.

Your task is to map each entry **Ai** to:

* **1** if **Aj mod Ai** is odd for each **j** such that **1 ≤ j ≤ n** and **j ≠ i**
* **2** if **Aj mod Ai** is even for each **j** such that **1 ≤ j ≤ n** and **j ≠ i**
* **0** otherwise (mixed parities)

## Example

For **A = \[ 73, 50, 61 \]**, we have:

* 50 mod 73 = **50**, 61 mod 73 = **61** → mixed
* 73 mod 50 = **23**, 61 mod 50 = **11** → all odd
* 73 mod 61 = **12**, 50 mod 61 = **50** → all even

Therefore, the expected output is **\[ 0, 1, 2 \]**.

## Rules

* You may use any three distinct values (of any type) instead of **0**, **1** and **2** as long as they're consistent. *Please specify your mapping* if you're not using the one described in the challenge.
* Should there be any doubt about that, zero is even.
* This is , so the shortest answer in bytes wins!

## Test cases

```
[ 1, 2 ] --> [ 2, 1 ]
[ 3, 4 ] --> [ 1, 1 ]
[ 1, 2, 3 ] --> [ 2, 1, 0 ]
[ 4, 4, 4 ] --> [ 2, 2, 2 ]
[ 73, 50, 61 ] --> [ 0, 1, 2 ]
[ 941, 459, 533 ] --> [ 1, 0, 0 ]
[ 817, 19, 928, 177 ] --> [ 1, 2, 1, 1 ]
[ 312, 463, 336, 729, 513 ] --> [ 0, 2, 0, 0, 0 ]
[ 53, 47, 33, 87, 81, 3, 17 ] --> [ 0, 0, 0, 1, 0, 2, 0 ]

```

# Answer
> 9 votes
# Python 2, ~~68~~ ~~67~~ 66 bytes

-1 byte thanks to Mr. Xcoder
-1 byte thanks to ovs

```
x=input()
for j in x:k=sum(i%j%2for i in x);print(k<len(x)-1)+0**k

```

Try it online!

Returns `1,0,2` instead `0,1,2`.

# Answer
> 5 votes
# Jelly, 9 bytes

```
%þœ-€0Ḃ‘Ṭ

```

Returns **\[1, 1\], \[0, 1\], \[1\]** instead of **0, 1, 2**.

Try it online!

### How it works

```
%þœ-€0Ḃ‘Ṭ  Main link. Argument: A (array)

%þ           Build the modulus table.
  œ-€0       Remove one 0 from each list of moduli.
      Ḃ      Take the last bit of each.
       ‘     Increment, mapping 0 and 1 to 1 and 2.
        Ṭ    Untruth; map each array to an aray of 1's at the specified indices.
             This yields:
                 [1] if the array contains only 1's (all even).
                 [0, 1] if the array contains only 2's (all odd).
                 [1, 1] if the array contains 1's and 2's.

```

# Answer
> 3 votes
# MATL, 12 bytes

```
!G\o~tAws1=-

```

This uses `0`, `-1`, `1` instead of `0`, `1`, `2` respectively.

Try it online! Or verify all test cases.

### Explanation

```
!    % Implicit input: row vector. Transpose into a column
G    % Push input again
\    % Modulus, element-wise with broadcast. Gives a square matrix
o    % Parity: gives 1 for odd, 0 for even
~    % Logical negate: 0 for odd, 1 for even
t    % Duplicate
A    % All: gives 1 for columns that contain only 1
w    % Swap
s    % Sum of each column
1    % Push 1
=    % Is equal? Gives 1 if the column sum was 1, 0 otherwise
-    % Subtract, element-wise. Implicit display

```

# Answer
> 3 votes
# C (gcc), ~~118~~ ~~114~~ ~~97~~ ~~92~~ ~~91~~ 86 bytes

* Thanks to Peter Cordes for bugfixing.
* Saved ~~four~~ twenty-one bytes thanks to Peter Cordes; suggesting to use a different output value mapping; `[0 1 2] ~ [3 2 1]`.
* Saved five bytes; using yet another mapping; `[0 1 2] ~ [  ]`.
* Saved a byte; golfed `for(i=0;i<n;i++,putchar...` to `for(i=~0;++i<n;putchar...`.
* Saved five bytes thanks to ceilingcat.

```
i,j,r;f(A,n)int*A;{for(i=~0;++i<n;putchar(r))for(r=0,j=n;j--;)r|=j-i?A[j]%A[i]%2+1:0;}

```

Try it online!

# Answer
> 3 votes
# Mathematica, ~~57~~ ~~49~~ 48 bytes

```
(s=#;And@@#.Or@@#&@OddQ@Rest@Sort[s~Mod~#]&)/@#&

```

This returns:

* `False.True` for **0** (mixed)
* `True.True` for **1** (all odd)
* `False.False` for **2** (all even)

Try it online!

Here's a slightly longer alternative (49 bytes):

```
Sign[(s=#;Tr@Mod[s~Mod~#,2]&)/@#/.Tr[1^#]-1->-1]&

```

This one returns:

* `1` for **0** (mixed)
* `-1` for **1** (all odd)
* `0` for **2** (all even)

Try it online!

# Answer
> 2 votes
# Red, 101 bytes

```
g: func[b][foreach n b[a: copy[]foreach m b[append a m % n % 2]sort a a: copy next a print unique a]]

```

Try it online!

Returns `1 0` for mixed, `1` for odd and `0` for even

```
g: func[b] [
    foreach n b [
        a: copy []
        foreach m b [
            append a m % n % 2
        ]
        sort a
        a: copy next a
        print unique a
    ]
]

```

# Answer
> 2 votes
# JavaScript (ES6), 46 bytes

```
a=>a.map(A=>a.map(B=>d+=B%A%2,d=0)|!a[d+1]-!d)

```

Returns -1 (even), 1 (odd), and 0 (mixed).

**How it works:**

The `d` accumulator will be:

1. Zero if all even moduli. (`!a[d+1]` == false, `!d` == 1, `false - 1` == **-1**)
2. One less *  than the length of the array if all odd moduli. ( * The accumulator includes an element modulused against itself, resulting in *one* even modulus.) (`!a[d+1]` == true, `!d` == 0, `true - 0` == **1**)
3. Two or more less than the length of the array if a mix. (`!a[d+1]` == false, `!d` == 0, `false - 0` == **0**)

**Test cases:**

```
let f=

a=>a.map(A=>a.map(B=>d+=B%A%2,d=0)|!a[d+1]-!d)

console.log(f([ 1, 2 ] ) + ''); // [ -1, 1 ]
console.log(f([ 3, 4 ] ) + ''); // [ 1, 1 ]
console.log(f([ 1, 2, 3 ] ) + ''); // [ -1, 1, 0 ]
console.log(f([ 4, 4, 4 ] ) + ''); // [ -1, -1, -1 ]
console.log(f([ 73, 50, 61 ] ) + ''); // [ 0, 1, -1 ]
console.log(f([ 941, 459, 533 ] ) + ''); // [ 1, 0, 0 ]
console.log(f([ 817, 19, 928, 177 ] ) + ''); // [ 1, -1, 1, 1 ]
console.log(f([ 312, 463, 336, 729, 513 ] ) + ''); // [ 0, -1, 0, 0, 0 ]
console.log(f([ 53, 47, 33, 87, 81, 3, 17 ] ) + ''); // [ 0, 0, 0, 1, 0, -1, 0 ]
```

# Answer
> 1 votes
# , 27 20 bytes

```
[:<@~.@}:@\:"1~2||/~

```

Try it online!

Uses \[1 0\] \[1\] \[0\] instead of 0 1 2

## Explanation:

`|/~` \- makes a table with remainders:

```
  |/~ 73 50 61
 0 50 61
23  0 11
12 50  0

```

`2|` odd or even? :

```
   2||/~ 73 50 61
0 0 1
1 0 1
0 0 0

```

`<@~.@}:@\:"1` \- sort down, drop last element (always a zero), keep the ùnique elements and box each row:

```
   <@~.@}:@\:"1~2||/~ 73 50 61
┌───┬─┬─┐
│1 0│1│0│
└───┴─┴─┘

```

# Answer
> 1 votes
# Ruby, ~~58~~ 56 bytes

```
->r{r.map{m=r.shift;s=r.map{|e|e%m%2}.uniq.sort;r<<m;s}}

```

Returns **\[0, 1\], \[1\], \[0\]** instead of **0, 1, 2** (i.e. **\[0\]** for all even , **\[1\]** for all odd, and **\[0, 1\]** for mixed).

Try it online!

# Answer
> 1 votes
# Perl 5, ~~71~~ 69 + 1 (`-a`) = 70 bytes

```
map{//;$j=$s='';$j++-$i&&($s+=$_%$'&1)for@F;say$s?0|$s==$#F:2;$i++}@F

```

Try it online!

# Answer
> 1 votes
# Perl, 38 bytes

Includes `+3` for `-p`

```
#!/usr/bin/perl -p
s/\d+/$@|=$_%$&%2+1for<$`$'>;$@/gee

```

Outputs 1 for all even, 2 for all odd, 3 for mixed

# Answer
> 1 votes
# Clean, ~~95~~ ~~65~~ 63 bytes

```
import StdEnv

```

#

```
\l=[sum(removeDup[-1^(j rem i)\\j<-l|j<>i])\\i<-l]

```

Try it online!

As a lambda, taking `[Int]` and returning `[Int]`, mapping to:

* `0`: mixed
* `1`: all even
* `-1`: all odd

# Answer
> 1 votes
# Java 8, ~~91~~ 89 bytes

```
a->{for(int z:a){int s=1;for(int y:a)s+=y%z%2;System.out.print(" "+(s<a.length)+(s<2));}}

```
* Using `truetrue` instead of `2` for even
* Using `falsefalse` instead of `1` for odd
* Using `truefalse` instead of `0` for mixed

**Explanation:**

Try it online.

```
a->{                      // Method with integer-array parameter and no return-type
  for(int z:a){           //  Loop over the array
    int s=1;              //   Sum-integer, starting at 1
    for(int y:a)          //   Inner loop over the array again
      s+=y%z%2;           //    Increase the sum by `y` modulo-`z` modulo-2
    System.out.print(" "  //   Print a space
      +(s<a.length)       //    + "true" if the sum is smaller than the length of the array
                          //      (this means there is at least one even)
      +(s<2));}}          //    + "true" if the sum is still 1
                          //      (this means all are even)

```

# Answer
> 1 votes
# Pari/GP, 42 bytes

```
a->[[!s=vecsum([x%y%2|x<-a]),s>#a-2]|y<-a]

```

Returns `[0, 0], [0, 1], [1, 0]` instead of `0, 1, 2`.

Try it online!

# Answer
> 0 votes
## Clojure, 82 bytes

```
#(for[R[(range(count %))]i R](set(for[j R :when(not= i j)](odd?(mod(% j)(% i))))))

```

A complete example with output conversion:

```
(def f #(for[R[(range(count %))]i R](set(for[j R :when(not= i j)](odd?(mod(% j)(% i)))))))
(->> [ 53, 47, 33, 87, 81, 3, 17] f
     (map {#{true} 1, #{false} 2, #{true false} 0}))
; (0 0 0 1 0 2 0)

```

---
Tags: code-golf, array, number-theory
---