答:
Befunge, 165 <s>227</s> bytes

```<code>&::&*:1` v
v+3*2:\/\_"o",@
v       _$ v<
>"_",1-:^  2
v:,,"| ",*5<
v         _v
>" o",,1-:^$
>*v>\     #\^
5 #|:-1,"|"<
^2$<
v1, *95<
- >2*3+^
>:    #^_@
</code>```

Not as much whitespace as before, but there are still gaps. The principle is the same as in the previous solution, but the layout is different. This time, to check if both numbers are 1, I'm just taking their product and seeing if the result is greater than 1.

Old solution (227 bytes)

```<code>v           v       <
&   >>\:2*3+>"_",1-:|
>&:1`|v ,,"| ",*52:$<   :\<
    #\v         <
     :>" o",,1-:|
     1          >"|",$\1-:|
    \`            @       $
    ^_"o",@>:!    |       2
           ^-1,*95<+3*2,*5<
</code>```

It might be possible to golf it more. Just look at all that whitespace!

Here's my poor attempt at an explanation in MSPaint picture form:

Code flows in the direction of the arrow.

Title: Print a Lego piece

Body:
Befunge, 165 <s>227</s> bytes

&::&*:1` v
v+3*2:\/\_"o",@
v       _$ v<
>"_",1-:^  2
v:,,"| ",*5<
v         _v
>" o",,1-:^$
>*v>\     #\^
5 #|:-1,"|"<
^2$<
v1, *95<
- >2*3+^
>:    #^_@

Not as much whitespace as before, but there are still gaps. The principle is the same as in the previous solution, but the layout is different. This time, to check if both numbers are 1, I'm just taking their product and seeing if the result is greater than 1.

Old solution (227 bytes)

v           v       <
&   >>\:2*3+>"_",1-:|
>&:1`|v ,,"| ",*52:$<   :\<
    #\v         <
     :>" o",,1-:|
     1          >"|",$\1-:|
    \`            @       $
    ^_"o",@>:!    |       2
           ^-1,*95<+3*2,*5<

It might be possible to golf it more. Just look at all that whitespace!

Here's my poor attempt at an explanation in MSPaint picture form:

Code flows in the direction of the arrow.


问:
Golf bit weaving
Note: the first half of this challenge comes from Martin Ender's previous challenge, Visualize Bit Weaving.

The esoteric programming language evil has an interesting operation on byte values which it calls "weaving".

It is essentially a permutation of the eight bits of the byte (it doesn't matter which end we start counting from, as the pattern is symmetric):

Bit 0 is moved to bit 2

Bit 1 is moved to bit 0

Bit 2 is moved to bit 4

Bit 3 is moved to bit 1

Bit 4 is moved to bit 6

Bit 5 is moved to bit 3

Bit 6 is moved to bit 7

Bit 7 is moved to bit 5

For convenience, here are three other representations of the permutation. As a cycle:

```<code>(02467531)
</code>```

As a mapping:

```<code>57361402 -> 76543210 -> 64725031
</code>```

And as a list of pairs of the mapping:

```<code>[[0,2], [1,0], [2,4], [3,1], [4,6], [5,3], [6,7], [7,5]]
</code>```

After 8 weavings, the byte is essentially reset.

For example, weaving the number 10011101 (which is 157 in base 10) will produce 01110110 (which is 118 in base 10).

Input

There are only 256 valid inputs, namely all the integers between 0 and 255 inclusive. That may be taken in any base, but it must be consistent and you must specify it if the base you choose is not base ten.

You may not zero-pad your inputs.

Output

You should output the result of the bit weaving, in any base, which must also be consistent and specified if not base ten.

You may zero-pad your outputs.

Related: Visualize Bit Weaving

答:
Actually, 27 bytes

```<code>'08*+7~@tñiWi┐W13052746k♂└Σ
</code>```

Try it online!

This program does input and output as a binary string (output is zero-padded to 8 bits).

Explanation:

```<code>'08*+7~@tñiWi┐W13052746k♂└Σ
'08*+                        prepend 8 zeroes
     7~@t                    last 8 characters (a[:~7])
         ñi                  enumerate, flatten
           Wi┐W              for each (i, v) pair: push v to register i
               13052746k     push [1,3,0,5,2,7,4,6] (the permutation order, zero-indexed)
                        ♂└   for each value: push the value in that register
                          Σ  concatenate the strings

</code>```

ContentLicense: CC BY-SA 3.0

Title: Golf bit weaving

Body:
Actually, 27 bytes

'08*+7~@tñiWi┐W13052746k♂└Σ

Try it online!

This program does input and output as a binary string (output is zero-padded to 8 bits).

Explanation:

'08*+7~@tñiWi┐W13052746k♂└Σ
'08*+                        prepend 8 zeroes
     7~@t                    last 8 characters (a[:~7])
         ñi                  enumerate, flatten
           Wi┐W              for each (i, v) pair: push v to register i
               13052746k     push [1,3,0,5,2,7,4,6] (the permutation order, zero-indexed)
                        ♂└   for each value: push the value in that register
                          Σ  concatenate the strings


问:
Choose from an existing set of weights to make a target sum
When doing weightlifting, I want to make a specific weight by attaching several plates to a bar.

I have the following plates:

6 plates of 1 kg each

6 plates of 2.5 kg each

6 plates of 5 kg each

6 plates of 10 kg each

The bar itself weighs 10 kg.

It's only allowed to attach the plates in pairs - they are attached at each end of the bar, and the arrangement at the two ends must be completely symmetrical (e.g. attaching two 5-kg plates at one end, and one 10-kg plate at the other end is forbidden for reasons of safety).

Make a program or a function that tells me how many plates of each kind I have to use in order to get a given total weight. The input is an integer greater than 11; the output is a list/array/string of 4 numbers. If it's impossible to combine existing plates to get the target weight, output a zero/empty array, an invalid string, throw an exception or some such.

If there are several solutions, the code must output only one (don't make the user choose - he is too busy with other things).

Test cases:

```<code>12 -> [2 0 0 0] - 2 plates of 1 kg plus the bar of 10 kg
13 -> [0 0 0 0] - a special-case output that means "impossible"
20 -> [0 0 2 0] - 2 plates of 5 kg + bar
20 -> [0 4 0 0] - a different acceptable solution for the above
21 -> [6 2 0 0] - 6 plates of 1 kg + 2 plates of 2.5 kg + bar
28 -> [0 0 0 0] - impossible
45 -> [0 2 6 0] - a solution for a random number in range
112 -> [2 4 6 6] - a solution for a random number in range
121 -> [6 6 6 6] - maximal weight for which a solution is possible
</code>```

If your code outputs the numbers in the opposite order (from the heavy plate to the light one), please specify this explicitly to avoid confusion.

答:
Scala, 202 bytes

Decided Scala doesn't get much love here, so I present a (probably not optimal) solution in Scala.

```<code>def w(i:Int){var w=Map(20->0,10->0,5->0,2->0);var x=i-10;while(x>0){
var d=false;for(a<-w.keys)if(a<=x & w(a)<6 & !d){x=x-a;w=w.updated(a,w(a)+2);d=true;}
if(!d){println(0);return;}}
println(w.values);}
</code>```

The program outputs in reverse order and with extra junk compared to solutions in post. When a solution is not found, prints 0.

Note: I could not remove any of the newlines or spaces because Scala is dumb, so I think to reduce size, the method must be redone unless I missed something obvious.

Body:
Scala, 202 bytes

Decided Scala doesn't get much love here, so I present a (probably not optimal) solution in Scala.

def w(i:Int){var w=Map(20->0,10->0,5->0,2->0);var x=i-10;while(x>0){
var d=false;for(a<-w.keys)if(a<=x & w(a)<6 & !d){x=x-a;w=w.updated(a,w(a)+2);d=true;}
if(!d){println(0);return;}}
println(w.values);}

The program outputs in reverse order and with extra junk compared to solutions in post. When a solution is not found, prints 0.

Note: I could not remove any of the newlines or spaces because Scala is dumb, so I think to reduce size, the method must be redone unless I missed something obvious.


问:
Print a Lego piece
This challenge is a simple ascii-art one. Given two inputs, describing the height and width of a Lego piece, you have print an ASCII art representation of it.

Here is how the Lego pieces are supposed to look:

```<code>(4, 2)

___________
| o o o o |
| o o o o |
-----------

(8, 2)

___________________
| o o o o o o o o |
| o o o o o o o o |
-------------------

(4, 4)

___________
| o o o o |
| o o o o |
| o o o o |
| o o o o |
-----------

(3, 2)

_________
| o o o |
| o o o |
---------

(1, 1)

o
</code>```

If you can't tell from the test-cases, the top and bottom are width*2+3 underscores and dashes, and each row has pipes for the sides, o's for the little things, and everything is separated by spaces.

The only exception for this is (1, 1), which is just a single o.

You will never get 0 for any of the dimensions.

This is code-golf, so shortest code in bytes wins!

var QUESTION_ID=84050,OVERRIDE_USER=31343;function answersUrl(e){return"http://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"http://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="
"+e.body.replace(OVERRIDE_REG,"")+"
")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}</code>```

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

{{PLACE}}	{{NAME}}	{{LANGUAGE}}	{{SIZE}}	Link

{{LANGUAGE}}	{{NAME}}	{{SIZE}}	Link

```

答:
CJam, 34

```<code>'_q~'o*"||"\*S*f*f+'-f+zN*_,H='o@?
</code>```

Try it online

Explanation:

```<code>'_        push a '_' character
q~        read and evaluate the input (height and width)
'o*       repeat the 'o' character <width> times
"||"\*    join the "||" string by the string of o's (putting them in between)
S*        join with spaces (inserting a space between every 2 characters)
f*        repeat each character <height> times, making it a separate string
f+        prepend '_' to each string
'-f+      append '-' to each string
z         transpose the array of strings
N*        join with newlines; lego piece is ready, special case to follow
_,        duplicate the string and get its length
H=        compare with H=17
'o        push 'o' for the true case
@         bring the lego piece to the top for the false case
?         if the length was 17, use 'o' else use the lego piece
</code>```

Title: Print a Lego piece

Body:
CJam, 34

'_q~'o*"||"\*S*f*f+'-f+zN*_,H='o@?

Try it online

Explanation:

'_        push a '_' character
q~        read and evaluate the input (height and width)
'o*       repeat the 'o' character <width> times
"||"\*    join the "||" string by the string of o's (putting them in between)
S*        join with spaces (inserting a space between every 2 characters)
f*        repeat each character <height> times, making it a separate string
f+        prepend '_' to each string
'-f+      append '-' to each string
z         transpose the array of strings
N*        join with newlines; lego piece is ready, special case to follow
_,        duplicate the string and get its length
H=        compare with H=17
'o        push 'o' for the true case
@         bring the lego piece to the top for the false case
?         if the length was 17, use 'o' else use the lego piece


答:
Pyth, 38 bytes

```<code>?t*QJEjb+sm\_K+\|+j\o*dhQ\|+mKJsm\-K\o
</code>```

Test suite.

Title: Print a Lego piece

Body:
This challenge is a simple ascii-art one. Given two inputs, describing the height and width of a Lego piece, you have print an ASCII art representation of it.

Here is how the Lego pieces are supposed to look:

```<code>(4, 2)

___________
| o o o o |
| o o o o |
-----------

(8, 2)

___________________
| o o o o o o o o |
| o o o o o o o o |
-------------------

(4, 4)

___________
| o o o o |
| o o o o |
| o o o o |
| o o o o |
-----------

(3, 2)

_________
| o o o |
| o o o |
---------

(1, 1)

o
</code>```

If you can't tell from the test-cases, the top and bottom are width*2+3 underscores and dashes, and each row has pipes for the sides, o's for the little things, and everything is separated by spaces.

The only exception for this is (1, 1), which is just a single o.

You will never get 0 for any of the dimensions.

This is code-golf, so shortest code in bytes wins!

var QUESTION_ID=84050,OVERRIDE_USER=31343;function answersUrl(e){return"http://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"http://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="
"+e.body.replace(OVERRIDE_REG,"")+"
")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}</code>```

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

{{PLACE}}	{{NAME}}	{{LANGUAGE}}	{{SIZE}}	Link

{{LANGUAGE}}	{{NAME}}	{{SIZE}}	Link

```

Body:
Pyth, 38 bytes

?t*QJEjb+sm\_K+\|+j\o*dhQ\|+mKJsm\-K\o

Test suite.


问:
Rearranging the sequence

Introduction

Let's observe the following sequence (non-negative integers):

```<code>0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, ...
</code>```

For example, let's take the first three numbers. These are 0, 1, 2. The numbers used in this sequence can be ordered in six different ways:

```<code>012   120
021   201
102   210
</code>```

So, let's say that F(3) = 6. Another example is F(12). This contains the numbers:

```<code>0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11
</code>```

Or the concatenated version:

```<code>01234567891011
</code>```

To find the number of ways to rearrange this, we first need to look at the length of this string. The length of this string is 14. So we compute 14!. However, for example the ones can exchange places without disrupting the final string. There are 2 zeroes, so there are 2! ways to exhange the zeroes without disrupting the order. There are also 4 ones, so there are 4! ways to switch the ones. We divide the total by these two numbers:

This has 14! / (4! × 2!) = 1816214400 ways to arrange the string 01234567891011. So we can conclude that F(12) = 1816214400.

The task

Given N, output F(N). For the ones who don't need the introduction. To compute F(N), we first concatenate the first N non-negative integers (e.g. for N = 12, the concatenated string would be 01234567891011) and calculate the number of ways to arrange this string.

Test cases

```<code>Input:   Output:
0        1
1        1
2        2
3        6
4        24
5        120
6        720
7        5040
8        40320
9        362880
10       3628800
11       119750400
12       1816214400
13       43589145600
14       1111523212800
15       30169915776000
</code>```

Note

Computing the answer must be computed within a time limit of 10 seconds, brute-forcing is disallowed.

This is code-golf, so the submission with the least amount of bytes wins!

Title: Rearranging the sequence

Body:
J, 33 bytes

(#(%*/)&:!&x:#/.~)@([:;<@":"0)@i.

Converts the range into a string of digits, counts each digits, and applies the multinomial coefficient to compute the result.

Usage

   f =: (#(%*/)&:!&x:#/.~)@([:;<@":"0)@i.
   (,.f"0) i. 16
 0              1
 1              1
 2              2
 3              6
 4             24
 5            120
 6            720
 7           5040
 8          40320
 9         362880
10        3628800
11      119750400
12     1816214400
13    43589145600
14  1111523212800
15 30169915776000


问:
From Rgb to Cmyk
Given 3 bytes or RGB as input, calculate the nearest CMYK values, and output them.

create either a function with parameters and return value or a program that operates on stdin/stdout

use the color profile of your choice, but provide a reference

input may be either separate numeric values in range [0;255] or a 6 digit hex string

output should be separate numeric values ranging either [0;1] or [0;100]

standard code golf: no loopholes, shortest code wins

extravagant ideas are welcome

sample data:

```<code>input             output
108,174,106       [0.3793103448275862, 0.0, 0.3908045977011494, 0.3176470588235294]
0,0,0             0,0,0,1
170,255,238       33,0,7,0
0x0088ff          1,0.4667,0,0
[250,235,215]     [0,6,14,1.96]
#123456           .7907,.3953,0,.6627
</code>```

Uncalibrated mapping is fine and probably the easiest

No input validation required; floats are allowed (ranging from 0 to 255), but may also be rounded

Output format should be either clearly commented or obvious; i.e.:

CMYK in that order

does not matter if percentage [0;100] or pure numbers [0;1]

Testing should include the trivial example [0,0,0].

This site has the most digits of online tools that I could find. Does anyone know a tool that gives more than 4 digits?

答:
Pyth, <s>24</s> <s>21</s> <s>18</s> <s>24</s> 21 bytes

Life is a round trip, indeed.

```
<s>=cR255Q+mc--1dK-1JeSQJQK</s>
<s>=cR255Q+mc-JeSQdJQ-1J</s>
<s>+mc-JeSQdJQ-1cJ255</s>
<s>+mc-JeSQd+J^T_15Q-1cJ255</s>
+m-1?JeSQcdJ1Q-1cJ255
```

Test suite.

Sample input: 108,174,106

Sample output: [0.3793103448275862, 0.0, 0.3908045977011494, 0.3176470588235294]

Sample input: 0,0,0

Sample output: [0, 0, 0, 1.0]

Formula used:

$$
\begin{cases}
J = max(R,G,B)\\
C = 1-\frac{R}{J}\\
M = 1-\frac{G}{J}\\
Y = 1-\frac{B}{J}\\
K = 1-\frac{J}{255}\\
\end{cases}
$$

Old formula: http://i.stack.imgur.com/ZtPD6.gif

Old formula: http://i.stack.imgur.com/Nqi9F.gif

Title: From Rgb to Cmyk

Body:
Pyth, <s>24</s> <s>21</s> <s>18</s> <s>24</s> 21 bytes

Life is a round trip, indeed.

<s>=cR255Q+mc--1dK-1JeSQJQK</s>
<s>=cR255Q+mc-JeSQdJQ-1J</s>
<s>+mc-JeSQdJQ-1cJ255</s>
<s>+mc-JeSQd+J^T_15Q-1cJ255</s>
+m-1?JeSQcdJ1Q-1cJ255

Test suite.

Sample input: 108,174,106

Sample output: [0.3793103448275862, 0.0, 0.3908045977011494, 0.3176470588235294]

Sample input: 0,0,0

Sample output: [0, 0, 0, 1.0]

Formula used:

$$
\begin{cases}
J = max(R,G,B)\\
C = 1-\frac{R}{J}\\
M = 1-\frac{G}{J}\\
Y = 1-\frac{B}{J}\\
K = 1-\frac{J}{255}\\
\end{cases}
$$

Old formula: http://i.stack.imgur.com/ZtPD6.gif

Old formula: http://i.stack.imgur.com/Nqi9F.gif

ContentLicense: CC BY-SA 4.0


问:
matrix determinant

Calculate the determinant of an n x n matrix.

Rules

read matrix from standard input

write to standard output

do not use ready solutions from library or language

input: columns separated by any space char

input: lines separated by cr and/or lf

Winner

The shortest code :)

Title: matrix determinant

Body:
J, 61 characters

-/>([:+/#(([{.<:@[}.])[:*//._2,\2#])])&.>(|.;])".];._2[1!:1[3

A big ugly bit of code that takes its input from stdin (if you're running this on Windows you may need to change ".];._2[1!:1[3 to ".}:@];._2[1!:1[3 to ensure both character return and line feed are removed).

   -/>([:+/#(([{.<:@[}.])[:*//._2,\2#])])&.>(|.;])".];._2[1!:1[3
1 8 5
2 7 3
9 9 4
_72
   -/>([:+/#(([{.<:@[}.])[:*//._2,\2#])])&.>(|.;])".];._2[1!:1[3
_2 2 3
_1 1 3
2 0 _1
6

Of course, no-one using J would ever bother to do this. They'd just use:

(-/ .*)".];._2[1!:1[3

making use of the . determinant verb.


答:
Dyalog APL, <s>16</s> 15 bytes

```<code>1-⊢(÷,255÷⍨⊢)⌈/
</code>```

1 minus 1-

 X divided by ÷ Y, followed by , 255 dividing 255÷⍨ Y ⊢, where

  X is itself ⊢ (i.e. the list of RGB values), and

  Y is the max /⌈ (of the RGB values).

$$
\begin{cases}
J = max(R,G,B)\\
C = 1-\frac{R}{J}\\
M = 1-\frac{G}{J}\\
Y = 1-\frac{B}{J}\\
K = 1-\frac{J}{255}\\
\end{cases}
$$

TryAPL!

Credits:

 ∘ -1 byte by ngn.

Title: From Rgb to Cmyk

Body:
Given 3 bytes or RGB as input, calculate the nearest CMYK values, and output them.

create either a function with parameters and return value or a program that operates on stdin/stdout

use the color profile of your choice, but provide a reference

input may be either separate numeric values in range [0;255] or a 6 digit hex string

output should be separate numeric values ranging either [0;1] or [0;100]

standard code golf: no loopholes, shortest code wins

extravagant ideas are welcome

sample data:

```<code>input             output
108,174,106       [0.3793103448275862, 0.0, 0.3908045977011494, 0.3176470588235294]
0,0,0             0,0,0,1
170,255,238       33,0,7,0
0x0088ff          1,0.4667,0,0
[250,235,215]     [0,6,14,1.96]
#123456           .7907,.3953,0,.6627
</code>```

Uncalibrated mapping is fine and probably the easiest

No input validation required; floats are allowed (ranging from 0 to 255), but may also be rounded

Output format should be either clearly commented or obvious; i.e.:

CMYK in that order

does not matter if percentage [0;100] or pure numbers [0;1]

Testing should include the trivial example [0,0,0].

This site has the most digits of online tools that I could find. Does anyone know a tool that gives more than 4 digits?

Body:
Dyalog APL, <s>16</s> 15 bytes

1-⊢(÷,255÷⍨⊢)⌈/

1 minus 1-

 X divided by ÷ Y, followed by , 255 dividing 255÷⍨ Y ⊢, where

  X is itself ⊢ (i.e. the list of RGB values), and

  Y is the max /⌈ (of the RGB values).

$$
\begin{cases}
J = max(R,G,B)\\
C = 1-\frac{R}{J}\\
M = 1-\frac{G}{J}\\
Y = 1-\frac{B}{J}\\
K = 1-\frac{J}{255}\\
\end{cases}
$$

TryAPL!

Credits:

 ∘ -1 byte by ngn.


答:
APL, 40 bytes

```<code>{2×(4⍴4)⊤⍵⍳⍨10+2×,⊃∘.+/↓1 2.5 5 10∘.×⍳4}
</code>```

In ⎕IO←0. In English:

10+2×,∘.+⌿1 2.5 5 10∘.×⍳4: build the array of all the possible weights, by computing the 4D outer sum of the weights per weight type;

⍵⍳⍨: search the index of the given. If not found the index is 1+the tally of the array at step 1;

(4⍴4)⊤: represent the index in base 4, that is, compute the coordinate of the given weigth in the 4D space;

2×: bring the result to problem space, where the coordinates should be interpreted as half the number of the plates.

Example:
              {2×(4⍴4)⊤⍵⍳⍨10+2×,⊃∘.+/↓1 2.5 5 10∘.×⍳4}112
    2 4 6 6

Bonus: since APL is an array language, several weights can be tested at once. In this case the result is transposed:

```<code>      {2×(4⍴4)⊤⍵⍳⍨10+2×,⊃∘.+/↓1 2.5 5 10∘.×⍳4}12 13 20 21 28 45 112 121
2 0 0 6 0 0 2 6
0 0 0 2 0 2 4 6
0 0 2 0 0 2 6 6
0 0 0 0 0 2 6 6
</code>```

Title: Choose from an existing set of weights to make a target sum

Body:
When doing weightlifting, I want to make a specific weight by attaching several plates to a bar.

I have the following plates:

6 plates of 1 kg each

6 plates of 2.5 kg each

6 plates of 5 kg each

6 plates of 10 kg each

The bar itself weighs 10 kg.

It's only allowed to attach the plates in pairs - they are attached at each end of the bar, and the arrangement at the two ends must be completely symmetrical (e.g. attaching two 5-kg plates at one end, and one 10-kg plate at the other end is forbidden for reasons of safety).

Make a program or a function that tells me how many plates of each kind I have to use in order to get a given total weight. The input is an integer greater than 11; the output is a list/array/string of 4 numbers. If it's impossible to combine existing plates to get the target weight, output a zero/empty array, an invalid string, throw an exception or some such.

If there are several solutions, the code must output only one (don't make the user choose - he is too busy with other things).

Test cases:

```<code>12 -> [2 0 0 0] - 2 plates of 1 kg plus the bar of 10 kg
13 -> [0 0 0 0] - a special-case output that means "impossible"
20 -> [0 0 2 0] - 2 plates of 5 kg + bar
20 -> [0 4 0 0] - a different acceptable solution for the above
21 -> [6 2 0 0] - 6 plates of 1 kg + 2 plates of 2.5 kg + bar
28 -> [0 0 0 0] - impossible
45 -> [0 2 6 0] - a solution for a random number in range
112 -> [2 4 6 6] - a solution for a random number in range
121 -> [6 6 6 6] - maximal weight for which a solution is possible
</code>```

If your code outputs the numbers in the opposite order (from the heavy plate to the light one), please specify this explicitly to avoid confusion.

Body:
APL, 40 bytes

{2×(4⍴4)⊤⍵⍳⍨10+2×,⊃∘.+/↓1 2.5 5 10∘.×⍳4}

In ⎕IO←0. In English:

10+2×,∘.+⌿1 2.5 5 10∘.×⍳4: build the array of all the possible weights, by computing the 4D outer sum of the weights per weight type;

⍵⍳⍨: search the index of the given. If not found the index is 1+the tally of the array at step 1;

(4⍴4)⊤: represent the index in base 4, that is, compute the coordinate of the given weigth in the 4D space;

2×: bring the result to problem space, where the coordinates should be interpreted as half the number of the plates.

Example:
              {2×(4⍴4)⊤⍵⍳⍨10+2×,⊃∘.+/↓1 2.5 5 10∘.×⍳4}112
    2 4 6 6

Bonus: since APL is an array language, several weights can be tested at once. In this case the result is transposed:

      {2×(4⍴4)⊤⍵⍳⍨10+2×,⊃∘.+/↓1 2.5 5 10∘.×⍳4}12 13 20 21 28 45 112 121
2 0 0 6 0 0 2 6
0 0 0 2 0 2 4 6
0 0 2 0 0 2 6 6
0 0 0 0 0 2 6 6


问:
Calculate the sum of ILD

Input:

An integer

Output:

Sum of the input itself + the length of the input + each individual digit of the input.

```<code>nr + nr-length + {sum of digits} = output
</code>```

Examples:

Input: 99

Output: 99 (nr) + 2 (nr-length) + (9 + 9) (digits) → 119

Input: 123

Output: 123 + 3 + (1 + 2 + 3) → 132

Challenge rules:

The input can also contain negative input, which are resolved special. The -/minus-sign is also +1 for the length, and is part of the first digit.

For example:

Input: -123

Output: -123 + 4 + (-1 + 2 + 3) → -115

You can assume that the input nor output will ever be outside the range of an (32-bit) integer.

General rules:

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

Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.

Standard rules apply for your answer, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call.

Default Loopholes are forbidden.

If possible, please add a link with a test for your code.

Also, please add an explanation if necessary.

Test cases:

```<code>87901 → 87931
123 → 132
99 → 119
5 → 11
1 → 3
0 → 1
-3 → -4
-123 → -115
-900 → -905
-87901 → -87886
</code>```

Semi-related: Count Sum of all Digits

答:
Brachylog, <s>35</s> 32 bytes

```
<s>lL,?:ef+:?:L+I,(0>?h:2*:Ir-:1+.;I.)</s>
lL,(0>?h:1--I;I0),?b:ef+:?:L:I+.
```

Explanation

```<code>lL,             L is the length of the Input
(
    0>?         Input < 0
       h:1--I   I is (First digit - 1) * -1
;               Or
    I0          I is 0
),
?b:ef+          Sum all digits of the Input
      :?:L:I+.  Output = sum of digits + (Input minus first digit) + L + I
</code>```

Title: Calculate the sum of ILD

Body:
Brachylog, <s>35</s> 32 bytes

<s>lL,?:ef+:?:L+I,(0>?h:2*:Ir-:1+.;I.)</s>
lL,(0>?h:1--I;I0),?b:ef+:?:L:I+.

Explanation

lL,             L is the length of the Input
(
    0>?         Input < 0
       h:1--I   I is (First digit - 1) * -1
;               Or
    I0          I is 0
),
?b:ef+          Sum all digits of the Input
      :?:L:I+.  Output = sum of digits + (Input minus first digit) + L + I


答:
05AB1E, <s>28</s> <s>20</s> <s>18</s> 8 bytes

```<code>ÐgsS'+ýO
</code>```

Explanation

```<code>Ð           # triplicate input
 g          # get length of input
  sS'+ý     # split input and merge with '+' as separator
       O    # sum and implicitly display
</code>```

Try it online

Saved 10 bytes thanks to @Adnan

Title: Calculate the sum of ILD

Body:
Input:

An integer

Output:

Sum of the input itself + the length of the input + each individual digit of the input.

```<code>nr + nr-length + {sum of digits} = output
</code>```

Examples:

Input: 99

Output: 99 (nr) + 2 (nr-length) + (9 + 9) (digits) → 119

Input: 123

Output: 123 + 3 + (1 + 2 + 3) → 132

Challenge rules:

The input can also contain negative input, which are resolved special. The -/minus-sign is also +1 for the length, and is part of the first digit.

For example:

Input: -123

Output: -123 + 4 + (-1 + 2 + 3) → -115

You can assume that the input nor output will ever be outside the range of an (32-bit) integer.

General rules:

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

Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.

Standard rules apply for your answer, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call.

Default Loopholes are forbidden.

If possible, please add a link with a test for your code.

Also, please add an explanation if necessary.

Test cases:

```<code>87901 → 87931
123 → 132
99 → 119
5 → 11
1 → 3
0 → 1
-3 → -4
-123 → -115
-900 → -905
-87901 → -87886
</code>```

Semi-related: Count Sum of all Digits

Body:
05AB1E, <s>28</s> <s>20</s> <s>18</s> 8 bytes

ÐgsS'+ýO

Explanation

Ð           # triplicate input
 g          # get length of input
  sS'+ý     # split input and merge with '+' as separator
       O    # sum and implicitly display

Try it online

Saved 10 bytes thanks to @Adnan


答:
Java 8, <s>174</s> <s>136</s> <s>122</s> <s>107</s> <s>105</s> <s>93</s> 78 bytes

i->{int f=0;for(int j:(i+"").getBytes())i+=j<48?f++:f-->0?50-j:j-47;return i;}
```
<p>-14 bytes thanks to <em>@LeakyNun</em>.<br />
-15 bytes thanks to <em>@cliffroot</em>.</p>
<p><strong>Explanation:</strong></p>
<p>Try it online.</p>
<pre class="lang-java prettyprint-override"><code>i->{                   // Method with integer as both parameter and return-type
  int f=0;             //  Integer-flag, starting at 0
  for(int j:(i+"").getBytes())
                       //  Loop over the digits as bytes
    i+=                //   Increase the input with:
       j<48?           //    If the current byte is '-':
        f++            //     Increase the input with the flag-integer `f` (which is 0),
                       //     and increase the flag-integer `f` by 1 afterwards
       :               //    Else:
        f-->0?         //     If the flag-integer `f` is 1,
                       //     and decrease the flag-integer `f` back to 0 afterwards
         50-j          //      Increase it with 50 minus the current byte
        :              //    Else
         j-47;         //     Increase it with the byte as digit
                       //      + 1 to cover for the length part in ILD
  return i;}           //  Return the modified input as result
</code>```

Title: Calculate the sum of ILD

Body:
Java 8, <s>174</s> <s>136</s> <s>122</s> <s>107</s> <s>105</s> <s>93</s> 78 bytes

i->{int f=0;for(int j:(i+"").getBytes())i+=j<48?f++:f-->0?50-j:j-47;return i;}

-14 bytes thanks to @LeakyNun.

-15 bytes thanks to @cliffroot.

Explanation:

Try it online.

i->{                   // Method with integer as both parameter and return-type
  int f=0;             //  Integer-flag, starting at 0
  for(int j:(i+"").getBytes())
                       //  Loop over the digits as bytes
    i+=                //   Increase the input with:
       j<48?           //    If the current byte is '-':
        f++            //     Increase the input with the flag-integer `f` (which is 0),
                       //     and increase the flag-integer `f` by 1 afterwards
       :               //    Else:
        f-->0?         //     If the flag-integer `f` is 1,
                       //     and decrease the flag-integer `f` back to 0 afterwards
         50-j          //      Increase it with 50 minus the current byte
        :              //    Else
         j-47;         //     Increase it with the byte as digit
                       //      + 1 to cover for the length part in ILD
  return i;}           //  Return the modified input as result


答:
CJam, 18

```<code>q_,\~__Ab(@g*\~]:+
</code>```

Try it online

Explanation:

```<code>q_      read the input and make a copy
,\      get the string length and swap with the other copy
~__     evaluate the number and make 2 copies
Ab      convert to base A=10 (array of digits), it uses the absolute value
(       take out the first digit
@g*     get a copy of the number, get its sign and multiply with the digit
\~      dump the other digits on the stack
]:+     add everything together
</code>```

Title: Calculate the sum of ILD

Body:
CJam, 18

q_,\~__Ab(@g*\~]:+

Try it online

Explanation:

q_      read the input and make a copy
,\      get the string length and swap with the other copy
~__     evaluate the number and make 2 copies
Ab      convert to base A=10 (array of digits), it uses the absolute value
(       take out the first digit
@g*     get a copy of the number, get its sign and multiply with the digit
\~      dump the other digits on the stack
]:+     add everything together


Body:
JavaScript (ES6), 109 bytes

n=>`000${[...Array(256)].findIndex((_,i)=>i+(i&48)*9+(i&12)*79+(i&3)*639+320==n*32).toString(4)*2}`.slice(-4)

Returns 00-2 on error. Alternative solution that returns undefined on error, also 109 bytes:

n=>[...Array(256)].map((_,i)=>`000${i.toString(4)*2}`.slice(-4)).find(s=>+s[0]+s[1]*2.5+s[2]*5+s[3]*10+10==n)


问:
Solve the 15 Puzzle (the tile-sliding puzzle)
The 15 Puzzle is a famous puzzle involving sliding 15 tiles around on a 4x4 grid. Starting from a random configuration, the goal is to arrange the tiles in the correct order. Here is an example of a solved 15 Puzzle:

```<code>01 02 03 04
05 06 07 08
09 10 11 12
13 14 15
</code>```

Each move on the puzzle is of the form Up/Down/Left/Right. The move "Down" consists of sliding the tile that is above the empty spot downward. The move "Right" consists of sliding a tile to the right, into the empty spot. Here is how the board looks after the moves Down and Right.

```<code>01 02 03 04
05 06 07 08
09 10    11
13 14 15 12
</code>```

The goal of this challenge is to write a program that can output the series of moves needed to solve the 15 Puzzle. The winner is the program who solves the five test cases (below) in the fewest total moves. The generated solution does not need to be a perfect solution, it merely has to be better than the competitors. For each individual test case, the program should not take more than ten seconds on a reasonable machine.

Your program must be able to solve any puzzle that is solvable, I'm just using these five test cases as the scoring.

Your program will receive the unsolved 15 Puzzle as input in the format of a 2D array. The 2D array can be formatted according to the language used, or changed if the language does not have 2D arrays. The first element of the first sub-array will be the number in the upper left, and the last element of the first sub-array will be the number in the upper right. A 0 will be the empty space.

As output, your program should print a list of moves in the order that they need to be performed. Each step should be numbered in order to increase the usability of the results.

EDIT: Based on comments, I will allow output to be in either the form of Down/Up/etc or in the form of the coordinates of the piece to move. As this is not code golf, the most important part is to solve the puzzle.

Some other general rules involve no using an outside source, etc.

Test Case 1

```<code>([5,1,7,3],[9,2,11,4],[13,6,15,8],[0,10,14,12])
</code>```

Example Output:

```<code>1: Down
2: Down
3: Down
4: Left
....
</code>```

Test Case 2

```<code>([2,5,13,12],[1,0,3,15],[9,7,14,6],[10,11,8,4])
</code>```

Test Case 3

```<code>([5,2,4,8],[10,0,3,14],[13,6,11,12],[1,15,9,7])
</code>```

Test Case 4

```<code>([11,4,12,2],[5,10,3,15],[14,1,6,7],[0,9,8,13])
</code>```

Test Case 5

```<code>([5,8,7,11],[1,6,12,2],[9,0,13,10],[14,3,4,15])
</code>```

答:
I started working on this problem and wanted to contribute with my code so far.
As stated by Gareth, the problem is comparable to the 8-tile puzzle and so the code is based on the magnificient solution of Keith Randall and thus in Python.
This solution can solve all 5 test cases with a total sum of less than 400 moves, and other puzzles, too. It contains an optimized and a brute force solution. The code is a bit bloated by now. Output is abbrevated like "llururd.." Hope its helpful.
http://www.penschuck.org/joomla/tmp/15Tile.txt (explanation)
http://www.penschuck.org/joomla/tmp/tile15.txt (python code)

# Author: Heiko Penschuck
# www.penschuck.org
# (C) 2012

# import os;os.chdir('work')
# os.getcwd()

# def execfile(file, globals=globals(), locals=locals()):
#   with open(file, "r") as fh: exec(fh.read()+"\n", globals, locals)
#
#
# execfile("tile15.py");
#
## run these
# solve_brute();
# solve();

# some boards to play with
board2=(15,14,7,3,13,10,2,9,11,12,4,6,5,0,1,8);
# best: 76(52)
#    72(56)
#   68(51)      uurddlurrulldrrdllluuruldrddlururulddruurdllldrurddlurdruuldrdluurdd

board3=(13, 8, 9, 4, 15, 11, 5, 3, 14, 6, 12, 7, 1, 10, 2, 0)
# best: 106(77)
#best: 90(64)   ullldruuldrrdrlluurulldrrdldluruulddrulurrdrddlluuurdldrrulddrulldrurullldrdluurrrddllurdr

board4=(4, 8, 12, 1, 13, 7, 3, 11, 9, 15, 6, 14, 5, 2, 10, 0) ;# best  100(74)

board5=(15,2,3,4,5,6,7,8,9,10,11,12,13,1,14,0); # best 44(32)
board6=( 1, 2,  3,  4, 6, 11,  0, 12, 8, 14,  9, 13, 5, 10,  7, 15);

# testcases
board7=(5,1,7,3,9,2,11,4,13,6,15,8,0,10,14,12); #   15 (7)
board8=(2,5,13,12,1,0,3,15,9,7,14,6,10,11,8,4); #  124 (94)
board9=(5,2,4,8,10,0,3,14,13,6,11,12,1,15,9,7) ; #  72 (56)
board10=(11,4,12,2,5,10,3,15,14,1,6,7,0,9,8,13) ;# 71 (57)
board11=(5,8,7,11,1,6,12,2,9,0,13,10,14,3,4,15) ;# 99 (73)

board12=(1,2,3,4,5,6,7,8,9,10,11,12,13,0,14,15); #pretty simple board
board13=(4, 10, 5, 12, 11, 7, 15, 2, 13, 1, 14, 8, 6, 3, 9, 0)

board=board3 ; # used by solve()
bboard=list(board) ;# used by solve_brute()

# init
clean=(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,0)
i=0;
solution={};
invsolution={};
E={board:0}

# derived from Keith Randall 8-tile solution
# a: a board, d: offset to move from i: index in board
def Y(a,d,i):
 b=list(a); # b is now an indexable board
 b[i],b[i+d]=b[i+d],0; # make a move (up down left right)
 b=tuple(b); # now back to searchable
 if b not in E:E[b]=a;# store new board in E

def Calc():
 ii=0;
 # memory error when x is 21
 for x in ' '*14:
  if ii>10:
   print(ii);
  ii+=1
  for a in E.copy():
   # for all boards, make possible moves (up,left,right,down) and store the new boards
   i=list(a).index(0)
   if i>3:Y(a,-4,i)
   if i%4:Y(a,-1,i)
   if i%4 <3:Y(a,1,i)
   if i<12:Y(a,4,i)

def weigh(a,goal):
    factor=[26,8,4,6, 8,8,4,4, 4,4,1,1, 3,2,1,0]
    weight=0;
    for element in a:
        i=list(a).index(element);
        ix,iy=divmod(i,4); # ist
        if element == 0:
            # special for gap
            weight=weight+ix;
            #weight+=(ix+iy)
            continue;
        i=list(a).index(element);
        ix,iy=divmod(i,4); # ist
        j=list(goal).index(element);
        sx,sy=divmod(j,4); # soll
        #k=list(a).index(0); # gap
        #kx,ky=divmod(k,4)
        # try solving from topleft to bottom right (because clean board has gap at bottomright)
        tmp= abs(sx-ix)*abs(sx-ix)*factor[j]+ abs(sy-iy)*abs(sy-iy)*factor[j]
        #tmp += ((sx!=ix )& (sy!=iy)) *(4-sx)*(4-sy)*4
        weight+=tmp
        #(10-sx-sy-sy)
        # 8*abs(sx-ix) + (16-j)*(sx!=ix)
        #print('%2d   %2d_%2d (%2d_%2d)=> %d'%(element,i,j,(sx-ix),(sy-iy),weight))
    return weight

# read numbers seperated by a whitespace
def readboard():
    global E,D,board,clean,i
    reset()
    g=[]
    for x in' '*4:g+=map(int,input().split())
    board=tuple(g)

# read 'a' till 'o'
def readasciiboard():
    global E,D,board,clean,i
    trans={"0":0,"a":1,"b":2,"c":3,"d":4,"e":5,"f":6,"g":7,"h":8,"i":9,"j":10,"k":11,"l":12,"m":13,"n":14,"o":15}
    reset()
    g=[]
    vec=tuple(input().split());
    for x in vec: g.append(trans[x])
    board=tuple(g)

def printasciiboard(a):
    trans={"0":0,"a":1,"b":2,"c":3,"d":4,"e":5,"f":6,"g":7,"h":8,"i":9,"j":10,"k":11,"l":12,"m":13,"n":14,"o":15}
    itrans={}
    for x in trans: itrans[trans[x]]=x
    g=[]
    for x in a: g.append(itrans[x])
    for i in(0,4,8,12): print('%s %s %s %s'%tuple(g[i:i+4]))

# find the board with the smallest weight
def minimum():
    global minn,E,clean
    minn=1111111;# start with a huge number
    qq=board
    for q in E:
        if weigh(q,clean) < minn:
            minn=weigh(q,clean)
            qq=q
    return qq

# run this and printsolution()
# (you might have to reverse the order of the printed solution)
def solve():
    global start,board,E,clean,minn,solution
    start=board;
    solution={};
    E={ board:0 }
    for x in range(0,11):
        Calc(); # walks all possible moves starting from board to a depth of 10~20 moves
        if clean in E:
            print('Solution found')
            q=clean;
            tmp=[];
            while q:
                tmp.append(q)
                q=E[q]
            for x in reversed(tmp):
                solution[len(solution)]=x;
            printsolution();
            return
        q=minimum();  # calculates the "weight" for all Calc()-ed boards and returns the minimum
        #print("Len %3d"%len(E))
        print("weight %d"%minn)
#       stitch solution
        newboard=q;
        tmp=[];
        while q:
            tmp.append(q)
            q=E[q]
        for x in reversed(tmp):
            solution[len(solution)]=x;
        board=newboard;
        E={board:0}; #reset the Calc()-ed boards
    print("No Solution")

# collects and prints the moves of the solution
# from clean board to given board
# (you have to reverse the order)
def printsolution():
    global invsolution,solution,moves,clean,start
    moves=""
    g=start; # start from board to clean
    y=g
    #invsolution[clean]=0;
    for x in solution:
        # uncomment this if you want to see each board of the solution
        #print(g);
        g=solution[x];
        #sys.stdout.write(transition(y,g))
        if (transition(g,y)=="E"): continue
        moves+=transition(g,y)
        # or as squares
        #print('%10s %d %s'%("step",len(moves),transition(g,y)));
        #print(" %s -- %s "%(y,g))
        #for i in(0,4,8,12): print('%2d %2d %2d %2d'%g[i:i+4])
        y=g
    llen=len(moves)
    print(" moves%3d "%llen)
    print(moves)
    # processing moves. funny, but occysionally ud,du,lr or rl appears due to the stitching
    while 'lr' in moves:
        a,b,c=moves.partition('lr')
        moves=a+c
        llen-=2
    while 'rl' in moves:
        a,b,c=moves.partition('rl')
        moves=a+c
        llen-=2
    while 'ud' in moves:
        a,b,c=moves.partition('ud')
        moves=a+c
        llen-=2
    while 'du' in moves:
        a,b,c=moves.partition('du')
        moves=a+c
        llen-=2
    # processing moves. concatenating lll to 3l
    while 'lll' in moves:
        a,b,c=moves.partition('lll')
        moves=a+' 3l '+c
        llen-=2
    while 'rrr' in moves:
        a,b,c=moves.partition('rrr')
        moves=a+' 3r '+c
        llen-=2
    while 'uuu' in moves:
        a,b,c=moves.partition('uuu')
        moves=a+' 3u '+c
        llen-=2
    while 'ddd' in moves:
        a,b,c=moves.partition('ddd')
        moves=a+' 3d '+c
        llen-=2

    while 'll' in moves:
        a,b,c=moves.partition('ll')
        moves=a+' 2l '+c
        llen-=1
    while 'rr' in moves:
        a,b,c=moves.partition('rr')
        moves=a+' 2r '+c
        llen-=1
    while 'uu' in moves:
        a,b,c=moves.partition('uu')
        moves=a+' 2u '+c
        llen-=1
    while 'dd' in moves:
        a,b,c=moves.partition('dd')
        moves=a+' 2d '+c
        llen-=1
    print(" processed:%3d "%llen)
    print(moves)

    return

def transition(a,b):
    # calculate the move (ie up,down,left,right)
    # between 2 boards (distance of 1 move and a weight of 1 only)
    i=list(a).index(0);
    j=list(b).index(0);
    if (j==i+1): return "l"
    if (j==i-1): return "r"
    if (j==i-4): return "d"
    if (j==i+4): return "u"
    #print("transition not possible")
    return "E"

###################################################

# below this line are functions for the brute force solution only
# added for comparision
#
# its using a global variable bboard and works destructively on it

def solve_brute():
    global bboard,board;
    bboard=list(board); # working copy
    move(1,0);move(2,1);
    move(3,14); # <== additional move, move 3 out of way
    move(4,2);move(3,6);
    gap_down();gap_down();gap_right();gap_right();gap_up();gap_up();gap_up();gap_left();gap_down();
    #first line solved
    print("first line");printbboard();
    move(5,4);move(6,5);move(7,14);move(8,6);move(7,10);
    gap_down();gap_down();gap_right();gap_right();gap_up();gap_up();gap_left();gap_down();
    #second line solved (upper half)
    print("2nd line");printbboard();
    move(9,15);move(13,8);move(9,9)
    gap_down();gap_left();gap_left();gap_up();gap_right();
    print("left border");printbboard();
    #left border solved
    move(10,15);move(14,9);move(10,10);
    gap_down();movegap(1+3*4);gap_up();gap_right();
    print("left half");printbboard();
    #left half solved

    #rotating last 4 tiles 5 times
    for x in ' '*5:
        gap_right();gap_down(); # gap is now on 15
        if (bboard==[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,0]):
            print("solution found");printbboard();
            return;
        gap_left();gap_up();
    print("No solution found");
    printbboard();
    return

def printbboard():
    global bboard
    for i in(0,4,8,12): print('%2d %2d %2d %2d'%tuple(bboard[i:i+4]))

def gap_up():
    global bboard
    i=bboard.index(0);
    if (i<4):
        print("Err up()")
        return
    bboard[i],bboard[i-4] = bboard[i-4] , 0 ;

def gap_down():
    global bboard
    i=bboard.index(0);
    if (i>11):
        print("Err down()")
        return
    bboard[i],bboard[i+4] = bboard[i+4] , 0 ;

def gap_left():
    global bboard
    i=bboard.index(0);
    if (i%4<1):
        print("Err left()")
        return
    bboard[i],bboard[i-1]= bboard[i-1] , 0 ;

def gap_right():
    global bboard
    i=bboard.index(0);
    if (i%4>2):
        print("Err right()")
        return
    bboard[i],bboard[i+1] = bboard[i+1] , 0 ;

def movegap(d):
    global bboard;
    # d: destination location (0-15)
    k=bboard.index(0);
    ky,kx=divmod(k,4);
    dy,dx=divmod(d,4);
    # moving the gap
    while (ky>dy):
        gap_up();ky-=1;
    while (ky<dy):
        gap_down();ky+=1;
    while (kx>dx):
        gap_left();kx-=1;
    while (kx<dx):
        gap_right();kx+=1;

def move(s,d):
    global bboard
    i=bboard.index(s);
    iy,ix=divmod(i,4);
    dy,dx=divmod(d,4);
    #moving a number
    while (ix<dx):
        move1right(s);
        print("1right ");
        ix+=1;
    while (ix>dx):
        move1left(s);
        ix-=1;
        print("1left ");
    while(iy<dy):
        move1down(s);
        print("1down ");
        iy+=1;
    while(iy>dy):
        move1up(s);
        print("1up");
        iy-=1;

def move1up(s):
    global bboard
    i=bboard.index(s);
    iy,ix=divmod(i,4);
    k=bboard.index(0);
    ky,kx=divmod(k,4);
    if (ky<iy):
        # above: move 1 above, then leftorright, then 1 down
        movegap(kx+4*(iy-1))
        movegap(ix+4*(iy-1))
        movegap(ix+4*iy)
        return; # fin
    if (ky==iy):
        # if equal, then first try 1 down
        # (not nescessary if gap is right of s)
        if (kx<ix):
            if (ky<=2):
                movegap(kx+4*(iy+1))
                movegap(ix+1+4*(iy+1)); # 1right 1down of s
                movegap(ix+1+4*(iy-1)); # 1right 1up of s
                movegap(ix+4*(iy-1));# right over s
                gap_down(); # fin
                return;
            # bottom border, must go up first
            movegap(kx+4*(iy-1));
            movegap(ix+4*(iy-1));
            gap_down();
            return; # fin
        else:
            movegap(ix+1+4*iy); # move 1 right of s
            gap_up()
            gap_left()
            gap_down();
            return; # fin
    movegap(ix+1+4*ky); # move 1 right of s
    movegap(ix+1+4*(iy+1)); # move 1 right and 1 down of s
    gap_up();
    gap_up();
    gap_left();
    gap_down();

def move1left(s):
    global bboard
    i=bboard.index(s);
    iy,ix=divmod(i,4);
    k=bboard.index(0);
    ky,kx=divmod(k,4);
    if (ky<iy):
        # if above gap move 1 over s
        if (kx<ix):
            movegap(kx+4*iy);
            movegap(ix+4*iy);
            return;# fin
        if (kx==ix):
            #gap over s
            if (ix<3):
                # try to move under s and then left
                if (iy<3):
                    movegap(ix+1+4*ky)
                    movegap(ix+1+4*(iy+1))
                    movegap(ix-1+4*(iy+1))
                    movegap(ix-1+4*iy)
                    movegap(ix+4*iy)
                    return; #fin
            # have to move left
            movegap(kx-1+4*ky)
            movegap(ix-1+4*iy)
            movegap(ix+4*iy)
            return;# fin
        # move 1 right of s
        if (iy==3):
            # cant go under, have to go left over
            movegap(kx+4*(iy-1))
            movegap(ix-1+4*(iy-1))
            movegap(ix-1+4*iy)
            movegap(ix+4*iy);
            return; #fin
        movegap(ix+1+4*(iy-1))
        gap_down();gap_down();gap_left();gap_left();gap_up();gap_right();
        return; #fin
    if (ky==iy):
        if (kx<ix):
            movegap(ix-1+4*iy)
            gap_right();
            return; # fin
        if (ky<3):
            gap_down();
            ky+=1;
        else:
            #have to move up
            movegap(ix+4*(iy-1))
            movegap(ix-1+4*(iy-1))
            movegap(ix-1+4*iy)
            gap_right();
            return; #fin
    # gap below s
    movegap(ix+4*(iy+1));
    gap_left();gap_up();gap_right();

def move1right(s):
    global bboard
    i=bboard.index(s);
    iy,ix=divmod(i,4);
    k=bboard.index(0);
    ky,kx=divmod(k,4);
    if (ky<iy):
        if (kx==ix):
            movegap(kx+1+4*ky)
            movegap(kx+1+4*iy)
            movegap(ix+4*iy);
            return; #fin
        movegap(kx+4*iy)
        if (kx>ix):
            movegap(ix+4*iy);
            return; #fin
        movegap(kx+4*(iy+1))
        movegap(ix+1+4*(iy+1))
        movegap(ix+1+4*iy);
        movegap(ix+4*iy);
        return; #fin
    if (ky==iy):
        if (kx<ix):
            if (ky>2):
                # bottom row, left of s, have to move 1 up
                gap_up()
                # move 1 right 1 up of s
                movegap(ix+1+4*(ky-1));
                gap_down()
                gap_left()
                return; # fin
            # first 1 down
            movegap(kx+4*(ky+1))
            # to the right of s
            movegap(ix+1+4*(ky+1))
            gap_up()
            gap_left()
            return; # fin
        # already 1 right of s
        movegap(ix+4*iy);
        return; #fin
    # move gap 1 right and 1 down of s
    movegap(kx+4*(iy+1))
    movegap(ix+1+4*(iy+1))
    gap_up();
    gap_left();

def move1down(s):
    global bboard
    i=bboard.index(s);
    iy,ix=divmod(i,4);
    k=bboard.index(0);
    ky,kx=divmod(k,4);
    if (ky<iy):
        # gap is over s, move it below
        if (kx==ix):
            if (ix>2):
                # right border, have to move 1 to the left
                movegap(kx+4*(iy-1))
                movegap(kx-1+4*(iy-1))
                movegap(kx-1+4*(iy+1))
                gap_up();
                return; #fin
            # move right of s
            movegap(kx+4*(iy-1))
            movegap(kx+1+4*(iy-1))
            movegap(kx+1+4*(iy+1))
            movegap(kx+4*(iy+1))
            gap_up(); #fin
        movegap(kx+4*(iy+1))
        movegap(ix+4*(iy+1))
        gap_up(); #fin
    if (ky==iy):
        gap_down();
        ky+=1;
    # gap is below s, move 1 under s
    movegap(ix+4*(iy+1))
    gap_up();
    #fin
```


Title: Print a Lego piece

Body:
JavaScript ES6, <s>134</s> 124 Bytes

function p(e,n){r='repeat';e*n-1?x="_"[r](2*e+3)+"\n"+("|"+" o"[r](e)+" |\n")[r](n)+"-"[r](2*e+3)+"\n":x="o",console.log(x)}


答:
Pyth, <s>11</s> 10 bytes

Thanks to @LeakyNun for a byte!

```<code>++vj\+`Ql`
</code>```

Test suite

Explanation

```
++vj\+`Ql`QQ  # Q = input, last two implicitly added

  vj\+`Q      # Join the input on '+' and eval it
        l`Q   # Length of the input
           Q  # The input itself
++            # Add those three values to obtain the result
```

Title: Calculate the sum of ILD

Body:
Pyth, <s>11</s> 10 bytes

Thanks to @LeakyNun for a byte!

++vj\+`Ql`

Test suite

Explanation

++vj\+`Ql`QQ  # Q = input, last two implicitly added

  vj\+`Q      # Join the input on '+' and eval it
        l`Q   # Length of the input
           Q  # The input itself
++            # Add those three values to obtain the result


答:
Python 2, 39 bytes

lambda x:x+len(`x`)+eval("+".join(`x`))
```

Test suite

Using the same eval-trick as in my Pyth-answer.

Title: Calculate the sum of ILD

Body:
Python 2, 39 bytes

lambda x:x+len(`x`)+eval("+".join(`x`))

Test suite

Using the same eval-trick as in my Pyth-answer.


问:
Generalised Array Riffle
A simple golf to start the week! You're given three arrays: the base array B, the value array V and the index array I. You should produce another array where the values from V are inserted into B at the indices specified by I. Here is an example:

```<code>Base:    [5, 1, 4, 1, 3]
Values:  [0, 0, 7]
Indices: [5, 0, 3]
</code>```

The indices point at the following positions in the base array:

```<code>[ 5, 1, 4, 1, 3 ]
 ^        ^    ^
 0        3    5
</code>```

So inserting the corresponding elements from the value array, the result should be:

```<code>[0, 5, 1, 4, 7, 1, 3, 0]
</code>```

Rules

You may write a program or function, taking input via STDIN (or closest alternative), command-line arguments or function arguments and output the result via STDOUT (or closest alternative), function return value, or by modifying the array given as the B parameter.

If your submission is a function, I and V can be modified in any way, as well as B if it isn't used for output.

You may make the following assumptions about the input:

All elements of the base and value array will be non-negative integers.

The value array will have at most one more element than the base array.

The value array and index array will have the same number of elements.

The index array will not contain repeated indices, and all indices will be in range.

The base and value arrays may contain repeated elements.

Any or all of the arrays may be empty.

You must not assume that the indices are given in any particular order.

You may receive input and produce output in any convenient, unambiguous string or list format. You may also choose to receive the three arrays in a different order.

You may choose between 0-based and 1-based indexing.

This is code golf, so the shortest answer (in bytes) wins.

Test Cases

Given in the format B V I => Result for 0-based indexing. If you're using 1-based indexing, increment the elements of the third array by 1.

```<code>[] [] [] => []
[] [1] [0] => [1]
[1,2] [] [] => [1,2]
[1,2] [3] [0] => [3,1,2]
[1,2] [3] [1] => [1,3,2]
[1,2] [3] [2] => [1,2,3]
[0,0,0] [1,1,1,1] [0,1,2,3] => [1,0,1,0,1,0,1]
[5,1,4,1,3] [0,0,7] [5,0,3] => [0,5,1,4,7,1,3,0]
[1,2,3,4] [4,3,2,1] [4,0,3,1] => [3,1,1,2,3,2,4,4]
</code>```

Let me know if you come across other interesting edge cases, and I'll add them.

Leaderboard

Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language.

To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:

```<code># Language Name, N bytes
</code>```

where N is the size of your submission. If you improve your score, you can keep old scores in the headline, by striking them through. For instance:

```<code># Ruby, <s>104</s> <s>101</s> 96 bytes
</code>```

var QUESTION_ID=50369;function answersUrl(e){return"http://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),e.has_more?getAnswers():process()}})}function shouldHaveHeading(e){var a=!1,r=e.body_markdown.split("\n");try{a|=/^#/.test(e.body_markdown),a|=["-","="].indexOf(r[1][0])>-1,a&=LANGUAGE_REG.test(e.body_markdown)}catch(n){}return a}function shouldHaveScore(e){var a=!1;try{a|=SIZE_REG.test(e.body_markdown.split("\n")[0])}catch(r){}return a}function getAuthorName(e){return e.owner.display_name}function process(){answers=answers.filter(shouldHaveScore).filter(shouldHaveHeading),answers.sort(function(e,a){var r=+(e.body_markdown.split("\n")[0].match(SIZE_REG)||[1/0])[0],n=+(a.body_markdown.split("\n")[0].match(SIZE_REG)||[1/0])[0];return r-n});var e={},a=1,r=null,n=1;answers.forEach(function(s){var t=s.body_markdown.split("\n")[0],o=jQuery("#answer-template").html(),l=(t.match(NUMBER_REG)[0],(t.match(SIZE_REG)||[0])[0]),c=t.match(LANGUAGE_REG)[1],i=getAuthorName(s);l!=r&&(n=a),r=l,++a,o=o.replace("{{PLACE}}",n+".").replace("{{NAME}}",i).replace("{{LANGUAGE}}",c).replace("{{SIZE}}",l).replace("{{LINK}}",s.share_link),o=jQuery(o),jQuery("#answers").append(o),e[c]=e[c]||{lang:c,user:i,size:l,link:s.share_link}});var s=[];for(var t in e)e.hasOwnProperty(t)&&s.push(e[t]);s.sort(function(e,a){return e.lang>a.lang?1:e.lang<a.lang?-1:0});for(var o=0;o<s.length;++o){var l=jQuery("#language-template").html(),t=s[o];l=l.replace("{{LANGUAGE}}",t.lang).replace("{{NAME}}",t.user).replace("{{SIZE}}",t.size).replace("{{LINK}}",t.link),l=jQuery(l),jQuery("#languages").append(l)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",answers=[],page=1;getAnswers();var SIZE_REG=/\d+(?=[^\d&]*(?:<(?:s>[^&]*<\/s>|[^&]+>)[^\d&]*)*$)/,NUMBER_REG=/\d+/,LANGUAGE_REG=/^#*\s*([^,]+)/;```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}</code>```

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

{{PLACE}}	{{NAME}}	{{LANGUAGE}}	{{SIZE}}	Link

{{LANGUAGE}}	{{NAME}}	{{SIZE}}	Link

```

答:
APL, 22 bytes

```<code>{(∊⌽2↑⍵)[⍋(2⊃⍵),⍳≢⊃⍵]}
</code>```

In ⎕IO←0 to match the test cases.

It's a standard algorithm: the index vector of the first argument is appended to the given indexes (3rd argument). ⍋ computes the permutation that would sort the indexes in ascending order. Since APL's sorting algorithm is stable by definition, the permutation computed puts the element of the catenation of the second and first argument in the right place.

For instance:

```<code>    {(∊⌽2↑⍵)[⍋(2⊃⍵),⍳≢⊃⍵]}(5 1 4 1 3)(0 0 7)(5 0 3)
0 5 1 4 7 1 3 0
</code>```

Title: Generalised Array Riffle

Body:
APL, 22 bytes

{(∊⌽2↑⍵)[⍋(2⊃⍵),⍳≢⊃⍵]}

In ⎕IO←0 to match the test cases.

It's a standard algorithm: the index vector of the first argument is appended to the given indexes (3rd argument). ⍋ computes the permutation that would sort the indexes in ascending order. Since APL's sorting algorithm is stable by definition, the permutation computed puts the element of the catenation of the second and first argument in the right place.

For instance:

    {(∊⌽2↑⍵)[⍋(2⊃⍵),⍳≢⊃⍵]}(5 1 4 1 3)(0 0 7)(5 0 3)
0 5 1 4 7 1 3 0


答:
Dyalog APL, <s>19</s> <s>17</s> 16 bytes

```<code>≢+#⍎'\d'⎕R'&+',⊢
</code>```

Takes string and returns

 ≢ length

+ plus

 # in root namespace

⍎ evaluation of

 '\d'⎕R'&+' regex append digits with a plus

, followed by

 ⊢ the unmodified string

–3 thanks to ngn

Title: Calculate the sum of ILD

Body:
Dyalog APL, <s>19</s> <s>17</s> 16 bytes

≢+#⍎'\d'⎕R'&+',⊢

Takes string and returns

 ≢ length

+ plus

 # in root namespace

⍎ evaluation of

 '\d'⎕R'&+' regex append digits with a plus

, followed by

 ⊢ the unmodified string

–3 thanks to ngn


答:
C#, <s>88</s> <s>86</s> <s>85</s> 84 bytes

```<code>(r,g,b)=>{float[]a={r,g,b,1};var j=a.Max();a[3]=j*j/255;return a.Select(x=>1-x/j);};
</code>```

output for 108,174,106:

```<code>0.3793104
0
0.3908046
0.3176471
</code>```

Since OP allows function I submitted only the lambda. You can find a running demo on .NetFiddle. I am not a golfer, I post for fun. Also, it is my first answer \o/. Feel free to comment any improvement :)

Kudos to Leaky Nun for the formula.

caveat: it doesn´t work for [0,0,0] (thank you Titus)

Title: From Rgb to Cmyk

Body:
C#, <s>88</s> <s>86</s> <s>85</s> 84 bytes

(r,g,b)=>{float[]a={r,g,b,1};var j=a.Max();a[3]=j*j/255;return a.Select(x=>1-x/j);};

output for 108,174,106:

0.3793104
0
0.3908046
0.3176471

Since OP allows function I submitted only the lambda. You can find a running demo on .NetFiddle. I am not a golfer, I post for fun. Also, it is my first answer \o/. Feel free to comment any improvement :)

Kudos to Leaky Nun for the formula.

caveat: it doesn´t work for [0,0,0] (thank you Titus)


问:
Can Pac-Man Eat This String?
In the arcade version of the game, Pac-Man eats pac-dots. However, in this challenge, he's hungry for alphanumeric characters and punctuation in a string.

Your task is to create a function that feeds Pac-Man a string, evaluates if he can eat it or not, and returns the string with Pac-Man's location in it.

Pac-Man (<) eats characters from left to right, leaving an underscore or space for each character as he goes, and his goal is to get from the first position-1 to the last position+1:

```<code>1. <Pac
2. _<ac
3. __<c
4. ___<
</code>```

However, Pac-Man's natural enemy, the ghost, will stop him if he encounters one of the letters in the word "GHOST" (not case sensitive). Your function should return the string with Pac-Man's location as he encounters the ghost character:

```<code>1. <No!
2. _<o!
</code>```

The only thing that can defeat a ghost is a power pellet. If Pac-Man reaches a letter in the word "PELLET" (also not case sensitive) before coming to a ghost, he will eat the ghost and keep moving, and that pellet will be used up. Power pellets can stack (ie, in ppgg both ghosts would be eaten). The T character exists as both as a ghost and a pellet, so it can be ignored (treated as any other letter, like a).

```<code>1. <Pop
2. _<op
3. __<p
4. ___<
</code>```

To further clarify, in the string "Pac-Man loses here", the following operations occur:

```<code>P <P, +1 Pellet (1 pellet)
a <a
c <c
- <-
M <M
a <a
n <n
  <[space]
l <l, +1 Pellet (2 pellets)
o <o, -1 Pellet (1 pellet)
s <s, -1 Pellet (0 pellets)
e <e, +1 Pellet (1 pellet)
s <s, -1 Pellet (0 pellets)
  <[space]
h <h, ghost wins, returns
e
r
e
</code>```

Examples

```<code>Input: Pacman wins!
Output: ____________<

Input: Pacman loses wah-wah :(
Output: _______________<h-wah :(

Input: PELLET PELLET GHOST
Output: ___________________<

Input: Hello World!
Output: <Hello World!

Input: <_!@12<_<_<
Output: ___________<
</code>```

This is code-golf--lowest score in bytes wins.

答:
Retina, <s>55</s> 38 bytes

```<code>i`^(([elp])|[^ghos]|(?<-2>.))*
$.&$*_<
</code>```

Try it online! (The first line just allows running several test cases at once.)

Explanation

The problem is essentially to find the longest prefix that doesn't have an unmatched closing parenthesis. Except that we can use either e, l or p in place of ( and either g, h, o or s in place of ).

Hence, this solution is almost a textbook example of balancing groups. I won't go into too much detail about how they work, as this code is essentially the same as the standard example you can read up on in my SO answer on balancing groups.

The entire program is therefore a single regex substitution. The i activates case-insensitivity. Then we either match a pellet with [elp] and increment the depth counter (in the form of the capture stack of group 2), or we match something that isn't a ghost with [ghos] or we match a ghost with . and decrement the depth counter by popping from stack 2. Of course, in principle this allows matching a pellet with the [^ghos] section or a non-ghost with the . section, but thanks to greedy matching and the way the regex is backtracked, these possibilities are never attempted by the regex engine.

The substitution then uses two Retina specific features: $* repeats the character to its right as many times as specified by the token on its left. That token is $.& which is the length of the entire match. This just means that we replace each character in the match with a _. And then we also append a < to those underscores. The part of the input that isn't eaten simply remains unaffected by the substitution.

Title: Can Pac-Man Eat This String?

Body:
Retina, <s>55</s> 38 bytes

i`^(([elp])|[^ghos]|(?<-2>.))*
$.&$*_<

Try it online! (The first line just allows running several test cases at once.)

Explanation

The problem is essentially to find the longest prefix that doesn't have an unmatched closing parenthesis. Except that we can use either e, l or p in place of ( and either g, h, o or s in place of ).

Hence, this solution is almost a textbook example of balancing groups. I won't go into too much detail about how they work, as this code is essentially the same as the standard example you can read up on in my SO answer on balancing groups.

The entire program is therefore a single regex substitution. The i activates case-insensitivity. Then we either match a pellet with [elp] and increment the depth counter (in the form of the capture stack of group 2), or we match something that isn't a ghost with [ghos] or we match a ghost with . and decrement the depth counter by popping from stack 2. Of course, in principle this allows matching a pellet with the [^ghos] section or a non-ghost with the . section, but thanks to greedy matching and the way the regex is backtracked, these possibilities are never attempted by the regex engine.

The substitution then uses two Retina specific features: $* repeats the character to its right as many times as specified by the token on its left. That token is $.& which is the length of the entire match. This just means that we replace each character in the match with a _. And then we also append a < to those underscores. The part of the input that isn't eaten simply remains unaffected by the substitution.


问:
Calculate the nth term of Golomb's self-describing sequence
Inspired by the previous question.

Golomb's self-describing sequence g(n) is a sequence where any natural number n is repeated within the sequence g(n) times.

The first few numbers in the sequence are:

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

You can see that g(4)=3, and that "4" is repeated 3 times in the sequence.

Given an input of n, output g(n).

Limitations: n < 100000.

Smallest code wins.

答:
Python - 76 chars

```<code>n=20;g=[1,2,2];[[g.append(i)for j in range(g[i-1])]for i in range(3,n)];g[n]
</code>```

Body:
Python - 76 chars

n=20;g=[1,2,2];[[g.append(i)for j in range(g[i-1])]for i in range(3,n)];g[n]


答:
Pyth, <s>53</s> <s>48</s> 44 bytes

4 bytes thanks to @Pietu1998 for the !!@ -> } trick (which only people who know Pyth can understand)

```
<s>++*Jf<@+sM._m-!!@d"PELpel"!!@d"GHOSghos"Q_1T00\_\<>QJ</s>
<s>++*Jf<@+sM._m-!!@d"PEL"!!@d"GHOS"rQ1_1T00\_\<>QJ</s>
++*Jf<@+sM._m-}d"PEL"}d"GHOS"rz1_1T00\_\<>zJ
```

Test suite.

Title: Can Pac-Man Eat This String?

Body:
In the arcade version of the game, Pac-Man eats pac-dots. However, in this challenge, he's hungry for alphanumeric characters and punctuation in a string.

Your task is to create a function that feeds Pac-Man a string, evaluates if he can eat it or not, and returns the string with Pac-Man's location in it.

Pac-Man (<) eats characters from left to right, leaving an underscore or space for each character as he goes, and his goal is to get from the first position-1 to the last position+1:

```<code>1. <Pac
2. _<ac
3. __<c
4. ___<
</code>```

However, Pac-Man's natural enemy, the ghost, will stop him if he encounters one of the letters in the word "GHOST" (not case sensitive). Your function should return the string with Pac-Man's location as he encounters the ghost character:

```<code>1. <No!
2. _<o!
</code>```

The only thing that can defeat a ghost is a power pellet. If Pac-Man reaches a letter in the word "PELLET" (also not case sensitive) before coming to a ghost, he will eat the ghost and keep moving, and that pellet will be used up. Power pellets can stack (ie, in ppgg both ghosts would be eaten). The T character exists as both as a ghost and a pellet, so it can be ignored (treated as any other letter, like a).

```<code>1. <Pop
2. _<op
3. __<p
4. ___<
</code>```

To further clarify, in the string "Pac-Man loses here", the following operations occur:

```<code>P <P, +1 Pellet (1 pellet)
a <a
c <c
- <-
M <M
a <a
n <n
  <[space]
l <l, +1 Pellet (2 pellets)
o <o, -1 Pellet (1 pellet)
s <s, -1 Pellet (0 pellets)
e <e, +1 Pellet (1 pellet)
s <s, -1 Pellet (0 pellets)
  <[space]
h <h, ghost wins, returns
e
r
e
</code>```

Examples

```<code>Input: Pacman wins!
Output: ____________<

Input: Pacman loses wah-wah :(
Output: _______________<h-wah :(

Input: PELLET PELLET GHOST
Output: ___________________<

Input: Hello World!
Output: <Hello World!

Input: <_!@12<_<_<
Output: ___________<
</code>```

This is code-golf--lowest score in bytes wins.

Body:
Pyth, <s>53</s> <s>48</s> 44 bytes

4 bytes thanks to @Pietu1998 for the !!@ -> } trick (which only people who know Pyth can understand)

<s>++*Jf<@+sM._m-!!@d"PELpel"!!@d"GHOSghos"Q_1T00\_\<>QJ</s>
<s>++*Jf<@+sM._m-!!@d"PEL"!!@d"GHOS"rQ1_1T00\_\<>QJ</s>
++*Jf<@+sM._m-}d"PEL"}d"GHOS"rz1_1T00\_\<>zJ

Test suite.


答:
Python 3, <s>176</s> <s>157</s> <s>150</s> <s>149</s> <s>134</s> <s>133</s> 124 bytes

Define a function named f which take the string as argument

```<code>def f(s):
 n=i=0
 for c in s:
  if c in"GgHhOoSs":
   if n:n-=1
   else:break
  n+=c in"PpEeLl";i+=1
 return"_"*i+"<"+s[i:]
</code>```

Can be probably be golfed more

Thanks to everyone who commented :D

Title: Can Pac-Man Eat This String?

Body:
Python 3, <s>176</s> <s>157</s> <s>150</s> <s>149</s> <s>134</s> <s>133</s> 124 bytes

Define a function named f which take the string as argument

def f(s):
 n=i=0
 for c in s:
  if c in"GgHhOoSs":
   if n:n-=1
   else:break
  n+=c in"PpEeLl";i+=1
 return"_"*i+"<"+s[i:]

Can be probably be golfed more

Thanks to everyone who commented :D


答:
JavaScript (ES6), <s>58</s> 51 bytes

```<code>a=>[...a.map(e=>1-e/m||1,m=Math.max(...a)),1-m/255]
</code>```

Accepts an array [R, G, B] (add 7 bytes for separate parameters) and returns an array [C, M, Y, K] using the uncalibrated colour mapping.

Title: From Rgb to Cmyk

Body:
Given 3 bytes or RGB as input, calculate the nearest CMYK values, and output them.

create either a function with parameters and return value or a program that operates on stdin/stdout

use the color profile of your choice, but provide a reference

input may be either separate numeric values in range [0;255] or a 6 digit hex string

output should be separate numeric values ranging either [0;1] or [0;100]

standard code golf: no loopholes, shortest code wins

extravagant ideas are welcome

sample data:

```<code>input             output
108,174,106       [0.3793103448275862, 0.0, 0.3908045977011494, 0.3176470588235294]
0,0,0             0,0,0,1
170,255,238       33,0,7,0
0x0088ff          1,0.4667,0,0
[250,235,215]     [0,6,14,1.96]
#123456           .7907,.3953,0,.6627
</code>```

Uncalibrated mapping is fine and probably the easiest

No input validation required; floats are allowed (ranging from 0 to 255), but may also be rounded

Output format should be either clearly commented or obvious; i.e.:

CMYK in that order

does not matter if percentage [0;100] or pure numbers [0;1]

Testing should include the trivial example [0,0,0].

This site has the most digits of online tools that I could find. Does anyone know a tool that gives more than 4 digits?

Body:
JavaScript (ES6), <s>58</s> 51 bytes

a=>[...a.map(e=>1-e/m||1,m=Math.max(...a)),1-m/255]

Accepts an array [R, G, B] (add 7 bytes for separate parameters) and returns an array [C, M, Y, K] using the uncalibrated colour mapping.


答:
Python 2, 114 113 108 bytes

s=raw_input()
p=i=0
for c in s:
 p+=(c in'plePLE')-(c in'ghosGHOS')
 if p<0:break
 i+=1
print'_'*i+'<'+s[i:]
```

Title: Can Pac-Man Eat This String?


答:
Octave, <s>97</s> <s>95</s> 86 bytes

@(w,h){[a=~(1:w*2+3)+95;repmat(['| ' repmat('o ',1,w) '|'],h,1);~a+45],'o'}{(w*h<2)+1}
```

I used the @atlasologist's method in Python to test (1, 1): (...,'o')[x<2>y]

Thanks to @Luis Mendo for saving 7 bytes: a=ones(1,w*2+3)*'_' to a=~(1:w*2+3)+95 and a./a*'-' to ~a+45

Thanks to @pajonk for saving 2 bytes: <s>f=</s>

Title: Print a Lego piece

Body:
This challenge is a simple ascii-art one. Given two inputs, describing the height and width of a Lego piece, you have print an ASCII art representation of it.

Here is how the Lego pieces are supposed to look:

```<code>(4, 2)

___________
| o o o o |
| o o o o |
-----------

(8, 2)

___________________
| o o o o o o o o |
| o o o o o o o o |
-------------------

(4, 4)

___________
| o o o o |
| o o o o |
| o o o o |
| o o o o |
-----------

(3, 2)

_________
| o o o |
| o o o |
---------

(1, 1)

o
</code>```

If you can't tell from the test-cases, the top and bottom are width*2+3 underscores and dashes, and each row has pipes for the sides, o's for the little things, and everything is separated by spaces.

The only exception for this is (1, 1), which is just a single o.

You will never get 0 for any of the dimensions.

This is code-golf, so shortest code in bytes wins!

var QUESTION_ID=84050,OVERRIDE_USER=31343;function answersUrl(e){return"http://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"http://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="
"+e.body.replace(OVERRIDE_REG,"")+"
")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}</code>```

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

{{PLACE}}	{{NAME}}	{{LANGUAGE}}	{{SIZE}}	Link

{{LANGUAGE}}	{{NAME}}	{{SIZE}}	Link

```

Body:
Octave, <s>97</s> <s>95</s> 86 bytes

@(w,h){[a=~(1:w*2+3)+95;repmat(['| ' repmat('o ',1,w) '|'],h,1);~a+45],'o'}{(w*h<2)+1}

I used the @atlasologist's method in Python to test (1, 1): (...,'o')[x<2>y]

Thanks to @Luis Mendo for saving 7 bytes: a=ones(1,w*2+3)*'_' to a=~(1:w*2+3)+95 and a./a*'-' to ~a+45

Thanks to @pajonk for saving 2 bytes: <s>f=</s>


问:
Bouncing in an array

Introduction

Arrays can also be seen as a field for a bouncing ball. This of course sounds very vague, so here is an example of an input:

```<code>[1, 2, 3, 4, 5, 6, 7, 8, 9]
[9, 8, 7, 6, 5, 4, 3, 2, 1]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
</code>```

The challenge is to output the bounced arrays. These are made from diagonal patterns which bounce at the edges of the field. This path is pointed upwards. The path for the first bounced array (in which the path is directly bounced off the egde), is:

```<code>[1, -, -, -, 5, -, -, -, 9]
[-, 8, -, 6, -, 4, -, 2, -]
[-, -, 3, -, -, -, 7, -, -]
</code>```

From left to right, this would result in [1, 8, 3, 6, 5, 4, 7, 2, 9]. This is our first bounced array. The path for the second bounced array:

```<code>[-, 2, -, -, -, 6, -, -, -]
[9, -, 7, -, 5, -, 3, -, 1]
[-, -, -, 4, -, -, -, 8, -]
</code>```

This results in [9, 2, 7, 4, 5, 6, 3, 8, 1]. The path for the third bounced array is:

```<code>[-, -, 3, -, -, -, 7, -, -]
[-, 8, -, 6, -, 4, -, 2, -]
[1, -, -, -, 5, -, -, -, 9]
</code>```

This results in [1, 8, 3, 6, 5, 4, 7, 2, 9]. So the three bounced arrays are:

```<code>[1, 8, 3, 6, 5, 4, 7, 2, 9]
[9, 2, 7, 4, 5, 6, 3, 8, 1]
[1, 8, 3, 6, 5, 4, 7, 2, 9]
</code>```

Task

Given at least 1 array containing only non-negative integers, with all the arrays having the same length, output all the bounced arrays.

Test cases

Test case 1:

```<code>Input:                       Output:
[1, 2, 3, 4, 5]              [1, 7, 3, 9, 5]
[6, 7, 8, 9, 0]              [6, 2, 8, 4, 0]

Input:                       Output:
[1, 2, 3, 4, 5]              [1, 2, 3, 4, 5]

Input:                       Output:
[0, 0, 0, 0, 0, 0, 0, 0]     [0, 9, 0, 9, 0, 9, 0, 100]
[9, 9, 9, 9, 9, 9, 9, 100]   [9, 0, 9, 0, 9, 0, 9, 0]
[0, 0, 0, 0, 0, 0, 0, 0]     [0, 9, 0, 9, 0, 9, 0, 100]

Input:                       Output:
[0, 1, 2, 3, 4, 5]           [0, 7, 14, 9, 4, 11]
[6, 7, 8, 9, 10, 11]         [6, 1, 8, 15, 10, 5]
[12, 13, 14, 15, 16, 17]     [12, 7, 2, 9, 16, 11]

Input:                       Output:
[0, 0, 0, 0, 0, 0]           [0, 2, 2, 6, 2, 6]
[1, 2, 3, 4, 5, 6]           [1, 0, 3, 2, 5, 2]
[2, 2, 2, 2, 2, 2]           [2, 2, 0, 4, 2, 4]
[9, 8, 7, 6, 5, 4]           [9, 2, 3, 0, 5, 2]
</code>```

This is code-golf, so the submission with the least amount of bytes wins!

答:
APL, 33 chars

```<code>{(⍳≢⍵){0⌷(⍺-⍳≢⍉⍵)⊖⍵⍪1↓¯1↓⊖⍵}¨⊂↑⍵}
</code>```

Assume ⎕IO←0.
The idea is that the bouncing movement can be obtained by simple shift upward of a matrix, if the original matrix is augmented along the first dimension with the matrix reversed with its first and last row shaved.
Graphically:

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

from

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

In APL reverse and upward rotate are the same symbol: ⊖.

Title: Bouncing in an array

Body:
APL, 33 chars

{(⍳≢⍵){0⌷(⍺-⍳≢⍉⍵)⊖⍵⍪1↓¯1↓⊖⍵}¨⊂↑⍵}

Assume ⎕IO←0.
The idea is that the bouncing movement can be obtained by simple shift upward of a matrix, if the original matrix is augmented along the first dimension with the matrix reversed with its first and last row shaved.
Graphically:

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

from

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

In APL reverse and upward rotate are the same symbol: ⊖.


答:
Batch, <s>172</s> 170 bytes

```<code>@echo off
if "%*"=="1 1" echo o&exit/b
set o=
for /l %%i in (1,1,%1)do call set o=%%o%% o
echo ---%o: o=--%
for /l %%i in (1,1,%2)do echo ^|%o% ^|
echo ---%o: o=--%
</code>```

Edit: Saved 2 bytes thanks to <s>@CᴏɴᴏʀO'Bʀɪᴇɴ</s> @EʀɪᴋᴛʜᴇGᴏʟғᴇʀ.

I can save 7 bytes if I can assume delayed expansion is enabled.

Title: Print a Lego piece

Body:
Batch, <s>172</s> 170 bytes

@echo off
if "%*"=="1 1" echo o&exit/b
set o=
for /l %%i in (1,1,%1)do call set o=%%o%% o
echo ---%o: o=--%
for /l %%i in (1,1,%2)do echo ^|%o% ^|
echo ---%o: o=--%

Edit: Saved 2 bytes thanks to <s>@CᴏɴᴏʀO'Bʀɪᴇɴ</s> @EʀɪᴋᴛʜᴇGᴏʟғᴇʀ.

I can save 7 bytes if I can assume delayed expansion is enabled.


Title: Print a Lego piece

Body:
JavaScript (ES6), <s>89</s> 86 bytes

(x,y,g=c=>c[r=`repeat`](x*2+3))=>x*y-1?g(`_`)+`
`+`| ${`o `[r](x)}|
`[r](y)+g(`-`):`o`

Edit: Saved 3 bytes thanks to @Shaggy.


答:
JavaScript (ES6), 38 bytes

```<code>n=>eval([n+=``,n.length,...n].join`+`)
</code>```

Uses the old join-and-eval trick. Save 4 bytes if I can insist on string input:

f=
n=>eval([n,n.length,...n].join`+`)
;```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type=number oninput=o.value=f(this.value)><input id=o readonly></code>```

Title: Calculate the sum of ILD

Body:
Input:

An integer

Output:

Sum of the input itself + the length of the input + each individual digit of the input.

```<code>nr + nr-length + {sum of digits} = output
</code>```

Examples:

Input: 99

Output: 99 (nr) + 2 (nr-length) + (9 + 9) (digits) → 119

Input: 123

Output: 123 + 3 + (1 + 2 + 3) → 132

Challenge rules:

The input can also contain negative input, which are resolved special. The -/minus-sign is also +1 for the length, and is part of the first digit.

For example:

Input: -123

Output: -123 + 4 + (-1 + 2 + 3) → -115

You can assume that the input nor output will ever be outside the range of an (32-bit) integer.

General rules:

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

Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.

Standard rules apply for your answer, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call.

Default Loopholes are forbidden.

If possible, please add a link with a test for your code.

Also, please add an explanation if necessary.

Test cases:

```<code>87901 → 87931
123 → 132
99 → 119
5 → 11
1 → 3
0 → 1
-3 → -4
-123 → -115
-900 → -905
-87901 → -87886
</code>```

Semi-related: Count Sum of all Digits

Body:
JavaScript (ES6), 38 bytes

n=>eval([n+=``,n.length,...n].join`+`)

Uses the old join-and-eval trick. Save 4 bytes if I can insist on string input:

f=
n=>eval([n,n.length,...n].join`+`)
;

<input type=number oninput=o.value=f(this.value)><input id=o readonly>


答:
Perl 6 - 30 bytes

As literal as it gets

```<code>{$^a+$^a.chars+[+]($^a.comb)}
</code>```

Use it as an anonymous function

```<code>> {$^a+$^a.chars+[+]($^a.comb)}(99)
119
</code>```

Title: Calculate the sum of ILD

Body:
Perl 6 - 30 bytes

As literal as it gets

{$^a+$^a.chars+[+]($^a.comb)}

Use it as an anonymous function

> {$^a+$^a.chars+[+]($^a.comb)}(99)
119


问:
Holiday Gift Exchange
Another problem from our internal golfing...this one around the holidays last year.

PROBLEM

Andy, Barb, Carl, Didi, Earl, and Fran are buying gifts for each other. Draw names for a gift exchange.

Each person buys one gift and receives one gift.

Nobody buys their own gift.

Running the solution multiple times should produce different results (giver-receiver pair should not be predictable or identical from run to run).

INPUT

None.

OUTPUT

Formatted as in this example:

Andy buys for Barb

  Barb buys for Carl

  Carl buys for Didi

  Didi buys for Earl

  Earl buys for Fran

  Fran buys for Andy

答:
D: 233 Characters

```<code>import std.random,std.stdio;void main(){auto p=["Andy","Barb","Carl","Didi","Earl","Fran"];auto q=p.dup;o:while(1){for(int i;i<6;++i)if(p[i]==q[i]){randomShuffle(q);continue o;}break;}foreach(i,a;p)writefln("%s buys for %s",a,q[i]);}
</code>```

More Legibly:

```<code>import std.random, std.stdio;

void main()
{
    auto p = ["Andy", "Barb", "Carl", "Didi", "Earl", "Fran"];
    auto q = p.dup;

    o:while(1)
    {
        for(int i; i < 6; ++i)
            if(p[i] == q[i])
            {
                randomShuffle(q);
                continue o;
            }

        break;
    }

    foreach(i, a; p)
        writefln("%s buys for %s", a, q[i]);
}
</code>```

ContentLicense: CC BY-SA 2.5

Title: Holiday Gift Exchange

Body:
D: 233 Characters

import std.random,std.stdio;void main(){auto p=["Andy","Barb","Carl","Didi","Earl","Fran"];auto q=p.dup;o:while(1){for(int i;i<6;++i)if(p[i]==q[i]){randomShuffle(q);continue o;}break;}foreach(i,a;p)writefln("%s buys for %s",a,q[i]);}

More Legibly:

import std.random, std.stdio;

void main()
{
    auto p = ["Andy", "Barb", "Carl", "Didi", "Earl", "Fran"];
    auto q = p.dup;

    o:while(1)
    {
        for(int i; i < 6; ++i)
            if(p[i] == q[i])
            {
                randomShuffle(q);
                continue o;
            }

        break;
    }

    foreach(i, a; p)
        writefln("%s buys for %s", a, q[i]);
}


问:
Twinkle Twinkle Little Star
Write a program to play the popular English nursery rhyme.

(This file is licensed under the Creative Commons Attribution-Share Alike 3.0 Unported license. Attribution: Helix84 at the English language Wikipedia; Blahedo at the English language Wikipedia.)

Some Wikipedia articles that may be useful:

Twinkle Twinkle Little Star (has an audio clip of what your program's output should sound like)

Modern musical symbols (to learn about the music notation used above)

Musical note#Note frequency (in hertz) (the formula for calculating the frequency of each note)

Some guidelines for your submission:

Your program must use the computer's sound card. If your programming language doesn't have convenient access to audio hardware, your program must create an output file in some standard format such as WAV or MIDI.

Your program must actually generate its output. For example, embedding the Ogg Vorbis file from Wikipedia would not be allowed.

The audio quality must be acceptable. At the very least, the song should be easily recognizable. Preferably, it should sound good as well.

The focus should be on code size, sound quality, or both (explain which one you decided on). Elegant solutions would also be great. Have fun!

This is a code-golf, so shortest code wins

答:
C, 96 chars

```<code>main(t){for(;++t>>16<3;)putchar(t*!!(t>>9&7|!(-t>>12&7))*(96+"#d|dOE3#dOE3dOE3"[t>>13&15])>>5);}
</code>```

Produces raw 8-bit unsigned mono audio data in classic bytebeat style.  Recommended sample rates for playback are between 8 and 16 kHz; changing the sample rate changes the tempo and pitch.

To compile and play under Linux, save the code above as twinkle.c and run the following commands:

```<code>gcc twinkle.c -o twinkle
./twinkle | aplay
</code>```

Some notes on how the code works:

The general trick used for bytebeat compositions like this is that putchar() takes an integer value but only prints the low eight bits of it.  Thus, putchar(t), where t is an increasing counter, generates a sawtooth wave, and the frequency of the wave can be altered by multiplying t with a suitable value.

!!(t>>9&7|!(-t>>12&7)) produces the repeating 6+1 note pattern.  Specifically, !!(t>>9&7) evaluates to 0 whenever t>>9 & 7 == 0 and to 1 otherwise.  Thus, it produces a 512-sample gap in the waveform every 4096 samples, while the !(-t>>12&7) eliminates every eighth such gap.

96+"#d|dOE3#dOE3dOE3"[t>>13&15] generates the melody: the ASCII code of each characters in the string plus 96 gives the relative frequency of the corresponding note.  Actually, the values are the approximate frequencies in Hz of concert pitch notes in the 3rd / small octave, i.e. with A corresponding to 220.  However, since the base tone with which these values are multiplied is about 64 Hz (when played at 16 kHz, or 32 Hz when played at 8 kHz), we need to scale the result down by five octaves with >>5 to get the frequency back into a reasonable range.

Ps. If you want to try this code on a JavaScript-based bytebeat player, replace [t>>13&15] with .charCodeAt(t>>13&15).

Title: Twinkle Twinkle Little Star

Body:
C, 96 chars

main(t){for(;++t>>16<3;)putchar(t*!!(t>>9&7|!(-t>>12&7))*(96+"#d|dOE3#dOE3dOE3"[t>>13&15])>>5);}

Produces raw 8-bit unsigned mono audio data in classic bytebeat style.  Recommended sample rates for playback are between 8 and 16 kHz; changing the sample rate changes the tempo and pitch.

To compile and play under Linux, save the code above as twinkle.c and run the following commands:

gcc twinkle.c -o twinkle
./twinkle | aplay

Some notes on how the code works:

The general trick used for bytebeat compositions like this is that putchar() takes an integer value but only prints the low eight bits of it.  Thus, putchar(t), where t is an increasing counter, generates a sawtooth wave, and the frequency of the wave can be altered by multiplying t with a suitable value.

!!(t>>9&7|!(-t>>12&7)) produces the repeating 6+1 note pattern.  Specifically, !!(t>>9&7) evaluates to 0 whenever t>>9 & 7 == 0 and to 1 otherwise.  Thus, it produces a 512-sample gap in the waveform every 4096 samples, while the !(-t>>12&7) eliminates every eighth such gap.

96+"#d|dOE3#dOE3dOE3"[t>>13&15] generates the melody: the ASCII code of each characters in the string plus 96 gives the relative frequency of the corresponding note.  Actually, the values are the approximate frequencies in Hz of concert pitch notes in the 3rd / small octave, i.e. with A corresponding to 220.  However, since the base tone with which these values are multiplied is about 64 Hz (when played at 16 kHz, or 32 Hz when played at 8 kHz), we need to scale the result down by five octaves with >>5 to get the frequency back into a reasonable range.

Ps. If you want to try this code on a JavaScript-based bytebeat player, replace [t>>13&15] with .charCodeAt(t>>13&15).


答:
Lua, <s>198</s> <s>190</s> <s>184</s> <s>185</s> 163 Bytes

Ok, I admit, this is long. Very long. Lua has some tools to play around with strings, but it is limited, same goes for conditionals that takes lots of spaces.

Edit: thanks @LeakyNun for saving me 9 bytes :)
        Lost some bytes to fix a bug

Edit 2: 163 Bytes solution found by @LeakyNun

i=0p=0n=...for c in n:gmatch"."do
p=p+(c:find"[ghosGHOS]"and-1or c:find"[pelPEL]"and 1or 0)if p<0then
break else i=i+1 end end print(('_'):rep(i)..'<'..n:sub(i+1))
```

<p><strong>Old 185</strong></p>

<pre class="lang-lua prettyprint-override"><code>p=0z=(...):gsub(".",function(c)p=p+(c:find"[ghosGHOS]"and-1or
c:find"[pelPEL]"and 1or 0)s=p<0 and 1or s
return s and c or'_'end)_,i,s=z:find"(_+)"print((s or'')..'<'..z:sub(1+(i or 0)))
</code>```

Ungolfed

i=0                        -- number of characters eaten
p=0                        -- pellet counter
n=...                      -- shorthand for the argument
for c in n:gmatch"."       -- iterate over each characters in the input
do
  p=p+(c:find"[ghosGHOS]"  -- if the current char is a GHOST
        and-1              -- decrement the pellet counter
      or c:find"[pelPEL]"  -- if it's a PELLET
        and 1              -- increment it
      or 0)                -- else, leave it alone
  if p<0                   -- if we try to eat a ghost without pellet
  then
    break                  -- stop iterating
  else
    i=i+1                  -- else, increment our score
  end
end

print(('_'):rep(i)         -- print i*'_'
  ..'<'                    -- appended with Pacman
  ..n:sub(i+1))            -- appended with the remaining characters if we died
```

Title: Can Pac-Man Eat This String?

Body:
Lua, <s>198</s> <s>190</s> <s>184</s> <s>185</s> 163 Bytes

Ok, I admit, this is long. Very long. Lua has some tools to play around with strings, but it is limited, same goes for conditionals that takes lots of spaces.

Edit: thanks @LeakyNun for saving me 9 bytes :)
        Lost some bytes to fix a bug

Edit 2: 163 Bytes solution found by @LeakyNun

i=0p=0n=...for c in n:gmatch"."do
p=p+(c:find"[ghosGHOS]"and-1or c:find"[pelPEL]"and 1or 0)if p<0then
break else i=i+1 end end print(('_'):rep(i)..'<'..n:sub(i+1))

Old 185

p=0z=(...):gsub(".",function(c)p=p+(c:find"[ghosGHOS]"and-1or
c:find"[pelPEL]"and 1or 0)s=p<0 and 1or s
return s and c or'_'end)_,i,s=z:find"(_+)"print((s or'')..'<'..z:sub(1+(i or 0)))

Ungolfed

i=0                        -- number of characters eaten
p=0                        -- pellet counter
n=...                      -- shorthand for the argument
for c in n:gmatch"."       -- iterate over each characters in the input
do
  p=p+(c:find"[ghosGHOS]"  -- if the current char is a GHOST
        and-1              -- decrement the pellet counter
      or c:find"[pelPEL]"  -- if it's a PELLET
        and 1              -- increment it
      or 0)                -- else, leave it alone
  if p<0                   -- if we try to eat a ghost without pellet
  then
    break                  -- stop iterating
  else
    i=i+1                  -- else, increment our score
  end
end

print(('_'):rep(i)         -- print i*'_'
  ..'<'                    -- appended with Pacman
  ..n:sub(i+1))            -- appended with the remaining characters if we died


答:
Python, 46 bytes

```<code>lambda*c:[1-i/max(c)for i in c]+[1-max(c)/255]
</code>```

Requires input to be floats in Python 2, fairly sure it doesn't in 3.

Title: From Rgb to Cmyk

Body:
Python, 46 bytes

lambda*c:[1-i/max(c)for i in c]+[1-max(c)/255]

Requires input to be floats in Python 2, fairly sure it doesn't in 3.