Draw an ASCII contour plot Consider the following 3x3 blocks which the marching squares algorithm would identify for every cell (with 0-based labeled ID):

0:
...
...
...

1:
...
...
\..

2:
...
...
../

3:
...
---
...

4:
..\
...
...

5:
/..
...
../

6:
.|.
.|.
.|.

7:
/..
...
...

8:
/..
...
...

9:
.|.
.|.
.|.

10:
..\
...
\..

11:
..\
...
...

12:
...
---
...

13:
...
...
../

14:
...
...
\..

15:
...
...
...

The goal of this challenge is given a 2D matrix of block ID's, draw the full contour plot by tiling these smaller cells together. Note that there are some repeated cases (ex.: 0 and 15 visually are the same)

Input

Your program/function should take as input a 2D rectangular matrix of integers in the range [0+a,15+a] (where a is an arbitrary integer shift of your choice; this allows you to use zero-based indexing or 1-based indexing for the blocks). This may be from any source desired (stdin, function parameter, etc.).

Output

Your program/function should output a single string representing the full contour plot. There should be no extra leading/trailing whitespace, but a single trailing newline is allowed. There should be no separation between adjacent blocks vertically or horizontally.

Note that you do not have to do any kind of special treatment for blocks which map to a "saddle"; just draw the block with the given ID as-is.

The output may be to any sink desired (stdout, return value, etc.)

Examples

All examples below use 0-based block ID's.

case 1:

2 1
4 8

......
......
../\..
..\/..
......
......

case 2:

15 13 12 14 15
13 8 0 4 14
11 1 0 2 7
15 11 3 7 15

...............
......---......
...../...\.....
.../.......\...
...............
../.........\..
..\........./..
...............
...\......./...
.....\.../.....
......---......
...............

case 3:

12 12 12 8 4
0 0 0 0 2
0 0 0 2 7
0 2 3 7 15

........./....\
---------......
...............
...............
...............
............../
............/..
...............
.........../...
........./.....
......---......
...../.........

case 4:

0 1 2 3
4 5 6 7
8 9 10 11
12 13 14 15

............
.........---
...\..../...
..\/...|./..
.......|....
...../.|....
/...|...\..\
....|.......
....|.\.....
............
---.........
...../\.....

case 5:

0 0 0 0 6 15 15
0 0 0 0 6 15 15
0 0 0 0 6 15 15
0 0 0 2 7 15 15
0 0 2 5 14 15 15
0 2 5 8 4 12 14
0 4 8 0 0 0 6
0 0 0 0 0 0 4

.............|.......
.............|.......
.............|.......
.............|.......
.............|.......
.............|.......
.............|.......
.............|.......
.............|.......
............/........
.....................
.........../.........
........./...........
.....................
......../../\........
....../../....\......
...............---...
...../../.........\..
.....\/............|.
...................|.
...................|.
....................\
.....................
.....................

Scoring

This is code golf; shortest code in bytes wins. Standard loopholes apply.


Reimplementing square root Define a function, s, which takes a number and returns the square root.

No use of library functions, such as Java's Math.sqrt() or PHP's built in sqrt(), allowed.

Python - 11 chars

Technically not a library function :)

input()**.5

As a function it's 16 chars

f=lambda x:x**.5


Parity of a Permutation Background
The parity of a permutation, as defined by wikipedia, is as follows:

The sign or signature of a permutation σ is denoted sgn(σ) and defined as +1 if σ is even and −1 if σ is odd.
The sign of a permutation can be explicitly expressed as
sgn(σ) = (−1)^N(σ)
where N(σ) is the number of inversions in σ.
Alternatively, the sign of a permutation σ can be defined from its decomposition into the product of transpositions as
sgn(σ) = (−1)^m
where m is the number of transpositions in the decomposition.

For those of you who are not fond of Greek alphabet soup in their math, I'll try and simplify the definition a bit with an example (also stolen from wikipedia).
Example
Consider the input array {1, 2, 3, 4, 5}, and a permutation of it, let's say, {3, 4, 5, 2, 1}. In order to get from the original array to its permutation, you must swap indices 0 and 2, 1 and 3, then 2 and 4. Although this is not a unique solution, the parity is well-defined so this works for all cases.
Since it requires 3 swaps, we label this permutation with an odd parity. As you might expect, a permutation that requires an even amount of swaps is said to have an even parity.
Challenge
Your challenge is to write a program in as few bytes as possible to determine the parity of a permutation. Your program or function must:

Accept as arguments, two input arrays (or strings) representing a set before and after a permutation.
Return or print the character e for even or o for odd, given the permutation.
Should assume that all indices in the arrays or strings have unique values.

Test Cases
Assuming you declared a function named f:
f([10], [10]) == "e"
f([10, 30, 20], [30, 20, 10]) == "e"
f([10, 30, 20, 40], [30, 20, 40, 10]) == "o"

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

MATL, 17 16 bytes
1 byte removed thanks to a suggestion by Dennis
2$St!<Rz2\'oe'w)

This works in current version (15.0.0) of the language.
Try it online!
Explanation
This uses the definition of parity in terms of inversions. An inversion is a pair of elements in the second array that are in the "wrong" order compared with the first array. Since the first array need not be sorted, we first sort it and the same rearrangement needed for that sorting is applied to the second array. Then an inversion corresponds to a pair of elements that is not increasing in the second array.
Note also that the two input arrays can be swapped and the result is the same. So it's not important which array is considered to be the "original" and which the "permuted".
2$S     % implicitly take two row vectors. Sort second and apply the indices
        % of that sorting to the first
t!      % duplicate. Transpose into column vector
<       % true for elements of the column vector that exceed those of the
        % row vector. Gives a 2D array with all pairs of comparisons
R       % keep only upper triangular part of that array
z       % number of nonzero elements. This is the number of inversions
2\      % parity of that number: gives 0 or 1
'oe'w   % push string 'eo' below the top of the stack
)       % apply index to produce 'e' or 'o'. An index 1 refers to the first
        % element, whereas 0 refers to the last. Implicitly display


The infinitely admissable sequence In this challenge we'll compute an infinite minimal admissible sequence.

The sequence for this challenge starts with a(1) = 1.

We continue this sequence by finding a(n) as the smallest possible number such that a(n) > a(n-1) and for every prime p, the set {a(i) mod p : 1 ≤ i ≤ n} has at most p-1 elements.

Write a program or function that takes positive integer n and outputs a(n). Shortest code in bytes wins.

Example:

a(6) is 19, rather than, say 17 because [1,3,7,9,13,19] (the previous terms) is admissible while [1,3,7,9,13,17] is not.

[1,3,7,9,13,17] is not admissible, because for the base 3, after taking the modulo of each term with 3, we obtain [1,0,1,0,1,2] which contains every non-negative number smaller than 3, our chosen base.

For [1,3,7,9,13,19] however, it would be impossible to come up with a base such that the list after modulo contains every non-negative integer smaller than such base.

Reference:

OEIS A020498

Testcases:

a(1) = 1
a(2) = 3
a(3) = 7
a(4) = 9
a(5) = 13
a(6) = 19
a(7) = 21
a(8) = 27
a(9) = 31
a(10) = 33
a(100) = 583

Brachylog, 44 bytes

-:[1]r:[1]cit.
t<gX=:?rc.'(l:2eLg:.rz:%adlL)

Try it online!

100 takes about a minute here, so be patient if you want to try 100.

Predicate 0 (main predicate)

-:[1]r:[1]cit.
-:[1]r:[1]c     create array [[1], input-1, 1]
           i    iterate: [1] as input, iterate (input-1) times, predicate 1
            t.  last element is the output

Predicate 1 (auxiliary predicate)

t<gX=:?rc.'(l:2eLg:.rz:%adlL)
t<                              last element of input < Temp
  gX                            [Temp] = X
   X=                           Assign a value to X, which assigns
                                a value to Temp
   X :?rc.                      [Input,X] concatenated is output
         .'(                )   The following about the output cannot
                                be proven:
            l:2eL                   L is a number between 2 and length
                                    of output, inclusive
                Lg:.rz:%a           every element of output, taken modulo L,
                         dlL        after removing duplicates, has length L


Alphabet triangle strikes again Task

Your task is to print this exact text:

A
BCD
EFGHI
JKLMNOP
QRSTUVWXY
ZABCDEFGHIJ
KLMNOPQRSTUVW
XYZABCDEFGHIJKL
MNOPQRSTUVWXYZABC
DEFGHIJKLMNOPQRSTUV
WXYZABCDEFGHIJKLMNOPQ
RSTUVWXYZABCDEFGHIJKLMN
OPQRSTUVWXYZABCDEFGHIJKLM
NOPQRSTUVWXYZABCDEFGHIJKLMN
OPQRSTUVWXYZABCDEFGHIJKLMNOPQ
RSTUVWXYZABCDEFGHIJKLMNOPQRSTUV
WXYZABCDEFGHIJKLMNOPQRSTUVWXYZABC
DEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKL
MNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVW
XYZABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJ
KLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXY
ZABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOP
QRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHI
JKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZABCD
EFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZA
BCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ

Specs

You may do it in all-lowercase instead of all-uppercase.
Trailing newlines at the end of the triangle is allowed.
Trailing spaces after each line is allowed.
You must print to STDOUT instead of outputting an array of strings.

Scoring

This is code-golf. Program with lowest byte-count wins.

Vim, 29 bytes

:h<_↵↵↵y$ZZ26P0qqa↵♥βjllq25@q

Where ↵ represents the Return key, ♥ the Escape key, and β the Backspace key.


Polite Near-Sighted Drunk Bot on a Minefield As the title may suggest, this problem is semi-inspired by the Polite Near-Sighted Drunk Bot by @N.P.

Our poor bot is placed on a cartesian grid at the origin, and after each minute, it moves 1 unit in one of four directions (Up, Down, Left, Right).

After n minutes, all of the latent mines on the grid activate, killing any poor bot that might find themselves over them. The mines are located at all integer coordinates satisfying the equation |y|=|x|.

Challenge

You will be provided n, the number of minutes before the mines blast, as an input, and as an output, you must find the probability that the bot is dead.

Input: An natural number representing n.

Output: Let the probability the bot is dead be p/q, where p and q are relatively prime whole numbers (q can't be 0, but p can). Output p.

Rules

Your algorithm must not run in exponential or higher time. It ideally should run in polynomial time or less.
Your algorithm must be able to handle inputs of n<20 (can be adjusted if too hard) in a reasonable time.
This is a code-golf challenge.
Iterating over all possibilities for a given n will most definitely not be accepted as an answer.

Test Cases

1->0

2->3

4->39

6->135

8->7735

10->28287

Example Calculation for n=6

We have 4 possible moves: U, D, R, and L. The total number of paths that could be taken is 4^6, or 4096. There are 4 possible cases that land along the line y = x: x,y = ±1; x,y = ±2; x,y = ±3; or x = y = 0. We will count the number of ways to end up at (1,1), (2,2), and (3,3), multiply them by 4 to account for the other quadrants, and add this to the number of ways to end up at (0,0).

Case 1: The bot ends at (3, 3). In order for the bot to end up here, it must have had 3 right moves, and 3 up moves. In other words, the total number of ways to get here is the ways to rearrange the letters in the sequence RRRUUU, which is 6 choose 3 = 20.

Case 2: The bot ends at (2,2). In order for the bot to end up here, it could have had 2 up moves, 3 right moves, and 1 left move; or 2 right moves, 3 up moves, and 1 down move. Thus, the total number of ways to get here is sum of the ways to rearrange the letters in the sequences RRRLUU and UUUDRR, both of which are (6 choose 1) * (5 choose 2) = 60, for a total of 120 possibilities.

Case 3: The bot ends at (1,1). In order for the bot to end up here, it could have had:
1 right move, 3 up moves, and 2 down moves. In this case, the number of ways to rearrange the letters in the sequence RUUUDD is (6 choose 1)*(5 choose 2) = 60.

1 up move, 3 right moves, and 2 left moves. In this case, the number of ways to rearrange the letters in the sequence URRRLL is (6 choose 1)*(5 choose 2) = 60.

2 right moves, 1 left move, 2 up moves, and 1 down move. In this case, the number of ways to rearrange the letters in the sequence UUDRRL is (6 choose 1)* (5 choose 1)*(4 choose 2) = 180.

Thus, the total number of ways to end up at (1,1) is 300.

Case 4: The bot ends at (0,0). In order for the bot to end up here, it could have had:

3 right moves and 3 left moves. In this case, the number of ways to rearrange the letters in the sequence RRRLLL is (6 choose 3) = 20.

3 up moves and 3 down moves. In this case, the number of ways to rearrange the letters in the sequence UUUDDD is (6 choose 3) = 20.

1 right move, 1 left move, 2 up moves, and 2 down moves. In this case, the number of ways to rearrange the letters in the sequence RLUUDD is (6 choose 1)* (5 choose 1)*(4 choose 2) = 180.

1 up move, 1 down move, 2 right moves, and 2 left moves. In this case, the number of ways to rearrange the letters in the sequence RRLLUD is (6 choose 1)* (5 choose 1)*(4 choose 2) = 180.

Thus, the total number of ways to end up at (0,0) is 400.

Adding these cases together, we get that the total number of ways to end up on |y| = |x| is 4(20 + 120 + 300) + 400 = 2160. Thus, our probability is 2160/4096. When this fraction is fully reduced, it is 135/256, so our answer is 135.

Python 2, 65 bytes

def p(n):b=2**n;r=b*b-((~b)**n/b**(n/2)%-b)**2;print~n%2*r/(r&-r)

Try it online!

The probability the bot is dead can be expressed as:

  $$ f(n) = 2s-s^2\text{, where }  s=\frac{1}{2^n}\binom{n}{n/2}$$

and the binomial is understood to equal \$0\$ when \$n/2\$ isn't whole.

We can reason like this. What's the probability that the bot lands on the \$y=x\$ line? This happens if the total number of up and left moves equals the total number of down and right moves. This is the same probability that, say, you flip a coin \$n\$ times and get as many tails as heads. You must choose \$n/2\$ flips to be heads of \$n\$ flips, which can be done in \$\binom{n}{n/2}\$ ways, of \$2^n\$ possible sequences overall, giving probability

$$s=\frac{1}{2^n}\binom{n}{n/2}$$

The probability of landing the \$y=-x\$ line is also \$s\$. So, the probability of landing on either line is the sum of these or \$2s\$, except we're double-counting the probability of landing of \$x=y=0\$ in both lines, and must subtract it to compensate.

It turns out the probability of landing on \$x=y=0\$ is just \$s^2\$, the product of the probability of landing on each line. We can argue the events are independent as follows: if we pick a random sequence of equal numbers of "Up or Left" and "Down or Right" to land on \$x=y\$ and likewise with "Up or Right" and "Down or Left" for \$x=-y\$, we can uniquely combine them into a sequence of Up, Down, Left, Right by taking the intersection of the pairs of directions at each position.

So, the probability of landing on \$x=y\$ or \$x=-y\$ is \$2s-s^2\$.

The code computes the binomial \$\binom{n}{n/2}\$ using this expression as (b+1)**n/b**(n/2)%b with base b=2**n. To extract the numerator from the probability fraction, we note that the denominator is a power of 2, so we use the expression r/(r&-r) to divide out the maximal power of 2 is r, expressed as the classic bit trick r&-r.

The solution is golfed by writing \$2s-s^2\$ as \$1-(1-s)^2\$ so that \$s\$ is only referenced once, and working without the \$1/2^n\$ fractions to stay within the integers. The computation is polynomial-time in \$n\$ even with the funky way of computing binomials.

After writing the proof of the probability the bot dies, I found a possibly cleaner way to prove it and present it.

Let's keep track of the values of \$a=x+y\$ and \$b=x-y\$ after each move of the bot. Each of the four directions up, down, left, and right either increments or decrements each of \$a\$ and \$b\$, with the four directions corresponding to the four combinations.

So, a random move is equivalent to randomly adding \$\pm 1\$ to \$a\$ and independently \$\pm 1\$ to \$b\$. This is equivalent to doing separate random walks on \$a\$ and \$b\$.

Now, the robot ends on the line \$x=y\$ or \$x=-y\$ exactly when \$a=0\$ or \$b=0\$. So, the probability of ending with \$a=0\$ is \$s=\frac{1}{2^n}\binom{n}{n/2}\$ and likewise for \$b=0\$. Since the walks are independent, the probability that \$a\neq 0\$ and \$b\neq 0\$ is \$(1-s)^2\$, so the probability that at least one is zero is the complement \$1-(1-s)^2\$.


Shortest code to write longest code Your challenge is to create a shortest code in your language of choice which writes on a .txt file the longest code to multiply two numbers by taking two numbers as input and output the answer.
NO INPUT NEEDED TO YOUR CODE WHICH IS DOING THE WRITING JOB!
The generator code and generated code can be in any languages
Do NOT use unlimited series or progression to make text file big.
Do NOT use unnecessary statements to increase the score.
SCORING
( size of text file generated in bytes )  (without any unnecessary white spaces, tabs or newlines)
-----------------------------------------
     ( size of your code in bytes )

Winner
Winner will be chosen after 1 week from now with the highest score.
EDIT : range of input in code multiplying two numbers should be in between -32768 to 32767

perl/perl, unlimited score under original rule with unlimited range

Here's some code which doesn't win:

$l=-2**5-1;
$h=2**5;
sub p{print@_}
p"sub add {(\$i,\$j)=\@_;\n";
for($i=$l;$i<=$h;++$i){
  for ($j=$l;$j<=$h;++$j){
    p" return ".($i*$j)." if (\$i == $i) && (\$j == $j);\n";
  }
}
p"}print add(<>,<>)\n";

The output has this form:

sub add {($i,$j)=@_;
 return 1089 if ($i == -33) && ($j == -33);
 return 1056 if ($i == -33) && ($j == -32);
 return 1023 if ($i == -33) && ($j == -31);
 return 990 if ($i == -33) && ($j == -30);
...
 return 928 if ($i == 32) && ($j == 29);
 return 960 if ($i == 32) && ($j == 30);
 return 992 if ($i == 32) && ($j == 31);
 return 1024 if ($i == 32) && ($j == 32);
}print add(<>,<>)

the output file is 181030 bytes long, but after stripping spaces and newlines, it is only 133109 bytes long. so, the score is 133109/248 = 536.7289...

Here's some other code that doesn't win - it is the same program except the first 2 lines:

$l=-2**6-1;
$h=2**6;

the output file is 718138 bytes long, but after stripping spaces and newlines, it is only 532233 bytes long. so, the score is 532233/248 = ~2146. better! using 7 yields a score of ~8750, 8 yields ~35347, 9 yields ~149129, 10 yields 151100000 non-space / 250 = 604,400 ....

of course we can do this as long as we want. the size of the source program, n, will increase as O(log(n)). the size of the output program is O(2*n). The limit of 2*n/log(n) as n goes to infinity is clearly infinity, so if I just substitute in my favorite large number, a googolplex, I win (until someone suggests googolplex+1).


Abstract Rewriting Challenge (Cops) This is a somewhat proof-golf-like cops-and-robbers challenge. This is the cops' thread; the robbers' thread is here.

Cops

Your task is to define an abstract rewriting system in which the reachability of one word from another is difficult to determine. You will prepare the following things:

A set of symbols, called the alphabet. (You may use any Unicode characters for these, but please don't use whitespace, or symbols that are hard to distinguish from each other.)
A source string composed of symbols from your alphabet.
A target string composed of symbols from your alphabet.
A set of rewrite rules using characters from your alphabet. (See below for the definition of a rewrite rule.)
A proof showing whether your source string can be converted into your target string by successive application of your rewrite rules. This proof might consist of an actual sequence of rewrite steps, or a mathematical proof that such a sequence must exist, or a mathematical proof that such a sequence does not exist.

You will post the first four of these, keeping the proof secret; the robbers will try to crack your answer by providing their own proof that your target string can or can not be reached from your source string. If your submission is not cracked within two weeks, you may mark it as safe and edit in your proof.

Submissions will be scored according to the number of characters in their rewrite rules and their source and target strings, as detailed below. The winner will be the uncracked submission with the lowest score.

What is a rewrite rule?

A rewrite rule is simply a pair of strings in your alphabet. (Either of these strings may be empty.) An application of a rewrite rule consists of finding a substring that is equal to the first string in the pair, and replacing it with the second.

An example should make this clear:

Suppose alphabet is A, B and C; the source string is "A"; the target string is "C" and the rewrite rules are

A:B
B:BB
B:A
AA:C

then the target string is reachable in the following way:

A
B   (using rule 1)
BB  (using rule 2)
AB  (using rule 3)
AA  (using rule 3)
C   (using rule 4)

Scoring

Your score will be

the length of your source string,
plus the length of your target string,
plus the length of all the strings included in your rewrite rules,
plus one extra point for each rewrite rule.

If you write your rewrite rules with a colon separator as above, this is just the total length of all the rewrite rules (including the separator), plus the lengths of the source and target strings. A lower score is better. The number of distinct characters in your alphabet will be used to break ties, with fewer being better.

Bounty

I'd like to see answers that really go for low scores. I will award 200 rep to the first answer that scores less than 100 points in this challenge and doesn't get cracked.

326 points - Cracked by jimmy23013
The level is Picokosmos #13 by Aymeric du Peloux (with a trivial modification). I tried to find a tasteful level that could be implemented with "boxes" and "walls" being the same character. For this level it was possible by making the central choke point two columns wide rather than one.
The rules/initial/target strings could be golfed a bit more, but this is just for fun.
Initial string:
___##___####_____##_#_#_##_#_!####______##_#####__####_#_######__###__

Target string:
___##___####_____##_#_#_##_#_#####____!__#_#####__####_#_######__###__

Rules:
_wW:!
_<:<_
Vv_:!
V_:_V
R:>>>>>>>>>>>>>
V#:#V
#w<:w#
>v_:_v
_wX:#
_!:!_
!:wLW_
L:<<<<<<<<<<<<<
#W:W#
!#_:_!#
_w<:w_
#<:<#
!:_VRv
>v#:#v
Uv_:#
_W:W_
_X:X_
>#:#>
#X:X#
U_:_U
Vv#:!URv
#wW:wLX!
>_:_>
!_:_!
_#!:#!_
U#:#U


Drop of Chaos (Constructing a Minimally Aperiodic Sequence) The idea here is to produce an almost repeating pattern. That is, the sequence being constructed changes at the last moment to avoid a repetition of some subsequence. Subsequences of the type AA and ABA are to be avoided (where B is no longer than A).
Examples:
I'll go ahead and start by listing all of the small examples to make my description clearer. Let's start with 0.
Valid:   0

Invalid: 00    (AA pattern)
Valid:   01

Invalid: 010   (ABA pattern)
Invalid: 011   (AA pattern)
Valid:   012

Valid:   0120
Invalid: 0121  (ABA pattern)
Invalid: 0122  (AA pattern)

Invalid: 01200 (AA pattern)
Invalid: 01201 (ABA pattern; 01-2-01)
Invalid: 01202 (ABA pattern)
Valid:   01203

Now, I strongly believe that a 4 is never needed, though I do not have a proof, because I have easily found sequences of hundreds of characters long that use only 0123. (It's probably closely related to how only three characters are needed to have infinite strings that do not have any AA patterns. There's a Wikipedia page on this.)
Input/Output
Input is a single, positive, non-zero integer n. You may assume that n <= 1000.
Output is an n-character sequence with no subsequences that match either prohibited pattern (AA or ABA).
Sample inputs and outputs

>>> 1
0

>>> 2
01

>>> 3
012

>>> 4
0120

>>> 5
01203

>>> 50
01203102130123103201302103120132102301203102132012

Rules

Only the characters 0123 are allowed.
B is no longer than A. This is to avoid the situation where 012345 has to be followed by 6 because 0123451 has this: 1-2345-1. In other words, the sequence would be trivial and uninteresting.
n may be inputted through any method desired, except hard-coding.
Output may be either a list or a string, depending on which is easier.
No brute force; the run time should be on the order of minutes, at most an hour on a really slow machine, for n=1000. (This is intended to disqualify solutions that just loop through all n-length permutations of {0,1,2,3}, so that trick and similar tricks are disallowed.)
Standard loopholes are disallowed, as usual.
Scoring is in bytes. This is code-golf, so the shortest entry wins (probably - see bonus).
Bonus: pick the lowest allowed digit at each step. If 1 and 3 are possible choices for the next digit in the sequence, pick 1. Subtract 5 bytes from your score. However, take note of the note below.

Note!
Dead-ends are possible. Your program or function must avoid these. Here's an example:

Stump: 0120310213012310320130210312013210230120310213201230210312013023103201230213203102301203210231201302103123013203102130120321023013203123021032012310213012031023013203123021320123102130120
Stump: 0120310213012310320130210312013210230120310213201230210312013023103201230213203102301203210231201302103123013203102130120321023013203123021032012310213012031023013203123021320123102130123
Stump: 012031021301231032013021031201321023012031021320123021031201302310320123021320310230120321023120130210312301320310213012032102301320312302103201231021301203102301320312302132012310320
Stump: 012031021301231032013021031201321023012031021320123021031201302310320123021320310230120321023120130210312301320310213012032102301320312302103201231021301203102301320312302132012310321301203102130

Each of these sequences cannot be extended any further (without using a 4). But also note that there is a crucial difference between the first two and the second two. I'll replace the shared initial subsequence with an X to make this clearer.

Stump: X2130120
Stump: X2130123
Stump: X320
Stump: X321301203102130

The last two digits of X are 10, so the only possible choices for the next digit are 2 and 3. Choosing 2 leads to a situation where the sequence must terminate. The greedy algorithm will not work here. (Not without backtracking, anyway.)

Retina, 86 bytes - 5 = 81

$
_
(r`^(?<-2>.)+_((.)+)\b$
$1!
\b$
0
3#
#
0#
1
1#
2
2#
3
)r`\1(?<-2>.)*((.)+)$
$0#
!
<empty>

Where <empty> represents an empty trailing line. You can run the above code from a single file with the -s flag.

The input should be given in unary, e.g. 111111. I haven't tested it for output on the order of thousands yet - two of the regexes might get a bit slow after a while - but it can easily handle a couple of hundred in a few seconds.

Explanation

This is a simple backtracking solution.

Append a 0.
While the current sequence is invalid, remove all trailing 3s and increment the last non-3.
Repeat until we have a valid sequence of the desired length.

This backtracking is implemented by a loop of regex substitutions which aborts once the string remains unchanged through one iteration.

$
_

This appends a _ to the input, which is used to separate the unary input from the sequence we're building.

(r`^(?<-2>.)+_((.)+)\b$
$1!

This is the first substitution in the loop (indicated by the leading ().  The regex matches if a) there is a word character (i.e. a digit) at the end the string (which means the string is valid - we'll see below that invalid sequences are marked with a trailing #) and b) there are at least as many characters in the sequence as in the input (this is checked using balancing groups). If that's the case, we remove the input and append a !. This ! serves to make all regexes in the loop fail, such that it terminates.

\b$
0

If there is a word character at the end (i.e. the sequence is valid, and the loop wasn't terminated by the previous step), append a 0.

3#
#

If (instead) the sequence had been marked invalid and ended in 3, we remove that 3 (but leave the sequence as invalid, because there's no possible continuation for the current prefix... so the next character needs to be backtracked as well).

0#
1
1#
2
2#
3

If the sequence is marked invalid and any digit other than 3 is at the end, we increment the digit and remove the marker.

)r`\1(?<-2>.)*((.)+)$
$0#

The last substitution in the loop (as indicated by the )). It checks whether the string ends in ABA (where B is not longer than A but potentially empty). The relative lengths of A and B are again checked using balancing groups, and the repetition of A is checked with a simple backreference.

If this regex matches, we mark the sequence invalid by appending #.

!
<empty>

Once the loop terminates, all we need to do is remove the ! and are then left with the desired output.


Smallest sum (and largest difference) of two 3-digit integers Given six unique non-negative integers, print the two 3-digit integers comprised of those numbers that sum to the smallest amount.

Additionally,

If there is more than one set of numbers that meets the smallest-sum requirement, print the two that have the greatest difference. For example, 269 + 157 = 267 + 159 = 426; however, 269 - 157 > 267 - 159, so the first set should be printed.
Print the numbers on the same line largest -> smallest, separated by a single space.
Zero (0) cannot be used as a leading number.
Inputs will always be digits.

Testcases

input        | output
2 6 5 1 9 7  | 269 157
1 9 5 0 8 3  | 359 108
1 2 3 4 5 6  | 246 135

Scoring

As this is code golf, shortest entry wins.

Jelly, 12 bytes

Ṣs3¬Þ€Fs2ZḌṚ

Try it online! or verify all test cases.

Background

Consider six digits a < b < c < d < e < f.

If a ≠ 0, a number pair of three-digit integers with minimal sum must clearly use a and b for the leftmost digits, c and d for the middle digits, and e and f for the rightmost digits.

That gives eight possible arrangements with identical sums (100(a + b) + 10(c + d) + (e + f)).

Since the difference should be as large as possible, all digits of the first integer should be larger than the corresponding digits of the second integer, leaving bdf10, ace10 as the optimal arrangement (difference 100(b - a) + 10(d - c)+ (f - e)).

Finally, if a = 0, a should still occur as early as possible (as middle digit), and a similar process reveals that the pair cdf10, bae10 is the correct solution.

How it works

Ṣs3¬Þ€Fs2ZḌṚ  Main link. Argument: <a, b, c, d, e, f> (in any order)

Ṣ             Sort; yield [a, b, c, d, e, f].
 s3           Split into triplets; yield [[a, b, c], [d, e, f]].
   ¬Þ€        Sort each triplet by logical NOT.
              If a ≠ 0, all digits have logical NOT 0, so this leaves the triplets
              unaltered. If a = 0, its logical NOT is 1, so the first triplet is
              sorted as [b, c, a], leaving [[b, c, a], [d, e, f]].
      F       Flatten; yield [a, b, c, d, e, f] or [b, c, a, d, e, f].
       s2     Split into pairs; yield [[a, b], [c, d], [e, f]] or
              [[b, c], [a, d], [e, f]].
         Z    Zip; yield [[a, c, e], [b, d, f]] or [[b, a, e], [c, d, f]].
          Ḍ   Undecimal; convert each triplet from base 10 to integer.
           Ṛ  Reverse the order of the generated integers.


Calculate the Lunar Phase Introduction

tl;dr

In this challenge you have to calculate the moon's phase for a given date.

This challenge is inspired by the game psycho social audiovisual experiment "Superbrothers: Sword & Sworcery EP". In S:S&S EP the moon's phases are important to the outcome of the adventure as some events occur only at a specific point in time.

The question is: Which lunar phase is present on a specific date. Each main phase – from new moon to first quarter to full moon to third quarter – is about 7.38 days long. The whole lunar cycle is roughly 29.52 days. Based on these values various methods of calculation exist.1

Input

A date based on the Gregorian calendar, between 1 January 1970 and 31 December 2116.
You can choose one of the following formats: yyyy-mm-dd, dd.mm.yyyy, dd/mm/yyyy, yyyymmdd or ddmmyyyy.

Output

Output the index [0-7] of the lunar phase based on this zero-indexed array:

['New moon', 'Waxing crescent', 'First quarter', 'Waxing gibbous', 'Full moon', 'Waning gibbous', 'Third quarter', 'Waning crescent`]

Requirements

You can write a program or a function. If you go with an anonymous function, please include an example of how to invoke it.
Input is accepted from STDIN, command line arguments, as function parameters or from the closest equivalent.
This is code-golf so shortest answer in bytes wins.
Built-ins or external libraries that calculate the moon phase are not allowed.2
Standard loopholes are disallowed.

Tests

The values are: date | index of the phase | illumination | name

A full lunar cycle:

08.02.2016 | 0 |   0% | New moon
07.02.2016 | 7 |   2% | Waning crescent
07.02.2016 | 7 |   2% | Waning crescent
06.02.2016 | 7 |   6% | Waning crescent
05.02.2016 | 7 |  12% | Waning crescent
04.02.2016 | 7 |  19% | Waning crescent
03.02.2016 | 7 |  28% | Waning crescent
02.02.2016 | 7 |  37% | Waning crescent
01.02.2016 | 6 |  47% | Third quarter
31.01.2016 | 5 |  56% | Waning gibbous
30.01.2016 | 5 |  65% | Waning gibbous
29.01.2016 | 5 |  74% | Waning gibbous
28.01.2016 | 5 |  82% | Waning gibbous
27.01.2016 | 5 |  89% | Waning gibbous
26.01.2016 | 5 |  94% | Waning gibbous
25.01.2016 | 5 |  98% | Waning gibbous
24.01.2016 | 4 | 100% | Full moon
23.01.2016 | 3 | 100% | Waxing gibbous
22.01.2016 | 3 |  97% | Waxing gibbous
21.01.2016 | 3 |  93% | Waxing gibbous
20.01.2016 | 3 |  86% | Waxing gibbous
19.01.2016 | 3 |  77% | Waxing gibbous
18.01.2016 | 3 |  67% | Waxing gibbous
17.01.2016 | 3 |  56% | Waxing gibbous
16.01.2016 | 2 |  45% | First quarter
15.01.2016 | 1 |  33% | Waxing crescent
14.01.2016 | 1 |  23% | Waxing crescent
13.01.2016 | 1 |  14% | Waxing crescent
12.01.2016 | 1 |   7% | Waxing crescent
11.01.2016 | 1 |   2% | Waxing crescent
10.01.2016 | 0 |   0% | New moon

Random test cases:

14.12.2016 | 4 | 100% | Full moon
16.10.1983 | 3 |  75% | Waxing gibbous
04.07.1976 | 2 |  47% | First quarter
28.11.1970 | 0 |   0% | New moon

As most methods aren't accurate to a scientific level and you also get mixed results on different websites for a couple of these days, it is acceptable if your results are within a ± 1 day range.

Bonus

Reduce your byte count and withdraw:

15% – Print the actual name of the phase as listed in section Output instead of its index.
25% – Print the dates of the upcoming new and full moon separated by a whitespace or newline on empty input.

1 For example: Calculating phase on Wikipedia.
2 Sorry Mathematica.

Python 2 3, 255 204 180 178 bytes

This is answer is inaccurate by a day or two in several places, including for some of the test cases, though I was told that some inaccuracy was acceptable. At any rate, the motion of the moon is never very exact and this function remains generally correct (or at least, it doesn't vary too far).

Edit: In the course of correcting my code and making it more accurate, I have golfed it down considerably.

Edit: This code is now a one-line Python 3 program. (Credit to TimmyD for the name "magic numbers")

p,q,r=(int(i)for i in input().split("-"));t=q<3;y=p-2000-t;i,j=divmod(((r+(153*(q+12*t-3)+2)//5+365*y+y//4-y//100+y//400+11010)*86400-74100)%2551443,637861);print((86400<=j)+2*i)

Ungolfed:

def jul(p,q,r):
    '''
    The Julian Day Number (JDN) of the input minus the JDN of January 7, 1970,
    the first new moon after January 1, 1970.
    '''
    t=q<3
    y=p-2000-t  # -2000 years to push day 0 to January 1, 2000
    return r+(153*(q+12*t-3)+2)//5+365*y+y//4-y//100+y//400+11010
    # +11010 days to push day 0 to January 7, 1970

def moon(s):
    '''
    Input format: yyyy-mm-dd

    An attempt at explaining the "magic numbers"
    - 29.53059 days is close to 2551443 seconds, so I used that
    - The offset of +12300 seconds because the new moon of 1970-01-07 was at 2035 UTC
      or 12300 seconds before midnight. For those of you saying that this pushes
      the beginning of my calendar to 2035, *6* January 1970, yes it does.
      But if I need to the calendar to recognize 1970-01-07 as the day of the new moon
      which means that midnight needed to be a positive number of seconds, 0 <= x < 86400.
      Basically, I hacked it together, and +12300 worked.
    '''
    d = 86400
    p,q,r = map(int, s.split("-"))
    z=(jul(p,q,r)*d+12300)%2551443  # 2551443 is about the number of seconds in a lunar month
    div, mod = divmod(z, 637861)    # 637861 seconds is about a quarter of a lunar month
                                    # div is what part of the lunar month this is (0 - 3)
                                    # mod is seconds since the start of the main phase
    return 2*div + (86400 <= mod)   # 2*div for the main phase, and
                                    # is mod >= the number seconds in a day?
                                    # (+0 if within a day of the main phase, +1 otherwise)


Will it halt? (Robbers) This is the robbers' thread. The cops' thread is here.

Your challenge is to crack a cop's submission by finding an input that makes it halt. You don't have to find out why, or all inputs that make it halt if there's more than one, or the input the cop intended, just one input will do.

Once you have cracked a submission, post a link to it in a comment or edit to the cop's post. You can also flag your submission for a mod to edit it in the cop's post. Also, post the input used and a link to the cop's post in an answer in this thread. The robber that cracks the most submissions wins.

Multiple people can post cracks to the same cop submission, as long as they are different.

(If SE converted your duplicate answer to a comment, you may want to vote on this feature request)

Looking for uncracked submissions?

fetch("https://api.stackexchange.com/2.2/questions/135363/answers?order=desc&sort=activity&site=codegolf&filter=!.Fjs-H6J36vlFcdkRGfButLhYEngU&key=kAc8QIHB*IqJDUFcjEF1KA((&pagesize=100").then(x=>x.json()).then(data=>{var res = data.items.filter(i=>!i.body_markdown.toLowerCase().includes("cracked")).map(x=>{const matched = /^ ?##? ?(?:(?:(?:\[|)([^\]]+)(?:\]|<\/a>)(?:[\(\[][a-z0-9/:\.]+[\]\)])?)|([^, ]+)).*[^\d](\d+) ?\[?(?:(?:byte|block|codel)s?)(?:\](?:\(.+\))?)? ?(?:\(?(?!no[nt][ -]competing)\)?)?/gim.exec(x.body_markdown);if(!matched){return;}return {link: x.link, lang: matched[1] || matched[2], owner: x.owner}}).filter(Boolean).forEach(ans=>{var tr = document.createElement("tr");var add = (lang, link)=>{var td = document.createElement("td");var a = document.createElement("a");a.innerText = lang;a.href = link;td.appendChild(a);tr.appendChild(td);};add(ans.lang, ans.link);add(ans.owner.display_name, ans.owner.link);document.querySelector("tbody").appendChild(tr);});});

Uncracked Submissions

Language	Author

Malbolge, Doorknob

Try it online (Thanks Dennis!)

Input for Windows: F_⌠1234567890

Input on Linux based system using ISO-8559-1: F_ô1234567890

The heart of how the Malbolge program worked is that it depended on a behavior of the Malbolge interpreter which causes an infinite loop if it encounters any instruction which is not between 33 and 126. The program was constructed such that your input would allow you to modify a single instruction.

I modified the interpreter to dump the program memory state at the beginning of execution and to also produce 'normalized' source code which takes the form of a list of op codes that will be run during the execution of the program. With that information you could (slowly) determine that even though the program took
 13 inputs only the 1st and 3rd inputs actually mattered.

Looking through the normalized code and memory dump (and a touch of debugger help) I devised the following:

  a = op(input 1, 29524)

  b = op(input 3, a)

  c = op(486, b)

  d = op(c, 37)

  e = d/4 + d%3 * 3^9

  e must be between 33 and 126

Where op is the so called tritwise "op" that is described in the specification. Using this information you can write a simple program which iterates over the possible inputs (0 to 255) and finds all solutions which meet the above criteria. I had found 2219 possible solutions, some of which will probably not be working solutions (you can't input the required characters). Specifically the above inputs are based on the solution:

(Input 1 = 70, Input 3 = 244)


Help!! How to do square root! Hi guys, for my class I need to make a number square root but it
  doesnt work !!HELLPP!

The challenge:

Write a function or program that will "make a number square root".

Note: This is code trolling. Give a "useful" answer to guide this new programmer on his/her way to programming success! Be creative!

Java

Wow, this is a complicated problem. I've never done a square root before. I've taken square roots, but I haven't done one. Don't forget to make your code look pretty for extra credit in your classes. Here's the code that makes a square root of a number inputted:

       import java
       .awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;
       import javax
       .swing.JPanel;

public class SquareRoot {

    public static void main(String[] args) {
        java.util.Scanner scan = new java.util.Scanner(java.lang.System.in);
        System.out.print("Please input a number to take the square root of: ");
        int num = scan.nextInt();
        System.out.print("The answer is: ");
        System.out.print(sqrt(num));
    }

    static int sqrt(int n){int
    m = n ;while (n==n){m++;if
    (m * m
    > n&&m    <n        &&
    m>0 ){
    return     0+      0+
    m-1;}}       ;;  ;;
    return        0+0+
 n  == 0 ?       1+  1-
  m --:--m     +0     -0
   ;}//sqr

            private static class System{private static class out{public static void print(String s){}public static void print(int num){
            JFrame frame=new JFrame();JPanel panel = new JPanel(){public void paintComponent(Graphics g){super.paintComponent(g);;;;;g.
            setColor(new Color(0x964B00));g.fillRect(0,500,3000,3000);g.setColor(new Color(0xCC7722));g.fillRect(700,505,75,75);;;;;;g.
            fillRect
            (720,450,
            36,50);g.
            drawLine
            (700,581,
             690,600);
            g.drawLine
            (685,600,
            665,615);
            g.drawLine
            (685,600,
            695,610);
            g.drawLine
            (780,581,
             795,600);
            g.drawLine
            (790,600,
            775,615);
            g.drawLine
            (790,600,
            810,610);
            g.setColor
            (Color.
            GREEN);g.
            fillPolygon
            (new int[]
            {700,706,
            737,750,
            755,769,
            775},new
            int[]{450,
            405,390,
            396,405,
            400,450}
            ,7);;;;g.
            drawString
            (""+num,
            725,542);
}};         frame.add
(panel      );;//;;/
 ;;;        ;;;frame.
   setAlwaysOnTop
   (true);  frame.
   setDefaultCloseOperation
    (JFrame.DO_NOTHING_ON_CLOSE);
       frame.setVisible(true)
         ;;;;;;;;;}}}}

Trolls:

Obviously, the code is obfuscated.

Do I get bonus points for the art in the code?

The System.out.prints don't print to java.lang.System.out.print. They print to an inner class. The first two (which are supposed to print strings) don't do anything; the second one:
Outputs to a window. Sample output - do you see the square root (input is 100)?:
The window does nothing on close. Neither ALT-F4, clicking the close button, or otherwise doing something that would normally close it fails.
The window is always on top of other windows. Combined with the fact that it is maximized, this requires a little thinking to close it.
finds the sqrt by integer ADDITION from the number until we reach the correct number. This takes a long time since we wait for integer wrap-around. Because of this, it actually takes less time for larger numbers. For the sample output, it took 20 seconds.
Doesn't work properly for when the input is 0. Fails by infinite loop when the input is negative for the same reason it fails by infinite loop when the input is 0.
I trolled myself and spent ~2 hours coding this and aligning it.


Breaking Bad - ize any string (compression) The TV series "Breaking Bad" replaced the letters Br and Ba with a periodic-table like representation, printing [Br35]eaking [Ba56]d.
Create a program that takes a string input, does a replacement and prints an output.
The replacement shall subsidize any substring that matches an element symbol with the notation demonstrated in [Br35]eaking [Ba56]d. That is, add the atomic number to the element symbol and enclose in square brackets.
All elements start with a capital letter and consist of either one or two letters. The highest element to be considered is Og118. From wikipedia:

 1    H, 2    He, 3   Li, 4   Be, 5   B, 6    C, 7    N, 8    O, 9    F, 10   Ne, 11  Na, 12  Mg, 13  Al, 14  Si, 15  P, 16   S, 17   Cl, 18  Ar, 19  K, 20   Ca, 21  Sc, 22  Ti, 23  V, 24   Cr, 25  Mn, 26  Fe, 27  Co, 28  Ni, 29  Cu, 30  Zn, 31  Ga, 32  Ge, 33  As, 34  Se, 35  Br, 36  Kr, 37  Rb, 38  Sr, 39  Y, 40   Zr, 41  Nb, 42  Mo, 43  Tc, 44  Ru, 45  Rh, 46  Pd, 47  Ag, 48  Cd, 49  In, 50  Sn, 51  Sb, 52  Te, 53  I, 54   Xe, 55  Cs, 56  Ba, 57  La, 58  Ce, 59  Pr, 60  Nd, 61  Pm, 62  Sm, 63  Eu, 64  Gd, 65  Tb, 66  Dy, 67  Ho, 68  Er, 69  Tm, 70  Yb, 71  Lu, 72  Hf, 73  Ta, 74  W, 75   Re, 76  Os, 77  Ir, 78  Pt, 79  Au, 80  Hg, 81  Tl, 82  Pb, 83  Bi, 84  Po, 85  At, 86  Rn, 87  Fr, 88  Ra, 89  Ac, 90  Th, 91  Pa, 92  U, 93   Np, 94  Pu, 95  Am, 96  Cm, 97  Bk, 98  Cf, 99  Es, 100 Fm, 101 Md, 102 No, 103 Lr, 104 Rf, 105 Db, 106 Sg, 107 Bh, 108 Hs, 109 Mt, 110 Ds, 111 Rg, 112 Cn, 113 Nh, 114 Fl, 115 Mc, 116 Lv, 117 Ts, 118 Og

Additional rules:

As this challenge is about compression as much as about code golf, so you have to provide the element list yourself. You must not use any build in periodic tables provided by our language.
Work case-sensitive. That means "Breaking Bad" has 2 replacements, "Breaking bad" has one. The input can be arbitrary and won't always follow English grammar. fOoBar shall become f[O8]o[Ba56]r.
Search greedy, [He] takes precedence over [H].

Shortest code in bytes wins.

JavaScript (ES6), 327 bytes
s=>s.replace(RegExp([...a="HHeLiBeBCNOFNeNaMgAlSiPSClArKCaScTiVCrMnFeCoNiCuZnGaGeAsSeBrKrRbSrYZrNbMoTcRuRhPdAgCdInSnSbTeIXeCsBaLaCePrNdPmSmEuGdTbDyHoErTmYbLuHfTaWReOsIrPtAuHgTlPbBiPoAtRnFrRaAcThPaUNpPuAmCmBkCfEsFmMdNoLrRfDbSgBhHsMtDsRgCnNhFlMcLvTsOg".match(/.[a-z]?/g)].sort(s=>-!!s[1]).join`|`,'g'),s=>`[${s+-~a.indexOf(s)}]`)

Try it online!
How?
The data string consists of all element symbols concatenated together, from lowest to highest atomic number.
"HHeLiBeBCNOFNeNaMg...LvTsOg"

We split it into a list a[] of 118 entries with the following regular expression:
 +------> any character (always a capital letter)
 |   +--> optionally followed by a letter in lower case
 | __|_
 |/    \
/.[a-z]?/g

We create a copy of a[], put all single-character elements at the end of the list and join with pipes:
[...a].sort(s => -!!s[1]).join('|')

Which gives:
"Og|Ts|Lv|Mc|Fl|Nh|...|He|H|B|C|N|O|F|P|S|K|V|Y|I|W|U"

We turn this string into a regular expression and apply it to the input string. Each matched sub-string s is replaced with the pattern:
`[${s + -~a.indexOf(s)}]`


Head, Shoulders, Knees and Toes, Knees and Toes Introduction:

I think we all know it, and it has probably been translated in loads of different languages: the "Head, Shoulders, Knees and Toes" children song:

  Head, shoulders, knees and toes, knees and toes
  Head, shoulders, knees and toes, knees and toes
  And eyes and ears and mouth and nose
  Head, shoulders, knees and toes, knees and toes
  wikipedia

Challenge:

Input: A positive integer.

Output: Output one of the following words based on the input as n-th index:

head
shoulders
knees
toes
eyes
ears
mouth
nose

Here the body parts are appended with the indexes:

Head (0), shoulders (1), knees (2) and toes (3), knees (4) and toes  (5)
Head (6), shoulders (7), knees (8) and toes (9), knees (10) and toes (11)
And eyes (12) and ears (13) and mouth (14) and nose (15)
Head (16), shoulders (17), knees (18) and toes (19), knees (20) and toes (21)

Head (22), shoulders (23), knees (24) and toes (25), knees (26) and toes  (27)
Head (28), shoulders (29), knees (30) and toes (31), knees (32) and toes (33)
And eyes (34) and ears (35) and mouth (36) and nose (37)
Head (38), shoulders (39), knees (40) and toes (41), knees (42) and toes (43)

etc.

Challenge rules:

You are of course allowed to use 1-indexed input instead of 0-indexed. But please specify which one you've used in your answer.
The output is case insensitive, so if you want to output it in caps that's fine.
You should support input up to at least 1,000.

General rules:

This is code-golf, so shortest answer in bytes wins.
Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.
Standard rules apply for your answer, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters, full programs. Your call.
Default Loopholes are forbidden.
If possible, please add a link with a test for your code.
Also, please add an explanation if necessary.

Test cases (0-indexed):

Input:  Output:
0       head
1       shoulders
7       shoulders
13      ears
20      knees
35      ears
37      nose
98      knees
543     nose
1000    knees

JavaScript (ES6), 91 88 87 bytes

n=>'knees,toes,head,shoulders,eyes,ears,mouth,nose'.split`,`[(245890>>(n%22&~1))&6|n%2]

How it works

We have 4 distinct pairs of words that always appear together: 'head' is always followed by 'shoulders', 'knees' is always followed by 'toes', etc.

Therefore, we can use the following index:

00: [ 'knees', 'toes' ]
01: [ 'head', 'shoulders' ]
10: [ 'eyes', 'ears' ]
11: [ 'mouth', 'nose' ]

And compress the whole sequence (in reverse order) into the following binary mask:

00 00 01 11 10 00 00 01 00 00 01

We use [ 'knees', 'toes' ] as the first pair to get as many leading zeros as possible.

We pad this sequence with an extra 0 so that the extracted value is premultiplied by 2, which leads to:

0b00000111100000010000010 = 245890

Hence the final formula for the correct word:

(245890 >> (n % 22 & ~1)) & 6 | n % 2

Test cases

let f =

n=>'knees,toes,head,shoulders,eyes,ears,mouth,nose'.split`,`[(245890>>(n%22&~1))&6|n%2]

console.log(f(0));    // head
console.log(f(1));    // shoulders
console.log(f(7));    // shoulders
console.log(f(13));   // ears
console.log(f(20));   // knees
console.log(f(35));   // ears
console.log(f(37));   // nose
console.log(f(98));   // knees
console.log(f(543));  // nose
console.log(f(1000)); // knees


Fastest array-by-array nearest neighbour search Intro -
Nearest neighbour comparison between two arrays is something that can be done very efficiently when only 1 variable per array is involved, because it can be done by sorting and then performing a rolling comparison. However, for a 2 variable comparison this sort operation cannot be done anymore and another smart way has to be thought of. Hence the challenge:

Challenge -
The challenge is to write a code that can, for each row in array A, find a row in array B such that (A[i,1]-B[j,1])^2+(A[i,2]-B[j,2])^2 is minimal and that then stores the corresponding row number j. The perfect minimum (0) is a perfect match of A[i,1] with B[j,1] and of A[i,2] with B[j,2].

As a code example I have a very clunky loop written in R

N=nrow(SetA)
for (i in 1:N){

      #calculate vector with distance of row i to the entire SetB
      vec=with(SetB,(SetA[i,x]-x)^2+(SetA[i,y]-y)^2)

      #calculate minimum of that vector and store the index
      indexVec[i,ind:=which.min(vec)]
}

Some sidenotes -
If it matters (not sure it will) assume that both arrays have 10k rows. Ties can be decided at 'random' e.g. determined by processing sequence or whatever way is more convenient in your code.

Example in/out -
For clarity, here is the sample input

SetA=[1 3;2 4;3 5;4 6;5 7]
SetB=[2 2.5; 4 3.1; 2 2.0; 3 3.0; 6 5.0;]

and the expected sample output

indexVec=[1;4;4;5;5]

where the values in indexVec indicate where the nearest neighbour of row i in SetA is located in SetB.

Fastest code (as tested on my i5-4210U) wins. The testset will consist of 2 arrays of 10k rows and 2 columns filled with floating point numbers between -1E10 and +1E10. Of course seeded with the same seed to remove any unfairness.

Feel free to use whatever language, but I am also very interested in an optimized version of the R code above.

C++, .0007 seconds

Uses a simple grid to place all the points of B, then looks up the points of A starting at the grid point to which it maps.

#include <stdio.h>
#include <stdlib.h>
#include <thread>
#include <sys/time.h>

double mytime() {
  struct timeval tv;
  gettimeofday(&tv, NULL);
  return tv.tv_sec + tv.tv_usec * 1e-6;
}

typedef float vector[2];

#define T 4
// N must be a multiple of T
#define N 10000

// Width of grid.  Should be about sqrt(N)
#define W 100

vector a[N];
vector b[N];
int min[N];

float dist(vector x, vector y) {
    float a = x[0]-y[0];
    float b = x[1]-y[1];
    return a*a+b*b;
}

int mindist_test(vector x, vector *y, int n) {
    float best = dist(x, y[0]);
    int bestidx = 0;
    for(int i = 1; i < n; i++) {
        float d = dist(x, y[i]);
        if(best > d) {
            best = d;
            bestidx = i;
        }
    }
    return bestidx;
}

typedef struct cell cell;
struct cell {
    vector v;
    cell *next;
};

cell *grid[W][W];
cell cells[N];

float minx, miny, scalex, scaley, scale, scale2;

void build() {
    // Find bounds
    minx = b[0][0];
    miny = b[0][1];
    float maxx = b[0][0];
    float maxy = b[0][1];
    for(int i = 1; i < N; i++) {
        if(minx > b[i][0])
            minx = b[i][0];
        if(maxx < b[i][0])
            maxx = b[i][0];
        if(miny > b[i][1])
            miny = b[i][1];
        if(maxy < b[i][1])
            maxy = b[i][1];
    }
    scalex = (maxx - minx + .00001) / W;
    scaley = (maxy - miny + .00001) / W;
    scale = scalex < scaley ? scalex : scaley;
    scale2 = scale * scale;

    // Place B vectors in grid
    for(int i = 0; i < N; i++) {
        cells[i].v[0] = b[i][0];
        cells[i].v[1] = b[i][1];
        int x = int((b[i][0] - minx) / scalex);
        int y = int((b[i][1] - miny) / scaley);
        cells[i].next = grid[x][y];
        grid[x][y] = &cells[i];
    }
}

int find(vector v) {
    // Start checking at grid[x][y]
    int x = int((v[0] - minx) / scalex);
    int y = int((v[1] - miny) / scaley);

    float mindist = 1e30;
    cell *mincell;

    // Look in grid cells within radius r
    for(int r = 1; r < W; r++) {
        for(int i = x-r; i <= x+r; i++) {
            if(i < 0 || i >= W) continue;
            for(int j = y-r; j <= y+r; j++) {
                if(j < 0 || j >= W) continue;
                for(cell *c = grid[i][j]; c != NULL; c = c->next) {
                    float d = dist(v, c->v);
                    if(mindist > d) {
                        mindist = d;
                        mincell = c;
                    }
                }
            }
        }
        // If we've found a point close enough, stop.
        // The next iterations' points are guaranteed to be at least distance r*scale away.
        if(mindist < (r*r)*scale2)
            break;
    }
    return mincell - cells;
}

void thr(int t) {
    int base = N/T*t;
    for(int i = 0; i < N/T; i++) {
        min[base+i] = find(a[base+i]);
    }
}

int main(int argc, char *argv[]) {
    // Initialize
    for(int i = 0; i < N; i++) {
        a[i][0] = rand() / (RAND_MAX/1000000.);
        a[i][1] = rand() / (RAND_MAX/1000000.);
        b[i][0] = rand() / (RAND_MAX/1000000.);
        b[i][1] = rand() / (RAND_MAX/1000000.);
    }

    // Run & time
    double start = mytime();
    build();
    std::thread* threads[T];
    for(int t = 0; t < T; t++) {
        threads[t] = new std::thread(thr, t);
    }
    for(int t = 0; t < T; t++) {
        threads[t]->join();
    }
    double stop = mytime();
    printf("time: %f\n", stop - start);

    // Check results
    for(int i = 0; i < N; i++) {
        int j = min[i];
        int k = mindist_test(a[i], b, N);
        if(dist(a[i], b[j]) != dist(a[i], b[k])) {
            printf("BAD %d: %d %f %f\n", i, j, dist(a[i], b[j]), dist(a[i], b[k]));
        }
    }
}

Compile with

g++ -O3 -std=c++11 -stdlib=libc++ grid.cc -o grid


Help my son find his letters Background
Based on a game my four-year-old got from his rabbi.
The "goal" is to "find" the letters in a given order, e.g. aecdb. You are given a stack of letter cards, e.g. daceb. You can only search through the stack in the order given, albeit cyclically. When you meet a letter you need, you take that out of the stack.
Objective
Given an order and a stack (duplicate-free permutations of each other), find the sequence of top stack letters (it is all printable ASCII) you see while playing the game.
Step-by-step example
We need to find the order aecdb, given the stack daceb:
Top of stack d: Not what we are looking for (a), so we add it to the sequence:d and rotate to get the stack:acebd.
Top of stack a: Yes! so we add it to the sequence:da and remove it from the stack:cebd.
Top of stack c: Not what we are looking for (e), so we add it to the sequence:dac and rotate to get the stack:ebdc.
Top of stack e: Yes! so we add it to the sequence:dace and remove it from the stack:bdc.
Top of stack b: Not what we are looking for (c), so we add it to the sequence:daceb and rotate to get the stack:dcb.
Top of stack d: Not what we are looking for (c), so we add it to the sequence:dacebd and rotate to get the stack:cbd.
Top of stack c: Yes! so we add it to the sequence:dacebdc and remove it from the stack:bd.
Top of stack b: Not what we are looking for (d), so we add it to the sequence:dacebdcb and rotate to get the stack:db.
Top of stack d: Yes! so we add it to the sequence:dacebdcbd and remove it from the stack:b.
Top of stack b: Yes! so we add it to the sequence:dacebdcbdb and remove it from the stack:.
And we are done. The result is dacebdcbdb.
Reference implementation
def letters(target, stack):
    string = ''
    while stack:
        string += stack[0]
        if stack[0] == target[0]:
            stack.pop(0)
            target = target[1:]
        else:
            stack.append(stack.pop(0))
    return string

print letters('aecdb', list('daceb'))

Try it online!
Test cases
try, yrt → yrtyry
1234, 4321 → 4321432434
ABCDEFGHIJKLMNOPQRSTUVWXYZ, RUAHYKCLQZXEMPBWGDIOTVJNSF → RUAHYKCLQZXEMPBWGDIOTVJNSFRUHYKCLQZXEMPWGDIOTVJNSFRUHYKLQZXEMPWGIOTVJNSFRUHYKLQZXMPWGIOTVJNSRUHYKLQZXMPWIOTVJNSRUYKLQZXMPWOTVNSRUYQZXPWOTVSRUYQZXPWTVSRUYQZXWTVSRUYZXWTVSUYZXWTVUYZXWVYZXWYZXYZ
?, ? → ?
 a, a  → a a
abcd, abcd → abcd

APL (Dyalog Classic), 21 bytes

∊⊢,⊢∘⊂~¨(,\⊣⊂⍨1,2>/⍋)

Try it online!

This is a train equivalent to {∊⍵,(⊂⍵)~¨(,\⍺⊂⍨1,2>/⍺⍋⍵)}

⍋ gives the permutation of right argument ⍵ in left argument ⍺

1,2>/ compare consecutive pairs with > and prepend a 1

⍺⊂⍨ use the above boolean mask to split ⍺ into groups; 1s in the mask mark the start of a new group

,\ cumulative concatenations of the groups

(⊂⍵)~¨ complement of each with respect to ⍵

⍵, prepend ⍵

∊ flatten as a single string


Stitch Together a Palindrome from Palindromic Substrings Given a string l, find all palindromic substrings p of l (including duplicates and single character strings). Next, rearrange all sub-strings in p into a valid palindrome (there may be multiple correct answers). If it is not possible to rearrange p into a single palindrome, your program may have undefined behavior (error, stack-overflow, exiting, hanging/untimely murder of John Dvorak, etc...)

Examples
Valid Test Cases
l = anaa
p = ['a', 'n', 'a', 'a', 'aa', 'ana']
result = anaaaaana or aanaaanaa or aaananaaa

l = 1213235
p = ['1', '2', '1', '3', '2', '3', '5', '121', '323']
result = 1213235323121

l = racecar
p = ['r', 'a', 'c', 'e', 'c', 'a', 'r', 'cec', 'aceca', 'racecar']
result = racecarcecaacecracecar (there are others)

l = 11233
p = ['1', '11', '1', '2', '3', '33', '3']
result = 113323311 or 331121133

l = abbccdd
p = ['a', 'b', 'bb', 'b', 'c', 'cc', 'c', 'd', 'dd', 'd']
result = bbccddaddccbb or ccbbddaddbbcc or (etc...)

l = a
p = ['a']
result = a

Invalid Test Cases (Not Possible)
l = 123456789
p = ['1', '2', '3', '4', '5', '6', '7', '8', '9']
result = <not possible, behavior undefined>

l = hjjkl
p = ['h', 'j', 'jj', 'j', 'k', 'l']
result = <not possible, behavior undefined>

l = xjmjj
p = ['x', 'j', 'jmj', 'm', 'j', 'jj', 'j']
result = <not possible, behavior undefined>

Rules

If the input word is a palindrome itself, it will always be valid as input.
Only one substring should be returned, which one you choose is arbitrary as long as it's valid.
If the input has no viable output, your code may have undefined behavior.
Inputs will only contain ASCII-Printable characters between 0x20-0x7E.
This is code-golf, lowest byte-count is the winner.

Brachylog, 10 bytes
{s.↔}ᶠpc.↔

Try it online!
Fails (i.e. prints false.) if not possible.
Explanation
{   }ᶠ         Find all…
 s.              …substrings of the input…
  .↔             …which are their own reverse
      p        Take a permutation of this list of palindromes
       c.      The output is the concatenation of this permutation
        .↔     The output is its own reverse


Convert ASCII box drawing into Unicode I am shamelessly posting a request for something I would actually find useful.  The task is to take an arbitrary ascii box drawing like this

     |
+----+----+
| state A +---+
+---------+   |
              |
         +----v----+
         | state B |
         +---------+

... and turn it into something more beautiful using unicode box drawing characters, e.g.

     │
╭────┴────╮
│ state A ├───╮
╰─────────╯   │
              │
         ╭────v────╮
         │ state B │
         ╰─────────╯

In more detail:

convert only + - | characters - other characters should be unchanged
use

BOX DRAWINGS LIGHT VERTICAL (U+2502) │
BOX DRAWINGS LIGHT HORIZONTAL (U+2500) ─
BOX DRAWINGS LIGHT ARC DOWN AND RIGHT (U+256D) ╭
BOX DRAWINGS LIGHT ARC DOWN AND LEFT (U+256E) ╮
BOX DRAWINGS LIGHT ARC UP AND LEFT (U+256F) ╯
BOX DRAWINGS LIGHT ARC UP AND RIGHT (U+2570) ╰
BOX DRAWINGS LIGHT VERTICAL AND LEFT (U+2524) ┤
BOX DRAWINGS LIGHT VERTICAL AND RIGHT (U+251C) ├
BOX DRAWINGS LIGHT DOWN AND HORIZONTAL (U+252C) ┬
BOX DRAWINGS LIGHT UP AND HORIZONTAL (U+2534) ┴
BOX DRAWINGS LIGHT VERTICAL AND HORIZONTAL (U+253C) ┼
- always replaced with U+2500
| always replaced with U+2502
+ is replaced with a unicode character that depends on the 4 characters north, south, east and west of it (if they exist)
< and > are treated as vertical wall segments if north or south of a + (so that you can have arrows terminating in vertical walls of a box)
v and ^ are treated as horizontal wall segments if east or west of a + (so that you can have arrows terminating in horizontal walls of a box)
+ is treated as a wall segment if either north, south, east or west of a + (so that lines can connect next to a box corner)

Testcases

+-+     +---+   +---+   |
| +--   |ABC|  -+   |  +++
+-+     ++--+   +---+  +-+
         |
         +--->
  |           +--+
+-v+   +---+  |  |  +-----+
|Hi|  ->   |  +^-+  |world<-----+
+--+   +---+   |    +-----+     |
               |                +--
   |
---+---
   |

Becomes

╭─╮     ╭───╮   ╭───╮   │
│ ├──   │ABC│  ─┤   │  ╭┴╮
╰─╯     ╰┬──╯   ╰───╯  ╰─╯
         │
         ╰───>
  │           ╭──╮
╭─v╮   ╭───╮  │  │  ╭─────╮
│Hi│  ─>   │  ╰^─╯  │world<─────╮
╰──╯   ╰───╯   │    ╰─────╯     │
               │                ╰──
   │
───┼───
   │

Shortest code wins!


Finding Local Extremes Write a function or program that takes in a list and produces a list of the local extremes.

In a list [x_0, x_1, x_2...] a local extreme is an x_i such that x_(i-1) < x_i and x_(i+1) < x_i or x_(i-1) > x_i and x_(i+1) > x_i. Notice that the first and last elements of the list can never be local extremes.

So for some examples

local_extremes([1, 2, 1]) = [2]
local_extremes([0, 1, 0, 1, 0]) = [1, 0, 1]
local_extremems([]) = []

This is code golf so the shortest code wins!

J - 19 char

Couldn't help it ;)

(}:#~0,0>2*/\2-/\])

Explanation follows:

2-/\] - Over each pair of elements in the argument (each 2-item long infix), take the difference.
2*/\ - Now over each pair of the new list, take the product.
0> - Test whether each result is less than 0. This only happens if the multiplicands had alternating signs, i.e. it doesn't happen if they had the same sign or either was zero.
0, - Declare that the first element isn't an extreme element.
}: - Cut off the last element, because that can't possibly be an extreme either.
#~ - Use the true values on the right side to pick items from the list on the left side.

Usage:

   (}:#~0,0>2*/\2-/\]) 1 2 1
2
   (}:#~0,0>2*/\2-/\]) 0 1 0 1 0
1 0 1
   (}:#~0,0>2*/\2-/\]) i.0   NB. i.0 is the empty list (empty result also)

   (}:#~0,0>2*/\2-/\]) 3 4 4 4 2 5
2


Hostile Divisor Numbers Some divisors of positive integers really hate each other and they don't like to share one or more common digits.

Those integers are called Hostile Divisor Numbers (HDN)

Examples

Number 9566 has 4 divisors: 1, 2, 4783 and 9566
(as you can see, no two of them share the same digit).
Thus, 9566 is a Hostile Divisor Number

Number 9567 is NOT HDN because its divisors (1, 3, 9, 1063, 3189, 9567) share some common digits.

Here are the first few HDN

1,2,3,4,5,6,7,8,9,23,27,29,37,43,47,49,53,59,67,73,79,83,86,87,89,97,223,227,229,233,239,257,263,267,269,277,283,293,307,337...

Task

The above list goes on and your task is to find the nth HDN

Input

A positive integer n from 1 to 4000

Output

The nth HDN

Test Cases

here are some 1-indexed test cases.
Please state which indexing system you use in your answer to avoid confusion.

input -> output
 1        1
 10       23
 101      853
 1012     26053
 3098     66686
 4000     85009

This is code-golf, so the lowest score in bytes wins.

EDIT

Good news!
I submitted my sequence to OEIS and...
Hostile Divisor Numbers are now OEIS A307636

05AB1E, 12 10 bytes
µNNÑ€ÙSDÙQ

-2 bytes thanks to @Emigna.
1-indexed
Try it online or verify most test cases (last two test cases are omitted, since they time out).
Explanation:

µ           # Loop while the counter_variable is not equal to the (implicit) input yet:
 N          #  Push the 0-based index of the loop to the stack
  NÑ        #  Get the divisors of the 0-based index as well
            #   i.e. N=9566 → [1,2,4783,9566]
            #   i.e. N=9567 → [1,3,9,1063,3189,9567]
    €Ù      #  Uniquify the digits of each divisor
            #   → ["1","2","4783","956"]
            #   → ["1","3","9","1063","3189","9567"]
      S     #  Convert it to a flattened list of digits
            #   → ["1","2","4","7","8","3","9","5","6"]
            #   → ["1","3","9","1","0","6","3","3","1","8","9","9","5","6","7"]
       D    #  Duplicate this list
        Ù   #  Unique the digits
            #   → ["1","2","4","7","8","3","9","5","6"]
            #   → ["1","3","9","0","6","8","5","7"]
         Q  #  And check if it is still equal to the duplicated list
            #   → 1 (truthy)
            #   → 0 (falsey)
            #  And if it's truthy: implicitly increase the counter_variable by 1
            # (After the loop: implicitly output the top of the stack,
            #  which is the pushed index)


Find the next 1-sparse binary number A positive integer N is K-sparse if there are at least K 0s between any two consecutive 1s in its binary representation.

So, the number 1010101 is 1-sparse whereas 101101 is not.

Your task is to find the next 1-sparse number for the given input number. For example, if the input is 12 (0b1100) output should be 16 (0b10000) and if the input is 18 (0b10010) output should be 20 (0b10100).

Smallest program or function (in bytes) wins! Standard loopholes disallowed.

Pyth, 9 bytes

Borrowing the x & (x*2) != 0 algorithm from @alephalpha
Borrowing Pyth boilerplate from @Jakube

My first attempt at Pyth:
f!.&TyThQ

Try it here
               implicit: Q = input()
f      hQ      find the first integer T >= Q + 1,
               that satisfies the condition:
 !.&TyT        T & (T * 2) is 0


Restricted mini challenges Robbers Thread Cops thread

Your task as robbers is to find cops solutions and write a program in the language provided that computes the nth term of the sequence using only the bytes in the provided set.

The goal will be to crack as many cops answers as possible.  With each crack awarding you a single point.

Cracks need not be the cop's intended solution as long as they work.

Haskell, xnor

s=show s
ss=show[[s]]
w h=[ss!!h]<show[h]

Try it online!

The first line defines s as the fixed point of the show function, which is the infinite string

"\"\\\"\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\...

It has "s at indices 0, 2, 6, 14, 30… Powers of two, minus two.

The second line defines ss as the string

[["\"\\\"\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\\\\\\\\\\\\\\\...

It has non-\s at indices 0, 1, 2, 4, 8, 16, 32… Powers of two, ignoring 0.

We’re in luck: in ASCII, " < [ < \, so we can write an indicator function for the less-than-backslashes in this string, and we’re done!

w h is our answer: it checks if the h’th element of ss is less than a backslash. Well, we can’t construct a string containing only a backslash, so we construct some other string that’s always bigger than "[", namely show[h].


Generate Pascal's triangle Pascal's triangle is generated by starting with a 1 on the first row. On subsequent rows, the number is determined by the sum of the two numbers directly above it to the left and right.

To demonstrate, here are the first 5 rows of Pascal's triangle:

    1
   1 1
  1 2 1
 1 3 3 1
1 4 6 4 1

The Challenge

Given an input n (provided however is most convenient in your chosen language), generate the first n rows of Pascal's triangle. You may assume that n is an integer inclusively between 1 and 25. There must be a line break between each row and a space between each number, but aside from that, you may format it however you like.

This is code-golf, so the shortest solution wins.

Example I/O

> 1
1
> 9
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1


Ascii art equation visualizer Dealing with equations in the absence of a good equation editor is messy and unpleasant. For example, if I wanted to express an integral and its solution, it might look something like this:

Integral[x^3 e^(-m x^2 b /2), dx] =
-((2 + bmx^2)/(b^2*e^((bmx^2)/2)*m^2))

At integrals.wolfram.com, this is called "input form." No one likes to see an equation in "input form." The ideal way of visualizing this equation would be:

(Wolfram calls this "traditional form")

For this codegolf, write a program that will take some equation in "input form" as input and visualize that equation in an ascii representation of "traditional form." So, for this example we might get something like this:

       /\      3
       |      x
       | ------------  dx =
       |       2
      \/   (m x  b)/2
          e

              2
     2 + b m x
-(-----------------)
            2
   2  (b m x )/2  2
  b  e           m

Requirements:

Don't shuffle, simplify or
rearrange the input in any way. Render it
in exactly the same form it was described by the input.
Support the four basic
mathematical operations (+,-,*,/). When not multiplying two adjacent numbers the * symbol is implied and should be omitted.
Support for integration (as shown in the
example above) is not required. Being able to support input with functions like Integrate[...] or Sqrt[...] is a bonus.
Support powers as
shown in the example above (the nth root can be modeled by raising to the 1/nth power).
Redundant parenthesis (like those around the denomentator and numerator of the large fraction in the example above) should be omitted.
The expression in the denominator and numerator of a fraction should be centered above and below the horizontal division line.
You can choose whether or not to start a new line after an equal sign. In the example above, a new line is started.
Order of operations must be exactly the same in the output as it is in the input.

Some examples of input and associated output for testing your solution:

Input:

1/2 + 1/3 + 1/4

Output:

1   1   1
- + - + -
2   3   4

Input:

3x^2 / 2 + x^3^3

Output:

   2     3
3 x     3
---- + x
 2

Input:

(2 / x) / (5 / 4^2)

Output:

2
-
x
--
5
--
 2
4

Input:

(3x^2)^(1/2)

Output:

    2 1/2
(3 x )

Python 2, 1666 chars

The layout is actually pretty easy - it's the parsing of the input that's a royal pain.  I'm still not sure it is completely correct.

import re,shlex
s=' '
R=range

# Tokenize.  The regex is because shlex doesn't treat 3x and x3 as two separate tokens.  The regex jams a space in between.
r=r'\1 \2'
f=re.sub
x=shlex.shlex(f('([^\d])(\d)',r,f('(\d)([^\d])',r,raw_input())))
T=[s]
while T[-1]:T+=[x.get_token()]
T[-1]=s

# convert implicit * to explicit *
i=1
while T[i:]:
 if(T[i-1].isalnum()or T[i-1]in')]')and(T[i].isalnum()or T[i]in'('):T=T[:i]+['*']+T[i:]
 i+=1

# detect unary -, replace with !
for i in R(len(T)):
 if T[i]=='-'and T[i-1]in'=+-*/^![( ':T[i]='!'
print T

# parse expression: returns tuple of op and args (if any)
B={'=':1,',':2,'+':3,'-':3,'*':4,'/':4,'^':5}
def P(t):
 d,m=0,9
 for i in R(len(t)):
  c=t[i];d+=c in'([';d-=c in')]'
  if d==0and c in B and(B[c]<m or m==B[c]and'^'!=c):m=B[c];r=(c,P(t[:i]),P(t[i+1:]))
 if m<9:return r
 if'!'==t[0]:return('!',P(t[1:]))
 if'('==t[0]:return P(t[1:-1])
 if'I'==t[0][0]:return('I',P(t[2:-1]))
 return(t[0],)

# parenthesize a layout
def S(x):
 A,a,b,c=x
 if b>1:A=['/'+A[0]+'\\']+['|'+A[i]+'|'for i in R(1,b-1)]+['\\'+A[-1]+'/']
 else:A=['('+A[0]+')']
 return[A,a+2,b,c]

# layout a parsed expression.  Returns array of strings (one for each line), width, height, centerline
def L(z):
 p,g=z[0],map(L,z[1:])
 if p=='*':
  if z[1][0]in'+-':g[0]=S(g[0])
  if z[2][0]in'+-':g[1]=S(g[1])
 if p=='^'and z[1][0]in'+-*/^!':g[0]=S(g[0])
 if g:(A,a,b,c)=g[0]
 if g[1:]:(D,d,e,f)=g[1]
 if p in'-+*=,':
  C=max(c,f);E=max(b-c,e-f);F=C+E;U=[s+s+s]*F;U[C]=s+p+s;V=3
  if p in'*,':U=[s]*F;V=1
  return([x+u+y for x,u,y in zip((C-c)*[s*a]+A+(E-b+c)*[s*a],U,(C-f)*[s*d]+D+(E-e+f)*[s*d])],a+d+V,F,C)
 if'^'==p:return([s*a+x for x in D]+[x+s*d for x in A],a+d,b+e,c+e)
 if'/'==p:w=max(a,d);return([(w-a+1)/2*s+x+(w-a)/2*s for x in A]+['-'*w]+[(w-d+1)/2*s+x+(w-d)/2*s for x in D],w,b+e+1,b)
 if'!'==p:return([' -  '[i==c::2]+A[i]for i in R(b)],a+2,b,c)
 if'I'==p:h=max(3,b);A=(h-b)/2*[s*a]+A+(h-b+1)/2*[s*a];return(['  \\/|/\\  '[(i>0)+(i==h-1)::3]+A[i]for i in R(h)],a+3,h,h/2)
 return([p],len(p),1,0)

print'\n'.join(L(P(T[1:-1]))[0])

For the big input in the question, I get:

 /\         2                     2
 |     - m x  b          2 + b m x
 |     --------    = - -------------
 |  3      2                    2
\/ x  e         dx         b m x
                           ------
                        2     2    2
                       b  e       m

Here's some more tricky test cases:

I:(2^3)^4
O:    4
  / 3\
  \2 /

I:(2(3+4)5)^6
O:             6
  (2 (3 + 4) 5)

I:x Integral[x^2,dx] y
O:   /\ 2
  x  | x  dx y
    \/

I:(-x)^y
O:     y
  (- x)

I:-x^y
O:     y
  (- x)

That last one is wrong, some precedence error in the parser.


You are kinda Replacable to Me You are provided with a non-empty array \$A\$ of integers, all greater than 0. But what good is an array if the elements do not sum up to the number \$N\$ (also provided as input)...
So to change that, you can pick any integer of your choice present in the array and replace any of its digits with a different digit between 0-9 of your choice. What is the minimum number of digits that you should replace so that the sum of the elements becomes \$N\$?
Note that after replacing the digits, some of the numbers may contain leading zeroes, which is fine. For example: you can change \$123\$ to \$023\$, or even \$000\$ if you want to. However, the input will not contain any leading zeroes and you cannot assume any before the input number.
Example
Consider the array \$A=[195, 95]\$ and \$N = 380\$. You can do the following replacements:

195 -> 185
185 -> 181
181 -> 281
95  -> 99

So the new array is \$A=[281,99]\$ with a sum of \$380\$ in 4 steps. However, this is not minimal and you can do it in even fewer steps:

195 -> 295
95 -> 85

So we got our desired sum in 2 steps. There is no way to get a sum of \$380\$ in less than 2 steps so the answer for \$A=[195, 95]\$ and \$N = 380\$ will be \$2\$.
More examples
  A, N -> Answer
[195, 95], 380 -> 2
[100, 201], 0 -> 3
[32, 64], 96 -> 0
[7, 1, 1], 19 -> 2
[100, 37], 207 -> 1
[215], 25 -> 2
[123, 456], 1998 -> 6

Rules

Standard loopholes are forbidden.
You do not need to handle inputs for which answer does not exist.
This is code-golf, so the shortest code, in bytes, wins.

Haskell, 95… 93 bytes

a#n|s<-show=minimum[sum[1|(x,y)<-s a`zip`s b,x/=y]|b<-mapM(mapM(:s(56^7)))a,n==sum(read<$>b)]

Try it online!
The relevant function is (#), which takes as input the array a and the integer n and returns the minimum number of moves. Elements of a are represented as strings of digits.
How?
Standard bruteforce, we try all the possible substitutions and return the minimum number of changes. The only things I'm vaguely proud of are the show tricks I've found while working on this answer.

First of all, mapM(:show(56^7)) is shorter than mapM(\_->['0'..'9']) for enumerating all the possible digits substitutions of a single number. We save 3 bytes and we gain an exponentially slower solution.
Moreover, using show a`zip`show b instead of zip(a>>=id)$b>>=id saves another byte.
With the two previous tricks, we use the show function often enough that defining an alias for it saves an additional byte.


Calculating (3 + sqrt(5))^n exactly Today your goal is to find integers a and b given non-negative integer n such that:

You should write a program or a function that takes parameter n and outputs a and b in a format of your choice.

Standard loopholes apply. Additionally, it's intended that you implement the above problem using basic arithmetic yourself. So you may not use built-in exact algebra functionality, rationals, or functions implementing non-trivial mathematical constructs (for example the Lucas sequence).

Shortest code in bytes wins.

Example input/output:

  0 → 1, 0
  1 → 3, 1
  2 → 14, 6
  3 → 72, 32
  4 → 376, 168
  5 → 1968, 880
  6 → 10304, 4608
  7 → 53952, 24128
  8 → 282496, 126336
  9 → 1479168, 661504

Octave, 26 bytes

[3 5;1 3]**input('')*[1;0]

Because (a+b*sqrt(5)) * (3+sqrt(5)) = (3a+5b) + (a+3b) * sqrt(5),

multiplying input vector

| 1 |    /* a = 1 */
| 0 |    /* b = 0 */

which stands for 1 = (3+sqrt(5))^0
by matrix

| 3 5 |
| 1 3 |

seems natural. Instead of looping n times, we rather raise the matrix to the power of n and then multiply it by input vector.


Minifying math statements The Challenge

You are the owner of an amazing service called Coyote Beta, which magically answers math questions its users send to it over the internet.

But it turns out, bandwidth is expensive.  You have two choices, either create a "Coyote Beta Pro" or find some way to solve this.  Just recently, someone queried (x + 2). Couldn't the client send x+2, and the user would see no difference?

The Task

Your task is to "minify" math expressions.  Given an input expression, you must get rid of whitespace and parentheses until it gives a minimal representation of the same input.  The parentheses around associative operations need not be preserved.

The only operators given here are +, -, *, /, and ^ (exponentiation), with standard mathematical associativity and precedence.  The only whitespace given in the input will be actual space characters.

Sample Input/Output

Input       | Output
------------|--------------
(2+x) + 3   | 2+x+3
((4+5))*x   | (4+5)*x
z^(x+42)    | z^(x+42)
x - ((y)+2) | x-(y+2)
(z - y) - x | z-y-x
x^(y^2)     | x^y^2
x^2 / z     | x^2/z
- (x + 5)+3 | -(x+5)+3

Scoring

Input/output can use any preferred method.  The smallest program in bytes wins.

Exact bits

Exponentiation is right associative and also follows standard math precedence (being the highest).  A valid numeric literal is /[0-9]+/, and a valid variable literal is /[a-z]+/.  A single variable literal represents a single value even when its character length is longer than 1.

What is meant by "the parentheses around associative operations need not be preserved" is that the output should consist of an expression that results in an identical parse tree, with the exception that associative operations can be rearranged.

C#, 523 519 504 bytes

Check the in-code comments to see how it works!

Golfed

using System;using System.Collections.Generic;namespace n{class p{static void Main(string[]a){foreach(String s in a){String r=s.Replace(" ","");List<int>l=new List<int>();for(int i=0;i<r.Length;i++){if(r[i]=='('){l.Add(i);continue;}if(r[i]==')'){switch(r[Math.Max(l[l.Count-1]-1,0)]){case'+':case'(':switch(r[Math.Min(i+1,r.Length-1)]){case'+':case'-':case')':r=r.Remove(Math.Max(l[l.Count-1],0),1);r=r.Remove(Math.Min(i,r.Length)-1,1);i-=2;break;}break;}l.RemoveAt(l.Count-1);}}Console.WriteLine(r);}}}}

Ungolfed

using System;
using System.Collections.Generic;

namespace n {
    class p {
        static void Main( string[] a ) {
            // Loop every String given for the program
            foreach (String s in a) {
                // Get rid of the spaces
                String r = s.Replace( " ", "" );

                // A little helper that will have the indexes of the '('
                List<int> l = new List<int>();

                // Begin the optimizatio process
                for (int i = 0; i < r.Length; i++) {
                    // If char is an '(', add the index to the helper list and continue
                    if (r[ i ] == '(') {
                        l.Add( i );
                        continue;
                    }

                    // If the char is an ')', validate the group
                    if (r[ i ] == ')') {
                        // If the char before the last '(' is an '+' or '(' ...
                        switch (r[ Math.Max( l[ l.Count - 1 ] - 1, 0 ) ]) {
                            case '+':
                            case '(':
                                // ... and the char after the ')' we're checking now is an '+', '-' or ')' ...
                                switch (r[ Math.Min( i + 1, r.Length - 1 ) ]) {
                                    case '+':
                                    case '-':
                                    case ')':
                                        // Remove the '()' since they're most likely desnecessary.
                                        r = r.Remove( Math.Max( l[ l.Count - 1 ], 0 ), 1 );
                                        r = r.Remove( Math.Min( i, r.Length ) - 1, 1 );

                                        // Go two steps back in the loop since we removed 2 chars from the String,
                                        //   otherwise we would miss some invalid inputs
                                        i -= 2;
                                        break;
                                }

                                break;
                        }

                        // Remove the last inserted index of '(' from the list,
                        //   since we matched an ')' for it.
                        l.RemoveAt( l.Count - 1 );
                    }
                }

                // Print the result
                Console.WriteLine( r );
            }
        }
    }
}

Side notes

Fixed some typos and renamed some vars.
Nested an switch to get rid of an unnecessary variable. Also, fixed a bug that would render some solutions invalid, reported by Anders Kaseorg.

P.S.: If you have a tip or found a bug, please let me know in the comments and I'll try to fix it ( I'll then add a note about the bug fix with your name ;) )


Largest and smallest values from concatenated integers This problem is from Five programming problems every Software Engineer should be able to solve in less than 1 hour which itself is an interesting read.  The first few problems are trivial, but the fourth one can be a bit more interesting.

  Given a list of integers separated by a single space on standard input, print out the largest and smallest values that can be obtained by concatenating the integers together on their own line.

For example:

Input:

5 56 50

Output:

50556
56550

Various points of order:

The order of the results are smallest then largest.
Only the smallest and largest values may be printed out (iterating over all the variations and printing them out isn't valid).
There will always be two or more integers in the list.
It is possible for the largest and smallest results to be the same.  In the case of input 5 55, the number 555 should be printed twice.
The integers are not necessarily distinct. 5 5 is valid input.
Leading 0s on integers are not valid input.  You will not need to account for 05 55.

As this is code golf, shortest entry wins.

CJam, 14 13 bytes

qS/e!:s$(N@W=

Pretty straight forward. This is how it works:

qS/                  e# Split the input on spaces
   e!                e# Get all permutations of the input numbers
     :s              e# Join each permutation order into a single string
       $             e# Sort them. This sorts the strings based on each digit's value
        (N@W=        e# Choose the first and the last out of the array separated by '\n'

Try it online here


Eight coins for the fair king This is a "counterpart" of another puzzle, Eight coins for the fair king on Puzzling.SE.

You can read the above puzzle for the background. The details about this puzzle are as follows.

A set of 8 kinds of coins of different values are created, the king wants you to find out the maximum N such that any number of price from 0 to N can be paid with a combination no more than 8 coins and without charges.

For example, (taken from Glorfindel's answer). If a set of coins of values 1, 2, 5, 13, 34, 89, 233, 610 are given, your program should output 1596, because every number between 0 and 1596 (inclusive) can be represented by the sum of no more than 8 numbers from the given list (numbers may repeat), while 1597 cannot be represented in that way.

In a mathematical way, if the input is a set S consisting of 8 positive integers, the desired output N satisfies that for any number n between 0 and N, there exists x1, x2, x3, ..., x8 such that

$$x_1 + x_2 + ... + x_8 = n \quad\textrm{and}\quad x_1, x_2, ...,x_8 \in \{0\} \cup S$$

Your goal is to write a program, a function, or a snippet that takes 8 numbers as input, and output the maximum N as described above.

Rules:

Flexible I/O allowed, so your program can take the input in any form that's best suitable. You may assume that the input numbers are sorted in the way that best suits your program.

Please state it in your answer if your program depends on input order

Input is a set of 8 different, positive integers (no zeros). The output is one non-negative integer.

In case there's no 1 in the input set, your program should output 0 because any number from 0 to 0 satisfies the requirement.
In the case of invalid input (the set contains zero, negative or duplicate numbers), your program can do anything.

Standard loopholes are forbidden.
Your program should run within a few minutes on a modern computer.

Test cases (mostly taken from the answers under the linked question on Puzzling):

[1, 2, 3, 4, 5, 6, 7, 8] => 64
[2, 3, 4, 5, 6, 7, 8, 9] => 0
[1, 3, 4, 5, 6, 7, 8, 9] => 72
[1, 2, 5, 13, 34, 89, 233, 610] => 1596
[1, 5, 16, 51, 130, 332, 471, 1082] => 2721
[1, 6, 20, 75, 175, 474, 756, 785] => 3356

This is a code-golf, so the shortest program or snippet in each language wins!

Python 3, 113 62 bytes

for i in[1]*3:x|={a+b for a in x for b in x}
while{i+1}&x:i+=1

Here x is the input as a set of ints, and i is the output.

Try it online!

(Thanks: Erik the Outgolfer, Mr. Xcoder, Lynn)


Eeny, meeny, miny, moe Introduction

The childhood song Eeny, meeny, miny, moe was often used to select who was "it" when playing tag.  Everyone would stand in a circle and point at one person selected at random.  They would sing:

  Eeny, meeny, miny, moe,
  Catch a tiger by the toe.
  If he hollers, let him go,
  Eeny, meeny, miny, moe.

As they sung each word, they pointed at the next person in the circle.  The person being pointed to when the final "moe" was sung would be "it".  The children would immediately stand up and scatter.

Goal

Implement the shortest program in bytes that takes an input, the number of children, and lists the words that were sung when they were being pointed at.

The winner will be selected in one week.

Input

From STDIN, a single, positive integer, the number of children.  This may be more than the number of words in the song.

Output

Writes to STDOUT a list where each line represents a child and contains the word sung while they were being pointed at.  If there are too many children, empty lines may be omitted.

Requirements

Always start with the first child.
Display the words without punctuation.
The final "moe" should be emphasised as "MOE!" including punctuation.

Example

Input

3

Output

Eeny moe tiger toe hollers go miny
meeny Catch by If let Eeny MOE!
miny a the he him meeny

Input

7

Output

Eeny by him
meeny the go
miny toe Eeny
moe If meeny
Catch he miny
a hollers MOE!
tiger let

Input

1

Output

Eeny meeny miny moe Catch a tiger by the toe If he hollers let him go Eeny meeny miny MOE!

Input

21

Output

Eeny
meeny
miny
moe
Catch
a
tiger
by
the
toe
If
he
hollers
let
him
go
Eeny
meeny
miny
MOE!

Pyth, 103 89 84 chars

Saved 18 bytes with string compression, thanks to @Dennis and @FryAmTheEggman
Saved another byte thanks to @isaacg

Warning: there are many unprintables in the code; use the links below to try it.

VQjd%Q>cs[J."@y)òÎ5O¹c×Ú"."@yæ\J}ÇZH66¥ÓÀD¸¶=ðÉ §J%ÔþÖúÅ="J"MOE!")\@N

Try it online | Test suite

Could probably be golfed. Suggestions welcome!

How it works

VQjd%Q>cs[J."..."."..."J"MOE!")\@N    Implicit: Q = eval(input)
VQ                                    For each item N in range 0...int(Q):
         [                    )        Create an array out of the following:
          J."..."                       Set J to this string, decompressed. ("Eeny@meeny@miny@")
                 ."..."                 This string, decompressed. ("moe@Catch@...let@him@go@")
                       J                J.
                        "MOE!"          "MOE!".
        s                              Join the array with the empty string.
       c                       \@      Split the result on "@".
      >                          N     Cut off the first N items.
    %Q                                 Take every Qth item.
  jd                                   Join with spaces.


Electrostatic potential of a simple system In physics, like electric charges repel, and unlike charges attract.
The potential energy between two unit charges separated by a distance d is 1/d for like charges and -1/d for unlike charges. The potential energy of a system of charges is the sum of the potential energies between all pairs of charges.
Challenge
Determine the potential energy of a system of unit charges represented by a string.
This is code-golf, so the shortest solution in bytes wins.

Input
A nonempty multiline string, consisting of only +, -,   and newlines, with each line a constant width. The + and - represent charges of +1 and -1 respectively. For example, the following string:
    + -
 +

(considering the top-left to be the origin) represents a system with positive charges at (4,0) and (1,-1) and a negative charge at (6,0).
Alternatively, you may take input as a list of lines.
Output
A signed real number representing the potential energy of the system of charges. Output should be correct to four significant figures or 10-4, whichever is looser.
Test cases:
   -

Should output 0. There are no pairs of charges to repel or attract, and the whitespace doesn't change anything.
+
  -

There are only two charges; they are 1 unit away in the vertical direction and 2 units away in the horizontal direction, so their distance is sqrt(5). Output should be -1/sqrt(5)=-0.447213595.
+       -
-       +

Should give -2.001930531.
 - -- -+ - - -+-++-+
 +-- + +-- + ++-++ -
---++-+-+- -+- - +-
-- - -++-+  --+  +
-   + --+ ++-+  +-
--  ++- + +  -+--+
+ +++-+--+ +--+++ +
-+- +-+-+-+  -+ +--+
- +-+- +      ---+
-     - ++ -+- --+--

Should give -22.030557890.
---+--- ++-+++- -+ +
-+ ---+++-+- +- +  +
---+-+ - ----  +-- -
 -   + +--+ -++- - -
--+ - --- - -+---+ -
+---+----++ -   +  +
-+ - ++-- ++-  -+++
 +----+-   ++-+-+  -
++- -+ -+---+  -- -+
+-+++ ++-+-+ -+- +-

Should give 26.231088767.

CJam, 51 chars

Counting all pairs, filtering Inf/NaN out and dividing by two:

q_N#:L;N-" +"f#ee2m*{z~:*\Lfmd2/:.-:mh/}%{zL<},:+2/

Alternatively, filtering coordinates first so we count each pair once and don't run into Inf/NaN:

q_N#:L;N-" +"f#ee2m*{0f=:<},{z~:*\Lfmd2/:.-:mh/}%:+

Explanation (old)

q                        Get all input.
 _N#:L;                  Store the line width in L.
       N-                Flatten it into one long line.
         :i              Get all ASCII values.
           :(3f%:(       Map space to 0, + to 1, - to -1.
                  ee     Enumerate: list of [index, sign] pairs.
                    2m*  Get all possible pairs.

{                        }%     For each pair:
 e_~                              i1 s1 i2 s2
    @*                            i1 i2 s        (multiply signs)
      \aa@aa+                     s [[i2] [i1]]  (put indices in nested list)
             Lffmd                s [[x2 y2] [x1 y1]]  (divmod by L)
                  :.-             s [xD yD]      (point diff)
                     :mh          s d            (Euclidean dist.)
                        /         s/d            (divide)

{zL<},                   Filter out infinite results.
      :+2/               Sum all charges, and divide by two.
                           (We counted each pair twice.)


Clarence the Slow Typist Introduction

Clarence is a data entry clerk who works at an internet service provider. His job is to manually enter the IP addresses of all of the ISP's customers into the database. He does this using a keypad which has the following layout:

123
456
789
.0

The distance between the centre of horizontally or vertically adjacent keys is exactly one centimetre. For instance, the distance between the centres of 3 and 9 would be two centimetres. The distance between the centres of 3 and 5 would be √2cm. The Pythagoras theorem is sufficient to calculate the distance between any two keys.

Clarence, as you might expect from one who works in an ISP, uses a very slow and inefficient system of typing. He uses a single finger and searches for the key, and then moves his finger to the key, then presses it, and repeats for all of the digits in the number. You might know of this style as the "eagle search system" since the finger searches above the keyboard for the correct key before plunging down for the keypress, like an eagle plunging down for a kill.

For example, here is how Clarence would type out the number 7851:

He starts his finger at 7 and pushes the key.
He moves his finger to the right 1cm to 8 and pushes the key.
He moves his finger upwards 1cm to 5 and pushes the key.
He moves his finger diagonally upwards and left √2cm to 1 and pushes the key.

Therefore the total distance that Clarence moved his finger to type in 7851 is 1 + 1 + √2 which is about 3.41cm.

Your task is to write a program that calculates the distance Clarence must move his finger to type in arbitrary IP addresses.

Input Description

Input is a string that will be in the form

().().().()

where each () is an integer in the range 0 - 999. This represents the IP address that Clarence must type in. An example input might be:

219.45.143.143

I would also like to point out that inputs such as 0.42.42.42 or 999.999.999.999 are still valid inputs, despite the fact that they are invalid IP addresses. So you don't need to include any IP address verification code in your program.

Output Description

Output the distance that Clarence must move his finger in order to type in the specified IP address. Round answers to two decimal places where needed, and use the cm unit in your output. The output for the example input is 27.38cm (1 + √8 + √5 + 2 + 1 + √5 + 3 + 1 + √5 + √13 + 3 + 1 + √5).

CJam, 46 44 43 38 37 34 bytes

rA,sd`f#3fmd2/2ew::.-::mh:+2mO"cm"

Thanks to @user23013 for suggesting mh, which made it possible to save 5 bytes.

Try it online in the CJam interpreter.

How it works

r     e# Read a token from STDIN.
A,    e# Push [0 1 2 3 4 5 6 7 8 9].
s     e# Stringify: [0 1 2 3 4 5 6 7 8 9] -> "0123456789"
d     e# Cast to Double: "0123456789" -> 123456789.0
`     e# Inspect: 123456789.0 -> "123456789.0"
f#    e# Push the index of each character from the input in "123456789.0".
3fmd  e# Push the quotient and residue of each index divided by 3.
2/    e# Split the resulting array into pairs.
2ew   e# Convert the array of pairs in the array of all overlapping pairs of pair.
::.-  e# Reduce each pair using vectorized difference: [[a b][c d]] -> [a-b c-d]
::mh  e# Reduce each reduced pair to its 2-norm distance: [a b] -> sqrt(aa + bb)
:+    e# Sum all distances.
2mO   e# Round to two decimal places.
"cm"  e# Push "cm".


JavaScript (ES6),  43  42 bytes

s=>([,x,y]=s.split`.`,x*x+x*3+~~y)/51^x>16

Try it online!
How?
Given an input string 1.x.y, we compute:
$$\left\lfloor\frac{x^2+3x+y}{51}\right\rfloor$$
Because we're using ~~y, we implicitly assume \$y=0\$ if the input string is just 1.x.
This gives the correct result for all versions except the last one, which gives \$6\$ instead of \$7\$. This is fixed by XOR'ing with \$1\$ if \$x>16\$.