Compute the Wilson numbers Given a positive integer n, compute the nth Wilson number W(n) where

and e = 1 if n has a primitive root modulo n, otherwise e = -1. In other words, n has a primitive root if there does not exist an integer x where 1 < x < n-1 and x2 = 1 mod n.

This is code-golf so create the shortest code for a function or program that computes the nth Wilson number for an input integer n > 0.
You may use either 1-based or 0-based indexing. You may also choose to output the first n Wilson numbers.
This is the OEIS sequence A157249.

Test Cases

n  W(n)
1  2
2  1
3  1
4  1
5  5
6  1
7  103
8  13
9  249
10 19
11 329891
12 32
13 36846277
14 1379
15 59793
16 126689
17 1230752346353
18 4727
19 336967037143579
20 436486
21 2252263619
22 56815333
23 48869596859895986087
24 1549256
25 1654529071288638505

Jelly, 8 7 bytes

1 byte thanks to Dennis.

gRỊTP‘:

Try it online!

You don't really have to compute e since you need to divide anyway.


Fastest unique finder Given 4096 16-bit integers, only four of which are unique and others appeared twice (so 2050 different integers exist). Find the four uniques.
To time precisely and limit RAM usage, your program will be run on a 12MHz 8051(with 128B RAM). I'll test with a random case generated by some code to test, but we aim at the worst case, so anyone can provide other test cases.
You can answer in C or ASM, but C will likely give some extra disadvantage. The input array is placed on ROM 0xE000-0xFFFF, and output is placed on extra write-only RAM 0x00-0x07. When you finish outputting, clear P3.5.
A C code that solves the problem with bad score, to better understand the I/O way:
#include <reg51.h>
sbit P3_5 = P3^5;
unsigned int code input[4096] _at_ 0xE000;
unsigned int pdata output[4] _at_ 0x00;
void main() {
    unsigned long i;
    unsigned int j;
    unsigned char cnt, wr = 0;
    for (i=0; i<65536L; ++i) {
        cnt = 0;
        for (j=0; j<4096; ++j) {
            if (input[j] == i) ++cnt;
        }
        if (cnt==1) { // Order doesn't matter
            output[wr++] = i;
        }
    }
    P3_5 = 0;
    while (1);
}

According to test this runs for 04:19:36.997507. Also see the example ASM solution that solve in several seconds.

For extreme push, I'll run the simulation on Proteus with such circuit:

and check the time when DBT1 is actived.

You can use all ROM in 0000-DFFF.
You can assume RAM is initialized to 0.
You can use SFRs, including pins, as RAM
You don't need to jmp $ after clearing P3.5
You can write trash into outer RAM 08-FF, they'll be ignored

C, 0.480298s
Codes

#ifndef LOCAL_DEBUG
#include <reg51.h>
sbit P3_5 = P3 ^ 5;
unsigned int code input[4096] _at_ 0xE000;
unsigned int pdata output[4] _at_ 0x00;
#else

#include <stdio.h>
#define int short

#define UNIQ1 17
#define UNIQ2 273
#define UNIQ3 1298
#define UNIQ4 1554

unsigned int input[4096] = {
UNIQ1,
UNIQ2,
UNIQ3,
UNIQ4
};
unsigned int output[4];

#endif

#define INPUT_SIZE 4096
#define BUCKET_BITS 4
#define BUCKET_SIZE (1 << (BUCKET_BITS))
#define BUCKET_MASK ((BUCKET_SIZE) - 1)

unsigned int buckets[BUCKET_SIZE];

#define buckets_value(n) (buckets[n] & ~(bucket_mask)) | ((n) << bit_offset)

void main() {
  unsigned int output_offset = 0;
  unsigned int i, j, k, l;
  unsigned int search_bucket = 0, search_bucket_2 = 0, bit_offset = 0, bit_offset_2, bucket_mask;
  unsigned int target_mask, target_value;
  do {
    bucket_mask = BUCKET_MASK << bit_offset;
    for (i = 0; i < BUCKET_SIZE; ++i) {
      buckets[i] = 0;
    }
    for (i = 0; i < INPUT_SIZE; ++i) {
      buckets[(input[i] >> bit_offset) & BUCKET_MASK] ^= input[i] | bucket_mask;
    }
    for (i = j = 0; i < BUCKET_SIZE; ++i) {
      if (buckets[i] != 0) ++j;
    }
    if (j <= 1) {
      bit_offset += BUCKET_BITS;
    }
  } while (j <= 1);
  if (j == 4) {
    for (i = 0; i < BUCKET_SIZE; ++i) {
      if (buckets[i] == 0) continue;
      output[output_offset++] = buckets_value(i);
    }
  } else if (j == 3) {
    for (i = 0; i < BUCKET_SIZE; ++i) {
      if (buckets[i] == 0) continue;
      if (buckets[i] & (BUCKET_MASK << bit_offset)) {
        output[output_offset++] = buckets_value(i);
      } else {
        search_bucket = i << bit_offset;
      }
    }
  } else if (j == 2) {
    for (i = k = 0; i < BUCKET_SIZE; ++i) {
      if (buckets[i] == 0) continue;
      if (buckets[i] & (BUCKET_MASK << bit_offset)) {
        l = buckets_value(i);
        if (k == 0) {
          for (j = 0; j < INPUT_SIZE; ++j) {
            if (input[j] == l) ++k;
          }
          if (k == 1) {
            output[output_offset++] = l;
          } else {
            search_bucket = i << bit_offset;
            k = 2;
          }
        } else if (k == 1) {
          search_bucket = i;
        } else {
          output[output_offset++] = l;
        }
      } else {
        if (search_bucket) {
          search_bucket_2 = i << bit_offset;
        } else {
          search_bucket = i << bit_offset;
        }
      }
    }
  }
  bit_offset_2 = bit_offset;
  target_mask = BUCKET_MASK << bit_offset;
  target_value = search_bucket;
  while (output_offset < 4) {
    bit_offset += BUCKET_BITS;
    bucket_mask = BUCKET_MASK << bit_offset;
    for (i = 0; i < BUCKET_SIZE; ++i) {
      buckets[i] = 0;
    }
    for (i = 0; i < INPUT_SIZE; ++i) {
      if ((input[i] & target_mask) != target_value) continue;
      buckets[(input[i] >> bit_offset) & BUCKET_MASK] ^= input[i] | bucket_mask;
    }
    for (i = j = 0; i < BUCKET_SIZE; ++i) {
      if (buckets[i] != 0) ++j;
    }
    if (j == 1) {
      continue;
    }
    for (i = 0; i < BUCKET_SIZE; ++i) {
      if (buckets[i] == 0) continue;
      if ((buckets[i] >> bit_offset) & BUCKET_MASK) {
        output[output_offset++] = buckets_value(i);
        --j;
      } else {
        target_mask |= bucket_mask;
        target_value |= i << bit_offset;
      }
    }
    if (j == 0) {
      bit_offset = bit_offset_2;
      target_mask = BUCKET_MASK << bit_offset;
      target_value = search_bucket_2;
    }
  }
#ifndef LOCAL_DEBUG
  P3_5 = 0;
  while (1);
#else
  for (i = 0; i < 4; i++) {
    printf("%d\n", output[i]);
  }
#endif
}

Try it online!
I'm not sure about its correctness. Please comment if you find out some failed testcases. I will try my best to fix it.

Algorithm
Algorithm here only works when input array contains 4 unique values. It will fail if input array contains more than 4 values.
Consider xor of some numbers where most numbers occurred 2 times, and some occurred once. It is easy to prove: The xor result is zero if and only if we have at least 3 unique numbers here. Also, we try to count how many numbers at all. It is trivial to know: If the count is even / odd, then we have even / odd number of unique numbers here.
As there are only 4 unique numbers according to the description of this question. If both xor result is zero and count result is even, there should be 0 or 4 unique numbers.
By using this idea, we need to split numbers into some buckets while keep equals number in same buckets. You can do it by (input[i] >> n) & m. So we first split all values input[i] into 16 buckets based on (input[i] >> 0) & 15. We use input[i] | bucket_mask to mask out the bits for bucket name. We set them to 1s, so they are used to know count number in that buckets is odd or even.
for (i = 0; i < INPUT_SIZE; ++i) {
  buckets[(input[i] >> bit_offset) & BUCKET_MASK] ^= input[i] | bucket_mask;
}

We use above code. And after calculate these buckets:

If buckets[i] & bucket_mask is non-zero: we know the bucket i contains 1 or 3 unique numbers (number count is odd).
If buckets[i] & bucket_mask is zero, but buckets[i] is non-zero: we know the bucket i contains 2 unique numbers.
If buckets[i] is zero, and some other bucket bucket[j] is non-zero: we know the bucket i contains no unique numbers.
If all buckets are zero: 4 unique numbers are located in the same bucket. We need to try another 4 bits as mask and run the loop again.

After we know where the number is in some bucket:

If the bucket contains only 1 unique numbers: the unique number is (buckets[i] & ~(bucket_mask)) | ((i) << bit_offset);
If the bucket contains more than 1 unique numbers: We loop again on numbers in this bucket, and split them into different buckets based on other bits;

Analysis
Time complexity is \$O\left(size \cdot bit  / buckets + 2^{buckets} \right)\$. \$size\$ is how many numbers the input contains. \$bit\$ is how many bits each input contains. \$bucket\$ is how many bits for bucket id (4 in above codes).
Extra storage complexity is \$O\left(2^{buckets}\right)\$.


Detecting loops in in in strings Given a string, mark which parts in the string repeat in box brackets, and write how many times it does so before the box.

Example:st st st Hello ThereThere
st(with a space after) repeats 3 times, There repeats 2 times, and l repeats 2 times in Hello, so the output will be:
3[st ]He2[l]o 2[There]
There is no space between [st ] and Hello because the space in the string is being taken up by the repeating part. [st ], 3 times with a Hello after it would be st st st Hello, which is what the string has.

Other examples:
st Hello st st Bye -> st He2[l]o 2[st ]Bye
Bookkeeper -> B2[o]2[k]2[e]per
/\/\/\\\\\\\\/\/\/ -> 3[/\]6[\]3[\/]

Shortestest code wins.

EDIT: To clarify the choice of selections, choose the largest possible repeating section, and try and leave as little non-repeating characters as possible. Do not nest boxed-in sections.

Perl, 36 bytes

#!perl -p
s!(.+)\1+!@{[$&=~/\Q$1/g]}."[$1]"!eg

Try it online!

PHP 5.6, 68 bytes

Same code in PHP. Requires the command line option -F, and relies on deprecated /e modifier.

<?=preg_filter('/(.+)\1+/e','substr_count("\0","\1")."[\1]"',$argn);


Semi-decide Post's Correspondence Problem The Post's Correspondence Problem (PCP) gives you a list of pairs of strings, P_1 ... P_n. Your task is to find a k, and some sequence of k indices such that fst(P_i1) ... fst(P_ik) = snd(P_i1) ... snd(P_ik)

We're trying to find some sequence of the pairs where the word we build from the first part is equal to the word on the second part.
A solution can use any of the pairs any number of times, and in any order.

For example, if our pairs are (0,110), (11,1) and (001,100) , then one solution is the world 11001110, with the solution sequence of 2321:

11 001 11 0
1  100 1  110

Some will have no solution, such as (001, 01), (0001, 01).

Input:

An arbitrary number of words, separated by spaces.
Each word is of the format seq1,seq2 where each seq1 and seq2 are strings consisting only of 0 or 1, of arbitrary length.

Example: the above examples would have the following formats:

0,110 11,1 001,110

001,01 0001,01

Output:

If there is some sequence of the pairs which solves the PCP, output the word of the solution, followed by a space, followed by the sequence. The pairs are numbered starting at 1.

If there is no such sequence, run forever. (The problem is undecidable, so this will have to do).

Example output

11001110 2321

# second example never halts

Hint:

This is Turing Complete, so you're going to have to use some sort of infinite search.

Python 3, 223 216 199 192 191 189 183 bytes
Thanks to @KarlKastor for pointing out that I could use count
from itertools import*
j=''.join
def f(x):
 for l in count(1):
  for i in product(x,repeat=l):
   *b,=zip(*i);c=j(b[0])
   if c==j(b[1]):print(c,j(str(x.index(k)+1)for k in i));return

A function that takes input of a tuple of pairs of strings x in the form ((seq1,seq2),(seq1,seq2)...) and prints the output to STDOUT in the same format as the test cases.
To continuously output solutions rather than just one solution, remove the return statement.
How it works
The function generates all l-length arrangements of the string pairs using product, with l being initialised at 1. This list is then unpacked and transposed using zip; this leaves a two-element list, where the first element contains all the first strings in the pairs, and the second all the second strings in the pairs. Each element is concatenated to a string using join; if these are the same, we have a hit and the string is printed to STDOUT. The sequence of pair indices is then generated by looking up each pair in the original arrangement using index; these indices are concatenated to a string, and also printed to STDOUT. If no solution exists for that l, l is incremented and the process repeated.
Try it on Ideone


The Decryption Function You must write a program that takes an encrypted string and decrypt it according to specific rules and then print it out. Decryption will occur by performing two operations.
Sample Input Argument 1 (the encrypted string)
HGJILKBADCFE

Operation 1:
Swap the first half of the string with the second half, which should leave you with:
BADCFEHGJILK

Operation 2:
Swap every two characters with each other such as swapping character 1 with 2, 3 with 4, etc., which should leave you with the decrypted string:
ABCDEFGHIJKL

Guidelines:

Input Argument 1 will contain only uppercase letters

Input Argument 1's length will be between 2 and 100 characters

Input Argument 1's length will always be an even number

Preferably the input will be taken from the command line (like below).

Another Test Case MPORQTSVUXWZYBADCFEHGJILKN is the input, Output is ABCDEFGHIJKLMNOPQRSTUVWXYZ

My Attempt
import sys
_,a=sys.argv
b=len(a)//2
s=a[b:]+a[:b]
print(''.join(x+y for x,y in zip(s[1::2],s[::2])))

Ruby -p, 48 47 bytes

$_=$_[l= ~/$//2,l]+$_[0,l];gsub /(.)(.)/,'\2\1'

Try it online!
Operation 1 is handled by splitting $_ (the predefined global variable that contains the input) into two substrings of equal length; ~/$/ gives the length of the input. Then gsub /(.)(.)/,'\2\1' completes Operation 2 by swapping each pair of characters. (With the -p flag, gsub without a receiver implicitly acts on $_.)


Find the last position in a matrix walking like a spiral This question will be deleted soon, do not read/answer it

Introduction

Given one matrix A x A and a number of movements N.

You will need to walk like a spiral starting in (1; 1):

right while possible, then
down while possible, then
left while possible, then
up while possible, repeat until got N.

Challenge

You can only take as input the numbers A and N.

You must output the final (row; column) after walking N steps in the conditions explained above. You can not invert the output order.

You can use indexes starting with zero as well. Just state it in your answer.

Program or function allowed.

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

Sample

For input (A = 8; N = 54).

The output should be (5; 6).

Another samples

input: A=8, N=64
output: [5, 4]

input: A=15, N=14
output: [1, 14]

input: A=26, N=400
output: [22, 9]

input: A=1073741824, N=1152921504603393520
output: [536871276, 536869983]

Restrictions

1 <= A <= 230

1 <= N <= (A2 OR the below higher number supported in your language).

And, if you want a generic formula.

MATL, 24 bytes
This works in release 16.0.0 of the language, which predates the challenge.
2^Q6Y3GYLG2\?!P!}P]-=2#f

Output is 1-based, as in the examples.
A^2 and N are limited to 2^53 as per the language's default data type (double). In addition, since the whole matrix is being generated, memory will limit A to significantly lower values.
Try it online! (In the online version I have changed the order of G and 6Y3 so it works in the new 16.1.0 release)
Explanation
This uses MATL's builtin for generating an outward spiral. To make it inward, a subtraction and a reversal are needed. The direction of reversal depends on whether A is odd or even.
2^Q     % take input A implicitly. Compute A^2+1
6Y3GYL  % outward spiral of side length A
G2\     % is A odd?
?       % if so
  !P!   %   flip matrix horizontally
}       % else
  P     %   flip matrix vertically
]       % end if
-       % compute A^2+1 minus the matrix element-wise, so (1,1) contains 1
=       % take input N implicitly. Set matrix entry that contains that value to true
2#f     % row and column index of that true value


Demonstrate a lower bound for the Ramsey number R(4,4) A special case of Ramsey's theorem says the following: whenever we color the edges of the complete graph on 18 vertices red and blue, there is a monochromatic clique of size 4.

In language that avoids graph theory: suppose we place 18 points around a circle and draw all possible line segments connecting them in one of two colors: either red or blue. No matter how this is done, it's always possible to choose 4 of the points such that all 6 line segments between them are the same color: either all 6 are red or all 6 are blue.

Moreover, 18 is the least number for which this will work. For 17 points, we can color the line segments so that it's impossible to choose 4 points in this way.

Your goal is to print one such coloring. Your output must be a 17 by 17 adjacency matrix in which the (i,j) entry gives the color of the line segment joining points i and j. It must be in a format such as the one below:

  R R B R B B B R R B B B R B R R
R   R R B R B B B R R B B B R B R
R R   R R B R B B B R R B B B R B
B R R   R R B R B B B R R B B B R
R B R R   R R B R B B B R R B B B
B R B R R   R R B R B B B R R B B
B B R B R R   R R B R B B B R R B
B B B R B R R   R R B R B B B R R
R B B B R B R R   R R B R B B B R
R R B B B R B R R   R R B R B B B
B R R B B B R B R R   R R B R B B
B B R R B B B R B R R   R R B R B
B B B R R B B B R B R R   R R B R
R B B B R R B B B R B R R   R R B
B R B B B R R B B B R B R R   R R
R B R B B B R R B B B R B R R   R
R R B R B B B R R B B B R B R R

The exact output above represents a valid coloring, so it is perfectly acceptable. But you have the following additional freedom to do something else:

You may print the adjacency matrix for any graph that satisfies the Ramsey condition, not just this one. (For example, any permutation of the rows with a corresponding permutation of the columns gives another acceptable output. I haven't checked if any non-isomorphic colorings exist.)
You may use any two distinct, non-whitespace characters in place of R and B to represent the two colors.

However, the spacing must appear exactly as in the example above: a space between cells in the same row, spaces in the diagonal entries, and newlines after each row. Leading and trailing spaces and newlines are allowed (but the entries of the adjacency matrix should be aligned with each other).

This is code-golf, so the shortest code in bytes wins. Because this is kolmogorov-complexity, hardcoding the output is allowed. Otherwise,
 standard loopholes apply.


Relative dates in words Given a specific date, have the code output a relative reference:

If the date entered is ahead of the current date, express as "x days from now" or "x weeks, y days from now", or "x years, y weeks, z days from now". Zero units need not be mentioned.
If the date is the current simply have it output "Today"
If the date entered is earlier than the current date, express as "x days ago" or "x weeks, y days ago", or "x years, y weeks, z days ago". Zero units need not be mentioned.

Smallest solutions are the winners here...

Good luck!

R, 102, 98

(kinda cheating: literal interpretation of the question)

cat(if(x<-as.Date(readline())-Sys.Date())c(abs(x),"days",c("from now","ago")[(x<0)+1])else"today")

Examples:

2013-12-08
today

2010-01-13
1425 days ago

2015-12-2
724 days from now


Calculate practical numbers Definition

A positive integer n is a practical number (OEIS sequence A005153) iff all smaller positive integers can be represented as sums of distinct divisors of n.

For example, 18 is a practical number: its divisors are 1, 2, 3, 6, 9, and 18, and the other positive integers smaller than 18 can be formed as follows:

 4 = 1 + 3          5 = 2 + 3           7 = 1 + 6
 8 = 2 + 6          10 = 1 + 9         11 = 2 + 9
12 = 3 + 9 = 1 + 2 + 9 = 1 + 2 + 3 + 6
13 = 1 + 3 + 9      14 = 2 + 3 + 9      15 = 6 + 9
16 = 1 + 6 + 9      17 = 2 + 6 + 9

But 14 is not a practical number: its divisors are 1, 2, 7, and 14, and there's no subset of these which adds to 4, 5, 6, 11, 12, or 13.

Challenge

Write a program, function, or verb which takes as input a positive integer x and either returns or prints the xth practical number, indexed from 1 for consistency with OEIS. Your code must be sufficiently efficient that it can handle inputs up to 250000 in less than two minutes on a reasonable desktop computer. (NB my reference implementation in Java manages 250000 in less than 0.5 seconds, and my reference implementation in Python manages it in 12 seconds).

Test cases

Input        Expected output
1            1
8            18
1000         6500
250000       2764000
1000000      12214770
3000000      39258256

Mathematica, 126 121 chars
Thanks to belisarius.
Using the formula on wikipedia.
f=(i=j=1;While[j<#,If[And@@Thread[#[[;;,1]]<2+Most@DivisorSum[FoldList[#Power@@#2&,1,#],#&]&@FactorInteger@++i],j++]];i)&

Examples:
f[1]

1

f[8]

18

f[250000]

2764000

It took 70s to compute f[250000] on my computer.


Generate MathJax for the Golden Ratio Continued Fraction In anticipation of MathJax being temporarily disabled, the rendered MathJax in this question has been replaced with images. You are still welcome to post answers but you'll have to view the rendered MathJax on another site.

PPCG just got MathJax! This means we can now easily include well formatted mathematical formulas into posts. (Handy MathJax tutorial.)

For example, here is the golden ratio expressed as an infinite continued fraction:

The MathJax code for this equation is

$$\varphi=1+\cfrac1{1+\cfrac1{1+\cfrac1{1+\cfrac1{1+\ddots}}}}$$

You can find this by right clicking the formula and following Show Math As → TeX Commands.
The $$ means it is displayed on its own in the center of the page instead of inline. Use a single $ for inline.

Challenge

Write a program that takes in a non-negative integer, n, and outputs the MathJax code for that many "steps" of the continued fraction for the golden ratio.

To keep things standard across answers, you must use this exact MathJax syntax:

For n = 0, the output must be $$\varphi=1+\dots$$.
Which is rendered as:

For n = 1, the output must be $$\varphi=1+\cfrac1{1+\ddots}$$.
Which is rendered as:

For n = 2, the output must be $$\varphi=1+\cfrac1{1+\cfrac1{1+\ddots}}$$.
Which is rendered as:

For n = 3, the output must be $$\varphi=1+\cfrac1{1+\cfrac1{1+\cfrac1{1+\ddots}}}$$.
Which is rendered as:

This pattern continues on for larger n. You could say that n represents the number of division lines in the equation.

Notes

\cfrac is used instead of the more common \frac.
\dots is used instead of \ddots for n = 0.
Take input from stdin or the command line.
Output to stdout (with an optional trailing newline).
Alternatively, you may write a function that takes in n as an integer and returns the MathJax code as a string (or still prints it).

Scoring

The smallest submission in bytes wins. Tiebreaker goes to the earlier submission.

Python, 70 68 67 bytes

lambda n:"$$\\varphi=1+\%sdots%s$$"%("cfrac1{1+\\"*n+"d"[:n],"}"*n)

This defines an anonymous function which just uses simple string multiplication and string formatting.

(Thanks to @xnor for pointing out that \\c can just be written as \c, since c can't be escaped. Unfortunately this doesn't hold true for \\v, since \v is ASCII 11.)

Previous attempts:

lambda n:"$$\\varphi="+"1+\\cfrac1{"*n+"1+\\"+"ddots"[n<1:]+"}"*n+"$$"
lambda n:r"$$\varphi=%s1+\%s$$"%("1+\cfrac1{"*n,"ddots"[n<1:]+"}"*n)


Collatz Paths: Forwards and Backwards along the Collatz Conjecture The Collatz conjecture is a very well-known conjecture. Take a positive integer; if it's even, divide by 2, else, multiply by 3 and add 1. Repeat until you reach 1 or something else happens. The conjecture is that this process always reaches 1.

You can also reverse the process. Start at 1, multiply by 2, and to branch to multiply by 3 and add 1 numbers, when you reach an even number that is 1 (mod 3), subtract 1 and divide by 3.

A Collatz path combines the two, trying to get from one number to another with those four operations.

For example, to get to 20 from 1:

1     *2
2     *2
4     *2
8     *2
16    *2
5     (-1)/3
10    *2
20    *2

You can also get to 3 from 10 by subtracting 1 and dividing by 3.

With these tools, you can traverse a Collatz path from one number to another. For example, the path from 20 to 3 is (divide by 2), (subtract 1, divide by 3).

In short, the available operations are:

n * 2       always
n // 2      if n % 2 == 0
n * 3 + 1   if n % 2 == 1
(n-1) // 3  if n % 6 == 4

Note: not all Collatz paths are short. a(7,3) could run

7, 22, 11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1, 2, 4, 8, 16, 5, 10, 3

but a shorter path is

7, 22, 11, 34, 17, 52, 26, 13, 40, 20, 10, 3

The Challenge

Find the length of the shortest Collatz path between any two positive integers, p and q.

Input is any two positive integers less than 2^20 to avoid integer overflow. The input method is left to the discretion of the golfer. The integers may be the same, in which case, the length of the Collatz path is 0.
Output should be one integer, denoting the length of the shortest Collatz path between p and q.

Test Cases

a(2,1)
1

a(4,1)
1         # 4 -> 1

a(3,1)
6         # 3 -> 10 -> 5 -> 16 -> 8 -> 4 -> 1

a(11,12)
11        # 11 -> 34 -> 17 -> 52 -> 26 -> 13
          # -> 40 -> 20 -> 10 -> 3 -> 6 -> 12

a(15,9)
20        # 46 -> 23 -> 70 -> 35 -> 106 -> 53 -> 160 -> 80 -> 40 -> 13
          # -> 26 -> 52 -> 17 -> 34 -> 11 -> 22 ->  7 -> 14 -> 28 -> 9

Many thanks to orlp for their help in clarifying this challenge.

As always, if the problem is unclear, please let me know. Good luck and good golfing!

Haskell, 170 158 157 146 143 137 135 112 109 108 106 100 99 bytes
a!b=length$fst$break(elem b)$iterate(>>= \n->2*n:cycle[div n 2,n*3+1]!!n:[div(n-1)3|mod n 6==4])[a]

I did not expect that my original version was so much more golfable, this is also the work of @nimi @Lynn and @Laikoni!
Thanks @Laikoni for a byte, @Lynn for 11 14 20 21 bytes, @nimi for 8 bytes!
This expands the the tree of visited numbers (beginning by a) step by step, and checks in each step whether we arrived at the given number b.


CJam, 147 bytes, slightly broken

qN/6/{z{:i:+165%91%' +}%"e 3 VG rr A>Q V) rP r4 />/ F> [> C >> 9$ j8 fQrQ rG rN rD VV $>$ ;$ 859 98 ff = BB"S/eeWf%$W%{~@@/\a*}/{`''#},'@f+'@/S*N}%

It passes CODE GOLF and A-Z but not STAR WARS (which it reads as SAR WARS). I give up, but maybe someone is inspired.


Count blocks in a 2D grid Challenge description

Let's define an W x H grid as a two-dimensional array of length H whose each subarray is of length W. Example: a 2x3 grid (. character used as a blank):

..
..
..

A unit is a single point of a grid. A block is either a single unit or a set of contiguous units (meaning each unit of a block has at least another one next to, above or below it). In the 10x10 grid below there are 4 blocks (units represented by X's):

........X.   ........1.
..X.......   ..2.......
..X.......   ..2.......
..X.......   ..2.......
.......X..   .......3..
.......XX.   .......33.
.......XX.   .......33.
..X.......   ..4.......
..XX..X...   ..44..4...
...XXXX...   ...4444...

Two blocks are distinct if either their positions in the grid or the number of blocks they consist of are different. In the 10x10 grid below there are 5 blocks (they're all 2x2 squares, but their positions are different, therefore they're distinct):

..........   ..........
.XX....XX.   .11....22.
.XX....XX.   .11....22.
..........   ..........
.......XX.   .......33.
.......XX.   .......33.
....XX....   ....44....
....XX....   ....44....
XX........   55........
XX........   55........

Given two integers W and H (W, H > 0), calculate the number of distinct blocks that can be constructed within a W x H grid.

Sample inputs / outputs

(1, 1) -> 1     | only a 1x1 block can be constructed
(1, 2) -> 3     | two 1x1 blocks, and one 1x2 block
(2, 2) -> 13
(3, 3) -> 218
(4, 4) -> 11506

Notes

Remember that this is a code-golf challenge, so make your code as short as possible!
Relevant sequences: A059525, A059020


Spiral out the Alphabet! Look at the following string. Notice a pattern?

ABEFNOPEFGH
DC G  Q   I
M  H  R   J
LKJI  S   K
D     T   L
C     U   M
BAZYXWV   N
E         O
D         P
C         Q
BAZYXWVUTSR

As some might have noticed, it's basically a spiral of the alphabet, where the distances between rows / columns are gradually increasing by 1 space / newline.

Rigorous definition

Let's have a counter c, which is initially 0.
We write out the first c + 1 letters of the alphabet from left to right: A.
Then, from top to bottom the next (c + 1)(c + 2)/2 letters (add B): AB.
From left to right, the next (c + 1)(c + 2)/2 (add C):

AB
 C

And from bottom to top, the next c + 1 letters (add D):

AB
DC

Reached the end of the cycle. Hence, let's increment c (which becomes 1). Then, it starts back from the first step, the only difference being that instead of using the first c + 1 letters of the alphabet, we use the next c + 1 letters, starting from the last element of this cycle (D in this case, so we continue with EFG...). When Z is reached, it cycles back from A.

Task

Given an integer N (which is positive for 1-indexing or non-negative for 0-indexing), output the first N cycles of the spiral.

Rules

You can either use the lowercase or the uppercase alphabet, but your choice must be consistent (only use one of them, mixing is not allowed).
You can take input and provide output through any of the standard methods, in any programming language, while noting that these loopholes are forbidden by default.
Acceptable output formats: multiline string, a list of strings representing lines, a list containing multiple lists of characters, each representing one line, or anything else you find suitable. In case you don't choose the first format, it would be nice to include a pretty-print version of your code.
This is code-golf, so the shortest code in bytes (in each language) which fulfils the requirements wins!

Test cases

The input integer will be separated by its corresponding output through a newline, and the tests will be separated using dashes. Note that these are 1-indexed.

1

AB
DC

--------

2

ABEF
DC G
M  H
LKJI

--------

3

ABEFNOP
DC G  Q
M  H  R
LKJI  S
D     T
C     U
BAZYXWV

-------

4

ABEFNOPEFGH
DC G  Q   I
M  H  R   J
LKJI  S   K
D     T   L
C     U   M
BAZYXWV   N
E         O
D         P
C         Q
BAZYXWVUTSR

-------
5

ABEFNOPEFGHFGHIJ
DC G  Q   I    K
M  H  R   J    L
LKJI  S   K    M
D     T   L    N
C     U   M    O
BAZYXWV   N    P
E         O    Q
D         P    R
C         Q    S
BAZYXWVUTSR    T
R              U
Q              V
P              W
O              X
NMLKJIHGFEDCBAZY

------

6

ABEFNOPEFGHFGHIJSTUVWX
DC G  Q   I    K     Y
M  H  R   J    L     Z
LKJI  S   K    M     A
D     T   L    N     B
C     U   M    O     C
BAZYXWV   N    P     D
E         O    Q     E
D         P    R     F
C         Q    S     G
BAZYXWVUTSR    T     H
R              U     I
Q              V     J
P              W     K
O              X     L
NMLKJIHGFEDCBAZY     M
S                    N
R                    O
Q                    P
P                    Q
O                    R
NMLKJIHGFEDCBAZYXWVUTS

Charcoal, 31 bytes

Ｆ⮌…⁰ＮＢ⁺²⊘×ι⁺³ι⭆α§α⁺λ÷×ι⊕×ι⁺⁹⊗ι⁶

Try it online! Link is to verbose version of code. Note: The deverbosifier outputs a trailing separator for some reason. Explanation:

Ｆ⮌…⁰ＮＢ

Draw boxes in reverse order of size (largest to smallest).

⁺²⊘×ι⁺³ι

Calculate the size of the box.

⭆α§α⁺λ

Draw the border of the box using a rotated alphabet.

÷×ι⊕×ι⁺⁹⊗ι⁶

Calculate the letter that would appear at the top left of the box (0-indexed).


Miller-Rabin Strong Pseudoprimes Given a non-negative integer N, output the smallest odd positive integer that is a strong pseudoprime to all of the first N prime bases.
This is OEIS sequence A014233.
Test Cases (one-indexed)
1       2047
2       1373653
3       25326001
4       3215031751
5       2152302898747
6       3474749660383
7       341550071728321
8       341550071728321
9       3825123056546413051
10      3825123056546413051
11      3825123056546413051
12      318665857834031151167461
13      3317044064679887385961981

Test cases for N > 13 are not available because those values have not been found yet. If you manage to find the next term(s) in the sequence, be sure to submit it/them to OEIS!
Rules

You may choose to take N as a zero-indexed or a one-indexed value.
It's acceptable for your solution to only work for the values representable within your language's integer range (so up to N = 12 for unsigned 64-bit integers), but your solution must theoretically work for any input with the assumption that your language supports arbitrary-length integers.

Background
Any positive even integer x can be written in the form x = d*2^s where d is odd. d and s can be computed by repeatedly dividing n by 2 until the quotient is no longer divisible by 2. d is that final quotient, and s is the number of times 2 divides n.
If a positive integer n is prime, then Fermat's little theorem states:

In any finite field Z/pZ (where p is some prime), the only square roots of 1 are 1 and -1 (or, equivalently, 1 and p-1).
We can use these three facts to prove that one of the following two statements must be true for a prime n (where d*2^s = n-1 and r is some integer in [0, s)):

The Miller-Rabin primality test operates by testing the contrapositive of the above claim: if there is a base a such that both of the above conditions are false, then n is not prime. That base a is called a witness.
Now, testing every base in [1, n) would be prohibitively expensive in computation time for large n. There is a probabilistic variant of the Miller-Rabin test that only tests some randomly-chosen bases in the finite field. However, it was discovered that testing only prime a bases is sufficient, and thus the test can be performed in an efficient and deterministic manner. In fact, not all of the prime bases need to be tested - only a certain number are required, and that number is dependent on the size of the value being tested for primality.
If an insufficient number of prime bases are tested, the test can produce false positives - odd composite integers where the test fails to prove their compositeness. Specifically, if a base a fails to prove the compositeness of an odd composite number, that number is called a strong pseudoprime to base a. This challenge is about finding the odd composite numbers who are strong psuedoprimes to all bases less than or equal to the Nth prime number (which is equivalent to saying that they are strong pseudoprimes to all prime bases less than or equal to the Nth prime number).

C, 349 295 277 267 255 bytes

N,i;__int128 n=2,b,o,l[999];P(m){i<N&&P(m<2?l[i++]=n:n%m?m-1:n++);}main(r){for(P(scanf("%d",&N));r|!b;)for(++n,b=i=N;i--&&b;){for(b=n-1,r=0;~b&1;b/=2)++r;for(o=1;b--;o=o*l[i]%n);for(b=o==1;r--;o=o*o%n)b|=o>n-2;for(o=r=1;++o<n;r&=n%o>0);}printf("%llu",n);}

Takes 1-based input on stdin, e.g.:

echo "1" | ./millerRabin

It certainly isn't going to discover any new values in the sequence any time soon, but it gets the job done. UPDATE: now even slower!

Slightly faster and shorter, with inspiration from Neil A's answer (a^(d*2^r) == (a^d)^(2^r))
Significantly slower again after realising that all solutions to this challenge will be odd, so there is no need to explicitly enforce that we only check odd numbers.
Now using GCC's __int128, which is shorter than unsigned long long while also working with larger numbers! Also on little-endian machines, the printf with %llu still works fine.

Less-minified

N,i;
__int128 n=2,b,o,l[999];
P(m){i<N&&P(m<2?l[i++]=n:n%m?m-1:n++);}
main(r){
    for(P(scanf("%d",&N));r|!b;)
        for(++n,b=i=N;i--&&b;){
            for(b=n-1,r=0;~b&1;b/=2)++r;
            for(o=1;b--;o=o*l[i]%n);
            for(b=o==1;r--;o=o*o%n)b|=o>n-2;
            for(o=r=1;++o<n;r&=n%o>0);
        }
    printf("%llu",n);
}

(Outdated) Breakdown

unsigned long long                  // Use the longest type available
n=2,N,b,i,d,p,o,                    // Globals (mostly share names with question)
l[999];                             // Primes to check (limited to 999, but if you
                                    // want it to be "unlimited", change to -1u)
m(){for(o=1;p--;o=o*l[i]%n);}       // Inefficiently calculates (l[i]^p) mod n

// I cannot possibly take credit for this amazing prime finder;
// See https://codegolf.stackexchange.com/a/5818/8927
P(m){i<N&&P(m<2?l[i++]=n:n%m?m-1:n++);}

main(r){
    for(
        P(scanf("%llu",&N));        // Read & calculate desired number of primes
        r|!b;){                     // While we haven't got an answer:
        n=n+1|1;                    // Advance to next odd number
        for(b=1,i=N;i--&&b;){       // For each prime...
            for(d=n-1,r=0;~d&1;d/=2)++r; // Calculate d and r: d*2^r = n-1
            // Check if there exists any r such that a^(d*2^r) == -1 mod n
            // OR a^d == 1 mod n
            m(p=d);
            for(b=o==1;r--;b|=o==n-1)m(p=d<<r);
            // If neither of these exist, we have proven n is not prime,
            // and the outer loop will keep going (!b)
        }
        // Check if n is actually prime;
        // if it is, the outer loop will keep going (r)
        for(i=r=1;++i<n;r&=n%i!=0);
    }
    printf("%llu",n);               // We found a non-prime; print it & stop.
}

As mentioned, this uses 1-based input. But for n=0 it produces 9, which follows the related sequence https://oeis.org/A006945. Not any more; now it hangs on 0.

Should work for all n (at least until the output reaches 2^64) but is incredibly slow. I have verified it on n=0, n=1 and (after a lot of waiting), n=2.


Rolling three dice and show the probabilities Roll 3 dice, count the two highest two values and add them to the result. Every 1 must be rolled once again.

Now show the average throw after 1000000 tries and the probabilities for each result occurring:

Desired Result:

  avg(9.095855)
  2: 0.0023
  3: 0.0448
  4: 1.1075
  5: 2.8983
  6: 6.116
  7: 10.1234
  8: 15.4687
  9: 18.9496
  10: 19.3575
  11: 16.0886
  12: 9.8433


Is this relationship creepy? According to this XKCD comic, there is a formula to determine whether or not the age gap in a relationship is "creepy". This formula is defined as:

(Age/2) + 7

being the minimum age of people you can date.

Therefore a relationship is creepy if either of the people in said relationship are younger than the minimum age of the other.

Given the age of two people, can you output whether or not that relationship is creepy?

Rules

Your program should take two integers as input, the age of both people in the relationship. These can be taken in any reasonable format.
Your program must then output a truthy or falsy value describiing whether or not the relationship is "creepy" (Truthy = Creepy).
Standard loopholes are not allowed.
This puzzle is Code Golf, so the answer with the shortest source code in bytes wins

Test Cases

40, 40    - Not Creepy
18, 21    - Not Creepy
80, 32    - Creepy
15, 50    - Creepy
47, 10000 - Creepy
37, 38    - Not Creepy
22, 18    - Not Creepy

Python 3, 26 bytes

lambda x:max(x)/2+7>min(x)

Try it online!
The input is a list with both ages


Rearranging the sequence Introduction

Let's observe the following sequence (non-negative integers):

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

For example, let's take the first three numbers. These are 0, 1, 2. The numbers used in this sequence can be ordered in six different ways:

012   120
021   201
102   210

So, let's say that F(3) = 6. Another example is F(12). This contains the numbers:

0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11

Or the concatenated version:

01234567891011

To find the number of ways to rearrange this, we first need to look at the length of this string. The length of this string is 14. So we compute 14!. However, for example the ones can exchange places without disrupting the final string. There are 2 zeroes, so there are 2! ways to exhange the zeroes without disrupting the order. There are also 4 ones, so there are 4! ways to switch the ones. We divide the total by these two numbers:

This has 14! / (4! × 2!) = 1816214400 ways to arrange the string 01234567891011. So we can conclude that F(12) = 1816214400.

The task

Given N, output F(N). For the ones who don't need the introduction. To compute F(N), we first concatenate the first N non-negative integers (e.g. for N = 12, the concatenated string would be 01234567891011) and calculate the number of ways to arrange this string.

Test cases

Input:   Output:
0        1
1        1
2        2
3        6
4        24
5        120
6        720
7        5040
8        40320
9        362880
10       3628800
11       119750400
12       1816214400
13       43589145600
14       1111523212800
15       30169915776000

Note

Computing the answer must be computed within a time limit of 10 seconds, brute-forcing is disallowed.

This is code-golf, so the submission with the least amount of bytes wins!

ES6, 118 81 78 bytes

n=>[...[...Array(n).keys()].join``].map(c=>r/=(o[c]=-~o[c])/i++,o=[],i=r=1)&&r

Someone's bound to tell me there's a shorter way of concatenating the numbers up to n.

Saved a cool 37 bytes by taking @edc65's idea and running it on steroids. (Save an extra byte by using '|' instead of && but that limits the result to 31 bits.)

Edit: Saved 3 further bytes again thanks to @edc65.


Discord large text generator Input:

The input will be a string of any characters.

Output:

the output will be an emojified (discord emojis) version of the input string. The way it will work is as so:

Letters: a-z (case insensitive) will become ':regional_indicator_lowercase letter here:'

e.g 'A' will become ':regional_indicator_a:'

Digits: any digits (0-9) will become the word version of the digit like so ':digit:'

e.g '0' will become ':zero:'

Whitespace: any whitespace character that's matched with the regex: /\s/ will become ':white_large_square:'

e.g ' ' will become ':white_large_square:'

Important notes:

The ':' surrounding the emoji's are necessary or else it won't display correctly in discord.
Each emoji needs to be separated by 1 space or else it won't display correctly in discord.
Trailing whitespace is allowed in the final output.
Any other characters that it comes across should not be in the final output and will be ignored.

Examples:

#1: Input:

this is a test string 0123456789

output:

:regional_indicator_t: :regional_indicator_h: :regional_indicator_i: :regional_indicator_s: :white_large_square: :regional_indicator_i: :regional_indicator_s: :white_large_square: :regional_indicator_a: :white_large_square: :regional_indicator_t: :regional_indicator_e: :regional_indicator_s: :regional_indicator_t: :white_large_square: :regional_indicator_s: :regional_indicator_t: :regional_indicator_r: :regional_indicator_i: :regional_indicator_n: :regional_indicator_g: :white_large_square: :zero: :one: :two: :three: :four: :five: :six: :seven: :eight: :nine:

#2: input:

!?#$YAY 1234

output:

:regional_indicator_y: :regional_indicator_a: :regional_indicator_y: :white_large_square: :one: :two: :three: :four:

#3: input:

lots         of         spaces

output:

:regional_indicator_l: :regional_indicator_o: :regional_indicator_t: :regional_indicator_s: :white_large_square: :white_large_square: :white_large_square: :white_large_square: :white_large_square: :white_large_square: :white_large_square: :white_large_square: :white_large_square: :regional_indicator_o: :regional_indicator_f: :white_large_square: :white_large_square: :white_large_square: :white_large_square: :white_large_square: :white_large_square: :white_large_square: :white_large_square: :white_large_square: :regional_indicator_s: :regional_indicator_p: :regional_indicator_a: :regional_indicator_c: :regional_indicator_e: :regional_indicator_s:

Examples as shown in discord:

This is codegolf so the shortest code wins!

Python 2, 275 268 267 bytes

d=['']*256
d[48:58]='zero one two three four five six seven eight nine'.split()
d[9]=d[10]=d[32]='white_large_square'
d[65:90]=d[97:122]=map(lambda c:'regional_indicator_'+chr(c),range(97,122))
print' '.join((':%s:'%d[ord(c)])*(d[ord(c)]!='')for c in input()).strip()

It creates a large list of strings, iterates through the input string's characters and gets the string from the list using the character's ord value.
Works for ascii characters only. Replaces space, tab and newline only; any other whitespace will be discarded.

It did leave whitespaces in front so I had to strip it in the end.

I also tried doing it with regex, turned out to be longer (286 bytes):

import re
print re.sub('([ \t\n])|([a-z])|(\d)',lambda m:':'+['white_large_square','regional_indicator_'+m.group(m.lastindex),'zero one two three four five six seven eight nine'.split()[(ord(m.group(m.lastindex))-68)%10]][m.lastindex-1]+': ',re.sub('[^a-z0-9 \t\n]','',input().lower()))


Count unrooted, unlabeled binary trees of n nodes An unrooted binary tree is an unrooted tree (a graph that has single connected component and contains no cycles) where each vertex has exactly one or three neighbors. It is used in bioinformatics to show evolutionary relationships between species.
If such a tree has \$n\$ internal nodes, it necessarily has \$n+2\$ leaves. Therefore it always has an even number of vertices.
Challenge
Given a positive integer \$n\$, compute the number of distinct unrooted, unlabeled binary trees having \$2n\$ vertices. This is OEIS A000672. You may take \$2n\$ as input instead, and in that case, you may assume the input is always even.
The shortest code in bytes wins.
Illustration
n=1 (2 nodes, 1 possible)

O-O

n=2 (4 nodes, 1 possible)

O
 \
  O-O
 /
O

n=3 (6 nodes, 1 possible)

O     O
 \   /
  O-O
 /   \
O     O

n=4 (8 nodes, 1 possible)

O     O
 \   /
  O-O
 /   \
O     O-O
     /
    O

n=5 (10 nodes, 2 possible)

                  C
                   \
A     B       C     O-C
 \   /         \   /
  O-O     A     O-O
 /   \   /     /   \
A     O-O     C     O-C
     /   \         /
    B     A       C

n=6 (12 nodes, 2 possible)
(branching from A)  (branching from B or C)
    O                    O
   /                      \
O-O     O            O     O-O
   \   /              \   /
    O-O     O          O-O     O
   /   \   /          /   \   /
  O     O-O          O     O-O
       /   \              /   \
      O     O            O     O

Test cases
The values for first 20 terms (for \$n=1\dots 20\$) are as follows:
1, 1, 1, 1, 2, 2, 4, 6, 11, 18,
37, 66, 135, 265, 552, 1132, 2410, 5098, 11020, 23846

JavaScript (ES6), 265 bytes
This code actually builds all possible trees and filters out isomorphic results. This is quite slow for \$n>9\$ but \$a(10)=18\$ was checked locally.

n=>(K=A=>A.map(a=>[...a].sort()).sort(),g=(A,k)=>k>n-3?g[K(A)]||(N--,P=(p,a)=>a.map((v,i)=>P([...p,v],a.filter(_=>i--)))+a?1:g[K(A.map(a=>a.map(v=>~p[v])))]=1)(i=[],A.map(_=>--i)):A.map((a,i)=>a.some((v,j)=>~v?0:a[g([...A,[i,v,v]],a[j]=-~k),j]=v)))([[N=-1,N,N]])|~N

Try it online!
How?
Tree representation
Only internal nodes are stored explicitly as triplets \$[n_0,n_1,n_2]\$ where each value is either the 0-indexed ID of another internal node, or \$-1\$ for a leaf.
The final list of triplets can be normalized with the helper function \$K\$ which first sorts each triplet and then the entire list:
K = A => A.map(a => [...a].sort()).sort()

Main algorithm
The main recursive function \$g\$ builds all possible trees with \$n-1\$ internal nodes1. We start with an arbitrary root node \$[-1,-1,-1]\$ and attach each new internal node to the first available slot in one of the previous nodes.
For the first iteration, there's only one possible option:
$$\big[[-1,-1,-1]\big] \rightarrow \big[[1,-1,-1],[0,-1,-1]\big]$$
The underlying object of \$g\$ is also used to store all normalized trees that were already found.
Whenever a new tree is generated, we use the helper function \$P\$ to generate all permutations of the vertex identifiers. This allows us to store in \$g\$ all normalized trees that are isomorphic to the one we've found.

1: For obscure golfing reasons, the code actually generates at least 2 internal nodes. This is inconsistent for \$n<3\$ but leads to only one possible tree anyway, which is the expected result.


Counting creatures on a hexagonal tiling This challenge will have you count "creatures" in the tile game Palago.

  A creature is any closed shape that can be formed by Palago tiles of matching colour in a hexagonal grid.

The game Palago consists of tiles like this:

These tiles can be rotated \$120^\circ\$, \$240^\circ\$, or not at all and placed anywhere on a hexagonal grid. For example, here is a (red) creature that requires 12 tiles.

Challenge

The goal of this challenge is to write a program that takes an integer n as an input and computes the number of creatures (up to rotation and reflection) that require n tiles. The program should be able to handle up to n=10 on TIO. This is code-golf, so fewest bytes wins.

Example data

The values should match the data found in the "Creature Counts and Estimates" section of the creator's website. Namely

 n | output
---+-------
 1 | 0
 2 | 0
 3 | 1
 4 | 0
 5 | 1
 6 | 1
 7 | 2
 8 | 2
 9 | 9
10 | 13
11 | 37
12 | 81

JavaScript (Node.js),  578 ... 433  431 bytes

f=(n,T=[B=[N=0,0,0,1,1]])=>!n||T.some(([x,y,q,m])=>B.some((p,d)=>m>>d&1&&((p=x+~-s[d],q=y+~-s[d+2],t=T.find(([X,Y])=>X==p&Y==q))?(q=t[3])&(p=D[d*3+t[4]])^p?t[f(n,T,t[3]|=p),3]=q:0:[0,1,2].map(t=>f(n-1,[...T,[p,q,-p-q,D[d*3+t],t]])))),s="2100122",D=Buffer("160).(9!'8 &$<%"))|n>1||[0,1,2,1,2,0].some((_,d,A)=>B[k=T.map(a=>[(h=n=>Math.min(...T.map(R=a=>a[A[(d+n)%6]]))-R(a))(0),h(3),(x=(a[4]+d*2)%3,d>2)*x?3-x:x]).sort()])?N:B[k]=++N

Try it online! (\$n=1\$ to \$n=13\$)

How?

Directions and tiles

We use the following codes for the 6-direction compass and the tiles:

We assume that the creature is blue.

Connections

We need a table to know which parts of the creature need to be connected to other tiles when we enter a given tile in a given direction:

     |  T=0  |  T=1  |  T=2
-----+-------+-------+-------
 d=0 | 0,4,5 | 1,2,4 |   4
 d=1 | 0,3,5 | 1,2,3 |   3
 d=2 | 0,3,4 |   0   | 0,1,2
 d=3 | 3,4,5 |   5   | 1,2,5
 d=4 |   2   | 2,3,4 | 0,2,5
 d=5 |   1   | 1,3,4 | 0,1,5

Example:

If we enter a tile of type \$1\$ with direction \$5\$, we need to connect in directions \$1\$, \$3\$ and \$4\$:

But the way the tiles are designed, there can't possibly be a single missing connection in a single direction. A consequence of that is that we can ignore one direction entirely and still be able to detect if the path is closed or not. By convention, we are going to ignore direction \$5\$.

     |  T=0  |  T=1  |  T=2
-----+-------+-------+-------
 d=0 |  0,4  | 1,2,4 |   4
 d=1 |  0,3  | 1,2,3 |   3
 d=2 | 0,3,4 |   0   | 0,1,2
 d=3 |  3,4  |   -   |  1,2
 d=4 |   2   | 2,3,4 |  0,2

These updated sets of directions are first re-encoded as 5-bit integers, and then as ASCII characters with a fixed offset of \$+32\$:

     |  T=0  |  T=1  |  T=2              |  T=0  |  T=1  |  T=2
-----+-------+-------+-------       -----+-------+-------+-------
 d=0 |   17  |   22  |   16          d=0 |  "1"  |  "6"  |  "0"
 d=1 |    9  |   14  |    8          d=1 |  ")"  |  "."  |  "("
 d=2 |   25  |    1  |    7    -->   d=2 |  "9"  |  "!"  |  "'"
 d=3 |   24  |    0  |    6          d=3 |  "8"  |  " "  |  "&"
 d=4 |    4  |   28  |    5          d=4 |  "$"  |  "<"  |  "%"

Once flattened, this gives:

D = Buffer("160).(9!'8 &$<%")

Coordinates

To describe the positions of the tiles, we use cube coordinates with \$x+y+z=0\$:

Credits: www.redblobgames.com

It will make it easier to process rotations and reflections in the final step of the algorithm.

Tile encoding

The tiles are stored in a list, with no specific order. It means that we don't have to worry about some dynamic 2D allocation and we can easily iterate on the existing tiles. The downside is that, given specific coordinates, we need to find() the corresponding tile in the list.

Each tile is stored as \$(x, y, z, m, t)\$ where:

\$(x, y, z)\$ are the cube coordinates of the tile as described above
\$m\$ is the 5-bit mask of directions that need to be connected
\$t\$ is its type (\$0\$, \$1\$ or \$2\$)

Algorithm

We start with a single tile of type \$1\$ at \$(0,0,0)\$, with a required connection in direction \$0\$:

Therefore, this tile is encoded as [0,0,0,1,1].

At each iteration, we look for:

Tiles with missing connections: in this case, we successively try to complete the connection with each type of tile.
Tiles that are already connected but for which new connections need to be added because they have been reached in a different direction: in this case, we update the direction mask (with a bitwise OR) and force a new iteration.

If all connections are valid and we have reached the requested number of tiles, we still need to test whether it is a new creature or just a modified version of an existing one:

We apply the following transformations:

We perform the 3 possible rotations by replacing \$(x,y)\$ with \$(x,y)\$ (no rotation), \$(y,z)\$ (120°) or \$(z,x)\$ (240°), and updating the types of the tiles accordingly.
We perform the 3 corresponding reflections by replacing \$(x,y)\$ with \$(y,x)\$, \$(z,y)\$ or \$(x,z)\$, and updating the types of the tiles accordingly.

For each transformation, we translate all tiles such that the bottom-right corner is always located at \$(0,0)\$. (The signs of the coordinates are inverted in the process, which technically leads to another reflection, but this is harmless.)
We sort the tiles according to their coordinates and types. (This sort is processed in lexicographical order, which is fine.)
We finally coerce the resulting list to a key string which can be compared with the other keys.
We abort as soon as a known key is matched, or store the new key and increment the final result if none of the transformations lead to a known key.

Commented

f = (n, T = [B = [N = 0, 0, 0, 1, 1]]) =>
  // abort if n = 0
  !n ||
  // for each tile in T
  T.some(([x, y, q, m]) =>
    // for d = 0 to d = 4
    B.some((p, d) =>
      // if this tile requires a connection in this direction
      m >> d & 1 && (
        // look for a connected tile t at the corresponding position (p, q)
        (
          p = x + ~-s[d],
          q = y + ~-s[d + 2],
          t = T.find(([X, Y]) => X == p & Y == q)
        ) ?
          // if t exists, make sure that its direction mask is up-to-date
          (q = t[3]) & (p = D[d * 3 + t[4]]) ^ p ?
            // if it's not, update it and force a new iteration
            t[f(n, T, t[3] |= p), 3] = q
          :
            0
        :
          // if t does not exist, try each type of tile at this position
          [0, 1, 2].map(t => f(n - 1, [...T, [p, q, -p - q, D[d * 3 + t], t]]))
      )
    ),
    // s is used to apply (dx, dy)
    s = "2100122",
    // D holds the direction masks for the connections
    D = Buffer("160).(9!'8 &$<%")
  ) |
  // stop here if the above some() was truthy or we have more tiles to add
  n > 1 ||
  // otherwise, apply the transformations
  [0, 1, 2, 1, 2, 0].some((_, d, A) =>
    B[
      // compute the key k
      k =
        // by generating the updated tuples [x, y, type] and sorting them
        T.map(a =>
          [
            // transform the 1st coordinate
            (h = n => Math.min(...T.map(R = a => a[A[(d + n) % 6]])) - R(a))(0),
            // transform the 2nd coordinate
            h(3),
            // update the type
            (x = (a[4] + d * 2) % 3, d > 2) * x ? 3 - x : x
          ]
        ).sort()
    ]
  ) ?
    // if the key was found, just return N
    N
  :
    // if this is a new creature, store its key and increment N
    B[k] = ++N


Iterate over the neighborhood of a string Input
A string S of length between 2 and 30. The only letters in the string will be a or b.
Output
All strings within Levenshtein distance 2 of S. You must output all the strings without duplicates but in any order you like.
Example
If S = aaa then the output would be (in any order):
aa
abab
ab
aabba
aaaa
abaa
bbaaa
aba
bbaa
babaa
bba
abaaa
abaab
baaa
baab
baaaa
baba
aabaa
ba
abba
aaba
aabb
abbaa
abb
aabab
aaaaa
aaaab
baaba
a
aaaba
aaabb
aaa
aab
ababa
aaab
bab
baa
baaab

Constraints
Your code must be fast enough that it would run to completion on TIO when S is of length 30.  This is only to stop brute force solutions.

Haskell, 115 109 bytes

-6 thanks to Unrelated String

import Data.List
f=nub.(=<<)g.g
g=(=<<)h.(zip.inits<*>tails)
h(x,y)=[x++b++c|b<-["a","b",""],c<-[y,drop 1 y]]

Try it online!
Explanation:

f :: String -> [String]
f=nub    -- delete duplicates
 .(=<<)g -- apply g to every result (get all words with distance <= 2)
 .g      -- apply g once to the input (get all words with distance <= 1)

g :: String -> [String]
g=(=<<)h               -- apply h to every split and flatten the resulting list
 .(zip.inits<*>tails)  -- split the string at every possible position

{- |
h takes a pair of Strings (x,y the input split at some point) and returns all
combinations of x, one of a, b or nothing, and y with the first letter present
or removed
("he","llo") -> ["heallo","healo","hebllo","heblo","hello","helo"]
drop 1 is basically the same as tail with the difference that drop 1 [] returns
[] instead of throwing an error
-}
h :: (String,String) -> [String]
h(x,y)=[x++b++c|b<-["a","b",""],c<-[y,drop 1 y]]


Write a function that tells you which TWO of its lines has been removed In my previous code challenge, I asked you to write a function that tells you which of its lines has been removed.

The instructions were:

  Write a function that contains five lines.

  If you run the function as-is, it should return 0.

  If you remove any one of the five lines and run the function, it
  should tell you which of the lines has been removed (e.g., if you
  remove the final line it should return 5).

Now, let's try something a teensy bit more difficult.

Follow the same rules as above, but this time, the function should return an array telling you which TWO lines have been removed.

So, for instance, if I remove lines 1 and 5, the return value should be [1,5], and if I remove lines 3 and 4, the return value should be [3,4].

Again, if no lines are removed, the function should return 0.  Bonus points if you can also handle the one-line-removed case, but it's not strictly necessary that you do so.

Can you make use of helper functions?  Yes, but only if you have to.  A single self-contained function that pulls this off is the ideal.

As with the last challenge, the highest upvoted solution wins.  I'll pick the winner in a week, or sooner if no new submissions have been received in 24 hours.

Perl

sub foo {
    @a = (2..5);
    @a = grep $_ != 2, (@a ? @a : (1..5));
    @a = grep $_ != 3, (@a ? @a : (1..5));
    @a = grep $_ != 4, (@a ? @a : (1..5));
    @a = grep $_ != 5, (@a ? @a : (1..5));
}

This actually works for any number of lines removed (as long as it's not all the lines, that is), and can be trivially extended to more than 5 lines.  No helper functions are used, and it even uses only one statement per line.  It relies on the fact that, in the absence of an explicit return statement, the return value of a Perl function is the value of the last statement in it.

Note that (in list context) this code returns an empty list rather than the number 0 if no lines have been deleted.  This could be fixed (e.g. by appending "@a ? @a : 0;" to the last line), but would make the code uglier.  In any case, in scalar context it does return the number of deleted lines, which will be 0 if no lines have been removed. ;-)


stupid restrictions and desert So, you were sitting at your desk, golfing a program to calculate the first 20 digits of pi, and along comes your boss and throws your apple IIe out the window. You are now working on a new project and this computer does not yet have any text capability. None. No fonts. Nothing.

Now let's finish that program. Calculate and Display the first 20 characters of pi without using any fonts that are not part of your program. Your output can be displayed or written to standard out as an image file (jpeg, png, gif, svg(as long as you don't use any characters), bmp, xpm). You can use any language, but you can not use your language's font functions, text display or similar.

small bonus (10 characters) If it will work on a Lisa.

Edit: for those who didn't figure it out my inspiration was the first mac, and the title is a pun. A big kudos to @Sukminder whose animated gif is just cool. The contest is not over if a better answer comes along.

Python, 217 bytes

Requires the Python Imaging Library

import Image
x=p=141
i=Image.new('1',(x,11))
while~-p:x=p/2*x/p+2*10**19;p-=2
for c in str(x):[i.putpixel((j%7/5*4-~j%7/4*~j/7+p,j%7*3%14%8+j%14/10+2),1&ord('}`7gjO_a\177o'[int(c)])>>j%7)for j in range(17)];p+=7
i.show()

The byte count assumes that the escaped character \177 is replaced with its literal equivalent (char 127).

Output will appear as the following (it will open in your default *.bmp viewer):

Note that this could easily be parameterized to print any number of digits you like. The following will accept an integer input from stdin, and display that many digits:

import Image
n=input()
x=p=n*7|1
i=Image.new('1',(x,11))
while~-p:x=p/2*x/p+2*10**(n-1);p-=2
for c in str(x):[i.putpixel((j%7/5*4-~j%7/4*~j/7+p,j%7*3%14%8+j%14/10+2),1&ord('}`7gjO_a\177o'[int(c)])>>j%7)for j in range(17)];p+=7
i.show()

Output for n=80:

Pi Calculation

while~-p:x=p/2*x/p+2*10**19;p-=2

Yup, that's it. The formula used is the result of applying Euler's Transform to the Leibniz Series, and then factoring out each term from the remainder of the sum. The formula converges linearly; each digit requires log2(10) ≈ 3.32 iterations. For those interested in the derivation, see Appendix A.

Display

PIL is used for image generation, because it's the most convenient library that I know of. A blank 141×11 black and white bitmap is created, and then white lines are drawn on it in a seven-segment fashion, one pixel at a time. The positions required to draw each segment are stored in a bitmask string, with bits corresponding to the following positions:

 000
3   5
3   5
 111
4   6
4   6
 222

The bit of magic (j%7/5*4-~j%7/4*~j/7+p,j%7*3%14%8+j%14/10+2) produces the each pixel in the following order (base-18):

(2, 2), (2, 5), (2, 8), (1, 3), (1, 6), (5, 3), (5, 6),
(3, 2), (3, 5), (3, 8), (1, 4), (1, 7), (5, 4), (5, 7),
(4, 2), (4, 5), (4, 8)

 07e
3   5
a   c
 18f
4   6
b   d
 29g

Appendix A

Euler's Transform is a convergence acceleration technique that works for any series which displays absolute monotonic convergence. The resulting series will converge linearly, typically at the rate of one bit per term (note that if the original series was already super-linear, the resulting series will actually converge slower). The purely mathematical description is a bit hard to follow, so I'll be taking a procedural approach.

We'll start with the Leibniz Series:

Then split each term in half, combining neighboring terms:

Simplified:

Generalized:

Notice that the leading ½ didn't have a partner term, and thus was excluded from the rest of the sum. This is the first term of the transformed series. To find the next term, we repeat the process again:

And again:

And again:

And once more for good measure:

At this point we have the first five terms, and the sixth term is evident. This should be enough to generalize, so
we'll stop here. We'll start by factoring the numerators and denominators:

The denominators evidently contain a Double Factorial of 2n+1, so we'll patch that in:

Everything fits, except for the first two terms which have an unaccounted for 2 in the denominator. We can fix that by multiplying the entire expression by 2:

23 = 2·4, so:

The numerator can now be easily identified as n!.

Notice that the factor added to each successive term, n/(2n+1), approaches ½ as n becomes large, implying a linear convergence at the rate of one bit per term - this is in fact by design. A nice result, but it'd be even nicer without the factorials in there. What we can do here is to factor out each successive term from the rest of the sum, which will generate a nested expression:

This can be rewritten as a recurrence relation:

Where n counts backwards from ⌈log2(10)·d⌉ .. 0, where d is the number of digits required.

It might be interesting to note that the stable point of this recurrence is exactly 2 (or 4 if you've doubled it, as I have in the implmentation above), so you can save a number of iterations by initializing properly. Though, initializing to a random value you need elsewhere, and throwing a few extra iterations on the top is generally cheaper byte-wise.


Time to adjust some prices! I'm sure you know about the $9.99 price scheme, instead of using $10. Well, in your new job as a sys admin at a large retail store, they want prices to adhere to a similar scheme:

All prices are in whole dollars, no cents.
All prices should end with 5 or 9, rounding to the closest but up if the last digit is right between 5 and 9. (Applies to last digit 2 and 7)
Lowest input is $1, and the lowest outputted price should be $5.

Your input is a list of integers:

12
8
41
27
144
99
3

And the output should a list of the new prices. In the above case:

15
9
39
29
145
99
5


Is the word typeable with keys adjacent to each other? Before reading this I suggest reading this little puzzle: https://puzzling.stackexchange.com/questions/11408/longest-word-with-adjacent-letters-on-a-keyboard

I want you to make a program that takes one argument, a word (only lowercase letters), and outputs "Yes" if the word can be typed with adjacent keys on the keyboard (see the article) and "No" if the word can't be typed with adjacent letters.

Here's the keyboard layout used in this challenge:

 ┌───┬───┬───┬───┬───┬───┬───┬───┬───┬───┐
 | Q | W | E | R | T | Y | U | I | O | P |
 └─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┘
   | A | S | D | F | G | H | J | K | L |
   └─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴───┘
     | Z | X | C | V | B | N | M |
     └───┴───┴───┴───┴───┴───┴───┘

Remember: this is codegolf so the the shortest answer wins!

Pyth, 66
?"Yes".Am>2sm^-.uk2Cm.Dx"qwertyuiopasdfghjkl*zxcvbnm"b9.5dC,ztz"No

Try it here.
I was surprised to learn Pyth doesn't have a hypotenuse function, so this will likely be beat by a different language. I'll propose a hypotenuse function to Pyth, so this atrocity won't happen in the future.
Explanation
I transform the keyboard into this:
┌───┬───┬───┬───┬───┬───┬───┬───┬───┬───┐
| Q | W | E | R | T | Y | U | I | O | P |
└─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┐
  | A | S | D | F | G | H | J | K | L | * |
  └─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴───┴───┘
    | Z | X | C | V | B | N | M |
    └───┴───┴───┴───┴───┴───┴───┘

Which I then encode as "qwertyuiopasdfghjkl*zxcvbnm". Then I used divmod with modulo 9.5 to figure out the 2D coordinates of every key. Then I compute distances between consecutive keys, and check if the squared distance < 2.


Golf a Solubility Chart Given the name of a cation and anion, output "S" (soluble) or "I" (insoluble). The table we will be using is from wikipedia: https://en.wikipedia.org/wiki/Solubility_chart. It is copied at the end of the question for future reference.

Input: The cation, followed by the anion, separated by a space. The cation will be one of the following:

Lithium Sodium Potassium Ammonium Beryllium Magnesium Calcium
Strontium Barium Zinc Iron(II) Copper(II) Aluminium Iron(III) Lead(II) Silver

and the anion will be one of the following:

Fluoride Chloride Bromide Iodide Carbonate Chlorate Hydroxide Cyanide Cyanate
Thiocyanate Nitrate Oxide Phosphate Sulfate Dichromate

Each will have its first letter capitalized.

Example Input: Sodium Chloride

Output: A truthy value, or S, if it is soluble, falsey or I otherwise. If the wikipedia page lists anything else (e.g. slightly soluble, or reacts with water) or if the input is not in the form "cation anion," your program may do anything (undefined behavior), so it may output 'S', 'I', or anything else.

Table:

?,S,S,S,?,S,S,S,?,S,S,?,I,S,S
S,S,S,S,S,S,S,S,S,S,S,?,S,S,S
S,S,S,S,S,S,S,S,S,S,S,?,S,S,S
S,S,S,S,S,S,S,S,?,S,S,?,S,S,S
S,S,S,?,?,?,?,?,?,?,S,?,?,S,?
?,S,S,S,I,S,I,?,?,?,S,I,I,S,I
I,S,S,S,I,S,?,S,?,?,S,?,I,?,I
?,S,S,S,I,S,S,?,?,?,S,?,?,I,?
?,S,S,S,I,S,S,S,?,?,S,?,?,I,?
?,S,S,S,I,S,I,I,?,?,S,I,I,S,I
S,S,S,S,I,S,I,?,?,?,S,I,I,S,I
?,S,S,?,I,S,I,?,?,I,S,I,I,S,I
S,S,S,?,?,S,I,?,?,?,S,I,I,S,I
?,S,S,?,?,S,I,?,?,?,S,I,I,?,I
?,?,?,I,I,S,I,?,?,?,S,I,I,I,?
S,I,I,I,I,S,?,I,I,?,S,?,I,?,I

The rows are cations in the order listed above and the columns are anions. For example, since Magnesium Iodide is soluble, and Magnesium was the 6th cation and Iodide was the 4th anion, the 6th row and 4th column has the character 'S'. The ? indicates undefined behavior.

JavaScript (Node.js), 143 bytes

Returns 1 for soluble, 0 for insoluble.

s=>Buffer(`## 5)6.'04+ n:# (F* E"/$;&-"/"7&#.%`).map(c=>S+='1'.repeat(c-32)+0,S='')|S[parseInt(s.split` `[1].slice(1,7)+s[0]+s[1],35)%1325%508]

Try it online!

How?

Conversion of the input string to a lookup index

We first build a key by extracting the 2nd to 7th characters of the anion and adding the two first characters of the cation:

key = s.split` `[1].slice(1, 7) + s[0] + s[1]

Examples:

'Lithium Fluoride'  --> 'luoridLi'
'Sodium Fluoride'   --> 'luoridSo'
'Sodium Dichromate' --> 'ichromSo'
'Calcium Oxide'     --> 'xideCa'

We turn this into a lookup index by parsing it in base-35 and applying a modulo 1325 followed by a modulo 508 (brute-forced values):

parseInt(key, 35) % 1325 % 508

Compression of the lookup table

Because there are significantly more soluble pairs than insoluble ones, we  fill all unused entries in the lookup with soluble.

By encoding soluble with 1 and insoluble with 0, our lookup table essentially consists of long strings of 1's followed by a 0:

11101110011111111111111111111101111111110111111111111111111111101111111111111101111111011111
11111111111011111111111111111111011111111111001111111111111111111111111111111111111111111111
11111111111111111111111111111111011111111111111111111111111011100111111110111111111111111111
11111111111111111111011111111110011111111111111111111111111111111111110110111111111111111011
11011111111111111111111111111101111110111111111111101101111111111111110110111111111111111111
11111011111101110111111111111110111110

We compress it by storing the lengths of the strings of 1's as ASCII characters in the range [32-126].


Average an array until all numbers are (almost) equal Given an array of numbers, find out how many iterations of averaging* it takes for the average of every element to be no more than 1 higher or lower than the first element (absolute difference between the array's average and the first element is less than or equal to 1).
*Array averaging
To "average" a number in our array, we take the average of itself, the number behind it, and the number ahead of it. The last number of the array assumes the number ahead of it is the first number of the array (wrapping). Do this for all but the first number of the array, it needs to stay constant. The averages should all be applied at the same time (i.e. don't take the average of a number, put it back into the array, then average the next number).
Example:
ITERATION 0: [-1,4,3.5,7]
          1: [-1, 2.1666666666666665, 4.833333333333333, 3.1666666666666665]
          2: [-1, 2.0, 3.388888888888889, 2.3333333333333335]
          3: [-1, 1.462962962962963, 2.5740740740740744, 1.5740740740740742]
          4: [-1, 1.0123456790123457, 1.8703703703703705, 1.049382716049383]
          5: [-1, 0.6275720164609054, 1.3106995884773662, 0.6399176954732511]
          6: [-1, 0.31275720164609055, 0.8593964334705076, 0.3168724279835391]
          7: [-1, 0.057384545038866065, 0.4963420210333791, 0.058756287151348875]
abs(AVERAGE - FIRST_ELEMENT) = 0.903120713306 (IS LESS THAN 1)
OUTPUT: 7

Other I/O
INPUT >> OUTPUT
[-3, 9]  >>  2
[0, 0, 0, 0]  >>  0
[64, -66, -9, 78, -60]  >>  29
[9, 4, 5, 3, 3, 3, 10, 1, 1, 1]  >>  44
[-6, 5, -4, 3, -2, 1, -1, 2, -3, 4, -5, 6]  >>  70
[100000000, 2.11, 0.0, 16.88, 8.44, 6.33, 16.88, 100000000]  >>  348
[-8245, 6832, 9525, -3397, 5595, -9242, 1954, 6427, 36, -9647, -8887, 3062, -4424, -4806, -3803, 3608, -5115, -3725, -3308, -277]  >>  1038

Though not a part of the challenge; technically we are dealing with absolute values therefore complex numbers should also work. Your program does NOT need to handle complex numbers.:
[(20-1j), (5-4j), 7, (-0-100j)]  >>  15

Notes:

Other mathematical methods are accepted
You are to assume there are at least two elements in the array
This is code-golf so the shortest code in bytes wins

Perl 6,  83  82 bytes

->\a(\b,|c){(c,{[(b,|$_,b).rotor(3=>-2).map: *.sum/3]}...{(b+.sum)/a~~b-1..b+1})-1}

Try it

->\a(\b,|c){(c,{[(b,|$_,b).rotor(3=>-2).map: *.sum/3]}...{1>abs (b+.sum)/a -b})-1}

Try it (also works for complex numbers

Expanded

->      # pointy block lambda

  \a    # the input array
  (
    \b, # the first value
    |c  # all the rest of the values
  )

{
  (
    # generate a sequence

    c,                 # initialize the sequence starting with the second value

    {                  # bare block lambda with implicit parameter ｢$_｣

      [                # turn the result from a Seq into an array

        ( b, |$_, b )  # re-add the first element
                       # and add it to the end

        .rotor(3=>-2)  # grab 3 at a time, backing up 2

        .map: *.sum/3  # return the average for each sub sequence

      ]
    }

    ...                # keep calling that to generate values until

    {
      1 > abs ( b + .sum )/a - b     # they are almost equal
    }

  ) - 1 # count them and reduce by one (ignore initial value)
}


Magic: The Gathering, Paying for Spells For more MtG-goodness: Magic: The Gathering Combat with Abilities

Premise:

In Magic: the Gathering, you cast spells by paying their mana cost by tapping lands for the required amount. These lands can produce one of the five colors which are:

White (W)
Blue  (U)
Black (B)
Red   (R)
Green (G)

The cost is made up of two parts: a number which is the generic mana requirement, and a series of symbols representing the colored mana requirement. The number is the generic mana cost and can use any color of mana to satisfy it, e.g. (3) can be paid with WGG. The symbols are a 1:1 requirement of a specific color. e.g. WWUBR would require 2 white mana, 1 blue, 1 black and 1 red. The Generic part will always come before the Colored part. As a reminder, (0) is a valid cost and must be handled.

You can have costs that are entirely generic, or entirely colored, or both. For example, the following card has a cost of 4BB and is be paid with 4 of whatever colored mana and 2 black mana:

Lands in this challenge will each produce one mana. However, we will consider lands that can produce multiple colors but still only yield 1 mana. E.g. G will produce a green mana, WG can produce either 1 white or 1 green.

Input:

You will be given two inputs, a card's cost and a list of lands.

The card's cost can either be a string, or a tuple containing a number and a string for the colored part. If there's no generic part, you can pad the string/tuple with a 0.

The land list will be a list of strings where each one is what a given land can produce. This list can be empty (you have no lands). You can also take this as a list of ints using bit-mask logic but post your scheme if you do. Order is also up to you if it matters, otherwise it'll be assumed in WUBRG order.

#Example input formats
"4BB", ("WG","B","B") #
(4,"BB"), (7,3,3)     #Both should return falsy

Output:

A truthy value if you can successfully pay the cost given your lands and a falsey value if you cannot.

Rules:

You'll be guaranteed valid input
Mana will be assumed to always be in "WUBRG" order. If you want a different order, state so in your answer.
Colors will always be grouped in the cost, e.g. "WWUBBRG"
Input will use either all Uppercase or all lowercase, your choice.
You should be able to handle regex 127[WUBRG]{127} and 254 lands.
Standard loopholes forbidden
This is code-golf, shortest answer per language wins

Examples:

"0", ("")                => 1
"1BB", ("WG","B","B")    => 1
"BB", ("WG","B","B")     => 1
"WB", ("WG","B","B")     => 1
"1UB", ("W","U","B")     => 1
"1BB", ("WB","WB","WG")  => 1
"1", ("WG","B","B")      => 1
"1BB", ("WGR","WB","WB") => 1
"WUBRG", ("W","U","B","R","G")  => 1
"1WWUBB", ("W","WG","U","B","B","R")  => 1
"10BB", ("WGR","WB","WB","B","B","B","B","B","B","B","B","B") => 1

"R", ("")                => 0
"4", ("WG","B","B")      => 0
"1BB", ("WG","WB")       => 0
"1UB", ("WG","W","UB")   => 0
"1UBR", ("W","WG","UBR") => 0
"WUBRG", ("WUBRG")       => 0
"1WWUBB", ("W","WG","U","B","B")  => 0
"10UU", ("WGR","WB","WB","B","B","B","B","B","B","B","B","B") => 0

JavaScript (ES6), 91 bytes
Takes input as (cost)(lands):

\$cost\$ is a list of characters in BGRUW order, prefixed with the generic part, even when it's \$0\$
\$lands\$ is a list of strings.

a=>g=([c,...r],n=0,s=e='')=>[...n+s].sort()+e==a|(c&&[e,e,...c].some((c,i)=>g(r,n+!i,s+c)))

Try it online!
Commented
a =>                        // main function taking the array a[] describing the cost
  g = (                     // g = recursive function taking:
    [c, ...r],              //   c = next land string; r[] = remaining land strings
    n = 0,                  //   n = generic mana, initialized to 0
    s = e = ''              //   s = generated cost string, initialized to e = empty string
  ) =>                      //
    [...n + s].sort() + e   // prepend n to s, split, sort and force coercion to a string
    == a | (                // if this is matching a[], the test is successful
      c &&                  // if c is defined:
      [                     //   try the following recursive calls:
        e,                  //     - increment n and append nothing to s
        e,                  //     - do nothing
        ...c                //     - leave n unchanged and append a character to s
      ].some((c, i) =>      //   for each c at position i in the above array:
        g(r, n + !i, s + c) //     process the recursive call
      )                     //   end of some()
    )                       // end of the recursive part


Make Plan 9 Cat Turing Complete in as Few Bytes as Possible Your task is to modify the original Plan 9 cat tool for UNIX, in order to make it a fully turing complete language interpreter. You may make use of ANSI escape codes and the backspace character (\x08) to aid in this.

You must submit:

A modified version of the Plan 9 cat tool
A hexdump of the turing machine that can be run like so: cat turing_machine where turing_machine is the file you wrote.

Your score is the number of bytes you changed in the Plan 9 cat source code (where replacing a character counts as two bytes because you have to remove it and then replace it).

Here is the Plan 9 cat source code, taken from here.

#include <u.h>
#include <libc.h>

void
cat(int f, char *s)
{
    char buf[8192];
    long n;

    while((n=read(f, buf, (long)sizeof buf))>0)
        if(write(1, buf, n)!=n)
            sysfatal("write error copying %s: %r", s);
    if(n < 0)
        sysfatal("error reading %s: %r", s);
}

void
main(int argc, char *argv[])
{
    int f, i;

    argv0 = "cat";
    if(argc == 1)
        cat(0, "<stdin>");
    else for(i=1; i<argc; i++){
        f = open(argv[i], OREAD);
        if(f < 0)
            sysfatal("can't open %s: %r", argv[i]);
        else{
            cat(f, argv[i]);
            close(f);
        }
    }
    exits(0);
}

The headers in the above source are u.h and libc.h. Your code must conform to the C99 standard.

266 256 250 245 149 bytes (probably)

Thanks to @someone for suggesting using a cyclic tag system (originally I was using a modified version of Brainfuck).

Real computers aren't actually Turing-complete, because they have a finite amount of memory, whereas a Turing-machine has an infinite amount of memory. This is an implementation of a cyclic tag system with 9999 bytes of memory (although you could very easily change that), and with an initial word of 1 (I'm not entirely sure if cyclic tag systems with a fixed initial word are Turing-complete, but they probably are). The length of the program must be ≤8192, in this format:

00 (the first byte is ignored)
01 01 02 00 (first rule: 001 (null character to mark end))
02 02 02 01 02 00 (second rule: 11101)
03 (marks end of program)

There is no I/O. The added code should be C99-compliant (provided the input code doesn't use more than 9999 bytes of memory at once), but I'm pretty sure you can't (portably) declare main as void in C99.

#include <u.h>
#include <libc.h>

void
cat(int f, char *s)
{
    char buf[8192],m[9999];
    long n;

    while((n=read(f, buf, (long)sizeof buf))>0){char m[9999],*M=m+9998,*s=m,*e=m+1,*i=buf;*m=2;m[1]=0;do{for(i++;*i;i++){if(*i>2)i=buf+1;if(*s>1){*e++=*i;if(e>M)e=s;}}if(++s>M)s=m;}while(*s);
        /*if(write(1, buf, n)!=n)
            sysfatal("write error copying %s: %r");*/}
    if(n < 0)
        sysfatal("error reading %s: %r", s);
}

void
main(int argc, char *argv[])
{
    int f, i;

    argv0 = "cat";
    if(argc == 1)
        cat(0, "<stdin>");
    else for(i=1; i<argc; i++){
        f = open(argv[i], OREAD);
        if(f < 0)
            sysfatal("can't open %s: %r", argv[i]);
        else{
            cat(f, argv[i]);
            close(f);
        }
    }
    exits(0);
}

Slightly de-golfed, and printing each step:

#include <u.h>
#include <libc.h>

void
cat(int f, char *s)
{
    char buf[8192];
    size_t n;

    while((n=read(f, buf, (long)sizeof buf))>0) {
        char mem[9999];
        *mem=2;mem[1]=0;
        char* mem_end = &mem[9998];
        char*start=mem,*end=mem+1,*i=buf;
        do {
            for (char* p = start; p < end; p++) {
                printf("%d",*p - 1);
            }
            printf("\n");
            for (i++;*i;i++) {
                if(*i>2)i = buf+1;
                if (*start > 1){
                    *end++=*i;
                    if (end > mem_end)
                        end = mem;
                }
            }
            if (++start>mem_end)start=mem;
        } while (*start);
        /*if(write(1, buf, n)!=n)
            sysfatal("write error copying %s: %r");*/
    }
    if(n < 0)
        sysfatal("error reading %s: %r", s);
}

void
main(int argc, char *argv[])
{
    int f, i;

    argv0 = "cat";
    if(argc == 1)
        cat(0, "<stdin>");
    else for(i=1; i<argc; i++){
        f = open(argv[i], OREAD);
        if(f < 0)
            sysfatal("can't open %s: %r", argv[i]);
        else{
            cat(f, argv[i]);
            close(f);
        }
    }
    exits(0);
}

The following Python script converts any cyclic tag system into code which is accepted by this program:

productions =   [[0,0,1],
                 [0],
                 [0,0],
                 [0,1,1,1]]
f = open("turing_machine","w")
f.write("\0") # First byte is ignored
for production in productions:
    for c in production:
        f.write(chr(c+1))
    f.write("\0")
f.write("\3")
f.close()

When you run the output of this program with the de-golfed version, you get:

1
001
01
1
0111
111
110
1000
0000111
000111
00111
0111
111
11001
10010
001000
01000
1000
0000
000
00
0


Circles dividing the plane Task

You will be given a set of circles in the plane with their centers on the line y=0. It is guaranteed that no pair of circles has more than one common point.

Your task is to determine into how many regions into which the circles divide the plane. A region is an inclusion-maximal contiguous set of points not intersecting any of the circles.

You should write a program that computes this answer when given a description of the circles.

Here's an example:

On the left side you see the circles drawn in the plane. However, in the right half of the picture, the regions produced by the circles are colored distinctly (one color per region). There are six regions in this example.

Input

The first line of the input contains a number, N, the number of circle descriptions to follow. This line is optional, if your solution works without it, it's fine.

The following N lines each contain two integers, xi and ri > 0, representing a circle with center (xi, 0) and radius ri.

It is guaranteed that no pair of circles has more than one common point. It is further guaranteed that xi and ri do not exceed 10^9 in absolute value (so they comfortably fit into a 32-bit integer).

The input may be:

read from STDIN
read from a file named I in the current directory

Alternatively, the input could be:

available as a string (including newlines) in a global variable
on the stack

Output

This should be a single integer, the number to regions produced. This should be written to STDOUT or a file named O in the current directory.

Rules

Shortest code in bytes wins
+200 byte penalty if your code does not have a runtime + space complexity polynomial in n
-100 byte bonus for worst-case expected runtime + space complexity O(n log n)
-50 byte bonus for worst-case expected runtime + space complexity O(n)
-100 byte bonus for deterministic runtime + space complexity O(n)

While assessing the runtime:

Assume that hash tables have O(1) expected runtime for insert, delete and lookup, regardless of the sequence of operations and the input data. This may or may not be true, depending on whether the implementation uses randomization.
Assume that the builtin sort of your programming language takes deterministic O(n log n) time, where n is the size of the input sequence.
Assume that arithmetic operations on input numbers take only O(1) time.
Do not assume that input numbers are bound by a constant, although, for practical reasons, they are. This means that algorithms like radix sort or counting sort are not linear time. In general, very large constant factors should be avoided.

Examples

Input:

2
1 3
5 1

Output: 3

Input:

3
2 2
1 1
3 1

Output: 5

4
7 5
-9 11
11 9
0 20

Input:

9
38 14
-60 40
73 19
0 100
98 2
-15 5
39 15
-38 62
94 2

Output: 11

Hints

We can use the following idea for a very compact solution. Lets intersect the set of circles with the X axis and interpret the intersection points as nodes in a planar graph:

Every circle produces exactly 2 edges in this graph and up to two nodes. We can count the number of nodes by using a hash table to keep track of the total number of distinct left or right borders.

Then we can use the Euler characteristic formula to compute the number of faces of a drawing of the graph:

V - E + F - C = 1

F = E - V + C + 1

To compute C, the number of connected components, we can use a depth-first search.

Note: This problem idea is borrowed from a recent Croatian programming contest, but please don't cheat by looking at the solution outlines. :)

Ruby - 312 306 285 273 269 259 characters

This answer has been superseded by my other approach which uses considerably less characters and runs in O(n log n).

Okay, let's go. For starters, I just wanted a working implementation, so this is not algorithmically optimised yet. I sort the circles from largest to smallest, and build a tree (circles included in other circles are children of those larger ones). Both operations take O(n^2) at worst and O(n log n) at best. Then I iterate through the tree to count areas. If the children of a circle fill up its entire diameter, there are two new areas, otherwise there is just one. This iteration take O(n). So I have overall complexity O(n^2) and qualify for neither reward nor penalty.

This code expects the input without the number of circles to be stored in a variable s:

t=[]
s.lines.map{|x|x,r=x.split.map &:to_i;{d:2*r,l:x-r,c:[]}}.sort_by!{|c|-c[:d]}.map{|c|i=-1;n=t
while o=n[i+=1]
if 0>d=c[:l]-o[:l]
break
elsif o[:d]>d
n=o[:c]
i=-1
end
end
n[i,0]=c}
a=1
t.map &(b=->n{d=0
n[:c].each{|c|d+=c[:d]}.map &b
a+=d==n[:d]?2:1})
p a

Ungolfed version (expects input in variable string):

list = []
string.split("\n").map { |x|
  m = x.split
  x,radius = m.map &:to_i
  list<<{x:x, d:2*radius, l:x-radius, r:x+radius, children:[]}
}
list.sort_by! { |circle| -circle[:d] }
tree = []
list.map { |circle|
  i = -1
  node = tree
  while c=node[i+=1]
    if circle[:x]<c[:l]
      break
    elsif circle[:x]<c[:r]
      node = c[:children]
      i = -1
    end
  end
  node[i,0] = circle
}
areas = 1
tree.map &(count = -> node {
  d = 0
  i = -1
  while c=node[:children][i+=1]
    count.call c
    d += c[:d]
  end
  areas += d == node[:d] ? 2 : 1
})
p areas


Adding, the old-fashioned way Overview
The ancient Romans devised a number system using Latin letters, which served them well, and which is still used by modern civilization, though to a much smaller degree. In the time of its use, Romans would have had to learn to use and manipulate these numbers in order to be of much use for many applications. For example, if a man owned 35 oxen, and he procured 27 more, how would he know the new total other than counting them all? (Ok, that and using an abacus...) If the Romans could do it, surely we can figure it out as well.

Objective
Write the shortest algorithm/function/program that will add two Roman numerals together and output the result without converting the string representation of either input into a number.

Rules/Constraints
Because of historical/pre-medieval inconsistencies in formatting, I'm going to outline some non-standard (per modern usage) rules for orthography. See the value guide below as an example.

The letters I, X, C, and M can be repeated up to four times in succession, but no more. D, L, and V can never be repeated.
The letter immediately to the right of another letter in the Roman representation will be of the same or lesser value than that to its left.

In other words, VIIII == 9 but IX != 9 and is invalid/not allowed.

All input values will be 2,000 (MM) or less; no representation for numbers greater than M is necessary.
All input values will be a valid Roman numeral, pursuant to the rules above.
You may not convert any numbers to decimal, binary, or any other number system as part of your solution (you are welcome to use such a method to VERIFY your results).
This is code golf, so shortest code wins.

Value Guide

Symbol        Value
I             1
II            2
III           3
IIII          4
V             5
VIIII         9
X             10
XIIII         14
XXXXIIII      44
L             50
LXXXXVIIII    99
C             100
D             500
M             1,000

Examples

XII + VIII = XX (12 + 8 = 20)
MCCXXII + MCCXXII = MMCCCCXXXXIIII (1,222 + 1,222 = 2,444)
XXIIII + XXXXII = LXVI (24 + 42 = 66)

If any further clarification is needed, please ask.

Python, 100

s="IVXLCDM"
r=raw_input()
a=""
i=2
u=0
for c in s:r+=u/i*c;i=7-i;u=r.count(c);a+=u%i*c
print a[::-1]

Takes one string from input (e.g. VIII + XII or VIII + XII =).


The sequence of range-exponentiated integers Consider a triangle where the Nth row (1-indexed) is the array of the first N positive integer powers of N. Here are the first few rows:

N | Triangle

1 | 1
2 | 2 4
3 | 3 9 27
4 | 4 16 64 256
5 | 5 25 125 625 3125
...

Now if we concatenate those powers into a single sequence, we get OEIS A075363:
1, 2, 4, 3, 9, 27, 4, 16, 64, 256, 5, 25, 125, 625, 3125, 6, 36, 216, 1296, 7776, 46656 ...

Given an integer N, your task is to return the Nth term of this sequence. You can choose either 0 or 1-indexing.
Test cases
1-indexed:

N  -> Output

1  -> 1
2  -> 2
3  -> 4
5  -> 9
10 -> 256
12 -> 25
15 -> 3125

0-indexed:

N  -> Output

0  -> 1
1  -> 2
2  -> 4
4  -> 9
9  -> 256
11 -> 25
14 -> 3125

Note that these loopholes are forbidden by default. This is code-golf, thus the  shortest valid submission in each language wins!

Python 3, 39 bytes

1-indexed

f=lambda x,n=1:n**x*(x<=n)or f(x-n,n+1)

Try it online!