答:
PowerShell 26 bytes

```<code>process{if($_%2){break}$_}
</code>```

Explanation

```<code>process{if($_%2){break}$_}
process{                 } # runs the script block once per item in the passed parameter
        if($_%2){break}    # if odd, break out of process{}
                       $_  # implicit output
</code>```

Testing (save as evenodd.ps1):

```<code>PS> 42,14,42,2324 | .\evenodd.ps1
42
14
42
2324
PS> 7,14,42 | .\evenodd.ps1
PS> 171480372,13,14,42 | .\evenodd.ps1
171480372
</code>```

Title: Implement Takewhile

Body:
Introduction and Credit

Today without a fancy prelude: Please implement takewhile.

A variation of this (on a non-trivial data structure) was an assignment at my university functional programming course. This assignment is now closed and has been discussed in class and I have my professor's permission to post it here (I asked explicitly).

Specification

Input

The input will be a list (or your language's equivalent concept) of positive integers.

Output

The output should be a list (or your language's equivalent concept) of positive integers.

What to do?

Your task is to implement takewhile (language built-ins are allowed) with the predicate that the number under consideration is even (to focus on takewhile).

So you iterate over the list from start to end and while the condition (is even) holds, you copy to the output-list and as soon as you hit an element that doesn't make the condition true, you abort the operation and output (a step-by-step example is below). This higher-order functionality is also called takeWhile (takewhile).

Potential corner cases

The order of the output list compared to the input list may not be changed, e.g. [14,42,2] may not become [42,14].

The empty list is a valid in- and output.

Who wins?

This is code-golf so the shortest answer in bytes wins!

Standard rules apply of course.

Test Vectors

```<code>[14, 42, 2324, 97090, 4080622, 171480372] -> [14, 42, 2324, 97090, 4080622, 171480372]
[42, 14, 42, 2324] -> [42, 14, 42, 2324]
[7,14,42] -> []
[] -> []
[171480372, 13, 14, 42] -> [171480372]
[42, 14, 42, 43, 41, 4080622, 171480372] -> [42, 14, 42]
</code>```

Step-by-Step Example

```<code>Example Input: [42, 14, 42, 43, 41, 4080622, 171480372]

Consider first element: 42
42 is even (21*2)
Put 42 into output list, output list is now [42]

Consider second element: 14
14 is even (7*2)
Put 14 into output list, output list is now [42,14]

Consider third element: 42
42 is even (21*2)
Put 42 into output list, output list is now [42,14,42]

Consider fourth element: 43
43 is not even (2*21+1)
Drop 43 and return the current output list

return [42,14,42]
</code>```

Body:
PowerShell 26 bytes

process{if($_%2){break}$_}

Explanation

process{if($_%2){break}$_}
process{                 } # runs the script block once per item in the passed parameter
        if($_%2){break}    # if odd, break out of process{}
                       $_  # implicit output

Testing (save as evenodd.ps1):

PS> 42,14,42,2324 | .\evenodd.ps1
42
14
42
2324
PS> 7,14,42 | .\evenodd.ps1
PS> 171480372,13,14,42 | .\evenodd.ps1
171480372


问:
Score a game of Yahtzee
For each of the 13 rows of a Yahtzee scoresheet you are given (from stdin)
a space separated list of 5 numbers (dice).
Your task is to calculate the score for each line and output the Grand Total of the game.

Example

Input and how to interpret it:

```<code>Input       Box              Score
6 1 4 1 3   Aces              2
3 2 2 1 2   Twos              6
6 3 2 3 3   Threes            9
4 2 3 6 5   Fours             4
6 3 5 5 1   Fives            10
1 5 6 5 6   Sixes            12
            Bonus             -
4 2 4 4 1   3 of a kind      15
2 2 3 2 4   4 of a kind       -
3 2 2 2 3   Full house       25
1 3 1 6 1   Small straight    -
2 5 4 6 3   Large straight   40
2 2 2 2 2   Yahtzee          50
5 5 4 5 2   Chance           21
            Grand Total     194
</code>```

We will disregard the Yahtzee Bonus and Joker rules, and only sum up the scores from the Upper and Lower Section and the Bonus in the Upper Section. If in doubt, refer to these rules.

May the shortest code win!

答:
Python 364

```<code>S=sum;R=range;D=[map(int,raw_input().split())for i in R(13)];s=S(x for i in R(6)for x in D[i]if x==i+1)
for i in R(2):d=D[6+i];s+=[0,S(d)][max(map(d.count,d))>2+i];d=sorted(set(D[9+i]));s+=[0,30+i*10]['1, 1, 1'+', 1'*i in`[d[x+1]-d[x]for x in R(len(d)-1)]`]
e=D[8];a=map(e.count,e);d=D[11];print s+S(D[12])+[0,50][d.count(d[0])==5]+[0,25][2in a and 3in a or 5in a]
</code>```

As requested, input is on stdin:

```<code>$ yScore.py < dice.txt
194
</code>```

If the data could be preloaded into a list, as some other solutions have done, I could remove 62 characters to get to 302.

ContentLicense: CC BY-SA 3.0

Title: Score a game of Yahtzee

Body:
Python 364

S=sum;R=range;D=[map(int,raw_input().split())for i in R(13)];s=S(x for i in R(6)for x in D[i]if x==i+1)
for i in R(2):d=D[6+i];s+=[0,S(d)][max(map(d.count,d))>2+i];d=sorted(set(D[9+i]));s+=[0,30+i*10]['1, 1, 1'+', 1'*i in`[d[x+1]-d[x]for x in R(len(d)-1)]`]
e=D[8];a=map(e.count,e);d=D[11];print s+S(D[12])+[0,50][d.count(d[0])==5]+[0,25][2in a and 3in a or 5in a]

As requested, input is on stdin:

$ yScore.py < dice.txt
194

If the data could be preloaded into a list, as some other solutions have done, I could remove 62 characters to get to 302.


问:
Truncate consecutive character runs to n length

The challenge

Given an input string, and an integer n - truncate any runs of consecutive characters to a maximum of n length. The characters can be anything, including special characters. The function should be case sensitive, and n can range from 0 to infinity.

Example inputs/outputs:

```<code>f("aaaaaaabbbccCCCcc", 2) //"aabbccCCcc"
f("aaabbbc", 1) //"abc"
f("abcdefg", 0) //""
f("aaaaaaabccccccccCCCCCC@", 4) //"aaaabccccCCCC@"
</code>```

Scoring

The scoring is based on the number of bytes used.
Thus

```<code>function f(s,n){return s.replace(new RegExp("(.)\\1{"+n+",}","g"),function(x){return x.substr(0, n);});}
</code>```

would be 104 points.

Happy golfing!

Edit: removed language restriction, but I still would love to see javascript answers

答:
Perl 6, <s> 38 </s> 36 bytes

<s>->$_,$n {S:g/(.)$0**{$n..*}/{$0 x$n}/}</s>
->$_,\n{S:g/(.)$0**{n..*}/{$0 x n}/}```

<h3>Explanation:</h3>

<pre class="lang-perl6 prettyprint-override"><code>-> $_, \n { # pointy block lambda
  # regex replace ( return without modifying variant )
  # globally
  S:global /
    # a char
    (.)
    # followed by ｢n｣ or more identical chars
    $0 ** { n .. * }
  /{
    # repeat char ｢n｣ times
    $0 x n
  }/
}
</code>```

Test:

#! /usr/bin/env perl6
use v6.c;
use Test;

my &truncate-char-runs-to = ->$_,\n{S:g/(.)$0**{n..*}/{$0 x n}/}

my @tests = (
  ("aaaaaaabbbccCCCcc", 2) => "aabbccCCcc",
  ("aaabbbc", 1) => "abc",
  ("abcdefg", 0) => "",
  ("aaaaaaabccccccccCCCCCC@", 4) => "aaaabccccCCCC@",
);

plan +@tests;

for @tests -> $_ ( :key(@input), :value($expected) ) {
  is truncate-char-runs-to(|@input), $expected, qq'("@input[0]", @input[1]) => "$expected"';
}
```

<pre class="lang-perl6 prettyprint-override"><code>1..4
ok 1 - ("aaaaaaabbbccCCCcc", 2) => "aabbccCCcc"
ok 2 - ("aaabbbc", 1) => "abc"
ok 3 - ("abcdefg", 0) => ""
ok 4 - ("aaaaaaabccccccccCCCCCC@", 4) => "aaaabccccCCCC@"
</code>```

Body:
Perl 6, <s> 38 </s> 36 bytes

<s>->$_,$n {S:g/(.)$0**{$n..*}/{$0 x$n}/}</s>
->$_,\n{S:g/(.)$0**{n..*}/{$0 x n}/}

Explanation:

-> $_, \n { # pointy block lambda
  # regex replace ( return without modifying variant )
  # globally
  S:global /
    # a char
    (.)
    # followed by ｢n｣ or more identical chars
    $0 ** { n .. * }
  /{
    # repeat char ｢n｣ times
    $0 x n
  }/
}

Test:

#! /usr/bin/env perl6
use v6.c;
use Test;

my &truncate-char-runs-to = ->$_,\n{S:g/(.)$0**{n..*}/{$0 x n}/}

my @tests = (
  ("aaaaaaabbbccCCCcc", 2) => "aabbccCCcc",
  ("aaabbbc", 1) => "abc",
  ("abcdefg", 0) => "",
  ("aaaaaaabccccccccCCCCCC@", 4) => "aaaabccccCCCC@",
);

plan +@tests;

for @tests -> $_ ( :key(@input), :value($expected) ) {
  is truncate-char-runs-to(|@input), $expected, qq'("@input[0]", @input[1]) => "$expected"';
}

1..4
ok 1 - ("aaaaaaabbbccCCCcc", 2) => "aabbccCCcc"
ok 2 - ("aaabbbc", 1) => "abc"
ok 3 - ("abcdefg", 0) => ""
ok 4 - ("aaaaaaabccccccccCCCCCC@", 4) => "aaaabccccCCCC@"


答:
Javascript ES6, <s>60</s> <s>54</s> <s>55</s> 43 bytes

-12 bytes thanks to @TestSubject06 and @Downgoat

```<code>(s,n)=>s.replace(/(.)\1*/g,x=>x.slice(0,n))
</code>```

Example runs:

```<code>f("aaaaaaabbbccCCCcc"      , 2) -> "aabbccCCcc"
f("aaabbbc"                , 1) -> "abc"
f("abcdefg"                , 0) -> ""
f("aaaaaaabccccccccCCCCCC@", 4) -> "aaaabccccCCCC@"
f("a"                      , 1) -> "a"
</code>```

Title: Truncate consecutive character runs to n length

Body:
The challenge

Given an input string, and an integer n - truncate any runs of consecutive characters to a maximum of n length. The characters can be anything, including special characters. The function should be case sensitive, and n can range from 0 to infinity.

Example inputs/outputs:

```<code>f("aaaaaaabbbccCCCcc", 2) //"aabbccCCcc"
f("aaabbbc", 1) //"abc"
f("abcdefg", 0) //""
f("aaaaaaabccccccccCCCCCC@", 4) //"aaaabccccCCCC@"
</code>```

Scoring

The scoring is based on the number of bytes used.
Thus

```<code>function f(s,n){return s.replace(new RegExp("(.)\\1{"+n+",}","g"),function(x){return x.substr(0, n);});}
</code>```

would be 104 points.

Happy golfing!

Edit: removed language restriction, but I still would love to see javascript answers

Body:
Javascript ES6, <s>60</s> <s>54</s> <s>55</s> 43 bytes

-12 bytes thanks to @TestSubject06 and @Downgoat

(s,n)=>s.replace(/(.)\1*/g,x=>x.slice(0,n))

Example runs:

f("aaaaaaabbbccCCCcc"      , 2) -> "aabbccCCcc"
f("aaabbbc"                , 1) -> "abc"
f("abcdefg"                , 0) -> ""
f("aaaaaaabccccccccCCCCCC@", 4) -> "aaaabccccCCCC@"
f("a"                      , 1) -> "a"


问:
Print a bunch of uninteresting numbers!
An uninteresting number (which I totally didn't make up only for this challenge) is created like this:

Take a positive integer N

Create a new number O by adding the digits of N at the end of N

The final uninteresting number is O*N

For example for N=12:

O = 1212

O*N = 1212 * 12

Final number is 14544

Input

A positive integer N (N > 0) or your language's equivalent. You don't have to catch incorrect input.

Output

The corresponding uninteresting number.

Test cases

```<code>  1 -> 11
  2 -> 44
  3 -> 99
 10 -> 10100
174 -> 30306276
</code>```

Scoring

Shortest Code in Bytes wins.

答:
Ruby, 22 Bytes

```<code>->n{(n*2).to_i*n.to_i}
</code>```

Takes input as a string. Double the string, and then multiply it by the input, both as integers

Title: Print a bunch of uninteresting numbers!

Body:
Ruby, 22 Bytes

->n{(n*2).to_i*n.to_i}

Takes input as a string. Double the string, and then multiply it by the input, both as integers


答:
gs2, 6 bytes

Encoded in CP437:

```<code>╠c╨<ΘΣ
</code>```

This is an anonymous function (block) that expect a number on top of the stack and a string below it.

```<code>     Σ   Wrap previous five bytes in a block:
╠          Pop number into register A.
 c         Group string.
    Θ      Map previous two bytes over each group:
  ╨<         Take the first A bytes.
</code>```

Try it online. (The code here is lines, dump, read number, [the answer], run-block.)

Body:
gs2, 6 bytes

Encoded in CP437:

╠c╨<ΘΣ

This is an anonymous function (block) that expect a number on top of the stack and a string below it.

     Σ   Wrap previous five bytes in a block:
╠          Pop number into register A.
 c         Group string.
    Θ      Map previous two bytes over each group:
  ╨<         Take the first A bytes.

Try it online. (The code here is lines, dump, read number, [the answer], run-block.)


答:
Python 2, 52 bytes

lambda s,n:reduce(lambda r,c:r+c*(r[-n:]!=c*n),s,'')
```

<p>Written out as a program (54 bytes):</p>

<pre class="lang-python prettyprint-override"><code>s,n=input();r=''
for c in s:r+=c*(r[-n:]!=c*n)
print r
</code>```

Iterates through the input string s, appending each character to the output string r unless that last n characters of r are that character.

I though this would fail n==0 because r[-0:] is not the last 0 characters (empty string), but the entire string. But, it works because the string remains empty, so its keeps matching the 0-character string.

A recursive lambda gave 56 because of the repetition

f=lambda s,n:s and s[:f(s[1:],n)[:n]!=s[0]*n]+f(s[1:],n)
```

An alternate strategy to keep a counter i of repeats of the last character also turned out longer than just checking the last n characters directly.

Body:
Python 2, 52 bytes

lambda s,n:reduce(lambda r,c:r+c*(r[-n:]!=c*n),s,'')

Written out as a program (54 bytes):

s,n=input();r=''
for c in s:r+=c*(r[-n:]!=c*n)
print r

Iterates through the input string s, appending each character to the output string r unless that last n characters of r are that character.

I though this would fail n==0 because r[-0:] is not the last 0 characters (empty string), but the entire string. But, it works because the string remains empty, so its keeps matching the 0-character string.

A recursive lambda gave 56 because of the repetition

f=lambda s,n:s and s[:f(s[1:],n)[:n]!=s[0]*n]+f(s[1:],n)

An alternate strategy to keep a counter i of repeats of the last character also turned out longer than just checking the last n characters directly.


问:
Generate a Stack Exchange Favicon
Do you recognize the PPCG logo?
it looks like this, when you do an ascii art of it.

```<code>+---+
|PCG|
+---+
   v
</code>```

Now, In this Code Golf, You will make a code, that makes logos for other sites, similar to the PPCG logo.

What You should do

The "Shortened" string will be the string, with all upper case letters and numbers in the input string.(Which would be PPCG when the input string is Programming Puzzles & Code Golf)

The "Box" (

```<code>+---+
|   |
+---+
   v
</code>```

)
should fit the Shortened string perfectly.(No bigger or smaller)

Also the v part should be exactly 1 down and 1 left to the down right +.

Then output the box which has the shortened string in it.

Example

Stack Overflow:

```<code>+--+
|SO|
+--+
  v
</code>```

Area 51:

```<code>+---+
|A51|
+---+
   v
</code>```

Rules

You may assume that the input contains at least one digit or upper case letter.

Standard code-golf rules apply.

答:
Jolf, 35 bytes

```<code>Ά+,Alγ/x"[^A-Z0-9]"1'+'-'|γS*lγ" 'v
</code>```

I need a shorter way to remove all but caps & numbers...

Title: Generate a Stack Exchange Favicon

Body:
Jolf, 35 bytes

Ά+,Alγ/x"[^A-Z0-9]"1'+'-'|γS*lγ" 'v

I need a shorter way to remove all but caps & numbers...


问:
The Camouflage Color Changing Chameleon Challenge
Chameleon challenges are a bad thing, apparently. Too bad, chameleons are beautiful creatures. Time for a change!

As we all know, many chameleons posses a remarkable ability to blend in with their surroundings by changing the color of their skin. Which is also the objective of this challenge.

Challenge

Imagine a square of nine pixels. Eight pixels are the surroundings. At the center is the chameleon.

Like this:

The chameleon naturally tries to blend in with its surroundings. It does so by changing its color to the average of that of the surrounding pixels. So, in this case, the chameleon would change its color to .

Objective

Given the colors of the surrounding pixels, output the color of the chameleon.

The color of the chameleon is defined as the total of all red, green and blue in the pixels ÷ 8.

Input

An array of color values for the eight surrounding pixels, starting at the top left and continuing clockwise, like this:

```<code>[[<red>,<green>,<blue>],[<red>,<green>,<blue>],[<red>,<green>,<blue>],[<red>,<green>,<blue>],[<red>,<green>,<blue>],[<red>,<green>,<blue>],[<red>,<green>,<blue>],[<red>,<green>,<blue>]]
</code>```

You may choose to receive input in a different form, as long as it consists of eight triples of decimal numbers 0-255.

If you receive input in a different form, numbers must either be of a consistent length or have a non-numeric separator between them. Triples must have a separating character unless they are 0-padded to 9 digits. (E.g. 044200255044200255044200255044200255044200255044200255044200255044200255 is valid, so are 44 200 255 44 200 255 44 200 255 44 200 255 44 200 255 44 200 255 44 200 255 44 200 255 and 44?200?255$44?200?255$44?200?255$44?200?255$44?200?255$44?200?255$44?200?255$44?200?255, but 4420025544200255442002554420025544200255442002554420025544200255 is not.)

Output

An array / string / etc. containing the colors of the center pixel (in decimal), like this:

```<code>[<red>,<green>,<blue>]
</code>```

In case you output something other than an array: Numbers must either be of a consistent length or have a non-numeric separator between them. (E.g. 044200255 is valid, so is 44 200 255, but 44200255 is not.)

The numbers may not contain decimal points, so e.g. 44.0 200 255.0 is invalid.

Rounding

Output must be rounded to the nearest integer. (Halves must be rounded up.) E.g., if the sum of all red is 1620, you must output 203, not 202 or 202.5.

Examples

Pictures are for illustration only. The middle pixel is the output, the surrounding pixels are the input.

Input:

```<code>[[200,200,200],[200,200,200],[200,200,200],[200,200,200],[200,200,200],[200,200,200],[200,200,200],[200,200,200]]
</code>```

Output:

```<code>[200,200,200]
</code>```

Input:

```<code>[[0,0,0],[255,255,255],[0,0,0],[255,255,255],[255,255,255],[0,0,0],[255,255,255],[0,0,0]]
</code>```

Output:

```<code>[128,128,128]
</code>```

Input:

```<code>[[0,200,200],[200,0,200],[200,200,0],[60,200,0],[200,0,200],[0,200,220],[2,200,0],[0,0,0]]
</code>```

Output:

```<code>[83,125,103]
</code>```

Input:

```<code>[[0,56,58],[65,0,200],[33,200,0],[60,33,0],[98,0,200],[0,28,220],[2,200,0],[99,0,5]]
</code>```

Output:

```<code>[45,65,85]
</code>```

Submissions can be a full program or a function. Standard I/O and loophole rules apply.

答:
JavaScript, 75 64 55 bytes

```<code>a=>a.reduce((p,c)=>p.map((e,i)=>e+c[i])).map(x=>x+4>>3)
</code>```

A JavaScript answer to get you started.

Edit: Saved 11 bytes thanks to Dendrobium, and another  9 thanks to Neil.

Body:
JavaScript, 75 64 55 bytes

a=>a.reduce((p,c)=>p.map((e,i)=>e+c[i])).map(x=>x+4>>3)

A JavaScript answer to get you started.

Edit: Saved 11 bytes thanks to Dendrobium, and another  9 thanks to Neil.


答:
Pyth, 8 bytes

```<code>m.R.Od0C
</code>```

Test suite.

```<code>m.R.Od0C     input: Q
m.R.Od0CQ    implicit arguments
        Q    input
       C     transpose
m    d       for each:
   .O            take average
 .R   0          round off
</code>```

Title: The Camouflage Color Changing Chameleon Challenge

Body:
Chameleon challenges are a bad thing, apparently. Too bad, chameleons are beautiful creatures. Time for a change!

As we all know, many chameleons posses a remarkable ability to blend in with their surroundings by changing the color of their skin. Which is also the objective of this challenge.

Challenge

Imagine a square of nine pixels. Eight pixels are the surroundings. At the center is the chameleon.

Like this:

The chameleon naturally tries to blend in with its surroundings. It does so by changing its color to the average of that of the surrounding pixels. So, in this case, the chameleon would change its color to .

Objective

Given the colors of the surrounding pixels, output the color of the chameleon.

The color of the chameleon is defined as the total of all red, green and blue in the pixels ÷ 8.

Input

An array of color values for the eight surrounding pixels, starting at the top left and continuing clockwise, like this:

```<code>[[<red>,<green>,<blue>],[<red>,<green>,<blue>],[<red>,<green>,<blue>],[<red>,<green>,<blue>],[<red>,<green>,<blue>],[<red>,<green>,<blue>],[<red>,<green>,<blue>],[<red>,<green>,<blue>]]
</code>```

You may choose to receive input in a different form, as long as it consists of eight triples of decimal numbers 0-255.

If you receive input in a different form, numbers must either be of a consistent length or have a non-numeric separator between them. Triples must have a separating character unless they are 0-padded to 9 digits. (E.g. 044200255044200255044200255044200255044200255044200255044200255044200255 is valid, so are 44 200 255 44 200 255 44 200 255 44 200 255 44 200 255 44 200 255 44 200 255 44 200 255 and 44?200?255$44?200?255$44?200?255$44?200?255$44?200?255$44?200?255$44?200?255$44?200?255, but 4420025544200255442002554420025544200255442002554420025544200255 is not.)

Output

An array / string / etc. containing the colors of the center pixel (in decimal), like this:

```<code>[<red>,<green>,<blue>]
</code>```

In case you output something other than an array: Numbers must either be of a consistent length or have a non-numeric separator between them. (E.g. 044200255 is valid, so is 44 200 255, but 44200255 is not.)

The numbers may not contain decimal points, so e.g. 44.0 200 255.0 is invalid.

Rounding

Output must be rounded to the nearest integer. (Halves must be rounded up.) E.g., if the sum of all red is 1620, you must output 203, not 202 or 202.5.

Examples

Pictures are for illustration only. The middle pixel is the output, the surrounding pixels are the input.

Input:

```<code>[[200,200,200],[200,200,200],[200,200,200],[200,200,200],[200,200,200],[200,200,200],[200,200,200],[200,200,200]]
</code>```

Output:

```<code>[200,200,200]
</code>```

Input:

```<code>[[0,0,0],[255,255,255],[0,0,0],[255,255,255],[255,255,255],[0,0,0],[255,255,255],[0,0,0]]
</code>```

Output:

```<code>[128,128,128]
</code>```

Input:

```<code>[[0,200,200],[200,0,200],[200,200,0],[60,200,0],[200,0,200],[0,200,220],[2,200,0],[0,0,0]]
</code>```

Output:

```<code>[83,125,103]
</code>```

Input:

```<code>[[0,56,58],[65,0,200],[33,200,0],[60,33,0],[98,0,200],[0,28,220],[2,200,0],[99,0,5]]
</code>```

Output:

```<code>[45,65,85]
</code>```

Submissions can be a full program or a function. Standard I/O and loophole rules apply.

Body:
Pyth, 8 bytes

m.R.Od0C

<a href="http://pyth.herokuapp.com/?code=m.R.Od0C&test_suite=1&test_suite_input=%5B%5B200%2C200%2C200%5D%2C%5B200%2C200%2C200%5D%2C%5B200%2C200%2C200%5D%2C%5B200%2C200%2C200%5D%2C%5B200%2C200%2C200%5D%2C%5B200%2C200%2C200%5D%2C%5B200%2C200%2C200%5D%2C%5B200%2C200%2C200%5D%5D%0A%5B%5B0%2C0%2C0%5D%2C%5B255%2C255%2C255%5D%2C%5B0%2C0%2C0%5D%2C%5B255%2C255%2C255%5D%2C%5B255%2C255%2C255%5D%2C%5B0%2C0%2C0%5D%2C%5B255%2C255%2C255%5D%2C%5B0%2C0%2C0%5D%5D%0A%5B%5B0%2C200%2C200%5D%2C%5B200%2C0%2C200%5D%2C%5B200%2C200%2C0%5D%2C%5B60%2C200%2C0%5D%2C%5B200%2C0%2C200%5D%2C%5B0%2C200%2C220%5D%2C%5B2%2C200%2C0%5D%2C%5B0%2C0%2C0%5D%5D&debug=0" rel="nofollow">Test suite.

m.R.Od0C     input: Q
m.R.Od0CQ    implicit arguments
        Q    input
       C     transpose
m    d       for each:
   .O            take average
 .R   0          round off


答:
Jelly, 5 bytes

```<code>S+4:8
</code>```

Test suite. (Slightly modified so as to verify all testcases at once.)

```<code>S+4:8
S      sum (vectorized)
 +4    add 4
   :8  floor division by 8
</code>```

Body:
Jelly, 5 bytes

S+4:8

Test suite. (Slightly modified so as to verify all testcases at once.)

S+4:8
S      sum (vectorized)
 +4    add 4
   :8  floor division by 8


答:
Python, 38 bytes

lambda l:[sum(r)+4>>3for r in zip(*l)]
```

Rounds the average (towards the nearest integer, with halves rounding up) by adding 4 to the sum, then floor-dividing by 8 via the bit-shift >>3.

Body:
Python, 38 bytes

lambda l:[sum(r)+4>>3for r in zip(*l)]

Rounds the average (towards the nearest integer, with halves rounding up) by adding 4 to the sum, then floor-dividing by 8 via the bit-shift >>3.


答:
SAS, 32 Bytes

```<code>%macro x(a);%eval(&a&a*&a)%mend;
</code>```

Macro language, so no string/numeric concept.  Function style (so this doesn't return the value to the screen, that's your job, this just returns the value).

Examples:

```<code>86   %put %x(1);
11
87   %put %x(12);
14544
</code>```

Title: Print a bunch of uninteresting numbers!

Body:
An uninteresting number (which I totally didn't make up only for this challenge) is created like this:

Take a positive integer N

Create a new number O by adding the digits of N at the end of N

The final uninteresting number is O*N

For example for N=12:

O = 1212

O*N = 1212 * 12

Final number is 14544

Input

A positive integer N (N > 0) or your language's equivalent. You don't have to catch incorrect input.

Output

The corresponding uninteresting number.

Test cases

```<code>  1 -> 11
  2 -> 44
  3 -> 99
 10 -> 10100
174 -> 30306276
</code>```

Scoring

Shortest Code in Bytes wins.

Body:
SAS, 32 Bytes

%macro x(a);%eval(&a&a*&a)%mend;

Macro language, so no string/numeric concept.  Function style (so this doesn't return the value to the screen, that's your job, this just returns the value).

Examples:

86   %put %x(1);
11
87   %put %x(12);
14544


问:
Duplicate & switch case
The goal is, having taken a string as input, duplicate each latin letter and "toggle" its case (i.e. uppercase becomes lowercase and vice-versa).

Example inputs & outputs:

```<code>Input      Output
bad        bBaAdD
Nice       NniIcCeE
T e S t    Tt eE Ss tT
s E t      sS Ee tT
1!1!1st!   1!1!1sStT!
n00b       nN00bB
(e.g.)     (eE.gG.)
H3l|@!     Hh3lL|@!
</code>```

The input consists of printable ASCII symbols.

You shouldn't duplicate non-latin letters, numbers, special chars.

答:
Pyth, 7 bytes

```<code>sm{+dr2
</code>```

Test suite.

```<code>sm{+dr2    input: Q
sm{+dr2dQ  implicit arguments

        Q  input
 m         for each character as d:
     r2d       swapcase
   +d          prepend d
  {            deduplicate
s          join as string
</code>```

Title: Duplicate & switch case

Body:
Pyth, 7 bytes

sm{+dr2

Test suite.

sm{+dr2    input: Q
sm{+dr2dQ  implicit arguments

        Q  input
 m         for each character as d:
     r2d       swapcase
   +d          prepend d
  {            deduplicate
s          join as string


答:
Jelly, 5 bytes

```<code>żŒsQ€
</code>```

Try it online!

How it works

```<code>żŒsQ€  Main link. Argument: s (string)

 Œs    Yield s with swapped case.
ż      Zip s with the result.
   Q€  Unique each; deduplicate each pair of characters.
</code>```

Title: Duplicate & switch case

Body:
The goal is, having taken a string as input, duplicate each latin letter and "toggle" its case (i.e. uppercase becomes lowercase and vice-versa).

Example inputs & outputs:

```<code>Input      Output
bad        bBaAdD
Nice       NniIcCeE
T e S t    Tt eE Ss tT
s E t      sS Ee tT
1!1!1st!   1!1!1sStT!
n00b       nN00bB
(e.g.)     (eE.gG.)
H3l|@!     Hh3lL|@!
</code>```

The input consists of printable ASCII symbols.

You shouldn't duplicate non-latin letters, numbers, special chars.

Body:
Jelly, 5 bytes

żŒsQ€

Try it online!

How it works

żŒsQ€  Main link. Argument: s (string)

 Œs    Yield s with swapped case.
ż      Zip s with the result.
   Q€  Unique each; deduplicate each pair of characters.


问:
Rearrange a number into alphabetical order
Given a non-negative integer (n), create a function that returns n in alphabetical order, according to the literal spelling of each digit in n.

Examples:

```<code>Input: 101
>> one, zero, one
>> one, one, zero
Output: 110

Input: 31948
>> three, one, nine, four, eight
>> eight, four, nine, one, three
Output: 84913

Input: 5544
>> five, five, four, four
>> five, five, four, four
Output: 5544

Input: 1234567890
Output: 8549176320
</code>```

Note: the operations in the example are illustrative only and do not need to be included in the output. Only the alphabetically-sorted number needs to be returned.

This is code-golf, so the shortest code in bytes wins.

Edit: the input can be taken in any desired format that best suits your language, and the output can be produced similarly by returning from the function or printing. The input will always be a natural number (including 0) and will not contain leading 0's.

Relevant OEIS entry (A057846) found by @DomHastings

答:
Python 3, 74 bytes

lambda x:''.join(i[1]for i in sorted(['9487216503'[int(j)],j]for j in x))
```


答:
Retina, <s>28</s> <s>27</s> 21 bytes

Those are tabs, not spaces.

```<code>.
$&  $&
T`lL    p`Ll_`  .</code>```

Try it online

Thanks for the suggestions everyone.

Title: Duplicate & switch case

Body:
Retina, <s>28</s> <s>27</s> 21 bytes

Those are tabs, not spaces.

.
$&  $&
T`lL    p`Ll_`  .

Try it online

Thanks for the suggestions everyone.


答:
JavaScript ES6, <s>70</s> <s>68</s> <s>66</s> 64 bytes

Saved 2 bytes thanks to @Kevin Lau - not Kenny

Saved 2 bytes thanks to @Cᴏɴᴏʀ O'Bʀɪᴇɴ

```<code>s=>s.replace(/[A-Z]/gi,l=>l+l[`to${l<"a"?"Low":"Upp"}erCase`]())
</code>```

Explanation

This uses a really hacky:

```<code>l[`to${l<"a"?"Low":"Upp"}erCase`]()
</code>```

which ungolfed is:

```<code>l[`to${
   l < "a" ?
   "Low" :
   "Upp"
}erCase`]()
</code>```

Basically l < "a" checks if the code point of the letter is less then the code point of a (therefore being an uppercase letter). If it is it'll do to + Low + erCase which becomed l['toLowerCase']() and makes the character lowercase. ` quotes allow string formatting so essentially you can think of:

```<code>`to${l < "a" ?"Low" : "Upp"}erCase`
</code>```

as: "to" + (l<"a" ? "Low" : "Upp") + "erCase" which generates the function to call (make the string upper or lower case). We put this in square brackets [ ... ] which lets us access a property given its name as a string. This returns the appropriate function and then we just call it.

Title: Duplicate & switch case

Body:
JavaScript ES6, <s>70</s> <s>68</s> <s>66</s> 64 bytes

Saved 2 bytes thanks to @Kevin Lau - not Kenny

Saved 2 bytes thanks to @Cᴏɴᴏʀ O'Bʀɪᴇɴ

s=>s.replace(/[A-Z]/gi,l=>l+l[`to${l<"a"?"Low":"Upp"}erCase`]())

Explanation

This uses a really hacky:

l[`to${l<"a"?"Low":"Upp"}erCase`]()

which ungolfed is:

l[`to${
   l < "a" ?
   "Low" :
   "Upp"
}erCase`]()

Basically l < "a" checks if the code point of the letter is less then the code point of a (therefore being an uppercase letter). If it is it'll do to + Low + erCase which becomed l['toLowerCase']() and makes the character lowercase. ` quotes allow string formatting so essentially you can think of:

`to${l < "a" ?"Low" : "Upp"}erCase`

as: "to" + (l<"a" ? "Low" : "Upp") + "erCase" which generates the function to call (make the string upper or lower case). We put this in square brackets [ ... ] which lets us access a property given its name as a string. This returns the appropriate function and then we just call it.


答:
Ruby, <s>37</s> 33 (30 +  -p flag) bytes

swapcase to the rescue! Sort of. -4 bytes from @Lynn.

```<code>gsub(/[a-z]/i){$&+$&.swapcase}
</code>```

Title: Duplicate & switch case

Body:
Ruby, <s>37</s> 33 (30 +  -p flag) bytes

swapcase to the rescue! Sort of. -4 bytes from @Lynn.

gsub(/[a-z]/i){$&+$&.swapcase}


问:
Implement Takewhile

Introduction and Credit

Today without a fancy prelude: Please implement takewhile.

A variation of this (on a non-trivial data structure) was an assignment at my university functional programming course. This assignment is now closed and has been discussed in class and I have my professor's permission to post it here (I asked explicitly).

Specification

Input

The input will be a list (or your language's equivalent concept) of positive integers.

Output

The output should be a list (or your language's equivalent concept) of positive integers.

What to do?

Your task is to implement takewhile (language built-ins are allowed) with the predicate that the number under consideration is even (to focus on takewhile).

So you iterate over the list from start to end and while the condition (is even) holds, you copy to the output-list and as soon as you hit an element that doesn't make the condition true, you abort the operation and output (a step-by-step example is below). This higher-order functionality is also called takeWhile (takewhile).

Potential corner cases

The order of the output list compared to the input list may not be changed, e.g. [14,42,2] may not become [42,14].

The empty list is a valid in- and output.

Who wins?

This is code-golf so the shortest answer in bytes wins!

Standard rules apply of course.

Test Vectors

```<code>[14, 42, 2324, 97090, 4080622, 171480372] -> [14, 42, 2324, 97090, 4080622, 171480372]
[42, 14, 42, 2324] -> [42, 14, 42, 2324]
[7,14,42] -> []
[] -> []
[171480372, 13, 14, 42] -> [171480372]
[42, 14, 42, 43, 41, 4080622, 171480372] -> [42, 14, 42]
</code>```

Step-by-Step Example

```<code>Example Input: [42, 14, 42, 43, 41, 4080622, 171480372]

Consider first element: 42
42 is even (21*2)
Put 42 into output list, output list is now [42]

Consider second element: 14
14 is even (7*2)
Put 14 into output list, output list is now [42,14]

Consider third element: 42
42 is even (21*2)
Put 42 into output list, output list is now [42,14,42]

Consider fourth element: 43
43 is not even (2*21+1)
Drop 43 and return the current output list

return [42,14,42]
</code>```

Title: Implement Takewhile

Body:
Brainf***, 263 bytes

I took a little snippet from here

>>>>>>,[>>>>>>,]>++++[<++++++++>-]>>>>>+>>>>>>>++++[<++++++++>-]<<<<<<<[<<<<<<]>>>>>>[[>>>>>>>++++[<-------->-]<]<<<<<<[->>>+<<<]>>>[-<+<<+>>>]<>>+>+<<<[-[->]<]+>>>[>]<[-<]<[-]<-[<[<<<<<<]>>>>>>.>>>>>>[>[-]++++[<++++++++>-]<.>>>>>>]>++++[-<++++++++>]<.[-]]>>>>>>]

I'd give an explanation but even I don't have a clue how this works anymore.

Expects input as space-seperated numbers (eg 2 432 1)


答:
Python, 59 bytes

```<code>lambda s:''.join((x,x+x.swapcase())[x.isalpha()]for x in s)
</code>```

Edited to fix repeating non-alphabetic characters

Title: Duplicate & switch case

Body:
Python, 59 bytes

lambda s:''.join((x,x+x.swapcase())[x.isalpha()]for x in s)

Edited to fix repeating non-alphabetic characters


答:
Python 3.5, <s>60</s> 56 bytes:

```<code>for i in input():print(end=i+i.swapcase()[:i.isalpha()])
</code>```

A full program. Will try to golf more.

Try It Online! (Ideone)

Title: Duplicate & switch case

Body:
Python 3.5, <s>60</s> 56 bytes:

for i in input():print(end=i+i.swapcase()[:i.isalpha()])

A full program. Will try to golf more.

Try It Online! (Ideone)


答:
05AB1E, 7 bytes

Code:

```<code>vyyš«Ù?
</code>```

Explanation:

```<code>v       # For each in input.
 yyš    # Push y and y swapcased.
    «Ù  # Concatentate and uniquify.
      ? # Print without a newline.
</code>```

Uses the CP-1252 encoding. Try it online!

Title: Duplicate & switch case

Body:
05AB1E, 7 bytes

Code:

vyyš«Ù?

Explanation:

v       # For each in input.
 yyš    # Push y and y swapcased.
    «Ù  # Concatentate and uniquify.
      ? # Print without a newline.

Uses the CP-1252 encoding. Try it online!


答:
C, <s>151</s> <s>123</s> <s>103</s> 91

Requires 24 parameters passed to the program, in the order R G B R G B ... and outputs the triplet R G B without a newline.

```<code>i,t;main(c,v)char**v;{for(i=0;t=4,i++<3;printf("%d ",t/8))for(c=i;c<24;c+=3)t+=atoi(v[c]);}
</code>```

Body:
C, <s>151</s> <s>123</s> <s>103</s> 91

Requires 24 parameters passed to the program, in the order R G B R G B ... and outputs the triplet R G B without a newline.

i,t;main(c,v)char**v;{for(i=0;t=4,i++<3;printf("%d ",t/8))for(c=i;c<24;c+=3)t+=atoi(v[c]);}


答:
CJam, 11 bytes

```<code>l_el_eu.+.|
</code>```

Test it here.

Explanation

```<code>l      e# Read input.
_el    e# Duplicate, convert to lower case.
_eu    e# Duplicate, convert to upper case.
.+     e# Concatenate the two characters in matching positions from those two
       e# strings. E.g. "ab!" "AB!" would give ["aA" "bB" "!!"].
       e# For each character from the original string and the corresponding
.|     e# string from this list, take the set union (which eliminates duplicates
       e# and keeps the order the values appear in from left to right, so that
       e# the original case of each letter comes first).
</code>```

Title: Duplicate & switch case

Body:
CJam, 11 bytes

l_el_eu.+.|

Test it here.

Explanation

l      e# Read input.
_el    e# Duplicate, convert to lower case.
_eu    e# Duplicate, convert to upper case.
.+     e# Concatenate the two characters in matching positions from those two
       e# strings. E.g. "ab!" "AB!" would give ["aA" "bB" "!!"].
       e# For each character from the original string and the corresponding
.|     e# string from this list, take the set union (which eliminates duplicates
       e# and keeps the order the values appear in from left to right, so that
       e# the original case of each letter comes first).


答:
Python, <s>56</s> 54 bytes

lambda s:''.join(c+c.swapcase()*c.isalpha()for c in s)
```

Test it on Ideone.

Title: Duplicate & switch case

Body:
Python, <s>56</s> 54 bytes

lambda s:''.join(c+c.swapcase()*c.isalpha()for c in s)

Test it on Ideone.


答:
MATL, <s>8</s> 4 bytes

```<code>YmYo
</code>```

Try it online!

4 bytes saved thanks to beaker!

Explanation:

```<code>Ym          "Get the average of each column
  Yo        "And round up
</code>```

Body:
Chameleon challenges are a bad thing, apparently. Too bad, chameleons are beautiful creatures. Time for a change!

As we all know, many chameleons posses a remarkable ability to blend in with their surroundings by changing the color of their skin. Which is also the objective of this challenge.

Challenge

Imagine a square of nine pixels. Eight pixels are the surroundings. At the center is the chameleon.

Like this:

The chameleon naturally tries to blend in with its surroundings. It does so by changing its color to the average of that of the surrounding pixels. So, in this case, the chameleon would change its color to .

Objective

Given the colors of the surrounding pixels, output the color of the chameleon.

The color of the chameleon is defined as the total of all red, green and blue in the pixels ÷ 8.

Input

An array of color values for the eight surrounding pixels, starting at the top left and continuing clockwise, like this:

```<code>[[<red>,<green>,<blue>],[<red>,<green>,<blue>],[<red>,<green>,<blue>],[<red>,<green>,<blue>],[<red>,<green>,<blue>],[<red>,<green>,<blue>],[<red>,<green>,<blue>],[<red>,<green>,<blue>]]
</code>```

You may choose to receive input in a different form, as long as it consists of eight triples of decimal numbers 0-255.

If you receive input in a different form, numbers must either be of a consistent length or have a non-numeric separator between them. Triples must have a separating character unless they are 0-padded to 9 digits. (E.g. 044200255044200255044200255044200255044200255044200255044200255044200255 is valid, so are 44 200 255 44 200 255 44 200 255 44 200 255 44 200 255 44 200 255 44 200 255 44 200 255 and 44?200?255$44?200?255$44?200?255$44?200?255$44?200?255$44?200?255$44?200?255$44?200?255, but 4420025544200255442002554420025544200255442002554420025544200255 is not.)

Output

An array / string / etc. containing the colors of the center pixel (in decimal), like this:

```<code>[<red>,<green>,<blue>]
</code>```

In case you output something other than an array: Numbers must either be of a consistent length or have a non-numeric separator between them. (E.g. 044200255 is valid, so is 44 200 255, but 44200255 is not.)

The numbers may not contain decimal points, so e.g. 44.0 200 255.0 is invalid.

Rounding

Output must be rounded to the nearest integer. (Halves must be rounded up.) E.g., if the sum of all red is 1620, you must output 203, not 202 or 202.5.

Examples

Pictures are for illustration only. The middle pixel is the output, the surrounding pixels are the input.

Input:

```<code>[[200,200,200],[200,200,200],[200,200,200],[200,200,200],[200,200,200],[200,200,200],[200,200,200],[200,200,200]]
</code>```

Output:

```<code>[200,200,200]
</code>```

Input:

```<code>[[0,0,0],[255,255,255],[0,0,0],[255,255,255],[255,255,255],[0,0,0],[255,255,255],[0,0,0]]
</code>```

Output:

```<code>[128,128,128]
</code>```

Input:

```<code>[[0,200,200],[200,0,200],[200,200,0],[60,200,0],[200,0,200],[0,200,220],[2,200,0],[0,0,0]]
</code>```

Output:

```<code>[83,125,103]
</code>```

Input:

```<code>[[0,56,58],[65,0,200],[33,200,0],[60,33,0],[98,0,200],[0,28,220],[2,200,0],[99,0,5]]
</code>```

Output:

```<code>[45,65,85]
</code>```

Submissions can be a full program or a function. Standard I/O and loophole rules apply.

Body:
MATL, <s>8</s> 4 bytes

YmYo

Try it online!

4 bytes saved thanks to beaker!

Explanation:

Ym          "Get the average of each column
  Yo        "And round up


答:
ClojureScript, 45 bytes

```<code>#(apply str(sort-by(vec"9487216503")(str %)))
</code>```

Uses some screwy string->int conversion from Javascript leak through, so it's not valid Clojure.

Title: Rearrange a number into alphabetical order

Body:
Given a non-negative integer (n), create a function that returns n in alphabetical order, according to the literal spelling of each digit in n.

Examples:

```<code>Input: 101
>> one, zero, one
>> one, one, zero
Output: 110

Input: 31948
>> three, one, nine, four, eight
>> eight, four, nine, one, three
Output: 84913

Input: 5544
>> five, five, four, four
>> five, five, four, four
Output: 5544

Input: 1234567890
Output: 8549176320
</code>```

Note: the operations in the example are illustrative only and do not need to be included in the output. Only the alphabetically-sorted number needs to be returned.

This is code-golf, so the shortest code in bytes wins.

Edit: the input can be taken in any desired format that best suits your language, and the output can be produced similarly by returning from the function or printing. The input will always be a natural number (including 0) and will not contain leading 0's.

Relevant OEIS entry (A057846) found by @DomHastings

Body:
ClojureScript, 45 bytes

#(apply str(sort-by(vec"9487216503")(str %)))

Uses some screwy string->int conversion from Javascript leak through, so it's not valid Clojure.


Title: Score a game of Yahtzee

Body:
For each of the 13 rows of a Yahtzee scoresheet you are given (from stdin)
a space separated list of 5 numbers (dice).
Your task is to calculate the score for each line and output the Grand Total of the game.

Example

Input and how to interpret it:

```<code>Input       Box              Score
6 1 4 1 3   Aces              2
3 2 2 1 2   Twos              6
6 3 2 3 3   Threes            9
4 2 3 6 5   Fours             4
6 3 5 5 1   Fives            10
1 5 6 5 6   Sixes            12
            Bonus             -
4 2 4 4 1   3 of a kind      15
2 2 3 2 4   4 of a kind       -
3 2 2 2 3   Full house       25
1 3 1 6 1   Small straight    -
2 5 4 6 3   Large straight   40
2 2 2 2 2   Yahtzee          50
5 5 4 5 2   Chance           21
            Grand Total     194
</code>```

We will disregard the Yahtzee Bonus and Joker rules, and only sum up the scores from the Upper and Lower Section and the Bonus in the Upper Section. If in doubt, refer to these rules.

May the shortest code win!

Body:
Mathematica 359

y = IntegerDigits@ImportString[x, "Table"][[1]];
l = Length; g = Gather; r = Range; b = SortBy; h = l@b[g[y[[#]]], l][[-1]] &;
Tr@Flatten@{# Count[y[[#]], #] & /@ r@6, If[h@7 == 3, 15, 0],
If[h@8 == 4, 20, 0], If[(l /@ b[g[y[[9]]], l]) == {2, 3}, 25, 0],
If[MatchQ[Sort@y[[10]], {___, n_, m_, o_, q_, ___} /; m == n + 1 && o == m + 1 && q == o + 1], 30, 0],
If[Sort[y[[11]]] == r[y[[11, 1]], y[[11, 1]] + 4], 40, 0],
If[l@g[y[[12]]] == 1, 50, 0], y[[13]]}

There must be a more efficient way to check for the short straight.


答:
C, <s>87</s> 80

Pass a string as input to f() and the output is written to STDOUT. The string is not modified.

```<code>f(char*v){for(;*v;++v)putchar(*v),isalpha(*v)?putchar(*v-32+64*!islower(*v)):0;}
</code>```

Title: Duplicate & switch case

Body:
The goal is, having taken a string as input, duplicate each latin letter and "toggle" its case (i.e. uppercase becomes lowercase and vice-versa).

Example inputs & outputs:

```<code>Input      Output
bad        bBaAdD
Nice       NniIcCeE
T e S t    Tt eE Ss tT
s E t      sS Ee tT
1!1!1st!   1!1!1sStT!
n00b       nN00bB
(e.g.)     (eE.gG.)
H3l|@!     Hh3lL|@!
</code>```

The input consists of printable ASCII symbols.

You shouldn't duplicate non-latin letters, numbers, special chars.

Body:
C, <s>87</s> 80

Pass a string as input to f() and the output is written to STDOUT. The string is not modified.

f(char*v){for(;*v;++v)putchar(*v),isalpha(*v)?putchar(*v-32+64*!islower(*v)):0;}


答:
sed, 30 bytes

29 bytes code + 1 byte parameter -r

```<code>s/([a-z])|([A-Z])/&\u\1\l\2/g
</code>```

Usage:

```<code>echo -e 'bad\nNice\nT e S t\ns E t\n1!1!1st!\nn00b\n(e.g.)\nH3l|@!' |\
sed -r 's/([a-z])|([A-Z])/&\u\1\l\2/g'
</code>```

Title: Duplicate & switch case

Body:
sed, 30 bytes

29 bytes code + 1 byte parameter -r

s/([a-z])|([A-Z])/&\u\1\l\2/g

Usage:

echo -e 'bad\nNice\nT e S t\ns E t\n1!1!1st!\nn00b\n(e.g.)\nH3l|@!' |\
sed -r 's/([a-z])|([A-Z])/&\u\1\l\2/g'


答:
Ruby, <s>31+1=32</s> 30+1=31 bytes

With the -p flag, run

```<code>gsub(/(?<=(.))/){$1.swapcase!}
</code>```

Takes advantage of the fact that swapcase! will return nil on anything but an ASCII letter, which translates to an empty string when returned out of the gsub block. @Jordan saved a byte by capturing the previous character in a look-behind.

Title: Duplicate & switch case

Body:
Ruby, <s>31+1=32</s> 30+1=31 bytes

With the -p flag, run

gsub(/(?<=(.))/){$1.swapcase!}

Takes advantage of the fact that swapcase! will return nil on anything but an ASCII letter, which translates to an empty string when returned out of the gsub block. @Jordan saved a byte by capturing the previous character in a look-behind.


答:
Firebird, 317 bytes

Golfed:

```<code>select list(s,'')from(with recursive q as(select 1 p,substring(:a from 1 for 1)s from rdb$database q union all select q.p+1 p,substring(:a from q.p+1 for 1)s from q where q.p<char_length(:a))select s from q order by iif(s=8,0,iif(s=5,1,iif(s=4,2,iif(s=9,3,iif(s=1,4,iif(s=7,5,iif(s=3,7,iif(s=2,8,iif(s=0,9,6))))))))))
</code>```

Ungolfed:

```<code>select list(s, '')
from (
   with recursive q as (
      select 1 as p, substring(:a from 1 for 1) s
      from rdb$database q
      union all
      select q.p + 1 as p, substring(:a from q.p + 1 for 1) as s
      from q
      where q.p < char_length(:a)
   )
   select s
   from q
   order by iif(s = 8, 0,
               iif(s = 5, 1,
                  iif(s = 4, 2,
                     iif(s = 9, 3,
                        iif(s = 1, 4,
                           iif(s = 7, 5,
                              iif(s = 3, 7,
                                 iif(s = 2, 8,
                                    iif(s = 0, 9, 6)))))))))
)
</code>```

There's no split functionality in Firebird. Instead I created a recursive query to get the next character over and over. Then reselect those while sorting by our proper order. Finally concatenate those results back together in a list. Override the default comma delimiter with blank. I could save 11 bytes by creating a new dummy table instead of rdb$database but I thought that may be against the rules.

Body:
Firebird, 317 bytes

Golfed:

select list(s,'')from(with recursive q as(select 1 p,substring(:a from 1 for 1)s from rdb$database q union all select q.p+1 p,substring(:a from q.p+1 for 1)s from q where q.p<char_length(:a))select s from q order by iif(s=8,0,iif(s=5,1,iif(s=4,2,iif(s=9,3,iif(s=1,4,iif(s=7,5,iif(s=3,7,iif(s=2,8,iif(s=0,9,6))))))))))

Ungolfed:

select list(s, '')
from (
   with recursive q as (
      select 1 as p, substring(:a from 1 for 1) s
      from rdb$database q
      union all
      select q.p + 1 as p, substring(:a from q.p + 1 for 1) as s
      from q
      where q.p < char_length(:a)
   )
   select s
   from q
   order by iif(s = 8, 0,
               iif(s = 5, 1,
                  iif(s = 4, 2,
                     iif(s = 9, 3,
                        iif(s = 1, 4,
                           iif(s = 7, 5,
                              iif(s = 3, 7,
                                 iif(s = 2, 8,
                                    iif(s = 0, 9, 6)))))))))
)

There's no split functionality in Firebird. Instead I created a recursive query to get the next character over and over. Then reselect those while sorting by our proper order. Finally concatenate those results back together in a list. Override the default comma delimiter with blank. I could save 11 bytes by creating a new dummy table instead of rdb$database but I thought that may be against the rules.


答:
Pyke, <s>8</s> 6 bytes

```<code>FDl4+}
</code>```

Try it here!

Title: Duplicate & switch case

Body:
Pyke, <s>8</s> 6 bytes

FDl4+}

Try it here!


答:
C, <s>63</s> 60 bytes

```<code>f(char*s){for(;*s;s++)isalpha(putchar(*s))&&putchar(32^*s);}
</code>```

Uses the fact that 'a' XOR 32 == 'A', etc.

Three bytes saved thanks to FryAmTheEggman.

Title: Duplicate & switch case

Body:
C, <s>63</s> 60 bytes

f(char*s){for(;*s;s++)isalpha(putchar(*s))&&putchar(32^*s);}

Uses the fact that 'a' XOR 32 == 'A', etc.

Three bytes saved thanks to FryAmTheEggman.


答:
V, 21 bytes

Try it online!

Too many bytes...

```<code>Ó./°ò
Íá/°°
Îlg~lÎHògJ
</code>```

Title: Duplicate & switch case

Body:
V, 21 bytes

Try it online!

Too many bytes...

Ó./°ò
Íá/°°
Îlg~lÎHògJ


答:
Jolf, 4 bytes

Try it here!

```<code>*P+§
</code>```

Explanation

```<code>*P+§xxx
*     x   implicit input *
   §x       implicit input as string
  +  x      followed by implicit input
 P         as a number
</code>```

Title: Print a bunch of uninteresting numbers!

Body:
An uninteresting number (which I totally didn't make up only for this challenge) is created like this:

Take a positive integer N

Create a new number O by adding the digits of N at the end of N

The final uninteresting number is O*N

For example for N=12:

O = 1212

O*N = 1212 * 12

Final number is 14544

Input

A positive integer N (N > 0) or your language's equivalent. You don't have to catch incorrect input.

Output

The corresponding uninteresting number.

Test cases

```<code>  1 -> 11
  2 -> 44
  3 -> 99
 10 -> 10100
174 -> 30306276
</code>```

Scoring

Shortest Code in Bytes wins.

Body:
Jolf, 4 bytes

Try it here!

*P+§

Explanation

*P+§xxx
*     x   implicit input *
   §x       implicit input as string
  +  x      followed by implicit input
 P         as a number


答:
C, <s>171</s> 163

Function f() modifies its input and prints out the result.

```<code>l;f(char*n){char*p=n,*s=n,c[99];for(;*n;++n)isupper(*n)+isdigit(*n)?*p++=*n:0;*p=0;memset(c,45,l=strlen(s));c[l]=0;printf("+%s+\n|%s|\n+%s+\n%*.cv\n",c,s,c,l,32);}
</code>```

Test Program

Requires one parameter, the string to use in the favicon:

```<code>#include <stdlib.h>
#include <stdio.h>
#include <string.h>

int main(int argc, const char **argv)
{
    char *input=malloc(strlen(argv[1])+1);
    strcpy(input,argv[1]);
    f(input);
    free(input);
    return 0;
}
</code>```

Title: Generate a Stack Exchange Favicon

Body:
Do you recognize the PPCG logo?
it looks like this, when you do an ascii art of it.

```<code>+---+
|PCG|
+---+
   v
</code>```

Now, In this Code Golf, You will make a code, that makes logos for other sites, similar to the PPCG logo.

What You should do

The "Shortened" string will be the string, with all upper case letters and numbers in the input string.(Which would be PPCG when the input string is Programming Puzzles & Code Golf)

The "Box" (

```<code>+---+
|   |
+---+
   v
</code>```

)
should fit the Shortened string perfectly.(No bigger or smaller)

Also the v part should be exactly 1 down and 1 left to the down right +.

Then output the box which has the shortened string in it.

Example

Stack Overflow:

```<code>+--+
|SO|
+--+
  v
</code>```

Area 51:

```<code>+---+
|A51|
+---+
   v
</code>```

Rules

You may assume that the input contains at least one digit or upper case letter.

Standard code-golf rules apply.

Body:
C, <s>171</s> 163

Function f() modifies its input and prints out the result.

l;f(char*n){char*p=n,*s=n,c[99];for(;*n;++n)isupper(*n)+isdigit(*n)?*p++=*n:0;*p=0;memset(c,45,l=strlen(s));c[l]=0;printf("+%s+\n|%s|\n+%s+\n%*.cv\n",c,s,c,l,32);}

Test Program

Requires one parameter, the string to use in the favicon:

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

int main(int argc, const char **argv)
{
    char *input=malloc(strlen(argv[1])+1);
    strcpy(input,argv[1]);
    f(input);
    free(input);
    return 0;
}


问:
given prime factors of a number, what is the fastest way to calculate it's proper divisors?
Given prime factors of a number, what is the fastest way to calculate divisors?

```<code>clc; clear;
sms=0;
count = 1;
x=0;
for i=11:28123
    fac = factor(i);
    sm = 1;
    for j = 1:length(fac)-1
        sm = sm + sum(prod(unique(combntns(fac,j), 'rows'),2));
    end
    if sm>i
        x(count) = i;
        count = count + 1;
    end
end
sum1=0;
count = 1;
for i=1:length(x)
    for j=i:length(x)
        smss = x(i) + x(j);
        if smss <= 28123
            sum1(count) = smss;
            count = count + 1;
        end
    end
end
sum1 = unique(sum1);
disp(28123*28124/2-sum(sum1));
</code>```

currently I'm using this prod(unique(combntns(fac,j), 'rows'),2) code which is awfully slow and I'm using Matlab.

答:
Mathematica

```<code>Union[Prepend[Times @@@ Rest@Subsets@l, 1]]
</code>```

Usage

I'm assuming that repeated factors would be repeated in the list of factors, as below:

```<code>l = {2, 2, 3, 5, 5, 11, 11, 11, 31, 37, 617};
Union[Prepend[Times @@@ Rest@Subsets@l, 1]]//AbsoluteTiming
</code>```

This routine is much slower than the built in function Divisors, which has to first factor the Integer.  I am fairly certain that Divisors is compiled.

```<code>Divisors[282584210700]; // AbsoluteTiming
</code>```

{0.000262, Null}

Body:
Mathematica

Union[Prepend[Times @@@ Rest@Subsets@l, 1]]

Usage

I'm assuming that repeated factors would be repeated in the list of factors, as below:

l = {2, 2, 3, 5, 5, 11, 11, 11, 31, 37, 617};
Union[Prepend[Times @@@ Rest@Subsets@l, 1]]//AbsoluteTiming

This routine is much slower than the built in function Divisors, which has to first factor the Integer.  I am fairly certain that Divisors is compiled.

Divisors[282584210700]; // AbsoluteTiming

{0.000262, Null}


答:
Pyke, 7 bytes

```<code>,FsOO8f
</code>```

Try it here!

Body:
Chameleon challenges are a bad thing, apparently. Too bad, chameleons are beautiful creatures. Time for a change!

As we all know, many chameleons posses a remarkable ability to blend in with their surroundings by changing the color of their skin. Which is also the objective of this challenge.

Challenge

Imagine a square of nine pixels. Eight pixels are the surroundings. At the center is the chameleon.

Like this:

The chameleon naturally tries to blend in with its surroundings. It does so by changing its color to the average of that of the surrounding pixels. So, in this case, the chameleon would change its color to .

Objective

Given the colors of the surrounding pixels, output the color of the chameleon.

The color of the chameleon is defined as the total of all red, green and blue in the pixels ÷ 8.

Input

An array of color values for the eight surrounding pixels, starting at the top left and continuing clockwise, like this:

```<code>[[<red>,<green>,<blue>],[<red>,<green>,<blue>],[<red>,<green>,<blue>],[<red>,<green>,<blue>],[<red>,<green>,<blue>],[<red>,<green>,<blue>],[<red>,<green>,<blue>],[<red>,<green>,<blue>]]
</code>```

You may choose to receive input in a different form, as long as it consists of eight triples of decimal numbers 0-255.

If you receive input in a different form, numbers must either be of a consistent length or have a non-numeric separator between them. Triples must have a separating character unless they are 0-padded to 9 digits. (E.g. 044200255044200255044200255044200255044200255044200255044200255044200255 is valid, so are 44 200 255 44 200 255 44 200 255 44 200 255 44 200 255 44 200 255 44 200 255 44 200 255 and 44?200?255$44?200?255$44?200?255$44?200?255$44?200?255$44?200?255$44?200?255$44?200?255, but 4420025544200255442002554420025544200255442002554420025544200255 is not.)

Output

An array / string / etc. containing the colors of the center pixel (in decimal), like this:

```<code>[<red>,<green>,<blue>]
</code>```

In case you output something other than an array: Numbers must either be of a consistent length or have a non-numeric separator between them. (E.g. 044200255 is valid, so is 44 200 255, but 44200255 is not.)

The numbers may not contain decimal points, so e.g. 44.0 200 255.0 is invalid.

Rounding

Output must be rounded to the nearest integer. (Halves must be rounded up.) E.g., if the sum of all red is 1620, you must output 203, not 202 or 202.5.

Examples

Pictures are for illustration only. The middle pixel is the output, the surrounding pixels are the input.

Input:

```<code>[[200,200,200],[200,200,200],[200,200,200],[200,200,200],[200,200,200],[200,200,200],[200,200,200],[200,200,200]]
</code>```

Output:

```<code>[200,200,200]
</code>```

Input:

```<code>[[0,0,0],[255,255,255],[0,0,0],[255,255,255],[255,255,255],[0,0,0],[255,255,255],[0,0,0]]
</code>```

Output:

```<code>[128,128,128]
</code>```

Input:

```<code>[[0,200,200],[200,0,200],[200,200,0],[60,200,0],[200,0,200],[0,200,220],[2,200,0],[0,0,0]]
</code>```

Output:

```<code>[83,125,103]
</code>```

Input:

```<code>[[0,56,58],[65,0,200],[33,200,0],[60,33,0],[98,0,200],[0,28,220],[2,200,0],[99,0,5]]
</code>```

Output:

```<code>[45,65,85]
</code>```

Submissions can be a full program or a function. Standard I/O and loophole rules apply.

Body:
Pyke, 7 bytes

,FsOO8f

Try it here!


问:
Golf a Sentence
Everybody loves golfing code. Code is written in English (eh...). Therefore, everybody loves golfing English!

Your task is to write a program or function that takes a string as input, and then returns or prints the golfed version. There will be no newlines or tabs in the input.

This is how you golf a string. The order matters!

Remove spaces directly before and after punctuation: "Hey there", he said   ; he ' s a cat. -> "Hey there",he said;he's a cat. The following count as punctuation: .,?!"':;()

Replace he/she/it is, case insensitive, with he's/she's/it's: It is unfortunate that she is not coming ever. -> It's unfortunate that she's not coming ever.

Words that start with capital letters in a sentence can be moved against the preceding word (omitting the space): The farmer told Fred that he should leave. -> The farmer toldFred that he should leave.

Trailing and leading spaces should be removed: [      ]It's raining.[     ]-> It's raining. Ignore the brackets (annoying auto-formatting).

Remove repeated punctuation that is the same: ""Here''s the cake",, said Fred..! -> "Here's the cake",saidFred.!

If we were to golf the first paragraph of this challenge, the output would be:

Everybody loves golfing code.Code is written inEnglish(eh.).Therefore,everybody loves golfingEnglish!

This is code golf––or rather English golf––so shortest code in bytes wins!

Here is one all encompassing test case:

Input: "    You are crazy"",, , , she said. It is unfortunate that Margaret had to say that... she is a Martian!.

Output: "You are crazy",she said.It's unfortunate thatMargaret had to say that.she's aMartian!.

答:
V, 77 bytes

```<code>Ó *¨[.,"':;?!()]© */±
Óã¨s¿heüit©ús is/'s
Óó«úeõ
Ó^ *ü *$
Ó¨[.,"':;?!()]©±*/±
</code>```

Way longer than I'd like.

Try it online!

Title: Golf a Sentence

Body:
V, 77 bytes

Ó *¨[.,"':;?!()]© */±
Óã¨s¿heüit©ús is/'s
Óó«úeõ
Ó^ *ü *$
Ó¨[.,"':;?!()]©±*/±

Way longer than I'd like.

Try it online!


答:
JavaScript ES6, <s>102</s> <s>92</s> <s>61</s> <s>65</s> 95 bytes

```<code>x=>x.replace(/ *([.,?!"':;()])( *\1 *)*| ([A-Z])/g,"$1$3").replace(/(he|it) is/g,"$1's").trim()
</code>```

Works on the last testcase. Saved a lot of bytes thanks to Downgoat! Impressive.

Title: Golf a Sentence

Body:
Everybody loves golfing code. Code is written in English (eh...). Therefore, everybody loves golfing English!

Your task is to write a program or function that takes a string as input, and then returns or prints the golfed version. There will be no newlines or tabs in the input.

This is how you golf a string. The order matters!

Remove spaces directly before and after punctuation: "Hey there", he said   ; he ' s a cat. -> "Hey there",he said;he's a cat. The following count as punctuation: .,?!"':;()

Replace he/she/it is, case insensitive, with he's/she's/it's: It is unfortunate that she is not coming ever. -> It's unfortunate that she's not coming ever.

Words that start with capital letters in a sentence can be moved against the preceding word (omitting the space): The farmer told Fred that he should leave. -> The farmer toldFred that he should leave.

Trailing and leading spaces should be removed: [      ]It's raining.[     ]-> It's raining. Ignore the brackets (annoying auto-formatting).

Remove repeated punctuation that is the same: ""Here''s the cake",, said Fred..! -> "Here's the cake",saidFred.!

If we were to golf the first paragraph of this challenge, the output would be:

Everybody loves golfing code.Code is written inEnglish(eh.).Therefore,everybody loves golfingEnglish!

This is code golf––or rather English golf––so shortest code in bytes wins!

Here is one all encompassing test case:

Input: "    You are crazy"",, , , she said. It is unfortunate that Margaret had to say that... she is a Martian!.

Output: "You are crazy",she said.It's unfortunate thatMargaret had to say that.she's aMartian!.

Body:
JavaScript ES6, <s>102</s> <s>92</s> <s>61</s> <s>65</s> 95 bytes

x=>x.replace(/ *([.,?!"':;()])( *\1 *)*| ([A-Z])/g,"$1$3").replace(/(he|it) is/g,"$1's").trim()

Works on the last testcase. Saved a lot of bytes thanks to Downgoat! Impressive.


答:
Pyke, 14 bytes

```<code>.#uЀB`@
</code>```

Try it here!

Body:
Given a non-negative integer (n), create a function that returns n in alphabetical order, according to the literal spelling of each digit in n.

Examples:

```<code>Input: 101
>> one, zero, one
>> one, one, zero
Output: 110

Input: 31948
>> three, one, nine, four, eight
>> eight, four, nine, one, three
Output: 84913

Input: 5544
>> five, five, four, four
>> five, five, four, four
Output: 5544

Input: 1234567890
Output: 8549176320
</code>```

Note: the operations in the example are illustrative only and do not need to be included in the output. Only the alphabetically-sorted number needs to be returned.

This is code-golf, so the shortest code in bytes wins.

Edit: the input can be taken in any desired format that best suits your language, and the output can be produced similarly by returning from the function or printing. The input will always be a natural number (including 0) and will not contain leading 0's.

Relevant OEIS entry (A057846) found by @DomHastings

Body:
Pyke, 14 bytes

.#uЀB`@

Try it here!


Title: Golf a Sentence

Body:
Retina, 65 bytes

+` *([.,?!"':;()])\1* *| ([A-Z])| +$|^ +
$1$2
i`(s?he|it) is
$1's

Regex replacement and then a simple trim

The magic regex is:

 *([.,?!"':;()])\1* *| ([A-Z])| +$|^ +

Try it online!


问:
Interpret Kipple!

Introduction

Kipple is a stack-based, esoteric programming language invented by Rune Berg in March 2003.

Kipple has 27 stacks, 4 operators, and a control structure.

Stacks

The stacks are named a-z and contain 32-bit signed integers. There is also a special stack, @, to make outputting numbers more convenient. When a number is pushed onto @, the ASCII values of that number's digits are in fact pushed instead. (For example, if you push 12 to @, it will push 49 and then 50 to @ instead.)

Input is pushed onto the input stack i before the program is executed. The interpreter will ask for values to store in i before execution. After execution finishes, anything on the output stack o is popped to output as ASCII character . Since this is Kipple's only IO mechanism, interacting with a Kipple program is impossible.

Operators

An operand is either a stack identifier or a signed 32 bit integer.

Push: > or <

Syntax: Operand>StackIndentifier or StackIndentifier<Operand

The Push operator takes the operand to the left and pushes it onto the specified stack. For example, 12>a will push the value 12 onto stack a. a>b will pop the topmost value from stack a and push it onto stack b. Popping an empty stack always returns 0. a<b is equivalent to b>a. ac pops topmost value from b and pushes to both c and a.

Add: +

Syntax: StackIndentifier+Operand

The Add operator pushes the sum of the topmost item on the stack and the operand onto the stack. If the operand is a stack, then the value is popped from it. For example, if the topmost value of stack a is 1, then a+2 will push 3 onto it. If a is empty, then a+2 will push 2 onto it. If the topmost values of stack a and b are 1 and 2, then a+b will pop the value 2 from stack b and push 3 onto stack a.

Subtract: -

Syntax: StackIndentifier-Operand

The Subtract operator works exactly like the Add operator, except that it subtracts instead of adding.

Clear: ?

Syntax: StackIndentifier?

The Clear operator empties the stack if its topmost item is 0.

The interpreter will ignore anything that isn't next to an operator, so the following program would work: a+2 this will be ignored c<i. However, the proper way to add comments is by using the # character. Anything between a # and an end-of-line character is removed before execution. ASCII character #10 is defined as end-of-line in Kipple.

Operands may be shared by two operators, e.g. a>b c>b c? may be written as a>b<c?.

The program 1>a<2 a+a will result in a containing the values [1 4] (from bottom to top) and not [1 3]. Likewise for the - operator.

The Control Structure

There is only one control structure in Kipple: the loop.

Syntax: (StackIndentifier code )

As long as the specified stack is not empty, the code within the matching parentheses will be repeated. Loops may contain other loops. For example, (a a>b) will move all the values of stack a onto stack b, though the order will be reversed. A functionally identical, but more elegant way to do this is (a>b).

Examples

```<code>100>@ (@>o)
</code>```

This will output 100

```<code>33>o 100>o 108>o 114>o 111>o 87>o 32>o 111>o 108>o 108>o 101>o 72>o
</code>```

This will print "Hello World!". When the o stack is being output, it starts to pop characters from top of the stack to bottom.

```<code>#prime.k by Jannis Harder
u<200
#change 200

k<2>m
u-2
(u-1 u>t u>z u<t
  (k>e e+0 e>r)
  (e>k)
  m+1
  m>t
  m>z
  m<t
  t<0>z? t?
  1>g
  (r>b
    m+0 m>a
    b+0 b>w
    (a-1
      b+0 b>j
      j?
      1>s
      (j<0>s j?)
      s?
      (s<0 w+0 w>b s?)
      a>t
      a>z
      t>a
      b-1
      b>t
      b>z
      t>b
      z<0>t? z?
    a?)
    b?
    1>p
    (b<0 b? 0>p)
    p?
    (p 0>r? 0>p? 0>g)
  )
  g?
  (g m+0 m>k 0>g?)
u?)
(k>@
  10>o
  (@>o)
)
</code>```

This is a prime number generator, but I'm not sure how it works.

Rules

You must write a program/function that interprets Kipple. This program/function may get a Kipple program via a source file, or get it via STDIN directly from the user. If STDIN is not available, it must get it from keyboard input, and continue getting input until a specific unprintable character is entered. For example, if your interpreter is written in x86 machine code, it would get the Kipple program character by character from keyboard, and continue to do so until esc (or any other key other that does not emit a printable character) is pressed.

If there is an error, e.g. a syntax error or stack overflow, it must acknowledge it in some way, for example by returning 10 instead of 0 or error messages produced by the interpreter/compiler, BUT NOT PRINTING ERROR MESSAGES.

Any other regular rules for code golf apply for this challenge.

Your code will be tested with some of the examples in Kipple's samples archive

This is a code-golf . Shortest code in bytes will win.
Good Luck!

Note that there is an optional operator in Kipple, ", but it is not a part of the specification and just an extra feature in official interpreter. I haven't mentioned it here so it does not need to be supported in your submission.

If you have any doubt about any part of specification , you can examine it with official interpreter written in Java . This will download a zip file containing compiled program and source code . It's licensed under the GPL.

答:
C, 709 702 bytes

The byte score is with newlines (that can be removed) removed, but for ease of reading I post it here with newlines:

```<code>#define R return
#define C ;break;case
c[999]={};*P=c;*S[28];M[99999]={};t;*T;
u(s,v){S[s]+=28;*S[s]=v;
if(s>26){for(t=v/10;t;t/=10)S[s]+=28;T=S[s];do{*T=48+v%10;T-=28;}while(v/=10);}}
o(s){t=S[s]-M>27;S[s]-=28*t;R S[s][28]*t;}
I(s){R s<65?27:s-97;}
O(int*p){if(!isdigit(*p))R o(I(*p));
for(;isdigit(p[-1]);--p);for(t=0;isdigit(*p);t*=10,t+=*p++-48);R t;}

main(i,a){for(i=0;i<28;++i)S[i]=M+i;
for(;~(*++P=getchar()););P=c+1;
for(;;){i=I(P[-1]);switch(*P++){
case 35:for(;*P++!=10;)
C'<':u(i,O(P))
C'>':u(I(*P),O(P-2))
C'+':u(i,*S[i]+O(P))
C'-':u(i,*S[i]-O(P))
C'?':if(!*S[i])S[i]=M+i
C'(':for(i=1,T=P;i;++T)i+=(*T==40)-(*T==41);if(S[I(*P)]-M<28)P=T;else u(26,P-c)
C')':P=c+o(26)-1
C-1:for(;i=o(14);)putchar(i); R 0;}}}
</code>```

Compile with gcc -w golf.c (-w silences warnings for your sanity).

Supports everything except the i input, as the asker has not responded yet to my inquiry on how to do it if you take the code from stdin. It does not report syntax errors.

Title: Interpret Kipple!

Body:
C, 709 702 bytes

The byte score is with newlines (that can be removed) removed, but for ease of reading I post it here with newlines:

#define R return
#define C ;break;case
c[999]={};*P=c;*S[28];M[99999]={};t;*T;
u(s,v){S[s]+=28;*S[s]=v;
if(s>26){for(t=v/10;t;t/=10)S[s]+=28;T=S[s];do{*T=48+v%10;T-=28;}while(v/=10);}}
o(s){t=S[s]-M>27;S[s]-=28*t;R S[s][28]*t;}
I(s){R s<65?27:s-97;}
O(int*p){if(!isdigit(*p))R o(I(*p));
for(;isdigit(p[-1]);--p);for(t=0;isdigit(*p);t*=10,t+=*p++-48);R t;}

main(i,a){for(i=0;i<28;++i)S[i]=M+i;
for(;~(*++P=getchar()););P=c+1;
for(;;){i=I(P[-1]);switch(*P++){
case 35:for(;*P++!=10;)
C'<':u(i,O(P))
C'>':u(I(*P),O(P-2))
C'+':u(i,*S[i]+O(P))
C'-':u(i,*S[i]-O(P))
C'?':if(!*S[i])S[i]=M+i
C'(':for(i=1,T=P;i;++T)i+=(*T==40)-(*T==41);if(S[I(*P)]-M<28)P=T;else u(26,P-c)
C')':P=c+o(26)-1
C-1:for(;i=o(14);)putchar(i); R 0;}}}

Compile with gcc -w golf.c (-w silences warnings for your sanity).

Supports everything except the i input, as the asker has not responded yet to my inquiry on how to do it if you take the code from stdin. It does not report syntax errors.


问:
Normal sentences
Write a program or function which, given an input string and a standard deviation σ, outputs that string along the normal distribution curve with mean 0 and standard deviation σ.

Normal distribution curve

The y coordinate of each character c is:

where σ is given as input, and where x is the x axis coordinate of c.

The character in the center of the string has x = 0. If the string's length is even, either of the two middle characters can be chosen as the center.

Characters are separated by steps of 0.1 (e.g. the character to the left of the center one has x = -0.1, the one to the right of the middle one has x = 0.1, etc.).

Printing the string

Lines, like characters, are separated by steps of 0.1.

Each character is printed on the line with the y value that is closest to its own y value (if the value is precisely in between the values of two lines, choose the one with the biggest value (just like how round usually returns 1.0 for 0.5)).

For example, if the y coordinate of the center value (i.e. the maximum value) is 0.78 and the y coordinate of the first character is 0.2, then there will 9 lines: the center character being printed on line 0 and the first character being printed on line 8.

Inputs and outputs

You may take both inputs (the string and σ) as program arguments, through STDIN, function arguments or anything similar in your language.

The string will only contain printable ASCII characters. The string can be empty.

σ > 0.

You may print the output to STDOUT, in a file, or return it from a function (as long as it is a string and not say a list of strings for each line).

A trailing new line is acceptable.

Trailing spaces are acceptable as long as they don't make the line exceed the last line in length (so no trailing space is acceptable on the last line).

Test cases

```<code>σ    String

0.5  Hello, World!

     , W
   lo   or
  l       l
 e         d
H           !

0.5  This is a perfectly normal sentence

                tly
              ec    n
             f       o
            r         r
           e           m
          p             a
        a                l
      s                    se
This i                       ntence

1.5  Programming Puzzles & Code Golf is a question and answer site for programming puzzle enthusiasts and code golfers.

                                                d answer site for p
                                      uestion an                   rogramming
                      Code Golf is a q                                        puzzle enthusia
Programming Puzzles &                                                                        sts and code golfers.

0.3  .....................

          .
         . .

        .   .

       .     .

      .       .

     .         .
    .           .
   .             .
...               ...
</code>```

Scoring

This is code-golf,

```<code>                 nsw
                a   er
              t
             s         i
            e           n
           t
         or               by
       sh                   te
so the                        s wins.
</code>```

答:
Python 3 with SciPy, <s>239</s> 233 bytes

```<code>from scipy import stats,around,arange
def f(s,t):
 l=len(t);p=[];y=around(stats.norm.pdf((arange(l)-l//2)*.1,scale=s),1)*10
 for i in range(l):p+=[[' ']*(max(y)-y[i])];p[i]+=[t[i]]+[' ']*(y[i]-y[0])
 for j in zip(*p):print(*j,sep='')
</code>```

A function that takes input via argument of standard deviation s and string t, and prints the result to STDOUT.

How it works

```<code>from scipy import stats,around,arange  Import the statistics, rounding and range functions
                                       from SciPy
def f(s,t):                            Function with input standard deviation s and string
                                       t
l=len(t);p=[]                          Define the much-used length of t as l and initialise
                                       the print values list p
arange(l)                              Generate a list of integer x values in [0,l)...
...-l//2*.1                            ...and scale such that 0 is at the middle character
                                       and the x-step is 0.1
stats.norm.pdf(...,scale=s)            Generate a list containing the y values for each x
                                       value by calling the normal probability
                                       density function scaled with s...
y=around(...,1)                        ...round all values to 1 decimal place...
...*10                                 ...and multiply by 10 to give the vertical index of
                                       each character
for i in range(l):...                  For all characters in t...
p+=[[' ']*(max(y)-y[i])]               ..add the number of lines below the character as
                                       spaces...
p[i]+=[t[i]]+[' ']*(y[i]-y[0])         ...add the character and the number of lines above
                                       the character as spaces

This leaves p containing a list for each desired output line, but transposed.

for j in zip(*p):...                   For every output line in the transpose of p...
print(*j,sep='')                       ...print the output line
</code>```

Try it on Ideone

Title: Normal sentences

Body:
Python 3 with SciPy, <s>239</s> 233 bytes

from scipy import stats,around,arange
def f(s,t):
 l=len(t);p=[];y=around(stats.norm.pdf((arange(l)-l//2)*.1,scale=s),1)*10
 for i in range(l):p+=[[' ']*(max(y)-y[i])];p[i]+=[t[i]]+[' ']*(y[i]-y[0])
 for j in zip(*p):print(*j,sep='')

A function that takes input via argument of standard deviation s and string t, and prints the result to STDOUT.

How it works

from scipy import stats,around,arange  Import the statistics, rounding and range functions
                                       from SciPy
def f(s,t):                            Function with input standard deviation s and string
                                       t
l=len(t);p=[]                          Define the much-used length of t as l and initialise
                                       the print values list p
arange(l)                              Generate a list of integer x values in [0,l)...
...-l//2*.1                            ...and scale such that 0 is at the middle character
                                       and the x-step is 0.1
stats.norm.pdf(...,scale=s)            Generate a list containing the y values for each x
                                       value by calling the normal probability
                                       density function scaled with s...
y=around(...,1)                        ...round all values to 1 decimal place...
...*10                                 ...and multiply by 10 to give the vertical index of
                                       each character
for i in range(l):...                  For all characters in t...
p+=[[' ']*(max(y)-y[i])]               ..add the number of lines below the character as
                                       spaces...
p[i]+=[t[i]]+[' ']*(y[i]-y[0])         ...add the character and the number of lines above
                                       the character as spaces

This leaves p containing a list for each desired output line, but transposed.

for j in zip(*p):...                   For every output line in the transpose of p...
print(*j,sep='')                       ...print the output line

Try it on Ideone


问:
Directory Structure Graphical Treefication
Convert a classical directory structure like this:

```<code>config.yml
drafts
    begin-with-the-crazy-ideas.textile
    on-simplicity-in-technology.markdown
includes
    footer.html
    header.html
</code>```

Into this

```<code>.
├── config.yml
├── drafts
|   ├── begin-with-the-crazy-ideas.textile
|   └── on-simplicity-in-technology.markdown
└── includes
    ├── footer.html
    └── header.html
</code>```

Four spaces specify a nested folder or file of the above dir.

Nested categories levels allowed can vary.

Update

filenames: valid Linux filenames without spaces and linefeeds: any byte except NUL, / and spaces, linefeeds

drawing characters:

| vertical line (U+007C)

─ box drawings light horizontal (U+2500)

├ box drawings light vertical and right (U+251C)

Winner: Shortest Code in Bytes wins!

答:
JavaScript (ES6), <s>237</s> 128 bytes

```<code>f=(s,r=`.\n`+s.replace(/^ */gm,"$&└── "),q=r.replace(/^(.*)( |└)(?=.+\n\1[|└])/m,(_,i,j)=>i+`|├`[+(j>' ')]))=>q==r?r:f(s,q)
</code>```

Where \n represents the literal newline character. Explanation: r is created from s by prepending the . line and inserting the └── at the end of each line's indent. This is now correct for the last line of the input, but each └ must be "extended" upwards as far as possible. This is the job of q, which searches for a └ and recursively replaces the spaces directly above it with |s unless it reaches another └ which gets turned into ├ instead. The recursion ends when no further replacements can be made. Note that if the character above the └ is a space or a └ then the text to the left of the └ is always the same as that on the previous line so I can just use \1 to test that the one character is above the other.

Body:
JavaScript (ES6), <s>237</s> 128 bytes

f=(s,r=`.\n`+s.replace(/^ */gm,"$&└── "),q=r.replace(/^(.*)( |└)(?=.+\n\1[|└])/m,(_,i,j)=>i+`|├`[+(j>' ')]))=>q==r?r:f(s,q)

Where \n represents the literal newline character. Explanation: r is created from s by prepending the . line and inserting the └── at the end of each line's indent. This is now correct for the last line of the input, but each └ must be "extended" upwards as far as possible. This is the job of q, which searches for a └ and recursively replaces the spaces directly above it with |s unless it reaches another └ which gets turned into ├ instead. The recursion ends when no further replacements can be made. Note that if the character above the └ is a space or a └ then the text to the left of the └ is always the same as that on the previous line so I can just use \1 to test that the one character is above the other.


Title: Generate a Stack Exchange Favicon

Body:
Ruby, 81 bytes (78 + -p flag)

gsub(/[^A-Z\d]/,'')
gsub(/.+/){"+#{k=?-*s=$&.size}+
|#{$&}|
+#{k}+
#{' '*s}v"}


问:
How to determine if a number is odd or even without mod -or- bitwise operations?
How to determine if a number is odd or even without mod -or- bitwise operations?

This challenge is grossly inefficient, but challenges your ability to think outside the box for a creative solution.

EDIT:

Please create a function. Also, while regex is a fun response, the function should accept any valid number.

BACKGROUND:
This question stems from my earliest programming days.  The homework for our first day of class was to write a simple program that printed 'odd' or 'even'.  Being the brat I was, I didn't read the book we had for the class where it simply showed us how to use % to determine that.  I spent about a half hour pacing back in forth in my room trying to think of a way to do this and had remembered from the lecture that numbers can lose and gain precision as they are cast from one primitive type to another.  Therefore, if you took the number, divided it by two and then multiplied it back didn't equal the original number, then you would know that the number was odd.

I was stunned the next day, while our instructor was evaluating our programs, that he thought that it was the most original, if inefficient, way of solving the problem.

答:
Python

I decided to try for the ugliest, most confusing solution I could think of:

```<code>n=input();r=range(n+1)
print [j for i in zip(map(lambda x:str(bool(x))[4],[8&7for i in r]),
map(lambda x:str(x)[1],[[].sort()for x in r])) for j in i][n]
</code>```

Prints e if even, o if odd.

Body:
Python

I decided to try for the ugliest, most confusing solution I could think of:

n=input();r=range(n+1)
print [j for i in zip(map(lambda x:str(bool(x))[4],[8&7for i in r]),
map(lambda x:str(x)[1],[[].sort()for x in r])) for j in i][n]

Prints e if even, o if odd.


答:
Python 3.5, 213 bytes:

```<code>import re;R=re.sub;W=lambda G:G.group(0);print(R(r'(\W)\1+',lambda f:W(f)[0],R('\s*[^\s\w]\s*|\s*[A-Z]',lambda f:W(f).strip(),R('((I|i)t|(s|S)?(h|H)e) is',lambda i:W(i)[:[*W(i)].index(" ")]+"'s",input().strip()))))
</code>```

Uses 3 regular expressions in a row with re.sub in conjunction with Python's str.strip() built in to golf the input English sentence.

Try It Online! (repl.it)

Title: Golf a Sentence

Body:
Python 3.5, 213 bytes:

import re;R=re.sub;W=lambda G:G.group(0);print(R(r'(\W)\1+',lambda f:W(f)[0],R('\s*[^\s\w]\s*|\s*[A-Z]',lambda f:W(f).strip(),R('((I|i)t|(s|S)?(h|H)e) is',lambda i:W(i)[:[*W(i)].index(" ")]+"'s",input().strip()))))

Uses 3 regular expressions in a row with re.sub in conjunction with Python's str.strip() built in to golf the input English sentence.

Try It Online! (repl.it)


问:
Determine the "Luck" of a string
Given a string, return that string's "luck".

A string's luck, as I completely just made up for the purpose of this challenge, is an integer, determined as so:

The base luck for a string is 1.

For each consecutive letter it shares with the word "lucky" (case insensitive), multiply the luck by 2. For instance, if your string was "lumberjack" or "smack" you'd multiply by 4. (More specifically, 2^number of consecutive characters shared.)

The shared letters have to be in the same consecutive order it appears in "lucky" but can start anywhere in the word for the same value ("luc" has the same 8* multiplier as "cky").

If the word has multiple occurrences where it shares consecutive characters with lucky, use the longest consecutive string of the characters.

For ANY letter it shares with the word "omen" subtract 2 from the luck.

It can match a character any amount of times, in any order. For instance the string "nnnnnomemenn" loses 24 luck (12 matching letters)

Example:

```<code>luck("lucky")
>>32
</code>```

2^5 (5 consecutive letters) = 32

```<code>luck("firetruck")
>>6
</code>```

2^3 - 2 (3 consecutive letters from uck, e shared with omen)

```<code>luck("memes")
>>-7
</code>```

1 - 8 (base amount, 4 shared with "omen")

This is code golf, so the answer with the fewest bytes wins.

You can input and output any way you'd like - write a function, use standard input, etc.

For functions, assume whatever data type would make sense for that language. (For example, in JavaScript, you'd be passed a String and return a Number)

Edit: You can assume any input is lowercase.

答:
Haskell, 99

Another approach... I just learned about function aliasing

```<code>import Data.List
s=subsequences
i=intersect
l=length
f n=2^(l$last$i(s"lucky")$s n)-2*l(i n$"omen")
</code>```

Usage

```<code>f"lucky"
32

f"firetruck"
6

f"memes"
-7
</code>```

Title: Determine the "Luck" of a string

Body:
Haskell, 99

Another approach... I just learned about function aliasing

import Data.List
s=subsequences
i=intersect
l=length
f n=2^(l$last$i(s"lucky")$s n)-2*l(i n$"omen")

Usage

f"lucky"
32

f"firetruck"
6

f"memes"
-7

ContentLicense: CC BY-SA 4.0


答:
J, <s>31</s> 29 bytes

```<code>[:;]<@~."1@,.tolower,.toupper
</code>```

Explanation

```<code>[:;]<@~."1@,.tolower,.toupper  Input: s
                      toupper  Convert s to all uppercase
             tolower           Convert s to all lowercase
                    ,.         Join them as columns in a 2d array
   ]                           Identity function, get s
           ,.                  Prepend s as a column to the 2d array
      ~."1@                    Take the unique chars on each row
    <@                         Box them
[:;                            Unbox the list of boxes and join their contents and return
</code>```

Title: Duplicate & switch case

Body:
The goal is, having taken a string as input, duplicate each latin letter and "toggle" its case (i.e. uppercase becomes lowercase and vice-versa).

Example inputs & outputs:

```<code>Input      Output
bad        bBaAdD
Nice       NniIcCeE
T e S t    Tt eE Ss tT
s E t      sS Ee tT
1!1!1st!   1!1!1sStT!
n00b       nN00bB
(e.g.)     (eE.gG.)
H3l|@!     Hh3lL|@!
</code>```

The input consists of printable ASCII symbols.

You shouldn't duplicate non-latin letters, numbers, special chars.

Body:
J, <s>31</s> 29 bytes

[:;]<@~."1@,.tolower,.toupper

Explanation

[:;]<@~."1@,.tolower,.toupper  Input: s
                      toupper  Convert s to all uppercase
             tolower           Convert s to all lowercase
                    ,.         Join them as columns in a 2d array
   ]                           Identity function, get s
           ,.                  Prepend s as a column to the 2d array
      ~."1@                    Take the unique chars on each row
    <@                         Box them
[:;                            Unbox the list of boxes and join their contents and return


答:
Actually, 8 bytes

```<code>`;Öo╔`MΣ
</code>```

Try it online!

Explanation:

```<code>`;Öo╔`MΣ
`;Öo╔`M   for each character in input:
 ;          duplicate the character
  Ö         swap case
   o        append to original character
    ╔       remove duplicated characters
       Σ  concatenate
</code>```

Title: Duplicate & switch case

Body:
Actually, 8 bytes

`;Öo╔`MΣ

Try it online!

Explanation:

`;Öo╔`MΣ
`;Öo╔`M   for each character in input:
 ;          duplicate the character
  Ö         swap case
   o        append to original character
    ╔       remove duplicated characters
       Σ  concatenate


问:
Guess the language

Introduction

This site is rapidly building up a huge dataset of code snippets, so let's do something with it!

Here's a data file. It contains 9,066 unique language+snippet pairs for 113 languages, all taken from this site. The format is tab-separated (language-TAB-snippet), with all newlines in the snippets replaced with <LF>, and all tabs replaced with 4 spaces. There are at least 5 snippets for each language.

[update: I've made a minor change to the data file to merge some Python & RegExp versions I missed before - the link above has been updated]

Challenge

Write a program or function which takes a code snippet and outputs the language it is written in (see below for details). The total size of your source + any data you require must be 300 bytes or less, and your program must output the correct language when given its own source code. Highest accuracy (most correct answers on the dataset above) wins.

Rules

The total size of your source code, resources, and any required compilation / runtime flags must not exceed 300 bytes.

Your answer will be tested against the dataset above; it will be given one of the "Snippet" values as input and its output will be compared against the "correct" output according to the dataset. This will be repeated for all entries in the dataset and the final number of correct answers is your score.

You can choose the input encoding - I'll assume UTF-8, so if you need another encoding specify it in your answer.

You don't need to use the <LF> replacement for newlines; if your entry expects to receive newlines as literal newlines (char 10), specify it in your answer.

Your entry must output the language it thinks the input snippet is written in. To avoid the need to compress lots of language strings, I'll allow mappings (If you want to output 3 for "Java", that's fine); just note the mappings in your answer.

You can only have 1 output mapping for each language (i.e. if 3 means "Java", you can't also have 4 meaning "Java").

When given its own source code, your program must produce the correct answer (must output the language it is written in).

You don't need to support all languages in the dataset, and you can support extra languages if you want to (e.g. if your entry isn't in one of the languages in the dataset).

Your program must be deterministic (providing the same input twice must produce the same output).

Tie-Breaking

Ties will be decided by reducing the dataset until one entry wins. The dataset will be reduced by removing all snippets for the most popular language (i.e. ties are broken by accuracy on rarer languages). For example, if A and B score 70% on the full dataset, all Python snippets will be removed. If A and B now both score 60%, CJam will be removed. If A now scores 50% but B scores 55%, B is the winner.

If 100% accuracy is achieved, ties will be decided using a second (blind) dataset containing more samples for the same languages.

Example 1

The Python script:

```<code>print("python")
</code>```

This script successfully produces "python" when given its own source code, so it is valid. On the dataset, it scores 1008/9066 = 11.1%

Example 2

The JavaScript function:

```<code>function f(s){return /function/.test(s)?1:2}
</code>```

With the mappings 1 → javascript, 2 → python. Again it successfully produces 1 ("javascript") for its own source, and on the dataset it scores 1092/9066 = 12.0%

Where did the data come from?

I created an SEDE query to pull samples from [code-golf] challenges on this site. From the resulting 10,000 answers, I used a hacked-together python script to find the code & language name for each, then filtered out any language with less than 5 examples. The data isn't 100% clean (I know there are some non-code snippets it pulled), but should be good enough.

Inspired by this challenge from earlier in the year: Who said that? 2016 Presidential election

Also partly related to What's the Language?

答:
C, 297 bytes, 43.194351% matched (v2)

This is the first non-golf challenge I've competed in. Surprisingly, golfing languages are actually rather easy to separate, with about 60% matching accuracy per language.

The code requires input as UTF-8 string, results based on version 2 of the supplied dataset. This code does not require <LF> to be replaced with actual newlines.

```<code>#define S(x)!!strstr(p,#x)
f(char*p){return S(#d)?:S(voi)?0:S(mai)|S(utc)?:S(mbd)|S(impor)|S(input)|S(def)|S(rang)?2:S(log)|S(fun)|S(=>)|S(lert)?3:S(<?)?4:S(echo)|S(sed)?5:S(+++)?6:S(<-)?7:S($_)|S(say)?8:S(\342)|S(\303)?9:S(->)|S(map)?10:S(@#)|S(]])|S([#)?11:S(V)|S(Q)?12:S(Z)|S(Y)?13:S(.)?14:15;}
</code>```

Mapping table:

```<code> 0. java
 1. c
 2. python
 3. javascript
 4. php
 5. bash
 6. brainf*
 7. haskell
 8. perl
 9. apl
10. ruby
11. wolfram
12. pyth
13. matl
14. golfscript
15. cjam
</code>```

The percentage is based on my hits/total calculation: 3916 hits/9066 total.

Title: Guess the language

Body:
C, 297 bytes, 43.194351% matched (v2)

This is the first non-golf challenge I've competed in. Surprisingly, golfing languages are actually rather easy to separate, with about 60% matching accuracy per language.

The code requires input as UTF-8 string, results based on version 2 of the supplied dataset. This code does not require <LF> to be replaced with actual newlines.

#define S(x)!!strstr(p,#x)
f(char*p){return S(#d)?:S(voi)?0:S(mai)|S(utc)?:S(mbd)|S(impor)|S(input)|S(def)|S(rang)?2:S(log)|S(fun)|S(=>)|S(lert)?3:S(<?)?4:S(echo)|S(sed)?5:S(+++)?6:S(<-)?7:S($_)|S(say)?8:S(\342)|S(\303)?9:S(->)|S(map)?10:S(@#)|S(]])|S([#)?11:S(V)|S(Q)?12:S(Z)|S(Y)?13:S(.)?14:15;}

Mapping table:

 0. java
 1. c
 2. python
 3. javascript
 4. php
 5. bash
 6. brainf*
 7. haskell
 8. perl
 9. apl
10. ruby
11. wolfram
12. pyth
13. matl
14. golfscript
15. cjam

The percentage is based on my hits/total calculation: 3916 hits/9066 total.


答:
Haskell, <s>121, 101, 85,</s> 82

```<code>import Data.Char
g n|isLower n=toUpper n|1<2=toLower n
(>>= \x->x:[g x|isAlpha x])
</code>```

Title: Duplicate & switch case

Body:
Haskell, <s>121, 101, 85,</s> 82

import Data.Char
g n|isLower n=toUpper n|1<2=toLower n
(>>= \x->x:[g x|isAlpha x])


答:
16-bit x86 machine code, 72 bytes

In hex:

```<code>565789F731C9FCAC84C074143C5A77F73C4173083C3977EF3C3072EBAA41EBE75F5EE81500B07CAA51F3A4AB59E80A00B020F3AAB076AA91AAC351B02BAAB02DF3AAB82B10AB59C3
</code>```

Parameters: SI = input string, DI - output buffer.

Outputs a NULL-terminated string with lines delimited by newline.
Uses input string as a temporary buffer.

```<code>56           push   si
57           push   di
89 f7        mov    di,si    ;Using source string as a buffer
31 c9        xor    cx,cx    ;Counter
fc           cld
_loop:
ac           lodsb
84 c0        test   al,al    ;Test for NULL
74 14        jz     _draw    ;Break
3c 5a        cmp    al,'z'   ;\
77 f7        ja     _loop    ; |
3c 41        cmp    al,'a'    ; \
73 08        jae    _stor    ;  >[A-Z0-9]?
3c 39        cmp    al,'9'   ; /
77 ef        ja     _loop    ; |
3c 30        cmp    al,'0'   ;/
72 eb        jb     _loop
_stor:
aa           stosb           ;Store char in the source buffer
41           inc    cx
eb e7        jmp    _loop
_draw:
5f           pop    di
5e           pop    si
e8 15 00     call   _line    ;Output the first line
b0 7c        mov    al,'|'   ;This proc upon return leaves '\n' in AH
aa           stosb           ;First char of the second line
51           push   cx
f3 a4        rep    movsb    ;Copy CX logo characters from the source buffer
ab           stosw           ;Outputs "|\n", which is still in AX
59           pop    cx
e8 0a 00     call   _line    ;Output the third line
b0 20        mov    al,0x20  ;Space
f3 aa        rep    stosb    ;Output it CX times
b0 76        mov    al,'v'
aa           stosb           ;Output the final 'v'
91           xchg   cx,ax    ;CX == 0
aa           stosb           ;NULL-terminate the string
c3           retn            ;Return to caller
_line:
51           push   cx
b0 2b        mov    al,'+'
aa           stosb
b0 2d        mov    al,'-'
f3 aa        rep    stosb     ;'-'*CX
b8 2b 10     mov    ax,0x102b ;"+\n"
ab           stosw
59           pop    cx
c3           retn
</code>```

Title: Generate a Stack Exchange Favicon

Body:
Do you recognize the PPCG logo?
it looks like this, when you do an ascii art of it.

```<code>+---+
|PCG|
+---+
   v
</code>```

Now, In this Code Golf, You will make a code, that makes logos for other sites, similar to the PPCG logo.

What You should do

The "Shortened" string will be the string, with all upper case letters and numbers in the input string.(Which would be PPCG when the input string is Programming Puzzles & Code Golf)

The "Box" (

```<code>+---+
|   |
+---+
   v
</code>```

)
should fit the Shortened string perfectly.(No bigger or smaller)

Also the v part should be exactly 1 down and 1 left to the down right +.

Then output the box which has the shortened string in it.

Example

Stack Overflow:

```<code>+--+
|SO|
+--+
  v
</code>```

Area 51:

```<code>+---+
|A51|
+---+
   v
</code>```

Rules

You may assume that the input contains at least one digit or upper case letter.

Standard code-golf rules apply.

Body:
16-bit x86 machine code, 72 bytes

In hex:

565789F731C9FCAC84C074143C5A77F73C4173083C3977EF3C3072EBAA41EBE75F5EE81500B07CAA51F3A4AB59E80A00B020F3AAB076AA91AAC351B02BAAB02DF3AAB82B10AB59C3

Parameters: SI = input string, DI - output buffer.

Outputs a NULL-terminated string with lines delimited by newline.
Uses input string as a temporary buffer.

56           push   si
57           push   di
89 f7        mov    di,si    ;Using source string as a buffer
31 c9        xor    cx,cx    ;Counter
fc           cld
_loop:
ac           lodsb
84 c0        test   al,al    ;Test for NULL
74 14        jz     _draw    ;Break
3c 5a        cmp    al,'z'   ;\
77 f7        ja     _loop    ; |
3c 41        cmp    al,'a'    ; \
73 08        jae    _stor    ;  >[A-Z0-9]?
3c 39        cmp    al,'9'   ; /
77 ef        ja     _loop    ; |
3c 30        cmp    al,'0'   ;/
72 eb        jb     _loop
_stor:
aa           stosb           ;Store char in the source buffer
41           inc    cx
eb e7        jmp    _loop
_draw:
5f           pop    di
5e           pop    si
e8 15 00     call   _line    ;Output the first line
b0 7c        mov    al,'|'   ;This proc upon return leaves '\n' in AH
aa           stosb           ;First char of the second line
51           push   cx
f3 a4        rep    movsb    ;Copy CX logo characters from the source buffer
ab           stosw           ;Outputs "|\n", which is still in AX
59           pop    cx
e8 0a 00     call   _line    ;Output the third line
b0 20        mov    al,0x20  ;Space
f3 aa        rep    stosb    ;Output it CX times
b0 76        mov    al,'v'
aa           stosb           ;Output the final 'v'
91           xchg   cx,ax    ;CX == 0
aa           stosb           ;NULL-terminate the string
c3           retn            ;Return to caller
_line:
51           push   cx
b0 2b        mov    al,'+'
aa           stosb
b0 2d        mov    al,'-'
f3 aa        rep    stosb     ;'-'*CX
b8 2b 10     mov    ax,0x102b ;"+\n"
ab           stosw
59           pop    cx
c3           retn