答:
Clojure, 59 bytes

```<code>(fn[n](nth(iterate #(mapcat(fn[x](range 1(inc x)))%)[n])n))
</code>```

Explanation:

Really straight forward way to solve the problem. Working from the inside out:

```<code>(1) (fn[x](range 1(inc x))) ;; return a list from 1 to x
(2) #(mapcat (1) %)         ;; map (1) over each item in list and flatten result
(3) (iterate (2) [n])       ;; call (2) repeatedly e.g. (f (f (f [n])))
(4) (nth (3) n))            ;; return the nth value of the iteration
</code>```

Title: Count Up, Replace, Repeat!

Body:
Clojure, 59 bytes

(fn[n](nth(iterate #(mapcat(fn[x](range 1(inc x)))%)[n])n))

Explanation:

Really straight forward way to solve the problem. Working from the inside out:

(1) (fn[x](range 1(inc x))) ;; return a list from 1 to x
(2) #(mapcat (1) %)         ;; map (1) over each item in list and flatten result
(3) (iterate (2) [n])       ;; call (2) repeatedly e.g. (f (f (f [n])))
(4) (nth (3) n))            ;; return the nth value of the iteration


答:
Swift 3, 58 Bytes

Meant to run directly in the a playground, with n set to the input:

```<code>var x=[n];for i in 0..<n{x=x.reduce([]){$0+[Int](1...$1)}}
</code>```

Ungolfed, with most short hand notation reverted:

```<code>let n = 3 //input

var x: Array<Int> = [n]
for i in 0..<n {
    x = x.reduce(Array<Int>[], combine: { accumulator, element in
        accumulator + Array<Int>(1...element)
    })
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Count Up, Replace, Repeat!

Body:
Definition

Define the nth array of the CURR sequence as follows.

Begin with the singleton array A = [n].

For each integer k in A, replace the entry k with k natural numbers, counting up from 1 to k.

Repeat the previous step n - 1 more times.

For example, if n = 3, we start with the array [3].

We replace 3 with 1, 2, 3, yielding [1, 2, 3].

We now replace 1, 2, and 3 with 1; 1, 2 and 1, 2, 3 (resp.), yielding [1, 1, 2, 1, 2, 3].

Finally, we perform the same replacements as in the previous step for all six integers in the array, yielding [1, 1, 1, 2, 1, 1, 2, 1, 2, 3]. This is the third CURR array.

Task

Write a program of a function that, given a strictly positive integer n as input, computes the nth CURR array.

The output has to be a flat list of some kind (and array returned from a function, a string representation of your language's array syntax, whitespace-separated, etc.).

This is code-golf. May the shortest code in bytes win!

Test cases

```<code> 1 -> [1]
 2 -> [1, 1, 2]
 3 -> [1, 1, 1, 2, 1, 1, 2, 1, 2, 3]
 4 -> [1, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4]
 5 -> [1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 2, 3, 4, 5]
 6 -> [1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 2, 3, 4, 5, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 2, 3, 4, 5, 1, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 2, 3, 4, 5, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 2, 3, 4, 5, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 6]
</code>```

Body:
Swift 3, 58 Bytes

Meant to run directly in the a playground, with n set to the input:

var x=[n];for i in 0..<n{x=x.reduce([]){$0+[Int](1...$1)}}

Ungolfed, with most short hand notation reverted:

let n = 3 //input

var x: Array<Int> = [n]
for i in 0..<n {
    x = x.reduce(Array<Int>[], combine: { accumulator, element in
        accumulator + Array<Int>(1...element)
    })
}


问:
Create a GUI Piano

Challenge

Create a GUI Keyboard with as few characters as possible.

Example

Because this was an assignment in one of my courses, I can't show the source code.  However, here is a screen shot of my keyboard.

In this example, my keys were of type JButton and I used a Midi Synthesizer to produce the sound (with the default ADSR envelope values).

Rules

You are allowed to use standard external libraries.

Be creative with your sound.  You can use 8-bit, a sitar, etc.

For simplicities sake, you may have five keys; black and white, from C to E (the first five keys on my keyboard).

Most importantly... showcase your work!

NOTICE: Depending on what language you choose to work with, this may be a rather large task.

This is my first question on SE Code Golf.  If anything is unclear, please ask for further details.

EDIT: The due date for this challenge will be 9/22/12.  If you post an answer after this date, I will look over it regardless (and possibly +1 it).

答:
Groovy: 577 (703 with whitespaces)

The first 5 notes. Others could be added easily, it's somewhat dynamic.

Damn swing. Probably with a swing lib it would be better.

Plays through JFugue.

On github: https://github.com/wpiasecki/glissando/blob/master/src/br/glissando/Piano.groovy

On groovy 2.0.2

```<code>import java.awt.event.*
class Note { def n; boolean s; def p() { new org.jfugue.Player().with {play n;close()}} }
notes=['C','C#','D','D#','E'].inject([]){ l,n -> l<< Note[n:n,s:n=~/#/]}
h=300
l=0
w=60
x=0
new groovy.swing.SwingBuilder().edt {
  frame size:[notes.size()*30+30,h],
    show:true,
    defaultCloseOperation:javax.swing.JFrame.EXIT_ON_CLOSE,
    { l = layeredPane() }
  notes.each { n ->
    C=java.awt.Color
    s=n.s
    p=panel bounds:(s ? [x-15,0,w-30,h-100] : [x,0,w,h]),
      background: s ? C.BLACK : C.WHITE,
      border: lineBorder(1, color: C.BLACK)
    p.addMouseListener({ if(it.id==MouseEvent.MOUSE_CLICKED)n.p() }as MouseListener)
    if(!s)x+=w
    l.add p,s?0:1
  }
}
</code>```

Title: Create a GUI Piano

Body:
Groovy: 577 (703 with whitespaces)

The first 5 notes. Others could be added easily, it's somewhat dynamic.

Damn swing. Probably with a swing lib it would be better.

Plays through JFugue.

On github: https://github.com/wpiasecki/glissando/blob/master/src/br/glissando/Piano.groovy

On groovy 2.0.2

import java.awt.event.*
class Note { def n; boolean s; def p() { new org.jfugue.Player().with {play n;close()}} }
notes=['C','C#','D','D#','E'].inject([]){ l,n -> l<< Note[n:n,s:n=~/#/]}
h=300
l=0
w=60
x=0
new groovy.swing.SwingBuilder().edt {
  frame size:[notes.size()*30+30,h],
    show:true,
    defaultCloseOperation:javax.swing.JFrame.EXIT_ON_CLOSE,
    { l = layeredPane() }
  notes.each { n ->
    C=java.awt.Color
    s=n.s
    p=panel bounds:(s ? [x-15,0,w-30,h-100] : [x,0,w,h]),
      background: s ? C.BLACK : C.WHITE,
      border: lineBorder(1, color: C.BLACK)
    p.addMouseListener({ if(it.id==MouseEvent.MOUSE_CLICKED)n.p() }as MouseListener)
    if(!s)x+=w
    l.add p,s?0:1
  }
}


答:
APL, 11 bytes

```<code>{∊⍳¨∘∊⍣⍵+⍵}
</code>```

Test:

```<code>      {∊⍳¨∘∊⍣⍵+⍵} 3
1 1 1 2 1 1 2 1 2 3
</code>```

Explanation:

+⍵: starting with ⍵,

⍣⍵: do the following ⍵ times:

⍳¨∘∊: flatten the input, and then generate a list [1..N] for each N in the input

∊: flatten the result of that

Title: Count Up, Replace, Repeat!

Body:
APL, 11 bytes

{∊⍳¨∘∊⍣⍵+⍵}

Test:

      {∊⍳¨∘∊⍣⍵+⍵} 3
1 1 1 2 1 1 2 1 2 3

Explanation:

+⍵: starting with ⍵,

⍣⍵: do the following ⍵ times:

⍳¨∘∊: flatten the input, and then generate a list [1..N] for each N in the input

∊: flatten the result of that


Title: Count Up, Replace, Repeat!

Body:
Java, 159 Bytes

Procedure

int[] q(int y){int z[]=new int[]{y};for(int i=0;i<y;i++){int d=0,a=0;for(int c:z)d+=c;int[]r=new int[d];for(int c:z)for(int j=0;j<c;)r[a++]=++j;z=r;}return z;}

Usage

public static void main(String[] args){String out = "["; int [] b = q(6);for(int c:b)out+=c+", ";System.out.println(out+"]");}

public static int[] q(int y){int z[]=new int[]{y};for(int i=0;i<y;i++){int d=0,a=0;for(int c:z)d+=c;int[]r=new int[d];for(int c:z)for(int j=0;j<c;)r[a++]=++j;z=r;}return z;}

Sample output:

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


问:
Same length sub arrays

Background:

Here's a little simple challenge. You want to be able to find out whether the arrays inside an array have the same length.

Input:

Your input should consist of exactly one array (this is the value passed to the function, not a user input). Your function takes exactly 1 parameter.  It could contain arrays or be empty. No error checking needed, assume only list is ever passed in. Assume a 1-D array such as [1] or [1,2,3,4,5] is never passed in.

Output:

Return true if all the list elements have the same length, false if they don't, and the parameter itself if the list is empty (or null if your language doesn't support multiple return types).

Some test cases:

```<code>List: [] - [] (or null/your language equivalent)
List: [[1], [1], [2]] - True
List: [[1]] - True
List: [[1, 2, 3, 4]] - True
List: [[1, 2, 3, 4, 5], [2], [12, 314123]] - False
List: [[1, 2, 3, 4], [1]] - False
</code>```

No std(in/out) input/output needed (however, it is allowed, just not required!), the function only needs to return boolean values true or false; or the parameter itself if the function is passed an empty list (or null/your language equivalent). Only one return value is returned.

Rules:

Shortest byte count wins, only function is necessary (full programs are allowed if you desire).

答:
APL, 13 bytes

```<code>{(×⍴⍵)↑⍵≡↓↑⍵}
</code>```

Explanation:

↓↑⍵: turn the list of arrays into a matrix, and then turn the matrix back into a list of arrays. Because a matrix has to be rectangular, short arrays will be padded with zeroes to match the longest.

⍵≡: see if the result is equal to the input. This is only the case if no zeroes have been added, which means all the sublists were the same length.

×⍴⍵: take the sign of the length of ⍵, which is 0 if ⍵ is empty and 1 if not.

↑: take the first 0 or 1 items from the result depending on whether the array was empty or not.

Title: Same length sub arrays

Body:
APL, 13 bytes

{(×⍴⍵)↑⍵≡↓↑⍵}

Explanation:

↓↑⍵: turn the list of arrays into a matrix, and then turn the matrix back into a list of arrays. Because a matrix has to be rectangular, short arrays will be padded with zeroes to match the longest.

⍵≡: see if the result is equal to the input. This is only the case if no zeroes have been added, which means all the sublists were the same length.

×⍴⍵: take the sign of the length of ⍵, which is 0 if ⍵ is empty and 1 if not.

↑: take the first 0 or 1 items from the result depending on whether the array was empty or not.


答:
Retina, 35 bytes

If only [] could return true or false. Returning a 3rd value makes it so much longer.

```<code>\[]
xx
\d|],

M`^\[(\[,*)\1*]]|x
2

</code>```

Try it online

This is the core program. It removes digits and occurrences of ],, then matches if the number of commas is the same after each [. It would return 0 for []. The code above varies because I added a check for an empty list to make it match twice, then I replace 2 with nothing for a null return.

```<code>\d|],

^\[(\[,*)\1*]]
</code>```

Title: Same length sub arrays

Body:
Background:

Here's a little simple challenge. You want to be able to find out whether the arrays inside an array have the same length.

Input:

Your input should consist of exactly one array (this is the value passed to the function, not a user input). Your function takes exactly 1 parameter.  It could contain arrays or be empty. No error checking needed, assume only list is ever passed in. Assume a 1-D array such as [1] or [1,2,3,4,5] is never passed in.

Output:

Return true if all the list elements have the same length, false if they don't, and the parameter itself if the list is empty (or null if your language doesn't support multiple return types).

Some test cases:

```<code>List: [] - [] (or null/your language equivalent)
List: [[1], [1], [2]] - True
List: [[1]] - True
List: [[1, 2, 3, 4]] - True
List: [[1, 2, 3, 4, 5], [2], [12, 314123]] - False
List: [[1, 2, 3, 4], [1]] - False
</code>```

No std(in/out) input/output needed (however, it is allowed, just not required!), the function only needs to return boolean values true or false; or the parameter itself if the function is passed an empty list (or null/your language equivalent). Only one return value is returned.

Rules:

Shortest byte count wins, only function is necessary (full programs are allowed if you desire).

Body:
Retina, 35 bytes

If only [] could return true or false. Returning a 3rd value makes it so much longer.

\[]
xx
\d|],

M`^\[(\[,*)\1*]]|x
2

Try it online

This is the core program. It removes digits and occurrences of ],, then matches if the number of commas is the same after each [. It would return 0 for []. The code above varies because I added a check for an empty list to make it match twice, then I replace 2 with nothing for a null return.

\d|],

^\[(\[,*)\1*]]


问:
Wait a minute – in less than ten seconds

Task

Using any type of parallelisation, wait multiple periods, for a total sleep time of at least a minute (but less than a minute and a half).

The program/function must terminate within 10 seconds and return (by any means and in any format) two values: the total elapsed time, and the total executed sleep time. Both time values have to have a precision of at least 0.1 seconds.

This is similar to the concept of man-hours: a job that takes 60 hours can be completed in only 6 hours if 10 workers are splitting the job. Here we can have 60 seconds of sleep time e.g. in 10 parallel threads, thus requiring only 6 seconds for the whole job to be completed.

Example

The program MyProgram creates 14 threads, each thread sleeps for 5 seconds:

MyProgram → [5.016,70.105]

The execution time is greater than 5 seconds, and the total sleep time is greater than 70 seconds because of overhead.

答:
Common Lisp (SBCL) 166 bytes:

```<code>(do((m #1=(get-internal-real-time))(o(list 0)))((>(car o)60000)`(,(car o),(- #1#m)))(sb-thread:make-thread(lambda(&aux(s #1#))(sleep 1)(atomic-incf(car o)(- #1#s)))))
</code>```

This just spawns threads that sleep and then atomically increment the time took, with an outer-loop that spins waiting for the total time to be more than 60000 ticks (i.e. 60s on sbcl).  The counter is stored in a list due to limitations to the types of places atomic-incf can modify.  This may run out of space before terminating on faster machines.

Ungolfed:

```<code>(do ((outer-start (get-internal-real-time))
       (total-inner (list 0)))
      ((> (car total-inner) 60000)
       `(,(car total-inner)
      ,(- (get-internal-real-time) outer-start)))
    (sb-thread:make-thread
     (lambda (&aux(start (get-internal-real-time)))
       (sleep 1)
       (atomic-incf (car total-inner) (- (get-internal-real-time) start)))))
</code>```

Body:
Common Lisp (SBCL) 166 bytes:

(do((m #1=(get-internal-real-time))(o(list 0)))((>(car o)60000)`(,(car o),(- #1#m)))(sb-thread:make-thread(lambda(&aux(s #1#))(sleep 1)(atomic-incf(car o)(- #1#s)))))

This just spawns threads that sleep and then atomically increment the time took, with an outer-loop that spins waiting for the total time to be more than 60000 ticks (i.e. 60s on sbcl).  The counter is stored in a list due to limitations to the types of places atomic-incf can modify.  This may run out of space before terminating on faster machines.

Ungolfed:

(do ((outer-start (get-internal-real-time))
       (total-inner (list 0)))
      ((> (car total-inner) 60000)
       `(,(car total-inner)
      ,(- (get-internal-real-time) outer-start)))
    (sb-thread:make-thread
     (lambda (&aux(start (get-internal-real-time)))
       (sleep 1)
       (atomic-incf (car total-inner) (- (get-internal-real-time) start)))))


答:
Bash + GNU utilities, 49

1 byte saved thanks to @Dennis.

Piped recursive functions FTW!

f()((($1))&&xargs -l seq|f $[$1-1]||dd)
f $1<<<$1
```

n is passed on the command-line.  Output is newline-separated.

The use of dd causes statistics to be sent to STDERR.  I think this is OK, but if not, dd can be replaced with cat at a cost of 1 extra byte.

Title: Count Up, Replace, Repeat!

Body:
Bash + GNU utilities, 49

1 byte saved thanks to @Dennis.

Piped recursive functions FTW!

f()((($1))&&xargs -l seq|f $[$1-1]||dd)
f $1<<<$1

n is passed on the command-line.  Output is newline-separated.

The use of dd causes statistics to be sent to STDERR.  I think this is OK, but if not, dd can be replaced with cat at a cost of 1 extra byte.


问:
How many squares are guarded by chess queens?
Today marks the 15th anniversary of Garry Kasparov's defeat against Deep Blue. Speaking of chess...

Input is a string that represents an 8x8 chess board containing only empty squares (.) and queens (Q). Output the number of squares that any queen can move to the next move. Queens can move any number of squares vertically, horizontally or diagonally.

Write either a program or a function. Shortest code wins, but most inventive solution gets the most upvotes.

Examples

Input:

```<code>Q.......
........
.Q......
........
........
........
........
........
</code>```

Output:

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

Input:

```<code>QQQQQQQQ
QQQQQQQQ
QQQQQQQQ
QQQQ.QQQ
QQQQQQQQ
QQQQQQQQ
QQQQQQQQ
QQQQQQQQ
</code>```

Output:

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

答:
Python - 125 chars

```<code>import os
s=os.read(0,99)
print sum(any('*'<s[i]!='Q'in s[i::j].split()[0]for j in(-10,-9,-8,-1,1,8,9,10))for i in range(71))
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Python - 125 chars

import os
s=os.read(0,99)
print sum(any('*'<s[i]!='Q'in s[i::j].split()[0]for j in(-10,-9,-8,-1,1,8,9,10))for i in range(71))


问:
When does (x == x+2)?
The challenge: Define x in such a way that the expression (x == x+2) would evaluate to true.

I tagged the question with C, but answers in other languages are welcome, as long as they're creative or highlight an interesting aspect of the language.

I intend to accept a C solution, but other languages can get my vote.

Correct - works on standard-compliant implementations. Exception - assuming an implementation of the basic types, if it's a common implementation (e.g. assuming int is 32bit 2's complement) is OK.

Simple - should be small, use basic language features.

Interesting - it's subjective, I admit. I have some examples for what I consider interesting, but I don't want to give hints. Update: Avoiding the preprocessor is interesting.

Quick - The first good answer will be accepted.

After getting 60 answers (I never expected such prticipation), It may be good to summarize them.

The 60 answers divide into 7 groups, 3 of which can be implemented in C, the rest in other languages:

The C preprocessor. #define x 2|0 was suggested, but there are many other possibilities.

Floating point. Large numbers, infinity or NaN all work.

Pointer arithmetic. A pointer to a huge struct causes adding 2 to wrap around.

The rest don't work with C:

Operator overloading - A + that doesn't add or a == that always returns true.

Making x a function call (some languages allow it without the x() syntax). Then it can return something else each time.

A one-bit data type. Then x == x+2 (mod 2).

Changing 2 - some language let you assign 0 to it.

答:
Groovy

```<code>Integer.metaClass.plus = { Integer y -> delegate }
def x = 0
assert x == x+2
</code>```

The plus method is overridden to return the first number :-D

Title: When does (x == x+2)?

Body:
Groovy

Integer.metaClass.plus = { Integer y -> delegate }
def x = 0
assert x == x+2

The plus method is overridden to return the first number :-D


问:
Tips for golfing in Java

Are there any useful shortcuts that can be used in Java?

As shown below, import already adds at least 17 characters to a program.

import java.io.*;
```

I understand that the simple solution would be to use another language, but it seems to be a real challenge to shorten Java programs.

Tips should be specific to Java: if they're applicable to most C-like languages, they belong in the more general list of tips.

答:
Avoid StringBuilders

Appending stuff to a String takes up much fewer bytes.

```<code>// s is a StringBuilder
s.append("Hello, World!");

// S is a String
S+="Hello, World!";
</code>```

If you have to reverse a string and print it right away, use a StringBuffer.

```<code>System.out.print(new StringBuilder("Hello, World!").reverse());
System.out.print(new StringBuffer("Hello, World!").reverse()); // Note that you can omit toString() when printing a non-String object
</code>```

If you have to reverse a string and then do something else than printing it, use a foreach loop.

```<code>String b=new StringBuffer("Hello, World!").reverse().toString();
String B="";for(String c:"Hello, World!".split(""))B=c+B;
</code>```

Title: Tips for golfing in Java

Body:
Avoid StringBuilders

Appending stuff to a String takes up much fewer bytes.

// s is a StringBuilder
s.append("Hello, World!");

// S is a String
S+="Hello, World!";

If you have to reverse a string and print it right away, use a StringBuffer.

System.out.print(new StringBuilder("Hello, World!").reverse());
System.out.print(new StringBuffer("Hello, World!").reverse()); // Note that you can omit toString() when printing a non-String object

If you have to reverse a string and then do something else than printing it, use a foreach loop.

String b=new StringBuffer("Hello, World!").reverse().toString();
String B="";for(String c:"Hello, World!".split(""))B=c+B;


问:
Write a program to elasticize strings
Nice verb there, in the title.

Write a program that given an input string, will "elasticize" this string and output the result. Elasticizing a string is done as follows:

The first character is shown once.
The second character is shown twice.
The third character is shown thrice,
and so on.

As you can see, the amount of duplications of a certain character is related to the character's index as opposed to its previous occurrences in the string.

You can expect to receive only printable ASCII characters. Based off the following link, these characters have decimal values 32-126.

Examples:

Why: Whhyyy

SKype: SKKyyyppppeeeee

LobbY: LoobbbbbbbYYYYY (Note how there are 7 b's since the first b is shown 3 times and the second b is shown 4 times, making a total of 7 b's).

A and B: A  aaannnnddddd      BBBBBBB

Shortest bytes wins :)

答:
C, 84 bytes

```<code>main(c,v,i,j)char**v;{for(i=0;i<strlen(v[1]);++i)for(j=0;j<=i;++j)putchar(v[1][i]);}
</code>```

This should compile on gcc with no flags. Input is taken through the first command-line argument. E.g.

```<code>$ ./elasticize Why
Whhyyy
$ ./elasticize SKype
SKKyyyppppeeeee
$ ./elasticize LobbY
LoobbbbbbbYYYYY
$ ./elasticize A and B
A  aaannnnddddd      BBBBBBB
</code>```

Ungolfed:

```<code>int main(int argc, char** argv) {
    int i, j;
    for(i = 0; i < strlen(argv[1]); ++i) {
        for(j = 0; j <= i; ++j) {
            putchar(v[1][i]);
        }
    }
}
</code>```

Title: Write a program to elasticize strings

Body:
C, 84 bytes

main(c,v,i,j)char**v;{for(i=0;i<strlen(v[1]);++i)for(j=0;j<=i;++j)putchar(v[1][i]);}

This should compile on gcc with no flags. Input is taken through the first command-line argument. E.g.

$ ./elasticize Why
Whhyyy
$ ./elasticize SKype
SKKyyyppppeeeee
$ ./elasticize LobbY
LoobbbbbbbYYYYY
$ ./elasticize A and B
A  aaannnnddddd      BBBBBBB

Ungolfed:

int main(int argc, char** argv) {
    int i, j;
    for(i = 0; i < strlen(argv[1]); ++i) {
        for(j = 0; j <= i; ++j) {
            putchar(v[1][i]);
        }
    }
}


问:
Tell Me about yourself
Your task is to write a self referential program similar to a quine. The objective is to write a program that will generally print to stdout twice whatever the input is. But when it receives the input of "Tell me about your source" it should output its source (like a quine). Also if it receives the query "tell me about your length". It should output its length in utf-8 characters. Like always all standard loopholes are disabled. This is code golf in any language of your choosing.

Sample Input

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

Sample Output

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

Sample Input

```<code>Tell me about your source
</code>```

Sample Output

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

Sample Input

```<code>Tell me about your length
</code>```

Sample Output

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

Clarifications:
The input will always be valid your program is always going to receive valid input. Your code is not required to recognize invalid input.

答:
Javascript - <s>93</s> <s>92</s> 89 bytes

Defines a function f. Not sure of a better way to return.

```<code>f=n=>{y="Tell me about your ";x="f="+f;return n==y+"source"?x:n==y+"length"?x.length:2*n}
</code>```

Title: Tell Me about yourself

Body:
Javascript - <s>93</s> <s>92</s> 89 bytes

Defines a function f. Not sure of a better way to return.

f=n=>{y="Tell me about your ";x="f="+f;return n==y+"source"?x:n==y+"length"?x.length:2*n}


问:
Ways to get to the number
Given the input of the first number and the second number (both positive integers, zero exluded), determine in how many ways could you make the second out of the first, using following actions: +1,+2 and *3. Operations are simply applied from left to right.

Examples:

Input: 1 2. Output: 1. I.e, you could only get 2 by doing +1, so one way.

Input: 1 3. Output: 3. I.e, you could get 3 by either doing +2 or +1+1, or *3

Input: 1 4. Output: 4.

Input: 2 6. Output: 6.

Input: 2 7. Output: 9.

Input: 1 10. Output: 84.

In case there're no ways, e.g. 100 100, or 100 80, output is 0.

You could also take input as an array, or string with any convenient separator.

The shortest solution wins.

答:
Pyth - <s>26</s> 24 bytes

There seems to be a bug in Pyth that's making it take inputs in the wrong order, but it shouldn't matter anyway.

```<code>/m.vj;+sdzs^Lc3"+1+2*3"S
</code>```

Test Suite.

(1 10 timed out online, but worked on my computer).

Title: Ways to get to the number

Body:
Pyth - <s>26</s> 24 bytes

There seems to be a bug in Pyth that's making it take inputs in the wrong order, but it shouldn't matter anyway.

/m.vj;+sdzs^Lc3"+1+2*3"S

Test Suite.

(1 10 timed out online, but worked on my computer).


Title: Ways to get to the number

Body:
Given the input of the first number and the second number (both positive integers, zero exluded), determine in how many ways could you make the second out of the first, using following actions: +1,+2 and *3. Operations are simply applied from left to right.

Examples:

Input: 1 2. Output: 1. I.e, you could only get 2 by doing +1, so one way.

Input: 1 3. Output: 3. I.e, you could get 3 by either doing +2 or +1+1, or *3

Input: 1 4. Output: 4.

Input: 2 6. Output: 6.

Input: 2 7. Output: 9.

Input: 1 10. Output: 84.

In case there're no ways, e.g. 100 100, or 100 80, output is 0.

You could also take input as an array, or string with any convenient separator.

The shortest solution wins.

Body:
Javascript ES6, <s>45</s> 44 bytes

f=(a,b=B)=>a<(B=b)?f(a+1)+f(a+2)+f(a*3):a==b

Example runs:

f(1,2)  -> 1
f(2,6)  -> 6
f(1 10) -> 84


问:
Unicode character classification
Real-world programs often use libraries like ICU to support Unicode.

The puzzle is to create the smallest possible function that can determine whether a given Unicode character is lowercase, uppercase, or neither (a commonly used Unicode character property).

You may indicate the property in any way (whatever is shortest for your language); just explain what the output means in your answer.

Of course, using a language feature or a function from the standard library that already provides this distinction is forbidden.

This could potentially have some practical use, since some embedded programs have to choose between including a bulky library and not supporting Unicode.

答:
C & C++, 1922 1216 bytes/chars (BMP only 1451 1005 bytes/chars)

This is the "shortest" solution that came to mind that is both valid C and C++ and that supports all of Unicode version 6.1, not just the BMP:

```<code>int s[]={-74,-68,31054,-50,-49,-48,-47,-46,-44,-43,-39,-38,-37,-34,-33,-32,-30,-29,-28,-27,-26,-25,-24,-23,-22,-17,-16,-13,-12,-11,-10,-9,-8,-7,-6,-5,-4,-3,-2,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,16,19,20,27,28,29,53195,31,34,36,42,49,50,52,54,58,59,62,64,66,73,81,98,102,103,140,194,263,275,290,1066,1222,1230,2685,2732,2890,3379,6009,21254,22391,30996,53209};
char l[]="l5Hf`7HIAH2IH@IH7IJFIFHJIJKHLJKFHFJFIJIHIJKIJHJFHNFJ@IH?IHJIK1IBHFJHILDI!HI4HpIFKFHWZ-HIHKFH<IDHIFJHc&H9IQ4IJBIH(Ie+H{)Hh<HI.Hn I@H$I@HPCHRAHPAHPCHRAHPAHP;HJAHPAHPAHPDHIHNKFHIHPEHJHPAHRFHIHrKHKZFLJHPEHLdx'HJKHEILIHICHM$IHOILT,HIM~8IX=IoBIFH/IAHFIJDILIJIUDIk|BHTDHt5Hv*H\\5HYBHI9HY5HYEHFIBHI>HY5HY5HY5HY5HY5HY5HY5HY5HY3H[6HICHY6HICHY6HICHY6HICHY6HICHIG";
char u[]="i5Hm8HIBH^3IJAIJ7IHFIKHFIHIFHJEHIHIFHKHIHEIHIJIHIFHFIHKOEJAIJ@IFJIFH1IOHIHJIEHDIsIKVIFHFIHI:HI@H_JFHK=IMJIHJ#Ha:IQ3IHBIJ)IR,Hy,HIMz IQ%IQAHPCHRAHPAHPCHSEIPAHjEHTEHTEHTDHSEHqLKFHJFHJKDHNEIEHJEHRHMgw'HbIFHJEIEHIJPFH$IPIL\"8IX=IoBIK0IRFIHDILIJIUCI}5Hu*H\1775HY5HY5HYIHFJHJEHIAHY5HYHIEHJAHIBHZHIEHIDHIKBHZ5HY5HY5HY5HY5HY5H]6H^6H^6H^6H^6H^G";
int x(int a,char*p){int c=0,i=0,b=-1;while(c>0||s[*p-32]){if(!c)c=s[*p-32]<0?-s[*p++-32]:1,i=s[*p++-32];b+=i,--c;if(a==b)return 1;}return 0;}
</code>```

Please note that "shortest" in this case does not mean that the solution is in any way efficient; it simply means that it is the shortest source code solution. It does not require any Unicode support in the standard library, and in fact does not use the standard library at all. (Which I now understand is what code golf means ... I'm a newbie around here, what can I say.)

To build the lower and upper case data tables I worked as follows:

Downloaded UnicodeData.txt.

Extracted a list of all lines that included the text ";Ll;" or ";Lu;" to indicate a lower case letter or upper case letter respectively.

Built two vectors of code points using the data from step 2.

Converted each absolute code point value to a relative value, the difference between the previous code point and this code point. Because it is convenient for the difference to always be a positive integer (not zero or negative), I use -1 as the value of the first previous code point. In this way zero will not appear anywhere in the sequence.

Used a form of run length encoding to compress runs of identical values into a pair of values. If the next value appears two or more times consecutively, replace the sequence with the negative of the length of the sequence and the value. Otherwise the value only appears once, so just use it as is.

Terminated the compressed vector with zero to mark the end of the sequence.

I noticed there were 96 unique values in the run length encoded vectors, so I built an array of the unique integers and used the index into that array for the lower and upper case vectors.

The above process compressed the vector of lower case code points from 1751 unique values to 350 mostly small non-unique values. In like fashion, the upper case code point vector went from 1441 values to 331 values.

Next I wrote the unique value vector out as a comma separated list of integers suitable for including in source code. I assumed int was 32 bits to avoid using long so that I could save an additional four characters / bytes of source code. Then I wrote out the lower and upper case vectors as strings, where each character in the string has a code 32 greater than its index into the unique integer array. This saves about half the characters necessary to encode the lower & upper case array through omission of comma characters. Three of the characters used have to be escaped (\", \, and \177). They are assigned to unique integers that only appear once in the data so as to minimize the size of the string literals.

What I wound up with was a global array of integers, two global arrays of characters, and a function. An array named s for the unique signed integers, an array named u for the character based upper case code point indexes, and another array named l for the character based lower case code point indexes. The function x takes code point a and pointer to an array of characters p and returns 1 if the code point is in the decompressed / normalized array of code points or 0 otherwise.

If you want to determine if code point cp is lower case, you call "x(cp, l)". If you want to determine if it is upper case, you call "x(cp, u)".

Since the point to this exercise is to make the smallest code to accomplish the task, I never save the decompressed / normalized data. I decompress it piecemeal as I need it every time I call it.

It would be possible to terminate the while loop early if the code point I'm checking has already been passed by during decompression. That would add extra code so I didn't bother, deciding I'd rather pay the speed penalty.

I admit the code is ugly. I did not write it this way originally. Here is the C++ version that I derived the compact C version from:

```<code>const int Ii[] = {-74,-68,31054,-50,-49,-48,-47,-46,-44,-43,-39,-38,-37,-34,-33,-32,-30,-29,-28,-27,-26,-25,-24,-23,-22,-17,-16,-13,-12,-11,-10,-9,-8,-7,-6,-5,-4,-3,-2,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,16,19,20,27,28,29,53195,31,34,36,42,49,50,52,54,58,59,62,64,66,73,81,98,102,103,140,194,263,275,290,1066,1222,1230,2685,2732,2890,3379,6009,21254,22391,30996,53209};
const char Ll[] = "l5Hf`7HIAH2IH@IH7IJFIFHJIJKHLJKFHFJFIJIHIJKIJHJFHNFJ@IH?IHJIK1IBHFJHILDI!HI4HpIFKFHWZ-HIHKFH<IDHIFJHc&H9IQ4IJBIH(Ie+H{)Hh<HI.Hn I@H$I@HPCHRAHPAHPCHRAHPAHP;HJAHPAHPAHPDHIHNKFHIHPEHJHPAHRFHIHrKHKZFLJHPEHLdx'HJKHEILIHICHM$IHOILT,HIM~8IX=IoBIFH/IAHFIJDILIJIUDIk|BHTDHt5Hv*H\\5HYBHI9HY5HYEHFIBHI>HY5HY5HY5HY5HY5HY5HY5HY5HY3H[6HICHY6HICHY6HICHY6HICHY6HICHIG";
const char Lu[] = "i5Hm8HIBH^3IJAIJ7IHFIKHFIHIFHJEHIHIFHKHIHEIHIJIHIFHFIHKOEJAIJ@IFJIFH1IOHIHJIEHDIsIKVIFHFIHI:HI@H_JFHK=IMJIHJ#Ha:IQ3IHBIJ)IR,Hy,HIMz IQ%IQAHPCHRAHPAHPCHSEIPAHjEHTEHTEHTDHSEHqLKFHJFHJKDHNEIEHJEHRHMgw'HbIFHJEIEHIJPFH$IPIL\"8IX=IoBIK0IRFIHDILIJIUCI}5Hu*H\1775HY5HY5HYIHFJHJEHIAHY5HYHIEHJAHIBHZHIEHIDHIKBHZ5HY5HY5HY5HY5HY5H]6H^6H^6H^6H^6H^G";

bool isXx(int cp, const char* Xx)
{
    int count = 0, step = 0, code = -1;

    while ((count > 0) || (Ii[*Xx-32] != 0))
    {
        if (count == 0)
        {
            count = (Ii[*Xx-32] < 0) ? -(Ii[*(Xx++)-32]) : 1;
            step = Ii[*(Xx++)-32];
        }

        code += step;
        --count;

        if (cp < code)
            break;

        if (cp == code)
            return true;
    }

    return false;
}

inline bool isLl(int cp)
{
    return isXx(cp, Ll);
}

inline bool isLu(int cp)
{
    return isXx(cp, Lu);
}
</code>```

In the end, the compact version takes 1922 1216 bytes (including CR+LF end of line sequences). The original version only takes 2271 1578 bytes.

To put this in context of the other solutions that only support the BMP, the equivalent compact version only takes 1451 1005 bytes (or 1800 1367 bytes for the original version).

Title: Unicode character classification

Body:
C & C++, 1922 1216 bytes/chars (BMP only 1451 1005 bytes/chars)

This is the "shortest" solution that came to mind that is both valid C and C++ and that supports all of Unicode version 6.1, not just the BMP:

int s[]={-74,-68,31054,-50,-49,-48,-47,-46,-44,-43,-39,-38,-37,-34,-33,-32,-30,-29,-28,-27,-26,-25,-24,-23,-22,-17,-16,-13,-12,-11,-10,-9,-8,-7,-6,-5,-4,-3,-2,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,16,19,20,27,28,29,53195,31,34,36,42,49,50,52,54,58,59,62,64,66,73,81,98,102,103,140,194,263,275,290,1066,1222,1230,2685,2732,2890,3379,6009,21254,22391,30996,53209};
char l[]="l5Hf`7HIAH2IH@IH7IJFIFHJIJKHLJKFHFJFIJIHIJKIJHJFHNFJ@IH?IHJIK1IBHFJHILDI!HI4HpIFKFHWZ-HIHKFH<IDHIFJHc&H9IQ4IJBIH(Ie+H{)Hh<HI.Hn I@H$I@HPCHRAHPAHPCHRAHPAHP;HJAHPAHPAHPDHIHNKFHIHPEHJHPAHRFHIHrKHKZFLJHPEHLdx'HJKHEILIHICHM$IHOILT,HIM~8IX=IoBIFH/IAHFIJDILIJIUDIk|BHTDHt5Hv*H\\5HYBHI9HY5HYEHFIBHI>HY5HY5HY5HY5HY5HY5HY5HY5HY3H[6HICHY6HICHY6HICHY6HICHY6HICHIG";
char u[]="i5Hm8HIBH^3IJAIJ7IHFIKHFIHIFHJEHIHIFHKHIHEIHIJIHIFHFIHKOEJAIJ@IFJIFH1IOHIHJIEHDIsIKVIFHFIHI:HI@H_JFHK=IMJIHJ#Ha:IQ3IHBIJ)IR,Hy,HIMz IQ%IQAHPCHRAHPAHPCHSEIPAHjEHTEHTEHTDHSEHqLKFHJFHJKDHNEIEHJEHRHMgw'HbIFHJEIEHIJPFH$IPIL\"8IX=IoBIK0IRFIHDILIJIUCI}5Hu*H\1775HY5HY5HYIHFJHJEHIAHY5HYHIEHJAHIBHZHIEHIDHIKBHZ5HY5HY5HY5HY5HY5H]6H^6H^6H^6H^6H^G";
int x(int a,char*p){int c=0,i=0,b=-1;while(c>0||s[*p-32]){if(!c)c=s[*p-32]<0?-s[*p++-32]:1,i=s[*p++-32];b+=i,--c;if(a==b)return 1;}return 0;}

Please note that "shortest" in this case does not mean that the solution is in any way efficient; it simply means that it is the shortest source code solution. It does not require any Unicode support in the standard library, and in fact does not use the standard library at all. (Which I now understand is what code golf means ... I'm a newbie around here, what can I say.)

To build the lower and upper case data tables I worked as follows:

Downloaded UnicodeData.txt.

Extracted a list of all lines that included the text ";Ll;" or ";Lu;" to indicate a lower case letter or upper case letter respectively.

Built two vectors of code points using the data from step 2.

Converted each absolute code point value to a relative value, the difference between the previous code point and this code point. Because it is convenient for the difference to always be a positive integer (not zero or negative), I use -1 as the value of the first previous code point. In this way zero will not appear anywhere in the sequence.

Used a form of run length encoding to compress runs of identical values into a pair of values. If the next value appears two or more times consecutively, replace the sequence with the negative of the length of the sequence and the value. Otherwise the value only appears once, so just use it as is.

Terminated the compressed vector with zero to mark the end of the sequence.

I noticed there were 96 unique values in the run length encoded vectors, so I built an array of the unique integers and used the index into that array for the lower and upper case vectors.

The above process compressed the vector of lower case code points from 1751 unique values to 350 mostly small non-unique values. In like fashion, the upper case code point vector went from 1441 values to 331 values.

Next I wrote the unique value vector out as a comma separated list of integers suitable for including in source code. I assumed int was 32 bits to avoid using long so that I could save an additional four characters / bytes of source code. Then I wrote out the lower and upper case vectors as strings, where each character in the string has a code 32 greater than its index into the unique integer array. This saves about half the characters necessary to encode the lower & upper case array through omission of comma characters. Three of the characters used have to be escaped (\", \, and \177). They are assigned to unique integers that only appear once in the data so as to minimize the size of the string literals.

What I wound up with was a global array of integers, two global arrays of characters, and a function. An array named s for the unique signed integers, an array named u for the character based upper case code point indexes, and another array named l for the character based lower case code point indexes. The function x takes code point a and pointer to an array of characters p and returns 1 if the code point is in the decompressed / normalized array of code points or 0 otherwise.

If you want to determine if code point cp is lower case, you call "x(cp, l)". If you want to determine if it is upper case, you call "x(cp, u)".

Since the point to this exercise is to make the smallest code to accomplish the task, I never save the decompressed / normalized data. I decompress it piecemeal as I need it every time I call it.

It would be possible to terminate the while loop early if the code point I'm checking has already been passed by during decompression. That would add extra code so I didn't bother, deciding I'd rather pay the speed penalty.

I admit the code is ugly. I did not write it this way originally. Here is the C++ version that I derived the compact C version from:

const int Ii[] = {-74,-68,31054,-50,-49,-48,-47,-46,-44,-43,-39,-38,-37,-34,-33,-32,-30,-29,-28,-27,-26,-25,-24,-23,-22,-17,-16,-13,-12,-11,-10,-9,-8,-7,-6,-5,-4,-3,-2,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,16,19,20,27,28,29,53195,31,34,36,42,49,50,52,54,58,59,62,64,66,73,81,98,102,103,140,194,263,275,290,1066,1222,1230,2685,2732,2890,3379,6009,21254,22391,30996,53209};
const char Ll[] = "l5Hf`7HIAH2IH@IH7IJFIFHJIJKHLJKFHFJFIJIHIJKIJHJFHNFJ@IH?IHJIK1IBHFJHILDI!HI4HpIFKFHWZ-HIHKFH<IDHIFJHc&H9IQ4IJBIH(Ie+H{)Hh<HI.Hn I@H$I@HPCHRAHPAHPCHRAHPAHP;HJAHPAHPAHPDHIHNKFHIHPEHJHPAHRFHIHrKHKZFLJHPEHLdx'HJKHEILIHICHM$IHOILT,HIM~8IX=IoBIFH/IAHFIJDILIJIUDIk|BHTDHt5Hv*H\\5HYBHI9HY5HYEHFIBHI>HY5HY5HY5HY5HY5HY5HY5HY5HY3H[6HICHY6HICHY6HICHY6HICHY6HICHIG";
const char Lu[] = "i5Hm8HIBH^3IJAIJ7IHFIKHFIHIFHJEHIHIFHKHIHEIHIJIHIFHFIHKOEJAIJ@IFJIFH1IOHIHJIEHDIsIKVIFHFIHI:HI@H_JFHK=IMJIHJ#Ha:IQ3IHBIJ)IR,Hy,HIMz IQ%IQAHPCHRAHPAHPCHSEIPAHjEHTEHTEHTDHSEHqLKFHJFHJKDHNEIEHJEHRHMgw'HbIFHJEIEHIJPFH$IPIL\"8IX=IoBIK0IRFIHDILIJIUCI}5Hu*H\1775HY5HY5HYIHFJHJEHIAHY5HYHIEHJAHIBHZHIEHIDHIKBHZ5HY5HY5HY5HY5HY5H]6H^6H^6H^6H^6H^G";

bool isXx(int cp, const char* Xx)
{
    int count = 0, step = 0, code = -1;

    while ((count > 0) || (Ii[*Xx-32] != 0))
    {
        if (count == 0)
        {
            count = (Ii[*Xx-32] < 0) ? -(Ii[*(Xx++)-32]) : 1;
            step = Ii[*(Xx++)-32];
        }

        code += step;
        --count;

        if (cp < code)
            break;

        if (cp == code)
            return true;
    }

    return false;
}

inline bool isLl(int cp)
{
    return isXx(cp, Ll);
}

inline bool isLu(int cp)
{
    return isXx(cp, Lu);
}

In the end, the compact version takes 1922 1216 bytes (including CR+LF end of line sequences). The original version only takes 2271 1578 bytes.

To put this in context of the other solutions that only support the BMP, the equivalent compact version only takes 1451 1005 bytes (or 1800 1367 bytes for the original version).


问:
Prove that a Number is Algebraic
Inspired by this answer (emphasis mine):

We will play a game. Suppose you have some number x. You start with x and then you can add, subtract, multiply, or divide by any integer, except zero. You can also multiply by x. You can do these things as many times as you want. If the total becomes zero, you win.

For example, suppose x is 2/3. Multiply by 3, then subtract 2. The result is zero. You win!

Suppose x is 7^(1/3). Multiply by x , then by x again, then subtract 7. You win!

Suppose x is √2+√3. Here it's not easy to see how to win. But it turns out that if you multiply by x, subtract 10, multiply by x twice, and add 1, then you win. (This is not supposed to be obvious; you can try it with your calculator.)

But if you start with x=π, you cannot win. There is no way to get from π to 0 if you add, subtract, multiply, or divide by integers, or multiply by π, no matter how many steps you take. (This is also not supposed to be obvious. It is a very tricky thing!)

Numbers like √2+√3 from which you can win are called algebraic. Numbers like π with which you can't win are called transcendental.

Why is this interesting? Each algebraic number is related arithmetically to the integers, and the winning moves in the game show you how so. The path to zero might be long and complicated, but each step is simple and there is a path. But transcendental numbers are fundamentally different: they are not arithmetically related to the integers via simple steps.

Essentially, you will use the steps used in the question quoted above to "win" the game for given input.

Given a real, algebraic constant x, convert the number to zero by using the following allowed operations:

Add or Subtract an integer.

Multiply or Divide by a non-zero integer.

Multiply by the original constant x.

Input is a string that may contain integers, addition, subtraction, multiplication, division, exponentiation (your choice of ** or ^, exponents are used to represent roots), and parentheses. Spaces in the input are optional, but not in the output. You should output the steps necessary to obtain a result of zero, so multiplying by 7 as one step would be output as *7. A trailing space and/or newline is allowed.

Examples

```<code>0               ->  +0 (or any other valid, or empty)
5/7 + 42        ->  -42 *7 -5 (or shorter: *7 -299)
2^(1/3)         ->  *x *x -2
5*(3**(1/4))    ->  *x *x *x -1875
2^(1/2)+3^(1/2) ->  *x -10 *x *x +1
</code>```

Shortest code wins.

答:
SageMath, 108 bytes

def f(s):p=map('{:+} '.format,numerator(minpoly(sage_eval(s)/1)));return'*'+p[-1][1:]+'*x '.join(p[-2::-1])
```

<p>Try it on SageMathCell.</p>

<p>Explanation:</p>

<p>Evaluate the string symbolically as an algebraic number (<code>sage_eval()</code>).  Every algebraic number is a zero of some polynomial <em>a</em>[0] + <em>a</em>[1] <em>x</em>^1 + <em>a</em>[2] <em>x</em>^2 + ⋯ + <em>a</em>[n] <em>x</em>^<em>n</em> with rational coefficients <em>a</em>[0], …, <em>a</em>[<em>n</em>] (<code>minpoly()</code>). Multiply all the coefficients by their common denominator to turn them into integers (<code>numerator()</code>), then write this polynomial in the desired output format,</p>

```*a[n] +a[n-1] *x +a[n-2] *x … *x +a[1] *x +a[0]
```

<h3>SageMath, 102 bytes, almost</h3>

<pre class="lang-sage prettyprint-override"><code>lambda s:(lambda a,*p:'*%d'%a+'*x'.join(map(' {:+} '.format,p)))(*numerator(minpoly(1/sage_eval(s))))
</code>```

This works for all inputs except 0, because a polynomial for 1/α is a polynomial for α with the coefficients reversed.  :-(

Title: Prove that a Number is Algebraic

Body:
SageMath, 108 bytes

def f(s):p=map('{:+} '.format,numerator(minpoly(sage_eval(s)/1)));return'*'+p[-1][1:]+'*x '.join(p[-2::-1])

Try it on SageMathCell.

Explanation:

Evaluate the string symbolically as an algebraic number (sage_eval()).  Every algebraic number is a zero of some polynomial a[0] + a[1] x^1 + a[2] x^2 + ⋯ + a[n] x^n with rational coefficients a[0], …, a[n] (minpoly()). Multiply all the coefficients by their common denominator to turn them into integers (numerator()), then write this polynomial in the desired output format,

*a[n] +a[n-1] *x +a[n-2] *x … *x +a[1] *x +a[0]

SageMath, 102 bytes, almost

lambda s:(lambda a,*p:'*%d'%a+'*x'.join(map(' {:+} '.format,p)))(*numerator(minpoly(1/sage_eval(s))))

This works for all inputs except 0, because a polynomial for 1/α is a polynomial for α with the coefficients reversed.  :-(


问:
"Add one" to every color in an image
You would simply take this image and make every color added one to every hexadecimal digit. For example, #49de5f would become #5aef60 (with the 9 looping to an a, and the f looping to a 0.)

This would also mean that all white (#ffffff) would become black (#000000) because all f loops back to 0, but all black will become a lighter shade of black (#111111).

Scoring is based on the least number of bytes used, as this is a code-golf question.

Use the below image as the input image for your code, and put the output image of your code into your answer.

If you want to, you can also use this other rainbow image:

答:
Dyalog APL, <s>21</s> 15 bytes

Programs may output as a matrix of RGB pixel values

I assume output may be in the same format.

New solution takes matrix of values [[r,g,b,r,g,b],[r,g,b,…

```<code>16⊥16|1+16 16⊤⎕
</code>```

Explanation

⎕ get numeric input

16 16⊤ convert to 2-digit base 16

1+ add 1, i.e. 0 → 1, 1 → 2, 15 → 16

16| modulus 16, i.e. 16 → 0

16⊥ convert from base 16

Example

```<code>      ⊢m←2 6⍴90 239 96 255 255 255 0 0 0 239 239 239
90 239 96 255 255 255
 0   0  0 239 239 239
      16⊥16|1+⎕⊤⍨2/16
⎕:
      m
107 240 113   0   0   0
 17  17  17 240 240 240
</code>```

Old 21 byte solution takes matrix of [["RRGGBB","RRGGBB"],["RRGGBB",…

```<code>{n[16|1+⍵⍳⍨n←⎕D,⎕A]}¨
</code>```

Needs ⎕IO←0, which is default on many systems.

Explanation

{…}¨ for each RGB 6-char string, represent it as ⍵ and do:

n←⎕D,⎕A assign "0…9A…Z" to n

⍵⍳⍨ find indices of the individual characters in n

1+ add one to the index, i.e. 0 → 1, 1 → 2, 15 → 16

16| modulus 16, i.e. 16 → 0

n[…] use that to index into n

Example

```<code>      f←{n[16|1+⍵⍳⍨n←⎕D,⎕A]}¨
      ⊢p←2 2⍴'5AEF60' 'FFFFFF' '000000' 'EFEFEF'
┌──────┬──────┐
│5AEF60│FFFFFF│
├──────┼──────┤
│000000│EFEFEF│
└──────┴──────┘
      f p
┌──────┬──────┐
│6BF071│000000│
├──────┼──────┤
│111111│F0F0F0│
└──────┴──────┘
</code>```

Title: "Add one" to every color in an image

Body:
Dyalog APL, <s>21</s> 15 bytes

Programs may output as a matrix of RGB pixel values

I assume output may be in the same format.

New solution takes matrix of values [[r,g,b,r,g,b],[r,g,b,…

16⊥16|1+16 16⊤⎕

Explanation

⎕ get numeric input

16 16⊤ convert to 2-digit base 16

1+ add 1, i.e. 0 → 1, 1 → 2, 15 → 16

16| modulus 16, i.e. 16 → 0

16⊥ convert from base 16

Example

      ⊢m←2 6⍴90 239 96 255 255 255 0 0 0 239 239 239
90 239 96 255 255 255
 0   0  0 239 239 239
      16⊥16|1+⎕⊤⍨2/16
⎕:
      m
107 240 113   0   0   0
 17  17  17 240 240 240

Old 21 byte solution takes matrix of [["RRGGBB","RRGGBB"],["RRGGBB",…

{n[16|1+⍵⍳⍨n←⎕D,⎕A]}¨

Needs ⎕IO←0, which is default on many systems.

Explanation

{…}¨ for each RGB 6-char string, represent it as ⍵ and do:

n←⎕D,⎕A assign "0…9A…Z" to n

⍵⍳⍨ find indices of the individual characters in n

1+ add one to the index, i.e. 0 → 1, 1 → 2, 15 → 16

16| modulus 16, i.e. 16 → 0

n[…] use that to index into n

Example

      f←{n[16|1+⍵⍳⍨n←⎕D,⎕A]}¨
      ⊢p←2 2⍴'5AEF60' 'FFFFFF' '000000' 'EFEFEF'
┌──────┬──────┐
│5AEF60│FFFFFF│
├──────┼──────┤
│000000│EFEFEF│
└──────┴──────┘
      f p
┌──────┬──────┐
│6BF071│000000│
├──────┼──────┤
│111111│F0F0F0│
└──────┴──────┘


问:
Derivative at the Edge
My preferred way to approximate a derivative is the central difference, its more accurate than forward difference or backward difference, and I'm too lazy to go higher-order. But the central difference requires a data point on either side of point you are evaluating. Normally this means you end up not having a derivative at either endpoint. To solve it, I want you to switch to forward and backward difference at the edges:

Specifically, I want you to use a forward difference for the first point, a backward difference for the last point, and a central difference for all the points in the middle. Also, you can assume x values are evenly spaced, and focus only on y. Use these formulas:

Good luck, I'm looking forward to seeing if someone comes up with a simple rule which reproduces all 3 derivatives in the right places!

EX INPUT:

```<code>0.034  9.62    8.885   3.477   2.38
</code>```

I will use FD, CD, and BD to denote which algorithm to use in which spot, so above 5 points are used to approximate derivatives using

```<code>FD     CD      CD      CD     BD
</code>```

And then the calculated values would be:

```<code>9.586  4.4255 -3.0715 -3.2525 -1.097
</code>```

You can assume that there will always be at least 3 input points, and you can calculate using single or double precision.

And as always, shortest answer wins.

答:
Pyth - 29 bytes

Stupid simple approach.

```<code>s[_-F<Q2mc-@Qhd@Qtd2tUtQ_-F>2
</code>```

Try it online here.

Title: Derivative at the Edge

Body:
Pyth - 29 bytes

Stupid simple approach.

s[_-F<Q2mc-@Qhd@Qtd2tUtQ_-F>2

Try it online here.


问:
Create output twice the length of the code

The Challenge

Write a complete program that writes twice as many bytes to standard output as the length of the program.

Rules

The program must write ASCII characters to the standard output.

The contents of the output doesn't matter.

The output, measured in bytes, must be exactly twice the length of the program, also measured in bytes, unless you fulfill the bonus.

Any trailing newline is included in the output's byte count.

Bonus

Your program can optionally take a number, n, as input. If so, the output must be exactly n * program length bytes. You can assume that n will always be a positive integer. If no input is provided, n must default to 2.

If you do this,  you can subtract 25 bytes from your score.

Shortest program wins.

Restrictions

No standard loopholes.

The program must be at least 1 byte long.

No adding unnecessary whitespace to the source code to change its length. Similarly, comments don't count.

Unless you fulfill the bonus, the program must accept no input. If you do fulfill the bonus, the integer must be the only input.

Lowest score (program length in bytes - bonus) wins.

The shortest answer for each language wins for that language.

Leaderboards

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

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

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

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

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

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

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

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

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

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

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

```

答:
dc, 7 bytes

```<code>2oFddnf
</code>```

```<code>2o         Set the output radix to 2: write to stdout using the binary digits [01]
  F        Push 0xF on the stack, equivalent to 1111b
   dd      Duplicate the top-of-stack, then duplicate the top-of-stack: 1111b, 1111b, 1111b
     n     Pop the topmost item from the stack (1111b) and write it (using binary, per
               the above) to stdout. Do not follow with a newline.
      f    Dump the contents of the stack (1111b, 1111b), following each item with a
               newline.
</code>```

Visible characters comprise 12 bytes; add two (2) newlines for a total of 14.

Edit: Since I'm the only dc answer with a natural number for a score, why not post the following?

dc, 8 bytes

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

Clears the stack seven times, then attempts to pop the top (non-existent) value and print it as text (i.e., a number with output-radix UCHAR_MAX+1). Since the stack is empty, this results in a fifteen-byte error message followed by a single newline. (Works for GNU dc 1.2)

Body:
dc, 7 bytes

2oFddnf

2o         Set the output radix to 2: write to stdout using the binary digits [01]
  F        Push 0xF on the stack, equivalent to 1111b
   dd      Duplicate the top-of-stack, then duplicate the top-of-stack: 1111b, 1111b, 1111b
     n     Pop the topmost item from the stack (1111b) and write it (using binary, per
               the above) to stdout. Do not follow with a newline.
      f    Dump the contents of the stack (1111b, 1111b), following each item with a
               newline.

Visible characters comprise 12 bytes; add two (2) newlines for a total of 14.

Edit: Since I'm the only dc answer with a natural number for a score, why not post the following?

dc, 8 bytes

cccccccP

Clears the stack seven times, then attempts to pop the top (non-existent) value and print it as text (i.e., a number with output-radix UCHAR_MAX+1). Since the stack is empty, this results in a fifteen-byte error message followed by a single newline. (Works for GNU dc 1.2)


答:
Pyth, 29 bytes

```<code>M?>GH0|qGH+sgLGtBtH?%H3ZgG/H3
</code>```

Try it online!

Defines a function. Added three bytes in the link to call the function.

Title: Ways to get to the number

Body:
Pyth, 29 bytes

M?>GH0|qGH+sgLGtBtH?%H3ZgG/H3

Try it online!

Defines a function. Added three bytes in the link to call the function.


问:
Chessboard maze
Chess pieces (kings, queens, rooks, bishops, and knights) and pawns are on a board, but not on the a1 or h8 square. Your task is to travel from the empty a1 to the empty h8 squares, passing through only empty squares. The rules of movement are as follows:

You can proceed from any empty square to any empty square next to it (same rank, next or preceding file; or same file, next or preceding rank).

You can proceed from any empty square to any empty square diagonally next to it (next or preceding rank, next or preceding file), provided that the catty-corner squares contain either (a) two pawns or (b) pawns/pieces of opposite color. (Two non-pawn pieces, or a non-pawn piece and a pawn, of the same color are strong enough to bar your progress across the corner, but two pawns are not; and pieces/pawns of opposite color don't work in concert to bar your way.) For example, if you're on c4 and d5 is empty, you can proceed to it provided c5 and d4 contain pawns or contain pieces/pawns of opposite color. See the "Example diagonals" section, below, for pictures.

Input

FEN's board description. That is: The input will be a string that includes a description of rank 8, a slash (/), a description of rank 7, a slash, …, and a description of rank 1. The description of each rank comprises numbers and letters running from file a to file h, where the letters indicate pieces and pawns (the black ones are p= pawn, n=knight, b=bishop, r=rook, q=queen, k=king, and the white ones are capitalized versions of the same) and the numbers indicate the successive number of empty squares. For example, rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBN is the board after one ply move (king's pawn to e4) in a chess game.

a1 and h8 will be empty in the input; i.e., the first slash has a digit before it, and the last slash has a digit after it.

Output

Truthy or falsey, indicating whether successful passage to h8 is possible.

If the input is not a valid FEN board description (meaning, one that matches my explanation above), or if a1 or h8 is occupied, then the output can be anything or nothing. (In other words: you may assume the input meets the requirements above.)

Scoring

This is code golf: fewest bytes wins.

Example input and output

Note that your code must work for all valid inputs, not only the examples.

Add a space and a w after each FEN to visualize it at http://www.dhtmlgoodies.com/scripts/chess-fen/chess-fen-3.html. (Note that some other online FEN visualizers will not allow a board that's illegal in chess, e.g. with a pawn on rank 1 or 8, so can't be used for our purposes.)

Truthy examples

8/8/8/8/8/8/8/8 — the empty board

1p1Q4/2p1Q3/2p1Q3/2p1Q3/2p1Q3/2p1Q3/Q1p1Q3/1q3q2 — there's a path a1, b2, b3, b4, b5, b6, b7, c8, d7, (not e8, that's blocked off, but) d6, d5, d4, d3, d2, d1, e1, f2, f3, f4, f5, f6, f7, f8, g8, h8

8/8/KKKKK3/K3K3/K1K1p3/Kp1K4/K1KK4/2KK4 — an example where a square that's blocked at one point must be passed through later on (to make sure you don't set squares as impassable)

K1k1K1K1/1K1k1K1k/K1K1k1K1/1k1K1K1k/K1k1K1k1/1K1k1k1K/K1K1k1K1/1k1k1K1k — there's a single path through (just follow your nose: there's only one square to move to at each step, unless take a step backward); this is also an example where a square is blocked at one point but necessary later

Falsey examples

6Q1/5N2/4Q3/3N4/2Q5/1N6/2Q5/1N6 — any attempt at a path will have to pass through two diagonally situated same-color pieces

N1q1K1P1/1R1b1p1n/r1B1B1Q1/1p1Q1p1b/B1P1R1N1/1B1P1Q1R/k1k1K1q1/1K1R1P1r — the only way through the a8-h1 diagonal is at f2-g3, but that would require passage through e1-d2 or f2-e3, which are both impossible.

4Q3/4q3/4Q3/5Q2/6Q1/3QqP2/2Q5/1Q6

4q3/4Q3/4q3/5q2/6q1/3qQp2/2q5/1q6

Example diagonals

In case the prose above was unclear, here are some pictures.

Passable diagonals

Impassable diagonals

答:
VBA 668 666 633 622 548 510 489 435 331 322 319 315 bytes

```<code>Function Z(F):Dim X(7,7):While Q<64:R=R+1:V=Asc(Mid(F,R))-48:If V>9 Then X(Q\8,Q Mod 8)=(3+(V\8=V/8))*Sgn(48-V):V=1
Q=Q-V*(V>0):Wend:X(7,0)=1:For W=0 To 2E3:Q=W Mod 8:P=W\8 Mod 8:For T=Q+(Q>0) To Q-(Q<7):For S=P+(P>0) To P-(P<7):If X(S,T)=0 Then X(S,T)=(1=X(P,Q))*(6>X(P,T)*X(S,Q))
Next S,T,W:Z=X(0,7):End Function
</code>```

Reading the input string occupies up to 'Wend'. Nice side effect - this abandons the input string once the board [X] is fully coded, so you can leave a description on the end.

In the board coding, pawns are 2, other pieces are 3, black is negative. Pawns are recognized by 'P' & 'p' having character codes divisible by 8.

'X(7,0)=1', setting a1 accessible, is where the path checks start. This repeatedly scans the board trying to add accessible squares from squares marked as accessible (1) so far. Diagonal access and occupancy are checked in a IF + logic-calc which once lived in a function but now sits in nested neighbour loops. The diagonal access check relies on the product of the two kitty-corner squares, which is only at 6 or more if pieces there are the same colour and at least one is a piece not a pawn.

Call in spreadsheet; returns the value in X(0,7) - 1 if h8 accessible and 0 if not - which Excel recognizes as truthy / falsy.
=IF(Z(C2), "yes","no")

I maybe got carried away with scrunching the code down, above, so here is a semi-ungolfed commented version:

```<code>Function MazeAssess(F)  'input string F (FEN)
Dim X(7, 7)             'size/clear the board; also, implicitly, Q = 0: R = 0
'Interpret string for 8 rows of chessboard
While Q < 64
    R = R + 1           ' next char
    V = Asc(Mid(F, R)) - 48  ' adjust so numerals are correct
    If V > 9 Then X(Q \ 8, Q Mod 8) = (3 + (V \ 8 = V / 8)) * Sgn(48 - V): V = 1 ' get piece type (2/3) and colour (+/-); set for single column step
    Q = Q - V * (V > 0) ' increment column (unless slash)
Wend
'Evaluate maze
X(7, 0) = 1             ' a1 is accessible
For W = 0 To 2000       ' 1920 = 30 passes x 8 rows x 8 columns, golfed to 2E3
    Q = W Mod 8         ' extracting column
    P = W \ 8 Mod 8     ' extracting row
    For T = Q + (Q > 0) To Q - (Q < 7)     ' loop on nearby columns Q-1 to Q+1 with edge awareness
        For S = P + (P > 0) To P - (P < 7) ' loop on nearby rows (as above)
            If X(S, T) = 0 Then X(S, T) = (1 = X(P, Q)) * (6 > X(P, T) * X(S, Q)) ' approve nearby empty squares if current square approved and access is possible
        Next 'S
    Next 'T
Next 'W
MazeAssess = X(0, 7)    ' report result for h8
End Function
</code>```

Progress notes

Edit1: The code is now not as 666-devilish :-D  and has lost its functions; I found a short-enough way to write them to avoid the overhead.

Edit2: Another biggish leap forward, effectively finishing the work of removing the inc/dec functions, sigh, and using a couple of globals. I might finally be getting the hang of this....

The coding of pieces & squares changed. No effect on code length.

Edit3: Return of (fake) functions, removing all those annoying Call bytes, and some other tweaks.

Edit4: Breaking through the big 500, woohoo - smooshed the 3 For loops into 1.

Edit5: Jiminy Cricket, another big drop when I smooshed the two functions together - my diagonal access check always passes for adjacent squares, so...

Edit6: Holy niblicks, another massive drop. Buh-bye to external functions and thus globals... I have gone to under half the original posted length....

Edit7: Add ungolfed version

Edit8: Revised the read process for a few dollars more

Edit9: Squeezed a couple of expressions for the last few drops of blood

Edit10: Compund Next statement sheds a few bytes

For interest, graphics of the boards after accessibility analysis (the code numbers are out of date but...) accessible squares are green, inaccessible squares white and other colours are pieces or pawns.

A couple of challenge boards: h8 is accessible in both:

P1Pq2p1/1P1R1R1p/1K2R1R1/1p1p1p2/p1b1b1np/1B1B1N1k/Q1P1P1N1/1r1r1n2 - 10 passes to solve

P1P3r1/1P1R2r1/1N1R1N2/1P1P1P2/1n1p1ppp/1B1B4/1b1pppp1/1P6 - a winding path

Title: Chessboard maze

Body:
VBA 668 666 633 622 548 510 489 435 331 322 319 315 bytes

Function Z(F):Dim X(7,7):While Q<64:R=R+1:V=Asc(Mid(F,R))-48:If V>9 Then X(Q\8,Q Mod 8)=(3+(V\8=V/8))*Sgn(48-V):V=1
Q=Q-V*(V>0):Wend:X(7,0)=1:For W=0 To 2E3:Q=W Mod 8:P=W\8 Mod 8:For T=Q+(Q>0) To Q-(Q<7):For S=P+(P>0) To P-(P<7):If X(S,T)=0 Then X(S,T)=(1=X(P,Q))*(6>X(P,T)*X(S,Q))
Next S,T,W:Z=X(0,7):End Function

Reading the input string occupies up to 'Wend'. Nice side effect - this abandons the input string once the board [X] is fully coded, so you can leave a description on the end.

In the board coding, pawns are 2, other pieces are 3, black is negative. Pawns are recognized by 'P' & 'p' having character codes divisible by 8.

'X(7,0)=1', setting a1 accessible, is where the path checks start. This repeatedly scans the board trying to add accessible squares from squares marked as accessible (1) so far. Diagonal access and occupancy are checked in a IF + logic-calc which once lived in a function but now sits in nested neighbour loops. The diagonal access check relies on the product of the two kitty-corner squares, which is only at 6 or more if pieces there are the same colour and at least one is a piece not a pawn.

Call in spreadsheet; returns the value in X(0,7) - 1 if h8 accessible and 0 if not - which Excel recognizes as truthy / falsy.
=IF(Z(C2), "yes","no")

I maybe got carried away with scrunching the code down, above, so here is a semi-ungolfed commented version:

Function MazeAssess(F)  'input string F (FEN)
Dim X(7, 7)             'size/clear the board; also, implicitly, Q = 0: R = 0
'Interpret string for 8 rows of chessboard
While Q < 64
    R = R + 1           ' next char
    V = Asc(Mid(F, R)) - 48  ' adjust so numerals are correct
    If V > 9 Then X(Q \ 8, Q Mod 8) = (3 + (V \ 8 = V / 8)) * Sgn(48 - V): V = 1 ' get piece type (2/3) and colour (+/-); set for single column step
    Q = Q - V * (V > 0) ' increment column (unless slash)
Wend
'Evaluate maze
X(7, 0) = 1             ' a1 is accessible
For W = 0 To 2000       ' 1920 = 30 passes x 8 rows x 8 columns, golfed to 2E3
    Q = W Mod 8         ' extracting column
    P = W \ 8 Mod 8     ' extracting row
    For T = Q + (Q > 0) To Q - (Q < 7)     ' loop on nearby columns Q-1 to Q+1 with edge awareness
        For S = P + (P > 0) To P - (P < 7) ' loop on nearby rows (as above)
            If X(S, T) = 0 Then X(S, T) = (1 = X(P, Q)) * (6 > X(P, T) * X(S, Q)) ' approve nearby empty squares if current square approved and access is possible
        Next 'S
    Next 'T
Next 'W
MazeAssess = X(0, 7)    ' report result for h8
End Function

Progress notes

Edit1: The code is now not as 666-devilish :-D  and has lost its functions; I found a short-enough way to write them to avoid the overhead.

Edit2: Another biggish leap forward, effectively finishing the work of removing the inc/dec functions, sigh, and using a couple of globals. I might finally be getting the hang of this....

The coding of pieces & squares changed. No effect on code length.

Edit3: Return of (fake) functions, removing all those annoying Call bytes, and some other tweaks.

Edit4: Breaking through the big 500, woohoo - smooshed the 3 For loops into 1.

Edit5: Jiminy Cricket, another big drop when I smooshed the two functions together - my diagonal access check always passes for adjacent squares, so...

Edit6: Holy niblicks, another massive drop. Buh-bye to external functions and thus globals... I have gone to under half the original posted length....

Edit7: Add ungolfed version

Edit8: Revised the read process for a few dollars more

Edit9: Squeezed a couple of expressions for the last few drops of blood

Edit10: Compund Next statement sheds a few bytes

For interest, graphics of the boards after accessibility analysis (the code numbers are out of date but...) accessible squares are green, inaccessible squares white and other colours are pieces or pawns.

A couple of challenge boards: h8 is accessible in both:

P1Pq2p1/1P1R1R1p/1K2R1R1/1p1p1p2/p1b1b1np/1B1B1N1k/Q1P1P1N1/1r1r1n2 - 10 passes to solve

P1P3r1/1P1R2r1/1N1R1N2/1P1P1P2/1n1p1ppp/1B1B4/1b1pppp1/1P6 - a winding path


问:
Finding duplicate balls in a basket?
A basket is full with \$n\$ colored balls. For each color except one, there are at least 2 balls with that color. Find the color which only has one ball. in \$O(n)\$ space complexity.

What if each ball is repeated exactly  twice?

You can consider the input to be an array or a list or any container of colors as strings with a maximum length of 100

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

答:
Groovy - 22 chars

```<code>it.min{a->it.count(a)}
</code>```

Attribution and test case:

```<code>lone={it.min{a->it.count(a)}}

l = ['red','green', 'red', 'blue', 'green']

assert lone(l) == 'blue'
assert lone(l) != 'red'
</code>```

ContentLicense: CC BY-SA 4.0

Title: Finding duplicate balls in a basket?

Body:
Groovy - 22 chars

it.min{a->it.count(a)}

Attribution and test case:

lone={it.min{a->it.count(a)}}

l = ['red','green', 'red', 'blue', 'green']

assert lone(l) == 'blue'
assert lone(l) != 'red'


问:
Tips for golfing in dc
What general tips do you have for golfing in dc?

dc is a calculator utility for UNIX/Linux that predates the C language. I am interested in how to make my dc programs (calculations?) shorter. I'm looking for ideas that can be applied to general code-golf that are at least a little bit specific to dc (eg. removing comments is not a helpful answer)

Please post one tip per answer.

答:
When initialising a <s>function</s> macro (we'll use F) that you want to run immediately, use something like dsFx rather than sFlFx. The same works for variables: dsa rather than sala.

If you need to do other stuff in between the storing and the loading (e.g., sa[other stuff]la), still consider whether the above is viable: If you leave a value on the stack before the other operations, will it be back at the top by the end of those operations?

Title: Tips for golfing in dc


问:
Alternating sign matrix verification
An alternating sign matrix is an n by n matrix consisting of the numbers -1, 0, 1, such that:

The sum of each row and column is 1

The nonzero entries in each row and column alternate in sign

These matrices generalise permutation matrices, and the number of such matrices for a given n was of interest for some time. They occur naturally during the Dodgson condensation method of computing matrix determinants (named after Charles Dodgson, better known as Lewis Carroll).

Here are some examples of 4 by 4 alternating sign matrices:

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

And here are some examples of 4 by 4 matrices which aren't alternating sign matrices:

```<code> 0  1  0  0
 0  0  0  1
 1  0  0  0
 0  0  1 -1    (last row and last column don't add to 1)

 0  0  0  1
 1  0  0  0
-1  1  1  0
 1  0  0  0    (third row does not alternate correctly)
</code>```

Your program or function will be given an n by n matrix (n >= 1) of -1s, 0s and 1s — output a truthy value if the given matrix is an alternating sign matrix, otherwise output a falsy value.

This is code-golf, so the goal is to minimise the number of bytes used.

Test cases

The following test cases are given in a Python-like 2D list format.

Truthy:

```<code>[[1]]
[[1,0],[0,1]]
[[0,1],[1,0]]
[[0,1,0],[0,0,1],[1,0,0]]
[[0,1,0],[1,-1,1],[0,1,0]]
[[0,1,0,0],[0,0,1,0],[1,0,0,0],[0,0,0,1]]
[[1,0,0,0],[0,0,1,0],[0,1,-1,1],[0,0,1,0]]
[[0,0,1,0],[0,1,-1,1],[1,-1,1,0],[0,1,0,0]]
[[0,0,1,0],[1,0,-1,1],[0,1,0,0],[0,0,1,0]]
[[0,0,1,0,0],[0,1,-1,1,0],[1,-1,1,0,0],[0,1,0,-1,1],[0,0,0,1,0]]
[[0,0,1,0,0,0,0,0],[1,0,-1,0,1,0,0,0],[0,0,0,1,-1,0,0,1],[0,0,1,-1,1,0,0,0],[0,0,0,0,0,0,1,0],[0,0,0,0,0,1,0,0],[0,1,-1,1,0,0,0,0],[0,0,1,0,0,0,0,0]]
[[0,0,0,0,1,0,0,0],[0,0,1,0,-1,1,0,0],[0,0,0,1,0,0,0,0],[1,0,0,-1,1,-1,1,0],[0,1,-1,1,-1,1,0,0],[0,0,0,0,1,0,0,0],[0,0,1,0,0,0,0,0],[0,0,0,0,0,0,0,1]]
</code>```

Falsy:

```<code>[[0]]
[[-1]]
[[1,0],[0,0]]
[[0,0],[0,1]]
[[-1,1],[1,0]]
[[0,1],[1,-1]]
[[0,0,0],[0,0,0],[0,0,0]]
[[0,1,0],[1,0,1],[0,1,0]]
[[-1,1,1],[1,-1,1],[1,1,-1]]
[[0,0,1],[1,0,0],[0,1,-1]]
[[0,1,0,0],[0,0,0,1],[1,0,0,0],[0,0,1,-1]]
[[0,0,1,0],[0,0,1,0],[1,0,-1,1],[0,1,0,0]]
[[0,0,0,1],[1,0,0,0],[-1,1,1,0],[1,0,0,0]]
[[1,0,1,0,-1],[0,1,0,0,0],[0,0,0,0,1],[0,0,0,1,0],[0,0,0,0,1]]
[[0,0,1,0,0],[0,1,-1,1,0],[1,-1,1,0,0],[0,1,1,-1,0],[0,0,-1,1,1]]
[[0,-1,0,1,1],[1,-1,1,-1,1],[0,1,1,0,-1],[1,1,-1,1,-1],[-1,1,0,0,1]]
[[0,0,1,0,0,0,0,0],[1,0,1,0,1,0,0,0],[0,0,0,1,-1,0,0,1],[0,0,1,-1,1,0,0,0],[0,0,0,0,0,0,1,0],[0,0,0,0,0,1,0,0],[0,1,-1,1,0,0,0,0],[0,0,1,0,0,0,0,0]]
</code>```

答:
Jelly, 11 bytes

```<code>;Zj-+\ṚQḄ=2
</code>```

Returns 1 for alternating sign matrices, 0 otherwise. Try it online! or verify all test cases.

Background

Disregarding zeroes, each row and column has to consist of the pattern (1, -1)* 1, i.e., alternating occurrences of 1 and -1, starting and ending with a 1 (so the sum is 1).

To verify this is the case, we take the array of all rows and columns, and join them using -1 as separator. Since all endpoints are 1's, the resulting flat array satisfies the pattern (1, -1)* 1 if and only if the rows and columns do.

For the actual test, we compute the cumulative sum of the array. For an alternating sign matrix, the result will be an array of 0's and 1's that ends with a 1.

We reverse the cumulative sum and deduplicate it, keeping the order of the initial occurrences of all unique elements. For a truthy input, the result will be the list [1, 0].

To output the corresponding Boolean, we convert the duplicated cumulative sums from binary to integer and test if the result is 2.

How it works

```<code>;Zj-+\ṚQḄ=2  Main link. Argument: M (matrix / 2D array)

 Z           Zip; transpose M's rows and columns.
;            Concatenate M and zipped M.
  j-         Join, separating by -1.
    +\       Take the cumulative sum of the result.
      Ṛ      Reverse the array of partial sums.
       Q     Unique; deduplicate the partial sums.
        Ḅ    Unbinary; convert from base 2 to integer.
         =2  Test for equality with 2.
</code>```

Title: Alternating sign matrix verification


问:
We're no strangers to code golf, you know the rules, and so do I
Write the shortest program that prints the entire lyrics of "Never Gonna Give You Up" by Rick Astley.

Rules:

Must output the lyrics exactly as they appear in the above pastebin*. Here's the raw dump: http://pastebin.com/raw/wwvdjvEj

Cannot rely on any external resources - all lyrics must be generated by / embedded in code.

No use of existing compression algorithms (e.g. gzip / bzip2) unless you include the full algorithm in your code.

Use any language, shortest code wins.

Update, 1st June 2012:

For solutions containing non-ASCII text, the size of your solution will be counted in bytes, based on UTF-8 encoding. If you use codepoints that cannot be encoded in UTF-8, your solution will not be judged as valid.

Update, 7th June 2012:

Thank you all for your awesome solutions! I'll be accepting the shortest answer tomorrow afternoon. Right now, Peter Taylor's GolfScript answer is winning, so get cracking on some improvements if you want to beat him! :)

*There is a typo in the Pastebin (line 46, "know" should be "known").  You may either replicate it or not at your discretion.

答:
Java, 858 bytes

```<code>interface a{static void main(String[]A){String b="I just wanna tell you how I'm feeling\nGotta make you understand\n\n",B="Never gonna give you up\nNever gonna let you down\nNever gonna run around and desert you\nNever gonna make you cry\nNever gonna say goodbye\nNever gonna tell a lie and hurt you\n\n",c="We've known each other for so long\nYour heart's been aching but\nYou're too shy to say it\nInside we both know what's been going on\nWe know the game and we're gonna play it\n",C="(Ooh, give you up)\n",d="(Ooh)\nNever gonna give, never gonna give\n(Give you up)\n";System.out.print("We're no strangers to love\nYou know the rules and so do I\nA full commitment's what I'm thinking of\nYou wouldn't get this from any other guy\n"+b+B+c+"And if you ask me how I'm feeling\nDon't tell me you're too blind to see\n\n"+B+B+C+C+d+d+"\n"+c+"\n"+b+B+B+B);}}
</code>```

Wow. I didn't really think I could compress this hard.

Ungolfed In a human-readable form:

```<code>interface a {
    static void main(String[] A) {
        String b = "I just wanna tell you how I'm feeling\n"+
                   "Gotta make you understand\n\n";

        String B = "Never gonna give you up\n"+
                   "Never gonna let you down\n"+
                   "Never gonna run around and desert you\n"+
                   "Never gonna make you cry\n"+
                   "Never gonna say goodbye\n"+
                   "Never gonna tell a lie and hurt you\n\n";

        String c = "We've known each other for so long\n"+
                   "Your heart's been aching but\n"+
                   "You're too shy to say it\n"+
                   "Inside we both know what's been going on\n"+
                   "We know the game and we're gonna play it\n";

        String C = "(Ooh, give you up)\n";

        String d = "(Ooh)\n"+
                   "Never gonna give, never gonna give\n"+
                   "(Give you up)\n";

        System.out.print(
            "We're no strangers to love\n"+
            "You know the rules and so do I\n"+
            "A full commitment's what I'm thinking of\n"+
            "You wouldn't get this from any other guy\n"+
            b+
            B+
            c+
            "And if you ask me how I'm feeling\n"+
            "Don't tell me you're too blind to see\n\n"+
            B+
            B+
            C+
            C+
            d+
            d+
            "\n"+
            c+
            "\n"+
            b+
            B+
            B+
            B
        );
    }
}
</code>```

Body:
Java, 858 bytes

interface a{static void main(String[]A){String b="I just wanna tell you how I'm feeling\nGotta make you understand\n\n",B="Never gonna give you up\nNever gonna let you down\nNever gonna run around and desert you\nNever gonna make you cry\nNever gonna say goodbye\nNever gonna tell a lie and hurt you\n\n",c="We've known each other for so long\nYour heart's been aching but\nYou're too shy to say it\nInside we both know what's been going on\nWe know the game and we're gonna play it\n",C="(Ooh, give you up)\n",d="(Ooh)\nNever gonna give, never gonna give\n(Give you up)\n";System.out.print("We're no strangers to love\nYou know the rules and so do I\nA full commitment's what I'm thinking of\nYou wouldn't get this from any other guy\n"+b+B+c+"And if you ask me how I'm feeling\nDon't tell me you're too blind to see\n\n"+B+B+C+C+d+d+"\n"+c+"\n"+b+B+B+B);}}

Wow. I didn't really think I could compress this hard.

Ungolfed In a human-readable form:

interface a {
    static void main(String[] A) {
        String b = "I just wanna tell you how I'm feeling\n"+
                   "Gotta make you understand\n\n";

        String B = "Never gonna give you up\n"+
                   "Never gonna let you down\n"+
                   "Never gonna run around and desert you\n"+
                   "Never gonna make you cry\n"+
                   "Never gonna say goodbye\n"+
                   "Never gonna tell a lie and hurt you\n\n";

        String c = "We've known each other for so long\n"+
                   "Your heart's been aching but\n"+
                   "You're too shy to say it\n"+
                   "Inside we both know what's been going on\n"+
                   "We know the game and we're gonna play it\n";

        String C = "(Ooh, give you up)\n";

        String d = "(Ooh)\n"+
                   "Never gonna give, never gonna give\n"+
                   "(Give you up)\n";

        System.out.print(
            "We're no strangers to love\n"+
            "You know the rules and so do I\n"+
            "A full commitment's what I'm thinking of\n"+
            "You wouldn't get this from any other guy\n"+
            b+
            B+
            c+
            "And if you ask me how I'm feeling\n"+
            "Don't tell me you're too blind to see\n\n"+
            B+
            B+
            C+
            C+
            d+
            d+
            "\n"+
            c+
            "\n"+
            b+
            B+
            B+
            B
        );
    }
}


答:
Length Calculation: Z, X, and z

Z pops the ToS and pushes the number of digits (decimal) if it's a number or the number of characters if it's a string. This can be useful for detecting the length of a result (for buffering output) or computing string length. Note that for numbers, Z pushes the combined length of the integer part and the fraction part.

X pops the ToS and pushes the number of digits in the fraction part of the number. If the ToS was a string, 0 is pushed.

To find the number of digits in the integer part of the number, one might use dZrX-. If you haven't changed the precision from the default k==0, using 1/Z is shorter, but suppose you need to maintain a particular non-zero precision after the operation: Kr0k1/Zrk is rather an eyesore.

z pushes the number of items on the stack. One of my favourite commands, it does not actually pop any values! It could be used to generate a sequence of numbers or increment a counter. Using zd repeatedly (say, at the start of a macro) could let one test a calculation on each natural or whole number in ascending order.

Title: Tips for golfing in dc

Body:
What general tips do you have for golfing in dc?

dc is a calculator utility for UNIX/Linux that predates the C language. I am interested in how to make my dc programs (calculations?) shorter. I'm looking for ideas that can be applied to general code-golf that are at least a little bit specific to dc (eg. removing comments is not a helpful answer)

Please post one tip per answer.


问:
ASCII Art Mayan Numerals
This challenge is simple.  Given a number, output a ascii-art representation of the number, using the Mayan Base-20 numeral system.

What is the Mayan system?

The Mayans used base 20 to store numbers, so the first position was the 1s place, the next the 20s place, then the 400s, etc.

So Mayan number 1 is 1 in base 10, but 10 is actually 20 in base 10, 207 is 807 in base 10, etc..

And they represented their numbers as pictographs, with a special symbol for 0.

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

That was their zero.  (at least the half picascii half my artisticness ascii art version)

That is a <s>real</s> picture of the mayan zero symbol.1

This was their five:

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

And a 4:

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

Finally, to put it together:

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

So they have x//5 bars, and x%5 dots on top of the bars.  And if x=0, they use the shell/loaf instead of a blank space.

For more images, try the Wikimedia Commons page of Maya number images.

But this is only for numbers up to 19. We aren't allowed to have more than 4 bars and 4 dots in a single 'story'... So we go up!

The output for 20 is:

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

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

Note this would normally be invalid, because is has a 1 and a 0 at the same time.  But the 3 (note that, your answer needs at least 3) newlines before the 0 mean a new place value.

The bottom story has dots, meaning 1, and bars meaning 5.  But it actually has dots meaning 20^0 and bars meaning 20^0 * 5.

Each story goes up a power.  The second story dots mean 20 (20^1) and 100 (20^1 * 5).

So the number 506 can be represented as:

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

--------------------------------
|                              |
--------------------------------

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

This is (20^0) * 1 + (20^0 * 5) * 1 + (20^1 * 5) * 1 + (20^2) * 1 = 1 + 5 + 100 + 400 = 506.

Your mission, should you choose not or choose to (it doesn't matter), is to output a ascii art representation of the base-10 number.

Other Rules:

Leading/trailing space is okay, as long as the dots, bars, and shells are intact.

The bars, dots, and shells must be exactly what the test cases have.  No resizing.

Leading '0's are okay. (leading shells on the output)

You don't have to have exactly 3 newlines between each place value or story, just at least 3.

Test Cases:

```<code>15

--------------------------------
|                              |
--------------------------------
--------------------------------
|                              |
--------------------------------
--------------------------------
|                              |
--------------------------------

12

 ----   ----
|    | |    |
|    | |    |
 ----   ----
--------------------------------
|                              |
--------------------------------
--------------------------------
|                              |
--------------------------------

4

 ----   ----   ----   ----
|    | |    | |    | |    |
|    | |    | |    | |    |
 ----   ----   ----   ----

0

 -------------------
|    |    |    |    |
|    |    |    |    |
|-------------------|
|                   |
|                   |
 -------------------

24

 ----
|    |
|    |
 ----

 ----   ----   ----   ----
|    | |    | |    | |    |
|    | |    | |    | |    |
 ----   ----   ----   ----

33

 ----
|    |
|    |
 ----

 ----   ----   ----
|    | |    | |    |
|    | |    | |    |
 ----   ----   ----
--------------------------------
|                              |
--------------------------------
--------------------------------
|                              |
--------------------------------

20

 ----
|    |
|    |
 ----

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

1: They also used the heads of gods for the symbols, but for this challenge the shell/bread/zelda chest will be used.

答:
Python 3, 243 bytes

```<code>s,v,h,x=' |-\n';P=print
t=s+h*19+s+x
def m(n):
 n//20and m(n//20);r=n%20
 if r:
  for a,b,f in[(r%5*' ----  ',r%5*'|    | ',1),('-'*32,'|'+' '*30+'|',r//5)]:P(*((a,b,b,a)*f),sep=x)
 else:P(t+2*(v+(4*s+v)*4+x)+v+h*19+v+x+2*(v+s*19+v+x)+t)
 P(x)
</code>```

Discussion

n//20and m(n//20) calls m() recursively if there are higher powers of 20 to be handled.  The recursion is done before printing the current place value, so that higher powers get printed first.

If the current place value is non-zero (r!=0), the for a,b,f-loop prints the units and then the fives.  a is the first/forth row and b is the second/third row. The trick is in the print(*((a,b,b,a)*f),sep=x).  For the units, f = 1 resulting in print(*(a,b,b,a),sep=x), which prints the 4 rows that make up the units symbols (x is a '\n').  For the fives, f = the number of fives to print (r//5), so the tuple (a,b,b,a) gets multiplied (i.e., repeated) by the number of fives to print. If f = 2, we get print(*(a,b,b,a,a,b,b,a),sep=x), which prints two symbols for five.

If the current place value is 0, then the zero symbol is printed.

Title: ASCII Art Mayan Numerals

Body:
Python 3, 243 bytes

s,v,h,x=' |-\n';P=print
t=s+h*19+s+x
def m(n):
 n//20and m(n//20);r=n%20
 if r:
  for a,b,f in[(r%5*' ----  ',r%5*'|    | ',1),('-'*32,'|'+' '*30+'|',r//5)]:P(*((a,b,b,a)*f),sep=x)
 else:P(t+2*(v+(4*s+v)*4+x)+v+h*19+v+x+2*(v+s*19+v+x)+t)
 P(x)

Discussion

n//20and m(n//20) calls m() recursively if there are higher powers of 20 to be handled.  The recursion is done before printing the current place value, so that higher powers get printed first.

If the current place value is non-zero (r!=0), the for a,b,f-loop prints the units and then the fives.  a is the first/forth row and b is the second/third row. The trick is in the print(*((a,b,b,a)*f),sep=x).  For the units, f = 1 resulting in print(*(a,b,b,a),sep=x), which prints the 4 rows that make up the units symbols (x is a '\n').  For the fives, f = the number of fives to print (r//5), so the tuple (a,b,b,a) gets multiplied (i.e., repeated) by the number of fives to print. If f = 2, we get print(*(a,b,b,a,a,b,b,a),sep=x), which prints two symbols for five.

If the current place value is 0, then the zero symbol is printed.


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

```<code>I.ịṚjI+2\H
</code>```

Try it online!

How it works

```<code>I.ịṚjI+2\H  Main link. Argument: A (array)

I           Increments; compute the deltas of consecutive values.
            For [a, b, c, d, e], this yields [b-a, c-b, d-c, e-d].
 .ị         At-index 0.5; get the the last and first element.
            This yields [e-d, b-a].
   Ṛ        Reverse the pair.
            This yields [b-a, e-d].
    jI      Join, separating by the increments.
            This yields [b-a, b-a, c-b, d-c, e-d, e-d].
      +2\   Add the values of all overlapping pairs.
            This yields [2(b-a), c-a, d-b, e-c, 2(e-d)].
         H  Halve all resulting numbers.
            This yields [b-a, (c-a)/2, (d-b)/2, (e-c)/2, e-d].
</code>```

Title: Derivative at the Edge

Body:
My preferred way to approximate a derivative is the central difference, its more accurate than forward difference or backward difference, and I'm too lazy to go higher-order. But the central difference requires a data point on either side of point you are evaluating. Normally this means you end up not having a derivative at either endpoint. To solve it, I want you to switch to forward and backward difference at the edges:

Specifically, I want you to use a forward difference for the first point, a backward difference for the last point, and a central difference for all the points in the middle. Also, you can assume x values are evenly spaced, and focus only on y. Use these formulas:

Good luck, I'm looking forward to seeing if someone comes up with a simple rule which reproduces all 3 derivatives in the right places!

EX INPUT:

```<code>0.034  9.62    8.885   3.477   2.38
</code>```

I will use FD, CD, and BD to denote which algorithm to use in which spot, so above 5 points are used to approximate derivatives using

```<code>FD     CD      CD      CD     BD
</code>```

And then the calculated values would be:

```<code>9.586  4.4255 -3.0715 -3.2525 -1.097
</code>```

You can assume that there will always be at least 3 input points, and you can calculate using single or double precision.

And as always, shortest answer wins.

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

I.ịṚjI+2\H

Try it online!

How it works

I.ịṚjI+2\H  Main link. Argument: A (array)

I           Increments; compute the deltas of consecutive values.
            For [a, b, c, d, e], this yields [b-a, c-b, d-c, e-d].
 .ị         At-index 0.5; get the the last and first element.
            This yields [e-d, b-a].
   Ṛ        Reverse the pair.
            This yields [b-a, e-d].
    jI      Join, separating by the increments.
            This yields [b-a, b-a, c-b, d-c, e-d, e-d].
      +2\   Add the values of all overlapping pairs.
            This yields [2(b-a), c-a, d-b, e-c, 2(e-d)].
         H  Halve all resulting numbers.
            This yields [b-a, (c-a)/2, (d-b)/2, (e-c)/2, e-d].