| Bytes | Lang | Time | Link |
|---|---|---|---|
| nan | 250410T115927Z | noodle p | |
| nan | C clang | 250409T165125Z | ceilingc |
| nan | 170531T000400Z | sergiol | |
| nan | 241214T234013Z | sergiol | |
| 050 | Perl 5 | 180328T155035Z | Dom Hast |
| nan | 180328T150347Z | 12Me21 | |
| nan | 180328T141645Z | Andre | |
| nan | 170601T014505Z | sergiol | |
| nan | 170531T232151Z | sergiol | |
| nan | 170528T211658Z | sergiol | |
| nan | 170117T075917Z | Sir Bite | |
| nan | 170117T145117Z | Denham C | |
| nan | 161010T231939Z | ATaco | |
| nan | 151230T183216Z | user1921 | |
| nan | 160905T172012Z | fede s. | |
| nan | 140213T125043Z | Noyo | |
| nan | 140212T150827Z | Timtech | |
| nan | 140212T222012Z | sqlab | |
| nan | 140212T181600Z | Riot | |
| nan | 140214T154108Z | Bill Woo | |
| nan | 150429T131001Z | SuperJed | |
| nan | 150429T130342Z | SuperJed | |
| 003 | Python 2 and | 150429T112704Z | pgy |
| nan | 150426T235600Z | fede s. | |
| nan | 140609T045552Z | Fish | |
| nan | 140609T063026Z | Spedward | |
| nan | 140607T171712Z | mikeserv | |
| nan | 140427T155916Z | Yshayy | |
| 002 | Python | 140327T133102Z | Justin F |
| nan | 140327T102115Z | Mau | |
| nan | 140308T084742Z | Mamun | |
| nan | 140308T081508Z | Piotr | |
| nan | 140308T061323Z | Shreyas | |
| nan | 140215T195648Z | Justin | |
| nan | 140225T153231Z | Mark Jer | |
| nan | 140222T071000Z | Clyde Lo | |
| nan | 140221T105653Z | Pharap | |
| nan | 140212T212915Z | Lance | |
| nan | Kinda lame | 140219T213654Z | DLeh |
| 008 | Java | 140218T230723Z | David Co |
| nan | 140218T220606Z | David Co | |
| nan | 140218T173957Z | Douglas | |
| nan | 140212T180435Z | Nick | |
| nan | 140218T101516Z | James_pi | |
| nan | 140218T103806Z | James_pi | |
| nan | 140218T073442Z | tbrosman | |
| 003 | Python | 140218T061644Z | Strigoid |
| nan | 140214T092334Z | Noyo | |
| nan | 140217T214321Z | Gilsham | |
| nan | 140217T160409Z | dav_i | |
| nan | 140217T152725Z | Geoff Re | |
| 002 | Python | 140217T084946Z | OregonTr |
| nan | 140214T121818Z | Mr Liste | |
| nan | 140216T224001Z | Ingo | |
| 006 | Perl | 140216T104121Z | Ayiko |
| 003 | Python | 140216T094836Z | Evpok |
| nan | 140216T031933Z | palanik | |
| nan | 140216T001205Z | Jarry | |
| nan | 140215T203248Z | Tarmil | |
| nan | 140215T170755Z | user8658 | |
| nan | 140215T180806Z | Callie J | |
| nan | 140215T172810Z | Pran | |
| nan | 140215T161235Z | Kjellski | |
| nan | 140215T125721Z | ceased t | |
| nan | 140215T143442Z | ToXik-yo | |
| nan | Smalltalk 79/66/143 chars | 140215T111504Z | blabla99 |
| nan | 140215T010215Z | Matteo I | |
| nan | 140214T234728Z | Phil Hor | |
| nan | 140212T190558Z | Hydrothe | |
| nan | 140214T213034Z | Kevin | |
| nan | 140214T202214Z | Kevin | |
| nan | 140214T205308Z | Kevin | |
| 003 | Python | 140214T175450Z | jazzpi |
| nan | 140214T163009Z | davidak | |
| nan | 140214T142805Z | Pieter W | |
| 005 | Perl | 140214T142201Z | Ilmari K |
| nan | 140214T123952Z | 6160 | |
| nan | 140214T120956Z | Riymus | |
| nan | 140214T091133Z | ojk | |
| nan | 140213T220017Z | asgoth | |
| nan | 140214T012430Z | Matteo I | |
| nan | 140214T010958Z | Boris | |
| nan | 140214T001130Z | Ruslan | |
| nan | 140213T231023Z | mattnewp | |
| nan | 140213T221845Z | Ruslan | |
| nan | 140213T221930Z | gnibbler | |
| nan | 140213T222557Z | gnibbler | |
| nan | 140212T162251Z | ugoren | |
| nan | 140213T213909Z | Digital | |
| nan | 140213T205819Z | Digital | |
| nan | 140212T204616Z | masterX2 | |
| nan | 140213T203031Z | Izkata | |
| nan | 140213T191821Z | AShelly | |
| nan | 140212T163850Z | bwoebi | |
| nan | 140213T175320Z | Nick H. | |
| nan | 140213T162104Z | hvd | |
| nan | 140213T153438Z | user6019 | |
| nan | 140213T152400Z | Dennis J | |
| nan | 140213T151624Z | Dero | |
| nan | 140213T151120Z | SamYonno | |
| nan | 140213T143641Z | user1117 | |
| nan | 140213T140953Z | hmilch | |
| nan | 140213T131818Z | nightTre | |
| 003 | Python | 140213T120544Z | Mark Plo |
| nan | 140213T112203Z | user1635 | |
| nan | 140212T144844Z | draegtun | |
| nan | 140213T081456Z | Indy | |
| nan | 140212T184526Z | Justin | |
| nan | 140212T195910Z | Mo D | |
| nan | 140213T073959Z | Sergey T | |
| 003 | Python | 140213T063429Z | a_e_m |
| nan | 140213T041428Z | Josh | |
| nan | 140213T035401Z | aragaer | |
| nan | 140213T034611Z | Kevin | |
| nan | 140213T032727Z | unclemea | |
| nan | 140213T031029Z | cory.tod | |
| nan | 140213T030745Z | justhalf | |
| nan | 140212T143800Z | Danny | |
| 001 | Common Lisp № | 140212T204422Z | Joshua T |
| nan | 140212T231749Z | Danko Du | |
| nan | 140212T230447Z | Xaqq | |
| nan | 140212T212700Z | Potherca | |
| nan | 140212T203607Z | chinese | |
| nan | 140212T202402Z | David Ya | |
| nan | 140212T190007Z | svick | |
| nan | 140212T184324Z | 11684 | |
| nan | 140212T183249Z | svick | |
| nan | 140212T183546Z | gggg | |
| nan | 140212T182054Z | svick | |
| nan | 140212T182401Z | tmartin | |
| nan | 140212T153140Z | RobIII | |
| 003 | Python | 140212T181152Z | user344 |
| nan | 140212T180031Z | Tumin | |
| nan | 140212T180646Z | kelunik | |
| nan | 140212T175003Z | Decent D | |
| nan | 140212T174813Z | draegtun | |
| nan | 140212T173817Z | davidak | |
| nan | 140212T152802Z | luxcem | |
| nan | 140212T170546Z | p.s.w.g | |
| nan | 140212T165039Z | daniero | |
| nan | 140212T171132Z | George R | |
| nan | 140212T141056Z | manatwor | |
| nan | 140212T165253Z | p.s.w.g | |
| nan | 140212T163013Z | swish | |
| nan | 140212T154800Z | user2846 | |
| nan | 140212T161726Z | Einacio | |
| nan | 140212T161540Z | dirkk | |
| nan | 140212T160609Z | Ricardo | |
| nan | 140212T160225Z | user2846 | |
| nan | 140212T145828Z | TheConst | |
| nan | 140212T152155Z | JoshWill | |
| nan | 140212T143137Z | ecatmur | |
| nan | 140212T133438Z | Tom Tann | |
| nan | 140212T130115Z | shiona | |
| nan | 140212T124659Z | histocra | |
| nan | 140212T122016Z | Florent | |
| nan | 140212T114319Z | Michael | |
| nan | 140212T113723Z | mniip | |
| nan | 140212T113525Z | Gareth |
TinyAPL
⎕P"Line 1"⊣
⎕P"Line 2"⊣
⎕P"Line 3"⊣
⎕P"Line 4"
This might've won if this were a code golf competition :P
(Single newlines are treated as whitespace and ignored, code runs right-to-left)
C (clang), With Apple's Blocks extension
#import<stdlib.h>
#import<stdio.h>
int main(){
atexit_b(^(){puts("Line 1");});
atexit_b(^(){puts("Line 2");});
atexit_b(^(){puts("Line 3");});
atexit_b(^(){puts("Line 4");});
}
C (gcc), without Blocks extension
main(){
atexit("j\1Xj\7Zj\1_\xe8\7\0\0\0Line 1\n^\xf\5Ã");
atexit("j\1Xj\7Zj\1_\xe8\7\0\0\0Line 2\n^\xf\5Ã");
atexit("j\1Xj\7Zj\1_\xe8\7\0\0\0Line 3\n^\xf\5Ã");
atexit("j\1Xj\7Zj\1_\xe8\7\0\0\0Line 4\n^\xf\5Ã");
}
"j\1Xj\7Zj\1_\xe8\7\0\0\0foo bar^\xf\5Ã" is a string literal containing x86_64 machine language for write(1,"foo bar",7);.
C++ (gcc)
#import<iostream>
main(){
atexit([](){std::cout<<"Line 1\n";});
atexit([](){std::cout<<"Line 2\n";});
atexit([](){std::cout<<"Line 3\n";});
atexit([](){std::cout<<"Line 4\n";});
}
C++ (gcc)
Abusing Right-to-Left interpretation order of parameters
#include <iostream>
using namespace std;
void dummy_function(ostream &, ostream &, ostream &, ostream &)
{
}
int main()
{
dummy_function(
cout<<"Line 1"<<endl,
cout<<"Line 2"<<endl,
cout<<"Line 3"<<endl,
cout<<"Line 4"<<endl
);
}
Tcl
lmap x [lreverse {
{puts "line 1"}
{puts "line 2"}
{puts "line 3"}
{puts "line 4"}
}] {eval $x}
SmileBASIC
WHILE 1
WHILE B
WHILE C
WHILE D
PRINT "Line1"
END
WEND
PRINT "Line2"
D=1
WEND
PRINT "Line3"
C=1
WEND
PRINT "Line4"
B=1
WEND
R
Despite the fact that this contest ended some time ago, I would like to leave an answer in my favourite language for the sake of completeness. Also, this has been discussed on Meta that reanimating old question is not bad and sometimes encouraged.
sink("a.txt")
cat("Line1\n")
cat("Line2\n")
cat("Line3\n")
cat("Line4\n")
sink()
cat(rev(readLines("a.txt")), sep="\n")
This programme writes four lines to an external file, then imports it as a vector of strings and prints them out in reverse order.
C++
Based on my own C++ answer, but next level: no functors and no lambdas! Just function pointers!
#include <iostream>
#include <stack>
using namespace std;
void f1() {cout<<"Line 1"<<endl;}
void f2() {cout<<"Line 2"<<endl;}
void f3() {cout<<"Line 3"<<endl;}
void f4() {cout<<"Line 4"<<endl;}
int main()
{
stack<void(*)()> instructions;
instructions.push(f1);
instructions.push(f2);
instructions.push(f3);
instructions.push(f4);
while(!instructions.empty())
{
instructions.top()();
instructions.pop();
}
}
Tcl/Tk
pack [label .l1 -text "Line 1"] -side bottom
pack [label .l2 -text "Line 2"] -side bottom
pack [label .l3 -text "Line 3"] -side bottom
pack [label .l4 -text "Line 4"] -side bottom
C++
I can't believe there was not still a std::stack based solution!
#include <iostream>
#include <stack>
#include <functional>
using namespace std;
int main()
{
stack<function<void()>> instructions;
instructions.push([](){cout<<"Line 1"<<endl;});
instructions.push([](){cout<<"Line 2"<<endl;});
instructions.push([](){cout<<"Line 3"<<endl;});
instructions.push([](){cout<<"Line 4"<<endl;});
while(!instructions.empty())
{
instructions.top()();
instructions.pop();
}
}
C#
Simply using a Stack of type Action to store lambdas that execute Console.WriteLine. As the nature of a stack dictates the last "pushed" Action will be "popped" first.
static void Main(string[] args)
{
var s = new Stack<Action>();
s.Push(() => { Console.WriteLine("Line1"); });
s.Push(() => { Console.WriteLine("Line2"); });
s.Push(() => { Console.WriteLine("Line3"); });
s.Push(() => { Console.WriteLine("Line4"); });
while (s.Count > 0)
{
s.Pop().Invoke();
}
Console.Read();
}
Java
Idea borrowed from this answer. Reverses the values used by the Integer class.
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.Collections;
public class Print4
{
public static void main(String[] args) throws Exception {
Class cache = Integer.class.getDeclaredClasses()[0];
Field c = cache.getDeclaredField("cache");
c.setAccessible(true);
Integer[] array = (Integer[]) c.get(cache);
Collections.reverse(Arrays.asList(array).subList(129, 133));
System.out.printf("Line %d \n", 1);
System.out.printf("Line %d \n", 2);
System.out.printf("Line %d \n", 3);
System.out.printf("Line %d \n", 4);
}
}
RProgN
1 print
2 print
3 print
4 print
Output
4
3
2
1
Print doesn't actually exist in RProgN, it's actually titled just 'p'. This just appends 1 through 4 to the stack, then RProgN implicitly prints the stack from top to bottom, which gives the desired result.
DC
File rev3.dc:
[[line 1]PAP]
[[line 2]PAP]
[[line 3]PAP]
[[line 4]PAP]
xxxx
This pushes the print actions on the stack and executes them by x (== pop and execute).
Run:
$ dc -f rev3.dc
line 4
line 3
line 2
line 1
Factor
[ print "line1"
print "line2"
print "line3"
print "line4" ]
reverse call
Similar to the Common Lisp, Rebol, and Bash+tac answers, actually reverses the code before executing it.
Code-is-data + RPN = Most direct solution... even too trivial to be interesting maybe?
ES6 (using backwards mode ;)
Wow, it looks like the designers of ECMAScript had some incredible foresight when they made backwards mode part of the spec:
// activate backwards mode:
'use backwardsˈ; \* mode backwards in now *\
code of lines some ⧵\
\*code*\ "Line1" print \*code*\
\*code*\ "Line2" print \*code*\
\*code*\ "Line3" print \*code*\
\*code*\ "Line4" print \*code*\
code of lines some ⧵\
⁏ˈforwards useˈ // back to ˈnormal'.
// So simple! No need to do anything this complicated:
split('"').reduce((L,o,l)=>(l%2?o:'')+L,'')
Output (evaluation, really):
"Line4Line3Line2Line1"
Note that it's exactly of the form requested, with only slight backwardification to fit the syntax of the mode. Note also that this mode is only supported in recent versions of Firefox at the moment.
Final note: Actually, there is no backwards mode. But this is still a valid script that runs in Firefox (copy the whole thing). :D
ES6 "lax mode"
BONUS: Here's an updated version that doesn't use backwards mode, but uses the newly-specified "lax mode" where the JS engine will just try to guess what the code is supposed to do, regardless of adherence to any specified JS syntax (basically the antithesis of strict mode):
// activate "lax" mode:
`use laxˋ; // also works: ˋuse relaxˋ, ˋuse guessingˋ, ˋuse whatevsˋ, etc.
//some lines of code
/*code*/ print "Line1" /*code*/
/*code*/ print "Line2" /*code*/
/*code*/ print "Line3" /*code*/
/*code*/ print "Line4" /*code*/
//some lines of code
ˋuse normalˋ; // same as ˋuse default`.
// Again, compare to inferior, illegible "traditional" ES6:
split('"').reduce((L,o,l)=>(l%2?o:'')+L,'')
Please note that "lax mode" is currently only available in Firefox >= 34. ;P
BF
Assumes cell-wrapping.
++++[->+
----[> (line 1) .[-]<]++++
---[> (line 2) .[-]<]+++
--[> (line 3) .[-]<]++
-[> (line 4) .[-]<]+
<]
Why it works
The first and last lines compose of a loop that repeats four times (counter = cell0).
Inside the loop, there is a counter variable (cell1) that is increased every run.
Each lines checks if decreasing by four, three, two, or one equals zero. Therefore, on the first run, the counter is one and the last line is executed, on the second run, the third line is executed, etc.
The (line 1) shows where you should make the text that is printed. The arrows in the loops allocate cell2 for this purpose. The [-] cleans out cell2 after you use it.
Rebol
do sort/skip/reverse/compare [
print "Line1"
print "Line2"
print "Line3"
print "Line4"
] 2 2
and
cmd: [
[print "Line1"]
[print "Line2"]
[print "Line3"]
[print "Line4"]
]
for i 4 1 -1 [do cmd/:i]
one more
until [
do cmd: skip tail [
print "Line1"
print "Line2"
print "Line3"
print "Line4"
] -2
empty? head clear cmd
]
Rebol allows so many variations on that
do reverse [
""
print "Line1"
print "Line2"
print "Line3"
print "Line4"
print
]
.
print also "line 1" print also "line 2" print also "line 3" print "line 4"
Bash
In memory of the revered SleepSort and SleepAdd, I present to you... SleepReverse:
#!/bin/bash
function print(){(sleep $((4-$1));echo "Line $1";)&}
print 1
print 2
print 3
print 4
COBOL
The original of this I wrote some 30 years ago, so if the prize was for the oldest living, if brought-back-to-life, example of such a task... I re-wrote it about three years ago. After I had posted parts of it, parts appeared on some French web-site. This is the original and full working program, which I have posted some time last year on a LinkedIn group.
It still "works" today, and would have "worked" with the first COBOL compilers. GNU Cobol is readily available (SourgeForge) for anyone who would like to test the program...
The reason for writing it is mentioned in comments. Explanation follows the code. Enjoy :-)
ID DIVISION.
PROGRAM-ID. DEEPDOO.
*REMARKS. THE PURPOSE OF THIS PROGRAM IS TO SHOW THAT, FAR
* FROM "THAT CAN'T BE THE PROBLEM, COBOL DOESN'T DO
* THAT", IT IS, AND IT DOES.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 A1-FG PIC X VALUE SPACE.
01 B1-FG PIC X VALUE SPACE.
01 C1-FG PIC X VALUE SPACE.
PROCEDURE DIVISION.
OBLIGATORY-SECTION SECTION.
OB-PARA.
PERFORM A
IF A1-FG EQUAL TO "Y"
DISPLAY "DO"
GO TO G6
END-IF
.
G1.
PERFORM B
IF B1-FG EQUAL TO "Y"
DISPLAY "DOO"
GO TO G5
END-IF
.
G2.
PERFORM C
IF C1-FG EQUAL TO "Y"
DISPLAY "IN DEEP"
GO TO G4
END-IF
.
G3.
GO TO C5
.
G4.
GO TO B5
.
G5.
GO TO A5
.
G6.
MOVE +11 TO RETURN-CODE
GOBACK
.
A SECTION.
A0-PARA.
GO TO G1
.
A5.
MOVE "Y" TO A1-FG
.
A9.
EXIT.
B SECTION.
B0-PARA.
GO TO G2
.
B5.
MOVE "Y" TO B1-FG
.
B9.
EXIT.
0A SECTION.
0-PARA.
DISPLAY "I WAS GOING ALONG QUIETLY AND NOW I'M"
.
C SECTION.
C0-PARA.
IF C1-FG NOT EQUAL TO "Y"
GO TO G3
ELSE
GO TO C9
END-IF
.
C5.
MOVE "Y" TO C1-FG
GO TO 0-PARA
.
C9.
EXIT.
Z-OBFUSCATION SECTION.
Z-OB.
DISPLAY "IT DOESN'T GET HERE, NOT IN A MILLION YEARS"
STOP RUN.
There, wasn't so bad, was it?
Output is:
I WAS GOING ALONG QUIETLY AND NOW I'M
IN DEEP
DOO
DO
Which is just a different way of spelling
Line4
Line3
Line2
Line1
When COBOL was designed, it was done such that a label (a paragraph or a SECTION) could be the target of a PERFORM or a GO TO or just "fallen into" sequentially, and even, though not explicitly stated, any combination for the same label.
The problem arises when the same label is already under the scope of a PERFORM, a GO TO (accidentally) comes out of the range of the PERFORM (leaving it still "active") and control later arrives at the same label. If progress is then smoothly to the end of the scope of the original PERFORM, then control will be returned to the statement after the original PERFORM, no matter what else has happened since (as long as an infinite loop has not been created).
Very, very, bad practice to knowingly make use of that. Very. Can't stress that enough. Very, very, bad.
However, carelessness in whirling chunks of code about in an editor can cause this unintentionally. It can also be deliberately coded, without realising the consequences (example on SO recently, but without causing this type of problem).
However, when it does happen, the consequences evident seem so unlikely that people do not believe it. Parts of a program appear to, and actually do, run out of their expected sequence.
Of course, the "expected sequence" is just wrong, not the actual sequence, until you know what to expect, and then everything is OK (except the program doesn't work).
After two people came to me within a week with this type of problem, and didn't believe what I told them (although that bit of their code worked after my pointing out the errant GO TOs) I wrote the program to show these and any future Doubting Thomases.
For fun I compiled it using GNU COBOL with the -debug switch, which lists each verb and label as they are encountered. Here is the output:
Program-Id: DEEPDOO Statement: PERFORM Line: 15
Program-Id: DEEPDOO Section: A Line: 48
Program-Id: DEEPDOO Paragraph: A0-PARA Line: 49
Program-Id: DEEPDOO Statement: GO TO Line: 50
Program-Id: DEEPDOO Paragraph: G1 Line: 21
Program-Id: DEEPDOO Statement: PERFORM Line: 22
Program-Id: DEEPDOO Section: B Line: 57
Program-Id: DEEPDOO Paragraph: B0-PARA Line: 58
Program-Id: DEEPDOO Statement: GO TO Line: 59
Program-Id: DEEPDOO Paragraph: G2 Line: 28
Program-Id: DEEPDOO Statement: PERFORM Line: 29
Program-Id: DEEPDOO Section: C Line: 70
Program-Id: DEEPDOO Paragraph: C0-PARA Line: 71
Program-Id: DEEPDOO Statement: IF Line: 72
Program-Id: DEEPDOO Statement: GO TO Line: 73
Program-Id: DEEPDOO Paragraph: G3 Line: 35
Program-Id: DEEPDOO Statement: GO TO Line: 36
Program-Id: DEEPDOO Paragraph: C5 Line: 78
Program-Id: DEEPDOO Statement: MOVE Line: 79
Program-Id: DEEPDOO Statement: GO TO Line: 80
Program-Id: DEEPDOO Paragraph: 0-PARA Line: 67
Program-Id: DEEPDOO Statement: DISPLAY Line: 68
I WAS GOING ALONG QUIETLY AND NOW I'M
Program-Id: DEEPDOO Section: C Line: 70
Program-Id: DEEPDOO Paragraph: C0-PARA Line: 71
Program-Id: DEEPDOO Statement: IF Line: 72
Program-Id: DEEPDOO Statement: GO TO Line: 75
Program-Id: DEEPDOO Paragraph: C9 Line: 82
Program-Id: DEEPDOO Statement: EXIT Line: 83
Program-Id: DEEPDOO Statement: IF Line: 30
Program-Id: DEEPDOO Statement: DISPLAY Line: 31
IN DEEP
Program-Id: DEEPDOO Statement: GO TO Line: 32
Program-Id: DEEPDOO Paragraph: G4 Line: 38
Program-Id: DEEPDOO Statement: GO TO Line: 39
Program-Id: DEEPDOO Paragraph: B5 Line: 61
Program-Id: DEEPDOO Statement: MOVE Line: 62
Program-Id: DEEPDOO Paragraph: B9 Line: 64
Program-Id: DEEPDOO Statement: EXIT Line: 65
Program-Id: DEEPDOO Statement: IF Line: 23
Program-Id: DEEPDOO Statement: DISPLAY Line: 24
DOO
Program-Id: DEEPDOO Statement: GO TO Line: 25
Program-Id: DEEPDOO Paragraph: G5 Line: 41
Program-Id: DEEPDOO Statement: GO TO Line: 42
Program-Id: DEEPDOO Paragraph: A5 Line: 52
Program-Id: DEEPDOO Statement: MOVE Line: 53
Program-Id: DEEPDOO Paragraph: A9 Line: 55
Program-Id: DEEPDOO Statement: EXIT Line: 56
Program-Id: DEEPDOO Statement: IF Line: 16
Program-Id: DEEPDOO Statement: DISPLAY Line: 17
DO
Program-Id: DEEPDOO Statement: GO TO Line: 18
Program-Id: DEEPDOO Paragraph: G6 Line: 44
Program-Id: DEEPDOO Statement: MOVE Line: 45
Program-Id: DEEPDOO Statement: GOBACK Line: 46
Program-Id: DEEPDOO Exit: DEEPDOO
Line: 80 is what causes the unwinding of the PERFORMs to start, as control will "fall through" from the target of that GO TO into the following SECTION.
This mimics the situation where a SECTION in the program has been copied, modified, but the "GO TO the named paragraph which happens to be the end of the PERFORM range has not been changed - so it GO TOs the end of the wrong SECTION, and "falls through" into the next SECTION and continues falling until it stumbles across a PERFORM-range which is still active, or it gets into a Big Fat Loop or the end of the program is reached.
There are COBOL programmers who feel it is OK to use GO TO to get to the last paragraph of a PERFORM-range (I'm not one). If doing this, and using SECTIONs, it is best to name the final paragraph in each SECTION identically. The compiler will then automatically "qualify" that paragraph-reference in the GO TO to being the one in the current SECTION.
Javascript
Sort of a translation of Gareth's Perl answer
setTimeout(function(){alert("Line1")},200);
setTimeout(function(){alert("Line2")},140);
setTimeout(function(){alert("Line3")},80);
setTimeout(function(){alert("Line4")},20);
Thue
00::=~Line1 11::=~Line2 22::=~Line3 33::=~Line4 ::= 01233210
Python 2 and 3
Reverses the order of statements using abstract syntax tree manipulation.
a = __import__('ast').parse(open(__file__).read())
a.body = list(reversed(a.body[4:]))
exec(compile(a, '', 'exec'))
exit()
print("Line 1")
print("Line 2")
print("Line 3")
print("Line 4")
Smalltalk
#("
/*code*/ print "Line1" /*code*/
/*code*/ print "Line2" /*code*/
/*code*/ print "Line3" /*code*/
/*code*/ print "Line4" /*code*/
") reverse do: [:s| Transcript cr; show: s].
It's mostly the same as the other smalltalk answer, but inspired in the common lisp literal one.
C++
#include <iostream>
#include <cstring>
#include <vector>
#include <conio.h>
std::vector <char *> *lines = new std::vector <char *>();
void print(char *text)
{
lines->push_back(text);
}
class Dummy
{
public:
~Dummy()
{
for(int i = lines->size() - 1; i >= 0; --i)
{
std::cout << lines->at(i) << std::endl;
}
}
};
void PrintLines()
{
Dummy d;
print("Line 1");
print("Line 2");
print("Line 3");
print("Line 4");
}
int main(int argc, char* argv[])
{
PrintLines();
_getch();
return 0;
}
A bad technique, still it works.
Batch
@echo off
cls
goto d
:a
echo 'line1' & goto e
:b
echo 'line2' & goto a
:c
echo 'line3' & goto b
:d
echo 'line4' & goto c
:e
pause>nul
Quite frankly the best I could do...
SHELL
_rp() {
eval "printf '%s\\n' \
\"\${$(seq -s'}" "${' $# -1 1)}\""
}
Hand that a list of shell arguments and it will print them back at you in reverse. It works by evaluating the output of GNU's sequence into a shell quoted list of positional parameters.
DEMO
set -vx
_rp one two three
###OUTPUT
+ _rp one two three
seq -s'}" "${' $# -1 1
++ seq '-s}" "${' 3 -1 1
+ eval 'printf '\''%s\n'\'' "${3}" "${2}" "${1}"'
printf '%s\n' "${3}" "${2}" "${1}"
++ printf '%s\n' three two one
three
two
one
From that point on you can just define IFS as necessary when invoking it in order to split among the arguments as you please.
JavaScript
eval(
'console.log("Line1"); \
console.log("Line2"); \
console.log("Line3"); \
console.log("Line4"); '
.split(";").reverse().join(";"))
Python 2
import inspect
def main():
print "Line 1"
print "Line 2"
print "Line 3"
print "Line 4"
for line in inspect.getsourcelines(main)[0][:0:-1]:
exec(line.strip())
F#
""
|> sprintf "Line1 %s"
|> sprintf "Line2 %s"
|> sprintf "Line3 %s"
|> sprintf "Line4 %s"
|> printfn "%s"
Clojure
Using clojure macro.
(defmacro do-reverse [& v]
`(do
~@(reverse v)))
(do-reverse
(println "Line 1")
(println "Line 2")
(println "Line 3")
(println "Line 4"))
Objective-C
#define NSLog(a) NSLog( [self changeNumber:(NSString*)a])
...
NSLog(@"Line1");
NSLog(@"Line2");
NSLog(@"Line3");
NSLog(@"Line4");
...
- (NSString *)changeNumber:(NSString *)string
{
int number = [string substringFromIndex:string.length-1].intValue;
int newnumber = -number + 5;
NSString *newString = [string stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"%d", number] withString:[NSString stringWithFormat:@"%d", newnumber]];
return newString;
}
output_list = []
class newstdout():
def write(self, s):
output_list.append(s)
stdout, sys.stdout = sys.stdout, newstdout()
print("Line 1")
print("Line 2")
print("Line 3")
sys.stdout = stdout
_ = [print(s, end='') for s in output_list[::-1]]
Java
This is another, but different System.out abuse:
public class PrintBackwards {
public static void main(String[] args) {
System.out.println("Line1");
System.out.println("Line2");
System.out.println("Line3");
System.out.println("Line4");
}
public static class System {
public static class out {
public static void println(String val) {
Print.println(val);
}
}
}
}
class Print {
private static java.util.Stack<String> s = new java.util.Stack<>();
public static void println(String val) {
s.push(val);
if (s.size() >= 4) {
while (!s.isEmpty()) {
System.out.println(s.pop());
}
}
}
}
The best thing about it: the main method is unchanged.
Java
This is an alternative to the System.out abuse in the other submission, by abusing the PrintStream instead (the out).
class MyPrintStream extends PrintStream {
String t = "";
public MyPrintStream() {
super(System.out);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
MyPrintStream.super.println(t);
}
});
}
public void println(String s) {
t = s + "\n" + t;
}
}
public class Temp {
static {
System.setOut(new MyPrintStream());
}
public static void main(String[] args) throws InterruptedException {
System.out.println("Line 1");
System.out.println("Line 2");
System.out.println("Line 3");
System.out.println("Line 4");
}
}
Javascript
eval(
"console.log('line1');"+
"console.log('line2');"+
"console.log('line3');"+
"console.log('line4')"
.split(";").reverse().join(";"));
The very lazy C# method:
using System;
using System.Collections.Generic;
namespace P
{
static class P
{
static void Main()
{
Stack<Action> s = new Stack<Action>();
s.Push(() => Console.WriteLine("Line1"));
s.Push(() => Console.WriteLine("Line2"));
s.Push(() => Console.WriteLine("Line3"));
s.Push(() => Console.WriteLine("Line4"));
foreach (var a in s) a();
Console.ReadKey();
}
}
}
And a version with using aliases (not sure if it's shorter or not, cba to count)
using C = System.Console;
using SA = System.Collections.Generic.Stack<System.Action>;
namespace P
{
static class P
{
static void Main()
{
SA s = new SA();
s.Push(() => C.WriteLine("Line1"));
s.Push(() => C.WriteLine("Line2"));
s.Push(() => C.WriteLine("Line3"));
s.Push(() => C.WriteLine("Line4"));
foreach (var a in s) a();
C.ReadKey();
}
}
}
Isn't it nice when code writes itself?
Pseudo Code (will probably work in most languages with minor tweaks)
void printLine1() { print "Line 1"; }
void printLine2() { print "Line 2"; }
void printLine3() { print "Line 3"; }
void printLine4() { print "Line 4"; }
main
{
printLine4();
printLine3();
printLine2();
printLine1();
}
Kinda lame, but I think it works. C-like languages.
main()
{
switch(4)
{
case 1: print(1); goto 5; break;
case 2: print(2); goto 1; break;
case 3: print(3); goto 2; break;
case 4: print(4); goto 3; break;
case 5: break;
}
}
Java 8
Abusing lambdas
import java.util.function.Function;
public class Backwards {
public static void main(String[] args) {
reverse(
print -> "Line 1",
print -> "Line 2",
print -> "Line 3",
print -> "Line 4"
);
}
@SafeVarargs
public static void reverse(Function<Integer, String>... funcs) {
for (int i = funcs.length; i --> 0; ) {
System.out.println(funcs[i].apply(0));
}
}
}
Note the artful use of the "goes to" operator.
Scala
object Backwards {
def print(msg: String): String = msg
def main(args: Array[String]) {
(
print("Line 1") ::
print("Line 2") ::
print("Line 3") ::
print("Line 4") ::
List()).reverse.foreach(println)
}
}
Python
import sys
class revout():
def __init__(self):
self.out = sys.stdout
self.buffer = ""
def write(self,a):
self.buffer += a
def unclog(self):
self.out.write("\n".join(self.buffer.split("\n")[::-1]))
sys.stdout = revout()
print "Line 1"
print "Line 2"
print "Line 3"
print "Line 4",
sys.stdout.unclog()
C
Undefined behavior is the most exciting kind of behavior!
f(){}
main()
{
f(printf("Line 1\n"),
printf("Line 2\n"),
printf("Line 3\n"),
printf("Line 4\n"));
}
Actual output may vary depending on your compiler, linker, operating system, and processor :)
Scala
implicit class Abuse(string: String) {
def print(o: String) = o + string
def print = println(string)
}
"Line1" print
"Line2" print
"Line3" print
"Line4" print
Note the abusive use of semicolon insertion, and postfix operators, and the (almost legitimate) use of implicits.
Python 2.7
The great thing about dynamic languages is that you can override anything. Also, finalizers are the future.
import sys
class StdOut(object):
text = ""
def __init__(self):
self.stdout = sys.stdout
def write(self, text):
self.text = text + self.text
def __del__(self):
self.stdout.write(self.text)
sys.stdout = StdOut()
print "Line1"
print "Line2"
print "Line3"
print "Line4"
Note that we haven't overridden print - we're using the stock print function that comes with Python.
Ruby (abusing eval)
eval(File.readlines(__FILE__).reverse.join "\n")
exit
puts "Line 1"
puts "Line 2"
puts "Line 3"
puts "Line 4"
Python 3
Redefining print
import sys
old_print = print
strings = []
def print(thing):
strings.append(thing)
if thing == "Line 4":
for thing in reversed(strings):
old_print(thing)
print("Line 1")
print("Line 2")
print("Line 3")
print("Line 4")
Plain ol' Simple JavaScript
No loops, no arrays, no reversals, no string manipulation, no new function definitions, just plain ol' JS console.log():
console.log("Line1",
console.log("Line2",
console.log("Line3",
console.log("Line4"
)||'')||'')||'')
(Partially inspired by bwoebi's (oft-adapted) PHP entry.)
A slightly more interesting/specific variant:
console.log("Line1".valueOf(
console.log("Line2".valueOf(
console.log("Line3".valueOf(
console.log("Line4"
)))))))
The trick here is not just precedence, but also the fact that valueOf is a function that takes no arguments, and thus acts as an identity function. Unlike other precedence-based solutions, there's no need to rely on type coercion for empty-string concatenation or boolean logic. Just plain damn, built-in JS. :]
Coldfusion
anything not in a coldfusion tag is written to the output webpage, Coldfusion also lets you treat pretty much any string as a list and loop over a list in an output tag where things in #'s are evaluated
<cfsavecontent variable="output">
Line 1
Line 2
Line 3
Line 4
</cfsavecontent>
<cfset output = ListSort(output,'text','desc',chr(13))>
<cfloop index="i" list="#output#" delimiters="#chr(13)#">
<cfoutput>#i#</cfoutput>
</cfloop>
C#
Switching the console output to a MemoryStream and modifying that before dumping to screen
void Main()
{
var stream = new MemoryStream();
using (var writer = new StreamWriter(stream))
{
var defaultOut = Console.Out;
// change the console output to the in-memory writer
Console.SetOut(writer);
Console.WriteLine("line1");
Console.WriteLine("line2");
Console.WriteLine("line3");
Console.WriteLine("line4");
// reset the console output to the default
Console.SetOut(defaultOut);
}
// write the contents of the MemoryStream to screen whilst tweaking the output
Console.Write(stream.ToArray().Select(SwitchChar).ToArray());
}
public char SwitchChar(byte b)
{
var c = (char)b;
switch (c)
{
case '1': return '4';
case '2': return '3';
case '3': return '2';
case '4': return '1';
default: return c;
}
}
Haskell
(<<)=flip(>>)
main=putStrLn "Line1" <<
putStrLn "Line2" <<
putStrLn "Line3" <<
putStrLn "Line4"
Python 2
Using the much maligned inline if-else
from sys import stdout
stdout.write('Line 1\n') if (stdout.write('Line 2\n') if (stdout.write('Line 3\n') if stdout.write('Line 4\n') or 1 else 0) or 1 else 0) or 1 else 0
HTML + CSS
<p>Line 1</p>
<p>Line 2</p>
<p>Line 3</p>
<p>Line 4</p>
CSS:
body {margin-top:7em}
p + p {margin-top:-4em}
See jsFiddle.
Edit:
To conform to the rules better, here is a variant in XML, that actually uses print.
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet href="style.css"?>
<root>
<print>Line 1</print>
<print>Line 2</print>
<print>Line 3</print>
<print>Line 4</print>
</root>
where style.css should be
* {display:block; margin-top:3em}
print + print {margin-top:-3em}
HTML without CSS
And for the heck of it, here's one without CSS.
<table>
<tfoot><tr><td><table><tfoot><tr><td>Line 1</tr></tfoot>
<tbody><tr><td> Line 2</table></tfoot>
<tbody><tr><td><table><tfoot><tr><td>Line 3</tr></tfoot>
<tbody><tr><td> Line 4</table></tbody>
</table>
Shell again
cat <<XXX | sort -r | sh -
echo Line 1
echo Line 2
echo Line 3
echo Line 4
XXX
Perl 6
END say 'Line1';
END say 'Line2';
END say 'Line3';
END say 'Line4';
There's a lot more phasers where END came from :)
Python 3
[a(b) for a,b in (
(print, "Line1"),
(print, "Line2"),
(print, "Line3"),
(print, "Line4"))[::-1]]
Which is sadly not compliant to the contest rules, due to four unfortunate commas, but I so love abusing comprehensions with side-effects.
JS/Node
(function() {
while (arguments.length > 0) {
eval([].pop.call(arguments));
}
}).apply(this, [
'console.log("Line1")',
'console.log("Line2")',
'console.log("Line3")',
'console.log("Line4")'
]);
Javascript
Monkeypatching for the win!
var oldAlert = alert;
var buf = [];
alert = function(v)
{
if(v != undefined)
buf.push(v);
else
{
while(buf.length > 0)
oldAlert(buf.pop());
}
}
alert("line 1");
alert("line 2");
alert("line 3");
alert("line 4");
alert();
F#
(Ab)using custom keywords in a computation expression.
type Reverse = Reverse with
[<CustomOperation "print">]
member this.Print(l, x) = x :: l
member this.Yield(_) = []
member this.Run(l) = List.iter (printfn "%s") l
Reverse {
print "Line1"
print "Line2"
print "Line3"
print "Line4"
}
Coffeescript
revision 2: not as coffeescriptic but smaller
do(c=console)->c.log "Line1" if!c
.log "Line2" if!c
.log "Line3" if!c
.log "Line4"
revision 1:
do(c=console)->c.log "Line1" unless c
.log "Line2" unless c
.log "Line3" unless c
.log "Line4"
Single line variant:
do(c=console)->c.log "Line1" unless c.log "Line2" unless c.log "Line3" unless c.log "Line4"
Powershell
"line1`n" `
-replace "^","line2`n" `
-replace "^","line3`n" `
-replace "^","line4`n"
I'm not sure if line continuation chars are cheating or not, but they've not been explicity banned ;-)
Alternatively without line continuation:
("line1",
"line2",
"line3",
"line4")[3..0]
JavaScript
console.log("Line 1",
(console.log("Line 2",
(console.log("Line 3",
(console.log("Line 4"), "")), "")
), "")
)
C#
Kind of lame, just my two cents:
var printMeReverse = new List<Action> {
new Action(() => Console.WriteLine ("Line1")),
new Action(() => Console.WriteLine ("Line2")),
new Action(() => Console.WriteLine ("Line3")),
new Action(() => Console.WriteLine ("Line4"))
};
printMeReverse.Reverse();
printMeReverse.ForEach(a => a.Invoke());
Haskell
import Prelude (print, return, (>>=))
main = do
print "Line 1"
print "Line 2"
print "Line 3"
print "Line 4"
a>>b=b>>= \_->a
Run with
$ runhaskell -XRebindableSyntax reversed.hs
(Note that without the RebindableSyntax flag, it's still a valid Haskell program and will print in the normal order)
Standard Haskell98 alternative:
import Prelude hiding (print)
main = r$do
print "Line 1"
print "Line 2"
print "Line 3"
print "Line 4"
data R a=R{r::IO a}
instance Monad R where R a>>=b=R$r(b u)>>= \_->fmap u a;return=R .return
print=R .putStrLn
u::u;u=u
SQL
(mySQL 5.6)
SELECT 'Line1' UNION
SELECT 'Line2' UNION
SELECT 'Line3' UNION
SELECT 'Line4'
ORDER BY Line1 DESC;
If you count SELECTing a literal as equivalent to a print statement anyway.
mySQL defaults to including the column name and adding fancy table formatting, but if you're at the cli they can be turned off if you do something like:
mysql --skip-column-names -B -e "SELECT 'Line1' ... etc ...;"
Output:
Line4
Line3
Line2
Line1
Smalltalk (79/66/143 chars)
version 1 (79):
{
[ 'line1' print ].
[ 'line2' print ].
[ 'line3' print ].
[ 'line4' print ]
} reverse map:#value
little explanation:
[..] is a block (aka lambda closure);
{..} is an array constructor;
reverse and map are obvious;
#value evaluates a block closure.
output:
line4line3line2line1
version 2 (66):
Here is a version using reflection; it fetches the string constants of the block and prints them:
Given any block containing string-prints:
b := [
'line1' print.
'line2' print.
'line3' print.
'line4' print
].
where 'normal' evaluation with:
b value.
gives: line1line2line3line4l
The following extracts the string literals and prints them reverse:
(b method literals select:[:l|l class==String]) reverse map:#print
gives: line4line3line2line1
the code is a little unsafe (it requires that the block's containing method does not contain other string literals; but we are playing golf - not trusted software development ;-)
version 3 (143)
defines a 'function' which redirects stdout to some internal stream, evaluates a block closure and finally prints the collected output in reverse:
w := [:b | |sav red|
[
sav := Stdout.
Stdout := red := '' writeStream.
b value.
] ensure:[
Stdout := sav.
red contents asCollectionOfLines reverse map:#printNL
]
].
then we evaluate any code within that wrapper:
w value:[
'line1' printNL.
'line2' printNL.
'line3' printNL.
'line4' printNL
]
its not thread save, though.
(all character counts are w.o omittable whitespace)
Python 2.7 (may work down to 2.4)
Tested with CPython 2.7.5 and PyPy 2.0.2
def inv(fn):
import types
t=fn.__code__
c=list(t.co_code)
idxs=[i+1 for i,j in enumerate(c) if j=='d' and c[i+1]!='\0']
for i in range(len(idxs)/2):
c[idxs[i]], c[idxs[-i-1]] = c[idxs[-i-1]], c[idxs[i]]
outcode=types.CodeType( t.co_argcount, t.co_nlocals, t.co_stacksize, t.co_flags, ''.join(c), t.co_consts, t.co_names, t.co_varnames, t.co_filename, t.co_name, t.co_firstlineno, t.co_lnotab)
return types.FunctionType(outcode, globals(), fn.__name__[::-1])
@inv
def f():
print 'Line1'
print 'Line2'
print 'Line3'
print 'Line4'
f()
A somewhat more secure approach requires changing the inv function to something like this:
def inv(fn):
import types
import dis
t=fn.__code__
c=list(t.co_code)
idxs=[]
i=0
n=len(c)
lc=dis.opmap['LOAD_CONST']
while i<n:
opcode=ord(c[i])
if opcode==lc and c[i+1]!='\0':
idxs+=[i+1]
i+=1
if opcode>=dis.HAVE_ARGUMENT:
i+=2
for i in range(len(idxs)/2):
c[idxs[i]], c[idxs[-i-1]] = c[idxs[-i-1]], c[idxs[i]]
outcode=types.CodeType( t.co_argcount, t.co_nlocals, t.co_stacksize, t.co_flags, ''.join(c), t.co_consts, t.co_names, t.co_varnames, t.co_filename, t.co_name, t.co_firstlineno, t.co_lnotab)
return types.FunctionType(outcode, globals(), fn.__name__[::-1])
#include <stdio.h>
#include <stdlib.h>
void line1() { printf("line1\n"); }
void line2() { printf("line2\n"); }
void line3() { printf("line3\n"); }
void line4() { printf("line4\n"); }
int main() {
atexit(line1);
atexit(line2);
atexit(line3);
atexit(line4);
}
JavaScript
function golf() {
/*
console.log("Line1");
console.log("Line2");
console.log("Line3");
console.log("Line4");
*/
/\/\*(.+)\*\//.exec(golf.toString().replace(/\n/g,""))[1].split("; ").reverse().forEach(function(e){eval(e)});
}
golf();
Explanation:
golf.toString().replace(/\n/g,"") returns the function's source on one line. The /\/\*(.+)\*\// regular expression matches the four console.log lines; it then separates them into an array, reverses the array, and uses forEach to eval each item in the array.
Edit: Removed the unnecessary var r =.
One more from the Bash command-line:
echo "Line1" "Line2" "Line3" "Line4" | { read a b c d; echo $d $c $b $a; }
Output:
Line4 Line3 Line2 Line1
Here is a version expanded to multiple lines to match the exact syntax of the spec:
echo "Line1" < \
echo "Line2" < \
echo "Line3" < \
echo "Line4" | { read a b c d; echo $d; echo $c; echo $b; echo $a; }
Bash
#!/bin/bash
eval `tac $0 | head -n 4` && exit
echo 'Line1' ;
echo 'Line2' ;
echo 'Line3' ;
echo 'Line4' ;
Output:
Line4
Line3
Line2
Line1
More fun with BASH arrays
#!/bin/bash
a=("echo Line1"
"echo Line2"
"echo Line3"
"echo Line4")
for (( i=${#a[@]}-1; i>=0; i-- )) ; do
eval ${a[i]}
done
Output:
Line4
Line3
Line2
Line1
Python 3
import sys
plist = []
cout = 0
def print(s):
global cout
plist.append(s+"\n")
cout += 1
if cout == 4:
for i in reversed(plist):
sys.stdout.write(i)
print("Line 1")
print("Line 2")
print("Line 3")
print("Line 4")
Output (escaped):
"Line4\nLine3\nLine2\nLine1\n"
Python 2.7
for l in """
print "Line1"
print "Line2"
print "Line3"
print "Line4"
""".splitlines()[::-1]:
exec(l)
you can see the result here: http://ideone.com/QypGiB
a[::-1] represents the reversed list a.
C#
Instead of directly calling the Run method, I'm creating a dynamic method that contains a copy of Run's IL bytecode, except that the load-string opcode operands are swapped. Which causes the new method to display the strings in reverse order.
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Reflection.Emit;
namespace TestApp
{
class Program
{
public static void Run()
{
Console.WriteLine("Line 1");
Console.WriteLine("Line 2");
Console.WriteLine("Line 3");
Console.WriteLine("Line 4");
}
static void Main(string[] args)
{
var method = typeof(Program).GetMethod("Run");
var il = method.GetMethodBody().GetILAsByteArray();
var loadStringOperands = new Stack<int>();
for (int i = 0; i < il.Length; i++)
{
if (il[i] == OpCodes.Ldstr.Value)
{
loadStringOperands.Push(BitConverter.ToInt32(il, i + 1));
i += 4;
}
}
var run = new DynamicMethod("Run", typeof(void), null);
var gen = run.GetILGenerator(il.Length);
for (int i = 0; i < il.Length; i++)
{
if (il[i] == OpCodes.Ldstr.Value)
{
var str = method.Module.ResolveString(loadStringOperands.Pop());
gen.Emit(OpCodes.Ldstr, str);
i += 4;
}
else if (il[i] == OpCodes.Call.Value)
{
var mInfo = method.Module.ResolveMethod(BitConverter.ToInt32(il, i + 1)) as MethodInfo;
gen.Emit(OpCodes.Call, mInfo);
i += 4;
}
else if (il[i] == OpCodes.Ret.Value)
{
gen.Emit(OpCodes.Ret);
}
}
run.Invoke(null, null);
}
}
}
Perl 5
use 5.010;
!say "Line 1",
!say "Line 2",
!say "Line 3",
!say "Line 4";
This works basically the same way as bwoebi's PHP answer: the return value of each of the say commands is given as an argument to the previous one, so the interpreter must evaluate them from last to first. The negation operator ! maps the return values from 1 to an empty string, keeping them from interfering with the output.
Python
there's my code :)
import sys
old_stdout = sys.stdout
sys.stdout = open('file.txt', 'w')
print 'Line 1'
print 'Line 2'
print 'Line 3'
print 'Line 4'
sys.stdout = old_stdout
a = open('file.txt','r').read().splitlines()
a.sort(reverse=True)
print '\n'.join(a)
Perl
eval ($_) for ( reverse split("\n", <<EOF
print "Line1";
print "Line2";
print "Line3";
print "Line4";
EOF
) );
Very simple perl-Example with eval...
PowerShell
( {Write-Host 'Line 1'},
{Write-Host 'Line 2'},
{Write-Host 'Line 3'},
{Write-Host 'Line 4'}
)[3..0]|ForEach-Object {Invoke-Command $_}
Coffeescript
This one is using coffeescript, by overriding the console.log function to skip the undefined second argument.
c = window.console
console =
log: () ->
c.log arguments[0]
c.log arguments[1] if arguments[1]
console.log "Line1",
console.log "Line2",
console.log "Line3",
console.log "Line4"
Bash
Here comes the double-faced script:
#!/bin/bash
s=1
if [ $s -ne 0 ]; then tac $0 | bash; exit; fi
s=0
echo "Line1"
echo "Line2"
echo "Line3"
echo "Line4"
Scala
object PrintRev extends App{
val rev : (=>Unit,=>Unit,=>Unit,=>Unit) => Unit = (v1,v2,v3,v4) => {v4;v3;v2;v1}
rev(println("Line1"),
println("Line2"),
println("Line3"),
println("Line4"))
}
Simple T-SQL Solution
The code here is not "organic" (not part of the raw code body), though, unlike my other batch solution.
set nocount on
declare @t table (stmt nvarchar(500))
declare @stmt nvarchar(500)
insert into @t values
('print ''Line1'''),
('print ''Line2'''),
('print ''Line3'''),
('print ''Line4''')
select top 1 @stmt = stmt from @t order by stmt desc
while @@rowcount > 0 begin
exec(@stmt)
delete from @t where stmt = @stmt
select top 1 @stmt = stmt from @t order by stmt desc
end
C++
#include <iostream>
#define print(s) std::cout << s << "\n"; return g; }
#define f []{ auto g =
int main() {
f f f f []{};
print ("Line 1");
print ("Line 2");
print ("Line 3");
print ("Line 4")
()()()()();
}
My version in batch - using "batch file reflection" ;)
This one actually supports up to 9 statements to be executed backwards (but can easily be expanded to support more), and they could be almost any kind of commands - not just print statements!
The only rules are that the statements which you want to run reversed must appear in the file between the "rem BEGIN_REV" and "rem END_REV" comments, and that the file name you run it as must end in .BAT (not .CMD!).
@echo off
setlocal enabledelayedexpansion
set ffrag=FILEFRAG%random%
call :run %0
goto :eof
rem BEGIN_REV
echo Line1
echo Line2
echo Line3
echo Line4
rem END_REV
:run
set me=%1
set me=%me:.bat=%.bat
set /a isOn=0
set /a incrCount=0
for /f "tokens=*" %%i in (%me%) do (
set ln=
set ln=%%i
if !isOn!==0 (
set d=
set d=!ln:begin_rev=!
if not !d!==!ln! (
rem Starting block
set /a isOn=1
)
) else (
rem Inside block
set /a incrCount=!incrCount!+1
echo !ln! > %ffrag%_!incrCount!.b
set d=
set d=!ln:END_REV=!
if not !d!==!ln! (
rem End of block reached
goto :endloop
)
)
)
:endloop
del %ffrag%_%incrCount%.b
for /f %%i in ('dir /s/b/O:-N %ffrag%*') do (
type %%i >> %ffrag%_FINAL.bat
)
del %ffrag%*.b
call %ffrag%_FINAL.bat
del %ffrag%_FINAL.bat
Output:
Line4
Line3
Line2
Line1
Python3
print('line1') if not (
print('line2') if not (
print('line3') if not
print('line4') else
0) else 0) else 0
Python3
def print(x,p=
print):p(x[:-1]+str(5-int(x[-1])))
print("line1")
print("line2")
print("line3")
print("line4")
C (and sort-of Python)
New version, using a macro to fit the question format perfectly.
Following Quincunx's comment, I added return to make it nicer.
It also works in Python, but it prints in correct order.
#define print"\n",printf(
#define return"\n"))));}
#define def main(){0?
def main():
print "Line 1"
print "Line 2"
print "Line 3"
print "Line 4"
return
main();
Original version - the two are practically the same, after macro substitution:
main(){
printf("Line 1\n",
printf("Line 2\n",
printf("Line 3\n",
printf("Line 4\n",
0))));
}
Bash
This one abusing bash process substitution and redirects:
< <(< <(< <(< <(
1>&2 echo "Line1")
1>&2 echo "Line2")
1>&2 echo "Line3")
1>&2 echo "Line4")
Bash and coreutils
Not very creative, I'm afraid, but gets the job done with the tac tool, which is built for this job:
{
echo "Line1"
echo "Line2"
echo "Line3"
echo "Line4"
} | tac
Couldnt resist abusing overloaded System.out :P
import java.io.PrintStream;
import java.util.ArrayList;
class A
{
public static void main(String[] arggxes)
{
CStream c = new CStream(System.out);
System.setOut(c);
System.out.println("Line 1");
System.out.println("Line 2");
System.out.println("Line 3");
System.out.println("Line 4");
c.done();
}
}
class CStream extends PrintStream
{
ArrayList<String> bfr;
public CStream(PrintStream ul)
{
super(ul);
bfr=new ArrayList<>();
}
@Override
public void println(String x)
{
bfr.add(x);
}
public void done()
{
for (int i = bfr.size(); i > 0; i--)
{
super.println(bfr.get(i-1));
}
}
}
variable string amount print() with string as return works, too :P; inspired by the printf c one and the rebol one
class pr
{
public static void main (String[] args)
{
print("Line1",
print("Line2",
print("Line3",
print("Line4"
))));
}
public static String print(String... in)
{
System.out.println(in[0]);
return "";
}
}
Rebol
use [p][p: :print print: func [s n [any-type!]][p s]]
print {Line1}
print {Line2}
print {Line3}
print {Line4}
Normally 'print only takes 1 argument, but we're redefining it to take 2 - the second of which is the next call to `print, which must be evaluated first to get a return value.
Except because it accepts [any-type!], the second argument is optional - hence not needing an extra arg for the last call.
Python
After a little setup, you can get reversed printing from nearly unaltered Python code. (You do need parens around your print arguments).
from __future__ import print_function
import atexit
stack=[]
def done():
stack.reverse()
for a,k in stack: __builtins__.print(*a,**k)
atexit.register(done)
def print(*args,**kwargs):
stack.append((args,kwargs))
#normal code from here down.
print('Line1')
print('Line2')
print('Line3')
print('Line4')
PHP
Abusing precedence... :-)
!print "Line1\n".
!print "Line2\n".
!print "Line3\n".
!print "Line4\n";
SQL
I felt a little left out no one tackled this with SQL.
declare @oldsql varchar(max)
declare @newSQL varchar(max)
declare @findvar varchar(7)
declare @replaceVar varchar(20)
declare @varLength int
declare @sqlLength int
set @findvar = '%print%'
set @varLength = len(@findvar) - 3
set @oldsql =
' print ''Line1''' +
' print ''Line2''' +
' print ''Line3''' +
' print ''Line4'''
set @sqlLength = len(@oldsql)
SET @newSQL = (
SELECT SUBSTRING(@oldsql
,@sqlLength - PATINDEX(reverse(@findvar)
,REVERSE(@oldsql)) - @varLength
,LEN(@oldsql)))
SET @replaceVar =
RIGHT(@oldsql
,PATINDEX(reverse(@findvar)
,REVERSE(@oldsql))+@varLength)
SET @oldSql =
RTRIM(REPLACE(@oldSQL
, REPLACE(@replaceVar,'','''')
,''))
SET @sqlLength = LEN(@oldsql)
SET @newSQL = @newSQL + (
SELECT SUBSTRING(@oldsql
,@sqlLength - PATINDEX(reverse(@findvar)
,REVERSE(@oldsql)) - @varLength
,LEN(@oldsql)))
SET @replaceVar =
RIGHT(@oldsql
,PATINDEX(reverse(@findvar)
,REVERSE(@oldsql))+@varLength)
SET @oldSql =
RTRIM(REPLACE(@oldSQL
, REPLACE(@replaceVar,'','''')
,''))
SET @sqlLength = LEN(@oldsql)
SET @newSQL = @newSQL + (
SELECT SUBSTRING(@oldsql
,@sqlLength - PATINDEX(reverse(@findvar)
,REVERSE(@oldsql)) - @varLength
,LEN(@oldsql)))
SET @replaceVar =
RIGHT(@oldsql
,PATINDEX(reverse(@findvar)
,REVERSE(@oldsql))+@varLength)
SET @oldSql =
RTRIM(REPLACE(@oldSQL
, REPLACE(@replaceVar,'','''')
,''))
SET @sqlLength = LEN(@oldsql)
SET @newSQL = @newSQL + (
SELECT SUBSTRING(@oldsql
,@sqlLength - PATINDEX(reverse(@findvar)
,REVERSE(@oldsql)) - @varLength
,LEN(@oldsql)))
exec (@newSQL)
C
Trying to make defiance of the tips in the question as creative as possible:
#include <stdio.h>
#define print if (i == __LINE__) puts
static unsigned i;
int main(void) {
while (--i) {
print("Line 1");
print("Line 2");
print("Line 3");
print("Line 4");
}
return 0;
}
main-while-loop and if switches (Python)
next = 4
while next:
if next == 1: print "Line1"
if next == 2: print "Line2"
if next == 3: print "Line3"
if next == 4: print "Line4"
next -= 1
Matlab: something different
s = {'print ' 'Line1'...
'print ' 'Line2'...
'print ' 'Line3'...
'print ' 'Line4'};
[s{end:-2:2}]
Obfuscation attempted
JavaScript
Kinda wanted to avoid using eval() or strings, so I gave each Line a separate function.
.reverse() makes it still too easy. :9
var cg = [
function() {console.log('Line one')},
function() {console.log('Line two')},
function() {console.log('Line three')},
function() {console.log('Line four')}
];
for(i in cg.reverse()) {cg[i]()}
Output:
Line four
Line three
Line two
Line one
Guess I could replace the loop with
for(i in cg) {cg[cg.length-++i]()}
to make it more interesting. Doesn't make it prettier, though.
OCaml
Since lists are created starting from the tail prepending elements in front of it, these print statements end up executing backwards.
[print_string "Line1";
print_string "Line2";
print_string "Line3";
print_string "Line4"]
output is
Line4Line3Line2Line1
(you can try it here)
Java
Using instance initializers:
class L1 {{new L2();System.out.println("Line 1");}}
class L2 {{new L3();System.out.println("Line 2");}}
class L3 {{new L4();System.out.println("Line 3");}}
class L4 {{System.out.println("Line 4");}}
public class S {
public static void main(String[] args) {
new L1();
}
}
Batch
echo off
call :revers ^
echo.line1 ^
echo.line2 ^
echo.line3 ^
echo.line4
:revers
if not "%2"=="" call :revers %2 %3 %4 %5 %6 %7 %8 %9
%1
q
Very easy in a language with "left-of-right" evaluation.
(show "Line1"),
(show "Line2"),
(show "Line3"),
show "Line4"
"Line4"
"Line3"
"Line2"
"Line1"
edit: formatted code to fit one print per line rule, though q ignores white space so I'm not sure this counts
Python 3
import atexit
atexit.register(print,"Line1")
atexit.register(print,"Line2")
atexit.register(print,"Line3")
atexit.register(print,"Line4")
Javascript 1.8
See Javascript 1.8 and browser support.
console.log([
'print "Line1"',
'print "Line2"',
'print "Line3"',
'print "Line4"'
].reduceRight(
function(p,s) p + s.match(/"(.*)"/)[1],
""
)
)
Rebol
do reverse [
(print "Line1")
(print "Line2")
(print "Line3")
(print "Line4")
]
An alternative option that doesn't use paren! blocks would be like this:
reverse2: func [
"Reverse series/block in groups of 2 elements (modifies & returns)"
s [block! series!]
][
forskip s 2 [insert s take/last/part s 2]
s
]
do reverse2 [
print "Line1"
print "Line2"
print "Line3"
print "Line4"
]
A little explanation
In Rebol, code is data and data is code...
four-lines: [
print "Line1"
print "Line2"
print "Line3"
print "Line4"
]
At this point four-lines is just a variable pointing to data. But we can assign it to a function like so:
print-4-lines: does four-lines
; or exactly same is
print-4-lines: func [] four-lines
Now the print-4-lines function will print the 4 lines as is. However if we do this...
print-4-lines: does reverse2 four-lines
then print-4-lines now prints in reverse order.
If you go into Rebol console (REPL) you will see that print-4-lines function code is reversed.
>> source print-4-lines
print-4-lines: make function! [[][
print "Line4"
print "Line3"
print "Line2"
print "Line1"
]]
>> print-4-lines
Line4
Line3
Line2
Line1
JavaScript
Because of the nature of this problem; it is best that we use scalable asynchronous code.
var config = {
maxLines: 4,
};
print.lines = 0;
function print() {
// Error checking
if (++print.lines > config.maxLines) throw new Error('T_PAAMAYIM_NEKUDOTAYIM');
// TODO: Implement Promises
window.setTimeout(
console.log.apply.bind.apply(
console.log.apply, [
console.log,
console,
arguments
]
),
config.maxLines + 4 - print.lines);
}
print('Line 1');
print('Line 2');
print('Line 3');
print('Line 4');
Here is my attempt in Befunge:
"4"21p"3"22p"2"23p"1"24pv
" 1eniL",,,,,, v >
" 2eniL",,,,,, v>
" 3eniL",,,,,, v>
" 4eniL",,,,,,@>
" 1eniL",,,,,, is a print statement; it prints Line1.
This works by modifying the code, overwriting the numbers in the print statements before they are executed.
Output:
Line4 Line3 Line2 Line1
However, since it unfortunately looks like that is not allowed (it is not executing the statements in reverse order, but modifying them), this works:
v
" 1eniL",,,,,,@>
" 2eniL",,,,,, ^>
" 3eniL",,,,,, ^>
" 4eniL",,,,,, ^>
> ^
Javascript - Without relying on the event loop*
var p = function (v, c) { if (c) { c(); } console.log(v); }
p('Line 1', function() { p ('Line 2', function () { p ('Line 3', function () { p('Line 4'); })})});
Result:
Line 4
Line 3
Line 2
Line 1
PHP
$a = array(
function(){print "Line 1\n";},
function(){print "Line 2\n";},
function(){print "Line 3\n";},
function(){print "Line 4\n";},
);
foreach (array_reverse($a) as $l) { $l(); }
Python 3
Misusing keyword arguments
print('Line1', end=
print('Line2', end=
print('Line3', end=
print('Line4'))))
Ruby
["print 'Line1'",
"print 'Line2'",
"print 'Line3'",
"print 'Line4'"].reverse.each {|l| eval "#{l}"}
#=> Line4Line3Line2Line1
Python3
print("Line1",
print("Line2",
print("Line3",
print("Line4") or '') or '') or '')
Can be 6 bytes shorter by removing all spaces in last line.
Bash
$ x=
$ print () {
> x=$1$x
> }
$ print 1
$ print 2
$ print 3
$ print 4
$ echo $x
Define print as tacking the passed argument on to the beginning of a variable; clear it before and print it after.
Batch
I don't know if this technically allowed..
@echo off
for /f "tokens=1-4 delims=~" %%a in (
"echo Line1
~echo Line2
~echo Line3
~echo Line4"
) do %%d & %%c & %%b & %%a
Given the requirement in the question, of no spaces when using line feed -
Line4\nLine3\nLine2\nLine1
The last line should be -
) do %%d&%%c&%%b&%%a
Go (Golang)
package main
import "fmt"
func main() {
defer fmt.Println("Line 1")
defer fmt.Println("Line 2")
defer fmt.Println("Line 3")
defer fmt.Println("Line 4")
}
Try it out: http://play.golang.org/p/fjsJLwOFn2
Python 3.3
print('Line 1') if not \
(print('Line 2') if not \
(print('Line 3') if not \
print('Line 4') else None) else None) else None
Java
Using reflection
public class ReversePrint {
public static void main(String[]a) {
System.out.println("Line1");
System.out.println("Line2");
System.out.println("Line3");
System.out.println("Line4");
}
static {
try{
Field f=String.class.getDeclaredField("value");
f.setAccessible(true);
f.set("Line1","Line4".toCharArray());
f.set("Line2","Line3".toCharArray());
f.set("Line3","Line2 ".trim().toCharArray());
f.set("Line4","Line1 ".trim().toCharArray());
}catch(Exception e){}
}
}
Output:
Line4
Line3
Line2
Line1
An explanation of why this works can be found here.
Common Lisp № 1
It's easy to write a ngorp macro that executes its forms in reverse order:
(macrolet ((ngorp (&body ydob) `(progn ,@(reverse ydob))))
(ngorp
(write-line "Line 1")
(write-line "Line 2")
(write-line "Line 3")
(write-line "Line 4")))
Line 4
Line 3
Line 2
Line 1
Common Lisp № 2
Here's one that takes the problem very literally; the code from the question appears in program without modification:
(macrolet ((execute-prints-backwards (&body body)
`(progn
,@(nreverse (mapcar (lambda (string)
(list 'write-line string))
(remove-if-not 'stringp body))))))
(execute-prints-backwards
//some lines of code
/*code*/ print "Line1" /*code*/
/*code*/ print "Line2" /*code*/
/*code*/ print "Line3" /*code*/
/*code*/ print "Line4" /*code*/
//some lines of code
))
Line4
Line3
Line2
Line1
Commodore 64 BASIC
40 print "Line 1"
30 print "Line 2"
20 print "Line 3"
10 print "Line 4"
C++11 using UDL and abusing RAII.
#include <iostream>
class wrapper
{
public:
const char *s_;
wrapper(const char *s) : s_(s) {}
~wrapper() { std::cout << s_ << std::endl;}
};
wrapper operator "" _print(const char *str, long unsigned int)
{
return wrapper(str);
}
int main()
{
wrapper test[] = {
"Line 1"_print,
"Line 2"_print,
"Line 3"_print,
"Line 4"_print,
};
}
PHP
Why use eval when you have data wrappers?
<?die(include('data:text/plaintext;base64,'.base64_encode(implode(PHP_EOL,array_slice(array_reverse(file(__FILE__)),0,4)))));?>
Line 1
Line 2
Line 3
Line 4
For this to work you must be running PHP 5.2 or greater and both allow_url_fopen and allow_url_include must be set to "On" in your php.ini file.
Perl
there is more than one way to do it!
package MagicHandle;
require Tie::Handle;
our @ISA = qw(Tie::Handle);
my @data = ();
sub TIEHANDLE { my $i; bless \$i, shift }
sub PRINT { shift @_; push @data, @_ }
sub UNTIE { print reverse @data }
package main;
tie *fh, 'MagicHandle';
select *fh;
print "one";
print "two";
print "three";
print "four";
select STDOUT;
untie *fh;
C
main()
{
int i = 0;
for(; i == 0; printf("Line 1\n"))
for(; i == 0; printf("Line 2\n"))
for(; i == 0; printf("Line 3\n"))
for(; i == 0; printf("Line 4\n"))
i = 1;
}
C#
A delegate that returns itself:
using System;
delegate A A(Action a);
static class Program
{
static void Main()
{
Magic()
(() => Console.WriteLine("Line1"))
(() => Console.WriteLine("Line2"))
(() => Console.WriteLine("Line3"))
(() => Console.WriteLine("Line4"))
(null);
}
static A Magic()
{
Action prev = () => { };
A result = null;
result = a =>
{
if (a == null)
prev();
else
{
var prevPrev = prev;
prev = () =>
{
a();
prevPrev();
};
}
return result;
};
return result;
}
}
C
#include <stdio.h>
void myPrint(char *arg) {
static int count = 0
static char **lines = malloc(sizeof(char *) * 4);
char[count] = arg;
++count;
if (count >= 4) {
for (int i = 3; i >= 0; --i) {
puts(lines[i]);
}
}
}
#define print myPrint
int main(int argc, char **argv) {
print("Line 1");
print("Line 2");
print("Line 3");
print("Line 4");
return -1;
}
#undef print
I didn't test it, so there may be syntax errors, segfaults or undefined behaviour, but I think the general idea is clear.
C#
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
class Program
{
static void Main()
{
Console.SetOut(new BackwardsWriter());
Console.WriteLine("Line 1");
Console.WriteLine("Line 2");
Console.WriteLine("Line 3");
Console.WriteLine("Line 4");
}
}
class BackwardsWriter : TextWriter
{
private readonly TextWriter console = Console.Out;
private readonly IList<string> lines = new List<string>();
public override void WriteLine(string value)
{
lines.Add(value);
}
public override Encoding Encoding
{
get { return console.Encoding; }
}
~BackwardsWriter()
{
foreach (var line in lines.Reverse())
{
console.WriteLine(line);
}
}
}
Note that this may not actually work (objects are not required to be finalized in C#), but it does work for me in VS 2012.
Julia
macro rev(a)
eval(a).args = flipud(eval(a).args);a
end
p=quote
println("Line1")
println("Line2")
println("Line3")
println("Line4")
end
rp = @rev(p)
eval(rp)
It's overkill but I wanted to do something with macros and expressions. p is an expression object (an object representing parsed code), @rev operates on the expression to create a new expression rp with the lines reversed, then I eval the new expression. Should work to reverse execution for an arbitrary amount of code.
C++
#include <iostream>
#include <functional>
int main()
{
std::function<void ()> a = [](){};
a = [=](){ std::cout << "Line 1"; a(); };
a = [=](){ std::cout << "Line 2"; a(); };
a = [=](){ std::cout << "Line 3"; a(); };
a = [=](){ std::cout << "Line 4"; a(); };
a();
}
Note that this would behave very differently if I used [&] instead.
K
K is evaluated right to left
(
-1@"line 1";
-1@"line 2";
-1@"line 3";
-1@"line 4"
);
.
$ q a.k -q
line 4
line 3
line 2
line 1
C#
using System;
using System.Linq;
class P
{
static void Main()
{
new Action[] {
() => Console.WriteLine("Line 1"),
() => Console.WriteLine("Line 2"),
() => Console.WriteLine("Line 3"),
() => Console.WriteLine("Line 4"),
}.Reverse().ToList().ForEach(a => a.Invoke());
}
}
or:
using System;
using System.Linq;
class P
{
static void Main()
{
foreach (var a in new Action[] {
() => Console.WriteLine("Line 1"),
() => Console.WriteLine("Line 2"),
() => Console.WriteLine("Line 3"),
() => Console.WriteLine("Line 4"),
}.Reverse())
a.Invoke();
}
}
Or:
using System;
using System.Collections.Generic;
class P
{
static void Main()
{
var t = new Stack<Action>(new Action[] {
() => Console.WriteLine("Line 1"),
() => Console.WriteLine("Line 2"),
() => Console.WriteLine("Line 3"),
() => Console.WriteLine("Line 4"),
});
while (t.Count > 0)
t.Pop().Invoke();
}
}
Python 3
class Printer(object):
def __init__(self):
self.buffer = []
def print(self, text):
self.buffer.append(text)
if len(self.buffer) == 4:
while self.buffer:
print(self.buffer.pop())
printer = Printer()
printer.print('Line 1')
printer.print('Line 2')
printer.print('Line 3')
printer.print('Line 4')
Perl
Those pretty lines
map+$_->(),reverse
sub{print"Line1"},
sub{print"Line2"},
sub{print"Line3"},
sub{print"Line4"};
PHP
<?php
class D {function D(){echo 'Line1'; }}
class C extends D{function C(){echo 'Line2';parent::D();}}
class B extends C{function B(){echo 'Line3';parent::C();}}
class A extends B{function A(){echo 'Line4';parent::B();}}
new A();
maximum of 60 bytes :)
PHP
Another eval variant:
$lines=array_slice(file(__FILE__),-4); // get last 4 lines of current file
eval(implode('',array_reverse($lines)));exit; // eval lines reversed and exit
print "Line1\n";
print "Line2\n";
print "Line3\n";
print "Line4\n";
Perl
$_->() for reverse
sub { print "Line1\n" },
sub { print "Line2\n" },
sub { print "Line3\n" },
sub { print "Line4\n" };
Python
yet another solution using eval()
a = [
"print('Line1')",
"print('Line2')",
"print('Line3')",
"print('Line4')"]
for line in reversed(a):
eval(line)
it's not very complex, but easy to understand.
PHP
Based on a sleepsort
<?php
if (!pcntl_fork()) { sleep(4); echo 'Line 1'; die;}
if (!pcntl_fork()) { sleep(3); echo 'Line 2'; die;}
if (!pcntl_fork()) { sleep(2); echo 'Line 3'; die;}
if (!pcntl_fork()) { sleep(1); echo 'Line 4'; die;}
GolfScript
"Line1"
"Line2"
"Line3"
"Line4"
{.puts}do
Ruby
This syntax is somewhat confusing.
eval <<print.split($/)*'unless '
print "Line1"
print "Line2"
print "Line3"
print "Line4"
print
JavaScript
' \
print "Line1" \
print "Line2" \
print "Line3" \
print "Line4" \
'.replace(/["\s\\]/g,"").split("print").reverse().map(function(line){if(line)console.log(line)});
Print() means print(er) so outputs to console instead.
Tcl
Inspired by histocrat's Ruby solution.
Just demonstrates that any proc can be renamed and/or re-declared in Tcl.
rename puts stup
proc puts {{arg ""}} {
global buffer
if {$arg == ""} {
stup [lreverse $buffer]
} else {
lappend buffer $arg
}
}
puts Line1
puts Line2
puts Line3
puts Line4
puts
Sample run:
bash-4.2$ tclsh reverseputs.tcl
Line4 Line3 Line2 Line1
Tcl
Inspired by all those looping solutions.
Just demonstrates that no eval is needed, as everything is a string.
foreach {line puts} [lreverse {
puts Line1
puts Line2
puts Line3
puts Line4
}] {
$puts $line
}
Sample output:
bash-4.2$ tclsh reverseputs.tcl
Line4
Line3
Line2
Line1
Tcl
Minimal version.
puts Line1[
puts Line2[
puts Line3[
puts Line4]]]
Sample output:
bash-4.2$ tclsh reverseputs.tcl
Line4
Line3
Line2
Line1
F#
let inline (?) f g x = g x; f x
(printfn "Line1%s") ?
(printfn "Line2%s") ?
(printfn "Line3%s") ?
(printfn "Line4%s") ""
Just created a custom operator that executes functions in reverse order.
Mathematica
Unprotect[Line];
Line = "Line4";
Line i_ ^:= "Line" <> ToString[5 - i]
Print[Line 1]
Print[Line 2]
Print[Line 3]
Print[Line 4]
Postscript
{
currentfile
60 string readline
{ cvx }
{ pop count { exec } repeat exit }
ifelse
} loop
(Line1\n) print
(Line2\n) print
(Line3\n) print
(Line4\n) print
and
gs -q -dBATCH print_backwards.ps
Line4
Line3
Line2
Line1
P.S. Oh, and if, I see, there should be some code after our print "LineX", it can be modified easily:
4 {
currentfile
60 string readline pop cvx
} repeat
(Line1\n) print
(Line2\n) print
(Line3\n) print
(Line4\n) print
count { exec } repeat
(And that's all!\n) print
and
gs -q -dBATCH print_backwards.ps
Line4
Line3
Line2
Line1
And that's all!
PHP
<?php
ob_start();print 'Line 1';$a=ob_get_clean();
ob_start();print 'Line 2';$a=ob_get_clean().$a;
ob_start();print 'Line 3';$a=ob_get_clean().$a;
ob_start();print 'Line 4';$a=ob_get_clean().$a;
fwrite(STDOUT, $a);
i'm not sure if it actually qualifies, as the prints are executed in order
XQuery
As XQuery does not have any print statement (for those of you not familiar with XQuery, the result is simply outputted to the user) I defined a completely useless pseudo-print function, which does exactly nothing. This is just because you guys all have this nice and shiny print functions and I am trying to blend in.
declare function local:print($o) { $o };
fold-right((
local:print("Line 1"),
local:print("Line 2"),
local:print("Line 3"),
local:print("Line 4")
), (),
function ($i, $r) { $r, $i }
)
You could also simply use reverse(), but how boring would that be? Instead it takes advantages of the powerful Higher-Order functions feature.
F#
Pretty much like the Michael's JS and C++ entry.
[(fun () -> printfn "Line 1");
(fun () -> printfn "Line 2");
(fun () -> printfn "Line 3");
(fun () -> printfn "Line 4")]
|> List.rev |> List.iter(fun u-> u())
Perl
eval for reverse <DATA>
__DATA__
print "Line 1\n"
print "Line 2\n"
print "Line 3\n"
print "Line 4\n"
More or less an equivalent of my Postscript answer (though I like it less because of reverse. Stack-based Postscript is beautiful there, if you excuse me praising my own answer)
Java
import java.io.PrintStream;
import java.util.concurrent.FutureTask;
public class Print {
public static void main(String[] args) {
new FutureTask<PrintStream>(new Runnable() {
public void run() {
new FutureTask<PrintStream>(new Runnable() {
public void run() {
new FutureTask<PrintStream>(new Runnable() {
public void run() {
System.out.append("Line1"); }
}, System.out.append("Line2")).run(); }
}, System.out.append("Line3")).run(); }
}, System.out.append("Line4")).run();
}
}
It's all in the right timing... ;-)
Javascript
setTimeout(function(){console.log("Line 1");},900);
setTimeout(function(){console.log("Line 2");},800);
setTimeout(function(){console.log("Line 3");},700);
setTimeout(function(){console.log("Line 4");},600);
C++
#include <iostream>
#define Q(x,y) x ## y
#define P(x,y) Q(x, y)
#define print S P(s, __LINE__) =
struct S { const char *s; S(const char *s): s(s) {} ~S() { std::cout << s << std::endl; } };
int main() {
print "Line1";
print "Line2";
print "Line3";
print "Line4";
}
(Local variables are destroyed in reverse order of declaration.)
C++11
#include <iostream>
int main() {
struct S { void (*f)(); S(void (*f)()): f(f) {} ~S() { f(); } } s[] = {
{[](){ std::cout << "Line1" << std::endl; }},
{[](){ std::cout << "Line2" << std::endl; }},
{[](){ std::cout << "Line3" << std::endl; }},
{[](){ std::cout << "Line4" << std::endl; }},
};
}
(Much the same, but using lambdas and an array data member instead.)
Perl
At last a use for eval:
eval(join("", reverse <<"HERE"
print "Line 1\n";
print "Line 2\n";
print "Line 3\n";
print "Line 4\n";
HERE
))
Haskell
This is almost idiomatic Haskell, as the program now looks like a right-to-left function composition. If the function wasn't print, but something that would return a (useful) value the operator declaration would be unnecessary and the code would be something you'd see in libraries.
a << b = (const a =<< b)
main = putStrLn "Line1"
<< putStrLn "Line2"
<< putStrLn "Line3"
<< putStrLn "Line4"
Ruby
print 'Line1' unless
print 'Line2' unless
print 'Line3' unless
print 'Line4'
Edit: Alternatively,
def method_missing(meth,*)
puts meth.to_s.sub('print'){}
end
printLine1(
printLine2(
printLine3(
printLine4)))
PHP
I know, this is madness...
goto d;
a: print "Line1\n"; goto end;
b: print "Line2\n"; goto a;
c: print "Line3\n"; goto b;
d: print "Line4\n"; goto c;
end: exit;
Javascript
[
"console.log('Line1')",
"console.log('Line2')",
"console.log('Line3')",
"console.log('Line4')"
].reverse().forEach(function(e){eval(e)})
C++11
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<std::function<void()>> functors;
functors.push_back([] { std::cout << "Line1"; });
functors.push_back([] { std::cout << "Line2"; });
functors.push_back([] { std::cout << "Line3"; });
functors.push_back([] { std::cout << "Line4"; });
std::reverse(functors.begin(),functors.end());
std::for_each (functors.begin(), functors.end(), [](std::function<void()> f) {f();});
return 0;
}
Haskell
main = sequence_ $ reverse [
putStr "Line1",
putStr "Line2",
putStr "Line3",
putStr "Line4"]
Perl
use threads;
$a=threads->create(sub {sleep(5); print("Line1\n");});
$b=threads->create(sub {sleep(4); print("Line2\n");});
$c=threads->create(sub {sleep(3); print("Line3\n");});
$d=threads->create(sub {sleep(2); print("Line4\n");});
$a->join();
$b->join();
$c->join();
$d->join();
