# Question
Title: LARGEST program to reverse a single line from stdin with no redundant code
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!).

# Answer
## 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?).
> 6 votes

# Answer
## 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;
        }
    }
}

```
> 3 votes

# Answer
# Mornington Crescent, ~~1480~~ 1587 bytes

+107 bytes thanks to Cloudy7

```
Take Northern Line to Moorgate
Take Metropolitan Line to Moorgate
Take Metropolitan Line to Wembley Park
Take Metropolitan Line to Wembley Park
Take Jubilee Line to West Ham
Take Hammersmith & City Line to West Ham
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 West Ham
Take Hammersmith & City Line to West Ham
Take Jubilee Line to Wembley Park
Take Metropolitan Line to Wembley Park
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.

Try it online!
> 2 votes

# Answer
**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...
> 1 votes

# Answer
# 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
> 1 votes

# Answer
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;
        }
    }
}

```
> 0 votes

---
Tags: code-bowling
---


# Question
Title: Find the remaining side of the tangential quadrilateral
(Taken from https://en.wikipedia.org/wiki/File:Tangential\_quadrilateral.svg)

A tangential quadrilateral (see example above) is a quadrilateral in which a circle can be inscribed.

Your task is to find the possible value of `d` given `a`, `b`, and `c`.

# Specs

* `a`, `b`, `c` will all be positive integers.
* If no possible value of `d` exists, output `0`.

# Scoring

This is . Shortest solution in bytes wins.

# Testcases

```
a b c d
3 4 4 3
1 2 3 2
1 5 3 0

```

# Answer
> 7 votes
# Dyalog APL, 4 bytes

```
0⌈-/

```

Try it online!

### How it works

```
0⌈-/  Monadic function train. Argument: (a b c)

  -/  Reduce by subtraction.
      APL evaluates everything from right to left, so this computes
      a - b - c = a - (b - c) = a - b + c.
0⌈    Take the maximum of 0 and a - b + c.

```

# Answer
> 7 votes
# Piet, 32 Codels

Codelsize 20:

### Notes

### Npiet trace images

Valid input \[1, 2, 3\]

Invalid input \[1, 5, 3\]

# Answer
> 5 votes
# 05AB1E, ~~5~~ 4 bytes

Input is taken as:

```
b
a
c

```

Code:

```
-+0M

```

Explanation:

```
      # Inputs: b, a, c
-     # Substract, (a - b).
 +    # Add with implicit input, (a - b + c).
  0   # Push zero on top of the stack.
   M  # Get the largest number that exists in the stack and implicitly print that value.

```

Try it online!

# Answer
> 4 votes
# Jelly, 5 bytes

```
_@/»0

```

Try it online! or verify all test cases.

### How it works

```
_@/»0    Main link. Argument: [a, b, c]

_@/      Reduce by swapped subtraction.
         This computes (a _@ b) _@ c = c - (b - a) = c - b + a.
   »0    Take the maximum of 0 and c - b + a.

```

# Answer
> 4 votes
# MATL, 6 bytes

```
-+OvX>

```

My very first MATL answer! It can probably be shorter, I'd love tips! Input is backwards, e.g.:

```
c
b
a

```

Try it online!.

Explanation:

```
-        #Subtract the top two numbers (c and b)
 +       #Add the top two numbers (c-b and a)
  O      #Push a 0
   v     #Concatenate this into a array
    X>   #Print the smallest value of the array

```

# Answer
> 3 votes
# Cubix, 12 ~~9~~ bytes

This turned out longer than I wanted and then I messed up the spec. I might be able to knock out a byte or 2.

```
@w+?II-.\0O@

```

Wraps onto a cube with side length 2

```
    @ w
    + ?
I I - . \ 0 O @
. . . . . . . .
    . .
    . .

```

Gets `II` integer input twice, `-.` subtract followed by noop, `\` redirect down (in this case around), hits the second `I` input again, `+` adds, `?` conditional that turns left on negative, right on positive and straight through for zero.
Turning left (invalid negative) `w` change lane to the right onto the literal `0` heading right through the `O@` output and terminate.
Straight through (invalid zero) hits `\` reflector and head right onto the literal `0` and the `O@` output terminate.
Turning right (valid positive) travels around the cube, hitting the `O` output on the bottom face, onto the `w` change lane right, that switches the lane to the `@` terminate.

Try it here

# Answer
> 1 votes
## PowerShell, ~~41~~ 38 bytes

```
param($a,$b,$c)[math]::Max(0,$a+$c-$b)

```

Pretty straightforward implementation of the Pitot theorem (*thanks to Martin for remembering the name of it*).

Saved 3 bytes by using the .NET `[math]::Max()` function.

# Answer
> 1 votes
# J, ~~12~~ ~~9~~ ~~8~~ 5 bytes

Input is given as `a, b, c`. Saved a byte inspired by using Dennis's subtraction method.

```
0>.-/

```

## Explanation

```
0>.-/
   -/   reduce argument over subtraction
0>.     greater of the reduction and 0

```

## Test cases

```
   rem =: 0>.-/
   rem 3 3 4
4
   rem 1 2 3
2
   rem 1 5 3
0
   rem"1 > (3 3 4 ; 1 2 3 ; 1 5 3)
4 2 0

```

---

Previously: (`a,c,b` input) `+/@}:-{:)`, `+/@(}:,-@{:)`

# Answer
> 1 votes
# Python, 25 bytes

```
lambda a,b,c:max(0,a-b+c)

```

# Answer
> 1 votes
# Jolf, 4 bytes

```
\r0m4

```

Replace `\r` with a literal return, or try it here! Explanation:

```
\r0m4
   m4  anti-sum of implicit input
\r0    max of `0` and the anti-sum

```

# Answer
> 1 votes
# Reng v.3.3, 33 bytes

```
ii+i-:²1#x1ø
:x²eq!vx1+#x
 ~n%2+<

```

Takes input like `a c b`. Try it here!

The calculation is simple. `i` gets input, so `ii+` is `a + c`, and `i-` is then `(a + c) - b`. Very simple stuff.

The hard part is taking the max with `0`. "What!? How could it be that hard?" Well, I didn't implement inequality in Reng. So we'll have to use math!

**Observation 1:** `max(a,b) = (a+b+|a-b|)/2`

**Observation 2:** `max(a,0) = (a+|a|)/2`

**Observation 3:** `|a| = Sqrt[a^2]`

**Observation 4:** Reng doesn't have square roots, either. Nor does it have power. But knowing that we'll only be taking the square roots of perfect squares, we can use trial and error, starting at 1. That is, our algorithm can look like this:

```
x = 1 to a, iterate:
  if x * x == a break, return X

```

Since we always have `k` being a perfect square, this algorithm always terminates.

So, into the rest of the code explanation!

```
ii+i-:²1#x1ø
:x²eq!vx1+#x
 ~n%2+<

```

## part 1: initialization

I've already explained how `ii+i-` works, so let's look at the rest of the line.

```
     :²1#x1ø

```

`:` duplicates this number. The bottom number will be `a` in `(a + |a|)/2`. Now, we need to take the absolute value of the top value. We can do this using observations 3 and 4. `²` squares the top value, and `1#x` initializes our counter `x` with `1`. Then we go to the next line with

## part 2: square root loop

```
:x²eq!vx1+#x

```

`:` duplicates our maximum value `a` from the top of the stack (for the equality check).  squares our counter `x` and `e` pushes a Boolean representing the equality of  and `a`. If they are equal, `q!` breaks out of the loop by going down (`v`), leaving `|a|` on the stack. Otherwise, we increment `x` (`x1+`) and set `x` to that value (`#x`).

## finalization

```
 ~n%2+<

```

`<` redirects the program to look left. shhh it saves bytes. It's equivalent to this series of steps:

```
+2%n~

```

`+` adds the top two of the stack, thus implementing the first part of `(a + |a|)/2`. `2%` divides that sum by two (`%` is division here because `/` is a mirror). Lastly, we output this as a number (`n`) and terminates the program (`~`).

# Answer
> 1 votes
## JavaScript (ES6), 22 bytes

```
(a,b,c)=>a+c>b?a+c-b:0

```

`Math.max` is too long and there isn't a long enough common subexpression to deduplicate, so that's basically it. If a falsy value had been acceptable, then 21 bytes: `(a,b,c)=>a+c>b&&a+c-b`.

# Answer
> 1 votes
## \>\<\>, 7 bytes

```
-+:0)*n

```

Input assumed to be on the stack, in the order a, c, b.

It does c-b+a, and compares that with zero. Then it outputs either 0 or the answer before it terminates.

Try it online!

# Answer
> 1 votes
## Pyke, 6 bytes

```
-+0]Se

```

Explanation:

```
+-     - do the mathsy bit (a+c)-b
  0]  - create a list with [0, ^]
 Se - Get the maximum value

```

Try it here!

# Answer
> 1 votes
# Mathematica, 13 bytes

```
Max[##2-#,0]&

```

Anonymous function. Takes input in the order *b*, *a*, *c*. The `##2-#` is just some crazy `Sequence`craft that computes `#2+#3-#`. The `Max[..,0]` just takes the maximum of the result and 0.

# Answer
> 0 votes
# MATLAB / Octave, 20 bytes

```
@(a,b,c)max(c-b+a,0)

```

Anonymous function that accepts the three inputs and returns the length of the fourth side. Can be called using `ans(a,b,c)`.

Demo with all test cases

# Answer
> 0 votes
# Python 2, ~~59~~ ~~53~~ 47 bytes

*-6 bytes thanks to @KennyLau!*

```
i=input;a,b,c=i(),i(),i();print(0,a+c-b)[b<a+c]

```

Takes 3 inputs, a, b and c. Then applies the Pitot Theorem (d=a+c-b).

**Ungolfed**

```
a = input()
b = input()
c = input()
if b < a + c:
    print a + c - b
else:
    print 0

```

# Answer
> 0 votes
# Hexagony, 16

```
?{?>+'<'-{?/@.!<

```

Try it online!

In expanded form:

```
  ? { ?
 > + ' <
' - { ? /
 @ . ! <
  . . .

```

This is actually a fairly simple program. First, we always execute the instructions in this order: `?{?'-{?/<'+` which just reads some values and computes `a-b+c`. Now if the value is positive, the `>` sends us north west and we bounce to the lower right `<` and then print the number (`!`) and exit (`@`).

The only really fancy part of the program is how it handles if the result was negative. If this happens, we move south west and execute: `'?`{` which actually attempts to read another integer after moving the memory pointer around a bit and we land back on the place where we read another integer. Since the read fails to find a value, it returns zero and because zero isn't positive we wrap to the upper edge of the hexagon in this configuration, so we hit `/<!.@` to print out the zero and exit.

---
Tags: code-golf, geometry
---


# Question
Title: Write a program whose nontermination is independent of Peano arithmetic
## Challenge

Write a program P, taking no input, such that the proposition “the execution of P eventually terminates” is independent of Peano arithmetic.

## Formal rules

(In case you are a mathematical logician who thinks the above description is too informal.)

One can, in principle, convert some Universal Turing machine *U* (e.g. your favorite programming language) into a Peano arithmetic formula HALT over the variable *p*, where HALT(*p*) encodes the proposition “*U* terminates on the program (Gödel-encoded by) *p*”. The challenge is to find *p* such that neither HALT(*p*) nor ¬HALT(*p*) can be proven in Peano arithmetic.

You may assume your program runs on an ideal machine with unlimited memory and integers/pointers big enough to access it.

## Example

To see that such programs exist, one example is a program that exhaustively searches for a Peano arithmetic proof of 0 = 1. Peano arithmetic proves that this program halts if and only if Peano arithmetic is inconsistent. Since Peano arithmetic is consistent but cannot prove its own consistency, it cannot decide whether this program halts.

However, there are many other propositions independent of Peano arithmetic on which you could base your program.

## Motivation

This challenge was inspired by a new paper by Yedidia and Aaronson (2016) exhibiting a 7,918-state Turing machine whose nontermination is independent of ZFC, a much stronger system than Peano arithmetic. You may be interested in its citation \[22\]. For this challenge, of course, you may use your programming language of choice in place of actual Turing machines.

# Answer
> 34 votes
# Haskell, 838 bytes

“If you want something done, …”

```
import Control.Monad.State
data T=V Int|T:$T|A(T->T)
g=guard
r=runStateT
s!a@(V i)=maybe a id$lookup i s
s!(a:$b)=(s!a):$(s!b)
s@((i,_):_)!A f=A(\a->((i+1,a):s)!f(V$i+1))
c l=do(m,k)<-(`divMod`sum(1<$l)).pred<$>get;g$m>=0;put m;l!!fromEnum k
i&a=V i:$a
i%t=(:$).(i&)<$>t<*>t
x i=c$[4%x i,5%x i,(6&)<$>x i]++map(pure.V)[7..i-1]
y i=c[A<$>z i,1%y i,(2&)<$>y i,3%x i]
z i=(\a e->[(i,e)]!a)<$>y(i+1)
(i?h)p=c[g$any(p#i)h,do q<-y i;i?h$q;i?h$1&q:$p,do f<-z i;a<-x i;g$p#i$f a;c[i?h$A f,do b<-x i;i?h$3&b:$a;i?h$f b],case p of A f->c[(i+1)?h$f$V i,do i?h$f$V 7;(i+1)?(f(V i):h)$f$6&V i];V 1:$q:$r->c[i?(q:h)$r,i?(2&r:h)$V 2:$q];_->mzero]
(V a#i)(V b)=a==b
((a:$b)#i)(c:$d)=(a#i)c&&(b#i)d
(A f#i)(A g)=f(V i)#(i+1)$g$V i
(_#_)_=0<0
main=print$(r(8?map fst(r(y 8)=<<[497,8269,56106533,12033,123263749,10049,661072709])$3&V 7:$(6&V 7))=<<[0..])!!0

```

## Explanation

This program directly searches for a Peano arithmetic proof of 0 = 1. Since PA is consistent, this program never terminates; but since PA cannot prove its own consistency, the nontermination of this program is independent of PA.

`T` is the type of expressions and propositions:

* `A P` represents the proposition ∀*x* \[*P*(*x*)\].
* `(V 1 :$ P) :$ Q` represents the proposition *P**Q*.
* `V 2 :$ P` represents the proposition ¬*P*.
* `(V 3 :$ x) :$ y` represents the proposition *x* = *y*.
* `(V 4 :$ x) :$ y` represents the natural *x* \+ *y*.
* `(V 5 :$ x) :$ y` represents the natural *x**y*.
* `V 6 :$ x` represents the natural S(*x*) = *x* \+ 1.
* `V 7` reprents the natural 0.

In an environment with *i* free variables, we encode expressions, propositions, and proofs as 2×2 integer matrices \[1, 0; *a*, *b*\], as follows:

* M(*i*, ∀*x* \[*P*(*x*)\]) = \[1, 0; 1, 4\] ⋅ M(*i*, λ*x* \[P(x)\])
* M(*i*, λ*x* \[*F*(*x*)\]) = M(*i* \+ 1, *F*(*x*)) where M(*j*, *x*) = \[1, 0; 5 + *i*, 4 + *j*\] for all *j* \> *i*
* M(*i*, *P**Q*) = \[1, 0; 2, 4\] ⋅ M(*i*, *P*) ⋅ M(*i*, *Q*)
* M(*i*, ¬*P*) = \[1, 0; 3, 4\] ⋅ M(*i*, *P*)
* M(*i*, *x* = *y*) = \[1, 0; 4, 4\] ⋅ M(*i*, *x*) ⋅ M(*i*, *y*)
* M(*i*, *x* \+ *y*) = \[1, 0; 1, 4 + *i*\] ⋅ M(*i*, *x*) ⋅ M(*i*, *y*)
* M(*i*, *x**y*) = \[1, 0; 2, 4 + *i*\] ⋅ M(*i*, *x*) ⋅ M(*i*, *y*)
* M(*i*, S *x*) = \[1, 0; 3, 4 + *i*\] ⋅ M(*i*, *x*)
* M(*i*, 0) = \[1, 0; 4, 4 + *i*\]
* M(*i*, (*Γ*, *P*) ⊢ *P*) = \[1, 0; 1, 4\]
* M(*i*, *Γ**P*) = \[1, 0; 2, 4\] ⋅ M(*i*, *Q*) ⋅ M(*i*, *Γ**Q*) ⋅ M(*i*, *Γ**Q**P*)
* M(*i*, *Γ**P*(*x*)) = \[1, 0; 3, 4\] ⋅ M(*i*, λ*x* \[P(x)\]) ⋅ M(*i*, *x*) ⋅ \[1, 0; 1, 2\] ⋅ M(*i*, *Γ* ⊢ ∀*x* P(x))
* M(*i*, *Γ**P*(*x*)) = \[1, 0; 3, 4\] ⋅ M(*i*, λ*x* \[P(x)\]) ⋅ M(*i*, *x*) ⋅ \[1, 0; 2, 2\] ⋅ M(*i*, *y*) ⋅ M(*i*, *Γ**y* = *x*) ⋅ M(*i*, *Γ**P*(*y*))
* M(*i*, *Γ* ⊢ ∀*x*, *P*(*x*)) = \[1, 0; 8, 8\] ⋅ M(*i*, λ*x* \[*Γ**P*(*x*)\])
* M(*i*, *Γ* ⊢ ∀*x*, *P*(*x*)) = \[1, 0; 12, 8\] ⋅ M(*i*, *Γ**P*(0)) ⋅ M(*i*, λ*x* \[(*Γ*, *P*(*x*)) ⊢ *P*(S(*x*))\])
* M(*i*, *Γ**P**Q*) = \[1, 0; 8, 8\] ⋅ M(*i*, (*Γ*, *P*) ⊢ *Q*)
* M(*i*, *Γ**P**Q*) = \[1, 0; 12, 8\] ⋅ M(*i*, (*Γ*, ¬*Q*) ⊢ ¬*P*)

The remaining axioms are encoded numerically and included in the initial environment *Γ*:

* M(0, ∀*x* \[*x* = *x*\]) = \[1, 0; 497, 400\]
* M(0, ∀*x* \[¬(S(*x*) = 0)\]) = \[1, 0; 8269, 8000\]
* M(0, ∀*x**y* \[S(*x*) = S(*y*) → *x* = *y*\]) = \[1, 0; 56106533, 47775744\]
* M(0, ∀*x* \[*x* \+ 0 = *x*\]) = \[1, 0; 12033, 10000\]
* M(0, ∀*y* \[*x* \+ S(*y*) = S(*x* \+ *y*)\]) = \[1, 0; 123263749, 107495424\]
* M(0, ∀*x* \[*x* ⋅ 0 = 0\]) = \[1, 0; 10049, 10000\]
* M(0, ∀*x**y* \[*x* ⋅ S(*y*) = *x**y* \+ *x*\]) = \[1, 0; 661072709, 644972544\]

A proof with matrix \[1, 0; *a*, *b*\] can be checked given only the lower-left corner *a* (or any other value congruent to *a* modulo *b*); the other values are there to enable composition of proofs.

For example, here is a proof that addition is commutative.

* M(0, *Γ* ⊢ ∀*x**y* \[*x* \+ *y* = *y* \+ *x*\]) = \[1, 0; 6651439985424903472274778830412211286042729801174124932726010503641310445578492460637276210966154277204244776748283051731165114392766752978964153601068040044362776324924904132311711526476930755026298356469866717434090029353415862307981531900946916847172554628759434336793920402956876846292776619877110678804972343426850350512203833644, 14010499234317302152403198529613715336094817740448888109376168978138227692104106788277363562889534501599380268163213618740021570705080096139804941973102814335632180523847407060058534443254569282138051511292576687428837652027900127452656255880653718107444964680660904752950049505280000000000000000000000000000000000000000000000000000000\]

You can verify it with the program as follows:

```
*Main> let p = A $ \x -> A $ \y -> V 3 :$ (V 4 :$ x :$ y) :$ (V 4 :$ y :$ x)
*Main> let a = 6651439985424903472274778830412211286042729801174124932726010503641310445578492460637276210966154277204244776748283051731165114392766752978964153601068040044362776324924904132311711526476930755026298356469866717434090029353415862307981531900946916847172554628759434336793920402956876846292776619877110678804972343426850350512203833644
*Main> r(8?map fst(r(y 8)=<<[497,8269,56106533,12033,123263749,10049,661072709])$p)a :: [((),Integer)]
[((),0)]

```

If the proof were invalid you would get the empty list instead.

---
Tags: code-golf, open-ended-function
---


title: Inverse regex of compound interest

text:
# Question
Title: Inverse regex of compound interest
*Koronkorko* is the Finnish word for *compound interest*. We don't want compound interest in our strings, so let's find the shortest possible regular expression to exclude it.

Given a string consisting only of the uppercase alphabetic characters A-Z, determine the shortest possible regular expression that matches the string if it does not contain the substring `KORONKORKO`. Any string that contains `KORONKORKO` as a substring should not be matched by the regex.

Only the characters `A`-`Z`, `[`, `]`, `-`, `^`, , `?`, `*`, `+`, `|`, `(`, and `)` should be used in the expression.

I think this can be done with 118 characters in the expression. Can you make it shorter?

Note: This challenge is from Ohjelmointiputka (in Finnish).

# Answer
# 204 characters

```
(K((O(R(O(NKORO)*(NK(O(RK)?)?)?)?)?)?K)*(O(R(O(NKORO)*(N(K(O(RK?[^KO]|[^KR])|[^KO])|[^K])|[^KN])|[^KO])|[^KR])|[^KO])|[^K])*(K((O(R(O(NKORO)*(NK(O(RK)?)?)?)?)?)?K)*(O(R(O(NKORO)*(N(K(O(RK?)?)?)?)?)?)?)?)?

```

Generated by turning `.*KORONKORKO.*` into a finite state machine, inverting the finite state machine, and turning it back into a regex.
> 6 votes

# Answer
# Python, ~~77~~ ~~79~~ ~~97~~ 118 bytes

**Edit 3:** Rewrite. Uses nested lookaheads

```
^([^K]|K(?=$|[^O]|O(?=$|[^R]|R(?=$|[^O]|O(?=$|[^N]|N(?=$|[^K]|K(?=$|[^O]|O(?=$|[^R]|R(?=$|[^K]|K(?=$|[^O]))))))))))*$

```

Regex 101

**Edit 2:** Added '$|' throughout the regex. Now, if a prefix of KORONKORKO has been matched, the next item to match is end-of-string, a character that ends the prefix, or a character that extends the prefix if it is followed by something that ends the prefix.

This regex works with `re.fullmatch()`, which was added in Python 3.4. To use with `re.match()`, `^` and `$` need to be added to the beginning and end of the pattern, respectively, for 2 more bytes.

```
([^K]|K($|[^O]|O($|[^R]|R($|[^O]|O($|[^N]|N($|[^K]|K($|[^O]|O($|[^R]|R($|[^K]|K($|[^O]))))))))))*

```

Regex101 link

Previous **incorrect** solution (see comments):

```
K|([^K]|K([^O]|O([^R]|R([^O]|O([^N]|N([^K]|K([^O]|O([^R]|R([^K]|K[^O])))))))))*

```

**Edit:** Added single K
> 1 votes

---
Tags: code-golf, regular-expression
---


title: Area under a curve

text:
# Question
Title: Area under a curve
Write a program that when given five integers as input, outputs the value given by the following integral:

* Input is five integers (in any reasonable format) in the order `a b c d e` where each number corresponds to the variables in the image above.
* No built in integral functions allowed.
* Output must be a base ten float, precise to `+/- 1e-3`.

Least number of bytes wins.

# Answer
# CJam, 27 bytes

```
q~W%2/~~[2*\~3*\6*0]fb:-6d/

```

Example input:

```
[1 2 3 4 8]

```

Output:

```
209.33333333333334

```
> 2 votes

# Answer
# CJam, ~~46~~ 43 bytes

```
l~\:D-A3#:K*),])\f{\dK/D+\~\Z$*+@_*@*+K/}:+

```

The arguments are read via STDIN like

```
1 2 3 4 7

```

and the output is printed to STDOUT like

```
135.04650050000018

```

You can increase the precision by changing the `3` in `A3#:K` to a higher number. The higher the number, the longer the program will take to finish.

Try it online here
> 3 votes

# Answer
# R, 71 bytes

If the input is a vector `x <- c(a, b, c, d, e)` then you can compute the integral directly as per @feersum's comment.

```
e=x[5];d=x[4];x[1]*e^3/3+x[2]*e^2/2+x[3]*e-x[1]*d^3/3-x[2]*d^2/2-x[3]*d

```
> 1 votes

# Answer
# JavaScript, 52 bytes

```
(a,b,c,d,e)=>a*e^3/3+b*e^2/2+c*e-a*d^3/3-b*d^2/2-c*d

```

Calculates the indefinite integral at `e` and `d`, then subtract.
> 0 votes

---
Tags: code-golf
---


# Question
Title: Sort, with your hands tied behind your back
The problem is very simple: write a program that accepts a single unsigned integer from the command line, and prints out that many random numbers on the standard output, in ascending order.

For example:

input:

```
5

```

output (you can use any type of whitespace):

```
557
9424
19212
32293
39135

```

However, you are not allowed to define any variables. **Any at all.**

Score is given by code length, shortest wins, and by up-votes if equal.

 The random numbers can be anything generated by a reasonable pseudo-random generator with a uniform distribution: for example, integers at least 8 bits long (no cheap "0 0 0 0 0 1 1 1 1 " one bit solutions, please), or real numbers (e.g. float) between 0 and 1. In dynamically typed languages, the fist assignment counts as definition in our context, so no cheap Matlab solutions, please :)

# Answer
> 7 votes
## J, 8 characters

If we can take the number of numbers to be generated at the end of the program like the Q solution, then:

```
/:~256?~

```

Example:

```
   /:~256?~8
18 21 91 201 212 226 246 253

```

If not, then taking input from the keyboard requires another 8 characters:

```
/:~256?~".1!:1[1

```

# Answer
> 3 votes
# Q, 10

```
{asc x?1f}

```

.

```
q){asc x?1f}5
`s#0.08724017 0.1024432 0.2310108 0.2560658 0.8671096

```

# Answer
> 2 votes
### Perl - 28 26 20 chars

`say sort map rand.$/,1..<>`

I realized the sorting isn't unnecessary, we only need random numbers in ascending order. `rand` will return a real in \[0,1), so just add our iteration counter to each `rand` result.

```
say$_+rand for 1..<>

```

or

```
map{say$_+rand}1..<>

```

# Answer
> 2 votes
## GolfScript, 14 chars

```
~{9.?rand}*]$`

```

Generating random numbers in GolfScript takes quite many characters, especially if you want to pick them from a reasonably large range. Sorting the list takes only one char (`$`), though, and needs no variables.

Same code de-golfed and with comments added:

```
~            # eval input string, turning it into a number
{            # define a code block:
  9.? rand   #   push a random number between 0 and 9<sup>9</sup>-1 onto the stack
} *          # execute the previous code block as many times as the input number indicates
]            # collect the random numbers off the stack into an array
$            # sort the array
`            # un-eval the array for output

```

# Answer
> 2 votes
## Ruby, ~~42~~ 34

```
puts (1..gets.to_i).map{rand}.sort

```

This could probably be made smaller, but don't blame me - I don't even know Ruby. Also, that whitespace after `puts` is significant. Silly language ;)

# Answer
> 1 votes
# Bash, 45 characters

```
eval `yes 'echo $RANDOM;'|head -n$1`|sort -n

```

Put in a file and run `sh file.sh 25` or replace `$1` by any number

# Answer
> 1 votes
# Octave / MATLAB, 23

```
sort(rand(input(""),1))

```

# Answer
> 1 votes
## C, 108 chars

You wanted a C (or derived) answer, so here's one.
Gets the number as the first parameter.
Works successfully with numbers up to 10 or so. With larger numbers, it usually overflows the stack (due to my awful algorithm).

```
f(x,m,r){x&&f(x-(r>m),r>m?printf("%d\n",r),r:m,rand());}
main(c,v)char**v;{srand(time(0));f(atoi(v[1]),0,0);}

```

# Answer
> 1 votes
## R, 19/43(TRUE random) characters

```
sort(runif(scan()))

```

Just for fun, selecting TRUE random numbers:

```
library(random);sort(randomNumbers(scan()))

```

# Answer
> 1 votes
### Scala, 44:

```
(1 to readInt)map(util.Random.nextInt)sorted

```

# Answer
> 0 votes
## Python, 73 characters

```
import sys,random
print sorted(eval("random.random(),"*int(sys.argv[1])))

```

Hopefully imports don't count as defining variables.

# Answer
> 0 votes
# Haskell (102 / 71 chars)

As a proper program (102 chars)

```
import Random
import List
main=getLine>>=(\n->getStdGen>>=(print.sort.take n.randomRs(0,256*n))).read

```

Or in GHCi (71 chars)

```
:m Random List
getLine>>=(`fmap`getStdGen).(sort.).(.randoms).take.read

```

# Answer
> 0 votes
# JavaScript, 85 bytes

```
n=>{o=[];for(i=[];i.length<n;i.push(1))o.push(Math.random());return o.sort().join` `}

```

In JavaScript, arrays are objects, not variables.

# Answer
> 0 votes
## Java 8, 96 bytes

Because Java is obviously the right tool for this ! \[/sarcasm\]

```
n->java.util.stream.Stream.generate(Math::random).limit(n).sorted().forEach(System.out::println)

```

This is a `Consumer<Long>` or anything that can be implicitly cast to `long`. Prints random `double`s.

```
n->                                 // Given an input n
   ...Stream.generate(Math::random) // Generate an infinite stream by calling Math.random()
   .limit(n)                        // Limit the stream to n elements
   .sorted()                        // On the sorted stream
   .forEach(System.out::println)    // Print each element on its own line

```

---
Tags: code-golf, restricted-source, random, sorting
---


# Question
Title: Read n random lines from a potentially huge file
This challenge is about reading random lines from a potentially huge file without reading the whole file into memory.

**Input**

An integer `n` and the name of a text file.

**Output**

`n` lines of the text file chosen uniformly at random without replacement.

You can assume that `n` is in the range 1 to the number of lines in the file.

Be careful when sampling `n` numbers at random from the range that the answer you get is uniform. `rand()%n` in C is not uniform for example. Every outcome must be equally likely.

**Rules and restrictions**

Each line of the text file will have the same number of characters and that will be no more than 80.

Your code must not read any of the contents of text file except:

* Those lines it outputs.
* The first line to work out how many characters per line there are in the text file.

We can assume each character in the text file takes exactly one byte.

Line separators are assumed to be 1 byte long. Solutions may use 2 bytes long line separators only if they specify this need. You may also assume the last line is terminated by a line separator.

Your answer should be a complete program but you can specify the input in any way that is convenient.

**Languages and libraries**

You can use any language or library you like.

**Notes**

There was a concern about calculating the number of lines in the file. As nimi points out in the comments, you can infer this from the file size and the number of chars per line.

**Motivation**

In chat some people asked if this is really a "Do X without Y" question. I interpret this to ask if the restrictions are unusually artificial.

The task of randomly sampling lines from huge files is not uncommon and is in fact one I sometimes have to do. One way to do this is in bash:

`shuf -n <num-lines>`

This is however very slow for large files as it reads in the whole file.

# Answer
# Dyalog APL, 63 bytes

```
⎕NREAD¨t 82l∘,¨l×¯1+⎕?(⎕NSIZE t)÷l←10⍳⍨⎕NREAD 83 80,⍨t←⍞⎕NTIE 0

```

Prompts for file name, then for how many random lines are desired.

### Explanation

Prompt for text input (file name)
`⎕NTIE 0` Tie the file using next available tie number (-1 on a clean system)
`t←` Store the chosen tie number as `t`
`83 80,⍨` Append \[83,80\] yielding \[-1,83,80\]
`⎕NREAD` Read the first 80 bytes of file -1 as 8-bit integers (conversion code 83)
`10⍳⍨` Find the index of the first number 10 (LF)
`l←` Store the line length as `l`
`(⎕NSIZE t)÷` Divide the size of file -1 with the line length
Prompt for numeric input (desired number of lines)
`?` X random selections (without replacement) out the first Y natural numbers
`¯1+` Add -1 to get 0-origin line numbers\*
Multiply by the line length to get the start bytes
`t 82l∘,¨` Prepend \[-1,82,LineLength\] to each start byte (creates list of arguments for `⎕NREAD`)
`⎕NREAD¨` Read each line as 8-bit character (conversion code 82)

### Practical example

File /tmp/records.txt contains:

```
Hello
Think
12345
Klaus
Nilad

```

Make the program RandLines contain the above code verbatim by entering the following into the APL session:

```
∇RandLines
⎕NREAD¨t 82l∘,¨l×¯1+⎕?(⎕NSIZE t)÷l←10⍳⍨⎕NREAD 83 80,⍨t←⍞⎕NTIE 0
∇

```

In the APL session type `RandLines` and press Enter.

The system moves the cursor to the next line, which is a 0-length prompt for character data; enter `/tmp/records.txt`.

The system now outputs `⎕:` and awaits numeric input; enter `4`.

The system outputs four random lines.

### Real life

In reality, you may want to give filename and count as arguments and receive the result as a table. This can be done by entering:

```
RandLs←{↑⎕NREAD¨t 82l∘,¨l×¯1+⍺?(⎕NSIZE t)÷l←10⍳⍨⎕NREAD 83 80,⍨t←⍵⎕NTIE 0}

```

Now you make MyLines contain three random lines with:

```
MyLines←3 RandLs'/tmp/records.txt'

```

How about returning just a single random line if count is not specified:

```
RandL←{⍺←1 ⋄ ↑⎕NREAD¨t 82l∘,¨l×¯1+⍺?(⎕NSIZE t)÷l←10⍳⍨⎕NREAD 83 80,⍨t←⍵⎕NTIE 0}

```

Now you can do both:

```
MyLines←2 RandL'/tmp/records.txt'

```

and (notice absence of left argument):

```
MyLine←RandL'/tmp/records.txt'

```

### Making code readable

Golfed APL one-liners are a bad idea. Here is how I would write in a production system:

```
RandL←{ ⍝ Read X random lines from file Y without reading entire file
    ⍺←1 ⍝ default count
    tie←⍵⎕NTIE 0 ⍝ tie file
    length←10⍳⍨⎕NREAD 83 80,⍨tie ⍝ find first NL
    size←⎕NSIZE tie ⍝ total file length
    starts←length×¯1+⍺?size÷length ⍝ beginning of each line
    ↑⎕NREAD¨tie 82length∘,¨starts ⍝ read each line as character and convert list to table
}

```

---

\*I could save a byte by running in 0-origin mode, which is standard on some APL systems: remove `¯1+` and insert `1+` before `10`.
> 6 votes

# Answer
# Ruby, ~~104~~ ~~94~~ ~~92~~ 90 bytes

File name and number of lines are passed into the command line. For example, if the program is `shuffle.rb` and the file name is `a.txt`, run `ruby shuffle.rb a.txt 3` for three random lines.

-4 bytes from discovering the `open` syntax in Ruby instead of `File.new`

```
f=open$*[0]
puts [*0..f.size/n=f.gets.size+1].sample($*[1].to_i).map{|e|f.seek n*e;f.gets}

```

Also, here's a 85-byte anonymous function solution that takes a string and a number as its arguments.

```
->f,l{f=open f;puts [*0..f.size/n=f.gets.size+1].sample(l).map{|e|f.seek n*e;f.gets}}

```
> 7 votes

# Answer
## Haskell, ~~240~~ ~~224~~ 236 bytes

```
import Test.QuickCheck
import System.IO
g=hGetLine
main=do;f<-getLine;n<-readLn;h<-openFile f ReadMode;l<-(\x->1+sum[1|_<-x])<$>g h;s<-hFileSize h;generate(shuffle[0..div s l-1])>>=mapM(\p->hSeek h(toEnum 0)(l*p)>>g h>>=putStrLn).take n

```

Reads filename and n from stdin.

How it works:

```
main=do
  f<-getLine                   -- read file name from stdin
  n<-readLn                    -- read n from stdin
  h<-openFile f ReadMode       -- open the file
  l<-(\x->1+sum[1|_<-x])<$>g h -- read first line and bind l to it's length +1
                               -- sum[1|_<-x] is a custom length function
                               -- because of type restrictions, otherwise I'd have
                               -- to use "toInteger.length"
  s<-hFileSize h               -- get file size
  generate(shuffle[0..div s l-1])>>=
                               -- shuffle all possible line numbers
  mapM (\->p  ...  ).take n    -- for each of the first n shuffled line numbers
     hSeek h(toEnum 0).(l*p)>> -- jump to that line ("toEnum 0" is short for "AbsoluteSeek")
     g h>>=                    -- read a line from current position
     putStrLn                  -- and print

```

It takes a lot of time and memory to run this program for files with many lines, because of a horrible inefficient `shuffle` function.

Edit: I missed the "random without replacement" part (thanks @feersum for noticing!).
> 5 votes

# Answer
## PowerShell v2+, 209 bytes

```
param($a,$n)
$f=New-Object System.IO.FileStream $a,"Open"
for(;$f.ReadByte()-ne10){$l++}
$t=$f.Length/++$l-1
[byte[]]$z=,0*$l
0..$t|Get-Random -c $n|%{$a=$f.Seek($l*$_,0);$a=$f.Read($z,0,$l-1);-join[char[]]$z}

```

Takes input `$a` as the filename and `$n` as the number of lines. Note that `$a` must be a full-path filename, and assumed to be ANSI encoding.

We then construct a new `FileStream` object, and tell it to access the file `$a` with `Open` privilege.

The `for` loop `.Read()`s through the first line until we hit a `\n` character, incrementing our line-length counter each character. We then set `$t` equal to the size of the file (i.e., how long the stream is) divided by how many characters per line (plus one so it counts the terminator), minus one (since we're zero-indexed). We then construct our buffer `$z` to also be line length.

The final line constructs a dynamic array with the `..` range operator.1 We pipe that array to `Get-Random` with a `-C`ount of `$n` to randomly select `$n` line numbers without repetition. The lucky numbers are piped into a loop with `|%{...}`. Each iteration we `.Seek` to the particular location, and then `.Read` in a line's worth of characters, stored into `$z`. We re-cast `$z` as a char-array and `-join` it together, leaving the resultant string on the pipeline and output is implicit at the end of the program.

*Technically* we should end with a `$f.Close()` call to close out the file, but that costs bytes! :p

### Example

```
a.txt:
a0000000000000000000000000000000000000000000000001
a0000000000000000000000000000000000000000000000002
a0000000000000000000000000000000000000000000000003
a0000000000000000000000000000000000000000000000004
a0000000000000000000000000000000000000000000000005
a0000000000000000000000000000000000000000000000006
a0000000000000000000000000000000000000000000000007
a0000000000000000000000000000000000000000000000008
a0000000000000000000000000000000000000000000000009
a0000000000000000000000000000000000000000000000010

PS C:\Tools\Scripts\golfing> .\read-n-random-lines.ps1 "c:\tools\scripts\golfing\a.txt" 5
a0000000000000000000000000000000000000000000000002
a0000000000000000000000000000000000000000000000001
a0000000000000000000000000000000000000000000000004
a0000000000000000000000000000000000000000000000010
a0000000000000000000000000000000000000000000000006

```

---

1 Technically, this means we can only support a maximum of 50,000 lines, as that's the largest range that can be dynamically created in this manner. :-/ But, we can't just loop a `Get-Random` command `$n` times, discarding duplicates each loop, since that's not deterministic ...
> 3 votes

# Answer
# Python 3, ~~146~~ 139 bytes

```
from random import*
i=input
f=open(i())
l=len(f.readline())
[(f.seek(v*l),print(f.read(l)))for v in sample(range(f.seek(0,2)//l),int(i()))]
#print is here^

```

Input: \[filename\]\n\[lines\]\n

This solution heavily stole from @pppery but ~~is python3.5 only and~~ is a complete program.

Edit: Thanks to @Mego for the inline range and python3.x compatibility. Edit2: Clarification where the print is because i got two comments about it. (Comment is obviously not part of the code or the byte count.)
> 2 votes

# Answer
# Lua, ~~126~~ 122

```
r=io.read;f=io.open(r())c=2+f:read():len()for i=1,r()do f:seek("set",c*math.random(0,f:seek("end")/c-1))print(f:read())end

```

Uses 2 bytes for line breaks. Change the 2 to a 1 for 1. I only have it as 2 because that's what my test file had.

Got myself under the PHP entry, but still 2nd place (currently). Curse you, Ruby entry!
> 2 votes

# Answer
## Bash (well, coreutils), 100 bytes

```
n=`head -1 $2|wc -c`;shuf -i0-$[`stat -c%s $2`/$n] -n$1|xargs -i dd if=$2 bs=$n skip={} count=1 2>&-

```

### Explanation

This avoids reading the whole file using `dd` to extract the portions of the file we need without reading the file entirely, unfortunately it ends up quite large with all the options we have to specify:

`if` is the input file
`bs` is the block size (here we set it to `$n` which is the length of the first line
`skip` is set to the random integers extracted from `shuf` and equates to the `ibs` value skipping `skip`*`ibs` bytes
`count` the number of `ibs` length sections to return
`status=none` is needed to strip out the information normally output by `dd`

We get the line length using `head -1 $2|wc -c` and the filesize with `stat -c%s $2`.

### Usage

Save above as `file.sh` and run using `file.sh n filename`.

### Timings

```
time ~/randlines.sh 4 test.txt
9412647
4124435
7401105
1132619

real    0m0.125s
user    0m0.035s
sys     0m0.061s

```

vs.

```
time shuf -n4 test.txt
1204350
3496441
3472713
3985479

real    0m1.280s
user    0m0.287s
sys     0m0.272s

```

Times above for a 68MiB file generated using `seq 1000000 9999999 > test.txt`.

Thanks to @PeterCordes for his -1 tip!
> 2 votes

# Answer
# Python 3 - ~~161 160~~  149 bytes

```
from random import*;
def f(n,g):f=open(g);l=len(f.readline());r=list(range(f.seek(0,2)/l));shuffle(r);[(f.seek(v*l),print(f.read(l)))for v in r[:k]]

```

This code defines a function which is called like `f(10,'input.txt')`
> 1 votes

# Answer
# C# 259 bytes without duplicates

```
class Program{static void Main(string[]a){int c=Convert.ToInt32(a[1]);var h=File.ReadLines(a[0]);HashSet<int>n=new HashSet<int>();while(n.Count<c)n.Add(new Random().Next(0,h.Count()));for(;c>0;c--)Console.WriteLine(h.Skip(n.ElementAt(c-1)).Take(1).First());}}

```

Ungolfed

```
class Program{static void Main(string[] a)
{
        int c = Convert.ToInt32(a[1]);
        var h = File.ReadLines(a[0]);
        HashSet<int> n = new HashSet<int>();
        while (n.Count < c)
            n.Add(new Random().Next(0, h.Count()));
        for (; c > 0; c--)
            Console.WriteLine(h.Skip(n.ElementAt(c-1)).Take(1).First());
    }
}

```

File.ReadLines is Lazy. This has the additional benefit that all lines can have different length.

Running it would be:

```
sample.exe a.txt 10000

```

# C# 206 bytes with duplicates

```
class Program{static void Main(string[]a){var n=new Random();int c=Convert.ToInt32(a[1]);var h=File.ReadLines(a[0]);for(;c>0;c--)Console.WriteLine(h.Skip((int)(n.NextDouble()*h.Count())).Take(1).First());}}

```

Ungolfed

```
class Program
{
    static void Main(string[] a)
    {
        Random n = new Random();
        int c = Convert.ToInt32(a[1]);
        var h = File.ReadLines(a[0]);
        for (; c > 0; c--)
            Console.WriteLine(h.Skip((int)(n.NextDouble()*h.Count())).Take(1).First());
    }
}

```
> 1 votes

# Answer
# Python (141 bytes)

Keeps each line with equal probability, use with pipes too. It doesn't answer the skip ahead limitation of the question though...

Usage `cat largefile | python randxlines.py 100` or `python randxlines 100 < largefile` (as @petercordes pointed out)

```
import random,sys
N=int(sys.argv[1])
x=['']*N
for c,L in enumerate(sys.stdin):
    t=random.randrange(c+1)
    if(t<N):x[t] = L
print("".join(x))

```
> 1 votes

---
Tags: code-golf, random, file-system
---


title: Implement the dog bash utility

text:
# Question
Title: Implement the dog bash utility
`dog` is a command-line utility that takes in an arbitrary number of arguments, the first of which is the text to be written and the others are arbitrarily many files.

The `dog` utility will split the text in equal portions over these files. If there is a remainder `n`, the first `n` files get an additional byte

`dog` is the opposite of `cat`, as such, forall `x`, the following should hold.

```
$> dog x a.txt b.txt ...
$> cat a.txt b.txt ...
x$>

```

Where `...` indicates arbitrarily many files.

An example (12 bytes, 3 files, can be split evenly):

```
$> ./dog.py "Dogs vs Cats" a.txt b.txt c.txt
$> cat a.txt
Dogs$> cat b.txt
 vs $> cat c.txt
Cats$> cat a.txt b.txt c.txt
Dogs vs Cats$>

```

An example with remainder (13 bytes, 5 files, remainder 3):

```
9$>./dog.py "0123456789abc" a.txt b.txt c.txt d.txt e.txt
$> cat a.txt
012$> cat b.txt
345$> cat c.txt
678$> cat d.txt
9a$> cat e.txt
bc$> cat a.txt b.txt c.txt d.txt e.txt
0123456789abc$>

```

# Answer
> 4 votes
# Pyth - 12 bytes

```
.wMC,cl.zz.z

```

Uses builtin split function and then uses splat-map on the write function. Doesn't work online.

# Answer
> 2 votes
# Python - 181 bytes

```
import sys
a=sys.argv
l=len
d=a[2:]
s=a[1]
n,r=divmod(l(s),l(d))
p=0
for i in range(l(d)):
    with open(d[i],'w') as f:
        o=n+int(i<=n)
        f.write(s[p:p+o])
        p+=o

```

# Answer
> 1 votes
# PHP, 107 bytes

The golfed code:

```
for($i=1;++$i<$argc;fputs(fopen($argv[$i],w),substr($s=$argv[1],($i-2)*$l=ceil(strlen($s)/($argc-2)),$l)));

```

The detailed code:

```
$len = ceil(strlen($argv[1])/($argc - 2));
for ($i = 2; $i < $argc; $i ++) {
    $fh = fopen($argv[$i], 'w');
    fputs($fh, substr($argv[1], ($i - 2) * $len, $len));
    fclose($fh);          // omitted in the golfed version
}

```

# Answer
> 0 votes
### Pure bash: 97

```
s=$1;shift;for((l=${#s}/$#,m=${#s}-l*$#,i=1;i<=$#;p+=q,i++)){
printf "${s:p:q=i>m?l:l+1}">${!i};}

```

As a function: (`p=` is only required for second run)

```
dog() { p=
    s=$1;shift;for((l=${#s}/$#,m=${#s}-l*$#,i=1;i<=$#;p+=q,i++)){
    printf "${s:p:q=i>m?l:l+1}">${!i};}
}

```

Tests

```
$> rm *
$> dog "Dogs vs Cats" a.txt b.txt c.txt
$> ls -l
total 12
-rw-r--r-- 1 user user 4 May 13 22:09 a.txt
-rw-r--r-- 1 user user 4 May 13 22:09 b.txt
-rw-r--r-- 1 user user 4 May 13 22:09 c.txt
$> cat {a,b,c}.txt;echo
Dogs vs Cats
$>

```

All files is 4 byte len and concatenated in right order, contain *"Dogs vs Cats"*.

```
$> rm *
$> dog "$(printf "%s" {0..9} {a..c})" {a..e}.txt
$> ls -l
total 20
-rw-r--r-- 1 user user 3 May 13 22:09 a.txt
-rw-r--r-- 1 user user 3 May 13 22:09 b.txt
-rw-r--r-- 1 user user 3 May 13 22:09 c.txt
-rw-r--r-- 1 user user 2 May 13 22:09 d.txt
-rw-r--r-- 1 user user 2 May 13 22:09 e.txt
$> cat *;echo
0123456789abc
$>

```

Firsts files is 3 byte len and last only 2, concatenated by alphabetic order, contain *"0123456789abc"*.

### Explanation (ungolfing):

If you hit: `declare -f dog`, will answer:

```
$> declare -f dog
dog ()
{
    p=;
    s=$1;
    shift;
    for ((l=${#s}/$#,m=${#s}-l*$#,i=1; i<=$#; p+=q,i++))
    do
        printf "${s:p:q=i>m?l:l+1}" > ${!i};
    done
}

```

This could be written:

```
dog2 ()
{
    position=0;
    string=$1;
    shift;
    partLen=$((${#string}/$#));
    oneMore=$((${#string}-partLen*$#));
    for ((i=1; i<=$#; i++))
    do
        if ((i<=oneMore)); then
            partQuant=$((partLen+1));
        else
            partQuant=$partLen;
        fi;
        printf "${string:position:partQuant}" > ${!i};
        ((position+=partQuant));
    done
}

```

# Answer
> 0 votes
# Ruby, ~~93~~ 87 bytes

Full program using command line arguments.

If I could use `s.slice!` to mutate the string, I'd do that instead of needing to use `s[c..-1]`, but Ruby doesn't let you mutate the strings from argv without duplicating them first

```
s,*t=$*
d,r=s.size.divmod t.size
t.map{|e|open(e,?w)<<s[0,c=(0>r-=1)?d:d+1];s=s[c..-1]}

```

---
Tags: code-golf, string, file-system
---


title: Needs more jQuery!

text:
# Question
Title: Needs more jQuery!
Inspired by this site, this question could potentially be a doozie. People on StackOverflow often overuse jQuery as an answer. Therefore, we need a way to recognize programmatically if a code snippet uses jQuery.

Given a string (which may or may not contain new lines,) of valid Javascript, determine if jQuery is used.

You determine if jQuery is used if the `$` or `jQuery` functions are called.

**Input quirks:**

* Input will always be valid Javascript.
* Input can contain new lines.
* Input can omit a semicolon where it would automatically be inserted
* There will always be only one argument to the jQuery function.
* Dollar signs could exist elsewhere (strings, comments) so be careful.
* No base64 conversion functions will/can be used in input.
* No `eval` will/can be used in input.
* Any referenced variable or function can be assumed to be defined, but will be guaranteed not to produce errors.
* Code snippets will always produce either a truthy or a falsey value, there will be no ambiguous code.
* Comments can exist in either form.

**Rules:**

* No Standard Loopholes
* This is code-golf, the shortest answer wins.
* You must write a program or a function that takes a string as input and returns a truthy value if it uses jQuery, and a falsey value if it does not.
* If someone can provide a valid input that breaks your code or causes it to return an incorrect value, it is not a winning answer.

**Example Test cases:**

*include, but are not limited to:*

```
$('div') // true

console.log("$5.99"); // false

$ += 3; // false, the `$` variable clearly has a different value type here

var a = "span" /* this is a comment */
$(a).each(function(){
 jQuery(this);
}); // true

```

Good luck, and remember, everything's better with a little extra jQuery!

# Answer
# Javascript - 52 byte * .9 * .8 = 37.44

Don't know how valid this is, because it redefines `$` and `jQuery` and evals the input to check if it was called.

```
(x)=>{$=jQuery=()=>alert(1)&3();eval(x+";alert(0)")}

```
> 4 votes

---
Tags: code-golf, string, javascript
---


title: Continuously expanding code

text:
# Question
Title: Continuously expanding code
Your job is to write a program that rewrites and makes itself longer on each run of the program.

# Challenge

The program will print `Hello, World!\n` (`\n` denotes a newline). Then, it will modify its own file so that the new program length is exactly 2x the length at runtime. This modified file when run, will print `Hello, World!\nHello, World!\n`. When run a third time, the file will print `Hello, World!\nHello, World!\nHello, World!\nHello, World!\n`.

More simply, on the `n`th run of the program, it will output `2^(n-1)` instances of `Hello, World!\n`, and have a program length of `2^(n-1)` the length of the original.

This is , so shortest code (before first run) wins. Please comment if you need something is not clear.

**Edit:** To get past the restriction of file-rewriting, your program may print the modified source along with the `Hello, World!\n`s at a **+40%** penalty.

# Answer
# PHP, 100

## More efficient, 101

```
<?$a=$argv[0];$b=file_get_contents($a);file_put_contents($a,$b.substr($b,81,20));echo"Hello World\n";

```

This script is appending an `echo"Hello World";`, but because you said the size should also vary, and because it's shorter, I'm also having this script:

## Shorter, 100

```
<?$a=$argv[0];$b=file_get_contents($a);file_put_contents($a,$b.substr($b,2,98));echo"Hello World\n";

```

This script is appending itself, in a way it adds one Hello World, but this version will overall take more space and takes longer to execute.

## Example

But the scripts don't vary when it comes to the output:

```
root@raspberrypi:~/stack# php hello_expand.php
Hello World
root@raspberrypi:~/stack# php hello_expand.php
Hello World
Hello World
root@raspberrypi:~/stack# php hello_expand.php
Hello World
Hello World
Hello World

```
> 0 votes

---
Tags: code-golf, quine
---


title: Shortest code for longest output

text:
# Question
Title: Shortest code for longest output
This one is pretty simple.

Write the shortest program you can, while generating the most output.

To make it fun, programs that produce infinite output will be disqualified.

The winner is the program with the largest output size/code size ratio.

The results are based on what works on *my* computer, which is a Mac running Mac OS X 10.7.5 with an Intel Core i5 and 8GB of memory.

# Answer
> 18 votes
### Python: 8 chars code, 387420489 chars output -- Ratio: 48427561.125 : 1

```
'a'*9**9

```

We can have the ratio tend to infinity by adding more `**9`s:

```
'a'*9**9**9
'a'*9**9**9**9
etc.

```

For example:

```
'a'*9**9**9**9**9**9

```

which has a ratio of **~10101010108.568** (unimaginably large number).

# Answer
> 16 votes
So, these are all good programs that produce lots of output with very little code, but none of them are *really* short...

**brainfuck, 5 characters, 255 bytes of output**

```
-[.-]

```

I think this is the only use case where brainfuck really excels. I know this one isn't going to win, but I don't think we can possibly do better than the Python example. Not only that, but...

**brainfuck, 4 characters, infinite output**

```
-[.]

```

I conjecture that this is the shortest infinite-output program out there.

Actually, hold on, my mate's just come up with a really good one.

**Python, 80 bytes, unknown amount of output**

```
from datetime import datetime
while datetime.now()!=datetime.max()
 print "This will probably get disqualified"

```

This program will definitely halt eventually, but will only do so after roughly 8,000 years. The exact number of characters output depends on the rate at which your computer can produce characters.

# Answer
> 14 votes
## Perl - 19 bytes, 187200000000000000 bytes output (9852631578947368.42 : 1)

```
print+($]x9e7)x26e7

```

166 petabyes with a single print statement, using no more than 1.7GB of memory.

There's a few things that made this challenge more interesting that I thought it would be. Perl seems to refuse to allocate more than 1GB of memory to any single list. Hence, the 4-byte scalar reference to the inner string may only be repeated *26e7 ≈ 228* times. `$]` is the 'old perl version' number which, as a string, is 8 bytes long, resembling `5.016002`.

With more system memory, it should be able to go higher. Assuming the full 8GB were actually available, you should be able to use `$]x9e8` for the inner string instead, which would output 1.62 exabytes.

# Answer
> 5 votes
## Ruby and Python, 13 chars, 599994 char output, ~46153:1 ratio

```
999999**99999

```

Simply raises a very large number to the power of another very large number. Takes about 20 seconds to run. I can't increase the numbers because that would make the number become Infinity.

(I did this earlier, I am currently working on making a loop for even longer output)

Edit: I did it!

## Ruby, 28 chars, 6e599999 char output, ~6e599998 ratio (I think)

```
a=999999**99999;a.times{p a}

```

Untested (for obvious reasons), but I'm pretty sure the first number is about 1e599994, which multiplied by 599994 is about 6e599999. Theoretically it would work, but I'm not sure if it would crash your computer, so disclaimer: I am not responsible if it harms your computer in any way :P

Of course, you can keep going:

## Ruby, 37 chars, 6e359992800041 char output, ~6e359992800040 ratio

```
a=999999**99999;a.times{a.times{p a}}

```

And so on, but I doubt any computer can handle that :P

# Answer
> 5 votes
If infinite input was allowed,

```
cat /dev/random

```

Since it's not,

```
head -99 /dev/random

```

(25128 output : 20 input = 1256.4:1)

I'm not on a Linux box, but I imagine you could do something like

```
timeout 99d cat /dev/random

```

and get a huge output. (via GigaWatt's response)

# Answer
> 4 votes
## HQ9+, 11471

```
9

```

Actual character count varies depending on the interpreter, but probably around 10000 would be right?

# Answer
> 2 votes
# C#: 108 chars. Ratio: 742123445489230793057592 : 1

```
for(ulong i=0;i<ulong.MaxValue;i++){Console.Write(new WebClient().DownloadString(@"http://bit.ly/dDuoI4"));}

```

It just downloads and prints the wikipedia's *List of law clerks of the Supreme Court of the United States* (4344904 chars) 18446744073709551615 times.

# Answer
> 2 votes
# ~-~! - Ratio: (6444464)/154 ~= 10101010101.583328920493678

```
'=~~~~,~~~~,~~~~:''=|*<%[%]'=',',',':''&*-~|:'''=|*<%[%]''&',',',':'''&*-~|:''''=|*<%[%]'''&',',',':''''&*-~|:''''&':''=|*<%[%]@~~~~,~~~~,~~:''&*-~|:''&':

```

How it works: First, it sets `'` to 4^3, or 64. Then, it makes `''` a function which sets `'` to `'`^4 * times (where * is it's input). `'''` is then made a function which calls `''` with the input as `'`^4. Then, `''''` is made a function which calls `'''` with `'`^4 as it's input. `''''` is then called with an input of 64. Finally, `''` is changed to a function which prints a space * times; this is then called with an input of `'`.

Turns out, in the end, `'` is **6444464**, and my program's length is **154**; punch that into Wolfram|Alpha and it spits out **10101010101.583328920493678**, which it doesn't even bother to calculate. I don't even know how many digits it contains, but 6444 contains 463. Pretty nice for a language that only supports unary explicit numbers and doesn't have an exponent function ;3

I could have made this a lot larger, but, overkill.

# Answer
> 1 votes
## ruby, ~~283~~ ~~96~~ 44 chars

```
a=1e99.times;a{a{a{a{a{puts'a'*99}}}}}}}}}}

```

Not very short, but it compensates for it in output, which is so much I haven't yet been able to measure it.

# Answer
> 1 votes
# Mathematica 9 chars Ratio: ~ 4564112 : 1

The following is a picture of Mathematica input. I haven't figured how to render it in SE.

Here's a screen shot showing the number of digits in the output. `IntegerDigits` converts the output to a list of digits. `Length` counts the number of digits.

Keystrokes to enter: `9`, `ctrl``6`, `9`, `ctrl``6`, `9`, `ctrl``6`, `9`, `ctrl``6`, `9`....

# Answer
> 1 votes
## Javascript: 27 chars; 260,431,976 char output; 9,645,628.74 ratio

```
for(s=i=61;s=btoa(s),i--;)s

```

This code recursively encodes the input `61` to Base64 61 times. Encoding any input of length `n` to Base64 produces an output of length `n * 8/6`, rounded up to a multiple of 4.

This must be run from a JavaScript console environment that natively supports the Base64-encoding function `btoa`. (Any modern browser, but not Node.js.) Note Chrome cannot run higher than `i=61`, while Firefox can only reach `i=60`. Note also that Chrome's console cannot actually display the output because it is too large, but you can verify the result size by running

```
for(s=i=61;s=btoa(s),i--;)s.length

```

If this program were allowed to run for the maximum `i=99`, it would produce a hypothetical output of size **14,566,872,071,840** (14.5 trillion, 14.5e12) chars, for a hypothetical ratio of around 540 billion (5.39e11).

# Answer
> 1 votes
# Befunge-93: 48 characters, about ((2^32)^2)\*10 characters output

Befunge's stack is theoretically infinite, but the numbers that stack stores are limited to the size of an unsigned long integer (here assumed to be 32 bits). Thus, to a Befunge interpreter, (x+1)\>x is false for the proper value of x. We use this fact to first push all values from zero to the maximum (twice, with a one every third number), and then for each value on the stack, we output and decrement it, then pop it when it reaches zero. Eventually the stack empties and the program terminates. I may be a bit off on the output size, but it should be somewhere in that ballpark.

```
>::1# + #1\`# :# _> #- #1 :# :# .# _# .# :# _@

```

# Answer
> 1 votes
## C: 48 chars, approx. (2^32 - 1)\*65090 bytes output

```
main(){for(int i=1<<31;i<~0;)puts("!");main();}

```

Note that the 65090 is not exact, and depends on stack size. The program will eventually stop when it crashes. Also, I could just put a longer and longer string in puts() to make the ration approach infinity, but that seems rather cheaty.

# Answer
> 1 votes
## Ruby, 23 characters - ~500000000000000 (5e14) Output

```
while rand
puts 0
end

```

## Ti-Basic 84, 13 characters - ~3000 Output

```
:Disp 1
:prgmA

```

Name the program `prgmA`

# Answer
> 1 votes
# Python 3, 115 bytes, runs for 7983 years (unknown # of chars)

EDIT: ymbirtt beat me to it .\_.

I know, this isn't really short, and I know that the other Python answer is *much* longer, But I decided to give this a shot.

The program runs for about 8000 years, which, as you know, is a pretty long time.

What it does is continuously get the current time using the `datetime.datetime.now()` function, and it compares it to `9999-12-31 24:59:59.999999`, which is as far as I know the maximum date in Python.

If is *is* equal, the program stops. If it isn't, it continously outputs `a`.

```
import datetime
while 1:
    if str(datetime.datetime.now())=="9999-12-31 24:59:59.999999":exit
    else:print("a")

```

# Answer
> 0 votes
java(131): unknown but finite amount

```
class A{public static void main(String[] args){while(Math.random()>0){for(long l=0;l!=-1;l++){System.out.println("1234567890");}}}}

```

Using the low chance of Math.random() to get to 0 in a loop and then goin 2^64-1 loops thru a foreach with the output 1234567890;

---
Tags: code-golf
---


title: Virtual Keyboard Text Input

text:
# Question
Title: Virtual Keyboard Text Input
On modern game consoles and other devices without traditional keyboards, trying to input text is a nightmare. Having to type with a few buttons and a joystick on a virtual keyboard is annoying, and I like to make as few movements/button presses as possible.

The keyboard you will be using looks like this:

```
+---+---+---+---+---+---+---+---+---+---+
| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 0 |
+---+---+---+---+---+---+---+---+---+---+
| q | w | e | r | t | y | u | i | o | p |
+---+---+---+---+---+---+---+---+---+---+
| a | s | d | f | g | h | j | k | l | - |
+---+---+---+---+---+---+---+---+---+---+
| z | x | c | v | b | n | m | _ | @ | . |
+---+---+---+---+---+---+---+---+---+---+

```

The following operations can be used:

* `L`: move one square to the left on the keyboard (wraps)
* `R`: move one square to the right on the keyboard (wraps)
* `U`: move one square up on the keyboard (wraps)
* `D`: move one square down on the keyboard (wraps)
* `Y`: insert a space
* `B`: move the insertion pointer one space to the left (does nothing if pointer is at the beginning)
* `F`: move the insertion pointer one space to the right (does nothing if pointer is at the end)
* `C`: toggle caps lock
* `A`: insert the selected character at the position of the insertion pointer

Given an input string containing only ASCII characters that can be typed using the above keyboard and commands (matches `[a-zA-Z0-9 _@.-]*`), output a sequence of commands that will result in the output string. The initial position of the cursor is on the `1` key (the top-left), and caps lock is initially off.

## Scoring

For any given string, a naive approach would be, for each character in the string, navigate to the character on the keyboard by the shortest path, toggle caps lock if necessary, and select the character. Such a naive approach would generate a command of length `(length of input string) + (sum of Manhattan distances on keyboard between consecutive non-space characters) + (number of times the string alternates between lowercase and uppercase characters) + (1 if string starts with an uppercase letter else 0)`. For example, the naive approach for `101` would result in `ALARA`, a length 5 command, and `Noob 5` would result in `DDDRRRRRCAUURRRCAADDLLLLAYUUUA`, a length 30 command.

Your submission, however, seeks to do better than the naive approach. For each input string, your submission will receive points equal to the number of commands the naive approach uses minus the number of commands your submission outputs. Your overall score will be the sum of the individual scores.

## Rules

* Submissions will be run on a Cloud9 free virtual workspace. The workspace has 512 MB of RAM, 2 GB of disk space, 8 Intel(R) Xeon(R) CPUs @ 2.50 GHz (full CPU info, found by running `cat /proc/cpuinfo`, can be found here), and is running 64-bit Ubuntu 14.04 Trusty. You may request access to the testing workspace in order to run and score your submission, or I can score it for you.
* Submissions will be run once per test case. Storing state between runs is forbidden. Submissions may not write to or read from any files other than the source file (which may not be modified between runs), with the possible exception of reading an input file if required.
* Submissions are limited to 1 minute of runtime for each test case. Submissions may output multiple solutions, but only the last valid solution within the allotted time will be used for scoring. Failure to output any valid solutions within the allotted time will result in a score of 0 for that test case.
* Please include directions on how to invoke your submission, as well as any tools/libraries that need to be installed that aren't included with a standard Ubuntu 14.04 install.
* The winner will be the submission with the largest score. In the event of a tie, the submission with the better algorithmic complexity will win. If the tie is still not resolved, the first submission to reach the score and algorithmic complexity will win.
* Submissions may not optimize for the test cases. I reserve the right to change the test cases if I feel there is a need.

## Test cases

Format: `input string => naive score`

(if you see any errors in these, please leave a comment with the correction)

```
101 => 5
quip => 12
PPCG => 15
Mego => 25
Noob 5 => 26
penguin => 27
867-5309 => 32
2_sPoOkY_4_mE => 60
The Nineteenth Byte => 76
penguins@SouthPole.org => 95
8xM3R__5ltZgrkJ.-W b => 98
correcthorsebatterystaple => 104
verylongRUNSOFCAPSandnocaps => 118
This is an English sentence. => 122
WNtza.akjzSP2GI0V9X .0epmUQ-mo => 131
Programming Puzzles and Code Golf => 140

```

# Answer
> 2 votes
# C

The score is 193.

```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define LEFT 'L'
#define RIGHT 'R'
#define CAPS 'C'
#define UP 'U'
#define DOWN 'D'
#define SPACE 'Y'
#define CURSORLEFT 'B'
#define CURSORRIGHT 'F'
#define APPLY 'A'
#define TABLEX 10
#define TABLEY 4
#define casediff(A,B) (isupper(A)*islower(B)+islower(A)*isupper(B))
typedef struct {int x; int y;} coord;
coord letters[300];
#define initLetter(letter, X, Y) \
letters[letter].x=X, letters[letter].y=Y
#define initAllLetters(); \
initLetter('1',0,0);\
initLetter('1',0,0);\
initLetter('2',1,0);\
initLetter('2',1,0);\
initLetter('3',2,0);\
initLetter('3',2,0);\
initLetter('4',3,0);\
initLetter('4',3,0);\
initLetter('5',4,0);\
initLetter('5',4,0);\
initLetter('6',5,0);\
initLetter('6',5,0);\
initLetter('7',6,0);\
initLetter('7',6,0);\
initLetter('8',7,0);\
initLetter('8',7,0);\
initLetter('9',8,0);\
initLetter('9',8,0);\
initLetter('0',9,0);\
initLetter('0',9,0);\
initLetter('Q',0,1);\
initLetter('q',0,1);\
initLetter('W',1,1);\
initLetter('w',1,1);\
initLetter('E',2,1);\
initLetter('e',2,1);\
initLetter('R',3,1);\
initLetter('r',3,1);\
initLetter('T',4,1);\
initLetter('t',4,1);\
initLetter('Y',5,1);\
initLetter('y',5,1);\
initLetter('U',6,1);\
initLetter('u',6,1);\
initLetter('I',7,1);\
initLetter('i',7,1);\
initLetter('O',8,1);\
initLetter('o',8,1);\
initLetter('P',9,1);\
initLetter('p',9,1);\
initLetter('A',0,2);\
initLetter('a',0,2);\
initLetter('S',1,2);\
initLetter('s',1,2);\
initLetter('D',2,2);\
initLetter('d',2,2);\
initLetter('F',3,2);\
initLetter('f',3,2);\
initLetter('G',4,2);\
initLetter('g',4,2);\
initLetter('H',5,2);\
initLetter('h',5,2);\
initLetter('J',6,2);\
initLetter('j',6,2);\
initLetter('K',7,2);\
initLetter('k',7,2);\
initLetter('L',8,2);\
initLetter('l',8,2);\
initLetter('-',9,2);\
initLetter('-',9,2);\
initLetter('Z',0,3);\
initLetter('z',0,3);\
initLetter('X',1,3);\
initLetter('x',1,3);\
initLetter('C',2,3);\
initLetter('c',2,3);\
initLetter('V',3,3);\
initLetter('v',3,3);\
initLetter('B',4,3);\
initLetter('b',4,3);\
initLetter('N',5,3);\
initLetter('n',5,3);\
initLetter('M',6,3);\
initLetter('m',6,3);\
initLetter('_',7,3);\
initLetter('_',7,3);\
initLetter('@',8,3);\
initLetter('@',8,3);\
initLetter('.',9,3);\
initLetter('.',9,3);
typedef struct {int length; char instr[300];} movement;
movecasefold(char*instr,coord A, coord B){
    register int i=0;int j;
    if(A.x<B.x)
     if(B.x-A.x<=TABLEX/2)
      for(;B.x-A.x!=i;)instr[i++]=RIGHT;
     else
      for(;TABLEX-B.x+A.x!=i;)instr[i++]=LEFT;
    else if(A.x>B.x)
     if(A.x-B.x<=TABLEX/2)
      for(;A.x-B.x!=i;)instr[i++]=LEFT;
     else
      for(;TABLEX-A.x+B.x!=i;)instr[i++]=RIGHT;
    j=i;
    if(A.y<B.y)
     if(B.y-A.y<=TABLEY/2)
      for(;B.y-A.y!=i-j;)instr[i++]=DOWN;
     else
      for(;TABLEY-B.y+A.y!=i-j;)instr[i++]=UP;
    else if(A.y>B.y)
     if(A.y-B.y<=TABLEY/2)
      for(;A.y-B.y!=i-j;)instr[i++]=UP;
     else
      for(;TABLEY-A.y+B.y!=i-j;)instr[i++]=DOWN;
    instr[i]='\0';
    return i;
}
char sentence[50], oldcase, oldletter;
int sentencelength;
typedef struct {
int sentencetoorder[50];
int ordertosentence[50];
int length;
} order;
ordercopy(order*a, order b){
register int i;
for(i=0;++i<sentencelength;) a->sentencetoorder[i]=b.sentencetoorder[i], a->ordertosentence[i]=b.ordertosentence[i];
a->length=b.length;
}
order currentOrder;
movetwo(char*instr,int A, int B){
    register int j; int i=0;
    if(A<B)
    { for(j=A+1;j<B;j++)
      if(currentOrder.sentencetoorder[j]<currentOrder.sentencetoorder[B])
       instr[i++]=CURSORRIGHT;
    }
    else
    { for(j=A;j>B;j--)
      if(currentOrder.sentencetoorder[j]<currentOrder.sentencetoorder[B])
       instr[i++]=CURSORLEFT;
    }
    if(sentence[B]==' '){
        instr[i++]=SPACE;
        instr[i]='\0';
        return i;
    }
    i+=movecasefold(instr+i,letters[oldletter],letters[sentence[B]]);
    oldletter=sentence[B];
    if(casediff(oldcase,sentence[B]))oldcase=sentence[B],instr[i++]=CAPS;
    instr[i++]=APPLY;
    instr[i]='\0';
    return i;
}
moveall(char*instr){
    int j;int i = 0;
    oldcase='a';
    oldletter='1';
    for(j=0;++j<sentencelength;)
        i+=movetwo(instr+i,currentOrder.ordertosentence[j-1],currentOrder.ordertosentence[j]);
    return i;
}
iteration();
main(){
initAllLetters();
gets(sentence+1);*sentence='1';sentencelength=strlen(sentence);
int i;
for(i=0;++i<sentencelength;)currentOrder.sentencetoorder[i]=currentOrder.ordertosentence[i]=i;
char instr[300];
currentOrder.length=moveall(instr);
puts(instr);
while(iteration());
}
#define inside(item, start, stop) (((start)<=(item))&((item)<(stop)))
#define min(a,b) ((a)<(b)?(a):(b))
#define max(a,b) ((a)>(b)?(a):(b))
iteration(){
char instr[300];
register int i;
int newstart, start, l;
static order oldorder, neworder;
ordercopy(&oldorder,currentOrder);
ordercopy(&neworder,currentOrder);
for(l=0;++l<sentencelength-1;)
for(start=0;++start<sentencelength-l;)
for(newstart=0;++newstart<sentencelength-l;)
if(start!=newstart){
 for(i=0;++i<sentencelength;)
  if(inside(i,start,start+l))currentOrder.ordertosentence[i-start+newstart]=oldorder.ordertosentence[i];
  else if(inside(i,min(start,newstart),max(start+l,newstart+l)))currentOrder.ordertosentence[newstart<start?i+l:(i-l)]=oldorder.ordertosentence[i];
  else currentOrder.ordertosentence[i]=oldorder.ordertosentence[i];
 for(i=0;++i<sentencelength;) currentOrder.sentencetoorder[currentOrder.ordertosentence[i]]=i;
  currentOrder.length=moveall(instr);
 if(currentOrder.length<neworder.length){
  puts(instr);
  ordercopy(&neworder, currentOrder);
 }
}
ordercopy(&currentOrder, neworder);
return neworder.length<oldorder.length;
}

```

Compile with as "gcc virtualKeyboard.c". Run it without arguments "./a.out". It reads the input from stdin and writes the output to stdout.

---
Tags: string, code-challenge, keyboard
---


# Question
Title: Calculate the Fermat Point of a Triangle
This is somewhat similar to The centers of a triangle, but with a different point. The Fermat Point is the point P in triangle ABC such that the value of AP + BP + CP is minimized. There are two cases:

If there is an angle greater than 120 degrees, that vertex is the fermat point. Otherwise, draw equilateral triangles on each of the sides of ABC. Connect the far vertex of each equilateral triangle to the opposite vertex of triangle ABC. Doing this for each of the three equilateral triangles results in a single common point of intersection for all three lines, which is the Fermat Point.

It should run within 5 seconds on a reasonable machine.

**Input**: A set of 3 points, not necessarily integers. This can be taken as a nested array, string, list of tuples, etc. (whatever suits your language).

**Output**: The coordinates of the Fermat point, again, however your language best handles points. Floating point inaccuracies will not be counted against you.

**Test Cases**:

```
[[1, 1], [2, 2], [1, 2]] --> [1.2113248654051871, 1.788675134594813]
[[-1, -1], [-2, -1], [0, 0]] --> [-1, -1]
[[-1, -1], [1, -1], [0, 1]] --> [0, -0.42264973081037427]
[[0, 0], [0.5, 0.8660254037844386], [-5, 0]] --> [0, 0]
[[0, 0], [0, -5], [-0.8660254037844386, 0.5]] --> [0, 0]

```

This is code golf so shortest code wins!

# Answer
# Mathematica, 39 bytes

```
Sum[Norm[p-{x,y}],{p,#}]~NArgMin~{x,y}&

```

Constructs an equation based on the distances between the vertices and a point `{x,y}`. Then uses the `NArgMin` function to find a global minimum for that equation, which will be the Fermat Point by definition.
> 4 votes

# Answer
# Haskell, ~~346~~ ~~291~~ 295 bytes

```
infixl 5£
z=zipWith
(?)=z(-)
t[a,b]=[-b,a]
a¤b=sum$z(*)a b
a%b=t a¤b
r a b c=[c%b/a%b,c%a/a%b]
x£y=2*x¤y<= -sqrt(x¤x*y¤y)
f[a,b,c]|a?b£c?b=b|a?c£b?c=c|b?a£c?a=a|[n,m,p,o]<-c?k a b c++a?k b c a=r[m,o][n,p][c%[n,m],a%[p,o]]
k a b c=map(/2)$z(+)a b?map(signum((b?a)%(c?a))*sqrt 3*)(t$b?a)

```

The same code with some explanations

```
infixl 5£
z=zipWith

-- operator ? : difference of two vectors
(?)=z(-)

-- function t : rotate a vector by +90 degrees
t[a,b]=[-b,a]

-- operator ¤ : scalar product of two vectors ( a¤b = a0 * b0 + a1 * b1 )
a¤b=sum$z(*)a b

-- operator % : "cross product" of two vectors ( a%b = a0 * b1 - a1 * b0 )
--      this returns actually the z coordinate of the 3d cross vector
--      other coordinates are nul since a and b are in the xy plan
a%b=t a¤b

-- function r : solves the system of two linear equations with two variables x0,x1 :
--      a0*x0 - b0*x1 = c0
--      a1*x0 - b1*x1 = c1
r a b c=[c%b/a%b,c%a/a%b]

-- operator £ : returns true if the angle between two vectors is >= 120 degrees
--      x¤y = ||x|| * ||y|| * cos(xyAngle)
--      so xyAngle>=120° is equivalent to : x¤y / (||x|| * ||y||) <= -0.5
x£y=2*x¤y<= -sqrt(x¤x*y¤y)

-- function k : takes 3 points A B C of a triangle and constructs the point C'
--              of the equilateral triangle ABC' which is opposite to C:
--              C' = (A+B)/2 - ((+/-) sqrt(3)/2 * t(AB))
--
--      the sign +/- is given by the sign of the cross vector of AB an AC ((b?a)%(c?a))
--      which is >0 if the angle between AB and AC is positive
--      and <0 otherwise.
k a b c=map(/2)$z(+)a b?map(signum((b?a)%(c?a))*sqrt 3*)(t$b?a)

-- function f : returns the fermat point of a triangle
f[a,b,c]
    |a?b£c?b=b  -- return B if angle ABC >= 120°
    |a?c£b?c=c  -- return C if angle BCA >= 120°
    |b?a£c?a=a  -- return A if angle CAB >= 120°
    |[n,m,p,o]<-c?k a b c++a?k b c a= -- calculate the two segments C'C and A'A
        r[m,o][n,p][c%[n,m],a%[p,o]]  -- return their intersection

```

Tests:

```
main = do
    print $ f [[1, 1], [2, 2], [1, 2]]
    print $ f [[-1, -1], [-2, -1], [0, 0]]
    print $ f [[-1, -1], [1, -1], [0, 1]]
    print $ f [[0, 0], [0.5, 0.8660254037844386], [-5, 0]]
    print $ f [[0, 0], [0, -5], [-0.8660254037844386, 0.5]]

```

Output:

```
[1.2113248654051871,1.7886751345948126]
[-1.0,-1.0]
[0.0,-0.42264973081037427]
[0.0,0.0]
[0.0,0.0]

```
> 3 votes

# Answer
# Python, ~~475~~ ~~448~~ 440 bytes

Any help to golf further is appreciated.

```
from math import *
d=lambda x,y:((x[0]-y[0])**2+(x[1]-y[1])**2)**0.5
s=lambda A,B,C:(d(B,C), d(C,A), d(A,B))
j=lambda a,b,c:acos((b*b+c*c-a*a)/(2*b*c))
t=lambda a,b,c:1/cos(j(a,b,c)-pi/6)
b=lambda A,B,C,p,q,r:[(p*A[i]+q*B[i]+r*C[i])/(p+q+r) for i in [0,1]]
f=lambda A,B,C:A if j(*s(A,B,C)) >= 2*pi/3 else B if j(*s(B,C,A)) >= 2*pi/3 else C if j(*s(C,A,B)) >= 2*pi/3 else b(A,B,C,d(B,C)*t(*s(A,B,C)),d(C,A)*t(*s(B,C,A)),d(A,B)*t(*s(C,A,B)))

```

Ungolfed:

```
from math import *
#distance between two points
d = lambda x,y: ((x[0]-y[0])**2+(x[1]-y[1])**2)**0.5

#given the points, returns the sides
s = lambda A,B,C : (d(B,C), d(C,A), d(A,B))

#given the sides, returns the angle
j = lambda a,b,c : acos((b*b+c*c-a*a)/(2*b*c))

#given the sides, returns secant of that angle
t = lambda a,b,c: 1/cos(j(a,b,c)-pi/6)

#given the sides and the Trilinear co-ordinates, returns the Cartesian co-ordinates
b = lambda A,B,C,p,q,r: [(p*A[i]+q*B[i]+r*C[i])/(p+q+r) for i in [0,1]]

#this one checks if any of the angle is >= 2π/3 returns that point else computes the point
f = lambda A,B,C: A if j(*s(A,B,C)) >= 2*pi/3 else B if j(*s(B,C,A)) >= 2*pi/3 else C if j(*s(C,A,B)) >= 2*pi/3 else b(A,B,C,d(B,C)*t(*s(A,B,C)),d(C,A)*t(*s(B,C,A)),d(A,B)*t(*s(C,A,B)))

```

Input:

```
print('{}'.format(f([1, 1], [2, 2], [1, 2])))
print('{}'.format(f([-1, -1], [-2, -1], [0, 0])))
print('{}'.format(f([-1, -1], [1, -1], [0, 1])))
print('{}'.format(f([0, 0], [0.5, 0.8660254037844386], [-5, 0])))
print('{}'.format(f([0, 0], [0, -5], [-0.8660254037844386, 0.5])))

```

Output:

```
[1.2113248652983113, 1.7886751347016887]
[-1, -1]
[0.0, -0.42264973086764884]
[0, 0]
[0, 0]

```
> 2 votes

# Answer
# Python 3.5, ~~1019~~ ~~1016~~ ~~998~~ ~~982~~ ~~969~~ 953 bytes:

```
from math import*
def H(z,a,b):c=complex;T=lambda A,B:abs(c(*A)-c(*B));d=T(z,a);e=T(z,b);f=T(a,b);g=[d,e,f];h=max(g);g.remove(h);i=acos((sum(i*i for i in g)-(h*h))/(2*g[0]*g[-1]));_=[[z,a],[z,b],[a,b]];j,s,t=cos,sin,atan;N=[[b,a]for a,b in zip([b,a,z],[max(i,key=i.get)if i!=''else''for i in[{(g[0]+(h*j(t(l))),g[1]+(h*s(t(l)))):T(k,(g[0]+(h*j(t(l))),g[1]+(h*s(t(l))))),(g[0]-(h*j(t(l))),g[1]-(h*s(t(l)))):T(k,(g[0]-(h*j(t(l))),g[1]-(h*s(t(l)))))}if l else{(g[0]+h,g[1]):T(k,(g[0]+h,g[1])),(g[0]-h,g[1]):T(k,(g[0]-h,g[1]))}if l==0else''for g,h,l,k in zip([((a[0]+b[0])/2,(a[1]+b[1])/2)for a,b in _],[(3**0.5)*(i/2)for i in[d,e,f]],[-1/p if p else''if p==0else 0for p in[((a[1]-b[1])/(a[0]-b[0]))if a[0]-b[0]else''for a,b in _]],[b,a,z])]])if b!=''];I=N[0][0][1];J=N[0][0][0];K=N[1][0][1];G=N[1][0][0];A=(N[0][1][1]-I)/(N[0][1][0]-J);B=I-(A*J);C=(K-N[1][1][1])/(G-N[1][1][0]);D=K-(C*G);X=(D-B)/(A-C);Y=(A*X)+B;return[[X,Y],[[a,b][h==d],z][h==f]][i>2.0943]

```

**Incredibly** long compared to other answers, but hey, at least it works! I could not be happier with the result I got as this has got to be one of the hardest challenges I have ever done. I am just so ***happy*** that it actually works! :D Now, onto the more technical notes:

* This function takes each ordered pair in as a list or a tuple. For instance, `H((1,1),(2,2),(1,2))` will work, but so will `H([1,1],[2,2],[1,2])`.
* Outputs the coordinates of the points in either a list of integers or floating points depending on whether or not one angle more than or equal to 120º exists.
* This may output `-0.0` in place of `0.0` for some inputs. For instance, the output for the input `[-1, -1], [1, -1], [0, 1]` is `[-0.0, -0.4226497308103744]`. ~~I hope this is okay, although if it isn't, I will change it, though it will cost me a few more bytes.~~ This is okay, as confirmed by OP.
* Should be accurate up to at least `13` to `14` significant figures.

I will try and golf this more over time. An explanation, possibly very long, coming soon.

Try It Online! (Ideone)
> 2 votes

---
Tags: code-golf, math, geometry
---