title: Make an almost quine

text:
# Question
Title: Make an almost quine
I wanted to fool a friend by giving him a quine that *almost* worked, but became sloppier and sloppier.

Create a program that, when run, will output the program, but one character off. Either one character can be added, removed or both (one character changes). But only **one** character.

Your score will be `(length of your program) / floor(sqrt(number of times the program almost quines))` (Where `/ 0` is infinity)

`number of times the program almost quines` is how many times your program runs while only changing one character in stdout. Your program may not accept input. It may also not print a program it has already printed.

You may also **not** add a character that you have previously added before, or remove a character from the same index. For example, if you have added `1` before, and you add `1` again, that's where the `number of times the program almost quines` stops. If you remove the first character, you may not remove the first character again. If you changed the third character into a `2`, you may not add a `2` or remove the third character.

# Answer
> 7 votes
# CJam, 0.000884

```
{_,6/[{64md}6*](124+\+'�f++`"1$~"}""1$~

```

Here, � denotes the unprintable character with code point 128. Try it online.

### Idea

This approach appends all UCS characters (original specification) with code points between U+4000000 and U+7FFFFFFF to the initially empty string that follows the code block.

We choose UTF-8, which encodes each of these characters using a 6 byte string as follows:

```
1111110u₂     10vvvvvv₂     10wwwwww₂     10xxxxxx₂     10yyyyyy₂     10zzzzzz₂

252 + u       128 + vvvvvv  128 + wwwwww  128 + xxxxxx  128 + yyyyyy  128 + zzzzzz

```

Thus, we can encode the *nth* character in this range by computing its 6 least significant digits in base 64 and adding 252 to the most significant and 128 to the remaining ones.

### Scoring

There are `2 ** 31 = 2,147,483,648` 6 byte UTF-8 characters and the length of the original code is 39, so the score is `39 / floor(2 ** 15.5) = 39 / 46340 = 0.0008416055243849806`.

### How it works

```
{                                }""    e# Push the code block and an empty string.
                                    1$~ e# Execute a copy of the code block.
 _,                                     e# Push the length of the string.
   6/                                   e# Divide by 6 to get the number of chars.
      {64md}6*                          e# Perform modular division six times.
     [        ]                         e# Collect the results in an array.
               (124+\+                  e# Add 124 to the first element.
                      '�f+              e# Add 128 to all and cast each to Char.
                          +             e# Concatenate the strings.
                           `            e# Push a string representation.
                            "1$~"       e# Push '1$~' to complete the quine.

```

# Answer
> 6 votes
# CJam, 46 bytes, 65504 add, 65505 del, Score 0.127424

```
{`-2<_0c#)!{'#/~(_)\+\+S+]'#*}*W<"
}_~"e#
}_~

```

Test it here.

The basic form is a standard generalised CJam quine. To "almost quine", there's a comment `e#` at the end of the quine's block, where I can freely add characters without affecting the code. Note that the comment initially contains a single space.

The program continues adding characters to the *front* of the comment, starting at `!` and then going in order of ASCII value. CJam's character codes wrap around after 216 so at some point, this will add a null byte. Once that happens, the program starts removing bytes from the *end* of the comment (such that the position of the removed character is always different) until the comment is empty.

# Answer
> 5 votes
# CJam, 19 bytes, 65536 add, 0 del, Score 0.074219

```
"a"{\)_)++`\"_~"}_~

```

Simpler is better.

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


title: Digits Digging a Dungeon

text:
# Question
Title: Digits Digging a Dungeon
> **Edit:** I will award a **100-reputation bounty** for the first solver of the **bonus puzzle** at the end of the question!
>
> I will add the bounty to the question only when the answer appears as this bounty has no deadline.

Given a non-decreasing list of one-digit positive integers, you should determine how deep dungeon the digits will dig.

```
███  ███  A dungeon with 5 blocks removed and a depth of 3.
███  ███
███ ████
████████

```

Before the start of the digging the ground is level.

Every digit can remove exactly one block of soil from below itself but it has to reach that position from outside the dungeon and after it removed the block has to leave the dungeon. While doing so a digit **can't descend or ascend more than its numerical value** at any horizontal step.

The digits use the following strategy for digging:

* The digit with the smallest value digs firsts and after that the next digger is always the next smallest value from the rest of the digits.
* The first digit can dig at any position. (All ground is the same.)
* The following digits always dig at the leftmost already started column where they can go and come out. If no such column exists they start to dig a new column on the right side of the rightmost one.

For example the digits `1 1 1 2 3 3` would dig the following dungeon (step-by-step visualization with numbers marking which kind of digit dig out that position):

```
███1████    ███11███    ███11███    ███11███    ███11███    ███11███
████████    ████████    ███1████    ███1████    ███1████    ███13███
████████    ████████    ████████    ███2████    ███2████    ███2████
████████    ████████    ████████    ████████    ███3████    ███3████
████████    ████████    ████████    ████████    ████████    ████████

```

Explanation for the example:

* The second `1` couldn't climb out of the only available column if it would deepen it to `2`-deep so it digs right to it.
* The third `1` can dig in the leftmost column creating a `2`-deep column as it can move out into the `1`-deep column and then to the ground level.
* The next `2` and `3` both can dig in the leftmost column.
* The last `3` can't dig in the leftmost column but can in the next one.

## Input

* A non-decreasing list of positive one-digit integers with at least one element.

## Output

* A single positive integer, the depth of the constructed dungeon.

## Examples

Input =\> Output (with the depths of the columns of the dungeon from left to right as explanation which is not part of the output)

```
[3]  =>  1
(column depths are [1])

[1, 1, 1, 2, 3, 3]  =>  4
(column depths are [4, 2])

[1, 1, 1, 1, 1, 1, 1, 1]  =>  3
(column depths are [3, 2, 2, 1])

[1, 1, 1, 1, 1, 3, 3, 3, 3, 3, 3, 5, 5, 5, 5, 5, 5, 5, 5]  =>  11
(column depths are [11, 6, 2])

[1, 1, 1, 1, 1, 2, 2, 9, 9, 9]  =>  7
(column depths are [7, 2, 1])

[2, 2, 2, 2, 2, 5, 5, 5, 7, 7, 9]  =>  9
(column depths are [9, 2])

[1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5]  =>  10
(column depths are [10, 5])

[1, 2, 2, 2, 3, 3, 3, 3, 3, 4, 4, 5, 5, 5, 5, 7, 7, 9]  =>  13
(column depths are [13, 5])

[1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9]  =>  13
(column depths are [13, 5])

[1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9]  =>  21
(column depths are [21, 12, 3])

```

This is code-golf so the shortest entry wins.

## Bonus puzzle

Can you prove (or disprove) that the strategy described in the *"The digits use the following strategy for digging"* section always gives the deepest possible dungeon for the given digits?

# Answer
# Pyth, 21 bytes

```
huXf>+H@GhT@GT0G1Qm0Q

```

Try it online: Single Demonstration or Test Suite

### Explanation:

```
                  m0Q   generate a list of zeros of length len(input)
                        This will simulate the current depths
 u               Qm0Q   reduce G, starting with G=[0,...,0], for H in input():
   f          0             find the first number T >= 0, which satisfies:
    >+H@GhT@GT                  H + G[T+1] > G[T]
  X            G1           increase the depth at this position by one
                            update G with this result
h                       print the first element in this list

```
> 5 votes

# Answer
# Java, 199

```
import java.util.*;a->{List<Integer>l=new ArrayList();l.add(0);int x,y,z=0;s:for(int i:a){for(x=0;x<z;x++)if((y=l.get(x))-l.get(x+1)<i){l.set(x,l.get(x)+1);continue s;}l.add(z++,1);}return l.get(0);}

```

## Expanded, runnable version

```
import java.util.*;
class DIGits {
    public static void main(String[] args) {
        java.util.function.Function<int[], Integer> f =
                a->{
                    List<Integer> l = new ArrayList();
                    l.add(0);
                    int x, y, z = 0;
                    s:
                    for (int i : a) {
                        for (x = 0; x < z; x++) {
                            if ((y = l.get(x)) - l.get(x + 1) < i) {
                                l.set(x, l.get(x) + 1);
                                continue s;
                            }
                        }
                        l.add(z++, 1);
                    }
                    return l.get(0);
                };
        System.out.println(f.apply(new int[]{1, 2, 2, 2, 3, 3, 3, 3, 3, 4, 4, 5, 5, 5, 5, 7, 7, 9}));
    }
}

```
> 2 votes

---
Tags: code-golf, number, simulation
---


# Question
Title: Concatenate lists of strings item-wise in Python
This is a question for golfing in .

Suppose you have two lists of strings, and you want to concatenate the corresponding entries from each list. E.g. with `a=list("abcd")` and `b=list("1234")`, calculate `["a1","b2","c3","d4"]`.

This is trivial in array-based programming languages, where operations generally apply memberwise to lists. For example, in my golfing language Pip, the code is simply `a.b`. But in Python, it's not so easy.

The Pythonic way is probably to use `zip` and a list comprehension (25 chars):

```
[x+y for x,y in zip(a,b)]

```

Another method is `map` with a lambda function (23):

```
map(lambda x,y:x+y,a,b)

```

The following is the shortest I've come up with (21):

```
map("".join,zip(a,b))

```

Is there any shorter method?

Assume that the lists are the same length and that some kind of iterable is all that's needed (so a `map` object is fine in Python 3).

# Answer
## 20 chars

```
map(str.__add__,a,b)

```

Uses the build-in method string addition method `__add__` that is invoked by `+` on strings in place of your anonymous function `lambda x,y:x+y`.
> 14 votes

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


title: Race of the Digits

text:
# Question
Title: Race of the Digits
You should write a program or function which given a starting order of distinct one-digit positive integers and the length of the track as input outputs or returns the finish order of the numbers.

The input `[5,1,2,6,7] and 14` defines the following race:

```
--------------
76215 ->
--------------

```

## Rules of the race

* The track wraps around and digits can go multiple laps.
* Order of steps is cyclic and based on the starting position. In our example `5 1 2 6 7 5 1 2 ...`.
* There can be no multiple digits in the same position.
* Every digit has a speed of `digit_value` cell per step. Overtaking a digit or a continuous block of digits costs one extra step. If the digit doesn't have the necessary speed for that it will stop before the (block of) digit(s). Examples:

```
[41   ] => [ 1 4 ]  4 overtakes 1

[2 1  ] => [ 21  ]  2 can only move 1 as it can't move 3 to overtake 1

[4 12 ] => [ 412 ]  4 can only move 1 as it can't move 5 to overtake 12

[   3 ] => [ 3   ]  3 starting a new lap

```
* Every digit has to go `digit_value` laps before it finishes. A lap is completed when the last cell of the track is left. A finished digit is removed from the track.
* *Note that a digit might reach its starting position multiple times through a step and complete multiple laps.*

## Input

* A list of distinct one-digit positive integers (`1..9`) with at least one element and a single positive integer, greater than the length of the list, the length of the track.

## Output

* A list of digits in the order they finished in any unambiguous format.

## Examples

A visual step-by-step example for the input `starting_order = [5,9,2] and length = 6`

```
295   | Start position
29   5| digit 5 moves
2  9 5| digit 9 moves, finishing lap #1
  29 5| digit 2 moves
 529  | digit 5 moves, finishing lap #1
 52  9| digit 9 moves, finishing lap #2
 5  29| digit 2 moves
   529| digit 5 moves
 9 52 | digit 9 moves, finishing laps #3 and #4
29 5  | digit 2 moves, finishing lap #1
29   5| digit 5 moves
2  9 5| digit 9 moves, finishing lap #5
  29 5| digit 2 moves
 529  | digit 5 moves, finishing lap #2
 52  9| digit 9 moves, finishing lap #6
 5  29| digit 2 moves
   529| digit 5 moves
 9 52 | digit 9 moves, finishing laps #7 and #8
 9 5  | digit 2 moves, finishing lap #2 --> remove 2 from the track
59    | digit 5 moves, finishing lap #3
5     | digit 9 moves, finishing lap #9 --> remove 9 from the track
     5| digit 5 moves
    5 | digit 5 moves, finishing lap #4
      | digit 5 moves, finishing lap #5 --> remove 5 from the track
------
Finish order: 2 9 5

```

Examples in format `Input => Output`

```
[3], 2  =>  [3]

[9, 5], 3  =>  [9, 5]

[5, 9, 2], 6  =>  [2, 9, 5]

[5, 9, 2], 10  =>  [5, 9, 2]

[5, 7, 8, 1, 2], 10  =>  [1, 5, 7, 8, 2]

[5, 1, 6, 8, 3, 2], 17  =>  [1, 6, 8, 2, 3, 5]

[1, 2, 3, 7, 8, 9], 15  =>  [1, 7, 8, 9, 2, 3]

[9, 8, 7, 3, 2, 1], 15  =>  [8, 7, 9, 1, 2, 3]

[1, 2, 3, 4, 5, 6, 7, 8, 9], 20  =>  [1, 2, 3, 4, 5, 6, 7, 8, 9]

[9, 8, 7, 6, 5, 4, 3, 2, 1], 20  =>  [8, 7, 5, 9, 6, 1, 2, 4, 3]

```

This is code-golf so the shortest entry wins.

# Answer
# Ruby 229 ~~236~~

This is a function that takes two parameters: an array representing the digits and an int representing the length of the track. It returns an array, representing the order in which the digits finish the race.

```
F=->d,l{
i=0
t=d.map{|x|[x,d.size-(i+=1)]}
r=[]
d.cycle.map{|n|
t==[]&&break
(c=t.find{|x,_|x==n})&&(s=n
w=c[1]
o=p
(a=(t-[c]).map{|_,p|p%l}
s-=1;w+=1
a&[w%l]==[]?(o=p;c[1]=w):o||s-=o=1)while s>0
c[1]>=n*l&&(t.delete c;r<<n))}
r}

```

Test it online: http://ideone.com/KyX5Yu

*Edit:* Figured out some tricks to save some more chars.

Ungolfed version:

```
F=->digits,length{
  digit_positions = digits.map.with_index{|d,i|[d,digits.size-i-1] }

  result = []

  digits.cycle.map{|n|
    break if digit_positions==[]
    crt = digit_positions.find{|x,_|x==n}
    next unless crt

    steps_left = n
    pos = crt[1]
    taking_over = false

    while steps_left > 0
      other_pos = (digit_positions-[crt]).map{|_,p|p%length}

      steps_left-=1
      pos += 1

      if other_pos.include? (pos%length)
        steps_left -= 1 unless taking_over
        taking_over = true
      else
        taking_over = false
        crt[1] = pos
      end
    end

    if crt[1] >= n*length
      digit_positions.delete(crt)
      result<<n
    end
  }
  result
}

```
> 3 votes

# Answer
# Python 2, 345 bytes

Too bad it's not shorter than @w0lf's, but whatev. (Note that the large indents are tabs, which translate to 4-space when I post.)

```
def r(o,l):
 n=len(o);s,t,a,d=dict(zip(o,range(n)[::-1])),-1,{_:0 for _ in o},[]
 while len(s):
    t+=1;g=o[t%n]
    if g in d:continue
    y,k=s[g],1;i=z=w=0
    for _ in[0]*g:
     i+=1;m=y+i;e,p=m%l,m/l
     if-~a[g]+w>=g<d>m>=l:a[g]+=1;del s[g];d+=[g];break
     if e in s.values()and e!=y:i-=k;k=0
     else:k,s[g],(w,z)=1,e,[(w,z),(z,p)][z<p]
    a[g]+=z
 print d

```
> 2 votes

# Answer
here is my magical padded code

## C (~~457~~ 430b)

```
int v(int*M,int m){
int i,n,c,d,e=32,f=48,u=0,g=10,h,k,r,l=m,j;char a,*b=&a,*B,V[m];
for (i=0;u<m*m*m;i=(++u%m),*B=*b=(u<=l)?*b:e,b=B=&a)
printf("%c%c",0*(V[i]=(u<l?u>=(r=l-sizeof(M)/4)?M[u-r]+f:e:V[i])),((((V[c=(((V[i]=u<l?e:V[i])-f)/10<u/m)?j>=0&h<i|((h=(j=strchr(V+((k=(m+(d=(i-(V[i]-f)%g+1)))%m)),e)-V)<0?(int)(strchr(V,e)-V):(int)j)>=k)*(k>i)?h:m :m])=((V[c]==e)?(*(b=V+i)+(d<0)*g):V[c])))-f)%11==0?(*(B=V+c)-f)%g+f:0);
getch();
}

```

**Note**: it needs more improvement ...

**EDIT:** code shortened ... \- sizeof(int)=4 , function=v , still remains some variable replacing to do .
> 0 votes

---
Tags: code-golf, simulation
---


title: Write the shortest game of alak

text:
# Question
Title: Write the shortest game of alak
> Alak was invented by the mathematician A. K. Dewdney, and described in his 1984 book Planiverse. The rules of Alak are simple:
>
> Alak is a two-player game played on a one-dimensional board with eleven slots on it. Each slot can hold at most one piece at a time. There's two kinds of pieces, "x" and "o". x's belong to one player, o's to the other. The initial configuration of the board is:

```
      xxxx___oooo

```

> The players take turns moving. At each turn, each player can move only one piece, once. A player cannot pass up on his turn. A player can move any one of his pieces to the next unoccupied slot to its right or left, which may involve jumping over occupied slots. A player cannot move a piece off the side of the board.
>
> If a move creates a pattern where the opponent's pieces are surrounded, on both sides, by two pieces of the mover's color (with no intervening unoccupied blank slot), then those surrounded pieces are removed from the board.
>
> The goal of the game is to remove all of your opponent's pieces, at which point the game ends. Removing all-but-one ends the game as well, since the opponent can't surround you with one piece, and so will always lose within a few moves anyway.

I found this game online and was wondering: can it be golfed?

### Rules of the golf

* Your code must follow all the rules in the game, handling captures, proper moving, etc. (only exception is you don't have to add a bot, but you must have both players controlled somehow, and one player must be human).
* Input must be move piece at tile X to tile Y, or quit. For example, you can use `1 4` to say 'move this piece at tile 1 to tile 4'. `quit` would end the program, although using `Control`-`C` would be acceptable. You also have to check if a move is invalid (by going outside the board or moving somewhere that you would have to cross over unoccupied spaces to get to or sending a message that is not a pair of tiles or `quit`).
* Outputs for players winning and invalid must be `P1 WINS`, `P2 WINS`, and `INVALID`, respectively. (All of these are 7 characters.)
* Output must show the board. That's all that's required.
* It doesn't matter if you use any aids like numbered tiles or other pieces.
* The challenge ends if:

+ One answer gets 50 votes
    + One answer remains the top-voted for 3 weeks, and no other answers were posted in that time

and the challenge has at least 3 answers (so there's some real competition).

### Rules of the game<br>

* The player on the left must start first.
* Only one piece occupies a square at a time. You move the piece left or right until it hits an unoccupied space. The board does not wrap, and you can't move through unoccupied areas. For example:
    + `xoo__o`. Here, the `x` moving right would change the board to `_oox_o`.
    + `xxooo_`. Here, the farthest-left `x` could move to yield `_xooox`, which captures the `o`s, leaving `_x___x`.
    + `x__oox`. Here, the `o`s are not captured (there is still a gap). Capture is not possible because you can't move through unoccupied spaces. The `x` on the left could only move one space, because there are no other pieces in between (leaving `_x_oox`).
* Multiple adjacent pieces can be captured at once if the group is surrounded by the opponent's pieces. E.g. from `x_oox` to `_xoox` will capture both `o`s and result in `_x__x`.
* If after a move, you first capture the *opponent's* pieces, before checking if your own piece should be remove. Take two examples:
    + `o_oxx` to `oxox_`. First, the second `o` is captured, `ox_x_`, so the first `x` remains on the board.
    + `o_oox` to `oxoo_`. This time, none of the `o`s are captured, so the `x` is captured instead.
    + If you have only one piece, the game ends, because you can't capture with just one piece.

Let the games begin! I look forward to seeing what you come up with.

# Answer
# C, ~~617~~ 592 bytes

```
#define O(x)(x-'x'?'x':'o')
q,f,t,k,i,x=4,o=4,*d;main(){char*A,Q[9],c='x',b[]="xxxx___oooo";printf(b);while(!q){scanf(" %8[^\n]%*[^\n]",Q);if(!strcmp(Q,"quit"))break;f=*Q>47&&*Q<58?atoi(Q):-1;A=f>9?Q+2:Q+1;t=*A==32&&A[1]>47&&A[1]<58?atoi(A+1):-1;i=t==f&&t<0&&f<0?1:0;for(k=f;k!=t;k+=(t-f)/abs(t-f))if(b[k]==95||b[t]-95||b[f]-c)i=1;if(i){printf("INVALID");continue;}b[t]=c;b[f]=95;for(t=0;t<2;t++){d=c-'x'?&o:&x;for(k=1;k<11;k++)if(b[k]==O(c)){for(i=k+1;b[i]==O(c)&&b[i];i++);if(b[i]==c&&b[k-1]==c)while(k<i)b[k++]=95,(*d)--;}c=t?c:O(c);}printf(b);if(o<2||x<2)printf("P%d WINS",(x>1)+1),q=1;}}

```

Unraveled:

```
#define O(x)(x-'x'?'x':'o')
q,f,t,k,i,x=4,o=4,*d;
main(){
    char*A,Q[9],c='x',b[]="xxxx___oooo";
    printf(b);
    while(!q){
        scanf(" %8[^\n]%*[^\n]",Q);
        if(!strcmp(Q,"quit"))break;
        f=*Q>47&&*Q<58?atoi(Q):-1;
        A=f>9?Q+2:Q+1;
        t=*A==32&&A[1]>47&&A[1]<58?atoi(A+1):-1;
        i=t==f&&t<0&&f<0?1:0;
        for(k=f;k!=t;k+=(t-f)/abs(t-f))
            if(b[k]==95||b[t]-95||b[f]-c)
                i=1;
        if(i){
            printf("INVALID");
            continue;
        }
        b[t]=c;
        b[f]=95;
        for(t=0;t<2;t++){
            d=c-'x'?&o:&x;
            for(k=1;k<11;k++)
                if(b[k]==O(c)){
                    for(i=k+1;b[i]==O(c)&&b[i];i++);
                    if(b[i]==c&&b[k-1]==c)
                        while(k<i)b[k++]=95,(*d)--;
                }
            c=t?c:O(c);
        }
        printf(b);
        if(o<2||x<2)printf("P%d WINS",(x>1)+1),q=1;
    }
}

```

I really wanted to get this one in ~400 bytes, but there are a lot of little rules here and the input processing ended up pretty obnoxious. I'm definitely not done with this. Here's a set of sample runs that covers just about everything:

```
xxxx___oooo0 4
_xxxx__oooo7 6
_xxxx_o_ooo4 5
_xxx_xo_ooo8 6
INVALID8 7
_xxx_xoo_oo3 4
_xx_xxoo_oo7 3
_xxo__o__oo1 4
__x_x_o__oo10 9
INVALID10 8
__x_x_o_oo_2 3
___xx_o_oo_6 5
___xxo__oo_6 6
INVALID5 5
INVALID3 6
____x_x_oo_8 7
____x_xo_o_6 8
____x__o_o_P2 WINS

xxxx___oooo0 4
_xxxx__oooo10 6
_xxxx_oooo_1 5
__xxxxoooo_9 1
_o____ooo__P2 WINS

xxxx___oooo0 4
_xxxx__oooo7 6
_xxxx_o_ooo1 5
__xxxxo_ooo10 7
__xxxxoooo_2 10
___xxx____xP1 WINS

xxxx___oooo3 4
xxx_x__ooooquits
INVALIDtestme
INVALID3*4
INVALID3 four
INVALIDthree four
INVALIDthisstringislongerthanmybuffer
INVALID10 0
INVALID4 5
INVALID7 6
xxx_x_o_oooquit

```

If I've misinterpreted something, please let me know!
> 9 votes

# Answer
# PHP - 505

```
<?php
$s="xxxx___ooo".$y=o;$x=x;$c=function($m)use(&$x){return$x.str_repeat('_',strlen($m[1])).$x;};$e='$s=preg_replace_callback("~$x($y+)$x~",$c,$s);';$_=substr_count;while(true){echo$s;if($_($s,x)<2)die("P2 WINS");if($_($s,o)<2)die("P1 WINS");$i=trim(fgets(STDIN));if($i=='quit')die;if(!preg_match('!^(\d+) (\d+)$!',$i,$m)||$s[$f=$m[1]]!=$x||$s[$t=$m[2]]!="_"||(0&($a=min($f,$t))&$b=max($f,$t))||$_($s,"_",$a,($b-$a)+1)>1)echo"INVALID\n";else{$s[$f]='_';$s[$t]=$x;eval($e);$z=$x;$x=$y;$y=$z;eval($e);}}

```

Notices must be suppressed by redirecting `STDERR` to `/dev/null`.

With sane whitespace:

```
<?php
@$s = "xxxx___ooo".($y = o);
@$x = x;
$c = function($m)usea(&$x){
    return$x.str_repeat('_',strlen($m[1])).$x;
};
$e = '$s=preg_replace_callback("~$x($y+)$x~",$c,$s);';
@$_ = substr_count;
while (true){
    echo $s;

    if (@$_($s,x) < 2) die("P2 WINS");
    if (@$_($s,o) < 2) die("P1 WINS");

    $i = trim(fgets(STDIN));
    if($i == 'quit') die;

    if( !preg_match('!^(\d+) (\d+)$!',$i,$m)
    ||   $s[$f = $m[1]] != $x
    ||  @$s[$t = $m[2]] != "_"
    ||  (0 & ($a = min($f, $t)) & $b = max($f, $t))
    ||  $_($s, "_", $a, ($b - $a) + 1) > 1
    ) echo "INVALID\n";
    else {
        $s[$f] = '_';
        $s[$t] = $x;
        eval($e);
        $z = $x;
        $x = $y;
        $y = $z;
        eval($e);
    }
}

```

With the test cases of BrainSteel:

```
xxxx___oooo0 4
_xxxx__oooo7 6
_xxxx_o_ooo4 5
_xxx_xo_ooo8 6
INVALID
_xxx_xo_ooo8 7
_xxx_xoo_oo3 4
_xx_xxoo_oo7 3
_xxo__o__oo1 4
__x_x_o__oo10 9
INVALID
__x_x_o__oo10 8
__x_x_o_oo_2 3
___xx_o_oo_6 5
___xxo__oo_6 6
INVALID
___xxo__oo_5 5
INVALID
___xxo__oo_3 6
____x_x_oo_8 7
____x_xo_o_6 8
____x__o_o_P2 WINS

xxxx___oooo0 4
_xxxx__oooo10 6
_xxxx_oooo_1 5
__xxxxoooo_9 1
_o____ooo__P2 WINS

xxxx___oooo0 4
_xxxx__oooo7 6
_xxxx_o_ooo1 5
__xxxxo_ooo10 7
__xxxxoooo_2 10
___xxx____xP1 WINS

xxxx___oooo3 4
xxx_x__ooooquits
INVALID
xxx_x__ooootestme
INVALID
xxx_x__oooo3*4
INVALID
xxx_x__oooo3 four
INVALID
xxx_x__oooothree four
INVALID
xxx_x__oooothisstringislongerthanmybuffer
INVALID
xxx_x__oooo10 0
INVALID
xxx_x__oooo4 5
INVALID
xxx_x__oooo7 6
xxx_x_o_oooquit

```
> 3 votes

# Answer
# Python 2, ~~536~~ ~~509~~ ~~448~~ 441 bytes

Call via `a()`; moves are to be entered in the form `piece,destination` (i.e., `1,4`); quit with Ctrl-C. If anyone can see more golfing potential, I'm all ears.

```
b,r,x='_',lambda p:''.join([p[i]for i in x]),range(11)
def a(m='xo'):
 t=w=0;p=dict(zip(x,'xxxx___oooo'))
 while w<1:
    print r(p);y=m[t%2]
    try:
     s,v=input();1/all([y==p[s],{v}<{r(p).rfind(b,0,s),r(p).find(b,s)},v-s]);p[s],p[v],h,c=b,y,0,{}
     for _ in y,m[-~t%2]:
        for i in p:exec{_:"h=1;p.update(c)",b:"h,c=0,{}"}.get(p[i],h*"c[i]=b")
     w=min(map(r(p).count,m))<2;t+=1
    except:print"INVALID"
 print"P%d WINS"%-~(r(p).count('o')<2)

```
> 1 votes

# Answer
# SpecBAS - 718 bytes

SpecBAS is an updated version of Sinclair/ZX BASIC that can run outside of an emulator. (Still interpreted).

Have used some of the new features to get the size down as much as I could.

Line 12 sets up a regex to search for "sandwiched" pieces using inline IF and line 18 uses the wrap around nature of INC (rather than saying `INC p: IF p=3 THEN LET p=1`)

```
1 LET b$="xxxx---oooo": LET p=1: LET c$="xo": DIM s=4,4
2 LET v=0: PRINT b$'"[";p;"] ";
3 INPUT m$: IF m$(1)="Q" THEN PRINT "QUIT": STOP
4 LET f=VAL(ITEM$(m$,1," ")): LET t=VAL(ITEM$(m$,2," ")): PRINT f;" ";t
5 IF (f<1 OR f>11) OR (t<1 OR t>11) THEN LET v=1: GO TO 10
6 IF (b$(f)<>c$(p)) OR b$(t)<>"-" THEN LET v=1: GO TO 10
7 FOR i=f TO t STEP SGN(t-f)
8 IF b$(i)="-" THEN IF i<>t THEN LET v=1
9 NEXT i
10 IF v=1 THEN PRINT "INVALID": GO TO 2
11 LET b$(t)=b$(f): LET b$(f)="-"
12 LET r$=IIF$(p=1,"xo+x","ox+o")
13 LET m=MATCH(r$,b$): IF m=0 THEN GO TO 18
14 FOR i=m+1 TO POS(c$(p),b$,m+2)
15 IF b$(i)=c$(3-p) THEN LET b$(i)="-": DEC s(3-p): END IF
16 NEXT i
17 IF s(3-p)<2 THEN PRINT b$'"P";p;" WINS": STOP
18 INC p,1 TO 2
19 GO TO 2

```

Output (can't copy from the output widow, so screen shot)
> 1 votes

# Answer
# C#, 730 bytes

```
using System;using System.Linq;class P{static void Main(string[]z){int p=1,d,e,g,x,y;var b=new[]{3,1,1,1,1,0,0,0,2,2,2,2};var o=new[]{"_","x","o"};Action<string>h=s=>{Console.Write(s,p);Environment.Exit(0);};Action i=()=>h("INVALID");Func<int,int,bool>j=(q,r)=>b.Select((v,w)=>w<=q||w>=r||v>0?0:w).Any(w=>w>0);Action<int>k=m=>{e=0;for(d=1;d<12;d++){if(b[d]==m){if(e>0&&!j(e,d))for(g=e+1;g<d;g++)b[g]=0;e=d;}}if(b.Count(w=>w>0&&w!=m)<3)h("P{0} WINS");};try{for(;;){for(g=1;g<12;g++)Console.Write(o[b[g]]);var n=Console.ReadLine();if(n=="quit")h("");var c=n.Split(' ');x=int.Parse(c[0]);y=int.Parse(c[1]);if(c.Length>2||b[x]!=p||b[y]!=0||(p>1?y:x)>=(p>1?x:y)||j(x<y?x:y,x<y?y:x))i();b[x]=0;b[y]=p;k(p);p=p>1?1:2;k(p);}}catch{i();}}}

```

I imagine that further improvements are possible. On the other hand, I interpreted the `INVALID` output as ending execution, so I may need to fix that issue to be in parity with other answers.
> 0 votes

---
Tags: code-golf, board-game
---


title: Pythy Finite Ordinals

text:
# Question
Title: Pythy Finite Ordinals
Write a program in any language that takes a single natural number *n* as input and generates a Pyth program that, in turn, produces, using nested lists, the nested set given by S(n), where:

> *S(0) = ∅*
> *S(n+1) = S(n) ∪ {S(n)}*

S(n) giving the set representation of the corresponding ordinal number.

Using the list representation required by this question, this gives (as the final output from the generated Pyth program):

```
0->[]
1->[[]]
2->[[],[[]]]
3->[[],[[]],[[],[[]]]]

```
Etc.

Again, the challenge is to write a program in another language for generating the corresponding Pyth program.

This is code golf, so shortest full program wins.

# Answer
> 1 votes
# Pyth, 11 10 bytes

```
"u+G]G"z\]

```

*"Answers must be at least 30 characters."*

---
Tags: code-golf, code-generation, set-theory, pyth
---


title: Can you cast the spell?

text:
# Question
Title: Can you cast the spell?
In Magic: the Gathering, mages (known as "planeswalkers") battle each other by casting spells. Spells cost mana. Five colors of mana exist: White, Blue, Black, Red, and Green, represented as {W}, {U}, {B}, {R}, and {G}, respectively.

A spell's cost is slightly more complex. The cost can be any combination of the following:

* One or more colors
* One or more colorless, represented as {X}, where X is a positive integer
* One or more hybrids, represented as {Y/Z}, where Y and Z are either a color (represented by one of the five letters) or colorless, represented by a positive integer

The following rules apply when attempting to cast a spell:

* A color in a cost must be satisfied by one mana of that color
* A colorless cost {X} may be satisfied by X mana of any color
* A hybrid cost {Y/Z} may be satisfied by satisfying either Y or Z
    + Note that braces are not nested
    + Y and Z are not hybrid

Write a program or function that, given a pool of mana and a cost, prints or returns true (or some truthy value) if and only if the mana in that pool can satisfy the cost, else false (or some falsy value).

A mana pool is a non-empty string of the format:

```
Color<sub>1</sub>,Color<sub>2</sub>,Color<sub>3</sub>,...,Color<sub>n-1</sub>,Color<sub>n</sub>
```

A cost is a non-empty string of the format:

```
Cost<sub>1</sub>,Cost<sub>2</sub>,Cost<sub>3</sub>,...,Cost<sub>n-1</sub>,Cost<sub>n</sub>
```

**Examples**

In the format `Pool Cost -> ExpectedOutput` (with a space between Pool and Cost):

```
{R},{R},{G},{B},{R} {4},{R} -> True
{G},{G},{G},{G},{W},{W},{W} {2/W},{2/U},{2/B},{2/R},{2/G} -> False
{G},{G},{R} {R/G},{G/B},{B/R} -> True
{R},{R},{R},{G} {1},{G},{2/G}-> True
{R} {R},{R},{R},{R},{R} -> False
{W},{R},{R} {2/W},{W/B} -> True
{U},{U} {1} -> True
{W},{R},{G} {1},{2} -> True

```

# Answer
> 7 votes
# Pyth, ~~55~~ ~~53~~ ~~52~~ 50 bytes

```
FN*Fmsm?k}kG^Gvkcd\/ceKc-rz0`Hd\,#=sN)I!.-NhK1B)E0

```

Try it online: Demonstration or Test harness

Notice that the time and memory complexity is really bad. So the second example doesn't work. I allocates about 1.6 GB of Ram before it crashes on my machine.

### Explanation

The explanation is for the 53 solution. The only difference is, that the initial parsing happens in the middle instead of the beginning.

```
Kc-rz0"{}"dFN*Fmsm?k}kG^Gvkcd\/ceKc-rz0`H\,#=sN)I!.-NhK1B)E0

```

So here's the initial parsing.

```
Kc-rz0`Hd
   rz0     convert input() to lowercase
  -   `H   remove all curly brackets (`H = "{}")
 c      d  split at the space
K          assign to K

```

So the input `"{W},{R},{R} {2/W},{W/B}"` gets converted into `['w,r,r', '2/w,w/b']`.

```
m               ceK\,    map each cost d of the costs split by "," to:
 s                         the sum of
  m         cd\/           map each value k of cost split by "/" to:
    k                        k
   ? }kG                     if k in "abcdef...xyz" else
        ^Gvk                 Cartesian product with "abc...yz" of int(k) repeats

```

So what does this do? The cost input `'2/w,w/b'` gets converted into:

```
[['aa', 'ab', 'ac', ..., 'zx', 'zy', 'zz', 'w'], 'wb']

```

Every string in `['aa', 'ab', 'ac', ..., 'zx', 'zy', 'zz', 'w']` satisfies `{2/W}` and every char in `'wb'` satisfies `{w/b}`.

Now we generate the Cartesian product of these lists (or strings) and see, if any combination can be produced with the mana-pool.

```
FN*F...              )      for N in Cartesian product of ...:
       #   )                   while 1:
        =sN                      N = sum(N)
                               this flattens N
            I!.-NhK            if not (subtract mana pool from N):
                   1             print 1 (True)
                    B            break
                      E      else:
                       0       print 0 (False)

```

# Answer
> 2 votes
# Python 2.7, 412 characters

```
import re,collections as C
r,C=re.findall,C.Counter
def g(m,h,c,v):
 try:return t(m,h,c+int(v))
 except:
  if m[v]:return t(m-C({v:1}),h,c)
def t(m,h,c):return any(g(m,h[1:],c,v)for v in h[0].split('/'))if h else sum(m.values())>=c
def f(m,c):m=C(r(r'\w',m));c=[filter(None, x)for x in zip(*r(r'(\w+/\w+)|(\d+)|(\w)',c))];m.subtract(C(c[2]));print all(x>=0 for x in m.values())*t(m,c[0],sum(int(x)for x in c[1]))

```

The function `f` is the one that does the check. It takes the mana pool and cost as string arguments, and prints `1` when the mana satisfies the cost and `0` otherwise. For example, `f('{R},{R},{G},{B},{R}', '{4},{R}')` prints `1`.

Ungolfed, it basically looks like this

```
import re
from collections import Counter
def helper(mana, hybrids, colorless, option):
  try:
    option = int(option) # See if option is an integer
    # For colorless hybrid, just add the value to the colorless amount
    # to check at the end.
    return check_hybrids(mana, hybrids, colorless + option)
  except ValueError: # Option is a mana letter
    # For colored hybrid costs, check if any of that color is
    # available, then try to pay the rest of the cost with 1 less
    # of that color.
    if mana[option] >= 0:
      return check_hybrids(mana - Counter({option: 1}), hybrids, colorless)
    else:
      return False
def check_hybrids(mana, hybrids, colorless):
  '''Check whether the given mana pool can pay the given hybrid costs and colorless costs'''
  if hybrids:
    # For each option in the first hybrid cost, check whether the
    # rest of the cost can be paid after paying that cost
    return any(helper(mana, hybrids[1:], colorless, option) for option in hybrids[0].split('/'))
  else:
    # When there are no remaining hybrid costs, if there is enough
    # remaining mana to pay the colorless costs, we have success
    return sum(m.values()) > colorless
def can_cast(mana_str, cost_str):
  mana = Counter(re.findall(r'\w', mana_str))
  # transpose to get separate lists of hybrid, colorless, and colored symbols
  cost = zip(*re.findall(r'(\w+/\w+)|(\d+)|(\w)',cost_str))
  cost = [filter(None, sublist) for sublist in cost] # Remove unfound symbols
  mana.subtract(Counter(cost[2]))
  # After subtracting the single-colored cost from the mana pool, if
  # anything in the mana pool is negative, we didn't have enough to
  # pay for that color.
  if any(x <=0 for x in mana.values()):
    return False
  return check_hybrids(mana, cost[0], sum(int(x)for x in cost[1]))

```

---
Tags: code-golf, game, combinatorics, card-games
---


title: Shortest Identifying Substring

text:
# Question
Title: Shortest Identifying Substring
This challenge is inspired by dmenu, the program I use to launch other programs on my Linux box. To start, for example, GIMP, I simply hit the keyboard shortcut I have assigned to dmenu, type "gimp" and hit enter. However, I don't have to type the whole name. On my machine, if I type "gim", that's enough. Here's how dmenu decides which program to launch when you hit enter1:

1. Find all program names that contain the input as a substring.
2. Sort this list alphabetically.
3. Take the items in the list that *begin* with the input, and (preserving their order) put them at the beginning.
4. Launch the first2 program in the list.

While this is usually quite convenient, it is sometimes annoying. For example, on my computer I have `chromedriver` and `chromium`. I never want to launch `chromedriver`, but it's earlier alphabetically than `chromium` is. If I start typing at the beginning of the word, like I naturally want to do, I have to type six characters to specify that I mean the latter.

However, we don't need to start typing at the beginning of the word! `chromium` is, alphabetically, the first program name containing the substring `iu`. I have no programs that start with `iu`. Therefore, I only need to type those two characters to unambiguously specify which program I want.

For this challenge, your program or function will receive at least two lines of input. No line will contain any whitespace characters (other than the newline, obviously) and the first line is guaranteed to be repeated somewhere in the remaining input. Your program or function will output (stdout, `return`, etc.) the shortest string that, using dmenu's rules, would find that first line in all the rest. If there are two or more that are tied for shortest, you may output whichever you like.

# Examples

```
In:
bbbb
aaaa
bbbb
cccc

Out:
b

In:
bc
bc
aaaa
bbc

Out:
bc

```

---

1: I don't actually know this to be the case, but in my experience it seems to work this way.
2: When actually using dmenu, you can hit left and right to choose different items in the list, but that's irrelevant for this challenge.

# Answer
> 3 votes
# Pyth, ~~22~~ 21 bytes

```
hfqzho>xNT0Sf}TY.z.:z

```

isaacg and me got the same 21 solution more or less at the same time. So he deleted his solution.

Try it online: Pyth Compiler/Executor

### Explanation

```
                         implicit:  z = first input line
                                   .z = all other input lines
 f                .:z   filter all substrings T of z, which satisfy:
            f   .z        filter .z for lines Y, which satisfy:
             }TY            T in Y
           S              sort these lines alphabetically
     o                    order these lines N by:
      >xNT0                 (index of T in N) > 0
                          (sorting in Pyth is stable, so this brings the lines,
                           which start with T, to the beginning
                           without messing up the alphabetically order)
  qzh                     z == first element of ...
h                       print first elment

```

---
Tags: code-golf
---


title: StickStack Numbers

text:
# Question
Title: StickStack Numbers
StickStack is a very simple stack-based programming language with only two instructions:

* `|` pushes the length of the stack onto the stack
* `-` pops the top two elements from the stack and pushes back their difference (`second topmost - topmost`)

## Language details

* The stack is empty at the start of the program.
* All instructions are executed sequentially from left to right.
* If there are less than 2 numbers on the stack the `-` instruction is illegal.
* At the end of the execution the stack should contain **exactly one number**.

Any integer can be generated by a StickStack program. For example:

```
|||--||-- generates the number 2 through the following stack states:

[]
[0]
[0, 1]
[0, 1, 2]
[0, -1]
[1]
[1, 1]
[1, 1, 2]
[1, -1]
[2]

```

To evaluate your StickStack code you can use this online (CJam) evaluator. (Thanks for @Martin for the code.)

## The task

You should write a program or function which given an integer number as input outputs or returns a string representing a StickStack program which outputs the given number.

## Scoring

* Your primary score is the **total length of the StickStack programs** for the below given test cases. Lower score is better.
* Your submission is valid only if you ran your program on all the test cases and counted your score.
* Your secondary (tiebreaker) score is the length of your generating program or function.

## Input test cases

(Each number is a different test case.)

```
-8607 -6615 -6439 -4596 -4195 -1285 -72 12 254 1331 3366 3956 5075 5518 5971 7184 7639 8630 9201 9730

```

Your program should work for any integers (which your data-type can handle) not just for the given test cases. The solutions for the test numbers should not be hardcoded into your program. If there will be doubt of hardcoding the test numbers will be changed.

# Answer
> 8 votes
# Python 2 - 5188

Quite efficient time-wise, and seems to be (probably) the optimal solution. I observed that a pattern such as

`|||||-|||-|-|-|------` (an optimal solution for 25)

can be delineated as

```
 0  |
-1  |
+2   |                 -
-3    |               -
+4     | |           -
-5      - |         -
+6         | | | | -
-7          - - - -

```

where each the total value at the end is the sum of (each level's value times the number of '|'s ). So for example above, we have `-1*1 + 2*1 - 3*1 + 4*2 - 5*1 + 6*4 = 25`. Using this I wrote this solution which produces similar output to other answers, and in a trivial amount of time.

I believe this is the optimal solution, as I test every possible optimal height (I actually test many more than necessary) and I'm pretty sure the solution always involves at most one layer with two '|'s besides the last (I can guarantee this for positive numbers but not 100% sure about negatives).

```
def solution(num):
    if num == 0:
        return '|'

    neg = num<0
    num = abs(num)
    high = int(num**0.5)

    def sub(high):
        counts = [1]*high
        total = num - (high+neg)/2

        if total%high == 0:
            counts[-1] += total/high
        else:
            counts[-1] += total/high
            if (total%high)%2==1 and not neg:
                counts[-1] += 1
                counts[-(total%high)-1] += 1
            elif (total%high)%2==0 and neg:
                counts[(total%high)-2] += 1
                counts[0] += 1
            else:
                counts[total%high-1] += 1

        string = ""
        for c in counts[::-1]:
            string = '|-'*(c-1)+'|'+string+'-'
        return '|'+string

    return min((sub(h) for h in range(2-neg,2*high+2,2)), key=lambda s: len(s))

```

Here is the code I used to test it

```
string = "-8607 -6615 -6439 -4596 -4195 -1285 -72 12 254 1331 3366 3956 5075 5518 5971 7184 7639 8630 9201 9730"
total = 0

def string_to_binary(string):
    total = 0
    for i,char in enumerate(string[::-1]):
        total += (char=='|')*(2**i)
    return total

def stickstack(bits,length):
    stack = []
    for i in range(length):
        d,bits = divmod(bits,2**(length-i-1))
        if d == 1:
            stack.append(len(stack))
        else:
            stack[-2] -= stack[-1]
            stack = stack[:-1]
    return stack

for num in string.split():
    s = solution(int(num))
    print '%s:' % num
    print s
    result = stickstack(string_to_binary(s),len(s))
    print 'Result: %s' % result
    print 'Length: %s' % len(s)
    total += len(s)
    print

print 'Total length: %s' % total

```

# Answer
> 12 votes
# Java, 5208 ~~5240~~ ~~5306~~ ~~6152~~

This is a recursive function that edges closer to the target, with base cases for when it gets within 5 (which is often only one step).

Basically, you can get `(a*b)+(a/2)` for `(a+b)*2` sticks with a simple pattern. If `a` is odd, the result will be negative, so that leads to some weird logic.

This takes a minute or so for 231-1, with a length of 185,367 as the result. It works almost instantly for all test cases, though. It scores `4*(sqrt|n|)` on average. The longest individual test case is `9730`, which results in a 397-length stick stack:

```
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||-|||||||||||||||||||||-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|--------------------------------------------------------------------------------------------------|-

```

**Update:**

Found a shorter way to add/subtract from the basic pattern. Back in the lead (for now)!

---

With a harness and test cases:

```
import static java.lang.Math.*;

public class StickStacker {

    public static void main(String[] args){
        StickStacker stacker = new StickStacker();
        int tests[] = {-8607,-6615,-6439,-4596,-4195,-1285,-72,12,254,1331,3366,3956,5075,5518,5971,7184,7639,8630,9201,9730};
        int sum = 0;
        for(int test : tests){
            String sticks = stacker.stickStack3(test);
            sum += sticks.length();
            System.out.println("In: " + test + "\t\tLength: " + sticks.length());
            System.out.println(sticks+"\n");
        }
        System.out.println("\n\nTotal: "+sum);
    }

    String stickStack3(int n){return"|"+k(n);}
    String k(int n){
        String o="";
        int q=(int)sqrt(abs(n)),a,b,d=1,e=0,c=1<<30,
        z[]={232,170,42,10,2,0,12,210,52,844,212};
        a=n>0?q:-q;
        a-=n>0?a%2<1?0:1:a%2<0?0:-1;

        for(b=0;b<abs(a)+10;b++)
            if(abs(n-(a*b+a/2-(n>0?0:1)))<abs(a)&&abs(a)+b<c){
                    c=abs(a)+b;
                    d=a;e=b;
            }

        for(a=0;a++<e;)o+="-|";
        for(a=0;a++<abs(d);)o="|"+o+"-";

        c=n-(d*e+d/2-(n>0?0:1));
        if(c>0&&c<abs(d)){
            if(c%2==0)
                o=o.substring(0,c)+"-|"+o.substring(c);
            else
                o=o.substring(0,c+1)+"-|"+o.substring(c+1)+"|-";
            c=0;
        }else if(c<0&-c<abs(d)){
            if(c%2!=0)
                o=o.substring(0,-c)+"-|"+o.substring(-c);
            else
                o=o.substring(0,-c-1)+"-|"+o.substring(-c-1)+"|-";
            c=0;
        }

        return n==0?"":n<6&&n>-6?
                Long.toBinaryString(z[n+5])
                .replaceAll("0","-")
                .replaceAll("1","|"):
                o+k(c);
    }
}

```

Will golf (more) in the unlikely event of an exact tie.

# Answer
> 4 votes
# JavaScript (ES6) 5296 ~~6572~~

**Edit** As I said in my explanation, I'm not good at solving integer equations. My guess of b value was not so good, so I have widened the range of values to try. ~~And (wow) I'm leading by now.~~

**Edit 2** Bug fix, same results. I have an idea, but cant't nail it down.

Bytes: ~460, quite golfed. It works on 32 bit integers, run time near 0.

The code is the F function (hidden in the snippet) below.
Run the snippet to test (in FireFox).

```
F=n=>{
  l=1e8;
  v=Math.sqrt(n>0?n:-n)/2|0;
  p='|';
  if (n)
    for(b=v>>2|1;b<=v+v+9;b++)
    [w=n>0?(n-b)/(2*b)|0:(-n-b)/(2*b-1)|0,w+1].map(r=>(
      t=2*r*b+b, d=n-t, n<0?t=r-t:0,
      q=n>0?'|'.repeat(2*b+1)+'-|'.repeat(r)+'-'.repeat(2*b)
      :'|'.repeat(2*b)+'-|'.repeat(r)+'-'.repeat(2*b-1),
      q+=t<n?'||--'.repeat(n-t):'|-'.repeat(t-n),
      m=q.length,m<l&&(l=m,p=q)
    ))
  return p
}

// Test --------------------------------------------

FreeTest=_=>{var n=IN.value|0,s=F(n)
  LEN.value=s.length,CK.value=Check(s),ST.innerHTML=s}
Check=t=>{var s=[],a,b;
  [...t].forEach(c=>c=='|'? s.push(s.length):(b=s.pop(),a=s.pop(),s.push(a-b)))
  return s.pop()}

ot=[];
tot=0;
[-8607,-6615,-6439,-4596,-4195,-1285,-72,
 12,254,1331,3366,3956,5075,5518,5971,7184,7639,8630,9201,9730]
.forEach(x=>{
  s=F(x), k=Check(s), l=s.length, tot+=l,
  ot.push(`<tr><td>${x}</td><td>${l}</td><td>${k}</td><td class='S'>${s}</td></tr>`)
})
ot.push(`<tr><th>Total:</th><th>${tot}</th></tr>`)
TOUT.innerHTML=ot.join("")
```

```
td.S { font-size: 8px; font-family: courier}
pre { font-size: 8px; }
input { width: 6em }
```

```
Free test: <input id="IN" value=1073741824>
<button onclick="FreeTest()">-></button>
Len:<input readonly id="LEN"> Check:<input readonly id="CK">
<pre id=ST></pre>
<table><thead>
<tr><th>Number</th><th>Len</th><th>Check</th><th>Sticks</th></tr>
</thead>
<tbody id=TOUT></tbody>
</table>
```

**Explanation**

Positive numbers, to begin with. Start with a "base" (try in CJam if you like, spaces allowed)

```
| gives 0
||| -- gives 1
||||| ---- gives 2
||||||| ------ gives 3

```

Summary: 1 stick, then b\*2 sticks, then b\*2 dashes

Then try adding one or more '-|' in the middle split. Each one add a fixed increment that is two time the starting base and can be repeated many times. So we have a formula, with b=base and r=increment repeat factor

```
v=b+r*2*b

b=1, r=0 to 3, inc=2
| || -- 1
| || -| -- 3
| || -| -| -- 5
| || -| -| -| -- 7

b=3, r=0 to 3, inc=6
| |||||| ------ 3
| |||||| -| ------ 9
| |||||| -| -| ------ 15
| |||||| -| -| -| ------ 21

```

See? The addes value increases quicky and each addition still is only 2 chars. The base increment gives 4 more chars each time.

Given v and our formula v=b+r\*2\*b, we need to find 2 ints b and r. I'not an expert in this kind of equation, but b=int sqrt(v/2) is a good starting guess.

Then we have an r and b that together give a value near v. We reach v exactly with repeated increment (||--) or decrement (|-).

Follow the same reasoning for negative numbers, alas the formula is similar but not equal.

# Answer
> 1 votes
# Python, 398710 (71 bytes)

Simplest possible solution, I think. Uses 4\*n (+/-1) characters of stickstack to represent n.

```
def s(n):return'|'*(n*2+1)+'-'*n*2 if n>=0 else'|'*(n*-2)+'-'*(n*-2-1)

```

# Answer
> 1 votes
# JavaScript, 398710

## 94 bytes/chars of code

I came up with a solution! ... and then read Sparr's answer and it was exactly the same.

Figured I would post it anyway, as js allows for slightly fewer chars.

Here's an unminified version of the code:

```
function p(a){
    s = "";
    if(a<=0){
        for(i=0; i<-2*a-1;i++)
            s="|"+s+"-";
        return "|"+s;
    }
    return "|"+p(0-a)+"-";
}

```

---
Tags: number, kolmogorov-complexity, metagolf, stack
---


title: draw ASCII function plots

text:
# Question
Title: draw ASCII function plots
Consider a function plot like this:

```
                                                       ###########
                                                    #################
                                                  ####################
                                                 #######################
                                               ###########################
                                              #############################
                                            ################################
                                           ###################################
                                          #####################################
                                        ########################################
--------------------------------------------------------------------------------
  #####################################
   ###################################
    #################################
      #############################
       ###########################
         #######################
          #####################
            #################
               ###########

```

This function plot has been created with the J code below, which is not a solution to this challenge.

```
([: |: ([: |."1 [: #&'#'"0 [: >. [: - (* 0&>)) ,. '-' ,. [: #&'#'"0 [: <. (* 0&<)) 10 * sin 12.7 %~ i. 80

```

Your task is to write a function or program that takes as input from an implementation defined source that is not the source code of your entry:

1. Two positive integers
    * *w,* the width of the plot
    * *h,* the height of the plot
2. Two real numbers
    * *b,* the beginning of the region to plot
    * *e,* the end of the region to plot
3. A function *f* mapping real numbers to real numbers. You may assume that this function does not crash, throw an exception, return a NaN or ±∞ for arguments in the range *b* to *e* inclusive. The way in which this function is described is implementation defined, but it should be possible to use any combination of the following:
    * floating point constants except NaN and ±∞
    * addition
    * subtraction
    * multiplication
    * division
    * the e*x* function
    * natural logarithm
    * sine and cosine

Your function or program shall return or print out an ASCII art plot with dimensions *w* × *h* that looks like plot above and plots *f* in the range *b* to *e* inclusive. The plot shall be scaled so that both the topmost and bottommost line contain a `#` sign or a `-`. Your output format may diverge from the output format shown above in a meaningful way if that doesn't simplify your solution. In particular, you may exchange `#` and `-` for other characters that give the impression of *black space* and *horizontal line.*

The score of your submission is the number of tokens your program source consists of. String literals count as the length of the string they describe but at least as one point, numeric literals count as ⌈log256(|*n*|)⌉ where *n* is the number described by the numeric literal.

An identifier which is either predefined by the language or a library your submission uses or whose name can be exchanged with any other unused name counts as one character. All other identifiers count as their length in characters.

If the programming language your submission is written does not have the concept of a token, it's score is the total number of characters that can't be removed from the source without changing the meaning of the program.

The scoring rules ensure that you can indent your code and use descriptive names for your variables, etc. and lowers the edge of domain-specific languages for golfing.

The winner is the submission with the least score.

# Answer
# Ruby (\>=2.1), ~28.19812

As @FUZxxl considered that *the scoring scheme is flawed anyway*, I shall make full use of it.

```
eval ([encoded data, 5654 characters]).numerator.to_s.chars.each_slice(3).map{|x|x.join.to_i.chr}.join

```

Try it online here at repl.it. Click `run`, then enter a valid argument line, such as `35 15 0 2*pi sin x`.

Note that ruby has got numeric literals in rational notation, ie. `4/5r` *is* the number `0.8`. For your convenience, that number is in decimal notation:

```
0.[encoded data, 5651 characters]

```

This is a complete program, use it like this from the command line:

```
~ $ ruby cplot.rb 35 15 0 2*pi 'sin x'

      ######
     ########
    ##########
   ############
  ##############
 ###############
#################
-----------------------------------
                  #################
                   ###############
                   ##############
                    ############
                     ##########
                      ########
                       ######

```

or

```
~ $ ruby cplot.rb 35 15 1/pi pi '1/x'
#
#
##
##
###
###
####
######
#######
#########
#############
##################
#############################
###################################
-----------------------------------

```

I count the code as follows:

```
eval
(
<numeric> [log_256(1)=0]
)
.
numerator
.
to_s
.
chars
.
each_slice
(
<numeric> [log_256(3)=0.19812]
)
.
map
{
|
x
|
.
join
.
to_i
.
chr
}
.
join

```
> 3 votes

# Answer
**c# - 70ish?**

```
using System;
using System.Collections.Generic;
using System.Linq;
class P
{
    static void Main()
    {
        Func<double,double> f = x => Math.Sin(x) -0.5;
        string r = Draw(60, 20, -10, 10, f);
        Console.Write(r);
        Console.ReadLine();
    }

    static string Draw(int w, int h, int b, int e, Func<double, double> f)
    {
        IEnumerable<double> values = Enumerable.Range(0, w).Select(i => f(i * (double)(e - b) / w));
        double scale = h / (values.Max() - values.Min());

        return String.Join(Environment.NewLine,
            Enumerable.Range(0, h)
            .Select(y => ((h - y) / scale) - Math.Abs(values.Min()))
            .Select(ypos => Math.Abs(ypos) < 1 / (scale * 2)
                ? new String('-', w)
                : new String(values.Select(v => v > ypos ^ ypos < 0
                    ? '#'
                    : ' ').ToArray())
                )
        );
    }
}

```
> 1 votes

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


title: Calculate the first n perfect numbers

text:
# Question
Title: Calculate the first n perfect numbers
Write a program that calculates the first n perfect numbers. A perfect number is one where the sum of the factors is the original number. For example, 6 is a perfect number because 1+2+3=6. No non standard libraries.The standard loopholes are forbidden.

# Answer
> 2 votes
# Pyth - 27 25 bytes

Extremely super slow brute force approach.

```
K2W<ZQ~K1IqKsf!%KTr1KK~Z1

```

Trial division to factor, then while loop till length of perfect numbers is enough.

Try it here online.

# Answer
> 2 votes
# Pyth, 25 bytes

```
J1W<lYQy=JI!tPKtyJaY*JK;Y

```

Tests whether Mersenne numbers are prime. If so, it generates the corresponding perfect number. Can find the first 8 perfect numbers in under a second.

Note: Only generates even perfect numbers. However, since it has been proven that any odd perfect number is greater than 10^1500, this algorithm is correct on inputs up to 14.

Demonstration.

# Answer
> 2 votes
# CJam, 24 bytes

```
1{{2*_(mp!}g__(*2/p}ri*;

```

Try it online.

Makes use of the Euclid–Euler theorem:

An even number `P` is perfect iff `P = 2 ** (N - 1) * (2 ** N - 1)` where `2 ** N - 1` is prime.

### Disclaimer

If there are odd perfect numbers, this code will fail to generate them. However, there are no known odd perfect numbers.

### How it works

```
1                        e# A := 1
 {                 }ri*  e# do int(input()) times:
  {       }g             e#   do:
   2*                    e#     A *= 2
     _(                  e#     M := A - 1
       mp!               e#   while(prime(P))
            __(2/        e#   P := A * (A - 1) / 2
                 p       e#   print(P)
                       ; e# discard(A)

```

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


title: How can I use cmp(a,b) with Python3?

text:
# Question
Title: How can I use cmp(a,b) with Python3?
I was told that using the `cmp` function can be very useful in code-golf. But unfortunately, Python 3 doesn't have a `cmp` function.

So what's the shortest equivalent of `cmp` that works in python 3?

# Answer
Python 3 does not have `cmp`. For golfing, you can do

*11 chars*

```
(a>b)-(a<b)

```

which loses 3 chars over `cmp(a,b)`.

Amusingly, this is also an "official" workaround. The What's New in Python 3 page says "(If you really need the `cmp()` functionality, you could use the expression `(a > b) - (a < b)` as the equivalent for `cmp(a, b)`.)"
> 36 votes

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


title: ASCII Art Generation

text:
# Question
Title: ASCII Art Generation
## Task

Write a program or function that takes an image of width `w` and height `h`, and two integers `a <= w/2` and `b <= h/2`, and outputs an ascii art representation of the image, with the dimensions `a` x `b`.

The ascii art should be generated through the following steps (or another process with the same output):

1. Resize the `w` x `h` image to `2a` x `2b`. The color of the pixel `(x, y)` in the resized image should be equal to the average of the colors of all the pixels from the original image inside the rectangle with the following corners:

```
(floor[x * w/2a], floor[y * h/2b])
(ceil[(x+1) * w/2a], ceil[(y+1) * h/2b])

```
2. The resized image should be desaturated by taking the average of the red, green, and blue components of the color, and setting each component to this average.
3. A character should be outputted for each 2x2 block of pixels, following the rules below:

* Let `e = 3 - floor[color/64]`, where color refers to the red component of the color of the top-left pixel (in the range 0..255). Let `f`, `g`, and `h` refer to this value, but for the top-right, bottom-left, and bottom-right pixels respectively.
    * Let `z` be the average of `e`, `f`, `g`, `h`.
    * Output the character corresponding to the following (white represents a pixel where `3 - floor[color/64]` is zero, and grey represents nonzero).
    * = Output a space ()
    * or = Output `"` if `e (or f) >= 2` and `'` otherwise.
    * or = Output `,` if `g (or h) >= 2` and `.` otherwise.
    * or = Output `-`
    * or = Output `;`
    * = Output `\`
    * = Output `/`
    * = Output `J`
    * = Output `L`
    * = Output `7`
    * = Output `P`
    * + `z = 1`: output `*`.
        + `z = 2`: output `C`.
        + `z = 3`: output `#`.

Other notes: All averages taken in the above steps should use integer division (i.e. rounding towards 0).

You may use a library to read images, but libraries may not be used for the resizing and desaturation steps.

## Input

Your program will take in three pieces of data:

* An image. This image may be in any format of your choice (e.g. PNG, PPM)
* The width of the ascii art (in number of characters)
* The height of the ascii art (in number of characters)

Input may be read through STDIN, passed as an command-line argument, stored as a variable, etc.

## Output

Your program will output the ascii art generated from the image and through the process described above. Each line must be the same width (the width passed as input), and no extra spaces may be added or removed. The last line may have a trailing newline, but this is not mandatory. Blank lines (lines with only spaces) must not be omitted.

## Examples

All images were taken from Wikipedia and released into public domain. Your program is expected to work for all images and valid inputs.

**Width = 52, Height = 25:**

```

            .--***--                   ----.
          -**********L.--          .--7----P-
        .J****************.       .*********\.
       ,******************L      \J**********'.
      -********************.     J***********L/
     J*********************;   ./*************.L
    ;*********************P    J**************;7;
   .**********************'   .***************;;*
   ;**********************    ;***************;J*.
   ***********************    *******P********'**;
   C*********************C    *******P;*******.**;
   C**********************    J***************;**;
   C*********************;    ****************.**;
   **********************'    ***************P;**
  J*********************P     ***************/***
 .**********************      7*************'J**;
 ;********************C"      'P***********PJ***'
 "7******************C"        '**********P.**C;
     '*C*************'         ;*********-J**CP
      '*C**********P            7**7**P/-****P
        -*CCCCC*P-               '7********P'
          '---                       '---'

```

**Width: 70, Height: 3:**

```
         ---------------------------.        .----------------
    J*****************************P     -J********************/J**;
  ----------*********P---------'          ----------------------'

```

**Width: 50, Height: 25:**

```

        .J---
      .J*P                     ---J*L--.
     J***'                L -J***********-
    J****                ;****************L
   ;*****'             .J********************
   J****7              ************************P
   **CC*    ;         .*********LJ***********P-
   **C*P    '         J**********************-
   7*C*L              **********************;
   J*C**;             **********************;
  JC**C**.     ;      ;********CCC*C**CCCC**
  "7*****L     .       7*****CCCCCC****CC**'
     -*****. -J         -**C*C*CC******CC*'
      ;**CC***;          '**CCC*****CCCC*;
       '-****-             --***CCCCC***-
                               '------'

```

**Width: 26, Height: 17:**

```
    -                  ,L
  J-**L               .C#
 J';*P-L             ,C#"
.P  P  7.           JC7P
;; * J ;;          ,C'C;
J; C C ;L          C" #
*L 7-P ;*         ;P  C
7CL***J*P         C'  #
'7#C*C#P'        ;P JC#C-
 J#CCC#L      .JC#CJCC##C;
;#-   -#,     CCC#CCCCCCCC
;*.- -.C;    ;CCCCCCCCCCCC
;****J**L    ;CCCCCCCCCCCC
;*******;    'CCCCCCCCCCCP
'*******'     CCCCCCCCCCC'
 '*P-7*'      "CCCCP '--
               '---

```

This is , so the shortest answer wins.

# Answer
# JavaScript ~~752~~,701

```
function Z(I,a,b){
    var C=document.createElement('canvas')
    var W=C.width=I.width,H=C.height=I.height,X=C.getContext('2d')
    X.drawImage(I,0,0)
    a*=2,b*=2,W/=a,H/=b
    for(var o=a*b,x=0,y=0,T="",S=[],V;--o;){
        var A=~~(x*W),B=~~(y*H)
        var d=X.getImageData(A,B,(((x+1)*W)<<0)-A,(((y+1)*H)<<0)-B).data
        for(var i=0,p=0,L=d.length;i<L;i+=4)p+=(d[i]+d[i+1]+d[i+2])/3
        p/=L/4
        S[x]=3-(p>>6)
        if(x%2&&y%2){
            var e=V[x-1],f=V[x],g=S[x-1],h=S[x],z=(e+f+g+h)>>2,B=0,c
            B|=e>0?8:0,B|=f>0?4:0,B|=g>0?2:0,B|=h>0?1:0
            c=" ..-';\\J'/;L-7P*".charAt(B)
            c=c=="'"&&(e>1||f>1)?'"':c
            c=c=="."&&(g>1||h>1)?",":c
            T+=c=="*"?z>2?"#":z>1?"C":c:c
        }
        if(++x==a)x=0,y++,V=S,T+=y%2?"\n":"",S=[]
    }
    return T
}

```

Examples:

```
var items = {
    lemons: {w:52, h:25},
    spuds: {w:50, h:25},
    tux: {w:26, h:17}
};

for(var k in items) {
    var val = items[k];
    var img = new Image();
    img.onload = function() {
        console.log(Z(this,this.w,this.h));
    }
    img.src=k+'.png';
    img.w = val.w;
    img.h = val.h;
}

```

Lemons:

```
            .--JJL--                   .---.
          -**********-.--          .--7----P-
        .J***************L.       .*********\.
       .******************L      \J**********'.
      .********************.     ;***********L/
     J*********************;   ./*************.L
    ,*********************P    -**************;7;
    **********************'   .***************;;*
   ;**********************    ;***************;;*.
   ***********************    *******PP*******'J*;
   ***********************    *******P;*******.**;
   ***************7*******    J******;J*******;**;
   **********************;    ****************.**;
   **********************'    ***************P;**'
  J*********************P     ***************/***
 .**********************      7*************'J**P
 ;*********************"      '\***********PJ***'
 "7*******************"        '**********P.***;
     '***************'         ;*********-J***P
      '************P'           7*-7**P/-****P
        -*******P-               '7********P'
          '---                       -----

```

Spuds:

```
         J---
      .J*P                     .---*L--.
     J***'                L -J***********-
    J****                ;****************L
   ;*****'             .J******************L*
   J***L7              ************************P
   **CC*    .         .*********L'***********P-
   **C*P    '         J**********************-
   7*C*L              **********************;
   J*C**.             **********************;
  JC**C**      .      7********CCC****CCCC**
  "7*****L     .       7*****CCCCCC****CC**'
     -****L. .J         -**C*C**C*******C*'
      ;**CC***;          '**CCC*****CCCC*;
       '-****-             --**CCCCCC***-
                               '------'

```

Tux:

```
                       ,L
  --**L                C#'
 J';*P-L             ,C#"
 P  7  7.           ,C7P
;; J J ;;          ,C"C;
;; C C  L          C" C
*L 7-P ;*         ;P  #
;CL***J**         C'  #
'7#C*C#C'        ,P JC#C-
 J#CCC#L      .JCCLJCC##C,
.#-   -#,     JCC#CCCCCCCC
;C.- -.*;    .CCCCCCCCCCCC
;L***J**C    ;CCCCCCCCCCCC
;*******P    'CCCCCCCCCCCP
'*******"     CCCCCCCCCCC'
 '*P-7*'      "CCCCP "--
               '---

```
> 6 votes

# Answer
# IDL 8.3, ~~588~~ ~~597~~ 588 bytes

~~I'm getting slightly different values than you are, I'm not sure why... I did integer division for everything. But it otherwise works splendidly... are these results acceptable?~~ Much better now, though still not identical for some reason.

```
pro c,m,a,b
e=2*a
f=2*b
s=size(m,/d)/[1.,e,f]
g=intarr(3,e,f)
u=floor([0:e-1]*s[1])
x=ceil([1:e]*s[1])-1
v=floor([0:f-1]*s[2])
y=ceil([1:f]*s[2])-1
n=(x-u)#(y-v)
for k=0,2 do for i=0,e-1 do for j=0,f-1 do g[k,i,f-j-1]=total(m[k,u[i]:x[i],v[j]:y[j]],/i)/n[i,j]
g=3-total(g/192,1,/i)
t=intarr(4,a,b)
for i=0,3 do t[i,*,*]=g[rebin([0:a-1]*2+i mod 2,a,b),rebin(2#[0:b-1]+i/2,a,b)]
w=total((t ne 0)*rebin(2^[0:3],4,a,b),1,/i)
for i=0,3 do w+=(w eq 2^i)*(t ge 2)[i,*,*]*(18-2^i+i/2)
w+=(w eq 15)*(total(t,1,/i)/4-1)
print,strmid(' '+"''"+'-.;/P.\;7-LJ*C#",',w[*],1),f='('+strtrim(a,2)+'A1)'
end

```

Test cases:

```
IDL> c,read_png('lemons.png'),52,25

            .-J***L-.                 .----.
          -**********L.--          .J-*LJJ**-
        .J****************.       J*********J.
       ,*******************      /J**********7.
      J********************.    ;J***********L*
     J*********************;   .\*************/L
    ;*********************P    ***************;*;
   .C*********************'   ;***************;**
   J**********************    J***************;**.
   ***********************    ****************'**;
   C*********************C    ********J*******;**;
   C**********************    *******************;
   C*********************P   ;****************7**;
  .**********************'    ***************PJ**'
  J*********************P     ***************\***
 .**********************      7*************'***P
 ;********************C"      ;************PJ**C'
 "7******************C"        ***********PJ***;
     '*C*************"         ;*********7J**CP
      '*C*********CP'           7*****P\-***CP
        -*CCCCC*P-               '7********P"
          '---                       -----

IDL> c,read_png('lemons.png'),70,3
        --------J**********L--------.       .-----------------
   .J*****************************P'    -*************************;
  ---------*************P-------         '------7**********P-----
IDL> c,read_png('potatoes.png'),50,25

         J-"-
      .J*'                     ----JL--
     -*C*                 * -J***********-
    J*C*L                ;****************L
   .*C*-*              .J********************
   J*CC;-              ********************C**CP
   *CC#*    7         .**********************P-
   *CCC;    '         J**********************-
   7CCCL              **********************;
   JCCC*.             ****C*C*****CCCC*CC***;
  ;C*CCCL      .      ;***CC*CCCCCCCCCCCCC**
  "--*CCC;             7***CCCCCCCCCCCCCCC*'
     '7CC*L.  .         -*CCCCCCCCCCCCCCCP'
       7CCCCC*'           7CC#CCCCCCC###P
        '-7P-'             '-7CC######C-
                                 '-'

IDL> c,read_png('penguin.png'),26,17
                       ,L
      ,                C#
 "  #- ;             ,##"
 ;  -  ;            ,#7;
;" - - ";          ,#"J"
;  # #  ;          #" #
;; .-. ,;         ;;  #
;#-***-#;         #   #
 7#C*C#P         ,P -C#C,
 J##-##L       JCCL-CC#CC,
,#"   "#,     JCC#CCCCCCCL
;L.- -.C;    ,CCCCCCCCCCCC
;***L***;    ;CCCCCCCCCCCC
;*******;     CCCCCCCCCCC;
 *** ***"     CCCCCC7CCCP
 '*P--*'      "CCCCP "-"
                --"

```
> 2 votes

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


title: Valid snakes on a plane

text:
# Question
Title: Valid snakes on a plane
Inspired by one of Vi Hart's videos (which are a treasure trove full of potential challenge ideas)

A snake is made up of segments of same length and the connection between each segment can be straight or make a 90° turn.
We can encode such a snake (up to a rotation, which depends on the initial direction) by writing down a *slither*, the direction of turns (Straight/Left/Right) it takes. This one, starting in the top left and pointing to the right

```
-+    +--+    SR    RSSR
 |  +-+  |     S  RSL  S
 +--+  --+     LSSL  SSR

```

Would be represented by the slither `SRSLSSLRLRSSRSRSS`

And of course a planar snake cannot intersect itself (like in `SSSSLLLSS`), that would result in a horrible pixelated Game Over.

Your task is to determine whether a slither is valid or not (results in at least one self-intersection)

**Input**
A string made from letters `SLR` with `2 < length < 10000`
**Output**
Something Truthy if it is a valid slither and something Falsey if its not.

**Test cases**

```
__Valid__
SSLSLSRSRSSRSSSLLSSSRRLRSLRLLSSS
SRRLSLLRRLLSLRRSRLLRSRRLLRRSRLLSSLLRSRRLLRRSRLLRSRRLSLLRRLLSLRR (A hilbert curve)
RLLRSRRLSLLRRLLSLRRSRLLRSRRLLRRSRLLSSLLRSRRLLRRSRLLRSRRLSLLRRLLSLRRSRLLRSRRLLRRSRLLSSLLRSRRLLRR
SRRSRSRSSRSSRSSSRSSSRSSSSRSSSSRSSSSSRSSSSSRSSSSSSRSSSSSSRSSSSSS (Spiral)
SSSSSSSSSSLSSSSSSSLSSSSSSSSLSSSSSLSSSSSSLSSSLLRRLLRRLLSLSSSRRSSSSRSSSRSSSSSSRSSSSSRSSSSSSSSRSSSSSSSRSSSSSSSSS (bigger, squigglier spiral)
LRSLLRLSRSLLSRLSLRSLSSSLRRSSLSRRLRSRLRLSLRLLRLRSSLSLRLRSRSSSSSLSRRLSLSSSRRLRLRLRLRRLLSSLSSSRRLRLRLRLRLSLSSSSSSSSSSSSSRLRLLRLRLRLRLRLRLRLSLSSSLSLSLL

__Invalid__
SRRLSLLRRLLSLRRSRLLRSRRLLRRSRLLLLRSRRLLRRSRLLRSRRLSLLRRLLSLRR
SRRLSLLRRLLSLRRSRLLRSRRLLSRSSSRSSSSSSSRSRSSSSSSSRRLLRRSRLLRSRRLSLLRRLLSLRR
SRRSRSRSSRSSRSSSRSSSRSSSSSSSSSSRSSSSRSSSSSRSSSSSRSSSSSSRSSSSSSRSSSSSS
SSSSSSSSSSLSSSSSSSLSSSSSSSSLSSSSSLSSSSSSLSSSLLRRLRLRRLLSLSSSRRSSSSRSSSRSSSSSSRSSSSSRSSSSSSSSRSSSSSSSRSSSSSSSSS
LRSLLRLSRSLLSRLSLRSLSSSLRRSSLSRRLRSRLRLSLRLLRLRSSLSLRLRSRSSSSSLSRRLSLSSSRRLRLRLRLRRLLSSLSSSRRLRLRLRLRLSLSSSSSSSSSSSSSRLRLLRLRLRLRLRLRLRLSLSSSLSLSLLSLRLSLRSLRSLRSLSLSLRSRLSLRSLRLSRSLLLRLRLRRRRSLSLSSLLSLSLSLSSLLSLSLLRLRSLLRSRLSLSSLLLLSSSSSSSSSSSSSSSSSSSSRLRLLRRLRLRLLRLRLRLRLRLSSSSLSLRLLRLSLSSLSLSLSLSLRLLRLSLLLSRSSSSSSSSSSSSSSSRLRLRLLRLRLSLSRSRSSSLSRLRLRLRSLSLSLSRLLSRLSLSLSLSLSSLSLSLLSLSRLLRLRLRLRLRLRLRLRLRLRLSLSRLRLSLLRRLSLLSLSLSLSLSLLSLSLSLRLRLRLRLRLRLRLRLRLRRLRSLSLSLSLSLSLSLSSLSSSSSLSLSSSLSLSLSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS

```

You can draw the slithers here (R and L are flipped, but it doesnt affect validity)

# Answer
# Pyth, 22 20 bytes

```
ql{m+=Z*=T^.j)hCdzlz

```

Try it yourself or run the testsuite.

Note the ASCII values of SRL, respectively 83, 76, 82. I abuse the fact that:

> *i 83 + 1* = 1
> *i 76 + 1* = *i*
> *i 82 + 1* = *-i*

From here I just keep a variable for the current position and current direction. For every character I multiply the current direction with the above complex number, then add it to the current position.

At the end I check if all the visited positions are unique.
> 20 votes

# Answer
# CJam, 30 bytes

```
q{iF%U+:U[XWe4W1e4]=T+:T}%__&=

```

Explanation to follow soon.

Try it online here or run the whole suite.
> 6 votes

# Answer
# JavaScript (ES6), 84 ~~89~~

Run snippet in Firefox to test.

Some notes:

* the snake moves inside the f array. Unvisited cells have value `undefined`. On first visit, the tilde operator change it to -1 that is a truthy. Eventually, on a second visit the value change to 0 that is falsy and the `every` loop terminates returning false.
* in JS, array elements with non canonic indices (not numeric or negative) are somehow 'hidden', but they do exist. Here I use negative indices with no problem.

```
F=s=>[...s].every(c=>f[p+=[1,1e5,-1,-1e5][d=d+{R:1,L:3,S:0}[c]&3]]=~f[p],d=p=0,f=[])

//TEST
$('#S').on('keyup mouseup change', Draw);

function Draw(){
  var s = S.value.toUpperCase();
  if (!s) {
    C.width = C.height = 0;
    return
  }
  C.width = 600;
  C.height = 400;

  var ctx = C.getContext("2d");
  var px, py, int=0;

  ctx.strokeStyle = '#008';
  ctx.lineWidth = 2;
  ctx.translate(300,200);
  ctx.beginPath();
  ctx.moveTo(0,0);

  [...s].forEach(c=>{
    (f[p+=[1,1e4,-1,-1e4][d=d+{R:1,L:3,S:0}[c]&3]]=~f[p])
    ? 1
    : (++int)
    if (int==1) ctx.stroke(), ctx.strokeStyle = '#800', ctx.beginPath(), ctx.moveTo(10*px,10*py);

    py = (p / 1e4 | 0) - 5e3;
    px = (p % 1e4) -5e3
    ctx.lineTo(10*px, 10*py);
  }, d=0,p=50005000,f=[]);
  ctx.stroke();

}

valid=["SSLSLSRSRSSRSSSLLSSSRRLRSLRLLSSS",
"SRRLSLLRRLLSLRRSRLLRSRRLLRRSRLLSSLLRSRRLLRRSRLLRSRRLSLLRRLLSLRR",
"RLLRSRRLSLLRRLLSLRRSRLLRSRRLLRRSRLLSSLLRSRRLLRRSRLLRSRRLSLLRRLLSLRRSRLLRSRRLLRRSRLLSSLLRSRRLLRR",
"SRRSRSRSSRSSRSSSRSSSRSSSSRSSSSRSSSSSRSSSSSRSSSSSSRSSSSSSRSSSSSS",
"SSSSSSSSSSLSSSSSSSLSSSSSSSSLSSSSSLSSSSSSLSSSLLRRLLRRLLSLSSSRRSSSSRSSSRSSSSSSRSSSSSRSSSSSSSSRSSSSSSSRSSSSSSSSS",
"LRSLLRLSRSLLSRLSLRSLSSSLRRSSLSRRLRSRLRLSLRLLRLRSSLSLRLRSRSSSSSLSRRLSLSSSRRLRLRLRLRRLLSSLSSSRRLRLRLRLRLSLSSSSSSSSSSSSSRLRLLRLRLRLRLRLRLRLSLSSSLSLSLL"];
invalid=["SRRLSLLRRLLSLRRSRLLRSRRLLRRSRLLLLRSRRLLRRSRLLRSRRLSLLRRLLSLRR",
"SRRLSLLRRLLSLRRSRLLRSRRLLSRSSSRSSSSSSSRSRSSSSSSSRRLLRRSRLLRSRRLSLLRRLLSLRR",
"SRRSRSRSSRSSRSSSRSSSRSSSSSSSSSSRSSSSRSSSSSRSSSSSRSSSSSSRSSSSSSRSSSSSS",
"SSSSSSSSSSLSSSSSSSLSSSSSSSSLSSSSSLSSSSSSLSSSLLRRLRLRRLLSLSSSRRSSSSRSSSRSSSSSSRSSSSSRSSSSSSSSRSSSSSSSRSSSSSSSSS",
"LRSLLRLSRSLLSRLSLRSLSSSLRRSSLSRRLRSRLRLSLRLLRLRSSLSLRLRSRSSSSSLSRRLSLSSSRRLRLRLRLRRLLSSLSSSRRLRLRLRLRLSLSSSSSSSSSSSSSRLRLLRLRLRLRLRLRLRLSLSSSLSLSLLSLRLSLRSLRSLRSLSLSLRSRLSLRSLRLSRSLLLRLRLRRRRSLSLSSLLSLSLSLSSLLSLSLLRLRSLLRSRLSLSSLLLLSSSSSSSSSSSSSSSSSSSSRLRLLRRLRLRLLRLRLRLRLRLSSSSLSLRLLRLSLSSLSLSLSLSLRLLRLSLLLSRSSSSSSSSSSSSSSSRLRLRLLRLRLSLSRSRSSSLSRLRLRLRSLSLSLSRLLSRLSLSLSLSLSSLSLSLLSLSRLLRLRLRLRLRLRLRLRLRLRLSLSRLRLSLLRRLSLLSLSLSLSLSLLSLSLSLRLRLRLRLRLRLRLRLRLRRLRSLSLSLSLSLSLSLSSLSSSSSLSLSSSLSLSLSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS"];

V.innerHTML=valid.map(s=>F(s)+' '+s).join('\n')
I.innerHTML=invalid.map(s=>F(s)+' '+s).join('\n')
```

```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Type to check and draw <input id=S>
(better full page)<br>
<canvas id=C width=1 height=1 ></canvas><br>
Valid<pre id=V></pre>
Invalid<pre id=I></pre>
```
> 6 votes

# Answer
# TI-BASIC, 49 56 53 51 bytes

```
abs(e^(i)-cumSum(i^cumSum(seq(inString("SL",sub(Ans,X,1))-1,X,1,length(Ans→X
SortA(∟X
min(ΔList(∟X

```

Similar to orlp's method, this creates a list of all points in the complex plane visited by the snake, starting at the origin. If the list has no duplicate elements, the code returns some positive value. Note that on a string of more than 999 elements, the calculator will be unable to generate a sufficiently long list, and will error.

EDIT: Saved two bytes at the cost of ugliness as no two lattice points on the complex plane can be the same distance away from e^i.
> 6 votes

# Answer
# Ruby 87 ~~89~~

```
F=->s{d=[1,w=1e4,-1,-w]
v=[w]+s.chars.map{|c|w+=d.rotate!(c<?R?-1:c>?R?0:1)[0]}
v==v&v}

```

Online test: http://ideone.com/pepeW2

Ungolfed version:

```
F = -> input {
  # Coordinates are expressed using one number,
  # that is computed using the formula `y + x*max_x`.
  # Assume max horizontal field width (max_x) to be 10000,
  # since that's the max length of the input.
  position = max_x = 1e4

  # These are possible directions to move to (coordinate deltas).
  # The current direction is always the first in the array.
  directions = [1,max_x,-1,-max_x]

  visited = [position]

  visited += input.chars.map{|c|
    # adjust current direction...
    directions.rotate! case c
    when ?L
      -1
    when ?R
      1
    when ?S
      0
    end

    # ...and move there
    position += directions[0]
  }

  # Return `true` if `visited` only contains distinct elements, `false` otherwise
  visited == visited & visited
}

```
> 1 votes

# Answer
# Golfscript 48 ~~49 50~~

```
[10.4?:z-10z~)]z*z@{'R L S'?@>(@+.`n}%n/@;\;..&=

```

Expects the string to exist on the stack and returns either `0` or `1`.

You can try it online with tests for valid and invalid snakes.

This is basically the same idea as in my Ruby answer. Just the direction array is dealt with differently, because AFAIK Golfscript does not have an arary rotate function. In this case, I build a sufficiently large directions array, by multiplying it 10000 times and then trimming from its start 0, 1, or 3 elements, depending on the current command (S, R, or L). The current "direction" to move to is always the first item in the array.

Here it is with comments:

```
# Build the direction array and set current position
[1 10000:z-1z~)]z*z

@{
  # For each character in the input:

  # set current direction by cutting 0, 1 or 3 elements
  # from the beginning of the directions array
  'SR L'?
  @>

  # move to current direction
  .0=@+.

  # format as number and addd newline
  `n
}%

# split by newlines
n/

# cleanup
@;\;

# return 1 if array contains distinct elements, 0 otherwise
..&=

```

### Edit:

Saved 1 char by modifying how the "directions" array is consumed.

### Edit:

saved 1 char by moving increments of 10 instead of 1 to make use of the `?` (power) syntax.
> 0 votes

---
Tags: code-golf, decision-problem
---


# Question
Title: Books Algorithm Dealing with Square Digit Sums
A little context:

> * Book has 411 Pages
> * Read a random number of pages on the first day which is unknown
> * Number of pages to read next day is the square of the sum of the digits of the page currently on
>
> I.e. on Page 36: read 81 pages next day
> * On day 6 The square answer directly adds to current page number to make 411
> * Finish Book
>
> How many pages did she read on the first day and how many pages did she read on the 6 days?

This is what I have so far:

```
from itertools import accumulate, count

def read_book( start ):
    for i in range( 6 ): yield start; start += sum( int( digit ) for digit in str( start ) ) ** 2

def find_start( pages ):
    for start in count( 1 ):
        for read in read_book( start ): pass
        if read == pages: return start

previous_answer, start = 0, find_start( 411 )
for i, read in enumerate( read_book( start ), 1 ):
    print( "Pages read on day", i ,"was", read-previous_answer ,"\t(Now on page", str(read) + ")\n")
    previous_answer += read-previous_answer

```

Output:

> Pages read on day 1 was 61 (Now on page 61)
>
> Pages read on day 2 was 49 (Now on page 110)
>
> Pages read on day 3 was 4 (Now on page 114)
>
> Pages read on day 4 was 36 (Now on page 150)
>
> Pages read on day 5 was 36 (Now on page 186)
>
> Pages read on day 6 was 225 (Now on page 411)

Is there a more efficient way? Who can do it in the least no. chars

# Answer
> 1 votes
# gcc - 176 chars

I don't grok Python (it is Python right?) so I don't understand how your example works. Is it actually treating the page number as a string?

I'm not sure but (at least in C) string handling uses more characters than integers. So to sum the digits of an integer between 0 and 1000 I use:

```
for(s=0,i=1;i<1001;i*=10)s+=(x%i*10)/i;

```

Where x is the input and s is the sum.

If you want the sum from some x for 7 days you could:

```
for(c=2;c<7;x+=s*s,c++)
  for(s=0,i=1;i<1001;i*=10)s+=(x%i*10)/i;

```

Where x is the input and the output.

To find the sum for 7 days which matches the number of pages in the book (p):

```
for(y=1;y<p&&x!=p;y++)
  for(x=y,c=2;c<7;x+=s*s,c++)
    for(s=0,i=1;i<1001;i*=10)s+=(x%i*10)/i;

```

Where y-1 is the calculated starting page when the sum adds up to p.

The whole program with which reads from the command line and prints to stdout:

```
main(_,a)char**a;{
  int p=atoi(a[1]),s,i,y,x,c;
  for(y=1;y<p&&x!=p;y++)
    for(x=y,c=2;c<7;x+=s*s,c++)
      for(s=0,i=1;i<1001;i*=10)s+=(x%i*10)/i;
  if(x==p)printf("%d",y-1);else puts("n/a");
}

```

It surely is possible to golf it some more. If you see something that would help please comment.

---
Tags: code-golf, tips
---


title: Looping Random Number Generator

text:
# Question
Title: Looping Random Number Generator
I'm not even sure if this is even possible, but I think it's worth a shot.

**The Challenge**

Code/conceptualize a pseudo-random number generator that has the potential to produce results evenly spaced out with similar frequencies... with a twist. The random number generator has to 'loop' back after Foo iterations to its beginning state then produce the exact same results. *Foo is a variable of all positive integers.*

For example, if the iterations amount is 4 and the random numbers generated after 4 iterations are {93,5,80,13}, then the next 4 iterations will produce {93,5,80,13}, as will the next 4 after that and so on.

**Limitations**

1. Random numbers can't be pre-defined. For example, the algorithm can't simply iterate over {1,2,3,4,...int.MaxValue}, up to the iteration amount then go back to the first value.
2. Similar to Limitation 1, random numbers can't be cached so a set of numbers can't be generated, saved, then repeatedly returned.
3. Similar to Limitation 2, the random number generator can't be 'forced' back to a certain state. Beginning seed numbers and whatnot cannot be saved.
4. The RNG can't use the number of iterations its run.

In other words, the Generator has to arrive back at its beginning state solely through consecutive calculations.

**Objective**

Shortest code wins!

# Answer
# J

I think the simplest solution to this would be the slightly bendy

```
   p =: 0
   random =: 3 : '(p =: y | >: p) } ?. y # 0'

```

That is used like this:

```
   random 5
0.329284
   random 5
0.335644
   random 5
0.985972
   random 5
0.0583756
   random 5
0.038363
   random 5
0.329284

```

This can be easily modified to provide integers, just change the 0 to whatever value you want as a maximum. Alternatively, one might write the following code:

```
   p =: 0
   random =: 4 : '(p =: y | >: p) } ?. y # x'

```

Used like this:

```
   10 random 5
8
   10 random 5
6
   10 random 5
5
   10 random 5
4
   10 random 5
6
   10 random 5
8

```

### How this works

> This uses the J primitive `?.`: the statically seeded random number generator; as opposed to `?`: the dynamically seeded random number generator. This makes sure the outcome is always the same when run with the same arguments. `p` is just a simple array pointer here, that gets incremented with every run of the function, up to a maximum of `y`: the left argument. Every time this code is executed, a list of `y` random numbers is generated (to comply with the rules). Yes, I do realize this is very much on the edge of the phrasing of the question and that it is most likely against the spirit of the question.
> 4 votes

# Answer
# Python

# Edit

Since the approach below does not satisfy the criterion, I give an even simpler method Full Cycle, which always produces a full cycle:

```
def generatePeriodic(seed, period):
    x = seed
    increment = findSmallestCoPrime(period)
    while True:
        x = (x + increment) % period
        yield x

```

This method always yields all values from `[0, period - 1]` and then repeats itself. Here `findSmallestCoPrime` is a function that returns the smallest prime `p` for which `gcd(p, period) = 1` holds.

# Previous approach

```
def generate(seed):
    a = 2 * 5 * 7 + 1
    c = 1
    m = 2 * 5 * 7 * 7
    x = seed % m
    while True:
        yield x
        x = (a * x + c) % m

```

This is a basic Linear congruential generator, with a period `m`. `m` is in this case 490.

The restrictions are:

1. `0 < m`
2. `0 < a < m`
3. `0 <= c < m`
4. `0 <= seed < m`

Linear congruential generator has full period for all seed values if and only if:

1. `c` and `m` are coprime,
2. `a - 1` is divisible by all prime factors of `m`, and
3. `a - 1` is a multiple of `4` if `m` is a multiple of `4`.

With the following, we can choose (almost) any period `m`, and modify the code accordingly. We always choose `c = 1`, to satisfy the first point. Then we factorize `m = p_1 ^ k_1 * p_2 ^ k_2 * ... * p_n ^ k_n`, and we set `a = p_1 * p_2 * ... * p_n + 1`. So we satisfy the second point. Finally, if `m % 4 == 0` we set a new value to `a = 2 * (p_1 * p_2 * ... * p_k) + 1` (here note, that `(p_1 * p_2 * ... * p_n) % 2 == 0`). With this, we satisfy the third point (and the second point is still satisfied).

The only values of `m` that can not generate a Linear congruential generator are of type: `m = 4 * p_1 * p_2 * ... p_n`, where `p_i != 2`. This is because in such cases we get `a = m + 1`, which violates the second point of restrictions.
> 2 votes

---
Tags: code-golf, random, repeated-transformation
---


title: Identify halves of Poker cards

text:
# Question
Title: Identify halves of Poker cards
A casino uses the following deck of cards. (`*` is one of the card suits `D`, `S`, `C` or `H`.)

```
 _________    _________    _________    _________    _________
|         |  |         |  |         |  |         |  |         |
|         |  |         |  |    *    |  |  *   *  |  |  *   *  |
|         |  |    *    |  |         |  |         |  |         |
|    *    |  |         |  |    *    |  |         |  |    *    |
|         |  |    *    |  |         |  |         |  |         |
|         |  |         |  |    *    |  |  *   *  |  |  *   *  |
|_________|  |_________|  |_________|  |_________|  |_________|

 _________    _________    _________    _________    _________
|         |  |         |  |         |  |         |  |         |
|  *   *  |  |  *   *  |  |  *   *  |  |  *   *  |  |  *   *  |
|         |  |         |  |  *   *  |  |  *   *  |  |  *   *  |
|  *   *  |  |  * * *  |  |         |  |    *    |  |  *   *  |
|         |  |         |  |  *   *  |  |  *   *  |  |  *   *  |
|  *   *  |  |  *   *  |  |  *   *  |  |  *   *  |  |  *   *  |
|_________|  |_________|  |_________|  |_________|  |_________|

 _________    _________    _________
|         |  |         |  |         |
|  *   *  |  |  *   *  |  |  * * *  |
|  *   *  |  |  * * *  |  |  *   *  |
|  * * *  |  |  *   *  |  |  * * *  |
|  *   *  |  |  * * *  |  |  *   *  |
|  *   *  |  |  *   *  |  |  * * *  |
|_________|  |_________|  |_________|

```

After each night, old decks are discarded, and cut in half to avoid reuse. As a result, the casino has a big room full of cut card halves.

Unfortunately the economy is bad, and the casino is in financial trouble. The most reasonable thing to save money seems to be recycling, so the casino owners decide to tape old cards back together. So they hire a team to build a machine which will do this.

You are part of the team, and your job is to help identifying the card.

Write a program or function which will take an ASCII art image of a card half in the form of a string, and will return a string of what card it is.

Input is an 11x5 string, plus line break characters (CR, LF or CRLF, you only need to support one). You may assume trailing whitespace at the end of each input line, if necessary. The input won't contain any invalid characters (any other than `_|-HSCD` and space and line break).

A card half will look like this:

```
 _________
|         |
|  H   H  |
|  H H H  |
---H---H---

```

which should be identified as the Queen of Hearts:

```
H12

```

The casino is on a limited budget, so this is code golf: the shortest program wins.

# Answer
# CJam, ~~16~~ ~~15~~ ~~13~~ 12 bytes

```
q2*A~<$e`3=(

```

Test it here.

## Explanation

The basic idea is to manipulate the string such that we can make CJam's built-in run-length encoding work for us.

Let's go through an example (the one from the question). The input string is

```
 _________
|         |
|  H   H  |
|  H H H  |
---H---H---

```

We repeat that twice:

```
 _________
|         |
|  H   H  |
|  H H H  |
---H---H---
 _________
|         |
|  H   H  |
|  H H H  |
---H---H---

```

And remove the last line:

```
 _________
|         |
|  H   H  |
|  H H H  |
---H---H---
 _________
|         |
|  H   H  |
|  H H H  |

```

Then we sort this string. It'll now have a bunch of newlines at the start, and then this (shortened by a few spaces to avoid a horizontal scrollbar):

```
                                    ---------HHHHHHHHHHHH__________________||||||||||||

```

While the suit character will vary, it'll always be an upper case letter, found in the fourth run of the sorted string (accounting for the newline). When we run-length encode this we get

```
[8 '\n] [46 ' ] [9 '-] [12 'H] [18 '_] [12 '|]]

```

So all we need to do is pick out the fourth element and reverse it.

Here is a breakdown of the actual code:

```
q              e# Read the input.
 2*            e# Repeat twice.
   A~<         e# Remove the last 11 characters, i.e. the last line.
      $        e# Flatten into a single string and sort its characters.
       e`      e# Run-length encode: turns the sorted string into 5 pairs of numbers
               e# and characters.
         3=    e# Select the one corresponding to the suit.
           (   e# Pull off the number so that its printed after the suit.

```
> 33 votes

# Answer
# Pyth (recent version), 16 bytes

```
p/KsP*2.zJ@S{K2J

```

Try it online: Pyth Compiler/Executor

### Explanation:

```
       .z           read all lines from input
     *2             duplicate all lines
    P               remove the last line
   s                combine all lines to a big string
  K                 store in K

            {K      set(K), removes duplicate chars
           S        sort, this will result in the list [' ', '-', color, '_', '|']
          @   2     take the element at index 2
         J          and store it in J

p/K      J     J    print J + (count J in K)

```

# Pyth 4.0, 13 bytes

```
jk@.rSsP*2.z2

```

Pyth had a build in run-length-encoding. But only for short time. If someone wants to try this: Clone the Pyth repo and checkout the commit 6a6dccd.

This program works pretty much the same way as Martin's CJam solution.

```
      sP*2.z        like in the 16 bytes solution
     S              sort
   .r               run-length-encoding
  @         2       element at index 2
jk                  join by "" and print

```
> 7 votes

# Answer
# CJam, 22 bytes

```
qN/)'--\s"_| "-_]s)\,)

```

Looking at more golfing options here. Here is how it works:

```
qN/                       e# Read the entire input from STDIN and split it on new lines
   )'--                   e# Take out the last line and remove - from it
       \                  e# Stack contains the half HSDC now. We swap this with rest of
                          e# the input
        s                 e# join the rest of the input array to a single string
         "_| "-           e# Remove anything other than HSCD
               _]s        e# Copy this and convert everything on stack into a single
                          e# string. Now we have the total HSCD in the complete card
                  )       e# Take out the last of HSCD. This serves as first character of
                          e# the output
                   \,)    e# Swap and take length of rest of the HSCD. Increment it by 1
                          e# as we removed 1 in the previous step.

```

Try it online here
> 6 votes

# Answer
# Python 2, ~~80~~ ~~68~~ 66 bytes

**Try it here**

Duplicate the input, find all the letters in all but the last line (the first couple chars in the last line cannot be letters), then print the first letter and how many.

```
s=(input()*2)[:-9]
for c in"CDHS":
    if c in s:print c+`s.count(c)`

```

**Input**: `' _________\n| |\n| H H |\n| H H H |\n---H---H---'`

**Output**: `H12`

Previous version that uses regex (68):

```
import re
r=re.findall('[C-S]',(input()*2)[:-9])
print r[0]+`len(r)`

```

Thanks to Sp3000 for golf help.
> 3 votes

# Answer
# J, 26 bytes

```
(],[:":@(+/)]=[,_9}.[)4{~.

```

Usage:

```
   ((],[:":@(+/)]=[,_9}.[)4{~.) input
H12

```

Reading the code from left to right:

* We get the suit from the input as the 5th distinct character in it (`4{~.`).
* Count (`+/`) the number that character occurs total in the input (`[`) and the input without the last 9 characters (`_9}.[`).
* Finally we concatenate the suit (`]`) to the resulting sum's string representation (`":`) .
> 3 votes

# Answer
# APL, 39 bytes

I'm sure this could be made much shorter, but it's a start.

```
f←{X←(∊⍵[⍳46]⍵)∩'HDCS'⋄((⊃X),0⍕⍴X)~' '}

```

This creates a named monadic function that accepts an input string and returns a string containing the card's suit and value. You can try it online!

Explanation:

```
f ← {                         ⍝ Define the function f.
     X←                       ⍝ Assign X as
       (∊⍵[⍳46]⍵)             ⍝ the right input duplicated, no center line
                 ∩ 'HDCS'     ⍝ intersect 'HDCS'.
                              ⍝ X is now a vector like 'HHHHHH'.
     ((⊃X)                    ⍝ Return the first element of X
          ,                   ⍝ concatenated with
           0⍕⍴X)              ⍝ the length of X as a string
                ~' '          ⍝ without a space.
}

```

Suggestions are welcome as always!
> 3 votes

# Answer
# Perl, 75 bytes

```
@r=();foreach ((<>)[2,2,3,3,4]){push@r,$1 while(/([CDSH])/g)}print $r[0].@r

```

Ungolfed version

```
@r=(); # Collect matches in this array
foreach ((<>)               # Read stdin as a single array of lines
                            # Note that for a subroutine use @_ for (<>)
         [2,2,3,3,4]) {     # Look at the 3rd, 4th rows twice, 5th row once
    push @r, $1             # Collect individual character matches
        while (/([CDSH])/g) # As long as one of the suits matches
}
print $r[0]                 # Each element of array is matching letter
      .@r                   # Array reference in scalar context gives length

```
> 3 votes

# Answer
# Bash + coreutils, 73

```
sed '$q;s/.*/&&/'|fold -1|sort|uniq -c|sed -nr 's/ +(\w+) ([C-S])/\2\1/p'

```
> 2 votes

# Answer
# Julia, 58 bytes

```
s->(m=matchall(r"[A-Z]",s*s[1:46]);join([m[1],length(m)]))

```

This creates an unnamed function that takes a string as input and returns the card's suit and value. To call it, give it a name, e.g. `f=s->(...)`.

Ungolfed + explanation:

```
function f(s)
    # Find all alphabetic characters in the input joined with itself
    # excluding the second center line, which begins at the 47th
    # character

    m = matchall(r"[A-Z]", s * s[1:46])

    # Take the first match and the number of matches as an array,
    # collapse the array into a string, and return it

    join([m[1], length(m)])
end

```

Suggestions are welcome as always!
> 2 votes

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