答:
JavaScript (ES6), 54

p=>eval(0+p.map(v=>x+='*-+'[(p>v)+2*(p<v)]+(p=v),x=1))
```

<p><code>eval</code> receives a comma separated list of expressions and returns the value of the last one.</p>

<p><strong>Test</strong></p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>f=p=>eval(0+p.map(v=>x+='*-+'[(p>v)+2*(p<v)]+(p=v),x=1))

t=p=>(0+p.map(v=>x+='*-+'[(p>v)+2*(p<v)]+(p=v),x=1))

function Test() {
  var a=I.value.match(/\d+/g).map(x=>+x) // convert input to a numeric array

  var x=f(a),y=t(a)
  O.textContent='Value '+x+'\n(no eval '+y+')'
}

Test()</code>```

#I { width:80%}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input value='12, 0, 7, 7, 29, 10, 2, 2, 1' id=I>
<button onclick='Test()'>Test</button>
<pre id=O>``````

Title: Turn an Array into a Math Problem

Body:
JavaScript (ES6), 54

p=>eval(0+p.map(v=>x+='*-+'[(p>v)+2*(p<v)]+(p=v),x=1))

eval receives a comma separated list of expressions and returns the value of the last one.

Test

f=p=>eval(0+p.map(v=>x+='*-+'[(p>v)+2*(p<v)]+(p=v),x=1))

t=p=>(0+p.map(v=>x+='*-+'[(p>v)+2*(p<v)]+(p=v),x=1))

function Test() {
  var a=I.value.match(/\d+/g).map(x=>+x) // convert input to a numeric array

  var x=f(a),y=t(a)
  O.textContent='Value '+x+'\n(no eval '+y+')'
}

Test()

#I { width:80%}

<input value='12, 0, 7, 7, 29, 10, 2, 2, 1' id=I>
<button onclick='Test()'>Test</button>
<pre id=O></pre>


问:
Reverse stdin and place on stdout
Requirements:

Take an input on stdin including new lines / carriage returns of unlimited length (only bounded by system memory; that is, there is no inherent limit in the program.)

Output the reverse of the input on stdout.

Example:

Input:

```<code>Quick brown fox
He jumped over the lazy dog
</code>```

Output:

```<code>god yzal eht revo depmuj eH
xof nworb kciuQ
</code>```

Shortest wins.

Leaderboard:

var QUESTION_ID=242,OVERRIDE_USER=61563;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

```

答:
Stack Cats, 7 bytes

```<code><!]T[!>
</code>```

Try it online!

There's a bunch of alternatives for the same byte count, most of which are essentially equivalent in how they work:

Explanation

A short Stack Cats primer:

Every program has to have mirror symmetry, and by mirroring any piece of code we obtain new code which computes the inverse function. Therefore the last three characters of the program above undo the first three, if it wasn't for the command in the centre.

The memory model is an infinite tape of stacks, which hold an implicit, infinite amount of zeros at the bottom. The initial stack has a -1 on top of those zeros and then the input bytes on top of that (with the first byte at the very top and the last byte above the -1).

For output, we simply take the final stack, discard a -1 at the bottom if there is one, and then print all the values as bytes to STDOUT.

Now for the actual program:

```<code><    Move the tape head one stack left (onto an empty stack).
!    Bitwise NOT of the implicit zero on top, giving -1.
]    Move back to the original stack, taking the -1 with the tape head.
     We're now back to the original situation, except that we have a -1
     on top.
T    Reverse the stack down to the -1 at the bottom. One of the reasons
     we needed to move a -1 on top is that T only works when the top of
     the stack is nonzero. Since the first byte of the input could have
     been a null-byte we need the -1 to make sure this does anything at
     all.
[    Push the -1 to the stack on the left.
!    Bitwise NOT, turning it back into 0 (this is irrelevant).
>    Move the tape head back onto the original stack.
</code>```

Sp3000 set his brute force search to find all other 7-byte solutions, so here are some alternatives:

```<code><]!T![>
>![T]!<
>[!T!]<
</code>```

These three variants are essentially the same, except that they differ in when the bitwise NOT is computed and whether we use the empty stack on the left or on the right.

```<code><]T!T[>
>[T!T]<
</code>```

Like I said in the explanation above, T doesn't do anything when the top of the stack is zero. That means we can actually put the ! in the middle instead. That means the first T is a no-op, then we turn the zero on top into a -1 and then then second T performs the reversal. Of course, this means that the final memory state has a -1 on the stack next to the original one, but that doesn't matter since only the stack at the current tape head position affects the output.

```<code><*ITI*>
</code>```

This variant uses * (XOR 1) instead of !, so that it turns the zero into +1, and the I is a conditional push which pushes positive values and right, negative values left, and negates them in either case (such that we still end up with a -1 on top of the original stack when we encounter T), so this ultimately works the same as the original <!]T[!> solution.

ContentLicense: CC BY-SA 3.0

Title: Reverse stdin and place on stdout

Body:
Stack Cats, 7 bytes

<!]T[!>

Try it online!

There's a bunch of alternatives for the same byte count, most of which are essentially equivalent in how they work:

Explanation

A short Stack Cats primer:

Every program has to have mirror symmetry, and by mirroring any piece of code we obtain new code which computes the inverse function. Therefore the last three characters of the program above undo the first three, if it wasn't for the command in the centre.

The memory model is an infinite tape of stacks, which hold an implicit, infinite amount of zeros at the bottom. The initial stack has a -1 on top of those zeros and then the input bytes on top of that (with the first byte at the very top and the last byte above the -1).

For output, we simply take the final stack, discard a -1 at the bottom if there is one, and then print all the values as bytes to STDOUT.

Now for the actual program:

<    Move the tape head one stack left (onto an empty stack).
!    Bitwise NOT of the implicit zero on top, giving -1.
]    Move back to the original stack, taking the -1 with the tape head.
     We're now back to the original situation, except that we have a -1
     on top.
T    Reverse the stack down to the -1 at the bottom. One of the reasons
     we needed to move a -1 on top is that T only works when the top of
     the stack is nonzero. Since the first byte of the input could have
     been a null-byte we need the -1 to make sure this does anything at
     all.
[    Push the -1 to the stack on the left.
!    Bitwise NOT, turning it back into 0 (this is irrelevant).
>    Move the tape head back onto the original stack.

Sp3000 set his brute force search to find all other 7-byte solutions, so here are some alternatives:

<]!T![>
>![T]!<
>[!T!]<

These three variants are essentially the same, except that they differ in when the bitwise NOT is computed and whether we use the empty stack on the left or on the right.

<]T!T[>
>[T!T]<

Like I said in the explanation above, T doesn't do anything when the top of the stack is zero. That means we can actually put the ! in the middle instead. That means the first T is a no-op, then we turn the zero on top into a -1 and then then second T performs the reversal. Of course, this means that the final memory state has a -1 on the stack next to the original one, but that doesn't matter since only the stack at the current tape head position affects the output.

<*ITI*>

This variant uses * (XOR 1) instead of !, so that it turns the zero into +1, and the I is a conditional push which pushes positive values and right, negative values left, and negates them in either case (such that we still end up with a -1 on top of the original stack when we encounter T), so this ultimately works the same as the original <!]T[!> solution.


问:
Turn an Array into a Math Problem
Given a nonempty list of nonnegative integers, consider rewriting it as an arithmetic problem where:

A plus sign (+) is inserted between pairs of numbers that increase from left to right (a.k.a. from the start of the list to the end).

A minus sign (-) is inserted between pairs of numbers that decrease from left to right.

A multiplication sign (*) is inserted between pairs of numbers that are equal.

Said another way: any sublist a,b becomes a+b if a<b, a-b if  a>b, and a*b if a==b.

For example, the list

```<code>[12, 0, 7, 7, 29, 10, 2, 2, 1]
</code>```

would become the expression

```<code>12 - 0 + 7*7 + 29 - 10 - 2*2 - 1
</code>```

which evaluates to 75.

Write a program or function that takes in such a list and evaluates it, printing or returning the result.

Order of operations matters. Multiplications should be done before any addition or subtraction.

If the input list has one number, that should be what it evaluates to. e.g. [64] should give 64.

Use of eval or exec or similar constructs is allowed.

Here are some additional examples:

```<code>[list]
expression
value

[0]
0
0

[1]
1
1

[78557]
78557
78557

[0,0]
0*0
0

[1,1]
1*1
1

[2,2]
2*2
4

[0,1]
0+1
1

[1,0]
1-0
1

[1,2]
1+2
3

[2,1]
2-1
1

[15,4,4]
15-4*4
-1

[9,8,1]
9-8-1
0

[4,2,2,4]
4-2*2+4
4

[10,9,9,12]
10-9*9+12
-59

[1,1,2,2,3,3]
1*1+2*2+3*3
14

[5,5,4,4,3,3]
5*5-4*4-3*3
0

[3,1,4,1,5,9,2,6,5,3,5,9]
3-1+4-1+5+9-2+6-5-3+5+9
29

[7637,388,389,388,387,12,0,0,34,35,35,27,27,2]
7637-388+389-388-387-12-0*0+34+35*35-27*27-2
7379
</code>```

The shortest code in bytes wins. Tiebreaker is earlier answer.

答:
Perl, 49 bytes

48 bytes code + 1 for -p

s/\d+ (?=(\d+))/$&.qw(* - +)[$&<=>$1]/ge;$_=eval
```

<h3>Usage</h3>

<pre class="lang-sh prettyprint-override"><code>perl -pe 's/\d+ (?=(\d+))/$&.qw(* - +)[$&<=>$1]/ge;$_=eval' <<< '12 0 7 7 29 10 2 2 1'
75
</code>```

Notes

I learnt here that you can capture a lookahead in PCRE, although it's a little unintuitive ((?=(\d+)) instead of ((?=\d+))). It does make sense after reading though as you would be capturing a zero-length match (the lookahead) with the latter, and instead capture the match with the former).

Thanks to @ninjalj for saving 8 bytes!

Title: Turn an Array into a Math Problem

Body:
Perl, 49 bytes

48 bytes code + 1 for -p

s/\d+ (?=(\d+))/$&.qw(* - +)[$&<=>$1]/ge;$_=eval

Usage

perl -pe 's/\d+ (?=(\d+))/$&.qw(* - +)[$&<=>$1]/ge;$_=eval' <<< '12 0 7 7 29 10 2 2 1'
75

Notes

I learnt here that you can capture a lookahead in PCRE, although it's a little unintuitive ((?=(\d+)) instead of ((?=\d+))). It does make sense after reading though as you would be capturing a zero-length match (the lookahead) with the latter, and instead capture the match with the former).

Thanks to @ninjalj for saving 8 bytes!


Title: Turn an Array into a Math Problem

Body:
Given a nonempty list of nonnegative integers, consider rewriting it as an arithmetic problem where:

A plus sign (+) is inserted between pairs of numbers that increase from left to right (a.k.a. from the start of the list to the end).

A minus sign (-) is inserted between pairs of numbers that decrease from left to right.

A multiplication sign (*) is inserted between pairs of numbers that are equal.

Said another way: any sublist a,b becomes a+b if a<b, a-b if  a>b, and a*b if a==b.

For example, the list

```<code>[12, 0, 7, 7, 29, 10, 2, 2, 1]
</code>```

would become the expression

```<code>12 - 0 + 7*7 + 29 - 10 - 2*2 - 1
</code>```

which evaluates to 75.

Write a program or function that takes in such a list and evaluates it, printing or returning the result.

Order of operations matters. Multiplications should be done before any addition or subtraction.

If the input list has one number, that should be what it evaluates to. e.g. [64] should give 64.

Use of eval or exec or similar constructs is allowed.

Here are some additional examples:

```<code>[list]
expression
value

[0]
0
0

[1]
1
1

[78557]
78557
78557

[0,0]
0*0
0

[1,1]
1*1
1

[2,2]
2*2
4

[0,1]
0+1
1

[1,0]
1-0
1

[1,2]
1+2
3

[2,1]
2-1
1

[15,4,4]
15-4*4
-1

[9,8,1]
9-8-1
0

[4,2,2,4]
4-2*2+4
4

[10,9,9,12]
10-9*9+12
-59

[1,1,2,2,3,3]
1*1+2*2+3*3
14

[5,5,4,4,3,3]
5*5-4*4-3*3
0

[3,1,4,1,5,9,2,6,5,3,5,9]
3-1+4-1+5+9-2+6-5-3+5+9
29

[7637,388,389,388,387,12,0,0,34,35,35,27,27,2]
7637-388+389-388-387-12-0*0+34+35*35-27*27-2
7379
</code>```

The shortest code in bytes wins. Tiebreaker is earlier answer.

Body:
Javascript ES6, 79 chars

a=>eval(`${a}`.replace(/(\d+),(?=(\d+))/g,(m,a,b)=>a+('*+-'[+a<+b|(+a>+b)*2])))


Title: Turn an Array into a Math Problem

Body:
Javascript ES6, <s>64</s> 62 chars

a=>eval(a.map((x,i)=>x+('*+-'[x<a[++i]|(x>a[i])*2])).join``+1)


答:
MATL, 12 bytes

```<code>Y'^l6MdZSh*s
</code>```

This uses @aditsu's very nice idea of run-length encoding.

Try it online!

Explanation

```<code>       % Take input vector implicitly
Y'     % RLE. Produces two vectors: values and lengths
^      % Rise each value to the number of consecutive times it appears. This
       % realizes the product of consecutive equal values
l      % Push 1
6M     % Push vector of values again
d      % Consecutive differences
ZS     % Sign function. Gives 1 or -1 (no 0 in this case)
h      % Concatenate horizontally with previous 1
*      % Multiply. This gives plus or minus depending on increasing character
s      % Sum of vector. This realizes the additions or subtractions
       % Display implicitly
</code>```

Title: Turn an Array into a Math Problem

Body:
MATL, 12 bytes

Y'^l6MdZSh*s

This uses @aditsu's very nice idea of run-length encoding.

Try it online!

Explanation

       % Take input vector implicitly
Y'     % RLE. Produces two vectors: values and lengths
^      % Rise each value to the number of consecutive times it appears. This
       % realizes the product of consecutive equal values
l      % Push 1
6M     % Push vector of values again
d      % Consecutive differences
ZS     % Sign function. Gives 1 or -1 (no 0 in this case)
h      % Concatenate horizontally with previous 1
*      % Multiply. This gives plus or minus depending on increasing character
s      % Sum of vector. This realizes the additions or subtractions
       % Display implicitly


问:
Approximation of e
We all know that the Euler's number, denoted by \$e\$, to the power of some variable \$x\$, can be approximated by using the Maclaurin Series expansion:

$$e^x=\sum_{k=0}^{\infty}{\frac{x^k}{k!}}=1+x+\frac{x^2}{2!}+\frac{x^3}{3!}+\frac{x^4}{4!}+\dots$$

By letting \$x\$ equal \$1\$, we obtain

$$\sum_{k=0}^{\infty}{\frac{1}{k!}{=\frac{1}{0!}+\frac{1}{1!}+\frac{1}{2!}+\frac{1}{3!}+\frac{1}{4!}+\dots\\=1+1+\frac{1}{2}+\frac{1}{6}+\frac{1}{24}+\dots}}$$

Challenge

Write a program in any language which approximates Euler's number by taking in an input \$n\$ and calculates the series to the \$n\$th term. Note that the first term has denominator \$0!\$, not \$1!\$, i.e. \$n=1\$ corresponds to \$\frac{1}{0!}\$.

Scoring

Program with least amount of bytes wins.

ContentLicense: CC BY-SA 4.0

Title: Approximation of e

Body:
Haskell, 37 bytes

((scanl(+)0$(1/)<$>scanl(*)1[1..])!!)

Not the shortest, but arguably the prettiest.

Also courtesy of Laikoni, here is a solution that is 2 bytes shorter:

sum.(`take`((1/)<$>scanl(*)1[1..]))

λ> let f = ((scanl (+) 0 $ (1/) <$> scanl (*) 1 [1..]) !!)

λ> map f [1..5]
[1.0,2.0,2.5,2.6666666666666665,2.708333333333333]

λ> f 10
2.7182815255731922

λ> f 100
2.7182818284590455

λ> log (f 10)
0.9999998885745155

λ> log (f 100)
1.0


问:
Write a program that reverses the name of its source file
In a single file, write a program that requires no input and produces no output. When run it should reverse the name of the file it is contained in, regardless of what the name is, without altering the code or producing other lasting side effects.

Any way of achieving this is fine. It only matters that once the program is run the only lasting change is that its file name has been reversed. e.g. no new files should be in the directory.

Running the program again should reverse the name back. Indeed, the program should be able to be run arbitrarily many times.

For the purposes of this challenge:

You may assume filenames are always strings of lowercase letters (a-z) between 1 and 127 characters long. (If your language requires files to have extensions to run then just reverse the part before the extension, e.g. mycode.bat → edocym.bat.)

You may assume the code file is in a directory by itself so it will not have naming conflicts (except with itself).

You may not assume the filename is not a palindrome, i.e. the same when reversed. Filenames that are palindromes should work just as well as those that aren't.

You may read your file's contents or metadata. There are no quine restrictions here.

You may assume your program will be run on a particular, modern, commonplace operating system (e.g. Windows/Linux), since not all shells have the same command set.

As a concrete example, say you have a Python program in a file called
  mycode in its own directory. Running

```<code>python mycode
</code>```

in the terminal should result in the filename being reversed to
  edocym. The file edocym should be alone in its directory - no file
  named mycode should exist anymore. Running

```<code>python edocym
</code>```

will reverse the name back to mycode, at which point the process can
  be repeated indefinitely.

If the same Python file was renamed racecar (without changing the code) and then run

```<code>python racecar
</code>```

nothing should visibly change since "racecar" is a palindrome.
  That same goes if the filename were, say, a or xx.

The shortest code in bytes wins. Tiebreaker is higher voted answer.

答:
C#,  153 bytes

```<code>void f(){var x=System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name;File.Move(x,new string(x.Reverse().ToArray()).Substring(4)+".exe");}
</code>```

OO is cool and all untill you have a variable defined:

System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name

thats just mean

Body:
C#,  153 bytes

void f(){var x=System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name;File.Move(x,new string(x.Reverse().ToArray()).Substring(4)+".exe");}

OO is cool and all untill you have a variable defined:

System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name

thats just mean


答:
Perl 5, 18 bytes

A bit like the Ruby one (run perl nameofscript):

```<code>rename$0,reverse$0
</code>```

Taking a possible path into account is uglier (47 bytes)

```<code>($a,$b)=$0=~/(.*\/)?(.*)/;rename$0,$a.reverse$b
</code>```

Title: Write a program that reverses the name of its source file

Body:
In a single file, write a program that requires no input and produces no output. When run it should reverse the name of the file it is contained in, regardless of what the name is, without altering the code or producing other lasting side effects.

Any way of achieving this is fine. It only matters that once the program is run the only lasting change is that its file name has been reversed. e.g. no new files should be in the directory.

Running the program again should reverse the name back. Indeed, the program should be able to be run arbitrarily many times.

For the purposes of this challenge:

You may assume filenames are always strings of lowercase letters (a-z) between 1 and 127 characters long. (If your language requires files to have extensions to run then just reverse the part before the extension, e.g. mycode.bat → edocym.bat.)

You may assume the code file is in a directory by itself so it will not have naming conflicts (except with itself).

You may not assume the filename is not a palindrome, i.e. the same when reversed. Filenames that are palindromes should work just as well as those that aren't.

You may read your file's contents or metadata. There are no quine restrictions here.

You may assume your program will be run on a particular, modern, commonplace operating system (e.g. Windows/Linux), since not all shells have the same command set.

As a concrete example, say you have a Python program in a file called
  mycode in its own directory. Running

```<code>python mycode
</code>```

in the terminal should result in the filename being reversed to
  edocym. The file edocym should be alone in its directory - no file
  named mycode should exist anymore. Running

```<code>python edocym
</code>```

will reverse the name back to mycode, at which point the process can
  be repeated indefinitely.

If the same Python file was renamed racecar (without changing the code) and then run

```<code>python racecar
</code>```

nothing should visibly change since "racecar" is a palindrome.
  That same goes if the filename were, say, a or xx.

The shortest code in bytes wins. Tiebreaker is higher voted answer.

Body:
Perl 5, 18 bytes

A bit like the Ruby one (run perl nameofscript):

rename$0,reverse$0

Taking a possible path into account is uglier (47 bytes)

($a,$b)=$0=~/(.*\/)?(.*)/;rename$0,$a.reverse$b


答:
Python (2 & 3), 88 78 bytes

```<code>import os;os.rename(__file__,''.join(reversed(__file__.split(".")[0]))+".py"))
</code>```

Exploits the fact that the filename is given by sys.argv (as the working directory is the folder the file is in), and makes use of os.rename. Annoyingly, reversed returns an iterator, so we have to use join.

Edit: Saved 10 bytes by using __file__ instead of sys.argv[0], as suggested by @muddyfish to @DigitalTrauma.

Body:
Python (2 & 3), 88 78 bytes

import os;os.rename(__file__,''.join(reversed(__file__.split(".")[0]))+".py"))

Exploits the fact that the filename is given by sys.argv (as the working directory is the folder the file is in), and makes use of os.rename. Annoyingly, reversed returns an iterator, so we have to use join.

Edit: Saved 10 bytes by using __file__ instead of sys.argv[0], as suggested by @muddyfish to @DigitalTrauma.


问:
Tips for golfing in Mathematica
What general tips do you have for golfing in Mathematica? I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to Mathematica (e.g. "remove comments" is not an answer). </p>

答:
Operators as Functions

Inspired by Dennis's recent discovery for Julia I thought I'd look into this for Mathematica. I was aware that Mathematica defines a large number of unused operators, but never paid much attention to it.

For reference, the list of all operators can be found here in the form of a precedence table. The triangle in the last column indicates whether that operator has a built-in meaning or not. While not all of those that don't can be defined easily, most of them can.

Conveniently, there are two unused operators with a codepoint less than 256, such that they can be used as single bytes in an ISO 8859-1 encoded source file:

± (0xB1) can be used either as a unary prefix operator or a binary infix operator.

· (0xB7) can be used as a variadic or n-ary infix operator, for n > 2.

There's one more catch though: for some weird reason when defining these operators you need one space in front of them, or else Mathematica tries to parse a multiplication. When using them you don't need any spaces though:

```<code>±x_:=2x
x_ ±y_:=x+y
x_ ·y_ ·z_:=x*y+z
Print[±5]  (* 10 *)
Print[3±4] (*  7 *)
Print[3·4·5] (* 17 *)
</code>```

Compare this with:

```<code>f@x_:=2x
x_~g~y_:=x+y
h[x_,y_,z_]:=x*y+z
Print[f@5]   (* 10 *)
Print[3~g~4] (*  7 *)
Print[h[x,y,z]] (* 17 *)
</code>```

So this saves one byte when defining the function and two bytes when using it. Note that the definition of · will not save bytes for four operands and will start costing bytes for more operands, but the usage may still save bytes, depending the precedence of operators used in the arguments. It's also good to note that you can cheaply define a variadic function that can then be called much more efficiently:

```<code>x_ ·y__:={y}
Print[1·2·3·4·5] (* {2, 3, 4, 5} *)
</code>```

But note that it's not easily possible to call these variadic functions with a single argument. (You could do CenterDot[x] or ##&[]·x but if you actually need that there's a good chance you're better off with a different solution.)

Of course, this isn't saving anything for solutions where an unnamed function suffices, but sometimes you need to define helper functions for use later on, and sometimes it's shorter to define named functions e.g. to set up different definitions for different parameters. In those cases, using an operator instead can save a decent amount of bytes.

Note that using these ISO 8859-1 encoded files requires $CharacterEncoding to be set to a compatible value, like the Windows default WindowsANSI. On some systems this defaults to UTF-8 which won't be able to read these code points from single bytes.

Title: Tips for golfing in Mathematica

Body:
Operators as Functions

Inspired by Dennis's recent discovery for Julia I thought I'd look into this for Mathematica. I was aware that Mathematica defines a large number of unused operators, but never paid much attention to it.

For reference, the list of all operators can be found here in the form of a precedence table. The triangle in the last column indicates whether that operator has a built-in meaning or not. While not all of those that don't can be defined easily, most of them can.

Conveniently, there are two unused operators with a codepoint less than 256, such that they can be used as single bytes in an ISO 8859-1 encoded source file:

± (0xB1) can be used either as a unary prefix operator or a binary infix operator.

· (0xB7) can be used as a variadic or n-ary infix operator, for n > 2.

There's one more catch though: for some weird reason when defining these operators you need one space in front of them, or else Mathematica tries to parse a multiplication. When using them you don't need any spaces though:

±x_:=2x
x_ ±y_:=x+y
x_ ·y_ ·z_:=x*y+z
Print[±5]  (* 10 *)
Print[3±4] (*  7 *)
Print[3·4·5] (* 17 *)

Compare this with:

f@x_:=2x
x_~g~y_:=x+y
h[x_,y_,z_]:=x*y+z
Print[f@5]   (* 10 *)
Print[3~g~4] (*  7 *)
Print[h[x,y,z]] (* 17 *)

So this saves one byte when defining the function and two bytes when using it. Note that the definition of · will not save bytes for four operands and will start costing bytes for more operands, but the usage may still save bytes, depending the precedence of operators used in the arguments. It's also good to note that you can cheaply define a variadic function that can then be called much more efficiently:

x_ ·y__:={y}
Print[1·2·3·4·5] (* {2, 3, 4, 5} *)

But note that it's not easily possible to call these variadic functions with a single argument. (You could do CenterDot[x] or ##&[]·x but if you actually need that there's a good chance you're better off with a different solution.)

Of course, this isn't saving anything for solutions where an unnamed function suffices, but sometimes you need to define helper functions for use later on, and sometimes it's shorter to define named functions e.g. to set up different definitions for different parameters. In those cases, using an operator instead can save a decent amount of bytes.

Note that using these ISO 8859-1 encoded files requires $CharacterEncoding to be set to a compatible value, like the Windows default WindowsANSI. On some systems this defaults to UTF-8 which won't be able to read these code points from single bytes.


答:
Julia, <s>76</s> 57 bytes

```<code>!x=[[" ""-*+"[2+sign(diff(x))]...] x]'|>join|>parse|>eval
</code>```

My first time golfing Julia, so maybe there are obvious improvements.
Try it online!

Dennis saved a ton of bytes.

Title: Turn an Array into a Math Problem

Body:
Julia, <s>76</s> 57 bytes

!x=[[" ""-*+"[2+sign(diff(x))]...] x]'|>join|>parse|>eval

My first time golfing Julia, so maybe there are obvious improvements.
Try it online!

Dennis saved a ton of bytes.


答:
C, 102 bytes

main(c,v)char**v;{char*b=strdup(*v),*n=strrchr(*v,47),*t=strchr(b,0);for(;*++n;*--t=*n);rename(*v,b);}
```

<p>Breakdown:</p>

<pre class="lang-c prettyprint-override"><code>                            // No #include lines required (for GCC at least)
main(c,v)char**v;{          // K&R style function to save 2 bytes
    char*b=strdup(*v),      // Duplicate args[0] (script path)
        *n=strrchr(*v,47),  // Find last "/" in input
        *t=strchr(b,0);     // Go to end of output string
    for(;*++n;*--t=*n);     // Reverse input into output character-by-character
    rename(*v,b);           // Rename the file
}                           // Implicit return 0
</code>```

Finally a challenge where C isn't (quite so hopelessly) uncompetitive!

If we take "You can assume the working directory of the shell will be the folder the file is in" to mean that the program will always be invoked as ./myexecutable, we can simplify *n=strrchr(*v,47) to *n=*v+1 to save 10 characters, but this isn't entirely valid (it could be invoked as ././myexecutable, for example).

Also if you want to keep a file extension (e.g. ".out") in-tact, you can change *t=strchr(b,0) to *t=strrchr(b,46), costing 2 bytes. Not required though.

Body:
C, 102 bytes

main(c,v)char**v;{char*b=strdup(*v),*n=strrchr(*v,47),*t=strchr(b,0);for(;*++n;*--t=*n);rename(*v,b);}

Breakdown:

                            // No #include lines required (for GCC at least)
main(c,v)char**v;{          // K&R style function to save 2 bytes
    char*b=strdup(*v),      // Duplicate args[0] (script path)
        *n=strrchr(*v,47),  // Find last "/" in input
        *t=strchr(b,0);     // Go to end of output string
    for(;*++n;*--t=*n);     // Reverse input into output character-by-character
    rename(*v,b);           // Rename the file
}                           // Implicit return 0

Finally a challenge where C isn't (quite so hopelessly) uncompetitive!

If we take "You can assume the working directory of the shell will be the folder the file is in" to mean that the program will always be invoked as ./myexecutable, we can simplify *n=strrchr(*v,47) to *n=*v+1 to save 10 characters, but this isn't entirely valid (it could be invoked as ././myexecutable, for example).

Also if you want to keep a file extension (e.g. ".out") in-tact, you can change *t=strchr(b,0) to *t=strrchr(b,46), costing 2 bytes. Not required though.


答:
PHP, 103 bytes

Neat challenge. This got longer than expected. I think using array_map or similar won't improve the byte count, as anonymous functions are still expensive in PHP.

```<code>foreach(fgetcsv(STDIN)as$v)(0<=$p?$o.=$p.('*-+'[($p>$v)+2*($p<$v)]):_)&&$p=$v;echo eval("return$o$v;");
</code>```

Runs from command line, will prompt for a comma separated list, like:

```<code>php array_to_math.php
12, 0, 7, 7, 29, 10, 2, 2, 1
</code>```

Title: Turn an Array into a Math Problem

Body:
PHP, 103 bytes

Neat challenge. This got longer than expected. I think using array_map or similar won't improve the byte count, as anonymous functions are still expensive in PHP.

foreach(fgetcsv(STDIN)as$v)(0<=$p?$o.=$p.('*-+'[($p>$v)+2*($p<$v)]):_)&&$p=$v;echo eval("return$o$v;");

Runs from command line, will prompt for a comma separated list, like:

php array_to_math.php
12, 0, 7, 7, 29, 10, 2, 2, 1


答:
C, 249 bytes

```<code>#include <stdio.h>
#include <stdlib.h>
#define z double
z f(z x){z r=1;z n=1;while(x>0){r*=n;n++;x--;}return r;}int main(int argc, char **argv){z e=0;z p=0;z d=0;p=strtod(argv[1],NULL);while(p>0){e+=1.0d/f(d);printf("%.10f\n",e);p--;d++;}return 0;}
</code>```

Ungolfed:

```<code>/* approximate e */

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

double fact(double x){
    double result = 1;
    double num = 1;

    while (x > 0){
        result *= num;
        num++;
        x--;
    }
    return result;
}

int main(int argc, char **argv){
    double e = 0;
    double precision = 0;
    double denom = 0;

    precision = strtod(argv[1], NULL);
    while (precision > 0){
        e += 1.0d / fact(denom);
        printf("%.10f\n", e);
        precision--;
        denom++;
    }
    return 0;
}
</code>```

Takes a number as an argument to determine number of iterations.

Title: Approximation of e

Body:
We all know that the Euler's number, denoted by \$e\$, to the power of some variable \$x\$, can be approximated by using the Maclaurin Series expansion:

$$e^x=\sum_{k=0}^{\infty}{\frac{x^k}{k!}}=1+x+\frac{x^2}{2!}+\frac{x^3}{3!}+\frac{x^4}{4!}+\dots$$

By letting \$x\$ equal \$1\$, we obtain

$$\sum_{k=0}^{\infty}{\frac{1}{k!}{=\frac{1}{0!}+\frac{1}{1!}+\frac{1}{2!}+\frac{1}{3!}+\frac{1}{4!}+\dots\\=1+1+\frac{1}{2}+\frac{1}{6}+\frac{1}{24}+\dots}}$$

Challenge

Write a program in any language which approximates Euler's number by taking in an input \$n\$ and calculates the series to the \$n\$th term. Note that the first term has denominator \$0!\$, not \$1!\$, i.e. \$n=1\$ corresponds to \$\frac{1}{0!}\$.

Scoring

Program with least amount of bytes wins.

Body:
C, 249 bytes

#include <stdio.h>
#include <stdlib.h>
#define z double
z f(z x){z r=1;z n=1;while(x>0){r*=n;n++;x--;}return r;}int main(int argc, char **argv){z e=0;z p=0;z d=0;p=strtod(argv[1],NULL);while(p>0){e+=1.0d/f(d);printf("%.10f\n",e);p--;d++;}return 0;}

Ungolfed:

/* approximate e */

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

double fact(double x){
    double result = 1;
    double num = 1;

    while (x > 0){
        result *= num;
        num++;
        x--;
    }
    return result;
}

int main(int argc, char **argv){
    double e = 0;
    double precision = 0;
    double denom = 0;

    precision = strtod(argv[1], NULL);
    while (precision > 0){
        e += 1.0d / fact(denom);
        printf("%.10f\n", e);
        precision--;
        denom++;
    }
    return 0;
}

Takes a number as an argument to determine number of iterations.


问:
Distance between two points in n-dimensional space
Here is another simple one:

The Challenge

Given two points in an n-dimensional space, output the distance between them, also called the Euclidean distance.

The coordinates will be rational numbers; the only limits are the restrictions of your language.

Lowest dimension is 1, highest is whatever your language can handle

You may assume that the two points are of the same dimension and that there will be no empty input.

The distance has to be correct to at least 3 decimal places. If your language does not support floating point numbers, output the nearest whole number.

Rules

As usual, function or full program allowed.

Input may be taken from STDIN, command line- or function arguments.

Input format is up to you, specify which one you used in your answer.

Output may be provided by printing to stdout or return value.

This is code-golf so lowest byte-count wins! In case of a tie, the earlier answer wins.

Test cases

Each point is represented by a list of length n.

```<code>[1], [3] -> 2
[1,1], [1,1] -> 0
[1,2], [3,4] -> 2.82842712475
[1,2,3,4], [5,6,7,8] -> 8
[1.5,2,-5], [-3.45,-13,145] -> 150.829382085
[13.37,2,6,-7], [1.2,3.4,-5.6,7.89] -> 22.5020221314
</code>```

Happy Coding!

Body:
Haskell, 32 bytes

((sqrt.sum.map(^2)).).zipWith(-)

λ> let d = ((sqrt.sum.map(^2)).).zipWith(-)
λ> d [1] [3]
2.0
λ> d [1,1] [1,1]
0.0
λ> d [1,2] [3,4]
2.8284271247461903
λ> d [1..4] [5..8]
8.0
λ> d [1.5,2,-5] [-3.45,-13,145]
150.82938208452623
λ> d [13.37,2,6,-7] [1.2,3.4,-5.6,7.89]
22.50202213135522


问:
An Old Irish Blessing
I don't know who coined these words, and I'm not Irish, but I give you an Irish blessing:

```<code>May the road rise up to meet you
May the wind be always at your back
May the sun shine warm upon your face
The rains fall soft upon your fields
And until we meet again
May God hold you in the hollow of His hand
</code>```

I was planning on posting this a few weeks from now, but it just dawned on me that yesterday was Saint Patrick's Day.

Rules:

Produce the above text exactly.

(Feel free to break this rule for the sake of cleverness and amusement.)

The program must generate the text on its own accord.  cat is not a valid solution.

The solution with the fewest characters "wins".

I saw slight variations in wording among versions of the blessing I obtained from the Internet, so I tried to average them out.  Please use the version posted above.  Also, I dropped the punctuation to make it a bit easier.

May the luck of the Irish enfold you.

答:
INTERCALL, 3421 bytes

A simple solution.
Genered automatically, if anyone is wondering...

```<code>INTERCALL IS A ANTIGOLFING LANGUAGE
SO THIS HEADER IS HERE TO PREVENT GOLFING IN INTERCALL
THE PROGRAM STARTS HERE:
PUSH LXXVII
PRINT
PUSH XCVII
PRINT
PUSH CXXI
PRINT
PUSH XXXII
PRINT
PUSH CXVI
PRINT
PUSH CIV
PRINT
PUSH CI
PRINT
PUSH XXXII
PRINT
PUSH CXIV
PRINT
PUSH CXI
PRINT
PUSH XCVII
PRINT
PUSH C
PRINT
PUSH XXXII
PRINT
PUSH CXIV
PRINT
PUSH CV
PRINT
PUSH CXV
PRINT
PUSH CI
PRINT
PUSH XXXII
PRINT
PUSH CXVII
PRINT
PUSH CXII
PRINT
PUSH XXXII
PRINT
PUSH CXVI
PRINT
PUSH CXI
PRINT
PUSH XXXII
PRINT
PUSH CIX
PRINT
PUSH CI
PRINT
PUSH CI
PRINT
PUSH CXVI
PRINT
PUSH XXXII
PRINT
PUSH CXXI
PRINT
PUSH CXI
PRINT
PUSH CXVII
PRINT
PUSH X
PRINT
PUSH LXXVII
PRINT
PUSH XCVII
PRINT
PUSH CXXI
PRINT
PUSH XXXII
PRINT
PUSH CXVI
PRINT
PUSH CIV
PRINT
PUSH CI
PRINT
PUSH XXXII
PRINT
PUSH CXIX
PRINT
PUSH CV
PRINT
PUSH CX
PRINT
PUSH C
PRINT
PUSH XXXII
PRINT
PUSH XCVIII
PRINT
PUSH CI
PRINT
PUSH XXXII
PRINT
PUSH XCVII
PRINT
PUSH CVIII
PRINT
PUSH CXIX
PRINT
PUSH XCVII
PRINT
PUSH CXXI
PRINT
PUSH CXV
PRINT
PUSH XXXII
PRINT
PUSH XCVII
PRINT
PUSH CXVI
PRINT
PUSH XXXII
PRINT
PUSH CXXI
PRINT
PUSH CXI
PRINT
PUSH CXVII
PRINT
PUSH CXIV
PRINT
PUSH XXXII
PRINT
PUSH XCVIII
PRINT
PUSH XCVII
PRINT
PUSH XCIX
PRINT
PUSH CVII
PRINT
PUSH X
PRINT
PUSH LXXVII
PRINT
PUSH XCVII
PRINT
PUSH CXXI
PRINT
PUSH XXXII
PRINT
PUSH CXVI
PRINT
PUSH CIV
PRINT
PUSH CI
PRINT
PUSH XXXII
PRINT
PUSH CXV
PRINT
PUSH CXVII
PRINT
PUSH CX
PRINT
PUSH XXXII
PRINT
PUSH CXV
PRINT
PUSH CIV
PRINT
PUSH CV
PRINT
PUSH CX
PRINT
PUSH CI
PRINT
PUSH XXXII
PRINT
PUSH CXIX
PRINT
PUSH XCVII
PRINT
PUSH CXIV
PRINT
PUSH CIX
PRINT
PUSH XXXII
PRINT
PUSH CXVII
PRINT
PUSH CXII
PRINT
PUSH CXI
PRINT
PUSH CX
PRINT
PUSH XXXII
PRINT
PUSH CXXI
PRINT
PUSH CXI
PRINT
PUSH CXVII
PRINT
PUSH CXIV
PRINT
PUSH XXXII
PRINT
PUSH CII
PRINT
PUSH XCVII
PRINT
PUSH XCIX
PRINT
PUSH CI
PRINT
PUSH X
PRINT
PUSH LXXXIV
PRINT
PUSH CIV
PRINT
PUSH CI
PRINT
PUSH XXXII
PRINT
PUSH CXIV
PRINT
PUSH XCVII
PRINT
PUSH CV
PRINT
PUSH CX
PRINT
PUSH CXV
PRINT
PUSH XXXII
PRINT
PUSH CII
PRINT
PUSH XCVII
PRINT
PUSH CVIII
PRINT
PUSH CVIII
PRINT
PUSH XXXII
PRINT
PUSH CXV
PRINT
PUSH CXI
PRINT
PUSH CII
PRINT
PUSH CXVI
PRINT
PUSH XXXII
PRINT
PUSH CXVII
PRINT
PUSH CXII
PRINT
PUSH CXI
PRINT
PUSH CX
PRINT
PUSH XXXII
PRINT
PUSH CXXI
PRINT
PUSH CXI
PRINT
PUSH CXVII
PRINT
PUSH CXIV
PRINT
PUSH XXXII
PRINT
PUSH CII
PRINT
PUSH CV
PRINT
PUSH CI
PRINT
PUSH CVIII
PRINT
PUSH C
PRINT
PUSH CXV
PRINT
PUSH X
PRINT
PUSH LXV
PRINT
PUSH CX
PRINT
PUSH C
PRINT
PUSH XXXII
PRINT
PUSH CXVII
PRINT
PUSH CX
PRINT
PUSH CXVI
PRINT
PUSH CV
PRINT
PUSH CVIII
PRINT
PUSH XXXII
PRINT
PUSH CXIX
PRINT
PUSH CI
PRINT
PUSH XXXII
PRINT
PUSH CIX
PRINT
PUSH CI
PRINT
PUSH CI
PRINT
PUSH CXVI
PRINT
PUSH XXXII
PRINT
PUSH XCVII
PRINT
PUSH CIII
PRINT
PUSH XCVII
PRINT
PUSH CV
PRINT
PUSH CX
PRINT
PUSH X
PRINT
PUSH LXXVII
PRINT
PUSH XCVII
PRINT
PUSH CXXI
PRINT
PUSH XXXII
PRINT
PUSH LXXI
PRINT
PUSH CXI
PRINT
PUSH C
PRINT
PUSH XXXII
PRINT
PUSH CIV
PRINT
PUSH CXI
PRINT
PUSH CVIII
PRINT
PUSH C
PRINT
PUSH XXXII
PRINT
PUSH CXXI
PRINT
PUSH CXI
PRINT
PUSH CXVII
PRINT
PUSH XXXII
PRINT
PUSH CV
PRINT
PUSH CX
PRINT
PUSH XXXII
PRINT
PUSH CXVI
PRINT
PUSH CIV
PRINT
PUSH CI
PRINT
PUSH XXXII
PRINT
PUSH CIV
PRINT
PUSH CXI
PRINT
PUSH CVIII
PRINT
PUSH CVIII
PRINT
PUSH CXI
PRINT
PUSH CXIX
PRINT
PUSH XXXII
PRINT
PUSH CXI
PRINT
PUSH CII
PRINT
PUSH XXXII
PRINT
PUSH LXXII
PRINT
PUSH CV
PRINT
PUSH CXV
PRINT
PUSH XXXII
PRINT
PUSH CIV
PRINT
PUSH XCVII
PRINT
PUSH CX
PRINT
PUSH C
PRINT
END
</code>```

Wow

ContentLicense: CC BY-SA 2.5

Title: An Old Irish Blessing

Body:
INTERCALL, 3421 bytes

A simple solution.
Genered automatically, if anyone is wondering...

INTERCALL IS A ANTIGOLFING LANGUAGE
SO THIS HEADER IS HERE TO PREVENT GOLFING IN INTERCALL
THE PROGRAM STARTS HERE:
PUSH LXXVII
PRINT
PUSH XCVII
PRINT
PUSH CXXI
PRINT
PUSH XXXII
PRINT
PUSH CXVI
PRINT
PUSH CIV
PRINT
PUSH CI
PRINT
PUSH XXXII
PRINT
PUSH CXIV
PRINT
PUSH CXI
PRINT
PUSH XCVII
PRINT
PUSH C
PRINT
PUSH XXXII
PRINT
PUSH CXIV
PRINT
PUSH CV
PRINT
PUSH CXV
PRINT
PUSH CI
PRINT
PUSH XXXII
PRINT
PUSH CXVII
PRINT
PUSH CXII
PRINT
PUSH XXXII
PRINT
PUSH CXVI
PRINT
PUSH CXI
PRINT
PUSH XXXII
PRINT
PUSH CIX
PRINT
PUSH CI
PRINT
PUSH CI
PRINT
PUSH CXVI
PRINT
PUSH XXXII
PRINT
PUSH CXXI
PRINT
PUSH CXI
PRINT
PUSH CXVII
PRINT
PUSH X
PRINT
PUSH LXXVII
PRINT
PUSH XCVII
PRINT
PUSH CXXI
PRINT
PUSH XXXII
PRINT
PUSH CXVI
PRINT
PUSH CIV
PRINT
PUSH CI
PRINT
PUSH XXXII
PRINT
PUSH CXIX
PRINT
PUSH CV
PRINT
PUSH CX
PRINT
PUSH C
PRINT
PUSH XXXII
PRINT
PUSH XCVIII
PRINT
PUSH CI
PRINT
PUSH XXXII
PRINT
PUSH XCVII
PRINT
PUSH CVIII
PRINT
PUSH CXIX
PRINT
PUSH XCVII
PRINT
PUSH CXXI
PRINT
PUSH CXV
PRINT
PUSH XXXII
PRINT
PUSH XCVII
PRINT
PUSH CXVI
PRINT
PUSH XXXII
PRINT
PUSH CXXI
PRINT
PUSH CXI
PRINT
PUSH CXVII
PRINT
PUSH CXIV
PRINT
PUSH XXXII
PRINT
PUSH XCVIII
PRINT
PUSH XCVII
PRINT
PUSH XCIX
PRINT
PUSH CVII
PRINT
PUSH X
PRINT
PUSH LXXVII
PRINT
PUSH XCVII
PRINT
PUSH CXXI
PRINT
PUSH XXXII
PRINT
PUSH CXVI
PRINT
PUSH CIV
PRINT
PUSH CI
PRINT
PUSH XXXII
PRINT
PUSH CXV
PRINT
PUSH CXVII
PRINT
PUSH CX
PRINT
PUSH XXXII
PRINT
PUSH CXV
PRINT
PUSH CIV
PRINT
PUSH CV
PRINT
PUSH CX
PRINT
PUSH CI
PRINT
PUSH XXXII
PRINT
PUSH CXIX
PRINT
PUSH XCVII
PRINT
PUSH CXIV
PRINT
PUSH CIX
PRINT
PUSH XXXII
PRINT
PUSH CXVII
PRINT
PUSH CXII
PRINT
PUSH CXI
PRINT
PUSH CX
PRINT
PUSH XXXII
PRINT
PUSH CXXI
PRINT
PUSH CXI
PRINT
PUSH CXVII
PRINT
PUSH CXIV
PRINT
PUSH XXXII
PRINT
PUSH CII
PRINT
PUSH XCVII
PRINT
PUSH XCIX
PRINT
PUSH CI
PRINT
PUSH X
PRINT
PUSH LXXXIV
PRINT
PUSH CIV
PRINT
PUSH CI
PRINT
PUSH XXXII
PRINT
PUSH CXIV
PRINT
PUSH XCVII
PRINT
PUSH CV
PRINT
PUSH CX
PRINT
PUSH CXV
PRINT
PUSH XXXII
PRINT
PUSH CII
PRINT
PUSH XCVII
PRINT
PUSH CVIII
PRINT
PUSH CVIII
PRINT
PUSH XXXII
PRINT
PUSH CXV
PRINT
PUSH CXI
PRINT
PUSH CII
PRINT
PUSH CXVI
PRINT
PUSH XXXII
PRINT
PUSH CXVII
PRINT
PUSH CXII
PRINT
PUSH CXI
PRINT
PUSH CX
PRINT
PUSH XXXII
PRINT
PUSH CXXI
PRINT
PUSH CXI
PRINT
PUSH CXVII
PRINT
PUSH CXIV
PRINT
PUSH XXXII
PRINT
PUSH CII
PRINT
PUSH CV
PRINT
PUSH CI
PRINT
PUSH CVIII
PRINT
PUSH C
PRINT
PUSH CXV
PRINT
PUSH X
PRINT
PUSH LXV
PRINT
PUSH CX
PRINT
PUSH C
PRINT
PUSH XXXII
PRINT
PUSH CXVII
PRINT
PUSH CX
PRINT
PUSH CXVI
PRINT
PUSH CV
PRINT
PUSH CVIII
PRINT
PUSH XXXII
PRINT
PUSH CXIX
PRINT
PUSH CI
PRINT
PUSH XXXII
PRINT
PUSH CIX
PRINT
PUSH CI
PRINT
PUSH CI
PRINT
PUSH CXVI
PRINT
PUSH XXXII
PRINT
PUSH XCVII
PRINT
PUSH CIII
PRINT
PUSH XCVII
PRINT
PUSH CV
PRINT
PUSH CX
PRINT
PUSH X
PRINT
PUSH LXXVII
PRINT
PUSH XCVII
PRINT
PUSH CXXI
PRINT
PUSH XXXII
PRINT
PUSH LXXI
PRINT
PUSH CXI
PRINT
PUSH C
PRINT
PUSH XXXII
PRINT
PUSH CIV
PRINT
PUSH CXI
PRINT
PUSH CVIII
PRINT
PUSH C
PRINT
PUSH XXXII
PRINT
PUSH CXXI
PRINT
PUSH CXI
PRINT
PUSH CXVII
PRINT
PUSH XXXII
PRINT
PUSH CV
PRINT
PUSH CX
PRINT
PUSH XXXII
PRINT
PUSH CXVI
PRINT
PUSH CIV
PRINT
PUSH CI
PRINT
PUSH XXXII
PRINT
PUSH CIV
PRINT
PUSH CXI
PRINT
PUSH CVIII
PRINT
PUSH CVIII
PRINT
PUSH CXI
PRINT
PUSH CXIX
PRINT
PUSH XXXII
PRINT
PUSH CXI
PRINT
PUSH CII
PRINT
PUSH XXXII
PRINT
PUSH LXXII
PRINT
PUSH CV
PRINT
PUSH CXV
PRINT
PUSH XXXII
PRINT
PUSH CIV
PRINT
PUSH XCVII
PRINT
PUSH CX
PRINT
PUSH C
PRINT
END

Wow


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

```

答:
INTERCALL, 133 bytes

wat

```<code>INTERCALL IS A ANTIGOLFING LANGUAGE
SO THIS HEADER IS HERE TO PREVENT GOLFING IN INTERCALL
THE PROGRAM STARTS HERE:
READ
PRINT
GOTO I
</code>```

Title: Simple cat program

Body:
INTERCALL, 133 bytes

wat

INTERCALL IS A ANTIGOLFING LANGUAGE
SO THIS HEADER IS HERE TO PREVENT GOLFING IN INTERCALL
THE PROGRAM STARTS HERE:
READ
PRINT
GOTO I


问:
Calculate the number of primes up to n
π(n) is the number of primes less than or equal to n.

Input: a natural number, n.

Output:  π(n).

Scoring: This is a fastest-code challenge. Score will be the sum of times for the score cases. I will time each entry on my computer.

Rules and Details

Your code should work for n up to 2 billion ( 2,000,000,000 ).

Built-ins that trivialize this are not allowed. This includes built in π functions or lists of values for π(n).

Built-ins that test primality or generate primes are not allowed. This includes lists of primes, which  may not be looked up externally or hardcoded locally, except with regards to the next bullet point.

You may hardcode primes up to and including  19  and no higher.

your implementation of π should be deterministic. This means that given a specific n, your code should run in (approximately) the same amount of time.

Languages used must be freely available on Linux (Centos 7). Instructions should be included on how to run your code. Include compiler/interpreter details if necessary.

Official times will be from my computer.

When posting, please include a self-measured time on some/all of the test/score cases, just to give me an estimate of how fast your code is running.

Submissions must fit in an answer post to this question.

I am running 64bit centos7. I only have 8GB of RAM
and 1GB swap. The cpu model is: AMD FX(tm)-6300 Six-Core Processor.

Test cases(source):

```<code>Input        Output
90           24
3000         430
9000         1117
4000000      283146           <--- input = 4*10^6
800000000    41146179         <--- input = 9*10^8
1100000000   55662470         <--- input = 1.1*10^9
</code>```

Score Cases (same source)

As usual, these cases are subject to change. Optimizing for the scoring cases is not permitted. I may also change the number of cases in an effort to balance reasonable run times and accurate results.

```<code>Input        Output
1907000000   93875448         <--- input = 1.907*10^9
1337000000   66990613         <--- input = 1.337*10^9
1240000000   62366021         <--- input = 1.24*10^9
660000000    34286170         <--- input = 6.6*10^8
99820000     5751639          <--- input = 9.982*10^7
40550000     2465109          <--- input = 4.055*10^7
24850000     1557132          <--- input = 2.485*10^7
41500        4339
</code>```

Duration

Since this is a fastest-code challenge and entries are to be run on my computer, I reserve the right to stop timing entries after 2 weeks. After this point, entries are still accepted, but there is no guarantee that they are officially timed.

Having said this, I don't expect too many answers to this challenge and I will likely continue to time new answers indefinitely.

Scoring Particulars

I timed the faster entries with the following script:

```<code>#!/bin/bash

a=(1907000000 1337000000 1240000000 660000000 99820000 40550000 24850000 41500)

echo DennisC
exec 2>> times/dennisc.txt
time for j in ${a[@]}; do ./dennisc $j; done >> /dev/null;

echo DennisPy
exec 2>> times/dennispy.txt
time for j in ${a[@]}; do pypy dennispy.py <<< $j; done >> /dev/null;

echo arjandelumens
exec 2>> times/arjandelumens.txt
time for j in ${a[@]}; do ./arjandelumens $j; done >> /dev/null;

echo orlp
exec 2>> times/orlp.txt
time for j in ${a[@]}; do ./orlp $j; done >> /dev/null;

# echo mwr247
# time node-v4.3.1-linux-x64/bin/node mwr247.js

# mwr247 using js seems a bit longer, so I am going to run the fastest
# and then come back to his.

# mwr247 provided a function, so I appended
# console.log( F( <argument> ) )
# to his code, for each argument.
</code>```

time writes to stderr, so I sent stderr to a log file using exec 2 >> <filename>. You may notice that stdout is sent to /dev/null. This isn't a problem, because I already verified that the programs were producing the correct output.

I ran the above timeall.sh script 10 times using for i in {1..10}; do ./timeall.sh; done;

I then averaged the real time score for each entry.

Note that no other programs were running on my computer while timing.

Also, the official times have been appended to each entry. Please double check your own average.

答:
Rust, 0.37001 sec (12 June 2016)

About 10 times slower than slower than Dennis' C answer, but 10 times faster than his Python entry. This answer is made possible by @Shepmaster and @Veedrac who helped improve it on Code Review. It is taken verbatim from @Veedrac's post.

```<code>use std::env;

const EMPTY: usize = std::usize::MAX;
const MAX_X: usize = 800;

fn main() {
    let args: Vec<_> = env::args().collect();
    let x: usize = args[1].trim().parse().expect("expected a number");

    let root = (x as f64).sqrt() as usize;
    let y = (x as f64).powf(0.3333333333333) as usize + 1;

    let sieve_size = x / y + 2;
    let mut sieve = vec![true; sieve_size];
    let mut primes = vec![0; sieve_size];
    sieve[0] = false;
    sieve[1] = false;

    let mut a = 0;
    let mut num_primes = 1;

    let mut num_primes_smaller_root = 0;

    // find all primes up to x/y ~ x^2/3 aka sieve_size
    for i in 2..sieve_size {
        if sieve[i] {
            if i <= root {
                if i <= y {
                    a += 1;
                }
                num_primes_smaller_root += 1;
            }

            primes[num_primes] = i;
            num_primes += 1;
            let mut multiples = i;
            while multiples < sieve_size {
                sieve[multiples] = false;
                multiples += i;
            }
        }
    }

    let interesting_primes = primes[a + 1..num_primes_smaller_root + 1].iter();

    let p_2 =
        interesting_primes
        .map(|ip| primes.iter().take_while(|&&p| p <= x / ip).count())
        .enumerate()
        .map(|(i, v)| v - 1 - i - a)
        .fold(0, |acc, v| acc + v);

    let mut phi_results = vec![EMPTY; (a + 1) * MAX_X];
    println!("pi({}) = {}", x, phi(x, a, &primes, &mut phi_results) + a - 1 - p_2);
}

fn phi(x: usize, b: usize, primes: &[usize], phi_results: &mut [usize]) -> usize {
    if b == 0 {
        return x;
    }

    if x < MAX_X && phi_results[x + b * MAX_X] != EMPTY {
        return phi_results[x + b * MAX_X];
    }

    let value = phi(x, b - 1, primes, phi_results) - phi(x / primes[b], b - 1, primes, phi_results);
    if x < MAX_X {
        phi_results[x + b * MAX_X] = value;
    }
    value
}
</code>```

Timed with: time ./time.sh where time.sh looks like:

```<code>#!/bin/bash

a=(1907000000 1337000000 1240000000 660000000 99820000 40550000 24850000 41500)

for i in {0..100}; do
    for j in ${a[@]}; do
        ./target/release/pi_n $j  > /dev/null;
    done;
done;
</code>```

Here is the output.

```<code>[me@localhost pi_n]$ time ./time.sh

real    0m37.011s
user    0m34.752s
sys 0m2.410s
</code>```

Title: Calculate the number of primes up to n

Body:
Rust, 0.37001 sec (12 June 2016)

About 10 times slower than slower than Dennis' C answer, but 10 times faster than his Python entry. This answer is made possible by @Shepmaster and @Veedrac who helped improve it on Code Review. It is taken verbatim from @Veedrac's post.

use std::env;

const EMPTY: usize = std::usize::MAX;
const MAX_X: usize = 800;

fn main() {
    let args: Vec<_> = env::args().collect();
    let x: usize = args[1].trim().parse().expect("expected a number");

    let root = (x as f64).sqrt() as usize;
    let y = (x as f64).powf(0.3333333333333) as usize + 1;

    let sieve_size = x / y + 2;
    let mut sieve = vec![true; sieve_size];
    let mut primes = vec![0; sieve_size];
    sieve[0] = false;
    sieve[1] = false;

    let mut a = 0;
    let mut num_primes = 1;

    let mut num_primes_smaller_root = 0;

    // find all primes up to x/y ~ x^2/3 aka sieve_size
    for i in 2..sieve_size {
        if sieve[i] {
            if i <= root {
                if i <= y {
                    a += 1;
                }
                num_primes_smaller_root += 1;
            }

            primes[num_primes] = i;
            num_primes += 1;
            let mut multiples = i;
            while multiples < sieve_size {
                sieve[multiples] = false;
                multiples += i;
            }
        }
    }

    let interesting_primes = primes[a + 1..num_primes_smaller_root + 1].iter();

    let p_2 =
        interesting_primes
        .map(|ip| primes.iter().take_while(|&&p| p <= x / ip).count())
        .enumerate()
        .map(|(i, v)| v - 1 - i - a)
        .fold(0, |acc, v| acc + v);

    let mut phi_results = vec![EMPTY; (a + 1) * MAX_X];
    println!("pi({}) = {}", x, phi(x, a, &primes, &mut phi_results) + a - 1 - p_2);
}

fn phi(x: usize, b: usize, primes: &[usize], phi_results: &mut [usize]) -> usize {
    if b == 0 {
        return x;
    }

    if x < MAX_X && phi_results[x + b * MAX_X] != EMPTY {
        return phi_results[x + b * MAX_X];
    }

    let value = phi(x, b - 1, primes, phi_results) - phi(x / primes[b], b - 1, primes, phi_results);
    if x < MAX_X {
        phi_results[x + b * MAX_X] = value;
    }
    value
}

Timed with: time ./time.sh where time.sh looks like:

#!/bin/bash

a=(1907000000 1337000000 1240000000 660000000 99820000 40550000 24850000 41500)

for i in {0..100}; do
    for j in ${a[@]}; do
        ./target/release/pi_n $j  > /dev/null;
    done;
done;

Here is the output.

[me@localhost pi_n]$ time ./time.sh

real    0m37.011s
user    0m34.752s
sys 0m2.410s


问:
7-segment differences
I think most people around here know what a 7-segment display for digits is:

```<code> _         _   _         _    _    _    _    _
| |    |   _|  _|  |_|  |_   |_     |  |_|  |_|
|_|    |  |_   _|    |   _|  |_|    |  |_|   _|
</code>```

We can define the 7-segment difference (7SD) between two digits to be the number of segments that need to be toggled to switch from one to the other. E.g. the 7SD between 1 and 2 is 5 (the three horizontal segments and the lower two vertical segments need to be toggled), and the 7SD between 6 and 8 is 1.

Furthermore, we can define the 7SD between two numbers to be the sum of 7SDs between their corresponding digits. If one number is longer than the other, we assume they are right-aligned and add the number of segments needed to display the additional most-significant digits of the larger number. As an example, consider the 7SD between 12345 and 549:

```<code>  x:  1 2 3 4 5
  y:      5 4 9
7SD:  2+5+2+0+1 = 10
</code>```

Your task is to compute 7SD between n and n+1, given n.

For convenience, here is the full table of 7SDs between individual digits. The row _ represents an empty position.

```<code>   _ 0 1 2 3 4 5 6 7 8 9

_  0 6 2 5 5 4 5 6 3 7 6
0  6 0 4 3 3 4 3 2 3 1 2
1  2 4 0 5 3 2 5 6 1 5 4
2  5 3 5 0 2 5 4 3 4 2 3
3  5 3 3 2 0 3 2 3 2 2 1
4  4 4 2 5 3 0 3 4 3 3 2
5  5 3 5 4 2 3 0 1 4 2 1
6  6 2 6 3 3 4 1 0 5 1 2
7  3 3 1 4 2 3 4 5 0 4 3
8  7 1 5 2 2 3 2 1 4 0 1
9  6 2 4 3 1 2 1 2 3 1 0
</code>```

Input

Input is a single positive integer n.

You may write a program or function, taking input via STDIN (or closest alternative), command-line argument or function argument.

You may assume that the input is at most one less than the largest number which can be represented by your language's standard integer type, as long as that type supports at least values up to and including 127.

Output

You should print a single integer, the 7SD between n and n+1.

You may output via STDOUT (or closest alternative), function return value or function (out) argument.

Scoring

Standard code-golf rules apply, shortest code (in bytes) wins.

Test Cases

For some obscure reason, this sequence isn't in OEIS yet, although there is the closely related sequence A123587. Here are the first 100 numbers (starting with n = 1, 2, 3, ...):

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

The first input for which the 7SD is greater than 9 is 1999 which should yield 11. Here are some other larger examples:

```<code>n          7SD
1999        11
12345        1
999999      14
5699999     15
8765210248   1
</code>```

Title: 7-segment differences

Body:
JavaScript (ES6), <s>46</s> 40 bytes

f=n=>n?+"452331541"[n%10]||f(n/10|0)+2:2

Alternative formulation, also <s>46</s> 40 bytes:

f=n=>n?26523308>>n%10*3&7||f(n/10|0)+2:2

Edit: Saved 6 bytes thanks to @xsot.


答:
Pyth - <s>78</s> <s>30</s> 27 bytes

That first one was embarrassing.

```<code>s@LjC"
(J"ThC{I#.tjRThBQT
</code>```

Test Suite.

Title: 7-segment differences

Body:
I think most people around here know what a 7-segment display for digits is:

```<code> _         _   _         _    _    _    _    _
| |    |   _|  _|  |_|  |_   |_     |  |_|  |_|
|_|    |  |_   _|    |   _|  |_|    |  |_|   _|
</code>```

We can define the 7-segment difference (7SD) between two digits to be the number of segments that need to be toggled to switch from one to the other. E.g. the 7SD between 1 and 2 is 5 (the three horizontal segments and the lower two vertical segments need to be toggled), and the 7SD between 6 and 8 is 1.

Furthermore, we can define the 7SD between two numbers to be the sum of 7SDs between their corresponding digits. If one number is longer than the other, we assume they are right-aligned and add the number of segments needed to display the additional most-significant digits of the larger number. As an example, consider the 7SD between 12345 and 549:

```<code>  x:  1 2 3 4 5
  y:      5 4 9
7SD:  2+5+2+0+1 = 10
</code>```

Your task is to compute 7SD between n and n+1, given n.

For convenience, here is the full table of 7SDs between individual digits. The row _ represents an empty position.

```<code>   _ 0 1 2 3 4 5 6 7 8 9

_  0 6 2 5 5 4 5 6 3 7 6
0  6 0 4 3 3 4 3 2 3 1 2
1  2 4 0 5 3 2 5 6 1 5 4
2  5 3 5 0 2 5 4 3 4 2 3
3  5 3 3 2 0 3 2 3 2 2 1
4  4 4 2 5 3 0 3 4 3 3 2
5  5 3 5 4 2 3 0 1 4 2 1
6  6 2 6 3 3 4 1 0 5 1 2
7  3 3 1 4 2 3 4 5 0 4 3
8  7 1 5 2 2 3 2 1 4 0 1
9  6 2 4 3 1 2 1 2 3 1 0
</code>```

Input

Input is a single positive integer n.

You may write a program or function, taking input via STDIN (or closest alternative), command-line argument or function argument.

You may assume that the input is at most one less than the largest number which can be represented by your language's standard integer type, as long as that type supports at least values up to and including 127.

Output

You should print a single integer, the 7SD between n and n+1.

You may output via STDOUT (or closest alternative), function return value or function (out) argument.

Scoring

Standard code-golf rules apply, shortest code (in bytes) wins.

Test Cases

For some obscure reason, this sequence isn't in OEIS yet, although there is the closely related sequence A123587. Here are the first 100 numbers (starting with n = 1, 2, 3, ...):

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

The first input for which the 7SD is greater than 9 is 1999 which should yield 11. Here are some other larger examples:

```<code>n          7SD
1999        11
12345        1
999999      14
5699999     15
8765210248   1
</code>```

Body:
Pyth - <s>78</s> <s>30</s> 27 bytes

That first one was embarrassing.

s@LjC"
(J"ThC{I#.tjRThBQT

Test Suite.


答:
MATL, <s>61</s> <s>39</s> 36 bytes

```<code>tQvV15\'3dAsMh818RG5'6Y27WZaw)Z}Z~Bz
</code>```

Try it online!

Explanation

```<code>tQv            % Implicit input. Duplicate, add 1, concatenate vertically
V              % Convert to 2D char array: each number in a row, possibly left-padded
               % with a space
15\            % Modulo 15. With modular indexing this corresponds to the order
               % '9', ' ', '0', '1', ..., '8'
'3dAsMh818RG5' % This string encodes active segments for each of the 11 chars
6Y2            % Source alphabet printable ASCII chars (predefined literal)
7W             % Target alphabet: [0 1 ... 127]
Za             % Base conversion: decode string into vector of 11 numbers, where each
               % number from 0 to 127 encodes the 7-segment representation of a digit,
               % in the order '9', ' ', '0', '1', ..., '8'
w              % Swap top two elements in stack
)              % Use as index. Gives 2-row array, where each column is a digit
Z}             % Split into the two rows
Z~             % Bitwise XOR, elementwise
B              % Convert to binary. Each number gives a row
z              % Number of nonzero elements. Implicitly display
</code>```

Title: 7-segment differences

Body:
MATL, <s>61</s> <s>39</s> 36 bytes

tQvV15\'3dAsMh818RG5'6Y27WZaw)Z}Z~Bz

Try it online!

Explanation

tQv            % Implicit input. Duplicate, add 1, concatenate vertically
V              % Convert to 2D char array: each number in a row, possibly left-padded
               % with a space
15\            % Modulo 15. With modular indexing this corresponds to the order
               % '9', ' ', '0', '1', ..., '8'
'3dAsMh818RG5' % This string encodes active segments for each of the 11 chars
6Y2            % Source alphabet printable ASCII chars (predefined literal)
7W             % Target alphabet: [0 1 ... 127]
Za             % Base conversion: decode string into vector of 11 numbers, where each
               % number from 0 to 127 encodes the 7-segment representation of a digit,
               % in the order '9', ' ', '0', '1', ..., '8'
w              % Swap top two elements in stack
)              % Use as index. Gives 2-row array, where each column is a digit
Z}             % Split into the two rows
Z~             % Bitwise XOR, elementwise
B              % Convert to binary. Each number gives a row
z              % Number of nonzero elements. Implicitly display


答:
05AB1E, <s>31</s> <s>30</s> <s>28</s> <s>27</s> 26 bytes

Code:

```<code>9Ü©T%•2X›ùì•sè¹g®g-·¹Ú9Q·O
</code>```

Explanation (outdated):

```<code>9Ü                              # Trim off trailing 9's
  ©                             # Copy this into the register
   T%                           # Get the last non-9 digit
     žh                         # Short for 0123456789
       •2X›ùì•§                 # Compressed version of 4523315412
               ‡                # Transliterate
</code>```

We are changing the following to the last non-9 digit:

```<code>0 -> 4
1 -> 5
2 -> 2
3 -> 3
4 -> 3
5 -> 1
6 -> 5
7 -> 4
8 -> 1
9 -> 2
</code>```

For the special cases:

```<code>                ¹g              # Get the length of the input
                  ®g            # Get the length of the input with all trailing 9 gone
                    -           # Substract, giving the number of 9's at the end of
                                  the input
                     2*         # Multiply by two
                       O        # Sum everything up
                        ¹Ú      # Uniquify the input
                          9Qi   # If this is equal to 9 (only 9's in the input)
                             Ì  #   Increment by 2 (_ -> 1)
</code>```

Uses the CP-1252 encoding. Try it online!.

28 byte alternative: D[¤©•2X›ùì•sès®9Ê#¨]\rÚ9Q4*O.

Title: 7-segment differences

Body:
05AB1E, <s>31</s> <s>30</s> <s>28</s> <s>27</s> 26 bytes

Code:

9Ü©T%•2X›ùì•sè¹g®g-·¹Ú9Q·O

Explanation (outdated):

9Ü                              # Trim off trailing 9's
  ©                             # Copy this into the register
   T%                           # Get the last non-9 digit
     žh                         # Short for 0123456789
       •2X›ùì•§                 # Compressed version of 4523315412
               ‡                # Transliterate

We are changing the following to the last non-9 digit:

0 -> 4
1 -> 5
2 -> 2
3 -> 3
4 -> 3
5 -> 1
6 -> 5
7 -> 4
8 -> 1
9 -> 2

For the special cases:

                ¹g              # Get the length of the input
                  ®g            # Get the length of the input with all trailing 9 gone
                    -           # Substract, giving the number of 9's at the end of
                                  the input
                     2*         # Multiply by two
                       O        # Sum everything up
                        ¹Ú      # Uniquify the input
                          9Qi   # If this is equal to 9 (only 9's in the input)
                             Ì  #   Increment by 2 (_ -> 1)

Uses the CP-1252 encoding. Try it online!.

28 byte alternative: D[¤©•2X›ùì•sès®9Ê#¨]\rÚ9Q4*O.


答:
Jolf, 32 bytes

```<code>Ώ?H?<γ%Ht9P."452331541"γ+2Ώc/Ht2
</code>```

Try it here!

Explanation

This is a transpilation of Neil's answer.

```<code>Ώ?H?<γ%Ht9P."452331541"γ+2Ώc/Ht2
Ώ                                 define a function Ώ of H
 ?H                            2  (when H is zero, return is 2)
      %Ht                         H mod 10
     γ                            γ = ^
   ?<    9                        is it less than 9?
                                  if so:
           ."452331541"γ           get the γth element of that string
          P                        as a number
                                  else
                        +2         add two to
                          Ώ        Ώ over
                           c/Ht    int(H / 10)
</code>```

Title: 7-segment differences

Body:
Jolf, 32 bytes

Ώ?H?<γ%Ht9P."452331541"γ+2Ώc/Ht2

Try it here!

Explanation

This is a transpilation of Neil's answer.

Ώ?H?<γ%Ht9P."452331541"γ+2Ώc/Ht2
Ώ                                 define a function Ώ of H
 ?H                            2  (when H is zero, return is 2)
      %Ht                         H mod 10
     γ                            γ = ^
   ?<    9                        is it less than 9?
                                  if so:
           ."452331541"γ           get the γth element of that string
          P                        as a number
                                  else
                        +2         add two to
                          Ώ        Ώ over
                           c/Ht    int(H / 10)


答:
Julia, 44 bytes

```<code>!x=x<1?2:(t=x%10÷1)<9?3045058÷6^t%6:2+!.1x
</code>```

Try it here.

Dennis saved a byte!

Title: 7-segment differences

Body:
Julia, 44 bytes

!x=x<1?2:(t=x%10÷1)<9?3045058÷6^t%6:2+!.1x

Try it here.

Dennis saved a byte!


问:
Complementary colors
Given an input of a color in #rrggbb hex format, output its RGB complement in
the same format.

The RGB complement R2G2B2 of any color
R1G1B1 is defined as the color with
R2 value 255 - R1, B2 value 255 -
B1, and G2 value 255 - G1.

Hex digits may be either in uppercase (#FFAA20) or lowercase (#ffaa20). The
case of the input and output need not be consistent (so you may take input in
lowercase but output in uppercase, and vice versa).

Since this is code-golf, the shortest code in bytes wins.

Test cases (note that since giving your program/function its own output should
result in the original input (it is
involutory), the test
cases should work in both directions):

```<code>In/Out   Out/In
----------------
#ffffff  #000000
#abcdef  #543210
#badcab  #452354
#133742  #ecc8bd
#a1b2c3  #5e4d3c
#7f7f80  #80807f
</code>```

答:
Python, 96

```<code>x=input()
print("#")
for i in range(3):
    print(hex(255-int(x[(1+2*i)]+x[(2+2*i)],16))[2:4])
</code>```

First code golf, please give opinions :)

Title: Complementary colors

Body:
Python, 96

x=input()
print("#")
for i in range(3):
    print(hex(255-int(x[(1+2*i)]+x[(2+2*i)],16))[2:4])

First code golf, please give opinions :)


答:
Ruby, 50 bytes

Zip, then map/reduce. Barely edges out the other Ruby answer from @LevelRiverSt by 2 bytes...

```<code>->p,q{p.zip(q).map{|a,b|(a-b)**2}.reduce(:+)**0.5}
</code>```

Try it online

Title: Distance between two points in n-dimensional space

Body:
Here is another simple one:

The Challenge

Given two points in an n-dimensional space, output the distance between them, also called the Euclidean distance.

The coordinates will be rational numbers; the only limits are the restrictions of your language.

Lowest dimension is 1, highest is whatever your language can handle

You may assume that the two points are of the same dimension and that there will be no empty input.

The distance has to be correct to at least 3 decimal places. If your language does not support floating point numbers, output the nearest whole number.

Rules

As usual, function or full program allowed.

Input may be taken from STDIN, command line- or function arguments.

Input format is up to you, specify which one you used in your answer.

Output may be provided by printing to stdout or return value.

This is code-golf so lowest byte-count wins! In case of a tie, the earlier answer wins.

Test cases

Each point is represented by a list of length n.

```<code>[1], [3] -> 2
[1,1], [1,1] -> 0
[1,2], [3,4] -> 2.82842712475
[1,2,3,4], [5,6,7,8] -> 8
[1.5,2,-5], [-3.45,-13,145] -> 150.829382085
[13.37,2,6,-7], [1.2,3.4,-5.6,7.89] -> 22.5020221314
</code>```

Happy Coding!

Body:
Ruby, 50 bytes

Zip, then map/reduce. Barely edges out the other Ruby answer from @LevelRiverSt by 2 bytes...

->p,q{p.zip(q).map{|a,b|(a-b)**2}.reduce(:+)**0.5}

Try it online


问:
"Hello, World!"
So... uh... this is a bit embarrassing. But we don't have a plain "Hello, World!" challenge yet (despite having 35 variants tagged with hello-world, and counting). While this is not the most interesting code golf in the common languages, finding the shortest solution in certain esolangs can be a serious challenge. For instance, to my knowledge it is not known whether the shortest possible Brainfuck solution has been found yet.

Furthermore, while all of <s>Wikipedia</s> (the Wikipedia entry has been deleted but there is a copy at archive.org
), esolangs and Rosetta Code have lists of "Hello, World!" programs, none of these are interested in having the shortest for each language (there is also this GitHub repository). If we want to be a significant site in the code golf community, I think we should try and create the ultimate catalogue of shortest "Hello, World!" programs (similar to how our basic quine challenge contains some of the shortest known quines in various languages). So let's do this!

The Rules

Each submission must be a full program.

The program must take no input, and print Hello, World! to STDOUT (this exact byte stream, including capitalization and punctuation) plus an optional trailing newline, and nothing else.

The program must not write anything to STDERR.

If anyone wants to abuse this by creating a language where the empty program prints Hello, World!, then congrats, they just paved the way for a very boring answer.

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

Submissions are scored in bytes, in an appropriate (pre-existing) encoding, usually (but not necessarily) UTF-8. Some languages, like Folders, are a bit tricky to score - if in doubt, please ask on Meta.

This is not about finding the language with the shortest "Hello, World!" program. This is about finding the shortest "Hello, World!" program in every language. Therefore, I will not mark any answer as "accepted".

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 Alphuck), consider adding a note to the existing answer that the same or a very similar solution is also the shortest in the other language.

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 authors actually had to put effort into golfing the code.

For inspiration, check the Hello World Collection.

The 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>## [><>](https://esolangs.org/wiki/Fish), 121 bytes
</code>```

/* Configuration */

var QUESTION_ID = 55422; // 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 = 8478; // This should be the user ID of the challenge author.

/* App */

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

function answersUrl(index) {
  return "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,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/;

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

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

function process() {
  var valid = [];

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

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

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

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

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

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

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

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

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

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

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

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

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

table thead {
  font-weight: bold;
}

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

<link rel="stylesheet" type="text/css" href="https://cdn.sstatic.net/Sites/codegolf/all.css?v=ffb5d0584c5f">

Shortest Solution by Language

Language	User	Score

Leaderboard

	Author	Language	Size

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

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

```

答:
Wat, 47 + 1 = 48 bytes

```<code>0«!dlroW ,olleH»>ó#ÐÑÅv
                ^     <
</code>```

<s>I post a explanation tomorrow</s>
Here is the explanation:

```<code>First line:

0«!dlroW ,olleH»>ó#ÐÑÅv

0«!dlroW ,olleH»        Push a reversed null terminated string
                >       Go forward
                 ó      Duplicate the top of stack
                  #     Skip the next instruction
                   Ð    Kill all "execution engines" (end the program)
                    Ñ   If the top of the stack is 0, go backward (execute Ð and end the program), otherwise go forward
                     Å  Print the character on the top of the stack
                      v Go downward
Second line:

                ^     <

Simply loop from the 'v' to the '>'
</code>```

Title: "Hello, World!"

Body:
Wat, 47 + 1 = 48 bytes

0«!dlroW ,olleH»>ó#ÐÑÅv
                ^     <

<s>I post a explanation tomorrow</s>
Here is the explanation:

First line:

0«!dlroW ,olleH»>ó#ÐÑÅv

0«!dlroW ,olleH»        Push a reversed null terminated string
                >       Go forward
                 ó      Duplicate the top of stack
                  #     Skip the next instruction
                   Ð    Kill all "execution engines" (end the program)
                    Ñ   If the top of the stack is 0, go backward (execute Ð and end the program), otherwise go forward
                     Å  Print the character on the top of the stack
                      v Go downward
Second line:

                ^     <

Simply loop from the 'v' to the '>'


Title: 7-segment differences

Body:
J, 53 bytes

2:`((2+10$:@<.@%~[)`(6|3045058<.@%6^])@.(9>])10&|)@.*

Originally based on @Neil's solution. Then improved by saving a byte using the same formula in @Lynn's solution.

The 54 byte version based on the string is

2:`((2+10$:@<.@%~[)`('452331541'".@{~])@.(9>])10&|)@.*

Usage

   f =: 2:`((2+10$:@<.@%~[)`(6|3045058<.@%6^])@.(9>])10&|)@.*
   f 1999
11
   f 1999 12345 999999 5699999 8765210248
11 1 14 15 1


答:
Jelly, <s>25</s> <s>22</s> <s>21</s> 20 bytes

```<code>‘DṁDḟ"DFị9979482ḃ5¤S
</code>```

Try it online! or verify all test cases.

Background

We first increment the input n and discard all digits of n + 1 that haven't changed.

For example, if n is 5699999, we get the following.

```<code>n     : 5700000
n + 1 : 5699999
Result:  700000
</code>```

All digits in this result have a fixed number of segments that have to get toggled. We can convert the list of toggles to bijective base 5 to save some bytes.

```<code>digit:   1 2 3 4 5 6 7 8 9 0
toggles: 4 5 2 3 3 1 5 4 1 2
</code>```

The output is simply the sum of the individual toggles.

This works for most values of n, but special care must be taken if n + 1 has more digits than n. In this case, all digits must be 9's, and we solve this problem by chopping off a trailing 0 from n + 1.

For example, if n is 999999, we get the following.

```<code>n     :  999999
n + 1 : 1000000
Result: 100000
</code>```

This works because the leading 1 evaluates to 4 toggles (distance between 0 and 1), while the actual amount of toggles is 2 (distance between 0 and 1), and suppressing one trailing 0 removes its 2 toggles from the sum.

How it works

```<code>‘DṁDḟ"DFị9979482ḃ5¤S  Main link. Argument: n

‘                     Compute n+1.
 D                    Convert n+1 from integer to base 10.
   D                  Convert n from integer to base 10.
  ṁ                   Mold the left result as the right result.
                      This chops of a 0 if n+1 has more digits than n.
    ḟ"D               Vectorized filter-false with the base 10 digits of n.
                      This removes the digits from n+1 that are identical to
                      the corresponding digits of n.
       F              Flatten the resulting list of lists.
         9979482ḃ5¤   Convert 9979482 to bijective base 5.
                      This yields [4, 5, 2, 3, 3, 1, 5, 4, 1, 2].
        ị             Retrieve the digits at the right that correspond to the
                      indices at the left.
                   S  Compute the sum of the results.
</code>```

Title: 7-segment differences

Body:
Jelly, <s>25</s> <s>22</s> <s>21</s> 20 bytes

‘DṁDḟ"DFị9979482ḃ5¤S

Try it online! or verify all test cases.

Background

We first increment the input n and discard all digits of n + 1 that haven't changed.

For example, if n is 5699999, we get the following.

n     : 5700000
n + 1 : 5699999
Result:  700000

All digits in this result have a fixed number of segments that have to get toggled. We can convert the list of toggles to bijective base 5 to save some bytes.

digit:   1 2 3 4 5 6 7 8 9 0
toggles: 4 5 2 3 3 1 5 4 1 2

The output is simply the sum of the individual toggles.

This works for most values of n, but special care must be taken if n + 1 has more digits than n. In this case, all digits must be 9's, and we solve this problem by chopping off a trailing 0 from n + 1.

For example, if n is 999999, we get the following.

n     :  999999
n + 1 : 1000000
Result: 100000

This works because the leading 1 evaluates to 4 toggles (distance between 0 and 1), while the actual amount of toggles is 2 (distance between 0 and 1), and suppressing one trailing 0 removes its 2 toggles from the sum.

How it works

‘DṁDḟ"DFị9979482ḃ5¤S  Main link. Argument: n

‘                     Compute n+1.
 D                    Convert n+1 from integer to base 10.
   D                  Convert n from integer to base 10.
  ṁ                   Mold the left result as the right result.
                      This chops of a 0 if n+1 has more digits than n.
    ḟ"D               Vectorized filter-false with the base 10 digits of n.
                      This removes the digits from n+1 that are identical to
                      the corresponding digits of n.
       F              Flatten the resulting list of lists.
         9979482ḃ5¤   Convert 9979482 to bijective base 5.
                      This yields [4, 5, 2, 3, 3, 1, 5, 4, 1, 2].
        ị             Retrieve the digits at the right that correspond to the
                      indices at the left.
                   S  Compute the sum of the results.


答:
Python, <s>71</s> 66 bytes

48 bytes by xsot. Even more magic maths!

f=lambda n:(2+f(n/10)if n%10==9else 26523308>>n%10*3&7)if n else 2
```

See it on ideone

Because the prior Python answer doesn't work and is far from optimal. A simple port of a previous ES6 version. Now using bit twiddling (from the ES6 alternate formulation) to cut out a cast!

Can be made to work with Python 3 by explicitly using floordiv for +1 byte.

Title: 7-segment differences

Body:
Python, <s>71</s> 66 bytes

48 bytes by xsot. Even more magic maths!

f=lambda n:(2+f(n/10)if n%10==9else 26523308>>n%10*3&7)if n else 2

See it on ideone

Because the prior Python answer doesn't work and is far from optimal. A simple port of a previous ES6 version. Now using bit twiddling (from the ES6 alternate formulation) to cut out a cast!

Can be made to work with Python 3 by explicitly using floordiv for +1 byte.


问:
Self-Mutilating Program
Simply put, your goal is to create a complete program that modifies its own source code until every character of the source is different than what it started as.

Please include the beginning source as well as the ending source in your post, as well as a description. E.g. Describe what (else) your program does, the language you used, your strategy, etc.

Rules

Your program must halt sometime after the modification is complete.

It must actually modify its own, currently running source code (not necessarily the file you passed to the interpreter, it modifies its instructions), not print a new program or write a new file.

Standard loopholes are disallowed.

Shortest program wins.

If your language can modify its own file and execute a new compiler process, but cannot modify its own (currently running) source code, you may write such a program instead at a +20% bytes penalty, rounded up. Real self-modifying languages should have an advantage.

Edit: If your program halts with errors, please specify it as such (and maybe say what the errors are.)

答:
(Filesystem) Befunge 98, 46 bytes

```<code>ff*:1100'aof0'ai
               21f0'ai@
</code>```

Note that this program creates and manipulates a file named a.
How it works:

The code creates a file named a containing the entire code (out to 256 characters in each dimension) shifted one space upward and two the left.

This program then reads the file named a as one line, replacing the entire first line with the contents of the a file.

The second line, which has been copied in front of the IP, is executed

Which reads the a file into the second line shifted two places to the right.

As a side effect, the ending source code isn't even valid Befunge! (because it contains newlines as data in a single line)

Title: Self-Mutilating Program

Body:
(Filesystem) Befunge 98, 46 bytes

ff*:1100'aof0'ai
               21f0'ai@

Note that this program creates and manipulates a file named a.
How it works:

The code creates a file named a containing the entire code (out to 256 characters in each dimension) shifted one space upward and two the left.

This program then reads the file named a as one line, replacing the entire first line with the contents of the a file.

The second line, which has been copied in front of the IP, is executed

Which reads the a file into the second line shifted two places to the right.

As a side effect, the ending source code isn't even valid Befunge! (because it contains newlines as data in a single line)


问:
Same length sub arrays

Background:

Here's a little simple challenge. You want to be able to find out whether the arrays inside an array have the same length.

Input:

Your input should consist of exactly one array (this is the value passed to the function, not a user input). Your function takes exactly 1 parameter.  It could contain arrays or be empty. No error checking needed, assume only list is ever passed in. Assume a 1-D array such as [1] or [1,2,3,4,5] is never passed in.

Output:

Return true if all the list elements have the same length, false if they don't, and the parameter itself if the list is empty (or null if your language doesn't support multiple return types).

Some test cases:

```<code>List: [] - [] (or null/your language equivalent)
List: [[1], [1], [2]] - True
List: [[1]] - True
List: [[1, 2, 3, 4]] - True
List: [[1, 2, 3, 4, 5], [2], [12, 314123]] - False
List: [[1, 2, 3, 4], [1]] - False
</code>```

No std(in/out) input/output needed (however, it is allowed, just not required!), the function only needs to return boolean values true or false; or the parameter itself if the function is passed an empty list (or null/your language equivalent). Only one return value is returned.

Rules:

Shortest byte count wins, only function is necessary (full programs are allowed if you desire).

答:
J, 26 bytes

```<code>]`(1=[:#@~.#@>@>)@.(*@#@>)
</code>```

Since J doesn't support ragged arrays, I will use boxed arrays instead. It returns 1 for true, 0 for false, and the input if empty.

Usage

```<code>   f =: ]`(1=[:#@~.#@>@>)@.(*@#@>)

   NB. Boxed array representing [[1, 2, 3, 4, 5], [2], [12, 314123]]
   < 1 2 3 4 ; 2 ; 12 314123
┌─────────────────────┐
│┌───────┬─┬─────────┐│
││1 2 3 4│2│12 314123││
│└───────┴─┴─────────┘│
└─────────────────────┘
   f < 1 2 3 4 ; 2 ; 12 314123
0
   NB. The empty list
   a:
┌┐
││
└┘
   f a:
┌┐
││
└┘
   f < 1 ; 1 ; 2
1
   f < < 1
1
   f < < 1 2 3 4
1
   f < 1 2 3 4 ; 1
0
</code>```

Title: Same length sub arrays

Body:
J, 26 bytes

]`(1=[:#@~.#@>@>)@.(*@#@>)

Since J doesn't support ragged arrays, I will use boxed arrays instead. It returns 1 for true, 0 for false, and the input if empty.

Usage

   f =: ]`(1=[:#@~.#@>@>)@.(*@#@>)

   NB. Boxed array representing [[1, 2, 3, 4, 5], [2], [12, 314123]]
   < 1 2 3 4 ; 2 ; 12 314123
┌─────────────────────┐
│┌───────┬─┬─────────┐│
││1 2 3 4│2│12 314123││
│└───────┴─┴─────────┘│
└─────────────────────┘
   f < 1 2 3 4 ; 2 ; 12 314123
0
   NB. The empty list
   a:
┌┐
││
└┘
   f a:
┌┐
││
└┘
   f < 1 ; 1 ; 2
1
   f < < 1
1
   f < < 1 2 3 4
1
   f < 1 2 3 4 ; 1
0


答:
Java, 63 bytes

The world is righted as Python passes Java once more.

Cause, ya know, Java.

int f(int n){return n>0?n%10<9?26523308>>n%10*3&7:2+f(n/10):2;}
```

See it on ideone

Maxes out at 2147483647, as that is Java's Integer.MAX_VALUE.

This is a port of my Python answer which is a port of the ES6 answer.

Title: 7-segment differences

Body:
Java, 63 bytes

The world is righted as Python passes Java once more.

Cause, ya know, Java.

int f(int n){return n>0?n%10<9?26523308>>n%10*3&7:2+f(n/10):2;}

See it on ideone

Maxes out at 2147483647, as that is Java's Integer.MAX_VALUE.

This is a port of my Python answer which is a port of the ES6 answer.