问:
Columnar Transposition Cipher

Columnar Transposition Cipher

While I have plenty of programs I have written for more advanced ciphers, I just realised I don't actually have one for one of the simplest: Columnar Transposition. The cipher, in case you don't know, works as follows:

First, you take the key, and write it as numbers. The numbers are made by replacing the letter which comes first in the alphabet with 1, the letter that comes next 2 and so on, ignoring duplicates (the key GOAT would become 2314). These numbers are the headers of the columns.

```<code>2314
----
</code>```

Next, you write your message under the columns.

```<code>2314
----
Hell
o Wo
rld!
</code>```

Finally, rearrange the columns into the numerical order in which they would fall, and read the ciphertext across.

```<code>1234
----
lHel
Wo o
drl!
</code>```

Which will result in your encoded text: lHelWo odrl!

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.

There must be a free interpreter/compiler available for your language.

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

Your program must not write anything to STDERR.

Your program should take input as an argument or from STDIN (or the closest alternative in your language).

Standard loopholes are forbidden.

Requirements

Case must be preserved.

Your cipher should be 'irregular', that is, if there are any spaces left after you have written out your message, it is treated as if it were a normal space character.

Only encryption is required, decryption may come in a later challenge.

Input should be taken from STDIN with the key on the first line, and the plaintext on the second. If you are taking input as an argument, please specify how this is done for your language.

The key can be in any case.

Duplicates in the key should be ignored - that is, ABCDB would become ABCD. Duplicates also apply in any case.

Trailing whitespace is included.

Test Cases

```<code>CBABD, Duplicates are ignored. ==> puDlacit sea eriongr.de
bDaEc, Key can be in multicase! ==> yKce  aenbn mi tucliea s!
</code>```

Full example, with 'surplus space' rule.

```<code>ADCB
----
"Goo
d Mo
rnin
g!"
he c
alle
d.

ABCD
----
"ooG
dom
rnin
g "!
hc e
aell
d  .

Message: "ooGdom rning "!hc eaelld  .
</code>```

Scoring

code-golf is how we score this challenge!

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 = 79810; // 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

```

答:
MATL, 12 bytes

```<code>kune2M&SY)1e
</code>```

Try it online!

Explanation

The code works using rows instead of columns. This is totally equivalent and fits better with MATL's column-major indexing.

```<code>k     % Take first input (key) implicitly. Convert to lowercase
u     % Keep unique chars, stably
n     % Number of unique chars
e     % Take second input (message) implicitly. Reshape into char matrix
      % with the above number of rows, padding with zeros if needed
2M    % Push string with unique chars of key again
&S    % Sort and push the indices of the sorting
Y)    % Use as row indices into char matrix
1e    % Reshape into a row. Zeros are displayed as spaces
</code>```

Title: Columnar Transposition Cipher

Body:
MATL, 12 bytes

kune2M&SY)1e

Try it online!

Explanation

The code works using rows instead of columns. This is totally equivalent and fits better with MATL's column-major indexing.

k     % Take first input (key) implicitly. Convert to lowercase
u     % Keep unique chars, stably
n     % Number of unique chars
e     % Take second input (message) implicitly. Reshape into char matrix
      % with the above number of rows, padding with zeros if needed
2M    % Push string with unique chars of key again
&S    % Sort and push the indices of the sorting
Y)    % Use as row indices into char matrix
1e    % Reshape into a row. Zeros are displayed as spaces


问:
Universal Spooky Meme Translator

Introduction

Turns out, aliens love memes just as much as we do. Every alien race we've encountered so far has their own version of 2spooky4me (see the following question) and equivalent, though, with some variation. The inhabitants of planet CUTE1f can't handle a lot of spook, so their preferred spook is 1spooky2me, while skeletor7 memers love them some spook, so they tend to use 9spooky11me.

Challenge

Translating memes is hard work, so you've been tasked with writing a universal meme translator to help these guys access the memenet correctly. Your program will accept a meme and a transformation to apply to the digit sequences in that meme to make it appropriate for the inhabitants of a different planet.

Input

Your program will receive two string inputs:

The input meme (e.g. 2spooky4me). Matches [a-zA-Z0-9]+.

The transformation to apply to it (e.g. +1, to go from 2spooky4me to 3spooky5me). Matches [+\-*/^]\d+ (you must accept +, -, *, /, and ^ as operators, regardless of the native representation in your language).

Output

Your program must return a string output (printed to standard output or equivalent) with the given transformation applied to the digit sequences in the input meme. In a weird turn of events, it also turns out that all races encountered so far prefer integral memes over fractional ones, so these transformations should perform integer arithmetic (e.g. 1spooky1me /2 should result in 0spooky0me).

Examples

Standard arithmetic operations apply:

```<code>Input:  2spooky4me +1
Output: 3spooky5me

Input:  2spooky4me -1
Output: 1spooky3me

Input:  2spooky4me *15
Output: 30spooky60me

Input:  10spooky900me /5
Output: 2spooky180me
</code>```

Digit sequences are integral; integer truncation should occur in cases like this:

```<code>Input:  idontunderstandmemes3 /2
Output: idontunderstandmemes1
</code>```

Your input may not have any digit sequences:

```<code>Input:  notreallyafunnymeme *100
Output: notreallyafunnymeme
</code>```

You must support exponentiation, even if it is not a native operation in your language of choice:

```<code>Input:  2spooky4me ^3
Output: 8spooky64me
</code>```

There's no limit on string length of number of digit sequences in the string:

```<code>Input:  some1meme2sequences3can4be5really6long7 /2
Output: some0meme1sequences1can2be2really3long3
</code>```

Addendum

If your language supports arbitrary-precision integers as a language feature, you must use those. If it does not, you do not need to support arbitrary-precision integers. For example, you must use Integer in Haskell instead of Int because it's available as part of the language; in Java, you are not required to use BigInteger because it's a library feature, not a language feature.

```<code>Input:  2000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000spooky4me /2
Output: 1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000spooky2me
</code>```

This is code-golf, so standard loopholes are forbidden, and the shortest answer in bytes wins!

Leaderboard

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

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

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

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

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

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

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

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

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

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

Shortest Solution by Language

Language	User	Score

Leaderboard

	Author	Language	Size

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

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

```

答:
Bash + GNU coreutils, 144 Bytes

```<code>d=
u=$1,
for((i=0;i<${#u};i++)){ l=${u:i:1}
[[ "$l" =~ [0-9] ]]&&d=$d$l||{ [ -z $d ]||echo -n `bc<<<$d$2`&&{ [ $l != , ]&&echo -n $l; };d=; }
}
</code>```

This looks at the alteration between digits and non-digits, that's why a random invalid input character (comma) is appended to the input string. This comma is then ignored in the output. The convention of the OP follows exactly the syntax of bc which is used here to do the maths.

ContentLicense: CC BY-SA 3.0

Title: Universal Spooky Meme Translator

Body:
Bash + GNU coreutils, 144 Bytes

d=
u=$1,
for((i=0;i<${#u};i++)){ l=${u:i:1}
[[ "$l" =~ [0-9] ]]&&d=$d$l||{ [ -z $d ]||echo -n `bc<<<$d$2`&&{ [ $l != , ]&&echo -n $l; };d=; }
}

This looks at the alteration between digits and non-digits, that's why a random invalid input character (comma) is appended to the input string. This comma is then ignored in the output. The convention of the OP follows exactly the syntax of bc which is used here to do the maths.


答:
J, 53 bytes

```<code>(3 :',/|:((/:tolower~.>0{y){|:((-#~.>0{y),\(>1{y)))')
</code>```

Usage example: (3 :',/|:((/:tolower~.>0{y){|:((-#~.>0{y),\(>1{y)))') ('ADCB';'"Good Morning!" he called.') ==> "ooGdoM rning "!hc eaelld  .

I basically did exactly what the cipher does, no shortcuts. I had to transpose the matrix to deal with ranking the columns then transpose it back.

Try it Online! (make sure to type "j-bot: " without quotes then paste the code.)

Title: Columnar Transposition Cipher

Body:
Columnar Transposition Cipher

While I have plenty of programs I have written for more advanced ciphers, I just realised I don't actually have one for one of the simplest: Columnar Transposition. The cipher, in case you don't know, works as follows:

First, you take the key, and write it as numbers. The numbers are made by replacing the letter which comes first in the alphabet with 1, the letter that comes next 2 and so on, ignoring duplicates (the key GOAT would become 2314). These numbers are the headers of the columns.

```<code>2314
----
</code>```

Next, you write your message under the columns.

```<code>2314
----
Hell
o Wo
rld!
</code>```

Finally, rearrange the columns into the numerical order in which they would fall, and read the ciphertext across.

```<code>1234
----
lHel
Wo o
drl!
</code>```

Which will result in your encoded text: lHelWo odrl!

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.

There must be a free interpreter/compiler available for your language.

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

Your program must not write anything to STDERR.

Your program should take input as an argument or from STDIN (or the closest alternative in your language).

Standard loopholes are forbidden.

Requirements

Case must be preserved.

Your cipher should be 'irregular', that is, if there are any spaces left after you have written out your message, it is treated as if it were a normal space character.

Only encryption is required, decryption may come in a later challenge.

Input should be taken from STDIN with the key on the first line, and the plaintext on the second. If you are taking input as an argument, please specify how this is done for your language.

The key can be in any case.

Duplicates in the key should be ignored - that is, ABCDB would become ABCD. Duplicates also apply in any case.

Trailing whitespace is included.

Test Cases

```<code>CBABD, Duplicates are ignored. ==> puDlacit sea eriongr.de
bDaEc, Key can be in multicase! ==> yKce  aenbn mi tucliea s!
</code>```

Full example, with 'surplus space' rule.

```<code>ADCB
----
"Goo
d Mo
rnin
g!"
he c
alle
d.

ABCD
----
"ooG
dom
rnin
g "!
hc e
aell
d  .

Message: "ooGdom rning "!hc eaelld  .
</code>```

Scoring

code-golf is how we score this challenge!

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 = 79810; // 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:
J, 53 bytes

(3 :',/|:((/:tolower~.>0{y){|:((-#~.>0{y),\(>1{y)))')

Usage example: (3 :',/|:((/:tolower~.>0{y){|:((-#~.>0{y),\(>1{y)))') ('ADCB';'"Good Morning!" he called.') ==> "ooGdoM rning "!hc eaelld  .

I basically did exactly what the cipher does, no shortcuts. I had to transpose the matrix to deal with ranking the columns then transpose it back.

Try it Online! (make sure to type "j-bot: " without quotes then paste the code.)


问:
Fix my Basic Orthography

Fix my Basic Orthography

While I am excellent at following the English capitalisation rules when writing, when I am typing I have a habit a capitalising almost everything (as you will see from the titles of my challenges). I need a program to fix that, but because I use so many capitals, and capitals are big letters, your program must be as short as possible.

Requirements

Your program should take each word, and if it is the first alphanumeric set of characters after a full stop or the beginning of the input, capitalize the first letter. All the rest of the letters until the next full stop will be lowercase.  At the full stop, capitalize the first letter and continue.

Punctuation must be preserved.

In a sentence without a full stop at the end, that should be added.

Spaces, where missing, should be inserted. A space is 'missing' if there is nothing between a full stop and the character following it.

(Note for americanish speakers: full stop = period = .)

Test Cases

```<code>tHIS SenteNce HAS veRy bAd GrammAr. ==> This sentence has very bad grammar.

-----

PuncTuation must-be PReserved. ==> Punctuation must-be preserved.

-----

full StOps ShoulD Be inserted ==> Full stops should be inserted.

-----

MultiPLe sEntEnceS Are possible. thEY Are, yoU KNOW. ==> Multiple sentences are possible. They are, you know.

-----

spaces. are.inserted. ==> Spaces. Are. Inserted.
</code>```

Rules

Your program should take input as an argument or from STDIN (or the closest alternative in your language).

Standard loopholes are forbidden.

Scoring

When code-golf is the tag, it's the least bytes to win!

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

/* Configuration */

var QUESTION_ID = 79842; // 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©;
      });
      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

```

答:
Lua, <s>149</s> 141 bytes

```<code>u=function(l)return l:upper()end print(io.read():lower():gsub("%s+"," "):gsub("%.([^%s])",". %1"):gsub("^(%w)",u):gsub("(%.[^%w]*%w)",u).."")
</code>```

Lua lacks some common features of regular expressions, and so it had to get a little sloppier than I would have liked. I might try to fix it up later though.

Title: Fix my Basic Orthography

Body:
Lua, <s>149</s> 141 bytes

u=function(l)return l:upper()end print(io.read():lower():gsub("%s+"," "):gsub("%.([^%s])",". %1"):gsub("^(%w)",u):gsub("(%.[^%w]*%w)",u).."")

Lua lacks some common features of regular expressions, and so it had to get a little sloppier than I would have liked. I might try to fix it up later though.


答:
Jolf, <s>15</s> 14 bytes

```<code>ρi«\d+»dC!6+HI
</code>```

Try it here!

Explanation

```<code>ρi«\d+»dC!6+HI
ρ «\d+»         replace all digits
 i              in the input
       d        (functional replace)
         !6     eval (using jolf's custom infix eval)
           +H   the number as a string plus
             I  the second input
        C       floor the result (integer truncate)
</code>```

Fun to note, I updated Jolf after this challenge, adding some RegExp builtins. This could be <s>12</s> 11 bytes:

```<code>ρiLRdC!6+HI
</code>```

Title: Universal Spooky Meme Translator

Body:
Introduction

Turns out, aliens love memes just as much as we do. Every alien race we've encountered so far has their own version of 2spooky4me (see the following question) and equivalent, though, with some variation. The inhabitants of planet CUTE1f can't handle a lot of spook, so their preferred spook is 1spooky2me, while skeletor7 memers love them some spook, so they tend to use 9spooky11me.

Challenge

Translating memes is hard work, so you've been tasked with writing a universal meme translator to help these guys access the memenet correctly. Your program will accept a meme and a transformation to apply to the digit sequences in that meme to make it appropriate for the inhabitants of a different planet.

Input

Your program will receive two string inputs:

The input meme (e.g. 2spooky4me). Matches [a-zA-Z0-9]+.

The transformation to apply to it (e.g. +1, to go from 2spooky4me to 3spooky5me). Matches [+\-*/^]\d+ (you must accept +, -, *, /, and ^ as operators, regardless of the native representation in your language).

Output

Your program must return a string output (printed to standard output or equivalent) with the given transformation applied to the digit sequences in the input meme. In a weird turn of events, it also turns out that all races encountered so far prefer integral memes over fractional ones, so these transformations should perform integer arithmetic (e.g. 1spooky1me /2 should result in 0spooky0me).

Examples

Standard arithmetic operations apply:

```<code>Input:  2spooky4me +1
Output: 3spooky5me

Input:  2spooky4me -1
Output: 1spooky3me

Input:  2spooky4me *15
Output: 30spooky60me

Input:  10spooky900me /5
Output: 2spooky180me
</code>```

Digit sequences are integral; integer truncation should occur in cases like this:

```<code>Input:  idontunderstandmemes3 /2
Output: idontunderstandmemes1
</code>```

Your input may not have any digit sequences:

```<code>Input:  notreallyafunnymeme *100
Output: notreallyafunnymeme
</code>```

You must support exponentiation, even if it is not a native operation in your language of choice:

```<code>Input:  2spooky4me ^3
Output: 8spooky64me
</code>```

There's no limit on string length of number of digit sequences in the string:

```<code>Input:  some1meme2sequences3can4be5really6long7 /2
Output: some0meme1sequences1can2be2really3long3
</code>```

Addendum

If your language supports arbitrary-precision integers as a language feature, you must use those. If it does not, you do not need to support arbitrary-precision integers. For example, you must use Integer in Haskell instead of Int because it's available as part of the language; in Java, you are not required to use BigInteger because it's a library feature, not a language feature.

```<code>Input:  2000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000spooky4me /2
Output: 1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000spooky2me
</code>```

This is code-golf, so standard loopholes are forbidden, and the shortest answer in bytes wins!

Leaderboard

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

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

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

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

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

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

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

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

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

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

Shortest Solution by Language

Language	User	Score

Leaderboard

	Author	Language	Size

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

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

```

Body:
Jolf, <s>15</s> 14 bytes

ρi«\d+»dC!6+HI

Try it here!

Explanation

ρi«\d+»dC!6+HI
ρ «\d+»         replace all digits
 i              in the input
       d        (functional replace)
         !6     eval (using jolf's custom infix eval)
           +H   the number as a string plus
             I  the second input
        C       floor the result (integer truncate)

Fun to note, I updated Jolf after this challenge, adding some RegExp builtins. This could be <s>12</s> 11 bytes:

ρiLRdC!6+HI


问:
Zeroes at the end of a factorial
Write a program or function that finds the number of zeroes at the end of n! in base 10, where n is an input number (in any desired format).

It can be assumed that n is a positive integer, meaning that n! is also an integer. There are no zeroes after a decimal point in n!. Also, it can be assumed that your programming language can handle the value of n and n!.

Test cases

```<code>1
==> 0

5
==> 1

100
==> 24

666
==> 165

2016
==> 502

1234567891011121314151617181920
==> 308641972752780328537904295461
</code>```

This is code golf. Standard rules apply. The shortest code in bytes wins.

答:
CJam, 11

Efficient solution, similar to other answers.

Loop version:

```<code>ri{5/_}h]:+
</code>```

Try it online

Explanation:

```<code>ri      read the input and convert to integer
{…}h    do…while
  5/    divide by 5
  _     duplicate the last number
         the loop terminates when the number reaches 0
]:+     add all the numbers from the stack
</code>```

Recursive version:

```<code>ri0{5/_j+}j
</code>```

Try it online

Explanation:

```<code>ri       read the input and convert to integer
0{…}j    calculate with memoized recursion and initial value 0 for input 0
  5/     divide by 5
  _      duplicate the result
  j      calculate the number of zeros recursively for that number
  +      add the 2 results
</code>```

Title: Zeroes at the end of a factorial

Body:
CJam, 11

Efficient solution, similar to other answers.

Loop version:

ri{5/_}h]:+

Try it online

Explanation:

ri      read the input and convert to integer
{…}h    do…while
  5/    divide by 5
  _     duplicate the last number
         the loop terminates when the number reaches 0
]:+     add all the numbers from the stack

Recursive version:

ri0{5/_j+}j

Try it online

Explanation:

ri       read the input and convert to integer
0{…}j    calculate with memoized recursion and initial value 0 for input 0
  5/     divide by 5
  _      duplicate the result
  j      calculate the number of zeros recursively for that number
  +      add the 2 results


答:
Mornington Crescent, <s>1949 1909</s> 1873 bytes

```<code>Take Northern Line to Bank
Take Circle Line to Bank
Take District Line to Parsons Green
Take District Line to Cannon Street
Take Circle Line to Victoria
Take Victoria Line to Seven Sisters
Take Victoria Line to Victoria
Take Circle Line to Victoria
Take Circle Line to Bank
Take Circle Line to Hammersmith
Take District Line to Turnham Green
Take District Line to Hammersmith
Take District Line to Upminster
Take District Line to Hammersmith
Take District Line to Turnham Green
Take District Line to Bank
Take Circle Line to Hammersmith
Take Circle Line to Blackfriars
Take Circle Line to Hammersmith
Take Circle Line to Notting Hill Gate
Take Circle Line to Notting Hill Gate
Take Circle Line to Bank
Take Circle Line to Hammersmith
Take District Line to Upminster
Take District Line to Upney
Take District Line to Upminster
Take District Line to Upney
Take District Line to Upminster
Take District Line to Upney
Take District Line to Upminster
Take District Line to Bank
Take Circle Line to Blackfriars
Take District Line to Upminster
Take District Line to Temple
Take Circle Line to Hammersmith
Take Circle Line to Cannon Street
Take Circle Line to Bank
Take Circle Line to Blackfriars
Take Circle Line to Hammersmith
Take District Line to Upney
Take District Line to Cannon Street
Take District Line to Upney
Take District Line to Cannon Street
Take District Line to Upney
Take District Line to Blackfriars
Take Circle Line to Bank
Take District Line to Upminster
Take District Line to Upney
Take District Line to Upminster
Take District Line to Upney
Take District Line to Upminster
Take District Line to Upney
Take District Line to Bank
Take Circle Line to Bank
Take Northern Line to Angel
Take Northern Line to Bank
Take Circle Line to Bank
Take District Line to Upminster
Take District Line to Bank
Take Circle Line to Bank
Take Northern Line to Mornington Crescent
</code>```

Try it online!

-40 bytes thanks to NieDzejkob

-45 bytes thanks to Cloudy7

Title: Zeroes at the end of a factorial

Body:
Write a program or function that finds the number of zeroes at the end of n! in base 10, where n is an input number (in any desired format).

It can be assumed that n is a positive integer, meaning that n! is also an integer. There are no zeroes after a decimal point in n!. Also, it can be assumed that your programming language can handle the value of n and n!.

Test cases

```<code>1
==> 0

5
==> 1

100
==> 24

666
==> 165

2016
==> 502

1234567891011121314151617181920
==> 308641972752780328537904295461
</code>```

This is code golf. Standard rules apply. The shortest code in bytes wins.

Body:
Mornington Crescent, <s>1949 1909</s> 1873 bytes

Take Northern Line to Bank
Take Circle Line to Bank
Take District Line to Parsons Green
Take District Line to Cannon Street
Take Circle Line to Victoria
Take Victoria Line to Seven Sisters
Take Victoria Line to Victoria
Take Circle Line to Victoria
Take Circle Line to Bank
Take Circle Line to Hammersmith
Take District Line to Turnham Green
Take District Line to Hammersmith
Take District Line to Upminster
Take District Line to Hammersmith
Take District Line to Turnham Green
Take District Line to Bank
Take Circle Line to Hammersmith
Take Circle Line to Blackfriars
Take Circle Line to Hammersmith
Take Circle Line to Notting Hill Gate
Take Circle Line to Notting Hill Gate
Take Circle Line to Bank
Take Circle Line to Hammersmith
Take District Line to Upminster
Take District Line to Upney
Take District Line to Upminster
Take District Line to Upney
Take District Line to Upminster
Take District Line to Upney
Take District Line to Upminster
Take District Line to Bank
Take Circle Line to Blackfriars
Take District Line to Upminster
Take District Line to Temple
Take Circle Line to Hammersmith
Take Circle Line to Cannon Street
Take Circle Line to Bank
Take Circle Line to Blackfriars
Take Circle Line to Hammersmith
Take District Line to Upney
Take District Line to Cannon Street
Take District Line to Upney
Take District Line to Cannon Street
Take District Line to Upney
Take District Line to Blackfriars
Take Circle Line to Bank
Take District Line to Upminster
Take District Line to Upney
Take District Line to Upminster
Take District Line to Upney
Take District Line to Upminster
Take District Line to Upney
Take District Line to Bank
Take Circle Line to Bank
Take Northern Line to Angel
Take Northern Line to Bank
Take Circle Line to Bank
Take District Line to Upminster
Take District Line to Bank
Take Circle Line to Bank
Take Northern Line to Mornington Crescent

Try it online!

-40 bytes thanks to NieDzejkob

-45 bytes thanks to Cloudy7

ContentLicense: CC BY-SA 4.0


答:
PHP, 62 bytes

```<code>for($n=$z=0;++$n<=log(125,5);){$z+=floor(125/(5**$n));}echo$z;
</code>```
exploded view
```<code>for ($n=$z=0; ++$n<=log(125,5); ) {
  $z += floor( 125 / (5 ** $n) );
}
echo $z;
</code>```

The starting point for many of the answers here is that every 5th factor adds a single 0, since there are 2-3 even numbers that precede it, and you can only get a new 0 with both a factor of 2 and a factor of 5.

If we assumed this to be true, the answer is simple in PHP, in 23 bytes:

```<code>echo(floor(argv[0]/5));
</code>```

However, consider 25!.  24! has 4 0's in it (because of 5, 10, 15, and 20).  But 25 adds two 5's to the equation, meaning 25! has 6 0's in it.  So we have to account for 5^n as well.

Title: Zeroes at the end of a factorial

Body:
PHP, 62 bytes

for($n=$z=0;++$n<=log(125,5);){$z+=floor(125/(5**$n));}echo$z;

exploded view

for ($n=$z=0; ++$n<=log(125,5); ) {
  $z += floor( 125 / (5 ** $n) );
}
echo $z;

The starting point for many of the answers here is that every 5th factor adds a single 0, since there are 2-3 even numbers that precede it, and you can only get a new 0 with both a factor of 2 and a factor of 5.

If we assumed this to be true, the answer is simple in PHP, in 23 bytes:

echo(floor(argv[0]/5));

However, consider 25!.  24! has 4 0's in it (because of 5, 10, 15, and 20).  But 25 adds two 5's to the equation, meaning 25! has 6 0's in it.  So we have to account for 5^n as well.


答:
PowerShell (v4), <s>124</s> 120 bytes

# New 120 byte version:
$s,$a=$args;[regex]::Replace($s,'\d+',{($(if($a-ne($a=$a.Trim('^'))){
"$args*"*$a+1}else{"$args$a"})|iex)-replace'\..*'})

# Previous 124 byte version
$s,$a=$args;[regex]::Replace($s,'\d+',{if($a[0]-eq'^'){
[math]::pow("$args",$a.Trim('^'))}else{iex "$args$a-replace'\..*'"}})
```

<p>(the newlines are only here to avoid horizontal scrolling, they work when saved as one line).</p>

<p>Comments, and ungolfed version was requested:</p>

<pre class="lang-powershell prettyprint-override"><code>$meme, $instruction = $args

# Scriptblock which processes the numbers
# to be replaced. $args is the input number.
$replacement = {

    # Generates a string of the calculation, by:
    # Removing leading ^ character, if present.
    # ^3 -> 3,      +3 -> +3
    # See if it was present, and switch code paths.
    # (Can be one combined step in the golf)
    # Switch code paths for "raise to the power of",
    # or basic arithmetic.
    $trimmedInstruction = $instruction.Trim('^')
    $tmp = if ( $instruction -ne $trimmedInstruction ) {

        # String multiplication, changes
        # function input "45" and instruction "3" into
        # "45*45*45*+1". The "3" implicitly casts to [int]
        # the +1 is there to make the trailing * not crash.
        "$args*" * $instruction + 1

    } else {
        # Cobble the basic math together as a string
        # "45" and "+10" becomes
        # "45+10"
        "$args$instruction"
    }

    # eval() the generated string (e.g. "45+10" or "45*45*45*+1")
    $tmp = Invoke-Expression $tmp      # iex

    # Use a regex golf to replace trailing .23423
    # decimals in case of division with remainder.
    # Acts as [math]::floor(), harmless on other numbers.
    $tmp -replace'\..*'
}

# A regular expression replacement which picks out all
# the numbers (\d+) and runs them through the
# replacement function. Returns a string which
# ends up on stdout
[regex]::Replace($meme, '\d+', $replacement)
</code>```

.Net regex library can do a replace with a scriptblock that executes on the content of the match, and PowerShell casts types strings to numbers, and iex is like eval() in other languages. It just does "2spooky" "+3" -> eval("2+3")

Except... it can't handle ^ operator or any other convenient exponentiation like **, it can only use the [math]::Pow() library call so there's a big block to handle that branch.

The updated version steals an idea from @TimmyD and does string multiplication instead - "2*" * n which becomes "2*2*2*2*" and then adds +1 on the end to multiply by one instead of complaining about the trailing *.

Except... .Net does Banker's Rounding which rounds to the nearest even number by default, and 3/2 = 2 rather than 3/2 = 1. This challenge calls for truncation, and that means [math]::Truncate(). Instead, I save characters by using -replace to trim a decimal point and anything after it.

Test cases:

PS D:\> .\meme.ps1 2spooky4me +1
3spooky5me

PS D:\> .\meme.ps1 2spooky4me -1
1spooky3me

PS D:\> .\meme.ps1 2spooky4me *15
30spooky60me

PS D:\> .\meme.ps1 10spooky900me /5
2spooky180me

PS D:\> .\meme.ps1 idontunderstandememes3 /2
idontunderstandememes1

PS D:\> .\meme.ps1 "idontunderstandememes3" "/2"
idontunderstandememes1

PS D:\> .\meme.ps1 "notreallyafunnymeme" "*100"
notreallyafunnymeme

PS D:\> .\meme.ps1 "2spooky4me" "^3"
8spooky64me

PS D:\> .\meme.ps1 "some1meme2sequences3can4be5really6long7" "/2"
some0meme1sequences1can2be2really3long3

PS D:\> .\meme.ps1 2000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000spooky4me /2
1E+780spooky2me
```

NB. In the last test the numbers overflow into type [BigInteger] automatically, but they get rendered in scientific notation. Luckily, every known race able to communicate between the stars has enough scientific development to be able to process scientific notation without problem.

Title: Universal Spooky Meme Translator

Body:
PowerShell (v4), <s>124</s> 120 bytes

# New 120 byte version:
$s,$a=$args;[regex]::Replace($s,'\d+',{($(if($a-ne($a=$a.Trim('^'))){
"$args*"*$a+1}else{"$args$a"})|iex)-replace'\..*'})

# Previous 124 byte version
$s,$a=$args;[regex]::Replace($s,'\d+',{if($a[0]-eq'^'){
[math]::pow("$args",$a.Trim('^'))}else{iex "$args$a-replace'\..*'"}})

(the newlines are only here to avoid horizontal scrolling, they work when saved as one line).

Comments, and ungolfed version was requested:

$meme, $instruction = $args

# Scriptblock which processes the numbers
# to be replaced. $args is the input number.
$replacement = {

    # Generates a string of the calculation, by:
    # Removing leading ^ character, if present.
    # ^3 -> 3,      +3 -> +3
    # See if it was present, and switch code paths.
    # (Can be one combined step in the golf)
    # Switch code paths for "raise to the power of",
    # or basic arithmetic.
    $trimmedInstruction = $instruction.Trim('^')
    $tmp = if ( $instruction -ne $trimmedInstruction ) {

        # String multiplication, changes
        # function input "45" and instruction "3" into
        # "45*45*45*+1". The "3" implicitly casts to [int]
        # the +1 is there to make the trailing * not crash.
        "$args*" * $instruction + 1

    } else {
        # Cobble the basic math together as a string
        # "45" and "+10" becomes
        # "45+10"
        "$args$instruction"
    }

    # eval() the generated string (e.g. "45+10" or "45*45*45*+1")
    $tmp = Invoke-Expression $tmp      # iex

    # Use a regex golf to replace trailing .23423
    # decimals in case of division with remainder.
    # Acts as [math]::floor(), harmless on other numbers.
    $tmp -replace'\..*'
}

# A regular expression replacement which picks out all
# the numbers (\d+) and runs them through the
# replacement function. Returns a string which
# ends up on stdout
[regex]::Replace($meme, '\d+', $replacement)

.Net regex library can do a replace with a scriptblock that executes on the content of the match, and PowerShell casts types strings to numbers, and iex is like eval() in other languages. It just does "2spooky" "+3" -> eval("2+3")

Except... it can't handle ^ operator or any other convenient exponentiation like **, it can only use the [math]::Pow() library call so there's a big block to handle that branch.

The updated version steals an idea from @TimmyD and does string multiplication instead - "2*" * n which becomes "2*2*2*2*" and then adds +1 on the end to multiply by one instead of complaining about the trailing *.

Except... .Net does Banker's Rounding which rounds to the nearest even number by default, and 3/2 = 2 rather than 3/2 = 1. This challenge calls for truncation, and that means [math]::Truncate(). Instead, I save characters by using -replace to trim a decimal point and anything after it.

Test cases:

PS D:\> .\meme.ps1 2spooky4me +1
3spooky5me

PS D:\> .\meme.ps1 2spooky4me -1
1spooky3me

PS D:\> .\meme.ps1 2spooky4me *15
30spooky60me

PS D:\> .\meme.ps1 10spooky900me /5
2spooky180me

PS D:\> .\meme.ps1 idontunderstandememes3 /2
idontunderstandememes1

PS D:\> .\meme.ps1 "idontunderstandememes3" "/2"
idontunderstandememes1

PS D:\> .\meme.ps1 "notreallyafunnymeme" "*100"
notreallyafunnymeme

PS D:\> .\meme.ps1 "2spooky4me" "^3"
8spooky64me

PS D:\> .\meme.ps1 "some1meme2sequences3can4be5really6long7" "/2"
some0meme1sequences1can2be2really3long3

PS D:\> .\meme.ps1 2000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000spooky4me /2
1E+780spooky2me

NB. In the last test the numbers overflow into type [BigInteger] automatically, but they get rendered in scientific notation. Luckily, every known race able to communicate between the stars has enough scientific development to be able to process scientific notation without problem.


问:
Read n random lines from a potentially huge file
This challenge is about reading random lines from a potentially huge file without reading the whole file into memory.

Input

An integer n and the name of a text file.

Output

n lines of the text file chosen uniformly at random without replacement.

You can assume that n is in the range 1 to the number of lines in the file.

Be careful when sampling n numbers at random from the range that the answer you get is uniform. rand()%n in C is not uniform for example. Every outcome must be equally likely.

Rules and restrictions

Each line of the text file will have the same number of characters and that will be no more than 80.

Your code must not read any of the contents of text file except:

Those lines it outputs.

The first line to work out how many characters per line there are in the text file.

We can assume each character in the text file takes exactly one byte.

Line separators are assumed to be 1 byte long. Solutions may use 2 bytes long line separators only if they specify this need. You may also assume the last line is terminated by a line separator.

Your answer should be a complete program but you can specify the input in any way that is convenient.

Languages and libraries

You can use any language or library you like.

Notes

There was a concern about calculating the number of lines in the file. As nimi points out in the comments, you can infer this from the file size and the number of chars per line.

Motivation

In chat some people asked if this is really a "Do X without Y" question. I interpret this to ask if the restrictions are unusually artificial.

The task of randomly sampling lines from huge files is not uncommon and is in fact one I sometimes have to do. One way to do this is in bash:

shuf -n <num-lines>

This is however very slow for large files as it reads in the whole file.

答:
Python (141 bytes)

Keeps each line with equal probability, use with pipes too. It doesn't answer the skip ahead limitation of the question though...

Usage cat largefile | python randxlines.py 100 or python randxlines 100 < largefile (as @petercordes pointed out)

```<code>import random,sys
N=int(sys.argv[1])
x=['']*N
for c,L in enumerate(sys.stdin):
    t=random.randrange(c+1)
    if(t<N):x[t] = L
print("".join(x))
</code>```

Body:
Python (141 bytes)

Keeps each line with equal probability, use with pipes too. It doesn't answer the skip ahead limitation of the question though...

Usage cat largefile | python randxlines.py 100 or python randxlines 100 < largefile (as @petercordes pointed out)

import random,sys
N=int(sys.argv[1])
x=['']*N
for c,L in enumerate(sys.stdin):
    t=random.randrange(c+1)
    if(t<N):x[t] = L
print("".join(x))


问:
Implement the dog bash utility
dog is a command-line utility that takes in an arbitrary number of arguments,
the first of which is the text to be written and the others are arbitrarily many files.

The dog utility will split the text in equal portions over these files. If there is a remainder n, the first n files get an additional byte

dog is the opposite of cat, as such, forall x, the following should hold.

```<code>$> dog x a.txt b.txt ...
$> cat a.txt b.txt ...
x$>
</code>```

Where ... indicates arbitrarily many files.

An example (12 bytes, 3 files, can be split evenly):

```<code>$> ./dog.py "Dogs vs Cats" a.txt b.txt c.txt
$> cat a.txt
Dogs$> cat b.txt
 vs $> cat c.txt
Cats$> cat a.txt b.txt c.txt
Dogs vs Cats$>
</code>```

An example with remainder (13 bytes, 5 files, remainder 3):

```<code>9$>./dog.py "0123456789abc" a.txt b.txt c.txt d.txt e.txt
$> cat a.txt
012$> cat b.txt
345$> cat c.txt
678$> cat d.txt
9a$> cat e.txt
bc$> cat a.txt b.txt c.txt d.txt e.txt
0123456789abc$>
</code>```

答:
Ruby, <s>93</s> 87 bytes

Full program using command line arguments.

If I could use s.slice! to mutate the string, I'd do that instead of needing to use s[c..-1], but Ruby doesn't let you mutate the strings from argv without duplicating them first

```<code>s,*t=$*
d,r=s.size.divmod t.size
t.map{|e|open(e,?w)<<s[0,c=(0>r-=1)?d:d+1];s=s[c..-1]}
</code>```

Title: Implement the dog bash utility

Body:
Ruby, <s>93</s> 87 bytes

Full program using command line arguments.

If I could use s.slice! to mutate the string, I'd do that instead of needing to use s[c..-1], but Ruby doesn't let you mutate the strings from argv without duplicating them first

s,*t=$*
d,r=s.size.divmod t.size
t.map{|e|open(e,?w)<<s[0,c=(0>r-=1)?d:d+1];s=s[c..-1]}


问:
What is the most frequent word?

What is the most frequent word?

Given a sentence, your program must make its way through it, counting the frequencies of each word, then output the most used word. Because a sentence has no fixed length, and so can get very long, your code must be as short as possible.

Rules/Requirements

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.

There must be a free interpreter/compiler available for your language.

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

Your program must not write anything to STDERR.

Your program should take input from STDIN (or the closest alternative in your language).

Standard loopholes are forbidden.

Your program must be case-insensitive (tHe, The and the all contribute to the count of the).

If there is no most frequent word (see test case #3), your program should output nothing.

Definition of a 'word':

You get the list of words by splitting the input text on spaces. The input will never contain any other type of whitespace than plain spaces (in particular no newlines). However, the final words should only contain alphanumerics (a-z, A-Z, 0-9), hyphens (-) and apostrophes ('). You can make that so by removing all other characters or by replacing them by space before doing the word splitting. To remain compatible with previous versions of the rules, apostrophes are not required to be included.

Test Cases

```<code>The man walked down the road.
==> the

-----

Slowly, he ate the pie, savoring each delicious bite. He felt like he was truly happy.
==> he

-----

This sentence has no most frequent word.
==>

-----

"That's... that's... that is just terrible!" he said.
==> that's / thats

-----

The old-fashioned man ate an old-fashioned cake.
==> old-fashioned

-----

IPv6 looks great, much better than IPv4, except for the fact that IPv6 has longer addresses.
==> IPv6

-----

This sentence with words has at most two equal most frequent words.
==>
</code>```

Note: The third and seventh test cases have no output, you may choose either on the fourth.

Scoring

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

When the challenge finishes, the program with the least bytes (it's called code-golf), will win.

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 = 79576; // 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

```

答:
bash, <s>153</s> <s>146</s> <s>131</s> <s>154</s> <s>149</s> <s>137</s> bytes

```<code>declare -iA F
f(){ (((T=++F[$1])==M))&&I=;((T>M))&&M=$T&&I=$1;}
read L
L=${L,,}
L=${L//[^- a-z0-9]}
printf -vA "f %s;" $L
eval $A;echo $I
</code>```

Operation:

declare an associative array F of integers (declare -iA F)

f is a function that, given a word parameter $1, increments frequency count for this word (T=++F[$1]) and compares to max count so far (M).

If equal, the we have a tie so we will not consider this word to be most frequent (I=)

If greater than max count so far (M), then set max count so far to frequency count of this word so far (M=$T) and remember this word (I=$1)

End function f

Read a line (read L)
Make lowercase (L=${L,,})
Remove any character except a-z, 0-9, dash(-) and space (L=${L//[^- a-z0-9]})
Make a sequence of bash statements that calls f for each word (printf -vA "f %s;" $L). This is saved to variable A.
eval A and print result (eval $a;echo$I)

Output:

```<code>This quick brown fox jumps over this lazy dog.
-->this
This sentence with the words has at most two equal most frequent the words.
-->
The man walked down the road.
-->the
This sentence has no most frequent word.
-->
Slowly, he ate the pie, savoring each delicious bite. He felt like he was truly happy.
-->he
"That's... that's... that is just terrible!" he said.
-->thats
The old-fashioned man ate an old-fashioned cake.
-->old-fashioned
IPv6 looks great, much better than IPv4, except for the fact that IPv6 has longer addresses.
-->ipv6
</code>```

Bug: FIXED
I have a bug that is not revealed in these test cases.
If input is

```<code>This sentence with words has at most two equal most frequent words.
</code>```

then my code should output nothing.

<s>I have a fix but I seem to have hit a bash bug... I get very odd behaviour is M is not declared an integer: ++F[$1]==M (after a few repeated words) increments both F[$1] and M!!</s> - my mistake.

Title: What is the most frequent word?

Body:
bash, <s>153</s> <s>146</s> <s>131</s> <s>154</s> <s>149</s> <s>137</s> bytes

declare -iA F
f(){ (((T=++F[$1])==M))&&I=;((T>M))&&M=$T&&I=$1;}
read L
L=${L,,}
L=${L//[^- a-z0-9]}
printf -vA "f %s;" $L
eval $A;echo $I

Operation:

declare an associative array F of integers (declare -iA F)

f is a function that, given a word parameter $1, increments frequency count for this word (T=++F[$1]) and compares to max count so far (M).

If equal, the we have a tie so we will not consider this word to be most frequent (I=)

If greater than max count so far (M), then set max count so far to frequency count of this word so far (M=$T) and remember this word (I=$1)

End function f

Read a line (read L)
Make lowercase (L=${L,,})
Remove any character except a-z, 0-9, dash(-) and space (L=${L//[^- a-z0-9]})
Make a sequence of bash statements that calls f for each word (printf -vA "f %s;" $L). This is saved to variable A.
eval A and print result (eval $a;echo$I)

Output:

This quick brown fox jumps over this lazy dog.
-->this
This sentence with the words has at most two equal most frequent the words.
-->
The man walked down the road.
-->the
This sentence has no most frequent word.
-->
Slowly, he ate the pie, savoring each delicious bite. He felt like he was truly happy.
-->he
"That's... that's... that is just terrible!" he said.
-->thats
The old-fashioned man ate an old-fashioned cake.
-->old-fashioned
IPv6 looks great, much better than IPv4, except for the fact that IPv6 has longer addresses.
-->ipv6

Bug: FIXED
I have a bug that is not revealed in these test cases.
If input is

This sentence with words has at most two equal most frequent words.

then my code should output nothing.

<s>I have a fix but I seem to have hit a bash bug... I get very odd behaviour is M is not declared an integer: ++F[$1]==M (after a few repeated words) increments both F[$1] and M!!</s> - my mistake.


答:
Kotlin, <s>416</s> 413 Bytes

The lack of an eval() in Kotlin really upped that byte count...

```<code>fun main(a:Array<String>){var r=Regex("\\d+");var i=a[0];var n=a[1].takeLast(a[1].length-1).toInt();when(a[1][0]){'+'->print(r.replace(i,{m->""+(m.value.toInt()+n)}));'*'->print(r.replace(i,{m->""+(m.value.toInt()*n)}));'/'->print(r.replace(i,{m->""+(m.value.toInt()/n)}));'-'->print(r.replace(i,{m->""+(m.value.toInt()-n)}));'^'->print(r.replace(i,{m->""+(Math.pow(m.value.toDouble(),n.toDouble())).toInt()}));}}
</code>```

Try it Online!

Ungolfed

```<code>fun main(a: Array<String>) {
    var r = Regex("""\d+""")
    var i = a[0]
    var n = a[1].takeLast(a[1].length - 1).toInt()
    when (a[1][0]) {
        '+' -> print(r.replace(i, { m -> "" + (m.value.toInt() + n) }))
        '*' -> print(r.replace(i, { m -> "" + (m.value.toInt() * n) }))
        '/' -> print(r.replace(i, { m -> "" + (m.value.toInt() / n) }))
        '-' -> print(r.replace(i, { m -> "" + (m.value.toInt() - n) }))
        '^' -> print(r.replace(i, { m -> "" + (Math.pow(m.value.toDouble(), n.toDouble())).toInt() }))
    }
}
</code>```

Title: Universal Spooky Meme Translator

Body:
Kotlin, <s>416</s> 413 Bytes

The lack of an eval() in Kotlin really upped that byte count...

fun main(a:Array<String>){var r=Regex("\\d+");var i=a[0];var n=a[1].takeLast(a[1].length-1).toInt();when(a[1][0]){'+'->print(r.replace(i,{m->""+(m.value.toInt()+n)}));'*'->print(r.replace(i,{m->""+(m.value.toInt()*n)}));'/'->print(r.replace(i,{m->""+(m.value.toInt()/n)}));'-'->print(r.replace(i,{m->""+(m.value.toInt()-n)}));'^'->print(r.replace(i,{m->""+(Math.pow(m.value.toDouble(),n.toDouble())).toInt()}));}}

Try it Online!

Ungolfed

fun main(a: Array<String>) {
    var r = Regex("""\d+""")
    var i = a[0]
    var n = a[1].takeLast(a[1].length - 1).toInt()
    when (a[1][0]) {
        '+' -> print(r.replace(i, { m -> "" + (m.value.toInt() + n) }))
        '*' -> print(r.replace(i, { m -> "" + (m.value.toInt() * n) }))
        '/' -> print(r.replace(i, { m -> "" + (m.value.toInt() / n) }))
        '-' -> print(r.replace(i, { m -> "" + (m.value.toInt() - n) }))
        '^' -> print(r.replace(i, { m -> "" + (Math.pow(m.value.toDouble(), n.toDouble())).toInt() }))
    }
}


问:
Calculate the Trump Tax
If elected president, Donald Trump plans to implement a system of four income tax brackets (full details can be found on his website here). Your job is to take two inputs, annual income and filing status (single, married, or head of household), and output the income tax that must be paid.

Income Tax Brackets

(We are only interested in the income tax rate; you can ignore the long-term capital gain rate).

Note that income taxes are computed using marginal rates — that is, you only pay the bracket rate for the portion that exceeds the bracket's minimum amount.

For example, a single filer making $45,000 a year would pay 0% on the first $25,000, and 10% on the $20,000 after that, for a total of $2,000 in taxes.

A married couple filing jointly for $500,000 would count 25% only on the amount exceeding $300,000, and add $45,000 to that to account for the income earned in lower brackets (which is 10% of $50,000 plus 20% of $200,000).

Input/Output

Input/Output is flexible. You can take input as command-line arguments or prompt for inputs, as well as either return or output/display the result. The inputs and output must be numbers, but you are free to determine what the second number would be (for example, 0 = single, 1 = married, 2 = head of household). Just don't be ridiculous - Single digit numbers only.

Also, functionality for decimal inputs (i.e. including cents) is undefined, so you only have to worry about integer inputs. For your output, you may either output a decimal value or round it to the nearest whole number.

Test Cases

Although the second number's range can be flexible as stated above, these test cases assume that 0 = single, 1 = married, and 2 = head of household:

```<code>25000  0 --> 0
37501  2 --> 0.1 or 0
51346  1 --> 134.6 or 135
75000  0 --> 7500
75000  1 --> 2500
123456 2 --> 13441.2 or 13441
424242 0 --> 91060.5 or 91061
</code>```

Title: Calculate the Trump Tax

Body:
Pyth, 32 bytes

*c@_j270588 6shS,6ca0tQ*12500E20

Test suite.

2 = single

4 = married

3 = head of household

Some ridiculous encodings:

Previous 6-byte:

JQ.vCE

<a href="http://pyth.herokuapp.com/?code=JQ.vCE&test_suite=1&test_suite_input=0%0A74892585093965377905208487730659359537614936740881725652453863997600444976%0A%0A25000%0A74892585093965377905208487730659359537614936740881725652453863997600444976%0A%0A37501%0A74892585093965377905208487730659359537614936740881725652526490039149933104%0A%0A51346%0A74892585093965377905208487730659359537614936740881725652668629404830675504%0A%0A75000%0A74892585093965377905208487730659359537614936740881725652453863997600444976%0A%0A75000%0A74892585093965377905208487730659359537614936740881725652668629404830675504%0A%0A123456%0A74892585093965377905208487730659359537614936740881725652526490039149933104%0A%0A424242%0A74892585093965377905208487730659359537614936740881725652453863997600444976%0A&debug=0&input_size=3" rel="nofollow noreferrer">Test suite.

74892585093965377905208487730659359537614936740881725652453863997600444976 = single

74892585093965377905208487730659359537614936740881725652668629404830675504 = married

74892585093965377905208487730659359537614936740881725652526490039149933104 = head of household

Encodes the whole program into the second number.

Previous 24-byte:

JjE^T6*c@tJhS,7shctQhJ20

<a href="http://pyth.herokuapp.com/?code=JjE%5ET6*c%40tJhS%2C7shctQhJ20&test_suite=1&test_suite_input=0%0A25000000000000000000002000004000004000004000004000005%0A%0A25000%0A25000000000000000000002000004000004000004000004000005%0A%0A37501%0A37500000000000000000002000004000004000004000004000005%0A%0A51346%0A50000000000000000000002000004000004000004000004000005%0A%0A75000%0A25000000000000000000002000004000004000004000004000005%0A%0A75000%0A50000000000000000000002000004000004000004000004000005%0A%0A123456%0A37500000000000000000002000004000004000004000004000005%0A%0A424242%0A25000000000000000000002000004000004000004000004000005%0A&debug=0&input_size=3" rel="nofollow noreferrer">Test suite.

25000000000000000000002000004000004000004000004000005 = single

50000000000000000000002000004000004000004000004000005 = married

37500000000000000000002000004000004000004000004000005 = head of household

Previous 26-byte:

*c@_j270588 6shS,6ca0tQE20

Test suite.

25000 = single

50000 = married

37500 = head of household


答:
TI-Basic, 34 32 bytes

Variable F is filing status where 2 = single, 3 = head of household, and 4 = married. Also, E is the scientific E.

```<code>Prompt I,F:4I/F>E5{.5,1,3:.1Isum(Ans{1,1,.5
</code>```

Explanation:

```<code>Prompt I,F          get input into I and F
4I/F               converts the income so it fits the married tax bracket
    >E5{.5,1,3     gives a list like {0 0 0}, {1 0 0}, {1 1 0}, or {1 1 1} based on bracket
   sum(Ans{1,1,.5  Multiplies previous list by {1 1 .5} and sums it
.1I                Previous number is 0 1 2 or 2.5, so multiply by .1 and then by income
</code>```

Title: Calculate the Trump Tax

Body:
If elected president, Donald Trump plans to implement a system of four income tax brackets (full details can be found on his website here). Your job is to take two inputs, annual income and filing status (single, married, or head of household), and output the income tax that must be paid.

Income Tax Brackets

(We are only interested in the income tax rate; you can ignore the long-term capital gain rate).

Note that income taxes are computed using marginal rates — that is, you only pay the bracket rate for the portion that exceeds the bracket's minimum amount.

For example, a single filer making $45,000 a year would pay 0% on the first $25,000, and 10% on the $20,000 after that, for a total of $2,000 in taxes.

A married couple filing jointly for $500,000 would count 25% only on the amount exceeding $300,000, and add $45,000 to that to account for the income earned in lower brackets (which is 10% of $50,000 plus 20% of $200,000).

Input/Output

Input/Output is flexible. You can take input as command-line arguments or prompt for inputs, as well as either return or output/display the result. The inputs and output must be numbers, but you are free to determine what the second number would be (for example, 0 = single, 1 = married, 2 = head of household). Just don't be ridiculous - Single digit numbers only.

Also, functionality for decimal inputs (i.e. including cents) is undefined, so you only have to worry about integer inputs. For your output, you may either output a decimal value or round it to the nearest whole number.

Test Cases

Although the second number's range can be flexible as stated above, these test cases assume that 0 = single, 1 = married, and 2 = head of household:

```<code>25000  0 --> 0
37501  2 --> 0.1 or 0
51346  1 --> 134.6 or 135
75000  0 --> 7500
75000  1 --> 2500
123456 2 --> 13441.2 or 13441
424242 0 --> 91060.5 or 91061
</code>```

Body:
TI-Basic, 34 32 bytes

Variable F is filing status where 2 = single, 3 = head of household, and 4 = married. Also, E is the scientific E.

Prompt I,F:4I/F>E5{.5,1,3:.1Isum(Ans{1,1,.5

Explanation:

Prompt I,F          get input into I and F
4I/F               converts the income so it fits the married tax bracket
    >E5{.5,1,3     gives a list like {0 0 0}, {1 0 0}, {1 1 0}, or {1 1 1} based on bracket
   sum(Ans{1,1,.5  Multiplies previous list by {1 1 .5} and sums it
.1I                Previous number is 0 1 2 or 2.5, so multiply by .1 and then by income


问:
Tips for golfing in PowerShell
What general tips do you have for golfing in Windows PowerShell? I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to PowerShell (e.g. "remove comments" is not an answer). Please post one tip per answer.

—taken nearly verbatim from marcog's question.

答:
Converting floating-point numbers to integers in PowerShell is a bit of a minefield. By default the conversion does Bankers Rounding which doesn't always trim off the decimal and leave the smaller whole number, or always round .5 up to the next number like people do casually, it rounds evens one way and odds another way - this can be surprising, e.g.

```<code>PS C:\> [int]1.5
2

PS C:\> [int]2.5
2
</code>```

and break codegolf calculations. Many other common languages do truncation-rounding, therefore golf questions often require truncation. You might reach for [Math]::Floor() as the next best thing, but beware this only behaves the same as truncation for positive numbers, but it takes negative numbers lower - further away from zero. [Math]::Truncate() is what you need to bring PS behaviour in line with other language's default rounding, but it's a lot of characters.

Regex replacing digits after the decimal point can help save a couple of characters:

```<code>[Math]::Truncate(1.5)
[Math]::Floor(1.5)
1.5-replace'\..*'

[Math]::Truncate($a)
[Math]::Floor($a)
$a-replace'\..*'
$a.split('.')[0]        # literal character split, not regex pattern split
</code>```

Title: Tips for golfing in PowerShell

Body:
Converting floating-point numbers to integers in PowerShell is a bit of a minefield. By default the conversion does Bankers Rounding which doesn't always trim off the decimal and leave the smaller whole number, or always round .5 up to the next number like people do casually, it rounds evens one way and odds another way - this can be surprising, e.g.

PS C:\> [int]1.5
2

PS C:\> [int]2.5
2

and break codegolf calculations. Many other common languages do truncation-rounding, therefore golf questions often require truncation. You might reach for [Math]::Floor() as the next best thing, but beware this only behaves the same as truncation for positive numbers, but it takes negative numbers lower - further away from zero. [Math]::Truncate() is what you need to bring PS behaviour in line with other language's default rounding, but it's a lot of characters.

Regex replacing digits after the decimal point can help save a couple of characters:

[Math]::Truncate(1.5)
[Math]::Floor(1.5)
1.5-replace'\..*'

[Math]::Truncate($a)
[Math]::Floor($a)
$a-replace'\..*'
$a.split('.')[0]        # literal character split, not regex pattern split


答:
Fake ternary operator. You can assign straight from an if statement:

```<code>$z=if($x-eq$y){"truth"}else{"false"}
</code>```

But you can use a 2-element array and use the test to index into it. $falsey results get element 0, $truthy results take element 1:

```<code>$z=("false","true")[$x-eq$y]
</code>```

NB. that this is really doing array indexing, and if the test results in a value which can be cast to an integer, you'll ask for an item outside the bounds of the array and get $null back, and will need to do !(test) to force cast the result to a bool, with the options reversed.

[ Edit: There's a genuine ternary operator in PowerShell 7+ in the C-language-style cond ? 1 : 0 ]

Title: Tips for golfing in PowerShell

Body:
What general tips do you have for golfing in Windows PowerShell? I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to PowerShell (e.g. "remove comments" is not an answer). Please post one tip per answer.

—taken nearly verbatim from marcog's question.

Body:
Fake ternary operator. You can assign straight from an if statement:

$z=if($x-eq$y){"truth"}else{"false"}

But you can use a 2-element array and use the test to index into it. $falsey results get element 0, $truthy results take element 1:

$z=("false","true")[$x-eq$y]

NB. that this is really doing array indexing, and if the test results in a value which can be cast to an integer, you'll ask for an item outside the bounds of the array and get $null back, and will need to do !(test) to force cast the result to a bool, with the options reversed.

[ Edit: There's a genuine ternary operator in PowerShell 7+ in the C-language-style cond ? 1 : 0 ]


问:
Shortest code for infinite disk I/O
(Just open 50 tabs in Google Chrome :D (just kidding, no you can't))

Shortest code for infinite disk I/O any language, C# example:

using System.IO;

namespace FileApp {
    static class Program {
        public static void Main() {
            do {
                File.WriteAllText("a", "a");
                File.Delete("a");
            } while (true);
        }
    }
}
```

You can't just fill the entire disk though, as then it would halt in the end and would be finite.

And you can't do reading only, infinite writing has to happen. (It has to kill my SSD after enough runtime.)

Get cracking! :)

答:
Python, 32 bytes

```<code>while 1:open("a","w").write("b")
</code>```

Note that if run on python 3, this will produce an infinite number of warnings. Also, it will probably run out of fds if run in a non-refcounting implementation.

Title: Shortest code for infinite disk I/O

Body:
Python, 32 bytes

while 1:open("a","w").write("b")

Note that if run on python 3, this will produce an infinite number of warnings. Also, it will probably run out of fds if run in a non-refcounting implementation.


答:
Lua, 39 bytes

```<code>while''do io.open('a',"w"):write('')end
</code>```

Title: Shortest code for infinite disk I/O

Body:
(Just open 50 tabs in Google Chrome :D (just kidding, no you can't))

Shortest code for infinite disk I/O any language, C# example:

using System.IO;

namespace FileApp {
    static class Program {
        public static void Main() {
            do {
                File.WriteAllText("a", "a");
                File.Delete("a");
            } while (true);
        }
    }
}
```

You can't just fill the entire disk though, as then it would halt in the end and would be finite.

And you can't do reading only, infinite writing has to happen. (It has to kill my SSD after enough runtime.)

Get cracking! :)

Body:
Lua, 39 bytes

while''do io.open('a',"w"):write('')end


问:
Needs more jQuery!
Inspired by this site, this question could potentially be a doozie. People on StackOverflow often overuse jQuery as an answer. Therefore, we need a way to recognize programmatically if a code snippet uses jQuery.

Given a string (which may or may not contain new lines,) of valid Javascript, determine if jQuery is used.

You determine if jQuery is used if the $ or jQuery functions are called.

Input quirks:

Input will always be valid Javascript.

Input can contain new lines.

Input can omit a semicolon where it would automatically be inserted

There will always be only one argument to the jQuery function.

Dollar signs could exist elsewhere (strings, comments) so be careful.

No base64 conversion functions will/can be used in input.

No eval will/can be used in input.

Any referenced variable or function can be assumed to be defined, but will be guaranteed not to produce errors.

Code snippets will always produce either a truthy or a falsey value, there will be no ambiguous code.

Comments can exist in either form.

Rules:

No Standard Loopholes

This is code-golf, the shortest answer wins.

You must write a program or a function that takes a string as input and returns a truthy value if it uses jQuery, and a falsey value if it does not.

If someone can provide a valid input that breaks your code or causes it to return an incorrect value, it is not a winning answer.

Example Test cases:

include, but are not limited to:

```<code>$('div') // true

console.log("$5.99"); // false

$ += 3; // false, the `$` variable clearly has a different value type here

var a = "span" /* this is a comment */
$(a).each(function(){
 jQuery(this);
}); // true
</code>```

Good luck, and remember, everything's better with a little extra jQuery!

答:
Javascript - 52 byte * .9 * .8 = 37.44

Don't know how valid this is, because it redefines $ and jQuery and evals the input to check if it was called.

```<code>(x)=>{$=jQuery=()=>alert(1)&3();eval(x+";alert(0)")}
</code>```

Title: Needs more jQuery!

Body:
Javascript - 52 byte * .9 * .8 = 37.44

Don't know how valid this is, because it redefines $ and jQuery and evals the input to check if it was called.

(x)=>{$=jQuery=()=>alert(1)&3();eval(x+";alert(0)")}


问:
Fast line drawing algorithm
The task is to find a way to draw a horizontal line in an array of 16-bit integers.

We're assuming a 256x192 pixel array with 16 pixels per word. A line is a contiguous run of set (1) bits. Lines can start in the middle of any word, overlap any other words, and end in any word; they may also start and end in the same word. They may not wrap on to the next line. Hint: the middle words are easy - just write 0xffff, but the edges will be tricky, as will handling the case for the start and end in the same word. A function/procedure/routine must take an x0 and x1 coordinate indicating the horizontal start and stop points, as well as a y coordinate.

I exclude myself from this because I designed a nearly identical algorithm myself for an embedded processor but I'm curious how others would go about it. Bonus points for using relatively fast operations (for example, a 64 bit multiply or floating point operation wouldn't be fast on an embedded machine but a simple bit shift would be.)

答:
Python

The main trick here is to use a lookup table to store bitmasks of the pixels. This saves a few operations. A 1kB table is not that large even for an embedded platform these days

If space is really tight, for the price of a couple of &0xf the lookup table can be reduced to just 64B

This code is in Python, but would be simple to port to any language that supports bit operations.

If using C, you could consider unwinding the loop using the switch from Duff's device. Since the line is maximum of 16 words wide, I would extend the switch to 14 lines and dispense with the while altogether.

```<code>T=[65535, 32767, 16383, 8191, 4095, 2047, 1023, 511,
   255, 127, 63, 31, 15, 7, 3, 1]*16
U=[32768, 49152, 57344, 61440, 63488, 64512, 65024, 65280,
   65408, 65472, 65504, 65520, 65528, 65532, 65534, 65535]*16

def drawline(x1,x2,y):
    y_=y<<4
    x1_=y_+(x1>>4)
    x2_=y_+(x2>>4)
    if x1_==x2_:
        buf[x1_]|=T[x1]&U[x2]
        return
    buf[x1_]|=T[x1]
    buf[x2_]|=U[x2]
    x1_+=+1
    while x1_<x2_:
        buf[x1_] = 0xffff
        x1_+=1

#### testing code ####

def clear():
    global buf
    buf=[0]*192*16

def render():
    for y in range(192):
        print "".join(bin(buf[(y<<4)+x])[2:].zfill(16) for x in range(16))

clear()
for y in range(0,192):
    drawline(y/2,y,y)
for x in range(10,200,6):
    drawline(x,x+2,0)
    drawline(x+3,x+5,1)
for y in range(-49,50):
    drawline(200-int((2500-y*y)**.5), 200+int((2500-y*y)**.5), y+60)
render()
</code>```

ContentLicense: CC BY-SA 2.5

Title: Fast line drawing algorithm

Body:
Python

The main trick here is to use a lookup table to store bitmasks of the pixels. This saves a few operations. A 1kB table is not that large even for an embedded platform these days

If space is really tight, for the price of a couple of &0xf the lookup table can be reduced to just 64B

This code is in Python, but would be simple to port to any language that supports bit operations.

If using C, you could consider unwinding the loop using the switch from Duff's device. Since the line is maximum of 16 words wide, I would extend the switch to 14 lines and dispense with the while altogether.

T=[65535, 32767, 16383, 8191, 4095, 2047, 1023, 511,
   255, 127, 63, 31, 15, 7, 3, 1]*16
U=[32768, 49152, 57344, 61440, 63488, 64512, 65024, 65280,
   65408, 65472, 65504, 65520, 65528, 65532, 65534, 65535]*16

def drawline(x1,x2,y):
    y_=y<<4
    x1_=y_+(x1>>4)
    x2_=y_+(x2>>4)
    if x1_==x2_:
        buf[x1_]|=T[x1]&U[x2]
        return
    buf[x1_]|=T[x1]
    buf[x2_]|=U[x2]
    x1_+=+1
    while x1_<x2_:
        buf[x1_] = 0xffff
        x1_+=1

#### testing code ####

def clear():
    global buf
    buf=[0]*192*16

def render():
    for y in range(192):
        print "".join(bin(buf[(y<<4)+x])[2:].zfill(16) for x in range(16))

clear()
for y in range(0,192):
    drawline(y/2,y,y)
for x in range(10,200,6):
    drawline(x,x+2,0)
    drawline(x+3,x+5,1)
for y in range(-49,50):
    drawline(200-int((2500-y*y)**.5), 200+int((2500-y*y)**.5), y+60)
render()


问:
Fibonacci products
You can decompose a number greater than 0 as a unique sum of positive Fibonacci numbers. In this question we do this by repeatedly subtracting the largest possible positive Fibonacci number. E.g.:

```<code>1 = 1
2 = 2
3 = 3
4 = 3 + 1
12 = 8 + 3 + 1
13 = 13
100 = 89 + 8 + 3
</code>```

Now, I call a Fibonacci product the same lists as above, but with the addition replaced by multiplication. For example, \$f(100) = 89 \times 8 \times 3 = 2136\$.

Write a program or function that given a positive integer n returns the Fibonacci product of that number.

Testcases:

```<code>1: 1
2: 2
3: 3
4: 3
5: 5
6: 5
7: 10
8: 8
9: 8
42: 272
1000: 12831
12345: 138481852236
</code>```

答:
Haskell, 44 bytes

Yay for mutual recursion:

```<code>(a&b)c|c<1=1|b>c=a*f(c-a)|d<-a+b=b&d$c
f=0&1
</code>```

a is the previous Fibonacci number

b is the current Fibonacci number

c is the input

f is the desired function

Less golfed:

```<code>(a & b) c | c == 0    = 1
          | c <  b    = a * f (c-a)
          | otherwise = b & (a + b) $ c
f x = (0 & 1) x
</code>```

Title: Fibonacci products

Body:
Haskell, 44 bytes

Yay for mutual recursion:

(a&b)c|c<1=1|b>c=a*f(c-a)|d<-a+b=b&d$c
f=0&1

a is the previous Fibonacci number

b is the current Fibonacci number

c is the input

f is the desired function

Less golfed:

(a & b) c | c == 0    = 1
          | c <  b    = a * f (c-a)
          | otherwise = b & (a + b) $ c
f x = (0 & 1) x


答:
Actually, 22 bytes

```<code>W;╗uR♂F;`╜≥`M░M;╜-WXkπ
</code>```

Try it online!

Explanation:

```<code>W;╗uR♂F;`╜≥`M░M;╜-WXkπ
                        (implicit input)
W                 W     while top of stack is truthy:
 ;╗                       push a copy of n to reg0
   uR♂F;                  push 2 copies of [Fib(a) for a in range(1, n+2)]
        `╜≥`M░            filter: take values where n <= Fib(a)
              M;          two copies of maximum (call it m)
                ╜-        subtract from n (this leaves n-m on top of the stack to be the new n next iteration, with a copy of m below it)
                   X    discard the 0 left over after the loop ends
                    kπ  product of all stack values
</code>```

Title: Fibonacci products

Body:
You can decompose a number greater than 0 as a unique sum of positive Fibonacci numbers. In this question we do this by repeatedly subtracting the largest possible positive Fibonacci number. E.g.:

```<code>1 = 1
2 = 2
3 = 3
4 = 3 + 1
12 = 8 + 3 + 1
13 = 13
100 = 89 + 8 + 3
</code>```

Now, I call a Fibonacci product the same lists as above, but with the addition replaced by multiplication. For example, \$f(100) = 89 \times 8 \times 3 = 2136\$.

Write a program or function that given a positive integer n returns the Fibonacci product of that number.

Testcases:

```<code>1: 1
2: 2
3: 3
4: 3
5: 5
6: 5
7: 10
8: 8
9: 8
42: 272
1000: 12831
12345: 138481852236
</code>```

Body:
Actually, 22 bytes

W;╗uR♂F;`╜≥`M░M;╜-WXkπ

Try it online!

Explanation:

W;╗uR♂F;`╜≥`M░M;╜-WXkπ
                        (implicit input)
W                 W     while top of stack is truthy:
 ;╗                       push a copy of n to reg0
   uR♂F;                  push 2 copies of [Fib(a) for a in range(1, n+2)]
        `╜≥`M░            filter: take values where n <= Fib(a)
              M;          two copies of maximum (call it m)
                ╜-        subtract from n (this leaves n-m on top of the stack to be the new n next iteration, with a copy of m below it)
                   X    discard the 0 left over after the loop ends
                    kπ  product of all stack values


问:
Code-Golf: Lattice Points inside a Circle
The following picture shows the problem:

Write a function that, given an integer as the circle radius, calculates the number of lattice points inside the centered circle (including the boundary).

The image shows:

```<code>f[1] = 5  (blue points)
f[2] = 13 (blue + red points)
</code>```

other values for your checking/debugging:

```<code>f[3]    = 29
f[10]   = 317
f[1000] = 3,141,549
f[2000] = 12,566,345
</code>```

Should have a reasonable performance. Let's say less than a minute for f[1000].

Shortest code wins. Usual Code-Golf rules apply.

Please post the calculation and timing of f[1001] as an example.

答:
PHP, 85 83 bytes

The code:

```<code>function f($n){for($x=$n;$x;$c+=$x,$y++)for(;$n*$n<$x*$x+$y*$y;$x--);return$c*4+1;}
</code>```

Its outcome (check https://3v4l.org/bC0cY for multiple PHP versions):

```<code>f(1001)=3147833
time=0.000236 seconds.
</code>```

The ungolfed code:

```<code>/**
 * Count all the points having x > 0, y >= 0 (a quarter of the circle)
 * then multiply by 4 and add the origin.
 *
 * Walk the lattice points in zig-zag starting at ($n,0) towards (0,$n), in the
 * neighbourhood of the circle. While outside the circle, go left.
 * Go one line up and repeat until $x == 0.
 * This way it checks about 2*$n points (i.e. its complexity is linear, O(n))
 *
 * @param int $n
 * @return int
 */
function countLatticePoints2($n)
{
    $count = 0;
    // Start on the topmost right point of the circle ($n,0), go towards the topmost point (0,$n)
    // Stop when reach it (but don't count it)
    for ($y = 0, $x = $n; $x > 0; $y ++) {
        // While outside the circle, go left;
        for (; $n * $n < $x * $x + $y * $y; $x --) {
            // Nothing here
        }
        // ($x,$y) is the rightmost lattice point on row $y that is inside the circle
        // There are exactly $x lattice points on the row $y that have x > 0
        $count += $x;
    }
    // Four quarters plus the center
    return 4 * $count + 1;
}
</code>```

A naive implementation that checks $n*($n+1) points (and runs 1000 times slower but still computes f(1001) in less than 0.5 seconds) and the test suite (using the sample data provided in the question) can be found on github.

Body:
PHP, 85 83 bytes

The code:

function f($n){for($x=$n;$x;$c+=$x,$y++)for(;$n*$n<$x*$x+$y*$y;$x--);return$c*4+1;}

Its outcome (check https://3v4l.org/bC0cY for multiple PHP versions):

f(1001)=3147833
time=0.000236 seconds.

The ungolfed code:

/**
 * Count all the points having x > 0, y >= 0 (a quarter of the circle)
 * then multiply by 4 and add the origin.
 *
 * Walk the lattice points in zig-zag starting at ($n,0) towards (0,$n), in the
 * neighbourhood of the circle. While outside the circle, go left.
 * Go one line up and repeat until $x == 0.
 * This way it checks about 2*$n points (i.e. its complexity is linear, O(n))
 *
 * @param int $n
 * @return int
 */
function countLatticePoints2($n)
{
    $count = 0;
    // Start on the topmost right point of the circle ($n,0), go towards the topmost point (0,$n)
    // Stop when reach it (but don't count it)
    for ($y = 0, $x = $n; $x > 0; $y ++) {
        // While outside the circle, go left;
        for (; $n * $n < $x * $x + $y * $y; $x --) {
            // Nothing here
        }
        // ($x,$y) is the rightmost lattice point on row $y that is inside the circle
        // There are exactly $x lattice points on the row $y that have x > 0
        $count += $x;
    }
    // Four quarters plus the center
    return 4 * $count + 1;
}

A naive implementation that checks $n*($n+1) points (and runs 1000 times slower but still computes f(1001) in less than 0.5 seconds) and the test suite (using the sample data provided in the question) can be found on github.