答:
Python 2, 59 bytes

def f(n,L):exec"l=len(L)/2;L=(L+L[1:]*~-l)[::l];"*n;print L
```

<p>A different approach, slightly longer than the other Python answers. Only works for positive even numbers of elements.</p>

<p>e.g. for <code>1, [1,2,3,4,5,6,7,8]</code>, take the array and append <code>len(L)/2-1</code> copies of itself minus the first element, e.g.</p>

```[1,2,3,4,5,6,7,8,2,3,4,5,6,7,8,2,3,4,5,6,7,8,2,3,4,5,6,7,8]
```

<p>Then take every <code>len(L)/2</code>th element.</p>

```[1,2,3,4,5,6,7,8,2,3,4,5,6,7,8,2,3,4,5,6,7,8,2,3,4,5,6,7,8]
 ^       ^       ^       ^       ^       ^       ^       ^
```

Title: Faro shuffle an array

Body:
Python 2, 59 bytes

def f(n,L):exec"l=len(L)/2;L=(L+L[1:]*~-l)[::l];"*n;print L

A different approach, slightly longer than the other Python answers. Only works for positive even numbers of elements.

e.g. for 1, [1,2,3,4,5,6,7,8], take the array and append len(L)/2-1 copies of itself minus the first element, e.g.

[1,2,3,4,5,6,7,8,2,3,4,5,6,7,8,2,3,4,5,6,7,8,2,3,4,5,6,7,8]

Then take every len(L)/2th element.

[1,2,3,4,5,6,7,8,2,3,4,5,6,7,8,2,3,4,5,6,7,8,2,3,4,5,6,7,8]
 ^       ^       ^       ^       ^       ^       ^       ^


问:
Faro shuffle an array
A Faro shuffle is a technique frequently used by magicians to "shuffle" a deck. To perform a Faro shuffle you first cut the deck into 2 equal halves then you interleave the two halves. For example

```<code>[1 2 3 4 5 6 7 8]
</code>```

Faro shuffled is

```<code>[1 5 2 6 3 7 4 8]
</code>```

This can be repeated any number of times. Interestingly enough, if you repeat this enough times, you will always end up back at the original array. For example:

```<code>[1 2 3 4 5 6 7 8]
[1 5 2 6 3 7 4 8]
[1 3 5 7 2 4 6 8]
[1 2 3 4 5 6 7 8]
</code>```

Notice that 1 stays on the bottom and 8 stays on the top. That makes this an outer-shuffle. This is an important distinction.

The Challenge

Given an array of integers A, and a number N, output the array after N Faro shuffles. A may contain repeated or negative elements, but it will always have an even number of elements. You can assume the array will not be empty. You can also assume that N will be a non-negative integer, although it may be 0. You can take these inputs in any reasonable manner. The shortest answer in bytes wins!

Test IO:

```<code>#N, A,                                              Output
1,  [1, 2, 3, 4, 5, 6, 7, 8]                        [1, 5, 2, 6, 3, 7, 4, 8]
2,  [1, 2, 3, 4, 5, 6, 7, 8]                        [1, 3, 5, 7, 2, 4, 6, 8]
7,  [-23, -37, 52, 0, -6, -7, -8, 89]               [-23, -6, -37, -7, 52, -8, 0, 89]
0,  [4, 8, 15, 16, 23, 42]                          [4, 8, 15, 16, 23, 42]
11, [10, 11, 8, 15, 13, 13, 19, 3, 7, 3, 15, 19]    [10, 19, 11, 3, 8, 7, 15, 3, 13, 15, 13, 19]
</code>```

And, a massive test case:

```<code>23, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100]
</code>```

Should output:

```<code>[1, 30, 59, 88, 18, 47, 76, 6, 35, 64, 93, 23, 52, 81, 11, 40, 69, 98, 28, 57, 86, 16, 45, 74, 4, 33, 62, 91, 21, 50, 79, 9, 38, 67, 96, 26, 55, 84, 14, 43, 72, 2, 31, 60, 89, 19, 48, 77, 7, 36, 65, 94, 24, 53, 82, 12, 41, 70, 99, 29, 58, 87, 17, 46, 75, 5, 34, 63, 92, 22, 51, 80, 10, 39, 68, 97, 27, 56, 85, 15, 44, 73, 3, 32, 61, 90, 20, 49, 78, 8, 37, 66, 95, 25, 54, 83, 13, 42, 71, 100]
</code>```

答:
05AB1E, 5 bytes

Code:

```<code>F2äø˜
</code>```

Explanation, input: N, array:

```<code>F      # Do the following N times
 2ä    # Split the array into 2 pieces
   ø   # Zip
    ˜  # Deep flatten
</code>```

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

ContentLicense: CC BY-SA 3.0

Title: Faro shuffle an array

Body:
05AB1E, 5 bytes

Code:

F2äø˜

Explanation, input: N, array:

F      # Do the following N times
 2ä    # Split the array into 2 pieces
   ø   # Zip
    ˜  # Deep flatten

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


答:
vim, <s>62</s> <s>59</s> 54

```<code>qrma50%mb:norm@q<cr>ggqOjdd'apjma'b@q<esc>0"qDJ<C-a>D@"i@r<esc>xxdd@"
</code>```

Wow. This is possibly the hackiest thing I've written for PPCG, and that's saying something.

Input is taken as N on the first line followed by the elements of the array, each on its own line.

```<code>qr         first, we're going to record the contents of the @r macro. this is
             the macro which does the faro-shuffle operation.
  ma       set the mark 'a at the beginning of the file
  50%      move to the 50% point of the file (i.e. halfway down)
  mb       set another mark here
  :norm@q  evaluate the recursive macro @q. we'll get to what that does later,
             but the interesting part here is that it's :norm@q instead of @q.
             this is because a recursive macro terminates at the end of the
             file, which means when @q terminates, @r would also abort, which
             would make calling it with a count impossible. running @q under
             :norm prevents this.
  gg       move back to the top of the file for the next iteration
q          end recording
O          now we're inserting contents of the @q macro, the recursive part
             we can't record it directly because it's destructive
  j        move to line directly below mark 'b (which was just set before @q)
  dd       delete this line and bring it...
  'ap      up after mark 'a (which starts on line 1, bringing the N/2th line
             directly below line 1, aka line 2)
  jma      replace mark 'a one line below this so that the next time we call
             'ap, the line from the second half is interleaved with the lines
             from the first half
  'b       jump back to mark 'b (remember, 'b is the last line of the first
             half of the file, originally reached via 50%)
  @q       call ourselves, causing the macro to run until hitting EOF
0"qD       delete this into register "q
J          delete the empty line that remains
<C-a>      here's another interesting bit: we want to run @r N times. but 0@r
             means "go to column 0, and then run @r once." so we have to
             increment the input number...
D@"        and then *that* many times...
  i@r        insert @r...
xx         ... and finally, delete two characters, which is the extra @r from
             the increment
dd         delete the sequence of @rs into the "" register...
@"         and run it!
</code>```

I actually possibly found several vim bugs while writing this answer:

recording macros is not possible within other macros (when setting their text manually, not with q) or within :*maps.

:let @a='<C-v><cr>'<cr>i<C-r>a outputs two newlines, not one, for whatever arcane reason.

I might investigate those further later.

Thanks to Dr Green Eggs and Ham DJ for 3 bytes!

Title: Faro shuffle an array

Body:
A Faro shuffle is a technique frequently used by magicians to "shuffle" a deck. To perform a Faro shuffle you first cut the deck into 2 equal halves then you interleave the two halves. For example

```<code>[1 2 3 4 5 6 7 8]
</code>```

Faro shuffled is

```<code>[1 5 2 6 3 7 4 8]
</code>```

This can be repeated any number of times. Interestingly enough, if you repeat this enough times, you will always end up back at the original array. For example:

```<code>[1 2 3 4 5 6 7 8]
[1 5 2 6 3 7 4 8]
[1 3 5 7 2 4 6 8]
[1 2 3 4 5 6 7 8]
</code>```

Notice that 1 stays on the bottom and 8 stays on the top. That makes this an outer-shuffle. This is an important distinction.

The Challenge

Given an array of integers A, and a number N, output the array after N Faro shuffles. A may contain repeated or negative elements, but it will always have an even number of elements. You can assume the array will not be empty. You can also assume that N will be a non-negative integer, although it may be 0. You can take these inputs in any reasonable manner. The shortest answer in bytes wins!

Test IO:

```<code>#N, A,                                              Output
1,  [1, 2, 3, 4, 5, 6, 7, 8]                        [1, 5, 2, 6, 3, 7, 4, 8]
2,  [1, 2, 3, 4, 5, 6, 7, 8]                        [1, 3, 5, 7, 2, 4, 6, 8]
7,  [-23, -37, 52, 0, -6, -7, -8, 89]               [-23, -6, -37, -7, 52, -8, 0, 89]
0,  [4, 8, 15, 16, 23, 42]                          [4, 8, 15, 16, 23, 42]
11, [10, 11, 8, 15, 13, 13, 19, 3, 7, 3, 15, 19]    [10, 19, 11, 3, 8, 7, 15, 3, 13, 15, 13, 19]
</code>```

And, a massive test case:

```<code>23, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100]
</code>```

Should output:

```<code>[1, 30, 59, 88, 18, 47, 76, 6, 35, 64, 93, 23, 52, 81, 11, 40, 69, 98, 28, 57, 86, 16, 45, 74, 4, 33, 62, 91, 21, 50, 79, 9, 38, 67, 96, 26, 55, 84, 14, 43, 72, 2, 31, 60, 89, 19, 48, 77, 7, 36, 65, 94, 24, 53, 82, 12, 41, 70, 99, 29, 58, 87, 17, 46, 75, 5, 34, 63, 92, 22, 51, 80, 10, 39, 68, 97, 27, 56, 85, 15, 44, 73, 3, 32, 61, 90, 20, 49, 78, 8, 37, 66, 95, 25, 54, 83, 13, 42, 71, 100]
</code>```

Body:
vim, <s>62</s> <s>59</s> 54

qrma50%mb:norm@q<cr>ggqOjdd'apjma'b@q<esc>0"qDJ<C-a>D@"i@r<esc>xxdd@"

Wow. This is possibly the hackiest thing I've written for PPCG, and that's saying something.

Input is taken as N on the first line followed by the elements of the array, each on its own line.

qr         first, we're going to record the contents of the @r macro. this is
             the macro which does the faro-shuffle operation.
  ma       set the mark 'a at the beginning of the file
  50%      move to the 50% point of the file (i.e. halfway down)
  mb       set another mark here
  :norm@q  evaluate the recursive macro @q. we'll get to what that does later,
             but the interesting part here is that it's :norm@q instead of @q.
             this is because a recursive macro terminates at the end of the
             file, which means when @q terminates, @r would also abort, which
             would make calling it with a count impossible. running @q under
             :norm prevents this.
  gg       move back to the top of the file for the next iteration
q          end recording
O          now we're inserting contents of the @q macro, the recursive part
             we can't record it directly because it's destructive
  j        move to line directly below mark 'b (which was just set before @q)
  dd       delete this line and bring it...
  'ap      up after mark 'a (which starts on line 1, bringing the N/2th line
             directly below line 1, aka line 2)
  jma      replace mark 'a one line below this so that the next time we call
             'ap, the line from the second half is interleaved with the lines
             from the first half
  'b       jump back to mark 'b (remember, 'b is the last line of the first
             half of the file, originally reached via 50%)
  @q       call ourselves, causing the macro to run until hitting EOF
0"qD       delete this into register "q
J          delete the empty line that remains
<C-a>      here's another interesting bit: we want to run @r N times. but 0@r
             means "go to column 0, and then run @r once." so we have to
             increment the input number...
D@"        and then *that* many times...
  i@r        insert @r...
xx         ... and finally, delete two characters, which is the extra @r from
             the increment
dd         delete the sequence of @rs into the "" register...
@"         and run it!

I actually possibly found several vim bugs while writing this answer:

recording macros is not possible within other macros (when setting their text manually, not with q) or within :*maps.

:let @a='<C-v><cr>'<cr>i<C-r>a outputs two newlines, not one, for whatever arcane reason.

I might investigate those further later.

Thanks to Dr Green Eggs and Ham DJ for 3 bytes!


答:
Julia, <s>45</s> 42 bytes

```<code>a\n=n>0?reshape(a,endof(a)÷2,2)'[:]\~-n:a
</code>```

Try it online!

How it works

We (re)define the binary operator \ for this task. Let a be an array and n a non-negative integer.

If n is positive, we shuffle the array. This is achieved by reshaping it into a matrix of length(a) ÷ 2 rows and two columns. ' transposes the resulting matrix, creating of two rows, then flattening the result with [:]. Since Julia stores matrices in column-major order, this interleaves the two rows.

Afterwards, we call \ recursively with the shuffled a and n - 1 (~-n) as arguments, thus performing additional shuffles. Once n reaches 0, we return the current value of a.

Title: Faro shuffle an array

Body:
Julia, <s>45</s> 42 bytes

a\n=n>0?reshape(a,endof(a)÷2,2)'[:]\~-n:a

Try it online!

How it works

We (re)define the binary operator \ for this task. Let a be an array and n a non-negative integer.

If n is positive, we shuffle the array. This is achieved by reshaping it into a matrix of length(a) ÷ 2 rows and two columns. ' transposes the resulting matrix, creating of two rows, then flattening the result with [:]. Since Julia stores matrices in column-major order, this interleaves the two rows.

Afterwards, we call \ recursively with the shuffled a and n - 1 (~-n) as arguments, thus performing additional shuffles. Once n reaches 0, we return the current value of a.


问:
Implement SHA-256
Given a sequence of bytes, output the SHA-256 hash value of the sequence.

The SHA-256 Algorithm

The following pseudocode is taken from the Wikipedia page for SHA-2.

```<code>Note 1: All variables are 32 bit unsigned integers and addition is calculated modulo 2^32
Note 2: For each round, there is one round constant k[i] and one entry in the message schedule array w[i], 0 ≤ i ≤ 63
Note 3: The compression function uses 8 working variables, a through h
Note 4: Big-endian convention is used when expressing the constants in this pseudocode,
    and when parsing message block data from bytes to words, for example,
    the first word of the input message "abc" after padding is 0x61626380

Initialize hash values:
(first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19):
h0 := 0x6a09e667
h1 := 0xbb67ae85
h2 := 0x3c6ef372
h3 := 0xa54ff53a
h4 := 0x510e527f
h5 := 0x9b05688c
h6 := 0x1f83d9ab
h7 := 0x5be0cd19

Initialize array of round constants:
(first 32 bits of the fractional parts of the cube roots of the first 64 primes 2..311):
k[0..63] :=
   0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
   0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
   0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
   0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
   0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
   0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
   0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
   0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2

Pre-processing:
append the bit '1' to the message
append k bits '0', where k is the minimum number >= 0 such that the resulting message
    length (modulo 512 in bits) is 448.
append length of message (without the '1' bit or padding), in bits, as 64-bit big-endian integer
    (this will make the entire post-processed length a multiple of 512 bits)

Process the message in successive 512-bit chunks:
break message into 512-bit chunks
for each chunk
    create a 64-entry message schedule array w[0..63] of 32-bit words
    (The initial values in w[0..63] don't matter, so many implementations zero them here)
    copy chunk into first 16 words w[0..15] of the message schedule array

    Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array:
    for i from 16 to 63
        s0 := (w[i-15] rightrotate 7) xor (w[i-15] rightrotate 18) xor (w[i-15] rightshift 3)
        s1 := (w[i-2] rightrotate 17) xor (w[i-2] rightrotate 19) xor (w[i-2] rightshift 10)
        w[i] := w[i-16] + s0 + w[i-7] + s1

    Initialize working variables to current hash value:
    a := h0
    b := h1
    c := h2
    d := h3
    e := h4
    f := h5
    g := h6
    h := h7

    Compression function main loop:
    for i from 0 to 63
        S1 := (e rightrotate 6) xor (e rightrotate 11) xor (e rightrotate 25)
        ch := (e and f) xor ((not e) and g)
        temp1 := h + S1 + ch + k[i] + w[i]
        S0 := (a rightrotate 2) xor (a rightrotate 13) xor (a rightrotate 22)
        maj := (a and b) xor (a and c) xor (b and c)
        temp2 := S0 + maj

        h := g
        g := f
        f := e
        e := d + temp1
        d := c
        c := b
        b := a
        a := temp1 + temp2

    Add the compressed chunk to the current hash value:
    h0 := h0 + a
    h1 := h1 + b
    h2 := h2 + c
    h3 := h3 + d
    h4 := h4 + e
    h5 := h5 + f
    h6 := h6 + g
    h7 := h7 + h

Produce the final hash value (big-endian):
digest := hash := h0 append h1 append h2 append h3 append h4 append h5 append h6 append h7
</code>```

Reference implementation

Here is a reference implementation, in Python 3:

#!/usr/bin/env python3

import sys

# ror function modified from http://stackoverflow.com/a/27229191/2508324
def ror(val, r_bits):
   return (val >> r_bits) | (val << (32-r_bits)) % 2**32

h = [0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19]

k = [0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
   0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
   0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
   0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
   0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
   0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
   0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
   0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2]

s = sys.stdin.read().encode()
msg = [int(x,2) for c in s for x in '{:08b}'.format(c)]
msg.append(1)
while len(msg) % 512 != 448:
    msg.append(0)
msg.extend([int(x,2) for x in '{:064b}'.format(len(s) * 8)])

for i in range(len(msg)//512):
    chunk = msg[512*i:512*(i+1)] # sloth love chunk
    w = [0 for _ in range(64)]
    for j in range(16):
        w[j] = int(''.join(str(x) for x in chunk[32*j:32*(j+1)]),2)
    for j in range(16, 64):
        s0 = ror(w[j-15], 7) ^ ror(w[j-15], 18) ^ (w[j-15] >> 3)
        s1 = ror(w[j-2], 17) ^ ror(w[j-2], 19) ^ (w[j-2] >> 10)
        w[j] = (w[j-16] + s0 + w[j-7] + s1) % 2**32
    work = h[:]
    for j in range(64):
        S1 = ror(work[4], 6) ^ ror(work[4], 11) ^ ror(work[4], 25)
        ch = (work[4] & work[5]) ^ (~work[4] & work[6])
        temp1 = (work[7] + S1 + ch + k[j] + w[j]) % 2**32
        S0 = ror(work[0], 2) ^ ror(work[0], 13) ^ ror(work[0], 22)
        maj = (work[0] & work[1]) ^ (work[0] & work[2]) ^ (work[1] & work[2])
        temp2 = (S0 + maj) % 2**32
        work = [(temp1 + temp2) % 2**32] + work[:-1]
        work[4] = (work[4] + temp1) % 2**32
    h = [(H+W)%2**32 for H,W in zip(h,work)]

print(''.join('{:08x}'.format(H) for H in h))
```

<h2>Restrictions</h2>

<ul>
<li>The usage of builtins which compute SHA-256 hashes or otherwise trivialize the challenge is forbidden</li>
<li>The input and output may be in any reasonable format (encoded in a single-byte encoding, base64, hexadecimal, etc.)</li>
</ul>

<h2>Test cases</h2>

```<empty string> -> e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855
abc -> ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad
Hello, World! -> c98c24b677eff44860afea6f493bbaec5bb1c4cbb209c6fc2bbb47f66ff2ad31
1234 -> 03ac674216f3e15c761ee1a5e255f067953623c8b388b4459e13f978d7c846f4
```

答:
Python 2, 519 bytes

Q=2**32
G=lambda e:[int(x**e%1*Q)for x in range(2,312)if 383**~-x%x<2]
H=G(.5)[:8]
r=lambda v,b:v>>b|v<<32-b
M=input()
l=len(M)
M+=bin(l|1<<(447-l)%512+64)[2:]
while M:j=0;a,b,c,d,e,f,g,h=H;exec"H+=int(M[:32],2),;M=M[32:];"*16+"x=H[-15];y=H[-2];H+=(H[-16]+H[-7]+(r(y,17)^r(y,19)^y>>10)+(r(x,7)^r(x,18)^x/8))%Q,;"*48+"u=(r(e,6)^r(e,11)^r(e,25))+(e&f^~e&g)+h+G(1/3.)[j]+H[j+8];X=a,b,c,d,e,f,g,h=(u+(r(a,2)^r(a,13)^r(a,22))+(a&b^a&c^b&c))%Q,a,b,c,(d+u)%Q,e,f,g;j+=1;"*64;H=tuple(a+b&Q-1for a,b in zip(H,X))
print"%08x"*8%H
```

I was working off the pseudocode, but some parts just ended up being the same as the golfed reference Mego posted since there's not much to golf (e.g. the constant tables, for which the only real golf was a <2 instead of ==1). Over 100 bytes down though, but I'm sure there's still more to be gotten.

Input/output is also string of bits to hex string.

Title: Implement SHA-256

Body:
Python 2, 519 bytes

Q=2**32
G=lambda e:[int(x**e%1*Q)for x in range(2,312)if 383**~-x%x<2]
H=G(.5)[:8]
r=lambda v,b:v>>b|v<<32-b
M=input()
l=len(M)
M+=bin(l|1<<(447-l)%512+64)[2:]
while M:j=0;a,b,c,d,e,f,g,h=H;exec"H+=int(M[:32],2),;M=M[32:];"*16+"x=H[-15];y=H[-2];H+=(H[-16]+H[-7]+(r(y,17)^r(y,19)^y>>10)+(r(x,7)^r(x,18)^x/8))%Q,;"*48+"u=(r(e,6)^r(e,11)^r(e,25))+(e&f^~e&g)+h+G(1/3.)[j]+H[j+8];X=a,b,c,d,e,f,g,h=(u+(r(a,2)^r(a,13)^r(a,22))+(a&b^a&c^b&c))%Q,a,b,c,(d+u)%Q,e,f,g;j+=1;"*64;H=tuple(a+b&Q-1for a,b in zip(H,X))
print"%08x"*8%H

I was working off the pseudocode, but some parts just ended up being the same as the golfed reference Mego posted since there's not much to golf (e.g. the constant tables, for which the only real golf was a <2 instead of ==1). Over 100 bytes down though, but I'm sure there's still more to be gotten.

Input/output is also string of bits to hex string.


问:
Count up folks!

Introduction

It may sound strange, but we haven't got ONE challenge for counting from 1 to n, inclusive.

This is not the same thing. That one is a (closed) not well-explained challenge.

This is not the same thing. That one is about counting up indefinitely.

Challenge

Write a program or function that prints every integer from 1 to n inclusive.

Rules

You can get n any way.

You can assume that n will always be a positive integer.

You can get n in any base, but you should always output in decimal.

Output must be separated by any character (or pattern) not in 0123456789. Non-decimal leading or trailing characters are allowed (for example when using arrays such as [1, 2, 3, 4, 5, 6]).

Standard loopholes are denied.

We want to find the shortest approach in each language, not the shortest language, so I will not accept any answer.

You must update your answer(s) after this edit, answers posted before the last edit must comply with the change rule about standard loopholes (I didn't want to deny them, but I didn't want to make the community roar, so I denied them).

You can use any post-dating language version (or language). You cannot use any language or language version made just for this challenge.

Bonuses

20%

Your program must be able to count at least up to 18446744073709551615 (2^64-1). For example, if a new datatype is the only way to support big integers, you must construct it. If your language does not have any way to support huge integers up to 2^64-1, the upper limit of that particular language must be supported instead.

EDIT: I've changed the limit from 2^64 to 2^64-1 to allow more answers.

EDIT: I made the 2^64-1 rule a bonus, since there has not been much interest in this challenge. If your answer supports 2^64-1, you can now edit it to include the bonus. Also, you can post an answer not supporting it, if it is shorter.

答:
Brachylog, 7 bytes

```<code>:1:efrw
</code>```

or alternatively

```<code>:1:efr.
</code>```

Title: Count up folks!

Body:
Brachylog, 7 bytes

:1:efrw

or alternatively

:1:efr.


问:
Solve a traffic intersection

The task

Write a program or function that takes a traffic intersection structure and outputs the sequence, in which vehicles will pass.

The output should contain at most four lines with the following format #. x->y\n, where # is a sequence number number, followed by the dot ., x and y are characters ["N", "E", "S", "W"]. They should be separated by characters ->. If you do not return an array of strings, each line must end with a \n (new line character) or equivalent to your system.

The input should take the following form:

Part 1: four characters, each having the destination road for the source roads in order N, E, S, W (clockwise). The allowed characters are N, S, W, E or . Space means that there is no vehicle on particular road. For example string S WE means, that N vehicle wishes to go South, space means that there is no E vehicle, W means that S wishes to go West, E means West wishes to go East.

Part 2 - a space or a single letter meaning which one is of the emergency vehicle.

Part 3 - two characters determining which two roads have priority (eg. NE means that North and East both have higher priorities than both South and West). If it is easier for you, you may take lower priority roads (in that case SW).

In an unsolvable situation you are allowed to return a one-line string which is clear to the user, like unsolvable, no solution and similar. JavaScript users may take built-in undefined constant.

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

The rules of traffic

Please note that some of the rules may not follow your country traffic rules. Some of them have been simplified to make the challenge easier. Do not use this question as a guide for real life traffic system.

For the challenge you are allowed to use only right-side traffic.

The traffic intersection consists of exactly four roads which meet in one point. They are marked N (as for "North"), S, W, E. These letters should be used instead of x and y in the output example above.

On each road there is at most one vehicle. It is not guaranteed that there is a vehicle on each road. Each vehicle can drive in any of four directions, ie. turn left, turn right, go straight or make a U-turn.

If paths of two vehicles do not intersect (they do not collide), they can go at the very same moment. Paths do not collide, if two vehicles (the list might not be complete, but this is intentional, just to give you a clue):

come from opposite directions and both go straight, or at least one of them turns right,

come from opposite directions and both turn left,

come from opposite directions and one of them turns in any direction or makes the U-turn, while the other makes the U-turn,

come from orthogonal directions, the one to the left is turning right and the other does not make the U-turn

Some examples of not colliding paths below. Please note that on the third drawing any path of N would collide with the path of E, even if N makes a U-turn.

If two paths collide, it is necessary to use other rules. If two vehicles are on the same priority road (see below), the right of way is given to the vehicle that:

is comes from the road on the right side, if they come from orthogonal directions

turns right if the other turns left

goes straight or turns right if the other makes a U-turn.

In both examples below the E vehicle has right of way over the vehicle S.

In the example below first goes W, then N, then E and last goes S.

For this particular case the output of your program should be:

```<code>1. W->S
2. N->S
3. E->S
4. S->S
</code>```

All drivers use turn signals and know where all others want to go to (for simplicity we assume that it is possible to distinguish between the left turn and the U-turn).

Sometimes roads are given priority signs, which are more important that the rules above. A road with higher priority has a priority sign (priority sign image). If the priority road does not go straight, also additional signs are used, like this one. The roads with lower priority have a yield sign or a stop sign (they are equivalent). None or exactly two different roads will have higher priority. The user of your program should be able to enter which roads have higher (or lower) priorities.

A vehicle that comes from the road with higher priority has the right of way over a vehicle coming from lower priority road, even if it is on its left side.

If paths of two vehicles coming from the roads with the same priority collide, above right-side rules are active.

On the example below roads S and W have priority signs, which means that vehicles on N and E should give them the way. The S vehicle has the priority over the W vehicle, because it is on its right side, so goes first. Then goes W, because it is on the road of higher priority than E. The vehicle N has right of way from E, because it is on its right side. As the last goes E.

For this particular case the output of your program should be:

```<code>1. S->W
2. W->N
3. N->S
4. E->W
</code>```

It is possible that one (and no more) vehicle is an emergency vehicle, which has the priority regardless to which direction it comes from or goes to, and what sign it has (it always goes first). The program should allow the user to enter, which vehicle is an emergency vehicle. Considering that on the last example N is an emergency vehicle, N goes first, then S, W and as the last E.

For this particular case with an emergency vehicle at N the output of your program should be:

```<code>1. N->S
2. S->W
3. W->N
4. E->W
</code>```

If two vehicles are allowed to go at the very same moment (their paths do not collide and they do not have to give way to other vehicles), your program should find this out and return them as having the same sequence number

On the example below paths of N and E as well as E and S or W and E do not collide. Because S has to give way to N and W give way to S, S cannot go simultaneously with E, etc. The N and E can. So at first N and E go together, than goes S, and W as the last.

The proper output of your program should be:

```<code>1. N->W
1. E->E
2. S->W
3. W->N
</code>```

You are free to choose the order of lines 1 (N->W / E->E is equivalent to E->E / N->W)

Sometimes the traffic may lead to unsolvable situation, that does not allow any vehicle to go. In real life it is solved when one of the drivers voluntarily resigns from his right of way. Here, your program should output unsolvable etc., as mentioned in the first part of the question.

Below is an example of unsolvable situation. E should give way to W, W should give way to S, and S should give way to E.

答:
Q, 645 Bytes

```<code>r:{(1_x),*x}                                                    /rot
R:{x 3,!3}                                                      /-rot
A:4 4#/:@[16#0;;:;]'[(&0100011001111100b;&0001111101100010b;&0010001111000100b;0);(&0 6 2;&0 1 7;&0 3 3;0)]
K:,/{,'/A x}'3 R\3 0 2 1                                        /Konflick matrix
G:3 R\|E:"NESW"                                                 /E:NESW  G:WSEN NWSE ENWS SENW
m:{x-y*_x%y}                                                    /mod
t:{1=+/m'[_x%4;2]}                                              /orthogonal
w:{-1($x),". ",y[0],"->",y 1;}                               /write
b:{_x%4}                                                        /n-> base dir.
g:m[;4]                                                         /n-> turn
e:(!4)in                                                        /exists
d:{s:r a:e b x;R s&~a}                                       /right free
I:{(G[a]?x 1)+4*a:E?*x}                                         /"dd"->n
O:{E[a],G[a:b x]g x}                                            /n-> "dd"
P:{N::(y=4)&z~4 4;a@&0<a:(@[4#0;b x;:;4-g x])+(5*d x)+(24*e z)+99*e y}          /priority
H:{a::K ./:/:x,/:\:x; if[N&2 in *a;:,0N]; x@&{~|/x[;z]'y}[a]'[!:'u+1;u:!#x]}    /each set of concurrent movements
f:{i:I'(E,'a)@&~^a:4#x; i:i@p:>P[i;E?x 4;E?x 5 6]; {0<#x 1}{a:H x 1;$[a~,0N;-1"unsolvable";w[*x]'O'a];$[a~,0N;(0;());(1+*x;x[1]@&~x[1] in a)]}/(1;i);}
</code>```

COMMENTS

Definitively, it's not short (nor simple) code. It can be (severely) compacted, but it's left as excercise to the reader (I've dedicated too much time to this problem).

I've included multiline commented solution, but assume newlines as 1 Byte and discard comments (from / to end of line) to count size

The main difficulty is to fully understand all rules. Early optimization of code length is incompatible with developing a solution for a complex problem. Nor bottom-up or top-down approach copes well with unreadable code.

Finally, I developed a decission table (conflict matrix) with 16 rows and 16 columns (for each direction combined with each possible turn). The values of the items are 0 (compatibility), 1 (preference for row), or 2 (preference for column). It satisfies all test, by I'm not sure that all possible situations are well covered

Source file must have k extension. Start interactive interpreter (free for non-commertial use, kx.com) and evaluate at prompt (as shown in 'test' paragraph)

TEST

```<code>q)f " WN    "
1. E->W
2. S->N

q)f " SW    "
1. E->S
2. S->W

q)f "SSSS   "
1. W->S
2. N->S
3. E->S
4. S->S

q)f "SWWN WS"
1. S->W
2. W->N
3. N->S
4. E->W

q)f "SWWNNWS"
1. N->S
2. S->W
3. W->N
4. E->W

q)f "WEWN   "
1. N->W
1. E->E
2. S->W
3. W->N

q)f " SWE   "
unsolvable
</code>```

EXPLANATION

The base structure is the 'precedence matrix'

```<code>   N       E       S       W
   W S E N N W S E E N W S S E N W
NW 0 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1
 S 0 0 0 0 0 1 1 0 0 0 1 1 2 2 2 2
 E 0 0 0 0 0 1 1 1 2 2 0 0 0 2 2 0
 N 0 0 0 0 2 2 0 0 0 2 0 0 0 0 2 0
EN 0 0 0 1 0 0 0 0 0 1 0 0 0 0 1 0
 W 2 2 2 2 0 0 0 0 0 1 1 0 0 0 1 1
 S 0 2 2 0 0 0 0 0 0 1 1 1 2 2 0 0
 E 0 0 2 0 0 0 0 0 2 2 0 0 0 2 0 0
SE 0 0 1 0 0 0 0 1 0 0 0 0 0 1 0 0
 N 0 0 1 1 2 2 2 2 0 0 0 0 0 1 1 0
 W 2 2 0 0 0 2 2 0 0 0 0 0 0 1 1 1
 S 0 2 0 0 0 0 2 0 0 0 0 0 2 2 0 0
WS 0 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0
 E 0 1 1 0 0 0 1 1 2 2 2 2 0 0 0 0
 N 0 1 1 1 2 2 0 0 0 2 2 0 0 0 0 0
 W 2 2 0 0 0 2 0 0 0 0 2 0 0 0 0 0
</code>```

Meaning (by example)

m[NW][SE] has 0 value (both movements are compatible -concurrent-)

m[EW][SN] has 1 value (EW has priority over SN) NOTE.- other priority factors may alter this sentence (emergency vehicles, priority road, ..)

m[NE][SE] has 2 value (SE has priority over NE) NOTE.- other priority factors may alter this sentence (emergency vehicles, priority road, ..)

The matrix can be constructed using four submatrix (4x4) types

```<code>  NESW  A    B    C    D
N DACB  0100 0001 0010 0000
E BDAC  0110 2222 0011 0000
S CBDA  0111 0220 2200 0000
W ACBD  2200 0020 0200 0000
</code>```

The matrix is complemented with a function that assigns a priority to each movement. That function takes account of emergency vehicles, priority roads, orthogonal directions, type of turn and vehicles 'comming from right'

We sort movements by priority and applies matrix values. The resulting submatrix includes conflicts and priority of each movement.

we analyze unsolvable cases (mutual conflicts)

if not, we select most priority item and all movements compatible with it and not incompatible with previous incompatible movements, and create a set of movements allowed to go simultaneously

Write that set of movements and iterate over the rest of candidates

Title: Solve a traffic intersection

Body:
Q, 645 Bytes

r:{(1_x),*x}                                                    /rot
R:{x 3,!3}                                                      /-rot
A:4 4#/:@[16#0;;:;]'[(&0100011001111100b;&0001111101100010b;&0010001111000100b;0);(&0 6 2;&0 1 7;&0 3 3;0)]
K:,/{,'/A x}'3 R\3 0 2 1                                        /Konflick matrix
G:3 R\|E:"NESW"                                                 /E:NESW  G:WSEN NWSE ENWS SENW
m:{x-y*_x%y}                                                    /mod
t:{1=+/m'[_x%4;2]}                                              /orthogonal
w:{-1($x),". ",y[0],"->",y 1;}                               /write
b:{_x%4}                                                        /n-> base dir.
g:m[;4]                                                         /n-> turn
e:(!4)in                                                        /exists
d:{s:r a:e b x;R s&~a}                                       /right free
I:{(G[a]?x 1)+4*a:E?*x}                                         /"dd"->n
O:{E[a],G[a:b x]g x}                                            /n-> "dd"
P:{N::(y=4)&z~4 4;a@&0<a:(@[4#0;b x;:;4-g x])+(5*d x)+(24*e z)+99*e y}          /priority
H:{a::K ./:/:x,/:\:x; if[N&2 in *a;:,0N]; x@&{~|/x[;z]'y}[a]'[!:'u+1;u:!#x]}    /each set of concurrent movements
f:{i:I'(E,'a)@&~^a:4#x; i:i@p:>P[i;E?x 4;E?x 5 6]; {0<#x 1}{a:H x 1;$[a~,0N;-1"unsolvable";w[*x]'O'a];$[a~,0N;(0;());(1+*x;x[1]@&~x[1] in a)]}/(1;i);}

COMMENTS

Definitively, it's not short (nor simple) code. It can be (severely) compacted, but it's left as excercise to the reader (I've dedicated too much time to this problem).

I've included multiline commented solution, but assume newlines as 1 Byte and discard comments (from / to end of line) to count size

The main difficulty is to fully understand all rules. Early optimization of code length is incompatible with developing a solution for a complex problem. Nor bottom-up or top-down approach copes well with unreadable code.

Finally, I developed a decission table (conflict matrix) with 16 rows and 16 columns (for each direction combined with each possible turn). The values of the items are 0 (compatibility), 1 (preference for row), or 2 (preference for column). It satisfies all test, by I'm not sure that all possible situations are well covered

Source file must have k extension. Start interactive interpreter (free for non-commertial use, kx.com) and evaluate at prompt (as shown in 'test' paragraph)

TEST

q)f " WN    "
1. E->W
2. S->N

q)f " SW    "
1. E->S
2. S->W

q)f "SSSS   "
1. W->S
2. N->S
3. E->S
4. S->S

q)f "SWWN WS"
1. S->W
2. W->N
3. N->S
4. E->W

q)f "SWWNNWS"
1. N->S
2. S->W
3. W->N
4. E->W

q)f "WEWN   "
1. N->W
1. E->E
2. S->W
3. W->N

q)f " SWE   "
unsolvable

EXPLANATION

The base structure is the 'precedence matrix'

   N       E       S       W
   W S E N N W S E E N W S S E N W
NW 0 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1
 S 0 0 0 0 0 1 1 0 0 0 1 1 2 2 2 2
 E 0 0 0 0 0 1 1 1 2 2 0 0 0 2 2 0
 N 0 0 0 0 2 2 0 0 0 2 0 0 0 0 2 0
EN 0 0 0 1 0 0 0 0 0 1 0 0 0 0 1 0
 W 2 2 2 2 0 0 0 0 0 1 1 0 0 0 1 1
 S 0 2 2 0 0 0 0 0 0 1 1 1 2 2 0 0
 E 0 0 2 0 0 0 0 0 2 2 0 0 0 2 0 0
SE 0 0 1 0 0 0 0 1 0 0 0 0 0 1 0 0
 N 0 0 1 1 2 2 2 2 0 0 0 0 0 1 1 0
 W 2 2 0 0 0 2 2 0 0 0 0 0 0 1 1 1
 S 0 2 0 0 0 0 2 0 0 0 0 0 2 2 0 0
WS 0 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0
 E 0 1 1 0 0 0 1 1 2 2 2 2 0 0 0 0
 N 0 1 1 1 2 2 0 0 0 2 2 0 0 0 0 0
 W 2 2 0 0 0 2 0 0 0 0 2 0 0 0 0 0

Meaning (by example)

m[NW][SE] has 0 value (both movements are compatible -concurrent-)

m[EW][SN] has 1 value (EW has priority over SN) NOTE.- other priority factors may alter this sentence (emergency vehicles, priority road, ..)

m[NE][SE] has 2 value (SE has priority over NE) NOTE.- other priority factors may alter this sentence (emergency vehicles, priority road, ..)

The matrix can be constructed using four submatrix (4x4) types

  NESW  A    B    C    D
N DACB  0100 0001 0010 0000
E BDAC  0110 2222 0011 0000
S CBDA  0111 0220 2200 0000
W ACBD  2200 0020 0200 0000

The matrix is complemented with a function that assigns a priority to each movement. That function takes account of emergency vehicles, priority roads, orthogonal directions, type of turn and vehicles 'comming from right'

We sort movements by priority and applies matrix values. The resulting submatrix includes conflicts and priority of each movement.

we analyze unsolvable cases (mutual conflicts)

if not, we select most priority item and all movements compatible with it and not incompatible with previous incompatible movements, and create a set of movements allowed to go simultaneously

Write that set of movements and iterate over the rest of candidates


问:
Tips for Golfing in Go
What general tips do you have for golfing in Go? I'm new to Code Golfing and looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to Go.

Please keep to one tip per answer.

答:
Inspired by @EMBLEM's answer here.

You can put a package's functions in the global namespace when you import them like so:

```<code>package main

import ."fmt"

func main() {
    Printf("Hello World!")
}
</code>```

Title: Tips for Golfing in Go

Body:
Inspired by @EMBLEM's answer here.

You can put a package's functions in the global namespace when you import them like so:

package main

import ."fmt"

func main() {
    Printf("Hello World!")
}


答:
JavaScript (ES6), <s>61</s> 51 bytes

```<code>(n,a)=>[...a].map((e,i)=>a[(i<<n)%~-a.length||i]=e)
</code>```

Modifies the input array in place and returns a copy of the original array. If this is unacceptable, &&a can be suffixed to return the modified array. Only works for small values of n due to the limitations of JavaScript's integer arithmetic. <s>61</s> 60 byte recursive version that works with larger n, based on @Lynn's formula:

```<code>f=(n,a,l=a.length)=>n?f(n-1,a.map((_,i)=>a[(i*-~l>>1)%l])):a
</code>```

Title: Faro shuffle an array

Body:
JavaScript (ES6), <s>61</s> 51 bytes

(n,a)=>[...a].map((e,i)=>a[(i<<n)%~-a.length||i]=e)

Modifies the input array in place and returns a copy of the original array. If this is unacceptable, &&a can be suffixed to return the modified array. Only works for small values of n due to the limitations of JavaScript's integer arithmetic. <s>61</s> 60 byte recursive version that works with larger n, based on @Lynn's formula:

f=(n,a,l=a.length)=>n?f(n-1,a.map((_,i)=>a[(i*-~l>>1)%l])):a


答:
Haskell, 62 bytes

```<code>0!a=a
n!a|s<-length a=(n-1)![a!!mod(div(s*i+i)2)s|i<-[0..s-1]]
</code>```

Let s = 2·t be the size of the list. The i-th element of the new list is obtained by taking the -th element of the old list, zero-indexed, modulo s.

Proof: if i = 2·k is even, then

and if i = 2·k + 1 is odd, then

Thus the values used for indexing are 0, t, 1, t + 1, 2, t + 2, …

Title: Faro shuffle an array

Body:
Haskell, 62 bytes

0!a=a
n!a|s<-length a=(n-1)![a!!mod(div(s*i+i)2)s|i<-[0..s-1]]

Let s = 2·t be the size of the list. The i-th element of the new list is obtained by taking the -th element of the old list, zero-indexed, modulo s.

Proof: if i = 2·k is even, then

and if i = 2·k + 1 is odd, then

Thus the values used for indexing are 0, t, 1, t + 1, 2, t + 2, …


答:
Pyke, 7 bytes

```<code>VDlec,s
</code>```

Try it here!

```<code>V       - Repeat N times:
 D      -  a,b = a (2nd arg first time round)
  le    -  b = len(b)//2
    c   -  a = chunk(a,b)
     ,  -  a = zip(*a)
      s -  a = sum(a, [])
</code>```

Title: Faro shuffle an array

Body:
Pyke, 7 bytes

VDlec,s

Try it here!

V       - Repeat N times:
 D      -  a,b = a (2nd arg first time round)
  le    -  b = len(b)//2
    c   -  a = chunk(a,b)
     ,  -  a = zip(*a)
      s -  a = sum(a, [])


答:
APL, 23 21 chars

```<code>({⊃,/⍵(↑,¨↓)⍨2÷⍨⍴⍵}⍣N)A
</code>```

Without the assumption (Thanks to Dennis) and 1 char shorter:

```<code>({{∊,⌿2(2÷⍨≢⍵)⍴⍵}⍣⎕)⎕
</code>```

Try it on online.

Title: Faro shuffle an array

Body:
APL, 23 21 chars

({⊃,/⍵(↑,¨↓)⍨2÷⍨⍴⍵}⍣N)A

Without the assumption (Thanks to Dennis) and 1 char shorter:

({{∊,⌿2(2÷⍨≢⍵)⍴⍵}⍣⎕)⎕

Try it on online.


问:
Generate a "GitHub" Avatar

Background / Description

Note: as @HelkaHomba points out, the actual GitHub identicons are not actually random but based on the hash of a username

The default GitHub avatar is a 5x5-pixel image. A color is picked randomly, and then random pixels are filled in on one side (right or left, 2x5 size) using that color. Then that side is copied & flipped to the other side, across the y-axis. The pixels left over that are not filled in are #F0F0F0, or rgb(240,240,240).

The center column's pixels (1x5 size) are then randomly filled in, using the same color as previously.

Output

Note: for this challenge we will ignore the space that encloses the GitHub avatars

The program should output a 5x5 pixel image file. See http://meta.codegolf.stackexchange.com/a/9095/42499 for specifics

Examples

Note: these were obviously scaled up from 5x5 so you can see them

Good luck!

答:
Python, <s>167</s> <s>164</s> <s>155</s> 148 bytes

Output as ppm

```<code>from random import*
print"P3 5 5 255"
C,P=choice,[[240]*3,[randint(0,255)for _ in"RGB"]]
exec"a,b=C(P),C(P);print' '.join(map(str,a+b+C(P)+b+a));"*5
</code>```

Edit1: range(5) to " "*5

Edit2: shoved a byte at the first print

Edit3: Replaced list comprehension with map since only str(p) was used

Edit4: exec""*5 instead for _ in " "*5:

Some improvement over old, string-based code:

```<code>from random import*
print "P3 5 5 255"
j,c,a=' '.join,choice,['']*5
P=["240 "*3,j([str(randint(0,255))for _ in"RGB"])]
for _ in a:a=[c(P)]*5;a[1]=a[3]=c(P);a[2]=c(P);print j(a)
</code>```

Title: Generate a "GitHub" Avatar

Body:
Python, <s>167</s> <s>164</s> <s>155</s> 148 bytes

Output as ppm

from random import*
print"P3 5 5 255"
C,P=choice,[[240]*3,[randint(0,255)for _ in"RGB"]]
exec"a,b=C(P),C(P);print' '.join(map(str,a+b+C(P)+b+a));"*5

Edit1: range(5) to " "*5

Edit2: shoved a byte at the first print

Edit3: Replaced list comprehension with map since only str(p) was used

Edit4: exec""*5 instead for _ in " "*5:

Some improvement over old, string-based code:

from random import*
print "P3 5 5 255"
j,c,a=' '.join,choice,['']*5
P=["240 "*3,j([str(randint(0,255))for _ in"RGB"])]
for _ in a:a=[c(P)]*5;a[1]=a[3]=c(P);a[2]=c(P);print j(a)


Title: Faro shuffle an array

Body:
Mathematica 44 bytes

With 4 bytes saved thanks to @miles.

Riffle@@TakeDrop[#,Length@#/2]&~Nest~##&

Riffle @@ TakeDrop[#, Length@#/2] &~Nest~## &[list, nShuffles] splits the list into two equal sublists and shuffles (Riffles) them.

 Riffle @@ TakeDrop[#, Length@#/2] &~Nest~## &[Range@8, 1]

{1, 5, 2, 6, 3, 7, 4, 8}

Riffle @@ TakeDrop[#, Length@#/2] &~Nest~## &[Range@100, 23]

{1, 30, 59, 88, 18, 47, 76, 6, 35, 64, 93, 23, 52, 81, 11, 40, 69,
98, 28, 57, 86, 16, 45, 74, 4, 33, 62, 91, 21, 50, 79, 9, 38, 67, 96,
26, 55, 84, 14, 43, 72, 2, 31, 60, 89, 19, 48, 77, 7, 36, 65, 94, 24,
53, 82, 12, 41, 70, 99, 29, 58, 87, 17, 46, 75, 5, 34, 63, 92, 22,
51, 80, 10, 39, 68, 97, 27, 56, 85, 15, 44, 73, 3, 32, 61, 90, 20,
49, 78, 8, 37, 66, 95, 25, 54, 83, 13, 42, 71, 100}


答:
J - 12 bytes

Adverb (!) taking number of shuffles on the left and the array to shuffle on the right.

```<code>/:#/:@$0,#^:
</code>```

The J parser has rules for writing tacit adverbs, but they have very low precedence: if you want to use a train of verbs as a left argument, you can omit an otherwise necessary set of parentheses. So the above is actually short for (/:#/:@$0,#)^:, which takes the number of shuffles on the left as an adverb, and then becomes a monadic function taking the array to shuffle on the right.

That said, we shuffle as follows. # is the length of the array, so 0,# is a two element list: 0 followed by something nonzero. Then #/:@$ replicates that into a list as long as the input array, and takes its sort vector.

The sort vector of a list is the information for how to sort the list: the (0-based) invdex of the smallest element, followed by the index of the next-smallest, and so on. For example, the sort vector of 0 1 0 1 ... will thus be 0 2 4 ... 1 3 5 ....

If J were now to sort this sort vector, it would Faro-shuffle it; but that would be trivial, since we'd get 0 1 2 3 ... back. So we use dyadic /: to sort the input array as if it were 0 2 4 ... 1 3 5 ..., which Faro-shuffles it.

Example usage below. Try it yourself at tryj.tk!

```<code>   1 (/:#/:@$0,#^:) 1 2 3 4 5 6 7 8
1 5 2 6 3 7 4 8

   f =: /:#/:@$0,#^:

   2  f  1 2 3 4 5 6 7 8
1 3 5 7 2 4 6 8

   7  f  _23 _37 52 0 _6 _7 _8 89   NB. "negative 1" is spelled _1
_23 _6 _37 _7 52 _8 0 89

   1  f  0 0 0 0 1 1 1              NB. odd-length lists
0 1 0 1 0 1 0
</code>```

Title: Faro shuffle an array

Body:
J - 12 bytes

Adverb (!) taking number of shuffles on the left and the array to shuffle on the right.

/:#/:@$0,#^:

The J parser has rules for writing tacit adverbs, but they have very low precedence: if you want to use a train of verbs as a left argument, you can omit an otherwise necessary set of parentheses. So the above is actually short for (/:#/:@$0,#)^:, which takes the number of shuffles on the left as an adverb, and then becomes a monadic function taking the array to shuffle on the right.

That said, we shuffle as follows. # is the length of the array, so 0,# is a two element list: 0 followed by something nonzero. Then #/:@$ replicates that into a list as long as the input array, and takes its sort vector.

The sort vector of a list is the information for how to sort the list: the (0-based) invdex of the smallest element, followed by the index of the next-smallest, and so on. For example, the sort vector of 0 1 0 1 ... will thus be 0 2 4 ... 1 3 5 ....

If J were now to sort this sort vector, it would Faro-shuffle it; but that would be trivial, since we'd get 0 1 2 3 ... back. So we use dyadic /: to sort the input array as if it were 0 2 4 ... 1 3 5 ..., which Faro-shuffles it.

Example usage below. Try it yourself at tryj.tk!

   1 (/:#/:@$0,#^:) 1 2 3 4 5 6 7 8
1 5 2 6 3 7 4 8

   f =: /:#/:@$0,#^:

   2  f  1 2 3 4 5 6 7 8
1 3 5 7 2 4 6 8

   7  f  _23 _37 52 0 _6 _7 _8 89   NB. "negative 1" is spelled _1
_23 _6 _37 _7 52 _8 0 89

   1  f  0 0 0 0 1 1 1              NB. odd-length lists
0 1 0 1 0 1 0


问:
Visualize Church numerals

Background

Visualizing λ-calculus terms

Famous lambda-juggler (and code golfer) John Tromp devised an interesting visualization of terms in the λ-calculus. In his words:

abstractions (lambdas) are represented by horizontal lines, variables by vertical lines emanating down from their binding lambda, and applications by horizontal links connecting the leftmost variables.

For example, the lambda term λf.λx.f (f (f (f x))) corresponds to the visualization:

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

Read it from top to bottom:

The first horizontal line represents the first λ.

The four lines descending from it represent the fs in the body.

Similarly, the second horizontal line represents the second λ, and the single new line descending from it represents the x in the body.

The rightmost f line and the x line are connected by a horizontal line representing an application (f x).

The next application is (f (f x)), et cetera.

Church numerals

The Church numerals are a specific sequence of terms in the λ-calculus, taking on the following pattern:

```<code>0 = λf. λx. x
1 = λf. λx. f x
2 = λf. λx. f (f x)
3 = λf. λx. f (f (f x))
...
</code>```

Task

Given an input number n, print some ASCII art that visualizes the nth Church numeral. For instance, the example above is your target output when given n = 4. For n = 0, print:

```<code>---

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

Test cases

Your answer must output exactly the same text (modulo trailing newlines) as this stack snippet for all integer inputs n ≥ 0:

function visualize() {
  var vin = document.getElementById('visualize-in');
  var vout = document.getElementById('visualize-out');
  var n = Number(vin.value);
  if (n < 0) n = 0;
  var line = '-'.repeat(4 * n + 3);
  var bars = function(k) { return '   |'.repeat(k).substr(2); };
  var img = [line, bars(n), line, bars(n + 1)];
  for (var i = n; i > 0; --i) img.push(bars(i) + '----');
  vout.innerHTML = img.join('\n') + '\n |';
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><label for="visualize-in">n <input style="width:50px;" type="number" id="visualize-in" name="visualize-in" onchange="visualize()"/></label>
<pre style="background-color: #eff0f1" id="visualize-out">``````

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

答:
Retina, <s>74</s> <s>67</s> 63 bytes

Byte count assumes ISO 8859-1 encoding.

```<code>.
 |
^
$.'$*----¶
\z
¶$` |
+`(.+\|) .+$
$&¶$1----
$
¶ |
  ¶
¶
</code>```

Input is in unary, using any character except linefeeds as the digit.

Try it online!

Explanation

```<code>.
 |
</code>```

We start by turning each unary digit into  |   (note the trailing spaces). This gives us the second line of the output (plus two trailing spaces if the input is at least 1).

```<code>^
$.'$*----¶
</code>```

We match the beginning of the string in order to prepend the first line. This is done using some Retina-specific substitution features. $* repeats the character on the right as many times as its left arugment. $.' evaluates the number of characters to the right of the match. Since the match is only the beginning of the string this gives as many - as there are characters in the string and --- appends three more. The ¶ is an alias for a linefeed. So now we've got the first two lines.

```<code>\z
¶$` |
</code>```

Now we append the next two lines. We do this by matching the end of the string and appending a linefeed, the entire string again and then  | to get the fourth line right.

```<code>+`(.+\|) .+$
$&¶$1----
</code>```

Time for the applications. The leading + makes Retina repeat this stage until the output stops changing (in this case because the regex no long matches). The regex matches the entire last line, provided it contains a | follows by a space. We capture everything up to the | (which will be the second to last) in group 1. We write the line back with $&, a linefeed, then group 1 (thereby dropping the last |) and then ----.

```<code>$
¶ |
</code>```

This just adds the final line containing only a single |.

```<code>  ¶
¶
</code>```

Finally we need to get rid of the trailing spaces on the second line.

Title: Visualize Church numerals

Body:
Retina, <s>74</s> <s>67</s> 63 bytes

Byte count assumes ISO 8859-1 encoding.

.
 |
^
$.'$*----¶
\z
¶$` |
+`(.+\|) .+$
$&¶$1----
$
¶ |
  ¶
¶

Input is in unary, using any character except linefeeds as the digit.

Try it online!

Explanation

.
 |

We start by turning each unary digit into  |   (note the trailing spaces). This gives us the second line of the output (plus two trailing spaces if the input is at least 1).

^
$.'$*----¶

We match the beginning of the string in order to prepend the first line. This is done using some Retina-specific substitution features. $* repeats the character on the right as many times as its left arugment. $.' evaluates the number of characters to the right of the match. Since the match is only the beginning of the string this gives as many - as there are characters in the string and --- appends three more. The ¶ is an alias for a linefeed. So now we've got the first two lines.

\z
¶$` |

Now we append the next two lines. We do this by matching the end of the string and appending a linefeed, the entire string again and then  | to get the fourth line right.

+`(.+\|) .+$
$&¶$1----

Time for the applications. The leading + makes Retina repeat this stage until the output stops changing (in this case because the regex no long matches). The regex matches the entire last line, provided it contains a | follows by a space. We capture everything up to the | (which will be the second to last) in group 1. We write the line back with $&, a linefeed, then group 1 (thereby dropping the last |) and then ----.

$
¶ |

This just adds the final line containing only a single |.

  ¶
¶

Finally we need to get rid of the trailing spaces on the second line.


Title: Visualize Church numerals

Body:
Background

Visualizing λ-calculus terms

Famous lambda-juggler (and code golfer) John Tromp devised an interesting visualization of terms in the λ-calculus. In his words:

abstractions (lambdas) are represented by horizontal lines, variables by vertical lines emanating down from their binding lambda, and applications by horizontal links connecting the leftmost variables.

For example, the lambda term λf.λx.f (f (f (f x))) corresponds to the visualization:

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

Read it from top to bottom:

The first horizontal line represents the first λ.

The four lines descending from it represent the fs in the body.

Similarly, the second horizontal line represents the second λ, and the single new line descending from it represents the x in the body.

The rightmost f line and the x line are connected by a horizontal line representing an application (f x).

The next application is (f (f x)), et cetera.

Church numerals

The Church numerals are a specific sequence of terms in the λ-calculus, taking on the following pattern:

```<code>0 = λf. λx. x
1 = λf. λx. f x
2 = λf. λx. f (f x)
3 = λf. λx. f (f (f x))
...
</code>```

Task

Given an input number n, print some ASCII art that visualizes the nth Church numeral. For instance, the example above is your target output when given n = 4. For n = 0, print:

```<code>---

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

Test cases

Your answer must output exactly the same text (modulo trailing newlines) as this stack snippet for all integer inputs n ≥ 0:

function visualize() {
  var vin = document.getElementById('visualize-in');
  var vout = document.getElementById('visualize-out');
  var n = Number(vin.value);
  if (n < 0) n = 0;
  var line = '-'.repeat(4 * n + 3);
  var bars = function(k) { return '   |'.repeat(k).substr(2); };
  var img = [line, bars(n), line, bars(n + 1)];
  for (var i = n; i > 0; --i) img.push(bars(i) + '----');
  vout.innerHTML = img.join('\n') + '\n |';
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><label for="visualize-in">n <input style="width:50px;" type="number" id="visualize-in" name="visualize-in" onchange="visualize()"/></label>
<pre style="background-color: #eff0f1" id="visualize-out">``````

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

Body:
Python, 201 bytes

from pylab import*
n=input()
p=array(list(' -|\n'))
a=zeros((n+5,n*4+4),int)
for k in range(n):l=4*k+5;a[:-k-1,l]=2;a[-k-2,l-3:l+1]=1
a[:,1]=2
a[1,-3]=0
a[0]=a[2]=1
a[:,-1]=3
print''.join(ravel(p[a]))


问:
Jam don't add like that

Background

Jelly's arithmetic atoms vectorize automatically. In fact, x + y is well-defined whenever x and y are numbers or ragged arrays of numbers. Jelly's source code implements this behavior using a generic vectorizer, but for this challenge, we'll only consider addition of integers and nested integer arrays.

Definitions

Define the depth of x as 0 if x is an integer, as 1 if it is a (possibly empty) flat array of integers, and as n + 1 if it contains at least one element of depth n and no elements of depth k > n.

This way, 1 has depth 0, [] and [1] and [1, 1] have depth 1, [[], []] and [[1], [1]] and [[1]] and [1, []] have depth 2, [1, [1, [1]]] has depth 3, etc.

The operation x + y is defined as follows.

If x and y have depth 0, return their sum.

If x and y have equal but positive depths, recursively apply + to all items of x and the corresponding items of y.

If x and y have different lengths, append the tail of the longer array to the array of sums.

Return the result.

If x's depth is strictly smaller than y's depth, recursively apply + to x and all items of y, and return the result.

Do the opposite if y's depth is strictly smaller than x's.

For example, consider the operation [1, [2, 3], [4]] + [[[10, 20], [30], 40, 50], 60].

The depth of the left argument is 2, while the depth of the right argument is 3, so we compute [1, [2, 3], [4]] + [[10, 20], [30], 40, 50] and [1, [2, 3], [4]] + 60.

[1, [2, 3], [4]] and [[10, 20], [30], 40, 50] both have depth 2, so we compute 1 + [10, 20], [2, 3] + [30] and [4] + 40.

1 + [10, 20] = [1 + 10, 1 + 20] = [11, 21]

[2, 3] + [30] = [2 + 30, 3] = [32, 3]

Note that 3 remains untouched, since it doesn't have a matching element.

[4] + 40 = [4 + 40] = [44]

50 doesn't have a matching element, so the result is [[[11, 21], [32, 3], [44], 50]].

[1, [2, 3], [4]] + 60 = [1 + 60, [2, 3] + 60, [4] + 60] = [61, [2 + 60, 3 + 60], [4 + 60]], resulting in [61, [62, 63], [64]].

The final result is [[[11, 21], [32, 3], [44], 50], [61, [62, 63], [64]]].

Task

Write a program or a function that takes two integers, two nested arrays of integers or a combination thereof as input and returns their sum, as defined above.

If your language has multiple array-like types (lists, tuples, vectors, etc.) you may choose any of them for your answer. The return type must match the argument type.

To prevent boring and unbeatable solutions, if a language has this exact operation as a built-in, you may not use that language.

All built-ins of all other languages are allowed. If your language of choice permits this, you may overload and/or redefine the built-in addition.

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

Test cases

```<code>0 + 0                           = 0
[-1, 0, -1] + [1]               = [0, 0, -1]
[] + [0]                        = [0]
[] + 0                          = []
[] + []                         = []
[[], 0] + []                    = [[], []]
[1, 2, 3] + 10                  = [11, 12, 13]
[1, 2, 3] + [10]                = [11, 2, 3]
[1, 2, 3] + [10, [20]]          = [[11, 12, 13], [21, 2, 3]]
[1, 2, 3, []] + [10, [20]]      = [11, [22], 3, []]
[1, [2, [3, [4]]]] + [10, [20]] = [[11, [21]], [[12, [22]], [13, [24]]]]
</code>```

To generate more test cases, you can use this Jelly program.

答:
Pyth, 42 bytes

```<code>L?sIb0heSyM+b0M?qFyMJ,GH?yGgM.tJ0+GHgLFyDJ
</code>```

Test suite

The last 4 bytes simply run the function on the input.

```<code>L?sIb0heSyM+b0M?qFyMJ,GH?yGgM.tJ0+GHgLFyDJ

L?sIb0heSyM+b0
                  Define y(b), a helper function to calculate the depth.
 ?                Ternary:
  sIb             If b is invariant under the s function, which is only the case
                  if s is an int.
     0            The depth is 0.
           +b0    Add a 0 on to b. This handles the edge case where b is [].
         yM       Map each to their depth
       eS         Take the max.
      h           Add one.

M?qFyMJ,GH?yGgM.tJ0+GHgLFyDJ
M                               Define g(G, H), which calculates the Jelly +.
 ?                              Ternary:
       ,GH                      Form [G, H].
      J                         Save it to J.
    yM                          Map each to its depth.
  qF                            Check if they are equal.
          ?yG                   If so, check if the depth is nonzero.
               .tJ0             If so, transpose J, pairing each element of each
                                argument with the corresponding element of the
                                other. Pad with zeroes.
             gM                 Map each to its Jelly +.
                   +GH          If the depths are zero, return the normal sum.
                         yDJ    If the depths are different, order J by depth.
                      gLF       Apply the function which left-maps the Jelly +
                                function to the two values. The first is
                                treated as a constant, while the second varies
                                over elements over the second values.
</code>```

Title: Jam don't add like that

Body:
Pyth, 42 bytes

L?sIb0heSyM+b0M?qFyMJ,GH?yGgM.tJ0+GHgLFyDJ

<a href="https://pyth.herokuapp.com/?code=L%3FsIb0heSyM%2Bb0M%3FqFyMJ%2CGH%3FyGgM.tJ0%2BGHgLFyDJgF.Q&test_suite=1&test_suite_input=0%0A0%0A%5B-1%2C+0%2C+-1%5D%0A%5B1%5D%0A%5B%5D%0A%5B0%5D%0A%5B%5D%0A0%0A%5B%5D%0A%5B%5D%0A%5B%5B%5D%2C+0%5D%0A%5B%5D%0A%5B1%2C+2%2C+3%5D%0A10%0A%5B1%2C+2%2C+3%5D%0A%5B10%5D%0A%5B1%2C+2%2C+3%5D%0A%5B10%2C+%5B20%5D%5D%0A%5B1%2C+2%2C+3%2C+%5B%5D%5D%0A%5B10%2C+%5B20%5D%5D%0A%5B1%2C+%5B2%2C+%5B3%2C+%5B4%5D%5D%5D%5D%0A%5B10%2C+%5B20%5D%5D%0A%5B1%2C+%5B2%2C+3%5D%2C+%5B4%5D%5D%0A%5B%5B%5B10%2C+20%5D%2C+%5B30%5D%2C+40%2C+50%5D%2C+60%5D&debug=0&input_size=2" rel="nofollow">Test suite

The last 4 bytes simply run the function on the input.

L?sIb0heSyM+b0M?qFyMJ,GH?yGgM.tJ0+GHgLFyDJ

L?sIb0heSyM+b0
                  Define y(b), a helper function to calculate the depth.
 ?                Ternary:
  sIb             If b is invariant under the s function, which is only the case
                  if s is an int.
     0            The depth is 0.
           +b0    Add a 0 on to b. This handles the edge case where b is [].
         yM       Map each to their depth
       eS         Take the max.
      h           Add one.

M?qFyMJ,GH?yGgM.tJ0+GHgLFyDJ
M                               Define g(G, H), which calculates the Jelly +.
 ?                              Ternary:
       ,GH                      Form [G, H].
      J                         Save it to J.
    yM                          Map each to its depth.
  qF                            Check if they are equal.
          ?yG                   If so, check if the depth is nonzero.
               .tJ0             If so, transpose J, pairing each element of each
                                argument with the corresponding element of the
                                other. Pad with zeroes.
             gM                 Map each to its Jelly +.
                   +GH          If the depths are zero, return the normal sum.
                         yDJ    If the depths are different, order J by depth.
                      gLF       Apply the function which left-maps the Jelly +
                                function to the two values. The first is
                                treated as a constant, while the second varies
                                over elements over the second values.


答:
Actually, 15 bytes

```<code>`;l½≈@│t)HZ♂i`n
</code>```

Try it online!

Explanation:

```<code>`;l½≈@│t)HZ♂i`n
`            `n  do the following n times:
 ;l½≈              push half the length of the array
     @             swap
      │            duplicate entire stack
       t)H         last L//2 elements, first L//2 elements
          Z♂i      zip, flatten each element
</code>```

Title: Faro shuffle an array

Body:
A Faro shuffle is a technique frequently used by magicians to "shuffle" a deck. To perform a Faro shuffle you first cut the deck into 2 equal halves then you interleave the two halves. For example

```<code>[1 2 3 4 5 6 7 8]
</code>```

Faro shuffled is

```<code>[1 5 2 6 3 7 4 8]
</code>```

This can be repeated any number of times. Interestingly enough, if you repeat this enough times, you will always end up back at the original array. For example:

```<code>[1 2 3 4 5 6 7 8]
[1 5 2 6 3 7 4 8]
[1 3 5 7 2 4 6 8]
[1 2 3 4 5 6 7 8]
</code>```

Notice that 1 stays on the bottom and 8 stays on the top. That makes this an outer-shuffle. This is an important distinction.

The Challenge

Given an array of integers A, and a number N, output the array after N Faro shuffles. A may contain repeated or negative elements, but it will always have an even number of elements. You can assume the array will not be empty. You can also assume that N will be a non-negative integer, although it may be 0. You can take these inputs in any reasonable manner. The shortest answer in bytes wins!

Test IO:

```<code>#N, A,                                              Output
1,  [1, 2, 3, 4, 5, 6, 7, 8]                        [1, 5, 2, 6, 3, 7, 4, 8]
2,  [1, 2, 3, 4, 5, 6, 7, 8]                        [1, 3, 5, 7, 2, 4, 6, 8]
7,  [-23, -37, 52, 0, -6, -7, -8, 89]               [-23, -6, -37, -7, 52, -8, 0, 89]
0,  [4, 8, 15, 16, 23, 42]                          [4, 8, 15, 16, 23, 42]
11, [10, 11, 8, 15, 13, 13, 19, 3, 7, 3, 15, 19]    [10, 19, 11, 3, 8, 7, 15, 3, 13, 15, 13, 19]
</code>```

And, a massive test case:

```<code>23, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100]
</code>```

Should output:

```<code>[1, 30, 59, 88, 18, 47, 76, 6, 35, 64, 93, 23, 52, 81, 11, 40, 69, 98, 28, 57, 86, 16, 45, 74, 4, 33, 62, 91, 21, 50, 79, 9, 38, 67, 96, 26, 55, 84, 14, 43, 72, 2, 31, 60, 89, 19, 48, 77, 7, 36, 65, 94, 24, 53, 82, 12, 41, 70, 99, 29, 58, 87, 17, 46, 75, 5, 34, 63, 92, 22, 51, 80, 10, 39, 68, 97, 27, 56, 85, 15, 44, 73, 3, 32, 61, 90, 20, 49, 78, 8, 37, 66, 95, 25, 54, 83, 13, 42, 71, 100]
</code>```

Body:
Actually, 15 bytes

`;l½≈@│t)HZ♂i`n

Try it online!

Explanation:

`;l½≈@│t)HZ♂i`n
`            `n  do the following n times:
 ;l½≈              push half the length of the array
     @             swap
      │            duplicate entire stack
       t)H         last L//2 elements, first L//2 elements
          Z♂i      zip, flatten each element


答:
Python 2, 138 bytes

```<code>def f(n,a=1):
 if ~n:b="---\n";c=" |";d="  "+c;print("-"*n*4+b+c*(n>0)+d*(n-1)+"\n"+"-"*n*4+b+c+d*n+"\n")*a+c+d*(n-1)+"-"*4*(n>0);f(n-1,0)
</code>```

The function contains an extra parameter, but it is for internal use only.  It has a default value and should be omitted when calling the function.  I hope this doesn't violate the rules.

The function draws the first 5 rows, then recursively calls itself to draw the remaining rows.

Try it online

Title: Visualize Church numerals

Body:
Python 2, 138 bytes

def f(n,a=1):
 if ~n:b="---\n";c=" |";d="  "+c;print("-"*n*4+b+c*(n>0)+d*(n-1)+"\n"+"-"*n*4+b+c+d*n+"\n")*a+c+d*(n-1)+"-"*4*(n>0);f(n-1,0)

The function contains an extra parameter, but it is for internal use only.  It has a default value and should be omitted when calling the function.  I hope this doesn't violate the rules.

The function draws the first 5 rows, then recursively calls itself to draw the remaining rows.

Try it online


答:
Java, <s>802</s> <s>794</s> <s>754</s> 746 bytes

I decided to take up @Dennis♦ for the challenge to operate on strings "as a last resort" because it was probably "too complicated". Also, in the worst language to golf on.

Arrays in the input are comma-separated, surrounded with square brackets, and without whitespace.

Full program with functions wrapped into a class and with test cases

```<code>import java.util.*;
List<String>p(String s){List r=new ArrayList<String>();String p="";int l=0;for(char c:s.substring(1,s.length()-1).toCharArray()){l+=c=='['?1:c==']'?-1:0;if(c==','&&l<1){r.add(p);p="";}else p+=c;}if(p!="")r.add(p);return r;}
int d(String s){int l=0;if(s.contains("[")){for(String c:p(s))l=d(c)>l?d(c):l;l++;}return l;}
String f(String x,String y){int i=0;String r="";if(d(x)<1&&d(y)<1)r+=Integer.valueOf(x)+Integer.valueOf(y);else{r="[";if(d(x)<d(y))for(String k:p(y))r+=(i++<1?"":",")+f(x,k);else if(d(x)>d(y))for(String k:p(x))r+=(i++<1?"":",")+f(k,y);else for(;i<p(x).size()||i<p(y).size();i++)r+=(i<1?"":",")+(i<p(x).size()&&i<p(y).size()?f(p(x).get(i),p(y).get(i)):i<p(x).size()?p(x).get(i):p(y).get(i));r+="]";}return r;}
</code>```

I might port this to C++ later since it's the other language I know that doesn't support ragged arrays, since I'm <s>pretty sure</s> almost certain it'll be shorter than this answer. This was mostly a proof of concept but any golfing tips would still be appreciated!

-31 bytes from @user902383 suggesting using a foreach over a converted character array, and then I saved a little more from rearranging the if blocks in the final part.

Title: Jam don't add like that

Body:
Background

Jelly's arithmetic atoms vectorize automatically. In fact, x + y is well-defined whenever x and y are numbers or ragged arrays of numbers. Jelly's source code implements this behavior using a generic vectorizer, but for this challenge, we'll only consider addition of integers and nested integer arrays.

Definitions

Define the depth of x as 0 if x is an integer, as 1 if it is a (possibly empty) flat array of integers, and as n + 1 if it contains at least one element of depth n and no elements of depth k > n.

This way, 1 has depth 0, [] and [1] and [1, 1] have depth 1, [[], []] and [[1], [1]] and [[1]] and [1, []] have depth 2, [1, [1, [1]]] has depth 3, etc.

The operation x + y is defined as follows.

If x and y have depth 0, return their sum.

If x and y have equal but positive depths, recursively apply + to all items of x and the corresponding items of y.

If x and y have different lengths, append the tail of the longer array to the array of sums.

Return the result.

If x's depth is strictly smaller than y's depth, recursively apply + to x and all items of y, and return the result.

Do the opposite if y's depth is strictly smaller than x's.

For example, consider the operation [1, [2, 3], [4]] + [[[10, 20], [30], 40, 50], 60].

The depth of the left argument is 2, while the depth of the right argument is 3, so we compute [1, [2, 3], [4]] + [[10, 20], [30], 40, 50] and [1, [2, 3], [4]] + 60.

[1, [2, 3], [4]] and [[10, 20], [30], 40, 50] both have depth 2, so we compute 1 + [10, 20], [2, 3] + [30] and [4] + 40.

1 + [10, 20] = [1 + 10, 1 + 20] = [11, 21]

[2, 3] + [30] = [2 + 30, 3] = [32, 3]

Note that 3 remains untouched, since it doesn't have a matching element.

[4] + 40 = [4 + 40] = [44]

50 doesn't have a matching element, so the result is [[[11, 21], [32, 3], [44], 50]].

[1, [2, 3], [4]] + 60 = [1 + 60, [2, 3] + 60, [4] + 60] = [61, [2 + 60, 3 + 60], [4 + 60]], resulting in [61, [62, 63], [64]].

The final result is [[[11, 21], [32, 3], [44], 50], [61, [62, 63], [64]]].

Task

Write a program or a function that takes two integers, two nested arrays of integers or a combination thereof as input and returns their sum, as defined above.

If your language has multiple array-like types (lists, tuples, vectors, etc.) you may choose any of them for your answer. The return type must match the argument type.

To prevent boring and unbeatable solutions, if a language has this exact operation as a built-in, you may not use that language.

All built-ins of all other languages are allowed. If your language of choice permits this, you may overload and/or redefine the built-in addition.

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

Test cases

```<code>0 + 0                           = 0
[-1, 0, -1] + [1]               = [0, 0, -1]
[] + [0]                        = [0]
[] + 0                          = []
[] + []                         = []
[[], 0] + []                    = [[], []]
[1, 2, 3] + 10                  = [11, 12, 13]
[1, 2, 3] + [10]                = [11, 2, 3]
[1, 2, 3] + [10, [20]]          = [[11, 12, 13], [21, 2, 3]]
[1, 2, 3, []] + [10, [20]]      = [11, [22], 3, []]
[1, [2, [3, [4]]]] + [10, [20]] = [[11, [21]], [[12, [22]], [13, [24]]]]
</code>```

To generate more test cases, you can use this Jelly program.

Body:
Java, <s>802</s> <s>794</s> <s>754</s> 746 bytes

I decided to take up @Dennis♦ for the challenge to operate on strings "as a last resort" because it was probably "too complicated". Also, in the worst language to golf on.

Arrays in the input are comma-separated, surrounded with square brackets, and without whitespace.

Full program with functions wrapped into a class and with test cases

import java.util.*;
List<String>p(String s){List r=new ArrayList<String>();String p="";int l=0;for(char c:s.substring(1,s.length()-1).toCharArray()){l+=c=='['?1:c==']'?-1:0;if(c==','&&l<1){r.add(p);p="";}else p+=c;}if(p!="")r.add(p);return r;}
int d(String s){int l=0;if(s.contains("[")){for(String c:p(s))l=d(c)>l?d(c):l;l++;}return l;}
String f(String x,String y){int i=0;String r="";if(d(x)<1&&d(y)<1)r+=Integer.valueOf(x)+Integer.valueOf(y);else{r="[";if(d(x)<d(y))for(String k:p(y))r+=(i++<1?"":",")+f(x,k);else if(d(x)>d(y))for(String k:p(x))r+=(i++<1?"":",")+f(k,y);else for(;i<p(x).size()||i<p(y).size();i++)r+=(i<1?"":",")+(i<p(x).size()&&i<p(y).size()?f(p(x).get(i),p(y).get(i)):i<p(x).size()?p(x).get(i):p(y).get(i));r+="]";}return r;}

I might port this to C++ later since it's the other language I know that doesn't support ragged arrays, since I'm <s>pretty sure</s> almost certain it'll be shorter than this answer. This was mostly a proof of concept but any golfing tips would still be appreciated!

-31 bytes from @user902383 suggesting using a foreach over a converted character array, and then I saved a little more from rearranging the if blocks in the final part.


问:
Divisor sum from prime-power factorisation
The task is to compute the divisor sum of a number given its prime factorisation.

Input

Two arrays (or something equivalent) of length n, one containing the prime factor and the other containing the corresponding exponent.

Output

The sum of all divisors (including the number itself).

Example

The number 240 has 2, 3, and 5 as prime factors with 4, 1, and 1 as the respective exponents. The expected output would then be 744.

```<code>Input: [2,3,5] [4,1,1]
Output: 744
</code>```

Scoring

Shortest code in bytes wins!

If your solution's run time complexity is O(sum of exponents) rather than O(product of exponents), your score may be multiplied by 0.8.

There was a similar question posted here, but it wasn't a challenge. I think the problem is interesting enought to be golfed.

The winner will be choosen this weekend

答:
Racket (Scheme), 65 * 0.8 = 52 bytes

Same arithmetic as everyone else

```<code>(λ(x y)(foldl(λ(m n o)(*(/(-(expt m(+ n 1))1)(- m 1))o))1 x y))
</code>```

Explanation:

```<code>(λ (x y)    ;defines anonymous function with two inputs
    (foldl    ;recursively applies the following function to all elements of the lists given to an argument given (foldl function argument lists lists lists...)
        (λ (m n o) (* (/ (- (expt m (+ n 1)) 1) (- m 1)) o))    ;an anonymous function representing the same arithmetic used in the CJam answer, then multiplying it with our incrementor
        1 x y))    ;the incrementor argument is 1, and the input lists are the ones provided into the original function
</code>```

Body:
Racket (Scheme), 65 * 0.8 = 52 bytes

Same arithmetic as everyone else

(λ(x y)(foldl(λ(m n o)(*(/(-(expt m(+ n 1))1)(- m 1))o))1 x y))

Explanation:

(λ (x y)    ;defines anonymous function with two inputs
    (foldl    ;recursively applies the following function to all elements of the lists given to an argument given (foldl function argument lists lists lists...)
        (λ (m n o) (* (/ (- (expt m (+ n 1)) 1) (- m 1)) o))    ;an anonymous function representing the same arithmetic used in the CJam answer, then multiplying it with our incrementor
        1 x y))    ;the incrementor argument is 1, and the input lists are the ones provided into the original function


Title: Divisor sum from prime-power factorisation

Body:
The task is to compute the divisor sum of a number given its prime factorisation.

Input

Two arrays (or something equivalent) of length n, one containing the prime factor and the other containing the corresponding exponent.

Output

The sum of all divisors (including the number itself).

Example

The number 240 has 2, 3, and 5 as prime factors with 4, 1, and 1 as the respective exponents. The expected output would then be 744.

```<code>Input: [2,3,5] [4,1,1]
Output: 744
</code>```

Scoring

Shortest code in bytes wins!

If your solution's run time complexity is O(sum of exponents) rather than O(product of exponents), your score may be multiplied by 0.8.

There was a similar question posted here, but it wasn't a challenge. I think the problem is interesting enought to be golfed.

The winner will be choosen this weekend

Body:
J, 14 bytes * 0.8 = 11.2

[:*/(^>:)%&<:[

Usage

   f =: [:*/(^>:)%&<:[
   2 3 5 f 4 1 1
744


问:
Swap bits with their neighbours

Task description

Given an integer, swap its (2k–1)-th and 2k-th least significant bits for all integers k > 0. This is sequence A057300 in the OEIS.

(The number is assumed to have “infinitely many” leading zeroes. In practice, this simply means prepending a single 0 bit to odd-length numbers.)

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

Test cases

```<code>0 -> 0
1 -> 2
9 -> 6
85 -> 170
220 -> 236
1827 -> 2835
47525 -> 30298
</code>```

答:
C, <s>32</s> <s>30</s> 29 bytes

```<code>f(x){return(x&~0U/3)*3+x>>1;}                // 30 bit version, see below

// less golfed:
f(x){return ((x & 0x55555555)*3 + x) >>1;}   //  >> is lower precedence than +
</code>```

Algorithm copied from xsot's comment on xnor's Python answer.  Instead of masking both ways, mask one way and combine.

This compiles to the same asm as the last version I tested, and it works (for x up to 0x3FFFFFFF, and for x above that as long as bit 30 isn't set, see below).  In machine code, it's the same length as my existing asm answer.

The above version always clears the high bit of the result.  The best safe version is 32 bytes:

```<code>g(x){return 2*x-3*(x/2U&~0U/3);}   // safe 32bit version, works for all x
</code>```

The Python version doesn't have this problem, because python uses arbitrary-precision integer types when needed, instead of truncating to a fixed upper limit.

Title: Swap bits with their neighbours

Body:
C, <s>32</s> <s>30</s> 29 bytes

f(x){return(x&~0U/3)*3+x>>1;}                // 30 bit version, see below

// less golfed:
f(x){return ((x & 0x55555555)*3 + x) >>1;}   //  >> is lower precedence than +

Algorithm copied from xsot's comment on xnor's Python answer.  Instead of masking both ways, mask one way and combine.

This <a href="http://gcc.godbolt.org/#compilers:!((compiler:g6,options:'-xc+-std%3Dgnu99+-O3+-Wno-all+-Wno-extra+-fno-verbose-asm',sourcez:PQKgBAIglg5lAuBDANmAKgJ0QVwLaIHIBnMAYTADcBTDIqAewDswRgAoAMwAoAPASgDeGKvGwZGvAGQA/AAwBVYAGYQAJj7BVAailzFSvmoDcAXzZtQYGPWQcqAEzKUadJmHocwPRvQzF3jFT4RADWYAAOAJ7wABZuHNiMAMbwDMysbDC8gsKi4mCqIDwAtCq8mvIyCsp8pmwx2UIiYsyFJWU8VfpqGqqmYGDAwGBEiNRgsVRg8uZDXkT08P5RsW5UPOHCRK6MAHRsAOKNuS1eOp16NSBKAHw3AIx1ABLHzeK8511XBpr9g8N3MBQEjIegAdxoEWESQcVGSU1iiGYWgANCN6BMYsCgSQwTFEPAwAccWB7PQoIwYGwAJKvPISC7VAzXLQ8O6PEwDf5gJJiYSMQnUWhpABcI0QuCmiCIuDA0qJ2TljEcL34YDxUCSMXVNARVCI8AcbAAUnSWlxdEzDEpWb06mwAMRQTyyNiJOgwQKOUGUsAcABsABYuO7YF6wD6YF5BGwBid8pb5AAZJPKHqaMBaMCJlNXPpsMxsCmEjger1cYvRpr0xNp9SaT6XZl9Myhz0OP30DEAXjATaMjrh9md5gs4A4GHosu8vmW0TizCRRAhGDRACNsIT6OFwvQ6IaJjRcBSbPQYJExWuELISVRqOl2G3w0wgtKQgB9XywEOMMsdtUCLGYBPh2d5wsEYS9v2QEgY49BXvAJC9haPBgIC9x8GAkhgGBjAQbUQHxq0RRgMUYAqPBCBEAOhZur%2BYYdi%2BEHvsxkyMO%2BRBYhw8A/n%2BjgATB9HtnBEFgFBTIsAUA4DLB7iqGJ2aodhU5vgRMlCc%2BCFIXJaE3GAjyEW8xGoWRFFaTRswgLGzC9oUGJZlQsbaYUUxZvQ5g4QpzBkXZXJcshSl9goqYGLGPbZt5OG9H5AVYdmeghXwAA8SUYbp9yxk5CkuZmEXFFQvSZWAWW2SAXCRXZmFudlIDeYGID2e4NWRRRsYZGOEwYJEmJTIsMSQmCiCRGi8qIBEe50GuyBTDwAAc/pyjKSrLpCGSyUxb7vrhvEMfxmGAepfE4aJ4n6NJwEaaBCm8HFr6hGpYBEThai5ShpFRbp%2BkEYWTrJMg2D2FMSUGsOAq7DENxusWQbvlugTMbhQYhtDgaw9GYAHcBKNo3dkFBcmyjndg2OElMsXYbjD1PVQL1Zm9ZEFZ9GEWUAAA%3D)),filterAsm:(binary:!t,commentOnly:!t,directives:!t,intel:!t,labels:!t),version:3" rel="nofollow noreferrer">compiles to the same asm as the last version I tested, and it works (for x up to 0x3FFFFFFF, and for x above that as long as bit 30 isn't set, see below).  In machine code, it's the same length as my existing asm answer.

The above version always clears the high bit of the result.  The best safe version is 32 bytes:

g(x){return 2*x-3*(x/2U&~0U/3);}   // safe 32bit version, works for all x

The Python version doesn't have this problem, because python uses arbitrary-precision integer types when needed, instead of truncating to a fixed upper limit.


问:
Swap prime exponents with their neighbours
(Follow-up to my question about swapping bits with their neighbours.)

Task

Given a positive integer x = (2a · 3b) · (5c · 7d) · (11e · 13f) · …, print the integer obtained by swapping the exponents in this factorization for each successive pair of primes, y = (2b · 3a) · (5d · 7c) · (11f · 13e) · …

A061898 in the OEIS. This is code-golf, so the shortest program (in bytes) wins!

Test cases

```<code>1 -> 1
2 -> 3
3 -> 2
10 -> 21
37 -> 31
360 -> 756
12345 -> 11578
67895678 -> 125630871
</code>```

答:
Python 2, <s>112</s> <s>109</s> <s>108</s> <s>95</s> 94 bytes

f=lambda n,k=4,m=6,p=[3,2]:1/n or n%p[1]and f(n,k+1,m*k,m*m%k*[k]+p)or p[len(p)*2%4]*f(n/p[1])
```
<p>Test it on Ideone.</p>
<h3>How it works</h3>
<p>When <strong>f</strong> is called, it first computes <strong>1/n</strong>. If the result is non-zero, <strong>n</strong> is <strong>1</strong> and <strong>f</strong> returns <strong>1</strong>.</p>
<p>If <strong>n > 1</strong>, the following happens.</p>
<ul>
<li><p>If <strong>n</strong> is not divisible by <strong>p[1]</strong> (initially <strong>2</strong>), <code>n%p[1]</code> yields a truthy value and</p>
<pre class="lang-python prettyprint-override"><code>  f(n,k+1,m*k,m*m%k*[k]+p)
</code>```

gets called.

This branch generates prime number until the penultimate one evenly divides n. To do so, it uses the following corollary of Wilson's theorem.

At all times, m is equal to the factorial of k - 1 (initially 6 = 3! and 4. In each iteration, the result of m*m%k*[k] gets prepended to the list of primes p. By the corollary, m*m%k is 1 if k is prime and 0 if not, so this prepends k to p if and only if k is a prime number.

If n is divisible by p[1], n%p[1] yields 0 and

  p[len(p)*2%4]*f(n/p[1])
```

gets executed.

If p contains an even amount of prime numbers, len(p)*2%4 will yield 0 and the first multiplicand takes the value of p[0]. If p contains an odd amount of prime numbers, len(p)*2%4 will yield 2 and the first multiplicand takes the value of p[2].

In either case, this is the prime whose exponents has to get swapped with the one of p[1], so we divide n by p[1] (decreasing the exponent by 1) and multiply the result of f(n/p[1]) by the corresponding prime (increasing the exponent by 1).

Note that f(n/p[1]) resets k, m and p to their default values. f(n/p[1],k,m,p) would improve efficiency, at the cost of six extra bytes.

Body:
Python 2, <s>112</s> <s>109</s> <s>108</s> <s>95</s> 94 bytes

f=lambda n,k=4,m=6,p=[3,2]:1/n or n%p[1]and f(n,k+1,m*k,m*m%k*[k]+p)or p[len(p)*2%4]*f(n/p[1])

Test it on Ideone.

How it works

When f is called, it first computes 1/n. If the result is non-zero, n is 1 and f returns 1.

If n > 1, the following happens.

If n is not divisible by p[1] (initially 2), n%p[1] yields a truthy value and

  f(n,k+1,m*k,m*m%k*[k]+p)

gets called.

This branch generates prime number until the penultimate one evenly divides n. To do so, it uses the following corollary of Wilson's theorem.

At all times, m is equal to the factorial of k - 1 (initially 6 = 3! and 4. In each iteration, the result of m*m%k*[k] gets prepended to the list of primes p. By the corollary, m*m%k is 1 if k is prime and 0 if not, so this prepends k to p if and only if k is a prime number.

If n is divisible by p[1], n%p[1] yields 0 and

  p[len(p)*2%4]*f(n/p[1])

gets executed.

If p contains an even amount of prime numbers, len(p)*2%4 will yield 0 and the first multiplicand takes the value of p[0]. If p contains an odd amount of prime numbers, len(p)*2%4 will yield 2 and the first multiplicand takes the value of p[2].

In either case, this is the prime whose exponents has to get swapped with the one of p[1], so we divide n by p[1] (decreasing the exponent by 1) and multiply the result of f(n/p[1]) by the corresponding prime (increasing the exponent by 1).

Note that f(n/p[1]) resets k, m and p to their default values. f(n/p[1],k,m,p) would improve efficiency, at the cost of six extra bytes.


答:
Actually, 15 bytes

```<code>w`i;r♂Pí1^Pn`Mπ
</code>```

Try it online!

Explanation:

```<code>w`i;r♂Pí1^Pn`Mπ
w                prime factorization
 `          `M   map (for (p,e) in factorization):
  i;               flatten, make a copy of p
    r♂P            [prime[i] for i in range(p)]
       í           index (essentially the 0-based prime index of p)
        1^         XOR with 1
          P        prime[n]
           n       repeat e times
              π  product
</code>```

Title: Swap prime exponents with their neighbours

Body:
(Follow-up to my question about swapping bits with their neighbours.)

Task

Given a positive integer x = (2a · 3b) · (5c · 7d) · (11e · 13f) · …, print the integer obtained by swapping the exponents in this factorization for each successive pair of primes, y = (2b · 3a) · (5d · 7c) · (11f · 13e) · …

A061898 in the OEIS. This is code-golf, so the shortest program (in bytes) wins!

Test cases

```<code>1 -> 1
2 -> 3
3 -> 2
10 -> 21
37 -> 31
360 -> 756
12345 -> 11578
67895678 -> 125630871
</code>```

Body:
Actually, 15 bytes

w`i;r♂Pí1^Pn`Mπ

Try it online!

Explanation:

w`i;r♂Pí1^Pn`Mπ
w                prime factorization
 `          `M   map (for (p,e) in factorization):
  i;               flatten, make a copy of p
    r♂P            [prime[i] for i in range(p)]
       í           index (essentially the 0-based prime index of p)
        1^         XOR with 1
          P        prime[n]
           n       repeat e times
              π  product


答:
Actually, 16 bytes

```<code>4@¡"21""12"(t4@¿
</code>```

Try it online!

Explanation:

```<code>4@¡"21""12"(t4@¿
4@¡               base 4 representation of n
   "21""12"(t     translate (swap 1s and 2s)
             4@¿  base 4 to decimal
</code>```

Title: Swap bits with their neighbours

Body:
Task description

Given an integer, swap its (2k–1)-th and 2k-th least significant bits for all integers k > 0. This is sequence A057300 in the OEIS.

(The number is assumed to have “infinitely many” leading zeroes. In practice, this simply means prepending a single 0 bit to odd-length numbers.)

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

Test cases

```<code>0 -> 0
1 -> 2
9 -> 6
85 -> 170
220 -> 236
1827 -> 2835
47525 -> 30298
</code>```

Body:
Actually, 16 bytes

4@¡"21""12"(t4@¿

Try it online!

Explanation:

4@¡"21""12"(t4@¿
4@¡               base 4 representation of n
   "21""12"(t     translate (swap 1s and 2s)
             4@¿  base 4 to decimal


问:
Determine the winner of a game of War
The card game War is interesting in that the final outcome is entirely determined by the initial arrangement of the deck, so long as certain rules are followed for the order in which cards are picked up from the playing field and moved to decks. In this challenge, there will only be 2 players, simplifying things greatly.

The Game

Each player is dealt a deck of 26 cards.

Each player places the top card in their deck face-up. The player with the higher-ranking card (Ace > King > Queen > Jack > 10 > 9 > 8 > 7 > 6 > 5 > 4 > 3 > 2) wins the round, and places their card on top of their opponent's card, flips them over, and adds them to the bottom of their deck (so their winning card is on the bottom of the deck, and the other player's losing card is just above it). This is done until one of the players runs out of cards.

If the cards are of equal rank, then each player places the top 2 cards of their deck face-up on top of their previous card (so that the card that was on top of the deck is the second card in the stack, and the card that was second-from-top is on top). Then, the ranks (of the top card of each stack) are compared again, and the winner places their entire stack on top of the loser's entire stack, turns the stack upside-down, and places it on the bottom of their deck. If there is another tie, more cards are played in the same way, until a winner is chosen or one player runs out of cards.

If at any point one of the players needs to draw a card from their deck, but their deck is empty, they immediately lose the game.

The Challenge

Given two lists of cards in the players' decks, in any convenient format, output a truthy value if Player 1 wins, and a falsey value if Player 2 wins.

For convenience, a 10 card will be represented with a T, and face cards will be abbreviated (Ace -> A, King -> K, Queen -> Q, Jack -> J), so that all cards are one character long. Alternatively, ranks may be represented with decimal integers 2-14 (Jack -> 11, Queen -> 12, King -> 13, Ace -> 14) or hex digits 2-E (10 -> A, Jack -> B, Queen -> C, King -> D, Ace -> E). Since suits don't matter, suit information will not be given.

You may assume that all games will terminate at some point (though it may take a very long time), and one player will always run out of cards before the other.

Each player places cards simultaneously, and one card at a time, so there is never any ambiguity about which player ran out of cards first.

Test Cases

The test cases use 23456789ABCDE to represent the ranks (in ascending order).

```<code>D58B35926B92C7C4C7E8D3DAA2, 8E47C38A2DEA43467EB9566B95 -> False
669D9D846D4B3BA52452C2EDEB, E747CA988CC76723935A3B8EA5 -> False
5744B95ECDC6D325B28A782A72, 68394D9DA96EBBA8533EE7C6C4 -> True
87DB6C7EBC6C8D722389923DC6, E28435DBEBEA543AA47956594A -> False
589EAB9DCD43E9EC264A5726A8, 48DC2577BD68AB9335263B7EC4 -> True
E3698D7C46A739AE5BE2C49286, BB54B7D78954ED526A83C3CDA2 -> True
32298B5E785DC394467D5C9CB2, 5ED6AAD93E873EA628B6A4BC47 -> True
B4AB985B34756C624C92DE5E97, 3EDD5BA2A68397C26CE837AD48 -> False
9A6D9A5457BB6ACBC5E8D7D4A9, 73E658CE2C3E289B837422D463 -> True
96E64D226BC8B7D6C5974BAE32, 58DC7A8C543E35978AEBA34D29 -> True
C2978A35E74D7652BA9762C458, 9A9BB332BE8C8DD44CE3DE66A5 -> False
BEDB44E947693CD284923CEA82, 8CC3B75756255A683A6AB9E7DD -> False
EEDDCCBBAA8877665544332299, EEDDCCBBAA9988776655443322 -> False
EEDDCCBBAA9988776655443322, DDCCBBAA9988776655443E3E22 -> True
</code>```

Reference Implementation

This reference implementation is written in Python 3, and takes input in the same format as the test cases (except separated by a newline instead of a comma and a space).

#!/usr/bin/env python3

from collections import deque

p1, p2 = [deque(s) for s in (input(),input())]
print(''.join(p1))
print(''.join(p2))

try:
    while p1 and p2:
        p1s = [p1.popleft()]
        p2s = [p2.popleft()]
        while p1s[-1] == p2s[-1]:
            p1s.append(p1.popleft())
            p2s.append(p2.popleft())
            p1s.append(p1.popleft())
            p2s.append(p2.popleft())
        if p1s[-1] > p2s[-1]:
            p1.extend(p2s+p1s)
        else:
            p2.extend(p1s+p2s)
except IndexError:
    pass
finally:
    print(len(p1) > 0)
```

答:
JavaScript (ES6), 134 bytes

f=([p,...r],[q,...s],t=[],u=[],v)=>!q||p&&(v|p==q?f(r,s,[...t,p],[...u,q],!v):p>q?f([...r,...u,q,...t,p],s):f(r,[...s,...t,p,...u,q]))```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div oninput=o.checked=f(p.value,q.value)>
Player 1's cards: <input id=p><br>
Player 2's cards: <input id=q><br>
<input id=o type="checkbox"> Player 2 loses</code>```

Return undefined if Player 2 wins, true otherwise. Accepts comparable iterators, usually arrays of integers or strings of hex characters. Answer is composed of over 22% of . characters, which I think must be a record for me.

Title: Determine the winner of a game of War

Body:
JavaScript (ES6), 134 bytes

f=([p,...r],[q,...s],t=[],u=[],v)=>!q||p&&(v|p==q?f(r,s,[...t,p],[...u,q],!v):p>q?f([...r,...u,q,...t,p],s):f(r,[...s,...t,p,...u,q]))

<div oninput=o.checked=f(p.value,q.value)>
Player 1's cards: <input id=p><br>
Player 2's cards: <input id=q><br>
<input id=o type="checkbox"> Player 2 loses

Return undefined if Player 2 wins, true otherwise. Accepts comparable iterators, usually arrays of integers or strings of hex characters. Answer is composed of over 22% of . characters, which I think must be a record for me.