答:
Befunge, 15 bytes, James Holderness

```<code><:0:+1_@#%9,:g-
</code>```

Try it online!

Explanation

The catch here is that the loop terminates when the current character is divisible by 9, which is only the case for -. Hence, that needs to go at the end.

```<code><                 Run code from right to left.
              -   There will always be 2 zeros on top of the stack at this
                  point, and this just reduces them to 1 zero.
             g    Get the character at the coordinates given by the top
                  two stack values, (0, 0) initially.
           ,:     Print a copy of that character.
         %9       Modulo 9.
      _@#         Terminate if that is 0.
    +1            Increment the x coordinate.
   :              Duplicate it.
 :0               Push two zeros.
</code>```

Title: Quine Anagrams! (Robbers' Thread)

Body:
This is the robbers' thread. For the cops' thread, click here.

Cops' Task

For the cops' thread, click here.

Robbers' Task

Find an uncracked submission on the cops' thread. (A submission may only be cracked once.)

Unscramble the code to find a working quine.

Post an answer on the robbers' thread. Include the language, the byte count, the user who posted the scrambled code, a link to that answer, and the unscrambled code.

Here is an example of a robber submission:

Python, 29 bytes, Oliver

```<code>_='_=%r;print _%%_';print _%_
</code>```

Scoring

The user with the most cracks will be the winner of this section.

Body:
Befunge, 15 bytes, James Holderness

<:0:+1_@#%9,:g-

Try it online!

Explanation

The catch here is that the loop terminates when the current character is divisible by 9, which is only the case for -. Hence, that needs to go at the end.

<                 Run code from right to left.
              -   There will always be 2 zeros on top of the stack at this
                  point, and this just reduces them to 1 zero.
             g    Get the character at the coordinates given by the top
                  two stack values, (0, 0) initially.
           ,:     Print a copy of that character.
         %9       Modulo 9.
      _@#         Terminate if that is 0.
    +1            Increment the x coordinate.
   :              Duplicate it.
 :0               Push two zeros.


问:
Code ladder, Cops

Note: This challenge is finished. Submissions are still welcome but can not win.

This is the cops' thread. The robbers' thread goes here.

Write a code that outputs the integer 1. If you add, remove or substitute a single character (of your choosing), the code should output the integer 2. Change one more character (the same or another), and the code should output 3. Continue like this as far as you can, but maximum up to 10. Default output formats such as ans = 1 are accepted. You can ignore output to STDERR (or equivalent).

You must reveal the language, byte count of your initial code, the number of integers it works for, as well as an optional number of characters of the initial code. Note: You don't have to reveal any characters, but remember that revealing characters might make it harder for the robbers as they must use the same character in the same position. You can choose which character you use to denote unrevealed characters (for instance underscore), but make sure to specify this.

Cops can provide the uncracked code after one week and call the submission "SAFE". The winning submission will be the shortest uncracked submission that produces the number 10. If no uncracked submissions are able to print 10, the shortest code that produces 9 will win, and so on. Note that the robbers don't have to make the same changes as you do, and they don't have to reproduce the exact code (unless you reveal all characters). They must only reproduce the output.

Submissions posted later than November 24th are welcome but not eligible for the win (because there will likely be fewer robbers around).

Example post:

The following post is a submission in the language MyLang, it is 9 bytes long, and it works for numbers 1 - 8.

MyLang, 9 bytes, 8 numbers

This submission works for 1 - 8. Unrevealed characters are indicated with an underscore: _.

```<code>abc____i
</code>```

Leaderboard

Disclaimer: The leaderboard is not tested and uncracked submissions might not appear in the list.

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

Uncracked submissions

 Language	 Score	 User

Sort by: score creation

Safe submissions

 Language	 Score	 User

```

ContentLicense: CC BY-SA 3.0

Title: Code ladder, Cops

Body:
Python, 28 bytes, 10 numbers, cracked!

_____ (__________)_(_____*4)_

Intended solution:

print (ord("a"   )-(24   *4))


答:
PowerShell, 7 bytes, 10 numbers, Cracked

Works for 1 through 10. Hidden characters are _.

```<code>___(__0
</code>```

Intended solution: +!@()+0 and swap out the 0 on the end for successively larger numbers.

Title: Code ladder, Cops

Body:
Note: This challenge is finished. Submissions are still welcome but can not win.

This is the cops' thread. The robbers' thread goes here.

Write a code that outputs the integer 1. If you add, remove or substitute a single character (of your choosing), the code should output the integer 2. Change one more character (the same or another), and the code should output 3. Continue like this as far as you can, but maximum up to 10. Default output formats such as ans = 1 are accepted. You can ignore output to STDERR (or equivalent).

You must reveal the language, byte count of your initial code, the number of integers it works for, as well as an optional number of characters of the initial code. Note: You don't have to reveal any characters, but remember that revealing characters might make it harder for the robbers as they must use the same character in the same position. You can choose which character you use to denote unrevealed characters (for instance underscore), but make sure to specify this.

Cops can provide the uncracked code after one week and call the submission "SAFE". The winning submission will be the shortest uncracked submission that produces the number 10. If no uncracked submissions are able to print 10, the shortest code that produces 9 will win, and so on. Note that the robbers don't have to make the same changes as you do, and they don't have to reproduce the exact code (unless you reveal all characters). They must only reproduce the output.

Submissions posted later than November 24th are welcome but not eligible for the win (because there will likely be fewer robbers around).

Example post:

The following post is a submission in the language MyLang, it is 9 bytes long, and it works for numbers 1 - 8.

MyLang, 9 bytes, 8 numbers

This submission works for 1 - 8. Unrevealed characters are indicated with an underscore: _.

```<code>abc____i
</code>```

Leaderboard

Disclaimer: The leaderboard is not tested and uncracked submissions might not appear in the list.

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

Uncracked submissions

 Language	 Score	 User

Sort by: score creation

Safe submissions

 Language	 Score	 User

```

Body:
PowerShell, 7 bytes, 10 numbers, Cracked

Works for 1 through 10. Hidden characters are _.

___(__0

Intended solution: +!@()+0 and swap out the 0 on the end for successively larger numbers.


问:
Code ladder, Robbers
This is the robbers' thread. The cops' thread goes here.

Write a code that has the same number of bytes as the cop post and where the revealed characters are identical. The code must produce 1 in its initial state, and produce the numbers 2, 3 .. when single alterations are made.

The winner will be the robber that cracked the most posts.

Example post:

MyLang, 9 bytes, 8 numbers (including link to answer), Cop's username.

Original code:

```<code>abc1efghi
</code>```

Code that produces 1 - 8:

```<code>1: abc1efghi
2: abc2efghi
3: abc2efghij
4: kbc2efghij
5: kbc23fghij
6: kbc23fghi
7: kbc63fghi
8: kbc63fhi
</code>```

Explanations are encouraged. The exact format of the robber post is optional.

Title: Code ladder, Robbers

Body:
Python, 28 bytes, 10 numbers, by CrazyPython

print (0+1+0*1000)+(0*0*0*4)
print (1+1+0*1000)+(0*0*0*4)
print (2+1+0*1000)+(0*0*0*4)
...


问:
Quine Anagrams! (Robbers' Thread)
This is the robbers' thread. For the cops' thread, click here.

Cops' Task

For the cops' thread, click here.

Robbers' Task

Find an uncracked submission on the cops' thread. (A submission may only be cracked once.)

Unscramble the code to find a working quine.

Post an answer on the robbers' thread. Include the language, the byte count, the user who posted the scrambled code, a link to that answer, and the unscrambled code.

Here is an example of a robber submission:

Python, 29 bytes, Oliver

```<code>_='_=%r;print _%%_';print _%_
</code>```

Scoring

The user with the most cracks will be the winner of this section.

答:
MATL, 20 bytes, Luis Mendo

```<code>'wo&GzL0fk'tl#DwI-ch
</code>```

Try it online!

I've never used MATL before, so my understanding may be slightly off, but this is basically how it works:

```<code>'wo&GzL0fk' This is a string representation of the code, offset by 3
t           Creates a duplicate copy of the string
l#D         Adds quotes to the second copy
w           Swap the unquoted version to the top of the stack
I-          Offset the characters in that version by 3
c           Convert back to characters
h           Join with the quoted string
</code>```

Title: Quine Anagrams! (Robbers' Thread)

Body:
MATL, 20 bytes, Luis Mendo

'wo&GzL0fk'tl#DwI-ch

Try it online!

I've never used MATL before, so my understanding may be slightly off, but this is basically how it works:

'wo&GzL0fk' This is a string representation of the code, offset by 3
t           Creates a duplicate copy of the string
l#D         Adds quotes to the second copy
w           Swap the unquoted version to the top of the stack
I-          Offset the characters in that version by 3
c           Convert back to characters
h           Join with the quoted string


Title: Code ladder, Robbers

Body:
This is the robbers' thread. The cops' thread goes here.

Write a code that has the same number of bytes as the cop post and where the revealed characters are identical. The code must produce 1 in its initial state, and produce the numbers 2, 3 .. when single alterations are made.

The winner will be the robber that cracked the most posts.

Example post:

MyLang, 9 bytes, 8 numbers (including link to answer), Cop's username.

Original code:

```<code>abc1efghi
</code>```

Code that produces 1 - 8:

```<code>1: abc1efghi
2: abc2efghi
3: abc2efghij
4: kbc2efghij
5: kbc23fghij
6: kbc23fghi
7: kbc63fghi
8: kbc63fhi
</code>```

Explanations are encouraged. The exact format of the robber post is optional.

Body:
PowerShell, 7 bytes, 10 numbers, by TimmyD

Original code :

___(__0

Cracked code :

+1#(__0
+2#(__0
+3#(__0
...
+9#(__0
1+9#(__0


答:
Python 2, 17 bytes, 10 numbers, cracked

print len([????])
```

The hidden character is ?.

Title: Code ladder, Cops

Body:
Python 2, 17 bytes, 10 numbers, cracked

print len([????])

The hidden character is ?.


答:
Python 2, 17 bytes, 10 numbers, by xnor

print len(['  '])
print len(*['  '])
print len(*['   '])
print len(*['    '])
print len(*['     '])
print len(*['      '])
print len(*['       '])
print len(*['        '])
print len(*['         '])
print len(*['          '])
```

repl.it

Title: Code ladder, Robbers

Body:
Python 2, 17 bytes, 10 numbers, by xnor

print len(['  '])
print len(*['  '])
print len(*['   '])
print len(*['    '])
print len(*['     '])
print len(*['      '])
print len(*['       '])
print len(*['        '])
print len(*['         '])
print len(*['          '])

repl.it


答:
Haskell, 86 bytes, Laikoni

```<code>y!r=r:y:r:[y]>>=id;main=putStr$[succ$'!']!"y!r=r:y:r:[y]>>=id;main=putStr$[succ$'!']!"
</code>```

Nice idea to get the " via succ$'!' (ascii char after !). There were some missing chars to get them the usual way, i.e. implicitly via show or print.

Title: Quine Anagrams! (Robbers' Thread)

Body:
Haskell, 86 bytes, Laikoni

y!r=r:y:r:[y]>>=id;main=putStr$[succ$'!']!"y!r=r:y:r:[y]>>=id;main=putStr$[succ$'!']!"

Nice idea to get the " via succ$'!' (ascii char after !). There were some missing chars to get them the usual way, i.e. implicitly via show or print.


问:
Probability of All Combinations of Given Events
Given a sequences of events with probabilities between 0.0 and 1.0, generate and derive the probability of each combination occurring. You may presume that a sequence of numbers is provided in whatever construct your chosen language provides.

Here's an example; you may presume that the length of the sequence's combinations fit into memory:

```<code>{ 0.55, 0.67, 0.13 }
</code>```

The program shall print each combination and the associated probability of that sequence occurring. A 1 shall denote that the event in that index of the input sequence occurred and a 0 shall denote that that event did not occur. The desired output is below (I don't care about printing the work, that's just for informational purposes of the algorithm):

```<code>[0,0,0] = (1 - 0.55) * (1-0.67) * (1-0.13) = 0.129195
[0,0,1] = (1 - 0.55) * (1-0.67) * (0.13)   = 0.019305
[0,1,0] = (1 - 0.55) * (0.67)   * (1-0.13) = 0.262305
[0,1,1] = (1 - 0.55) * (0.67)   * (0.13)   = 0.039195
[1,0,0] = (0.55)     * (1-0.67) * (1-0.13) = 0.157905
[1,0,1] = (0.55)     * (1-0.67) * (0.13)   = 0.023595
[1,1,0] = (0.55)     * (0.67)   * (1-0.13) = 0.320595
[1,1,1] = (0.55)     * (0.67)   * (0.13)   = 0.047905
</code>```

This problem is tangentially related to calculating a "Cartesian product".

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

答:
C++17, <s>137</s> <s>131</s> 129 bytes

Saving 6 bytes by declaring #define A auto, first time that such a short macro saves anything. -2 bytes for using #import and deleting the space before <

#import<iostream>
#define A auto
A g(A r){std::cout<<r<<",";}A g(A r,A x,A...p){g(x*r,p...);g(r-x*r,p...);}A f(A...p){g(1,p...);}
```
<p>Spawns all possible combinations.</p>
<p>Ungolfed:</p>
<pre class="lang-c++ prettyprint-override"><code>//base case to print the result
int g(auto r){std::cout << r << ",";}

//extract item from parameter pack
int g(auto r, auto x, auto... p) {
 g(x*r,p...);    //multiply with temp result and call with tail
 g(r-x*r,p...);  //same as above for (1-x)
}

//start of recursion, setting temp result to 1
int f(auto...p){g(1,p...);}
</code>```

Usage:

f(0.55, 0.67, 0.13);
```

Body:
C++17, <s>137</s> <s>131</s> 129 bytes

Saving 6 bytes by declaring #define A auto, first time that such a short macro saves anything. -2 bytes for using #import and deleting the space before <

#import<iostream>
#define A auto
A g(A r){std::cout<<r<<",";}A g(A r,A x,A...p){g(x*r,p...);g(r-x*r,p...);}A f(A...p){g(1,p...);}

Spawns all possible combinations.

Ungolfed:

//base case to print the result
int g(auto r){std::cout << r << ",";}

//extract item from parameter pack
int g(auto r, auto x, auto... p) {
 g(x*r,p...);    //multiply with temp result and call with tail
 g(r-x*r,p...);  //same as above for (1-x)
}

//start of recursion, setting temp result to 1
int f(auto...p){g(1,p...);}

Usage:

f(0.55, 0.67, 0.13);


问:
Code close to the challenge: Sum of integers
This is a simple challenge:
Given a sequence of integers, find the sum of all integers in it.

But with a twist.
Your score is the Levenshtein distance between your code and the following phrase (The challenge):

Given a set of integers, find the sum of all integers in it.

You may assume there are no newlines or trailing spaces in the input.

Example input/output:

```<code>Input: 1 5 -6 2 4 5
Output: 11
Input: 1 -2 10
Output: 9
</code>```

An online calculator for Levenshtein distance can be found here: http://planetcalc.com/1721/

答:
RProgN, Distance 2.

```<code>Given aset of integers, ;find the sum of all integers in it.
</code>```

In RProgN, a, set, find and sum are all commands. Everything else is per default ignored in syntax. a pushes the alphabet to the stack, which will cause sum to fail. Set never has enough arguments, so always fails, erroring. Find either has the wrong number of arguments, or tries to compare the alphabet with the input stack, which doesn't work.

a and set can both be 'fixed' by removing the space between then, aset is not a function, so it's ignored. Find just has an extra character inserted at the start, causing it also to not be recognized, and ignored. Only sum is left, which conveniently sums the contents of the input stack.

Finally, RProgN might win something!

Try it Online!

Body:
RProgN, Distance 2.

Given aset of integers, ;find the sum of all integers in it.

In RProgN, a, set, find and sum are all commands. Everything else is per default ignored in syntax. a pushes the alphabet to the stack, which will cause sum to fail. Set never has enough arguments, so always fails, erroring. Find either has the wrong number of arguments, or tries to compare the alphabet with the input stack, which doesn't work.

a and set can both be 'fixed' by removing the space between then, aset is not a function, so it's ignored. Find just has an extra character inserted at the start, causing it also to not be recognized, and ignored. Only sum is left, which conveniently sums the contents of the input stack.

Finally, RProgN might win something!

Try it Online!


问:
Draw diagonal lines of text
Given an input of a list of words, output the words with their letters arranged
diagonally:

```<code>p
 r
  o
p  g
 u  r
  z  a
a  z  m
 n  l  m
  d  e  i
c     s  n
 o        g
  d
g  e
 o
  l
   f
</code>```

(The above should be the output for the input programming puzzles and code golf.)

To be precise, each word starts on the first column and three rows below the
previous word, and each successive letter moves one column to the right and one
row down.

The input may be provided as either a single string of words, separated by
exactly one space, or a list/array of words. The words will only be composed of
lowercase letters, a-z, and will always be at least one character long.

The output may be a single string, an array of lines, or an array of arrays of
characters. Leading or trailing whitespace is not allowed, except for a single
trailing newline.

Further test cases:

a bcd efgh i j

```<code>a

b
 c
  d
e
 f
  g
i  h

j
</code>```

x

```<code>x
</code>```

verylongword short

```<code>v
 e
  r
s  y
 h  l
  o  o
   r  n
    t  g
        w
         o
          r
           d
</code>```

Since this is code-golf, the shortest code in bytes will win!

答:
JavaScript (ES6), <s>118</s> <s>109</s> 84 bytes

Takes input as an array of words. Returns an array of arrays of characters.

s=>s.map((w,y)=>[...w].map((c,x)=>(a[p=y*3+x]=a[p]||Array(x).fill(' '))[x]=c),a=[])&&a
```

<h3>Alternative version, 109 bytes</h3>

<p>Returns a string.</p>

<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>let f =

s=>s.map((w,y)=>[...w].map((c,x)=>(a[p=y*3+x]=a[p]||Array(x).fill` `)[x]=c),a=[])&&a.map(s=>s.join``).join`
`

console.log(f(["programming", "puzzles", "and", "code", "golf"]))</code>```

Title: Draw diagonal lines of text

Body:
JavaScript (ES6), <s>118</s> <s>109</s> 84 bytes

Takes input as an array of words. Returns an array of arrays of characters.

s=>s.map((w,y)=>[...w].map((c,x)=>(a[p=y*3+x]=a[p]||Array(x).fill(' '))[x]=c),a=[])&&a

Alternative version, 109 bytes

Returns a string.

let f =

s=>s.map((w,y)=>[...w].map((c,x)=>(a[p=y*3+x]=a[p]||Array(x).fill` `)[x]=c),a=[])&&a.map(s=>s.join``).join`
`

console.log(f(["programming", "puzzles", "and", "code", "golf"]))


问:
Steganographic Squares

Steganographic Squares

Your job is to take in a string, and generate an NxN image that represents this string. You must also write the algorithm that takes in the image and turns it back into a string as well. The scoring will be will include the byte count of both algorithms:

"Encryption" Algorithm + "Decryption" Algorithm.

You should post each separately, with byte-counts for both the encryption and decryption algorithms displayed individually.

Example Algorithm

For instance, here's the "Programming Puzzles and Code Golf" using a simple ASCII based steganographic algorithm in the Blue channel:

```<code>#2e7250,#6ea972,#04eb6f,#0fc767,#74ab72,#ee6161
#b73b6d,#1aae6d,#f37169,#bda56e,#1fe367,#e99620
#706450,#0d3575,#146b7a,#4ea47a,#2a856c,#95d065
#3f2d73,#cef720,#bab661,#d1b86e,#f22564,#12b820
#0f3d43,#c86e6f,#1ee864,#a66565,#247c20,#c3bb47
#0e296f,#89d46c,#585b66,#c08f20,#455c20,#136f20
</code>```

Actual Image (  )

You can see the blue channel simply holds the ascii values for this image:

```<code>50 =  80(P) 72 = 114(r) 6f = 111(o) 67 = 103(g) 72 = 114(r) 61 =  97(a)
6d = 109(m) 6d = 109(m) 69 = 105(i) 6e = 110(n) 67 = 103(g) 20 =  32( )
50 =  80(P) 75 = 117(u) 7a = 122(z) 7a = 122(z) 6c = 108(l) 65 = 101(e)
73 = 115(s) 20 =  32( ) 61 =  97(a) 6e = 110(n) 64 = 100(d) 20 =  32( )
43 =  67(C) 6f = 111(o) 64 = 100(d) 65 = 101(e) 20 =  32( ) 47 =  71(G)
6f = 111(o) 6c = 108(l) 66 = 102(f) 20 =  32( ) 20 =  32( ) 20 =  32( )
</code>```

While the rest of the channels hold randomly generated values to "spice up" the variety of colors in the image. When pulling the message back out of the image, we can just simply ignore the other channel values, and pull the hex bit in the blue channel, reconstructing the string:

```<code>"Programming Puzzles and Code Golf"
</code>```

Notice the spaces that were used to pad the string in the square are not included in the final decrypted output. While you must pad the string in the image, you may assume that the input string will not end with spaces.

Rules

You must encode 1 character per pixel, the channel chosen to encode the char is arbitrary.

The channels of the other RGB colors must be randomized, other than the one you're choosing to encode the string into; this means your final non-encoded channels would need to be between 0x0000-0xFFFF (randomly chosen).

Expressing the final result as a 2D array of RGB color values is fine 0x000000-0xFFFFFF, no need to use image creation unless you want to have fun with it or if it's less bytes. If you choose to output as hex strings, prefix the hex string with # E.G. #FFFFFF or #05AB1E. You may separate with tabs, commas, or anything else that would be horizontally sensible, but it must maintain the square pattern; in other words, you must use appropriate newline separation.

The output must be in a square, and the string must be padded with spaces at the end to accomodate this. This means that N≈SQRT(Input#Length()). If the input length is not a perfect square, you should round up on N and pad with spaces.

As stated previously, if you are padding with spaces in the image, you must not include the padded characters in the final "decrypted" output.

You can assume that:

The input string will not end with spaces.

The input string will only use printable ASCII characters.

This is code-golf, lowest byte count wins.

答:
C, 201 (Encoding) + 175 (Decoding) = 376 bytes

To Encode:

```<code>E(char*J){size_t L=ceil(sqrt(strlen(J)));int U;srand(time(NULL));for(int i=0;i<L;i++){for(int f=0;f<L;f++){printf("#%02X%02X%02X ",rand()%256,(U<strlen(J))?(int)J[U]:32,rand()%256);U+=1;}printf("\n");}}
</code>```

Encodes each character of the input string in the green channel of the RGB spectrum while setting the two other channels as random hex values. Takes input through STDIN as a string and outputs to STDOUT a multiline string of hex color code in the shape of a square. Assuming you have Python 3 and ImageMagick installed, and the above file is compiled into a file named a.out in the current working directory (CWD), you can directly get the resulting image, named Output.png, to the CWD from the textual output using the following command:

```<code>./a.out "<Multiline Input>"|python3 -c "import sys,subprocess;Input=sys.stdin.read();print('# ImageMagick pixel enumeration: {0},{0},255,rgb\n'.format(len(Input.split('\n')[1].split()))+'\n'.join(['%d,%d:(%d,%d,%d)'%(g,i,int(j[1:][:2],16),int(j[1:][2:4],16),int(j[1:][4:6],16))for g,h in enumerate(Input.split('\n'))for i,j in enumerate(h.split())]))"|convert - -scale 1000% Output.png
</code>```

Here is a sample output image created by the above commamd using Programming Puzzles and Code Golf as the input string:

To Decode:

```<code>D(int c,char**U){char T[c];for(int Y=1;Y<c;Y++){char G[2]={U[Y][3],U[Y][4]};T[Y-1]=(char)strtol(G,NULL,16);}int C=c-1;T[C]='\0';while(T[C]==' '){T[C]='\0';C-=1;}printf("%s\n",T);}
</code>```

Takes input through STDIN a sequence of space-separated hex color code strings with each one enclosed in double quotes (") (char** argv in main) and also, when called in main, int argc for the integer input. Outputs to STDOUT a single/multi-line string representing the decoded message.

I will try to golf these more over time whenever and wherever I can.

Also, if you same both of the methods into the same file, you can use the following main method to put it all together with each function getting the correct inputs:

```<code>int main(int argc,char**argv){if(strcmp(argv[1],"E")==0){Encode(argv[2]);}else{Decode(argc,argv);}}
</code>```

and using this, for encoding you must provide E as the first argument to call the encoding method followed by the single string argument, whereas for decoding, all you need to provide is the sequence of space-separated hex color code strings with each one enclosed in double-quotes (").

Finally, if you want, you can get the fully prepared, ready-to-use version here, although it is not golfed, but also does not output any warnings or errors upon compilation.

Title: Steganographic Squares

Body:
C, 201 (Encoding) + 175 (Decoding) = 376 bytes

To Encode:

E(char*J){size_t L=ceil(sqrt(strlen(J)));int U;srand(time(NULL));for(int i=0;i<L;i++){for(int f=0;f<L;f++){printf("#%02X%02X%02X ",rand()%256,(U<strlen(J))?(int)J[U]:32,rand()%256);U+=1;}printf("\n");}}

Encodes each character of the input string in the green channel of the RGB spectrum while setting the two other channels as random hex values. Takes input through STDIN as a string and outputs to STDOUT a multiline string of hex color code in the shape of a square. Assuming you have Python 3 and ImageMagick installed, and the above file is compiled into a file named a.out in the current working directory (CWD), you can directly get the resulting image, named Output.png, to the CWD from the textual output using the following command:

./a.out "<Multiline Input>"|python3 -c "import sys,subprocess;Input=sys.stdin.read();print('# ImageMagick pixel enumeration: {0},{0},255,rgb\n'.format(len(Input.split('\n')[1].split()))+'\n'.join(['%d,%d:(%d,%d,%d)'%(g,i,int(j[1:][:2],16),int(j[1:][2:4],16),int(j[1:][4:6],16))for g,h in enumerate(Input.split('\n'))for i,j in enumerate(h.split())]))"|convert - -scale 1000% Output.png

Here is a sample output image created by the above commamd using Programming Puzzles and Code Golf as the input string:

To Decode:

D(int c,char**U){char T[c];for(int Y=1;Y<c;Y++){char G[2]={U[Y][3],U[Y][4]};T[Y-1]=(char)strtol(G,NULL,16);}int C=c-1;T[C]='\0';while(T[C]==' '){T[C]='\0';C-=1;}printf("%s\n",T);}

Takes input through STDIN a sequence of space-separated hex color code strings with each one enclosed in double quotes (") (char** argv in main) and also, when called in main, int argc for the integer input. Outputs to STDOUT a single/multi-line string representing the decoded message.

I will try to golf these more over time whenever and wherever I can.

Also, if you same both of the methods into the same file, you can use the following main method to put it all together with each function getting the correct inputs:

int main(int argc,char**argv){if(strcmp(argv[1],"E")==0){Encode(argv[2]);}else{Decode(argc,argv);}}

and using this, for encoding you must provide E as the first argument to call the encoding method followed by the single string argument, whereas for decoding, all you need to provide is the sequence of space-separated hex color code strings with each one enclosed in double-quotes (").

Finally, if you want, you can get the fully prepared, ready-to-use version here, although it is not golfed, but also does not output any warnings or errors upon compilation.


答:
MATL, 28 bytes

```<code>c!t&n:q3_*ts_b+5M4$XdZ!cZ{Zv
</code>```

Input is a cell array of strings, with commas as optional separators:

```<code>{'programming' 'puzzles' 'and' 'code' 'golf'}
</code>```

or

```<code>{'programming', 'puzzles', 'and', 'code', 'golf'}
</code>```

Try it online! Or verify all test cases: 1, 2, 3, 4.

Explanation

Consider the following input as an example:

```<code>{'aaaa' 'bb' 'ccc'}
</code>```

You can view the partial results (stack contents) inserting the comment symbol % at any point in the code. For example, view the stack contents after the fourth function (&n).

```<code>c        % Input cell array of strings implicitly. Convert to 2D char array,
         % right-padding with spaces
         % STACK: ['aaaa'; 'bb  '; 'ccc']
!        % Transpose
         % STACK: ['abc'
                   'abc'
                   'a c'
                   'a  ']
t        % Duplicate
         % STACK: ['abc'
                   'abc'
                   'a c'
                   'a  '],
                  ['abc'
                   'abc'
                   'a c'
                   'a  '],
&n       % Number of rows and of columns
         % STACK: ['abc'
                   'abc'
                   'a c'
                   'a  '], 4, 3
:q       % Range, subtract 1
         % STACK: ['abc'
                   'abc'
                   'a c'
                   'a  '], 4, [0 1 2]
3_*      % Multiply by -3
         % STACK: ['abc'
                   'abc'
                   'a c'
                   'a  '], 4, [0 -3 -6]
ts_      % Duplicate, sum, negate
         % STACK: ['abc'
                   'abc'
                   'a c'
                   'a  '], 4, [0 -3 -6], 9
b        % Bubble up in stack
         % STACK: ['abc'
                   'abc'
                   'a c'
                   'a  '], [0 -3 -6], 9, 4
+        % Add
         % STACK: ['abc'
                   'abc'
                   'a c'
                   'a  '], [0 -3 -6], 13
5M       % Push second input of last function again
         % STACK: ['abc'
                   'abc'
                   'a c'
                   'a  '], [0 -3 -6], 13, 4
4$Xd     % Buld numerical sparse matrix from the above four arguments. The
         % columns of the first input argument will be the diagonals of the
         % result, with indices given bu the second input (negative is below
         % main diagonal). The matrix size is the third and fourth arguments
         % STACK: [97  0  0  0
                    0 97  0  0
                    0  0 97  0
                   98  0  0 97
                    0 98  0  0
                    0  0 32  0
                   99  0  0 32
                    0 99  0  0
                    0  0 99  0
                    0  0  0 32
                    0  0  0  0
                    0  0  0  0
                    0  0  0  0]
Z!c      % Convert from sparse to full, and then to char. Character 0 is
         % displayed as space
         % STACK: ['a   '
                   ' a  '
                   '  a '
                   'b  a'
                   ' b  '
                   '    '
                   'c   '
                   ' c  '
                   '  c '
                   '    '
                   '    '
                   '    '
                   '    ']
Z{       % Split into cell array, with each row in a cell
         % STACK: {'a   ', ' a  ', '  a ', 'b  a', ' b  ', '    ', 'c   ', ' c  ', '  c ', '   ', '   ', '   ', '   '}
Zv       % Deblank: remove trailing space from each string. Implicitly display,
         % each string on a different line. Empty strings do not generate
         % a newline
         % STACK: {'a   ', ' a', '  a', 'b  a', ' b', '', 'c', ' c', '  c', '', '', '', ''}
</code>```

Title: Draw diagonal lines of text

Body:
Given an input of a list of words, output the words with their letters arranged
diagonally:

```<code>p
 r
  o
p  g
 u  r
  z  a
a  z  m
 n  l  m
  d  e  i
c     s  n
 o        g
  d
g  e
 o
  l
   f
</code>```

(The above should be the output for the input programming puzzles and code golf.)

To be precise, each word starts on the first column and three rows below the
previous word, and each successive letter moves one column to the right and one
row down.

The input may be provided as either a single string of words, separated by
exactly one space, or a list/array of words. The words will only be composed of
lowercase letters, a-z, and will always be at least one character long.

The output may be a single string, an array of lines, or an array of arrays of
characters. Leading or trailing whitespace is not allowed, except for a single
trailing newline.

Further test cases:

a bcd efgh i j

```<code>a

b
 c
  d
e
 f
  g
i  h

j
</code>```

x

```<code>x
</code>```

verylongword short

```<code>v
 e
  r
s  y
 h  l
  o  o
   r  n
    t  g
        w
         o
          r
           d
</code>```

Since this is code-golf, the shortest code in bytes will win!

Body:
MATL, 28 bytes

c!t&n:q3_*ts_b+5M4$XdZ!cZ{Zv

Input is a cell array of strings, with commas as optional separators:

{'programming' 'puzzles' 'and' 'code' 'golf'}

or

{'programming', 'puzzles', 'and', 'code', 'golf'}

Try it online! Or verify all test cases: 1, 2, 3, 4.

Explanation

Consider the following input as an example:

{'aaaa' 'bb' 'ccc'}

You can view the partial results (stack contents) inserting the comment symbol % at any point in the code. For example, view the stack contents after the fourth function (&n).

c        % Input cell array of strings implicitly. Convert to 2D char array,
         % right-padding with spaces
         % STACK: ['aaaa'; 'bb  '; 'ccc']
!        % Transpose
         % STACK: ['abc'
                   'abc'
                   'a c'
                   'a  ']
t        % Duplicate
         % STACK: ['abc'
                   'abc'
                   'a c'
                   'a  '],
                  ['abc'
                   'abc'
                   'a c'
                   'a  '],
&n       % Number of rows and of columns
         % STACK: ['abc'
                   'abc'
                   'a c'
                   'a  '], 4, 3
:q       % Range, subtract 1
         % STACK: ['abc'
                   'abc'
                   'a c'
                   'a  '], 4, [0 1 2]
3_*      % Multiply by -3
         % STACK: ['abc'
                   'abc'
                   'a c'
                   'a  '], 4, [0 -3 -6]
ts_      % Duplicate, sum, negate
         % STACK: ['abc'
                   'abc'
                   'a c'
                   'a  '], 4, [0 -3 -6], 9
b        % Bubble up in stack
         % STACK: ['abc'
                   'abc'
                   'a c'
                   'a  '], [0 -3 -6], 9, 4
+        % Add
         % STACK: ['abc'
                   'abc'
                   'a c'
                   'a  '], [0 -3 -6], 13
5M       % Push second input of last function again
         % STACK: ['abc'
                   'abc'
                   'a c'
                   'a  '], [0 -3 -6], 13, 4
4$Xd     % Buld numerical sparse matrix from the above four arguments. The
         % columns of the first input argument will be the diagonals of the
         % result, with indices given bu the second input (negative is below
         % main diagonal). The matrix size is the third and fourth arguments
         % STACK: [97  0  0  0
                    0 97  0  0
                    0  0 97  0
                   98  0  0 97
                    0 98  0  0
                    0  0 32  0
                   99  0  0 32
                    0 99  0  0
                    0  0 99  0
                    0  0  0 32
                    0  0  0  0
                    0  0  0  0
                    0  0  0  0]
Z!c      % Convert from sparse to full, and then to char. Character 0 is
         % displayed as space
         % STACK: ['a   '
                   ' a  '
                   '  a '
                   'b  a'
                   ' b  '
                   '    '
                   'c   '
                   ' c  '
                   '  c '
                   '    '
                   '    '
                   '    '
                   '    ']
Z{       % Split into cell array, with each row in a cell
         % STACK: {'a   ', ' a  ', '  a ', 'b  a', ' b  ', '    ', 'c   ', ' c  ', '  c ', '   ', '   ', '   ', '   '}
Zv       % Deblank: remove trailing space from each string. Implicitly display,
         % each string on a different line. Empty strings do not generate
         % a newline
         % STACK: {'a   ', ' a', '  a', 'b  a', ' b', '', 'c', ' c', '  c', '', '', '', ''}


问:
Polygonal Numbers!

Introduction

In mathematics, a polygonal number is a number represented as dots or pebbles arranged in the shape of a regular polygon. The dots are thought of as alphas (units). These are one type of 2-dimensional figurate numbers.

The number 10, for example, can be arranged as a triangle:

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

But 10 cannot be arranged as a square. The number 9, on the other hand, can be:

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

Some numbers, like 36, can be arranged both as a square and as a triangle:

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

By convention, 1 is the first polygonal number for any number of sides. The rule for enlarging the polygon to the next size is to extend two adjacent arms by one point and to then add the required extra sides between those points. In the following diagrams, each extra layer is shown as in red.

Triangular Numbers:

Square Numbers:

Polygons with higher numbers of sides, such as pentagons and hexagons, can also be constructed according to this rule, although the dots will no longer form a perfectly regular lattice like above.

Pentagonal Numbers:

Hexagonal Numbers:

Source: Wikipedia

Your task

Given a positive integer N (1 <= N <= 1000), print every type of Polygonal Number N is starting from Triangular Numbers up to and including Icosagonal (20-gon) Numbers.

For example, the number 10 is a triangular number and a decagonal number, so the output should be something like (you can choose your own output format, but it should look somewhat like this):

```<code>3 10
</code>```

Test cases

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

For reference, the n-th k-gonal number is:

Credit: xnor

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

答:
Python 3, 68 bytes

lambda R:[s+2for s in range(1,19)if(s-2+(4+s*(s-4+8*R))**.5)/2%s==0]
```

<p>For each potential number of sides <code>s+2</code>, solves the quadratic formula <code>R=s*n*(n-1)/2 + n</code> for <code>n</code> to see if the result is a whole number.</p>

<p>Compare (73 bytes):</p>

<pre class="lang-python prettyprint-override"><code>lambda R:[s+2for s in range(1,19)if R in[n+s*n*~-n/2for n in range(R+1)]]
</code>```

An alternative approach of solving for s gives 62 bytes in Python 3, but fails on R=1.

lambda R:{(R-n)*2/n/~-n+2for n in range(2,R+1)}&{*range(3,21)}
```

Title: Polygonal Numbers!

Body:
Python 3, 68 bytes

lambda R:[s+2for s in range(1,19)if(s-2+(4+s*(s-4+8*R))**.5)/2%s==0]

For each potential number of sides s+2, solves the quadratic formula R=s*n*(n-1)/2 + n for n to see if the result is a whole number.

Compare (73 bytes):

lambda R:[s+2for s in range(1,19)if R in[n+s*n*~-n/2for n in range(R+1)]]

An alternative approach of solving for s gives 62 bytes in Python 3, but fails on R=1.

lambda R:{(R-n)*2/n/~-n+2for n in range(2,R+1)}&{*range(3,21)}


问:
Print the tetration

Tetration, represented as \${}^ba\$, is repeated exponentiation. For example, \${}^32\$ is \$2^{2^2}\$, which is \$16\$.

Given two numbers \$a\$ and \$b\$, print \${}^ba\$.

Test cases

```<code>1 2 -> 1
2 2 -> 4
5 2 -> 3125
3 3 -> 7625597484987
etc.
</code>```

Scientific notation is acceptable.

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

答:
C, 50 bytes

double t(int x,int n){return n?pow(x,t(x,n-1)):1;}
```

Straightforward from the definition of Tetration.

ContentLicense: CC BY-SA 4.0

Title: Print the tetration

Body:
C, 50 bytes

double t(int x,int n){return n?pow(x,t(x,n-1)):1;}

Straightforward from the definition of Tetration.


答:
Vim, <s>85, 76, 66</s>, 52 keystrokes/bytes

When I first looked at this challenge, I thought "This is perfect for vim!" And then when I tried it everything went wrong. Here it is, in all of it's messy hacky glory:

```<code>:se ve=all|s/ /\r\r\r/g
qqGo<esc>?\<.\S
lDjP@qq@qG?.
jdG
</code>```

Try it online, thanks to the (mostly) backwards compatible V interpreter.

Explanation:

At first I thought I could do this beautifully simple 37 byte version:

```<code>:se ve=all
qq:g/\S\S/norm ^lDjP
@qq@q
</code>```

Unfortunately, it's not that simple. Let's take it line by line:

```<code>:se ve=all
</code>```

This enables a feature called 'virtual editing'. It allows the cursor to move to columns that don't exist yet. This answer would be basically impossible without it.

Now we need to separate out the words onto different lines. So we'll replace each space with 3 newlines. Since this is an ex command we can run it simultaneously with our last ex command :se ve=all by seperating the two with a bar.

```<code>|s/ /\r\r\r/g
</code>```

Now the buffer looks like this:

```<code>Programming

Puzzles

and

code-golf
</code>```

Here's where the fun begins. We set up the traditional recursive macro with: qq, and then call this:

```<code>G               " Move to the last line
 o<esc>         " Append an extra newline

?               " Search backwards for
 \<.            " Any character at the beginning of a word
    \S          " Followed by a non-space character
l               " Move one character to the right
 D              " Delete eveything until the end of this line
  j             " Move down one line
   P            " Paste what we just deleted
</code>```

Then we finish the recursive macro with @qq@q. At this point, we have all of the diagonals, we just need to do a little clean up.

```<code>G                   " Move to the last line
 ?.                 " Search backwards for any character
j                   " Move down one line
 dG                 " Delete until the end of the buffer
</code>```

Title: Draw diagonal lines of text

Body:
Vim, <s>85, 76, 66</s>, 52 keystrokes/bytes

When I first looked at this challenge, I thought "This is perfect for vim!" And then when I tried it everything went wrong. Here it is, in all of it's messy hacky glory:

:se ve=all|s/ /\r\r\r/g
qqGo<esc>?\<.\S
lDjP@qq@qG?.
jdG

Try it online, thanks to the (mostly) backwards compatible V interpreter.

Explanation:

At first I thought I could do this beautifully simple 37 byte version:

:se ve=all
qq:g/\S\S/norm ^lDjP
@qq@q

Unfortunately, it's not that simple. Let's take it line by line:

:se ve=all

This enables a feature called 'virtual editing'. It allows the cursor to move to columns that don't exist yet. This answer would be basically impossible without it.

Now we need to separate out the words onto different lines. So we'll replace each space with 3 newlines. Since this is an ex command we can run it simultaneously with our last ex command :se ve=all by seperating the two with a bar.

|s/ /\r\r\r/g

Now the buffer looks like this:

Programming

Puzzles

and

code-golf

Here's where the fun begins. We set up the traditional recursive macro with: qq, and then call this:

G               " Move to the last line
 o<esc>         " Append an extra newline

?               " Search backwards for
 \<.            " Any character at the beginning of a word
    \S          " Followed by a non-space character
l               " Move one character to the right
 D              " Delete eveything until the end of this line
  j             " Move down one line
   P            " Paste what we just deleted

Then we finish the recursive macro with @qq@q. At this point, we have all of the diagonals, we just need to do a little clean up.

G                   " Move to the last line
 ?.                 " Search backwards for any character
j                   " Move down one line
 dG                 " Delete until the end of the buffer


答:
Dyalog APL, 10 bytes

New Solution

Index origin independent. Anonymous function. Takes probabilities list as argument.

∘.×/⊢,¨1-⊢
```

<p><code>∘.×/</code> The Cartesian product reduction over</p>

<p><code>⊢</code> the argument values</p>

<p><code>,¨</code> each paired up with</p>

<p><code>1-⊢</code> the complement argument values (lit. one minus the argument values)</p>

<p>TryAPL online!</p>

<hr>

<h2>Old Solution</h2>

<p>Requires <code>⎕IO←0</code> which is default on many systems. Prompts for probabilities' list.</p>

<pre class="lang-apl prettyprint-override"><code>|⎕∘.×.-⊂⍳2
</code>```

Explanation

| absolute value of

⎕ the input, ɑ = [ɑ₁ ɑ₂ ɑ₃]

∘.×.- modified inner tensor multiplied, (ɑ₁ – b₁) ⊗ (ɑ₂ – b₂) ⊗ (ɑ₃ – b₃), with

⊂⍳2 the enclosed list b = [[0 1]]

Mathematical definition

As b is enclosed, it is scalar, and therefore extended to the length of ɑ, namely 3, so the entire expression is

 A = │(ɑ₁ – b) ⊗ (ɑ₂ – b) ⊗ (ɑ₃ – b)│ =

 │(ɑ₁ – [0,1]) ⊗ (ɑ₂ – [0,1]) ⊗ (ɑ₃ – [0,1])│ =

 │[ɑ₁,ɑ₁ – 1] ⊗ [ɑ₂, ɑ₂ – 1] ⊗ [ɑ₃,ɑ₃ – 1]│ =

 ⎢ ⎡ ⎡  ɑ₁ɑ₂ɑ₃  ⎤ ⎡  ɑ₁ɑ₂(ɑ₃-1)  ⎤ ⎤ ⎥

 ⎢ ⎢ ⎣  ɑ₁(ɑ₂-1)ɑ₃  ⎦ ⎣  ɑ₁(ɑ₂-1)(ɑ₃-1)  ⎦ ⎥ ⎥

 ⎢ ⎢ ⎡  (ɑ₁-1)ɑ₂ɑ₃  ⎤ ⎡  (ɑ₁-1)ɑ₂(ɑ₃-1)  ⎤ ⎥ ⎥

 ⎢ ⎣ ⎣(ɑ₁-1)(ɑ₂-1)ɑ₃⎦ ⎣(ɑ₁-1)(ɑ₂-1)(ɑ₃-1)⎦ ⎦ ⎥

TryAPL online!

Notes (applies to both old and new solution)

The program and formula works for any number (n) of variables, and returns an n-dimensional array of length 2 in every dimension. With three variables, the probability of a specific outcome

 P(p,q,r) = Ap,q,r

which can conveniently be selected from the array with (⊃A)[p;q;r] extracted with p q r⌷⊃A

E.g. 1 1 0⌷⊃|0.55 0.67 0.13∘.×.-⊂⍳2 gives P(55%,  67%, ¬13%) = 1.9305%

Title: Probability of All Combinations of Given Events

Body:
Given a sequences of events with probabilities between 0.0 and 1.0, generate and derive the probability of each combination occurring. You may presume that a sequence of numbers is provided in whatever construct your chosen language provides.

Here's an example; you may presume that the length of the sequence's combinations fit into memory:

```<code>{ 0.55, 0.67, 0.13 }
</code>```

The program shall print each combination and the associated probability of that sequence occurring. A 1 shall denote that the event in that index of the input sequence occurred and a 0 shall denote that that event did not occur. The desired output is below (I don't care about printing the work, that's just for informational purposes of the algorithm):

```<code>[0,0,0] = (1 - 0.55) * (1-0.67) * (1-0.13) = 0.129195
[0,0,1] = (1 - 0.55) * (1-0.67) * (0.13)   = 0.019305
[0,1,0] = (1 - 0.55) * (0.67)   * (1-0.13) = 0.262305
[0,1,1] = (1 - 0.55) * (0.67)   * (0.13)   = 0.039195
[1,0,0] = (0.55)     * (1-0.67) * (1-0.13) = 0.157905
[1,0,1] = (0.55)     * (1-0.67) * (0.13)   = 0.023595
[1,1,0] = (0.55)     * (0.67)   * (1-0.13) = 0.320595
[1,1,1] = (0.55)     * (0.67)   * (0.13)   = 0.047905
</code>```

This problem is tangentially related to calculating a "Cartesian product".

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

Body:
Dyalog APL, 10 bytes

New Solution

Index origin independent. Anonymous function. Takes probabilities list as argument.

∘.×/⊢,¨1-⊢

∘.×/ The Cartesian product reduction over

⊢ the argument values

,¨ each paired up with

1-⊢ the complement argument values (lit. one minus the argument values)

TryAPL online!

Old Solution

Requires ⎕IO←0 which is default on many systems. Prompts for probabilities' list.

|⎕∘.×.-⊂⍳2

Explanation

| absolute value of

⎕ the input, ɑ = [ɑ₁ ɑ₂ ɑ₃]

∘.×.- modified inner tensor multiplied, (ɑ₁ – b₁) ⊗ (ɑ₂ – b₂) ⊗ (ɑ₃ – b₃), with

⊂⍳2 the enclosed list b = [[0 1]]

Mathematical definition

As b is enclosed, it is scalar, and therefore extended to the length of ɑ, namely 3, so the entire expression is

 A = │(ɑ₁ – b) ⊗ (ɑ₂ – b) ⊗ (ɑ₃ – b)│ =

 │(ɑ₁ – [0,1]) ⊗ (ɑ₂ – [0,1]) ⊗ (ɑ₃ – [0,1])│ =

 │[ɑ₁,ɑ₁ – 1] ⊗ [ɑ₂, ɑ₂ – 1] ⊗ [ɑ₃,ɑ₃ – 1]│ =

 ⎢ ⎡ ⎡  ɑ₁ɑ₂ɑ₃  ⎤ ⎡  ɑ₁ɑ₂(ɑ₃-1)  ⎤ ⎤ ⎥

 ⎢ ⎢ ⎣  ɑ₁(ɑ₂-1)ɑ₃  ⎦ ⎣  ɑ₁(ɑ₂-1)(ɑ₃-1)  ⎦ ⎥ ⎥

 ⎢ ⎢ ⎡  (ɑ₁-1)ɑ₂ɑ₃  ⎤ ⎡  (ɑ₁-1)ɑ₂(ɑ₃-1)  ⎤ ⎥ ⎥

 ⎢ ⎣ ⎣(ɑ₁-1)(ɑ₂-1)ɑ₃⎦ ⎣(ɑ₁-1)(ɑ₂-1)(ɑ₃-1)⎦ ⎦ ⎥

TryAPL online!

Notes (applies to both old and new solution)

The program and formula works for any number (n) of variables, and returns an n-dimensional array of length 2 in every dimension. With three variables, the probability of a specific outcome

 P(p,q,r) = Ap,q,r

which can conveniently be selected from the array with (⊃A)[p;q;r] extracted with p q r⌷⊃A

E.g. 1 1 0⌷⊃|0.55 0.67 0.13∘.×.-⊂⍳2 gives P(55%,  67%, ¬13%) = 1.9305%


问:
Armistice Day Challenge
Today, November 11th, is known as Remembrance Day, Armistice Day, or Veterans Day (depending upon the country), and is a day of reflection and gratitude for members of the military and their service, specifically started to reflect the end of European hostilities in the first World War. Let us reflect on that with a simple ASCII-art output of 11/11.

Given an input n, output an ASCII-art rendition of 11/11 that is n units tall. Specifically, each 1 is composed of vertical pipes ||, the slash is composed of slashes //, and each character is two spaces apart. Note that this means varying output widths -- for example, for n=3 below, see how the "bottom" of the slash is two spaces from the 1 to its left, but is four spaces from the 1 on its right, so that the top of the slash lines up appropriately and is two spaces from the 1 on its right.

```<code>n = 1
||  ||  //  ||  ||

n = 2
||  ||   //  ||  ||
||  ||  //   ||  ||

n = 3
||  ||    //  ||  ||
||  ||   //   ||  ||
||  ||  //    ||  ||

n = 4
||  ||     //  ||  ||
||  ||    //   ||  ||
||  ||   //    ||  ||
||  ||  //     ||  ||

n = 5
||  ||      //  ||  ||
||  ||     //   ||  ||
||  ||    //    ||  ||
||  ||   //     ||  ||
||  ||  //      ||  ||
</code>```

and so on.

Input

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

Output

An ASCII-art representation of 11/11, following the above rules and examples. Leading/trailing newlines or other whitespace are optional, provided that the characters line up appropriately.

Rules

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

Standard loopholes are forbidden.

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

Title: Armistice Day Challenge

Body:
Powershell, 66 bytes

$a=read-host;1..$a|%{$s="||  ";$s*2+" "*($a-$_)+"// "+" "*$_+$s*2}


问:
Add weight to one side of a see-saw to balance it

Balancing Act

A see-saw (supposedly from the French 'ci-ça', meaning 'this-that') forms a third of the holy trinity of playground equipment, along with the similarly ubiquitous slide and swing. A see-saw is in perfect balance if, and only if, the sum of the moments on each side are equivalent. A see-saw can therefore be balanced by adding a specific quantity of weight to the side with the lower moment sum; achieving this is your goal for this challenge.

Challenge

Your challenge is to take a depiction of a see-saw as input and output it again, with weight added to one end of the see-saw to balance it.

Input

Your program must take, in any reasonable format, an ASCII see-saw such as the following:

```<code>100             100
-------------------
         ^
</code>```

The first line contains two numbers, each representing weights on the see-saw. Exactly one weight is present on each side, each acting on the very end of its side of the plank. Weights are guaranteed to be integers, and always align with their corresponding end of the plank. These numbers will never overlap the fulcrum (^).

The second line represents the 'plank' of the see-saw. Each dash (-) represents an equal length to each other dash, with the sole exception of the dash directly over the fulcrum (^), which has no length.

The third line represents the fulcrum of the see-saw. This fulcrum is marked by the only character that is not a space on this line, a circumflex ('^'). The fulcrum can be positioned anywhere along the length of the plank in a valid input so long as enough space is left so that the numbers representing weights do not overlap the fulcrum in either the input or the output.

The input is guaranteed to have three lines, and have no white-space prior to or after the characters that constitute the see-saw (excepting, of course, the third line, which requires it).

Output

For output, the same see-saw depiction should be printed to stdout, but with one (and only one) of the weights replaced with a larger weight, so as to balance the see-saw. Inputs are guaranteed to make this possible using integers alone. Therefore, weights must be shown without decimal points or any other similar notations. If your language does not use stdout you should go by community / meta consensus on output. Trailing newlines are fine but any other changes to the depiction format are probably not OK.

Exemplification

Test Inputs and Corresponding Outputs

Input 1

```<code>12                22
--------------------
             ^
</code>```

Output 1

```<code>12                26
--------------------
             ^
</code>```

Input 2

```<code>42       42
-----------
     ^
</code>```

Output 2

```<code>42       42
-----------
     ^
</code>```

Input 3

```<code>3             16
----------------
        ^
</code>```

Output 3

```<code>14            16
----------------
        ^
</code>```

Input 4

```<code>1                56
-------------------
    ^
</code>```

Output 4

```<code>196              56
-------------------
    ^
</code>```

Reference Implementation - Python 3

```<code># Takes a list of strings as input
def balance_seesaw(lines):
    weights = [int(w.strip()) for w in lines[0].split()]

    length  = len(lines[1])
    pivot   = lines[2].find("^")
    left_length    = pivot
    right_length   = length - 1 - pivot

    left_torque  = weights[0] * left_length
    right_torque = weights[1] * right_length

    if left_torque > right_torque:
        weights[1] = left_torque // right_length
    elif right_torque > left_torque:
        weights[0] = right_torque // left_length

    weights = [str(w) for w in weights]

    string_gap = " " * (length - sum(len(w) for w in weights))
    lines[0] = weights[0] + string_gap + weights[1]

    print("\n".join(lines))

balance_seesaw(["1                56",
                "-------------------",
                "    ^              "])
</code>```

Rules

This is code-golf, so the shortest code wins counted in bytes. Check meta if counting bytes is awkward in your language.

Standard rules/loopholes apply.

Input must be taken in a reasonable format. A non-exhaustive list of appropriate formats are given as follows:

A single string with lines separated by newline characters

A list of strings, each string represented a line

A 2D Array or Matrix of characters

Related Challenges

Balance a set of weights on a see-saw - Proposed Aug 2015 by samgak

Body:
Befunge, 223 217 bytes

&:00p&10p~$0>~#<2#+%#1_:20p0~>8#~%#+!#1_:3v
v\g01/g03*g01_v#!\g04`*g01g04:*g03p04-1-p0<
>#g>#0>#0>#/>#<:.2\5>5>#\+/#1:#\_$50p:50g\5>5>#\+/#1:#\_$20g\-v>
1#,>#*-#4:#8_$.55+,20g>:#,1#*-#9\#5_55+,30g>:#,1#*-#8\#4_"^",@>>

Try it online!


答:
Python 3, 54 bytes

```<code>for i in range(10):print(('_|__'*175)[70*i:70*(i+1)])
</code>```

I know this is longer than other Python 3 solutions, so I post because it is a different approach.

Title: Build me a brick wall!

Body:
Challenge

I need help building a brick wall! Throw together some code for me
 using no input and produce the following output wall shown below:

```<code>_|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|
___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|__
_|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|
___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|__
_|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|
___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|__
_|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|
___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|__
_|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|
___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|__
</code>```

Now, this wall is exactly 10 characters high and 70 characters
 wide.

As stated above, no inputs, only code. Least amount of bytes, we have
 to efficiently build this brick wall. Obviously, this program has to
 function to get the wall built..? or it obviously won't build itself!
 Good luck!

Winner

The winner goes to Marinus using the APL language, requiring a whole 12 bytes!
https://codegolf.stackexchange.com/a/99028/61857

Thank you everyone for participating!

Body:
Python 3, 54 bytes

for i in range(10):print(('_|__'*175)[70*i:70*(i+1)])

I know this is longer than other Python 3 solutions, so I post because it is a different approach.


问:
Find the Centroid of a Polygon
From Wikipedia:

The centroid of a non-self-intersecting closed polygon
  defined by n vertices (x0,y0),
  (x1,y1), ...,
  (xn−1,yn−1) is the point (Cx,
  Cy), where

and where A is the polygon's signed area,

In these formulas, the vertices are assumed to be numbered in order of
  their occurrence along the polygon's perimeter. Furthermore, the
  vertex ( xn, yn ) is assumed to be the same as
  ( x0, y0 ), meaning i + 1 on the last case
  must loop around to i = 0. Note that if the points are numbered in
  clockwise order the area A, computed as above, will have a negative
  sign; but the centroid coordinates will be correct even in this case.

Given a list of vertices in order (either clockwise, or counter-clockwise), find the centroid of the non-self-intersecting closed polygon represented by the vertices.

If it helps, you may assume input to be only CW, or only CCW. Say so in your answer if you require this.

The coordinates are not required to be integers, and may contain negative numbers.

Input will always be valid and contain at least three vertices.

Inputs only need to be handled that fit in your language's native floating point data type.

You may assume that input numbers will always contain a decimal point.

You may assume that input integers end in . or .0.

You may use complex numbers for input.

Output should be accurate to the nearest thousandth.

Examples

```<code>[(0.,0.), (1.,0.), (1.,1.), (0.,1.)]        -> (0.5, 0.5)
[(-15.21,0.8), (10.1,-0.3), (-0.07,23.55)]  -> -1.727 8.017
[(-39.00,-55.94), (-56.08,-4.73), (-72.64,12.12), (-31.04,53.58), (-30.36,28.29), (17.96,59.17), (0.00,0.00), (10.00,0.00), (20.00,0.00), (148.63,114.32), (8.06,-41.04), (-41.25,34.43)]   -> 5.80104769975, 15.0673812762
</code>```

Too see each polygon on a coordinate plane, paste the coordinates without the square brackets in the "Edit" menu of this page.

I confirmed my results using this Polygon Centroid Point Calculator, which is awful. I couldn't find one that you can input all vertices at once, or that didn't try to erase your - sign when you type it first. I'll post my Python solution for your use after people have had a chance to answer.

答:
C++14, 241 bytes

struct P{float x;float y;};
#define S(N,T)auto N(P){return 0;}auto N(P a,P b,auto...V){return(T)*(a.x*b.y-b.x*a.y)+N(b,V...);}
S(A,1)S(X,a.x+b.x)S(Y,a.y+b.y)auto f(auto q,auto...p){auto a=A(q,p...,q)*3;return P{X(q,p...,q)/a,Y(q,p...,q)/a};}
```
<p>Output is the helper struct <code>P</code>,</p>
<p>Ungolfed:</p>
<pre class="lang-c++ prettyprint-override"><code> //helper struct
struct P{float x;float y;};

//Area, Cx and Cy are quite similar
#define S(N,T)\  //N is the function name, T is the term in the sum
auto N(P){return 0;} \   //end of recursion for only 1 element
auto N(P a,P b,auto...V){ \ //extract the first two elements
  return (T)*(a.x*b.y-b.x*a.y) //compute with a and b
         + N(b,V...); \        //recursion without first element
}

//instantiate the 3 formulas
S(A,1)
S(X,a.x+b.x)
S(Y,a.y+b.y)

auto f(auto q,auto...p){
  auto a=A(q,p...,q)*3; //q,p...,q appends the first element to the end
  return P{X(q,p...,q)/a,Y(q,p...,q)/a};
}
</code>```

Usage:

f(P{0.,0.}, P{1.,0.}, P{1.,1.}, P{0.,1.})
f(P{-15.21,0.8}, P{10.1,-0.3}, P{-0.07,23.55})
```

Title: Find the Centroid of a Polygon

Body:
C++14, 241 bytes

struct P{float x;float y;};
#define S(N,T)auto N(P){return 0;}auto N(P a,P b,auto...V){return(T)*(a.x*b.y-b.x*a.y)+N(b,V...);}
S(A,1)S(X,a.x+b.x)S(Y,a.y+b.y)auto f(auto q,auto...p){auto a=A(q,p...,q)*3;return P{X(q,p...,q)/a,Y(q,p...,q)/a};}

Output is the helper struct P,

Ungolfed:

 //helper struct
struct P{float x;float y;};

//Area, Cx and Cy are quite similar
#define S(N,T)\  //N is the function name, T is the term in the sum
auto N(P){return 0;} \   //end of recursion for only 1 element
auto N(P a,P b,auto...V){ \ //extract the first two elements
  return (T)*(a.x*b.y-b.x*a.y) //compute with a and b
         + N(b,V...); \        //recursion without first element
}

//instantiate the 3 formulas
S(A,1)
S(X,a.x+b.x)
S(Y,a.y+b.y)

auto f(auto q,auto...p){
  auto a=A(q,p...,q)*3; //q,p...,q appends the first element to the end
  return P{X(q,p...,q)/a,Y(q,p...,q)/a};
}

Usage:

f(P{0.,0.}, P{1.,0.}, P{1.,1.}, P{0.,1.})
f(P{-15.21,0.8}, P{10.1,-0.3}, P{-0.07,23.55})


答:
Java, <s>273</s> 263 bytes

```<code>interface Z{int z(int x);default Z g(int m,int n){return x->{for(int t;x!=(t=x==m?z(n):z(x));)x=t;return x;};}static void f(int[]a,int[]b){Z y=x->x;int i=0,v;for(int u:a){u=y.z(u);v=y.z(b[i++]);if(u<v)y=y.g(u,v);if(v<u)y=y.g(v,u);}i=0;for(int u:a)a[i++]=y.z(u);}}
</code>```

The method f(int[]a,int[]b) solves the challenge.

```<code>interface Z{

  //should return an "equivalent" integer
  int z(int x);

  //return a Z lambda where the 1st arg is "equivalent" to the 2nd arg
  default Z g(int m,int n){
    return x->{
      for(int t;x!=(t=x==m?z(n):z(x));) //always find the last equivalent number for x
        x=t;
      return x;
    };
  }

  //solve the challenge
  static void f(int[]a,int[]b){
    Z y=x->x; //start off with all numbers only equivalent only to themselves
    int i=0,v;
    for(int u:a){
      u=y.z(u); //get a's element's equivalent number
      v=y.z(b[i++]); //get b's element's equivalent number
      if(u<v)y=y.g(u,v); //if a's was smaller than b's, make a's equivalent to b's
      if(v<u)y=y.g(v,u); //if b's was smaller than a's, make b's equivalent to a's
    }
    i=0;
    for(int u:a) //overwrite a with each element's equivalent value
      a[i++]=y.z(u);
  }

}
</code>```

First go through both arrays and keep track of equivalent numbers.
Then modify every element in the first array to have the equivalent numbers stored.

Title: Array unification

Body:
Introduction

Consider two arrays of the same length, say A = [0,1,0,2] and B = [-1,1,2,2].
Suppose we know that their contents are equivalent in some sense, item by item:

0 is equivalent to -1,

1 is equivalent to 1,

0 is equivalent to 2, and

2 is equivalent to 2.

Equivalence is transitive: -1 and 0 are equivalent, and 0 and 2 are equivalent, so -1 and 2 are also equivalent.
The unification of A and B is the array where each item of A (or B) has been replaced by the largest number that's equivalent to it.
In this case, the unification would be [2,1,2,2].

The task

Write a program or function that takes two non-empty integer arrays of equal length, and outputs their unification. You can also modify one of the inputs in place instead of returning.
The lowest byte count wins.

Test cases

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

Body:
Java, <s>273</s> 263 bytes

interface Z{int z(int x);default Z g(int m,int n){return x->{for(int t;x!=(t=x==m?z(n):z(x));)x=t;return x;};}static void f(int[]a,int[]b){Z y=x->x;int i=0,v;for(int u:a){u=y.z(u);v=y.z(b[i++]);if(u<v)y=y.g(u,v);if(v<u)y=y.g(v,u);}i=0;for(int u:a)a[i++]=y.z(u);}}

The method f(int[]a,int[]b) solves the challenge.

interface Z{

  //should return an "equivalent" integer
  int z(int x);

  //return a Z lambda where the 1st arg is "equivalent" to the 2nd arg
  default Z g(int m,int n){
    return x->{
      for(int t;x!=(t=x==m?z(n):z(x));) //always find the last equivalent number for x
        x=t;
      return x;
    };
  }

  //solve the challenge
  static void f(int[]a,int[]b){
    Z y=x->x; //start off with all numbers only equivalent only to themselves
    int i=0,v;
    for(int u:a){
      u=y.z(u); //get a's element's equivalent number
      v=y.z(b[i++]); //get b's element's equivalent number
      if(u<v)y=y.g(u,v); //if a's was smaller than b's, make a's equivalent to b's
      if(v<u)y=y.g(v,u); //if b's was smaller than a's, make b's equivalent to a's
    }
    i=0;
    for(int u:a) //overwrite a with each element's equivalent value
      a[i++]=y.z(u);
  }

}

First go through both arrays and keep track of equivalent numbers.
Then modify every element in the first array to have the equivalent numbers stored.


问:
Golfing Flower of Life
The challenge here is to accurately depict the flower of life (which is a sacred geometrical figure according to some) in the language of your choice.

The design consists an arrangement of circles and partial circles of radius 1 as shown whose centres arranged on a triangular grid of pitch 1, plus one larger circle of radius 3 surrounding them.

The design can be scaled as you like, but a max error of 2% from mathematically correct is permitted. If using raster graphics, this effectively limits the diameter of the small circles to at least about 100 pixels.

Since this is code-golf, shortest code (bytes) wins.

答:
OpenSCAD, 228 bytes

```<code>$fn=99;module o(a=9){difference(){circle(a);circle(a-1);}}function x(n)=9*[sin(n*60),cos(n*60)];module q(g){for(i=[1:6])if(g>0){translate(x(i))union(){o();q(g-1);}}else{intersection(){translate(x(i))o();circle(9);}}}q(2);o(27);
</code>```

The below is a version allowing someone to set parameters r (radius) and w (width of rings).

```<code>r=1;w=.1;$fn=99;module o(n){difference(){circle(n);circle(n-w);}}function x(n)=(r-w/2)*[sin(n*60),cos(n*60)];module q(g){for(i=[1:6])if(g>0){translate(x(i))union(){o(r);q(g-1);}}else{intersection(){translate(x(i))o(r);circle(r);}}}q(2);o(3*r-w);
</code>```

This version is xactly 246 characters.

Some of this code is technically unnecessary but makes it look more like the picture.

Title: Golfing Flower of Life

Body:
OpenSCAD, 228 bytes

$fn=99;module o(a=9){difference(){circle(a);circle(a-1);}}function x(n)=9*[sin(n*60),cos(n*60)];module q(g){for(i=[1:6])if(g>0){translate(x(i))union(){o();q(g-1);}}else{intersection(){translate(x(i))o();circle(9);}}}q(2);o(27);

The below is a version allowing someone to set parameters r (radius) and w (width of rings).

r=1;w=.1;$fn=99;module o(n){difference(){circle(n);circle(n-w);}}function x(n)=(r-w/2)*[sin(n*60),cos(n*60)];module q(g){for(i=[1:6])if(g>0){translate(x(i))union(){o(r);q(g-1);}}else{intersection(){translate(x(i))o(r);circle(r);}}}q(2);o(3*r-w);

This version is xactly 246 characters.

Some of this code is technically unnecessary but makes it look more like the picture.


问:
Invert a boolean array
A nice simple one

Input

Given a boolean array (Or an acceptable alternative), you can assume the array will never be more than 32 elements long.

```<code>[false, false, true, false, false]
</code>```

Output

Invert every element of the array and output it.

```<code>[true, true, false, true, true]
</code>```

Rules

You can write a full program or just a function

Standard loopholes apply

Shortest code in bytes, per language, wins!

Test cases

```<code>Input:
[true, false]
Output:
[false, true]

Input: //Example of acceptable alternative
[0,1,1]
Output:
[1,0,0]
</code>```

答:
C++11, 30 bytes

As unnamed lambda:

[](auto&v){for(auto&x:v)x=!x;}
```

Accepts any standard container like vector<int> (but not vector<bool>) or int[] or bool[].

Title: Invert a boolean array

Body:
C++11, 30 bytes

As unnamed lambda:

[](auto&v){for(auto&x:v)x=!x;}

Accepts any standard container like vector<int> (but not vector<bool>) or int[] or bool[].


答:
JavaScript, 22 bytes, 10 numbers, by Arnauld

Original program:

```<code>alert(0_6_4_>_0_2_0_7)
</code>```

Cracked:

alert(0+6^42>101210^7)

alert(0+5^42>101210^7)

alert(0+4^42>101210^7)

alert(0+3^42>101210^7)

alert(0+2^42>101210^7)

alert(0+1^42>101210^7)

alert(0+0^42>101210^7)

alert(0+0^42>101210^8)

alert(0+0^42>101210^9)

alert(0+3^42>101210^9)

The hard part is to deal with the >, which has a very low precedence. I tried changing it to an >>, but it's easiest to just absorb it by making it uselessly calculate a boolean false (the 42>101210 section) which is numerically 0, and just generate the numbers from 1 to 10 with operators with an even lower precedence than >. I used ^, bitwise xor, because it can generate the numbers from 1 to 10 fairly easily (conveniently, the 6 and 7 in the original input let me simplify the expression down to 6^7 which is 1).

Title: Code ladder, Robbers

Body:
This is the robbers' thread. The cops' thread goes here.

Write a code that has the same number of bytes as the cop post and where the revealed characters are identical. The code must produce 1 in its initial state, and produce the numbers 2, 3 .. when single alterations are made.

The winner will be the robber that cracked the most posts.

Example post:

MyLang, 9 bytes, 8 numbers (including link to answer), Cop's username.

Original code:

```<code>abc1efghi
</code>```

Code that produces 1 - 8:

```<code>1: abc1efghi
2: abc2efghi
3: abc2efghij
4: kbc2efghij
5: kbc23fghij
6: kbc23fghi
7: kbc63fghi
8: kbc63fhi
</code>```

Explanations are encouraged. The exact format of the robber post is optional.

Body:
JavaScript, 22 bytes, 10 numbers, by Arnauld

Original program:

alert(0_6_4_>_0_2_0_7)

Cracked:

alert(0+6^42>101210^7)

alert(0+5^42>101210^7)

alert(0+4^42>101210^7)

alert(0+3^42>101210^7)

alert(0+2^42>101210^7)

alert(0+1^42>101210^7)

alert(0+0^42>101210^7)

alert(0+0^42>101210^8)

alert(0+0^42>101210^9)

alert(0+3^42>101210^9)

The hard part is to deal with the >, which has a very low precedence. I tried changing it to an >>, but it's easiest to just absorb it by making it uselessly calculate a boolean false (the 42>101210 section) which is numerically 0, and just generate the numbers from 1 to 10 with operators with an even lower precedence than >. I used ^, bitwise xor, because it can generate the numbers from 1 to 10 fairly easily (conveniently, the 6 and 7 in the original input let me simplify the expression down to 6^7 which is 1).


问:
List of primes under a million
This is my first code golf question, and a very simple one at that, so I apologise in advance if I may have broken any community guidelines.

The task is to print out, in ascending order, all of the prime numbers less than a million. The output format should be one number per line of output.

The aim, as with most code golf submissions, is to minimise code size. Optimising for runtime is also a bonus, but is a secondary objective.

答:
ASMD, 7 bytes

```<code>W(i|P?p
</code>```

Explanation:

```<code>W        # Push 1,000,000
 (       # Begin range loop (0 -> 999,999)
  i      # Push counter variable
   |     # Duplicate
    P?p  # If prime, print
       . # Implicit end range loop
</code>```

Title: List of primes under a million

Body:
ASMD, 7 bytes

W(i|P?p

Explanation:

W        # Push 1,000,000
 (       # Begin range loop (0 -> 999,999)
  i      # Push counter variable
   |     # Duplicate
    P?p  # If prime, print
       . # Implicit end range loop


答:
<s>ASMD, 10 bytes</s> Cracked!

```<code>1_**_**_*÷
</code>```

Hidden characters are denoted by _.

This should be really easy to crack.

Works from 1 to 10.

Title: Code ladder, Cops

Body:
Note: This challenge is finished. Submissions are still welcome but can not win.

This is the cops' thread. The robbers' thread goes here.

Write a code that outputs the integer 1. If you add, remove or substitute a single character (of your choosing), the code should output the integer 2. Change one more character (the same or another), and the code should output 3. Continue like this as far as you can, but maximum up to 10. Default output formats such as ans = 1 are accepted. You can ignore output to STDERR (or equivalent).

You must reveal the language, byte count of your initial code, the number of integers it works for, as well as an optional number of characters of the initial code. Note: You don't have to reveal any characters, but remember that revealing characters might make it harder for the robbers as they must use the same character in the same position. You can choose which character you use to denote unrevealed characters (for instance underscore), but make sure to specify this.

Cops can provide the uncracked code after one week and call the submission "SAFE". The winning submission will be the shortest uncracked submission that produces the number 10. If no uncracked submissions are able to print 10, the shortest code that produces 9 will win, and so on. Note that the robbers don't have to make the same changes as you do, and they don't have to reproduce the exact code (unless you reveal all characters). They must only reproduce the output.

Submissions posted later than November 24th are welcome but not eligible for the win (because there will likely be fewer robbers around).

Example post:

The following post is a submission in the language MyLang, it is 9 bytes long, and it works for numbers 1 - 8.

MyLang, 9 bytes, 8 numbers

This submission works for 1 - 8. Unrevealed characters are indicated with an underscore: _.

```<code>abc____i
</code>```

Leaderboard

Disclaimer: The leaderboard is not tested and uncracked submissions might not appear in the list.

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

Uncracked submissions

 Language	 Score	 User

Sort by: score creation

Safe submissions

 Language	 Score	 User

```

Body:
<s>ASMD, 10 bytes</s> Cracked!

1_**_**_*÷

Hidden characters are denoted by _.

This should be really easy to crack.

Works from 1 to 10.


答:
05AB1E, distance 3

```<code>#O,Given a set of integers, find the sum of all integers in it.
</code>```

Try it online!

Title: Code close to the challenge: Sum of integers

Body:
This is a simple challenge:
Given a sequence of integers, find the sum of all integers in it.

But with a twist.
Your score is the Levenshtein distance between your code and the following phrase (The challenge):

Given a set of integers, find the sum of all integers in it.

You may assume there are no newlines or trailing spaces in the input.

Example input/output:

```<code>Input: 1 5 -6 2 4 5
Output: 11
Input: 1 -2 10
Output: 9
</code>```

An online calculator for Levenshtein distance can be found here: http://planetcalc.com/1721/

Body:
05AB1E, distance 3

#O,Given a set of integers, find the sum of all integers in it.

Try it online!


答:
Common Lisp, <s>673</s> <s>668</s> 597 bytes

Terrible solution, I know. I'll probably edit this more after some sleep.

```<code>(defun f(&rest z)(let((l)(a 0)(s)(o)(b)(c 0))(loop(setf b(length l))(setf l"")(loop for w in z for i from 0 do(if(>(+(length w)(* i 3))c)(setf c(+(length w)(* i 3))))(setf s(+(* i -3)a))(when(and(>= s 0)(< s(length w)))(setf o(format nil"~v@{~a~:*~}"s" "))(if(and(>=(- s 3)0)(not(equal i(-(length z)1))))(setf o(subseq o(- s 2))))(setf l(concatenate'string o(string(char w s))l)))(when(>= s(length w))(setf l(concatenate'string"   "l))))(if(<=(length l)b)(setf l(concatenate'string(format nil"~v@{~a~:*~}"(- b(length l)-1)" ")l)))(print(string-right-trim" "l))(if(>= b c)(return))(setf a(1+ a)))))
</code>```

Usage:

```<code>* (f "ppcg" "is" "pretty" "ok")

"p"
" p"
"  c"
"i  g"
" s"
""
"p"
" r"
"  e"
"o  t"
" k  t"
"     y"
""
NIL
</code>```

This loops over every word in the provided list and adds appropriate characters to the current line. Appropriate padding is provided by my subpar usage of format.

Note: I'm new to Common Lisp, but I know enough to realize that this could use a lot of improvement.

Title: Draw diagonal lines of text

Body:
Given an input of a list of words, output the words with their letters arranged
diagonally:

```<code>p
 r
  o
p  g
 u  r
  z  a
a  z  m
 n  l  m
  d  e  i
c     s  n
 o        g
  d
g  e
 o
  l
   f
</code>```

(The above should be the output for the input programming puzzles and code golf.)

To be precise, each word starts on the first column and three rows below the
previous word, and each successive letter moves one column to the right and one
row down.

The input may be provided as either a single string of words, separated by
exactly one space, or a list/array of words. The words will only be composed of
lowercase letters, a-z, and will always be at least one character long.

The output may be a single string, an array of lines, or an array of arrays of
characters. Leading or trailing whitespace is not allowed, except for a single
trailing newline.

Further test cases:

a bcd efgh i j

```<code>a

b
 c
  d
e
 f
  g
i  h

j
</code>```

x

```<code>x
</code>```

verylongword short

```<code>v
 e
  r
s  y
 h  l
  o  o
   r  n
    t  g
        w
         o
          r
           d
</code>```

Since this is code-golf, the shortest code in bytes will win!

Body:
Common Lisp, <s>673</s> <s>668</s> 597 bytes

Terrible solution, I know. I'll probably edit this more after some sleep.

(defun f(&rest z)(let((l)(a 0)(s)(o)(b)(c 0))(loop(setf b(length l))(setf l"")(loop for w in z for i from 0 do(if(>(+(length w)(* i 3))c)(setf c(+(length w)(* i 3))))(setf s(+(* i -3)a))(when(and(>= s 0)(< s(length w)))(setf o(format nil"~v@{~a~:*~}"s" "))(if(and(>=(- s 3)0)(not(equal i(-(length z)1))))(setf o(subseq o(- s 2))))(setf l(concatenate'string o(string(char w s))l)))(when(>= s(length w))(setf l(concatenate'string"   "l))))(if(<=(length l)b)(setf l(concatenate'string(format nil"~v@{~a~:*~}"(- b(length l)-1)" ")l)))(print(string-right-trim" "l))(if(>= b c)(return))(setf a(1+ a)))))

Usage:

* (f "ppcg" "is" "pretty" "ok")

"p"
" p"
"  c"
"i  g"
" s"
""
"p"
" r"
"  e"
"o  t"
" k  t"
"     y"
""
NIL

This loops over every word in the provided list and adds appropriate characters to the current line. Appropriate padding is provided by my subpar usage of format.

Note: I'm new to Common Lisp, but I know enough to realize that this could use a lot of improvement.


问:
Print numbers from 1 to 10
This might be a very simple challenge, but I am surprised it hasn't been done on code-golf yet:

Print all Integers from 1 to 10 inclusive in ascending order to standard output.

Your output format can be whatever your language supports. This includes arbitrary separators (commas, semicolons, newlines, combinations of those, etc., but no digits), and prefixes and postfixes (like [...]). However, you may not output any other numbers than 1 through 10. Your program may not take any input. Standard loopholes are disallowed.

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

Leaderboard

var QUESTION_ID=86075,OVERRIDE_USER=42570;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

```

答:
APL, 3 bytes

```<code>⍳10
</code>```

Explanation:

```<code>⍳   range
10   10
</code>```

Title: Print numbers from 1 to 10

Body:
APL, 3 bytes

⍳10

Explanation:

⍳   range
10   10


问:
Sum of neighbours
This should be a fairly simple challenge.

For an array of numbers, generate an array where for every element all neighbouring elements are added to itself, and return the sum of that array.

Here is the transformation which occurs on the input array [1,2,3,4,5]

```<code>[1,2,3,4,5] => [1+2, 2+1+3, 3+2+4, 4+3+5, 5+4] => [3,6,9,12,9] => 39
 0          => neighbours of item 0, including item 0
[1,2]       => 1 + 2      => 3
   1
[1,2,3]     => 1 + 2 + 3  => 6
     2
  [2,3,4]   => 2 + 3 + 4  => 9
       3
    [3,4,5] => 3 + 4 + 5  => 12
         4
      [4,5] => 4 + 5      => 9

               3+6+9+12+9 => 39
</code>```

Test cases

```<code>[]            => 0 (or falsy)
[1]           => 1
[1,4]         => 10 (1+4 + 4+1)
[1,4,7]       => 28
[1,4,7,10]    => 55
[-1,-2,-3]    => -14
[0.1,0.2,0.3] => 1.4
[1,-20,300,-4000,50000,-600000,7000000] => 12338842
</code>```

Leaderboard

var QUESTION_ID=96188,OVERRIDE_USER=41257;function answersUrl(e){return"http://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"http://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="
"+e.body.replace(OVERRIDE_REG,"")+"
")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\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

```

答:
C++14, <s>64</s> 59 bytes

As unnamed lambda

[](auto c,int&r){r=-c[0];for(auto x:c)r+=3*x;r-=c.back();}
```
<p>Initializes counter with <code>-c[0]</code>, then sums all elements times <code>3</code> and subtracts the last element. This gives <code>3*sum(c)-c.first-c.last</code> which is the direct formula for this problem.</p>
<p>Takes any container that supports <code>.back()</code>. If you insinst on using plain old arrays (<em>örglöärks</em>) then substitute <code>c.back()</code> with <code>std::end(c)[-1]</code> for <strong>+7 bytes</strong>.</p>
<p>Usage:</p>
<pre class="lang-c++ prettyprint-override"><code>auto n=[](auto c,int&r){r=-c[0];for(auto x:c)r+=3*x;r-=c.back();};

std::vector<int> v{1,2,3,4,5};
//or// std::array<int,5> v{1,2,3,4,5};
//or// int v[]={1,2,3,4,5}; //with std::end(c)[-1]
int r;
n(v,r);
std::cout << r << std::endl;
</code>```

Title: Sum of neighbours

Body:
C++14, <s>64</s> 59 bytes

As unnamed lambda

[](auto c,int&r){r=-c[0];for(auto x:c)r+=3*x;r-=c.back();}

Initializes counter with -c[0], then sums all elements times 3 and subtracts the last element. This gives 3*sum(c)-c.first-c.last which is the direct formula for this problem.

Takes any container that supports .back(). If you insinst on using plain old arrays (örglöärks) then substitute c.back() with std::end(c)[-1] for +7 bytes.

Usage:

auto n=[](auto c,int&r){r=-c[0];for(auto x:c)r+=3*x;r-=c.back();};

std::vector<int> v{1,2,3,4,5};
//or// std::array<int,5> v{1,2,3,4,5};
//or// int v[]={1,2,3,4,5}; //with std::end(c)[-1]
int r;
n(v,r);
std::cout << r << std::endl;


问:
Score a hand of Hearts
Hearts is a trick-taking card game for 4 players. Each trick is taken by the player who played the highest card of the leading suit. At the end of each hand, the players incur a penalty score depending on the penalty cards they have taken; the task is to determine the scores under Microsoft Hearts rules.

Input

Input is 4 lists (or delimited string, array, etc.) showing the penalty cards taken by each of the 4 players. The penalty cards are

```<code>2♥, 3♥, 4♥, 5♥, 6♥, 7♥, 8♥, 9♥, 10♥, J♥, Q♥, K♥, A♥, Q♠
</code>```

which we shall represent as

```<code>2,  3,  4,   5,  6,  7,  8,  9,  10,  11, 12,  13,  1,  0
</code>```

respectively.

Output

Output is the 4 penalty points incurred by the 4 players (list, string, array etc.). Scoring is as follows:

Each heart (♥, represented by integers 1 to 13 inclusive) incurs 1 point

The queen of spades (Q♠, represented by 0) incurs 13 points

Exception: if a player has taken all of the penalty cards (called shooting the moon), then he incurs 0 points, while all other players incur 26 points.

Test cases

```<code>[2, 8, 7, 1], [3, 4], [], [9, 5, 6, 0, 10, 11, 12, 13]     -->  4,  2,  0, 20
[0, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13], [], [], [1]   --> 25,  0,  0,  1
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 0], [], [], [] -->  0, 26, 26, 26
</code>```

Shortest code in bytes wins.

答:
R, 85 77 74 bytes

```<code>function(x,z=sapply(x,function(x)sum(x>0)+any(x<1)*13))abs(z-any(z>25)*26)
</code>```

Unnamed function that takes an R-list as input. Works by counting the number of elements >0 and adds 13 if any element within each vector is <1 (i.e. queen of spades) and store as z.

If any element in z is >25, return 26-z, else return z.

Try it on R-fiddle

Title: Score a hand of Hearts

Body:
R, 85 77 74 bytes

function(x,z=sapply(x,function(x)sum(x>0)+any(x<1)*13))abs(z-any(z>25)*26)

Unnamed function that takes an R-list as input. Works by counting the number of elements >0 and adds 13 if any element within each vector is <1 (i.e. queen of spades) and store as z.

If any element in z is >25, return 26-z, else return z.

Try it on R-fiddle


Title: Score a hand of Hearts

Body:
Hearts is a trick-taking card game for 4 players. Each trick is taken by the player who played the highest card of the leading suit. At the end of each hand, the players incur a penalty score depending on the penalty cards they have taken; the task is to determine the scores under Microsoft Hearts rules.

Input

Input is 4 lists (or delimited string, array, etc.) showing the penalty cards taken by each of the 4 players. The penalty cards are

```<code>2♥, 3♥, 4♥, 5♥, 6♥, 7♥, 8♥, 9♥, 10♥, J♥, Q♥, K♥, A♥, Q♠
</code>```

which we shall represent as

```<code>2,  3,  4,   5,  6,  7,  8,  9,  10,  11, 12,  13,  1,  0
</code>```

respectively.

Output

Output is the 4 penalty points incurred by the 4 players (list, string, array etc.). Scoring is as follows:

Each heart (♥, represented by integers 1 to 13 inclusive) incurs 1 point

The queen of spades (Q♠, represented by 0) incurs 13 points

Exception: if a player has taken all of the penalty cards (called shooting the moon), then he incurs 0 points, while all other players incur 26 points.

Test cases

```<code>[2, 8, 7, 1], [3, 4], [], [9, 5, 6, 0, 10, 11, 12, 13]     -->  4,  2,  0, 20
[0, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13], [], [], [1]   --> 25,  0,  0,  1
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 0], [], [], [] -->  0, 26, 26, 26
</code>```

Shortest code in bytes wins.

Body:
Haskell, <s>62</s> <s>59</s> 56 bytes

f x|all(<26)x=x|0<1=map(26-)x
f.map(sum.map((13^).(0^)))

Usage:

> f.map(sum.map((13^).(0^))) $ [[0, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13], [], [], [1]]
[25,0,0,1]


问:
Calculating waves
I've been scrolling around this site for a while, but just recently got really interested in actually trying out some of the challenges. I was intending to try my hand at some of the existing code-golf topics, but I didn't have Internet access for a while yesterday, and in the meantime, I thought up my own challenge.

Your task is to create a program or function that takes an array of Floats a and an integer n, then sets each value in a to the average of the two beside it, n times. When repeatedly used with increasing values of n, this generates a wave-like motion:

Specifics:

If there happens to be only one item in a, or if n is 0 or less, the program should return the original array.

Inputs and outputs can be in any format you desire, as long as they are visibly separated.

For each step:

The first item in a should become the average of itself and the next item.

The last item in a should become the average of itself and the previous item.

Any other item in a should become the average of the previous item and the next item.

Make sure you are calculating off the previous step's array and not the current one!

Test cases: NOTE: Your inputs/outputs do not have to be in this format!

```<code>[0, 0, 1, 0, 0], 1          -> [0, 0.5, 0, 0.5, 0]
[0, 0, 1, 0, 0], 2          -> [0.25, 0, 0.5, 0, 0.25]
[0, 0, 1, 0, 0], 0          -> [0, 0, 1, 0, 0]
[0, 0, 1, 0, 0], -39        -> [0, 0, 1, 0, 0]
[0, 16, 32, 16, 0], 1       -> [8, 16, 16, 16, 8]
[0, 1, 2, 3, 4, 5], 1       -> [0.5, 1, 2, 3, 4, 4.5]
[0, 64], 1                  -> [32, 32]
[0], 482                    -> [0]
[32, 32, 32, 16, 64, 16, 32, 32, 32], 4 -> [33, 27, 40, 22, 44, 22, 40, 27, 33]
</code>```

This is code-golf, so shortest answer in bytes wins. The winner will be chosen in one week (on August 1). Good luck!

Edit: Congrats to the winner, @issacg, with a whopping 18 bytes!

答:
C++14, 158 bytes

#define D(a,b)d[i]=(c[a]+c[b])/2;
auto f(auto c,int n){while(n-->0&&c.size()>1){auto d{c};int i{};D(0,1)while(++i<c.size()-1)D(i-1,i+1)D(i,i-1)c=d;}return c;}
```
<p>Requires input to be a container <code>value_type==double</code>, like <code>vector<double></code>.</p>
<p>Ungolfed:</p>
<pre class="lang-c++ prettyprint-override"><code>#define D(a,b) d[i] = (c[a]+c[b])/2;   //average
auto f(auto c, int n) {
  while(n-- > 0 && c.size() > 1) {     //breaks
    auto d{c};                         //copy container
    int i{};
    D(0,1)                             //left
    while(++i < c.size()-1)            //count up to right
      D(i-1,i+1)                       //interior
    D(i,i-1)                           //right
    c=d;                               //overwrite container
  }
  return c;
}
</code>```

Title: Calculating waves

Body:
C++14, 158 bytes

#define D(a,b)d[i]=(c[a]+c[b])/2;
auto f(auto c,int n){while(n-->0&&c.size()>1){auto d{c};int i{};D(0,1)while(++i<c.size()-1)D(i-1,i+1)D(i,i-1)c=d;}return c;}

Requires input to be a container value_type==double, like vector<double>.

Ungolfed:

#define D(a,b) d[i] = (c[a]+c[b])/2;   //average
auto f(auto c, int n) {
  while(n-- > 0 && c.size() > 1) {     //breaks
    auto d{c};                         //copy container
    int i{};
    D(0,1)                             //left
    while(++i < c.size()-1)            //count up to right
      D(i-1,i+1)                       //interior
    D(i,i-1)                           //right
    c=d;                               //overwrite container
  }
  return c;
}


答:
05AB1E, 26 22 21 bytes

Trailing whitespace must be removed from input so that it is interpreted as an array.
The ending was inspired of the other answers when using (26-x) when a player gathered all penalty cards.

```<code>vy0å12*yg+})D26©åi(®+

v                    For each array
 y                   Push array on the stack
  0å                 Generate a boolean array indicating whether the queen of spades is at the same index in the original array
    12*              Multiply by 12 the value of the queen of spades
       yg+           Add the length of the array; the queen of spades gets her last point from this part
          }          End for
           )         Push an array of all evaluated scores
            D26©å    1 if there is a 26, 0 otherwise
                 i   If there is a 26
                  (®+ Mirror the array: for each element yield 26-element
                      Implicit end if
                      Implicitly print the score array
</code>```

Try it online!

It still looks pretty golfable, with duplicated constants and conditional statements.

Former version, 26 bytes

(One byte for each point in maximal penalty value)

I decided to keep it as its length fits best this challenge in my opinion :) .

```<code>vyD0å12*sg+})D26©QDOi_®*ë\
</code>```

Try it online!

Title: Score a hand of Hearts

Body:
05AB1E, 26 22 21 bytes

Trailing whitespace must be removed from input so that it is interpreted as an array.
The ending was inspired of the other answers when using (26-x) when a player gathered all penalty cards.

vy0å12*yg+})D26©åi(®+

v                    For each array
 y                   Push array on the stack
  0å                 Generate a boolean array indicating whether the queen of spades is at the same index in the original array
    12*              Multiply by 12 the value of the queen of spades
       yg+           Add the length of the array; the queen of spades gets her last point from this part
          }          End for
           )         Push an array of all evaluated scores
            D26©å    1 if there is a 26, 0 otherwise
                 i   If there is a 26
                  (®+ Mirror the array: for each element yield 26-element
                      Implicit end if
                      Implicitly print the score array

Try it online!

It still looks pretty golfable, with duplicated constants and conditional statements.

Former version, 26 bytes

(One byte for each point in maximal penalty value)

I decided to keep it as its length fits best this challenge in my opinion :) .

vyD0å12*sg+})D26©QDOi_®*ë\

Try it online!