103
\$\begingroup\$

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


Specs:
Your code will be in this form:

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

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

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

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

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

  • The most upvoted answer in 2 weeks wins this.

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

Happy coding!

UPDATE: Contest is over! Thank you all :)

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

156 Answers 156

1
\$\begingroup\$

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

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();
\$\endgroup\$
1
\$\begingroup\$

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")'
]);
\$\endgroup\$
1
\$\begingroup\$

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.

\$\endgroup\$
1
\$\begingroup\$

Perl 6

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

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

\$\endgroup\$
1
\$\begingroup\$

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

\$\endgroup\$
0
1
\$\begingroup\$

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")
\$\endgroup\$
1
\$\begingroup\$

Ruby (abusing eval)

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

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.

\$\endgroup\$
1
\$\begingroup\$

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()
\$\endgroup\$
1
\$\begingroup\$

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

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.

\$\endgroup\$
1
\$\begingroup\$

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?

\$\endgroup\$
1
\$\begingroup\$

Javascript

eval(
        "console.log('line1');"+
        "console.log('line2');"+
        "console.log('line3');"+
        "console.log('line4')"
        .split(";").reverse().join(";"));
\$\endgroup\$
1
\$\begingroup\$

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.

\$\endgroup\$
2
  • 1
    \$\begingroup\$ thats lol; abusing inner classes to nullify System from tje JDK in mainclass:P \$\endgroup\$
    – masterX244
    Commented Feb 15, 2014 at 20:27
  • \$\begingroup\$ @masterX244 I considered doing java.lang.System.out.println instead of a secondary class, but I think that this way, it is more unclear. \$\endgroup\$
    – Justin
    Commented Feb 15, 2014 at 22:15
1
\$\begingroup\$

F#

""
    |> sprintf "Line1 %s"
    |> sprintf "Line2 %s"
    |> sprintf "Line3 %s"
    |> sprintf "Line4 %s"
    |> printfn "%s"
\$\endgroup\$
0
1
\$\begingroup\$

JavaScript

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

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.

\$\endgroup\$
1
\$\begingroup\$

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.

\$\endgroup\$
1
\$\begingroup\$

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")
\$\endgroup\$
1
\$\begingroup\$

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

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?

\$\endgroup\$
1
\$\begingroup\$

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

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

\$\endgroup\$
1
\$\begingroup\$

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

\$\endgroup\$
4
  • \$\begingroup\$ ostream &huh? \$\endgroup\$ Commented May 31, 2017 at 8:14
  • \$\begingroup\$ @EriktheOutgolfer: what's the problem? \$\endgroup\$
    – sergiol
    Commented May 31, 2017 at 9:24
  • \$\begingroup\$ Does & go on its own? Otherwise you have a syntax error. \$\endgroup\$ Commented May 31, 2017 at 9:25
  • \$\begingroup\$ It compiled, as you can see in the demo. \$\endgroup\$
    – sergiol
    Commented May 31, 2017 at 9:40
1
\$\begingroup\$

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.

\$\endgroup\$
1
\$\begingroup\$

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

Perl 5, 50 bytes

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

Try it online!

\$\endgroup\$
0
\$\begingroup\$

Ruby

This syntax is somewhat confusing.

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

GolfScript

"Line1"
"Line2"
"Line3"
"Line4"
{.puts}do
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.