2
\$\begingroup\$

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

\$\endgroup\$

closed as unclear what you're asking by Mego, NoOneIsHere, DJMcMayhem, Alex A. May 13 '16 at 2:32

Please clarify your specific problem or add additional details to highlight exactly what you need. As it's currently written, it’s hard to tell exactly what you're asking. See the How to Ask page for help clarifying this question. If this question can be reworded to fit the rules in the help center, please edit the question.

  • 1
    \$\begingroup\$ Longest code is code-bowling rather than code-trolling \$\endgroup\$ – Gareth Jan 23 '14 at 15:07
  • 2
    \$\begingroup\$ Ok, I'm really confused about the goal of this. You tagged this as popularity-contest, which implies a subjective competition, but you've defined an objective winning criteria. Then you've also tagged it 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 code-bowling only. \$\endgroup\$ – Iszi Jan 23 '14 at 15:10
  • 1
    \$\begingroup\$ @Iszi: I'm new to this site... \$\endgroup\$ – Mark K Cowan Jan 23 '14 at 15:11
  • 3
    \$\begingroup\$ Note: least efficient and largest are not necessarily the same. \$\endgroup\$ – Howard Jan 23 '14 at 15:33
  • 1
    \$\begingroup\$ I suppose that this challenge should require a finitely long code that can theoretically deal with an infinitely long input. \$\endgroup\$ – Dennis Jaheruddin Jan 23 '14 at 16:40
6
\$\begingroup\$

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

\$\endgroup\$
  • 1
    \$\begingroup\$ On 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. :-) \$\endgroup\$ – Mormegil Jan 23 '14 at 16:37
  • 1
    \$\begingroup\$ For extra bytes, why not use stuff from Microsoft.CSharp to compile your code and run it instead of printing it :D \$\endgroup\$ – Mark K Cowan Jan 23 '14 at 18:42
  • \$\begingroup\$ Or make it Java! That program might fill your hard drive with all the System.out.println()s! \$\endgroup\$ – C0deH4cker Jan 23 '14 at 21:02
  • \$\begingroup\$ I think this challenge would perfectly suit COBOL :D \$\endgroup\$ – Mark K Cowan Jan 24 '14 at 11:59
  • \$\begingroup\$ Wouldn't this be called redundant because it can safely be replaced by a recursive call? \$\endgroup\$ – Thomas Weller Feb 21 '14 at 16:04
3
\$\begingroup\$

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

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

\$\endgroup\$
  • \$\begingroup\$ 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]. \$\endgroup\$ – Mark K Cowan Jan 23 '14 at 22:46
  • 1
    \$\begingroup\$ This 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 \$\endgroup\$ – Mark K Cowan Jan 23 '14 at 22:47
1
\$\begingroup\$

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

\$\endgroup\$
  • \$\begingroup\$ To do better in this challenge, consider converting your program to Unary or VerboseFuck \$\endgroup\$ – pppery May 14 '16 at 0:51
  • \$\begingroup\$ @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? \$\endgroup\$ – Sylwester May 14 '16 at 1:06
  • \$\begingroup\$ Becuase they're longer and this is a code-bowling challenge \$\endgroup\$ – pppery May 14 '16 at 1:08
1
\$\begingroup\$

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

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

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;
        }
    }
}
\$\endgroup\$
  • \$\begingroup\$ Wow. Just wow. This code is dangerous, it tempts usage of the "doge" meme on SE... So awesome! Much variables! \$\endgroup\$ – Mark K Cowan Jan 24 '14 at 11:58
  • \$\begingroup\$ I think that the =null in the StreamReader initializers is unnecessary code. \$\endgroup\$ – pppery May 12 '16 at 17:16
  • \$\begingroup\$ Also, there is more than one occurence where you say a=b;return a (except with way longer variable names), which is redundant. \$\endgroup\$ – pppery May 17 '16 at 13:30

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