title: Neustadtl score

text:
# Question
Title: Neustadtl score
Write the shortest function that takes a two-dimensional square array representing the scores of a chess round, and outputs an array of the Neustadtl scores of the players.

The two-dimensional array is structured so that `array[i][j]` is the score earned by the player i against player j.

The Neustadtl score is used to tie-break in chess tournaments when their conventional scores tie. The Neustadtl score is calculated by adding the scores of the player defeated and half of the scores the player drew with.

Here is an example data for a 5 on 5 match.

```
               cs  ns
1. X 1 ½ 1 0 | 2½  4.25
2. 0 X 1 ½ 0 | 1½  2.5
3. ½ 0 X ½ ½ | 1½  3.5
4. 0 ½ ½ X 1 | 2   4
5. 1 1 ½ 0 X | 2½  4.75

```

where `cs` stands for conventional score and `ns` stands for Neustadtl score.

For example, the Neustadtl score of the 4th player is:

```
  0(player 1's cs) + ½(player 2's cs) + ½(player 3's cs) + 1(player 5's cs)
= 0(2½) + ½(1½) + ½(1½) + 1(2½)
= 4

```

For more details and another example data, see its Wikipedia article.

Some notes:

1. Assume the diagonal is always zero (`array[j, j] = 0`)
2. No need to check if the array is square
3. No need to check if the data makes sense (a valid scoretable has the property `array[i, j] + array[j, i] = 1, i != j`)

# Answer
## Mathematica ~~11~~ ~~10~~ 8

```
#.Tr/@#&

```

(Thanks @chyanog!) Usage

```
m = {{0,  1, .5, 1, 0}, {0, 0, 1, .5, 0}, {.5, 0, 0, .5, .5},
     {0, .5, .5, 0, 1}, {1, 1, .5, 0, 0}}

#.Tr/@#&[m]

```

Result {4.25, 2.5, 3.5, 4., 4.75}

**Edit**

Some explanations:

> `Tr` is "Trace". When applied to a one-dimensional list returns the elements sum
> `/@` is "Map". Feeds the preceding operator with one element at a time and returns a list
> `.` is "dot product". Multiplies vectors (or matrices and vectors)
> the set `# ... &` is a functional construct. The `&`feeds the `#`with its arguments
> 7 votes

# Answer
## APL ~~31 29~~ 24 or 10 or 7

If you will accept decimal input and output then the following takes your score array as screen input via ←⊃⎕ with each row of the array enclosed in parentheses.

```
((m,'|'),+/m),m+.×+/m←⊃⎕

```

Your example would look as follows:

```
Input:

(0 1 0.5 1 0)(0 0 1 0.5 0)(0.5 0 0 0.5 0.5)(0 0.5 0.5 0 1)(1 1 0.5 0 0)

Output:

0.0 1.0 0.5 1.0 0.0 | 2.5 4.25
0.0 0.0 1.0 0.5 0.0 | 1.5 2.50
0.5 0.0 0.0 0.5 0.5 | 1.5 3.50
0.0 0.5 0.5 0.0 1.0 | 2.0 4.00
1.0 1.0 0.5 0.0 0.0 | 2.5 4.75

```

with the input displayed along with the separator and the two scores as the output. Or if you just want the Neustadtl score then:

```
m+.×+/m←⊃⎕

```

If the input scores array exists as a global m then:

```
m←⊃(0 1 0.5 1 0)(0 0 1 0.5 0)(0.5 0 0 0.5 0.5)(0 0.5 0.5 0 1)(1 1 0.5 0 0)

m+.×+/m

4.25 2.5 3.5 4 4.75

```

Latest mods prompted by marinus. Thanks.
> 7 votes

# Answer
# K,13

```
{+/'x*\:+/'x}

```

.

```
k)input:(0 1 0.5 1 0;0 0 1 0.5 0;0.5 0 0 0.5 0.5;0 0.5 0.5 0 1;1 1 0.5 0 0)
k)input
0   1   0.5 1   0
0   0   1   0.5 0
0.5 0   0   0.5 0.5
0   0.5 0.5 0   1
1   1   0.5 0   0
k){+/'x*\:+/'x}[input]
4.25 2.5 3.5 4 4.75

```

It's unclear whether you just want a 1-d array of Neustadtl scores or if you want the output that's in your example. If it's the latter then:

# K, 23

```
{x!,:'b,'+/'x*\:b:+/'x}

```

.

```
k){x!,:'b,'+/'x*\:b:+/'x}[input]
0   1   0.5 1   0  | 2.5 4.25
0   0   1   0.5 0  | 1.5 2.5
0.5 0   0   0.5 0.5| 1.5 3.5
0   0.5 0.5 0   1  | 2 4
1   1   0.5 0   0  | 2.5 4.75

```
> 4 votes

# Answer
## R - 25

```
function(x)x%*%rowSums(x)

```

---

```
R> input <- matrix(c(0,  1, .5,  1,  0,
                     0,  0,  1, .5,  0,
                    .5,  0,  0, .5, .5,
                     0, .5, .5,  0,  1,
                     1,  1, .5,  0,  0), nrow=5, byrow=TRUE)

R> (function(x)x%*%rowSums(x))(input)
     [,1]
[1,] 4.25
[2,] 2.50
[3,] 3.50
[4,] 4.00
[5,] 4.75

```
> 3 votes

# Answer
## C# 106 (88 function body + 18 required `using` stetement)

```
float[]N(float[][]s){return s.Select(l=>l.Select((v,i)=>v*s[i].Sum()).Sum()).ToArray();}

```

This function requires the `using System.Linq;` directive to be present in the file, so I added that to the character count as well.

IdeOne link: http://ideone.com/cPcfwg

OK, I know it's not very short, but I love C# and LINQ so much that I just had to do it. :)

Here's a more readable version of the code:

```
public float[] Neustadl(float[][] scoreTable)
{
    return scoreTable.Select(scoreLine =>
                        scoreLine.Select((lineValue, otherPlayerIndex) =>
                            lineValue * scoreTable[otherPlayerIndex].Sum())
                        .Sum()
                    ).ToArray();
}

```
> 2 votes

# Answer
## Ruby, 62

```
N=->a{a.map{|l|z=0
l.zip(a.map{|l|eval l*?+}){|k,s|z+=k*s}
z}}

```
> 0 votes

---
Tags: code-golf, chess
---


title: Implement DFA/NFA/epsilon-NFA

text:
# Question
Title: Implement DFA/NFA/epsilon-NFA
Write the shortest code that implements a:

1. DFA
2. NFA
3. epsilon-NFA

The program should accept as input:

* a string(that we want to see if is accepted or not)
* the delta function, represented in whichever way it's more convenient.
* the "set" of final states of the automaton

And it should output `Accepted!` if the string is accepted by the automaton, and the string `Not a chance!` otherwise.

Note that all inputs should be taken from stdin or the command line.

The total points should be computed as `(L1 + 2*L2 + 3*L3) / 6` where `Li` is the length, in bytes, of the code solving point `i` and the winner will be the answer with *smallest* score.

---

**Edit:** You can assume the starting state, so that it is *not* required as input.

The epsilon transitions can be labelled in any way you want.

---

**Edit2:** An example of input for the DFA:

```
0100
{'q_0': {'0': 'q_1', '1': 'q_0'}, 'q_1': {'0': 'q_2', '1': 'q_3'}, 'q_2': {'0': 'q_2', '1': 'q_3'}, 'q_3': {'1': 'q_0', '0': 'q_1'}}
{'q_2', 'q_3'}

```

Output:

```
Accepted!

```

An other input:

```
010010
{'q_0': {'0': 'q_1', '1': 'q_0'}, 'q_1': {'0': 'q_2', '1': 'q_3'}, 'q_2': {'0': 'q_2', '1': 'q_3'}, 'q_3': {'1': 'q_0', '0': 'q_1'}}
{'q_2', 'q_3'}

```

Output:

```
Not a chance!

```

I want to stress that you are free to use a different formatting for the inputs. Choose the simpler to "parse" in your target language. The above is simple to use in python since you can `eval` it to obtain the real objects.

# Answer
## Python, score = 138 1/6 = (79+108\*2+178\*3)/6

## DFA

```
S,D,F=input()
s=1
for c in S:s=D[s,c]
print["Not a chance!","Accepted!"][F&s>0]

```

Input is a triple of string `S`, a delta function `D`, and final state mask `F`. I number each state with a power of 2, so `F` is just the OR of each accepting state. `D` is a map from (state,input char)-\>state.

example input (accepts all strings ending in `b`):

```
'abab',{(1,'a'):1,(1,'b'):2,(2,'a'):1,(2,'b'):2},2

```

## NFA

```
S,D,F=input()
s=1
for c in S:
 t,s=s,0
 for a,b in D[c]:s|=t/a%2*b
print["Not a chance!","Accepted!"][F&s>0]

```

We number states as powers of 2 as before. `D` is a map from input character to a list of transitions labeled by that character.

example input (accepts all strings ending in `b`):

```
'abab',{'a':[(1,1)],'b':[(1,1),(1,2)]},2

```

## epsilon-NFA

```
S,D,F=input()
E={1:1}
for i in D[0]:
 for a,b in D[0]:E[a]=a|E.get(b,b)
s=E[1]
for c in S:
 t,s=s,0
 for a,b in D[c]:s|=t/a%2*E.get(b,b)
print["Not a chance!","Accepted!"][F&s>0]

```

Same as `NFA`, but with the additional `0` character listing the epsilon transitions.

example input (accepts all strings ending in `b`):

```
'abab',{'a':[(1,1)],'b':[(1,1),(1,2)],0:[(2,4)]},2

```
> 4 votes

---
Tags: code-golf
---


# Question
Title: The making of "Spot It!": Finding almost unique sets
**Puzzle:** Find a deck of *c* cards, each containing *p* pictures, such that no two pictures match on a given card, and exactly 1 picture on each card matches exactly 1 picture on each of the other cards, where the number of unique pictures in the deck is minimized.

**Criteria:** Fastest code for *c* = 31 and *p* = 6.

**Inspiration:** This puzzle was inspired by wondering how the makers of the card game Spot It! came up with a deck of cards that differ from each other by only one picture. If it helps, the game's instructions say it contains 31 cards with at least 30 unique pictures.

**Brute-force reference implementation:** (Entirely impractical for use at the scale of the contest judging criteria, but perhaps useful for thinking about the problem.)

```
class Program
{
    const int CardCount = 31, PicturesPerCard = 6;

    static void Main()
    {
        for (int pictureLimit = PicturesPerCard; ; ++pictureLimit)
            new Solver(pictureLimit).FindValidCards(0, 0);
    }

    class Solver
    {
        readonly byte[,] cards = new byte[CardCount, PicturesPerCard];
        readonly int pictureLimit;

        public Solver(int pictureLimit)
        {
            this.pictureLimit = pictureLimit;
        }

        public void FindValidCards(int c, int p)
        {
            for (; c < CardCount; ++c) {
                for (; p < PicturesPerCard; ++p) {
                    for (int picture = p == 0 ? 0 : cards[c, p - 1] + 1; picture < pictureLimit; ++picture) { // Only consider pictures in numerically increasing sequence, since sequence order is irrelevant.
                        cards[c, p] = (byte)picture;
                        if (p < PicturesPerCard - 1) {
                            FindValidCards(c, p + 1);
                        } else if (c < CardCount - 1) {
                            FindValidCards(c + 1, 0);
                        } else if (AreCardsValid()) {
                            WriteCards();
                            System.Environment.Exit(0);
                        }
                    }
                }
            }
        }

        bool AreCardsValid()
        {
            for (int c = 0; c < CardCount; ++c)
                for (int otherC = c + 1; otherC < CardCount; ++otherC) {
                    int matchCount = 0;
                    for (int p = 0; p < PicturesPerCard; ++p)
                        for (int otherP = 0; otherP < PicturesPerCard; ++otherP)
                            if (cards[c, p] == cards[otherC, otherP])
                                ++matchCount;
                    if (matchCount != 1)
                        return false;
                }
            return true;
        }

        /// <summary>
        /// Writes to the console all the cards with each unique picture placed in its own column for easier comparison between cards.
        /// </summary>
        void WriteCards()
        {
            for (int c = 0; c < CardCount; ++c) {
                string cardString = string.Empty;
                for (int picture = 0; picture < pictureLimit; ++picture)
                    for (int p = 0; ; ++p) {
                        if (p == PicturesPerCard) {
                            cardString += ' ';
                            break;
                        }
                        if (cards[c, p] == picture) {
                            cardString += (char)(picture < 26 ? 'A' + picture : 'a' + (picture - 26));
                            break;
                        }
                    }
                System.Console.WriteLine(cardString);
            }
        }
    }
}

```

**Edits:** Reworded puzzle to correctly articulate the intent that the goal is to find a deck that matches the constraints. Added the missing constraint that no two pictures on a card may match. Changed contest type from code golf to speed.

# Answer
> 6 votes
This should be a comment rather than an answer, but it's not going to fit in a comment.

One way of looking at this problem is to flip it around:

> Given that you have `N` distinct pictures, what's the largest deck of cards you can build each of which has `n` distinct pictures such that the intersection of any two cards is precisely one picture?

Another way of phrasing this flipped-round problem is:

> What is the maximal size of binary code of length `N`, constant weight `n` and exact pairwise Hamming distance `2(n-1)`?

This is bounded by the maximal size of binary codes of length `N`, constant weight `n`, and *minimal* Hamming distance `2(n-1)`. The best resource for such bounds appears to be http://www.win.tue.nl/~aeb/codes/Andw.html although some values here are extracted from OEIS (specifically A001839).

```
 N \ n  0   1   2   3   4   5   6   7   8   9
 0      1   -   -   -   -   -   -   -   -   -
 1      1   1   -   -   -   -   -   -   -   -
 2      1   1   1   -   -   -   -   -   -   -
 3      1   1   3   1   -   -   -   -   -   -
 4      1   1   3   1   1   -   -   -   -   -
 5      1   1   4   2   1   1   -   -   -   -
 6      1   1   5   4   1   1   1   -   -   -
 7      1   1   6   7   2   1   1   1   -   -
 8      1   1   7   8   2   1   1   1   1   -
 9      1   1   8   12  3   2   1   1   1   1
 10     1   1   9   13  5   2   1   1   1   1
 11     1   1   10  17  6   2   2   1   1   1
 12     1   1   11  20  9   3   2   1   1   1
 13     1   1   12  26  13  3   2   2   1   1
 14     1   1   13  28  14  4   2   2   1   1
 15     1   1   14  35  15  6   3   2   2   1
 16     1   1   15  37  20  6   3   2   2   1
 17     1   1   16  44  20  7   3   2   2   2
 18     1   1   17  48  22  9   4   3   2   2
 19     1   1   18  57  25  12  4   3   2   2
 20     1   1   19  60  30  16  5   3   2   2
 21     1   1   20  70  31  21  7   3   3   2
 22     1   1   21  73  37  21  7   4   3   2
 23     1   1   22  83  40  23  8   4   3   2
 24     1   1   23  88  42  24  9   4   3   3
 25     1   1   24  100 50  30  10  5   3   3
 26     1   1   25  104 52  30  13  5   4   3
 27     1   1   26  117 54  31  14  6   4   3
 28     1   1   27  121 63  33  16  8   4   3
 29     1   1   28  134 65  ?   20  8   4   3
 30     1   1   29  140 ?   ?   25  9   5   4
 31     1   1   30  155 ?   ?   31  9   5   4
 32     1   1   31  160 ?   ?   31  10  5   4

```

There are some easy to prove properties, but from what I've read so far it seems that in general there's no better method known than brute force.

Note that for `n > 2` these bounds appear to be loose for `N > n^2 - n + 1` (certainly they are for the values of `n` in the table above), and tight for `N <= n^2 - n + 1`.

One useful result which handles the case that most interests you is as follows. (I could also write some code to wrap this up by using special cases and falling back to brute force, but I don't see the point).

> If `N = n^2 - n + 1` then there is a nicely structured deck of `N` cards satisfying the required property.

The construction is quite simple:

```
(-1,-1) (x,0) (x,1) ... (x,n-2)                for x in 0..n-1
(0,y) (1,y+z % n-1) ... (n-1, y+(n-1)z % n-1)  for y in 0..n-2, z in 0..n-2

```

Each element appears in precisely `n` cards, which makes it optimal for decks in which more than one picture repeats.

Call the most frequent picture (selecting arbitrarily in case of a tie) `f`.

### Lemma 1

> If `f` appears in more than `n` cards then it must appear in every card, and no other element repeats.

Proof: because each pairwise intersection contains precisely one element, all of the other elements in the cards containing `f` must be distinct. But then a card which doesn't contain `f` must have a non-trivial intersection with more than `n` disjoint sets despite having only `n` elements, which is impossible.

### Corollary

> The largest possible deck in which `f` appears in more than `n` cards has size `floor((N-1) / (n-1))`

Excluding `f` from the `N` available pictures we get `N-1` from which to draw disjoint sets of size `n-1` to complete each card.

### Lemma 2

> Any deck in which `f` appears in no more than `n` cards has at most `n^2 - n + 1` cards.

Consider an arbitrary card containing `f`. By definition of `f`, none of the `n` elements of that card appears in more than `n` cards, and since each appears in that card the number of other cards is no more than `n(n-1)`. Hence the deck cannot be larger than `n(n-1) + 1`.

### Theorem

> The largest possible deck has an upper bound of `max(n^2 - n + 1, floor((N-1) / (n-1)))`.

By combining the corollary and lemma 2.

# Answer
> 4 votes
Because I view this question as primarily a challenge question, I'll describe how an approach can be developed. I'll present the code in ungolfed format in the hopes that it might shed light on how the solution was constructed. Perhaps I'll add a golfed version later.

Throughout I'll illustrate using the example of the deck of 7 cards, each having 3 pictures on it.

### Complete Graph

Whatever the size of the deck, the problem calls for a complete graph. If each vertex or node in the graph represents a distinct card from the deck, there should be a single link or edge between each vertex. This corresponds to the constraint that any pair of cards shares a single picture.

### Adjacency Matrix

Another way to express this it through an adjacency matrix. Rows and Columns correspond to cards. A cell (i,j) with a 1 in it indicates that card i has one picture in common with card j. No cells can contain an integer greater than 1 (that would mean that cards i and j share more than one picture). The diagonal consists of zeros; there are no links from a card to itself.

### Which pictures are in each card?

Below we include additional information that was not in the above diagrams. And in fact this is not the only possible solution. Even if you accept that this constitutes one viable deck of 7 cards and 7 pictures, we might have stumbled upon it by chance. We need an approach that will work for any number of pictures and cards.

### Filling in the Complete Graph

We may as well use the preceding picture to fill in information in the complete graph. Remember, we haven't solved anything. We're merely explore different ways of thinking about a specific solution, once found.

### Matrix of Cards by Pictures

Let's represent the above illustration in a another matrix. This time, the rows represent cards; the columns represent pictures.

Reading the first row, we see that card 1 contains picture 1, picture 2, and picture 3. Card 2 contains picture 1 (the picture in common between cards 1 and 2), as well as pictures 4 and 5. And so on.

By studying the distribution of pictures to cards (where the 1's appear in the matrix) we can identify a procedure that will guarantee a full deck. (Be sure to see Peter Taylor's analysis of why *a* pictures per card can produce a maximum deck of *a*(*a*-1)+1 cards using a total of *a*(*a*-1)+1 pictures.) In the example, 3 pictures per card suffice to make a deck of 7 cards.

### Steps for making a deck of Spot It! cards.

1. Choose how many pictures per card, *a*. Your deck will have c=*a*(*a*-1)+1 cards.
2. Make a *c* by *c* null matrix (all zeros). The rows will represent cards. The columns will represent pictures.
3. We will arbitrarily proceed row by row, left to right. We need to distribute three 1's to each row (three distinct pictures per card) such that: (a) there is **at most** one picture from the present card's row that matches a picture from any other card's row and (b) at most *a* copies of picture will be used in the deck. Because of how *a* and *c* were set, It automatically turns out that the proper number of pictures per card will result. (If you desire a slightly smaller deck, simply remove the extra cards. Any one is as good as the other.)

### Code in Mathematica (ungolfed)

```
deck[picsPerCard_]:=

Module[{pics=picsPerCard (picsPerCard-1)+1,cards,matrix,linked,elegible},
(*pics not really needed, but it helps distinguish columns from rows *)
cards=pics;

(*the null matrix *)
matrix=ConstantArray[0,{cards,pics}];

(* cards considered already linked; hence the cell under consideration will not be
 elegible for receiving a 1.*)
linked[m_,row1_,row2_]:=row1==row2\[Or]Tr[m[[row1]] m[[row2]]]>0;

(*Checks whether cell (r,c) is elegible for receiving card c *)
elegible[m_,{r_,c_},ppc_]:=Tr[m[[r]]]<ppc\[And](m[[r,c]]==0)\[And]
(Length[(f=Flatten[Position[matrix\[Transpose][[c]],1]])]<ppc)\[And]\[Not]
(Or@@(linked[matrix,r,#]&/@f));

(* Fill in with 1's all elegible cells.  Proceed row by row, i.e. card by card *)
Do[If[elegible[matrix,{i,j},picsPerCard], matrix=ReplacePart[matrix,{i,j}->1]],
{i,cards},{j,pics}];

(*return the solution matrix *)
matrix]

```

Examples:

```
deck[3] // MatrixForm

```

>

# Answer
> 3 votes
This is a (correct?) C# implementation of David Carraher's algorithm. I am posting it in case it provides insight into the glitch he discovered. When run with 3 pictures per card, it provides identical output as David's solution. However, for 4 or more pictures per card, it fails for want of more unique pictures across the deck than there are cards in the deck.

**Edit:** Updated to allow creation of additional pictures as needed (so it no longer fails). Also added sample runs.

```
/// <summary>Finds a deck that solves the puzzle.</summary>
/// <returns>An array of cards, where each card is a bit vector and each bit is true only if the corresponding picture is present.</returns>
static long[] FindDeck(int picturesPerCard, out int uniquePicturesCount)
{
    // Start with an initially zeroed matrix of rows of cards and columns of picture bits (bit is on if the card contains that picture).
    int cardCount = picturesPerCard * (picturesPerCard - 1) + 1;
    var deck = new long[cardCount];
    var pictureCountsForDeck = new List<int>();

    // Go through each card row, and find a valid card for that row:
    for (int c = 0; c < cardCount; ++c) { // Single-letter variables are indexes.
        var card = deck[c];
        int pictureCountForCurrentCard = 0;

        // Go through each possible picture, and turn on that picture bit if it is valid:
        for (int p = 0; ; ++p) {
            var proposedCard = card;
            proposedCard |= 1L << p; // Sets the bit for the proposed picture to true.

            // Each picture can only be used so often across the entire deck. The cap is the same as the number of pictures per card.
            if (pictureCountsForDeck.Count <= p)
                pictureCountsForDeck.Add(0);
            if (pictureCountsForDeck[p] == picturesPerCard)
                continue;

            // Check whether the picture bit is valid against the previous picture cards.
            for (int checkC = 0; ; ++checkC) {

                // If this card has been successfully checked against all previous cards:
                if (checkC == c) {
                    deck[c] = card = proposedCard;
                    ++pictureCountsForDeck[p];
                    if (++pictureCountForCurrentCard == picturesPerCard)
                        goto NextCard; // All pictures found for this card. Move to the next card.
                    break; // Find another picture for this card.
                }

                // To determine that a picture proposal is invalid, show that there was a previous match or that the new set of matched pictures differs from the previous set. This indicates more than one picture matches.
                var checkCard = deck[checkC];
                long existingMatch = card & checkCard;
                if (existingMatch != 0 && existingMatch != (proposedCard & checkCard))
                    break; // This picture proposal is invalid. Move on to the next picture.
            }
        }
    NextCard: ;
    }
    uniquePicturesCount = pictureCountsForDeck.Count;
    return deck;
}

```

The results for 4 pictures per card looks good for the square part of the matrix. However, the matrix gets sparse as columns are added:

```
1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0
1 0 0 0 1 1 1 0 0 0 0 0 0 0 0 0 0
1 0 0 0 0 0 0 1 1 1 0 0 0 0 0 0 0
1 0 0 0 0 0 0 0 0 0 1 1 1 0 0 0 0
0 1 0 0 1 0 0 1 0 0 1 0 0 0 0 0 0
0 1 0 0 0 1 0 0 1 0 0 1 0 0 0 0 0
0 1 0 0 0 0 1 0 0 1 0 0 1 0 0 0 0
0 0 1 0 1 0 0 0 1 0 0 0 1 0 0 0 0
0 0 1 0 0 1 0 1 0 0 0 0 0 1 0 0 0
0 0 1 0 0 0 1 0 0 0 1 0 0 0 1 0 0
0 0 0 1 1 0 0 0 0 1 0 1 0 0 0 0 0
0 0 0 1 0 1 0 0 0 0 1 0 0 0 0 1 0
0 0 0 1 0 0 1 1 0 0 0 0 0 0 0 0 1

```

Or is it just an anomaly at that size? The matrix is square and well filled for 5 pictures per card:

```
1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
1 0 0 0 0 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0
1 0 0 0 0 0 0 0 0 1 1 1 1 0 0 0 0 0 0 0 0
1 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 0 0 0 0
1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1
0 1 0 0 0 1 0 0 0 1 0 0 0 1 0 0 0 1 0 0 0
0 1 0 0 0 0 1 0 0 0 1 0 0 0 1 0 0 0 1 0 0
0 1 0 0 0 0 0 1 0 0 0 1 0 0 0 1 0 0 0 1 0
0 1 0 0 0 0 0 0 1 0 0 0 1 0 0 0 1 0 0 0 1
0 0 1 0 0 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1
0 0 1 0 0 0 1 0 0 1 0 0 0 0 0 0 1 0 0 1 0
0 0 1 0 0 0 0 1 0 0 0 0 1 1 0 0 0 0 1 0 0
0 0 1 0 0 0 0 0 1 0 0 1 0 0 1 0 0 1 0 0 0
0 0 0 1 0 1 0 0 0 0 0 1 0 0 0 0 1 0 1 0 0
0 0 0 1 0 0 1 0 0 0 0 0 1 0 0 1 0 1 0 0 0
0 0 0 1 0 0 0 1 0 1 0 0 0 0 1 0 0 0 0 0 1
0 0 0 1 0 0 0 0 1 0 1 0 0 1 0 0 0 0 0 1 0
0 0 0 0 1 1 0 0 0 0 0 0 1 0 1 0 0 0 0 1 0
0 0 0 0 1 0 1 0 0 0 0 1 0 1 0 0 0 0 0 0 1
0 0 0 0 1 0 0 1 0 0 1 0 0 0 0 0 1 1 0 0 0
0 0 0 0 1 0 0 0 1 1 0 0 0 0 0 1 0 0 1 0 0

```

On the other hand, at 6 pictures per card (also even), it's back to sparse again at the tail. Have we really minimized the number of unique pictures?

```
01000000100001000010000100001000000000000000000
01000000010000100001000010000100000000000000000
01000000001000010000100001000010000000000000000
00100010000010000010000010000010000000000000000
00100001000100000001000100000001000000000000000
00100000100000101000001000000000100000000000000
00100000010001000100010000000000010000000000000
00100000001000000000000000100000001110000000000
00010010000001000001001000000000001000000000000
00010001000000100010010000000000000100000000000
00010000100100000100000010000000000010000000000
00010000010010001000000100000000000001000000000
00010000001000000000000000010001110000000000000
00001010000000100100000100000000000000100000000
00001001000001001000000010000000000000010000000
00001000100010000001010000000000000000001000000
00001000010100000010001000000000000000000100000
00001000001000000000000000001000000001000011000
00000110000000010000000000010000000101000000000
00000101000000000000100000100000100000100000000
00000100100000000000000001000101001000000000000
00000100010000000000000000001000000010011000000
00000100001100000000000000000000000000000000111

```

---
Tags: fastest-code, number-theory, combinatorics
---


title: secret language hackerrank.com

text:
# Question
Title: secret language hackerrank.com
I tried this contest: https://www.hackerrank.com/challenges/secret-language Well, the score in this contest said I made 30 out of 30 points. As the score is calculated with the formula 30\*(1000-#chars)/1000 this is impossible. Here is my code:

```
import sys,string as s
b='anbycoduepfxgqhvirjzkslwmt'
a=s.letters
b+=b.upper()
t=s.translate
m=s.maketrans
for l in sys.stdin:
 print{'N':t(l[7:],m(a,b)),'E':t(l[7:],m(b,a)),'O':''}[l[1]],

```

The contest is over, so asking is no cheating but I would like to get some realistic score. I have 187 chars with newline and 195 with cr-lf. For pythoncode 24.39 (assuming newline) isn't so bad, but I think it can be done better.

For completeness here is the challenge:

Bob and Fred pass notes to each other in class all the time. However their teacher started intercepting their messages and reading the messages out loud to the class. Undeterred, Bob and Fred decided to encode their messages before they pass them so that when the message is intercepted the teacher and class will not understand it.

They got together and decided on using a simple substitution cipher. The substition cipher they agreed upon is listed below:

Old Letter: ABCDEFGHIJKLMNOPQRSTUVWXYZ New Letter: ANBYCODUEPFXGQHVIRJZKSLWMT

Using this key (Case matters!), A is changed to A, a is changed to a, B is changed to N, b is changed to n, C is changed to B, c is changed to b, … . All other characters remain the same.

However after Bob and Fred started using this method of note transfer they quickly realized that they are very slow at encoding and decoding messages. They have hired you to help them transfer messages faster by writing a program that will encode or decode messages using their substitution cipher. They want the code to be very portable so the smaller the source file is the better.

**Input**

Input will consist of several lines. Each line will begin with either the string “ENCODE”, “DECODE”, or “DONE”. If the string is “ENCODE” or “DECODE” then a message will follow. This is the message that you will have to either encode (if the first string is “ENCODE”) or decode (if the first string is “DECODE”). Messages will contain spaces and punctuation but will always be on the same line. If the string is “DONE” then this signifies that Bob and Fred are done exchanging messages.

**Output**

For each line that begins with “ENCODE” print the encoding of the message that follows.

For each line that begins with “DECODE” print the decoding of the message that follows.

Be sure to keep all capitolization and punctuation that is used in the message.

**Sample Input**

ENCODE This is a message. DECODE Zuej ej a gcjjadc. DONE

**Sample Output**

Zuej ej a gcjjadc. This is a message.

**Scoring**

Your score will be 30 * (1000 - #characters) / 1000. The minimum score a correct solution will receive is 0.03.

# Answer
## bash and friends (168 167 chars)

```
T=ANBYCODUEPFXGQHVIRJZKSLWMT
while read x&&[ "$x" != "DONE" ]
do
[ "$x" \> "E" ]
for((z=1+$?*58;z;z--))do
x=$(tr a-zA-Z `tr A-Z a-z<<<$T`$T<<<$x)
done
echo ${x:6}
done

```

The magic number isn't so magic: it's obtained by solving a set of simultaneous modular identities obtained from the cycle structure of the permutation.
> 3 votes

# Answer
## K, 95

```
d:(,/.Q`A`a)!t,_t:"ANBYCODUEPFXGQHVIRJZKSLWMT"
while[~"DONE"~f:0:0;-1@7_f^$[f like"E*";d@;d?]f]

```

Example

```
k)d:(,/.Q`A`a)!t,_t:"ANBYCODUEPFXGQHVIRJZKSLWMT"
k)while[~"DONE"~f:0:0;-1@7_f^$[f like"E*";d@;d?]f]
ENCODE This is a message.
Zuej ej a gcjjadc.
DECODE Zuej ej a gcjjadc.
This is a message.
DONE

```
> 1 votes

# Answer
### GolfScript, 93 characters

```
n/{(.1=3%{;0}{(2*343+\6>1/{{..'ANBYCODUEPFXGQHVIRJZKSLWMT'.{32+}%+.@+1/\$@+@?=}%}@*n@1}if}do;

```

Example:

```
>ENCODE This is a message.
>DECODE Zuej ej a gcjjadc.
>DONE
>ENCODE This line is not processed

Zuej ej a gcjjadc.
This is a message.

```

Note: Due to the nature of i/o the input is read completely before processing and output starts.
> 1 votes

# Answer
## Python, 159

```
from string import*
n='anbycoduepfxgqhvirjzkslwmt'
r=raw_input
s=r()
while'N'>s[2]:print translate(s[7:],maketrans(*(letters,n+upper(n))[::1-2*('E'>s)]));s=r()

```
> 0 votes

---
Tags: code-golf, python
---


# Question
Title: Find all the numbers have this property, its double and its triple contain each digit from 1 to 9 exactly once
192 is such a number, together with its double (384) and triple (576) they contain each 1-9 digit exactly once. Find all the numbers have this property.

No input.

Output:

```
192 384 576
219 438 657
273 546 819
327 654 981

```

# Answer
## GolfScript (31 30 chars)

```
1246`{[27*1131-..2*\3*]' '*n}/

```

(thanks to Howard for 31-\>30); or for a non-hard-coded approach, 33 32 (thanks again to Howard) chars:

```
333,{[..2*\3*]' '*}%{.&0-,9>},n*

```

If the output doesn't have to be character-for-character identical to the text in the question (i.e. if that is a sample), we can shorten to 27 chars:

```
[4.)7 9]{[27*84+..2*\3*]}%`

```
> 4 votes

# Answer
## APL (20)

```
192 219 273 327∘.×⍳3

```

Just prints the numbers multiplied by 1, 2, and 3.

## Without hardcoding (25)

```
{∧/1↓⎕D∊⍕k←⍵×⍳3:⎕←k}¨⍳400

```
> 6 votes

# Answer
### GolfScript ~~44~~ 39

Here's a program that's slightly shorter than the trivial (just print the numbers) solution:

```
333,{4,(;{1$*}%\;.''*$10,0-''*={.p}*;}/

```

(thanks Howard & Peter)

v1:

```
333,{3,{)}%{1$*}%\;.''*$9,{)}%''*={p}{;}if}/

```

Online test here.
> 2 votes

# Answer
# Python: ~~84~~ ~~77~~ 73 characters

```
for i in range(328):
 if`set(`i`+`i*2`+`i*3`)-{'0'}`[45:]:print i,i*2,i*3

```

```
192 384 576
219 438 657
273 546 819
327 654 981

```
> 2 votes

# Answer
# Haskell: 55 characters

```
[(i,2*i,3*i)|i<-[0..333],9==length(nub$show$1002003*i)]

```

Or 65 characters if it is to be compiled and not just interpreted:

```
main=print[(i,2*i,3*i)|i<-[0..333],9==length(nub$show$1002003*i)]

```
> 2 votes

# Answer
# Ruby: ~~76~~ ~~65~~ 60 characters

```
(99..999).map{|n|s=[n,2*n,3*n]*" ";s=~/(\d).*\1|0/||puts(s)}

```

Sample run:

```
bash-4.2$ ruby -e '(99..999).map{|n|s=[n,2*n,3*n]*" ";s=~/(\d).*\1|0/||puts(s)}'
192 384 576
219 438 657
273 546 819
327 654 981

```
> 1 votes

# Answer
### C#, 109 characters

```
String.Format("{0}{1}{2}",a,a*2,a*3).Length ==9 && String.String.Format("{0}{1}{2}",a,a*2,a*3).Distinct()==9;

```
> 0 votes

---
Tags: code-golf
---


# Question
Title: Count characters in lo..ol and print a phrase
Assuming 'lol' with a variavle number of 'o's. Print a the following phrase:

```
What does 1st, 2nd, 3rd, 4th ... 'o' stand for?

```

Examples:

```
lol    -> What does 1st 'o' stand for?
loooool -> What does 1st, 2nd, 3rd, 4th, 5th 'o' stand for?

```

So far I managed to write a 128 characters solution in Perl:

```
$l=(<>=~tr/o//);print"What does ";print$_,$_==1?'st':$_==2?'nd':$_==3?'rd':'th',$_<$l?', ':''for(1..$l);print " 'o' stand for?";

```

and a 123 characters solution in Haskell:

```
p 1="1st";p 2="2nd";p 3="3rd";p n=show n++"th";main=putStr$"What does "++(foldr(++)"'o' stand for?"[p i++", "|i<-[1..23]]);

```

How short can you write it?

# Answer
### GolfScript, 82 characters

```
"What does "\,2-,{)..10/10%1=!\10%`"123"\?)*"thstndrd"2/=+}%", "*" 'o' stand for?"

```

Works even for \>100 'o's, test it online.
> 4 votes

# Answer
## Python, 112

```
print'What does '+', '.join(`n+1`+['th','snrtdd'[n::3]][n<3]for n in range(len(raw_input())-2)),"'o' stand for?"

```
> 2 votes

# Answer
## Perl 104 (+1) bytes

```
s/l?ol?/($`?', ':"What does the ").++$n.((0,st,nd,rd)[$n%(10<<($n%100<20))]||th)/ge;s/$/ 'o' stand for?/

```

Correctly handles `11th, 12th, 13th`, `21st, 22nd, 23rd`, `111th, 112th, 113th` etc. Takes input from stdin, and requires a `-p` command line switch:

```
$ echo loooool| perl -p loool.pl
What does the 1st, 2nd, 3rd, 4th, 5th 'o' stand for?

$ echo looooooooooooooooooooooooooooooooooooooooool| perl -p loool.pl
What does the 1st, 2nd, 3rd, 4th, 5th, 6th, 7th, 8th, 9th, 10th, 11th, 12th, 13th, 14th,
15th, 16th, 17th, 18th, 19th, 20th, 21st, 22nd, 23rd, 24th, 25th, 26th, 27th, 28th, 29th,
30th, 31st, 32nd, 33rd, 34th, 35th, 36th, 37th, 38th, 39th, 40th, 41st, 42nd 'o' stand for?

```

If it is not required that `21st, 22nd, 23rd` be reported correctly (as in the example code), this can be reduced to **87 bytes**:

```
s/l?ol?/($`?', ':"What does the ").++$n.((0,st,nd,rd)[$n]||th)/ge;s/$/ 'o' stand for?/

```

---

## PHP 107 bytes

```
What does the <?for(;$argv[1][++$n]>l;$f=', ')echo$f,$n,date(S,~-$n%(10<<($n%100<20))*9e4)?> 'o' stand for?

```

Input is taken by command line argument:

```
$ php loool.php loooool
What does the 1st, 2nd, 3rd, 4th, 5th 'o' stand for?

$ php loool.php looooooooooooooooooooooooooooooooooooooooool
What does the 1st, 2nd, 3rd, 4th, 5th, 6th, 7th, 8th, 9th, 10th, 11th, 12th, 13th, 14th,
15th, 16th, 17th, 18th, 19th, 20th, 21st, 22nd, 23rd, 24th, 25th, 26th, 27th, 28th, 29th,
30th, 31st, 32nd, 33rd, 34th, 35th, 36th, 37th, 38th, 39th, 40th, 41st, 42nd 'o' stand for?

```

Once again, if correctly handling `n>20` is not required, this can be reduced to **87 bytes**:

```
What does the <?for(;$argv[1][++$n]>l;$f=', ')echo$f,date(jS,~-$n*9e4)?> 'o' stand for?

```
> 2 votes

# Answer
## R - 158 characters

```
f=function(s){n=1:(nchar(s)-2);v=c("st","nd","rd",rep("th",7));cat("What does the",paste0(n,c(v,rep("th",10),rep(v,8))[n],collapse=", "),"\"o\" stand for?")}

```

Works until 100 "o"s.

Usage:

```
f("looooooooooooooooooooooooooooooooool")
What does the 1st, 2nd, 3rd, 4th, 5th, 6th, 7th, 8th, 9th, 10th, 11th, 12th, 13th, 14th, 15th, 16th, 17th, 18th, 19th, 20th, 21st, 22nd, 23rd, 24th, 25th, 26th, 27th, 28th, 29th, 30th, 31st, 32nd, 33rd, 34th "o" stands for?

```
> 1 votes

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


title: Star programming!

text:
# Question
Title: Star programming!
## The challenge

Write a program or function that prints stars! The program will receive two parameters by standar input: Size of the star and number of points of the star. A star can be any size between 0 and 10 and have 3, 4 or 5 points. The input parameters are separated by a comma, for example: `5,3` means a size 5 star with 3 points. The stars are composed by asterisks `*`

Consider the program will only receive valid inputs.

The prints must be correctly spaced so we can see pretty stars in the output!

## Parameters explanations

## Points

Is the number of arms counting from the central asterisk.

**3 points stars**:

```
       *
       *
       *
     *   *
    *     *

```

They are composed by a vertical arms and two diagonal arms. The separation between diagonal arms is `2*size-1`

**4 points stars**

```
   *     *
    *   *
      *
    *   *
   *     *

```

They have the form of a X and composed by two diagonal lines. The separation between lines is `2*(size-1)+1`

**5 points stars**

```
     *
     *
 * * * * *
    * *
   *   *

```

They are composed by a vertical line and a horizontal line. Each asterisk in the horizontal line is separated by one space. Also they have two diagonal lines, with a separation between themselves of `2*(size-2)+1`

## Size

Size is the number of asterisks that has each arm of the star counting from the central asterisk (inclusive).

**Size 1 stars are composed by a single asterisk**

```
*

```

**Size 2 stars examples**

**3 points**

```
       *
       *
     *   *

```

**4 points stars**

```
    *   *
      *
    *   *

```

**5 points stars**

```
     *
   * * *
    * *

```

You have examples of the size 3 stars in the Points parameter explanation.

## Winning criteria

Shortest code wins. Code have to be checked with the following input parameters: `3,2` `3,3` `4,2` `4,3` `5,2` `5,3`

## Bonus

**-25% characters count** for creating a size 6 pointed with the criteria explained before (6 arms and the size is the number of asterisks counting from the central asterisk). It can be any form you want while it respect the specifications. A example of a size 6 star with size 3:

```
      *
      *
  * * * * *
    * * *
   *  *  *

```

6 points stars must be checked with the following inputs `6,2` `6,3`.

# Answer
# Mathematica 80 76 67 chars

Some would question whether this is ASCII art, but I couldn't resist.

```
Graphics@Table[Text["*", r {Cos@t, Sin@t}], {t,0,2π,2π/#1}, {r,0,#2-1}]&

```

**Usage** (setting the font size at 24 to make the stars appear large.)

```
Graphics@Table[Text["*"~Style~24, r {Cos@t, Sin@t}], {t,0,2π,2π/#1}, {r,0,#2-1}] &[6,4]

```

---

**Output** for the following cases:

{{3, 2}, {3, 3}, {4, 2}, {4, 3},

{5, 2}, {5, 3}, {6, 2}, {6, 3},

{7, 4}, {8, 3}, {9, 2}, {12, 4}}

---

**How it works**

(a) The first star is at the origin of a coordinate space. Let's display it.

(b) Afterwards, we'll display a point at {1,0}.

(c) Then 5 points at once. We applied a pure function onto each pair of coordinates that follows it.

(d) Use Cos and Sin to determine the coordinates

(e) Coordinates work only on unit circle; 6 is the number of light beams.

(f) Draw radii from 0 to 4 unit.

```
options = Sequence[Axes -> True, ImageSize -> 225, BaseStyle -> 14];
a = Graphics[Text["*"~Style~{28, Blue}, {0, 0}], PlotLabel -> Style["a", 20], options];

b = Graphics[Text["*"~Style~{28, Blue}, {1, 0}], PlotLabel -> Style["b", 20], options];

c = Graphics[Text["*"~Style~{28, Blue}, {#1, #2}] & @@@ {{0, 0}, {1, 0}, {0, 1}, {-1, 0}, {0, -1}}, PlotLabel -> Style["c", 20], options];

d = Graphics[Text["*"~Style~{28, Blue}, {Cos@#, Sin@#}] & /@ {0, \[Pi]/3, 2 \[Pi]/3, \[Pi], 4 \[Pi]/3, 5 \[Pi]/3}, PlotLabel -> Style["d", 20], options];

e = Graphics@Table[Text["*"~Style~24, {Cos@t, Sin@t}], {t, 0, 2 \[Pi],  2 \[Pi]/#1}] &[6];

f = Graphics@Table[Text["*"~Style~24, r {Cos@t, Sin@t}], {t, 0, 2 \[Pi], 2 \[Pi]/#1}, {r, 0, #2 - 1}] &[6, 4];

GraphicsGrid[{{a, b, c}, {d, e, f}}, Dividers -> All]

```
> 37 votes

# Answer
# Ruby, ASCII, ~~193~~ score 142 (189 chars - 25 % bonus)

```
def s r,d
f=->a,n{[n*Math.sin(a),n*Math.cos(a)]}
s=d*6
p=[]
s.times{|k|p<<" "*s}
c=s/2
p[c][c]=?*
r.times{|a|d.times{|l|x,y=f[6.28/r*a,d*l]
p[c+x.round][c+y.round]=?*}}
p.map{|j|puts j}
end

```

Test it online

I think it qualifies for the 6-rays star bonus.

```
      *     *

       *  *

   *  *  *  *  *

        *  *

      *     *

     * *

    * * *

     * *

      *           *

        *       *

          *   *

*   *   *   *   *   *   *

          *   *

        *       *

      *           *

```
> 7 votes

# Answer
## *Mathematica*, ~~65~~ 64

My take on David's method:

```
f@p_=Graphics@Array[Text["*",{Cos@#,Sin@#}&[2π/p[[1]]#]#2]&,p,0]

```

Use:

```
f @ {6,4}

```

Errors are produced because of the use of `=` rather than `:=`, and it isn't the proper way to make a definition, but it does work here.

If one were allowed to use dots instead of asterisks this could be written (52 chars):

```
f@p_:=Most@ListPolarPlot@Array[{2π/p[[1]]#,#2}&,p,0]

f @ {6, 4}

```
> 3 votes

# Answer
```
use subs qw /N W E S NW NE SE SW Circler Printer/;
($size,$points)=split(/\,/,$ARGV[0]);
my $arrsize = $size>$points ? $size : $points;
for $my (0...2*$arrsize-2) {
    $starArray[$my]=();
}
if($size == 3) {
    @armlist=('N','SW','SE');
}
elsif($size == 4) {
    @armlist=('NE','NW','SW','SE');
}
elsif($size == 5) {
    @armlist=('E','N','W','SW','SE');
}
elsif($size == 6) {
    @armlist=('E','N','W','SW','S','SE');
}
elsif($size == 7) {
    @armlist=('E','N','W','SW','S','SE','NE');
}
elsif($size == 8) {
    @armlist=('E','N','W','SW','S','SE','NE','NW');
}
Circler;
Printer;
sub Circler{
    for (@armlist) {
        &{$_};
    }
}
sub Printer{
    for $my1 (0...2*$arrsize-2) {
        for $my2 (0...2*$arrsize-2) {
            print "$starArray[$my1]->[$my2]"."\t";
        }
        print "\n\n";
    }
}
sub N {
    for $my (0...$points-1) {
        $starArray[$arrsize-1-$my]->[$arrsize-1]="*";
    }
}
sub E {
    for $my (0...$points-1) {
        $starArray[$arrsize-1]->[$arrsize-1+$my]="*";
    }
}
sub W {
    for $my (0...$points-1) {
        $starArray[$arrsize-1]->[$arrsize-1-$my]="*";
    }
}
sub S {
    for $my (0...$points-1) {
        $starArray[$arrsize-1+$my]->[$arrsize-1]="*";
    }
}
sub NW {
    for $my (0...$points-1) {
        $starArray[$arrsize-1-$my]->[$arrsize-1-$my]="*";
    }
}
sub NE {
    for $my (0...$points-1) {
        $starArray[$arrsize-1-$my]->[$arrsize-1+$my]="*";
    }
}
sub SE {
    for $my (0...$points-1) {
        $starArray[$arrsize-1+$my]->[$arrsize-1+$my]="*";
    }
}
sub SW {
    for $my (0...$points-1) {
        $starArray[$arrsize-1+$my]->[$arrsize-1-$my]="*";
    }
}
__END__;

```
> 1 votes

---
Tags: code-golf, ascii-art
---


# Question
Title: Find the generating function of a sequence
Given a set of space-delimited integers, you've gotta either return a function that can generate that sequence, or return "There isn't any such function".

Sample input:

```
"1 11 41 79"
 - x^3+x^2-1

"12 38 78"
 - 7x^2 + 5x

```

The operations that the functions can contain are: +-/\* and exponentiation.

If anyone has any other ideas LMK. As this is a code-golf, the shortest code will win.

# Answer
## Python 256 bytes

```
a=raw_input().split();r=range(len(a));m=[[(i+1.)**p for p in r]+[int(a[i])]for i in r]
for j in r:s=m[j];m=[map(lambda a,b:a-b*(i[j]-(i==s))/s[j],i,s)for i in m]
while~j:
 c=m[j][-1]
 if c:print('%+.15g'%c)[s>c>0:j>=c*c==1or 18]+('x^%d'%j)[:j*j],;s=0
 j-=1

```

Sets up a system of linear equations, matrix style, and then uses Gaussian elimination to solve. Quite a few bytes are spent pretty-printing the output. Non-integer solutions are displayed to 15 digits of accuracy.

As every sequence of *n* real numbers can be generated by a polynomial of order no more than *n-1*, the "function does not exist" case is not handled.

Sample usage:

```
$ echo 1 11 41 79 | python find-poly.py
-2x^3 +22x^2 -42x +23

$ echo 1 11 35 79 | python find-poly.py
x^3 +x^2 -1

$ echo 12 38 78 | python find-poly.py
7x^2 +5x

$ echo 43 12 -5 19 57 | python find-poly.py
-2.25x^4 +27x^3 -98.75x^2 +110x +7

```
> 4 votes

# Answer
There was no restriction in using any specific library, so here is a solution in Python using Sympy

**Python 2.x: 71 Characters**

```
from sympy import*
print interpolate(map(int,raw_input().split()),abc.x)

```
> 2 votes

---
Tags: code-golf
---


title: Sibling Rivalry

text:
# Question
Title: Sibling Rivalry
# Objective Requirements

* A main 'parent' file and a 'child' file.
* The parent file creates a new child file that contains code that must execute after creation.
* The child file that is created must delete the existing sibling file. It wants all the attention, afterall.
* No matter how many times the parent file is executed, a new child file must be created and executed.
* Every time a child file is executed, it must delete it's sibling.
* Since no two siblings are ever truly identical, each child file must also be unique.
* No matter how many child files are created, their names and file contents MUST be unique.
* Only the parent file may explicitly know the child names. (Parent may tell the new child it's older sibling's name.)
* Child files may not simply be renamed.

# Things to consider

* The parent may be modified by the child (children give us all grey hairs anyways, right?), but it's methods may not change.
* The child has to kill its sibling. It cannot force its sibling to commit suicide.
* No human interaction may occur beyond the execution of the parent (such as manual input).

# Winning Requirements

* Only the parent file character length / byte size will be measured.
* Fewest bytes/shortest length wins.

*Inspired by this challenge.*

# Answer
# Perl, 4 characters

Parent file (parent.pl):

```
do a

```

Initial child file (named a):

```
if ($0 =~ /parent\.pl$/)
{
    $ARGV[0]=(-f 'a' ? 'a' : <a*>);
    open B,'>'.($a='a'.time);
    print B <>,'a';
    exec "perl $a";
}
else
{
    open PARENT,'>parent.pl';
    print PARENT "do <a*>";
    close PARENT;

    while (<a*>)
    {
        if ($0 !~ /\Q$_\E$/)
        {
            unlink $_;
        }
    }
}
#

```

Nowhere does the question state that a child file does not exist at the beginning. Further, it *might* even be interpreted as requiring an initial child file (it states that the child must delete its sibling, never mentioning a special case when a sibling does not exist).

I assert that this fulfills all the requirements stated in the question.

One might object that "the child creates its own sibling"; however, this is not true. The parent is the program which is being executed when the child is created. It just gets some code stored in another file and runs that code.

This child not only kills its sibling; it also kills anyone else who is unlucky enough to have a name starting with `a` (consider that collateral damage). This is an artifact of my earlier attempts at the problem. Obviously, any method of killing the sibling could be implemented without changing the score.
> 3 votes

# Answer
## Perl 68 bytes

```
utime$a+open(C,'>',$a=(stat$0)[8]),print(C"unlink~-$a"),$0;`perl $a`

```

Works in a similar fashion to the PHP script below, by updating its own access time to keep track of children names. As with all solutions below, the parent script may be named anything you choose.

---

## PHP 87 bytes

It seems that since our parent is reproducing asexually, all it really needs to do is touch itself.

```
<?touch($f=__FILE__,1+$t=filemtime($f));fputs(fopen($t,w),"<?@unlink($t-1);");`php $t`;

```

---

## PHP 110 (104) bytes

```
<?$f=$g=AAAAAAAA;fputs(fopen(++$f,w),"<?@unlink($g);fputs(fopen('".__FILE__."',c),'<?\$f=\$g=$f');");`php $f`;

```

If the parent is allowed to self-modify, a few bytes can be saved, mainly on quotation marks:

```
<?$f=$g=AAAAAAAA;fputs(fopen(++$f,w),"<?@unlink($g);");fputs(fopen(__FILE__,c),"<?\$f=\$g=$f");`php $f`;

```

Admittedly, the parent isn't very creative when naming its children. The first will be called `AAAAAAAB`, the second `AAAAAAAC` and so forth. The created child will delete its previous sibling, and modify its parent, making it somewhat 'older'.

The first child will contain the following (if the parent script is named `parent.php`):

```
<?@unlink(AAAAAAAA);fputs(fopen('parent.php',c),'<?$f=$g=AAAAAAAB');

```
> 2 votes

# Answer
## Lua, 80

```
n=io.open(0,'a'):write' ':seek()os.execute('echo rm '..n-1 ..' >'..n..'&sh '..n)

```

Parent file (filename `0`) appends one character to its own body on each run and treats its new length as name of next child file (so, first child file will be given name `82` and will contain `rm 81`).
Lua 5.2 required.
Usage: `lua 0`.
> 2 votes

# Answer
## python2 - 154

Needs a subdirectory called `c` to be at the same directory. Generates sh. I took the liberty of calling the file contents unique when it contains the files random (enough?) name. Seems to work although I never close the generated file.

```
import os,binascii
l=os.listdir("c")
n="c/"+binascii.b2a_hex(os.urandom(15))+".py"
open(n,"w+").write("rm $1\n#"+n)
for v in l:os.system("sh "+n+" c/"+v)

```

If we know there is ALWAYS one child, we can shorten the script to 146 bytes:

```
import os,binascii
l=os.listdir("c")[0]
n="c/"+binascii.b2a_hex(os.urandom(15))+".py"
open(n,"w+").write("rm $1\n#"+n)
os.system("sh "+n+" c/"+l)

```
> 0 votes

# Answer
# PHP 279

```
<?php $s="00000000.php";$c="11111111.php";$n=fopen($c,"w");fwrite($n,"<?php \$h=fopen('p.php','r');\$d=fread(\$h,328);\$h=fopen('p.php','w');fwrite(\$h,'<?php \$s=\"'.basename(__FILE__).'\";\$c=\"'.hash('crc32',microtime(true)).'.php\";'.substr(\$d,42));unlink('$s');");`php $c`;

```

It uses crc32 as a hash function, so it's not ENTIRELY 100% unique... I'll try to think of another solution. This one does cause a warning on the first execution, but works as expected every time there-after.

Here is a semi-ungolfed readable version (changed `substr()` start point so it would work ungolfed as a bit of copy+pasta):

```
<?php
$s="02204f88.php";
$c="4b2e0cfb.php";
$n = fopen($c, "w");
fwrite($n,"<?php
\$h=fopen('p.php','r');
\$d=fread(\$h,328);
\$h=fopen('p.php','w');
fwrite(\$h,'<?php
\$s=\"'.basename(__FILE__).'\";
\$c=\"'.hash('crc32',microtime(true)).'.php\";'.substr(\$d,43));
unlink('$s');
");
exec("php $c");

```
> 0 votes

# Answer
**python 2.7 - 110 Characters**

```
c=0
import os
i=`c+1`
o(__file__,'r+').write('c='+i)
o('c'+i,'w').write('rm c'+`c`)
os.system('sh c'+i)

```

The above code would throw an error that can be ignored, the first time it is run.

A slightly longer modified version (128 characters) won;t complain the first time its run

```
c=0
import os
i=`c+1`
o(__file__,'r+').write('c='+i)
o('c'+i,'w').write('rm c'+`c`)
os.system('sh c'+i+'>/dev/null 2>&1')

```
> 0 votes

# Answer
# Tcl - 131 chars

```
set n c[expr rand()].tcl;set f [open $n w+];puts $f [string map "@ $n" {lmap f [glob -ta -di . c*] {if {$f ne {@}} {file del $f}}}]

```

Not sure if I understand this correctly. (Delete all siblings, or only delete last one?)
I use glob and kill all other siblings in the same directory.
Names are unique, files are unique (contains own file name).
> 0 votes

---
Tags: code-golf
---


title: "Cowsay" in short

text:
# Question
Title: "Cowsay" in short
Simulate `cowsay` in the default mode.

```
$ cowsay <<< Hello
 _______
< Hello >
 -------
        \   ^__^
         \  (oo)\_______
            (__)\       )\/\
                ||----w |
                ||     ||

$ perl -e 'print "Long text "x20' | cowsay
 __________________________________________
/ Long text Long text Long text Long text  \
| Long text Long text Long text Long text  |
| Long text Long text Long text Long text  |
| Long text Long text Long text Long text  |
\ Long text Long text Long text Long text  /
 ------------------------------------------
        \   ^__^
         \  (oo)\_______
            (__)\       )\/\
                ||----w |
                ||     ||

```

How short can be the code? The cow and the balloon can be slightly different, but all elements should be present. Dynamic/multiline balloon is a plus.

Explicit list of the required elements:

* Text;
* Balloon;
* Line from the cow to the balloon;
* The cow (eye\[s\], month, ears, body, legs (minimum two), udder, tail).

`/usr/share/cowsay/cows/` may be accessed, but obviously not `/usr/games/cowsay` itself.

Note: here is the `/usr/share/cowsay/cows/default.cow` file:

```
$the_cow = <<"EOC";
        $thoughts   ^__^
         $thoughts  ($eyes)\\_______
            (__)\\       )\\/\\
             $tongue ||----w |
                ||     ||
EOC

```

Usage of the file is optional. When used, it must be accessed by full path. (Windows users may copy it to something like `C:\usr\share\cowsay\co\default.cow`, for fairness).

# Answer
> 29 votes
## Mathematica: Work in progress

I'll pin down the balloon once I can get the cow to settle:

```
ExampleData[{"Geometry3D", "Cow"}]

```

# Answer
> 16 votes
# Perl, 84 characters

```
print$a='-'x52,<>=~s/.{1,50}\b/sprintf"
|%-50s|",$&/rge,"$a
\\
]:p
| )=
| P=
 ¬"

```

Output:

```
----------------------------------------------------
|Long text Long text Long text Long text Long text |
|Long text Long text Long text Long text Long text |
|Long text Long text Long text Long text Long text |
|Long text Long text Long text Long text Long text |
----------------------------------------------------
\
]:p
| )=
| P=
 ¬

```

Admittedly, I golfed the cow as much as I golfed the code. But the Mathematica cow is going to win anyway :)

**Note:** Requires Perl 5.16 for the `/r` non-destructive substitution flag.

# Answer
> 5 votes
# Ruby: ~~152~~ ~~150~~ ~~149~~ ~~146~~ 143 characters

```
load'/usr/share/cowsay/cows/default.cow'
p=%w{U~ o* o o}
puts l=?-*44,gets.gsub(/(.{1,40})\b\s*/){"( %-41s)\n"%$1}+l,$the_cow.gsub(/\$\w+/){p.pop}

```

The cow art is read from the default.cow file and decorated in after-12-rounds-vs-Mike-Tyson manner, similar with a `cowthink -e 'o*' -T 'U~'` invocation.

The text is read from standard input and wrapped at most 40 characters. Line breaks in the input text are not supported.

Sample run:

```
bash-4.2$ perl -e 'print "Long text "x15' | ruby cow.rb
--------------------------------------------
( Long text Long text Long text Long text  )
( Long text Long text Long text Long text  )
( Long text Long text Long text Long text  )
( Long text Long text Long text            )
--------------------------------------------
        o   ^__^
         o  (o*)\_______
            (__)\       )\/\
             U~ ||----w |
                ||     ||

```

## With art bending: ~~138~~ ~~135~~ 136 characters

```
load'/usr/share/cowsay/cows/default.cow'
puts l=?-*44,gets.gsub(/(.{1,40})\b\s*/){"( %-41s)\n"%$1}+l,$the_cow.gsub(/\$.+?([use]+)\b/,'\1')

```

As the elements have to be just present, we can use what we have in place instead of defining realistic ones.

Sample run:

```
bash-4.2$ ruby cow.rb <<< 'Hello poor little cow'
--------------------------------------------
( Hello poor little cow                    )
--------------------------------------------
        s   ^__^
         s  (es)\_______
            (__)\       )\/\
             ue ||----w |
                ||     ||

```

# Answer
> 2 votes
## APL ~~133 140 138~~ 122

This one liner takes screen input in the form of a character vector or array enclosed in quotes via: ←⍎⍞ The appearance of the output is improved by including leading and following spaces in the input.

```
('∘'⍪'∘',((¯2↑1,⍴t)⍴t←⍎⍞),'∘')⍪'∘'⋄5 19⍴(,⍉(19⍴2)⊤323584 196592 63503 4072 3096)\'∘^__^∘(oo)\_______(__)\)\/\||----w|||||'

```

The cow character locations on each row of the array are specified as 19 bit boolean vectors.

To use input the one liner followed by the bubble text in quotes:

```
' Hello '

°°°°°°°°°
° Hello °
°°°°°°°°°
°  ^__^
 ° (oo)\_______
   (__)\       )\/\
       ||----w |
       ||     ||

```

Multi-line text is input as an array.

```
3 36⍴' Multi-line text input as an array. '

°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°
° Multi-line text input as an array. °
° Multi-line text input as an array. °
° Multi-line text input as an array. °
°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°
°  ^__^
 ° (oo)\_______
   (__)\       )\/\
       ||----w |
       ||     ||

```

This version can be tested via the free APL interpreter at www.nars2000.org

# Answer
> 2 votes
## K, 178

```
{-1'g,({"+ ",x,((&/(c-4;60-#x))#" ")," +"}'l),(g:,(&/(64;4+c::#*l:(60*!-_-(#x)%60)_x))#"+"),("+  ^__^";" + (oo)\\_______";"   (__)\\       )\\/\\";"       ||----w |";"       ||     ||");}

```

.

```
k){-1'g,({"+ ",x,((c-#x)#" ")," +"}'l),(g:,(&/(64;4+c::#*l:(60*!-_-(#x)%60)_x))#"+"),("+  ^__^";" + (oo)\\_______";"   (__)\\       )\\/\\";"       ||----w |";"       ||     ||");}"Hello codegolf.stackexchange.com"
++++++++++++++++++++++++++++++++++++
+ Hello codegolf.stackexchange.com +
++++++++++++++++++++++++++++++++++++
+  ^__^
 + (oo)\_______
   (__)\       )\/\
       ||----w |
       ||     ||

```

---
Tags: code-golf, ascii-art
---


# Question
Title: Advanced Code Golf - Disk Operations, and File Allocation
Good Afternoon Golfgeneers.

This is reasonably long and detailed question. Given what it was asking, it needed to be. If you have any questions, please ask them. If there is anything that isn't clear, please alert me to it so I can fix it. This is probably on the tougher side of codegolf.

We are building a lightweight computer, and we need the lightest weight file system possible. The shortest code will be chosen.

We are providing a cutting edge 65536 byte hard drive. For the sake of this prototype, it will be a direct image file, which your program can assume exists, and is in whichever location suits you - ie, a binary file representing the entire hard disk. You may assume that this image is already 'formatted' - ie. if your program relies on something being in the file to work, it can be. If you require the initial empty state to be something other then all-zeros, please state what it is.

There is no memory limit as to RAM used by your application.

The input and output commands will require an interface to the actual hard drive. Like the disk image, your program can assume that the file for input exists, and is wherever you want it to be. Likewise, your program can output wherever is convenient. It must however close the file after executing the input or output command.

You are not being provided with a format which you must use for the disc image - you are free to develop your own. It must be capable of storing up to 248 files. Any file greater then 256 bytes can count as a new file for the sake of this limit for every 256 bytes or part thereof. A file can be up to 63488 bytes. Basically - it must be as capable as a hard drive with 248 sectors of 256 bytes each.

The reasoning behind these seemingly sizes is to give you 2048 bytes of 'administration' - to store details of the files. Each file/folder must be accessible by a name of 4 alphanumeric characters, which may be case sensitive or insensitive as per your preference. If your program supports names of 4 or less characters, then there is bonus of a 0.95 multiplier.

Your program must accept, via stdin, the following commands. Parameters will be separated by a space. The command will be terminated by a newline.

* L - List the names to stdout of all the current files and their sizes in bytes, separated by newlines.
* C a b - Copy file a to new file b.
* D a - Delete file a
* R a b - Renames file a to new name b
* I a - Adds the input file (see note above) as file a
* O a - Outputs file a to the output file

The following errors may be reported to STDOUT or STDERR as valid reasons for a command to fail to execute. You may choose to only print ERR# where # is the number of the error:

* 1 - File doesn't exist
* 2 - File already exists
* 3 - Out of space\*

* Note that your program can not issue this just because it is out of continuous space. If you still have sectors available, you must defragment the disk to make it work.

A folder system is optional - however, will net a bonus of a 0.8 multiplier to your score. If it supports more then 1 level of directory, it will net a bonus of a 0.7 multiplier (not in addition to the 0.8). For the bonus, you must have

* L, R, C and D only work within the current directory. L must list folders in the current directory, as well as the files.
* New command M a b moves file a to folder b. If b is '.', moves file to the parent director
* New command G a goes to folder a. If a is '.', goes to parent folder
* R must also rename folders
* D must also delete folders, and any files/folders within them
* C must also copy folders, and any files/folders within them

The following additional errors may be reported to STDOUT or STDERR as valid reasons for a command to fail to execute.

* 4 - Folder doesn't exist
* 5 - File, not folder required - where, I and O require file names, and a folder was given

Your score is:

* The size, in bytes, of your source code
* Multiplied by

+ 0.95 if you support names of 4, or less characters
    + 0.8 if you support a single level of folders
    + 0.7 if you support multiple levels of folders
    + 0.95 if you support commands (not necessarily file names) in lower or uppercase

Good luck.

# Answer
### Ruby, score 505.4 (560 characters)

```
x,a,b=gets.chomp.split
f=IO.read('F')
e=f[0,4*X=248].unpack 'A4'*X
s=f[4*X,2*X].unpack 's'*X
d=f[6*X..-1].unpack 'A'+s*'A'
u,v,w,y=[[N=nil,q=e.index(a),!t=e.index(""),"e[t]=a;s[t]=(d[t]=IO.binread('I')).size"],[!q,r=e.index(b),!t,"e[t]=b;d[t]=d[q];s[t]=s[q]"],[!q,N,N,"e[q]=d[q]='';s[q]=0"],[!q,r,N,"e[q]=b"],[!q,N,N,"IO.binwrite('O',d[q])"],[N,N,N,'X.times{|i|e[i]>""&&puts(e[i]+" #{s[i]}")}']]['ICDROL'=~/#{x}/i]
u&&$><<"ERR1\n"||v&&$><<"ERR2\n"||w&&$><<"ERR3\n"||eval(y)
d=d*""
d.size>63488&&$><<"ERR3\n"||IO.write('F',(e+s+[d]).pack('A4'*X+'s'*X+'A63488'))

```

Notes:

* Filesystem is located in file `F` in the current directory. `F` must exist and may be created/formatted via the following command: `IO.write('F',(([""]*248)+([0]*248)+[""]).pack('A4'*248+'s'*248+'A63488'))`.
* Input file is always `I` also in the current directoy, output file is `O`.
* Since it wasn't required to check errors, be sure to type correct commands (i.e. no unsupported commands, no missing arguments, too long filenames).
* The file system implementation is extremely simple - for each command the full hard drive is read into memory and rebuild upon (successful) completion.

Bonuses:

* Filenames may be 1-4 chars
* Commands may be upper or lower case

The code is not yet fully golfed but shows already that for a substancial better score I'd try a completely different approach.

Test session (only STDIN/STDOUT is shown but of course each command is prepended by calling the above program):

```
> L
> I F001
> L
F001 558
> I F001
ERR2
> C F002 F003
ERR1
> C F001 F003
> L
F001 558
F003 558
> C F001 F003
ERR2
> R F002 F003
ERR1
> R F001 F003
ERR2
> R F001 F002
> L
F002 558
F003 558
> O F001
ERR1
> O F002
> L
F002 558
F003 558
> D F001
ERR1
> D F002
> L
F003 558
> C F003 F001
> L
F001 558
F003 558
> D F001
> L
F003 558
> D F003
> L

```
> 3 votes

# Answer
## Tcl, score 487,711 (772 bytes)

```
{*}[set a {interp alias {}}] s {} dict se f
{*}$a u {} dict un f
{*}$a h {} dict g
proc 0 {} {return -level 1}
proc p {n a b} {foreach l $n {proc $l $a "global f c;$b;S"}}
p L\ l {} {puts [join [dict k [h $f {*}$c]] \n]}
p C\ c a\ b {s {*}$c $b [h $f {*}$c $b]}
p D\ d a {u {*}$c $a}
p R\ r a\ b {s {*}$c $a [h $f {*}$c $b];u {*}$c $b}
p I\ i a {set i [open i rb];s {*}$c $a [read $i];close $i}
p O\ o a {set o [open o wb];chan puts $o [h $f {*}$c $a];close $o}
p M\ m a\ b {set d $c;if {$b eq "."} {set d [lrange $c 0 end-1]};s {*}$d $a [h $f {*}$c $a];u {*}$c $a}
p G\ g a {if {$a eq "."} {set c [lrange $c 0 end-1]} {lappend c $a}}
p S {} {puts [set o [open F wb]] $f;close $o;return}
set f [read [set i [open F rb]]]
close $i
set c {}
while 1 {{*}[split [gets stdin]]}

```

Bonuses (gotta catch them all):

* support file names with 4 byte or less - or more. I don't care. **0.95**
* support multilevel folders **0.7**
* support lower and upper case commands **0.95**

Known limitations:

* File system `F` must already exist. Empty or whitespace is fine.
* I don't check the size of the file system - I don't care.
* Input file is `i`, outputfile is `o` and the filesystem is in `F`
* Errors will crash the program.
* No checks if file/directory exist, might be an error.
* No difference between a file and a directory. Yes, you can write a directory to output and use this as file system.
* Using a file as directory that is not a valid file system will result in an error.
* No input validation. Invalid commands may throw an error. Or not: `eval puts [expr 1+2]`
* No command to create a directory (was not my idea), but will be created implicit by `I` (also not my idea, and `G` doesn't create)
* `G` does not validate the directory.
* Filenames could contain spaces, but the interface does not support them.
* Concurrent modification of the same file system is not supported.

Some hacks:

* `eval puts $c` -\> current directory, separated by spaces.
* `exit` \- no comment.
* `lappend c .` -\> switches into the subdirectory `.`
> 3 votes

# Answer
# Python 2.7 373 (413 bytes)

```
from pickle import*
E=exit;o=open;D,I,W='DIw'
def T(i):w[i]in d and E('ERR2')
d=load(o(D))
w=raw_input().split();b=w[0].upper()
if b=='L':
 for k in d:print k,len(d[k])
elif b==I:T(1);d[w[1]]=o(I).read()
else:
 a=w[1];a in d or E('ERR1')
 if b in'RC':T(2);d[w[2]]=(b<D and d.get or d.pop)(a)
 if b==D:d.pop(a)
 if b=='O':o(I,W).write(d[a])
d=dumps(d,-1)
x=65536-len(d)
x>-1or E('ERR3')
o(D,W).write(d+I*x)

```

The disk is saved in the Python pickle-Format: to create an empty disk you have to put these two bytes '}.' at the beginning and optionally 65534 fill bytes afterwards. Supports arbitrary large filenames (\*0.95), upper and lowercase commands (\*0.95) and hard links (:-).
> 3 votes

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


# Question
Title: Fastest python code to find a set of winning words in this game
This is a word game from a set of activity cards for children. Below the rules is code to find the best triplet using /usr/share/dict/words. I thought it was an interesting optimization problem, and am wondering if people can find improvements.

## Rules

1. Choose one letter from each of the sets below.
2. Choose a word using the letters chosen (and any others).
3. Score the word.
    * Each letter from the chosen set gets the number shown with the set (repeats included).
    * `AEIOU` count 0
    * All other letters are -2
4. Repeat steps 1-3 above (no reusing letters in step 1) twice more.
5. Final score is the sum of the three word scores.

## Sets

### (set 1 scores 1 point, set 2 scores 2 points, etc.)

1. LTN
2. RDS
3. GBM
4. CHP
5. FWV
6. YKJ
7. QXZ

## Code:

```
from itertools import permutations
import numpy as np

points = {'LTN' : 1,
          'RDS' : 2,
          'GBM' : 3,
          'CHP' : 4,
          'FWV' : 5,
          'YKJ' : 6,
          'QXZ' : 7}

def tonum(word):
    word_array = np.zeros(26, dtype=np.int)
    for l in word:
        word_array[ord(l) - ord('A')] += 1
    return word_array.reshape((26, 1))

def to_score_array(letters):
    score_array = np.zeros(26, dtype=np.int) - 2
    for v in 'AEIOU':
        score_array[ord(v) - ord('A')] = 0
    for idx, l in enumerate(letters):
        score_array[ord(l) - ord('A')] = idx + 1
    return np.matrix(score_array.reshape(1, 26))

def find_best_words():
    wlist = [l.strip().upper() for l in open('/usr/share/dict/words') if l[0].lower() == l[0]]
    wlist = [l for l in wlist if len(l) > 4]
    orig = [l for l in wlist]
    for rep in 'AEIOU':
        wlist = [l.replace(rep, '') for l in wlist]
    wlist = np.hstack([tonum(w) for w in wlist])

    best = 0
    ct = 0
    bestwords = ()
    for c1 in ['LTN']:
        for c2 in permutations('RDS'):
            for c3 in permutations('GBM'):
                for c4 in permutations('CHP'):
                    for c5 in permutations('FWV'):
                        for c6 in permutations('YJK'):
                            for c7 in permutations('QZX'):
                                vals = [to_score_array(''.join(s)) for s in zip(c1, c2, c3, c4, c5, c6, c7)]
                                ct += 1
                                print ct, 6**6
                                scores1 = (vals[0] * wlist).A.flatten()
                                scores2 = (vals[1] * wlist).A.flatten()
                                scores3 = (vals[2] * wlist).A.flatten()
                                m1 = max(scores1)
                                m2 = max(scores2)
                                m3 = max(scores3)
                                if m1 + m2 + m3 > best:
                                    print orig[scores1.argmax()], orig[scores2.argmax()], orig[scores3.argmax()], m1 + m2 + m3
                                    best = m1 + m2 + m3
                                    bestwords = (orig[scores1.argmax()], orig[scores2.argmax()], orig[scores3.argmax()])
    return bestwords, best

if __name__ == '__main__':
    import timeit
    print timeit.timeit('print find_best_words()', 'from __main__ import find_best_words', number=1)

```

The matrix version is what I came up with after writing one in pure python (using dictionaries and scoring each word independently), and another in numpy but using indexing rather than matrix multiplication.

The next optimization would be to remove the vowels from the scoring entirely (and use a modified `ord()` function), but I wonder if there are even faster approaches.

**EDIT**: added timeit.timeit code

**EDIT**: I'm adding a bounty, which I'll give to whichever improvement I most like (or possibly multiple answers, but I'll have to accrue some more reputation if that's the case).

# Answer
> 3 votes
Using Keith's idea of precomputing the best possible score for each word, I managed to reduce the execution time to about 0.7 seconds on my computer (using a list of 75,288 words).

The trick is to go through the combinations of words to be played instead of all combinations of letters picked. We can ignore all but a few combinations of words (203 using my word list) because they can't get a higher score than we've already found. Nearly all of the execution time is spent precomputing word scores.

Python 2.7:

```
import collections
import itertools

WORDS_SOURCE = '../word lists/wordsinf.txt'

WORDS_PER_ROUND = 3
LETTER_GROUP_STRS = ['LTN', 'RDS', 'GBM', 'CHP', 'FWV', 'YKJ', 'QXZ']
LETTER_GROUPS = [list(group) for group in LETTER_GROUP_STRS]
GROUP_POINTS = [(group, i+1) for i, group in enumerate(LETTER_GROUPS)]
POINTS_IF_NOT_CHOSEN = -2

def best_word_score(word):
    """Return the best possible score for a given word."""

    word_score = 0

    # Score the letters that are in groups, chosing the best letter for each
    # group of letters.
    total_not_chosen = 0
    for group, points_if_chosen in GROUP_POINTS:
        letter_counts_sum = 0
        max_letter_count = 0
        for letter in group:
            if letter in word:
                count = word.count(letter)
                letter_counts_sum += count
                if count > max_letter_count:
                    max_letter_count = count
        if letter_counts_sum:
            word_score += points_if_chosen * max_letter_count
            total_not_chosen += letter_counts_sum - max_letter_count
    word_score += POINTS_IF_NOT_CHOSEN * total_not_chosen

    return word_score

def best_total_score(words):
    """Return the best score possible for a given list of words.

    It is fine if the number of words provided is not WORDS_PER_ROUND. Only the
    words provided are scored."""

    num_words = len(words)
    total_score = 0

    # Score the letters that are in groups, chosing the best permutation of
    # letters for each group of letters.
    total_not_chosen = 0
    for group, points_if_chosen in GROUP_POINTS:
        letter_counts = []
        # Structure:  letter_counts[word_index][letter] = count
        letter_counts_sum = 0
        for word in words:
            this_word_letter_counts = {}
            for letter in group:
                count = word.count(letter)
                this_word_letter_counts[letter] = count
                letter_counts_sum += count
            letter_counts.append(this_word_letter_counts)

        max_chosen = None
        for letters in itertools.permutations(group, num_words):
            num_chosen = 0
            for word_index, letter in enumerate(letters):
                num_chosen += letter_counts[word_index][letter]
            if num_chosen > max_chosen:
                max_chosen = num_chosen

        total_score += points_if_chosen * max_chosen
        total_not_chosen += letter_counts_sum - max_chosen
    total_score += POINTS_IF_NOT_CHOSEN * total_not_chosen

    return total_score

def get_words():
    """Return the list of valid words."""
    with open(WORDS_SOURCE, 'r') as source:
        return [line.rstrip().upper() for line in source]

def get_words_by_score():
    """Return a dictionary mapping each score to a list of words.

    The key is the best possible score for each word in the corresponding
    list."""

    words = get_words()
    words_by_score = collections.defaultdict(list)
    for word in words:
        words_by_score[best_word_score(word)].append(word)
    return words_by_score

def get_winning_words():
    """Return a list of words for an optimal play."""

    # A word's position is a tuple of its score's index and the index of the
    # word within the list of words with this score.
    #
    # word played: A word in the context of a combination of words to be played
    # word chosen: A word in the context of the list it was picked from

    words_by_score = get_words_by_score()
    num_word_scores = len(words_by_score)
    word_scores = sorted(words_by_score, reverse=True)
    words_by_position = []
    # Structure:  words_by_position[score_index][word_index] = word
    num_words_for_scores = []
    for score in word_scores:
        words = words_by_score[score]
        words_by_position.append(words)
        num_words_for_scores.append(len(words))

    # Go through the combinations of words in lexicographic order by word
    # position to find the best combination.
    best_score = None
    positions = [(0, 0)] * WORDS_PER_ROUND
    words = [words_by_position[0][0]] * WORDS_PER_ROUND
    scores_before_words = []
    for i in xrange(WORDS_PER_ROUND):
        scores_before_words.append(best_total_score(words[:i]))
    while True:
        # Keep track of the best possible combination of words so far.
        score = best_total_score(words)
        if score > best_score:
            best_score = score
            best_words = words[:]

        # Go to the next combination of words that could get a new best score.
        for word_played_index in reversed(xrange(WORDS_PER_ROUND)):
            # Go to the next valid word position.
            score_index, word_chosen_index = positions[word_played_index]
            word_chosen_index += 1
            if word_chosen_index == num_words_for_scores[score_index]:
                score_index += 1
                if score_index == num_word_scores:
                    continue
                word_chosen_index = 0

            # Check whether the new combination of words could possibly get a
            # new best score.
            num_words_changed = WORDS_PER_ROUND - word_played_index
            score_before_this_word = scores_before_words[word_played_index]
            further_points_limit = word_scores[score_index] * num_words_changed
            score_limit = score_before_this_word + further_points_limit
            if score_limit <= best_score:
                continue

            # Update to the new combination of words.
            position = score_index, word_chosen_index
            positions[word_played_index:] = [position] * num_words_changed
            word = words_by_position[score_index][word_chosen_index]
            words[word_played_index:] = [word] * num_words_changed
            for i in xrange(word_played_index+1, WORDS_PER_ROUND):
                scores_before_words[i] = best_total_score(words[:i])
            break
        else:
            # None of the remaining combinations of words can get a new best
            # score.
            break

    return best_words

def main():
    winning_words = get_winning_words()
    print winning_words
    print best_total_score(winning_words)

if __name__ == '__main__':
    main()

```

This returns the solution `['KNICKKNACK', 'RAZZMATAZZ', 'POLYSYLLABLES']` with a score of 95. With the words from Keith's solution added to the word list I get the same result as him. With thouis's "xylopyrography" added, I get `['XYLOPYROGRAPHY', 'KNICKKNACKS', 'RAZZMATAZZ']` with a score of 105.

# Answer
> 5 votes
Here's an idea - you can avoid checking lots of words by noticing that most words have awful scores. Say you have found a pretty good scoring play that gets you 50 points. Then any play with more than 50 points must have a word of at least ceil(51/3)=17 points. So any word that can't possibly generate 17 points can be ignored.

Here's some code that does the above. We compute the best possible score for each word in the dictionary, and store it in an array indexed by score. Then we use that array to check only words that have the required minimum score.

```
from itertools import permutations
import time

S={'A':0,'E':0,'I':0,'O':0,'U':0,
   'L':1,'T':1,'N':1,
   'R':2,'D':2,'S':2,
   'G':3,'B':3,'M':3,
   'C':4,'H':4,'P':4,
   'F':5,'W':5,'V':5,
   'Y':6,'K':6,'J':6,
   'Q':7,'X':7,'Z':7,
   }

def best_word(min, s):
    global score_to_words
    best_score = 0
    best_word = ''
    for i in xrange(min, 100):
        for w in score_to_words[i]:
            score = (-2*len(w)+2*(w.count('A')+w.count('E')+w.count('I')+w.count('O')+w.count('U')) +
                      3*w.count(s[0])+4*w.count(s[1])+5*w.count(s[2])+6*w.count(s[3])+7*w.count(s[4])+
                      8*w.count(s[5])+9*w.count(s[6]))
            if score > best_score:
                best_score = score
                best_word = w
    return (best_score, best_word)

def load_words():
    global score_to_words
    wlist = [l.strip().upper() for l in open('/usr/share/dict/words') if l[0].lower() == l[0]]
    score_to_words = [[] for i in xrange(100)]
    for w in wlist: score_to_words[sum(S[c] for c in w)].append(w)
    for i in xrange(100):
        if score_to_words[i]: print i, len(score_to_words[i])

def find_best_words():
    load_words()
    best = 0
    bestwords = ()
    for c1 in permutations('LTN'):
        for c2 in permutations('RDS'):
            for c3 in permutations('GBM'):
            print time.ctime(),c1,c2,c3
                for c4 in permutations('CHP'):
                    for c5 in permutations('FWV'):
                        for c6 in permutations('YJK'):
                            for c7 in permutations('QZX'):
                                sets = zip(c1, c2, c3, c4, c5, c6, c7)
                                (s1, w1) = best_word((best + 3) / 3, sets[0])
                                (s2, w2) = best_word((best - s1 + 2) / 2, sets[1])
                                (s3, w3) = best_word(best - s1 - s2 + 1, sets[2])
                                score = s1 + s2 + s3
                                if score > best:
                                    best = score
                                    bestwords = (w1, w2, w3)
                                    print score, w1, w2, w3
    return bestwords, best

if __name__ == '__main__':
    import timeit
    print timeit.timeit('print find_best_words()', 'from __main__ import find_best_words', number=1)

```

The minimum score gets rapidly up to 100, which means we need only consider 33+ point words, which is a very small fraction of the overall total (my `/usr/share/dict/words` has 208662 valid words, only 1723 of which are 33+ points = 0.8%). Runs in about half an hour on my machine and generates:

```
(('MAXILLOPREMAXILLARY', 'KNICKKNACKED', 'ZIGZAGWISE'), 101)

```

---
Tags: fastest-code, python, optimization
---


# Question
Title: Rosetta Stone Challenge: Draw a Box Plot
The goal of a Rosetta Stone Challenge is to write solutions in as many languages as possible. Show off your programming multilingualism!

# The Challenge

Your challenge is to implement a program that will input a list of numbers and output a box plot of the data, *in as many programming languages as possible*. The box plot will display the quartiles and outliers in the data, and it will even have a scale. You are allowed to use any sort of standard library function that your language has, since this is mostly a language showcase.

## What is a "box plot?"

A box plot is a way of graphing data. A box plot has a few essential features. The first feature is a box, with either side being located at the first and third quartiles of the data. There is a line down the center of the box plot that gives the median. On either end of the box plot, there are "whiskers" that help show the variance of the data. The whisker extends from the box to the least and greatest points in the data set, excluding the outliers. The outliers are plotted as individual points.

First, take the median of the data. Then, take all of the data points that are *strictly less than* the median, and compute the median of this set to become the first quartile (Q1). Take all of the data points that are *strictly greater than* the median, and compute the median of this set to become the third quartile (Q3). Find the value of `R = 1.5*(Q3 - Q1)`. Any numbers less `Q1 - R` this are outliers. Any numbers greater than `Q3 + R` are outliers. Take the set of all data points that are *not* outliers, and the minimum and maximum of this set determines the ends of the two whiskers.

## Input

Input will begin with `n=` followed by a number. There will then be `n` numbers, one per line. All of the numbers will be integers from 0 to 63, inclusive.

```
n=8
29
1
22
18
12
16
16
22

```

## Output

Output will be a rendition of the box plot. One possible way to draw the plot is by rendering it in ASCII. You can render the box plot in many ways other than ASCII, but the main requirement is that drawn large enough so that it is possible to tell the exact locations of the important features. The box plot should have a scale, consisting of around 5-10 numbers equally spaced. Here is one example plot of the above data:

```
              +--+----+
              |  |    |
 X          +-+  |    +------+
              |  |    |
              +--+----+

0    0    1    1    2    2    3
0    5    0    5    0    5    0

```

# The Objective Winning Criterion

As for an objective winning criterion, here it is: Each language is a separate competition as to who can write the shortest entry, but the overall winner would be the person who wins the most of these sub-competitions. This means that a person who answers in many uncommon languages can gain an advantage. Code-golf is mostly a tiebreaker for when there is more than one solution in a language: the person with the shortest program gets credit for that language.

## Rules, Restrictions, and Notes

Your program can be written in any language that existed prior to April 11th, 2013. I will also have to rely on the community to validate some responses written in some of the more uncommon/esoteric languages, since I am unlikely to be able to test them.

---

# Current Leaderboard

This section will be periodically updated to show the number of languages and who is leading in each.

* Julia (604) - plannapus
* Mathematica (71) - chyanog
* Python2.X (85) - Abhijit
* R (34) - plannapus

---

# Current User Rankings

1. plannapus - 2
2. Abhijit - 1
3. chyanog - 1

# Answer
> 6 votes
## R: 34 characters

Of course, R being a language used for statistics, it comes with a function `boxplot` to do this (which needs a wrapper here to accomodate the input style):

```
f=function(x)boxplot(scan(x,sk=1))

```

Usage: Given a file `input1.txt` containing the following:

```
n=10
29
1
22
19
9
13
15
22
63
2

```

Then `f("input1.txt")` produces:

## Julia: 604 characters

This is my first ever function in Julia, so my apologies to fans of Julia if this is badly written.

```
function g(f)
a=int(split(readall(open(f)),'\n')[2:])
b,c,d=int(quantile(a,[.25,.5,.75]))
w=1.5*(d-b)
o=a[a.<b-w]
O=a[a.>d+w]
t=int(b-w>0?b-w:0)
u=int(d+w<63?d+w:63)
S=s=""
if !isempty(o)
for i in 1:length(o)
s=s*lpad('x',[0,o][i+1]-[0,o][i]-1,' ')
end
end
if !isempty(O)
for i in 1:length(O)
S=S*lpad('x',[0,O][i+1]-[0,O][i]-u-1,' ')
end
end
x="0"
for i in 9:9:63
x=x*lpad(string(i),i-(i-9)," ")
end
v=isempty(o)?b-1:b-o[length(o)]-1
print(x*"\n"*lpad('+'*'-'^(d-b-1)*'+',d,' ')*'\n'*s*lpad('-'^(b-t-1),v,' ')*'|'*lpad('|',c-b,' ')*' '^(d-c-1)*'|'*'-'^(u-d)*S*'\n'*lpad('+'*'-'^(d-b-1)*'+',d,' '))
end

```

Usage:

```
g("input1.txt")
0        9       18       27       36       45       54       63
         +-----------+
---------|      |    |------------------                     x
         +-----------+

```

# Answer
> 2 votes
**Python2.X 85 Characters, using matplotlib**

```
import matplotlib.pylab as p
p.boxplot(map(input,['']*int(raw_input()[2:])))
p.show()

```

# Answer
> 1 votes
**Mathematica 71**

```
BoxWhiskerChart[Input/@x~Array~FromDigits@StringTake[InputString[],-1]]

```

---
Tags: code-golf, math, rosetta-stone
---


title: Lawnmower Patterns

text:
# Question
Title: Lawnmower Patterns
Taken from Google Code Jam 2013 Qualification Round Problem B:

> Alice and Bob have a lawn in front of their house, shaped like an N metre by M metre rectangle. Each year, they try to cut the lawn in some interesting pattern. They used to do their cutting with shears, which was very time-consuming; but now they have a new automatic lawnmower with multiple settings, and they want to try it out.
>
> The new lawnmower has a height setting - you can set it to any height h between 1 and 100 millimetres, and it will cut all the grass higher than h it encounters to height h. You run it by entering the lawn at any part of the edge of the lawn; then the lawnmower goes in a straight line, perpendicular to the edge of the lawn it entered, cutting grass in a swath 1m wide, until it exits the lawn on the other side. The lawnmower's height can be set only when it is not on the lawn.
>
> Alice and Bob have a number of various patterns of grass that they could have on their lawn. For each of those, they want to know whether it's possible to cut the grass into this pattern with their new lawnmower. Each pattern is described by specifying the height of the grass on each 1m x 1m square of the lawn.
>
> The grass is initially 100mm high on the whole lawn.

Write a function which takes a 2D array of integer heights and determines whether the lawn can be cut accordingly.

Here are 100 test cases from Google Code Jam. The first 35 cases should pass, the rest should not.

Shortest code wins.

# Answer
## J, 15 chars

```
   (-:>./"1<./>./)

```

Didn't expect this short solution.

Short explanation:

```
(input == ((max of rows of input) table with min of left and right (max in columns of input)))
(      -:          >./"1                        <./                       >./              )

```

If your function is 4 other function like in the solution: `(f1 f2 f3 f4)` and an input J computes it like `f1(input,f3(f2(input),f4(input)))` i.e. `input f1 ((f2 input) f3 (f4 input))`.
> 9 votes

# Answer
### APL, 15 characters

```
{⍵≡(⌈/⍵)∘.⌊⌈⌿⍵}

```

Explanation:

* `⌈⌿⍵` calculates the maximum of the columns of rhs
* `⌈/⍵` does the same with rows
* `∘.⌊` does the outer product of the previous two with respect to function minimum
* `⍵≡` compares the result to the rhs

Examples:

```
      {⍵≡(⌈/⍵)∘.⌊⌈⌿⍵} 3 3 ⍴ 2 1 2 1 1 1 2 1 2
1

      {⍵≡(⌈/⍵)∘.⌊⌈⌿⍵} 2 3 ⍴ 2 2 2 2 1 1
0

```
> 5 votes

# Answer
# Python, 112 104

```
z=zip
y=lambda l:[[max(r)]*len(r)for r in l]
f=lambda l:l==[map(min,z(*r))for r in z(y(l),z(*y(z(*l))))]

```
> 3 votes

---
Tags: code-golf
---


title: Guess my Number - Code Golf

text:
# Question
Title: Guess my Number - Code Golf
The puzzle is as follows:

Create the traditional 'Guess my Number' game in as little keystrokes as possible. The player should input a guess between and including 1 and 100, and the computer should reply with either `+` (meaning the player needs to guess higher), `-` (meaning the player needs to guess lower) or `=` (meaning the player has guessed the number. The game continues until the player has guessed the number. The number that the computer generates MUST be a random number between and including 1 and 100.

### Sample gameplay

```
50
+
75
-
60
-
55
+
57
=

```

Happy Golfing!

# Answer
> 10 votes
# Ruby: ~~63~~ ~~58~~ ~~52~~ 49 characters

```
puts"=-+"[r=$_.to_i<=>n||=1+rand(100)];r==0&&exit

```

Sample run:

```
bash-4.2$ ruby -ne 'puts"=-+"[r=$_.to_i<=>n||=1+rand(100)];r==0&&exit'
50
-
25
+
37
+
43
-
40
+
42
=

```

# Answer
> 9 votes
**Python 84 83 characters**

```
import os
a,c=0,ord(os.urandom(1))%100+1
while c-a:a=input();print'=-+'[c!=a:][c>a]

```

# Answer
> 6 votes
**Perl 57 53 50 (thanks to @manatwork) Characters**

```
$_=qw(= + -)[$^T%100+1<=>$_];print"$_
";exit if/=/

```

Note You need to invoke with `-n` option

Alternate version as suggested by @primo

**Perl 40 Characters**

```
$_=chr 44-($^T%100+1<=>$_||exit print'=')

```

# Answer
> 6 votes
# JavaScript, 52

```
for(u=r=1+new Date%100;u=r-prompt(u<0?'-':'+'););'='

```

Just paste it in the console.

# Answer
> 5 votes
## APL (28)

```
{'='≠⎕←'+=-'[2+×⎕-⍵]:∇⍵}?100

```

# Answer
> 3 votes
**C#: 147 136 Characters**

It won't beat most other languages, but here's a C# solution for fun:

```
var r=new Random().Next(1,100);var g=0;while(g!=r){g=int.Parse(Console.ReadLine());Console.WriteLine(""+g+'\n'+(g<r?'+':g>r?'-':'='));}

```

# Answer
> 3 votes
# Haskell, 128

Won’t be winning any awards, but here it is.

```
main=fix.(.)(=<<(read<$>getLine)).f=<<(`mod`100).fst.next<$>newStdGen where p=putStrLn;f y r x|x<y=p"+">>r|x>y=p"-">>r|True=p"="

```

Ungolfed logic and imports:

```
import Control.Applicative
import Data.Function
import System.Random

main :: IO ()
main = do
  random <- newStdGen
  let number = fst (next random) `mod` 100
  fix $ \loop -> do
    guess <- read <$> getLine
    check number guess loop
  where
    check number guess loop
      | guess < number = do
        putStrLn "+"
        loop
      | guess > number = do
        putStrLn "-"
        loop
      | otherwise = putStrLn "="

```

# Answer
> 2 votes
**C89 92 90 89 (Thanks to @ugoren) 84 characters** *running on OS and linked with Linker supporting ASLR*

```
main(c,g){g=g/8%100+1;while(scanf("%d",&c)&&printf("%c\n",g-c?"-+"[c<g]:'=')&&c-g);}

```

# Answer
> 2 votes
## Clojure (117 characters)

```
java -jar clojure.jar  -e "(loop[n(int(*(rand 100)))]((get{-1#(prn '+)0#(do(prn '=)(System/exit 0))1#(prn '-)}(compare(eval(read))n)))(recur n))"
50
+
75
+
90
-
86
-
82
=

```

## Clojure (74 characters)

Guessing a real number. Nobody will be patient enought to solve to "=", so nobody notice the missing exit.

```
java -jar clojure.jar  -e "(loop[n(rand)](prn (get{-1 '+ 0 '= 1 '-}(compare(eval(read))n)))(recur n))"
0.5
+
0.8
-
0.6
+
0.7
+
0.75
-
0.72
+
0.74
+
0.745
+
0.748
-
0.746
-
0.7455
-
...

```

# Answer
> 2 votes
# R, ~~89~~ 85 chars

```
s=sample(1:100,1);while(s!=(a=as.real(readline())))cat(ifelse(a>s,"-","+"));cat("=")

```

# Answer
> 1 votes
## K, 69

```
b:1b;g:1+*1?100;while[b;-1(*$[g<f:"I"$m:0:0;"-";g>f;"+";("=";b:0b)])]

```

Could definitely be golfed more

```
k)b:1b;g:1+*1?100;while[b;-1(*$[g<f:"I"$m:0:0;"-";g>f;"+";("=";b:0b)])]
50
+
75
-
60
+
65
-
63
+
64
=

```

# Answer
> 1 votes
# Tcl, 96 chars

```
set n [expr int(rand()*100)+1];while {[gets stdin g]&&$g!=$n} {puts [expr $g<$n?"+":"-"]};puts =

```

Ok, and now guessing a real number (91 chars):

```
set n [expr rand()*100+1];while {[gets stdin g]&&$g!=$n} {puts [expr $g<$n?"+":"-"]};puts =

```

And here a small script to test this: (Solver)

```
set fd [open "| /usr/local/bin/tclsh hilo.tcl" RDWR]
fconfigure $fd -buffering none
lassign 0\ 100 + -
while 1 {
    puts "-> [set new [expr {(${-} - ${+}) / 2. + ${+}}]]"
    puts $fd $new
    gets $fd in
    puts "<- $in"
    if {$in in {+ -}} {set $in $new} break
}

```

Change the `2.` to `2` for integers.

# Answer
> 1 votes
# Go, 152

Golfed :

```
package main
import(f"fmt";"os")
func main(){
c:=1+os.Getpid()%100
u:=0
for u!=c{
f.Scanf("%d",&u)
s:="="
if u<c{s="+"}else if u>c{s="-"}
f.Println(s)}}

```

Ungolfed :

```
package main

import (
    f "fmt"
    "os"
)

func main() {
    c := 1 + os.Getpid()%100
    u := 0
    for u != c {
        f.Scanf("%d", &u)
        s := "="
        if u < c {
            s = "+"
        } else if u > c {
            s = "-"
        }
        f.Println(s)
    }
}

```

Session :

> guess
>
> 4
>
> +
>
> 88
>
> -
>
> 66
>
> +
>
> 77
>
> -
>
> 71
>
> +
>
> 73
>
> +
>
> 75
>
> =

Hard to golf when you start any program with `package main` and a list of imports...

# Answer
> 1 votes
## R: 88 characters

```
r=sample(1:100,1);i=scan(n=1);while(i!=r){cat(ifelse(i<r,"+","-"));i=scan(n=1)};cat("=")

```

Ex:

```
> r=sample(1:100,1);i=scan(n=1);while(i!=r){cat(ifelse(i<r,"+","-"));i=scan(n=1)};cat("=")
1: 23
Read 1 item
+
1: 46
Read 1 item
-
1: 35
Read 1 item
-
1: 31
Read 1 item
-
1: 28
Read 1 item
+
1: 30
Read 1 item
-
1: 29
Read 1 item
=
>

```

# Answer
> 1 votes
## PHP: 95 91 87 73 71 65 chars

```
<?php $n=rand(1,100);while(@$g!=$n){$g=trim(fgets(STDIN));echo$g==$n?'=':($g>$n?'-':'+')."\n";}
<? for($n=rand(1,100);@$g!=$n?$g=trim(fgets(STDIN)):0;)echo$g==$n?'=':($g>$n?'-':'+')."\n";
<? for($n=rand(1,100);$n!=$g=trim(fgets(STDIN));print(($g>$n?'-':'+')."\n"));echo"=\n";
<? for($n=rand(1,100);$n!=$g=fgets(STDIN);print(($g>$n?'-':'+')."\n"))?>=
<? for($n=rand(1,100);$n!=$g=fgets(STDIN);print($g>$n?'-':'+')."\n")?>=

```

```
<?for($n=rand(1,100);$n!=$g=fgets(STDIN);print$g>$n?"-
":"+
")?>=

```

# Answer
> 1 votes
# C: 86 characters

```
i;main(r){r+=(7*time(0)+3)%100;while(scanf("%d",&i)&&puts(i<r?"+":i>r?"-":"=")&&i-r);}

```

It is well-behaved, implements a simple LCG and compiles under both Clang (Clang is much more picky than GCC) and GCC.

# Answer
> 1 votes
## R 70

```
n=sample(1e2)[1];while(n-(g=scan(n=1)))cat(if(n>g)"+"else"-");cat("=")

```

# Answer
> 1 votes
VB.net 146

`Dim r,g As Integer:Dim s As String:r=New Random().Next(1,100):Do Until g=r:g=InputBox(s):If g<r Then s="+" Else If r=g Then s="-" Else s="="
Loop`

# Answer
> 0 votes
Javascript (75 **74** chars):

```
for(n=1+Math.random(a=alert)*100>>0;(g=+prompt())-n;)a('+-'[+(g>n)]);a('=')
for(n=1+Math.random(a=alert)*100>>0;(g=+prompt())-n;)a(n>g?'+':'-');a('=')

```

Numbers are actually random

# Answer
> 0 votes
# J: 64 characters

```
r=.>:?100
while.(t=.{&'<=>'>:*-&r".(1!:1)1)~:'='do.t(1!:2)2 end.t

```

Doing I/O in J is sort of bulky compared to the rest of the language.

# Answer
> 0 votes
**vbScript 115 110**

Randomize:dim n,r,s:r=(Int)((100\*Rnd+1)\*2):do until(r=n\*2):n=inputbox(s):If(n\*2\>r)Then:s="-":else:s="+":end if:loop

```
Randomize:dim n,r,s:r=Int(100*Rnd+1)*2:do until r=n*2:n=inputbox(s):If(n*2>r)Then:s="-":else:s="+":end if:loop

```

# Answer
> 0 votes
**Mathematica 66**

```
n=RandomInteger@100;For[,(i=Input[])!=n,Print@If[n>i,"+","-"]];"="

```

# Answer
> 0 votes
## vba, 95

(immediate window)

```
randomize:z=int(rnd()*100)+1:while q<>z:q=cint(inputbox(q)):?iif(q<z,"+",iif(q>z,"-","=")):wend

```

# Answer
> 0 votes
## GWBASIC, 104

```
1 RANDOMIZE TIMER:Z=INT(RND*100)+1:WHILE Q<>Z:INPUT Q:IF Q<Z THEN ?"+" ELSE IF Q>Z THEN ?"-"
2 WEND:?"="

```

(just because I can)

---
Tags: code-golf
---