答:
Python, <s>74</s> 71 bytes

f=lambda s:s and{r[0]+t for r in{s,s.swapcase()}for t in f(s[1:])}or{s}
```

Handles non-ASCII characters. Test it on Ideone.

Title: Case Permutation

Body:
Who needs to compare things case insensitively when you're able to generate every permutation of uppercase and lowercase? No one! That's the answer. No one does. Your task is to achieve this feat; generate all possible permutations of uppercase/lowercase for a given input.

Input

A string of printable standard ascii characters. Input should not be assumed to be all lowercase. Input will always be at least one character.

Output

Every permutation of uppercase and lowercase for the inputted string (no duplicates). This should only change characters with a small and large version (numbers will stay the same). Each permutation must be output as a string or a list of characters; lists of singleton strings are not allowed.

Examples

```<code>a1a
['a1a', 'a1A', 'A1a', 'A1A']

abc
['abc', 'abC', 'aBc', 'aBC', 'Abc', 'AbC', 'ABc', 'ABC']

Hi!
['hi!', 'hI!', 'Hi!', 'HI!']
</code>```

Scoring

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

As a fun extra see how much additional effort it will take to handle the extended ascii characters, here is an extra test case:

```<code>ž1a -> ['ž1a', 'ž1A', 'Ž1a', 'Ž1A']
</code>```

(your program does not need to support this)

Body:
Python, <s>74</s> 71 bytes

f=lambda s:s and{r[0]+t for r in{s,s.swapcase()}for t in f(s[1:])}or{s}

Handles non-ASCII characters. Test it on Ideone.


问:
Case Permutation
Who needs to compare things case insensitively when you're able to generate every permutation of uppercase and lowercase? No one! That's the answer. No one does. Your task is to achieve this feat; generate all possible permutations of uppercase/lowercase for a given input.

Input

A string of printable standard ascii characters. Input should not be assumed to be all lowercase. Input will always be at least one character.

Output

Every permutation of uppercase and lowercase for the inputted string (no duplicates). This should only change characters with a small and large version (numbers will stay the same). Each permutation must be output as a string or a list of characters; lists of singleton strings are not allowed.

Examples

```<code>a1a
['a1a', 'a1A', 'A1a', 'A1A']

abc
['abc', 'abC', 'aBc', 'aBC', 'Abc', 'AbC', 'ABc', 'ABC']

Hi!
['hi!', 'hI!', 'Hi!', 'HI!']
</code>```

Scoring

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

As a fun extra see how much additional effort it will take to handle the extended ascii characters, here is an extra test case:

```<code>ž1a -> ['ž1a', 'ž1A', 'Ž1a', 'Ž1A']
</code>```

(your program does not need to support this)

答:
Haskell, <s>69</s> 58 bytes

```<code>import Data.Char
mapM(\x->toLower x:[toUpper x|isAlpha x])
</code>```

Try it online!

Edit: @Angs saved 11 bytes. Thanks!

ContentLicense: CC BY-SA 3.0

Title: Case Permutation

Body:
Haskell, <s>69</s> 58 bytes

import Data.Char
mapM(\x->toLower x:[toUpper x|isAlpha x])

Try it online!

Edit: @Angs saved 11 bytes. Thanks!


问:
Recognize a vine

Background

I have a bunch of old and grainy black-and-white images.
Some of them depict vines climbing on a wall, others don't – your task is to classify them for me.

Input and output

Your input is a rectangular 2D array of bits A, given in any convenient format.
It will not be empty, but it's not guaranteed to contain both 0s and 1s.
The array depicts a vine if the following conditions hold:

The bottom row of A contains at least one 1. These are the roots of the vine.

Every 1 in A is connected to the bottom row by a path of 1s that only goes left, right and down (not up, and not diagonally). These paths are the branches of the vine.

Your output is a consistent truthy value if the input depicts a vine, and a consistent falsy value otherwise.

Examples

This array depicts a vine:

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

This input does not depict a vine, since there's a 1 at the middle of the right border that's not connected to the roots by a branch:

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

The all-0 array never depicts a vine, but the all-1 array always does.

Rules and scoring

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

Test cases

Truthy inputs:

```<code>1

0
1
1

01
11

0000
0111
1100
1001

1111
1111
1111
1111

001001
011001
010111
110101
011101
001011

1011011
1001001
1111111
0100000
0111111
1111001
1001111
1111101

0000000
0011100
0010100
0011100
0001000
1111111
0001000
0011100
0010100
0010100
</code>```

Falsy inputs:

```<code>0

1
0

10
01

000
000
000

011
110
000

111111
000000
101011
111001

010010
001000
000010
110001

001100
111111
110101
010011
111011

000110
010111
010101
011110
001101

11000000
10110001
10011111
11110001
01100011
00110110
01101100
01100001
01111111
</code>```

答:
Snails, <s>25</s> <s>19</s> 17 bytes

```<code>&
\0z),(\1dlr)+d~
</code>```

Try it online!

Explanation

Snails is a 2D pattern-matching language inspired by regex, which was originally developed for our 2D pattern matching language design challenge.

The & makes Snails try the pattern from every possible starting position and prints 0 or 1 depending on whether the pattern fails in any of them or matches in all of them.

Now Snails can work with implicit parentheses, so the pattern is shorthand for the following:

```<code>(\0z),(\1dlr)+d~
</code>```

The , acts like a * in regex (i.e. match zero or more times), whereas the + is the same as in regex (match one or more times). So we start by matching \0z as often as necessary, which matches a single 0 and then allows the snail to reset its direction arbitrarily with z. This allows zeros in the input, provided a valid vine cell can be found anywhere else.

Then we match at least one \1dlr, which matches a single 1 and then allows the snail to reset its direction either down, left or right. Note that if the cell we've started at contains a 1 then we're only matching this part. It basically allows the snail to traverse a vine from a branch down to the roots.

Finally, we need to ensure that we did reach the ground by looking for an out-of-bounds cell (~) below (d).

Title: Recognize a vine

Body:
Snails, <s>25</s> <s>19</s> 17 bytes

&
\0z),(\1dlr)+d~

Try it online!

Explanation

Snails is a 2D pattern-matching language inspired by regex, which was originally developed for our 2D pattern matching language design challenge.

The & makes Snails try the pattern from every possible starting position and prints 0 or 1 depending on whether the pattern fails in any of them or matches in all of them.

Now Snails can work with implicit parentheses, so the pattern is shorthand for the following:

(\0z),(\1dlr)+d~

The , acts like a * in regex (i.e. match zero or more times), whereas the + is the same as in regex (match one or more times). So we start by matching \0z as often as necessary, which matches a single 0 and then allows the snail to reset its direction arbitrarily with z. This allows zeros in the input, provided a valid vine cell can be found anywhere else.

Then we match at least one \1dlr, which matches a single 1 and then allows the snail to reset its direction either down, left or right. Note that if the cell we've started at contains a 1 then we're only matching this part. It basically allows the snail to traverse a vine from a branch down to the roots.

Finally, we need to ensure that we did reach the ground by looking for an out-of-bounds cell (~) below (d).


答:
Oracle SQL 11.2, 276 bytes

WITH v AS(SELECT SUBSTR(:1,LEVEL,1)c,ROWNUM p FROM DUAL CONNECT BY LEVEL<=LENGTH(:1))SELECT w FROM(SELECT REPLACE(SYS_CONNECT_BY_PATH(c,','),',','')w FROM(SELECT UPPER(c)c,p FROM v UNION SELECT LOWER(c),p FROM v)START WITH p=1CONNECT BY PRIOR p=p-1)WHERE LENGTH(:1)=LENGTH(w);
```

<p>Un-golfed</p>

<pre class="lang-sql prettyprint-override"><code>WITH v AS
( -- Split input into an array of characters
  SELECT SUBSTR(:1,LEVEL,1)c,ROWNUM p FROM DUAL CONNECT BY LEVEL<=LENGTH(:1)
)
SELECT w
FROM   ( -- Build every string combination
         SELECT REPLACE(SYS_CONNECT_BY_PATH(c,','),',','')w
         FROM   ( -- Merge upper and lower arrays, keep same position for each character, it allows to mix cases
                  SELECT UPPER(c)c,p FROM v UNION SELECT LOWER(c),p FROM v
                )
         START WITH p=1          -- Start with first character (either lowercase or uppercase)
         CONNECT BY PRIOR p=p-1  -- Add the next character (either lowercase or uppercase)
       )
WHERE LENGTH(:1)=LENGTH(w); -- Keep only full strings
</code>```

Ugly as hell, must be more golfable.

Title: Case Permutation

Body:
Oracle SQL 11.2, 276 bytes

WITH v AS(SELECT SUBSTR(:1,LEVEL,1)c,ROWNUM p FROM DUAL CONNECT BY LEVEL<=LENGTH(:1))SELECT w FROM(SELECT REPLACE(SYS_CONNECT_BY_PATH(c,','),',','')w FROM(SELECT UPPER(c)c,p FROM v UNION SELECT LOWER(c),p FROM v)START WITH p=1CONNECT BY PRIOR p=p-1)WHERE LENGTH(:1)=LENGTH(w);

Un-golfed

WITH v AS
( -- Split input into an array of characters
  SELECT SUBSTR(:1,LEVEL,1)c,ROWNUM p FROM DUAL CONNECT BY LEVEL<=LENGTH(:1)
)
SELECT w
FROM   ( -- Build every string combination
         SELECT REPLACE(SYS_CONNECT_BY_PATH(c,','),',','')w
         FROM   ( -- Merge upper and lower arrays, keep same position for each character, it allows to mix cases
                  SELECT UPPER(c)c,p FROM v UNION SELECT LOWER(c),p FROM v
                )
         START WITH p=1          -- Start with first character (either lowercase or uppercase)
         CONNECT BY PRIOR p=p-1  -- Add the next character (either lowercase or uppercase)
       )
WHERE LENGTH(:1)=LENGTH(w); -- Keep only full strings

Ugly as hell, must be more golfable.


问:
24 and 12 Hour Times
Write a program or function with no input that prints or returns this string of 24-hour and 12-hour times:

```<code>00:00 12:00am
01:00  1:00am
02:00  2:00am
03:00  3:00am
04:00  4:00am
05:00  5:00am
06:00  6:00am
07:00  7:00am
08:00  8:00am
09:00  9:00am
10:00 10:00am
11:00 11:00am
12:00 12:00pm
13:00  1:00pm
14:00  2:00pm
15:00  3:00pm
16:00  4:00pm
17:00  5:00pm
18:00  6:00pm
19:00  7:00pm
20:00  8:00pm
21:00  9:00pm
22:00 10:00pm
23:00 11:00pm
</code>```

The string must be output exactly as it appears here. The only exception is that it may optionally have a single trailing newline.

So the MD5 hash of your output should be

```<code>827ae6e2dbb1df494930baedb3ee2653
</code>```

if you do not have a trailing newline and

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

if you do. (Your hash could be different if your system uses another type of newline but that's OK.)

The shortest code in bytes wins. Tiebreaker is earlier answer.

答:
Kotlin, 95 bytes

It can be improved for sure.

```<code>fun p(){for(i in 0..23)println("%02d:00 ${(i+11)%12+1}:00${if(i>12)"p" else "a"}m".format(i))}
</code>```

Title: 24 and 12 Hour Times

Body:
Kotlin, 95 bytes

It can be improved for sure.

fun p(){for(i in 0..23)println("%02d:00 ${(i+11)%12+1}:00${if(i>12)"p" else "a"}m".format(i))}


答:
Julia, <s>66</s> 60 bytes

!s=s>""?[~s[1:1]t for~=(ucfirst,lcfirst),t=!s[2:end]]∪[]:[s]
```

Try it online!

Title: Case Permutation

Body:
Julia, <s>66</s> 60 bytes

!s=s>""?[~s[1:1]t for~=(ucfirst,lcfirst),t=!s[2:end]]∪[]:[s]

Try it online!


答:
JavaScript (ES6), 103

Handles non-ASCII characters

(a,r=new Set)=>a?f(a.slice(1)).map(v=>(C=o=>r.add(a[0][`to${o}erCase`]()+v),C`Upp`,C`Low`))&&[...r]:[a]
```

<p><strong>Test</strong>
<div class="snippet" data-lang="js" data-hide="false" data-console="true">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>f=(a,r=new Set)=>a?f(a.slice(1)).map(v=>(C=o=>r.add(a[0][`to${o}erCase`]()+v),C`Upp`,C`Low`))&&[...r]:[a]

function test() { O.textContent = f(I.value).join('\n') }

test()</code>```

<input id=I oninput='test()' value='ž1a'>

```</code>```

Title: Case Permutation

Body:
JavaScript (ES6), 103

Handles non-ASCII characters

(a,r=new Set)=>a?f(a.slice(1)).map(v=>(C=o=>r.add(a[0][`to${o}erCase`]()+v),C`Upp`,C`Low`))&&[...r]:[a]

Test

f=(a,r=new Set)=>a?f(a.slice(1)).map(v=>(C=o=>r.add(a[0][`to${o}erCase`]()+v),C`Upp`,C`Low`))&&[...r]:[a]

function test() { O.textContent = f(I.value).join('\n') }

test()

<input id=I oninput='test()' value='ž1a'>
<pre id=O></pre>


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

答:
Iterate over functions

This is also possible in other languages, but usually longer than the straightforward method. However, Julia's ability to redefine its unary and binary operators make it quite golfy.

For example, to generate the addition, subtraction, multiplication and division table for the natural numbers from 1 to 10, one could use

[x|y for x=1:10,y=1:10,| =(+,-,*,÷)]
```

<p>which redefines the <em>binary</em> operator <code>|</code> as <code>+</code>, <code>-</code>, <code>*</code> and <code>÷</code>, then computes <code>x|y</code> for each operation and <code>x</code> and <code>y</code> in the desired ranges.</p>

<p>This works for unary operators as well. For example, to compute complex numbers <strong>1+2i</strong>, <strong>3-4i</strong>, <strong>-5+6i</strong> and <strong>-7-8i</strong>, their negatives, their complex conjugates and their multiplicative inverses, one could use</p>

<pre class="lang-julia prettyprint-override"><code>[~x for~=(+,-,conj,inv),x=(1+2im,3-4im,-5+6im,-7-8im)]
</code>```

which redefines the unary operator ~ as +, -, conj and inv, then computes ~x for all desired complex numbers.

Examples in actual contests

Female and Male Sequences (binary)

Case Permutation (unary)

Title: Tips for golfing in Julia

Body:
Iterate over functions

This is also possible in other languages, but usually longer than the straightforward method. However, Julia's ability to redefine its unary and binary operators make it quite golfy.

For example, to generate the addition, subtraction, multiplication and division table for the natural numbers from 1 to 10, one could use

[x|y for x=1:10,y=1:10,| =(+,-,*,÷)]

which redefines the binary operator | as +, -, * and ÷, then computes x|y for each operation and x and y in the desired ranges.

This works for unary operators as well. For example, to compute complex numbers 1+2i, 3-4i, -5+6i and -7-8i, their negatives, their complex conjugates and their multiplicative inverses, one could use

[~x for~=(+,-,conj,inv),x=(1+2im,3-4im,-5+6im,-7-8im)]

which redefines the unary operator ~ as +, -, conj and inv, then computes ~x for all desired complex numbers.

Examples in actual contests

Female and Male Sequences (binary)

Case Permutation (unary)


答:
Tcl, 165 <s>181</s> bytes

```<code>set n -1
while {[incr n]<1<<[llength [set s [split $argv {}]]]} {puts [join [lmap c $s b [split [format %0[llength $s]b $n] {}] {string to[expr $b?{u}:{l}] $c}] ""]}
</code>```

Improvements thanks to sergiol.
Previous answer:

```<code>set s [split $argv {}]
set n -1
while {[incr n]<1<<[llength $s]} {set r ""
foreach c $s b [split [format %0[llength $s]b $n] {}] {set r $r[string [expr $b?{tou}:{tol}] $c]}
puts $r}
</code>```

Uses a binary number to choose between upper/lower case when creating the output text.

Title: Case Permutation

Body:
Tcl, 165 <s>181</s> bytes

set n -1
while {[incr n]<1<<[llength [set s [split $argv {}]]]} {puts [join [lmap c $s b [split [format %0[llength $s]b $n] {}] {string to[expr $b?{u}:{l}] $c}] ""]}

Improvements thanks to sergiol.
Previous answer:

set s [split $argv {}]
set n -1
while {[incr n]<1<<[llength $s]} {set r ""
foreach c $s b [split [format %0[llength $s]b $n] {}] {set r $r[string [expr $b?{tou}:{tol}] $c]}
puts $r}

Uses a binary number to choose between upper/lower case when creating the output text.


答:
Wolfram - 254

Spend some time making this work, so I'll just leave it here:

```<code>f[s_]:=(
v=Characters@StringSplit@s;
{h,w}=Dimensions@v;
g=GridGraph@{w,h};
r=First/@Position[Flatten@v,"0"];
g=VertexDelete[Graph[VertexList@g,
EdgeList@g/.x_y_/;Abs[x-y]>1yx],r];
v=VertexList@g;
v≠{}∧v~Complement~VertexOutComponent[g,Select[v,#>w h-w&]]{}
)
</code>```

Basically I construct a grid graph with directed edges pointing up, remove vertices that correspond to 0s, check that bottom vertex components contain all vertices. Ridiculous, I know...

Title: Recognize a vine

Body:
Background

I have a bunch of old and grainy black-and-white images.
Some of them depict vines climbing on a wall, others don't – your task is to classify them for me.

Input and output

Your input is a rectangular 2D array of bits A, given in any convenient format.
It will not be empty, but it's not guaranteed to contain both 0s and 1s.
The array depicts a vine if the following conditions hold:

The bottom row of A contains at least one 1. These are the roots of the vine.

Every 1 in A is connected to the bottom row by a path of 1s that only goes left, right and down (not up, and not diagonally). These paths are the branches of the vine.

Your output is a consistent truthy value if the input depicts a vine, and a consistent falsy value otherwise.

Examples

This array depicts a vine:

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

This input does not depict a vine, since there's a 1 at the middle of the right border that's not connected to the roots by a branch:

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

The all-0 array never depicts a vine, but the all-1 array always does.

Rules and scoring

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

Test cases

Truthy inputs:

```<code>1

0
1
1

01
11

0000
0111
1100
1001

1111
1111
1111
1111

001001
011001
010111
110101
011101
001011

1011011
1001001
1111111
0100000
0111111
1111001
1001111
1111101

0000000
0011100
0010100
0011100
0001000
1111111
0001000
0011100
0010100
0010100
</code>```

Falsy inputs:

```<code>0

1
0

10
01

000
000
000

011
110
000

111111
000000
101011
111001

010010
001000
000010
110001

001100
111111
110101
010011
111011

000110
010111
010101
011110
001101

11000000
10110001
10011111
11110001
01100011
00110110
01101100
01100001
01111111
</code>```

Body:
Wolfram - 254

Spend some time making this work, so I'll just leave it here:

f[s_]:=(
v=Characters@StringSplit@s;
{h,w}=Dimensions@v;
g=GridGraph@{w,h};
r=First/@Position[Flatten@v,"0"];
g=VertexDelete[Graph[VertexList@g,
EdgeList@g/.x_y_/;Abs[x-y]>1yx],r];
v=VertexList@g;
v≠{}∧v~Complement~VertexOutComponent[g,Select[v,#>w h-w&]]{}
)

Basically I construct a grid graph with directed edges pointing up, remove vertices that correspond to 0s, check that bottom vertex components contain all vertices. Ridiculous, I know...


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

答:
PHP, <s>48</s> 52 bytes

```<code>echo"Greetings, Planet!";//;"!tenalP ,sgniteerG"ohce
</code>```

// comments out the rest of the line, leaving echo"Greetings, Planet!";.

No space is needed between echo and ", meaning this is this the shortest possible response for PHP.

Would have loved a clever excuse to use /* */, but couldn't think of one.

Title: Palindrome Hello, World

Body:
PHP, <s>48</s> 52 bytes

echo"Greetings, Planet!";//;"!tenalP ,sgniteerG"ohce

// comments out the rest of the line, leaving echo"Greetings, Planet!";.

No space is needed between echo and ", meaning this is this the shortest possible response for PHP.

Would have loved a clever excuse to use /* */, but couldn't think of one.


Title: 24 and 12 Hour Times

Body:
Write a program or function with no input that prints or returns this string of 24-hour and 12-hour times:

```<code>00:00 12:00am
01:00  1:00am
02:00  2:00am
03:00  3:00am
04:00  4:00am
05:00  5:00am
06:00  6:00am
07:00  7:00am
08:00  8:00am
09:00  9:00am
10:00 10:00am
11:00 11:00am
12:00 12:00pm
13:00  1:00pm
14:00  2:00pm
15:00  3:00pm
16:00  4:00pm
17:00  5:00pm
18:00  6:00pm
19:00  7:00pm
20:00  8:00pm
21:00  9:00pm
22:00 10:00pm
23:00 11:00pm
</code>```

The string must be output exactly as it appears here. The only exception is that it may optionally have a single trailing newline.

So the MD5 hash of your output should be

```<code>827ae6e2dbb1df494930baedb3ee2653
</code>```

if you do not have a trailing newline and

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

if you do. (Your hash could be different if your system uses another type of newline but that's OK.)

The shortest code in bytes wins. Tiebreaker is earlier answer.

Body:
C#, 91 bytes

for(var i=0;i<24;i++){Console.Write($"{i:00}:00 {(i+11)%12+1,2}:00 {(i>11?"p":"a")}m\n");};


答:
Redefine operators to define functions

Redefining operators can save a lot of bytes in parentheses and commas.

Recursive unary operators

For a unary example, compare the following recursive implementations of the Fibonacci sequence:

F(n)=n>1?F(n-1)+F(n-2):n # 24 bytes
!n=n>1?!~-n+!(n-2):n     # 20 bytes
!n=n>1?!~-n+!~-~-n:n     # 20 bytes
```

<p>Try it online!</p>

<p>The redefined operator retains its initial precedence.</p>

<p>Note that we could not simply swap out <code>!</code> in favor of <code>~</code>, since <code>~</code> is already defined for integers, while <code>!</code> is only defined for Booleans.</p>

<h3>Binary operators</h3>

<p>Even without recursion, redefining an operator is shorter than defining a binary function. Compare the following definitions of a simple divisibility test.</p>

<pre class="lang-julia prettyprint-override"><code>f(x,y)=x==0?y==0:y%x==0 # 23 bytes
(x,y)->x==0?y==0:y%x==0 # 23 bytes
x->y->x==0?y==0:y%x==0  # 22 bytes
x\y=x==0?y==0:y%x==0    # 20 bytes
</code>```

Try it online!

Recursive binary operators

The following illustrates how to redefine a binary operator to compute the Ackermann function:

A(m,n)=m>0?A(m-1,n<1||A(m,n-1)):n+1    # 35 bytes
^ =(m,n)->m>0?(m-1)^(n<1||m^~-n):n+1   # 36 bytes
| =(m,n)->m>0?m-1|(n<1||m|~-n):n+1     # 34 bytes
m\n=m>0?~-m\(n<1||m\~-n):n+1           # 28 bytes
```

<p>Try it online!</p>

<p>Note that <code>^</code> is even longer than using a regular identifier, since its precedence is too high.</p>

<p>As mentioned before</p>

<pre class="lang-julia prettyprint-override"><code>m|n=m>0?m-1|(n<1||m|~-n):n+1           # 28 bytes
</code>```

would not work for integer arguments, since | is already defined in this case. The definition for integers can be changed with

m::Int|n::Int=m>0?m-1|(n<1||m|~-n):n+1 # 38 bytes
```

but that's prohibitively long. However, it does work if we pass a float as left argument and an integer as right argument.

Title: Tips for golfing in Julia

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

Body:
Redefine operators to define functions

Redefining operators can save a lot of bytes in parentheses and commas.

Recursive unary operators

For a unary example, compare the following recursive implementations of the Fibonacci sequence:

F(n)=n>1?F(n-1)+F(n-2):n # 24 bytes
!n=n>1?!~-n+!(n-2):n     # 20 bytes
!n=n>1?!~-n+!~-~-n:n     # 20 bytes

Try it online!

The redefined operator retains its initial precedence.

Note that we could not simply swap out ! in favor of ~, since ~ is already defined for integers, while ! is only defined for Booleans.

Binary operators

Even without recursion, redefining an operator is shorter than defining a binary function. Compare the following definitions of a simple divisibility test.

f(x,y)=x==0?y==0:y%x==0 # 23 bytes
(x,y)->x==0?y==0:y%x==0 # 23 bytes
x->y->x==0?y==0:y%x==0  # 22 bytes
x\y=x==0?y==0:y%x==0    # 20 bytes

Try it online!

Recursive binary operators

The following illustrates how to redefine a binary operator to compute the Ackermann function:

A(m,n)=m>0?A(m-1,n<1||A(m,n-1)):n+1    # 35 bytes
^ =(m,n)->m>0?(m-1)^(n<1||m^~-n):n+1   # 36 bytes
| =(m,n)->m>0?m-1|(n<1||m|~-n):n+1     # 34 bytes
m\n=m>0?~-m\(n<1||m\~-n):n+1           # 28 bytes

Try it online!

Note that ^ is even longer than using a regular identifier, since its precedence is too high.

As mentioned before

m|n=m>0?m-1|(n<1||m|~-n):n+1           # 28 bytes

would not work for integer arguments, since | is already defined in this case. The definition for integers can be changed with

m::Int|n::Int=m>0?m-1|(n<1||m|~-n):n+1 # 38 bytes

but that's prohibitively long. However, it does work if we pass a float as left argument and an integer as right argument.


Title: 24 and 12 Hour Times

Body:
PHP, <s>110</s> 107 bytes

for($h=0;$h<24;){$m=($h+11)%12+1;echo($h<10?0:"")."$h:00 ".($m<10?" ":"")."$m:00".($h++<12?"a":"p")."m\n";}

exploded view

for ($h=0; $h<24; ) {
  $m = ($h+11) % 12 + 1;
  echo ($h < 10 ?  0  : "") . "$h:00 " .
       ($m < 10 ? " " : "") . "$m:00"  . ($h++ < 12 ? "a" : "p") . "m\n";
}

Somewhat surprised, tried to turn the ($i < 10 ? $s : "") . "$i:00" bit into a function, but it wound up adding ~25 characters.  No go there.


问:
Shortest infinite loop producing no output
Your task is to create the shortest infinite loop!

The point of this challenge is to create an infinite loop producing no output, unlike its possible duplicate. The reason to this is because the code might be shorter if no output is given.

Rules

Each submission must be a full program.

You must create the shortest infinite loop.

Even if your program runs out of memory eventually, it is still accepted as long as it is running the whole time from the start to when it runs out of memory. Also when it runs out of memory, it should still not print anything to STDERR.

The program must take no input (however, reading from a file is allowed), and should not print anything to STDOUT. Output to a file is also forbidden.

The program must not write anything to STDERR.

Feel free to use a language (or language version) even if it's newer than this challenge.
-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. :D

Submissions are scored in bytes, in an appropriate (pre-existing) encoding, usually (but not necessarily) UTF-8. Some languages, like Folders, are a bit tricky to score - if in doubt, please ask on Meta.

This is not about finding the language with the shortest infinite loop program. This is about finding the shortest infinite loop program in every language. Therefore, I will not accept an answer.

If your language of choice is a trivial variant of another (potentially more popular) language which already has an answer (think BASIC or SQL dialects, Unix shells or trivial Brainf**k-derivatives like Alphuck), consider adding a note to the existing answer that the same or a very similar solution is also the shortest in the other language.

There should be a website such as Wikipedia, Esolangs, or GitHub for the language. For example, if the language is CJam, then one could link to the site in the header like #[CJam](http://sourceforge.net/p/cjam/wiki/Home/), X bytes.

Standard loopholes are not allowed.

(I have taken some of these rules from Martin Büttner's "Hello World" challenge)

Please feel free to post in the comments to tell me how this challenge could be  improved.

Catalogue

This is a Stack Snippet which generates both an alphabetical catalogue of the used languages, and an overall leaderboard. To make sure your answer shows up, please start it with this Markdown header:

```<code># Language name, X bytes
</code>```

Obviously replacing Language name and X bytes with the proper items. If you want to link to the languages' website, use this template, as posted above:

```<code>#[Language name](http://link.to/the/language), X bytes
</code>```

Now, finally, here's the snippet: (Try pressing "Full page" for a better view.)

var QUESTION_ID=59347;var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";var COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk";var OVERRIDE_USER=41805;var answers=[],answers_hash,answer_ids,answer_page=1,more_answers=true,comment_page;function answersUrl(index){return"//api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+index+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(index,answers){return"//api.stackexchange.com/2.2/answers/"+answers.join(';')+"/comments?page="+index+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:true,success:function(data){answers.push.apply(answers,data.items);answers_hash=[];answer_ids=[];data.items.forEach(function(a){a.comments=[];var id=+a.share_link.match(/\d+/);answer_ids.push(id);answers_hash[id]=a});if(!data.has_more)more_answers=false;comment_page=1;getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:true,success:function(data){data.items.forEach(function(c){if(c.owner.user_id===OVERRIDE_USER)answers_hash[c.post_id].comments.push(c)});if(data.has_more)getComments();else if(more_answers)getAnswers();else process()}})}getAnswers();var SCORE_REG=/<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/;var OVERRIDE_REG=/^Override\s*header:\s*/i;function getAuthorName(a){return a.owner.display_name}function process(){var valid=[];answers.forEach(function(a){var body=a.body;a.comments.forEach(function(c){if(OVERRIDE_REG.test(c.body))body='
'+c.body.replace(OVERRIDE_REG,'')+'
'});var match=body.match(SCORE_REG);if(match)valid.push({user:getAuthorName(a),size:+match[2],language:match[1],link:a.share_link,});else console.log(body)});valid.sort(function(a,b){var aB=a.size,bB=b.size;return aB-bB});var languages={};var place=1;var lastSize=null;var lastPlace=1;valid.forEach(function(a){if(a.size!=lastSize)lastPlace=place;lastSize=a.size;++place;var answer=jQuery("#answer-template").html();answer=answer.replace("{{PLACE}}",lastPlace+".").replace("{{NAME}}",a.user).replace("{{LANGUAGE}}",a.language).replace("{{SIZE}}",a.size).replace("{{LINK}}",a.link);answer=jQuery(answer);jQuery("#answers").append(answer);var lang=a.language;lang=jQuery(''+lang+'').text();languages[lang]=languages[lang]||{lang:a.language,lang_raw:lang,user:a.user,size:a.size,link:a.link}});var langs=[];for(var lang in languages)if(languages.hasOwnProperty(lang))langs.push(languages[lang]);langs.sort(function(a,b){if(a.lang_raw.toLowerCase()>b.lang_raw.toLowerCase())return 1;if(a.lang_raw.toLowerCase()<b.lang_raw.toLowerCase())return-1;return 0});for(var i=0;i<langs.length;++i){var language=jQuery("#language-template").html();var lang=langs[i];language=language.replace("{{LANGUAGE}}",lang.lang).replace("{{NAME}}",lang.user).replace("{{SIZE}}",lang.size).replace("{{LINK}}",lang.link);language=jQuery(language);jQuery("#languages").append(language)}}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body{text-align:left!important}#answer-list{padding:10px;width:500px;float:left}#language-list{padding:10px;padding-right:40px;width:500px;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">

Shortest Solution by Language

Language	User	Score

Leaderboard

	Author	Language	Size

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

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

```

答:
Binary Lambda Calculus, 3 bytes

Before I dive into the explanation, let's start with the program itself.

```<code>F†€
</code>```

Trust me, it's pure luck that they're all printable, and I'll get to why it is 2 1/4 bytes instead of 3 after the explanation. I'll explain this by walking through the process I took to create this program.

To start, BLC programs are just lambda calculus programs encoded in a special way. With this in mind, let's begin with the lambda calculus program that enters an infinite loop, known as omega.

```<code>(λx.xx)(λx.xx)
</code>```

This results in an infinite loop because, according to Wikipedia, it reduces to itself after a single beta-reduction. To convert this into BLC, we must first convert it to De Bruijn indices. It converts into the following:

```<code>.λ.11λ.11 (The dots after the λs are necessary for BLC but not part of De Bruijn indices)
</code>```

Okay, now that it's in De Bruijin indices we can now convert it into BLC where λ translates to 00, function application or . translates to 01, and numbers are represented as 1^n0 where n is the number. Knowing this, it translates into the following binary:

```<code>01 00 01 10 10 00 01 10 10
</code>```

This is why it's 2 1/4 bytes. As BLC instructions aren't full bytes (with the exception of 7), it is rare for programs to fit exactly into a certain byte count. To turn this into hex, we have to pad it in order to make it fit into 3 bytes. Doing this yields the following:

```<code>46 86 80
</code>```

There we have the hex dump of our program! It runs in an infinite loop, doesn't run out of memory to my knowledge, doesn't output anything, and is a complete program that can be saved and run by piping the contents of the file to the official interpreter. You can also pipe the binary text to the interpreter and add the -b flag, to demonstrate that the non-padded version can be run.

Body:
Binary Lambda Calculus, 3 bytes

Before I dive into the explanation, let's start with the program itself.

F†€

Trust me, it's pure luck that they're all printable, and I'll get to why it is 2 1/4 bytes instead of 3 after the explanation. I'll explain this by walking through the process I took to create this program.

To start, BLC programs are just lambda calculus programs encoded in a special way. With this in mind, let's begin with the lambda calculus program that enters an infinite loop, known as omega.

(λx.xx)(λx.xx)

This results in an infinite loop because, according to Wikipedia, it reduces to itself after a single beta-reduction. To convert this into BLC, we must first convert it to De Bruijn indices. It converts into the following:

.λ.11λ.11 (The dots after the λs are necessary for BLC but not part of De Bruijn indices)

Okay, now that it's in De Bruijin indices we can now convert it into BLC where λ translates to 00, function application or . translates to 01, and numbers are represented as 1^n0 where n is the number. Knowing this, it translates into the following binary:

01 00 01 10 10 00 01 10 10

This is why it's 2 1/4 bytes. As BLC instructions aren't full bytes (with the exception of 7), it is rare for programs to fit exactly into a certain byte count. To turn this into hex, we have to pad it in order to make it fit into 3 bytes. Doing this yields the following:

46 86 80

There we have the hex dump of our program! It runs in an infinite loop, doesn't run out of memory to my knowledge, doesn't output anything, and is a complete program that can be saved and run by piping the contents of the file to the official interpreter. You can also pipe the binary text to the interpreter and add the -b flag, to demonstrate that the non-padded version can be run.


问:
Fibonacci function or sequence
The Fibonacci sequence is a sequence of numbers, where every number in the sequence is the sum of the two numbers preceding it.  The first two numbers in the sequence are both 1. Here are the first few terms:

```<code>1 1 2 3 5 8 13 21 34 55 89 ...
</code>```

Write the shortest code that either:

Generates the Fibonacci sequence without end.

Given n calculates the nth term of the sequence. (Either 1 or zero indexed)

You may use standard forms of input and output.

(I gave both options in case one is easier to do in your chosen language than the other.)

For the function that takes an n, a reasonably large return value (the largest Fibonacci number that fits your computer's normal word size, at a minimum) has to be supported.

Leaderboard

/* Configuration */

var QUESTION_ID = 85; // Obtain this from the url
// It will be like https://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page
var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";
var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk";
var OVERRIDE_USER = 3; // This should be the user ID of the challenge author.

/* App */

var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page;

function answersUrl(index) {
  return "https://api.stackexchange.com/2.2/questions/" +  QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER;
}

function commentUrl(index, answers) {
  return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER;
}

function getAnswers() {
  jQuery.ajax({
    url: answersUrl(answer_page++),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      answers.push.apply(answers, data.items);
      answers_hash = [];
      answer_ids = [];
      data.items.forEach(function(a) {
        a.comments = [];
        var id = +a.share_link.match(/\d+/);
        answer_ids.push(id);
        answers_hash[id] = a;
      });
      if (!data.has_more) more_answers = false;
      comment_page = 1;
      getComments();
    }
  });
}

function getComments() {
  jQuery.ajax({
    url: commentUrl(comment_page++, answer_ids),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      data.items.forEach(function(c) {
        if (c.owner.user_id === OVERRIDE_USER)
          answers_hash[c.post_id].comments.push(c);
      });
      if (data.has_more) getComments();
      else if (more_answers) getAnswers();
      else process();
    }
  });
}

getAnswers();

var SCORE_REG = /<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/;

var OVERRIDE_REG = /^Override\s*header:\s*/i;

function getAuthorName(a) {
  return a.owner.display_name;
}

function process() {
  var valid = [];

  answers.forEach(function(a) {
    var body = a.body;
    a.comments.forEach(function(c) {
      if(OVERRIDE_REG.test(c.body))
        body = '
' + c.body.replace(OVERRIDE_REG, '') + '
';
    });

    var match = body.match(SCORE_REG);
    if (match)
      valid.push({
        user: getAuthorName(a),
        size: +match[2],
        language: match[1],
        link: a.share_link,
      });
    else console.log(body);
  });

  valid.sort(function (a, b) {
    var aB = a.size,
        bB = b.size;
    return aB - bB
  });

  var languages = {};
  var place = 1;
  var lastSize = null;
  var lastPlace = 1;
  valid.forEach(function (a) {
    if (a.size != lastSize)
      lastPlace = place;
    lastSize = a.size;
    ++place;

    var answer = jQuery("#answer-template").html();
    answer = answer.replace("{{PLACE}}", lastPlace + ".")
                   .replace("{{NAME}}", a.user)
                   .replace("{{LANGUAGE}}", a.language)
                   .replace("{{SIZE}}", a.size)
                   .replace("{{LINK}}", a.link);
    answer = jQuery(answer);
    jQuery("#answers").append(answer);

    var lang = a.language;
    lang = jQuery(''+lang+'').text();

    languages[lang] = languages[lang] || {lang: a.language, lang_raw: lang, user: a.user, size: a.size, link: a.link};
  });

  var langs = [];
  for (var lang in languages)
    if (languages.hasOwnProperty(lang))
      langs.push(languages[lang]);

  langs.sort(function (a, b) {
    if (a.lang_raw.toLowerCase() > b.lang_raw.toLowerCase()) return 1;
    if (a.lang_raw.toLowerCase() < b.lang_raw.toLowerCase()) return -1;
    return 0;
  });

  for (var i = 0; i < langs.length; ++i)
  {
    var language = jQuery("#language-template").html();
    var lang = langs[i];
    language = language.replace("{{LANGUAGE}}", lang.lang)
                       .replace("{{NAME}}", lang.user)
                       .replace("{{SIZE}}", lang.size)
                       .replace("{{LINK}}", lang.link);
    language = jQuery(language);
    jQuery("#languages").append(language);
  }

}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  text-align: left !important;
  display: block !important;
}

#answer-list {
  padding: 10px;
  width: 290px;
  float: left;
}

#language-list {
  padding: 10px;
  width: 290px;
  float: left;
}

table thead {
  font-weight: bold;
}

table td {
  padding: 5px;
}</code>```

<link rel="stylesheet" type="text/css" href="https://cdn.sstatic.net/Sites/codegolf/all.css?v=ffb5d0584c5f">

Shortest Solution by Language

Language	User	Score

Leaderboard

	Author	Language	Size

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

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

```

答:
Julia, 20 bytes

!n=n>1?!~-n+!~-~-n:n
```

Straightforward implementation of the recursive definition. No match for the matrix approach, but a lovely opportunity to abuse Julia's ability to redefine operators.

Try it online!

ContentLicense: CC BY-SA 4.0

Title: Fibonacci function or sequence

Body:
Julia, 20 bytes

!n=n>1?!~-n+!~-~-n:n

Straightforward implementation of the recursive definition. No match for the matrix approach, but a lovely opportunity to abuse Julia's ability to redefine operators.

Try it online!


答:
JavaScript (Firefox 30-57), <s>92</s> 90 bytes

```<code>f=([c,...s])=>c?[for(t of f(s))for(d of new Set(c.toUpperCase()+c.toLowerCase()))d+t]:['']
</code>```

Edit: Saved 2 bytes because new Set will happily extract the unique characters from a string.

Title: Case Permutation

Body:
Who needs to compare things case insensitively when you're able to generate every permutation of uppercase and lowercase? No one! That's the answer. No one does. Your task is to achieve this feat; generate all possible permutations of uppercase/lowercase for a given input.

Input

A string of printable standard ascii characters. Input should not be assumed to be all lowercase. Input will always be at least one character.

Output

Every permutation of uppercase and lowercase for the inputted string (no duplicates). This should only change characters with a small and large version (numbers will stay the same). Each permutation must be output as a string or a list of characters; lists of singleton strings are not allowed.

Examples

```<code>a1a
['a1a', 'a1A', 'A1a', 'A1A']

abc
['abc', 'abC', 'aBc', 'aBC', 'Abc', 'AbC', 'ABc', 'ABC']

Hi!
['hi!', 'hI!', 'Hi!', 'HI!']
</code>```

Scoring

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

As a fun extra see how much additional effort it will take to handle the extended ascii characters, here is an extra test case:

```<code>ž1a -> ['ž1a', 'ž1A', 'Ž1a', 'Ž1A']
</code>```

(your program does not need to support this)

Body:
JavaScript (Firefox 30-57), <s>92</s> 90 bytes

f=([c,...s])=>c?[for(t of f(s))for(d of new Set(c.toUpperCase()+c.toLowerCase()))d+t]:['']

Edit: Saved 2 bytes because new Set will happily extract the unique characters from a string.


问:
The Ackermann function
The Ackermann function is notable for being the one of the simplest examples of a total, computable function that isn't primitive recursive.

We will use the definition of \$A(m,n)\$ taking in two nonnegative integers where

$$\begin{align}
A(0,n) & = n+1 \\
A(m,0) & = A(m-1,1) \\
A(m,n) & = A(m-1,A(m,n-1))
\end{align}$$

You may implement

a named or anonymous function taking two integers as input, returning an integer, or

a program taking two space- or newline-separated integers on STDIN, printing a result to STDOUT.

You may not use an Ackermann function or hyperexponentiation function from a library, if one exists, but you may use any other function from any other library. Regular exponentiation is allowed.

Your function must be able to find the value of \$A(m,n)\$ for \$m \le 3\$ and \$n \le 10\$ in less than a minute. It must at least theoretically terminate on any other inputs: given infinite stack space, a native Bigint type, and an arbitrarily long period of time, it would return the answer. Edit: If your language has a default recursion depth that is too restrictive, you may reconfigure that at no character cost.

The submission with the shortest number of characters wins.

Here are some values, to check your answer:

$$\begin{array}{c|cccccccccc}
A & n = 0 & 1 & 2 & 3 & 4 & 5 & 6 & 7 & 8 & 9 & 10 \\
\hline
m=0 & 1 & 2 & 3 & 4 & 5 & 6 & 7 & 8 & 9 & 10 & 11 \\
1 & 2 & 3 & 4 & 5 & 6 & 7 & 8 & 9 & 10 & 11 & 12 \\
2 & 3 & 5 & 7 & 9 & 11 & 13 & 15 & 17 & 19 & 21 & 23 \\
3 & 5 & 13 & 29 & 61 & 125 & 253 & 509 & 1021 & 2045 & 4093 & 8189 \\
4 & 13 & 65533 & \text{big}
\end{array}$$

答:
Julia, <s>34</s> <s>31</s> 28 bytes

m\n=m>0?~-m\(n<1||m\~-n):n+1
```

This is a named anonymous function. It is a straightforward implementation of the recursive definition, abusing Julia's ability to redefine operators.

Try it online!

Title: The Ackermann function

Body:
Julia, <s>34</s> <s>31</s> 28 bytes

m\n=m>0?~-m\(n<1||m\~-n):n+1

This is a named anonymous function. It is a straightforward implementation of the recursive definition, abusing Julia's ability to redefine operators.

Try it online!


Title: List all times in the day at a half hour rate

Body:
Shortest answer wins.

It must be sorted, and in 24hr time. The final line does not have a comma.

Output should be as follows:

```<code>'00:00',
'00:30',
'01:00',
'01:30',
'02:00',
'02:30',
'03:00',
'03:30',
'04:00',
'04:30',
'05:00',
'05:30',
'06:00',
'06:30',
'07:00',
'07:30',
'08:00',
'08:30',
'09:00',
'09:30',
'10:00',
'10:30',
'11:00',
'11:30',
'12:00',
'12:30',
'13:00',
'13:30',
'14:00',
'14:30',
'15:00',
'15:30',
'16:00',
'16:30',
'17:00',
'17:30',
'18:00',
'18:30',
'19:00',
'19:30',
'20:00',
'20:30',
'21:00',
'21:30',
'22:00',
'22:30',
'23:00',
'23:30'
</code>```

Body:
PHP, <s>104</s> 96 bytes

for($h=$m=0;$h<24;){echo($h||$m?",\n":"")."'".($h<10?0:"")."$h:".($m*3)."0'";if($m)$h++;$m=!$m;}

exploded view

for ($h = $m = 0; $h < 24; ) {
  echo ($h || $m ? ",\n" : "") . "'" . // echoes ",\n" on all but the first loop
       ($h < 10 ? 0 : "") . "$h:" .    // leading 0 for 0:00 - 9:30
       ($m * 3) . "0'";                // :00 if $m=0, :30 if $m=1
  if ($m) $h++;                        // increments $h if :30
  $m = !$m;                            // swaps :00 <-> :30
}


问:
Collide against walls

Statement

Given an input like this 35 15 0 0 10 that matches the following constrains:

Width in characters of the grid (5-50)

Height in characters of the grid (5-25)

Initial X position of the ball (0-(Width-1)

Initial Y position of the ball (0-(Height-1)

Number of movements to simulate

Generate a grid that shows the trajectory of the ball, knowing it's direction is initially DR (down-right) and that colliding with a wall will reverse the increment being applied to that axis. In other words, if we are going DR and hit the bottom we will now be going UR until we collide again.

The trajectory is not affected by passing twice over the same point since it's not the game snake, it's the trajectory of an object in 2d.

The input will be a string such as the one above and the output should be similar to this, not caring about which characters represent the wall, trajectory or ball, as long as they're consistent.

Points

Your score is the length of your submission, in characters.

Winners by language

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

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

```

答:
MATL, <s>35</s> 34 characters

```<code>Z"42Gi:qi!+lGqE!/tYo-KM!*|QYoZ}X](
</code>```

Try it online!

Explanation

This takes care of the reflections using the formulas

```<code>nx = 2*(Nx-1)
px = abs(t/nx-round(t/nx))*nx
</code>```

where t is a time variable that increases in steps of 1, Nx is the maximum size along the x direction and px is the computed x position. Analogous formulas are used for the y coordinate.

A char matrix of spaces is initially created, and then it is filled with character * at the computed x and y positions.

```<code>Z"     % Implicitly take [width height]. Push char matrix of spaces with that size
42     % Push 42. ASCII for character `*`
G      % Push first input again, that is, [width height]
i      % Take number of movements, M
:q     % Range [0 1 ... M-1]
i!     % Take initial position [x y]. Transpose into column vector
+      % Add element-wise with broadcast. Gives 2-row vector
lG     % Push first input, [width height]
qE!    % Transform into column vector [2*width-2; 2*height-2]
/      % Divide element-wise with broadcast
tYo    % Duplicate. Round to closest integer
-      % Subtract
KM!    % Push [2*width-2; 2*height-2] again
*      % Multiply element-wise with broadcast
|      % Absolute value
Q      % Add 1
Yo     % Round to closest integer
Z}     % Separate 2-row array into two row arrays. These contain row and column
       % indices, respectively, of the ball positions
X]     % Convert row and colummn indices to linear index
(      % Assign 42 to those positions of the matrix of spaces
</code>```

Title: Collide against walls

Body:
MATL, <s>35</s> 34 characters

Z"42Gi:qi!+lGqE!/tYo-KM!*|QYoZ}X](

Try it online!

Explanation

This takes care of the reflections using the formulas

nx = 2*(Nx-1)
px = abs(t/nx-round(t/nx))*nx

where t is a time variable that increases in steps of 1, Nx is the maximum size along the x direction and px is the computed x position. Analogous formulas are used for the y coordinate.

A char matrix of spaces is initially created, and then it is filled with character * at the computed x and y positions.

Z"     % Implicitly take [width height]. Push char matrix of spaces with that size
42     % Push 42. ASCII for character `*`
G      % Push first input again, that is, [width height]
i      % Take number of movements, M
:q     % Range [0 1 ... M-1]
i!     % Take initial position [x y]. Transpose into column vector
+      % Add element-wise with broadcast. Gives 2-row vector
lG     % Push first input, [width height]
qE!    % Transform into column vector [2*width-2; 2*height-2]
/      % Divide element-wise with broadcast
tYo    % Duplicate. Round to closest integer
-      % Subtract
KM!    % Push [2*width-2; 2*height-2] again
*      % Multiply element-wise with broadcast
|      % Absolute value
Q      % Add 1
Yo     % Round to closest integer
Z}     % Separate 2-row array into two row arrays. These contain row and column
       % indices, respectively, of the ball positions
X]     % Convert row and colummn indices to linear index
(      % Assign 42 to those positions of the matrix of spaces


答:
JavaScript (ES6), 135 bytes

```<code>s=>s.replace(/^[^1]*\n/,``).split`
`.map(s=>+`0b${s}`).reverse(g=(n,m,o=(m<<1|m|m>>1)&n)=>n-m?o-m&&g(n,o):n).reduce((m,n,i)=>g(n,n&m))
</code>```

Note: Due to limitations of integer type, only works for vines of up to 31 characters wide. Explanation: Each row is bitwise ANDed with the adjacent row to determine the connection points, and then the g function is used to recursively expand the row horizontally until it can expand no more. For instance, if two adjacent rows are 1110111 and 1011100 then the connection points are 1010100 and this is then expanded to 1110110 and then 1110111 which then finds that the row is connected. If the g function fails then it returns zero which causes all subsequent g functions to fail too, and the result is then falsy. If the g function succeeds it returns the new row which is then propagated through the reduce to test the next row.

```<code>s=>s.replace(/^[^1]*\n/,``)         Remove irrelevant leading "blank" rows
    .split`\n`                      Split into lines
    .map(s=>+`0b${s}`)              Convert into binary
    .reverse(                       Process from bottom to top
     g=(n,m,o=(m<<1|m|m>>1)&n)=>     Expand row horizontally
      n-m?o-m&&g(n,o):n)             Check whether rows are connected
    .reduce((m,n,i)=>g(n,n&m))      Check all rows
</code>```

Title: Recognize a vine

Body:
JavaScript (ES6), 135 bytes

s=>s.replace(/^[^1]*\n/,``).split`
`.map(s=>+`0b${s}`).reverse(g=(n,m,o=(m<<1|m|m>>1)&n)=>n-m?o-m&&g(n,o):n).reduce((m,n,i)=>g(n,n&m))

Note: Due to limitations of integer type, only works for vines of up to 31 characters wide. Explanation: Each row is bitwise ANDed with the adjacent row to determine the connection points, and then the g function is used to recursively expand the row horizontally until it can expand no more. For instance, if two adjacent rows are 1110111 and 1011100 then the connection points are 1010100 and this is then expanded to 1110110 and then 1110111 which then finds that the row is connected. If the g function fails then it returns zero which causes all subsequent g functions to fail too, and the result is then falsy. If the g function succeeds it returns the new row which is then propagated through the reduce to test the next row.

s=>s.replace(/^[^1]*\n/,``)         Remove irrelevant leading "blank" rows
    .split`\n`                      Split into lines
    .map(s=>+`0b${s}`)              Convert into binary
    .reverse(                       Process from bottom to top
     g=(n,m,o=(m<<1|m|m>>1)&n)=>     Expand row horizontally
      n-m?o-m&&g(n,o):n)             Check whether rows are connected
    .reduce((m,n,i)=>g(n,n&m))      Check all rows


问:
Alternating Sign Sequence

Introduction

The sign of a number is either a +, or a - for every non-zero integer. Zero itself is signless (+0 is the same as -0). In the following sequence, we are going to alternate between the positive sign, the zero and the negative sign. The sequence starts with 1, so we write 1 with a positive sign, with zero (this one is weird, but we just multiply the number by 0) and the negative sign:

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

The next number is 2, and we do the same thing again:

```<code>2, 0, -2
</code>```

The sequence eventually is:

```<code>1, 0, -1, 2, 0, -2, 3, 0, -3, 4, 0, -4, 5, 0, -5, 6, 0, -6, 7, 0, -7, ...
</code>```

Or a more readable form:

```<code>a(0) = 1
a(1) = 0
a(2) = -1
a(3) = 2
a(4) = 0
a(5) = -2
a(6) = 3
a(7) = 0
a(8) = -3
a(9) = 4
...
</code>```

The Task

Given a non-negative integer n, output the nth term of the above sequence. You can choose if you use the zero-indexed or one-indexed version.

Test cases:

Zero-indexed:

```<code>a(0) = 1
a(11) = -4
a(76) = 0
a(134) = -45
a(296) = -99
</code>```

Or if you prefer one-indexed:

```<code>a(1) = 1
a(12) = -4
a(77) = 0
a(135) = -45
a(297) = -99
</code>```

This is code-golf, so the submission with the smallest number of bytes wins!

答:
APL, 14 bytes

```<code>{⍵⌷∊{⍵0,-⍵}¨⍳⍵}
</code>```

This is 1-indexed, i.e.:

```<code>     {⍵⌷∊{⍵0,-⍵}¨⍳⍵}¨1 2 3 4 5 6 7 8
1 0 ¯1 2 0 ¯2 3 0
</code>```

Explanation:

```<code>{⍵⌷                   select the ⍵th element
   ∊                  from all elements in
    {⍵0,-⍵}           the values ⍵, 0, and -⍵
           ¨⍳⍵}       for each number in 1..⍵
</code>```

Title: Alternating Sign Sequence

Body:
APL, 14 bytes

{⍵⌷∊{⍵0,-⍵}¨⍳⍵}

This is 1-indexed, i.e.:

     {⍵⌷∊{⍵0,-⍵}¨⍳⍵}¨1 2 3 4 5 6 7 8
1 0 ¯1 2 0 ¯2 3 0

Explanation:

{⍵⌷                   select the ⍵th element
   ∊                  from all elements in
    {⍵0,-⍵}           the values ⍵, 0, and -⍵
           ¨⍳⍵}       for each number in 1..⍵


Title: Collide against walls

Body:
Statement

Given an input like this 35 15 0 0 10 that matches the following constrains:

Width in characters of the grid (5-50)

Height in characters of the grid (5-25)

Initial X position of the ball (0-(Width-1)

Initial Y position of the ball (0-(Height-1)

Number of movements to simulate

Generate a grid that shows the trajectory of the ball, knowing it's direction is initially DR (down-right) and that colliding with a wall will reverse the increment being applied to that axis. In other words, if we are going DR and hit the bottom we will now be going UR until we collide again.

The trajectory is not affected by passing twice over the same point since it's not the game snake, it's the trajectory of an object in 2d.

The input will be a string such as the one above and the output should be similar to this, not caring about which characters represent the wall, trajectory or ball, as long as they're consistent.

Points

Your score is the length of your submission, in characters.

Winners by language

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

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

```

Body:
JavaScript, <s>293</s> 279

Nothing too clever going on here.

EDIT: Saved 14 characters by initialising the 2D array differently.

p=prompt().split(' ')
a=[];for(i=0;i++<p[1];)a.push(new Array(~~p[0]).fill(' '))
x=~~p[2];y=~~p[3]
d=e=1
for(i=0;i++<p[4];){a[y][x]=i==p[4]?'x':'o'
if(x<1&&d<0||x>p[0]-2&&d>0)d*=-1
if(y<1&&e<0||y>p[1]-2&&e>0)e*=-1
x+=d;y+=e}o=''
for(i=0;i++<p[1];)o+=a[i-1].join('')+'\n'
alert(o)


Body:
TreeHugger, 1433 Bytes

TreeHugger is a bf variant that uses a binary tree instead of a linear tape. Read about it here and you can run scripts on the implementation here. As for how this program works, here is a rough run down:

Store the characters needed

In the first loop, get within 5 of the desired value

Manually adjust to the correct value

Walk through the tree and print the proper characters in the proper order

WARNING: This step is a little tedious

++++++++++[>++++++>+++++>+++++>++++>++++>+^^^^^<+++++>+++++^^^<++++>+++++>+++++^<+++++^^<+++++>+++++>++++++^<++++++^^<+++++>++++++^<+++++^^^^-]>-->+>-->->++++>^^^^^<+++>++^^^<->->+++^<++^^<-->+>---^<----^^<>-----^<++++^^^^<.<..^^>.>>.[.>]^^^^^^^^<.<..^^>[.>]^^^^^^^^<.<.^>.^^>.>>.[.>]^^^^^^^^<.<.^>.^^>[.>]^^^^^^^^<.<.<.^^^>.>>.[.>]^^^^^^^^<.<.<.^^^>[.>]^^^^^^^^<.<.>.^^^>.>>.[.>]^^^^^^^^<.<.>.^^^>[.>]^^^^^^^^<.<.^><.^^^>.>>.[.>]^^^^^^^^<.<.^><.^^^>[.>]^^^^^^^^<.<.^>>.^^^>.>>.[.>]^^^^^^^^<.<.^>>.^^^>[.>]^^^^^^^^<.<.<<.^^^^>.>>.[.>]^^^^^^^^<.<.<<.^^^^>[.>]^^^^^^^^<.<.<>.^^^^>.>>.[.>]^^^^^^^^<.<.<>.^^^^>[.>]^^^^^^^^<.<.><.^^^^>.>>.[.>]^^^^^^^^<.<.><.^^^^>[.>]^^^^^^^^<.<.>>.^^^^>.>>.[.>]^^^^^^^^<.<.>>.^^^^>[.>]^^^^^^^^<.>.^<.^^>.>>.[.>]^^^^^^^^<.>.^<.^^>[.>]^^^^^^^^<.>..^^>.>>.[.>]^^^^^^^^<.>..^^>[.>]^^^^^^^^<.>.^<<.^^^>.>>.[.>]^^^^^^^^<.>.^<<.^^^>[.>]^^^^^^^^<.>.^<>.^^^>.>>.[.>]^^^^^^^^<.>.^<>.^^^>[.>]^^^^^^^^<.>.<.^^^>.>>.[.>]^^^^^^^^<.>.<.^^^>[.>]^^^^^^^^<.>.>.^^^>.>>.[.>]^^^^^^^^<.>.>.^^^>[.>]^^^^^^^^<.>.^<<<.^^^^>.>>.[.>]^^^^^^^^<.>.^<<<.^^^^>[.>]^^^^^^^^<.>.^<<>.^^^^>.>>.[.>]^^^^^^^^<.>.^<<>.^^^^>[.>]^^^^^^^^<.>.^<><.^^^^>.>>.[.>]^^^^^^^^<.>.^<><.^^^^>[.>]^^^^^^^^<.>.^<>>.^^^^>.>>.[.>]^^^^^^^^<.>.^<>>.^^^^>[.>]^^^^^^^^<.<<.^.^^>.>>.[.>]^^^^^^^^<.<<.^.^^>[.>]^^^^^^^^<.<<.^^>.^^>.>>.[.>]^^^^^^^^<.<<.^^>.^^>[.>]^^^^^^^^<.<<..^^^>.>>.[.>]^^^^^^^^<.<<..^^^>[.>]^^^^^^^^<.<<.^>.^^^>.>>.[.>]^^^^^^^^<.<<.^>.^^^>.>.>.>.

Un-Golfed

The three digit numbers are the ASCII values we're aiming for in the approximation and adjustment phases. The numbers in the print phase, indicate the hour that we are printing.

# Approximation
+++++ +++++ [
058 > +++++ +
051 > +++++
048 > +++++
039 > ++++
044 > ++++
010 > +
^^^^^
053 < +++++
052 > +++++
^^^
039 < ++++
049 > +++++
053 > +++++
^
052 < +++++
^^
048 < +++++
051 > +++++
057 > +++++ +
^
056 < +++++ +
^^
050 < +++++
055 > +++++ +
^
054 < +++++
^^^^ -
]
# Adjustment
058 > --
051 > +
048 > --
039 > -
044 > ++++
010 >
^^^^^
053 < +++
052 > ++
^^^
039 < -
049 > -
053 > +++
^
052 < ++
^^
048 < --
051 > +
057 > ---
^
056 < ----
^^
050 <
055 > -----
^
054 < ++++
^^^^
# Print
0
<.<..^^     >.>>.[.>] ^^^^^ ^^^
<.<..^^     >[.>] ^^^^^ ^^^
1
<.<.^>.^^   >.>>.[.>] ^^^^^ ^^^
<.<.^>.^^   >[.>] ^^^^^ ^^^
2
<.<.<.^^^   >.>>.[.>] ^^^^^ ^^^
<.<.<.^^^   >[.>] ^^^^^ ^^^
3
<.<.>.^^^   >.>>.[.>] ^^^^^ ^^^
<.<.>.^^^   >[.>] ^^^^^ ^^^
4
<.<.^><.^^^ >.>>.[.>] ^^^^^ ^^^
<.<.^><.^^^ >[.>] ^^^^^ ^^^
5
<.<.^>>.^^^ >.>>.[.>] ^^^^^ ^^^
<.<.^>>.^^^ >[.>] ^^^^^ ^^^
6
<.<.<<.^^^^ >.>>.[.>] ^^^^^ ^^^
<.<.<<.^^^^ >[.>] ^^^^^ ^^^
7
<.<.<>.^^^^ >.>>.[.>] ^^^^^ ^^^
<.<.<>.^^^^ >[.>] ^^^^^ ^^^
8
<.<.><.^^^^ >.>>.[.>] ^^^^^ ^^^
<.<.><.^^^^ >[.>] ^^^^^ ^^^
9
<.<.>>.^^^^ >.>>.[.>] ^^^^^ ^^^
<.<.>>.^^^^ >[.>] ^^^^^ ^^^
10
<.>.^<.^^   >.>>.[.>] ^^^^^ ^^^
<.>.^<.^^   >[.>] ^^^^^ ^^^
11
<.>..^^     >.>>.[.>] ^^^^^ ^^^
<.>..^^     >[.>] ^^^^^ ^^^
12
<.>.^<<.^^^ >.>>.[.>] ^^^^^ ^^^
<.>.^<<.^^^ >[.>] ^^^^^ ^^^
13
<.>.^<>.^^^ >.>>.[.>] ^^^^^ ^^^
<.>.^<>.^^^ >[.>] ^^^^^ ^^^
14
<.>.<.^^^   >.>>.[.>] ^^^^^ ^^^
<.>.<.^^^   >[.>] ^^^^^ ^^^
15
<.>.>.^^^   >.>>.[.>] ^^^^^ ^^^
<.>.>.^^^   >[.>] ^^^^^ ^^^
16
<.>.^<<<.^^^^ >.>>.[.>] ^^^^^ ^^^
<.>.^<<<.^^^^ >[.>] ^^^^^ ^^^
17
<.>.^<<>.^^^^ >.>>.[.>] ^^^^^ ^^^
<.>.^<<>.^^^^ >[.>] ^^^^^ ^^^
18
<.>.^<><.^^^^ >.>>.[.>] ^^^^^ ^^^
<.>.^<><.^^^^ >[.>] ^^^^^ ^^^
19
<.>.^<>>.^^^^ >.>>.[.>] ^^^^^ ^^^
<.>.^<>>.^^^^ >[.>] ^^^^^ ^^^
20
<.<<.^.^^      >.>>.[.>] ^^^^^ ^^^
<.<<.^.^^      >[.>] ^^^^^ ^^^
21
<.<<.^^>.^^  >.>>.[.>] ^^^^^ ^^^
<.<<.^^>.^^  >[.>] ^^^^^ ^^^
22
<.<<..^^^    >.>>.[.>] ^^^^^ ^^^
<.<<..^^^    >[.>] ^^^^^ ^^^
23
<.<<.^>.^^^    >.>>.[.>] ^^^^^ ^^^
<.<<.^>.^^^    >.>.>.>.

This can be golfed down more, I have a 1198 byte version that should work, but I think this implementation might have a bug. So stay tuned until I finish debugging my own implementation.


Title: 24 and 12 Hour Times

Body:
Write a program or function with no input that prints or returns this string of 24-hour and 12-hour times:

```<code>00:00 12:00am
01:00  1:00am
02:00  2:00am
03:00  3:00am
04:00  4:00am
05:00  5:00am
06:00  6:00am
07:00  7:00am
08:00  8:00am
09:00  9:00am
10:00 10:00am
11:00 11:00am
12:00 12:00pm
13:00  1:00pm
14:00  2:00pm
15:00  3:00pm
16:00  4:00pm
17:00  5:00pm
18:00  6:00pm
19:00  7:00pm
20:00  8:00pm
21:00  9:00pm
22:00 10:00pm
23:00 11:00pm
</code>```

The string must be output exactly as it appears here. The only exception is that it may optionally have a single trailing newline.

So the MD5 hash of your output should be

```<code>827ae6e2dbb1df494930baedb3ee2653
</code>```

if you do not have a trailing newline and

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

if you do. (Your hash could be different if your system uses another type of newline but that's OK.)

The shortest code in bytes wins. Tiebreaker is earlier answer.

Body:
C# function, 100 bytes

void F(){for(int i=0;i<24;i++){Console.Write($"{i:00}:00 {(i+11)%12+1,2}:00 {(i>11?"p":"a")}m\n");}}

Ungolfed version:

void F()
{
    for (int i = 0; i < 24; i++)
    {
        Console.Write($"{i:00}:00 {(i + 11)%12 + 1,2}:00 {(i > 11 ? "p" : "a")}m\n");
    }
}

Console.Write() takes too many characters!


问:
Toggle a string

The challenge involve simply toggling a string within another string.

Explanation

If the toggle string is a substring of the main string, remove all instances of the toggle string from the main string; otherwise, append the toggle string at the end of the main string.

Rules

All string are composed of printable ASCII characters

The function should take two parameters: the main string and the toggle string.

The main string can be empty.

The toggle string cannot be empty.

The result should be a string, which can be empty.

The shortest answer wins.

Examples

```<code>function toggle(main_string, toggle_string){ ... }

toggle('this string has 6 words ', 'now')
=> 'this string has 6 words now'

toggle('this string has 5 words now', ' now')
=> 'this string has 5 words'
</code>```

Tests cases

```<code>'','a'          => 'a'
'a','a'         => ''

'b','a'         => 'ba'
'ab','a'        => 'b'

'aba','a'       => 'b'
'ababa', 'aba'  => 'ba'
</code>```

答:
PHP, 73 chars

<?$s=$argv[1];$t=$argv[2];echo!strpos($s,$t)?$s.$t:str_replace($t,'',$s);

Longer than the other php answer, but uninspired and fully working as a standalone in the console.

Title: Toggle a string


答:
R, 156 bytes/chars

As an unnamed function. It's quite long but I quite like the method.  There's probably a better way to do the 1 to w to 1 vector.

```<code>function(w,h,x,y,i)cat(c(' ','o')[1:(w*h)%in%(rep(c(c(1:w),c((w-1):2)),i)[x:((i=i-1)+x)+1]+(rep(c(c(1:h),c((h-1):2)),i)*w-w)[y:(i+y)+1])*1+1],fill=w,sep='')
</code>```

Brief explanation of function internals

```<code>cat(                                                 # output to STDOUT
  c(' ','o')                                         # vector of characters
    [1:(w*h)%in%(                                    # number of characters in the board
      rep(c(c(1:w),c((w-1):2)),i)[x:((i=i-1)+x)+1]+  # oscillating vector of x to w to 1 to x
      (rep(c(c(1:h),c((h-1):2)),i)*w-w)[y:(i+y)+1]   # similar to above but in steps of w
    *1+1]                                            # cause a vector of 1 or 2 to pick char
  ,fill=w,sep='')                                    # print width of w, no separator
</code>```

Like the other current answers this doesn't output the border, but I will add one if required.

Title: Collide against walls

Body:
R, 156 bytes/chars

As an unnamed function. It's quite long but I quite like the method.  There's probably a better way to do the 1 to w to 1 vector.

function(w,h,x,y,i)cat(c(' ','o')[1:(w*h)%in%(rep(c(c(1:w),c((w-1):2)),i)[x:((i=i-1)+x)+1]+(rep(c(c(1:h),c((h-1):2)),i)*w-w)[y:(i+y)+1])*1+1],fill=w,sep='')

Brief explanation of function internals

cat(                                                 # output to STDOUT
  c(' ','o')                                         # vector of characters
    [1:(w*h)%in%(                                    # number of characters in the board
      rep(c(c(1:w),c((w-1):2)),i)[x:((i=i-1)+x)+1]+  # oscillating vector of x to w to 1 to x
      (rep(c(c(1:h),c((h-1):2)),i)*w-w)[y:(i+y)+1]   # similar to above but in steps of w
    *1+1]                                            # cause a vector of 1 or 2 to pick char
  ,fill=w,sep='')                                    # print width of w, no separator

Like the other current answers this doesn't output the border, but I will add one if required.


问:
Collatz Conjecture (OEIS A006577)
This is the Collatz Conjecture (OEIS A006577):

Start with an integer n > 1.

Repeat the following steps:

If n is even, divide it by 2.

If n is odd, multiply it by 3 and add 1.

It is proven that for all positive integers up to 5 * 260, or about 5764000000000000000, n will eventually become 1.

Your task is to find out how many iterations it takes (of halving or tripling-plus-one) to reach 1.

Relevant xkcd :)

Rules:

Shortest code wins.

If a number < 2 is input, or a non-integer, or a non-number, output does not matter.

Test cases

```<code>2  -> 1
16 -> 4
5  -> 5
7  -> 16
</code>```

答:
Python 2, <s>38</s> 37 bytes

f=lambda n:n<3or-~f([n/2,n*3+1][n%2])
```

Thanks to @user84207 for a suggestion that saved 1 byte!

Note that this returns True instead of 1.

Try it online!

Title: Collatz Conjecture (OEIS A006577)

Body:
Python 2, <s>38</s> 37 bytes

f=lambda n:n<3or-~f([n/2,n*3+1][n%2])

Thanks to @user84207 for a suggestion that saved 1 byte!

Note that this returns True instead of 1.

Try it online!


答:
Python, 69 bytes

```<code>import itertools as i;f=lambda s:set(i.product(*zip(s,s.swapcase())))
</code>```

Title: Case Permutation

Body:
Python, 69 bytes

import itertools as i;f=lambda s:set(i.product(*zip(s,s.swapcase())))


问:
Find the smallest number bigger than the input whose digital sum is the input
"Digital sum" refers to the sum of all the digits in a number.

For example, the digital sum of 1324 is 10, because 1+3+2+4 = 10.

The challenge is to write a program/function to calculate the smallest number bigger than the input whose digital sum is the input.

Example with walkthrough

As an example, take the number 9 as the input:

```<code>9 = 1+8 -> 18
9 = 2+7 -> 27
9 = 3+6 -> 36
...
9 = 8+1 -> 81
9 = 9+0 -> 90
</code>```

The valid output would be the smallest number above, which is 18.

Specs

Note that 9 is not the valid output for this example, because the reversed number must be greater than the original number.

Note that the input will be positive.

Test-Cases:

```<code> 2 => 11      (2 = 1 + 1)
 8 => 17      (8 = 1 + 7)
12 => 39     (12 = 3 + 9)
16 => 79     (16 = 7 + 9)
18 => 99     (18 = 9 + 9)
24 => 699    (24 = 6 + 9 + 9)
32 => 5999   (32 = 5 + 9 + 9 + 9)
</code>```

References:

This is OEIS A161561.

Edit: Added an additional Testcase (18)

Thanks to Martin Ender for the Leaderboard Snippet

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

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

```

答:
Pyth, 8 bytes

```<code>fqQsjT;h
</code>```

Test suite.

```<code>fqQsjT;h

f      h first number T from (input+1) onward where:
 qQ          the input is equal to
   s         the sum of
    jT;      the base-10 representation of T
</code>```

Body:
Pyth, 8 bytes

fqQsjT;h

Test suite.

fqQsjT;h

f      h first number T from (input+1) onward where:
 qQ          the input is equal to
   s         the sum of
    jT;      the base-10 representation of T


答:
Retina, <s>39</s> 31 bytes

```<code>r`1{1,9}
$.&
T`d`_d`^.$
^.$
1$&
</code>```

Takes input in unary.

Try it online! (The first two lines allows running several test cases at once and converts from decimal to unary for  convenience.)

This doesn't actually search for the result linearly, but computes it explicitly:

If the input n is greater than 9, we replace it with n % 9 followed by n / 9 (floored) nines.

Otherwise, we replace it with n + 9.

Using ! (or anything else that isn't 1) as the unary digit, I can save one more byte with the following approach:

```<code>^!(?!!{9})
1
r`!{0,9}
$.&
0\B

</code>```

But this input format is a bit of a stretch, I think.

Title: Find the smallest number bigger than the input whose digital sum is the input

Body:
"Digital sum" refers to the sum of all the digits in a number.

For example, the digital sum of 1324 is 10, because 1+3+2+4 = 10.

The challenge is to write a program/function to calculate the smallest number bigger than the input whose digital sum is the input.

Example with walkthrough

As an example, take the number 9 as the input:

```<code>9 = 1+8 -> 18
9 = 2+7 -> 27
9 = 3+6 -> 36
...
9 = 8+1 -> 81
9 = 9+0 -> 90
</code>```

The valid output would be the smallest number above, which is 18.

Specs

Note that 9 is not the valid output for this example, because the reversed number must be greater than the original number.

Note that the input will be positive.

Test-Cases:

```<code> 2 => 11      (2 = 1 + 1)
 8 => 17      (8 = 1 + 7)
12 => 39     (12 = 3 + 9)
16 => 79     (16 = 7 + 9)
18 => 99     (18 = 9 + 9)
24 => 699    (24 = 6 + 9 + 9)
32 => 5999   (32 = 5 + 9 + 9 + 9)
</code>```

References:

This is OEIS A161561.

Edit: Added an additional Testcase (18)

Thanks to Martin Ender for the Leaderboard Snippet

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

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

```

Body:
Retina, <s>39</s> 31 bytes

r`1{1,9}
$.&
T`d`_d`^.$
^.$
1$&

Takes input in unary.

Try it online! (The first two lines allows running several test cases at once and converts from decimal to unary for  convenience.)

This doesn't actually search for the result linearly, but computes it explicitly:

If the input n is greater than 9, we replace it with n % 9 followed by n / 9 (floored) nines.

Otherwise, we replace it with n + 9.

Using ! (or anything else that isn't 1) as the unary digit, I can save one more byte with the following approach:

^!(?!!{9})
1
r`!{0,9}
$.&
0\B

But this input format is a bit of a stretch, I think.


答:
Python 2, 33 bytes

lambda n:[n+9,`n%9`+n/9*'9'][n>9]
```

A direct expression. Makes a number string with 9's at the end and the remainder at the beginning. Except, for single-digit n, gives n+9.

Some outputs have leading zeroes (099 for 18).

Body:
Python 2, 33 bytes

lambda n:[n+9,`n%9`+n/9*'9'][n>9]

A direct expression. Makes a number string with 9's at the end and the remainder at the beginning. Except, for single-digit n, gives n+9.

Some outputs have leading zeroes (099 for 18).


答:
Pyke, <s>9</s> <s>8</s> 7 bytes

```<code>.fhsq)h
</code>```

Try it here!

```<code>.f      - first where true:
  h     - n+1
   sq    - digital_root(^) == input()
      h - that number +1
</code>```

Body:
Pyke, <s>9</s> <s>8</s> 7 bytes

.fhsq)h

Try it here!

.f      - first where true:
  h     - n+1
   sq    - digital_root(^) == input()
      h - that number +1


问:
Minimum cost block diagonalisation
Consider binary block diagonal matrices which have square blocks of 1s on the main diagonal, and are 0 everywhere else. Let's call such matrices "valid" matrices.

For example, here are some valid 4x4 matrices:

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

Note that an alternative way of describing such matrices is that there is a chain of square 1 blocks from the top-left to the bottom-right, touching corner to corner, and everywhere else is 0.

For contrast, here are some invalid 4x4 matrices:

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

You will be given an n by n binary matrix as input – what is the minimum number of 0 bits you'll need to set to 1 in order to get a valid matrix?

You may write a function or program taking in any convenient string, list or matrix format representing an n by n matrix of 0s and 1s (as long as it isn't preprocessed). Rows must be clearly separated in some way, so formats like a 1D array of bits are not allowed.

This is code-golf, so the goal is to minimise the number of bytes in your program.

Examples

For example, if the input is

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

then the answer is 5, since you can set five 0 bits to 1 to get:

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

and this is the minimum number required. However, if the input was

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

then the answer is 24, since the only valid 5x5 matrix where the top-right is 1 is the matrix of all 1s.

Test cases

Tests are represented here as a 2D array of integers.

```<code>[[0]] -> 1
[[1]] -> 0
[[0,1],[0,0]] -> 3
[[1,0],[0,0]] -> 1
[[0,0,0],[0,1,0],[0,0,0]] -> 2
[[0,1,0],[0,0,0],[0,1,0]] -> 7
[[0,1,0],[1,0,0],[0,0,1]] -> 2
[[1,1,1],[1,1,1],[1,1,1]] -> 0
[[0,0,0,0],[0,0,1,0],[0,1,0,0],[0,0,0,0]] -> 4
[[0,0,1,0],[0,0,0,0],[0,0,0,0],[0,0,0,1]] -> 8
[[0,0,1,0],[0,0,0,0],[0,0,0,0],[0,0,1,0]] -> 14
[[0,0,1,0],[0,0,0,0],[0,0,0,0],[0,1,0,0]] -> 14
[[0,0,0,0,0],[0,0,0,0,0],[0,1,0,0,0],[0,0,0,0,1],[0,0,0,0,0]] -> 7
[[0,0,0,0,0],[0,0,0,0,0],[1,0,0,0,0],[0,0,0,0,1],[0,0,0,0,0]] -> 11
[[0,0,0,0,0],[0,0,1,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,1]] -> 5
[[0,0,0,0,1],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0]] -> 24
[[0,0,0,1,0],[0,0,0,0,1],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0]] -> 23
[[0,1,0,0,0],[1,0,0,0,0],[0,0,1,0,0],[0,0,0,0,1],[0,0,0,1,0]] -> 4
[[0,1,1,1,0],[0,1,1,0,1],[0,1,1,1,0],[0,1,0,0,1],[0,0,0,0,0]] -> 14
</code>```

Notes

Related challenge: Print a Block-Diagonal Matrix

Inspiration: Freedom Factory, Google Code Jam 2016 Problem 2D

答:
Python with numpy, 102

from numpy import*
lambda M:sum(diff([k for k in range(len(M)+1)if(M|M.T)[:k,k:].any()-1])**2)-M.sum()
```
<p>An efficient algorithm. Finds the "neck points" on the diagonal that can separate blocks. These have all 0's above and right, as well as below and left. The minimal blocks are those between neck points.</p>
```??000
??000
00???
00???
00???
```

The length of a block is the difference between consecutive neck points, so their total area of the sum of squares of these. Subtracting the sum of the original matrix then gives the number of flips needed from 0 to 1.

Title: Minimum cost block diagonalisation

Body:
Python with numpy, 102

from numpy import*
lambda M:sum(diff([k for k in range(len(M)+1)if(M|M.T)[:k,k:].any()-1])**2)-M.sum()

An efficient algorithm. Finds the "neck points" on the diagonal that can separate blocks. These have all 0's above and right, as well as below and left. The minimal blocks are those between neck points.

??000
??000
00???
00???
00???

The length of a block is the difference between consecutive neck points, so their total area of the sum of squares of these. Subtracting the sum of the original matrix then gives the number of flips needed from 0 to 1.


问:
Is it a lipogram?
A lipogram is a block of words that omits a particular symbol. Right now, I am avoiding our fifth symbol of 26 that commonly show up. You should know by now what I am omitting. If not, look up "lipogram" and you will know.

Your Task

With a char, a blank, and a following string (blanks may show up in this; with only ASCII 32-126 chars) in input, output falsy if this char is in input string, truthy if not. This char that you must look for will always fit in two spans: "A" to "Z" or "a" to "z" (ASCII 65-90, 97-122). Do not distinguish capitals and non-capitals. Also, don't worry about blanks or punctuation symbols. Both programs and functions satisfy. Also, you may split input char and string into two args for programs or functions, and string as first arg is okay.

Illustrations

Truthy

```<code>e This is a lipogram.
a You need to consider other letters too.
E Capitals also count.
</code>```

Falsy

```<code>e This sentence is not a lipogram (for e).
t This particular letter is surprisingly hard.
A You don't need to care about any non-alphabetic symbols.
</code>```

Non-lipogrammed version

A lipogram is a series of words that leaves out a letter. I left out the letter "e" above.

Your task is to take a character and a string (which may include spaces) as input, separated by a space or newline, and output falsy if the character is in the string, and truthy otherwise. You may assume the string is composed solely of printable ASCII characters (char codes 32-126). The character will always be in the English alphabet, and there is no difference between lowercase and uppercase. The character will not be a space or symbol. You may write a program or a function. For either, you may take the character and string as separate arguments, and the string may come first.

答:
Java, 51 bytes

```<code>return(!s.toLowerCase().contains(c.toLowerCase()));
</code>```

Uses s as input and c as char, but c must be of type String.

Title: Is it a lipogram?

Body:
Java, 51 bytes

return(!s.toLowerCase().contains(c.toLowerCase()));

Uses s as input and c as char, but c must be of type String.


答:
Actually, 17 bytes

```<code>╗1`;$♂≈Σ╜;)=)>*`╓
</code>```

Try it online!

Explanation:

```<code>╗1`;$♂≈Σ╜;)=)>*`╓
╗                  save input to reg0
 1`;$♂≈Σ╜;)=)>*`╓  first integer n (>= 0) where:
   ;$♂≈Σ╜;)=         the base-10 digital sum equals the input and
            )>*      is greater than the input
</code>```

Body:
Actually, 17 bytes

╗1`;$♂≈Σ╜;)=)>*`╓

Try it online!

Explanation:

╗1`;$♂≈Σ╜;)=)>*`╓
╗                  save input to reg0
 1`;$♂≈Σ╜;)=)>*`╓  first integer n (>= 0) where:
   ;$♂≈Σ╜;)=         the base-10 digital sum equals the input and
            )>*      is greater than the input


答:
Javascript ES6 <s>202</s> <s>181</s> 177 chars

```<code>(w,h,x,y,s)=>(a=(r=Array)(h).fill().map(_=>r(w).fill` `),eval("for(vx=vy=1;s--;x+=vx,y+=vy,a){a[y][x]=0;if(!x||x==w-1)vx*=-1;if(!y||y==h-1)vy*=-1;}"),a.map(r=>r.join``).join`
`)
</code>```

<s>Not very golfed, I take a another look at it once I get home.</s>

Title: Collide against walls

Body:
Javascript ES6 <s>202</s> <s>181</s> 177 chars

(w,h,x,y,s)=>(a=(r=Array)(h).fill().map(_=>r(w).fill` `),eval("for(vx=vy=1;s--;x+=vx,y+=vy,a){a[y][x]=0;if(!x||x==w-1)vx*=-1;if(!y||y==h-1)vy*=-1;}"),a.map(r=>r.join``).join`
`)

<s>Not very golfed, I take a another look at it once I get home.</s>


答:
Python 2, 39 bytes

lambda n:[n+9,(1+n%9)*10**(n/9)-1][n>9]
```
<p>Pure integer arithmetic.</p>
<h3>Full program with output</h3>
<pre class="lang-python prettyprint-override"><code>f=lambda n:[n+9,(1+n%9)*10**(n/9)-1][n>9]

print(f(2))
print(f(8))
print(f(12))
print(f(16))
print(f(17))
print(f(18))
print(f(24))
print(f(32))
</code>```

Output:

11
17
39
79
89
99
699
5999
```

Body:
Python 2, 39 bytes

lambda n:[n+9,(1+n%9)*10**(n/9)-1][n>9]

Pure integer arithmetic.

Full program with output

f=lambda n:[n+9,(1+n%9)*10**(n/9)-1][n>9]

print(f(2))
print(f(8))
print(f(12))
print(f(16))
print(f(17))
print(f(18))
print(f(24))
print(f(32))

Output:

11
17
39
79
89
99
699
5999


Title: 24 and 12 Hour Times

Body:
Ruby, 66 62 bytes

0.upto(23){|i| puts "%02d:00%3d:00#{'ap'[i/12]}m"%[i,(i-1)%12+1]}

New version

24.times{|i|puts"%02d:00%3d:00#{'ap'[i/12]}m"%[i,(i-1)%12+1]}


答:
Java 10, <s>114</s> 62 bytes

n->{var r="";for(int i=0;i++<n/9;r+=9);return(n>9?n%9:n+9)+r;}
```
<p>Try it online.</p>
<p>EDIT: <strong><s>130</s> 73 bytes</strong> without leading zeros (Thanks to <em>@levanth`</em>):</p>
<pre class="lang-java prettyprint-override"><code>n->{var r="";for(int i=0;i++<n/9;r+=9);return new Long((n>9?n%9:n+9)+r);}
</code>```

Try it online.

Explanation:

n->                           // Method with integer parameter and long return-type
  var r="";                   //  Result-String, starting empty
  for(int i=0;i++<n/9;r+=9);  //  Append `n` integer-divided by 9 amount of 9's to `r`
  return new Long(            //  Cast String to number to remove any leading zeroes:
    (n>9?                     //   If the input `n` is 10 or larger
      n%9                     //    Use `n` modulo-9
     :                        //   Else (`n` is smaller than 10):
      n+9)                    //    Use `n+9`
    +r);}                     //   And append `r`
```

Body:
Java 10, <s>114</s> 62 bytes

n->{var r="";for(int i=0;i++<n/9;r+=9);return(n>9?n%9:n+9)+r;}

Try it online.

EDIT: <s>130</s> 73 bytes without leading zeros (Thanks to @levanth`):

n->{var r="";for(int i=0;i++<n/9;r+=9);return new Long((n>9?n%9:n+9)+r);}

Try it online.

Explanation:

n->                           // Method with integer parameter and long return-type
  var r="";                   //  Result-String, starting empty
  for(int i=0;i++<n/9;r+=9);  //  Append `n` integer-divided by 9 amount of 9's to `r`
  return new Long(            //  Cast String to number to remove any leading zeroes:
    (n>9?                     //   If the input `n` is 10 or larger
      n%9                     //    Use `n` modulo-9
     :                        //   Else (`n` is smaller than 10):
      n+9)                    //    Use `n+9`
    +r);}                     //   And append `r`