title: Last digit large number

text:
# Question
Title: Last digit large number
For a given list of number \\$\[x\_1, x\_2, x\_3, ..., x\_n\]\\$ find the last digit of \\$x\_1 ^{x\_2 ^ {x\_3 ^ {\dots ^ {x\_n}}}}\\$ Example:

```
[3, 4, 2] == 1
[4, 3, 2] == 4
[4, 3, 1] == 4
[5, 3, 2] == 5

```

Because \\$3 ^ {(4 ^ 2)} = 3 ^ {16} = 43046721\\$.

Because \\$4 ^ {(3 ^ 2)} = 4 ^ {9} = 262144\\$.

Because \\$4 ^ {(3 ^ 1)} = 4 ^ {3} = 64\\$.

Because \\$5 ^ {(3 ^ 2)} = 5 ^ {9} = 1953125\\$.

Rules:

This is code golf, so the answer with the fewest bytes wins.

If your language has limits on integer size (ex. \\$2^{32}-1\\$) n will be small enough that the sum will fit in the integer.

Input can be any reasonable form (stdin, file, command line parameter, integer, string, etc).

Output can be any reasonable form (stdout, file, graphical user element that displays the number, etc).

Saw on code wars.

# Answer
# JavaScript (ES7), 22 bytes

Limited to \\$2^{53}-1\\$.

```
a=>eval(a.join`**`)%10

```

Try it online!
> 15 votes

# Answer
# , 25 bytes

```
Reduce(`^`,scan(),,T)%%10

```

Try it online!
> 13 votes

# Answer
## Haskell, 19 bytes

```
(`mod`10).foldr1(^)

```

Try it online!
> 10 votes

# Answer
# HP 49G RPL, 36.5 bytes

Run it in APPROX mode (but enter the program in EXACT mode). Takes input on the stack with the first element deepest in the stack, as integers or reals.

```
WHILE DEPTH 1 - REPEAT ^ END 10 MOD

```

It straightforwardly exponentiates on the stack as in Sophia's solution until there is one value left, then takes it mod 10 to get the last digit.

The reason I use APPROX for computation is because 0.0^0.0 = 1 (when they are both reals), but 0^0 = ? (when they are both integers). APPROX coerces all integers to reals, so the input is fine with either. However, I use EXACT to enter the program because 10 (integer) is stored digit-by-digit, and is 6.5 bytes, but 10.0 (real) is stored as a full real number, and is 10.5 bytes. I also avoid using RPL's reduce (called STREAM) because it introduces an extra program object, which is 10 bytes of overhead. I already have one and don't want another.

Limited to the precision of an HP 49G real (12 decimal digits)

-10 bytes after empty list -\> 1 requirement was removed.

-2 bytes by taking input on stack.
> 9 votes

# Answer
# dc, 17 15 bytes

```
1[^z1<M]dsMxzA%

```

Try it online!

Takes input from the stack, outputs to the stack. Very straightforward implementation - exponentiates until only one value is left on the stack and mod for the last digit.

Thanks to brhfl for saving two bytes!
> 7 votes

# Answer
# , 5 bytes

-3 bytes thanks to cole!

```
10|^/

```

Try it online!
> 6 votes

# Answer
# 05AB1E, 4 bytes

```
.«mθ

```

Try it online!

**Explanation**

```
.«     # fold
  m    # power
   θ   # take the last digit

```
> 6 votes

# Answer
# Wolfram Language (Mathematica), 16 bytes

```
Power@##~Mod~10&

```

Try it online!
> 5 votes

# Answer
# Pure Bash (builtins only - no external utilities), 21

```
echo $[${1//,/**}%10]

```

Input is given on the command line as a comma-separated list.

Bash integers are subject to normal signed integer limits for 64- and 32-bit versions.

Try it online!
> 5 votes

# Answer
# Perl 6, 14 bytes

```
{([**] $_)%10}

```

Try it online!

Uses the reduction meta square brackets with the operator \**, modulo 10.
> 4 votes

# Answer
# Python 2 and Python 3, 30 bytes

```
lambda N:eval('**'.join(N))%10

```

Try it online!

The input `N` is expected to be an iterable object over *string representations of number literals*.
> 4 votes

# Answer
# Julia 0.6, 30 bytes

```
first∘digits∘x->foldl(^,x)

```

Try it online!

This is an anon function
∘ is the composition operator.
It is multiple bytes
> 4 votes

# Answer
# Ruby, ~~41~~ 47 bytes

Size increase due to handling of any 0 in the input array, which needs extra consideration. Thanks to `rewritten`

```
->a{a.reverse.inject{|t,n|n<2?n:n**(t%4+4)}%10}

```

This is solved as I believe the original source intended, i.e. for very large exponentiations that will not fit into language native integers - the restriction is that the array will sum into `2**32-1`, not that the interim calculations are also guaranteed to fit. In fact that would seem to be the point of the challenge on Code Wars. Although Ruby's native integers can get pretty big, they cannot cope with the example below processed naively with a %10 at the end

E.g.

Input: `[999999,213412499,34532597,4125159,53539,54256439,353259,4314319,5325329,1242149,142219,1243219,14149,1242149,124419,999999999]`

Output: `9`
> 4 votes

# Answer
# Japt `-h`, ~~7~~ 6 bytes

If input can be taken in reverse order then the first character can be removed.

Limited to `2**53-1`.

```
Ôr!p ì

```

Try it

---

## Explanation

```
Ô          :Reverse the array
 r         :Reduce by
  !p       :  Raising the current element to the power of the current total, initially the first element
     ì     :Split to an array of digits
           :Implicitly output the last element

```
> 3 votes

# Answer
# PHP, ~~50~~ 44 bytes

*-6 bytes from @Shaggy*

```
<?=eval("return ".join('**',$argv).";")%10?>

```

Try it online!
> 3 votes

# Answer
# 05AB1E, 8 bytes

```
`.gGm}T%

```

Try it online!
> 3 votes

# Answer
# C (gcc), 56

* Saved 4 bytes thanks to @JonathanFrech

Recursive function `r()` called from macro `f` \- normal stack limits apply.

```
R;r(int*n){R=pow(*n,n[1]?r(n+1):1);}
#define f(n)r(n)%10

```

Input given as a zero-terminated int array. This is under the assumption that none of the xn are zero.

Try it online!
> 3 votes

# Answer
# C# (.NET Core), 84 bytes

```
a=>{int i=a.Length-1,j=a[i];for(;i-->0;)j=(int)System.Math.Pow(a[i],j);return j%10;}

```

Try it online!

* -7 bytes thanks to @raznagul
> 3 votes

# Answer
# APL (Dyalog Unicode), 5 bytes

```
10|*⌿

```

Try it online!
> 3 votes

# Answer
# Japt `-h`, 7 bytes

```
OvUqp)ì

```

Try it online!

## Explanation:

```
OvUqp)ì
Ov   )    // Japt eval:
   q      //   Join
  U       //   Input with
    p     //   Power method
      ì   // Split into an array of numbers
-h        // Return the last number

```
> 3 votes

# Answer
# Jelly, 6 bytes

```
U*@/DṪ

```

Try it online!
> 2 votes

# Answer
# Python 3, 55 bytes

```
p=lambda l,i=-1:not l or f'{l[0]**int(p(l[1:],0))}'[i:]

```

Older versions

~~```
p=lambda l,i=-1:len(l)and f'{l[0]**int(p(l[1:],0))}'[i:]or 1    (60 bytes)

```~~
> 2 votes

# Answer
# Python 2, ~~45~~ 43 bytes

```
lambda x:reduce(lambda b,a:a**b,x[::-1])%10

```

Try it online!
> 2 votes

# Answer
# Excel VBA, 60 bytes

An anonymous VBE immediate window function that takes input from range `[A1:XFD1]`

```
s=1:For i=-[Count(1:1)]To-1:s=Cells(1,-i)^s:Next:?Right(s,1)

```
> 2 votes

# Answer
# Stax, 7 bytes

```
üT(Çó╖⌐

```

Run and debug it

Algorithm like in my Python answer
> 2 votes

# Answer
# C (gcc), ~~76~~ 75 bytes

* Saved a byte thanks to ceilingcat; golfing `o<=O` to `O/o`.

```
o(int*O){O=_(O)%10;}_(O,o,Q)int*O;{for(o=Q=1;*O>=0&&_(O+1)/Q++;o*=*O);O=o;}

```

Try it online! Takes input as an `int` pointer to a `-1`-terminated list of integers.
> 2 votes

# Answer
# Ruby, ~~24~~ 20 bytes

```
->a{eval(a*'**')%10}

```

Try it online!
> 2 votes

# Answer
# CJam, 14 bytes

```
q~_,({~#]}*~A%

```

Should work for any input, since CJam isn't limited to 64 bit integers

Try it online!
> 2 votes

# Answer
# Python 3, 47 bytes

```
f=lambda x,y=1:f(x[:-1],x[-1]**y)if x else y%10

```

Try it online!
> 2 votes

# Answer
# Brain-Flak, 161 bytes

Includes +1 for `-r`

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

```

Try it online!

The example `[3, 4, 2]` takes longer than 60 seconds, so the TIO link uses `[4, 3, 2]`.

The `-r` can be removed if input can be taken in reverse order for a byte count of 160.

```
# Push stack size -1
([][()])

# While there are 2 numbers on the stack
{({}[()]<

    # Duplicate the second number on the stack (we're multiplying this number by itself)
    ({}<(({}))>[()])

    # For 0 .. TOS
    {({}<

        # Copy TOS
        (({})<

        # Multiple Top 2 numbers
        ({}<>)({<({}[()])><>({})<>}{}<><{}>)

        # Paste the old TOS
        >)

    # End for (and clean up a little)
    >[()])}{}{}

# End While (and clean up)
>)}{}

# Mod 10
({}((()()()()()){})(<>))<>{(({})){({}[()])<>}{}}{}<>([{}()]{})

```
> 2 votes

# Answer
# Pari/GP, 32 bytes

```
a->fold((x,y)->y^x,Vecrev(a))%10

```

Try it online!
> 2 votes

# Answer
# Z80Golf, 36 bytes

```
00000000: cd03 80f5 30fa f1f1 57f1 280d 4f41 15af  ....0...W.(.OA..
00000010: 8110 fd47 1520 f818 ef7a d60a 30fc c60a  ...G. ...z..0...
00000020: cd00 8076                                ...v

```

Try it online!

Brute-force test harness

Takes input as raw bytes. Limited to 2\**8-1.

## Explanation

```
input:
    call $8003    ;      the input bytes
    push af       ; push                 on the stack
    jr nc, input  ;                                   until EOF
    pop af        ; the last byte is going to be pushed twice
    pop af
outer:
    ld d, a       ; d = exponentiation loop counter, aka the exponent
    pop af        ; pop the new base off the stack
    jr z, output  ; The flags are being pushed and popped together with the
                  ; accumulator. Since the Z flag starts as unset and no
                  ; instruction in the input loop modifies it, the Z flag is
                  ; going to be unset as long as there is input, so the jump
                  ; won't be taken. After input is depleted, a controlled stack
                  ; underflow will occur. Since SP starts at 0, the flags
                  ; register will be set to the $cd byte from the very beginning
                  ; of the program. The bit corresponding to the Z flag happens
                  ; to be set in that byte, so the main loop will stop executing
    ld c, a       ; C = current base
    ld b, c       ; B = partial product of the exponentiation loop
    dec d         ; if the exponent is 2, the loop should only execute once, so
                  ; decrement it to adjust that
pow:
    xor a         ; the multiplication loop sets A to B*C and zeroes B in the
mul:              ; process, since it's used as the loop counter
    add c         ; it's definitely not the fastest multiplication algorithm,
    djnz mul      ; but it is the smallest
    ld b, a       ; save the multiplication result as the partial product
    dec d         ; jump back to make the next iteration of either
    jr nz, pow    ; the exponentiation loop or the main loop, adjusting the
    jr outer      ; loop counter in the process
output:           ; after all input is processed, we jump here. We've prepared
    ld a, d       ; to use the result as the next exponent, so copy it back to A
mod:              ; simple modulo algorithm:
    sub 10        ;            subtract ten
    jr nc, mod    ; repeatedly              until you underflow,
    add 10        ; then undo the last subtraction by adding ten
    call $8000    ; output the result
    halt          ; and exit

```
> 2 votes

# Answer
# Ruby, without limitation on very high exponential towers, 142 bytes

```
def d(b,h,*t)
h=h%b
return h if !t[0]
l=b.times.find_index{|i|h**(i+2)%b==h} unless h*h==b
l ?l==0?h:h**d(l+1,*t)%b:[1,h,0][[t[0],2].min]
end

```

This code operates a reduction at each step so every single exponentiation is done on very small numbers. It is able to deal with almost arbitrarily high exponential towers without using arbitrary precision, all is done within a very small integer range, the highest integer used at any point is `9**9`.

The function must be called with an initial base, for the examples it would be

> `d(10, 3, 4, 2)`

so it is able to return the "last digit" of the result in any base.
> 2 votes

# Answer
# Pyth, 7 bytes

```
e.U^Zb_

```

Try it online!

Explanation:

```
e.U^Zb_   //full program
 .U       //reduce with the function
   ^Zb    //lambda b,Z:Z^b
      _   //on reversed (implicit) input
e         //return last digit

```

Also, if input can be taken in reverse order, the final _ can be removed for a final score of 6 bytes.
> 2 votes

# Answer
# Factor, 37 bytes

```
[ reverse [ swap ^ ] 1reduce 10 mod ]

```

Attempt This Online!

Reverse the input, reduce by swapped exponentiation, take the last digit.
> 2 votes

# Answer
# Arturo, 25 bytes

```
$=>[%do join.with:"^"&10]

```

Try it!

```
$=>[                ; a function where input is assigned to &
    join.with:"^"&  ; turn [3 4 2] into "3^4^2", for example
    do              ; eval
    %...10          ; modulo 10
]                   ; end fucntion

```
> 2 votes

# Answer
# ES6, 44 bytes, solves all cases from the original problem

Thanks to @NeilSlater for the (mod 4) condition

```
a=>a.reduceRight((t,n)=>n<2?n:n**(t%4+4))%10

```

Tested passing an array of 2^20 elements each equal to 2^20
> 1 votes

# Answer
## Perl 5, 22 + 2 (`-pl` flag) = 24 bytes

One-liner:

```
$_=(s/ +/**/g,eval)%10

```

Try it online.
> 1 votes

# Answer
# PHP, 54 bytes

```
<?eval('echo '.str_replace(',','**',$argv[1]).'%10;');

```

To run it:

```
php -n <filename> <number,number,...>

```

Example:

```
php -n last_digit.php 5,3,2

```

Or Try it online!

---

# How?

Simply creates a string with format of `<number>**<number>**<number>...%10` and outputs the evaluation of that string.

For input of `5,3,2`, the evaluation string will be `echo 5**3**2%10;`.
> 1 votes

# Answer
# Java 10, 77 bytes (limited to 232-1)

```
a->{int i=a.length-1,j=a[i];for(;i-->0;)j=(int)Math.pow(a[i],j);return j%10;}

```

Input is an `int[]`, output is an `int`.

Try it online.

# Java 10, 82 bytes (limited to 264-1)

```
a->{int i=a.length-1;var j=a[i];for(;i-->0;)j=(long)Math.pow(a[i],j);return j%10;}

```

Input is a `long[]`, output is a `long`.

Try it online.

# Java 10, 177 bytes (unlimited)

```
a->{int i=a.length-1;var j=a[i];for(;i-->0;){var r=j.ONE;for(var t=a[i];j.signum()>0;t=t.multiply(t),j=j.shiftRight(1))if(j.testBit(0))r=r.multiply(t);j=r;}return j.mod(j.TEN);}

```

Input is a `java.math.BigInteger[]`, output is a `java.math.BigInteger`.

Try it online.

`java.math.BigInteger` has a builtin `pow` method, but only accepts `int` as parameter. This last answer uses a golfed variation of this SO answer as implementation of a `pow(BigInteger, BigInteger)` method.
> 1 votes

# Answer
# Thunno 2 `t`, 3 bytes

```
µʋ@

```

Try it online!

#### Explanation

```
µʋ@  # Implicit input
µʋ   # Right-reduce the list by:
  @  #  Swapped exponentiation
     # Take the last item (digit)
     # Implicit output

```
> 1 votes

# Answer
# Uiua, 6 bytes

```
◿10/ⁿ⇌

```

Try it!

```
     ⇌  # reverse
   /ⁿ   # reduce by power
◿10     # modulo 10

```
> 1 votes

# Answer
# TI-Basic, 34 bytes

```
Prompt A
1
For(I,dim(lA),1,~1
lA(I)^Ans
End
10fPart(.1Ans

```

`~` represents the negative sign.
> 1 votes

# Answer
# Python 3, 19 bytes

```
lambda N:eval(N)%10

```

Try it online!

The input is given as a string where each integer is separated by the characters `**`. I claim that the two characters `**` are equally reasonable to `,`  at separating digit sequences.
> -13 votes

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


title: Play a game of memory

text:
# Question
Title: Play a game of memory
*Playing the game of memory against a machine is highly unfair, because they play almost as good as small children. So let's make the machine play alone, but in a fair way:*

* **Input**: 1...26 pairs of lowercase letters in random order like `zz` or `gttg` or `abcdefghiabcdefghi`. You can trust each letter appears exactly twice and no other characters show up.
* Lowercase letters represent unknown cards, uppercase letters are cards we already saw. Being a fair program, your code will not make knowledge of hidden cards.
* With each turn, you are allowed to uncover a pair of cards (making them uppercase). Start to uncover cards at the left side and continue to the right. If the first card was seen before, pick the match. If not, continue with the next unknown card. If you uncover a pair, remove it.
* Play the best you can: If you know an uppercase pair, uncover it. Otherwise never uncover a card you already know!
* **Output**: The number of turns you needed to remove all cards. With the given strategy, this is fixed for a given input. Output as binary, ASCII number or length of output string, whatever you like best.
* **Goal**: The shortest code wins, whatelse!

**Let's illustrate this**:

```
afzaxxzf | This is our input
AFzaxxzf | 1st turn, too bad: no pair
AFZAxxzf | 2nd turn was ZA, again no pair, but ...
 FZ xxzf | 3rd turn used to remove the AA pair
 FZ   zf | 4th turn uncovered XX, which can be immediately removed
 F     f | 5th turn started with z, so as second card we can pick the Z we already know
         | With the 6th turn we solved it, so output will be 6

```

**Some more test data**:

```
aa          --> 1
aabb        --> 2
abba        --> 3
ggijkikj    --> 6
qqwweerrtt  --> 5
cbxcxvbaav  --> 8
zyxzwyvxvw  --> 9
tbiaktyvnxcurczlgwmhjluoqpqkgspwsfidfedrzmhyeanxvboj --> 43

```

**Hint**:

You don't have to actually play memory, you don't need to actually turn anything uppercase! All that counts is the correct output with the lowest number of code bytes. Feel free to discover a hidden algorithm (but it's not as simple as it could appear on the first sight).

# Answer
# , 35 bytes

```
[:#(#@]<.[+2-{.+./@e.~2{.}.)~^:a:&2

```

Attempt This Online!

A bit chonky as far as J code goes, but imo a nice simplification of the algorithm:

* We imagine a pointer, starting at index 2, pointing into our string:

```
ggijkikj
  ^
01234567

```
* On each iteration, we increment the pointer by 2 as a default

+ But: If the character at the pointer, or the character to the right of the pointer, exists within any of the previous characters (left of the pointer), we only increment by 1.
* We keep incrementing until the pointer exceeds the length of the string
* Our answer is the number of iterations that process took

This approach has the advantage of reducing the number of rules/cases down to just a single rule: increment by 2 or 1, depending on whether the next two characters have been seen. This avoids special-casing the `aa` case, or distinguishing between "1st character was already seen" and "2nd character was already seen".
> 10 votes

# Answer
#### *Implementing Jonah's smart trick*

*saved 10 bytes thanks to @DominicVanEssen*

# 4.1, 82 bytes

```
a=\(v,x=1,j=duplicated(v))`if`(sum(j|1)>x,1+a(v,x+2-(v[x]!=v[x+1]&j[x]|j[x+1])),1)

```

Attempt this online!

---

#### *Previous solution*

# 4.1, 141 bytes

```
b=\(v,x){j=duplicated(v)
ifelse(is.na(v[3]),1,ifelse(j[x],1+b(v[v!=v[x]],x-1),ifelse(j[x+1],2+b(v[v!=v[x+1]],x)-(v[x]==v[x+1]),1+b(v,x+2))))}

```

Try it online!

#### Test:

```
w<-c("t","b","i","a","k","t","y","v","n","x","c","u","r","c","z","l","g","w","m","h","j","l","u","o","q","p","q","k","g","s","p","w","s","f","i","d","f","e","d","r","z","m","h","y","e","a","n","x","v","b","o","j")

b(w,1)

```

> 43

#### Brief explanation:

b is a recursive function with input:

* v a vector of characters
* x the position of the first unknown element of v

It proceeds :

* If v\[x\] is duplicated we use one move to remove that pair, and we continue with a shorter vector and one less known element.
* If v\[x+1\] is duplicated we use a second move to remove its pair (but if its twin is v\[x\]), and we continue with a shorter vector and as many known elements.
* Otherwise we use one move to see two more elements.
> 8 votes

# Answer
# Jelly, 10 bytes

```
ṪfṖƊƤŒɠHĊS

```

Try it online!

This alternate solution kinda grew alongside the one preserved below, for what it's worth. Ultimately derived from Jonah's description of his J solution, but whatever the actual code does I strongly suspect it isn't this.

```
   ƊƤ         For every prefix:
Ṫ             Pop the last element
 f            and filter it by membership in
  Ṗ           all but the last remaining (after the pop!) elements.
     Œɠ       Take the lengths of all runs of consecutive equal results,
       H      halve
        Ċ     and ceiling them,
         S    and sum.

```

# Jelly, ~~16~~ ~~13~~ ~~12~~ 11 bytes

```
ṪeṖƊƤœṣØ0KL

```

Try it online!

*-1 kinda back-porting Neil's Retina solution since I don't actually have a clue why Jonah's pointer starts at 2 to begin with*

*-1 doing it again*

Vague port of Jonah's J algorithm.

```
   ƊƤ          For each prefix:
Ṫ              Is the last element
 e             also found
Ṫ Ṗ            two or more indices earlier?
     œṣØ0      Split on all non-overlapping occurrences of the substring 0,0,
         K     join on spaces,
          L    and take the length of that result.

```
> 8 votes

# Answer
# JavaScript (Node.js), 57 bytes

```
a=>a.map(c=>a[n+=!i|a[c]&i!=c,i=i||a[c]?0:c,c]=1,i=n=0)|n

```

Try it online!

We uncover cards from left to right and, for every next card `c`, with previous uncovered card in this turn `i`:

* Count an extra turn (`++n`) whenever:
    + This is the first card to uncover in this turn (`!i`): as a new turn;
    + This is the second card to uncover in this turn (`i`), AND the card just uncovered in the same turn does not equals to the current one (`i!=c`), AND the card just uncovered had already seen some time before (`a[c]`): as we need an extra turn to match these two cards;
* Leave this card uncovered for this turn (`i=c`) whenever:
    + This is the first card to uncover this turn (`!i`), AND this card is not ever seen before (`!a[c]`);
* Remember the card as a seen card (`a[c]=1`)
> 3 votes

# Answer
# Charcoal, ~~25~~ 15 bytes

```
Ｉ⁻Ｌθ№⭆θ№…θ⊖κι00

```

Try it online! Link is to verbose version of code. Explanation: Port of @UnrelatedString's Jelly answer, although I'm not entirely sure why it works.

```
   θ            Input string
  Ｌ             Take the length
 ⁻              Subtract
      θ         Input string
     ⭆          Map over characters and join
         θ      Input string
        …       Truncated to length
           κ    Current index
          ⊖     Decremented
       №        Count of
            ι   Current character
    №           Count of
             00 Literal string `00`
Ｉ               Cast to string
                Implicitly print

```

Previous 25-byte solution:

```
ＦＬθＭ⊕×⊕﹪ⅈ²№…θ⁻ι﹪ⅈ²§θι→Ｉ⊘ⅈ

```

Try it online! Link is to verbose version of code. Explanation:

```
ＦＬθ

```

Loop over the indices of the input.

```
Ｍ⊕×⊕﹪ⅈ²№…θ⁻ι﹪ⅈ²§θι→

```

Calculate how many cards get turned as a result of this card. This is `1` for the card itself and then a possible further `1` or `2` if this card has been seen before depending on whether an even or odd number of cards have been turned so far, except in the odd case where the previous card is the one seen before.

```
Ｉ⊘ⅈ

```

Output the number of turns (which is half of the number of cards turned).
> 3 votes

# Answer
# Retina 0.8.2, ~~25~~ 20 bytes

```
(.)(?<!\1..+)
1
11|.

```

Try it online! Link includes test cases. Explanation: Port of @UnrelatedString's Jelly answer, as I don't see how it works, let alone ports @Jonah's J answer.

```
(.)(?<!\1..+)
1

```

Replace the first character of each pair with a `1`, but also the second if it's adjacent.

```
11|.

```

Subtract the number of pairs of `1`s from the length of the string.

Would be `22` bytes as a one-liner: `((.)(?<!\2..+)){1,2}|.`
> 3 votes

# Answer
# JavaScript (Node.js), 54 bytes

```
a=>a.map(c=>a[i+=a[c]?i%2?i-a[c]?3:1:2:1,c]=i,i=0)|i/2
                 ^    ^   ^          ^
             seen?    |   | Flip the seen
               even-th?   |
  seen early? (abc[a] | bca[a])

```

Try it online!
> 3 votes

# Answer
# Python3, 126 bytes:

```
def f(a):
 s,c=[],0
 while a:
  if(v:=a.pop(0))in s:s={*s}-{v}
  else:s={*s,*[v,(K:=a.pop(0))]*(v!=K)}
  c+=1
 return c+len(s)

```

Try it online!
> 2 votes

# Answer
# sed,  ~~108~~  102 bytes

*(97 bytes for buggy old GNU `sed` 4.2.2 by using empty label instead of `1`)*

I insert an underscore `_` as marker up to where cards are known, then do backreference replacements for all possible cases. For each turn, `H` appends the pattern to the hold space, so in the end I output the number of turns as `+`:

```
s/^/_/
t2
:1
H
:2
s/(.)(.*)\1_/\2_/
t1
s/_(.)\1/_/
t1
s/(.)(.*_)\1/\2/
t1
s/_(..)/\1_/
t1
x
s/.\S*/+/g

```

The `t2` at the beginning looks avoidable, but is needed to reset the `t` trigger after the first replacement.

Try it online!
> 2 votes

# Answer
# Python 3.8 (pre-release), 101 bytes

This is a golfed version of Ajax1234 answer:

```
lambda a,s=set():(A:=iter(a),len([s!=(s:=s-{v})or(K:=next(A))!=v and(s:=s|{v,K})for v in A]+[*s]))[1]

```

Try it online!

This can be 85 bytes if we can take iterator as input, 95 bytes if you can accept "outputs as length of list containing weird random stuff", and 80 bytes if both are allowed:)

85 bytes iterator solution:

```
lambda A,s=set():len([s!=(s:=s-{v})or(K:=next(A))!=v and(s:=s|{v,K})for v in A]+[*s])

```

Try it online!
> 2 votes

# Answer
# 05AB1E, 14 bytes

```
ηεRõ1ǝćÃ}Åγ;îO

```

Port of *@Unrelated String*'s Jelly answer, which is based on the explanation of *@Jonah*'s J answer, so make sure to upvote both of those answers as well!
Will see if I can find something shorter using a similar approach, when I have a bit more time later on.

Try it online or verify all test cases.

**Explanation:**

```
η        # Get all prefixes of the (implicit) input-string
 ε       # Map over each prefix:
  R      #  Reverse it
   õ1ǝ   #  Remove the second character by inserting an empty string at index 1
      ć  #  Extract head; push remainder-string and first character separately
       Ã #  Keep all occurrences of this extracted head in the remainder-string
 }Åγ     # After the map: run-length encode the list of strings,
         # pushing a list of strings and list of counts of equal adjacent values
    ;    # Halve all counts
     î   # Ceil each
      O  # Sum those together
         # (which is output implicitly as result)

```
> 2 votes

# Answer
## X86\_64/Linux Machine Code,  41 40 39 Bytes

Try it online!

**Usage:**

```
$> gcc -DIDEAL_BSS -Wl,-Tbss=0x10000000 -s -static -nostartfiles -nodefaultlibs -nostdlib -Wl,--build-id=none memory.S -o memory
$> echo -n "<Input>" | ./memory; echo $?

```

Program reads input from stdin (it is sensitive to the exact byte count of input, i.e stray spaces/new lines will change result).

The return value of the program is the number of rounds.

**Notes:**

* Size is measured in machine code (i.e 39 bytes of PROGBITS; .text, .data, etc...)
* The 39-byte size assumes the above compile command which sets the BSS address at an ideal value. With generic compile commands (no linker inputs), its 41-bytes.

**Program:**

```
/* Uncomment below if BSS was setup at 2^20.  */
/* #define IDEAL_BSS */

    .global _start
    .text
_start:
    /* Incoming registers are zero.  */

    movb    $60, %dl
#ifdef IDEAL_BSS
    btsl    %edx, %esi
#else
    movl    $G_mem + 0, %esi
#endif
    /* eax == 0 == SYS_read.  */
    /* edi == 0 == STDIN.  */
    syscall
    leal    (%rsi, %rax), %ecx
    movl    %esi, %eax
play:
    /* Load next character.  */
    lodsb
uncovered_already:
    /* Increment round number (returned at prog exit).  */
    incl    %edi

    /* (rax) is a byte-map of characters we have already seen.  */
    movb    (%rax), %bl
    /* Value zero indicates we haven't seen this character yet.  */
    testb   %bl, %bl
    jnz uncover_pair

    /* We haven't seen this character so update byte-map with its
       position + 1.  */
    movb    %dl, (%rax)

    /* Load assosiated character.  Compare first to check for back-
       to-back.  */
    cmpb    %al, (%rsi)
    lodsb

    /* If we uncovered the same character (by chance) then continue.  */
    je  uncovered_adjacent

    /* If the second uncover was an already uncovered character we
       reloop with it as the initial value.  */
    cmpb    %bl, (%rax)
    jne uncovered_already

    /* Update the second unique character's location then continue.  */
    movb    %dl, (%rax)
uncover_pair:
uncovered_adjacent:
    /* At end of buffer, this will always a final turn.  */
    cmpl    %esi, %ecx
    ja  play
done:
    /* Exit.  */
    xchgl   %eax, %edx
    syscall

    .section .bss
    .align  256
G_mem:  .space 4096

```

**Examples/Tests:**

```
$> for x in aa aabb abba ggijkikj qqwweerrtt cbxcxvbaav zyxzwyvxvw tbiaktyvnxcurczlgwmhjluoqpqkgspwsfidfedrzmhyeanxvboj; do echo -n "${x}" | ./memory; echo "${x} -> $?"; done
aa -> 1
aabb -> 2
abba -> 3
ggijkikj -> 6
qqwweerrtt -> 5
cbxcxvbaav -> 8
zyxzwyvxvw -> 9
tbiaktyvnxcurczlgwmhjluoqpqkgspwsfidfedrzmhyeanxvboj -> 43

```
> 0 votes

# Answer
## C#, 132 bytes

Wanted to keep working on this (ideally finding a smarter algorithm) but never did, so here's where I got up to 3 weeks ago. I just started with a naïve algorithm and golfed it.

```
string d=args[0],s="";int t=0,i=0;for(;i<d.Length;t++)if(!s.Contains(d[i++])){if(s.Contains(d[i]))t++;s+=d[i-1];s+=d[i++];}return t;

```

### Formatted

```
string d = args[0], // deck
s = "";             // seen cards
int t = 0,          // turns taken
i = 0;              // current index
for (; i < d.Length; t++)
    if (!s.Contains(d[i++]))
    {
        if (s.Contains(d[i]))
            t++;
        s += d[i - 1];
        s += d[i++];
    }
return t;

```
> 0 votes

---
Tags: code-golf, game, card-games
---


title: Multiply numerical polynomials

text:
# Question
Title: Multiply numerical polynomials
A numerical polynomial is a polynomial \\$p\\$ in one variable with rational coefficients such that for every integer \\$i\\$, \\$p(i)\\$ is also an integer. The numerical polynomials have a basis given by the binomial coefficients:

$$p\_n = {x \choose n} = \frac{x(x-1)\cdots(x-n+1)}{n!}$$

For instance:

\\$p\_0 = 1\\$
\\$p\_1 = x\\$
\\$p\_2 = \frac{x(x-1)}{2} = \frac{1}{2}x^2 - \frac{1}{2}x\\$
\\$p\_3 = \frac{x(x-1)(x-2)}{6} = \frac{1}{6}x^3 - \frac{1}{2}x^2 + \frac{1}{3}x\\$

The product of any two numerical polynomials is a numerical polynomial, so there are formulas expressing \\$p\_m\times p\_n\\$ as a linear combination of \\$p\_0, p\_1, ..., p\_{m+n}\\$.

Your job is to produce these formulas.

## Goal:

Input: A pair of positive integers \\$m\\$ and \\$n\\$

Output: The list of integers \\$\[a\_1,...,a\_{m+n}\]\\$ of length \\$m+n\\$ such that

$$p\_m\times p\_n = \sum\_{i=1}^{m+n} a\_ip\_i$$

This is code golf, so shortest code wins.

## Examples:

**Input: (1,1)**

We have \\$p\_1 = x\\$, so \\$p\_1\times p\_1 = x^2\\$. The leading term is \\$1x^2\\$, and the leading term of \\$p\_2\\$ is \\$\frac{1}{2!}x^2\\$, so we set \\$a\_2 = \frac{2!}{1} = 2\\$. Subtracting off \\$2p\_2\\$ we have \\$p\_1\times p\_1-2p\_2 = x^2 - (x^2 - x) = x\\$. Thus, we see that \\$p\_1\times p\_1 = p\_1 + 2p\_2\\$, so the output should be \\$\[1,2\]\\$.

**Input: (1,2)**

\\$p\_2 = \frac{1}{2}x(x-1)\\$, so \\$p\_1\times p\_2 = \frac{1}{2}x^2(x-1)\\$, which has leading term \\$\frac{1}{2}x^3\\$. The leading term of \\$p\_3\\$ is \\$\frac{1}{3!}x^3\\$, so we set \\$a\_3 = \frac{3!}{2} = 3\\$. \\$p\_1\times p\_2 - 3p\_3 = x^2-x = 2p\_2\\$, so we deduce that \\$p\_1\times p\_2=0p\_1 + 2p\_2 + 3p\_3\\$, so the output should be \\$\[0,2,3\]\\$.

**Input (2,2)**

The leading term of \\$p\_2^2\\$ is \\$\frac{1}{4}x^4\\$, so we start with \\$p\_2^2-\frac{4!}{4}p\_4\\$. This has leading term \\$x^3\\$, so we subtract off \\$\frac{3!}{1}p\_3\\$ to get \\$p\_2^2-\frac{4!}{4}p\_4-\frac{3!}{1}p\_3\\$. This expression turns out to be equal to \\$p\_2\\$, so rearranging we get that \\$p\_2^2 = 0p\_1+p\_2+6p\_3+6p\_4\\$, so the output should be \\$\[0,1,6,6\]\\$.

## Test Cases:

```
(1,1) ==> [1,2]
(1,2) ==> [0,2,3]
(1,3) ==> [0, 0, 3, 4]
(1,4) ==> [0, 0, 0, 4, 5]
(2,2) ==> [0, 1, 6, 6]
(2,3) ==> [0, 0, 3, 12, 10]
(2,4) ==> [0, 0, 0, 6, 20, 15]
(3,4) ==> [0, 0, 0, 4, 30, 60, 35]
(4,4) ==> [0, 0, 0, 1, 20, 90, 140, 70]

```

# Answer
> 8 votes
# APL (Dyalog Extended), <sub>~~20~~</sub> 18 bytes

```
,((×⌿!\)⌹⊢!⍨\⊢)⍳⍤+

```

Try it online!

A tacit dyadic function that takes `m` and `n` as left and right arguments respectively. Mainly uses the matrix division built-in  to solve the linear equations:

$$ \begin{bmatrix} \binom{1}{1} & \binom{1}{2} & \cdots & \binom{1}{n+m} \\ \binom{2}{1} & \binom{2}{2} & \cdots & \binom{2}{n+m} \\ \vdots & \vdots & \ddots & \vdots \\ \binom{n+m}{1} & \binom{n+m}{2} & \cdots & \binom{n+m}{n+m} \end{bmatrix} \begin{bmatrix} a\_1 \\ a\_2 \\ \vdots \\ a\_{n+m} \end{bmatrix} = \begin{bmatrix} \binom{1}{n} \binom{1}{m} \\ \binom{2}{n} \binom{2}{m} \\ \vdots \\ \binom{n+m}{n} \binom{n+m}{m} \end{bmatrix} \Leftrightarrow Ba = v $$

When \\$ B \\$ and \\$ v \\$ are ready, the answer is simply `v⌹B`. So the main work is to golf the parts to build \\$ B \\$ and \\$ v \\$.

### How it works

```
,((×⌿!\)⌹⊢!⍨\⊢)⍳⍤+  ⍝ Left argument: n, Right argument: m
,(            )⍳⍤+  ⍝ Pass [n m] and [1 .. n+m] to the inner function
         ⊢!⍨\⊢      ⍝ Compute B
  (×⌿!\)            ⍝ Compute v
        ⌹           ⍝ Solve the linear equation

```

### Computing \\$ B \\$

`x!y` computes \\$ \binom{y}{x} \\$.

```
⊢!⍨\⊢  ⍝ Left: [n m], Right: [1 .. n+m]
⊢   ⊢  ⍝ Use right argument for both sides (L, R)
 !⍨\   ⍝ Outer product by flipped binomial:
       ⍝ For each pair of l∊L and r∊R, compute r!l or lCr

```

### Computing \\$ v \\$

```
×⌿!\  ⍝ Left: [n m], Right: [1 .. n+m]
  !\  ⍝ Outer product by binomial function
      ⍝ Result is a matrix of two rows [U V]
×⌿    ⍝ Reduce by multiply; compute U×V element-wise

```

# Answer
> 6 votes
# Haskell, 74 bytes

```
a%b|let a?i|a<1=0^(i-b)^2|d<-a-1=div(i*d?(i-1)-(d-i)*d?i)a=map(a?)[1..a+b]

```

Try it online!

Uses a recursive formulation I found. Let \\$g\_b(a,i)\\$ be the coefficient of \\$p\_i\\$ in \\$p\_a p\_b\\$, which is implemented in the code by `a?i` (with `b` fixed). We can express \\$g\_b\\$ recursively as

$$g\_b(a,i)=\frac{i\cdot g\_b(a-1,i-1)-(a-1-i)\cdot g\_b(a-1,i-1)}{a}$$

with base case $$g\_b(0,i)= \begin{cases} 1,\text{ if }b=i\\ 0,\text{ otherwise}\\ \end{cases} $$

The base case corresponds to the expansion for \\$p\_b\\$, which has a single nonzero coefficient of \\$p\_i\\$ at \\$i=b\\$. The code implements this indicator function as `0^(i-b)^2`.

The code has guards belonging to the definition of `?` in the `let` binding. It's perhaps easier to read as the following (non-working) code where the definition of `a?i` expects `b` as a global variable. Perhaps confusingly, the `a` in the definition of `?` is not always the same as the input to `%`, since it recurses down.

```
a?i|a<1=0^(i-b)^2|d<-a-1=div(i*d?(i-1)-(d-i)*d?i)a
a%b=map(a?)[1..a+b]

```

The main function `%` lists the coefficients for each `i` from 1 to a+b. It's possible to code the recursion in `%` directly by zipping shifted lists, but I did not find a short way to do it especially with the dependence on the position `i`.

# Answer
> 5 votes
# Haskell, 84 bytes

```
n#m=[foldr1(-)[i!k*k!n*k!m|k<-[i,i-1..0]]|i<-[1..n+m]]
_!0=1
n!k=n*(n-1)!(k-1)`div`k

```

Try it online!

## Explanation

Given a polynomial \\$q\\$, the following algorithm (see here) computes the unique coefficients \\$a\_0,a\_1,\ldots\\$ such that \\$q=a\_0p\_0+a\_1p\_1+\ldots\\$.

Let $$ \Delta^{(0)}q(x)=q(x)\\ \Delta^{(i+1)}q(x)=\Delta^{(i)}q(x+1)-\Delta^{(i)}q(x). $$

Then \\$a\_i=\Delta^{(i)}q(0)\\$.

Moreover, it can be easily proved that $$ \Delta^{(i)}q(0)=\sum\_{k=0}^{i}(-1)^{i-k}{i\choose k}q(k). $$

---

```
_!0=1
n!k=n*(n-1)!(k-1)`div`k

```

`n!k` is the binomial coefficient \\$n\choose k\\$.

---

```
n#m=[foldr1(-)[i!k*k!n*k!m|k<-[i,i-1..0]]|i<-[1..n+m]]

```

The function `#` computes the answer to the challenge. It simply uses the observation above to compute $$ a\_i=\sum\_{k=0}^{i}(-1)^{i-k}{i\choose k}{k\choose n}{k\choose m}. $$ The `foldr1(-)` is the only thing that needs explaining. When applied to a list \\$\[b\_0,b\_1,\ldots,b\_l\]\\$, `foldr1(-)` returns $$ b\_0-(b\_1-(\ldots-(b\_{l-1}-b\_l)\ldots)=\sum\_{j=0}^{l}(-1)^jb\_j $$

---

# Haskell, ~~108~~ 100 bytes

I'm also keeping this one. It is, in my opinion, more elegant, albeit much more verbose.

```
n#m=take(n+m).tail$head<$>iterate(zipWith(-)=<<tail)[x!n*x!m|x<-[0..]]
_!0=1
n!k=n*(n-1)!(k-1)`div`k

```

Try it online!

---

```
_!0=1
n!k=n*(n-1)!(k-1)`div`k

```

`n!k` is the binomial coefficient \\$n\choose k\\$.

---

```
n#m=take(n+m).tail$head<$>iterate(zipWith(-)=<<tail)[x!n*x!m|x<-[0..]]

```

The function `#` computes the answer to the challenge. Let \\$q=p\_n\cdot p\_m\\$.

* `[x!n*x!m|x<-[0..]]` is the infinite list $$ \left\[{0\choose n}{0\choose m},{1\choose n}{1\choose m},{2\choose n}{2\choose m},\ldots\right\] $$ i.e. $$ \[q(0),q(1),q(2),\ldots\]. $$
* Given a list \\$\[b\_0,b\_1,b\_2,\ldots\]\\$, the function `zipWith(-)=<<tail` returns \\$\[b\_1-b\_0,b\_2-b\_1,\ldots\]\\$. Thus the code `head<$>iterate(zipWith(-)=<<tail)[x!n*x!m|x<-[0..]]` returns the infinite list $$ \[\Delta^{(0)}q(0),\Delta^{(1)}q(0),\Delta^{(2)}q(0),\ldots\]=\[a\_0,a\_1,a\_2,\ldots\]. $$
* Finally with `take(n+m).tail` we drop \\$a\_0\\$ and we take the first \\$n+m\\$ coefficients, thereby solving the challenge.

# Answer
> 4 votes
# Pari/GP, 46 bytes

```
m->n->b=binomial;[b(m,i-n)*b(i,m)|i<-[1..m+n]]

```

Try it online!

I did not expect the formula to be so simple: the \\$i\\$-th element of the output for \\$(m,n)\\$ is \\${m \choose i-n} {i \choose m}\\$.

In fact, it can be proven that \\$\sum\_{i=0}^{m+n} {m \choose i-n} {i \choose m} {x \choose i} = {x \choose m} {x \choose n}\\$. The RHS counts the number of ways to choose two subsets of \\$\\{1,2,\dots,x\\}\\$ of size \\$m\\$ and \\$n\\$ respectively; while the LHS counts, for each \\$i\\$, the number of ways to choose a subset of size \\$i\\$, and two subsets of size \\$m\\$ and \\$n\\$ respectively whose union is the chosen subset of size \\$i\\$.

---

## Pari/GP, 62 bytes

Saved one byte thanks to Mr. Xcoder.

```
m->n->b=matpascal(m+n);([b[i,m+1]*b[i,n+1]|i<-[1..#b]]/b~)[^1]

```

Sadly, GP does not have a built-in for pointwise product.

Try it online!

# Answer
> 2 votes
# Wolfram Language (Mathematica), 37 bytes

```
b[r=Range@+##,#]b[#,r-#2]&
b=Binomial

```

Try it online!

-5 bytes thanks to att.

---

## Wolfram Language (Mathematica), 42 bytes

```
Table[b=Binomial;b[#,i-#2]b[i,#],{i,+##}]&

```

Try it online!

---

## Wolfram Language (Mathematica), 57 bytes

Saved one byte thanks to Misha Lavrov.

```
Inverse[b=Array[Binomial,0{,}+##]].(b[[;;,#]]b[[;;,#2]])&

```

Try it online!

# Answer
> 1 votes
# JavaScript (ES6), 109 bytes

This is really just a port of Delfad0r's great answer, implemented as nested recursive functions.

Takes input as `(n)(m)`.

```
n=>m=>(g=i=>i?[...g(i-1),(h=k=>k&&h(k-1)-(b=(y,x=k)=>y?x*b(y-1,x-1)/y:i-k&1||-1)(k,i)*b(n)*b(m))(i)]:[])(n+m)

```

Try it online!

### How?

The function \\$b(y,x)\\$ computes:

$$-(-1)^{i-k}{x\choose y}$$

It's slightly shorter to return \\$-(-1)^{i-k}\\$ as the last iteration of this function than processing it separately. Because we compute the product of three binomial coefficients, the signs of the first two of them are simply cancelling each other out.

The function \\$h()\\$ is used to compute:

$$\sum\_{k=1}^{i}-b(k,i)\times b(n,k)\times b(m,k)\\ =\sum\_{k=1}^{i}{(-1)^{i-k}{i\choose k}{k\choose n}{k\choose m}}$$

And the function \\$g()\\$ is used to compute each term \\$a\_i\\$ for \\$1\le i \le n+m\\$.

# Answer
> 1 votes
# Maxima, 55 bytes

Golfed version. Try it online!

```
f(m,n):=makelist(binomial(m,i-n)*binomial(i,m),i,1,m+n)

```

Ungolfed version. Try it online!

```
f(m,n) := block(
    local(i),
    makelist(binomial(m,i-n)*binomial(i,m), i, 1, m+n)
)$

for x in [[1, 1], [1, 2], [1, 3], [1, 4], [2, 2], [2, 4], [3, 3], [3, 4], [4, 4]] do (
    print(x[1], " -> ", f(x[1], x[2]))
)$

```

# Answer
> 1 votes
# Haskell, 61 bytes

```
n#m=[n!(m+n-i)*i!n|i<-[1..n+m]]
_!0=1
n!k=n*(n-1)!(k-1)`div`k

```

Try it online!

Based on @Delfad0r's answer, but using the formula in my PARI/GP answer.

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


title: The rectangle spanned by two numbers

text:
# Question
Title: The rectangle spanned by two numbers
One way to generalize the concept of a range from the integers to the Gaussian integers (complex numbers with integer real and imaginary part) is taking all numbers contained in the rectangle enclosed by the two ends of the range. So the range between two Gaussian integers `a+bi` and `c+di` would be all Gaussian integers `x+iy` with `min(a,c)<=x<=max(a,c)` and `min(b,d)<=y<=max(b,d)`.

For instance the range from `1-i` to `-1+2i` would be the following set of numbers:

`-1-i, -1, -1+i, -1+2i, -i, 0, i, 2i, 1-i, 1, 1+i, 1+2i`

Your task is given two numbers `a+bi` and `c+di` to return the 2D range spanned by `a+bi` to `c+di`

## Examples

```
1       5      -> [1,2,3,4,5]
5       1      -> [5,4,3,2,1]
-1      -3     -> [-3,-2,-1]
1+i     1+i    -> [1+i]
1-i     -1+2i  -> [-1-i, -1, -1+i, -1+2i, -i, 0, i, 2i, 1-i, 1, 1+i, 1+2i]
1-i     2+i    -> [1-i, 1, 1+i, 2-i, 2, 2+i]
-2-i     -1+3i  -> [-2-i, -2, -2+i, -2+2i, -2+3i, -1-i, -1, -1+i, -1+2i, -1+3i, -i, 0, i, 0+2i, 0+3i, 1-i, 1, 1+i, 1+2i, 1+3i]

```

## Rules

* You can use pairs of integers to Input/Output Complex numbers
* If your language has a built-it for generating this range, please consider adding a non built-in answer as well
* The elements in the range can be sorted in any order
* Each element can only appear once in the range
* This is the shortest solution (per language) wins

# Answer
> 7 votes
# Vyxal, 2 bytes

```
ṡΠ

```

Try it Online!

```
ṡ  # Vectorised range
 Π # Cartesian product

```

# Answer
> 6 votes
# , 20 bytes

```
<.+"1[:(#:,@i.)1+|@-

```

Attempt This Online!

For positive integers `x` and `y`, `i.(x,y)` creates a matrix of

```
0      1        2        ... y-1
y      y+1      y+2      ... 2y-1
...
(x-1)y (x-1)y+1 (x-1)y+2 ... xy-1

```

Then `(x,y)#:` converts each number `iy + j` to a pair `(i,j)`.

```
<.+"1[:(#:,@i.)1+|@-   Input: two pairs of integers
                 |@-   Elementwise absolute difference
               1+      Add 1 to each
     [:(      )        Apply monadically:
          ,@i.           Create 2D range and flatten
        #:               Base convert as described above
<.+"1                  Add elementwise minimum of two inputs to each row

```

# Answer
> 5 votes
# K (ngn/k), 18 bytes

```
++/(!1--)\(&;|)@\:

```

Try it online!

-1 thanks to ovs.

# K (ngn/k), 19 bytes

```
{+a+!1+(x|y)-a:x&y}

```

Try it online!

A function that takes two complex numbers as integer pairs `x` and `y`.

`!(x,y)` generates a two-row matrix whose columns are the cartesian pairs of `0..x` and `0..y` (excluding x and y).

# Answer
> 4 votes
# , 47 bytes

The following dyad does the job, taking as left and right arguments the range edges:

```
   ([:>@,@{(<.<@:+i.@(+_1+2*0&<:)@:-~)/"1@,.)&.:+.

```

J uses ajb for denoting the number a+b\*i, for instance:

```
   1j1 ([:>@,@{(<.<@:+i.@(+_1+2*0&<:)@:-~)/"1@,.)&.:+. 2j2
1j1 1j2 2j1 2j2

```

See this Demonstration on the J playground (press the "run" button on the upper right of the editor).

## Explanation

```
([:  >@,@{  (<.<@:+i.@(+_1+2*0&<:)@:-~) /"1@,.) &.:+.
 __ _____  ___________________________ ___ __ _____: under complex decompose
cap  |      |                           |    \combine real and imag parts
     |      |                           \insert verb in () in each row
     |      \ verb creating boxed real/imag ranges (explained below)
     \ open raveled Carthesian product between boxed coordinate ranges

 <.  <@:+  i.@(+_1+2*0&<:)@:-~  fork; takes x, y and returns a boxed range.
___  ____  __ ____________  __
|    |     |  |             \_ difference between y and x
|    |     |  \_ adjust diff s.t. works for empty and reversed ranges
|    |     \_ range from 0 to y-1
|    \_ add min and range and box the result
\_ min of x and y

```

# Answer
> 3 votes
# Raku, 41 bytes

```
{($^x.re...$^y.re)X+(($x.im...$y.im)X*i)}

```

Try it online!

This anonymous function takes two complex numbers are arguments.

`$^x.re ... $^y.re` is the range of integers between the real parts of the arguments; `...` is smart enough to make a decreasing range as appropriate. Similarly, `$x.im ... $y.im` is the range of integers between the imaginary parts of the arguments. `X* i` multiplies each element of the latter range by `i`, and `X+` crosses the two ranges together with addition.

# Answer
> 3 votes
# Jelly, 3 bytes

```
rp/

```

A dyadic Link that accepts the two pairs of real and imaginary parts and yields a list of pairs of real and imaginary parts.

**Try it online!**

### How?

```
rp/ - Link: [R1, I1]; [R2, I2]
r   - inclusive range -> [[R1..R2], [I1..I2]]
  / - reduce by:
 p  -   Cartesian product

```

---

`rŒp` does the same thing, where `Œp` is the Cartesian product of the items of `[[R1..R2], [I1..I2]]`.

# Answer
> 3 votes
# Bash, 49 bytes

```
eval echo \{${1%,*}..${2%,*}},\{${1#*,}..${2#*,}}

```

Try it online!

# Answer
> 3 votes
# Desmos, 44 bytes

```
f(A,B)=[(X,Y)forX=[A.x...B.x],Y=[A.y...B.y]]

```

Complex numbers \\$a+bi\\$ are represented with coordinate pairs \\$(a,b)\\$. Input is two coordinate pairs, output is a list of coordinate pairs.

Try It On Desmos!

Try It On Desmos! - Prettified

# Answer
> 3 votes
# , 30 bytes

```
\(a,b,c,d)expand.grid(a:c,b:d)

```

Attempt This Online!

Takes input as four numbers `a,b,c,d` and returns a matrix with real and imaginary parts in columns.

---

# , 35 bytes

```
\(x,y)outer(x:y,Im(x):Im(y)*1i,`+`)

```

Attempt This Online!

Input and output as complex numbers.

# Answer
> 2 votes
# Ruby, 58 bytes

```
->a,b{r,i=a.zip b;[*r.min..r.max].product [*i.min..i.max]}

```

Attempt This Online!

# Answer
> 2 votes
# Charcoal, 27 bytes

```
Ｆθ⊞υ⊟ιＩΣＥ…·⌊υ⌈υＥ…·⌊⌊θ⌈⌈θ⟦λι

```

Attempt This Online! Link is to verbose version of code. Uses pairs of integers for I/O, and takes a pair of pairs as input. Explanation:

```
Ｆθ⊞υ⊟ι

```

Separate out the imaginary parts.

```
ＩΣＥ…·⌊υ⌈υＥ…·⌊⌊θ⌈⌈θ⟦λι

```

Form inclusive ranges over the imaginary and real parts and make into pairs.

Previous 19-byte answer only worked with ascending ranges:

```
ＩΣＥ…·⊟θ⊟ηＥ…·ΣθΣη⟦λι

```

Attempt This Online! Link is to verbose version of code. Uses pairs of integers for I/O. Explanation:

```
   …·               Inclusive range from
     ⊟θ             First imaginary part to
       ⊟η           Second imaginary part
  Ｅ                 Map over values
          …·        Inclusive range from
            Σθ      First real part to
              Ση    Second real part
         Ｅ          Map over values
                 λ  Real part
                  ι Imaginary part
                ⟦   Make into pair
 Σ                  Flatten 1 level
Ｉ                   Cast to string
                    Implicitly print

```

# Answer
> 2 votes
# sclin, 29 bytes

```
";"zip Q*
,""sort"1+"' ,_ a>b

```

Try it here! Inputs/outputs pairs representing complex numbers.

For testing purposes:

```
[1 1_ ] [1_ 3] ; >A
";"zip Q*
,""sort"1+"' ,_ a>b

```

## Explanation

Prettified code:

```
\; zip Q*
, () sort 1.+ ' ,_ a>b

```
* `\; zip` zip inputs...
    + `, () sort` pair and sort ascending
    + `1.+ '` increment second number in pair
    + `,_ a>b` exclusive range from pair
* `Q*` Cartesian product

An inclusive range function would actually provide a substantial byte-save here, entirely removing the need to sort/increment pairs.

# Answer
> 2 votes
# Excel, 155 bytes

```
=LET(
    a,+A1:A2,
    b,HSTACK(SORT(IMREAL(a)),SORT(IMAGINARY(a))),
    c,LAMBDA(d,LET(e,INDEX(b,1,d),+SEQUENCE(1+INDEX(b,2,d)-e,,e))),
    TOCOL(COMPLEX(c(1),TOROW(c(2))))
)

```

Inputs are complex numbers in cells `A1` and `A2`.

# Answer
> 2 votes
# Japt, 7 bytes

I/O as pairs of integers

```
ÕËrõÃrï

```

Try it

```
ÕËrõÃrï     :Implicit input of 2D integer array
Õ           :Transpose
 Ë          :Map
  r         :  Reduce by
   õ        :    Inclusive range
    Ã       :End map
     r      :Reduce by
      ï     :  Cartesian product

```

# Answer
> 2 votes
# MATL, 5 bytes

```
:i:Z*

```

Input: two cell arrays of two numbers each. Output: pairs of numbers separated by newlines.

**Try it online!**

### Explanation

```
:    % Implicit input: cell array of two numbers. Range
i:   % Input: cell array of two numbers. Range
Z*   % Cartesian product. Implicit display

```

# Answer
> 2 votes
# 05AB1E, 5 bytes

```
ø€Ÿ`â

```

Input as a pair of pairs of regular integers.

Try it online.

**Explanation:**

```
ø      # Zip/transpose the (implicit) input 2x2-block, swapping rows/columns
 €     # Map over both pairs:
  Ÿ    #  Convert the pair to a ranged list
   `   # Pop and push both lists separately to the stack
    â  # Pop both, and create all possible pairs with the cartesian product
       # (after which the result is output implicitly)

```

# Answer
> 2 votes
# Haskell \+ hgl, 9 bytes

```
sQ<<zW eR

```

Takes two lists of length two as input.

```
>>> (sQ<<zW eR) [1,2] [-3,3]
[[1,2],[1,3],[0,2],[0,3],[-1,2],[-1,3],[-2,2],[-2,3],[-3,2],[-3,3]]

```

## Explanation

* `zW eR` zip with the reversable range
* `sQ` generalized cartesian product

## Reflection

* There should be a builtin for cartesian product. `l2(,)` is way too long.
* At this point `Uc` should be promoted to `U`. `Uc` is frequently used and its not like there is anything else that is going to use the `U` character.
* There should be a couple of things in terms of arrows that could be implemented for this.

# Answer
> 1 votes
# Mathematica, 100 bytes

100 bytes, it can be golfed much more.

Try it online!

```
f[a_,b_]:=Flatten@Table[r~Complex~i,{r,Re@a~Min~Re@b,Re@a~Max~Re@b},{i,Im@a~Min~Im@b,Im@a~Max~Im@b}]

```

# Answer
> 1 votes
# JavaScript (V8), 89 bytes

```
f=(x,y,X,Y=y)=>y-Y?f(x,y,X)|f(x,y+(Y>y||-1),X,Y):x-X?f(x,y)|f(x+(X>x||-1),y,X):print(x,y)

```

Try it online!

Silly

---
Tags: code-golf, complex-numbers
---


title: Mirror quine (or my head hurts)

text:
# Question
Title: Mirror quine (or my head hurts)
I was reading Print your code backwards - reverse quine And I thought, this could be more interesting if your **backwards code is also executable**. So this challenge will have all the rules and requirements of the other, but must also be valid source once reversed (in the same or another language and still print its source backwards).

All rules and scoring from the reverse quine challenge apply, so all answers to this question will answer that one (but not score as well).

## Rules:

* Write a program p which when executed produces output p' where p' is p backwards and p' when executed produces p.
* No using other files (e.g. `reverse.txt`)
* Minimum code length is two characters.
* **Your program cannot be a palindrome.**

## Scoring:

* +50 if you use pull data from the Internet.
* +25 if you read your own source code.
* +1 point per character.
* Lowest score wins.

# Answer
## GolfScript, 46 chars

```
0{`".~#"+.-1%+\.!@@}.~##~.}@@!.\+%1-.+"#~."`{1

```

Well, this is ugly, but it works. The output equals the code reversed, and is also a valid GolfScript program which outputs the original code again.

OK, let me try to explain how I constructed it. First, I started from the quine `{".~"}.~`, and modified it as in this answer to reverse itself. To make the output an executable quine in itself, I made a copy of the code before reversing it, and included a `#` at the end of the code, so that the reversed version at the end became just a comment. Thus, we get the palindromic quine:

```
{`".~#"+.-1%}.~##~.}%1-.+"#~."`{

```

However, by the rules, palindromes are not allowed, so I needed to break the symmetry somehow. I figured the easiest way would be to include a `0` (which, in itself, is a quine in GolfScript) in the code and flip it to `1` with `!` after creating the reversed copy. Most of the remaining complexity is just ugly stack manipulation to get everything in the right order.
> 23 votes

# Answer
## Perl and C ~~6478~~ 1955

```
#!/usr/bin/perl -i//
$_=<<'rahc';eval $_; #//
print scalar reverse "#!/usr/bin/perl -i//\n\$_=<<'rahc';eval \$_; #//\n${_}rahc\n" #//
__END__
__END__ enifed#
};)"{ = ][cn\rahcn\n\"(p
};)'n\'( rahctup) 1 == 21%b ( fi
;)d(p;)]1-b[c,",d%",)d(foezis,d( ftnirpns{)b--;b;)c(foezis=b( rof
;)c(p;]9[d rahc;b tni{)(niam diov
}};)]1-b[c(rahctup )]1-b[c(fi{)b--;b;)c(nelrts=b(rof;b tni{)c*rahc(p diov
>h.gnirts< edulcni#
>h.oidts< edulcni#
;}
,0
,53,33,74,711,511,411,74,89,501,011,74,211
,101,411,801,23,54,501,74,74,01,63,59,16
,06,06,93,411,79,401,99,93,95,101,811,79
,801,23,63,59,95,23,53,74,74,01,211,411
,501,011,611,23,511,99,79,801,79,411,23,411
,101,811,101,411,511,101,23,43,53,33,74,711
,511,411,74,89,501,011,74,211,101,411,801,23
,54,501,74,74,29,011,29,63,59,16,06,06
,93,411,79,401,99,93,95,101,811,79,801,23
,29,63,59,95,23,53,74,74,29,011,63,321
,59,521,411,79,401,99,29,011,43,23,53,74
,74,01,59,59,96,87,86,59,59,01,59,59
,96,87,86,59,59,23,101,011,501,201,101,001
,53,01,521,95,14,43,321,23,16,23,39,19
,99,011,29,411,79,401,99,011,29,011,29,43
,04,211,01,521,95,14,93,011,29,93,04,23
,411,79,401,99,611,711,211,14,23,94,23,16
,16,23,05,94,73,89,23,04,23,201,501,01
,95,14,001,04,211,95,14,39,94,54,89,19
,99,44,43,44,001,73,43,44,14,001,04,201
,111,101,221,501,511,44,001,04,23,201,611,011
,501,411,211,011,511,321,14,89,54,54,95,89
,95,14,99,04,201,111,101,221,501,511,16,89
,04,23,411,111,201,01,95,14,99,04,211,95
,39,75,19,001,23,411,79,401,99,95,89,23
,611,011,501,321,14,04,011,501,79,901,23,001
,501,111,811,01,521,521,95,14,39,94,54,89
,19,99,04,411,79,401,99,611,711,211,23,14
,39,94,54,89,19,99,04,201,501,321,14,89
,54,54,95,89,95,14,99,04,011,101,801,411
,611,511,16,89,04,411,111,201,95,89,23,611
,011,501,321,14,99,24,411,79,401,99,04,211
,23,001,501,111,811,01,26,401,64,301,011,501
,411,611,511,06,23,101,001,711,801,99,011,501
,53,01,26,401,64,111,501,001,611,511,06,23
,101,001,711,801,99,011,501,53,01,95,521,01
{ = ][c
rahc

```

# Edit:

Brief explanation: from perl the two interesting lines are the second and the third. The second line has two statements the first of which reads the rest of the document into a string. The second evals the string. The Third line prints everything backwards. every thing else gets ignored. from the c side you have an array which has the program as a string, which gets printed as an array and a string, and the rest is a comment.
> 21 votes

# Answer
# Ruby 145

```

DATA.read.tap{|a|puts a.reverse,a.tr("\x79\x59","\x59\x79")}
:y
__END__
__DNE__
Y:
})"97x\95x\","95x\97x\"(rt.a,esrever.a stup|a|{pat.daer.ATAD

```

The main idea is simple: just put the first half of the source code backwards after the `__END__` which can be read using `DATA` from ruby. Then just print the reverse of this data, then print the data, and you get back the original source code

The problem is, that this becomes a palindrome (note that the first line needs an endline), so we have to break the symmetry. I just added a symbol `:y` to the code, and some code that will transform this symbol between lowercase and uppercase between runs, thereby reverting to the original state after two runs.

Test one: they can be executed

```
$ ruby rq2.rb > rq2t.rb
$ ruby rq2t.rb > rq2tt.rb

```

Test two: the result of two runs will return the original source

```
$ diff rq2.rb rq2tt.rb
$

```

Test three: the code is not a palindrome (the middle run is different)

```
$ diff rq2.rb rq2t.rb
3c3
< :y
---
> :Y
6c6
< Y:
---
> y:

```
> 8 votes

# Answer
# Gol\>\<\>, 11 bytes

```
":5-}H}+5:'

```

A whole byte chopped off! it almost is a palindrome, but technically isn't because of the '+' and '-', haha!

Try it online!

**The two below don't work, or at least they don't meet the specifications of the challenge, but the code above does.**

**slightly younger version, 12 bytes**

```
"r2ssrH}+5:'

```

Golfed off a byte, simply by using the double quote and incrementing it by 5! And this new version looks less like a palindrome.

Try it online!

**older version, 13 bytes**

```
"r2ssrHrss7r'

```

There was a problem with the previous that JoKing pointed out, thank you for that, now it works, but with the price of 4 extra bytes...

Try it online!
> 5 votes

# Answer
# Python 3.8 (pre-release), 99 bytes

## forward :

```
a=1;exec(s:=#)]a::[
"print(('a=1;exec(s:=#)]a::[\\n%r\\n)#=:s(cexe;1-=a'%s)[::-a])"
)#=:s(cexe;1-=a

```

Try it online!

## backward:

```
a=-1;exec(s:=#)
")]a-::[)s%'a=-1;exec(s:=#)n\\r%n\\[::a])#=:s(cexe;1=a'((tnirp"
[::a])#=:s(cexe;1=a

```

Try it online!

## How it works:

I based my solution on the quine `exec(s:="print('exec(s:=%r)'%s)")`

* In the forward solution, `a=1` transforms the slices to have something like :

```
exec(s:="print('<string for the quine>'[::-1])")

```

which prints the backward quine

* in the backward solution, `a=-1` transforms the slice to have something like :

```
exec(s:=")]1::['<string for the quine in backward>'(tnirp"[::-1])

```

which (due to the `[::-1]`) gives:

```
exec(s:="print('<string for the quine>'[::1])")

```

and prints the original quine
> 5 votes

# Answer
# \>\<\>, ~~21~~ 19 bytes

```
'rd3*70.r l?!;o90.<

```

Try it here!

Uses the \*\>\<\> interpreter for convenience, but this is valid \>\<\> code.

---

If erroring out is allowed, then it can be done in 16 bytes:

```
'd3*}70.!r  !|o|

```

Try it here!
> 4 votes

# Answer
# Help, WarDoq! (27 bytes)

25 bytes added because of reading source code.

```
<space>q

```

How it works:
`<space>` \- a comment that ends on non-space character
`q` \- print source code reversed (q"space")

### Reversed:

```
q<space>

```

How it works:
`q` \- print source code reversed (q for now)
`<space>` \- a comment that ends on non-space character, and add a character to beginning of q command (making "space"q)
> 2 votes

# Answer
# JavaScript (V8), 817 bytes

I'm sure this can be golfed further. I might also try to translate this into Python.

```
//))""(nioj.)(esrever.])q+s+q(nioj.))53(edoCrahCmorf.gnirtS(tilps.)c,)63(edoCrahCmorf.gnirtS(ecalper.)q+c+q,)33(edoCrahCmorf.gnirtS(ecalper.))""(nioj.)(esrever.]c...[,)621(edoCrahCmorf.gnirtS(ecalper.s...[(gol.elosnoc
c=//
`console.log([...s.replace(String.fromCharCode(126),[...c].reverse().join("")).replace(String.fromCharCode(33),q+c+q).replace(String.fromCharCode(36),c).split(String.fromCharCode(35)).join(q+s+q)].reverse().join(""))//`
//=c
s=//
`~
c=//
!
//=c
s=//
#
//=s
q=String.fromCharCode(96)//
//)69(edoCrahCmorf.gnirtS=q
$`
//=s
q=String.fromCharCode(96)//
//)69(edoCrahCmorf.gnirtS=q
console.log([...s.replace(String.fromCharCode(126),[...c].reverse().join("")).replace(String.fromCharCode(33),q+c+q).replace(String.fromCharCode(36),c).split(String.fromCharCode(35)).join(q+s+q)].reverse().join(""))//

```

Try it online!

## How?

Line comments at the end of the line comment out that line in the reversed version.

Although the entire program is not a palindrome, it is made up of several palindromic or semi-palindromic sections. These are not true palindromes, but are close enough.

```
// This line is the last line reversed
//))""(nioj.)(esrever.])q+s+q(nioj.))53(edoCrahCmorf.gnirtS(tilps.)c,)63(edoCrahCmorf.gnirtS(ecalper.)q+c+q,)33(edoCrahCmorf.gnirtS(ecalper.))""(nioj.)(esrever.]c...[,)621(edoCrahCmorf.gnirtS(ecalper.s...[(gol.elosnoc

// This is a palindrome (apart from the string in the middle)
c=//
`console.log([...s.replace(String.fromCharCode(126),[...c].reverse().join("")).replace(String.fromCharCode(33),q+c+q).replace(String.fromCharCode(36),c).split(String.fromCharCode(35)).join(q+s+q)].reverse().join(""))//`
//=c

// This is a palindrome (apart from the string in the middle)
s=//
`~
c=//
!
//=c
s=//
#
//=s
q=String.fromCharCode(96)//
//)69(edoCrahCmorf.gnirtS=q
$`
//=s

// This is also a palindrome
q=String.fromCharCode(96)//
//)69(edoCrahCmorf.gnirtS=q

// This line is the first line reversed
console.log([...s.replace(String.fromCharCode(126),[...c].reverse().join("")).replace(String.fromCharCode(33),q+c+q).replace(String.fromCharCode(36),c).split(String.fromCharCode(35)).join(q+s+q)].reverse().join(""))//

```

Apart from this, it's a pretty standard quine. Writing the code twice, once in code and once in a string, and substituting the string into itself is a common quine technique.
> 1 votes

# Answer
# Julia, <sup>~~194~~</sup> 177 bytes

```
~=reverse;(s= #lave>|esrap.ateM>|))
"print(~\"~=reverse;(s= #lave>|esrap.ateM>|))\\n\$(~repr(~s))\\n)|>Meta.parse|>eval#(esrever=s(;* =~\")"
)|>Meta.parse|>eval#(esrever=s(;* =~

```

Attempt This Online!

port of Jakque's answer, Julia is not very good at quines

**previous answer, 194 bytes:** `(q=:(print(replace((k = "(q=:($(q)))|>eval#") |> (*), 'q' => :Q, 'Q' => :q), reverse(k))))|>eval##lave>|))))k(esrever ,)Q: >= 'q' ,q: >= 'Q' ,)*( >| )"#lave>|)))Q($(:=Q(" = k((ecalper(tnirp(:=Q(`

based on this quine, by appending the reversed program in a comment, and switching between lowercase and uppercase `Q` so it's not a palindrome
> 0 votes

---
Tags: code-golf, quine, source-transformation
---


# Question
Title: Print your code backwards - reverse quine
Write a program that prints its own source code out backwards, in other words an *eniuq*.

**Scoring:**

* +50 if you use pull data from the Internet.
* +25 if you read your own source code.
* +1 point per character
* Lowest score wins.

**Rules:**

* No using other files (e.g. `reverse.txt`)
* Minimum code length is two characters.
* **Your program cannot be a palindrome.**

# Answer
> 75 votes
# GolfScript - 2

```

1

```

(ie `\n1` where `\n` is the newline character)

Output:

```
1

```

(ie `1\n`)

---

To quote Ilmari:

> GolfScript automatically appends a newline to the end of the output

Thus a newline followed by a number will print the number followed by a newline.

# Answer
> 104 votes
## huh?, 5 characters

```
!hcuO

```

I actually have NO idea how it works, but If you download the interpreter, and if you write `!hcuO`, then you get `Ouch!`

To run this, you need to execute the program like this:

```
huh.exe !hcuO

```

It will actually look for a file called `!hcuO`, but it doesn't exist, so it outputs `Ouch!`

# Answer
> 93 votes
# Mathematica, 3 chars

```
a 2

```

`a 2` means `a` times 2. So the answer is `2 a`.

# Answer
> 70 votes
## H9+, 13 characters

```
!dlrow ,olleH

```

As the web page says, all characters that are not `H`, `9` or `+` are ignored, so my program will print `Hello, world!`

# Answer
> 46 votes
## Javascript: 34 characters

```
reifitnedi detcepxenU :rorrExatnyS

```

outputs `SyntaxError: Unexpected identifier`, at least in the Chrome console

# Answer
> 29 votes
# Python, ~~43~~ 41

```
_=']0~::[_%%_ tnirp;%r=_';print _%_[::~0]

```

# Answer
> 27 votes
# Mathematica, 2 bytes

```
1#

```

Outputs:

> #1

# Answer
> 22 votes
## TI-BASIC, 2

```
i2

```

Where `i` is the imaginary number.

Outputs `2i`

# Answer
> 19 votes
# BASIC, ~~22~~ ~~12~~ 7 characters

:-)

```
1 enil ni rorre xatnyS

```

**EDIT:** If you're allowed to enter the program in immediate mode, then this could be reduced to `rorre xatnyS` (12 characters).

In BBC BASIC, you only need 7 characters:

```
ekatsiM

```

# Answer
> 17 votes
**ksh** (**21 chars**)

```
$ dnuof ton :found :hsk
ksh: dnuof: not found

```

---

**bash** (31 chars)

```
$ dnuof ton dnammoc :found :hsab-
-bash: dnuof: command not found

```

---

**sh** (29 chars)

```
$ dnuof ton dnammoc :found :hs-
sh: dnuof: command not found

```

This one could not work on some Linux distributions, but works on OSX.

---

**tcsh** (26 chars)

```
$ .dnuof ton dnammoC :found.
.dnuof: Command not found.

```

---

**csh** (26 chars)

```
% .dnuof ton dnammoC :found.
.dnuof: Command not found.

```

---

Above should work on all \*unix based OS.

---

Assumptions:

* You don't have `dnuof` command or alias present.

---

**bash** (2-4 chars)

This one most likely doesn't qualify, but I'll share it as curiosity.

Assuming the previous shell command in Bash was `$!`. The following command:

```
!$

```

will produce: `$!`.

# Answer
> 15 votes
# C++ 472 characters

A lot of characters but I cant think of a simpler way in a c-based language.

```
#include<iostream>
#include<string.h>
#define p(t) std::cout<<'}'<<';'<<')'<<strrev(&std::string(#t)[0])<<t;
char* strrev(char*p){char*t=p;char*q=p;while(q&&*q)++q;for(--q;p<q;++p,--q)*p=*p^*q,*q=*p^*q,*p=*p^*q;return t;}
int main(){p("(p{)(niam tni};t nruter;q*^p*=p*,q*^p*=q*,q*^p*=p*)q--,p++;q<p;q--(rof;q++)q*&&q(elihw;p=q*rahc;p=t*rahc{)p*rahc(verrts *rahc;t<<)]0[)t#(gnirts::dts&(verrts<<')'<<';'<<'}'<<tuoc::dts )t(p enifed#>h.gnirts<edulcni#>maertsoi<edulcni#");}

```

# Answer
> 12 votes
# Befunge 98 - 10 chars

```
"8k,'!1+,@

```

This works if your interpreter does not interpret wrapped lines after `"` as adding an extra space. If your interpreter does interpret wrapped lines like that, then this 11 char solution works (because duplicate spaces in a string literal are interpreted as one):

```
"9k,'!1+,@

```

---

If I can use `g` without penalty, then these also work (7 and 8 chars respectively):

```
"5k,g,@

```

and

```
"6k,g,@

```

# Answer
> 11 votes
## GolfScript, 12 chars

```
"-1%.`"-1%.`

```

This code takes the double-quoted string `"-1%.`"`, reverses it (`-1%`), duplicates it (`.`) and un-evals (```) the second copy, restoring the double quotes around it.

### Previous entry (13 chars):

```
{`'.~'+-1%}.~

```

Based on the 8-char quine `{'.~'}.~` from this answer; the extra 5 chars are needed to stringify and reverse the output.

Ps. Note that GolfScript automatically appends a newline to the end of the output. If this is counted as part of the output, a corresponding newline can be prepended to either version of the code without affecting the output, for a cost of one extra char.

# Answer
> 11 votes
# Fission, 6 bytes

A rare case of a generalised quine that is the same length as the normal quine:

```
"LO+!'

```

The idea is the same as that of the normal quine, but we're using a left-going atom (starting at the `L`) so that print mode traverses the code in the opposite order.

# Answer
> 10 votes
## Ruby, 60

```
puts(2,s=<<2.chop.reverse,s)
puts(2,s=<<2.chop.reverse,s)
2

```

Based on a classic Ruby quine.

# Answer
> 9 votes
## Perl, 41

```
$_=q{print~~reverse"\$_=q{$_};eval"};eval

```

Old 52 character answer (27+25 penalty)

```
open+0;print ~~ reverse <0>

```

Reads its own source, stores the reverse in a scalar, and prints that.

# Answer
> 8 votes
# J: 26

**Standard quining** *(26 chars)*: by defining a function and passing it its own definition, in quotes:

```
|.(,],2#{:)'|.(,],2#{:)'''

```

Could probably be made shorter.

**J-specific** *(33 chars)*: by defining a variable and asking what file the variable was defined in, i.e. this one, then printing out the contents of that file:

```
1!:2&2|.1!:1(4!:4 a=:<'a'){4!:3''

```

Must be saved & run from a script (i.e. not in the REPL, because then the answer to the question is "your argument wasn't defined in a file", so there's no file to read).

# Answer
> 8 votes
# Microscript, 11 bytes

I kind of had to do this.

```
0"Caxq"Caxq

```

Surprisingly, this is actually shorter than the language's shortest known true quine. `q` and `a` are otherwise equivalent, except `q` adds wrapping quotes while `a` does not.

# Answer
> 8 votes
# \>\<\>, 25 bytes

I was surprised to find this hadn't been done yet. :)

```
...yhsif sllems gnihtemoS

```

Paste code here and run it.

`.` is the Jump command, popping `x` and `y` off the stack, and moving the IP to `(x, y)` in the code box. In this case, the stack is empty, so the language's only error message is printed:

```
Something smells fishy...

```

# Answer
> 5 votes
## PHP, 41 characters (+25)

Don't know if I understood the assignment correctly. But here's a PHP try:

```
while(!isset($s) || $s) echo isset($s) ? array_pop($s) : ($s = str_split(file_get_contents(__FILE__)) and null);

```

**edit:** this can be much shorter:

```
echo strrev(file_get_contents(__FILE__));

```

But since it can be that simple, this is probably not what is being asked...

# Answer
> 5 votes
# JavaScript jQuery ~~119~~ ~~92~~ ~~74~~ 70 characters

```
alert($("#answer-16051 pre code").text().split("").reverse().join(""))

```

Now using jQuery, as minitech suggested in the comments, and manually wrapping with `<pre><code>` so I can use `text()` without fear of other code blocks in this post interfering. Manually wrapping with `<h4>` was incompatible with chromeium when I tested it, so now it should work in most browsers.

This program, if run from this page, finds the code block directly above, reverses its contents, and puts it in an alertbox.

Its easy enough to verify, just paste it into the dev console.

# Answer
> 5 votes
# UNIX shell, 31

Real solution at **52 characters:**

```
A='printf "A$ lave;\047`echo $A|rev`\047=A"';eval $A

```

But beware! Honesty doesn't pay off in today's world! Penalty is too low!!

**6 chars + 25 = 31:**

```
rev $0

```

# Answer
> 4 votes
## MATLAB, 78 characters:

```

|
.snoisserpxe ro stnemetats BALTAM ni dilav ton si retcarahc tupni ehT :rorrE

```

Note that the solution requires you to begin with a special character (alt+0160) and that it prints exactly the reversed message. (Unlike the python solution)

# Answer
> 4 votes
## MS-DOS, 24 bytes

```
eman elif ro dnammoc daB

```

Output:

```
Bad command or file name

```

# Answer
> 4 votes
# Windows 10 .EXE, 98 bytes

```
.rehsilbup erawtfos eht htiw kcehc ,CP ruoy htiw noisrev a dnif oT

.CP ruoy no nur t'nac ppa sihT

```

# Answer
> 3 votes
# JavaScript, 62

```
function f(){alert((f+'f()').split('').reverse().join(''))}f()

```

Works for me on latest Chrome (v 31.0.1650.63). Some other browsers may give a different output. (If you reverse that output, then it would work :P)

# Answer
> 3 votes
# SmileBASIC, ~~118~~ 102 bytes

```
FOR I=-101TO.?MID$(("+CHR$(34))*3,30,102)[-I];:NEXTFOR I=-100TO.?MID$(("+CHR$(34))*3,30,102)[-I];:NEXT

```

# Answer
> 3 votes
# Japt, 12 bytes

```
"iQ ²w"iQ ²w

```

Try it online!

Based off the standard Japt quine

### Explanation

```
"iQ ²w"      // Take this string.        iQ ²w
       iQ    // Insert a quote.          "iQ ²w
          ²  // Double.                  "iQ ²w"iQ ²w
           w // Reverse.                 w² Qi"w² Qi"
             // Implicitly output.

```

# Answer
> 3 votes
# Windows command prompt, 93 bytes

```
.elif hctab ro margorp elbarepo ,dnammoc lanretxe ro lanretni na sa dezingocer ton si 'file.'

```

# Answer
> 2 votes
## JavaScript, 56

```
($=_=>_!=$._?_?$(_.slice(1))+_[0]:')':$('($='+$+')('))()

```

# Answer
> 2 votes
## C, 148

```
char *a="};)43,b,43,a(ftnirp;]i-57[a=]i[b)++i;67<i;(rof{)(niam;i,]99[b,%c%s%c=a* rahc",b[99],i;main(){for(;i<76;i++)b[i]=a[75-i];printf(a,34,b,34);}

```

Just a fun play on a typical C quine.

# Answer
> 2 votes
# CSS, 88 bytes

```
<style>:before,*{display:block;unicode-bidi:bidi-override;direction:rtl;content:'<style>

```

Put in a blank html page to avoid conflict with other tags.

# Answer
> 2 votes
# JavaScript, ~~53~~ ~~50~~ ~~46~~ 43 bytes

~~```
q=_=>("q="+q+";q()").split("").reverse().join("");q()

```~~ ~~```
(q=_=>`(q=${q})()`.split("").reverse().join(""))()

```~~ ~~```
(q=_=>`(q=${q})()`.split``.reverse().join``)()

```~~
```
(q=_=>[...`(q=${q})()`].reverse().join``)()

```

Please help me shorten this up.

# Answer
> 2 votes
# Fuzzy Octo Guacamole, 4 bytes

```
KNU_

```

`K` prints `_UNK`, `N` pushes `None`, and `U` pushes `0`. And `_` pops the top value on the stack (but doesn't print). So only `_UNK` is printed.

# Answer
> 2 votes
# Brain-Flak, 3836 + 3 = 3839

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

```

Try it online

+3 bytes from the `-A` flag

This is a very simple variation on the standard Brain-Flak Quine. In fact this variant is obtained by *removing bytes* from the original Quine. Here is a picture of the original Quine with the removed characters in red:

The reason this variation is so simple is that the original Quine builds two parts of the program each on its own stack. One of the two parts is reversed so that when they are joined it becomes un-reversed.

So to make the reverse Quine we simply remove a stack swap.

We also have to remove the part of the program that encodes these two bytes otherwise they will be printed as well.

# Answer
> 2 votes
# C, 115 bytes

```
f(){char*s="f(){char*s=c%s%c%;printf(s+42,34,a,34);};)43,s,43,24+s(ftnirp;%c%s%c=s*rahc{)(f";printf(s+42,34,s,34);}

```

Haha, this is possible in C! Took me a few hours and nearly cheats, but it gets the job done.

# Answer
> 1 votes
## Perl, 49 characters

(Note: the actual program is three lines long, the third line being empty.)

```
print$/,~~reverse<<''x2
print$/,~~reverse<<''x2

```

Newlines can be a little unintuitive when text is reversed: the output starts with two blank lines. A naive user might expect the output to look more like this program, which is actually significantly shorter:

```
say~~reverse<< x2
say~~reverse<< x2

```

But only first listing is actually correct.

# Answer
> 1 votes
# Racket 178

```
(let((l(list->string(reverse(string->list"(let((l(list->string(reverse(string->lista~a~a~))))(q (integer->char 34)))(printf l q l q))"))))(q (integer->char 34)))(printf l q l q))

```

Output:

```
))q l q l ftnirp()))43 rahc>-regetni( q())))"))q l q l ftnirp()))43 rahc>-regetni( q())))~a~a~atsil>-gnirts(esrever(gnirts>-tsil(l((tel("tsil>-gnirts(esrever(gnirts>-tsil(l((tel(

```

Using the powerful `printf` makes it almost cheating (though I see people pulling their own sources for *only 25 penalty*.)

# Answer
> 1 votes
# beeswax,22 bytes

This is a variant of my beeswax quine (golf you a quine for great good!), also using beeswax’ ability to modify its own code.

```
J~@D@~1~M.8~3@.+~++~4*

```

GitHub repository to my beeswax interpreter written in Julia.

# Answer
> 1 votes
# \>\<\>, ~~10~~ 8 bytes

*2 bytes saved thanks to @JoKing by using `'` strings instead of `"` strings*

```
'd3*}>o<

```

Try it online!

### Explanation

```
'd3*}>o<               Push the code points of every character in the string 'd3*}>o<'
d3*                    Computes 39, the code point of ' (13*3)
                       Now the stack contains the quote on top of the stack
}                      Shift the stack to the right, so that the ' will be shifted to the bottom of the stack
                       This is required because the ' needs to be printed last
>o<                    Print everything in the stack until the stack is empty
                       And finally the program ends in an error

```

# Answer
> 1 votes
# Apple \]\[ BASIC, 12 bytes

```
RORRE XATNYS?

```

Hit the soft `RESET` key on the emulator to enter BASIC mode.

# Commodore 64 BASIC, 13 bytes

```
RORRE  XATNYS?

```

# Answer
> 1 votes
## CJam, 12 bytes

```
{"~_"\`W%}_~

```

Explanation:

```
{             e# Push this block literal:
 "~_"         e#   Push the string "~_"
     \        e#   Swap
      `       e#   Escape
       W%     e#   Reverse
         }    e# End
          _   e# Duplicate
           ~  e# Execute

```

# Answer
> 1 votes
## Wumpus, 11 bytes

```
"@o&l]=43#"

```

Try it online!

### Explanation

In Wumpus, the IP gets reflected off the boundaries of the grid, so without any further control flow redirection, a program on a single line will bounce back and forth through the code.

```
"@o&l]=43#"    Push the individual code points of this string to the stack.
               This gives us the entire code except the quotes.
               The IP then bounces off the end and starts moving back through
               the code. Since the " ended string mode, this time around the
               code will actually be executed.
#34            Push 34, the code point of double quotes.
=              Duplicate.
]              Shift one copy to the bottom of the stack.
l              Push the stack depth (i.e. the program length 11).
&o             Print that many characters.
@              Terminate the program.

```

# Answer
> 1 votes
# Python 2, 38 bytes

```

s="print's cexe;%r=s'%s[::-1]";exec s

```

Try it online!

# Answer
> 1 votes
# Jstx, 3 bytes

```
£↕o

```

Try it online!

# Answer
> 1 votes
# JavaScript, 42 bytes

```
(f=([a,...b]=`(f=${f})()`)=>a?f(b)+a:'')()

```

Try it online!

# Answer
> 1 votes
# Gol\>\<\>, 6 bytes

```
"2ss}H

```

Try it online!

Same as regular Gol\>\<\> quine, except that we just put the 34 at the bottom of the stack, instead of flipping the entire stack.

# Answer
> 1 votes
# Pepe, 7 bytes

```
!RORRER

```

Link to interpreter (paste the code above, link removes the `!` and `O`)

**Explanation:**

The interpreter ignores characters other than `R`,`r`,`E`,`e` so the code is:

```
RRRER

```

Now to put the code in explanation:

```
  RE  # Push 0
RR    # (RR flag: doesn't exist)
    R # R doesn't exist, so output RERROR!

```

# Answer
> 1 votes
# 05AB1E, 15 bytes

```
0"D34çýR"D34çýR

```

Try it online.

Or **17 bytes** if a default trailing newline isn't allowed:

```
0"D34çýR?"D34çýR?

```

Try it online.

Modification of the default `0"D34çý"D34çý` by adding `R`.

**Explanation:**

```
0                   # Push 0 to the stack
                    #  STACK: [0]
 "D34çýR"           # Push the string 'D34çýR' to the stack
                    #  STACK: [0, 'D34çýR']
          D         # Duplicate this string
                    #  STACK: [0, 'D34çýR', 'D34çýR']
           34ç      # Push '"' to the stack
                    #  STACK: [0, 'D34çýR', 'D34çýR', '"']
              ý     # Join the stack by this '"' delimiter
                    #  STACK: ['0"D34çýR"D34çýR']
               R    # Reverse the top value on the stack:
                    #  STACK ['Rýç43D"Rýç43D"0']
                    # (Output the top of the stack implicitly)

```

# Answer
> 1 votes
# Oracle SQL, 142 bytes

```
select
reverse(replace('@''[@'||chr(93)||'''))from dual;','@',q'[select
reverse(replace('@''[@'||chr(93)||'''))from dual;','@',q]'))from dual;

```

# Oracle SQL, 118 bytes

```
select
reverse(substr(rpad(1,144,'||chr(39)),27))from dual;select
reverse(substr(rpad(1,144,'||chr(39)),27))from dual;

```

Test in SQL Plus

```
SQL> set lines 80 pages 0
SQL> select
  2  reverse(replace('@''[@'||chr(93)||'''))from dual;','@',q'[select
  3  reverse(replace('@''[@'||chr(93)||'''))from dual;','@',q]'))from dual;
;laud morf))']q,'@',';laud morf))'''||)39(rhc||'@[''@'(ecalper(esrever
tceles['q,'@',';laud morf))'''||)39(rhc||'@[''@'(ecalper(esrever
tceles

SQL> select
  2  reverse(substr(rpad(1,144,'||chr(39)),27))from dual;select
  3  reverse(substr(rpad(1,144,'||chr(39)),27))from dual;
;laud morf))72,))93(rhc||',441,1(dapr(rtsbus(esrever
tceles;laud morf))72,))93(rhc||',441,1(dapr(rtsbus(esrever
tceles

```

# Answer
> 1 votes
# Gol\>\<\>, 6 bytes

```
sP#Hr"

```

This is just another way of doing a reverse quine, similar to Bubbler's answer

Try it online!

# Answer
> 1 votes
# JavaScript, ~~33~~ 32 bytes

```
f=([c,...s]='f='+f)=>c?f(s)+c:''

```

Recursively reverses the string by first providing the quine as the default argument. This beats the syntax error version, which isn't even consistent between browsers.

# Answer
> 1 votes
# MS SQL Server 2017, 173 bytes

```
declare @ char=1
select
reverse(substring(left(@+replicate('+char(39),3),201),28,174))
declare @ char=1
select
reverse(substring(left(@+replicate('+char(39),3),201),28,174))

```

**Output:**

```
))471,82,)102,)3,)93(rahc+'(etacilper+@(tfel(gnirtsbus(esrever
tceles
1=rahc @ eralced
))471,82,)102,)3,)93(rahc+'(etacilper+@(tfel(gnirtsbus(esrever
tceles
1=rahc @ eralced

```

Try it on db\<\>fiddle!

# Answer
> 1 votes
# Keg, 16 bytes (SBCS)

```
`÷^℠⅀:,.`÷^℠⅀:,.

```

Outputs:

```
.,:⅀℠^÷`.,:⅀℠^÷`

```

## Explained

```
`÷^℠⅀:,.`÷^℠⅀:,.

`÷^℠⅀:,.`           #Push the string '÷^℠⅀:,.'
÷^                  #Item split string and reverse stack
℠⅀                  #Summate it all into a string
:,.                 #Standard Keg quine procedure

```

Try it online!

# Answer
> 1 votes
# Vyxal `D`, 6 bytes

```
`IṘ`IṘ

```

Try it Online!

## Explained

```
`IṘ`IṘ
`IṘ`   # The string "IṘ"
    I  # appended to a backtick-surrounded version of itself
     Ṙ # Reversed

```

# Answer
> 0 votes
# PHP, 59

34 + 25 for reading own sourcecode.

```
<?=strrev(join(file((__FILE__))));

```

`**Online demo**`

# Answer
> 0 votes
# Ruby, 33+25=58

```
print File.read(__FILE__).reverse

```

# Answer
> 0 votes
## Lua, 31 Characters

```
'''' raen rorre xatnys :1:tupni

```

# Answer
> 0 votes
## Matlab, 111

```
function d=g();d='gvodujpo!e>h)*<e>(<e>gmjqms)\e)2;29*.2-e-e)29;foe*.2^*<';d=fliplr([d(1:18)-1,d,d(18:end)-1]);

```

# Answer
> 0 votes
# Bash, 8 + 25 for reading source = 33 bytes

```
rev "$0"

```

31 for no space in path to file

```
rev $0

```

# Answer
> 0 votes
# Help, WarDoq!, 2 bytes + 25 = 27

```
 q

```

The space is needed.

> * Minimum code length is two characters.

# Answer
> 0 votes
## Alice, 10 bytes

```
"9&o57*to@

```

Try it online!

### Explanation

```
"9&o57*to@"   Push code points of the entire program except the " to the stack.
9&            Execute the next command 9 times.
o             Print 9 characters from top to bottom (i.e. in reverse order).
57*           Compute 5*7 = 35.
t             Decrement to 34 (the code point of ").
o             Print the quote.
@             Terminate the program.

```

I'm not 100% sure whether this is optimal. 4 bytes to compute `34` seems painful and while I've found a whole bunch of 4-byte alternatives, I haven't found anything in 3 bytes yet. Some of those alternatives (some of these give other results, but they're 34 (mod 256)):

```
aN4Y
7aRY
5R1Y
4Pa+
7PYN

```

# Answer
> 0 votes
## CJam, 10 bytes

```
"W%_`"W%_`

```

Try it online!

Alternatively:

```
"`W%_"_W%`

```

### Explanation

```
"W%_`"   e# Push this string which contains the code after the string.
W%       e# Reverse the string.
_        e# Duplicate it.
`        e# Stringify the copy which wraps it in quotes. The unquoted and
         e# quoted versions are then implicitly printed to STDOUT back to back.

```

In the alternative solution, the string itself already contains the code in reverse and then we only reverse the copy (i.e. the string representation). It's kinda neat that it's then just one character off from being a palindrome.

# Answer
> 0 votes
# Java 8 (function), 144 bytes

```
v->{String s="v->{String s=%c%s%1$c;return new StringBuffer(s.format(s,34,s)).reverse();}";return new StringBuffer(s.format(s,34,s)).reverse();}

```

Try it online.

# Java 8 (full program), 240 bytes

```
interface M{static void main(String[]a){String s="interface M{static void main(String[]a){String s=%c%s%1$c;System.out.print(new StringBuffer(s.format(s,34,s)).reverse());}}";System.out.print(new StringBuffer(s.format(s,34,s)).reverse());}}

```

Try it online.

**Explanation:**

* The `String s` contains the unformatted source code.
* `%s` is used to input this String into itself with the `s.format(...)`.
* `%c`, `%1$c` and the `34` are used to format the double-quotes.
* `s.format(s,34,s)` puts it all together.

And then `new StringBuffer(...).reverse()` is used to reverse this source code.

# Answer
> 0 votes
# Haskell, 66 bytes

```
main=putStr$reverse$s++show s;s="main=putStr$reverse$s++show s;s="

```

Try it online!

# Answer
> 0 votes
# Tcl, 38 bytes

```
puts [string rev [read [open $argv0]]]

```

Try it online!

# Answer
> 0 votes
# J, 24 Bytes

```
(|.@,quote)'(|.@,quote)'

```

Evaluates to the string `')etouq,@.|(')etouq,@.|(`

Try it online! Uses `echo` in order to print result.

Alternatively, if a full program is required:

```
(echo@|.@,quote)'(echo@|.@,quote)'

```

Is 34 bytes and prints `')etouq,@.|@ohce(')etouq,@.|@ohce(`

### Explanation:

Both of these work in the same way:

```
(|.@,quote)'(|.@,quote)' | Expression to be evaluated
           '(|.@,quote)' | String literal containing the code
(         )              | Hook, (f g) y is evaluated as y f (g y)
     quote               | Wrap the string in quotes
    ,                    | Append to the unquoted version
 |.@                     | Reverse the whole thing

```

# Answer
> 0 votes
# Stax, 14 bytes

```
"r34b4l"r34b4l

```

Run and debug it

Yet another adaption of the `"34bL"34bL` quine.

# Answer
> 0 votes
# Jelly, 2 bytes

```
1-

```

Try it online!

Short but boring.

`1` gets ignored when `-` makes `-1` the argument which gets printed.

# Jelly, 8 bytes

```
“ṚṾȮ”ȮṾṚ

```

Try it online!

(More) interesting but long.

`“ṚṾȮ”` is a string literal for `ṚṾȮ`. `Ȯ` prints the string and returns it.  unevals the string, yielding the string `“ṚṾȮ”` (with the quote characters `“”` as part of the string).  reverses this string and its result, `”ȮṾṚ“` implicitly gets printed.

# Answer
> 0 votes
# Befunge-93 (FBBI), 13 bytes

```
">:#,_98+2*,@

```

Try it online!

Relies on nonstandard interpreter behavior. Works pretty much the same as this answer, except it's reversed.

# Answer
> 0 votes
# PowerShell Core, 36 bytes

```
&($f={&{-join"&(`$f={$f})"[35..0]}})

```

Try it online!

# Answer
> 0 votes
# Julia 1.0, 48 bytes

```
(a=:(print(reverse("(a=:($(a)))|>eval"))))|>eval

```

Try it online!

based on this quine

# Julia 1.0, 52 bytes

```
"]esrever∘wohs,tnirp[>|.".|>[print,show∘reverse]

```

Try it online!

based on this quine

---
Tags: code-golf, quine
---