答:
Java, <s>422</s> 419 bytes:

```<code>import java.util.*;class A{static int[]P(int n){int[]U=new int[(int)Math.pow(2,n)];for(int i=0;i<U.length;i++){String Q=new String(Integer.toBinaryString(i));if(Q.length()<n){Q=new String(new char[n-Q.length()]).replace("\0","0")+Q;}U[i]=Integer.parseInt(new StringBuilder(Q).reverse().toString(),2);}return U;}public static void main(String[]a){System.out.print(Arrays.toString(P(new Scanner(System.in).nextInt())));}}
</code>```

Well, I finally learned Java for my second programming language, so I wanted to use my new skills to complete a simple challenge, and although it turned out very long, I am not disappointed. I am just glad I was able to complete a simple challenge in Java.

Try It Online! (Ideone)

Title: Bit-Reversal Permutations

Body:
Your goal is to create a function or a program to reverse the bits in a range of integers given an integer \$n\$. In other words, you want to find the bit-reversal permutation of a range of \$2^n\$ items, zero-indexed. This is also the OEIS sequence A030109. This process is often used in computing Fast Fourier Transforms, such as the in-place Cooley-Tukey algorithm for FFT. There is also a challenge for computing the FFT for sequences where the length is a power of 2.

This process requires you to iterate over the range \$[0, 2^n-1]\$, convert each value to binary and reverse the bits in that value. You will be treating each value as a \$n\$-digit number in base 2 which means reversal will only occur among the last \$n\$ bits.

For example, if \$n = 3\$, the range of integers is [0, 1, 2, 3, 4, 5, 6, 7]. These are

```<code>i  Regular  Bit-Reversed  j
0    000        000       0
1    001        100       4
2    010        010       2
3    011        110       6
4    100        001       1
5    101        101       5
6    110        011       3
7    111        111       7
</code>```

where each index \$i\$ is converted to an index \$j\$ using bit-reversal. This means that the output is [0, 4, 2, 6, 1, 5, 3, 7].

The output for \$n\$ from 0 thru 4 are

```<code>n    Bit-Reversed Permutation
0    [0]
1    [0, 1]
2    [0, 2, 1, 3]
3    [0, 4, 2, 6, 1, 5, 3, 7]
</code>```

You may have noticed a pattern forming. Given \$n\$, you can take the previous sequence for \$n-1\$ and double it. Then concatenate that doubled list to the same double list but incremented by one. To show,

```<code>[0, 2, 1, 3] * 2 = [0, 4, 2, 6]
[0, 4, 2, 6] + 1 = [1, 5, 3, 7]
[0, 4, 2, 6] ⊕ [1, 5, 3, 7] = [0, 4, 2, 6, 1, 5, 3, 7]
</code>```

where \$⊕\$ represents concatenation.

You can use either of the two methods above in order to form your solution. If you know a better way, you are free to use that too. Any method is fine as long as it outputs the correct results.

Rules

This is code-golf so the shortest solution wins.

Builtins that solve this challenge as a whole and builtins that compute the bit-reversal of a value are not allowed. This does not include builtins which perform binary conversion or other bitwise operations.

Your solution must be, at the least, valid for \$n\$ from 0 to 31.

Body:
Java, <s>422</s> 419 bytes:

import java.util.*;class A{static int[]P(int n){int[]U=new int[(int)Math.pow(2,n)];for(int i=0;i<U.length;i++){String Q=new String(Integer.toBinaryString(i));if(Q.length()<n){Q=new String(new char[n-Q.length()]).replace("\0","0")+Q;}U[i]=Integer.parseInt(new StringBuilder(Q).reverse().toString(),2);}return U;}public static void main(String[]a){System.out.print(Arrays.toString(P(new Scanner(System.in).nextInt())));}}

Well, I finally learned Java for my second programming language, so I wanted to use my new skills to complete a simple challenge, and although it turned out very long, I am not disappointed. I am just glad I was able to complete a simple challenge in Java.

Try It Online! (Ideone)


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

答:
Ruby, 29 bytes

Try it online

```<code>->s{i=0;s.gsub(/./){$&*i+=1}}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Write a program to elasticize strings

Body:
Ruby, 29 bytes

Try it online

->s{i=0;s.gsub(/./){$&*i+=1}}


问:
Decode a Microsoft MS-DOS 5.0 FAT directory entry
The Microsoft FAT file system has a directory table to represent which "files" are in which "folders" on the disk. For the time, these entries crammed a lot of information into a small amount of bits. There are a bunch of technical specifications over on Wiki for the curious, but the challenge here is going to focus on a "simple" decoding of an entry.

Each entry consists of a 32-byte binary word, broken up into several sections. For consistency in this challenge, we'll be using the MS-DOS 5.0 version, the bytes are ordered as big endian, and we're calling byte 0x00 as the left-most, and byte 0x1F as the right-most.

Below is a brief schematic of the relevant sections, and what should be the output for each section (in bold).

The first 11 bytes are the file name in ASCII format (this is where the famous 8.3 filename comes from -- 8 bytes for the file name, 3 bytes for the extension). These are straight ASCII encoding, and should be output as ASCII with a period (.) between.

Note: both the 8 and the 3 parts are padded with spaces to make a full-length entry. The output should ignore spaces (i.e., don't output them).

The file extension may be empty (i.e., all spaces), in which case the output should not output the dot.

Since ASCII only uses the lower 7 bits, the bytes will all have a leading 0.

The next byte (0x0b) is a bitmask of the following:

0x01 Read Only - output RO

0x02 Hidden - output H

0x04 System - output S

0x08 Volume Label - output VL. File size (below) should be output as 0, regardless of its actual entry.

0x10 Subdirectory - output SD. File size (below) should be output as 0, regardless of its actual entry.

0x20 Archive - output A

0x40 Device - ignored for this challenge.

0x80 Reserved - ignored for this challenge.

Since this is a bitmask, multiple flags are possible - all applicable outputs should be concatenated together in any order. For example, 0xff could be ROHSVLSDA (or any other combination).

The next two bytes (0x0c and 0x0d) are not used under MS-DOS 5.0.

The next two bytes (0x0e and 0x0f) are the creation time as follows:

Bits 15 to 11 are the hours in 24-hour format - output 00 to 23

Bits 10 to 5 are the minutes - output 00 to 59

Bits 4 to 0 are the seconds/2 - output 00 to 58 (note that seconds are only in two-second resolution)

For clarification: hhhhhmmmmmmsssss when written big-endian.

The next two bytes (0x10 and 0x11) are the creation date as follows:

Bits 15 to 9 are the year - output 1980 for 0 up to 2107 for 127

Bits 8 to 5 are the months - output 1 to 12 (with or without leading zero)

Bits 4 to 0 are the day - output 0 to 31 (with or without leading zero)

For clarification: yyyyyyymmmmddddd when written big-endian.

The next two bytes (0x12 and 0x13) are the last access date. While used in MS-DOS 5.0, we're ignoring this portion for this challenge.

The next two bytes (0x14 and 0x15) are not used by MS-DOS 5.0.

The next two bytes (0x16 and 0x17) are the last modified time, following the same format as the creation time, above.

The next two bytes (0x18 and 0x19) are the last modified date, following the same format as the creation date, above.

The next two bytes (0x1a and 0x1b) are the cluster location of the file on disk. We're ignoring this portion for this challenge.

The final four bytes (0x1c, 0x1d, 0x1e, and 0x1f) are the file size - output as an unsigned integer, unless the VL or SD flags are set (above), in which case output 0.

Visual representation

```<code>0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
\______________________________FILENAME________________________________________________/\_ATTR_/\___NOTUSED____/\_CREATIONTIME_/\_CREATIONDATE_/\__LASTACCESS__/\___NOTUSED____/\_MODIFIEDTIME_/\_MODIFIEDDATE_/\___NOTUSED____/\___________FILESIZE___________/
</code>```

Input

A single 32-byte word (i.e., 256 bits), in whatever format is convenient.

This could be as a string of 1 and 0, as several unsigned ints, an array of Boolean values, etc.

Please specify in your answer what format you're using for input.

You cannot take multiple input (i.e., an array pre-broken into the relevant byte sizes) unless that is the only way for your language to take input. Parsing the input is part of the challenge.

You can assume input to be valid (for example, you don't need to perform date checking to verify that the date is valid).

Bytes that are unused can be all 0, all 1, etc., just so long as they are present. In the below examples, I used all 0 for the unused bytes.

Output

Either printed to screen or returned, the following:

The filename as an ASCII string

The file attributes as an ASCII string

The creation time and creation date, with appropriate separators (colons, slashes, something to distinguish the components)

The modified time and modified date, again with appropriate separators

The file size

The output can be a space-separated or newline-separated single string, separate elements in an array, etc. Please specify in your answer how your output is formatted.

Rules

Standard I/O formats are acceptable.

Either a full program or a function are acceptable.

Standard loopholes are forbidden.

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

Built-ins that perform exactly this function are forbidden.

Examples

```<code>0111000001110010011011110110011101110010011000010110110101101101011010010110111001100111000001100000000000000000101000100100010001001000110101000000000000000000000000000000000010100010010001000100100011010100000000000000000000000000000000001101000000000000

programm.ing HS 20:18:08 2016/06/20 20:18:08 2016/06/20 53248

0010000000100000001000000010000001110000011100000110001101100111001000000010000000100000000101000000000000000000010111010110110000111101100111110000000000000000000000000000000010100010010001000100100011010100000000000000000011110000000100111111001011100001

ppcg SDS 11:43:24 2010/12/31 20:18:08 2016/06/20 0
</code>```

答:
Haskell, <s>781</s> 710 bytes

Thanks to BlackCap for some simplification

```<code>w n=('0'<$[1..2-length a])++a where a=show n
x s=tail.foldr(\a b->s:a++b)""
t=snd.span(==' ')
y a|all(==' ')a=""|0<1='.':t a
nm=(\(a,b)->t a++y b).splitAt 8
ms n(r,s)|n`mod`2^(r+1)`div`2^r>0=s|0<1=""
tm n=x ':'[w$n`div`2^11,w$n`mod`2^11`div`32,w$2*n`mod`64]
dt n=x '/'[w$1980+n`div`2^9,w$n`mod`2^9`div`32,w$n`mod`32]
pa s=x ' '[nm.map(toEnum.v.take 8).takeWhile(not.null)$iterate(drop 8)a,t,dt$v i,tm$v g,dt$v o,tm$v m,show u,"\n"]where{z n=splitAt(8*n);(a,b)=z 11 s;(c,d)=z 1 b;(e,f)=z 2 d;(g,h)=z 2 f;(i,j)=z 2 h;(k,l)=z 4 j;(m,n)=z 2 l;(o,p)=z 2 n;(q,r)=z 2 p;t=(zip [0..](words"RO H S VL SD A")>>=).ms$v c;u|any(`elem`t)"LD"=0|0<1=v r;v=foldl((+).(2*))0.map(read.pure).filter(`elem`"01")}
main=interact pa
</code>```

This additionally allows garbage (like a newline character) to appear after the input.

Body:
Haskell, <s>781</s> 710 bytes

Thanks to BlackCap for some simplification

w n=('0'<$[1..2-length a])++a where a=show n
x s=tail.foldr(\a b->s:a++b)""
t=snd.span(==' ')
y a|all(==' ')a=""|0<1='.':t a
nm=(\(a,b)->t a++y b).splitAt 8
ms n(r,s)|n`mod`2^(r+1)`div`2^r>0=s|0<1=""
tm n=x ':'[w$n`div`2^11,w$n`mod`2^11`div`32,w$2*n`mod`64]
dt n=x '/'[w$1980+n`div`2^9,w$n`mod`2^9`div`32,w$n`mod`32]
pa s=x ' '[nm.map(toEnum.v.take 8).takeWhile(not.null)$iterate(drop 8)a,t,dt$v i,tm$v g,dt$v o,tm$v m,show u,"\n"]where{z n=splitAt(8*n);(a,b)=z 11 s;(c,d)=z 1 b;(e,f)=z 2 d;(g,h)=z 2 f;(i,j)=z 2 h;(k,l)=z 4 j;(m,n)=z 2 l;(o,p)=z 2 n;(q,r)=z 2 p;t=(zip [0..](words"RO H S VL SD A")>>=).ms$v c;u|any(`elem`t)"LD"=0|0<1=v r;v=foldl((+).(2*))0.map(read.pure).filter(`elem`"01")}
main=interact pa

This additionally allows garbage (like a newline character) to appear after the input.


问:
Jordan Decomposition
Important note: Because this challenge only applies to square matrices, any time I use the term "matrix", it is assumed that I am referring to a square matrix. I am leaving off the "square" description for brevity's sake.

Background

Many matrix-related operations, such as computing the determinant, solving a linear system, or extending scalar-valued functions to matrices are made easier by using a diagonal matrix (one whose elements that are not on the main diagonal are 0) that is similar to the original matrix (meaning, for the input matrix A and the diagonal matrix D, there exists some invertible matrix P such that D = P^(-1) * A * P; also, D and A share some important properties, like eigenvalues, determinant, and trace). For matrices with distinct eigenvalues (the roots to the matrix's characteristic polynomial, given by solving det(A-λI) = 0 for λ, where I is the identity matrix with the same dimensions as A), diagonalization is simple: D is a matrix with the eigenvalues on the main diagonal, and P is a matrix formed from eigenvectors corresponding to those eigenvalues (in the same order). This process is called eigendecomposition.

However, matrices with repeated eigenvalues cannot be diagonalized in this manner. Luckily, the Jordan normal form of any matrix can be computed rather easily, and is not much harder to work with than a regular diagonal matrix. It also has the nice property that, if the eigenvalues are unique, then Jordan decomposition is identical to eigendecomposition.

Jordan decomposition explained

For a square matrix A whose eigenvalues all have a geometric multiplicity of 1, the process of Jordan decomposition can be described as such:

Let λ = {λ_1, λ_2, ... λ_n} be the list of eigenvalues of A, with multiplicity, with repeated eigenvalues appearing consecutively.

Create a diagonal matrix J whose elements are the elements of λ, in the same order.

For each eigenvalue with multiplicity greater than 1, place a 1 to the right of each of the repetitions of the eigenvalue in the main diagonal of J, except the last.

The resulting matrix J is a Jordan normal form of A (there can be multiple Jordan normal forms for a given matrix, depending on the order of the eigenvalues).

A worked example

Let A be the following matrix:

The eigenvalues of A, with multiplicity, are λ = {1, 2, 4, 4}. By putting these into a diagonal matrix, we get this result:

Next, we place 1s to the right of all but one of each of the repeated eigenvalues. Since 4 is the only repeated eigenvalue, we place a single 1 next to the first 4:

This is a Jordan normal form of A (a single matrix can potentially have several valid Jordan normal forms, but I'm glossing over that detail for the purpose of explanation).

The task

Given a square matrix A as input, output a valid Jordan normal form of A.

The input and output may be in any reasonable format (2D array/list/whatever, list/array/whatever of column or row vectors, a builtin matrix data type, etc.).

The elements and eigenvalues of A will always be integers in the range [-200, 200].

For the sake of simplicity, all of the eigenvalues will have a geometric multiplicity of 1 (and thus the above process holds).

A will at most be a 10x10 matrix and at least a 2x2 matrix.

Builtins that compute eigenvalues and/or eigenvectors or perform eigendecomposition, Jordan decomposition, or any other kind of decomposition/diagonalization are not allowed. Matrix arithmetic, matrix inversion, and other matrix builtins are allowed.

Test cases

```<code>[[1, 0], [0, 1]] -> [[1, 1], [0, 1]]
[[3, 0], [0, 3]] -> [[1, 1], [0, 1]]
[[4, 2, 2], [1, 2, 2],[0, 3, 3]] -> [[6, 0, 0], [0, 3, 0], [0, 0, 0]]
[[42, 48, 40, 64, 64], [41, 47, 31, 58, 42], [-55, -47, -27, -74, -46], [-46, -58, -46, -70, -68], [30, 20, 12, 34, 18]] -> [[10, 0, 0, 0, 0], [0, -18, 0, 0, 0], [0, 0, 6, 1, 0], [0, 0, 0, 6, 1], [0, 0, 0, 0, 6]]
</code>```

答:
Mathematica, <s>140</s> <s>139</s> 105 bytes

```<code>Total[DiagonalMatrix@@@{{#},{1-Sign[Differences@#^2],1}}]&@(x/.Solve[#~CharacteristicPolynomial~x==0,x])&
</code>```

I just found the builtin DiagonalMatrix which allows for an easy way to place the 0s and 1s along the superdiagonal.

Usage

Title: Jordan Decomposition

Body:
Mathematica, <s>140</s> <s>139</s> 105 bytes

Total[DiagonalMatrix@@@{{#},{1-Sign[Differences@#^2],1}}]&@(x/.Solve[#~CharacteristicPolynomial~x==0,x])&

I just found the builtin DiagonalMatrix which allows for an easy way to place the 0s and 1s along the superdiagonal.

Usage


答:
Pyke, 4 bytes

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

Try it here!

Title: Write a program to elasticize strings

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

Body:
Pyke, 4 bytes

Foh*

Try it here!


答:
Python 2.7 - 47 Bytes

```<code>''.join([s[i-1]*i for i in range(1, len(s)+1)])
</code>```

where 's' is the given string
Output:

```<code>welcome: weelllccccooooommmmmmeeeeeee
00004:   000000000044444
Why:     Whhyyy
SKype:   SKKyyyppppeeeee
A and B: A  aaannnnddddd      BBBBBBB
</code>```

Title: Write a program to elasticize strings

Body:
Python 2.7 - 47 Bytes

''.join([s[i-1]*i for i in range(1, len(s)+1)])

where 's' is the given string
Output:

welcome: weelllccccooooommmmmmeeeeeee
00004:   000000000044444
Why:     Whhyyy
SKype:   SKKyyyppppeeeee
A and B: A  aaannnnddddd      BBBBBBB


答:
VBA, 75 bytes

```<code>Function e(s):For a=1 To Len(s):e=e &String(a,Mid(s,a,1)):Next:End Function
</code>```

Call as e.g. a user function in a spreadsheet.

=e(A1)

```<code>┌─────────┬───────────────┐
│   SKype │SKKyyyppppeeeee│
└─────────┴───────────────┘
</code>```

It truncates if you feed it its own output a few times :-).

Title: Write a program to elasticize strings

Body:
VBA, 75 bytes

Function e(s):For a=1 To Len(s):e=e &String(a,Mid(s,a,1)):Next:End Function

Call as e.g. a user function in a spreadsheet.

=e(A1)

┌─────────┬───────────────┐
│   SKype │SKKyyyppppeeeee│
└─────────┴───────────────┘

It truncates if you feed it its own output a few times :-).


问:
Count, Replace, Add Up!

Definition

Define the nth term of the CRAU sequence as follows.

Begin with the singleton array A = [n].

Do the following n times:

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

Compute the sum of all integers in A.

For example, if n = 3, we start with the list [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].

The sum of the resulting integers is 15, so this is the third CRAU number.

Task

Write a program of a function that, given a strictly positive integer n as input, computes the nth term of the CRAU sequence.

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

Test cases

```<code> 1 ->       1
 2 ->       4
 3 ->      15
 4 ->      56
 5 ->     210
 6 ->     792
 7 ->    3003
 8 ->   11440
 9 ->   43758
10 ->  167960
11 ->  646646
12 -> 2496144
13 -> 9657700
</code>```

Related

Simplicial polytopic numbers

OEIS A001791: Binomial coefficients C(2n,n-1)

答:
Retina, 27 bytes

```<code>$
$.`$*
M!&+%`.+(?=1)|^.+
0
</code>```

Input in unary, using 0 as the unary digit.

Try it online!

Title: Count, Replace, Add Up!

Body:
Retina, 27 bytes

$
$.`$*
M!&+%`.+(?=1)|^.+
0

Input in unary, using 0 as the unary digit.

Try it online!


答:
MATL, 5 bytes

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

Try it online, or verify all test cases!

Explanation:

```<code>E       #Double the input
 Gq     #Push "input - 1"
   Xn   #Calculate "nchoosek" on the two numbers
</code>```

Title: Count, Replace, Add Up!

Body:
Definition

Define the nth term of the CRAU sequence as follows.

Begin with the singleton array A = [n].

Do the following n times:

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

Compute the sum of all integers in A.

For example, if n = 3, we start with the list [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].

The sum of the resulting integers is 15, so this is the third CRAU number.

Task

Write a program of a function that, given a strictly positive integer n as input, computes the nth term of the CRAU sequence.

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

Test cases

```<code> 1 ->       1
 2 ->       4
 3 ->      15
 4 ->      56
 5 ->     210
 6 ->     792
 7 ->    3003
 8 ->   11440
 9 ->   43758
10 ->  167960
11 ->  646646
12 -> 2496144
13 -> 9657700
</code>```

Related

Simplicial polytopic numbers

OEIS A001791: Binomial coefficients C(2n,n-1)

Body:
MATL, 5 bytes

EGqXn

Try it online, or verify all test cases!

Explanation:

E       #Double the input
 Gq     #Push "input - 1"
   Xn   #Calculate "nchoosek" on the two numbers


答:
Python, 65 bytes

def f(k):
 n,p=2*k,1
 for i in range(1,k):p=p*n//i;n-=1
 return p
```

Explanation: It's a simplified version of n choose k. See this sequence.

Title: Count, Replace, Add Up!

Body:
Python, 65 bytes

def f(k):
 n,p=2*k,1
 for i in range(1,k):p=p*n//i;n-=1
 return p

Explanation: It's a simplified version of n choose k. See this sequence.


答:
J, 5 bytes

```<code><:!+:
</code>```

Uses the binomial coefficient of (2n, n-1).

For 22 bytes, this is a possible solution based on using the process described in the challenge.

```<code>[:+/([:;<@(1+i.)"0)^:]
</code>```

Usage

Note: Extra commands used to format output for multiple input.

```<code>   f =: <:!+:
   (,.f"0) >: i. 13
 1       1
 2       4
 3      15
 4      56
 5     210
 6     792
 7    3003
 8   11440
 9   43758
10  167960
11  646646
12 2496144
13 9657700
</code>```

Explanation

```<code><:!+:  Input: n
   +:  Double the value of n to get 2*n
<:     Decrement n to get n-1
  !    Calculate the binomial coefficient of (2*n, n-1) and return

[:+/([:;<@(1+i.)"0)^:]  Input: n
                     ]  Identify function, gets the value n
    (     ...     )^:   Repeat the following n times with an initial value [n]
          (    )"0        Means rank 0, or to operate on each atom in the list
             i.           Create a range from 0 to that value, exclusive
           1+             Add 1 to each to make the range from 1 to that value
        <@                Box the value
     [:;                  Combine the boxes and unbox them to make a list and return
[:+/                    Sum the values in the list after n iterations and return
</code>```

Title: Count, Replace, Add Up!

Body:
J, 5 bytes

<:!+:

Uses the binomial coefficient of (2n, n-1).

For 22 bytes, this is a possible solution based on using the process described in the challenge.

[:+/([:;<@(1+i.)"0)^:]

Usage

Note: Extra commands used to format output for multiple input.

   f =: <:!+:
   (,.f"0) >: i. 13
 1       1
 2       4
 3      15
 4      56
 5     210
 6     792
 7    3003
 8   11440
 9   43758
10  167960
11  646646
12 2496144
13 9657700

Explanation

<:!+:  Input: n
   +:  Double the value of n to get 2*n
<:     Decrement n to get n-1
  !    Calculate the binomial coefficient of (2*n, n-1) and return

[:+/([:;<@(1+i.)"0)^:]  Input: n
                     ]  Identify function, gets the value n
    (     ...     )^:   Repeat the following n times with an initial value [n]
          (    )"0        Means rank 0, or to operate on each atom in the list
             i.           Create a range from 0 to that value, exclusive
           1+             Add 1 to each to make the range from 1 to that value
        <@                Box the value
     [:;                  Combine the boxes and unbox them to make a list and return
[:+/                    Sum the values in the list after n iterations and return


问:
Bit-Reversal Permutations
Your goal is to create a function or a program to reverse the bits in a range of integers given an integer \$n\$. In other words, you want to find the bit-reversal permutation of a range of \$2^n\$ items, zero-indexed. This is also the OEIS sequence A030109. This process is often used in computing Fast Fourier Transforms, such as the in-place Cooley-Tukey algorithm for FFT. There is also a challenge for computing the FFT for sequences where the length is a power of 2.

This process requires you to iterate over the range \$[0, 2^n-1]\$, convert each value to binary and reverse the bits in that value. You will be treating each value as a \$n\$-digit number in base 2 which means reversal will only occur among the last \$n\$ bits.

For example, if \$n = 3\$, the range of integers is [0, 1, 2, 3, 4, 5, 6, 7]. These are

```<code>i  Regular  Bit-Reversed  j
0    000        000       0
1    001        100       4
2    010        010       2
3    011        110       6
4    100        001       1
5    101        101       5
6    110        011       3
7    111        111       7
</code>```

where each index \$i\$ is converted to an index \$j\$ using bit-reversal. This means that the output is [0, 4, 2, 6, 1, 5, 3, 7].

The output for \$n\$ from 0 thru 4 are

```<code>n    Bit-Reversed Permutation
0    [0]
1    [0, 1]
2    [0, 2, 1, 3]
3    [0, 4, 2, 6, 1, 5, 3, 7]
</code>```

You may have noticed a pattern forming. Given \$n\$, you can take the previous sequence for \$n-1\$ and double it. Then concatenate that doubled list to the same double list but incremented by one. To show,

```<code>[0, 2, 1, 3] * 2 = [0, 4, 2, 6]
[0, 4, 2, 6] + 1 = [1, 5, 3, 7]
[0, 4, 2, 6] ⊕ [1, 5, 3, 7] = [0, 4, 2, 6, 1, 5, 3, 7]
</code>```

where \$⊕\$ represents concatenation.

You can use either of the two methods above in order to form your solution. If you know a better way, you are free to use that too. Any method is fine as long as it outputs the correct results.

Rules

This is code-golf so the shortest solution wins.

Builtins that solve this challenge as a whole and builtins that compute the bit-reversal of a value are not allowed. This does not include builtins which perform binary conversion or other bitwise operations.

Your solution must be, at the least, valid for \$n\$ from 0 to 31.

答:
JavaScript (Firefox 30-57), 48 bytes

```<code>f=n=>n?[for(x of[0,1])for(y of f(n-1))x+y+y]:[0]
</code>```

Port of @Dennis♦'s Python 2 solution.

ContentLicense: CC BY-SA 4.0

Title: Bit-Reversal Permutations

Body:
JavaScript (Firefox 30-57), 48 bytes

f=n=>n?[for(x of[0,1])for(y of f(n-1))x+y+y]:[0]

Port of @Dennis♦'s Python 2 solution.


答:
Retina, 22 bytes

Byte count assumes ISO 8859-1 encoding.

```<code>.
$&$.`$*·
+`(.)·
$1$1
</code>```

Try it online!

Basically, we insert the right amount of · as placeholders between the characters (since these extended ASCII characters can't appear in the input), then fill them up with the adjacent character in the second stage.

Title: Write a program to elasticize strings

Body:
Retina, 22 bytes

Byte count assumes ISO 8859-1 encoding.

.
$&$.`$*·
+`(.)·
$1$1

Try it online!

Basically, we insert the right amount of · as placeholders between the characters (since these extended ASCII characters can't appear in the input), then fill them up with the adjacent character in the second stage.


答:
Pyth, 8 bytes

```<code>usSMGQ]Q
</code>```

Try it online!

```<code>usSMGQ]Q   input as Q

u    Q     repeat for Q times,
      ]Q   starting as [Q]:

  SMG          convert each number in the array to its range
 s             flatten

           then implicitly prints the result.
</code>```

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:
Pyth, 8 bytes

usSMGQ]Q

Try it online!

usSMGQ]Q   input as Q

u    Q     repeat for Q times,
      ]Q   starting as [Q]:

  SMG          convert each number in the array to its range
 s             flatten

           then implicitly prints the result.


答:
Jelly, 7 bytes

Quick, before Dennis answers (jk)

```<code>WR€F$³¡
</code>```

Try it online!

```<code>WR€F$³¡  Main monadic chain. Argument: z

W        Yield [z].
     ³¡  Repeat the following z times:
 R€          Convert each number in the array to the corresponding range.
   F         Flatten the array.
</code>```

Title: Count Up, Replace, Repeat!

Body:
Jelly, 7 bytes

Quick, before Dennis answers (jk)

WR€F$³¡

Try it online!

WR€F$³¡  Main monadic chain. Argument: z

W        Yield [z].
     ³¡  Repeat the following z times:
 R€          Convert each number in the array to the corresponding range.
   F         Flatten the array.


答:
J, 18 bytes

```<code>([:;<@(1+i.)"0)^:]
</code>```

Straight-forward approach based on the process described in the challenge.

Usage

```<code>   f =: ([:;<@(1+i.)"0)^:]
   f 1
1
   f 2
1 1 2
   f 3
1 1 1 2 1 1 2 1 2 3
   f 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
</code>```

Explanation

```<code>([:;<@(1+i.)"0)^:]  Input: n
                 ]  Identity function, gets the value n
(     ...     )^:   Repeat the following n times with an initial value [n]
      (    )"0        Means rank 0, or to operate on each atom in the list
         i.           Create a range from 0 to that value, exclusive
       1+             Add 1 to each to make the range from 1 to that value
    <@                Box the value
 [:;                  Combine the boxes and unbox them to make a list and return
                    Return the final result after n iterations
</code>```

Title: Count Up, Replace, Repeat!

Body:
J, 18 bytes

([:;<@(1+i.)"0)^:]

Straight-forward approach based on the process described in the challenge.

Usage

   f =: ([:;<@(1+i.)"0)^:]
   f 1
1
   f 2
1 1 2
   f 3
1 1 1 2 1 1 2 1 2 3
   f 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

Explanation

([:;<@(1+i.)"0)^:]  Input: n
                 ]  Identity function, gets the value n
(     ...     )^:   Repeat the following n times with an initial value [n]
      (    )"0        Means rank 0, or to operate on each atom in the list
         i.           Create a range from 0 to that value, exclusive
       1+             Add 1 to each to make the range from 1 to that value
    <@                Box the value
 [:;                  Combine the boxes and unbox them to make a list and return
                    Return the final result after n iterations


答:
Retina, 33 bytes

```<code>$
$.`$*0
+%(M!&`1.*(?=0)|^.+
O`.+
</code>```

Input and output in unary.

Try it online!

Even though I didn't use the closed form for the related challenge, adapting this answer was surprisingly tricky.

Title: Count Up, Replace, Repeat!

Body:
Retina, 33 bytes

$
$.`$*0
+%(M!&`1.*(?=0)|^.+
O`.+

Input and output in unary.

Try it online!

Even though I didn't use the closed form for the related challenge, adapting this answer was surprisingly tricky.


答:
05AB1E, <s>6</s> 3 bytes

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

Explained

```<code>D     # duplicate input
 F    # input times do
  L   # range(1,N)
</code>```

Try it online

Saved 3 bytes thanks to @Adnan

Title: Count Up, Replace, Repeat!

Body:
05AB1E, <s>6</s> 3 bytes

DFL

Explained

D     # duplicate input
 F    # input times do
  L   # range(1,N)

Try it online

Saved 3 bytes thanks to @Adnan


答:
CJam, 14 bytes

```<code>{_a\{:,:~:)}*}
</code>```

Test it here.

Explanation

```<code>_a   e# Duplicate N and wrap it in an array.
\    e# Swap with other copy of N.
{    e# Do this N times...
  :, e#   Turn each x into [0 1 ... x-1].
  :~ e#   Unwrap each of those arrays.
  :) e#   Increment each element.
}*
</code>```

Title: Count Up, Replace, Repeat!

Body:
CJam, 14 bytes

{_a\{:,:~:)}*}

Test it here.

Explanation

_a   e# Duplicate N and wrap it in an array.
\    e# Swap with other copy of N.
{    e# Do this N times...
  :, e#   Turn each x into [0 1 ... x-1].
  :~ e#   Unwrap each of those arrays.
  :) e#   Increment each element.
}*


答:
Haskell, 33 bytes

f n=iterate(>>= \a->[1..a])[n]!!n
```
<p>Thanks to nimi for saving a byte.</p>
<p>A pointfree version is longer (35 bytes):</p>
<pre class="lang-haskell prettyprint-override"><code>(!!)=<<iterate(>>= \a->[1..a]).pure
</code>```

Title: Count Up, Replace, Repeat!

Body:
Haskell, 33 bytes

f n=iterate(>>= \a->[1..a])[n]!!n

Thanks to nimi for saving a byte.

A pointfree version is longer (35 bytes):

(!!)=<<iterate(>>= \a->[1..a]).pure


答:
Actually, 9 bytes

```<code>;#@`♂RΣ`n
</code>```

Try it online!

Explanation:

```<code>;#@`♂RΣ`n
;#@        dupe n, make a singleton list, swap with n
   `♂RΣ`n  call the following function n times:
    ♂R       range(1, k+1) for k in list
      Σ      concatenate the ranges
</code>```

Thanks to Leaky Nun for a byte, and inspiration for another 2 bytes.

Title: Count Up, Replace, Repeat!

Body:
Actually, 9 bytes

;#@`♂RΣ`n

Try it online!

Explanation:

;#@`♂RΣ`n
;#@        dupe n, make a singleton list, swap with n
   `♂RΣ`n  call the following function n times:
    ♂R       range(1, k+1) for k in list
      Σ      concatenate the ranges

Thanks to Leaky Nun for a byte, and inspiration for another 2 bytes.


答:
Mathematica, <s>27</s> 26 bytes

1 byte saved with some inspiration from Essari's answer.

```<code>Flatten@Nest[Range,{#},#]&
</code>```

Fairly straightforward: for input x we start with {x} and then apply the Range to it x times (Range is Listable which means that it automatically applies to the integers inside arbitrarily nested lists). At the end Flatten the result.

Title: Count Up, Replace, Repeat!

Body:
Mathematica, <s>27</s> 26 bytes

1 byte saved with some inspiration from Essari's answer.

Flatten@Nest[Range,{#},#]&

Fairly straightforward: for input x we start with {x} and then apply the Range to it x times (Range is Listable which means that it automatically applies to the integers inside arbitrarily nested lists). At the end Flatten the result.


答:
Python 3, <s>75</s> 74 bytes

def f(k):N=[k];exec('A=N;N=[]\nfor i in A:N+=range(1,i+1)\n'*k+'print(N)')
```

This is just a straightforward translation of the problem description to code.

Edit: Saved one byte thanks to @Dennis.

Title: Count Up, Replace, Repeat!

Body:
Python 3, <s>75</s> 74 bytes

def f(k):N=[k];exec('A=N;N=[]\nfor i in A:N+=range(1,i+1)\n'*k+'print(N)')

This is just a straightforward translation of the problem description to code.

Edit: Saved one byte thanks to @Dennis.


答:
Pyth, 8 bytes

```<code>iR2_M^U2
</code>```

Try it online: Demonstration or Test Suite

Explanation:

```<code>iR2_M^U2Q   implicit Q (=input number) at the end
     ^U2Q   generate all lists of zeros and ones of length Q in order
   _M       reverse each list
iR2         convert each list to a number
</code>```

Title: Bit-Reversal Permutations

Body:
Your goal is to create a function or a program to reverse the bits in a range of integers given an integer \$n\$. In other words, you want to find the bit-reversal permutation of a range of \$2^n\$ items, zero-indexed. This is also the OEIS sequence A030109. This process is often used in computing Fast Fourier Transforms, such as the in-place Cooley-Tukey algorithm for FFT. There is also a challenge for computing the FFT for sequences where the length is a power of 2.

This process requires you to iterate over the range \$[0, 2^n-1]\$, convert each value to binary and reverse the bits in that value. You will be treating each value as a \$n\$-digit number in base 2 which means reversal will only occur among the last \$n\$ bits.

For example, if \$n = 3\$, the range of integers is [0, 1, 2, 3, 4, 5, 6, 7]. These are

```<code>i  Regular  Bit-Reversed  j
0    000        000       0
1    001        100       4
2    010        010       2
3    011        110       6
4    100        001       1
5    101        101       5
6    110        011       3
7    111        111       7
</code>```

where each index \$i\$ is converted to an index \$j\$ using bit-reversal. This means that the output is [0, 4, 2, 6, 1, 5, 3, 7].

The output for \$n\$ from 0 thru 4 are

```<code>n    Bit-Reversed Permutation
0    [0]
1    [0, 1]
2    [0, 2, 1, 3]
3    [0, 4, 2, 6, 1, 5, 3, 7]
</code>```

You may have noticed a pattern forming. Given \$n\$, you can take the previous sequence for \$n-1\$ and double it. Then concatenate that doubled list to the same double list but incremented by one. To show,

```<code>[0, 2, 1, 3] * 2 = [0, 4, 2, 6]
[0, 4, 2, 6] + 1 = [1, 5, 3, 7]
[0, 4, 2, 6] ⊕ [1, 5, 3, 7] = [0, 4, 2, 6, 1, 5, 3, 7]
</code>```

where \$⊕\$ represents concatenation.

You can use either of the two methods above in order to form your solution. If you know a better way, you are free to use that too. Any method is fine as long as it outputs the correct results.

Rules

This is code-golf so the shortest solution wins.

Builtins that solve this challenge as a whole and builtins that compute the bit-reversal of a value are not allowed. This does not include builtins which perform binary conversion or other bitwise operations.

Your solution must be, at the least, valid for \$n\$ from 0 to 31.

Body:
Pyth, 8 bytes

iR2_M^U2

Try it online: Demonstration or Test Suite

Explanation:

iR2_M^U2Q   implicit Q (=input number) at the end
     ^U2Q   generate all lists of zeros and ones of length Q in order
   _M       reverse each list
iR2         convert each list to a number


答:
TSQL, 97 bytes

Golfed:

```<code>DECLARE @x varchar(max)='Lobby'
DECLARE @ int=LEN(@x)WHILE @>0SELECT
@x=STUFF(@x,@,1,REPLICATE(SUBSTRING(@x,@,1),@)),@-=1PRINT @x
</code>```

Ungolfed:

```<code>DECLARE @x varchar(max)='Lobby'

DECLARE @ int=LEN(@x)
WHILE @>0
  SELECT
    @x=STUFF(@x,@,1,REPLICATE(SUBSTRING(@x,@,1),@)),
    @-=1

PRINT @x
</code>```

Try it online

Title: Write a program to elasticize strings

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

Body:
TSQL, 97 bytes

Golfed:

DECLARE @x varchar(max)='Lobby'
DECLARE @ int=LEN(@x)WHILE @>0SELECT
@x=STUFF(@x,@,1,REPLICATE(SUBSTRING(@x,@,1),@)),@-=1PRINT @x

Ungolfed:

DECLARE @x varchar(max)='Lobby'

DECLARE @ int=LEN(@x)
WHILE @>0
  SELECT
    @x=STUFF(@x,@,1,REPLICATE(SUBSTRING(@x,@,1),@)),
    @-=1

PRINT @x

Try it online


问:
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, 15 bytes

```<code>;Zḟ€0;€-;@€-IFP
</code>```

Try it online!

```<code>;Zḟ€0;€-;@€-IFP   Main monadic chain. Argument: z

;Z                Concatenate with its transpose.
  ḟ€0             Remove zeros from each sub-list. At this point,
                  one expects lists of the form [1, -1, 1, -1, ..., 1] for truthy,
                  and any other arrays containing purely 1 and -1 for falsey.
     ;€-          Append -1 to each sub-list.
        ;€@-      Prepend -1 to each sub-list.
            I     Compute the difference between each term. At this point,
                  for truthy, one expects arrays filled with 2, and arrays
                  containing 0 otherwise.
             FP   Product of every item. This checks if any item is equal to zero.
</code>```

Title: Alternating sign matrix verification

Body:
Jelly, 15 bytes

;Zḟ€0;€-;@€-IFP

Try it online!

;Zḟ€0;€-;@€-IFP   Main monadic chain. Argument: z

;Z                Concatenate with its transpose.
  ḟ€0             Remove zeros from each sub-list. At this point,
                  one expects lists of the form [1, -1, 1, -1, ..., 1] for truthy,
                  and any other arrays containing purely 1 and -1 for falsey.
     ;€-          Append -1 to each sub-list.
        ;€@-      Prepend -1 to each sub-list.
            I     Compute the difference between each term. At this point,
                  for truthy, one expects arrays filled with 2, and arrays
                  containing 0 otherwise.
             FP   Product of every item. This checks if any item is equal to zero.


答:
Jelly, 3 bytes

```<code>R¡F
</code>```

Try it online

Explanation

```<code>R¡F    Argument n

R      Yield range [1..n]
 ¡     Repeat n times
  F    Flatten the result
</code>```

Title: Count Up, Replace, Repeat!

Body:
Jelly, 3 bytes

R¡F

Try it online

Explanation

R¡F    Argument n

R      Yield range [1..n]
 ¡     Repeat n times
  F    Flatten the result


答:
JavaScript (Firefox 30-57), <s>63</s> 60 bytes

```<code>f=n=>eval(`[${`for(n of Array(n+1).keys())`.repeat(n--)}n+1]`)
</code>```

Port of @xnor's Python answer.

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:
JavaScript (Firefox 30-57), <s>63</s> 60 bytes

f=n=>eval(`[${`for(n of Array(n+1).keys())`.repeat(n--)}n+1]`)

Port of @xnor's Python answer.


答:
Python 2, <s>69</s> <s>68</s> 66 bytes

```<code>def f(n):a=[n];exec'a=sum([range(1,i+1)for i in a],[]);'*n;print a
</code>```

Edit: Saved 1 byte thanks to @xnor. Saved 2 bytes thanks to @Dennis♦.

Title: Count Up, Replace, Repeat!

Body:
Python 2, <s>69</s> <s>68</s> 66 bytes

def f(n):a=[n];exec'a=sum([range(1,i+1)for i in a],[]);'*n;print a

Edit: Saved 1 byte thanks to @xnor. Saved 2 bytes thanks to @Dennis♦.


答:
Julia, 32 bytes

```<code>!s=join(split(s[k=1:end],"").^k)
</code>```

Unlike Dennis's solution, this is not recursive. split with argument "" separates the string into an array of strings of length 1. The [k=1:end] is a trick to create a range from 1 to the number of characters in the string, and this range is used to concatenate n copies of the n-th character. join then recombines the array of strings into a single string, in order.

Usage example: !"SKype"

Title: Write a program to elasticize strings

Body:
Julia, 32 bytes

!s=join(split(s[k=1:end],"").^k)

Unlike Dennis's solution, this is not recursive. split with argument "" separates the string into an array of strings of length 1. The [k=1:end] is a trick to create a range from 1 to the number of characters in the string, and this range is used to concatenate n copies of the n-th character. join then recombines the array of strings into a single string, in order.

Usage example: !"SKype"


答:
Python 2, 82 bytes

lambda n:[1+bin(i)[::-1].find('1')for i in range(1<<2*n-1)if bin(i).count('1')==n]
```

This isn't the shortest solution, but it illustrates an interesting method:

Write down the first 2^(2*n-1) numbers in binary

Keep those with exactly n ones

For each number, count the number of trailing zeroes, and add 1.

Title: Count Up, Replace, Repeat!

Body:
Python 2, 82 bytes

lambda n:[1+bin(i)[::-1].find('1')for i in range(1<<2*n-1)if bin(i).count('1')==n]

This isn't the shortest solution, but it illustrates an interesting method:

Write down the first 2^(2*n-1) numbers in binary

Keep those with exactly n ones

For each number, count the number of trailing zeroes, and add 1.


答:
Retina, <s>62</s> <s>58</s> <s>56</s> 53 bytes

Byte count assumes ISO 8859-1 encoding, and the \t should be replaced with actual tabs (0x09 which would be turned into spaces by SE otherwise).

```<code>$
\t$`¶
O$#`...(?<=^[^\t]*(.+))
$.1
T` 0
^(1(-11)*\s)+$
</code>```

Input format is a matrix where each column uses three right-aligned characters, e.g.:

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

Output is either 0 (falsy) or 1 (truthy).

Test suite. (The first few lines transform the input format and let Retina run several test cases at once.)

Explanation

Thankfully, the input is a square matrix: transposing squares is just about doable in Retina, whereas transposing rectangles is a massive pain.

```<code>$
\t$`¶
</code>```

We start by appending a tab, the entire input again (using the prefix $`) and then a linefeed at the end (using Retina's alias ¶). We're using a tab to separate the two copies so that we can distinguish between them when we're transposing one of them, and by using a whitespace character we can save a couple of bytes later on.

```<code>O$#`...(?<=^[^\t]*(.+))
$.1
</code>```

This is the trickiest bit: transposing the first copy of the matrix. The idea is to match cells in the first copy and then sorting them (stably) by the horizontal position. We match the cells with ... (since they're always three characters wide) and then measure the horizontal position with (.+) inside the lookbehind. Then, to make sure that we only transpose the first copy, we check that we can reach the beginning of the string without moving past a tab.

You might notice that this will also match some three-byte strings (that don't even align with the cells) in the first row of the second copy, because the .+ can pass through the tab. However, this is not an issue because the horizontal position of these matches is strictly greater than any inside the first copy, so these matches remain in their position.

The rest is fairly simple:

```<code>T` 0
</code>```

We remove spaces and zeros from the input.

```<code>^(1(-11)*\s)+$
</code>```

And finally we check that the entire input consists of whitespace-terminated rows of the form 1(-11)*, i.e. an alternating sequence of 1 and -1 that begins and ends with 1 (because otherwise it doesn't sum to 1).

Title: Alternating sign matrix verification

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

Body:
Retina, <s>62</s> <s>58</s> <s>56</s> 53 bytes

Byte count assumes ISO 8859-1 encoding, and the \t should be replaced with actual tabs (0x09 which would be turned into spaces by SE otherwise).

$
\t$`¶
O$#`...(?<=^[^\t]*(.+))
$.1
T` 0
^(1(-11)*\s)+$

Input format is a matrix where each column uses three right-aligned characters, e.g.:

  0  0  1  0
  1  0 -1  1
  0  1  0  0
  0  0  1  0

Output is either 0 (falsy) or 1 (truthy).

<a href="http://retina.tryitonline.net/#code=JShTYF0sXFsKW11bXQoKKD88IS0pXGQKICQmCi0_XGQKICQmCiwKCiQKCSRgwrYKTyQjYC4uLig_PD1eW14JXSooLispKQokLjEKVGAgMApeKDEoLTExKSpccykrJA&input=W1sxXV0KW1sxLDBdLFswLDFdXQpbWzAsMV0sWzEsMF1dCltbMCwxLDBdLFswLDAsMV0sWzEsMCwwXV0KW1swLDEsMF0sWzEsLTEsMV0sWzAsMSwwXV0KW1swLDEsMCwwXSxbMCwwLDEsMF0sWzEsMCwwLDBdLFswLDAsMCwxXV0KW1sxLDAsMCwwXSxbMCwwLDEsMF0sWzAsMSwtMSwxXSxbMCwwLDEsMF1dCltbMCwwLDEsMF0sWzAsMSwtMSwxXSxbMSwtMSwxLDBdLFswLDEsMCwwXV0KW1swLDAsMSwwXSxbMSwwLC0xLDFdLFswLDEsMCwwXSxbMCwwLDEsMF1dCltbMCwwLDEsMCwwXSxbMCwxLC0xLDEsMF0sWzEsLTEsMSwwLDBdLFswLDEsMCwtMSwxXSxbMCwwLDAsMSwwXV0KW1swLDAsMSwwLDAsMCwwLDBdLFsxLDAsLTEsMCwxLDAsMCwwXSxbMCwwLDAsMSwtMSwwLDAsMV0sWzAsMCwxLC0xLDEsMCwwLDBdLFswLDAsMCwwLDAsMCwxLDBdLFswLDAsMCwwLDAsMSwwLDBdLFswLDEsLTEsMSwwLDAsMCwwXSxbMCwwLDEsMCwwLDAsMCwwXV0KW1swLDAsMCwwLDEsMCwwLDBdLFswLDAsMSwwLC0xLDEsMCwwXSxbMCwwLDAsMSwwLDAsMCwwXSxbMSwwLDAsLTEsMSwtMSwxLDBdLFswLDEsLTEsMSwtMSwxLDAsMF0sWzAsMCwwLDAsMSwwLDAsMF0sWzAsMCwxLDAsMCwwLDAsMCwwXSxbMCwwLDAsMCwwLDAsMCwxXV0KW1swXV0KW1stMV1dCltbMCwwLDBdLFswLDAsMF0sWzAsMCwwXV0KW1swLDEsMF0sWzEsMCwxXSxbMCwxLDBdXQpbWy0xLDEsMV0sWzEsLTEsMV0sWzEsMSwtMV1dCltbMCwwLDFdLFsxLDAsMF0sWzAsMSwtMV1dCltbMCwwLDEsMCwwXSxbMCwxLC0xLDEsMF0sWzEsLTEsMSwwLDBdLFswLDEsMSwtMSwwXSxbMCwwLC0xLDEsMV1dCltbMCwtMSwwLDEsMV0sWzEsLTEsMSwtMSwxXSxbMCwxLDEsMCwtMV0sWzEsMSwtMSwxLC0xXSxbLTEsMSwwLDAsMV1dCltbMCwwLDEsMCwwLDAsMCwwXSxbMSwwLDEsMCwxLDAsMCwwXSxbMCwwLDAsMSwtMSwwLDAsMV0sWzAsMCwxLC0xLDEsMCwwLDBdLFswLDAsMCwwLDAsMCwxLDBdLFswLDAsMCwwLDAsMSwwLDBdLFswLDEsLTEsMSwwLDAsMCwwXSxbMCwwLDEsMCwwLDAsMCwwXV0" rel="nofollow">Test suite. (The first few lines transform the input format and let Retina run several test cases at once.)

Explanation

Thankfully, the input is a square matrix: transposing squares is just about doable in Retina, whereas transposing rectangles is a massive pain.

$
\t$`¶

We start by appending a tab, the entire input again (using the prefix $`) and then a linefeed at the end (using Retina's alias ¶). We're using a tab to separate the two copies so that we can distinguish between them when we're transposing one of them, and by using a whitespace character we can save a couple of bytes later on.

O$#`...(?<=^[^\t]*(.+))
$.1

This is the trickiest bit: transposing the first copy of the matrix. The idea is to match cells in the first copy and then sorting them (stably) by the horizontal position. We match the cells with ... (since they're always three characters wide) and then measure the horizontal position with (.+) inside the lookbehind. Then, to make sure that we only transpose the first copy, we check that we can reach the beginning of the string without moving past a tab.

You might notice that this will also match some three-byte strings (that don't even align with the cells) in the first row of the second copy, because the .+ can pass through the tab. However, this is not an issue because the horizontal position of these matches is strictly greater than any inside the first copy, so these matches remain in their position.

The rest is fairly simple:

T` 0

We remove spaces and zeros from the input.

^(1(-11)*\s)+$

And finally we check that the entire input consists of whitespace-terminated rows of the form 1(-11)*, i.e. an alternating sequence of 1 and -1 that begins and ends with 1 (because otherwise it doesn't sum to 1).


答:
Python, 50 bytes

lambda i:eval("[i "+"for i in range(1,i+1)"*i+"]")
```

<p>Scope abuse! For example, for <code>i=3</code>, the string to be evaluated expands to. </p>

<pre class="lang-python prettyprint-override"><code>[i for i in range(1,i+1)for i in range(1,i+1)for i in range(1,i+1)]
</code>```

Somehow, despite using the function input variable i for everything, Python distinguishes each iteration index as belonging to a separate scope as if the expression were

[l for j in range(1,i+1)for k in range(1,j+1)for l in range(1,k+1)]
```

with i the input to the function.

Title: Count Up, Replace, Repeat!

Body:
Python, 50 bytes

lambda i:eval("[i "+"for i in range(1,i+1)"*i+"]")

Scope abuse! For example, for i=3, the string to be evaluated expands to.

[i for i in range(1,i+1)for i in range(1,i+1)for i in range(1,i+1)]

Somehow, despite using the function input variable i for everything, Python distinguishes each iteration index as belonging to a separate scope as if the expression were

[l for j in range(1,i+1)for k in range(1,j+1)for l in range(1,k+1)]

with i the input to the function.


答:
Mathematica, 46 bytes

```<code>""<>Table@@@(#^Range@Length@#&@Characters[#])&
</code>```

Unnamed function. Takes the characters of the input string and raises them to the power of their position in the string (i.e. "abc" becomes {"a"^1, "b"^2, "c"^3}). Yes, MMA don't give a shit 'bout types :-)

The FullForm of the above list elements is Power["a", 1], etc.

Table@@@ acts on the list, replacing the head of each element (in this case Power) with Table.

Results in {Table["a"], Table["b", 2], Table["c", 3]} (because "a"^1 -> "a").

This evaluates to {"a", {"b", "b"}, {"c", "c", "c"}} Finally the infix concatenation operator <> concatenates this with the empty string.

I exploited the fact that Power is Listable, i.e. it automatically threads over corresponding elements of lists, but not orderless (because "a" + 1 would evaluate to Plus[1, "a"]).

Title: Write a program to elasticize strings

Body:
Mathematica, 46 bytes

""<>Table@@@(#^Range@Length@#&@Characters[#])&

Unnamed function. Takes the characters of the input string and raises them to the power of their position in the string (i.e. "abc" becomes {"a"^1, "b"^2, "c"^3}). Yes, MMA don't give a shit 'bout types :-)

The FullForm of the above list elements is Power["a", 1], etc.

Table@@@ acts on the list, replacing the head of each element (in this case Power) with Table.

Results in {Table["a"], Table["b", 2], Table["c", 3]} (because "a"^1 -> "a").

This evaluates to {"a", {"b", "b"}, {"c", "c", "c"}} Finally the infix concatenation operator <> concatenates this with the empty string.

I exploited the fact that Power is Listable, i.e. it automatically threads over corresponding elements of lists, but not orderless (because "a" + 1 would evaluate to Plus[1, "a"]).


答:
JavaScript (ES6), <s>112</s> 100 bytes

```<code>a=>!/(^|,)(?!0*10*(-10*10*)*(,|$))/.test(a.map(b=>b.join``)+','+a.map((_,i)=>a.map(b=>b[i]).join``))
</code>```

Flattens the array and its transpose into strings, then (ignoring 0s) checks for the pattern 1-11...1-11 in each string.

Edit: Saved 12 bytes thanks to @PeterTaylor.

Title: Alternating sign matrix verification

Body:
JavaScript (ES6), <s>112</s> 100 bytes

a=>!/(^|,)(?!0*10*(-10*10*)*(,|$))/.test(a.map(b=>b.join``)+','+a.map((_,i)=>a.map(b=>b[i]).join``))

Flattens the array and its transpose into strings, then (ignoring 0s) checks for the pattern 1-11...1-11 in each string.

Edit: Saved 12 bytes thanks to @PeterTaylor.


答:
Pyth, 16 bytes

```<code>!sm-sM._+d_1U2+C
</code>```

Try it online: Demonstration or Test Suite

Explanation:

```<code>!sm-sM._+d_1U2+CQQ   two implicit Qs (=input matrix) at the end
              +CQQ   zip Q and connect it with Q (=list of columns and rows)
  m                  map each column/row d to:
        +d_1            append -1 to d
      ._                compute all prefixes of ^
    sM                  compute the sums of the prefixes
   -        U2          remove zeros and ones
                        a column/row is correct, if this gives an empty list
 s                   connect up all resulting lists
!                    check, if this result is empty
</code>```

Title: Alternating sign matrix verification


答:
C#, 128 Bytes

```<code>List<int>j(int n){var l=new List<int>(){n};for(;n>0;n--)l=l.Select(p=>Enumerable.Range(1,p)).SelectMany(m=>m).ToList();return l;
</code>```

Title: Count Up, Replace, Repeat!

Body:
C#, 128 Bytes

List<int>j(int n){var l=new List<int>(){n};for(;n>0;n--)l=l.Select(p=>Enumerable.Range(1,p)).SelectMany(m=>m).ToList();return l;


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

答:
Web page (840/796 characters)

>>> Start playing (Internet Explorer is not supported for multiple reasons; Google Chrome and Opera work best.)

I probably could make this a bit shorter, yet it is a good start. The lower score is after replacing all occurrences of   with the character itself and removing the keyword new, the latter change breaking Google Chrome compatibility.

```<code><style>table{border-collapse:collapse;border-width:1 0;border-style:solid;font-size:64;line-height:2}td{border-style:solid;border-width:0 1}</style><table><td colspan=3 title=0> <td bgcolor=black colspan=2 title=1> <td colspan=2 title=2> <td bgcolor=black colspan=2 title=3> <td colspan=3 title=4> <tr><td colspan=4 title=0> <td colspan=4 title=2> <td colspan=4 title=4> </table><script>for(A=[y=5];y--;){for(s=x=64e3;x--;)s+="~ "[x*(268+17*y)>>13&1];A[y]=new Audio("data:audio/wav;base64,UklGRiXuAgBXQVZFZm10IBAAAAABAAEAQB8AAEAfAAABAAgAZGF0YQHuAgCA"+btoa(s))}setInterval("for(y=5;y--;)with(A[y])volume=volume&&Math.exp(-currentTime)",99);onmousedown=function(e){if(z=e.target.title)with(A[z])play(currentTime=0,volume=1)};onmouseup=function(e){if(z=e.target.title)with(A[z])pause(volume=0)}</script>
</code>```

Save this code as a text file with a name ending in .htm or .html and open it in Chrome or Opera (Safari might also work), or just open the solution's JSBin page to start playing. I reused the WAV file header from my solution to the Twinkle Twinkle Little Star code golf problem.

An important feature is that the sound diminishes as time passes. To observe this behavior, try holding down a key for a few seconds and listening to what happens.

Here is a more readable version of the code:

```<code><style>
    table {
        border-collapse: collapse;
        border-width: 1 0;
        border-style: solid;
        font-size: 64;
        line-height: 2;
    }

    td {
        border-style: solid;
        border-width: 0 1;
    }
</style>

<table>
        <td colspan=3 title=0>
        <td bgcolor=black colspan=2 title=1>
        <td colspan=2 title=2>
        <td bgcolor=black colspan=2 title=3>
        <td colspan=3 title=4>
    <tr>
        <td colspan=4 title=0>
        <td colspan=4 title=2>
        <td colspan=4 title=4>
</table>

<script>
    for (A = [y = 5]; y--;) {

        for (s = x = 64e3; x--;)
            s += "~ "[x * (268 + 17 * y) >> 13 & 1];

        A[y] = new Audio("data:audio/wav;base64,UklGRiXuAgBXQVZFZm10IBAAAAABAAEAQB8AAEAfAAABAAgAZGF0YQHuAgCA" + btoa(s));
    }

    setInterval(function() {
        for (y = 5; y--;)
            with (A[y])
                volume = volume && Math.exp(-currentTime);
    }, 99);

    onmousedown = function(e) {
        if (z = e.target.title)
            with (A[z])
                play(currentTime = 0, volume = 1);
    };

    onmouseup = function(e) {
        if (z = e.target.title)
            with (A[z])
                pause(volume = 0);
    };
</script>
</code>```

Title: Create a GUI Piano

Body:
Web page (840/796 characters)

>>> Start playing (Internet Explorer is not supported for multiple reasons; Google Chrome and Opera work best.)

I probably could make this a bit shorter, yet it is a good start. The lower score is after replacing all occurrences of &nbsp; with the character itself and removing the keyword new, the latter change breaking Google Chrome compatibility.

<style>table{border-collapse:collapse;border-width:1 0;border-style:solid;font-size:64;line-height:2}td{border-style:solid;border-width:0 1}</style><table><td colspan=3 title=0>&nbsp;<td bgcolor=black colspan=2 title=1>&nbsp;<td colspan=2 title=2>&nbsp;<td bgcolor=black colspan=2 title=3>&nbsp;<td colspan=3 title=4>&nbsp;<tr><td colspan=4 title=0>&nbsp;<td colspan=4 title=2>&nbsp;<td colspan=4 title=4>&nbsp;</table><script>for(A=[y=5];y--;){for(s=x=64e3;x--;)s+="~ "[x*(268+17*y)>>13&1];A[y]=new Audio("data:audio/wav;base64,UklGRiXuAgBXQVZFZm10IBAAAAABAAEAQB8AAEAfAAABAAgAZGF0YQHuAgCA"+btoa(s))}setInterval("for(y=5;y--;)with(A[y])volume=volume&&Math.exp(-currentTime)",99);onmousedown=function(e){if(z=e.target.title)with(A[z])play(currentTime=0,volume=1)};onmouseup=function(e){if(z=e.target.title)with(A[z])pause(volume=0)}</script>

Save this code as a text file with a name ending in .htm or .html and open it in Chrome or Opera (Safari might also work), or just open the solution's JSBin page to start playing. I reused the WAV file header from my solution to the Twinkle Twinkle Little Star code golf problem.

An important feature is that the sound diminishes as time passes. To observe this behavior, try holding down a key for a few seconds and listening to what happens.

Here is a more readable version of the code:

<style>
    table {
        border-collapse: collapse;
        border-width: 1 0;
        border-style: solid;
        font-size: 64;
        line-height: 2;
    }

    td {
        border-style: solid;
        border-width: 0 1;
    }
</style>

<table>
        <td colspan=3 title=0>&nbsp;
        <td bgcolor=black colspan=2 title=1>&nbsp;
        <td colspan=2 title=2>&nbsp;
        <td bgcolor=black colspan=2 title=3>&nbsp;
        <td colspan=3 title=4>&nbsp;
    <tr>
        <td colspan=4 title=0>&nbsp;
        <td colspan=4 title=2>&nbsp;
        <td colspan=4 title=4>&nbsp;
</table>

<script>
    for (A = [y = 5]; y--;) {

        for (s = x = 64e3; x--;)
            s += "~ "[x * (268 + 17 * y) >> 13 & 1];

        A[y] = new Audio("data:audio/wav;base64,UklGRiXuAgBXQVZFZm10IBAAAAABAAEAQB8AAEAfAAABAAgAZGF0YQHuAgCA" + btoa(s));
    }

    setInterval(function() {
        for (y = 5; y--;)
            with (A[y])
                volume = volume && Math.exp(-currentTime);
    }, 99);

    onmousedown = function(e) {
        if (z = e.target.title)
            with (A[z])
                play(currentTime = 0, volume = 1);
    };

    onmouseup = function(e) {
        if (z = e.target.title)
            with (A[z])
                pause(volume = 0);
    };
</script>


答:
LINQPad w/ C#, 82 bytes

```<code>void m(string s){Console.Write(s.SelectMany((x,i)=>new string(x,++i)).ToArray());}
</code>```

Single output operation.

Title: Write a program to elasticize strings

Body:
LINQPad w/ C#, 82 bytes

void m(string s){Console.Write(s.SelectMany((x,i)=>new string(x,++i)).ToArray());}

Single output operation.


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

答:
When you have a method that should return a boolean or Boolean, i.e.:

// Return true if the (non-negative) input is dividable by 5
boolean c(int i){return i%5<1;}
```

<p>You can change the <code>boolean</code>/<code>Boolean</code> return-type to <code>Object</code> to save 1 byte:</p>

<pre class="lang-java prettyprint-override"><code>Object c(int i){return i%5<1;}
</code>```

In addition, as you may have noticed, you can use a <1 check instead of ==0 to save a byte. Although that is more a general code-golf tip instead of Java-specific.

This is mostly used when the integer can't be negative, like checking for length:

a.length<1
```

<p>instead of</p>

<pre class="lang-java prettyprint-override"><code>a.length==0
</code>```

Title: Tips for golfing in Java

Body:
When you have a method that should return a boolean or Boolean, i.e.:

// Return true if the (non-negative) input is dividable by 5
boolean c(int i){return i%5<1;}

You can change the boolean/Boolean return-type to Object to save 1 byte:

Object c(int i){return i%5<1;}

In addition, as you may have noticed, you can use a <1 check instead of ==0 to save a byte. Although that is more a general code-golf tip instead of Java-specific.

This is mostly used when the integer can't be negative, like checking for length:

a.length<1

instead of

a.length==0


答:
Oracle SQL 11.2, 125 bytes

SELECT LISTAGG(SUBSTR(RPAD(' ',LEVEL+1,SUBSTR(:1,LEVEL,1)),2))WITHIN GROUP(ORDER BY 1)FROM DUAL CONNECT BY LEVEL<=LENGTH(:1);
```

Title: Write a program to elasticize strings

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


问:
Downward Number Race
Your task is to create a program that adds random numbers to previous sums in the ultimate number racing showdown.

Each racer (column) starts at 0 and adds either 1 or 0 to the previous sum at each step of the race until all of the racers reach the score required to win. The 1 or 0 should be chosen at random (the standard definition of random can be found here). The output will show the result of the race, with each column representing one racer, in this format:

```<code>>> racers:5,score needed:2

0 0 0 0 0 # all racers start at 0
+ + + + + # add
1 0 0 0 1 # random 1 or 0
= = = = = # equals
1 0 0 0 1 # sum
+ + + + +
0 0 0 0 1
= = = = =
1 0 0 0 2 # winner!
+ + + +
1 1 1 1
= = = =
2 1 1 1
  + + +
  1 1 1
  = = =
  2 2 2   # losers
</code>```

Note: only the numbers, +, and = need to be included in the output.

Input

Your program will accept the following two parameters as input:

the number of racers (columns), which must be greater than two

the score required to win, which must be greater than one

This is code-golf--the program with the least bytes wins.

Edit: there's a non-enforceable max score of 9--this is to preserve the integrity of the column. Also, spaces between columns can be omitted in the output.

答:
Pyth, <s>38</s> 34 bytes

```
<s>j.tm+j\=jL\+C,.u+NYJ.WnsHQ+ZO2Y0J+\=QE</s>
j.tmj\=jL\+.T,.u+NYJ.WnsHQ+ZO2Y0JE
```

Try it online!

Title: Downward Number Race

Body:
Pyth, <s>38</s> 34 bytes

<s>j.tm+j\=jL\+C,.u+NYJ.WnsHQ+ZO2Y0J+\=QE</s>
j.tmj\=jL\+.T,.u+NYJ.WnsHQ+ZO2Y0JE

Try it online!


答:
R, <s>60</s> 49 bytes

Pretty straightforward use of unlist and sapply.

```<code>y=x=scan();for(i in 1:x)y=unlist(sapply(y,seq));y
</code>```

Thanks to @MickyT for saving 11 bytes

Title: Count Up, Replace, Repeat!

Body:
R, <s>60</s> 49 bytes

Pretty straightforward use of unlist and sapply.

y=x=scan();for(i in 1:x)y=unlist(sapply(y,seq));y

Thanks to @MickyT for saving 11 bytes


问:
Count up forever
Write a program that counts up forever, starting from one.

Rules:

Your program must log to STDOUT or an acceptable alternative, if STDOUT is not available.

Your program must be a full, runnable program, and not a function or snippet.

Your program must output each number with a separating character in between (a newline, space, tab or comma), but this must be consistent for all numbers.

You may print the numbers in decimal, in unary or in base 256 where each digit is represented by a byte value.

Your program must count at least as far as 2128 (inclusive) without problems and without running out of memory on a reasonable desktop PC. In particular, this means if you're using unary, you cannot store a unary representation of the current number in memory.

Unlike our usual rules, feel free to use a language (or language version) even if it's newer than this challenge. Languages specifically written to submit a 0-byte answer to this challenge are fair game but not particularly interesting.

Note that there must be an interpreter so the submission can be tested. It is allowed (and even encouraged) to write this interpreter yourself for a previously unimplemented language.

This is not about finding the language with the shortest solution for this (there are some where the empty program does the trick) - this is about finding the shortest solution in every language. Therefore, no answer will be marked as accepted.

Catalogue

The Stack Snippet at the bottom of this post generates the catalogue from the answers a) as a list of shortest solution per language and b) as an overall leaderboard.

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 snippet:

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

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

Shortest Solution by Language

Language	User	Score

Leaderboard

	Author	Language	Size

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

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

```

答:
Oracle SQL, 42 Bytes

```<code>select level from t connect by level=level
</code>```

Title: Count up forever

Body:
Oracle SQL, 42 Bytes

select level from t connect by level=level


Title: Create a GUI Piano

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

Body:
Mathematica 319 259 255

Edit:
Keys now depress (as buttons) when clicked.

This will play the grand piano notes {"C","C#","D","D#","E"}, where "C" is middle C.  z[n_] plays the note.

z@n_ := EmitSound@Sound[SoundNote[n, .3, 1]]; w = {10, 300}; b = {35, 180};
Graphics[Inset[Button["", z[#[[1]]], Background -> If[#[[2]] == w, None, Black],
ImageSize -> #〚2〛], #〚3〛] & /@ {{"C", w, {-.4, 0}}, {"D", w, {0, 0}}, {"E", w, {.4, 0}},
{"C#", b, {-.2, 0.31}}, {"D#", b, {.2, 0.31}}}, PlotRange -> 1]

The keyboard can be extended to 18-keys by using fewer than double the characters:

z@n_ := EmitSound@Sound@SoundNote[n, .3, 1];
w = {"C", "D", "E", "F", "G", "A", "B", "C5", "D5", "E5", "F5"};
b = {"C#", "D#", "", "F#", "G#", "A#", "", "C#5", "D#5"}; i = ImageSize; t = Thread;
l = List; s = Inset; m = Table; u = Button;
Graphics[Join[t[s[u @@@ t[l["", y /@ w, i -> {5, 350}]] /. y -> z, m[{90 k, 0}, {k, -5, 5}]]],
Delete[t[s[u @@@ t[l["", y /@ b, Background -> Black, i -> {28, 212}]] /.
  y -> z, m[{90 k + 45, 220}, {k, -5, 3}]]], {{3}, {7}}]],
AspectRatio -> .45, PlotRange -> {{-500, 500}, {-610, 610}}, i -> {800, 430}]


答:
MATL, <s>18</s> <s>16</s> <s>15</s> 13 bytes

3 bytes saved thanks to @Luis

```<code>t!h"@s1=@Xzdv
</code>```

This solution accepts a 2D array as input and will output a truthy or falsey array. It is important to note that in MATL, a truthy array is composed of all non-zero elements while a falsey result has at least one zero element. Here is another demonstration of truthy/falsey arrays.

Try it Online

Modified version to show all test cases

Explanation

```<code>        % Implicitly grab input matrix
t!      % Duplicate and transpose input
h       % Horizontally concatenate input with transpose. This allows us to
        % process only columns since now the columns *also* contain the rows.
"       % For each column (of our column/row combined matrix)
  @s1=  % Compute the sum and ensure it is equal to 1
  @Xz   % Get the non-zeros
  d     % Compute the element-to-element difference. The 1 and -1 alternate only if
        % all these differences are non-zero
  v     % Vertically concatenate everything on the stack
        % Implicit end of loop and implicitly display truthy/falsey value
</code>```

Title: Alternating sign matrix verification

Body:
MATL, <s>18</s> <s>16</s> <s>15</s> 13 bytes

3 bytes saved thanks to @Luis

t!h"@s1=@Xzdv

This solution accepts a 2D array as input and will output a truthy or falsey array. It is important to note that in MATL, a truthy array is composed of all non-zero elements while a falsey result has at least one zero element. Here is another demonstration of truthy/falsey arrays.

Try it Online

<a href="http://matl.tryitonline.net/#code=YHQhaCJAczE9QFh6ZHZBXURUXQ&input=MQpbMSwwOyAwLDFdClswLDE7IDEsMF0KWzAsMSwwOyAwLDAsMTsgMSwwLDBdClswLDEsMDsgMSwtMSwxIDswLDEsMF0KWzAsMSwwLDA7IDAsMCwxLDA7IDEsMCwwLDA7IDAsMCwwLDFdClsxLDAsMCwwOyAwLDAsMSwwOyAwLDEsLTEsMTsgMCwwLDEsMF0KWzAsMCwxLDA7IDAsMSwtMSwxOyAxLC0xLDEsMDsgMCwxLDAsMF0KWzAsMCwxLDA7IDEsMCwtMSwxOyAwLDEsMCwwOyAwLDAsMSwwXQpbMCwwLDEsMCwwOyAwLDEsLTEsMSwwOyAxLC0xLDEsMCwwOyAwLDEsMCwtMSwxOyAwLDAsMCwxLDBdClswLDAsMSwwLDAsMCwwLDA7IDEsMCwtMSwwLDEsMCwwLDA7IDAsMCwwLDEsLTEsMCwwLDE7IDAsMCwxLC0xLDEsMCwwLDA7IDAsMCwwLDAsMCwwLDEsMDsgMCwwLDAsMCwwLDEsMCwwOyAwLDEsLTEsMSwwLDAsMCwwOyAwLDAsMSwwLDAsMCwwLDBdClswLDAsMCwwLDEsMCwwLDA7IDAsMCwxLDAsLTEsMSwwLDA7IDAsMCwwLDEsMCwwLDAsMDsgMSwwLDAsLTEsMSwtMSwxLDA7IDAsMSwtMSwxLC0xLDEsMCwwOyAwLDAsMCwwLDEsMCwwLDA7IDAsMCwxLDAsMCwwLDAsMDsgMCwwLDAsMCwwLDAsMCwxXQpbMF0KWy0xXQpbLTEsMTsxLDBdClswLDE7IDEsLTFdClswLDAsMDsgMCwwLDA7IDAsMCwwXQpbMCwxLDA7IDEsMCwxOyAwLDEsMF0KWy0xLDEsMTsgMSwtMSwxOyAxLDEsLTFdClswLDAsMTsgMSwwLDA7IDAsMSwtMV0KWzAsMSwwLDA7IDAsMCwwLDE7IDEsMCwwLDA7IDAsMCwxLC0xXQpbMCwwLDEsMDsgMCwwLDEsMDsgMSwwLC0xLDE7IDAsMSwwLDBdClswLDAsMCwxOyAxLDAsMCwwOyAtMSwxLDEsMDsgMSwwLDAsMF0KWzAsMCwxLDAsMDsgMCwxLC0xLDEsMDsgMSwtMSwxLDAsMDsgMCwxLDEsLTEsMDsgMCwwLC0xLDEsMV0KWzAsLTEsMCwxLDE7IDEsLTEsMSwtMSwxOyAwLDEsMSwwLC0xOyAxLDEsLTEsMSwtMTsgLTEsMSwwLDAsMV0KWzAsMCwxLDAsMCwwLDAsMDsgMSwwLDEsMCwxLDAsMCwwOyAwLDAsMCwxLC0xLDAsMCwxOyAwLDAsMSwtMSwxLDAsMCwwOyAwLDAsMCwwLDAsMCwxLDA7IDAsMCwwLDAsMCwxLDAsMDsgMCwxLC0xLDEsMCwwLDAsMDsgMCwwLDEsMCwwLDAsMCwwXQ" rel="nofollow noreferrer">Modified version to show all test cases

Explanation

        % Implicitly grab input matrix
t!      % Duplicate and transpose input
h       % Horizontally concatenate input with transpose. This allows us to
        % process only columns since now the columns *also* contain the rows.
"       % For each column (of our column/row combined matrix)
  @s1=  % Compute the sum and ensure it is equal to 1
  @Xz   % Get the non-zeros
  d     % Compute the element-to-element difference. The 1 and -1 alternate only if
        % all these differences are non-zero
  v     % Vertically concatenate everything on the stack
        % Implicit end of loop and implicitly display truthy/falsey value


答:
F# , 63 bytes

```<code>fun n->Seq.fold(fun A _->List.collect(fun k->[1..k])A)[n]{1..n}
</code>```

Returns an anonymous function taking n as input.

Replaces every entry k in A with [1..k], repeats the process n times, starting with A = [n].

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:
F# , 63 bytes

fun n->Seq.fold(fun A _->List.collect(fun k->[1..k])A)[n]{1..n}

Returns an anonymous function taking n as input.

Replaces every entry k in A with [1..k], repeats the process n times, starting with A = [n].


答:
PHP, 68 bytes

```<code><?php foreach(str_split($argv[1])as$i=>$a)echo str_repeat($a,$i+1);
</code>```

Title: Write a program to elasticize strings

Body:
PHP, 68 bytes

<?php foreach(str_split($argv[1])as$i=>$a)echo str_repeat($a,$i+1);


答:
Jelly, <s>37</s> <s>36</s> 33 bytes

```<code>,‘X
0Ç<³$Ð¿µżIFµ“+=”ṁṖ⁸żF
ÇÐ¡Ḋz⁶G
</code>```

3 bytes thanks to Dennis.

Try it online

Explanation

```<code>,‘X                    Helper link. Argument: n. Radomly return n or n+1.

 ‘                     Increment n
,                      Pair. Yield [n, n+1]
  X                    Return a random item from the pair.

0Ç<³$Ð¿µżIFµ“+=”ṁṖ⁸żF   Monadic link. Argument: s. Generate one racer.

0                       Start with value 0.
  <³$Ð¿µ                While value is less than s:
 Ç                        Use helper link to increment current value.
                        Collect intermediate results in a list.
         I              Compute consecutive differences.
        ż               Zip intermediate results with their next increment value 0 or 1.
          Fµ            Flatten. Let's call the current list A.
                        Odd items of A are racer state and even items are random 0 or 1.
            “+=”        Yield "+=".
                 Ṗ      Yield A without its last element.
                ṁ       Mold i.e Repeat the characters of the string until it contains length(A)-1 characters.
                  ⁸ż    Zipwith. Pair the elements of A with the correponding characters
                    F   Flatten.

ÇÐ¡ṫ2z” G               Main link. Arguments: s (score needed), r (#racers)

ÇÐ¡                     Call the link above r times.
                        Generate a list of r racers.
   Ḋ                    Remove first element of the list (its a garbage s value)
    z⁶                  Transpose with space as fill value.
      G                 Grid. Format the result.
</code>```

Title: Downward Number Race

Body:
Your task is to create a program that adds random numbers to previous sums in the ultimate number racing showdown.

Each racer (column) starts at 0 and adds either 1 or 0 to the previous sum at each step of the race until all of the racers reach the score required to win. The 1 or 0 should be chosen at random (the standard definition of random can be found here). The output will show the result of the race, with each column representing one racer, in this format:

```<code>>> racers:5,score needed:2

0 0 0 0 0 # all racers start at 0
+ + + + + # add
1 0 0 0 1 # random 1 or 0
= = = = = # equals
1 0 0 0 1 # sum
+ + + + +
0 0 0 0 1
= = = = =
1 0 0 0 2 # winner!
+ + + +
1 1 1 1
= = = =
2 1 1 1
  + + +
  1 1 1
  = = =
  2 2 2   # losers
</code>```

Note: only the numbers, +, and = need to be included in the output.

Input

Your program will accept the following two parameters as input:

the number of racers (columns), which must be greater than two

the score required to win, which must be greater than one

This is code-golf--the program with the least bytes wins.

Edit: there's a non-enforceable max score of 9--this is to preserve the integrity of the column. Also, spaces between columns can be omitted in the output.

Body:
Jelly, <s>37</s> <s>36</s> 33 bytes

,‘X
0Ç<³$Ð¿µżIFµ“+=”ṁṖ⁸żF
ÇÐ¡Ḋz⁶G

3 bytes thanks to Dennis.

Try it online

Explanation

,‘X                    Helper link. Argument: n. Radomly return n or n+1.

 ‘                     Increment n
,                      Pair. Yield [n, n+1]
  X                    Return a random item from the pair.

0Ç<³$Ð¿µżIFµ“+=”ṁṖ⁸żF   Monadic link. Argument: s. Generate one racer.

0                       Start with value 0.
  <³$Ð¿µ                While value is less than s:
 Ç                        Use helper link to increment current value.
                        Collect intermediate results in a list.
         I              Compute consecutive differences.
        ż               Zip intermediate results with their next increment value 0 or 1.
          Fµ            Flatten. Let's call the current list A.
                        Odd items of A are racer state and even items are random 0 or 1.
            “+=”        Yield "+=".
                 Ṗ      Yield A without its last element.
                ṁ       Mold i.e Repeat the characters of the string until it contains length(A)-1 characters.
                  ⁸ż    Zipwith. Pair the elements of A with the correponding characters
                    F   Flatten.

ÇÐ¡ṫ2z” G               Main link. Arguments: s (score needed), r (#racers)

ÇÐ¡                     Call the link above r times.
                        Generate a list of r racers.
   Ḋ                    Remove first element of the list (its a garbage s value)
    z⁶                  Transpose with space as fill value.
      G                 Grid. Format the result.


答:
Don't be afraid to use scientific notation

If you are dealing with doubles, or floats, you can use scientific notation for numbers. So instead of writing double a=1000 you can change it to double a=1e3 to save 1 byte.

Title: Tips for golfing in Java

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


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

答:
Prolog, 40

```<code>m([],L).
m([H|T],L):-length(H,L),m(T,L).
</code>```

Provide a true/false answer when calling m(X,L) for some input X.

Title: Same length sub arrays

Body:
Prolog, 40

m([],L).
m([H|T],L):-length(H,L),m(T,L).

Provide a true/false answer when calling m(X,L) for some input X.