答:
Jelly, <s>10</s> <s>9</s> 7 bytes

```<code>b4d2UFḄ
</code>```

Try it online! or verify all test cases.

How it works

```<code>b4d2UFḄ  Main link. Argument: n (integer)

b4       Convert n to base 4.
  d2     Divmod each quaternary digit x by 2, yielding [x : 2, x % 2].
    U    Upend; reverse each pair, yielding [x % 2, x : 2].
     F   Flatten the 2D list of binary digits.
      Ḅ  Convert from binary to integer.
</code>```

Title: Swap bits with their neighbours

Body:
Jelly, <s>10</s> <s>9</s> 7 bytes

b4d2UFḄ

Try it online! or verify all test cases.

How it works

b4d2UFḄ  Main link. Argument: n (integer)

b4       Convert n to base 4.
  d2     Divmod each quaternary digit x by 2, yielding [x : 2, x % 2].
    U    Upend; reverse each pair, yielding [x % 2, x : 2].
     F   Flatten the 2D list of binary digits.
      Ḅ  Convert from binary to integer.


问:
N-uniquely additive sets
Remember that a set is unordered without duplicates.

Definition An N-uniquely additive set S whose length is K is a set such that all N-length subsets in S sum to different numbers. In other words, the sums of all the N-length subsets of S are all distinct.

Objective Given an array/set as input and a number N to a function or to a full program in any reasonable format, find and return or output a truthy or falsey value (erroring for falsey is okay) denoting whether or not the input is N-uniquely additive.

You may assume that each element only appears at most once and that each number is within your language's native datatype. If need be, you may also assume that the input is sorted. Last, you may assume that 0 < N <= K.

Examples

Let's consider the set S = {1, 2, 3, 5} and N = 2. Here are all the sums of all unique pairs over S (for the unique ones are the only ones of interest for sums):

```<code>1 + 2 = 3
1 + 3 = 4
1 + 5 = 6
2 + 3 = 5
2 + 5 = 7
3 + 5 = 8
</code>```

We can see that there are no duplicates in output, so S is 2-uniquely additive.

Let's now consider the set T = {12, 17, 44, 80, 82, 90} and N = 4. Here are all the possible sums of length four:

```<code>12 + 17 + 44 + 80 = 153
12 + 17 + 44 + 82 = 155
12 + 17 + 44 + 90 = 163
12 + 17 + 80 + 82 = 191
12 + 17 + 80 + 90 = 199
12 + 17 + 82 + 90 = 201
12 + 44 + 80 + 82 = 218
12 + 44 + 80 + 90 = 226
12 + 44 + 82 + 90 = 228
12 + 80 + 82 + 90 = 264
17 + 44 + 80 + 82 = 223
17 + 44 + 80 + 90 = 231
17 + 44 + 82 + 90 = 233
17 + 80 + 82 + 90 = 269
44 + 80 + 82 + 90 = 296
</code>```

They are all unique, and so T is 4-uniquely additive.

Test Cases

```<code>[members], N => output
[1, 4, 8], 1 => true
[1, 10, 42], 1 => true                ; all sets trivially satisfy N = 1
[1, 2, 3, 4], 3 => true
[1, 2, 3, 4, 5], 5 => true
[1, 2, 3, 5, 8], 3 => true
[1, 2, 3, 4, 5], 2 => false           ;  1 +  4       =  5 =        2 + 3
[-2, -1, 0, 1, 2], 3 => false         ; -2 + -1 + 2   = -1 =   -2 + 0 + 1
[1, 2, 3, 5, 8, 13], 3 => false       ;  1 +  2 + 13  = 16 =    3 + 5 + 8
[1, 2, 4, 8, 16, 32], 3 => true
[1, 2, 4, 8, 16, 32], 4 => true
[1, 2, 4, 8, 16, 32], 5 => true
[1, 2, 4, 8, 16, 32], 6 => true
[3, 4, 7, 9, 12, 16, 18], 6 => true
[3, 4, 7, 9, 12, 16, 18], 3 => false  ; 3 + 4 + 12 = 19 = 3 + 7 + 9
</code>```

答:
MATL, 7 bytes

```<code>XN!sSdA
</code>```

Try it online!

Returns true (displayed as 1) or false (displayed as 0).

```<code>XN   % Take array S and number N. Generate all combinations of elements from S
     % taken N at a time. Gives a 2D array where each combination is a row
!    % Transpose. Each combination is now a column
s    % Sum of each column: gives a row array. If N=1 computes the sum of
     % the only row, and so gives a number
S    % Sort vector
d    % Array of consecutive differences. For a single number gives an empty array
A    % True if all elements of the input array are nonzero (for an empty array
     % it also gives true)
</code>```

ContentLicense: CC BY-SA 3.0

Title: N-uniquely additive sets

Body:
MATL, 7 bytes

XN!sSdA

Try it online!

Returns true (displayed as 1) or false (displayed as 0).

XN   % Take array S and number N. Generate all combinations of elements from S
     % taken N at a time. Gives a 2D array where each combination is a row
!    % Transpose. Each combination is now a column
s    % Sum of each column: gives a row array. If N=1 computes the sum of
     % the only row, and so gives a number
S    % Sort vector
d    % Array of consecutive differences. For a single number gives an empty array
A    % True if all elements of the input array are nonzero (for an empty array
     % it also gives true)


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

答:
Javascript (ES6), <s>113</s> 109 bytes

Saved 4 bytes thanks to Upgoat

```<code>n=>+('0b'+/(..)+$/.exec('0'+n.toString`2`)[0].split``.reduce((p,c)=>p.length-1?[p.join(c)]:[p[0],c],[''])[0],2)
</code>```

How it works

```<code>n=>+('0b'+                              //parse as binary literal
    /(..)+$/.exec('0'+n.toString`2`)[0] //convert to binary string with an even number of digits
        .split``                        //convert to array
        .reduce((p,c)=>p.length-1?[p.join(c)]:[p[0],c],[''])
                                        //swap all numbers
)
</code>```

Title: Swap bits with their neighbours

Body:
Javascript (ES6), <s>113</s> 109 bytes

Saved 4 bytes thanks to Upgoat

n=>+('0b'+/(..)+$/.exec('0'+n.toString`2`)[0].split``.reduce((p,c)=>p.length-1?[p.join(c)]:[p[0],c],[''])[0],2)

How it works

n=>+('0b'+                              //parse as binary literal
    /(..)+$/.exec('0'+n.toString`2`)[0] //convert to binary string with an even number of digits
        .split``                        //convert to array
        .reduce((p,c)=>p.length-1?[p.join(c)]:[p[0],c],[''])
                                        //swap all numbers
)


答:
Jelly, 7 bytes

```<code>œcS€ṢIP
</code>```

Try it online!

Returns a positive number for truthy and zero for falsey.

```<code>œc       find combinations
  S€     sum each combination
    Ṣ    sort the sums
     I   find the difference between each pair of sums
           iff any sums are the same, this returns a list containing 0
      P  product of the elements of the resulting list
</code>```

Title: N-uniquely additive sets

Body:
Remember that a set is unordered without duplicates.

Definition An N-uniquely additive set S whose length is K is a set such that all N-length subsets in S sum to different numbers. In other words, the sums of all the N-length subsets of S are all distinct.

Objective Given an array/set as input and a number N to a function or to a full program in any reasonable format, find and return or output a truthy or falsey value (erroring for falsey is okay) denoting whether or not the input is N-uniquely additive.

You may assume that each element only appears at most once and that each number is within your language's native datatype. If need be, you may also assume that the input is sorted. Last, you may assume that 0 < N <= K.

Examples

Let's consider the set S = {1, 2, 3, 5} and N = 2. Here are all the sums of all unique pairs over S (for the unique ones are the only ones of interest for sums):

```<code>1 + 2 = 3
1 + 3 = 4
1 + 5 = 6
2 + 3 = 5
2 + 5 = 7
3 + 5 = 8
</code>```

We can see that there are no duplicates in output, so S is 2-uniquely additive.

Let's now consider the set T = {12, 17, 44, 80, 82, 90} and N = 4. Here are all the possible sums of length four:

```<code>12 + 17 + 44 + 80 = 153
12 + 17 + 44 + 82 = 155
12 + 17 + 44 + 90 = 163
12 + 17 + 80 + 82 = 191
12 + 17 + 80 + 90 = 199
12 + 17 + 82 + 90 = 201
12 + 44 + 80 + 82 = 218
12 + 44 + 80 + 90 = 226
12 + 44 + 82 + 90 = 228
12 + 80 + 82 + 90 = 264
17 + 44 + 80 + 82 = 223
17 + 44 + 80 + 90 = 231
17 + 44 + 82 + 90 = 233
17 + 80 + 82 + 90 = 269
44 + 80 + 82 + 90 = 296
</code>```

They are all unique, and so T is 4-uniquely additive.

Test Cases

```<code>[members], N => output
[1, 4, 8], 1 => true
[1, 10, 42], 1 => true                ; all sets trivially satisfy N = 1
[1, 2, 3, 4], 3 => true
[1, 2, 3, 4, 5], 5 => true
[1, 2, 3, 5, 8], 3 => true
[1, 2, 3, 4, 5], 2 => false           ;  1 +  4       =  5 =        2 + 3
[-2, -1, 0, 1, 2], 3 => false         ; -2 + -1 + 2   = -1 =   -2 + 0 + 1
[1, 2, 3, 5, 8, 13], 3 => false       ;  1 +  2 + 13  = 16 =    3 + 5 + 8
[1, 2, 4, 8, 16, 32], 3 => true
[1, 2, 4, 8, 16, 32], 4 => true
[1, 2, 4, 8, 16, 32], 5 => true
[1, 2, 4, 8, 16, 32], 6 => true
[3, 4, 7, 9, 12, 16, 18], 6 => true
[3, 4, 7, 9, 12, 16, 18], 3 => false  ; 3 + 4 + 12 = 19 = 3 + 7 + 9
</code>```

Body:
Jelly, 7 bytes

œcS€ṢIP

Try it online!

Returns a positive number for truthy and zero for falsey.

œc       find combinations
  S€     sum each combination
    Ṣ    sort the sums
     I   find the difference between each pair of sums
           iff any sums are the same, this returns a list containing 0
      P  product of the elements of the resulting list


答:
Haskell, 69 bytes

```<code>import Data.List
n#s=(==)=<<nub$[sum x|x<-subsequences s,length x==n]
</code>```

Usage example: 6 # [3,4,7,9,12,16,18] -> True.

Direct implementation of the definition: make a list of sums of all subsequences of length n and check if it equals itself with duplicates removed.

Title: N-uniquely additive sets

Body:
Haskell, 69 bytes

import Data.List
n#s=(==)=<<nub$[sum x|x<-subsequences s,length x==n]

Usage example: 6 # [3,4,7,9,12,16,18] -> True.

Direct implementation of the definition: make a list of sums of all subsequences of length n and check if it equals itself with duplicates removed.


答:
JavaScript (ES6), 132 bytes

```<code>(a,n)=>a.map(m=>{for(i=n;i--;)s[i].map(k=>s[i+1].push(m+k))},s=[...Array(n+1)].map(_=>[]),s[0]=[0])&&new Set(s[n]).size==s[n].length
</code>```

Builds up the additive lists from 1 to n and then checks the last one for uniqueness.

Title: N-uniquely additive sets

Body:
JavaScript (ES6), 132 bytes

(a,n)=>a.map(m=>{for(i=n;i--;)s[i].map(k=>s[i+1].push(m+k))},s=[...Array(n+1)].map(_=>[]),s[0]=[0])&&new Set(s[n]).size==s[n].length

Builds up the additive lists from 1 to n and then checks the last one for uniqueness.


答:
Python 2, 26 bytes

lambda n:2*n-3*(4**n/3&n/2)
```
<p>Bit tricks!</p>
<p>Say <code>n</code> has form <code>...ghfedcba</code> in binary. Then, we can split it into every other bit as</p>
```n   = o + 2*e
n   = ...hgfedcba
o   = ...0g0e0c0a
2*e = ...h0f0d0b0
```
<p>Then, the bit-switched result <code>s</code> can be expressed as <code>s=2*o+e</code>.</p>
```s   = 2*o + e
s   = ...ghefcdab
2*o = ...g0e0c0a0
e   = ...0h0f0d0b
```
<p>We'd rather compute only one of <code>e</code> and <code>o</code>, so we express <code>o=n-2*e</code> and substitute</p>
```s=2*(n-2*e)+e = 2*n-3*e
```
<p>So, now it remains to express <code>e</code> in terms of <code>n</code>. The number <code>M=4**n/3</code> has form <code>...10101010101</code> in binary, which serves as a mask for the odd digits. The exponent <code>n</code> ensures that <code>M</code> is long enough. Taking the bitwise <code>and</code> of <code>n/2</code> and this value gives <code>e</code> as desired.</p>
```n/2     = ...hgfedcb
M       = ...1010101
n/2 & M = ...h0f0d0b = e
```
<p>We can instead express <code>e</code> in terms of <code>o</code> <code>e=(n-o)/2</code>, which gives <code>s=(n+o*3)/2</code>, which saves a byte thanks to an optimization from xsot.</p>
<pre class="lang-python prettyprint-override"><code>lambda n:n+(n&4**n/3)*3>>1
</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:
Python 2, 26 bytes

lambda n:2*n-3*(4**n/3&n/2)

Bit tricks!

Say n has form ...ghfedcba in binary. Then, we can split it into every other bit as

n   = o + 2*e
n   = ...hgfedcba
o   = ...0g0e0c0a
2*e = ...h0f0d0b0

Then, the bit-switched result s can be expressed as s=2*o+e.

s   = 2*o + e
s   = ...ghefcdab
2*o = ...g0e0c0a0
e   = ...0h0f0d0b

We'd rather compute only one of e and o, so we express o=n-2*e and substitute

s=2*(n-2*e)+e = 2*n-3*e

So, now it remains to express e in terms of n. The number M=4**n/3 has form ...10101010101 in binary, which serves as a mask for the odd digits. The exponent n ensures that M is long enough. Taking the bitwise and of n/2 and this value gives e as desired.

n/2     = ...hgfedcb
M       = ...1010101
n/2 & M = ...h0f0d0b = e

We can instead express e in terms of o e=(n-o)/2, which gives s=(n+o*3)/2, which saves a byte thanks to an optimization from xsot.

lambda n:n+(n&4**n/3)*3>>1


答:
JavaScript (ES6), <s>32</s> 30 bytes

```<code>(n,m=0x55555555)=>n*2&~m|n/2&m
</code>```

Only works up to 1073741823 due to the limitations of JavaScript's integers. <s>38</s> 36 bytes works up to 4294967295:

```<code>(n,m=0x55555555)=>(n*2&~m|n/2&m)>>>0
</code>```

Edit: Saved 2 bytes thanks to @user81655.

51 bytes works up to 4503599627370495:

```<code>n=>parseInt(n.toString(4).replace(/1|2/g,n=>3-n),4)
</code>```

Title: Swap bits with their neighbours

Body:
JavaScript (ES6), <s>32</s> 30 bytes

(n,m=0x55555555)=>n*2&~m|n/2&m

Only works up to 1073741823 due to the limitations of JavaScript's integers. <s>38</s> 36 bytes works up to 4294967295:

(n,m=0x55555555)=>(n*2&~m|n/2&m)>>>0

Edit: Saved 2 bytes thanks to @user81655.

51 bytes works up to 4503599627370495:

n=>parseInt(n.toString(4).replace(/1|2/g,n=>3-n),4)


答:
C function, 38

Bit-twiddling:

f(x){return(x&~0U/3*2)/2+(x&~0U/3)*2;}
```
<p>Ideone.</p>
<hr />
<p>Or for the fun of it:</p>
<h1>C recursive function, 43</h1>
<p>As per the OEIS formula, <code>a(4n+k) = 4a(n) + a(k), 0 <= k <= 3</code></p>
<pre class="lang-c prettyprint-override"><code>f(x){return x>3?4*f(x/4)+f(x%4):x%3?3-x:x;}
</code>```

or

f(x){return x>3?4*f(x/4)+f(x%4):x%2*2+x/2;}
```

Ideone.

Title: Swap bits with their neighbours

Body:
C function, 38

Bit-twiddling:

f(x){return(x&~0U/3*2)/2+(x&~0U/3)*2;}

Ideone.

Or for the fun of it:

C recursive function, 43

As per the OEIS formula, a(4n+k) = 4a(n) + a(k), 0 <= k <= 3

f(x){return x>3?4*f(x/4)+f(x%4):x%3?3-x:x;}

or

f(x){return x>3?4*f(x/4)+f(x%4):x%2*2+x/2;}

Ideone.


答:
Retina, 70 bytes

```
.+
$*
+`(1+)\1
$1x
x1
1
^
x
r`(.)(.)
$2$1
1
x@
+`@x
x@@
x*(@*)
$.1
0$

```

Test suite. (Slightly modified.)

Well, just for fun: 7 bytes

```<code>T`12`21
</code>```

Takes base-4 as input, and outputs as base-4.

Try it online!

Title: Swap bits with their neighbours

Body:
Retina, 70 bytes

.+
$*
+`(1+)\1
$1x
x1
1
^
x
r`(.)(.)
$2$1
1
x@
+`@x
x@@
x*(@*)
$.1
0$

Test suite. (Slightly modified.)

Well, just for fun: 7 bytes

T`12`21

Takes base-4 as input, and outputs as base-4.

Try it online!


答:
J, 34 bytes

```<code>load'stats'
[:*/@~:[:+/"1(comb#){]
</code>```

Straight-forward approach, only requires the stats add-on for the comb function. Returns 0 for false and 1 for true.

As an alternative to using the comb builtin, there is a 38 byte solution that generates the power set and chooses the subsets of size n.

```<code>[:*/@~:(>@{[:(</.~+/"1)2#:@i.@^#)+/@#]
</code>```

Usage

```<code>   f =: [:*/@~:[:+/"1(comb#){]
   2 f 1 2 3 5
1
   4 f 12 17 44 80 82 90
1
   3 f _2 _1 0 1 2
0
   6 f 3 4 7 9 12 16 18
1
   3 f 3 4 7 9 12 16 18
0
</code>```

Title: N-uniquely additive sets

Body:
J, 34 bytes

load'stats'
[:*/@~:[:+/"1(comb#){]

Straight-forward approach, only requires the stats add-on for the comb function. Returns 0 for false and 1 for true.

As an alternative to using the comb builtin, there is a 38 byte solution that generates the power set and chooses the subsets of size n.

[:*/@~:(>@{[:(</.~+/"1)2#:@i.@^#)+/@#]

Usage

   f =: [:*/@~:[:+/"1(comb#){]
   2 f 1 2 3 5
1
   4 f 12 17 44 80 82 90
1
   3 f _2 _1 0 1 2
0
   6 f 3 4 7 9 12 16 18
1
   3 f 3 4 7 9 12 16 18
0


答:
Julia, <s>46</s> 41 bytes

x\n=(t=map(sum,combinations(x,n)))==t∪t
```

Try it online!

How it works

This (re)defines the binary operator \ for Array/Int arguments.

combinations(x,n) returns all arrays of exactly n different elements of x. We map sum over these arrays and store the result in t.

t∪t performs the set union of the array t with itself, which works like the longer unique in this case.

Finally, we compare t with the deduplicated t, returning true if and only if all sums are different.

Title: N-uniquely additive sets

Body:
Julia, <s>46</s> 41 bytes

x\n=(t=map(sum,combinations(x,n)))==t∪t

<a href="http://julia.tryitonline.net/#code=eFxuPSh0PW1hcChzdW0sY29tYmluYXRpb25zKHgsbikpKT09dOKIqnQKCmZvciAoeCwgbikgaW4gKAogICAgKFsxLCA0LCA4XSwgMSksCiAgICAoWzEsIDEwLCA0Ml0sIDEpLAogICAgKFsxLCAyLCAzLCA0XSwgMyksCiAgICAoWzEsIDIsIDMsIDQsIDVdLCA1KSwKICAgIChbMSwgMiwgMywgNSwgOF0sIDMpLAogICAgKFsxLCAyLCAzLCA0LCA1XSwgMiksCiAgICAoWy0yLCAtMSwgMCwgMSwgMl0sIDMpLAogICAgKFsxLCAyLCAzLCA1LCA4LCAxM10sIDMpLAogICAgKFsxLCAyLCA0LCA4LCAxNiwgMzJdLCAzKSwKICAgIChbMSwgMiwgNCwgOCwgMTYsIDMyXSwgNCksCiAgICAoWzEsIDIsIDQsIDgsIDE2LCAzMl0sIDUpLAogICAgKFsxLCAyLCA0LCA4LCAxNiwgMzJdLCA2KSwKICAgIChbMywgNCwgNywgOSwgMTIsIDE2LCAxOF0sIDYpLAogICAgKFszLCA0LCA3LCA5LCAxMiwgMTYsIDE4XSwgMykKKQogICAgcHJpbnRsbih4XG4pCmVuZA&input=" rel="nofollow">Try it online!

How it works

This (re)defines the binary operator \ for Array/Int arguments.

combinations(x,n) returns all arrays of exactly n different elements of x. We map sum over these arrays and store the result in t.

t∪t performs the set union of the array t with itself, which works like the longer unique in this case.

Finally, we compare t with the deduplicated t, returning true if and only if all sums are different.


答:
Python, 89 bytes

from itertools import*
lambda s,n,c=combinations:all(x^y for x,y in c(map(sum,c(s,n)),2))
```

Test it on Ideone.

How it works

c(s,n) lists all n-combinations of s, i.e., all lists of n different elements of s. We map sum over the resulting lists, thus computing all possible sums of sublists of length n.

After wards, we use c(...,2) to create all pairs of the resulting sums. If any two sums x and y are equal, x^y will return 0 and all will return False. Conversely, if all sums are unique, x^y will always be truthy, and any will return True.

Title: N-uniquely additive sets

Body:
Python, 89 bytes

from itertools import*
lambda s,n,c=combinations:all(x^y for x,y in c(map(sum,c(s,n)),2))

Test it on Ideone.

How it works

c(s,n) lists all n-combinations of s, i.e., all lists of n different elements of s. We map sum over the resulting lists, thus computing all possible sums of sublists of length n.

After wards, we use c(...,2) to create all pairs of the resulting sums. If any two sums x and y are equal, x^y will return 0 and all will return False. Conversely, if all sums are unique, x^y will always be truthy, and any will return True.


Title: Display "Happy Easter!"

Body:
Your task is to print the following ASCII Art:

```<code> _     _                            _______                           _
| |   | |                          (_______)          _              | |
| |__ | | ____ ____  ____  _   _    _____   ____  ___| |_  ____  ____| |
|  __)| |/ _  |  _ \|  _ \| | | |  |  ___) / _  |/___)  _)/ _  )/ ___)_|
| |   | ( ( | | | | | | | | |_| |  | |____( ( | |___ | |_( (/ /| |    _
|_|   |_|\_||_| ||_/| ||_/ \__  |  |_______)_||_(___/ \___)____)_|   |_|
              |_|   |_|   (____/
</code>```

Remember, this is code-golf, so the code with the smallest amount of bytes wins.
Good luck.

Body:
Python 2, <s>343</s> <s>328</s> 316 bytes

This solution uses no decompression functions or other imports.

o=""
for i in range(250):j=ord(")*I*yyQZyyI*(!+9!+yyA,Z-q*y9!+(!+2)!!B)B1B1*9*AJ9B1:!+*1B1B!+(+12-!+/)*1+1*).+1*).!!!+1+1:-)/)*1+/:-1*-/)*1-/):-*+(!+9!,),)!!!!!!!!+*!+1!+B,),)!+:)!+*,),/)/!+A*(+*+9+*+.*3*!3*/!3*/).21+1+Z-*3*,:/).:-B-*+9+*+(y9+*+9+*+9,B/(".replace("!","+)")[i])-40;o+="\n _|()\/"[j&7]*(j/8+1)
print o

Readable version:

DATA=(")*I*yyQZyyI*("
"!+9!+yyA,Z-q*y9!+("
"!+2)!!B)B1B1*9*AJ9B1:!+*1B1B!+("
"+12-!+/)*1+1*).+1*).!!!+1+1:-)/)*1+/:-1*-/)*1-/):-*+("
"!+9!,),)!!!!!!!!+*!+1!+B,),)!+:)!+*,),/)/!+A*("
"+*+9+*+.*3*!3*/!3*/).21+1+Z-*3*,:/).:-B-*+9+*+("
"y9+*+9+*+9,B/(").replace("!","+)")
SIZE=250
o=""
for i in range(SIZE):
 j=ord(DATA[i])-40
 o+="\n _|()\/"[j&7]*(j/8+1)
print o

Uses a version of run length encoding with 3 bits for a symbol from the set "\n _|()/".  The remainder of the byte is the length, but I have limited the length to 10 and manipulated it so that the results are printable characters that are valid in a python string without any escaping.

Replacing the string corresponding with "| " with a single character in the encoded data saves a few more bytes.

I removed the trailing spaces on lines 1 and 5, which may be bending the rules a bit, but seems practical.

This program generates the packed data:

message="""
 _     _                            _______                           _
| |   | |                          (_______)          _              | |
| |__ | | ____ ____  ____  _   _    _____   ____  ___| |_  ____  ____| |
|  __)| |/ _  |  _ \|  _ \| | | |  |  ___) / _  |/___)  _)/ _  )/ ___)_|
| |   | ( ( | | | | | | | | |_| |  | |____( ( | |___ | |_( (/ /| |    _
|_|   |_|\_||_| ||_/| ||_/ \__  |  |_______)_||_(___/ \___)____)_|   |_|
              |_|   |_|   (____/"""[1:]
size=len(message)
symbols="\n _|()\/"
i=0
encoded=""
while i<size:
    count=0
    while count<10 and i+count+1<size and message[i+count+1]==message[i]:
        count+=1
    n = symbols.find(message[i]) | count<<3
    encoded+=chr(n+40)
    i+=count+1
encoded_lines = encoded.replace("+)","!").split(chr(40))
for line in encoded_lines:
    print line+chr(40)
print len(encoded)


问:
Tips for golfing in Pyth
Pyth is a Python-inspired procedural programming language, created by PPCG user isaacg.

What general tips do you have for golfing in Pyth? I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to Pyth.

One tip per answer, please.

答:
Finding the maximum of two integers

```<code>g#
</code>```

For instance, suppose you have J=5 and K=12. Then g#JK = 12, and g#KJ = 12 as well.

This was discovered by @Pietu1998, who put it this way:

Not sure if someone has already found it, but there's a cool way to do max(A, B) in 2 bytes, no need to use 3 for eS,AB. g#AB does the same thing. (It's very inefficient, though, since it loops max(1, A-B+1) times. An optimization is to put the number likely to be larger as B.)

Title: Tips for golfing in Pyth

Body:
Finding the maximum of two integers

g#

For instance, suppose you have J=5 and K=12. Then g#JK = 12, and g#KJ = 12 as well.

This was discovered by @Pietu1998, who put it this way:

Not sure if someone has already found it, but there's a cool way to do max(A, B) in 2 bytes, no need to use 3 for eS,AB. g#AB does the same thing. (It's very inefficient, though, since it loops max(1, A-B+1) times. An optimization is to put the number likely to be larger as B.)

ContentLicense: CC BY-SA 4.0


问:
Has My Pie Been Bisected?
Write a program or function that takes in a nonempty list of positive integers. You may assume it is input in a reasonable convenient format such as "1 2 3 4" or [1, 2, 3, 4].

The numbers in the input list represent the slices of a full pie chart where each slice size is proportional to its corresponding number and all slices are arranged around the chart in the order given.

For example, the pie for 1 2 3 4 is:

The question your code must answer is: Is the pie chart ever bisected? That is, is there ever a perfectly straight line from one side of the circle to the other, splitting it symmetrically in two?

You need to output a truthy value if there is at least one bisector and output a falsy value if there are none.

In the 1 2 3 4 example there is a bisection between 4 1 and 2 3 so the output would be truthy.

But for input 1 2 3 4 5 there is no bisector so the output would be falsy:

Additional Examples

Arranging numbers differently may remove bisectors.

e.g. 2 1 3 4 → falsy:

If only one number is in the input list the pie is not bisected.

e.g. 10 → falsy:

There may be multiple bisectors. As long as there are more than zero the output is truthy.

e.g. 6 6 12 12 12 11 1 12 → truthy: (there are 3 bisectors here)

Bisections may exist even if they are not visually obvious.

e.g. 1000000 1000001 → falsy:

e.g. 1000000 1000001 1 → truthy:

(Thanks to nces.ed.gov for generating the pie charts.)

Test Cases

```<code>Truthy
1 2 3 4
6 6 12 12 12 11 1 12
1000000 1000001 1
1 2 3
1 1
42 42
1 17 9 13 2 7 3
3 1 2
10 20 10

Falsy
1 2 3 4 5
2 1 3 4
10
1000000 1000001
1
1 2
3 1 1
1 2 1 2 1 2
10 20 10 1
</code>```

Scoring

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

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

```<code>Ḥ+\©_Sf®
</code>```

Return a non-empty list (truthy) or an empty list (falsy). Try it online! or verify all test cases.

How it works

```<code>Ḥ+\©_Sf®  Main link. Argument: A (list)

Ḥ         Double all integers in A.
 +\       Take the cumulative sum of 2A.
   ©      Copy; store the result in the register.
    _S    Subtract the sum of A from each partial sum of 2A.
      f®  Filter; intersect this list with the list in the register.
</code>```

Title: Has My Pie Been Bisected?

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

Ḥ+\©_Sf®

Return a non-empty list (truthy) or an empty list (falsy). Try it online! or verify all test cases.

How it works

Ḥ+\©_Sf®  Main link. Argument: A (list)

Ḥ         Double all integers in A.
 +\       Take the cumulative sum of 2A.
   ©      Copy; store the result in the register.
    _S    Subtract the sum of A from each partial sum of 2A.
      f®  Filter; intersect this list with the list in the register.


答:
J, 20 bytes

```<code>4#.0 2 1 3{~4#.^:_1]
</code>```

Usage

```<code>>> f =: 4#.0 2 1 3{~4#.^:_1]
>> f 85
<< 170
</code>```

Where >> is STDIN and << is STDOUT.

Ungolfed

```<code>to_base   =: 4 #.^:_1 ]
transpose =: 0 2 1 3 {~ to_base
from_base =: 4 #. transpose
</code>```

Three forks.

Sidenote

In the official interpreter, ^:_1 can be replaced by inv, saving 1 byte.

However, none of the online interpreters implement this.

Title: Swap bits with their neighbours

Body:
J, 20 bytes

4#.0 2 1 3{~4#.^:_1]

Usage

>> f =: 4#.0 2 1 3{~4#.^:_1]
>> f 85
<< 170

Where >> is STDIN and << is STDOUT.

Ungolfed

to_base   =: 4 #.^:_1 ]
transpose =: 0 2 1 3 {~ to_base
from_base =: 4 #. transpose

Three forks.

Sidenote

In the official interpreter, ^:_1 can be replaced by inv, saving 1 byte.

However, none of the online interpreters implement this.


答:
Julia, <s>34</s> <s>30</s> 29 bytes

```<code>!x=sum(x)∈cumsum!(x,2x).-x'
</code>```

Thanks to @GlenO for golfing off 1 byte!

Try it online!

How it works

After storing the cumulative sum of 2x in x, we subtract the row vector x' from the column vector x, yielding the matrix of all possible differences. Essentially, this computes the sums of all adjacent subarrays of x that do not contain the first value, their negatives, and 0's in the diagonal.

Finally, we test if the sum of the original array x belongs to the generated matrix. If this is the case, the sum of at least one of the adjacent sublists is equal to exactly halve of the sum of the entire list, meaning that there is at least one bisector.

Title: Has My Pie Been Bisected?

Body:
Write a program or function that takes in a nonempty list of positive integers. You may assume it is input in a reasonable convenient format such as "1 2 3 4" or [1, 2, 3, 4].

The numbers in the input list represent the slices of a full pie chart where each slice size is proportional to its corresponding number and all slices are arranged around the chart in the order given.

For example, the pie for 1 2 3 4 is:

The question your code must answer is: Is the pie chart ever bisected? That is, is there ever a perfectly straight line from one side of the circle to the other, splitting it symmetrically in two?

You need to output a truthy value if there is at least one bisector and output a falsy value if there are none.

In the 1 2 3 4 example there is a bisection between 4 1 and 2 3 so the output would be truthy.

But for input 1 2 3 4 5 there is no bisector so the output would be falsy:

Additional Examples

Arranging numbers differently may remove bisectors.

e.g. 2 1 3 4 → falsy:

If only one number is in the input list the pie is not bisected.

e.g. 10 → falsy:

There may be multiple bisectors. As long as there are more than zero the output is truthy.

e.g. 6 6 12 12 12 11 1 12 → truthy: (there are 3 bisectors here)

Bisections may exist even if they are not visually obvious.

e.g. 1000000 1000001 → falsy:

e.g. 1000000 1000001 1 → truthy:

(Thanks to nces.ed.gov for generating the pie charts.)

Test Cases

```<code>Truthy
1 2 3 4
6 6 12 12 12 11 1 12
1000000 1000001 1
1 2 3
1 1
42 42
1 17 9 13 2 7 3
3 1 2
10 20 10

Falsy
1 2 3 4 5
2 1 3 4
10
1000000 1000001
1
1 2
3 1 1
1 2 1 2 1 2
10 20 10 1
</code>```

Scoring

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

Body:
Julia, <s>34</s> <s>30</s> 29 bytes

!x=sum(x)∈cumsum!(x,2x).-x'

Thanks to @GlenO for golfing off 1 byte!

<a href="http://julia.tryitonline.net/#code=IXg9eHw-c3Vt4oiIKHQ9Mnh8PmN1bXN1bSkuLXQnCgpmb3IgeCBpbiAoCiAgICBbMSwyLDMsNF0sCiAgICBbNiw2LDEyLDEyLDEyLDExLDEsMTJdLAogICAgWzEwMDAwMDAsMTAwMDAwMSwxXSwKICAgIFsxLDIsM10sCiAgICBbMSwxXSwKICAgIFs0Miw0Ml0sCiAgICBbMSwxNyw5LDEzLDIsNywzXSwKICAgIFszLDEsMl0sCiAgICBbMTAsMjAsMTBdLAogICAgWzEsMiwzLDQsNV0sCiAgICBbMiwxLDMsNF0sCiAgICBbMTBdLAogICAgWzEwMDAwMDAsMTAwMDAwMV0sCiAgICBbMV0sCiAgICBbMSwyXSwKICAgIFszLDEsMV0sCiAgICBbMSwyLDEsMiwxLDJdLAogICAgWzEwLDIwLDEwLDFdCikKICAgIHByaW50bG4oIXgpCmVuZA&input=" rel="nofollow">Try it online!

How it works

After storing the cumulative sum of 2x in x, we subtract the row vector x' from the column vector x, yielding the matrix of all possible differences. Essentially, this computes the sums of all adjacent subarrays of x that do not contain the first value, their negatives, and 0's in the diagonal.

Finally, we test if the sum of the original array x belongs to the generated matrix. If this is the case, the sum of at least one of the adjacent sublists is equal to exactly halve of the sum of the entire list, meaning that there is at least one bisector.


答:
Pyth, <s>10</s> 9 bytes

```<code>}sQmysd.:
</code>```

Test it in the Pyth Compiler.

How it works

```<code>       .:  Generate the list of all adjacent sublists.
   m       Map over the result:
     sd       Add the integers of the sublist.
    y         Double the sum.
 sQ        Compute the sum of the input.
}          Check if it belongs to the list of doubled sublist sums.
</code>```

Title: Has My Pie Been Bisected?

Body:
Pyth, <s>10</s> 9 bytes

}sQmysd.:

Test it in the <a href="https://pyth.herokuapp.com/?code=%7DsQmysd.%3A&test_suite=1&test_suite_input=%5B1%2C+2%2C+3%2C+4%5D%0A%5B6%2C+6%2C+12%2C+12%2C+12%2C+11%2C+1%2C+12%5D%0A%5B1000000%2C+1000001%2C+1%5D%0A%5B1%2C+2%2C+3%5D%0A%5B1%2C+1%5D%0A%5B42%2C+42%5D%0A%5B1%2C+17%2C+9%2C+13%2C+2%2C+7%2C+3%5D%0A%5B3%2C+1%2C+2%5D%0A%5B10%2C+20%2C+10%5D%0A%5B1%2C+2%2C+3%2C+4%2C+5%5D%0A%5B2%2C+1%2C+3%2C+4%5D%0A%5B10%5D%0A%5B1000000%2C+1000001%5D%0A%5B1%5D%0A%5B1%2C+2%5D%0A%5B3%2C+1%2C+1%5D%0A%5B1%2C+2%2C+1%2C+2%2C+1%2C+2%5D%0A%5B10%2C+20%2C+10%2C+1%5D&debug=0" rel="nofollow">Pyth Compiler.

How it works

       .:  Generate the list of all adjacent sublists.
   m       Map over the result:
     sd       Add the integers of the sublist.
    y         Double the sum.
 sQ        Compute the sum of the input.
}          Check if it belongs to the list of doubled sublist sums.


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

答:
If you need to compare many different values to a single one, it may be more space-efficient to use a switch with a single case.

```<code>if x==1||x==2||x==3||x==4{}
switch x{case 1,2,3,4:}
</code>```

Title: Tips for Golfing in Go

Body:
If you need to compare many different values to a single one, it may be more space-efficient to use a switch with a single case.

if x==1||x==2||x==3||x==4{}
switch x{case 1,2,3,4:}


答:
Brachylog, 20 bytes

```<code>:1f:+aLdL
[L:I]hs.lI
</code>```

Expects a list containing the list and then the integer as Input, and no Output, e.g. run_from_atom(':{[L:I]hs.lI}f:+aLdL', [[1:2:3:5]:2])..

Explanation

Main Predicate

```<code>           Input = [A:I]
:1f        Find all ordered subsets of A of length I
   :+aL    Apply summing to each element of that list of subsets. Call that L
       dL  True if L minus all duplicate elements is still L
</code>```

Predicate 1: Find all ordered subsets of fixed length of a list

```<code>[L:I]      Input = [L:I]
     hs.   Unify Output with an ordered subset of L
        lI True if I is the length of Output
</code>```

Title: N-uniquely additive sets

Body:
Remember that a set is unordered without duplicates.

Definition An N-uniquely additive set S whose length is K is a set such that all N-length subsets in S sum to different numbers. In other words, the sums of all the N-length subsets of S are all distinct.

Objective Given an array/set as input and a number N to a function or to a full program in any reasonable format, find and return or output a truthy or falsey value (erroring for falsey is okay) denoting whether or not the input is N-uniquely additive.

You may assume that each element only appears at most once and that each number is within your language's native datatype. If need be, you may also assume that the input is sorted. Last, you may assume that 0 < N <= K.

Examples

Let's consider the set S = {1, 2, 3, 5} and N = 2. Here are all the sums of all unique pairs over S (for the unique ones are the only ones of interest for sums):

```<code>1 + 2 = 3
1 + 3 = 4
1 + 5 = 6
2 + 3 = 5
2 + 5 = 7
3 + 5 = 8
</code>```

We can see that there are no duplicates in output, so S is 2-uniquely additive.

Let's now consider the set T = {12, 17, 44, 80, 82, 90} and N = 4. Here are all the possible sums of length four:

```<code>12 + 17 + 44 + 80 = 153
12 + 17 + 44 + 82 = 155
12 + 17 + 44 + 90 = 163
12 + 17 + 80 + 82 = 191
12 + 17 + 80 + 90 = 199
12 + 17 + 82 + 90 = 201
12 + 44 + 80 + 82 = 218
12 + 44 + 80 + 90 = 226
12 + 44 + 82 + 90 = 228
12 + 80 + 82 + 90 = 264
17 + 44 + 80 + 82 = 223
17 + 44 + 80 + 90 = 231
17 + 44 + 82 + 90 = 233
17 + 80 + 82 + 90 = 269
44 + 80 + 82 + 90 = 296
</code>```

They are all unique, and so T is 4-uniquely additive.

Test Cases

```<code>[members], N => output
[1, 4, 8], 1 => true
[1, 10, 42], 1 => true                ; all sets trivially satisfy N = 1
[1, 2, 3, 4], 3 => true
[1, 2, 3, 4, 5], 5 => true
[1, 2, 3, 5, 8], 3 => true
[1, 2, 3, 4, 5], 2 => false           ;  1 +  4       =  5 =        2 + 3
[-2, -1, 0, 1, 2], 3 => false         ; -2 + -1 + 2   = -1 =   -2 + 0 + 1
[1, 2, 3, 5, 8, 13], 3 => false       ;  1 +  2 + 13  = 16 =    3 + 5 + 8
[1, 2, 4, 8, 16, 32], 3 => true
[1, 2, 4, 8, 16, 32], 4 => true
[1, 2, 4, 8, 16, 32], 5 => true
[1, 2, 4, 8, 16, 32], 6 => true
[3, 4, 7, 9, 12, 16, 18], 6 => true
[3, 4, 7, 9, 12, 16, 18], 3 => false  ; 3 + 4 + 12 = 19 = 3 + 7 + 9
</code>```

Body:
Brachylog, 20 bytes

:1f:+aLdL
[L:I]hs.lI

Expects a list containing the list and then the integer as Input, and no Output, e.g. run_from_atom(':{[L:I]hs.lI}f:+aLdL', [[1:2:3:5]:2])..

Explanation

Main Predicate

           Input = [A:I]
:1f        Find all ordered subsets of A of length I
   :+aL    Apply summing to each element of that list of subsets. Call that L
       dL  True if L minus all duplicate elements is still L

Predicate 1: Find all ordered subsets of fixed length of a list

[L:I]      Input = [L:I]
     hs.   Unify Output with an ordered subset of L
        lI True if I is the length of Output


答:
Python 2, <s>76</s> <s>74</s> <s>70</s> 66 bytes

def f(x):n=sum(x);print n in[2*sum(x[k/n:k%n])for k in range(n*n)]
```

Thanks to @xnor for golfing off <s>4</s> 8 bytes!

Test it on Ideone. (larger test cases excluded)

Title: Has My Pie Been Bisected?

Body:
Python 2, <s>76</s> <s>74</s> <s>70</s> 66 bytes

def f(x):n=sum(x);print n in[2*sum(x[k/n:k%n])for k in range(n*n)]

Thanks to @xnor for golfing off <s>4</s> 8 bytes!

Test it on Ideone. (larger test cases excluded)


答:
J, 18 bytes

5 bytes thanks to Dennis.

```<code>+/e.[:,/2*+/\-/+/\
</code>```

@HelkaHomba: Nope.

Usage

```<code>>> f =: +/e.[:,/2*+/\-/+/\
>> f 6 6 12 12 12 11 1 12
<< 4
>> f 10 20 10 1
<< 0
</code>```

Ungolfed

```<code>black_magic  =: +/\-/+/\
doubled_bm   =: 2 * black_magic
flatten      =: ,/
sum          =: +/
is_member_of =: e.
f =: sum is_member_of monadic flatten doubled_bm
</code>```

Previous 23-byte version:

```<code>[:+/[:+/+/=+:@-/~@(+/\)
</code>```

Usage

```<code>>> f =: [:+/[:+/+/=+:@-/~@(+/\)
>> f 6 6 12 12 12 11 1 12
<< 4
>> f 10 20 10 1
<< 0
</code>```

Ungolfed

```<code>black_magic =: -/~@(+/\)
double      =: +:
equals      =: =
sum         =: +/
monadic     =: [:
of          =: @
f =: monadic sum monadic sum (sum equals double of black_magic)
</code>```

Explanation

The sum of all substrings is calculated by the black_magic. The +/\ calculate the partial sums.

For example, a b c d becomes a a+b a+b+c a+b+c+d.

The -/~ then constructs a subtraction table based on the input, so x y z becomes:

```<code>x-x x-y x-z
y-x y-y y-z
z-x z-y z-z
</code>```

When applied to a a+b a+b+c a+b+c+d, the result would be:

```<code>    0  -b -b-c -b-c-d
    b   0   -c   -c-d
  b+c   c    0     -d
b+c+d c+d    d      0
</code>```

This calculated the sums of all the substrings which does not contain a.

This guarantees to be enough, since if one bisection contains a, the other bisection will not contain a and also will not wrap around.

Title: Has My Pie Been Bisected?

Body:
J, 18 bytes

5 bytes thanks to Dennis.

+/e.[:,/2*+/\-/+/\

@HelkaHomba: Nope.

Usage

>> f =: +/e.[:,/2*+/\-/+/\
>> f 6 6 12 12 12 11 1 12
<< 4
>> f 10 20 10 1
<< 0

Ungolfed

black_magic  =: +/\-/+/\
doubled_bm   =: 2 * black_magic
flatten      =: ,/
sum          =: +/
is_member_of =: e.
f =: sum is_member_of monadic flatten doubled_bm

Previous 23-byte version:

[:+/[:+/+/=+:@-/~@(+/\)

Usage

>> f =: [:+/[:+/+/=+:@-/~@(+/\)
>> f 6 6 12 12 12 11 1 12
<< 4
>> f 10 20 10 1
<< 0

Ungolfed

black_magic =: -/~@(+/\)
double      =: +:
equals      =: =
sum         =: +/
monadic     =: [:
of          =: @
f =: monadic sum monadic sum (sum equals double of black_magic)

Explanation

The sum of all substrings is calculated by the black_magic. The +/\ calculate the partial sums.

For example, a b c d becomes a a+b a+b+c a+b+c+d.

The -/~ then constructs a subtraction table based on the input, so x y z becomes:

x-x x-y x-z
y-x y-y y-z
z-x z-y z-z

When applied to a a+b a+b+c a+b+c+d, the result would be:

    0  -b -b-c -b-c-d
    b   0   -c   -c-d
  b+c   c    0     -d
b+c+d c+d    d      0

This calculated the sums of all the substrings which does not contain a.

This guarantees to be enough, since if one bisection contains a, the other bisection will not contain a and also will not wrap around.


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

答:
Ruby 2.3, <s>143</s> <s>145</s> <s>148</s> 149  bytes

Ruby has all these little quirks in how zip works with different-length arrays and map with multi-argument functions, making this pretty fun to golf down.

```<code>f=->x,y{d=->a{-~(a.map(&d).max||0)rescue 0}
d[x]<d[y]?y.map{|e|f[x,e]}:d[x]>d[y]?x.map{|e|f[e,y]}:d[x]<1?x+(y||0):[*x.zip(y).map(&f),*y[x.size..-1]]}
</code>```

Title: Jam don't add like that

Body:
Ruby 2.3, <s>143</s> <s>145</s> <s>148</s> 149  bytes

Ruby has all these little quirks in how zip works with different-length arrays and map with multi-argument functions, making this pretty fun to golf down.

f=->x,y{d=->a{-~(a.map(&d).max||0)rescue 0}
d[x]<d[y]?y.map{|e|f[x,e]}:d[x]>d[y]?x.map{|e|f[e,y]}:d[x]<1?x+(y||0):[*x.zip(y).map(&f),*y[x.size..-1]]}


答:
Python 2, 64 bytes

f=lambda l,s=0:l>[]and(sum(l)==s)|f(l[1:],s+l[0])|f(l,s+l.pop())
```

Recursively tries to remove elements from the front or end until the sum of what remains equals the sum of what was deleted, which is stored is s. Takes time exponential in the list length.

Dennis saved 3 bytes with pop.

Title: Has My Pie Been Bisected?

Body:
Python 2, 64 bytes

f=lambda l,s=0:l>[]and(sum(l)==s)|f(l[1:],s+l[0])|f(l,s+l.pop())

Recursively tries to remove elements from the front or end until the sum of what remains equals the sum of what was deleted, which is stored is s. Takes time exponential in the list length.

Dennis saved 3 bytes with pop.


答:
Actually, 21 bytes

```<code>;Σ@2*;lR@τ╗`╜V♂Σi`Míu
</code>```

Try it online!

This program prints out a 0 for false cases, and a positive integer for true cases.

Explanation:

```<code>;Σ@2*;lR@τ╗`╜V♂Σi`Míu
;Σ                     sum of copy of input
  @2*                  double values in other copy
     ;lR               copy, range(1, len(input)+1)
        @τ             append other copy to itself
          ╗            save in reg0
           `╜V♂Σi`M    map: generate cyclic cumulative sums
                   íu  1-based index of sum of input (0 if not found)
</code>```

Non-competing version, 10 bytes

```<code>;Σ@2*σ;)-∩
</code>```

Try it online!

This program outputs an empty list for false cases and a non-empty list otherwise. It is essentially a port of Dennis's Jelly answer. It is non-competing because the cumulative sum and vectorized difference functionality post-date the challenge.

Explanation:

```<code>;Σ@2*σ;)-∩
;Σ          sum of copy of input
  @2*       multiply values in other copy by 2
     σ;     two copies of cumulative sum
       )-   subtract sum of input from each element in one copy
         ∩  set intersection with other copy
</code>```

Title: Has My Pie Been Bisected?

Body:
Actually, 21 bytes

;Σ@2*;lR@τ╗`╜V♂Σi`Míu

Try it online!

This program prints out a 0 for false cases, and a positive integer for true cases.

Explanation:

;Σ@2*;lR@τ╗`╜V♂Σi`Míu
;Σ                     sum of copy of input
  @2*                  double values in other copy
     ;lR               copy, range(1, len(input)+1)
        @τ             append other copy to itself
          ╗            save in reg0
           `╜V♂Σi`M    map: generate cyclic cumulative sums
                   íu  1-based index of sum of input (0 if not found)

Non-competing version, 10 bytes

;Σ@2*σ;)-∩

Try it online!

This program outputs an empty list for false cases and a non-empty list otherwise. It is essentially a port of Dennis's Jelly answer. It is non-competing because the cumulative sum and vectorized difference functionality post-date the challenge.

Explanation:

;Σ@2*σ;)-∩
;Σ          sum of copy of input
  @2*       multiply values in other copy by 2
     σ;     two copies of cumulative sum
       )-   subtract sum of input from each element in one copy
         ∩  set intersection with other copy


答:
JavaScript (ES6), 83 bytes

```<code>a=>a.map(_=>a.slice(--n).map(m=>s.push(t+=m),t=0),s=[],n=a.length)&&s.includes(t/2)
</code>```

Generates all possible sums, then checks to see whether half of the last sum (which is the sum of the whole list) appears in the list. (Generating the sums in the slightly awkward order to arrange for the sum I need to be last saves 4 bytes.)

Title: Has My Pie Been Bisected?

Body:
JavaScript (ES6), 83 bytes

a=>a.map(_=>a.slice(--n).map(m=>s.push(t+=m),t=0),s=[],n=a.length)&&s.includes(t/2)

Generates all possible sums, then checks to see whether half of the last sum (which is the sum of the whole list) appears in the list. (Generating the sums in the slightly awkward order to arrange for the sum I need to be last saves 4 bytes.)


答:
MATL, 10 bytes

```<code>EYst!-Gs=z
</code>```

The output is the number of bisectors.

Try it online!

Explanation

Same approach as Dennis' Julia answer.

```<code>E       % Implicit input. Multiply by 2 element-wise
Ys      % Cumulative sum
t!-     % Compute all pairwise differences. Gives a 2D array
Gs      % Sum of input
=       % Test for equality, element-wise
z       % Number of nonzero elements. Implicit display
</code>```

Title: Has My Pie Been Bisected?

Body:
MATL, 10 bytes

EYst!-Gs=z

The output is the number of bisectors.

Try it online!

Explanation

Same approach as Dennis' Julia answer.

E       % Implicit input. Multiply by 2 element-wise
Ys      % Cumulative sum
t!-     % Compute all pairwise differences. Gives a 2D array
Gs      % Sum of input
=       % Test for equality, element-wise
z       % Number of nonzero elements. Implicit display


问:
Shortest way to reverse a number
Write a function (or equivalent subprogram) to accept a single integer valued argument and return a (similarly typed) value found by reversing the order of the base-10 digits of the argument.

For example given 76543 return 34567

OwnerDisplayName: eltond

Title: Shortest way to reverse a number

Body:
mIRC 4.45 (35 Bytes)

$regsubex(12,/(.)/g,$mid(\A,-\n,1))


答:
C, 161 145 129 bytes

saved few bytes thanks to @LeakyNun

saved few bytes thanks to @ceilingcat

i;j;k;t;r;s;f(x,n)int*x;{for(t=i=k=r=0;i<n;)t+=x[i++];for(;++k<n;i=n)for(;i--;r|=2*s==t)for(s=0,j=i;j<i+k;)s+=x[j++%n];return r;}
```

<p><strong>Ungolfed</strong> try online</p>

<pre class="lang-c prettyprint-override"><code>int f(int*x,int n)
{
    int t=0;

    for(int i=0;i<n;i++)
    {
        t += x[i];
    }

    for(int k=1;k<n;k++) // subset-size
    {
        for(int i=0,s;i<n;i++) // where to start
        {
            s=0;

            for(int j=i;j<i+k;j++) // sum the subset
            {
                s+=x[j%n];
            }

            if(2*s==t) return 1; // TRUE
        }
    }

    return 0; // FALSE
}
</code>```

Title: Has My Pie Been Bisected?

Body:
C, 161 145 129 bytes

saved few bytes thanks to @LeakyNun

saved few bytes thanks to @ceilingcat

i;j;k;t;r;s;f(x,n)int*x;{for(t=i=k=r=0;i<n;)t+=x[i++];for(;++k<n;i=n)for(;i--;r|=2*s==t)for(s=0,j=i;j<i+k;)s+=x[j++%n];return r;}

Ungolfed try online

int f(int*x,int n)
{
    int t=0;

    for(int i=0;i<n;i++)
    {
        t += x[i];
    }

    for(int k=1;k<n;k++) // subset-size
    {
        for(int i=0,s;i<n;i++) // where to start
        {
            s=0;

            for(int j=i;j<i+k;j++) // sum the subset
            {
                s+=x[j%n];
            }

            if(2*s==t) return 1; // TRUE
        }
    }

    return 0; // FALSE
}


答:
Haskell, 68 bytes

```<code>f l|x<-[0..length l]=any(sum l==)[2*(sum$take a$drop b l)|a<-x,b<-x]
</code>```

The function f first creates a list of the sums of all the possible slices of the given list. Then it compares to the total sum of list elements. If we get at some point half of the total sum, then we know that we've got a bisection. I'm also using the fact that if you take or drop more elements than there are in the list, Haskell does not throw an error.

Title: Has My Pie Been Bisected?

Body:
Haskell, 68 bytes

f l|x<-[0..length l]=any(sum l==)[2*(sum$take a$drop b l)|a<-x,b<-x]

The function f first creates a list of the sums of all the possible slices of the given list. Then it compares to the total sum of list elements. If we get at some point half of the total sum, then we know that we've got a bisection. I'm also using the fact that if you take or drop more elements than there are in the list, Haskell does not throw an error.


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

答:
Pyth, 25 bytes

```<code>JfP_TSfP_ThQ*F+1m@Jx1xJdP
</code>```

Test suite.

Explanation

```<code>JfP_TSfP_ThQ*F+1m@Jx1xJdP

           Q    get input
          h     add one
      fP_T      find the first prime after it
     S          range from 1 to that prime
 fP_T           filter for the primes
J               assign to J

                        P  prime factorize input
                m      d   for each factor
                     xJ    find its index in J
                   x1      xor with 1
                 @J        find the corresponding entry in J
            *F+1           product of the whole list
</code>```

Body:
Pyth, 25 bytes

JfP_TSfP_ThQ*F+1m@Jx1xJdP

Test suite.

Explanation

JfP_TSfP_ThQ*F+1m@Jx1xJdP

           Q    get input
          h     add one
      fP_T      find the first prime after it
     S          range from 1 to that prime
 fP_T           filter for the primes
J               assign to J

                        P  prime factorize input
                m      d   for each factor
                     xJ    find its index in J
                   x1      xor with 1
                 @J        find the corresponding entry in J
            *F+1           product of the whole list


答:
Jelly, <s>17</s> <s>16</s> 11 bytes

5 bytes thanks to Dennis.

```<code>ÆfÆC’^1‘ÆNP
</code>```

Try it online!

Explanation

```<code>ÆfÆC’^1‘ÆNP   Main monadic chain. Argument: n

Æf            Yield the prime factors of n.
  ÆC          For each factor, count the number of primes below it.
              This effectively yields their indices.
    ’         Decrement [each] by 1.
     ^1       Xor with 1
       ‘      Increment [each] by 1.
        ÆN    Find their corresponding primes.
          P   Yield their product.
</code>```

Previous 16-byte version

```<code>ÆnÆRiÐ€Æf’^1‘ÆNP
</code>```

Try it online!

Explanation

```<code>ÆnÆRiÐ€Æf’^1‘ÆNP   Main monadic chain. Argument: n

Æn                 Yield the next prime from n.
  ÆR               Yield all primes from 2 to it.
       Æf          Yield prime factors of n
    iÐ€            Yield their index in the prime list.
         ’         Decrement [each] by 1.
          ^1       Xor with 1
            ‘      Increment [each] by 1.
             ÆN    Find their corresponding primes.
               P   Yield their product.
</code>```

Previous 17-byte version:

```<code>ÆnÆR©iÐ€Æf’^1‘ị®P
</code>```

Try it online!

Explanation

```<code>ÆnÆR©iÐ€Æf’^1‘ị®P   Main monadic chain. Argument: n

Æn                  Yield the next prime from n.
  ÆR                Yield all primes from 2 to it.
    ©               Store to register.
        Æf          Yield prime factors of n
     iÐ€            Yield their index in the prime list.
          ’         Decrement [each] by 1.
           ^1       Xor with 1
             ‘      Increment [each] by 1.
              ị®    Find their corresponding primes in
                    the list in register.
                P   Yield their 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:
Jelly, <s>17</s> <s>16</s> 11 bytes

5 bytes thanks to Dennis.

ÆfÆC’^1‘ÆNP

Try it online!

Explanation

ÆfÆC’^1‘ÆNP   Main monadic chain. Argument: n

Æf            Yield the prime factors of n.
  ÆC          For each factor, count the number of primes below it.
              This effectively yields their indices.
    ’         Decrement [each] by 1.
     ^1       Xor with 1
       ‘      Increment [each] by 1.
        ÆN    Find their corresponding primes.
          P   Yield their product.

Previous 16-byte version

ÆnÆRiÐ€Æf’^1‘ÆNP

Try it online!

Explanation

ÆnÆRiÐ€Æf’^1‘ÆNP   Main monadic chain. Argument: n

Æn                 Yield the next prime from n.
  ÆR               Yield all primes from 2 to it.
       Æf          Yield prime factors of n
    iÐ€            Yield their index in the prime list.
         ’         Decrement [each] by 1.
          ^1       Xor with 1
            ‘      Increment [each] by 1.
             ÆN    Find their corresponding primes.
               P   Yield their product.

Previous 17-byte version:

ÆnÆR©iÐ€Æf’^1‘ị®P

Try it online!

Explanation

ÆnÆR©iÐ€Æf’^1‘ị®P   Main monadic chain. Argument: n

Æn                  Yield the next prime from n.
  ÆR                Yield all primes from 2 to it.
    ©               Store to register.
        Æf          Yield prime factors of n
     iÐ€            Yield their index in the prime list.
          ’         Decrement [each] by 1.
           ^1       Xor with 1
             ‘      Increment [each] by 1.
              ị®    Find their corresponding primes in
                    the list in register.
                P   Yield their product.


问:
Color count, sorted by occurences
This one is simple to describe and I could hardly believe that this was not golfed before:

For a given image (whatever format is supported by your language), find the unique colors and output a list of the colors.

Print the color code in hex RGB, that is a hash sign # followed by 2 digits for R, 2 digits for G and 2 digits for B. (#xxxxxx where x can be 0-9, A-F and/or a-f).

The hex code shall be followed by a space  and the decimal pixel count, then a newline (\n or \r\n).

The list shall be sorted by count descending (most frequent color at the top).

If there's a tie (two colors with the same amount), the order is not important.

The image will not contain transparency, so any alpha value is not important. The alpha value may not be part of the output.

An image size of 4000x3000 must be supported (that may matter to type definitions)

Sample image "10red 20blue 30black 40white":

Expected output:

```<code>#FFFFFF 40
#000000 30
#0000FF 20
#FF0000 10
</code>```

Sample image "blue gradient":

One of the expected outputs (since the order of same colors may vary):

```<code>#718DFF 19
#5571FF 15
#3855FF 11
#8DAAFF 11
#1C38FF 7
#AAAAFF 7
#8D8DFF 6
#AAC6FF 6
#C6C6FF 5
#C6E2FF 4
#001CFF 3
#E2E2FF 3
#FFFFFF 3
</code>```

Sample image "testImage", kindly provided by @Luis Mendo:

Expected output:

```<code>#FFFFFF 18042
#000000 1754
#FF3300 204
</code>```

Similar to this question, but the output is text, not an image.

答:
Pyth, 29 bytes

```<code>jmj;_d_SrSm+\#.[\06.Hid256'Q8
</code>```

Try it online!

(The online interpreter cannot read image, so I stripped of that part and inputted the result of reading that image, which is a list of color triplets. The part responsible for reading the image is ', a single colon.)

Proof of functionality of ' a single colon

Title: Color count, sorted by occurences

Body:
Pyth, 29 bytes

jmj;_d_SrSm+\#.[\06.Hid256'Q8

Try it online!

(The online interpreter cannot read image, so I stripped of that part and inputted the result of reading that image, which is a list of color triplets. The part responsible for reading the image is ', a single colon.)

Proof of functionality of ' a single colon


答:
Python 2, <s>149</s> 139 bytes

10 bytes thanks to Dennis.

n=input()
p=f=1;w=[2]
while w[-1]<=n:f*=p;p+=1;w+=[p]*(-~f%p<1)
r=p=1;w=w[1:]
while n>1:
    p+=1
    while n%p<1:n/=p;r*=w[w.index(p)^1]
print r
```


答:
Mathematica, <s>70</s> 69 bytes

```<code>1##&@@(Prime[BitXor[PrimePi@#+1,1]-1]^#2&)@@@FactorInteger@#/._@_->1&
</code>```

An unnamed function which takes and returns an integer. It throws an error on input 1 but still computes the correct result.

Explanation

As usual, due to all the syntactic sugar, the reading order is a bit funny. A & on the right defines an unnamed function and its arguments are referred to by #, #2, #3, etc.

```<code>...FactorInteger@#...
</code>```

We start by factoring the input. This gives a list of pairs {prime, exponent} e.g. input 12 gives {{2, 2}, {3, 1}}. Somewhat inconveniently, 1 gives {{1, 1}}.

```<code>(...&)@@@...
</code>```

This applies the function on the left to the list of integers at level 1, that is the function is called for each pair, passing the prime and exponent in as separate arguments, and then returns a list of the results. (This is similar to mapping the function over the list, but receiving two separate arguments is more convenient than receiving a pair.)

```<code>...PrimePi@#...
</code>```

We compute the number of primes up to and including the (prime) input using the built-in PrimePi. This gives us the index of the prime.

```<code>...BitXor[...+1,1]-1...
</code>```

The result is incremented, XOR'ed with 1 and decremented again. This swaps 1 <-> 2, 3 <-> 4, 5 <-> 6, ..., i.e. all 1-based indices. Note that input 1 will yield 0 for PrimePi which is then mapped to -1 in this process. We'll deal with that later.

```<code> ...Prime[...]^#2...
</code>```

We now obtain the nth prime (where n is the result from the previous computation), which is the correctly swapped prime, and raise it to the power of the original prime in the factorisation of the input. At this point Prime[-1] will throw an error but will return itself unevaluated. The power in this case is 1 so that the entire process so far yields {Prime[-1]} for input 1 and a list of correct prime powers for all other inputs.

```<code> 1##&@@...
</code>```

Next, we just multiply up all prime powers. 1##& is a standard golfing trick for the Times function. See this tip (section "Sequences of arguments") for how it works.

Finally, we need to take care of input 1 for which all of the above resulted in Prime[-1]. We can easily fix that with a simple replacement rule. Remember that f@x is short for f[x]. We just want to match any expression of that form (since all other results will be integers, i.e. atomic expressions), and replace it with a 1:

```<code>.../._@_->1
</code>```

Here, /. is short for ReplaceAll, _@_ is a pattern for anything of the form f[x] (i.e. any compound expression with a single child) and ->1 says "replace with 1".

Body:
Mathematica, <s>70</s> 69 bytes

1##&@@(Prime[BitXor[PrimePi@#+1,1]-1]^#2&)@@@FactorInteger@#/._@_->1&

An unnamed function which takes and returns an integer. It throws an error on input 1 but still computes the correct result.

Explanation

As usual, due to all the syntactic sugar, the reading order is a bit funny. A & on the right defines an unnamed function and its arguments are referred to by #, #2, #3, etc.

...FactorInteger@#...

We start by factoring the input. This gives a list of pairs {prime, exponent} e.g. input 12 gives {{2, 2}, {3, 1}}. Somewhat inconveniently, 1 gives {{1, 1}}.

(...&)@@@...

This applies the function on the left to the list of integers at level 1, that is the function is called for each pair, passing the prime and exponent in as separate arguments, and then returns a list of the results. (This is similar to mapping the function over the list, but receiving two separate arguments is more convenient than receiving a pair.)

...PrimePi@#...

We compute the number of primes up to and including the (prime) input using the built-in PrimePi. This gives us the index of the prime.

...BitXor[...+1,1]-1...

The result is incremented, XOR'ed with 1 and decremented again. This swaps 1 <-> 2, 3 <-> 4, 5 <-> 6, ..., i.e. all 1-based indices. Note that input 1 will yield 0 for PrimePi which is then mapped to -1 in this process. We'll deal with that later.

 ...Prime[...]^#2...

We now obtain the nth prime (where n is the result from the previous computation), which is the correctly swapped prime, and raise it to the power of the original prime in the factorisation of the input. At this point Prime[-1] will throw an error but will return itself unevaluated. The power in this case is 1 so that the entire process so far yields {Prime[-1]} for input 1 and a list of correct prime powers for all other inputs.

 1##&@@...

Next, we just multiply up all prime powers. 1##& is a standard golfing trick for the Times function. See this tip (section "Sequences of arguments") for how it works.

Finally, we need to take care of input 1 for which all of the above resulted in Prime[-1]. We can easily fix that with a simple replacement rule. Remember that f@x is short for f[x]. We just want to match any expression of that form (since all other results will be integers, i.e. atomic expressions), and replace it with a 1:

.../._@_->1

Here, /. is short for ReplaceAll, _@_ is a pattern for anything of the form f[x] (i.e. any compound expression with a single child) and ->1 says "replace with 1".


答:
Jelly, 10 bytes

```<code>ÆE;0s2UFÆẸ
</code>```

Try it online! or verify all test cases.

How it works

```<code>ÆE;0s2UFÆẸ  Main link. Argument: n

ÆE          Yield the exponents of n's prime factorization.
  ;0        Append a zero.
    s2      Split into pairs.
      U     Upend; reverse each pair.
       F    Flatten the resulting list of pairs.
        ÆẸ  Convert the prime exponents to integer.
</code>```

Body:
Jelly, 10 bytes

ÆE;0s2UFÆẸ

Try it online! or verify all test cases.

How it works

ÆE;0s2UFÆẸ  Main link. Argument: n

ÆE          Yield the exponents of n's prime factorization.
  ;0        Append a zero.
    s2      Split into pairs.
      U     Upend; reverse each pair.
       F    Flatten the resulting list of pairs.
        ÆẸ  Convert the prime exponents to integer.


答:
C#, 44 bytes

Based on the C implementation

int f(int n)=>n>3?4*f(n/4)+f(n%4):n%2*2+n/2;

Try it here: C# pad

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>```


问:
Implement Bogosort
Is solving Sudoku too hard? Even the brute force version? Here's a coding exercise that's a little easier. I hope. :-P

Write the shortest function to implement bogosort. In specific, your function should:

Take an array (or your language's equivalent) as input

Check if its elements are in sorted order; if so, return the array

If not, shuffle the elements, and start again

The shortest entry wins. In the case of a tie, a function that supports a custom comparator (and/or pseudorandom number generator) is favoured. Any remaining ties are resolved by favouring the earlier submission.

Clarifications: You can use any element type you want, as long as there's some way to order them, of course. Also, the shuffling has to be uniform; none of this "I'll just quicksort it and call it shuffled" business. :-)

答:
C++11, 150 characters

```<code>#include<deque>
#include<algorithm>
void B(std::deque &A){while(!std::is_sorted(A.begin(),A.end())std::random_shuffle(myvector.begin(),myvector.end());}
</code>```

Just.. made for fun.

ContentLicense: CC BY-SA 2.5

Title: Implement Bogosort

Body:
C++11, 150 characters

#include<deque>
#include<algorithm>
void B(std::deque &A){while(!std::is_sorted(A.begin(),A.end())std::random_shuffle(myvector.begin(),myvector.end());}

Just.. made for fun.


答:
05AB1E, 8 bytes

```<code>4B12Â‡4ö
</code>```

Thanks to @Adnan for -5 bytes!

Uses CP-1252 encoding.

Try It Online!

Explanation:

```<code>4B       - Take input and convert to base 4.
  12Â    - Push 12 bifurcated.
     ‡   - Transliterate [1, 2] to [2, 1].
      4ö - Convert to base 10.
</code>```

Title: Swap bits with their neighbours

Body:
05AB1E, 8 bytes

4B12Â‡4ö

Thanks to @Adnan for -5 bytes!

Uses CP-1252 encoding.

Try It Online!

Explanation:

4B       - Take input and convert to base 4.
  12Â    - Push 12 bifurcated.
     ‡   - Transliterate [1, 2] to [2, 1].
      4ö - Convert to base 10.


答:
Mathematica, 48 bytes

```<code>!FreeQ[Outer[Plus,#,-#],Last@#/2]&@Accumulate@#&
</code>```

Anonymous function, similar in action to the numerous other answers.

Outer[Plus, #, -#], when acting on Accumulate@# (which in turn acts on the input list, giving a list of successive totals) generates essentially the same table, as at the bottom of Leaky Nun's answer.

!FreeQ[..., Last@#/2] checks if (Last@#)/2 is not absent from the resulting table, and Last@# is the last of the successive totals, i.e. the sum of all elements of the input list.

If this answer is somewhat interesting, it is not because of a new algorithm, but more about the tricks specific to Mathematica; e.g. !FreeQ is nice, compared to MemberQ, since it does not require a flattening of the table it checks and it saves a byte.

Title: Has My Pie Been Bisected?

Body:
Write a program or function that takes in a nonempty list of positive integers. You may assume it is input in a reasonable convenient format such as "1 2 3 4" or [1, 2, 3, 4].

The numbers in the input list represent the slices of a full pie chart where each slice size is proportional to its corresponding number and all slices are arranged around the chart in the order given.

For example, the pie for 1 2 3 4 is:

The question your code must answer is: Is the pie chart ever bisected? That is, is there ever a perfectly straight line from one side of the circle to the other, splitting it symmetrically in two?

You need to output a truthy value if there is at least one bisector and output a falsy value if there are none.

In the 1 2 3 4 example there is a bisection between 4 1 and 2 3 so the output would be truthy.

But for input 1 2 3 4 5 there is no bisector so the output would be falsy:

Additional Examples

Arranging numbers differently may remove bisectors.

e.g. 2 1 3 4 → falsy:

If only one number is in the input list the pie is not bisected.

e.g. 10 → falsy:

There may be multiple bisectors. As long as there are more than zero the output is truthy.

e.g. 6 6 12 12 12 11 1 12 → truthy: (there are 3 bisectors here)

Bisections may exist even if they are not visually obvious.

e.g. 1000000 1000001 → falsy:

e.g. 1000000 1000001 1 → truthy:

(Thanks to nces.ed.gov for generating the pie charts.)

Test Cases

```<code>Truthy
1 2 3 4
6 6 12 12 12 11 1 12
1000000 1000001 1
1 2 3
1 1
42 42
1 17 9 13 2 7 3
3 1 2
10 20 10

Falsy
1 2 3 4 5
2 1 3 4
10
1000000 1000001
1
1 2
3 1 1
1 2 1 2 1 2
10 20 10 1
</code>```

Scoring

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

Body:
Mathematica, 48 bytes

!FreeQ[Outer[Plus,#,-#],Last@#/2]&@Accumulate@#&

Anonymous function, similar in action to the numerous other answers.

Outer[Plus, #, -#], when acting on Accumulate@# (which in turn acts on the input list, giving a list of successive totals) generates essentially the same table, as at the bottom of Leaky Nun's answer.

!FreeQ[..., Last@#/2] checks if (Last@#)/2 is not absent from the resulting table, and Last@# is the last of the successive totals, i.e. the sum of all elements of the input list.

If this answer is somewhat interesting, it is not because of a new algorithm, but more about the tricks specific to Mathematica; e.g. !FreeQ is nice, compared to MemberQ, since it does not require a flattening of the table it checks and it saves a byte.


答:
J, 22 bytes

```<code>$:@({~?~@#)`]@.(-:/:~)
</code>```

This is a recursive, tacit monad using an agenda. Here's how it works:

Let y be our list. First, the verb on the right of the agenda is -:/:~. This a verb graciously provided by Leaky Nun. It matches (-:) whether or not the input is sorted (/:~) using a monadic hook. ((f g) y = y f (g y)) This returns a one or a zero accordingly. The left hand side of the agenda is a gerund of two verbs: on the right is the identity verb ], and on the left is where the recursion takes place. The agenda selects either the identity verb at position 1 if the list is sorted, and the longer verb at position 0 if the list isn't sorted.

$:@({~?~@#) calls $: (the longest verb it is contained in) atop the result of {~?~@# on y. This shuffles the list, as ?~@# takes the permutations of the length of y, being randomly-sorted indices of y. {~, in a monadic hook, returns a list from y whose indices are the right arg. This shuffled list is then called again with the agenda, and repeats until it is sorted.

Title: Implement Bogosort

Body:
Is solving Sudoku too hard? Even the brute force version? Here's a coding exercise that's a little easier. I hope. :-P

Write the shortest function to implement bogosort. In specific, your function should:

Take an array (or your language's equivalent) as input

Check if its elements are in sorted order; if so, return the array

If not, shuffle the elements, and start again

The shortest entry wins. In the case of a tie, a function that supports a custom comparator (and/or pseudorandom number generator) is favoured. Any remaining ties are resolved by favouring the earlier submission.

Clarifications: You can use any element type you want, as long as there's some way to order them, of course. Also, the shuffling has to be uniform; none of this "I'll just quicksort it and call it shuffled" business. :-)

Body:
J, 22 bytes

$:@({~?~@#)`]@.(-:/:~)

This is a recursive, tacit monad using an agenda. Here's how it works:

Let y be our list. First, the verb on the right of the agenda is -:/:~. This a verb graciously provided by Leaky Nun. It matches (-:) whether or not the input is sorted (/:~) using a monadic hook. ((f g) y = y f (g y)) This returns a one or a zero accordingly. The left hand side of the agenda is a gerund of two verbs: on the right is the identity verb ], and on the left is where the recursion takes place. The agenda selects either the identity verb at position 1 if the list is sorted, and the longer verb at position 0 if the list isn't sorted.

$:@({~?~@#) calls $: (the longest verb it is contained in) atop the result of {~?~@# on y. This shuffles the list, as ?~@# takes the permutations of the length of y, being randomly-sorted indices of y. {~, in a monadic hook, returns a list from y whose indices are the right arg. This shuffled list is then called again with the agenda, and repeats until it is sorted.


答:
MATL, 17 bytes

```<code>EZqGYfy&mt2\Eq+)p
</code>```

Try it online!

Explanation

This doesn't use the exponents directly. Instead, it swaps each (possibly repeated) prime factor by the next or the preceding prime.

```<code>EZq    % Implicit input. Multiply by 2
Zq     % Array with sequence of primes up to that (this is more than enough)
GYf    % Prime factors of input, with possible repetitions
y      % Duplicate array with sequence of primes
&m     % Indices of prime factors in the sequence of primes
t2\    % Duplicate, modulo 2. Gives 0 for even indices, 1 for odd
Eq     % Multiply by 2, add 1. Transforms 0 / 1 into -1 / 1
+      % Add. This modifies the indices to perform the swapping
)      % Apply the new indices into the sequence of primes
p      % Product. Implicit display
</code>```

Body:
MATL, 17 bytes

EZqGYfy&mt2\Eq+)p

Try it online!

Explanation

This doesn't use the exponents directly. Instead, it swaps each (possibly repeated) prime factor by the next or the preceding prime.

EZq    % Implicit input. Multiply by 2
Zq     % Array with sequence of primes up to that (this is more than enough)
GYf    % Prime factors of input, with possible repetitions
y      % Duplicate array with sequence of primes
&m     % Indices of prime factors in the sequence of primes
t2\    % Duplicate, modulo 2. Gives 0 for even indices, 1 for odd
Eq     % Multiply by 2, add 1. Transforms 0 / 1 into -1 / 1
+      % Add. This modifies the indices to perform the swapping
)      % Apply the new indices into the sequence of primes
p      % Product. Implicit display


问:
Tell me how many math problems I have to do!
My teacher always gives me the most complicated set of math problems for homework. Like: pg. 546: 17-19, 22, 26, pg. 548: 35-67 odd, 79, 80-86 even. And I want to know in advance how much time to set aside for my homework, but I don't want to have to figure all that out. That's why its your task to program it for me.

Specifications

You will get a string detailing the problems that I have to complete as args, stdio, etc.

They will be comma separated (possibly comma-space separated)

It will include single problems in the form of just a number (e.g. 79)

And ranges in the form 17-18 (again, you have to deal with optional spaces)

The ranges are inclusive of both ends

The ranges will optionally be suffixed by odd or even, which you have to take into account.

A set of ranges/pages will be prepended by a page number in the form pg. 545: , again having to deal with optional spaces. You can safely ignore these, as you need to get the problems over all the pages

The text may be in uppercase or lowercase, but will not be both.

Return, stdout, etc. the number of problems I have to do for homework.

Since this is code-golf, shortest code in bytes wins!

Test Cases

```<code>pg. 546: 17-19, 22, 26, pg. 548: 35-67 odd, 79, 80-86 even   ->    27
pg. 34: 1                                                    ->    1
PG. 565: 2-5,PG.345:7                                        ->    5
pg. 343: 5,8,13 - 56 even,pg. 345: 34 - 78,80                ->    70
pg.492: 2-4 odd,7-9 even                                     ->    2
</code>```

答:
C++ <s>226</s> <s>224</s> 222

I know I'm kinda late for the party, but this seemed like a fun problem and lack of entries using C-family languages bothered me.

So here's a C++ function using no regexp or string substitution, just some simple math:

```<code>void f(){char c;int o=0,i,j;while(cin>>c)c=='p'||c==80?cin.ignore(9,58):cin.unget(),cin>>i>>c&&c==45?cin>>j>>c&&(c=='e'||c=='o')?cin.ignore(9,44),c=='e'?i+=i&1,j+=!(j&1):(i+=!(i&1),j+=j&1),o+=(j-i)/2:o+=j-i:0,++o;cout<<o;}
</code>```

Ungolfed:

```<code>void f()
{
  char c;
  int o=0,i,j;
  while(cin>>c)
    c=='p'||c==80?cin.ignore(9,58):cin.unget(),
    cin>>i>>c&&c==45?
      cin>>j>>c&&(c=='e'||c=='o')?
        cin.ignore(9,44),
        c=='e'?
          i+=i&1,j+=!(j&1)
        :(i+=!(i&1),j+=j&1),
        o+=(j-i)/2
      :o+=j-i
    :0,
    ++o;
  cout<<o;
}
</code>```

I didn't say it would be readable, now did I? :) Ternary operators are hell. I tried my best to (sort of) format it, though, so I hope it helps at least a little bit.

Usage:

```<code>#include <iostream>
using namespace std;

void f(){char c;int o=0,i,j;while(cin>>c)c=='p'||c==80?cin.ignore(9,58):cin.unget(),cin>>i>>c&&c==45?cin>>j>>c&&(c=='e'||c=='o')?cin.ignore(9,44),c=='e'?i+=i&1,j+=!(j&1):(i+=!(i&1),j+=j&1),o+=(j-i)/2:o+=j-i:0,++o;cout<<o;}

int main()
{
  f();
}
</code>```

Body:
C++ <s>226</s> <s>224</s> 222

I know I'm kinda late for the party, but this seemed like a fun problem and lack of entries using C-family languages bothered me.

So here's a C++ function using no regexp or string substitution, just some simple math:

void f(){char c;int o=0,i,j;while(cin>>c)c=='p'||c==80?cin.ignore(9,58):cin.unget(),cin>>i>>c&&c==45?cin>>j>>c&&(c=='e'||c=='o')?cin.ignore(9,44),c=='e'?i+=i&1,j+=!(j&1):(i+=!(i&1),j+=j&1),o+=(j-i)/2:o+=j-i:0,++o;cout<<o;}

Ungolfed:

void f()
{
  char c;
  int o=0,i,j;
  while(cin>>c)
    c=='p'||c==80?cin.ignore(9,58):cin.unget(),
    cin>>i>>c&&c==45?
      cin>>j>>c&&(c=='e'||c=='o')?
        cin.ignore(9,44),
        c=='e'?
          i+=i&1,j+=!(j&1)
        :(i+=!(i&1),j+=j&1),
        o+=(j-i)/2
      :o+=j-i
    :0,
    ++o;
  cout<<o;
}

I didn't say it would be readable, now did I? :) Ternary operators are hell. I tried my best to (sort of) format it, though, so I hope it helps at least a little bit.

Usage:

#include <iostream>
using namespace std;

void f(){char c;int o=0,i,j;while(cin>>c)c=='p'||c==80?cin.ignore(9,58):cin.unget(),cin>>i>>c&&c==45?cin>>j>>c&&(c=='e'||c=='o')?cin.ignore(9,44),c=='e'?i+=i&1,j+=!(j&1):(i+=!(i&1),j+=j&1),o+=(j-i)/2:o+=j-i:0,++o;cout<<o;}

int main()
{
  f();
}


答:
Ruby, 60 53 bytes

```<code>->a{a.any?{r=eval a*?+;a.rotate!.any?{|i|0==r-=2*i}}}
</code>```

Generates all possible partitions by taking every rotation of the input array and then taking all slices of length 1..n, where n is the size of the input array. Then checks if there exists any partition with a sum half the total sum of the input array.

Title: Has My Pie Been Bisected?

Body:
Ruby, 60 53 bytes

->a{a.any?{r=eval a*?+;a.rotate!.any?{|i|0==r-=2*i}}}

Generates all possible partitions by taking every rotation of the input array and then taking all slices of length 1..n, where n is the size of the input array. Then checks if there exists any partition with a sum half the total sum of the input array.


答:
JavaScript (ES6), <s>359</s> 355 bytes

Saved 4 bytes thanks to @Neil

u=>{i=new Image;i.src=u;e=document.createElement`canvas`;c=e.getContext`2d`;i.onload=_=>{w=e.width=i.width;h=e.height=i.height;c.drawImage(i,0,0);d=c.getImageData(0,0,w,h).data;for(o={},i=0;i<d.length;i+=4)++o[s='#'+`00000${(d[i]<<16|d[i+1]<<8|d[i+2]).toString(16)} `.slice(-7)]?0:o[s]=1;Object.keys(o).sort((a,b)=>o[b]-o[a]).map(c=>console.log(c+o[c]))}}
```

<h2>Demo</h2>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>f=u=>{i=new Image;i.crossOrigin='';i.src=u;e=document.createElement`canvas`;c=e.getContext`2d`;i.onload=_=>{w=e.width=i.width;h=e.height=i.height;c.drawImage(i,0,0);d=c.getImageData(0,0,w,h).data;for(o={},i=0;i<d.length;i+=4)++o[s='#'+`00000${(d[i]<<16|d[i+1]<<8|d[i+2]).toString(16)} `.slice(-7)]?0:o[s]=1;Object.keys(o).sort((a,b)=>o[b]-o[a]).map(c=>console.log(c+o[c]))}}
f('http://i.imgur.com/acPudA9.gif')</code>```

<input value="https://i.imgur.com/acPudA9.gif" onchange="console.log('-------');f(this.value)">```

Other test cases I uploaded to imgur to support CORS:

https://i.imgur.com/OgV45Vc.png

https://i.imgur.com/n3BhpJi.png

The specific color data on these two seems to have altered slightly when uploading for some reason but it still prints the same amount of occurrences for those two test cases.

Title: Color count, sorted by occurences

Body:
This one is simple to describe and I could hardly believe that this was not golfed before:

For a given image (whatever format is supported by your language), find the unique colors and output a list of the colors.

Print the color code in hex RGB, that is a hash sign # followed by 2 digits for R, 2 digits for G and 2 digits for B. (#xxxxxx where x can be 0-9, A-F and/or a-f).

The hex code shall be followed by a space  and the decimal pixel count, then a newline (\n or \r\n).

The list shall be sorted by count descending (most frequent color at the top).

If there's a tie (two colors with the same amount), the order is not important.

The image will not contain transparency, so any alpha value is not important. The alpha value may not be part of the output.

An image size of 4000x3000 must be supported (that may matter to type definitions)

Sample image "10red 20blue 30black 40white":

Expected output:

```<code>#FFFFFF 40
#000000 30
#0000FF 20
#FF0000 10
</code>```

Sample image "blue gradient":

One of the expected outputs (since the order of same colors may vary):

```<code>#718DFF 19
#5571FF 15
#3855FF 11
#8DAAFF 11
#1C38FF 7
#AAAAFF 7
#8D8DFF 6
#AAC6FF 6
#C6C6FF 5
#C6E2FF 4
#001CFF 3
#E2E2FF 3
#FFFFFF 3
</code>```

Sample image "testImage", kindly provided by @Luis Mendo:

Expected output:

```<code>#FFFFFF 18042
#000000 1754
#FF3300 204
</code>```

Similar to this question, but the output is text, not an image.

Body:
JavaScript (ES6), <s>359</s> 355 bytes

Saved 4 bytes thanks to @Neil

u=>{i=new Image;i.src=u;e=document.createElement`canvas`;c=e.getContext`2d`;i.onload=_=>{w=e.width=i.width;h=e.height=i.height;c.drawImage(i,0,0);d=c.getImageData(0,0,w,h).data;for(o={},i=0;i<d.length;i+=4)++o[s='#'+`00000${(d[i]<<16|d[i+1]<<8|d[i+2]).toString(16)} `.slice(-7)]?0:o[s]=1;Object.keys(o).sort((a,b)=>o[b]-o[a]).map(c=>console.log(c+o[c]))}}

Demo

f=u=>{i=new Image;i.crossOrigin='';i.src=u;e=document.createElement`canvas`;c=e.getContext`2d`;i.onload=_=>{w=e.width=i.width;h=e.height=i.height;c.drawImage(i,0,0);d=c.getImageData(0,0,w,h).data;for(o={},i=0;i<d.length;i+=4)++o[s='#'+`00000${(d[i]<<16|d[i+1]<<8|d[i+2]).toString(16)} `.slice(-7)]?0:o[s]=1;Object.keys(o).sort((a,b)=>o[b]-o[a]).map(c=>console.log(c+o[c]))}}
f('http://i.imgur.com/acPudA9.gif')

<input value="https://i.imgur.com/acPudA9.gif" onchange="console.log('-------');f(this.value)">

Other test cases I uploaded to imgur to support CORS:

https://i.imgur.com/OgV45Vc.png

https://i.imgur.com/n3BhpJi.png

The specific color data on these two seems to have altered slightly when uploading for some reason but it still prints the same amount of occurrences for those two test cases.


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

答:
PyCal, 6 bytes

```<code>*i[+^]
</code>```

This runs the code +^ for n times.

+ adds one to the variable and ^ outputs the variable's value. Simple enough.

EDIT: Interestingly enough, this solution is the exact same length as my Tellurium (another esoteric language I made) solution.

Title: Count up folks!

Body:
PyCal, 6 bytes

*i[+^]

This runs the code +^ for n times.

+ adds one to the variable and ^ outputs the variable's value. Simple enough.

EDIT: Interestingly enough, this solution is the exact same length as my Tellurium (another esoteric language I made) solution.


答:
Common Lisp, 39 bytes

Disclaimer: I'm not responsible for any traumatic effect caused by the extreme density of parentheses. It's the language specification's fault. This one has surprisingly few parentheses!

```<code>(loop for a from 1 to(read)do(write a))
</code>```

Title: Count up folks!

Body:
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.

Body:
Common Lisp, 39 bytes

Disclaimer: I'm not responsible for any traumatic effect caused by the extreme density of parentheses. It's the language specification's fault. This one has surprisingly few parentheses!

(loop for a from 1 to(read)do(write a))


问:
Stack Overflowing
(Inspired by this question)

Objective

Your task is to write a program or function to print an ASCII version of the Stack Overflow logo to STDOUT

```<code> \|/
(-)
(-)
(-)
(-)
</code>```

Your program should take two inputs, referred to here as H and N.
The height of the stack "container" (the parentheses) is determined by H. The number of items in the stack is determined by N. If N>H, the stack will "overflow".

Input/Output

H will determine the height of the containers

For example:

H=1:

```<code>( )
</code>```

H=2:

```<code>( )
( )
</code>```

H=3:

```<code>( )
( )
( )
</code>```

H will always be at least 1

N will determine how many items are in the stack. The following examples are all H = 2:

N=0

```<code>( )
( )
</code>```

N=1

```<code>( )
(-)
</code>```

N=2

```<code>(-)
(-)
</code>```

N=3

```<code> \
(-)
(-)
</code>```

N=4

```<code> \|
(-)
(-)
</code>```

N=5

```<code> \|/
(-)
(-)
</code>```

N=6

```<code>( )
</code>```0

N=7

```<code>( )
</code>```1

N will never be more than 2H+3 (In other words, the stack will never go through the ground).

Rules

No Standard Loopholes.

Your program must not produce any errors.

All test cases must pass.

You can input H and N any way you want.

I seriously doubt that your language has a built-in for this.

Each line may optionally have an extra space at the end. A blank line above a stack where N <= H is optional, as is a trailing newline.

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

Test Cases

In addition to all of the H=2 test cases from the Input/Output section, all of the following test cases must pass:

H=1, N=1

```<code>( )
</code>```2

H=1, N=5

```<code> \|/
(-)-
</code>```

H=4, N=7

```<code> \|/
(-)
(-)
(-)
(-)
</code>```

H=5, N=0

```<code>( )
( )
( )
( )
( )
</code>```

Leaderboards

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

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

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

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

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

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

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

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

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

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

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

```

Title: Stack Overflowing

Body:
C++11, <s>155</s> <s>148</s> 145 bytes

void f(int h,int n){cout<<string{" \\|/",max(min(3,n-h),0)+1}<<'\n';for(int i=0;i<h;++i)cout<<(h-i<=n?"(-)":"( )")<<(i<max(n-h-3,0)?"-\n":"\n");}

Ungolfed:

void f(int h,int n)
{
  cout << string{" \\|/", max(min(3, n-h), 0) + 1} << '\n';
  for(int i=0; i<h; ++i)
    cout << (h-i <= n ? "(-)" : "( )") << (i < max(n-h-3,0) ? "-\n" : "\n");
}

Usage:

#include <iostream>
#include <string>
using namespace std;

void f(int h,int n){cout<<string{" \\|/",max(min(3,n-h),0)+1}<<'\n';for(int i=0;i<h;++i)cout<<(h-i<=n?"(-)":"( )")<<(i<max(n-h-3,0)?"-\n":"\n");}

int main()
{
  int h,n;
  cin >> h >> n;
  f(h, n);
}