问:
Print the Nth non-palindromic number
A palindromic number (in case you don't know) is a number which reads the same backwards and forwards (example, 11). The first 15 non-palindromic numbers are: 10, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 23, 24, 25, 26. This is A029742. I constantly need these numbers, but my sticky note pad is very small, so your code must be as short as possible.

Rules

Each submission must be a full program or function (e.g. in C, you can't just define a function without headers, but you can define a function WITH necessary headers
).

If it is possible, provide a link to a site where your program can be tested.

Your program must not write anything to STDERR.

You can take input as an argument or from STDIN (or the closest alternative in your language).

Programs are scored according to bytes. The usual character set is UTF-8, if you are using another please specify.

Standard loopholes are forbidden.

Test Cases

```<code>1
==> 10

-----

5
==> 15

-----

12
==> 23
</code>```

Scoring

This is code-golf, so least bytes wins.

Submissions

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 leaderboard snippet:

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

Leaderboard

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

/* Configuration */

var QUESTION_ID = 79251; // Obtain this from the url
// It will be like https://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page
var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";
var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk";
var OVERRIDE_USER = 53406; // 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 "https://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 "https://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,]*[^\s,]),.*?(\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,
      });

  });

  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;
    if (/ b.lang) return 1;
    if (a.lang < b.lang) 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">

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

```

答:
Perl 6, 29 bytes

{grep({$_!= .flip},^Inf)[$_]}
```

<p>( uses 0 based index )</p>

<pre class="lang-perl6 prettyprint-override"><code>{         # The $_ is implied above
  grep(   # V
    { $_ != $_.flip }, # only the non-palindromic elements of
    ^Inf               # an Infinite list ( 0,1,2,3 ...^ Inf )
  )[ $_ ]              # grab the value at the given index
}
</code>```

Usage:

my &non-palindrome = {grep({$_!= .flip},^Inf)[$_]}

say non-palindrome 1  - 1; # 10
say non-palindrome 5  - 1; # 15
say non-palindrome 12 - 1; # 23

# this also works:
say non-palindrome 0..20;
# (10 12 13 14 15 16 17 18 19 20 21 23 24 25 26 27 28 29 30 31 32)
```

Title: Print the Nth non-palindromic number

Body:
Perl 6, 29 bytes

{grep({$_!= .flip},^Inf)[$_]}

( uses 0 based index )

{         # The $_ is implied above
  grep(   # V
    { $_ != $_.flip }, # only the non-palindromic elements of
    ^Inf               # an Infinite list ( 0,1,2,3 ...^ Inf )
  )[ $_ ]              # grab the value at the given index
}

Usage:

my &non-palindrome = {grep({$_!= .flip},^Inf)[$_]}

say non-palindrome 1  - 1; # 10
say non-palindrome 5  - 1; # 15
say non-palindrome 12 - 1; # 23

# this also works:
say non-palindrome 0..20;
# (10 12 13 14 15 16 17 18 19 20 21 23 24 25 26 27 28 29 30 31 32)


答:
Actually, 17 bytes

```<code>;τR9+;`$;R=Y`M@░E
</code>```

Try it online!

Values are 1-indexed. This could be easily changed to 0-indexed by replacing the first R with r. But, R is what I initially typed, so that's what I'm going with.

The nonpalindromic numbers satisfy a(n) ≈ n + 10, so 2n+9 is a sufficient upper bound.

Explanation:

```<code>;τR9+;`$;R=Y`M@░E
;τ9+R;             push n, range(1,(2*n)+10)
      `$;R=Y`M@░   take values that are not palindromic
                E  take nth element
</code>```

ContentLicense: CC BY-SA 3.0

Title: Print the Nth non-palindromic number

Body:
A palindromic number (in case you don't know) is a number which reads the same backwards and forwards (example, 11). The first 15 non-palindromic numbers are: 10, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 23, 24, 25, 26. This is A029742. I constantly need these numbers, but my sticky note pad is very small, so your code must be as short as possible.

Rules

Each submission must be a full program or function (e.g. in C, you can't just define a function without headers, but you can define a function WITH necessary headers
).

If it is possible, provide a link to a site where your program can be tested.

Your program must not write anything to STDERR.

You can take input as an argument or from STDIN (or the closest alternative in your language).

Programs are scored according to bytes. The usual character set is UTF-8, if you are using another please specify.

Standard loopholes are forbidden.

Test Cases

```<code>1
==> 10

-----

5
==> 15

-----

12
==> 23
</code>```

Scoring

This is code-golf, so least bytes wins.

Submissions

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 leaderboard snippet:

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

Leaderboard

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

/* Configuration */

var QUESTION_ID = 79251; // Obtain this from the url
// It will be like https://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page
var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";
var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk";
var OVERRIDE_USER = 53406; // 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 "https://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 "https://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,]*[^\s,]),.*?(\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,
      });

  });

  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;
    if (/ b.lang) return 1;
    if (a.lang < b.lang) 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">

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

```

Body:
Actually, 17 bytes

;τR9+;`$;R=Y`M@░E

Try it online!

Values are 1-indexed. This could be easily changed to 0-indexed by replacing the first R with r. But, R is what I initially typed, so that's what I'm going with.

The nonpalindromic numbers satisfy a(n) ≈ n + 10, so 2n+9 is a sufficient upper bound.

Explanation:

;τR9+;`$;R=Y`M@░E
;τ9+R;             push n, range(1,(2*n)+10)
      `$;R=Y`M@░   take values that are not palindromic
                E  take nth element


答:
Ruby, 287 bytes

Runs on an infinite tape in both directions. DOGO input is a file on the command line. If there is no command line argument, a DOGO program will still work if passed in as STDIN, unless it uses operation 3 (get a byte from STDIN) in which case I have no idea. At any rate, file input is best.

Assumes no other text other than the four commands and whitespace exist in the program file.

Hello World Demonstration

```<code>i=k=o=0;m={}
c=$<.read.upcase.split.map{|e|%w{SIT STAY ROLL-OVER HEEL}.index e}.join
(m[k]||=0
e=c[i].to_i
e>2?o>4?$><<m[k].chr:
o>3?m[k]=STDIN.getc.ord:
o>1?k+=o>2?-1:1:
m[k]=o<1?-~m[k]%256:~-m[k]%256:
e>1?o=-~o%6:
e>0?m[k]>0?i=c.rindex(?0,i):0:
m[k]<1?i=c.index(?1,i):0
i+=1)while c[i]
</code>```

Title: Interpret DOGO!

Body:
Interpret DOGO

DOGO is a lesser known programming language. While the original DOGO (a joke language from a Usenet post) has never been implemented, a language resembling it has been created. The commands for the language are:

```<code>+===========+================================================================+
|  Command  |                          Description                           |
+===========+================================================================+
| SIT       | If the value of the current memory cell is 0, jump to STAY.    |
+-----------+----------------------------------------------------------------+
| STAY      | If the value of the current memory cell is not 0, jump to SIT. |
+-----------+----------------------------------------------------------------+
| ROLL-OVER | Select the next operation from the operation list.             |
+-----------+----------------------------------------------------------------+
| HEEL      | Execute the currently selected operation.                      |
+-----------+----------------------------------------------------------------+
</code>```

The operations are:

```<code>+========+=======================================================+====+
| Number |                      Description                      | BF |
+========+=======================================================+====+
|      0 | Increment current memory cell.                        | +  |
+--------+-------------------------------------------------------+----+
|      1 | Decrement current memory cell.                        | -  |
+--------+-------------------------------------------------------+----+
|      2 | Move to next memory cell.                             | >  |
+--------+-------------------------------------------------------+----+
|      3 | Move to previous memory cell.                         | <  |
+--------+-------------------------------------------------------+----+
|      4 | Input a byte and store it in the current memory cell. | ,  |
+--------+-------------------------------------------------------+----+
|      5 | Output the current memory cell as ASCII.              | .  |
+--------+-------------------------------------------------------+----+
</code>```

Examples

Hello World:

```<code>roll-over roll-over heel roll-over roll-over roll-over roll-over heel heel heel
heel heel heel heel heel heel sit roll-over roll-over roll-over heel roll-over
roll-over roll-over heel heel heel heel heel heel heel heel roll-over roll-over
heel roll-over roll-over roll-over roll-over roll-over heel roll-over roll-over
roll-over roll-over roll-over stay roll-over roll-over roll-over heel roll-over
roll-over heel roll-over roll-over roll-over heel roll-over roll-over roll-over
roll-over heel heel heel heel heel heel heel sit roll-over roll-over roll-over
heel roll-over roll-over roll-over heel heel heel heel roll-over roll-over heel
roll-over roll-over roll-over roll-over roll-over heel roll-over roll-over
roll-over roll-over roll-over stay roll-over roll-over roll-over heel roll-over
roll-over roll-over heel roll-over roll-over roll-over roll-over roll-over heel
roll-over heel heel heel heel heel heel heel roll-over roll-over roll-over
roll-over roll-over heel heel roll-over heel heel heel roll-over roll-over
roll-over roll-over roll-over heel roll-over roll-over roll-over heel heel heel
roll-over roll-over roll-over roll-over heel heel heel heel heel heel heel heel
sit roll-over roll-over roll-over heel roll-over roll-over roll-over heel heel
heel heel roll-over roll-over heel roll-over roll-over roll-over roll-over
roll-over heel roll-over roll-over roll-over roll-over roll-over stay roll-over
roll-over roll-over heel roll-over roll-over heel roll-over roll-over roll-over
heel heel heel roll-over roll-over roll-over roll-over heel heel heel heel heel
heel heel heel heel heel sit roll-over roll-over roll-over heel roll-over
roll-over roll-over heel heel heel heel heel heel heel heel heel roll-over
roll-over heel roll-over roll-over roll-over roll-over roll-over heel roll-over
roll-over roll-over roll-over roll-over stay roll-over roll-over roll-over heel
roll-over roll-over roll-over roll-over heel heel heel roll-over roll-over
roll-over roll-over heel roll-over roll-over roll-over roll-over heel heel heel
heel roll-over roll-over heel roll-over heel heel heel roll-over roll-over
roll-over roll-over roll-over heel roll-over roll-over heel heel heel heel heel
heel roll-over roll-over roll-over roll-over heel roll-over roll-over heel heel
heel heel heel heel heel heel roll-over roll-over roll-over roll-over heel
roll-over roll-over roll-over heel heel roll-over roll-over roll-over roll-over
heel roll-over roll-over roll-over roll-over roll-over heel
</code>```

99 bottles of beer

Rules

Each submission should be either a full program or function. If it is a function, it must be runnable by only needing to add the function call to the bottom of the program. Anything else (e.g. headers in C), must be included.

If it is possible, please provide a link to an online site where your code can be tested.

Your program cannot write anything to STDERR (or something similar).

You can take input from STDIN (or the closest alternative in your language), or as an argument.

Standard loopholes are forbidden.

Scoring

Programs are scored according to bytes. The default character set is UTF-8, if you are using a different one, please specify.

That aside, this is code-golf, and the lowest byte count will be deemed the winner!

Submissions

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 leaderboard snippet:

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

Leaderboard

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

/* Configuration */

var QUESTION_ID = 79350; // Obtain this from the url
// It will be like https://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page
var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";
var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk";
var OVERRIDE_USER = 53406; // 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 "https://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 "https://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,]*[^\s,]),.*?(\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,
      });

  });

  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;
    if (/ b.lang) return 1;
    if (a.lang < b.lang) 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">

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

```

Update:

Sorry for not clarifying the sit and stay commands very well. They are, as @user6245072 said, like [ and ] in BF.

Update 2:

To clarify @KennyLau's questions:

The default operation is 0.

Memory consists of 8-bit cells.

Cells wrap on overflow/underflow.

Input is required for operation 4.

Body:
Ruby, 287 bytes

Runs on an infinite tape in both directions. DOGO input is a file on the command line. If there is no command line argument, a DOGO program will still work if passed in as STDIN, unless it uses operation 3 (get a byte from STDIN) in which case I have no idea. At any rate, file input is best.

Assumes no other text other than the four commands and whitespace exist in the program file.

Hello World Demonstration

i=k=o=0;m={}
c=$<.read.upcase.split.map{|e|%w{SIT STAY ROLL-OVER HEEL}.index e}.join
(m[k]||=0
e=c[i].to_i
e>2?o>4?$><<m[k].chr:
o>3?m[k]=STDIN.getc.ord:
o>1?k+=o>2?-1:1:
m[k]=o<1?-~m[k]%256:~-m[k]%256:
e>1?o=-~o%6:
e>0?m[k]>0?i=c.rindex(?0,i):0:
m[k]<1?i=c.index(?1,i):0
i+=1)while c[i]


问:
Showcase of Languages

Notes

This thread is open and unlocked only because the community decided to make an exception. Please do not use this question as evidence that you can ask similar questions here. Please do not create additional showcase questions.

This is no longer a popularity-contest, nor are snippet lengths limited by the vote tally. If you know this thread from before, please make sure you familiarize yourself with the changes.

This thread is dedicated to showing off interesting, useful, obscure, and/or unique features your favorite programming languages have to offer. This is neither a challenge nor a competition, but a collaboration effort to showcase as many programming languages as possible as well as possible.

How this works

All answers should include the name of the programming language at the top of the post, prefixed by a #.

Answers may contain one (and only one) factoid, i.e., a couple of sentences without code that describe the language.

Aside from the factoid, answers should consist of snippets of code, which can (but don't have to be) programs or functions.

The snippets do not need to be related. In fact, snippets that are too related may be redundant.

Since this is not a contest, all programming languages are welcome, whenever they were created.

Answers that contain more than a handful of code snippets should use a Stack Snippet to collapse everything except the factoid and one of the snippets.

Whenever possible, there should be only one answer per programming language. This is a community wiki, so feel free to add snippets to any answer, even if you haven't created it yourself. There is a Stack Snippet for compressing posts, which should mitigate the effect of the 30,000 character limit.

Answers that predate these guidelines should be edited. Please help updating them as needed.

Current answers, sorted alphabetically by language name

$.ajax({type:"GET",url:"https://api.stackexchange.com/2.2/questions/44680/answers?site=codegolf&filter=withbody",success:function(data){for(var i=0;i<data.items.length;i++){var temp=document.createElement('p');temp.innerHTML = data.items[i].body.split("\n")[0];$('#list').append('
' + temp.innerText || temp.textContent + '');}}})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><base href="http://codegolf.stackexchange.com"><ul id="list"></ul></code>```

答:
Sonic Pi

Code Snippet 4:

```<code>dice
</code>```

You don't see anything on the output, but if you show it with puts, it's a random number. Don't worry if your number is always the same, Sonic Pi uses the same random seed for every run, but that's good because else your songs would sound different every time.

Code Snippet 3:

```<code>:e1
</code>```

This equals the MIDI-Note 52 and the frequency 164.81377845643496 hz. It must start with a : so Sonic Pi knows it's an integrated constant.

Code Snippet 2:

```<code>[]
</code>```

Empty list. Sorry, nothing else except comments can be written in two bytes.

Code Snippet 1:

```<code>#
</code>```

Starts a comment.

Factoid: Sonic Pi is a sound coding language and is a full valued programming language.

Title: Showcase of Languages

Body:
Sonic Pi

Code Snippet 4:

dice

You don't see anything on the output, but if you show it with puts, it's a random number. Don't worry if your number is always the same, Sonic Pi uses the same random seed for every run, but that's good because else your songs would sound different every time.

Code Snippet 3:

:e1

This equals the MIDI-Note 52 and the frequency 164.81377845643496 hz. It must start with a : so Sonic Pi knows it's an integrated constant.

Code Snippet 2:

[]

Empty list. Sorry, nothing else except comments can be written in two bytes.

Code Snippet 1:

#

Starts a comment.

Factoid: Sonic Pi is a sound coding language and is a full valued programming language.


问:
Filter this string!
Your task is to write a program that will filter out some characters in a string, so that the remaining spells out (part of) the other string.

Let's say we received the string "123456781234567812345678", and the second string is "314159".

First, we put a pointer on the second string:

```<code>314159
^
</code>```

So the pointer is now on 3, and we replace the not-3 characters with a hashtag until the first 3:

```<code>##3456781234567812345678
</code>```

We then move the pointer to the next character until we have iterated through the string.

Specs

You may use any character to replace "#", and the first string will not contain the hashtag (or the replaced hashtag).

The second string will always be longer than enough.

Both strings will only contain ASCII printable characters (U+0020-U+007F).

Testcases

```<code>input1: 123456781234567812345678
input2: 314159
output: ##3#####1##4####1###5###

input1: abcdefghijklmnopqrstuvwxyz
input2: dilemma
output: ###d####i##l##############
</code>```

答:
Ruby, 44 bytes

If someone helps me golf it down by any amount, then I can say crossed-out 44 is still 44

```<code>->s,r{s.gsub(/./){$&==r[0]?(r[0]='';$&):?#}}
</code>```

Title: Filter this string!

Body:
Ruby, 44 bytes

If someone helps me golf it down by any amount, then I can say crossed-out 44 is still 44

->s,r{s.gsub(/./){$&==r[0]?(r[0]='';$&):?#}}


问:
Building a Bridge
Your task is to build a bridge to connect two cliffs given an input d, the distance apart. d will always be even

However, the bridge needs columns to hold it up. Each column can hold a max of 6 spaces on each side.

For this example:

```<code>________                        ________
        |                      |
   A    |                      |   B

        |----------------------|
                d = 22
</code>```

The bridge for d = 20should look like this with two columns. Columns do not count in d.

```<code>_____|__________|_____
12345|1234554321|12345
     |          |
</code>```

Rules:

Must have enough columns to stand up.

Must have minimum number of columns needed to stand up.

Must be symmetrical

Lowest amount of Bytes Wins

Examples: (#s are only to help you count spaces. Should not be included in your output)

d = 10

```<code>_____|_____
12345|12345
     |
</code>```

d = 32

```<code>_____|___________|___________|_____
12345|12345654321|           |
     |           |           |
</code>```

d = 8

```<code>____|____
1234|1234
    |
</code>```

d = 4

```<code>__|__
12|34
  |
</code>```

d = 22

```<code>_____|____________|_____
12345|123456654321|
     |            |
</code>```

or

```<code>______|__________|______
123456|1234554321|123456
      |          |
</code>```

答:
Ruby, 108 bytes

Probably can be golfed down a lot more. Greedy algorithm.

```<code>->d{s='',k=6
(s+=?_*[d,k].min+(d>k/2??|:'');d-=k;k=12)while d>0
s=s.chomp(?|)+s.reverse+$/
s+s.tr(?_,' ')*2}
</code>```

Title: Building a Bridge

Body:
Ruby, 108 bytes

Probably can be golfed down a lot more. Greedy algorithm.

->d{s='',k=6
(s+=?_*[d,k].min+(d>k/2??|:'');d-=k;k=12)while d>0
s=s.chomp(?|)+s.reverse+$/
s+s.tr(?_,' ')*2}


问:
Toilet Paper Mysteries
Today you need to solve a very practical problem: How many loops do you need to have a certain number of sheets on your toilet paper roll? Let's look at some facts:

The diameter of a bare toilet paper cylinder is 3.8cm

The length of one sheet of toilet paper is 10cm.

The thickness of one sheet of toilet paper is 1mm.

Before you wrap around the cylinder the first time, it has a circumference in cm of 3.8*pi. Every time you wrap a sheet around the cylinder its radius increases by .1, therefore its circumference increases by .2*PI. Use this information to find out how many loops it takes to fit n sheets of toilet paper. (Note: Use an approximation of Pi that is at least as accurate as 3.14159).

Test Cases:

n=1:

10/(3.8*pi) = .838 loops

n=2:

(How many full loops can we make?) 1 full loop = 3.8*pi = 11.938.

(How much do we have left after the 1st loop?) 20 - 11.938 = 8.062

(How much of a 2nd loop does the remaining piece make?) 8.062/(4*pi) = .642 loops

Answer: 1.642 loops

n=3:

1st full loop = 3.8*pi = 11.938, 2nd full loop = 4*pi = 12.566

30 - 11.938 - 12.566 = 5.496

5.496/(4.2*pi) = .417

Answer: 2.417 loops

n=100 => 40.874

答:
JavaScript, 44 bytes

```<code>w=(i,d=19,c=d/15.9155)=>i<c?i/c:1+w(i-c,d+1)
</code>```

I used anatolyg's idea and translated the code into JavaScript.

Title: Toilet Paper Mysteries

Body:
JavaScript, 44 bytes

w=(i,d=19,c=d/15.9155)=>i<c?i/c:1+w(i-c,d+1)

I used anatolyg's idea and translated the code into JavaScript.


问:
Find the remaining side of the tangential quadrilateral
(Taken from https://en.wikipedia.org/wiki/File:Tangential_quadrilateral.svg)

A tangential quadrilateral (see example above) is a quadrilateral in which a circle can be inscribed.

Your task is to find the possible value of d given a, b, and c.

Specs

a, b, c will all be positive integers.

If no possible value of d exists, output 0.

Scoring

This is code-golf. Shortest solution in bytes wins.

Testcases

```<code>a b c d
3 4 4 3
1 2 3 2
1 5 3 0
</code>```

答:
Python 2, <s>59</s> <s>53</s> 47 bytes

-6 bytes thanks to @KennyLau!

```<code>i=input;a,b,c=i(),i(),i();print(0,a+c-b)[b<a+c]
</code>```

Takes 3 inputs, a, b and c. Then applies the Pitot Theorem (d=a+c-b).

Ungolfed

```<code>a = input()
b = input()
c = input()
if b < a + c:
    print a + c - b
else:
    print 0
</code>```

Body:
Python 2, <s>59</s> <s>53</s> 47 bytes

-6 bytes thanks to @KennyLau!

i=input;a,b,c=i(),i(),i();print(0,a+c-b)[b<a+c]

Takes 3 inputs, a, b and c. Then applies the Pitot Theorem (d=a+c-b).

Ungolfed

a = input()
b = input()
c = input()
if b < a + c:
    print a + c - b
else:
    print 0


答:
><>, 122 bytes

At the risk of a little thread necromancy, I thought writing an answer in ><> would be an interesting challenge...

```<code>1&f8r\
1-:?!\r:@@:@$:@@:@g:2*1+&+4%:&}1$-@p{:3$-5gaa*-$@+@5gaa*-+r
2}p70\~
a7+=?\:@@:@g4+5go$1+:
o053.>~1+:64*=?;a
dedc_#@
</code>```

This program expects the number of steps to compute to be present on the stack before execution.

ContentLicense: CC BY-SA 2.5

Title: Langton's ant ASCII art.

Body:
Draw the path of Langton's ant.

Description

Squares on a plane are colored variously either black or white. We arbitrarily identify one square as the "ant". The ant can travel in any of the four cardinal directions at each step it takes. The ant moves according to the rules below:

At a white square, turn 90° right, flip the color of the square, move forward one unit

At a black square, turn 90° left, flip the color of the square, move forward one unit

Specifications

Input: an integer N between 0 and 725 (inclusive).

Output: a 17 by 17 grid representing the "path" of the ant as of step N.

Rules

The ant starts facing right (3 o' clock).

The ant starts at the center of the grid.

Use _#@ for white squares, black squares and the ant respectively.

The grid is initially completely white.

You may make either a complete program or a function on an interpreted language.

Input by stdin or argument.

Examples

Update: case's N = 450 output was wrong.

N = 0

```<code>_________________
_________________
_________________
_________________
_________________
_________________
_________________
_________________
________@________
_________________
_________________
_________________
_________________
_________________
_________________
_________________
_________________
</code>```

N = 1

```<code>_________________
_________________
_________________
_________________
_________________
_________________
_________________
_________________
________#________
________@________
_________________
_________________
_________________
_________________
_________________
_________________
_________________
</code>```

N = 450

```<code>_________________
_________________
___________##____
____##______##___
___#__##___##_#__
__###_#@#__#__#__
__#_#_#_#__#_#___
_____###___#_____
_____#___________
_____#__###______
___#_#_#__#_#_#__
__#__#_#____###__
__#_##__##___#___
___##______##____
____##___________
_________________
_________________
</code>```

Body:
><>, 122 bytes

At the risk of a little thread necromancy, I thought writing an answer in ><> would be an interesting challenge...

1&f8r\
1-:?!\r:@@:@$:@@:@g:2*1+&+4%:&}1$-@p{:3$-5gaa*-$@+@5gaa*-+r
2}p70\~
a7+=?\:@@:@g4+5go$1+:
o053.>~1+:64*=?;a
dedc_#@

This program expects the number of steps to compute to be present on the stack before execution.


问:
Remove unnecessary parentheses
You are given a string composed with the characters 0123456789+*(). You can assume that string is always a valid mathematical expression.

Your task is to remove the unnecessary parentheses, assuming multiplication has higher priority than addition.

The parentheses should be removed only when they are not needed structurally:

because of multiplication higher priority: 3+(4*5) => 3+4*5

because of multiplication or addition associativity: 3*(4*5) => 3*4*5

when they are redundant around an expression: 3*((4+5)) => 3*(4+5)

Parentheses should be kept when they could be simplified because of specific number values:

1*(2+3) should not be simplified to 1*2+3

0*(1+0) should not be simplified to 0*1+0

Examples:

```<code>(4*12)+11         ==>    4*12+11
(1+2)*3           ==>    (1+2)*3
3*(4*5)           ==>    3*4*5
((((523))))       ==>    523
(1+1)             ==>    1+1
1*(2*(3+4)*5)*6   ==>    1*2*(3+4)*5*6
1*(2+3)           ==>    1*(2+3)
0*(1+0)           ==>    0*(1+0)

(((2+92+82)*46*70*(24*62)+(94+25))+6)    ==>    (2+92+82)*46*70*24*62+94+25+6
</code>```

答:
Retina, 155 bytes

```<code>{`\(((\d+|\((((\()|(?<-5>\))|[^()])*(?(5)^))\))(\*(\d+|\((((\()|(?<-10>\))|[^()])*(?(10)^))\)))*)\)
$1
(?<!\*)\((((\()|(?<-3>\))|[^()])*(?(3)^))\)(?!\*)
$1
</code>```

Try it online!

Verify all testcases at once.

Explanation

The main thing is this code:

```<code>(((\()|(?<-3>\))|[^()])*(?(3)^)
</code>```

This regex can match any string in which the brackets are balanced, e.g. 1+(2+(3))+4 or 2+3.

For the ease of explanation, let this regex be B.

Also, let us use < and > instead for the brackets, as well as p and m for \+ and \*.

The code becomes:

```<code>{`<((\d+|<B>)(m(\d+|<B>))*)>
$1
(?<!m)<B>(?!m)
$1
</code>```

The first two lines match for brackets which consist of only multiplication, e.g. (1*2*3) or even (1*(2+3)*4). They are replaced by their content inside.

The last two lines match for brackets which are not preceded and which are not followed by multiplication. They are replaced by their content inside.

The initial {` means "replace until idempotent", meaning that the replacements are done until they either no longer match or they are replaced with themselves.

In this case, the replacements are done until they no longer match.

Title: Remove unnecessary parentheses

Body:
Retina, 155 bytes

{`\(((\d+|\((((\()|(?<-5>\))|[^()])*(?(5)^))\))(\*(\d+|\((((\()|(?<-10>\))|[^()])*(?(10)^))\)))*)\)
$1
(?<!\*)\((((\()|(?<-3>\))|[^()])*(?(3)^))\)(?!\*)
$1

Try it online!

Verify all testcases at once.

Explanation

The main thing is this code:

(((\()|(?<-3>\))|[^()])*(?(3)^)

This regex can match any string in which the brackets are balanced, e.g. 1+(2+(3))+4 or 2+3.

For the ease of explanation, let this regex be B.

Also, let us use < and > instead for the brackets, as well as p and m for \+ and \*.

The code becomes:

{`<((\d+|<B>)(m(\d+|<B>))*)>
$1
(?<!m)<B>(?!m)
$1

The first two lines match for brackets which consist of only multiplication, e.g. (1*2*3) or even (1*(2+3)*4). They are replaced by their content inside.

The last two lines match for brackets which are not preceded and which are not followed by multiplication. They are replaced by their content inside.

The initial {` means "replace until idempotent", meaning that the replacements are done until they either no longer match or they are replaced with themselves.

In this case, the replacements are done until they no longer match.


Title: Filter this string!

Body:
Your task is to write a program that will filter out some characters in a string, so that the remaining spells out (part of) the other string.

Let's say we received the string "123456781234567812345678", and the second string is "314159".

First, we put a pointer on the second string:

```<code>314159
^
</code>```

So the pointer is now on 3, and we replace the not-3 characters with a hashtag until the first 3:

```<code>##3456781234567812345678
</code>```

We then move the pointer to the next character until we have iterated through the string.

Specs

You may use any character to replace "#", and the first string will not contain the hashtag (or the replaced hashtag).

The second string will always be longer than enough.

Both strings will only contain ASCII printable characters (U+0020-U+007F).

Testcases

```<code>input1: 123456781234567812345678
input2: 314159
output: ##3#####1##4####1###5###

input1: abcdefghijklmnopqrstuvwxyz
input2: dilemma
output: ###d####i##l##############
</code>```

Body:
Perl, 77 bytes

sub _{$p=substr$f,0,1,''}($_,$f)=@ARGV;_;print map{$_ eq$p?_&&$_||$_:'#'}/./g


答:
Mathematica, <s>105</s> <s>97</s> 91 bytes

-6 bytes thanks to Roman!

```<code>a=StringReplace;ToString@ToExpression@a[#,{"*"->"**","+"->"~~"}]~a~{" ** "->"*","~~"->"+"}&
</code>```

Replaces + and * with ~~ (StringExpression) and ** (NonCommutativeMultiply) respectively, evaluates it, stringifies it, and replaces the operators back.

Title: Remove unnecessary parentheses

Body:
You are given a string composed with the characters 0123456789+*(). You can assume that string is always a valid mathematical expression.

Your task is to remove the unnecessary parentheses, assuming multiplication has higher priority than addition.

The parentheses should be removed only when they are not needed structurally:

because of multiplication higher priority: 3+(4*5) => 3+4*5

because of multiplication or addition associativity: 3*(4*5) => 3*4*5

when they are redundant around an expression: 3*((4+5)) => 3*(4+5)

Parentheses should be kept when they could be simplified because of specific number values:

1*(2+3) should not be simplified to 1*2+3

0*(1+0) should not be simplified to 0*1+0

Examples:

```<code>(4*12)+11         ==>    4*12+11
(1+2)*3           ==>    (1+2)*3
3*(4*5)           ==>    3*4*5
((((523))))       ==>    523
(1+1)             ==>    1+1
1*(2*(3+4)*5)*6   ==>    1*2*(3+4)*5*6
1*(2+3)           ==>    1*(2+3)
0*(1+0)           ==>    0*(1+0)

(((2+92+82)*46*70*(24*62)+(94+25))+6)    ==>    (2+92+82)*46*70*24*62+94+25+6
</code>```

Body:
Mathematica, <s>105</s> <s>97</s> 91 bytes

-6 bytes thanks to Roman!

a=StringReplace;ToString@ToExpression@a[#,{"*"->"**","+"->"~~"}]~a~{" ** "->"*","~~"->"+"}&

Replaces + and * with ~~ (StringExpression) and ** (NonCommutativeMultiply) respectively, evaluates it, stringifies it, and replaces the operators back.

ContentLicense: CC BY-SA 4.0


Title: Remove unnecessary parentheses

Body:
JavaScript (ES6) 163 <s>178</s>

Edit 15 bytes saved thx @IsmaelMiguel

a=>eval(`s=[]${_=';for(b=0;a!=b;a=b.replace(/'}\\(([^()]*)\\)(?=(.?))/,(x,y,z,p)=>~y.indexOf('+')?-s.push(b[p-1]=='*'|z=='*'?x:y):y))b=a;${_}-\\d+/,x=>s[~x]))b=a`)

Less golfed

a=>{
  for(s=[],b='';
      a!=b;
      a=b.replace(/\(([^()]*)\)(?=(.?))/,(x,y,z,p)=>y.indexOf('+')<0?y:-s.push(b[p-1]=='*'|z=='*'?x:y)))
    b=a;
  for(b=0;
      a!=b;
      a=b.replace(/-\d+/,x=>s[~x]))
    b=a;
  return a
}

Test

f=a=>eval(`s=[]${_=';for(b=0;a!=b;a=b.replace(/'}\\(([^()]*)\\)(?=(.?))/,(x,y,z,p)=>~y.indexOf('+')
?-s.push(b[p-1]=='*'|z=='*'?x:y)
:y))b=a;${_}-\\d+/,x=>s[~x]))b=a`)

console.log=x=>O.textContent+=x+'\n'

test=`(4*12)+11         ==>    4*12+11
(1+2)*3           ==>    (1+2)*3
3*(4*5)           ==>    3*4*5
((((523))))       ==>    523
(1+1)             ==>    1+1
1*(2*(3+4)*5)*6   ==>    1*2*(3+4)*5*6
1*(2+3)           ==>    1*(2+3)
0*(1+0)           ==>    0*(1+0)
(((2+92+82)*46*70*(24*62)+(94+25))+6)    ==>    (2+92+82)*46*70*24*62+94+25+6`

test.split`\n`.forEach(r=>{
  var t,k,x
  [t,,k]=r.match(/\S+/g)
  x=f(t)
  console.log((x==k?'OK ':'KO ')+t+' -> '+x+(x==k?'':' expected '+k))
})

<pre id=O></pre>


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

答:
><>, 27 26 23 bytes

```<code>\ln;
\::2%:@5*1+2,*+:2=?
</code>```

Like the other ><> answers, this builds the sequence on the stack. Once the sequence reaches 2, the size of the stack is the number of steps taken.

Thanks to @Hohmannfan, saved 3 bytes by a very clever method of computing the next value directly. The formula used to calculate the next value in the sequence is:

$$f(n)=n\cdot\frac{5(n\bmod2)+1}{2}+(n\bmod2)$$

The fraction maps even numbers to 0.5, and odd numbers to 3. Multiplying by n and adding n%2 completes the calculation - no need to choose the next value at all!

Edit 2: Here's the pre-@Hohmannfan version:

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

The trick here is that both 3n+1 and n/2 are computed at each step in the sequence, and the one to be dropped from the sequence is chosen afterwards. This means that the code doesn't need to branch until 1 is reached, and the calculation of the sequence can live on one line of code.

Edit: Golfed off another character after realising that the only positive integer that can lead to 1 is 2. As the output of the program doesn't matter for input < 2, the sequence generation can end when 2 is reached, leaving the stack size being the exact number of steps required.

Previouser version:

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

Title: Collatz Conjecture (OEIS A006577)

Body:
><>, 27 26 23 bytes

\ln;
\::2%:@5*1+2,*+:2=?

Like the other ><> answers, this builds the sequence on the stack. Once the sequence reaches 2, the size of the stack is the number of steps taken.

Thanks to @Hohmannfan, saved 3 bytes by a very clever method of computing the next value directly. The formula used to calculate the next value in the sequence is:

$$f(n)=n\cdot\frac{5(n\bmod2)+1}{2}+(n\bmod2)$$

The fraction maps even numbers to 0.5, and odd numbers to 3. Multiplying by n and adding n%2 completes the calculation - no need to choose the next value at all!

Edit 2: Here's the pre-@Hohmannfan version:

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

The trick here is that both 3n+1 and n/2 are computed at each step in the sequence, and the one to be dropped from the sequence is chosen afterwards. This means that the code doesn't need to branch until 1 is reached, and the calculation of the sequence can live on one line of code.

Edit: Golfed off another character after realising that the only positive integer that can lead to 1 is 2. As the output of the program doesn't matter for input < 2, the sequence generation can end when 2 is reached, leaving the stack size being the exact number of steps required.

Previouser version:

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


答:
Python3 + PEG implementation in Python, 271 bytes

```<code>import peg
e=lambda o,m=0:o.choice and str(o)or(m and o[1][1]and"("+e(o[1])+")"or e(o[1]))if hasattr(o,"choice")else o[1]and e(o[0],1)+"".join(str(x[0])+e(x[1],1)for x in o[1])or e(o[0])
print(e(peg.compile_grammar('e=f("+"f)*f=p("*"p)*p="("e")"/[0-9]+').parse(input())))
</code>```

A while back I made a PEG implementation in Python. I guess I can use that here.

Parses the expression into a tree, and only keeps parenthesis if the child is addition, and the parent is multiplication.

Title: Remove unnecessary parentheses

Body:
Python3 + PEG implementation in Python, 271 bytes

import peg
e=lambda o,m=0:o.choice and str(o)or(m and o[1][1]and"("+e(o[1])+")"or e(o[1]))if hasattr(o,"choice")else o[1]and e(o[0],1)+"".join(str(x[0])+e(x[1],1)for x in o[1])or e(o[0])
print(e(peg.compile_grammar('e=f("+"f)*f=p("*"p)*p="("e")"/[0-9]+').parse(input())))

A while back I made a PEG implementation in Python. I guess I can use that here.

Parses the expression into a tree, and only keeps parenthesis if the child is addition, and the parent is multiplication.


问:
Finite Cantor's Diagonal
Given a list of N integers, each with N digits, output a number which differs from the first number because of the first digit, the second number because of the second digit, etc.

Example

Given this list:

```<code>1234
4815
1623
4211
</code>```

The number 2932's first digit is different from the first number's first digit, its second digit is different from the second number's second digit, etc. Therefore it would be a valid output.

Inputs

You may take both the list and N as input, or only the list if you wish.

Each integer in the list will necessarily have as many digits as the length of the list (N)

Numbers will not have any leading zeroes

The input list must contain numbers and not strings.

You may take inputs as function arguments, through STDIN, or anything similar.

You may assume that the list will not be longer than 10 elements (and no number in the list will be bigger than 2147483647)

Outputs

It is not sufficient that the output is not in the list. The digits must differ as explained above.

You can use any digit selection strategy that respects the constraint of different digits.

The number cannot have leading zeroes

You may output the number through STDOUT, return it from a function, etc.

Test cases

```<code>Input:
12345678
23456789
34567890
45678901
56789012
67890123
78901234
89012345

Possible output: 24680246

Input:
1

Possible output: 2
</code>```

Scoring

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

答:
MATL, <s>11</s> <s>10</s> 9 bytes

```<code>VXd9\QV!U
</code>```

Takes only a column vector of integers as input. N is not provided.

Try it Online

Explanation

```<code>    % Implicity grab input as column vector of numbers
V   % Convert the input column vector into a 2D character array
Xd  % Grab the diagonal elements of the character array
9\  % Take the modulus of each ASCII code and 9
Q   % Add 1 to remove all zeros
V   % Convert the result to a string
!   % Transpose to yield a row vector of characters
U   % Convert back to an integer (as per the rules)
    % Implicitly display result
</code>```

Title: Finite Cantor's Diagonal

Body:
MATL, <s>11</s> <s>10</s> 9 bytes

VXd9\QV!U

Takes only a column vector of integers as input. N is not provided.

Try it Online

Explanation

    % Implicity grab input as column vector of numbers
V   % Convert the input column vector into a 2D character array
Xd  % Grab the diagonal elements of the character array
9\  % Take the modulus of each ASCII code and 9
Q   % Add 1 to remove all zeros
V   % Convert the result to a string
!   % Transpose to yield a row vector of characters
U   % Convert back to an integer (as per the rules)
    % Implicitly display result


答:
CJam (15 14 bytes)

```<code>qN/ee{:=i2%)}%
</code>```

Online demo

Thanks to Adnan for a one-byte saving.

Dissection

```<code>qN/    e# Split input on newlines
ee{    e# Label each line with its index and map:
  :=i  e#   Get the character at the same index (i.e. diagonalise)
  2%)  e#   Compute (ASCII value mod 2) + 1
       e#   Maps 0 1 2 3 4 5 6 7 8 9
       e#     to 1 2 1 2 1 2 1 2 1 2
}%
</code>```

Title: Finite Cantor's Diagonal

Body:
Given a list of N integers, each with N digits, output a number which differs from the first number because of the first digit, the second number because of the second digit, etc.

Example

Given this list:

```<code>1234
4815
1623
4211
</code>```

The number 2932's first digit is different from the first number's first digit, its second digit is different from the second number's second digit, etc. Therefore it would be a valid output.

Inputs

You may take both the list and N as input, or only the list if you wish.

Each integer in the list will necessarily have as many digits as the length of the list (N)

Numbers will not have any leading zeroes

The input list must contain numbers and not strings.

You may take inputs as function arguments, through STDIN, or anything similar.

You may assume that the list will not be longer than 10 elements (and no number in the list will be bigger than 2147483647)

Outputs

It is not sufficient that the output is not in the list. The digits must differ as explained above.

You can use any digit selection strategy that respects the constraint of different digits.

The number cannot have leading zeroes

You may output the number through STDOUT, return it from a function, etc.

Test cases

```<code>Input:
12345678
23456789
34567890
45678901
56789012
67890123
78901234
89012345

Possible output: 24680246

Input:
1

Possible output: 2
</code>```

Scoring

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

Body:
CJam (15 14 bytes)

qN/ee{:=i2%)}%

Online demo

Thanks to Adnan for a one-byte saving.

Dissection

qN/    e# Split input on newlines
ee{    e# Label each line with its index and map:
  :=i  e#   Get the character at the same index (i.e. diagonalise)
  2%)  e#   Compute (ASCII value mod 2) + 1
       e#   Maps 0 1 2 3 4 5 6 7 8 9
       e#     to 1 2 1 2 1 2 1 2 1 2
}%


答:
Pyth, 14 bytes

```<code>s.e|-\1@bk\2`M
</code>```

Try it online!

Title: Finite Cantor's Diagonal

Body:
Pyth, 14 bytes

s.e|-\1@bk\2`M

Try it online!


答:
Pyth, 11 bytes

```<code>jk.eh!ts@`b
</code>```

Simple loop, change every digit to 1, except 1 becomes 2.

Title: Finite Cantor's Diagonal

Body:
Pyth, 11 bytes

jk.eh!ts@`b

Simple loop, change every digit to 1, except 1 becomes 2.


答:
Jelly, <s>8</s> 7 bytes

1 byte saved thanks to Dennis.

```<code>DŒDḢỊ‘Ḍ
</code>```

Try it online!

Explanation

```<code>DŒDḢỊ‘Ḍ    Main link. Takes list as argument.
D          Convert each integer to decimal.
 ŒD        Get the diagonals.
   Ḣ       Get the first diagonal.
    Ị      Check if every digit <= 1.
     ‘     Increment every digit.
      Ḍ    Convert back to integer from decimal.
</code>```

Converts each digit to 1, except 0 and 1 becomes 2.

Title: Finite Cantor's Diagonal

Body:
Jelly, <s>8</s> 7 bytes

1 byte saved thanks to Dennis.

DŒDḢỊ‘Ḍ

Try it online!

Explanation

DŒDḢỊ‘Ḍ    Main link. Takes list as argument.
D          Convert each integer to decimal.
 ŒD        Get the diagonals.
   Ḣ       Get the first diagonal.
    Ị      Check if every digit <= 1.
     ‘     Increment every digit.
      Ḍ    Convert back to integer from decimal.

Converts each digit to 1, except 0 and 1 becomes 2.


问:
Tiling by substitution
EDIT: The incorrect A rhomb substitution has been fixed. Apologies to anoyone who had started working on a solution.

Consider the following substitutions, where the substituted rhomb(us) is scaled up and shown in red:

EDIT: Note the anchor points (circle) created where a corner of each new rhomb touches the substituted rhomb. Also note the substitution's anchor point (black circle).

A rhomb (144°, 36°)

... becomes ...

B rhomb (72°, 108°)

 ... becomes ...

Each substitution is made up of some combination of A rhombs and B rhombs, on which the same substitutions can be performed.

A tiling can be created by repeating the substitutions n times.

After n=2 substitutions of A rhomb:

EDIT: The substitution is oriented by aligning the rhomb's anchor point with the substitution's anchor point

In the fewest bytes of code (given input n>=0) draw the tiling after n substitutions, where n=0 is A rhomb

Notes:

The red lines and anchor points shouldn't be included, they only illustrate the substitution.

In each substitution the tiling is scaled up so the rhombs have a constant size.

Any rotation is optional.

Graphical choices (colour, dimensions, cropping etc.) are optional if not exploited for loopholes.

答:
Java, 881 bytes

```<code>import java.awt.image.BufferedImage;import static java.lang.Math.*;class J{BufferedImage o=new BufferedImage(999,999,1);java.awt.Graphics g=o.getGraphics();double v=2.5132,w=1.2566,p=PI,s=(p-v)/2,u=(p+w)/2;public static void main(String[]v){new J(Integer.parseInt(v[0]));}J(int i){d(609,391,v,p/4+s,500,i);try{javax.imageio.ImageIO.write(o,"png",new java.io.File("a.png"));}catch(Exception e){}}void d(int x,int y,double o,double q,double l,int r){int m=(int)(2*l*sin((p-o)/2)),a=(int)(x+cos(q)*l),b=(int)(y+sin(q)*l),c=(int)(x+cos(q+o/2)*m),d=(int)(y+sin(q+o/2)*m),e=(int)(x+cos(q+o)*l),f=(int)(y+sin(q+o)*l);if(r-->0){double n=l/(2*sin((v)/2));if(o>w){d(x,y,v,q-s,n,r);d(c,d,v,q+p+s,n,r);d(a,b,w,q+u,n,r);}else{d(x,y,w,q-s,n,r);d(c,d,w,q+p+s,n,r);d(e,f,w,q-p/2,n,r);d(a,b,v,q+p/2-s-s,n,r);}}else{g.drawLine(x,y,a,b);g.drawLine(a,b,c,d);g.drawLine(x,y,e,f);g.drawLine(c,d,e,f);}}}
</code>```

Ungolfed

```<code>import java.awt.image.BufferedImage;

import static java.lang.Math.*;

class Q79373 {
    BufferedImage image = new BufferedImage(999, 999, 1);
    java.awt.Graphics graphics = image.getGraphics();
    double aRad = 2.5132, bRad = 1.2566, pi = PI, aAcuteHalf = (pi - aRad) / 2, bRadHalfPi = (pi + bRad) / 2;

    public static void main(String[] v) {
        new Q79373(Integer.parseInt(v[0]));
    }

    Q79373(int i) {
        draw(609, 391, aRad, pi / 4 + aAcuteHalf, 500, i);
        try {
            javax.imageio.ImageIO.write(image, "png", new java.io.File("a.png"));
        } catch (Exception e) {
        }
    }

    void draw(int x, int y, double rad, double rot, double length, int recDepth) {
        int
                height = (int) (2 * length * sin((pi - rad) / 2)),
                a = (int) (x + cos(rot) * length),
                b = (int) (y + sin(rot) * length),
                c = (int) (x + cos(rot + rad / 2) * height),
                d = (int) (y + sin(rot + rad / 2) * height),
                e = (int) (x + cos(rot + rad) * length),
                f = (int) (y + sin(rot + rad) * length);

        if (recDepth-- > 0) {
            double lengthNew = length / (2 * sin((aRad) / 2));
            if (rad > bRad) {
                draw(x, y, aRad, rot - aAcuteHalf, lengthNew, recDepth);
                draw(c, d, aRad, rot + pi + aAcuteHalf, lengthNew, recDepth);
                draw(a, b, bRad, rot + bRadHalfPi, lengthNew, recDepth);
            } else {
                draw(x, y, bRad, rot - aAcuteHalf, lengthNew, recDepth);
                draw(c, d, bRad, rot + pi + aAcuteHalf, lengthNew, recDepth);
                draw(e, f, bRad, rot - pi / 2, lengthNew, recDepth);
                draw(a, b, aRad, rot + pi / 2 - aAcuteHalf - aAcuteHalf, lengthNew, recDepth);
            }
        } else {
            graphics.drawLine(x, y, a, b);
            graphics.drawLine(a, b, c, d);
            graphics.drawLine(x, y, e, f);
            graphics.drawLine(c, d, e, f);
        }
    }
}
</code>```

Notes

The results arent 100% acurate thanks to integer precision. I used integers for the coordinates because Graphics::drawLine only takes integers as arguments, and I would've ended up with way more integer casts than I have now.

I'll probably golf a bit more later, still not optimal.

Results

```<code>Full image filled
</code>```

```<code>Recursion 1
</code>```

```<code>Recursion 2
</code>```

```<code>Recursion 3
</code>```

Title: Tiling by substitution

Body:
Java, 881 bytes

import java.awt.image.BufferedImage;import static java.lang.Math.*;class J{BufferedImage o=new BufferedImage(999,999,1);java.awt.Graphics g=o.getGraphics();double v=2.5132,w=1.2566,p=PI,s=(p-v)/2,u=(p+w)/2;public static void main(String[]v){new J(Integer.parseInt(v[0]));}J(int i){d(609,391,v,p/4+s,500,i);try{javax.imageio.ImageIO.write(o,"png",new java.io.File("a.png"));}catch(Exception e){}}void d(int x,int y,double o,double q,double l,int r){int m=(int)(2*l*sin((p-o)/2)),a=(int)(x+cos(q)*l),b=(int)(y+sin(q)*l),c=(int)(x+cos(q+o/2)*m),d=(int)(y+sin(q+o/2)*m),e=(int)(x+cos(q+o)*l),f=(int)(y+sin(q+o)*l);if(r-->0){double n=l/(2*sin((v)/2));if(o>w){d(x,y,v,q-s,n,r);d(c,d,v,q+p+s,n,r);d(a,b,w,q+u,n,r);}else{d(x,y,w,q-s,n,r);d(c,d,w,q+p+s,n,r);d(e,f,w,q-p/2,n,r);d(a,b,v,q+p/2-s-s,n,r);}}else{g.drawLine(x,y,a,b);g.drawLine(a,b,c,d);g.drawLine(x,y,e,f);g.drawLine(c,d,e,f);}}}

Ungolfed

import java.awt.image.BufferedImage;

import static java.lang.Math.*;

class Q79373 {
    BufferedImage image = new BufferedImage(999, 999, 1);
    java.awt.Graphics graphics = image.getGraphics();
    double aRad = 2.5132, bRad = 1.2566, pi = PI, aAcuteHalf = (pi - aRad) / 2, bRadHalfPi = (pi + bRad) / 2;

    public static void main(String[] v) {
        new Q79373(Integer.parseInt(v[0]));
    }

    Q79373(int i) {
        draw(609, 391, aRad, pi / 4 + aAcuteHalf, 500, i);
        try {
            javax.imageio.ImageIO.write(image, "png", new java.io.File("a.png"));
        } catch (Exception e) {
        }
    }

    void draw(int x, int y, double rad, double rot, double length, int recDepth) {
        int
                height = (int) (2 * length * sin((pi - rad) / 2)),
                a = (int) (x + cos(rot) * length),
                b = (int) (y + sin(rot) * length),
                c = (int) (x + cos(rot + rad / 2) * height),
                d = (int) (y + sin(rot + rad / 2) * height),
                e = (int) (x + cos(rot + rad) * length),
                f = (int) (y + sin(rot + rad) * length);

        if (recDepth-- > 0) {
            double lengthNew = length / (2 * sin((aRad) / 2));
            if (rad > bRad) {
                draw(x, y, aRad, rot - aAcuteHalf, lengthNew, recDepth);
                draw(c, d, aRad, rot + pi + aAcuteHalf, lengthNew, recDepth);
                draw(a, b, bRad, rot + bRadHalfPi, lengthNew, recDepth);
            } else {
                draw(x, y, bRad, rot - aAcuteHalf, lengthNew, recDepth);
                draw(c, d, bRad, rot + pi + aAcuteHalf, lengthNew, recDepth);
                draw(e, f, bRad, rot - pi / 2, lengthNew, recDepth);
                draw(a, b, aRad, rot + pi / 2 - aAcuteHalf - aAcuteHalf, lengthNew, recDepth);
            }
        } else {
            graphics.drawLine(x, y, a, b);
            graphics.drawLine(a, b, c, d);
            graphics.drawLine(x, y, e, f);
            graphics.drawLine(c, d, e, f);
        }
    }
}

Notes

The results arent 100% acurate thanks to integer precision. I used integers for the coordinates because Graphics::drawLine only takes integers as arguments, and I would've ended up with way more integer casts than I have now.

I'll probably golf a bit more later, still not optimal.

Results

Full image filled

Recursion 1

Recursion 2

Recursion 3


答:
Python 2, 54 bytes

```<code>d,r=1,""
for n in input():r+=`1+-~n/d%9`;d*=10
print r
</code>```

Title: Finite Cantor's Diagonal

Body:
Python 2, 54 bytes

d,r=1,""
for n in input():r+=`1+-~n/d%9`;d*=10
print r


答:
J, 37 bytes

```<code>f@(9&-@"."0@((>:@#*i.@#){f=:[:,":"0))
</code>```

Can probably be golfed, but I forgot if there was a command for "diagonals".

Title: Finite Cantor's Diagonal

Body:
J, 37 bytes

f@(9&-@"."0@((>:@#*i.@#){f=:[:,":"0))

Can probably be golfed, but I forgot if there was a command for "diagonals".


问:
Outline a PNG image

Intro (semi fictional)

I'm the solo developer of a game, I'm already struggling with character design as is. Hence I've thought of a smart solution, I'll just use images for regular monsters, outline them a bit and suddenly they are boss monsters! That will save me from thinking up new bosses yay.

However, I have approximately 100 monster designs already and I wouldn't like duplicating them all and manually drawing an outline to the images...

Challenge

Given a file name (of a PNG file) as input, you should write a program/function which will draw an outline around every non-transparent pixel. The program/function should save the output file to a new file called a.png

What does outlining mean

Outlining is the process of adding non-transparent pixels in the place of transparent pixels, around pixels which were non-transparent already. Any transparent pixel has an opacity of exactly 0%, anything else is defined as non-transparent. Any pixel which will be outlined will have an opacity of 100%, aka the alpha channel of that pixel will be 255.

Input

Your program/function should take 3 variables as input. Feel free to provide these as function parameters, read them from stdin or any other method which suits you best.

The first variable is the file name, which is always a PNG file.

The second variable is the outline colour, which is a round integer, you can also take the colour from 3 separate r,g,b byte values.

The third variable is the outline width, also an integer.

Outline width

The width of the outline equals the maximum distance any transparent pixel should have to a non-transparent pixel in order to be outlined. The distance is calculated using the Manhattan distance between two points.

If the input image has only 1 non-transparent pixel, at [0,0] and the outline width is 2, then the following pixels will be coloured:
[0,1] [0,-1] [1,0] [-1,0] [1,1] [-1,-1] [1,-1] [-1,1] [2,0] [-2,0] [0,2] [0,-2], for these have a manhattan distance of 2 or less from the coloured pixel

Test cases

The following test cases are scaled up 7 times for visibility, so every block of 7 pixels should be treated as a single pixel

These are the input images used for the test cases:

```<code>input1.png
</code>```

```<code>input2.png
</code>```

```<code>input3.png
</code>```

These are the actual test cases:

```<code>input1.png, 0xFF0000, 0
</code>```

```<code>input1.png, 0xFF0000, 1
</code>```

```<code>input1.png, 0xFF0000, 2
</code>```

```<code>input1.png, 0xFF0000, 3
</code>```

```<code>input1.png, 0xFF0000, 10
</code>```

```<code>input2.png, 0xFF0000, 2
</code>```

```<code>input3.png, 0x000000, 2
</code>```

Click here for the full Imgur album.

This is code-golf, standard loopholes apply! Feel free to submit your own images as test cases, since these pixel images aren't very creative ;)

答:
Matlab, 202 bytes

```<code>function f(i,r,g,b,n);[i,~,a]=imread(i);[x,y]=ndgrid(abs(-n:n));d=permute([r,g,b,255]',3:-1:1);I=cat(3,i,a);J=uint8(bsxfun(@times,~~convn(a,x+y<=n,'s')&~a,d))+I;imwrite(J(:,:,1:3),'a.png','Al',J(:,:,4))
</code>```

As always:

Convolution is the key to success.

The function can be called like so:

```<code>f('my_image.png', red_int, green_int, blue_int, dist)
</code>```

Commented:

```<code>function f(i,r,g,b,n)
[i,~,a]=imread(i);                   %read image and alpha channel
[x,y]=ndgrid(abs(-n:n));             %computations for convolution kernel
d=permute([r,g,b,255]',3:-1:1);      %create 'pixel' that will be inserted
I=cat(3,i,a);                        %concatenate image and alpha channel
J=uint8(bsxfun(@times,~~convn(a,x+y<=n,'s')&~a,d))+I; %find border via convolution of kernel, insert pixels and recombine with original
imwrite(J(:,:,1:3),'a.png','Al',J(:,:,4)) %write file
</code>```

Title: Outline a PNG image

Body:
Matlab, 202 bytes

function f(i,r,g,b,n);[i,~,a]=imread(i);[x,y]=ndgrid(abs(-n:n));d=permute([r,g,b,255]',3:-1:1);I=cat(3,i,a);J=uint8(bsxfun(@times,~~convn(a,x+y<=n,'s')&~a,d))+I;imwrite(J(:,:,1:3),'a.png','Al',J(:,:,4))

As always:

Convolution is the key to success.

The function can be called like so:

f('my_image.png', red_int, green_int, blue_int, dist)

Commented:

function f(i,r,g,b,n)
[i,~,a]=imread(i);                   %read image and alpha channel
[x,y]=ndgrid(abs(-n:n));             %computations for convolution kernel
d=permute([r,g,b,255]',3:-1:1);      %create 'pixel' that will be inserted
I=cat(3,i,a);                        %concatenate image and alpha channel
J=uint8(bsxfun(@times,~~convn(a,x+y<=n,'s')&~a,d))+I; %find border via convolution of kernel, insert pixels and recombine with original
imwrite(J(:,:,1:3),'a.png','Al',J(:,:,4)) %write file


问:
KOTH: TNT Run Challenge
This was inspired by a Minecraft mini-game. The rules are pretty simple: you run and jump around, and every block you step on disappears once you've stepped on it. The goal is to be the last one left.

Your bot should be a complete program. It should accept input as a command line argument. The input will be a map of the "world"; here is an example:

```<code>xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxx xxxxxxxxxxxxxxxxxxxxxxxxxxx
xxx xxxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxx x xxxxxxxxxxxxx@xxxxxxxxxxx
xxxxxx1xxxxxxxxxxxxx xxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxx xxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxx xxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxx xxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxx xxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxx xxxxxxxxxxx
xxxxxxxxxx           xxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxx xxxxxxxxxxxx
xxxxxxxxxxxxxxxxx x x xxxxxxxxxx
xxxxxxxxxxxxxxxxxxxx xxxxxxxxxxx
xxxxxxxxxxxxxx xxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxx xxx xx3xxxxxxxxxx
xxxxxxxxxxxxxxxxxxx xxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxxxxx  x
xxxxxxxxxxxxxxxxxxxxxxxxxxx   xx
xxxxxxxxxxxxxxxxxxxxxxxxx      2
xxxxxxxxxxxxxxxxxxxxxxx
</code>```

The legend is as follows:

x: solid block

 : empty air

@: your bot

1,2,3,4,5,6,7,8,9,0: other bots

Your bot should output your move as a pair of integers. Example: -1, 2 will move 1 block to the left and 2 blocks down (coordinates origin is in the top left corner).

You may move up to four blocks, manhattan distance, from your current location. If you try to move further than that, the move is invalid. Any move that would move you past the edge will put you on the edge instead. Invalid moves will be ignored.

Once you land on a block it is removed; if you remain on the same block next turn you will fall. Two bots may land on the same block on the same turn and both survive; if this happens, both bots will only see themselves and not the other bot.

If you need to store files for persistence, please do so in a folder with the name of your bot. You may not read other bots' persistent data if any exists.

The match controller is available at https://paste.ee/p/Xf65d.

Please use languages that can be run on a standard Linux or OSX install.

Current results (100 rounds):

```<code>JumpBot                   31
LookBot                   27
ShyBot                    26
Slow Bot                  15
KnightBot                 2
Moat Builder              0
UpBot                     0
Random Bot                0
</code>```

答:
JumpBot (C)

Try to jump to field with most possible moves in next round.

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

typedef struct map {
     char *raw_map;
     int size;
     int lines;
     char *pos;
} *MAP;

typedef struct cdata {
     int result;
     MAP m;
     int x;
     int y;
} *CDATA;

typedef struct mdata {
     int x;
     int y;
     int moves;
     int bx;
     int by;
     MAP m;
} *MDATA;

int numberOfMoves(MAP, int, int);
char getAt(MAP, int, int);

int abs(int x)
{
    return x < 0 ? x*-1 : x;
}

void count(void *data, int x, int y)
{
    CDATA d = (CDATA)data;
    char c = getAt(d->m, d->x + x, d->y + y);
    if(c != 'x') return;
    d->result++;
}

void choose(void *data, int x, int y)
{
    MDATA m = (MDATA)data;
    char c = getAt(m->m, m->x + x, m->y + y);
    if(c != 'x') return;
    int moves = numberOfMoves(m->m, m->x+x, m->y+y);
    if(moves > m->moves || (!m->bx && !m->by)) {
        m->moves = moves;
        m->bx = x;
        m->by = y;
    }
}

MAP parse_input(char *input)
{
    MAP m = malloc(sizeof *m);
    if(!m) {
        fprintf(stderr, "failed to alloc map\n");
        return NULL;
    }

    m->size=0;
    m->lines=1;
    m->pos=0;

    char *temp;
    for(temp = input;*temp;temp++) {
        switch(*temp) {
            case '\n': m->lines++; break;
            default: break;
        }
    }
    m->size = (temp + 1) - (input + m->lines);
    m->raw_map = malloc(m->size);
    if(!m->raw_map) {
        fprintf(stderr, "failed to alloc raw_map\n");
        return NULL;
    }

    int index = 0;
    for(temp = input; *temp; temp++) {
        if(*temp == '@') m->pos = m->raw_map + index;
        if(*temp != '\n') m->raw_map[index++] = *temp;
    }

    return m;
}

char getAt(MAP m, int x, int y)
{
    return m->raw_map[x + y*(m->size / m->lines)];
}

void posToXY(MAP m, int *x, int *y)
{
    int index = m->pos - m->raw_map;
    int length = m->size / m->lines;
    *x = index % length;
    *y = index / length;
}

typedef void (*DOFUNC)(void *, int, int);
void processMoves(MAP m, int x, int y, DOFUNC proc, void *data)
{
    int length = m->size / m->lines;
    int left = x>=4 ? 4 : x;
    int right = x + 4 <= length ? 4 : length - (x + 1);
    int up = y >= 4 ? 4 : y;
    int down = y + 4 <= m->lines ? 4 : m->lines - (y + 1);

    for(int i=-left; i<=right; i++) {
        for(int j=-up; j<=down; j++) {
            if((abs(i) + abs(j) <= 4) && (i || j)) (*proc)(data, i, j);
        }
    }
}

int numberOfMoves(MAP m, int x, int y)
{
    struct cdata d;
    d.result = 0;
    d.x = x;
    d.y = y;
    d.m = m;
    processMoves(m, x, y, &count, &d);
    return d.result;
}

void getMove(MAP m, int *x, int *y)
{
    struct mdata d;
    posToXY(m, &d.x, &d.y);
    d.moves = 0;
    d.bx = 0;
    d.by = 0;
    d.m = m;
    processMoves(m, d.x, d.y, &choose, &d);
    *x = d.bx;
    *y = d.by;
}

int main(int argc, char *argv[])
{
    if(argc != 2) {
        fprintf(stderr, "bad number of arguments %d\n", argc);
        return -1;
    }

    MAP m = parse_input(argv[1]);
    int x=0, y=0;
    getMove(m, &x, &y);
    printf("%d %d\n", x, y);
    return 0;
}
</code>```

Title: KOTH: TNT Run Challenge

Body:
JumpBot (C)

Try to jump to field with most possible moves in next round.

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

typedef struct map {
     char *raw_map;
     int size;
     int lines;
     char *pos;
} *MAP;

typedef struct cdata {
     int result;
     MAP m;
     int x;
     int y;
} *CDATA;

typedef struct mdata {
     int x;
     int y;
     int moves;
     int bx;
     int by;
     MAP m;
} *MDATA;

int numberOfMoves(MAP, int, int);
char getAt(MAP, int, int);

int abs(int x)
{
    return x < 0 ? x*-1 : x;
}

void count(void *data, int x, int y)
{
    CDATA d = (CDATA)data;
    char c = getAt(d->m, d->x + x, d->y + y);
    if(c != 'x') return;
    d->result++;
}

void choose(void *data, int x, int y)
{
    MDATA m = (MDATA)data;
    char c = getAt(m->m, m->x + x, m->y + y);
    if(c != 'x') return;
    int moves = numberOfMoves(m->m, m->x+x, m->y+y);
    if(moves > m->moves || (!m->bx && !m->by)) {
        m->moves = moves;
        m->bx = x;
        m->by = y;
    }
}

MAP parse_input(char *input)
{
    MAP m = malloc(sizeof *m);
    if(!m) {
        fprintf(stderr, "failed to alloc map\n");
        return NULL;
    }

    m->size=0;
    m->lines=1;
    m->pos=0;

    char *temp;
    for(temp = input;*temp;temp++) {
        switch(*temp) {
            case '\n': m->lines++; break;
            default: break;
        }
    }
    m->size = (temp + 1) - (input + m->lines);
    m->raw_map = malloc(m->size);
    if(!m->raw_map) {
        fprintf(stderr, "failed to alloc raw_map\n");
        return NULL;
    }

    int index = 0;
    for(temp = input; *temp; temp++) {
        if(*temp == '@') m->pos = m->raw_map + index;
        if(*temp != '\n') m->raw_map[index++] = *temp;
    }

    return m;
}

char getAt(MAP m, int x, int y)
{
    return m->raw_map[x + y*(m->size / m->lines)];
}

void posToXY(MAP m, int *x, int *y)
{
    int index = m->pos - m->raw_map;
    int length = m->size / m->lines;
    *x = index % length;
    *y = index / length;
}

typedef void (*DOFUNC)(void *, int, int);
void processMoves(MAP m, int x, int y, DOFUNC proc, void *data)
{
    int length = m->size / m->lines;
    int left = x>=4 ? 4 : x;
    int right = x + 4 <= length ? 4 : length - (x + 1);
    int up = y >= 4 ? 4 : y;
    int down = y + 4 <= m->lines ? 4 : m->lines - (y + 1);

    for(int i=-left; i<=right; i++) {
        for(int j=-up; j<=down; j++) {
            if((abs(i) + abs(j) <= 4) && (i || j)) (*proc)(data, i, j);
        }
    }
}

int numberOfMoves(MAP m, int x, int y)
{
    struct cdata d;
    d.result = 0;
    d.x = x;
    d.y = y;
    d.m = m;
    processMoves(m, x, y, &count, &d);
    return d.result;
}

void getMove(MAP m, int *x, int *y)
{
    struct mdata d;
    posToXY(m, &d.x, &d.y);
    d.moves = 0;
    d.bx = 0;
    d.by = 0;
    d.m = m;
    processMoves(m, d.x, d.y, &choose, &d);
    *x = d.bx;
    *y = d.by;
}

int main(int argc, char *argv[])
{
    if(argc != 2) {
        fprintf(stderr, "bad number of arguments %d\n", argc);
        return -1;
    }

    MAP m = parse_input(argv[1]);
    int x=0, y=0;
    getMove(m, &x, &y);
    printf("%d %d\n", x, y);
    return 0;
}


答:
Java, 94 bytes

int c(int[]d){int p=1,r=0,l=d.length,i=0;for(;i<l;p*=10)r+=(d[l-++i]/p%10==1?2:1)*p;return r;}
```

<p>Pure numeric operations for the win! :)</p>

<h3>Sample input/output:</h3>

<pre class="lang-java prettyprint-override"><code>8            <-- size
12345678     <-- start of list
23456789
34567890
45678901
56789012
67890123
78901234
89012345     <-- end of list
21111211     <-- result from ungolfed code
21111211     <-- result from golfed code
</code>```

Full program (with ungolfed code):

import java.util.Scanner;

public class Q79444 {
    int cantor_ungolfed(int[] data){
        int power = 1;
        int result = 0;
        for(int i=0;i<data.length;i++){
            result += (((data[data.length-i-1]/power))%10==1? 2 : 1)*power;
            power *= 10;
        }
        return result;
    }
    int c(int[]d){int p=1,r=0,l=d.length,i=0;for(;i<l;p*=10)r+=(d[l-++i]/p%10==1?2:1)*p;return r;}
    public static void main(String args[]){
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int[] input = new int[n];
        for(int i=0;i<n;i++){
            input[i] = sc.nextInt();
        }
        System.out.println(new Q79444().cantor_ungolfed(input));
        System.out.println(new Q79444().c(input));
        sc.close();
    }
}
```

Title: Finite Cantor's Diagonal

Body:
Java, 94 bytes

int c(int[]d){int p=1,r=0,l=d.length,i=0;for(;i<l;p*=10)r+=(d[l-++i]/p%10==1?2:1)*p;return r;}

Pure numeric operations for the win! :)

Sample input/output:

8            <-- size
12345678     <-- start of list
23456789
34567890
45678901
56789012
67890123
78901234
89012345     <-- end of list
21111211     <-- result from ungolfed code
21111211     <-- result from golfed code

Full program (with ungolfed code):

import java.util.Scanner;

public class Q79444 {
    int cantor_ungolfed(int[] data){
        int power = 1;
        int result = 0;
        for(int i=0;i<data.length;i++){
            result += (((data[data.length-i-1]/power))%10==1? 2 : 1)*power;
            power *= 10;
        }
        return result;
    }
    int c(int[]d){int p=1,r=0,l=d.length,i=0;for(;i<l;p*=10)r+=(d[l-++i]/p%10==1?2:1)*p;return r;}
    public static void main(String args[]){
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int[] input = new int[n];
        for(int i=0;i<n;i++){
            input[i] = sc.nextInt();
        }
        System.out.println(new Q79444().cantor_ungolfed(input));
        System.out.println(new Q79444().c(input));
        sc.close();
    }
}


答:
Retina, 39 38 37

```<code>(?<=(.*¶)*)(?<-1>.)*(.).*¶
$2
T`d`121
</code>```

Saved 1 byte thanks Martin!

Requires a trailing linefeed in the input.

Gets diagonals and translates 0 and 2-9 to 1 and 1 to 2.

The basic idea for getting the diagonals is to push a capture for each row above the current row and then consume a capture to match a character, then keep the next character.

Try it online

Title: Finite Cantor's Diagonal

Body:
Retina, 39 38 37

(?<=(.*¶)*)(?<-1>.)*(.).*¶
$2
T`d`121

Saved 1 byte thanks Martin!

Requires a trailing linefeed in the input.

Gets diagonals and translates 0 and 2-9 to 1 and 1 to 2.

The basic idea for getting the diagonals is to push a capture for each row above the current row and then consume a capture to match a character, then keep the next character.

Try it online


Title: Finite Cantor's Diagonal

Body:
Java, 93 bytes

String k(int n,int[]a){String s="";for(int i=0;i<n;)s+=(a[i]+s).charAt(i++)<57?9:1;return s;}

Ungolfed

String k(int n, int[] a) {
    String s = "";
    for (int i = 0; i < n; )
        s += (a[i] + s).charAt(i++) < 57 ? 9 : 1;
    return s;
}

Output

Input:
12345678
23456789
34567890
45678901
56789012
67890123
78901234
89012345

Output:
99991999

Input:
1234
4815
1623
4211

Output:
9999


答:
Reng v.3.3, 60 bytes

```<code>k1-#kaiír1ø          ~; !nb$<
1[å{$}k*$k1-#k)9(-#oa$;]o)ks^$
</code>```

For Reng, that was rather simple. Try it here! Input is a space-separated list of numbers.

1: init

```<code>k1-#kaiír1ø
</code>```

k is the number of inputs (number of numbers), and we decrement by 1 and restore for the loop stage. aií takes all input. r reverses the stack for the processing of input. 1ø goes to the next line.

2: loop

```<code>1[å{$}k*$k1-#k)9(-#oa$;]o)ks^$
</code>```

1[ takes the top item off the stack and into a new stack. å splits it into digits. {$} pushes a code block containing the operation "drop"; this is repeated k times (k*) and the code block is dropped ($. k1-#k decrements k. )9( puts 9 at the STOS, and - subtracts TOS from the STOS. #o stores this number in o, and a$; drops all the members of the stack. ] closes the parent stack. o puts o back at the top; this is our digit we're saving. ) moves it to the bottom so that we can continue our looping. s usually checks for non-input (i.e., equality to -1), but we can use it to break out of our loop when k == -1. So s^ goes up when k == -1. $ drops k from the stack, and our loop begins again.

3: final

```<code>                     ~; !nb$<
</code>```

< directs the pointer left, and $ drops k from the stack. b is a leftway mirror, so we enter through it, but it bounce back when hitting ;, a stack-condition mirror. !n prints a digit if and only if we're going left. ~ ends the program when we're done printing.

Title: Finite Cantor's Diagonal

Body:
Reng v.3.3, 60 bytes

k1-#kaiír1ø          ~; !nb$<
1[å{$}k*$k1-#k)9(-#oa$;]o)ks^$

For Reng, that was rather simple. Try it here! Input is a space-separated list of numbers.

1: init

k1-#kaiír1ø

k is the number of inputs (number of numbers), and we decrement by 1 and restore for the loop stage. aií takes all input. r reverses the stack for the processing of input. 1ø goes to the next line.

2: loop

1[å{$}k*$k1-#k)9(-#oa$;]o)ks^$

1[ takes the top item off the stack and into a new stack. å splits it into digits. {$} pushes a code block containing the operation "drop"; this is repeated k times (k*) and the code block is dropped ($. k1-#k decrements k. )9( puts 9 at the STOS, and - subtracts TOS from the STOS. #o stores this number in o, and a$; drops all the members of the stack. ] closes the parent stack. o puts o back at the top; this is our digit we're saving. ) moves it to the bottom so that we can continue our looping. s usually checks for non-input (i.e., equality to -1), but we can use it to break out of our loop when k == -1. So s^ goes up when k == -1. $ drops k from the stack, and our loop begins again.

3: final

                     ~; !nb$<

< directs the pointer left, and $ drops k from the stack. b is a leftway mirror, so we enter through it, but it bounce back when hitting ;, a stack-condition mirror. !n prints a digit if and only if we're going left. ~ ends the program when we're done printing.


答:
Python 2, <s>47</s> 45 bytes

```<code>lambda x,n:int(`x`[1::n+3])%(10**n/2)+10**n/9
</code>```

Thanks to @xnor for golfing off 2 bytes!

Test it on Ideone.

How it works

`x` yields a string representation of the list x.

For the first test case, this gives the string

```<code>[92345678, 23456789, 34567890, 45678901, 56789012, 67890123, 78901234, 89012345]
</code>```

[1::n+3] retrieves every (n + 3)th character – where n is the length of x starting with the second one. Accounting 2 characters for ,, we retrieve the first digit of the first number, the second digit of the second number, etc.

```<code>[92345678, 23456789, 34567890, 45678901, 56789012, 67890123, 78901234, 89012345]
 ^          ^          ^          ^          ^          ^          ^          ^
</code>```

We now take the number modulo 10n ÷ 2 to map the first digit in the range [0, 4].

For 93579135, we get 93579135 % 50000000 = 43579135.

Finally, we add 10n ÷ 9 to the last result, which increments – wrapping around from 9 to 0 – all digits by 1 (no carry) or 2 (with carry).

For 43579135, we get 43579135 + 11111111 = 54690246.

Title: Finite Cantor's Diagonal

Body:
Python 2, <s>47</s> 45 bytes

lambda x,n:int(`x`[1::n+3])%(10**n/2)+10**n/9

Thanks to @xnor for golfing off 2 bytes!

Test it on Ideone.

How it works

`x` yields a string representation of the list x.

For the first test case, this gives the string

[92345678, 23456789, 34567890, 45678901, 56789012, 67890123, 78901234, 89012345]

[1::n+3] retrieves every (n + 3)th character – where n is the length of x starting with the second one. Accounting 2 characters for ,, we retrieve the first digit of the first number, the second digit of the second number, etc.

[92345678, 23456789, 34567890, 45678901, 56789012, 67890123, 78901234, 89012345]
 ^          ^          ^          ^          ^          ^          ^          ^

We now take the number modulo 10n ÷ 2 to map the first digit in the range [0, 4].

For 93579135, we get 93579135 % 50000000 = 43579135.

Finally, we add 10n ÷ 9 to the last result, which increments – wrapping around from 9 to 0 – all digits by 1 (no carry) or 2 (with carry).

For 43579135, we get 43579135 + 11111111 = 54690246.


问:
Transpose a page of text
EDIT I modified the wording of the rules to make some things which were implicit more explicit. I also added some emphasis to clear up some points of apparent confusion, and explicitly defined the option of making a standalone program instead of a function.

The goal here is to make a function that takes a text file (or string) and transposes it so that lines become columns and vice versa.

Example:

```
I am a text.
Transpose me.
Can you do it?
```

Results in:

```
ITC
 ra
aan
mn
 sy
apo
 ou
ts
eed
x o
tm
.ei
 .t
  ?
```

The rules:

You are allowed to assume that the only whitespace characters used are " " and "\n" and that there is no trailing whitespace on any line.

You may assume that the file is ASCII. Which endline marker you want to use is up to you.(CRLF or LF). It must work correctly on the example, but it should also work on any input that satisfies the above assumptions.

You might have to insert spaces (as in the example) where there were none in order to keep the columns in line.

Your result must not have trailing whitespace on any line.

The final newline character(for the last line) is optional.

It should be either a function or a complete program. If your function accepts a string, then it should return the results as a string. If it accepts a filename, then you return the name of the file where you saved the result. You are additionally allowed to write a complete program that accepts input from STDIN and outputs the correct result to STDOUT; if you do this, you must not output anything to STDERR.

Shortest procedure wins, but I will upvote any answer I like.

Based on the rules, the output on the example is either 53 or 52 bytes long (for LF newlines) depending on whether the final newline is included or not.

Note: It is not a specific requirement, but if your function, when run twice successively is not identical to the original(the final newline might be differ, and any empty lines at the end of the file will be deleted), then you are probably breaking one of the rules.

答:
JavaScript, <s>177</s> 173 bytes

```<code>s=>{l=s.split`
`.sort((a,b)=>b.length-a.length)[0];for(i=0,t=[];i<l.length;i++){t[i]=s.split`
`.map(i=>i+" ".repeat(l.length-i.length)).map(j=>j[i]).join``}return t.join`
`}
</code>```

<s>

```<code>s=>{l=s.split`\n`.sort((a,b)=>b.length-a.length)[0];for(i=0,t=[];i<l.length;i++){t[i]=s.split`\n`.map(i=>i+" ".repeat(l.length-i.length)).map(j=>j[i]).join``;}return t.join`\n`}
</code>```

</s>
If you can help me shorten this up, please do so.

Title: Transpose a page of text

Body:
JavaScript, <s>177</s> 173 bytes

s=>{l=s.split`
`.sort((a,b)=>b.length-a.length)[0];for(i=0,t=[];i<l.length;i++){t[i]=s.split`
`.map(i=>i+" ".repeat(l.length-i.length)).map(j=>j[i]).join``}return t.join`
`}

<s>

s=>{l=s.split`\n`.sort((a,b)=>b.length-a.length)[0];for(i=0,t=[];i<l.length;i++){t[i]=s.split`\n`.map(i=>i+" ".repeat(l.length-i.length)).map(j=>j[i]).join``;}return t.join`\n`}

</s>
If you can help me shorten this up, please do so.


答:
Mathematica 52 bytes

```<code>FromDigits[Mod[#,2]+1&/@Diagonal[IntegerDigits/@#]]&
</code>```

This follows the approach of Peter Taylor and others (without using Ascii codes).

Example

```<code>FromDigits[Mod[#,2]+1&/@Diagonal[IntegerDigits/@ #]]&[{1234,4815,1623,4211}]
</code>```

2112

Title: Finite Cantor's Diagonal

Body:
Mathematica 52 bytes

FromDigits[Mod[#,2]+1&/@Diagonal[IntegerDigits/@#]]&

This follows the approach of Peter Taylor and others (without using Ascii codes).

Example

FromDigits[Mod[#,2]+1&/@Diagonal[IntegerDigits/@ #]]&[{1234,4815,1623,4211}]

2112


问:
Matrix Trigonometry

Introduction

The two most common trigonometric functions, sine and cosine (or sin and cos for short), can be extended to be matrix-valued functions. One way to compute the matrix-valued analogs is as follows:

Consider these two important trigonometric identities:

Using these identities, we can derive the following equations for sin and cos:

The matrix exponential exists for all square matrices and is given by:

where A0 is the identity matrix I with the same dimensions as A. Using the matrix exponential, these two trigonometric functions (and thus all the other trigonometric functions) can be evaluated as functions of matrices.

The Challenge

Given a square matrix A, output the values of sin(A) and cos(A).

Rules

Input and output may be in any convenient, reasonable format (2D array, your language's matrix format, etc.).

You may write a single program, two independent programs, a single function, or two functions. If you choose to write two functions, code may be shared between them (such as imports and helper functions).

The input matrix's values will always be integers.

Your solution may have accuracy issues as the result of floating-point imprecision. If your language had magical infinite-precision values, then your solution should work perfectly (ignoring the fact that it would require infinite time and/or memory). However, since those magical infinite-precision values don't exist, inaccuracies caused by limited precision are acceptable. This rule is in place to avoid complications resulting from requiring a specific amount of precision in the output.

Builtins which compute trigonometric functions for matrix arguments (including hyperbolic trig functions) are not allowed. Other matrix builtins (such as multiplication, exponentiation, diagonalization, decomposition, and the matrix exponential) are allowed.

Test Cases

Format: A -> sin(A), cos(A)

```<code>[[0]] -> [[0]], [[1]]
[[0, 2], [3, 5]] -> [[-0.761177343863758, 0.160587281888277], [0.240880922832416, -0.359709139143065]], [[0.600283445979886, 0.119962280223493], [0.179943420335240, 0.900189146538619]]
[[1, 0, 1], [0, 0, 0], [0, 1, 0]] -> [[0.841470984807897, -0.158529015192103, 0.841470984807897], [0, 0, 0], [0, 1, 0]], [[0.540302305868140, -0.459697694131860, -0.459697694131860], [0, 1, 0], [0, 0, 1]]
[[1, 0, 0, 0, 0], [0, 1, 0, 0, 0], [0, 0, 1, 0, 0], [0, 0, 0, 1, 0], [0, 0, 0, 0, 1]] -> [[0.841470984807897, 0, 0, 0, 0], [0, 0.841470984807897, 0, 0, 0], [0, 0, 0.841470984807897, 0, 0], [0, 0, 0, 0.841470984807897, 0], [0, 0, 0, 0, 0.841470984807897]], [[0.540302305868140, 0, 0, 0, 0], [0, 0.540302305868140, 0, 0, 0], [0, 0, 0.540302305868140, 0, 0], [0, 0, 0, 0.540302305868140, 0], [0, 0, 0, 0, 0.540302305868140]]
[[-3, 2, -6], [3, 0, 4], [4, -2, 7]] -> [[-0.374786510963954, 0.135652884035570, -1.35191037980742], [1.14843105375406, 0.773644542790111, 1.21625749577185], [1.21625749577185, -0.135652884035570, 2.19338136461532]], [[4.13614256031450, -1.91289828483056, 5.50873853927692], [-2.63939111203107, 1.49675144828342, -3.59584025444636], [-3.59584025444636, 1.91289828483056, -4.96843623340878]]
</code>```

Further Reading

This excellent question over at Math.SE includes some alternate derivations of the matrix-valued analogs of trigonometric functions.

答:
Matlab, <s>138 121 52</s> 50 bytes

Since matrix exponentiation is allowed, (what I didnt notice first, d'oh) I do not need to define my helper funciton anymore, and the whole thing can be trivially solved:

```<code>A=input('')*i;a=expm(A);b=expm(-A);[(b-a)*i,a+b]/2
</code>```

The input should be a matrix e.g. [1,2;4,5] or alternatively [[1,2];[3,4]]

An unexpected thing (in hindsight not so unexpected) is that the cosine and sine matrix still satisfy

```<code>I = sin(A)^2+cos(A)^2
</code>```

Title: Matrix Trigonometry

Body:
Matlab, <s>138 121 52</s> 50 bytes

Since matrix exponentiation is allowed, (what I didnt notice first, d'oh) I do not need to define my helper funciton anymore, and the whole thing can be trivially solved:

A=input('')*i;a=expm(A);b=expm(-A);[(b-a)*i,a+b]/2

The input should be a matrix e.g. [1,2;4,5] or alternatively [[1,2];[3,4]]

An unexpected thing (in hindsight not so unexpected) is that the cosine and sine matrix still satisfy

I = sin(A)^2+cos(A)^2