Jelly, 34 bytes

+þµFṢ
ç©ṀRœċL}Œċµç/⁼®µÐf
,Ṣ€,Ṛ$ḟ@ç

Returns a list of all possible pairs of dice up to ordering of dice and faces* (excluding any that are the same dice as the input pair).

Try it online!

This is a brute-forcer, and is not efficient (too slow to even run the 6-face test case at TIO).

+þµFṢ - Link 1, sorted sums: dieA, dieB
 þ    - outer product with
+     -     addition (make a table of the sums, a list of lists)
  µ   - monadic chain separation
   F  - flatten into one list
    Ṣ - sort

ç©ṀRœċL}Œċµç/⁼®µÐf - Link 2, all possible fair dice pairs (including input): dieA, dieB
ç                  - call the last link (1) as a dyad
 ©                 - save the result to the register for later use too
  Ṁ                - maximum (the largest sum)
   R               - range [1,2,...,maxSum]
       }           - use right argument (dice B) to turn the monad into a dyad:
      L            -     length
    œċ             - all combinations with replacement (i.e. all dice with faces between 1 and maxSum inclusive [overkill, but golfier than less])
        Œċ         - all pairs of these dice
          µ        - monadic chain separation
               µÐf - filter keep:
            /      -     reduce with:
           ç       -         last link (1) as a dyad (the sorted sums of the current pair)
              ®    -     retrieve register value (the sorted sums of the input pair)
             ⁼     -     equal?

,Ṣ€,Ṛ$ḟ@ç - Main link: dieA, dieB
,         - pair - [dieA, dieB]
 Ṣ€       - sort €ach - [dieASorted, dieBSorted]
     $    - last two links as a monad:
    Ṛ     -     reverse - [dieBSorted, dieASorted]
   ,      -     pair - [[dieASorted, dieBSorted], [dieBSorted, dieASorted]]
        ç - call the last link (2) as a dyad (with dieA, dieB)
       @  - reversed @rguments:
      ḟ   -     filter out - removes any results that are equivalent to the input pair.

* i.e. if [[1,1,4,4],[1,1,5,5]] is a possibility (like in one of the examples) there wont be a [[1,1,5,5],[1,1,4,4] or [[1,4,1,4],[1,1,5,5]], etc.


JavaScript, 29 28 bytes

Thanks @user5090812 for golfing off 1 byte

(a,b,x,y)=>a+x*((b+y-1)/y|0)

Try it online!

If it did not have to move x then y but was instead falling in a straight line it would be 18 bytes

(a,b,x,y)=>a+x*b/y


Pyth, 29 bytes

e.f>}ZPZsmq1lPs.D`Z}Fd.CU`Z2Q

Golfing, explanation, etc. to follow.


Retina, 44 20 bytes

Crossed out 44 is still regular 44 :(

+`'(\w).(.*).\B
$1$2

Assumes input in following format (in unary - counting character: '):
{number of repeats}{string}
For example: '''''''ABCDEFGHIJKLMNOP
There is no space between number of repeats and the string.

Thanks @MartinBüttner for shaving off 24 bytes!

Try it online!


Edit distance where a substitution only costs the first time

Naive recursive algorithm \$ O(\frac{(1+\sqrt2)^n}{\sqrt{n}}) \$
The basic idea is try adding, removing and replacing one character and recursive.

def f(str1, str2):
  l1, l2 = len(str1), len(str2)
  mapping = set()
  def g(p1, p2):
    if l1 == p1 or l2 == p2:
      return l1 + l2 - p1 - p2
    cost1 = g(p1 + 1, p2) + 1
    cost2 = g(p1, p2 + 1) + 1
    if str1[p1] != str2[p2] and (str1[p1], str2[p2]) not in mapping:
      mapping.add((str1[p1], str2[p2]))
      cost3 = g(p1 + 1, p2 + 1) + 1
      mapping.discard((str1[p1], str2[p2]))
    else:
      cost3 = g(p1 + 1, p2 + 1)
    return min(cost1, cost2, cost3)
  return g(0, 0)

The function g will be invoked \$ O(\frac{(1+\sqrt2)^n}{\sqrt{n}}) \$ times[1]. While adding, discarding, or checking an element in the mapping cost \$ O(1) \$ on average.
[1]: Based on https://oeis.org/A027618 ; I don't know why actually...


Find number of polynomials with a root which is a root of unity

GolfScript (111 107 chars)

~3\?:k,{2k*+3base{(}%:P,.*,{,{!}%-1+P{.,2$,>!{\[.0={*}+2$%\2$0={*}+%\]zip{{-}*}%\}*\0:x;{x|:x},.}do;,(},},,

Note: I disagree with some of the given test cases: I get

input   output
   1         2
   2         6
   3        12
   4        36
   5        94
   6       276
   7       790
   8      2270
   9      6412
  10     18334

Theory

Every algebraic number \$a\$ over a field \$F\$ has a minimal polynomial which is a factor of any polynomial \$P\$ in \$F[x]\$ for which \$P(a) = 0\$. For every integer \$n\$, the primitive \$n^\textrm{th}\$ roots of unity (those which are not roots of unity for any smaller \$n\$) share a minimal polynomial, the \$n^\textrm{th}\$ cyclotomic polynomial, whose degree is \$\varphi(n)\$.

So for input \$k\$ we can get an exact result by enumerating the possible functions and for each one looking for a non-trivial GCD with a cyclotomic polynomial of degree no greater than \$k\$.

There are two ways of doing that check: either by looping over the cyclotomic polynomials (or safe products thereof - e.g. \$x^n - 1\$ rather than the \$n^\textrm{th}\$ cyclotomic polynomial), or by multiplying them together and doing one GCD. My current approach is to take a very loose bound \$N = (k+1)^2\$ on the largest number whose totient is \$k\$ and then loop over \$x^i - 1\$. This is much faster than doing a single GCD with a massive polynomial, which can get some truly enormous intermediate values in the GCD, and I've managed to golf it ever so slightly more as well.

For speedier results at the cost of some characters, the bound can be improved moderately. Let \$M(n) = \max \{i : \varphi(i) = n\}\$. This has one major problem, which is that it's not well defined for odd \$n\$ greater than \$1\$ or for all even \$n\$. It also has the minor problem that it's not monotone. We need to use bound \$B(n) = \max \{i : \varphi(i) \le n\} = \max \{M(j) : j \le n\}\$.

H. Gupta defines \$A(n) = n \prod_{(p-1) \mid n} \frac{p}{p-1}\$ where \$p\$ prime and proves that \$M(n) \le A(n)\$. The bound is tight for \$n=1, 2, 8\$. Note that this is also not a monotone function: e.g. \$A(14) < A(12)\$.

We can modify the definition of \$A(n)\$ to get a looser bound which is monotone. First observe that since \$2 - 1\$ divides any integer, we can say that \$A(n) = 2n \prod_{(p-1) \mid n} \frac{p}{p-1}\$ where the \$p\$ must be odd primes. Then the number of multiplicands of the \$\prod\$ is bounded above by \$\log_3 (n+1)\$, and each multiplicand is bounded above by \$\frac32\$, so we get \$A(n) \le 2^{1 - \log_3 (n+1)} n(n+1)\$, and since this is monotone increasing for positive \$n\$ we also have \$B(n) \le 2^{1 - \log_3 (n+1)} n(n+1)\$. This bound overestimates by a factor of about \$2.5\$ at \$n=96\$, which isn't too shabby.

To use this bound, replace .* with ..(*2*2@3base,(?/). This is what I did to get the output for n=6 and n=7 in a reasonable amount of time.

More efficient calculation

;10,{
    )..).(*2*2@3base,(?/),{
        ):N,{!}%-1+
        N,0-{
            .N\%!{
                ~${
                    1$,\:Q,-),{
                        ;.0=\
                        [.0={*}+Q%]zip
                        {{-}*}%(;\
                    }%\
                }:^~;
            }{;}if
        }/
    }/]

    (\{,(1$)<},
    3@?:k,{
        2k*+3base{(}%[`{\^0-!*}+1$?]
    },
    ,p;
}/

prints the values for \$1\$ to \$10\$, taking about 8 minutes to get to \$8\$ and 125 minutes to get to \$10\$ on my computer. It applies the theory above more directly: it computes the actual cyclotomic polynomials (filtering to only include relevant ones), and then rather than doing GCD it suffices to do a division. Thus we replace a loop per (candidate, cyclotomic) tuple with a loop per cyclotomic, and makes the remaining division per (candidate, cyclotomic) work with smaller polynomials. It also has a quick-accept which speeds up testing for the successful candidates. I'm not sure whether it's possible to golf it to beat the GCD version, even ditching some of these optimisations.


JSON tips: filter objects from array of objects where object name is alpha

45 bytes

filtered_obj=objs.filter(n=>n.name=='Alpha');

This uses the filter function for arrays.

Ideone it!


Python, 42

i=4
while i<203:print 2*i,i*i-1,i*i+1;i+=2


Python 2: 55 bytes

f=lambda a,b,c,d,e:e+c-d*2and e*e/d**(d*d==e*c)or e*2-d

We check for the three cases as follows:

Check for arithmetic sequence: If e+c==d+d, output e+e-d
Check for geometric sequence: If e*c==d*d, output e*e/d
Otherwise, squared sequence: Output e*e.

Case 3 is used as the else-case to avoid the more-lengthy checking for successive squaring.

Case 1 is checked first, with Boolean short-circuiting to avoid checking Case 2 after a success, as this causes an error when d=0. There's a test case of all zeroes, so we can't cheat this by picking another position in place of d.

Afterwards, we can treat both Cases 2 and 3, since there's no risk of a divide-by-0 error. Noting that the choices are similar (e*e vs e*e/d), we combine them with an arithmetic expression by dividing by either d**1 for Case 3 or d**0 for Case 2. Although this division produces an integer value, we must use Python 2 (or //) to avoid float errors that case the largest-output test case to fail.

Thanks to @Will for inspiration on the code structure and a very-helpful test framework.


We're no strangers to code golf, you know the rules, and so do I

Ruby 576 557 556 (552) chars && PHP 543 chars

Another search-and-replace solution. Note that this form of solution is essentially a Grammar-based Compression Code http://en.wikipedia.org/wiki/Grammar-based_code
Check out http://www.cs.washington.edu/education/courses/csep590a/07au/lectures/lecture05small.pdf for a simple to understand compression example.

I've written the substitution rules so that the starting character for each substitution is computed (they are in sequential ASCII order); it need not be present in the transition data.

i=44
s="We; n7trangMsL8loT63Ke rules5s8d8I
AJull commit4nt'sChatFKink: of6CHldn'tRetKisJrom<ny@Ruy-/A= if?<sk 42DS'tLE 4?;Lo8bli=L7ee..
O,R1)O,R001)/-.."
"
I justCannaLE?2Gotta >u=Msta=.|
Ng1Nlet? downNrun<rH=5desMt?N>cryNsayRoodbyeNtE< lie5hurt?|

We'T3n each@Jor s8lSg6r hear9<ch: but6;Lo7hyL7BInsideCe both3Cha9Ro: S
We3KeRa45we;QplB|1)O)NgiT, nPgiT
(G|iT? up| howFJeel:
| know|me|<= |
YH|8s|o |t's been|ing|'re| a|nd|make? | yH| othM|A|ay it
| w|D|ell| I'm|G|ou|I| f|Lh| t|er|
NP|
(Ooh|eTrQ|RSna | g|on|ve".scan(/[^|]+/){s.gsub!((i+=1).chr,$&)}
puts s

implementation notes

The above solution is 556 chars long, but scores 552 with the removal of newlines from source code. It is slightly better scoring than the original 556 char solution I had that scored 554.
I use "known" instead of "know"; this makes the verse repetition identical and should make the compression better
I originally optimized the rules by repeatedly searching for the substitution that would yield the most decrease in current code size. However, I found that RiderOfGiraffe's substitution rules were (slightly) better than mine, so I'm now using a modified version of his rules.
I spent time reordering the rules so that a single substitution pass can decompress everything.
Due to the computed initial character in the substitution rules, my rule list has a rule for every character in a contiguous ASCII range. I found that having some "dummy" substitution rules was better for code size than having all real rules and coding a final text fixup substitution.
This example is small enough that you probably could successfully write a program to find the optimal (least total cost) set of rules. I would not expect doing this would yield size reductions of more than a few bytes.

older implementation

This older implementation has 576 characters and started with substitution rules from ugoren's bash/sed implementation. Ignoring the substitution variable renaming, my first 28 substitutions are exactly the same as those performed in ugoren's program. I added a few more to lower the overall byte count. This is possible because my rules are more efficiently represented than those in ugoren's implementation.

i=44
puts"WeM noHtraLersB loJ;6 C rules=so do $
& full commitment'sGhat<thinkDof;Gouldn'tKet this fromFny oCrKuy.
-&E if9ask me1~on't @ me:MBo bliEBHee//

3300-.//|
We'J6n each oCr forHo loL;r hear2FchDbut;MBoHhyBH7$nsideGe both6Gha2ADon
We6 CKame=weM>pl7|
$ justGanna @:1#otta 8uEerstaE/|
5?9up5let9down5runFrouE=desert:58cry5sayAodbye5@F lie=hurt:|(Ooh)5?, nI>?
(#4| how<feeliL
|t's been|(Ooh,K4|iJ9up)
|
NI>| know|ay it
|make9|: | you|
You| $'m |FE |Anna |giJ|tell|Ko| to|the|iL |nd| a| w| s|eJr|ve| g|ng|'re".split("|").inject{|m,o|m.gsub((i+=1).chr,o)}.tr('&~#$',"ADGI")

I did not try optimizing the substitution rules in this one.

contest notes

The search-and-replace decompression scheme works well for this contest because most languages have pre-built routines that can do this. With such a small amount of text to be generated, complex decompression schemes do not seem to be feasible winners.

I've used only ASCII text and also avoided using unprintable ASCII characters. With these restrictions, each character in your code can only represent up to a maximum of 6.6 bits of information; this is very different than to real compression techniques where you use all 8 bits. In some sense, it is not "fair" to compare to gzip/bzip2 code size because those algorithms will use all 8 bits. A fancier decompression algorithm may be possible if you can include traditionally unprintable ASCII in your strings AND each unprintable character is still written in your code as a single byte.

PHP Solution

<?=str_replace(range('-',T),split(q,"
I justCannaLE?2Gotta >u=Msta=.q
Ng1Nlet? downNrun<rH=5desMt?N>cryNsayRoodbyeNtE< lie5hurt?q

We'T3n each@Jor s8lSg6r hear9<ch: but6;Lo7hyL7BInsideCe both3Cha9Ro: S
We3KeRa45we;QplBq1)O)NgiT, nPgiT
(GqiT? upq howFJeel:
q knowqmeq<= q
YHq8sqo qt's beenqingq'req aqndqmake? q yHq othMqAqay it
q wqDqellq I'mqGqouqIq fqLhq tqerq
NPq
(OohqeTrQqRSna q gqonqve"),"We; n7trangMsL8loT63Ke rules5s8d8I
AJull commit4nt'sChatFKink: of6CHldn'tRetKisJrom<ny@Ruy-/A= if?<sk 42DS'tLE 4?;Lo8bli=L7ee..
O,R1)O,R001)/-..");

The above solution takes the PHP from "a sad dude" and combines it with my substitution rules. The PHP answer turns out to have the shortest decompression code. See http://ideone.com/XoW5t


Pyth, 24 bytes

?}KcsJsQlJmcsdldtPyJK":(

Try it online: Demonstration

Thanks to Dennis for noticing an error and golfing one byte.

Explanation:

?}KcsJsQlJmcsdldtPyJK":(   implicit: Q = evaluated input
      sQ                   all numbers of Q
     J                     save them in J
  KcsJ  lJ                 average of J (sum(J) / len(J))
                           store in K
          m     tPyJ       map each nonempty subset d of J to:
           csdld             average of d
?}                         if K in ^:
                    K        print K
                     ":(   else print sad-face


Charcoal, 19 bytes

Ｎθ←¹↙θ↓θ→↘θ↑↑θ←↖θ‖Ｂ

Try it online!


Score: 61

10 (no jQuery) + 15 (scaling cells) + 15 (the scaling part uses no CSS) + 20 (no labels) + 1 (upvotes)

When you click on a cell, it turns the current color.

JavaScript

var w = h = 20, color = 'red'
function createTable() {
    var tbl = document.createElement('table')
    tbl.id = 'tbl'
    for (var i = 0; i < h; i++) {
        var tr = document.createElement('tr')
        for (var i2 = 0; i2 < w; i2++) {
            var td = document.createElement('td')
            td.addEventListener('mousedown', draw)
            tr.appendChild(td)
        }
        tbl.appendChild(tr)
    }
    document.body.appendChild(tbl)
    return tbl
}
function killTable(tbl) {
    tbl.parentNode.removeChild(tbl)
}
var tbl = createTable()

function draw(e) {
   e.preventDefault()
   this.style.backgroundColor = color
}

document.getElementById('finalize').addEventListener('click', finalize)
function finalize() {
    var tds = document.getElementsByTagName('td')
    for (var i = 0; i < tds.length; i++) {
        tds[i].style.border = 'none'
        tds[i].removeEventListener('mousedown', draw)
    }
    document.getElementById('optionsWrapper').style.display = 'none'
}

document.getElementById('changeColor').addEventListener('click', changeColor)
function changeColor() {
    color = document.getElementById('color').value
}

document.getElementById('changeDims').addEventListener('click', changeDims)
function changeDims() {
    var dims = document.getElementById('dims').value.split('x')
    w = +dims[0], h = +dims[1]

    killTable(tbl)
    tbl = createTable()
}

HTML

    <button id='finalize'>Finalize</button>

    Color: <input id='color' type='text' value='red' /><button id='changeColor'>Go</button>

    Change dimensions (WARNING: will erase drawing): <input id='dims' type='text' value='20x20' /><button id='changeDims'>Go</button>

CSS

td {
    width: 5px;
    height: 5px;
    padding: 0;
    border: 1px solid black;
}

table {
    border-collapse: collapse;
}

JSFiddle

http://jsfiddle.net/D9u2N/1/

Screenshots

Zoomed in view (while editing, click to enlarge to full size):

Finalized view (zoomed out):


Python 3, 44 bytes (cracked)

'**:(((paraboloid / rabid,mad,immoral))):**'

No rounding. Floating point accuracy.


A program that outputs itself in reverse order

RProgN 2, 3 bytes

1
0

Try it online!

Pretty sure this has been submitted before, but here's one in RProgN 2.

It outputs

0
1


Jelly, 5 bytes

QfÆṣ⁼

A monadic link taking a list of two integers which returns 1 if they are a pair of amicable numbers and 0 otherwise.

Try it online!

How?

QfÆṣ⁼ - Link: pair of numbers L, [a, b]   e.g. [220,284]  or [6,6]  or [6,11]  or [100,52]
Q     - de-duplicate L                         [220,284]     [6]       [6,11]     [100,52]
  Æṣ  - proper divisor sum of L (vectorises)   [284,220]     [6]       [6,1]      [117,46]
 f    - filter keep left if in right           [220,284]     [6]       [6]        []
    ⁼ - equal to L?                            1             0         0          0


MATL, 25 24 21 bytes
Q:qJyZpbB!sEq*^YpYsXG

Try it at MATL online
Thanks @LuisMendo for a nice golfing session in chat that ultimately led to this 21 byte version, by suggesting Eq*^
Explanation
Q:q % Push 0:n
J   % Push 1i for later use.
y   % Duplicate 0:n from below
Zp  % Vector result of isprime()
b   % Bubble 0:n from bottom of stack
B!s % Sum of bits in binary representation
Eq  % Double minus one to get an odd number
*   % Multiply by isprime result to get either zero or aforementioned odd number
^   % Exponentiate 1i by an odd number or zero to get -i, 1 or i (corresponding to left turn, straight ahead, right turn).
Yp  % Cumulative product to get a vector of directions
Ys  % Cumulative sum to get vector of positions
XG  % Plot

Example for \$k=12345\$:


Mathematica, 46 bytes

{1,4^8}.Fold[##+{0,#&@@#}&,{1,0},#]~Mod~65521&

An anonymous function that takes an integer array and returns the Adler-32, with some improvements from miles and Martin (see comments).

miles' is also 46 bytes, but faster:

{1,4^8}.{Tr@#+1,Tr[Accumulate@#+1]}~Mod~65521&


Stacked, 51 50 bytes

Saved 1 byte thanks to @RickHitchcock - golfed regex

['^(##?#?) (.+)'[\#'5\-@k CS k*k rep LF#`]3/mrepl]

Try it online!

Anonymous function that takes input from the stack and leaves it on the stack.

Explanation

['^(##?#?) (.+)'[\#'5\-@k CS k*k rep LF#`]3/mrepl]
[                                            mrepl]   perform multiline replacement
 '^(##?#?) (.+)'                                     regex matching headers
                [                        ]3/         on each match:
                 \#'                                   count number of hashes
                    5\-                                5 - (^)
                       @k                              set k to number of repetitions
                          CS                           convert the header to a char string
                             k*                        repeat each char `k` times
                               k rep                   repeat said string `k` times
                                     LF#`              join by linefeeds


Perl 6, 14 bytes

{pick *,0..$_}

Try it

Expanded:

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

  pick      # choose randomly without repeats
    *,      # Whatever (all)
    0 .. $_ # Range from 0, to the input (inclusive)
}


Cops and Robbers: Redacted Primality (Cops' Thread)

8086 DOS COM, 87 bytes, score 19/87 ~= 0.2183

Cracked by NieDzejkob

1└╣██1█╛ü ¼<█t<< u≈¼<█t█,0|/<██+ô≈ßô☺├δδâ√█|█╞█S█Y╣██9┘t█ë╪1╥≈±○╥t█Aδ∩╞█S█N┤█║S█═!├A
$

This is a COM program; expects number as a command line argument, outputs Y or N. Limit: 65535 because 16 bit processor (sizeof(int) would be 2). Newline is 0x0D 0x0A on this platform. Yes you count 20 █ instead of 19 █. One of them's a real █ and has not been substituted. Muhahaha.

The space in position 10 is actually a NUL byte. The symbol for NUL is the same as space in the old VGA font.


Foo, PotatoLatte's answer

puts "Hello World!"

Try it online!

Ah, the bane of cops and robbers, Foo.


Jelly, 10 9 bytes

JạþTS×¬MḢ

Uses 1-based indexing. Try it online! or verify all test cases.

How it works

JạþTS×¬MḢ  Main link. Argument: A (array of Booleans)

J          Yield all indices of A.
   T       Yield all truthy indices of A.
 ạþ        Compute the table of absolute differences.
    S      Compute the sums of all columns.
           For each index, this yields the sum of all distances to occupied stalls.
     ×¬    Multiply each sum by the logical NOT of the corresponding Boolean in A.
           This zeroes sums that correspond to occupied stalls.
       M   Maximal; yield an array of all indices of maximal sums.
        Ḣ  Head; extract the first index.


Output the anti-clockwise inward spiral of a 2D array

R, 54 bytes

Several bytes saved by @Giuseppe and @J.Doe.

f=function(m)if(ncol(m))c(m[,1],f(t(m[nrow(m):1,-1])))

Try it online!

Recursively strip off the first column and row-reverse/transpose (making the bottom row the new first column) the rest of the matrix until you end up with only one column. Ungolfed "traditional" version:

f <- function(m) {
 if(ncol(m) == 1) {
    m
  } else {
    c(m[,1], f(t(m[nrow(m):1,-1])))
  }
}

It was pointed out that ncol(m) could be golfed to sum(m) to save another byte because we are allowed to assume positive integer matrix values. But I'll leave it like this since it works for all matrices (even matrices of strings!)


Find the next subpermutation of base-64 digits

GolfScript, 115 characters
:I,,0\{26,{65+.32+}%$10,{`}%'+/'++:A,1$-@*\)I<)A@-?+}/1I,,{A,\-*}/\)1$%\I,,{A,\-/\.2$%\2$/@\}%*>A\{1$=\[1$]-\}%\0<+

It passes all the test cases and works also for subpermutations of size other than 12 and for full permutations as well.
Online tester
Annotated Code:
:I                        # save input to variable I

### get the numerical index of the (sub)permutation
,,0\                      # push 0 (accumulator) and [0 .. <Length I>-1]
{                         # loop over

  ### construct the alphabet A
  26,{65+.32+}%$          # A-Z and a-z
  10,{`}%                 # 0-9
  '+/'++                  # append '+/'
  :A                      # save to variable A

  ,1$-                    # length of alphabet (i.e. 64) minus loop variable
                          # i.e. 64 -> 63 -> 62 -> 61 -> ...
                          # (this is the number of possible characters at
                          # the current position)
  @*                      # multiply the accumulator by this value
  \)I<                    # get anything from the input up to the current character
  )                       # extract the current character of input
  A@-                     # remove anything from the alphabet which was in the rest,
                          # i.e. the already processed chars cannot be used any more
  ?                       # find the index of the current input character
  +                       # add to the accumulator
}/

### calculate the total number of (sub)permutations
1                         # push 1 (accumulator)
I,,{                      # loop for i = 0 .. <Length I>-1
  A,\-                    # length of alphabet minus loop variable
  *                       # multiply to accumulator
}/

### at this point the stack is <Index of input (sub)permutation>
###   <Total number of (sub)permutations>
\)                        # increment the index (i.e. next (sub)permutation)
1$%                       # warp around for the last possible (sub)permutation
\                         # swap back order

### backwards transformation into the (sub)permutation space
I,,{                      # map for each index [0 .. <Length I>-1]
  A,\-/                   # divide the weight factor by length of alphabet minus
                          # loop variable
  \.2$%                   # take index % new weight factor
  \2$/                    # and index / new weight factor (result for the map operation)
  @\                      # re-order stack
}%
*>                        # get rid of 0 1 on the stack

### back to the alphabet
A\                        # push the full alphabet under the index array
{                         # map on the index array
  1$=                     # take the i-th element of the alphabet
  \[1$]-\                 # and reduce the alphabet by this characters
}%

\0<                       # transforms the remaining alphabet into an empty string
+                         # make string from array by joining with the empty string


Quandle Quandary Episode I: Identifying Finite Quandles

Haskell, 100 bytes

This answer uses transposed input.

q m=and$(elem<$>v<*>m)++[a#a==a&&a#b#c==a#c#(b#c)|a<-v,b<-v,c<-v]where v=[0..length m-1];i#j=m!!j!!i

Seems like I can't use a pattern guard to bind an infix operator, so I'm using where in this case.

(First version was 108 bytes but missed idempotency test, fixed version was 120 bytes, later versions had 108, 103 and 98 bytes but I had to realize thanks to @nimi that they were all wrong: of course I need to do the right-divisibility test (which implies closedness) before doing any dangerous !! operations,  but I could still use most of my later golfing ideas and with one more, it was 102 bytes, now improved by changing the operand order of # (which is nicer anyway to compensate the transposition) to make better use of its associating to the left)

Use like this:

*Main> q [[0,1,2,3],[0,1,3,2],[1,0,2,3],[0,1,2,3]]
False


If you need to use labels then for sure you'll want your label names to be as short as possible.  In fact taken to the extreme, you may even use the empty string as a label name:

:    # define label ""
p    # print pattern space
b    # infinite loop! - branch to label ""


Generating combinations without recursion

GolfScript (44 42 32 chars)

n%){\,=}+[[]]@1/{`{1$+}+%}%;\,n*

This takes input on stdin as a list of newline-separated strings followed by a line containing the desired subset size. It assumes that none of the input strings is empty. It takes some inspiration from Howard's solution, and can be shortened by two chars if using his input format:

~{\,=}+[[]]@1/{`{1$+}+%}%;\,n*

Output is a newline separated list of concatenations.

E.g.

$ golfscript.rb subcombo.gs <<END
> a
> b
> c
> 2
> END
ab
ac
bc

Note: this uses a horribly inefficient algorithm. A much nicer implementation in terms of performance is (62 61 chars)

n%)~\:S;2\?({2S,?<}{:s.~)&.s+.s^@4*/|}/{:x;S{;x.2/:x;1&},}%n*

which uses Gosper's hack.


Count from 1 to 100... in Roman Numerals

Perl 69 bytes

s;.;y/XVI60-9/CLXVIX/dfor$a[$_].="32e$&"%72726;gefor 1..100;print"@a"

Works by way of magic formula. The expression "32e$&"%72726 transforms each digit in the following manner:
0⇒32, 1⇒320, 2⇒3200, 3⇒32000, 4⇒29096, 5⇒56, 6⇒560, 7⇒5600, 8⇒56000, 9⇒50918

After applying the translation y/016/IXV/, we have this instead:
0⇒32, 1⇒32I, 2⇒32II, 3⇒32III, 4⇒29I9V, 5⇒5V, 6⇒5VI, 7⇒5VII, 8⇒5VIII, 9⇒5I9X8

The rest of the digits (2-57-9) are removed. Note that this could be improved by one byte by using a formula which translates 012 instead of 016, simplifying /XVI60-9/ to /XVI0-9/. I wasn't able to find one, but maybe you'll have better luck.

Once one digit has been transformed in this manner, the process repeats for the next digit, appending the result, and translating the previous XVIs to CLX at the same time the translation for the new digit occurs.

Update
Exhaustive search didn't reveal anything shorter. I did, however, find an alternative 69 byte solution:

s;.;y/XVI0-9/CLXIXV/dfor$a[$_].="57e$&"%474976;gefor 1..100;print"@a"

This one uses a 0-2 substitution for IXV, but has a modulo that's one digit longer.

Update: 66 65 bytes

This version is notably different, so I should probably say a few words about it. The formula it uses is actually one byte longer!

Unable to shorten the formula any more than it is, I decided to golf down what I had. It wasn't long until I remembered my old friend $\. When a print statment is issued, $\ is automatically appended to the end of the output. I was able to get rid of the awkward $a[$_] construction for a two byte improvement:

s;.;y/XVI60-9/CLXVIX/dfor$\.="32e$&"%72726;ge,$\=!print$"for 1..100

Much better, but that $\=!print$" still looked a bit verbose. I then remembered an alternative, equal length formula I had found which didn't contain the number 3 in any of its digit transforms. So, it should be possible to use $\=2+print instead, and substitute the resulting 3 with a space:

s;.;y/XVI0-9/CLXIIX V/dfor$\.="8e$&"%61535;ge,$\=2+print for 1..100

Also 67 bytes, due to the necessary whitespace between print and for.

  Edit: This can be improved by one byte, by moving the print to the front:

$\=2+print!s;.;y/XVI0-9/CLXIIX V/dfor$\.="8e$&"%61535;gefor 1..100

  Because the substitution needs to evaluate completely before the print, the assignment to $\ will still occur last. Removing the whitespace between ge and for will issue a deprecation warning, but is otherwise valid.

But, if there were a formula which didn't use a 1 anywhere, $\=2+print becomes $\=print for another two bytes worth of savings. Even if it were one byte longer, it'd still be an improvement.

As it turns out, such a formula does exist, but it is one byte longer than the original, resulting in a final score of 65 bytes:

$\=print!s;.;y/XVI60-9/CLXXI V/dfor$\.="37e$&"%97366;gefor 1..100

Methodology

The question was asked how one might go about finding such a formula. In general, finding a magic formula to generalize any set of data is matter of probability. That is, you want to choose a form which is as likely as possible to produce something similar to the desired result.

Examing the first few roman numerals:

0:
1: I
2: II
3: III
4: IV
5: V
6: VI
7: VII
8: VIII
9: IX

there is some regularity to be seen. Specifically, from 0-3 and then again from 5-8, each successive term increases in length by one numeral. If we wanted to create a mapping from digits to numerals, we would want to have an expression that also increases in length by one digit for each successive term. A logical choice is k • 10d where d is the corresponding digit, and k is any integer constant.

This works for 0-3, but 4 needs to break the pattern. What we can do here is tack on a modulo:
k • 10d % m, where m is somewhere between k • 103 and k • 104. This will leave the range 0-3 untouched, and modify 4 such that it won't contain four Is. If we additionally constrain our search algorithm such that the modular residue of 5, let's call it j, is less than m / 1000, this will ensure that we also have regularity from 5-8 as well. The result is something like this:

0: k
1: k0
2: k00
3: k000
4: ????
5: j
6: j0
7: j00
8: j000
9: ????

As you can see, if we replace 0 with I, 0-3 and 5-8 are all guaranteed to be mapped correctly! The values for 4 and 9 need to be brute forced though. Specifically, 4 needs to contain one 0 and one j (in that order), and 9 needs to contain one 0, followed by one other digit that doesn't appear anywhere else. Certainly, there are a number of other formulae, which by some fluke of a coincidence might produce the desired result. Some of them may even be shorter. But I don't think there are any which are as likely to succeed as this one.

I also experimented with multiple replacements for I and/or V with some success. But alas, nothing shorter than what I already had. Here is a list of the shortest solutions I found (the number of solutions 1-2 bytes heavier are too many to list):

y/XVI60-9/CLXVIX/dfor$\.="32e$&"%72726
y/XVI0-9/CLXIXV/dfor$\.="57e$&"%474976
y/XVI0-9/CLXIVXI/dfor$\.="49e$&"%87971

y/XVI0-9/CLXIIXIV/dfor$\.="7e$&"%10606  #
y/XVI0-9/CLXIIXIV/dfor$\.="7e$&"%15909  # These are all essentially the same
y/XVI0-9/CLXIIXIV/dfor$\.="7e$&"%31818  #

y/XVI0-9/CLXIIX V/dfor$\.="8e$&"%61535  # Doesn't contain 3 anywhere

y/XVI60-9/CLXXI V/dfor$\.="37e$&"%97366 # Doesn't contain 1 anywhere


64-bit Perl, 67 68

Perl 5.10 or later, run with perl -E 'code here' or perl -M5.010 filename

map{$d++,/^S/||$w++if$_=`date -d@ARGV-$_`}1..31;say int.5+100*$w/$d

Concessions to code size:

locale-sensitive: it counts as work days the days whose date output don't start with a capital S.  Run under LC_ALL=C if in doubt.
output is pure and well-formatted, but there's "garbage" on stderr on months shorter than 31.  2> /dev/null if upset.
for some reason, my version of date considers 2817-12 an invalid month.  Who knew, GNU new apocalypse is due! Requires a 64 bit build of date for dates after 2038.  (Thanks Joey)


R, 43 bytes

f=function(s,n)"if"(n,function()f(s,n-1),s)

Try it online!

Returns a zero-argument function that recursively calls f with n set to n-1. n successive function applications returns s.


Arranging arbitrary shapes to fill a rectangular space

Python 2, 434 bytes

lambda s:F([[' ']*sum(map(lambda s:len(s[0]),s)) for _ in' '*sum(map(len,s))],s)
L=len
R=range
def F(a,s):
 if not s:return len(set(tuple(l)for l in a if'X'in l))==len(set(tuple(l)for l in zip(*a)if'X'in l))==1
 c=s[0];h,w=L(c),L(c[0])
 for i in R(L(a)-h):
	for j in R(L(a[0])-w):
	 T=1;A=[l[:]for l in a]
	 for y in R(h):
		for x in R(w):
		 C=c[y][x]
		 if C>' ':T&=A[y+i][x+j]<'!';A[y+i][x+j]=C
	 r=T and F(A,s[1:])
	 if r:return r

Try it online!

Takes input as a list of lists.

Returns True or None

Assumes that each line in a shape is padded to the length of that shape.

(based on my answer to Do the figures fit?)


GNU Octave, 55 56 58 78 87* 93 chars

a=t(:,1);b=t(:,2);-4*max(2*(g=a.*b)-3*(a+b)+4,0)+g.*--g

Octave doesn't take input from STDIN, so you've got to provide the input in the program:

t = [
    1 7;
    2 2;
    2 3;
    4 5;
    5000 6000
];                % test cases

a=t(:,1);b=t(:,2);-4*max(2*(g=a.*b)-3*(a+b)+4,0)+g.*--g

The logic is as follows:

nchoosek(n*m, 2) gives us the number of combinations of two positions we can have on a N*M board. We then multiply it by two since we have two different knights.

Then we work out how many 3*2 blocks fit in an N*M board. For each 3*2 block there are 4 different positions our knights can be attacking each other. So we multiply it by 4 and subtract it from the value we calculated above.

*thanks to a simplification of the nchoosek I shamelessly stole from Matt.

Edit

I've just tested this on my laptop to make sure it meets the time requirements.

It will compute 500,000 10,000,000 test cases in an average of 0.918787 0.231201 seconds


Bash+common Linux utilities, 12 or 16 bytes
pkill "$1"||"$@"

If we can assume no whitespace in the program name and arg, then we can drop the quotes for a score of 12:
pkill $1||$@


Jelly, 8 bytes

Œ!ṗµfZ€L

Brute force solution. Inputs 5 and higher will time out on TIO.

Try it online!

How it works

Œ!ṗµfZ€L  Main link. Argument: n

Œ!        Generate all permutations of R := [1, ..., n].
  ṗ       Take the n-th Cartesian power, yielding the array A of all n×n matrices
          whose rows are permutations of R.
   µ      New chain. Argument: A
     Z€   Zip each; transpose each matrix in A, yielding the array B of all n×n
          matrices whose columns are permutations of R.
    f     Filter; keep only matrices that appear in A and B.
       L  Compute the length, counting the kept matrices.


Python 2, 74 72 bytes

lambda s:':'.join(['AM','PM','00',`ord(c)-97`]['az '.find(c)]for c in s)

Try it online!

Takes input as all lowercase


Jelly, 12 bytes

ṢṖḊȯµÆmḤær0H

Try it online!

    µ           Take
Ṣ               the input sorted,
 Ṗ              without its last
  Ḋ             or first element,
   ȯ            or the unchanged input if that's empty,
     Æm         then calculate the mean,
       Ḥ        double it,
        ær      round it to the nearest multiple of
          0     10^-0 (= 1),
           H    and halve it.

A version which rounds halves down, in accordance with the spec at the expense of the second test case:

Jelly, 12 bytes

ṢṖḊȯµÆmḤ_.ĊH

Try it online!

The rounding method here is closer to Jonathan Allan's:

Ḥ        Double,
 _       subtract
  .      one half,
   Ċ     round up,
    H    and halve.


Python 3,262 236 209 196 179 114 93 92  97 bytes

def f(n):
 m=k=1;s=''
 while n:m*=k*k;k+=1;n-=m%k
 while k:s=chr(~-k%26+97)+s;k=~-k//26
 return s

Try it online!

Fixed a bug mentioned by @benrg about getting a wrong output for the input 123.

Thanks to:
- @AdmBorkBork for help me getting started and save a few bytes
- @Sriotchilism O'Zaic for saving me 6 bytes
- @mypetlion for saving me 65 bytes and bringing me under 150 bytes :)
- @dingledooper for saving me 21 bytes and bringing me under 100 bytes :D
- @Jitse for saving 1 byte

98 bytes

f=lambda n,i=1,p=1:n and-~f(n-p%i,i+1,p*i*i)
g=lambda n,s='':n and g(~-n//26,chr(~-n%26+97)+s)or s

Try it online!


Format microseconds as hours:minutes:seconds, etc

Python 2, 82 79 bytes

n=input()
o=""
for k in[1000]*2+[60]*3:o=":%0*d"%(k%7/2,n%k)+o;n/=k
print o[1:]

Builds the string, iterating through a series of divmods. The only fancy bit is the %7/2, which maps 1000 -> 3 and 60 -> 2.


Use the ending conditions

Suppose you have a function reversing a list:

r([H|T])->[T]++r(H);r([])->[].

Since this is the only condition left, this can be golfed into:

r([H|T])->r(T)++[H];r(_)->[].

Or, since this is an identity function:

r([H|T])->r(T)++[H];r(I)->I.

You can also abuse the wild-cards in if statements. E.g.

if A<B->A;true->B end.

This can be golfed into:

if A<B->A;_->B end.


K (ngn/k), 37 32 bytes

{$[|/x=r:x[,/|2 0N#<x]@<<x;0;r]}

Try it online!

{ } function with argument x

$[ ; ; ] if-then-else

<x "grade" - the sorting permutation for x

<<x "rankings" - the inverse of the sorting permutation

2 0N# split in two halves (or when length is odd - only approximately)

| swap the halves

,/ concatenate

x[ ] use as indices in x

..@<<x use <<x as indices in the previous result (a@b is alternative syntax for a[b])

r: assign to r - the potential result

x=r boolean list of which elements of x are equal to their counterparts in r

|/ or-reduction, i.e. "any?"


String of alphanumeric characters to a sorted list of comma-separated ranges

Ruby, 87-16=71

EDIT:  Had to add some characters so that two-character ranges are displayed correctly.  Also using ?[ instead of ?Z to fix a bug with ranges ending in Z.

$><<[*?0..?[].join.gsub(/[^ABC321STPpJqZZr0]/i,$/).gsub(/\B.+\B/,?-).scan(/.-.|./)*', '

You can see the Ideone run here.


Pyth, 16 bytes
Still new to Pyth, but this looks promising..
s_`smvs.[_d0lzcz

The idea here is simple. To do backwards addition, you need backwards numbers. We take the input, reverse it, make sure that it has same number of digits be adding trailing 0, sum the two numbers, reverse it again and make sure no leading zero exists.
Code expansion
              cz          # Take the input and Python split it. Splits on space automatically
    m                     # Now we map over these two strings
         _d               # Reverse the string
       .[  0lz            # Pad it with 0 on right so that its length is same as input length
     vs                   # We have array of character and number, stringify and eval
   s                      # Sum the numbers in array
  `                       # Stringify
 _                        # Reverse
s                         # Convert back to number, removing leading 0

Try it online here


What golfing languages are better suited as an object for genetic programming?

I would be surprised if any golfing languages were appropriate for genetic programming. Pyth, at least, is very unlikely to form a valid program with random bytes, and I believe the same is true of most golfing languages. This, if nothing else, probably invalidates them as genetic programming languages.


Edit: for people reading this who don't  know APL at all but want  to take it up, Mastering Dyalog APL is a very good resource.

Evaluation is strictly right-to-left. This includes setting variables, so take advantage of it.
2+a, 1+a←1  -> 3 4
a is set to 1, 1+a evaluates to 2, a,2 evaluates to 1 2 and 2+1 2 evaluates to 3 4.

Like C, ← can be combined with a function, i.e. a +← 3. Unlike C, this is generic: foo F← bar sets foo to F bar. Somewhat unintuitively, as an expression this returns bar, not F bar.
It works with anonymous functions too:
       a←0
       a+←3 ⋄ a
 3
       a+←3 ⋄ a
 6
       a { ⍵/'!' } ←4 ⋄ a
 !!!!

You can assign to an array: A[3]←8, like you'd expect. But you can also assign multiple items at the same time: A[3 5 6]←9 1 4, or even A[3 5 6]←9, setting them all to the same item. You can, of course, add a function to the ← here too. The  function will then be applied to each element separately, as if you did F¨.

⍨ is your friend, even if he doesn't look too happy about it.
1. If `F` is dyadic, dyadic `⍨` switches the arguments: `a F b` <-> `b F⍨ a`. This comes in handy when golfing because it can save you from using braces:

     (F G H x) K y      <->     y K⍨ F G H x

This does change the evaluation order, as the right hand is always evaluated before the left hand.

2. If `F` is dyadic, *monadic* `⍨` applies the same argument to both sides of the function:

           5⍴5
     5 5 5 5 5
           ⍴⍨5
     5 5 5 5 5

   The argument is only evaluated once. This particularly comes in handy with outer products, i.e. to compare each value in an array with the other values in the same array, you can use `∘.=⍨` instead of having to do `x∘.=x←(whatever)`.

3. If `F` is monadic, `⍨` does nothing, but it does separate the function from the argument. So it can still save you braces if the function is complex:

           {⍵+3}⍣5 6
           ∇{⍵+3}
          ∇ ⍣ 5 6
           ({⍵+3}⍣5)6
     21
           {⍵+3}⍣5⍨6
     21

Learn the idioms! Then golf the idioms. For example:
 ((((1↑⍴X),⍴Y)↑X)^.=Y)⌿X

can be mechanically transformed into:
 X⌿⍨Y^.=⍨X↑⍨(1↑⍴X),⍴Y

and then further into:
 X⌿⍨Y^.=⍨X↑⍨(⊃⍴X),⍴Y

⊃ (first) being equivalent to 1↑ (take one) in this case. And possibly:
 X⌿⍨Y^.=⍨X↑⍨(≢X),⍴Y

≢ (tally) being equivalent to ⊃⍴ (the first element of the shape) for all but scalars.


Ruby, 370 339 305 bytes
Latest edit: a few bytes saved by rearrangement of the plotting formulas and removal of unnecessary brackets. A massive saving by rewriting the generation of the cube - I never knew Ruby had a builtin for Cartesian Products!
->s{q=[-66,0,71].product [-87,0,89],[-79,0,82]
s.map{|c|m="LDBRUF".index c[0];e=m/3*2-1
c.sub(/[i']/,"33").chars{q.map{|j|j[m%=3]*e>0&&(j[m-2],j[m-1]=j[m-1]*e,-j[m-2]*e)}}}
t=[" "*12]*9*$/
q.map{|r|a,b,c=r.map{|i|i<=>0}
3.times{|i|r[i]!=0&&t[56+[a*3-a*c-d=b*13,a-d*3+d*c,3-d-c*3+c*a][i]]=r[i].abs.chr}}
t}

Anonymous function.
Accepts an array of strings, each representing one face turn (a single string with spaces between each face turn is an additional 6 bytes.)
Returns a 9x12 rectangular string.
Brief explanation
This is closely based on a concept from my answer to this question, which in turn was based on a similar concept by Jan Dvorak.
The first line generates a 27 element array, representing the 27 cubies. Each cubie is represented by a 3 dimensional vector in which the sign represents its current position and the magnitude of each coordinate represents the ascii code for the colour of the sticker.
Example move: for R, for each cubie check if the x coordinate is >0 and if so rotate 90 degrees by swapping the y and z coordinates and swapping the sign of one of them.
Take a 9x12 array of spaces and plot the cube into it. For each cubie and axis we check if the sticker exists (coordinate in that axis nonzero), and work out where it is to go. Then we take the coordinate and perform .abs.chr to change the number into the required character and plot it.
Ungolfed in test program (per 339 byte edit)
f=->s{

  q=(0..26).map{|i|                         #Build an array of 27 cubies
    [[-66,0,71][i%3],                       #x coordinate B.G
     [-87,0,89][i/3%3],                     #y coordinate Y.W
     [-79,0,82][i/9]]                       #z coordinate O.R
  }

  s.map{|c|                                 #For each move in the input array
    m="LDBRUF".index(c[0]);e=m/3*2-1        #m=face to move. e=-1 for LDB, +1 for RUF.
    c.sub(/[i']/,"33").chars{               #Substitute "i" and "'" for "33" so chars in string = clockwise 1/4 turns required. For each char...
      q.map{|j|j[m%=3]*e>0&&                #...and each cubie, m%3 tells the relevant axis. if coordinate*e>1 rotate the cubie 1/4 turn.
        (j[m-2],j[m-1]=j[m-1]*e,-j[m-2]*e)} #Swap other two axes and change sign of one. e performs sign change if necessary for LDB.
    }
  }

  t=[" "*12]*9*$/                           #Make an array of 9 strings of 12 spaces, then make a single string by joining them with newlines
  q.map{|r|                                 #For each cubie
    a,b,c=r.map{|i|i<=>0}                   #make a normalised (-1,0,1) copy of each coordinate.
    d=b*13                                  #13 chars per line, d will be useful for plotting to the correct line of the output.
    3.times{|i|                             #For each of the 3 coordinates of the cubie
      r[i]!=0&&                             #if zero, sticker doesn't exist (edges and centres have <3 stickers.) If not zero plot the sticker.
      t[[56-d+a*3-a*c,                      #Calculate position on plot for x (L/R faces),
         56-d*3+d*c+a,                      #Calculate position on plot for y (D/U faces),
         59-d-c*3+c*a][i]]=                 #Calculate position on plot for z (B/F faces). Select the correct axis.
      r[i].abs.chr                          #Convert the coordinate to a character and assign to the correct space on the output plot.
    }
  }
t}                                          #Return the output string.

puts f[gets.chomp.split]

Output
Checkerboard
U2 D2 F2 B2 L2 R2
   YWY
   WYW
   YWY
BGBRORGBGORO
GBGOROBGBROR
BGBRORGBGORO
   WYW
   YWY
   WYW

6-spot
U D' R L' F B' U D'
   RRR
   RYR
   RRR
WWWGGGYYYBBB
WBWGRGYGYBOB
WWWGGGYYYBBB
   OOO
   OWO
   OOO

Testcase
U2 L' D
   OYY
   RYY
   RYY
GBBWOOBBBRRY
GBBWRRGGGOOY
OOYGBBWRRGGG
   ROO
   WWW
   WWW


Look, up in the sky! It's a super duper array!

Jelly, 47 45 4̷4̷ 42 bytes

+\,×\<ḊZṖP“sd”x;€“uper ”;/“It's a ”,“¥ṫɲ»j

This prints an empty string (falsy) for arrays that are neither super nor duper. Try it online!

How it works

+\,×\<ḊZṖP“sd”x;€“uper ”  Main link (first half). Argument: A (array)

+\                        Compute all partial sums of A.

   ×\                     Compute all partial products of A.
  ,                       Pair the results to the left and to the right.
     <Ḋ                   Perform vectorized comparison with A[1:].
                          This yields a 2D array of Booleans.
       Z                  Zip; pair the Booleans corresponding to each integer.
        Ṗ                 Remove the last pair.
                          (Nothing is compared with the last sum/product.)
         P                Take the product of each column.
          “sd”x           Perform vectorized character repetition.
                          This yields ['s', d'], ['s'], ['d'], or [].
               ;€“uper ”  Append the string "uper " to each character.

;/“It's a ”,“¥ṫɲ»j        Main link (second half).

;/                        Reduce the resulting array of strings by concatenation.
                          This will fail for an empty array, exiting immediately.
  “It's a ”,“¥ṫɲ»         Push ['It's a ', 'array!'].
                 j        Join that array, separating by the super duper string.


GolfScript (101 100 bytes)

n/:g,,{:&g=:r,,{&1$r='^v<>*'?70429 3base 2/=++}/}%{,4=},.{2<}%:&\{2/~\{[~2$~@+(@@+(\]&1$?)!}do\;}%^`

Output is in the form [[x y]] where the co-ordinates are both 0-based.

Online demo

Processing is in two phases: the first phase turns the maze into an array of [x y dx dy] tuples; the second phase maps each arrow / asterisk to the arrow / asterisk it points to. (Asterisks are considered to point to themselves). By the definition of the problem, there is exactly one arrow which isn't in the result of this map, and that is the solution.


Python 2, 81 79 bytes
-2 bytes thanks to dingledooper with a different way to detect if k-2 is a prime which works with k=2.
Uses Wilson's theorem for the primality tests and the fact that \$p\$, \$p+1\$ and \$p+2\$ are coprime for most primes \$p\$.

P=k=q=1
exec"if P%k:print`k`+'*'[k<3:P%(k+2)|q/k];q=k+2\nP*=k*k;k+=1\n"*input()

Try it online!
The output includes the input if it is prime, but this is fine since all testcases are composite.
How?
We use the following result of Wilson's theorem:
$$
(k-1)!^2 \operatorname{mod} k =
\begin{cases}
1 & \text{if $k$ is prime}\\
0 & \text{otherwise.}
\end{cases}
$$
In the code P is used to keep track of \$(k-1)!^2\$ and P%k tests if k is a prime.
If this is the case, we print the output and update q to k+2.
If k==q at the print statement, we know that k-2 was a prime and k is a twin prime.
P%(k+2) tests if k+2 is a prime number. If we would use the exact same prime test as before, this would be P*k*k*(k+1)*(k+1)%(k+2), but with our assumption that \$k\$, \$k+1\$ and \$k+2\$ are coprime for prime \$k\$, this gives the same result.
The assumption doesn't hold for k=2, but this is handled separately with '*'[k<3:], which results in the empty string if k<3.


Jelly, 24 bytes

,ZµŒgaS$€F)Zṣ€0Ṣ<JƊ€€)FẸ

Try it online!

A monadic link taking as its argument the grid as a matrix with 1 representing squares needing a number and 0 representing the spacers. Returns 0 if the grid is Latin and 1 if not.

Explanation

Main link, takes a matrix of 1s and 0s as its argument, z

,                         | Pair with:
 Z                        | - z transposed
  µ                       | Start a new monadic chain
                     )    | For each matrix (z and transpose(z)):
          )               | - For each row:
   Œg                     |   - Group runs of equal elements
       $€                 |   - For each group:
     a                    |     - And with:
      S                   |       - Sum of group
         F                |   - Flatten
           Z              | - Transpose
            ṣ€0           | - Split each at zeros
                  Ɗ€€     | - For each group:
               Ṣ<         |   - Check whether sorted group is less than:
                 J        |     - Sequence along group
                      F   | Finally, flatten
                       Ẹ  | And check if any group returned true

Alternative in case true=true/false=false required:

Jelly, 24 bytes

,ZµŒgaS$€F)Zṣ€0Ṣ_JƊ€€)AƑ

Try it online!


Smallest multiple being run of 9 followed by optional run of 0

Jelly, 13 11 bytes

ṚḌ‘DS=ḍ@ð1#

Try it online!

How it works

ṚḌ‘DS=ḍ@ð1#  Main link. Argument: n

        ð    Start a dyadic chain with arguments n and n.
         1#  Execute the chain to the left with left argument k = n, n+1, n+2, ...
             and right argument n until 1 match has been found. Return the match.
Ṛ                Get the decimal digits of k, reversed.
 Ḍ               Convert from base 10 to integer.
                 This essentially removes trailing zeroes. As a side effect, it
                 reverses the digits, which doesn't matter to us.
  ‘              Increment the resulting integer. If and only if it consisted
                 entirely of 9's, the result is a power of 10.
   DS            Compute the sum of the digits. The sum is 1 if and only if the
                 integer is a power of 10. Note that the sum cannot be 0.
      ḍ@         Test k for divisibility by n.
     =           Compare the results.


Octave, 28 bytes

@(n)find((I=eye(n))+flip(I))

Anonymous function that inputs a number and outputs a column vector of numbers.

Try it online!


JavaScript (ES7),  234  232 bytes
Finds the solutions by solving Pell equations of the form \$x^2-2qy^2=1\$, where \$q\$ is a \$P\$-smooth square free number.
This is an implementation of Derrick Henry Lehmer's procedure, derived from Størmer's original procedure.
Returns an object whose keys and values describe the \$P\$-smooth pairs.

P=>[...Array(P**P)].map((_,n)=>(s=(n,i=0,k=2)=>k>P?n<2:n%k?s(n,i,k+1):s(n/k,i,k+i))(n,1)&&(_=>{for(x=1;(y=((++x*x-1)/n)**.5)%1;);(h=(x,y)=>k--&&h(X*x+n*Y*y,X*y+Y*x,x&s(x=~-x/2)&s(x+1)?r[x]=x+1:0))(X=x,Y=y,k=P<5?3:-~P/2)})(),r={})&&r

Try it online!
How?
The helper function \$s\$ tests whether a given integer \$n\$ is a \$P\$-smooth number when it's called with \$i=0\$, or a square free1 \$P\$-smooth number when it's called with \$i=1\$.
s = (
  n,
  i = 0,
  k = 2
) =>
  k > P ?
    n < 2
  :
    n % k ?
      s(n, i, k + 1)
    :
      s(n / k, i, k + i)

We look for all square free1 \$P\$-smooth numbers in \$[1..P^P-1]\$, where \$P^P\$ is used as an upper bound for \$P!\$.
P=>[...Array(P ** P)].map((_, n) => s(n, 1) && (...))

For each number \$n\$ found above, we look for the fundamental solution of the Pell equation \$x^2-ny^2=1\$:
(_ => {
  for(x = 1; (y = ((++x * x - 1) / n) ** .5) % 1;);
  ...
})()

(the above code is the non-recursive version of my answer to this other challenge)
Once the fundamental solution \$(x_1,y_1)\$ has been found, we compute the solutions \$(x_k,y_k)\$ with \$k\le max(3,(P+1)/2)\$, using the recurrence relations:
$$x_{k+1}=x_1x_k+ny_1y_k\\
y_{k+1}=x_1y_k+y_1x_k
$$
For each \$x_k\$, we test whether \$x_k\$ is odd and both \$(x_k-1)/2\$ and \$(x_k+1)/2\$ are \$P\$-smooth. If so, we store them in the object \$r\$.
( h = (x, y) =>
  k-- &&
  h(
    X * x + n * Y * y,
    X * y + Y * x,
    x &
    s(x = ~-x / 2) &
    s(x + 1) ?
      r[x] = x + 1
    :
      0
  )
)(X = x, Y = y, k = P < 5 ? 3 : -~P / 2)

1: Because it does not test the primality of the divisors, the function \$s\$ will actually be truthy for some non-square free numbers, even when it's called with \$i=1\$. The idea is to filter out most of them so that not too many useless Pell equations are solved.


Hacker Challenge: Guess the Correct Password

Python 3.7, 162 bytes
import string as S,functools as F
A=lambda s:'N'!=Input(s+'\n')
print(''.join(sorted(filter(A,S.ascii_letters+S.digits),key=F.cmp_to_key(lambda a,b:1-2*A(a+b)))))

Tries characters one-by-one to see which ones are in the password. Then sorts those letters using a comparison function.  To compare 'A' and 'B', check to see if 'AB' returns 'Y'.  If is does, then 'A' comes before 'B', otherwise 'A' comes after 'B'.


Help me accelerate linear recurrence relation!

MATL, 8 7 bytes
-1 byte thanks to @LuisMendo
Xy4LY)i

Takes the coefficients in reverse order
Try it online!
Explanation
Xy4LY)i
Xy        : Create an identity matrix of size equal to input
  4LY)    : Remove the first row
      i   : Insert input onto the stack


Bash, 182 bytes

curl "https://www.rottentomatoes.com/api/private/v2.0/browse?minTomato=$2&maxTomato=$2&type=dvd-streaming-all" 2>/dev/null|grep -o "{[^}]*aRating\":\"$1\""|grep -Po 'title":"\K[^"]*'

Usage:

$ bash script PG 98
The Island President
Inside Out
Zootopia
Paddington
Love & Friendship
Long Way North (Tout en haut du monde)


Haskell, 72 bytes

This is "permuting characters only", but is it shorter than a different approach?

s(a:b:c)|(x,y)<-s c=(a:x,b:y)
s n=(n,n)
r a|[_]<-a=a|(x,y)<-s a=r x++r y

s is a helper function to seperate the characters from even and odd positions, r is the bit reversal permutation function:

Prelude> r "codegolf"
"cgdlooef"


Use the Third Stack
If you have read the title you might be a bit confused.  Surely there are only two stacks in Brain-Flak?  However I assure you that it exists and it is one of the most powerful if not the most powerful tool in writing and golfing Brain-Flak.

What is the "Third Stack"?
Every Brain-Flak program uses the third stack in one way or another but most of the use goes on behind the scenes and it is often useful to simply ignore the fact that it exists.  Each parenthesis in the program either adds or removes one item from the stack.  Three of the open braces ([< all add an item to the stack while their three conjugates )]> all remove an item from the stack.  The value of the item on the stack is the value of the current scope of the program and using nilads will modify this value in certain ways.  The close parenthesis ) has the unique function of moving an element from the Third Stack to the current stack; a push.
Hopefully this is becoming clear to you.  The Third Stack is some sort of stack that remembers the return values of code that has already been executed.  Let's walk through an example of a simple program keeping track of the two normal stacks and the Third Stack.
Example
We will walk through the following program.  This program pushes -3, 1, -2 to the stack.
(([()()()])(()))

We start with three open braces, which all push a zero to the third stack.
Our stacks now look like this, the Third Stack is the one on the right and the active stack has a ^ under it:
        0
        0
  0  0  0
  ^

(([()()()])(()))
   ^

Now we have three () nilads.  These do not do anything to the normal two stacks, however they do each add one to the top of the Third Stack making our stacks look like:
        3
        0
  0  0  0
  ^

(([()()()])(()))
         ^

Now we encounter a ] as stated before close braces remove an item from the Third Stack, but ] has the function of subtracting the element it removes from the top of the stack.  Thus our new stacks will look like:
       -3
  0  0  0
  ^

(([()()()])(()))
          ^

This makes sense; [...] does negation so ] should subtract downwards.
Now we must execute a ).  As you likely recall ) is the place in the program where stuff gets pushed to the stack so we will be moving the top of the Third Stack to the current stack, in addition we will be adding the -3 to the next element in the third stack.
 -3  0 -3
  ^

(([()()()])(()))
           ^

Once again we encounter one of our three open braces so we will add another element to our Third Stack.
        0
 -3  0 -3
  ^

(([()()()])(()))
            ^

As we said earlier () will increment the top of our third stack by one.
        1
 -3  0 -3
  ^

(([()()()])(()))
              ^

And ) will move the top of the Third Stack onto the active stack and add downwards
  1
 -3  0 -2
  ^

(([()()()])(()))
               ^

The last ) moves the Third Stack onto the active stack and since there are no elements left on the Third Stack for it to add, does nothing else.
 -2
  1
 -3  0
  ^

(([()()()])(()))
                ^

The program is over so we terminate and output.

This example is intended to give you a feel for what the Third Stack is and does.  It does not include all of the operations, but hopefully you can figure out what each of them does on its own.  If you are still struggling I have included a "cheatsheet" at the bottom of this answer to help you along.
Ok, So what?
Ok, now you understand the Third Stack, but "So what"?  You were already using it even if you didn't call it the "Third Stack", how does thinking in terms of the Third Stack help you golf?
Lets look at a problem.  You want to take the Triangle of a number.  This is the sum of all numbers less than n.
One approach might be to create an accumulator on the offstack and add to it as you count down.  This creates code that looks like this:
(<>)<>{(({}[()])()<>{})<>}{}<>({}<>)

Try it Online!
This code is pretty compact and one might think that it can't get much smaller.  However if we approach it from a third stack point of view it become clear that this is grossly inefficient.  Instead of putting our accumulator on the offstack we can put it on the third stack with a ( and retrieve it at the end we use ).  We will once again loop through all the numbers, but this time we don't have to do much of anything to increment our Third Stack, the program does it for us.  This looks like:
({()({}[()])}{})

Try it Online
This code is less than half the size of the pretty well golfed version we made before.  In fact a computer search has proven that this program is the shortest possible program that can perform this task.  This program can be explained using the "sum of all runs" approach, but I think it is a lot more intuitive and clear when explained using a Third Stack approach.
When do I use the Third Stack?
Ideally whenever you begin work on a new problem in Brain-Flak you should think to yourself how would I do this with the Third Stack in mind.  However as a general rule of thumb whenever you have to keep track of some type of accumulator or have a running total it is a good idea to try putting that on your third stack instead of the two real stacks.
Another time that it might be a good idea to consider using your third stack is when you don't have any space to store some value on the other two stacks.  This can be particularly useful when you are doing manipulations on two existing stacks and you want to save a value for later use without having to keep track of where it is.
Limitations of the Third Stack
The Third Stack is very powerful in a lot of ways but it comes with its own limitations and drawbacks.
Firstly, the maximum stack height for the Third Stack at any given point is determined at compile time.  This means that if you want to use an amount of space on the stack you have to allocate that space when you are writing the program.
Secondly the Third Stack is not Random Access.  This means that you cannot perform any operations on any value but the top most value.  In addition you cannot move values around on the stack (say swap the first two elements).
Conclusion
The Third Stack is a powerful tool and I would consider it essential to every Brain-Flak user.  It takes some getting used to and requires a shift in the way your think about programming in Brain-Flak, but when used properly it makes all the difference between a decent and an amazing when it comes to golfing.
Cheatsheet
Here is a list of operations and how they affect the Third Stack
 Operation  |                 Action
====================================================
   (,[,<    | Put a zero on top of the Third Stack
----------------------------------------------------
     )      | Add the top of the Third Stack to the
            | second element and move it to the
            | active stack
----------------------------------------------------
     ]      | Subtract the top of the Third Stack
            | from the second element and pop it
----------------------------------------------------
     >      | Pop the top of the Third Stack
----------------------------------------------------
     ()     | Add one to the top of the Third Stack
----------------------------------------------------
     {}     | Pop the top of the active stack and
            | add it to the top of the Third Stack
----------------------------------------------------
     []     | Add the stack height to the Third
            | Stack
----------------------------------------------------
   <>,{,}   | Nothing


Produce n n-squares of integers with rotating *'s in consecuitive corners

Dyalog APL, 57  bytes

Requires ⎕IO←0 which is default on many systems.
Assuming double-spacing is permitted, as per the OP's first example.
{A←⊃∘⍕¨?10⍴⍨3⍴⍵⋄A[(⍳⍵),¨⍵⍴2↑¨1⍵(⍵ ⍵)(1⍵)-1]←'*'⋄⍉⎕FMT A}

TryAPL online!
Non-competing 49-byte solution (Dyalog APL 16.0):
{⍉⎕FMT'*'@((⍳⍵),¨⍵⍴2↑¨1⍵(⍵ ⍵)(1⍵)-1)⊃∘⍕¨?10⍴⍨3⍴⍵}


PHP >=7.1, 130 Bytes

18 Bytes saved by @Titus

for([,$x,$y]=$argv;a&$o=$y[$i];)$o==($p=$x[$i++])?:$k[$c[$p]=$o]=$p;echo$y==strtr($x,$c)&$x==strtr($y,$k)?join($k)." ".join($c):0;

Testcases

Expanded

for([,$x,$y]=$argv;a&$o=$y[$i];)
$o==($p=$x[$i++])?:$k[$c[$p]=$o]=$p; # if char string 1 not equal char string 2 make key=char1 value=char2 and key array
echo$y==strtr($x,$c) # boolean replacement string 1 equal to string 2
    &$x==strtr($y,$k) # boolean replacement string 2 equal to string 1
    ?join($k)." ".join($c) # output for true cases
:0; #Output false cases

PHP >=7.1, 148 Bytes

prints 0 for false Output true as string

for([,$x,$y]=$argv;a&$o=$y[$i];$i++)$x[$i]==$o?:$c[$x[$i]]=$o;echo$y==strtr($x,($f=array_flip)($k=$f($c)))&$x==strtr($y,$k)?join($k)." ".join($c):0;

Testcases

Expanded

for([,$x,$y]=$argv;a&$o=$y[$i];$i++)
$x[$i]==$o?:$c[$x[$i]]=$o; # if char string 1 not equal char string 2 set key=char1 value=char2
echo$y==strtr($x,($f=array_flip)($k=$f($c))) # boolean replacement string 1 equal to string 2
&$x==strtr($y,$k) # boolean replacement string 2 equal to string 1
    ?join($k)." ".join($c) # output for true cases
:0; #Output false cases

PHP >=7.1, 131 Bytes

The second answer can be shorted to this if associative arrays are allowed

prints 0 for false Output true as associative array instead of string

for([,$x,$y]=$argv;a&$o=$y[$i];$i++)$x[$i]==$o?:$c[$x[$i]]=$o;print_r($y==strtr($x,($f=array_flip)($f($c)))&$x==strtr($y,$k)?$c:0);

Testcases

PHP >=7.1, 227 Bytes

prints 0 for false

[,$x,$y]=$argv;echo strlen($x)==strlen($y)?strtr($x,$c=array_filter(($f=array_flip)($z=$f(array_combine(($p=str_split)($x),$p($y)))),function($v,$k){return$k!=$v;},1))==$y&$x==strtr($y,$z)?join(array_keys($c))." ".join($c):0:0;

Testcases

Expanded

[,$x,$y]=$argv; #
echo strlen($x)==strlen($y) #compare string lengths
?strtr($x,  # replace function
$c=array_filter( # filter
($f=array_flip)($z=$f( # # remove doubles like in testcase: a1 => 22
    array_combine(($p=str_split)($x),$p($y))  # replacement array keys string 1 values string 2
))
    ,function($v,$k){return$k!=$v;},1)) # remove all keys that equal to values in array
    ==$y # boolean replacement string 1 equal to string 2
&$x==strtr($y,$z) # boolean replacement string 2 equal to string 1
?join(array_keys($c))." ".join($c) # output for true cases
    :0 # Output if replacement from string 1 is not equal to string 2
:0; #Output for different lengths


Jelly, 15 bytes

,ZṚ¥;ŒD$+⁹\€€FṀ

Try it online!

How it works

,ZṚ¥;ŒD$+⁹\€€FṀ  Main link. Left argument: M (matrix). Right argument: n (integer)

 ZṚ¥             Zip/transpose and reverse M. This is equivalent to rotating M 90°
                 counterclockwise.
,                Pair M and the result to the right.
    ;ŒD$         Append the diagonals of both matrices to the pair.
        +⁹\€€    Take the sums of length n of each flat array.
             FṀ  Flatten and take the maximum.


Jelly, 17 16 bytes

-1 byte thanks to Erik the outgolfer (make use of the quick, ¥)

SHð;_P
ṗ3Ç⁼¥Ðf²Ḣ

Brute force application of Heron's formula.

Try it online! (reaches the 60s time out for the 114 tests case. Takes 3m 30s locally - it does check 1143 = 1,481,544 triples)

How?

A true golf solution - given an area a it finds all tuples of three integers between 1 and a (even with repeated triangles and ones of no area), gets their area and filters for those with the desired area (it doesn't even stop as soon as one is found, it ploughs through them all and pops the first result afterwards). Yields 0 if none exists.

SHð;_P - Link 1, get the square of the area of a triangle: list of sides
S      - sum the sides (get the perimeter)
 H     - halve
  ð    - dyadic chain separation (call that p)
    _  - subtraction (vectorises) =    [p-side1,  p-side2,  p-side3]
   ;   - concatenate              = [p, p-side1,  p-side2,  p-side3]
     P - product                  =  p*(p-side1)*(p-side2)*(p-side3)
                                  = the square of Heron's formula = area squared

ṗ3Ç⁼¥Ðf²Ḣ - Main link: number a (area)
ṗ3        - third Cartesian power (all triples of [1,area] : [[1,1,1],[1,1,2],[1,2,1],[1,2,2],[2,1,1],[2,1,2],[2,2,1],[2,2,2], ... ,[a,a,a]]
       ²  - square a
     Ðf   - filter keep if:
    ¥     -   last two links as a dyad:
  Ç       -     call last link (1) as a monad f(list of sides)
   ⁼      -     left (that result) equals right (square of a)?
        Ḣ - head - get the first one (an empty list yields 0, perfect for the falsey case)


Python 3

Seems fast...

 print(0 < 10**100 - 1 < 10**100)

Seems slow...

 print(10**100 - 1 in range(0, 10**100))

But the two run in very similar times! range has an efficient implementation of in


How many characters are there on the icon of a Stack Exchange site?

CJam, 50 48 45 bytes

l22b391"þÁ "+{i%}/"Yª>Þÿ9cîÂcVáòe~"322b4b=

There's unprintable characters in the strings above, which can be obtained by the snippets

[254 193 160]:c
[89 170 62 222 30 255 20 57 99 238 194 99 86 225 242 101 126 20]:c

This also shows that the code points are all below 256. Output is 0 for 1 letter, 1 for 2 letters, 2 for 3 letters and 3 for non-ASCII.

The program simply converts the input string to a base 22 number, performs a series of modulos to reduce the number down, before performing a lookup from a base-4 encoded table.

Try it online | Test suite


Jelly,  17  18 bytes

!P
ÇṗLÇ⁼¥ÐfÇḢḟ1ȯ0F

A monadic link taking and returning a list of the numbers (sticks to the one factorial per number option)

Try it online!

How?

A golfed (although independently written) version of Pietu1998's solution.

!P - Link 1, product of factorials: list
!  - factorial (vectorises)
 P - product

ÇṗLÇ⁼¥ÐfÇḢḟ1ȯ0F - Main link: list                       e.g. [3,2,2]
Ç               - call the last link (1) as a monad           24
  L             - length                                      3
 ṗ              - Cartesian power      [[1,1,1],[1,1,2],...,[1,1,24],...,[24,24,24]]
        Ç       - call the last link (1) as a monad           24
      Ðf        - filter keep if:
     ¥          -   last two links as a dyad:
   Ç            -     call the last link (1) as a monad     [1,2,...,24!,...,24!^3]
    ⁼           -     equal?
         Ḣ      - head
          ḟ1    - filter out any ones
            ȯ0  - or with zero (for the empty list case)
              F - flatten (to cater for the fact that zero is not yet a list)


Mathematica, 34 bytes

<<Combinatorica`
LabeledTreeToCode

Somebody had to do it....

After loading the Combinatorica package, the function LabeledTreeToCode expects a tree input as an undirected graph with explicitly listed edges and vertices; for example, the input in the second test case could be Graph[{{{1, 4}}, {{4, 3}}, {{4, 2}}, {{2, 5}}, {{2, 6}}, {{6, 7}}, {{5, 8}}}, {1, 2, 3, 4, 5, 6, 7, 8}].


Generate combinations that add up to a target value

JavaScript (ES6), 96 bytes

Takes input in currying syntax (list)(target).

a=>s=>a.reduce((b,_,x)=>[...b,...b.map(y=>[...y,x])],[[]]).filter(b=>!b.reduce((p,i)=>p-a[i],s))

Test cases

This would fail on the 2nd test case if 4.8 and 10 were swapped because of an IEEE 754 precision error -- i.e. 14.8 - 4.8 - 10 == 0 but 14.8 - 10 - 4.8 != 0. I think this is fine, although there may be a more relevant reference somewhere in meta.

let f =

a=>s=>a.reduce((b,_,x)=>[...b,...b.map(y=>[...y,x])],[[]]).filter(b=>!b.reduce((p,i)=>p-a[i],s))

console.log(JSON.stringify(f([1, 2, 1, 5])(8)))
console.log(JSON.stringify(f([4.8, 9.5, 2.7, 11.12, 10])(14.8)))
console.log(JSON.stringify(f([7, 8, 9, -10, 20, 27])(17)))
console.log(JSON.stringify(f([1, 2, 3])(7)))

Commented

a => s =>                 // given an array a[] of length N and an integer s
  a.reduce((b, _, x) =>   // step #1: build the powerset of [0, 1, ..., N-1]
    [ ...b,               //   by repeatedly adding to the previous list b[]
      ...b                //   new arrays made of:
      .map(y =>           //     all previous entries stored in y[]
        [...y, x]         //     followed by the new index x
      )                   //   leading to:
    ],                    //   [[]] -> [[],[0]] -> [[],[0],[1],[0,1]] -> ...
    [[]]                  //   we start with a list containing an empty array
  )                       // end of reduce()
  .filter(b =>            // step #2: filter the powerset
    !b.reduce((p, i) =>   //   keeping only entries b
      p - a[i],           //     for which sum(a[i] for i in b)
      s                   //     is equal to s
    )                     //   end of reduce()
  )                       // end of filter()


JavaScript Regex, 99 101 99 97 + 1 for g flag = 98 bytes

^(((Xe|Lua)?(La)?|Bib|MiK|pdf|Mac)TeX|ConTeXt|TeX Live|Meta(FUN|Post)|PostScript|MakeIndex|Lyx)$

Test it here. Type into the Text box. Alternatively, test it here.

var j = $("#dos");
var text;
function abc(){
  text = $('#uno').val();
  j.val(text.match(/^(((Xe|Lua)?(La)?|Bib|MiK|pdf|Mac)TeX|ConTeXt|TeX Live|Meta(FUN|Post)|PostScript|MakeIndex|Lyx)$/g) == text ? "Matches!" : "No match!");
};

<input id='uno' />

<button id='tres' onclick="javascript:abc()">Test!</button>

<input id='dos' />

Test all cases:

var j = $("#dos");
var tests = ["TeX", "pTeX", "ConTeXt", "context", "MetaFun", "MetaFUN", "TeX Live"];
function abc(e){
  j.val(j.val() + e + ": " + (e.match(/^(((Xe|Lua)?(La)?|Bib|MiK|pdf|Mac)TeX|ConTeXt|TeX Live|Meta(FUN|Post)|PostScript|MakeIndex|Lyx)$/g) == e ? "Matches!" : "No match!") + "\n");
};

function def(){
  tests.forEach(abc);
}

<button id='tres' onclick="javascript:def()">Test!</button>

<textarea rows=50 cols=200 id='dos'>
</textarea>


Python 2.7 / Gurobi n=9

This solution is very straight usage of Gurobi's ILP solver for the boolean Mixed-Integer Problems (MIP).

The only trick is to take out symmetry in 1's complement to halve the problem sizes.

Using Gurobi LLC's limited time "free" licence we are restricted to 2000 constraints, but solving 10 del 1 is well outside the 60 second time-limit anyway on my laptop.

from gurobipy import *
from itertools import combinations

def mincover(n,d):
    bs = pow(2,n-1-d)
    m = Model()
    m.Params.outputFlag = 0
    b = {}
    for i in range(bs):
      b[i] = m.addVar(vtype=GRB.BINARY, name="b%d" % i)
    m.update()
    for row in range(pow(2,n-1)):
      x = {}
      for i in combinations(range(n), n-d):
        v = 0
        for j in range(n-d):
          if row & pow(2,i[j]):
            v += pow(2,j)
        if v >= bs:
          v = 2*bs-1-v
        x[v] = 1
      m.addConstr(quicksum(b[i] for i in x.keys()) >= 1)
    m.setObjective(quicksum(b[i] for i in range(bs) ), GRB.MINIMIZE)
    m.optimize()
    return int(round(2*m.objVal,0))

for n in range(4,10):
    for d in range((n//2)+1):
        print n, d, mincover(n,d)

UPDATE+CORR: 10,2 has optimal solution size 31 (see e.g.) Gurobi shows no symmetric solution of size 30 exists (returns problem infeasible) .. [my attempt to show asymmetric feasibility at 30 remained inconclusive after 9.5hrs runtime]
e.g. bit patterns of integers 0 7 13 14    25 28 35 36 49 56 63 64 95 106 118 128 147 159 170 182 195 196 200 207 225 231 240 243 249 252 255 or 0 7 13 14 19 25 28 35 36 49 56 63 64 95 106 118 128     159 170 182 195 196 200 207 225 231 240 243 249 252 255


MATL, 12 bytes

|1>?GtYf/s}0

Try it online!

Explanation

Consider an integer a with |a|>1, and let the (possibly repeated) prime factors of |a| be f1, ..., fn. Then the desired result is a·(1/f1 + ... + 1/fn).

|1>     % take input's absolute value. Is it greater than 1?
?       % if so:
  Gt    %   push input twice
  Yf    %   prime factors. For negative input uses its absolute value
  /     %   divide element-wise
  s     %   sum of the array
}       % else:
  0     %   push 0


Zsh, 14(?) bytes

If N is substituted in place of $1 (as described in the prompt), then 14 bytes. If N is given as an argument, then 16 bytes.

time (: {0..$1})

Try it online!

Uses the builtin time (you can verify that this is a Zsh builtin: run type time). The time to expand the brace expansion increases with the input.

You might think to use time sleep $1, but sleep is an external program, not pure Zsh.


Remove partial matching duplicate lines and retain longest line

JavaScript (ES6),  85 82  79 bytes

a=>a.sort((a,b)=>-!b[a.length]).filter(s=>a[k=/reminder \d+/.exec(s)]^(a[k]=1))

Try it online!
How?
We first sort all strings from longest to shortest.
a.sort((a, b) =>
  -!b[a.length]  // 0 if 'b' is longer than 'a', -1 otherwise
)

We then filter the strings, keeping only the first occurrence of each reminder N key. The underlying object of the input array a[] is re-used to keep track of the keys that were already encountered.
.filter(s =>
  a[k = /reminder \d+/.exec(s)]
  ^
  (a[k] = 1)
)


05AB1E, 11 10 bytes
Code:
\>GN¹¢ÈiN,

Explanation:
\           # Pop input, which saves the first input into ¹
 >          # Increment on second input
  G         # For N in range(1, input + 1)
   N        # Push N
    ¹       # Push the first input from the input register
     ¢      # Count the number of occurences of the digit in N
      È     # Is even?
       iN,  # If true, print N with a newline

Try it online
Uses CP-1252 encoding.


Advent Challenge 1: Help Santa unlock his present vault!

Java

import java.util.Arrays;

public class SantaMatrix4 {

	public static void flipV(int[][] matrix, int row1, int col1, int row2, int col2) {
		for (int row = row1; row <= (row2 - row1) / 2 + row1; row++) {
			for (int col = col1; col <= col2; col++) {
				int tmp = matrix[row][col];
				matrix[row][col] = matrix[row2 - row + row1][col];
				matrix[row2 - row + row1][col] = tmp;
			}
		}
	}

	public static void flipH(int[][] matrix, int row1, int col1, int row2, int col2) {
		for (int row = row1; row <= row2; row++) {
			for (int col = col1; col <= (col2 - col1) / 2 + col1; col++) {
				int tmp = matrix[row][col];
				matrix[row][col] = matrix[row][col2 - col + col1];
				matrix[row][col2 - col + col1] = tmp;
			}
		}
	}

	public static void main(String[] args) {
		int counter = 0;
		int n = Integer.parseInt(args[counter++]);
		int[][] matrix1 = new int[n][n];
		for (int i = 0; i < n; i++) {
			for (int j = 0; j < n; j++) {
				matrix1[i][j] = Integer.parseInt(args[counter++]);
			}
		}

		int[][] matrix2 = new int[n][n];
		for (int i = 0; i < n; i++) {
			for (int j = 0; j < n; j++) {
				matrix2[i][j] = Integer.parseInt(args[counter++]);
			}
		}

		int[] ops = new int[5 * matrix1.length * matrix1.length * 2];
		int numOps = 0;
		int opsI = 0;

		for (int row = 0; row < n; row++) {
			for (int col = 0; col < n; col++) {
				int goal = matrix2[row][col];
				boolean gotIt = false;

				//Look for required number to the right
				for (int i = row; i < n && !gotIt; i++) {
					for (int j = col; j < n && !gotIt; j++) {
						if (i == row && j == col) continue;
						if (matrix1[i][j] == goal) {
							flipH(matrix1, row, col, i, j);
							flipV(matrix1, row, col, i, j);
							ops[opsI++] = 1;
							ops[opsI++] = row;
							ops[opsI++] = col;
							ops[opsI++] = i;
							ops[opsI++] = j;
							numOps++;

							gotIt = true;
						}
					}
				}

				//Look for required number below and to the left
				for (int i = row + 1; i < n && !gotIt; i++) {
					for (int j = 0; j < col && !gotIt; j++) {
						if (matrix1[i][j] == goal) {
							flipH(matrix1, i, j, i, col);
							ops[opsI++] = 2;
							ops[opsI++] = i;
							ops[opsI++] = j;
							ops[opsI++] = i;
							ops[opsI++] = col;

							flipV(matrix1, row, col, i, col);
							ops[opsI++] = 3;
							ops[opsI++] = row;
							ops[opsI++] = col;
							ops[opsI++] = i;
							ops[opsI++] = col;

							numOps += 2;
							gotIt = true;
						}
					}
				}

			}
		}

		System.out.println(Arrays.toString(ops));
		System.out.println(numOps);
	}
}

Slightly faster hard-coded version: Try it online!

Input is space separated integers via the command line. The first integer is the width of the two matrices. The remaining integers are their elements, row-by-row.

Every permutation of a matrix can be obtained with just the horizontal flip and vertical flip operators, so I ignored the rest except for replacing a consecutive vFlip and hFlip in the same region with a rotation by 180 degrees.

The program scans through each element. Whenever we encounter an element that has the wrong bit, it looks further ahead through the array to find a spot that has the correct bit. I've divided the search region in two: those with an equal or larger column coordinate, and those with a smaller column coordinate. Note that the latter must have a larger row coordinate based on the way we're traversing the array. If we find a correct bit in the first search region, we can just rotate by 180 degrees the sub-matrix spanning the two elements for a total of one operation. If it's in the second region, we can use a horizontal flip to move the correct bit to the same column as the wrong bit and then vertically flip the sub-matrix spanning the two for a total of two operations.

The output of the program is an array that should be mentally split into groups of five. Each group is (i, row1, col1, row2, col2) where i is 0 for a no-op, 1 for a rotation by 180 degrees, 2 for a horizontal flip, and 3 for a vertical flip. The remaining 4 components describe the region over which the operation runs. I am not sure if this is a readable format.

For the given test case, I get 258 operations and two to three milliseconds on my computer.


Convert a Point of the Compass to Degrees

Ruby, 118 106
Thanks to Martin Büttner for 12 bytes saved.
This is currently the same length regardless of whether it's a function or a program.
lambda function
->s{n=4
d=0,0
s.chars{|e|c="SWNE".index e
c ?d[c%2]+=c/2*2*n-n :n=1}
(Complex(*d).arg*5.1).round%32*11.25}

program
n=4
d=0,0
gets.chars{|e|c="SWNE".index e
c ?d[c%2]+=c/2*2*n-n :n=1}
p (Complex(*d).arg*5.1).round%32*11.25

This is a cartesian walk through the points. The characters NSEW add or subtract 4 from the x and y coordinates stored in d[]. After a b (or any symbol other than NSEW) is encountered, this is reduced to 1.
The x and y data is then treated as a complex number to extract the angular argument. This is multiplied by 16/PI=5.1 . Although there are some geometrical errors in the approach, rounding this angle is sufficient to give the correct number -15..+16. Modulo is used to correct this to 0..31 (in Ruby % always returns positive.) Finally the result is multiplied by 11.25.


Brainfuck 76 bytes
>>+[<+++++++++[->---------<]+>-[--[[-]<->]<[<[->-]>[<+]<]>]<[-<+>]+>,]<<[<+]

This goes out of it's bonds if square brackets are unbalanced turning the bf interpreter/compiler to fail runtime and some of them have exit codes to reflect that.
requires eof=0, wrapping values and finit number of cells
In Ubuntu you can use the interpreter bf (sudo apt-get install bf)
% echo '[[[]' | bf -n bf_matching.bf
Error: Out of range! Youwanted to '<' below the first cell.
To solve, add some '>'s at the beginning, for example.
an error occured
% echo $?
5
% bf -n bf_matching.bf < bf_matching.bf
% echo $?
0


05AB1E, 2 bytes

ÓZ

Try it online!

How?

Ó   exponents of prime factors
 Z  maximum


C, Perl, PHP, Python, Ruby

Update: I've put together a jsfiddle that helps visualize the path through the code for each of the five languages: http://jsfiddle.net/wK6bD/4/embedded/result/

An alternative version, that removes all comments, and compresses all insignificant strings, regex and replacement patterns: http://jsfiddle.net/wK6bD/5/embedded/result/

And I saved a byte while I was at it. Turns out C had an unnecessary semi-colon ;)

#/*<?php ob_clean();"
s='''*/include<stdio.h>
main($y){char*$s,$t[3],$u[3]/*';'''
def printf(a,*b):import sys;sys.stdout.write(a%b)
for y in range(99,-1,-1):
  '''
99.downto(0){|y|$y=y;"/*=;#*/;
for($y=100;$y--;){
  #/*"
  $u=(($t=$y)+99)%100;'*/
  sprintf($t,"%d",$y);sprintf($u,"%d",($y+99)%100);
  #//';#'''
  printf("%s bottle%s of beer on the wall, %s bottle%s of beer.\n%s",
    #/* -- THIS LINE ENDS WITH CR --
    y//1or'No more','s'[:y!=1],y or'no more','''s*/
    +$y>0?$t:"No more",$s=$y!=1?"s":"",$y>0?$t:"no more",$s,$y>0?
    #//'''[:y!=1],y and'''
    "Take one down and pass it around":
    #//'''[6:38]or
    "Go to the store and buy some more");
  printf(", %s bottle%s of beer on the wall.\n\n",
    #/* -- THIS LINE ENDS WITH CR --
    y//1-1and~-y%100or'no more','''s*/
    +$y!=1?$u:"no more",$y!=2?"s":"");}
    #/*?><?php "
    %w;q(*/
    }//";#'''[:y!=2])

Please Note: This file needs to be saved with mixed line endings. All lines should be terminated with LF (char 10, a.k.a. unix-style), except for the two lines marked -- THIS LINE ENDS WITH CR --, which should be terminated with CR (char 13, a.k.a. mac-style). I recommend using notepad++, or other text editor which allows you to manually edit line endings.

For PHP, it is assumed that output_buffering is enabled. According to the documentation, this is hardcoded to be Off when using the CLI, regardless of ini settings, so it needs to be explicitly (re)enabled:

$ php -d output_buffering=4096 bottles.pl.php.py.rb.c

This enables a 4kb buffer, which is the 'recommended' value. If you're using one of the supplied inis this will already be set, so it should run as-is from any web server.

The total file size is 823 bytes (not counting the comments about the line endings), an average of 164.6 bytes per language.

Versions Tested
C - gcc 4.8.1, cl 15.00
Perl - 5.16.2
PHP - 5.4.16
Python - 2.7.6, 3.3.4
Ruby - 1.8.7, 1.9.3

Output is identical for all five languages (see below).

Perl, PHP

<?php '>#'
;for($i='no more';100>($a="$i bottle".(2^($i+=1)?'s':'').' of beer');$o="
Take one down and pass it around, $b.

".ucfirst($f="$b, $a.$o")){$b="$a on the wall";}print"$f
Go to the store and buy some more, $b.";

I like this one because of how short it is, so I'm leaving it. It also demonstrates how much of a Perl-wanna-be PHP is ;)

Sample Usage:

$ perl bottles
99 bottles of beer on the wall, 99 bottles of beer.
Take one down and pass it around, 98 bottles of beer on the wall.

98 bottles of beer on the wall, 98 bottles of beer.
Take one down and pass it around, 97 bottles of beer on the wall.

...

2 bottles of beer on the wall, 2 bottles of beer.
Take one down and pass it around, 1 bottle of beer on the wall.

1 bottle of beer on the wall, 1 bottle of beer.
Take one down and pass it around, no more bottles of beer on the wall.

No more bottles of beer on the wall, no more bottles of beer.
Go to the store and buy some more, 99 bottles of beer on the wall.


JavaScript (ES6), 35 bytes

s=>s.replace(/[aeiouy]+/gi,'$&p$&')

Try it online!
Where the special replacement pattern $& means matched substring.


V, 10 bytes

ò^llYpr $x

Try it online!

Explanation:

ò^ll         " While there are at least two non-whitespace characters on the current line
    Y        " Yank this line
     p       " Paste it below
      r      " Replace the first character with a space
        $    " Move to the end of the line
         x   " Delete a character


Jelly, 20 bytes

;Zµ⁼Ṣ€
ẋÇFŒ!ṁ€⁸ÇÐfL’

For valid ballot triangles, run time and memory usage are at least O(n!), where n is the number of entries of the triangle. Invalid ones are recognized by crashing, thus printing nothing.

Try it online!

Test run

Locally, I was able to verify that a(4) is calculated correctly.

$ time jelly eun ';Zµ⁼Ṣ€¶ẋÇFŒ!ṁ€⁸ÇÐfL’' '[1],[2,3],[4,5,6],[7,8,9,10]'
11

real    6m9.829s
user    6m7.930s
sys     0m2.579s

How it works

;Zµ⁼Ṣ€         Helper link. Argument: T (triangular array)

 Z             Zip/transpose T.
;              Concatenate the original and the transposed copy.
  µ            Begin a new monadic chain, with the previous result (R) as argument.
    Ṣ€         Sort each array in R.
   ⁼           Test for equality with R.
               This returns 1 if T is a ballot triangle, 0 if not.

ẋÇFŒ!ṁ€⁸ÇÐfL’  Main link. Argument: A (triangular array)

 Ç             Call the helper link with argument A.
ẋ              Repeat A that many times.
               This yields an empty array if A is not a ballot triangle.
  F            Flatten the result.
   Œ!          Generate all permutations of the digits of A.
     ṁ€⁸       Mold each permutation like A, i.e., give it triangular form.
               This crashes if permutation array is empty.
        ÇÐf    Filter; keep permutations for which the helper link returns 1.
           L’  Compute the length and decrement it.


Mathematica, 32 bytes

Resultant[#,#2/.x->z-x,x]/.z->x&

Or the same length:

Resultant[#/.x->y,#2/.x->x-y,y]&

Example:

In[1]:= Resultant[#,#2/.x->z-x,x]/.z->x&[x^4 - 10 x^2 + 1, x^2 + 1]

Out[1]= 144 + 192 x^2 + 88 x^4 - 16 x^6 + x^8

In[2]:= Resultant[#/.x->y,#2/.x->x-y,y]&[x^2 - 2, x^2 - 2]

Out[2]= -8 x^2 + x^4

Explanation:

If x is a root of f(x), y is a root of g(y), and let z = x + y, then (x, z) is a root of the simultaneous equations f(x) = 0, g(z - x) = 0. Then we can eliminate the variable x using the resultant.


Jelly, 10 8 10 bytes

ŒR’+%12‘Ɠe

Try it online!

Saved 2 bytes thanks to Mr. Xcoder

+2 bytes due a bug if one = 12

I believe this meets the criteria. Takes one from STDIN, range as left argument and two as right argument


Smallest number of contiguous monotonic subsequences

Brachylog, 12 bytes
~c:{<=|>=}al

Try it online!
This returns false. for the empty list [].
Explanation
(?)~c                 Take a list of sublists which when concatenated result in the Input
     :{<=|>=}a        Each sublist must be either increasing or decreasing
              l(.)    Output is the length of that list

This will return the smallest one because ~c will generate choice points from the smallest number of sublists to the biggest.


JavaScript (ES6), 46 40 bytes

f=n=>n?+"452331541"[n%10]||f(n/10|0)+2:2

Alternative formulation, also 46 40 bytes:

f=n=>n?26523308>>n%10*3&7||f(n/10|0)+2:2

Edit: Saved 6 bytes thanks to @xsot.


Is it a Linearized Tree? (Breadth-first Edition)

Haskell, 44 bytes

f[n:k]=iterate f[k]!!n
f _=[]
g x=f[x]==[[]]

Defines a function g that takes a list and returns a boolean.
See it pass all test cases.

Explanation

This relies on the fact that depth-first and breadth-first linearizations produce the same arrays.
See Martin's answers for details; basically they both give the same arithmetical condition on the array.

The function f is given the input list wrapped in a singleton list.
It pops one number n off the list, then calls itself n times on the remaining list to process the children of the popped node (depth first).
Popping the empty list results in [], which I use as an error state.
The function g checks that the end result is [[]], the unique non-erroneous state with no unprocessed nodes.
If Haskell was weakly typed, I could just use 0 or something as the error state, and wouldn't have to wrap the input into another list.


Pyth, 18 14 bytes

hfqSjkTjkS7./Q

Thanks to @isaacg for golfing off 2 bytes and paving the way for 2 more.

The code will crash if it should produce no output, which causes no output to be produced.

This will work for small-ish inputs if you're patient enough, and for larger ones if given enough time and memory.

To verify that the code works as intended, you can replace the 7 with a 3 for sums of digits 1 through 3. Click here for a test suite.

Example runs

$ time pyth/pyth.py -c 'hfqSjkTjkS7./Q' <<< 28
(1, 2, 3, 4, 5, 6, 7)

real    4m34.634s
user    4m34.751s
sys     0m0.101s
$ time pyth/pyth.py -c 'hfqSjkTjkS7./Q' <<< 29 2>/dev/null

real    9m5.819s
user    9m6.069s
sys     0m0.093s

How it works

           ./Q    Compute all integer partitions of the input.
 f                Filter the integer partitions:
    jkT             Join the integers with empty separator.
   S                Sort the characters of the resulting string.
      jkS7          Join [1, ..., 7] with empty separator.
  q                 Check both results for equality.
                  Keep the partition of `q' returned True.
h                 Retrieve the first element of the filtered list.
                  For a non-empty list, this retrieves the solution.
                  For the empty list, it causes an error and produces no output.


Cayley Table of the Dihedral Group \$D_3\$

Python 2, 27 bytes

lambda o,O:[o[_]for _ in O]

Try it online!


JavaScript ES7, 194 bytes

(d,c,s,g=(a,b)=>[...b].reduce((z,l,i)=>z+(a[i]==l?1:0),0))=>[for(s of s.split` `)~d.indexOf(s)?[...c[(x=[for(i of c)g(i,s)]).indexOf(Math.max(...x))]].map((l,i)=>l!=s[i]?`*`:l).join``:s].join` `

A very large function. I'm guessing a few bytes can be golfed off but not much unless I completely change the way it works.


Approximate the proportion of integers with neighboring factors

Jelly,  14 13  10 bytes
-1 using Erik the Outgolfer's idea to take the mean of a list of zeros and ones.
-3 by using 3-indexing (as allowed in the question) - thanks to Dennis for pointing this out.
ḊPƝḍⱮ!Ẹ€Æm

A monadic Link accepting an integer, n+2, which yields a float.
Try it online! (very inefficient since it tests divisibility over the range \$[2, (n+2)!]\$)
(Started out as +2µḊPƝḍⱮ!§T,$Ẉ, taking n and yielding [numerator, denominator], unreduced)
How?
ḊPƝḍⱮ!Ẹ€Æm - Link: integer, x=n+2
Ḋ          - dequeue (implicit range of) x  - i.e. [2,3,4,...,n+2]
  Ɲ        - apply to neighbours:
 P         -   product                             [2×3,3×4,...,(n+1)×(n+2)]
     !     - factorial of x                        x!
    Ɱ      - map across (implicit range of) x! with:
   ḍ       -   divides?                            [[2×3ḍ1,3×4ḍ1,...,(n+1)×(n+2)ḍ1],[2×3ḍ2,3×4ḍ2,...,(n+1)×(n+2)ḍ2],...,[2×3ḍ(x!),3×4ḍ(x!),...,(n+1)×(n+2)ḍ(x!)]]
       €   - for each:
      Ẹ    -   any?  (1 if divisible by any of the neighbour products else 0)
        Æm - mean


Number of string permutations that are palindromes

Brachylog (2), 15 bytes

{p.↔}ᶠdl%₆₆₆₀₁₃

Try it online!

Explanation

{p.↔}ᶠdl%₆₆₆₀₁₃
{   }ᶠdl          Count (l) the number of distinct (d) results (ᶠ) obtainable by:
 p                  permuting {the input}
  .                 to produce an output
   ↔                that, if reversed, is still the output
        %₆₆₆₀₁₃   then take that number modulo 666013


Perl 769 chars * 0.9 * 0.8 = 554

Probably still some improvements to be made on some of the regexes, but it's slowly getting there!

$_=join"",<>;$s="<tt class";$c="</tt>";$d=counter;$e=color;s/\t/    /g;s!<!&lt;!g;s!>!&gt;!g;s!^#.+(?=$|
)!$s=d>$&$c!gm;s!//.+!$s=c>$&$c!g;s|(['"]).*?(?<!\\)(\\\\)*\1|($h=$&)=~s!/!&#47;!g;"$s=s>$h$c"|smeg;s!/\*.*?\*/!$s=c>$&$c!smg;s!\b(_Packed|(au|go)to|break|c(ase|har|onst|ontinue)|d(efault|o|ouble)|e(lse|num|xtern)|f(loat|or)|if|int|long|re(gister|turn)|short|(un)?signed|s(izeof|tatic|truct|witch)|typedef|union|vo(id|latile)|while)\b!$s=r>$&$c!g;s!=(\w)>.+?$c!join"$c
$s=$1>",split$/,$&!smeg;s!
!
!g;print"

$_"

Slightly less obfuscated version with comments:

$_=join"",<>; # slurp file
$s="<tt class"; # used later - use <tt/> instead of , fewer chars!
$c="</tt>";
$d=counter;
$e=color;
s/\t/    /g; # convert tabs to spaces
s!<!&lt;!g; # htmlentity < and >
s!>!&gt;!g;
s!^#.+(?=$|\n)!$s=d>$&$c!gm; # directives
s!//.+!$s=c>$&$c!g; # inline comments
s|(['"]).*?(?<!\\)(\\\\)*\1|($h=$&)=~s!/!&#47;!g;"$s=s>$h$c"|smeg; # strings, might have 0 length - thanks @Einacio; work-around string that contain /* by converting them to HTML entities
s!/\*.*?\*/!$s=c>$&$c!smg; # multi-line comments
s!\b(_Packed|(au|go)to|break|c(ase|har|onst|ontinue)|d(efault|o|ouble)|e(lse|num|xtern)|f(loat|or)|if|int|long|re(gister|turn)|short|(un)?signed|s(izeof|tatic|truct|witch)|typedef|union|vo(id|latile)|while)\b!$s=r>$&$c!g; # reserved words, don't optimise this too much! - thanks @bwoebi
s!=(\w)>.+?$c!join"$c
$s=$1>",split$/,$&!smeg; # any multi-line string/comment, ensure s are repeated
s!\n!
!g; # strip newlines, replace with
, don't need 	 _or_
 - thanks @xfix!
print"

$_"

Now successfully highlights @xfix's entry.

Borrowed the idea to drop
 from @xfix's entry, thank you!

Example of output for @xfix's solution.