答:
Jelly, 16 bytes

```<code>L‘Hị⁸Sṭ
1Ç¡ṫ-j”/
</code>```

Try it online! or verify all test cases.

How it works

```<code>1Ç¡ṫ-j”/  Main link. Argument: n

1         Set the return value to 1.
 Ç¡       Apply the helper link n times.
   ṫ-     Tail -1; extract the last two items.
     j”/  Join, separating by a slash.

L‘Hị⁸Sṭ   Helper link. Argument: A (array)

L         Get the length of A.
 ‘        Add 1 to compute the next index.
  H       Halve.
   ị⁸     Retrieve the item(s) of A at those indices.
          If the index in non-integer, ị floors and ceils the index, then retrieves
          the items at both indices.
    S     Compute the sum of the retrieved item(s).
     ṭ    Tack; append the result to A.
</code>```

Body:
Jelly, 16 bytes

L‘Hị⁸Sṭ
1Ç¡ṫ-j”/

Try it online! or verify all test cases.

How it works

1Ç¡ṫ-j”/  Main link. Argument: n

1         Set the return value to 1.
 Ç¡       Apply the helper link n times.
   ṫ-     Tail -1; extract the last two items.
     j”/  Join, separating by a slash.

L‘Hị⁸Sṭ   Helper link. Argument: A (array)

L         Get the length of A.
 ‘        Add 1 to compute the next index.
  H       Halve.
   ị⁸     Retrieve the item(s) of A at those indices.
          If the index in non-integer, ị floors and ceils the index, then retrieves
          the items at both indices.
    S     Compute the sum of the retrieved item(s).
     ṭ    Tack; append the result to A.


问:
Calculate the Super-Logarithm
This should be a simple challenge.

Given a number \$n \ge 0\$, output the super-logarithm (or the \$\log^*\$, log-star, or iterated logarithm, which are equivalent since \$n\$ is never negative for this challenge.) of \$n\$.

$$\log^*(n) = \begin{cases}
0  & \text{ if } n \le 1 \\
1 + \log^*(\log(n)) & \text{ if } n > 1
\end{cases}$$

This is one of the two inverse functions to tetration. The other is the super-root, which is in a related question.

Examples

```<code>Input       Output
0           0
1           0
2           1
3           2
4           2
...
15          2
16          3
...
3814279     3
3814280     4
</code>```

Rules

You do not need to support decimals, though you may.

You need to support input of at least \$3814280 =  \left\lceil e^{e^e} \right\rceil\$.

You may not hard-code the values like 3814280. (Your program must theoretically support higher numbers.) I want an algorithm to be implemented.

Shortest code wins.

Related OEIS

答:
R, 36 bytes

Slightly different approach from Plannapus

```<code>->n;a=0;while(n>1){a=a+1;n=log(n)};a
</code>```

Uses a right assign to run the code -- so the desired number must precede it. i.e.

```<code>10->n;a=0;while(n>1){a=a+1;n=log(n)};a
</code>```

ContentLicense: CC BY-SA 4.0

Title: Calculate the Super-Logarithm

Body:
R, 36 bytes

Slightly different approach from Plannapus

->n;a=0;while(n>1){a=a+1;n=log(n)};a

Uses a right assign to run the code -- so the desired number must precede it. i.e.

10->n;a=0;while(n>1){a=a+1;n=log(n)};a

ContentLicense: CC BY-SA 3.0


问:
Golf me a card dealer
Frank has been working IT his whole life. Each day he responds to tickets, organizes equipment, and reports to his boss. One day, near the closing time on friday, Frank is doing his final inventory and sorting come cables in the supply closet. Suddenly, the door closes and locks from the outside! Such audacity! Frank shakes the door to try and let anyone know that he's stuck in the closet. Blast, nobody comes to his aid. With no cellphone, and no internet connection, Frank settles in with his laptop. After countless games of solitaire, frank decides to make his own card game....

Challenge:

In this case, you are frank (but not really). Your challenge is to create a dealer that can deal hands of cards, that could be dealt realistically. Your program needs to do 2 things: deal hands of cards according to an input, and take all the hands and reshuffle them. You must do this in the least ammount of bytes possible.

Rules:

Possible cards include all classic numbers and faces (a,2,3,4,5,6,7,8,9,10,j,q,k) and all suits (c,s,h,d), and two jokers (0j).

If a card is dealt, it cannot be dealt again until the program is given the reshuffle command, or it runs out of cards.

valid inputs are 'd' to deal a hand of 6 cards, and 'r' to reshuffle. NOTE that you can only deal out 9 hands before you run out of cards. Your program can either:

Automatically reshuffle,

Or give a 'X' to indicate that the dealer is out of cards.

your program needs to be able to take multiple commands over its running span.

All possible hands need to be able to be dealt in every order. Though, your program does NOT have to be random.

Examples:

We deal twice, the first hand yields the 2 of hearts, a 4 of spades, 9 of clubs, a joker, an ace of spades, and a 6 of diamonds. The second hand yields the 3 of hearts, the 10 of diamonds, the 10 of clubs, the king of clubs, the ace of diamonds, and the queen of spades. this is VALID because this is possible in real life.

d

  2h4s9c0jas6d

  d

  3h10d10ckcadqs

We deal twice, the first hand yields a mass of 5 cards (indicated by the dashes) and a 6 of hearts. The second hand deals another mass of 5 cards (again, the dashes) and another 6 of hearts. This is INVALID because it cannot happen in real life.

d

  -----6h

  d

  6h-----

we deal once, reset, and deal again. some of the cards from the first and the second deal match. this is VALID because cardstacks are renewed when shuffled.

d

  123456

  r

d

  456789

Scoring:

As with any golf, the lowest byte count wins! Good luck!

答:
PHP, 411 bytes

This will generate a random outcome for each play (each deal(d)) and then once it's used all the cards, it will reshuffle the deck, clearing the play space.

To run, input comma separated commands: php card_dealer_golf.php d,d,d,d,r

```<code>$c=explode(",","a,2,3,4,5,6,7,8,9,10,j,q,k");$a=["h"=>$c,"d"=>$c,"s"=>$c,"c"=>$c,"0"=>["J","J"]];$cd=0;foreach(explode(",",$argv[1]) as $cmd){if($cd>=54){$cmd="r";}if($cmd=='d'){$cd+=6;for($i=0;$i<6;$i++){$s=array_keys($a)[rand(0,4)];$l=rand(1,count($a[$s])-1);if(isset($a[$s][$l])){echo$a[$s][$l].$s;unset($a[$s][$l]);}else{$i--;}}echo PHP_EOL;}else{$cd=0;$a=["h"=>$c,"d"=>$c,"s"=>$c,"c"=>$c,"0"=>["J","J"]];}}
</code>```

Output:

```<code>$ php card_dealer_golf.php d,d,d,d,r
10djs5cjh2h3h
3cJ06d2d7d3s
9s6s7h4d6c4s
10c4c3d7c8h6h
</code>```

Ungolfed version

```<code>$cards = explode(",","a,2,3,4,5,6,7,8,9,10,j,q,k");
$a = [
        "h" => $cards,
        "d" => $cards,
        "s" => $cards,
        "c" => $cards,
        "0" => ["J","J"]
    ];
$cd=0;
foreach(explode(",",$argv[1]) as $cmd) {
        if($cd>=54) {$cmd = "r";}
        if($cmd=='d'){
                $cd+=6; //+6 cards dealt
                for($i=0;$i<6;$i++){
                    $suit = array_keys($a)[rand(0,4)]; //get random suit
                    $l=rand(1,count($a[$suit])-1); //get random card from suit
                    if(isset($a[$suit][$l])){ //if the card is still in the deck
                        echo $a[$suit][$l].$suit; //output it
                        unset($a[$suit][$l]); //remove from deck
                    }else{
                        $i--; //card not in deck, decrease the cards dealt in this round to be regenered
                    }
                }
                echo PHP_EOL;
        }else{
                //reshuffle logic. reset deck and amount of cards dealth
                $cd=0;
                $a = [
                        "h" => $cards,
                        "d" => $cards,
                        "s" => $cards,
                        "c" => $cards,
                        "0" => ["J","J"]
                ];
        }
}
</code>```

Title: Golf me a card dealer

Body:
PHP, 411 bytes

This will generate a random outcome for each play (each deal(d)) and then once it's used all the cards, it will reshuffle the deck, clearing the play space.

To run, input comma separated commands: php card_dealer_golf.php d,d,d,d,r

$c=explode(",","a,2,3,4,5,6,7,8,9,10,j,q,k");$a=["h"=>$c,"d"=>$c,"s"=>$c,"c"=>$c,"0"=>["J","J"]];$cd=0;foreach(explode(",",$argv[1]) as $cmd){if($cd>=54){$cmd="r";}if($cmd=='d'){$cd+=6;for($i=0;$i<6;$i++){$s=array_keys($a)[rand(0,4)];$l=rand(1,count($a[$s])-1);if(isset($a[$s][$l])){echo$a[$s][$l].$s;unset($a[$s][$l]);}else{$i--;}}echo PHP_EOL;}else{$cd=0;$a=["h"=>$c,"d"=>$c,"s"=>$c,"c"=>$c,"0"=>["J","J"]];}}

Output:

$ php card_dealer_golf.php d,d,d,d,r
10djs5cjh2h3h
3cJ06d2d7d3s
9s6s7h4d6c4s
10c4c3d7c8h6h

Ungolfed version

$cards = explode(",","a,2,3,4,5,6,7,8,9,10,j,q,k");
$a = [
        "h" => $cards,
        "d" => $cards,
        "s" => $cards,
        "c" => $cards,
        "0" => ["J","J"]
    ];
$cd=0;
foreach(explode(",",$argv[1]) as $cmd) {
        if($cd>=54) {$cmd = "r";}
        if($cmd=='d'){
                $cd+=6; //+6 cards dealt
                for($i=0;$i<6;$i++){
                    $suit = array_keys($a)[rand(0,4)]; //get random suit
                    $l=rand(1,count($a[$suit])-1); //get random card from suit
                    if(isset($a[$suit][$l])){ //if the card is still in the deck
                        echo $a[$suit][$l].$suit; //output it
                        unset($a[$suit][$l]); //remove from deck
                    }else{
                        $i--; //card not in deck, decrease the cards dealt in this round to be regenered
                    }
                }
                echo PHP_EOL;
        }else{
                //reshuffle logic. reset deck and amount of cards dealth
                $cd=0;
                $a = [
                        "h" => $cards,
                        "d" => $cards,
                        "s" => $cards,
                        "c" => $cards,
                        "0" => ["J","J"]
                ];
        }
}


Title: Calculate the Super-Logarithm

Body:
This should be a simple challenge.

Given a number \$n \ge 0\$, output the super-logarithm (or the \$\log^*\$, log-star, or iterated logarithm, which are equivalent since \$n\$ is never negative for this challenge.) of \$n\$.

$$\log^*(n) = \begin{cases}
0  & \text{ if } n \le 1 \\
1 + \log^*(\log(n)) & \text{ if } n > 1
\end{cases}$$

This is one of the two inverse functions to tetration. The other is the super-root, which is in a related question.

Examples

```<code>Input       Output
0           0
1           0
2           1
3           2
4           2
...
15          2
16          3
...
3814279     3
3814280     4
</code>```

Rules

You do not need to support decimals, though you may.

You need to support input of at least \$3814280 =  \left\lceil e^{e^e} \right\rceil\$.

You may not hard-code the values like 3814280. (Your program must theoretically support higher numbers.) I want an algorithm to be implemented.

Shortest code wins.

Related OEIS

Body:
Ruby, 29 bytes

l=->n{n<=1?0:1+l[Math.log n]}


问:
Smallest positive integer not yet appeared so that the sum of the first n elements is divisible by n

Task

Given positive integer n, output a(n) where a is the sequence defined below:

a(n) is the smallest positive integer not yet appeared so that the sum of the first n elements in the sequence is divisible by n.

Example

a(1) is 1 because it is the smallest positive integer that has not appeared in the sequence, and 1 is divisible by 1.

a(10) is 16 because look at the first nine elements: 1,3,2,6,8,4,11,5,14. They sum up to 54, so for the first ten elements to sum up to a multiple of 10, a(10) would need to have a remainder of 6 when divided by 10. 6 has already appeared, so a(10) is 16 instead.

Testcases

```<code>n     a(n)
1     1
2     3
3     2
4     6
5     8
6     4
7     11
8     5
9     14
10    16
11    7
12    19
13    21
14    9
15    24
16    10
17    27
18    29
19    12
20    32
100   62
1000  1618
10000 16180
</code>```

a(n) from n=1 to n=10000

References

OEIS A019444

答:
R, 99 bytes

```<code>f=function(n){a=n
b=c()
while(0<(a=a-1))b=c(f(a),b)
while(a<-a+1)if(!(sum(b)+a)%%n&!a%in%b)break
a}
</code>```

Simple algorithm. Runs from n-1 to 1 and gathers all of those numbers in the sequence. Then it moves up from 1 -- checking membership and whether it divides appropriately.

Body:
R, 99 bytes

f=function(n){a=n
b=c()
while(0<(a=a-1))b=c(f(a),b)
while(a<-a+1)if(!(sum(b)+a)%%n&!a%in%b)break
a}

Simple algorithm. Runs from n-1 to 1 and gathers all of those numbers in the sequence. Then it moves up from 1 -- checking membership and whether it divides appropriately.


问:
Output the nth rational number according to the Stern-Brocot sequence
The Stern-Brocot sequence is a Fibonnaci-like sequence which can be constructed as follows:

Initialise the sequence with s(1) = s(2) = 1

Set counter n = 1

Append s(n) + s(n+1) to the sequence

Append s(n+1) to the sequence

Increment n, return to step 3

This is equivalent to:

Amongst other properties, the Stern-Brocot sequence can be used to generate every possible positive rational number. Every rational number will be generated exactly once, and it will always appear in its simplest terms; for example, 1/3 is the 4th rational number in the sequence, but the equivalent numbers 2/6, 3/9 etc won't appear at all.

We can define the nth rational number as r(n) = s(n) / s(n+1), where s(n) is the nth Stern-Brocot number, as described above.

Your challenge is to write a program or function which will output the nth rational number generated using the Stern-Brocot sequence.

The algorithms described above are 1-indexed; if your entry is 0-indexed, please state in your answer

The algorithms described are for illustrative purposes only, the output can be derived in any way you like (other than hard-coding)

Input can be via STDIN, function parameters, or any other reasonable input mechanism

Ouptut can be to STDOUT, console, function return value, or any other reasonable output stream

Output must be as a string in the form a/b, where a and b are the relevant entries in the Stern-Brocot sequence. Evaluating the fraction before output is not permissable. For example, for input 12, output should be 2/5, not 0.4.

Standard loopholes are disallowed

This is code-golf, so shortest answer in bytes will win.

Test cases

The test cases here are 1-indexed.

```<code>n    r(n)
--  ------
1    1/1
2    1/2
3    2/1
4    1/3
5    3/2
6    2/3
7    3/1
8    1/4
9    4/3
10   3/5
11   5/2
12   2/5
13   5/3
14   3/4
15   4/1
16   1/5
17   5/4
18   4/7
19   7/3
20   3/8
50   7/12
100  7/19
1000 11/39
</code>```

OEIS entry: A002487

Excellent Numberphile video discussing the sequence: Infinite Fractions

答:
CJam (20 bytes)

```<code>1_{_@_2$%2*-+}ri*'/\
</code>```

Online demo. Note that this is 0-indexed. To make it 1-indexed, replace the initial 1_ by T1.

Dissection

This uses the characterisation due to Moshe Newman that

the fraction a(n+1)/a(n+2) can be generated from the previous fraction a(n)/a(n+1) = x by 1/(2*floor(x) + 1 - x)

If x = s/t then we get

```<code>  1 / (2 * floor(s/t) + 1 - s/t)
= t / (2 * t * floor(s/t) + t - s)
= t / (2 * (s - s%t) + t - s)
= t / (s + t - 2 * (s % t))
</code>```

Now, if we assume that s and t are coprime then

```<code>  gcd(t, s + t - 2 * (s % t))
= gcd(t, s - 2 * (s % t))
= gcd(t, -(s % t))
= 1
</code>```

So a(n+2) = a(n) + a(n+1) - 2 * (a(n) % a(n+1)) works perfectly.

```<code>1_           e# s=1, t=1
{            e# Loop...
  _@_2$%2*-+ e#   s, t = t, s + t - 2 * (s % t)
}
ri*          e# ...n times
'/\          e# Separate s and t with a /
</code>```

Body:
CJam (20 bytes)

1_{_@_2$%2*-+}ri*'/\

Online demo. Note that this is 0-indexed. To make it 1-indexed, replace the initial 1_ by T1.

Dissection

This uses the characterisation due to Moshe Newman that

the fraction a(n+1)/a(n+2) can be generated from the previous fraction a(n)/a(n+1) = x by 1/(2*floor(x) + 1 - x)

If x = s/t then we get

  1 / (2 * floor(s/t) + 1 - s/t)
= t / (2 * t * floor(s/t) + t - s)
= t / (2 * (s - s%t) + t - s)
= t / (s + t - 2 * (s % t))

Now, if we assume that s and t are coprime then

  gcd(t, s + t - 2 * (s % t))
= gcd(t, s - 2 * (s % t))
= gcd(t, -(s % t))
= 1

So a(n+2) = a(n) + a(n+1) - 2 * (a(n) % a(n+1)) works perfectly.

1_           e# s=1, t=1
{            e# Loop...
  _@_2$%2*-+ e#   s, t = t, s + t - 2 * (s % t)
}
ri*          e# ...n times
'/\          e# Separate s and t with a /


问:
Show off your tree analysing toolbox
As a programmer or computer scientist one might encounter quite a lot of trees - of course not the woody growing-in-the-wrong-direction kind, but the nice, pure mathematical kind:

```<code>  *<- root (also a node)
 /|\<- edge
* * *<- inner node
|  / \
* *   *<- leaf (also a node)
  |
  *
</code>```

Naturally over time we all have put together our own small handy toolbox to analyse such trees as we encounter them, right?
Now is the time to show it off!

Task

The toolbox must include the following functions:

size: The number of nodes in the tree.

depth: The number of edges on the longest path from the root to any leaf.

breadth: The number of leaves.

degree: The maximum number of child nodes for any node.

You have to submit a program or function for each of the tools, however they might share subroutines (e.g. parsing) which then have to be submitted only once. Note that those subroutines need to be full programs or functions too.

Input Format

The trees can be given in any reasonable format capturing the structure, e.g. the tree

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

could be represented through parentheses (()()), lists of lists [[],[]], or data structures with a constructor T[T[],T[]].
However not through linearisation [2,0,0] or a format like (size, depth, breath, degree, whatever-else-is-needed-to-make-this-format-unique-for-every-tree).
Generally speaking, your tree format should not contain numbers.

Output Format

A natural number for each of the properties described above.

Scoring

Lowest code in bytes for the 4 functions in every language wins, thus I will not accept an answer.

Feel free to provide additional tree tools like fold, isBinaryTree, preLinearise, postLinearize, or whatever you like. Of course those don't have to be included in the byte count.

Examples

First the tree is given in the sample formats from above, then the results of the functions as (size, depth, breadth, degree).

```<code>()
[]
T[]
(1,0,1,0)

(()())
[[],[]]
T[T[],T[]]
(3,1,2,2)

((())()((())()))
[[[]],[],[[[]],[]]]
T[T[T[]],T[],T[T[T[]],T[]]]
(8,3,4,3)

((()())((())()((())()))(()())(()))
[[[],[]],[[[]],[],[[[]],[]]],[[],[]],[[]]]
T[T[T[],T[]],T[T[T[]],T[],T[T[T[]],T[]]],T[T[],T[]],T[T[]]]
(17,4,9,4)

((((((((()))))))))
[[[[[[[[[]]]]]]]]]
T[T[T[T[T[T[T[T[T[]]]]]]]]]
(9,8,1,1)

(((((((()()))((()()))))((((()()))((()()))))))((((((()()))((()()))))((((()()))((()())))))))
[[[[[[[[],[]]],[[[],[]]]]],[[[[[],[]]],[[[],[]]]]]]],[[[[[[[],[]]],[[[],[]]]]],[[[[[],[]]],[[[],[]]]]]]]]
T[T[T[T[T[T[T[T[],T[]]],T[T[T[],T[]]]]],T[T[T[T[T[],T[]]],T[T[T[],T[]]]]]]],T[T[T[T[T[T[T[],T[]]],T[T[T[],T[]]]]],T[T[T[T[T[],T[]]],T[T[T[],T[]]]]]]]]
(45,7,16,2)
</code>```

答:
tinylisp, 248 bytes

```<code>(d X(q((m n)(i(l m n)n m))))(d F(q(()g(c(q(T))(c(c(q i)(c(q T)g))())))))(d S(F(s(S(h T))(s 0(S(t T))))1))(d H(F(X(s 1(s 0(H(h T))))(H(t T)))0))(d B(F(s(B(h T))(s 0(i(t T)(B(t T))0)))1))(d C(F(s 1(s 0(C(t T))))0))(d D(F(X(C T)(X(D(h T))(D(t T))))0))
</code>```

Fun fact: 49% of that program is parentheses.

tinylisp is a minimalistic version of Lisp, containing only 10 built-in functions and macros. Because Lisp is awesome, it is nonetheless very powerful, and well-suited to manipulating abstract data structures like trees.

The program defines functions S, H (for "height"), B, and D, as well as a max function X and a number-of-children function C. It uses the (()()) form of trees, with the added requirement that each tree must be quoted to be treated as data rather than code: (q (()())). Example run:

```<code>tl> (d tree (q ((())()((())()))))
tree
tl> (S tree)
8
tl> (H tree)
3
tl> (B tree)
4
tl> (D tree)
3
</code>```

Here's an ungolfed version, with a couple extra utility functions defined to make things clearer. For reference, the built-ins used are define, quote, if, less than, cons, subtract, head, and tail. (Yes, addition has to be implemented from subtraction.)

```<code>(d lambda (q (() args args)))

(d add
 (lambda (a b)
  (s a (s 0 b))))

(d max
 (lambda (a b)
  (i (l a b) b a)))

(d size
 (lambda (tree)
  (i tree
   (add (size (h tree)) (size (t tree)))
   1)))

(d depth
 (lambda (tree)
  (i tree
   (max (add 1 (depth (h tree))) (depth (t tree)))
   0)))

(d breadth
 (lambda (tree)
  (i tree
   (add
    (breadth (h tree))
    (i (t tree)
     (breadth (t tree))
     0))
   1)))

(d children
 (lambda (tree)
  (i tree
   (add 1 (children (t tree)))
   0)))

(d degree
 (lambda (tree)
  (i tree
   (max (children tree) (max (degree (h tree)) (degree (t tree))))
   0))))
</code>```

This is pretty horrible Lisp style, since there's no tail recursion, but hey--it's code golf. ;^)

Title: Show off your tree analysing toolbox

Body:
tinylisp, 248 bytes

(d X(q((m n)(i(l m n)n m))))(d F(q(()g(c(q(T))(c(c(q i)(c(q T)g))())))))(d S(F(s(S(h T))(s 0(S(t T))))1))(d H(F(X(s 1(s 0(H(h T))))(H(t T)))0))(d B(F(s(B(h T))(s 0(i(t T)(B(t T))0)))1))(d C(F(s 1(s 0(C(t T))))0))(d D(F(X(C T)(X(D(h T))(D(t T))))0))

Fun fact: 49% of that program is parentheses.

tinylisp is a minimalistic version of Lisp, containing only 10 built-in functions and macros. Because Lisp is awesome, it is nonetheless very powerful, and well-suited to manipulating abstract data structures like trees.

The program defines functions S, H (for "height"), B, and D, as well as a max function X and a number-of-children function C. It uses the (()()) form of trees, with the added requirement that each tree must be quoted to be treated as data rather than code: (q (()())). Example run:

tl> (d tree (q ((())()((())()))))
tree
tl> (S tree)
8
tl> (H tree)
3
tl> (B tree)
4
tl> (D tree)
3

Here's an ungolfed version, with a couple extra utility functions defined to make things clearer. For reference, the built-ins used are define, quote, if, less than, cons, subtract, head, and tail. (Yes, addition has to be implemented from subtraction.)

(d lambda (q (() args args)))

(d add
 (lambda (a b)
  (s a (s 0 b))))

(d max
 (lambda (a b)
  (i (l a b) b a)))

(d size
 (lambda (tree)
  (i tree
   (add (size (h tree)) (size (t tree)))
   1)))

(d depth
 (lambda (tree)
  (i tree
   (max (add 1 (depth (h tree))) (depth (t tree)))
   0)))

(d breadth
 (lambda (tree)
  (i tree
   (add
    (breadth (h tree))
    (i (t tree)
     (breadth (t tree))
     0))
   1)))

(d children
 (lambda (tree)
  (i tree
   (add 1 (children (t tree)))
   0)))

(d degree
 (lambda (tree)
  (i tree
   (max (children tree) (max (degree (h tree)) (degree (t tree))))
   0))))

This is pretty horrible Lisp style, since there's no tail recursion, but hey--it's code golf. ;^)


问:
Complexity-free Kolmogorov(-Smirnov)
In statistics, sometimes it's useful to know whether two data samples come from the same underlying distribution. One way to do this is to use the two-sample Kolmogorov-Smirnov test.

Your task will be to write a program that reads in two unsorted nonnegative integer arrays and calculates the main statistic used in the test.

Given an array A and a real number x, define the distribution function F by

```<code>F(A,x) = (#number of elements in A less than or equal to x)/(#number of elements in A)
</code>```

Given two arrays A1 and A2, define

```<code>D(x) = |F(A1, x) - F(A2, x)|
</code>```

The two-sample Kolmogorov-Smirnov statistic is the maximum value of D over all real x.

Example

```<code>A1 = [1, 2, 1, 4, 3, 6]
A2 = [3, 4, 5, 4]
</code>```

Then:

```<code>D(1) = |2/6 - 0| = 1/3
D(2) = |3/6 - 0| = 1/2
D(3) = |4/6 - 1/4| = 5/12
D(4) = |5/6 - 3/4| = 1/12
D(5) = |5/6 - 4/4| = 1/6
D(6) = |6/6 - 4/4| = 0
</code>```

The KS-statistic for the two arrays is 1/2, the maximum value of D.

Test cases

```<code>[0] [0] -> 0.0
[0] [1] -> 1.0
[1, 2, 3, 4, 5] [2, 3, 4, 5, 6] -> 0.2
[3, 3, 3, 3, 3] [5, 4, 3, 2, 1] -> 0.4
[1, 2, 1, 4, 3, 6] [3, 4, 5, 4] -> 0.5
[8, 9, 9, 5, 5, 0, 3] [4, 9, 0, 5, 5, 0, 4, 6, 9, 10, 4, 0, 9] -> 0.175824
[2, 10, 10, 10, 1, 6, 7, 2, 10, 4, 7] [7, 7, 9, 9, 6, 6, 5, 2, 7, 2, 8] -> 0.363636
</code>```

Rules

You may write a function or a full program. Input may be via STDIN or function argument, and output may be via STDOUT or return value.

You may assume any unambiguous list or string format for the input, as long as it is consistent for both arrays

On the off-chance that your language has a builtin for this, you may not use it.

Answers need to be correct to at least 3 significant figures

This is code-golf, so the program in the fewest bytes wins

答:
R, 107 bytes

Different Approach

```<code>f=function(a,b){e=0
d=sort(unique(c(a,b)))
for(i in d-min(diff(d))*0.8)e=max(abs(mean(a<i)-mean(b<i)),e)
e}
</code>```

Ungolfed

```<code>f=function(a,b){
    e=0
    d=sort(unique(c(a,b)))
    d=d-min(diff(d))*0.8
    for(i in d) {
        f=mean(a<i)-mean(b<i)
        e=max(e,abs(f))
    }
    e
}
</code>```

Title: Complexity-free Kolmogorov(-Smirnov)

Body:
R, 107 bytes

Different Approach

f=function(a,b){e=0
d=sort(unique(c(a,b)))
for(i in d-min(diff(d))*0.8)e=max(abs(mean(a<i)-mean(b<i)),e)
e}

Ungolfed

f=function(a,b){
    e=0
    d=sort(unique(c(a,b)))
    d=d-min(diff(d))*0.8
    for(i in d) {
        f=mean(a<i)-mean(b<i)
        e=max(e,abs(f))
    }
    e
}


问:
Narayana-Zidek-Capell numbers
Generate the nth Narayana-Zidek-Capell number given an input n. Fewest bytes win.

f(1)=1, f(n) is the sum of the previous floor(n/2) Narayana-Zidek-Capell terms.

Test Cases:

```<code>f(1)=1

f(9)=42

f(14)=1308

f(15)=2605

f(23)=664299
</code>```

答:
R, 63 bytes

```<code>f=function(n,a=0)if(n<2)1 else{for(i in n-1:(n%/%2))a=a+f(i);a}
</code>```

a=0 is added as a default because it saves me two curly brackets. Function recursively calls itself as needed.

Title: Narayana-Zidek-Capell numbers

Body:
R, 63 bytes

f=function(n,a=0)if(n<2)1 else{for(i in n-1:(n%/%2))a=a+f(i);a}

a=0 is added as a default because it saves me two curly brackets. Function recursively calls itself as needed.


答:
R, 93 bytes

```<code>f=function(n)ifelse(n<3,1,ifelse(n%%2,f(n/2-1/2)+f(n/2+1/2),f(n/2)))
g=function(n)f(n)/f(n+1)
</code>```

Literally the simplest implementation. Working on golfing it a bit.

Title: Output the nth rational number according to the Stern-Brocot sequence

Body:
The Stern-Brocot sequence is a Fibonnaci-like sequence which can be constructed as follows:

Initialise the sequence with s(1) = s(2) = 1

Set counter n = 1

Append s(n) + s(n+1) to the sequence

Append s(n+1) to the sequence

Increment n, return to step 3

This is equivalent to:

Amongst other properties, the Stern-Brocot sequence can be used to generate every possible positive rational number. Every rational number will be generated exactly once, and it will always appear in its simplest terms; for example, 1/3 is the 4th rational number in the sequence, but the equivalent numbers 2/6, 3/9 etc won't appear at all.

We can define the nth rational number as r(n) = s(n) / s(n+1), where s(n) is the nth Stern-Brocot number, as described above.

Your challenge is to write a program or function which will output the nth rational number generated using the Stern-Brocot sequence.

The algorithms described above are 1-indexed; if your entry is 0-indexed, please state in your answer

The algorithms described are for illustrative purposes only, the output can be derived in any way you like (other than hard-coding)

Input can be via STDIN, function parameters, or any other reasonable input mechanism

Ouptut can be to STDOUT, console, function return value, or any other reasonable output stream

Output must be as a string in the form a/b, where a and b are the relevant entries in the Stern-Brocot sequence. Evaluating the fraction before output is not permissable. For example, for input 12, output should be 2/5, not 0.4.

Standard loopholes are disallowed

This is code-golf, so shortest answer in bytes will win.

Test cases

The test cases here are 1-indexed.

```<code>n    r(n)
--  ------
1    1/1
2    1/2
3    2/1
4    1/3
5    3/2
6    2/3
7    3/1
8    1/4
9    4/3
10   3/5
11   5/2
12   2/5
13   5/3
14   3/4
15   4/1
16   1/5
17   5/4
18   4/7
19   7/3
20   3/8
50   7/12
100  7/19
1000 11/39
</code>```

OEIS entry: A002487

Excellent Numberphile video discussing the sequence: Infinite Fractions

Body:
R, 93 bytes

f=function(n)ifelse(n<3,1,ifelse(n%%2,f(n/2-1/2)+f(n/2+1/2),f(n/2)))
g=function(n)f(n)/f(n+1)

Literally the simplest implementation. Working on golfing it a bit.


问:
Generate random PESEL number
From Wikipedia:

PESEL is the
  national identification number used in Poland since 1979. It always
  has 11 digits, identifies just one person and cannot be changed to
  another one.

It has the form of YYMMDDZZZXQ, where YYMMDD is the date of birth
  (with century encoded in month field), ZZZ is the personal
  identification number, X denotes sex (even number for females, odd
  number for males) and Q is a control digit, which is used to verify
  whether a given PESEL is correct or not.

Having a PESEL in the form of ABCDEF GHIJK, one can check the
  vailidity of the number by computing the following expression:

A*1 + B*3 + C*7 + D*9 + E*1 + F*3 + G*7 + H*9 + I*1 + J*3

Then the last digit of the result should be subtracted from 10. If the
  result of the last operation is not equal to the last digit of a given
  PESEL, the PESEL is incorrect. This system works reliably well for
  catching one-digit mistakes and digit swaps.

Provide a short program to generate random, valid PESEL number:

It has to be a PESEL a person born in either 20th or 21st century

The birth birth date has to be random but doesn't have to validate leap years or number of days in a month (i.e. the numbers representing the day number have to be between 01 and 31)

All valid PESELs in this date range (01.01.1990-31.12.2099) must be possible

The shortest code (i.e. complete program code), in bytes, wins.

答:
Matlab, 156 bytes

```<code>a=datestr(693961+randi(73049),'yyyymmdd');a(5)=a(5)+2*(a(1)>49);A=a(3:8)-48;b=randi(10,1,4);[[A b mod(10-mod(sum(('1379137913'-48).*[A b]),10),10)]+48 '']
</code>```

Ungolfed with some explanation:

```<code>a=datestr(693961+randi(73049),'yyyymmdd');
  -- generates date serial number in desired range and converts do string
a(5)=a(5)+2*(a(1)>49);
  -- modifies the first digit of the month if year >= 2000 (first digit >1)
A=a(3:8)-48;
  -- gets the "YYMMDD" part and converts from string to array of numbers
b=randi(10,1,4)-1;
  -- gets remaining 4 random digits ("ZZZX")
[[A b mod(10-mod(sum(('1379137913'-48).*[A b]),10),10)]+48 '']
  -- computes the last digit and converts the whole thing to string
</code>```

Title: Generate random PESEL number

Body:
Matlab, 156 bytes

a=datestr(693961+randi(73049),'yyyymmdd');a(5)=a(5)+2*(a(1)>49);A=a(3:8)-48;b=randi(10,1,4);[[A b mod(10-mod(sum(('1379137913'-48).*[A b]),10),10)]+48 '']

Ungolfed with some explanation:

a=datestr(693961+randi(73049),'yyyymmdd');
  -- generates date serial number in desired range and converts do string
a(5)=a(5)+2*(a(1)>49);
  -- modifies the first digit of the month if year >= 2000 (first digit >1)
A=a(3:8)-48;
  -- gets the "YYMMDD" part and converts from string to array of numbers
b=randi(10,1,4)-1;
  -- gets remaining 4 random digits ("ZZZX")
[[A b mod(10-mod(sum(('1379137913'-48).*[A b]),10),10)]+48 '']
  -- computes the last digit and converts the whole thing to string


问:
Is this square symmetrical?
Write a program or function that takes in a 4×4 text grid consisting of exactly 4 A's, 4 B's, 4 C's, and 4 D's, such as:

```<code>ACDC
BBCA
BADD
ABCD
</code>```

The ABCD's may be in any arrangement but there will always be 4 of each. You can assume the input is valid. If desired you can also assume it has a trailing newline and/or that it comes as one line in reading order, e.g. ACDCBBCABADDABCD. You may also replace the characters ABCD with 0123 or 1234 respectively, if desired (but that's all).

Output a truthy value if the text grid has any form of reflective or rotational symmetry. Specifically:

If there is a central horizontal line of symmetry. e.g.

```<code>BACD
BACD
BACD \___ bottom mirrors top
BACD /
</code>```

If there is a central vertical line of symmetry. e.g.

```<code>BCCB
DAAD
CAAC
BDDB
  \/___ right mirrors left
</code>```

If there is a diagonal line of symmetry (in either direction). e.g.

```<code>     ___ diagonally mirrored
    /
ABDC
BACD
DCAB
CDBA
    \___ diagonally mirrored
</code>```

If there is 90° rotational symmetry. e.g.

```<code>BDAB
ACCD    same if rotated 90 degrees (or 180 or 270)
DCCA
BADB
</code>```

If there is 180° rotational symmetry. e.g.

```<code>DBCA
BDCA    same if rotated 180 degrees
ACDB
ACBD
</code>```

(Note that translational symmetry doesn't come into play here.)

Output a falsy value if the grid doesn't have one of the symmetries mentioned above. e.g. the very first example grid.

The shortest code in bytes wins.

答:
Python 2, <s>154</s> 146 bytes

Checks if any of the necessary transformations is equivalent to the original using numpy arrays. Input is taken as a list of four strings.

from numpy import*
A=array(map(list,input()))
R=rot90
T=transpose(A)
print any([all(A==Z)for Z in(A[:,::-1],A[::-1],R(A),R(A,2),R(A,3),T,R(T,2))])
```

Try it online

Taking input as a single string is one char longer, with A=array(list(input())).reshape(4,4). A[:,::-1] is the same as fliplr(A). A[::-1] is the same as flipud(A).

Title: Is this square symmetrical?

Body:
Python 2, <s>154</s> 146 bytes

Checks if any of the necessary transformations is equivalent to the original using numpy arrays. Input is taken as a list of four strings.

from numpy import*
A=array(map(list,input()))
R=rot90
T=transpose(A)
print any([all(A==Z)for Z in(A[:,::-1],A[::-1],R(A),R(A,2),R(A,3),T,R(T,2))])

Try it online

Taking input as a single string is one char longer, with A=array(list(input())).reshape(4,4). A[:,::-1] is the same as fliplr(A). A[::-1] is the same as flipud(A).


问:
Add without addition (or any of the 4 basic arithmetic operators)
Problem:

Your goal is to add two input numbers without using any of the following math operators: +,-,*,/.

Additionally, you can't use any built-in functions that are designed to replace those math operators.

Scoring:

Smallest code (in number of bytes) wins.

Update

Most of the programs i've seen either concatenate two arrays containing their numbers, or make first number of a character, append second number characters, then count them all.

Shortest array counter: APL with 8 chars, by Tobia

Shortest array concatenation: Golfscript with 4 chars, by Doorknob

Shortest logarithmic solution: TI-89 Basic with 19 chars, by Quincunx

Integration solution: Mathematica with 45 chars, by Michael Stern

Coolest, in my opinion: bitwise operators in javascript, by dave

答:
Python 3, 46 Bytes

```<code>def s(a,b):
 for i in range(b):a=-~a
 return a
</code>```

Body:
Python 3, 46 Bytes

def s(a,b):
 for i in range(b):a=-~a
 return a


答:
JavaScript (ES6), 43 bytes

```<code>f=(i,n=0,d=1)=>i?f(i-1,d,n+d-n%d*2):n+'/'+d
</code>```

1-indexed; change to n=1 for 0-indexed. The linked OEIS page has a useful recurrence relation for each term in terms of the previous two terms; I merely reinterpreted it as a recurrence for each fraction in terms of the previous fraction. Unfortunately we don't have inline TeX so you'll just have to paste it onto another site to find out how this formats:

$$ \frac{a}{b} \Rightarrow \frac{b}{a + b - 2(a \bmod b)} $$

Body:
JavaScript (ES6), 43 bytes

f=(i,n=0,d=1)=>i?f(i-1,d,n+d-n%d*2):n+'/'+d

1-indexed; change to n=1 for 0-indexed. The linked OEIS page has a useful recurrence relation for each term in terms of the previous two terms; I merely reinterpreted it as a recurrence for each fraction in terms of the previous fraction. Unfortunately we don't have inline TeX so you'll just have to paste it onto another site to find out how this formats:

$$ \frac{a}{b} \Rightarrow \frac{b}{a + b - 2(a \bmod b)} $$


答:
m4, 131 bytes

```<code>define(s,`ifelse($1,1,1,eval($1%2),0,`s(eval($1/2))',`eval(s(eval(($1-1)/2))+s(eval(($1+1)/2)))')')define(r,`s($1)/s(eval($1+1))')
</code>```

Defines a macro r such that r(n) evaluates according to the spec. Not really golfed at all, I just coded the formula.

Body:
m4, 131 bytes

define(s,`ifelse($1,1,1,eval($1%2),0,`s(eval($1/2))',`eval(s(eval(($1-1)/2))+s(eval(($1+1)/2)))')')define(r,`s($1)/s(eval($1+1))')

Defines a macro r such that r(n) evaluates according to the spec. Not really golfed at all, I just coded the formula.


问:
Is it a wordinian?
What is the shortest way to see if an input is a wordinian using any programming language?

A wordinian is a word that contains words of length 1 to the original word's length. For example,

bin

'I' is a word

  'in' is a word

  'bin' is a word

Or,

stage

'a' is a word

  'ta' is a word (yes it is)

  'age' is a word

  'stag' is a word

  'stage' is a word

Input

Your code should take a word and a dictionary as inputs, in any reasonable format.

Output

The output should be a value to indicate true or false, to tell us if the word is a wordinian.

For more info on wordinians click here.

Here is a list of words that I will be using as inputs and subwords. Also, in response to @xnor, it has to contain subwords of each length, not a chain of subwords. Note that only one word will be used as an input.

答:
Perl, <s>42</s> 41 bytes

Includes +2 for -p0

Give word followed by the dictionary on STDIN:

```<code>(echo stage; cat dictionary.txt) | ./wordinian.pl
</code>```

(When testing on unix make sure dictionary.txt uses \n as line terminator, not \r\n)

wordinian.pl:

```<code>#!/usr/bin/perl -p0
s%\G.%!/^.*(.{$+[0]})\H*
\1
/%eg;$_=!//
</code>```

Title: Is it a wordinian?

Body:
Perl, <s>42</s> 41 bytes

Includes +2 for -p0

Give word followed by the dictionary on STDIN:

(echo stage; cat dictionary.txt) | ./wordinian.pl

(When testing on unix make sure dictionary.txt uses \n as line terminator, not \r\n)

wordinian.pl:

#!/usr/bin/perl -p0
s%\G.%!/^.*(.{$+[0]})\H*
\1
/%eg;$_=!//


答:
Python 3, 99 bytes

```<code>def f(x):
 t=x;c=[]
 for i in range(7):*t,=[map(''.join,zip(*t)),t[::-1]][i%2];c+=t,
 return x in c
</code>```

A function that takes input, via argument, of a list of strings and returns True or False as relevant.

This uses the same approach as @MartinEnder's answer.

How it works

```<code>def f(x)                Function with input list of strings x
 t=x;c=[]               Initilaise temporary square t and combination list c
 for i in range(7):...  For i in range [0,6]:
 [...][i%2]              If i is even:
 zip(*t)                  transpose(t)
 *t,=map(''.join,...)     t = t with each line concatenated (such that t is in the same
                          format as x)
                         Else:
 *t,=t[::-1]              t = reverse(t)
 c+=t,                   Append t to c
 return x in c           Return True if x is in c else return False
</code>```

Try it on Ideone

Title: Is this square symmetrical?

Body:
Write a program or function that takes in a 4×4 text grid consisting of exactly 4 A's, 4 B's, 4 C's, and 4 D's, such as:

```<code>ACDC
BBCA
BADD
ABCD
</code>```

The ABCD's may be in any arrangement but there will always be 4 of each. You can assume the input is valid. If desired you can also assume it has a trailing newline and/or that it comes as one line in reading order, e.g. ACDCBBCABADDABCD. You may also replace the characters ABCD with 0123 or 1234 respectively, if desired (but that's all).

Output a truthy value if the text grid has any form of reflective or rotational symmetry. Specifically:

If there is a central horizontal line of symmetry. e.g.

```<code>BACD
BACD
BACD \___ bottom mirrors top
BACD /
</code>```

If there is a central vertical line of symmetry. e.g.

```<code>BCCB
DAAD
CAAC
BDDB
  \/___ right mirrors left
</code>```

If there is a diagonal line of symmetry (in either direction). e.g.

```<code>     ___ diagonally mirrored
    /
ABDC
BACD
DCAB
CDBA
    \___ diagonally mirrored
</code>```

If there is 90° rotational symmetry. e.g.

```<code>BDAB
ACCD    same if rotated 90 degrees (or 180 or 270)
DCCA
BADB
</code>```

If there is 180° rotational symmetry. e.g.

```<code>DBCA
BDCA    same if rotated 180 degrees
ACDB
ACBD
</code>```

(Note that translational symmetry doesn't come into play here.)

Output a falsy value if the grid doesn't have one of the symmetries mentioned above. e.g. the very first example grid.

The shortest code in bytes wins.

Body:
Python 3, 99 bytes

def f(x):
 t=x;c=[]
 for i in range(7):*t,=[map(''.join,zip(*t)),t[::-1]][i%2];c+=t,
 return x in c

A function that takes input, via argument, of a list of strings and returns True or False as relevant.

This uses the same approach as @MartinEnder's answer.

How it works

def f(x)                Function with input list of strings x
 t=x;c=[]               Initilaise temporary square t and combination list c
 for i in range(7):...  For i in range [0,6]:
 [...][i%2]              If i is even:
 zip(*t)                  transpose(t)
 *t,=map(''.join,...)     t = t with each line concatenated (such that t is in the same
                          format as x)
                         Else:
 *t,=t[::-1]              t = reverse(t)
 c+=t,                   Append t to c
 return x in c           Return True if x is in c else return False

Try it on Ideone


问:
Deciphering XKCD colors
Randall Munroe (author of XKCD) held a survey to give names to colors. The main outcome is a list of names for the 954 most common RGB monitor colors.

For ease of programming, here is the list in plain text: http://xkcd.com/color/rgb.txt. Beware, the first line is not data, but contains the license.

Write a program or function that takes a valid color name from above list as input and outputs the associated RGB color code. Your program does not have to handle invalid inputs in any defined manner.

Standard loopholes apply. Additionally, your answer must not use pre-defined (built-in or external) color code <-> color name maps. (This includes the linked list.) Shortest code in bytes wins. If you read from a file, the file's byte count must be included.

Examples:

```<code>dark peach -> #de7e5d
robin's egg blue -> #98eff9
pink/purple -> #ef1de7
</code>```

答:
C#, 6422 bytes

Code is 575 bytes, data is 5847 bytes

The data exists in an adjacent GZipped file which contains a transformed representation of the original data. Color words which appear more than once are extracted and placed in a header table at the top of the file, prefixed by a one-byte length.

Data entries (after the header) consist of a set of:

Single byte entries representing a common word from the header table (value equals array offset + 16)

Inline string data prefixed by a single-byte length field (max length 15)

Each entry is terminated with either 0xFF, 0xFE, 0xFD which indicates that the next one, two, or three bytes following represent the color value offset, respectively.

The table is parsed in-order and color value is accumulated until a matching string to the input is found.

Minified Decompression / Lookup Code:

```<code>using System;using System.IO;using System.IO.Compression;namespace G{partial class P{static void Main(string[]a){var f=new GZipStream(File.OpenRead("m"),CompressionMode.Decompress);var b=new BinaryReader(f,S.Encoding.GetEncoding(1252));Func<int>r=()=>f.ReadByte();var d=new string[256];int t,v=0;while(""!=(d[v++]=new string(b.ReadChars(r()))));var k="";v=0;while(0<(t=r())){if(t<0xFD)k+=(t<16?new string(b.ReadChars(t)):d[t-16])+" ";else{v+=t==0xFF?r():t==0xFE?b.ReadUInt16():(r())+(b.ReadUInt16()<<8);if(k.Trim()==a[0]){Console.WriteLine($"#{v:x6}");return;}k="";}}}}}
</code>```

Data Compression Code

```<code>public static void Compress(string path)
{
    var lines = File.ReadAllLines(path);

    var grams = new Dictionary<string, int>();

    var data = new Dictionary<string, string>();

    foreach (var line in lines)
    {
        var tokens = line.Split('\t');

        data[tokens[0]] = tokens[1];

        foreach (var gram in tokens[0].Split(' '))
        {
            int count;

            if (grams.TryGetValue(gram, out count))
            {
                grams[gram] = count + 1;
            }
            else
            {
                grams[gram] = 1;
            }
        }
    }

    var dict = new Dictionary<string, byte>();
    byte codeValue = 0;
    foreach (var result in grams.OrderBy(kvp => -kvp.Value))
    {
        if (result.Value == 1)
            break;

        dict[result.Key] = codeValue;
        codeValue++;
    }

    using (var outputData = new BinaryWriter(File.OpenWrite("m.dat"), Encoding.GetEncoding(1252)))
    {
        foreach(var dictValue in dict.OrderBy(kvp => kvp.Value))
        {
            outputData.Write((byte)dictValue.Key.Length);
            outputData.Write(dictValue.Key.ToCharArray());
        }

        outputData.Write('\0');

        int currentColor = 0;

        foreach (var entry in data.OrderBy(kvp => kvp.Value))
        {
            foreach (var gram in entry.Key.Split(' '))
            {
                if (dict.ContainsKey(gram))
                {
                    outputData.Write((byte)(dict[gram] + 16));
                }
                else
                {
                    outputData.Write((byte)gram.Length);
                    outputData.Write(gram.ToCharArray());
                }
            }

            var colorValueString = entry.Value.TrimStart('#');
            var colorValueInt = int.Parse(colorValueString, System.Globalization.NumberStyles.AllowHexSpecifier);

            var colorValueDiff = colorValueInt - currentColor;

            if(colorValueDiff <= byte.MaxValue)
            {
                outputData.Write((byte)0xFF);
                outputData.Write((byte)colorValueDiff);
            }
            else if(colorValueDiff <= ushort.MaxValue)
            {
                outputData.Write((byte)0xFE);
                outputData.Write((ushort)colorValueDiff);
            }
            else
            {
                outputData.Write((byte)0xFD);
                outputData.Write(colorValueDiff);
                outputData.BaseStream.Seek(-1, SeekOrigin.Current);
            }

            currentColor = colorValueInt;
        }
    }

    var d = File.ReadAllBytes("m.dat");
    var g = new GZipStream(File.OpenWrite("m"), CompressionLevel.Optimal);

    g.Write(d, 0, d.Length);
    g.Dispose();
}
</code>```

Title: Deciphering XKCD colors

Body:
C#, 6422 bytes

Code is 575 bytes, data is 5847 bytes

The data exists in an adjacent GZipped file which contains a transformed representation of the original data. Color words which appear more than once are extracted and placed in a header table at the top of the file, prefixed by a one-byte length.

Data entries (after the header) consist of a set of:

Single byte entries representing a common word from the header table (value equals array offset + 16)

Inline string data prefixed by a single-byte length field (max length 15)

Each entry is terminated with either 0xFF, 0xFE, 0xFD which indicates that the next one, two, or three bytes following represent the color value offset, respectively.

The table is parsed in-order and color value is accumulated until a matching string to the input is found.

Minified Decompression / Lookup Code:

using System;using System.IO;using System.IO.Compression;namespace G{partial class P{static void Main(string[]a){var f=new GZipStream(File.OpenRead("m"),CompressionMode.Decompress);var b=new BinaryReader(f,S.Encoding.GetEncoding(1252));Func<int>r=()=>f.ReadByte();var d=new string[256];int t,v=0;while(""!=(d[v++]=new string(b.ReadChars(r()))));var k="";v=0;while(0<(t=r())){if(t<0xFD)k+=(t<16?new string(b.ReadChars(t)):d[t-16])+" ";else{v+=t==0xFF?r():t==0xFE?b.ReadUInt16():(r())+(b.ReadUInt16()<<8);if(k.Trim()==a[0]){Console.WriteLine($"#{v:x6}");return;}k="";}}}}}

Data Compression Code

public static void Compress(string path)
{
    var lines = File.ReadAllLines(path);

    var grams = new Dictionary<string, int>();

    var data = new Dictionary<string, string>();

    foreach (var line in lines)
    {
        var tokens = line.Split('\t');

        data[tokens[0]] = tokens[1];

        foreach (var gram in tokens[0].Split(' '))
        {
            int count;

            if (grams.TryGetValue(gram, out count))
            {
                grams[gram] = count + 1;
            }
            else
            {
                grams[gram] = 1;
            }
        }
    }

    var dict = new Dictionary<string, byte>();
    byte codeValue = 0;
    foreach (var result in grams.OrderBy(kvp => -kvp.Value))
    {
        if (result.Value == 1)
            break;

        dict[result.Key] = codeValue;
        codeValue++;
    }

    using (var outputData = new BinaryWriter(File.OpenWrite("m.dat"), Encoding.GetEncoding(1252)))
    {
        foreach(var dictValue in dict.OrderBy(kvp => kvp.Value))
        {
            outputData.Write((byte)dictValue.Key.Length);
            outputData.Write(dictValue.Key.ToCharArray());
        }

        outputData.Write('\0');

        int currentColor = 0;

        foreach (var entry in data.OrderBy(kvp => kvp.Value))
        {
            foreach (var gram in entry.Key.Split(' '))
            {
                if (dict.ContainsKey(gram))
                {
                    outputData.Write((byte)(dict[gram] + 16));
                }
                else
                {
                    outputData.Write((byte)gram.Length);
                    outputData.Write(gram.ToCharArray());
                }
            }

            var colorValueString = entry.Value.TrimStart('#');
            var colorValueInt = int.Parse(colorValueString, System.Globalization.NumberStyles.AllowHexSpecifier);

            var colorValueDiff = colorValueInt - currentColor;

            if(colorValueDiff <= byte.MaxValue)
            {
                outputData.Write((byte)0xFF);
                outputData.Write((byte)colorValueDiff);
            }
            else if(colorValueDiff <= ushort.MaxValue)
            {
                outputData.Write((byte)0xFE);
                outputData.Write((ushort)colorValueDiff);
            }
            else
            {
                outputData.Write((byte)0xFD);
                outputData.Write(colorValueDiff);
                outputData.BaseStream.Seek(-1, SeekOrigin.Current);
            }

            currentColor = colorValueInt;
        }
    }

    var d = File.ReadAllBytes("m.dat");
    var g = new GZipStream(File.OpenWrite("m"), CompressionLevel.Optimal);

    g.Write(d, 0, d.Length);
    g.Dispose();
}


问:
Code golf ABC's: The ASCII Box Challenge
Given two positive integers, 'a' and 'b', output an ascii-art "box" that is a characters wide and b characters tall. For example, with '4' and '6':

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

Simple right? Here's the twist: The border of the box must be the characters of "a" and "b" alternating. This starts at the top left corner, and continues in a clockwise spiral. For example, the previous example with 4 and 6 should be

```<code>4646
6  4
4  6
6  4
4  6
6464
</code>```

A and B may be two-digit numbers. For example, the inputs "10" and "3" should output this:

```<code>1031031031
1        0
3013013013
</code>```

In order to keep the output relatively small, you do not have to support three or more digit numbers. Also, since inputs are restricted to positive integers, '0' is an invalid input, which you do not have to handle.

Here are some more test cases:

```<code>Input: (3, 5)
Output:

353
5 5
3 3
5 5
353

Input: (1, 1)
Output:

1

Input: (4, 4)
Output:

4444
4  4
4  4
4444

Input: (27, 1)
Output:

271271271271271271271271271

Input: (1, 17)
Output:

1
1
7
1
1
7
1
1
7
1
1
7
1
1
7
1
1

Input: (12, 34):
Output:

123412341234
4          1
3          2
2          3
1          4
4          1
3          2
2          3
1          4
4          1
3          2
2          3
1          4
4          1
3          2
2          3
1          4
4          1
3          2
2          3
1          4
4          1
3          2
2          3
1          4
4          1
3          2
2          3
1          4
4          1
3          2
2          3
1          4
432143214321
</code>```

You may take input and output in any reasonable format, and standard loopholes are banned. Since this is code-golf, the shortest answer in bytes wins!

答:
JavaScript (ES6), 171 bytes

```<code>(w,h)=>[...Array(h)].map((_,i)=>i?++i<h?(w>1?s[p+p+1-i]+` `.repeat(w-2):``)+s[w+i-2]:[...s.substr(p,w)].reverse().join``:s.slice(0,w),s=`${w}${h}`.repeat(p=w+h-2)).join`\n`
</code>```

Where \n represents the literal newline character. Creates a repeated digit string, then decides what to concatenate based on which row we're on; top row is just the initial slice of the repeated digit string, bottom row (if any) is a reversed slice from the middle of the string, while intervening rows are built up using characters taken from other parts of the string.

Body:
JavaScript (ES6), 171 bytes

(w,h)=>[...Array(h)].map((_,i)=>i?++i<h?(w>1?s[p+p+1-i]+` `.repeat(w-2):``)+s[w+i-2]:[...s.substr(p,w)].reverse().join``:s.slice(0,w),s=`${w}${h}`.repeat(p=w+h-2)).join`\n`

Where \n represents the literal newline character. Creates a repeated digit string, then decides what to concatenate based on which row we're on; top row is just the initial slice of the repeated digit string, bottom row (if any) is a reversed slice from the middle of the string, while intervening rows are built up using characters taken from other parts of the string.


Title: Golf me a card dealer

Body:
Frank has been working IT his whole life. Each day he responds to tickets, organizes equipment, and reports to his boss. One day, near the closing time on friday, Frank is doing his final inventory and sorting come cables in the supply closet. Suddenly, the door closes and locks from the outside! Such audacity! Frank shakes the door to try and let anyone know that he's stuck in the closet. Blast, nobody comes to his aid. With no cellphone, and no internet connection, Frank settles in with his laptop. After countless games of solitaire, frank decides to make his own card game....

Challenge:

In this case, you are frank (but not really). Your challenge is to create a dealer that can deal hands of cards, that could be dealt realistically. Your program needs to do 2 things: deal hands of cards according to an input, and take all the hands and reshuffle them. You must do this in the least ammount of bytes possible.

Rules:

Possible cards include all classic numbers and faces (a,2,3,4,5,6,7,8,9,10,j,q,k) and all suits (c,s,h,d), and two jokers (0j).

If a card is dealt, it cannot be dealt again until the program is given the reshuffle command, or it runs out of cards.

valid inputs are 'd' to deal a hand of 6 cards, and 'r' to reshuffle. NOTE that you can only deal out 9 hands before you run out of cards. Your program can either:

Automatically reshuffle,

Or give a 'X' to indicate that the dealer is out of cards.

your program needs to be able to take multiple commands over its running span.

All possible hands need to be able to be dealt in every order. Though, your program does NOT have to be random.

Examples:

We deal twice, the first hand yields the 2 of hearts, a 4 of spades, 9 of clubs, a joker, an ace of spades, and a 6 of diamonds. The second hand yields the 3 of hearts, the 10 of diamonds, the 10 of clubs, the king of clubs, the ace of diamonds, and the queen of spades. this is VALID because this is possible in real life.

d

  2h4s9c0jas6d

  d

  3h10d10ckcadqs

We deal twice, the first hand yields a mass of 5 cards (indicated by the dashes) and a 6 of hearts. The second hand deals another mass of 5 cards (again, the dashes) and another 6 of hearts. This is INVALID because it cannot happen in real life.

d

  -----6h

  d

  6h-----

we deal once, reset, and deal again. some of the cards from the first and the second deal match. this is VALID because cardstacks are renewed when shuffled.

d

  123456

  r

d

  456789

Scoring:

As with any golf, the lowest byte count wins! Good luck!

Body:
Javascript (ES6), 189 bytes

i=>{for(n=52,d=['0j','0j'];n;d[n+1]='123456789JQKA'[--n>>2]+(n<4?0:'')+'cdhs'[n&3]);i.forEach(c=>{c!='r'&&n-54||(d.sort((a,b)=>Math.random()-.5),n=0);c=='d'&&console.log(d.slice(n,n+=6))})}

Demo:

let F =
i=>{for(n=52,d=['0j','0j'];n;d[n+1]='123456789JQKA'[--n>>2]+(n<4?0:'')+'cdhs'[n&3]);i.forEach(c=>{c!='r'&&n-54||(d.sort((a,b)=>Math.random()-.5),n=0);c=='d'&&console.log(d.slice(n,n+=6))})}

F([..."rddrdddddd"]);


答:
Pyth, 11 bytes

```<code><7.u?%Y2CN_
</code>```

Test suite

This uses Martin's transpose and reverse technique, but with a twist. While other solutions have explicitly generated all 8 symmetries, then counted the number of appearances of the original, this program uses Pyth's .u function.

The .u function is the "Apply until repeat is found". In this case, we alternately transpose and reverse until a repetition happens, then accumulate the results into a list. Then, I remove the last 7 values, so there will only be a value remaining if there were no symmetries, and the first repetition happened after all 8 reflections and repetitions were generated.

Explanation:

```<code><7.u?%Y2CN_
<7.u?%Y2CN_NQ    Implicit variables
                 Q = eval(input())
  .u        Q    Starting with Q, apply the following until a repeat occurs,
                 then accumulate all values into a list.
    ?%Y2         If the iteration number is odd
        CN       Transpose
          _N     Else reverse
<7               Remove the last 7 results
</code>```

Title: Is this square symmetrical?

Body:
Pyth, 11 bytes

<7.u?%Y2CN_

<a href="https://pyth.herokuapp.com/?code=%3C7.u%3F%25Y2CN_&input=%0A&test_suite=1&test_suite_input=%5B%27ACDC%27%2C+%27BBCA%27%2C+%27BADD%27%2C+%27ABCD%27%5D%0A%5B%22BACD%22%2C+%22BACD%22%2C+%22BACD%22%2C+%22BADC%22%5D%0A%5B%22BCCB%22%2C+%22DAAD%22%2C+%22CAAC%22%2C+%22BDDB%22%5D%0A%5B%22BACD%22%2C+%22BACD%22%2C+%22BACD%22%2C+%22BACD%22%5D%0A%5B%27ABDC%27%2C+%27BACD%27%2C+%27DCAB%27%2C+%27CDBA%27%5D%0A%5B%27BDAB%27%2C+%27ACCD%27%2C+%27DCCA%27%2C+%27BADB%27%5D%0A%5B%27DBCA%27%2C+%27BDCA%27%2C+%27ACDB%27%2C+%27ACBD%27%5D&debug=0">Test suite

This uses Martin's transpose and reverse technique, but with a twist. While other solutions have explicitly generated all 8 symmetries, then counted the number of appearances of the original, this program uses Pyth's .u function.

The .u function is the "Apply until repeat is found". In this case, we alternately transpose and reverse until a repetition happens, then accumulate the results into a list. Then, I remove the last 7 values, so there will only be a value remaining if there were no symmetries, and the first repetition happened after all 8 reflections and repetitions were generated.

Explanation:

<7.u?%Y2CN_
<7.u?%Y2CN_NQ    Implicit variables
                 Q = eval(input())
  .u        Q    Starting with Q, apply the following until a repeat occurs,
                 then accumulate all values into a list.
    ?%Y2         If the iteration number is odd
        CN       Transpose
          _N     Else reverse
<7               Remove the last 7 results


答:
JavaScript (ES6), 69 bytes

```<code>n=>{for(a=[],s=i=0;i++<n;a[j]=1,s+=j)for(j=i-s%i;a[j];)j+=i;return j}
</code>```

At each stage just checks all the numbers with the appropriate remainder until it finds one that it hasn't seen before, then marks it seen and updates the total.

Title: Smallest positive integer not yet appeared so that the sum of the first n elements is divisible by n

Body:
Task

Given positive integer n, output a(n) where a is the sequence defined below:

a(n) is the smallest positive integer not yet appeared so that the sum of the first n elements in the sequence is divisible by n.

Example

a(1) is 1 because it is the smallest positive integer that has not appeared in the sequence, and 1 is divisible by 1.

a(10) is 16 because look at the first nine elements: 1,3,2,6,8,4,11,5,14. They sum up to 54, so for the first ten elements to sum up to a multiple of 10, a(10) would need to have a remainder of 6 when divided by 10. 6 has already appeared, so a(10) is 16 instead.

Testcases

```<code>n     a(n)
1     1
2     3
3     2
4     6
5     8
6     4
7     11
8     5
9     14
10    16
11    7
12    19
13    21
14    9
15    24
16    10
17    27
18    29
19    12
20    32
100   62
1000  1618
10000 16180
</code>```

a(n) from n=1 to n=10000

References

OEIS A019444

Body:
JavaScript (ES6), 69 bytes

n=>{for(a=[],s=i=0;i++<n;a[j]=1,s+=j)for(j=i-s%i;a[j];)j+=i;return j}

At each stage just checks all the numbers with the appropriate remainder until it finds one that it hasn't seen before, then marks it seen and updates the total.


答:
Haskell, 25 bytes

```<code>n+m=length$[1..m]++[1..n]
</code>```

We can no longer use the old +? No problem, we can just define a new one. This approach doesn't work with negative numbers, I have yet to figure out something else for them.

Title: Add without addition (or any of the 4 basic arithmetic operators)

Body:
Problem:

Your goal is to add two input numbers without using any of the following math operators: +,-,*,/.

Additionally, you can't use any built-in functions that are designed to replace those math operators.

Scoring:

Smallest code (in number of bytes) wins.

Update

Most of the programs i've seen either concatenate two arrays containing their numbers, or make first number of a character, append second number characters, then count them all.

Shortest array counter: APL with 8 chars, by Tobia

Shortest array concatenation: Golfscript with 4 chars, by Doorknob

Shortest logarithmic solution: TI-89 Basic with 19 chars, by Quincunx

Integration solution: Mathematica with 45 chars, by Michael Stern

Coolest, in my opinion: bitwise operators in javascript, by dave

Body:
Haskell, 25 bytes

n+m=length$[1..m]++[1..n]

We can no longer use the old +? No problem, we can just define a new one. This approach doesn't work with negative numbers, I have yet to figure out something else for them.


问:
Determine if a move exists in a Bejeweled/match 3 game

Background

In Bejeweled and similar games, the player must swap any two adjacent gems (no diagonals) in an 8x8 grid of gems in order to match three of the same color in a row. The gems can be matched horizontally or vertically. Gameplay continues until there no move exists that can be made resulting in three in a row, at which point the game is over.

Task

The goal is to write a program that determines whether a game of Bejeweled is not over yet. In other words, it must check to see if there is a possible move that makes at least three in a row. There can be more than three gems in a row and it is still a valid move.

Input

Your program must accept via standard input an 8x8 representation of a Bejeweled grid. Each of the seven gem colors will be represented by a digit from 1 to 7. Each line will contain one row, and 8 lines, each consisting of 8 digits, will be input. See the examples. You can assume that the input will always follow this format, and will never already contain three in a row.

Output

The program must then output (to standard output) yes or no depending on whether or not at least one valid move exists that would result in three or more gems in a row. Your program must not output anything other than a single instance of either yes or no.

Rules

Your program must not use any external files or resources, command-line arguments, or require a certain file name. The program with the least number of bytes in its source code wins.

Examples

Input:

```<code>12314131
13224145
54762673
61716653
61341144
23453774
27645426
75575656
</code>```

Output: yes

Input:

```<code>35261546
76421754
15743271
62135642
35617653
64565476
54427254
15635465
</code>```

Output: no

See MT0's answer below for additional test cases.

答:
Ruby, 201 bytes

I was disappointed not to see any solutions to this great challenge that don't use a regex or brute force (although those are great), so I wrote one. It takes input on STDIN.

The core bitwise arithmetic algorithm is derived from this fantastic answer on Game Development Stack Exchange by @leander.

```<code>s=$<.read
$><<(?1..?9).any?{|n|a=[0]*19
s.scan(n){i=$`.size
a[i/9+1]+=2**(i%9)
a[i%9+10]+=2**(i/9)}
a.each_cons(3).any?{|x,y,z|q=y&y<<1
l=q<<1
q>>=2
y&(l<<1|q>>1)|(q|l|(y&y<<2)>>1)&(x|z)>0}}?"yes":"no"
</code>```

Ruby lambda, 181 bytes

Here it is as a lambda that takes a string and returns true or false:

```<code>->s{(?1..?9).any?{|n|a=[0]*19
s.scan(n){i=$`.size
a[i/9+1]+=2**(i%9)
a[i%9+10]+=2**(i/9)}
a.each_cons(3).any?{|x,y,z|q=y&y<<1
l=q<<1
q>>=2
y&(l<<1|q>>1)|(q|l|(y&y<<2)>>1)&(x|z)>0}}}
</code>```

See it on repl.it: https://repl.it/ColJ/2

Ungolfed & explanation

```<code>->s{
  (?1..?9).any? {|n|
    a = [0] * 19

    s.scan(n) {
      i = $`.size
      a[i/9+1] += 2**(i%9)
      a[i%9+10] += 2**(i/9)
    }

    a.each_cons(3).any? {|x,y,z|
      q = y & y << 1
      l = q << 1
      q >>= 2
      y & (l << 1 | q >> 1) |
        (q | l | (y & y << 2) >> 1) &
        (x | z) > 0
    }
  }
}
</code>```

The code iterates over the digits "1" to "9." Each iteration has two discrete steps:

The first step is board transformation, which you can see in the s.scan(n) block in the ungolfed code. It transforms the board into an array of 8 integers, one for each row, by treating matching digits as 1s and all others as 0s in a binary string. For example, take the row 12231123. In the first iteration, this will become the binary string 10001100 (all 1s become—er, stay—1s and all other digits become 0s), which is the decimal number 140. In the second iteration the same row becomes 01100010 (all 2s become 2s and all other digits become 0s), or decimal 98.

It simultaneously performs a second transformation, which is the same as the first but with the board rotated 90 degrees. This lets us use the same logic for making horizontal matches as vertical ones. For simplicity, it concatenates the two boards into a single long one with a zero at the beginning, middle (to separate the two boards), and end for padding.

The second step is searching for possible matches, which you can see in the each_cons(3).any? block. The transformed rows (which are now 8-bit integers) are checked in (overlapping) groups of three rows (x, y, z) using bitwise arithmetic. Each group is checked to see if a match can be made in row y, either by shifting a piece in row y or by shifting a piece into y from x or z. Since there is a zero "row" before and after both the original and rotated boards' rows, we don't have to check if we're on the first or last row of a board.

If no matches were found, it continues to the next iteration.

Body:
Ruby, 201 bytes

I was disappointed not to see any solutions to this great challenge that don't use a regex or brute force (although those are great), so I wrote one. It takes input on STDIN.

The core bitwise arithmetic algorithm is derived from this fantastic answer on Game Development Stack Exchange by @leander.

s=$<.read
$><<(?1..?9).any?{|n|a=[0]*19
s.scan(n){i=$`.size
a[i/9+1]+=2**(i%9)
a[i%9+10]+=2**(i/9)}
a.each_cons(3).any?{|x,y,z|q=y&y<<1
l=q<<1
q>>=2
y&(l<<1|q>>1)|(q|l|(y&y<<2)>>1)&(x|z)>0}}?"yes":"no"

Ruby lambda, 181 bytes

Here it is as a lambda that takes a string and returns true or false:

->s{(?1..?9).any?{|n|a=[0]*19
s.scan(n){i=$`.size
a[i/9+1]+=2**(i%9)
a[i%9+10]+=2**(i/9)}
a.each_cons(3).any?{|x,y,z|q=y&y<<1
l=q<<1
q>>=2
y&(l<<1|q>>1)|(q|l|(y&y<<2)>>1)&(x|z)>0}}}

See it on repl.it: https://repl.it/ColJ/2

Ungolfed & explanation

->s{
  (?1..?9).any? {|n|
    a = [0] * 19

    s.scan(n) {
      i = $`.size
      a[i/9+1] += 2**(i%9)
      a[i%9+10] += 2**(i/9)
    }

    a.each_cons(3).any? {|x,y,z|
      q = y & y << 1
      l = q << 1
      q >>= 2
      y & (l << 1 | q >> 1) |
        (q | l | (y & y << 2) >> 1) &
        (x | z) > 0
    }
  }
}

The code iterates over the digits "1" to "9." Each iteration has two discrete steps:

The first step is board transformation, which you can see in the s.scan(n) block in the ungolfed code. It transforms the board into an array of 8 integers, one for each row, by treating matching digits as 1s and all others as 0s in a binary string. For example, take the row 12231123. In the first iteration, this will become the binary string 10001100 (all 1s become—er, stay—1s and all other digits become 0s), which is the decimal number 140. In the second iteration the same row becomes 01100010 (all 2s become 2s and all other digits become 0s), or decimal 98.

It simultaneously performs a second transformation, which is the same as the first but with the board rotated 90 degrees. This lets us use the same logic for making horizontal matches as vertical ones. For simplicity, it concatenates the two boards into a single long one with a zero at the beginning, middle (to separate the two boards), and end for padding.

The second step is searching for possible matches, which you can see in the each_cons(3).any? block. The transformed rows (which are now 8-bit integers) are checked in (overlapping) groups of three rows (x, y, z) using bitwise arithmetic. Each group is checked to see if a match can be made in row y, either by shifting a piece in row y or by shifting a piece into y from x or z. Since there is a zero "row" before and after both the original and rotated boards' rows, we don't have to check if we're on the first or last row of a board.

If no matches were found, it continues to the next iteration.


Title: Is this square symmetrical?

Body:
JavaScript (ES6), 131 bytes

s=>[...`0101010`].map(c=>+c?``+b.reverse():`${b=b.map((s,i)=>s.replace(/./g,(_,j)=>b[j][i]))}`,b=a=s.match(/..../g)).includes(``+a)

17 bytes could be removed if you pass an array of 4 strings directly. I tried bit-twiddling (input in "0123301223011230" format) but that took me 199 bytes:

s=>[...'0101010'].map(c=>r=+c?r<<24&255<<24|r<<8&255<<16|r>>8&255<<8|r>>>24:r&0xc0300c03|r<<6&806093568|r<<12&3075<<16|r<<18&3<<24|r>>6&0xc0300c|r>>12&49200|r>>18&192,r=n=parseInt(s,4)|0).includes(n)


答:
C# 7,209 bytes: 6,643 bytes data + 566 bytes code (878 bytes unminimized)

Github repo is here: https://github.com/nbcarey/color-map

Color names are compressed in the data file using the FNV-32-1a hash as this hash algorithm is conventiently collision-free for this set of color names. So each color name is stored as 4 bytes.

Each color is stored as 3 bytes (1 each for red, green and blue). No magic there.

Consequently, each mapping of color name to RGV value occupies 7 bytes in the compressed file.

This is a one-line version of the FNV-32-1a hash (assuming a string containing only simple ASCII characters:

```<code>uint hash = Encoding.ASCII.GetBytes("royal blue")
            .Aggregate(0x811c9dc5u, (h,b)=> h=(h^b)*0x01000193u )
            ;
</code>```

This compressed data file is in the github repo at https://github.com/nbcarey/color-map/blob/master/color-map/hashed-color-map.dat

Here's the minimized code:

```<code>using System;using System.Collections.Generic;using System.IO;using System.Linq;using System.Text;namespace A{class B{static void Main(string[]C){var D = new Dictionary<uint,uint>();var E=File.ReadAllBytes("hashed-color-map.dat");for(int i=0;i<E.Length;i+=7){uint F=BitConverter.ToUInt32(E,i);uint G =(uint)(E[i+4]<<16|E[i+5]<<8|E[i+6]);D.Add(F,G);}foreach(var H in C){uint I;var J=D.TryGetValue(Encoding.ASCII.GetBytes(H).Aggregate(0x811c9dc5u,(h,b)=>h=(h^b)*0x01000193u),out I);var c=J?String.Format("#{0:X6}",I):"NOT FOUND";Console.WriteLine("{0}: {1}",c,H);}}}}
</code>```

And here's human-readable code:

```<code>using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace color_map
{
  class Program
  {
    static void Main( string[] args )
    {
      var map = new Dictionary<uint,uint>();

      var data = File.ReadAllBytes("hashed-color-map.dat");
      for ( int i = 0 ; i < data.Length ; i += 7 )
      {
        uint hash = BitConverter.ToUInt32(data,i);
        uint rgb   = (uint)( data[i+4] << 16 | data[i+5] << 8 | data[i+6] << 0 );
        map.Add(hash,rgb);
      }

      foreach (var cn in args )
      {
        uint rgb;
        var hit = map.TryGetValue(Encoding.ASCII.GetBytes(cn).Aggregate(0x811c9dc5u, (h,b)=> h=(h^b)*0x01000193u ), out rgb);
        var c = hit ? String.Format("#{0:X6}",rgb) : "NOT FOUND";
        Console.WriteLine("{0}: {1}", c , cn);
      }

    }
  }
}
</code>```

Title: Deciphering XKCD colors

Body:
Randall Munroe (author of XKCD) held a survey to give names to colors. The main outcome is a list of names for the 954 most common RGB monitor colors.

For ease of programming, here is the list in plain text: http://xkcd.com/color/rgb.txt. Beware, the first line is not data, but contains the license.

Write a program or function that takes a valid color name from above list as input and outputs the associated RGB color code. Your program does not have to handle invalid inputs in any defined manner.

Standard loopholes apply. Additionally, your answer must not use pre-defined (built-in or external) color code <-> color name maps. (This includes the linked list.) Shortest code in bytes wins. If you read from a file, the file's byte count must be included.

Examples:

```<code>dark peach -> #de7e5d
robin's egg blue -> #98eff9
pink/purple -> #ef1de7
</code>```

Body:
C# 7,209 bytes: 6,643 bytes data + 566 bytes code (878 bytes unminimized)

Github repo is here: https://github.com/nbcarey/color-map

Color names are compressed in the data file using the FNV-32-1a hash as this hash algorithm is conventiently collision-free for this set of color names. So each color name is stored as 4 bytes.

Each color is stored as 3 bytes (1 each for red, green and blue). No magic there.

Consequently, each mapping of color name to RGV value occupies 7 bytes in the compressed file.

This is a one-line version of the FNV-32-1a hash (assuming a string containing only simple ASCII characters:

uint hash = Encoding.ASCII.GetBytes("royal blue")
            .Aggregate(0x811c9dc5u, (h,b)=> h=(h^b)*0x01000193u )
            ;

This compressed data file is in the github repo at https://github.com/nbcarey/color-map/blob/master/color-map/hashed-color-map.dat

Here's the minimized code:

using System;using System.Collections.Generic;using System.IO;using System.Linq;using System.Text;namespace A{class B{static void Main(string[]C){var D = new Dictionary<uint,uint>();var E=File.ReadAllBytes("hashed-color-map.dat");for(int i=0;i<E.Length;i+=7){uint F=BitConverter.ToUInt32(E,i);uint G =(uint)(E[i+4]<<16|E[i+5]<<8|E[i+6]);D.Add(F,G);}foreach(var H in C){uint I;var J=D.TryGetValue(Encoding.ASCII.GetBytes(H).Aggregate(0x811c9dc5u,(h,b)=>h=(h^b)*0x01000193u),out I);var c=J?String.Format("#{0:X6}",I):"NOT FOUND";Console.WriteLine("{0}: {1}",c,H);}}}}

And here's human-readable code:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace color_map
{
  class Program
  {
    static void Main( string[] args )
    {
      var map = new Dictionary<uint,uint>();

      var data = File.ReadAllBytes("hashed-color-map.dat");
      for ( int i = 0 ; i < data.Length ; i += 7 )
      {
        uint hash = BitConverter.ToUInt32(data,i);
        uint rgb   = (uint)( data[i+4] << 16 | data[i+5] << 8 | data[i+6] << 0 );
        map.Add(hash,rgb);
      }

      foreach (var cn in args )
      {
        uint rgb;
        var hit = map.TryGetValue(Encoding.ASCII.GetBytes(cn).Aggregate(0x811c9dc5u, (h,b)=> h=(h^b)*0x01000193u ), out rgb);
        var c = hit ? String.Format("#{0:X6}",rgb) : "NOT FOUND";
        Console.WriteLine("{0}: {1}", c , cn);
      }

    }
  }
}


问:
A047841: Autobiographical numbers

Definition

Here is the process to describe a number:

For each number from 0 to 9 that is present in the number:

Write down the frequency of that digit and then the digit.

For example, for the number 10213223:

There is 1 occurrence of 0,

2 occurrences of 1,

3 occurrences of 2,

2 occurrences of 3.

Therefore, the number that describes 10213223 is 10213223 (10 from the first property, 21 from the second, etc.).

Note that the number of occurrences of a digit may be greater than 9.

Task

You are to print/output all numbers that describe themselves.

Specs

Standard loopholes apply, except that you are allowed to hardcode the output or store information related to the output in your program.

The numbers in the output can be in any order.

The numbers in the output are allowed to have duplicates.

You may use any separator, if you choose to print instead of output.

You are allowed to prefix and/or postfix output if you choose to print instead of output.

The separator and the prefix and the postfix may not contain any digits (U+0030 to U+0039).

The solution must compute in one day.

Full list (109 items)

```<code>22
10213223
10311233
10313314
10313315
10313316
10313317
10313318
10313319
21322314
21322315
21322316
21322317
21322318
21322319
31123314
31123315
31123316
31123317
31123318
31123319
31331415
31331416
31331417
31331418
31331419
31331516
31331517
31331518
31331519
31331617
31331618
31331619
31331718
31331719
31331819
1031223314
1031223315
1031223316
1031223317
1031223318
1031223319
3122331415
3122331416
3122331417
3122331418
3122331419
3122331516
3122331517
3122331518
3122331519
3122331617
3122331618
3122331619
3122331718
3122331719
3122331819
10413223241516
10413223241517
10413223241518
10413223241519
10413223241617
10413223241618
10413223241619
10413223241718
10413223241719
10413223241819
41322324151617
41322324151618
41322324151619
41322324151718
41322324151719
41322324151819
41322324161718
41322324161719
41322324161819
41322324171819
1051322314251617
1051322314251618
1051322314251619
1051322314251718
1051322314251719
1051322314251819
1051322325161718
1051322325161719
1051322325161819
1051322325171819
5132231425161718
5132231425161719
5132231425161819
5132231425171819
5132232516171819
106132231415261718
106132231415261719
106132231415261819
106132231426171819
106132231526171819
613223141526171819
1011112131415161718
1011112131415161719
1011112131415161819
1011112131415171819
1011112131416171819
1011112131516171819
1011112141516171819
1011113141516171819
1111213141516171819
10713223141516271819
101112213141516171819
</code>```

References

Autobiographical numbers: OEIS A047841

Biographical number: OEIS A047842

答:
gawk, 161 bytes

```<code>BEGIN{
    for(split("0 10 2 2 1 1 1 1",a);c=c<11;n=o=_){
        while(++$c>a[c]+1)$(c++)=0;
        for(i in a)n=$i?n$i i-1:n;
        for(i=10;i--;)if(d=gsub(i,i,n))o=d i o;
        if(n==o)print n
    }
}
</code>```

(line breaks and tabs for clarity)

It's a simple counter which uses the fact that each number has a limited occurrence. For instance is 0 no more than one time in any number, 1 no more than 11 times, 2 no more than 3 times ... and so on.

This way there are only 124415 numbers to check.

It then creates all numbers and checks their validity.

Completes in a few seconds.

Title: A047841: Autobiographical numbers

Body:
gawk, 161 bytes

BEGIN{
    for(split("0 10 2 2 1 1 1 1",a);c=c<11;n=o=_){
        while(++$c>a[c]+1)$(c++)=0;
        for(i in a)n=$i?n$i i-1:n;
        for(i=10;i--;)if(d=gsub(i,i,n))o=d i o;
        if(n==o)print n
    }
}

(line breaks and tabs for clarity)

It's a simple counter which uses the fact that each number has a limited occurrence. For instance is 0 no more than one time in any number, 1 no more than 11 times, 2 no more than 3 times ... and so on.

This way there are only 124415 numbers to check.

It then creates all numbers and checks their validity.

Completes in a few seconds.


问:
Reinvent the For loop
For loops are used extensively in many languages, but what would you do if no languages supported them?

Create a way to execute a basic for loop without using any repetition structures (for, foreach, while, do, etc).

The basic for loop that you need to replicate is set up like this

```<code>for(i=0;i<1000;i++)
</code>```

You must be able to replicate this without using repetition structures.  It must also execute code in your language that would be in the body of the loop.  Any form of eval is allowed, though it may not execute the for loop on its own.

You can test your code by having it print i with a space 100 times, add this test case to the end of your answer to verify your code with others.

There are no restrictions on what exactly it has to be, all it needs to do is replicate the for loop.

Winner will be decided based on upvotes at the time that it is chosen.

答:
Javascript - 86 chars

```<code>e=eval,n=function(j,k,c){if(e(j))e(k),c(),n(j,k,c)},f=function(i,j,k,c){e(i),n(j,k,c)}
</code>```

Maybe not the shortest javascript solution, but it replicates iterator declaration, iterator manipulation as well as a looping condition.

Example use case:

```<code>f('a = 0', 'a < 9', 'a++', function() {
    console.log(a);
});
</code>```

ContentLicense: CC BY-SA 2.5

Title: Reinvent the For loop

Body:
Javascript - 86 chars

e=eval,n=function(j,k,c){if(e(j))e(k),c(),n(j,k,c)},f=function(i,j,k,c){e(i),n(j,k,c)}

Maybe not the shortest javascript solution, but it replicates iterator declaration, iterator manipulation as well as a looping condition.

Example use case:

f('a = 0', 'a < 9', 'a++', function() {
    console.log(a);
});


答:
R, 80 bytes

Went for a recursive function doing bit operations.

```<code>f=function(a,b){d=bitwXor(a,b);e=bitwShiftL(bitwAnd(a,b),1);ifelse(!e,d,f(d,e))}
</code>```

Ungolfed:

```<code>f=function(a,b){
    d=bitwXor(a,b)            # xors a and b.(tells us bits that are 1 in end)
    f=bitwAnd(a,b)            # tells us which bits need to carry over 1
    e=bitwShiftL(e,1)         # carries those bits over
    if (e==0) d else f(d,e)   # if carried nothing, return xored bits.
}                             # otherwise, recursively call fn on xored and
                              # carried bits.
</code>```

It would have been shorter -- but R really does not intend for bit operations.

Body:
R, 80 bytes

Went for a recursive function doing bit operations.

f=function(a,b){d=bitwXor(a,b);e=bitwShiftL(bitwAnd(a,b),1);ifelse(!e,d,f(d,e))}

Ungolfed:

f=function(a,b){
    d=bitwXor(a,b)            # xors a and b.(tells us bits that are 1 in end)
    f=bitwAnd(a,b)            # tells us which bits need to carry over 1
    e=bitwShiftL(e,1)         # carries those bits over
    if (e==0) d else f(d,e)   # if carried nothing, return xored bits.
}                             # otherwise, recursively call fn on xored and
                              # carried bits.

It would have been shorter -- but R really does not intend for bit operations.


答:
Python 2.7 - 684 bytes

```<code>o=[22]
i=[[10213223,100096],[21322314,5],[31123314,5],[31331415,404],[1031223314,5],[3122331415,404],[10413223241516,303],[41322324151617,20202],[1051322314251617,202],[1051322325161718,10101],[5132231425161718,10101],[5132232516171819,0],[106132231415261718,101],[106132231426171819,0],[106132231526171819,0],[613223141526171819,0],[1011112131415161718,10101]]
l=[1011112131416171819,1011112131516171819,1011112141516171819,1011113141516171819,1111213141516171819,10713223141516271819,101112213141516171819]
for n in i:
 for x in range(n[0],n[0]+n[1]):
  m="";x=str(x)
  for v in range(10):
   v=str(v);c=x.count(v)
   if c!=0:
    m=m+str(c)+v
    if m==x:o.append(m)
o+=l
print o
</code>```

Kind of half hard coded and half computed. It takes the approach of splitting the numbers into groups of a manageable size with an upper and lower limit. The list i stores the lower limit and the difference between it and the upper limit as a nested list, All potential candidates are then checked within the range added to the output list o. The last 7 numbers are so far apart that it is cheaper to store them in their own list and add it at the end.

It currently runs in a couple of seconds and obviously increasing the group size would reduce the byte count but increase the run time. Not sure what it would come down to and still be within the one day limit.

Title: A047841: Autobiographical numbers

Body:
Definition

Here is the process to describe a number:

For each number from 0 to 9 that is present in the number:

Write down the frequency of that digit and then the digit.

For example, for the number 10213223:

There is 1 occurrence of 0,

2 occurrences of 1,

3 occurrences of 2,

2 occurrences of 3.

Therefore, the number that describes 10213223 is 10213223 (10 from the first property, 21 from the second, etc.).

Note that the number of occurrences of a digit may be greater than 9.

Task

You are to print/output all numbers that describe themselves.

Specs

Standard loopholes apply, except that you are allowed to hardcode the output or store information related to the output in your program.

The numbers in the output can be in any order.

The numbers in the output are allowed to have duplicates.

You may use any separator, if you choose to print instead of output.

You are allowed to prefix and/or postfix output if you choose to print instead of output.

The separator and the prefix and the postfix may not contain any digits (U+0030 to U+0039).

The solution must compute in one day.

Full list (109 items)

```<code>22
10213223
10311233
10313314
10313315
10313316
10313317
10313318
10313319
21322314
21322315
21322316
21322317
21322318
21322319
31123314
31123315
31123316
31123317
31123318
31123319
31331415
31331416
31331417
31331418
31331419
31331516
31331517
31331518
31331519
31331617
31331618
31331619
31331718
31331719
31331819
1031223314
1031223315
1031223316
1031223317
1031223318
1031223319
3122331415
3122331416
3122331417
3122331418
3122331419
3122331516
3122331517
3122331518
3122331519
3122331617
3122331618
3122331619
3122331718
3122331719
3122331819
10413223241516
10413223241517
10413223241518
10413223241519
10413223241617
10413223241618
10413223241619
10413223241718
10413223241719
10413223241819
41322324151617
41322324151618
41322324151619
41322324151718
41322324151719
41322324151819
41322324161718
41322324161719
41322324161819
41322324171819
1051322314251617
1051322314251618
1051322314251619
1051322314251718
1051322314251719
1051322314251819
1051322325161718
1051322325161719
1051322325161819
1051322325171819
5132231425161718
5132231425161719
5132231425161819
5132231425171819
5132232516171819
106132231415261718
106132231415261719
106132231415261819
106132231426171819
106132231526171819
613223141526171819
1011112131415161718
1011112131415161719
1011112131415161819
1011112131415171819
1011112131416171819
1011112131516171819
1011112141516171819
1011113141516171819
1111213141516171819
10713223141516271819
101112213141516171819
</code>```

References

Autobiographical numbers: OEIS A047841

Biographical number: OEIS A047842

Body:
Python 2.7 - 684 bytes

o=[22]
i=[[10213223,100096],[21322314,5],[31123314,5],[31331415,404],[1031223314,5],[3122331415,404],[10413223241516,303],[41322324151617,20202],[1051322314251617,202],[1051322325161718,10101],[5132231425161718,10101],[5132232516171819,0],[106132231415261718,101],[106132231426171819,0],[106132231526171819,0],[613223141526171819,0],[1011112131415161718,10101]]
l=[1011112131416171819,1011112131516171819,1011112141516171819,1011113141516171819,1111213141516171819,10713223141516271819,101112213141516171819]
for n in i:
 for x in range(n[0],n[0]+n[1]):
  m="";x=str(x)
  for v in range(10):
   v=str(v);c=x.count(v)
   if c!=0:
    m=m+str(c)+v
    if m==x:o.append(m)
o+=l
print o

Kind of half hard coded and half computed. It takes the approach of splitting the numbers into groups of a manageable size with an upper and lower limit. The list i stores the lower limit and the difference between it and the upper limit as a nested list, All potential candidates are then checked within the range added to the output list o. The last 7 numbers are so far apart that it is cheaper to store them in their own list and add it at the end.

It currently runs in a couple of seconds and obviously increasing the group size would reduce the byte count but increase the run time. Not sure what it would come down to and still be within the one day limit.


问:
Reverse a string while maintaining the capitalization in the same places
The goal here is to simply reverse a string, with one twist:

Keep the capitalization in the same places.

Example Input 1: Hello, Midnightas

Example Output 1: SathginDim ,olleh

Example Input 2: .Q

Exmaple Output 2: q.

Rules:

Output to STDOUT, input from STDIN

The winner will be picked 13th of July on GMT+3 12:00 (One week)

The input may only consist of ASCII symbols, making it easier for programs that do not use any encoding that contains non-ASCII characters.

Any punctuation ending up in a position where there was an upper-case letter must be ignored.

答:
Lua, 132 Bytes

```<code>function(s)o=""i=0 for m in s:gmatch(".")do n=s:sub(#s-i,#s-i)l=m:lower()o=o..(m==l and n:lower()or n:upper())i=i+1 end print(o)end
</code>```

There might be a better way to do this in lua, but I think this works.

Body:
Lua, 132 Bytes

function(s)o=""i=0 for m in s:gmatch(".")do n=s:sub(#s-i,#s-i)l=m:lower()o=o..(m==l and n:lower()or n:upper())i=i+1 end print(o)end

There might be a better way to do this in lua, but I think this works.


答:
Ruby, 64 bytes

Try it online!

```<code>->s{i=0;s.gsub(/./){c=s[i-=1];$&=~/[A-Z]/?c.upcase: c.downcase}}
</code>```

Title: Reverse a string while maintaining the capitalization in the same places

Body:
The goal here is to simply reverse a string, with one twist:

Keep the capitalization in the same places.

Example Input 1: Hello, Midnightas

Example Output 1: SathginDim ,olleh

Example Input 2: .Q

Exmaple Output 2: q.

Rules:

Output to STDOUT, input from STDIN

The winner will be picked 13th of July on GMT+3 12:00 (One week)

The input may only consist of ASCII symbols, making it easier for programs that do not use any encoding that contains non-ASCII characters.

Any punctuation ending up in a position where there was an upper-case letter must be ignored.

Body:
Ruby, 64 bytes

Try it online!

->s{i=0;s.gsub(/./){c=s[i-=1];$&=~/[A-Z]/?c.upcase: c.downcase}}


答:
Python 2, 66 bytes

f=lambda n:1/n or f(n/2)+n%2*f(-~n/2)
lambda n:`f(n)`+'/'+`f(n+1)`
```

Uses the recursive formula.

Body:
The Stern-Brocot sequence is a Fibonnaci-like sequence which can be constructed as follows:

Initialise the sequence with s(1) = s(2) = 1

Set counter n = 1

Append s(n) + s(n+1) to the sequence

Append s(n+1) to the sequence

Increment n, return to step 3

This is equivalent to:

Amongst other properties, the Stern-Brocot sequence can be used to generate every possible positive rational number. Every rational number will be generated exactly once, and it will always appear in its simplest terms; for example, 1/3 is the 4th rational number in the sequence, but the equivalent numbers 2/6, 3/9 etc won't appear at all.

We can define the nth rational number as r(n) = s(n) / s(n+1), where s(n) is the nth Stern-Brocot number, as described above.

Your challenge is to write a program or function which will output the nth rational number generated using the Stern-Brocot sequence.

The algorithms described above are 1-indexed; if your entry is 0-indexed, please state in your answer

The algorithms described are for illustrative purposes only, the output can be derived in any way you like (other than hard-coding)

Input can be via STDIN, function parameters, or any other reasonable input mechanism

Ouptut can be to STDOUT, console, function return value, or any other reasonable output stream

Output must be as a string in the form a/b, where a and b are the relevant entries in the Stern-Brocot sequence. Evaluating the fraction before output is not permissable. For example, for input 12, output should be 2/5, not 0.4.

Standard loopholes are disallowed

This is code-golf, so shortest answer in bytes will win.

Test cases

The test cases here are 1-indexed.

```<code>n    r(n)
--  ------
1    1/1
2    1/2
3    2/1
4    1/3
5    3/2
6    2/3
7    3/1
8    1/4
9    4/3
10   3/5
11   5/2
12   2/5
13   5/3
14   3/4
15   4/1
16   1/5
17   5/4
18   4/7
19   7/3
20   3/8
50   7/12
100  7/19
1000 11/39
</code>```

OEIS entry: A002487

Excellent Numberphile video discussing the sequence: Infinite Fractions

Body:
Python 2, 66 bytes

f=lambda n:1/n or f(n/2)+n%2*f(-~n/2)
lambda n:`f(n)`+'/'+`f(n+1)`

Uses the recursive formula.


答:
PHP, 5014 bytes

Not the best there is but it's late and I need to get some sleep. :-)

The beauty of PHP is that you can inline payload data into your script and read the file itself, so the script is self-sufficient. Just download it, run it and it will prompt for the color name.

```<code><?$f=fopen(__FILE__,r);fseek($f,269);$m=stream_get_contents($f);while($l<4745){$d.=str_pad(dechex(ord($m{$l++})),2,0);}$h=sha1(trim(fgets(STDIN)));$k=substr($h,0,3).$h{16};for($i=0;$i<9490;$i+=10){if($k==substr($d,$i,4)){echo'#'.substr($d,$i+4,6);}};__HALT_COMPILER();
$¥¬ÂÙóûV®W}a²™nÂÀ¨ÿÄ°iØOûO‰E…&@p²? xÔÿÿuAe«|Šü•.¤üüÁÿ¥£‘F²8€?šL…8^›Šlï´5m‘Ù›‚´
[...MORE BINARY DATA...]
</code>```

The basic trick here is to hash the color names and generate minimally identifying substrings of that hash. I found that 4 chars of a SHA1 hash are enough, the first 3 and the 17th to uniquely identify all those colors. The key is in binary as well as the color code, which is conveniently one byte per color channel. So every entry takes up 5 bytes, which makes for 5 x 949 = 4745 bytes payload (the magic number you see in the code).

Compression didn't help very much, bzip2, LZMA all created bigger files so without any further tricks, this is as compressed as it goes for this approach.

Title: Deciphering XKCD colors

Body:
PHP, 5014 bytes

Not the best there is but it's late and I need to get some sleep. :-)

The beauty of PHP is that you can inline payload data into your script and read the file itself, so the script is self-sufficient. Just download it, run it and it will prompt for the color name.

<?$f=fopen(__FILE__,r);fseek($f,269);$m=stream_get_contents($f);while($l<4745){$d.=str_pad(dechex(ord($m{$l++})),2,0);}$h=sha1(trim(fgets(STDIN)));$k=substr($h,0,3).$h{16};for($i=0;$i<9490;$i+=10){if($k==substr($d,$i,4)){echo'#'.substr($d,$i+4,6);}};__HALT_COMPILER();
$¥¬ÂÙóûV®W}a²™nÂÀ¨ÿÄ°iØOûO‰E…&@p²? xÔÿÿuAe«|Šü•.¤üüÁÿ¥£‘F²8€?šL…8^›Šlï´5m‘Ù›‚´
[...MORE BINARY DATA...]

The basic trick here is to hash the color names and generate minimally identifying substrings of that hash. I found that 4 chars of a SHA1 hash are enough, the first 3 and the 17th to uniquely identify all those colors. The key is in binary as well as the color code, which is conveniently one byte per color channel. So every entry takes up 5 bytes, which makes for 5 x 949 = 4745 bytes payload (the magic number you see in the code).

Compression didn't help very much, bzip2, LZMA all created bigger files so without any further tricks, this is as compressed as it goes for this approach.