问:
What's the chance that I'll win a door prize?
My local ACM chapter gives out door prizes to people who come to the meetings. You get an increased chance of winning if you solve the programming puzzle, however (but I always solve that puzzle). Thus, some people have 1 entry, while others have 2. But wait! The way the raffle program works is not by adding in another entry when someone solves the puzzle. Instead, it keeps track of the number of "lives" a person has, decrementing that if that person is chosen in each pass of it's random sampling algorithm. So it works like this:

```<code>Doorknob: 1.  xnor: 2.  Justin: 2.  Alex: 1.  Dennis: 2.
</code>```

Then the program randomly chooses one of [Doorknob, xnor, Justin, Alex, Dennis], decrements the number (say it chooses Justin):

```<code>Doorknob: 1.  xnor: 2.  Justin: 1.  Alex: 1. Dennis: 2.
</code>```

And repeats. If someone's number of "lives" goes to 0 (let's choose Justin again), they're removed from the list:

```<code>Doorknob: 1.  xnor: 2.  Alex: 1.  Dennis: 2.
</code>```

This continues until there's one person left; that person is the winner.

Now the real question is, what was the probability that I would have won?

You will be given two inputs:

n. This is the number of people entered into the challenge

k. This is the number of people (of those n) who have 2 lives. This number always includes you.

So if I had a function p and called p(10, 5), that would be the probability of winning the prize where there are 10 people total, 5 of which only have 1 life, whereas 5 (including you) have 2 lives.

You are expected to output the probability of winning either exactly, or as a decimal. At any rate, answers must be accurate up to and including the 4th decimal place after the decimal point. Whether or not you round to that digit is up to you.

Your solution may be a randomized solution which outputs the answer to the 4th decimal place with high probability. You may assume that the built in RNG you use is truly random, and it must output the correct answer with at least 90% probability.

Furthermore, your code need only work for n, k <= 1000, although I did provide test cases larger than that for those curious.

Test Cases

Note: some of these are general formulae.

```<code>n,    k   |  output
----------+---------
1,    1   |  1
2,    2   |  0.5
2,    1   |  0.75
3,    1   |  11/18 = 0.611111111
1000, 1   |  0.007485470860550352
4,    3   |  0.3052662037037037
k,    k   |  1/k
n,    1   |  (EulerGamma + PolyGamma[1 + n])/n    (* Mathematica code *)
          |  (γ + ψ(1 + n))/n
10,   6   |  0.14424629234373537
300,  100 |  0.007871966408910648
500,  200 |  0.004218184180294532
1000, 500 |  0.0018008560286627948
---------------------------------- Extra (not needed to be a valid answer)
5000, 601 |  0.0009518052922680399
5000, 901 |  0.0007632938197806958
</code>```

For another few checks, take p(n, 1) * n as follows:

```<code>n     |  output
------+---------
1     | 1
2     | 1.5
3     | 1.8333333333333335
10    | 2.928968253968254
100   | 5.1873775176396215
-------------------------- Extra (not needed to be a valid answer)
100000| 12.090146129863305
</code>```

答:
JavaScript (ES6), 65 bytes

```<code>f=(n,k,d=n-k)=>(!d||(f(n-1,k)*++d*--d+1+(--k&&f(n,k)*k*d))/++d)/n
</code>```

Don't try it with the big numbers though; even f(30, 10) takes a noticeable amount of time.

Body:
JavaScript (ES6), 65 bytes

f=(n,k,d=n-k)=>(!d||(f(n-1,k)*++d*--d+1+(--k&&f(n,k)*k*d))/++d)/n

Don't try it with the big numbers though; even f(30, 10) takes a noticeable amount of time.


问:
How should you arrange your chairs?
You teach a class of students with interesting preferences for how their chairs are arranged. There are 3 very specific requirements they have for how the chairs are arranged:

They most be arranged in a rectangle, even if it means some chairs go empty.

There must be as few empty chairs as possible.

They must be as "squarey" as possible. Squarey-ness is determined by the distance between the width and the height of the rectangle, lower is better. For example, a rectangle that is 4x7 has a squarey-ness of 3.

To be more specific, the "score" of an arrangement is the distance between the width and height plus the number of chairs that would go empty.

Let's take an example. Let's say you have 13 students. You could arrange the chairs any of these ways:

```<code>1x13
2x7
3x5
4x4
</code>```

1x13 is not very squarey. In fact, 1 and 13 are 12 apart, so we give this arrangement 12 points. It also has 0 empty chairs, so we add 0 points, giving this arrangement a score of 12. Not that great.

2x7 is certainly better. 2 and 7 are only 5 apart, so we give this arrangement 5 points. However, if you actually arranged 2 rows of seven chairs, that would take 14 chairs, meaning one chair would be empty. So we add one point, giving this arrangement a score of 6.

We could also do 3x5. 3 and 5 are 2 apart, so +2 points. It takes 15 chairs, meaning we'd have two extra chairs, so another +2 points, for a score of 4.

Last option, 4x4. 4 and 4 are 0 apart, so we give this +0 points. 4x4 takes 16 chairs, so 3 chairs go empty, for a total score of 3. This is the optimal solution.

In case of a tie, the optimal solution is the one with less empty chairs.

The challenge

You must write a program or function that takes an integer and outputs the optimal arrangement of chairs for that number of students. IO can be in any reasonable format. Here is sample output for any number of students from 1 to 100:

```<code>1:  (1, 1)
2:  (1, 2)
3:  (2, 2)
4:  (2, 2)
5:  (2, 3)
6:  (2, 3)
7:  (3, 3)
8:  (3, 3)
9:  (3, 3)
10: (2, 5)
11: (3, 4)
12: (3, 4)
13: (4, 4)
14: (4, 4)
15: (4, 4)
16: (4, 4)
17: (3, 6)
18: (3, 6)
19: (4, 5)
20: (4, 5)
21: (3, 7)
22: (5, 5)
23: (5, 5)
24: (5, 5)
25: (5, 5)
26: (4, 7)
27: (4, 7)
28: (4, 7)
29: (5, 6)
30: (5, 6)
31: (4, 8)
32: (4, 8)
33: (6, 6)
34: (6, 6)
35: (6, 6)
36: (6, 6)
37: (5, 8)
38: (5, 8)
39: (5, 8)
40: (5, 8)
41: (6, 7)
42: (6, 7)
43: (5, 9)
44: (5, 9)
45: (5, 9)
46: (7, 7)
47: (7, 7)
48: (7, 7)
49: (7, 7)
50: (5, 10)
51: (6, 9)
52: (6, 9)
53: (6, 9)
54: (6, 9)
55: (7, 8)
56: (7, 8)
57: (6, 10)
58: (6, 10)
59: (6, 10)
60: (6, 10)
61: (8, 8)
62: (8, 8)
63: (8, 8)
64: (8, 8)
65: (6, 11)
66: (6, 11)
67: (7, 10)
68: (7, 10)
69: (7, 10)
70: (7, 10)
71: (8, 9)
72: (8, 9)
73: (7, 11)
74: (7, 11)
75: (7, 11)
76: (7, 11)
77: (7, 11)
78: (9, 9)
79: (9, 9)
80: (9, 9)
81: (9, 9)
82: (7, 12)
83: (7, 12)
84: (7, 12)
85: (8, 11)
86: (8, 11)
87: (8, 11)
88: (8, 11)
89: (9, 10)
90: (9, 10)
91: (7, 13)
92: (8, 12)
93: (8, 12)
94: (8, 12)
95: (8, 12)
96: (8, 12)
97: (10, 10)
98: (10, 10)
99: (10, 10)
100: (10, 10)
</code>```

As usual, this is code-golf, so standard loopholes apply, and the winner is the shortest answer in bytes.

答:
Julia, <s>61</s> <s>59</s> <s>55</s> <s>53</s> 52 bytes

/ =cld
n->[m=indmax([~i*~-max(i,n/i)for i=1:n]),n/m]
```

<p>Try it online!</p>

<h3>How it works</h3>

<p>The code is equivalent to the following, ungolfed version, where <code>cld</code> is ceiling division.</p>

<pre class="lang-julia prettyprint-override"><code>function chairs(n)
    m = indmin([(i + 1) * (max(i, cld(n, i)) - 1) for i in 1:n])
    return [m, cld(n, m)]
end
</code>```

To find the optimal arrangement, it is clearly sufficient to examine the pairs [i, j], where 1 ≤ i ≤ n and j = ⌈n / i⌉.

The score for such an arrangement is |j - i| + (ij - n), where the second summand is the number of empty chairs. Instead of the actual scores, we can compare scores augmented by a constant, such as ij + |j - i| + 1.

It is sufficient to consider pairs [i, j] where i ≤ j since the arrangements [i, j] and [j, i] are equally valid. We deal with strictly descending pairs by setting j = max(⌈n / i⌉, i) instead, which makes sure that j ≥ i and will yield a suboptimal score if ⌈n / i⌉ < i.

Since j - i ≥ 0, we have ij + |j - i| + 1 = ij + j - i + 1 = (i + 1) × (j - 1), which can be computed in fewer bytes of code.

Finally indmin / indmax gives the index m (and thus the value of i) of the optimal arrangement, which is m by ⌈n / m⌉. Ties are broken by first occurrence, which corresponds to the lowest value of i, therefore the highest value of j - i and thus the lowest value of ij - n (empty chairs).

ContentLicense: CC BY-SA 3.0

Title: How should you arrange your chairs?


问:
Palindrome Hello, World
Your task is to create a program that prints "Greetings, Planet!" exactly to the console. Seems simple enough, right? Well, here's the trick. The code must be a palindrome, meaning it reads from right to left the same as in left to right.
Standard loopholes are NOT allowed.

答:
Hoon, 41 bytes

```<code>"Greetings, Planet!":"!tenalP ,sgniteerG"
</code>```

In Hoon, a:b means "compute a in the context of b". To include a library, for example, you stick a rune that evaluates the rest of your program in the context of the core containing the library. This is possible because cores also contain the entire kernel and stdlib, so you can nest them and still compute.

Because a string literal is just a constant expression that doesn't depend on the context it is being evaluated in at all, we can replace the entire stdlib with just another constant expression and it will evaluate to the same thing.

Title: Palindrome Hello, World

Body:
Hoon, 41 bytes

"Greetings, Planet!":"!tenalP ,sgniteerG"

In Hoon, a:b means "compute a in the context of b". To include a library, for example, you stick a rune that evaluates the rest of your program in the context of the core containing the library. This is possible because cores also contain the entire kernel and stdlib, so you can nest them and still compute.

Because a string literal is just a constant expression that doesn't depend on the context it is being evaluated in at all, we can replace the entire stdlib with just another constant expression and it will evaluate to the same thing.


问:
Compress your code in an image
This is a quine variation.

Introduction

We all write short code, because some obscure reasons, but whatever we do, the'll take up at least 144 pixels/byte (with a 12px font). But what would happen, if we would encode our code in images? This is your task today.

Challenge

You task is to read in your own source code (non-proper quines are allowed, e.g. literally reading the source file), and create an image out of it, by setting the red, green and blue components of a pixel based on the ASCII value of the character.

Example:

We have the string "Hello world!"

```<code>Hello world!
</code>```

Let's convert this to ASCII values:

```<code>72 101 108 108 111 32 119 111 114 108 100 33
</code>```

Map the RGB values to it (If the source code's length is not divisible by 3, use 0s as the remaining characters):

```<code> __________________________________________________
| R | G | B || R | G | B || R | G | B || R | G | B |
----------------------------------------------------
|72 |101|108||108|111|32 ||119|111|114||108|100|33 |
----------------------------------------------------
</code>```

We then create the image with the smallest area out of it. We have 4 sets of RGB values, so the smallest image will be a 2*2 image, going from the top left pixel to the right:

And we get this awfully colored image (resized, so it's at least visible, also proves the fact how small it can get)

Rules/Additional information

There's no input

The output should be as a separate file, or in a separate window.

For multibyte characters, split the character in 2 bytes.

The source code must be at least 1 byte long

The image should be the one from the possible sizes, wich has the closest width/height ratio to 1

The pixel count on the image should exactly be ceil(byte count / 3), no extra pixels should be added

Scoring

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

答:
Actually, 12 bytes

```<code>Q"P6 4 1 255
</code>```

Try it online!

This program also works in Seriously.

This program outputs a PPM image, which is acceptable by default.

Output image (scaled up 50x):

Explanation:

```<code>Q"P6 4 1 255
Q             push source code
 "P6 4 1 255  push header for a 4x1 raw (type P6) 8-bit PPM image (the closing " is implicitly added at EOF)
</code>```

Title: Compress your code in an image

Body:
Actually, 12 bytes

Q"P6 4 1 255

Try it online!

This program also works in Seriously.

This program outputs a PPM image, which is acceptable by default.

Output image (scaled up 50x):

Explanation:

Q"P6 4 1 255
Q             push source code
 "P6 4 1 255  push header for a 4x1 raw (type P6) 8-bit PPM image (the closing " is implicitly added at EOF)


问:
Golf Text into DNA

Text to DNA golf

Challenge

Convert input into a DNA output.

Algorithm

Convert text into ASCII code points (e.g. codegolf -> [99, 111, 100, 101, 103, 111, 108, 102])

String the ASCII codes together (e.g. 99111100101103111108102)

Convert to binary (e.g. 10100111111001101001011010001000011001101011011110000110010111111011000000110)

Pad 0s onto the end to make an even number of characters (e.g. 101001111110011010010110100010000110011010110111100001100101111110110000001100)

Replace 00 with A, 01 with C, 10 with G, and 11 with T (e.g. GGCTTGCGGCCGGAGACGCGGTCTGACGCCTTGTAAATA)

Output

Test Cases

```<code>codegolf > GGCTTGCGGCCGGAGACGCGGTCTGACGCCTTGTAAATA
ppcg > GGCTAATTGTCGCACTT
} > TTGG (padding)
</code>```

Specifications

This is code-golf

Your program must accept spaces in input.

Your program must work for codegolf.

答:
Hoon, <s>148</s> 138 bytes

```<code>|*
*
=+
(scan (reel +< |=({a/@ b/tape} (weld <a> b))) dem)
`tape`(flop (turn (rip 1 (mul - +((mod (met 0 -) 2)))) |=(@ (snag +< "ACGT"))))
</code>```

"abc" is a list of atoms. Interpolate them into strings () while folding over the list, joining them together into a new string. Parse the number with ++dem to get it back to an atom.

Multiply the number by (bitwise length + 1) % 2 to pad it. Use ++rip to disassemble every two byte pair of the atom into a list, map over the list and use the number as an index into the string "ACGT".

```<code>> =a |*
  *
  =+
  (scan (reel +< |=({a/@ b/tape} (weld <a> b))) dem)
  `tape`(flop (turn (rip 1 (mul - +((mod (met 0 -) 2)))) |=(@ (snag +< "ACGT"))))
> (a "codegolf")
"GGCTTGCGGCCGGAGACGCGGTCTGACGCCTTGTAAATA"
> (a "ppcg")
"GGCTAATTGTCGCACTT"
> (a "}")
"TTGG"
</code>```

Title: Golf Text into DNA

Body:
Hoon, <s>148</s> 138 bytes

|*
*
=+
(scan (reel +< |=({a/@ b/tape} (weld <a> b))) dem)
`tape`(flop (turn (rip 1 (mul - +((mod (met 0 -) 2)))) |=(@ (snag +< "ACGT"))))

"abc" is a list of atoms. Interpolate them into strings (<a>) while folding over the list, joining them together into a new string. Parse the number with ++dem to get it back to an atom.

Multiply the number by (bitwise length + 1) % 2 to pad it. Use ++rip to disassemble every two byte pair of the atom into a list, map over the list and use the number as an index into the string "ACGT".

> =a |*
  *
  =+
  (scan (reel +< |=({a/@ b/tape} (weld <a> b))) dem)
  `tape`(flop (turn (rip 1 (mul - +((mod (met 0 -) 2)))) |=(@ (snag +< "ACGT"))))
> (a "codegolf")
"GGCTTGCGGCCGGAGACGCGGTCTGACGCCTTGTAAATA"
> (a "ppcg")
"GGCTAATTGTCGCACTT"
> (a "}")
"TTGG"


答:
PowerShell v4, 64 bytes

```<code>"P6 11 2 255"+[char[]](gc $MyInvocation.MyCommand.Name)|sc a.ppm
</code>```

It gets the content of its own filename, casts the string as a char array, adds some PPM header and sets the content to a.ppm as output. 64 bytes makes it 11x2 pixels:

Title: Compress your code in an image

Body:
This is a quine variation.

Introduction

We all write short code, because some obscure reasons, but whatever we do, the'll take up at least 144 pixels/byte (with a 12px font). But what would happen, if we would encode our code in images? This is your task today.

Challenge

You task is to read in your own source code (non-proper quines are allowed, e.g. literally reading the source file), and create an image out of it, by setting the red, green and blue components of a pixel based on the ASCII value of the character.

Example:

We have the string "Hello world!"

```<code>Hello world!
</code>```

Let's convert this to ASCII values:

```<code>72 101 108 108 111 32 119 111 114 108 100 33
</code>```

Map the RGB values to it (If the source code's length is not divisible by 3, use 0s as the remaining characters):

```<code> __________________________________________________
| R | G | B || R | G | B || R | G | B || R | G | B |
----------------------------------------------------
|72 |101|108||108|111|32 ||119|111|114||108|100|33 |
----------------------------------------------------
</code>```

We then create the image with the smallest area out of it. We have 4 sets of RGB values, so the smallest image will be a 2*2 image, going from the top left pixel to the right:

And we get this awfully colored image (resized, so it's at least visible, also proves the fact how small it can get)

Rules/Additional information

There's no input

The output should be as a separate file, or in a separate window.

For multibyte characters, split the character in 2 bytes.

The source code must be at least 1 byte long

The image should be the one from the possible sizes, wich has the closest width/height ratio to 1

The pixel count on the image should exactly be ceil(byte count / 3), no extra pixels should be added

Scoring

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

Body:
PowerShell v4, 64 bytes

"P6 11 2 255"+[char[]](gc $MyInvocation.MyCommand.Name)|sc a.ppm

It gets the content of its own filename, casts the string as a char array, adds some PPM header and sets the content to a.ppm as output. 64 bytes makes it 11x2 pixels:


答:
Python 2, 64 bytes

lambda n:max((~-i*~min(i,n/i),0-n/i,-i)for i in range(-n,0))[1:]
```

This is an amalgamation of @Lynn's Python answer (from where I took the max(...)[1:] trick) and the algorithm from my Julia answer (which allows a slightly shorter implementation).

Test it on Ideone.

Title: How should you arrange your chairs?

Body:
You teach a class of students with interesting preferences for how their chairs are arranged. There are 3 very specific requirements they have for how the chairs are arranged:

They most be arranged in a rectangle, even if it means some chairs go empty.

There must be as few empty chairs as possible.

They must be as "squarey" as possible. Squarey-ness is determined by the distance between the width and the height of the rectangle, lower is better. For example, a rectangle that is 4x7 has a squarey-ness of 3.

To be more specific, the "score" of an arrangement is the distance between the width and height plus the number of chairs that would go empty.

Let's take an example. Let's say you have 13 students. You could arrange the chairs any of these ways:

```<code>1x13
2x7
3x5
4x4
</code>```

1x13 is not very squarey. In fact, 1 and 13 are 12 apart, so we give this arrangement 12 points. It also has 0 empty chairs, so we add 0 points, giving this arrangement a score of 12. Not that great.

2x7 is certainly better. 2 and 7 are only 5 apart, so we give this arrangement 5 points. However, if you actually arranged 2 rows of seven chairs, that would take 14 chairs, meaning one chair would be empty. So we add one point, giving this arrangement a score of 6.

We could also do 3x5. 3 and 5 are 2 apart, so +2 points. It takes 15 chairs, meaning we'd have two extra chairs, so another +2 points, for a score of 4.

Last option, 4x4. 4 and 4 are 0 apart, so we give this +0 points. 4x4 takes 16 chairs, so 3 chairs go empty, for a total score of 3. This is the optimal solution.

In case of a tie, the optimal solution is the one with less empty chairs.

The challenge

You must write a program or function that takes an integer and outputs the optimal arrangement of chairs for that number of students. IO can be in any reasonable format. Here is sample output for any number of students from 1 to 100:

```<code>1:  (1, 1)
2:  (1, 2)
3:  (2, 2)
4:  (2, 2)
5:  (2, 3)
6:  (2, 3)
7:  (3, 3)
8:  (3, 3)
9:  (3, 3)
10: (2, 5)
11: (3, 4)
12: (3, 4)
13: (4, 4)
14: (4, 4)
15: (4, 4)
16: (4, 4)
17: (3, 6)
18: (3, 6)
19: (4, 5)
20: (4, 5)
21: (3, 7)
22: (5, 5)
23: (5, 5)
24: (5, 5)
25: (5, 5)
26: (4, 7)
27: (4, 7)
28: (4, 7)
29: (5, 6)
30: (5, 6)
31: (4, 8)
32: (4, 8)
33: (6, 6)
34: (6, 6)
35: (6, 6)
36: (6, 6)
37: (5, 8)
38: (5, 8)
39: (5, 8)
40: (5, 8)
41: (6, 7)
42: (6, 7)
43: (5, 9)
44: (5, 9)
45: (5, 9)
46: (7, 7)
47: (7, 7)
48: (7, 7)
49: (7, 7)
50: (5, 10)
51: (6, 9)
52: (6, 9)
53: (6, 9)
54: (6, 9)
55: (7, 8)
56: (7, 8)
57: (6, 10)
58: (6, 10)
59: (6, 10)
60: (6, 10)
61: (8, 8)
62: (8, 8)
63: (8, 8)
64: (8, 8)
65: (6, 11)
66: (6, 11)
67: (7, 10)
68: (7, 10)
69: (7, 10)
70: (7, 10)
71: (8, 9)
72: (8, 9)
73: (7, 11)
74: (7, 11)
75: (7, 11)
76: (7, 11)
77: (7, 11)
78: (9, 9)
79: (9, 9)
80: (9, 9)
81: (9, 9)
82: (7, 12)
83: (7, 12)
84: (7, 12)
85: (8, 11)
86: (8, 11)
87: (8, 11)
88: (8, 11)
89: (9, 10)
90: (9, 10)
91: (7, 13)
92: (8, 12)
93: (8, 12)
94: (8, 12)
95: (8, 12)
96: (8, 12)
97: (10, 10)
98: (10, 10)
99: (10, 10)
100: (10, 10)
</code>```

As usual, this is code-golf, so standard loopholes apply, and the winner is the shortest answer in bytes.

Body:
Python 2, 64 bytes

lambda n:max((~-i*~min(i,n/i),0-n/i,-i)for i in range(-n,0))[1:]

This is an amalgamation of @Lynn's Python answer (from where I took the max(...)[1:] trick) and the algorithm from my Julia answer (which allows a slightly shorter implementation).

Test it on Ideone.


问:
Shortest Pangrammatic Window
A pangram is a sentence or excerpt which contains all twenty-six letters of the alphabet, as is demonstrated in this code golf challenge. However, a pangrammatic window is a pangram in the form of some segment of text, which may end or begin halfway through a word, found somewhere within a larger work. These naturally occur everywhere, being proper subsets of true pangrams, so just verifying if something contains a pangrammatic window would be boring and also it was previously done.

So, we're interested in finding the smallest one there is in a given piece of text based on its letter length! In the shortest possible code in bytes, of course, to fit the theme.

Rules and Guidelines

Receive a string as the input and return  the string of the smallest pangrammatic window in the input if there is one. If there is not, return either a Boolean False or an empty string.

Whether a string is a pangrammatic window or not is case-insensitive and only depends on the 26 letters, not any punctuation or numbers or other odd symbols.

Similarly, a pangrammatic window's letter length is the total number of how many appearances of letters occur in it alone, and not simply the number of every character. The returned value must be smallest based on this count. We're linguists, after all, not programmers.

An output of a pangrammatic window must, however, must be an exact substring of the input, containing the same capitalization and punctuation, etc.

If there are multiple shortest pangrammatic windows of the same letter length, return any one of them.

Test Cases

```<code>'This isn't a pangram.'
==> False

'Everyone knows about that infamous Quick-Brown-Fox (the one who jumped over some lazy ignoramus of a dog so many years ago).'
==> 'Quick-Brown-Fox (the one who jumped over some lazy ig'

'"The five boxing wizards jump quickly." stated Johnny, before beginning to recite the alphabet with a bunch of semicolons in the middle. "ABCDEFGHI;;;;;;;;;;;;;;;JKLMNOPQRSTUVWXYZ!" he shouted to the heavens.'
==> 'ABCDEFGHI;;;;;;;;;;;;;;;JKLMNOPQRSTUVWXYZ'
</code>```

答:
PowerShell (v4), <s>198</s> 156 bytes

param($s)
-join(@(1..($y=$s.Length)|%{$w=$_
0..$y|%{(,@($s[$_..($_+$w)]))}}|?{($_-match'[a-z]'|sort -U).Count-eq26}|sort -Pr {($_-match'[a-z]').count})[0])

# Previous 198 byte golf
$a,$b,$c=@(1..($s="$args").Length|%{$w=$_
0..($s.Length-$w)|%{if((($t=$s[$_..($_+$w)]-match'[a-z]')|sort -u).Count-eq26){(,@($t.Length,$_,$w))}}}|sort -pr{$_[0]})[0]
(-join($s[$b..($b+$c)]),'')[!$a]
```

<h3>Test Cases</h3>

<pre class="lang-powershell prettyprint-override"><code>PS C:\> .\PangramWindow.ps1 "This isn't a pangram."

PS C:\> .\PangramWindow.ps1 'Everyone knows about that infamous Quick-Brown-Fox (the one who jumped over some lazy ignoramus of a dog so many years ago).'
Quick-Brown-Fox (the one who jumped over some lazy ig

PS C:\> .\PangramWindow.ps1 '"The five boxing wizards jump quickly." stated Johnny, before beginning to recite the alphabet with a bunch of semicolons in the middle. "ABCDEFGHI;;;;;;;;;;;;;;;JKLMNOPQRSTUVWXYZ!" he shouted to the heavens.'
ABCDEFGHI;;;;;;;;;;;;;;;JKLMNOPQRSTUVWXYZ!
</code>```

Ungolfed explanation of the original

It's a brute-force nested loop which makes sliding windows of all sizes:

.SubString(0, 1) -> slide window over the string
.SubString(0, 2) -> slide window over the string
..
.SubString(0, string.Length) -> slide window over the string
```

<p>For each window, it filters for only letters (case insensitive regex matching by default), runs the remaining characters through a unique filter, checks if there are 26 unique characters as the pangram test.</p>

<p>All windows with pangrams are turned into triplets of <em>(number of letters including dupes, start index, window length including punctuation)</em>, which get sorted to find the shortest by overall character count, the first one is picked, and the output string built from that.</p>

<p>There's a lot of indexing outside the bounds of the string, which PowerShell usefully returns $null for, instead of throwing exceptions.</p>

<p>NB. the new 156 byte one is the same approach, but rewritten to use the pipeline a lot more.</p>

<pre class="lang-powershell prettyprint-override"><code>$string = "$args"

# increasing window widths, outer loop
$allPangramWindows =  foreach ($windowWidth in 1..$string.Length) {

    # sliding windows over string, inner loop
    0..($string.Length - $windowWidth) | ForEach {

        # slice window out of string, returns a char array
        $tmp = $string[$_..($_+$windowWidth)]

        # filter the char array to drop not-letters
        $tmp = $tmp -match '[a-z]'

        # Drop duplicate letters
        $tmpNoDupes = $tmp | sort -Unique

        # If we're left with a 26 character array, this is a pangrammatic window. Output
        # a PowerShell-style tuple of count of letters, start index, width.
        if($tmpNoDupes.Count -eq 26){
            (,@($tmp.Length,$_,$windowWidth))
        }
    }
}

# Force the result into an array (to handle no-results), sort it
# by the first element (num of letters in the window, total)
$allPangramWindows = @( $allPangramWindows | sort -Property {$_[0]} )

# take element 0, a window with the fewest letters
$windowCharCount, $windowStart, $WindowEnd = $allPangramWindows[0]

# uses the results to find the original string with punctuation and whitespace
if ($windowLen) {
    $string[$windowStart..($windowStart + $windowLen)] -join ''
}
</code>```

NB. not sure the ungolfed version works, because I didn't write that then golf it, it's just for exposition.

Title: Shortest Pangrammatic Window

Body:
PowerShell (v4), <s>198</s> 156 bytes

param($s)
-join(@(1..($y=$s.Length)|%{$w=$_
0..$y|%{(,@($s[$_..($_+$w)]))}}|?{($_-match'[a-z]'|sort -U).Count-eq26}|sort -Pr {($_-match'[a-z]').count})[0])

# Previous 198 byte golf
$a,$b,$c=@(1..($s="$args").Length|%{$w=$_
0..($s.Length-$w)|%{if((($t=$s[$_..($_+$w)]-match'[a-z]')|sort -u).Count-eq26){(,@($t.Length,$_,$w))}}}|sort -pr{$_[0]})[0]
(-join($s[$b..($b+$c)]),'')[!$a]

Test Cases

PS C:\> .\PangramWindow.ps1 "This isn't a pangram."

PS C:\> .\PangramWindow.ps1 'Everyone knows about that infamous Quick-Brown-Fox (the one who jumped over some lazy ignoramus of a dog so many years ago).'
Quick-Brown-Fox (the one who jumped over some lazy ig

PS C:\> .\PangramWindow.ps1 '"The five boxing wizards jump quickly." stated Johnny, before beginning to recite the alphabet with a bunch of semicolons in the middle. "ABCDEFGHI;;;;;;;;;;;;;;;JKLMNOPQRSTUVWXYZ!" he shouted to the heavens.'
ABCDEFGHI;;;;;;;;;;;;;;;JKLMNOPQRSTUVWXYZ!

Ungolfed explanation of the original

It's a brute-force nested loop which makes sliding windows of all sizes:

.SubString(0, 1) -> slide window over the string
.SubString(0, 2) -> slide window over the string
..
.SubString(0, string.Length) -> slide window over the string

For each window, it filters for only letters (case insensitive regex matching by default), runs the remaining characters through a unique filter, checks if there are 26 unique characters as the pangram test.

All windows with pangrams are turned into triplets of (number of letters including dupes, start index, window length including punctuation), which get sorted to find the shortest by overall character count, the first one is picked, and the output string built from that.

There's a lot of indexing outside the bounds of the string, which PowerShell usefully returns $null for, instead of throwing exceptions.

NB. the new 156 byte one is the same approach, but rewritten to use the pipeline a lot more.

$string = "$args"

# increasing window widths, outer loop
$allPangramWindows =  foreach ($windowWidth in 1..$string.Length) {

    # sliding windows over string, inner loop
    0..($string.Length - $windowWidth) | ForEach {

        # slice window out of string, returns a char array
        $tmp = $string[$_..($_+$windowWidth)]

        # filter the char array to drop not-letters
        $tmp = $tmp -match '[a-z]'

        # Drop duplicate letters
        $tmpNoDupes = $tmp | sort -Unique

        # If we're left with a 26 character array, this is a pangrammatic window. Output
        # a PowerShell-style tuple of count of letters, start index, width.
        if($tmpNoDupes.Count -eq 26){
            (,@($tmp.Length,$_,$windowWidth))
        }
    }
}

# Force the result into an array (to handle no-results), sort it
# by the first element (num of letters in the window, total)
$allPangramWindows = @( $allPangramWindows | sort -Property {$_[0]} )

# take element 0, a window with the fewest letters
$windowCharCount, $windowStart, $WindowEnd = $allPangramWindows[0]

# uses the results to find the original string with punctuation and whitespace
if ($windowLen) {
    $string[$windowStart..($windowStart + $windowLen)] -join ''
}

NB. not sure the ungolfed version works, because I didn't write that then golf it, it's just for exposition.


问:
Normal and visual string reversion
Write some code that acts as a cat program. That is, to input a string and output it as is. But the normal reversion of your code must output the normal reversion of the input string. And the visual reversion of your code must output the visual reversion of the input string.

The normal reversion is the reversed character sequence of a string. The visual reversion is the normal reversion with the characters ()[]{}<> replaced by )(][}{>< respectively.

You could use any codepage that has the characters ()[]{}<> and is published before this challenge to define characters. You must use the same codepage for all your code. Your original code must be valid in this codepage, and applying either of your reversed code to that should yield itself.

This is code-golf, shortest code in bytes wins.

Example

For the string AB(XY), its normal and visual reversions are )YX(BA and (YX)BA respectively.

If your code (in a hypothetical language) is AB(XY), then the code )YX(BA and (YX)BA should output the normal and visual reversions of the input string respectively. And AB(XY) should act as a cat program.

答:
GolfScript, <s>32</s> 28 bytes

```<code>#%{=1-[=-\7?@.`{[(<>)]}.}%1-
</code>```

Try it online!

Normal reversion:

```<code>-1%}.}])><([{`.@?7\-=[-1={%#
</code>```

Try it online!

Visual reversion:

```<code>-1%{.{[(<>)]}`.@?7\-=]-1=}%#
</code>```

Try it online!

The fact that an unmatched } terminates the program in GolfScript, made this fairly simple. However, I'm pretty sure that my code for swapping the brackets isn't optimal yet.

Title: Normal and visual string reversion

Body:
GolfScript, <s>32</s> 28 bytes

#%{=1-[=-\7?@.`{[(<>)]}.}%1-

Try it online!

Normal reversion:

-1%}.}])><([{`.@?7\-=[-1={%#

Try it online!

Visual reversion:

-1%{.{[(<>)]}`.@?7\-=]-1=}%#

Try it online!

The fact that an unmatched } terminates the program in GolfScript, made this fairly simple. However, I'm pretty sure that my code for swapping the brackets isn't optimal yet.


答:
CJam, 21 bytes

```<code>qe#ere$_"}{][><)("%Wq
</code>```

Test it here.

Normal reversion:

```<code>qW%"()<>[]{}"_$ere#eq
</code>```

Test it here.

Visual reversion:

```<code>qW%")(><][}{"_$ere#eq
</code>```

Test it here.

Explanation

First, the normal code:

```<code>qe#ere$_"}{][><)("%Wq
</code>```

This is simple: q reads all input, e# comments out the remainder of the program, and the input is printed implicitly at the end.

Now the normal reversion:

```<code>q            e# Read all input.
W%           e# Reverse it.
"()<>[]{}"   e# Push this string.
_$           e# Duplicate and sort it. However, the string is already sorted
             e# so we just get two copies of it.
er           e# Transliteration (i.e. character-wise substitution). But since the
             e# source and target string are identical, the reversed input
             e# is left unchanged.
e#eq            Just a comment...
</code>```

And finally, the visual reversion:

```<code>q            e# Read all input.
W%           e# Reverse it.
")(><][}{"   e# Push this string.
_$           e# Duplicate and sort it. This gives us "()<>[]{}", i.e. the
             e# same string with each bracket pair swapped.
er           e# Transliteration (i.e. character-wise substitution). This
             e# time, this toggles all the brackets in the reversed input
             e# completing the visual reversion.
e#eq            Just a comment...
</code>```

Title: Normal and visual string reversion

Body:
Write some code that acts as a cat program. That is, to input a string and output it as is. But the normal reversion of your code must output the normal reversion of the input string. And the visual reversion of your code must output the visual reversion of the input string.

The normal reversion is the reversed character sequence of a string. The visual reversion is the normal reversion with the characters ()[]{}<> replaced by )(][}{>< respectively.

You could use any codepage that has the characters ()[]{}<> and is published before this challenge to define characters. You must use the same codepage for all your code. Your original code must be valid in this codepage, and applying either of your reversed code to that should yield itself.

This is code-golf, shortest code in bytes wins.

Example

For the string AB(XY), its normal and visual reversions are )YX(BA and (YX)BA respectively.

If your code (in a hypothetical language) is AB(XY), then the code )YX(BA and (YX)BA should output the normal and visual reversions of the input string respectively. And AB(XY) should act as a cat program.

Body:
CJam, 21 bytes

qe#ere$_"}{][><)("%Wq

Test it here.

Normal reversion:

qW%"()<>[]{}"_$ere#eq

Test it here.

Visual reversion:

qW%")(><][}{"_$ere#eq

Test it here.

Explanation

First, the normal code:

qe#ere$_"}{][><)("%Wq

This is simple: q reads all input, e# comments out the remainder of the program, and the input is printed implicitly at the end.

Now the normal reversion:

q            e# Read all input.
W%           e# Reverse it.
"()<>[]{}"   e# Push this string.
_$           e# Duplicate and sort it. However, the string is already sorted
             e# so we just get two copies of it.
er           e# Transliteration (i.e. character-wise substitution). But since the
             e# source and target string are identical, the reversed input
             e# is left unchanged.
e#eq            Just a comment...

And finally, the visual reversion:

q            e# Read all input.
W%           e# Reverse it.
")(><][}{"   e# Push this string.
_$           e# Duplicate and sort it. This gives us "()<>[]{}", i.e. the
             e# same string with each bracket pair swapped.
er           e# Transliteration (i.e. character-wise substitution). This
             e# time, this toggles all the brackets in the reversed input
             e# completing the visual reversion.
e#eq            Just a comment...


答:
05AB1E, 16 bytes

Uses the fact that 05AB1E has a constant predefined to "()<>[]{}" and isn't affected the visually reversion.

Code:

```<code>,q‡"}{][><)("užR
</code>```

Explanation:

```<code>,                 # Pop and print the input.
 q                # Quit.
  ‡"}{][><)("užR  # This part is ignored.
</code>```

Try it online!

Reversed:

```<code>Ržu"()<>[]{}"‡q,
</code>```

Explanation:

```<code>R                 # Reverse the input.
 žu               # Short for "()<>[]{}".
   "()<>[]{}"     # Push this string.
             ‡    # Transliterate (no-op, since everything is transliterated to itself).
              q   # Quit and implicitly print.
               ,  # This part is ignored.
</code>```

Try it online!

Visually reversed:

```<code>Ržu")(><][}{"‡q,
</code>```

Explanation:

```<code>R                 # Reverse the input.
 žu               # Short for "()<>[]{}".
   ")(><][}{"     # Push this string.
             ‡    # Transliterate (giving the visually reversed string).
              q   # Quit and implicitly print.
               ,  # This part is ignored.
</code>```

Try it online!

Uses CP-1252 encoding.

Title: Normal and visual string reversion

Body:
05AB1E, 16 bytes

Uses the fact that 05AB1E has a constant predefined to "()<>[]{}" and isn't affected the visually reversion.

Code:

,q‡"}{][><)("užR

Explanation:

,                 # Pop and print the input.
 q                # Quit.
  ‡"}{][><)("užR  # This part is ignored.

Try it online!

Reversed:

Ržu"()<>[]{}"‡q,

Explanation:

R                 # Reverse the input.
 žu               # Short for "()<>[]{}".
   "()<>[]{}"     # Push this string.
             ‡    # Transliterate (no-op, since everything is transliterated to itself).
              q   # Quit and implicitly print.
               ,  # This part is ignored.

Try it online!

Visually reversed:

Ržu")(><][}{"‡q,

Explanation:

R                 # Reverse the input.
 žu               # Short for "()<>[]{}".
   ")(><][}{"     # Push this string.
             ‡    # Transliterate (giving the visually reversed string).
              q   # Quit and implicitly print.
               ,  # This part is ignored.

Try it online!

Uses CP-1252 encoding.


答:
Javascript, 98 bytes

My first code golf, so I post anyway!

```<code>f=n=>{for(o=1/0,i=1;i<=n;i++)for(j=n;i*j>=n;j--)t=i*j-n+Math.abs(i-j),o>t&&(o=t,a=[i,j]);return a}
</code>```

Initially my o was an empty object and I checked if o.a was empty, so it was a special case at the first round. But I found the 1/0 trick in edc65's answer to initialize the variable to Infinity.

Title: How should you arrange your chairs?

Body:
Javascript, 98 bytes

My first code golf, so I post anyway!

f=n=>{for(o=1/0,i=1;i<=n;i++)for(j=n;i*j>=n;j--)t=i*j-n+Math.abs(i-j),o>t&&(o=t,a=[i,j]);return a}

Initially my o was an empty object and I checked if o.a was empty, so it was a special case at the first round. But I found the 1/0 trick in edc65's answer to initialize the variable to Infinity.


问:
Find the last three words of each paragraph if they are shorter than 20 characters in total
Based on my SO question, but more specifically:

Find a RegEx such that, given a text where paragraphs end with an empty line (or $ at the very end), match the up to twenty last characters of a paragraph excluding the \r or $ but no more than three complete "words" including the "separators" in between and the punctuation following it. The following constraints apply:

"words" also include abbreviations and the like (and thus punctuation), i.e. "i.e." and "non-trivial" count as one word each

whitespaces are "separators"

isolated dashes do not count as "words" but as "separators"

"separators" before the first word must not be included

trailing punctuation counts to that limit, but not the leading one nor the linebreaks and $ that must not be in the matching group

whether trailing punctuation is included in the match or not is up to you

Some examples:

The early bird catches the worm. Two words.

But only if they got up - in time.

Here we have a supercalifragilisticexpialidocious etc. sentence.

Short words.

Try accessing the .html now, please.

Vielen Dank und viele Grüße.

Did any-one try this?

Score is given in bytesteps: bytes multiplied by amount of steps according to https://regex101.com, but there are three penalties:

if the upper limit of words cannot trivially+ be modified: +10%

if the upper limit of character count cannot trivially+ be modified: +10%

failure to handle unicode used in actual words: add the percentage of world population speaking the language according to Wikipedia the failing word stems from. Example: Failing to match the German word "Grüße" as a word => +1.39%. Whether you consider a language's letters as single characters or count the bytes to utf8-encode them is up to you. The penalty does not have to be applied before someone actually provides a counter-example, so feel free to demote your competitors ;)

Since this is my first challenge, please suggest any clarifications. I assume regular-expression means there are no "loopholes" to exclude.

+ With trivially modified I mean expressions such as {0,2} and {21} are valid but repeating something three times (which would have to be re-repeated to increase the amount words) is not.

Body:
<s>37 bytes * 1403 steps = 51911 bytesteps</s>

<s>34 bytes * 1036 steps = 35224 bytesteps</s>

37 bytes * 666 steps = 24642 bytesteps

(?<!\S)(?!.{21})\S+(( | - )\S+){0,2}$

Verify it here!


答:
Haskell, 123 bytes

```<code>import Data.Lists
import Data.Char
h x=take 1$sortOn((1<$).filter isAlpha)[e|e<-powerslice x,['a'..'z']\\map toLower e==""]
</code>```

Defines a function h, which returns the empty list if there's no pangrammatic window or a one element list with the minimum window.  Usage example:

```<code>*Main>  h "'The five boxing wizards jump quickly.' stated Johnny, before beginning to recite the alphabet with a bunch of semicolons in the middle. 'ABCDEFGHI;;;;;;;;;;;;;;;JKLMNOPQRSTUVWXYZ!' he shouted to the heavens."
[". 'ABCDEFGHI;;;;;;;;;;;;;;;JKLMNOPQRSTUVWXYZ"]
</code>```

How it works:

```<code>          [e|e<-powerslice x                  ]  -- for all continuous subsequences
                                                 -- e of the input
                ,['a'..'z']\\map toLower e==""   -- keep those where the list
                                                 -- difference with all letters is
                                                 -- empty, i.e. every letter appears
                                                 -- at least once
    sortOn((1<$).filter isAlpha)                 -- sort all remaining lists on
                                                 -- their length after removing all
                                                 -- non-letters -> (1<$) see below
take 1                                           -- take the first, i.e. the minimum

calculating the length of a list: we're not interested in the length itself, but
in the relative order of the length. (1<$) replaces each element in a list with
the number 1, e.g. "abc" -> "111", "abcd" -> "1111", etc. Such '1'-strings have
the same order as the length of the original list. One byte saved!
</code>```

Title: Shortest Pangrammatic Window

Body:
A pangram is a sentence or excerpt which contains all twenty-six letters of the alphabet, as is demonstrated in this code golf challenge. However, a pangrammatic window is a pangram in the form of some segment of text, which may end or begin halfway through a word, found somewhere within a larger work. These naturally occur everywhere, being proper subsets of true pangrams, so just verifying if something contains a pangrammatic window would be boring and also it was previously done.

So, we're interested in finding the smallest one there is in a given piece of text based on its letter length! In the shortest possible code in bytes, of course, to fit the theme.

Rules and Guidelines

Receive a string as the input and return  the string of the smallest pangrammatic window in the input if there is one. If there is not, return either a Boolean False or an empty string.

Whether a string is a pangrammatic window or not is case-insensitive and only depends on the 26 letters, not any punctuation or numbers or other odd symbols.

Similarly, a pangrammatic window's letter length is the total number of how many appearances of letters occur in it alone, and not simply the number of every character. The returned value must be smallest based on this count. We're linguists, after all, not programmers.

An output of a pangrammatic window must, however, must be an exact substring of the input, containing the same capitalization and punctuation, etc.

If there are multiple shortest pangrammatic windows of the same letter length, return any one of them.

Test Cases

```<code>'This isn't a pangram.'
==> False

'Everyone knows about that infamous Quick-Brown-Fox (the one who jumped over some lazy ignoramus of a dog so many years ago).'
==> 'Quick-Brown-Fox (the one who jumped over some lazy ig'

'"The five boxing wizards jump quickly." stated Johnny, before beginning to recite the alphabet with a bunch of semicolons in the middle. "ABCDEFGHI;;;;;;;;;;;;;;;JKLMNOPQRSTUVWXYZ!" he shouted to the heavens.'
==> 'ABCDEFGHI;;;;;;;;;;;;;;;JKLMNOPQRSTUVWXYZ'
</code>```

Body:
Haskell, 123 bytes

import Data.Lists
import Data.Char
h x=take 1$sortOn((1<$).filter isAlpha)[e|e<-powerslice x,['a'..'z']\\map toLower e==""]

Defines a function h, which returns the empty list if there's no pangrammatic window or a one element list with the minimum window.  Usage example:

*Main>  h "'The five boxing wizards jump quickly.' stated Johnny, before beginning to recite the alphabet with a bunch of semicolons in the middle. 'ABCDEFGHI;;;;;;;;;;;;;;;JKLMNOPQRSTUVWXYZ!' he shouted to the heavens."
[". 'ABCDEFGHI;;;;;;;;;;;;;;;JKLMNOPQRSTUVWXYZ"]

How it works:

          [e|e<-powerslice x                  ]  -- for all continuous subsequences
                                                 -- e of the input
                ,['a'..'z']\\map toLower e==""   -- keep those where the list
                                                 -- difference with all letters is
                                                 -- empty, i.e. every letter appears
                                                 -- at least once
    sortOn((1<$).filter isAlpha)                 -- sort all remaining lists on
                                                 -- their length after removing all
                                                 -- non-letters -> (1<$) see below
take 1                                           -- take the first, i.e. the minimum

calculating the length of a list: we're not interested in the length itself, but
in the relative order of the length. (1<$) replaces each element in a list with
the number 1, e.g. "abc" -> "111", "abcd" -> "1111", etc. Such '1'-strings have
the same order as the length of the original list. One byte saved!


答:
Haskell, 124 bytes

Forward:

```<code>f=id
--esrever.q pam=2>1|esrever=2<1|f;x=x q;')'='(' q;'('=')' q;']'='[' q;'['=']' q;'>'='<' q;'<'='>' q;'}'='{' q;'{'='}' q
</code>```

Normal reverse:

```<code>q '}'='{';q '{'='}';q '>'='<';q '<'='>';q ']'='[';q '['=']';q ')'='(';q '('=')';q x=x;f|1<2=reverse|1>2=map q.reverse--
di=f
</code>```

Visual reverse:

```<code>q '{'='}';q '}'='{';q '<'='>';q '>'='<';q '['=']';q ']'='[';q '('=')';q ')'='(';q x=x;f|1>2=reverse|1<2=map q.reverse--
di=f
</code>```

Each version defines a function f which takes and returns a string. In forward mode f is the identity function id, the rest of the code is a comment. In normal reverse mode the guard 1<2 in f is True, so reverse is applied. In visual reverse mode, the < is switched to > and the guard is False. The second guard is just the other way around and Truein visual mode, so additionally q is applied which switches "()<>{}[]".

```<code>f|1<2=reverse|1>2=map q.reverse      -- normal reverse mode
f|1>2=reverse|1<2=map q.reverse      -- visual reverse mode
</code>```

Besides <and > in the guards, my code doesn't use any of the brackets, so they can't be messed up.

Title: Normal and visual string reversion

Body:
Haskell, 124 bytes

Forward:

f=id
--esrever.q pam=2>1|esrever=2<1|f;x=x q;')'='(' q;'('=')' q;']'='[' q;'['=']' q;'>'='<' q;'<'='>' q;'}'='{' q;'{'='}' q

Normal reverse:

q '}'='{';q '{'='}';q '>'='<';q '<'='>';q ']'='[';q '['=']';q ')'='(';q '('=')';q x=x;f|1<2=reverse|1>2=map q.reverse--
di=f

Visual reverse:

q '{'='}';q '}'='{';q '<'='>';q '>'='<';q '['=']';q ']'='[';q '('=')';q ')'='(';q x=x;f|1>2=reverse|1<2=map q.reverse--
di=f

Each version defines a function f which takes and returns a string. In forward mode f is the identity function id, the rest of the code is a comment. In normal reverse mode the guard 1<2 in f is True, so reverse is applied. In visual reverse mode, the < is switched to > and the guard is False. The second guard is just the other way around and Truein visual mode, so additionally q is applied which switches "()<>{}[]".

f|1<2=reverse|1>2=map q.reverse      -- normal reverse mode
f|1>2=reverse|1<2=map q.reverse      -- visual reverse mode

Besides <and > in the guards, my code doesn't use any of the brackets, so they can't be messed up.


答:
MATL, <s>26</s> <s>24</s> <s>22</s> 16 bytes

Forward

```<code>DPEXSt'><}{][)('
</code>```

Try it Online!

Explanation:

```<code>                % Implicitly grab the input as a string
D               % Pop the top of the stack and display it
P               % Tries to flip the top element on the stack but errors out
                % because the stack is empty. Program terminates.
EXSt'><}{][)('  % Not executed
</code>```

Normal reversion:

```<code>'()[]{}<>'tSXEPD
</code>```

Try it Online!

Explanation:

```<code>            % Implicitly grab input as a string
'()[]{}<>'  % String literal (search string)
tS          % Duplicate and sort to create the replacement string: '()[]{}<>'
XE          % Replace all entries in the input using the search and replacement strings.
            % Corresponding characters in the strings are used for the replacement.
            % Effectively a no-op
P           % Flip the string
D           % Explicitly display result

</code>```

Visual reversion:

```<code>')(][}{><'tSXEPD
</code>```

Try it Online!

Explanation:

```<code>            % Implicitly grab the input as a string
')(][}{><'  % String literal (search string)
tS          % Duplicate and sort to create the replacement string: '()[]{}<>'
XE          % Replace all entries in the input using the search and replacement strings.
            % Corresponding characters in the strings are used for the replacement.
P           % Flip the result
D           % Explicitly display the result
</code>```

Title: Normal and visual string reversion

Body:
MATL, <s>26</s> <s>24</s> <s>22</s> 16 bytes

Forward

DPEXSt'><}{][)('

Try it Online!

Explanation:

                % Implicitly grab the input as a string
D               % Pop the top of the stack and display it
P               % Tries to flip the top element on the stack but errors out
                % because the stack is empty. Program terminates.
EXSt'><}{][)('  % Not executed

Normal reversion:

'()[]{}<>'tSXEPD

Try it Online!

Explanation:

            % Implicitly grab input as a string
'()[]{}<>'  % String literal (search string)
tS          % Duplicate and sort to create the replacement string: '()[]{}<>'
XE          % Replace all entries in the input using the search and replacement strings.
            % Corresponding characters in the strings are used for the replacement.
            % Effectively a no-op
P           % Flip the string
D           % Explicitly display result

Visual reversion:

')(][}{><'tSXEPD

Try it Online!

Explanation:

            % Implicitly grab the input as a string
')(][}{><'  % String literal (search string)
tS          % Duplicate and sort to create the replacement string: '()[]{}<>'
XE          % Replace all entries in the input using the search and replacement strings.
            % Corresponding characters in the strings are used for the replacement.
P           % Flip the result
D           % Explicitly display the result


问:
Output the Current Time

Challenge

You must output the current time continuously (until cancelled by an interrupt), once every second, by any of the following means:

It must be in 24-hour or AM/PM format.

If it is the former, it must be spaced out with colons (i.e. 15:47:36).

If it is the latter, it must be spaced out with colons and have the AM/PM following (i.e. 3:47:36 PM)

It may be pulled from the internet.

It may be the system time.

It must output any naturally accessible form of output which supports text that you choose.

Output may have extra information aside of the time in it, but you must guarantee one, and only one, output of time per second.

The continuous output must be a second apart - if you choose to wait until the second changes between outputs, that is fine. If you wait a second between each output, that is perfectly acceptable, despite the eventual loss of accuracy.

Since this is a catalog, languages created after this challenge are allowed to compete. Note that there must be an interpreter so the submission can be tested. It is allowed (and even encouraged) to write this interpreter yourself for a previously unimplemented language. Other than that, all the standard rules of code-golf must be obeyed. Submissions in most languages will be scored in bytes in an appropriate preexisting encoding (usually UTF-8).

Catalog

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

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

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

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

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

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

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

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

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

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

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

```

答:
Rebol, 25 bytes

```<code>forever[print now wait 1]
</code>```

This prints day & time (24 hour HH:MM:SS).  For an extra 5 bytes you can make it print just the time: forever[print now/time wait 1]

Title: Output the Current Time

Body:
Rebol, 25 bytes

forever[print now wait 1]

This prints day & time (24 hour HH:MM:SS).  For an extra 5 bytes you can make it print just the time: forever[print now/time wait 1]


问:
Smallest integers after N divisible by 2, 3, and 4
Give credit to whom credit is due.

Objective Given an integer N > 0, out the smallest integers A, B, and C so that:

All of A, B, and C are strictly greater than N;

2 divides A;

3 divides B;

and 4 divides C.

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

Test cases

```<code>N => A, B, C
1 => 2, 3, 4
4 => 6, 6, 8
43 => 44, 45, 44
123 => 124, 126, 124
420 => 422, 423, 424
31415 => 31416, 31416, 31416
1081177 => 1081178, 1081179, 1081180
</code>```

答:
Scala, 268 bytes

```<code>def logic(y:Int)(x: Int) = (x)%y ==0

def fun(n:Int,  logic: Int => Boolean) : Int = {
  if (logic(n)) n else fun(n+1, logic)
}
for {
    N <- Array[Int](1,4, 43, 123, 420, 31415, 1081177)
    ABC <- Array[Int](2,3,4)
    res = fun(x+1, logic(i) _)
    } yield res
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Scala, 268 bytes

def logic(y:Int)(x: Int) = (x)%y ==0

def fun(n:Int,  logic: Int => Boolean) : Int = {
  if (logic(n)) n else fun(n+1, logic)
}
for {
    N <- Array[Int](1,4, 43, 123, 420, 31415, 1081177)
    ABC <- Array[Int](2,3,4)
    res = fun(x+1, logic(i) _)
    } yield res


答:
Oracle SQL 11.2, 173 bytes

SELECT MIN(x||','||y)KEEP(DENSE_RANK FIRST ORDER BY y-x+(y*x-:1))FROM(SELECT CEIL(LEVEL/:1)x,CEIL(MOD(LEVEL+.1,:1))y FROM DUAL CONNECT BY LEVEL<=:1*:1)WHERE x<=y AND:1<=x*y;
```

<p>Un-golfed</p>

<pre class="lang-sql prettyprint-override"><code>SELECT MIN(x||','||y)KEEP(DENSE_RANK FIRST ORDER BY y-x+(y*x-:1))  -- Keeps the minimal score
FROM   (SELECT CEIL(LEVEL/:1)x,CEIL(MOD(LEVEL+.1,:1))y FROM DUAL CONNECT BY LEVEL<=:1*:1) -- Generate x,y combinations
WHERE  x<=y AND :1<=x*y  -- Filters out wrong combinations
</code>```

Title: How should you arrange your chairs?

Body:
Oracle SQL 11.2, 173 bytes

SELECT MIN(x||','||y)KEEP(DENSE_RANK FIRST ORDER BY y-x+(y*x-:1))FROM(SELECT CEIL(LEVEL/:1)x,CEIL(MOD(LEVEL+.1,:1))y FROM DUAL CONNECT BY LEVEL<=:1*:1)WHERE x<=y AND:1<=x*y;

Un-golfed

SELECT MIN(x||','||y)KEEP(DENSE_RANK FIRST ORDER BY y-x+(y*x-:1))  -- Keeps the minimal score
FROM   (SELECT CEIL(LEVEL/:1)x,CEIL(MOD(LEVEL+.1,:1))y FROM DUAL CONNECT BY LEVEL<=:1*:1) -- Generate x,y combinations
WHERE  x<=y AND :1<=x*y  -- Filters out wrong combinations


答:
Bash + common linux utilities, 51

2 bytes saved thanks to @jimmy23013

2 bytes saved thanks to @AdamKatz

#'><}{][)(' `P5BD706D5AC79E196iFe- cd` rt|ver|
\cat
```
<p>Normal reversion:</p>
<pre class="lang-bash prettyprint-override"><code>tac\
|rev|tr `dc -eFi691E97CA5D607DB5P` '()[]{}<>'#
</code>```

Visual reversion:

tac\
|rev|tr `dc -eFi691E97CA5D607DB5P` ')(][}{><'#
```

The main trick here is that the string ()[]{}<> is encoded as 691E97CA5D607DB5 (base 15).  The resulting dc command will yield this same result after either kind of reversion.  However the '()[]{}<>' string literal is sensitive to the reversal type.

tac is required to reverse order of input lines and rev is required to reverse the characters of each line.  Any ASCII input should be acceptable.

Title: Normal and visual string reversion

Body:
Bash + common linux utilities, 51

2 bytes saved thanks to @jimmy23013

2 bytes saved thanks to @AdamKatz

#'><}{][)(' `P5BD706D5AC79E196iFe- cd` rt|ver|
\cat

Normal reversion:

tac\
|rev|tr `dc -eFi691E97CA5D607DB5P` '()[]{}<>'#

Visual reversion:

tac\
|rev|tr `dc -eFi691E97CA5D607DB5P` ')(][}{><'#

The main trick here is that the string ()[]{}<> is encoded as 691E97CA5D607DB5 (base 15).  The resulting dc command will yield this same result after either kind of reversion.  However the '()[]{}<>' string literal is sensitive to the reversal type.

tac is required to reverse order of input lines and rev is required to reverse the characters of each line.  Any ASCII input should be acceptable.


问:
Tips for golfing in JavaScript
What general tips do you have for golfing in JavaScript? I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to JavaScript (e.g. "remove comments" is not an answer).

Note: Also see Tips for Golfing in ECMAScript 6 and above

答:
Function

If you need a function in as few bytes as possible, and any function will do (perhaps you just want to access some of the goodies from Function.prototype), then here are some options (starting with large ones):

```<code>Function.prototype
[].map
Date
CSS     (available in modern browsers)
Map     (ES6: available in Node and modern browsers)
Set     (ES6: available in Node and modern browsers)
URL     (available in very old browsers, but not in Node)
</code>```

So if you want a reference to the call function, you can get it like this:

```<code>c=URL.call
</code>```

Title: Tips for golfing in JavaScript

Body:
Function

If you need a function in as few bytes as possible, and any function will do (perhaps you just want to access some of the goodies from Function.prototype), then here are some options (starting with large ones):

Function.prototype
[].map
Date
CSS     (available in modern browsers)
Map     (ES6: available in Node and modern browsers)
Set     (ES6: available in Node and modern browsers)
URL     (available in very old browsers, but not in Node)

So if you want a reference to the call function, you can get it like this:

c=URL.call


问:
Will the beam hit?
A laser shoots a straight beam in one of the four orthogonal directions, indicated by <>^v. Determine whether it will hit the target O on a rectangular grid.

Each of these will hit (True):

```<code>.....
...O.
.....
...^.
.....

>O.
...

v....
O....

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

These will miss (False):

```<code>......
......
.^..O.

......
.....>
O.....
......
......

.O.
...
.v.

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

Input: A rectangular grid of ., sized at least 2x2, with exactly one target O and one laser that's one of <>^v. The lines can be a list of strings, a 2D array or nested list of characters, or a single newline-separated string with an optional trailing newline.

Output: A consistent truthy value if the laser beam hits the target, and a consistent falsy value if it misses.

I'll consider submissions that don't use regular expressions (or built-in pattern-based string matching) as a separate category. If you put (no regex) after the language name, your answer will appear separately in the leaderboard.

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

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

```

答:
MATL (no regex), <s>26</s> <s>25</s> <s>24</s> 22 bytes

```<code>'>v<^'XJymfX!tZpYswJm)
</code>```

Try it Online!

Modified version for all test cases

Explanation

```<code>        % Implicitly grab input
'>v<^'  % String literal indicating the direction chars
XJ      % Store in the J clipboard
y       % Copy the input from the bottom of the stack
m       % Check to see which of the direction chars is in the input. The
        % result is a 1 x 4 logical array with a 1 for the found direction char
f       % Get the 1-based index into '>v<^' of this character
X!      % Rotate the input board 90 degrees N times where N is the index. This
        % Way we rotate the board so that, regardless of the direction char,
        % the direction char should always be BELOW the target in the same column
t       % Duplicate
Zp      % Determine if any elements are prime ('O' is the only prime)
Ys      % Compute the cumulative sum of each column
w       % Flip the top two stack elements
J       % Grab '>v<^' from clipboard J
m       % Create a logical matrix the size of the input where it is 1 where
        % the direction char is and 0 otherwise
)       % Use this to index into the output of the cumulative sum. If the
        % direction char is below 'O' in a column, this will yield a 1 and 0 otherwise
        % Implicitly display the result
</code>```

Title: Will the beam hit?

Body:
MATL (no regex), <s>26</s> <s>25</s> <s>24</s> 22 bytes

'>v<^'XJymfX!tZpYswJm)

Try it Online!

Modified version for all test cases

Explanation

        % Implicitly grab input
'>v<^'  % String literal indicating the direction chars
XJ      % Store in the J clipboard
y       % Copy the input from the bottom of the stack
m       % Check to see which of the direction chars is in the input. The
        % result is a 1 x 4 logical array with a 1 for the found direction char
f       % Get the 1-based index into '>v<^' of this character
X!      % Rotate the input board 90 degrees N times where N is the index. This
        % Way we rotate the board so that, regardless of the direction char,
        % the direction char should always be BELOW the target in the same column
t       % Duplicate
Zp      % Determine if any elements are prime ('O' is the only prime)
Ys      % Compute the cumulative sum of each column
w       % Flip the top two stack elements
J       % Grab '>v<^' from clipboard J
m       % Create a logical matrix the size of the input where it is 1 where
        % the direction char is and 0 otherwise
)       % Use this to index into the output of the cumulative sum. If the
        % direction char is below 'O' in a column, this will yield a 1 and 0 otherwise
        % Implicitly display the result


答:
Pyth, 43 bytes

```<code>KxJ"^<v>"h@Js.z}\Ohc_W>K1hf}@JKTCW!%K2.z@JK
</code>```

Live demo.

Title: Will the beam hit?

Body:
A laser shoots a straight beam in one of the four orthogonal directions, indicated by <>^v. Determine whether it will hit the target O on a rectangular grid.

Each of these will hit (True):

```<code>.....
...O.
.....
...^.
.....

>O.
...

v....
O....

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

These will miss (False):

```<code>......
......
.^..O.

......
.....>
O.....
......
......

.O.
...
.v.

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

Input: A rectangular grid of ., sized at least 2x2, with exactly one target O and one laser that's one of <>^v. The lines can be a list of strings, a 2D array or nested list of characters, or a single newline-separated string with an optional trailing newline.

Output: A consistent truthy value if the laser beam hits the target, and a consistent falsy value if it misses.

I'll consider submissions that don't use regular expressions (or built-in pattern-based string matching) as a separate category. If you put (no regex) after the language name, your answer will appear separately in the leaderboard.

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

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

```

Body:
Pyth, 43 bytes

KxJ"^<v>"h@Js.z}\Ohc_W>K1hf}@JKTCW!%K2.z@JK

Live demo.


问:
Print NxN spiral of ascending numbers
The numbers should be printed with leading zeroes in a field with length = (number of digits of N^2).

Input (N):

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

Output:

```<code>01 12 11 10
02 13 16 09
03 14 15 08
04 05 06 07
</code>```

I am interested in the algorithm and the cleanliness of the implementation.
So, the white space does not count and the upper limit for N is 42.

答:
Perl, 178 chars

Uses Math::Complex and maintains the current direction in a complex variable (1/i/-1/.i). Run with:

```<code>$ perl -MMath::Complex spiral.pl
</code>```

Put N in $l.

```<code># $l = shift;
$d=i;
$x=0;
until($s{$x}){
    $s{$x}=++$n;
    $x+=$d;
    $d*=-i if
        Re($x)==Im($x)+(Re($x)<$l/2)
        ||Re($x)==$l-1-Im($x)
}
for$y(0..$l-1){
    printf'%0'.length($l**2).'d ',$s{$_+i*$y}for 0..$l-1;
    print"\n"
}
</code>```

Title: Print NxN spiral of ascending numbers

Body:
Perl, 178 chars

Uses Math::Complex and maintains the current direction in a complex variable (1/i/-1/.i). Run with:

$ perl -MMath::Complex spiral.pl

Put N in $l.

# $l = shift;
$d=i;
$x=0;
until($s{$x}){
    $s{$x}=++$n;
    $x+=$d;
    $d*=-i if
        Re($x)==Im($x)+(Re($x)<$l/2)
        ||Re($x)==$l-1-Im($x)
}
for$y(0..$l-1){
    printf'%0'.length($l**2).'d ',$s{$_+i*$y}for 0..$l-1;
    print"\n"
}

ContentLicense: CC BY-SA 2.5


答:
Snails, 19 bytes

```<code>\>|\<l|\^u|\vd).,\O
</code>```

The spec for this one can be implemented as literally as possible, no thinking required.

Title: Will the beam hit?

Body:
Snails, 19 bytes

\>|\<l|\^u|\vd).,\O

The spec for this one can be implemented as literally as possible, no thinking required.


答:
Python 3 (no regex), 184 bytes.

Hooray for eval hacking!

```<code>def f(a,o=0,d={},q=''):
 for r in a:
  i=0
  for c in r:d[c]=o,i;i+=1;q=(c,q)[c in'O.']
  o+=1
 z,y=d['O'];e,j=d[q];return eval("z%se and y%sj"%(('><'[q<'v'],'=='),('==',q))[q in'><'])
</code>```

Title: Will the beam hit?

Body:
Python 3 (no regex), 184 bytes.

Hooray for eval hacking!

def f(a,o=0,d={},q=''):
 for r in a:
  i=0
  for c in r:d[c]=o,i;i+=1;q=(c,q)[c in'O.']
  o+=1
 z,y=d['O'];e,j=d[q];return eval("z%se and y%sj"%(('><'[q<'v'],'=='),('==',q))[q in'><'])


答:
Ruby, <s>71</s> <s>55</s> 54 bytes

Regex solution, which means that it's probably going to be easily beaten by Retina or Perl.

Returns an index number (truthy) if there is a match.

Now with a similar trick to @Downgoat Retina answer, matching for down and up beams at the same time.

```<code>->m{m=~/>\.*O|O\.*<|(?=[vO])(.{#{??+m=~/\n/}})+[O^]/m}
</code>```

Title: Will the beam hit?

Body:
Ruby, <s>71</s> <s>55</s> 54 bytes

Regex solution, which means that it's probably going to be easily beaten by Retina or Perl.

Returns an index number (truthy) if there is a match.

Now with a similar trick to @Downgoat Retina answer, matching for down and up beams at the same time.

->m{m=~/>\.*O|O\.*<|(?=[vO])(.{#{??+m=~/\n/}})+[O^]/m}


问:
Generate 100 Java Tuple classes
Write a script that writes to standard output, or your language's equivalent, 100 lines of (valid) Java code that begins with:

```<code>class Tuple1 {public Object _0;}
class Tuple2 {public Object _0,_1;}
class Tuple3 {public Object _0,_1,_2;}
class Tuple4 {public Object _0,_1,_2,_3;}
class Tuple5 {public Object _0,_1,_2,_3,_4;}
class Tuple6 {public Object _0,_1,_2,_3,_4,_5;}
class Tuple7 {public Object _0,_1,_2,_3,_4,_5,_6;}
class Tuple8 {public Object _0,_1,_2,_3,_4,_5,_6,_7;}
class Tuple9 {public Object _0,_1,_2,_3,_4,_5,_6,_7,_8;}
class Tuple10 {public Object _0,_1,_2,_3,_4,_5,_6,_7,_8,_9;}
class Tuple11 {public Object _0,_1,_2,_3,_4,_5,_6,_7,_8,_9,_10;}
class Tuple12 {public Object _0,_1,_2,_3,_4,_5,_6,_7,_8,_9,_10,_11;}
</code>```

The last line should begin with class Tuple100.

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

答:
Kotlin, 92 Bytes

```<code>fun j(){var s="_0";for(i in 1..100){println("class Tuple$i {public Object $s;}");s+=",_"+i}}
</code>```

Try it online!

Ungolfed

```<code>fun j(){
    var s = "_0"
    for(i in 1..100){
        println("class Tuple$i {public Object $s;}")
        s+=",_"+i
    }
}
</code>```

Title: Generate 100 Java Tuple classes

Body:
Kotlin, 92 Bytes

fun j(){var s="_0";for(i in 1..100){println("class Tuple$i {public Object $s;}");s+=",_"+i}}

Try it online!

Ungolfed

fun j(){
    var s = "_0"
    for(i in 1..100){
        println("class Tuple$i {public Object $s;}")
        s+=",_"+i
    }
}


问:
Sort an Integer List

The Challenge

It's quite simple really, sort a list of numbers.

Details

You must sort a list of numbers in ascending order, without using any built-in sorting functions/libraries/etc (i.e. list.sort() in Python).

Input/output can be done in any method you choose, as long as it is human readable.

Standard loopholes are disallowed as always.

Shortest code in bytes wins.

You must explain/list what sort method you used (Bubble, Insertion, Selection, etc.)

Input will not contain duplicates.

Sample Input/Output

Input: 99,-2,53,4,67,55,23,43,88,-22,36,45

Output: -22,-2,4,23,36,43,45,53,55,67,88,99

Note: A near direct opposite of Sort a List of Numbers

答:
Javascript 55 bytes

```<code>a=>[...a].map(b=>a.splice(a.indexOf(Math.min(...a)),1)
</code>```

Title: Sort an Integer List

Body:
Javascript 55 bytes

a=>[...a].map(b=>a.splice(a.indexOf(Math.min(...a)),1)