答:
R, 94 bytes

```<code>N=scan();a=replicate(N,{x=sample(1e6,2);q=1:x[1];max(q[!x[1]%%q&!x[2]%%q])<2});(6*N/sum(a))^.5
</code>```

Relatively slow but still works. Replicate N times a function that takes 2 random numbers (from 1 to 1e6) and checks if their gcd is less than 2 (using an old gcd function of mine).

Title: Natural Pi #0 - Rock

Body:
R, 94 bytes

N=scan();a=replicate(N,{x=sample(1e6,2);q=1:x[1];max(q[!x[1]%%q&!x[2]%%q])<2});(6*N/sum(a))^.5

Relatively slow but still works. Replicate N times a function that takes 2 random numbers (from 1 to 1e6) and checks if their gcd is less than 2 (using an old gcd function of mine).


问:
Natural Pi #0 - Rock

Goal

Create a program/function that takes an input N, check if N random pairs of integers are relatively prime, and returns sqrt(6 * N / #coprime).

TL;DR

These challenges are simulations of algorithms that only require nature and your brain (and maybe some re-usable resources) to approximate Pi. If you really need Pi during the zombie apocalypse, these methods don't waste ammo! There are eight more challenges to come. Checkout the sandbox post to make recommendations.

Simulation

What are we simulating? Well, the probability that two random integers are relatively prime (ie coprime or gcd==1) is 6/Pi/Pi, so a natural way to calculate Pi would be to scoop up two buckets (or handfuls) of rocks; count them; see if their gcd is 1; repeat. After doing this a <s>couple</s> lot of times, sqrt(6.0 * total / num_coprimes) will tend towards Pi. If calculating the square-root in post-apocalyptic world makes you nervous, don't worry! There is Newton's Method for that.

How are we simulating this?

Take input N

Do the following N times:

Uniformly generate random positive integers, i and j

With 1 <= i , j <= 10^6

If gcd(i , j) == 1: result = 1

Else: result = 0

Take the sum of the N results, S

Return sqrt(6 * N / S)

Specification

Input

Flexible, take input in any of the standard ways (eg function parameter,STDIN) and in any standard format (eg String, Binary)

Output

Flexible, give output in any of the standard ways (eg return, print)

White space, trailing and leading white space is acceptable

Accuracy, please provide at least 4 decimal places of accuracy (ie 3.1416)

Scoring

Shortest code wins!

Test Cases

Your output may not line up with these, because of random chance. But on average, you should get about this much accuracy for the given value of N.

```<code>Input     ->  Output
-----         ------
100       ->  3.????
10000     ->  3.1???
1000000   ->  3.14??
</code>```

答:
PowerShell v2+, <s>118</s> 114 bytes

```<code>param($n)for(;$k-le$n;$k++){$i,$j=0,1|%{Random -mi 1};while($j){$i,$j=$j,($i%$j)}$o+=!($i-1)}[math]::Sqrt(6*$n/$o)
</code>```

Takes input $n, starts a for loop until $k equals $n (implicit $k=0 upon first entering the loop). Each iteration, get new Random numbers $i and $j (the -minimum 1 flag ensure we're >=1 and no maximum flag allows up to [int]::MaxValue, which is allowed by the OP since it's larger than 10e6).

We then go into a GCD while loop. Then, so long as the GCD is 1, $o gets incremented. At the end of the for loop, we do a simple [math]::Sqrt() call, which gets left on the pipeline and output is implicit.

Takes about 15 minutes to run with input 10000 on my ~1 year old Core i5 laptop.

Examples

```<code>PS C:\Tools\Scripts\golfing> .\natural-pi-0-rock.ps1 100
3.11085508419128

PS C:\Tools\Scripts\golfing> .\natural-pi-0-rock.ps1 1000
3.17820863081864

PS C:\Tools\Scripts\golfing> .\natural-pi-0-rock.ps1 10000
3.16756133579975
</code>```

ContentLicense: CC BY-SA 3.0

Title: Natural Pi #0 - Rock

Body:
PowerShell v2+, <s>118</s> 114 bytes

param($n)for(;$k-le$n;$k++){$i,$j=0,1|%{Random -mi 1};while($j){$i,$j=$j,($i%$j)}$o+=!($i-1)}[math]::Sqrt(6*$n/$o)

Takes input $n, starts a for loop until $k equals $n (implicit $k=0 upon first entering the loop). Each iteration, get new Random numbers $i and $j (the -minimum 1 flag ensure we're >=1 and no maximum flag allows up to [int]::MaxValue, which is allowed by the OP since it's larger than 10e6).

We then go into a GCD while loop. Then, so long as the GCD is 1, $o gets incremented. At the end of the for loop, we do a simple [math]::Sqrt() call, which gets left on the pipeline and output is implicit.

Takes about 15 minutes to run with input 10000 on my ~1 year old Core i5 laptop.

Examples

PS C:\Tools\Scripts\golfing> .\natural-pi-0-rock.ps1 100
3.11085508419128

PS C:\Tools\Scripts\golfing> .\natural-pi-0-rock.ps1 1000
3.17820863081864

PS C:\Tools\Scripts\golfing> .\natural-pi-0-rock.ps1 10000
3.16756133579975


问:
10 PRINT CHR$(205.5+RND(1)); : GOTO 10 in PHP (or anything else, for that matter)
Just had a 'spirited' conversation with a co-worker about the succinctness of the following BASIC statement:

```<code>10 PRINT CHR$(205.5+RND(1)); : GOTO 10
</code>```

It's the title of this book, and will simply print a sequence of / and \ characters, alternating between the two randomly, resulting in a pattern similar to this:

(Image borrowed from http://www.flickr.com/photos/rndmcnlly/5058442151/sizes/o/in/photostream/)

Being of a PHP proclivity, we wondered what the most compact way of writing the same thing in PHP would be, and came up with this:

```<code>while(1) { echo chr(47 + 45 * rand(0,1)); }
</code>```

chr(47) is a / character, and chr(92) is a \. So the statement echo chr(47 + 45 * rand(0,1)); will randomly alternate between the two, ad nauseam.

In a language of your choosing, write the shortest program or function to output an infinite random sequence of \ and / characters, where each character has an equal probability of being chosen.

答:
Powershell, 37 bytes

```<code>for(){Write-Host(Random("\","/"))-N}
</code>```

unfortunately there seem to be no shorter aliases for Write-Host that don't cause a new line after every char.

OwnerDisplayName: Judy

ContentLicense: CC BY-SA 4.0

Body:
Powershell, 37 bytes

for(){Write-Host(Random("\","/"))-N}

unfortunately there seem to be no shorter aliases for Write-Host that don't cause a new line after every char.


答:
><>, 14 bytes

I was hoping I could restrict it to a 3*3 square but didn't succeed.

```<code>"/\
~x/
o</
 !
</code>```

You can try it here.

Title: 10 PRINT CHR$(205.5+RND(1)); : GOTO 10 in PHP (or anything else, for that matter)

Body:
Just had a 'spirited' conversation with a co-worker about the succinctness of the following BASIC statement:

```<code>10 PRINT CHR$(205.5+RND(1)); : GOTO 10
</code>```

It's the title of this book, and will simply print a sequence of / and \ characters, alternating between the two randomly, resulting in a pattern similar to this:

(Image borrowed from http://www.flickr.com/photos/rndmcnlly/5058442151/sizes/o/in/photostream/)

Being of a PHP proclivity, we wondered what the most compact way of writing the same thing in PHP would be, and came up with this:

```<code>while(1) { echo chr(47 + 45 * rand(0,1)); }
</code>```

chr(47) is a / character, and chr(92) is a \. So the statement echo chr(47 + 45 * rand(0,1)); will randomly alternate between the two, ad nauseam.

In a language of your choosing, write the shortest program or function to output an infinite random sequence of \ and / characters, where each character has an equal probability of being chosen.

Body:
><>, 14 bytes

I was hoping I could restrict it to a 3*3 square but didn't succeed.

"/\
~x/
o</
 !

You can try it here.


问:
Greatest Common Divisor
Your task is to compute the greatest common divisor (GCD) of two given integers in as few bytes of code as possible.

You may write a program or function, taking input and returning output via any of our accepted standard methods (including STDIN/STDOUT, function parameters/return values, command-line arguments, etc.).

Input will be two non-negative integers. You should be able to handle either the full range supported by your language's default integer type, or the range [0,255], whichever is greater. You are guaranteed that at least one of the inputs will be non-zero.

You are not allowed to use built-ins that compute either the GCD or the LCM (least common multiple).

Standard code-golf rules apply.

Test Cases

```<code>0 2     => 2
6 0     => 6
30 42   => 6
15 14   => 1
7 7     => 7
69 25   => 1
21 12   => 3
169 123 => 1
20 142  => 2
101 202 => 101
</code>```

答:
PHP, <s>41</s> 51 bytes

similar to my LCM answer:

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

loop $d down from $argv[1] while $argv[1]/$d or $argv[2]/$d have a remainder.

Title: Greatest Common Divisor

Body:
PHP, <s>41</s> 51 bytes

similar to my LCM answer:

for($d=1+$a=$argv[1];$argv[2]%--$d||$a%$d;);echo$d;

loop $d down from $argv[1] while $argv[1]/$d or $argv[2]/$d have a remainder.


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

Rules:

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

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

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

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

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

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

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

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

Catalogue

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

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

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

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

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

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

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

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

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

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

Shortest Solution by Language

Language	User	Score

Leaderboard

	Author	Language	Size

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

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

```

答:
Befunge - 4 bytes

I’m surprised there isn’t already a Befunge answer on here.

```<code>1+:.
</code>```

Title: Count up forever

Body:
Befunge - 4 bytes

I’m surprised there isn’t already a Befunge answer on here.

1+:.


问:
How many times will a bell tower ring?

Introduction

A bell tower will ring its bells every hour, n times, with n being the the current hour on a 12 hour clock.

For example, a bell will ring 5 times at 5pm, and 10 times at 10am.

Task

Given two times in a suitable format, output the number of times the bell will ring, inclusive of the start and end times

Examples

```<code>"10am-12pm"
10+11+12= 33

[01:00, 05:00]
1+2+3+4+5 = 15

[11, 15]
11+12+1+2+3 = 29

[10:00pm, 10:00am]
10+11+12+1+2+3+4+5+6+7+8+9+10 = 88
</code>```

If the start is the same as the end then the you simply just ouput the number of chimes for that hour:

```<code>[5pm, 5pm]
5 = 5
</code>```

As you can see, you may choose an input method but the output must be an integer on its own (or an acceptable alternative) trailing/ leading newlines and spaces are allowed.

Note:

inputs may span from the afternoon of one day to the morning of the next.

the difference between the two times will never be more than 24 hours.

input is flexible so long as you clearly state what format your input is.

your input must have a clear distinction between AM and PM.

答:
PHP, 69 bytes

```<code>list(,$i,$a)=$argv;for($a+=$i>$a?24:0;$i<=$a;)$n+=$i++%12?:12;echo$n;
</code>```

The list extraction was inspired by Jörg Hülsermann's answer but the rest of the similarities are a result of convergent evolution and because it's quite a lot shorter and the conditionals in the loop are different enough I'm posting it as a separate answer.

Takes input as 24 hour times (fine with either 0 or 24). Run like:

```<code>php -r "list(,$i,$a)=$argv;for($a+=$i>$a?24:0;$i<=$a;)$n+=$i++%12?:12;echo$n;" 9 18
</code>```

Title: How many times will a bell tower ring?

Body:
PHP, 69 bytes

list(,$i,$a)=$argv;for($a+=$i>$a?24:0;$i<=$a;)$n+=$i++%12?:12;echo$n;

The list extraction was inspired by Jörg Hülsermann's answer but the rest of the similarities are a result of convergent evolution and because it's quite a lot shorter and the conditionals in the loop are different enough I'm posting it as a separate answer.

Takes input as 24 hour times (fine with either 0 or 24). Run like:

php -r "list(,$i,$a)=$argv;for($a+=$i>$a?24:0;$i<=$a;)$n+=$i++%12?:12;echo$n;" 9 18


问:
Find the program that prints this integer sequence (Cops' thread)
This is the cops' thread. The robbers' thread goes here.

The last cops-and-robbers thread was already 4 months ago.

The cop's task

The cop's task is to write a program/function that takes a positive (or non-negative) integer and outputs/returns another integer.

The cop must state it if the program is intolerant towards zero.

The cop will provide at least 2 sample inputs/outputs.

For example, if I have decided to write the Fibonacci sequence, I would write this in my answer:

```
a(0) returns 0
a(3) returns 2
```

The number of examples is up to the cop's discretion.

However, the sequence must actually exist in the On-Line Encyclopedia of Integer Sequences®, so no pseudo-random number generator for you. :(

The cop can hide as many characters as is so wished.

For example, if my program is:

```<code>function a(n)
    if n>2 then
        return n
    else
        return a(n-1) + a(n-2)
    end
end
</code>```

Then I would hide these characters as I want:

```<code>function a(n)
    if ### then
        ########
    else
        ######################
    end
end
</code>```

The robber's task

is obviously to find the original source code.

However, any proposed source code that produces the same set of output also counts as valid, as long as it is also found in OEIS.

Tips for the cops

<s>The search function in the OEIS only works for consecutive terms, so if you want to hide your sequence, then just leave a hole anywhere.</s>

Apparently there is no way to hide the sequence. Put this in mind when you choose the sequence.

Your score is the number of bytes in your code.

The winner will be the submission with the lowest score that hasn't been cracked in 7 days.

Only submissions that are posted in 2016 April are eligible for the win. Submissions that are posted later than this are welcome, but cannot win.

In order to claim the win you need to reveal the full code and the OEIS sequence (after 7 days).

Your post should be formatted like this (NN is the number of characters):

Lua, 98 bytes

Output:

```<code>a(0) returns 0
a(3) returns 2
</code>```

Code (# marks unrevealed characters):

```<code>function a(n)
    if ### then
        ########
    else
        ######################
    end
end
</code>```

If the code is cracked, insert [Cracked](link to cracker) in the header.
If the submission is safe, insert "Safe" in the header and reveal the full code in your answer. Only answers that have revealed the full code will be eligible for the win.

Body:
Python, 42 bytes Cracked

def f(x):return # if x<#else ######+######

Where

f(0) -> 0
f(1) -> 1
f(7) -> 13
f(15) -> 610


问:
Find the program that prints this integer sequence (Robbers' thread)
This is the robbers' thread. The cops' thread goes here.

In the cops thread, the task was to write a program/function that takes a positive (or non-negative) integer and outputs/returns another number (not necessarily integer). The robbers task is to unscramble the code the cops used to produce this output.

The cracked code doesn't have to be identical, as long as it has the same length and any revealed characters are in the correct positions. The language must also be the same (version numbers can be different). The output must of course be identical.

No-ops can be used in robber's solution.

The winner of the robbers thread will be the user who has cracked the
most submissions by May 7th 2016. If there's a tie, the user who has cracked submissions with the longest combined code will win.

The submission should be formatted like this:

Language, nn characters (including link to answer), Cop's username

Code:

```<code>function a(n)
    if n<2 then
        return n
    else
        return a(n-1) + a(n-2)
    end
end
</code>```

Output

```<code>a(0) returns 0
a(3) returns 2
</code>```

Optional explanation and comments.

答:
Python, 42 bytes, TùxCräftîñg

```<code>def f(x):return x if x<2else f(x-1)+f(x-2)
</code>```

This is the Fibonacci sequence.

Body:
Python, 42 bytes, TùxCräftîñg

def f(x):return x if x<2else f(x-1)+f(x-2)

This is the Fibonacci sequence.


问:
pssssssssssssst
Introduction

This is one is pretty straightforward. We will be drawing a snake in ascii. This was inspired by that old snake game where you have to collect the fruit and you continuously grow.

Definition

Given a positive integer N that represents the snake's length, draw a snake so that it has a body of n plus a head and a tail.

Parts:

head:     <, >, ^, v

tail:     @

vertical: |

horizonal: -

All corners should be satisfied with a \ or / respectively. Unless the head ends on a corner in which case the head <, >, ^, v takes priority in the direction the snake is curled. i.e. for the length 1 example, it is turned counter clockwise and so the head is turned that way. For a clockwise solution it would be to the right >.

The snake must start in the middle with its tail but it may go outwards in any direction you choose either clockwise or counter-clockwise. It must also wrap tightly around itself as it expands outwards in a circular fashion.

Example

```<code>/--\
|/\|
||@|
|\-/
\--->
</code>```

Where the @ is the tail and starting position. As seen above the tail starts in the middle, goes up to the left in a counter-clockwise rotation outward.

Here the length is 19 plus a tail and a head.

As another example, here is length 1:

```<code><\
 @

</code>```

Winning

This is code-golf so the answer that is submitted with the smallest number of bytes wins, with time to be used as a tie breaker.

Have fun!

答:
Python 2, <s>250</s> <s>233</s> 191 bytes

```<code>n=input()
l=[''],
a=x=0
b='@'
while a<=n:x+=1;l+=b,;l=zip(*l[::-1]);m=x%2;b='\/'[m]+x/2*'-|'[m];k=len(b);a+=k
l+=b[:n-a]+'>v'[m]+' '*(k-n+a-1),
if m:l=zip(*l[::-1])
for i in l:print''.join(i)
</code>```

 Saved 39 bytes thanks to @JonathanAllan

repl.it

Draw the snake by rotating the entire snake 90º clockwise and adding the bottom segment, this way the snake will always be anticlockwise.

The new segment will always start with \ and have - as body for even sides and / - for odd sides. The segments sizes (without corners) are 0,1,1,2,2,3... which is floor(side/2).
If the segment is the last, it remove the excess characters, add the head and complete with spaces.

```<code>desired_size=input()
snake=[['']]
snake_size=side=0
new_segment='@'
while snake_size<=desired_size:
    side+=1
    snake+=[new_segment]
    snake=zip(*snake[::-1])
    odd_side=side%2
    new_segment='\/'[odd_side]+side/2*'-|'[odd_side]
    snake_size+=len(new_segment)
diff=desired_size-snake_size
snake+=[new_segment[:diff]+'>v'[odd_side]+' '*(len(new_segment)-diff-1)]
if odd_side:
    snake=zip(*snake[::-1])

for line in snake:print ''.join(line)
</code>```

Title: pssssssssssssst

Body:
Python 2, <s>250</s> <s>233</s> 191 bytes

n=input()
l=[''],
a=x=0
b='@'
while a<=n:x+=1;l+=b,;l=zip(*l[::-1]);m=x%2;b='\/'[m]+x/2*'-|'[m];k=len(b);a+=k
l+=b[:n-a]+'>v'[m]+' '*(k-n+a-1),
if m:l=zip(*l[::-1])
for i in l:print''.join(i)

 Saved 39 bytes thanks to @JonathanAllan

repl.it

Draw the snake by rotating the entire snake 90º clockwise and adding the bottom segment, this way the snake will always be anticlockwise.

The new segment will always start with \ and have - as body for even sides and / - for odd sides. The segments sizes (without corners) are 0,1,1,2,2,3... which is floor(side/2).
If the segment is the last, it remove the excess characters, add the head and complete with spaces.

desired_size=input()
snake=[['']]
snake_size=side=0
new_segment='@'
while snake_size<=desired_size:
    side+=1
    snake+=[new_segment]
    snake=zip(*snake[::-1])
    odd_side=side%2
    new_segment='\/'[odd_side]+side/2*'-|'[odd_side]
    snake_size+=len(new_segment)
diff=desired_size-snake_size
snake+=[new_segment[:diff]+'>v'[odd_side]+' '*(len(new_segment)-diff-1)]
if odd_side:
    snake=zip(*snake[::-1])

for line in snake:print ''.join(line)


答:
MATL, <s>85</s> 83 bytes

And I thought that having a spiral builtin would make for short code...

```<code>Oli2+XH:UQXItH:+XJh(YsXKoQ3I(4J(5l(H:)0HX^XkU(6H(3M1YL3X!P)'|-\/@' '<v>^'KHq))h0hw)
</code>```

Try it online!

Explanation

Let N denote the input. We will create a vector of length ceil(sqrt(N+2))^2, that is, the smallest perfect square that equals or exceeds N+2. This vector will be filled with numeric values, rolled into a spiral (that's why its length needs to be a perfect square), and then the numeric values will be replaced by characters.

Let n denote each step starting from 1 at the center of the spiral. The steps where the snake turns are given by n2+1 (that is: 2, 5, 10, ...) for \ symbols and n2+n+1 (that is: 3, 7, 13, ...) for /. The steps between a \ and a / should be -, and those between a / and a \ should be |.

The vector is created such that it contains 1 at the turn points (2,3,5,7,10,13...) and 0 at the rest. The parity of the cumulative sum tells if each entry should be a - or a |. Adding 1 to this result we get a vector containing 1 (for |) or 2 (for -). But this makes the turn points themselves become 1 or 2 too. So the turn points, whose positions we know, are overwritten: positions n2+1 are filled with 3 and positions n2+n+1 are filled with 4. The tail and head are also special cases: the first element of the vector (tail) is set to 5, and the element with index N+2 (head) is set to 6. Finally, elements with indices exceeding N+2 are set to 0.

Taking input N=19 as an example, we now have a vector with length 25:

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

We need to roll this vector into a spiral. For this we use a builtin function that generates a spiral matrix, followed by a reflection and a transposition to produce:

```<code>13 12 11 10 25
14  3  2  9 24
15  4  1  8 23
16  5  6  7 22
17 18 19 20 21
</code>```

Indexing the vector with the matrix gives

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

where 0 corresponds to space, 1 corresponds to |, 2to -, 3 to \, 4 to /, 5 to @, and 6 to the head.

To know which of the four characters ^, <, v, or > the head should have, we use the cumulative sum of turn points that we previously computed. Specifically, the second-last value of this cumulative sum (i.e. the N+1-th value) modulo 4 tells us which character should be used for the head. We take the second-last value of the cumulative sum, not the last, because of the requirement "if the head ends on a corner the head <, >, ^, v takes priority in the direction the snake is curled". For the N=19 example the head  is >.

Now we can build a string containing all the snake characters, including the appropriate character for the head at the sixth position: '|-\/@> '. We then index this string with the above matrix  (indexing is 1-based and modular, so space goes last), which gives

```<code>/--\
|/\|
||@|
|\-/
\--->
</code>```

Title: pssssssssssssst

Body:
Introduction

This is one is pretty straightforward. We will be drawing a snake in ascii. This was inspired by that old snake game where you have to collect the fruit and you continuously grow.

Definition

Given a positive integer N that represents the snake's length, draw a snake so that it has a body of n plus a head and a tail.

Parts:

head:     <, >, ^, v

tail:     @

vertical: |

horizonal: -

All corners should be satisfied with a \ or / respectively. Unless the head ends on a corner in which case the head <, >, ^, v takes priority in the direction the snake is curled. i.e. for the length 1 example, it is turned counter clockwise and so the head is turned that way. For a clockwise solution it would be to the right >.

The snake must start in the middle with its tail but it may go outwards in any direction you choose either clockwise or counter-clockwise. It must also wrap tightly around itself as it expands outwards in a circular fashion.

Example

```<code>/--\
|/\|
||@|
|\-/
\--->
</code>```

Where the @ is the tail and starting position. As seen above the tail starts in the middle, goes up to the left in a counter-clockwise rotation outward.

Here the length is 19 plus a tail and a head.

As another example, here is length 1:

```<code><\
 @

</code>```

Winning

This is code-golf so the answer that is submitted with the smallest number of bytes wins, with time to be used as a tie breaker.

Have fun!

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

And I thought that having a spiral builtin would make for short code...

Oli2+XH:UQXItH:+XJh(YsXKoQ3I(4J(5l(H:)0HX^XkU(6H(3M1YL3X!P)'|-\/@' '<v>^'KHq))h0hw)

Try it online!

Explanation

Let N denote the input. We will create a vector of length ceil(sqrt(N+2))^2, that is, the smallest perfect square that equals or exceeds N+2. This vector will be filled with numeric values, rolled into a spiral (that's why its length needs to be a perfect square), and then the numeric values will be replaced by characters.

Let n denote each step starting from 1 at the center of the spiral. The steps where the snake turns are given by n2+1 (that is: 2, 5, 10, ...) for \ symbols and n2+n+1 (that is: 3, 7, 13, ...) for /. The steps between a \ and a / should be -, and those between a / and a \ should be |.

The vector is created such that it contains 1 at the turn points (2,3,5,7,10,13...) and 0 at the rest. The parity of the cumulative sum tells if each entry should be a - or a |. Adding 1 to this result we get a vector containing 1 (for |) or 2 (for -). But this makes the turn points themselves become 1 or 2 too. So the turn points, whose positions we know, are overwritten: positions n2+1 are filled with 3 and positions n2+n+1 are filled with 4. The tail and head are also special cases: the first element of the vector (tail) is set to 5, and the element with index N+2 (head) is set to 6. Finally, elements with indices exceeding N+2 are set to 0.

Taking input N=19 as an example, we now have a vector with length 25:

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

We need to roll this vector into a spiral. For this we use a builtin function that generates a spiral matrix, followed by a reflection and a transposition to produce:

13 12 11 10 25
14  3  2  9 24
15  4  1  8 23
16  5  6  7 22
17 18 19 20 21

Indexing the vector with the matrix gives

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

where 0 corresponds to space, 1 corresponds to |, 2to -, 3 to \, 4 to /, 5 to @, and 6 to the head.

To know which of the four characters ^, <, v, or > the head should have, we use the cumulative sum of turn points that we previously computed. Specifically, the second-last value of this cumulative sum (i.e. the N+1-th value) modulo 4 tells us which character should be used for the head. We take the second-last value of the cumulative sum, not the last, because of the requirement "if the head ends on a corner the head <, >, ^, v takes priority in the direction the snake is curled". For the N=19 example the head  is >.

Now we can build a string containing all the snake characters, including the appropriate character for the head at the sixth position: '|-\/@> '. We then index this string with the above matrix  (indexing is 1-based and modular, so space goes last), which gives

/--\
|/\|
||@|
|\-/
\--->


Title: Retrieve all possible marks that can be placed in a Sudoku puzzle

Body:
Given a Sudoku puzzle, find all possible marks that can be filled into each empty cell.

Test case

Input:

```<code>[
    [
        // Top left:
        [
            0, 0, 0,
            3, 4, 0,
            0, 0, 2
        ],
        // Top middle:
        [
            7, 4, 0,
            0, 0, 0,
            0, 0, 3
        ],
        // Top right:
        [
            8, 0, 0,
            1, 7, 0,
            0, 0, 0
        ]
    ],
    [
        // Middle left:
        [
            9, 0, 4,
            7, 0, 0,
            1, 0, 3
        ],
        // Center:
        [
            0, 5, 0,
            0, 0, 0,
            0, 7, 0
        ],
        // Middle right:
        [
            0, 0, 0,
            6, 4, 0,
            0, 0, 0
        ]
    ],
    [
        // Bottom left:
        [
            0, 0, 7,
            6, 3, 0,
            0, 0, 0
        ],
        // Bottom middle:
        [
            0, 0, 5,
            0, 0, 0,
            9, 1, 0
        ],
        // Bottom right:
        [
            0, 0, 0,
            5, 2, 0,
            7, 0, 0
        ]
    ]
]
</code>```

Output:

```<code>[
    [
        // Top left:
        [
            [5], [1, 5, 6, 9], [1, 5, 6, 9],
            [], [], [5, 6, 8, 9],
            [5, 8], [1, 5, 6, 7, 8, 9], []
        ],
        // Top middle:
        [
            [], [], [1, 2, 6, 9],
            [2, 5, 6, 8], [2, 6, 8, 9], [2, 6, 8, 9],
            [1, 5, 6, 8], [6, 8, 9], []
        ],
        // Top right:
        [
            [], [3, 5, 6, 9], [2, 3, 5, 6, 9],
            [], [], [2, 5, 6, 9],
            [4, 9], [5, 6, 9], [4, 5, 6, 9]
        ]
    ],
    [
        // Middle left:
        [
            [], [2, 6, 8], [],
            [], [2, 5, 8], [5, 8],
            [], [2, 5, 6, 8], []
        ],
        // Center:
        [
            [1, 2, 3, 6, 8], [], [1, 2, 6, 8],
            [1, 2, 3, 8], [2, 3, 8, 9], [1, 2, 8, 9],
            [2, 4, 6, 8], [], [2, 4, 6, 8, 9]
        ],
        // Middle right:
        [
            [2, 3], [1, 3, 8], [1, 2, 3, 7, 8],
            [], [], [1, 2, 3, 5, 8, 9],
            [2, 9], [5, 8, 9], [2, 5, 8, 9]
        ]
    ],
    [
        // Bottom left:
        [
            [2, 4, 8], [1, 2, 8, 9], [],
            [], [], [1, 8, 9],
            [2, 4, 5, 8], [2, 5, 8], [5, 8]
        ],
        // Bottom middle:
        [
            [2, 3, 4, 6, 8], [2, 3, 6, 8], [],
            [4, 8], [8], [4, 7, 8],
            [], [], [2, 4, 6, 8]
        ],
        // Bottom right:
        [
            [3, 4, 9], [1, 3, 6, 8, 9], [1, 3, 4, 6, 8, 9],
            [], [], [1, 4, 8, 9],
            [], [3, 6, 8], [3, 4, 6, 8]
        ]
    ]
]
</code>```

Output visualisation; the small numbers:

Rules

This is a code-golf. The shortest answer in bytes (or equivalent) wins.

Input can be in array or string format.

Input must be in the order presented above (top-left, top-middle, top-right, etc...)

Output can be in array or string format, as long as the output can logically represent the expected result.

Output must be in the same order as the input (top-left, top-middle, top-right, etc...)

Output does not need to be prettified.

Code must be applicable to any valid incomplete Sudoku grid.

Standard golfing rules apply.

Additional Notes:

You get additional fake internet points if your program or function uses the result to solve the Sudoku puzzle to the point where cell values can no longer be logically solved. For example, the very first cell in the test case can only ever possibly contain the number 5, so it should be considered when filling in the other values. This is just for fun and additional challenge, otherwise the shortest answer wins regardless of whether or not this criterion is met.

Body:
C (gcc), 193 bytes

#define F(x)for(x=0;x<9;++x)
char s[99];main(k,r,c){gets(s);F(r)F(c){
int d[99]={};F(k)d[s[r*9+k]]=d[s[k*9+c]]=d[s[r/3*27+k/3*9+c/3*3+k%3]]=1;
F(k)s[r*9+c]<48&&!d[49+k]&&putchar(49+k);puts("");}}

Assumes input in the following format (same sudoku as above):

..74.8..34....17...2..3...9.4.5....7.....64.1.3.7......7..5...63....52....91.7..

And outputs in the following format:

5
1569
1569

1269

3569
23569

5689
etc


答:
JavaScript (ES6), <s>208</s> <s>196</s> <s>190</s> <s>188</s> 186 bytes

g=>g.map((B,i)=>[...B].map((s,x)=>+s||[..."123456789"].filter(n=>(t=i=>(k=g[i].search(n)%m)b)(j=i%3,m=3,a=b=x%3)&t(j+3)&t(j+6)&t(j=i-j,m=9,a=x-a,b=a+2)&t(j+1)&t(j+2)&t(i,a=0,b=8))))
```

<p><strong>Input</strong>:<br>
An array of 9 strings (one per box, from top-left to bottom-right).</p>

<p><strong>Output</strong>:<br>
An array of 9 arrays, where each item consists of either the original number at this position or an array of characters representing the possible digits.</p>

<h3>Formatted and commented</h3>

<pre class="lang-js prettyprint-override"><code>g => g.map((B, i) =>              // for each box B at position i in the grid:
  [...B].map((s, x) =>            // for each cell s at position x in this box:
    +s ||                         // if there already is a number at this position, use it
    [..."123456789"].filter(n =>  // else, for each digit n in [1 .. 9]:
      (t = i =>                   // t() = helper function that looks for the digit n inside
        (k = g[i].search(n) % m)  // a given box i and returns a truthy value if its
        < a | k > b               // position modulo m is not in the range [a .. b]
      )(                          //
        j = i % 3,                // test the top box in the current column, using:
        m = 3,                    // modulo = 3 and
        a = b = x % 3             // range = [x % 3 .. x % 3]
      ) &                         //
      t(j + 3) &                  // test the middle box in the current column
      t(j + 6) &                  // test the bottom box in the current column
      t(                          //
        j = i - j,                // test the left box in the current row, using:
        m = 9,                    // modulo = 9 and
        a = x - a, b = a + 2      // range = [floor(x / 3) .. floor(x / 3) + 2]
      ) &                         //
      t(j + 1) &                  // test the middle box in the current row
      t(j + 2) &                  // test the right box in the current row
      t(i, a = 0, b = 8)          // finally test the current box, using:
    )                             // modulo = 9 (unchanged) and
  )                               // range = [0 .. 8] (thus testing the entire box)
)                                 //
</code>```

Demo

let f =

g=>g.map((B,i)=>[...B].map((s,x)=>+s||[..."123456789"].filter(n=>(t=i=>(k=g[i].search(n)%m)b)(j=i%3,m=3,a=b=x%3)&t(j+3)&t(j+6)&t(j=i-j,m=9,a=x-a,b=a+2)&t(j+1)&t(j+2)&t(i,a=0,b=8))))

console.log(f([
  "000340002",
  "740000003",
  "800170000",
  "904700103",
  "050000070",
  "000640000",
  "007630000",
  "005000910",
  "000520700"
]));```

Body:
JavaScript (ES6), <s>208</s> <s>196</s> <s>190</s> <s>188</s> 186 bytes

g=>g.map((B,i)=>[...B].map((s,x)=>+s||[..."123456789"].filter(n=>(t=i=>(k=g[i].search(n)%m)<a|k>b)(j=i%3,m=3,a=b=x%3)&t(j+3)&t(j+6)&t(j=i-j,m=9,a=x-a,b=a+2)&t(j+1)&t(j+2)&t(i,a=0,b=8))))

Input:

An array of 9 strings (one per box, from top-left to bottom-right).

Output:

An array of 9 arrays, where each item consists of either the original number at this position or an array of characters representing the possible digits.

Formatted and commented

g => g.map((B, i) =>              // for each box B at position i in the grid:
  [...B].map((s, x) =>            // for each cell s at position x in this box:
    +s ||                         // if there already is a number at this position, use it
    [..."123456789"].filter(n =>  // else, for each digit n in [1 .. 9]:
      (t = i =>                   // t() = helper function that looks for the digit n inside
        (k = g[i].search(n) % m)  // a given box i and returns a truthy value if its
        < a | k > b               // position modulo m is not in the range [a .. b]
      )(                          //
        j = i % 3,                // test the top box in the current column, using:
        m = 3,                    // modulo = 3 and
        a = b = x % 3             // range = [x % 3 .. x % 3]
      ) &                         //
      t(j + 3) &                  // test the middle box in the current column
      t(j + 6) &                  // test the bottom box in the current column
      t(                          //
        j = i - j,                // test the left box in the current row, using:
        m = 9,                    // modulo = 9 and
        a = x - a, b = a + 2      // range = [floor(x / 3) .. floor(x / 3) + 2]
      ) &                         //
      t(j + 1) &                  // test the middle box in the current row
      t(j + 2) &                  // test the right box in the current row
      t(i, a = 0, b = 8)          // finally test the current box, using:
    )                             // modulo = 9 (unchanged) and
  )                               // range = [0 .. 8] (thus testing the entire box)
)                                 //

Demo

let f =

g=>g.map((B,i)=>[...B].map((s,x)=>+s||[..."123456789"].filter(n=>(t=i=>(k=g[i].search(n)%m)<a|k>b)(j=i%3,m=3,a=b=x%3)&t(j+3)&t(j+6)&t(j=i-j,m=9,a=x-a,b=a+2)&t(j+1)&t(j+2)&t(i,a=0,b=8))))

console.log(f([
  "000340002",
  "740000003",
  "800170000",
  "904700103",
  "050000070",
  "000640000",
  "007630000",
  "005000910",
  "000520700"
]));


问:
Let's draw some Atari ST bombs!

Introduction

The Atari ST was a rather popular personal computer from the mid 80's to early 90's era, powered by a Motorola 68000 microprocessor. On this machine, the default behavior of the operating system for uncaught CPU exceptions was to display a row of bombs on the screen, as shown in the following picture:

Source: https://commons.wikimedia.org/wiki/File:Row_of_bombs.png

NB: Depending on the OS version, the bomb graphics may vary slightly. But let's take this one as reference.

The number of bombs depends on the exception vector, the most common ones being:

($008) Bus Error : 2 bombs

($00c) Address Error : 3 bombs

($010) Illegal Instruction : 4 bombs

Goal

Your goal is to write a program or function that prints or outputs an ASCII art of such Atari ST bombs.

Input

An integer representing the number of bombs to display. Your code must support the most common values: 2, 3 and 4. Supporting less and/or more bombs is fine, but it is neither required nor subject to a bonus.

Output

The original bomb consists of a 16x16 pixel tile, represented here in both ASCII and binary:

```<code>....##..........    0000110000000000
.#.#..#.........    0101001000000000
.......#........    0000000100000000
#..#....#.......    1001000010000000
..#...#####.....    0010001111100000
......#####.....    0000001111100000
....#########...    0000111111111000
...###########..    0001111111111100
...###########..    0001111111111100
..#############.    0011111111111110
..########.####.    0011111111011110
...#######.###..    0001111111011100
...######.####..    0001111110111100
....#########...    0000111111111000
.....#######....    0000011111110000
.......###......    0000000111000000
</code>```

In this challenge, each ASCII bomb must be stretched to twice its original width for a better rendering. Therefore, it will consist of 16 rows of 32 characters, using ## for 'ON' pixels and two spaces for 'OFF' pixels. All bomb tiles must be put side by side. Leading spaces are forbidden. Trailing spaces are also forbidden, except the ones that are actually part of the bomb tile (i.e. the 31st and 32nd columns) which must be present. You may include no more than one leading line-break and no more than one trailing line-break.

Example

Below is the reference output for two bombs, where mandatory line-breaks are marked as \n and tolerated extra line-breaks are marked as (\n):

```<code>(\n)
        ####                            ####                    \n
  ##  ##    ##                    ##  ##    ##                  \n
              ##                              ##                \n
##    ##        ##              ##    ##        ##              \n
    ##      ##########              ##      ##########          \n
            ##########                      ##########          \n
        ##################              ##################      \n
      ######################          ######################    \n
      ######################          ######################    \n
    ##########################      ##########################  \n
    ################  ########      ################  ########  \n
      ##############  ######          ##############  ######    \n
      ############  ########          ############  ########    \n
        ##################              ##################      \n
          ##############                  ##############        \n
              ######                          ######            (\n)
</code>```

(Of course, other line-break formats such as \r or \r\n may be used just as well.)

Rules

This is code-golf, so the shortest answer in bytes wins. Standard loopholes are forbidden.

答:
MS-DOS .COM file, 84 bytes

OK. Just for fun because I cannot beat the 50 bytes...

Tried under DOSbox as well as under MS-DOS 6.22 in a virtual machine.

Under DOSbox the program works fine however under real MS-DOS the output will not be displayed correctly because DOS requires CR-LF instead of LF at the end of the line.

(However the output is correct.)

A 88 byte variant would use CR-LF at the end of the line.

Here is the file:

```<code>0000  be 32 01 fc ad 89 c3 8a  36 82 00 80 ee 30 b9 10
0010  00 d1 c3 18 d2 80 ca 20  80 e2 23 b4 02 cd 21 cd
0020  21 e2 ee fe ce 75 e7 b2  0a cd 21 ad 85 c0 75 d5
0030  cd 20 00 0c 00 52 00 01  80 90 e0 23 e0 03 f8 0f
0040  fc 1f fc 1f fe 3f de 3f  dc 1f bc 1f f8 0f f0 07
0050  c0 01 00 00
</code>```

The assembler code (in AT&T syntax) looks like this:

```<code>start:
      # Read data from "image:"
    mov $image,%si
    cld
      # Read the first 16 bytes
    lodsw
nextLine:
      # Use bx as shift register
    mov %ax, %bx
      # Read the number of bombs
    mov 0x82,%dh
    sub $'0',%dh
nextBombInThisLine:
      # Number of characters
    mov $16, %cx
nextCharacter:
      # Rotate the data# get the next bit to CY
    rol $1, %bx
      # This results in 0x23 ('#') if CY is set, to 0x20 (' ') otherwise
    sbb %dl, %dl
    or $0x20, %dl
    and $0x23, %dl
      # Print result character twice
    mov $2, %ah
    int $0x21
    int $0x21
      # more Characters in this line?
    loop nextCharacter
      # More bombs to draw?
    dec %dh
    jnz nextBombInThisLine
      # Print a newline
#        mov $13, %dl # <- Additional 4 bytes needed for "\r\n"
#        int $0x21    #    at the end of the line!
    mov $10, %dl
    int $0x21
      # Read the next 16 bytes# 0x0000 means: EOF
    lodsw
    test %ax,%ax
    jnz nextLine
      # End of program
    int $0x20
image:
    # Here 34 bytes follow:
    # 16 16-bit-words "bitmap" for the bombs followed
    # by 0x0000 indicating the end of the bitmap
</code>```

--- Edit ---

I forgot to mention: The program must be started with the following command line:

Name of the COM file + exactly one space character + Number of bombs (1-9)

Title: Let's draw some Atari ST bombs!

Body:
MS-DOS .COM file, 84 bytes

OK. Just for fun because I cannot beat the 50 bytes...

Tried under DOSbox as well as under MS-DOS 6.22 in a virtual machine.

Under DOSbox the program works fine however under real MS-DOS the output will not be displayed correctly because DOS requires CR-LF instead of LF at the end of the line.

(However the output is correct.)

A 88 byte variant would use CR-LF at the end of the line.

Here is the file:

0000  be 32 01 fc ad 89 c3 8a  36 82 00 80 ee 30 b9 10
0010  00 d1 c3 18 d2 80 ca 20  80 e2 23 b4 02 cd 21 cd
0020  21 e2 ee fe ce 75 e7 b2  0a cd 21 ad 85 c0 75 d5
0030  cd 20 00 0c 00 52 00 01  80 90 e0 23 e0 03 f8 0f
0040  fc 1f fc 1f fe 3f de 3f  dc 1f bc 1f f8 0f f0 07
0050  c0 01 00 00

The assembler code (in AT&T syntax) looks like this:

start:
      # Read data from "image:"
    mov $image,%si
    cld
      # Read the first 16 bytes
    lodsw
nextLine:
      # Use bx as shift register
    mov %ax, %bx
      # Read the number of bombs
    mov 0x82,%dh
    sub $'0',%dh
nextBombInThisLine:
      # Number of characters
    mov $16, %cx
nextCharacter:
      # Rotate the data# get the next bit to CY
    rol $1, %bx
      # This results in 0x23 ('#') if CY is set, to 0x20 (' ') otherwise
    sbb %dl, %dl
    or $0x20, %dl
    and $0x23, %dl
      # Print result character twice
    mov $2, %ah
    int $0x21
    int $0x21
      # more Characters in this line?
    loop nextCharacter
      # More bombs to draw?
    dec %dh
    jnz nextBombInThisLine
      # Print a newline
#        mov $13, %dl # <- Additional 4 bytes needed for "\r\n"
#        int $0x21    #    at the end of the line!
    mov $10, %dl
    int $0x21
      # Read the next 16 bytes# 0x0000 means: EOF
    lodsw
    test %ax,%ax
    jnz nextLine
      # End of program
    int $0x20
image:
    # Here 34 bytes follow:
    # 16 16-bit-words "bitmap" for the bombs followed
    # by 0x0000 indicating the end of the bitmap

--- Edit ---

I forgot to mention: The program must be started with the following command line:

Name of the COM file + exactly one space character + Number of bombs (1-9)


问:
Implement a Truth-Machine
A truth-machine (credits goes to this guy for coming up with it) is a very simple program designed to demonstrate the I/O and control flow of a language. Here's what a truth-machine does:

Gets a number (either 0 or 1) from STDIN.

If that number is 0, print out 0 and terminate.

If that number is 1, print out 1 forever.

Challenge

Write a truth-machine as described above in your language of choice. The truth-machine must be a full program that follows these rules:

take input from STDIN or an acceptable alternative

If your language cannot take input from STDIN, it may take input from a hardcoded variable or suitable equivalent in the program

must output to STDOUT or an acceptable alternative

If your language is incapable of outputting the characters 0 or 1, byte or unary I/O is acceptable.

when the input is 1, it must continually print 1s and only stop if the program is killed or runs out of memory

the output must only be either a 0 followed by either one or no newline or space, or infinite 1s with each 1 followed by either one or no newline or space. No other output can be generated, except constant output of your language's interpreter that cannot be suppressed (such as a greeting, ANSI color codes or indentation). Your usage of newlines or spaces must be consistent: for example, if you choose to output 1 with a newline after it all 1s must have a newline after them.

if and only if your language cannot possibly terminate on an input of 0 it is acceptable for the code to enter an infinite loop in which nothing is outputted.

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

Catalog

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

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

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

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

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

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

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

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

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

 <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

```

答:
reticular, <s>8</s> 6 bytes

```<code>[do?!]
</code>```

Try it online!

This is a function. g calls the function with the TOS as input. do outputs without popping, ?! skips the next char if it's 1. Because of the way functions work, the actual constructed function is:

```<code>do?!;
</code>```

This is made in a child instance of the program. Thus, if the TOS is 0, then it terminates (exits function).

Previous versions:

8 bytes:

```<code>indp?!;!
</code>```

11 bytes:

```<code>in@@p;
p1 <
</code>```

This goes right by @@ if 0, and up if 1 (wrapping around to <) and prints 1 infinitely. It's in better style to do it this way, y'know, more readable. Because 2D languages are easy to read.

Title: Implement a Truth-Machine

Body:
reticular, <s>8</s> 6 bytes

[do?!]

Try it online!

This is a function. g calls the function with the TOS as input. do outputs without popping, ?! skips the next char if it's 1. Because of the way functions work, the actual constructed function is:

do?!;

This is made in a child instance of the program. Thus, if the TOS is 0, then it terminates (exits function).

Previous versions:

8 bytes:

indp?!;!

11 bytes:

in@@p;
p1 <

This goes right by @@ if 0, and up if 1 (wrapping around to <) and prints 1 infinitely. It's in better style to do it this way, y'know, more readable. Because 2D languages are easy to read.


问:
Divisibility test

Task

Given two strictly positive integers n and d as input, determine whether n is evenly divisible by d, i.e., if there exists an integer q such that n = qd.

You may write a program or a function and use any of the our standard methods of receiving input and providing output.

The output should be a truthy or a falsy value; truthy if n is divisible by d, and falsy otherwise.

Your code only has to handle integers it can represent natively, as long as it works for all signed 8-bit integers. However, your algorithm has to work for arbitrarily large integers.

You may use any programming language, but note that these loopholes are forbidden by default.

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

Test cases

```<code> n,  d    output

 1,  1    truthy
 2,  1    truthy
 6,  3    truthy
17, 17    truthy
22,  2    truthy
 1,  2    falsy
 2,  3    falsy
 2,  4    falsy
 3,  9    falsy
15, 16    falsy
</code>```

Leaderboard

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

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

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

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

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

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

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

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

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

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

Shortest Solution by Language

Language	User	Score

Leaderboard

	Author	Language	Size

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

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

```

答:
PHP, 53 Bytes

Trying to get the boutny for an exemplary answer

```<code>$r=range($d=$argv[2],$n=$argv[1],$d);echo$n==end($r);
</code>```

My answer based on Set Theory
In the set from d to n where all items are multiple from d
if n is the last member of the set it is divisible by d

Expressed differently you could say that the count of the items multiplied with d must be n

```<code>$r=range($d=$argv[2],$n=$argv[1],$d);echo$n==count($r)*$d;
</code>```

Title: Divisibility test

Body:
PHP, 53 Bytes

Trying to get the boutny for an exemplary answer

$r=range($d=$argv[2],$n=$argv[1],$d);echo$n==end($r);

My answer based on Set Theory
In the set from d to n where all items are multiple from d
if n is the last member of the set it is divisible by d

Expressed differently you could say that the count of the items multiplied with d must be n

$r=range($d=$argv[2],$n=$argv[1],$d);echo$n==count($r)*$d;


问:
Smallest Hamming distance to a palindrome containing a substring
This was inspired by a now removed CS.SE question.

Task

Given two non-empty input strings A and B, output the smallest distance from A to a palindrome that contains B as a substring. Distance is defined by the number of character replacements (Hamming distance).

Restrictions

Sensible input: a palindrome exists. This means |A| ≥ |B|.

A and B contain only lower ASCII characters, lowercase and uppercase are distinct (as are all other characters).

If your language cannot deal with ASCII characters, you may use integers (or some other reasonable data type) as well, and you may choose to limit the range to 128 elements.

You may take input from stdin, function arguments, command line arguments, etc.

You may give the result on stdout, return value, etc.

You do not need to give a working palindrome, the smallest distance to one is sufficient.

Examples

```<code>A                   B            Output
thilloaoyreot       hello        4 (thelloaolleht)
benjonson           stack        9 (stackcats)
neversaynever!      odd          9 (neveroddoreven)
ppcggcpp            gg           0 (ppcggcpp)
stars               tat          1 (stats)
</code>```

Scoring

This is code golf, shortest code in bytes wins.

答:
JavaScript (Firefox 30+), <s>152</s> 146 bytes

```<code>(A,B)=>Math.min(...[...Array(A[l='length']-B[l]+1)].map((_,i)=>[for(c of q=A.slice(j=t=0,i)+B+A.slice(i+B[l]))t+=(c!=A[j])+(c!=q[q[l]-++j])/2]|t))
</code>```

Brute force approach: generate each possible overlap of A and B, make each into a palindrome, calculate Hamming distances from A, and take the smallest of the resulting distances.

Probably could be golfed a bit more...

Test snippet

f=(A,B)=>Math.min(...[...Array(A[l='length']-B[l]+1)].map((_,i)=>[for(c of q=A.slice(j=t=0,i)+B+A.slice(i+B[l]))t+=(c!=A[j])+(c!=q[q[l]-++j])/2]|t))
g=(A,B)=>console.log("A:",A," B:",B," f(A,B):",f(A,B))

g("thilloaoyreot", "hello")
g("benjonson", "stack")
g("neversaynever!", "odd")
g("ppcggcpp", "gg")```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input id=A value="amanaplanacanalrussia">
<input id=B value="panama">
<button onclick="g(A.value,B.value)">Run</button></code>```

Body:
JavaScript (Firefox 30+), <s>152</s> 146 bytes

(A,B)=>Math.min(...[...Array(A[l='length']-B[l]+1)].map((_,i)=>[for(c of q=A.slice(j=t=0,i)+B+A.slice(i+B[l]))t+=(c!=A[j])+(c!=q[q[l]-++j])/2]|t))

Brute force approach: generate each possible overlap of A and B, make each into a palindrome, calculate Hamming distances from A, and take the smallest of the resulting distances.

Probably could be golfed a bit more...

Test snippet

f=(A,B)=>Math.min(...[...Array(A[l='length']-B[l]+1)].map((_,i)=>[for(c of q=A.slice(j=t=0,i)+B+A.slice(i+B[l]))t+=(c!=A[j])+(c!=q[q[l]-++j])/2]|t))
g=(A,B)=>console.log("A:",A," B:",B," f(A,B):",f(A,B))

g("thilloaoyreot", "hello")
g("benjonson", "stack")
g("neversaynever!", "odd")
g("ppcggcpp", "gg")

<input id=A value="amanaplanacanalrussia">
<input id=B value="panama">
<button onclick="g(A.value,B.value)">Run</button>


Title: Let's draw some Atari ST bombs!

Body:
Introduction

The Atari ST was a rather popular personal computer from the mid 80's to early 90's era, powered by a Motorola 68000 microprocessor. On this machine, the default behavior of the operating system for uncaught CPU exceptions was to display a row of bombs on the screen, as shown in the following picture:

Source: https://commons.wikimedia.org/wiki/File:Row_of_bombs.png

NB: Depending on the OS version, the bomb graphics may vary slightly. But let's take this one as reference.

The number of bombs depends on the exception vector, the most common ones being:

($008) Bus Error : 2 bombs

($00c) Address Error : 3 bombs

($010) Illegal Instruction : 4 bombs

Goal

Your goal is to write a program or function that prints or outputs an ASCII art of such Atari ST bombs.

Input

An integer representing the number of bombs to display. Your code must support the most common values: 2, 3 and 4. Supporting less and/or more bombs is fine, but it is neither required nor subject to a bonus.

Output

The original bomb consists of a 16x16 pixel tile, represented here in both ASCII and binary:

```<code>....##..........    0000110000000000
.#.#..#.........    0101001000000000
.......#........    0000000100000000
#..#....#.......    1001000010000000
..#...#####.....    0010001111100000
......#####.....    0000001111100000
....#########...    0000111111111000
...###########..    0001111111111100
...###########..    0001111111111100
..#############.    0011111111111110
..########.####.    0011111111011110
...#######.###..    0001111111011100
...######.####..    0001111110111100
....#########...    0000111111111000
.....#######....    0000011111110000
.......###......    0000000111000000
</code>```

In this challenge, each ASCII bomb must be stretched to twice its original width for a better rendering. Therefore, it will consist of 16 rows of 32 characters, using ## for 'ON' pixels and two spaces for 'OFF' pixels. All bomb tiles must be put side by side. Leading spaces are forbidden. Trailing spaces are also forbidden, except the ones that are actually part of the bomb tile (i.e. the 31st and 32nd columns) which must be present. You may include no more than one leading line-break and no more than one trailing line-break.

Example

Below is the reference output for two bombs, where mandatory line-breaks are marked as \n and tolerated extra line-breaks are marked as (\n):

```<code>(\n)
        ####                            ####                    \n
  ##  ##    ##                    ##  ##    ##                  \n
              ##                              ##                \n
##    ##        ##              ##    ##        ##              \n
    ##      ##########              ##      ##########          \n
            ##########                      ##########          \n
        ##################              ##################      \n
      ######################          ######################    \n
      ######################          ######################    \n
    ##########################      ##########################  \n
    ################  ########      ################  ########  \n
      ##############  ######          ##############  ######    \n
      ############  ########          ############  ########    \n
        ##################              ##################      \n
          ##############                  ##############        \n
              ######                          ######            (\n)
</code>```

(Of course, other line-break formats such as \r or \r\n may be used just as well.)

Rules

This is code-golf, so the shortest answer in bytes wins. Standard loopholes are forbidden.

Body:
Python 2, <s>206</s> <s>205</s> <s>203</s> <s>199</s> <s>191</s> <s>188</s> <s>186</s> <s>184</s> 160 bytes

z=input()
for y in 3072,20992,256,36992,9184,992,4088,8188,8188,16382,16350,8156,8124,4088,2032,448:print"".join(" #"[e>0]*2for e in map(int,bin(y+8**6)[5:]))*z

Looked at Hex for the number list but it didn't seem to save enough to make it worth the effort. Was hoping to be able to golf the code down but seem to have got as far as I can with this approach. Any additional hints gratefully received.

EDIT

-1 by changing e==1 to e>0. I always forget that one.

-2 by ignoring the length of the binary string, prepending 7 0's and taking only the last 16 elements. Works as there are never more than 7 leading 0's.

-4 because now that I have lost the second reference to the variable b I can use bin(y)[2:] directly in the map function taking it below the magic 200 :-)

-8 by using slice assignment on the second list. Learned something new this evening.

-3 with thanks to @Jonathan

-2 by using c=d=([0]*7+map(int,bin(y)[2:]))[-16:] instead of having c=d;

-2 again thanks to @Jonathan

-24 with thanks to @Linus

Output

python bombs.py
2
        ####                            ####
  ##  ##    ##                    ##  ##    ##
              ##                              ##
##    ##        ##              ##    ##        ##
    ##      ##########              ##      ##########
            ##########                      ##########
        ##################              ##################
      ######################          ######################
      ######################          ######################
    ##########################      ##########################
    ################  ########      ################  ########
      ##############  ######          ##############  ######
      ############  ########          ############  ########
        ##################              ##################
          ##############                  ##############
              ######                          ######


答:
Python 2, 178 bytes

```<code>lambda s,R=range(9):[[[(s[Y][X][i]<1)*[q+1for q in R if~-(q+1in sum([[s[j/3][X][j%3*3+i%3],s[Y][j/3][j%3+i/3*3]]for j in R],[])+s[Y][X])]for i in R]for X in R[:3]]for Y in R[:3]]
</code>```

An anonymous function that takes a 3-dimensional array of ints and returns a 4-dimensional array of ints.

Body:
Python 2, 178 bytes

lambda s,R=range(9):[[[(s[Y][X][i]<1)*[q+1for q in R if~-(q+1in sum([[s[j/3][X][j%3*3+i%3],s[Y][j/3][j%3+i/3*3]]for j in R],[])+s[Y][X])]for i in R]for X in R[:3]]for Y in R[:3]]

An anonymous function that takes a 3-dimensional array of ints and returns a 4-dimensional array of ints.


问:
Fabulous glamour shot

Found this picture on the web today. Being a lazy programmer, I don't want to actually open google and type a couple of characters. Way too much work! This is such an important task that it should be automated.

Challenge

Everyone knows that the first image in a google search result is always the best. Hence it should be presented to the user.

You are to write a program or function which takes a string as parameter and displays the first image it finds on google when you search for that name + the words glamour shot behind it.

Google search queries

To search for images on google, the url should contain the query parameter tbm=isch and q=query, with query being the name you want to search for.

A valid query string for my name Bas would be www.google.com/search?tbm=isch&q=Bas

Input

Your program or function takes a single parameter of input, which is the name you want to search for on google. This string will consist of the characters [a-z], [A-Z], [0-9] and   (space). This string can be space seperated, to search for a space seperated string on google, one should replace the spaces with +. For example, this is a valid query:

www.google.com/search?tbm=isch&q=Bassdrop+Cumberwubwubwub+glamour+shot

Output

The image can either be drawn to the screen, or saved to a file (in any format).

If the first search result on google is a gif file, you can either show the gif or show any frame of that gif.

Test cases

Run this snippet to see the expected results

```f('Bas') // www.google.com/search?tbm=isch&q=Bas+glamour+shot

<img src="http://i.stack.imgur.com/IViaM.jpg" style="width:40%;height:40%"/>

```f('Bassdrop Cumberwubwubwub') // www.google.com/search?tbm=isch&q=Bassdrop+Cumberwubwubwub+glamour+shot

```

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

答:
PowerShell v4+, 160 bytes

param($a)iwr (((iwr "google.com/search?tbm=isch&q=$($a-replace' ','+')+glamour+shot").links|?{$_.innerhtml-like"*$a*"})[0].innerhtml-split'"')[3] -outf "$a.jpg"
```

Takes input $a as a string. Does an Invoke-WebRequest (iwr) to the appropriate Google location, using inner-string script block to -replace spaces with + in the input string. We take the .links of that, where the .innerhtml is -like our input string. That yields the links with the proper thumbnail description. Take the first [0] one of those, take its .innerhtml and -split it on quotations. The fourth [3] element is the text inside the img src=" portion, so we do another iwr on that, specifying -outfile to be $a.jpg in the local folder. Since these are just the Google generated thumbnails, they're guaranteed to be jpg.

Title: Fabulous glamour shot

Body:
PowerShell v4+, 160 bytes

param($a)iwr (((iwr "google.com/search?tbm=isch&q=$($a-replace' ','+')+glamour+shot").links|?{$_.innerhtml-like"*$a*"})[0].innerhtml-split'"')[3] -outf "$a.jpg"

Takes input $a as a string. Does an Invoke-WebRequest (iwr) to the appropriate Google location, using inner-string script block to -replace spaces with + in the input string. We take the .links of that, where the .innerhtml is -like our input string. That yields the links with the proper thumbnail description. Take the first [0] one of those, take its .innerhtml and -split it on quotations. The fourth [3] element is the text inside the img src=" portion, so we do another iwr on that, specifying -outfile to be $a.jpg in the local folder. Since these are just the Google generated thumbnails, they're guaranteed to be jpg.


Title: How many times will a bell tower ring?

Body:
Introduction

A bell tower will ring its bells every hour, n times, with n being the the current hour on a 12 hour clock.

For example, a bell will ring 5 times at 5pm, and 10 times at 10am.

Task

Given two times in a suitable format, output the number of times the bell will ring, inclusive of the start and end times

Examples

```<code>"10am-12pm"
10+11+12= 33

[01:00, 05:00]
1+2+3+4+5 = 15

[11, 15]
11+12+1+2+3 = 29

[10:00pm, 10:00am]
10+11+12+1+2+3+4+5+6+7+8+9+10 = 88
</code>```

If the start is the same as the end then the you simply just ouput the number of chimes for that hour:

```<code>[5pm, 5pm]
5 = 5
</code>```

As you can see, you may choose an input method but the output must be an integer on its own (or an acceptable alternative) trailing/ leading newlines and spaces are allowed.

Note:

inputs may span from the afternoon of one day to the morning of the next.

the difference between the two times will never be more than 24 hours.

input is flexible so long as you clearly state what format your input is.

your input must have a clear distinction between AM and PM.

Body:
C, 56 Bytes

f(a,b,c=0){while(b-->a){c+=b>12?b-12:b;}printf("%d",c);}


答:
PHP, 118 Bytes, Safe

I hope that I'm understand the rules right

```<code>function f($n){for($a=[],$i=0,$n++;$n!=@@@@@@($a);$i++)if(@@@@@@@)if(@@@@@@@@(@@@@@@@@@@@@@@))$a[]=$i;return end($a);}

echo f(6); # 16
echo f(13);# 32
echo f(0); #2
echo f(1); #4
echo f(54); #128
</code>```

Original code

```<code>function f($n){
  for($a=[],$i=0,$n++;$n!=sizeof($a);$i++){
      if($t=$i%7)if(in_array($t,array(2,4,6)))$a[]=$i;
  }
  return end($a);
}
</code>```

generates this sequence

Title: Find the program that prints this integer sequence (Cops' thread)

Body:
This is the cops' thread. The robbers' thread goes here.

The last cops-and-robbers thread was already 4 months ago.

The cop's task

The cop's task is to write a program/function that takes a positive (or non-negative) integer and outputs/returns another integer.

The cop must state it if the program is intolerant towards zero.

The cop will provide at least 2 sample inputs/outputs.

For example, if I have decided to write the Fibonacci sequence, I would write this in my answer:

```
a(0) returns 0
a(3) returns 2
```

The number of examples is up to the cop's discretion.

However, the sequence must actually exist in the On-Line Encyclopedia of Integer Sequences®, so no pseudo-random number generator for you. :(

The cop can hide as many characters as is so wished.

For example, if my program is:

```<code>function a(n)
    if n>2 then
        return n
    else
        return a(n-1) + a(n-2)
    end
end
</code>```

Then I would hide these characters as I want:

```<code>function a(n)
    if ### then
        ########
    else
        ######################
    end
end
</code>```

The robber's task

is obviously to find the original source code.

However, any proposed source code that produces the same set of output also counts as valid, as long as it is also found in OEIS.

Tips for the cops

<s>The search function in the OEIS only works for consecutive terms, so if you want to hide your sequence, then just leave a hole anywhere.</s>

Apparently there is no way to hide the sequence. Put this in mind when you choose the sequence.

Your score is the number of bytes in your code.

The winner will be the submission with the lowest score that hasn't been cracked in 7 days.

Only submissions that are posted in 2016 April are eligible for the win. Submissions that are posted later than this are welcome, but cannot win.

In order to claim the win you need to reveal the full code and the OEIS sequence (after 7 days).

Your post should be formatted like this (NN is the number of characters):

Lua, 98 bytes

Output:

```<code>a(0) returns 0
a(3) returns 2
</code>```

Code (# marks unrevealed characters):

```<code>function a(n)
    if ### then
        ########
    else
        ######################
    end
end
</code>```

If the code is cracked, insert [Cracked](link to cracker) in the header.
If the submission is safe, insert "Safe" in the header and reveal the full code in your answer. Only answers that have revealed the full code will be eligible for the win.

Body:
PHP, 118 Bytes, Safe

I hope that I'm understand the rules right

function f($n){for($a=[],$i=0,$n++;$n!=@@@@@@($a);$i++)if(@@@@@@@)if(@@@@@@@@(@@@@@@@@@@@@@@))$a[]=$i;return end($a);}

echo f(6); # 16
echo f(13);# 32
echo f(0); #2
echo f(1); #4
echo f(54); #128

Original code

function f($n){
  for($a=[],$i=0,$n++;$n!=sizeof($a);$i++){
      if($t=$i%7)if(in_array($t,array(2,4,6)))$a[]=$i;
  }
  return end($a);
}

generates this sequence


问:
How much will this cost?
Given N items (0 < N <= 50) with prices (which are always integers) P0 ... PN-1 and given amounts of each item A0 ... AN-1, determine how much the total cost will be.

Examples

N: 2

P0: 2

P1: 3

A0: 1

A1: 4

Result: 14

N: 5

P0: 2

P1: 7

P2: 5

P3: 1

P4: 9

A0: 1

A1: 2

A2: 3

A3: 2

A4: 3

Result: 60

Remember, this is code-golf, so the code with the smallest number of bytes wins.

Leaderboards

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

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

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

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

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

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

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

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

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

var QUESTION_ID=95128,OVERRIDE_USER=12537;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

```

答:
TI-BASIC, 3 tokens

```<code>sum(L₁L₂
</code>```

Input in L₁ and L₂, output in Ans.

Usage:

```<code>{1,2,3→L1
{4,5,6→L2
prgmCOST
</code>```

Output: 32

Title: How much will this cost?

Body:
TI-BASIC, 3 tokens

sum(L₁L₂

Input in L₁ and L₂, output in Ans.

Usage:

{1,2,3→L1
{4,5,6→L2
prgmCOST

Output: 32


问:
A Mouse with Dynamite
You're a mouse. Your mouse friends have all been captured, and are unconscious and trapped in a maze that has only one entrance/exit. You happen to have a perfect map of the maze, so you can plot a solution to rush in and carry them all to safety. However, the maze is guarded with a security system that will trigger an alert if a threshold of 1000 is reached, causing you to be captured and fail your rescue mission.

From your previous investigations of the maze, each square you step (i.e., each horizontal or vertical movement -- mice can't move diagonally) adds 1 to the security system's counter. However, if you're carrying a weight (either a block of dynamite or an unconscious mouse friend), it instead adds 2 since it detects the additional pressure. The entrance/exit square doesn't have this security system, and so doesn't add to the counter.

You have an unlimited supply of dynamite that you've brought to the entrance, so you can simply blow up all the walls to free your friends. But you need to be cautious with doing so, since each explosion adds 50 to the counter from the concussive pressure. Additionally, you can only carry one thing at a time, either one mouse or one block of dynamite. Since each block of dynamite can only detonate one wall space, this means that if there are multiple walls in a row, you need to make an empty-handed trip back to the entrance to grab more.

Worked-through example

Suppose our maze looks like the following:

```<code>######
#M# E#
######
</code>```

I'll use c for the counter. We start at the Entrance, move one square left while carrying dynamite, c=2. We detonate the dynamite to explode the wall, c=52. We move two squares left, empty-handed, to get c=54, and we're now standing on the mouse's square. We pick our friend up, and move 3 squares back to the Exit, but the last square doesn't count since it doesn't have any sensors, so that's only 2 squares with something on our back. That means that when we reach the exit with the final mouse, c=58, which is less than 1000, and therefore the mission succeeds.

Challenge

Given an input maze, output whether you, the mouse hero, can successfully rescue all trapped mice within the constraints outlined above, or whether the mission is a failure.

Input

A 2D maze in any acceptable format (multiline string, array of strings, etc.).

For this challenge, I will be using # for both the interior and exterior walls, M for the mouse friends, and E for the entrance.

The entrance will never be immediately adjacent to an interior wall (there will always be at least one space in which to move freely).

You can substitute any printable ASCII characters you wish so long as it's consistent. This does allow you to use two different symbols for interior walls vs. exterior walls, so long as you maintain consistency (e.g., if you choose to use @ for interior walls instead, and leave # for exterior, every interior wall must be @ and every exterior wall #).

The maze will always be completely bounded by walls, but is not necessarily rectangular. If desired, you can assume that the maze is padded with spaces to make rectangular input (optional).

The maze may have sections that are unreachable without dynamite.

You cannot dynamite the exterior walls of the maze.

Output

A truthy/falsey value. Truthy for "Yes, the mouse can rescue every other mouse" or Falsey for "No, the alarm system will be tripped."

The Rules

Either a full program or a function are acceptable.

Standard loopholes are forbidden.

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

Examples

Truthy examples, separated by blank lines.

```<code>#####
#M E#
#####

######
#M# E#
######

########
#E  # M#
#   #  #
#   #  #
#      #
########

#############################
#    ##      #       #      #
#  M ## M    #       #      #
#    ##      #   M   #    E #
#M   ##      #       #      #
#############################

###############
#MMMMMMMMMMMMM#
#MMMMMMMMMMMMM#
#MMMMMMMMMMMMM#
#MMMMMMMMMM MM#
#MMMMMMMMMMMME#
###############
</code>```

Falsey examples, separated by blank lines

```<code>#############################
#M   ##      ##      ##     #
#  M ## M    ##      ##     #
#    ##      ##  M   ##   E #
#M   ##      ##      ##     #
#############################
#############################
                     ########
                     ########
                     #   #  #
                     # M # M#
                     ########

              #####
              # M #
              #####
              #####
              #####
              #####
###################
# # # ##   ## # # #
#M#M#M## E ##M#M#M#
# # # ##   ## # # #
###################
#######
######
#####
####
# M#
####

###############
#MMMMMMMMMMMMM#
#MMMMMMMMMMMMM#
#MMMMMMMMMMMMM#
#MMMMMMMMMMMMM#
#MMMMMMMMMMMME#
###############
</code>```

答:
Perl, <s>216</s> 215 bytes

Includes +2 for -0p

Give input on STDIN. Use % for external walls, # for internal walls, 0 for empty spaces, 8 for mice and r for the starting position. The whole boards must be padded so it forms a rectangle. You can transform and run the examples as:

```<code>cat dynamite.txt | perl -p0e 's/.+/$a^=$&/egr;s//sprintf"%-*s",length$a,$&/eg;1while/\n/,s/^ *\K#|#(?= *$)|^ *.{@{-}}\K#|\A[^\n]*\K#|#(?=[^\n]*\n\z)|#(?=.{@{-}} *$)/%/sm;y/ EM/0x2/' | dynamite.pl
</code>```

dynamite.pl:

```<code>#!/usr/bin/perl -0p
sub f{@a{@_}||=push@{$%+($&?$1?50:$&=~8?0:$&&"5"?2:1:0)},@_}f$_;for(@{$%}){f y/xr|/ytx/r;{f s/\pL\d/$&^(E&$&)x2/er}{f s/(q|s|y)#/$&^"\x01\x13"/er}my$o;{$\|=/x/>/2/;$o.="
"while s/.$/$o.=$&,""/meg}f$o}$%++>999|$\||redo}{
</code>```

Replace the \xhh escapes for the claimed score.

The program can't realistically handle complex cases. In particular it can't handle any of the failure cases. This is because there are just too many different ways of blowing up the internal walls or picking up mice so the search becomes too wide and uses too much memory even though it's at least smart enough to never process the same state multiple times. The pressure limit has to be lowered to 100 or so for somewhat bearable runtimes and memory usage.

Explanation

I use the bit pattern of a character to represent the state of a field:

```<code>contains victim: 0000 0010
has hero:        0100 0000
carry dynamite   0000 0001
carry mouse      0000 0100
home             0000 1000
walkable         0001 0000 (not really needed but results in shorter regexes)
make printable   0010 0000
wall             0010 xxxx (bit patterns not very important,
permawall        0010 xxxx  just avoid letters and digits)
</code>```

For example the hero (01000000) carrying dynamite (00000001) must be on a place he can walk (00010000) and we want all values to be printable ASCII (00100000). Taking the bitwise or of all these bitmasks gives 01110001 which is the ASCII code for q. In total this becomes::

```<code>p: hero                     r hero on victim
q: hero carrying dynamite   s hero carrying dynamite on victim
t: hero carrying mouse      v hero carrying mouse on victim

x : hero at home
y : hero at home carrying dynamite
| : hero at home carrying mouse

0: empty  without hero
8: home   without hero
2: victim without hero

%: permanent wall
#: normal wall
</code>```

The program will only consider the hero moving to the right (the rotation explained later will take care of the other directions). The bitmasks were carefully chosen such that the hero is always represented by a letter and a place he can move to by a digit (except the hero at home carrying a victim, but again this is intentional so that the hero's only move will be to drop the victim). So a hero that can move forward is matched by /\pL\d/. The matched substring has to be modified so that the hero and what he is carrying is removed from the first character and added to the second one, which can be done with a bitwise xor with the same value for both characters. The xor value consists of the hero bit (01000000), the dynamite bit (00000001) and the carry mouse bit (00000100). Together they or to 01000101 which is ASCII E. So moving the hero becomes:

```<code>s/\pL\d/$&^(E&$&)x2/e
</code>```

The hero can blow up a wall if he is standing right in front of it and is carrying dynamite (q, s or y). The hero will lose his dynamite (xor with 00000001) and the wall # will change to a passage 0 (xor with 00010011), so

```<code>s/(q|s|y)#/$&^"\x01\x13"/e
</code>```

To handle the other directions the whole board is rotated (rotated board ends up in $o):

```<code>my$o;$o.="\n"while s/.$/$o.=$&,""/meg
</code>```

Apart from moving the hero also has a number of other choices he can make:

```<code>When at home, pick up dynamite:                   x -> y
When on victim not carrying anything pick him up: r -> t
When at home carrying a victim, drop him off:     | -> x
</code>```

This is done by

```<code>y/xr|/ytx/
</code>```

The board is finished if the hero is at home carrying nothing (x) and there are no more victims to rescue (no 2). This can be conveniently tested using

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

Once the board is solved I want to remember this state and at the end print it. For that I carry the "is solved" flag in $\ and print that at the end of the program without printing $_, so

```<code>#!/usr/bin/perl -0p
sub f{@a{@_}||=push@{$%+($&?$1?50:$&=~8?0:$&&"5"?2:1:0)},@_}f$_;for(@{$%}){f y/xr|/ytx/r;{f s/\pL\d/$&^(E&$&)x2/er}{f s/(q|s|y)#/$&^"\x01\x13"/er}my$o;{$\|=/x/>/2/;$o.="
"while s/.$/$o.=$&,""/meg}f$o}$%++>999|$\||redo}{
</code>```0

The states to be processed at pressure 0 are kept in @0, at pressure 1 on @1 etc. The current pressure is kept in $%. Using $n or something like it would be shorter but the code doesn't work if the variable isn't initialized to something because autovivification will otherwise change $n to an ARRAY reference.Looping over the states at a certain pressure is done using a for and not a map because with a for you can extend the array while it is still being looped over and will pick up the new elements. This is needed because the rotations and single field choices of the hero happen in 0 time and end up in the same pressure array. So the loop for a given pressure is done by

```<code>#!/usr/bin/perl -0p
sub f{@a{@_}||=push@{$%+($&?$1?50:$&=~8?0:$&&"5"?2:1:0)},@_}f$_;for(@{$%}){f y/xr|/ytx/r;{f s/\pL\d/$&^(E&$&)x2/er}{f s/(q|s|y)#/$&^"\x01\x13"/er}my$o;{$\|=/x/>/2/;$o.="
"while s/.$/$o.=$&,""/meg}f$o}$%++>999|$\||redo}{
</code>```1

This is repeated until the pressure reaches 1000 or a solution is found:

```<code>#!/usr/bin/perl -0p
sub f{@a{@_}||=push@{$%+($&?$1?50:$&=~8?0:$&&"5"?2:1:0)},@_}f$_;for(@{$%}){f y/xr|/ytx/r;{f s/\pL\d/$&^(E&$&)x2/er}{f s/(q|s|y)#/$&^"\x01\x13"/er}my$o;{$\|=/x/>/2/;$o.="
"while s/.$/$o.=$&,""/meg}f$o}$%++>999|$\||redo}{
</code>```2

All that is left is adding newly discovered states to their respective pressure arrays. That will be done by subroutine f. We only want to add a state if it has not been seen yet. States that have been seen before are kept in %a so:

```<code>sub f{@a{@_}||=push@$n, @_}
</code>```

$n represents the new pressure for a state. I will derive that from the state that the regex variables still have as a result of the hero's action leading to this call:

```<code>if $1 is set it was from s/(q|s|y)#/$&^"\x01\x13"/e which blows a wall -> 50
else if $& is set it was from s/\pL\d/$&^(E&$&)x2/e, so the hero moves.
    if $& contains 8 the hero went home -> 0
    else if the hero has carry bits (5) -> 2
    else                                   1
else ($& was not set) it was from y/xr|/ytx/r -> 0
</code>```

This leads to the following formula for $n:

```<code>$%+($&?$1?50:$&=~8?0:$&&"5"?2:1:0)
</code>```

All the substitutions get an r modifier so they return the changed state and leave the current state in $_ alone. f is then called on this changed state, so you get code like

```<code>f y/xr|/ytx/r;
</code>```

Because the calculation of $n needs the regex variables they must default to unset in case the substitutions changes nothing (because the condition to trigger them is not fulfilled). I must also not pick up any regex variables from a previous loop. Therefore the substitutions are wrapped in {} blocks to save and restore the regex state. That's how you get statements like

```<code>{f s/\pL\d/$&^(E&$&)x2/er}
</code>```

In particular the rotation is so wrapped so it calls f without regex variables and gets a pressure contribution of 0.

The only thing still to do is to prime @0 with the initial state at the start

```<code>f$_
</code>```

This is in the main loop so it also tries to add $_ to later pressure arrays, but since the initial state will already be in %a nothing will happen.

Together all this basically finds the shortest solution using Dijkstra's algorithm. There is a potential problem though. The current code won't add a state if it is rediscovered with a lower pressure than the first discovery. I've not been able to construct a board that would trigger this, but have also been unable to prove it is impossible.

Title: A Mouse with Dynamite

Body:
Perl, <s>216</s> 215 bytes

Includes +2 for -0p

Give input on STDIN. Use % for external walls, # for internal walls, 0 for empty spaces, 8 for mice and r for the starting position. The whole boards must be padded so it forms a rectangle. You can transform and run the examples as:

cat dynamite.txt | perl -p0e 's/.+/$a^=$&/egr;s//sprintf"%-*s",length$a,$&/eg;1while/\n/,s/^ *\K#|#(?= *$)|^ *.{@{-}}\K#|\A[^\n]*\K#|#(?=[^\n]*\n\z)|#(?=.{@{-}} *$)/%/sm;y/ EM/0x2/' | dynamite.pl

dynamite.pl:

#!/usr/bin/perl -0p
sub f{@a{@_}||=push@{$%+($&?$1?50:$&=~8?0:$&&"5"?2:1:0)},@_}f$_;for(@{$%}){f y/xr|/ytx/r;{f s/\pL\d/$&^(E&$&)x2/er}{f s/(q|s|y)#/$&^"\x01\x13"/er}my$o;{$\|=/x/>/2/;$o.="
"while s/.$/$o.=$&,""/meg}f$o}$%++>999|$\||redo}{

Replace the \xhh escapes for the claimed score.

The program can't realistically handle complex cases. In particular it can't handle any of the failure cases. This is because there are just too many different ways of blowing up the internal walls or picking up mice so the search becomes too wide and uses too much memory even though it's at least smart enough to never process the same state multiple times. The pressure limit has to be lowered to 100 or so for somewhat bearable runtimes and memory usage.

Explanation

I use the bit pattern of a character to represent the state of a field:

contains victim: 0000 0010
has hero:        0100 0000
carry dynamite   0000 0001
carry mouse      0000 0100
home             0000 1000
walkable         0001 0000 (not really needed but results in shorter regexes)
make printable   0010 0000
wall             0010 xxxx (bit patterns not very important,
permawall        0010 xxxx  just avoid letters and digits)

For example the hero (01000000) carrying dynamite (00000001) must be on a place he can walk (00010000) and we want all values to be printable ASCII (00100000). Taking the bitwise or of all these bitmasks gives 01110001 which is the ASCII code for q. In total this becomes::

p: hero                     r hero on victim
q: hero carrying dynamite   s hero carrying dynamite on victim
t: hero carrying mouse      v hero carrying mouse on victim

x : hero at home
y : hero at home carrying dynamite
| : hero at home carrying mouse

0: empty  without hero
8: home   without hero
2: victim without hero

%: permanent wall
#: normal wall

The program will only consider the hero moving to the right (the rotation explained later will take care of the other directions). The bitmasks were carefully chosen such that the hero is always represented by a letter and a place he can move to by a digit (except the hero at home carrying a victim, but again this is intentional so that the hero's only move will be to drop the victim). So a hero that can move forward is matched by /\pL\d/. The matched substring has to be modified so that the hero and what he is carrying is removed from the first character and added to the second one, which can be done with a bitwise xor with the same value for both characters. The xor value consists of the hero bit (01000000), the dynamite bit (00000001) and the carry mouse bit (00000100). Together they or to 01000101 which is ASCII E. So moving the hero becomes:

s/\pL\d/$&^(E&$&)x2/e

The hero can blow up a wall if he is standing right in front of it and is carrying dynamite (q, s or y). The hero will lose his dynamite (xor with 00000001) and the wall # will change to a passage 0 (xor with 00010011), so

s/(q|s|y)#/$&^"\x01\x13"/e

To handle the other directions the whole board is rotated (rotated board ends up in $o):

my$o;$o.="\n"while s/.$/$o.=$&,""/meg

Apart from moving the hero also has a number of other choices he can make:

When at home, pick up dynamite:                   x -> y
When on victim not carrying anything pick him up: r -> t
When at home carrying a victim, drop him off:     | -> x

This is done by

y/xr|/ytx/

The board is finished if the hero is at home carrying nothing (x) and there are no more victims to rescue (no 2). This can be conveniently tested using

/x/>/2/

Once the board is solved I want to remember this state and at the end print it. For that I carry the "is solved" flag in $\ and print that at the end of the program without printing $_, so

$\|=/x/>/2/  ...   }{

The states to be processed at pressure 0 are kept in @0, at pressure 1 on @1 etc. The current pressure is kept in $%. Using $n or something like it would be shorter but the code doesn't work if the variable isn't initialized to something because autovivification will otherwise change $n to an ARRAY reference.Looping over the states at a certain pressure is done using a for and not a map because with a for you can extend the array while it is still being looped over and will pick up the new elements. This is needed because the rotations and single field choices of the hero happen in 0 time and end up in the same pressure array. So the loop for a given pressure is done by

for(@{$%}){...}

This is repeated until the pressure reaches 1000 or a solution is found:

$%++>999|$\||redo

All that is left is adding newly discovered states to their respective pressure arrays. That will be done by subroutine f. We only want to add a state if it has not been seen yet. States that have been seen before are kept in %a so:

sub f{@a{@_}||=push@$n, @_}

$n represents the new pressure for a state. I will derive that from the state that the regex variables still have as a result of the hero's action leading to this call:

if $1 is set it was from s/(q|s|y)#/$&^"\x01\x13"/e which blows a wall -> 50
else if $& is set it was from s/\pL\d/$&^(E&$&)x2/e, so the hero moves.
    if $& contains 8 the hero went home -> 0
    else if the hero has carry bits (5) -> 2
    else                                   1
else ($& was not set) it was from y/xr|/ytx/r -> 0

This leads to the following formula for $n:

$%+($&?$1?50:$&=~8?0:$&&"5"?2:1:0)

All the substitutions get an r modifier so they return the changed state and leave the current state in $_ alone. f is then called on this changed state, so you get code like

f y/xr|/ytx/r;

Because the calculation of $n needs the regex variables they must default to unset in case the substitutions changes nothing (because the condition to trigger them is not fulfilled). I must also not pick up any regex variables from a previous loop. Therefore the substitutions are wrapped in {} blocks to save and restore the regex state. That's how you get statements like

{f s/\pL\d/$&^(E&$&)x2/er}

In particular the rotation is so wrapped so it calls f without regex variables and gets a pressure contribution of 0.

The only thing still to do is to prime @0 with the initial state at the start

f$_

This is in the main loop so it also tries to add $_ to later pressure arrays, but since the initial state will already be in %a nothing will happen.

Together all this basically finds the shortest solution using Dijkstra's algorithm. There is a potential problem though. The current code won't add a state if it is rediscovered with a lower pressure than the first discovery. I've not been able to construct a board that would trigger this, but have also been unable to prove it is impossible.