问:
Patch the Paragraph
In the spirit of Patch the Image, here's a similar challenge but with text.

Challenge

Bit rot has afflicted your precious text! Given a paragraph composed of ASCII characters, with a rectangular hole somewhere in it, your program should try to fill in the hole with appropriate text, so that the paragraph blends as best as possible.

Further definitions

The hole will always be rectangular, and it may span multiple lines.

There will only ever be one hole.

Note that the hole does not necessarily fall on word boundaries (in fact, it usually won't).

The hole will be at most 25% of the input paragraph, but may overlap or extend past the "end" of the "normal" text (see the Euclid or Badger examples below).

Since finding the hole is not the main point of this challenge, it will be composed solely of hash marks # to allow for easy identification.

No other location in the input paragraph will have a hash mark.

Your code cannot use the "normal" text in the examples below - it will only receive and process the text with the hole in it.

The input can be as a single multi-line string, as an array of strings (one element per line), as a file, etc. -- your choice of what is most convenient for your language.

If desired, an optional additional input detailing the coordinates of the hole can be taken (e.g., a tuple of coordinates or the like).

Please describe your algorithm in your submission.

Voting

Voters are asked to judge the entries based on how well the algorithm fills in the text hole. Some suggestions include the following:

Does the filled in area match the approximate distribution of spaces and punctuation as the rest of the paragraph?

Does the filled in area introduce faulty syntax? (e.g., two spaces in a row, a period followed by a question mark, an erroneous sequence like , ,, etc.)

If you squint your eyes (so you're not actually reading the text), can you see where the hole used to be?

If there aren't any CamelCase words outside the hole, does the hole contain any? If there aren't any Capitalized Letters outside the hole, does the hole contain any? If There Are A Lot Of Capitalized Letters Outside The Hole, does the hole contain a proportionate amount?

Validity Criterion

In order for a submission to be considered valid, it must not alter any text of the paragraph outside of the hole (including trailing spaces). A single trailing newline at the very end is optional.

Test Cases

Format is original paragraph in a code block, followed by the same paragraph with a hole. The paragraphs with the hole will be used for input.

1 (Patch the Image)

```<code>In a popular image editing software there is a feature, that patches (The term
used in image processing is inpainting as @minxomat pointed out.) a selected
area of an image, based on the information outside of that patch. And it does a
quite good job, considering it is just a program. As a human, you can sometimes
see that something is wrong, but if you squeeze your eyes or just take a short
glance, the patch seems to fill in the gap quite well.

In a popular image editing software there is a feature, that patches (The term
used in image processing is inpainting as @minxomat pointed out.) a selected
area of an image, #############information outside of that patch. And it does a
quite good job, co#############is just a program. As a human, you can sometimes
see that something#############t if you squeeze your eyes or just take a short
glance, the patch seems to fill in the gap quite well.
</code>```

2 (Gettysburg Address)

```<code>But, in a larger sense, we can not dedicate, we can not consecrate, we can not
hallow this ground. The brave men, living and dead, who struggled here, have
consecrated it, far above our poor power to add or detract. The world will
little note, nor long remember what we say here, but it can never forget what
they did here. It is for us the living, rather, to be dedicated here to the
unfinished work which they who fought here have thus far so nobly advanced. It
is rather for us to be here dedicated to the great task remaining before us-
that from these honored dead we take increased devotion to that cause for which
they gave the last full measure of devotion-that we here highly resolve that
these dead shall not have died in vain-that this nation, under God, shall have
a new birth of freedom-and that government of the people, by the people, for
the people, shall not perish from the earth.

But, in a larger sense, we can not dedicate, we can not consecrate, we can not
hallow this ground. The brave men, living and dead, who struggled here, have
consecrated it, far above our poor power to add or detract. The world will
little note, nor long remember what we say here, but it can never forget what
they did here. It is for us the living, rather, to be dedicated here to the
unfinished work which they who fought here h######################advanced. It
is rather for us to be here dedicated to the######################before us-
that from these honored dead we take increas######################use for which
they gave the last full measure of devotion-######################solve that
these dead shall not have died in vain-that ######################, shall have
a new birth of freedom-and that government of the people, by the people, for
the people, shall not perish from the earth.
</code>```

3 (Lorem Ipsum)

```<code>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do
eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim
ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit
in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur
sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt
mollit anim id est laborum.

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do
eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim
ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
aliquip ex ea commodo conse################irure dolor in reprehenderit
in voluptate velit esse cil################giat nulla pariatur. Excepteur
sint occaecat cupidatat non################in culpa qui officia deserunt
mollit anim id est laborum.
</code>```

4 (Jabberwocky)

```<code>'Twas brillig, and the slithy toves
Did gyre and gimble in the wabe;
All mimsy were the borogoves,
And the mome raths outgrabe.

'Twas brillig, and the slithy toves
Did gyre a######### in the wabe;
All mimsy #########borogoves,
And the mome raths outgrabe.
</code>```

5 (Euclid's proof of the Pythagorean Theorem)

```<code>1.Let ACB be a right-angled triangle with right angle CAB.
2.On each of the sides BC, AB, and CA, squares are drawn,
CBDE, BAGF, and ACIH, in that order. The construction of
squares requires the immediately preceding theorems in Euclid,
and depends upon the parallel postulate. [footnote 14]
3.From A, draw a line parallel to BD and CE. It will
perpendicularly intersect BC and DE at K and L, respectively.
4.Join CF and AD, to form the triangles BCF and BDA.
5.Angles CAB and BAG are both right angles; therefore C, A,
and G are collinear. Similarly for B, A, and H.
6.Angles CBD and FBA are both right angles; therefore angle ABD
equals angle FBC, since both are the sum of a right angle and angle ABC.
7.Since AB is equal to FB and BD is equal to BC, triangle ABD
must be congruent to triangle FBC.
8.Since A-K-L is a straight line, parallel to BD, then rectangle
BDLK has twice the area of triangle ABD because they share the base
BD and have the same altitude BK, i.e., a line normal to their common
base, connecting the parallel lines BD and AL. (lemma 2)
9.Since C is collinear with A and G, square BAGF must be twice in area
to triangle FBC.
10.Therefore, rectangle BDLK must have the same area as square BAGF = AB^2.
11.Similarly, it can be shown that rectangle CKLE must have the same
area as square ACIH = AC^2.
12.Adding these two results, AB^2 + AC^2 = BD × BK + KL × KC
13.Since BD = KL, BD × BK + KL × KC = BD(BK + KC) = BD × BC
14.Therefore, AB^2 + AC^2 = BC^2, since CBDE is a square.

1.Let ACB be a right-angled triangle with right angle CAB.
2.On each of the sides BC, AB, and CA, squares are drawn,
CBDE, BAGF, and ACIH, in that order. The construction of
squares requires the immediately preceding theorems in Euclid,
and depends upon the parallel postulate. [footnote 14]
3.From A, draw a line parallel to BD and CE. It will
perpendicularly intersect BC and DE at K and L, respectively.
4.Join CF and AD, to form the triangles BCF and BDA.
5.Angles CAB and BAG are both right angles; therefore C, A,
and G are #############milarly for B, A, and H.
6.Angles C#############e both right angles; therefore angle ABD
equals ang############# both are the sum of a right angle and angle ABC.
7.Since AB#############FB and BD is equal to BC, triangle ABD
must be co#############iangle FBC.
8.Since A-#############ight line, parallel to BD, then rectangle
BDLK has t############# of triangle ABD because they share the base
BD and hav#############titude BK, i.e., a line normal to their common
base, conn#############rallel lines BD and AL. (lemma 2)
9.Since C #############with A and G, square BAGF must be twice in area
to triangl#############
10.Therefo############# BDLK must have the same area as square BAGF = AB^2.
11.Similar############# shown that rectangle CKLE must have the same
area as square ACIH = AC^2.
12.Adding these two results, AB^2 + AC^2 = BD × BK + KL × KC
13.Since BD = KL, BD × BK + KL × KC = BD(BK + KC) = BD × BC
14.Therefore, AB^2 + AC^2 = BC^2, since CBDE is a square.
</code>```

6 (Badger, Badger, Badger by weebl)

```<code>Badger, badger, badger, badger, badger,
badger, badger, badger, badger, badger
Mushroom, mushroom, a-
Badger, badger, badger, badger, badger,
badger, badger, badger, badger, badger
Mushroom, mushroom, a-
Badger, badger, badger, badger, badger,
badger, badger, badger, badger, badger
Mush-mushroom, a
Badger, badger, badger, badger, badger,
badger, badger, badger, badger, badger
Argh! Snake, a snake!
Snaaake! A snaaaake, oooh its a snake!

Badger, badger, badger, badger, badger,
badger, badger, badger, badger, badger
Mushroom, mushroom, a-
Badger##################badger, badger,
badger##################badger, badger
Mushro##################
Badger##################badger, badger,
badger##################badger, badger
Mush-mushroom, a
Badger, badger, badger, badger, badger,
badger, badger, badger, badger, badger
Argh! Snake, a snake!
Snaaake! A snaaaake, oooh its a snake!
</code>```

答:
C# 5 massive as ever

I threw this together, it's a bit of a mess, but it produces some OK results some of the time. It a mostly-deterministic algorithm, but with some (fixed-seed) randomness added to avoid it producing the same string for similar gaps. It goes to some effort to try to avoid just having columns of spaces either side of the gaps.

It works by tokenizing the input into words and punctuation (punctuation comes from a manually entered list, because I can't be bothered to work out if Unicode can do this for me), so that it can put spaces before words, and not before punctuation, because this is fairly typical. It splits on typical whitespace. In the vein of markov chains (I think), it counts how often each token follows each other token, and then doesn't compute probabilities for this (I figure that because the documents are so tiny, we would do better to bias toward things we see a lot where we can). Then we perform a breadth-first search, filling the space left by the hashes and the 'partial' words either side, with the cost being computed as -fabness(last, cur) * len(cur_with_space), where fabness returns the number of times cur has followed last for each appended token in the generated string. Naturally, we try to minimise the cost. Because we can't always fill the gap with words and punctuation found in the document, it also considers a number of 'special' tokens from certain states, including the partial strings on either side, which we bias against with arbitrarily increased costs.

If the BFS fails to find a solution, then we naively try to pick a random adverb, or just insert spaces to fill the space.

Results

All 6 can be found here: https://gist.github.com/anonymous/5277db726d3f9bdd950b173b19fec82a

The Euclid test-case did not go very well...

Patch the Image

```<code>In a popular image editing software there is a feature, that patches (The term
used in image processing is inpainting as @minxomat pointed out.) a selected
area of an image, that patches information outside of that patch. And it does a
quite good job, co the patch a is just a program. As a human, you can sometimes
see that something In a short it if you squeeze your eyes or just take a short
glance, the patch seems to fill in the gap quite well.
</code>```

Jabberwocky

```<code>'Twas brillig, and the slithy toves
Did gyre and the in in the wabe;
All mimsy the mome borogoves,
And the mome raths outgrabe.
</code>```

Badger

```<code>Badger, badger, badger, badger, badger,
badger, badger, badger, badger, badger
Mushroom, mushroom, a-
Badger, badger, badger, badger, badger,
badger, badger, badger, badger, badger
Mushroom, badger, badger
Badger, badger, badger, badger, badger,
badger, badger, badger, badger, badger
Mush-mushroom, a
Badger, badger, badger, badger, badger,
badger, badger, badger, badger, badger
Argh! Snake, a snake!
Snaaake! A snaaaake, oooh its a snake!
</code>```

_I'm glad with how this one turned out... it's fortuate that "badger, badger," fits, or this one would not have done so well

Code

Run it with

```<code>csc ParaPatch.cs
ParaPatch.exe infile outfile
</code>```

There is quite a lot of it. The only remotely interesting bit is the Fill method. I include the heap implementation, because .NET doesn't have one (WHY MS WHY?!).

using System;
using System.Collections.Generic;
using System.Linq;

namespace ParaPatch
{
    class Program
    {
        private static string[] Filler = new string[] { "may", "will", "maybe", "rather", "perhaps", "reliably", "nineword?", "definitely", "elevenword?", "inexplicably" }; // adverbs
        private static char[] Breaking = new char[] { ' ', '\n', '\r', '\t' };
        private static char[] Punctuation = new char[] { ',', '.', '{', '}', '(', ')', '/', '?', ':', ';', '\'', '\\', '"', ',', '!', '-', '+', '[', ']', '£', '$', '%', '^', '—' };

        private static IEnumerable<string> TokenizeStream(System.IO.StreamReader reader)
        {
            System.Text.StringBuilder sb = new System.Text.StringBuilder();

            HashSet<char> breaking = new HashSet<char>(Breaking);
            HashSet<char> punctuation = new HashSet<char>(Punctuation);

            while (!reader.EndOfStream)
            {
                int ci = reader.Read();
                if (ci == -1) // sanity
                    break;

                char c = (char)ci;

                if (breaking.Contains(c))
                {
                    if (sb.Length > 0)
                        yield return sb.ToString();
                    sb.Clear();
                }
                else if (punctuation.Contains(c))
                {
                    if (sb.Length > 0)
                        yield return sb.ToString();
                    yield return ""+c;
                    sb.Clear();
                }
                else
                {

                    sb.Append(c);
                }
            }

            if (sb.Length > 0)
                yield return sb.ToString();
        }

        private enum DocTokenTypes
        {
            Known,
            LeftPartial,
            RightPartial,
            Unknown,
        }

        private class DocToken
        {
            public DocTokenTypes TokenType { get; private set; }
            public string StringPart { get; private set; }
            public int Length { get; private set; }

            public DocToken(DocTokenTypes tokenType, string stringPart, int length)
            {
                TokenType = tokenType;
                StringPart = stringPart;
                Length = length;
            }
        }

        private static IEnumerable<DocToken> DocumentTokens(IEnumerable<string> tokens)
        {
            foreach (string token in tokens)
            {
                if (token.Contains("#"))
                {
                    int l = token.IndexOf("#");
                    int r = token.LastIndexOf("#");

                    if (l > 0)
                        yield return new DocToken(DocTokenTypes.LeftPartial, token.Substring(0, l), l);

                    yield return new DocToken(DocTokenTypes.Unknown, null, r - l + 1);

                    if (r < token.Length - 1)
                        yield return new DocToken(DocTokenTypes.RightPartial, token.Substring(r + 1), token.Length - r - 1);
                }
                else
                    yield return new DocToken(DocTokenTypes.Known, token, token.Length);
            }
        }

        private class State : IComparable<State>
        {
            // missing readonly params already... maybe C#6 isn't so bad
            public int Remaining { get; private set; }
            public int Position { get; private set; }
            public State Prev { get; private set; }
            public string Token { get; private set; }
            public double H { get; private set; }
            public double Fabness { get; private set; }
            public string FullFilling { get; private set; }

            public State(int remaining, int position, Program.State prev, double fabness, double h, string token, string toAdd)
            {
                Remaining = remaining;
                Position = position;
                Prev = prev;
                H = h;
                Fabness = fabness;
                Token = token;

                FullFilling = prev != null ? prev.FullFilling + toAdd : toAdd;
            }

            public int CompareTo(State other)
            {
                return H.CompareTo(other.H);
            }
        }

        public static void Main(string[] args)
        {
            if (args.Length < 2)
                args = new string[] { "test.txt", "testout.txt" };

            List<DocToken> document;
            using (System.IO.StreamReader reader = new System.IO.StreamReader(args[0], System.Text.Encoding.UTF8))
            {
                document = DocumentTokens(TokenizeStream(reader)).ToList();
            }

            foreach (DocToken cur in document)
            {
                Console.WriteLine(cur.StringPart + " " + cur.TokenType);
            }

            // these are small docs, don't bother with more than 1 ply
            Dictionary<string, Dictionary<string, int>> FollowCounts = new Dictionary<string, Dictionary<string, int>>();
            Dictionary<string, Dictionary<string, int>> PreceedCounts = new Dictionary<string, Dictionary<string, int>>(); // mirror (might be useful)

            HashSet<string> knowns = new HashSet<string>(); // useful to have lying around

            // build counts
            DocToken last = null;
            foreach (DocToken cur in document)
            {
                if (cur.TokenType == DocTokenTypes.Known)
                {
                    knowns.Add(cur.StringPart);
                }

                if (last != null && last.TokenType == DocTokenTypes.Known && cur.TokenType == DocTokenTypes.Known)
                {
                    {
                        Dictionary<string, int> ltable;
                        if (!FollowCounts.TryGetValue(last.StringPart, out ltable))
                        {
                            FollowCounts.Add(last.StringPart, ltable = new Dictionary<string, int>());
                        }

                        int count;
                        if (!ltable.TryGetValue(cur.StringPart, out count))
                        {
                            count = 0;
                        }
                        ltable[cur.StringPart] = count + 1;
                    }

                    {
                        Dictionary<string, int> ctable;
                        if (!PreceedCounts.TryGetValue(cur.StringPart, out ctable))
                        {
                            PreceedCounts.Add(cur.StringPart, ctable = new Dictionary<string, int>());
                        }

                        int count;
                        if (!ctable.TryGetValue(last.StringPart, out count))
                        {
                            count = 0;
                        }
                        ctable[last.StringPart] = count + 1;
                    }
                }

                last = cur;
            }

            // build probability grid (none of this efficient table filling dynamic programming nonsense, A* all the way!)
            // hmm... can't be bothered
            Dictionary<string, Dictionary<string, double>> fabTable = new Dictionary<string, Dictionary<string, double>>();
            foreach (var k in FollowCounts)
            {
                Dictionary<string, double> t = new Dictionary<string, double>();

                // very naive
                foreach (var k2 in k.Value)
                {
                    t.Add(k2.Key, (double)k2.Value);
                }

                fabTable.Add(k.Key, t);
            }

            string[] knarr = knowns.ToArray();
            Random rnd = new Random("ParaPatch".GetHashCode());

            List<string> fillings = new List<string>();
            for (int i = 0; i < document.Count; i++)
            {
                if (document[i].TokenType == DocTokenTypes.Unknown)
                {
                    // shuffle knarr
                    for (int j = 0; j < knarr.Length; j++)
                    {
                        string t = knarr[j];
                        int o = rnd.Next(knarr.Length);
                        knarr[j] = knarr[o];
                        knarr[o] = t;
                    }

                    fillings.Add(Fill(document, fabTable, knarr, i));
                    Console.WriteLine(fillings.Last());
                }
            }

            string filling = string.Join("", fillings);

            int fi = 0;

            using (System.IO.StreamWriter writer = new System.IO.StreamWriter(args[1]))
            using (System.IO.StreamReader reader = new System.IO.StreamReader(args[0]))
            {
                while (!reader.EndOfStream)
                {
                    int ci = reader.Read();
                    if (ci == -1)
                        break;

                    char c = (char)ci;
                    c = c == '#' ? filling[fi++] : c;

                    writer.Write(c);
                    Console.Write(c);
                }
            }

//            using (System.IO.StreamWriter writer = new System.IO.StreamWriter(args[1], false, System.Text.Encoding.UTF8))
//            using (System.IO.StreamReader reader = new System.IO.StreamReader(args[0]))
//            {
//                foreach (char cc in reader.ReadToEnd())
//                {
//                    char c = cc;
//                    c = c == '#' ? filling[fi++] : c;
//
//                    writer.Write(c);
//                    Console.Write(c);
//                }
//            }

            if (args[0] == "test.txt")
                Console.ReadKey(true);
        }

        private static string Fill(List<DocToken> document, Dictionary<string, Dictionary<string, double>> fabTable, string[] knowns, int unknownIndex)
        {
            HashSet<char> breaking = new HashSet<char>(Breaking);
            HashSet<char> punctuation = new HashSet<char>(Punctuation);

            Heap<State> due = new Heap<Program.State>(knowns.Length);

            Func<string, string, double> fabness = (prev, next) =>
            {
                Dictionary<string, double> table;
                if (!fabTable.TryGetValue(prev, out table))
                    return 0; // not fab
                double fab;
                if (!table.TryGetValue(next, out fab))
                    return 0; // not fab
                return fab; // yes fab
            };

            DocToken mostLeft = unknownIndex > 2 ? document[unknownIndex - 2] : null;
            DocToken left = unknownIndex > 1 ? document[unknownIndex - 1] : null;
            DocToken unknown = document[unknownIndex];
            DocToken right = unknownIndex < document.Count - 2 ? document[unknownIndex + 1] : null;
            DocToken mostRight = unknownIndex < document.Count - 3 ? document[unknownIndex + 2] : null;

            // sum of empty space and partials' lengths
            int spaceSize = document[unknownIndex].Length
                + (left != null && left.TokenType == DocTokenTypes.LeftPartial ? left.Length : 0)
                + (right != null && right.TokenType == DocTokenTypes.RightPartial ? right.Length : 0);

            int l = left != null && left.TokenType == DocTokenTypes.LeftPartial ? left.Length : 0;
            int r = l + unknown.Length;

            string defaultPrev =
                left != null && left.TokenType == DocTokenTypes.Known ? left.StringPart :
                mostLeft != null && mostLeft.TokenType == DocTokenTypes.Known ? mostLeft.StringPart :
                "";

            string defaultLast =
                right != null && right.TokenType == DocTokenTypes.Known ? right.StringPart :
                mostRight != null && mostRight.TokenType == DocTokenTypes.Known ? mostRight.StringPart :
                "";

            Func<string, string> topAndTail = str =>
            {
                return str.Substring(l, r - l);
            };

            Func<State, string, double, bool> tryMove = (State prev, string token, double specialFabness) =>
            {
                bool isPunctionuation = token.Length == 1 && punctuation.Contains(token[0]);
                string addStr = isPunctionuation || prev == null ? token : " " + token;
                int addLen = addStr.Length;

                int newRemaining = prev != null ? prev.Remaining - addLen : spaceSize - addLen;
                int oldPosition = prev != null ? prev.Position : 0;
                int newPosition = oldPosition + addLen;

                // check length
                if (newRemaining < 0)
                    return false;

                // check start
                if (oldPosition < l) // implies left is LeftPartial
                {
                    int s = oldPosition;
                    int e = newPosition > l ? l : newPosition;
                    int len = e - s;
                    if (addStr.Substring(0, len) != left.StringPart.Substring(s, len))
                        return false; // doesn't match LeftPartial
                }

                // check end
                if (newPosition > r) // implies right is RightPartial
                {
                    int s = oldPosition > r ? oldPosition : r;
                    int e = newPosition;
                    int len = e - s;
                    if (addStr.Substring(s - oldPosition, len) != right.StringPart.Substring(s - r, len))
                        return false; // doesn't match RightPartial
                }

                if (newRemaining == 0)
                {
                    // could try to do something here (need to change H)
                }

                string prevToken = prev != null ? prev.Token : defaultPrev;
                bool isLastunctionuation = prevToken.Length == 1 && punctuation.Contains(prevToken[0]);

                if (isLastunctionuation && isPunctionuation) // I hate this check, it's too aggresive to be realistic
                    specialFabness -= 50;

                double fab = fabness(prevToken, token);

                if (fab < 1 && (token == prevToken))
                    fab = -1; // bias against unrecognised repeats

                double newFabness = (prev != null ? prev.Fabness : 0.0)
                    - specialFabness // ... whatever this is
                    - fab * addLen; // how probabilistic

                double h = newFabness; // no h for now

                State newState = new Program.State(newRemaining, newPosition, prev, newFabness, h, token, addStr);

//                Console.WriteLine((prev != null ? prev.Fabness : 0) + "\t" + specialFabness);
//                Console.WriteLine(newFabness + "\t" + h + "\t" + due.Count + "\t" + fab + "*" + addLen + "\t" + newState.FullFilling);

                due.Add(newState);
                return true;
            };

            // just try everything everything
            foreach (string t in knowns)
                tryMove(null, t, 0);

            if (left != null && left.TokenType == DocTokenTypes.LeftPartial)
                tryMove(null, left.StringPart, -1);

            while (!due.Empty)
            {
                State next = due.RemoveMin();

                if (next.Remaining == 0)
                {
                    // we have a winner!!
                    return topAndTail(next.FullFilling);
                }

                // just try everything
                foreach (string t in knowns)
                    tryMove(next, t, 0);
                if (right != null && right.TokenType == DocTokenTypes.RightPartial)
                    tryMove(next, right.StringPart, -5); // big bias
            }

            // make this a tad less stupid, non?
            return Filler.FirstOrDefault(f => f.Length == unknown.Length) ?? new String(' ', unknown.Length); // oh dear...
        }
    }

    //
    // Ultilities
    //

    public class Heap<T> : System.Collections.IEnumerable where T : IComparable<T>
    {
        // arr is treated as offset by 1, all idxes stored need to be -1'd to get index in arr
        private T[] arr;
        private int end = 0;

        private void s(int idx, T val)
        {
            arr[idx - 1] = val;
        }

        private T g(int idx)
        {
            return arr[idx - 1];
        }

        public Heap(int isize)
        {
            if (isize < 1)
                throw new ArgumentException("Cannot be less than 1", "isize");

            arr = new T[isize];
        }

        private int up(int idx)
        {
            return idx / 2;
        }

        private int downLeft(int idx)
        {
            return idx * 2;
        }

        private int downRight(int idx)
        {
            return idx * 2 + 1;
        }

        private void swap(int a, int b)
        {
            T t = g(a);
            s(a, g(b));
            s(b, t);
        }

        private void moveUp(int idx, T t)
        {
        again:
            if (idx == 1)
            {
                s(1, t);
                return; // at end
            }

            int nextUp = up(idx);
            T n = g(nextUp);
            if (n.CompareTo(t) > 0)
            {
                s(idx, n);
                idx = nextUp;
                goto again;
            }
            else
            {
                s(idx, t);
            }
        }

        private void moveDown(int idx, T t)
        {
        again:
            int nextLeft = downLeft(idx);
            int nextRight = downRight(idx);

            if (nextLeft > end)
            {
                s(idx, t);
                return; // at end
            }
            else if (nextLeft == end)
            { // only need to check left
                T l = g(nextLeft);

                if (l.CompareTo(t) < 0)
                {
                    s(idx, l);
                    idx = nextLeft;
                    goto again;
                }
                else
                {
                    s(idx, t);
                }
            }
            else
            { // check both
                T l = g(nextLeft);
                T r = g(nextRight);

                if (l.CompareTo(r) < 0)
                { // left smaller (favour going right if we can)
                    if (l.CompareTo(t) < 0)
                    {
                        s(idx, l);
                        idx = nextLeft;
                        goto again;
                    }
                    else
                    {
                        s(idx, t);
                    }
                }
                else
                { // right smaller or same
                    if (r.CompareTo(t) < 0)
                    {
                        s(idx, r);
                        idx = nextRight;
                        goto again;
                    }
                    else
                    {
                        s(idx, t);
                    }
                }
            }
        }

        public void Clear()
        {
            end = 0;
        }

        public void Trim()
        {
            if (end == 0)
                arr = new T[1]; // don't /ever/ make arr len 0
            else
            {
                T[] narr = new T[end];
                for (int i = 0; i < end; i++)
                    narr[i] = arr[i];
                arr = narr;
            }
        }

        private void doubleSize()
        {
            T[] narr = new T[arr.Length * 2];
            for (int i = 0; i < end; i++)
                narr[i] = arr[i];
            arr = narr;
        }

        public void Add(T item)
        {
            if (end == arr.Length)
            {
                // resize
                doubleSize();
            }

            end++;
            moveUp(end, item);
        }

        public T RemoveMin()
        {
            if (end < 1)
                throw new Exception("No items, mate.");

            T min = g(1);

            end--;
            if (end > 0)
                moveDown(1, g(end + 1));

            return min;
        }

        public bool Empty
        {
            get
            {
                return end == 0;
            }
        }

        public int Count
        {
            get
            {
                return end;
            }
        }

        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }

        public IEnumerator<T> GetEnumerator()
        {
            return (IEnumerator<T>)arr.GetEnumerator();
        }
    }
}
```

Title: Patch the Paragraph

Body:
C# 5 massive as ever

I threw this together, it's a bit of a mess, but it produces some OK results some of the time. It a mostly-deterministic algorithm, but with some (fixed-seed) randomness added to avoid it producing the same string for similar gaps. It goes to some effort to try to avoid just having columns of spaces either side of the gaps.

It works by tokenizing the input into words and punctuation (punctuation comes from a manually entered list, because I can't be bothered to work out if Unicode can do this for me), so that it can put spaces before words, and not before punctuation, because this is fairly typical. It splits on typical whitespace. In the vein of markov chains (I think), it counts how often each token follows each other token, and then doesn't compute probabilities for this (I figure that because the documents are so tiny, we would do better to bias toward things we see a lot where we can). Then we perform a breadth-first search, filling the space left by the hashes and the 'partial' words either side, with the cost being computed as -fabness(last, cur) * len(cur_with_space), where fabness returns the number of times cur has followed last for each appended token in the generated string. Naturally, we try to minimise the cost. Because we can't always fill the gap with words and punctuation found in the document, it also considers a number of 'special' tokens from certain states, including the partial strings on either side, which we bias against with arbitrarily increased costs.

If the BFS fails to find a solution, then we naively try to pick a random adverb, or just insert spaces to fill the space.

Results

All 6 can be found here: https://gist.github.com/anonymous/5277db726d3f9bdd950b173b19fec82a

The Euclid test-case did not go very well...

Patch the Image

In a popular image editing software there is a feature, that patches (The term
used in image processing is inpainting as @minxomat pointed out.) a selected
area of an image, that patches information outside of that patch. And it does a
quite good job, co the patch a is just a program. As a human, you can sometimes
see that something In a short it if you squeeze your eyes or just take a short
glance, the patch seems to fill in the gap quite well.

Jabberwocky

'Twas brillig, and the slithy toves
Did gyre and the in in the wabe;
All mimsy the mome borogoves,
And the mome raths outgrabe.

Badger

Badger, badger, badger, badger, badger,
badger, badger, badger, badger, badger
Mushroom, mushroom, a-
Badger, badger, badger, badger, badger,
badger, badger, badger, badger, badger
Mushroom, badger, badger
Badger, badger, badger, badger, badger,
badger, badger, badger, badger, badger
Mush-mushroom, a
Badger, badger, badger, badger, badger,
badger, badger, badger, badger, badger
Argh! Snake, a snake!
Snaaake! A snaaaake, oooh its a snake!

_I'm glad with how this one turned out... it's fortuate that "badger, badger," fits, or this one would not have done so well

Code

Run it with

csc ParaPatch.cs
ParaPatch.exe infile outfile

There is quite a lot of it. The only remotely interesting bit is the Fill method. I include the heap implementation, because .NET doesn't have one (WHY MS WHY?!).

using System;
using System.Collections.Generic;
using System.Linq;

namespace ParaPatch
{
    class Program
    {
        private static string[] Filler = new string[] { "may", "will", "maybe", "rather", "perhaps", "reliably", "nineword?", "definitely", "elevenword?", "inexplicably" }; // adverbs
        private static char[] Breaking = new char[] { ' ', '\n', '\r', '\t' };
        private static char[] Punctuation = new char[] { ',', '.', '{', '}', '(', ')', '/', '?', ':', ';', '\'', '\\', '"', ',', '!', '-', '+', '[', ']', '£', '$', '%', '^', '—' };

        private static IEnumerable<string> TokenizeStream(System.IO.StreamReader reader)
        {
            System.Text.StringBuilder sb = new System.Text.StringBuilder();

            HashSet<char> breaking = new HashSet<char>(Breaking);
            HashSet<char> punctuation = new HashSet<char>(Punctuation);

            while (!reader.EndOfStream)
            {
                int ci = reader.Read();
                if (ci == -1) // sanity
                    break;

                char c = (char)ci;

                if (breaking.Contains(c))
                {
                    if (sb.Length > 0)
                        yield return sb.ToString();
                    sb.Clear();
                }
                else if (punctuation.Contains(c))
                {
                    if (sb.Length > 0)
                        yield return sb.ToString();
                    yield return ""+c;
                    sb.Clear();
                }
                else
                {

                    sb.Append(c);
                }
            }

            if (sb.Length > 0)
                yield return sb.ToString();
        }

        private enum DocTokenTypes
        {
            Known,
            LeftPartial,
            RightPartial,
            Unknown,
        }

        private class DocToken
        {
            public DocTokenTypes TokenType { get; private set; }
            public string StringPart { get; private set; }
            public int Length { get; private set; }

            public DocToken(DocTokenTypes tokenType, string stringPart, int length)
            {
                TokenType = tokenType;
                StringPart = stringPart;
                Length = length;
            }
        }

        private static IEnumerable<DocToken> DocumentTokens(IEnumerable<string> tokens)
        {
            foreach (string token in tokens)
            {
                if (token.Contains("#"))
                {
                    int l = token.IndexOf("#");
                    int r = token.LastIndexOf("#");

                    if (l > 0)
                        yield return new DocToken(DocTokenTypes.LeftPartial, token.Substring(0, l), l);

                    yield return new DocToken(DocTokenTypes.Unknown, null, r - l + 1);

                    if (r < token.Length - 1)
                        yield return new DocToken(DocTokenTypes.RightPartial, token.Substring(r + 1), token.Length - r - 1);
                }
                else
                    yield return new DocToken(DocTokenTypes.Known, token, token.Length);
            }
        }

        private class State : IComparable<State>
        {
            // missing readonly params already... maybe C#6 isn't so bad
            public int Remaining { get; private set; }
            public int Position { get; private set; }
            public State Prev { get; private set; }
            public string Token { get; private set; }
            public double H { get; private set; }
            public double Fabness { get; private set; }
            public string FullFilling { get; private set; }

            public State(int remaining, int position, Program.State prev, double fabness, double h, string token, string toAdd)
            {
                Remaining = remaining;
                Position = position;
                Prev = prev;
                H = h;
                Fabness = fabness;
                Token = token;

                FullFilling = prev != null ? prev.FullFilling + toAdd : toAdd;
            }

            public int CompareTo(State other)
            {
                return H.CompareTo(other.H);
            }
        }

        public static void Main(string[] args)
        {
            if (args.Length < 2)
                args = new string[] { "test.txt", "testout.txt" };

            List<DocToken> document;
            using (System.IO.StreamReader reader = new System.IO.StreamReader(args[0], System.Text.Encoding.UTF8))
            {
                document = DocumentTokens(TokenizeStream(reader)).ToList();
            }

            foreach (DocToken cur in document)
            {
                Console.WriteLine(cur.StringPart + " " + cur.TokenType);
            }

            // these are small docs, don't bother with more than 1 ply
            Dictionary<string, Dictionary<string, int>> FollowCounts = new Dictionary<string, Dictionary<string, int>>();
            Dictionary<string, Dictionary<string, int>> PreceedCounts = new Dictionary<string, Dictionary<string, int>>(); // mirror (might be useful)

            HashSet<string> knowns = new HashSet<string>(); // useful to have lying around

            // build counts
            DocToken last = null;
            foreach (DocToken cur in document)
            {
                if (cur.TokenType == DocTokenTypes.Known)
                {
                    knowns.Add(cur.StringPart);
                }

                if (last != null && last.TokenType == DocTokenTypes.Known && cur.TokenType == DocTokenTypes.Known)
                {
                    {
                        Dictionary<string, int> ltable;
                        if (!FollowCounts.TryGetValue(last.StringPart, out ltable))
                        {
                            FollowCounts.Add(last.StringPart, ltable = new Dictionary<string, int>());
                        }

                        int count;
                        if (!ltable.TryGetValue(cur.StringPart, out count))
                        {
                            count = 0;
                        }
                        ltable[cur.StringPart] = count + 1;
                    }

                    {
                        Dictionary<string, int> ctable;
                        if (!PreceedCounts.TryGetValue(cur.StringPart, out ctable))
                        {
                            PreceedCounts.Add(cur.StringPart, ctable = new Dictionary<string, int>());
                        }

                        int count;
                        if (!ctable.TryGetValue(last.StringPart, out count))
                        {
                            count = 0;
                        }
                        ctable[last.StringPart] = count + 1;
                    }
                }

                last = cur;
            }

            // build probability grid (none of this efficient table filling dynamic programming nonsense, A* all the way!)
            // hmm... can't be bothered
            Dictionary<string, Dictionary<string, double>> fabTable = new Dictionary<string, Dictionary<string, double>>();
            foreach (var k in FollowCounts)
            {
                Dictionary<string, double> t = new Dictionary<string, double>();

                // very naive
                foreach (var k2 in k.Value)
                {
                    t.Add(k2.Key, (double)k2.Value);
                }

                fabTable.Add(k.Key, t);
            }

            string[] knarr = knowns.ToArray();
            Random rnd = new Random("ParaPatch".GetHashCode());

            List<string> fillings = new List<string>();
            for (int i = 0; i < document.Count; i++)
            {
                if (document[i].TokenType == DocTokenTypes.Unknown)
                {
                    // shuffle knarr
                    for (int j = 0; j < knarr.Length; j++)
                    {
                        string t = knarr[j];
                        int o = rnd.Next(knarr.Length);
                        knarr[j] = knarr[o];
                        knarr[o] = t;
                    }

                    fillings.Add(Fill(document, fabTable, knarr, i));
                    Console.WriteLine(fillings.Last());
                }
            }

            string filling = string.Join("", fillings);

            int fi = 0;

            using (System.IO.StreamWriter writer = new System.IO.StreamWriter(args[1]))
            using (System.IO.StreamReader reader = new System.IO.StreamReader(args[0]))
            {
                while (!reader.EndOfStream)
                {
                    int ci = reader.Read();
                    if (ci == -1)
                        break;

                    char c = (char)ci;
                    c = c == '#' ? filling[fi++] : c;

                    writer.Write(c);
                    Console.Write(c);
                }
            }

//            using (System.IO.StreamWriter writer = new System.IO.StreamWriter(args[1], false, System.Text.Encoding.UTF8))
//            using (System.IO.StreamReader reader = new System.IO.StreamReader(args[0]))
//            {
//                foreach (char cc in reader.ReadToEnd())
//                {
//                    char c = cc;
//                    c = c == '#' ? filling[fi++] : c;
//
//                    writer.Write(c);
//                    Console.Write(c);
//                }
//            }

            if (args[0] == "test.txt")
                Console.ReadKey(true);
        }

        private static string Fill(List<DocToken> document, Dictionary<string, Dictionary<string, double>> fabTable, string[] knowns, int unknownIndex)
        {
            HashSet<char> breaking = new HashSet<char>(Breaking);
            HashSet<char> punctuation = new HashSet<char>(Punctuation);

            Heap<State> due = new Heap<Program.State>(knowns.Length);

            Func<string, string, double> fabness = (prev, next) =>
            {
                Dictionary<string, double> table;
                if (!fabTable.TryGetValue(prev, out table))
                    return 0; // not fab
                double fab;
                if (!table.TryGetValue(next, out fab))
                    return 0; // not fab
                return fab; // yes fab
            };

            DocToken mostLeft = unknownIndex > 2 ? document[unknownIndex - 2] : null;
            DocToken left = unknownIndex > 1 ? document[unknownIndex - 1] : null;
            DocToken unknown = document[unknownIndex];
            DocToken right = unknownIndex < document.Count - 2 ? document[unknownIndex + 1] : null;
            DocToken mostRight = unknownIndex < document.Count - 3 ? document[unknownIndex + 2] : null;

            // sum of empty space and partials' lengths
            int spaceSize = document[unknownIndex].Length
                + (left != null && left.TokenType == DocTokenTypes.LeftPartial ? left.Length : 0)
                + (right != null && right.TokenType == DocTokenTypes.RightPartial ? right.Length : 0);

            int l = left != null && left.TokenType == DocTokenTypes.LeftPartial ? left.Length : 0;
            int r = l + unknown.Length;

            string defaultPrev =
                left != null && left.TokenType == DocTokenTypes.Known ? left.StringPart :
                mostLeft != null && mostLeft.TokenType == DocTokenTypes.Known ? mostLeft.StringPart :
                "";

            string defaultLast =
                right != null && right.TokenType == DocTokenTypes.Known ? right.StringPart :
                mostRight != null && mostRight.TokenType == DocTokenTypes.Known ? mostRight.StringPart :
                "";

            Func<string, string> topAndTail = str =>
            {
                return str.Substring(l, r - l);
            };

            Func<State, string, double, bool> tryMove = (State prev, string token, double specialFabness) =>
            {
                bool isPunctionuation = token.Length == 1 && punctuation.Contains(token[0]);
                string addStr = isPunctionuation || prev == null ? token : " " + token;
                int addLen = addStr.Length;

                int newRemaining = prev != null ? prev.Remaining - addLen : spaceSize - addLen;
                int oldPosition = prev != null ? prev.Position : 0;
                int newPosition = oldPosition + addLen;

                // check length
                if (newRemaining < 0)
                    return false;

                // check start
                if (oldPosition < l) // implies left is LeftPartial
                {
                    int s = oldPosition;
                    int e = newPosition > l ? l : newPosition;
                    int len = e - s;
                    if (addStr.Substring(0, len) != left.StringPart.Substring(s, len))
                        return false; // doesn't match LeftPartial
                }

                // check end
                if (newPosition > r) // implies right is RightPartial
                {
                    int s = oldPosition > r ? oldPosition : r;
                    int e = newPosition;
                    int len = e - s;
                    if (addStr.Substring(s - oldPosition, len) != right.StringPart.Substring(s - r, len))
                        return false; // doesn't match RightPartial
                }

                if (newRemaining == 0)
                {
                    // could try to do something here (need to change H)
                }

                string prevToken = prev != null ? prev.Token : defaultPrev;
                bool isLastunctionuation = prevToken.Length == 1 && punctuation.Contains(prevToken[0]);

                if (isLastunctionuation && isPunctionuation) // I hate this check, it's too aggresive to be realistic
                    specialFabness -= 50;

                double fab = fabness(prevToken, token);

                if (fab < 1 && (token == prevToken))
                    fab = -1; // bias against unrecognised repeats

                double newFabness = (prev != null ? prev.Fabness : 0.0)
                    - specialFabness // ... whatever this is
                    - fab * addLen; // how probabilistic

                double h = newFabness; // no h for now

                State newState = new Program.State(newRemaining, newPosition, prev, newFabness, h, token, addStr);

//                Console.WriteLine((prev != null ? prev.Fabness : 0) + "\t" + specialFabness);
//                Console.WriteLine(newFabness + "\t" + h + "\t" + due.Count + "\t" + fab + "*" + addLen + "\t" + newState.FullFilling);

                due.Add(newState);
                return true;
            };

            // just try everything everything
            foreach (string t in knowns)
                tryMove(null, t, 0);

            if (left != null && left.TokenType == DocTokenTypes.LeftPartial)
                tryMove(null, left.StringPart, -1);

            while (!due.Empty)
            {
                State next = due.RemoveMin();

                if (next.Remaining == 0)
                {
                    // we have a winner!!
                    return topAndTail(next.FullFilling);
                }

                // just try everything
                foreach (string t in knowns)
                    tryMove(next, t, 0);
                if (right != null && right.TokenType == DocTokenTypes.RightPartial)
                    tryMove(next, right.StringPart, -5); // big bias
            }

            // make this a tad less stupid, non?
            return Filler.FirstOrDefault(f => f.Length == unknown.Length) ?? new String(' ', unknown.Length); // oh dear...
        }
    }

    //
    // Ultilities
    //

    public class Heap<T> : System.Collections.IEnumerable where T : IComparable<T>
    {
        // arr is treated as offset by 1, all idxes stored need to be -1'd to get index in arr
        private T[] arr;
        private int end = 0;

        private void s(int idx, T val)
        {
            arr[idx - 1] = val;
        }

        private T g(int idx)
        {
            return arr[idx - 1];
        }

        public Heap(int isize)
        {
            if (isize < 1)
                throw new ArgumentException("Cannot be less than 1", "isize");

            arr = new T[isize];
        }

        private int up(int idx)
        {
            return idx / 2;
        }

        private int downLeft(int idx)
        {
            return idx * 2;
        }

        private int downRight(int idx)
        {
            return idx * 2 + 1;
        }

        private void swap(int a, int b)
        {
            T t = g(a);
            s(a, g(b));
            s(b, t);
        }

        private void moveUp(int idx, T t)
        {
        again:
            if (idx == 1)
            {
                s(1, t);
                return; // at end
            }

            int nextUp = up(idx);
            T n = g(nextUp);
            if (n.CompareTo(t) > 0)
            {
                s(idx, n);
                idx = nextUp;
                goto again;
            }
            else
            {
                s(idx, t);
            }
        }

        private void moveDown(int idx, T t)
        {
        again:
            int nextLeft = downLeft(idx);
            int nextRight = downRight(idx);

            if (nextLeft > end)
            {
                s(idx, t);
                return; // at end
            }
            else if (nextLeft == end)
            { // only need to check left
                T l = g(nextLeft);

                if (l.CompareTo(t) < 0)
                {
                    s(idx, l);
                    idx = nextLeft;
                    goto again;
                }
                else
                {
                    s(idx, t);
                }
            }
            else
            { // check both
                T l = g(nextLeft);
                T r = g(nextRight);

                if (l.CompareTo(r) < 0)
                { // left smaller (favour going right if we can)
                    if (l.CompareTo(t) < 0)
                    {
                        s(idx, l);
                        idx = nextLeft;
                        goto again;
                    }
                    else
                    {
                        s(idx, t);
                    }
                }
                else
                { // right smaller or same
                    if (r.CompareTo(t) < 0)
                    {
                        s(idx, r);
                        idx = nextRight;
                        goto again;
                    }
                    else
                    {
                        s(idx, t);
                    }
                }
            }
        }

        public void Clear()
        {
            end = 0;
        }

        public void Trim()
        {
            if (end == 0)
                arr = new T[1]; // don't /ever/ make arr len 0
            else
            {
                T[] narr = new T[end];
                for (int i = 0; i < end; i++)
                    narr[i] = arr[i];
                arr = narr;
            }
        }

        private void doubleSize()
        {
            T[] narr = new T[arr.Length * 2];
            for (int i = 0; i < end; i++)
                narr[i] = arr[i];
            arr = narr;
        }

        public void Add(T item)
        {
            if (end == arr.Length)
            {
                // resize
                doubleSize();
            }

            end++;
            moveUp(end, item);
        }

        public T RemoveMin()
        {
            if (end < 1)
                throw new Exception("No items, mate.");

            T min = g(1);

            end--;
            if (end > 0)
                moveDown(1, g(end + 1));

            return min;
        }

        public bool Empty
        {
            get
            {
                return end == 0;
            }
        }

        public int Count
        {
            get
            {
                return end;
            }
        }

        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }

        public IEnumerator<T> GetEnumerator()
        {
            return (IEnumerator<T>)arr.GetEnumerator();
        }
    }
}


问:
Can you outgolf me? (Cops section)

Cops section

The robbers section can be found here.

Thanks to FryAmTheEggman, Peter Taylor, Nathan Merrill, xnor, Dennis, Laikoni and Mego for their contributions.

Challenge

Your task is to write 2 different programs (full programs/functions/etc.) in the same language and the same version (e.g. Python 3.5 ≠ Python 3.4, so that is not allowed), and when given n (using STDIN/function arguments/etc.), compute a(n) where a is an OEIS sequence of your choice. One of those programs is shorter than the other. You only need to submit the longer program of the two. The other one needs to be saved in case of not being cracked after 7 days. Your submission is cracked when your program has been outgolfed (whether it is by 1 byte or more).

For example, if the task you chose was to perform 2 × n, this could be a valid submission (in Python 2):

Python 2, 16 bytes, score = 15 / 16 = 0.9375

```<code>print(2*input())
</code>```

Computes A005843, (offset = 0).

If your submission has been cracked, then you need to state that in your header like so:

Python 2, 16 bytes, score = 15 / 16 = 0.9375, [cracked] + link

```<code>print(2*input())
</code>```

Computes A005843, (offset = 0).

Offset

This can be found on every OEIS page. For example, for A005843, the offset is 0,2. We only need to use the first one, which is 0. This means that the function is defined for all numbers ≥ 0.

In other words, the function OEIS(n) starts with n = 0. Your program needs to work for all cases given by OEIS.

More information can be found here.

Scoring

The score you get for your submission is equal to the following formula:

Score = Length (in bytes) of secret code ÷ Length (in bytes) of public code

The example above has the score 15 ÷ 16 = 0.9375.

The submission with the lowest score wins. Only submissions that have posted their solution will be eligible for winning.

Rules

The task you need to do is an OEIS sequence of your choice.

Given n, output OEIS(n). Deviation is not allowed, so you need to produce the exact same sequence (when given n, you need to output OEIS(n)).

Submissions that are not cracked within a period of 7 days are considered safe after the solution has been posted (submissions older than 7 days that do not have their solution posted are still vulnerable in being cracked).

In your submission, you need to post the following things: language name, byte count, full code, so no pastebin links etc. (to prevent answers like Unary), OEIS sequence, score with lengths of both programs and additionally, the encoding that is used.

Note: the same sequence cannot be posted twice in the same language. (For example, if the sequence A005843 has been done in Pyth, you cannot use Pyth again for that same sequence.)

Input and output are both in decimal (base 10)

Leaderboard

 <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/Sites/codegolf/all.css?v=7509797c03ea">

Uncracked submissions

 Language	 Score	 User

Sort by: score creation

Safe submissions

 Language	 Score	 User

```

Note

This challenge is finished. The final winner is feersum with his Seed answer. Congratulations! :).

You can still submit new cops, but be aware that they are no longer competing.

答:
Hexagony, 91 bytes, Score = 0.725274725 (66/91) [Cracked]

Computes A000045 (Fibonacci sequence, offset 0).

I won't be too surprised if someone manages to beat this and my more golfed version<s>, although it should be hard.</s>

Edit: Holy cow, @MartinEnder whipped me with a 33 byte solution.

Golfed (91):

```<code>?\]~<~.{>'"/(@{\''1<{!1>{{1}/}{'\1</={}/_\'0"/>+(}\/}(+'+'%=<>=%"=+("\/+"(+}+<>{{}=~\.....|
</code>```

Formatted:

```<code>      ? \ ] ~ < ~
     . { > ' " / (
    @ { \ ' ' 1 < {
   ! 1 > { { 1 } / }
  { ' \ 1 < / = { } /
 _ \ ' 0 " / > + ( } \
  / } ( + ' + ' % = <
   > = % " = + ( " \
    / + " ( + } + <
     > { { } = ~ \
      . . . . . |
</code>```

Try it online!

I'm not going to post an explanation for this, it's too horrible...

Golfed (66):

```<code>?{1}]0@._.>\>+{./'++.!.|.*'}..\}{\=++.../'"<_}\"+<./{(/\=*"=/>{=+"
</code>```

Formatted:

```<code>      ? { 1 } ] 0
     @ . _ . > \ >
    + { . / ' + + .
   ! . | . * ' } . .
  \ } { \ = + + . . .
 / ' " < _ } \ " + < .
  / { ( / \ = * " = /
   > { = + " . . . .
    . . . . . . . .
     . . . . . . .
      . . . . . .
</code>```

Colored:

Try it online!

Explanation:

The memory layout I used looks a little like this:

```<code>   |
   a
   |
  / \
b+a  b
/     \
      |
    input
</code>```

The initialization (in black) sets a=0 and b=1. Then, the main loop:

goes from a to the input cell - '"

decrements the input - (

adds b and a - {{=+

moves it "out of the way" - "+{=*

sets a to b - '+

moves a "out of the way" - '+}=*

moves b+a back to its original position - "=+

sets b to b+a - "+

moves a back to its original position - }+

Once the input cell reaches 0, the MP moves to a, prints, and exits.

What I could have done to save more bytes is to use &, which just sets the current cell to either its left or right neighbor. I also could have had a bit better flow control, but it's okay as it stands.

ContentLicense: CC BY-SA 3.0

Title: Can you outgolf me? (Cops section)

Body:
Hexagony, 91 bytes, Score = 0.725274725 (66/91) [Cracked]

Computes A000045 (Fibonacci sequence, offset 0).

I won't be too surprised if someone manages to beat this and my more golfed version<s>, although it should be hard.</s>

Edit: Holy cow, @MartinEnder whipped me with a 33 byte solution.

Golfed (91):

?\]~<~.{>'"/(@{\''1<{!1>{{1}/}{'\1</={}/_\'0"/>+(}\/}(+'+'%=<>=%"=+("\/+"(+}+<>{{}=~\.....|

Formatted:

      ? \ ] ~ < ~
     . { > ' " / (
    @ { \ ' ' 1 < {
   ! 1 > { { 1 } / }
  { ' \ 1 < / = { } /
 _ \ ' 0 " / > + ( } \
  / } ( + ' + ' % = <
   > = % " = + ( " \
    / + " ( + } + <
     > { { } = ~ \
      . . . . . |

Try it online!

I'm not going to post an explanation for this, it's too horrible...

Golfed (66):

?{1}]0@._.>\>+{./'++.!.|.*'}..\}{\=++.../'"<_}\"+<./{(/\=*"=/>{=+"

Formatted:

      ? { 1 } ] 0
     @ . _ . > \ >
    + { . / ' + + .
   ! . | . * ' } . .
  \ } { \ = + + . . .
 / ' " < _ } \ " + < .
  / { ( / \ = * " = /
   > { = + " . . . .
    . . . . . . . .
     . . . . . . .
      . . . . . .

Colored:

Try it online!

Explanation:

The memory layout I used looks a little like this:

   |
   a
   |
  / \
b+a  b
/     \
      |
    input

The initialization (in black) sets a=0 and b=1. Then, the main loop:

goes from a to the input cell - '"

decrements the input - (

adds b and a - {{=+

moves it "out of the way" - "+{=*

sets a to b - '+

moves a "out of the way" - '+}=*

moves b+a back to its original position - "=+

sets b to b+a - "+

moves a back to its original position - }+

Once the input cell reaches 0, the MP moves to a, prints, and exits.

What I could have done to save more bytes is to use &, which just sets the current cell to either its left or right neighbor. I also could have had a bit better flow control, but it's okay as it stands.


问:
Roll an ASCII die
In this code-golf challenge, you must output an ascii-art of a random die roll.

like this:

```<code>   ________
  /\       \
 /  \   6   \
{ 4  }-------}
 \  /   5   /
  \/_______/
</code>```

Please note that:

```<code>   ________
  /\       \
 /  \   3   \
{ 4  }-------}
 \  /   5   /
  \/_______/
</code>```

is invalid output, because that is not a possible result on a die

There are 6(faces that could be up)*4(faces that could be the left face after the top is determined)*1(faces that could be the right face after the other two are determined)=24 possibilities of die rolls.

Your program must output one of these die rolls in the form of an ascii art (modeled like the one below, with the x y and zs replaced with numbers) like above, with each output having >0 probability of occurring, but the probabilities do not have to be even (they are allowed to be trick dice, unlike in real life). Your program cannot output an invalid die roll, or a non die roll. Your program must have a probability of 1 of outputting a valid roll

Please note that your die does not necessarily have to be a right handed die like shown in the first image. (right- and left-handed describe the die's net)

```<code>right-handed die
   ________
  /\       \    net
 /  \   z   \     _|4|_ _
{ x  }-------}   |6|2|1|5|
 \  /   y   /      |3|
  \/_______/

left handed die
   ________
  /\       \    net
 /  \   y   \     _|3|_ _
{ x  }-------}   |6|2|1|5|
 \  /   z   /      |4|
  \/_______/
</code>```

If your die is left handed, the following is valid output, but not if your die is right handed:

```<code>   ________
  /\       \
 /  \   2   \
{ 1  }-------}
 \  /   3   /
  \/_______/
</code>```

While you can choose left handed or right handed, your die has to be consistent: it cannot change from left to right or vice versa

the following is a list of valid outputs for the die. Refer to the pictures above for positions of X-Y-Z:

```<code>X-Y-Z
-----
5-4-1
1-5-4
4-1-5

5-6-4
4-5-6
6-4-5

5-3-6
6-5-3
3-6-5

5-1-3
3-5-1
1-3-5

2-6-3
3-2-6
6-3-2

2-4-6
6-2-4
4-6-2

2-1-4
4-2-1
1-4-2

2-3-1
1-2-3
3-1-2
</code>```

again this is code-golf, so fewer bytes is better

答:
Python 3, <s>197 196 192</s>190 bytes

from random import*;c=choice;r=range(1,7);u=c(r);l=c(list({*r}-{u,u^7}));print(r'''   ________
  /\       \
 /  \%4d   \
{ %d  }-------}
 \  /%4d   /
  \/_______/'''%(u,l,3*u*l*(u*u-l*l)%7))
```

Try it online!

Right-handed (switch to a lefty by swapping u*u with l*l on the last line)

Bound to be beat - but let's get the dice rolling sigh - especially since all my attempts to golf the ASCII except going raw and using old-school formatting all failed to save bytes;

any further golfing tips for a n00b gladly appreciated.

Title: Roll an ASCII die

Body:
Python 3, <s>197 196 192</s>190 bytes

from random import*;c=choice;r=range(1,7);u=c(r);l=c(list({*r}-{u,u^7}));print(r'''   ________
  /\       \
 /  \%4d   \
{ %d  }-------}
 \  /%4d   /
  \/_______/'''%(u,l,3*u*l*(u*u-l*l)%7))

Try it online!

Right-handed (switch to a lefty by swapping u*u with l*l on the last line)

Bound to be beat - but let's get the dice rolling sigh - especially since all my attempts to golf the ASCII except going raw and using old-school formatting all failed to save bytes;

any further golfing tips for a n00b gladly appreciated.

ContentLicense: CC BY-SA 4.0


答:
05AB1E, 10 bytes, score = 5 ÷ 10 = 0.5, cracked

This one isn't too hard actually :p. Code:

```<code>[NNÂÊ½¾¹Q#
</code>```

Computes the Nth non-palindromic number, which is A029742.

Try it online!

Title: Can you outgolf me? (Cops section)

Body:
Cops section

The robbers section can be found here.

Thanks to FryAmTheEggman, Peter Taylor, Nathan Merrill, xnor, Dennis, Laikoni and Mego for their contributions.

Challenge

Your task is to write 2 different programs (full programs/functions/etc.) in the same language and the same version (e.g. Python 3.5 ≠ Python 3.4, so that is not allowed), and when given n (using STDIN/function arguments/etc.), compute a(n) where a is an OEIS sequence of your choice. One of those programs is shorter than the other. You only need to submit the longer program of the two. The other one needs to be saved in case of not being cracked after 7 days. Your submission is cracked when your program has been outgolfed (whether it is by 1 byte or more).

For example, if the task you chose was to perform 2 × n, this could be a valid submission (in Python 2):

Python 2, 16 bytes, score = 15 / 16 = 0.9375

```<code>print(2*input())
</code>```

Computes A005843, (offset = 0).

If your submission has been cracked, then you need to state that in your header like so:

Python 2, 16 bytes, score = 15 / 16 = 0.9375, [cracked] + link

```<code>print(2*input())
</code>```

Computes A005843, (offset = 0).

Offset

This can be found on every OEIS page. For example, for A005843, the offset is 0,2. We only need to use the first one, which is 0. This means that the function is defined for all numbers ≥ 0.

In other words, the function OEIS(n) starts with n = 0. Your program needs to work for all cases given by OEIS.

More information can be found here.

Scoring

The score you get for your submission is equal to the following formula:

Score = Length (in bytes) of secret code ÷ Length (in bytes) of public code

The example above has the score 15 ÷ 16 = 0.9375.

The submission with the lowest score wins. Only submissions that have posted their solution will be eligible for winning.

Rules

The task you need to do is an OEIS sequence of your choice.

Given n, output OEIS(n). Deviation is not allowed, so you need to produce the exact same sequence (when given n, you need to output OEIS(n)).

Submissions that are not cracked within a period of 7 days are considered safe after the solution has been posted (submissions older than 7 days that do not have their solution posted are still vulnerable in being cracked).

In your submission, you need to post the following things: language name, byte count, full code, so no pastebin links etc. (to prevent answers like Unary), OEIS sequence, score with lengths of both programs and additionally, the encoding that is used.

Note: the same sequence cannot be posted twice in the same language. (For example, if the sequence A005843 has been done in Pyth, you cannot use Pyth again for that same sequence.)

Input and output are both in decimal (base 10)

Leaderboard

 <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/Sites/codegolf/all.css?v=7509797c03ea">

Uncracked submissions

 Language	 Score	 User

Sort by: score creation

Safe submissions

 Language	 Score	 User

```

Note

This challenge is finished. The final winner is feersum with his Seed answer. Congratulations! :).

You can still submit new cops, but be aware that they are no longer competing.

Body:
05AB1E, 10 bytes, score = 5 ÷ 10 = 0.5, cracked

This one isn't too hard actually :p. Code:

[NNÂÊ½¾¹Q#

Computes the Nth non-palindromic number, which is A029742.

Try it online!


问:
Can you outgolf me? (Robbers section)

Robbers section

The cops section can be found here.

Challenge

Your task is to outgolf the submissions of the cops in the same language and the same version (for example, Python 3.5 ≠ Python 3.4, so that is not allowed). A submission is outgolfed when the length in bytes is shorter than the original submission. You only need to golf off at least 1 byte in order to crack a submission. E.g. if the task was to perform 2 × n, and the submission was the following:

```<code>print(2*input())
</code>```

You could outgolf the cop by doing the following:

```<code>print 2*input()
</code>```

Or even this (since lambda's are allowed):

```<code>lambda x:2*x
</code>```

Post this with the following header:

```<code>##{language name}, <s>{prev byte count}</s> {byte count}, {cop's submission + link}
</code>```

For example:

Python 2, <s>16</s> 12 bytes, Adnan (+ link to submission)

```<code>lambda x:2*x
</code>```

Computes A005843, (offset = 0).

In that case, you have cracked the submission.

Scoring

The person with who cracked the most submissions is the winner.

Rules

The crack submission must be in the same language as the cop submission.

The same input should result into the same output (so a(2) = 4 should remain 4).

For languages such as Python, you can import libraries that are standard included within the language. (So, no numpy/sympy etc.)

Input and output are both in decimal (base 10).

Note

This challenge is finished. The winner of the Robbers section is feersum. The final scores for the CnR are shown below:

feersum: 16 cracks

Dennis: 12 cracks

Leaky Nun: 6 cracks

Lynn: 4 cracks

miles: 3 cracks

Martin Ender: 2 cracks

Emigna: 2 cracks

jimmy23013: 1 crack

Sp3000: 1 crack

randomra: 1 crack

alephalpha: 1 crack

nimi: 1 crack

Destructible Watermelon: 1 crack

Dom Hastings: 1 crack

答:
05AB1E, 10 8 bytes, Adnan

```<code>µNÂÂQ>i¼
</code>```

Try it online.

Title: Can you outgolf me? (Robbers section)

Body:
05AB1E, 10 8 bytes, Adnan

µNÂÂQ>i¼

Try it online.


答:
Hexagony, <s>91</s> 33 bytes, Blue

```<code>1""?{\>{+/</+'+./_'..@'~&/!}'+=($
</code>```

Unfolded:

```<code>    1 " " ?
   { \ > { +
  / < / + ' +
 . / _ ' . . @
  ' ~ & / ! }
   ' + = ( $
    . . . .
</code>```

Try it online!

Still looks somewhat golfable but I figured I'd post it before FryAmTheEggman beats me to it. ;)

Explanation

Here are some colour-coded execution paths:

However, these are unnecessarily convoluted due to golfing. Here is the exact same code with a saner layout:

That's better. And finally, here is a memory diagram, where the red arrow indicates the initial position and orientation of the memory pointer (MP):

The gist is that I'm iteratively computing Fibonacci numbers on the three edges labelled f(i), f(i+1) and f(i+2) while keeping track of the iterator on the edges A, B and C. While doing so the roles of these edges are swapped out cyclically after each iteration. Let's see how this happens...

The code starts on the grey path which does some initial setup. Note that f(i) already has its correct initial value of 0.

```<code>1   Set edge f(i+1) to 1.
""  Move the MP to edge A.
?   Read input n into edge A.
)   Increment n.
</code>```

Now the green path is the main loop. _ and > are just mirrors.

```<code>(     Decrement n.
<     If the result is zero or less, continue on the red path, otherwise
      perform another iteration of the main loop.
{     Move the MP to edge f(i+2).
+     Add edges f(i) and f(i+1) into this edge, computing the next Fibonacci number.
'     Move the MP to the edge opposite A.
~     Multiply by -1 to ensure that it's non-positive (the edge may have a positive
      value after a few iterations).
&     Copy the current value of n from A.
'     Move back and to the right again.
+     Copy n by adding it to zero. Since we know that the other adjacent edge
      is always zero, we no longer need to use ~&.
'+'+  Repeat the process twice, moving n all the way from A to B.
=     Reverse the orientation of the MP so that it points at f(i) which now
      becomes f(i+2) for the next iteration.
</code>```

This way, the MP moves around the inner triplet of edges, computing successive Fibonacci numbers until n reaches zero. Then finally the red path is executed:

```<code>{}    Move the MP to f(i).
!     Print it.
@     Terminate the program.
</code>```

Diagrams generated with Timwi's HexagonyColorer and EsotericIDE.

Title: Can you outgolf me? (Robbers section)

Body:
Robbers section

The cops section can be found here.

Challenge

Your task is to outgolf the submissions of the cops in the same language and the same version (for example, Python 3.5 ≠ Python 3.4, so that is not allowed). A submission is outgolfed when the length in bytes is shorter than the original submission. You only need to golf off at least 1 byte in order to crack a submission. E.g. if the task was to perform 2 × n, and the submission was the following:

```<code>print(2*input())
</code>```

You could outgolf the cop by doing the following:

```<code>print 2*input()
</code>```

Or even this (since lambda's are allowed):

```<code>lambda x:2*x
</code>```

Post this with the following header:

```<code>##{language name}, <s>{prev byte count}</s> {byte count}, {cop's submission + link}
</code>```

For example:

Python 2, <s>16</s> 12 bytes, Adnan (+ link to submission)

```<code>lambda x:2*x
</code>```

Computes A005843, (offset = 0).

In that case, you have cracked the submission.

Scoring

The person with who cracked the most submissions is the winner.

Rules

The crack submission must be in the same language as the cop submission.

The same input should result into the same output (so a(2) = 4 should remain 4).

For languages such as Python, you can import libraries that are standard included within the language. (So, no numpy/sympy etc.)

Input and output are both in decimal (base 10).

Note

This challenge is finished. The winner of the Robbers section is feersum. The final scores for the CnR are shown below:

feersum: 16 cracks

Dennis: 12 cracks

Leaky Nun: 6 cracks

Lynn: 4 cracks

miles: 3 cracks

Martin Ender: 2 cracks

Emigna: 2 cracks

jimmy23013: 1 crack

Sp3000: 1 crack

randomra: 1 crack

alephalpha: 1 crack

nimi: 1 crack

Destructible Watermelon: 1 crack

Dom Hastings: 1 crack

Body:
Hexagony, <s>91</s> 33 bytes, Blue

1""?{\>{+/</+'+./_'..@'~&/!}'+=($

Unfolded:

    1 " " ?
   { \ > { +
  / < / + ' +
 . / _ ' . . @
  ' ~ & / ! }
   ' + = ( $
    . . . .

Try it online!

Still looks somewhat golfable but I figured I'd post it before FryAmTheEggman beats me to it. ;)

Explanation

Here are some colour-coded execution paths:

However, these are unnecessarily convoluted due to golfing. Here is the exact same code with a saner layout:

That's better. And finally, here is a memory diagram, where the red arrow indicates the initial position and orientation of the memory pointer (MP):

The gist is that I'm iteratively computing Fibonacci numbers on the three edges labelled f(i), f(i+1) and f(i+2) while keeping track of the iterator on the edges A, B and C. While doing so the roles of these edges are swapped out cyclically after each iteration. Let's see how this happens...

The code starts on the grey path which does some initial setup. Note that f(i) already has its correct initial value of 0.

1   Set edge f(i+1) to 1.
""  Move the MP to edge A.
?   Read input n into edge A.
)   Increment n.

Now the green path is the main loop. _ and > are just mirrors.

(     Decrement n.
<     If the result is zero or less, continue on the red path, otherwise
      perform another iteration of the main loop.
{     Move the MP to edge f(i+2).
+     Add edges f(i) and f(i+1) into this edge, computing the next Fibonacci number.
'     Move the MP to the edge opposite A.
~     Multiply by -1 to ensure that it's non-positive (the edge may have a positive
      value after a few iterations).
&     Copy the current value of n from A.
'     Move back and to the right again.
+     Copy n by adding it to zero. Since we know that the other adjacent edge
      is always zero, we no longer need to use ~&.
'+'+  Repeat the process twice, moving n all the way from A to B.
=     Reverse the orientation of the MP so that it points at f(i) which now
      becomes f(i+2) for the next iteration.

This way, the MP moves around the inner triplet of edges, computing successive Fibonacci numbers until n reaches zero. Then finally the red path is executed:

{}    Move the MP to f(i).
!     Print it.
@     Terminate the program.

Diagrams generated with Timwi's HexagonyColorer and EsotericIDE.


问:
Print a 10 by 10 grid of asterisks

Background

This is a standard textbook example to demonstrate for loops.

This is one of the first programs I learnt when I started learning programming ~10 years ago.

Task

You are to print this exact text:

```<code>**********
**********
**********
**********
**********
**********
**********
**********
**********
**********
</code>```

Specs

You may have extra trailing newlines.

You may have extra trailing spaces (U+0020) at the end of each line, including the extra trailing newlines.

Scoring

This is code-golf. Shortest answer in bytes wins.

答:
Jelly, 7 bytes

```<code>”*x⁵Ṅ9¡
</code>```

What's going on?

```<code>”*x⁵Ṅ9¡  - No arguments
”*       - character literal, *
  x      - multiply (dyadic operation)
   ⁵     - integer literal, 10 (we have now constructed the string '**********')
    Ṅ    - Print & linefeed (monadic operation)
     9   - integer literal, 9
      ¡  - Repeat n times (n is 9 as the first Ṅ is not a repeat)
</code>```

Test it on tryitonline

Title: Print a 10 by 10 grid of asterisks

Body:
Jelly, 7 bytes

”*x⁵Ṅ9¡

What's going on?

”*x⁵Ṅ9¡  - No arguments
”*       - character literal, *
  x      - multiply (dyadic operation)
   ⁵     - integer literal, 10 (we have now constructed the string '**********')
    Ṅ    - Print & linefeed (monadic operation)
     9   - integer literal, 9
      ¡  - Repeat n times (n is 9 as the first Ṅ is not a repeat)

Test it on tryitonline


Title: Roll an ASCII die

Body:
In this code-golf challenge, you must output an ascii-art of a random die roll.

like this:

```<code>   ________
  /\       \
 /  \   6   \
{ 4  }-------}
 \  /   5   /
  \/_______/
</code>```

Please note that:

```<code>   ________
  /\       \
 /  \   3   \
{ 4  }-------}
 \  /   5   /
  \/_______/
</code>```

is invalid output, because that is not a possible result on a die

There are 6(faces that could be up)*4(faces that could be the left face after the top is determined)*1(faces that could be the right face after the other two are determined)=24 possibilities of die rolls.

Your program must output one of these die rolls in the form of an ascii art (modeled like the one below, with the x y and zs replaced with numbers) like above, with each output having >0 probability of occurring, but the probabilities do not have to be even (they are allowed to be trick dice, unlike in real life). Your program cannot output an invalid die roll, or a non die roll. Your program must have a probability of 1 of outputting a valid roll

Please note that your die does not necessarily have to be a right handed die like shown in the first image. (right- and left-handed describe the die's net)

```<code>right-handed die
   ________
  /\       \    net
 /  \   z   \     _|4|_ _
{ x  }-------}   |6|2|1|5|
 \  /   y   /      |3|
  \/_______/

left handed die
   ________
  /\       \    net
 /  \   y   \     _|3|_ _
{ x  }-------}   |6|2|1|5|
 \  /   z   /      |4|
  \/_______/
</code>```

If your die is left handed, the following is valid output, but not if your die is right handed:

```<code>   ________
  /\       \
 /  \   2   \
{ 1  }-------}
 \  /   3   /
  \/_______/
</code>```

While you can choose left handed or right handed, your die has to be consistent: it cannot change from left to right or vice versa

the following is a list of valid outputs for the die. Refer to the pictures above for positions of X-Y-Z:

```<code>X-Y-Z
-----
5-4-1
1-5-4
4-1-5

5-6-4
4-5-6
6-4-5

5-3-6
6-5-3
3-6-5

5-1-3
3-5-1
1-3-5

2-6-3
3-2-6
6-3-2

2-4-6
6-2-4
4-6-2

2-1-4
4-2-1
1-4-2

2-3-1
1-2-3
3-1-2
</code>```

again this is code-golf, so fewer bytes is better

Body:
Javascript, 251 bytes

r="replace";a=()=>(0|Math.random()*6)+1;b=(x,y)=>3*x*y*(x*x+6*y*y)%7;u=()=>{x=a(),y=a();z=b(x,y);if(z==0)u();return"   ________\r\n  \/\\       \\\r\n \/  \\   1   \\\r\n{ 2  }-------}\r\n \\  \/   3   \/\r\n  \\\/_______\/"[r](1,x)[r](2,y)[r](3,z);}

Call using u();

It's long but it's an answer, and I haven't answered in a long time.


问:
Gauss to Eisenstein
Given a Gaussian integer \$a+bi\$ where \$a\$,\$b\$ are integers and \$i = \exp\left(\pi i/2\right)\$ is the imaginary unit, return the closest (w.r.t to the Euclidean distance) Eisenstein integer \$k+l\omega\$ where \$k\$,\$l\$ are integers and \$\omega = \exp(2\pi i/3) = (-1+i\sqrt{3})/2\$.

Background

It is probably quite obvious that every Gaussian integer can uniquely be written as \$a+bi\$ with \$a\$,\$b\$ integers. It is not so obvious but nonetheless true: Any Eisenstein integer can uniquely be written as \$k+l\omega\$ with \$k\$,\$l\$ integers. They both form a \$\mathbb{Z}\$-module within the complex numbers, and are both p-th cyclotomic integers for \$p=2\$ or \$3\$ respectively. Note that \$3+2i \neq 3+2\omega\$

Source: commons.wikimedia.org

Details

In case the given complex number has two or three closest points, any of those can be returned.

The complex number is given in rectangular coordinates (basis \$(1,i)\$), but other than that in any convenient format like (A,B) or A+Bi or A+B*1j etc.

The Eisenstein integer has to be returned as coordinates of the basis \$(1,\omega)\$ but other than that in any convenient format like (K,L) or K+Lω or K+L*1ω etc.

Examples

All real integers should obviously be mapped to the real integers again.

```<code>  6,14 -> 14,16
  7,16 -> 16,18
-18,-2 ->-19,-2
 -2, 2 -> -1, 2
 -1, 3 -> 1, 4
</code>```

答:
JavaScript (ES6), 112 bytes

```<code>(a,b,l=b/Math.pow(.75,.5),k=a+l/2,f=Math.floor,x=k-(k=f(k)),y=l-(l=f(l)),z=x+y>1)=>[k+(y+y+z>x+1),l+(x+x+z>y+1)]
</code>```

ES7 can obviously trim 9 bytes. Explanation: k and l initially represent the floating-point solution to k+ωl=a+ib. However, the coordinates needed to be rounded to the nearest integer by Euclidean distance. I therefore take the floor of k and l, then perform some tests on the fractional parts to determine whether incrementing them would result in a nearer point to a+ib.

Title: Gauss to Eisenstein

Body:
JavaScript (ES6), 112 bytes

(a,b,l=b/Math.pow(.75,.5),k=a+l/2,f=Math.floor,x=k-(k=f(k)),y=l-(l=f(l)),z=x+y>1)=>[k+(y+y+z>x+1),l+(x+x+z>y+1)]

ES7 can obviously trim 9 bytes. Explanation: k and l initially represent the floating-point solution to k+ωl=a+ib. However, the coordinates needed to be rounded to the nearest integer by Euclidean distance. I therefore take the floor of k and l, then perform some tests on the fractional parts to determine whether incrementing them would result in a nearer point to a+ib.


问:
Tips for golfing in Postscript?
As one of the less popular languages, it's difficult to find literature on the avant garde of postscript hackery. So what discoveries have the golfers here made to exploit the stack model (or other features) to overcome Postscript's inherent verbosity?</p>

答:
Factor-out repeated uses of long operator names

If you're already using a <<>>begin dictionary, there is a constant overhead of /?{} 4 characters per redefinition. So an operator of length n repeated N times will yield a character-count change of

(4 + n) - (N * (n - 1)).

Setting this formula equal to 0 gives the equation of the break-even point. From this we can solve for each variable in terms of the other, yielding

n = - (N - 4) / (1 - N) and

N = (4 + n) / (n - 1) .

No we can answer questions like, "For how many uses of 'print' is it worthwhile to abbreviate?" n = 5, so N = 9/4. Take the ceiling, since you can't effectively call print 1/4 times. So, 3. 3 uses. And indeed,

```<code>print print print
/P{print}p p p
</code>```

(assuming you've already paid the overhead of <<>>begin to activate the definition, of course).

Of course, binary tokens makes this kind of moot, giving you the first 255 names from the system name table as 2-bytes: 0x92, 0x??. And binary tokens are also self-delimiting, requiring no whitespace before or after, since the high-bit of the first byte is outside of the ascii range.

Title: Tips for golfing in Postscript?

Body:
Factor-out repeated uses of long operator names

If you're already using a <<>>begin dictionary, there is a constant overhead of /?{} 4 characters per redefinition. So an operator of length n repeated N times will yield a character-count change of

(4 + n) - (N * (n - 1)).

Setting this formula equal to 0 gives the equation of the break-even point. From this we can solve for each variable in terms of the other, yielding

n = - (N - 4) / (1 - N) and

N = (4 + n) / (n - 1) .

No we can answer questions like, "For how many uses of 'print' is it worthwhile to abbreviate?" n = 5, so N = 9/4. Take the ceiling, since you can't effectively call print 1/4 times. So, 3. 3 uses. And indeed,

print print print
/P{print}p p p

(assuming you've already paid the overhead of <<>>begin to activate the definition, of course).

Of course, binary tokens makes this kind of moot, giving you the first 255 names from the system name table as 2-bytes: 0x92, 0x??. And binary tokens are also self-delimiting, requiring no whitespace before or after, since the high-bit of the first byte is outside of the ascii range.


答:
MATL, <s>39</s> <s>38</s> 35 bytes

```<code>t|Ekt_w&:2Z^tl2jYP3/*Zeh*!sbw6#YkY)
</code>```

Input format is 6 + 14*1j (space is optional). Output format is 14 16.

Try it online!

Explanation

The code first takes the input as a complex number. It then generates a big enough hexagonal grid in the complex plane, finds the point that is closest to the input, and returns its Eisenstein "coordinates".

```<code>t         % Take input implicitly. This is the Gauss number, say A. Duplicate
|Ek       % Absolute value times two, rounded down
t_        % Duplicate and negate
w&:       % Range. This is one axis of Eisenstein coordinates. This will generate
          % the hexagonal grid big enough
2Z^       % Cartesian power with exponent 2. This gives 2-col 2D array, say B
t         % Duplicate
l         % Push 1
2jYP3/*   % Push 2*j*pi/3
Ze        % Exponential
h         % Concatenate. Gives [1, exp(2*j*pi/3)]
*         % Multiply by B, with broadcast.
!s        % Sum of each row. This is the hexagonal grid as a flattened array, say C
bw        % Bubble up, swap. Stack contains now, bottom to top: B, A, C
6#Yk      % Index of number in C that is closest to A
Y)        % Use as row index into B. Implicitly display
</code>```

Title: Gauss to Eisenstein

Body:
Given a Gaussian integer \$a+bi\$ where \$a\$,\$b\$ are integers and \$i = \exp\left(\pi i/2\right)\$ is the imaginary unit, return the closest (w.r.t to the Euclidean distance) Eisenstein integer \$k+l\omega\$ where \$k\$,\$l\$ are integers and \$\omega = \exp(2\pi i/3) = (-1+i\sqrt{3})/2\$.

Background

It is probably quite obvious that every Gaussian integer can uniquely be written as \$a+bi\$ with \$a\$,\$b\$ integers. It is not so obvious but nonetheless true: Any Eisenstein integer can uniquely be written as \$k+l\omega\$ with \$k\$,\$l\$ integers. They both form a \$\mathbb{Z}\$-module within the complex numbers, and are both p-th cyclotomic integers for \$p=2\$ or \$3\$ respectively. Note that \$3+2i \neq 3+2\omega\$

Source: commons.wikimedia.org

Details

In case the given complex number has two or three closest points, any of those can be returned.

The complex number is given in rectangular coordinates (basis \$(1,i)\$), but other than that in any convenient format like (A,B) or A+Bi or A+B*1j etc.

The Eisenstein integer has to be returned as coordinates of the basis \$(1,\omega)\$ but other than that in any convenient format like (K,L) or K+Lω or K+L*1ω etc.

Examples

All real integers should obviously be mapped to the real integers again.

```<code>  6,14 -> 14,16
  7,16 -> 16,18
-18,-2 ->-19,-2
 -2, 2 -> -1, 2
 -1, 3 -> 1, 4
</code>```

Body:
MATL, <s>39</s> <s>38</s> 35 bytes

t|Ekt_w&:2Z^tl2jYP3/*Zeh*!sbw6#YkY)

Input format is 6 + 14*1j (space is optional). Output format is 14 16.

Try it online!

Explanation

The code first takes the input as a complex number. It then generates a big enough hexagonal grid in the complex plane, finds the point that is closest to the input, and returns its Eisenstein "coordinates".

t         % Take input implicitly. This is the Gauss number, say A. Duplicate
|Ek       % Absolute value times two, rounded down
t_        % Duplicate and negate
w&:       % Range. This is one axis of Eisenstein coordinates. This will generate
          % the hexagonal grid big enough
2Z^       % Cartesian power with exponent 2. This gives 2-col 2D array, say B
t         % Duplicate
l         % Push 1
2jYP3/*   % Push 2*j*pi/3
Ze        % Exponential
h         % Concatenate. Gives [1, exp(2*j*pi/3)]
*         % Multiply by B, with broadcast.
!s        % Sum of each row. This is the hexagonal grid as a flattened array, say C
bw        % Bubble up, swap. Stack contains now, bottom to top: B, A, C
6#Yk      % Index of number in C that is closest to A
Y)        % Use as row index into B. Implicitly display


答:
PowerShell, 14 bytes

```<code>0..9|%{'*'*10}
</code>```

Items exiting the pipeline are automatically printed on individual lines by the default PowerShell host.

Hooray for * doing string repetition.

Title: Print a 10 by 10 grid of asterisks

Body:
Background

This is a standard textbook example to demonstrate for loops.

This is one of the first programs I learnt when I started learning programming ~10 years ago.

Task

You are to print this exact text:

```<code>**********
**********
**********
**********
**********
**********
**********
**********
**********
**********
</code>```

Specs

You may have extra trailing newlines.

You may have extra trailing spaces (U+0020) at the end of each line, including the extra trailing newlines.

Scoring

This is code-golf. Shortest answer in bytes wins.

Body:
PowerShell, 14 bytes

0..9|%{'*'*10}

Items exiting the pipeline are automatically printed on individual lines by the default PowerShell host.

Hooray for * doing string repetition.


答:
VBA, 31 bytes

```<code>for i=0to 9:?"**********":next
</code>```

in the VBA Immediate window. I couldn't find any byte-saving tricks beyond this. My best non-loop version was 45 bytes:

```<code>?replace("..........",".","**********"&vblf)
</code>```

Title: Print a 10 by 10 grid of asterisks

Body:
VBA, 31 bytes

for i=0to 9:?"**********":next

in the VBA Immediate window. I couldn't find any byte-saving tricks beyond this. My best non-loop version was 45 bytes:

?replace("..........",".","**********"&vblf)


Title: Print a 10 by 10 grid of asterisks

Body:
Unary, 3584048336806633376708256331142263836115215 bytes

Can't post it here for obvious reasons.

But it's literally just 3584048336806633376708256331142263836115215 zeroes.


问:
Tips for golfing in Cheddar

Cheddar is a high-level, functional + object-oriented programming language created by our user Downgoat designed to make programming easier, faster, and more intuitive.

What general tips do you have for golfing in Cheddar? I'm looking for ideas which can be applied to code-golf problems and which are also at least somewhat specific to Cheddar (e.g. "Remove unnecessary whitespace." is not an answer).

答:
Use default arguments

Declaring Cheddar variables can be quite the byte-waster:

```<code>->{var a=b+1}
</code>```

luckily, you can (ab)use function default values for creating variables:

```<code>b=a+1->b
</code>```

Here are some examples of uses:

```<code>let f= (a,b=a+1)->b
f(5) // 6

let f= a=Math.rand()->a
f() // 0.8757450950797647
</code>```

Title: Tips for golfing in Cheddar

Body:
Use default arguments

Declaring Cheddar variables can be quite the byte-waster:

->{var a=b+1}

luckily, you can (ab)use function default values for creating variables:

b=a+1->b

Here are some examples of uses:

let f= (a,b=a+1)->b
f(5) // 6

let f= a=Math.rand()->a
f() // 0.8757450950797647