JavaScript (ES6), 292 bytes 306 325

Edit I did the byte count totally wrong, corrected now thx http://bytesizematters.com/ correct for the last time I hope thx  Cᴏɴᴏʀ O'Bʀɪᴇɴ see https://goo.gl/LSHC1U (and 1 byte less using a literal newline insteads of '\n')

(h,z)=>(o=>{r=p=>" ),┌(─┐┬'└│├┘┴┤┼".search(z[p]);for(q=s=0;++s<o/2&s<h;)for(y=0;y<(h-s)*o;y+=o)for(x=0;x<o-s*2;q+=!n,x+=2)for(n=i=0,t=x,u=y;i<=s;t+=2,u+=o,i++)n|=i<s&(!(r(t+y)&r(t+y+s*o)&1)|!(r(x+u)&r(x+u+s*2)&2))|i>0&(!(r(t+y)&r(t+y+s*o)&4)|!(r(x+u)&r(x+u+s*2)&8))})(-~z.search`
`)|q

Longer than I expected (probably a few more byte can be shaved off)

All possible squares are checked and counted.

The r function map each character to a bitmap having

1 : horizontal line center to right
2 : vertical line center to bottom
4 : horizontal line center to left
8 : vertical line center to top

A square of any size must have

4 in all cells except the first in top and bottom row
1 in all cells except the last in top and bottom row
8 in all cells except the first in leftmost and rightmost column
2 in all cells except the last in leftmost and rightmost column

Test

f=(h,z)=>(o=>{r=p=>" ),┌(─┐┬'└│├┘┴┤┼".search(z[p]);k=(p,d,m)=>r(p)&r(p+s*d)&m;for(q=s=0;++s<o/2&s<h;)for(y=0;y<(h-s)*o;y+=o)for(x=0;x<o-s*2;q+=!n,x+=2)for(n=i=0,t=x,u=y;i<=s;t+=2,u+=o,i++)n=n|i<s&(!k(t+y,o,1)|!k(x+u,2,2))|i>0&(!k(t+y,o,4)|!k(x+u,2,8));})(-~z.search`
`)|q

console.log=(...x)=>O.textContent+=x+'\n'

// Less golfed

Uf=(h,z)=>{
  o=-~z.search`\n`;
  w=o/2;
  r=p=>" ),┌(─┐┬'└│├┘┴┤┼".search(z[p]);
  k=(p,d,m)=>r(p)&r(p+s*d)&m;
  for(q=s=0;++s<w&s<h;)
    for(y=0;y<(h-s)*o;y+=o)
      for(x=0;x<(w-s)*2;q+=!n,x+=2)
        for(n=i=0,t=x,u=y;i<=s;t+=2,u+=o,i++)
          n|=i<s&(!k(t+y,o,1)|!k(x+u,2,2))
          |i>0&(!k(t+y,o,4)|!k(x+u,2,8));
  return q
}

;[[5,`┌─┬───┬─┐
├─┼─┬─┼─┤
├─┼─┴─┼─┤
├─┼─┬─┼─┤
└─┴─┴─┴─┘`,20]
,[5,`┌─┬─┬─┬─┐
├─┼─┼─┼─┤
├─┼─┼─┼─┤
├─┼─┼─┼─┤
└─┴─┴─┴─┘`,30]
,[3,`┌─┬─┐
├─┼─┤
└─┴─┘`,5]
,[5,`┌─┬─┐
├─┴─┤
├───┤
├─┬─┤
└─┴─┘`,7]
,[4,`┌─┬─┬─┬─┬─┬─┐
├─┼─┼─┼─┼─┼─┤
├─┼─┼─┼─┼─┼─┤
└─┴─┴─┴─┴─┴─┘`,32]
,[2,`┌─┐
└─┘`,1]
,[4,`┌─┬─┬─┬─┬─┬─┐
├─┴─┼─┼─┼─┴─┤
├─┬─┼─┼─┼─┬─┤
└─┴─┴─┴─┴─┴─┘`,22],
,[6,`┌─┬─────┐
├─┼─┬─┐ │
│ ├─┼─┼─┤
│ └─┼─┼─┤
│   └─┼─┤
└─────┴─┘`,12],
,[6,`┌─┬─┬─┬─┐
├─┴─┼─┼─┤
│   └─┼─┤
├─┬─┬─┼─┤
├─┼─┼─┼─┤
└─┴─┴─┴─┘`,23]]
.forEach(t=>{
  var r=t[0],a=t[1],k=t[2],x=f(r,a)
  console.log(x==k?'OK '+x:'KO '+x+' Expected '+k,'\n'+a)
})


Python 3, 79 bytes

lambda s:eval('{*range%s}'%s.translate({91:40,40:'(1+',93:'+1)',85:',*range'}))

Try it online!
-6 bytes thanks to ovs
-3 bytes thanks to dingledooper


C, Python, and Brainfuck

The Brainfuck program on the line starting with pgm= can be changed into any valid Brainfuck program (so it is Turing-complete). The program will then run in C, Python, and Brainfuck. The given program prints Hello World!.

The interpreters in both C and Python have the following characteristics:

8-bit cells
Infinite tape in both directions
-1 (255) on EOF

It runs like this:

$ gcc poly_bf.c; ./a.out
Hello World!
$ python poly_bf.c
Hello World!
$ bf poly_bf.c
Hello World!

And here's the program:

#define AA [
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define BB ]
#define PGM char*\
pgm="++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++.";
#define ZZ \
""" [-][";
struct cell { char val; struct cell *prev; struct cell *next; };
struct cell *prv(struct cell *c) {
    if (!c->prev) {
        struct cell *z = malloc(sizeof(struct cell));
        z->next = c;
        z->prev = 0;
        z->val = 0;
        c->prev = z;
    }
    return c->prev;
}
struct cell *nxt(struct cell *c) {
    if (!c->next) {
        struct cell *z = malloc(sizeof(struct cell));
        z->prev = c;
        z->next = 0;
        z->val = 0;
        c->next = z;
    }
    return c->next;
}
int main() {
    PGM
    int ip=0, t=0;
    struct cell *c = malloc(sizeof(struct cell));
    memset(c, 0, sizeof(struct cell));
    while (pgm[ip]) {
       switch(pgm[ip]) {
           case '+': c->val++;break;
           case '-': c->val--;break;
           case '>': c=nxt(c);break;
           case '<': c=prv(c);break;
           case '.': putchar(c->val);break;
           case ',': c->val=getchar();break;
           case '[':
               if (c->val) break;
               ip++;
               t=1;
               while (t) {
                  t += pgm[ip] == '[';
                  t -= pgm[ip] == ']';
                  ip++;
               }
               ip--;
               break;
           case ']':
               if (!c->val) break;
               ip--;
               t=1;
               while (t) {
                  t -= pgm[ip] == '[';
                  t += pgm[ip] == ']';
                  ip--;
               }
               ip++;
               break;
       }
       ip++;
    }
    return 0;
}
#define YY \
" """;
#define XX /*
import sys;
ip=t=0
class Cell:
  pv=None
  nx=None
  val=0

  def prev(self):
     if not self.pv:
        self.pv = Cell()
        self.pv.nx = self
     return self.pv
  def next(self):
     if not self.nx:
        self.nx = Cell()
        self.nx.pv = self
     return self.nx

cell=Cell()
while ip<len(pgm):
  if pgm[ip]=='+': cell.val+=1;cell.val%=256
  elif pgm[ip]=='-': cell.val-=1;cell.val%=256
  elif pgm[ip]=='>': cell=cell.next()
  elif pgm[ip]=='<': cell=cell.prev()
  elif pgm[ip]=='.': sys.stdout.write(chr(cell.val))
  elif pgm[ip]==',':
      ch=sys.stdin.read(1)
      if ch:cell.val=ord(ch)
      else:cell.val=255
  elif pgm[ip]=='[' and not cell.val:
      t=1
      ip+=1
      while t:
        t += pgm[ip] == '['
        t -= pgm[ip] == ']'
        ip+=1
      ip-=1
  elif pgm[ip]==']' and cell.val:
      t=1
      ip-=1
      while t:
        t -= pgm[ip] == '['
        t += pgm[ip] == ']'
        ip-=1
      ip+=1
  ip+=1
#]*/


MATL, 3 bytes

1YL

Try it online!

Explanation

Built-in... ¯\_(ツ)_/¯


Perl - 72 bytes

$~=<>=~$"+$'*2;$_=1-$_*$`/$~--/$~*$`for($,,$;)x$';printf'%f
%f',$`*$,,$;

Or, counting command line options as 1 byte each, in 70 bytes:

#!perl -n
$-=/ /+$'*2;$_=1-$_*$`/$---/$-*$`for($,,$;)x$';printf'%f
%f',$`*$,,$;

Or, if you'll allow me Perl 5.8, in 63 bytes:

#!perl -p
$.+=$'<</ /;$_=1-$_*$`/$.--/$.*$`for($_=$#='%f
',$\)x$';$_*=$`

but why would you.

Edit: Compliance with the new rules. %f rounds to 6 places by default, how convenient!

Algorithm

Examining the Taylor series for sin(x):

it can be seen that each term evenly divides every successive term. Because of this, it can be transformed rather effortlessly into a nested expression:

cos(x) transforms similarly, without the leading x, and denominator terms one smaller.

Additionally, this nested expression can be reformulated as a reverse recursive expression:

with s∞ = 0 and sin(x) = x·s1, which is ultimately what is used.

Ungolfed

<> =~ m/ /;          # read one line from stdin, match a space
                     # prematch ($`) is now x, postmatch ($') is now n
($x, $n) = ($`, $'); # reassign, for clarity
$i = 2*$n + 1;       # counting variable (denominators)

for (($s, $c)x$n) {  # iterate over $s and $c, n times each
  # compute the next term of the recursive expression
  # note: inside this loop $_ is not the _value_
  # of $s and $c alternately, it _is_ $s and $c

  $_ = 1 - $_ * $x**2 / $i-- / $i;
}

# formated output
printf("%f\n%f", $x*$s, $c);

Sample Usage

$ echo 5 3 | perl sin-cos.pl
10.208333
14.541667

$ echo 8.555 13 | perl sin-cos.pl
0.765431
-0.641092

$ echo 9.26 10 | perl sin-cos.pl
-3.154677
-8.404354

$ echo 6.54 12 | perl sin-cos.pl
0.253986
0.967147

$ echo 5 1 | perl sin-cos.pl
5.000000
1.000000

$ echo 20 20 | perl sin-cos.pl
-5364.411846
-10898.499385

If you want to test this online, I recommend using compileonline.com. Copy-Paste the code into main.pl, and the input into the STDIN box, then Execute Script.


Now I know my ABCs, won't you come and golf with me?

Vim, 42, 40 keystrokes/bytes
:h<_<cr>jjYZZP:s/./&, /g<cr>7f r<cr>9;.3;.3;.$ch.

Thanks to Lynn and her awesome vim answer for the tip to grab the alphabet from help.
Thanks to RomanGräf for saving two bytes!
Explanation:
:h<_<cr>                                      " Open up vim-help
        jj                                    " Move down two lines
          Y                                   " Yank this line (containing the alphabet)
           ZZ                                 " Close this buffer
             P                                " Paste the line we just yanked
              :s/./&, /g<cr>                  " Replace every character with that character followed by a comma and a space
                            7f                " Find the seven space on this line
                               r<cr>          " And replace it with a newline
                                    9;        " Repeat the last search (space) 9 times
                                      .       " Repeat the last edit (replace with a newline)
                                       3;     " Third space
                                         .    " Replace with newline
                                          3;  " Third space
                                            . " Replace with newline

Then, we move the end of the of the line with $, change back a character with ch and insert a dot.


C

#include <stdio.h>
#include <stdlib.h>
#include <memory.h>

enum mode
{
    CORD_MODE_CONST = 1,
    CORD_MODE_SLOPE = 2,
};
typedef struct point {
    float x;
    float y;
} CORD;

typedef struct l {
    int mode;
    float m;
    float b;
}LINE;

typedef struct r {

    CORD topL;
    CORD botL;

    CORD topR;
    CORD botR;

    CORD midRight;
    CORD midBot;
    CORD midLeft;
    CORD midTop;

    CORD center;
    LINE vertLine;
    LINE horLine;

} RECTANGLE;

void findBorderIntersection(RECTANGLE * pR, LINE * p);
int isPointContained(RECTANGLE * pR, CORD * pC1);
float dotProduct(float y1, float y2, float x1, float x2);
void findCenterOfRetangle(RECTANGLE * pR);
void findIntersection(LINE * pL1, LINE * pL2, CORD *pInt);
void findMidPointOfLine(CORD * pC1, CORD * pC2, CORD * pMid);
void getLine(CORD * pC1, CORD * pC2, LINE * pLine );

void dumpCord(char * pS, CORD * pC)
{
    printf(" %s y:%f x:%f\n",pS,pC->y,pC->x);
}

int main()
{
    RECTANGLE yourLand;
    RECTANGLE cityLand;
    LINE  lineThroughCenter;

    memset(&yourLand,0x0, sizeof(RECTANGLE));
    memset(&cityLand,0x0, sizeof(RECTANGLE));

    scanf("%f%f%f%f%f%f%f%f",&(yourLand.topL.x),
                             &(yourLand.topL.y),
                             &(yourLand.topR.x),
                             &(yourLand.topR.y),
                             &(yourLand.botL.x),
                             &(yourLand.botL.y),
                             &(yourLand.botR.x),
                             &(yourLand.botR.y));

    scanf("%f%f%f%f%f%f%f%f",&(cityLand.topL.x),
                             &(cityLand.topL.y),
                             &(cityLand.topR.x),
                             &(cityLand.topR.y),
                             &(cityLand.botL.x),
                             &(cityLand.botL.y),
                             &(cityLand.botR.x),
                             &(cityLand.botR.y));

    /* Find center of your land */
    findCenterOfRetangle(&yourLand);

    /* Find center of city land */
    findCenterOfRetangle(&cityLand);

    /* Handle the case where the centers are right on top of each other */
    if((yourLand.center.x == cityLand.center.x) &&
     (yourLand.center.y == cityLand.center.y))
    {
        /* Find the line through center and the top border */
        getLine(&(yourLand.midTop),&(cityLand.center),&lineThroughCenter);
    }
    else
    {
        /* Find the line through center of both lands */
        getLine(&(yourLand.center),&(cityLand.center),&lineThroughCenter);
    }

    /* Find the border cords */
    findBorderIntersection(&(yourLand),&lineThroughCenter);

    return 0;
}
void findBorderIntersection(RECTANGLE * pR, LINE * p)
{
    LINE line;
    CORD c1;
    CORD c2;

    int bTop = 0;

    getLine(&(pR->topL), &(pR->topR),&line);

    /* Figure out if the the line goes through the top/bottom or right/left */
    if( p->m != line.m)
    {
          findIntersection(p,&line, &c1);
          bTop = isPointContained(pR,&c1);
    }

    if(bTop)
    {
        getLine(&(pR->botL), &(pR->botR),&line);
        findIntersection(p,&line, &c2);
    }
    else
    {
        getLine(&(pR->topL), &(pR->botL),&line);
        findIntersection(p,&line, &c1);

        getLine(&(pR->topR), &(pR->botR),&line);
        findIntersection(p,&line, &c2);
    }

    dumpCord("Border Cord1:",&c1);
    dumpCord("Border Cord2:",&c2);

}

int isPointContained(RECTANGLE * pR, CORD * pC1)
{
    float pointProduct1;
    float vectorProduct1;
    float pointProduct2;
    float vectorProduct2;

    vectorProduct1 = dotProduct((pR->topL.y - pR->botL.y),
                               (pR->topL.y - pR->botL.y),
                               (pR->topL.x - pR->botL.x),
                               (pR->topL.x - pR->botL.x));

    pointProduct1 = dotProduct((pC1->y - pR->botL.y),
                              (pR->topL.y - pR->botL.y),
                              (pC1->x - pR->botL.x),
                              (pR->topL.x - pR->botL.x));

    vectorProduct2 = dotProduct((pR->botR.y - pR->botL.y),
                               (pR->botR.y - pR->botL.y),
                               (pR->botR.x - pR->botL.x),
                               (pR->botR.x - pR->botL.x));

    pointProduct2 = dotProduct((pC1->y - pR->botL.y),
                              (pR->botR.y - pR->botL.y),
                              (pC1->x - pR->botL.x),
                              (pR->botR.x - pR->botL.x));

    if( (pointProduct1 <= vectorProduct1) &&
        (pointProduct1 >= 0) &&
        (pointProduct2 <= vectorProduct2) &&
        (pointProduct2 >= 0))
    {
        return 1;
    }

    return 0;

}
float dotProduct(float y1, float y2, float x1, float x2)
{
    return y1*y2 + x1*x2;
}

void findCenterOfRetangle(RECTANGLE * pR)
{
     /* Find the mid point of the left side */
    findMidPointOfLine(&(pR->topL), &(pR->botL), &(pR->midLeft));

     /* Find the mid point of the right side */
    findMidPointOfLine(&(pR->topR), &(pR->botR), &(pR->midRight));

    /* Get the line */
    getLine(&(pR->midLeft), &(pR->midRight), &(pR->horLine));

     /* Find the mid point of the top side */
    findMidPointOfLine(&(pR->topL), &(pR->topR), &(pR->midTop));

     /* Find the mid point of the bottom side */
    findMidPointOfLine(&(pR->botL), &(pR->botR), &(pR->midBot));

    /* Get the line */
    getLine(&(pR->midTop), &(pR->midBot), &(pR->vertLine));

    /* Find the center of the first rectangle */
    findIntersection(&(pR->horLine), &(pR->vertLine),&(pR->center));

}
void findIntersection(LINE * pL1, LINE * pL2, CORD *pInt)
{

    if(pL1->mode == CORD_MODE_CONST)
    {
        pInt->x = pL1->m;
        pInt->y = ((pL2->m * pInt->x) + pL2->b);
    }
    else if(pL2->mode == CORD_MODE_CONST)
    {
        pInt->x = pL2->m;
        pInt->y = ((pL1->m * pInt->x) + pL1->b);
    }
    else
    {
        pInt->x = (pL2->b - pL1->b) / (pL1->m - pL2->m);
        pInt->y = ((pL2->m * pInt->x) + pL2->b);
    }
}

void findMidPointOfLine(CORD * pC1, CORD * pC2, CORD * pMid)
{
    pMid->y = (pC1->y + pC2->y) / 2;
    pMid->x = (pC2->x + pC1->x) / 2;
}
void getLine(CORD * pC1, CORD * pC2, LINE * pLine )
{

    /* Find slope */
    if((pC1->x - pC2->x) == 0)
    {
        pLine->mode = CORD_MODE_CONST;
        pLine->m = pC1->x;
        pLine->b = 0;
    }
    else
    {
        pLine->mode = CORD_MODE_SLOPE;
        pLine->m = ((pC1->y - pC2->y) / (pC1->x - pC2->x));

        /* Find y inter. */
        pLine->b = pC1->y - (pLine->m * pC1->x);
    }
}


Who's that pokemon (based on its etymology)?

JavaScript (Node.js 11.7+), 100%, 2094 bytes
Same as below, with the data file compressed with Brotli instead of zlib.
n=>a=>(require('zlib').brotliDecompressSync(require('fs').readFileSync('a'))+'').split`/`[n-1].replace(/\d.\d?/g,([i,p,l])=>a[i].substr(p,++l||9))

Try it online! (not working on TIO)

JavaScript (Node.js), 100%,  2176 2158  2151 bytes
This is similar to the self-contained version below but uses an external data file of 2010 bytes named 'a'. The TIO link generates a local copy of this file.
The final size was computed according to the rules for scoring multiple files:
$$2010+140+1=2151$$
n=>a=>(require('zlib').inflateRawSync(require('fs').readFileSync('a'))+'').split`/`[n-1].replace(/\d.\d?/g,([i,p,l])=>a[i].substr(p,++l||9))

Try it online!

JavaScript (Node.js), 100%,  2701 ... 2359  2356 bytes
Takes input as (id)([etymology0, etymology1, ...]).
The source contains many unprintable characters.
n=>g=(a,i=2,s="aZOEDQ]^4+24><e_<ZZ)aku[XdFyXdttoXdt|63a%}5ks/arbok_[__S♀E2a_S♂E_]]Sx_Sy`SytuffS[K~_SB]NO[h~[]?4PS@NB;2ZW)H~~pBR_]3!AA[r~?6G/@W@GA;5'dOOXel?3U~rXk~d,/!Z%~/@82arXix_S)ZD_~?3=I?3=CO;ak*@*@&tuV2)offHUXy`Xy`WseyWelaSs18/Ta*R[WyuWmie4~r/jyUS(~r[WosWkZXarados/lapras~eveeG_NXrT/omy/om(~~ps}5_XT3`[]*i&te[~P2Z[2efD/cyF(4]Q%NB4r>KW_/leledikXi([0Tu_$~f0,`Ye`Ye`/n/x`MXZ!ORR+22T3`oed[]]/ai!/2HV2^3~J_[_]W@+vXP]SarigWH2K3P+ce*&x/qwF`YzH2>Y(QW_M5]N+KW@]$NN`2K4XrT42OBR*@~um[M[y[2u~cZeWYSXgiho-ohWbiRWy,>E2^4C;3NBN^4%euFVM<17M]2|6XV4N3	SryD]Q/TtsJG+~8VA/U4,VE[ME]]2dEWH~]Q~[NOXVRRN<CQ5~leWn[Jse~lJQYvIQail`3aK]Z$NQ]B/3T3YnZ2e]2[/z=IO	],/corphH_[M3]Y2I?4ldo]2/4I/P4`)ec,XZ}7RMNSyut[KR]]2n/@eI]]{64/luv`XIQ{VC/P30TR__]_YiZYiZ)yogre_*zjir01Ss]K]_MO_KSy]XdZ2f|VCL6ZL6ZWx&oMO�NAA/buVZ]/H4Z{TnGXizC~zC?7{6{VW!Q[yO*iISkZ	M?2Uy_>N]Sjr.]]A/gZ@6$[E/=olu/luca=o~sE222kFuP2%_NA[N]MWa0b4[S&yXyV]SivZ]_]3__+Yo`XrT-zBB__/r0Im/uV$5/az`Ylgpalkia]3_QiphV~phyRYyminOni$[>WgMO/oshaw!*{TW=S<pDGQK###XnV2?5r222$~lYez,>[5aXggen3aXT2`	__�2Wr/guFr`3rDAWhawkMWlI]%>DJeeS4|VZ2Y0UIK5�)=ko=kL4C^3;niBM>~QEO|72ri18/tiFoPYF`WenWH3sXZ_YuaYoZYccV/ccV>QSt18DME2,]~Jite^3^3]aws`0UlH)FT3ZR/fooUYs{6�/alo0U0P&k^5GGLLL4ZXVkC3kkC222lgyem/beheeyem[D<Z~wYxHXxo24MQQ2rk~fooXZ3iTQOQRJlHRK^IWH3]/doQ?4F23]ENSkZWzZASZ$4am~kVm~ormM}53aR}53B�GRNK2ieD]Dby~sby^5AG<`RD[O];M3sQR+++OR]ENe<V&xNMK4XI^4kFVeMerQE>OBY082a?50aYv`[5X0TneRKYg`*LkiEMSa17�	M/xZ3eas/Z3lt25/zy`Yncie~aA/VRKW(<Z~pC3}5Xk2k_^3/yC3^52?7Wj(Xk(]R8Yc0PGO321_{T4iO[[|5OO3H/fo`ONW23RR~ul/!01_/H5072RaWey]D]GYos`/py=17@Vu~: `_D?2FIQ~de`Wkyu]K/d`4T-o-oL4-o3o~ V4iSg{UYg(]G]<V/xkH3eeaXrUNXcT2zC$[[_a=ka[7nYaZ	Qy/U5`_OK{7{6kwZB{6GG_lerO&t{VWW=/dF`Q;2VXIRFolQnRGRDWk{P07[2%>SskVB3<aSanremZ&@1]3~m`SgC/pZ2V]3%5'd~ riI~rig17K|Vmie/fF,Ym_RisP2eJT2%~f,A~zZWozZ~vZWovZAXVZQ/zaciU/za0UzTJtus~/}W1|Y1{S1`10_}0^J1]}1[|0Z11Y~3X~2W~4V12U0!03S~5R}2Q}3P04O|1N{1M|2L)01K|3J~6I13H05G{0FU2E{2D}4C14B{3A^1@20?/`>{4=0V<~7;YP,15+[4*[3)/k(a`&~i%|4$X`#/P3`_!2Ti`J`_3U3~eYk{5_4/T4~ `Z;20006/wa/09/s^2�}6_2	][16na/eanur~tWi")=>i<127?g(a,i+1,/[\r\n "'\--:\\a-z]/.test(c=Buffer([i]))?s:(l=s.split(c)).join(l.pop())):s.split`/`[n-1].replace(/\d.\d?/g,([i,p,l])=>a[i].substr('0x'+p,l||9))

Try it online!
How?
Each name is encoded as a sequence of sub-strings from the etymology words, with some possible hard-coded characters in between.
Example:
For the first name, we are given:
n = 1, a = ['bulb', '-saur']

The name bulbasaur is first encoded as 004a114, which is interpreted as:
'004' -> a[0].substr(0, 4) -> 'bulb'
'a'   -> hard-coded character 'a'
'114' -> a[1].substr(1, 4) -> 'saur'

But the length of the sub-string is omitted whenever this is possible without resulting in any ambiguity. When the length is omitted, the decoder assumes that the word must be read to its end.
Both lengths can be omitted in this case, so the final encoding is:
00a11

All the 890 encoding sequences are concatenated together, using / as a separator. This results in a string with a lot of repeated patterns which can be efficiently crushed:
00a11/00211/00412/00314/00313/00311/00514/00210324/00414/006e/00310/.../za001z03/005tus


R - 10 / 71 70 66 39 bytes = 0.26 points

Saved 27 bytes thanks to Mickey!

function(d,s)s[order(xor(!is.na(s),d))]

This creates an unnamed function which takes a direction d (logical with TRUE corresponding to right and FALSE to left (legit per OP's comment)) and a vector s (assumed to use NA for empty elements) as input and returns a vector. To call it, give it a name, e.g. f=function(d,s)....

This does not support "Moses Mode."

Ungolfed + explanation:

f <- function(d, s) {
    # Order the elements of s by non-missing exclusive or direction
    s[order(xor(!is.na(s), d))]
}

Examples:

> test <- c(1, 5, NA, NA, 4, 6, 2, NA, 2, 2, NA, 2, NA, NA, NA, NA)
> f(FALSE, test)
[1] NA NA NA NA NA NA NA NA  1  5  4  6  2  2  2  2
> f(TRUE, test)
[1]  1  5  4  6  2  2  2  2 NA NA NA NA NA NA NA NA

And an extra special example just for FryAmTheEggman:

> c(f(TRUE, test), "BATMAN")
[1] "1" "5" "4" "6" "2" "2" "2" "2" NA NA NA NA NA NA NA NA "BATMAN"


Perl

sub mymap (&@) {
  my $fn = shift;
  my @ret;
  while (my $val = shift) {
    local $_ = $_[0]; # map calling convention is element in $_
    push @ret, $fn->();
  }
  return @ret;
}

Looks plausible for at least a moment, until you have the sense to go "why isn't he using $val?"


Python, 166 162 159 bytes
You guys are much better. This is what I used! (the algorithm that solved it calls this)

from primefac import*
def c(n):
 x=factorint(n)
 a=''
 for i in range(len(x)):
  l=min(x.keys())
  a+=str(l)
  if x[l]>1:a+=str(x[l])
  x.pop(l)
 return int(a)


APL (99 76)

F←⍳S←10 20⋄'.T^~^To'[⊃7⌊1++/(⊂7×F∊{?S}¨⍳2),T×{F∊(?S)∘+¨+\{2-?3 3}¨⍳99}¨T←⍳3]

A bit longer than it needs to be (so that it gives better output) but I'll shorten it when the Golfscript answer comes in.

The GolfScript answer was posted so here's a shorter one. I thought of another (rather obvious, in hindsight) way to shorten it so that the output is not much worse than the original program, and it's even shorter than my original backup plan.

(In the old version, I had five bitfields that I was xor-ing with each other, now I have three that I am adding to each other.)

I have replaced the example output with output of the new version, of course.

Explanation:

F←⍳S←10 20: size is 20x10, F is a matrix where each element is its coordinates
{F∊(?S)∘+¨+\{2-?3 3}¨⍳99}¨T←⍳5: generate 3 bitfields, by starting at a random coordinate, and taking 99 random steps to a neighbouring field and then setting that bit on. 99 seems high but it often backtracks as it is random. This makes the maps for the areas.
(⊂7×F∊{?S}¨⍳2): Add in two villages.
⊃7⌊1++/: sum the areas, giving a matrix where each number represents a certain type. Cap it at 7, because the villages might appear in another area giving high numbers.
'.T^~^To'[...]: replace each number with the right character. There are 3 possibly overlapping fields so the highest possible value is 6. (3+3)

Example output:

....TTT.TTT...TTT.^^
...TT....TTT....T..^
....T....TT.......^^
...~..o..T..^^...^^.
...~.........^^^^^^^
...~~~~....^^..^^^..
~..~~~......^.^.^^^^
~~.~~~......^^.^^^..
~.~~~~........o.....
~~~~~~..............

and

.....o........~~..~~
..............~~~~~.
.^T.T..........~~.~.
^T~~TTTTTT.......~~~
~~~~TT.TT.T......~~~
^~^TTT....T.....~~~~
^^^^T.....T...T..~~.
^^^^.......TT.T.....
^^^^.........TT.....
^^^^.........o......

Old version:

F←⍳S←10 20⋄G←{F∊(?S)∘+¨+\{2-?3 3}¨⍳99}¨T←⍳5⋄'.T^~^To'[⊃7⌊1++/(⊂7×F∊{?S}¨⍳2),T×{(⊃⍵⌽G)∧~⊃∨/1↓⍵⌽G}¨T]


Python 2, 99 73 65 64 63 bytes

lambda s:'PVC'*('ea'in s)or'wtoiondnyy'[s[-2:]in'instperit'::2]

Try it online!

Alternatives also with 63 bytes:

lambda s:'PVC'*('ea'in s)or'wtoiondnyy'[s[-6::5]in'dtenmsr'::2]
lambda s:'PVC'*('ea'in s)or'wtoiondnyy'[s[::5]in'lrinaosit'::2]


C (Windows), 361 bytes

#import<time.h>
#import<windows.h>
C(x){SetConsoleTextAttribute(GetStdHandle(-11),x);}F(I,N,l,a,n,d)time_t n;struct tm*d;{system("mode 90,65");time(&n);d=gmtime(&n);n=d->tm_year<<24|d->tm_mon<<16|d->tm_mday<<8|d->tm_hour;for(a=l=I=15;I++<70;a=l=I<35|I>49?15:9)for(N=n>1963656468&I<17?C(240),printf("100"):0;N++<90;a=N-25?a:9,a=N-40||l==9?a:15)C(a),putchar(70);}

Unrolled:

#import <time.h>
#import <windows.h>

C(x)
{
    SetConsoleTextAttribute(GetStdHandle(-11),x);
}

F(I,N,l,a,n,d) time_t n;struct tm*d;
{
    system("mode 90,65");

    time(&n);
    d = gmtime(&n);
    n = d->tm_year<<24 | d->tm_mon<<16 | d->tm_mday<<8 | d->tm_hour;

    for(a=l=I=15; I++<70; a=l=I<35|I>49?15:9)
        for(N=n>1963656468&I<17?C(240),printf("100"):0; N++<90; a=N-25?a:9,a=N-40||l==9?a:15)
            C(a), putchar(70);
}

Output:

Output when UTC time >= 2017-12-05-22-00:

Add the following in the code after d=gmtime(&n); to try it:

d->tm_year = 117;
d->tm_mon = 11;
d->tm_mday = 5;
d->tm_hour = 21;


JavaScript (ES7), 70 bytes
Returns a Boolean value.

(a,b,c,t)=>(t-=c,(a*=2)?(x=(b*b+2*a*t)**.5-b)%a&&(x+b+b)%a:b?t%b:t)==0

Try it online!
How?
For the sake of clarity, we define \$d = T_n-c\$. (The same variable \$t\$ is re-used to store this result in the JS code.)
Case \$a\neq0\$
The equation really is quadratic:
$$T_n=an^2+bn+c\\
an^2+bn-d=0$$
With \$a'=2a\$, the discriminant is:
$$\Delta=b^2+2a'd$$
and the roots are:
$$n_0=\frac{-b-\sqrt{\Delta}}{a'}\\
n_1=\frac{-b+\sqrt{\Delta}}{a'}$$
The equation admits an integer root if \$\sqrt{\Delta}\$ is an integer and either:
$$\begin{align}&-b-\sqrt{\Delta}\equiv 0\pmod{a'}\\ \text{ or }&-b+\sqrt{\Delta}\equiv 0\pmod{a'}\end{align}$$
Case \$a=0, b\neq0\$
The equation is linear:
$$T_n=bn+c\\
bn=d\\
n=\frac{d}{b}$$
It admits an integer root if \$d\equiv0\pmod b\$.
Case \$a=0, b=0\$
The equation is not depending on \$n\$ anymore:
$$T_n=c\\
d=0$$


JavaScript (ES6),  45  44 bytes
Takes input as (n)(p1), where \$n\$ is 0-indexed.

n=>g=(p,d=2)=>n?~p%d?g(p,d+1):--n?g(p*d):d:p

Try it online!
Commented
n =>                // n = 0-based index of the requested term
  g = (             // g is a recursive function taking:
    p,              //   p = current prime product
    d = 2           //   d = current divisor
  ) =>              //
    n ?             // if n is not equal to 0:
      ~p % d ?      //   if d is not a divisor of ~p (i.e. not a divisor of p + 1):
        g(p, d + 1) //     increment d until it is
      :             //   else:
        --n ?       //     decrement n; if it's still not equal to 0:
          g(p * d)  //       do a recursive call with the updated prime product
        :           //     else:
          d         //       stop recursion and return d
    :               // else:
      p             //   don't do any recursion and return p right away


Golf a bijection within the natural numbers which map the primes to a proper subset of the primes

Mathematica, 54 48 bytes

±(t=x_?PrimeQ)=NextPrime@x
±n_:=Abs[n-1]/.t:>x-1

Defines the following bijection:

 n  0, 1, 2, 3, 4, 5, 6,  7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, ...
±n  1, 0, 3, 5, 2, 7, 4, 11, 6, 8,  9, 13, 10, 17, 12, 14, 15, 19, ...

The basic idea is to map each prime to the next, to ensure that they are mapped to a proper subset. This results in a "gap" at 2. To fill that gap, we want to map 4 to 2 and then each other composite number to the previous composite number, to "bubble up" the gap. Since 2 and 3 are the only two adjacent primes, we can express both of those mappings as "n-1 or if that's a prime then n-2". Finally, this mapping ends up sending 1 to 0 and we make it send 0 back to 1 by taking the absolute value of n-1.


APL (Dyalog Unicode) with Co-dfns, 7 bytesSBCS

Anonymous prefix lambda. I have verified with the author of Co-dfns that the code will indeed run according to the required spec.

{+.×⍨⍵}

Try it online! (equivalent code, but TIO doesn't provide GPU access)

{…} compilable dfn; ⍵ is the argument vector

 +.× dot-product of

 ⍨ itself ("selfie")

 ⍵ using the argument as data


Generate alphabet with 4 copies of each letter

APL (5)

⍪4/⎕A

Matrix format (⍪) of 4-replication (4/) of alphabet (⎕A).


R, 179 158 151 bytes
function(s,m){p=1;t=c(which(diff(s)<0),length(s));for(i in t){d=c(s[p]-m,s[(p+1):i],s[i+1]+m);if(p==1)d[1]=s[1];if(p==t[-1])d=head(d,-1);print(d);p=i}}

Try it online!
Edit: Code is now a function and takes input. (Thanks to Giuseppe, user202729 and JayCe for calmly pointing that out)
Edit: -21 bytes suggested by Giuseppe.
Edit: -7 bytes by removing d=NULL;.


Python 3, 363 308 293 274 characters

import os,sys,re,collections as C
c=C.Counter()
n=sys.argv[1]
o="graph d{"
for w in re.findall("\w*",open(n).read()):c[w]+=1
for w,x in c.most_common(75)[1:]:o+="%s[fontsize=%s,shape=none];"%(w,x/5)
open(n+'.dot','w').write(o+"}")
os.system("fdp -Tpng %s.dot>%s.png"%(n,n))

Call it like this: python cloud.py file.txt. The script uses Graphviz's fdp force-directed graph generator to generate the image (it will spit out a GraphViz file to file.txt.dot and a PNG image file to file.txt.png). This means you'll need to have Graphviz installed.

The image above is the cloud it makes of Shakespeare's Hamlet - you can tell, since it contains "To be or not to be". There's also some delightful nonsense to be found:

  It is, to You and I, the Ham of Not thatO lord have us, what now...


CJam, 21 bytes
qN/:.e>(o2%:i"DRXU"f=

Fold the lines (:) by vectorizing (.) a character-wise maximum operation e>. Since there is only one non-space character in each column, this one will be the result, as space has a smaller ASCII code than all printable non-space characters.
Unshift and print the first asterisk (o, then map every other (2%) remaining char to UDR using modular indexing.
Old solution (29 bytes)
'*qN/z2%'*f#0+2ew);::-"RDU"f=

qN/ gets input lines. z transposes this character matrix. 2% drops every odd row. '*f# finds the index of the asterisk in each row. 0+2ew); gets all successive pairs of indices. ::- computes their differences, and "RDU"f= maps them to letters (via modular indexing: 0 → R, 2 → U, -2 ≡ 1 → D). The leading '* prepends the asterisk.
EDIT: I changed 2ew to 0+2ew); to work around CJam not handling ew (successive slices) on lists that are too short. This makes the code work for the input string *.
Try it here, or watch it in action:


Of Dumps and Cubes, and Structured Nonsense

Clean, 150 145 143 bytes

Contains many non-printable characters.

import StdEnv
$d=map(\c=['ULFRBD ']!!(digitToInt(['96':d]!!(toInt c))))['!�B5J8P;H2)*\'&-,/$ "C76A43O1<Q:9']

Try it online!

Defines the function $, taking [Char], and giving [Char].

This works by mapping each character position in the input to another character position in the output (using the character codes in a string), taking advantage of the swapped 'cubies' in the output being paralleled by swapped colors in the corresponding position in the input.

Output is separated by spaces.


Python 3, Hello World + Quine = Cat, 129 bytes

Hello World:
import os,atexit as a
p=print
a.register(p,"Hello World!")
def print(_):
 p(input())
 os._exit(0)

Quine:
s='s=%r;print(s%%s)';print(s%s)

Cat:
import os,atexit as a
p=print
a.register(p,"Hello World!")
def print(_):
 p(input())
 os._exit(0)
s='s=%r;print(s%%s)';print(s%s)

atexit lets you define cleanup steps that will run when your program exits "normally". In this case, I register the print function (renamed p) with the argument "Hello World!", so it will print that string when the program ends.
I then redefine print to become a cat function. Normally, this would cause the program to print its input and "Hello World!", but os._exit() is an "abnormal" exit that bypasses the cleanup steps.
Now that print has been redefined, the Quine simply calls this cat function and the program abruptly exits. If the Quine doesn't exist, then the program exits normally, printing "Hello World!" in the process.
The final program doesn't work on TIO, but it works for me running Python 3.7.3 on MacOS.


Wolfram Language (Mathematica), 45 bytes

Because the other solution is incorrect (see Martin's comment below), so I decide to post my solution:

8~KnightTourGraph~8~AdjacencyList~#&~Nest~##&

Try it online!

Ultimate infix notation...

Takes 2 input, the first one is a list of numbers in range [1,64] describe the starting positions of the knight, the second one is the number of steps.

This solution relies on the extreme convenience of Mathematica builtin functions:

AdjacencyList may takes a list of vertices on its right side, and return a list of vertices adjacent to any of those, already removed duplicates and sorted.
KnightTourGraph is a builtin. Not surprise.
Nest takes arguments in order Nest[f, expr, n], which we can splat the ## over its right side as Nest[f, ##].
And finally, Mathematica parse a~b~c~d~e as (a~b~c)~d~e, so no square bracket is necessary. Without infix notation and flatten ##, it would be Nest[AdjacencyList[KnightTourGraph[8, 8], #] &, #, #2]&.


Python 2, 80 79 bytes

D=1;N=n=0;exec"n+=1;y=N=N*n+D;x=D=D*n;"*input()
while y:x,y=y,x%y
print N/x,D/x

Try it online!

Prints the numerator and denominator.

Yay! MathJax support!!!! One observes:

$$\sum_{i=1}^{n} \frac{1}{i} = \sum_{i=1}^{n} \frac{n!}{n!i} = \frac{\sum_{i=1}^{n} \frac{n!}{i}}{n!}$$

Then, thinking about recursion, for \$n\$ positive, in the Numerator:

$$\sum_{i=1}^{n+1} \frac{(n+1)!}{i} = (n+1) \sum_{i=1}^{n} \frac{n!}{i} + \frac{(n+1)!}{n+1} = (n+1) \sum_{i=1}^{n} \frac{n!}{i} + n!$$

and one can't help think of the Denominator \$n!\$ recursively as well; thus the exec.

We must pay the Reduced Fraction Piper with a GCD calculation in the while loop; and then we're done.


Python, 27 bytes

lambda a,b:[a,b][2*b*b>a*b]

Try it online!

An arithmetic formula. Why is the negation of 2*b*b>a*b equivalent to the problem condition a-b in symrange(a,b)?

Note that x in symrange(a,b) is equivalent to 0 in symrange(a-x,b-x). Applying this to x=a-b gives 0 in symrange(b,2*b-a). The value 0 is included in the interval unless it stretches between two positive values or two negative values. This can be stated arithmetically as  "their product b*(2*b-a) is not positive.

Finally, take b*(2*b-a)<=0, and rewrite to 2*b*b<=a*b. A byte is saved by flipping <= to > and switching the cases.


Husk, 72 58 bytes
mṙ1₁Fz+m(₁TT' Ṡ:→S:öR'-→▲mL)TTømėF`-FnF-
Ṡz:(`:'+:'+R'|-2L

Try it online!
Husk does not support arrays of multiple types, so the arguments must be string arrays.
I am not sure whether I want to explain this monstrosity.
Due to it's sheer size, it takes about 28 secs(due to type inference) for the first test case mentioned. Without some of the type inference issues, this could be a lot shorter.
-14 bytes with a lot of adjustments(I got better at Husk).


GolfScript + CJam + Fission 2 + Jelly, 4 languages, 24 bytes, score 2.667
Let's start with the hex dump:
00000000:  3322 3024 700a 2721 2b4f 5222 0a3c 3024 700a 6523 7fff cccc

For GolfScript, CJam and Fission 2, we interpret this in some ASCII-compatible single-byte encoding like ISO 8859-1 (the exact encoding doesn't really matter, because the languages only define operators for ASCII characters anyway):
3"0$p
'!+OR"
<0$p
e#<DEL>ÿÌÌ

Where <DEL> is the control character 0x7f.
In Jelly, this is assumed to be in Jelly's own code page, where it looks like this instead:
3"0$p½'!+OR"½<0$p½e#¶”ṘṘ

GolfScript
The e on the last line is an unknown variable and # comments out the remainder of the line, so this prints
"0$p"
0$p

with a trailing linefeed. This is the GolfScript/CJam polyglot version of the standard quine:
".p"
.p

Try the polyglot. | Try the quine.
CJam
Here, e# comments out the last line, so almost identically, this prints
"0$p"
0$p

without a trailing linefeed.
Try the polyglot | Try the quine.
Fission
Fission only sees the second line which is the standard Fission quine, so it prints
'!+OR"

I can't provide an online link for the polyglot here, because TIO sends the file to Fission as UTF-8, but Fission reads the source byte by byte, which makes the last line too long. However, I've tested this locally with an ISO 8859-1 encoded file (in which the last line has the same length as the second), to confirm that this works.
Try the quine.
Jelly
The pilcrow is an alias for linefeeds in Jelly, so the source is equivalent to:
3"0$p½'!+OR"½<0$p½e#
”ṘṘ

All but the last line of a Jelly program are "helper links" (i.e. functions) which can be ignored unless they are called, provided they are syntactically valid. This is actually the reason the 3 comes first in the CJam and GolfScript programs, because otherwise the " can't be parsed in Jelly.
Otherwise, since the function isn't called, the program is equivalent to only its second line, which is the standard Jelly quine.
Try the polyglot. | Try the quine.


brainfuck, 39 38 35 bytes

Saved 3 bytes thanks to @Dorian.

,+++>,>,.,.<<.-->>,.,.,[-<->]<[<.<]

Try it online!

This abuses the fact that the characters *,+, and - are very close to each other in ASCII.

Ungolfed:

,+++>  create a minus from the first asterisk
,>      store the second asterisk for comparison later
,.      display T
,.      display I
<<.-->> display the minus from line 1 and turn it into a plus
,.      display first number
,.      display second number

,[-<->]<[  if the last char is not an asterisk from line 2
  <.<      display the plus from line 5
]

Original 38 byte solution:

>,+++>,>,.,.<<.-->>,.,.,<[->-<]>[<<.<]

Original 39 byte solution:

,+++>,>,.,.<<.-->>,.,.,<[->-<]>[<<.[-]]


A Pear Tree, 76 bytes

$@='NOT ';print"$@CORRUPTED"__DATA__ =®®”print"$@CORRUPTED"__DATA__ =®®”Ê®›~

This program contains a few stray octets that aren't valid UTF-8. As such, it's shown as it looks in Windows-1252. (By default, if A Pear Tree sees a non-ASCII octet in a string literal or the like it treats it as an opaque object and doesn't try to understand it beyond being aware of what its character code is; this behaviour can be changed via an encoding declaration but the program doesn't have one. So the program is logically in "unspecified ASCII-compatible character set". All the non-ASCII octets are in comments anyway, so it doesn't really matter.)

Explanation

A Pear Tree checksums the program, looking for the longest substring that has a CRC-32 of 00000000. (If there's a tie, it picks the octetbetically first.) Then the program gets rotated to put it at the start. Finally, the program gets interpreted as a language that's almost a superset of Perl, defining a few things that are undefined in Perl to work the same way as in Python (and with a few minor changes, e.g. print prints a final newline in A Pear Tree but not in Perl). This mechanism (and the language as a whole) was designed for polyglot and radiation-hardening problems; this isn't the former, but it's definitely the latter.

In this program, we have two notable substrings that CRC-32 to 00000000; the entire program does, and so does print"$@CORRUPTED"__DATA__ =®® by itself (which appears twice). As such, if the program is uncorrupted, it'll set $@ to NOT  and then print it followed by CORRUPTED. If the program is corrupted, then the CRC-32 of the program as a whole will fail to match, but one of the shorter sections will remain uncorrupted. Whichever one is rotated to the start of the program will just print CORRUPTED, as $@ will be the null string.

Once the string's been printed, __DATA__ is used to prevent the rest of the program running. (It crosses my mind writing this that __END__ could be used instead, which would clearly save two bytes. But I may as well post this version now, because I've spent a bunch of time verifying it, and a modified version would have to be re-verified due to the CRC changes; and I haven't put a huge amount of effort into golfing the "payload" yet, so I want to see if anyone has other improvements in the comments that I can incorporate at the same time. Note that # doesn't work in the situation where a character is corrupted into a newline.)

You might be wondering how I managed to control the CRC-32 of my code in the first place. This is a fairly simple mathematical trick based on the way that CRC-32 is defined: you take the CRC-32 of the code, write it in little-endian order (the reverse of the byte order that's normally used by CRC-32 calculation programs), and XOR with 9D 0A D9 6D. Then you append that to the program, and you'll have a program with a CRC-32 of 0. (As the simplest example possible, the null string has a CRC-32 of 0, thus 9D 0A D9 6D also has a CRC-32 of 0.)

Verification

A Pear Tree can handle most sorts of mutations, but I'm assuming "changed" means "replaced with an arbitrary octet". It's theoretically possible (although unlikely in a program this short) that there could be a hash collision somewhere that lead to the wrong program running, so I had to check via brute force that all possible octet substitutions would leave the program working correctly. Here's the verification script (written in Perl) that I used:

use 5.010;
use IPC::Run qw/run/;
use warnings;
use strict;
undef $/;
$| = 1;
my $program = <>;
for my $x (0 .. (length $program - 1)) {
    for my $a (0 .. 255) {
        print "$x $a    \r";
        my $p = $program;
        substr $p, $x, 1, chr $a;
        $p eq $program and next;
        alarm 4;
        run [$^X, '-M5.010', 'apeartree.pl'], '<', \$p, '>', \my $out, '2>', \my $err;
        if ($out ne "CORRUPTED\n") {
            print "Failed mutating $x to $a\n";
            print "Output: {{{\n$out}}}\n";
            print "Errors: {{{\n$err}}}\n";
            exit;
        }
    }
}

say "All OK!    ";


Matlab, 292
I am sure this can be shortened a lot just by porting it into another language.
The basic idea is bruteforcing: I came up with kind of an enumeration of all ways how to place m*n/2 domino bricks on an m*n board. But this enumeration also includes many invalid tilings (bricks that overlap or go outside of the board.) So the program constructs all those tilings, and only counts the valid ones. The runtime complexity is about O(2^(m*n/2) * m*n). Memory is not a problem for the 8x8 as it only needs O(m*n) memory. But the time needed for 8x8 is about 20 days.
Here the fully commented version that explains what is going on.
PS: If anyone knows how to make the Matlab syntax highlighting work, please include the corresponding tag in this answer!
function C=f(m,n)
d = ceil(m*n/2);%number of dominoes
%enumeration: %the nth bit in the enumeration says whether the nth
% domino pice is upright or not. we enumerate like this:
% firt piece goes top left:
% next piece goes to the left most column that has an empty spot, in the
% top most empty spot of that column
C=0;%counter of all valid tilings
for e=0:2^d-1 %go throu all enumerations
    %check whether each enumeration is valid
    A = ones(m,n);
    %empty spots are filled with 1
    %filled spots are 0 (or if overlapping <0)
    v=1;%flag for the validity. hte grid is assumed to be valid until proven otherwise
    for i=1:d %go throu all pieces, place them in A
        %find the column where to place:
        c=find(sum(A)>0,1);
        %find the row where to place:
        r=find(A(:,c)>0,1);
        %find direction of piece:
        b=de2bi(e,d);
        if b(i)
            x=0;y=1;
        else
            x=1;y=0;
        end
        %fill in the piece:
        try
            A(r:r+y,c:c+x)=A(r:r+y,c:c+x)-1;
        catch z
            v=0;break;
        end
        %check whether A has no overlapping pieces
        if any(A(:)<0)
            v=0;break;
        end
    end
    %if valid, count it as valid
    if v && ~norm(A(:))
        disp(A)
        C=C+1;
    end
end

Here the fully golfed one:
function C=f(m,n);m=4;n=6;d=ceil(m*n/2);C=0;for e=0:2^d-1;A=ones(m,n);v=1;for i=1:d;c=find(sum(A)>0,1);r=find(A(:,c)>0,1);b=de2bi(e,d);if b(i);x=0;y=1;else;x=1;y=0;end;try;A(r:r+y,c:c+x)=A(r:r+y,c:c+x)-1;catch z;v=0;break;end;if any(A(:)<0);v=0;break;end;end;if v && ~norm(A(:));C=C+1;end;end


C++11, 186 184 bytes

#include<map>
int i,c;int main(){std::map<int,int>p;while(~(c=getchar())){for(int m:{40,41,95,64,36,38})p[i]+=c==m;for(int m:{33,124,46,34,58})if(c==m&&!p[i]--)return 1;i=c-10?i+1:0;}}

Ungolfed

#include <map>
int i, c;
int main()
{
    std::map<int, int> p;
    while (~(c = getchar()))
    {
//        for (int m : { '(', ')', '_', '@', '$', '&'})
        for (int m : { 40, 41, 95, 64, 36, 38})
            p[i] += c == m;
//        for (int m : { '!', '|', '.', '"', ':'})
        for (int m : { 33, 124, 46, 34, 58})
            if (c == m && !p[i]--)
                return 1;
        i = c - '\n' ? i + 1 : 0;
    }
    return 0;
}

Basic approach, storing positions of cloud particles in a row and if rain particle is encountered, it checks whether the cloud particle is above it and decreases the counter of cloud particles in that column. The program returns 0 if it's valid and 1 otherwise.


Jelly, 26 25 bytes
2ṗ⁵’µ×“wØ][:koR¶{‘^/=µÐfḢ

Try it online!
Takes input as a 7-bit integer. Returns the binary form of a 10-bit integer.
This just brute forces all possibilities. Remove the Ḣ to get all possible outputs or replace it with an X to get a random possible output.
Magic Visualization Program!
How it works
2ṗ⁵’µ×“wØ][:koR¶{‘^/=µÐfḢ  - main link, takes one integer
2ṗ⁵’                       - generate all length-10 binary arrays
    µ                µÐf   - now we find those arrays which correspond to digit-
                              sequences which work to switch off all segments:
                              Filter (keep) those arrays which:
     ×                      - multiplied by
      “wØ][:koR¶{‘          - [119, 18, 93, 91, 58, 107, 111, 82, 127, 123]
                               (encoding for turned-on segments given number)
                  ^/        - reduced by XOR
                    =      - are equal to (implicit) the program's input
                        Ḣ  - output the first of these valid arrays


Unicorn (ES6), 5934 5278 bytes

Under the custom encoding, this is 5278 bytes (1 byte per char); but with UTF-8, it would 4 bytes per char (though only 1 for a space), or 20869 total.

(too many Unicorns and Goats to reasonably display here)

Instead, here's a pastebin. This Unicorn code transpiles to this JS snippet:

s=>eval(s.replace(/\S+ ?/g,c=>String.fromCharCode(c.length>>1<<c.charCodeAt()%2)))

Now, this isn't the shortest possible version; this is shorter:

s=>eval(s.replace(/\S+ ?/g,c=>String.fromCharCode(c.length>>1<<("">c))))

However, the one unicorn in there would transpile to 56034 goats, thus multiplying the score by roughly 11.

Here's the function I used to transpile to Unicorn:

function g(s){return s.replace(/./g,function(c){i=c.charCodeAt();return(i%2?"".repeat(i):"".repeat(i/2))+" "}).slice(0,-1)}
<textarea id=O cols=100></textarea><button id=P onclick="Q.value=g(O.value);R.innerHTML=(Q.value.length+Q.value.split(' ').length-1)/2">Run</button>
<textarea id=Q rows=10 cols=100>Output appears here.</textarea>

Length: 0

Note: I haven't actually tested the program, as there isn't an online interpreter that I could find (although I suppose I could hook up the .js file to HTML...?)


Jelly, 14 7 bytes

_þ%ṀṬSE

Try it online!

How it works

_þ%ṀṬSE  Main link. Argument: A (array of unique elements / ordered set)

_þ       Subtract table; yield a 2D array of all possible differences of two
         (not necessarily distinct) elements of A.
  %Ṁ     Take the differences modulo max(A).
    Ṭ    Untruth; map each array of differences modulo max(A) to a Boolean array
         with 1's at the specified indices. Note that all 0's in the index array
         are ignored, since indexing is 1-based in Jelly.
     S   Take the sum of these arrays, counting occurrences.
      E  Test if all resulting counts are equal.


Abuse the preprocessor

All SILOS programs can optionally have a macro statement on the second line

Consider the following program... One of my favorite SILOS submissions by betseg.

a=97
def q print z bottle v beer L Line g wall x IntNoLine h the c around
qL 99 zs of v on h g, 99 zs of v.
lbls
q Take one down and pass it c,
a+1
qx a
qL  zs of v on h g.
qx a
q  zs of v on h g,
qx a
qL  zs of v.
a-2
if a s
qL Take one down and pass it c, 1 z of v on h g.
qL 1 z of v on h g, 1 z of v.
q Go to h store and buy some more, 99 zs of v on h g.

Look at that savings
Try it out!


J - 19 char

Couldn't help it ;)

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

Explanation follows:

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

Usage:

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

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


Ruby, 390 chars
o=->s,c{f=s=~/o/;[*0..8].select{|t|s[t]==c&&(t<1||(t+6)%8+1==f||t%8+1==f||f<1&&(s[(t+6)%8+1]!=c||s[t%8+1]!=c))}.map{|t|k=s*1;k[f]=c;k[t]=?o;k}}
v=->s,c,h{f=o[s,c];f==[]?0:h<1?1:2-f.map{|t|v[t,c>?b??b:?w,h-1]}.min}
q=->g{puts"1-2-3\n|\\|/|\n8-0-4\n|/|\\|\n7-6-5\n".tr"0-8",g;$>.flush}
q[g="obbbbwwww"]
(g.tr!?o,?b;g[gets.to_i]=?o;q[g];q[g=o[g,?w].sort_by{|q|v[q,?w,5]}[-1]])while v[g,?b,5]>0

An implementation in ruby which directly calculates the game tree (which takes quite some code) and thus always plays optimally. The board positions are spiraling outwards as shown in the following figure:
1 - 2 - 3
| \ | / |
8 - 0 - 4
| / | \ |
7 - 6 - 5


Haskell, 69 bytes

x#a|x<3=1|a>x=a#2+(x-1)#2|mod x a<1,a<x=a#2*div x a#2|b<-a+1=x#b
(#2)

Usage example: (#2) 1025 -> 81

The parameter a is counted up until it divides x or it reaches x (i.e. x is prime). It it one byte shorter to test for a > x and add a further condition (a < x) to the modulus test instead of testing for a == x, because the former binds a to x+1, which helps in the recursive call. Compare:

|a==x=(x+1)#2+(x-1)#2|mod x a<1=
|a>x=a#2+(x-1)#2|mod x a<1,a<x=


Ruby, 1220

Wow that was something... I didn't think it would take THAT much to make this, but hey, only way to learn was try it. It's clear now why there weren't any answers to the question...

Well, I'm sure this is golfable, but It's been a whole job only to make it. Following is golfed code and then ungolfed with some explanations:

e=[[]]
while(a=gets)
if(a=a.chomp)==""
e.push []
else
e.last.push a.chomp
end
end
e.keep_if{|p|p!=[]}
e.map!{|p|m={}
t=p[0].strip
if t.length==1
m[:t]=t
l=p[1].split" "
b=p[2]
else
m[:t]=nil
l=t.split" "
b=p[1]
end
x=l[0]=~/\d/
m.merge!({l: !x ? l[0]:nil,v:(x ? l[0]:l[1]).to_i,r:x ? l[1]:l[2]})
m[:b]=b.nil? ? nil:b.strip
m}
w=e.select{|p|p[:t].nil?}.length
h=e.length/w
def c(j,p,l)
x=l[0]
y=l[1]
(x==0&&p[:l].nil?||x!=0&&(j[x-1][y].nil?||j[x-1][y][:r].swapcase==p[:l]&&(j[x-1][y][:v]-p[:v]).abs<2))&&(x==j.length-1&&p[:r].nil?||x!=j.length-1&&(j[x+1][y].nil?||j[x+1][y][:l].swapcase==p[:r]&&(j[x+1][y][:v]-p[:v]).abs<2))&&(y==0&&p[:t].nil?||y!=0&&(j[x][y-1].nil?||j[x][y-1][:b].swapcase==p[:t]&&(j[x][y-1][:v]-p[:v]).abs<2))&&(y==j[0].length-1&&p[:b].nil?||y!=j[0].length-1&&(j[x][y+1].nil?||j[x][y+1][:t].swapcase==p[:b]&&(j[x][y+1][:v]-p[:v]).abs<2))
end
def d(j,q,l)
f=[false,[]]
q.each_index{|i|p=q[i]
if c j,p,l
r=q.dup
r.delete_at i
j2=j.dup
j2[l[0]][l[1]] = p
if r.length==0
f = [true,j2]
break
else
n=l[0]+1
l2=[n%j.length, l[1]+n/j.length]
f = d(j2,r,l2)
break if f[0]
end
end}
f
end
j=[]
w.times{j.push [];h.times{j.last.push nil}}
s=d(j,e,[0,0])
h.times{|y|w.times{|x|print s[1][x][y][:v].to_s+" "}
puts''}

Ungolfed:

pieces=[[]]
while (a=gets) # Read the input and separate by pieces when finding an empty line
  if (a=a.chomp)==""
    pieces.push []
  else
    pieces.last.push a.chomp
  end
end
pieces.keep_if{|p|p!=[]} # Remove possible empty pieces
pieces.map!{|p| # Parse each piece
  m={}
  t=p[0].strip
  if t.length==1
    m[:t]=t
    l=p[1].split" "
    b=p[2]
  else
    m[:t]=nil
    l=t.split" "
    b=p[1]
  end
  x=l[0]=~/\d/
  m.merge!({l: !x ? l[0]:nil,v:(x ? l[0]:l[1]).to_i,r:x ? l[1]:l[2]})
  m[:b]=b.nil? ? nil:b.strip
  m
}
w=pieces.select{|p|p[:t].nil?}.length
h=pieces.length/w

def fits(j,p,l) # This function determines if a piece fits in an empty spot
  (l[0]==0&&p[:l].nil? || l[0]!=0 && (j[l[0]-1][l[1]].nil? || j[l[0]-1][l[1]][:r].swapcase==p[:l] && (j[l[0]-1][l[1]][:v]-p[:v]).abs<2)) &&
    (l[0]==j.length-1&&p[:r].nil? || l[0]!=j.length-1 && (j[l[0]+1][l[1]].nil? || j[l[0]+1][l[1]][:l].swapcase==p[:r] && (j[l[0]+1][l[1]][:v]-p[:v]).abs<2)) &&
    (l[1]==0&&p[:t].nil? || l[1]!=0 && (j[l[0]][l[1]-1].nil? || j[l[0]][l[1]-1][:b].swapcase==p[:t] && (j[l[0]][l[1]-1][:v]-p[:v]).abs<2)) &&
    (l[1]==j[0].length-1&&p[:b].nil? || l[1]!=j[0].length-1 && (j[l[0]][l[1]+1].nil? || j[l[0]][l[1]+1][:t].swapcase==p[:b] && (j[l[0]][l[1]+1][:v]-p[:v]).abs<2))
end

def rec(j,pl,l) # Recursive function to try every piece at every position it can fit
  found = [false,[]]
  pl.each_index{|i|
    p=pl[i]
    if fits(j,p,l) # Try the piece in the spot
      pl2=pl.dup
      pl2.delete_at i
      j2=j.dup
      j2[l[0]][l[1]] = p
      if pl2.length==0 # If we have spent all the pieces, then we have a complete puzzle
        found = [true,j2]
        break
      else             # Keep recurring until we use up all the pieces
        n=l[0]+1
        l2=[n%j.length, l[1]+n/j.length]
        found = rec(j2,pl2,l2)
        break if found[0]
      end
    end
  }
  found
end

j=[]
w.times { j.push []; h.times { j.last.push nil }}
solved = rec(j, pieces, [0,0])
h.times{|y|
  w.times{|x|
    print solved[1][x][y][:v].to_s + " "
  }
  puts ''
}


Make a (somewhat) self-referential string

C, 64 bytes

l,i;main(n){for(scanf("%d%n",&n,&l);i<n;)printf("%0*d",l,i+=l);}

Takes a single integer as input on stdin.


gdb, 108 chars

star
b open if !(int)strcmp(((char**)$esp)[1],"orange.txt")
comm
set((char**)$esp)[1]="green.txt"
c
end
c
q

Save as the file redirect and run like this:

gdb -x redirect <program you want to redirect>

Works on x86 (linux at least, and probably Windows/Mac also).  Here's what the lines do:

star = start gets to the beginning of main (needed so open is defined for the next step).

b open if... = break if we're calling open on orange.txt

comm = command the code up to the next end is executed when the breakpoint fires.

set ((char*))... = replace the open argument with green.txt

c=continue

q=quit


Haskell, 19 bytes

foldr1(/).tail.init

Given a flat list like [a,b,c,d,e,f], tail.init removes the first and last elements, and then foldr1(/) creates a cascade of divisions b/(c/(d/e)))) that works out to alternating * and /: b/c*d/e.


Python, 34 bytes

lambda a,b:bin(a&b).count('01')==1

Try it online!
Although this doesn't use xor, I'm xnor.


Fastest C/C++ comparison function for an opaque field containing doubles

This function is written in MMIX assembly. It should perform the calculation in 2υ
+ 5μ. If you inline it, the call is no longer needed so you can save the POP instruction. This function should be compatible with gcc for MMIX. (Read TAOCP vol 1. fasc 1 for more information):

compareDoubles IS @  ; Declare symbol, @ is the current position
   LDOU $0,$0,0      ; Load first double  (LDOU: load octa unsigned), 1v
   LDOU $1,$1,0      ; Load second double, 1
   FCMP $0,$0,$1     ; Compare floating point values, 4µ
   POP  1,0          ; return, 1µ

If you assemble it, the code is 16 bytes long and may looks this:

8f 00 00 00  8f 01 01 00  01 00 00 01  f8 01 00 00


MATL, 13 14 15 16 20 21 bytes

2*:"!tP2:Y)sv

Thanks @Zgarb for removing 1 byte!

Try it online!

2*         % implicitly input number N and multiply by 2
:          % create vector [1,2,...,2*N]
"          % for loop: do this 2*N times
  !        %   transpose. Implicitly input matrix in the first iteration
  tP       %   duplicate and flip vertically
  2:       %   vector [1,2]
  Y)       %   pick submatrix formed by the first two rows
  s        %   sum of each column
  v        %   append as a new row
           % end for
           % implicit display


Haskell, 404 characters

This Haskell program prints all FRACTRAN programs which halt when given the input 2. (The syntax of a FRACTRAN program is a list of positive rational numbers.)

import Data.Ratio
import Data.List
import Data.Either
r=do
 z<-[1..]
 let r=repeat z
 (p,q)<-zip r[1..z]++zip[1..z]r
 if gcd p q==1 then[p%q]else[]
o l=d[map(:xs)r|xs<-l]
e p n=n:maybe[](e p)(find((==1).denominator)$map(*n)p)
h p=map Left(e p 2)++[Right p]
main=mapM print$rights$d$map h$d$iterate o[[]]
d=concat.s
s[]=[]
s([]:b)=s b
s((x:a):b)=[x]:z a(s b)
z[]b=b
z a[]=map(:[])a
z(x:a)(y:b)=(x:y):z a b

I have made no great effort to compress this program. Furthermore, the GCD test in the definition of r is purely an optimization (it avoids duplicates).

(Also, If you are interested in running it, be sure to compile it, perhaps with optimization; I found that running it in ghci quickly consumed gigabytes of memory.)

It operates by successively constructing infinite lists of infinite lists and then flattening them in a diagonal order: the list of all positive rational numbers, the list of all lists of positive rational numbers (all programs), and the list of all evaluation states (including “halted”) of all programs. We then print only the halted states (which are annotated with the program which halted).

Here is the uncompressed and commented version:

import Data.Ratio
import Data.List
import Data.Either

-- List of all positive rational numbers
rationals = do
  limit <- [1..]
  let r = repeat limit
  (p,q) <- zip r [1..limit] ++ zip [1..limit] r
  if gcd p q == 1 then [p%q] else []
-- List of all lists of positive rational numbers (all FRACTRAN programs)
programs = diagonal $ iterate oneMore [[]]
oneMore l = diagonal [map (:xs) rationals | xs <- l]

-- FRACTRAN evaluator
evalStep p n = find ((== 1) . denominator) $ map (* n) p
evaluation p n = n : maybe [] (evaluation p) (evalStep p n)
evaluationWithHaltMarker p = map Left (evaluation p 2) ++ [Right p]

-- All evaluation states of all programs
evaluations = diagonal $ map evaluationWithHaltMarker programs

-- All halting programs
haltingPrograms = rights evaluations

main = mapM_ print haltingPrograms

-- from http://stackoverflow.com/questions/7141287/haskell-cartesian-product-of-infinite-lists
diagonal :: [[a]] -> [a]
diagonal = concat . stripe
    where
    stripe [] = []
    stripe ([]:xss) = stripe xss
    stripe ((x:xs):xss) = [x] : zipCons xs (stripe xss)

    zipCons [] ys = ys
    zipCons xs [] = map (:[]) xs
    zipCons (x:xs) (y:ys) = (x:y) : zipCons xs ys

The Left values are never actually looked at since we don't care about non-halting states; it's just the shortest way I saw to carry through the incremental evaluation.

Some “future work” if one were trying to write a practical implementation to generate interesting programs, rather than golfing, would be to reduce the needed work by restricting the set of programs under consideration to those which:

do not have a statically obvious loop (e.g. an integer).
are unique under “register renaming”; e.g. [3/2, 5/3] is the same as [7/2, 5/7].
have no dead code under the assumption that the input is 2; e.g. in [5/3, 7/2], 5/3 is dead code because no 3s are in numerators.
have no dead code due to preceding code; e.g. in [3/2, 5/2], 3/2 will always take precedence over 5/2.

I mention these cases in particular because (other than the looping one) they form the majority of the output. As far as I've run it, it has not produced any output program of length greater than 2.


CJam - 13

q~,>{mfW=}$0=

Try it at http://cjam.aditsu.net/

Example input: 2001 2014
Example output: 2002

Explanation:

q~ reads and evaluates the input, pushing the 2 numbers on the stack (say min and max)
, makes an array [0 1 ... max-1]
> slices the array starting at min, resulting in [min ... max-1]
{…}$ sorts the array using the block to calculate the sorting key
mf gets an array with all the prime factors of a number, in order
W= gets the last element of the array (W=-1), thus obtaining the largest prime factor to be used as a sorting key
0= gets the first element of the (sorted) array


6 chars

Following on the answers of primo and Peter Taylor, and a hint from man perlre:

/(?!)/

This perl-compatible regex matches an empty string which is not followed by another empty string.


Haskell, 255…247 242 bytes

-2 bytes thanks to xnor, for suggesting a better partitioning function q.
-8 bytes thanks to ovs, for suggesting [a!!i|i:_<-u] and removing an unnecessary map.

(a#b)c d=sum[1|g<-nub$(permutations(zipWith replicate b[0..]>>=id)>>=q)>>=mapM(q.sort),l g==l c,and[l x==h&&all(==x!!0)x&&sum[a!!i|i:_<-u]==w|(u,w,h)<-zip3 g c d,x<-u]]
q=foldr(\h t->map([h]:)t++[(h:y):z|y:z<-t])[[]]
l=length
import Data.List

Try it online!
A grid \$\mu\$ is represented as a pair \$(W_\mu,H_\mu)\$ where \$W_\mu\$, \$H_\mu\$ are lists containing, respectively, the widths and the heights of the blocks in \$\mu\$.
The relevant function is (#), which takes as input four lists: a\$=W_\mu\$, b\$=H_\mu\$, c\$=W_\lambda\$, d\$=H_\lambda\$. It returns the integer \$T(\mu,\lambda)\$.


MATLAB/Octave, 25 bytes
p=primes(2e6)
p(p(1:1e4))

It doesn't get much more straightforward than this.


Format the given number of bytes to a human readable format

TI-BASIC, 44

Would be the right tool for the job if TI-BASIC had halfway decent string manipulation (I had to resort to overwriting the exponent of the number, displayed in engineering notation, with the unit). As it is it rounds and outputs correctly, but it's not even close to winning entries. Maybe a different calculator language could win this one?

Fix 1
Eng
ClrHome
Disp Ans
Output(1,15,sub(" kMG",1+iPart(log(Ans+.5)/3),1)+"B

Input in the form [number]:[program name] on the homescreen.

Given test cases:

Input       Output (leading spaces intentional; screen clear before each output)
0                      0.0 B
999                  999.0 B
1000                   1.0kB
1023                   1.0kB
1024                   1.0kB
1601                   1.6kB
160581               160.6kB
4066888                4.1MB
634000000            634.0MB
2147483647             2.1GB


Ruby, 147 144 bytes

Saved 3 bytes thanks to m-chrzan!

z=STDIN.read
eval ARGV[i=a=0].gsub(/./){|e|"#{{?;=>"a+=1",?#=>"putc(a%127);a=0",?:=>"while a>0",?)=>"end",?*=>"a+=z[i%=z.size].ord;i+=1"}[e]};"}

Try it online!

Program is taken from first command line argument.


How high can you go? (A coding+algorithms challenge)

Nimrod (N=22)

import math, locks

const
  N = 20
  M = N + 1
  FSize = (1 shl N)
  FMax = FSize - 1
  SStep = 1 shl (N-1)
  numThreads = 16

type
  ZeroCounter = array[0..M-1, int]
  ComputeThread = TThread[int]

var
  leadingZeros: ZeroCounter
  lock: TLock
  innerProductTable: array[0..FMax, int8]

proc initInnerProductTable =
  for i in 0..FMax:
    innerProductTable[i] = int8(countBits32(int32(i)) - N div 2)

initInnerProductTable()

proc zeroInnerProduct(i: int): bool =
  innerProductTable[i] == 0

proc search2(lz: var ZeroCounter, s, f, i: int) =
  if zeroInnerProduct(s xor f) and i < M:
    lz[i] += 1 shl (M - i - 1)
    search2(lz, (s shr 1) + 0, f, i+1)
    search2(lz, (s shr 1) + SStep, f, i+1)

when defined(gcc):
  const
    unrollDepth = 1
else:
  const
    unrollDepth = 4

template search(lz: var ZeroCounter, s, f, i: int) =
  when i < unrollDepth:
    if zeroInnerProduct(s xor f) and i < M:
      lz[i] += 1 shl (M - i - 1)
      search(lz, (s shr 1) + 0, f, i+1)
      search(lz, (s shr 1) + SStep, f, i+1)
  else:
    search2(lz, s, f, i)

proc worker(base: int) {.thread.} =
  var lz: ZeroCounter
  for f in countup(base, FMax div 2, numThreads):
    for s in 0..FMax:
      search(lz, s, f, 0)
  acquire(lock)
  for i in 0..M-1:
    leadingZeros[i] += lz[i]*2
  release(lock)

proc main =
  var threads: array[numThreads, ComputeThread]
  for i in 0 .. numThreads-1:
    createThread(threads[i], worker, i)
  for i in 0 .. numThreads-1:
    joinThread(threads[i])

initLock(lock)
main()
echo(@leadingZeros)

Compile with

nimrod cc --threads:on -d:release count.nim

(Nimrod can be downloaded here.)

This runs in the allotted time for n=20 (and for n=18 when only using a single thread, taking about 2 minutes in the latter case).

The algorithm uses a recursive search, pruning the search tree whenever a non-zero inner product is encountered. We also cut the search space in half by observing that for any pair of vectors (F, -F) we only need to consider one because the other produces the exact same sets of inner products (by negating S also).

The implementation uses Nimrod's metaprogramming facilities to unroll/inline the first few levels of the recursive search. This saves a little time when using gcc 4.8 and 4.9 as the backend of Nimrod and a fair amount for clang.

The search space could be further pruned by observing that we only need to consider values of S that differ in an even number of the first N positions from our choice of F. However, the complexity or memory needs of that do not scale for large values of N, given that the loop body is completely skipped in those cases.

Tabulating where the inner product is zero appears to be faster than using any bit counting functionality in the loop. Apparently accessing the table has pretty good locality.

It looks as though the problem should be amenable to dynamic programming, considering how the recursive search works, but there is no apparent way to do that with a reasonable amount of memory.

Example outputs:

N=16:

@[55276229099520, 10855179878400, 2137070108672, 420578918400, 83074121728, 16540581888, 3394347008, 739659776, 183838720, 57447424, 23398912, 10749184, 5223040, 2584896, 1291424, 645200, 322600]

N=18:

@[3341140958904320, 619683355033600, 115151552380928, 21392898654208, 3982886961152, 744128512000, 141108051968, 27588886528, 5800263680, 1408761856, 438001664, 174358528, 78848000, 38050816, 18762752, 9346816, 4666496, 2333248, 1166624]

N=20:

@[203141370301382656, 35792910586740736, 6316057966936064, 1114358247587840, 196906665902080, 34848574013440, 6211866460160, 1125329141760, 213330821120, 44175523840, 11014471680, 3520839680, 1431592960, 655872000, 317675520, 156820480, 78077440, 39005440, 19501440, 9750080, 4875040]

For purposes of comparing the algorithm with other implementations, N=16 takes about 7.9 seconds on my machine when using a single thread and 2.3 seconds when using four cores.

N=22 takes about 15 minutes on a 64-core machine with gcc 4.4.6 as Nimrod's backend and overflows 64-bit integers in leadingZeros[0] (possibly not unsigned ones, haven't looked at it).

Update: I've found room for a couple more improvements. First, for a given value of F, we can enumerate the first 16 entries of the corresponding S vectors precisely, because they must differ in exactly N/2 places. So we precompute a list of bit vectors of size N that have N/2 bits set and use these to derive the initial part of S from F.

Second, we can improve upon the recursive search by observing that we always know the value of F[N] (as the MSB is zero in the bit representation). This allows us to predict precisely which branch we recurse into from the inner product. While that would actually allow us to turn the entire search into a recursive loop, that actually happens to screw up branch prediction quite a bit, so we keep the top levels in its original form. We still save some time, primarily by reducing the amount of branching we are doing.

For some cleanup, the code is now using unsigned integers and fix them at 64-bit (just in case someone wants to run this on a 32-bit architecture).

Overall speedup is between a factor of x3 and x4. N = 22 still needs more than eight cores to run in under 10 minutes, but on a 64-core machine it's now down to about four minutes (with numThreads bumped up accordingly). I don't think there's much more room for improvement without a different algorithm, though.

N=22:

@[12410090985684467712, 2087229562810269696, 351473149499408384, 59178309967151104, 9975110458933248, 1682628717576192, 284866824372224, 48558946385920, 8416739196928, 1518499004416, 301448822784, 71620493312, 22100246528, 8676573184, 3897278464, 1860960256, 911646720, 451520512, 224785920, 112198656, 56062720, 28031360, 14015680]

Updated again, making use of further possible reductions in search space. Runs in about 9:49 minutes for N=22 on my quadcore machine.

Final update (I think). Better equivalence classes for choices of F, cutting runtime for N=22 down to 3:19 minutes 57 seconds (edit: I had accidentally run that with only one thread) on my machine.

This change makes use of the fact that a pair of vectors produces the same leading zeros if one can be transformed into the other by rotating it. Unfortunately, a fairly critical low-level optimization requires that the top bit of F in the bit representation is always the same, and while using this equivalence slashed the search space quite a bit and reduced runtime by about one quarter over using a different state space reduction on F, the overhead from eliminating the low-level optimization more than offset it. However, it turns out that this problem can be eliminated by also considering the fact that F that are inverses of one another are also equivalent. While this added to the complexity of the calculation of the equivalence classes a bit, it also allowed me to retain the aforementioned low-level optimization, leading to a speedup of about x3.

One more update to support 128-bit integers for the accumulated data. To compile with 128 bit integers, you'll need longint.nim from here and to compile with -d:use128bit. N=24 still takes more than 10 minutes, but I've included the result below for those interested.

N=24:

@[761152247121980686336, 122682715414070296576, 19793870419291799552, 3193295704340561920, 515628872377565184, 83289931274780672, 13484616786640896, 2191103969198080, 359662314586112, 60521536552960, 10893677035520, 2293940617216, 631498735616, 230983794688, 102068682752, 48748969984, 23993655296, 11932487680, 5955725312, 2975736832, 1487591936, 743737600, 371864192, 185931328, 92965664]

import math, locks, unsigned

when defined(use128bit):
  import longint
else:
  type int128 = uint64 # Fallback on unsupported architectures
  template toInt128(x: expr): expr = uint64(x)

const
  N = 22
  M = N + 1
  FSize = (1 shl N)
  FMax = FSize - 1
  SStep = 1 shl (N-1)
  numThreads = 16

type
  ZeroCounter = array[0..M-1, uint64]
  ZeroCounterLong = array[0..M-1, int128]
  ComputeThread = TThread[int]
  Pair = tuple[value, weight: int32]

var
  leadingZeros: ZeroCounterLong
  lock: TLock
  innerProductTable: array[0..FMax, int8]
  zeroInnerProductList = newSeq[int32]()
  equiv: array[0..FMax, int32]
  fTable = newSeq[Pair]()

proc initInnerProductTables =
  for i in 0..FMax:
    innerProductTable[i] = int8(countBits32(int32(i)) - N div 2)
    if innerProductTable[i] == 0:
      if (i and 1) == 0:
        add(zeroInnerProductList, int32(i))

initInnerProductTables()

proc ror1(x: int): int {.inline.} =
  ((x shr 1) or (x shl (N-1))) and FMax

proc initEquivClasses =
  add(fTable, (0'i32, 1'i32))
  for i in 1..FMax:
    var r = i
    var found = false
    block loop:
      for j in 0..N-1:
        for m in [0, FMax]:
          if equiv[r xor m] != 0:
            fTable[equiv[r xor m]-1].weight += 1
            found = true
            break loop
        r = ror1(r)
    if not found:
      equiv[i] = int32(len(fTable)+1)
      add(fTable, (int32(i), 1'i32))

initEquivClasses()

when defined(gcc):
  const unrollDepth = 4
else:
  const unrollDepth = 4

proc search2(lz: var ZeroCounter, s0, f, w: int) =
  var s = s0
  for i in unrollDepth..M-1:
    lz[i] = lz[i] + uint64(w)
    s = s shr 1
    case innerProductTable[s xor f]
    of 0:
      # s = s + 0
    of -1:
      s = s + SStep
    else:
      return

template search(lz: var ZeroCounter, s, f, w, i: int) =
  when i < unrollDepth:
    lz[i] = lz[i] + uint64(w)
    if i < M-1:
      let s2 = s shr 1
      case innerProductTable[s2 xor f]
      of 0:
        search(lz, s2 + 0, f, w, i+1)
      of -1:
        search(lz, s2 + SStep, f, w, i+1)
      else:
        discard
  else:
    search2(lz, s, f, w)

proc worker(base: int) {.thread.} =
  var lz: ZeroCounter
  for fi in countup(base, len(fTable)-1, numThreads):
    let (fp, w) = fTable[fi]
    let f = if (fp and (FSize div 2)) == 0: fp else: fp xor FMax
    for sp in zeroInnerProductList:
      let s = f xor sp
      search(lz, s, f, w, 0)
  acquire(lock)
  for i in 0..M-1:
    let t = lz[i].toInt128 shl (M-i).toInt128
    leadingZeros[i] = leadingZeros[i] + t
  release(lock)

proc main =
  var threads: array[numThreads, ComputeThread]
  for i in 0 .. numThreads-1:
    createThread(threads[i], worker, i)
  for i in 0 .. numThreads-1:
    joinThread(threads[i])

initLock(lock)
main()
echo(@leadingZeros)


Use the future module

The future module contains two main byte-saving features: lambdas and list comprehensions. Lambdas are extremely useful.

For example, this:

proc f(s:any):any=s&", world!"

can be shortened to this:

import future
s=>s&", world!"

which saves a byte. Note, however, that lambdas can't be used outside of a parameter list -- so to test your code, you'll have to do something like this:

import future
proc test(f: string -> string) = echo f "Hello"
test(s=>s&", world!")

As well, list comprehensions can be used with the future module. For example, this code prints a seq (@[...]) of all squares less than 100 divisible by 4:

import future
echo lc[x*x|(x<-1..9,x*x mod 4==0),int]


APL, 279 208 206 203

s←1 ¯1
f←{x←⊣/¨z←⍺⍵[⍋⊣/¨⍺⍵]
2 2≡x:∧/0∧.=⌊(2⊃-⌿↑z)⌹⍣(≠.×∘⌽/x)⍉↑x←s×-/2⊢/↑z
2≡2⌷x:∨/((2⊃z)∇2,x[1]×(2⌷⊃z)+,∘-⍨⊂y÷.5*⍨+.×⍨y←⌽s×⊃-/y),x[1]=(×⍨3⊃⊃z)>+.×⍨¨y←(s↓⌽↑z)-2⌷⊃z
~x∨.∧x[1]≠(.5*⍨+.×⍨2⊃-⌿↑z)<-/⊢/¨z×s*1⌷x}

Line breaks in the function f are for clarity. They should be replaced with the statement separator ⋄

It has been so long since I last made such a complex APL program. I think the last time was this but I am not even sure that was as complex.

Input format
Basically same as the OP, except using 0 for cavity, 1 for disc and 2 for line segment.

Major update

I managed to golf a lot of chars using a different algorithm. No more g bulls**t!!

The main function f is divided into cases:

2 2≡x: Segment-segment

In this case, calculate the vector from the end points of each line and solve a system of linear equations to check if the intersection is contained within the vectors.

Caveats:

The end point of a vector is not considered as a part of the vector (while its origin is). However, if only the tip of a vector is on the other one, the input is invalid according to spec.
Non-degenerate parallel segments always returns false, regardless of collinearity.
If one of the segments is degenerate, always return false. If both segments are degenerate, always return true.

Examples: (Note caveat 1 in action in the figure on the right)

2≡2⌷x: Segment-other

In this case, the other object is a circular one. Check if the end points of the segment is within the circle using distance check.

In the disc case, also construct a line segment of the diameter perpendicular to the given segment. Check if the segments collide by recursion.
In the cavity case, sneak in a "times 0" in the construction of the said segment to make it degenerate. (See why I use 0 for cavity and 1 for disc now?) As the given segment is not degenerate, the segment-segment collision detection always return false.

Finally combine the results of the distance checks and the collision detection. For the cavity case, negate the results of the distance checks first. Then (in both cases) OR the 3 results together.

Regarding the segment-segment caveats, numbers 3 is addressed (and exploited). Number 2 is not a problems as we are intersecting perpendicular segments here, which are never parallel if they are not degenerate. Number 1 takes effect only in the disc case, when one of the given end points is on the constructed diameter. If the end point is well inside the circle, the distance checks would have taken care of it. If the end point is on the circle, since the constructed diameter is parallel to the given segment, the latter must be tangent to the circle with only one point touching the disc, which is not valid input.

Examples:

Default case: Other-other

Calculate the distance between the centers. Disc-disc collision occurs if and only if the distance is smaller than the sum of radii. Disc-cavity collision occurs if and only if the distance is greater than the difference in radii.

To take care of the cavity-cavity case, negate the result of the distance check, AND with each of the identifying integers and then OR them together. Using some logic, one can show that this process returns true if and only if both identifying integers are falsy (Cavity-cavity case), or if the distance check returned true


How can I shorten this python code analyzing a 3d grid?

Python 3, 108 107 bytes
Since the cube only contains the strings "X" and "Z", there are only two valid cube patterns. The one that starts with XZXZX... and the one that starts with ZXZXZ....
My solutions generates these 2 cubes and checks if the inputted cube is one of them.
def golf(l):L=len(l);r=range(L);return l in[[[list("XZ"*L)[(i+j+k)%2:][:L]for j in r]for k in r]for i in r]
i iterates over the possible cubes. Since the dimension is at least 2, we can reuse r instead of writing for i in(0,1).


Maximum Area of a Polygon with Vertices of a Polygon

Python 2, 172 bytes

-1 byte thanks to J843136028

bug fix thanks to Jonathan Frech

from itertools import*
def f(l,n,L=()):
 for p in combinations(l,n):
  r=0;j=-1
  for i in range(n):r+=(p[j][0]+p[i][0])*(p[j][1]-p[i][1]);j=i
  L+=abs(r/2.),
 print max(L)

Try it online!


Jelly, 11 bytes

WẋLŒDUṙLFsL

Try it online!

Explanation

               Input: array z
WẋL            length(z) copies of z
   ŒD          Diagonals (starting with main diagonal)
     U         Reverse each
      ṙL       Rotate left length(z) places
               (now the top-left diagonal is in front)
        F      Flatten
         sL    Split into chunks of size length(z)


Pyth, 59 51 bytes

*Ksm/.s.s.sd\ \#\ \ fq4l:T"#+"4.z13+-/s.sR\ .zdK*2K

Try it here!

Outputs the time to juic the advacado (totally correct english) first and on the next line the amount of juic.

Explanation

Code - Overview

*Ksm/.s.s.sd\ \#\ \ fq4l:T"#+"4.z13+-/s.sR\ .zdK*2K # .z=list of all input lines

                    fq4l:T"#+"4.z                   # Get the pit-lines
   m/.s.s.sd\ \#\ \                                 # Map the pit-lines to the whitespace amount
 Ks                                                 # Sum the amount of pit-spaces and assign to K
*                                13                 # Print the juic time
                                     /s.sR\ .zd     # Count all whitespaces in the advacado
                                    -          K    # Subtract the pit size from it
                                   +            *2K # Do the Rest of the amount calcluation and print it

Detailed explanations of the size calculation parts see below.

Getting the advacado size

Let's look at this one:

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

First the leading and trailing whitespaces get removed. After that we wrap everything in one line, which results in this string:

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

This contains all whitespaces in the advacado, so we just have to count them (the advacado will always be convex, so this works for all valid inputs). This number still contains the spaces in the pit, but for the juic amount calculation we only need the spaces in the fruit without the pit-spaces. So we need to calculate them too.

The code for that explained in detail:

/s.sR\ .zd   # .z=list of all input lines

  .sR\ .z    # strip spaces from every input line
 s           # Concatenate all lines
/        d   # Count all spaces

Getting the pit size

This is a bit trickier. First we remove the lines which don't contribute to the pit size. This is done by filtering out all lines that have less than 4 groups of hashes (using the regex #+ and counting its matches). In the example above only one line will survive this process:

  #  #--# #

The spaces I marked with a - here are the ones we need to count. So we just strip spaces, then hashes and then spaces again which leaves us with this:

#  #

There we just have to count the spaces. We do all that for every line which survived the filtering process, sum everything and we are done. The rest is trivial math.

The code for that explained in detail:

sm/.s.s.sd\ \#\ \ fq4l:T"#+"4.z   # .z=list of all input lines

                  f          .z   # filter the input
                     l:T"#+"4     # length of the matches for the regex `#+`
                   q4             # if there are 4 groups of hashes its a pit line
 m                                # map the pit lines to...
  /             \                 # The occurences of spaces in..
   .s.s.sd\ \#\                   # ...the stripped pit line (see explanation above)
s                                 # Sum all amounts of spaces in the pits


JavaScript (ES8), 33 bytes

Expects the input in the range of safe JS integers: \$-2^{53}\le n < 2^{53}\$.

Returns a string of 76 characters.

n=>btoa(n.toString(2)).padEnd(76)

Try it online!

How?

Step 1

The input is first converted to binary. This preserves the leading minus sign for negative numbers.

Examples:

123 → "1111011"
-77 → "-1001101"

Step 2

The resulting string is encoded in base-64.

It means that each block of 1 to 3 characters will be turned into a new block of 4 characters. This conversion is safe because none of the resulting blocks contain the forbidden symbols (digits or minus sign).

3-character blocks

"-10" -> "LTEw" | "011" -> "MDEx"
"-11" -> "LTEx" | "100" -> "MTAw"
"000" -> "MDAw" | "101" -> "MTAx"
"001" -> "MDAx" | "110" -> "MTEw"
"010" -> "MDEw" | "111" -> "MTEx"

A single final block of 1 or 2 characters has to be encoded if the length of the binary string is not a multiple of 3:

1-character blocks

"0"   -> "MA==" | "1"   -> "MQ=="

2-character blocks

"-1"  -> "LTE=" | "10"  -> "MTA="
"00"  -> "MDA=" | "11"  -> "MTE="
"01"  -> "MDE=" |

Step 3

The final output is padded with trailing spaces.


PDP-11 Assembler (UNIX Sixth Edition), 1 byte
9

Instruction 9 is not a valid instruction on the PDP-11 (in octal, it would be 000011, which does not appear on the list of instructions (PDF)). The PDP-11 assembler that ships with UNIX Sixth Edition apparently echoes everything it doesn't understand into the file directly; in this case, 9 is a number, so it generates a literal instruction 9. It also has the odd property (unusual in assembly languages nowadays) that files start running from the start, so we don't need any declarations to make the program work.
You can test out the program using this emulator, although you'll have to fight with it somewhat to input the program.
Here's how things end up once you've figured out how to use the filesystem, the editor, the terminal, and similar things that you thought you already knew how to use:
% a.out
Illegal instruction -- Core dumped

I've confirmed with the documentation that this is a genuine SIGILL signal (and it even had the same signal number, 4, all the way back then!)


APL (106 114)

'Computer' 'User'[1+X],'wins with','points',⍨|Z-21×X←11>Z←+/>/⎕←⍉↑{⍵[{?6}¨⍳21]}¨(↓5 6⍴545170074510753⊤⍨18⍴7)[⎕+⍳2]

Explanation:

(↓5 6⍴545170074510753⊤⍨18⍴7)[⎕+⍳2]: The big number is a base-7 representation of the dice. We make a 6x5 matrix containing the values of the dice in the order: 2 3 1 2 3. Ask for user input and add this to the vector 1 2, and select these lines from the matrix. Because the list of dice is shifted, the user now gets the one he selected (on the right) and the computer gets the stronger one.
{⍵[{?6}¨⍳21]}¨: do 21 rolls for each of these two dice.
⎕←⍉↑: put the rolls in matrix form and output them.
Z←+/>/: get the score of the computer (amount of times the computer's value was higher than the user's)
X←11>Z: set X to whether the user won (if 11 is higher than the computer's score).
'Computer' 'User'[1+X]. X is whether the user won.
'wins with','points',⍨|Z-21×X: Z is the computer's score, so if the computer won display Z, otherwise display 21-Z.


Jelly,  10  8 bytes

-2 thanks to Erik the Outgolfer

,⁷y⁵iⱮ⁶o

A full program accepting four command line arguments, incomparables nomatch table x which prints a Jelly representation* of the list of R's match function results.

Try it online!

How?

e.g. with incomparables nomatch table x = [1,4], 2, [2,4], [4,3,2,1,0]:

,⁷y⁵iⱮ⁶o - Main Link: list, incomparables; list, nomatch
 ⁷       - newline character                                '\n'
,        - pair (incompararables) with (right)              [[1,4],'\n']
   ⁵     - 5th argument (3rd input = table)                 [2,4]
  y      - translate (right) with lookup (left)             [2,'\n']
      ⁶  - 6th argument (4th input = x)                     [4,3,2,1,0]
     Ɱ   - map with:
    i    -   first index of (right) in (left)               [0,0,1,0,0]
       o - logical OR                                       [2,2,1,2,2]

* An empty list is represented as nothing, a list of lenth one is represented as just the item, while other lists are enclosed in [] and delimited by ,


Thinking outside the box - Am I doing it right?

Javascript (ES6), 274 263 bytes

f=(a,b=(b,c="")=>a=a.replace(b,c),c=b=>b.test(`,${a},`))=>(b(/\w+/,5),b(/\+/g,1),b(/\-/g,2),b(/\|/g,3),b(/\n/g,4),c(/[13][2 ]{0,7}[13]|[12] *4 *[12]/)||(b(/ /g),b(/43+(?=4)/g),!c(/353|24542|12+435|21453|35412|5342+1/)&&(!c(/^([^1]*|([^15]*1){1,2}[^15]*)$/)||-1)))

The function f returns true, false, or -1 as its "maybe" value. It should be called with one argument: the input. The other two parameters only exist to shorten the code.

Here's a less golfed version with comments:

var f = (input) => {
    var replace = (re, s) => input = input.replace(re, s);
    var test = re => re.test(input);

    /*
        Replace some "special" characters with ones that are shorter to put in a regex.
        "+" --> "1"
        "-" --> "2"
        "|" --> "3"
        "\n" --> ","
    */
    replace(/\+/g,1);
    replace(/\-/g,2);
    replace(/\|/g,3);
    replace(/\n/g,',');

    /*
        Shorten the word, if there is one, to just a single character "a".
    */
    replace(/[a-z]+/g,'a');

    /*
        Append a newline to the beginning and end of the input.
    */
    input = ','+input+',';

    /*
        Test the size of the box. These are the cases covered:
        /[13][2 ]{0,7}[13]/ : A horizontal edge or middle section has an inner width of fewer than 8 characters.
        /[12] *, *[12]/     : There are two horizontal edges in a row, with no space between.

        If either of these match, the word must be outside of the box. Return the truthy value (true).
    */
    if (test(/[13][2 ]{0,7}[13]|[12] *, *[12]/)) return true;

    /*
        Remove any spacing from the input. It it unnecessary from this point onwards.
    */
    replace(/ /g,'');

    /*
        Remove any lines with only vertical bars. These are also unnecessary.
    */
    replace(/,3+(?=,)/g,'');

    /*
        Edge / corner cases (heh). These are the cases covered:
        /3a3/    : two vertical bars with the word between.
        /2,a,2/  : two horizontal bars with the word between.
        /12+,3a/ : word inside the top left corner.
        /21,a3/  : word inside the top right corner.
        /3a,12/  : word inside the bottom left corner.
        /a3,2+1/ : word inside the bottom right corner.

        If any of these match, the word is inside the box. Return the falsy value (false).
    */
    if (test(/3a3|2,a,2|12+,3a|21,a3|3a,12|a3,2+1/)) return false;

    /*
        "Maybe" cases. These are the cases covered:
        /^[^1]*$/                : Input contains no corners, and may or may not contain a word.
        /^([^1a]*1){1,2}[^1a]*$/ : Input contains 1 or 2 corners, and no word.

        If either of these match, assuming the previous test cases have not been hit,
        we cannot tell if the word is inside or outside the box. Return the maybe value (-1).
    */
    if (test(/^([^1]*|([^1a]*1){1,2}[^1a]*)$/)) return -1;

    /*
        If none of the previous cases matched, the word must be outside of the box. Return the truthy value (true).
    */
    return true;
};

Had a lot of fun with this one. Thanks!

Edit: Saved 6 bytes thanks @L. Serné by modifying b to use a default argument, saving 3 bytes, and changing [a-z] to \w, saving 3 more bytes. Also saved 5 more bytes by making the word replacement non-global, saving 1 byte, and changing "a" to 5 and "," to 4, saving 4 bytes.


Surround a string with "friendliness pellets"

Charcoal, 40 bytes
≔⌈⟦¹⁻Ｌθ⁸⟧η×η0↘↘0→↘00↓00‖ＯＯ←η‖Ｏ↓Ｊ⊘⁻⊖ηＬθ⁵θ

Try it online! Link is to verbose version of code. Explanation:
≔⌈⟦¹⁻Ｌθ⁸⟧η

Calculate the number of 0s in the top row.
×η0

Print them.
↘↘0→↘00↓00

Print the remaining 0s on the right.
‖ＯＯ←η

Reflect the additional rows of 0s to the left, by overlapping the top row of 0s onto itself.
‖Ｏ↓

Reflect the 0s downwards overlapping the middle row.
Ｊ⊘⁻⊖ηＬθ⁵θ

Calculate the position of the text and print it there. This is necessary for short strings but also avoids dealing with a Charcoal bug whereby an overlapped reflection moves the cursor to the wrong place.


CJam, 49 42 bytes

Lri{)mp0S?}%{1$,)/(a@Wf%z+\L*}h;eeSff*W%N*

Input as a single integer in STDIN. Output as an ASCII grid with 0 for primes. The rotation of the spiral is not consistent: the largest number of the spiral will always be on the bottom row.

Test it here.

Explanation

The basic idea is to represent the triangle as a ragged 2D array while doing the computation. You get this array by reversing the lines and aligning all rows to the left:

   4
  5 3
 6 1 2
7 8 9 A

Would be represented as

[[7 8 9 A]
 [6 1 2]
 [5 3]
 [4]]

Since we've mirrored the line, we want to roll up the spiral in a clockwise manner. That's convenient, because all we need to do is rotate the triangle counter-clockwise and prepend the next sublist in order. We can rotate the ragged array by reversing all lines and transposing it:

                                                           [[B C D E F]
[[7 8 9 A]         [[A 9 8 7]           [[A 2 3 4]          [A 2 3 4]
 [6 1 2]   reverse  [2 1 6]   transpose  [9 1 5]   prepend  [9 1 5]
 [5 3]      ---->   [3 5]      ------>   [8 6]      ---->   [8 6]
 [4]]               [4]]                 [7]]               [7]]

So here is the code. One detail I'd like to draw attention to is the last bit that creates the triangular layout. I think that's rather nifty. :)

L     e# Push an empty array. This will become the spiral.
ri    e# Read input and convert to integer N.
{     e# Map this block over 0 to N-1...
  )   e#   Increment to get 1 to N.
  mp  e#   Test for primality.
  0S? e#   Select 0 or a space correspondingly.
}%
{     e# While the list we just created is not empty yet...
  1$  e#   Copy the spiral so far.
  ,)  e#   Get the number of lines and increment.
  /   e#   Split the list into chunks of that size.
  (a@ e#   Pull off the first chunk, wrap it in an array, pull up the spiral.
  Wf% e#   Reverse the lines of the spiral.
  z   e#   Transpose the spiral.
  +   e#   Prepend the new line.
  \L* e#   Swap with the remaining chunks and join them back together into a single list.
}h
;     e# Discard the empty list that's left on the stack.
ee    e# Enumerate the spiral. This turns each line into a pair of 0-based index
      e# and the line itself.
Sff*  e# Multiply each element of each pair with a space. For the enumeration index i,
      e# this produces a string of i spaces - the required indentation (keeping in
      e# mind that our spiral is still upside down). For the line itself, this
      e# riffles the cells with spaces, creating the required gaps between the cells.
      e# All of this works because we always end the spiral on the bottom edge.
      e# This ensures that the left edge is always complete, so we don't need
      e# different indentation such as in the N=12 example in the challenge.
W%    e# Reverse the lines to make the spiral point upwards.
N*    e# Join the lines with linefeeds.


C - 2,361,024 2,509,949 clues

Remove clues starting from the last cell if a brute force solver finds only one unique solution.

Second try: use heuristic to decide in which order to remove clues instead of starting from the last. This makes the code run much slower (20 minutes instead of 2 to calculate the result). I could make the solver faster, to experiment with different heuristics, but for now it will do.

#include <stdio.h>
#include <string.h>
char ll[100];
short b[81];
char m[81];
char idx[81][24];
int s;
char lg[513];
void pri2() {
    int i;
    for(i=0;i<81;i++) putchar(lg[b[i]]);
    putchar('\n');
}
void solve(pos){
int i,p;
if (s > 1) return;
if (pos == 81) { s++; return; }
if (b[pos]) return solve(pos+1);
for (p=i=0;i<24;i++) p |= b[idx[pos][i]];
for (i = 0; i < 9; i++) if (!(p&(1<<i))) {
    b[pos] = 1 << i;
    solve(pos + 1);
}
b[pos] = 0;
}
int main() {
    int i,j,t;
    for(i=0;i<9;i++) lg[1<<i]='1'+i;
    lg[0] = '.';
    for(i=0;i<81;i++) {
    t = 0;
    for(j=0;j<9;j++) if(i/9*9 + j != i) idx[i][t++] = i/9*9 + j;
    for(j=0;j<9;j++) if(i%9 + j*9 != i) idx[i][t++] = i%9 + j*9;
    for(j=0;j<81;j++) if(j/27 == i/27 && i%9/3 == j%9/3 && i!=j) idx[i][t++] = j;
    }
    while(scanf("%s ",ll)>0) {
    memset(m, 0, sizeof(m));
    for(i=0;i<81;i++) b[i] = 1 << (ll[i]-'1');
    for(i=0;i<81;i++) {
    int j,k,l = 99;
    for(k=0;k<81;k++) if (m[k] <= l) l = m[k], j = k;
    m[j] = 24;
    t = b[j]; b[j] = 0;
    s = 0; solve(0);
    if (s > 1) b[j] = t;
    else for(k=0;k<24;k++) m[idx[j][k]]++;
    }
    pri2();
    }
    return 0;
}


Brainfuck

I always had in mind to do this, so here we go:

>>>,
[
[->+>+<<]             copy input

<<<+++++++++++++      fill cell with 13 for subtraction
[->+>+>+<<<]          and duplicate some times

>>>[->---<]           sub 39
>----                 43

[                     plus
-
[                     comma
-
[                     minus
-
[                     dot

<<[->>-<<]>>-         60

[                     less than
--
[                     greater than

<<<[->>>--<<<]>>>     86
---                   91

[                     open square bracket
--
[                     closing square bracket

>[-]                  remove copy

]]]]]]]]

>[.[-]>]              the copy has not been removed; print

<<[-]<<<[-]>[-]>      clean up

,]

Compresses itself to (144 characters):

>>>,[[->+>+<<]<<<+++++++++++++[->+>+>+<<<]>>>[->---<]>----[-[-[-[<<[->>-
<<]>>-[--[<<<[->>>--<<<]>>>---[--[>[-]]]]]]]]]>[.[-]>]<<[-]<<<[-]>[-]>,]

The size of the compressing could probably still reduced a bit. The compression alogorithm itself is near perfect, it's hard to do any more than removing non-+-[]<>,..


Write a java code to detect the JVM version

I'm not sure what my score is, because it depends on what precisely you consider to be a lexical token, but I'm trying to abuse that counting system as much as possible with a long string...

It also depends on whether you count this as identifying 7 different versions or 16... (It could trivially be extended up to 190).

class V extends ClassLoader
{
    public static void main(String[]args)
    {
        for(byte b=60;;)
            try {
                byte[]buf="\u00ca\u00fe\u00ba\u00be\u0000\u0000\u00002\u0000\u0005\u0007\u0000\u0003\u0007\u0000\u0004\u0001\u0000\u0001A\u0001\u0000\u0010java/lang/Object\u0006\u0000\u0000\u0001\u0000\u0002\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000".getBytes("ISO-8859-1");
                buf[7]=b--;
                new V().defineClass(buf,0,53);
                System.out.println(b-43);
                break;
            }
            catch(Throwable t){}
    }
}

It works by attempting to define an interface in a custom classloader with descending major version numbers of the class format. The first one which doesn't throw a java.lang.UnsupportedClassVersionError corresponds to the VM's version.


Find largest prime which is still a prime after digit deletion


Windows PowerShell, 65
Fairly straightforward.
filter f{for($d=date $_;($d+='1').day*$d.month-58){}$d.dayofweek}

As usual, we can shave off two bytes if we are willing to wait a long time till completion:
filter f{for($d=date $_;($d+=9).day*$d.month-58){}$d.dayofweek}

Test:
> '0001-01-01','1899-12-03','1970-01-01','1999-07-06','2003-05-22','2011-02-17','2100-01-01'|f
Sunday
Monday
Tuesday
Tuesday
Sunday
Wednesday
Friday

History:

2011-02-18 00:06 (65) First attempt.


Finding n'th character in a Lucky String

JavaScript - 49

for(s=i=0;!(r=s[n+i++]);s+=i.toString(2));"FE"[r]

Execute this on a JavaScript console (tested on Node), with n set to the 1-based index of the digit you want.

Explanation:

The script builds a version of the lucky string, and stops when the character we're looking for exists.

Lucky string:        4 5 44 45 54 55
Generated string: 011011100101110111

The lucky string is equivalent to the concatenation of all binary numbers with the leading one stripped. We can get the index of the appropriate character in s from n by adding the number of leading ones in the string to skip, or, equivalently, how many binary numbers we generated. Luckily for us, we can just grab the current value of i.

It greatly helps to see the final values of s and i after running. For sake of brevity, I won't post a table here, but you can certainly check their values in the console.

Details:

s=i=0

Initializes s and i. s later becomes a string, but rather than initialize to "0", 0 works fine because of implicit type conversion.

i++

Increments i every iteration.

r=s[n+i++]

Gets the character of s at n+i (0 or 1) and stores it in r.

!(r=s[n+i++])

Loops while the character we are looking for is still undefined.

s+=i.toString(2)

Appends the next binary number in sequence to s.

"FE"[r]

Causes the expression to evaluate to F if r is 0, E if r is 1.


Unscramble those case-(very)-sensitive strings

Retina, 53 bytes

Not really clever, but a clean and quite readable solution

([a-z])(.*?)([a-z])
$3$2$1
([A-Z])(.*?)([A-Z])
$3$2$1

Try it online!


Haskell, 21 bytes

all$scanr1 max>>=(==)

Try it online!

Takes a list of columns, with empty spaces as 0.