答:
dc, 62 bytes

```<code>?si2sa1dd2:a:a[la1+dsadd1-;a-;alad2-;a-;a+r:ali;a0=A]dsAxli;af
</code>```

This solution makes use of arrays and recursion.

```<code>?si          # Take input from stdin and store it in register `i'
2sa          # Initialise register `a' with 2, since we'll be putting in the first
             #   two values in the sequence
1dd2         # Stack contents, top-down: 2 1 1 1
:a           # Pop index, then pop value: Store 1 in a[2]
:a           # Ditto:                     Store 1 in a[1]
[            # Open macro definition
 la 1+ dsa   # Simple counter mechanism: Increment a and keep a copy on stack

# The STACK-TRACKER(tm): Top of stack will be at top of each column, under the
#   dashed line. Read commands from left to right, wrapping around to next line.
#   This will be iteration number n.
  dd   1-    ;a       -          ;a            la            d
#-----------------------------------------------------------------------
# n    n-1   a[n-1]   n-a[n-1]   a[n-a[n-1]]   n             n
# n    n     n        n          n             a[n-a[n-1]]   n
# n    n     n                                 n             a[n-a[n-1]]
#                                                            n
#

  2-            ;a            -             ;a            +      r    :a
#-----------------------------------------------------------------------
# n-2           a[n-2]        n-a[n-2]      a[n-a[n-2]]   a[n]   n
# n             n             a[n-a[n-1]]   a[n-a[n-1]]   n      a[n]
# a[n-a[n-1]]   a[n-a[n-1]]   n             n
# n             n

 li;a        # Load index of target element, and fetch that element's current value
             #    Uninitialised values are zero
 0=A         # If a[i]==0, execute A to compute next term
]dsAx        # Close macro definition, store on `A' and execute
li;a         # When we've got enough terms, load target index and push value
f            # Dump stack (a[i]) to stdout
</code>```

Title: Hofstadter Q-sequence

Body:
dc, 62 bytes

?si2sa1dd2:a:a[la1+dsadd1-;a-;alad2-;a-;a+r:ali;a0=A]dsAxli;af

This solution makes use of arrays and recursion.

?si          # Take input from stdin and store it in register `i'
2sa          # Initialise register `a' with 2, since we'll be putting in the first
             #   two values in the sequence
1dd2         # Stack contents, top-down: 2 1 1 1
:a           # Pop index, then pop value: Store 1 in a[2]
:a           # Ditto:                     Store 1 in a[1]
[            # Open macro definition
 la 1+ dsa   # Simple counter mechanism: Increment a and keep a copy on stack

# The STACK-TRACKER(tm): Top of stack will be at top of each column, under the
#   dashed line. Read commands from left to right, wrapping around to next line.
#   This will be iteration number n.
  dd   1-    ;a       -          ;a            la            d
#-----------------------------------------------------------------------
# n    n-1   a[n-1]   n-a[n-1]   a[n-a[n-1]]   n             n
# n    n     n        n          n             a[n-a[n-1]]   n
# n    n     n                                 n             a[n-a[n-1]]
#                                                            n
#

  2-            ;a            -             ;a            +      r    :a
#-----------------------------------------------------------------------
# n-2           a[n-2]        n-a[n-2]      a[n-a[n-2]]   a[n]   n
# n             n             a[n-a[n-1]]   a[n-a[n-1]]   n      a[n]
# a[n-a[n-1]]   a[n-a[n-1]]   n             n
# n             n

 li;a        # Load index of target element, and fetch that element's current value
             #    Uninitialised values are zero
 0=A         # If a[i]==0, execute A to compute next term
]dsAx        # Close macro definition, store on `A' and execute
li;a         # When we've got enough terms, load target index and push value
f            # Dump stack (a[i]) to stdout


问:
Linear combination of two vectors

Executive summary

Given input representing two vectors and their respective "weights", produce output that also represents the weighted sum of those vectors.

Challenge

The input will consist of one or more lines of the following characters:

exactly one occurrence of the digit 0, which represents the origin in a two-dimensional plane;

exactly two other digits (1-9; may or may not be the same digit), whose positions relative to the origin represent vectors, and whose values represent the weights attached to thse vectors;

some number of "background characters". The solver may choose a specific background character; for example, I will choose "." (mostly for human readability). Alternately, the background characters can be anything that look like blank space.

(The solver can choose whether the input is a single multi-line string or an array of one-line strings.)

For example, the input

```<code>....2
.0...
...3.
</code>```

represents a vector at coordinates (3,1) with weight 2, and a vector at coordinates (2,-1) with weight 3.

The output should be almost the same as the input, with the following changes:

a "result character", chosen by the solver, to be added at the position specified by weighted sum of the input vectors (equivalently, at the position that is the appropriate linear combination of the input vectors);

as many background characters as are needed to fit the origin, the two input vectors, and the output vector in the same picture. Extra background characters can be included if desired; the only constraint is that, if the background character is a visible character, then the entire output must be rectangular in shape and every character not representing a vector must be the background character. (If blank space is used as background characters, then these constraints don't need to be enforced.)

(In general, if we have one vector (v,w) with weight a and second vector (x,y) with weight b, their weighted sum is a(v,w)+b(x,y) = (av+bx,aw+by).)

In the previous example, the appropriate linear combination is 2*(3,1) + 3*(2,-1) = (12,-1). If we use "X" as the result character, then the output could look like

```<code>....2.........
.0............
...3.........X
</code>```

or

```<code>................
...2............
0...............
..3.........X...
................
................
</code>```

Usual code-golf scoring: the shortest answer, in bytes, wins.

Example input and output

If blank space is used, the above input would look like

```<code>    2
 0
   3
</code>```

and the output would look like

```<code>    2
 0
   3         X
</code>```

Leading/trailing whitespace characters/lines are irrelevant; if they're invisible to the reader, it's fine. (That being said, for the rest of the examples I'll go back to using "." for the background character, to make it easier to read.)

If both vectors have weight 1, then the result will look like a parallelogram: the input

```<code>.1.
...
1.0
</code>```

leads to the output

```<code>X.1.
....
.1.0
</code>```

Note this parallelogram can be degenerate if the input vectors are collinear: the input

```<code>0.1..1
</code>```

leads to the output

```<code>0.1..1.X
</code>```

It is possible for the result vector to equal one of the input vectors or the origin; in this case, it simply overwrites the input character. For example, the input

```<code>..2.0.1...
</code>```

yields the output

```<code>....2.........
.0............
...3.........X
</code>```0

(where in input and/or output, the leading and trailing periods could be deleted). The input

```<code>....2.........
.0............
...3.........X
</code>```1

yields the output

```<code>....2.........
.0............
...3.........X
</code>```2

Finally, the input

```<code>90
.8
</code>```

yields the output

```<code>........90
.........8
..........
..........
..........
..........
..........
..........
X.........
</code>```

答:
MATL, 48 bytes

```<code>tZyyX:UX>*Yat48-tt0>*3#fbbhb~2#fh-*s7M+'X'wZ}4$(
</code>```

The background character is space. Input is a 2D char array with rows separated by semicolons. So the tests cases have respective inputs:

```<code>['    2'; ' 0   '; '   3 ']
[' 1 '; '   '; '1 0']
['0 1  1']
['  2 0 1   ']
['     3'; '      '; '   0  '; '      '; '      '; '2     ']
['90'; ' 8']
</code>```

The output includes a significant amount of padding whitespace.

Try it online!

ContentLicense: CC BY-SA 3.0

Title: Linear combination of two vectors

Body:
MATL, 48 bytes

tZyyX:UX>*Yat48-tt0>*3#fbbhb~2#fh-*s7M+'X'wZ}4$(

The background character is space. Input is a 2D char array with rows separated by semicolons. So the tests cases have respective inputs:

['    2'; ' 0   '; '   3 ']
[' 1 '; '   '; '1 0']
['0 1  1']
['  2 0 1   ']
['     3'; '      '; '   0  '; '      '; '      '; '2     ']
['90'; ' 8']

The output includes a significant amount of padding whitespace.

Try it online!


问:
Hofstadter Q-sequence

Definition

a(1) = 1

a(2) = 1

a(n) = a(n-a(n-1)) + a(n-a(n-2)) for n > 2 where n is an integer

Task

Given positive integer n, generate a(n).

Testcases

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

Reference

Obligatory OEIS A005185

答:
Sesos, 54 bytes

```<code>0000000: eefb5b 04f83a a75dc2 36f8d7 cf6dd0 af7b3b 3ef8d7  ..[..:.].6...m..{;>..
0000015: cfed12 f661f0 ae9d83 ee63e6 065df7 ce6183 af7383  ....a.....c..]..a..s.
000002a: 76ef3c 3f6383 7eff9c b9e37f                       v.<?c.~.....
</code>```

Try it online

Disassembled

```<code>set numin
set numout
add 1
fwd 1
add 1
fwd 6
get
sub 1
jmp
    jmp
        sub 1
        fwd 1
        add 1
        rwd 1
    jnz
    fwd 1
    sub 1
    rwd 2
    add 2
    jmp
        rwd 4
        jmp
            sub 1
            fwd 3
            add 1
            rwd 3
        jnz
        fwd 4
        jmp
            sub 1
            rwd 3
            add 1
            rwd 1
            add 1
            fwd 4
        jnz
        rwd 3
        jmp
            sub 1
            fwd 3
            add 1
            rwd 3
        jnz
        fwd 4
        add 2
        jmp
            rwd 5
            jmp
                rwd 1
                jmp
                    sub 1
                    fwd 2
                    add 1
                    rwd 2
                jnz
                fwd 1
                jmp
                    sub 1
                    rwd 1
                    add 1
                    fwd 1
                jnz
                rwd 1
                sub 1
            jnz
            fwd 2
            jmp
                sub 1
                rwd 1
                add 1
                rwd 1
                add 1
                fwd 2
            jnz
            fwd 1
            jmp
                rwd 2
                jmp
                    sub 1
                    fwd 1
                    add 1
                    rwd 1
                jnz
                fwd 2
                jmp
                    sub 1
                    rwd 2
                    add 1
                    fwd 2
                jnz
                fwd 1
            jnz
            fwd 3
            sub 1
        jnz
        rwd 2
        jmp
            sub 1
            rwd 3
            add 1
            fwd 3
        jnz
        fwd 1
        sub 1
    jnz
    fwd 2
jnz
rwd 7
put
</code>```

Or in Brainfuck notation:

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

Title: Hofstadter Q-sequence

Body:
Sesos, 54 bytes

0000000: eefb5b 04f83a a75dc2 36f8d7 cf6dd0 af7b3b 3ef8d7  ..[..:.].6...m..{;>..
0000015: cfed12 f661f0 ae9d83 ee63e6 065df7 ce6183 af7383  ....a.....c..]..a..s.
000002a: 76ef3c 3f6383 7eff9c b9e37f                       v.<?c.~.....

<a href="http://sesos.tryitonline.net/#code=c2V0IG51bWluCnNldCBudW1vdXQKYWRkIDEKZndkIDEKYWRkIDEKZndkIDYKZ2V0CnN1YiAxCmptcAogICAgam1wCiAgICAgICAgc3ViIDEKICAgICAgICBmd2QgMQogICAgICAgIGFkZCAxCiAgICAgICAgcndkIDEKICAgIGpuegogICAgZndkIDEKICAgIHN1YiAxCiAgICByd2QgMgogICAgYWRkIDIKICAgIGptcAogICAgICAgIHJ3ZCA0CiAgICAgICAgam1wCiAgICAgICAgICAgIHN1YiAxCiAgICAgICAgICAgIGZ3ZCAzCiAgICAgICAgICAgIGFkZCAxCiAgICAgICAgICAgIHJ3ZCAzCiAgICAgICAgam56CiAgICAgICAgZndkIDQKICAgICAgICBqbXAKICAgICAgICAgICAgc3ViIDEKICAgICAgICAgICAgcndkIDMKICAgICAgICAgICAgYWRkIDEKICAgICAgICAgICAgcndkIDEKICAgICAgICAgICAgYWRkIDEKICAgICAgICAgICAgZndkIDQKICAgICAgICBqbnoKICAgICAgICByd2QgMwogICAgICAgIGptcAogICAgICAgICAgICBzdWIgMQogICAgICAgICAgICBmd2QgMwogICAgICAgICAgICBhZGQgMQogICAgICAgICAgICByd2QgMwogICAgICAgIGpuegogICAgICAgIGZ3ZCA0CiAgICAgICAgYWRkIDIKICAgICAgICBqbXAKICAgICAgICAgICAgcndkIDUKICAgICAgICAgICAgam1wCiAgICAgICAgICAgICAgICByd2QgMQogICAgICAgICAgICAgICAgam1wCiAgICAgICAgICAgICAgICAgICAgc3ViIDEKICAgICAgICAgICAgICAgICAgICBmd2QgMgogICAgICAgICAgICAgICAgICAgIGFkZCAxCiAgICAgICAgICAgICAgICAgICAgcndkIDIKICAgICAgICAgICAgICAgIGpuegogICAgICAgICAgICAgICAgZndkIDEKICAgICAgICAgICAgICAgIGptcAogICAgICAgICAgICAgICAgICAgIHN1YiAxCiAgICAgICAgICAgICAgICAgICAgcndkIDEKICAgICAgICAgICAgICAgICAgICBhZGQgMQogICAgICAgICAgICAgICAgICAgIGZ3ZCAxCiAgICAgICAgICAgICAgICBqbnoKICAgICAgICAgICAgICAgIHJ3ZCAxCiAgICAgICAgICAgICAgICBzdWIgMQogICAgICAgICAgICBqbnoKICAgICAgICAgICAgZndkIDIKICAgICAgICAgICAgam1wCiAgICAgICAgICAgICAgICBzdWIgMQogICAgICAgICAgICAgICAgcndkIDEKICAgICAgICAgICAgICAgIGFkZCAxCiAgICAgICAgICAgICAgICByd2QgMQogICAgICAgICAgICAgICAgYWRkIDEKICAgICAgICAgICAgICAgIGZ3ZCAyCiAgICAgICAgICAgIGpuegogICAgICAgICAgICBmd2QgMQogICAgICAgICAgICBqbXAKICAgICAgICAgICAgICAgIHJ3ZCAyCiAgICAgICAgICAgICAgICBqbXAKICAgICAgICAgICAgICAgICAgICBzdWIgMQogICAgICAgICAgICAgICAgICAgIGZ3ZCAxCiAgICAgICAgICAgICAgICAgICAgYWRkIDEKICAgICAgICAgICAgICAgICAgICByd2QgMQogICAgICAgICAgICAgICAgam56CiAgICAgICAgICAgICAgICBmd2QgMgogICAgICAgICAgICAgICAgam1wCiAgICAgICAgICAgICAgICAgICAgc3ViIDEKICAgICAgICAgICAgICAgICAgICByd2QgMgogICAgICAgICAgICAgICAgICAgIGFkZCAxCiAgICAgICAgICAgICAgICAgICAgZndkIDIKICAgICAgICAgICAgICAgIGpuegogICAgICAgICAgICAgICAgZndkIDEKICAgICAgICAgICAgam56CiAgICAgICAgICAgIGZ3ZCAzCiAgICAgICAgICAgIHN1YiAxCiAgICAgICAgam56CiAgICAgICAgcndkIDIKICAgICAgICBqbXAKICAgICAgICAgICAgc3ViIDEKICAgICAgICAgICAgcndkIDMKICAgICAgICAgICAgYWRkIDEKICAgICAgICAgICAgZndkIDMKICAgICAgICBqbnoKICAgICAgICBmd2QgMQogICAgICAgIHN1YiAxCiAgICBqbnoKICAgIGZ3ZCAyCmpuegpyd2QgNwpwdXQ&input=MjA&debug=on">Try it online

Disassembled

set numin
set numout
add 1
fwd 1
add 1
fwd 6
get
sub 1
jmp
    jmp
        sub 1
        fwd 1
        add 1
        rwd 1
    jnz
    fwd 1
    sub 1
    rwd 2
    add 2
    jmp
        rwd 4
        jmp
            sub 1
            fwd 3
            add 1
            rwd 3
        jnz
        fwd 4
        jmp
            sub 1
            rwd 3
            add 1
            rwd 1
            add 1
            fwd 4
        jnz
        rwd 3
        jmp
            sub 1
            fwd 3
            add 1
            rwd 3
        jnz
        fwd 4
        add 2
        jmp
            rwd 5
            jmp
                rwd 1
                jmp
                    sub 1
                    fwd 2
                    add 1
                    rwd 2
                jnz
                fwd 1
                jmp
                    sub 1
                    rwd 1
                    add 1
                    fwd 1
                jnz
                rwd 1
                sub 1
            jnz
            fwd 2
            jmp
                sub 1
                rwd 1
                add 1
                rwd 1
                add 1
                fwd 2
            jnz
            fwd 1
            jmp
                rwd 2
                jmp
                    sub 1
                    fwd 1
                    add 1
                    rwd 1
                jnz
                fwd 2
                jmp
                    sub 1
                    rwd 2
                    add 1
                    fwd 2
                jnz
                fwd 1
            jnz
            fwd 3
            sub 1
        jnz
        rwd 2
        jmp
            sub 1
            rwd 3
            add 1
            fwd 3
        jnz
        fwd 1
        sub 1
    jnz
    fwd 2
jnz
rwd 7
put

Or in Brainfuck notation:

+>+>>>>>>,-[[->+<]>-<<++[<<<<[->>>+<<<]>>>>[-<<<+<+>>>>]<<<[->>>+<<<]>>>>++[<<<<<[<
[->>+<<]>[-<+>]<-]>>[-<+<+>>]>[<<[->+<]>>[-<<+>>]>]>>>-]<<[-<<<+>>>]>-]>>]<<<<<<<.


答:
VBA Excel 87 bytes

Non-recursive, since I want this to work for n=100000, say:

```<code>Function A(N):ReDim B(N):For i=3 To N:B(i)=B(i-B(i-1)-1)+B(i-B(i-2)-1)+1:Next:A=B(N)+1
</code>```

... and press return (byte #87) at the end of the line to get the End Function statement for "free". Note that B values are offset by -1 to avoid initializing for n=1 and 2.

Invoke in spreadsheet as normal, eg =A(100000) to get 48157

The recursive version, 61 bytes,

```<code>Function Y(N):If N<3 Then Y=1 Else Y=Y(N-Y(N-1))+Y(N-Y(N-2))
</code>```

starts to get unreasonably slow for n>30, and couldn't be said to work at all for n>40.

Title: Hofstadter Q-sequence

Body:
Definition

a(1) = 1

a(2) = 1

a(n) = a(n-a(n-1)) + a(n-a(n-2)) for n > 2 where n is an integer

Task

Given positive integer n, generate a(n).

Testcases

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

Reference

Obligatory OEIS A005185

Body:
VBA Excel 87 bytes

Non-recursive, since I want this to work for n=100000, say:

Function A(N):ReDim B(N):For i=3 To N:B(i)=B(i-B(i-1)-1)+B(i-B(i-2)-1)+1:Next:A=B(N)+1

... and press return (byte #87) at the end of the line to get the End Function statement for "free". Note that B values are offset by -1 to avoid initializing for n=1 and 2.

Invoke in spreadsheet as normal, eg =A(100000) to get 48157

The recursive version, 61 bytes,

Function Y(N):If N<3 Then Y=1 Else Y=Y(N-Y(N-1))+Y(N-Y(N-2))

starts to get unreasonably slow for n>30, and couldn't be said to work at all for n>40.


答:
JavaScript (ES6), <s>45 Bytes</s> 34 Bytes

A recursive solution in ES6. Any golfing tips much appreciated.

```<code>a=n=>n>2?a(n-a(n-1))+a(n-a(n-2)):1
</code>```

Thank you to /u/ismillo for shortening even further.

Title: Hofstadter Q-sequence

Body:
JavaScript (ES6), <s>45 Bytes</s> 34 Bytes

A recursive solution in ES6. Any golfing tips much appreciated.

a=n=>n>2?a(n-a(n-1))+a(n-a(n-2)):1

Thank you to /u/ismillo for shortening even further.


答:
Python 3, <s>374</s> 355 bytes

Not too refined python solution that is very generous with padding (uses maximum chessboard distance). Input is a single line where rows are separated with pipes | (although the algorithm can easily use anything not alphanumerical that isn't a newline or a EOF). Anything non alphanumeric or | works for input padding, output padding uses periods. Feedback and improvement from more seasoned python golfers is appreciated.

Edit: Some improvements thanks to @TheBikingViking. Also added even more margins since I wasn't quite generous enough with padding.

```<code>s=input()
l=[len(s),1+s.find('|')]['|'in s]
P=sorted([int(c),i%l,i//l]for i,c in enumerate(s)if c.isalnum())
L=X=Y=0
P[0][0]=-sum(p[0]for p in P)
for w,x,y in P:L=max(abs(x),abs(y),L);X+=x*w;Y+=y*w
P+=[['X',P[0][1]+X,P[0][2]+Y]]
P[0][0]=0
L=2*max(abs(X),abs(Y),L)
S=[2*L*["."]for _ in[0]*2*L]
for w,x,y in P:S[L+y][L+x]=str(w)
for s in S:print(''.join(s))
</code>```

Title: Linear combination of two vectors

Body:
Executive summary

Given input representing two vectors and their respective "weights", produce output that also represents the weighted sum of those vectors.

Challenge

The input will consist of one or more lines of the following characters:

exactly one occurrence of the digit 0, which represents the origin in a two-dimensional plane;

exactly two other digits (1-9; may or may not be the same digit), whose positions relative to the origin represent vectors, and whose values represent the weights attached to thse vectors;

some number of "background characters". The solver may choose a specific background character; for example, I will choose "." (mostly for human readability). Alternately, the background characters can be anything that look like blank space.

(The solver can choose whether the input is a single multi-line string or an array of one-line strings.)

For example, the input

```<code>....2
.0...
...3.
</code>```

represents a vector at coordinates (3,1) with weight 2, and a vector at coordinates (2,-1) with weight 3.

The output should be almost the same as the input, with the following changes:

a "result character", chosen by the solver, to be added at the position specified by weighted sum of the input vectors (equivalently, at the position that is the appropriate linear combination of the input vectors);

as many background characters as are needed to fit the origin, the two input vectors, and the output vector in the same picture. Extra background characters can be included if desired; the only constraint is that, if the background character is a visible character, then the entire output must be rectangular in shape and every character not representing a vector must be the background character. (If blank space is used as background characters, then these constraints don't need to be enforced.)

(In general, if we have one vector (v,w) with weight a and second vector (x,y) with weight b, their weighted sum is a(v,w)+b(x,y) = (av+bx,aw+by).)

In the previous example, the appropriate linear combination is 2*(3,1) + 3*(2,-1) = (12,-1). If we use "X" as the result character, then the output could look like

```<code>....2.........
.0............
...3.........X
</code>```

or

```<code>................
...2............
0...............
..3.........X...
................
................
</code>```

Usual code-golf scoring: the shortest answer, in bytes, wins.

Example input and output

If blank space is used, the above input would look like

```<code>    2
 0
   3
</code>```

and the output would look like

```<code>    2
 0
   3         X
</code>```

Leading/trailing whitespace characters/lines are irrelevant; if they're invisible to the reader, it's fine. (That being said, for the rest of the examples I'll go back to using "." for the background character, to make it easier to read.)

If both vectors have weight 1, then the result will look like a parallelogram: the input

```<code>.1.
...
1.0
</code>```

leads to the output

```<code>X.1.
....
.1.0
</code>```

Note this parallelogram can be degenerate if the input vectors are collinear: the input

```<code>0.1..1
</code>```

leads to the output

```<code>0.1..1.X
</code>```

It is possible for the result vector to equal one of the input vectors or the origin; in this case, it simply overwrites the input character. For example, the input

```<code>..2.0.1...
</code>```

yields the output

```<code>....2.........
.0............
...3.........X
</code>```0

(where in input and/or output, the leading and trailing periods could be deleted). The input

```<code>....2.........
.0............
...3.........X
</code>```1

yields the output

```<code>....2.........
.0............
...3.........X
</code>```2

Finally, the input

```<code>90
.8
</code>```

yields the output

```<code>........90
.........8
..........
..........
..........
..........
..........
..........
X.........
</code>```

Body:
Python 3, <s>374</s> 355 bytes

Not too refined python solution that is very generous with padding (uses maximum chessboard distance). Input is a single line where rows are separated with pipes | (although the algorithm can easily use anything not alphanumerical that isn't a newline or a EOF). Anything non alphanumeric or | works for input padding, output padding uses periods. Feedback and improvement from more seasoned python golfers is appreciated.

Edit: Some improvements thanks to @TheBikingViking. Also added even more margins since I wasn't quite generous enough with padding.

s=input()
l=[len(s),1+s.find('|')]['|'in s]
P=sorted([int(c),i%l,i//l]for i,c in enumerate(s)if c.isalnum())
L=X=Y=0
P[0][0]=-sum(p[0]for p in P)
for w,x,y in P:L=max(abs(x),abs(y),L);X+=x*w;Y+=y*w
P+=[['X',P[0][1]+X,P[0][2]+Y]]
P[0][0]=0
L=2*max(abs(X),abs(Y),L)
S=[2*L*["."]for _ in[0]*2*L]
for w,x,y in P:S[L+y][L+x]=str(w)
for s in S:print(''.join(s))


问:
Golf all the 16 logic gates with 2 inputs and 1 output!
For example, the gate A and B is a logic gate with 2 inputs and 1 output.

There are exactly 16 of them, because:

each logic gate takes two inputs, which can be truthy or falsey, giving us 4 possible inputs

of the 4 possible inputs, each can have an output of truthy and falsey

therefore, there are 2^4 possible logic gates, which is 16.

Your task is to write 16 programs/functions which implement all of them separately.

Your functions/programs must be independent.

They are valid as long as they output truthy/falsey values, meaning that you can implement A or B in Python as lambda a,b:a+b, even if 2 is produced for A=True and B=True.

Score is total bytes used for each function/program.

List of logic gates

0,0,0,0 (false)

0,0,0,1 (and)

0,0,1,0 (A and not B)

0,0,1,1 (A)

0,1,0,0 (not A and B)

0,1,0,1 (B)

0,1,1,0 (xor)

0,1,1,1 (or)

1,0,0,0 (nor)

1,0,0,1 (xnor)

1,0,1,0 (not B)

1,0,1,1 (B implies A)

1,1,0,0 (not A)

1,1,0,1 (A implies B)

1,1,1,0 (nand)

1,1,1,1 (true)

Where the first number is the output for A=false, B=false,
the second number is the output for A=false, B=true,
the third number is the output for A=true, B=false,
the fourth number is the output for A=true, B=true.

Leaderboard

var QUESTION_ID=82938,OVERRIDE_USER=48934;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+(?:\.\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

```

答:
Bitwise Cyclic Tag, 118 bits = 14.75 bytes

Bitwise Cyclic Tag is perhaps the simplest Turing-complete language ever devised. There is a program tape and a data tape, both consisting of a list of bits. The program tape is interpreted cyclically until the data tape is empty, as follows:

0: delete the first bit from the data tape.

1x: if the first bit of the data tape is 1, append the bit x to the data tape.

We initialize the data tape with a 1 followed by the two input bits (the 1 is necessary because there is no way to create a 1 if the data tape consists entirely of 0s), and we use the final deleted data bit as the gate’s output.

0,0,0,0 (false): 001

0,0,0,1 (and): 1001001

0,0,1,0 (A and not B): 0110100

0,0,1,1 (A): 1001

0,1,0,0 (not A and B): 0100

0,1,0,1 (B): 0

0,1,1,0 (xor): 0110110010

0,1,1,1 (or): 0110

1,0,0,0 (nor): 1101001000

1,0,0,1 (xnor): 110101001100

1,0,1,0 (not B): 1100100

1,0,1,1 (B implies A): 110101101000

1,1,0,0 (not A): 11010000

1,1,0,1 (A implies B): 11010011001

1,1,1,0 (nand): 10110100100010

1,1,1,1 (true): 1100


问:
Make a sprite-sheet from all the Stack Exchange sites' favicons
Your goal in this code golf is to compile all the Stack Exchange sites' favicons.

Getting the Domains

The domains you will be using will be:

*.stackexchange.com

stackexchange.com

stackoverflow.com

superuser.com

serverfault.com

askubuntu.com

mathoverflow.net

stackapps.com

stackauth.com

Everything but stackexchange.com and stackauth.com, as of now, can be gathered from /sites.

All the meta counterparts will also be included. (just prepend meta. to the beginning of any of the domains to get the meta site)

The list above shows the order of the sites. Sites without their own domain (*.stackexchange.com, i.e. codegolf.stackexchange.com) are first in the stylesheet, and are sorted alphabetically. After you've sorted the subdomain sites, the rest of the domains are in the order listed above.

Then, you can append /favicon.ico to each one of the domains you dynamically compiled and get the 32 by 32 pixel image that results from it.

Here's another list for domains that redirect to *.stackexchange.com sites:

askdifferent.com → apple.stackexchange.com

arqade.com → gaming.stackexchange.com

seasonedadvice.com → cooking.stackexchange.com

Output the Images

As soon as you have all of the favicons from the sites and their meta counterparts, your code combines them. Optionally, convert them into .PNG files (you gathered .ICOs, and trying to get favicon.png doesn't work) After that, you can start combining the images into one rectangle.

There will be 10 columns, each 32 pixels in width, making a total of 320 pixels. The number of rows will match those needed to fit all the favicons, and they are 32 pixels in height.

Your code should output an image with all of the favicons you gathered as a transparent .PNG file, which is already , like seen below:

Scoring

This is code-golf and so the least bytes wins!

Leaderboard

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

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

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

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

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

var QUESTION_ID=86753;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 getAnswers(){jQuery.ajax({url:answersUrl(page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),e.has_more?getAnswers():process()}})}function shouldHaveHeading(e){var a=!1,r=e.body_markdown.split("\n");try{a|=/^#/.test(e.body_markdown),a|=["-","="].indexOf(r[1][0])>-1,a&=LANGUAGE_REG.test(e.body_markdown)}catch(n){}return a}function shouldHaveScore(e){var a=!1;try{a|=SIZE_REG.test(e.body_markdown.split("\n")[0])}catch(r){}return a}function getAuthorName(e){return e.owner.display_name}function process(){answers=answers.filter(shouldHaveScore).filter(shouldHaveHeading),answers.sort(function(e,a){var r=+(e.body_markdown.split("\n")[0].match(SIZE_REG)||[1/0])[0],n=+(a.body_markdown.split("\n")[0].match(SIZE_REG)||[1/0])[0];return r-n});var e={},a=1,r=null,n=1;answers.forEach(function(s){var t=s.body_markdown.split("\n")[0],o=jQuery("#answer-template").html(),l=(t.match(NUMBER_REG)[0],(t.match(SIZE_REG)||[0])[0]),c=t.match(LANGUAGE_REG)[1],i=getAuthorName(s);l!=r&&(n=a),r=l,++a,o=o.replace("{{PLACE}}",n+".").replace("{{NAME}}",i).replace("{{LANGUAGE}}",c).replace("{{SIZE}}",l).replace("{{LINK}}",s.share_link),o=jQuery(o),jQuery("#answers").append(o),e[c]=e[c]||{lang:c,user:i,size:l,link:s.share_link}});var s=[];for(var t in e)e.hasOwnProperty(t)&&s.push(e[t]);s.sort(function(e,a){return e.lang>a.lang?1:e.lang<a.lang?-1:0});for(var o=0;o<s.length;++o){var l=jQuery("#language-template").html(),t=s[o];l=l.replace("{{LANGUAGE}}",t.lang).replace("{{NAME}}",t.user).replace("{{SIZE}}",t.size).replace("{{LINK}}",t.link),l=jQuery(l),jQuery("#languages").append(l)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",answers=[],page=1;getAnswers();var SIZE_REG=/\d+(?=[^\d&]*(?:<(?:s>[^&]*<\/s>|[^&]+>)[^\d&]*)*$)/,NUMBER_REG=/\d+/,LANGUAGE_REG=/^#*\s*([^,]+)/;```
<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

```

答:
Python 3.5, <s>591</s> <s>549</s> <s>541</s> <s>557</s> 570 bytes:

(+16 bytes (541 -> 557) to add the ability for the final image to dynamically expand in height based on the number of favicons gathered.)

(+13 bytes (557 -> 570) since URL shorteners are apparently not allowed.)

```<code>from urllib.request import*;from PIL import Image as I;from io import*;import re
H='http://';U=urlopen;u=y=0;V=sorted(re.findall('<h2><a href="%s((?!meta).+?.stackexchange.com)">'%H,U(H+'stackexchange.com/sites?view=list').read().decode()[7167:]))+['%s.com'%i for i in'stackexchange stackoverflow superuser serverfault askubuntu mathoverflow stackapps stackauth'.split()];i=I.new("RGBA",(320,-~(len(V)*2//10)*32))
for l in V+['meta.'+i for i in V]:
 try:
  i.paste(I.open(BytesIO(U(H+l+'/favicon.ico').read())),(u,y));u+=32
  if u>319:u=0;y+=32
 except:0
i.save('O.png')
</code>```

Quite long, but hey, I beat Javascript! :D This imports the modules for the following uses:

urllib to fetch website and image data.

io module for the BytesIO function to decode the fetched image data for PIL.

re for the use of regular expressions to parse the website data.

PIL to create the final image from the fetched image data.

Creates and saves a 320 x 1024 PNG image named O.png in the current working directory, with all the favicons in the order specified. I will try to golf this down more over time as much as I can, but for now, I could not be happier. :)

Final Output Image:

Body:
Python 3.5, <s>591</s> <s>549</s> <s>541</s> <s>557</s> 570 bytes:

(+16 bytes (541 -> 557) to add the ability for the final image to dynamically expand in height based on the number of favicons gathered.)

(+13 bytes (557 -> 570) since URL shorteners are apparently not allowed.)

from urllib.request import*;from PIL import Image as I;from io import*;import re
H='http://';U=urlopen;u=y=0;V=sorted(re.findall('<h2><a href="%s((?!meta).+?.stackexchange.com)">'%H,U(H+'stackexchange.com/sites?view=list').read().decode()[7167:]))+['%s.com'%i for i in'stackexchange stackoverflow superuser serverfault askubuntu mathoverflow stackapps stackauth'.split()];i=I.new("RGBA",(320,-~(len(V)*2//10)*32))
for l in V+['meta.'+i for i in V]:
 try:
  i.paste(I.open(BytesIO(U(H+l+'/favicon.ico').read())),(u,y));u+=32
  if u>319:u=0;y+=32
 except:0
i.save('O.png')

Quite long, but hey, I beat Javascript! :D This imports the modules for the following uses:

urllib to fetch website and image data.

io module for the BytesIO function to decode the fetched image data for PIL.

re for the use of regular expressions to parse the website data.

PIL to create the final image from the fetched image data.

Creates and saves a 320 x 1024 PNG image named O.png in the current working directory, with all the favicons in the order specified. I will try to golf this down more over time as much as I can, but for now, I could not be happier. :)

Final Output Image:


问:
Write the fastest Fibonacci
This is yet another challenge about the Fibonacci numbers.

The goal is to compute the 20'000'000th Fibonacii number as fast as possible. The decimal output is about 4 MiB large; it starts with:

28543982899108793710435526490684533031144309848579

The MD5 sum of the output is

fa831ff5dd57a830792d8ded4c24c2cb

You have to submit a program that calculates the number while running and puts the result to stdout. The fastest program, as measured on my own machine, wins.

Here are some additional rules:

You have to submit the source code and a binary runnable on an x64 Linux

The source code must be shorter than 1 MiB, in case of assembly it is also acceptable if only the binary is that small.

You must not include the number to be computed in your binary, even in a disguised fashion. The number has to be calculated at runtime.

My computer has two cores; you are allowed to use parallelism

I took a small implementation from the Internet which runs in about 4.5 seconds. It should not be very difficult to beat this, assuming that you have a good algorithm.

答:
Go

It's embarrasingly slow. On my computer it takes a little less than 3 minutes. It's only 120 recursive calls, though (after adding the cache). Note that this may use a lot of memory (like 1.4 GiB)!

```<code>package main

import (
    "math/big"
    "fmt"
)

var cache = make(map[int64] *big.Int)

func fib_log_cache(n int64) *big.Int {
    if res, ok := cache[n]; ok {
        return res
    }
    res := fib_log(n)
    cache[n] = res
    return res
}

func fib_log(n int64) *big.Int {
    if n <= 1 {
        return big.NewInt(n)
    }

    if n % 2 == 0 {
        f_n_half := fib_log_cache(n/2)
        f_n_half_minus_one := fib_log_cache(n/2-1)
        res := new(big.Int).Lsh(f_n_half_minus_one, 1)
        res.Add(f_n_half, res)
        res.Mul(f_n_half, res)
        return res
    }
    f_n_half := fib_log_cache(n/2)
    f_n_half_plus_one := fib_log_cache(n/2+1)
    res := new(big.Int).Mul(f_n_half_plus_one, f_n_half_plus_one)
    tmp := new(big.Int).Mul(f_n_half, f_n_half)
    res.Add(res, tmp)
    return res
}

func main() {
    fmt.Println(fib_log(20000000))
}
</code>```

Title: Write the fastest Fibonacci

Body:
Go

It's embarrasingly slow. On my computer it takes a little less than 3 minutes. It's only 120 recursive calls, though (after adding the cache). Note that this may use a lot of memory (like 1.4 GiB)!

package main

import (
    "math/big"
    "fmt"
)

var cache = make(map[int64] *big.Int)

func fib_log_cache(n int64) *big.Int {
    if res, ok := cache[n]; ok {
        return res
    }
    res := fib_log(n)
    cache[n] = res
    return res
}

func fib_log(n int64) *big.Int {
    if n <= 1 {
        return big.NewInt(n)
    }

    if n % 2 == 0 {
        f_n_half := fib_log_cache(n/2)
        f_n_half_minus_one := fib_log_cache(n/2-1)
        res := new(big.Int).Lsh(f_n_half_minus_one, 1)
        res.Add(f_n_half, res)
        res.Mul(f_n_half, res)
        return res
    }
    f_n_half := fib_log_cache(n/2)
    f_n_half_plus_one := fib_log_cache(n/2+1)
    res := new(big.Int).Mul(f_n_half_plus_one, f_n_half_plus_one)
    tmp := new(big.Int).Mul(f_n_half, f_n_half)
    res.Add(res, tmp)
    return res
}

func main() {
    fmt.Println(fib_log(20000000))
}


问:
Random character from a string
Your goal in this code-golf is to pick a random character from a string. If a character appears X times, and there are Y characters, then the chance of that character being picked will be X/Y.

Input

The program takes a string as an input.

Output

Your program outputs a character.

Examples

xyz: x, y, or z

xxX: x, x, or X

}^€: }, ^, or €

xxx: x

0123456789: random number, 0-9

答:
Pyth, 1 byte

```<code>O
</code>```

Try it online!

Explanation

From the definition of the operator O:

```<code>op. arg.    func.
O   <col>   Random element of A.
</code>```

Title: Random character from a string

Body:
Pyth, 1 byte

O

Try it online!

Explanation

From the definition of the operator O:

op. arg.    func.
O   <col>   Random element of A.


答:
PowerShell, 231 bytes

These are all full scripts, with arguments passed as either Boolean values ($true or $false) or integers (0 or 1 for false and true, respectively) on the command line.

0000 is pretty simple, by which I mean it's completely blank. Null coerces to $false.

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

0001 multiplies the two values together; $true coerces to 1, $false to 0.

```<code>$args[0]*$args[1]
</code>```

0010 inverts B by subtracting 1 from it, then does the same as the previous. The integer -1 coerces to $true.

```<code>$args[0]*($args[1]-1)
</code>```

0011 just returns A.

```<code>$args[0]
</code>```

0100 does the same as #3, just flipped.

```<code>($args[0]-1)*$args[1]
</code>```

0101 just returns B.

```<code>$args[1]
</code>```

0110 subtracts B from A, again using the fact that any nonzero value becomes $true.

```<code>$args[0]-$args[1]
</code>```

0111 adds the two arguments together.

```<code>$args[0]+$args[1]
</code>```

1000 adds the two and makes sure the result is still zero.

```<code>$args[0]+$args[1]-eq0
</code>```

1001 makes sure the values are the same.

```<code>$args[0]-eq$args[1]
</code>```

1010 subtracts 1 from B.

```<code>$args[1]-1
</code>```

1011 shifts B to the left, adds A, and subtracts two. If the result is zero, we found the one unacceptable configuration.

```<code>$args[1]*2+$args[0]-2
</code>```

1100 inverts A with the same trick as #11.

```<code>$args[0]-1
</code>```

1101 is the same as #12 but with the arguments flipped.

```<code>$args[0]*2+$args[1]-2
</code>```

1110 does "and" and then inverts it.

```<code>$args[0]*$args[1]-1
</code>```

1111 is just $true.

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

Title: Golf all the 16 logic gates with 2 inputs and 1 output!

Body:
For example, the gate A and B is a logic gate with 2 inputs and 1 output.

There are exactly 16 of them, because:

each logic gate takes two inputs, which can be truthy or falsey, giving us 4 possible inputs

of the 4 possible inputs, each can have an output of truthy and falsey

therefore, there are 2^4 possible logic gates, which is 16.

Your task is to write 16 programs/functions which implement all of them separately.

Your functions/programs must be independent.

They are valid as long as they output truthy/falsey values, meaning that you can implement A or B in Python as lambda a,b:a+b, even if 2 is produced for A=True and B=True.

Score is total bytes used for each function/program.

List of logic gates

0,0,0,0 (false)

0,0,0,1 (and)

0,0,1,0 (A and not B)

0,0,1,1 (A)

0,1,0,0 (not A and B)

0,1,0,1 (B)

0,1,1,0 (xor)

0,1,1,1 (or)

1,0,0,0 (nor)

1,0,0,1 (xnor)

1,0,1,0 (not B)

1,0,1,1 (B implies A)

1,1,0,0 (not A)

1,1,0,1 (A implies B)

1,1,1,0 (nand)

1,1,1,1 (true)

Where the first number is the output for A=false, B=false,
the second number is the output for A=false, B=true,
the third number is the output for A=true, B=false,
the fourth number is the output for A=true, B=true.

Leaderboard

var QUESTION_ID=82938,OVERRIDE_USER=48934;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+(?:\.\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

```

Body:
PowerShell, 231 bytes

These are all full scripts, with arguments passed as either Boolean values ($true or $false) or integers (0 or 1 for false and true, respectively) on the command line.

0000 is pretty simple, by which I mean it's completely blank. Null coerces to $false.

0001 multiplies the two values together; $true coerces to 1, $false to 0.

$args[0]*$args[1]

0010 inverts B by subtracting 1 from it, then does the same as the previous. The integer -1 coerces to $true.

$args[0]*($args[1]-1)

0011 just returns A.

$args[0]

0100 does the same as #3, just flipped.

($args[0]-1)*$args[1]

0101 just returns B.

$args[1]

0110 subtracts B from A, again using the fact that any nonzero value becomes $true.

$args[0]-$args[1]

0111 adds the two arguments together.

$args[0]+$args[1]

1000 adds the two and makes sure the result is still zero.

$args[0]+$args[1]-eq0

1001 makes sure the values are the same.

$args[0]-eq$args[1]

1010 subtracts 1 from B.

$args[1]-1

1011 shifts B to the left, adds A, and subtracts two. If the result is zero, we found the one unacceptable configuration.

$args[1]*2+$args[0]-2

1100 inverts A with the same trick as #11.

$args[0]-1

1101 is the same as #12 but with the arguments flipped.

$args[0]*2+$args[1]-2

1110 does "and" and then inverts it.

$args[0]*$args[1]-1

1111 is just $true.

1


答:
Jelly, 1 byte

```<code>X
</code>```

Try it online!

Explanation

From the definition of the operator X:

Arity: 1

Name: Random

Function: choose a random item from z if z is a list, or from 1 to z inclusive if z is a positive integer. If z = 0, return z. Error if z is negative or a decimal.

Title: Random character from a string

Body:
Your goal in this code-golf is to pick a random character from a string. If a character appears X times, and there are Y characters, then the chance of that character being picked will be X/Y.

Input

The program takes a string as an input.

Output

Your program outputs a character.

Examples

xyz: x, y, or z

xxX: x, x, or X

}^€: }, ^, or €

xxx: x

0123456789: random number, 0-9

Body:
Jelly, 1 byte

X

Try it online!

Explanation

From the definition of the operator X:

Arity: 1

Name: Random

Function: choose a random item from z if z is a list, or from 1 to z inclusive if z is a positive integer. If z = 0, return z. Error if z is negative or a decimal.


答:
Actually, 1 byte

```<code>J
</code>```

Try it online!

Explanation

From the definition of the operator J:

4A (J): pop a: push a random integer in [0,a) (randrange(a)); pop [a] or "a": push a random element from [a] or "a" (random.choice([a]|"a"))

Title: Random character from a string

Body:
Actually, 1 byte

J

Try it online!

Explanation

From the definition of the operator J:

4A (J): pop a: push a random integer in [0,a) (randrange(a)); pop [a] or "a": push a random element from [a] or "a" (random.choice([a]|"a"))


答:
J, 5 bytes

```<code>?@#{]
</code>```

Usage

```<code>>> f =: ?@#{]
>> f 'xyz'
<< x
</code>```

Explanation

This is a fork, where f is ?@#, g is {, and h is ].

Therefore, (?@#{])'xyz', when expanded, would become ((?@#)'xyz') ({) ((])'xyz')

The (?@#) is just a composed function, so (?@#)'xyz' expanded would become ?(#'xyz').

#'xyz' gets the length of 'xyz', then ? generates a random non-negative integer below the length.

The { then takes the item at the corresponding index.

Title: Random character from a string

Body:
J, 5 bytes

?@#{]

Usage

>> f =: ?@#{]
>> f 'xyz'
<< x

Explanation

This is a fork, where f is ?@#, g is {, and h is ].

Therefore, (?@#{])'xyz', when expanded, would become ((?@#)'xyz') ({) ((])'xyz')

The (?@#) is just a composed function, so (?@#)'xyz' expanded would become ?(#'xyz').

#'xyz' gets the length of 'xyz', then ? generates a random non-negative integer below the length.

The { then takes the item at the corresponding index.


答:
CJam, 3 bytes

```<code>lmR
</code>```

Try it online!

```<code>lmR
l    read line
 mR  random element
</code>```

Title: Random character from a string

Body:
CJam, 3 bytes

lmR

Try it online!

lmR
l    read line
 mR  random element


答:
Python 3.5 and Python 2.7, 26 bytes:

```<code>from random import*;choice
</code>```

A function declaration. Name the function, and then call it like print(<Function Name>(<String>)).

Title: Random character from a string

Body:
Python 3.5 and Python 2.7, 26 bytes:

from random import*;choice

A function declaration. Name the function, and then call it like print(<Function Name>(<String>)).


答:
05AB1E, 2 bytes

```<code>.R
</code>```

from Info.txt:

```<code>.R      = pop a      push random_pick(a)
</code>```

Try it online!

Title: Random character from a string

Body:
05AB1E, 2 bytes

.R

from Info.txt:

.R      = pop a      push random_pick(a)

Try it online!


答:
Java 8, 44 bytes

x->x.charAt((int)(Math.random()*x.length()))
```

Try it online!

Title: Random character from a string

Body:
Java 8, 44 bytes

x->x.charAt((int)(Math.random()*x.length()))

Try it online!


答:
Ocaml, 0.856s on my laptop

Requires the zarith library. I used  Big_int but it's dog slow compared to zarith. It took 10 minutes with the same code! Most of the time was spent printing the damn number (9½ minutes or so)!

```<code>module M = Map.Make
  (struct
    type t = int
    let compare = compare
   end)

let double b = Z.shift_left b 1
let ( +. ) b1 b2 = Z.add b1 b2
let ( *. ) b1 b2 = Z.mul b1 b2

let cache = ref M.empty
let rec fib_log n =
  if n = 0
  then Z.zero
  else if n = 1
  then Z.one
  else if n mod 2 = 0
  then
    let f_n_half = fib_log_cached (n/2)
    and f_n_half_minus_one = fib_log_cached (n/2-1)
    in f_n_half *. (f_n_half +. double f_n_half_minus_one)
  else
    let f_n_half = fib_log_cached (n/2)
    and f_n_half_plus_one = fib_log_cached (n/2+1)
    in (f_n_half *. f_n_half) +.
    (f_n_half_plus_one *. f_n_half_plus_one)
and fib_log_cached n =
    try M.find n !cache
    with Not_found ->
      let res = fib_log n
      in cache := M.add n res !cache;
      res

let () =
  let res = fib_log 20_000_000 in
  Z.print res; print_newline ()
</code>```

I can't believe how much a difference the library made!

Title: Write the fastest Fibonacci

Body:
This is yet another challenge about the Fibonacci numbers.

The goal is to compute the 20'000'000th Fibonacii number as fast as possible. The decimal output is about 4 MiB large; it starts with:

28543982899108793710435526490684533031144309848579

The MD5 sum of the output is

fa831ff5dd57a830792d8ded4c24c2cb

You have to submit a program that calculates the number while running and puts the result to stdout. The fastest program, as measured on my own machine, wins.

Here are some additional rules:

You have to submit the source code and a binary runnable on an x64 Linux

The source code must be shorter than 1 MiB, in case of assembly it is also acceptable if only the binary is that small.

You must not include the number to be computed in your binary, even in a disguised fashion. The number has to be calculated at runtime.

My computer has two cores; you are allowed to use parallelism

I took a small implementation from the Internet which runs in about 4.5 seconds. It should not be very difficult to beat this, assuming that you have a good algorithm.

Body:
Ocaml, 0.856s on my laptop

Requires the zarith library. I used  Big_int but it's dog slow compared to zarith. It took 10 minutes with the same code! Most of the time was spent printing the damn number (9½ minutes or so)!

module M = Map.Make
  (struct
    type t = int
    let compare = compare
   end)

let double b = Z.shift_left b 1
let ( +. ) b1 b2 = Z.add b1 b2
let ( *. ) b1 b2 = Z.mul b1 b2

let cache = ref M.empty
let rec fib_log n =
  if n = 0
  then Z.zero
  else if n = 1
  then Z.one
  else if n mod 2 = 0
  then
    let f_n_half = fib_log_cached (n/2)
    and f_n_half_minus_one = fib_log_cached (n/2-1)
    in f_n_half *. (f_n_half +. double f_n_half_minus_one)
  else
    let f_n_half = fib_log_cached (n/2)
    and f_n_half_plus_one = fib_log_cached (n/2+1)
    in (f_n_half *. f_n_half) +.
    (f_n_half_plus_one *. f_n_half_plus_one)
and fib_log_cached n =
    try M.find n !cache
    with Not_found ->
      let res = fib_log n
      in cache := M.add n res !cache;
      res

let () =
  let res = fib_log 20_000_000 in
  Z.print res; print_newline ()

I can't believe how much a difference the library made!


答:
Javascript, 40 bytes

x=>x[Math.floor(x.length*Math.random())]
```

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>f=x=>x[Math.floor(x.length*Math.random())]
alert(f(prompt()))</code>```

Title: Random character from a string

Body:
Javascript, 40 bytes

x=>x[Math.floor(x.length*Math.random())]

f=x=>x[Math.floor(x.length*Math.random())]
alert(f(prompt()))


答:
VBA, 284 bytes

```<code>Function H(W,S)
L=vbLf:H=Space(4*W)&"*"&L
For R=1 To 4*W:H=H &Space(4*W-R)&"/"&Space(2*R-1)&"\"&L:Next
J=".":P=String(W,J)&"|"&L
D=String(8*W+1,"-")&L
E=Replace(P,J,"|       ")
F=Replace(P,J,"|  ---  ")
H=H &Replace(String(S,J),J,D &E &F &Replace(P,J,"|  | |  ")&F &E)&D
End Function
</code>```

The Replace function is a neat tool for making multiple copies in a way that the String function unfortunately doesn't want to.

Invoke for best effect in the Immediate window of the VBA editor: ?H(8,8) for example.

```<code>?H(8,8)
                                *
                               / \
                              /   \
                             /     \
                            /       \
                           /         \
                          /           \
                         /             \
                        /               \
                       /                 \
                      /                   \
                     /                     \
                    /                       \
                   /                         \
                  /                           \
                 /                             \
                /                               \
               /                                 \
              /                                   \
             /                                     \
            /                                       \
           /                                         \
          /                                           \
         /                                             \
        /                                               \
       /                                                 \
      /                                                   \
     /                                                     \
    /                                                       \
   /                                                         \
  /                                                           \
 /                                                             \
/                                                               \
-----------------------------------------------------------------
|       |       |       |       |       |       |       |       |
|  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |
|  | |  |  | |  |  | |  |  | |  |  | |  |  | |  |  | |  |  | |  |
|  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |
|       |       |       |       |       |       |       |       |
-----------------------------------------------------------------
|       |       |       |       |       |       |       |       |
|  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |
|  | |  |  | |  |  | |  |  | |  |  | |  |  | |  |  | |  |  | |  |
|  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |
|       |       |       |       |       |       |       |       |
-----------------------------------------------------------------
|       |       |       |       |       |       |       |       |
|  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |
|  | |  |  | |  |  | |  |  | |  |  | |  |  | |  |  | |  |  | |  |
|  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |
|       |       |       |       |       |       |       |       |
-----------------------------------------------------------------
|       |       |       |       |       |       |       |       |
|  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |
|  | |  |  | |  |  | |  |  | |  |  | |  |  | |  |  | |  |  | |  |
|  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |
|       |       |       |       |       |       |       |       |
-----------------------------------------------------------------
|       |       |       |       |       |       |       |       |
|  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |
|  | |  |  | |  |  | |  |  | |  |  | |  |  | |  |  | |  |  | |  |
|  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |
|       |       |       |       |       |       |       |       |
-----------------------------------------------------------------
|       |       |       |       |       |       |       |       |
|  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |
|  | |  |  | |  |  | |  |  | |  |  | |  |  | |  |  | |  |  | |  |
|  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |
|       |       |       |       |       |       |       |       |
-----------------------------------------------------------------
|       |       |       |       |       |       |       |       |
|  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |
|  | |  |  | |  |  | |  |  | |  |  | |  |  | |  |  | |  |  | |  |
|  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |
|       |       |       |       |       |       |       |       |
-----------------------------------------------------------------
|       |       |       |       |       |       |       |       |
|  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |
|  | |  |  | |  |  | |  |  | |  |  | |  |  | |  |  | |  |  | |  |
|  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |
|       |       |       |       |       |       |       |       |
-----------------------------------------------------------------
</code>```

Title: Draw an ASCII house

Body:
This is a window:

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

Let's add some walls |. Put two spaces on either side of it so that the window has plenty of room.

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

Now let's add a roof and a ceiling. To keep the window in the middle of the room, let's add one more row above it and below it.

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

Now, just add a roof. Put a slash as far left as possible, and a backslash as far right as possible, and we have this:

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

Then move the slash up one and right one. Move the backslash up one and left one:

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

Repeat until the two slashes meet, then add an asterisk where they meet:

```<code>    *
   / \
  /   \
 /     \
/       \
---------
|       |
|  ---  |
|  | |  |
|  ---  |
|       |
---------
</code>```

And you're done! This is a 1x1 house. a 2x2 house would look like this:

```<code>        *
       / \
      /   \
     /     \
    /       \
   /         \
  /           \
 /             \
/               \
-----------------
|       |       |
|  ---  |  ---  |
|  | |  |  | |  |
|  ---  |  ---  |
|       |       |
|-------|-------|
|       |       |
|  ---  |  ---  |
|  | |  |  | |  |
|  ---  |  ---  |
|       |       |
-----------------
</code>```

and a 3x2 house:

```<code>            *
           / \
          /   \
         /     \
        /       \
       /         \
      /           \
     /             \
    /               \
   /                 \
  /                   \
 /                     \
/                       \
-------------------------
|       |       |       |
|  ---  |  ---  |  ---  |
|  | |  |  | |  |  | |  |
|  ---  |  ---  |  ---  |
|       |       |       |
|-------|-------|-------|
|       |       |       |
|  ---  |  ---  |  ---  |
|  | |  |  | |  |  | |  |
|  ---  |  ---  |  ---  |
|       |       |       |
-------------------------
</code>```

The challenge

You must write a full program that takes two integers, x and y, and prints a house that is X rooms wide and Y rooms tall. Your program should be able to handle houses up to 10x10. IO can be in any reasonable format. Trailing spaces on each line are allowed, and one trailing newline is allowed.

Shortest answer in bytes wins.

Body:
VBA, 284 bytes

Function H(W,S)
L=vbLf:H=Space(4*W)&"*"&L
For R=1 To 4*W:H=H &Space(4*W-R)&"/"&Space(2*R-1)&"\"&L:Next
J=".":P=String(W,J)&"|"&L
D=String(8*W+1,"-")&L
E=Replace(P,J,"|       ")
F=Replace(P,J,"|  ---  ")
H=H &Replace(String(S,J),J,D &E &F &Replace(P,J,"|  | |  ")&F &E)&D
End Function

The Replace function is a neat tool for making multiple copies in a way that the String function unfortunately doesn't want to.

Invoke for best effect in the Immediate window of the VBA editor: ?H(8,8) for example.

?H(8,8)
                                *
                               / \
                              /   \
                             /     \
                            /       \
                           /         \
                          /           \
                         /             \
                        /               \
                       /                 \
                      /                   \
                     /                     \
                    /                       \
                   /                         \
                  /                           \
                 /                             \
                /                               \
               /                                 \
              /                                   \
             /                                     \
            /                                       \
           /                                         \
          /                                           \
         /                                             \
        /                                               \
       /                                                 \
      /                                                   \
     /                                                     \
    /                                                       \
   /                                                         \
  /                                                           \
 /                                                             \
/                                                               \
-----------------------------------------------------------------
|       |       |       |       |       |       |       |       |
|  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |
|  | |  |  | |  |  | |  |  | |  |  | |  |  | |  |  | |  |  | |  |
|  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |
|       |       |       |       |       |       |       |       |
-----------------------------------------------------------------
|       |       |       |       |       |       |       |       |
|  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |
|  | |  |  | |  |  | |  |  | |  |  | |  |  | |  |  | |  |  | |  |
|  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |
|       |       |       |       |       |       |       |       |
-----------------------------------------------------------------
|       |       |       |       |       |       |       |       |
|  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |
|  | |  |  | |  |  | |  |  | |  |  | |  |  | |  |  | |  |  | |  |
|  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |
|       |       |       |       |       |       |       |       |
-----------------------------------------------------------------
|       |       |       |       |       |       |       |       |
|  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |
|  | |  |  | |  |  | |  |  | |  |  | |  |  | |  |  | |  |  | |  |
|  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |
|       |       |       |       |       |       |       |       |
-----------------------------------------------------------------
|       |       |       |       |       |       |       |       |
|  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |
|  | |  |  | |  |  | |  |  | |  |  | |  |  | |  |  | |  |  | |  |
|  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |
|       |       |       |       |       |       |       |       |
-----------------------------------------------------------------
|       |       |       |       |       |       |       |       |
|  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |
|  | |  |  | |  |  | |  |  | |  |  | |  |  | |  |  | |  |  | |  |
|  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |
|       |       |       |       |       |       |       |       |
-----------------------------------------------------------------
|       |       |       |       |       |       |       |       |
|  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |
|  | |  |  | |  |  | |  |  | |  |  | |  |  | |  |  | |  |  | |  |
|  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |
|       |       |       |       |       |       |       |       |
-----------------------------------------------------------------
|       |       |       |       |       |       |       |       |
|  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |
|  | |  |  | |  |  | |  |  | |  |  | |  |  | |  |  | |  |  | |  |
|  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |  ---  |
|       |       |       |       |       |       |       |       |
-----------------------------------------------------------------


答:
Perl 6, 11 bytes

*.comb.pick
```

<pre class="lang-perl6 prettyprint-override"><code>*.comb.roll
</code>```

Explanation:

* starts the Whatever lambda

.comb splits the string into a list of grapheme clusters

.roll/.pick grabs a single element from the list at random

( so it is effectively a weighted roll )

( There isn't a difference between .pick and .roll unless you give them an argument that is something other than 1 )

Usage:

say ( *.comb.pick )( 'xxX' ); # ⅔ chance of ｢x｣, ⅓ chance of ｢X｣

my &code = *.comb.pick;

say code 'xyz'; # ⅓ chance of each of ｢x｣ ｢y｣ or ｢z｣

say ('}^€:','0123456789').map: *.comb.pick;
```

Title: Random character from a string

Body:
Perl 6, 11 bytes

*.comb.pick

*.comb.roll

Explanation:

* starts the Whatever lambda

.comb splits the string into a list of grapheme clusters

.roll/.pick grabs a single element from the list at random

( so it is effectively a weighted roll )

( There isn't a difference between .pick and .roll unless you give them an argument that is something other than 1 )

Usage:

say ( *.comb.pick )( 'xxX' ); # ⅔ chance of ｢x｣, ⅓ chance of ｢X｣

my &code = *.comb.pick;

say code 'xyz'; # ⅓ chance of each of ｢x｣ ｢y｣ or ｢z｣

say ('}^€:','0123456789').map: *.comb.pick;


答:
Jelly, 6 bytes

```<code>+Ð¡1ḊP
</code>```

Input 100 finishes in 500 ms locally. Try it online!

How it works

```<code>+Ð¡1ḊP  Niladic link. No input.
        Since the link doesn't start with a nilad, the argument 0 is used.

   1    Yield 1.
+       Add the left and right argument.
 Ð¡     Read a number n from STDIN.
        Repeatedly call the dyadic link +, updating the right argument with
        the value of the left one, and the left one with the return value.
        Collect all values of the left argument into an array.
    Ḋ   Dequeue; discard the first Fibonacci number (0).
     P  Product; multiply the remaining ones.
</code>```

Title: Fibonacci-orial

Body:
Definition

Fibonacci sequence F(n), on the positive integers, are defined as such:

```<code>1. F(1) = 1
2. F(2) = 1
3. F(n) = F(n-1) + F(n-2), where n is an integer and n > 2
</code>```

The Fibonacci-orial of a positive integer is the product of [F(1), F(2), ..., F(n)].

Task

Given positive integer n, find the Fibonacci-orial of n.

Specs

The fibonacci-orial of 100 must compute in under 5 seconds on a reasonable computer.

Testcases

```<code>n   Fibonacci-orial of n
1   1
2   1
3   2
4   6
5   30
6   240
7   3120
8   65520
9   2227680
10  122522400
11  10904493600
12  1570247078400
13  365867569267200
14  137932073613734400
15  84138564904377984000
16  83044763560621070208000
17  132622487406311849122176000
18  342696507457909818131702784000
19  1432814097681520949608649339904000
20  9692987370815489224102512784450560000
100 3371601853146468125386964065447576689828006172937411310662486977801540671138589868616500834190029067583665182291701553172011082574587431382310099030394306877775647395167143332483560925112960024644459715300507481235056111434293619038347456390454209587101225261757371666449068625033999573552165524529725467628060170886602001077137613803027158648329335507728698605769992818756765633305318529965186184043999696650407246193257877568825245646129366994079739720698147440310773871269639752334356493678913424390564535389212240038895626811627949132978086070255082668392290037141141291484839596694182152062726390364094447642643912371532491388089634845995941928089653751672688740718152064107169357399466473375804972260594768969952507346694189050233823596316467570584434128052398891223730335019092974935617029638919358286124350711360361279157416837428904150054292406756317837582840596331363581207781793070936765786629772999832857257349696094416616259974304208756997835360702840912518532683324936435856348020736000000000000000000000000
</code>```

References

Obligatory OEIS A003266

OEIS A000045 - Fibonacci sequence

Body:
Jelly, 6 bytes

+Ð¡1ḊP

Input 100 finishes in 500 ms locally. Try it online!

How it works

+Ð¡1ḊP  Niladic link. No input.
        Since the link doesn't start with a nilad, the argument 0 is used.

   1    Yield 1.
+       Add the left and right argument.
 Ð¡     Read a number n from STDIN.
        Repeatedly call the dyadic link +, updating the right argument with
        the value of the left one, and the left one with the return value.
        Collect all values of the left argument into an array.
    Ḋ   Dequeue; discard the first Fibonacci number (0).
     P  Product; multiply the remaining ones.


问:
Algebraic curve plotter
An algebraic curve is a certain "1D subset" of the "2D-plane" that can be described as set of zeros {(x,y) in R^2 : f(x,y)=0 }of a polynomial f. Here we consider the 2D-plane as the real plane R^2 such that we can easily imagine what such a curve could look like, basically a thing you can draw with a pencil.

Examples:

0 = x^2 + y^2 -1  a circle of radius 1

0 = x^2 + 2y^2 -1  an ellipse

0 = xy  a cross shape, basically the union of the x-axis and the y-axis

0 = y^2 - x  a parabola

0 = y^2 - (x^3 - x + 1) an elliptic curve

0 = x^3 + y^3 - 3xy the folium of Descartes

0 = x^4 - (x^2 - y^2) a lemniscate

0 = (x^2 + y^2)^2 - (x^3 - 3xy^2) a trifolium

0 = (x^2 + y^2 - 1)^3 + 27x^2y^2 an astroid

Task

Given a polynomial f (as defined below), and the x/y-ranges, output an black and white image of at least 100x100 pixels that shows the curve as black line on a white background.

Details

Color: You can use any two other colours of your choice, it should just be easy to tell them apart.

Plot: Instead of a pixel image you can also output this image as ascii-art, where the background "pixels" should be space/underline or an other character that "looks empty" and the line can be made of a character that looks "full" like M or X or #.

You do not have to worry about aliasing.

You only need to plot lines where the sign of the polynomial changes from one side of the line to the other (that means you could e.g. use the marching square algorithm), you do not have to correctly plot "pathological cases like 0 = x^2 where the sign does not change when going from one side of the line to the other. But the line should be continuous and separating the regions of the different signs of f(x,y).

Polynomial: The polynomial is given as a (m+1) x (n+1) matrix/list of lists of (real) coefficients, in the example below the terms of the coefficients are given in their position:

```<code>[   1 * 1,   1 * x,   1 * x^2,   1 * x^3,  ... , 1 * x^n ]
[   y * 1,   y * x,   y * x^2,   y * x^4,  ... , y * x^n ]
[   ...  ,   ...   ,   ...   ,    ...   ,  ... ,   ...   ]
[ y^m * 1, y^m * x, y^m * x^2, y^m * x^3 , ..., y^m * x^n]
</code>```

If you prefer, you can assume the matrix to be square (which can always be done with the necessary zero-padding), and if you want, you can also assume that the size of the matrix is given as aditional inputs.

In the following, the examples from above are represented as a matrix defined like this:

```<code>Circle:       Ellipse:      Parabola:  Cross:    Elliptic Curve: e.t.c
[-1, 0, 1]    [-1, 0, 1]    [ 0,-1]    [ 0, 0]   [-1, 1, 0,-1]
[ 0, 0, 0]    [ 0, 0, 0]    [ 0, 0]    [ 0, 1]   [ 0, 0, 0, 0]
[ 1, 0, 0]    [ 2, 0, 0]    [ 1, 0]              [ 1, 0, 0, 0]
</code>```

Test cases with x-range / y-range:

(In a not so readable but better copy-paste-able format available here on pastebin.)

```<code>Circle:
[-1, 0, 1]   [-2,2]   [-2,2]
[ 0, 0, 0]
[ 1, 0, 0]

Ellipse:
[-1, 0, 1]   [-2,2]   [-1,1]
[ 0, 0, 0]
[ 2, 0, 0]

Cross:
[ 0, 0]      [-1,2]   [-2,1]
[ 0, 1]

Parabola:
[ 0,-1]      [-1,3]   [-2,2]
[ 0, 0]
[ 1, 0]

Elliptic Curve:
[-1, 1, 0,-1]    [-2,2]   [-3,3]
[ 0, 0, 0, 0]
[ 1, 0, 0, 0]

Folium of Descartes:
[  0,  0,  0,  1]    [-3,3]   [-3,3]
[  0, -3,  0,  0]
[  0,  0,  0,  0]
[  1,  0,  0,  0]

Lemniscate:
[  0,  0, -1,  0,  1]    [-2,2]   [-1,1]
[  0,  0,  0,  0,  0]
[  1,  0,  0,  0,  0]

Trifolium:
[ 0, 0, 0,-1, 1]    [-1,1]   [-1,1]
[ 0, 0, 0, 0, 0]
[ 0, 3, 2, 0, 0]
[ 0, 0, 0, 0, 0]
[ 1, 0, 0, 0, 0]

Astroid:
[ -1,  0,  3,  0, -3,  0,  1]    [-1,1]   [-1,1]
[  0,  0,  0,  0,  0,  0,  0]
[  3,  0, 21,  0,  3,  0,  0]
[  0,  0,  0,  0,  0,  0,  0]
[ -3,  0,  3,  0,  0,  0,  0]
[  0,  0,  0,  0,  0,  0,  0]
[  1,  0,  0,  0,  0,  0,  0]
</code>```

I've got the inspiration for some curves from this pdf.

答:
Matlab, <s>114</s> <s>100</s> 92 bytes

The right tool for the job? I use the interesting way Matlab does printf to generate a polynomial as a string. This polynomial can be provided to ezplot which plots the implicit curve on the specified domain. For readability the code is presented with newlines after ; which isn't needed and isn't counted towards the size.

```<code>function P(A,W,H,h,w)
t=0:h*w-1;
ezplot(sprintf('+%d*x^%.0f*y^%d',[A(:)';t/h;rem(t,h)]),[W,H])
</code>```

Golfing progress as expandable snippet.

Iteration 1, clean arguments, 114 bytes
---------------------------------------
function P(A,W,H)
h=size(A,1);
t=0:numel(A)-1;
ezplot(sprintf('+%d*x^%d*y^%d',[A(:)';floor(t/h);rem(t,h)]),[W,H])

Iteration 1.5, historical revisionism (thanks @flawr), 111 bytes
--------------------------------------------------------------
function P(A,W,H)
[h,w]=size(A);
t=0:h*w-1;
ezplot(sprintf('+%d*x^%d*y^%d',[A(:)';floor(t/h);rem(t,h)]),[W,H])

Iteration 2, playing dirty, 100 bytes
-------------------------------------
The code can be golfed further if I use that taking matrix sizes as inputs are
fair game, but it feels sad to ruin such neat input arguments. However,
this is code golf and I'll abuse anything I can and I end up at a nice 100 bytes:

function P(A,W,H,h,w)
t=0:h*w-1;
ezplot(sprintf('+%d*x^%d*y^%d',[A(:)';floor(t/h);rem(t,h)]),[W,H]);

Iteration 2.5, fix your code (thanks @LuisMendo), 98 bytes
----------------------------------------------------------
function P(A,W,H,h,w)
t=0:h*w-1;
ezplot(sprintf('+%d*x^%d*y^%d',[A(:)';fix(t/h);rem(t,h)]),[W,H]);

Iteration 3, more power to printf, 92 bytes [current best]
----------------------------------------------------------
Use `%.0f` instead of `fix`/`floor`.

function P(A,W,H,h,w)
t=0:h*w-1;
ezplot(sprintf('+%d*x^%.0f*y^%d',[A(:)';t/h;rem(t,h)]),[W,H])```

Output of the test cases (click for full view):

Title: Algebraic curve plotter

Body:
Matlab, <s>114</s> <s>100</s> 92 bytes

The right tool for the job? I use the interesting way Matlab does printf to generate a polynomial as a string. This polynomial can be provided to ezplot which plots the implicit curve on the specified domain. For readability the code is presented with newlines after ; which isn't needed and isn't counted towards the size.

function P(A,W,H,h,w)
t=0:h*w-1;
ezplot(sprintf('+%d*x^%.0f*y^%d',[A(:)';t/h;rem(t,h)]),[W,H])

Golfing progress as expandable snippet.

Iteration 1, clean arguments, 114 bytes
---------------------------------------
function P(A,W,H)
h=size(A,1);
t=0:numel(A)-1;
ezplot(sprintf('+%d*x^%d*y^%d',[A(:)';floor(t/h);rem(t,h)]),[W,H])

Iteration 1.5, historical revisionism (thanks @flawr), 111 bytes
--------------------------------------------------------------
function P(A,W,H)
[h,w]=size(A);
t=0:h*w-1;
ezplot(sprintf('+%d*x^%d*y^%d',[A(:)';floor(t/h);rem(t,h)]),[W,H])

Iteration 2, playing dirty, 100 bytes
-------------------------------------
The code can be golfed further if I use that taking matrix sizes as inputs are
fair game, but it feels sad to ruin such neat input arguments. However,
this is code golf and I'll abuse anything I can and I end up at a nice 100 bytes:

function P(A,W,H,h,w)
t=0:h*w-1;
ezplot(sprintf('+%d*x^%d*y^%d',[A(:)';floor(t/h);rem(t,h)]),[W,H]);

Iteration 2.5, fix your code (thanks @LuisMendo), 98 bytes
----------------------------------------------------------
function P(A,W,H,h,w)
t=0:h*w-1;
ezplot(sprintf('+%d*x^%d*y^%d',[A(:)';fix(t/h);rem(t,h)]),[W,H]);

Iteration 3, more power to printf, 92 bytes [current best]
----------------------------------------------------------
Use `%.0f` instead of `fix`/`floor`.

function P(A,W,H,h,w)
t=0:h*w-1;
ezplot(sprintf('+%d*x^%.0f*y^%d',[A(:)';t/h;rem(t,h)]),[W,H])

Output of the test cases (click for full view):


Title: Fibonacci-orial

Body:
Python, 45 Bytes

a=b=o=1
exec"o*=a;a,b=b,a+b;"*input()
print o

Input is taken from stdin. Output for n = 100 finishes too quickly to accurately time. n = 1000 takes approximately 1s.

Sample Usage

$ echo 10 | python fib-orial.py
122522400

$ echo 100 | python fib-orial.py
3371601853146468125386964065447576689828006172937411310662486977801540671138589868616500834190029067583665182291701553172011082574587431382310099030394306877775647395167143332483560925112960024644459715300507481235056111434293619038347456390454209587101225261757371666449068625033999573552165524529725467628060170886602001077137613803027158648329335507728698605769992818756765633305318529965186184043999696650407246193257877568825245646129366994079739720698147440310773871269639752334356493678913424390564535389212240038895626811627949132978086070255082668392290037141141291484839596694182152062726390364094447642643912371532491388089634845995941928089653751672688740718152064107169357399466473375804972260594768969952507346694189050233823596316467570584434128052398891223730335019092974935617029638919358286124350711360361279157416837428904150054292406756317837582840596331363581207781793070936765786629772999832857257349696094416616259974304208756997835360702840912518532683324936435856348020736000000000000000000000000


答:
dc, <s>38</s> <s>40</s> <s>30</s> 28 bytes

<s>```<code>?si1d[sadlarla+zli>b]sbzli>b[*z1<*]ds*xf</code>```</s>

```<code>si1d[sadlarla+zli>b*]sbzli>b
</code>```

Expanded:

```<code>si     # Take input from top of stack and store it in register `i'
1d     # Push 1 on stack and duplicate
[      # Open macro definition
 sa    #  Store most recent term of Fibonacci sequence in register `a'
 d     #  Duplicate second most recent term
 la    #  Push most recent term onto stack
 r     #  Rotate top two items on stack
 la    #  Push most recent term onto stack (again)
       #  At this point, we've essentially duplicated the top two terms of the stack
       #    without altering the order of the terms
 +     #  Add top two terms of stack (generate next Fibonacci number)
 zli>b #  Take stack depth and load input (target number of terms); if we don't have
       #  enough terms yet, execute `b'
 *     #  Once we've generated all the terms (factors, really), we'll multiply
       #    them, one * for every time we iterated to generate a term
]sb    # Store macro in register `b'
zli>b  # Look familiar? This way, we change the "do-while" (`dsbx') to just "while"
       # Leave result on top of stack
</code>```

Title: Fibonacci-orial

Body:
dc, <s>38</s> <s>40</s> <s>30</s> 28 bytes

<s>
?si1d[sadlarla+zli>b]sbzli>b[*z1<*]ds*xf
</s>

si1d[sadlarla+zli>b*]sbzli>b

Expanded:

si     # Take input from top of stack and store it in register `i'
1d     # Push 1 on stack and duplicate
[      # Open macro definition
 sa    #  Store most recent term of Fibonacci sequence in register `a'
 d     #  Duplicate second most recent term
 la    #  Push most recent term onto stack
 r     #  Rotate top two items on stack
 la    #  Push most recent term onto stack (again)
       #  At this point, we've essentially duplicated the top two terms of the stack
       #    without altering the order of the terms
 +     #  Add top two terms of stack (generate next Fibonacci number)
 zli>b #  Take stack depth and load input (target number of terms); if we don't have
       #  enough terms yet, execute `b'
 *     #  Once we've generated all the terms (factors, really), we'll multiply
       #    them, one * for every time we iterated to generate a term
]sb    # Store macro in register `b'
zli>b  # Look familiar? This way, we change the "do-while" (`dsbx') to just "while"
       # Leave result on top of stack


问:
Partitions of a list
The answer to this question is much too long

Your challenge is to write a partitioning function in the smallest number of characters.

Input example

```<code>['a', 'b', 'c']
</code>```

Output example

```<code>[(('a'),('b'),('c')),
 (('a', 'b'), ('c')),
 (('a', 'c'), ('b')),
 (('b', 'c'), ('a')),
 (('a', 'b', 'c'))]
</code>```

The input can be a list/array/set/string etc. whatever is easiest for your function to process

You can also choose the output format to suit yourself as long as the structure is clear.

Your function should work for at least 6 items in the input

答:
GolfScript, 51 characters

```<code>{[[]]\{[.;]`{1$[1$]+@@`1$`{[2$]-@@[+]+}++/}+%}/}:P;
</code>```

The script defines a variable P which takes an array from top of the stack and pushes back a list of all partitions, e.g.

```<code>[1 2] P            # => [[[1] [2]] [[1 2]]]
["a" "b" "c"] P    # => [[["a"] ["b"] ["c"]] [["b"] ["a" "c"]] [["a"] ["b" "c"]] [["a" "b"] ["c"]] [["a" "b" "c"]]]
</code>```

It does also work on larger lists:

```<code>6, P ,p            # prints 203, i.e. Bell number B6
8, P ,p            # 4140
</code>```

You may perform own tests online.

Title: Partitions of a list

Body:
GolfScript, 51 characters

{[[]]\{[.;]`{1$[1$]+@@`1$`{[2$]-@@[+]+}++/}+%}/}:P;

The script defines a variable P which takes an array from top of the stack and pushes back a list of all partitions, e.g.

[1 2] P            # => [[[1] [2]] [[1 2]]]
["a" "b" "c"] P    # => [[["a"] ["b"] ["c"]] [["b"] ["a" "c"]] [["a"] ["b" "c"]] [["a" "b"] ["c"]] [["a" "b" "c"]]]

It does also work on larger lists:

6, P ,p            # prints 203, i.e. Bell number B6
8, P ,p            # 4140

You may perform own tests online.


答:
Pyth, 13 bytes

```<code>u*Gs=[sZhZ)Q1
</code>```

Demonstration

This employs a clever, non-typesafe trick. Five of the characters (u*G ... Q1) say that the output is the product of the input many numbers. The rest of the code generates the numbers.

=[sZhZ) updates the variable Z to the list [s(Z), h(Z)]. Then s sums that list, to be multiplied.

Z is initially 0. s, on ints, is the identity function. h, on its, is the + 1 function. So on the first iteration, Z becomes [0, 1]. s on lists is the sum function, as mentioned above. h is the head function. So the second iteration is [1, 0].

Here's a list:

```<code>Iter  Z          Sum
0     0          Not used
1     [0, 1]     1
2     [1, 0]     1
3     [1, 1]     2
4     [2, 1]     3
5     [3, 2]     5
</code>```

These sums are multiplied up to give the result.

Title: Fibonacci-orial

Body:
Pyth, 13 bytes

u*Gs=[sZhZ)Q1

Demonstration

This employs a clever, non-typesafe trick. Five of the characters (u*G ... Q1) say that the output is the product of the input many numbers. The rest of the code generates the numbers.

=[sZhZ) updates the variable Z to the list [s(Z), h(Z)]. Then s sums that list, to be multiplied.

Z is initially 0. s, on ints, is the identity function. h, on its, is the + 1 function. So on the first iteration, Z becomes [0, 1]. s on lists is the sum function, as mentioned above. h is the head function. So the second iteration is [1, 0].

Here's a list:

Iter  Z          Sum
0     0          Not used
1     [0, 1]     1
2     [1, 0]     1
3     [1, 1]     2
4     [2, 1]     3
5     [3, 2]     5

These sums are multiplied up to give the result.


答:
PARI/GP, 29 bytes

f=n->prod(i=1,n,fibonacci(i))
```

<p>Or alternatively:</p>

<pre class="lang-default prettyprint-override"><code>f=n->prod(i=a=!b=0,n,b=a+a=b)
</code>```

Title: Fibonacci-orial

Body:
PARI/GP, 29 bytes

f=n->prod(i=1,n,fibonacci(i))

Or alternatively:

f=n->prod(i=a=!b=0,n,b=a+a=b)


答:
Javascript (ES6), <s>51</s> 39 bytes

Recursive implementation (39 bytes)

```<code>f=(n,a=p=i=b=1)=>++i<n?f(n,b,p*=b+=a):p
</code>```

Original implementation (51 bytes)

```<code>n=>{for(i=a=b=p=1;++i<n;){c=a;a=b;p*=b+=c}return p}
</code>```

Note: Starts rounding errors for the Fibonacci-orial of 16, 100 is just Infinity, runs in what appears to be <1 second.

Title: Fibonacci-orial

Body:
Javascript (ES6), <s>51</s> 39 bytes

Recursive implementation (39 bytes)

f=(n,a=p=i=b=1)=>++i<n?f(n,b,p*=b+=a):p

Original implementation (51 bytes)

n=>{for(i=a=b=p=1;++i<n;){c=a;a=b;p*=b+=c}return p}

Note: Starts rounding errors for the Fibonacci-orial of 16, 100 is just Infinity, runs in what appears to be <1 second.


Title: Hofstadter Q-sequence

Body:
Definition

a(1) = 1

a(2) = 1

a(n) = a(n-a(n-1)) + a(n-a(n-2)) for n > 2 where n is an integer

Task

Given positive integer n, generate a(n).

Testcases

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

Reference

Obligatory OEIS A005185

Body:
Erlang, 46 bytes

f(N)when N<3->1;f(N)->f(N-f(N-1))+f(N-f(N-2)).


Title: Fibonacci-orial

Body:
Mathematica <s>25</s> 24 bytes

With thanks to Martin Ender.

1##&@@Fibonacci@Range@#&

1##&@@Fibonacci@Range@#&@100

Timing: 63 microseconds.

{0.000063,
3371601853146468125386964065447576689828006172937411310662486977801540
6711385898686165008341900290675836651822917015531720110825745874313823
1009903039430687777564739516714333248356092511296002464445971530050748
1235056111434293619038347456390454209587101225261757371666449068625033
9995735521655245297254676280601708866020010771376138030271586483293355
0772869860576999281875676563330531852996518618404399969665040724619325
7877568825245646129366994079739720698147440310773871269639752334356493
6789134243905645353892122400388956268116279491329780860702550826683922
9003714114129148483959669418215206272639036409444764264391237153249138
8089634845995941928089653751672688740718152064107169357399466473375804
9722605947689699525073466941890502338235963164675705844341280523988912
2373033501909297493561702963891935828612435071136036127915741683742890
4150054292406756317837582840596331363581207781793070936765786629772999
8328572573496960944166162599743042087569978353607028409125185326833249
36435856348020736000000000000000000000000}


Title: Fibonacci-orial

Body:
Brain-Flak, <s>110</s> <s>104</s> 100 bytes

Try it online!

({}<((())<>)>){({}[()]<<>(({})<>({}<>)<>)>)}<>{}([[]]()){({}()<({}<>)<>({<({}[()])><>({})<>}{})>)}{}

Explanation

First we run an improved version of the Fibonacci sequence generator curtesy of Dr Green Eggs and Iron Man

({}<((())<>)>){({}[()]<<>(({})<>({}<>)<>)>)}<>{}

Then while the stack has more than one item on it

([[]]()){({}()<...>)}

multiply the top two items

({}<>)<>({<({}[()])><>({})<>}{})

and pop the extra zero

{}