104
\$\begingroup\$

Your task is to reverse the order in which some prints get executed.


Specs:
Your code will be in this form:

//some lines of code /*code*/ print "Line1" /*code*/ /*code*/ print "Line2" /*code*/ /*code*/ print "Line3" /*code*/ /*code*/ print "Line4" /*code*/ //some lines of code 

You will have to print (or echo, or write, or equivalent) those strings from the fourth to the first.

  • You decide which lines of your program must print the strings, but they must be adjacent;

  • Every line can contain only one print, and cannot exceed 60 bytes in length;

  • Since this is , be creative and avoid to write just a goto or a simple for(i){if(i=4)print"Line1";if(i=3)...}

  • The most upvoted answer in 2 weeks wins this.

  • Your output MUST be Line4 Line3 Line2 Line1 OR Line4Line3Line2Line1 OR Line4\nLine3\nLine2\nLine1(where \n is a newline), and it must be generated only by executing those prints backwards.

Happy coding!

UPDATE: Contest is over! Thank you all :)

\$\endgroup\$
6
  • 17
    \$\begingroup\$ Does Arabic count? : ) \$\endgroup\$ Commented Feb 13, 2014 at 8:17
  • \$\begingroup\$ If you are able to meet the specs, of course :P \$\endgroup\$ Commented Feb 13, 2014 at 10:34
  • \$\begingroup\$ Wanted to quickly clarify one rule... When you say "Every like can contain only one print", do you mean one text line in the code file or one LOC/statement? \$\endgroup\$ Commented Feb 15, 2014 at 8:54
  • \$\begingroup\$ Every line of code can contain only one print \$\endgroup\$ Commented Feb 15, 2014 at 15:07
  • \$\begingroup\$ does it have to pass a code review - suitable for production code? \$\endgroup\$ Commented Feb 17, 2014 at 19:37

159 Answers 159

1
2 3 4 5 6
186
\$\begingroup\$

Commodore 64 BASIC

40 print "Line 1" 30 print "Line 2" 20 print "Line 3" 10 print "Line 4" 
\$\endgroup\$
3
  • 86
    \$\begingroup\$ I never could figure why line numbers are needed, until now. \$\endgroup\$ Commented Feb 13, 2014 at 9:11
  • 3
    \$\begingroup\$ I was going to propose, copying Character ROM ($D000) to RAM ($3000), swapping character bitmaps for "1"<->"4" and "2"<->"3", then running the program in forward order. This is cuter. \$\endgroup\$ Commented Feb 14, 2014 at 1:08
  • 1
    \$\begingroup\$ I'm pretty sure you can't actually save/load or otherwise list the code in the order shown using the standard tools (definitely can't on Apple II anyway), all you could do would be type those lines in to the console in that order. And if that's allowed couldn't you just use e.g. C# SendKeys library to type code in any of the answered languages in a different order with arrow keys to move around. \$\endgroup\$ Commented Feb 19, 2014 at 22:55
108
\$\begingroup\$

PHP

Abusing precedence... :-)

!print "Line1\n". !print "Line2\n". !print "Line3\n". !print "Line4\n"; 
\$\endgroup\$
12
  • 3
    \$\begingroup\$ In PHP, print may be used as an expression, as it may be in perl, the return value of which is always 1. !1 returns bool(false), which when typed as a string returns the empty string. A more proper restriction for PHP might be to require echo rather than print; the above really is only one statement. \$\endgroup\$ Commented Feb 13, 2014 at 6:10
  • 1
    \$\begingroup\$ @kuldeep.kamboj It's just grouped that way: print ("Line 1". !print ("Line2". !print ("Line 3". !print "Line4"))); — everything that's on the right of a print statement is part of it. \$\endgroup\$ Commented Feb 13, 2014 at 8:18
  • 5
    \$\begingroup\$ It seems to work in every version 3v4l.org/dpSpK very impressive! \$\endgroup\$ Commented Feb 13, 2014 at 13:33
  • 3
    \$\begingroup\$ Took me a while to understand (Thanks @eisberg for the link!) but I get it now. While the first print is called first, it doesn't finish evaulating what it needs to print until the inner (lower) prints have already been called and fully evaluated. And the !s are just to hide the 1's that would print otherwise. Brilliant, @bwoebi! \$\endgroup\$ Commented Feb 13, 2014 at 17:41
  • 1
    \$\begingroup\$ @sfarbota Reading rules is hard. Fixed. Thank you :-) \$\endgroup\$ Commented Feb 13, 2014 at 18:38
78
\$\begingroup\$

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 :)

\$\endgroup\$
8
  • 24
    \$\begingroup\$ I have absolutely no idea how come this actually works, +1. \$\endgroup\$ Commented Feb 12, 2014 at 18:39
  • 7
    \$\begingroup\$ @svick: to support varargs, most C compilers put function arguments on the stack in reverse order (so the top item on the stack is always the 1st argument), which means they're likely to evaluate arguments in the same way. Of course, this assumes arguments are passed on the stack which becomes less and less the case with newer compilers. \$\endgroup\$ Commented Feb 12, 2014 at 21:53
  • \$\begingroup\$ As @GuntramBlohm said, the basic idea is that C function parameters are often (but not always) pushed onto the stack in a right-to-left order. Since these are function calls, the functions are probably (but not necessarily) called from right-to-left as well. All this is not defined by the C standard though, so while it happens to yield the right result in GCC 4 it's totally up to the compiler and calling convention what actually happens. \$\endgroup\$ Commented Feb 13, 2014 at 21:21
  • 1
    \$\begingroup\$ @fluffy: Alas, it is the other way around: C does not treat arglist commas as sequence points, unlike other commas. \$\endgroup\$ Commented Feb 14, 2014 at 15:08
  • 7
    \$\begingroup\$ @WillihamTotland well then I know of some code that I really need to fix... thanks \$\endgroup\$ Commented Feb 14, 2014 at 23:12
74
\$\begingroup\$

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.

\$\endgroup\$
9
  • 61
    \$\begingroup\$ Horrible. I like it. \$\endgroup\$ Commented Feb 12, 2014 at 17:20
  • 4
    \$\begingroup\$ +1 People always are saying that java Strings are immutable. You prove that they aren't. \$\endgroup\$ Commented Feb 13, 2014 at 4:46
  • 16
    \$\begingroup\$ This is delightfully nasty, but the requirement of reverse execution is not met. \$\endgroup\$ Commented Feb 13, 2014 at 9:29
  • 4
    \$\begingroup\$ @ThorbjørnRavnAndersen shhhh... your not supposed to tell them that. :p \$\endgroup\$ Commented Feb 13, 2014 at 13:12
  • 5
    \$\begingroup\$ @Victor In Java, Strings are immutable. All over Stackoverflow, there are questions like "I thought Strings were immutable". They use reflection and it makes them seem immutable. Java's promises work like this: "If you use our things / classes in the way we intended, then we promise that our claims are correct." Reflection is not the way classes are intended to use. \$\endgroup\$ Commented Feb 15, 2014 at 19:37
72
\$\begingroup\$

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)))); } 
\$\endgroup\$
5
  • 1
    \$\begingroup\$ +1 for the macro. Maybe include another one; something like #define } 0)))); (I don't know exactly how macros work in C). That way you could just have the print statements in the main method, nothing else. \$\endgroup\$ Commented Feb 13, 2014 at 18:55
  • \$\begingroup\$ @Quincunx, you can't define }, but you can define return, which I now did. It's almost a polyglot now - the print syntax works in several script languages, #define is often a comment, but main(){..} doesn't work in any language I could find. \$\endgroup\$ Commented Feb 13, 2014 at 20:44
  • 1
    \$\begingroup\$ @Quincunx, and now it's really a polyglot. \$\endgroup\$ Commented Feb 13, 2014 at 20:50
  • \$\begingroup\$ how is the first two defines work without spaces? Would it make print to be replaced by "\n",printf(? \$\endgroup\$ Commented Jun 9, 2014 at 11:18
  • \$\begingroup\$ @LưuVĩnhPhúc - The space is optional. It replaces as you say. \$\endgroup\$ Commented Jun 9, 2014 at 12:06
62
\$\begingroup\$

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

\$\endgroup\$
12
  • 7
    \$\begingroup\$ All 3 links you posted are leading to 404. Is this kind of joke? \$\endgroup\$ Commented Feb 13, 2014 at 13:04
  • 8
    \$\begingroup\$ Ah. I see now. The syntax highlighter was your accomplice here. \$\endgroup\$ Commented Feb 13, 2014 at 14:34
  • 13
    \$\begingroup\$ This is a combo popularity-contest and code-trolling, no? :) I love it. \$\endgroup\$ Commented Feb 14, 2014 at 15:55
  • 8
    \$\begingroup\$ This is a phenomenal abuse of Javascript. I like it. \$\endgroup\$ Commented Feb 14, 2014 at 16:11
  • 2
    \$\begingroup\$ Sneaky. Soooo sneaky.... \$\endgroup\$ Commented Feb 18, 2014 at 19:37
61
\$\begingroup\$

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; } 
\$\endgroup\$
58
\$\begingroup\$

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))) 
\$\endgroup\$
6
  • 41
    \$\begingroup\$ I prefer this because it has meth \$\endgroup\$ Commented Feb 12, 2014 at 14:47
  • 2
    \$\begingroup\$ Wouldn't you normaly post two answers if you had two solutions? \$\endgroup\$ Commented Feb 12, 2014 at 15:30
  • 3
    \$\begingroup\$ Wouldn't this look more ruby-ish with code blocks? pastebin.com/LDWpxKx8 \$\endgroup\$ Commented Feb 12, 2014 at 15:37
  • 2
    \$\begingroup\$ @PacMani those parens don't use white space, they use White space. \$\endgroup\$ Commented Feb 12, 2014 at 18:22
  • \$\begingroup\$ @manatwork nice one! I do think method_missing is pretty Ruby-ish itself, though. \$\endgroup\$ Commented Feb 12, 2014 at 22:14
51
\$\begingroup\$

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; 
\$\endgroup\$
4
  • 70
    \$\begingroup\$ That noise you hear is Dijkstra spinning in his grave. :-) \$\endgroup\$ Commented Feb 12, 2014 at 12:21
  • 26
    \$\begingroup\$ Thought somebody said "be creative and avoid to write just a goto" ;-) \$\endgroup\$ Commented Feb 12, 2014 at 15:29
  • 24
    \$\begingroup\$ @TheConstructor The creative part is using goto in PHP ;) \$\endgroup\$ Commented Feb 12, 2014 at 18:54
  • 2
    \$\begingroup\$ So full of win. \$\endgroup\$ Commented Feb 12, 2014 at 20:36
42
\$\begingroup\$

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" 
\$\endgroup\$
4
  • 6
    \$\begingroup\$ tip: (<<) = flip (>>) \$\endgroup\$ Commented Feb 12, 2014 at 20:26
  • \$\begingroup\$ @Bergi That's another way to write it, I guess a little more elegant even. I was actually a little surprised to see the thing wasn't defined in prelude (or Control.Monad) \$\endgroup\$ Commented Feb 12, 2014 at 23:50
  • \$\begingroup\$ @shiona:Yeah, it's a surprising thing to miss. Happily, we have both operators for Applicatives: <* and *>. \$\endgroup\$ Commented Feb 13, 2014 at 12:42
  • \$\begingroup\$ @TikhonJelvis actually, the <* applicative operator is different than this << : a <* b is equivalent to do x<-a;b;return x , i.e. it runs a's effect first \$\endgroup\$ Commented Dec 1, 2014 at 21:37
41
\$\begingroup\$

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(); 
\$\endgroup\$
6
  • 24
    \$\begingroup\$ This is theoretically not guaranteed to print in exact reverse order. \$\endgroup\$ Commented Feb 12, 2014 at 16:12
  • 4
    \$\begingroup\$ @Cruncher I know, but with 1 second gaps the chances of it printing in anything other than reverse order are pretty slim. \$\endgroup\$ Commented Feb 12, 2014 at 16:13
  • 4
    \$\begingroup\$ @Gareth That's why I italicized theoretically :) \$\endgroup\$ Commented Feb 12, 2014 at 16:20
  • 3
    \$\begingroup\$ @Cruncher Isn't that what makes it so fun? \$\endgroup\$ Commented Feb 17, 2014 at 9:37
  • \$\begingroup\$ @Cruncher in the same way that theoretically my atoms could pass through a wall? \$\endgroup\$ Commented Jun 9, 2014 at 8:59
38
\$\begingroup\$

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> 

Fiddle.

\$\endgroup\$
8
  • 2
    \$\begingroup\$ Can anybody explain the downvote? This does work when printing, you know. \$\endgroup\$ Commented Feb 14, 2014 at 12:42
  • \$\begingroup\$ You can also just do p {float:right;} \$\endgroup\$ Commented Feb 14, 2014 at 12:52
  • \$\begingroup\$ But then the results will all be on one line! \$\endgroup\$ Commented Feb 14, 2014 at 12:57
  • \$\begingroup\$ ...and that's allowed. :] \$\endgroup\$ Commented Feb 14, 2014 at 14:25
  • 1
    \$\begingroup\$ ...and that's not disallowed. :D You could also wrap it in a div and add the CSS rule div {float:left}. \$\endgroup\$ Commented Feb 14, 2014 at 15:05
24
\$\begingroup\$

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.)

\$\endgroup\$
1
  • \$\begingroup\$ I posted a solution using std::function, and I was trying to get rid of it. Now I don't need because you got it! \$\endgroup\$ Commented May 31, 2017 at 0:10
22
\$\begingroup\$

Haskell

main = sequence_ $ reverse [ putStr "Line1", putStr "Line2", putStr "Line3", putStr "Line4"] 
\$\endgroup\$
22
\$\begingroup\$

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); 
\$\endgroup\$
6
  • \$\begingroup\$ Using 1,2,3,4 as timeouts also works for me. (However, I do not know whether this behavior is standardized in ECMAScript.) \$\endgroup\$ Commented Feb 12, 2014 at 20:06
  • 1
    \$\begingroup\$ @ComFreek: setTimeout is standardized in HTML5/timers, not in ES. Also, it specifies a minimum timeout of 4ms :-) \$\endgroup\$ Commented Feb 12, 2014 at 20:32
  • 1
    \$\begingroup\$ @Bergi Yep, you are right, of course! HTML Standard - Timers - if anyone is interested. \$\endgroup\$ Commented Feb 12, 2014 at 20:46
  • 1
    \$\begingroup\$ Run this on a slow enough machine (say, an 8086 running several other applications?) and it will fail. (By fail, I mean the order will not be reversed, since it will take >= 100ms to execute each statement. \$\endgroup\$ Commented Feb 13, 2014 at 22:20
  • 1
    \$\begingroup\$ @lastr2d2 Simulating a slow computer with while loops is fairly subjective, but I think this would be more like it: jsfiddle.net/7zbKw/1. Note from whatwg.org/specs/web-apps/current-work/multipage/… "This API does not guarantee that timers will run exactly on schedule. Delays due to CPU load, other tasks, etc, are to be expected." \$\endgroup\$ Commented Feb 14, 2014 at 17:41
21
\$\begingroup\$

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; } 
\$\endgroup\$
1
  • 3
    \$\begingroup\$ nice abuse of a #define :P +1 \$\endgroup\$ Commented Feb 13, 2014 at 16:25
15
\$\begingroup\$

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 
\$\endgroup\$
1
  • \$\begingroup\$ For it to look more like the specs, use $1 and $2: function print(){(sleep $((4-$2));echo "$1 $2";)&}; print Line 1 \$\endgroup\$ Commented Feb 25, 2014 at 19:35
15
\$\begingroup\$

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.

\$\endgroup\$
13
\$\begingroup\$

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... ;-)

\$\endgroup\$
3
  • \$\begingroup\$ The lines have to be adjacent. \$\endgroup\$ Commented Feb 12, 2014 at 15:09
  • \$\begingroup\$ They are no less adjacent than e.g. with codegolf.stackexchange.com/a/20660/16293 nobody said they should look the same. Will remove some newline-characters ;-) \$\endgroup\$ Commented Feb 12, 2014 at 15:13
  • \$\begingroup\$ Okay, great :-) \$\endgroup\$ Commented Feb 12, 2014 at 15:14
13
\$\begingroup\$

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" 
\$\endgroup\$
0
12
\$\begingroup\$

Python 3

import atexit atexit.register(print,"Line1") atexit.register(print,"Line2") atexit.register(print,"Line3") atexit.register(print,"Line4") 
\$\endgroup\$
11
\$\begingroup\$

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 
\$\endgroup\$
10
\$\begingroup\$

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"; 
\$\endgroup\$
1
  • 1
    \$\begingroup\$ Slick! Nonetheless, I feel compelled to point out this is a really bad idea. \$\endgroup\$ Commented Feb 12, 2014 at 22:53
9
\$\begingroup\$

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.

\$\endgroup\$
2
  • 3
    \$\begingroup\$ I am pretty sure (?) f(g(x)) = g(x); f(x) is calculus and not programming. \$\endgroup\$ Commented Feb 13, 2014 at 22:27
  • 2
    \$\begingroup\$ @JeffDavis: Pretty sure (?) f g x reads roughly as (?)(f, g, x), not f(g(x)) \$\endgroup\$ Commented Feb 17, 2014 at 0:41
9
\$\begingroup\$

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

\$\endgroup\$
3
  • \$\begingroup\$ I wanted to post the exact same code. Literally, byte-for-byte exactly the same. \$\endgroup\$ Commented Feb 13, 2014 at 15:08
  • \$\begingroup\$ @Art, awesome! I hope to see more Go used in Code Golf. \$\endgroup\$ Commented Feb 13, 2014 at 19:18
  • \$\begingroup\$ Probably won't happen. Go isn't really good a being compressed, they deliberately limit weird constructs so that you can't create an unreadable mess. But in this case (and maybe other popularity contests) it has a chance. \$\endgroup\$ Commented Feb 14, 2014 at 8:40
8
\$\begingroup\$

Python3

print("Line1", print("Line2", print("Line3", print("Line4") or '') or '') or '') 

Can be 6 bytes shorter by removing all spaces in last line.

\$\endgroup\$
7
\$\begingroup\$

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; } 
\$\endgroup\$
1
  • \$\begingroup\$ Instead of the std::reverse and std::for_each, simply use while (! functors.empty()) { functors.back()(); functors.pop_back(); } \$\endgroup\$ Commented Sep 5, 2015 at 18:37
7
\$\begingroup\$

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 
\$\endgroup\$
1
  • \$\begingroup\$ Welcome to codegolf! Nice post. \$\endgroup\$ Commented Feb 13, 2014 at 16:33
7
\$\begingroup\$

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); } } } 
\$\endgroup\$
6
\$\begingroup\$

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.

\$\endgroup\$
1
  • 2
    \$\begingroup\$ the only code I understand :D \$\endgroup\$ Commented Feb 13, 2014 at 8:31
1
2 3 4 5 6

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.