问:
What's being surrounded
I've always wanted to surround some text with #s, but I have trouble figuring out what I surrounded so in this challenge you'll be writing a program to do just that

Examples

Input / Outputs are separated by a newline.

```<code>###
#a#
###

a
</code>```

```<code> #
#a#
 #

a
</code>```

```<code>  ###
 # a #
# b c #
#######

  a
 b c
</code>```

```<code>ABCDHIJ
E####GK
F# M #L
#   N#O
P####

  M
   N
</code>```

```<code>###A###
#C#B#o#
#d###e#
 # go#
  ###

C   o
d   e
  go
</code>```

Spec

#s are what "surround" a block of text

# will always be adjacent to one another (including diagonally)

# will always form a closed shape

There will only be one # shape

In the event of a concave shape, holes should be filled with spaces.

Whitespace must be preserved in the output

答:
Perl, <s>144</s> <s>138</s> <s>132</s> <s>129</s> <s>128</s> <s>127</s> <s>126</s> 124 bytes

Includes +2 for -p0

The code assumes \0 is not a valid input character (at least inside the #).

Run with the input on STDIN:

```<code>surround.pl < surround.txt
</code>```

surround.pl:

```<code>#!/usr/bin/perl -p0
/^#[^#\0]/m&&s/^|[^#\n\0]\0/\0\0/mg,s%.%s/.(.*)/$+\0/g;/#/&&reverse"\n",/^./mg%seg until$?++<$$_++;y/\0/#/;s/^#*\n|#+$|^#//mg;y;#;
</code>```

The code works as is, but replace the \0 and \n by their literal versions for the claimed score. Notice there is a space  at the end of the line. The code loops way too many times, so you may have to wait 30 seconds or so for output.

Explanation

I am going to do a floodfill with \0 stopped by # from the outside in the orthogonal directions. After that I will slice off the # sides and replace all that is left by spaces. To avoid having to handle all directions in the floodfill I will repeatedly rotate the target area and only floodfill from right to left

```<code>/^#[^#\0]/m                   The rotation is written such that it slices
                              off the first column. That is ok unless the
                              first column contains a # that is followed by
                              something that could be the inside. There is
                              no newline inside the [] because short lines
                              will get extended during the rotation and
                              the character following the # will end
                              up as a \0 and match in a later round
    &&s/^|[^#\n\0]\0/\0\0/mg  In case the # could be an interior border I
                              will add two columns of \0's in front. One
                              will be a sacrifice for the rotation, the
                              other column will end up at the end of the area
                              after two rotations and function as seed for the
                              floodfill. This regex also does one step of
                              the floodfill from the back to the front.
                              After a certain number of loops we are certain
                              to get to a first column that must not be
                              dropped so at some point the last column is
                              guaranteed to consist of only \0. And we only need
                              to fill backward since the rotations will make
                              any direction backward at some point

s%.%  process column  %seg    I will replace each character (including \n)
                              in the string by the next column in reversed
                              order or an empty string if there are no more
                              interesting columns. This is therefore a right
                              rotation. There are less columns than
                              characters so this loop is long enough

    s%.%s/.(.*)/$+\0/g        Remove the next (now first) character from each
                              row (so remove the column). Because the
                              original area is not necessarily a rectangle
                              add a \0 at the end of the row so we won't run
                              out out of columns (this would cause shorter
                              rows to have no entry in the new rotated row)
                              This will not do anything for empty lines so
                              they DO get squeezed out. But that is not a
                              problem since the problem statement says there
                              will be only one # shape so any empty lines
                              are can be safely dropped (this would not be
                              so if there could be multiple # shapes because
                              that could create a new surrounded area

    /#/                       Check if any of the remaining columns still
                              has a #. If not all remaining columns are on
                              the outside and can be dropped
       &&reverse"\n",/^./mg   Collect the column and add a \n to its reverse

 until$?++<$$_++              Keep doing this until we get to a multiple of
                              65536 rotations when $? waraps back around to 0
                              (this is a multiple of 4 so the area is left
                              unrotated) and an area we have seen before
                              ($$_ >= 1)
                              (so all slicing and flood filling is finished)
                              $_ having been seen in a previous rotations is
                              not a problem (though rather tricky to prove)
</code>```

At this point e.g.

```<code>AB##J
E####GK
F# M #L
#   N#O
P####
</code>```

will have been replaced by:

```<code>0000000
0####00
0# M #0
#   N#0
0####00
</code>```

Basically all columns and rows that are not directly bordering the inside have been sliced off. Any outside characters left has been replaced by \0.
At the top and right there is an extra layer of \0. So all that is left is cleanup:

```<code>y/\0/#/                       Replace any outside that is left by #
s/^#*\n|#+$|^#//mg            Removes the first two and last line (the only
                              lines that can consist of purely #)
                              Removes any trailing #
                              Removes the first column of #
y;#; \n;                      Replace any remaining # by space since they
                              are needed to fill the concave parts
                              The final \n; is not written since it is implicit
                              in the -p loop
</code>```

Title: What's being surrounded

Body:
Perl, <s>144</s> <s>138</s> <s>132</s> <s>129</s> <s>128</s> <s>127</s> <s>126</s> 124 bytes

Includes +2 for -p0

The code assumes \0 is not a valid input character (at least inside the #).

Run with the input on STDIN:

surround.pl < surround.txt

surround.pl:

#!/usr/bin/perl -p0
/^#[^#\0]/m&&s/^|[^#\n\0]\0/\0\0/mg,s%.%s/.(.*)/$+\0/g;/#/&&reverse"\n",/^./mg%seg until$?++<$$_++;y/\0/#/;s/^#*\n|#+$|^#//mg;y;#;

The code works as is, but replace the \0 and \n by their literal versions for the claimed score. Notice there is a space  at the end of the line. The code loops way too many times, so you may have to wait 30 seconds or so for output.

Explanation

I am going to do a floodfill with \0 stopped by # from the outside in the orthogonal directions. After that I will slice off the # sides and replace all that is left by spaces. To avoid having to handle all directions in the floodfill I will repeatedly rotate the target area and only floodfill from right to left

/^#[^#\0]/m                   The rotation is written such that it slices
                              off the first column. That is ok unless the
                              first column contains a # that is followed by
                              something that could be the inside. There is
                              no newline inside the [] because short lines
                              will get extended during the rotation and
                              the character following the # will end
                              up as a \0 and match in a later round
    &&s/^|[^#\n\0]\0/\0\0/mg  In case the # could be an interior border I
                              will add two columns of \0's in front. One
                              will be a sacrifice for the rotation, the
                              other column will end up at the end of the area
                              after two rotations and function as seed for the
                              floodfill. This regex also does one step of
                              the floodfill from the back to the front.
                              After a certain number of loops we are certain
                              to get to a first column that must not be
                              dropped so at some point the last column is
                              guaranteed to consist of only \0. And we only need
                              to fill backward since the rotations will make
                              any direction backward at some point

s%.%  process column  %seg    I will replace each character (including \n)
                              in the string by the next column in reversed
                              order or an empty string if there are no more
                              interesting columns. This is therefore a right
                              rotation. There are less columns than
                              characters so this loop is long enough

    s%.%s/.(.*)/$+\0/g        Remove the next (now first) character from each
                              row (so remove the column). Because the
                              original area is not necessarily a rectangle
                              add a \0 at the end of the row so we won't run
                              out out of columns (this would cause shorter
                              rows to have no entry in the new rotated row)
                              This will not do anything for empty lines so
                              they DO get squeezed out. But that is not a
                              problem since the problem statement says there
                              will be only one # shape so any empty lines
                              are can be safely dropped (this would not be
                              so if there could be multiple # shapes because
                              that could create a new surrounded area

    /#/                       Check if any of the remaining columns still
                              has a #. If not all remaining columns are on
                              the outside and can be dropped
       &&reverse"\n",/^./mg   Collect the column and add a \n to its reverse

 until$?++<$$_++              Keep doing this until we get to a multiple of
                              65536 rotations when $? waraps back around to 0
                              (this is a multiple of 4 so the area is left
                              unrotated) and an area we have seen before
                              ($$_ >= 1)
                              (so all slicing and flood filling is finished)
                              $_ having been seen in a previous rotations is
                              not a problem (though rather tricky to prove)

At this point e.g.

AB##J
E####GK
F# M #L
#   N#O
P####

will have been replaced by:

0000000
0####00
0# M #0
#   N#0
0####00

Basically all columns and rows that are not directly bordering the inside have been sliced off. Any outside characters left has been replaced by \0.
At the top and right there is an extra layer of \0. So all that is left is cleanup:

y/\0/#/                       Replace any outside that is left by #
s/^#*\n|#+$|^#//mg            Removes the first two and last line (the only
                              lines that can consist of purely #)
                              Removes any trailing #
                              Removes the first column of #
y;#; \n;                      Replace any remaining # by space since they
                              are needed to fill the concave parts
                              The final \n; is not written since it is implicit
                              in the -p loop


问:
¿xu ti te gismytermorna? (Is it a valid gismu?)
(Literally: "Does this follow/realize the gismu-form?")

Premise

The language Lojban is a constructed language, meaning in part that all of its words have been created rather than allowed to develop naturally. The semantic base of Lojban are its gismu, or root words, which were synthesized by combining roots from widely spoken natural languages like Chinese, Hindi, and English. All gismu are 5 letters long and follow a certain strict form.

Information

For our purposes, the Lojban alphabet is:

```<code>abcdefgijklmnoprstuvxz
</code>```

That is, the Roman alphabet without hqwy.

This alphabet can be divided into four categories:

Vowels aeiou

Sonorant consonants lmnr

Unvoiced consonants ptkfcsx. When voiced, these become respectively the...

Voiced consonants bdgvjz (No voiced consonant corresponds to x.)

To be a valid gismu, a 5-char-long string must:

Be in one of the consonant-vowel patterns CVCCV or CCVCV, where C represents a consonant, and V represents a vowel.

Follow consonant-matching rules.

Consonant-matching rules for CCVCV words:

The first two characters must constitute one of the following 48 pairs (source):

```<code>ml mr
pl pr
bl br
   tr                   tc ts
   dr                   dj dz
kl kr
gl gr
fl fr
vl vr
cl cr cm cn cp ct ck cf
      jm    jb jd jg jv
sl sr sm sn sp st sk sf
      zm    zb zd zg zv
xl xr
</code>```

Note that this looks rather nicer when separated into voiced and unvoiced pairs. In particular, every voiced-voiced pair is valid iff the corresponding unvoiced-unvoiced pair is valid. This does not extend to pairs with a sonorant consonant; cl is valid but jl is not.

Consonant-matching rules for CVCCV words (source):

The third and fourth characters must follow the following rules:

It is forbidden for both consonants to be the same [...]

It is forbidden for one consonant to be voiced and the other unvoiced. The consonants “l”, “m”, “n”, and “r” are exempt from this
  restriction. As a result, “bf” is forbidden, and so is “sd”, but both
  “fl” and “vl”, and both “ls” and “lz”, are permitted.

It is forbidden for both consonants to be drawn from the set “c”, “j”, “s”, “z”.

The specific pairs “cx”, “kx”, “xc”, “xk”, and “mz” are forbidden.

Note that there are 179 possible pairs.

Challenge

Determine if the given string follows the gismu formation rules. This is code-golf, so the shortest solution in bytes wins.

Input: A string of length 5 from the Lojban alphabet.

Output: A truthy value if the string can be a gismu and a falsey value otherwise.

Test cases

Valid:

```<code>gismu
cfipu
ranxi
mupno
rimge
zosxa
</code>```

Invalid:

```<code>ejram
xitot
dtpno
rcare
pxuja
cetvu
</code>```

More test cases: this text file contains all valid gismu, one per line.

I don't really know Lojban, so I suspect the title translation is wrong. Help is appreciated.

答:
Javascript ES6, 240 bytes

```<code>x=>eval(`/${(c='[bcdfgjklmnprstvxz]')+c+(v='[aeiou]')+c+v}/${t='.test(x)'}?/^[bfgkmpvx][lr]|[cs][fklmnprt]|d[jrz]|[jz][bdgmv]/${t}:/${c+v+c+c+v}/${t}?!/^..((.)\\2|${V='[bdgvjz]'}${U='[ptkfcsx]'}|${U+V}|[cjsz][cjsz]|cx|kx|xc|xk|mz)/${t}:!1`)
</code>```

I guess this is my work now.

ContentLicense: CC BY-SA 3.0

Body:
Javascript ES6, 240 bytes

x=>eval(`/${(c='[bcdfgjklmnprstvxz]')+c+(v='[aeiou]')+c+v}/${t='.test(x)'}?/^[bfgkmpvx][lr]|[cs][fklmnprt]|d[jrz]|[jz][bdgmv]/${t}:/${c+v+c+c+v}/${t}?!/^..((.)\\2|${V='[bdgvjz]'}${U='[ptkfcsx]'}|${U+V}|[cjsz][cjsz]|cx|kx|xc|xk|mz)/${t}:!1`)

I guess this is my work now.


问:
Subsequence Substitution
Most languages come with a built-in to search a string for all occurrences of a given substring and replace those with another. I don't know of any language that generalises this concept to (not necessarily contiguous) subsequences. So that's your task in this challenge.

The input will consist of three strings A, B and C, where B and C are guaranteed to be of the same length. If B appears as a subsequence in A it should be replaced with C. Here is a simple example:

```<code>A: abcdefghijklmnopqrstuvwxyz
B: ghost
C: 12345
</code>```

It would be processed like this:

```<code>abcdefghijklmnopqrstuvwxyz
      ||      |   ||
abcdef12ijklmn3pqr45uvwxyz
</code>```

If there are several ways to find B as a subsequence, you should greedily replace the left-most one:

```<code>A: abcdeedcba
B: ada
C: BOB

Result:   BbcOeedcbB
and NOT:  BbcdeeOcbB
</code>```

The same applies if B could be found in multiple disjoint places:

```<code>A: abcdeedcbaabcde
B: ed
C: 12

Result:   abcd1e2cbaabcde
and NOT:  abcd112cbaabc2e (or similar)
</code>```

When B does not appear in A, you should output A unchanged.

Rules

As stated above, take three strings A, B and C as input and replace the left-most occurrence of B as a subsequence in A with C, if there is any.

You may write a program or function, taking input via STDIN (or closest alternative), command-line argument or function argument and outputting the result via STDOUT (or closest alternative), function return value or function (out) parameter.

You may take the three strings in any consistent order which you should specify in your answer. You may assume that B and C have the same length. All strings will only contain alphanumeric characters.

Standard code-golf rules apply.

Test Cases

Each test case is four lines: A, B, C followed by the result.

```<code>abcdefghijklmnopqrstuvwxyz
ghost
12345
abcdef12ijklmn3pqr45uvwxyz

abcdeedcba
ada
BOB
BbcOeedcbB

abcdeedcbaabcde
ed
12
abcd1e2cbaabcde

121
121
aBc
aBc

abcde
acb
123
abcde

ABC
ABCD
1234
ABC

012345678901234567890123456789
42
TT
0123T5678901T34567890123456789

edcbaedcbaedcbaedcba
abcde
12345
edcbaedcbaedcbaedcba

edcbaedcbaedcbaedcbaedcba
abcde
12345
edcb1edc2aed3bae4cba5dcba

daccdedca
ace
cra
dcrcdadca

aacbcbabcccaabcbabcaabbbbca
abaaaccbac
1223334444
aacbcbabcccaabcbabcaabbbbca

aacbcbabcccaabcbabcaabbbbcac
abaaaccbac
1223334444
1ac2cb2bccc33b3bab4aa4bbbc44
</code>```

Leaderboard

The Stack Snippet at the bottom of this post generates leaderboards from the answers a) as a list of shortest solution per language and b) as an overall leaderboard.

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>```

If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the last number in the header:

```<code>## Perl, 43 + 2 (-p flag) = 45 bytes
</code>```

You can also make the language name a link which will then show up in the snippet:

```<code>## [><>](http://esolangs.org/wiki/Fish), 121 bytes
</code>```

/* Configuration */

var QUESTION_ID = 77719; // Obtain this from the url
// It will be like http://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page
var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";
var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk";
var OVERRIDE_USER = 8478; // This should be the user ID of the challenge author.

/* App */

var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page;

function answersUrl(index) {
  return "http://api.stackexchange.com/2.2/questions/" +  QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER;
}

function commentUrl(index, answers) {
  return "http://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER;
}

function getAnswers() {
  jQuery.ajax({
    url: answersUrl(answer_page++),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      answers.push.apply(answers, data.items);
      answers_hash = [];
      answer_ids = [];
      data.items.forEach(function(a) {
        a.comments = [];
        var id = +a.share_link.match(/\d+/);
        answer_ids.push(id);
        answers_hash[id] = a;
      });
      if (!data.has_more) more_answers = false;
      comment_page = 1;
      getComments();
    }
  });
}

function getComments() {
  jQuery.ajax({
    url: commentUrl(comment_page++, answer_ids),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      data.items.forEach(function(c) {
        if (c.owner.user_id === OVERRIDE_USER)
          answers_hash[c.post_id].comments.push(c);
      });
      if (data.has_more) getComments();
      else if (more_answers) getAnswers();
      else process();
    }
  });
}

getAnswers();

var SCORE_REG = /<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/;

var OVERRIDE_REG = /^Override\s*header:\s*/i;

function getAuthorName(a) {
  return a.owner.display_name;
}

function process() {
  var valid = [];

  answers.forEach(function(a) {
    var body = a.body;
    a.comments.forEach(function(c) {
      if(OVERRIDE_REG.test(c.body))
        body = '
' + c.body.replace(OVERRIDE_REG, '') + '
';
    });

    var match = body.match(SCORE_REG);
    if (match)
      valid.push({
        user: getAuthorName(a),
        size: +match[2],
        language: match[1],
        link: a.share_link,
      });
    else console.log(body);
  });

  valid.sort(function (a, b) {
    var aB = a.size,
        bB = b.size;
    return aB - bB
  });

  var languages = {};
  var place = 1;
  var lastSize = null;
  var lastPlace = 1;
  valid.forEach(function (a) {
    if (a.size != lastSize)
      lastPlace = place;
    lastSize = a.size;
    ++place;

    var answer = jQuery("#answer-template").html();
    answer = answer.replace("{{PLACE}}", lastPlace + ".")
                   .replace("{{NAME}}", a.user)
                   .replace("{{LANGUAGE}}", a.language)
                   .replace("{{SIZE}}", a.size)
                   .replace("{{LINK}}", a.link);
    answer = jQuery(answer);
    jQuery("#answers").append(answer);

    var lang = a.language;
    lang = jQuery(''+lang+'').text();

    languages[lang] = languages[lang] || {lang: a.language, lang_raw: lang, user: a.user, size: a.size, link: a.link};
  });

  var langs = [];
  for (var lang in languages)
    if (languages.hasOwnProperty(lang))
      langs.push(languages[lang]);

  langs.sort(function (a, b) {
    if (a.lang_raw.toLowerCase() > b.lang_raw.toLowerCase()) return 1;
    if (a.lang_raw.toLowerCase() < b.lang_raw.toLowerCase()) return -1;
    return 0;
  });

  for (var i = 0; i < langs.length; ++i)
  {
    var language = jQuery("#language-template").html();
    var lang = langs[i];
    language = language.replace("{{LANGUAGE}}", lang.lang)
                       .replace("{{NAME}}", lang.user)
                       .replace("{{SIZE}}", lang.size)
                       .replace("{{LINK}}", lang.link);
    language = jQuery(language);
    jQuery("#languages").append(language);
  }

}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body { text-align: left !important}

#answer-list {
  padding: 10px;
  width: 290px;
  float: left;
}

#language-list {
  padding: 10px;
  width: 290px;
  float: left;
}

table thead {
  font-weight: bold;
}

table td {
  padding: 5px;
}</code>```

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

Shortest Solution by Language

Language	User	Score

Leaderboard

	Author	Language	Size

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

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

```

答:
Python 3, 123 Bytes

A different approach I wanted to share, which is a few bytes shorter. There are no rules against standard library/regex, right?

```<code>import re
j=''.join
m='(.*?)'
def f(A,B,C):
 *r,l=(re.findall(m+m.join(B)+'(.*)',A)or[[A]])[0]
 print(j(map(j,zip(r,C)))+l)
</code>```

PS. This is my first golf. Let me know of any issues/improvements.

Title: Subsequence Substitution

Body:
Python 3, 123 Bytes

A different approach I wanted to share, which is a few bytes shorter. There are no rules against standard library/regex, right?

import re
j=''.join
m='(.*?)'
def f(A,B,C):
 *r,l=(re.findall(m+m.join(B)+'(.*)',A)or[[A]])[0]
 print(j(map(j,zip(r,C)))+l)

PS. This is my first golf. Let me know of any issues/improvements.


答:
R, 76 bytes

```<code>function(a,b,c){s=substr;for(x in 1:nchar(b)){a=sub(s(b,x,x),s(c,x,x),a)};a}
</code>```

uses sub to replace first match

Ungolfed

```<code>function(a,b,c){                    # function with 3 arguments as per description
  s=substr;                         # alias for substr (saves 1 byte)
   for(x in 1:nchar(b)){            # index 1 to number character in b
     a=sub(s(b,x,x),s(c,x,x),a)};   # replace first instance of b[x] in a
                                    # with c[x] and reassign to a
 a}                                 # return a
</code>```

Title: Subsequence Substitution

Body:
Most languages come with a built-in to search a string for all occurrences of a given substring and replace those with another. I don't know of any language that generalises this concept to (not necessarily contiguous) subsequences. So that's your task in this challenge.

The input will consist of three strings A, B and C, where B and C are guaranteed to be of the same length. If B appears as a subsequence in A it should be replaced with C. Here is a simple example:

```<code>A: abcdefghijklmnopqrstuvwxyz
B: ghost
C: 12345
</code>```

It would be processed like this:

```<code>abcdefghijklmnopqrstuvwxyz
      ||      |   ||
abcdef12ijklmn3pqr45uvwxyz
</code>```

If there are several ways to find B as a subsequence, you should greedily replace the left-most one:

```<code>A: abcdeedcba
B: ada
C: BOB

Result:   BbcOeedcbB
and NOT:  BbcdeeOcbB
</code>```

The same applies if B could be found in multiple disjoint places:

```<code>A: abcdeedcbaabcde
B: ed
C: 12

Result:   abcd1e2cbaabcde
and NOT:  abcd112cbaabc2e (or similar)
</code>```

When B does not appear in A, you should output A unchanged.

Rules

As stated above, take three strings A, B and C as input and replace the left-most occurrence of B as a subsequence in A with C, if there is any.

You may write a program or function, taking input via STDIN (or closest alternative), command-line argument or function argument and outputting the result via STDOUT (or closest alternative), function return value or function (out) parameter.

You may take the three strings in any consistent order which you should specify in your answer. You may assume that B and C have the same length. All strings will only contain alphanumeric characters.

Standard code-golf rules apply.

Test Cases

Each test case is four lines: A, B, C followed by the result.

```<code>abcdefghijklmnopqrstuvwxyz
ghost
12345
abcdef12ijklmn3pqr45uvwxyz

abcdeedcba
ada
BOB
BbcOeedcbB

abcdeedcbaabcde
ed
12
abcd1e2cbaabcde

121
121
aBc
aBc

abcde
acb
123
abcde

ABC
ABCD
1234
ABC

012345678901234567890123456789
42
TT
0123T5678901T34567890123456789

edcbaedcbaedcbaedcba
abcde
12345
edcbaedcbaedcbaedcba

edcbaedcbaedcbaedcbaedcba
abcde
12345
edcb1edc2aed3bae4cba5dcba

daccdedca
ace
cra
dcrcdadca

aacbcbabcccaabcbabcaabbbbca
abaaaccbac
1223334444
aacbcbabcccaabcbabcaabbbbca

aacbcbabcccaabcbabcaabbbbcac
abaaaccbac
1223334444
1ac2cb2bccc33b3bab4aa4bbbc44
</code>```

Leaderboard

The Stack Snippet at the bottom of this post generates leaderboards from the answers a) as a list of shortest solution per language and b) as an overall leaderboard.

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>```

If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the last number in the header:

```<code>## Perl, 43 + 2 (-p flag) = 45 bytes
</code>```

You can also make the language name a link which will then show up in the snippet:

```<code>## [><>](http://esolangs.org/wiki/Fish), 121 bytes
</code>```

/* Configuration */

var QUESTION_ID = 77719; // Obtain this from the url
// It will be like http://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page
var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";
var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk";
var OVERRIDE_USER = 8478; // This should be the user ID of the challenge author.

/* App */

var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page;

function answersUrl(index) {
  return "http://api.stackexchange.com/2.2/questions/" +  QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER;
}

function commentUrl(index, answers) {
  return "http://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER;
}

function getAnswers() {
  jQuery.ajax({
    url: answersUrl(answer_page++),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      answers.push.apply(answers, data.items);
      answers_hash = [];
      answer_ids = [];
      data.items.forEach(function(a) {
        a.comments = [];
        var id = +a.share_link.match(/\d+/);
        answer_ids.push(id);
        answers_hash[id] = a;
      });
      if (!data.has_more) more_answers = false;
      comment_page = 1;
      getComments();
    }
  });
}

function getComments() {
  jQuery.ajax({
    url: commentUrl(comment_page++, answer_ids),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      data.items.forEach(function(c) {
        if (c.owner.user_id === OVERRIDE_USER)
          answers_hash[c.post_id].comments.push(c);
      });
      if (data.has_more) getComments();
      else if (more_answers) getAnswers();
      else process();
    }
  });
}

getAnswers();

var SCORE_REG = /<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/;

var OVERRIDE_REG = /^Override\s*header:\s*/i;

function getAuthorName(a) {
  return a.owner.display_name;
}

function process() {
  var valid = [];

  answers.forEach(function(a) {
    var body = a.body;
    a.comments.forEach(function(c) {
      if(OVERRIDE_REG.test(c.body))
        body = '
' + c.body.replace(OVERRIDE_REG, '') + '
';
    });

    var match = body.match(SCORE_REG);
    if (match)
      valid.push({
        user: getAuthorName(a),
        size: +match[2],
        language: match[1],
        link: a.share_link,
      });
    else console.log(body);
  });

  valid.sort(function (a, b) {
    var aB = a.size,
        bB = b.size;
    return aB - bB
  });

  var languages = {};
  var place = 1;
  var lastSize = null;
  var lastPlace = 1;
  valid.forEach(function (a) {
    if (a.size != lastSize)
      lastPlace = place;
    lastSize = a.size;
    ++place;

    var answer = jQuery("#answer-template").html();
    answer = answer.replace("{{PLACE}}", lastPlace + ".")
                   .replace("{{NAME}}", a.user)
                   .replace("{{LANGUAGE}}", a.language)
                   .replace("{{SIZE}}", a.size)
                   .replace("{{LINK}}", a.link);
    answer = jQuery(answer);
    jQuery("#answers").append(answer);

    var lang = a.language;
    lang = jQuery(''+lang+'').text();

    languages[lang] = languages[lang] || {lang: a.language, lang_raw: lang, user: a.user, size: a.size, link: a.link};
  });

  var langs = [];
  for (var lang in languages)
    if (languages.hasOwnProperty(lang))
      langs.push(languages[lang]);

  langs.sort(function (a, b) {
    if (a.lang_raw.toLowerCase() > b.lang_raw.toLowerCase()) return 1;
    if (a.lang_raw.toLowerCase() < b.lang_raw.toLowerCase()) return -1;
    return 0;
  });

  for (var i = 0; i < langs.length; ++i)
  {
    var language = jQuery("#language-template").html();
    var lang = langs[i];
    language = language.replace("{{LANGUAGE}}", lang.lang)
                       .replace("{{NAME}}", lang.user)
                       .replace("{{SIZE}}", lang.size)
                       .replace("{{LINK}}", lang.link);
    language = jQuery(language);
    jQuery("#languages").append(language);
  }

}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body { text-align: left !important}

#answer-list {
  padding: 10px;
  width: 290px;
  float: left;
}

#language-list {
  padding: 10px;
  width: 290px;
  float: left;
}

table thead {
  font-weight: bold;
}

table td {
  padding: 5px;
}</code>```

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

Shortest Solution by Language

Language	User	Score

Leaderboard

	Author	Language	Size

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

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

```

Body:
R, 76 bytes

function(a,b,c){s=substr;for(x in 1:nchar(b)){a=sub(s(b,x,x),s(c,x,x),a)};a}

uses sub to replace first match

Ungolfed

function(a,b,c){                    # function with 3 arguments as per description
  s=substr;                         # alias for substr (saves 1 byte)
   for(x in 1:nchar(b)){            # index 1 to number character in b
     a=sub(s(b,x,x),s(c,x,x),a)};   # replace first instance of b[x] in a
                                    # with c[x] and reassign to a
 a}                                 # return a


答:
Pyth, 22 bytes

```<code>|eJ:Ej"(.*?)"+E\$3s.iJ
</code>```

Verify all test cases in the Pyth Compiler.

Background

We build a regex from the pattern by appending a $ and placing (.*?) between all characters. This regex will match the subsequence to be replaced and anything between its elements, and anything up to the end of the string.

Since the quantifiers are lazy, each (.*?) will match as few characters as possible.

For the pattern ghost, the constructed regex is g(.*?)h(.*?)o(.*?)s(.*?)t(.*?)$.

If the pattern matches the input, the builtin r<str><regex>3 will return an array containing the prematch (everything before the subsequence), all captured groups (everything in between and after the subsequence), and the postmatch (the empty string).

If the pattern does not match, the builtin will return a singleton array containing the original input.

How it works

```<code>|eJ:Ej"(.*?)"+E\$3s.iJQ  (implicit) Store the first line of input in Q.

             +E\$        Read the third line of input (pattern) and append '$'.
     j"(.*?)"            Join the result, separating by "(.*?)".
    E                    Read the third line of input (string).
   :             3       Match the string against the regex, as detailed above.
  J                      Save the returned array in J.
 e                       Extract the last element of J. This is an empty string
                         for a successful match or the original string.
|                        Logical OR; replace an empty string with the following:
                   .iJQ    Interleave J and the replacement.
                  s        Flatten the resulting array of strings.
</code>```

Title: Subsequence Substitution

Body:
Pyth, 22 bytes

|eJ:Ej"(.*?)"+E\$3s.iJ

Verify all test cases in the <a href="https://pyth.herokuapp.com/?code=%7CeJ%3AEj%22%28.%2a%3F%29%22%2BE%5C%243s.iJ&test_suite=1&test_suite_input=%2212345%22%0A%22abcdefghijklmnopqrstuvwxyz%22%0A%22ghost%22%0A%22BOB%22%0A%22abcdeedcba%22%0A%22ada%22%0A%2212%22%0A%22abcdeedcbaabcde%22%0A%22ed%22%0A%22aBc%22%0A%22121%22%0A%22121%22%0A%22123%22%0A%22abcde%22%0A%22acb%22%0A%221234%22%0A%22ABC%22%0A%22ABCD%22%0A%22TT%22%0A%22012345678901234567890123456789%22%0A%2242%22%0A%2212345%22%0A%22edcbaedcbaedcbaedcba%22%0A%22abcde%22%0A%2212345%22%0A%22edcbaedcbaedcbaedcbaedcba%22%0A%22abcde%22%0A%22cra%22%0A%22daccdedca%22%0A%22ace%22%0A%221223334444%22%0A%22aacbcbabcccaabcbabcaabbbbca%22%0A%22abaaaccbac%22%0A%221223334444%22%0A%22aacbcbabcccaabcbabcaabbbbcac%22%0A%22abaaaccbac%22&debug=0&input_size=3" rel="nofollow">Pyth Compiler.

Background

We build a regex from the pattern by appending a $ and placing (.*?) between all characters. This regex will match the subsequence to be replaced and anything between its elements, and anything up to the end of the string.

Since the quantifiers are lazy, each (.*?) will match as few characters as possible.

For the pattern ghost, the constructed regex is g(.*?)h(.*?)o(.*?)s(.*?)t(.*?)$.

If the pattern matches the input, the builtin r<str><regex>3 will return an array containing the prematch (everything before the subsequence), all captured groups (everything in between and after the subsequence), and the postmatch (the empty string).

If the pattern does not match, the builtin will return a singleton array containing the original input.

How it works

|eJ:Ej"(.*?)"+E\$3s.iJQ  (implicit) Store the first line of input in Q.

             +E\$        Read the third line of input (pattern) and append '$'.
     j"(.*?)"            Join the result, separating by "(.*?)".
    E                    Read the third line of input (string).
   :             3       Match the string against the regex, as detailed above.
  J                      Save the returned array in J.
 e                       Extract the last element of J. This is an empty string
                         for a successful match or the original string.
|                        Logical OR; replace an empty string with the following:
                   .iJQ    Interleave J and the replacement.
                  s        Flatten the resulting array of strings.


答:
C++, 204 bytes

Golfed

#include<iostream>
#include<string>
int main(){std::string a, b, c;std::cin>>a>>b>>c;int t=0;for(int x=0;x<b.length();x++){t=a.find(b[x],t);if(t!=-1){a.replace(t,1,c.substr(x,1));}}std::cout<<a;return 0;}
```

<h3>Ungolfed</h3>

<pre class="lang-cpp prettyprint-override"><code>#include<iostream>
#include<string>

int main()
{
    std::string a, b, c;
    std::cin>>a>>b>>c;
    int t = 0;
    for (int x=0;x<b.length();x++) {
        t = a.find(b[x], t);
        if (t != -1) {
            a.replace(t,1,c.substr(x, 1));
        }
    }
    std::cout<<a;
    return 0;
}
</code>```

Title: Subsequence Substitution

Body:
C++, 204 bytes

Golfed

#include<iostream>
#include<string>
int main(){std::string a, b, c;std::cin>>a>>b>>c;int t=0;for(int x=0;x<b.length();x++){t=a.find(b[x],t);if(t!=-1){a.replace(t,1,c.substr(x,1));}}std::cout<<a;return 0;}

Ungolfed

#include<iostream>
#include<string>

int main()
{
    std::string a, b, c;
    std::cin>>a>>b>>c;
    int t = 0;
    for (int x=0;x<b.length();x++) {
        t = a.find(b[x], t);
        if (t != -1) {
            a.replace(t,1,c.substr(x, 1));
        }
    }
    std::cout<<a;
    return 0;
}


答:
Python 3.5, 87 bytes

```<code>import re
lambda s,p,r:re.sub('(.*?)'.join(p),'\g<%d>'.join(r)%(*range(1,len(r)),),s,1)
</code>```

repl.it to verify all test cases.

How it works

'(.*?)'.join(p) builds a search pattern that matches the subsequence to be replaced and anything between its elements.

Since the quantifiers are lazy, each (.*?) will match as few characters as possible.

For the pattern ghost, the constructed regex is g(.*?)h(.*?)o(.*?)s(.*?)t.

'\g<%d>'.join(r)%(*range(1,len(r)),) builds the replacement string, using string formatting.

Each \g<n> refers to the nth captured group, just like \n would.

For the replacement 12345, the constructed string is 1\g<1>2\g<2>3\g<3>4\g<4>5.

re.sub(...,...,s,1) performs at most one replacement in the string s.

Title: Subsequence Substitution

Body:
Python 3.5, 87 bytes

import re
lambda s,p,r:re.sub('(.*?)'.join(p),'\g<%d>'.join(r)%(*range(1,len(r)),),s,1)

repl.it to verify all test cases.

How it works

'(.*?)'.join(p) builds a search pattern that matches the subsequence to be replaced and anything between its elements.

Since the quantifiers are lazy, each (.*?) will match as few characters as possible.

For the pattern ghost, the constructed regex is g(.*?)h(.*?)o(.*?)s(.*?)t.

'\g<%d>'.join(r)%(*range(1,len(r)),) builds the replacement string, using string formatting.

Each \g<n> refers to the nth captured group, just like \n would.

For the replacement 12345, the constructed string is 1\g<1>2\g<2>3\g<3>4\g<4>5.

re.sub(...,...,s,1) performs at most one replacement in the string s.


问:
Find the program that prints this integer sequence (Robbers' thread)
This is the robbers' thread. The cops' thread goes here.

In the cops thread, the task was to write a program/function that takes a positive (or non-negative) integer and outputs/returns another number (not necessarily integer). The robbers task is to unscramble the code the cops used to produce this output.

The cracked code doesn't have to be identical, as long as it has the same length and any revealed characters are in the correct positions. The language must also be the same (version numbers can be different). The output must of course be identical.

No-ops can be used in robber's solution.

The winner of the robbers thread will be the user who has cracked the
most submissions by May 7th 2016. If there's a tie, the user who has cracked submissions with the longest combined code will win.

The submission should be formatted like this:

Language, nn characters (including link to answer), Cop's username

Code:

```<code>function a(n)
    if n<2 then
        return n
    else
        return a(n-1) + a(n-2)
    end
end
</code>```

Output

```<code>a(0) returns 0
a(3) returns 2
</code>```

Optional explanation and comments.

答:
JavaScript, 10 bytes, user81655, A033999

<s>I think</s> I got it. Yeah. This one was really hard. I like the submission because it relies heavily on precedences.

It's the sequence A033999:

a(n) = (-1)^n.

Source

```<code>t=>~t.z**t
</code>```

Explanation

If you split this code according to the JavaScript operator precedences you get:

. (precedence 18) gets evaluated first and t.z will return undefined.

~ (precedence 15) tries to cast undefined, resulting in 0, and returns -1 after bitwise not.

** (precedence 14) will return -1 ^ t, where t is odd or even, resulting in -1 or 1.

Demo

```<code>console.log(
    (t=>~t.z**t)(0),
    (t=>~t.z**t)(1),
);
</code>```

Try before buy

I will award a 100 rep bounty on this cool Cop submission.

Body:
JavaScript, 10 bytes, user81655, A033999

<s>I think</s> I got it. Yeah. This one was really hard. I like the submission because it relies heavily on precedences.

It's the sequence A033999:

a(n) = (-1)^n.

Source

t=>~t.z**t

Explanation

If you split this code according to the JavaScript operator precedences you get:

. (precedence 18) gets evaluated first and t.z will return undefined.

~ (precedence 15) tries to cast undefined, resulting in 0, and returns -1 after bitwise not.

** (precedence 14) will return -1 ^ t, where t is odd or even, resulting in -1 or 1.

Demo

console.log(
    (t=>~t.z**t)(0),
    (t=>~t.z**t)(1),
);

Try before buy

I will award a 100 rep bounty on this cool Cop submission.


答:
Jelly, <s>23</s> <s>22</s> 21 bytes

```<code>='T€ŒpfṢ€$ḢṬœp³ż⁵$³Ḋ?
</code>```

Try it online! Note that the last two test cases will run out of memory.

Verification

```<code>$ head -n 5 test-cases
abcdefghijklmnopqrstuvwxyz
ghost
12345
abcdef12ijklmn3pqr45uvwxyz

$ cat subseq-short
while read s; do
        read p; read r; read o; echo $o; read
        timeout 1s jelly eun $1 "='T€ŒpfṢ€$ḢṬœp³ż⁵$³Ḋ?" "'$s'" "'$p'" "'$r'"
        (($?)) && echo '(killed)'
done < test-cases
$ ./subseq-short
abcdef12ijklmn3pqr45uvwxyz
abcdef12ijklmn3pqr45uvwxyz
BbcOeedcbB
BbcOeedcbB
abcd1e2cbaabcde
abcd1e2cbaabcde
aBc
aBc
abcde
abcde
ABC
ABC
0123T5678901T34567890123456789
0123T5678901T34567890123456789
edcbaedcbaedcbaedcba
edcbaedcbaedcbaedcba
edcb1edc2aed3bae4cba5dcba
edcb1edc2aed3bae4cba5dcba
dcrcdadca
dcrcdadca
aacbcbabcccaabcbabcaabbbbca
(killed)
1ac2cb2bccc33b3bab4aa4bbbc44
(killed)
</code>```

How it works

```<code>='T€ŒpfṢ€$ḢṬœp³ż⁵$³Ḋ?  Main link. Arguments: string s, pattern p, replacement r

='                     Compare each character of s with each character of p.
                       This yields a 2D list. Each row corresponds to a char in p.
  T€                   Compute the truthy indices of each row, i.e., the indices
                       of all occurrences of that char in s.
   Œp                  Compute the Cartesian product of the lists of indices.
        $              Combine the two links to the left into a monadic chain:
      Ṣ€                 Sort each list of indices.
     f                   Filter, removing all non-sorted lists of indices.
         Ḣ             Head; take the first (sorted) list of indices.
          Ṭ            Truth; generate a list with 1's at those indices.
           œp³         Partition; split s at all 1's, removing those characters.
                  Ḋ?   If the partition has more than more than one element:
              ż⁵$        Zip the partition with r.
                 ³       Else, return s.
</code>```

Title: Subsequence Substitution

Body:
Jelly, <s>23</s> <s>22</s> 21 bytes

='T€ŒpfṢ€$ḢṬœp³ż⁵$³Ḋ?

Try it online! Note that the last two test cases will run out of memory.

Verification

$ head -n 5 test-cases
abcdefghijklmnopqrstuvwxyz
ghost
12345
abcdef12ijklmn3pqr45uvwxyz

$ cat subseq-short
while read s; do
        read p; read r; read o; echo $o; read
        timeout 1s jelly eun $1 "='T€ŒpfṢ€$ḢṬœp³ż⁵$³Ḋ?" "'$s'" "'$p'" "'$r'"
        (($?)) && echo '(killed)'
done < test-cases
$ ./subseq-short
abcdef12ijklmn3pqr45uvwxyz
abcdef12ijklmn3pqr45uvwxyz
BbcOeedcbB
BbcOeedcbB
abcd1e2cbaabcde
abcd1e2cbaabcde
aBc
aBc
abcde
abcde
ABC
ABC
0123T5678901T34567890123456789
0123T5678901T34567890123456789
edcbaedcbaedcbaedcba
edcbaedcbaedcbaedcba
edcb1edc2aed3bae4cba5dcba
edcb1edc2aed3bae4cba5dcba
dcrcdadca
dcrcdadca
aacbcbabcccaabcbabcaabbbbca
(killed)
1ac2cb2bccc33b3bab4aa4bbbc44
(killed)

How it works

='T€ŒpfṢ€$ḢṬœp³ż⁵$³Ḋ?  Main link. Arguments: string s, pattern p, replacement r

='                     Compare each character of s with each character of p.
                       This yields a 2D list. Each row corresponds to a char in p.
  T€                   Compute the truthy indices of each row, i.e., the indices
                       of all occurrences of that char in s.
   Œp                  Compute the Cartesian product of the lists of indices.
        $              Combine the two links to the left into a monadic chain:
      Ṣ€                 Sort each list of indices.
     f                   Filter, removing all non-sorted lists of indices.
         Ḣ             Head; take the first (sorted) list of indices.
          Ṭ            Truth; generate a list with 1's at those indices.
           œp³         Partition; split s at all 1's, removing those characters.
                  Ḋ?   If the partition has more than more than one element:
              ż⁵$        Zip the partition with r.
                 ³       Else, return s.


问:
Collatz Conjecture (OEIS A006577)
This is the Collatz Conjecture (OEIS A006577):

Start with an integer n > 1.

Repeat the following steps:

If n is even, divide it by 2.

If n is odd, multiply it by 3 and add 1.

It is proven that for all positive integers up to 5 * 260, or about 5764000000000000000, n will eventually become 1.

Your task is to find out how many iterations it takes (of halving or tripling-plus-one) to reach 1.

Relevant xkcd :)

Rules:

Shortest code wins.

If a number < 2 is input, or a non-integer, or a non-number, output does not matter.

Test cases

```<code>2  -> 1
16 -> 4
5  -> 5
7  -> 16
</code>```

答:
Befunge, <s>42</s> 40 bytes

Surprisingly short to be an esolang! I thank @Sok for showing how to avoid one extra branching in his answer. Saved 2 bytes after a complete rewriting of the code.

```<code>0&>\1+\:2/\:3v
.$<v_v#%2\+1*<@
`!|>\>$:1
</code>```

Original answer:

```<code>1&>:2%v>2v
^\+1*3_^ /
>+v  v`1:<
^1\#\_$.@
</code>```

Shold be compatible with both Befunge 93 and Befunge 98. Interpretor available here.

There is no need for a trailing white space after @, so I count it as 42. However, 2D languages are often counted by their bounding box.

ContentLicense: CC BY-SA 4.0

Title: Collatz Conjecture (OEIS A006577)

Body:
Befunge, <s>42</s> 40 bytes

Surprisingly short to be an esolang! I thank @Sok for showing how to avoid one extra branching in his answer. Saved 2 bytes after a complete rewriting of the code.

0&>\1+\:2/\:3v
.$<v_v#%2\+1*<@
`!|>\>$:1

Original answer:

1&>:2%v>2v
^\+1*3_^ /
>+v  v`1:<
^1\#\_$.@

Shold be compatible with both Befunge 93 and Befunge 98. Interpretor available here.

There is no need for a trailing white space after @, so I count it as 42. However, 2D languages are often counted by their bounding box.


答:
Mathematica, <s>130</s> 129 bytes

```<code>#&@@FirstPosition[Partition[CellularAutomaton[{224,{2,{{2,2,2},{2,1,2},{2,2,2}}},{1,1}},#,2^Length[Join@@#]],2,1],{x_,x_},0,1]-1&
</code>```

I wouldn't recommend trying more than 4x4 inputs, because it's going to take forever (and a lot of memory).

Explanation

This simply simulates the Game of Life for 2N steps where N is the number of cells in the input. This guarantees that if the system settles into a stable state, we've reached it. Afterwards, we find the first pair of consecutive identical states in the simulated history.

Let's go through the code:

```<code>2^Length[Join@@#]
</code>```

This computes 2N, since Join@@ is used to flatten a 2D list.

```<code>CellularAutomaton[{224,{2,{{2,2,2},{2,1,2},{2,2,2}}},{1,1}},#,...]
</code>```

This simulates the Game of Life for 2N generations. The 3x3 matrix specifies the neighbourhood of a totalistic 2D automaton and 224 is the rule number of standard Game of Life. I've written about how to compute this number over here on Mathematica.SE.

```<code>Partition[...,2,1]
</code>```

This gets all consecutive (overlapping) pairs of generations.

```<code>FirstPosition[...,{x_,x_},0,1]
</code>```

This finds the first pair of identical generations, defaulting to 0 if none is found and limiting the search to depth 1. If such a pair is found, the result is returned in a list though. So we use:

```<code>#&@@...
</code>```

To extract the first element from that list (the default value of 0, being atomic, is unaffected by this).

```<code>...-1
</code>```

Finally we subtract one because the challenge expects 0-based indices and -1 for failure.

Title: Stable Game of Life

Body:
Challenge:

Given a matrix (or 2d array) of 0s and 1s, output the number of steps it takes for Conway's game of life to reach a stable state, or -1 if it never reaches one.  A stable state is a state in which no cells are turned on or off each step.  The game must run in the  given matrix, with the top and bottom connected, and the sides connected. (i.e. given a 4x3 matrix it should run on a 4x3 torus)  The input matrix will not be larger than 15x15.

Note: If the matrix starts in a stable state, the output should be 0.

Samples:

Input:

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

Output:

2

Process: (this does not need to be displayed)

```<code>[[0,0,0],
 [0,1,1],
 [0,1,0]]

[[1,1,1],
 [1,1,1],
 [1,1,1]]

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

Input:

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

Output:

2

Process:

```<code>[[0,0,1,1],
 [0,1,1,1],
 [0,1,0,0],
 [0,1,1,1]]

[[0,0,0,0],
 [0,1,0,1],
 [0,0,0,0],
 [0,1,0,1]]

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

Input:

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

Output:

-1

Process:

```<code>[[0,1,0,0],
 [0,1,0,0],
 [0,1,0,0],
 [0,0,0,0]]

[[0,0,0,0],
 [1,1,1,0],
 [0,0,0,0],
 [0,0,0,0]]

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

repeating forever

Input:

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

Output:

4

Process:

```<code>[[0,0,0,0],
 [0,0,0,1],
 [0,1,1,1],
 [0,0,1,0]]

[[0,0,0,0],
 [1,0,0,1],
 [1,1,0,1],
 [0,1,1,1]]

[[0,1,0,0],
 [0,1,1,1],
 [0,0,0,0],
 [0,1,0,1]]

[[0,1,0,1],
 [1,1,1,0],
 [0,1,0,1],
 [1,0,1,0]]

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

Input:

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

Output:

0

Process:

The beginning state is stable.

Rules of the Game of Life

If a cell that is off (0) is next to exactly three on (1) cells, it is turned on. Otherwise, it is left off. If a cell that is on is next to 2 or 3 on squares, it says on.  Otherwise, it is turned off.

Body:
Mathematica, <s>130</s> 129 bytes

#&@@FirstPosition[Partition[CellularAutomaton[{224,{2,{{2,2,2},{2,1,2},{2,2,2}}},{1,1}},#,2^Length[Join@@#]],2,1],{x_,x_},0,1]-1&

I wouldn't recommend trying more than 4x4 inputs, because it's going to take forever (and a lot of memory).

Explanation

This simply simulates the Game of Life for 2N steps where N is the number of cells in the input. This guarantees that if the system settles into a stable state, we've reached it. Afterwards, we find the first pair of consecutive identical states in the simulated history.

Let's go through the code:

2^Length[Join@@#]

This computes 2N, since Join@@ is used to flatten a 2D list.

CellularAutomaton[{224,{2,{{2,2,2},{2,1,2},{2,2,2}}},{1,1}},#,...]

This simulates the Game of Life for 2N generations. The 3x3 matrix specifies the neighbourhood of a totalistic 2D automaton and 224 is the rule number of standard Game of Life. I've written about how to compute this number over here on Mathematica.SE.

Partition[...,2,1]

This gets all consecutive (overlapping) pairs of generations.

FirstPosition[...,{x_,x_},0,1]

This finds the first pair of identical generations, defaulting to 0 if none is found and limiting the search to depth 1. If such a pair is found, the result is returned in a list though. So we use:

#&@@...

To extract the first element from that list (the default value of 0, being atomic, is unaffected by this).

...-1

Finally we subtract one because the challenge expects 0-based indices and -1 for failure.


答:
Lua, <s>531</s> <s>509</s> <s>488</s> <s>487</s> <s>464</s> <s>424</s> <s>405</s> 404 Bytes

Who wants a massive submission? \o/

Edit: Improved it, but don't know how to golf it anymore, so... <s>explanations are coming</s> comments added :)

Saved ~60 bytes with the help of @KennyLau

small golfing cutting one more byte by renaming a into Y to prevent the inlined hexadecimal conversion

function f(m)c={}t=table.concat::z::c[#c+1]={}p=c[#c]Y={}for i=1,#m do k=m[i]p[#p+1]=t(k)Y[i]={}for j=1,#k
do v=m[i%#m+1]l=j%#k+1w=m[(i-2)%#m+1]h=(j-2)%#k+1Y[i][j]=v[l]+k[l]+w[l]+v[h]+v[j]+w[h]+w[j]+k[h]end
end s=''for i=1,#m do k=m[i]for j=1,k do
x=Y[i][j]k[j]=k[j]>0 and((x<2or x>3)and 0or 1)or (x==3 and 1or 0)end
s=s..t(k)end for i=1,#c do
if(s==t(c[i]))then return#c>i and-1or i-1
end end goto z end
```

<h3>Ungolfed</h3>

<pre class="lang-lua prettyprint-override"><code>function f(m)                -- takes a 2D array of 0 and 1s as input
  c={}                       -- intialise c -> contains a copy of each generation
  t=table.concat             -- shorthand for the concatenating function
  ::z::                      -- label z, used to do an infinite loop
    c[#c+1]={}               -- initialise the first copy
    p=c[#c]                  -- initialise a pointer to this copy
    a={}                     -- initialise the 2D array of adjacency
    for i=1,#m               -- iterate over the lines of m
    do
      k=m[i]                 -- shorthand for the current line
      p[#p+1]=t(k])          -- saves the current line of m as a string
      a[i]={}                -- initialise the array of adjacency for the current line
      for j=1,#k             -- iterate over each row of m
      do
                             -- the following statements are used to wraps at borders
        v=m[i%#m+1]          -- wrap bottom to top
        l=j%#k+1             -- wrap right to left
        w=m[(i-2)%#m+1]      -- wrap top to bottom
        h=(j-2)%#k+1         -- wrap left to right

        a[i][j]= v[l]        -- living cells are 1 and deads are 0
                +k[l]        -- just add the values of adjacent cells
                +w[l]        -- to know the number of alive adjacent cells
                +v[h]
                +v[j]
                +w[h]
                +w[j]
                +k[h]
      end
    end

    s=''                     -- s will be the representation of the current generation
    for i=1,#m               -- iterate over each line
    do
      k=m[i]                 -- shorthand for the current line
      for j=1,#k             -- iterate over each row
      do
        x=a[i][j]            -- shorthand for the number of adjacent to the current cell
                             -- the next line change the state of the current cell
        k[j]=k[j]>0          -- if it is alive
                and((x<2     --   and it has less than 2 adjacent
                    or x>3)  --   or more than 3 adjacent
                  and 0      --     kill it
                  or 1)      --     else let it alive
                or           -- if it is dead
                  (x==3      --   and it has 3 adjacent
                  and 1      --     give life to it
                  or 0)      --     else let it dead
      end
      s=s..t(k)              -- save the representation of the current line
    end
    for i=1,#c               -- iterate over all the generation done until now
    do
      if(s==t(c[i]))         -- if the representation of the current generation
      then                   -- is equal to one we saved
        return#c>i           -- check if it is the latest generation
              and-1          -- if it isn't, it means we are in a loop -> return -1
              or i-1         -- if it is, we did 2 generations without changing
                             --  -> return the number of generation
      end
    end
  goto z                     -- if we reach that point, loop back to the label z
end
</code>```

Test cases

Here's some test cases

function f(m)c={}t=table.concat::z::c[#c+1]={}p=c[#c]a={}for i=1,#m do k=m[i]p[#p+1]=t(k)a[i]={}for j=1,#k
do v=m[i%#m+1]l=j%#k+1w=m[(i-2)%#m+1]h=(j-2)%#k+1
a[i][j]=v[l]+k[l]+w[l]+v[h]+v[j]+w[h]+w[j]+k[h]end
end s=''for i=1,#m do k=m[i]for j=1,k do
x=a[i][j]k[j]=k[j]>0 and((x<2or x>3)and 0or 1)or (x==3 and 1or 0)end
s=s..t(k)end for i=1,#c do
if(s==t(c[i]))then return#c>i and-1or i-1
end end goto z end

print(f({{0,0,0},{0,1,1},{0,1,0}}))
print(f({{0,1,0,0},{0,1,0,0},{0,1,0,0},{0,0,0,0}}))
-- 53 generation, 15x15, takes 50-100 ms on a bad laptop
print(f({{0,0,0,0,1,1,0,1,0,0,0,0,1,0,0},
       {0,1,1,0,1,1,1,1,1,1,1,0,0,0,0},
       {0,1,1,1,0,1,0,1,0,0,0,0,1,0,0},
       {0,0,1,0,1,1,1,0,0,1,1,1,0,1,1},
       {1,1,0,0,1,1,1,0,1,1,0,0,0,1,0},
       {0,0,0,0,1,1,0,1,0,0,0,0,1,0,0},
       {0,1,1,0,1,1,1,1,1,1,1,0,0,0,0},
       {0,1,1,1,0,1,0,1,0,0,0,0,1,0,0},
       {0,0,1,0,1,1,1,0,0,1,1,1,0,1,1},
       {1,1,0,0,1,1,1,0,1,1,0,0,0,1,0},
       {0,0,1,0,1,1,1,0,0,1,1,1,0,1,1},
       {1,1,0,0,1,1,1,0,1,1,0,0,0,1,0},
       {0,0,0,0,1,1,0,1,0,0,0,0,1,0,0},
       {0,0,0,0,1,1,0,1,0,0,0,0,1,0,0},
       {0,1,1,0,1,1,1,1,1,1,1,0,0,0,0}}))
-- Glider on a 15x14 board
-- 840 distinct generation
-- loop afterward -> return -1
-- takes ~4-5 seconds on the same bad laptop
print(f({{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
       {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
       {0,0,0,0,1,0,0,0,0,0,0,0,0,0,0},
       {0,0,0,0,0,1,0,0,0,0,0,0,0,0,0},
       {0,0,0,1,1,1,0,0,0,0,0,0,0,0,0},
       {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
       {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
       {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
       {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
       {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
       {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
       {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
       {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
       {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}}))
```

Title: Stable Game of Life

Body:
Lua, <s>531</s> <s>509</s> <s>488</s> <s>487</s> <s>464</s> <s>424</s> <s>405</s> 404 Bytes

Who wants a massive submission? \o/

Edit: Improved it, but don't know how to golf it anymore, so... <s>explanations are coming</s> comments added :)

Saved ~60 bytes with the help of @KennyLau

small golfing cutting one more byte by renaming a into Y to prevent the inlined hexadecimal conversion

function f(m)c={}t=table.concat::z::c[#c+1]={}p=c[#c]Y={}for i=1,#m do k=m[i]p[#p+1]=t(k)Y[i]={}for j=1,#k
do v=m[i%#m+1]l=j%#k+1w=m[(i-2)%#m+1]h=(j-2)%#k+1Y[i][j]=v[l]+k[l]+w[l]+v[h]+v[j]+w[h]+w[j]+k[h]end
end s=''for i=1,#m do k=m[i]for j=1,k do
x=Y[i][j]k[j]=k[j]>0 and((x<2or x>3)and 0or 1)or (x==3 and 1or 0)end
s=s..t(k)end for i=1,#c do
if(s==t(c[i]))then return#c>i and-1or i-1
end end goto z end

Ungolfed

function f(m)                -- takes a 2D array of 0 and 1s as input
  c={}                       -- intialise c -> contains a copy of each generation
  t=table.concat             -- shorthand for the concatenating function
  ::z::                      -- label z, used to do an infinite loop
    c[#c+1]={}               -- initialise the first copy
    p=c[#c]                  -- initialise a pointer to this copy
    a={}                     -- initialise the 2D array of adjacency
    for i=1,#m               -- iterate over the lines of m
    do
      k=m[i]                 -- shorthand for the current line
      p[#p+1]=t(k])          -- saves the current line of m as a string
      a[i]={}                -- initialise the array of adjacency for the current line
      for j=1,#k             -- iterate over each row of m
      do
                             -- the following statements are used to wraps at borders
        v=m[i%#m+1]          -- wrap bottom to top
        l=j%#k+1             -- wrap right to left
        w=m[(i-2)%#m+1]      -- wrap top to bottom
        h=(j-2)%#k+1         -- wrap left to right

        a[i][j]= v[l]        -- living cells are 1 and deads are 0
                +k[l]        -- just add the values of adjacent cells
                +w[l]        -- to know the number of alive adjacent cells
                +v[h]
                +v[j]
                +w[h]
                +w[j]
                +k[h]
      end
    end

    s=''                     -- s will be the representation of the current generation
    for i=1,#m               -- iterate over each line
    do
      k=m[i]                 -- shorthand for the current line
      for j=1,#k             -- iterate over each row
      do
        x=a[i][j]            -- shorthand for the number of adjacent to the current cell
                             -- the next line change the state of the current cell
        k[j]=k[j]>0          -- if it is alive
                and((x<2     --   and it has less than 2 adjacent
                    or x>3)  --   or more than 3 adjacent
                  and 0      --     kill it
                  or 1)      --     else let it alive
                or           -- if it is dead
                  (x==3      --   and it has 3 adjacent
                  and 1      --     give life to it
                  or 0)      --     else let it dead
      end
      s=s..t(k)              -- save the representation of the current line
    end
    for i=1,#c               -- iterate over all the generation done until now
    do
      if(s==t(c[i]))         -- if the representation of the current generation
      then                   -- is equal to one we saved
        return#c>i           -- check if it is the latest generation
              and-1          -- if it isn't, it means we are in a loop -> return -1
              or i-1         -- if it is, we did 2 generations without changing
                             --  -> return the number of generation
      end
    end
  goto z                     -- if we reach that point, loop back to the label z
end

Test cases

Here's some test cases

function f(m)c={}t=table.concat::z::c[#c+1]={}p=c[#c]a={}for i=1,#m do k=m[i]p[#p+1]=t(k)a[i]={}for j=1,#k
do v=m[i%#m+1]l=j%#k+1w=m[(i-2)%#m+1]h=(j-2)%#k+1
a[i][j]=v[l]+k[l]+w[l]+v[h]+v[j]+w[h]+w[j]+k[h]end
end s=''for i=1,#m do k=m[i]for j=1,k do
x=a[i][j]k[j]=k[j]>0 and((x<2or x>3)and 0or 1)or (x==3 and 1or 0)end
s=s..t(k)end for i=1,#c do
if(s==t(c[i]))then return#c>i and-1or i-1
end end goto z end

print(f({{0,0,0},{0,1,1},{0,1,0}}))
print(f({{0,1,0,0},{0,1,0,0},{0,1,0,0},{0,0,0,0}}))
-- 53 generation, 15x15, takes 50-100 ms on a bad laptop
print(f({{0,0,0,0,1,1,0,1,0,0,0,0,1,0,0},
       {0,1,1,0,1,1,1,1,1,1,1,0,0,0,0},
       {0,1,1,1,0,1,0,1,0,0,0,0,1,0,0},
       {0,0,1,0,1,1,1,0,0,1,1,1,0,1,1},
       {1,1,0,0,1,1,1,0,1,1,0,0,0,1,0},
       {0,0,0,0,1,1,0,1,0,0,0,0,1,0,0},
       {0,1,1,0,1,1,1,1,1,1,1,0,0,0,0},
       {0,1,1,1,0,1,0,1,0,0,0,0,1,0,0},
       {0,0,1,0,1,1,1,0,0,1,1,1,0,1,1},
       {1,1,0,0,1,1,1,0,1,1,0,0,0,1,0},
       {0,0,1,0,1,1,1,0,0,1,1,1,0,1,1},
       {1,1,0,0,1,1,1,0,1,1,0,0,0,1,0},
       {0,0,0,0,1,1,0,1,0,0,0,0,1,0,0},
       {0,0,0,0,1,1,0,1,0,0,0,0,1,0,0},
       {0,1,1,0,1,1,1,1,1,1,1,0,0,0,0}}))
-- Glider on a 15x14 board
-- 840 distinct generation
-- loop afterward -> return -1
-- takes ~4-5 seconds on the same bad laptop
print(f({{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
       {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
       {0,0,0,0,1,0,0,0,0,0,0,0,0,0,0},
       {0,0,0,0,0,1,0,0,0,0,0,0,0,0,0},
       {0,0,0,1,1,1,0,0,0,0,0,0,0,0,0},
       {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
       {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
       {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
       {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
       {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
       {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
       {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
       {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
       {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}}))


答:
Retina, 63 bytes

```<code>.+$
$&¶;$&
+`^(.)(.*¶)(.)([^;]+);(.*?)\1
$2$4$5$3;
A1`
;

G2=`.
</code>```

Input is taken in order B, C, A, separated by linefeeds.

Try it online.

Title: Subsequence Substitution

Body:
Retina, 63 bytes

.+$
$&¶;$&
+`^(.)(.*¶)(.)([^;]+);(.*?)\1
$2$4$5$3;
A1`
;

G2=`.

Input is taken in order B, C, A, separated by linefeeds.

Try it online.


问:
Print cos(2π/17) exactly
One way to construct a regular heptadecagon starts with drawing a horizontal line of length 1 from the center to a vertex. Then the distance along that line from the center to the second vertex is cos(2π/17). All other vertices are easy to get.

The goal of this challenge is to print (or produce in any other conventional way) an ASCII math expression involving the operations +, -, *, /, sqrt() and the natural numbers, which gives cos(2π/17) when evaluated. The power operator is not allowed: e.g. sqrt(17) cannot be written as 17^(1/2).

For example (formula taken from Wikipedia):

```<code>1/16*(
    -1+
    sqrt(17)+
    sqrt(34-2*sqrt(17))+
    2*sqrt(
        17+
        3*sqrt(17)-
        sqrt(34-2*sqrt(17))-
        2*sqrt(34+2*sqrt(17))
    )
)
</code>```

Whitespace doesn't matter. The length and complexity of the expression doesn't matter, as long as it's syntactically correct (as defined above) and numerically equivalent to cos(2π/17).

Built-in functions are allowed.

Title: Print cos(2π/17) exactly

Body:
R 68 bytes

s=sqrt;x=s(17);y=s(34-2*x);cat((x+y+2*s(17+3*x-y-2*s(34+2*x))-1)/16)


答:
Lua, 45 bytes, Katenkyo, A001477

```<code>a=function(n)return n-1<1 and 0or 1+a(n-1)end
</code>```

Title: Find the program that prints this integer sequence (Robbers' thread)

Body:
This is the robbers' thread. The cops' thread goes here.

In the cops thread, the task was to write a program/function that takes a positive (or non-negative) integer and outputs/returns another number (not necessarily integer). The robbers task is to unscramble the code the cops used to produce this output.

The cracked code doesn't have to be identical, as long as it has the same length and any revealed characters are in the correct positions. The language must also be the same (version numbers can be different). The output must of course be identical.

No-ops can be used in robber's solution.

The winner of the robbers thread will be the user who has cracked the
most submissions by May 7th 2016. If there's a tie, the user who has cracked submissions with the longest combined code will win.

The submission should be formatted like this:

Language, nn characters (including link to answer), Cop's username

Code:

```<code>function a(n)
    if n<2 then
        return n
    else
        return a(n-1) + a(n-2)
    end
end
</code>```

Output

```<code>a(0) returns 0
a(3) returns 2
</code>```

Optional explanation and comments.

Body:
Lua, 45 bytes, Katenkyo, A001477

a=function(n)return n-1<1 and 0or 1+a(n-1)end


答:
Swift, 55 bytes, Nefrin, A103847

The sequence is McCarthy's 91 Function.

It takes the value 91 for any n up to 101 and then continues with 92,93,94 ...

I wonder what it's actually useful for.

```<code>func M(n:Int)->Int{
return(n<=100) ?M(M(n+11)):n-10;
}
</code>```

Body:
Swift, 55 bytes, Nefrin, A103847

The sequence is McCarthy's 91 Function.

It takes the value 91 for any n up to 101 and then continues with 92,93,94 ...

I wonder what it's actually useful for.

func M(n:Int)->Int{
return(n<=100) ?M(M(n+11)):n-10;
}


答:
><>, 28 bytes

```<code>:1=?v::2%?v2,
+c0.\l1-n;\3*1
</code>```

This takes input from the stack, computes the different steps on the stack, then returns its size when 1 is reached.

Improved version by JoKing, 24 bytes :

```<code>:1=?\::2%b$.2,
3*1+\~ln;
</code>```

Title: Collatz Conjecture (OEIS A006577)

Body:
This is the Collatz Conjecture (OEIS A006577):

Start with an integer n > 1.

Repeat the following steps:

If n is even, divide it by 2.

If n is odd, multiply it by 3 and add 1.

It is proven that for all positive integers up to 5 * 260, or about 5764000000000000000, n will eventually become 1.

Your task is to find out how many iterations it takes (of halving or tripling-plus-one) to reach 1.

Relevant xkcd :)

Rules:

Shortest code wins.

If a number < 2 is input, or a non-integer, or a non-number, output does not matter.

Test cases

```<code>2  -> 1
16 -> 4
5  -> 5
7  -> 16
</code>```

Body:
><>, 28 bytes

:1=?v::2%?v2,
+c0.\l1-n;\3*1

This takes input from the stack, computes the different steps on the stack, then returns its size when 1 is reached.

Improved version by JoKing, 24 bytes :

:1=?\::2%b$.2,
3*1+\~ln;


问:
Find the program that prints this integer sequence (Cops' thread)
This is the cops' thread. The robbers' thread goes here.

The last cops-and-robbers thread was already 4 months ago.

The cop's task

The cop's task is to write a program/function that takes a positive (or non-negative) integer and outputs/returns another integer.

The cop must state it if the program is intolerant towards zero.

The cop will provide at least 2 sample inputs/outputs.

For example, if I have decided to write the Fibonacci sequence, I would write this in my answer:

```
a(0) returns 0
a(3) returns 2
```

The number of examples is up to the cop's discretion.

However, the sequence must actually exist in the On-Line Encyclopedia of Integer Sequences®, so no pseudo-random number generator for you. :(

The cop can hide as many characters as is so wished.

For example, if my program is:

```<code>function a(n)
    if n>2 then
        return n
    else
        return a(n-1) + a(n-2)
    end
end
</code>```

Then I would hide these characters as I want:

```<code>function a(n)
    if ### then
        ########
    else
        ######################
    end
end
</code>```

The robber's task

is obviously to find the original source code.

However, any proposed source code that produces the same set of output also counts as valid, as long as it is also found in OEIS.

Tips for the cops

<s>The search function in the OEIS only works for consecutive terms, so if you want to hide your sequence, then just leave a hole anywhere.</s>

Apparently there is no way to hide the sequence. Put this in mind when you choose the sequence.

Your score is the number of bytes in your code.

The winner will be the submission with the lowest score that hasn't been cracked in 7 days.

Only submissions that are posted in 2016 April are eligible for the win. Submissions that are posted later than this are welcome, but cannot win.

In order to claim the win you need to reveal the full code and the OEIS sequence (after 7 days).

Your post should be formatted like this (NN is the number of characters):

Lua, 98 bytes

Output:

```<code>a(0) returns 0
a(3) returns 2
</code>```

Code (# marks unrevealed characters):

```<code>function a(n)
    if ### then
        ########
    else
        ######################
    end
end
</code>```

If the code is cracked, insert [Cracked](link to cracker) in the header.
If the submission is safe, insert "Safe" in the header and reveal the full code in your answer. Only answers that have revealed the full code will be eligible for the win.

Body:
R 64 bytes

Code

##########################
a=function(x)sum(x*3,1,a(x-2):a(x-1))

Output

a(1) =1
a(2) =1
a(3) =2
a(4) =3
a(5) =5
a(6) =8
a(7) =13
a(8) =21
a(9) =34
a(10)=55
a(11)=89
a(12)=144
a(13)=233
a(14)=377
a(15)=610
a(16)=987
a(17)=1597
a(18)=2584
a(19)=4181
a(20)=6765

Simply, Fibonnaci sequence.

Hope it's fun enough.


问:
Bracket balancing
You will be given a (possibly empty) string containing brackets ([{()}]) and any other characters (A-Z, a-z, 0-9, punctuation). You need to check if it adheres to the following rules:

Non-bracket characters are ignored.

Every open bracket [{( has a closing bracket )}]. So []( is not allowed.

Brackets are nested properly. [(]) is not allowed.

Curly brackets cannot contain square brackets within them. Simple brackets cannot contain either curly or square brackets within them. So [({})], [{[]}] and ({}) are not allowed. Brackets can be nested with similar brackets, so [[{((()))}{{(())}}]()]{()} is allowed.

Output is a single truthy/falsey value as per your choice.

Shortest code wins.

Test cases

b[[a{(/)}(())+={{}-}],] -> Valid

([h][e][l][l][o]) -> Invalid

[///[{(\/(arg()))}1{{((-)-2)}}]()]{()} -> Valid

hi -> Valid

Title: Bracket balancing

Body:
C99, <s>226</s> <s>208</s> 207 Bytes

This is my first time ever trying to golf something

#define S s[i]
t(s,i)char*s;{int a[]={['[']=0,['{']=0,['(']=0};for(i=0;S*!(S=='{'&a['(']|S=='['&(a['(']|a['{'])|S==']'&(a['(']|a['{'])|S=='}'&a['(']);i++)a[S]++,a[S-S/90-1]--;return !(a['[']+a['{']+a['(']);}

Readable:

int t(char* s){
    int a[265]={['[']=0,['{']=0,['(']=0};
    for(int i=0;s[i]&&!((s[i]=='{'&a['(']>0)|(s[i]=='['&(a['(']>0|a['{']>0))|(s[i]==']'&(a['(']>0|a['{']>0))|(s[i]=='}'&a['(']>0));i++){
        a[s[i]]++;
        a[s[i]-(s[i]/90+1)]--;
    }
    return !(a['[']+a['{']+a['(']);
}

There is a buffer overflow but it doesnt seem to affect anything - I believe this is due to alignment.


问:
Is this number a prime?
Believe it or not, we do not yet have a code golf challenge for a simple primality test. While it may not be the most interesting challenge, particularly for "usual" languages, it can be nontrivial in many languages.

Rosetta code features lists by language of idiomatic approaches to primality testing, one using the Miller-Rabin test specifically and another using trial division. However, "most idiomatic" often does not coincide with "shortest." In an effort to make Programming Puzzles and Code Golf the go-to site for code golf, this challenge seeks to compile a catalog of the shortest approach in every language, similar to "Hello, World!" and Golf you a quine for great good!.

Furthermore, the capability of implementing a primality test is part of our definition of programming language, so this challenge will also serve as a directory of proven programming languages.

Task

Write a full program that, given a strictly positive integer n as input, determines whether n is prime and prints a truthy or falsy value accordingly.

For the purpose of this challenge, an integer is prime if it has exactly two strictly positive divisors. Note that this excludes 1, who is its only strictly positive divisor.

Your algorithm must be deterministic (i.e., produce the correct output with probability 1) and should, in theory, work for arbitrarily large integers. In practice, you may assume that the input can be stored in your data type, as long as the program works for integers from 1 to 255.

Input

If your language is able to read from STDIN, accept command-line arguments or any other alternative form of user input, you can read the integer as its decimal representation, unary representation (using a character of your choice), byte array (big or little endian) or single byte (if this is your languages largest data type).

If (and only if) your language is unable to accept any kind of user input, you may hardcode the input in your program.

In this case, the hardcoded integer must be easily exchangeable. In particular, it may appear only in a single place in the entire program.

For scoring purposes, submit the program that corresponds to the input 1.

Output

Output has to be written to STDOUT or closest alternative.

If possible, output should consist solely of a truthy or falsy value (or a string representation thereof), optionally followed by a single newline.

The only exception to this rule is constant output of your language's interpreter that cannot be suppressed, such as a greeting, ANSI color codes or indentation.

Additional rules

This is not about finding the language with the shortest approach for prime testing, this is about finding the shortest approach in every language. Therefore, no answer will be marked as accepted.

Submissions in most languages will be scored in bytes in an appropriate preexisting encoding, usually (but not necessarily) UTF-8.

The language Piet, for example, will be scored in codels, which is the natural choice for this language.

Some languages, like Folders, are a bit tricky to score. If in doubt, please ask on Meta.

Unlike our usual rules, feel free to use a language (or language version) even if it's newer than this challenge. If anyone wants to abuse this by creating a language where the empty program performs a primality test, then congrats for paving the way for a very boring answer.

Note that there must be an interpreter so the submission can be tested. It is allowed (and even encouraged) to write this interpreter yourself for a previously unimplemented language.

If your language of choice is a trivial variant of another (potentially more popular) language which already has an answer (think BASIC or SQL dialects, Unix shells or trivial Brainfuck derivatives like Headsecks or Unary), consider adding a note to the existing answer that the same or a very similar solution is also the shortest in the other language.

Built-in functions for testing primality are allowed. This challenge is meant to catalog the shortest possible solution in each language, so if it's shorter to use a built-in in your language, go for it.

Unless they have been overruled earlier, all standard code-golf rules apply, including the http://meta.codegolf.stackexchange.com/q/1061.

As a side note, please don't downvote boring (but valid) answers in languages where there is not much to golf; these are still useful to this question as it tries to compile a catalog as complete as possible. However, do primarily upvote answers in languages where the author actually had to put effort into golfing the code.

Catalog

The Stack Snippet at the bottom of this post generates the catalog from the answers a) as a list of shortest solution per language and b) as an overall leaderboard.

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>```

If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the last number in the header:

```<code>## Perl, 43 + 2 (-p flag) = 45 bytes
</code>```

You can also make the language name a link which will then show up in the snippet:

```<code>## [><>](http://esolangs.org/wiki/Fish), 121 bytes
</code>```

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

Shortest Solution by Language

Language	User	Score

Leaderboard

	Author	Language	Size

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

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

```

答:
Befunge 93, 33 bytes

```<code>&10p1 >1+:10g\`v
1.@.0_^#!%\g01:_
</code>```

Also works by trial division, as the other befunge post, but is substantially shorter.

Interpreter here.

Title: Is this number a prime?

Body:
Befunge 93, 33 bytes

&10p1 >1+:10g\`v
1.@.0_^#!%\g01:_

Also works by trial division, as the other befunge post, but is substantially shorter.

Interpreter here.


答:
JavaScript (ES6), <s>100</s> 95 bytes

```<code>(a,b,c)=>1?(t=[...a].map(e=>b[0]==e?(u=c[0],b=b.slice(1),c=c.slice(1),u):e).join``,b==""?t:a):a
</code>```

This is a valid JavaScript Lambda function. Outputs as function return. Takes in three arguments (a,b,c). Add f= at the beginning and invoke like f(arg1,arg2,arg3).

f=(a,b,c)=>1?(t=[...a].map(e=>b[0]==e?(u=c[0],b=b.slice(1),c=c.slice(1),u):e).join``,b==""?t:a):a

console.log(f(prompt("Value for A"),prompt("Value for B"),prompt("Value for C")))```

Title: Subsequence Substitution

Body:
Most languages come with a built-in to search a string for all occurrences of a given substring and replace those with another. I don't know of any language that generalises this concept to (not necessarily contiguous) subsequences. So that's your task in this challenge.

The input will consist of three strings A, B and C, where B and C are guaranteed to be of the same length. If B appears as a subsequence in A it should be replaced with C. Here is a simple example:

```<code>A: abcdefghijklmnopqrstuvwxyz
B: ghost
C: 12345
</code>```

It would be processed like this:

```<code>abcdefghijklmnopqrstuvwxyz
      ||      |   ||
abcdef12ijklmn3pqr45uvwxyz
</code>```

If there are several ways to find B as a subsequence, you should greedily replace the left-most one:

```<code>A: abcdeedcba
B: ada
C: BOB

Result:   BbcOeedcbB
and NOT:  BbcdeeOcbB
</code>```

The same applies if B could be found in multiple disjoint places:

```<code>A: abcdeedcbaabcde
B: ed
C: 12

Result:   abcd1e2cbaabcde
and NOT:  abcd112cbaabc2e (or similar)
</code>```

When B does not appear in A, you should output A unchanged.

Rules

As stated above, take three strings A, B and C as input and replace the left-most occurrence of B as a subsequence in A with C, if there is any.

You may write a program or function, taking input via STDIN (or closest alternative), command-line argument or function argument and outputting the result via STDOUT (or closest alternative), function return value or function (out) parameter.

You may take the three strings in any consistent order which you should specify in your answer. You may assume that B and C have the same length. All strings will only contain alphanumeric characters.

Standard code-golf rules apply.

Test Cases

Each test case is four lines: A, B, C followed by the result.

```<code>abcdefghijklmnopqrstuvwxyz
ghost
12345
abcdef12ijklmn3pqr45uvwxyz

abcdeedcba
ada
BOB
BbcOeedcbB

abcdeedcbaabcde
ed
12
abcd1e2cbaabcde

121
121
aBc
aBc

abcde
acb
123
abcde

ABC
ABCD
1234
ABC

012345678901234567890123456789
42
TT
0123T5678901T34567890123456789

edcbaedcbaedcbaedcba
abcde
12345
edcbaedcbaedcbaedcba

edcbaedcbaedcbaedcbaedcba
abcde
12345
edcb1edc2aed3bae4cba5dcba

daccdedca
ace
cra
dcrcdadca

aacbcbabcccaabcbabcaabbbbca
abaaaccbac
1223334444
aacbcbabcccaabcbabcaabbbbca

aacbcbabcccaabcbabcaabbbbcac
abaaaccbac
1223334444
1ac2cb2bccc33b3bab4aa4bbbc44
</code>```

Leaderboard

The Stack Snippet at the bottom of this post generates leaderboards from the answers a) as a list of shortest solution per language and b) as an overall leaderboard.

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>```

If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the last number in the header:

```<code>## Perl, 43 + 2 (-p flag) = 45 bytes
</code>```

You can also make the language name a link which will then show up in the snippet:

```<code>## [><>](http://esolangs.org/wiki/Fish), 121 bytes
</code>```

/* Configuration */

var QUESTION_ID = 77719; // Obtain this from the url
// It will be like http://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page
var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";
var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk";
var OVERRIDE_USER = 8478; // This should be the user ID of the challenge author.

/* App */

var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page;

function answersUrl(index) {
  return "http://api.stackexchange.com/2.2/questions/" +  QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER;
}

function commentUrl(index, answers) {
  return "http://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER;
}

function getAnswers() {
  jQuery.ajax({
    url: answersUrl(answer_page++),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      answers.push.apply(answers, data.items);
      answers_hash = [];
      answer_ids = [];
      data.items.forEach(function(a) {
        a.comments = [];
        var id = +a.share_link.match(/\d+/);
        answer_ids.push(id);
        answers_hash[id] = a;
      });
      if (!data.has_more) more_answers = false;
      comment_page = 1;
      getComments();
    }
  });
}

function getComments() {
  jQuery.ajax({
    url: commentUrl(comment_page++, answer_ids),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      data.items.forEach(function(c) {
        if (c.owner.user_id === OVERRIDE_USER)
          answers_hash[c.post_id].comments.push(c);
      });
      if (data.has_more) getComments();
      else if (more_answers) getAnswers();
      else process();
    }
  });
}

getAnswers();

var SCORE_REG = /<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/;

var OVERRIDE_REG = /^Override\s*header:\s*/i;

function getAuthorName(a) {
  return a.owner.display_name;
}

function process() {
  var valid = [];

  answers.forEach(function(a) {
    var body = a.body;
    a.comments.forEach(function(c) {
      if(OVERRIDE_REG.test(c.body))
        body = '
' + c.body.replace(OVERRIDE_REG, '') + '
';
    });

    var match = body.match(SCORE_REG);
    if (match)
      valid.push({
        user: getAuthorName(a),
        size: +match[2],
        language: match[1],
        link: a.share_link,
      });
    else console.log(body);
  });

  valid.sort(function (a, b) {
    var aB = a.size,
        bB = b.size;
    return aB - bB
  });

  var languages = {};
  var place = 1;
  var lastSize = null;
  var lastPlace = 1;
  valid.forEach(function (a) {
    if (a.size != lastSize)
      lastPlace = place;
    lastSize = a.size;
    ++place;

    var answer = jQuery("#answer-template").html();
    answer = answer.replace("{{PLACE}}", lastPlace + ".")
                   .replace("{{NAME}}", a.user)
                   .replace("{{LANGUAGE}}", a.language)
                   .replace("{{SIZE}}", a.size)
                   .replace("{{LINK}}", a.link);
    answer = jQuery(answer);
    jQuery("#answers").append(answer);

    var lang = a.language;
    lang = jQuery(''+lang+'').text();

    languages[lang] = languages[lang] || {lang: a.language, lang_raw: lang, user: a.user, size: a.size, link: a.link};
  });

  var langs = [];
  for (var lang in languages)
    if (languages.hasOwnProperty(lang))
      langs.push(languages[lang]);

  langs.sort(function (a, b) {
    if (a.lang_raw.toLowerCase() > b.lang_raw.toLowerCase()) return 1;
    if (a.lang_raw.toLowerCase() < b.lang_raw.toLowerCase()) return -1;
    return 0;
  });

  for (var i = 0; i < langs.length; ++i)
  {
    var language = jQuery("#language-template").html();
    var lang = langs[i];
    language = language.replace("{{LANGUAGE}}", lang.lang)
                       .replace("{{NAME}}", lang.user)
                       .replace("{{SIZE}}", lang.size)
                       .replace("{{LINK}}", lang.link);
    language = jQuery(language);
    jQuery("#languages").append(language);
  }

}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body { text-align: left !important}

#answer-list {
  padding: 10px;
  width: 290px;
  float: left;
}

#language-list {
  padding: 10px;
  width: 290px;
  float: left;
}

table thead {
  font-weight: bold;
}

table td {
  padding: 5px;
}</code>```

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

Shortest Solution by Language

Language	User	Score

Leaderboard

	Author	Language	Size

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

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

```

Body:
JavaScript (ES6), <s>100</s> 95 bytes

(a,b,c)=>1?(t=[...a].map(e=>b[0]==e?(u=c[0],b=b.slice(1),c=c.slice(1),u):e).join``,b==""?t:a):a

This is a valid JavaScript Lambda function. Outputs as function return. Takes in three arguments (a,b,c). Add f= at the beginning and invoke like f(arg1,arg2,arg3).

f=(a,b,c)=>1?(t=[...a].map(e=>b[0]==e?(u=c[0],b=b.slice(1),c=c.slice(1),u):e).join``,b==""?t:a):a

console.log(f(prompt("Value for A"),prompt("Value for B"),prompt("Value for C")))


问:
Create a pie chart
The challenge is simple:

Create a pie-chart based on a number of input values.

The input will be a list of positive numbers, decimal or integers, and the output will be a pie-chart where each of the input values are represented by separate colors, and a percentage value outside each of the areas.

Rules:

The colors must be visually distinguishable (the exact colors are optional)

There will be at least two, and maximum 10 input values

The radius of the circle must be in the range [100 300] pixels

Vector graphics are OK as long as the default output gives a radius of [100, 300] pixels

The percentage values shall be integers

There is no strict rule saying where the percentage value shall be placed, but it must be easily seen which area it belongs to

The distance between the closest character and the outer edge of the circle must be in the range [5, 40] pixels

The font is optional

The plot may or may not have black lines separating each region

Functions made for creating pie charts, for instance, MATLAB: pie, Python: matplotlib.pyplot.pie and Mathematica: PieChart are not allowed

Normal rounding rules (up if it's (1.00, 0.5], down if it's (0.5, 0.00))

If the percentage value of a slice is smaller than 0.5%, output 0%. The slice must still be included in the plot.

Please provide plots for examination (or a link to an interpreter). It's enough to show only the plot with 10 input values (to avoid very long answers)

Examples

Please use the example values below. You can convert the lists to an appropriate format using a numeric list converter, for instance this 27 byte one by jimmy23013.

```<code>x = [0.3, 1.2]
</code>```

```<code>x = [3, 6, 2, 10]
</code>```

```<code>x = [0.4387, 0.3816, 0.7655, 0.7952, 0.1869, 0.4898, 0.4456, 0.6463, 0.7094, 0.7547]
</code>```

答:
Mathematica, <s>186</s> <s>183</s> 164 bytes

```<code>Graphics[{Hue@#,Disk[{0,0},{1,1},a=2Pi{##}],Black,Text[ToString@Round[100(#2-#)]<>"%",5Through@{Cos,Sin}@Mean@a/4]}&@@@Partition[Accumulate[#/Tr@#]~Prepend~0,2,1]]&
</code>```

Could be golfed further. Currently generates a Graphics object. Test cases:

Title: Create a pie chart

Body:
Mathematica, <s>186</s> <s>183</s> 164 bytes

Graphics[{Hue@#,Disk[{0,0},{1,1},a=2Pi{##}],Black,Text[ToString@Round[100(#2-#)]<>"%",5Through@{Cos,Sin}@Mean@a/4]}&@@@Partition[Accumulate[#/Tr@#]~Prepend~0,2,1]]&

Could be golfed further. Currently generates a Graphics object. Test cases:


答:
JavaScript (ES6), <s>311</s> <s>310</s> <s>302</s> 298 bytes

a=>{with(Math)document.write(`<svg height=300>`+a.map(n=>`<path fill=#${(p*4e3|0).toString(16)} d=M135,150L${c(o=100,v=0)}A${[o,o,0,(v=n/=s)+.5|0,0,c(o)]}Z /><text x=${(z=c(135,v/=2))[0]} y=${z[p+=n,1]}>${n*o+.5|0}%</text>`,c=r=>[sin(d=PI*2*(v+p))*r+135,cos(d)*r+150],p=s=0,a.map(n=>s+=n)).join``)}
```

<p><em>Saved a byte with help from @Neil!</em></p>

<h2>Explanation</h2>

<p>Writes some SVG to the HTML of the current page. Builds the chart with centre point <code>135 x 150</code> of radius <code>100px</code> and text at a radius of <code>135px</code> from the centre.</p>

<p><div class="snippet" data-lang="js" data-hide="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var solution =

a=>{
  with(Math)
  document.write(       // write to HTML body
    `<svg height=300>`+ // create 300px x 300px SVG canvas (width defaults to 300px)
    a.map(n=>           // for each number

      // Get the hex colour by multiplying the current position by (roughly) 0xfff
      `<path fill=#${(p*4e3|0).toString(16)

      // Calculate the path of the pie slice
      } d=M135,150L${c(o=100,v=0)}A${[o,o,0,(v=n/=s)+.5|0,0,c(o)]

      // Text
      }Z /><text x=${(z=c(135,v/=2))[0]} y=${z[p+=n,1]}>${n*o+.5|0}%</text>`,

      // Returns [ x, y ] for a certain radius at position v around the pie
      c=r=>[sin(d=PI*2*(v+p))*r+135,cos(d)*r+150],
      p=s=0,             // p = current position around pie (0 - 1)
      a.map(n=>s+=n)     // s = sum of all numbers
    ).join``

    +`</svg>` // <- this is just here for the test, so multiple charts can be displayed
  )
}

// Test
;[
  [0.3, 1.2],
  [3, 6, 2, 10],
  [0.4387, 0.3816, 0.7655, 0.7952, 0.1869, 0.4898, 0.4456, 0.6463, 0.7094, 0.7547]
].map(c=>solution(c));</code>```

Title: Create a pie chart

Body:
The challenge is simple:

Create a pie-chart based on a number of input values.

The input will be a list of positive numbers, decimal or integers, and the output will be a pie-chart where each of the input values are represented by separate colors, and a percentage value outside each of the areas.

Rules:

The colors must be visually distinguishable (the exact colors are optional)

There will be at least two, and maximum 10 input values

The radius of the circle must be in the range [100 300] pixels

Vector graphics are OK as long as the default output gives a radius of [100, 300] pixels

The percentage values shall be integers

There is no strict rule saying where the percentage value shall be placed, but it must be easily seen which area it belongs to

The distance between the closest character and the outer edge of the circle must be in the range [5, 40] pixels

The font is optional

The plot may or may not have black lines separating each region

Functions made for creating pie charts, for instance, MATLAB: pie, Python: matplotlib.pyplot.pie and Mathematica: PieChart are not allowed

Normal rounding rules (up if it's (1.00, 0.5], down if it's (0.5, 0.00))

If the percentage value of a slice is smaller than 0.5%, output 0%. The slice must still be included in the plot.

Please provide plots for examination (or a link to an interpreter). It's enough to show only the plot with 10 input values (to avoid very long answers)

Examples

Please use the example values below. You can convert the lists to an appropriate format using a numeric list converter, for instance this 27 byte one by jimmy23013.

```<code>x = [0.3, 1.2]
</code>```

```<code>x = [3, 6, 2, 10]
</code>```

```<code>x = [0.4387, 0.3816, 0.7655, 0.7952, 0.1869, 0.4898, 0.4456, 0.6463, 0.7094, 0.7547]
</code>```

Body:
JavaScript (ES6), <s>311</s> <s>310</s> <s>302</s> 298 bytes

a=>{with(Math)document.write(`<svg height=300>`+a.map(n=>`<path fill=#${(p*4e3|0).toString(16)} d=M135,150L${c(o=100,v=0)}A${[o,o,0,(v=n/=s)+.5|0,0,c(o)]}Z /><text x=${(z=c(135,v/=2))[0]} y=${z[p+=n,1]}>${n*o+.5|0}%</text>`,c=r=>[sin(d=PI*2*(v+p))*r+135,cos(d)*r+150],p=s=0,a.map(n=>s+=n)).join``)}

Saved a byte with help from @Neil!

Explanation

Writes some SVG to the HTML of the current page. Builds the chart with centre point 135 x 150 of radius 100px and text at a radius of 135px from the centre.

var solution =

a=>{
  with(Math)
  document.write(       // write to HTML body
    `<svg height=300>`+ // create 300px x 300px SVG canvas (width defaults to 300px)
    a.map(n=>           // for each number

      // Get the hex colour by multiplying the current position by (roughly) 0xfff
      `<path fill=#${(p*4e3|0).toString(16)

      // Calculate the path of the pie slice
      } d=M135,150L${c(o=100,v=0)}A${[o,o,0,(v=n/=s)+.5|0,0,c(o)]

      // Text
      }Z /><text x=${(z=c(135,v/=2))[0]} y=${z[p+=n,1]}>${n*o+.5|0}%</text>`,

      // Returns [ x, y ] for a certain radius at position v around the pie
      c=r=>[sin(d=PI*2*(v+p))*r+135,cos(d)*r+150],
      p=s=0,             // p = current position around pie (0 - 1)
      a.map(n=>s+=n)     // s = sum of all numbers
    ).join``

    +`</svg>` // <- this is just here for the test, so multiple charts can be displayed
  )
}

// Test
;[
  [0.3, 1.2],
  [3, 6, 2, 10],
  [0.4387, 0.3816, 0.7655, 0.7952, 0.1869, 0.4898, 0.4456, 0.6463, 0.7094, 0.7547]
].map(c=>solution(c));