title: Reverse stdin and place on stdout

text:
# Question
Title: Reverse stdin and place on stdout
**Requirements:**

* Take an input on stdin including new lines / carriage returns of unlimited length (only bounded by system memory; that is, there is no inherent limit in the program.)
* Output the reverse of the input on stdout.

**Example:**

Input:

```
Quick brown fox
He jumped over the lazy dog

```

Output:

```
god yzal eht revo depmuj eH
xof nworb kciuQ

```

Shortest wins.

Leaderboard:

```
var QUESTION_ID=242,OVERRIDE_USER=61563;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
```

```
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
```

```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>
```

# Answer
## Golfscript - 3 chars

```
-1%

```

obfuscated version is also 3 chars

```
0(%

```

here is an explanation of how  works
> 26 votes

# Answer
## Bash - 7

```
tac|rev

```

`tac` reverses line order, while `rev` reverses character order.
> 48 votes

# Answer
## BrainFuck, 10 characters

```
,[>,]<[.<]

```

Beats a good amount of answers for such a simple language.
> 36 votes

# Answer
## C, 37 bytes

```
main(_){write(read(0,&_,1)&&main());}

```
> 24 votes

# Answer
# Haskell - 21

```
main=interact reverse

```
> 22 votes

# Answer
# Pancake Stack, ~~342~~ 316 bytes

```
Put this nice pancake on top!
[]
Put this  pancake on top!
How about a hotcake?
If the pancake is tasty, go over to "".
Put this delightful pancake on top!
[#]
Eat the pancake on top!
Eat the pancake on top!
Show me a pancake!
Eat the pancake on top!
If the pancake is tasty, go over to "#".
Eat all of the pancakes!

```

It assumes that the input is terminated by a null character (`^@` on commandline). Example run, using the interpreter:

```
Put this nice pancake on top!
[]
Put this  pancake on top!
How about a hotcake?
If the pancake is tasty, go over to "".
Put this delightful pancake on top!
[#]
Eat the pancake on top!
Eat the pancake on top!
Show me a pancake!
Eat the pancake on top!
If the pancake is tasty, go over to "#".
Eat all of the pancakes!
~~~~~~~~~~~~~~~~~~~~~~~~
Hello, World!^@
!dlroW ,olleH

```
> 17 votes

# Answer
# Python, 41 40 bytes

```
import sys;print sys.stdin.read()[::-1]

```

41 -\> 40 - removed semicolon at end of program.

Probably could be optimised!
> 16 votes

# Answer
## APL, 2

```
⊖⍞

```

Or CircleBar QuoteQuad if the characters don't come through, simply meaning: reverse keyboard character input.
> 14 votes

# Answer
# C - 47 characters

```
main(c){if(c=getchar(),c>=0)main(),putchar(c);}

```

Note that this uses O(n) stack space. Try it online!
> 11 votes

# Answer
## Perl - 23

```
print scalar reverse <>

```
> 11 votes

# Answer
## Ruby - 19 characters

```
puts$<.read.reverse

```
> 10 votes

# Answer
# Binary Lambda Calculus - 9 bytes

```
16 46 80 17 3E F0 B7 B0 40

```

Source: http://ioccc.org/2012/tromp/hint.html
> 10 votes

# Answer
### Windows PowerShell, 53 ~~54~~

```
-join($x=[char[]]($($input)-join'
'))[($x.count)..0]

```

**2011-01-30** (54) – First attempt

**2011-01-30** (53) – Inline line breaks are fun.

**2011-01-3-** (52) – Inlined variable assignments too.
> 9 votes

# Answer
## Perl 5.1, 14

```
say~~reverse<>

```
> 9 votes

# Answer
## Befunge-93 - 11x2 (22 characters)

```
>~:0`v >:v
^    _$^,_@

```

Tested using this interpreter.
> 8 votes

# Answer
## \>\<\>, ~~16~~ 14 bytes

### -2 bytes by @JoKing

two years (!) later, removes the extra -1 from reading input by shifting around the logic for halting.

```
i:0(7$.
0=?;ol

```

Try it online!

Similar to the other \>\<\> answer, this doesn't need to reverse the stack because of the way input is read in the first line. I'm actually not too sure whether or not this should be a suggestion for the other \>\<\> answer, as it is quite different in appearance but similar in concept.

The main difference is that my answer compares the input to 0, and if it is less (i.e. there is no input -- `i` returns -1 if there is no input) it jumps to (1,7), if not, (0,7). If it jumps to the former, it pops the top value (-1) and starts a print loop. If it jumps to the latter, it continues the input loop.

# 11 bytes, exits with an error

### Courtesy of @JoKing

```
i:0(7$.
~o!

```

Try it online!

I believe this is valid now via meta consensus.

# Previous answer (14 bytes)

```
i:0(7$.
~ol0=?;!

```
> 7 votes

# Answer
# Fission, ~~16~~ ~~14~~ 12 bytes

```
DY$\
?
[Z~K!

```

## Explanation

Control flow starts at `D` with a down-going `(1,0)` atom. The `?` reads from STDIN, one character at a time, setting the mass to the read character code and the energy to `0`. Once we hit EOF, `?` will instead set the energy to `1`. The `[` redirects the atom onto a `Z` switch. As long as we're reading characters, the energy will be `0`, so the atom is deflected to the upwards by the `Z`. We clone the atom, looping one copy back into the `?` to keep reading input. We increment the other copy's energy to `1` with `$` and push it onto the stack `K`. So the input loop is this:

```
DY$\
?
[Z K

```

When the energy is `1` due to EOF, the `Z` will instead let the atom pass straight through and decrement the energy to `0` again. `~` decrements the energy further to `-1`. Atoms with negative energy *pop* from the stack, so we can retrieve the characters in opposite order and print them with `!`. Now note that the grid is toroidal, so the atom reappears on the left edge of the same row. Remember that we incremented the energy of the pushed atoms earlier with `$`, so the atoms now have energy `1` just like the last output from `?` and will again pass straight through the `Z`. The path after EOF is therefore

```
?
[Z~K!

```

This loop on the bottom row continues until the stack is empty. When that happens, the atom is reflected back from the `K` and its energy becomes positive (`+1`). The `~` decrements it once more (moving to the left), so that we now hit the `Z` with non-positive energy. This deflects the atom downward, such that it ends up in the wedge of `Y` where it's stored, and because there are no more moving atoms, the program terminates.
> 6 votes

# Answer
## Stack Cats, 7 bytes

```
<!]T[!>

```

Try it online!

There's a bunch of alternatives for the same byte count, most of which are essentially equivalent in how they work:

### Explanation

A short Stack Cats primer:

* Every program has to have mirror symmetry, and by mirroring any piece of code we obtain new code which computes the inverse function. Therefore the last three characters of the program above undo the first three, if it wasn't for the command in the centre.
* The memory model is an infinite tape of stacks, which hold an implicit, infinite amount of zeros at the bottom. The initial stack has a `-1` on top of those zeros and then the input bytes on top of that (with the first byte at the very top and the last byte above the `-1`).
* For output, we simply take the final stack, discard a `-1` at the bottom if there is one, and then print all the values as bytes to STDOUT.

Now for the actual program:

```
<    Move the tape head one stack left (onto an empty stack).
!    Bitwise NOT of the implicit zero on top, giving -1.
]    Move back to the original stack, taking the -1 with the tape head.
     We're now back to the original situation, except that we have a -1
     on top.
T    Reverse the stack down to the -1 at the bottom. One of the reasons
     we needed to move a -1 on top is that T only works when the top of
     the stack is nonzero. Since the first byte of the input could have
     been a null-byte we need the -1 to make sure this does anything at
     all.
[    Push the -1 to the stack on the left.
!    Bitwise NOT, turning it back into 0 (this is irrelevant).
>    Move the tape head back onto the original stack.

```

Sp3000 set his brute force search to find all other 7-byte solutions, so here are some alternatives:

```
<]!T![>
>![T]!<
>[!T!]<

```

These three variants are essentially the same, except that they differ in when the bitwise NOT is computed and whether we use the empty stack on the left or on the right.

```
<]T!T[>
>[T!T]<

```

Like I said in the explanation above, `T` doesn't do anything when the top of the stack is zero. That means we can actually put the `!` in the middle instead. That means the first `T` is a no-op, then we turn the zero on top into a `-1` and *then* then second `T` performs the reversal. Of course, this means that the final memory state has a `-1` on the stack next to the original one, but that doesn't matter since only the stack at the current tape head position affects the output.

```
<*ITI*>

```

This variant uses `*` (XOR 1) instead of `!`, so that it turns the zero into `+1`, and the `I` is a conditional push which pushes positive values and right, negative values left, and negates them in either case (such that we still end up with a `-1` on top of the original stack when we encounter `T`), so this ultimately works the same as the original `<!]T[!>` solution.
> 6 votes

# Answer
# PHP - ~~38~~ 17 characters

```
<?=strrev(`cat`);

```
> 5 votes

# Answer
# Fuzzy Octo Guacamole, 2 bytes

(non-competing, FOG is newer than the challenge)

```
^z

```

`^` gets input, `z` reverses, and implicit output.
> 5 votes

# Answer
# Hexagony, 16 bytes

```
\{\{:}($.,.=;)$\

```

Try it online!

Expanded: (Made with Hexagony Colorer)

Explanation:

* Blue path moves IP to the red path
* Red path moves "forward" in memory, reads a byte from STDIN, and increments it by 1, then checks if it's positive. The increment is so that the check will pass for all values including null bytes, and only fail for EOF (which Hexagony reads as negative 1)
* Orange path is reached when the check fails, it reverses memory and then puts the IP on the green path
* Green path goes back through the memory, attempting to divide 0 by each byte in memory. If the byte is empty, the end of the string has been reached, and the program crashes attempting to divide by zero. Otherwise it decrements the byte by 1 (to undo the increment from before) and prints it as a character.

Alternative 21 byte solutions that properly terminate instead of crashing:

`\{}\(//,;./')"<$|/$/@`

and

`},)<>'"<{\@..(_$.>.$;`
> 5 votes

# Answer
## PHP, ~~82~~ ~~29~~ ~~24~~ ~~29~~ 28 characters

```
<?=strrev(fread(STDIN,2e9));

```

82 -\> 29: The new line character is preserved when reversed with `strrev`.
29 -\> 24: Uses the shortcut syntax now
24 -\> 29: Now reads all lines instead of a single line
> 4 votes

# Answer
## Befunge-98 - ~~11~~ 10

```
#v~
:<,_@#

```

(Tested with cfunge)

The variant below breaks the requirement slightly: it performs the task but outputs an infinite stream of null bytes afterwards (and doesn't terminate).

```
~#,

```

The way it works is that it repeatedly reads input to the stack (`~`) one character at a time, jumping over (`#`) the comma. When EOF is reached, `~` acts as a reflector and the PC flips over, repeatedly popping and outputting a character (`,`) while jumping over (`#`) the tilde.
> 4 votes

# Answer
# Pyth - 3 ~~5~~ 4 bytes

So, the original 3-char version didn't reverse the line order, just the lines. I then came up with this 5-char version:

```
_jb.z

```

I saved 1 byte thanks to @FryAmTheEggman to result it:

```
_j.z

```

Live demo.

## Explanation:

```
  .w  read all the input into a list of strings
 j    join (j) by using a newline character
_     reverse the result
      Pyth implicitly prints the result on an expression

```

# Original (incorrect) solution:

This technically doesn't count because Pyth was created in 2014, but it's still neat that it's tied with GolfScript.

```
#_w

```

## Explanation:

```
#    loop while no errors
  w  read a line of input (throws an error on end-of-file or Control-C)
 _   reverse the input line
     Pyth implicitly prints the result on an expression

```
> 4 votes

# Answer
# Cubix, ~~9~~ 8 bytes

Many thanks to Martin Ender for this golf:

```
w;o@i.?\

```

**See it work online!**

This becomes the following cube (`>` indicates initial instruction pointer):

```
      w ;
      o @
> i . ? \ . . . .
  . . . . . . . .
      . .
      . .

```

The first step of the program is to take all input. `i` puts 1 byte of input onto the stack. Unless the input is finished, `?` makes the IP turn right, wrapping around the cube until it reaches `w`, which sends it back to `i`.

When input finishes, the `?` makes the IP head north, entering the output loop:

* `o`: print the character at the top of the stack
* `w`: 'sidestep' the pointer to the right
* `;`: pop the character that was just printed
* `\`: reflect the IP, sending it East
* `?`: if there are chars left to print, turn right, back into the loop.

The final time `?` is hit, when nothing is left on the stack, the IP continues forward instead:

* `i`: take a byte of input. This will be `-1` as input has finished.
* `\`: reflect the IP, sending it North, into:
* `@`: terminate the program.

---

# 9 byte solution

```
..o;i?@!/

```

**See it work online!**

In cube form:

```
      . .
      o ;
> i ? @ ! / . . .
  . . . . . . . .
      . .
      . .

```

The first character encoutered is `i`, which takes a charcode of input. If there is no input left, this is `-1`.

The next character is `?` \- a decision. If the top of stack is positive, it turns right, wrapping around the cube until it hits `/` which sends it back to the `i`, creating an input loop. However, if the TOS is negative, input has finished, and so it turns left into the output loop.

The output loop is simple. `o;` outputs and pops the TOS. The first time this is run, `-1` is the top of stack, but does not map to a character and is therefore ignored. `/` reflects the IP to move left, where it encounters `!@` \- which terminates the program if the stack is empty. Otherwise, the IP continues, hitting `?` again - because the stack is not empty, the TOS must be a charcode, all of which are positive1, so this makes the IP turn right and continue the output loop.

---

*1 Both solutions assume that the input will not contain null bytes.*
> 4 votes

# Answer
## Wumpus, ~~13~~ 11 bytes

```
)?\;l&o@
=i

```

Try it online!

### Explanation

Since Wumpus is a stack-based language, the basic idea is to read all STDIN to the stack and then just print the entire stack from top to bottom. The interesting part here is the control flow through the grid.

To understand the control flow, we need to look at the actual triangular grid layout:

The IP starts in the top left corner going east. We can see that there's a loop through the group of six cells on the left, and a branch off of the `\`. As you might expect, the loop reads all input, and the linear section at the end writes the result back to STDOUT.

Let's look at the loop first. It makes more sense to think of the first `)?\` as not being part of the loop, with the actual loop beginning at the `i`. So here's the initial bit:

```
)   Increment an implicit zero to get a 1.
?\  Pop the 1 (which is truthy) and execute the \, which reflects the IP
    to move southwest.

```

Then the loop starts:

```
i   Read one byte from STDIN and push it to the stack (or -1 at EOF).
    Note that Wumpus's grid doesn't wrap around, instead the IP reflects
    off the bottom edge.
=   Duplicate the byte we've read, so that we can use it for the condition
    later without losing it.
)   Increment. EOF becomes zero (falsy) and everything else positive (truthy).
?\  If the incremented value is non-zero, execute the \ again, which
    continues the loop. Otherwise (at EOF), the \ is skipped and the
    IP keeps moving east.

```

That leaves the linear section at the end:

```
;   Get rid of the -1 we read at EOF.
l   Push the stack depth, i.e. the number of bytes we've read.
&o  Print that many bytes.

```
> 4 votes

# Answer
## Wumpus, 12 bytes

```
i=)!4*0.l&o@

```

Try it online!

---

Martin's answer showcases Wumpus' triangular grid control flow well, but I thought I'd give this challenge a try with a one-liner.

The easier to understand version (one byte longer) is:

```
i=)!8*0.;l&o@

```

which works like so:

```
[Input loop]
i        Read a byte of input (gives -1 on EOF)
=)!      Duplicate, increment then logical not (i.e. push 1 if EOF, else 0)
8*       Multiply by 8 (= x)
0        Push 0 (= y)
.        Jump to (x, y), i.e. (8, 0) if EOF else (0, 0) to continue input loop

[Output]
;        Pop the extraneous -1 at the top from EOF
l&o      Output <length of stack> times
@        Terminate the program

```

Now let's take a look at the golfed version, which differs in the middle:

```
i=)!4*0.l&o@

```

The golfed version saves a byte by not needing an explicit command `;` to pop the extraneous -1. On EOF, this program jumps to `(4, 0)` instead of `(8, 0)` where it executes `4*0.` again — except this time the extraneous -1 is on top! This causes us to jump to `(-4, 0)`, which due to wrapping is the same as `(8, 0)` for this grid, getting us where we want whilst consuming the extraneous value at the same time.
> 4 votes

# Answer
# Wren, ~~40~~ 33 bytes

After I discovered a really clever trick...

```
Fn.new{|a|System.write(a[-1..0])}

```

Try it online!

## Wren, 53 bytes

Wren has no STDIN functions... I guess I will just be using a function instead of hard-coding the value and using a snippet (which is a bit risky).

```
Fn.new{|a|[-1..-a.count].each{|w|System.print(a[w])}}

```

TIO

## Explanation

```
Fn.new{                                               Create a new anonymous function (because Wren has no input functions)
       |a|                                            With the parameter a
          [-1..-a.count]                              Generate the range [-1,-2,...,len(a-1),len(a)]
                        .each                         Pass this range to the given function:
                             {|w|                     Take one parameter a
                                 System.print(a[w])}} And output it to STDOUT

```

## Wren, 54 bytes

```
Fn.new{|a|
for(i in-1..-a.count)System.write(a[i])
}

```

TIO
> 4 votes

# Answer
# Prolog (SWI), 31 bytes

```
a:-get0(C),C>0,a,put(C);!.
:-a.

```

Try it online!
> 4 votes

# Answer
## PHP - 44 characters

```
<?=strrev(file_get_contents('php://stdin'));

```
> 3 votes

# Answer
## Perl

```
print scalar reverse for reverse(<STDIN>);

```
> 3 votes

# Answer
# GameMaker Language, ~~90~~ ~~89~~ 82 Characters

No built-in reverse functions.

```
s=r=argument0;for(l=string_length(r);i<r;i++){c=string_char_at(s,l-i)o+=c}return o

```

Compile with all uninitialized variables as `0`
> 3 votes

# Answer
# Fission, ~~20~~ 15 bytes

```
KX$ \
!
SR?J%
~

```

The algorithm is very similar to Martin's, but the implementation differs significantly.

# How it works

Everything starts at `R`, which releases an eastward atom with mass 1 and energy 0.

Upon hitting `?`, an input character is saved as the atom's mass, and the energy is left at 0 unless stdin returns EOF, in which case energy becomes 1.

`J` is Fission's jump command, and jumps an atom forward a number of cells equivalent to its current energy, leaving the atom with 0 energy. For now, our atom has 0 energy and ignores this command.

We then strike `%`, which is a switch. With greater than 0 energy, our atom would be directed down (as if reflected by an `\` mirror), but since we have exactly 0 energy, we are sent upwards by the opposite mirror, `/`.

Our atom continues until it strikes a second mirror, `\` this time directing it left.

We increment the atom's energy to 1 with `$`, and use `X` to duplicate the atom. One copy will reflect back on to the `$` command (leaving that copy with 2 energy) and the other copy will be pushed on to the stack, `K`.

Our reflected copy travels backwards from whence it came until it hits the `%` switch again. Now that we have a positive energy, we reflect as if we had hit an `\` mirror, wrapping around the board onto the next `S` and decrementing our energy to 1.

The `S` command will consume 1 energy to preserve our direction. Had we no energy, the atom would have deflected as if struck by an `\` mirror, downward. Instead, we move to the right again and pick up more input with `?` and the cycle repeats.

Once our atom reaches EOF, the `?` command will store 1 energy in the atom. Thus, when we hit the `J` command this time, we completely skip over the `%` switch and land on the `S` switch with 0 energy.

Now, since our energy was consumed in the jump, our direction is *not* preserved by the `S` switch, but we are rather directed downward. We then decrement our energy to -1 with the `~` command and wrap around the board. When hit with a negative energy, the `K` command *pops* an atom instead of pushing one. We output our newly popped atom with `!`, and use the 1 energy of that atom to bypass the `S` switch, and the cycle completes.

If the stack `K` was empty, our atom's energy is negated (resulting in +1 energy) and it is reflected back onto the `~` command, leaving it with energy 0. Upon hitting `S` again, we are deflected to the right, until the `?` is struck. Since EOF has been reached, the `?` destroys the atom and terminates the program.
> 3 votes

# Answer
## 05AB1E, 1 byte

```
R

```

R reverses the input.
> 3 votes

# Answer
## awk, 24 bytes

Field separator set to `''` means that each char is in its own field and we can use `NF` as iterator from end to begining. To break record barriers, `RS` is also `''` meaning record ends at first empty record (`\n\n`).

```
{for(;NF-->0;)printf$NF}

```

Execution ends in an error as the `NF--` reaches `-1` and awk can't handle that. It could be handled with 2 more bytes to change the `for(;NF-->0;)` to `for(;NF>0;NF--)`. Test it:

```
$ awk -F '' -v RS='' '{for(;NF-->0;)printf$NF}' file
od yzal eht revo depmuj eH
xof nworb kciuQawk: cmd. line:1: (FILENAME=asd FNR=1) fatal: NF set to negative value

```
> 3 votes

# Answer
# Perl 6, 16 bytes

```
print slurp.flip

```

`slurp` reads the input as a single string, and `flip` reverses it.

`say` is more common for output, but that introduces an extra newline that wasn't in the input.
> 3 votes

# Answer
# Keg, 1 byte

```
?

```

Try it online!

Print reversed input implicitly
> 3 votes

# Answer
## Javascript (Node.js), 89 bytes

*-6 bytes thanks to bbrk24*

Finally a JS answer that actually uses stdin and stdout.

```
s='';process.stdin.on('data',d=>s+=d).on('end',_=>console.log([...s].reverse().join('')))

```
> 3 votes

# Answer
# Apple Shortcuts, 13 actions

Try It Yourself! Copy this link: https://www.icloud.com/shortcuts/86237c5b05454596945efb6b8fdc6cdc and paste into Safari. Only works on iPad and iPhone.

Sorry for large image, I don’t know how to resize it.

## Issues:

Because of Apple Shortcut’s limited ability to process strings, input is limited to integers only.

Because of some unknown issue, the length of your integer must be less than 16. This is not because of the loop. I originally set the loop to 200.

Pretty self explanatory, so I don’t feel like adding an explanation.
> 3 votes

# Answer
## Python - 35 chars

```
import os;print os.read(0,2e9)[::-1]

```
> 2 votes

# Answer
**C++ - 168 chars**

```
#include<algorithm>
#include<iostream>
#include<string>
using namespace std;main(){string m;for(string l;getline(cin,l);)m+=l+"\n";reverse(m.begin(),m.end());cout<<m;}

```
> 2 votes

# Answer
## Groovy 44 characters

```
args.reverse().each{print it.reverse()+" "}

```
> 2 votes

# Answer
# Scala - 60

```
print(io.Source.fromInputStream(System.in).mkString.reverse)

```
> 2 votes

# Answer
# Java, ~~165~~ 156 bytes

```
class R{public static void main(String[]a){System.out.print(new StringBuilder(new java.util.Scanner(System.in).nextLine().replace("\\n","\n")).reverse());}}

```

Requires you to escape any line breaks in the input, but otherwise it works.
> 2 votes

# Answer
# Labyrinth, 10 bytes

```
,)";@
:".(

```

Normally, Labyrinth programs are supposed to resemble mazes, but I was able to compress the loops in this one so tightly, that code ended up as a single block (room?). Here is a slightly expanded version which makes it easier to follow the control flow:

```
,""")""""""";""@
"   "   "   "
:""""   ."""(

```

`,` reads one byte at a time from STDIN until it hits EOF and returns `-1`. The `)` increments this value so that we get something positive for each read byte and zero at EOF. The `:` duplicates each read byte.

Once we hit EOF, the instruction pointer proceeds to the second loop, where it repeatedly discards one value with `;` (initially the EOF, later the second copy of each byte), then decrements the next value with `(` and prints it with `.`. Due to that second copy (which is always positive) we know that the IP will take a right-turn at the top and continue in this loop.

After all bytes have been printed the top of the stack is zero again and the IP continues straight ahead to the `@` and the program ends.

The seemingly unnecessary duplication of each byte is what allows me to ensure that (even in the tight loops of the golfed version) the IP always takes the correct turn and never crosses from one loop to the other.

A tip of the hat to TheNumberOne and Sp3000 whose own attempts helped a lot in finding this highly compressed solution.
> 2 votes

# Answer
## Minkolang 0.10, 6 bytes (non-competitive)

This language was created after this challenge, but not *for* this challenge.

```
$or$O.

```

`$o` reads in all of the input as characters, `r` reverses the stack, `$O` outputs the whole stack as characters, and `.` stops the program. Try it here.
> 2 votes

# Answer
# CJam, 19

```
1q]e_{_1#0=}{)\}w;;

```

This is the first golfing language I've tried to learn, and I just started learning it. It's pretty crazy, but it works in the online interpreter. \[Try it here\]\[1\].

Explanation (It's very hard for me to explain it, maybe someone can help):

```
1q]        #e  puts a 1 and the text input into an array
e_         #e  flatten the array
{_1#0=}    #e  check if if the 1 is at the beginning of our array. If true, we keep looping. The trick is once the array is destroyed, we are applying the # operator on 1 not the array, in which case it is a power operator, so it's (1)^(1), which is 1, not 0. Yeah it's ridiculous.
{)\}w      #e  in the body of the while loop we pop the last element off of the array and put it onto the stack.
;;         #e  then we need to get rid of the 1 so we pop the top element off the stack. I'm not sure why we need to do this twice.

```

\[1\]: http://cjam.aditsu.net/#code=1q%5De\_%7B\_1%230%3D%7D%7B)%5C%7Dw%3B%3B&input=High%0ABye%09Cool%0ATry
> 2 votes

# Answer
# AppleScript, 81 Bytes

Yeah. I'm amused by the "concision", too.

```
(display dialog""default answer"")'s text returned's characters's reverse as text
```

It grabs input from the user from STDIN equivalent (since it's not a terminal based language) and outputs the reverse. Simplez.
> 2 votes

# Answer
## Pyke, 1 byte (noncompetitive)

```
_

```

Try it here!
> 2 votes

# Answer
# MarioLANG, ~~35~~ ~~31~~ 27 bytes

```
,)<.-<
+=">="
>[!([!
==#==#

```

Try it online!

I'm not sure if a MarioLANG interpreter existed prior to this challenge, but the esolangs page has been around since 2009 with information describing the language.

There are 2 main loops here. The first one, consisting of the first 3 columns, loads all the characters into memory (incrememnted by 1 for properly handing eof) The second loop, consisting of the last 3 columns, prints the data on the tape from right to left (along with decrementing the values so they display properly). I did some clever trickery to have these loops directly next to each other.
> 2 votes

# Answer
# Excel VBA, 18 + 1 = 19 Bytes

Anonymous VBE function that takes input from range `[A1]` and outputs it reversed to the VBE immediate window

Code:

```
?StrReverse([A1])

```

+1 for `'` before input in cell `A1` (allows for handling strings that begin with '=')
> 2 votes

# Answer
# Brain-Flak, 15 bytes (non-competing)

```
{({}<>)<>}<>

```

Try it online!

12 bytes of code, and `+3` bytes for the `-c` flag, which enables input and output in ASCII.

Explanation:

```
#While the stack is not empty:
{

 #Push the top of the stack onto the alternate stack
 ({}<>)

 #Toggle back to the main stack
 <>

#endwhile
}

#Toggle to the alternate stack, implicitly display
<>

```
> 2 votes

# Answer
# Japt, 1 byte

```
w

```

Try it online!
> 2 votes

# Answer
# Commodore 64/VIC-20 BASIC, 48 BASIC bytes used

Here's a *one-liner* that will solve this issue:

```
0 INPUTA$:FORI=1TOLEN(A$):B$=MID$(A$,I,1)+B$:NEXT:PRINTA$":"B$

```

and here's how it looks on a Commodore 64 (more or less):

This will work on PETs and the C16/+4 series as well as the C128
> 2 votes

# Answer
# Whitespace, 67 bytes

This program requires a null byte to mark the end of input as Whitespace has no way to detect when stdin is empty. If you're using the TIO link make sure not to delete the last character in the input field (looks like a space) as it's a null byte. If you do you'll need to append a null byte using your browsers console.

```

```

Try it online!

## Explanation

(s - space, t - tab, n - newline)

```
sssn  ; push 0 to use as the starting heap address
nsstn ; label 'read-loop'
sns   ; dup
tnts  ; getchar and store at address n
sns   ; dup
ttt   ; retrieve the character value we just read
ntsn  ; jez 'output-loop' - if it was a null byte switch to output
ssstn ; push 1
tsss  ; add - increment n
nsntn ; jmp 'read-loop'
nssn  ; label 'output-loop'
ssstn ; push 1
tsst  ; sub - decrement n
sns   ; dup
ttt   ; retrieve the character value at address n
tnss  ; putchar - display the character
nsnn  ; jmp 'output-loop'

```

Whitespace uses a stack and a heap for data storage. As I/O commands write to the heap naturally we store the string on the heap and keep the stack for our counter.

This program reads characters one at a time and stores them in order starting from heap address 0 counting up. Once the program reads a null byte it starts displaying characters starting from the previous heap address counting down. For the input `hello\0` this populates the heap as `[#0:h,#1:e,#2:l,#3:l,#4:o,#5:\0]` then outputs the characters at addresses `#4,#3,#2,#1,#0` and we end up with `olleh`.
> 2 votes

# Answer
# Brachylog, 1 bytes

(maybe noncompeting?)

Try it online!
> 2 votes

# Answer
# Common Lisp, 67 bytes

```
(do((a))((push(or(read-char()())(return(coerce a'string)))a)))

```

Try it online!
> 2 votes

# Answer
# Julia 0.6, 33 bytes

```
print(reverse(readstring(STDIN)))

```

Try it online!
> 2 votes

# Answer
# , 41 bytes

```
cat(intToUtf8(rev(utf8ToInt(scan(,"")))))

```

Try it online!

Alternate "classic" version working directly with characters:

### , 53 bytes

```
for(i in rev(el(strsplit(scan(,""),split=""))))cat(i)

```

Try it online!

Because every question deserves at least one answer in R. Even string questions...
> 2 votes

# Answer
# Ruby, ~~17~~ 11 bytes

```
$_.reverse!

```

Try it online!

-6 bytes thanks to Jordan! (Needs a -p flag though.)
> 2 votes

# Answer
# Trilangle, ~~32~~ 31 bytes

```
'0.<_@<.>i,S)(_<\_//(,.oS(/#..>

```

I want to say it's possible to do better, but I'm honestly not sure how. Still shorter than Hello, World at least.

Try it on the online interpreter!

Unfolds to the following grid:

```
       '
      0 .
     < _ @
    < . > i
   , S ) ( _
  < \ _ / / (
 , . o S ( / #
. . > . . . . .

```

*How dense can control flow get before my diagrams are illegible?*

The red & green paths push the contents of stdin to the stack, keeping track of the number of characters pushed. The blue path contains the most convoluted "add" instruction ever, and then a decrement-swap-print-pop loop. The yellow path completes the loop while there's still more to be printed, and then the magenta path terminates the program.

Starting on the red path:

* `'0`: push a 0 to the stack, representing the number of characters read so far.
* `<`: redirect control flow
* `i`: get a character from stdin
* `>`: branch

If EOF was read, it continues on the blue path; otherwise, it continues on the green path.

The green path increments the counter and closes the loop:

* `_`: redirect control flow
* `.`: no-op
* `S`: swap the two values on top of the stack, so that the counter is on top
* `\`: redirect control flow
* `_`: no-op when traversed horizontally
* `/`: redirect control flow
* `)`: increment the top of the stack
* `.`: no-op again
* `<`: redirect control flow, merging with the red path

On the blue path, the top of the stack is now -1 (representing EOF). The loop later in the program works best if the counter starts one too low -- the branch instruction is "branch if negative", not "branch if zero", so the counter needs to be negative once the output is finished. So, the following instruction sequence is used to transform `{ ..., n, -1 }` to `{ ..., n - 1 }`:

* `)`: increment the top of the stack: `{ ..., n, 0 }`
* `_`: redirect control flow
* `S`: swap the two values on top of the stack: `{ ..., 0, n }`
* `<`: redirect control flow
* `_`: no-op when traversed horizontally
* `(`: decrement the top of the stack: `{ ..., 0, n - 1 }`
* `)`: increment the top of the stack: `{ ..., 0, n }`
* `S`: swap the two values on top of the stack: `{ ..., n, 0 }`
* `,`: pop the value off the top of the stack: `{ ..., n }`
* `(`: decrement the top of the stack: `{ ..., n - 1 }`
* `//`: redirect control flow

At this point, it begins to print back out what it's stored (still on the blue path):

* `(`: decrement the top of the stack
* `S`: swap the two values on top of the stack
* `o`: print the character on top of the stack
* `.`: another no-op
* `,`: pop the value of the top of the stack
* `.....`: more no-ops
* `>`: branch

If there are more values to print, the IP takes the yellow path, jumping back into the dec-swap-print-pop loop. Once there are no more values to print, the IP takes the magenta path, performing a lot of useless operations before eventually reaching the `@` to end the program.
> 2 votes

# Answer
## C# - 116

```
using System.Linq;using c=System.Console;class p{static void Main(){c.Write(c.In.ReadToEnd().Reverse().ToArray());}}

```
> 1 votes

# Answer
## VB.Net - 96

```
Module M
Sub Main()
Console.Write(CStr(ConsoleIn.ReadToEnd.Reverse.ToArray))
End Sub
End Module

```

**90 (With Turned off Option Strict)**

```
Module M
Sub Main()
Console.Write(Console.In.ReadToEnd.Reverse.ToArray)
End Sub
End Module

```
> 1 votes

# Answer
# JavaScript - 44

I don't think you can get much shorter with JS. Nothing interesting here.

```
alert(prompt().split('').reverse().join(''))

```
> 1 votes

# Answer
# JavaScript - ~~50~~ ~~48~~ 47

Slightly longer than the other JS entry

```
a='';for(i=(b=prompt()).length;i;a+=b[i---1]);a

```
> 1 votes

# Answer
# Retina 0.8.2, 24 bytes

Contains the unprintable DEL `0xFF` character (delete) to use as a delimiter. These are located at the end of lines 2, 3, and 5, as well as between `$1` and `$2` on line 4.

```
$

+s`(.)(.*)
$2$1

```

**Try it online!**
> 1 votes

# Answer
# \>\<\>, 17 bytes

```
!vi:1+?
 ~
l<o;!?

```

I don't even need to reverse the input as putting it on a stack naturally does that.
> 1 votes

# Answer
# TI-BASIC, 43 (+ 7 = 50, for `Input` statement)

If you count `:` as TI's ‘newline’...

Programs show similarity to this, and are thus attributed to the site (too lazy to be involved in copyright infringement, etc.).

## V2 (with input ‘STDIN’, 50)

```
PROGRAM:R
Input Str1
Str1
For(I,1,length(Ans)-1
sub(Ans,2I,1)+Ans
End
sub(Ans,1,I

```

## V2 (no input, 43)

Called as `"string":prgmR`.

```
PROGRAM:R
For(I,1,length(Ans)-1
sub(Ans,2I,1)+Ans
End
sub(Ans,1,I

```
> 1 votes

# Answer
# Javascript (ES6), 37

Really simple. Try below in Firefox.

```
alert([...prompt()].reverse().join``)
```

---

# , 4 chars / 8 bytes (noncompetitive)

```
ôᴙï)

```

`Try it here (Firefox only).`
> 1 votes

# Answer
## Retina, 6 bytes

Non-competing, since Retina is newer than this challenge.

```
O$^s`.

```

Try it online!

With Retina's latest addition (sort stages), this became a lot shorter. Sort stages work by matching a bunch of things via the supplied regex, and then sorting those matches treating everything that wasn't matched like list-delimiters. This stage type comes with a bunch of options that we can (ab)use to reverse a string.

For a start, the regex is simply `.`, which matches a single character, and the `s` modifier ensures that it can also match linefeeds. That is, we're sorting all the characters in the input. As for the others:

* `O` just activates sorting.
* `$` tells Retina that the matches shouldn't be sorted by their actual string value, but that a regex substitution is first applied to them, and they are then sorted by the result of that substitution. Now the program has only a single line (the substitution would go on the second line), so that all matches are just replaced with an empty string. That means, to the sorting function, all matches are equal, and no sorting happens at all.
* Finally, `^` tells Retina to reverse the order of the matches after sorting.
> 1 votes

# Answer
# Tellurium, 5 bytes

```
i&r.^

```
* The `i` command gets input and stores it in the selected cell.
* `&` starts string manipulation mode.
* `r` is a string mode command. It reverses whatever is stored in the selected cell.
* `.` exits string mode.
* `^` outputs the cell's value.
> 1 votes

# Answer
# Java, 103 bytes

Full programs in Java suck.

```
class A{public static void main(String args[]){System.out.print(new StringBuffer(args[0]).reverse());}}

```
> 1 votes

# Answer
# SmileBASIC, ~~36~~ 32 bytes

```
INPUT S$WHILE""<S$?POP(S$);
WEND

```

Bonus: add `ATTR 2` between `S$` and `WHILE` to display the inputted text rotated 180 degrees.
> 1 votes

# Answer
# ZX81 BASIC 74 Bytes 71 Bytes (listing)

```
 1 LET B$=""
 2 INPUT A$
 3 FOR I=1 TO LEN A$
 4 LET B$=A$(I)+B$
 5 NEXT I
 6 PRINT A$;":";B$

```

You enter a string, which is stored in the variable `A$`; each character in `A$` is transferred to the empty string `B$`, but is copied to `B$` in reverse order (thanks to `Dr Beep` for the top tip).

Output is as follows:

Actual bytes can be saved by using more typing - this takes up less room in the ZX81 RAM but is longer:

Note that this listing is the original entry; Using the function `VAL` or dividing `PI` into `PI` is a byte-saving tip, i.e., `FOR I=PI/PI TO LEN A$`

So to do code golf properly on a ZX81, you need longer listings as a rule of thumb.
> 1 votes

# Answer
## Alice, 7 bytes

```
\oi
/R@

```

Try it online!

### Explanation

```
\    Reflect to SE. Switch to Ordinal.
R    Reverse top string on stack, does nothing.
     Reflect off bottom boundary --> move NE.
i    Read all input as a single string.
     Reflect off corner --> move back SW.
R    Reverse top string on stack, reverses input.
     Reflect off bottom boundary --> move NW.
\    Reflect to S. Switch to Cardinal.
/    Reflect to NE. Switch to Ordinal.
o    Print reversed output.
     Reflect off top boundary --> move SE.
@    Terminate the program.

```
> 1 votes

# Answer
## MarioLANG, ~~136~~ 91 bytes

```
>,----------[!(>[.[([!
"============#="=====#
!) ++++++++++< !     <
#============" #====="

```

Reverses a string ending in a newline (\n)

Example:

```
Hello World!

```

becomes

```
!dlroW olleH

```

NOTE: Only works on linux or mac. Doesn't work in TIO either.
> 1 votes

# Answer
# Braingolf, 4 bytes

```
&,&@

```

Try it online!

Another reverse builtin
> 1 votes

# Answer
# Aceto, 3 bytes

```
r~p

```

```
r reads input
~ reverses it
p prints it

```

Try it online!
> 1 votes

# Answer
# Momema, 39 bytes

```
z00+1*0*0*-9z=+1**0y00+-1*0-9**0y=+-1*0

```

Try it online!

## Explanation

```
                                                           #  i = 0
z    0       #  label z0: jump past label z0 (no-op)       #  do {
0    +1*0    #            [0] = [0] + 1                    #    i += 1
*0   *-9     #            [[0]] = read chr                 #    tape[i] = read chr
z    =+1**0  #  label z1: jump past label z(!([[0]] + 1))  #  } while (tape[i] != -1)
y    0       #  label y0: jump past label y0 (no-op)       #  do {
0    +-1*0   #            [0] = [0] - 1                    #    i -= 1
-9   **0     #            print chr [[0]]                  #    print chr tape[i]
y    =+-1*0  #  label y1: jump past label y(!([0] - 1))    #  } while (i != 1)

```
> 1 votes

# Answer
# Attache, 22 bytes

```
Stdout!Reverse!Stdin[]

```

Try it online!

`!` calls a function using its right argument. This is equivalent to:

```
Stdout[Reverse[Stdin[]]]

```

I couldn't find a more clever solution for reversing or outputting, unfortunately.
> 1 votes

# Answer
# Shakespeare Programming Language, 213 185 bytes (153 bytes with error)

Thanks to Jo King for saving 28 bytes!

Try it online!

213-byte old version

(Whitespace added for readability only)

```
R.Ajax,.Puck,.Act I:.Scene I:.[Exeunt][Enter Ajax and Puck]
Ajax:Remember you.Open mind.Be you nicer I?
If solet usAct I.
Recall.Be you nicer I?
If sospeak thy.If sorecall.
If solet usAct I.

```

153-byte version that terminates in an error (Try it online!)

```
R.Ajax,.Puck,.Act I:.Scene I:.[Exeunt][Enter Ajax and Puck]
Ajax:Open mind.Be you nicer I?If soremember you.
If solet usAct I.
Recall.
Speak thy.
Let usAct I.

```

### Explanation

Scene I is a reused loop. I use Jo King's own method to reuse Scene I, since jumping to Act I is shorter than jumping to Scene I. This is why I begin the scene with `[Exeunt]`. Then, Ajax tells Puck to push himself, so he pushes a 0 (all characters are initialized to 0). Now, Puck takes input (`Open mind`) and compares himself to Ajax, who remains at 0. If Puck's value is greater than 0, the scene loops. Thus, Puck pushes a 0 followed by the string, and then moves on to the next part when he encounters the terminating -1. In the second part, Puck pops a value and compares it to 0. If it is greater than 0, he prints it and pops a second value. He then returns to the beginning of the program. There, he pushes the value he just popped. He takes input, which will now be constantly -1, so he falls through back to the second half. This completes the loop.

In the error-terminating version, no 0 is initially pushed to mark the beginning of the string (end of the reversed string), so some things are re-ordered, and the checks for it are removed. The program eventually throws an error that Puck cannot recall anything.
> 1 votes

# Answer
# Poetic, 60 bytes

```
normally i create a reversal
so could i?i suppose maybe i do

```

Try it online!

This is actually slightly modified from an example on my website. The only things changed are that the letters are now stored right to left instead of left to right, the 11 letter word is replaced with two 1-letter words, and there is no 0 command at the end (which results in an error, but that's okay).
> 1 votes

# Answer
# 1+ (EOF returns 0), 17 bytes

```
1##,"1<1+#+(|;())

```

Try it online!

The TIO link uses integer I/O and a so-called input template (I'm going to use it for all my 1+ answers from now on) because 1. The interpreter reads input and source code from the same place for some reason and 2. It does not support EOF so I have to simulate it by manually putting the EOF in the input and 3. The NUL character cannot be placed in the input so I have to use integers.

## Explanation

This supports all printable ASCII (and LF and CR), and the question didn't say anything about other unprintable characters so I guess that is okay.

The first part of the program, `1##,"1<1+#+`, reads the input to the stack. Here we save 2 bytes by comparing `n <= 1` (`1<`) and not `n <= 0` (which is `1+1<`) since in 1+, 1 is the only literal, which indicates pushing a 0 is longer.

After the loop, we have the input and a trailing EOF (0) on the stack. We get rid of the EOF by adding the top two numbers (this doesn't work for empty input, but again, the question didn't say anything about it!) and since `a + 0 = a` it will not affect the rest of the input.

The second part, `(|;())`, is a simple recursive function that (pop and) outputs top of stack and it terminates with error when there are no more elements to output. I used recursion because loop is longer.

## Supports all ASCII characters except NUL, 19 bytes

```
1##,"1+1<1+#+(|;())

```
> 1 votes

# Answer
# Flurry, 52 bytes

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

```

### Run example

```
$ printf "Quick brown fox\nHe jumped over the lazy dog" | ./flurry -bnb -c \
  "[]{<>[(<<>()>)<>[<>{}{}]][<()()>{}]}[<>()][(){()}]{}"
god yzal eht revo depmuj eH
xof nworb kciuQ

```

Being a stack based language with stack content I/O, the task is essentially to reverse the entire stack. But due to how Flurry is designed, I had no choice but construct an encoding of a list containing all the stack contents, and then fold through the list to push the content one by one, in reverse order.

I decided to use the Church right-fold encoding and its variations: (in all cases, the bottom of the stack appears as the head of the list)

* Regular right fold

```
-- right fold; (1:2:3:4:nil) f n = f 1 (f 2 (f 3 (f 4 n)))
nil = \cn. n = SK
cons = \htcn. ch(tcn)
= \htc.S(K(ch))(tc)
= \ht.S(\c. S(K(ch))) t
= \h. S(\c. S(K(ch)))
= \h. S(\c.<SK>(ch))
= \h. S(S(K<SK>)(SI(Kh)))
= <S(S(K<SK>))(SI)K>
= <S(<SK><SK>)(SI)K>
= <<>[(<<>()>){}][<>{{}}]()>
listify = height (\t. S cons (K t) pop) nil
= []{<><<>[(<<>()>){}][<>{{}}]()>[(){}]{}}[<>()]

```
* Right fold, but with flipped args

```
-- right fold with flipped args; (1:2:3:4:nil) f n = f (f (f (f n 4) 3) 2) 1
cons' = \htcn. c(tcn)h
= \htc. S (\n. c(tcn)) (Kh)
= \htc. S (S(Kc)(tc)) (Kh)
= \ht. S (\c. S (S(Kc)(tc))) (K(Kh))
= \ht. S (S(KS)(\c. S(Kc)(tc))) (<KK>h)
= \ht. S (S(KS)(\c. <SK>c(tc))) (<KK>h)
= \ht. S (S(KS)(S<SK>t)) (<KK>h)
= \ht. S(<SK>S(S<SK>t)) (<KK>h)
= {{<>[(<<>()>)<>[<>{}{}]][<()()>{}]}}
listify
= []{<>[(<<>()>)<>[<>{}{}]][<()()>{}]}[<>()]

```
* Left fold

```
-- left fold; (1:2:3:4:nil) f n = f (f (f (f n 1) 2) 3) 4
cons = \htcn. t c (c n h)
= \htc. S (K (tc)) (\n. cnh)
= \htc. S (K (tc)) (S c (K h))
= \ht. S <SKt> (S S (K (K h)))
= {{<><<>(){}>[<[<><>]()()>{}]}}
listify = height {cons (t=arg; h=pop)} nil
= []{<><<>(){}>[<[<><>]()()>{}]}[<>()]

```

Out of the three, only right folds are feasible for stack reversal because the 4 must be handled (i.e. pushed to the stack) first. Then, the strict evaluation of Flurry makes the "flipped args" version easier to use for the task, because partial evaluation such as `f 1` part of `f 1 (f 2 (...))` may trigger the unwanted side effect to the stack.

So far, we got the function that transforms the stack into a fold function, which looks like `\fn. f (f (f (f n 4) 3) 2) 1`. Now is the time to decide what `f` (binary function) and `n` (starting value) should be.

`f` should basically ignore the first argument and push the second argument. Return value is irrelevant. So we can simply do this:

```
f = \xy. push y
= K (\y. push y)
= (){({})}

```

But `{...}` already implicitly pushes its argument, so we can just use a dummy result that is ignored every step:

```
f = (){()}

```

`n` can be anything too, so we use a dummy 2-byte token `{}`.

The full program is:

```
main = listify_stack_foldr_flip f n

```
> 1 votes

# Answer
# Stupidity, 5 Bytes

```
I R _

```

Here is how it works:

* `I` gets an input string from STDIN.
* `R` reverses the string.
* `_` prints the string from STDOUT.

I will be posting the link to the language soon.
> 1 votes

# Answer
# 05AB1E, ~~3~~ 1 byte

```
R

```

Try it online! Takes input surrounded in `"""triple double quotes"""`.

```
R  # full program
R  # reverse...
   # implicit input
   # implicit output

```
> 1 votes

# Answer
# Husk, 1 byte

*(not strictly valid, since Husk cannot read directly from STDIN; instead (from the Husk wiki) "In Husk, inputs are taken as command line arguments to the interpreter".*

Try it online!

Sometimes the language-designers really seem to hit the nail on the head with the choice of characters to represent the function they encode:

= reverse the argument
> 1 votes

# Answer
# V (vim), 14 bytes

```
:g/^/m0
:%!rev

```

Try it online!

reverses the entire buffer by reversing each line, and then reversing the order.

The first line comes from here.

`:%!rev` applies bash's `rev` command to each line.
> 1 votes

# Answer
# .mmo (MMIX executable), 96 bytes (24 tetras)

```
00000000: 98090100 98010001 00000100 e0002000  Ƭµ¢¡Ƭ¢¡¢¡¡¢¡ṭ¡ ¡
00000010: b5010008 2301000f 23010101 c1ff0000  Ọ¢¡®#¢¡Đ#¢¢¢Ḋ”¡¡
00000020: af010000 00000300 59fffffc c1ff0000  Ḥ¢¡¡¡¡¤¡Y””‘Ḋ”¡¡
00000030: 00000601 27010101 af010000 26ff0100  ¡¡©¢'¢¢¢Ḥ¢¡¡&”¢¡
00000040: 27ffff0f 5bfffffa 980a00ff 00000000  '””Đ[””«Ƭ½¡”¡¡¡¡
00000050: 00000100 980b0000 00000000 980c0001  ¡¡¢¡Ƭ¿¡¡¡¡¡¡Ƭ€¡¢

```

```
98090100 lop_pre 1,0                (mmo v1, 0 tetras)
98010001 lop_loc 0,1                (start loading at next tetra)
00000100 256                        (which is 256)
E0002000    SETH $0,#2000           (set $0 to address of data segment)
B5010008    STCO 1,$0,8             (we will read in one byte at a time)
2301000F    ADDU $1,$0,15           ($1 points to byte before buffer)
23010101 0H ADDU $1,$1,1            (inloop: increment $1)
C1FF0000    SET  $255,$0            (set $255 to handle)
AF010000    STOU $1,$0              (store address of byte to handle)
00000300    TRAP 0,Fread,StdIn      (read in that byte)
59FFFFFC    PBNN $255,0B            (if not EOF, jump back to inloop)
C1FF0000 0H SET  $255,$0            (set $255 to handle)
00000601    TRAP 0,Fwrite,StdOut    (write out the byte pointed to)
27010101    SUBU $1,$1,$1           (decrement the pointer)
AF010000    STOU $1,$0              (and store it again)
26FF0100    SUBU $255,$1,$0
27FFFF0F    SUBU $255,$255,15       (find how many bytes left to write)
5BFFFFFA    PBNZ $255,0B            (if any, jump back)
            TRAP 0,Halt,0           (implicit, due to being all zero)
980A00FF lop_post 255               (postamble, rG=255)
00000000
00000100                            (start at location 256)
980B0000 lop_stab                   (begin symbol table)
00000000                            (no tetras)
980C0001 lop_end 1                  (symbol table is one tetra long)

```
> 1 votes

# Answer
# !@#$%^&\*()\_+, 11 bytes

```
^*( *)+(*@)

```

Try it online!

Loses to BF :( Space represents a `\x01`.

EOF in !@#$%^&\*()\_+ is -1, so this adds 1 to each character and put them to the stack until a zero is pushed (`^*( *)`). Then it removes the zero by adding it to another number (`+`), and output the stack, decrementing each element (`(*@)`).

This uses `*` the input command nicely:

* It *adds* the input *with* the stack top, so to add 1 to the input, push 1 and then input saves one byte.
* EOF is -1, so after you finished reading the input, `*` can be used for decrement which would otherwise be expensive (`_^_`).
> 1 votes

# Answer
# Fig, \\$1\log\_{256}(96)\approx\\$ 0.823 bytes

```
$

```

Try it online!

You thought 1 byte builtins were short? Enter Fig.
> 1 votes

# Answer
# Knight (v2.0-alpha), 37 bytes

```
;=s=t@;W=gP=s+s+g"
";Ws;=t+[s t=s]sOt

```

Try it online!

Nothing super exciting, except for the fact that we can use `@` instead of `""` for the initial value of `s` and `t`.
> 1 votes

# Answer
# Vyxal, 1 byte

Try it Online!
> 1 votes

# Answer
# Thunno `W`, 1 byte

(actually \\$ 1 \log\_{256}(96) \approx \\$ 0.82 bytes, but that doesn't show up on the leaderboard)

```
r

```

Attempt This Online!

Also works in Thunno 2: Attempt This Online!

```
   # Implicit input.
   # The W flag reads the whole of STDIN as a multi-line string,
   # rather than taking each line separately.
r  # Reverse the string on the top of the stack.
   # Implicit output.

```
> 1 votes

# Answer
# ForWhile, ~~24 22 19 16~~ 14 bytes

Saved 2 bytes due to new language feature of looping without pushing loop counter (`[…)` instead of `(…)`)

```
9:`['1+_:~).[#)

```

Try it at the online interpreter!

This took me so long to figure out!! But I made it there in the end. I don't think the program can get shorter than this (but you never know…)

Thanks bsoelch for the tip to get large numbers.

Explanation:

```
9:`  \ 9 ^ 9
[    \ repeat (9 ^ 9) times:
  '  \   swap two items on the stack
  1+ \   add one (to string length)
  _  \   read a byte from STDIN
  :~ \   duplicate, bit flip; -1 (EOF) becomes 0
)    \ pop top of stack; if nonzero (not EOF) jump back to [
.    \ pop final -1
[    \ repeat (string length) times:
  #  \   print byte without popping
)    \ pop top of stack; if nonzero, jump back to [

```

---

## ForWhile, 70 bytes

This one works for input of infinite size; ForWhile doesn't really support infinite loops, but you can do source-modification to make it work. Thanks bsoelch for writing this one.

```
""(,#)6~$~7~$(!;$1-:){}9+:57(.:@;57-$1-:).7~@_:~![..7~@34;$?];$1+7~$57

```

Try it at the online interpreter!

---

For the record: for ForWhile, reversing the string is the easy part of this challenge. The hard part is reading all of STDIN as a string. If the string could be passed as an argument to a procedure, this could be 5 bytes:

```
{[#)}

```

Try it at the online interpreter!
> 1 votes

# Answer
# Python 2, 39 bytes

```
import sys;print sys.stdin.read()[::-1]

```
> 0 votes

# Answer
## Matlab (56)

```
a=1;b=0;while(a)a=input('','s');b=[flipud(a) 10 b];end,b

```

## Execution:

```
abc
def

b =

fed
cba

```
> 0 votes

# Answer
# Hassium, 62 Bytes

```
func main(){s=input();for(x=s.length- 1;x>=0;print(s[x--]))0;}

```

Run and see expanded here
> 0 votes

# Answer
## Seriously, 2 bytes (non-competitive)

```
R

```

There is a formfeed character (ASCII `0x0C`) as the first byte. Hexdump (reversible with `xxd -r`):

```
00000000: 0c52                                     .R

```

Try it online! (note that the formfeed shows up as the dingbat  on TIO - one of the nice features Dennis has added is the parsing of CP437 dingbats into ASCII control codes).
> 0 votes

# Answer
# Hexagony, 28 bytes (Non-competitive)

Compressed:

```
.$@.>;<..\'"/$\$/}{,<..>.../

```

Try it Online!
> 0 votes

# Answer
# Sesos, 3 bytes (non-competing)

```
x

```

Since this contains unprintables, here is a hexdump:

```
0000000: 788c19                                            x..

```

This is the code that was used to generate it:

```
fwd 1,jnz,rwd 1,jmp,put,rwd 1

```

Try it online!

This works, provided the input does not contain null characters (`\0`).
UTF-8 locale as far as I'm aware.

Explanation:

```
      ;(implicit nop) Start the input loop.
fwd 1 ;Store the input character for subsequent use.
jnz   ;(implicit jne) Store an input character. If EOF is reached, terminate input.
rwd 1 ;Let the output loop start.
jmp   ;Start the output loop.
put   ;Output a character.
rwd 1 ;Go to the next character.
      ;(implicit jnz) If the character is null (terminator), exit.

```
> 0 votes

# Answer
# tcl, 30

```
puts [string rev [read stdin]]

```

To terminate input press Ctrl+D.

Available to run on: https://goo.gl/18Sqz0
> 0 votes

# Answer
# Jelly, 6 bytes

```
⁸ƈ;$ÐL

```

Try it online!
> 0 votes

# Answer
# Triangular, 21 bytes

```
\.~/.?.`.<....p.]p@(<

```

Try it online!

This formats into the triangle:

```
     \
    . ~
   / . ?
  . ` . <
 . . . . p
. ] p @ ( <

```

This part:

```
   \
  . ~
 / . ?
. ` . <

```

creates a loop to continue reading input as long as it's not EOF. `?` jumps over the directional command `<` that restarts the loop.

This part:

```
 . . . . p
. ] p @ ( <

```

pops the EOF from the stack, directs control flow to the left, opens a loop, prints the top of stack, pops it, and continues the loop if there are any values left.
> 0 votes

# Answer
# 8th, 7 bytes

**Code**

```
s:rev .

```

**Example**

```
ok> "Quick brown fox\nHe jumped over the lazy dog" s:rev .
god yzal eht revo depmuj eH
xof nworb kciuQ

```
> 0 votes

# Answer
# Chip, 59 bytes

```
))))))))-v~.
ABCDEFGHS<8<
01234567 >9s
))))))))~\t
abcdefgh

```

Try it online!

Requires either a null terminator, or the `-z` flag (which handles that for you). Since I use the flag only for the benefit of TIO, it is not included in the byte count.

```
ABCDEFGH            These are the eight bits of the input.

01234567            These are the eight bits of the stack head.

abcdefgh            These are the eight bits of the output.

))))))))-v~.        When at least one bit is on, enable writing to the stack
ABCDEFGHS<8<        (9) and suppress output (S). When all bits are zero,
         >9s        read from the stack (8) and suppress input (s) instead.

ABCDEFGH            When stack is in write mode, copy input bits directly
01234567            onto the stack.

01234567            When the stack is in read mode, send the values directly
))))))))~\t         to output. Once the stack is empty (all bits are zero),
abcdefgh            terminate the program (t).

```
> 0 votes

# Answer
# Implicit, 3 bytes

```
©®"

```

Try it online!

```
©    consume all input
 ®   reverse the stack
  "  stringify entire stack
     implicit output

```

For an alternate and faster version, use `©"\`, which reads all input, stringifies it, and reverses the string. It's faster than reversing an entire stack.

Version without builtins:

```
(~.);(¸@;)
(~.);       read all input with each character incremented by 1
     (¸@;)  decrement each character, print, pop loop

```
> 0 votes

# Answer
# QBIC, 28 bytes

```
{_?~A=B|_X\Z=_fA|+chr$(13)+Z

```

## Explanation

I can't just grab a multi-line string off of the cmd line parameters with the `;` command, that doesn't work in QBasic. Also, when we ask the user for input with `_?` it terminates on enter. We work around that with a loop:

```
{          DO infinitely
_?         Ask the user for input, store it in A$
~A=B       IF A$ is empty (or equal to B$ which is unassigned and therefore == '')
|_X        THEN QUIT, and print Z$ on the way out
\Z=+Z      ELSE set Z to be
_fA|       The last line entered reversed
+chr$(13)  Plus a newline
+Z         plus whatever already was in Z$
           The IF and the DO-loop are closed implicitly

```
> 0 votes

# Answer
# K (oK), 12 bytes

**Solution:**

```
`0:||:'"\n"\

```

Try it online!

**Example:**

```
`0:||:'"\n"\"Quick brown fox\nHe jumped over the lazy dog";
god yzal eht revo depmuj eH
xof nworb kciuQ

```

**Explanation:**

We can't easily take `STDIN`, so take a string, split on newline, reverse each line and then reverse the list of lines before printing to `STDOUT`:

```
`0:||:'"\n"\ / the solution
       "\n"\ / split (\) on newline "\n"
    |:'      / reverse (|:) each (')
   |         / reverse (|)
`0:          / print to STDOUT

```
> 0 votes

# Answer
# Forked, 32 bytes

```
v
>-v
| ~&-:-v
| |  | !
\-:-p^-<

```

Try it online!

The first block is the same as in the 44-byte solution. The second changes a bit direction-wise:

```
   &-:-v
     | !
    p^-<

```

Still fairly self-explanatory once you read the 44-byte explanation.

---

# Forked, 44 bytes

```
v     &<
>-v    |
| ~  >-:
| |  | |
^-:-p^!<

```

Try it online!

I love how self-explanatory this language is. However, I'll still explain it, as the conditional structure is a bit complex.

The first block thingy reads all input to the stack:

```
>-v
| ~
| |
^-:-

```

The fork at the bottom `:` directs the instruction pointer West if the inputted character is \> 0, causing it to go back into the loop. When EOF is entered, it directs it East, causing it to enter the second block thingy:

```
      &<
       |
     >-:
     | |
    p^!<

```

First, it `p`ops the EOF character. Then it goes North, then West, then hits the fork. While the top of stack is nonzero (i.e. it exists), the fork directs the IP South, then the `<` immediately directs it West, hitting `!` (print as character and pop), and it goes back into the loop. The fork directs the IP North if it's zero (i.e. the stack is empty), where it hits `<` and then `&` (exit, in this scenario). (note that the redirect is entirely unnecessary but the bytecount is the same, so... whatever.)
> 0 votes

# Answer
# Add++, 32 bytes

```
x:1
y:''
Wx,]getchar,`y,x+,`x
oy

```

Try it online!

Fairly basic, although STDIN support was recently added to Add++, so I decided to show it off.

First, we set the two variables we need:

```
x:1
y:''

```

**x** to the integer **1** and **y** to the empty string. Next, we loop over each character in STDIN:

```
Wx,]getchar,`y,x+,`x

```

This is a while loop, with the condition simply being **x**. Each `,` denotes the separation of a new command, so the code is expanded into

```
Wx,
  ]getchar
  `y
  x+
  `x

```

`]getchar` is an additional, Add++ jargon for an extended command that is prefixed with a `]`. Here, it simply reads a character from STDIN and assigns that to **x**. If the end of STDIN is reached, an empty string is returned.

Next, with

```
`y
x+
`x

```

We prepend this character to **y**, effectively building the string in reverse.

Once all input has been read, the **x** variable contains the empty string, and the while loop is terminated. Then we reach the final command

```
oy

```

This uses prefix notation: `o` is the command, and `y` indicates the variable to operate here. Here, `o` means output, *without* a trailing newline. **y** contains the input reversed, so this outputs our final result.
> 0 votes

# Answer
# Pepe, 16 bytes

```
REEeREEEEeEeeReee

```

Try it online! (Compiler makes whitespaces when doing links between e and r)

Explanation:

```
REEeREEEEeEeeReee - full program

REEe              - insert input as string
    REEEEeEee     - reverse whole stack
             Reee - output

```
> 0 votes

# Answer
# Ahead,  ~~9~~  13 bytes

```
~ilj~#
 >dko@

```

This one will function properly when NULs are on the input.

Try it online!
> 0 votes

# Answer
# PowerShell, 38 bytes

Thanks to Joey for the `$($input)` expression.

```
$($input)-join'
'|% t*y|%{$s=$_+$s}
$s

```

Try it online!

---

## Alternative, 38 bytes

```
@($input)-join'
'|% t*y|%{$s=$_+$s}
$s

```

Try it online!
> 0 votes

# Answer
# Brain-Flak, 12 bytes

```
{({}<>)<>}<>

```

Not going to be winning with this, but it works

Try it Online!
> 0 votes

# Answer
# Rust, 57 bytes

```
fn q(s:&str)->String{s.chars().rev().collect::<String>()}

```

Try it online!

# Dart, 34 bytes

```
f(s)=>s.split('').reversed.join();

```

Try it online!

Pretty convoluted, you have to get a String List then reverse it and join it back for it to work.
> 0 votes

# Answer
# Triangular, 14 bytes

```
(\~(#vp]<./)?<

```

Try it online!

I am almost 100% certain that `,~#n^`>p/` (9 bytes) would work if IP switches behaved in accordance with their specification, but in the meantime, 14 ain't too shabby.

Ungolfed:

```
     (
    \ ~
   ( # v
  p ] < .
 / ) ? <
----------------------------------------------
(                Set a point for the IP to jump to
 ~v<             Read a character from input, change directions twice
    ?)/          ) returns to the previously set point. ? will skip the jump back if ToS < 0
       p(        Pop the top value of the stack (the null-input), then set a new jump point
         /#<[    Pop the top value of the stack and print that value, then jump back if ToS > 0

```
> 0 votes

# Answer
# Elixir, 42 bytes

```
IO.puts String.reverse IO.read :stdio,:all

```
> 0 votes

# Answer
# MAWP, 16 bytes

```
[25W|]%%~%%0~[;]

```

Try it!
> 0 votes

# Answer
# Java (JDK), 96 bytes

```
class M{public static void main(String[]a){System.out.print(new StringBuffer(a[0]).reverse());}}

```

Try it online!
> 0 votes

# Answer
# Zsh (builtins only), 22 bytes

```
<<<${(j::)${(Oas::)*}}

```

Try it online!
> 0 votes

# Answer
# BRASCA, 1 bytes

Another simple 1-byter.

```
,

```

## Explanation

```
<implicit input>    - Push STDIN to the stack
,                   - Reverse the stack
<implicit output>   - Output the stack, reversed.

```

## Language Link

**Github Repo**
> 0 votes

# Answer
# Burlesque, 3 bytes

```
<-Q

```

Try it online!

Explanation:

```
      # Implicit input
<-    # Reverse
  Q   # Pretty format (removes wrapping "")
      # Output stack

```
> 0 votes

# Answer
# Whispers v2, 79 bytes

```
> InputAll
> 0
>> #1
>> (3]
>> 2-L
>> Each 5 4
>> 1ⁿL
>> Each 7 6
>> Output 8

```

Try it online!
> 0 votes

# Answer
# itflabtijtslwi, ~~233~~ 204 bytes

```
/Z/\/\///Y/\\\\ZH/Y>ZF/P.ZE/C.ZD/.BZB/\/.ZA/Y.Y./B/<Y\HYYYZP1/GGE2GG./E1E3D\./F2.\D\DB/E1D\./F2.\./p.2.AAB/E3D\D/E1E2E3./F1./F3D/p.\2./F1D/<.HDB/F\3./F1D/<.H./<.A\.H.AAA/F2ZP\2/P1Z<HZ/P\3/P1Z<H/<Y\HYYY/P2

```

Try it online!

## Original

I am not familiar with the language well; I barely understand how the program works. This is a modification of cat program.

```
/./<\\\\>\\\\\\//P1/GGC.2GG./C.1C.3./.\./P.2.\./.\./././C.1./.\./P.2.\./p.2.\.\.\.\././C.3./.\././C.1C.2C.3./P.1./P.3././p.\2./P.1././<.\>./././P.\3./P.1././<.\>./<.\.\.\.\>.\.\.\.\.\.\./P.2//P\2/P1//<\>///P\3/P1//<\>/<\\\\>\\\\\\/P2

```

Try it online!
> 0 votes

# Answer
# Twue, 31 bytes

```
@!#␀::=
@!::>@!#.
#_::~_
::=
@!
```

Try it on the website! (Note, ␀ represents the byte 0x00, here in the snippet and in the rest of the explanation.)

This was a bit trickier than it might first seem, since we need to account for the fact that the input may contain any character, and hence, may bungle any particular replacement. To combat this, we use the two-character `@!` which is constantly replaced with `@!#.`, where `.` is a byte of input, until EOF is hit, eventually looking something like this:

```
@!#␀#g#o#d# #y#z#a#l# #e#h#t# #r#e#v#o# #d#e#p#m#u#j# #e#H#
#x#o#f# #n#w#o#r#b# #k#c#i#u#Q

```

Our termination condition is `@!#␀`. Now, if we were to just use a single character, say `@`, to take input, the program would then continue to perform replacements on any such character in the input. By separating each character by `#`, we ensure that `@!` can never appear as a substring given any input.

The rest of the program is simple; `#_` outputs each character, removing the `#` and that character, until no more replacements can be made. This will work even for `#` characters present in the input, as the first `#_` in the string is matched every time, and we do not start processing these until the input is fully read.
> 0 votes

# Answer
# Duocentehexaquinquagesimal, 4 bytes

```
;&Oo

```

Try it online!
> 0 votes

# Answer
# Pxem, Filename: 15 bytes + Content: 0 bytes = 15 bytes.

* Filename (escaped): `.w.i.c\001.+.a.s.p`
* Content: empty

Try it online!
> 0 votes

# Answer
# Branch, 10 bytes

```
,[/,]^[.^]

```

Try it on the online Branch interpreter!

This works pretty much the same was as the BF answer does. Actually my language is proven TC by being a direct superset of BF, because if you only use the left branch, then you can use `/` and `^` in place of `>` and `<`, and `{` and `}` in place of `-` and `+` to translate any BF program into Branch (though you will have to do a bit of manipulation with the right branch if you want to depend on BF cells wrapping at 256).
> 0 votes

# Answer
# Swift, 86 bytes

```
var o=""
while let s=readLine(){o="\n" + .init(s.reversed())+o}
print(o,terminator:"")

```

As far as I'm aware, Swift doesn't have any builtin facilities to get stdin as a sequence that I can just call `reversed()` on. There's something in the Foundation library that I could `for try await` over, but the extra setup makes it not worth it.

Try it online!
> 0 votes

# Answer
# K (ngn/k), 2 bytes

```
|:

```

Try it online!

Trivial questions got trivial answers. If it wasn't for the Right operator (`:`) this could be a one-byter though.

# K (ngn/k), 5 bytes

```
`0:|:

```

Try it online!

This one outputs back to stdout, which is what the challenge specifies.
> 0 votes

# Answer
# Z80Golf, 12 bytes

```
00000000: cd03 8038 03f5 e9ff f130 fc76            ...8.....0.v

```

Try it online!

```
start:
    ; while (A = getchar() != EOF)
    ;     push A
.read:
    call   0x8003         ; CD 03 80 -> call getchar
    jr     c, .next       ; 38 03    -> jump to .next if carry (EOF)
    push   af             ; F5       -> Push input to stack
    jp     (hl)           ; E9       -> Jump to HL which == 0 (jr .read)
    ; while (A = pop() != EOF)
    ;     putchar(A)
.write:
    rst    0x38           ; FF       -> Print A
.next:
    pop    af             ; F1       -> Pop input to print
    jr     nc, .write     ; 30 FC    -> print and loop if no carry
    halt                  ; 76       -> Exit

```

The loops do have a bit of a tricky structure because of how the entry points are and how I am cheeky with `jp (hl)` instead of `jr .read` since `hl == 0x0000`. For all intents and purposes, these are two C style while loops.

Detecting when there is EOF in z80golf is easy, as the getchar syscall will set the carry flag. When the carry is not set, I push the input to the stack and loop again.

However, as for detecting when the input starts, that is a whole new problem. And to answer that, we first need to talk about parallel universes. Or rather...flags.

`push af` and `pop af` also push and pop the FLAGS register. It has the following structure

```
|  7  |  6  |  5  |  4  |  3  |  2  |  1  |  0  |
|  S  |  Z  | n/a |  H  | n/a | P/V |  N  |  C  |

```

Initially, the FLAGS are `00000000`, so the stack looks like this if I type "foo":

```
      A  F    FLAGS
FFFA: 6F 00 (--------)
FFFC: 6F 00 (--------)
FFFE: 66 00 (--------)

```

However, when the stack is empty, it wraps around to `0x0000` which is where the code is, and notably, `call 0x8003` will set the `C` flag, which I can test with a `jr nc`.

```
      A  F    FLAGS
0000: CD 03 (-----PNC)
0002: 80 38 (---H----)
...

```
> 0 votes

# Answer
# GolfScript, 3 bytes

```
-1%

```

Try it online!

Unless you can somehow represent `-1` in one byte, I'm fairly certain 3 bytes is the lowest possible score here.
> 0 votes

# Answer
# Go, 103 bytes

```
import(o "os";."io";."fmt")
func f(){s,_:=ReadAll(o.Stdin)
for i:=len(s)-1;i>=0;i--{Printf("%c",s[i])}}

```

Attempt This Online!
> 0 votes

# Answer
# StackCell, 11 bytes

`1[@:]`:[;:]`

Assumes input does not contain any null bytes, as they would be treated as EOF

Explanation:

* `1`: Skip the next instruction (`[`)
* (`[`): The start of a loop. Never executed
* `@`: Input a character from stdin
* `:]`: Duplicate the top value of the stack, and if it is non-zero jump back to the matching `[`, else continue
* ```: Discard the top value of the stack (0)
* `:[`: Duplicate the top value of the stack, and if it is zero jump to after the matching `]`, else continue
* `;`: Print the top value of the stack, as a character
* `:]`: Duplicate the top value of the stack, and if it is non-zero jump back to the matching `[`, else continue (and halt the program)
> 0 votes

# Answer
# (,) ~~124~~ ~~110~~ ~~72~~ 51 Chars or \\$51\log\_{256}(3)\approx\\$ 10.1 Bytes

```
(,((()),(()(),(()())((())))),,((())),((()),(()))())

```

Into the explanation:
The code works by backindexing. Basically setting input to a negative number will next give that many characters from the back. It uses that to make input next give -1 by setting input to 0 (in the loop condition). Then, it sets input to (setting variable 2 to variable 2 + input). Then, it outputs input
> 0 votes

# Answer
# Python, 20 Bytes

```
print(input()[::-1])

```

`[::-1]` is the actual thing that reverses the string. Since I haven’t looked at all the answers and this is a trivial programme, I highly suspect this is a duplicate.
> 0 votes

# Answer
# Lua, 31 bytes

```
io.write(io.read"*a":reverse())

```

Try it online!
> 0 votes

# Answer
# Lua, 27 bytes

```
print(io.read'a':reverse())

```

This is Lua 5.4 and 5.3 compatible. If you want Lua 5.2, 5.1 and LuaJIT compatible then you need one more byte:

```
print(io.read'*a':reverse())

```
> 0 votes

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


title: Chamber of Reflection

text:
# Question
Title: Chamber of Reflection
## Background

A ray of light is fired from the top left vertex of an `MxN` Chamber, where `M` a denotes the width and `N` denotes the height of the chamber. The ray of light advances one grid space per second. Given that `T` is the number of seconds to be simulated, calculate the number of reflections in this time frame.

For example, given `5 4 11` (ie. `M = 5, N = 4, T = 11`):

```
\/\  [
/\ \ [
\ \ \[
   \/[
-----
There would be 4 reflections, so the output should be 4.

```

Note that a reflection only counts if the ray of light has already bounced off it, so for example, given `5 4 10`:

```
\/\  [
/\ \ [
  \ \[
   \/[
-----
There would only be 3 reflections, so the output should be 3.

```

## Your Task

* Sample Input: M, the width of the chamber, N, the height of the chamber, and T, the time frame. These are all numbers.
* Output: Return the number of reflections.

**Explained Examples**

```
Input => Output
1 1 10 => 9

Chamber:
\[
-

The ray will be reflected back and forth a total of 9 times.

```

```
Input => Output
5 1 10 => 9

Chamber:
\/\/\[
-----

The ray will be reflected back and forth a total of 9 times. It will first go left to right, then go backwards right to left.

```

```
Input => Output
4 5 16 => 6

Chamber:
\/\ [
/\ \[
\ \/[
 \/\[
\/\/[
----

The ray will be reflected back and forth a total of 6 times.

```

```
Input => Output
100 100 1 => 0

Chamber:
\ ... [
...    x100
-x100

The ray never touches a wall, and is never reflected, so output 0.

```

**Test Cases**

```
Input => Output
5 4 11 => 4
5 4 10 => 3
1 1 10 => 9
5 1 10 => 9
4 5 16 => 6
100 100 1 => 0

3 2 9 => 5
5 7 5 => 0
3 2 10 => 6
6 3 18 => 5
5 3 16 => 7
1 1 100 => 99
4 4 100 => 24
2398 2308 4 => 0
10000 500 501 => 1
500 10000 502 => 1

```

Bonus points (not really): Listen to DeMarco's song Chamber of Reflection while solving this.

This is , so shortest answer wins.

# Answer
> 19 votes
# Python, 47 bytes

```
lambda M,N,T:len({*range(M,T,M),*range(N,T,N)})

```

Attempt This Online!

### How?

Enumerates and counts all bouncing times using the Python set type for deduplication.

# Answer
> 9 votes
# C (gcc), 58 bytes

```
g(a,b){a=b?g(b,a%b):a;}f(M,N,T){T=--T/M+T/N-T*g(M,N)/M/N;}

```

Try it online!

Uses the formula:

\\$ \lfloor \frac{T - 1}{M} \rfloor + \lfloor \frac{T - 1}{N} \rfloor - \lfloor \frac{T - 1}{lcm(M,N)} \rfloor\\$

# Answer
> 7 votes
# Nekomata, 5 bytes

```
ᵒ÷u#←

```

Attempt This Online!

Takes input as `[m,n],t`.

```
ᵒ÷u#←
ᵒ÷      Generate a division table of [0,...,t-1] and [m,n]
  u     Uniquify
   #    Length
    ←   Decrement

```

# Answer
> 6 votes
# Python 3, 50 bytes

```
lambda x,y,t:len({(i//x,i//y)for i in range(t)})-1

```

Try it online!

# Answer
> 5 votes
# Python 3.8 (pre-release), ~~49~~ 48 bytes

```
f=lambda M,N,T:(T:=T-1)and(T%M*(T%N)<1)+f(M,N,T)

```

Try it online!

-1 byte thanks to c--

# Answer
> 5 votes
# Jelly, 6 bytes

```
ḍƇⱮṖTL

```

A dyadic Link that accepts the dimensions on the left and the time on the right and yields the number of completed reflections.

**Try it online!**

### How?

```
ḍƇⱮṖTL - Link: dimensions = [M, N, ...]; time = T
   Ṗ   - pop {T} -> Seconds=[1,2,3,...,T-1]
  Ɱ    - map {across S in Seconds} with:
 Ƈ     -   keep {dimensions} that:
ḍ      -     divide {S}
    T  - truthy indices
     L - length

```

---

Lots more sixes such as, TIO:

```
ṖÆDfƇL - Link: time = T; dimensions = [M, N, ...]
Ṗ      - pop {T}
 ÆD    - divisors
    Ƈ  - keep those for which:
   f   -   filter keep {dimensions}
     L - length

```

`RmFQL’` TIO

`ḍẸ¥ⱮṖS` TIO

`×ⱮFQ<S`, `×þFQ<S`, `ḍⱮṖṀƇL`, `ḍþṖṀƇL`, `ḍⱮṖṀ€S`, `ḍþṖṀ€S`, `ḍⱮṖẸ€S`, `ḍþṖẸ€S`, `ḍⱮṖẸƇL`, `ḍþṖẸƇL`, `Ḷ:€QL’`, `:þSṖṬS`, ...

# Answer
> 4 votes
# JavaScript (Node.js), 36 bytes

*port of user1609012's Python answer*

```
f=(M,N,T)=>--T&&!(T%M&&T%N)+f(M,N,T)

```

Try it online!

## Explanation

Start from the end of the ray \\$(t = T)\\$, and count the number of times it bounced in it's way, that is, anytime \\$t \equiv 1 \pmod M \lor t \equiv 1 \pmod N\\$. It's easier to see if you extend the chamber infinitely and have the ray cross the chamber walls.

---

# C (gcc), 39 bytes

*port to C*

```
f(M,N,T){T=--T?!(T%M&&T%N)+f(M,N,T):0;}

```

Try it online!

# Answer
> 4 votes
# , 18 bytes

```
<:@#@~.@(<.@%/~i.)

```

Uses the division table method used by others. Expects `M N f T`.

Attempt This Online!

```
<:@#@~.@(<.@%/~i.)
        (        )  NB. Dyadic hook
               i.   NB. 0..y-1
             /~     NB. Table with flipped arguments, execute a u b for every a in x and b in y
         <.@%       NB. Divide then floor
<:@#@~.@            NB. Then uniquify, length, and decrement

```

# , 19 bytes

```
+`-/@(<.@%[,*./)~<:

```

Uses the closed form from c--'s answer, so please go upvote!

Expects `M N f T`, where `M N` is a list.

The major form is two hooks, an inner and outer hook, `(H F)~ G`, which is equivalent to `(G y) H (F x)`, with `+`-/` tacked on at the end, where `x` and `y` are the left and right arguments, respectively.

Attempt This Online!

```
+`-/@(<.@%[,*./)~<:
                 <:  NB. Decrement T
     (         )~    NB. Flip the arguments for the inner hook
          [,*./      NB. Append lcm(M,N) to the list of dimensions
      <.@%           NB. Divide T-1 by each item of the result then floor
+`-/@                NB. Then reduce by both + and -, i.e. +`-/ 6 3 1 = 6 + 3 - 1 = 8

```

# Answer
> 4 votes
# Octave, 33 bytes

```
@(M,N,T)nnz(union(1:M:T,1:N:T))-1

```

Try it online!

Thanks to @Luis Mendo for -2.

### Octave, 35 bytes

```
@(M,N,T)numel(union(1:M:T,1:N:T))-1

```

Try it online!

Port of @Albert.Lang's Python answer.

# Answer
> 3 votes
# JavaScript (Node.js), 46 bytes

```
M=>N=>g=(T,x,y)=>T--?!(x*y)+g(T,-~x%M,-~y%N):T

```

Try it online!

# Answer
> 2 votes
# Scala, 156 bytes

Golfed version. Try it online!

```
def f(M:Int)(N:Int):(Int,Int,Int)=>Int={def g(T:Int,x:Int=0,y:Int=0):Int=if(T<1)-1 else if(x==0||y==0)1+g(T-1,(x+1)%M,(y+1)%N)else g(T-1,(x+1)%M,(y+1)%N);g}

```

Ungolfed version. Try it online!

```
object Main {
  def f(M: Int)(N: Int): (Int, Int, Int) => Int = {
    def g(T: Int, x: Int = 0, y: Int = 0): Int = {
      if (T == 0) T-1
      else if (x == 0 || y == 0) 1 + g(T - 1, (x + 1) % M, (y + 1) % N)
      else g(T - 1, (x + 1) % M, (y + 1) % N)
    }

    g
  }

  def main(args: Array[String]): Unit = {
    val testCases = Array(
      (5, 4, 11),
      (5, 4, 10),
      (1, 1, 10),
      (5, 1, 10),
      (4, 5, 16),
      (100, 100, 1),
      (3, 2, 9),
      (3, 2, 10),
      (6, 3, 18),
      (5, 3, 16),
      (1, 1, 100),
      (4, 4, 100),
      (2398, 2308, 4),
      (10000, 500, 501),
      (500, 10000, 502)
    )

    testCases.foreach { case (a, b, c) =>
      println(f(a)(b)(c, 0, 0))
    }
  }
}

```

# Answer
> 2 votes
# Charcoal, 15 bytes

```
≔…¹ＮθＩ№×﹪θＮ﹪θＮ⁰

```

Attempt This Online! Link is to verbose version of code. Takes `T` as the first parameter. Explanation:

```
 …              Exclusive range from
  ¹             Literal integer `1` to
   Ｎ            First input as a number
≔   θ           Save in variable
         θ      Saved range
        ﹪       Vectorised modulo
          Ｎ     Second input as a number
       ×        Pairwise multiplied by
            θ   Saved range
           ﹪    Vectorised modulo
             Ｎ  Third input as a number
      №         Count of
              ⁰ Literal integer `0`
     Ｉ          Cast to string
                Implicitly print

```

# Answer
> 1 votes
# Racket, 210 bytes

```
(define(r M N T[R 0][X 0][Y 0][x 1][y 1])(let*([A(+ X x)][B(+ Y y)][a(or(< A 0)(> A M))][b(or(< B 0)(> B N))])(if(= T 0)R(r M N(- T 1)(if(or a b)(+ R 1)R)(if a(- X x)A)(if b(- Y y)B)(if a(- x)x)(if b(- y)y)))))

```

Try it online!

---

## Explanation

For starters, this will definitely not win. Looking at the other answers, there seems to be a simpler algorithm to solving this. But I don't want to just copy things without having any understanding on how or why they work, so I decided to use a bruteforcing method of actually running the simulation.

Our function receives our three inputs `M`, `N` and `T`. It also receives a predefined state for the recursive loop.

```
(define (reflect M N T
                 [reflections 0]
                 [x-pos 0] [y-pos 0]
                 [dx 1] [dy 1])
  ...)

```

We then calculate the next `x` and `y` position, and see whether the next position are out-of-bounds (`-oob`).

```
  (let* ([next-x-pos (+ x-pos dx)]
         [next-y-pos (+ y-pos dy)]
         [next-x-oob (or (< next-x-pos 0) (> next-x-pos M))]
         [next-y-oob (or (< next-y-pos 0) (> next-y-pos N))])
    ...)

```

Once those values are calculated, we check whether our simulation time `T` is equal to zero. If it is, we return the resulting number of reflections. Otherwise we repeat the loop with a new set of configurations:

1. Same `M` and `N` sizes.
2. `T` \- 1.
3. If the next X and Y positions are out of bounds, `reflections` \+ 1, else `reflections`.
4. If the next X position is out of bounds, recalculate the next position by flipping `dx`.
5. If the next Y position is out of bounds, recalculate the next position by flipping `dy`.
6. If the previously calculated `next-x-pos` is out of bounds, flip `dx`.
7. If the previously calculated `next-y-pos` is out of bounds, flip `dy`.

```
(define (reflect M N T
                 [reflections 0]
                 [x-pos 0] [y-pos 0]
                 [dx 1] [dy 1])
  (let* ([next-x-pos (+ x-pos dx)]
         [next-y-pos (+ y-pos dy)]
         [next-x-oob (or (< next-x-pos 0) (> next-x-pos M))]
         [next-y-oob (or (< next-y-pos 0) (> next-y-pos N))])
    (if (= T 0)
        R
        (reflect M N (- T 1)
                 (if (or next-x-oob next-y-oob)
                     (+ reflections 1)
                     reflections)
                 (if next-x-oob
                     (- x-pos dx)
                     next-x-pos)
                 (if next-y-oob
                     (- y-pos dy)
                     next-y-pos)
                 (if next-x-oob
                     (- dx)
                     dx)
                 (if next-y-oob
                     (- dy)
                     dy))))

```

*Have an awesome weekend!*

# Answer
> 1 votes
# 05AB1E, 8 bytes

```
<Lsδ÷Ùg<

```

Try it online or verify all test cases.

**Explanation:**

```
<L        # Use the first (implicit) input, and push a list in the range [1,input-1]
  s       # Swap to push the second (implicit) input-pair
   δ      # Apply double-vectorized:
    ÷     #  Integer-division
     Ù    # Uniquify this list of pairs
      g   # Pop and push the length
       <  # Decrease it by 1
          # (after which the result is output implicitly)

```

# Answer
> 1 votes
# Thunno 2 `L`, 6 bytes

```
ėsȷ÷Uṫ

```

Try it online!

Port of alephalpha's Nekomata answer.

#### Explanation

```
ėsȷ÷Uṫ  # Implicit input
ė       # Push [1..t) to the stack
 s      # Swap so [m,n] is on top
  ȷ     # Outer product over:
   ÷    #  Integer division
    U   # Uniquify the list
     ṫ  # Remove the last item
        # Implicit output of length

```

# Answer
> 0 votes
# Pyth, 7 bytes

```
tl{/R.Q

```

Try it online!

Port of @alephalpha's Nekomata answer.

Takes three inputs: time, width, height in that order.

### Explanation

```
tl{/R.QQ    # implicitly add Q
            # implicitly assign Q = eval(input()) and .Q to a list of the remaining input
   /R.QQ    # map division over range(Q) with .Q as the second argument, this automatically vectorizes
  {         # deduplicate
 l          # take the length
t           # subtract 1

```

---
Tags: code-golf
---