Execute prints backwards

102

29

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

Vereos

Posted 2014-02-12T09:25:17.413

Reputation: 4 079

15Does Arabic count? : ) – None – 2014-02-13T08:17:28.277

If you are able to meet the specs, of course :P – Vereos – 2014-02-13T10:34:19.213

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? – Ruslan – 2014-02-15T08:54:15.123

Every line of code can contain only one print – Vereos – 2014-02-15T15:07:51.327

does it have to pass a code review - suitable for production code? – Lance – 2014-02-17T19:37:26.420

Not really, it just has to meet the specs. – Vereos – 2014-02-17T21:59:53.110

Answers

183

Commodore 64 BASIC

40 print "Line 1"
30 print "Line 2"
20 print "Line 3"
10 print "Line 4"

Danko Durbić

Posted 2014-02-12T09:25:17.413

Reputation: 10 241

83I never could figure why line numbers are needed, until now. – ugoren – 2014-02-13T09:11:57.847

3I 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. – Mark Lakata – 2014-02-14T01:08:04.327

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. – Lance – 2014-02-19T22:55:59.623

109

PHP

Abusing precedence... :-)

!print "Line1\n".
!print "Line2\n".
!print "Line3\n".
!print "Line4\n";

bwoebi

Posted 2014-02-12T09:25:17.413

Reputation: 1 721

Amazing I did not know how it works, Can you please guide or give a link which describe how this works ? – kuldeep.kamboj – 2014-02-13T05:04:42.880

3In 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. – primo – 2014-02-13T06:10:25.290

Well I am not aware of that php is executing print statement right to left in case of String concatenate operator. – kuldeep.kamboj – 2014-02-13T07:02:51.237

1@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. – bwoebi – 2014-02-13T08:18:11.520

4

It seems to work in every version http://3v4l.org/dpSpK very impressive!

– eisberg – 2014-02-13T13:33:04.417

3Took 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! – sfarbota – 2014-02-13T17:41:02.300

Although you did break the rules, @bwoebi...There can't be spaces between "Line" and the numbers. ;) – sfarbota – 2014-02-13T17:43:10.323

1@sfarbota Reading rules is hard. Fixed. Thank you :-) – bwoebi – 2014-02-13T18:38:15.380

Your answer is great. – MirroredFate – 2014-02-14T23:37:19.830

Don't mean to be pedantic, but isn't this technically one Line of Code? – Ruslan – 2014-02-15T08:50:57.893

1@Ruslan no, it's one statement, but four lines of code. just like multiple statements in one line are still one line of code… – bwoebi – 2014-02-15T10:55:17.203

@bwoebi Yep, you're right. That's some really cool code, then :) – Ruslan – 2014-02-15T11:01:07.537

76

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

Nick

Posted 2014-02-12T09:25:17.413

Reputation: 941

Use puts("Line x") instead of printf("Line x\n") to save 16 bytes (assuming this is counted as an equivalent to "print"). – G. Sliepen – 2016-09-05T17:47:17.953

22I have absolutely no idea how come this actually works, +1. – svick – 2014-02-12T18:39:15.830

7@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. – Guntram Blohm supports Monica – 2014-02-12T21:53:59.810

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. – Nick – 2014-02-13T21:21:02.197

I thought C treated arglist commas as a sequence point. – fluffy – 2014-02-14T06:09:09.500

1@fluffy: Alas, it is the other way around: C does not treat arglist commas as sequence points, unlike other commas. – Williham Totland – 2014-02-14T15:08:36.947

6@WillihamTotland well then I know of some code that I really need to fix... thanks – fluffy – 2014-02-14T23:12:49.533

FYI: With gcc and clang you can compile this successfully with: -Wno-implicit-function-declaration argument. – A T – 2014-02-15T15:07:54.190

74

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.

Danny

Posted 2014-02-12T09:25:17.413

Reputation: 1 563

Reflection is like making database edits in production. You don't do it in production. – Magic Octopus Urn – 2018-03-28T17:16:53.073

61Horrible. I like it. – Roger Lindsjö – 2014-02-12T17:20:04.653

That needs to go inside a class. – tbodt – 2014-02-13T00:21:46.170

@tbodt ya, since this wasn't a code-golf I left out the import and class. Otherwise it looks too wordy. – Danny – 2014-02-13T00:23:55.913

4+1 People always are saying that java Strings are immutable. You prove that they aren't. – Victor Stafusa – 2014-02-13T04:46:08.373

16This is delightfully nasty, but the requirement of reverse execution is not met. – Thorbjørn Ravn Andersen – 2014-02-13T09:29:50.220

4@ThorbjørnRavnAndersen shhhh... your not supposed to tell them that. :p – Danny – 2014-02-13T13:12:30.007

5@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. – Justin – 2014-02-15T19:37:56.283

2@Quincunx I know. If you use reflection, native code calls, bytecode manipulation and instrumentation, calls to sun.misc.Unsafe, rt.jar tampering, and other dark-side dirty tricks, you can always screw things in really bad ways. – Victor Stafusa – 2014-02-15T19:55:08.200

70

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

ugoren

Posted 2014-02-12T09:25:17.413

Reputation: 16 527

1+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. – Justin – 2014-02-13T18:55:15.983

@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. – ugoren – 2014-02-13T20:44:54.277

1@Quincunx, and now it's really a polyglot. – ugoren – 2014-02-13T20:50:49.997

how is the first two defines work without spaces? Would it make print to be replaced by "\n",printf(? – phuclv – 2014-06-09T11:18:38.637

@LưuVĩnhPhúc - The space is optional. It replaces as you say. – ugoren – 2014-06-09T12:06:13.200

61

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

Noyo

Posted 2014-02-12T09:25:17.413

Reputation: 943

1... I actually believed this for a few minutes – Oliver Ni – 2016-10-11T00:02:29.630

7All 3 links you posted are leading to 404. Is this kind of joke? – manatwork – 2014-02-13T13:04:25.860

@manatwork Yes. :] But the code still works. – Noyo – 2014-02-13T14:19:55.330

lol; got behind the vodoo; you split the source on "-es and loop from second last to beginning skipping each 2nd part :P Nice way on that :) +1 – masterX244 – 2014-02-13T14:30:01.627

8Ah. I see now. The syntax highlighter was your accomplice here. – manatwork – 2014-02-13T14:34:14.007

1How does this work!? I notice that \* is NOT the start of a multi-line comment, but I don't know what it DOES do. – Eddified – 2014-02-13T19:53:10.667

1I see it now. Two kinds of single quote character in use here. Not familiar with the 2nd one that makes its appearance. Very tricky! I think this is the best one... – Eddified – 2014-02-13T20:00:45.550

It's just a tricky use of certain homoglyphs: http://www.fileformat.info/info/unicode/char/02c8/index.htm and http://www.fileformat.info/info/unicode/char/2216/index.htm, plus a little creativity. :]

– Noyo – 2014-02-14T15:47:57.113

12This is a combo [tag:popularity-contest] and [tag:code-trolling], no? :) I love it. – Not that Charles – 2014-02-14T15:55:27.533

8This is a phenomenal abuse of Javascript. I like it. – Seiyria – 2014-02-14T16:11:51.653

thanks @Eddified now it got clear for me, too :P Nice abusal of it :P – masterX244 – 2014-02-14T17:02:55.820

2Sneaky. Soooo sneaky.... – David Conrad – 2014-02-18T19:37:06.657

59

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;
}

David Yaw

Posted 2014-02-12T09:25:17.413

Reputation: 931

56

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

histocrat

Posted 2014-02-12T09:25:17.413

Reputation: 20 600

38I prefer this because it has meth – Ray – 2014-02-12T14:47:41.043

2Wouldn't you normaly post two answers if you had two solutions? – TheConstructor – 2014-02-12T15:30:55.823

3

Wouldn't this look more ruby-ish with code blocks? http://pastebin.com/LDWpxKx8

– manatwork – 2014-02-12T15:37:49.357

2@PacMani those parens don't use white space, they use White space. – corsiKa – 2014-02-12T18:22:44.137

@manatwork nice one! I do think method_missing is pretty Ruby-ish itself, though. – histocrat – 2014-02-12T22:14:02.633

@TheConstructor I wasn't sure; I looked for guidelines and didn't find them. I get less reputation this way but I suppose a higher chance of winning. – histocrat – 2014-02-12T22:15:17.873

49

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;

Florent

Posted 2014-02-12T09:25:17.413

Reputation: 2 557

66That noise you hear is Dijkstra spinning in his grave. :-) – Gareth – 2014-02-12T12:21:45.657

24Thought somebody said "be creative and avoid to write just a goto" ;-) – TheConstructor – 2014-02-12T15:29:44.133

22@TheConstructor The creative part is using goto in PHP ;) – NikiC – 2014-02-12T18:54:23.917

1So full of win. – Nick T – 2014-02-12T20:36:43.767

41

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"

shiona

Posted 2014-02-12T09:25:17.413

Reputation: 2 889

5tip: (<<) = flip (>>) – Bergi – 2014-02-12T20:26:47.470

@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) – shiona – 2014-02-12T23:50:39.577

@shiona:Yeah, it's a surprising thing to miss. Happily, we have both operators for Applicatives: <* and *>. – Tikhon Jelvis – 2014-02-13T12:42:31.250

@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 – proud haskeller – 2014-12-01T21:37:20.933

40

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

Gareth

Posted 2014-02-12T09:25:17.413

Reputation: 11 678

22This is theoretically not guaranteed to print in exact reverse order. – Cruncher – 2014-02-12T16:12:05.640

4@Cruncher I know, but with 1 second gaps the chances of it printing in anything other than reverse order are pretty slim. – Gareth – 2014-02-12T16:13:28.287

4@Gareth That's why I italicized theoretically :) – Cruncher – 2014-02-12T16:20:18.847

3@Cruncher Isn't that what makes it so fun? – Pierre Arlaud – 2014-02-17T09:37:15.427

@Cruncher in the same way that theoretically my atoms could pass through a wall? – cdeange – 2014-06-09T08:59:11.607

@cdeange but this is cs theory :) – Cruncher – 2014-06-09T13:12:34.470

37

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.

Mr Lister

Posted 2014-02-12T09:25:17.413

Reputation: 3 668

2Can anybody explain the downvote? This does work when printing, you know. – Mr Lister – 2014-02-14T12:42:19.910

You can also just do p {float:right;} – Noyo – 2014-02-14T12:52:20.593

But then the results will all be on one line! – Mr Lister – 2014-02-14T12:57:03.173

...and that's allowed. :] – Noyo – 2014-02-14T14:25:30.720

But they would also be right aligned! – Mr Lister – 2014-02-14T14:31:29.727

1...and that's not disallowed. :D You could also wrap it in a div and add the CSS rule div {float:left}. – Noyo – 2014-02-14T15:05:47.983

Hmmm... you really hate my solution, don't you? OK, OK, I made another one with less CSS. http://jsfiddle.net/udU4X/1/ That better? No added markup though, that wasn't necessary.

– Mr Lister – 2014-02-14T15:20:44.620

Don't get me wrong, I don't dislike (and didn't downvote) your solution. Was just giving suggestions to make it a little more elegant. I guess I should also upvote it. :] – Noyo – 2014-02-14T15:40:01.487

23

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

ecatmur

Posted 2014-02-12T09:25:17.413

Reputation: 1 675

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! – sergiol – 2017-05-31T00:10:07.320

21

Haskell

main = sequence_ $ reverse [
    putStr "Line1",
    putStr "Line2",
    putStr "Line3",
    putStr "Line4"]

mniip

Posted 2014-02-12T09:25:17.413

Reputation: 9 396

21

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

JoshWillik

Posted 2014-02-12T09:25:17.413

Reputation: 311

Using 1,2,3,4 as timeouts also works for me. (However, I do not know whether this behavior is standardized in ECMAScript.) – ComFreek – 2014-02-12T20:06:04.710

1@ComFreek: setTimeout is standardized in HTML5/timers, not in ES. Also, it specifies a minimum timeout of 4ms :-) – Bergi – 2014-02-12T20:32:19.897

1

@Bergi Yep, you are right, of course! HTML Standard - Timers - if anyone is interested.

– ComFreek – 2014-02-12T20:46:39.443

1Run 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. – Jeff Davis – 2014-02-13T22:20:52.913

@JeffDavis No it won't. See http://jsfiddle.net/wM5em/

– lastr2d2 – 2014-02-14T05:23:04.897

1

@lastr2d2 Simulating a slow computer with while loops is fairly subjective, but I think this would be more like it: http://jsfiddle.net/7zbKw/1/. Note from http://www.whatwg.org/specs/web-apps/current-work/multipage/timers.html#timers "This API does not guarantee that timers will run exactly on schedule. Delays due to CPU load, other tasks, etc, are to be expected."

– Jeff Davis – 2014-02-14T17:41:51.063

20

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;
}

hvd

Posted 2014-02-12T09:25:17.413

Reputation: 3 664

3nice abuse of a #define :P +1 – masterX244 – 2014-02-13T16:25:21.800

15

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.

Timtech

Posted 2014-02-12T09:25:17.413

Reputation: 12 038

14

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

Riot

Posted 2014-02-12T09:25:17.413

Reputation: 4 639

For it to look more like the specs, use $1 and $2: function print(){(sleep $((4-$2));echo "$1 $2";)&}; print Line 1 – ThinkChaos – 2014-02-25T19:35:29.233

13

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

TheConstructor

Posted 2014-02-12T09:25:17.413

Reputation: 563

The lines have to be adjacent. – Timtech – 2014-02-12T15:09:17.190

They are no less adjacent than e.g. with http://codegolf.stackexchange.com/a/20660/16293 nobody said they should look the same. Will remove some newline-characters ;-)

– TheConstructor – 2014-02-12T15:13:24.920

Okay, great :-) – Timtech – 2014-02-12T15:14:15.603

12

Python 3

import atexit

atexit.register(print,"Line1")
atexit.register(print,"Line2")
atexit.register(print,"Line3")
atexit.register(print,"Line4")

Mark Plotnick

Posted 2014-02-12T09:25:17.413

Reputation: 1 231

12

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"

Matteo Italia

Posted 2014-02-12T09:25:17.413

Reputation: 3 669

2I never even knew tac existed! Haha, thanks. – Noyo – 2014-02-14T10:25:58.190

11

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

Joshua Taylor

Posted 2014-02-12T09:25:17.413

Reputation: 660

10

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";

Decent Dabbler

Posted 2014-02-12T09:25:17.413

Reputation: 605

1Slick! Nonetheless, I feel compelled to point out this is a really bad idea. – David Kryzaniak – 2014-02-12T22:53:07.773

9

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.

p.s.w.g

Posted 2014-02-12T09:25:17.413

Reputation: 573

3I am pretty sure (?) f(g(x)) = g(x); f(x) is calculus and not programming. – Jeff Davis – 2014-02-13T22:27:53.557

2@JeffDavis: Pretty sure (?) f g x reads roughly as (?)(f, g, x), not f(g(x)) – Eric – 2014-02-17T00:41:47.650

9

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

cory.todd

Posted 2014-02-12T09:25:17.413

Reputation: 201

I wanted to post the exact same code. Literally, byte-for-byte exactly the same. – Art – 2014-02-13T15:08:53.403

@Art, awesome! I hope to see more Go used in Code Golf. – cory.todd – 2014-02-13T19:18:35.247

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. – Art – 2014-02-14T08:40:59.090

8

Python3

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

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

aragaer

Posted 2014-02-12T09:25:17.413

Reputation: 431

7

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;
}

Michael M.

Posted 2014-02-12T09:25:17.413

Reputation: 12 173

Instead of the std::reverse and std::for_each, simply use while (! functors.empty()) { functors.back()(); functors.pop_back(); } – David Hammen – 2015-09-05T18:37:51.090

7

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

hmilch

Posted 2014-02-12T09:25:17.413

Reputation: 71

Welcome to codegolf! Nice post. – Cruncher – 2014-02-13T16:33:41.770

7

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

Pieter Witvoet

Posted 2014-02-12T09:25:17.413

Reputation: 201

6

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.

davidak

Posted 2014-02-12T09:25:17.413

Reputation: 161

2the only code I understand :D – moldovean – 2014-02-13T08:31:03.147

5

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

Hydrothermal

Posted 2014-02-12T09:25:17.413

Reputation: 231

5

Python 3

Misusing keyword arguments

print('Line1', end=
print('Line2', end=
print('Line3', end=
print('Line4'))))

a_e_m

Posted 2014-02-12T09:25:17.413

Reputation: 51

4

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

draegtun

Posted 2014-02-12T09:25:17.413

Reputation: 1 592

Edit submitted as you actually don't need the COMPOSE (since the parens are harmless in the DO evaluator in this case, unnecessary precedence grouping...) :-) – HostileFork says dont trust SE – 2014-02-13T09:35:15.870

@Dr.Rebmu Of course! Thats much better thanks :) – draegtun – 2014-02-13T10:14:54.213

4

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.

Reinstate Monica - dirkk

Posted 2014-02-12T09:25:17.413

Reputation: 251

4

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.

svick

Posted 2014-02-12T09:25:17.413

Reputation: 154

4

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 "";
    }
}

masterX244

Posted 2014-02-12T09:25:17.413

Reputation: 3 942

4

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();
}

Lance

Posted 2014-02-12T09:25:17.413

Reputation: 65

4

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();
    }
}

user11171

Posted 2014-02-12T09:25:17.413

Reputation: 141

nice work; and someone in PHP used the exact similar way to tackle this :P but still nice way to trololol the code order – masterX244 – 2014-02-13T15:22:53.703

4

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

Digital Trauma

Posted 2014-02-12T09:25:17.413

Reputation: 64 644

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.

Bill Woodger

Posted 2014-02-12T09:25:17.413

Reputation: 1 391

This is absolutely amazing. – cat – 2015-12-30T16:18:08.650

Never seen such beautiful code before... – ceased to turn counterclockwis – 2014-02-15T13:05:11.423

@leftaroundabout Thanks. I've never had this program described as beautiful. Updated with -debug results, if interested to see it flying around... – Bill Woodger – 2014-02-15T15:03:57.213

4

JavaScript

console.log("Line 1", 
(console.log("Line 2",
(console.log("Line 3", 
(console.log("Line 4"), "")), "")
  ), "")
)

Pran

Posted 2014-02-12T09:25:17.413

Reputation: 41

3

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!

user2846289

Posted 2014-02-12T09:25:17.413

Reputation: 1 541

3

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",,,,,,   ^>
 >                ^

Justin

Posted 2014-02-12T09:25:17.413

Reputation: 19 757

“[Your output] must be generated only by executing those prints backwards.” Your first solution doesn't execute anything backwards. – svick – 2014-02-12T18:47:14.010

The first solution is not bending the rules, it's breaking them: it's clearly stated that Your code will have 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 This means that you must code them in this order but execute them in the opposite way. – Vereos – 2014-02-13T07:54:11.990

Still not good, I'm sorry. As I stated in another comment, the contest is not about printing the strings, but executing the commands in the reverse way (like the title says). You are not actually executing those last three prints since they're comments. – Vereos – 2014-02-13T08:40:49.640

@Quincunx No, you are executing another print command that has the same arg, written before the comment. You cannot run a comment. – Vereos – 2014-02-13T08:47:46.947

let us continue this discussion in chat

– Justin – 2014-02-13T08:48:46.167

You can easily use ,,,,,,"Line 1 ", which is much nicer, if you execute right to left. – ugoren – 2014-02-13T09:14:14.453

@ugoren Yeah, but what's the fun in that? – Justin – 2014-02-13T09:15:01.890

3

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,
  };
}

Xaqq

Posted 2014-02-12T09:25:17.413

Reputation: 131

3

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)

SamYonnou

Posted 2014-02-12T09:25:17.413

Reputation: 816

3

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

AShelly

Posted 2014-02-12T09:25:17.413

Reputation: 4 281

nice way :) seems that ya got inspired by my modified output stream in java :) +1 – masterX244 – 2014-02-13T19:19:23.433

3

Bash

This one abusing process substitution and redirects:

< <(< <(< <(< <(
1>&2 echo "Line1")
1>&2 echo "Line2")
1>&2 echo "Line3")
1>&2 echo "Line4")

Digital Trauma

Posted 2014-02-12T09:25:17.413

Reputation: 64 644

3

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.

Ilmari Karonen

Posted 2014-02-12T09:25:17.413

Reputation: 19 513

3

#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);
}

phord

Posted 2014-02-12T09:25:17.413

Reputation: 131

3

Haskell

(<<)=flip(>>)
main=putStrLn "Line1" <<
     putStrLn "Line2" <<
     putStrLn "Line3" <<
     putStrLn "Line4"

Geoff Reedy

Posted 2014-02-12T09:25:17.413

Reputation: 2 828

3

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>

Gilsham

Posted 2014-02-12T09:25:17.413

Reputation: 131

3

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.

James_pic

Posted 2014-02-12T09:25:17.413

Reputation: 3 988

2

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

manatwork

Posted 2014-02-12T09:25:17.413

Reputation: 17 865

My upvote was for the last one. – sergiol – 2017-03-30T00:47:33.417

2

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;}

luxcem

Posted 2014-02-12T09:25:17.413

Reputation: 151

2

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();
    }
}

RobIII

Posted 2014-02-12T09:25:17.413

Reputation: 397

Why a.Invoke() when you can just a()? – svick – 2014-02-12T18:13:56.590

Habit I guess :P I think Invoke() more clearly conveys what's happening, but you are correct. However, since it's not a "shorter == better" contest I think I'll leave it this way. – RobIII – 2014-02-12T18:21:07.090

2

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

Ricardo Pieper

Posted 2014-02-12T09:25:17.413

Reputation: 131

2

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

Einacio

Posted 2014-02-12T09:25:17.413

Reputation: 436

It works but the print statements need \n. – Boann – 2014-02-12T22:40:00.500

1@Boann where? i'm using the second output style from the specs – Einacio – 2014-02-13T16:09:06.383

‍@Einacio Oh I see. Okay. – Boann – 2014-02-13T16:36:33.967

2

Perl

$_->() for reverse
  sub { print "Line1\n" },
  sub { print "Line2\n" },
  sub { print "Line3\n" },
  sub { print "Line4\n" };

draegtun

Posted 2014-02-12T09:25:17.413

Reputation: 1 592

@Quincunx There's a few moving parts here but the key point is that Perl has first class functions. Above uses a list of 4 anonymous functions (sub), it reverses this list then iterates over the list (for), this for usage is postfix so works on the $->() that precedes. The `$is Perl's *it* (context) variable whichforaliases to with each iteration. Finally the->()runs (calls) the anonymous functions that$_` points to. – draegtun – 2014-02-12T18:42:27.920

2

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.

Dero

Posted 2014-02-12T09:25:17.413

Reputation: 21

2

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

ToXik-yogHurt

Posted 2014-02-12T09:25:17.413

Reputation: 311

2

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;
    }
}

dav_i

Posted 2014-02-12T09:25:17.413

Reputation: 121

+1 :) similar approach i used; but seems that Principle that works in mutiple languages – masterX244 – 2014-02-18T08:31:12.137

2

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;
    }
}

DLeh

Posted 2014-02-12T09:25:17.413

Reputation: 1 111

2

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

Spedwards

Posted 2014-02-12T09:25:17.413

Reputation: 159

2

Thue

00::=~Line1
11::=~Line2
22::=~Line3
33::=~Line4
::=
01233210

SuperJedi224

Posted 2014-02-12T09:25:17.413

Reputation: 11 342

2

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.

ATaco

Posted 2014-02-12T09:25:17.413

Reputation: 7 898

This doesn't meet the specs. You have to use your language's print. – mbomb007 – 2017-01-17T15:05:57.857

1Although it doesn't use the explicit p, this does use the language's print. Simply, it's Implicit one, not the Explicit one. – ATaco – 2017-01-17T19:50:20.303

1

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

Denham Coote

Posted 2014-02-12T09:25:17.413

Reputation: 1 397

1

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();
    }
}

demo

sergiol

Posted 2014-02-12T09:25:17.413

Reputation: 3 055

1

C++

Abusing Right-to-Left interpretation order of parameters

#include <iostream>

using namespace std;

void dummy_function(ostream &a, ostream &b, ostream &c, ostream &)
{
}   

int main()
{
    dummy_function(
        cout<<"Line 1"<<endl,
        cout<<"Line 2"<<endl,
        cout<<"Line 3"<<endl,
        cout<<"Line 4"<<endl
   );
}

demo

sergiol

Posted 2014-02-12T09:25:17.413

Reputation: 3 055

ostream &huh? – Erik the Outgolfer – 2017-05-31T08:14:05.337

@EriktheOutgolfer: what's the problem? – sergiol – 2017-05-31T09:24:15.663

Does & go on its own? Otherwise you have a syntax error. – Erik the Outgolfer – 2017-05-31T09:25:53.807

It compiled, as you can see in the demo. – sergiol – 2017-05-31T09:40:37.170

1

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.

Andreï Kostyrka

Posted 2014-02-12T09:25:17.413

Reputation: 1 389

1

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

12Me21

Posted 2014-02-12T09:25:17.413

Reputation: 6 110

1

Perl 5, 50 bytes

say"Line 1"x
say"line 2"x
say"Line 3"x
say"Line 4"

Try it online!

Dom Hastings

Posted 2014-02-12T09:25:17.413

Reputation: 16 415

1

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

Tom Tanner

Posted 2014-02-12T09:25:17.413

Reputation: 251

1

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)

user2846289

Posted 2014-02-12T09:25:17.413

Reputation: 1 541

1

Mathematica

Unprotect[Line];
Line = "Line4";
Line i_ ^:= "Line" <> ToString[5 - i]
Print[Line 1]
Print[Line 2]
Print[Line 3]
Print[Line 4]

swish

Posted 2014-02-12T09:25:17.413

Reputation: 7 484

1

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.

George Reith

Posted 2014-02-12T09:25:17.413

Reputation: 2 424

1

Perl

Those pretty lines

map+$_->(),reverse
sub{print"Line1"},
sub{print"Line2"},
sub{print"Line3"},
sub{print"Line4"};

Tumin

Posted 2014-02-12T09:25:17.413

Reputation: 119

almost the same as http://codegolf.stackexchange.com/a/20707

– msh210 – 2016-06-16T21:37:41.440

1

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

nyuszika7h

Posted 2014-02-12T09:25:17.413

Reputation: 1 624

1

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

tmartin

Posted 2014-02-12T09:25:17.413

Reputation: 3 917

1

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.

svick

Posted 2014-02-12T09:25:17.413

Reputation: 154

You could improve this by immediately printing when the lines count reaches 4. Then you would not depend on finalization. – Sebastian Negraszus – 2014-02-13T19:48:43.143

@SebastianNegraszus Yeah, but then I would depend on there being exactly 4 lines, I think that goes against the spirit of the question. – svick – 2014-02-13T22:08:03.290

1

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;

chinese perl goth

Posted 2014-02-12T09:25:17.413

Reputation: 1 089

1

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.

Potherca

Posted 2014-02-12T09:25:17.413

Reputation: 111

1

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"

sqlab

Posted 2014-02-12T09:25:17.413

Reputation: 181

1

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

justhalf

Posted 2014-02-12T09:25:17.413

Reputation: 2 070

1

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

Indy

Posted 2014-02-12T09:25:17.413

Reputation: 119

1What language is it? – ugoren – 2014-02-13T09:15:18.540

Hoho, knew I forgot something. Edit made – Indy – 2014-02-13T09:28:58.290

T_PAAMAYIM_NEKOTAYIM What? I don't even... – Jeff Davis – 2014-02-14T20:21:41.613

This answer is a parody, and should not be taken very seriously. @Jeff T_PAAMAYIM_NEKOTAYIM is poking fun at PHP's obscure error, described here.

– Indy – 2014-02-14T20:28:41.007

1

Matlab: something different

s = {'print ' 'Line1'...
     'print ' 'Line2'...
     'print ' 'Line3'...
     'print ' 'Line4'};

[s{end:-2:2}]

Obfuscation attempted

Dennis Jaheruddin

Posted 2014-02-12T09:25:17.413

Reputation: 1 848

1

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)

Nick H.

Posted 2014-02-12T09:25:17.413

Reputation: 119

1

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.

Izkata

Posted 2014-02-12T09:25:17.413

Reputation: 151

similar vodoo works in almost all languages :)

made that for java – masterX244 – 2014-02-13T20:55:43.440

@masterX244 The difference being that most of those require some trickery with parens or other syntax to cause the reversal. I figured this would be a good addition because without the single first line, the code is still valid as-is – Izkata – 2014-02-13T21:01:33.700

@lzkata i didnt said exact identical; just similar; someone in PHP did something related with weird operator behavior – masterX244 – 2014-02-13T21:03:21.903

1

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"

asgoth

Posted 2014-02-12T09:25:17.413

Reputation: 111

1

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

Ruslan

Posted 2014-02-12T09:25:17.413

Reputation: 280

1

Python3

print('line1') if not (
print('line2') if not (
print('line3') if not 
print('line4') else 
0) else 0) else 0

gnibbler

Posted 2014-02-12T09:25:17.413

Reputation: 14 170

1

Python3

def print(x,p=
print):p(x[:-1]+str(5-int(x[-1])))
print("line1")
print("line2")
print("line3")
print("line4")

gnibbler

Posted 2014-02-12T09:25:17.413

Reputation: 14 170

1

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"))
}

Boris

Posted 2014-02-12T09:25:17.413

Reputation: 161

1

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. :]

Noyo

Posted 2014-02-12T09:25:17.413

Reputation: 943

1

Perl

eval ($_) for (   reverse split("\n", <<EOF
print "Line1"; 
print "Line2"; 
print "Line3"; 
print "Line4";
EOF
) );

Very simple perl-Example with eval...

Riymus

Posted 2014-02-12T09:25:17.413

Reputation: 37

1

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)

le_vine

Posted 2014-02-12T09:25:17.413

Reputation: 701

plain old stdout remap :) but works :P +1 – masterX244 – 2014-02-14T15:24:08.687

1

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

http://ideone.com/A2AJ2s

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

http://ideone.com/8WgMxk

Matteo Italia

Posted 2014-02-12T09:25:17.413

Reputation: 3 669

1

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

ceased to turn counterclockwis

Posted 2014-02-12T09:25:17.413

Reputation: 5 200

1

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

Kjellski

Posted 2014-02-12T09:25:17.413

Reputation: 111

1

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]

Chris J

Posted 2014-02-12T09:25:17.413

Reputation: 199

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.

Justin

Posted 2014-02-12T09:25:17.413

Reputation: 19 757

1thats lol; abusing inner classes to nullify System from tje JDK in mainclass:P – masterX244 – 2014-02-15T20:27:42.507

@masterX244 I considered doing java.lang.System.out.println instead of a secondary class, but I think that this way, it is more unclear. – Justin – 2014-02-15T22:15:52.480

1

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

Jarry

Posted 2014-02-12T09:25:17.413

Reputation: 111

1

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")'
]);

palanik

Posted 2014-02-12T09:25:17.413

Reputation: 111

1

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.

Evpok

Posted 2014-02-12T09:25:17.413

Reputation: 558

1

Perl 6

END say 'Line1';
END say 'Line2';
END say 'Line3';
END say 'Line4';

There's a lot more phasers where END came from :)

Ayiko

Posted 2014-02-12T09:25:17.413

Reputation: 519

1

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

Strigoides

Posted 2014-02-12T09:25:17.413

Reputation: 1 025

1

Ruby (abusing eval)

eval(File.readlines(__FILE__).reverse.join "\n")
exit
puts "Line 1"
puts "Line 2"
puts "Line 3"
puts "Line 4"

tbrosman

Posted 2014-02-12T09:25:17.413

Reputation: 11

1

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.

James_pic

Posted 2014-02-12T09:25:17.413

Reputation: 3 988

1

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

Douglas Vanny

Posted 2014-02-12T09:25:17.413

Reputation: 11

1

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

David Conrad

Posted 2014-02-12T09:25:17.413

Reputation: 1 037

1

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.

David Conrad

Posted 2014-02-12T09:25:17.413

Reputation: 1 037

1

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?

Pharap

Posted 2014-02-12T09:25:17.413

Reputation: 195

1

Javascript

eval(
        "console.log('line1');"+
        "console.log('line2');"+
        "console.log('line3');"+
        "console.log('line4')"
        .split(";").reverse().join(";"));

Clyde Lobo

Posted 2014-02-12T09:25:17.413

Reputation: 1 395

1

F#

""
    |> sprintf "Line1 %s"
    |> sprintf "Line2 %s"
    |> sprintf "Line3 %s"
    |> sprintf "Line4 %s"
    |> printfn "%s"

Mau

Posted 2014-02-12T09:25:17.413

Reputation: 1 654

1

JavaScript

eval(
'console.log("Line1"); \
console.log("Line2"); \
console.log("Line3"); \
console.log("Line4"); '
.split(";").reverse().join(";"))

Yshayy

Posted 2014-02-12T09:25:17.413

Reputation: 119

1

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.

wadf

Posted 2014-02-12T09:25:17.413

Reputation: 161

1

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.

fede s.

Posted 2014-02-12T09:25:17.413

Reputation: 945

1

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

pgy

Posted 2014-02-12T09:25:17.413

Reputation: 830

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?

fede s.

Posted 2014-02-12T09:25:17.413

Reputation: 945

0

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();
    }

Sir Bitesalot

Posted 2014-02-12T09:25:17.413

Reputation: 41

0

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

enter image description here

sergiol

Posted 2014-02-12T09:25:17.413

Reputation: 3 055

0

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();
    }
}

demo

sergiol

Posted 2014-02-12T09:25:17.413

Reputation: 3 055

0

Ruby

This syntax is somewhat confusing.

eval <<print.split($/)*'unless '
print "Line1"
print "Line2"
print "Line3"
print "Line4"
print

daniero

Posted 2014-02-12T09:25:17.413

Reputation: 17 193

0

GolfScript

"Line1"
"Line2"
"Line3"
"Line4"
{.puts}do

p.s.w.g

Posted 2014-02-12T09:25:17.413

Reputation: 573

0

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

kelunik

Posted 2014-02-12T09:25:17.413

Reputation: 160

If you do this, why not just have functions calling each other? – svick – 2014-02-12T18:34:35.857

Yes, I can (use OOP).^^ – kelunik – 2014-02-12T19:09:53.880

0

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.

gggg

Posted 2014-02-12T09:25:17.413

Reputation: 1 715

0

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.

11684

Posted 2014-02-12T09:25:17.413

Reputation: 121

0

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;
    }
}

svick

Posted 2014-02-12T09:25:17.413

Reputation: 154

0

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

Mo D

Posted 2014-02-12T09:25:17.413

Reputation: 201

This doesn't contain Line1, Line2, etc. at all, which, according to spec, it should. – svick – 2014-02-13T01:16:26.073

You are correct... That was oversight on my part but I have corrected it... It now includes Line 1, Line 2 etc. – Mo D – 2014-02-13T08:57:24.887

0

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

unclemeat

Posted 2014-02-12T09:25:17.413

Reputation: 2 302

0

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.

Kevin

Posted 2014-02-12T09:25:17.413

Reputation: 501

0

Ruby

["print 'Line1'",
"print 'Line2'",
"print 'Line3'",
"print 'Line4'"].reverse.each {|l| eval "#{l}"}

#=> Line4Line3Line2Line1

Josh

Posted 2014-02-12T09:25:17.413

Reputation: 101

0

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(); }

Sergey Telshevsky

Posted 2014-02-12T09:25:17.413

Reputation: 127

0

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],
        ""
    )
)

user16356

Posted 2014-02-12T09:25:17.413

Reputation: 1

0

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

nightTrevors

Posted 2014-02-12T09:25:17.413

Reputation: 171

1

Please use Markdown to format the code block appropriately.

– manatwork – 2014-02-13T13:27:53.327

Are you sure your code not violates the “Every line can contain only one print” rule? – manatwork – 2014-02-13T13:29:31.273

q ignores white space, so I may be in violation – nightTrevors – 2014-02-13T13:39:14.923

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

user60195

Posted 2014-02-12T09:25:17.413

Reputation: 1

4tip: read the rules; 3rd bullet says; avoid simple loops with ifs or similar – masterX244 – 2014-02-13T16:26:38.227

0

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")
    ()()()()();
}

mattnewport

Posted 2014-02-12T09:25:17.413

Reputation: 1 579

0

Using good ol' stacks, in Java:

public void reversePrinting () {
    Stack<String> S = new Stack();

    S.push("Line 1");
    S.push("Line 2");
    S.push("Line 3");
    S.push("Line 4");

    System.out.println(S.pop());
    System.out.println(S.pop());
    System.out.println(S.pop());
    System.out.println(S.pop());
}

user2994498

Posted 2014-02-12T09:25:17.413

Reputation: 1

1Unfortunately, push is not print :( – Vereos – 2014-02-14T08:00:17.697

0

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

Ruslan

Posted 2014-02-12T09:25:17.413

Reputation: 280

0

PowerShell

(   {Write-Host 'Line 1'},
    {Write-Host 'Line 2'},
    {Write-Host 'Line 3'},
    {Write-Host 'Line 4'}
)[3..0]|ForEach-Object {Invoke-Command $_}

ojk

Posted 2014-02-12T09:25:17.413

Reputation: 101

0

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.

davidak

Posted 2014-02-12T09:25:17.413

Reputation: 161

0

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"

jazzpi

Posted 2014-02-12T09:25:17.413

Reputation: 846

0

Bash

#!/bin/bash
eval `tac $0 | head -n 4` && exit
echo 'Line1' ;
echo 'Line2' ;
echo 'Line3' ;
echo 'Line4' ;

Output:

Line4
Line3
Line2
Line1

Kevin

Posted 2014-02-12T09:25:17.413

Reputation: 3 123

0

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

Kevin

Posted 2014-02-12T09:25:17.413

Reputation: 3 123

0

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; }

Kevin

Posted 2014-02-12T09:25:17.413

Reputation: 3 123

0

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)

blabla999

Posted 2014-02-12T09:25:17.413

Reputation: 1 869

0

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"

phillips1012

Posted 2014-02-12T09:25:17.413

Reputation: 101

0

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"
}

Tarmil

Posted 2014-02-12T09:25:17.413

Reputation: 101

0

Shell again

cat <<XXX | sort -r | sh -
echo Line 1
echo Line 2
echo Line 3
echo Line 4
XXX

Ingo

Posted 2014-02-12T09:25:17.413

Reputation: 101

0

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

OregonTrail

Posted 2014-02-12T09:25:17.413

Reputation: 221

1The rule says, “Every line can contain only one print”. – manatwork – 2014-02-17T09:43:50.313

0

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");
    }
}

Mark Jeronimus

Posted 2014-02-12T09:25:17.413

Reputation: 6 451

0

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]]

Shreyas

Posted 2014-02-12T09:25:17.413

Reputation: 101

0

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;
}

Piotr

Posted 2014-02-12T09:25:17.413

Reputation: 1 321

0

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

Mamun

Posted 2014-02-12T09:25:17.413

Reputation: 181

0

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

Justin Fay

Posted 2014-02-12T09:25:17.413

Reputation: 237

0

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.

mikeserv

Posted 2014-02-12T09:25:17.413

Reputation: 181

0

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

SuperJedi224

Posted 2014-02-12T09:25:17.413

Reputation: 11 342

0

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

user19214

Posted 2014-02-12T09:25:17.413

Reputation: