102
\$\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\$
  • 15
    \$\begingroup\$ Does Arabic count? : ) \$\endgroup\$ – user11739 Feb 13 '14 at 8:17
  • \$\begingroup\$ If you are able to meet the specs, of course :P \$\endgroup\$ – Vereos Feb 13 '14 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 Feb 15 '14 at 8:54
  • \$\begingroup\$ Every line of code can contain only one print \$\endgroup\$ – Vereos Feb 15 '14 at 15:07
  • \$\begingroup\$ does it have to pass a code review - suitable for production code? \$\endgroup\$ – Lance Feb 17 '14 at 19:37

157 Answers 157

2
\$\begingroup\$

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;
    }
}
\$\endgroup\$
  • \$\begingroup\$ +1 :) similar approach i used; but seems that Principle that works in mutiple languages \$\endgroup\$ – masterX244 Feb 18 '14 at 8:31
2
\$\begingroup\$

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

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

\$\endgroup\$
2
\$\begingroup\$

Thue

00::=~Line1
11::=~Line2
22::=~Line3
33::=~Line4
::=
01233210
\$\endgroup\$
2
\$\begingroup\$

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.

\$\endgroup\$
  • \$\begingroup\$ This doesn't meet the specs. You have to use your language's print. \$\endgroup\$ – mbomb007 Jan 17 '17 at 15:05
  • 1
    \$\begingroup\$ Although it doesn't use the explicit p, this does use the language's print. Simply, it's Implicit one, not the Explicit one. \$\endgroup\$ – ATaco Jan 17 '17 at 19:50
1
\$\begingroup\$

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

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)

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

Mathematica

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

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.

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

Perl

Those pretty lines

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

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

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

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.

\$\endgroup\$
  • \$\begingroup\$ You could improve this by immediately printing when the lines count reaches 4. Then you would not depend on finalization. \$\endgroup\$ – Sebastian Negraszus Feb 13 '14 at 19:48
  • \$\begingroup\$ @SebastianNegraszus Yeah, but then I would depend on there being exactly 4 lines, I think that goes against the spirit of the question. \$\endgroup\$ – svick Feb 13 '14 at 22:08
1
\$\begingroup\$

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

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.

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

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

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');
\$\endgroup\$
  • 1
    \$\begingroup\$ What language is it? \$\endgroup\$ – ugoren Feb 13 '14 at 9:15
  • \$\begingroup\$ Hoho, knew I forgot something. Edit made \$\endgroup\$ – Indy Feb 13 '14 at 9:28
  • \$\begingroup\$ T_PAAMAYIM_NEKOTAYIM What? I don't even... \$\endgroup\$ – Jeff Davis Feb 14 '14 at 20:21
  • \$\begingroup\$ 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. \$\endgroup\$ – Indy Feb 14 '14 at 20:28
1
\$\begingroup\$

Matlab: something different

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

[s{end:-2:2}]

Obfuscation attempted

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

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

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.

\$\endgroup\$
  • \$\begingroup\$ similar vodoo works in almost all languages :) made that for java \$\endgroup\$ – masterX244 Feb 13 '14 at 20:55
  • \$\begingroup\$ @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 \$\endgroup\$ – Izkata Feb 13 '14 at 21:01
  • \$\begingroup\$ @lzkata i didnt said exact identical; just similar; someone in PHP did something related with weird operator behavior \$\endgroup\$ – masterX244 Feb 13 '14 at 21:03
1
\$\begingroup\$

Python3

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

Python3

print('line1') if not (
print('line2') if not (
print('line3') if not 
print('line4') else 
0) else 0) else 0
\$\endgroup\$
1
\$\begingroup\$

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

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

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

Perl

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

Very simple perl-Example with eval...

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

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)
\$\endgroup\$
  • \$\begingroup\$ plain old stdout remap :) but works :P +1 \$\endgroup\$ – masterX244 Feb 14 '14 at 15:24
1
\$\begingroup\$

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

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

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

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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