Find the longest uninterrupted arc The challenge here is to find the longest uninterruped arc around a unit circle with a random amount of points distributed in random positions around it.
Here is a diagram to assist my explanation:

The red line indicates the largest arc between any two points that is not interrupted by any other points. The challenge is to find the two points on either end of the red line. The green line is simply the straight line distance.

A clarification about what interrupted means: When drawing an arc around the edge of the circle (the red line), this arc should not be intersected by any other point.

Here is a template for the function in C#:

int[] FindPair(double[][] points)
{
     return new[]{ 0, 1}; //Find the indices of the two points
}

The function should return two integers, the indices of the two points on either end of the green line.

Assumptions:

The Length of the points array is arbitrary but more than two. In the example we have: points[40][]
Each element of the points array contains the x, y position of the point, for example:  points[i] = {x, y}
You can assume that the distance of any given point to the origin at the centre of the circle is always 1.

Notes:

The answer with the smallest Big O algorithm complexity wins. In case of a tie, shorter code wins.
Bonus points for the solution to have the ability to work in more dimensions than two.
I do have a solution, but it is very computationally expensive and only produces the correct answer around 99% of the time.
I am not sure if the problem has a name in mathematics, or a generally accepted solution. If anyone knows of a better name for this problem so that I can have a better title, that would be helpful.

Test case 1:

Points: {
  { -0.71997 , -0.69400 },
  { 0.88564 , 0.46437 },
  { 0.78145 , -0.62397 },
  { 0.98409 , -0.17765 },
  { 0.88220 , 0.47087 },
  { 0.69938 , 0.71475 },
  { -0.89036 , -0.45526 },
  { -0.70588 , -0.70833 },
  { 0.70507 , 0.70914 },
  { -0.34971 , 0.93686 }
}

Solution:
{6, 9}

Test case 2:

Points: {
  { -0.71038 , 0.70382 },
  { 0.04882 , 0.99881 },
  { -0.53250 , -0.84643 },
  { -0.86814 , -0.49632 },
  { 0.97588 , -0.21829 },
  { 0.73581 , -0.67719 },
  { 0.88413 , -0.46724 },
  { -0.28739 , -0.95781 },
  { -0.68325 , 0.73019 },
  { 0.91879 , 0.39475 },
  { 0.65335 , 0.75706 },
  { -0.21009 , -0.97768 },
  { -0.94542 , -0.32585 },
  { 0.83207 , -0.55467 },
  { 0.99482 , 0.10170 },
  { 0.86228 , 0.50643 },
  { 0.98017 , 0.19817 },
  { 0.67520 , 0.73763 },
  { -0.03982 , -0.99921 },
  { -0.57624 , -0.81728 }
}

Solution: {0, 12}

Invalid example:

This is invalid, because when drawing an arc around the edge of the circle (the red line) between the two points connected by the green line, this arc is intersected by another point.

Python 3, O(n*log(n)), 167 bytes

import math
def f(p):p=[math.atan2(*x)for x in p];q=sorted(p);d=[b-a for a,b in zip(q,q[1:])]+[math.pi*2-q[-1]+q[0]];i=d.index(max(d));return map(p.index,(q*2)[i:i+2])

Try it online!

The sorting step takes O(n*log(n)) time, all other steps take linear time.

Ungolfed

import math
def f(p):
  p=[math.atan2(x, y)for x, y in p]   # convert coords to angle (radians)
  q=sorted(p)                         # sort by angle
  d=[b-a for a,b in zip(q,q[1:])]     # calculate the difference between two adjacent points
  d+=[math.pi*2-q[-1]+q[0]]           # difference between first and last point
  i=d.index(max(d))                   # where is the maximum delta?
  return map(p.index,(q*2)[i:i+2])    # where were these two points in the original list?


Counting shortest paths on a triangular grid Background

An Eisenstein integer is a complex number of the form \$ z = a + b\omega \$ where \$a, b\$ are integers and \$\omega\$ is the third root of unity \$\frac{1-\sqrt3i}{2}\$. The Eisenstein integers can be viewed as the triangular lattice points, as shown in the image below (from Wikipedia):

Following the triangular grid, one step of movement can be done in six directions:

$$
\begin{array}{r|r}
\text{Direction} & \text{Step} \\ \hline
E  & 1 \\
NE & 1 + \omega \\
NW & \omega \\
W  & -1 \\
SW & -1 - \omega \\
SE & -\omega
\end{array}
$$

Task

Given an Eisenstein integer \$z\$, count all shortest paths from the origin (\$0\$) to the point equivalent to \$z\$ on the triangular grid.

Since \$z = a + b \omega\$ can be represented by two integers \$ a, b \$, you can take the input as two integers \$a, b\$ in any consistent order and structure of your choice.

One way to compute this is (thanks to @xnor):

Take the absolute values of [a, b, a-b], and call it L
Calculate binomial(max(L), any other value in L)

Test cases

 a  b  ans
 0  0    1
 2  0    1
 5  3   10
 4  4    1
 2  3    3
 0  2    1
-2  2    6
-4  0    1
-5 -3   10
-1 -1    1
-3 -5   10
 0 -3    1
 4 -1    5
-4 -9  126
 7 -4  330
 8  1    8
 3 -3   20

Jelly, 7 bytes

;IAṀc$Ṁ

Try it online!

How?

;IAṀc$Ṁ - Link: list of two integers   e.g. [-4, -9]
 I      - incremental differences           [-5]           (since -9 - -4 = -5)
;       - concatenate                       [-4, -9, -5]
  A     - absolute values                   [4, 9, 5]
     $  - last two links as a monad:
   Ṁ    -   maximum                         9
    c   -   choose (vectorises)             [126, 1, 126]  (9c4=9c5=126 and 9c9=1)
      Ṁ - maximum                           126


Shortest string expressions stable under deleting quotes Forgetting quotes can lead to certain problems.
For example, in Scala the two expressions:

"("+("+")+(")+(")+")"
 ("+("+")+(")+(")+")

differ only in starting and ending quotes, but they respectively yield the result:

(+)+()
+()+()+

But this expression in scala almost has the desired property:

def m="+m+"
""+m+""

Your task is to write the shortest expression surrounded with quotes, such that if we remove the outer quotes, the expression still returns the same string.

Key points:

Your language must support "..." as string literals
The program has to contain at least three characters
You are not allowed to define a context outside of the quotes themselves (as I did for m)
You are not allowed to use other delimiters for strings, e.g. no """, no '.
Both expressions should return strings.
Shortest code wins (counting the quotes themselves)

C  (4 chars)

The expression

""""

satisfies the minimal requirement of three characters. It encodes the empty string, no matter even if you omit one level of quotes:

 ""

If you want the resulting string to be at least three characters, here is an expression of length 10 which results in three characters of string, namely three spaces:

""   "   "
 "   "

If you don't like spaces either, here are four printable characters in a length 12 expression:

""/**/"/**/"
 "/**/"/**/

Putting these expressions into a small program:

#include <stdio.h>
#define CASE(s) printf("'%s'\n", s)
int main() {
  CASE("""");
  CASE("");
  CASE(""   "   ");
  CASE("   "   );
  CASE(""/**/"/**/");
  CASE("/**/"/**/);
}

Output:

''
''
'   '
'   '
'/**/'
'/**/'


Create every combination of variable groups up to order n SPECIFICATION

Given m variables, create every combination up to order n. For example,

The output of mapping two variables (a and b) to order 1 would be:

a
b
a b

The output of mapping two variables (a and b) to order 2 would be:

a
a2
b
b2
a b
a2 b
a b2
a2 b2

The output of mapping two variables (a and b) to order 3 would be:

a
a2
a3
b
b2
b3
a b
a2 b
a3 b
a3 b2
a b2
a b3
a2 b3
a2 b2
a3 b3

The output of mapping three variables (a, b, and c) to order 1 would be:

a
b
c
a b
b c
a c
a b c

The output of mapping m variables to order n would be:

etc.

WINNING CRITERIA

Output every possible combination as outlined above. Order does not matter. Where in your code you print to the screen does not matter. All that matters is that what shows up in your output is correct.

LATEX, 354 bytes

When I saw this I knew it had to be done in Latex.  Equations just look so crisp and clean in Latex and I can't stand using ^ for power.

\documentclass{article}\input tikz\usepackage{intcalc}\usepackage{ifthen}\begin{document}\typein[\a]{}\typein[\b]{}\foreach\x in{1,...,\intcalcPow{\b+1}{\a}}{\begin{equation}\foreach[count=\i]\y in{a,...,z}{\ifthenelse{\(\i<\a\)\OR\(\i=\a\)}{\y^\intcalcDiv{\intcalcMod{\x}{\intcalcPow{\b+1}{\i}}}{\intcalcPow{\b+1}{\i-1}}}{}}\end{equation}}\end{document}

Explanation

There are three main forces at work here \typein  which is what allows us to take input from the command line, the intcalc package which is what allows us to make calculations with our variables, and the Latexequation environment.

Once we have taken in input we begin a loop we loop \intcalcPow{\b+1}{\a} times, once for each result we want to print.  Each loop we begin an equation environment and loop through the alphabet keeping track of \y for the current letter and \i for the current number of runs.  If \i is greater than or equal to \a we don't print anything at all (according to the specs this is not strictly necessary however Latex will overflow for values greater than 1 if we don't do this).  We then print \y to our equation and raise it to the power of

\intcalcDiv{\intcalcMod{\x}{\intcalcPow{\b+1}{\i}}}{\intcalcPow{\b+1}{\i-1}}

That whole mess simply means take the \ith digit of \x in base \b+1.  This ensures that the powers are decoded properly.

Example output:

Here is the output for 3, 2


Convert Salesforce 15-character ID to 18-character In Salesforce CRM, every object has 15-character alphanumeric ID, which is case-sensitive. If anyone's curious, actually it's base-62 number.
However, tools used for data migration and integration may or may not support case sensitivity. To overcome that, IDs can be safely converted to 18-character case-insensitive alphanumeric IDs. In that process 3-character alphanumeric checksum is appended to the ID. The conversion algorithm is:

Example:

a0RE000000IJmcN

Split ID into three 5-character chunks.

a0RE0  00000  IJmcN

Reverse each chunk.

0ER0a  00000  NcmJI

Replace each character in every chunk by 1 if it's uppercase or by 0 if otherwise.

01100  00000  10011

For each 5-digit binary number i, get character at position i in concatenation of uppercase alphabet and digits 0-5 (ABCDEFGHIJKLMNOPQRSTUVWXYZ012345).

00000 -> A,
00001 -> B,
00010 -> C, ...,
11010 -> Z,
11011 -> 0, ...,
11111 -> 5`

Yielding:

M  A  T

Append these characters, the checksum, to the original ID.

Output:

a0RE000000IJmcNMAT

Write program or function which takes 15-character alphanumeric (ASCII) string as input and returns 18-character ID.

Input validation is out of scope of this question. Programs may return any value or crash on invalid input.

Please, don't use Salesforce propretiary languages' features that make this challenge trivial (such as formula CASESAFEID(), converting Id to String in APEX &c).

Test Cases

a01M00000062mPg    -> a01M00000062mPgIAI
001M000000qfPyS    -> 001M000000qfPySIAU
a0FE000000D6r3F    -> a0FE000000D6r3FMAR
0F9E000000092w2    -> 0F9E000000092w2KAA
aaaaaaaaaaaaaaa    -> aaaaaaaaaaaaaaaAAA
AbCdEfGhIjKlMnO    -> AbCdEfGhIjKlMnOVKV
aBcDEfgHIJKLMNO    -> aBcDEfgHIJKLMNO025

Pyth, 23 22 bytes
1 byte saved by FryAmTheEggman.
sm@s+JrG1U6i}RJ_d2c3pz

Try it online. Test suite.
This might be the first time I've used the print instruction in golfing.
Explanation
     JrG1                   save uppercase alphabet in J
                     z      input string
                    p       print it without newline
                  c3        split into 3 parts
 m              d           for each part:
               _              reverse
            }R                map characters to being in
              J                 uppercase alphabet (saved in J)
           i     2            parse list of bools as binary
  @                           get correct item of
     J                          uppercase alphabet (saved in J)
   s+    U6                     add nums 0-5 to it
s                           concatenate and print


Partition a map of water flows This is a challenge on the internet asked by Palantir Technologies in their interviews.

  A group of farmers has some elevation data, and we’re going to help
  them understand how rainfall flows over their farmland.  We’ll
  represent the land as a two-dimensional array of altitudes and use the
  following model, based on the idea that water flows downhill:

  If a cell’s four neighboring cells all have higher altitudes, we call
  this cell a sink; water collects in sinks.  Otherwise, water will flow
  to the neighboring cell with the lowest altitude. If a cell is not a
  sink, you may assume it has a unique lowest neighbor and that this
  neighbor will be lower than the cell.

  Cells that drain into the same sink – directly or indirectly – are
  said to be part of the same basin.

  Your challenge is to partition the map into basins. In particular,
  given a map of elevations, your code should partition the map into
  basins and output the sizes of the basins, in descending order.

  Assume the elevation maps are square. Input will begin with a line
  with one integer, S, the height (and width) of the map. The next S
  lines will each contain a row of the map, each with S integers – the
  elevations of the S cells in the row. Some farmers have small land
  plots such as the examples below, while some have larger plots.
  However, in no case will a farmer have a plot of land larger than S =
  5000.

  Your code should output a space-separated list of the basin sizes, in
  descending order. (Trailing spaces are ignored.)

  A few examples are below.

  Input:

3
1 5 2
2 4 7
3 6 9

  Output:  7 2

  The basins, labeled with A’s and B’s, are:

A A B
A A B
A A A

  Input:

1
10

  Output:  1

  There is only one basin in this case.

  Input:

5
1 0 2 5 8
2 3 4 7 9
3 5 7 8 9
1 2 5 4 2
3 3 5 2 1

  Output:  11 7 7

  The basins, labeled with A’s, B’s, and C’s, are:

A A A A A
A A A A A
B B A C C
B B B C C
B B C C C

  Input:

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

  Output:  7 5 4

  The basins, labeled with A’s, B’s, and C’s, are:

A A B B
A B B B
A B B C
A C C C

Mathematica

The basin size list can be gotten by

WatershedComponents[
 Image[Rest@ImportString[m,"Table"]] // ImageAdjust,
 CornerNeighbors -> False,
 Method -> "Basins"
 ] // Reverse@Sort@Part[Tally[Flatten@#], All, 2] &

where m is the given input data. To display a matrix like the ones in the question one can replace // Reverse@Sort@Part[Tally[Flatten@#], All, 2] & with /. {1 -> "A", 2 -> "B", 3 -> "C"} // MatrixForm or one can display it as an image instead using //ImageAdjust//Image.


Draw the Devil's Staircase The Devil's Staircase is a fractal-like function related to the Cantor set.

Your task is to replicate this funky function — in ASCII art!

Input

A single integer n >= 0, indicating the size of the output. Input may be given via STDIN, function argument or command-line argument.

Output

The ASCII-art rendition of the Devil's staircase at size n, either returned as a string or printed to STDOUT. Trailing spaces at the end of each row are okay, but leading spaces are not. You may optionally print a single trailing newline.

For size 0, the output is just:

x

(If you wish, you may use any other printable ASCII character other than space, in place of x.)

For size n > 0, we:

Take the output of size n-1 and stretch each row by a factor of three
Riffle between rows of single xs
Shift the rows rightward so that there is exactly one x in each column, and the position of the first x are minimal while decreasing with the rows

For example, the output for n = 1 is:

    x
 xxx
x

To get the output for n = 2, we stretch each row by a factor of three:

            xxx
   xxxxxxxxx
xxx

Riffle between rows of single x's:

x
            xxx
x
   xxxxxxxxx
x
xxx
x

Shift rightward:

                  x
               xxx
              x
     xxxxxxxxx
    x
 xxx
x

As another example, here is n = 3.

Scoring

This is code-golf, so the solution in the fewest bytes wins.

J (73 68 58 41 39 38 35 34 characters)

After thinking about the problem for some time, I found an entirely different way to generate the Devil's Staircase pattern. The old answer including its explanation has been removed, you can look into the revisions of this answer to figure out how it was.

This answer returns an array of blanks and sharps, representing the devil's staircase.

' #'{~1(]|.@=@#~[:,3^q:)2}.@i.@^>:

Here is the answer split into its two parts in explicit notation:

f =: 3 : '|. = (, 3 ^ 1 q: y) # y'
g =: 3 : '(f }. i. 2 ^ >: y) { '' #'''

Explanation

The approach is a bit different, so observe and be amazed.

>: 3 – three incremented, that is,

4

2 ^ >: 3 – two to the power of three incremented, that is,

16

i. 2 ^ >: 3 – the first 2 ^ >: 3 integers, that is,

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

}. i. 2 ^ 4 – the first 2 ^ >: 3 integers, beheaded, that is,

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

Let's call this sequence s; we enter f now.
1 q: s – the exponents of 2 in the prime decomposition of each item of s. In general, x q: y yields a table of the exponents for the first x primes in the prime decomposition of y. This yields:

0
1
0
2
0
1
0
3
0
1
0
2
0
1
0

3 ^ 1 q: s – three to the power of these exponents, that is,

 1
 3
 1
 9
 1
 3
 1
27
 1
 3
 1
 9
 1
 3
 1

, 3 ^ 1 q: s – the ravel (that is, the argument with it's structure collapsed into a vector) of the previous result. This is needed because q: introduces an unwanted trailing axis. This yields

 1 3 1 9 1 3 1 27 1 3 1 9 1 3 1

(, 3 ^ 1 q: s) # s – each item of s replicated as often as the corresponding item in the previous result, that is,

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

= (, 3 ^ 1 q: s) # s – the self classification of the previous result, this is, a matrix where each row represents one of the unique items of the argument, each column represents the corresponding item of the argument and each cell represents whether the items of row and column are equal, that is,

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

|. = (, 3 ^ 1 q: s) # s – the previous result flipped along the vertical axis.
(|. = (, 3 ^ 1 q: s) # s) { ' #' – the items of the previous result used as indices into the array ' #', so 0 is replaced by   and 1 is replaced by #, that is,

                                                                #
                                                             ###
                                                            #
                                                   #########
                                                  #
                                               ###
                                              #
                   ###########################
                  #
               ###
              #
     #########
    #
 ###
#

the result we want.


All the k-mers/n-grams Intro
We have had histograms and counting, but not listing all of them.
Every year, Dyalog Ltd. holds a student competition. The challenge there is to write good APL code. This is a language agnostic code-golf edition of this year's sixth problem.
I have explicit permission to post this challenge here from the original author of the competition. Feel free to verify by following the provided link and contacting the author.
Problem
The term k-mer typically refers to all the possible substrings of length k that are contained in a string. In computational genomics, k-mers refer to all the possible subsequences (of length k) from a read obtained through DNA Sequencing. Write a function/program that takes a string and k (the substring
length) and returns/outputs a vector of the k-mers of the original string.
Examples
[4,"ATCGAAGGTCGT"] → ["ATCG","TCGA","CGAA","GAAG","AAGG","AGGT","GGTC","GTCG","TCGT"]
k > string length? Return nothing/any empty result:
[4,"AC"] → [] or "" or [""]

Jelly, 1 byte

ṡ

Jelly has a single byte dyadic atom for this very operation

Try it online! (the footer splits the resulting list with newlines, to avoid a mushed representation being printed.)


Where is that snake going? Write a function (using as few bytes as possible) that takes a bi-dimensional array of any number of columns and rows in which:

0 represents empty block,
1 represents snake block.

The function must return the number of possible paths the snake traveled.

Example 1:

Input:

[
  [1,1,1,1,1],
  [0,0,0,0,1],
  [0,0,0,0,1],
]

Output: 2

In the example above, the function will return 2 because the answer is either one of:

Example 2:

Input:

[
  [1,1,1,1],
  [0,0,1,1],
  [0,0,1,1],
]

Output: 6

In this example the function will return 6 because the answer is either one of:

Note:

When assessing the input, you can assume that:

The arrays representing columns will always have the same sizes (so the arrays are rectangular);
There exists at least 1 valid path;
The snake cannot walk through the edges (as can happen in some versions of snake);
The snake will always have at least 2 blocks;
The snake cannot move diagonally;
The paths are directed. (so, two paths ending at different positions but otherwise looking exactly the same are not the same path, it’ll add up to the total)

Wolfram Language (Mathematica), 16+83=99 bytes

Library import statement (16 bytes):

<<Combinatorica`

Actual function body (83 bytes):

Length@HamiltonianCycle[MakeGraph[#~Position~1~Join~{1>0},##||Norm[#-#2]==1&],All]&

Try it online!

Note that the question just ask for the number of Hamiltonian path in the graph.

However, (for some reason) the HamiltonianPath function doesn't really work with directed graph (example). So, I used the workaround described in this Mathematica.SE question:

Add an vertex (called True) that is connected to all other vertices.
Count the number of Hamiltonian cycle on the resulting graph.

The graph is constructed using MakeGraph (annoyingly there are no directly equivalent built-in), using the boolean function ##||Norm[#-#2]==1&, which returns True if and only if one of the arguments is True or the distance between the two vertices are 1.

Tr[1^x] cannot be used instead of Length@x, and <2 cannot be used instead of ==1.

HamiltonianPath can be used if the graph is undirected, with the function body takes 84 bytes (exactly 1 byte more than the current submission):

Length@HamiltonianPath[MakeGraph[#~Position~1,Norm[#-#2]==1&,Type->Undirected],All]&

Try it online!


Roll to see all sides! Let's say you have a 20-sided die. You start rolling that die and have to roll it a few dozen times before  you finally roll all 20 values. You wonder, how many rolls do I need before I get a 50% chance of seeing all 20 values? And how many rolls of an n-sided die do I need to roll before I roll all n sides?

After some research, you find out that a formula exists for calculating the chance of rolling all n values after r rolls.

P(r, n) = n! * S(r, n) / n**r

where S(a, b) denotes Stirling numbers of the second kind, the number of ways to partition a set of n objects (each roll) into k non-empty subsets (each side).

You also find the OEIS sequence, which we'll call R(n), that corresponds to the smallest r where P(r, n) is at least 50%. The challenge is to calculate the nth term of this sequence as fast as possible.

The challenge

Given an n, find the smallest r where P(r, n) is greater than or equal to 0.5 or 50%.
Your code should theoretically handle any non-negative integer n as input, but we will only be testing your code in the range of 1 <= n <= 1000000.
For scoring, we will be take the total time required to run R(n) on inputs 1 through 10000.
We will check if your solutions are correct by running our version of R(n) on your output to see if P(your_output, n) >= 0.5 and P(your_output - 1, n) < 0.5, i.e. that your output is actually the smallest r for a given n.
You may use any definition for S(a, b) in your solution. Wikipedia has several definitions that may be helpful here.
You may use built-ins in your solutions, including those that calculate S(a, b), or even those that calculate P(r, n) directly.
You can hardcode up to 1000 values of R(n) and a million Stirling numbers, though neither of these are hard limits, and can be changed if you can make a convincing argument for raising or lowering them.
You don't need to check every possible r between n and the r we're looking for, but you do need to find the smallest r and not just any r where P(r, n) >= 0.5.
Your program must use a language that is freely runnable on Windows 10.

The specifications of the computer that will test your solutions are i7 4790k, 8 GB RAM. Thanks to @DJMcMayhem for providing his computer for the testing. Feel free to add your own unofficial timing for reference, but the official timing will be provided later once DJ can test it.

Test cases

n       R(n)
1       1
2       2
3       5
4       7
5       10
6       13
20      67       # our 20-sided die
52      225      # how many cards from a huge uniformly random pile until we get a full deck
100     497
366     2294     # number of people for to get 366 distinct birthdays
1000    7274
2000    15934
5000    44418
10000   95768
100000  1187943
1000000 14182022

Let me know if you have any questions or suggestions. Good luck and good optimizing!

Python + NumPy, 3.95 Seconds

from __future__ import division
import numpy as np

def rolls(n):
    if n == 1:
        return 1
    r = n * (np.log(n) - np.log(np.log(2)))
    x = np.log1p(np.arange(n) / -n)
    cx = x.cumsum()
    y = cx[:-1] + cx[-2::-1] - cx[-1]
    while True:
        r0 = np.round(r)
        z = np.exp(y + r0 * x[1:])
        z[::2] *= -1
        r = r0 - (z.sum() + 0.5) / z.dot(x[1:])
        if abs(r - r0) < 0.75:
            return np.ceil(r).astype(int)

for n in [1, 2, 3, 4, 5, 6, 20, 52, 100, 366, 1000, 2000, 5000, 10000, 100000, 1000000]:
    print('R({}) = {}'.format(n, rolls(n)))

import timeit
print('Benchmark: {:.2f}s'.format(timeit.timeit(lambda: sum(map(rolls, range(1, 10001))), number=1)))

Try it online!

How it works

This uses the closed-form series for P(r, n), and its derivative with respect to r, rearranged for numerical stability and vectorization, to do a Newton’s method search for r such that P(r, n) = 0.5, rounding r to an integer before each step, until the step moves r by less than 3/4.  With a good initial guess, this usually takes just one or two iterations.

xi = log(1 − i/n) = log((n − i)/n)
cxi = log(n!/((n − i − 1)! ⋅ ni + 1)
yi = cxi + cxn − i − 2 − cxn − 1 = log binom(n, i + 1)
zi = (-1)i + 1 ⋅ binom(n, i + 1) ⋅ ((n − i − 1)/n)r
1 + ∑zi = n! ⋅ S(r, n)/nr = P(r, n)
zi ⋅ xi + 1 = (-1)i + 1 ⋅ binom(n, i + 1) ⋅ ((n − i − 1)/n)r log((n − i − 1)/n)
∑zi ⋅ xi + 1 = d/dr P(r, n)


Randomised list, formatted nicely Challenge
Task
Given a number N, output 2 NxN squares; each line of each square is a random permutation of [0, N); the squares are separated by a newline
Rules

Produce a randomised list of length N, separated by space
Repeat this N*2 times
Separate each output with a newline, with 2 newlines at the midpoint
The value of n must be "obvious", you can get it via stdin; argument; whatever, but there must be a distinct value somewhere, so the value of n can't just be scattered across your program.

Example
Given n = 4, the output could be:
1 2 0 3
2 3 1 0
2 0 3 1
2 0 3 1

0 3 2 1
3 1 0 2
0 1 3 2
0 2 1 3

Lowest number of bytes wins

J, 9 7 bytes

Thanks to @randomra for shaving off two characters:

?~2&,]

Previously I had:

?~($~2&,)

These are functions, you can apply them to an argument directly or store them in a variable and then use them:

   (?~2&,$]) 5
1 0 4 2 3
2 4 0 3 1
2 3 1 0 4
2 3 0 1 4
3 0 1 4 2

1 4 0 2 3
2 1 4 3 0
2 3 1 0 4
2 3 1 4 0
0 1 2 3 4

   f=.?~2&,$]
   f 5
4 2 3 0 1
3 4 1 0 2
3 4 0 2 1
1 2 4 3 0
2 0 4 1 3

2 1 3 0 4
1 3 4 2 0
2 4 1 3 0
3 2 1 0 4
3 0 4 2 1


Most Common Multiple Not to be confused with Least Common Multiple.
Given a list of positive integers with more than one element, return the most common product of two elements in the array.
For example, the MCM of the list [2,3,4,5,6] is 12, as a table of products is:
    2  3  4  5  6
  ---------------
2 | #  6  8  10 12
3 | #  #  12 15 18
4 | #  #  #  20 24
5 | #  #  #  #  30
6 | #  #  #  #  #

Thanks DJMcMayhem for the table
As 12 appears the most times (two times as 2*6 and 3*4). Note that we aren't including the product of an element and itself, so 2*2 or 4*4 do not not appear in this list. However, identical elements will still be multiplied, so the table for [2,3,3] looks like:
    2  3  3
  ----------
2 | #  6  6
3 | #  #  9
3 | #  #  #

With the MCM being 6.
In the event of a tie, you may return any of the tied elements, or a list of all of them.

This is code-golf, so the shortest byte count for each language wins!

Test-cases:
[2,3,4,5,6] -> 12
[7,2] -> 14
[2,3,3] -> 6
[3,3,3] -> 9
[1,1,1,1,2,2] -> 2
[6,200,10,120] -> 1200
[2,3,4,5,6,7,8,8] -> 24
[5,2,9,10,3,4,4,4,7] -> 20
[9,7,10,9,7,8,5,10,1] -> 63, 70, 90 or [63,70,90]

R, 54 50 41 bytes

order(-tabulate(combn(scan(),2,prod)))[1]

Try it online!

Alternatively, for 54 53 44 bytes:

names(sort(-table(combn(scan(),2,prod))))[1]

Try it online!

In principle, the latter version outputs the relevant result even without the names function, but followed by the count of such most frequent products, which isn't asked for...

Thanks to CriminallyVulgar  for -4 and -1, and Giuseppe for -9 on both.


Advent of Code 2020, Day 2, Part 1 Today, my girlfriend and I started with this year's Advent of Code to improve our Python. So far we only did Day 1 and the first part of Day 2. The latter, I found to be very fun, so, to spice it up a little, and with a tip o' the head to Eric Wastl, here's my attempt at turning it into a Code Golf challenge.
Task
Your task, should you accept it, would be to determine the number of lines where the number of occurrences of char in each string is at least min and at most max. With the above data, a valid entry will output 23¹.
Valid entries shall not only work with the below two example data sets, but with any data set produced by the Advent of Code website's Day 2 Part 1 puzzle (so head on over there already - but just going with the examples is fine, too). Other formats of input are not allowed. Specifically, the entry has to handle the newlines itself.
I've posted an answer with my Ruby version along with this Question in the hopes that it will help.
Input

A multiline string where each line/element contains a number min, a number max, a character char, and a string password² (i.e., min-max char: password).
min and max are positive integers, and max is guaranteed to be greater than or equal to min.
As far as I can tell, the passwords are all ASCII-alphabetical, as is the char.

Output

A number representing how many lines had at least min and at most max occurrences of char in password.

Scoring

The winner shall be the shortest entry by characters³, not bytes (to make sure that variable names such as ,  and  don't put contestants in the mood of the season at a disadvantage).

(Shorter) Test Case
Output: 3
Input:
1-5 c: abcdefg
5-12 j: abcdefg
1-5 z: zzzzzzzz
3-3 h: hahaha
4-20 e: egejeqwee

(Longer) Example
Output: 23
Input:
3-8 j: ksjjtvnjbjppjjjl
6-10 s: sszlkrsssss
1-4 z: znzfpz
7-11 m: dfkcbxmxmnmmtvmtdn
6-9 h: hlhhkhhhq
8-9 p: ppppppppvp
6-9 c: cccgccccmcch
5-8 g: bgkggjgtvggn
3-4 x: xxhk
10-12 h: hhhhhhhhhlhhhhdnh
5-6 j: zjjsjn
9-14 s: ksclwttsmpjtds
6-7 l: gtdcblql
1-4 d: dkndjkcd
1-6 k: kkkkkckmc
10-12 x: xxxxxxxxxrxl
2-5 v: fxdjtv
3-5 q: pjmkqdmqnzqppr
5-8 t: xtgtgtcht
6-11 j: nftjzjmfljqjrc
6-9 g: rskgggmgmwjggggvgb
11-12 v: vkvdmvdvvvdv
15-16 z: zzzzzzzzzzzzzzgxz
13-17 v: vvvvvvvvvvvvvvvvnv
9-14 j: clrfkrwhjtvzvqqj
1-12 l: lljljznslllffhblz
4-7 c: cccgcxclc
6-11 z: tbxqrzzbwbr
18-19 m: jmbmmqmshmczlphfgmf
1-5 s: ssvsq
4-5 k: kkkkw
4-7 f: fcqffxff
3-8 f: fffzthzf
9-12 v: vvvvvvvvvvvmvv
14-17 f: ftflcfffjtjrvfkffmvf
4-7 n: pnmnxnqqjp
6-7 r: rrrkrmr
4-13 k: drckdzxrsmzrkqckn
5-14 t: dttttttttttttt
13-14 v: vvvvfvvvvvvvvvv
7-12 j: jrljwnctjqjjxj
6-7 v: wchfzvm
1-8 d: dddddddzd
10-12 g: gvvzrglgrgggggggggg

¹: But, say puts 23 (that is, without doing the actual work) is no valid entry.
²: On Advent of Code, the background to the puzzle is that you're helping a toboggan rental company with their computer trouble. For some reason, their password database has been jumbled up and you're trying to fix it, which requires you to figure out which passwords adhere to the password policy, which solely consists of a specific character (char) to be present at least and at most a certain number of times.
³: As determined via wc -m.

Ruby, 56 characters
eval'㵰␼⹣潵湴筼汼氽縯層⬠⠮⤯㬨①⹴潟椮⸤☮瑯彩⤽㴽␧⹣潵湴⠤ㄩ紻'.encode('utf-16').b

Try it online!
Decompresses to:
p$<.count{|l|l=~/\d+ (.)/;($`.to_i..$&.to_i)===$'.count($1)}

Character scoring allows these sort of shenanigans!
This is also a great showcase of Ruby's regex global variables. Given a line:
3-8 j: ksjjtvnjbjppjjjl

Our regex matches here:
3-8 j: ksjjtvnjbjppjjjl
  \-/
  Regex matches here

Then $' is the part after the regex, $& is the part that matches the regex, $` is the part before the regex, and $1 matches the character to count, so we have:
$` = '3-'
$& = '8 j'
$1 = 'j'
$' = ': ksjjtvnjbjppjjjl'

Since Ruby's to_i just ignores garbage after a numeric string, we can just cast it to int.
Ruby -n, 60 characters
~/\d+ (.)/;($`.to_i..$&.to_i)===$'.count($1)||$.-=1
END{p$.}

Try it online!


Battle of the letters Your task is simple: tell me who wins the battle of the letters.

The troops

There are three different "troops" in this battle, summarized by this table.

name | health | damage
   A       25       25
   B      100        5
   C       10       50

You may use any three unique characters to represent the the troops, but must specify if they are not these letters.

The battle

Suppose we have a sample battle:

ABC # army 1
CBA # army 2

Each army repeatedly fires at the leftmost unit, until it is dead; then they move to the troop to the right and repeat. So army 2 attacks A in army 1 until A is dead, then move to B, then C. Army 1 attacks C first, then B, then A. Assume the armies attack at the same time, and thus troops will always fire if they were alive before the round and can kill each other at the same time. They fire in order from left to right.

The battle would play out as so:

ABC
CBA

BC # A (25 hp) killed by C (-50 hp), B (100 hp) attacked by B (-5 hp) and A (-25 hp), has 70 hp
BA # C (10 hp) killed by A (-25 hp), B (100 hp) attacked by B (-5 hp) and C (-50 hp), has 45 hp

BC # B (70 hp) attacked by B (-5 hp) and A (-25 hp), has 40 hp
A  # B (45 hp) killed by B (-5 hp) and C (-50 hp)

BC # B (40 hp) attacked by A (-25 hp), has 15 health
   # A (25 hp) killed by B (-5 hp) and C (-50 hp), army 2 dead

Therefore, army 1 wins the battle!

Input

Two strings, the first representing army 1 and the second army 2. They are not necessarily the same size (because who said it would be a fair fight?)

Output

Any three unique, constant values to represent army 1 winning, army 2 winning, or the unlikely event of a tie. Yes, it is possible for the last troops to kill each other, ending in a tie.

Battles

ABC
CBA
Army 1

CCCCC
CCCCC
Tie

CABCAB
ABBABBA
Army 2

Standard loopholes apply. You must submit a full program.

This is code-golf, shortest solution wins.

Pyth 145 97 bytes

=Y.d[,\A,25 25,\B,*TT5,\C,T*5T)Km=G@YdzJm=H@YdwW&KJMX0hG_smedH gKJ gJKI<hhK0=tK)I<hhJ0=tJ;?K1?J2Z

A little less naive than before.

Try it online!

Explanations:

Let's cut the program in several parts.

=Y.d[,\A,25 25,\B,*TT5,\C,T*5T)

     ,\A,25 25                     Create this list: ['A', [25, 25]]
              ,\B,*TT5             Create this list: ['B', [100, 5]]
                      ,\C,T*5T     Create this list: ['C', [10, 50]]
  .d[                         )    From the three lists, create a dictionary whose keys are the letters, and values are the inner lists
=Y                                 Assign to the variable Y

The dictionary Y is: {'A': [25, 25], 'C': [10, 50], 'B': [100, 5]}. Then:

Km=G@YdzJm=H@YdwMX0hG_smedH

 m=G@Ydz                           For all letters in first input string, make a copy of Y[letter]. Make a list of all those values...
K                                  ...and assign the list to the variable K
         m=H@Ydw                   For all letters in second input string, make a copy of Y[letter]. Make a list of all those values...
        J                          ...and assign the list to the variable J
                MX0hG_smedH        Create a function g which takes two lists of couples, and subtract the sum of the second elements of the couples of the second list from the first element of the first couple of the first list

At this point, K is a list of couples that represents the first army. Each couple of this list is a letter of the army, and is (health, damage) for that letter. J is exactly the same, but for the second army. g is a function which takes two armies, and deals the damage made by the second army to the first one. Now:

W&KJ gKJ gJKI<hhK0=tK)I<hhJ0=tJ;

W&KJ                               While K not empty and J not empty
     gKJ                           Call g(K,J). That computes the damages to first army
         gJK                       Call g(J,K). That computes the damages to second army
            I<hhK0=tK)             If the first army's first letter is dead, remove it
                      I<hhJ0=tJ    If the second army's first letter is dead, remove it
                               ;   End of while loop

When the while loop is over, K and J have their final value. If they are both empty, it's a tie; otherwise the non-empty army win. That is handled by the last piece of code:

?K1?J2Z

?K1                                If K non-empty, display 1. Else...
   ?J2                             ...if J non-empty, display 2. Else...
      Z                            ...display zero

That's it!


How can I golf this JavaScript code, if at all? I have some JavaScript code in a <script> HTML tag I'd like to golf, while still remaining in the tag. How can I golf that code, if at all? Here's the code:

&ltscript&gtdocument.write`&ltfont color=#40e0d0 face=arial&gtYOU ARE IN THE BEDROOM.&ltbr&gtYOU SEE CRAB NICHOLSON.&ltbr&gtHE HAS NO MITTENS.&ltbr&gtHIS CLAWS ARE MENACING.&ltbr&gtOBVIOUS EXITS ARE:&ltbr&gtBATHROOM, KITCHEN, LIVING ROOM&ltbr&gtAND CRAB NICHOLSON'S&ltbr&gtULTIMATE LAIR OF AWESOMENESS&lt/font&gt`;document.body.style.background="#000"&lt/script&gt

Save 3 bytes by assigning document to a variable:

(d=document).write`YOU ARE IN THE BEDROOM.
YOU SEE CRAB NICHOLSON.
HE HAS NO MITTENS.
HIS CLAWS ARE MENACING.
OBVIOUS EXITS ARE:
BATHROOM, KITCHEN, LIVING ROOM
AND CRAB NICHOLSON'S
ULTIMATE LAIR OF AWESOMENESS`;d.body.style.background="#000"

Save 2 bytes by reusing ' CRAB NICHOLSON':

(d=document).write(`YOU ARE IN THE BEDROOM.
YOU SEE${c=' CRAB NICHOLSON'}.
HE HAS NO MITTENS.
HIS CLAWS ARE MENACING.
OBVIOUS EXITS ARE:
BATHROOM, KITCHEN, LIVING ROOM
AND${c}'S
ULTIMATE LAIR OF AWESOMENESS`);d.body.style.background="#000"

Save 1 byte by using .join`<br>`:

(d=document).write(`YOU ARE IN THE BEDROOM._YOU SEE${c=' CRAB NICHOLSON'}._HE HAS NO MITTENS._HIS CLAWS ARE MENACING._OBVIOUS EXITS ARE:_BATHROOM, KITCHEN, LIVING ROOM_AND${c}'S_ULTIMATE LAIR OF AWESOMENESS`.split`_`.join`
`);d.body.style.background="#000"

Further golfs suggested by @Night2:

Save 14 bytes by using .bgColor=0:

(d=document).write(`YOU ARE IN THE BEDROOM._YOU SEE${c=' CRAB NICHOLSON'}._HE HAS NO MITTENS._HIS CLAWS ARE MENACING._OBVIOUS EXITS ARE:_BATHROOM, KITCHEN, LIVING ROOM_AND${c}'S_ULTIMATE LAIR OF AWESOMENESS`.split`_`.join`
`);d.body.bgColor=0

Save 7 bytes by 'forgetting' to close the  tag (YMMV):

(d=document).write(`YOU ARE IN THE BEDROOM._YOU SEE${c=' CRAB NICHOLSON'}._HE HAS NO MITTENS._HIS CLAWS ARE MENACING._OBVIOUS EXITS ARE:_BATHROOM, KITCHEN, LIVING ROOM_AND${c}'S_ULTIMATE LAIR OF AWESOMENESS`.split`_`.join`
`);d.body.bgColor=0


How high can you count? Challenge:

Your task is to write as many programs / functions / snippets as you can, where each one outputs / prints / returns an integer. The first program must output the integer 1, the second one 2 and so on.

You can not reuse any characters between the programs. So, if the first program is: x==x, then you may not use the characters x and = again in any of the other programs. Note: It's allowed to use the same character many times in one program.

Scoring:

The winner will be the submission that counts the highest. In case there's a tie, the winner will be the submission that used the fewest number of bytes in total.

Rules:

You can only use a single language for all integers
Snippets are allowed!
To keep it fair, all characters must be encoded using a single byte in the language you choose.
The output must be in decimal. You may not output it with scientific notation or some other alternative format. Outputting floats is OK, as long as all digits that are shown behind the decimal point are 0. So, 4.000 is accepted. Inaccuracies due to FPA is accepted, as long as it's not shown in the output.
ans =, leading and trailing spaces and newlines etc. are allowed.
You may disregard STDERR, as long as the correct output is returned to STDOUT
You may choose to output the integer to STDERR, but only if STDOUT is empty.
Symbol independent languages (such as Lenguage) are disallowed
Letters are case sensitive a != A.
The programs must be independent
Whitespace can't be reused
You must use ASCII-digits in the output

Explanations are encouraged!

JavaScript (ES7), score 17, 176 bytes

They said it couldn't be done, so I did it :D (thanks to a lot of help from @FullDecent)

""**""
~(~/~//~/~/)/~/~/
3
4
!NaN- -!NaN- -!NaN- -!NaN- -!NaN
6
7
8
9
++[[]][+[]]+[+[]]
11
'lengthlength'.length
222>>2>>2
`${``^``}xE`^``
0XF
C=CSS==CSS;C<<C<<C<<C<<C
555555555555555555555%55

Unused characters:

#&,:?@ABDGHIJKLMOPQRTUVWYZ\_bcdfijkmopqrsuvwyz|

I don't think 18 is possible, but I said the same thing about 17...

Explanation

JavaScript is a very weakly typed language; if you try to perform a mathematical operation on a non-number value, JS will try its hardest to convert it to a number first. This allows for a lot of interesting solutions. I've tried to avoid using the digits as much as possible so they can be used later on.

** is the exponentiation operator in ES7. The empty string when coerced to a number becomes 0, so this calculates 0 ** 0, which is 1 according to JavaScript.
A little ridiculous, but it works. /~/ is a regex literal, and ~/~/ returns -1, so this is ~(-1 / -1) / -1 = ~(1) / -1 = -2 / -1 = 2. (credits to @GOTO0 for the idea)
Simply 3.
Now simply 4.
NaN is falsy, so !NaN is true, which is equivalent to 1. The expression thus becomes 1 - -1 - -1 - -1 - -1 = 1 + 1 + 1 + 1 + 1 = 5.
Simply 6.
Simply 7.
Simply 8.
Simply 9.
This uses a little JSF*** magic. +[] is 0, so [[]][+[]] returns the first element of [[]] (that is, []), and ++ increments this to 1. Then +[+[]] adds the array [0], which is coerced to a string and makes "10".
Simply 11. I originally had used 11&1111 for 3 and 33/3 for 11 until I realized yet again just how dumb I am...
This strategy would work on any number: create a string of length 12 and use .length.
I just messed around with 2s and >s for a while to get this one. I got lucky again: 222 >> 2 is 55, and 55 >> 2 is 13.
This one is rather tricky. The basic idea is to create 14 in hex (0xE), but we need the digit 0 elsewhere. So instead we prepend the result of ``^`` to the string xE; the empty string coerced to a number is 0, so this returns 0 ^ 0 = 0. Then the result is XORed with the empty string, which converts both values to numbers; "0xE" ^ "" is 14.
This is now pretty easy: 0XF is a hexadecimal literal with a value of 15.
The trickiest of all? First we set the variable C to CSS == CSS (that is, true). Then we take the result and perform << C four times, which basically multiplies 1 by 2 ** 4.
JavaScript starts to lose integer precision at 253, which allows 555...555%55 to return a number that's not 0 or 5. I happened to get very lucky while playing around here.

Strategies that would work on many numbers:

-!NaN would work on any number (currently 5), though it gets large very fast.
~/~/ would work on any number (currently 2), though it gets very large very fast.
+[] would work on any number (currently 10), though it's by far easiest on 10 or 11.
.length would work on any number.
`${-``}xE`-`` would work on pretty much any number if you do it right.
C<<C would work on any power of two (currently 16), or any int at all if you included |.


Decomposition of a matrix in \$ SL_2(\mathbb{Z}) \$ Background

The special linear group \$ SL_2(\mathbb{Z}) \$ is a multiplicative group of \$ 2 \times 2 \$ matrices whose elements are integers and determinant is 1.

It is known that every member of \$ SL_2(\mathbb{Z}) \$ is a product of some sequence of the following two matrices \$ S \$ and \$ T \$ (reference pdf):

$$
S=\begin{pmatrix}0 & -1\\1 & 0\end{pmatrix},T=\begin{pmatrix}1 & 1\\0 & 1\end{pmatrix}
$$

Note that \$ S^{-1} \$ and \$ T^{-1} \$ can also be expressed as a product of \$ S \$ and \$ T \$:

$$
S^{-1} = S^3, T^{-1} = S^3 \cdot T \cdot S \cdot T \cdot S
$$

Task

Given a \$ 2 \times 2 \$ integer matrix whose determinant is 1, express it as the product of a sequence of \$ S \$ and \$ T \$.

Note that there are infinitely many possible answers for any valid input. Your code needs to just output one answer for a valid input.

Example algorithm

Here is a sample algorithm to find a decomposition; you may use different algorithms to solve the task.

First, note that

$$
M = \begin{pmatrix} a & b \\ c & d \end{pmatrix} \implies
S^{-1}M = \begin{pmatrix} c & d \\ -a & -b \end{pmatrix},
T^{-1}M = \begin{pmatrix} a-c & b-d \\ c & d \end{pmatrix}
$$

Using these two operations, we can use Euclidean-like algorithm to reduce the given matrix down to \$ I \$, and then construct the chain backwards:

Assume \$ M = \begin{pmatrix} a & b \\ c & d \end{pmatrix} \$.
Left-multiply \$ S^{-1} \$ until both \$ a \$ and \$ c \$ are positive.
Repeat the following until we reach \$ c = 0 \$:

Left-multiply \$ T^{-q} \$ where \$ -c < a - qc \le 0 \$.
Left-multiply \$ S^{-1} \$ (exactly once). Now, \$a\$ and \$c\$ are positive again, and \$c\$ is smaller than the original.

Then the result is \$ \begin{pmatrix} 1 & b \\ 0 & 1 \end{pmatrix} \$, which is simply \$ T^b \$. (If \$ b < 0 \$, we can use \$ (SSSTSTS)^{-b} \$ instead.) Now invert all the left-multiplications to get the representation for the original matrix.

Here is an example for \$ M = \begin{pmatrix}17 & 29\\7 & 12\end{pmatrix} \$.

$$
T^{-3} M = \begin{pmatrix}-4 & -7\\7 & 12\end{pmatrix}
\\ S^{-1} T^{-3} M = \begin{pmatrix}7 & 12\\4 & 7\end{pmatrix}
\\ T^{-2} S^{-1} T^{-3} M = \begin{pmatrix}-1 & -2\\4 & 7\end{pmatrix}
\\ S^{-1} T^{-2} S^{-1} T^{-3} M = \begin{pmatrix}4 & 7\\1 & 2\end{pmatrix}
\\ T^{-4} S^{-1} T^{-2} S^{-1} T^{-3} M = \begin{pmatrix}0 & -1\\1 & 2\end{pmatrix}
\\ S^{-1} T^{-4} S^{-1} T^{-2} S^{-1} T^{-3} M = \begin{pmatrix}1 & 2\\0 & 1\end{pmatrix} = T^2
\\ M = T^3 S T^2 S T^4 S T^2
$$

Input and output

You can take the input matrix in any suitable way, e.g. a matrix, a 4-element vector, two complex numbers, etc. You can assume that the input is always valid, i.e. the four elements are integers and the determinant is 1.

The output is a sequence of two distinct values (or objects) that represent \$ S \$ and \$ T \$ respectively. All of the following are accepted (using an example output \$ STTS \$):

"STTS"  # string
"0110"  # digit string
[0, 1, 1, 0]  # array of 0s and 1s
['S', 'T', 'T', 'S']  # array of characters
[(0,-1,1,0), (1,1,0,1), (1,1,0,1), (0,-1,1,0)]  # array of tuples

Also, by definition of empty product, an empty sequence (e.g. "" or []) is a valid answer when the input is \$ I \$.

Scoring and winning criterion

Standard code-golf rules apply. Shortest code in bytes wins.

Example I/O

Note that every valid input has infinitely many correct answers, so your code's output may differ from the sample outputs shown here.

[[1 0]
 [0 1]] -> empty or SSSS or SSSTSTST or ...

[[0 -1]
 [1  0]] -> S

[[1 10]
 [0  1]] -> TTTTTTTTTT

[[17 29]
 [ 7 12]] -> TTTSTTSTTTTSTT

[[-1  -7]
 [-2 -15]] -> SSTSTTSTSSTTTTSSTTT

JavaScript (ES6), 68 bytes
This is using xnor's method -- but obviously without complex numbers.
Takes the input matrix \$\begin{pmatrix}a&b\\c&d\end{pmatrix}\$ as 4 distinct parameters a,b,c,d.
Returns a string of digits (\$0\$ for \$S\$, \$1\$ for \$T\$).

f=(a,b,c,d)=>b|c|a-1|d-1?a*c>-b*d?1+f(a-c,b-d,c,d):0+f(c,d,-a,-b):''

Try it online!

JavaScript (ES6),  114 110  108 bytes
Takes the input matrix \$\begin{pmatrix}a&b\\c&d\end{pmatrix}\$ as a 4-element vector [a,b,c,d].
Returns a string of digits (\$0\$ for \$S\$, \$1\$ for \$T\$).
Brute forces a solution, which is guaranteed to be as short as possible, except for the identity matrix.

f=(M,i=0)=>(F=(a,b,c,d,s='')=>s[i]?a+[,b,c,d]==M&&s:F(a,a+b,c,c+d,s+1)||F(b,-a,d,-c,s+0))(1,0,0,1)||f(M,i+1)

Try it online!
Commented
f = (                      // f = wrapper function taking:
  M,                       //   M[] = input vector
  i = 0                    //   i   = maximum number of iterations (-1)
) => (                     //
  F = (                    // F is a recursive function taking:
    a, b, c, d,            //   the current matrix as 4 distinct parameters
    s = ''                 //   s = output string
  ) =>                     //
    s[i] ?                 // if we've reached the maximum length:
      a + [, b, c, d] == M //   if [a, b, c, d] matches the input matrix:
        && s               //     return s
    :                      // else:
      F(                   //   try a first recursive call
        a,                 //     where the matrix is multiplied by T
        a + b,             //     [ a b ]   [ 1 1 ]   [ a a+b ]
        c,                 //     [ c d ] x [ 0 1 ] = [ c c+d ]
        c + d,             //
        s + 1              //     append '1' to s
      ) ||                 //
      F(                   //   try a second recursive call
        b,                 //     where the matrix is multiplied by S
        -a,                //     [ a b ]   [ 0 -1 ]   [ b -a ]
        d,                 //     [ c d ] x [ 1  0 ] = [ d -c ]
        -c,                //
        s + 0              //     append '0' to s
      )                    //
)(1, 0, 0, 1)              // initial call to F with the identity matrix
|| f(M, i + 1)             // if it fails, try again with i + 1


Derivative at the Edge My preferred way to approximate a derivative is the central difference, its more accurate than forward difference or backward difference, and I'm too lazy to go higher-order. But the central difference requires a data point on either side of point you are evaluating. Normally this means you end up not having a derivative at either endpoint. To solve it, I want you to switch to forward and backward difference at the edges:

Specifically, I want you to use a forward difference for the first point, a backward difference for the last point, and a central difference for all the points in the middle. Also, you can assume x values are evenly spaced, and focus only on y. Use these formulas:

Good luck, I'm looking forward to seeing if someone comes up with a simple rule which reproduces all 3 derivatives in the right places!

EX INPUT:

0.034  9.62    8.885   3.477   2.38

I will use FD, CD, and BD to denote which algorithm to use in which spot, so above 5 points are used to approximate derivatives using

FD     CD      CD      CD     BD

And then the calculated values would be:

9.586  4.4255 -3.0715 -3.2525 -1.097

You can assume that there will always be at least 3 input points, and you can calculate using single or double precision.

And as always, shortest answer wins.

Jelly, 13 10 bytes

I.ịṚjI+2\H

Try it online!

How it works

I.ịṚjI+2\H  Main link. Argument: A (array)

I           Increments; compute the deltas of consecutive values.
            For [a, b, c, d, e], this yields [b-a, c-b, d-c, e-d].
 .ị         At-index 0.5; get the the last and first element.
            This yields [e-d, b-a].
   Ṛ        Reverse the pair.
            This yields [b-a, e-d].
    jI      Join, separating by the increments.
            This yields [b-a, b-a, c-b, d-c, e-d, e-d].
      +2\   Add the values of all overlapping pairs.
            This yields [2(b-a), c-a, d-b, e-c, 2(e-d)].
         H  Halve all resulting numbers.
            This yields [b-a, (c-a)/2, (d-b)/2, (e-c)/2, e-d].


Algebraic curve plotter An algebraic curve is a certain "1D subset" of the "2D-plane" that can be described as set of zeros {(x,y) in R^2 : f(x,y)=0 }of a polynomial f. Here we consider the 2D-plane as the real plane R^2 such that we can easily imagine what such a curve could look like, basically a thing you can draw with a pencil.
Examples:

0 = x^2 + y^2 -1  a circle of radius 1
0 = x^2 + 2y^2 -1  an ellipse
0 = xy  a cross shape, basically the union of the x-axis and the y-axis
0 = y^2 - x  a parabola
0 = y^2 - (x^3 - x + 1) an elliptic curve
0 = x^3 + y^3 - 3xy the folium of Descartes
0 = x^4 - (x^2 - y^2) a lemniscate
0 = (x^2 + y^2)^2 - (x^3 - 3xy^2) a trifolium
0 = (x^2 + y^2 - 1)^3 + 27x^2y^2 an astroid

Task
Given a polynomial f (as defined below), and the x/y-ranges, output an black and white image of at least 100x100 pixels that shows the curve as black line on a white background.
Details
Color: You can use any two other colours of your choice, it should just be easy to tell them apart.
Plot: Instead of a pixel image you can also output this image as ascii-art, where the background "pixels" should be space/underline or an other character that "looks empty" and the line can be made of a character that looks "full" like M or X or #.
You do not have to worry about aliasing.
You only need to plot lines where the sign of the polynomial changes from one side of the line to the other (that means you could e.g. use the marching square algorithm), you do not have to correctly plot "pathological cases like 0 = x^2 where the sign does not change when going from one side of the line to the other. But the line should be continuous and separating the regions of the different signs of f(x,y).
Polynomial: The polynomial is given as a (m+1) x (n+1) matrix/list of lists of (real) coefficients, in the example below the terms of the coefficients are given in their position:
[   1 * 1,   1 * x,   1 * x^2,   1 * x^3,  ... , 1 * x^n ]
[   y * 1,   y * x,   y * x^2,   y * x^4,  ... , y * x^n ]
[   ...  ,   ...   ,   ...   ,    ...   ,  ... ,   ...   ]
[ y^m * 1, y^m * x, y^m * x^2, y^m * x^3 , ..., y^m * x^n]

If you prefer, you can assume the matrix to be square (which can always be done with the necessary zero-padding), and if you want, you can also assume that the size of the matrix is given as aditional inputs.
In the following, the examples from above are represented as a matrix defined like this:
Circle:       Ellipse:      Parabola:  Cross:    Elliptic Curve: e.t.c
[-1, 0, 1]    [-1, 0, 1]    [ 0,-1]    [ 0, 0]   [-1, 1, 0,-1]
[ 0, 0, 0]    [ 0, 0, 0]    [ 0, 0]    [ 0, 1]   [ 0, 0, 0, 0]
[ 1, 0, 0]    [ 2, 0, 0]    [ 1, 0]              [ 1, 0, 0, 0]

Test cases with x-range / y-range:
(In a not so readable but better copy-paste-able format available here on pastebin.)
Circle:
[-1, 0, 1]   [-2,2]   [-2,2]
[ 0, 0, 0]
[ 1, 0, 0]

Ellipse:
[-1, 0, 1]   [-2,2]   [-1,1]
[ 0, 0, 0]
[ 2, 0, 0]

Cross:
[ 0, 0]      [-1,2]   [-2,1]
[ 0, 1]

Parabola:
[ 0,-1]      [-1,3]   [-2,2]
[ 0, 0]
[ 1, 0]

Elliptic Curve:
[-1, 1, 0,-1]    [-2,2]   [-3,3]
[ 0, 0, 0, 0]
[ 1, 0, 0, 0]

Folium of Descartes:
[  0,  0,  0,  1]    [-3,3]   [-3,3]
[  0, -3,  0,  0]
[  0,  0,  0,  0]
[  1,  0,  0,  0]

Lemniscate:
[  0,  0, -1,  0,  1]    [-2,2]   [-1,1]
[  0,  0,  0,  0,  0]
[  1,  0,  0,  0,  0]

Trifolium:
[ 0, 0, 0,-1, 1]    [-1,1]   [-1,1]
[ 0, 0, 0, 0, 0]
[ 0, 3, 2, 0, 0]
[ 0, 0, 0, 0, 0]
[ 1, 0, 0, 0, 0]

Astroid:
[ -1,  0,  3,  0, -3,  0,  1]    [-1,1]   [-1,1]
[  0,  0,  0,  0,  0,  0,  0]
[  3,  0, 21,  0,  3,  0,  0]
[  0,  0,  0,  0,  0,  0,  0]
[ -3,  0,  3,  0,  0,  0,  0]
[  0,  0,  0,  0,  0,  0,  0]
[  1,  0,  0,  0,  0,  0,  0]

I've got the inspiration for some curves from this pdf.

Haskell, 283 275 bytes

The function g should be called with the matrix and the two ranges as arguments. The matrix is just a list of lists, the ranges each a two element list.

import Data.List
t=transpose
u=tail
z=zipWith
l%x=sum$z(*)l$iterate(*x)1                                   --generate powers and multiply with coefficients
e m y x=[l%x|l<-m]%y                                         --evaluate the encoded polynomial
a#b=[a,a+(b-a)/102..b]                                       --create a range
g m[u,w][i,j]=unlines$v[map((0<).e m y)$u#w|y<-i#j]          --evaluate the function on the grid, get the sign
f g=u[u$u$map fst$scanl(\(r,l)c->(c==l,c))(1<0,1<0) l|l<-g]  --find +- or -+ transitions within lines
a&b|a&&b=' '|0<1='#'                                         --helper function for creating the string
v g=z(z(&))(f g)(t$f$t g)                                    --create the string

Here the outputs for the more interesting cases: Note that I had to downsize the resultion from 100x100 to about 40x40 such that it sill fits in the console (just change the hardcoded 102 to a smaller number). Also note that the y-axis is pointing downwards.


Normalise my decision map Write a function or program that processes a block of text and returns the new text. Smallest valid program wins.

Each line in the block of text will have the following format:

12:34,56

The first number is the line ID, the other two comma separated numbers are references to other lines.

In the input text the numbers can be any integer greater than or equal to 0. All numbers will be in ASCII encoded decimal with no leading zeros. There will be no duplicate line IDs. There will be no references to non-existent line IDs, although there may be line IDs that are not referenced.

In the output text the lowest numbered line will be moved to the start of the text block and renumbered to 0. Any references to this line must be updated too. The first reference on that line must be 0 or 1. The second reference can only be 2 if the first reference is 1. Otherwise it must be 0 or 1.

All the lines must be in ascending, incrementing order (no skipped numbers). You can only have a reference to line n if there has been a previous reference to line n-1 or the current line ID is n. There must be no lines that are not referenced by lower line IDs except for line 0. Any such lines must be removed before the final output.

You may assume that the input text is always in the correct format.

Test input #1:

45:73,24
78:24,78
89:24,73
73:45,3
72:3,24
3:24,24
24:3,89

Reordered:

3:24,24
24:3,89
89:24,73
73:45,3
45:73,24
78:24,78
72:3,24

Renumbered:

0:1,1
1:0,2
2:1,3
3:4,0
4:3,1
78:1,78
72:0,1

Unreferenced lines removed for final output:

0:1,1
1:0,2
2:1,3
3:4,0
4:3,1

Of course, your program doesn't have to follow this order, just produce the correct output. The output must be a single block of text or the closest equivalent in your language, i.e. no character by character direct output. You may either return it (preferred) or output the whole block directly. Assume your output will be passed to another function or program.

Test input #2

5:2,3
7:3,2
2:4,2
4:2,3
3:4,3

Output:

0:1,0
1:0,2
2:1,2

Test input #3

7:6,3
3:9,7
9:7,3
2:9,6
6:6,7

Output:

0:1,2
1:3,4
2:2,3
3:2,4
4:1,3

Python 3, 226 215 211 209 179 bytes

def f(s):
 S=dict(map(eval,i.split(":"))for i in s.split("\n"));r="";L=[min(S)];i=0
 while L[i:]:a=S[L[i]];L+=set(a)-set(L);r+="%%d:%d,%d\n"%tuple(map(L.index,a))%i;i+=1
 return r

Try it online!


Write a Rectangular Program that Outputs the Number of Times it was Rotated The title says it all. Your goal is to write a program that forms a w×h rectangle of characters that can be rotated and re-run to output the number of 90° Counter-Clockwise (CCW) rotations that have been done.

For example, if the 3×2 program

abc
def

solved the problem, it would initially output 0, and successive rotations of 90° CCW

cf    fed    da
be    cba    eb
ad           fc

would output 1, 2, and 3 respectively.

Using comments makes this a trivial task is most languages. In Ruby for example, it can be done in a 7×7 rectangle:

###p###
### ###
###1###
p 0#2 p
###3###
### ###
###p###

The challenge is to do this without any sort of comments.

Scoring

Your score is w*h, the area of your rectangle. Newlines are excluded. In other words, code-golf, newlines not counted.

The score for the Ruby example is 49 (though of course it is invalid since it has comments).

Notes

Your code must really be rectangular with no missing characters at the end of lines.
If you wish you may output other legal "mod 90°" values instead of 0 1 2 3. So 8 is fine instead of 0, and -1 is fine instead of 3, etc.
The output may go to the console or into a file.
Standard loopholes apply.

I hope this, my first question, really intrigues some people. Enjoy!

APL (1x3 = 3)

5!3

This solution uses the extra rule that any output that is correct mod 4 works.

In APL, x!y is the number of way to choose x elements from y, commonly known as binom(y,x) or choose(y,x). Let's check that each rotation gives the right answer.

0 rotations

5!3

There's no way to choose 5 elements from 3, so we get 0, which is automatically printed.

1 CCW rotation

3
!
5

APL happily evaluates each line, getting the number 3, the operator !, and then the number 5, printing only the last of these (5), which is 1 mod 4.

2 CCW rotations

3!5

This is binom(5,3), which is (5*4*3*2*1)/(3*2*1)/(2*1) = 10, which is 2 mod 4.

3 CCW rotations

5
!
3

As before, only the last-evaluated value of 3 is printer.

I don't actually know APL, so please tell me if I got any of the explanation wrong. I found it by trial and error as the first language on this site that:

Automatically prints the result of an expression
Given multiple lines of expressions, only outputs the last one
Has no issue with an operator standing alone on a line
Takes operators infix
Has a single-character arithmetic binary operator that is asymmetric (aRb != bRa), and flexible enough to return a variety of numbers.

For (5), I went down the list of APL dyadic functions. My first candidate operation was the integer division / of C and Python 2, but APL division ÷ gives floats. Exponentiation is tempting, but fails because a and a^b have the same parity but are gotten by consecutive rotations (unless b=0, but then b^a=0). Boolean operators like < give 0 and 1 180 degrees apart, which doesn't work. Finally, I found the binomial operator ! and tried numbers until I got some that work.

Thanks to Quincunx for his confidence that there exists a smaller solution than 2x2.


JavaScript (ES6),  128 125  124 bytes
Saved 1 bytes thanks to @OlivierGrégoire
Outputs each version on a separate line. Ordered from highest to lowest major version, and from lowest to highest revision.

f=(r=v=28)=>v?r<parseInt('0111131000244655ah002678b8940'[v],36)?(1+v/10).toFixed(1)+(r|v>22?'.'+r:'')+`
`+f(r+1):f(+!v--):''

Try it online!
How?
The major and minor versions are held in the variable \$v \in [0..27]\$:

major = \$\lfloor v/10+1\rfloor\$
minor = \$v \bmod 10\$

The revision is held in the variable \$r\ge0\$. The maximum value of \$r\$ depends on \$v\$ and is stored in a lookup table encoded in Base-36. Any \$0\$ in this table means that this version was not released at all.
Besides, we use the test \$v>22\$ to know whether the revision should be included even when it's \$0\$ (starting with Python 3.3.0).


Shortest Port Scanner Write the shortest program that will attempt to connect to open ports on a remote computer and check if they are open. (It's called a Port Scanner)

Take input from command line arguments.

your-port-scanner host_ip startPort endPort

Assume, startPort < endPort (and endPort - startPort < 1000)

Output: All the open ports between that range should space or comma seperated.

sh/netcat, 39

nc -vz $1 $2-$3 2>&1|cut -f3 -d\ |xargs

Netcat does the scanning and returns results in this form on standard error:

localhost [127.0.0.1] 22 (ssh) open
localhost [127.0.0.1] 25 (smtp) open

cut and xargs extract the port number and make a single line out of it.

Remind me to shut SMTP down on that node.


Automate your first grade counting exercise CodeGolf Challenge
PWSSHHHH! You wake up in a cryogenics lab in the year 3000. Upon being escorted to the assignment office to receive your career chip, presumably that of a delivery boy, a probe detects that you are from the year 2000. Because of this, and a few stereotypes, you are assumed stupid compared to today's modern human and are forced to repeat gradeschool.
You enter your first grade classroom and the teacher is giving an assignment. She will say or write a number up to 50. If she writes the number on the board (for example: 25) then you have to say the numbers up to that number "one, two, three, ..., twenty-five". If she says the number out loud (for example: "six") then, on your tablet, you have to write the numbers up to that number "1, 2, 3, 4, 5, 6"
This becomes very tedious and you decide you will automate the process with your still functioning, yet archaic, 21st century programming knowledge.

Objective:
Your program should take an input. This input will either be a decimal number (1 thru 50) or a written-out number (one thru fifty).
•If the input is a decimal number, your output should count from one to said number, using written-out style. (e.g. thirty-two)
•If the input is a written-out number, your output should count from 1 to said number, using decimal style. (e.g. 32)

Rules:
Input and Output can be in any case of your choosing (so you can make a program that only accepts upper-case if desired).
Input decimal numbers do not have to be of a number type (e.g. int), they can be a input string containing numbers (25 vs "25"). Either are fine and you can chose which one you want your program to accept. (Your program does not need to accept both)
Written out style does NOT require a hyphen between compound words, but you can if desired.
Output values have to be separated in some form, any separator is fine 1,2,3 1 2 3 etc
You can not add extra libraries like num2words (python) etc (However system libraries are fine)
Even though the back-story says you are from the year 2000, you can use languages created after that date (lol)

This is code-golf, so the program with the shortest bytecount wins!

Perl 6, 119 113 bytes

{my \n=<① ⑳ ㉑ ㉟ ㊱ ㊿>.map:{|map *.uniname.words[2..*].join,$^a..$^b}
/\d/??n[^$_]!!1..1+first $_,n,:k}

Unicode database FTW!

Uses upper-case written-out numbers without hypen, e.g. TWENTYTWO.
Returns a list of strings, or a range of numbers. (Both use space as separator when printed with put.)


Is this a BST pre-order traversal? Background

A binary tree is a rooted tree whose every node has at most two children.

A labelled binary tree is a binary tree whose every node is labelled with a positive integer; moreover, all labels are distinct.

A BST (binary search tree) is a labelled binary tree in which the label of each node is greater than the labels of all the nodes in its left subtree, and smaller than the labels of all the nodes in its right subtree. For instance, the following is a BST:

The pre-order traversal of a labelled binary tree is defined by the following pseudo-code.

function preorder(node)
    if node is null then
        return
    else
        print(node.label)
        preorder(node.left)
        preorder(node.right)

See the following image to get a better intuition:

The vertices of this binary tree are printed in the following order:

F, B, A, D, C, E, G, I, H

You can read more about BSTs here, and more about pre-order traversal here.

Challenge

Given a list of integers \$a\$, your task is to determine whether there is a BST whose pre-order traversal prints exactly \$a\$.

Input

A non-empty list of distinct positive integers \$a\$.
Optionally, the length of \$a\$.

Output

A truthy value if \$a\$ is the pre-order traversal of some BST.
A falsey value otherwise.

Rules

Standard rules for valid submissions, I/O, loopholes apply.
This is code-golf, so shortest solution (in bytes) wins. As usual, don't let ridiculously short solutions in golfy languages discourage you from posting a longer answer in your language of choice.
This is not a rule, but your answer will be better received if it includes a link to test the solution and an explanation of how it works.

Examples

Input                   ---->   Output

[1]                     ---->   True
[1,2,3,4]               ---->   True
[5,1,4,2,3]             ---->   True
[5,4,3,2,1,6,7,8,9]     ---->   True
[4,2,1,3,6,5,7]         ---->   True
[8,3,1,6,4,7,10,14,13]  ---->   True
[2,3,1]                 ---->   False
[6,3,2,4,5,1,8,7,9]     ---->   False
[1,2,3,4,5,7,8,6]       ---->   False
[3,1,4,2]               ---->   False

Check out this link (courtesy of Kevin Cruijssen) to have a visual look at the examples.

JavaScript (Node.js), 49 bytes

a=>!a.some((p,i)=>a.some((q,j)=>q>p&a[j+=j>i]<p))

Try it online!

Using the fact that for array \$a_0 ... a_{n-1}\$, \$a\$ is the pre-order traversal of some BST iff \$ \forall 0\le i<j<n; a_i<a_{j-1} \implies a_i<a_j \$ holds.

Thanks to Arnauld, save 1 byte.


Fermat's Last Theorem, mod n Fermat's Last Theorem, mod n
It is a well known fact that for all integers \$p>2\$, there exist no integers \$x, y, z>0\$ such that \$x^p+y^p=z^p\$. However, this statement is not true in general if we consider the integers modulo \$n\$.
You will be given \$n\$ and \$p\$, which are two positive integers with \$n>1\$. Your task will be to write a function or program to compute all positive integers \$x, y, z<n\$ such that \$(x^p+y^p)\$ and \$z^p\$ give the same remainder when divided by \$n\$.
Input
Any reasonable method of input is allowed. E.g. two separate user inputs, ordered pair, two function parameters, etc.
Output
Any reasonable method of output is valid, it may be produced by a function or output to the screen. The order the triples are listed does not matter. Triples such as (1, 2, 3) and (2, 1, 3) are considered distinct, and all distinct triples should be listed exactly once. No invalid/trivial triples such as (0, 0, 0) should be output.
The numbers \$x, y, z\$ may have any ordering within each of the triples, but that order should be consistent. For example if \$2^p+2^p\$ and \$3^p\$ have the same remainder when divided by \$n\$, you may list this triple as (2, 2, 3) or (3, 2, 2).
Examples
n p -> Possible Output
----------------------------------------------------------------
2 3 -> []
3 3 -> [(1,1,2),(2,2,1)]
3 4 -> []
4 3 -> [(1,2,1),(1,3,2),(2,1,1),(2,2,2),(2,3,3),(3,1,2),(3,2,3)]

Scoring
Shortest code in bytes with no standard loopholes wins.

Julia 1.0, 61 bytes

f(n,p,q=1:n-1)=[(x,y,z) for x=q,y=q,z=q if(x^p+y^p)%n==z^p%n]

-1 thanks to Glen O

Try it online!


A factorization game Input
A single integer \$1 \leq x \leq 10^{15}\$.
Output
The maximum number of distinct positive integers that have the product \$x\$.
Examples
Input: 1099511627776. Output: 9.  One possible optimal list of factors is: (1, 2, 4, 8, 16, 32, 64, 128, 4096).
Input: 127381. Output 4. One possible optimal list of factors is: (1, 17, 59, 127).
Related to this old question.

Wolfram Language (Mathematica), 52 bytes

Max[Length/@Cases[Subsets@Divisors@#,{a__}/;1a==#]]&

Try it online!

4-bytes saved thanks to @attinat

Here is also a 153 bytes version that calculates 1099511627776 and 10^15

Max[Length/@Table[s=RandomSample@Flatten[Table@@@FactorInteger[#]];Last@Select[Times@@@TakeList[s,#]&/@IntegerPartitions@Length@s,DuplicateFreeQ],5!]]+1&

Try it online!

The result for 10^15 is 12

  {1, 2, 4, 5, 10, 16, 25, 40, 50, 100, 125, 250}


Deserialize a binary tree breadth-first Deserializing binary trees depth-first is pretty easy, but doing it breadth-first is (hopefully) harder. Your mission, should you choose to accept it, is to do the latter.
The input will be a 1-D list of positive integers representing node values and some other consistent value representing the absence of a child (I'll use # here). The first element of that list is the root of your tree, the next is the root's left child, then the root's right child, then the left child's left child, then the root's left child's right child, and so on. If a node doesn't have a left or right child, there will be a # instead of a positive number to signify that.
You probably know how to do that already, but here's an example anyways:
Input: [1, 5, 3, #, 4, 10, 2]

First element is root
    Tree                List: [5, 3, #, 4, 10, 2]
      1

Set the root's left child to the next element
    Tree                List: [3, #, 4, 10, 2]
      1
     /
    5

Set the root's right child to the next element
    Tree                List: [#, 4, 10, 2]
      1
     / \
    5   3

That level's filled up, move on to 5's left child.
Since it's '#', there's no left child, so leave that empty.
    Tree                List: [4, 10, 2]
      1
     / \
    5   3
   #

Set 5's right child to 4
    Tree                List: [10, 2]
      1
     / \
    5   3
   # \
      4

Move on to 3's left child
    Tree                List: [2]
       1
     /   \
    5     3
   # \   /
     4  10

Move to 3's right child
    Tree                List: []
      1
     /   \
    5     3
   # \   / \
     4  10  2

List is empty, so we're done.

Input
The input will be a 1-D list or multiple values read from STDIN. It won't be empty, and the first element will always be a positive integer. I used '#' here, but you can use null, 0, or any consistent value that isn't a positive integer (please indicate what you use in your answer). The input may contain duplicate values and the tree it represents isn't necessarily sorted or in any sort of order.
Output
The output can be printed to STDOUT in the shape of a tree (you can make it look however you want as long as it's clear which nodes are connected to which and you don't just print the input back out), or returned from a function as a tree-like structure (the latter is preferred).
You can have each level on a separate line (or separated by some other character(s)), and each node also separated by some character(s) (like in Arnauld's JavaScript answer) OR you could have each child separated by some character, so long as it's clear which node is which node's child (like in Neil's Charcoal answer).
If your language doesn't have a "tree" data type or you can't make a Tree class (or you just don't want to), you could also use a list to represent the tree. Just make sure that it's in an unambiguous format. For example, the tree above could be written as this:
[Value, Left Child, Right Child]

[1,
  [5,
    #, //No left child, so #
    [4, #, #] //or just [4] since both children are absent
  ],
  [3,
    [10, #, #],
    [2, #, #]
  ]
]

Test cases:
Input -> Output
Tree

[1] -> [1, #, #] //or [1], whatever you wish

Tree: 1   //or just 1
     / \
    #   #
([1, #, #] and [1, #] yield the same result as above)

[100, 4, #, 5, #, #] -> [100,[4,[5],#],#]
Tree:    100
        /   \
       4     #
      / \
     5   #
    /
   #

[10, 5, 4, 2, #, 8, 1, 2, 2, 4] -> [10,[5,[2,[2],[2]],#],[4,[8,[4],#],[1]]]
Tree:     10
        /    \
       5      4
      / \    / \
     2   #  8   1
    / \    /
   2   2  4

[100, #, 4, 5, #, #] -> [100, #, [4, [5], #]]
Tree:    100
        /   \
       #     4
            / \
           5   #
          / \
         #   #

Rules

Since this is code-golf, shortest code (in bytes) wins.

100 point bounty for an answer that doesn't use any mutability whatsoever (but please don't just post something you found on StackOverflow).

JavaScript (ES10),  81  80 bytes
Saved 1 byte thanks to @Shaggy
Expects -1 for a non-existing child node. Returns a string where each line contains all the nodes at this depth.

a=>(g=r=>a+a&&(r=r.map(x=>+x||a.shift()||-1))+`
`+g(r.flatMap(x=>[x=-!~x,x])))``

Try it online!


Program that compiles into itself We've had lots of questions about quines, programs where the source code and output are identical. For compiled languages, there are other combinations: we've already had a question about writing a program where the executable and output are identical. But there's one combination left.

The task

Using a compiled language (i.e. a language which has a compiler that converts source code to executables, which are then executed), write a program which, when compiled, will produce an executable which is bit-for-bit identical to the source code.

Clarifications

As with all quine challenges that do not state otherwise, you must obey the site's proper quine rules. In particular, this excludes zero-byte programs, and programs where all the commands compile into themselves.
At least for this challenge, it doesn't matter what the resulting executable does when run; this is purely a compile-time challenge. (If it turns out to be easy, I'm sure that someone will end up posting a "write a program where the source code, executable and output when executed are all the same" challenge, but you don't need to go to that level of complexity for this challenge.)
Your program will, in effect, be a polyglot between the source language, and the language it compiles into. This means that you will need to pick a source language, and executable format, for which such a combination is possible.
Multistep compiling (e.g. compiling an esoteric language into C, which then compiles into an executable) is a legal way to answer the problem. However, this is limited to the use of three compilation steps at most (in order to avoid answers that encode the desired output in the sequence of compilers used rather than in the source code).
Don't use unusual compiler flags to loophole the question via abusing the -D option of a C compiler to hide code (or similar techniques that move code from the program into the compiler flags). You might well need to use unusual compiler flags to produce the executable in the right format, but these should be flags that would generally be useful for compiling programs, not flags specific to the program you've written (and that embed information about it); remember that on this site, the language you're using is defined by the interpreter and compiler flags that you're using.
Likewise, it's possible that your solution will require a specific filename for the source code; in order to prevent you using this to store code, any specific filename should consist of one character, possibly followed by a standard file extension for the language you are using.
Please state the exact compiler and version you're using to compile your program, together with the compiler flags you need to build it, because your answer may be hard to reproduce / verify for correctness otherwise; solutions to this question are likely to inherently be somewhat compiler-specific.
This problem is mostly aimed at compilation into executable formats used by operating systems, but if you have a language that compiles into something else (e.g. bytecode), feel free to submit an answer for that setup, too, even if it won't be quite as impressive. We aren't in the business of unnecessarily restricting what languages you can use here.

Victory condition

This is effectively a code-golf (minimize size of the source) and sizecoding (minimize size of the executable) challenge at the same time (because the two are the same): in this challenge, a program is considered to score better than another if it has a shorter length in bytes. So once you've figured out how to solve this problem at all, you can see if you can do better by fitting the program into fewer bytes.

CoffeeScript to JavaScript, 2 bytes

a;

Try it

a is compiled into a;. You may try it here.
; is compiled into nothing. You may try it here.

Without ban "programs where all the commands compile into themselves", js2js would be a much better choice, IMO.


Print the new site header The new site header has some bits of source code from various questions as the background. Here are the first 3 lines:

--<-<<+[+[<+>--->->->-<<<]>]<<--.<++++++.<<-..<<.<+.>>.>>.<<<.+++.>>.>>-.<<<+. Hello, World! IT'S SHOWTIME TALK TO THE HAND "Hello, World!" YOU HAVE BEEN TERMINATED "9!dlroW ,olleH"ck,@ 72a101a+7aa+3a44a32a87a111a+3a-6a-8a33a Take Circle Line to Paddington Take Circle Line to Wood Lane Take Circle L
alert'Hello, World!' target byteorder little;import puts;export main;section"data"{s:bits8[]"Hello, World!\0";}foreign"C"main(){foreign"C"puts("address"s);foreign"C"return(0);} aeeeaeeewueuueweeueeuewwaaaweaaewaeaawueweeeaeeewaaawueeueweeaweeeueuw H class H{public static void main(String[]a){System.
World!");}}+[-->-[>>+>-----<<]<--<---]>-.>>>+.>>..+++[.>]<<<<.+++.------.<<-.>>>>+. "Hello, World!"o| :after{content:"Hello, World!" H;e;P1;@/;W;o;/l;;o;Q/r;l;d;2;P0 ('&%:9]!~}|z2Vxwv-,POqponl$Hjihf|B@@>,=<M:9&7Y#VV2TSn.Oe*c;(I&%$#"mCBA?zxxv*Pb8`qo42mZF.{Iy*@dD'<;_?!\}}|z2VxSSQ main(){puts("Hello, W

However, a few microseconds of extra load time can cause the user to click away from the site, so the page header download really should be optimized as much as possible.

Write a program that takes no input and produces the (first 3 lines of) text from the new header as output.

Trailing newline is optional
Must include the line breaks from the original header
code-golf, so shortest code wins!

Stax, 601 584 574 564 553 539 bytes

«=¬█j▼sw│╥═7♫çÿñ╦*‼e"!‼╤Å╟D·εWÜå╖L♂@#î╚å♫▐ô;(┤┼»Kî→δäû║h◘│¶zurΘ█┐£ë}∞è┼$÷gôwg¬≤╒Ñ╧]∙ì▄╦╕ís│\☺'┴♫Φ^┐╤å{1█♠₧ï∩∙↑▀⌂d▲╡⌡3J‼¡qâ╧3¥Çƒwe▀≡╔MjZΣΩyüO╬ªÉΩö^Y╡►8K₧óN·ÿjg≈Cö9^◘■~Ä_ßx▐Å┌ Q>/♫╤QΩzN╤V½▓▀◙ß╗╗◄►(╔☺╡┘Ah╙¢√ß▼GΩ→ù◄:─◘#♫úq•ø≤>↨)Å│╤[ïmgBX┤╛v\ⁿ╛å╘╕7d╪TµbW#2¶ø╙╜~êê[↨>K►♪0∞#XJ°ñntG∞⌐V♥Z<ÿº'║☺;┤é⌡♠gáσßÑ+♂z♥‼S9 l≈╫ºÜT»↕▀τ♣¡gWe¥_çà(┬f╜n[╗╤fσ╞R₧▲V▌═◙úKÆÜ▄☺╥s1▼╩ûû╗▌▌Ω■g∞Y╡9╦tè┴y♂w∟⌂┌'╣W▀M╓·uBôúPm◘ ☻ⁿFh<╘sú▲Ö╘¶¿_2♦Θb{╪δC\lô+▀9¶ß§╡╓)ú}○8∟⌡nÑôI )╓îFbH[î║╞e&"¶↓~A#ç╔▄─áσ∙:═Æ▬ª▄ÄêQSNM◙∞Z╜≈±╘▬LIÿ|#.¿Φµ║▌Lväv▓♣;└Æ▲▄♣↕{╪½)╚φ╡♦:oÉ▀j╠ΔP<ç↔|±╦=╣▓Φ▒─4D▄■ìà>↓┐

Run and debug it

It does at least attempt to use different strategies for different pieces.
I've still got some hope for a few sections, but here's an explanation of the approaches so far.

                                    The general approach is to push a bunch of stuff on the stack.
                                    Then join it all together and split it in thirds.
'                                   just a space
`jaH1"jS3!`X                        compressed literal for "Hello, World!" assigned to the x register
`38dZl;i#D]|@Y@*`                   compressed literal for "It's showtime talk to the hand"
^                                   convert to upper case; it compresses better in lower case
n'"|SY                              Wrap the x register in quotes and save it in the y register
`=j("sx6c1 ob`^                     compressed literal for "you have been terminated" in upper
."9                                 literal for '"9'
yrD                                 register y (quoted hello world), reversed, first character dropped
"ck,@ "                             literal
"^h{ai{W>bJ,^T+NLDK(G$s@+"!         crammed array [725, 101597559, 354, 45325875, 1115935, -65, -85335]
$"5a9+"|t                           concat as strings, then map '5' to 'a' and '9' to '+'
`='9%[mh++PxF!`                     compressed literal for " Take Circle Line to "
`~J@[E<`n                           compressed literal for "Paddington"; copy the one about the circle
`jj_kmZ5`                           compressed literal for "Wood Lane"
n7T                                 copy " Take Circle Line to " and truncate last 7 characters
"alert'"x''                         some literals and x register
`~lLKPq'III^) .tI:G8?uMolVwpnT&u#`  compressed literal with commas in place of semi-colons
.,;|t                               replace with semi-colons, which aren't allowed in compressed literals
`/zOXzN`",data,{s:bits8[],`x\0_;}`cC,main(){`cC,puts(,address,s);` C,return(0);} ".,"|t
                                    compressed literal for "foreign", followed by a string template
"Nm\{<\3VdH,FF:c~7&u!n"96|E         carefully chosen string literal interpreted in base 96
"eawu":B                            encoded in custom base "eawu"
`dzJxVHC"`'{`pS7yzeENLM%_'`         two compressed literals with a '{' in the middle
"(String[]a){System."               literal
x6)                                 last 6 characters of register x
"`");}}"                            literal with escaped uote
"0;pKll>r&.sSP}JLNL==(>eP>-2\6fc8|)4&.:,1jA66O{t0>GpALk4I{.iDM:Gr_50ga"
90|E                                literal of ascii characters decoded in base 90
"[+-><],.":B                        re-encoded with a custom base of brainfuck
72:/                                split at position 72
~                                   push the right half to the input stack, effectively the beginning
" `yo| :after{content:`y H;e;P1;@/;W;o;/l;;o;Q/r;l;d;2;P0 ('&%:9]!~}|z2Vxwv-,POqponl$Hjihf|B@@>,=<M:9&7Y#VV2TSn.Oe*c;(I&%$#`"mCBA?zxxv*Pb8``qo42mZF.{Iy*@dD'<;_?!\}}|z2VxSSQ main(){puts("
                                    big string template including y register a few times
y9(                                 first 9 characters of y
Lr$                                 wrap all stacks in array and concatenate
3Mm                                 split into 3 equal parts and print as lines


Generating generating expressions for sequences (yes, "generating generating" in the title is correct :) )

Context

In middle (?) school we are taught about sequences and, in particular, we are taught about linear sequences where the nth term is generated with an expression of the form an + b, where a and b are some coefficients. In this challenge, we will deal with sequences generated by polynomials of arbitrary degree.

Task

Given the first m terms of a sequence, find the coefficients of the polynomial of lowest degree that could have generated such a sequence.

A polynomial, and thus the generating expression you are looking for, is to be seen as a function \$p(n)\$ that takes n as an argument and returns

$$a_0 + a_1 n + a_2 n^2 + a_3 n^3 + \cdots + a_k n^k$$

where \$k \geq 0\$ and \$a_i, 0 \leq i \leq k\$ have to be found by you.

You will assume that the m terms you were given correspond to taking n = 0, n = 1, ..., n = m-1 in the generating polynomial above.

Examples

If I am given the sequence [2, 2, 2] then I realize this is a constant sequence and can be generated by a polynomial of degree 0: p(n) = 2.

If I am given the sequence [1, 2, 3] then I realize this cannot come from a constant polynomial but it could come from a linear polynomial p(n) = n + 1, so that is what my output should be. Notice how

p(0) = 1
p(1) = 2
p(2) = 3    # and NOT p(1) = 1, p(2) = 2, p(3) = 3

Input

Your input will be the first terms of a sequence, which you can take in any reasonable format/data type. A standard list is the most obvious choice.

You may assume the input sequence is composed of integers (positive, 0 and negative).

Output

The coefficients of the polynomial of lowest degree that could have generated the input sequence. The output format can be in any sensible way, as long as the coefficients can be retrieved unambiguously from the output. For this, both the value of each coefficient and the degree of each coefficient are important. (e.g. if using a list, [1, 0, 2] is different from [0, 1, 2]).

You can assume the polynomial you are looking for has integer coefficients.

Test cases

For these test cases, the input is a list with the first terms; the output is a list of coefficients where (0-based) indices represent the coefficients, so [1, 2, 3] represents 1 + 2x + 3x^2.

[-2] -> [-2]
[0, 0] -> [0]
[2, 2, 2] -> [2]
[4, 4] -> [4]
[-3, 0] -> [-3, 3]
[0, 2, 4, 6] -> [0, 2]
[2, 6] -> [2, 4]
[3, 7] -> [3, 4]
[4, 8, 12, 16] -> [4, 4]
[-3, -1, 5, 15, 29] -> [-3, 0, 2]
[0, 1, 4, 9] -> [0, 0, 1]
[3, 2, 3, 6, 11] -> [3, -2, 1]
[3, 4, 13, 30, 55] -> [3, -3, 4]
[4, 12, 28, 52, 84] -> [4, 4, 4]
[2, 4, 12, 32, 70] -> [2, 1, 0, 1]
[3, 6, 21, 54] -> [3, -1, 3, 1]
[4, 2, 12, 52, 140] -> [4, -2, -3, 3]
[10, 20, 90, 280] -> [10, 0, 0, 10]
[-2, 8, 82, 352, 1022, 2368, 4738] -> [-2, 4, -1, 4, 3]
[4, 5, 32, 133, 380] -> [4, -2, 0, 2, 1]
[1, 0, 71, 646, 2877, 8996, 22675] -> [1, -1, 0, -3, 0, 3]
[4, 2, 60, 556, 2540, 8094, 20692] -> [4, -2, -1, 0, -2, 3]
[1, 2, -17, 100, 1517, 7966, 28027, 78128, 186265] -> [1, 3, -2, 4, -3, -2, 1]
[4, 5, 62, 733, 4160, 15869, 47290, 118997] -> [4, 3, -1, -3, 1, 0, 1]

Test cases generated with this code

This is code-golf so shortest submission in bytes, wins! If you liked this challenge, consider upvoting it! If you dislike this challenge, please give me your feedback. Happy golfing!

JavaScript (ES7),  193 ... 154  145 bytes
Saved 9 bytes thanks to @Bubbler
Returns \$(a_0,a_1,...,a_k)\$ with some possible trailing zeros.

v=>v.map((_,i)=>(g=(i,m=v.map((n,y)=>v.map((_,x)=>x==i?n:y**x)))=>+m||m.reduce((s,[v],i)=>v*g(0,m.map(([,...r])=>r).filter(_=>i--))-s,0))(i)/g())

Try it online!
(removed the penultimate test case, which requires more precision than IEEE-754 provides)
How?
We use Cramer's rule to solve a system of linear equations based on a square Vandermonde matrix:

Given an input vector of length \$n\$, we build a Vandermonde matrix \$V_n\$ of size \$n\times n\$ with coefficients \$\alpha_i=i,0\le i <n\$:
$$Vn=\begin{pmatrix}
1&0&0&...&0\\
1&1&1&...&1\\
1&2&4&...&2^{n-1}\\
\vdots&\vdots&\vdots&\ddots&\vdots\\
1&n-1&(n-1)^2&...&(n-1)^{n-1}
\end{pmatrix}$$

Using Cramer's rule, the coefficient \$a_i\$ of the polynomial is computed by taking the determinant of the matrix obtained by replacing the \$i\$-th column of \$V_n\$ with the input vector, and dividing by the determinant of \$V_n\$.

Example for \$(4,2,12,52,140)\$
The constant coefficient \$a_0\$ is given by:
$$a_0=\begin{vmatrix}
\color{blue}4&0&0&0&0\\
\color{blue}2&1&1&1&1\\
\color{blue}{12}&2&4&8&16\\
\color{blue}{52}&3&9&27&81\\
\color{blue}{140}&4&16&64&256
\end{vmatrix}/|V_5|=\frac{1152}{288}=4$$
The coefficient \$a_1\$ is given by:
$$a_1=\begin{vmatrix}
1&\color{blue}4&0&0&0\\
1&\color{blue}2&1&1&1\\
1&\color{blue}{12}&4&8&16\\
1&\color{blue}{52}&9&27&81\\
1&\color{blue}{140}&16&64&256
\end{vmatrix}/|V_5|=\frac{-576}{288}=-2$$
And so on.


Write a sorting program that looks erroneous but it is actually correct Write a program that sorts a vector of numbers (or any type of element) that looks like having one or more bugs, but it is actually ok.

The code must be clear. Someone looking over the code must easily identify that it is a sort algorithm and must easily confuse a correct piece of code with a bug.
The (apparent) bug can by anything that makes the code syntactically or semantically ill-formed (e.g. make the program not compile/run, exhibit UB when runned), make the program produce incorrect results, not terminate, or nondeterministic.
The code must actually be well-formed and the program must deterministically produce the correct output in a finite time.
The input can be hard coded in the program or can be read (from user, from file etc.).
Input is considered valid and the program is not needed to verify input correctness.
Any sorting algorithm is accepted. The data structure to hold the numbers is not needed to be an actual vector. The program can be designed to sort a variable number of numbers or a fixed number of numbers (e.g. a program to sort 3 numbers is ok). Sorting can be stable or not (note: a program designed to do a stable sort that has an apparent bug that makes the sort look unstable, but in actuality it is not a bug: the program actually does a stable sort — is a valid answer).
you can call any functions (including sort functions) except 3rd party tools (unless they are widely spread and used e.g. boos for C++, JQuery for Javascript – those are ok to use)
specify the language
comment in code the part that looks like a bug.
explain what the bug looks like doing wrong.
explain (in a spoiler box) why it is actually not a bug.

This is a popularity contest. The answer with most votes wins.

This challenge is now over. The winner is @Clueless https://codegolf.stackexchange.com/a/30190/11400 with 8 votes. Thanks to all the submitters!

If you want to come in after the winner was awarded, please feel free to add a new answer. You are out of the race, but we are all interested to see interesting answers.

C++

Inspired by Apple's goto fail; bug.

#include <vector>
#include <map>
#include <iostream>

/**
 * Sorts a vector of doubles in reverse order using the bucket sort algorithm.
 */
std::vector<double> reverse_bucket_sort(const std::vector<double>& input) {
    // put each element into a bucket as many times as it appears
    std::map<double, int> bucket_counts;
    for (auto it : input)
        ++bucket_counts[it];

    std::vector<double> sorted_elements; // the return value

    // loop until we are done
    while (bucket_counts.size() > 0) {
        // find the largest element
        double maximum = std::numeric_limits<double>::lowest();
        for (auto it : bucket_counts) {
            if (it.first > maximum)
                maximum = it.first;
                maximum = it.first;
        }

        // add the largest element N times to our sorted vector
        for (int i = 0; i < bucket_counts[maximum]; ++i)
            sorted_elements.push_back(maximum);

        // and now erase the bucket
        bucket_counts.erase(maximum);
    }

    return sorted_elements;
}

int main(int argc, const char * argv[]) {
    std::vector<double> test_case = { 0, 1, 2.5, 10, 2.5, 2 };

    std::cout << "unsorted:";
    for (auto it : test_case) std::cout << " " << it;
    std::cout << std::endl;

    std::cout << "sorted:";
    for (auto it : reverse_bucket_sort(test_case)) std::cout << " " << it;
    std::cout << std::endl;

    return 0;
}

   About halfway down the page there is a bug: we have a duplicate line
 after our if check! We are always going to update the maximum with whatever
 is the last value in bucket_count.

 Thankfully we are OK. In C++ std::map is sorted by keys. So we are
 just reversing the buckets, which is what we want.


Mondrian painting description language This challenge consists in coding an interpreter for a Mondrian painting description language (MPDL).

Language definition

The language operates on a stack of rectangles.
A rectangle is defined by its upper left coordinate and lower right coordinate. Coordinates must be integers.
The stack is initialized with a single rectangle with attributes (1,1,254,254)

Each command has the following format:
<character><integer>

There are three commands:

v<integer> : perform a vertical split on the latest rectangle in the stack, at the position indicated by the parameter (as percentage). The source rectangle is removed from the stack and replaced with the two new rectangles that result of the split. The left rectangle is pushed on the stack, then the right rectangle. As rectangle coordinates are integers, fractions should be rounded to biggest smaller integer.

h<integer> : horizontal split. The top rectangle is pushed on the stack, then the bottom rectangle.

c<integer> : removes the latest rectangle from the stack and paints it to the color given as parameter. 1 = white, 2 = red, 3 = blue, 4 = yellow

Challenge

Write a program that takes as parameter a painting description and creates a 256x256 bitmap representation of the painted rectangles. The rectangles must be separated with a 3 pixel black line. A one or two pixel rectangle should have his non-black pixels hidden by the border black pixels.

The input can be read as a parameter or as a file, up to you. The commands should be separated by a space. You can assume that the input file has correct syntax and does not have trailing or leading spaces, tabs, etc.
The output can be directly displayed on the screen, or saved to a file, up to you.

The shortest code wins.

Test

The following source:

v25 h71 v93 h50 c4 c1 c1 c2 h71 c3 h44 c1 c1

Should produce the Composition II in Red, Blue and Yellow:

Perl 5 + ImageMagick - 297

Something to start with:

sub a{my($x,$y,$X,$Y,$d)=@_;$_=shift@ARGV;
/v/?a($d=$x+($X-$x)*$'/100,$y,$X,$Y).a($x,$y,$d,$Y):
/h/?a($x,$d=$y+($Y-$y)*$'/100,$X,$Y).a($x,$y,$X,$d):
/c/&&"-fill ".qw/white red blue yellow/[$'-1]." -draw 'rectangle $x,$y $X,$Y' "}
system"convert -size 256x256 -stroke black xc: ".a(0,0,255,255)."a.gif"

Takes input on command line and generates a.gif.