LARGEST program to reverse a single line from stdin with no redundant code

2

The biggest program that reads a single line (terminated by your choice from NULL/CR/LF/CRLF) from stdin, reverses it, then prints it to stdout.

No redundant code [code which could safely be deleted] such as

return ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

or redundant data that's used to stop code being redundant:

char* data = <kernel source code>;
if (md5sum(data) != <hash>) {
    return 1; //Fail for no good reason because it lets us add 1000000 lines of data
}

Basically, the largest implementation of a string reverse, with no obvious attempt to game the question.

[edit]

I am tempted to say that the code must be finite for unbounded input length, but there have been some clever and interesting O(>1) length solutions. I instead ask that people avoid posting simple brute-force lookup-list solutions as separate answers (comments are fine!).

Mark K Cowan

Posted 2014-01-23T15:03:51.137

Reputation: 227

Question was closed 2016-05-13T02:32:09.843

1Longest code is [tag:code-bowling] rather than [tag:code-trolling] – Gareth – 2014-01-23T15:07:52.067

@Gareth: Cheers, changed – Mark K Cowan – 2014-01-23T15:09:35.527

2Ok, I'm really confused about the goal of this. You tagged this as [tag:popularity-contest], which implies a subjective competition, but you've defined an objective winning criteria. Then you've also tagged it [tag:code-trolling], which implies that you want some sort of useless or misguided answers to a relatively simple and undereducated question, but your challenge is not so simple and deliberately asking for a particular level of complexity. The challenge, as stated, is strictly [tag:code-bowling] only. – Iszi – 2014-01-23T15:10:42.907

1@Iszi: I'm new to this site... – Mark K Cowan – 2014-01-23T15:11:48.787

3Note: least efficient and largest are not necessarily the same. – Howard – 2014-01-23T15:33:17.497

Largest I can think of: if (!strcmp(input, "aaa")) printf("aaa"); else if (!strcmp(input, "aab")) printf("baa");, etc. So I guess the correct solution to this challenge is to figure out the longest possible size of an answer on stackexchange and implement as many compares as possible in it that reverse parts of the string. – Art – 2014-01-23T16:04:45.647

1I suppose that this challenge should require a finitely long code that can theoretically deal with an infinitely long input. – Dennis Jaheruddin – 2014-01-23T16:40:56.690

Answers

6

C# – Something about 90 KB, but actually, ~90×n for any n

See https://gist.github.com/mormegil-cz/8581459 for the full source code. A short preview version to taste:

var c1 = Console.Read();
if (c1 > 0 && c1 != 13)
{
    var c2 = Console.Read();
    if (c2 > 0 && c2 != 13)
    {
        var c3 = Console.Read();
        if (c3 > 0 && c3 != 13)
        {
            // ...
            Console.Write((char)c3);
        }
        Console.Write((char)c2);
    }
    Console.Write((char)c1);
}
Console.WriteLine();

And because writing the source code seems a bit repetitive, let’s use a simple tool:

void Main()
{
    const int MAX_DEPTH = 1000;
    Console.WriteLine("using System;");
    Console.WriteLine("using System.Text;");
    Console.WriteLine();
    Console.WriteLine("class C");
    Console.WriteLine("{");
    Console.WriteLine("\tstatic void Main()");
    Console.WriteLine("\t{");
    for (int i = 0; i < MAX_DEPTH; ++i)
    {
        var indent = new string('\t', i + 2);
        Console.WriteLine("{0}var c{1} = Console.Read();", indent, i);
        Console.WriteLine("{0}if (c{1} > 0 && c{1} != 13)", indent, i);
        Console.WriteLine("{0}{{", indent);
    }
    var restIndent = new string('\t', MAX_DEPTH + 2);
    Console.WriteLine("{0}var rest = new StringBuilder();", restIndent);
    Console.WriteLine("{0}for (var c = Console.Read(); c > 0 && c != 13; c = Console.Read())", restIndent);
    Console.WriteLine("{0}{{", restIndent);
    Console.WriteLine("{0}\trest.Append((char)c);", restIndent);
    Console.WriteLine("{0}}}", restIndent);
    Console.WriteLine("{0}var restArray = rest.ToString().ToCharArray();", restIndent);
    Console.WriteLine("{0}Array.Reverse(restArray);", restIndent);
    Console.WriteLine("{0}Console.Write(new string(restArray));", restIndent);
    for (int i = MAX_DEPTH - 1; i >= 0; --i)
    {
        var indent = new string('\t', i + 2);
        Console.WriteLine("{0}\tConsole.Write((char)c{1});", indent, i);
        Console.WriteLine("{0}}}", indent);
    }
    Console.WriteLine("\t\tConsole.WriteLine();");
    Console.WriteLine("\t}");
    Console.WriteLine("}");
}

Change MAX_DEPTH to get a larger score (or possibly an internal C# compiler error?).

Mormegil

Posted 2014-01-23T15:03:51.137

Reputation: 1 148

@ThomasWeller replacement != deletion – Patrick Roberts – 2017-08-27T19:48:12.883

1On a MS C# compiler I have here, MAX_DEPTH=2385 seems to be the maximum (corresponding to a source size of ~220 KB), anything larger causes fatal error CS1647: An expression is too long or complex to compile. :-) – Mormegil – 2014-01-23T16:37:39.070

1For extra bytes, why not use stuff from Microsoft.CSharp to compile your code and run it instead of printing it :D – Mark K Cowan – 2014-01-23T18:42:11.790

Or make it Java! That program might fill your hard drive with all the System.out.println()s! – C0deH4cker – 2014-01-23T21:02:30.537

I think this challenge would perfectly suit COBOL :D – Mark K Cowan – 2014-01-24T11:59:55.530

Wouldn't this be called redundant because it can safely be replaced by a recursive call? – Thomas Weller – 2014-02-21T16:04:23.657

3

C#

6710 bytes

212 lines of code including 6 comments

3 classes, 2 interfaces, 1 file

using System;
using System.Collections.Generic;

namespace StringReverse
{
    public class Program
    {
        public static void Main(string[] args)
        {
            UnreversedString unreversed = Console.ReadLine();
            ReversedString reversed = ReverseString(unreversed);
            Console.WriteLine(reversed);
        }

        public static ReversedString ReverseString(UnreversedString unreversed)
        {
            // We know that string reversing is recursive.
            // We also know that recursion is confusing.
            // Therefore, we will use a recursive algorithm without actually using recursion.
            // This will greatly "simplify" our code. ;)
            Stack<IString> stringStack = new Stack<IString>();
            stringStack.Push(unreversed);
            Random random = new Random();
            do
            {
                if (stringStack.Peek() is UnreversedString)
                {
                    IString unreversedString = stringStack.Pop();
                    if (unreversedString.Length < 2)
                    {
                        ReversedString reversedString = unreversedString.ToString();
                        stringStack.Push(reversedString);
                    }
                    else
                    {
                        int randomInt = random.Next(unreversedString.Length);
                        IString firstHalfOfUnreversedString = unreversedString.Substring(0, randomInt);
                        IString secondHalfOfUnreversedString = unreversedString.Substring(randomInt);
                        stringStack.Push(firstHalfOfUnreversedString);
                        stringStack.Push(secondHalfOfUnreversedString);
                    }
                }
                else
                {
                    IString firstString = stringStack.Pop();
                    IString secondString = stringStack.Pop();
                    if (secondString is UnreversedString)
                    {
                        stringStack.Push(firstString);
                        stringStack.Push(secondString);
                    }
                    else
                    {
                        ReversedString newReversedString = secondString.ToString() + firstString.ToString();
                        stringStack.Push(newReversedString);
                    }
                }
            }
            while (stringStack.Count > 1);
            return stringStack.Pop() as ReversedString;
        }
    }

    // We need a common way to treat strings, because they all need to be stored in the same stack.
    public interface IString
    {
        int Length
        {
            get;
        }

        IString Substring(int startIndex);
        IString Substring(int startIndex, int length);
    }

    public interface IString<T> : IString where T : IString<T>
    {
        new T Substring(int startIndex);
        new T Substring(int startIndex, int length);
    }

    // We also need a way to differentiate between them.
    public class UnreversedString : IString<UnreversedString>
    {
        private string unreversedString;

        public string UnreversedStringValue
        {
            get
            {
                return this.unreversedString;
            }
            set
            {
                this.unreversedString = value;
            }
        }

        public int Length
        {
            get
            {
                string unreversedString = this;
                return unreversedString.Length;
            }
        }

        public UnreversedString Substring(int startIndex)
        {
            string unreversedString = this;
            return unreversedString.Substring(startIndex);
        }

        public UnreversedString Substring(int startIndex, int length)
        {
            string unreversedString = this;
            return unreversedString.Substring(startIndex, length);
        }

        IString IString.Substring(int startIndex)
        {
            return this.Substring(startIndex);
        }

        IString IString.Substring(int startIndex, int length)
        {
            return this.Substring(startIndex, length);
        }

        public override string ToString()
        {
            return this.UnreversedStringValue;
        }

        public static implicit operator string(UnreversedString unreversedString)
        {
            return unreversedString.ToString();
        }

        public static implicit operator UnreversedString(string unreversedString)
        {
            UnreversedString newUnreversedString = new UnreversedString();
            newUnreversedString.UnreversedStringValue = unreversedString;
            return newUnreversedString;
        }
    }

    public class ReversedString : IString<ReversedString>
    {
        private string reversedString;

        public string ReversedStringValue
        {
            get
            {
                return this.reversedString;
            }
            set
            {
                this.reversedString = value;
            }
        }

        public int Length
        {
            get
            {
                string reversedString = this;
                return reversedString.Length;
            }
        }

        public ReversedString Substring(int startIndex)
        {
            string reversedString = this;
            return reversedString.Substring(startIndex);
        }

        public ReversedString Substring(int startIndex, int length)
        {
            string reversedString = this;
            return reversedString.Substring(startIndex, length);
        }

        IString IString.Substring(int startIndex)
        {
            return this.Substring(startIndex);
        }

        IString IString.Substring(int startIndex, int length)
        {
            return this.Substring(startIndex, length);
        }

        public override string ToString()
        {
            return this.ReversedStringValue;
        }

        public static implicit operator string(ReversedString reversedString)
        {
            return reversedString.ToString();
        }

        public static implicit operator ReversedString(string reversedString)
        {
            ReversedString newReversedString = new ReversedString();
            newReversedString.ReversedStringValue = reversedString;
            return newReversedString;
        }
    }
}

Kendall Frey

Posted 2014-01-23T15:03:51.137

Reputation: 2 384

1

Windows Command Script - 101 + 76*361 + 78*362 + ... + 276*36100 bytes

Note: max string length is 100, and the string is limited to alphanumeric characters

@echo off
echo.Enter string to reverse
set /p i=:
call :%i%
cscript //nologo rev.js
pause&exit/b
:a
echo.WScript.Echo("a".split("").reverse().join(""));>rev.js
exit /b 
:aa
echo.WScript.Echo("aa".split("").reverse().join(""));>rev.js
exit /b 
:aaa
.... and so on

Generated by:

@echo off
echo.Generating code... (this will take a LOOOONG time)
echo>b.cmd @echo off
echo>>b.cmd echo.Enter string to reverse
echo>>b.cmd set /p i=:
echo>>b.cmd call :%%i%%
echo>>b.cmd cscript //nologo rev.js
echo>>b.cmd pause^&exit/b
goto b
:a
echo>>b.cmd :%1
echo>>b.cmd echo.WScript.Echo("%1".split("").reverse().join(""));^>rev.js
echo>>b.cmd exit /b 1
set tmp=%1
if not "%tmp:~100,1%"=="" (
exit /b 0
)
:b
for %%a in (a b c d e f g h i j k l m n o p q r s t u v w x y z 0 1 2 3 4 5 6 7 8 9) do call :a %1%%%a

Have fun waiting...

Robert Sørlie

Posted 2014-01-23T15:03:51.137

Reputation: 1 036

I should have expected Windows CMD to take the lead here, after past experiences trying to port a 5-line bash script over to Windows... [took >100 lines of CMD, thanks largely to lack of backtick and programs not respecting the basic streams]. – Mark K Cowan – 2014-01-23T22:46:16.430

2This gives me an idea for a hybrid golf/bowling question...

Post a sh script and equivalent cmd script - the objective is to maximise (lines of cmd / lines of sh) without redundancy – Mark K Cowan – 2014-01-23T22:47:12.653

1

Brainfuck: 72 bytes

>>+[-<,[+[-----------[---[+++++++++++++>>+<]]]]>]<<[.[-]<]++++++++++.[-]

Suports CR/LF/CRLF no change EOF, -1 EOF and 0 EOF to get the bytecount up so it's very compatible.

Getting it larger is puishing it since BF is such a compact language. It's really better for golfing :-p

Sylwester

Posted 2014-01-23T15:03:51.137

Reputation: 3 678

To do better in this challenge, consider converting your program to Unary or VerboseFuck

– pppery – 2016-05-14T00:51:07.577

@ppperry I'll leave it to someone else as I don't find those dialects very interesting. I have no problems reading and following the code in this answer even two years after I wrote it, but a lot of BF dialects are just obscured syntax from the original that are far harder to read. Why would one want obscure BF? – Sylwester – 2016-05-14T01:06:28.180

Becuase they're longer and this is a [tag:code-bowling] challenge – pppery – 2016-05-14T01:08:02.430

1

Morington Crescent, 1480 bytes

Take Northern Line to Moorgate
Take Metropolitan Line to Moorgate
Take Metropolitan Line to Barbican
Take Hammersmith & City Line to Barbican
Take Hammersmith & City Line to Euston Square
Take Hammersmith & City Line to Euston Square
Take Circle Line to Liverpool Street
Take Central Line to Liverpool Street
Take Central Line to Oxford Circus
Take Victoria Line to Oxford Circus
Take Victoria Line to Victoria
Take Victoria Line to Victoria
Take District Line to Bank
Take Waterloo & City Line to Bank
Take Waterloo & City Line to Waterloo
Take Waterloo & City Line to Waterloo
Take Bakerloo Line to Piccadilly Circus
Take Piccadilly Line to Piccadilly Circus
Take Piccadilly Line to Turnpike Lane
Take Piccadilly Line to Turnpike Lane
Take Piccadilly Line to Piccadilly Circus
Take Piccadilly Line to Piccadilly Circus
Take Bakerloo Line to Waterloo
Take Waterloo & City Line to Waterloo
Take Waterloo & City Line to Bank
Take Waterloo & City Line to Bank
Take District Line to Victoria
Take District Line to Victoria
Take Victoria Line to Oxford Circus
Take Victoria Line to Oxford Circus
Take Central Line to Liverpool Street
Take Central Line to Liverpool Street
Take Circle Line to Euston Square
Take Hammersmith & City Line to Euston Square
Take Hammersmith & City Line to Barbican
Take Hammersmith & City Line to Barbican
Take Metropolitan Line to Moorgate
Take Metropolitan Line to Moorgate
Take Northern Line to Mornington Crescent

This code goes around in a huge loop using every single line but the Piccadilly Line, ending in Piccadilly Circus. Then it goes to Turnpike Lane, which reverses the string, before finally unwinding the loop and returning to Mornington Crescent

pppery

Posted 2014-01-23T15:03:51.137

Reputation: 3 987

0

You may find this answer a rule-bending one, you'll decide whether it's valid or not.

This code:

  • Is self-commented;
  • Handles every string from STDIN and outputs it in STDOUT;
  • Handles IO exceptions;
  • Has very bad memory usage;
  • Is very unefficient;
  • Will eventually end...

This answer is between the code-trolling and the code-bowling: it is trolling the user that reads/uses/wrote that code (am I trolling myself?), but it actually works; could be much shorter, but there is no redundant code (if you delete even one of the lines or the commands, it won't work). Also, it won't seem (at least, didn't to me) it is attempting to game the question.

C# - 6.825 7.037 bytes

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace Console
{
    class Program
    {
        private const string omgAreYouDumbYouHaveToUseThisProgramThisWay = "Oh gawd please type the command this way! programName inputfile.txt outputfile.txt";
        static int Main(string[] sgra)
        {
            StreamWriter initializeThisStreamWriterHereBecauseItsCool = null;
            StreamReader initializeThisStreamReaderHereBecauseItsEvenCooler = null;
            if (sgra.Length < (calculateIntegerToAdd()+calculateIntegerToAdd()))
            {
                int didYouNoticeThatSgraIsArgsBackwardsAhahImSoFunny = calculateIntegerToAdd();
                WriteThisLineHereAndNowDidYouHearMeh(omgAreYouDumbYouHaveToUseThisProgramThisWay);
                return didYouNoticeThatSgraIsArgsBackwardsAhahImSoFunny;
            }
            try
            {
                initializeThisStreamWriterHereBecauseItsCool = new StreamWriter(sgra[calculateIntegerToAdd()]);
                initializeThisStreamReaderHereBecauseItsEvenCooler = new StreamReader(sgra[calculateIntegerToAdd()-calculateIntegerToAdd()]);
                System.Console.SetOut(initializeThisStreamWriterHereBecauseItsCool);
                System.Console.SetIn(initializeThisStreamReaderHereBecauseItsEvenCooler);
            }
            catch (IOException thisExceptionWouldMakeMyProgramCrashButICatchedItHaha)
            {
                TextWriter thisWillWriteIfThereIsAnyRuntimeErrorBecauseCrapHappenz = System.Console.Error;
                int valueThatWillBeReturnedBecauseThereIsAnErrorWowItsSoBad = calculateIntegerToAdd();
                thisWillWriteIfThereIsAnyRuntimeErrorBecauseCrapHappenz.WriteLine(thisExceptionWouldMakeMyProgramCrashButICatchedItHaha.Message);
                thisWillWriteIfThereIsAnyRuntimeErrorBecauseCrapHappenz.WriteLine(omgAreYouDumbYouHaveToUseThisProgramThisWay);
                thisWillWriteIfThereIsAnyRuntimeErrorBecauseCrapHappenz.Close();
                return valueThatWillBeReturnedBecauseThereIsAnErrorWowItsSoBad;
            }
            string thisIsGoingToBeReversedButHowPleaseTellMe = WootAreYouDoingDontMessAroundAndReadThatLine();
            char[] imGoingToStoreAllCharactersHereBecauseItsFun = new char[thisIsGoingToBeReversedButHowPleaseTellMe.Length];
            for (int awfulCounterWhyAreYouHere = calculateIntegerToAdd()-calculateIntegerToAdd(); awfulCounterWhyAreYouHere < thisIsGoingToBeReversedButHowPleaseTellMe.Length; awfulCounterWhyAreYouHere++)
            {
                imGoingToStoreAllCharactersHereBecauseItsFun[awfulCounterWhyAreYouHere] = thisIsGoingToBeReversedButHowPleaseTellMe.ElementAt(awfulCounterWhyAreYouHere);
            }
            char[] thisIsTheSolutionIllCheckIfMineIsEqual = new char[imGoingToStoreAllCharactersHereBecauseItsFun.Length];
            int pseudoAuxiliaryCounterThatIWillIncrementInTheForCycleAwesome = thisIsGoingToBeReversedButHowPleaseTellMe.Length-thisIsGoingToBeReversedButHowPleaseTellMe.Length;
            for (int awfulReversedCounterWhyAreYouHere = imGoingToStoreAllCharactersHereBecauseItsFun.Length-calculateIntegerToAdd();awfulReversedCounterWhyAreYouHere>-calculateIntegerToAdd();awfulReversedCounterWhyAreYouHere--)
            {
                thisIsTheSolutionIllCheckIfMineIsEqual[pseudoAuxiliaryCounterThatIWillIncrementInTheForCycleAwesome] = imGoingToStoreAllCharactersHereBecauseItsFun[awfulReversedCounterWhyAreYouHere];
            pseudoAuxiliaryCounterThatIWillIncrementInTheForCycleAwesome =     pseudoAuxiliaryCounterThatIWillIncrementInTheForCycleAwesome + calculateIntegerToAdd();
            }
            int cycleCounterBecauseIWantToSeeHowMyAlgorythmIsUnefficient = pseudoAuxiliaryCounterThatIWillIncrementInTheForCycleAwesome-pseudoAuxiliaryCounterThatIWillIncrementInTheForCycleAwesome;
            while (new String(imGoingToStoreAllCharactersHereBecauseItsFun) != new String(thisIsTheSolutionIllCheckIfMineIsEqual))
            {
                imGoingToStoreAllCharactersHereBecauseItsFun = bogoSortCanSu_Ehm_CannotBeatMyAlgorythmsAwesomeness(imGoingToStoreAllCharactersHereBecauseItsFun);
                cycleCounterBecauseIWantToSeeHowMyAlgorythmIsUnefficient = cycleCounterBecauseIWantToSeeHowMyAlgorythmIsUnefficient + calculateIntegerToAdd();
            }
            string omgIHaveASolutionHowLongDidItTake = new String(imGoingToStoreAllCharactersHereBecauseItsFun);
            WriteThisLineHereAndNowDidYouHearMeh(omgIHaveASolutionHowLongDidItTake);
            initializeThisStreamWriterHereBecauseItsCool.Close();
            return cycleCounterBecauseIWantToSeeHowMyAlgorythmIsUnefficient;
        }

        public static char[] bogoSortCanSu_Ehm_CannotBeatMyAlgorythmsAwesomeness(char[] uselessVariableWhichIsGoingToBeUsedAsInput)
        {
            char[] uselessVariableWhichIsGoingTobeReturned = uselessVariableWhichIsGoingToBeUsedAsInput;
            Random thisWillDecideWhichIndexesAreGoingToBeSwapped = new Random();
            int firstIndexToBeSwappedRandomlyGenerated = thisWillDecideWhichIndexesAreGoingToBeSwapped.Next(uselessVariableWhichIsGoingTobeReturned.Length);
            int secondIndexToBeSwappedRandomlyGenerated = thisWillDecideWhichIndexesAreGoingToBeSwapped.Next(uselessVariableWhichIsGoingTobeReturned.Length);
            char tempVariableWhichWillBeUsedForSwap = uselessVariableWhichIsGoingTobeReturned[firstIndexToBeSwappedRandomlyGenerated];
            uselessVariableWhichIsGoingTobeReturned[firstIndexToBeSwappedRandomlyGenerated] = uselessVariableWhichIsGoingTobeReturned[secondIndexToBeSwappedRandomlyGenerated];
            uselessVariableWhichIsGoingTobeReturned[secondIndexToBeSwappedRandomlyGenerated] = tempVariableWhichWillBeUsedForSwap;
            return uselessVariableWhichIsGoingTobeReturned;
        }

        public static void WriteThisLineHereAndNowDidYouHearMeh(string stringToBeWrittenHereAndNow)
        {
            System.Console.WriteLine(stringToBeWrittenHereAndNow);
        }

        public static string WootAreYouDoingDontMessAroundAndReadThatLine()
        {
            string thisStringIsGoingTobeReturnedOmgWhatDoIDoWhatDoIDo;
            thisStringIsGoingTobeReturnedOmgWhatDoIDoWhatDoIDo = System.Console.ReadLine();
            return thisStringIsGoingTobeReturnedOmgWhatDoIDoWhatDoIDo;
        }

        public static int calculateIntegerToAdd()
        {
            Random thisWillGenerateNumbersUntilItGetsOneItMayTakeAWhile = new Random();
            int isThisIntegerEqualToOneOrNot = 0;
            while (isThisIntegerEqualToOneOrNot != 1)
            {
                isThisIntegerEqualToOneOrNot = thisWillGenerateNumbersUntilItGetsOneItMayTakeAWhile.Next(0,10);
            }
            int thisIntegerIsEqualToOne = isThisIntegerEqualToOneOrNot;
            return thisIntegerIsEqualToOne;
        }
    }
}

Vereos

Posted 2014-01-23T15:03:51.137

Reputation: 4 079

I think that the =null in the StreamReader initializers is unnecessary code. – pppery – 2016-05-12T17:16:45.667

Also, there is more than one occurence where you say a=b;return a (except with way longer variable names), which is redundant. – pppery – 2016-05-17T13:30:58.957

Wow. Just wow. This code is dangerous, it tempts usage of the "doge" meme on SE... So awesome! Much variables! – Mark K Cowan – 2014-01-24T11:58:59.027