| Bytes | Lang | Time | Link |
|---|---|---|---|
| 092 | Bespoke | 250802T065733Z | Josiah W |
| 030 | tcl | 170105T223728Z | sergiol |
| 014 | Pip | 190731T184234Z | Kenzie |
| nan | 230603T203845Z | Dadsdy | |
| 031 | Trilangle | 230227T031906Z | Bbrk24 |
| 001 | 05AB1E | 201210T231518Z | Makonede |
| 014 | ForWhile | 230717T112733Z | noodle p |
| 027 | Lua | 230717T151025Z | thenumbe |
| 011 | StackCell | 230603T203248Z | Starwort |
| 031 | Lua | 230603T213844Z | bluswimm |
| 020 | Python | 230603T205342Z | The Empt |
| 001 | Thunno W | 230217T110016Z | The Thon |
| 103 | Go | 230217T151007Z | bigyihsu |
| 003 | GolfScript | 230217T144104Z | emirps |
| 013 | Apple Shortcuts | 221117T162305Z | joyofori |
| 011 | Ruby | 221107T161919Z | joyofori |
| 012 | Z80Golf | 221105T175809Z | EasyasPi |
| 089 | Javascript Node.js | 220913T091053Z | Leaf |
| 002 | K ngn/k | 221010T141342Z | oeuf |
| 086 | Swift | 221010T140646Z | Bbrk24 |
| 001 | Vyxal | 221010T122332Z | DialFros |
| 037 | Knight v2.0alpha | 220918T062643Z | Sampersa |
| nan | Fig | 220915T210722Z | Seggan |
| 031 | Prolog SWI | 220906T035941Z | naffetS |
| 005 | Tellurium | 160524T044400Z | m654 |
| 004 | Braingolf | 170703T092131Z | Mayube |
| 019 | CJam | 151102T234834Z | geokavel |
| 011 | !@#$%^&*_+ | 220129T143640Z | Twilight |
| 9624 | .mmo MMIX executable | 210607T194302Z | NoLonger |
| 016 | Hexagony | 210606T115744Z | je je |
| 010 | Branch | 210418T145319Z | hyperneu |
| nan | Pxem | 210417T011048Z | user1004 |
| 204 | itflabtijtslwi | 210408T094849Z | user1004 |
| 004 | Duocentehexaquinquagesimal | 210414T183756Z | Makonede |
| 031 | Twue | 210413T083808Z | Conor O& |
| 014 | V vim | 210408T102333Z | Razetime |
| 079 | Whispers v2 | 210225T005834Z | Michael |
| 003 | Burlesque | 210122T100633Z | Mintable |
| 001 | BRASCA | 210122T094457Z | SjoerdPe |
| 022 | Zsh builtins only | 201211T013443Z | roblogic |
| 001 | Husk | 201211T000655Z | Dominic |
| 096 | Java JDK | 201210T180043Z | DMiddend |
| 005 | Stupidity | 201210T153637Z | user9921 |
| 052 | Flurry | 200818T095634Z | Bubbler |
| 016 | MAWP | 200818T070157Z | Razetime |
| 017 | 1+ EOF returns 0 | 200818T060111Z | Twilight |
| 060 | Poetic | 191116T081137Z | JosiahRy |
| 4033 | Wren | 191027T022953Z | user8505 |
| 042 | Elixir | 191027T183500Z | Vasu Ada |
| nan | Shakespeare Programming Language | 191026T214826Z | Hello Go |
| 014 | Triangular | 190916T195055Z | squid |
| 001 | Keg | 190916T074856Z | lyxal |
| 057 | Rust | 190820T084811Z | Elcan |
| 012 | BrainFlak | 190807T124216Z | Edgex42 |
| 038 | PowerShell | 190404T064600Z | mazzy |
| 013 | Ahead | 180714T185804Z | snail_ |
| 016 | Pepe | 180710T043112Z | u-ndefin |
| 041 | R | 180608T200529Z | JayCe |
| 032 | Add++ | 180608T195527Z | user8101 |
| 024 | Retina 0.8.2 | 150914T211823Z | mbomb007 |
| 047 | C | 110202T182902Z | Joey Ada |
| 039 | Momema | 180212T072727Z | Esolangi |
| 032 | Forked | 180212T042927Z | MD XF |
| 011 | Wumpus | 180215T125524Z | Martin E |
| 012 | Wumpus | 180216T105516Z | Sp3000 |
| 022 | Attache | 180215T190421Z | Conor O& |
| 001 | Japt | 170105T193010Z | Oliver |
| 033 | Julia 0.6 | 180116T190108Z | gggg |
| 014 | ><> | 150929T023422Z | cole |
| 003 | Implicit | 170919T030402Z | MD XF |
| 003 | Aceto | 171118T053411Z | qqq |
| 028 | QBIC | 171102T095213Z | steenber |
| 056 | Matlab | 150927T101842Z | Abr001am |
| 006 | Jelly | 170306T124005Z | Erik the |
| 012 | K oK | 171102T112702Z | mkst |
| 001 | 05AB1E | 160426T160647Z | penalosa |
| 067 | Common Lisp | 170815T211536Z | Renzo |
| 059 | Chip | 170814T213113Z | Phlarx |
| 001 | Brachylog | 170814T205525Z | DanTheMa |
| 007 | 8th | 170814T192748Z | Chaos Ma |
| nan | Excel VBA | 161130T175044Z | Taylor R |
| 021 | Triangular | 170615T042501Z | MD XF |
| 040 | Python | 110130T122726Z | Thomas O |
| 067 | Whitespace | 170531T124610Z | Ephphath |
| 091 | MarioLANG | 170528T022345Z | user6933 |
| 007 | Alice | 170412T075118Z | Martin E |
| 082 | GameMaker Language | 131206T160610Z | Timtech |
| 048 | Commodore 64/VIC20 BASIC | 170306T144915Z | Shaun Be |
| 8171 | ZX81 BASIC 71 Bytes listing | 170303T091338Z | Shaun Be |
| 039 | Python 2 | 150913T163453Z | TheIniti |
| 156 | Java | 150531T192551Z | SuperJed |
| 032 | SmileBASIC | 170201T235724Z | 12Me21 |
| 015 | BrainFlak | 170105T191849Z | DJMcMayh |
| 016 | Perl 6 | 161230T005949Z | Sean |
| 024 | awk | 161229T124045Z | James Br |
| 008 | Cubix | 161226T140954Z | FlipTack |
| 103 | Java | 161130T180751Z | Xanderha |
| 003 | Sesos | 161014T185625Z | Erik the |
| 028 | Hexagony | 160813T002136Z | X88B88 |
| 027 | MarioLANG | 160812T205017Z | Zwei |
| 022 | Befunge93 11x2 | 110202T181956Z | MiffTheF |
| 001 | Pyke | 160703T132034Z | Blue |
| 007 | Stack Cats | 160612T102738Z | Martin E |
| 002 | Fuzzy Octo Guacamole | 160404T035737Z | Riker |
| 006 | Retina | 160404T195632Z | Martin E |
| 002 | Seriously | 160404T050704Z | user4594 |
| 006 | Minkolang 0.10 | 151030T192535Z | El'e |
| 037 | C | 110309T053225Z | Quixotic |
| 037 | Javascript ES6 | 151030T221705Z | Mama Fun |
| 081 | AppleScript | 151103T162717Z | Addison |
| 004 | Pyth | 150601T001620Z | kirbyfan |
| 062 | Hassium | 151001T172250Z | Jacob Mi |
| nan | TIBASIC | 150929T012947Z | Conor O& |
| 017 | ><> | 150927T114342Z | Aaron |
| 010 | Labyrinth | 150829T162745Z | Martin E |
| 015 | Fission | 150531T153347Z | BrainSte |
| 012 | Fission | 150531T123155Z | Martin E |
| 316 | Pancake Stack | 140927T193433Z | Justin |
| 014 | Perl 5.1 | 140111T175753Z | Timtech |
| 010 | Befunge98 | 131005T110501Z | FireFly |
| 044 | Groovy | 110309T133520Z | Espen Sc |
| 047 | JavaScript | 131004T191513Z | user7906 |
| 060 | Scala | 130919T082443Z | Piotr Ko |
| 044 | JavaScript | 130919T033219Z | tristin |
| 002 | APL | 130918T085119Z | jpjacobs |
| 009 | Binary Lambda Calculus | 130918T031302Z | C0deH4ck |
| 010 | BrainFuck | 110316T230809Z | Kevin Br |
| 096 | VB.Net | 110202T060923Z | snmcdona |
| 116 | C# | 110202T055439Z | snmcdona |
| 021 | Haskell | 110207T151818Z | Konstant |
| 028 | PHP | 110130T211348Z | Kevin Br |
| 017 | PHP | 110204T160230Z | Arnaud L |
| 023 | Perl | 110204T200251Z | Andrew |
| nan | 110204T192444Z | huntar | |
| 044 | PHP | 110203T212139Z | ircmaxel |
| 003 | Golfscript | 110130T130711Z | gnibbler |
| 168 | C++ | 110131T042043Z | grokus |
| 035 | Python | 110130T131416Z | gnibbler |
| 019 | Ruby | 110130T190117Z | Nemo157 |
| 007 | Bash | 110130T153044Z | moinudin |
| 053 | Windows PowerShell | 110130T122154Z | Joey |
Bespoke, 92 bytes
getting heavily drunk
Id do some backward-talking phrases
for example:DRIEW YLLAER
Im tips-y
This is made super simple by the fact that Bespoke is stack-based.
Each input codepoint is pushed onto the stack (until -1, signifying EOF), and then each stack value is printed (except the top value, which will be the EOF marker and is skipped).
tcl, 30
puts [string rev [read stdin]]
To terminate input press Ctrl+D.
Available to run on: https://www.tutorialspoint.com/compilers/online-tcl-compiler.htm?PID=0Bw_CjBb95KQMYVRqeDNxc29WWlE
(,) 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
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 flowi: 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-opS: 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 flowS: 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 stackS: swap the two values on top of the stacko: 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.
05AB1E, 3 1 byte
R
Try it online! Takes input surrounded in """triple double quotes""".
R # full program
R # reverse...
# implicit input
# implicit output
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:
{[#)}
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())
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)
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.
Thunno W, 1 byte
(actually \$ 1 \log_{256}(96) \approx \$ 0.82 bytes, but that doesn't show up on the leaderboard)
r
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.
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])}}
GolfScript, 3 bytes
-1%
Unless you can somehow represent -1 in one byte, I'm fairly certain 3 bytes is the lowest possible score here.
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.
Z80Golf, 12 bytes
00000000: cd03 8038 03f5 e9ff f130 fc76 ...8.....0.v
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----)
...
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('')))
K (ngn/k), 2 bytes
|:
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:|:
This one outputs back to stdout, which is what the challenge specifies.
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.
Knight (v2.0-alpha), 37 bytes
;=s=t@;W=gP=s+s+g"
";Ws;=t+[s t=s]sOt
Nothing super exciting, except for the fact that we can use @ instead of "" for the initial value of s and t.
Tellurium, 5 bytes
i&r.^
- The
icommand gets input and stores it in the selected cell. &starts string manipulation mode.ris a string mode command. It reverses whatever is stored in the selected cell..exits string mode.^outputs the cell's value.
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
!@#$%^&*()_+, 11 bytes
^*( *)+(*@)
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 (_^_).
.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)
Hexagony, 16 bytes
\{\{:}($.,.=;)$\
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
},)<>'"<{\@..(_$.>.$;
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).
Pxem, Filename: 15 bytes + Content: 0 bytes = 15 bytes.
- Filename (escaped):
.w.i.c\001.+.a.s.p - Content: empty
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
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
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.
V (vim), 14 bytes
:g/^/m0
:%!rev
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.
Whispers v2, 79 bytes
> InputAll
> 0
>> #1
>> (3]
>> 2-L
>> Each 5 4
>> 1ⁿL
>> Each 7 6
>> Output 8
Burlesque, 3 bytes
<-Q
Explanation:
# Implicit input
<- # Reverse
Q # Pretty format (removes wrapping "")
# Output stack
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
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".
↔
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
Java (JDK), 96 bytes
class M{public static void main(String[]a){System.out.print(new StringBuffer(a[0]).reverse());}}
Stupidity, 5 Bytes
I R _
Here is how it works:
Igets an input string from STDIN.Rreverses the string._prints the string from STDOUT.
I will be posting the link to the language soon.
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+ (EOF returns 0), 17 bytes
1##,"1<1+#+(|;())
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+#+(|;())
Poetic, 60 bytes
normally i create a reversal
so could i?i suppose maybe i do
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).
Wren, 40 33 bytes
After I discovered a really clever trick...
Fn.new{|a|System.write(a[-1..0])}
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])}}
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])
}
Elixir, 42 bytes
IO.puts String.reverse IO.read :stdio,:all
Shakespeare Programming Language, 213 185 bytes (153 bytes with error)
Thanks to Jo King for saving 28 bytes!
(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.
Triangular, 14 bytes
(\~(#vp]<./)?<
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
Rust, 57 bytes
fn q(s:&str)->String{s.chars().rev().collect::<String>()}
Dart, 34 bytes
f(s)=>s.split('').reversed.join();
Pretty convoluted, you have to get a String List then reverse it and join it back for it to work.
PowerShell, 38 bytes
Thanks to Joey for the $($input) expression.
$($input)-join'
'|% t*y|%{$s=$_+$s}
$s
Alternative, 38 bytes
@($input)-join'
'|% t*y|%{$s=$_+$s}
$s
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
R, 41 bytes
cat(intToUtf8(rev(utf8ToInt(scan(,"")))))
Alternate "classic" version working directly with characters:
R, 53 bytes
for(i in rev(el(strsplit(scan(,""),split=""))))cat(i)
Because every question deserves at least one answer in R. Even string questions...
Add++, 32 bytes
x:1
y:''
Wx,]getchar,`y,x+,`x
oy
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.
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
C - 47 characters
main(c){if(c=getchar(),c>=0)main(),putchar(c);}
Note that this uses O(n) stack space. Try it online!
Momema, 39 bytes
z00+1*0*0*-9z=+1**0y00+-1*0-9**0y=+-1*0
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)
Forked, 32 bytes
v
>-v
| ~&-:-v
| | | !
\-:-p^-<
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^!<
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 pops 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.)
Wumpus, 13 11 bytes
)?\;l&o@
=i
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.
Wumpus, 12 bytes
i=)!4*0.l&o@
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.
Attache, 22 bytes
Stdout!Reverse!Stdin[]
! 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.
><>, 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
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!
I believe this is valid now via meta consensus.
Previous answer (14 bytes)
i:0(7$.
~ol0=?;!
Implicit, 3 bytes
©®"
© 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
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
Matlab (56)
a=1;b=0;while(a)a=input('','s');b=[flipud(a) 10 b];end,b
Execution:
abc
def
b =
fed
cba
K (oK), 12 bytes
Solution:
`0:||:'"\n"\
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
05AB1E, 1 byte
R
R reverses the input.
Chip, 59 bytes
))))))))-v~.
ABCDEFGHS<8<
01234567 >9s
))))))))~\t
abcdefgh
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).
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
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 '=')
Triangular, 21 bytes
\.~/.?.`.<....p.]p@(<
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.
Python, 41 40 bytes
import sys;print sys.stdin.read()[::-1]
41 -> 40 - removed semicolon at end of program.
Probably could be optimised!
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.
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.
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.
Alice, 7 bytes
\oi
/R@
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.
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
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
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.
Python 2, 39 bytes
import sys;print sys.stdin.read()[::-1]
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.
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.
Brain-Flak, 15 bytes (non-competing)
{({}<>)<>}<>
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
<>
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.
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
Cubix, 9 8 bytes
Many thanks to Martin Ender for this golf:
w;o@i.?\
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 stackw: '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-1as input has finished.\: reflect the IP, sending it North, into:@: terminate the program.
9 byte solution
..o;i?@!/
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.
Java, 103 bytes
Full programs in Java suck.
class A{public static void main(String args[]){System.out.print(new StringBuffer(args[0]).reverse());}}
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
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.
MarioLANG, 35 31 27 bytes
,)<.-<
+=">="
>[!([!
==#==#
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.
Stack Cats, 7 bytes
<!]T[!>
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
-1on 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
-1at 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.
Fuzzy Octo Guacamole, 2 bytes
(non-competing, FOG is newer than the challenge)
^z
^ gets input, z reverses, and implicit output.
Retina, 6 bytes
Non-competing, since Retina is newer than this challenge.
O$^s`.
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:
Ojust 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.
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).
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.
C, 37 bytes
main(_){write(read(0,&_,1)&&main());}
Javascript (ES6), 37
Really simple. Try below in Firefox.
alert([...prompt()].reverse().join``)
𝔼𝕊𝕄𝕚𝕟, 4 chars / 8 bytes (noncompetitive)
ôᴙï)
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.
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
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
Hassium, 62 Bytes
func main(){s=input();for(x=s.length- 1;x>=0;print(s[x--]))0;}
Run and see expanded here
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
><>, 17 bytes
!vi:1+?
~
l<o;!?
I don't even need to reverse the input as putting it on a stack naturally does that.
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.
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.
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.
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
Perl 5.1, 14
say~~reverse<>
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.
Groovy 44 characters
args.reverse().each{print it.reverse()+" "}
JavaScript - 50 48 47
Slightly longer than the other JS entry
a='';for(i=(b=prompt()).length;i;a+=b[i---1]);a
Scala - 60
print(io.Source.fromInputStream(System.in).mkString.reverse)
JavaScript - 44
I don't think you can get much shorter with JS. Nothing interesting here.
alert(prompt().split('').reverse().join(''))
APL, 2
⊖⍞
Or CircleBar QuoteQuad if the characters don't come through, simply meaning: reverse keyboard character input.
Binary Lambda Calculus - 9 bytes
16 46 80 17 3E F0 B7 B0 40
BrainFuck, 10 characters
,[>,]<[.<]
Beats a good amount of answers for such a simple language.
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
C# - 116
using System.Linq;using c=System.Console;class p{static void Main(){c.Write(c.In.ReadToEnd().Reverse().ToArray());}}
Haskell - 21
main=interact reverse
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
PHP - 38 17 characters
<?=strrev(`cat`);
Perl - 23
print scalar reverse <>
Perl
print scalar reverse for reverse(<STDIN>);
PHP - 44 characters
<?=strrev(file_get_contents('php://stdin'));
Golfscript - 3 chars
-1%
obfuscated version is also 3 chars
0(%
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;}
Python - 35 chars
import os;print os.read(0,2e9)[::-1]
Ruby - 19 characters
puts$<.read.reverse
Bash - 7
tac|rev
tac reverses line order, while rev reverses character order.
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.






