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

0
\$\begingroup\$

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

\$\endgroup\$
2
  • \$\begingroup\$ If you do this, why not just have functions calling each other? \$\endgroup\$
    – svick
    Commented Feb 12, 2014 at 18:34
  • \$\begingroup\$ Yes, I can (use OOP).^^ \$\endgroup\$
    – kelunik
    Commented Feb 12, 2014 at 19:09
0
\$\begingroup\$

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.

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

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.

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

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

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

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.

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

Ruby

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

#=> Line4Line3Line2Line1
\$\endgroup\$
0
\$\begingroup\$

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

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
\$\endgroup\$
2
  • \$\begingroup\$ This doesn't contain Line1, Line2, etc. at all, which, according to spec, it should. \$\endgroup\$
    – svick
    Commented Feb 13, 2014 at 1:16
  • \$\begingroup\$ You are correct... That was oversight on my part but I have corrected it... It now includes Line 1, Line 2 etc. \$\endgroup\$
    – Mo D
    Commented Feb 13, 2014 at 8:57
0
\$\begingroup\$

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],
        ""
    )
)
\$\endgroup\$
0
\$\begingroup\$

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

\$\endgroup\$
3
  • 1
    \$\begingroup\$ Please use Markdown to format the code block appropriately. \$\endgroup\$
    – manatwork
    Commented Feb 13, 2014 at 13:27
  • \$\begingroup\$ Are you sure your code not violates the “Every line can contain only one print” rule? \$\endgroup\$
    – manatwork
    Commented Feb 13, 2014 at 13:29
  • \$\begingroup\$ q ignores white space, so I may be in violation \$\endgroup\$ Commented Feb 13, 2014 at 13:39
0
\$\begingroup\$

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
\$\endgroup\$
1
  • 4
    \$\begingroup\$ tip: read the rules; 3rd bullet says; avoid simple loops with ifs or similar \$\endgroup\$
    – masterX244
    Commented Feb 13, 2014 at 16:26
0
\$\begingroup\$

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")
    ()()()()();
}
\$\endgroup\$
0
\$\begingroup\$

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

PowerShell

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

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.

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

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

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

Bash

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

Output:

Line4
Line3
Line2
Line1
\$\endgroup\$
0
\$\begingroup\$

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

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)

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

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

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

Shell again

cat <<XXX | sort -r | sh -
echo Line 1
echo Line 2
echo Line 3
echo Line 4
XXX
\$\endgroup\$
0
\$\begingroup\$

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
\$\endgroup\$
1
  • 1
    \$\begingroup\$ The rule says, “Every line can contain only one print”. \$\endgroup\$
    – manatwork
    Commented Feb 17, 2014 at 9:43
0
\$\begingroup\$

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

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

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

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())
\$\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.