问:
Next Friday the 13th
What is the shortest program that can predict the next time Friday will fall on the 13th day of the month?

Must be an complete functioning program (not just a function/subroutine)

Must print out date in the following format: YYYY-MM-DD

Allow user to provide a start date either as a command line argument or through STDIN

If user provides no start date, use today as the start date.

If the start date is a Friday the 13th, the program should find the next Friday the 13th.

If I were to run the program today (Feb 16 2011) I should get the following output.

```<code>$ ./fr13th 2013-05-09
2013-09-13
$ ./fr13th 2007-06-29
2007-07-13
$ ./fr13th 2007-07-13
2008-06-13
$ ./fr13th
2011-05-13
</code>```

答:
bash, 75

```<code>until set `date +%F -d$1+day`
date -d$1|grep -q '^F.* 13'
do :
done
echo $1
</code>```

This is a bit locale-sensitive; if it fails on your machine, try exporting LC_ALL=C beforehand.

```<code>$ bash fri13th.sh 2013-05-09
2013-09-13
$ bash fri13th.sh 2007-06-29
2007-07-13
$ bash fri13th.sh 2007-07-13
2008-06-13
$ bash fri13th.sh
2011-05-13
</code>```

ContentLicense: CC BY-SA 2.5

Title: Next Friday the 13th

Body:
bash, 75

until set `date +%F -d$1+day`
date -d$1|grep -q '^F.* 13'
do :
done
echo $1

This is a bit locale-sensitive; if it fails on your machine, try exporting LC_ALL=C beforehand.

$ bash fri13th.sh 2013-05-09
2013-09-13
$ bash fri13th.sh 2007-06-29
2007-07-13
$ bash fri13th.sh 2007-07-13
2008-06-13
$ bash fri13th.sh
2011-05-13


问:
Print a letter Fibonacci
Given N (2 <= N), print N lines of the letter Fibonacci series like this (i.e. N = 5)
First, start with a and b:

```<code>a
b
</code>```

Next, add the two lines.

```<code>a
b
ab
</code>```

Keep adding the last two lines.

```<code>a
b
ab
bab
</code>```

Keep going...

```<code>a
b
ab
bab
abbab
</code>```

And we're done.

Remember, this is code-golf, so the code with the fewest bytes wins.

答:
Ruby (1.9+) 46 bytes

```<code>a,b=?a,?b;ARGV[0].to_i.times{puts a;a,b=b,a+b}
</code>```

ContentLicense: CC BY-SA 4.0

Title: Print a letter Fibonacci

Body:
Ruby (1.9+) 46 bytes

a,b=?a,?b;ARGV[0].to_i.times{puts a;a,b=b,a+b}

ContentLicense: CC BY-SA 3.0


问:
Draw some mountain peaks
Write a program or function that draws a mountain range, where each subsequent larger mountain peak is "behind" the ones in front, and alternates which side is visible.

This is a mountain range of size 1

```<code>/\
</code>```

This is a mountain range of size 2

```<code> /\
/\ \
</code>```

This is a mountain range of size 3

```<code>  /\
 / /\
/ /\ \
</code>```

This is a mountain range of size 4

```<code>   /\
  /\ \
 / /\ \
/ /\ \ \
</code>```

This is a mountain range of size 5

```<code>    /\
   / /\
  / /\ \
 / / /\ \
/ / /\ \ \
</code>```

And so on.

Input

A single positive integer in any convenient format, n > 0.

Output

An ASCII-art representation of the mountain range, following the above rules. Leading/trailing newlines or other whitespace are optional, provided that the peaks line up appropriately.

Rules

Either a full program or a function are acceptable. If a function, you can return the output rather than printing it.

Standard loopholes are forbidden.

This is code-golf so all usual golfing rules apply, and the shortest code (in bytes) wins.

答:
Python 2, 67 bytes

n=input()
s='/\\'
while n:n-=1;print' '*n+s;s=['/ '+s,s+' \\'][n%2]
```

<p>Prints line by line, accumulating the string <code>s</code> by alternately adding a slash to the left or right based on the current parity of <code>n</code>. Prefixes with <code>n</code> spaces. </p>

<p>An alternative way to update was the same length:</p>

<pre class="lang-python prettyprint-override"><code>s=n%2*'/ '+s+~n%2*' \\'
s=['/ '+s,s+' \\'][n%2]
</code>```

A recursive method was longer (70 bytes).

f=lambda n,s='/\\':n*'_'and' '*~-n+s+'\n'+f(n-1,[s+' \\','/ '+s][n%2])
```

Title: Draw some mountain peaks

Body:
Python 2, 67 bytes

n=input()
s='/\\'
while n:n-=1;print' '*n+s;s=['/ '+s,s+' \\'][n%2]

Prints line by line, accumulating the string s by alternately adding a slash to the left or right based on the current parity of n. Prefixes with n spaces.

An alternative way to update was the same length:

s=n%2*'/ '+s+~n%2*' \\'
s=['/ '+s,s+' \\'][n%2]

A recursive method was longer (70 bytes).

f=lambda n,s='/\\':n*'_'and' '*~-n+s+'\n'+f(n-1,[s+' \\','/ '+s][n%2])


答:
Haskell, 77 bytes

0%_=""
n%s=(' '<$[2..n])++s++'\n':(n-1)%(cycle[s++" \\","/ "++s]!!n)
(%"/\\")
```

<p>Usage:</p>

<pre class="lang-haskell prettyprint-override"><code>putStrLn $ f 5
    /\
   / /\
  / /\ \
 / / /\ \
/ / /\ \ \
</code>```

Prints line by line, accumulating the string s by alternately adding a slash to the left or right based on the current parity of n. Prefixes with n-1 spaces.

Title: Draw some mountain peaks

Body:
Write a program or function that draws a mountain range, where each subsequent larger mountain peak is "behind" the ones in front, and alternates which side is visible.

This is a mountain range of size 1

```<code>/\
</code>```

This is a mountain range of size 2

```<code> /\
/\ \
</code>```

This is a mountain range of size 3

```<code>  /\
 / /\
/ /\ \
</code>```

This is a mountain range of size 4

```<code>   /\
  /\ \
 / /\ \
/ /\ \ \
</code>```

This is a mountain range of size 5

```<code>    /\
   / /\
  / /\ \
 / / /\ \
/ / /\ \ \
</code>```

And so on.

Input

A single positive integer in any convenient format, n > 0.

Output

An ASCII-art representation of the mountain range, following the above rules. Leading/trailing newlines or other whitespace are optional, provided that the peaks line up appropriately.

Rules

Either a full program or a function are acceptable. If a function, you can return the output rather than printing it.

Standard loopholes are forbidden.

This is code-golf so all usual golfing rules apply, and the shortest code (in bytes) wins.

Body:
Haskell, 77 bytes

0%_=""
n%s=(' '<$[2..n])++s++'\n':(n-1)%(cycle[s++" \\","/ "++s]!!n)
(%"/\\")

Usage:

putStrLn $ f 5
    /\
   / /\
  / /\ \
 / / /\ \
/ / /\ \ \

Prints line by line, accumulating the string s by alternately adding a slash to the left or right based on the current parity of n. Prefixes with n-1 spaces.


问:
Produce Dürer's magic square

The challenge

Output an array or string representation of Dürer's famous magic square:

that is,

```<code>16  3  2 13
 5 10 11  8
 9  6  7 12
 4 15 14  1
</code>```

Some properties of this square, which can perhaps be exploited, are:

It contains each integer from 1 to 16 exactly once

The sum of each column or row, as well as the the sum of each of the two diagonals, is the same. This is the defining property of a magic square. The sum is the magic constant of the square.

In addition, for this particular square, the sum of each of the four quadrants also equals the magic constant, as do the sum of the center four squares and the sum of the corner four squares.

Rules

Bultins that generate magic squares are not allowed (such as Matlab's magic or Mathematica's MagicSquare). Any other builtin can be used.

The code can be a program or a function.

There is no input.

The numbers must be in base 10. The output format is flexible as usual. Some possibilities are:

A nested array (either function output, or its string representation, with or without separators, any type of matching brackets):

```<code>[[16, 3, 2, 13], [5, 10, 11, 8], [9, 6, 7, 12], [4, 15, 14, 1]]
</code>```

A 2D array:

```<code>{16, 3, 2, 13; 5, 10, 11, 8; 9, 6, 7, 12; 4, 15, 14, 1}
</code>```

An array of four strings, or a string consisting of four lines. The numbers may be right-aligned

```<code>16  3  2 13
 5 10 11  8
 9  6  7 12
 4 15 14  1
</code>```

or left-aligned

```<code>16 3  2  13
5  10 11  8
9  6  7  12
4  15 14  1
</code>```

A string with two different separators for row and column, such as

```<code>16,3,2,13|5,10,11,8|9,6,7,12|4,15,14,1
</code>```

The output format should clearly differentiate rows and columns. For example, it is not allowed to output a flat array, or a string with all numbers separated by spaces.

Code golf. Shortest wins.

答:
Scala, 52 bytes

```<code>()=>Seq(15,4,8,3)map(x=>Seq(x,x^13,x^14,x^3)map(1+))
</code>```

Ungolfed:

```<code>()=>
  Seq(15, 4, 8, 3)
  .map(x=>
    Seq(x, x^13, x^14, x^3)
    .map(1+)
  )
</code>```

Inspired by Level River St's ruby answer.

Title: Produce Dürer's magic square

Body:
Scala, 52 bytes

()=>Seq(15,4,8,3)map(x=>Seq(x,x^13,x^14,x^3)map(1+))

Ungolfed:

()=>
  Seq(15, 4, 8, 3)
  .map(x=>
    Seq(x, x^13, x^14, x^3)
    .map(1+)
  )

Inspired by Level River St's ruby answer.


问:
Binary Countdown Length
inspired by Count down from infinity

Given a non-negative integer N, output the number of repetitions of the following steps it takes to reach 0:

Convert N to binary (4812390 -> 10010010110111001100110)

Flip each bit (10010010110111001100110 -> 01101101001000110011001)

Trim leading zeroes (01101101001000110011001 -> 1101101001000110011001)

Convert back to decimal (1101101001000110011001 -> 3576217)

Rules

Input and output may be in any unambiguous, consistent format

The input will be within the native representable integer range for your language (if your language supports arbitrarily-large integers, there is no bound)

Test Cases

```<code>0 -> 0
1 -> 1
42 -> 6
97 -> 3
170 -> 8
255 -> 1
682 -> 10
8675309 -> 11
4812390 -> 14
178956970 -> 28
2863311530 -> 32
</code>```

This sequence is A005811 in the OEIS.

答:
C (gcc), 76 Bytes, 72 Bytes (thanks to celingcat)

unsigned n,m,i;f(x){for(i=0;n=x;x^=m-1,i++)for(m=2;n/=2;m+=m);return i;}
```

Try it online!

Title: Binary Countdown Length

Body:
C (gcc), 76 Bytes, 72 Bytes (thanks to celingcat)

unsigned n,m,i;f(x){for(i=0;n=x;x^=m-1,i++)for(m=2;n/=2;m+=m);return i;}

Try it online!


答:
Ruby, 61 bytes

A pretty straightforward port of ETHproductions' JavaScript answer.

```<code>->n{s="/\\"
(puts" "*n+s
s=n%2>0?s+" \\":"/ "+s)until 0>n-=1}
</code>```

See it on repl.it: https://repl.it/EPU5/1

Ungolfed

->n{
  s = "/\\"
  ( puts " "*n+s
    s = n%2 > 0 ? s+" \\" : "/ "+s
  ) until 0 > n -= 1
}
```

Title: Draw some mountain peaks

Body:
Ruby, 61 bytes

A pretty straightforward port of ETHproductions' JavaScript answer.

->n{s="/\\"
(puts" "*n+s
s=n%2>0?s+" \\":"/ "+s)until 0>n-=1}

See it on repl.it: https://repl.it/EPU5/1

Ungolfed

->n{
  s = "/\\"
  ( puts " "*n+s
    s = n%2 > 0 ? s+" \\" : "/ "+s
  ) until 0 > n -= 1
}


问:
Square-unspiral the string!
Given a string, first square it as follows:

First, write the string.

```<code>abcde
</code>```

Next, write the string rotated one left.

```<code>abcde
bcdea
</code>```

Keep doing this until you have written len(string) lines.

```<code>abcde
bcdea
cdeab
deabc
eabcd
</code>```

Now, read from the string like this:

```<code>----+
+--+|
|+>||
|+-+|
+---+
</code>```

Which gives:

```<code>abcdeabcdcbaedcbcdeabaede
</code>```

Print this string.

Test cases

```<code>abcdef -> abcdefabcdedcbafedcbcdefabcbafedefaf
cena! -> cena!cenanec!anena!cec!a!
ppcg -> ppcgppcppgcpcgpg
abc -> abcabacbc
ab -> abab
a -> a
 ->
</code>```

Please comment if a test case is incorrect.

Remember, this is code-golf, so the code with the smallest number of bytes wins.

答:
Actually, <s>21</s> 13 bytes

This algorithm is largely based on Jonathan Allan's Jelly answer. There are two ways to go about printing the result as one string. The approach used here duplicates an intermediate step and then adds it to a running total in register 1 (an empty string by default); ;╕ in the function, then ╛ at the end. The other approach is to duplicate an intermediate step, leave those duplicate steps on the stack, and sum them into one string at the end; ; in the function, then kΣ at the end.

Golfing suggestions welcome. Try it online!

```<code>2*`dX;╕dXR`Y╛
</code>```

Ungolfing

```<code>         Implicit input s.
2*       Push a string that repeats s two times.
`...`Y   Call the following function until there is no change from the last call
  dX       Discard the last element. Call this new string m.
  ;╕       Duplicate m and add it to the running total in register 1.
  dXR      Discard the last element again and reverse the string.
╛        Push the unspiralled string from register 1 to the stack.
         Implicit return.
</code>```

Title: Square-unspiral the string!

Body:
Actually, <s>21</s> 13 bytes

This algorithm is largely based on Jonathan Allan's Jelly answer. There are two ways to go about printing the result as one string. The approach used here duplicates an intermediate step and then adds it to a running total in register 1 (an empty string by default); ;╕ in the function, then ╛ at the end. The other approach is to duplicate an intermediate step, leave those duplicate steps on the stack, and sum them into one string at the end; ; in the function, then kΣ at the end.

Golfing suggestions welcome. Try it online!

2*`dX;╕dXR`Y╛

Ungolfing

         Implicit input s.
2*       Push a string that repeats s two times.
`...`Y   Call the following function until there is no change from the last call
  dX       Discard the last element. Call this new string m.
  ;╕       Duplicate m and add it to the running total in register 1.
  dXR      Discard the last element again and reverse the string.
╛        Push the unspiralled string from register 1 to the stack.
         Implicit return.


答:
Pyth - 14 bytes

(yeah, another pyth answer)

```<code>A<G2VQG=H+~GHH
</code>```

Try it online

Explanation

```<code>A<G2              - take "ab" from the var G, dump "a" into G and "b" into H.
    VQ            - for N in range(Q)
      G           - print G
          ~GH     - like =GH but returns the previous G
         +   H    - concatenate the old G with the current H
       =H         - put that value back into H
</code>```

Title: Print a letter Fibonacci

Body:
Given N (2 <= N), print N lines of the letter Fibonacci series like this (i.e. N = 5)
First, start with a and b:

```<code>a
b
</code>```

Next, add the two lines.

```<code>a
b
ab
</code>```

Keep adding the last two lines.

```<code>a
b
ab
bab
</code>```

Keep going...

```<code>a
b
ab
bab
abbab
</code>```

And we're done.

Remember, this is code-golf, so the code with the fewest bytes wins.

Body:
Pyth - 14 bytes

(yeah, another pyth answer)

A<G2VQG=H+~GHH

Try it online

Explanation

A<G2              - take "ab" from the var G, dump "a" into G and "b" into H.
    VQ            - for N in range(Q)
      G           - print G
          ~GH     - like =GH but returns the previous G
         +   H    - concatenate the old G with the current H
       =H         - put that value back into H


答:
Actually, 16 bytes

There might be a shorter way to duplicate the top two elements of the stack in Actually, but I'm not sure what that way is. Golfing suggestions welcome. Try it online!

```<code>'a'b,¬`2╟2αio`na
</code>```

Ungolfing

```<code>'a'b     Push "a" then "b" to the stack.
,        Explicitly take input n.
¬        Push n-2.
`...`n   Run the following function n-2 times.
  2╟2α     Push a list that repeats the top two elements of the stack twice.
  i        Flatten that list to the stack. Stack: b, a, b, a, prev_iterations
  o        Append b to the end of a. Stack: ab, b, a, prev_iterations
a        Reverse the stack so that the strings will print in the correct order.
         Implicit print all of the elements in the stack.
</code>```

A different approach

This is also 16 bytes.
Try it online!

```<code>'a'b,¬`│ok╔Ri`na
</code>```

Ungolfing

The main difference is the function in the middle, so I'll only ungolf that here.

```<code>`...`n   Run the following function n-2 times.
  │        Duplicate the stack.
  o        Append the last item to the end of the second-to-last item.
  k╔       Uniquify the stack by wrapping the stack in a list and then calling uniquify().
  Ri       Reverse that list before returning everything to the stack
            so that the last items are at TOS again.
</code>```

Title: Print a letter Fibonacci

Body:
Actually, 16 bytes

There might be a shorter way to duplicate the top two elements of the stack in Actually, but I'm not sure what that way is. Golfing suggestions welcome. Try it online!

'a'b,¬`2╟2αio`na

Ungolfing

'a'b     Push "a" then "b" to the stack.
,        Explicitly take input n.
¬        Push n-2.
`...`n   Run the following function n-2 times.
  2╟2α     Push a list that repeats the top two elements of the stack twice.
  i        Flatten that list to the stack. Stack: b, a, b, a, prev_iterations
  o        Append b to the end of a. Stack: ab, b, a, prev_iterations
a        Reverse the stack so that the strings will print in the correct order.
         Implicit print all of the elements in the stack.

A different approach

This is also 16 bytes.
Try it online!

'a'b,¬`│ok╔Ri`na

Ungolfing

The main difference is the function in the middle, so I'll only ungolf that here.

`...`n   Run the following function n-2 times.
  │        Duplicate the stack.
  o        Append the last item to the end of the second-to-last item.
  k╔       Uniquify the stack by wrapping the stack in a list and then calling uniquify().
  Ri       Reverse that list before returning everything to the stack
            so that the last items are at TOS again.


问:
Depalindromize this string!
Given a palindrome generated according to this challenge, depalindromize it.

Test cases

```<code>abcdedcba -> abcde
johncenanecnhoj -> johncena
ppapapp -> ppap
codegolflogedoc -> codegolf
</code>```

As this is about depalindromizing, your code cannot be a palindrome.

Remember, this is code-golf, so the code with the fewest bytes wins.

答:
GO, 43 bytes

func(s string)string{return s[:len(s)/2+1]}

Try it online!

Title: Depalindromize this string!


问:
Interlace strings
Your challenge is to write a program or function that, when given two strings of equal length, swaps every other character and outputs/returns the resulting strings in either order.

Examples

```<code>"Hello," "world!" --> "Hollo!" "werld,"
"code" "golf" --> "codf" "gole"
"happy" "angry" --> "hnpry" "aagpy"
"qwerty" "dvorak" --> "qvertk" "dworay"
"1, 2, 3" "a, b, c" --> "1, b, 3" "a, 2, c"
"3.141592653589" "2.718281828459" --> "3.111291623489" "2.748582858559"
"DJMcMayhem" "trichoplax" --> "DrMcMoylex" "tJichapham"
"Doorknob" "Downgoat" --> "Doonkoot" "Dowrgnab"
"Halloween" "Challenge" --> "Hhlloeegn" "Caallwnee"
</code>```

Rules

The strings will only contain ASCII chars (32-126).

The strings will always be the same length, and will never be empty.

You may accept input in any suitable format: separate parameters, items in an array, separated by one or more newlines, even concatenated. The only restriction is that one string must come fully before the other (e.g. a1\nb2\nc3 for "abc", "123" is invalid).

The output may be in either order (i.e. you can start swapping from the first or the second char), and in any valid format mentioned above. (2-item array, separated by newline(s), concatenated, etc.)

Scoring

This is code-golf, so the shortest code in bytes for each language wins.

答:
Swift 3, <s>129</s> 107 bytes

```<code>func c(n:inout[String],b:inout[String]){
for(j,c)in n.enumerated(){
if j&1<1{n[j]=b[j];b[j]=c}}
print(n,b)}
</code>```

Original

The function receives two arrays of strings as parameters assuming both have same length, as follows:

```<code>c(n:["c", "o", "d", "e"],b:["g", "o", "l", "f"])
</code>```

Produces following output

```<code>codf gole
</code>```

Edit 1:

Get rid of the internal tuple and change the parameters of the function to be inout. Instead of string concatenation manipulate the parameters directly.

Example input:

```<code>var a:Array<String> = ["c", "o", "d", "e"]
var b:Array<String> = ["g", "o", "l", "f"]

c(n:&a,b:&b)
</code>```

Ouput changed to be array of strings as in:

["g", "o", "l", "e"] ["c", "o", "d", "f"]

Title: Interlace strings

Body:
Swift 3, <s>129</s> 107 bytes

func c(n:inout[String],b:inout[String]){
for(j,c)in n.enumerated(){
if j&1<1{n[j]=b[j];b[j]=c}}
print(n,b)}

Original

The function receives two arrays of strings as parameters assuming both have same length, as follows:

c(n:["c", "o", "d", "e"],b:["g", "o", "l", "f"])

Produces following output

codf gole

Edit 1:

Get rid of the internal tuple and change the parameters of the function to be inout. Instead of string concatenation manipulate the parameters directly.

Example input:

var a:Array<String> = ["c", "o", "d", "e"]
var b:Array<String> = ["g", "o", "l", "f"]

c(n:&a,b:&b)

Ouput changed to be array of strings as in:

["g", "o", "l", "e"] ["c", "o", "d", "f"]


答:
Jelly, <s>11</s> 10 bytes

```<code>ẋ2µṖȮṖUµÐL
</code>```

TryItOnline!, or all tests

How?

The unspiralled square is a series of "top-edge plus right-edge" and "bottom-edge plus left-edge" runs, each of which is the  reverse of the previous run without the first and last letter, and the first of which is the input plus the input without the last letter (e.g. input "abcde" has an output of "abcdeabcd" + "cbaedcb" + "cdeab" + "aed" + "e").

```<code>ẋ2µṖȮṖUµÐL - Main link: s                            e.g. abcde
ẋ2         - repeat s twice                          e.g. abcdeabcde
  µ    µ   - monadic chain separation
        ÐL - repeat until results are no longer unique:
   Ṗ       -     remove the last character                abcdeabcd / cbaedcb / cdeab / aed / e   / ""
    Ȯ      -     print z (with no linefeed) and return z
     Ṗ     -     remove the last character                abcdeabc  / cbaedc  / cdea  / ae  / ""  / ""
      U    -     reverse                                  cbaedcba  / cdeabc  / aedc  / ea  / ""  / "" <- no longer unique.

</code>```

Title: Square-unspiral the string!

Body:
Given a string, first square it as follows:

First, write the string.

```<code>abcde
</code>```

Next, write the string rotated one left.

```<code>abcde
bcdea
</code>```

Keep doing this until you have written len(string) lines.

```<code>abcde
bcdea
cdeab
deabc
eabcd
</code>```

Now, read from the string like this:

```<code>----+
+--+|
|+>||
|+-+|
+---+
</code>```

Which gives:

```<code>abcdeabcdcbaedcbcdeabaede
</code>```

Print this string.

Test cases

```<code>abcdef -> abcdefabcdedcbafedcbcdefabcbafedefaf
cena! -> cena!cenanec!anena!cec!a!
ppcg -> ppcgppcppgcpcgpg
abc -> abcabacbc
ab -> abab
a -> a
 ->
</code>```

Please comment if a test case is incorrect.

Remember, this is code-golf, so the code with the smallest number of bytes wins.

Body:
Jelly, <s>11</s> 10 bytes

ẋ2µṖȮṖUµÐL

TryItOnline!, or all tests

How?

The unspiralled square is a series of "top-edge plus right-edge" and "bottom-edge plus left-edge" runs, each of which is the  reverse of the previous run without the first and last letter, and the first of which is the input plus the input without the last letter (e.g. input "abcde" has an output of "abcdeabcd" + "cbaedcb" + "cdeab" + "aed" + "e").

ẋ2µṖȮṖUµÐL - Main link: s                            e.g. abcde
ẋ2         - repeat s twice                          e.g. abcdeabcde
  µ    µ   - monadic chain separation
        ÐL - repeat until results are no longer unique:
   Ṗ       -     remove the last character                abcdeabcd / cbaedcb / cdeab / aed / e   / ""
    Ȯ      -     print z (with no linefeed) and return z
     Ṗ     -     remove the last character                abcdeabc  / cbaedc  / cdea  / ae  / ""  / ""
      U    -     reverse                                  cbaedcba  / cdeabc  / aedc  / ea  / ""  / "" <- no longer unique.


问:
Tips for golfing in Python
What general tips do you have for golfing in Python? I'm looking for ideas which can be applied to code-golf problems and which are also at least somewhat specific to Python (e.g. "remove comments" is not an answer).

Please post one tip per answer.

答:
Use .center in ASCII art

In drawing a symmetrical ASCII art, you can center-justify each line in a fixed width of spaces. For example, "<|>".center(7) gives '  <|>  '. This can be shorter than computing how many spaces are needed to center it.

You can also pad with a different character by doing "<|>".center(7,'_')

Title: Tips for golfing in Python


答:
05AB1E, 12 bytes

```<code>2×[DõQ#¨D?¨R
</code>```

Try it online!

Explanation:

```<code> 2×[DõQ#¨D?¨R
               # Implicit input
 2×            # Repeat twice
   [           # Begin infinite loop
┏>  DõQ#       # If empty string, break
┃       ¨      # Remove last character
┃        D     # Duplicate
┃         ?    # Print with no newline and pop
┃          ¨   # Remove last character
┃           R  # Reverse
┗━━━━━━━━━━━━┛ # Implicit end infinite loop
</code>```

Title: Square-unspiral the string!

Body:
05AB1E, 12 bytes

2×[DõQ#¨D?¨R

Try it online!

Explanation:

 2×[DõQ#¨D?¨R
               # Implicit input
 2×            # Repeat twice
   [           # Begin infinite loop
┏>  DõQ#       # If empty string, break
┃       ¨      # Remove last character
┃        D     # Duplicate
┃         ?    # Print with no newline and pop
┃          ¨   # Remove last character
┃           R  # Reverse
┗━━━━━━━━━━━━┛ # Implicit end infinite loop


问:
Indexable quine
The goal of this challenge is to make a program that outputs the nth letter of its source code where n is given as input to the program. Like most quine challenges, you are not allowed to read your source code as a file or use any builtin quine functions.

Input

An integer 0 <= n < len(program).

Output

The nth character (not byte) of your program.

Winning

Like most codegolf questions, you win the challenge by using the lowest number of bytes to solve the challenge.

Bonuses

-5% If your program supports negative indices python style (e.g. -1 would be the last character of your program). If used with the below bonus, your ranges must support negative indices.

-20% If your program supports ranges as input (any format) in addition to the above requirements.

-25% If your program complete both bonuses.

Leaderboards

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

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

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

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

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

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

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

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

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

var QUESTION_ID=70727,OVERRIDE_USER=32700;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

```

答:
Befunge 93, 5 bytes

This is pretty (very) late but I'll post it anyway:

```<code>&0g,@
</code>```

Title: Indexable quine

Body:
Befunge 93, 5 bytes

This is pretty (very) late but I'll post it anyway:

&0g,@


问:
Ordered list of binary sequences of multiple dimensions
Given a positive integer n, output the 2^n binary sequences of length n sorted in the following precise ordering.

Test cases:

0:

```<code>0 or 1 (defining this is a matter of debate)
</code>```

1:

```<code>0
1
</code>```

2:

```<code>00
01
10
11
</code>```

3:

```<code>000
001
010
100
011
101
110
111
</code>```

4:

```<code>0000
0001
0010
0100
1000
0011
0101
1001
0110
1010
1100
0111
1011
1101
1110
1111
</code>```

etc.

Additionally, the pattern of combinatorics is related to Pascal's Triangle.

0:

```<code>1 (this is given regardless of the definition given to 2^0)
</code>```

1:

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

2:

```<code>1
2
1
</code>```

3:

```<code>1
3
3
1
</code>```

4:

```<code>1
4
6
4
1
</code>```

etc.

答:
Perl, <s>116</s> <s>106</s> <s>105</s> 102 bytes

```<code>sub e{sprintf"%0$%b",@_}sub f{$_=e@_;/0*$/;$%*y/1//-$-[0]}map{say e$_}sort{f($a)<=>f$b}0..2**($%=<>)-1
</code>```

Readable:

```<code>sub e{
    sprintf"%0$%b",@_
}
sub f{
    $_=e@_;/0*$/;$%*y/1//-$-[0]
}
map{
    say e$_
} sort {
    f($a)<=>f$b
} 0..2**($%=<>)-1
</code>```

The subroutine e converts its argument into a binary value, padded with zeros, to be the input length (e.g. input of 5 pads with zeros until it's 5 characters long).  The subroutine f takes such a binary value, and gives it sorting weight according to how it should be processed.

The range 0 .. [input]2-1 is then put through a stable sort, ordering by the weight (here, "stable" means that when two values have the same weight, they are returned in the same order they appear in the input), and then they are fed back to the subroutine e and output.

Some of you may have seen my original post, but I entirely misread the problem yesterday and deleted it immediately after I realized it.

Body:
Perl, <s>116</s> <s>106</s> <s>105</s> 102 bytes

sub e{sprintf"%0$%b",@_}sub f{$_=e@_;/0*$/;$%*y/1//-$-[0]}map{say e$_}sort{f($a)<=>f$b}0..2**($%=<>)-1

Readable:

sub e{
    sprintf"%0$%b",@_
}
sub f{
    $_=e@_;/0*$/;$%*y/1//-$-[0]
}
map{
    say e$_
} sort {
    f($a)<=>f$b
} 0..2**($%=<>)-1

The subroutine e converts its argument into a binary value, padded with zeros, to be the input length (e.g. input of 5 pads with zeros until it's 5 characters long).  The subroutine f takes such a binary value, and gives it sorting weight according to how it should be processed.

The range 0 .. [input]2-1 is then put through a stable sort, ordering by the weight (here, "stable" means that when two values have the same weight, they are returned in the same order they appear in the input), and then they are fed back to the subroutine e and output.

Some of you may have seen my original post, but I entirely misread the problem yesterday and deleted it immediately after I realized it.


问:
Minimum insertions to make palindrome
Today you will be doing another palindrome challenge!

So, your task today is to take a string, and determine the minimum amount of letters required to insert to turn it into a palindrome.

For example, let's take the string fishes.

In this, case the best way would be to add h if, so the result would be 3.

```<code>fishe s
     h if
---------
fishehsif
</code>```

Now let's try with codegolf. Since there is a repeated o, we can just do:

```<code>  codeg  o lf
fl     ed c
-------------
flcodegedoclf
</code>```

to get a result of 5.

Test cases

```<code>ppcg -> 2
codegolf -> 5
palindrome -> 9
stackexchange -> 8
programmingpuzzlesandcodegolf -> 20
</code>```

答:
Python, 112 bytes

d=lambda x,l,h:0if h<l else d(x,l+1,h-1)if x[l]==x[h]else-~min(d(x,l+1,h),d(x,l,h-1));e=lambda x:d(x,0,len(x)-1)
```

<p>Very inefficient.</p>

<p>Try it online! You have to wait a minute for the last case to finish.</p>

<p>Call with <code>e(<string>, 0, <length of string - 1>)</code>, like e("fishes", 0, 5)`.</p>

<p>Ungolfed (sort of) with explanation:</p>

<pre class="lang-py prettyprint-override"><code>def minInsert(x, l, h):                # Declare func, arugments for x, l, h       # d=lambda x,l,h:
  if l >= h:                           # If l is the same or past h                #                 if h<l
    return 0                           #     then return 0                         #                0
  elif x[l] == x[h]:                   # If first and last character are the same  #                        else             if x[l]==x[h]
    return minInsert(x, l + 1, h - 1)  #     then return the min w/o first & last  #                             d(x,l+1,h-1)
  else:                                # If not, we shave off a character          #                                                      else
    a = minInsert(x, l, h - 1)         #     (last one)                            #                                                                d(x,l+1,h)
    b = minInsert(x, l + 1, h)         #     (first one)                           #                                                                           d(x,l,h-1)
    return min(a, b) + 1               #     and add one for the char we took off  #                                                          -~min(          ,          )
</code>```

Title: Minimum insertions to make palindrome

Body:
Python, 112 bytes

d=lambda x,l,h:0if h<l else d(x,l+1,h-1)if x[l]==x[h]else-~min(d(x,l+1,h),d(x,l,h-1));e=lambda x:d(x,0,len(x)-1)

Very inefficient.

Try it online! You have to wait a minute for the last case to finish.

Call with e(<string>, 0, <length of string - 1>), like e("fishes", 0, 5)`.

Ungolfed (sort of) with explanation:

def minInsert(x, l, h):                # Declare func, arugments for x, l, h       # d=lambda x,l,h:
  if l >= h:                           # If l is the same or past h                #                 if h<l
    return 0                           #     then return 0                         #                0
  elif x[l] == x[h]:                   # If first and last character are the same  #                        else             if x[l]==x[h]
    return minInsert(x, l + 1, h - 1)  #     then return the min w/o first & last  #                             d(x,l+1,h-1)
  else:                                # If not, we shave off a character          #                                                      else
    a = minInsert(x, l, h - 1)         #     (last one)                            #                                                                d(x,l+1,h)
    b = minInsert(x, l + 1, h)         #     (first one)                           #                                                                           d(x,l,h-1)
    return min(a, b) + 1               #     and add one for the char we took off  #                                                          -~min(          ,          )


问:
The nth numerator
You can create a list of all rationals 0 < r ≤ 1 by listing them ordered first by denominator and then by numerator:

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

Note that we skip any rational number that already occurred before. E.g. 2/4 is skipped because we already listed 1/2.

In this challenge we're interested in the numerators only. Looking at the list above, write a function or program taking a positive integer n that returns the nth numerator from the list.

Testcases:

```<code>1 -> 1
2 -> 1
3 -> 1
4 -> 2
5 -> 1
6 -> 3
7 -> 1
8 -> 2
9 -> 3
50 -> 4
80 -> 15
</code>```

答:
Jelly, <s>11</s> 9 bytes

```<code>gRỊTµ€Fị@
</code>```

Try it online! or verify all test cases.

How it works

```<code>gRỊTµ€Fị@  Main link. Argument: n

    µ€     Map the monadic chain to the left over [1, ..., n]; for each k:
 R           Range; yield [1, ..., k].
g            Compute the GCD of k and each j in [1, ..., k].
  Ị          Insignificant; yield 1 for 1; 0 for 2, ..., k.
   T         Truth; yield all indices of 1's, i.e., all coprimes with k.
      F      Flatten the resulting 2D array.
       ị@    At-index swapped; return the n-th element.
</code>```

Title: The nth numerator

Body:
Jelly, <s>11</s> 9 bytes

gRỊTµ€Fị@

Try it online! or verify all test cases.

How it works

gRỊTµ€Fị@  Main link. Argument: n

    µ€     Map the monadic chain to the left over [1, ..., n]; for each k:
 R           Range; yield [1, ..., k].
g            Compute the GCD of k and each j in [1, ..., k].
  Ị          Insignificant; yield 1 for 1; 0 for 2, ..., k.
   T         Truth; yield all indices of 1's, i.e., all coprimes with k.
      F      Flatten the resulting 2D array.
       ị@    At-index swapped; return the n-th element.


答:
Python 2, 146 bytes

```<code>from itertools import*
lambda i:sum([sorted({''.join(b)for b in permutations((i-n)*"0"+"1"*n)},key=lambda x:x[::-1])[::-1]for n in range(i+1)],[])
</code>```

I'm still working on this, though any suggestions would be greatly appreciated!

Ungolfed

```<code>i=input()
import itertools
p=[]
for n in range(i+1):
    x=(i-n)*"0"+"1"*n
    t=[]
    for b in itertools.permutations(x):t+=[''.join(b)] if ''.join(b) not in t else []
    p.append(sorted(t, key=lambda x:x[::-1])[::-1])

p=sum(p,[])
print
for line in p:print line
</code>```

Title: Ordered list of binary sequences of multiple dimensions

Body:
Given a positive integer n, output the 2^n binary sequences of length n sorted in the following precise ordering.

Test cases:

0:

```<code>0 or 1 (defining this is a matter of debate)
</code>```

1:

```<code>0
1
</code>```

2:

```<code>00
01
10
11
</code>```

3:

```<code>000
001
010
100
011
101
110
111
</code>```

4:

```<code>0000
0001
0010
0100
1000
0011
0101
1001
0110
1010
1100
0111
1011
1101
1110
1111
</code>```

etc.

Additionally, the pattern of combinatorics is related to Pascal's Triangle.

0:

```<code>1 (this is given regardless of the definition given to 2^0)
</code>```

1:

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

2:

```<code>1
2
1
</code>```

3:

```<code>1
3
3
1
</code>```

4:

```<code>1
4
6
4
1
</code>```

etc.

Body:
Python 2, 146 bytes

from itertools import*
lambda i:sum([sorted({''.join(b)for b in permutations((i-n)*"0"+"1"*n)},key=lambda x:x[::-1])[::-1]for n in range(i+1)],[])

I'm still working on this, though any suggestions would be greatly appreciated!

Ungolfed

i=input()
import itertools
p=[]
for n in range(i+1):
    x=(i-n)*"0"+"1"*n
    t=[]
    for b in itertools.permutations(x):t+=[''.join(b)] if ''.join(b) not in t else []
    p.append(sorted(t, key=lambda x:x[::-1])[::-1])

p=sum(p,[])
print
for line in p:print line


答:
Wolfram Language (Mathematica), <s>53</s> 49 bytes

```<code>(Join@@Array[Pick[r=Range@#,r~GCD~#,1]&,#])[[#]]&
</code>```

Try it online!

Title: The nth numerator

Body:
You can create a list of all rationals 0 < r ≤ 1 by listing them ordered first by denominator and then by numerator:

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

Note that we skip any rational number that already occurred before. E.g. 2/4 is skipped because we already listed 1/2.

In this challenge we're interested in the numerators only. Looking at the list above, write a function or program taking a positive integer n that returns the nth numerator from the list.

Testcases:

```<code>1 -> 1
2 -> 1
3 -> 1
4 -> 2
5 -> 1
6 -> 3
7 -> 1
8 -> 2
9 -> 3
50 -> 4
80 -> 15
</code>```

Body:
Wolfram Language (Mathematica), <s>53</s> 49 bytes

(Join@@Array[Pick[r=Range@#,r~GCD~#,1]&,#])[[#]]&

Try it online!


问:
Output a googol copies of a string
I am interested in seeing programs which don't ask for any input, print a googol copies of some nonempty string, no less, no more, and then stop. A googol is defined as \$10^{100}\$, i.e., 1 followed by a hundred 0's in decimal.

Example output:

```<code>111111111111111111111111111111111111111111111111111111111111111111111111...
</code>```

or

```<code>Hello world
Hello world
Hello world
Hello world
Hello world
Hello world
...
</code>```

The string can also be entirely composed of white space or special symbols. The only exception to identical copies of a fixed string is if your language decorates the output in some way that can not be prevented, but could be trivially undone in a wrapper script, like prepending a line number to each line. The wrapper script in such cases need not be provided.

You can assume your computer will never run out of time, but other than that, your program must have a reasonable demand of resources. Also, you must respect any restrictions that the programming language of your choice poses, for example, you can not exceed a maximum value allowed for its integer types, and at no point more than 4 GB of memory must be needed.

In other words, the program should in principle be testable by running it on your computer. But because of the extent of this number you will be expected to prove that the number of copies of the string it outputs is exactly 10^100 and that the program stops afterwards. Stopping can be exiting or halting or even terminating due to an error, but if so, the error must not produce any output that could not easily be separated from the program's output.

This is code-golf,  so the solution with the fewest bytes wins.

Example solution (C, ungolfed, 3768 bytes)

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

int main() {
  int a00, a01, a02, a03, ..., a99;
  for(a00 = 0; a00 < 10; a00++)
  for(a01 = 0; a01 < 10; a01++)
  for(a02 = 0; a02 < 10; a02++)
  for(a03 = 0; a03 < 10; a03++)
  ...
  for(a99 = 0; a99 < 10; a99++)
    puts("1");
  return 0;
}
</code>```

答:
Slashalash, 36 ASCII characters (4 distinct)

```<code>/t./.ttttt//.t/t\..........//t//t...
</code>```

Outputs the . character 3*10^125 times, meaning that it outputs the string consisting of 3*10^25 repetitions of the . character, 10^100 times.

Explanation:

/t./.ttttt/: Replace t. with .ttttt throughout the rest of the program, repeating until no instances of t. remain. This replaces t... with ... followed by 125 ts.

/.t/t\........../: Replace .t with t.......... throughout the rest of the program, repeating until no instances of .t remain. This takes the ... followed by 125 ts, and turns it into 125 ts followed by 10^125 occurrences of ....

/t//: Remove all remaining ts.

t...: This gets replaced with 3*10^125 .s. Output them.

Now, outputting 10^100 repetitions of 3*10^25 repetitions of something kind of feels like cheating. This program outputs the . character exactly 10^100 times, using 45 ASCII characters:

```<code>/T/tttttttttt//.t/t..........//t//.TTTTTTTTTT
</code>```

Explanation of this one:

/T/tttttttttt/: Replace T with tttttttttt throughout the rest of the program. This replaces TTTTTTTTTT with 100 repetitions of t.

/.t/t........../: Replace .t with t.......... throughout the rest of the program. This takes the . followed by 100 ts, and turns it into 100 ts followed by 10^100 .s.

/t//: Remove all remaining ts.

.TTTTTTTTTT: This gets replaced with 10^100 .s. Output them.

Finally, here's a compromise program, which outputs the . character 2*10^100 times, using 40 characters:

```<code>/t./.tttttttttt//.t/t\..........//t//t..
</code>```

Title: Output a googol copies of a string

Body:
Slashalash, 36 ASCII characters (4 distinct)

/t./.ttttt//.t/t\..........//t//t...

Outputs the . character 3*10^125 times, meaning that it outputs the string consisting of 3*10^25 repetitions of the . character, 10^100 times.

Explanation:

/t./.ttttt/: Replace t. with .ttttt throughout the rest of the program, repeating until no instances of t. remain. This replaces t... with ... followed by 125 ts.

/.t/t\........../: Replace .t with t.......... throughout the rest of the program, repeating until no instances of .t remain. This takes the ... followed by 125 ts, and turns it into 125 ts followed by 10^125 occurrences of ....

/t//: Remove all remaining ts.

t...: This gets replaced with 3*10^125 .s. Output them.

Now, outputting 10^100 repetitions of 3*10^25 repetitions of something kind of feels like cheating. This program outputs the . character exactly 10^100 times, using 45 ASCII characters:

/T/tttttttttt//.t/t..........//t//.TTTTTTTTTT

Explanation of this one:

/T/tttttttttt/: Replace T with tttttttttt throughout the rest of the program. This replaces TTTTTTTTTT with 100 repetitions of t.

/.t/t........../: Replace .t with t.......... throughout the rest of the program. This takes the . followed by 100 ts, and turns it into 100 ts followed by 10^100 .s.

/t//: Remove all remaining ts.

.TTTTTTTTTT: This gets replaced with 10^100 .s. Output them.

Finally, here's a compromise program, which outputs the . character 2*10^100 times, using 40 characters:

/t./.tttttttttt//.t/t\..........//t//t..


答:
Pyth, 10 bytes

test suite.

```<code>l.-Qe@y_Qy

         y   All subsequences of the input (implicit), sorted by length
      y_Q    All subsequences of the reversed input, sorted by length
     @       Their setwise intersection: the common subsequences
    e        Last element: the longest common subsequence
 .-Q         Remove it bagwise from the input: the letters not in this LCS
l            The length of that
</code>```

There's a few equivalent characterizations of the value we're after:

The fewest insertions needed to make a palindrome

The fewest deletions needed to make a palindrome

Half the number of delete or insert operations needed to transform the string to its reverse

The length of the input with its longest palindromic subsequence removed

The length of the input, removing the longest common subsequence between it and its reverse. (The code uses this one.)

The common idea is the "skeleton" of letters in the input that are matched with  letters of the input in the final product.

```<code>  codeg  o lf
   *  *  *
fl o  gedoc

flcodegedoclf
</code>```

This skeleton is always a palindrome, with letters matching to their reversed counterparts. Each non-skeleton letters is unmatched and must have its counterpart inserted.

A same-length alternative instead uses the fourth condition, the length of the input minus the length of its longest palindromic subsequence

```<code>l.-Qef_ITy
</code>```

Link to test suite.

The part that's different is

```<code>f_ITy

    y   All subsequences of the input (implicit), sorted by length.
f       Filtered on:
 _IT     being invariant under reversal, i.e. a palindrome
</code>```

For both, instead of removing the palindromic subsequence from the input and taking the length, we could instead subtract its length from the length of the input. Either one costs 4 bytes: -lQl vs l.-Q.

Title: Minimum insertions to make palindrome

Body:
Today you will be doing another palindrome challenge!

So, your task today is to take a string, and determine the minimum amount of letters required to insert to turn it into a palindrome.

For example, let's take the string fishes.

In this, case the best way would be to add h if, so the result would be 3.

```<code>fishe s
     h if
---------
fishehsif
</code>```

Now let's try with codegolf. Since there is a repeated o, we can just do:

```<code>  codeg  o lf
fl     ed c
-------------
flcodegedoclf
</code>```

to get a result of 5.

Test cases

```<code>ppcg -> 2
codegolf -> 5
palindrome -> 9
stackexchange -> 8
programmingpuzzlesandcodegolf -> 20
</code>```

Body:
Pyth, 10 bytes

test suite.

l.-Qe@y_Qy

         y   All subsequences of the input (implicit), sorted by length
      y_Q    All subsequences of the reversed input, sorted by length
     @       Their setwise intersection: the common subsequences
    e        Last element: the longest common subsequence
 .-Q         Remove it bagwise from the input: the letters not in this LCS
l            The length of that

There's a few equivalent characterizations of the value we're after:

The fewest insertions needed to make a palindrome

The fewest deletions needed to make a palindrome

Half the number of delete or insert operations needed to transform the string to its reverse

The length of the input with its longest palindromic subsequence removed

The length of the input, removing the longest common subsequence between it and its reverse. (The code uses this one.)

The common idea is the "skeleton" of letters in the input that are matched with  letters of the input in the final product.

  codeg  o lf
   *  *  *
fl o  gedoc

flcodegedoclf

This skeleton is always a palindrome, with letters matching to their reversed counterparts. Each non-skeleton letters is unmatched and must have its counterpart inserted.

A same-length alternative instead uses the fourth condition, the length of the input minus the length of its longest palindromic subsequence

l.-Qef_ITy

Link to test suite.

The part that's different is

f_ITy

    y   All subsequences of the input (implicit), sorted by length.
f       Filtered on:
 _IT     being invariant under reversal, i.e. a palindrome

For both, instead of removing the palindromic subsequence from the input and taking the length, we could instead subtract its length from the length of the input. Either one costs 4 bytes: -lQl vs l.-Q.


问:
How many integers contain a number in a specific range
The program should take input the number, the start of the range and the end of the range, and output how many integers the number appears between the start and end of the range, inclusive. Both programs and functions are allowed.

Example Inputs

For example:

```<code>//Input example 1
3,1,100
//Input example 2
3
1
100
//Input example 3
3 1 100
//Input example 4
a(3, 1, 100);
</code>```

All the above four input examples are valid and all of them mean that 3 is the number in question, 1 is the beginning of the range and 100 the the end of the range.

And then the program should output how many times 3 appears in the range from 1 to 100 inclusive. 3 appears in the integers 3, 13, 23, 30, 31, 32, 33, ..., 93 at a total of 19 times. So the program should output 19 as the output because that is how many times 3 appears in the range from 1 to 100.

Rules

Both programs and functions are allowed.

All numbers will be integers, meaning that there will not be any floats or doubles.

Note: the sought number will always be in the range 0≤x≤127. There will be no cases where it will be outside this 0≤x≤127 range.

As in the first example, with the case as 33, the number 3 will be counted as appearing only once, not twice.

The values of the start and end of the range will be between -65536 and 65535 inclusive.

The value of range's start will never exceed or equal to range's end. start < end

Also the range is inclusive. For example if the input was 8 8 10, the range would be 8≤x≤10 and hence the output will be 1.

Input can be taken in any of the ways shown in the examples. Input can be taken as a string or as a number, any way you wish.

Test Cases

```<code>3 1 100
19

3 3 93
19

12,-200,200
24          //This is because 12 appears in -129, -128, ..., -112, -12, 12, 112, 120, 121, 122, ...

123,1,3
0           //This is because all of 123's digits have to appear in the same order

3 33 34
2           //Because 3 appears in 2 numbers: 33 and 34

a(0,-1,1);
1

$ java NotVerbose 127 -12 27
0
</code>```

Snack Snippet

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

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

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

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

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

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

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

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

/* Configuration */

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

/* App */

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

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

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

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

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

getAnswers();

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

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

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

function process() {
  var valid = [];

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

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

  });

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

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

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

    var lang = a.language;
    if (/ b.lang) return 1;
    if (a.lang < b.lang) return -1;
    return 0;
  });

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

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

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

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

table thead {
  font-weight: bold;
}

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

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

```

答:
R, 32 bytes

Quite straightforward:

```<code>function(a,b,c)sum(grepl(a,b:c))
</code>```

Body:
R, 32 bytes

Quite straightforward:

function(a,b,c)sum(grepl(a,b:c))


答:
Haskell, 40 bytes

((0:[n|d<-[1..],n<-[1..d],gcd n d<2])!!)
```

An anonymous function. Pretty straightforward: uses a list comprehension to generate an infinite list, looping over all numerators n and relatively prime denominators d. To convert zero-index to one-indexed, we prepend a 0, which takes 4 bytes.

Title: The nth numerator

Body:
Haskell, 40 bytes

((0:[n|d<-[1..],n<-[1..d],gcd n d<2])!!)

An anonymous function. Pretty straightforward: uses a list comprehension to generate an infinite list, looping over all numerators n and relatively prime denominators d. To convert zero-index to one-indexed, we prepend a 0, which takes 4 bytes.


答:
C, <s>89</s> 121 bytes

#define g(a) f(a,a+strlen(a)-1)
f(char*a,char*b){return a>=b?0:*a-*b?f(a+1,b)<f(a,b-1)?f(++a,b)+1:f(a,--b)+1:f(++a,--b);}
```
<p>Shameless port of Oliver's answer, could not think of any shorter solution.</p>
<p><code>g</code> calls <code>f</code> with the pointer to the first and the last char of a string (the last char is part of the string, not the <code>'\0'</code>). Gets even more inefficient because <code>f</code> is called two times for the <code>min</code> case.</p>
<p>Ungolfed:</p>
<pre class="lang-c prettyprint-override"><code>f(char*a,char*b){
 return a>=b ? 0 :
   *a-*b ?    //if the pointed chars are not the same
     f(a+1,b)<f(a,b-1) ? f(a+1,b)+1 : f(a,b-1)+1    //min(f..,f..)+1
   : f(a+1,b-1);  //if they were the same, make it more narrow
 }
</code>```

Usage:

int main(){
 char s[]="palindrome";
 printf("%d\n",g(s));
}
```

Title: Minimum insertions to make palindrome

Body:
C, <s>89</s> 121 bytes

#define g(a) f(a,a+strlen(a)-1)
f(char*a,char*b){return a>=b?0:*a-*b?f(a+1,b)<f(a,b-1)?f(++a,b)+1:f(a,--b)+1:f(++a,--b);}

Shameless port of Oliver's answer, could not think of any shorter solution.

g calls f with the pointer to the first and the last char of a string (the last char is part of the string, not the '\0'). Gets even more inefficient because f is called two times for the min case.

Ungolfed:

f(char*a,char*b){
 return a>=b ? 0 :
   *a-*b ?    //if the pointed chars are not the same
     f(a+1,b)<f(a,b-1) ? f(a+1,b)+1 : f(a,b-1)+1    //min(f..,f..)+1
   : f(a+1,b-1);  //if they were the same, make it more narrow
 }

Usage:

int main(){
 char s[]="palindrome";
 printf("%d\n",g(s));
}


问:
Binary Convolution
A binary convolution is described by a number M, and is applied to a number N. For each bit in the binary representation of M, if the bit is set (1), the corresponding bit in the output is given by XORing the two bits adjacent to the corresponding bit in N (wrapping around when necessary). If the bit is not set (0), then the corresponding bit in the output is given by the corresponding bit in N.

A worked example (with 8-bit values):

Let N = 150, M = 59. Their binary respresentations are (respectively) 10010110 and 00111011.

Based on M's binary representation, bits 0, 1, 3, 4, and 5 are convolved.

The result for bit 0 is given by XORing bits 1 and 7 (since we wrap around), yielding 1.

The result for bit 1 is given by XORing bits 0 and 2, yielding 0.

The result for bit 2 is given by the original bit 2, yielding 1.

The result for bit 3 is given by XORing bits 2 and 4, yielding 0.

The result for bit 4 is given by XORing bits 3 and 5, yielding 0.

The result for bit 5 is given by XORing bits 4 and 6, yielding 1.

The results for bits 6 and 7 are given by the original bits 6 and 7, yielding 0 and 1.

The output is thus 10100110 (166).

The Challenge

Given N and M, output the result of performing the binary convolution described by M upon N. Input and output may be in any convenient, consistent, and unambiguous format. N and M will always be in the (inclusive) range [0, 255] (8-bit unsigned integers), and their binary representations should be padded to 8 bits for performing the binary convolution.

Test Cases

```<code>150 59 -> 166
242 209 -> 178
1 17 -> 0
189 139 -> 181
215 104 -> 215
79 214 -> 25
190 207 -> 50
61 139 -> 180
140 110 -> 206
252 115 -> 143
83 76 -> 31
244 25 -> 245
24 124 -> 60
180 41 -> 181
105 239 -> 102
215 125 -> 198
49 183 -> 178
183 158 -> 181
158 55 -> 186
215 117 -> 198
255 12 -> 243
</code>```

Title: Binary Convolution

Body:
Python 2, 35 bytes

lambda m,n:n^m&(n^n*257/2^n*2^n>>7)


问:
Palindromic palindrome generator
Create a program, that converts input string to a palindrome starting with the input string. The program itself must be a palindrome.

For example input: neverod, print neveroddoreven. You should handle multi-word, multi-line inputs as well.

答:
Python 2, 51 bytes

```<code>s=input();print s+s[::-1]#]1-::[s+s tnirp;)(tupni=s
</code>```

I'm surprised no-one thought of this! Needs quoted input (' or "). If functions were allowed, I could have done this for 37 bytes instead:

```<code>lambda x:x+x[::-1]#]1-::[x+x:x adbmal
</code>```

Title: Palindromic palindrome generator

Body:
Python 2, 51 bytes

s=input();print s+s[::-1]#]1-::[s+s tnirp;)(tupni=s

I'm surprised no-one thought of this! Needs quoted input (' or "). If functions were allowed, I could have done this for 37 bytes instead:

lambda x:x+x[::-1]#]1-::[x+x:x adbmal


答:
MATL, <s>17</s> 13 bytes

```<code>:tt!/XR6#uG))
</code>```

Try it online! Or verify all test cases.

Input size may be limited by floating point accuracy. All test cases give the correct result.

Explanation

This generates all fractions k/m with k, m in [1 2 ...n], as an n×n matrix. The row indicates the numerator and the column indicates the denominator. Actually the matrix entry contains the inverse fraction m/k, instead of k/m, but this is irrelevant and can be ignored in the rest of the explanation.

Matrix entries are implicitly considered to be sorted in column-major order. In this case this corresponds to the required order: denominator, then numerator.

Three types of entries need to be disregarded from this matrix:

Entries k/m, k>m, that have the same value as a previous entry (for example, 2/4 is disregarded because it is the same as 1/2)

Entries k/k, k>1.
Entries that have a numerator exceeding the denominator

Entries k/m, k<m (these are not part of the problem).

Disregarding entries is done with a unique function, which stably removes duplicate values and outputs the indices of the surviving entries. With this, entries of type 1 above are automatically removed. To deal with types 2 and 3, the matrix entries at the diagonal and below are set to 0. This way, all zero entries will be removed except the first (corresponding to the valid fraction 1/1).

Consider input 4 as an example.

```<code>:     % Input n implicitly. Push range [1 2 ...n]
      % STACK: [1 2 3 4]
t     % Duplicate
      % STACK: [1 2 3 4], [1 2 3 4]
t!    % Duplicate and transpose
      % STACK: [1 2 3 4], [1 2 3 4], [1; 2; 3; 4]
/     % Divide element-wise with broadcast: gives matrix with all pairs
      % STACK: [1 2 3 4], [1       2       3       4;
                           0.5000  1       1.5000  2;
                           0.3333  0.6667  1       1.3333;
                           0.2500  0.5000  0.7500  1     ]
XR    % Upper triangular part above the diagonal. This sets to 0 all entries
      % corresponding to fractions that equal or exceed 1. (Since the matrix
      % actually contains the inverse fractions, nonzero entries will contain
      % values greater than 1)
      % STACK: [1 2 3 4], [0       2       3       4;
                           0       0       1.5000  2;
                           0       0       0       1.3333;
                           0       0       0       0     ]
6#u   % Indices of first appearance of unique elements
      % STACK: [1 2 3 4], [1; 5; 9; 10; 13; 15]
G     % Push input n again
      % STACK: [1 2 3 4], [1; 5; 9; 10; 13; 15], 4
)     % Index: get the n-th entry from the array of indices of unique elements
      % STACK: [1 2 3 4], 10
)     % Index (modular): get the corresponding real part. Display implicitly
      % STACK: 2
</code>```

Title: The nth numerator

Body:
MATL, <s>17</s> 13 bytes

:tt!/XR6#uG))

Try it online! Or verify all test cases.

Input size may be limited by floating point accuracy. All test cases give the correct result.

Explanation

This generates all fractions k/m with k, m in [1 2 ...n], as an n×n matrix. The row indicates the numerator and the column indicates the denominator. Actually the matrix entry contains the inverse fraction m/k, instead of k/m, but this is irrelevant and can be ignored in the rest of the explanation.

Matrix entries are implicitly considered to be sorted in column-major order. In this case this corresponds to the required order: denominator, then numerator.

Three types of entries need to be disregarded from this matrix:

Entries k/m, k>m, that have the same value as a previous entry (for example, 2/4 is disregarded because it is the same as 1/2)

Entries k/k, k>1.
Entries that have a numerator exceeding the denominator

Entries k/m, k<m (these are not part of the problem).

Disregarding entries is done with a unique function, which stably removes duplicate values and outputs the indices of the surviving entries. With this, entries of type 1 above are automatically removed. To deal with types 2 and 3, the matrix entries at the diagonal and below are set to 0. This way, all zero entries will be removed except the first (corresponding to the valid fraction 1/1).

Consider input 4 as an example.

:     % Input n implicitly. Push range [1 2 ...n]
      % STACK: [1 2 3 4]
t     % Duplicate
      % STACK: [1 2 3 4], [1 2 3 4]
t!    % Duplicate and transpose
      % STACK: [1 2 3 4], [1 2 3 4], [1; 2; 3; 4]
/     % Divide element-wise with broadcast: gives matrix with all pairs
      % STACK: [1 2 3 4], [1       2       3       4;
                           0.5000  1       1.5000  2;
                           0.3333  0.6667  1       1.3333;
                           0.2500  0.5000  0.7500  1     ]
XR    % Upper triangular part above the diagonal. This sets to 0 all entries
      % corresponding to fractions that equal or exceed 1. (Since the matrix
      % actually contains the inverse fractions, nonzero entries will contain
      % values greater than 1)
      % STACK: [1 2 3 4], [0       2       3       4;
                           0       0       1.5000  2;
                           0       0       0       1.3333;
                           0       0       0       0     ]
6#u   % Indices of first appearance of unique elements
      % STACK: [1 2 3 4], [1; 5; 9; 10; 13; 15]
G     % Push input n again
      % STACK: [1 2 3 4], [1; 5; 9; 10; 13; 15], 4
)     % Index: get the n-th entry from the array of indices of unique elements
      % STACK: [1 2 3 4], 10
)     % Index (modular): get the corresponding real part. Display implicitly
      % STACK: 2


问:
N-dimensional Circles!
Write a program that takes two numbers as its input. The first one is the number of dimensions - 0 for a dot, 1 for a straight line, 2 for a circle, 3 for a sphere. The second number is the radius of the object, or, if it's 1-dimensional, the number itself. Output 0 for 0 dimensions. The output is the length/area/volume of the object.

If we call the first number n, the second one r, and the output x, we get that:

for n = 0, x = 1

for n = 1, x = 2×r

for n = 2, x = r2×π

for n = 3, x = (4/3)×r3×π

and so on... if you want, though.

Notes:

Cases when one or both numbers are negative, or when the first number is not whole, don't need to be covered.

The program must not read from any file and the only input are those two numbers.

The output should use only numerals (e.g. not "14*pi"), and should be accurate to at least two decimal digits.

As for n = 0, you can output 0 if it makes the code shorter.

Extra swag for an answer covering even 4 and more-dimensional "spheres"!

It's code-golf, so the shortest answer in bytes wins!

Examples:

```<code> 1 1 -> 2

 2 3 -> 28,27

 3 1 -> 4,19

 3 4,5 -> 381,70

 1 9.379 -> 18.758

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

答:
Mathematica, 18 bytes, up to ~168.15 trillion dimensions

```<code>Pi^(a=.5#)/a!#2^#&
</code>```

Anonymous function. Takes two numbers as input, and returns an inexact number as output. Works with any number of dimensions. Outputs 1. for n = 0. Uses the formula from Volume of an n-ball on Wikipedia.

Explanation

We are attempting to compute πn/2/Γ(n/2 + 1)·Rn, or N[Pi^(n/2)/Gamma[n/2 + 1] R^n] in Mathematica. In our case, # (first argument) is n and #2 (second argument) is R. This leaves us with N[Pi^(#/2)/Gamma[#/2 + 1] #2^#] &, which can be golfed as follows:

```<code>N[Pi^(#/2)/Gamma[#/2 + 1] #2^#] &
Pi^(.5#)/Gamma[.5# + 1] #2^# &    (* replace exact with approximate numbers*)
Pi^(.5#)/(.5#)! #2^# &            (* n! == Gamma[n + 1] *)
Pi^(a=.5#)/a! #2^# &              (* replace repeated .5# *)
Pi^(a=.5#)/a!#2^#&                (* remove whitespace *)
</code>```

and thus, our original program.

Title: N-dimensional Circles!

Body:
Mathematica, 18 bytes, up to ~168.15 trillion dimensions

Pi^(a=.5#)/a!#2^#&

Anonymous function. Takes two numbers as input, and returns an inexact number as output. Works with any number of dimensions. Outputs 1. for n = 0. Uses the formula from Volume of an n-ball on Wikipedia.

Explanation

We are attempting to compute πn/2/Γ(n/2 + 1)·Rn, or N[Pi^(n/2)/Gamma[n/2 + 1] R^n] in Mathematica. In our case, # (first argument) is n and #2 (second argument) is R. This leaves us with N[Pi^(#/2)/Gamma[#/2 + 1] #2^#] &, which can be golfed as follows:

N[Pi^(#/2)/Gamma[#/2 + 1] #2^#] &
Pi^(.5#)/Gamma[.5# + 1] #2^# &    (* replace exact with approximate numbers*)
Pi^(.5#)/(.5#)! #2^# &            (* n! == Gamma[n + 1] *)
Pi^(a=.5#)/a! #2^# &              (* replace repeated .5# *)
Pi^(a=.5#)/a!#2^#&                (* remove whitespace *)

and thus, our original program.


答:
JavaScript, <s>61</s> <s>51</s> <s>49</s> 43 bytes

0-3 dimensions are supported because there is no 4th dimension.

Thanks to @Hedi for saving 7 bytes

```<code>d=(n,r)=>r**n*(n<2?n+1:Math.PI*(n<3?1:4/3))
</code>```

Creates function d. Then raises r to the nth power and then multiplies it with a number depending on n using ternary operators. Outputs 1 for n=0

Gives output to at least 2 decimal places (10+ dp)

Here's a snack snippet!

var N = document.getElementById("n");
var R = document.getElementById("r");
N.value="3";//default
R.value="4.5";//default
d=(n,r)=>r**n*(n<2?n+1:Math.PI*(n<3?1:4/3));
var b = document.getElementById("b");
b.onclick = function() {
  var s = document.getElementById("s");
  var n = document.getElementById("n").value;
  var r = document.getElementById("r").value;
  s.textContent = d(parseFloat(n),parseFloat(r));
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>span {border:1px solid black;padding:10px;font-size:30px;}</code>```

Value of n: <input id="n" type="number"></input>
Value of r: <input id="r" type="number"></input>

<button id="b">Calculate!</button>

THERE IS NO 4TH DIMENSION```

Title: N-dimensional Circles!

Body:
Write a program that takes two numbers as its input. The first one is the number of dimensions - 0 for a dot, 1 for a straight line, 2 for a circle, 3 for a sphere. The second number is the radius of the object, or, if it's 1-dimensional, the number itself. Output 0 for 0 dimensions. The output is the length/area/volume of the object.

If we call the first number n, the second one r, and the output x, we get that:

for n = 0, x = 1

for n = 1, x = 2×r

for n = 2, x = r2×π

for n = 3, x = (4/3)×r3×π

and so on... if you want, though.

Notes:

Cases when one or both numbers are negative, or when the first number is not whole, don't need to be covered.

The program must not read from any file and the only input are those two numbers.

The output should use only numerals (e.g. not "14*pi"), and should be accurate to at least two decimal digits.

As for n = 0, you can output 0 if it makes the code shorter.

Extra swag for an answer covering even 4 and more-dimensional "spheres"!

It's code-golf, so the shortest answer in bytes wins!

Examples:

```<code> 1 1 -> 2

 2 3 -> 28,27

 3 1 -> 4,19

 3 4,5 -> 381,70

 1 9.379 -> 18.758

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

Body:
JavaScript, <s>61</s> <s>51</s> <s>49</s> 43 bytes

0-3 dimensions are supported because there is no 4th dimension.

Thanks to @Hedi for saving 7 bytes

d=(n,r)=>r**n*(n<2?n+1:Math.PI*(n<3?1:4/3))

Creates function d. Then raises r to the nth power and then multiplies it with a number depending on n using ternary operators. Outputs 1 for n=0

Gives output to at least 2 decimal places (10+ dp)

Here's a snack snippet!

var N = document.getElementById("n");
var R = document.getElementById("r");
N.value="3";//default
R.value="4.5";//default
d=(n,r)=>r**n*(n<2?n+1:Math.PI*(n<3?1:4/3));
var b = document.getElementById("b");
b.onclick = function() {
  var s = document.getElementById("s");
  var n = document.getElementById("n").value;
  var r = document.getElementById("r").value;
  s.textContent = d(parseFloat(n),parseFloat(r));
}

span {border:1px solid black;padding:10px;font-size:30px;}

Value of n: <input id="n" type="number"></input>
Value of r: <input id="r" type="number"></input><br>
<button id="b">Calculate!</button><br><br><br>
<span id="s">THERE IS NO 4TH DIMENSION</span>


答:
Haskell, <s>74</s> <s>65</s> 36 bytes + extra swag

```<code>0%r=1
1%r=2*r
n%r=2*pi*r^2/n*(n-2)%r
</code>```

Recursive formula, works for all dimensions that can be presented exactly as a double-precision floating point number but will loop infinitely for non-integral dimensions. The old version for posteriority's sake:

```<code>n%r=(max 1$1-(-1)**n)*(2*pi)^(floor$n/2)*r**n/product[n,n-2..1.1]
</code>```

<s>Works for all dimensions. Uses the formula from the tau manifesto.
product[n,n-2..1.1] is a double factorial hack that won't count zero for n==2</s>

Title: N-dimensional Circles!

Body:
Haskell, <s>74</s> <s>65</s> 36 bytes + extra swag

0%r=1
1%r=2*r
n%r=2*pi*r^2/n*(n-2)%r

Recursive formula, works for all dimensions that can be presented exactly as a double-precision floating point number but will loop infinitely for non-integral dimensions. The old version for posteriority's sake:

n%r=(max 1$1-(-1)**n)*(2*pi)^(floor$n/2)*r**n/product[n,n-2..1.1]

<s>Works for all dimensions. Uses the formula from the tau manifesto.
product[n,n-2..1.1] is a double factorial hack that won't count zero for n==2</s>


问:
Matrix property X revisited (or the Joy of X)
This challenge is partly an algorithms challenge, partly an optimization challenge and partly simply a fastest code challenge.

A T matrix is fully specified by its first row r and first column c. Each remaining element of the matrix is just a copy of the element that is diagonally up and left. That is M[i,j] = M[i-1,j-1]. We will allow T matrices which are not square. We do however always assume that the number of rows is no more than the number of columns. For example, consider the following 3 by 5 T matrix.

```<code>10111
11011
11101
</code>```

We say a matrix has property X if it contains two non-empty sets of columns with non-identical indices which have the same (vector) sum. The vector sum of one or more columns is simply an element-wise summation of their columns.  That is the sum of two or more columns containing x elements each is another column containing x elements. The sum of one column is trivially the column itself.

The matrix above trivially has property X as the first and last columns are the same. The identity matrix never has property X.

If we just remove the last column of the matrix above then we get an example which does not have property X and would give a score of 4/3.

```<code>1011
1101
1110
</code>```

The task

The task is to write code to find the highest scoring T matrix with binary entries  and which does not have property X. For clarity, a matrix with binary entries has the property that each one of its entries is either 0 or 1.

Score

Your score will be the number columns divided by the number of rows in your best scoring matrix.

Tie Breaker

If two answers have the same score, the one submitted first wins.

In the (very) unlikely event that someone finds a method to get unlimited scores, the first valid proof of such a solution will be accepted.  In the even more unlikely event that you can find a proof of optimality of a finite matrix I will of course award the win too.

Hint

All the answers at Find highest scoring matrix without property X are valid here but they are not optimal. There are T matrices without property X which are not cyclic.

For example, there is a 7 by 12 T matrix without property X but no such cyclic matrix.

21/11 would beat all the current answers from this and the previous challenge.

Languages and libraries

You can use any language which has a freely available compiler/interpreter/etc. for Linux and any libraries which are also freely available for Linux.

Bonus The first answer with a score greater than 2 gets an immediate 200 point bounty award.  Ton Hospel has now achieved this!

Current leader board

C++. Score 31/15 by Ton Hospel

Java. Score 36/19 by Peter Taylor

Haskell. Score 14/8 by alexander-brett

Body:
C++, Score <s>23/12</s> <s>25/13</s> <s>27/14</s> <s>28/14</s> 31/15

Finally a result with ratio > 2:

rows=15,cols=31
1 1 0 0 1 0 0 0 1 1 1 1 0 1 0 1 1 0 0 1 0 0 0 1 1 1 1 0 1 1 0
1 1 1 0 0 1 0 0 0 1 1 1 1 0 1 0 1 1 0 0 1 0 0 0 1 1 1 1 0 1 1
1 1 1 1 0 0 1 0 0 0 1 1 1 1 0 1 0 1 1 0 0 1 0 0 0 1 1 1 1 0 1
1 1 1 1 1 0 0 1 0 0 0 1 1 1 1 0 1 0 1 1 0 0 1 0 0 0 1 1 1 1 0
1 1 1 1 1 1 0 0 1 0 0 0 1 1 1 1 0 1 0 1 1 0 0 1 0 0 0 1 1 1 1
0 1 1 1 1 1 1 0 0 1 0 0 0 1 1 1 1 0 1 0 1 1 0 0 1 0 0 0 1 1 1
0 0 1 1 1 1 1 1 0 0 1 0 0 0 1 1 1 1 0 1 0 1 1 0 0 1 0 0 0 1 1
1 0 0 1 1 1 1 1 1 0 0 1 0 0 0 1 1 1 1 0 1 0 1 1 0 0 1 0 0 0 1
0 1 0 0 1 1 1 1 1 1 0 0 1 0 0 0 1 1 1 1 0 1 0 1 1 0 0 1 0 0 0
0 0 1 0 0 1 1 1 1 1 1 0 0 1 0 0 0 1 1 1 1 0 1 0 1 1 0 0 1 0 0
0 0 0 1 0 0 1 1 1 1 1 1 0 0 1 0 0 0 1 1 1 1 0 1 0 1 1 0 0 1 0
1 0 0 0 1 0 0 1 1 1 1 1 1 0 0 1 0 0 0 1 1 1 1 0 1 0 1 1 0 0 1
0 1 0 0 0 1 0 0 1 1 1 1 1 1 0 0 1 0 0 0 1 1 1 1 0 1 0 1 1 0 0
0 0 1 0 0 0 1 0 0 1 1 1 1 1 1 0 0 1 0 0 0 1 1 1 1 0 1 0 1 1 0
1 0 0 1 0 0 0 1 0 0 1 1 1 1 1 1 0 0 1 0 0 0 1 1 1 1 0 1 0 1 1

I completely explored 1 to 14 rows. 15 would take too long to completely explore. The results are:

1/1   = 1
2/2   = 1
4/3   = 1.333
5/4   = 1.25
7/5   = 1.4
9/6   = 1.5
12/7  = 1.714
14/8  = 1.75
16/9  = 1.778
18/10 = 1.8
20/11 = 1.818
23/12 = 1.917
25/13 = 1.923
28/14 = 2

The code given below is an older version of the program. The newest version is at https://github.com/thospel/personal-propertyX.

/*
  Compile using something like:
    g++ -Wall -O3 -march=native -fstrict-aliasing -std=c++11 -g propertyX.cpp -lpthread -o propertyX
*/
#include <cstdint>
#include <climits>
#include <ctgmath>
#include <iostream>
#include <vector>
#include <array>
#include <chrono>
#include <mutex>
#include <atomic>
#include <thread>

using namespace std;

const int ELEMENTS = 2;

using uint    = unsigned int;
using Element = uint64_t;
using Column  = array<Element, ELEMENTS>;
using Set     = vector<Column>;
using Sum     = uint8_t;
using Index   = uint32_t;
using sec = chrono::seconds;

int const PERIOD = 5*60;
int const MAX_ROWS = 54;
int const COL_FACTOR = (MAX_ROWS+1) | 1;                // 55
int const ROW_ZERO   = COL_FACTOR/2;                    // 27
int const ROWS_PER_ELEMENT = CHAR_BIT * sizeof(Element) / log2(COL_FACTOR); //11
Element constexpr ELEMENT_FILL(Element v = ROW_ZERO, int n = ROWS_PER_ELEMENT) {
    return n ? ELEMENT_FILL(v, n-1) * COL_FACTOR + v : 0;
}
Element constexpr POWN(Element v, int n) {
    return n ? POWN(v, n-1)*v : 1;
}
Element const ELEMENT_TOP = POWN(COL_FACTOR, ROWS_PER_ELEMENT -1);
int const MAX_COLS = ROWS_PER_ELEMENT * ELEMENTS;       // 22

atomic<Index> col_next;
atomic<uint>  period;
chrono::steady_clock::time_point start;
mutex period_mutex;

uint ratio_row;
uint ratio_col;
mutex ratio_mutex;

auto const nr_threads = thread::hardware_concurrency();
// auto const nr_threads = 1;

struct State {
    State(uint cols);
    void process(Index i);
    void extend(uint row);
    void print(uint rows);
    Index nr_columns() const { return static_cast<Index>(1) << cols_; }

    Column last_;
    Element top_;
    int top_offset_;
    uint ratio_row_ = 0;
    uint ratio_col_ = 1;
    uint cols_;
    array<Sum, MAX_ROWS + MAX_COLS -1> side;
    vector<Set> sets;
};

ostream& operator<<(ostream& os, Column const& column) {
    for (int i=0; i<ELEMENTS; ++i) {
        auto v = column[i];
        for (int j=0; j<ROWS_PER_ELEMENT; ++j) {
            auto bit = v / ELEMENT_TOP;
            cout << " " << bit;
            v -= bit * ELEMENT_TOP;
            v *= COL_FACTOR;
        }
    }
    return os;
}

State::State(uint cols) : cols_{cols} {
    sets.resize(MAX_ROWS+2);
    for (int i=0; i<2; ++i) {
        sets[i].resize(2);
        for (int j=0; j < ELEMENTS; ++j) {
            sets[i][0][j] =  ELEMENT_FILL();
            sets[i][1][j] =  static_cast<Element>(-1) - ELEMENT_FILL(1);
        }
    }
    top_ = POWN(COL_FACTOR, (cols_-1) % ROWS_PER_ELEMENT);
    top_offset_ = ELEMENTS - 1 - (cols_-1) / ROWS_PER_ELEMENT;
}

void State::print(uint rows) {
    for (auto c=0U; c<cols_;c++) {
        for (auto r=0U; r<rows;r++) {
            cout << static_cast<int>(side[cols_-c+r-1]) << " ";
        }
        cout << "\n";
    }
    cout << "----------" << endl;
}

void check(uint cols, uint t) {
    State state(cols);

    Index nr_columns = state.nr_columns();
    while (1) {
        Index col = col_next++;
        if (col >= nr_columns) break;
        state.process(col);

        auto now = chrono::steady_clock::now();
        auto elapsed = chrono::duration_cast<sec>(now-start).count();
        if (elapsed >= period) {
            lock_guard<mutex> lock{period_mutex};
            if (elapsed >= period) {
                cout << "col=" << col << "/" << nr_columns << " (" << 100.*col/nr_columns << "% " << elapsed << " s)" << endl;
                period = (elapsed/PERIOD+1)*PERIOD;
            }
        }
    }
}

void State::process(Index col) {
    last_.fill(0);
    for (uint i=0; i<cols_; ++i) {
        Element bit = col >> i & 1;
        side[i] = bit;
        Element carry = 0;
        for (int j=0; j<ELEMENTS; ++j) {
            auto c = last_[j] % COL_FACTOR;
            last_[j] = last_[j] / COL_FACTOR + carry * ELEMENT_TOP;
            if (j == top_offset_ && bit) last_[j] += top_;
            carry = c;
        }
    }
    // cout << "col=" << col << ", value=" << last_ << "\n";
    extend(0);
}

void State::extend(uint row) {
    // cout << "Extend row " << row << " " << static_cast<int>(side[cols_+row-1]) << "\n";
    if (row >= MAX_ROWS) throw(range_error("row out of range"));

    // Execute subset sum. The new column is added to set {from} giving {to}
    // {sum} is the other set.
    auto const& set_from = sets[row];
    auto const& set_sum  = sets[row + 1];
    auto      & set_to   = sets[row + 2];
    if (set_to.size() == 0) {
        auto size = 3 * set_from.size() - 2;
        set_to.resize(size);
        for (int j=0; j<ELEMENTS; ++j)
            set_to[size-1][j] = static_cast<Element>(-1) - ELEMENT_FILL(1);
    }

    // Merge sort {set_from - last_} , {set_from} and {set_from + last_}
    auto ptr_sum    = &set_sum[1][0];
    auto ptr_low    = &set_from[0][0];
    auto ptr_middle = &set_from[0][0];
    auto ptr_high   = &set_from[0][0];
    Column col_low, col_high;
    for (int j=0; j<ELEMENTS; ++j) {
        col_low   [j] = *ptr_low++  - last_[j];
        col_high  [j] = *ptr_high++ + last_[j];
    }

    auto ptr_end = &set_to[set_to.size()-1][0];
    auto ptr_to  = &set_to[0][0];
    while (ptr_to < ptr_end) {
        for (int j=0; j<ELEMENTS; ++j) {
            if (col_low[j] < ptr_middle[j]) goto LOW;
            if (col_low[j] > ptr_middle[j]) goto MIDDLE;
        }
        // low == middle
        // cout << "low == middle\n";
        return;

      LOW:
        // cout << "LOW\n";
        for (int j=0; j<ELEMENTS; ++j) {
            if (col_low[j] < col_high[j]) goto LOW0;
            if (col_low[j] > col_high[j]) goto HIGH0;
        }
        // low == high
        // cout << "low == high\n";
        return;

      MIDDLE:
        // cout << "MIDDLE\n";
        for (int j=0; j<ELEMENTS; ++j) {
            if (ptr_middle[j] < col_high[j]) goto MIDDLE0;
            if (ptr_middle[j] > col_high[j]) goto HIGH0;
        }
        // middle == high
        // cout << "middle == high\n";
        return;

      LOW0:
        // cout << "LOW0\n";
        for (int j=0; j<ELEMENTS; ++j) {
            *ptr_to++  = col_low[j];
            col_low[j] = *ptr_low++ - last_[j];
        }
        goto SUM;

      MIDDLE0:
        // cout << "MIDDLE0\n";
        for (int j=0; j<ELEMENTS; ++j)
            *ptr_to++ = *ptr_middle++;
        goto SUM;

      HIGH0:
        // cout << "HIGH0\n";
        for (int j=0; j<ELEMENTS; ++j) {
            *ptr_to++ = col_high[j];
            col_high[j] = *ptr_high++ + last_[j];
        }
        goto SUM;
      SUM:
        for (int j=-ELEMENTS; j<0; ++j) {
            if (ptr_to[j] > ptr_sum[j]) {
                ptr_sum += ELEMENTS;
                goto SUM;
            }
            if (ptr_to[j] < ptr_sum[j]) goto DONE;
        }
        // sum == to
        for (int j=-ELEMENTS; j<0; ++j)
            if (ptr_to[j] != ELEMENT_FILL()) {
                // sum == to and to != 0
                // cout << "sum == to\n";
                // cout << set_sum[(ptr_sum - &set_sum[0][0])/ELEMENTS-1] << "\n";
                return;
            }
      DONE:;
    }
    // cout << "Wee\n";
    auto row1 = row+1;
    if (0)
        for (uint i=0; i<row1+2; ++i) {
            cout << "Set " << i << "\n";
            auto& set = sets[i];
            for (auto& column: set)
                cout << column << "\n";
        }

    if (row1 * ratio_col_ > ratio_row_ * cols_) {
        ratio_row_ = row1;
        ratio_col_ = cols_;
        lock_guard<mutex> lock{ratio_mutex};

        if (ratio_row_ * ratio_col > ratio_row * ratio_col_) {

            auto now = chrono::steady_clock::now();
            auto elapsed = chrono::duration_cast<sec>(now-start).count();
            cout << "cols=" << cols_ << ",rows=" << row1 << " (" << elapsed << " s)\n";
            print(row1);
            ratio_row = ratio_row_;
            ratio_col = ratio_col_;
        }
    }

    auto last = last_;

    Element carry = 0;
    for (int j=0; j<ELEMENTS; ++j) {
        auto c = last_[j] % COL_FACTOR;
        last_[j] = last_[j] / COL_FACTOR + carry * ELEMENT_TOP;
        carry = c;
    }

    side[cols_+row] = 0;
    extend(row1);

    last_[top_offset_] += top_;
    side[cols_+row] = 1;
    extend(row1);

    last_ = last;
}

void my_main(int argc, char** argv) {
    if (!col_next.is_lock_free()) cout << "col_next is not lock free\n";
    if (!period.  is_lock_free()) cout << "period is not lock free\n";

    int min_col = 2;
    int max_col = MAX_COLS;
    if (argc > 1) {
        min_col = atoi(argv[1]);
        if (min_col < 2)
            throw(range_error("Column must be >= 2"));
        if (min_col > MAX_COLS)
            throw(range_error("Column must be <= " + to_string(MAX_COLS)));
    }
    if (argc > 2) {
        max_col = atoi(argv[2]);
        if (max_col < min_col)
            throw(range_error("Column must be >= " + to_string(min_col)));
        if (max_col > MAX_COLS)
            throw(range_error("Column must be <= " + to_string(MAX_COLS)));
    }

    for (int cols = min_col; cols <= max_col; ++cols) {
        cout << "Trying " << cols << " columns" << endl;
        ratio_row = 0;
        ratio_col = 1;
        col_next = 0;
        period = PERIOD;
        start = chrono::steady_clock::now();
        vector<thread> threads;
        for (auto t = 1U; t < nr_threads; t++)
            threads.emplace_back(check, cols, t);
        check(cols, 0);
        for (auto& thread: threads)
            thread.join();
    }
}

int main(int argc, char** argv) {
    try {
        my_main(argc, argv);
    } catch(exception& e) {
        cerr << "Error: " << e.what() << endl;
        exit(EXIT_FAILURE);
    }
    exit(EXIT_SUCCESS);
}


答:
R, <s>75</s> <s>40</s> 38 bytes (plus extra swag)

Well, looks like I could golf this down by giving in and using the gamma function rather than recursive functions.

```<code>function(n,r)pi^(n/2)/gamma(n/2+1)*r^n
</code>```

Defines an anonymous function to calculate the volume of an n-dimensional hypersphere of radius r.

Some examples:

1 1 -> 2

0 48 ->  1

2 3 -> 28.27433

3 4.5 -> 381.7035

7 7 -> 3891048

100 3 -> 122051813

Swagless solution, <s>38</s> 34 bytes

For a few bytes less, you can have an anonymous function that only works for dimensions 1 to 3. Returns numeric(0) for n=0, and NA for n>3. (numeric(0) is a numeric vector of length 0; NA is for "not available".) Performance is otherwise identical to the general solution above.

```<code>function(n,r)c(1,pi,4/3*pi)[n]*r^n
</code>```

Title: N-dimensional Circles!

Body:
R, <s>75</s> <s>40</s> 38 bytes (plus extra swag)

Well, looks like I could golf this down by giving in and using the gamma function rather than recursive functions.

function(n,r)pi^(n/2)/gamma(n/2+1)*r^n

Defines an anonymous function to calculate the volume of an n-dimensional hypersphere of radius r.

Some examples:

1 1 -> 2

0 48 ->  1

2 3 -> 28.27433

3 4.5 -> 381.7035

7 7 -> 3891048

100 3 -> 122051813

Swagless solution, <s>38</s> 34 bytes

For a few bytes less, you can have an anonymous function that only works for dimensions 1 to 3. Returns numeric(0) for n=0, and NA for n>3. (numeric(0) is a numeric vector of length 0; NA is for "not available".) Performance is otherwise identical to the general solution above.

function(n,r)c(1,pi,4/3*pi)[n]*r^n


答:
MATL, 17 bytes

```<code>3:^[2P4*P/3]*1hi)
</code>```

This works up to 3 dimensions only. Inputs are in reverse order, that is: r, then n.

Try it online!

Consider r=3, n=2 as an example.

```<code>3:         % Push array [1 2 3]
           % STACK: [1 2 3]
^          % Take r implicitly, and raise it to [1 2 3] element-wise
           % STACK: [3 9 27]
[2P4*P/3]  % Push array [2 pi 4*pi/3]
           % STACK: [3 9 27], [2 pi 4*pi/3]
*          % Multiply element-wise
           % STACK: [6 28.2743 113.0973]
1h         % Append 1
           % STACK: [6 28.2743 113.0973, 1]
i)         % Input n and use it as modular index into the array. Display implicitly
           % STACK: 28.2743
</code>```

Title: N-dimensional Circles!

Body:
MATL, 17 bytes

3:^[2P4*P/3]*1hi)

This works up to 3 dimensions only. Inputs are in reverse order, that is: r, then n.

Try it online!

Consider r=3, n=2 as an example.

3:         % Push array [1 2 3]
           % STACK: [1 2 3]
^          % Take r implicitly, and raise it to [1 2 3] element-wise
           % STACK: [3 9 27]
[2P4*P/3]  % Push array [2 pi 4*pi/3]
           % STACK: [3 9 27], [2 pi 4*pi/3]
*          % Multiply element-wise
           % STACK: [6 28.2743 113.0973]
1h         % Append 1
           % STACK: [6 28.2743 113.0973, 1]
i)         % Input n and use it as modular index into the array. Display implicitly
           % STACK: 28.2743


Title: Binary Convolution

Body:
A binary convolution is described by a number M, and is applied to a number N. For each bit in the binary representation of M, if the bit is set (1), the corresponding bit in the output is given by XORing the two bits adjacent to the corresponding bit in N (wrapping around when necessary). If the bit is not set (0), then the corresponding bit in the output is given by the corresponding bit in N.

A worked example (with 8-bit values):

Let N = 150, M = 59. Their binary respresentations are (respectively) 10010110 and 00111011.

Based on M's binary representation, bits 0, 1, 3, 4, and 5 are convolved.

The result for bit 0 is given by XORing bits 1 and 7 (since we wrap around), yielding 1.

The result for bit 1 is given by XORing bits 0 and 2, yielding 0.

The result for bit 2 is given by the original bit 2, yielding 1.

The result for bit 3 is given by XORing bits 2 and 4, yielding 0.

The result for bit 4 is given by XORing bits 3 and 5, yielding 0.

The result for bit 5 is given by XORing bits 4 and 6, yielding 1.

The results for bits 6 and 7 are given by the original bits 6 and 7, yielding 0 and 1.

The output is thus 10100110 (166).

The Challenge

Given N and M, output the result of performing the binary convolution described by M upon N. Input and output may be in any convenient, consistent, and unambiguous format. N and M will always be in the (inclusive) range [0, 255] (8-bit unsigned integers), and their binary representations should be padded to 8 bits for performing the binary convolution.

Test Cases

```<code>150 59 -> 166
242 209 -> 178
1 17 -> 0
189 139 -> 181
215 104 -> 215
79 214 -> 25
190 207 -> 50
61 139 -> 180
140 110 -> 206
252 115 -> 143
83 76 -> 31
244 25 -> 245
24 124 -> 60
180 41 -> 181
105 239 -> 102
215 125 -> 198
49 183 -> 178
183 158 -> 181
158 55 -> 186
215 117 -> 198
255 12 -> 243
</code>```

Body:
J, 34 bytes

2#.[:({"_1],._1&|.~:1&|.)/(8#2)#:]

Straight-forward approach that applies the process defined in the challenge. Takes input as an array [n, m].

Forms seven smileys, [:, :(, :1, (8, 8#, #:, and :].

Usage

   f =: 2#.[:({"_1],._1&|.~:1&|.)/(8#2)#:]
   f 150 59
171
   f 59 150
166
   f 209 242
178
   f 17 1
0
   f 139 189
181