问:
Find a maximal rectangle of 1s

Background

I want to buy an plot of land and build my house on it.
My house should be rectangular, and as large as possible; however, the available plots have lots of rocky areas that I cannot build on, and I'm having trouble fitting a potential house on the plots.
I want you to write a program that analyzes the plots for me.

Input and output

Your input is a rectangular 2D array of bits, of size at least 1×1, in any reasonable format.
The array represents a plot of land; 1s are "good" areas where I could build my house, and 0s are "rocky" areas where the house cannot be built.

Your output shall be the maximal area of a solid rectangle of 1s in the input array.
It represents the area of the largest house I could build on the plot.
Note that if there are no 1s in the input, then the output is 0.

Example

Consider the input

```<code>101
011
111
</code>```

The largest rectangle of 1s is the 2×2 rectangle in the lower right corner.
This means that the correct output is 4.

Rules and scoring

You can write a full program or a function.
The lowest byte count wins, and standard loopholes are disallowed.

Test cases

```<code>0
-> 0

1
-> 1

00
00
-> 0

01
10
-> 1

01
11
-> 2

111
010
111
-> 3

101
011
111
-> 4

0111
1110
1100
-> 4

1111111
1110111
1011101
-> 7

111011000
110111100
001111110
011111111
001111110
000111100
000011000
-> 20

000110000
110110010
110111110
110011100
010011111
111111111
111101110
-> 12
</code>```

答:
MATL, <s>32</s> <s>31</s> 27  bytes

```<code>n:"@:"@1M2$ltntG4$bZ+=a*vX>
</code>```

This uses a brute-force 2D convolution-based approach. All possible rectangle sizes are created and convolved with the terrain. The maximum result of all convolutions is the maximal rectangle area.

This is an extremely inefficient solution because in order to save bytes, I create kernels for all rectangles between [1, 1] and [numel(input) numel(input)] rather than actually determining the number of rows/columns in the input to determine the proper rectangle dimension ranges.

Thanks to @Luis for suggesting the usage of M and omitting the ]].

Try it Online!

Explanation

```<code>        % Implicitly grab input as a 2D numeric array
n       % Compute the number of elements in the input (over estimation of max kernel size)
:       % Create array 1:n
"       % For each value
  @     % Current loop index
  :     % Create an array from 1:(current_index)
  "     % For each of these values
    @   % Push the current index onto the stack
    1M  % Grab the input to the previous function call (the outer index)
    2$l % Create an array of 1's whose dimensions are specified by top two stack elements
    tn  % Duplicate this array and compute number of elements
    t   % Duplicate this number
    G   % Explicitly grab input
    4$b % Bubble up the 4th element from the stack (the kernel)
    Z+  % Perform 2D convolution of this kernel and the input
    =a  % Determine if any convolution result (in each column) is equal to the area of the kernel.
        % This yields a row vector
    *   % Multiply the logical result by the area
    v   % Vertically concatenate all results (forces the row vectors above to be column vectors)
    X>  % Compute the maximum yielding the largest area
        % Implicitly display the result.
</code>```

Title: Find a maximal rectangle of 1s

Body:
MATL, <s>32</s> <s>31</s> 27  bytes

n:"@:"@1M2$ltntG4$bZ+=a*vX>

This uses a brute-force 2D convolution-based approach. All possible rectangle sizes are created and convolved with the terrain. The maximum result of all convolutions is the maximal rectangle area.

This is an extremely inefficient solution because in order to save bytes, I create kernels for all rectangles between [1, 1] and [numel(input) numel(input)] rather than actually determining the number of rows/columns in the input to determine the proper rectangle dimension ranges.

Thanks to @Luis for suggesting the usage of M and omitting the ]].

Try it Online!

Explanation

        % Implicitly grab input as a 2D numeric array
n       % Compute the number of elements in the input (over estimation of max kernel size)
:       % Create array 1:n
"       % For each value
  @     % Current loop index
  :     % Create an array from 1:(current_index)
  "     % For each of these values
    @   % Push the current index onto the stack
    1M  % Grab the input to the previous function call (the outer index)
    2$l % Create an array of 1's whose dimensions are specified by top two stack elements
    tn  % Duplicate this array and compute number of elements
    t   % Duplicate this number
    G   % Explicitly grab input
    4$b % Bubble up the 4th element from the stack (the kernel)
    Z+  % Perform 2D convolution of this kernel and the input
    =a  % Determine if any convolution result (in each column) is equal to the area of the kernel.
        % This yields a row vector
    *   % Multiply the logical result by the area
    v   % Vertically concatenate all results (forces the row vectors above to be column vectors)
    X>  % Compute the maximum yielding the largest area
        % Implicitly display the result.


问:
Finite Cantor's Diagonal
Given a list of N integers, each with N digits, output a number which differs from the first number because of the first digit, the second number because of the second digit, etc.

Example

Given this list:

```<code>1234
4815
1623
4211
</code>```

The number 2932's first digit is different from the first number's first digit, its second digit is different from the second number's second digit, etc. Therefore it would be a valid output.

Inputs

You may take both the list and N as input, or only the list if you wish.

Each integer in the list will necessarily have as many digits as the length of the list (N)

Numbers will not have any leading zeroes

The input list must contain numbers and not strings.

You may take inputs as function arguments, through STDIN, or anything similar.

You may assume that the list will not be longer than 10 elements (and no number in the list will be bigger than 2147483647)

Outputs

It is not sufficient that the output is not in the list. The digits must differ as explained above.

You can use any digit selection strategy that respects the constraint of different digits.

The number cannot have leading zeroes

You may output the number through STDOUT, return it from a function, etc.

Test cases

```<code>Input:
12345678
23456789
34567890
45678901
56789012
67890123
78901234
89012345

Possible output: 24680246

Input:
1

Possible output: 2
</code>```

Scoring

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

答:
PHP, 46/41/40 bytes

```<code>while($a=$argv[++$i])echo($b=9-$a[$i-1])?$b:1;

while($a=$argv[++$i])echo$a[$i-1]==7?6:7;

while($a=$argv[++$i])echo($a[$i-1]%2)+1;
</code>```

Various digit selectors for comparison. I thought "9-digit" would be shortest, but the special case needed to keep a zero out of the first digit overwhelms it.

Fed from CLI arguments:

```<code>php -r "while($a=$argv[++$i])echo($b=9-$a[$i-1])?$b:1;" 12345678 23456789 34567890 45678901 56789012 67890123 78901234 89012345
86421864
</code>```

ContentLicense: CC BY-SA 3.0

Title: Finite Cantor's Diagonal

Body:
PHP, 46/41/40 bytes

while($a=$argv[++$i])echo($b=9-$a[$i-1])?$b:1;

while($a=$argv[++$i])echo$a[$i-1]==7?6:7;

while($a=$argv[++$i])echo($a[$i-1]%2)+1;

Various digit selectors for comparison. I thought "9-digit" would be shortest, but the special case needed to keep a zero out of the first digit overwhelms it.

Fed from CLI arguments:

php -r "while($a=$argv[++$i])echo($b=9-$a[$i-1])?$b:1;" 12345678 23456789 34567890 45678901 56789012 67890123 78901234 89012345
86421864


问:
Remove unnecessary parentheses
You are given a string composed with the characters 0123456789+*(). You can assume that string is always a valid mathematical expression.

Your task is to remove the unnecessary parentheses, assuming multiplication has higher priority than addition.

The parentheses should be removed only when they are not needed structurally:

because of multiplication higher priority: 3+(4*5) => 3+4*5

because of multiplication or addition associativity: 3*(4*5) => 3*4*5

when they are redundant around an expression: 3*((4+5)) => 3*(4+5)

Parentheses should be kept when they could be simplified because of specific number values:

1*(2+3) should not be simplified to 1*2+3

0*(1+0) should not be simplified to 0*1+0

Examples:

```<code>(4*12)+11         ==>    4*12+11
(1+2)*3           ==>    (1+2)*3
3*(4*5)           ==>    3*4*5
((((523))))       ==>    523
(1+1)             ==>    1+1
1*(2*(3+4)*5)*6   ==>    1*2*(3+4)*5*6
1*(2+3)           ==>    1*(2+3)
0*(1+0)           ==>    0*(1+0)

(((2+92+82)*46*70*(24*62)+(94+25))+6)    ==>    (2+92+82)*46*70*24*62+94+25+6
</code>```

答:
Ruby, <s>140</s> 130 bytes

127 bytes source + 3 for  -p flag:

t={}
r=?%
0while$_.gsub!(/\(([^()]+)\)/){t[r+=r]=$1;r}
0while$_.gsub!(/%+/){|m|(s=t[m])[?+]&&($'[0]==?*||$`[/\*$/])??(+s+?):s}
```
<p>And ungolfed:</p>
<pre class="lang-ruby prettyprint-override"><code>tokens = Hash.new
key = '%'

# convert tokens to token keys in the original string, innermost first
0 while $_.gsub!(/\(([^()]+)\)/) { # find the innermost parenthetical
  key += key # make a unique key for this token
  tokens[key] = $1
  key # replace the parenthetical with the token key in the original string
}

# uncomment to see what's going on here
# require 'pp'
# pp $_
# pp tokens

# convert token keys back to tokens, outermost first
0 while $_.gsub!(/%+/) {|key|
  str = tokens[key]
  if str['+'] and ($'[0]=='*' or $`[/\*$/]) # test if token needs parens
    '(' + str + ')'
  else
    str
  end
}
# -p flag implicity prints $_
</code>```

Title: Remove unnecessary parentheses

Body:
Ruby, <s>140</s> 130 bytes

127 bytes source + 3 for  -p flag:

t={}
r=?%
0while$_.gsub!(/\(([^()]+)\)/){t[r+=r]=$1;r}
0while$_.gsub!(/%+/){|m|(s=t[m])[?+]&&($'[0]==?*||$`[/\*$/])??(+s+?):s}

And ungolfed:

tokens = Hash.new
key = '%'

# convert tokens to token keys in the original string, innermost first
0 while $_.gsub!(/\(([^()]+)\)/) { # find the innermost parenthetical
  key += key # make a unique key for this token
  tokens[key] = $1
  key # replace the parenthetical with the token key in the original string
}

# uncomment to see what's going on here
# require 'pp'
# pp $_
# pp tokens

# convert token keys back to tokens, outermost first
0 while $_.gsub!(/%+/) {|key|
  str = tokens[key]
  if str['+'] and ($'[0]=='*' or $`[/\*$/]) # test if token needs parens
    '(' + str + ')'
  else
    str
  end
}
# -p flag implicity prints $_


问:
Matrix Trigonometry

Introduction

The two most common trigonometric functions, sine and cosine (or sin and cos for short), can be extended to be matrix-valued functions. One way to compute the matrix-valued analogs is as follows:

Consider these two important trigonometric identities:

Using these identities, we can derive the following equations for sin and cos:

The matrix exponential exists for all square matrices and is given by:

where A0 is the identity matrix I with the same dimensions as A. Using the matrix exponential, these two trigonometric functions (and thus all the other trigonometric functions) can be evaluated as functions of matrices.

The Challenge

Given a square matrix A, output the values of sin(A) and cos(A).

Rules

Input and output may be in any convenient, reasonable format (2D array, your language's matrix format, etc.).

You may write a single program, two independent programs, a single function, or two functions. If you choose to write two functions, code may be shared between them (such as imports and helper functions).

The input matrix's values will always be integers.

Your solution may have accuracy issues as the result of floating-point imprecision. If your language had magical infinite-precision values, then your solution should work perfectly (ignoring the fact that it would require infinite time and/or memory). However, since those magical infinite-precision values don't exist, inaccuracies caused by limited precision are acceptable. This rule is in place to avoid complications resulting from requiring a specific amount of precision in the output.

Builtins which compute trigonometric functions for matrix arguments (including hyperbolic trig functions) are not allowed. Other matrix builtins (such as multiplication, exponentiation, diagonalization, decomposition, and the matrix exponential) are allowed.

Test Cases

Format: A -> sin(A), cos(A)

```<code>[[0]] -> [[0]], [[1]]
[[0, 2], [3, 5]] -> [[-0.761177343863758, 0.160587281888277], [0.240880922832416, -0.359709139143065]], [[0.600283445979886, 0.119962280223493], [0.179943420335240, 0.900189146538619]]
[[1, 0, 1], [0, 0, 0], [0, 1, 0]] -> [[0.841470984807897, -0.158529015192103, 0.841470984807897], [0, 0, 0], [0, 1, 0]], [[0.540302305868140, -0.459697694131860, -0.459697694131860], [0, 1, 0], [0, 0, 1]]
[[1, 0, 0, 0, 0], [0, 1, 0, 0, 0], [0, 0, 1, 0, 0], [0, 0, 0, 1, 0], [0, 0, 0, 0, 1]] -> [[0.841470984807897, 0, 0, 0, 0], [0, 0.841470984807897, 0, 0, 0], [0, 0, 0.841470984807897, 0, 0], [0, 0, 0, 0.841470984807897, 0], [0, 0, 0, 0, 0.841470984807897]], [[0.540302305868140, 0, 0, 0, 0], [0, 0.540302305868140, 0, 0, 0], [0, 0, 0.540302305868140, 0, 0], [0, 0, 0, 0.540302305868140, 0], [0, 0, 0, 0, 0.540302305868140]]
[[-3, 2, -6], [3, 0, 4], [4, -2, 7]] -> [[-0.374786510963954, 0.135652884035570, -1.35191037980742], [1.14843105375406, 0.773644542790111, 1.21625749577185], [1.21625749577185, -0.135652884035570, 2.19338136461532]], [[4.13614256031450, -1.91289828483056, 5.50873853927692], [-2.63939111203107, 1.49675144828342, -3.59584025444636], [-3.59584025444636, 1.91289828483056, -4.96843623340878]]
</code>```

Further Reading

This excellent question over at Math.SE includes some alternate derivations of the matrix-valued analogs of trigonometric functions.

答:
Julia 0.4, 28 bytes

```<code>A->imag({E=expm(im*A),im*E})
</code>```

Input is a matrix of floats, output is an array of matrices. Try it online!

Title: Matrix Trigonometry

Body:
Julia 0.4, 28 bytes

A->imag({E=expm(im*A),im*E})

Input is a matrix of floats, output is an array of matrices. Try it online!


Title: Finite Cantor's Diagonal

Body:
Given a list of N integers, each with N digits, output a number which differs from the first number because of the first digit, the second number because of the second digit, etc.

Example

Given this list:

```<code>1234
4815
1623
4211
</code>```

The number 2932's first digit is different from the first number's first digit, its second digit is different from the second number's second digit, etc. Therefore it would be a valid output.

Inputs

You may take both the list and N as input, or only the list if you wish.

Each integer in the list will necessarily have as many digits as the length of the list (N)

Numbers will not have any leading zeroes

The input list must contain numbers and not strings.

You may take inputs as function arguments, through STDIN, or anything similar.

You may assume that the list will not be longer than 10 elements (and no number in the list will be bigger than 2147483647)

Outputs

It is not sufficient that the output is not in the list. The digits must differ as explained above.

You can use any digit selection strategy that respects the constraint of different digits.

The number cannot have leading zeroes

You may output the number through STDOUT, return it from a function, etc.

Test cases

```<code>Input:
12345678
23456789
34567890
45678901
56789012
67890123
78901234
89012345

Possible output: 24680246

Input:
1

Possible output: 2
</code>```

Scoring

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

Body:
J, <s>26</s> 22 bytes

1+1>:i.@#{"_1"."0@":"0

Similar approach to the others using the <= 1 and increment method of the diagonal.

Usage

Only requires the list of integers as an argument.

   f =: 1+1>:i.@#{"_1"."0@":"0
   f 1234 4815 1623 4211
2 1 1 2
   f 92345678 23456789 34567890 45678901 56789012 67890123 78901234 89012345
1 1 1 1 1 2 1 1


答:
Jelly, <s>21</s> <s>20</s> <s>18</s> 17 bytes

```<code>ṡṂ€€×"
‘×¥\ç"Ụ€FṀ
</code>```

Try it online! or verify all test cases.

Background

Let M be a matrix of bits such as

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

We start by counting the number of 1 bits in each column of M, resetting the count every time we encounter a 0 bit.

For our example matrix, this gives

```<code>0 0 0 1 1 0 0 0 0
1 1 0 2 2 0 0 1 0
2 2 0 3 3 1 1 2 0
3 3 0 0 4 2 2 0 0
0 4 0 0 5 3 3 1 1
1 5 1 1 6 4 4 2 2
2 6 2 2 0 5 5 3 0
</code>```

Next, we compute all contiguous sublists of each row. We achieve this by generating all slices of length k, where k varies between 1 and the number of entries in each row.

For the penultimate row, this gives

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

Next, we map each slice to the product of its minimum and its length. For each slice, this computes the area of the rectangle of 1 bits of maximum height that has the given slice as bottom row.

For the slices of length 3 of the penultimate row of our example matrix, this gives

```<code>3 3 3 3 12 6 6
</code>```

All that's left to do is take the maximum across all slices of all rows.

For our example matrix, this gives 12.

How it works

```<code>‘×¥\ç"Ụ€FṀ  Main link. Argument: M (2D list of bits)

   \        Reduce the columns of M by the link to the left.
  ¥           Combine the two atoms to the left into a dyadic chain.
‘               Increment the left argument.
 ×              Multiply the result with the right argument.
      Ụ€    Grade up each; yield the indices of each row of M, sorted by their
            values. The order is not important here; we just need the indices.
    ç"      Apply the helper link to each element of the result to the left and
            the corresponding element of the result to the right.
        F   Flatten the resulting, nested list.
         Ṁ  Extract the maximum.

ṡṂ€€×"      Helper link. Arguments: R (row), X (indices of R)

ṡ           For each k in X, split R into overlapping slices of length k.
 Ṁ€€        Compute the minimum of each individual slice.
    ×"      Multiply the minima of all slices of length k by k.
</code>```

Title: Find a maximal rectangle of 1s

Body:
Background

I want to buy an plot of land and build my house on it.
My house should be rectangular, and as large as possible; however, the available plots have lots of rocky areas that I cannot build on, and I'm having trouble fitting a potential house on the plots.
I want you to write a program that analyzes the plots for me.

Input and output

Your input is a rectangular 2D array of bits, of size at least 1×1, in any reasonable format.
The array represents a plot of land; 1s are "good" areas where I could build my house, and 0s are "rocky" areas where the house cannot be built.

Your output shall be the maximal area of a solid rectangle of 1s in the input array.
It represents the area of the largest house I could build on the plot.
Note that if there are no 1s in the input, then the output is 0.

Example

Consider the input

```<code>101
011
111
</code>```

The largest rectangle of 1s is the 2×2 rectangle in the lower right corner.
This means that the correct output is 4.

Rules and scoring

You can write a full program or a function.
The lowest byte count wins, and standard loopholes are disallowed.

Test cases

```<code>0
-> 0

1
-> 1

00
00
-> 0

01
10
-> 1

01
11
-> 2

111
010
111
-> 3

101
011
111
-> 4

0111
1110
1100
-> 4

1111111
1110111
1011101
-> 7

111011000
110111100
001111110
011111111
001111110
000111100
000011000
-> 20

000110000
110110010
110111110
110011100
010011111
111111111
111101110
-> 12
</code>```

Body:
Jelly, <s>21</s> <s>20</s> <s>18</s> 17 bytes

ṡṂ€€×"
‘×¥\ç"Ụ€FṀ

Try it online! or <a href="http://jelly.tryitonline.net/#code=4bmh4bmC4oKs4oKsw5ciCuKAmMOXwqVcw6ci4buk4oKsRuG5gArDh-KCrEc&input=&args=WwogW1swXV0sCgogW1sxXV0sCgogW1swLDBdLAogIFswLDBdXSwKCiBbWzAsMV0sCiAgWzEsMF1dLAoKIFtbMCwxXSwKICBbMSwxXV0sCgogW1sxLDEsMV0sCiAgWzAsMSwwXSwKICBbMSwxLDFdXSwKCiBbWzEsMCwxXSwKICBbMCwxLDFdLAogIFsxLDEsMV1dLAoKIFtbMCwxLDEsMV0sCiAgWzEsMSwxLDBdLAogIFsxLDEsMCwwXV0sCgogW1sxLDEsMSwxLDEsMSwxXSwKICBbMSwxLDEsMCwxLDEsMV0sCiAgWzEsMCwxLDEsMSwwLDFdXSwKCiBbWzEsMSwxLDAsMSwxLDAsMCwwXSwKICBbMSwxLDAsMSwxLDEsMSwwLDBdLAogIFswLDAsMSwxLDEsMSwxLDEsMF0sCiAgWzAsMSwxLDEsMSwxLDEsMSwxXSwKICBbMCwwLDEsMSwxLDEsMSwxLDBdLAogIFswLDAsMCwxLDEsMSwxLDAsMF0sCiAgWzAsMCwwLDAsMSwxLDAsMCwwXV0sCgogW1swLDAsMCwxLDEsMCwwLDAsMF0sCiAgWzEsMSwwLDEsMSwwLDAsMSwwXSwKICBbMSwxLDAsMSwxLDEsMSwxLDBdLAogIFsxLDEsMCwwLDEsMSwxLDAsMF0sCiAgWzAsMSwwLDAsMSwxLDEsMSwxXSwKICBbMSwxLDEsMSwxLDEsMSwxLDFdLAogIFsxLDEsMSwxLDAsMSwxLDEsMF1dCl0" rel="noreferrer">verify all test cases.

Background

Let M be a matrix of bits such as

0 0 0 1 1 0 0 0 0
1 1 0 1 1 0 0 1 0
1 1 0 1 1 1 1 1 0
1 1 0 0 1 1 1 0 0
0 1 0 0 1 1 1 1 1
1 1 1 1 1 1 1 1 1
1 1 1 1 0 1 1 1 0

We start by counting the number of 1 bits in each column of M, resetting the count every time we encounter a 0 bit.

For our example matrix, this gives

0 0 0 1 1 0 0 0 0
1 1 0 2 2 0 0 1 0
2 2 0 3 3 1 1 2 0
3 3 0 0 4 2 2 0 0
0 4 0 0 5 3 3 1 1
1 5 1 1 6 4 4 2 2
2 6 2 2 0 5 5 3 0

Next, we compute all contiguous sublists of each row. We achieve this by generating all slices of length k, where k varies between 1 and the number of entries in each row.

For the penultimate row, this gives

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

Next, we map each slice to the product of its minimum and its length. For each slice, this computes the area of the rectangle of 1 bits of maximum height that has the given slice as bottom row.

For the slices of length 3 of the penultimate row of our example matrix, this gives

3 3 3 3 12 6 6

All that's left to do is take the maximum across all slices of all rows.

For our example matrix, this gives 12.

How it works

‘×¥\ç"Ụ€FṀ  Main link. Argument: M (2D list of bits)

   \        Reduce the columns of M by the link to the left.
  ¥           Combine the two atoms to the left into a dyadic chain.
‘               Increment the left argument.
 ×              Multiply the result with the right argument.
      Ụ€    Grade up each; yield the indices of each row of M, sorted by their
            values. The order is not important here; we just need the indices.
    ç"      Apply the helper link to each element of the result to the left and
            the corresponding element of the result to the right.
        F   Flatten the resulting, nested list.
         Ṁ  Extract the maximum.

ṡṂ€€×"      Helper link. Arguments: R (row), X (indices of R)

ṡ           For each k in X, split R into overlapping slices of length k.
 Ṁ€€        Compute the minimum of each individual slice.
    ×"      Multiply the minima of all slices of length k by k.


问:
The rice and chess problem
An Indian legend tells the story of the alleged inventor of the chess game, who impressed the emperor of India with his game so much that he would get rewarded with anything asked.

The man said he wanted to be paid in rice. He wanted a grain of rice for the first square of the chessboard, two for the second, four for the third, eight for the fourth, and so on, until the 64th square.

The emperor was amazed that the man asked for such a small reward, but as his mathematicians started counting, he ended up losing one of his provinces.

Task

Given the length of the side of a hypothetical chessboard (which is 8 on a default chessboard) and the multiplier between squares (which is 2 in the legend), calculate the number of grains of rice the emperor must pay to the man.

Notes

The side length will always be a positive integer. The multiplier could instead be any kind of rational number.

If your language of choice can't display very large numbers, it's okay as long as your program can correctly process smaller inputs.

Also if your language of choice rounds larger values (with exponential notations), it's okay if those values are approximately correct.

Testcases

```<code>Input (side length, multiplier) => Output
8, 2                            => 18446744073709551615
3, 6                            => 2015539
7, 1.5                          => 850161998.2854
5, -3                           => 211822152361
256, 1                          => 65536
2, 2                            => 15
2, -2                           => -5
</code>```

Please note that the explicit formula

```<code>result = (multiplier ^ (side ^ 2) - 1) / (multiplier - 1)
</code>```

Performs wrong on multiplier = 1, as

```<code>1 ^ (side ^ 2) - 1 = 0
1 - 1 = 0
0 / 0 != side ^ 2 (as it should be)
</code>```

Scoring

This is code-golf. Shortest answer in bytes wins.

Title: The rice and chess problem

Body:
Ruby: 39 bytes

->s,m{(0...s*s).reduce(0){|a,b|a+m**b}}

Test:

f = ->s,m{(0...s*s).reduce(0){|a,b|a+m**b}}

f[8,2]   # 18446744073709551615
f[3,6]   # 2015539
f[7,1.5] # 850161998.2853994
f[5,-3]  # 211822152361
f[256,1] # 65536
f[2,2]   # 15
f[2,-2]  # -5
f[1,1]   # 1


答:
C++, 305 bytes

#include<cmath>
#include<iostream>
#include<vector>
int x,i=0, j;void p(std::vector<double> v){int x=sqrt(v.size());for(i=0;i<x;i++){for(j=0;j<x;j++) std::cout << v[x] << " ";std::cout << "\n";}}int main(){std::vector<double> s, c;while(std::cin >> x){s.push_back(sin(x));c.push_back(cos(x));}p(s);p(c);}
```

Input is a list of numbers that are a perfect square on stdin. Output is a pretty printed 2d array on stdout

Title: Matrix Trigonometry

Body:
Introduction

The two most common trigonometric functions, sine and cosine (or sin and cos for short), can be extended to be matrix-valued functions. One way to compute the matrix-valued analogs is as follows:

Consider these two important trigonometric identities:

Using these identities, we can derive the following equations for sin and cos:

The matrix exponential exists for all square matrices and is given by:

where A0 is the identity matrix I with the same dimensions as A. Using the matrix exponential, these two trigonometric functions (and thus all the other trigonometric functions) can be evaluated as functions of matrices.

The Challenge

Given a square matrix A, output the values of sin(A) and cos(A).

Rules

Input and output may be in any convenient, reasonable format (2D array, your language's matrix format, etc.).

You may write a single program, two independent programs, a single function, or two functions. If you choose to write two functions, code may be shared between them (such as imports and helper functions).

The input matrix's values will always be integers.

Your solution may have accuracy issues as the result of floating-point imprecision. If your language had magical infinite-precision values, then your solution should work perfectly (ignoring the fact that it would require infinite time and/or memory). However, since those magical infinite-precision values don't exist, inaccuracies caused by limited precision are acceptable. This rule is in place to avoid complications resulting from requiring a specific amount of precision in the output.

Builtins which compute trigonometric functions for matrix arguments (including hyperbolic trig functions) are not allowed. Other matrix builtins (such as multiplication, exponentiation, diagonalization, decomposition, and the matrix exponential) are allowed.

Test Cases

Format: A -> sin(A), cos(A)

```<code>[[0]] -> [[0]], [[1]]
[[0, 2], [3, 5]] -> [[-0.761177343863758, 0.160587281888277], [0.240880922832416, -0.359709139143065]], [[0.600283445979886, 0.119962280223493], [0.179943420335240, 0.900189146538619]]
[[1, 0, 1], [0, 0, 0], [0, 1, 0]] -> [[0.841470984807897, -0.158529015192103, 0.841470984807897], [0, 0, 0], [0, 1, 0]], [[0.540302305868140, -0.459697694131860, -0.459697694131860], [0, 1, 0], [0, 0, 1]]
[[1, 0, 0, 0, 0], [0, 1, 0, 0, 0], [0, 0, 1, 0, 0], [0, 0, 0, 1, 0], [0, 0, 0, 0, 1]] -> [[0.841470984807897, 0, 0, 0, 0], [0, 0.841470984807897, 0, 0, 0], [0, 0, 0.841470984807897, 0, 0], [0, 0, 0, 0.841470984807897, 0], [0, 0, 0, 0, 0.841470984807897]], [[0.540302305868140, 0, 0, 0, 0], [0, 0.540302305868140, 0, 0, 0], [0, 0, 0.540302305868140, 0, 0], [0, 0, 0, 0.540302305868140, 0], [0, 0, 0, 0, 0.540302305868140]]
[[-3, 2, -6], [3, 0, 4], [4, -2, 7]] -> [[-0.374786510963954, 0.135652884035570, -1.35191037980742], [1.14843105375406, 0.773644542790111, 1.21625749577185], [1.21625749577185, -0.135652884035570, 2.19338136461532]], [[4.13614256031450, -1.91289828483056, 5.50873853927692], [-2.63939111203107, 1.49675144828342, -3.59584025444636], [-3.59584025444636, 1.91289828483056, -4.96843623340878]]
</code>```

Further Reading

This excellent question over at Math.SE includes some alternate derivations of the matrix-valued analogs of trigonometric functions.

Body:
C++, 305 bytes

#include<cmath>
#include<iostream>
#include<vector>
int x,i=0, j;void p(std::vector<double> v){int x=sqrt(v.size());for(i=0;i<x;i++){for(j=0;j<x;j++) std::cout << v[x] << " ";std::cout << "\n";}}int main(){std::vector<double> s, c;while(std::cin >> x){s.push_back(sin(x));c.push_back(cos(x));}p(s);p(c);}

Input is a list of numbers that are a perfect square on stdin. Output is a pretty printed 2d array on stdout


问:
Calculate the Gamma function for half-integer arguments
Gamma function is defined as

It is a well-known fact that for positive integers it coincides with a properly shifted factorial function: Γ(n) = (n - 1)!. However, a less famous fact is

Γ(1/2) = π1/2

Actually, the Gamma function can be evaluated for all half-integer arguments, and the result is a rational number multiplied by π1/2. The formulas, as mentioned in Wikipedia, are:

 (for n > 0)

In this challenge, you should write code (program or function) that receives an integer n and returns the rational representation of Γ(1/2 + n) / π1/2, as a rational-number object, a pair of integers or a visual plain-text representation like 15/8.

The numerator and denominator don't need to be relatively prime. The code should support values of n at least in the range -10 ... 10 (I chose 10 because 20! < 264 and 19!! < 232).

Test cases (taken from Wikipedia):

```<code>Input | Output (visual) | Output (pair of numbers)
0     | 1               | 1, 1
1     | 1/2             | 1, 2
-1    | -2              | -2, 1
-2    | 4/3             | 4, 3
-3    | -8/15           | -8, 15
</code>```

答:
Ruby, <s>80</s> <s>59</s> 58 bytes

f=->n{n<0?(-1)**n/f[-n]:(1..n).reduce(1){|z,a|z*(a-1r/2)}}
```

<p>Any golfing suggestions are welcome.</p>

<p><strong>Ungolfing:</strong></p>

<pre class="lang-ruby prettyprint-override"><code>def half_gamma(n)
  if n < 0
    return (-1) ** n / f(-n)
  else
    # Is there an golfier way to write product([1/2,3/2..(2*n-1)/2])?
    return (1..n).reduce(1) {|z, a| z * (a - 1r/2)}
  end
end
</code>```

Body:
Ruby, <s>80</s> <s>59</s> 58 bytes

f=->n{n<0?(-1)**n/f[-n]:(1..n).reduce(1){|z,a|z*(a-1r/2)}}

Any golfing suggestions are welcome.

Ungolfing:

def half_gamma(n)
  if n < 0
    return (-1) ** n / f(-n)
  else
    # Is there an golfier way to write product([1/2,3/2..(2*n-1)/2])?
    return (1..n).reduce(1) {|z, a| z * (a - 1r/2)}
  end
end


答:
Haskell, <s>81</s> <s>71</s> 69 bytes

```<code>import Data.Ratio
p=product
f n|n<0=1/(p[n+1%2..0-1])|0<1=p[1%2..n-1]
</code>```

This seems bloated, but I'm not sure where to golf this from here. Any golfing suggestions are welcome.

Edit: Used the fact that the default step of range [x..y] is 1, and moved product to p=product to save two bytes.

Ungolfing:

```<code>import Data.Ratio
gamma_half n | n < 0     = 1 / ( product [ n + 1%2 .. (-1) ] )
             | otherwise = product [ 1%2 .. n-1 ]
</code>```

Title: Calculate the Gamma function for half-integer arguments

Body:
Gamma function is defined as

It is a well-known fact that for positive integers it coincides with a properly shifted factorial function: Γ(n) = (n - 1)!. However, a less famous fact is

Γ(1/2) = π1/2

Actually, the Gamma function can be evaluated for all half-integer arguments, and the result is a rational number multiplied by π1/2. The formulas, as mentioned in Wikipedia, are:

 (for n > 0)

In this challenge, you should write code (program or function) that receives an integer n and returns the rational representation of Γ(1/2 + n) / π1/2, as a rational-number object, a pair of integers or a visual plain-text representation like 15/8.

The numerator and denominator don't need to be relatively prime. The code should support values of n at least in the range -10 ... 10 (I chose 10 because 20! < 264 and 19!! < 232).

Test cases (taken from Wikipedia):

```<code>Input | Output (visual) | Output (pair of numbers)
0     | 1               | 1, 1
1     | 1/2             | 1, 2
-1    | -2              | -2, 1
-2    | 4/3             | 4, 3
-3    | -8/15           | -8, 15
</code>```

Body:
Haskell, <s>81</s> <s>71</s> 69 bytes

import Data.Ratio
p=product
f n|n<0=1/(p[n+1%2..0-1])|0<1=p[1%2..n-1]

This seems bloated, but I'm not sure where to golf this from here. Any golfing suggestions are welcome.

Edit: Used the fact that the default step of range [x..y] is 1, and moved product to p=product to save two bytes.

Ungolfing:

import Data.Ratio
gamma_half n | n < 0     = 1 / ( product [ n + 1%2 .. (-1) ] )
             | otherwise = product [ 1%2 .. n-1 ]


答:
JavaScript (ES6), 154 <s>176</s>

Edit tried to shorten a bit, but cannot compete against @Neil's solution

Try every possible rectangle, return the max size. Probably the same algorithm of the Matl answer, just 6 times longer.

Input as a 2d array of integers

g=>g.map((r,i)=>r.map((x,j)=>v=s(r,j,(_,l)=>s(g,i,(_,k)=>!s(g,k,r=>s(r,l,x=>!x,l+j+1),k+i+1)))&(t=-~i*-~j)>v?t:v),s=(a,i,l,j)=>a.slice(i,j).some(l),v=0)|v
```

<p><em>Less golfed</em></p>

<p>This is the original algorithm, the golfed version abuse a lot of array traversing function istead of for loops</p>

<pre class="lang-js prettyprint-override"><code>g=>{
  v = 0
  for(i = h = g.length; i; i--)
    for(j = w = g[0].length; j; j--)
    {
      p = true
      for(k=0; p && k <= h-i; k++)
        for(l=0; p && l <= w-j; j++)
          p = g.slice(k, k+i).some(r=>r.slice(l, l+j).some(x=>!x));
      if (!p && i*j<v)
        v = i*j
    }
  return v
}
</code>```

Test

f=g=>g.map((r,i)=>r.map((x,j)=>v=s(r,j,(_,l)=>s(g,i,(_,k)=>!s(g,k,r=>s(r,l,x=>!x,l+j+1),k+i+1)))&(t=-~i*-~j)>v?t:v),s=(a,i,l,j)=>a.slice(i,j).some(l),v=0)|v

console.log=(...x)=>O.textContent+=x+'\n'

// test cases as strings, converted to 2d arrays
;[
  ['0',0],['1',1],['00 00',0],['01 10',1],['01 11',2],
  ['111 010 111',3],['101 011 111',4],
  ['0111 1110 1100',4],['1111111 1110111 1011101',7],
  ['111011000 110111100 001111110 011111111 001111110 000111100 000011000',20],
  ['000110000 110110010 110111110 110011100 010011111 111111111 111101110',12]
].forEach(t=>{
  var k=t[1]
  var p=t[0].split` `.map(r=>[...r].map(x=>+x))
  var r=f(p)
  console.log((r==k?'OK':'KO')+' '+r+(r==k?'':' expected '+k)+'\n'+p.join`\n`+'\n')
  })```
<pre class="snippet-code-html lang-html prettyprint-override"><code><pre id=O>``````

Title: Find a maximal rectangle of 1s

Body:
JavaScript (ES6), 154 <s>176</s>

Edit tried to shorten a bit, but cannot compete against @Neil's solution

Try every possible rectangle, return the max size. Probably the same algorithm of the Matl answer, just 6 times longer.

Input as a 2d array of integers

g=>g.map((r,i)=>r.map((x,j)=>v=s(r,j,(_,l)=>s(g,i,(_,k)=>!s(g,k,r=>s(r,l,x=>!x,l+j+1),k+i+1)))&(t=-~i*-~j)>v?t:v),s=(a,i,l,j)=>a.slice(i,j).some(l),v=0)|v

Less golfed

This is the original algorithm, the golfed version abuse a lot of array traversing function istead of for loops

g=>{
  v = 0
  for(i = h = g.length; i; i--)
    for(j = w = g[0].length; j; j--)
    {
      p = true
      for(k=0; p && k <= h-i; k++)
        for(l=0; p && l <= w-j; j++)
          p = g.slice(k, k+i).some(r=>r.slice(l, l+j).some(x=>!x));
      if (!p && i*j<v)
        v = i*j
    }
  return v
}

Test

f=g=>g.map((r,i)=>r.map((x,j)=>v=s(r,j,(_,l)=>s(g,i,(_,k)=>!s(g,k,r=>s(r,l,x=>!x,l+j+1),k+i+1)))&(t=-~i*-~j)>v?t:v),s=(a,i,l,j)=>a.slice(i,j).some(l),v=0)|v

console.log=(...x)=>O.textContent+=x+'\n'

// test cases as strings, converted to 2d arrays
;[
  ['0',0],['1',1],['00 00',0],['01 10',1],['01 11',2],
  ['111 010 111',3],['101 011 111',4],
  ['0111 1110 1100',4],['1111111 1110111 1011101',7],
  ['111011000 110111100 001111110 011111111 001111110 000111100 000011000',20],
  ['000110000 110110010 110111110 110011100 010011111 111111111 111101110',12]
].forEach(t=>{
  var k=t[1]
  var p=t[0].split` `.map(r=>[...r].map(x=>+x))
  var r=f(p)
  console.log((r==k?'OK':'KO')+' '+r+(r==k?'':' expected '+k)+'\n'+p.join`\n`+'\n')
  })

<pre id=O></pre>


答:
Ruby, 21 bytes

```<code>$><<$_[$.-1].hex%2+1
</code>```

A full program. Run with the -n flag. Uses the following mapping: n -> n%2+1.

Title: Finite Cantor's Diagonal

Body:
Ruby, 21 bytes

$><<$_[$.-1].hex%2+1

A full program. Run with the -n flag. Uses the following mapping: n -> n%2+1.


问:
ASCII piano keyboard
Piano keys are     3 characters wide, and 7 characters tall. However, if every key was 3 charactes wide, there wouldn't be enough room for the black keys. That's why some of the white keys have parts of them cut out. There are 3 types of white keys.

Keys with the right half missing (R):

```<code>____
|  |
|  |
|  |
|  |
|   |
|   |
|___|
</code>```

Keys with the left half missing (L):

```<code> ____
 |  |
 |  |
 |  |
 |  |
|   |
|   |
|___|
</code>```

And keys with the left and right halves missing (M):

```<code> ___
 | |
 | |
 | |
 | |
|   |
|   |
|___|
</code>```

On a real keyboard, the pattern of these goes like this:

```<code>RMLRMML, RMLRMML, RMLRMML...
</code>```

and repeats for a total of 88 keys. Now you can't see it when the keys are shown individually, but when you shove them together, you can see the black keys.

```<code>_________________________________________________________
|  | | | |  |  | | | | | |  |  | | | |  |  | | | | | |  |
|  | | | |  |  | | | | | |  |  | | | |  |  | | | | | |  |
|  | | | |  |  | | | | | |  |  | | | |  |  | | | | | |  |
|  | | | |  |  | | | | | |  |  | | | |  |  | | | | | |  |
|   |   |   |   |   |   |   |   |   |   |   |   |   |   |
|   |   |   |   |   |   |   |   |   |   |   |   |   |   |
|___|___|___|___|___|___|___|___|___|___|___|___|___|___|
</code>```

Your task

Given a positive integer N, print this ASCII-art of a piano with N white keys. You should be able to handle any N from 1 to 52 inclusive (since real 88-key pianos have 52 white keys). Here is test output from 1 to 8, and after that the pattern increases in a similar fashion.

```<code>1
____
|  |
|  |
|  |
|  |
|   |
|   |
|___|

2
________
|  | | |
|  | | |
|  | | |
|  | | |
|   |   |
|   |   |
|___|___|

3
_____________
|  | | | |  |
|  | | | |  |
|  | | | |  |
|  | | | |  |
|   |   |   |
|   |   |   |
|___|___|___|

4
________________
|  | | | |  |  |
|  | | | |  |  |
|  | | | |  |  |
|  | | | |  |  |
|   |   |   |   |
|   |   |   |   |
|___|___|___|___|

5
____________________
|  | | | |  |  | | |
|  | | | |  |  | | |
|  | | | |  |  | | |
|  | | | |  |  | | |
|   |   |   |   |   |
|   |   |   |   |   |
|___|___|___|___|___|

6
________________________
|  | | | |  |  | | | | |
|  | | | |  |  | | | | |
|  | | | |  |  | | | | |
|  | | | |  |  | | | | |
|   |   |   |   |   |   |
|   |   |   |   |   |   |
|___|___|___|___|___|___|

7
_____________________________
|  | | | |  |  | | | | | |  |
|  | | | |  |  | | | | | |  |
|  | | | |  |  | | | | | |  |
|  | | | |  |  | | | | | |  |
|   |   |   |   |   |   |   |
|   |   |   |   |   |   |   |
|___|___|___|___|___|___|___|

8
________________________________
|  | | | |  |  | | | | | |  |  |
|  | | | |  |  | | | | | |  |  |
|  | | | |  |  | | | | | |  |  |
|  | | | |  |  | | | | | |  |  |
|   |   |   |   |   |   |   |   |
|   |   |   |   |   |   |   |   |
|___|___|___|___|___|___|___|___|
</code>```

And last but not least, here is a full 52 key output:

```<code>_________________________________________________________________________________________________________________________________________________________________________________________________________________
|  | | | |  |  | | | | | |  |  | | | |  |  | | | | | |  |  | | | |  |  | | | | | |  |  | | | |  |  | | | | | |  |  | | | |  |  | | | | | |  |  | | | |  |  | | | | | |  |  | | | |  |  | | | | | |  |  | | | |  |
|  | | | |  |  | | | | | |  |  | | | |  |  | | | | | |  |  | | | |  |  | | | | | |  |  | | | |  |  | | | | | |  |  | | | |  |  | | | | | |  |  | | | |  |  | | | | | |  |  | | | |  |  | | | | | |  |  | | | |  |
|  | | | |  |  | | | | | |  |  | | | |  |  | | | | | |  |  | | | |  |  | | | | | |  |  | | | |  |  | | | | | |  |  | | | |  |  | | | | | |  |  | | | |  |  | | | | | |  |  | | | |  |  | | | | | |  |  | | | |  |
|  | | | |  |  | | | | | |  |  | | | |  |  | | | | | |  |  | | | |  |  | | | | | |  |  | | | |  |  | | | | | |  |  | | | |  |  | | | | | |  |  | | | |  |  | | | | | |  |  | | | |  |  | | | | | |  |  | | | |  |
|   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |
|   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |
|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|
</code>```

Standard loopholes are banned, and the shortest answer in bytes wins!

Title: ASCII piano keyboard

Body:
><>, 188 182 bytes

&0"_"o011.
.\:7%8g95*-"_"o1-:a1@@?.~~~1+:&:&=1+1$
.v~:7=?;ao"|"o1+:0$0$
.>:7%8g"0"-4*:9go1+:9go1+:9go1+9go1+:&:&=3$-1$
 ^
.>"| _"{:}7=?$~::oooo1+:&:&(3*2+1$
>^
^
0120112
  | | | |  |

The number of white keys to display should be present on the stack at program start.

Edit: I managed to shave off a few bytes through combining the output for lines 5/6 and 7. Previous version:

&0"_"o011.
.\:7%8g95*-"_"o1-:a1@@?.~~~1+:&:&=1+1$
.v~ao"|"o1+:0$0$.
.>:7%8g"0"-4*:9go1+:9go1+:9go1+9go1+:&:&=3$-1$
 ^
.>"|   "oooo1+:&:&(3*2+1$
 ^
 "|___"oooo1+:&:&=?;
0120112
  | | | |  |


问:
Briefest code to find vowels and print consonants
Challenge: Read a string from user, print number of each vowel, then place all remaining chars in a line. Shortest answer wins!

Output must look like this:

Enter String: Input

Vowel Count: a: #, e: #, i: #, o: #, u: #

Remaining characters: Vowel-less Input

For example:

```<code>Enter String: LoremIpsumDolorSitAmetConsecuteurAdipscingElit!
Vowel Count: a: 0, e: 4, i: 4, o: 4, u: 3
Remaining characters: LrmIpsmDlrStAmtCnsctrAdpscngElt!
</code>```

答:
Tcl, 184 (counting majuscule vowels) / 180 (ignoring them)

```<code>puts -nonewline {Enter String: }
flush stdout
gets stdin s
set c {Vowel Count:}
foreach v {a e i o u} {append c " $v: [regsub -all (?i)$v $s {} s]"}
puts "$c\nRemaining Characters: $s"
</code>```

Explanation

Most of the code is actually dealing with the strict I/O requirements. The remainder works by doing a regular expression substitution (deletion) on the input string $s for every vowel and appending the vowel $v and associated number of substitutions to the output string $c.

The above code works for mixed-case vowels. Remove the (?i) option from the regular expression on the penultimate line for strictly minuscule vowels.

Body:
Tcl, 184 (counting majuscule vowels) / 180 (ignoring them)

puts -nonewline {Enter String: }
flush stdout
gets stdin s
set c {Vowel Count:}
foreach v {a e i o u} {append c " $v: [regsub -all (?i)$v $s {} s]"}
puts "$c\nRemaining Characters: $s"

Explanation

Most of the code is actually dealing with the strict I/O requirements. The remainder works by doing a regular expression substitution (deletion) on the input string $s for every vowel and appending the vowel $v and associated number of substitutions to the output string $c.

The above code works for mixed-case vowels. Remove the (?i) option from the regular expression on the penultimate line for strictly minuscule vowels.


答:
C++17, 313 bytes

```<code>#include <cctype>
#include <iostream>
#include <string>
using namespace std;int main(){int n,h[6]={0};string s,v="aeiou",r;cout<<"Enter String: ";getline(cin,s);for(c:s){h[n=v.find(tolower(c))+1]++;if(!n)r+=c;}cout<<"Vowel Count:";n=1;for(c:v)cout<<" "<<c<<": "<<h[n++];cout<<"\nRemaining Characters: "<<r<<"\n";}
</code>```

I suppose I could make this just a function to eliminate standard boilerplate from the byte count.

Ungolfed

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

int main()
{
  int n;
  int histogram[6] = {0};   // { (consonants), A, E, I, O, U }
  string source;
  string vowels = "aeiou";  // vowel order matches the histogram
  string consonants;

  cout << "Enter String: ";
  getline( cin, source );

  for (c : source)
  {
    // n ← consonants=0, A=1, E=2, ...
    n = vowels.find( tolower(c) ) + 1;
    histogram[n]++;
    if (!n)
      consonants += c;
  }

  cout<<"Vowel Count:";
  n = 1;
  for (vowel : vowels)
    cout << " " << vowel << ": " << histogram[n++];

  cout << "\nRemaining Characters: " << consonants << "\n";
}
</code>```

Explanation

Computes a histogram using the std::string lookup functions.

Again, you can eliminate 27 bytes from the count if only minuscule vowels matter. (Remove the first #include and the call to tolower().)

Title: Briefest code to find vowels and print consonants

Body:
Challenge: Read a string from user, print number of each vowel, then place all remaining chars in a line. Shortest answer wins!

Output must look like this:

Enter String: Input

Vowel Count: a: #, e: #, i: #, o: #, u: #

Remaining characters: Vowel-less Input

For example:

```<code>Enter String: LoremIpsumDolorSitAmetConsecuteurAdipscingElit!
Vowel Count: a: 0, e: 4, i: 4, o: 4, u: 3
Remaining characters: LrmIpsmDlrStAmtCnsctrAdpscngElt!
</code>```

Body:
C++17, 313 bytes

#include <cctype>
#include <iostream>
#include <string>
using namespace std;int main(){int n,h[6]={0};string s,v="aeiou",r;cout<<"Enter String: ";getline(cin,s);for(c:s){h[n=v.find(tolower(c))+1]++;if(!n)r+=c;}cout<<"Vowel Count:";n=1;for(c:v)cout<<" "<<c<<": "<<h[n++];cout<<"\nRemaining Characters: "<<r<<"\n";}

I suppose I could make this just a function to eliminate standard boilerplate from the byte count.

Ungolfed

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

int main()
{
  int n;
  int histogram[6] = {0};   // { (consonants), A, E, I, O, U }
  string source;
  string vowels = "aeiou";  // vowel order matches the histogram
  string consonants;

  cout << "Enter String: ";
  getline( cin, source );

  for (c : source)
  {
    // n ← consonants=0, A=1, E=2, ...
    n = vowels.find( tolower(c) ) + 1;
    histogram[n]++;
    if (!n)
      consonants += c;
  }

  cout<<"Vowel Count:";
  n = 1;
  for (vowel : vowels)
    cout << " " << vowel << ": " << histogram[n++];

  cout << "\nRemaining Characters: " << consonants << "\n";
}

Explanation

Computes a histogram using the std::string lookup functions.

Again, you can eliminate 27 bytes from the count if only minuscule vowels matter. (Remove the first #include and the call to tolower().)


答:
Java, 272 bytes

```<code>class L{public static void main(String[]v){String p=v[0],o="Enter String: "+p+"\nVowel Count:",d=" ",e="aeiou";for(char c:e.toCharArray()){o+=d+c+": "+p.replaceAll("[^"+c+"]","").length();d=", ";}System.out.println("\nRemaining characters: "+p.replaceAll("["+e+"]",""));}}
</code>```

Ungolfed

```<code>class L {
    public static void main(String[] v) {
        String input = v[0], result = "Enter String: " + input + "\nVowel Count:", delimiter = " ", vowels = "aeiou";
        for (char c : vowels.toCharArray()) {
            result += delimiter + c + ": " + input.replaceAll("[^" + c + "]", "").length();
            delimiter = ", ";
        }
        System.out.println("\nRemaining characters: " + input.replaceAll("[" + vowels + "]", ""));
    }
}
</code>```

Notes

Input via program arguments: Save as L.java, compile with javac L.java, run with java L LoremIpsumDolorSitAmetConsecuteurAdipscingElit!

Output

```<code>Enter String: LoremIpsumDolorSitAmetConsecuteurAdipscingElit!
Vowel Count: a: 0, e: 4, i: 4, o: 4, u: 3
Remaining characters: LrmIpsmDlrStAmtCnsctrAdpscngElt!
</code>```

Body:
Java, 272 bytes

class L{public static void main(String[]v){String p=v[0],o="Enter String: "+p+"\nVowel Count:",d=" ",e="aeiou";for(char c:e.toCharArray()){o+=d+c+": "+p.replaceAll("[^"+c+"]","").length();d=", ";}System.out.println("\nRemaining characters: "+p.replaceAll("["+e+"]",""));}}

Ungolfed

class L {
    public static void main(String[] v) {
        String input = v[0], result = "Enter String: " + input + "\nVowel Count:", delimiter = " ", vowels = "aeiou";
        for (char c : vowels.toCharArray()) {
            result += delimiter + c + ": " + input.replaceAll("[^" + c + "]", "").length();
            delimiter = ", ";
        }
        System.out.println("\nRemaining characters: " + input.replaceAll("[" + vowels + "]", ""));
    }
}

Notes

Input via program arguments: Save as L.java, compile with javac L.java, run with java L LoremIpsumDolorSitAmetConsecuteurAdipscingElit!

Output

Enter String: LoremIpsumDolorSitAmetConsecuteurAdipscingElit!
Vowel Count: a: 0, e: 4, i: 4, o: 4, u: 3
Remaining characters: LrmIpsmDlrStAmtCnsctrAdpscngElt!


答:
C# 317 bytes

```<code>string t=Console.ReadLine();Dictionary v = new Dictionary<char,int>{{'a',0},{'e',0},{'i',0},{'o',0},{'u',0}};string o="";foreach(char c in t){if(v.Keys.Contains(c)){v[c]++;}else{o+=c;}}Console.WriteLine("a: "+v['a']+", e: "+v['e']+", i: "+v['i']+", o: "+v['o']+", u: "+v['u']);Console.WriteLine("Remaining Characters: "+o);
</code>```

Any suggestions, trying to learn to golf with C#. 1KB is obviously way bigger than the other answers though.

Ungolfed:

```<code>string t=Console.ReadLine();
Dictionary v = new Dictionary<char,int>
{
    {'a',0},
    {'e',0},
    {'i',0},
    {'o',0},
    {'u',0}
};
string o="";
foreach(char c in t)
{
    if(v.Keys.Contains(c))
    {
        v[c]++;
    }
    else
    {
        o+=c;
    }
}
Console.WriteLine("a: "+v['a']+", e: "+v['e']+", i: "+v['i']+", o: "+v['o']+", u: "+v['u']);
Console.WriteLine("Remaining Characters: "+o);
</code>```

Body:
C# 317 bytes

string t=Console.ReadLine();Dictionary v = new Dictionary<char,int>{{'a',0},{'e',0},{'i',0},{'o',0},{'u',0}};string o="";foreach(char c in t){if(v.Keys.Contains(c)){v[c]++;}else{o+=c;}}Console.WriteLine("a: "+v['a']+", e: "+v['e']+", i: "+v['i']+", o: "+v['o']+", u: "+v['u']);Console.WriteLine("Remaining Characters: "+o);

Any suggestions, trying to learn to golf with C#. 1KB is obviously way bigger than the other answers though.

Ungolfed:

string t=Console.ReadLine();
Dictionary v = new Dictionary<char,int>
{
    {'a',0},
    {'e',0},
    {'i',0},
    {'o',0},
    {'u',0}
};
string o="";
foreach(char c in t)
{
    if(v.Keys.Contains(c))
    {
        v[c]++;
    }
    else
    {
        o+=c;
    }
}
Console.WriteLine("a: "+v['a']+", e: "+v['e']+", i: "+v['i']+", o: "+v['o']+", u: "+v['u']);
Console.WriteLine("Remaining Characters: "+o);


问:
Continued Fraction of a Rational Number
The continued fraction of a number n is a fraction of the following form:

which converges to n.

The sequence a in a continued fraction is typically written as: [a0; a1, a2, a3, ..., an].

Your goal is to return the continued fraction of the given rational number (positive or negative), whether it is an:

integer x

fraction x/y

decimal x.yz

Input

May be a string representation, or numbers. For fractions, it may be a string, or some native data type for handling fractions, but you may not take it as a decimal.

Output

May be a delimited list or string of the convergents (the resulting numbers). The output does not have to have a semi-colon between a0 and a1, and may use a comma instead.

Note that although [3; 4, 12, 4] and [3; 4, 12, 3, 1] are both correct, only the first will be accepted, because it is simpler.

Examples:

```<code>860438      [860438]
3.245       [3; 4, 12, 4]
-4.2        [-5; 1, 4]
-114.7802   [-115; 4, 1, 1, 4, 1, 1, 5, 1, 1, 4]
0/11        [0]
1/42        [0; 42]
2/7         [0; 3, 2]
-18/17056   [-1; 1, 946, 1, 1, 4]
-17056/18   [-948; 2, 4]
</code>```

Rules

Shortest code wins.

Built-ins are allowed, but I'd also like you to post in the same answer what it would be without built-ins, so that you have to know how to do it.

Title: Continued Fraction of a Rational Number

Body:
Java, <s>85</s> 83 bytes

String f(int n,int d){return n<0?"-"+f(2*(d+n%d)-n,d):n/d+(n%d<1?"":","+f(d,n%d));}

Takes integer or fraction or decimal as String, 311 bytes

String c(String i){try{return""+Integer.decode(i);}catch(Exception e){int o=i.indexOf(46);if(o>=0)return c((i+"/"+Math.pow(10,i.length()-o-2)).replaceAll("\\.",""));String[]a=i.split("/");int n=Integer.decode(a[0]),d=Integer.decode(a[1]);return n<0?"-"+c(2*(d+n%d)-n+"/"+d):n%d<1?""+n/d:n/d+","+c(d+"/"+(n%d));}}

Sample input/output:

860438
860438

3.245
3,4,12,4

-4.2
-5,1,4

-114.7802
-115,4,1,1,4,1,1,5,1,1,4

0/11
0

1/42
0,42

2/7
0,3,2

-18/17056
-1,1,946,1,1,4

-17056/18
-948,2,4

Actual input/output from full program:

860438
860438
860438
860438
860438
3.245
3,4,12,4
3,4,12,4
3,4,12,4
3,4,12,4
-4.2
-5,1,4
-5,1,4
-5,1,4
-5,1,4
-114.7802
-115,4,1,1,4,1,1,5,1,1,4
-115,4,1,1,4,1,1,5,1,1,4
-115,4,1,1,4,1,1,5,1,1,4
-115,4,1,1,4,1,1,5,1,1,4
0/11
0
0
0
0
1/42
0,42
0,42
0,42
0,42
2/7
0,3,2
0,3,2
0,3,2
0,3,2
-18/17056
-1,1,946,1,1,4
-1,1,946,1,1,4
-1,1,946,1,1,4
-1,1,946,1,1,4
-17056/18
-948,2,4
-948,2,4
-948,2,4
-948,2,4

Full program (including ungolfed functions):

import java.util.Scanner;

public class Q79483 {
    String cf_ungolfed(String input){
        try{
            int result = Integer.parseInt(input);
            return Integer.toString(result);
        }catch(Exception e){
            if(input.indexOf('.')>=0){
                int numerator = Integer.parseInt(input.replaceAll("\\.",""));
                int denominator = (int) Math.pow(10, input.length()-input.indexOf('.')-1);
                return cf_ungolfed(numerator+"/"+denominator);
            }
            int numerator = Integer.parseInt(input.substring(0,input.indexOf('/')));
            int denominator = Integer.parseInt(input.substring(input.indexOf('/')+1));
            if(numerator%denominator == 0){
                return Integer.toString(numerator/denominator);
            }
            if(numerator < 0){
                return "-"+cf_ungolfed((denominator-numerator+(denominator+2*(numerator%denominator)))+"/"+denominator);
            }
            return (numerator/denominator) + "," + cf_ungolfed(denominator+"/"+(numerator%denominator));
        }
    }
    String c(String i){try{return""+Integer.decode(i);}catch(Exception e){int o=i.indexOf(46);if(o>=0)return c((i+"/"+Math.pow(10,i.length()-o-2)).replaceAll("\\.",""));int n=Integer.decode(i.split("/")[0]),d=Integer.decode(i.split("/")[1]);return n<0?"-"+c(2*(d+n%d)-n+"/"+d):n%d<1?""+n/d:n/d+","+c(d+"/"+(n%d));}}
    String f_ungolfed(int numerator,int denominator){
        if(numerator%denominator == 0){
            return Integer.toString(numerator/denominator);
        }
        if(numerator < 0){
            return "-"+f_ungolfed((denominator-numerator+(denominator+2*(numerator%denominator))),denominator);
        }
        return (numerator/denominator) + "," + f_ungolfed(denominator,(numerator%denominator));
    }
    String f(int n,int d){return n<0?"-"+f(2*(d+n%d)-n,d):n/d+(n%d<1?"":","+f(d,n%d));}
    public static int[] format(String input){
        if(input.indexOf('.') != -1){
            int numerator = Integer.parseInt(input.replaceAll("\\.",""));
            int denominator = (int) Math.pow(10, input.length()-input.indexOf('.')-1);
            return new int[]{numerator,denominator};
        }
        if(input.indexOf('/') != -1){
            int numerator = Integer.parseInt(input.substring(0,input.indexOf('/')));
            int denominator = Integer.parseInt(input.substring(input.indexOf('/')+1));
            return new int[]{numerator,denominator};
        }
        return new int[]{Integer.parseInt(input),1};
    }
    public static void main(String args[]){
        Scanner sc = new Scanner(System.in);
        while(sc.hasNext()){
            String input = sc.next();
            System.out.println(new Q79483().cf_ungolfed(input));
            System.out.println(new Q79483().c(input));
            int[] formatted = format(input);
            System.out.println(new Q79483().f_ungolfed(formatted[0], formatted[1]));
            System.out.println(new Q79483().f(formatted[0], formatted[1]));
        }
        sc.close();
    }
}


答:
JavaScript (ES6), 41

The %9+1 trick is borrowed from Suever's answer. For once, .reduce beats .map. Note, the += operator is used to avoid parentheses.

```<code>a=>+a.reduce((t,n,d)=>t+=(n+t)[d]%9+1,'')
</code>```

Title: Finite Cantor's Diagonal

Body:
Given a list of N integers, each with N digits, output a number which differs from the first number because of the first digit, the second number because of the second digit, etc.

Example

Given this list:

```<code>1234
4815
1623
4211
</code>```

The number 2932's first digit is different from the first number's first digit, its second digit is different from the second number's second digit, etc. Therefore it would be a valid output.

Inputs

You may take both the list and N as input, or only the list if you wish.

Each integer in the list will necessarily have as many digits as the length of the list (N)

Numbers will not have any leading zeroes

The input list must contain numbers and not strings.

You may take inputs as function arguments, through STDIN, or anything similar.

You may assume that the list will not be longer than 10 elements (and no number in the list will be bigger than 2147483647)

Outputs

It is not sufficient that the output is not in the list. The digits must differ as explained above.

You can use any digit selection strategy that respects the constraint of different digits.

The number cannot have leading zeroes

You may output the number through STDOUT, return it from a function, etc.

Test cases

```<code>Input:
12345678
23456789
34567890
45678901
56789012
67890123
78901234
89012345

Possible output: 24680246

Input:
1

Possible output: 2
</code>```

Scoring

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

Body:
JavaScript (ES6), 41

The %9+1 trick is borrowed from Suever's answer. For once, .reduce beats .map. Note, the += operator is used to avoid parentheses.

a=>+a.reduce((t,n,d)=>t+=(n+t)[d]%9+1,'')


答:
Jelly, <s>16</s> <s>13</s> 12 bytes

```<code>:;ç%@¥@⁶Ṗ¤%?
</code>```

Try it online!

Title: Continued Fraction of a Rational Number

Body:
The continued fraction of a number n is a fraction of the following form:

which converges to n.

The sequence a in a continued fraction is typically written as: [a0; a1, a2, a3, ..., an].

Your goal is to return the continued fraction of the given rational number (positive or negative), whether it is an:

integer x

fraction x/y

decimal x.yz

Input

May be a string representation, or numbers. For fractions, it may be a string, or some native data type for handling fractions, but you may not take it as a decimal.

Output

May be a delimited list or string of the convergents (the resulting numbers). The output does not have to have a semi-colon between a0 and a1, and may use a comma instead.

Note that although [3; 4, 12, 4] and [3; 4, 12, 3, 1] are both correct, only the first will be accepted, because it is simpler.

Examples:

```<code>860438      [860438]
3.245       [3; 4, 12, 4]
-4.2        [-5; 1, 4]
-114.7802   [-115; 4, 1, 1, 4, 1, 1, 5, 1, 1, 4]
0/11        [0]
1/42        [0; 42]
2/7         [0; 3, 2]
-18/17056   [-1; 1, 946, 1, 1, 4]
-17056/18   [-948; 2, 4]
</code>```

Rules

Shortest code wins.

Built-ins are allowed, but I'd also like you to post in the same answer what it would be without built-ins, so that you have to know how to do it.

Body:
Jelly, <s>16</s> <s>13</s> 12 bytes

:;ç%@¥@⁶Ṗ¤%?

Try it online!


答:
Pyth, 15 bytes

```<code>M+]/GH?J%GHgHJY
</code>```

Try it online! (The g.* at the end is to fetch the input.)

Title: Continued Fraction of a Rational Number

Body:
Pyth, 15 bytes

M+]/GH?J%GHgHJY

Try it online! (The g.* at the end is to fetch the input.)


问:
Compute the Adler-32 checksum

Background

Adler-32 is a 32-bit checksum invented by Mark Adler in 1995 which is part of the widely used zlib library (also developed by Adler). Adler-32 is not as reliable as a 32-bit cyclic redundancy check, but – at least in software  – it is much faster and easier to implement.

Definition

Let B = [b1, ⋯, bn] be a byte array.

The Adler-32 checksum of B is defined as the result of low + 65536 × high, where:

low := ((1 + b1 + ⋯ + bn) mod 65521)

high := (((1 + b1) + (1 + b1 + b2) + ⋯ (1 + b1 + ⋯ + bn)) mod 65521)

Task

Given a byte array as input, compute and return its Adler-32 checksum, abiding to the following.

You can take the input as an array of bytes or integers, or as a string.

In both cases, only bytes corresponding to printable ASCII characters will occur in the input.

You may assume that the length of the input will satisfy 0 < length ≤ 4096.

If you choose to print the output, you may use any positive base up to and including 256.

If you choose unary, make sure interpreter can handle up to 232 - 983056 bytes of output on a machine with 16 GiB of RAM.

Built-ins that compute the Adler-32 checksum are forbidden.

Standard code-golf rules apply.

Test cases

```<code>String:     "Eagles are great!"
Byte array: [69, 97, 103, 108, 101, 115, 32, 97, 114, 101, 32, 103, 114, 101, 97, 116, 33]
Checksum:   918816254

String:     "Programming Puzzles & Code Golf"
Byte array: [80, 114, 111, 103, 114, 97, 109, 109, 105, 110, 103, 32, 80, 117, 122, 122, 108, 101, 115, 32, 38, 32, 67, 111, 100, 101, 32, 71, 111, 108, 102]
Checksum:   3133147946

String:     "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
Byte array: [126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126]
Checksum:   68095937

String:     <1040 question marks>
Byte array: <1040 copies of 63>
Checksum:   2181038080
</code>```

答:
Postgresql, 164 bytes

```<code>SELECT t,((SUM(b)+1)%65521)+65536*(SUM(1+b*(LENGTH(t)-r+1))%65521)
FROM v,LATERAL generate_series(1,LENGTH(t))r
,LATERAL(SELECT ASCII(SUBSTRING(t,r,1))b)z GROUP BY t;
</code>```

SqlFiddleDemo

Output:

```<code>╔═══════════════════════════════════╦════════════╗
║                t                  ║  ?column?  ║
╠═══════════════════════════════════╬════════════╣
║ PostgreSQL can handle it          ║ 1850149040 ║
║ ?(x1040)                          ║ 2181038080 ║
║ Programming Puzzles & Code Golf   ║ 3133147946 ║
║ Eagles are great!                 ║  918816254 ║
║ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~  ║   68095937 ║
╚═══════════════════════════════════╩════════════╝
</code>```

Version with parameter as subquery:

```<code>SELECT((SUM(b)+1)%65521)+65536*(SUM(1+b*(LENGTH(t)-r+1))%65521)
FROM(SELECT text'Eagles are great!'t)s,LATERAL generate_series(1,LENGTH(t))r
,LATERAL(SELECT ASCII(SUBSTRING(t,r,1))b)z;
</code>```

SqlFiddleDemo2

Title: Compute the Adler-32 checksum

Body:
Postgresql, 164 bytes

SELECT t,((SUM(b)+1)%65521)+65536*(SUM(1+b*(LENGTH(t)-r+1))%65521)
FROM v,LATERAL generate_series(1,LENGTH(t))r
,LATERAL(SELECT ASCII(SUBSTRING(t,r,1))b)z GROUP BY t;

SqlFiddleDemo

Output:

╔═══════════════════════════════════╦════════════╗
║                t                  ║  ?column?  ║
╠═══════════════════════════════════╬════════════╣
║ PostgreSQL can handle it          ║ 1850149040 ║
║ ?(x1040)                          ║ 2181038080 ║
║ Programming Puzzles & Code Golf   ║ 3133147946 ║
║ Eagles are great!                 ║  918816254 ║
║ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~  ║   68095937 ║
╚═══════════════════════════════════╩════════════╝

Version with parameter as subquery:

SELECT((SUM(b)+1)%65521)+65536*(SUM(1+b*(LENGTH(t)-r+1))%65521)
FROM(SELECT text'Eagles are great!'t)s,LATERAL generate_series(1,LENGTH(t))r
,LATERAL(SELECT ASCII(SUBSTRING(t,r,1))b)z;

SqlFiddleDemo2


Title: Remove unnecessary parentheses

Body:
You are given a string composed with the characters 0123456789+*(). You can assume that string is always a valid mathematical expression.

Your task is to remove the unnecessary parentheses, assuming multiplication has higher priority than addition.

The parentheses should be removed only when they are not needed structurally:

because of multiplication higher priority: 3+(4*5) => 3+4*5

because of multiplication or addition associativity: 3*(4*5) => 3*4*5

when they are redundant around an expression: 3*((4+5)) => 3*(4+5)

Parentheses should be kept when they could be simplified because of specific number values:

1*(2+3) should not be simplified to 1*2+3

0*(1+0) should not be simplified to 0*1+0

Examples:

```<code>(4*12)+11         ==>    4*12+11
(1+2)*3           ==>    (1+2)*3
3*(4*5)           ==>    3*4*5
((((523))))       ==>    523
(1+1)             ==>    1+1
1*(2*(3+4)*5)*6   ==>    1*2*(3+4)*5*6
1*(2+3)           ==>    1*(2+3)
0*(1+0)           ==>    0*(1+0)

(((2+92+82)*46*70*(24*62)+(94+25))+6)    ==>    (2+92+82)*46*70*24*62+94+25+6
</code>```

Body:
Python 3, <s>274</s> <s>269</s> <s>359</s> <s>337</s> 336 bytes

This method basically removes every possible pair of parentheses and checks to see if it still evaluates the same.

from re import *
def f(x):
    *n,=sub('\D','',x);x=sub('\d','9',x);v,i,r,l=eval(x),0,lambda d,a,s:d.replace(s,"?",a).replace(s,"",1).replace("?",s),lambda:len(findall('\(',x))
    while i<l():
        j=0
        while j<l():
            h=r(r(x,i,"("),j,")")
            try:
                if eval(h)==v:i=j=-1;x=h;break
            except:0
            j+=1
        i+=1
    return sub('9','%s',x)%tuple(n)

Test Harness

print(f("(4*12)+11")=="4*12+11")
print(f("(1+2)*3") =="(1+2)*3")
print(f("3*(4*5)")=="3*4*5")
print(f("((((523))))")=="523")
print(f("(1+1)")=="1+1")
print(f("1*(2*(3+4)*5)*6")=="1*2*(3+4)*5*6")
print(f("(((2+92+82)*46*70*(24*62)+(94+25))+6)")=="(2+92+82)*46*70*24*62+94+25+6")
print(f("1*(2+3)")=="1*(2+3)")
print(f("0*(1+0)")=="0*(1+0)")

Updates

-1 [16-10-04] Removed extra space

-22 [16-05-07] Made use of the re lib

+90 [16-05-07] Updated to handle the new test cases

-5 [16-05-07] Removed parameter from the length (l) lambda


问:
Print N Squared
Write a program or function that takes in a non-negative integer N from stdin or as a function argument. It must print or return a string of a hollow ASCII-art square whose sides are each made with N copies of the number N.

Specifically:

If N is 0, no copies of N are used, so there should be no output (or only a single trailing newline).

If N is 1, the output is:

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

If N is 2:

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

If N is 3:

```<code>333
3 3
333
</code>```

If N is 4:

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

If N is 5:

```<code>55555
5   5
5   5
5   5
55555
</code>```

The pattern continues for 6 through 9.

If N is 10, the output is:

```<code>10101010101010101010
10                10
10                10
10                10
10                10
10                10
10                10
10                10
10                10
10101010101010101010
</code>```

Notice that this is not actually square. It is 10 rows tall but 20 columns wide because 10 is two characters long. This is intended. The point is that each side of the "square" contains N copies of N. So all inputs beyond 9 will technically be ASCII rectangles.

For example, if N is 23, the output is:

```<code>2323232323232323232323232323232323232323232323
23                                          23
23                                          23
23                                          23
23                                          23
23                                          23
23                                          23
23                                          23
23                                          23
23                                          23
23                                          23
23                                          23
23                                          23
23                                          23
23                                          23
23                                          23
23                                          23
23                                          23
23                                          23
23                                          23
23                                          23
23                                          23
2323232323232323232323232323232323232323232323</code>```

Here are Pastebins of the required outputs for 99, 100, 111, and 123 (they may look wrong in a browser but in a text editor they'll look correct). The output for 1000 is to large for Pastebin but it would have 1000 rows and 4000 columns. Numbers with 4 or more digits must work just like smaller numbers.

Details:

N must be written in the usual decimal number representation, with no + sign or other non-digits.

The hollow area must only be filled with spaces.

No lines should have leading or trailing spaces.

A single newline after the squares' last line is optionally allowed.

Languages written after this challenge was made are welcome, they just aren't eligible to win.

The shortest code in bytes wins!

答:
Python 3, 75 characters

```<code>def q(n):s=str(n);m=n-2;print(s*n,*[s+" "*len(s)*m+s]*m,s*n*(n>1),sep="\n")
</code>```

Title: Print N Squared

Body:
Python 3, 75 characters

def q(n):s=str(n);m=n-2;print(s*n,*[s+" "*len(s)*m+s]*m,s*n*(n>1),sep="\n")


答:
JavaScript (ES6), 97 bytes

```<code>a=>a.map((b,i)=>a.slice(i).map((c,j)=>c.map((d,k)=>(n=(b[k]&=d)&&n+j+1)>r?r=n:0,n=0),c=[]),r=0)|r
</code>```

Turns out bit twiddling still wins. Accepts an array of array of integers. Ungolfed:

```<code>function rect(array) {
    var max = 0;
    for (var i = 0; i < array.length; i++) {
        var bits = array[i];
        for (var j = 0; i + j < array.length;) {
            var row = array[i + j];
            j++;
            var size = 0;
            for (var k = 0; k < row.length; k++) {
                if (!row[k]) bits[k] = 0;
                size = ones[k] ? size + j : 0;
                if (size > max) max = size;
            }
        }
    }
    return max;
}
</code>```

The array is sliced by rows as per the other answers, so each possible range of rows is looped over. Given a range of rows, the next step is to measure the available rectangles. This is achieved by ANDing the rows together bitwise; the result is a list of bits which were set in the entire range of rows. It then remains to find the maximal length of set bits in the row and multiply that by the height of the range. Test shamelessly stolen from @ed65:

f=
a=>a.map((b,i)=>a.slice(i).map((c,j)=>c.map((d,k)=>(n=(b[k]&=d)&&n+j+1)>r?r=n:0,n=0),c=[]),r=0)|r

// test cases as strings, converted to 2d arrays
result.textContent = [
  ['0', 0],
  ['1', 1],
  ['00 00', 0],
  ['01 10', 1],
  ['01 11', 2],
  ['111 010 111', 3],
  ['101 011 111', 4],
  ['0111 1110 1100', 4],
  ['1111111 1110111 1011101', 7],
  ['111011000 110111100 001111110 011111111 001111110 000111100 000011000', 20],
  ['000110000 110110010 110111110 110011100 010011111 111111111 111101110', 12]
].map(t => t[0].replace(/ /g, '\n') + '\n' + t[1] + '\n' + f(t[0].split` `.map(r => [...r]))).join`\n\n````
<pre class="snippet-code-html lang-html prettyprint-override"><code><pre id=result>``````

Title: Find a maximal rectangle of 1s

Body:
Background

I want to buy an plot of land and build my house on it.
My house should be rectangular, and as large as possible; however, the available plots have lots of rocky areas that I cannot build on, and I'm having trouble fitting a potential house on the plots.
I want you to write a program that analyzes the plots for me.

Input and output

Your input is a rectangular 2D array of bits, of size at least 1×1, in any reasonable format.
The array represents a plot of land; 1s are "good" areas where I could build my house, and 0s are "rocky" areas where the house cannot be built.

Your output shall be the maximal area of a solid rectangle of 1s in the input array.
It represents the area of the largest house I could build on the plot.
Note that if there are no 1s in the input, then the output is 0.

Example

Consider the input

```<code>101
011
111
</code>```

The largest rectangle of 1s is the 2×2 rectangle in the lower right corner.
This means that the correct output is 4.

Rules and scoring

You can write a full program or a function.
The lowest byte count wins, and standard loopholes are disallowed.

Test cases

```<code>0
-> 0

1
-> 1

00
00
-> 0

01
10
-> 1

01
11
-> 2

111
010
111
-> 3

101
011
111
-> 4

0111
1110
1100
-> 4

1111111
1110111
1011101
-> 7

111011000
110111100
001111110
011111111
001111110
000111100
000011000
-> 20

000110000
110110010
110111110
110011100
010011111
111111111
111101110
-> 12
</code>```

Body:
JavaScript (ES6), 97 bytes

a=>a.map((b,i)=>a.slice(i).map((c,j)=>c.map((d,k)=>(n=(b[k]&=d)&&n+j+1)>r?r=n:0,n=0),c=[]),r=0)|r

Turns out bit twiddling still wins. Accepts an array of array of integers. Ungolfed:

function rect(array) {
    var max = 0;
    for (var i = 0; i < array.length; i++) {
        var bits = array[i];
        for (var j = 0; i + j < array.length;) {
            var row = array[i + j];
            j++;
            var size = 0;
            for (var k = 0; k < row.length; k++) {
                if (!row[k]) bits[k] = 0;
                size = ones[k] ? size + j : 0;
                if (size > max) max = size;
            }
        }
    }
    return max;
}

The array is sliced by rows as per the other answers, so each possible range of rows is looped over. Given a range of rows, the next step is to measure the available rectangles. This is achieved by ANDing the rows together bitwise; the result is a list of bits which were set in the entire range of rows. It then remains to find the maximal length of set bits in the row and multiply that by the height of the range. Test shamelessly stolen from @ed65:

f=
a=>a.map((b,i)=>a.slice(i).map((c,j)=>c.map((d,k)=>(n=(b[k]&=d)&&n+j+1)>r?r=n:0,n=0),c=[]),r=0)|r

// test cases as strings, converted to 2d arrays
result.textContent = [
  ['0', 0],
  ['1', 1],
  ['00 00', 0],
  ['01 10', 1],
  ['01 11', 2],
  ['111 010 111', 3],
  ['101 011 111', 4],
  ['0111 1110 1100', 4],
  ['1111111 1110111 1011101', 7],
  ['111011000 110111100 001111110 011111111 001111110 000111100 000011000', 20],
  ['000110000 110110010 110111110 110011100 010011111 111111111 111101110', 12]
].map(t => t[0].replace(/ /g, '\n') + '\n' + t[1] + '\n' + f(t[0].split` `.map(r => [...r]))).join`\n\n`

<pre id=result></pre>


问:
Read n random lines from a potentially huge file
This challenge is about reading random lines from a potentially huge file without reading the whole file into memory.

Input

An integer n and the name of a text file.

Output

n lines of the text file chosen uniformly at random without replacement.

You can assume that n is in the range 1 to the number of lines in the file.

Be careful when sampling n numbers at random from the range that the answer you get is uniform. rand()%n in C is not uniform for example. Every outcome must be equally likely.

Rules and restrictions

Each line of the text file will have the same number of characters and that will be no more than 80.

Your code must not read any of the contents of text file except:

Those lines it outputs.

The first line to work out how many characters per line there are in the text file.

We can assume each character in the text file takes exactly one byte.

Line separators are assumed to be 1 byte long. Solutions may use 2 bytes long line separators only if they specify this need. You may also assume the last line is terminated by a line separator.

Your answer should be a complete program but you can specify the input in any way that is convenient.

Languages and libraries

You can use any language or library you like.

Notes

There was a concern about calculating the number of lines in the file. As nimi points out in the comments, you can infer this from the file size and the number of chars per line.

Motivation

In chat some people asked if this is really a "Do X without Y" question. I interpret this to ask if the restrictions are unusually artificial.

The task of randomly sampling lines from huge files is not uncommon and is in fact one I sometimes have to do. One way to do this is in bash:

shuf -n <num-lines>

This is however very slow for large files as it reads in the whole file.

答:
PowerShell v2+, 209 bytes

```<code>param($a,$n)
$f=New-Object System.IO.FileStream $a,"Open"
for(;$f.ReadByte()-ne10){$l++}
$t=$f.Length/++$l-1
[byte[]]$z=,0*$l
0..$t|Get-Random -c $n|%{$a=$f.Seek($l*$_,0);$a=$f.Read($z,0,$l-1);-join[char[]]$z}
</code>```

Takes input $a as the filename and $n as the number of lines. Note that $a must be a full-path filename, and assumed to be ANSI encoding.

We then construct a new FileStream object, and tell it to access the file $a with Open privilege.

The for loop .Read()s through the first line until we hit a \n character, incrementing our line-length counter each character. We then set $t equal to the size of the file (i.e., how long the stream is) divided by how many characters per line (plus one so it counts the terminator), minus one (since we're zero-indexed). We then construct our buffer $z to also be line length.

The final line constructs a dynamic array with the .. range operator.1 We pipe that array to Get-Random with a -Count of $n to randomly select $n line numbers without repetition. The lucky numbers are piped into a loop with |%{...}. Each iteration we .Seek to the particular location, and then .Read in a line's worth of characters, stored into $z. We re-cast $z as a char-array and -join it together, leaving the resultant string on the pipeline and output is implicit at the end of the program.

Technically we should end with a $f.Close() call to close out the file, but that costs bytes! :p

Example

```<code>a.txt:
a0000000000000000000000000000000000000000000000001
a0000000000000000000000000000000000000000000000002
a0000000000000000000000000000000000000000000000003
a0000000000000000000000000000000000000000000000004
a0000000000000000000000000000000000000000000000005
a0000000000000000000000000000000000000000000000006
a0000000000000000000000000000000000000000000000007
a0000000000000000000000000000000000000000000000008
a0000000000000000000000000000000000000000000000009
a0000000000000000000000000000000000000000000000010

PS C:\Tools\Scripts\golfing> .\read-n-random-lines.ps1 "c:\tools\scripts\golfing\a.txt" 5
a0000000000000000000000000000000000000000000000002
a0000000000000000000000000000000000000000000000001
a0000000000000000000000000000000000000000000000004
a0000000000000000000000000000000000000000000000010
a0000000000000000000000000000000000000000000000006
</code>```

1 Technically, this means we can only support a maximum of 50,000 lines, as that's the largest range that can be dynamically created in this manner. :-/ But, we can't just loop a Get-Random command $n times, discarding duplicates each loop, since that's not deterministic ...

Body:
PowerShell v2+, 209 bytes

param($a,$n)
$f=New-Object System.IO.FileStream $a,"Open"
for(;$f.ReadByte()-ne10){$l++}
$t=$f.Length/++$l-1
[byte[]]$z=,0*$l
0..$t|Get-Random -c $n|%{$a=$f.Seek($l*$_,0);$a=$f.Read($z,0,$l-1);-join[char[]]$z}

Takes input $a as the filename and $n as the number of lines. Note that $a must be a full-path filename, and assumed to be ANSI encoding.

We then construct a new FileStream object, and tell it to access the file $a with Open privilege.

The for loop .Read()s through the first line until we hit a \n character, incrementing our line-length counter each character. We then set $t equal to the size of the file (i.e., how long the stream is) divided by how many characters per line (plus one so it counts the terminator), minus one (since we're zero-indexed). We then construct our buffer $z to also be line length.

The final line constructs a dynamic array with the .. range operator.1 We pipe that array to Get-Random with a -Count of $n to randomly select $n line numbers without repetition. The lucky numbers are piped into a loop with |%{...}. Each iteration we .Seek to the particular location, and then .Read in a line's worth of characters, stored into $z. We re-cast $z as a char-array and -join it together, leaving the resultant string on the pipeline and output is implicit at the end of the program.

Technically we should end with a $f.Close() call to close out the file, but that costs bytes! :p

Example

a.txt:
a0000000000000000000000000000000000000000000000001
a0000000000000000000000000000000000000000000000002
a0000000000000000000000000000000000000000000000003
a0000000000000000000000000000000000000000000000004
a0000000000000000000000000000000000000000000000005
a0000000000000000000000000000000000000000000000006
a0000000000000000000000000000000000000000000000007
a0000000000000000000000000000000000000000000000008
a0000000000000000000000000000000000000000000000009
a0000000000000000000000000000000000000000000000010

PS C:\Tools\Scripts\golfing> .\read-n-random-lines.ps1 "c:\tools\scripts\golfing\a.txt" 5
a0000000000000000000000000000000000000000000000002
a0000000000000000000000000000000000000000000000001
a0000000000000000000000000000000000000000000000004
a0000000000000000000000000000000000000000000000010
a0000000000000000000000000000000000000000000000006

1 Technically, this means we can only support a maximum of 50,000 lines, as that's the largest range that can be dynamically created in this manner. :-/ But, we can't just loop a Get-Random command $n times, discarding duplicates each loop, since that's not deterministic ...


问:
Is it a prefix code?
In information theory, a "prefix code" is a dictionary where none of the keys are a prefix of another. In other words, this means that none of the strings starts with any of the other.

For example, {"9", "55"} is a prefix code, but {"5", "9", "55"} is not.

The biggest advantage of this, is that the encoded text can be written down with no separator between them, and it will still be uniquely decipherable. This shows up in compression algorithms such as Huffman coding, which always generates the optimal prefix code.

Your task is simple: Given a list of strings, determine whether or not it is a valid prefix code.

Your input:

Will be a list of strings in any reasonable format.

Will only contain printable ASCII strings.

Will not contain any empty strings.

Your output will be a truthy/falsey value: Truthy if it's a valid prefix code, and falsey if it isn't.

Here are some true test cases:

```<code>["Hello", "World"]
["Code", "Golf", "Is", "Cool"]
["1", "2", "3", "4", "5"]
["This", "test", "case", "is", "true"]

["111", "010", "000", "1101", "1010", "1000", "0111", "0010", "1011",
 "0110", "11001", "00110", "10011", "11000", "00111", "10010"]
</code>```

Here are some false test cases:

```<code>["4", "42"]
["1", "2", "3", "34"]
["This", "test", "case", "is", "false", "t"]
["He", "said", "Hello"]
["0", "00", "00001"]
["Duplicate", "Duplicate", "Keys", "Keys"]
</code>```

This is code-golf, so standard loopholes apply, and shortest answer in bytes wins.

答:
PostgreSQL, 186, 173 bytes

```<code>WITH y AS(SELECT * FROM t,LATERAL unnest(c)WITH ORDINALITY s(z,r))
SELECT y.c,EVERY(u.z IS NULL)
FROM y LEFT JOIN y u ON y.i=u.i AND y.r<>u.r AND y.z LIKE u.z||'%' GROUP BY y.c
</code>```

Output:

No live demo this time. http://sqlfiddle.com supports only 9.3 and to run this demo 9.4 is required.

How it works:

Split string array with number and name it y

Get all y

LEFT OUTER JOIN to the same derived table based on the same i(id), but with different oridinal that start with prefix y.z LIKE u.z||'%'

Group result based on c (initial array) and use EVERY grouping function. If every row from second table IS NULL it means there is no prefixes.

Input if someone is interested:

```<code>CREATE TABLE t(i SERIAL,c text[]);

INSERT INTO t(c)
SELECT '{"Hello", "World"}'::text[]
UNION ALL SELECT  '{"Code", "Golf", "Is", "Cool"}'
UNION ALL SELECT  '{"1", "2", "3", "4", "5"}'
UNION ALL SELECT  '{"This", "test", "case", "is", "true"}'
UNION ALL SELECT  '{"111", "010", "000", "1101", "1010", "1000", "0111", "0010", "1011","0110", "11001", "00110", "10011", "11000", "00111", "10010"}'
UNION ALL SELECT  '{"4", "42"}'
UNION ALL SELECT  '{"1", "2", "3", "34"}'
UNION ALL SELECT  '{"This", "test", "case", "is", "false", "t"}'
UNION ALL SELECT  '{"He", "said", "Hello"}'
UNION ALL SELECT  '{"0", "00", "00001"}'
UNION ALL SELECT  '{"Duplicate", "Duplicate", "Keys", "Keys"}';
</code>```

EDIT:

SQL Server 2016+ implementation:

```<code>WITH y AS (SELECT *,z=value,r=ROW_NUMBER()OVER(ORDER BY 1/0) FROM #t CROSS APPLY STRING_SPLIT(c,','))
SELECT y.c, IIF(COUNT(u.z)>0,'F','T')
FROM y LEFT JOIN y u ON y.i=u.i AND y.r<>u.r AND y.z LIKE u.z+'%'
GROUP BY y.c;
</code>```

LiveDemo

Note: It is comma separated list, not real array. But the main idea is the same as in PostgreSQL.

EDIT 2:

Actually WITH ORDINALITY could be replaced:

```<code>WITH y AS(SELECT *,ROW_NUMBER()OVER()r FROM t,LATERAL unnest(c)z)
SELECT y.c,EVERY(u.z IS NULL)
FROM y LEFT JOIN y u ON y.i=u.i AND y.r<>u.r AND y.z LIKE u.z||'%' GROUP BY y.c
</code>```

SqlFiddleDemo

Title: Is it a prefix code?

Body:
PostgreSQL, 186, 173 bytes

WITH y AS(SELECT * FROM t,LATERAL unnest(c)WITH ORDINALITY s(z,r))
SELECT y.c,EVERY(u.z IS NULL)
FROM y LEFT JOIN y u ON y.i=u.i AND y.r<>u.r AND y.z LIKE u.z||'%' GROUP BY y.c

Output:

No live demo this time. http://sqlfiddle.com supports only 9.3 and to run this demo 9.4 is required.

How it works:

Split string array with number and name it y

Get all y

LEFT OUTER JOIN to the same derived table based on the same i(id), but with different oridinal that start with prefix y.z LIKE u.z||'%'

Group result based on c (initial array) and use EVERY grouping function. If every row from second table IS NULL it means there is no prefixes.

Input if someone is interested:

CREATE TABLE t(i SERIAL,c text[]);

INSERT INTO t(c)
SELECT '{"Hello", "World"}'::text[]
UNION ALL SELECT  '{"Code", "Golf", "Is", "Cool"}'
UNION ALL SELECT  '{"1", "2", "3", "4", "5"}'
UNION ALL SELECT  '{"This", "test", "case", "is", "true"}'
UNION ALL SELECT  '{"111", "010", "000", "1101", "1010", "1000", "0111", "0010", "1011","0110", "11001", "00110", "10011", "11000", "00111", "10010"}'
UNION ALL SELECT  '{"4", "42"}'
UNION ALL SELECT  '{"1", "2", "3", "34"}'
UNION ALL SELECT  '{"This", "test", "case", "is", "false", "t"}'
UNION ALL SELECT  '{"He", "said", "Hello"}'
UNION ALL SELECT  '{"0", "00", "00001"}'
UNION ALL SELECT  '{"Duplicate", "Duplicate", "Keys", "Keys"}';

EDIT:

SQL Server 2016+ implementation:

WITH y AS (SELECT *,z=value,r=ROW_NUMBER()OVER(ORDER BY 1/0) FROM #t CROSS APPLY STRING_SPLIT(c,','))
SELECT y.c, IIF(COUNT(u.z)>0,'F','T')
FROM y LEFT JOIN y u ON y.i=u.i AND y.r<>u.r AND y.z LIKE u.z+'%'
GROUP BY y.c;

LiveDemo

Note: It is comma separated list, not real array. But the main idea is the same as in PostgreSQL.

EDIT 2:

Actually WITH ORDINALITY could be replaced:

WITH y AS(SELECT *,ROW_NUMBER()OVER()r FROM t,LATERAL unnest(c)z)
SELECT y.c,EVERY(u.z IS NULL)
FROM y LEFT JOIN y u ON y.i=u.i AND y.r<>u.r AND y.z LIKE u.z||'%' GROUP BY y.c

SqlFiddleDemo


答:
Ruby, <s>134</s> <s>133</s> 131 bytes

Because the other Ruby answer didn't respond to my suggestions, I golfed it down further myself.

-2 bytes from @manatwork

```<code>$><<"Enter String: "
r=gets.tr v='aeiou',''
puts"Vowel Count: #{v.chars.map{|e|e+": #{$_.count e}"}*', '}
Remaining characters: "+r
</code>```

Body:
Challenge: Read a string from user, print number of each vowel, then place all remaining chars in a line. Shortest answer wins!

Output must look like this:

Enter String: Input

Vowel Count: a: #, e: #, i: #, o: #, u: #

Remaining characters: Vowel-less Input

For example:

```<code>Enter String: LoremIpsumDolorSitAmetConsecuteurAdipscingElit!
Vowel Count: a: 0, e: 4, i: 4, o: 4, u: 3
Remaining characters: LrmIpsmDlrStAmtCnsctrAdpscngElt!
</code>```

Body:
Ruby, <s>134</s> <s>133</s> 131 bytes

Because the other Ruby answer didn't respond to my suggestions, I golfed it down further myself.

-2 bytes from @manatwork

$><<"Enter String: "
r=gets.tr v='aeiou',''
puts"Vowel Count: #{v.chars.map{|e|e+": #{$_.count e}"}*', '}
Remaining characters: "+r


答:
T-SQL/SQL Server 2012+, 167 161 bytes

```<code>DECLARE @ INT = 6;

SELECT IIF(u IN(1,s),REPLICATE(s,s),CONCAT(s,REPLICATE(' ',s-2*LEN(s)),s))
FROM(SELECT @ s)z CROSS APPLY(SELECT TOP(s)ROW_NUMBER()OVER(ORDER BY 1/0)u FROM sys.messages)v
</code>```

Output:

```<code>666666
6    6
6    6
6    6
6    6
666666
</code>```

LiveDemo

Enter desired size and click Run query to get text representation.

Please note that this demo does not display fixed-width font. So 7 is thicker than 1.

EDIT:

If we treat input as string:

```<code>DECLARE @ VARCHAR(10) = '7';

SELECT IIF(u IN(1,s),REPLICATE(s,s),s+REPLICATE(' ',s-2*LEN(s))+s)
FROM(SELECT @ s)z CROSS APPLY(SELECT TOP(s+0)ROW_NUMBER()OVER(ORDER BY 1/0)u FROM sys.messages)v
</code>```

LiveDemo2

Title: Print N Squared

Body:
Write a program or function that takes in a non-negative integer N from stdin or as a function argument. It must print or return a string of a hollow ASCII-art square whose sides are each made with N copies of the number N.

Specifically:

If N is 0, no copies of N are used, so there should be no output (or only a single trailing newline).

If N is 1, the output is:

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

If N is 2:

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

If N is 3:

```<code>333
3 3
333
</code>```

If N is 4:

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

If N is 5:

```<code>55555
5   5
5   5
5   5
55555
</code>```

The pattern continues for 6 through 9.

If N is 10, the output is:

```<code>10101010101010101010
10                10
10                10
10                10
10                10
10                10
10                10
10                10
10                10
10101010101010101010
</code>```

Notice that this is not actually square. It is 10 rows tall but 20 columns wide because 10 is two characters long. This is intended. The point is that each side of the "square" contains N copies of N. So all inputs beyond 9 will technically be ASCII rectangles.

For example, if N is 23, the output is:

```<code>2323232323232323232323232323232323232323232323
23                                          23
23                                          23
23                                          23
23                                          23
23                                          23
23                                          23
23                                          23
23                                          23
23                                          23
23                                          23
23                                          23
23                                          23
23                                          23
23                                          23
23                                          23
23                                          23
23                                          23
23                                          23
23                                          23
23                                          23
23                                          23
2323232323232323232323232323232323232323232323</code>```

Here are Pastebins of the required outputs for 99, 100, 111, and 123 (they may look wrong in a browser but in a text editor they'll look correct). The output for 1000 is to large for Pastebin but it would have 1000 rows and 4000 columns. Numbers with 4 or more digits must work just like smaller numbers.

Details:

N must be written in the usual decimal number representation, with no + sign or other non-digits.

The hollow area must only be filled with spaces.

No lines should have leading or trailing spaces.

A single newline after the squares' last line is optionally allowed.

Languages written after this challenge was made are welcome, they just aren't eligible to win.

The shortest code in bytes wins!

Body:
T-SQL/SQL Server 2012+, 167 161 bytes

DECLARE @ INT = 6;

SELECT IIF(u IN(1,s),REPLICATE(s,s),CONCAT(s,REPLICATE(' ',s-2*LEN(s)),s))
FROM(SELECT @ s)z CROSS APPLY(SELECT TOP(s)ROW_NUMBER()OVER(ORDER BY 1/0)u FROM sys.messages)v

Output:

666666
6    6
6    6
6    6
6    6
666666

LiveDemo

Enter desired size and click Run query to get text representation.

Please note that this demo does not display fixed-width font. So 7 is thicker than 1.

EDIT:

If we treat input as string:

DECLARE @ VARCHAR(10) = '7';

SELECT IIF(u IN(1,s),REPLICATE(s,s),s+REPLICATE(' ',s-2*LEN(s))+s)
FROM(SELECT @ s)z CROSS APPLY(SELECT TOP(s+0)ROW_NUMBER()OVER(ORDER BY 1/0)u FROM sys.messages)v

LiveDemo2