问:
Simple cat program
One of the most common standard tasks (especially when showcasing esoteric programming languages) is to implement a "cat program": read all of STDIN and print it to STDOUT. While this is named after the Unix shell utility cat it is of course much less powerful than the real thing, which is normally used to print (and concatenate) several files read from disc.

Task

You should write a full program which reads the contents of the standard input stream and writes them verbatim to the standard output stream. If and only if your language does not support standard input and/or output streams (as understood in most languages), you may instead take these terms to mean their closest equivalent in your language (e.g. JavaScript's prompt and alert). These are the only admissible forms of I/O, as any other interface would largely change the nature of the task and make answers much less comparable.

The output should contain exactly the input and nothing else. The only exception to this rule is constant output of your language's interpreter that cannot be suppressed, such as a greeting, ANSI color codes or indentation. This also applies to trailing newlines. If the input does not contain a trailing newline, the output shouldn't include one either! (The only exception being if your language absolutely always prints a trailing newline after execution.)

Output to the standard error stream is ignored, so long as the standard output stream contains the expected output. In particular, this means your program can terminate with an error upon hitting the end of the stream (EOF), provided that doesn't pollute the standard output stream. If you do this, I encourage you to add an error-free version to your answer as well (for reference).

As this is intended as a challenge within each language and not between languages, there are a few language specific rules:

If it is at all possible in your language to distinguish null bytes in the standard input stream from the EOF, your program must support null bytes like any other bytes (that is, they have to be written to the standard output stream as well).

If it is at all possible in your language to support an arbitrary infinite input stream (i.e. if you can start printing bytes to the output before you hit EOF in the input), your program has to work correctly in this case. As an example yes | tr -d \\n | ./my_cat should print an infinite stream of ys. It is up to you how often you print and flush the standard output stream, but it must be guaranteed to happen after a finite amount of time, regardless of the stream (this means, in particular, that you cannot wait for a specific character like a linefeed before printing).

Please add a note to your answer about the exact behaviour regarding null-bytes, infinite streams, and extraneous output.

Additional rules

This is not about finding the language with the shortest solution for this (there are some where the empty program does the trick) - this is about finding the shortest solution in every language. Therefore, no answer will be marked as accepted.

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

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

Feel free to use a language (or language version) even if it's newer than this challenge. Languages specifically written to submit a 0-byte answer to this challenge are fair game but not particularly interesting.

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

Also note that languages do have to fulfil our usual criteria for programming languages.

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

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

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

Catalogue

The Stack Snippet at the bottom of this post generates the catalogue 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

```

答:
Fith, 7 bytes

```<code>read \.
</code>```

read gets input from STDIN.
The language cannot handle infinite streams.
\. prints the string on top of the stack without a trailing newline.

Title: Simple cat program

Body:
Fith, 7 bytes

read \.

read gets input from STDIN.
The language cannot handle infinite streams.
\. prints the string on top of the stack without a trailing newline.


问:
bfcat - encode a file as a brainf*** program

Challenge

Write a program or function that given a string, returns a valid Brainfuck program that when compiled and executed as Brainfuck, returns that string..

Assume all inputs are encoded as ASCII.

Assume the outputted BF program will execute in an environment with an infinite tape.

Assume the pointer starts at cell 0 with every cell initialized to a value of zero.

Each example below represent one possible correct output for the given input. In particular, the examples include extra newlines and spaces to help human readability. Solutions are free to format the outputted BF code in any way.

The tape is doubly infinite.

All cells provided by the interpreter are exactly 8-bit cells. Overflow and underflow wrap around in a predictable and sane matter.

Examples

Space string

Given the input  , your program/function could return:

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

Exclamation point

Given the input ! , your program/function could return:

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

Two letters

Given the input hi , your program/function could return:

```<code>+++++ +++++
+++++ +++++
+++++ +++++
+++++ +++++
+++++ +++++

+++++ +++++
+++++ +++++
+++++ +++++
+++++ +++++
+++++ +++++

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

This is code-golf, so the code with the smallest number of bytes wins. Good luck.

答:
Python 3, 43 bytes

```<code>lambda s:''.join('+'*ord(c)+'.>'for c in s)
</code>```

The Python puts a number of pluses equivalent to the ASCII code of each character, followed by .> to print and move to the next cell.
The brainfuck increments up to the correct value, prints, and moves on to the next cell.

Output for hi (with newlines for clarity):

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

That program's output:

```<code>hi
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Python 3, 43 bytes

lambda s:''.join('+'*ord(c)+'.>'for c in s)

The Python puts a number of pluses equivalent to the ASCII code of each character, followed by .> to print and move to the next cell.
The brainfuck increments up to the correct value, prints, and moves on to the next cell.

Output for hi (with newlines for clarity):

+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++.>++++++++++++++++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++.>

That program's output:

hi


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

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

The first few numbers in the sequence are:

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

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

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

Limitations: n < 100000.

Smallest code wins.

答:
Javascript, 93 chars

```<code>c=[,1],i=c.length;function g(n){for(i;i<n;i++) c[i]=g(i);return c[n]||(c[n]=1+g(n-g(g(n-1))))}
</code>```

Body:
Javascript, 93 chars

c=[,1],i=c.length;function g(n){for(i;i<n;i++) c[i]=g(i);return c[n]||(c[n]=1+g(n-g(g(n-1))))}


问:
Product over a range
Your task is simple: given two integers \$a\$ and \$b\$, output \$\Pi[a,b]\$; that is, the product of the range between \$a\$ and \$b\$. You may take \$a\$ and \$b\$ in any reasonable format, whether that be arguments to a function, a list input, STDIN, et cetera. You may output in any reasonable format, such as a return value (for functions) or STDOUT. \$a\$ will always be less than \$b\$.

Note that the end may be exclusive or inclusive of \$b\$. I'm not picky. ^_^

Test cases

```<code>[a,b) => result
[2,5) => 24
[5,10) => 15120
[-4,3) => 0
[0,3) => 0
[-4,0) => 24

[a,b] => result
[2,5] => 120
[5,10] => 151200
[-4,3] => 0
[0,3] => 0
[-4,-1] => 24
</code>```

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

Leaderboard

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

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

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

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

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

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

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

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

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

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

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

```

答:
Fith, 17 bytes (non-competing)

This language was created after the challenge.

```<code>{ range product }
</code>```

Anonymous function. Excludes b. Pretty self-explanatory.

Stack effect: a b -- *[a,b)

ContentLicense: CC BY-SA 4.0

Title: Product over a range

Body:
Fith, 17 bytes (non-competing)

This language was created after the challenge.

{ range product }

Anonymous function. Excludes b. Pretty self-explanatory.

Stack effect: a b -- *[a,b)


Title: bfcat - encode a file as a brainf*** program

Body:
Challenge

Write a program or function that given a string, returns a valid Brainfuck program that when compiled and executed as Brainfuck, returns that string..

Assume all inputs are encoded as ASCII.

Assume the outputted BF program will execute in an environment with an infinite tape.

Assume the pointer starts at cell 0 with every cell initialized to a value of zero.

Each example below represent one possible correct output for the given input. In particular, the examples include extra newlines and spaces to help human readability. Solutions are free to format the outputted BF code in any way.

The tape is doubly infinite.

All cells provided by the interpreter are exactly 8-bit cells. Overflow and underflow wrap around in a predictable and sane matter.

Examples

Space string

Given the input  , your program/function could return:

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

Exclamation point

Given the input ! , your program/function could return:

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

Two letters

Given the input hi , your program/function could return:

```<code>+++++ +++++
+++++ +++++
+++++ +++++
+++++ +++++
+++++ +++++

+++++ +++++
+++++ +++++
+++++ +++++
+++++ +++++
+++++ +++++

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

This is code-golf, so the code with the smallest number of bytes wins. Good luck.

Body:
Brainfuck, <s>39</s> <s>33</s> <s>32</s> 31 bytes

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

The algorithm that places 45 on the tape is taken from Esolang's Brainfuck constants.

This answer assumes that the output program's interpreter has wrapping, bounded cells; and that , zeroes the current cell (implying that the output program is run without input). Try it online!

For a (longer) solution that works unconditionally, see my other answer.

Test run

For input Code Golf, the following output is generated.

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------.,-------------------------------------------------------------------------------------------------------------------------------------------------.,------------------------------------------------------------------------------------------------------------------------------------------------------------.,-----------------------------------------------------------------------------------------------------------------------------------------------------------.,--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------.,-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------.,-------------------------------------------------------------------------------------------------------------------------------------------------.,----------------------------------------------------------------------------------------------------------------------------------------------------.,----------------------------------------------------------------------------------------------------------------------------------------------------------.,

<a href="http://brainfuck.tryitonline.net/#code=LS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLiwtLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLiwtLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0uLC0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLiwtLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS4sLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0uLC0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0uLC0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0uLC0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0uLA&input=" rel="noreferrer">Try it online!

How it works

We begin by putting the integer 45 (character code of -) into a cell of the tape. The following code achieves this.

-      Decrement cell 0, setting it to 255.
[      While the cell under the head in non-zero:
  [>]    Advance to the next zero cell.
  <--    Decrement the cell to its left.
  <--    Decrement the next cell to the left.
]

Before we enter the loop, the tape looks like this.

         v
000 000 255

These three cells – -2, -1, and 0 – are the only ones we'll use in this program.

In the first each iteration of the loop, the rightmost cell is, then that cell and middle cell are decremented twice, leaving the following state.

     v
000 254 252

In the next 126 iterations, the initial - decrements the middle cell, [>]< jumps to the rightmost cell, and --<-- decrements the middle and the right cell. As a result, 3 is subtracted from the middle cell (modulo 256) and 2 is subtracted from the rightmost cell.

Since 254 ÷ 3 (mod 256) = (254 + 256) ÷ 3 = 510 ÷ 3 = 170 and 252 ÷ 3 = 84, the rightmost cell is zeroed out before the middle one, leaving the following state.

     v
000 132 000

Similarly to the first iteration of the loop, the next iteration now subtracts 3 from the middle cell and 2 from the leftmost cell, placing the head on the leftmost cell.

 v
254 129 000

Subsequent iterations, as in the 126 iteration before them, subtract 3 from the leftmost cell and 2 from the rightmost cell.

Since 254 ÷ 3 (mod 256) = 170 and 129 ÷ 2 (mod 256) is undefined, this is done 170 times, leaving the following state.

 v
000 045 000

The cell under the head is zero; the loop ends.

Now we're ready to generate output.

,      Read a character from STDIN and put it the leftmost cell.
[        While the leftmost cell is non-zero:
  [        While the leftmost cell is non-zero:
    >.     Print the content of the middle cell ('-').
    <-     Increment the leftmost cell.
  ]      If the leftmost cell held n, the above will print 256 - n minus signs
         which, when executed, will put n in cell 0 of the output program.
  >      Increment the middle cell, setting it to 46 ('.').
  .      Print its content ('.').
  --     Decrement the middle cell twice, setting it to 44 (',').
  .      Print its content (',').
         When executed, since the output program receives no input, the above
         will zero cell 0 of the output program.
  +      Increment the second cell, setting it back to 45 ('-').
  <,     Go back to the leftmost cell and read another character from STDIN.
]      Once EOF is reached, this will put 0 in the leftmost cell, ending the loop.


问:
The Möbius Function
The Möbius function is an important number theoretic function.

Your submission should accept a positive integer \$n\$ and return the value of the Möbius function evaluated at \$n\$.

Definition

The Möbius function \$μ(n)\$ is defined as follows:

$$\mu(n) = \begin{cases}
\hphantom{-}1, &n\text{ is squarefree and has an even number of distinct prime factors} \\
-1, &n\text{ squarefree and has an odd number of distinct prime factors} \\
\hphantom{-}0, &\text{otherwise}
\end{cases}$$

\$n\$ is called squarefree if the exponents of the prime factorization of \$n\$ are all strictly less that two. (Alternatively: No prime to the power of two divides \$n\$).

Test cases

Here you can see the first 50 values of μ:

Public Domain Image from Wikipedia

The Möbius function is sequence number A008683 in the OEIS.

These are the first 77 values:

```<code>1, -1, -1, 0, -1, 1, -1, 0, 0, 1, -1, 0, -1, 1, 1, 0, -1, 0, -1, 0, 1, 1, -1, 0, 0, 1, 0, 0, -1, -1, -1, 0, 1, 1, 1, 0, -1, 1, 1, 0, -1, -1, -1, 0, 0, 1, -1, 0, 0, 0, 1, 0, -1, 0, 1, 0, 1, 1, -1, 0, -1, 1, 0, 0, 1, -1, -1, 0, 1, -1, -1, 0, -1, 1, 0, 0, 1
</code>```

Larger values can also easily be checked in Wolframalpha.com or in the b-file of OEIS, as suggested by @MartinBüttner.

答:
Julia, 35 bytes

```<code>\(n,k=1)=k%n>0?n\-~k-k\0^(n%k):1÷n
</code>```

Based on @xnor's Python answer. Try it online!

Title: The Möbius Function

Body:
Julia, 35 bytes

\(n,k=1)=k%n>0?n\-~k-k\0^(n%k):1÷n

Based on @xnor's Python answer. Try it online!


问:
Evaluate a Stratego Battle
In the game Stratego, the main game mechanic is when you attack an opponent's piece with yours. In this challenge, you job is to simulate one of these battles and say who survives.

Specs

You will get as input a pair of string representing Stratego pieces. The pieces are one of "S 1 2 3 4 5 6 7 8 9 10 B" (S is the Spy, and B are bombs). The first of the pair will be the attacker, and the second the attacked.

Here are the rules for determining the results of a battle:

The higher number beats the lower number: ["4", "6"] -> ["6"].

If both are the same, then both die: ["7", "7"] -> [].

Spies are at the bottom, underneath even 1: ["S", "2"] -> ["2"].

However, if a spy attacks the 10, then the spy wins: ["S", "10"] -> ["S"].

But the normal rules still apply if the 10 is the one attacking: ["10", "S"] -> ["10"].

If anything attacks a bomb, the bomb wins: ["5", "B"] -> ["B"].

However, a miner (a 3), can defuse a bomb: ["3", "B"] -> ["3"].

A bomb will never be the attacker.

A spotter (a 1), can attack using the normal mechanism, but they can also try to "guess" the rank of the other player, which can be denoted with any sane notation.

If they guess correctly, the other piece dies: ["1(5)", "5"] -> ["1"].

If they guess wrong, nothing happens: ["1(3)", "5"] -> ["1", "5"].

Spotters can spot bombs: ["1(B)", "B"] -> ["1"].

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

(You can use the examples up there as test-cases, because I'm too lazy to put them all together in one list).

答:
Haskell, 131 bytes

This solution is in the form of an infix function # with type String -> String -> String

Input is accepted through the two string arguments. The format for spotter input is 1 x where x is the guess.Output is given as a string. In the case where both units survive, the returned string contains both separated by a space.

My original solution was unfortunately bugged and the fix cost me a few bytes.

```<code>('1':' ':x)#y|x==y="1"|1>0="1 "++y
"S"#"10"="S"
"3"#"B"="3"
_#"B"="B"
x#y|x==y=[]
t@"10"#_=t
_#t@"10"=t
"S"#x=x
x#"S"=x
x#y=max x y
</code>```

Title: Evaluate a Stratego Battle

Body:
Haskell, 131 bytes

This solution is in the form of an infix function # with type String -> String -> String

Input is accepted through the two string arguments. The format for spotter input is 1 x where x is the guess.Output is given as a string. In the case where both units survive, the returned string contains both separated by a space.

My original solution was unfortunately bugged and the fix cost me a few bytes.

('1':' ':x)#y|x==y="1"|1>0="1 "++y
"S"#"10"="S"
"3"#"B"="3"
_#"B"="B"
x#y|x==y=[]
t@"10"#_=t
_#t@"10"=t
"S"#x=x
x#"S"=x
x#y=max x y


问:
Time for some TEA!

Introduction

A while back I stumbled across the tiny encryption algorithm (TEA) and since then I have recommended it whenever special cryptographic security properties were un-needed and a self-implementation was a requirement.

Now today, we want to take the name *tiny* encryption algorithm literally and your task will be to implement the tiniest encryption algorithm!

Specification

Input

The input is a list of 8 bytes (or your language equivalent), this is the plaintext, and another list of 16 bytes (or your language equivalent), this is the key.

Input conversion from decimal, hexadecimal, octal or binary is allowed.
 Reading 1 64-bit, 2 32-bit or 4 16-bit integers as output (optionally as a list) is allowed (for the plaintext, double the numbers for the key)

Output

The output is a list of 8 bytes (or your language equivalent), this is the ciphertext.

Output conversion to decimal, hexadecimal, octal or binary is allowed, but not mandatory.

Writing 1 64-bit, 2 32-bit or 4 16-bit integers as output (optionally as a list) is allowed.

What to do?

Your task is to implement the encryption direction of the tiny encryption algorithm (TEA), note XTEA and XXTEA are other algorithms.

Wikipedia has a C-code example and a list of references to some implementations in other languages, this is the original description (PDF).

More Formally:

```<code>Let k1, k2, k3, k4, v1, v2, sum be unsigned 32-bit integers.
(k1,k2,k3,k4) <- key input
(v1,v2) <- plaintext input
sum <- 0
repeat 32 times:
    sum <- ( sum + 0x9e3779b9 ) mod 2^32
    v0  <- ( v0 + ( ((v1 << 4) + k0) XOR (v1 + sum) XOR ((v1 >> 5) + k1) ) ) mod 2^32
    v1  <- ( v1 + ( ((v0 << 4) + k2) XOR (v0 + sum) XOR ((v0 >> 5) + k3) ) ) mod 2^32
output <- (v0,v1)

where 0x9e3779b9 is a hexadecimal constant and
"<<" denotes logical left shift and ">>" denotes logical right shift.
</code>```

Potential corner cases

\0 is a valid character and you may not shorten your input nor output.

Integer encoding is assumed to be little-endian (e.g. what you probably already have).

Who wins?

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

Standard rules apply of course.

Test-cases

Test vectors were generated using the Wikipedia C code example.

```<code>Key: all zero (16x \0)
Plaintext -> Ciphertext (all values as two 32-bit hexadecimal words)
00000000 00000000 -> 41ea3a0a 94baa940
3778001e 2bf2226f -> 96269d3e 82680480
48da9c6a fbcbe120 -> 2cc31f2e 228ad143
9bf3ceb8 1e076ffd -> 4931fc15 22550a01
ac6dd615 9c593455 -> 392eabb4 505e0755
ebad4b59 7b962f3c -> b0dbe165 cfdba177
ca2d9099 a18d3188 -> d4641d84 a4bccce6
b495318a 23a1d131 -> 39f73ca0 bda2d96c
bd7ce8da b69267bf -> e80efb71 84336af3
235eaa32 c670cdcf -> 80e59ecd 6944f065
762f9c23 f767ea2c -> 3f370ca2 23def34c
</code>```

Here are some self-generated test vectors with non-zero keys:

```<code>format: ( 4x 32-bit word key , 2x 32-bit word plaintext ) -> ( 2x 32-bit word ciphertext )
(all in hexadecimal)

( 4300e123 e39877ae 7c4d7a3c 98335923 , a9afc671 79dcdb73 ) -> ( 5d357799 2ac30c80 )
( 4332fe8f 3a127ee4 a9ca9de9 dad404ad , d1fe145a c84694ee ) -> ( a70b1d53 e7a9c00e )
( 7f62ac9b 2a0771f4 647db7f8 62619859 , 618f1ac2 67c3e795 ) -> ( 0780b34d 2ca7d378 )
( 0462183a ce7edfc6 27abbd9a a634d96e , 887a585d a3f83ef2 ) -> ( d246366c 81b87462 )
( 34c7b65d 78aa9068 599d1582 c42b7e33 , 4e81fa1b 3d22ecd8 ) -> ( 9d5ecc3b 947fa620 )
( f36c977a 0606b8a0 9e3fe947 6e46237b , 5d8e0fbe 2d3b259a ) -> ( f974c6b3 67e2decf )
( cd4b3820 b2f1e5a2 485dc7b3 843690d0 , 48db41bb 5ad77d7a ) -> ( b4add44a 0c401e70 )
( ee2744ac ef5f53ec 7dab871d d58b3f70 , 70c94e92 802f6c66 ) -> ( 61e14e3f 89408981 )
( 58fda015 c4ce0afb 49c71f9c 7e0a16f0 , 6ecdfbfa a705a912 ) -> ( 8c2a9f0c 2f56c18e )
( 87132255 41623986 bcc3fb61 7e6142ce , 9d0eff09 55ac6631 ) -> ( 8919ea55 c7d430c6 )
</code>```

答:
J, 149 bytes

```<code>4 :0
'u v'=.y
s=.0
m=.2x^32
for.i.32
do.s=.m|s+2654435769
u=.m|u+(22 b.)/(s+v),(2{.x)+4 _5(33 b.)v
v=.m|v+(22 b.)/(s+u),(2}.x)+4 _5(33 b.)u
end.u,v
)
</code>```

Yay! explicit (Boo!) J! I think there's a way to do this tacitly, but it'd probably become unreadable.

Usage

Takes the keys as four 32-bit integers on the LHS and the plaintext as two 32-bit integers on the RHS. The prefix 16b is equivalent to 0x in other languages and represents a hex value. The builtin hfd formats the output into a hex string for ease in testing.

```<code>    f =: 4 :0
'u v'=.y
s=.0
m=.2x^32
for.i.32
do.s=.m|s+2654435769
u=.m|u+(22 b.)/(s+v),(2{.x)+4 _5(33 b.)v
v=.m|v+(22 b.)/(s+u),(2}.x)+4 _5(33 b.)u
end.u,v
)
   hfd 0 0 0 0 f 0 0
41ea3a0a
94baa940
   hfd 0 0 0 0 f 16b3778001e 16b2bf2226f
96269d3e
82680480
   hfd 16b4300e123 16be39877ae 16b7c4d7a3c 16b98335923 f 16ba9afc671 16b79dcdb73
5d357799
2ac30c80
</code>```

Title: Time for some TEA!

Body:
J, 149 bytes

4 :0
'u v'=.y
s=.0
m=.2x^32
for.i.32
do.s=.m|s+2654435769
u=.m|u+(22 b.)/(s+v),(2{.x)+4 _5(33 b.)v
v=.m|v+(22 b.)/(s+u),(2}.x)+4 _5(33 b.)u
end.u,v
)

Yay! explicit (Boo!) J! I think there's a way to do this tacitly, but it'd probably become unreadable.

Usage

Takes the keys as four 32-bit integers on the LHS and the plaintext as two 32-bit integers on the RHS. The prefix 16b is equivalent to 0x in other languages and represents a hex value. The builtin hfd formats the output into a hex string for ease in testing.

    f =: 4 :0
'u v'=.y
s=.0
m=.2x^32
for.i.32
do.s=.m|s+2654435769
u=.m|u+(22 b.)/(s+v),(2{.x)+4 _5(33 b.)v
v=.m|v+(22 b.)/(s+u),(2}.x)+4 _5(33 b.)u
end.u,v
)
   hfd 0 0 0 0 f 0 0
41ea3a0a
94baa940
   hfd 0 0 0 0 f 16b3778001e 16b2bf2226f
96269d3e
82680480
   hfd 16b4300e123 16be39877ae 16b7c4d7a3c 16b98335923 f 16ba9afc671 16b79dcdb73
5d357799
2ac30c80


问:
Build a marginal tax calculator
There have been some tax rate calculator problems here that depend on defined rates (specifically US federal rates), but none that have done it for arbitrary lists.

Your task is to build a program or function that will take an arbitrary list of marginal tax brackets and calculate the effective amount of tax paid on a given amount of taxable income.

Your program will take as input:

N pairs of numbers in the form (amt, rate), each representing a tax bracket.

amt is the amount of taxable income above which at which the tax rate starts to apply. These amounts will all be integers, and appear in increasing order.

rate is the tax rate, expressed as a decimal percentage from 0 to 100 inclusive.

The amount of taxable income, as a nonnegative integer.

If no rate is specified for $0, the rate is assumed to be 0%.

Alternatively, your program can also take as input two lists (amt1, amt2, ...) and (rate1, rate2, ...), containing the amounts and rates in the same order.

Your program will then output the payable tax, either to two decimal places, or rounded down to the nearest whole currency unit.

An example input (the most recent Canadian tax brackets, from 2016, with the basic personal tax credit applied and nothing else):

```<code>11474 15
45282 20.5
90563 26
140388 29
200000 33

393216
</code>```

And its corresponding output:

```<code>108357.07  or  108357
</code>```

The shortest program in any language to do this wins.

答:
Haskell, <s>67</s> 66 bytes

Thanks Damien for -1 byte.

This solution is in the form of an infix function, ?, of type (Integral b, RealFrac r) => [(r, r)] -> r -> b. The helper function, #, does the required calculations while ? serves to handle the IO specifications.

```<code>a?b=floor$reverse a#b
((m,p):r)#i|v<-min i m=p/100*(i-v)+r#v
_#_=0
</code>```

Title: Build a marginal tax calculator

Body:
Haskell, <s>67</s> 66 bytes

Thanks Damien for -1 byte.

This solution is in the form of an infix function, ?, of type (Integral b, RealFrac r) => [(r, r)] -> r -> b. The helper function, #, does the required calculations while ? serves to handle the IO specifications.

a?b=floor$reverse a#b
((m,p):r)#i|v<-min i m=p/100*(i-v)+r#v
_#_=0


问:
Professor Schwartzman's Acme Canine Decoder 2000

Introduction

We -- especially the geeks among us, who tend to be fans -- all remember this old Far Side cartoon:

Clearly, Professor Schwartzman could have brushed up on his programming skills just a wee bit more before he put his invention to use. But can you replicate it yourself... using as few bytes as possible?

Input Specs

You must create a script that translates dog sounds into appropriately intonated "Hey"s. This is pure code golf; the lowest number of bytes wins.

Your input will consist of some combination of the following tokens:

Bark, Baark, Baaark, Baaaark, ... (that is, B*rk  with at least 1 a replacing the asterisk)

Woof, Wooof, Woooof, ... (W*f with at least 2 os replacing the asterisk)

Grr, Grrr, Grrrr, ..., (G followed by at least 2 rs)

Any number of . (period), ! (exclamation mark) and/or ? (question mark) characters, which may occur anywhere in the input

Note, again, that the Woof-based and Grr-based tokens always require at least two os and rs respectively; Wof and Gr are not valid tokens.

There is no limit on how long a token can be (e.g., how many repeated as there can be in a Bark token); however, your decoder only needs to work correctly for input tokens with up to 10 total as, os, or rs to pass this challenge.

Output Specs

Faithful to Schwartzman's design, your canine decoder program must process it into output text as follows:

Bark, Woof, and Grr become Hey;

Baark, Wooof, and Grrr become Heyy;

Baaark, Woooof, and Grrrr become Heyyy; etc.

For all Bark-based tokens, the number of ys in the output Hey-based token must be equal to the number of as;

For all Woof-based tokens, the number of ys in the output Hey-based token must be one less than the number of os;

For all Grr-based tokens, the number of ys in the output Hey-based token must be one less than the number of rs;

All punctuation (., !, and ?) is left unchanged.

Remember to drop one y from the output for Woofs and Grrs only! The input Baaaaaaaark?, with 8 as, will become Heyyyyyyyy?, with a matching set of 8 ys. However, Woooooooof? becomes only Heyyyyyyy?, with 7 ys.

Again, if you can get your program to work for input tokens of unlimited size, that's great, but for purposes of this challenge, your program will only be checked to ensure that it works properly for input tokens that have no more than 10 repeated letters.

All Bark-, Woof-, and Grr-based tokens in your input are assumed to begin with capital letters. Therefore, there is no need to handle turning Bark grrr into Hey heyy or anything similar.

Example Inputs and Outputs

Input: Bark. Bark! Bark!!

Output: Hey. Hey! Hey!!

Input: Baaaaaark? (six as)

Output: Heyyyyyy? (six ys)

Input: Grrrrrrrr... (eight rs)

Output: Heyyyyyyy... (seven ys)

Input: ?...!

Output: ?...!

Input: Wooof Woof? Grrrr. Baaaark Grr!

Output: Heyy Hey? Heyyy. Heyyyy Hey!

答:
Python, 106 bytes

```<code>f=lambda s,a="B,He,Gr,He,Wo,He,a,y,r,y,o,y,f,,yk,".split(","):s if a==[]else f(s.replace(a[0],a[1]),a[2:])
</code>```

Demo

https://repl.it/C6Rr

Body:
Python, 106 bytes

f=lambda s,a="B,He,Gr,He,Wo,He,a,y,r,y,o,y,f,,yk,".split(","):s if a==[]else f(s.replace(a[0],a[1]),a[2:])

Demo

https://repl.it/C6Rr


答:
Perl, 25 bytes

```<code>s/./"+"x ord($&).".>"/eg
</code>```

Usage

```<code>echo -n hi | perl -pe 's/./"+"x ord($&).".>"/eg'
</code>```

Explanation

Uses a regular expression replace operation to replace every character in every line given on standard input with a number of + calculated from the ordinal value of that character, then outputs .> to print and advance to the next character.

Uses the perl -p flag to automatically read the input and print the result, adding 1 extra to the bytecount.

Body:
Perl, 25 bytes

s/./"+"x ord($&).".>"/eg

Usage

echo -n hi | perl -pe 's/./"+"x ord($&).".>"/eg'

Explanation

Uses a regular expression replace operation to replace every character in every line given on standard input with a number of + calculated from the ordinal value of that character, then outputs .> to print and advance to the next character.

Uses the perl -p flag to automatically read the input and print the result, adding 1 extra to the bytecount.


问:
Is string X a subsequence of string Y?
Given strings X and Y, determine whether X is a subsequence of Y. The empty string is regarded as a subsequence of every string. (E.g., '' and 'anna' are subsequences of 'banana'.)

Input

X, a possibly-empty case-sensitive alphanumeric string

Y, a possibly-empty case-sensitive alphanumeric string

Output

True or False (or equivalents), correctly indicating whether X is a subsequence of Y.

I/O examples

```<code>X      Y        output

''     'z00'    True
'z00'  'z00'    True
'z00'  '00z0'   False
'aa'   'anna'   True
'anna' 'banana' True
'Anna' 'banana' False
</code>```

Criteria

The shortest program wins, as determined by the number of bytes of source code.

Example programs

Several programs that could be adapted are in this related posting.

答:
Javascript, 104 chars

```<code>function _(x,y){f=true;for(c in x){if(y.indexOf(x[c])>-1)y=y.replace(x[c],"");else{f=!f;break}}return f}
</code>```

Ungolfed

```<code>function _(x,y){
f=true;
    for(c in x)
    {
        if(y.indexOf(x[c])>-1)
           y=y.replace(x[c],"");
        else {
            f=!f;
            break;
        }
    }
    return f;
}
</code>```

Title: Is string X a subsequence of string Y?

Body:
Javascript, 104 chars

function _(x,y){f=true;for(c in x){if(y.indexOf(x[c])>-1)y=y.replace(x[c],"");else{f=!f;break}}return f}

Ungolfed

function _(x,y){
f=true;
    for(c in x)
    {
        if(y.indexOf(x[c])>-1)
           y=y.replace(x[c],"");
        else {
            f=!f;
            break;
        }
    }
    return f;
}


答:
Perl, 51 41 39 bytes

```<code>s/(G.|[BW]..)(\w+)/He."y"x length$2/ge
</code>```

Usage

```<code>perl -pE 's/(G.|[BW]..)(\w+)/He."y"x length$2/ge'
</code>```

Input

```<code>Bark. Bark! Bark!!
Baaaaaark?
Grrrrrrrr...
?...!
Wooof Woof? Grrrr. Baaaark Grr!
</code>```

Output

```<code>Hey. Hey! Hey!!
Heyyyyyy?
Heyyyyyyy...
?...!
Heyy Hey? Heyyy. Heyyyy Hey!
</code>```

How it works

Simple regexp substitution using the auto-printing -p adding 1 byte to the count. /ge executes the substitution for every pattern, and runs the replacement as code.

An older version used a three-way detection, but Martin Ender noticed that I was not aggressive enough, which saved me 10 bytes.

msh210 informed me that you don't need quotes around the string He, saving two bytes.

Title: Professor Schwartzman's Acme Canine Decoder 2000

Body:
Introduction

We -- especially the geeks among us, who tend to be fans -- all remember this old Far Side cartoon:

Clearly, Professor Schwartzman could have brushed up on his programming skills just a wee bit more before he put his invention to use. But can you replicate it yourself... using as few bytes as possible?

Input Specs

You must create a script that translates dog sounds into appropriately intonated "Hey"s. This is pure code golf; the lowest number of bytes wins.

Your input will consist of some combination of the following tokens:

Bark, Baark, Baaark, Baaaark, ... (that is, B*rk  with at least 1 a replacing the asterisk)

Woof, Wooof, Woooof, ... (W*f with at least 2 os replacing the asterisk)

Grr, Grrr, Grrrr, ..., (G followed by at least 2 rs)

Any number of . (period), ! (exclamation mark) and/or ? (question mark) characters, which may occur anywhere in the input

Note, again, that the Woof-based and Grr-based tokens always require at least two os and rs respectively; Wof and Gr are not valid tokens.

There is no limit on how long a token can be (e.g., how many repeated as there can be in a Bark token); however, your decoder only needs to work correctly for input tokens with up to 10 total as, os, or rs to pass this challenge.

Output Specs

Faithful to Schwartzman's design, your canine decoder program must process it into output text as follows:

Bark, Woof, and Grr become Hey;

Baark, Wooof, and Grrr become Heyy;

Baaark, Woooof, and Grrrr become Heyyy; etc.

For all Bark-based tokens, the number of ys in the output Hey-based token must be equal to the number of as;

For all Woof-based tokens, the number of ys in the output Hey-based token must be one less than the number of os;

For all Grr-based tokens, the number of ys in the output Hey-based token must be one less than the number of rs;

All punctuation (., !, and ?) is left unchanged.

Remember to drop one y from the output for Woofs and Grrs only! The input Baaaaaaaark?, with 8 as, will become Heyyyyyyyy?, with a matching set of 8 ys. However, Woooooooof? becomes only Heyyyyyyy?, with 7 ys.

Again, if you can get your program to work for input tokens of unlimited size, that's great, but for purposes of this challenge, your program will only be checked to ensure that it works properly for input tokens that have no more than 10 repeated letters.

All Bark-, Woof-, and Grr-based tokens in your input are assumed to begin with capital letters. Therefore, there is no need to handle turning Bark grrr into Hey heyy or anything similar.

Example Inputs and Outputs

Input: Bark. Bark! Bark!!

Output: Hey. Hey! Hey!!

Input: Baaaaaark? (six as)

Output: Heyyyyyy? (six ys)

Input: Grrrrrrrr... (eight rs)

Output: Heyyyyyyy... (seven ys)

Input: ?...!

Output: ?...!

Input: Wooof Woof? Grrrr. Baaaark Grr!

Output: Heyy Hey? Heyyy. Heyyyy Hey!

Body:
Perl, 51 41 39 bytes

s/(G.|[BW]..)(\w+)/He."y"x length$2/ge

Usage

perl -pE 's/(G.|[BW]..)(\w+)/He."y"x length$2/ge'

Input

Bark. Bark! Bark!!
Baaaaaark?
Grrrrrrrr...
?...!
Wooof Woof? Grrrr. Baaaark Grr!

Output

Hey. Hey! Hey!!
Heyyyyyy?
Heyyyyyyy...
?...!
Heyy Hey? Heyyy. Heyyyy Hey!

How it works

Simple regexp substitution using the auto-printing -p adding 1 byte to the count. /ge executes the substitution for every pattern, and runs the replacement as code.

An older version used a three-way detection, but Martin Ender noticed that I was not aggressive enough, which saved me 10 bytes.

msh210 informed me that you don't need quotes around the string He, saving two bytes.


答:
Retina, <s>24</s> <s>18</s> <s>17</s> 16 bytes

1 byte saved based on an idea in MT0's answer.

```<code>\wf?k?
y
\byy
He
</code>```

Try it online!

Explanation

```<code>\wf?k?
y
</code>```

This simply turns all letters into y, but if they are followed by an f or k we immediately replace that as well. By removing f and k we "normalise" the lengths of the words so that they now all have two more ys than they need.

```<code>\byy
He
</code>```

This turns the first two y of every word into He, completing the transformation.

Body:
Retina, <s>24</s> <s>18</s> <s>17</s> 16 bytes

1 byte saved based on an idea in MT0's answer.

\wf?k?
y
\byy
He

Try it online!

Explanation

\wf?k?
y

This simply turns all letters into y, but if they are followed by an f or k we immediately replace that as well. By removing f and k we "normalise" the lengths of the words so that they now all have two more ys than they need.

\byy
He

This turns the first two y of every word into He, completing the transformation.


答:
Vimscript, <s>51</s> <s>39</s> <s>37</s> <s>33</s> <s>32</s> <s>29</s> 28 bytes,

```<code>%s/\hk\?f\?/y/g|%s/\<yy/He/g
</code>```

Regex credits for shaving 9 more bytes: MT0, Martin Ender, msh210

Demo

Explanation:

```<code>                               1. Normalize words to same length & replace letters with ys

%s                             Regex search and replace
  /                            Regex search begin
   \hk\?f\?                    Find any letter (\h) optionally followed by k or f
           /                   Regex search end and replace start
            y                  Replace with y
             /                 Replace end
              g                Replace globally

               |               New command

                               2. Overwrite first two y of every word with He

                %s             Regex search and replace
                  /            Regex search begin
                   \<yy        Find yy at a word's beginning
                        /      Regex search end and replace start
                         He    replace with He
                           /   Replace end
                            g  Replace globally
</code>```

Body:
Vimscript, <s>51</s> <s>39</s> <s>37</s> <s>33</s> <s>32</s> <s>29</s> 28 bytes,

%s/\hk\?f\?/y/g|%s/\<yy/He/g

Regex credits for shaving 9 more bytes: MT0, Martin Ender, msh210

Demo

Explanation:

                               1. Normalize words to same length & replace letters with ys

%s                             Regex search and replace
  /                            Regex search begin
   \hk\?f\?                    Find any letter (\h) optionally followed by k or f
           /                   Regex search end and replace start
            y                  Replace with y
             /                 Replace end
              g                Replace globally

               |               New command

                               2. Overwrite first two y of every word with He

                %s             Regex search and replace
                  /            Regex search begin
                   \<yy        Find yy at a word's beginning
                        /      Regex search end and replace start
                         He    replace with He
                           /   Replace end
                            g  Replace globally


答:
Java, 91 bytes

String b(char[] f){String k="";for(char b:f){for(int u=b;u>0;u--)k+="+";k+=".>";}return k;}
```

Props to dorukayhan for beating me to it :)

Body:
Java, 91 bytes

String b(char[] f){String k="";for(char b:f){for(int u=b;u>0;u--)k+="+";k+=".>";}return k;}

Props to dorukayhan for beating me to it :)


答:
Pyke, 35 bytes

```<code>.cFDlR\G.^+3-\y*"He"R+)Rdc~lL-],AsJ
</code>```

Try it here!

Generates Heys, Generates punctuation, zips together, joins

Body:
Pyke, 35 bytes

.cFDlR\G.^+3-\y*"He"R+)Rdc~lL-],AsJ

Try it here!

Generates Heys, Generates punctuation, zips together, joins


问:
Theoretically output Graham's number
Graham's number G is defined in this way:

```<code>u(3,n,1) = 3^n
u(3,1,m) = 3
u(3,n,m) = u(3,u(3,n-1,m),m-1)
[Knuth's up-arrow notation]
[Conway chained arrow notation]

THEN

g1 = u(3,3,4)
g2 = u(3,3,g1)
g3 = u(3,3,g2)
...
G = u(3,3,g63)
</code>```

You are given that u(3,3,2)=7625597484987 to check your code.

Your task is to write a program/function that will output the value of G deterministically, given enough integer size and enough time.

References

Graham's number

Knuth's up-arrow notation

Conway chained arrow notation

Leaderboard

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

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

```

答:
Brachylog, 57 bytes

```<code>4:64:1iw
:3{[1:N],3:N^.|t1,3.|hM:1-X,?t:1-:Mr:2&:Xr:2&.}.
</code>```

Expects no Input nor Output and writes the result to STDOUT. This will produce a stack overflow at one point.

To check that this works for small values (e.g u(3,3,2)) you can replace the 4 with the value of m and 64 with 1.

Explanation

This is basically a straightforward implementation of the explained way of computing the number.

Main predicate:

```<code>4:64:1i                    Call Predicate 1 64 times with 4 as initial input (the second
                           call takes the output of the first as input, etc. 64 times).
       w                   Write the final output to STDOUT
</code>```

Predicate 1:

```<code>:3{...}.                   Call predicate 2 with input [Input, 3]. Its output is the
                           output of predicate 1.
</code>```

Predicate 2:

```<code>[1:N],                     M = 1
      3:N^.                Output = 3^N
|                          Or
t1,                        N = 1
   3.                      Output = 3
|                          Or
hM:1-X,                    X is M - 1
       ?t:1-:Mr:2&         Unify an implicit variable with u(3,N-1,M)
                  :Xr:2&.  Unify Output with u(3,u(3,N-1,M),X)
</code>```

Title: Theoretically output Graham's number

Body:
Brachylog, 57 bytes

4:64:1iw
:3{[1:N],3:N^.|t1,3.|hM:1-X,?t:1-:Mr:2&:Xr:2&.}.

Expects no Input nor Output and writes the result to STDOUT. This will produce a stack overflow at one point.

To check that this works for small values (e.g u(3,3,2)) you can replace the 4 with the value of m and 64 with 1.

Explanation

This is basically a straightforward implementation of the explained way of computing the number.

Main predicate:

4:64:1i                    Call Predicate 1 64 times with 4 as initial input (the second
                           call takes the output of the first as input, etc. 64 times).
       w                   Write the final output to STDOUT

Predicate 1:

:3{...}.                   Call predicate 2 with input [Input, 3]. Its output is the
                           output of predicate 1.

Predicate 2:

[1:N],                     M = 1
      3:N^.                Output = 3^N
|                          Or
t1,                        N = 1
   3.                      Output = 3
|                          Or
hM:1-X,                    X is M - 1
       ?t:1-:Mr:2&         Unify an implicit variable with u(3,N-1,M)
                  :Xr:2&.  Unify Output with u(3,u(3,N-1,M),X)


Title: Theoretically output Graham's number

Body:
Graham's number G is defined in this way:

```<code>u(3,n,1) = 3^n
u(3,1,m) = 3
u(3,n,m) = u(3,u(3,n-1,m),m-1)
[Knuth's up-arrow notation]
[Conway chained arrow notation]

THEN

g1 = u(3,3,4)
g2 = u(3,3,g1)
g3 = u(3,3,g2)
...
G = u(3,3,g63)
</code>```

You are given that u(3,3,2)=7625597484987 to check your code.

Your task is to write a program/function that will output the value of G deterministically, given enough integer size and enough time.

References

Graham's number

Knuth's up-arrow notation

Conway chained arrow notation

Leaderboard

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

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

```

Body:
JavaScript (ES7), 63 bytes

u=(n,m)=>n>1&m>1?u(u(n-1,m),m-1):3**n
g=n=>n?u(3,g(n-1)):4
g(64)


答:
05AB1E, <s>35</s> 24 bytes

```<code>vy³ï‚{0è)˜}³ï‚˜¥²ø€PTn/O
</code>```

Explanation

```<code>vy                         # for each amount
  ³ï‚                      # pair with taxable income
     {0è                   # get min
        )˜}                # add to list
           ³ï‚˜            # add income to the end of the list
               ¥           # get deltas
                ²ø         # zip with tax rates
                  €P       # map product on each pair of [amount in tax bracket,rate]
                    Tn/    # divide by 100
                       O   # sum
                           # implicitly display result
</code>```

Try it online

Title: Build a marginal tax calculator

Body:
There have been some tax rate calculator problems here that depend on defined rates (specifically US federal rates), but none that have done it for arbitrary lists.

Your task is to build a program or function that will take an arbitrary list of marginal tax brackets and calculate the effective amount of tax paid on a given amount of taxable income.

Your program will take as input:

N pairs of numbers in the form (amt, rate), each representing a tax bracket.

amt is the amount of taxable income above which at which the tax rate starts to apply. These amounts will all be integers, and appear in increasing order.

rate is the tax rate, expressed as a decimal percentage from 0 to 100 inclusive.

The amount of taxable income, as a nonnegative integer.

If no rate is specified for $0, the rate is assumed to be 0%.

Alternatively, your program can also take as input two lists (amt1, amt2, ...) and (rate1, rate2, ...), containing the amounts and rates in the same order.

Your program will then output the payable tax, either to two decimal places, or rounded down to the nearest whole currency unit.

An example input (the most recent Canadian tax brackets, from 2016, with the basic personal tax credit applied and nothing else):

```<code>11474 15
45282 20.5
90563 26
140388 29
200000 33

393216
</code>```

And its corresponding output:

```<code>108357.07  or  108357
</code>```

The shortest program in any language to do this wins.

Body:
05AB1E, <s>35</s> 24 bytes

vy³ï‚{0è)˜}³ï‚˜¥²ø€PTn/O

Explanation

vy                         # for each amount
  ³ï‚                      # pair with taxable income
     {0è                   # get min
        )˜}                # add to list
           ³ï‚˜            # add income to the end of the list
               ¥           # get deltas
                ²ø         # zip with tax rates
                  €P       # map product on each pair of [amount in tax bracket,rate]
                    Tn/    # divide by 100
                       O   # sum
                           # implicitly display result

Try it online


答:
Haskell, 43 bytes

q=((!!).).iterate
g=q(`q`1)(3*)
q(`g`3)4$64
```
<p>There has be a better way to flip <code>g</code> inline.</p>
<p><strong>46 bytes:</strong></p>
<pre class="lang-haskell prettyprint-override"><code>i=iterate
n%0=3*n
n%m=i(%(m-1))1!!n
i(3%)4!!64
</code>```

48 bytes:

n%1=3^n
1%m=3
n%m=(n-1)%m%(m-1)
iterate(3%)4!!64
```
<p>Just writing down the definitions.</p>
<p>The base cases are a bit cleaner backed up to 0, though it saves no bytes. Perhaps it will make it easier to write an alternate definition.</p>
<pre class="lang-haskell prettyprint-override"><code>n%0=3*n
0%m=1
n%m=(n-1)%m%(m-1)
z=iterate(3%)2!!1
</code>```

Title: Theoretically output Graham's number

Body:
Haskell, 43 bytes

q=((!!).).iterate
g=q(`q`1)(3*)
q(`g`3)4$64

There has be a better way to flip g inline.

46 bytes:

i=iterate
n%0=3*n
n%m=i(%(m-1))1!!n
i(3%)4!!64

48 bytes:

n%1=3^n
1%m=3
n%m=(n-1)%m%(m-1)
iterate(3%)4!!64

Just writing down the definitions.

The base cases are a bit cleaner backed up to 0, though it saves no bytes. Perhaps it will make it easier to write an alternate definition.

n%0=3*n
0%m=1
n%m=(n-1)%m%(m-1)
z=iterate(3%)2!!1


问:
When does (x == x+2)?
The challenge: Define x in such a way that the expression (x == x+2) would evaluate to true.

I tagged the question with C, but answers in other languages are welcome, as long as they're creative or highlight an interesting aspect of the language.

I intend to accept a C solution, but other languages can get my vote.

Correct - works on standard-compliant implementations. Exception - assuming an implementation of the basic types, if it's a common implementation (e.g. assuming int is 32bit 2's complement) is OK.

Simple - should be small, use basic language features.

Interesting - it's subjective, I admit. I have some examples for what I consider interesting, but I don't want to give hints. Update: Avoiding the preprocessor is interesting.

Quick - The first good answer will be accepted.

After getting 60 answers (I never expected such prticipation), It may be good to summarize them.

The 60 answers divide into 7 groups, 3 of which can be implemented in C, the rest in other languages:

The C preprocessor. #define x 2|0 was suggested, but there are many other possibilities.

Floating point. Large numbers, infinity or NaN all work.

Pointer arithmetic. A pointer to a huge struct causes adding 2 to wrap around.

The rest don't work with C:

Operator overloading - A + that doesn't add or a == that always returns true.

Making x a function call (some languages allow it without the x() syntax). Then it can return something else each time.

A one-bit data type. Then x == x+2 (mod 2).

Changing 2 - some language let you assign 0 to it.

答:
Coffeescript, 18 chars

```<code>x=1/0;alert x==x+2
</code>```

Title: When does (x == x+2)?

Body:
Coffeescript, 18 chars

x=1/0;alert x==x+2


答:
Pyth, 25 bytes

```<code>M?H.UgbtH*G]3^3Gug3tG64 4
</code>```

The first part M?H.UgbtH*G]3^3G defines a method g(G,H) = u(3,G,H+1).

To test the first part, check that 7625597484987=u(3,3,2)=g(3,1): g3 1.

The second part ug3tG64 4 starts from r0 = 4 and then compute rn = u(3,3,r(n-1)) = g(3,r(n-1)) 64 times, outputting the final value (r is chosen instead of g to avoid confusion).

To test this part, start from r0=2 and then compute r1: ug3tG1 2.

Title: Theoretically output Graham's number

Body:
Pyth, 25 bytes

M?H.UgbtH*G]3^3Gug3tG64 4

The first part M?H.UgbtH*G]3^3G defines a method g(G,H) = u(3,G,H+1).

To test the first part, check that 7625597484987=u(3,3,2)=g(3,1): g3 1.

The second part ug3tG64 4 starts from r0 = 4 and then compute rn = u(3,3,r(n-1)) = g(3,r(n-1)) 64 times, outputting the final value (r is chosen instead of g to avoid confusion).

To test this part, start from r0=2 and then compute r1: ug3tG1 2.


答:
Javascript, <s>72</s> <s>66</s> 64 Bytes

```<code>f=
t=>t.replace(/k|f/g,'').replace(/\w/g,'y').replace(/\byy/g,'He')
</code>```

Edit: separated f= and function + reduced byte count

Body:
Javascript, <s>72</s> <s>66</s> 64 Bytes

f=
t=>t.replace(/k|f/g,'').replace(/\w/g,'y').replace(/\byy/g,'He')

Edit: separated f= and function + reduced byte count


答:
Lua, <s>67</s> <s>66</s> 61 Bytes

Simply iterate over each characters in the argument, and print a line for each one with n +s followed by .> where n is the value of this character in the ASCII Table.

Uses gmatch as @LeakyNun advised in the comment for saving 1 Bytes over the the gsub solution

for c in(...):gmatch"."do print(("+"):rep(c:byte())..".>")end
```
<p><strong>Old solution using gsub</strong></p>
<pre class="lang-lua prettyprint-override"><code>(...):gsub(".",function(c)print(c.rep("+",c:byte())..".>")end)
</code>```

Old 67

(...):gsub(".",function(c)print(string.rep("+",c:byte())..".>")end)
```
<p>To run it, just save it as a file (<code>golf.lua</code> for instance) and run it with <code>lua golf.lua "hi"</code>. For <code>hi</code>, it should output</p>
<pre class="lang-lua prettyprint-override"><code>++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.>
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.>
</code>```

Body:
Challenge

Write a program or function that given a string, returns a valid Brainfuck program that when compiled and executed as Brainfuck, returns that string..

Assume all inputs are encoded as ASCII.

Assume the outputted BF program will execute in an environment with an infinite tape.

Assume the pointer starts at cell 0 with every cell initialized to a value of zero.

Each example below represent one possible correct output for the given input. In particular, the examples include extra newlines and spaces to help human readability. Solutions are free to format the outputted BF code in any way.

The tape is doubly infinite.

All cells provided by the interpreter are exactly 8-bit cells. Overflow and underflow wrap around in a predictable and sane matter.

Examples

Space string

Given the input  , your program/function could return:

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

Exclamation point

Given the input ! , your program/function could return:

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

Two letters

Given the input hi , your program/function could return:

```<code>+++++ +++++
+++++ +++++
+++++ +++++
+++++ +++++
+++++ +++++

+++++ +++++
+++++ +++++
+++++ +++++
+++++ +++++
+++++ +++++

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

This is code-golf, so the code with the smallest number of bytes wins. Good luck.

Body:
Lua, <s>67</s> <s>66</s> 61 Bytes

Simply iterate over each characters in the argument, and print a line for each one with n +s followed by .> where n is the value of this character in the ASCII Table.

Uses gmatch as @LeakyNun advised in the comment for saving 1 Bytes over the the gsub solution

for c in(...):gmatch"."do print(("+"):rep(c:byte())..".>")end

Old solution using gsub

(...):gsub(".",function(c)print(c.rep("+",c:byte())..".>")end)

Old 67

(...):gsub(".",function(c)print(string.rep("+",c:byte())..".>")end)

To run it, just save it as a file (golf.lua for instance) and run it with lua golf.lua "hi". For hi, it should output

++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.>
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.>


答:
Haskell, 41 bytes

i=((!!).).iterate
i(($3).i(`i`1)(*3))4 64
```

Explanation:

(`i`1)f n = i f 1 n computes the nth iterate of the function f starting at 1.  In particular, (`i`1)(*3)n = 3^n, and iterating this construction m times gives i(`i`1)(*3)m n = u(3, n, m).  We can rewrite that as (($n).i(`i`1)(*3))m = u(3, n, m), and iterate this construction k times to get i(($3).i(`i`1)(*3))4 k = g_k.

Title: Theoretically output Graham's number

Body:
Haskell, 41 bytes

i=((!!).).iterate
i(($3).i(`i`1)(*3))4 64

Explanation:

(`i`1)f n = i f 1 n computes the nth iterate of the function f starting at 1.  In particular, (`i`1)(*3)n = 3^n, and iterating this construction m times gives i(`i`1)(*3)m n = u(3, n, m).  We can rewrite that as (($n).i(`i`1)(*3))m = u(3, n, m), and iterate this construction k times to get i(($3).i(`i`1)(*3))4 k = g_k.


答:
Python 3, <s>140</s> <s>135</s> 134 bytes

```<code>from re import*
f=lambda s:''.join('He'+'y'*len(x)+y for x,y in[(a+b+c,d)for a,b,c,d in findall('(?:Wo(o+)f|Gr(r+)|B(a+)rk)(\W+)',s)])
</code>```

Using regex to find occurences of replacable characters.

Edit: Golfed 1 byte whitespace and 4 bytes on getting the values from findall result.

Edit2: Golfed 1 byte (Bark's "a" was not counted properly)

Body:
Introduction

We -- especially the geeks among us, who tend to be fans -- all remember this old Far Side cartoon:

Clearly, Professor Schwartzman could have brushed up on his programming skills just a wee bit more before he put his invention to use. But can you replicate it yourself... using as few bytes as possible?

Input Specs

You must create a script that translates dog sounds into appropriately intonated "Hey"s. This is pure code golf; the lowest number of bytes wins.

Your input will consist of some combination of the following tokens:

Bark, Baark, Baaark, Baaaark, ... (that is, B*rk  with at least 1 a replacing the asterisk)

Woof, Wooof, Woooof, ... (W*f with at least 2 os replacing the asterisk)

Grr, Grrr, Grrrr, ..., (G followed by at least 2 rs)

Any number of . (period), ! (exclamation mark) and/or ? (question mark) characters, which may occur anywhere in the input

Note, again, that the Woof-based and Grr-based tokens always require at least two os and rs respectively; Wof and Gr are not valid tokens.

There is no limit on how long a token can be (e.g., how many repeated as there can be in a Bark token); however, your decoder only needs to work correctly for input tokens with up to 10 total as, os, or rs to pass this challenge.

Output Specs

Faithful to Schwartzman's design, your canine decoder program must process it into output text as follows:

Bark, Woof, and Grr become Hey;

Baark, Wooof, and Grrr become Heyy;

Baaark, Woooof, and Grrrr become Heyyy; etc.

For all Bark-based tokens, the number of ys in the output Hey-based token must be equal to the number of as;

For all Woof-based tokens, the number of ys in the output Hey-based token must be one less than the number of os;

For all Grr-based tokens, the number of ys in the output Hey-based token must be one less than the number of rs;

All punctuation (., !, and ?) is left unchanged.

Remember to drop one y from the output for Woofs and Grrs only! The input Baaaaaaaark?, with 8 as, will become Heyyyyyyyy?, with a matching set of 8 ys. However, Woooooooof? becomes only Heyyyyyyy?, with 7 ys.

Again, if you can get your program to work for input tokens of unlimited size, that's great, but for purposes of this challenge, your program will only be checked to ensure that it works properly for input tokens that have no more than 10 repeated letters.

All Bark-, Woof-, and Grr-based tokens in your input are assumed to begin with capital letters. Therefore, there is no need to handle turning Bark grrr into Hey heyy or anything similar.

Example Inputs and Outputs

Input: Bark. Bark! Bark!!

Output: Hey. Hey! Hey!!

Input: Baaaaaark? (six as)

Output: Heyyyyyy? (six ys)

Input: Grrrrrrrr... (eight rs)

Output: Heyyyyyyy... (seven ys)

Input: ?...!

Output: ?...!

Input: Wooof Woof? Grrrr. Baaaark Grr!

Output: Heyy Hey? Heyyy. Heyyyy Hey!

Body:
Python 3, <s>140</s> <s>135</s> 134 bytes

from re import*
f=lambda s:''.join('He'+'y'*len(x)+y for x,y in[(a+b+c,d)for a,b,c,d in findall('(?:Wo(o+)f|Gr(r+)|B(a+)rk)(\W+)',s)])

Using regex to find occurences of replacable characters.

Edit: Golfed 1 byte whitespace and 4 bytes on getting the values from findall result.

Edit2: Golfed 1 byte (Bark's "a" was not counted properly)


答:
JavaScript (ES6) - <s>57</s> <s>55</s> <s>52</s> 51 Bytes

```<code>f=s=>s.replace(/\wk?f?/g,'y').replace(/\byy/g,'He')
</code>```

Test:

f=s=>s.replace(/\wk?f?/g,'y').replace(/\byy/g,'He');

[
  'Bark. Bark! Bark!!',
  'Baaaaaark?',
  'Grrrrrrrr...',
  '?...!',
  'Wooof Woof? Grrrr. Baaaark Grr!'
].forEach( s=>{console.log( f(s) );} );```

Thanks to @MartinEnder for bytes 56 & 51 and the inspiration for some of the other shavings.

Body:
JavaScript (ES6) - <s>57</s> <s>55</s> <s>52</s> 51 Bytes

f=s=>s.replace(/\wk?f?/g,'y').replace(/\byy/g,'He')

Test:

f=s=>s.replace(/\wk?f?/g,'y').replace(/\byy/g,'He');

[
  'Bark. Bark! Bark!!',
  'Baaaaaark?',
  'Grrrrrrrr...',
  '?...!',
  'Wooof Woof? Grrrr. Baaaark Grr!'
].forEach( s=>{console.log( f(s) );} );

Thanks to @MartinEnder for bytes 56 & 51 and the inspiration for some of the other shavings.


问:
Merge two sorted lists

Merge Sort

In this challenge, you will implement the merge subroutine of merge sort. Specifically, you must create a function or program or verb or similar which takes two lists, each sorted in increasing order, and combines them into one list sorted in increasing order.
Requirements:

 - Your algorithm must take an asymptotically linear amount of time in the size of the input. Please stop giving O(n^2) solutions.

You may not use any built-in functions capable of sorting a list, or merging a list, or anything like that. Author's discretion.

The code should be able to handle repeated elements.

Don't worry about empty lists.

Examples:

```<code>merge([1],[0,2,3,4])
[0,1,2,3,4]

merge([1,5,10,17,19],[2,5,9,11,13,20])
[1, 2, 5, 5, 9, 10, 11, 13, 17, 19, 20]
</code>```

This is code-golf, so may the shortest code win!

答:
Mathematica, 104 bytes

```<code>Reap[{m,n}=Length/@{##};i=k=1;Do[If[k>n||TrueQ[#[[i]]<#2[[k]]],Sow@#[[i++]],Sow@#2[[k++]]],n+m]][[2,1]]&
</code>```

Anonymous function, stores the length of the two input lists in the variables m and n, then each iteration of the Do loop Sows an element of one the lists incrementing the counter for that list (i for the first, k for the second) by one. If one of the counters exceeds the length of the list, the If statement will always Sow the element from the other list. After n+m operations, all the elements have been taken care of. Reap or rather part [[2,1]] of its output is a list of elements in the order they have been Sown.

I'm not sure of the internals (is accessing a part of a list a O(1) operation or not), but timings looked quite linear on my machine with respect to input list length.

Title: Merge two sorted lists

Body:
Mathematica, 104 bytes

Reap[{m,n}=Length/@{##};i=k=1;Do[If[k>n||TrueQ[#[[i]]<#2[[k]]],Sow@#[[i++]],Sow@#2[[k++]]],n+m]][[2,1]]&

Anonymous function, stores the length of the two input lists in the variables m and n, then each iteration of the Do loop Sows an element of one the lists incrementing the counter for that list (i for the first, k for the second) by one. If one of the counters exceeds the length of the list, the If statement will always Sow the element from the other list. After n+m operations, all the elements have been taken care of. Reap or rather part [[2,1]] of its output is a list of elements in the order they have been Sown.

I'm not sure of the internals (is accessing a part of a list a O(1) operation or not), but timings looked quite linear on my machine with respect to input list length.


问:
Simplify a square root
Given a positive integer n, simplify the square root √n into the form a√b by extracting all square factors. The outputted a,b should be positive integers with n = a^2 * b with b as small as possible.

You may output a and b in either order in any reasonable format. You may not omit outputs of 1 as implicit.

The outputs for n=1..36 as (a,b):

```<code>1 (1, 1)
2 (1, 2)
3 (1, 3)
4 (2, 1)
5 (1, 5)
6 (1, 6)
7 (1, 7)
8 (2, 2)
9 (3, 1)
10 (1, 10)
11 (1, 11)
12 (2, 3)
13 (1, 13)
14 (1, 14)
15 (1, 15)
16 (4, 1)
17 (1, 17)
18 (3, 2)
19 (1, 19)
20 (2, 5)
21 (1, 21)
22 (1, 22)
23 (1, 23)
24 (2, 6)
25 (5, 1)
26 (1, 26)
27 (3, 3)
28 (2, 7)
29 (1, 29)
30 (1, 30)
31 (1, 31)
32 (4, 2)
33 (1, 33)
34 (1, 34)
35 (1, 35)
36 (6, 1)
</code>```

These are OEIS A000188 and A007913.

Related: A more complex version.

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

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

```

答:
Haskell, <s>43></s> 42 bytes

Brute force solution.

Saved 1 byte thanks to Xnor

f n=[(x,y)|y<-[1..],x<-[1..n],x*x*y==n]!!0
```

Title: Simplify a square root


Title: Evaluate a Stratego Battle

Body:
In the game Stratego, the main game mechanic is when you attack an opponent's piece with yours. In this challenge, you job is to simulate one of these battles and say who survives.

Specs

You will get as input a pair of string representing Stratego pieces. The pieces are one of "S 1 2 3 4 5 6 7 8 9 10 B" (S is the Spy, and B are bombs). The first of the pair will be the attacker, and the second the attacked.

Here are the rules for determining the results of a battle:

The higher number beats the lower number: ["4", "6"] -> ["6"].

If both are the same, then both die: ["7", "7"] -> [].

Spies are at the bottom, underneath even 1: ["S", "2"] -> ["2"].

However, if a spy attacks the 10, then the spy wins: ["S", "10"] -> ["S"].

But the normal rules still apply if the 10 is the one attacking: ["10", "S"] -> ["10"].

If anything attacks a bomb, the bomb wins: ["5", "B"] -> ["B"].

However, a miner (a 3), can defuse a bomb: ["3", "B"] -> ["3"].

A bomb will never be the attacker.

A spotter (a 1), can attack using the normal mechanism, but they can also try to "guess" the rank of the other player, which can be denoted with any sane notation.

If they guess correctly, the other piece dies: ["1(5)", "5"] -> ["1"].

If they guess wrong, nothing happens: ["1(3)", "5"] -> ["1", "5"].

Spotters can spot bombs: ["1(B)", "B"] -> ["1"].

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

(You can use the examples up there as test-cases, because I'm too lazy to put them all together in one list).

Body:
TSQL,  <s>162</s> 124 bytes

Golfed:

DECLARE @1 varchar(2)='1',@ varchar(2)='3',@s varchar(2)='4'

PRINT IIF(@s>'',IIF(@=@s,@1,@1+','+@),IIF(@1=@,'',IIF(@1+@
IN('S10','3B')or'S'=@,@1,IIF(@='B'or'S'=@1,@,IIF(@1/1<@,@1,@)))))

Ungolfed:

DECLARE
  @1 varchar(2)='1', -- first piece
  @  varchar(2)='3',  -- second piece
  @s varchar(2)='4'  -- spotter(only fill this value for spotters)

PRINT
  IIF(@s>'',
    IIF(@=@s,@1,@1+','+@),
      IIF(@1=@,'',
        IIF(@1+@ IN('S10','3B')or'S'=@,@1,
          IIF(@='B'or'S'=@1,@,
            IIF(@1/1<@,@1,@)))))

Fiddle


问:
When does Santa enter the basement? (AOC Day 1)
I'm reproducing the second part of the first day of Advent of Code, with permission from the creator.

Santa is trying to deliver presents in a large apartment building, but he can't find the right floor - the directions he got are a little confusing. He starts on the ground floor (floor 0) and then follows the instructions one character at a time.

An opening parenthesis, (, means he should go up one floor, and a closing parenthesis, ), means he should go down one floor.

The apartment building is very tall, and the basement is very deep; he will never find the top or bottom floors.

Given a set of instructions, find the position of the first character that causes him to enter the basement (floor -1).

As examples:

input ) causes him to enter the basement at character position 1.

input ()()) causes him to enter the basement at character position 5.

A long input is given here that should yield the solution 1797.

This is code golf, so the shortest solution wins!

答:
APL, 18 chars

```<code>{1⍳⍨¯1=+\¯1*')'=⍵}
</code>```

In English:

¯1*')'=⍵: -1 where input =")", 1 otherwise;

+\: running sum;

1⍳⍨¯1=: find the index of the first -1.

Body:
APL, 18 chars

{1⍳⍨¯1=+\¯1*')'=⍵}

In English:

¯1*')'=⍵: -1 where input =")", 1 otherwise;

+\: running sum;

1⍳⍨¯1=: find the index of the first -1.


答:
J, 43 characters

```<code>f=:3 :'<.@:+&0.5(p^2-p)*y^p-1[p=:(+%)/20$1'
</code>```

Defines a function using the asymptotic expression given on the wikipedia page.

```<code>   f 5
3
   f 20
8
   f 100000
1479
</code>```

Annoyingly 9 characters are used just rounding to the nearest integer.

Title: Calculate the nth term of Golomb's self-describing sequence

Body:
Inspired by the previous question.

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

The first few numbers in the sequence are:

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

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

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

Limitations: n < 100000.

Smallest code wins.

Body:
J, 43 characters

f=:3 :'<.@:+&0.5(p^2-p)*y^p-1[p=:(+%)/20$1'

Defines a function using the asymptotic expression given on the wikipedia page.

   f 5
3
   f 20
8
   f 100000
1479

Annoyingly 9 characters are used just rounding to the nearest integer.


Title: Simplify a square root

Body:
Given a positive integer n, simplify the square root √n into the form a√b by extracting all square factors. The outputted a,b should be positive integers with n = a^2 * b with b as small as possible.

You may output a and b in either order in any reasonable format. You may not omit outputs of 1 as implicit.

The outputs for n=1..36 as (a,b):

```<code>1 (1, 1)
2 (1, 2)
3 (1, 3)
4 (2, 1)
5 (1, 5)
6 (1, 6)
7 (1, 7)
8 (2, 2)
9 (3, 1)
10 (1, 10)
11 (1, 11)
12 (2, 3)
13 (1, 13)
14 (1, 14)
15 (1, 15)
16 (4, 1)
17 (1, 17)
18 (3, 2)
19 (1, 19)
20 (2, 5)
21 (1, 21)
22 (1, 22)
23 (1, 23)
24 (2, 6)
25 (5, 1)
26 (1, 26)
27 (3, 3)
28 (2, 7)
29 (1, 29)
30 (1, 30)
31 (1, 31)
32 (4, 2)
33 (1, 33)
34 (1, 34)
35 (1, 35)
36 (6, 1)
</code>```

These are OEIS A000188 and A007913.

Related: A more complex version.

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

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

```

Body:
Python 2.7 (ungolfed) - 181 Bytes

def e(n):
 for x in range(1,n+1):
  r=(1,x)
  for i in range(1,x+1):
   l=i**.5
   for j in range(1,x+1):
    if i*j==x and l%1==0 and j<r[1]:r=(int(l),j)
  print x,r

Run as: e(number) eg. e(24)

Sample output:

>> e(24)
1 (1, 1)
2 (1, 2)
3 (1, 3)
4 (2, 1)
5 (1, 5)
6 (1, 6)
7 (1, 7)
8 (2, 2)
9 (3, 1)
10 (1, 10)
11 (1, 11)
12 (2, 3)
13 (1, 13)
14 (1, 14)
15 (1, 15)
16 (4, 1)
17 (1, 17)
18 (3, 2)
19 (1, 19)
20 (2, 5)
21 (1, 21)
22 (1, 22)
23 (1, 23)
24 (2, 6)


Title: When does Santa enter the basement? (AOC Day 1)

Body:
I'm reproducing the second part of the first day of Advent of Code, with permission from the creator.

Santa is trying to deliver presents in a large apartment building, but he can't find the right floor - the directions he got are a little confusing. He starts on the ground floor (floor 0) and then follows the instructions one character at a time.

An opening parenthesis, (, means he should go up one floor, and a closing parenthesis, ), means he should go down one floor.

The apartment building is very tall, and the basement is very deep; he will never find the top or bottom floors.

Given a set of instructions, find the position of the first character that causes him to enter the basement (floor -1).

As examples:

input ) causes him to enter the basement at character position 1.

input ()()) causes him to enter the basement at character position 5.

A long input is given here that should yield the solution 1797.

This is code golf, so the shortest solution wins!

Body:
k/kona, <s>23</s> 21 bytes

2 bytes saved by removing unnecessary parentheses.

{1+(+\1 -1"()"?x)?-1}

Usage:

k){1+(+\1 -1"()"?x)?-1} "())"
3


答:
05AB1E, 14 bytes

```<code>Lv¹ynÖi¹yn/y‚ï
</code>```

Explained

```<code>Lv              # for each x in range(1,N) inclusive
  ¹ynÖi         # if N % x^2 == 0
       ¹yn/y‚ï  # create [N/x^2,x] pairs, N=12 -> [12,1] [3,2]
                # implicitly output last found pair
</code>```

Try it online

Title: Simplify a square root

Body:
05AB1E, 14 bytes

Lv¹ynÖi¹yn/y‚ï

Explained

Lv              # for each x in range(1,N) inclusive
  ¹ynÖi         # if N % x^2 == 0
       ¹yn/y‚ï  # create [N/x^2,x] pairs, N=12 -> [12,1] [3,2]
                # implicitly output last found pair

Try it online