Self-Validating Triangular Checkerboard Program

C (gcc), 189 bytes

j
;l
;b;
d;f␉
(char
␉*␉t)
{b=*␉t%
2;for␉(␉
j=d=0;j=j
+ 1,␉l=j+
1,␉*␉t; ) {
for␉(;l=l- 1
 ;t=t+ 1 )b=
!b␉,␉d=d+ !(␉*
␉t␉*␉(␉*␉t- 10)
*␉(␉*␉t%2-b) ) ;
d␉|=*␉t- 10;t=t+
1 ; }b= !d; } ␉ ␉

Try it online!

␉ represents a tab character (I'm sorry). Note that there are several trailing spaces/tabs (I'm more sorry). The original with tabs intact is best viewed in vim with :set tabstop=1 (words cannot express how sorry I am).

It's a function (called f, which isn't immediately obvious from glancing at it) that takes a string as an argument and returns either 0 or 1.

I could reduce this by at least one and probably two or more lines, but note that it gets increasingly messy and low-effort towards the end, mostly because writing such awful code (even by PPCG  standards) was making me feel like a bad person and I wanted to stop as soon as possible.

The basic idea here is to avoid constructions that necessarily break the format (++, +=, return, etc.). Miraculously, important keywords like for, char, and while (which I didn't end up using) happen to fit the alternating parity rule. Then I used spaces (even parity) and tabs (odd parity) as padding to make the rest fit the rules.


Ruby 49 41

a,b=$*;puts (a*2).sub(b,'')==a ?:yes: :no

Edit: replaced gets.split by $*


Parallel projected voxel terrain generator

Python2 3D Function Plotter Voxel Edition

This is my entry in this competition:

import math
import random
import Image

terrain=""
randA=(random.random()*4+5)
randB=(random.random()*4+10)
randC=(random.random()*4+1)
randD=(random.random()*4+1)
im = Image.new("RGBA", (1248, 1000), "black")
tile=[Image.open("voxel/1.png"),Image.open("voxel/2.png"),Image.open("voxel/3.png"),Image.open("voxel/4.png"),Image.open("voxel/5.png"),Image.open("voxel/6.png"),Image.open("voxel/7.png"),Image.open("voxel/8.png"),Image.open("voxel/9.png")]

for y in range (-40,40):
        for x in range (-10, 10):
                val=int(1+abs(4+2.5*(math.sin(1/randA*x+randC)+math.sin(1/randB*y+randD))))
                if (val<9):
                        terrain+=str(val)
                else:
                        terrain+="9"
print terrain

for i in range (0,80*20):
        if((i/20)%2==0):
                shift=0
        else:
                shift=-32
        im.paste(tile[int(terrain[i])-1],((i%20)*64+shift,((i/20)*16-(32*(int(terrain[i])-1)))-32),tile[int(terrain[i])-1])

im.show()

As clearly stated in the title it works as a 3D function plotter, but since this competition requires the terrain to be randomly generated it this random sine function 1.5*(math.sin(1/randA*x+randC)+math.sin(1/randB*y+randD)) That depends on 4 random variables. This creates terrains like this:

We can ofcourse replace this random function by any 2 variable function, for example sin(sqrt((x/2)²+(y/2)²))*3 gives this terrain:

and -x*y*e^(-x^2-y^2) gives this:

(the plots on the right are computed by wolfram alpha)

And while we're at it, Riemann zeta along the critical strip:

For the people who aren't familiar with it, as you can see these pools of water (wich represent the zero's of the function) all lie on a straight line (real part = 0.5). If you can prove this, you will get $1000000! See this link.

I hope you like it!


Find the nth Fibonnaci Prime, in the shortest code


Pyth - 65 bytes
@c." y=CÅQ¯@îR
°©ÀáëªfÞ#[õNqÀN8Ô'¼ô,n7Ë¶~fB").d3

Try it online here.
@                     Modular indexing
 c           )        Split string, use default of spaces
  ."ajs&^asd"         Packed string to compress space separated zodicas
 .d3                  Current year


Python 3, 88 80 78 75 bytes

-6 bytes thanks to Wheat Wizard
-2 bytes thanks to RootTwo
-3 bytes thanks to notjagan

s={0}
n=1
while 1:n+=1;b=f"{n:b}";p={b[1:],b[:-1]};s|=p-s and{b,print(n)}|p

Try it online!


Interquine - Two programs that output each other in a loop

CJam, 13 + 13 = 26 bytes

{sYZe\"_~"}_~

Try it online!

Outputs

{sZYe\"_~"}_~

Explanation

{       e# Standard quine framework, leaves a copy of the block on the stack
        e# for the block itself to process.
  s     e# Stringify the block.
  YZe\  e# Swap the characters at indices 2 and 3, which are Y and Z themselves.
  "_~"  e# Push the "_~" to complete the quine.
}_~

Since e\ is commutative in its second and third operand, the other program does exactly the same, swapping Z and Y back into their original order.


Print all multiples of 32 from 0 to `n`...imperfectly

C

#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
    int n = atoi(argv[1]);
    for(int i = 0; i < n; i++) {
        if(i & 31 == 0) {
            printf("%d\n", i);
        }
    }
}


Python 3, 134 bytes
-3 bytes thanks to @tsh
Note that it fails for CH_2. It is unclear whether such a test case is valid, but I will keep this solution for now.

lambda e:['Aldehyde','Alcohol','Carboxylic Acid',0][e[::-1].rfind('O')]or'Alk%sne'%'eay'[eval(e.translate({67:45,72:43,95:43})+'//2')]

Try it online!
Python 3, 137 bytes
Works for all cases including CH_2.

lambda e:['Aldehyde','Alcohol','Carboxylic Acid',0][e[::-1].rfind('O')]or'Alk%sne'%'yae'[eval(e.translate({67:43,72:43,95:'~-'})+'//-2')]

Try it online!


shortest possible python pascal triangle code

This is a bit shorter, but still no good:

l=[1]
while(len(l)<32):
 print' '.join(map(str,l))
 l=[1]+map(int.__add__,l,l[1:]+[0])

And this one comes in at a score of 8.28 (credit to @primo):

l=[1];exec"print' '.join(map(str,l));l=map(sum,zip([0]+l,l+[0]));"*31


JavaScript (ES6), 65 bytes
1-indexed.

n=>{for(o=p=[k=1];o[k]|~-(i=p^k)&i?k++:k=o[p=k]=!!n--;);return p}

Try it online!
Commented
n => {                  // n = index of requested term
  for(                  // for loop:
    o =                 //   o = storage object for the terms of the sequence
    p =                 //   p = last term found in the sequence
      [k = 1];          //   k = current term
    o[k] |              //   if k was already encountered
    ~-(i = p ^ k) & i ? //   or (p XOR k) has more than 1 bit set:
      k++               //     increment k
    :                   //   else:
      k = o[p = k]      //     set o[k], set p to k
        = !!n--;        //     stop if n is equal to 0 or set k to 1; decrement n
  );                    // end of for()
  return p              // return p
}                       // end


Output the smallest powers of 2 with two identical sub-strings of digits n long

APL (Dyalog Extended), 68 bytes

'01'(0{x≢`∪x←⍺⍺,/⍺:⍺((⍺⍺+1)∇∇)⊃⎕←⍵,⊃a/⍨</¨⊢a←⍸∘.≡⍨x⋄(+⌂big⍨⍺)∇1+⍵})0

Try it online!
APL is not known for big integer arithmetic, infinite output, or interpreter speed (and using Extended incurs even more overhead), yet it outputs successfully up to n=9 barely under a minute.
How it works
The code is basically an infinitely running recursive operator. The left argument is the string representation of the power of 2, the right argument is the corresponding exponent (which was needed to meet the speed requirement), and the left operand is the current value of n.
{
  x←⍺⍺,/⍺          ⍝ Extract length-n segments of given number
  x≢`∪x:           ⍝ If it has duplicates...
  a←⍸∘.≡⍨x         ⍝   Construct the pairs of indices of equal slices
  ⊃a/⍨</¨⊢a        ⍝   Keep the ones (L,R) where L<R and take the first one
  ⊃⎕←⍵,...         ⍝   Concat with the exponent, print it, extract ⍵ back
  ⍺((⍺⍺+1)∇∇)...   ⍝   Continue running with n+1
  ⋄                ⍝ Otherwise...
  (+⌂big⍨⍺)∇1+⍵    ⍝   Recurse with next power of two, using same n implicitly
}
'01'(0{...})0  ⍝ Invoke the dop with starting values


Python, 23938 score

from math import*
def apothem(n):
 c=int(n*tan(pi/n)/2*10)

 s=',>' + '+'*c
 m=">[-]>[-]<<[>>+<<-]>>[<<<[>+>+<<-]>>[<<+>>-]>-]<<"*2
 p=">>[-]<[-]<+++++<[-]++++++++++"
 d=">[>+<-]>[<<[>>>+>+<<<<-]>>>>[<<<<+>>>>-]<[>+<<-[>>[-]>+<<<-]>>>[<<<+>>>-]<[<-[<<->>[-]]+>-]<-]<<+>]"
 o="<."
 print s+m+p+d+o

the area of a regular polygon is nsa/2 width n given in Python and a later in BF. s is the sidelength of the polygon, which can be computed from a and n
c is a constant, such that the area is (aac+5)/10, so only this formula must be coded into BF. c is between 15 and 25.
s is the starting point for the BF code: read the apothem and write c
m does c=ca twice, so in the cell formaly holding c there is aac
p prepares for the final operation, clearing temporary cells, adding 5 to aac and setting the first cell to 10
d division
o output

This is my first writing in BF, so all algorithms are from this page.


Pyth, 73 bytes

eo_S+*-5l@\AN}SPMJ+NZSM.:+\AT5+-4l{eMJlM.gPkJ-sM*=T+`M}2Tc4"JQKA""hscd"=Zc

This is pretty terrible. Parsing cards, sorting the values, ... Everything takes so many chars. But the approach is interesting.

Try it online: Demonstration or Test Suite

Explanation:

I generate all 52 cards, remove the four cards of the input, generate a score for each card (score of the hand), and print the card with the maximal score.

The score is a little bit odd. If I compare the score of two completely different hands, it may pick the wrong winner. E.g. a straight would beat 4 aces. But it works, if the first 4 cards are the same in both hands. And my computed score is actually not a value, but a list of values:

G: First I group the 5 cards by rank and take the lengths: 5h 5d 6c 5s Jd -> [3, 1, 1]
F: Then I append 4 minus the number of different suites to this list. Flush -> 3 gets appended, not flush -> 2/1/0 gets appended.
S: Add another number. 0 if it is not a straight, 4 if it is the straight A2345, or 5 if it is a higher straight.

These lists of 4-7 numbers get sorted in decreasing order and the list with maximal value is picked.

Why does this work? Here you see the possible configurations for all types. The letter beside the numbers, tell you with which rule this number got generated.

Straight flush: [5S, 3F, 1G, 1G, 1G, 1G, 1G] or [4S, 3F, 1G, 1G, 1G, 1G, 1G]
Four of a kind: [4G, 1G, 0F, 0S]
Full house: [3G, 2G, 1F, 0S] or [3G, 2G, 0F, 0S]
Flush: [3F, 1G, 1G, 1G, 1G, 1G, 0S]
Straight: [5S, 2F, 1G, 1G, 1G, 1G, 1G], [5S, 1F, 1G, 1G, 1G, 1G, 1G], [5S, 1G, 1G, 1G, 1G, 1G, 0F], [4S, 2F, 1G, 1G, 1G, 1G, 1G], [4S, 1F, 1G, 1G, 1G, 1G, 1G], [4S, 1G, 1G, 1G, 1G, 1G, 0F]
Three of a kind: [3G, 1G, 1G, 1F, 0S], [3G, 1G, 1G, 0F, 0S]
Two pair: [2G, 2G, 2F, 1G, 0S], [2G, 2G, 1F, 1G, 0S], [2G, 2G, 1G, 0F, 0S]
One pair: [2G, 2F, 1G, 1G, 1G, 0S], [2G, 1G, 1G, 1G, 1F, 0S], [2G, 1G, 1G, 1G, 0F, 0S]
High card: [2F, 1G, 1G, 1G, 1G, 1G, 0S], [1F, 1G, 1G, 1G, 1G, 1G, 0S], [1G, 1G, 1G, 1G, 1G, 0S, 0F]

Pyth compares lists element-wise. So it's obvious that a Straight flush will always beat Four of a kind. Most of the typical poker rules are obvious with these lists. Some seem conflicting.

A Straight will win against Four of a kind or a Full house: Not a problem. If you have a chance to get Four of a kind / Full house with the river card, than you can't reach a straight at the same time (since you already have 2 or 3 different suites in your hand).
A Straight will win against a flush. If you can reach a flush and a straight with the river card, then you also can reach a straight flush. And the straight flush has a better score than both the straight and the flush.
One pair [2G, 2F, 1G, 1G, 1G, 0S] will win against some two pair hands. Also no problem. If you get a two pair with the river card, than you had at least one pair before the river. But this means, that you can improve to three of a kind, which is better. So a two pair will actually never be the answer.
High card [2F, 1G, 1G, 1G, 1G, 1G, 0S] will win against some one pair hands. If this is the best score you can reach, before the river you will have 3 cards of one suite and one card of a different suite. But then you can choose the card with one of these two suites and with a value that already appears, and you'll end up with the score [2F, 2G, ...], which is also better.

So this chooses the correct type of solution. But how do I get the best one-pair (out of 4 possibilities), how do I choose the best straight, ...? Because two different one-pair solutions can have the same score.

That's easy. Pyth guaranties stable sorting (when taking the maximum). So I simple generate the cards in the order 2h 2s 2c 2d 3h 3s ... Ad. So the card with the highest value will automatically be the maximum.

Implementation details

=Zc splits the input string and stores the list of cards in Z.
=T+`M}2Tc4"JQKA" generates the list of ranks ['2', ..., '10', 'J', 'Q', 'K', 'A'] and stores them in T. -sM*T..."hscd"Z generates each combination of rank with the suites, and removes the cards of Z.

o... orders these remaining cards by: lM.gPkJ the lenght of the groups of the ranks, +-4l{eMJlM appends 4 - length(suites), +*-5l@\AN}SPMJ+NZSM.:+\AT5 appends 0/4/5 depending on suite (generate each substring of length 5 of "A"+T, check if the hand one of them (requires sorting the hand and sorting all subsets), multiply by 5 - number of "A"s in the card), _S sorts the list decreasing.

e pick the maximum and print.


Shortest code in your language to persist a string across a reboot

zsh, 4 bytes

Store: >f (reads from STDIN and writes to a file called f)
Retrieve: <f (writes the contents of f to STDOUT)


Create a list of snaking numbers under 50,000

K (ngn/k), 60 57 bytes

(x;#x:{*/1=3!5&+/x*x:+1_-':(+0 1,'2*!3 3)@10\x}#1+!50000)

Try it online!

!50000 list of 0 .. 49999

1+ add 1 to all

{ }# filter with the function in { }

10\x decimal digits of the argument

( )@ use as indices in ...

!3 3 a pair of lists: (0 0 0 1 1 1 2 2 2;0 1 2 0 1 2 0 1 2)
2* multiply all by 2
0 1,' prepend 0 to the first list and 1 to the second
+ transpose (pair of lists -> list of pairs). this gives us the approx button coords.

-': subtract from each pair the previous pair. use 0 0 as an imaginary element before the first.

1_ drop the first

+ transpose

x*x: square (assign to x and multiply by x). here x is a pair of lists - ∆x-s and ∆y-s

+/ sum the two lists (element by element)

5& min with 5

3! mod 3

1= boolean list of where it's equal to 1

*/ product (boolean "and")

(x;#x: ) make a pair of the result and the length (#) of the result


Can an ant spell words by walking on cube?

Ruby, 272 bytes
Two unnecessary newlines are added to the code either side of nested function g to improve readability. These are excluded from the score. The characters f= which assign the anonymous function to a variable are also excluded.
Output format is 0 or 1 per the question instead of Ruby's native true and false. A newline (rather than a space) is used to separate the boolean and the word. My understanding is that this is an acceptable interpretation of the output requirements, but if not, the impact on the byte count would be minor.
f=->n,l{c=''
x=[p=6*n,1,-p,-1]
(m=3*p*n).times{|i|c<<(5+i/n%6-i/n/p&6==6?65+rand(26):i%p==p-1?10:46)}
q=m+3*n
puts c

g=->w,i,d{w==''?$r=1:c[i]<?A?g[w,(i+x[d])%q,d^1]:w[0]==c[i]&&4.times{|j|g[w[1..-1],(i+x[j])%q,j^1]}}

l.each{|w|$r=0
m.times{|i|c[i]>?@&&g[w,i,0]}
puts $r,w}}

Output
After about 50 calls like this:
f[4,['PPCG','CODE','GOLF','ANT','CAN','CUBE','WORD','WALK','SPELL']]

I finally got the following output with 2 hits. ANT is at the bottom right going upwards, and the AN is shared by CAN, with the C wrapping round to top left.
....KCAAXRHT...........
....ALRZXRKL...........
....NDDLCMCT...........
....ETQZHXQF...........
........FYYUSRZX.......
........CFNPAUVX.......
........ZTJVHZVQ.......
........AUWKGVMC.......
............XWKSDWVZ...
............DPLUVTZF...
............DMFJINRJ...
............ZRXJIAFT...
0
PPCG
0
CODE
0
GOLF
1
ANT
1
CAN
0
CUBE
0
WORD
0
WALK
0
SPELL

Explanation
The particular unfolding of the cube selected, was chosen partly for its ease of drawing, but mainly for its ease of searching.
The non-alphabet characters (the dots plus the newline at the end of each line) are an important part of the field where the ant may be found walking.
Searching is performed by the recursive function g, which is nested in function f . If the word passed is an empty string the search is complete and $r is set to 1. If the ant is on a letter square which corresponds to the first letter of the word, the search is continued in all four directions: the function is called again with the word shortened by removing its first letter. In this case the direction parameter is ignored. The moving is done by recursively calling with the cell index altered by the values in x. The result of the addition is taken modulo the size of the grid plus an extra half line. This means that the bottom line wraps round to the top and vice versa, with the correct horizontal offset.
If the ant is on a non-letter square, she must zigzag in a staircase motion until she finds a letter square. She will zizag in southeast or northwest direction. This is simulated by recursive calls with the d parameter being XORed with 1 each time to keep track of her movement. Until she reaches the next letter square, there is no shortening of the input word. Conveniently, this may be done by the same recursion as is used when we are searching in the area with letters. The difference is, the recursion has only one branch when the ant is in the whitespace area, as opposed to 4 in the letter area.
Commented code
->n,l{                                   #n=square size, l=list of words to search
  c=''                                   #empty grid
  x=[p=6*n,1,-p,-1]                      #offsets for south, east, north, west. p is also number of characters per line
  (m=3*p*n).times{|i|                    #m=total cells in grid. for each cell
    c<<(5+i/n%6-i/n/p&6==6?              #apppend to c (according to the formula)
      65+rand(26):                       #either a random letter
      i%p==p-1?10:46)                    #or a "whitespace character" (newline, ASCII 10 or period, ASCII 46)
  }
  q=m+3*n                                #offset for vertical wraparound = grid size plus half a row.
  puts c                                 #print grid

  g=->w,i,d{                             #search function. w=word to search for, i=start index in grid, d=direction
    w==''?                               #if length zero, already found,
      $r=1:                              #so set flag to 1. Else
      c[i]<?A?                           #if grid cell is not a letter
        g[w,(i+x[d])%q,d^1]:             #recursively call from the cell in front, with the direction reflected in NW-SE axis
        w[0]==c[i]&&                     #else if the letter on the grid cell matches the start of the word
          4.times{|j|                    #for each direction (iterate 4 times, each time a different direction is "in front")
            g[w[1..-1],(i+x[j])%q,j^1]}  #recursively call from the cell in front. Chop first letter off word.
   }                                       #Direction parameter is XORed (reflected in NW-SE axis) in case ant hits whitespace and has to zigzag.

   l.each{|w|                            #for each word in the list
     $r=0                                #set global variable $r to zero to act as a flag
     m.times{|i|c[i]>?@&&g[w,i,0]}       #call g from all cells in the grid that contain a letter
     puts $r,w}                          #output flag value and word
}


Find the program that prints this integer sequence (Cops' thread)

Vim, 36 keystrokes -- Safe!

i****<esc>:let @q="^*i****$**@***"<cr><n>@qbD

(Note: <n> is where you type your input)

Here is the code unrelated to number generation:

          :let @q="              "<cr><n>@qbD

Meaning I am revealing 5 out of 19 characters.

<n> is the input. Here are some sample outputs:

1@q:    1
2@q:    3
6@q:    18

Answer

This code prints The Lucas Numbers (A000032), which are just like The Fibonnaci Sequence, except that it starts on 2, 1 instead of 1, 1. Here are the first 15 numbers:

2, 1, 3, 4, 7, 11, 18, 29, 47, 76, 123, 199, 322, 521, 843

Here's the revealed code:

i2 1 <esc>:let @q="^diwwyw$pb@-<c-v><c-a>"<cr><n>@qbD

Explanation:

i2 1 <esc>                          "Insert the starting numbers
          :let @q="....."<cr>       "Define the macro 'Q'

Explanation of the macro:

^                      "Move to the first non-whitespace character on the line.
 diw                   "(d)elete (i)nner (w)ord. This is different then 'dw' because it doesn't grab the space.
                      "It also throws people off since 'i' is usually used for inserting text.
    wyw$               "Move to the next number, yank it then move to the end of the line
        pb             "(p)aste the yanked text and move (b)ack
          @-     <c-a> "@- is the register holding the word we deleted. Increment the current number that many times.
            <c-v>      "Since we're adding <c-a> this from the command line, we need to type it as a literal.

Now, we just need to remove the second number, since the first number is the lucas number we want. So we do

b   "move (b)ack
 D  "(D)elete to the end of the line.

Also, if I'm not mistaken, this is the first safe submission! That's kinda cool.


Mathematica, 43 bytes

Union/@SortBy[l=#,f=-l~Count~#&]~SplitBy~f&

Try it online! (Using Mathics.)

Alternatively:

SortBy[Union[l=#],f=-l~Count~#&]~SplitBy~f&


Solve Subset-Sum in polynomial time (...if P = NP)

Python 3.8 (on Unix), 429 bytes

Since nobody else has posted an answer yet, I thought I'd have a go, though I not 100% certain I haven't missed something important (and I am 100% certain the code could be shrunk down significantly).

As noted in the question, evaluating arbitrary Python strings is dangerous. Fortunately, it's easy to come up with a safe subset of strings whose evaluation is still Turing complete, by embedding the Turing complete While Programming Language, summarised below:

This can be embedded into Python using only strings that match the following regex:

^([0-9 \n():_=+-]|while)+$

To reduce the number of necessary characters, we use a few embedding hacks:

variable names are built only of underscores
if B then C1 else C2 is emulated using while loops (and temporary variables x and y, which hang around afterwards but that's ok):

x=B;y=not x
while x:C1;x=False
while y:C2;y=False

skip is emulated using any constant expression, e.g. 0
true is emulated using e.g. 0==0
false is emulated using e.g. 0==1
B & C is emulated using a pre-evaluated if-then-else (and another temporary variable x):

if B then x=C else x=False

¬ B is emulated using 1-B

To make our life easier, we also allow [ and ], as this permits direct operations on lists (including slicing and concatenation) which avoids having to translate the problem from one on lists into one on integers.

Update: as noted by @ØrjanJohansen, it's also necessary to include < to ensure basic arithmetic remains polynomial.

I claim that any program with just those characters will either execute, or (far more likely) fail to execute, or raise an exception, but will not crash the interpreter or change any global state. Please correct me if I'm wrong.

The rest of the solution is now similar to the prototype presented in the question. We generate all strings of increasing lengths n and execute them, prepopulating the input in variable _ and checking and validating any output from the same variable. We catch any raised exceptions and continue.

The main tricky bit is ensuring polynomial complexity (and termination). We do this by breaking out of each execution after n seconds, using Unix signals and a handler that raises an exception (which the string executions themselves have no way of catching). Since every program will appear repeatedly (eg with trailing whitespace), we don't need to worry about breaking out too soon from a correct program. One tricky bit here is to make sure that the program doesn't crash if the signal is received after the execution completed (successfully or not) but before the signal has been reset; this explains the nested try-catch.

from itertools import*
from re import*
from signal import*
I=eval(input())
signal(SIGALRM,0)
for n in count():
 for p in product(*[set(map(chr,range(128)))]*n):
  if match("([0-9 \n()[\]:_=<+-]|while)+$",(s:="".join(p))):
   try:
    try:
     g={'_':I[::]};alarm(n);exec(s,g);h=g['_']
     if h and all(h.count(x)<=I.count(x)for x in h)and sum(h)==0:
      print(h);n=-1;break
    except:0
    alarm(0)
   except:0
 if n<0:break

Try it online! (though don't expect an actual result; it may be P but it's obscenely slow)


Plain English, 1059 1025 678 641 451 399 bytes

Saved 34 bytes by removing an error trap.  Then saved 384 bytes by golfing.  Then saved 190 bytes by combining the division operation with the append operation ("z") into a new operation ("p").  Then saved 52 bytes by golfing.

A s is a string.
To p a r remainder a s a x string a n number:
If the x is "", exit.
Divide the r by the n giving a q quotient and the r.
Fill a t s with the x's first's target given the q.
Append the t to the s.
To convert a r number to a s:
p the r the s "M" 1000.
p the r the s "D" 500.
p the r the s "C" 100.
p the r the s "L" 50.
p the r the s "X" 10.
p the r the s "V" 5.
p the r the s "I" 1.

Here is the ungolfed version of the final code, plus an error trap for a negative number:

A roman numeral is a string.

To process a remainder given a roman numeral and a letter string is a number:
  If the letter is "", exit.
  Divide the remainder by the number giving a quotient and the remainder.
  Fill a temp string with the letter's first's target given the quotient.
  Append the temp string to the roman numeral.

To convert a number to a roman numeral:
  If the number is negative, exit.
  Put the number in a remainder.
  Process the remainder given the roman numeral and "M" is 1000.
  Process the remainder given the roman numeral and "D" is  500.
  Process the remainder given the roman numeral and "C" is  100.
  Process the remainder given the roman numeral and "L" is   50.
  Process the remainder given the roman numeral and "X" is   10.
  Process the remainder given the roman numeral and "V" is    5.
  Process the remainder given the roman numeral and "I" is    1.


JavaScript (ES6),  226  219 bytes
Brute force search, using right ("R") and down ("D") moves.
Returns either a string describing the moves, or an empty array if the input matrix is already sorted. Columns and rows in the output are 0-indexed.

f=(m,M=2)=>(g=(s,m)=>m[S='some'](p=r=>r[S](x=>p>(p=x)))?!s[M]&&m[0][S]((_,x,a)=>g(s+'D'+x,m.map(([...r],y)=>(r[x]=(m[y+1]||a)[x])&&r)))|m[S]((_,y)=>g(s+'R'+y,m.map(([...r])=>y--?r:[r.pop(),...r]))):o=s)([],m)?o:f(m,M+2)

Try it online!
Commented
f =                              // f = main recursive function taking:
(m, M = 2) => (                  //   m[] = input matrix; M = maximum length of the solution
  g =                            // g = recursive solver taking:
  (s, m) =>                      //   s = solution, m[] = current matrix
    m[S = 'some'](p =            // we first test whether m[] is sorted
      r =>                       // by iterating on each row
        r[S](x =>                // and each column
          p > (p = x)            // and comparing each cell x with the previous cell p
        )                        //
    ) ?                          // if the matrix is not sorted:
      !s[M] &&                   //   if we haven't reached the maximum length:
      m[0][S]((_, x, a) =>       //     try all 'down' moves:
        g(                       //       do a recursive call:
          s + 'D' + x,           //         append the move to s
          m.map(([...r], y) =>   //         for each row r[] at position y:
            (r[x] =              //           rotate the column x by replacing r[x] with
              (m[y + 1] || a)[x] //           m[y + 1][x] or a[x] for the last row (a = m[0])
            ) && r               //           yield the updated row
      ))) |                      //
      m[S]((_, y) =>             //     try all 'right' moves:
        g(                       //       do a recursive call:
          s + 'R' + y,           //         append the move to s
          m.map(([...r]) =>      //         for each row:
            y-- ?                //           if this is not the row we're looking for:
              r                  //             leave it unchanged
            :                    //           else:
              [r.pop(), ...r]    //             rotate it to the right
      )))                        //
    :                            // else (the matrix is sorted):
      o = s                      //   store the solution in o
)([], m) ?                       // initial call to g(); if we have a solution:
  o                              //   return it
:                                // else:
  f(m, M + 2)                    //   try again with a larger maximum length


CJam, 32 30 29 28 bytes

ri_"/\ /"2/f*)@,\f>+_z..e>N*

Test it here.

I was trying to help Reto golf his CJam answer but ended up with a solution that had nothing to do with his, so I figured I might as well post it myself.

Explanation

This makes use of the symmetry of the output. In particular, the fact that the output is the same as its transpose.

First, we generate the first N+1 lines, but without the left edge:

ri       e# Read input and convert to integer N.
_        e# Duplicate.
"/\ /"2/ e# Push an array with two strings: ["/\" " /"]
f*       e# Repeat each of the two strings N times. That gives the first two rows.
)        e# Detach the second row.
@,       e# Pull up the other copy of N and turn into range [0 1 ... N-1].
\f>      e# For each element i in that range, discard the first i characters of
         e# the second row.
+        e# Add all those lines back to the first row.

Now we've got an array of strings representing the following grid:

/\/\/\/\
 / / / /
/ / / /
 / / /
/ / /

The transpose of that looks like this:

/ / /
\/ /
/ / /
\/ /
/ / /
\/ /
/ /
\/

Together, these have all the non-space characters that we need. We can now make use of Dennis's rad tip to combine two ASCII grids into one, by taking the maximum of each corresponding pair of characters. In all positions where the two grids differ, one will have a space (or nothing at all) and the other will have the character we're looking for. When one list in a vectorised operation is longer than the other, the additional elements of the longer list will simply be kept, which is just what we're looking for. In the other cases, the non-space character will always be the maximum of the two characters:

_z   e# Duplicate the grid and transpose it.
..e> e# For each pair of characters in corresponding positions, pick the maximum.
N*   e# Join the lines by linefeed characters.


05AB1E, 13 bytes

Encoder, 8 bytes

0ì¥ĀηOØP

Try it online!

Explanation

0ì          # prepend 0 to input
  ¥         # calculate deltas
   Ā        # truthify each
    η       # calculate prefixes
     O      # sum each
      Ø     # get the prime at that index
       P    # product

Decoder, 5 bytes

Ò.ØÉJ

Try it online!

Explanation

Ò       # get prime factors of input
 .Ø     # get their indices among the primes
   É    # check for oddness
    J   # join


Drat, I was hoping to get here before the GolfScripters arrived :-(
Anyhoo...
C: 228 characters:
char n,t,m[9],*c=" etianmsurwdkgohvf l pjbxcyzq  54 3   2& +    16=/   ( 7   8 90    $       ?_    \"  .    @   '  -        ;! )     ,    :";
main(){while(scanf("%s",m)>0){for(t=m[6]=n=0;m[n];n++)t+=t+1+(m[n]&1);putchar(c[t]);}}

I thought I'd add an explanation of how this works.
The input data is parsed according to the tree data in *c, which can be expanded as follows (using · to represent a vacant node):
                     dot <-- (start) --> dash
                e                               t
        i               a               n               m
    s       u       r       w       d       k       g       o
  h   v   f   ·   l   ·   p   j   b   x   c   y   z   q   ·   ·
 5 4 · 3 · · · 2 & · + · · · · 1 6 = / · · · ( · 7 · · · 8 · 9 0
····$·······?_····"··.····@···'··-········;!·)·····,····:·······

Starting at the top of the tree, work your way down while moving to the left for a dot and to the right  for a dash. Then output whatever character you happen to be at when the input string ends (i.e., when a whitespace character is encountered). So for example, three dots and a dash will take you to v via e, i and s. Instead of explicitly checking for dots (ASCII \x2e) and dashes (ASCII \x2d), we only need to check the last bit (m[n]&1), which is 0 for . and 1 for -.
Six rows are enough to encode everything except $, which has 7 dot/dashes: ...-..-, but since the input data is guaranteed to be valid, this can easily be fixed by truncating the input at 6 characters (m[6]=0) and interpreting ...-.. as $ instead. We can also cut away the last 7 bytes from the tree data, since they are all empty and aren't needed if the input is valid.


MATL, 31 bytes
Thanks to Jonathan Allan for a correction.
'BAGFEDC'"GYs12X\110BQX@YSYsm?@

Try it online! Or verify all test cases.
Explanation
The pattern 2 2 1 2 2 2 1 specifies the intervals between consecutive white keys. The program uses a loop that applies all cyclic shifts to this basic pattern, in order to test each key as a potential lowest note of the input chord. For each shift, the cumulative sum of the pattern is obtained. For example, for B as potential lowest note, the pattern has been shifted to 1 2 2 1 2 2 2 and its cumulative sum is 1 3 5 6 8 10 12.
Now, to see if this can support a 4 3 3 chord we compute the cumulative sum of the chord intervals, which is 4 7 10; reduce it via 1-based modulo 12 (an interval of 14 would give 2); and check if those numbers are all members of the allowed values 1 3 5 6 8 10 12. That's not the case in this example. Had it been the case, we would output the letter B.
The correspondence between cyclic shifts and output letters is defined by the string 'BAGFEDC'. This indicates that 'B' (first character) corresponds to a cyclic shift by 1; 'A' (second character) corresponds to a cyclic shift by 2 etc.
'BAGFEDC'  % Push this string
"          % For each character from the string
  G        %   Push input array
  Ys       %   Cumulative sum
  12X\     %   1-based modulo 12, element-wise (1,12,13,14 respectively give 1,12,1,2)
  110BQ    %   Push 110, convert to binary, add 1 element-wise: gives [2 2 1 2 2 2 1]
  X@       %   Push current iteration index, starting at 1
  YS       %   Cyclic shift to the right by that amount
  Ys       %   Cumulative sum
  m        %   Ismember. Gives an array of true of false entries
  ?        %   If all true
    @      %     Push current character
           %   End (implicit)
           % End (implicit)
           % Display (implicit)


Python 3, 269 254 252 246 bytes

d,m,i=eval(input())
S=set()
for n in range(1,1001):
 T=X=()
 while len(T)**3<1e9>=n:
  T=(n,)+T;n=[n//d,n*m+i][n%d>0]
  if n in T:I=T.index;L=T[:I(n)+1];M=I(min(L));X=L[M:]+L[:M]
 S|={X}
for x in sorted(S):print(x and"LOOP"or"DIVERGENT",*x[::-1])

(Now 10 times slower to save a few bytes. Typical code golf.)
Input a list via STDIN (e.g. [2, 3, 1]). I'm thinking that there's got to be a better way of standardising the cycles...
The approach is quite straightforward — test all 1000 numbers and take only the unique outputs. However, there are two little tricks in there:

Loops are represented by nonempty tuples, but more importantly divergence is represented by an empty tuple. This is good because:

It doesn't break sorted, and will even appear before all the loop tuples
It allows us to select a string via x and"LOOP"or"DIVERGENT"
*()[::-1] doesn't affect print

The loops are built backwards to turn "sort ascending by last element" into "sort ascending by first element", which removes the need to pass a lambda into sorted.

Previous submission, 252 bytes
d,m,i=eval(input())
def f(n,T=()):
 x=[n//d,n*m+i][n%d>0];I=T.index
 if x in T:L=T[:I(x)+1];M=I(min(L));return L[M:]+L[:M]
 return()if(T[1000:]or x>1e9)else f(x,(x,)+T)
for x in sorted(set(map(f,range(1,1001)))):print(x and"LOOP"or"DIVERGENT",*x[::-1])

This one's a lot faster.


This highway needs rain across both of its lanes

Jelly,  18  16 bytes

ZḢ”\E?€ṣ”|»Ṁ$€K»

A monadic Link accepting a list of lines, each of which is a list of characters, which yields another, similar list.

Try it online! Or see the test-suite.

How?

ZḢ”\E?€ṣ”|»Ṁ$€K» - Link: list of lists of characters (i.e. rows of text)
Z                - transpose - i.e. columns (each being: all spaces; all pipes; or a mix)
      €          - for each (column):
     ?           -   if...
    E            -   ...condition: all equal? - i.e. if not dashed
 Ḣ               -   ...then: head - i.e. the unique character
  ”\             -   ...else: literal '\' character
        ”|       - literal '|' character
       ṣ         - split at - i.e. highway chunks now contain spaces and '\' characters
             €   - for each (chunk):
            $    -   last two links as a monad:
           Ṁ     -     maximum - N.B. '\' > ' '
          »      -     maximum (vectorises across the chunk)
                 -   - i.e highway chunks become all '\', others remain as is
              K  - join with space characters
               » - maximum (vectorises across the rows)
                 -   - N.B. '|' > ' ' so the solid lines are not replaced by spaces; and
                 -          '|' > '\' so the dashed lines are not replaced with rain.


CJam, 67 62 60 58 57 54 bytes

Thanks to Dennis for saving 4 bytes.

{:Gsc_32&{"()"[GGz2{1m<_{S#}#>W<\}*z]{},{J}%',**+}|}:J

This defines a named block (function) J and leaves it on the stack. The function itself expects an array of strings on the stack, which represents the input grid, and leaves the desired string in its stead.

Test it here.

I've been meaning to tackle this one since it was posted, but apparently I needed a bounty and an overly long Pyth solution to motivate myself sufficiently.

Explanation

The solution is of course recursive and gradually builds up the string.

{
  :G       e#  Store the current grid in G.
  sc       e#  Convert the grid to a string, flattening it, then to a character, which
           e#  discards everything but the first character. This is a golfed 0=0=.
           e#  This character will either be an upper-case letter (function) or a lower-
           e#  case letter (variable).
  _32&     e#  Make a copy of the character and take bitwise AND with 32. This gives a
           e#  NULL character for functions and a space for variables.
  {        e#  If the result is falsy... (i.e. NULL, i.e. we have a function)
    "()"   e#   Push parentheses for later use.
    [      e#   Remember the current stack depth.
    GGz    e#   Push an array which contains the grid and its transpose.
    2{     e#   Run this block twice... (it will be applied once to each grid)
      1m<  e#    Rotate the rows. This has two effects: a) It removes the first row
           e#    from the front such that we can go looking for the next non-space
           e#    character down the first column from the start. b) It places a row
           e#    at the end which we know doesn't start with a space, which acts as
           e#    a guard in case there are no further letters below the current one.
      _    e#    Duplicate this grid.
      {    e#    Find the first index where this block yields something truthy...
        S# e#     Find the index of the first space in the current row. If the row
           e#     starts with a space, this is 0, i.e. falsy and the search continues.
           e#     If there is a space in any later position, that will be positive and
           e#     truthy, so this index gets returned. If there is no space at all,
           e#     the result is -1 which is also truthy and ends the search.
      }#
      >    e#     Discard all lines up to (but not including) the found index.
      W<   e#     Discard the guard row at the end.
      \    e#     Swap the grids so that the next pass processes the other grid.
    }*
    z      e#    Transpose the second grid back to its original orientation.
    ]      e#    Wrap both processed grids in an array.
    {},    e#    Remove a grid if it's empty.
    {J}/   e#    For each remaining grid, call J recursively.
    ',*    e#    Join the grids with commas if there are still two of them.
    *      e#    Wrap this string in the parentheses below on the stack.
    +      e#    Prepend the function name.
  }|
}:J


Project Euler Problem 12: optimize memory usage

MIPS32 Assembly.  Uses 8 bytes of memory (4 for format string, 4 for saving a pointer), everything else stays in registers.  This should work in x86-64, too, but ia32 will probably require some temporary values to be stored in memory.

    .text
    .globl main
main:
    xor $t0, $t0, $t0
    xor $t1, $t1, $t1
loop1:
    addiu $t0, $t0, 1
    addu $t1, $t1, $t0
    addiu $t3, $zero, 1
    addiu $t5, $zero, 2
    srl $t6, $t1, 1
loop2:
    slt $t4, $t6, $t5
    bne $t4, $zero, loop2end
    div $t1, $t5
    mfhi $t4
    bne $t4, $zero, non_divisor
    addiu $t3, $t3, 1
non_divisor:
    addiu $t5, $t5, 1
    j loop2
loop2end:
    slti $t4, $t3, 501
    bne $t4, $zero, loop1
    la $a0, str
    addu $a1, $t1, $zero
    addiu $sp, $sp, -4
    sw $ra, 0($sp)
    jal _printf
    lw $ra, 0($sp)
    addiu $sp, $sp, 4
    jr $ra
    .data
str:
    .asciiz "%d\n"


TI-BASIC, 3 bytes

Ans×√Ans

TI-BASIC uses tokens, so Ans and ×√ are both one byte.

Explanation

Ans is the easiest way to give input; it is the result of the last expression. ×√ is a function for the x'th root of x, so for example 5×√32 is 2.


Python 3, 443 158 155 154 134 131 128 124 117 116 115 bytes

c=d=C=D=0
for e in input():v='[<>,.-+]'.find(e);d=d*8+v;c+=c<0<6<v;c-=d>1>v;C,D=(c,C+1,d,D)[v>6::2]
print(-~D*8**C)

Several bytes thanks to Sp3000 and Mitch Schwartz :D

How this works:

This maps all valid BF programs into all possible, valid or invalid, BF programs, that don't start with a [, in a one-to-one ratio. After that, the new program is simply converted into octal.

Here is the mapping formula:

Separate a BF program into 3 parts. The first part is the largest prefix consisting of only [ characters. The third part is the largest postfix consisting of only ] characters. The second part is the middle.
Dispose of the first part. These can be recomputed later.
Remove all ] brackets in the third part that match [ brackets in the second part. These can also be recomputed later.
Concatenate the second and third parts together.

If you don't understand this explanation, you can find an extended explanation in chat starting here.

For reference, here are the first 20 programs:

1 :
2 : <
3 : >
4 : ,
5 : .
6 : -
7 : +
8 : []
9 : <[]
10 : <<
11 : <>
12 : <,
13 : <.
14 : <-
15 : <+
16 : [<]
17 : >[]
18 : ><
19 : >>
20 : >,

Here are the first 1000 programs: http://pastebin.com/qykBWhmD
Here is the program I used to generate them: http://ideone.com/e8oTVl

Here is Hello, World!:

>>> ++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++.
457711481836430915510337664562435564418569135809989841510260388418118348571803953323858180392373


Python 3, 71 69 bytes
Thanks to @xnor for -2 bytes
f=lambda r,a,b:b and[8-int(~-a/3),max(18-2*a,13-a)][r>2]+f(r,a-1,b-1)

A function that takes input via argument of the zero-indexed resource type r, the amount available a and the amount to buy b, and returns the cost.
This makes use of the fact that True and False equate to 1 and 0 in Python, allowing the use of Boolean expressions to index into lists.
How it works
f=lambda r,a,b           Function with input resource type r, amount available a and amount
                         to buy b
b and...                 Base case: return 0 if b=0
[8-int(~-a/3),...][r>2]  If not uranium, yield the unit cost 8-floor((a-1)/3)...
max(18-2*a,13-a)         ..else yield the current uranium unit cost
...f(r,a-1,b-1)          Decrement a and b, then pass to function
...+...                  Add the cost of each unit to give the total cost
:...                     Return the above

Try it on Ideone


Perl 6, 76 bytes

{$^b;$^a;&{S:g/$a<?{$!=$/;all m:ex/$b/>>.&{$!.to>.to||.from>$!.from}}>/$b/}}

Try it online!

Anonymous code block that takes input curried, like f(a,b)(s).

I'm pretty sure this matches up with the intent of the question. Basically, it only makes the substitution if the position of a is not within any of the overlapping matches of b.


JavaScript (Firefox 30-57), 137 bytes

f=(a,b=["",...a],s=new Set(b.map(w=>w[0])))=>b.length>1?(s.size>1)+Math.max(...(for(c of s)f(a,[for(w of b)if(w&&w[0]==c)w.slice(1)]))):1

There must be something wrong with my algorithm as I seem to have to special-case an empty string parameter.


Java 8, 48 39 33 bytes

s->"ROYGBRO BGYORBG".indexOf(s)|7

-6 bytes thanks to @RickHitchcock, so make sure to upvote him as well!
Takes uppercase color as input-String. Outputs -1 for none, 7 for clockwise, and 15 for counterclockwise.
Try it online.
Explanation:
s->      // Method with String parameter and integer return-type
   "ROYGBRO BGYORBG".indexOf(s)
         //  Get the index of the input in the String "ROYGBRO BGYORBG",
         //  which will result in -1 if the input is not a substring of this String
    |7   //  Then take a bitwise-OR 7 of this index, and return it as result

Old 39 bytes answer:
s->(char)"ROYGBRO BGYORBG".indexOf(s)/7

Takes uppercase color as input-String. Outputs 9362 for none, 0 for clockwise, and 1 for counterclockwise.
Try it online.
Explanation:
s->      // Method with String parameter and integer return-type
   (char)"ROYGBRO BGYORBG".indexOf(s)
         //  Get the index of the input in the String "ROYGBRO BGYORBG",
         //  which will result in -1 if the input is not a substring of this String
         //  And cast it to a char (-1 becomes character with unicode value 65535)
    /7   //  Integer-divide it by 7 (the char is implicitly converted to int doing so)


Julia, 78 71 bytes

n->[(i=j=x;while j<2i-3 j=i-(j%2>0?1-j:j+2)÷2;i-=1end;i+j-1)for x=1:n]

This is an unnamed function that accepts an integer and returns an integer array. To call it, assign it to a variable.

The approach here is the same as that described on OEIS.

Ungolfed:

# This computes the element of the sequence
function K(x)
    i = j = x
    while j < 2i - 3
        j = i - (j % 2 > 0 ? 1 - j : j + 2)÷2
        i -= 1
    end
    return i + j - 1
end

# This gives the first n terms of the sequence
n -> [K(i) for i = 1:n]

Saved 7 bytes thanks to Mauris!


AsciiDots, Bash, Cardinal, Dash, evil, fish, goruby, Haystack, Implicit, J-uby, ksh, Ly, mksh, Numberwang, OSH, Python 3, QuadR, Ruby, Super Stack!, Taco, Unefunge-98 (Pyfunge), V (Vim), Wumpus, xonsh, yash, Zsh, 1009 bytes
9 shells, 3 Rubies, some 2D (and 1D!) languages and many languages I learned just for this challenge. I really enjoyed this challenge and learned some new languages and features. I enjoyed finding a shorter way than just the raw string in some languages (in some languages generating the string seemed longer) and trying to re-use the s variable as many times as possible was fun too. I've also tried to keep the byte-count as low as possible. If I find the time and the inclination, I wonder if I could start adding the letters of the alphabet to the end instead... Crazy talk...
' # "194940711909711999999999999940391270919999999999994039127zaeeeawawawawavaeeaaaaamvawvusb"' #165#1#1;.040;"ZYXWVTSRQPONMLKJIHGFEDCBA"8 3*k,q"ABCDEFGIJKLMNOPQRSTUVWXYZ"o¡72"8:é9:é8++:90+1®;65µ
'\&p"A""K"R"M""Z"R&o;';#   x%"ABDEFGHIJKLMNOPQRSTUVWXYZ"x.-$"BCDEFGHIJKLMNOPQRSTUVWXYZ" 0 65 65 if pop dup dup 83 sub if pop outputascii 0 fi pop 1 add dup 91 sub fi "ZYXVUTSRQPONMLKJIHGFEDCBA"#25&o   @"ABCDEFGHIJKLMNOPQRSUVWXYZ"
s="ABCDEFGHIJKLMNOPQRSTUVWXYZ";0#'
0//1;
try:echo -n;print(s[0:23]+"YZ");
except:print(s[0:15]+s[16:]);"""/.__id__;begin ~:*;puts s.gsub ?J,"";rescue;begin A;puts s.gsub ?G,"";rescue;puts s.gsub ?R,"";end;end;'
[ -z $s ]&&echo ABCDEGHIJKLMNOPQRSTUVWXYZ&&exit;echo `[ $status = 1 ]&&echo \${s/Z/}&&exit;[ \e =~ e ]&&echo \${s/Y/}&&exit;\[ -z \$- \]&&echo ABC\${s#ABCD}&&exit;[ -z \$BASHPID ]&&echo \${s/K/}&&exit;[ -z $_OVM_PATH ]||echo $s|tr -d O;[ -z $_OVM_PATH ]||exit;[[ -n $USER_ID ]]&&echo \${s/M/}||echo \${s/B/}`;';/
('Q'⎕R'')⎕A⋄'\} #<esc>ggdG¬AZ:s/#\|V//"""#\'⍵

AsciiDots
The relevant code is:
.-$"BCDEFGHIJKLMNOPQRSTUVWXYZ"

This needs to be wrapped in [...] to avoid [Extended Brainfuck Type I] from outputting rubbish before the desired string because of the ..
Try it online!
Bash
The relevant code is:
s="ABCDEFGHIJKLMNOPQRSTUVWXYZ";0#'...'
[ -z $s ]&&echo ABCDEGHIJKLMNOPQRSTUVWXYZ&&exit;echo `[ $status = 1 ]&&echo \${s/Z/}&&exit;[ \e =~ e ]&&echo \${s/Y/}&&exit;\[ -z \$- \]&&echo ABC\${s#ABCD}&&exit;[ -z \$BASHPID ]&&echo \${s/K/}&&exit;[ -z $_OVM_PATH ]||echo $s|tr -d O;[ -z $_OVM_PATH ]||exit;[[ -n $USER_ID ]]&&echo \${s/M/}||echo \${s/B/}`;'...' #

This first line sets $s to be the full alphabet in uppercase, so -z  $s is false and skipped over. $status is unset, \e is treated as an escape, not a \ and e, $BASHPID is set, $_OVM_PATH is not and $USER_ID isn't set so B is replaced with the empty string in $s (${s/B/}) and echoed it out.
Try it online!
Cardinal
The relevant code is:
x%"ABDEFGHIJKLMNOPQRSTUVWXYZ"x

The cursors spawn from the % and are terminated by the xs. This needed to be moved slightly to prevent additional output.
Try it online!
Dash
The relevant code is:
s="ABCDEFGHIJKLMNOPQRSTUVWXYZ";0#'...'
[ -z $s ]&&echo ABCDEGHIJKLMNOPQRSTUVWXYZ&&exit;echo `[ $status = 1 ]&&echo \${s/Z/}&&exit;[ \e =~ e ]&&echo \${s/Y/}&&exit;\[ -z \$- \]&&echo ABC\${s#ABCD}&&exit;[ -z \$BASHPID ]&&echo \${s/K/}&&exit;[ -z $_OVM_PATH ]||echo $s|tr -d O;[ -z $_OVM_PATH ]||exit;[[ -n $USER_ID ]]&&echo \${s/M/}||echo \${s/B/}`;'...' #

As per Bash, this first sets $s to be the full alphabet in uppercase. so -z $s is false. $status is empty, \e is an escape sequence and doesn't match e, but $- is empty in Dash so that conditional is met and we echo out ABC followed by $s with the prefix ABCD removed (${s#ABCD}).
Try it online!
evil
The relevant code is:
zaeeeawawawawavaeeaaaaamvawvusb

Try it online!
fish
The relevant code is:
s="ABCDEFGHIJKLMNOPQRSTUVWXYZ";0#'...'
[ -z $s ]&&echo ABCDEGHIJKLMNOPQRSTUVWXYZ&&exit;echo `[ $status = 1 ]&&echo \${s/Z/}&&exit;[ \e =~ e ]&&echo \${s/Y/}&&exit;\[ -z \$- \]&&echo ABC\${s#ABCD}&&exit;[ -z \$BASHPID ]&&echo \${s/K/}&&exit;[ -z $_OVM_PATH ]||echo $s|tr -d O;[ -z $_OVM_PATH ]||exit;[[ -n $USER_ID ]]&&echo \${s/M/}||echo \${s/B/}`;'...' #

In fish, variables aren't assigned via the s=... syntax so $s is empty meaning the first conditional is hit, the required string is echoed out and then exit is called.
Try it online!
goruby + --disable=gems
This isn't available on TIO, but is distributed with the official Ruby source and can be compiled (after the normal autoconf and ./configure steps) with make goruby. Tested on version ruby 2.8.0dev (2020-08-24T10:24:07Z master 1eb1add68a) [x86_64-linux]. The relevant code is:
s="ABCDEFGHIJKLMNOPQRSTUVWXYZ";0
0//.../.__id__;begin ~:*&?,;puts s.gsub ?J,"";rescue;begin A;puts s.gsub ?G,"";rescue;puts s.gsub ?R,"";end;end

Haystack
The relevant code is:
"ABCDEFGIJKLMNOPQRSTUVWXYZ"o

which outputs the required string.
Try it online!
Implicit
The relevant code is:
¡72"8:é9:é8++:90+1®;65µ

This pushes  the range of 1..72 and joins the last 8 items on the stack to a string, duplicates the top the stack, increments all codepoints by 9, duplicates the stack again, increments all codepoints in the string by 8, pushes 90 to the stack and concatenates all, reverses the stack, pop off the top 65 elements then prints the stack.
Try it online!
J-uby
The relevant code is:
s="ABCDEFGHIJKLMNOPQRSTUVWXYZ";0
0//.../.__id__;begin ~:*&?,;puts s.gsub ?J,"";rescue;begin A;puts s.gsub ?G,"";rescue;puts s.gsub ?R,"";end;end

This shares the declaration of s with the shells and other Ruby implementations and and .gsubs J from the string before putsing it as long as ~:*&?, doesn't cause an error.
Try it online!
ksh
The relevant code is:
s="ABCDEFGHIJKLMNOPQRSTUVWXYZ";0#'...'
[ -z $s ]&&echo ABCDEGHIJKLMNOPQRSTUVWXYZ&&exit;echo `[ $status = 1 ]&&echo \${s/Z/}&&exit;[ \e =~ e ]&&echo \${s/Y/}&&exit;\[ -z \$- \]&&echo ABC\${s#ABCD}&&exit;[ -z \$BASHPID ]&&echo \${s/K/}&&exit;[ -z $_OVM_PATH ]||echo $s|tr -d O;[ -z $_OVM_PATH ]||exit;[[ -n $USER_ID ]]&&echo \${s/M/}||echo \${s/B/}`;'...' #

$s is set as the other shells and $status is empty, \e doesn't match e, $- is not empty, but $BASHPID is so $s is echoed removing K (${s/K/}).
Try it online!
Ly
The relevant code is:
&p"A""K"R"M""Z"R&o;

which first clears the stack then pushes the Ranges from A-K and M-Z, before &outputting the stack contents and terminating (;).
Try it online!
mksh
The relevant code is:
s="ABCDEFGHIJKLMNOPQRSTUVWXYZ";0#'...'
[ -z $s ]&&echo ABCDEGHIJKLMNOPQRSTUVWXYZ&&exit;echo `[ $status = 1 ]&&echo \${s/Z/}&&exit;[ \e =~ e ]&&echo \${s/Y/}&&exit;\[ -z \$- \]&&echo ABC\${s#ABCD}&&exit;[ -z \$BASHPID ]&&echo \${s/K/}&&exit;[ -z $_OVM_PATH ]||echo $s|tr -d O;[ -z $_OVM_PATH ]||exit;[[ -n $USER_ID ]]&&echo \${s/M/}||echo \${s/B/}`;'...' #

As per the previous shells, the first line sets $s to be the full alphabet in uppercase, so -z $s is false and skipped over. $status is unset, \e is treated as an escape, not a \ and e, $BASHPID is set, $_OVM_PATH is not and $USER_ID is set so M is replaced with the empty string in $s (${s/M/}) and echoed it out. Tested on version 58-1.
Numberwang
The relevant code is the big number as Numberwang is just a transliteration of brainfuck:
194940711909711999999999999940391270919999999999994039127
>+[+[<]>>+<+]>>+++++++++++++[<.+>-]<+>++++++++++++[<.+>-]

There's a minor amount of work to balance 4s and 7s throughout the rest of the code, alongside making sure things appear in the right order, but nothing major. Might be able to save some bytes by moving stuff around here...
Try it online!
OSH
Oh look, another shell! As per the others the relevant code is:
s="ABCDEFGHIJKLMNOPQRSTUVWXYZ";0#'...'
[ -z $s ]&&echo ABCDEGHIJKLMNOPQRSTUVWXYZ&&exit;echo `[ $status = 1 ]&&echo \${s/Z/}&&exit;[ \e =~ e ]&&echo \${s/Y/}&&exit;\[ -z \$- \]&&echo ABC\${s#ABCD}&&exit;[ -z \$BASHPID ]&&echo \${s/K/}&&exit;[ -z $_OVM_PATH ]||echo $s|tr -d O;[ -z $_OVM_PATH ]||exit;[[ -n $USER_ID ]]&&echo \${s/M/}||echo \${s/B/}`;'...' #

The main difference here is that $_OVM_PATH is set in OSH, but not in Bash, so the correct string is echoed using tr to remove the O.
Try it online!
Python 3
The relevant code is:
s="ABCDEFGHIJKLMNOPQRSTUVWXYZ";0
0//1;
try:echo -n;print(s[0:23]+"YZ");
except:print(s[0:15]+s[16:]);"""..."""

This shares the declaration of s with the shells and Rubies and is also shared with xonsh. The code in the try will fail in Python (echo -n), but works in xonsh so the code in the except is called, printing slices of s.
Try it online!
QuadR
The relevant code is:
('Q'⎕R'')⎕A⋄'...'⍵

In QuadR, when the final line contains ⍵ all the preceding lines are patterns to match and the final line is a transformation function. This particular transformation function just takes the alphabet ⎕A and ⎕Replaces 'Q' with '', the rest of the function after the statement separator (⋄) is just to close off all the other strings/comments/regex literals and comment out the end of the function.
Try it online!
Ruby
The relevant code is shared with J-uby and goruby:
s="ABCDEFGHIJKLMNOPQRSTUVWXYZ";0
0//.../.__id__;begin ~:*&?,;puts s.gsub ?J,"";rescue;begin A;puts s.gsub ?G,"";rescue;puts s.gsub ?R,"";end;end

Like the other Rubies, s is shared from the shells but in Ruby here, both the other clauses ~:*&?, and A will raise exceptions so the final statement is executed which replaces R in s with the empty string.
Try it online!
Super Stack!
The relevant code is:
0 65 65 if pop dup dup 83 sub if pop outputascii 0 fi pop 1 add dup 91 sub fi

This pushes 0 and 65 (twice) to the stack, then if (which is "while top of stack is truthy" - non-zero), pops the top element, duplicates the new top element twice, pushes 83 and subtracts it from the next stack item down. Then if top of stack is truthy (e.g. it's not 83 - S), pop it, outputascii, push 0 and terminate with fi (since top of stack is now 0). Finally, pop, push 1, add the two top elements together (increment), duplicate, push 91 and subtract, terminate the loop, which will happen if the last output char was 90 (Z).
Try it online!
TacO
The relevant code is:
@"ABCDEFGHIJKLMNOPQRSUVWXYZ"

Try it online!
Unefunge-98 (PyFunge)
The relevant code is:
"ZYXWVTSRQPONMLKJIHGFEDCBA"8 3*k,q

There are a few commands before this that are executed and push things to the stack, but basically this just pushes the required chars in reverse, then pushes 8 and 3 and multiplies them. The k command repeats the next command TOS (24) + 1 times, outputting the required string and quits.
Try it online!
V (vim) + -v
The relevant code is:
<esc>ggdG¬AZ:s/V//"...

Which first leaves insert mode (<esc>), goes to the first line of text (gg), deletes to the last line (dG), inserts the letters from A to Z (¬AZ), then finally replaces V with the empty string (:s/V//). The rest of the line is commented out (").
Try it online!
Wumpus
The relevant code is:
...#220#1#1;.
..."ZYXVUTSRQPONMLKJIHGFEDCBA"#25&o @

The #220#1#1 pushes 220, 1, 1 to the stack, then ; pops off the last item then calls . which jumps the IP to line 1, char 220 and executes. We need to just because TacO mandates only one @ in the code.
Try it online!
xonsh
The relevant code is:
s="ABCDEFGHIJKLMNOPQRSTUVWXYZ";0
0//1;
try:echo -n;print(s[0:23]+"YZ");
except:print(s[0:15]+s[16:]);"""..."""

xonsh is a Python based shell so the code is shared with Python 3 and uses the same s var as the shells and Rubies. I've used a technique I've used in many polyglots with Ruby to get this code in. 0//1 is integer division and the echo -n works fine since xonsh is a shell so the execution of printing the required substring portion of s with the literal string YZ concatenated, then the rest of the program is a """ string.
yash
The relevant code is:
s="ABCDEFGHIJKLMNOPQRSTUVWXYZ";0#'...'
[ -z $s ]&&echo ABCDEGHIJKLMNOPQRSTUVWXYZ&&exit;echo `[ $status = 1 ]&&echo \${s/Z/}&&exit;[ \e =~ e ]&&echo \${s/Y/}&&exit;\[ -z \$- \]&&echo ABC\${s#ABCD}&&exit;[ -z \$BASHPID ]&&echo \${s/K/}&&exit;[ -z $_OVM_PATH ]||echo $s|tr -d O;[ -z $_OVM_PATH ]||exit;[[ -n $USER_ID ]]&&echo \${s/M/}||echo \${s/B/}`;'...' #

Like the other shells, but in yash, the sequence \e is not an escape sequence and so is just the string \e which matches e so $s is printed substituting Y for the empty string (${s/Y/}).
Try it online!
Zsh + --continueonerror
The relevant code is:
s="ABCDEFGHIJKLMNOPQRSTUVWXYZ";0#'...'
[ -z $s ]&&echo ABCDEGHIJKLMNOPQRSTUVWXYZ&&exit;echo `[ $status = 1 ]&&echo \${s/Z/}&&exit;[ \e =~ e ]&&echo \${s/Y/}&&exit;\[ -z \$- \]&&echo ABC\${s#ABCD}&&exit;[ -z \$BASHPID ]&&echo \${s/K/}&&exit;[ -z $_OVM_PATH ]||echo $s|tr -d O;[ -z $_OVM_PATH ]||exit;[[ -n $USER_ID ]]&&echo \${s/M/}||echo \${s/B/}`;'...' #

Zsh is less tolerant of errors in a script than the other shells and so necessitates the --continueonerror flag. In Zsh $status is also set (in fish too) when a command fails, so if $status is 1, then $s is echoed out, substituting Z for the empty string (${s/Z/}).
Try it online!

Validation suite.


Javascript ES7 49 bytes
a=>a.reduce((c,d,e)=>[c**d,c+d,c-d,c*d,c/d][e%5])

Saved 9 bytes thanks to Dom Hastings, saved another 6 thanks to Leaky Nun
Uses the new exponentiation operator.


Python 2.7, 493 430 bytes

exec("L=['012','345','678','036','147','258','048','246'];L+=[i[::-1]IL];S=sorted;F=lambda t:''.join(str(i)It)\ndef N(x):\n s=' '.join(F(S(i))Ix)\nIL:s=s.replace(i[::2],i[:2]+' '+i[1:])\n return S(set(s.split()))\ndef P(s):\n e=0\nIL:e|=-1<s.find(i[::2])<s.find(i[1])\n return[zip(s[:-1],s[1:]),L][e]\nx=N(input());print[F(i)I__import__('itertools').permutations({iI`x`if i.isdigit()})if x==N(P(F(i)))]".replace('I',' for i in '))

The single line version wraps the program with exec("...".replace('I',' for i in ')) so that all for-loops and generators can be shorted with a single I and saves 15 bytes over this more readable version:

L=['012','345','678','036','147','258','048','246'];L+=[i[::-1]for i in L]
S=sorted;F=lambda t:''.join(str(i)for i in t)
def N(x):
 s=' '.join(F(S(i))for i in x)
 for i in L:s=s.replace(i[::2],i[:2]+' '+i[1:])
 return S(set(s.split()))
def P(s):
 e=0
 for i in L:e|=-1<s.find(i[::2])<s.find(i[1])
 return[zip(s[:-1],s[1:]),L][e]
x=N(input())
print[F(i)for i in __import__('itertools').permutations({i for i in`x`if i.isdigit()})if x==N(P(F(i)))]

The program takes the input in the manner shown (e.g. {(1,4),(3,4),(5,4),(8,5)}) or as a list of string (e.g. ['14','34','54','85']) (or in other python friendly formats) and returns the output as a list of strings. So we technically have an ordered container of ordered containers.

The function N normalizes a pattern so that two patterns can be easily compared. The normalization sorts the pairs denoting edges (so '02' instead of '20'), use string replacement to expand double edges (e.g. '02' becomes '01 12'), splits the edges into a set to remove duplicates, and sorts the result.

The function F flattens tuples of ints/strings to strings, so we can normalize paths produced in different ways.

The list L contains all lines on screen.

We then take each permutation of all digits in the normalized pattern and compute a valid path or L if invalid (which never normalizes to list of pairs like real paths would), or a list of pairs indicating the order nodes are visited if valid. If this normalizes to the same pattern then we have a valid solution and include it in the final list.

The main check needed to validate a permutation as a string s is -1<s.find(i[::2])<s.find(i[1]), which detects an error with a line i. For instance with the line '210' the code detects an error if '20' occurs (i.e. it's index is greater than -1) and '1' occurs after it. We don't have to worry about 1 not occurring because the 1 will show up in the normalized pattern when it wasn't in the input.

NOTE: I know replacing str(i)for i in t with map(str,t) and {i for i in`x`if i.isdigit()} with set('012345678')&set(`x`) would make the original code shorter, but this would still be slightly longer that substituting I.


Python 2, 60 bytes
lambda n:'a'+'n'[:`n`[0]=='8'or`n`[:2]in len(`n`)%3/2*'118']

An anonymous function. Adds an n if either:

The first digit is 8
The first two digits are 11 or 18, and the length is 2 modulo 3.


MATL, 14 bytes

!TM1*Zdl2$Xdl-

This outputs a non-empty column vector of nonzero numbers as truthy, or a vector containing at least a zero entry as falsy.

Try it online!
Verify all test cases. The footer code contains an if branch to test truthyness/falsyness.
Since MATL uses ASCII, the source code is encoded as

[33 84 77 49 42 90 100 108 50 36 88 100 108 45]

which satisfies the requirement.

Explanation

!     % Implicit input. Transpose
TM    % Push input to latest function again
1*    % Multiply by 1 (does nothing, but matches factors)
Zd    % Compute gcd with broadcast: matrix of gcd of all pairs
l     % Push 1
2$    % The next function will use 2 inputs
Xd    % Extract diagonal 1 (i.e. that below the main diagonal) from the matrix
l-    % Subtract 1 from each entry. Implicitly display


Jelly, 12 bytes

ÆRðfạṂ
Ç€M⁼W

Try it online!

How it works

Ç€M⁼W   Main link. Argument: n

Ç€      Map the helper link over [1, ..., n].
  M     Get all indices of the maximum.
    W   Wrap; yield [n].
   ⁼    Test the results to both sides for equality.

ÆRðfạṂ  Helper link. Argument: k

ÆR      Prime range; get all primes in R := [1, ..., k].
  ð     Begin a dyadic chain with arguments R and k.
    ạ   Absolute difference; yield k-p for each p in R.
   f    Filter; keep the q in R such that q = k-p for some p in R.
     Ṃ  Take the minimum.
        This yields 0 if the array is empty.


C, score 2,  747   720  662 bytes

L  [  1  <<  7  ]  ,  *  q  ,  *  r  ,  l  ,  d  ,  i  ,  c  ,  j  ,  s  ,  t  ,  k  =  1  <<  7  ;  h  (  )  {  q  =  s  +  i  +  j  ++  ;  *  q  %  k  &&  !  L  [  *  q  %  k  ]  ++  &&  h  (  ++  c  )  ;  }  g  (  )  {  q  =  s  +  i  ;  *  q  %  k  ?  z  (  k  )  ,  h  (  j  =  c  =  0  )  ,  c  >  d  &&  (  d  =  c  )  &&  (  l  =  i  )  ,  g  (  ++  i  )  :  0  ;  }  f  (  S  ,  T  )  {  s  =  S  ;  l  =  i  =  d  =  0  ;  g  (  t  =  T  )  ;  p  (  i  =  0  )  ;  }  p  (  )  {  q  =  s  +  l  +  i  ;  r  =  t  +  i  ;  i  ++  <  d  ?  p  (  *  r  =  *  q  )  :  (  *  r  =  0  )  ;  }  z  (  i  )  {  L  [  --  i  ]  =  0  ;  i  &&  z  (  i  )  ;  }

Works at least on 32-bit MinGW (with optimizations disabled). Doesn't use a single keyword.

Works apparently on TIO with gcc and clang, too: Try it online! (Thanks @Dennis!)

Call with:

int main()
{
    char str[1024];

    f("Good morning, Green orb!", str);
    puts(str);

    f("fffffffffff", str);
    puts(str);

    f("oiiiiioiiii", str);
    puts(str);

    f("1234567890", str);
    puts(str);

    f("L  [  1  <<  7  ]  ,  *  q  ,  *  r  ,  l  ,  d  ,  i  ,  c  ,  j  ,  s  ,  t  ,  k  =  1  <<  7  ;  h  (  )  {  q  =  s  +  i  +  j  ++  ;  *  q  %  k  &&  !  L  [  *  q  %  k  ]  ++  &&  h  (  ++  c  )  ;  }  g  (  )  {  q  =  s  +  i  ;  *  q  %  k  ?  z  (  k  )  ,  h  (  j  =  c  =  0  )  ,  c  >  d  &&  (  d  =  c  )  &&  (  l  =  i  )  ,  g  (  ++  i  )  :  0  ;  }  f  (  S  ,  T  )  {  s  =  S  ;  l  =  i  =  d  =  0  ;  g  (  t  =  T  )  ;  p  (  i  =  0  )  ;  }  p  (  )  {  q  =  s  +  l  +  i  ;  r  =  t  +  i  ;  i  ++  <  d  ?  p  (  *  r  =  *  q  )  :  (  *  r  =  0  )  ;  }  z  (  i  )  {  L  [  --  i  ]  =  0  ;  i  &&  z  (  i  )  ;  }");
    puts(str);
}

Output:

The code with slightly more readable formatting:

L[1<<7],
*q, *r, l, d, i, c, j, s, t, k=1<<7;

h()
{
    q = s+i+j++;
    *q%k && !L[*q%k]++ && h(++c);
}

g()
{
    q = s+i;
    *q%k ? z(k), h(j=c=0), c>d && (d=c) && (l=i), g(++i) : 0;
}

f(S, T)
{
    s = S;
    l = i = d = 0;
    g(t=T);
    p(i=0);
}

p()
{
    q = s+l+i;
    r = t+i;
    i++<d ? p(*r=*q) : (*r=0);
}

z(i)
{
    L[--i] = 0;
    i && z(i);
}

And this can be used to generate proper spacing to get to the formatting with score 2: Try it online!

C, score 3, 309 bytes

i
,
j
,
l
,
c
,
d
;
f
(
\
c\
\
h\
\
a\
\
r
*
s
)
{
\
f\
\
o\
\
r
\
(
i
=
l
=
d
=
0
;
s
[
i
]
;
c
>
d
&&
(
d
=
c
)
&&
(
l
=
i
)
,
++
i
)
\
f\
\
o\
\
r
(
\
c\
\
h\
\
a\
\
r

L
[
\
1\
\
2\
\
8
\
]
=
{
j
=
c
=
0
}
;
s
[
i
+
j
]
&&
!
L
[
s
[
i
+
j
++
]
]
++
;
++
c
)
;
\
w\
\
r\
\
i\
\
t\
\
e
(
1
,
s
+
l
,
d
)
;
}

Try it online!


Pyth, 34 bytes

.N|!N|&ghNT:tNhNY&gYhN:tNThN:QZ^T5

Test Suite

Uses memoized recursion to keep the runtime down. Defines a 3 input function :, which takes inputs `list suffix, end of increasing sequence, end of decreasing sequence.


Write a program that finds the most occurring paired letter in a string

Bash + GNU coreutils, 133

grep -Eo '([A-Z])\1+'<<<"${1^^}"|cut -c1|sort|uniq -c|sort -rn|while read n l
do((a-n&&a-0))&&exit||echo $l&&a=$n
done|sort|tr -d \\n

Testcases:

$ for t in "Sally's friend Bobby searched for seashells." \
> "Sally's friends Jimmy and Bobby rummaged for seashells." \
> "willless" \
> "Sally's sociable friends Sammy and Bobby searched for fabulous seashells." \
> "11ss11aa"
> do
> ./mostpaired.sh "$t"
> echo
> done
L
LM
LS
L
AS
$


Distance between the Sun and the nth planet

05AB1E, 7 bytes

oxOÌÌT/

Try it online!

Explanation

o          # push 2^input
 x         # pop a and push a, 2*a
  O        # sum stack
   ÌÌ      # add 2 twice
     T/    # divide by 10


Done recursively in Mathematica with no hard limits on the number control points in just three lines:

ctrlPts = {{0, 0}, {1, 1}, {2, 0}, {1, -1}, {0, 0}};
getLines[x_List] := Partition[x, 2, 1];
partLine[{a_, b_}, t_] := t a + (1 - t) b;
f[pts_, t_] := NestList[partLine[#, t] & /@ getLines@# &, pts, Length@pts- 1]

Showing it is more involved than the calculations!:

color[x_] := ColorData[5, "ColorList"][[x[[1]]]]
Animate[Graphics[{PointSize[.03], ,
        MapIndexed[{color@#2, Point/@ #1,Line@#1} &, f[ctrlPts,t]],
        Red, Point@Last@f[ctrlPts, t],
        Line@Flatten[(Last@f[ctrlPts, #]) & /@ Range[0, t, 1/50], 1]}], {t, 0, 1}]

Code dissection (kind of) for the calc part:

getLines[x_List] := Partition[x, 2, 1]; (* Takes a list of points { pt1, pt2, pt...}
                                           as input and returns {{pt1,pt2}, {pt2,pt3} ...}
                                           which are the endpoints for the successive
                                           lines between the input points *)

partLine[{a_, b_}, t_] := t a + (1 - t) b;(* Takes two points and a "time" as input
                                             and calculates
                                             a linear interpolation between them*)

f[pts_, t_] := NestList[partLine[#, t] & /@ getLines@# &, pts, Length@pts- 1]
                                          (* This is where the meat is :)
     Takes a list of n points and a "time" as input.
     Operates recursively on the previous result n-1 times, preserving all the results
     Each time it does the following with the list {pt1, pt2, pt3 ...} received:
           1) Generates a list {{pt1, pt2}, {pt2, pt3}, {pt3, pt4} ...}
           2) For each of those sublists calculate the linear interpolation at time "t",
              thus effectively reducing the number of input points by 1 in each round.
     So the end result is a list of lists resembling:
     {{pt1, pt2, pt3 ...}, {t*pt1+(1-t)*pt2, t*pt2+(1-t)*pt3,..}, {t*pt12+(1-t)*pt23, ..},..}
                             --------------   ---------------
                                  pt12              pt23
     And all those are the points you see in the following image:

With a few more lines you can drag the control points interactively while the animation is running:

Manipulate[
 Animate[Graphics[{
    PointSize[.03], Point@pts,
    MapIndexed[{color@#2, Point /@ #1, Line@#1} &, f[pts, t]],
    Red, Point@Last@f[pts, t], Line@Flatten[(Last@f[pts, #]) & /@ Range[0, t, 1/50], 1]},
   PlotRange -> {{0, 2}, {-1, 1}}], {t, 0, 1}],
  {{pts, ctrlPts}, Locator}]

Here dragging the green point:

BTW, the same code runs in 3D without modifications (For the Mathematica geeks you only have to replace Graphics[] by Graphics3D[] and add a third coordinate to the control points list):

NB:

Of course this kludge isn't needed in Mathematica as there are several primitives for drawing Beziers:

Graphics[{BSplineCurve[ctrlPts], Green, Line[ctrlPts], Red,  Point[ctrlPts]}]


Code golf ABC's: The ASCII Box Challenge

Pyth, 65 51 bytes

juXGhHX@GhHeH@jkQ~hZ{s[+L]0UhQ+R]thQUeQ+L]teQ_UhQ+R]0_UeQ)m*;hQeQ
AQjuXGhHX@GhHeH@jkQ~hZ{s[,L0G,RtGH_,LtHG_,R0H)m*;GH

Try it online!


Python 2, 142 136 135 bytes
-6 bytes thanks to ElPedro
-1 byte thanks to TuukkaX

p=input()
z=p[2].index(1)
m=(p[1][z]-p[1][z+1]<1)*2-1
k=i=0
for b in p[3:]:x=p[2][::m].index(1)+i;k|=1in b[::m][x-2:x+8];i+=1
print 1-k

Try it online! or Verify all test cases
Checking orientation (east/west):

Using z=p[2].index(1) to get the first square on 3rd row (represented by the red square), and then m=(p[1][z]-p[1][z+1]<1)*2-1 to subtract the value on the right (green) from the one on the left (blue), this way all the 4 gliders states that are going to southwest result in 1 (top row in the image), while the ones going to southeast result in 0 or -1.
Then convert : 1 -> -1 and 0,-1 -> 1 to be used on parameter to reverse the lists when dealing with west ones. This way the gliders going southwest are threated the same as the one going southeast.
Glider movement

This is the movement that the glider going southeast do, it has a "ladder" pattern, and the leftmost block on 3rd line is constant to every pattern. Using it as starting point, the surrounding 3 blocks on left and right, and the middle 4 blocks are checked for the presence of 1s (that would be the wall).


Create a programming language that only appears to be unusable (Robbers' thread)

Shuffle, by Liam Noronha

cinpush

main:
    gte Hans 1s Leopold
    jnz Leopold done

    mov 1s Hans

    gte Gertrude Hans Leopold
    jnz Leopold done

    mov Gertrude ShabbySam
    mov Hans Gertrude
    mov ShabbySam Hans

    gte Alberto Gertrude Leopold
    jnz Leopold done

    mov Alberto ShabbySam
    mov Gertrude Alberto
    mov ShabbySam Gertrude

    done:

    mov 10 ShabbySam

    gte 1s ShabbySam Leopold
    jz Leopold undo_u

    mov 30 ShabbySam
    gte 1s ShabbySam Leopold
    jz Leopold undo_d

    undo_r:

        POP!! 1

        "shuffle" f
        "shuffle" f
        "shuffle" b
        "shuffle" b
        "shuffle" l
        "shuffle" f
        "shuffle" f
        "shuffle" b
        "shuffle" b

        jmp end

    undo_u:

        POP!! 1

        "shuffle" f
        "shuffle" f
        "shuffle" f
        "shuffle" b
        "shuffle" b
        "shuffle" b
        "shuffle" l
        "shuffle" l
        "shuffle" l
        "shuffle" f
        "shuffle" b

        jmp end

    undo_d:

        POP!! 1

        "shuffle" f
        "shuffle" b
        "shuffle" l
        "shuffle" f
        "shuffle" f
        "shuffle" f
        "shuffle" b
        "shuffle" b
        "shuffle" b

    end:
    jnz 1s main

print Hans
done!

This was really great fun, thank you Liam! :)

Thanks to Sp3000 for a slight but necessary nudge in the right direction.

How?

Two words: Pocket Cube.

It turns out that the stacks correspond to the faces of a 2x2x2 Rubik's cube as follows:

           ____ ____
          |    |    |
          | 19 | 17 |
          |____U____|
          |    |    |
          | 20 | 18 |
 _________|____|____|____ ____ ____ ____
|    |    |    |    |    |    |    |    |
| 13 | 14 |  1 |  2 |  9 | 10 |  6 |  5 |
|____L____|____F____|____R____|____B____|
|    |    |    |    |    |    |    |    |
| 15 | 16 |  3 |  4 | 11 | 12 |  8 |  7 |
|____|____|____|____|____|____|____|____|
          |    |    |
          | 22 | 24 |
          |____D____|
          |    |    |
          | 21 | 23 |
          |____|____|

Where ULFRBD indicate which face corresponds to up, left, front, right, back, down when the cube is folded properly.

The permutations correspond to rotating any one side by 90 degrees (where the names thankfully match up). It turns out that f, r and d are clockwise rotations (when viewing the face) and r, l and u are counter-clockwise rotations (when viewing the face).

Now the cinpush command operates such that it applies one of the rotations u, d or r (depending on the given value) and then pushes the input value onto the stack in position 1. (And then it repeats doing this for every element in the input.) That means we can reverse this process (to ensure we end up with the correct order of stacks without having to solve an arbitrary Rubik's cube) by repeatedly looking at the stack in position 1, undoing the corresponding permutation and popping the value of that stack (so that next time we see the stack, we get the value underneath).

How do we undo the rotations? Thankfully, we have both f and b at our disposal. If we apply both of them, we rotate the entire cube by 90 degrees. This means we can move the affected side (U, R or D) to L, undo the rotation using one or three ls (depending on the relative direction of l and the rotation performed during the input), and then rotate the cube back to its previous orientation using f and b again.

In particular, each of the rotations performed during input can be undone as follows:

u --> fffbbblllfb
r --> ffbblffbb
d --> fblfffbbb

I'll see if I can come up with some animations to show that this works.

Now this gives us a way to iterate through the entire input once. But with 5 registers, that's all we need:

Alberto is the maximum value encountered so far.
Gertrude is the 2nd largest value encountered so far.
Hans is the 3rd largest value encountered so far.

When we encounter a new value, we bubble it up those three as far as necessary, where we can use ShabbySam as a temporary register for the swaps. That still leaves Leopold which we can use to hold a conditional when making the necessary comparisons.

At the end of the process, we simply print the contents of Hans, which will already hold the 3rd largest value.


Excel, 6 Bytes

=B1-A1

Assuming A is in cell A1 and B is in cell B1


Golf Wars Episode I: The Phantom Lightsabers

HTML/CSS solution, 765 740 541 bytes

The recent refactor uses the :target pseudo-class rather than a <form> and Javascript.

To enter either input, add it to the end of the URL as a target, e.g. test.html#Jedi or test.html#Sith

Here it is again with whitespace and a few comments:

The lightsabers are
 elements with one cell per part (blade/handle) that are unhidden via their id attributes.

The blades are colored with CSS box-shadows and the Jedi lightsabers undergo a transform: rotate().

Pictures or it didn't happen (click for full res):

If you add td{background:#fff}body{background:#000} to the CSS, you'll get a cool dark view.

Tested in Firefox and Chrome (on Linux).  Note that this is not at all standards-compliant, as I was trying to shrink the size as much as possible.

Thanks to @manatwork for border-spacing and :target.


R, 25 bytes

function(x,n)sum(x^(0:n))

Try it online!


Ruby, 114 113 characters

x,y=eval gets
(d=0..10).find{|r|d.find{|c|s=y.sort.combination(c).select{|s|s.reduce(:+)==x-r}.uniq
p s if s[0]}}

Input: a two-element array of the wizard mana and the spell list, formatted a one-line JSON.

Output: a 2D array of the spell lists, formatted as a one-line JSON, or nil if the wizard can cast no spell.

I especially love x,y = eval gets. So dangerous and evil, yet so powerful and simple. Perfect for golfing.

Both sort and uniq are neccessary. Otherwise, this will produce duplicates for input like [4, [1, 3, 1]]. I'm not happy about this.

find is a useful method for control flow. Its return value is not as useful here, though. Length-wise, it comes on par with any?, which return value is even less useful.

Examples:

> [4, [1, 2, 3, 3, 7, 6]]
# [[1, 3]]
> [3, [1, 3, 5, 2, 10]]
# [[3]]
> [8, [4, 1, 9]]
# [[1, 4]]
> [4, [1, 2, 2, 3]]
# [[1, 3], [2, 2]]
> [4, [5, 6, 7]]
# nil


Create a regex to match a given range of integers in a given radix

05AB1E, 17 bytes

ŸεD0‹'-×sÄIB«}'|ý

Try it online!

For some reason I don't seem to be able to replace I with ³.


JavaScript (ES6), 25 bytes

a=>f=n=>a[n]||f(--n-f(n))

An anonymous function that, when called, creates a function f that gives the item at a given index in the sequence.

Please let me know if I misunderstood anything...


Seamless conversion from square to hexagon

Mathematica, 231 211 209 208 201 188 173 bytes

ImageCrop[ImageCollage@{#,#,#,#},e,Left]~SetAlphaChannel~ColorNegate@Graphics[RegularPolygon@6,ImageSize->1.05e,AspectRatio->1]&@ImageResize[#,{3,2}(e=ImageDimensions@#)/4]&

This is an unnamed function which takes an image object and returns an image object:

I don't think there's a lot to explain here, but some details which are of note:

Normally, to tile an image 2x2, you'd use ImageAssemble[{{#,#},{#,#}}], i.e. you hand ImageAssemble a 2x2 matrix with copies of the image. However, there's ImageCollage which is some sort of magic function which tries to arrange a bunch of pictures as "well" as possible (whatever that means... you can even give the individual images weights and stuff). Anyway, it you give it four images of equal size and with equal (or no) weights, it will also arrange them in a 2x2 grid. That allows me to save some bytes for the nesting of the matrix, as well as the function name.
The hexagon is rendered as a single polygon via Graphics. I'm using the built-in RegularPolygon@6, but enforce an aspect ratio of 1 to stretch it as necessary. Unfortunately, Graphics needs a couple of expensive options to avoid padding and such, and it also renders black on white instead of the opposite. The result is fixed with ColorNegate and then attached to the image's original channels with SetAlphaChannel.
Graphics puts a small amount of padding around the hexagon, but we want the alpha hexagon to cover the full size of the cutout. However, SetAlphaChannel can combine images of different sizes, by centring them on top of each other and cropping to the smallest size. That means, instead of manually setting PlotRangePadding->0, we can simply scale up the hexagon image a bit with ImageSize->1.05e (and we need the `ImageSize option anyway).


Haskell, 78 characters

q(r,f)=[(r-b,b)|b<-f[1..r-1],r`gcd`b==1]
d=reverse:id:d
f=((zip[2..]d>>=q)!!)

Sample run:

> map f [0..10]
[(1,1),(2,1),(1,2),(1,3),(3,1),(4,1),(3,2),(2,3),(1,4),(1,5),(5,1)]
> f 100
(17,1)
> f 1000
(3,55)

Edit: (100 → 87) silly me, just testing the gcd is enough!
Edit: (87 → 85) clever trick with cycle and functions to alternate row order
Edit: (85 → 82) replace cycle with the hand-built infinite list d
Edit: (82 → 78) applied gcd identity as suggested by Matías


CJam, 36 35 34 32 30 bytes

riP*30/_60/_C/]2m*::-:mc:mC$3=

The output is in radians. I've verified the solutions for all 86400 possible inputs.

Try it online in the CJam interpreter.

Idea

Since 2π radians is a full lap, each minute/second interval on the clock is 2π/60 = π/30 radians wide.

Thus, dividing the number of seconds by π/30 yields the position of the second hand.

The minute hand moves at one sixtieth of the pace of the second hand, so dividing the result from above by 60 yields the position of the minute hand.

Likewise, dividing the last result by 12 yields the position of the hour hand.

Note that our three quotient from above are not necessarily in the range [0,2π).

By calculating all nine possible differences of the hands' angles, we obtain three 0's (angular distance between a hand and itself) and the six distances between the different hands.

If the closest hands are on a half that does not include 12, one of the differences from above will be the desired output (mod 2π).

However, at 01:55:30 (for example), the hour hand is at an angle of 1.008 rad (57.75 deg) and the minute hand at an angle of 5.812 rad (333.00 deg) from 12, giving a difference of 4.804 rad (275.25 deg). By subtracting this result from a full lap, we obtain the angle measured "in the other direction", which equals 1.479 rad (84.75 rad).

Now, rather than mapping each angle θ in [0,2π) and conditionally subtracting the result from π, we can simply calculate arccos(cos(θ)), since cos is both periodic and even, and arccos always yields a value in [0,π).

Skipping over the three smallest results (all zero), the fourth smallest will be the desired output.

Code

ri                             e# Read an integer from STDIN.
  P*30/                        e# Multiply by π and divide by 30.
       _60/                    e# Divide a copy by 60.
           _C/                 e# Divide a copy by 12.
              ]2m*             e# Push the array of all pairs of quotients.
                  ::-          e# Replace each pair by its difference.
                     :mc       e# Apply cosine to each difference.
                        :mC    e# Apply arccosine to each cosine.
                           $3= e# Sort and select the fourth smallest element.

Alternate version (34 bytes)

rd6*_60/_C/]360f%2m*::m360X$f-+$6=

The output is in degrees and no trigonometric functions are used.

Try it online in the CJam interpreter.


Husk, 15 bytes

!fo§&öεpd´ṘΠdİp

Try it online!

!                 Index into
             İp     the list of primes
 f                    for which:
            d            the digits of p
  o§&                      satisfy both:
     öεpd´Ṙ                  repeated "themselves" times, they form a prime.
           Π                 they are all nonzero.

Erik the Outgolfer saved a byte. Using ṗ instead of εp would save another byte, but that makes the program so slow it times our even for n = 2.


Spanning paths in a tournament on n nodes

C++ (gcc), \$N=10\$

#include <algorithm>
#include <iostream>
#include <vector>
#include <cstring>
#include <ctime>
//a rewrite for vector<int>
struct vi
{
	int l,a[9];
	const int& operator[](int u) const {return a[u];}
	int& operator[](int u) {return a[u];}
};
bool operator < (const vi&a,const vi&b)
{
	for(int i=0;i<a.l;++i) if(a[i]!=b[i]) return a[i]<b[i];
	return 0;
}
bool operator == (const vi&a,const vi&b)
{
	for(int i=0;i<a.l;++i) if(a[i]!=b[i]) return 0;
	return 1;
}
std::vector<vi> g[13];
void dfs(int x,int u,const vi&c,int*w)
{
	++w[u];
	if(c[x]&u)
		for(int o=c[x]&u;o;o^=o&-o)
			dfs(__builtin_ctz(o),u^(o&-o),c,w);
}
void dfsf(int x,int u,const vi&c,int*w)
{
	++w[u];
	if((~c[x])&u)
		for(int o=(~c[x])&u;o;o^=o&-o)
			dfsf(__builtin_ctz(o),u^(o&-o),c,w);
}
int main()
{
	g[0].push_back(vi());
	for(int i=0;i<9;++i)
	{
		for(auto t:g[i])
		{
			int m1=0,m=0;
			for(int j=0,r;j<i;++j)
			{
				if((r=__builtin_popcount(t[j]))>m1) m=0,m1=r;
				if(r==m1) m|=1<<j;
			}
			for(int e=0;e<(1<<i);++e) if(__builtin_popcount(e)>m1
			||(__builtin_popcount(e)==m1&&((e&m)==m))) //ensure the node has the highest degree
			{
				vi u; u.l=i+1;
				for(int p=0;p<=i;++p) //enumerate position
				{
					bool s=(p==0); int x;
					#define yield(l,c) do{if((x=(c))>u[l]&&!s) goto skip; else s|=x<u[l],u[l]=x;}while(0)
					for(int a=0;a<p;++a)
						yield(a,((t[a]>>p)<<(p+1))|(t[a]&((1<<p)-1))|((!((e>>a)&1))<<p));
					yield(p,((e>>p)<<(p+1))|(e&((1<<p)-1)));
					for(int a=p;a<i;++a)
						yield(a+1,((t[a]>>p)<<(p+1))|(t[a]&((1<<p)-1))|((!((e>>a)&1))<<p));
					skip:;
					#undef yield
				}
				g[i+1].push_back(u);
			}
		}
		std::sort(g[i+1].begin(),g[i+1].end());
		g[i+1].erase(std::unique(g[i+1].begin(),g[i+1].end()),g[i+1].end());
		int sz=g[i+1].size();
		std::vector<vi> h(sz);
		#pragma omp parallel for
		for(int w=0;w<sz;++w)
		{
			vi u=g[i+1][w],v;
			auto sw=[&](int x,int y) {
				std::swap(v[x],v[y]);
				for(int s=0;s<v.l;++s)
				{
					int&o=v[s];
					if(((o>>x)^(o>>y))&1) o^=(1<<x)|(1<<y);
				}
			};
			for(int x=0;x<=i;++x)
				for(int y=x+1;y<=i;++y)
				{
					{v=u;sw(x,y);u=std::min(u,v);}
					for(int z=y+1;z<=i;++z)
					{
						{v=u;sw(x,y);sw(y,z);u=std::min(u,v);}
						{v=u;sw(x,y);sw(x,z);u=std::min(u,v);}
						{v=u;sw(y,z);sw(x,z);u=std::min(u,v);}
						{v=u;sw(y,z);sw(x,y);u=std::min(u,v);}
						{v=u;sw(x,z);sw(x,y);u=std::min(u,v);}
						{v=u;sw(x,z);sw(y,z);u=std::min(u,v);}
					}
					{v=u;sw(x,y);u=std::min(u,v);}
				}
			h[w]=u;
		}
		std::sort(h.begin(),h.end());
		h.erase(std::unique(h.begin(),h.end()),h.end());
		g[i+1]=h;
	}
	std::cout<<"pre ("<<clock()*1./CLOCKS_PER_SEC<<"s)\n";
	for(int o=0;o<=9;++o)
	{
		int mx=0;
		const int s=g[o].size();
		#pragma omp parallel for reduction(max:mx)
		for(int t=0;t<s;++t)
		{
			int a[9<<9],b[9<<9];
			memset(a,0,sizeof(int)*(o<<o));
			memset(b,0,sizeof(int)*(o<<o));
			for(int i=0;i<o;++i)
				dfs(i,((1<<o)-1)^(1<<i),g[o][t],a+(i<<o)),
				dfsf(i,((1<<o)-1)^(1<<i),g[o][t],b+(i<<o));
			int r[9][9],c=(1<<o)-1,vx[1<<9];
			for(int p=0;p<o;++p)
			{
				int*A=a+(p<<o),vn=0;
				for(int x=0;x<=c;++x) if(A[x]) vx[vn++]=x;
				for(int q=0;q<o;++q) if(p!=q)
				{
					int*B=b+(q<<o),su=0;
					for(int u=0;u<vn;++u)
						su+=A[vx[u]]*B[c^vx[u]];
					r[p][q]=su;
				}
			}
			int m1=0,m=0;
			for(int j=0,pc;j<o;++j)
			{
				if((pc=__builtin_popcount(g[o][t][j]))>m1) m=0,m1=pc;
				if(pc==m1) m|=1<<j;
			}
			for(int i=0;i<(1<<o);++i) if(__builtin_popcount(i)>m1
			||(__builtin_popcount(i)==m1&&((i&m)==m)))
			{
				int tot=(o==0);
				for(int j=0;j<o;++j)
					if(i&(1<<j))
					{
						tot+=a[j<<o];
						for(int ii=c^i;ii;ii^=ii&-ii)
							tot+=r[j][__builtin_ctz(ii)];
					}
					else tot+=b[j<<o];
				mx=std::max(mx,tot);
			}
		}
		std::cout<<"a("<<o+1<<") = "<<mx<<" ("<<clock()*1./CLOCKS_PER_SEC<<"s)\n";
	}
}

Try it online!

Compile with g++ and -Ofast -funroll-all-loops -ffast-math -fno-stack-protector -march=native -fopenmp. Note that OpenMP is used for parallelism.

Output on my modest computer:

pre (5.217s)
a(1) = 1 (5.218s)
a(2) = 1 (5.218s)
a(3) = 3 (5.219s)
a(4) = 5 (5.221s)
a(5) = 15 (5.221s)
a(6) = 45 (5.222s)
a(7) = 189 (5.223s)
a(8) = 661 (5.225s)
a(9) = 3357 (5.318s)
a(10) = 15745 (18.634s)

The run time may differ a lot because of the use of OpenMP parallelism.

Explanation for \$N=9\$ version:

This code is two-fold. First, it will try to generate all tournament graphs up to isomorphism. Then, it will count the number of hamilton paths on these generated graphs. Adjacency matrices of graphs are stored as arrays of bitmasks (i.e. arrays of uint) for performance reasons.

The second part is relatively easier. We can just use depth-first-search to search for all possible paths and use bitmasks to speed up. The time complexity is \$O(\text{no. of paths in all graphs})\$. It's also possible to use bitmask dynamic programming to do it, with \$O(2^NN^2)\$. The above code used the former while the latter one should be faster when N goes higher. OpenMP parallelization is used to speed it up.

The first part is harder. My approach is incremental: first generating all tournament graphs of \$t\$ nodes, then add one node to be tournament graphs of \$t+1\$ nodes. The trick here is to find an order for adding nodes. Here, instead of adding any node, we restrict the added node to have the greatest degree in the result graph. Therefore, a graph won't be generated too many times.

Graph-isomorphism isn't a easy thing to check too. Therefore we're not really trying to make every graph unique, but to have some degree of tolerance. I have two strategies used here. First, the newest \$t+1\$-th node won't be directly assigned number \$t\$. Instead, we try all the possible numbers from \$0\$ to \$t\$ and take the result graph with the smallest lexicographic order (you can use early-stopping when comparing lexicographic order, so not much overhead). After generating all \$t+1\$-node graphs in this way, we remove the found duplicates by sorting and making them unique. This alone can cut down the number of found graphs for \$N=9\$ to around \$3\times 10^6\$.

The second strategy is that, after found such candidates, we further try to remove duplicates by trying to swap every two nodes and see if we can get a graph with smaller lexicographic order. We then proceed by sorting and making them unique. These two strategies cut down the number of found graphs for \$N=9\$ to around \$10^6\$. (This strategy alone is more powerful than I thought, cutting down to around \$1.1\times 10^6\$)

Explanation for \$N=10\$ version:

Some improvements are made upon the \$N=9\$ version. First, instead of swapping two positions, three positions are swapped to achieve a better result. This successfully cut the number of graphs generated at \$N=9\$ to less than \$5 \times 10^5\$ (~50% improvement). OpenMP parallelization is also introduced here to speed up.

Generating all graphs for \$N=10\$ sounds unfeasible, so instead I try to expand the last step. We still try to add one node for graphs with \$9\$ nodes, but instead of actually generating these new graphs, we can actually count the hamilton paths in them directly!

Consider the relationship between a hamilton path and the new node. The new node can be the first end of the path so we need to find an edge from the new node and continue the path from that node. The new node can also be the second end so we can find an edge to the new node and trace back the path starting from that node.

Of course, the new node can be in the middle of the path. In this case, we can enumerate the two nodes in front and on the back of it. We can then enumerate the subset of nodes both halves of the path contain and then multiply them to get the result.

Notice that the contribution is the same for every pair of nodes adjacent to the new node regardless of other edges to the new node, so we can get that precalculated for every two nodes.

In order to get the number of paths starting and ending on each node covering a certain subset of nodes, we can use depth-first-search from each starting and ending point. (A bitmask dynamic programming could work too, but I guess it's slower)


MATL, 51 bytes
'NS'tPXEii'WE'tPXE648e3i60:qXJZA-JYAtn3-?2:&)wJZAwh

Input format:
'N'
[50 26 23]
'W'
[4 18 29]

Output format:
S
50 26 23
E
175  41  31

Try it online!
Explanation
'NS'tPXE     % Take input (string) implicitly. Exchange 'N' and 'S'
i            % Take input (array)
i'WE'tPXE    % Take input (string). Exchange 'W' and 'E'
648e3        % Push 648000
i            % Take input (array)
60:qXJ       % Push [0 1 ... 59]. Copy into clipboard J
ZA           % Convert second input array from base 60 to decimal
-            % Subtract
JYA          % Convert to base 60
tn3-?        % If length exceeds 3
  2:&)       %   Split into first two elements and then the rest
  w          %   Swap
  JZA        %   Convert from base 60 to decimal
  wh         %   Swap, concatenate


05AB1E, 4 bytes

D1ìH

Explanation

D    Duplicate input
 1ì  Prepend 1
   H Interpret as hexadecimal and implicitly display the value in base 10

If the input has invalid hex characters, H won't push anything so the last value on the stack will be the duplicated input, that's why the program prints its input in case of invalid input.

Try it online!


Perl, 69 bytes

use bigrat;$s+=.5/($s>$ARGV[$_=0]?-++$n:++$p-++$_/2),print for 1..pop

Takes inputs as command line arguments.

Explanation: bigrat enables fractions everywhere for accurate calculations. $s is the current sum of terms, $ARGV[0] is the target value, pop (same as $ARGV[1]) represents the number of terms, $p and $n represent the positive and negative term counts. $_ is either 1 or 0 depending on whether a positive or negative term was added.


Mathematica, 112 103 77 76 66 bytes
Mathematica has a builtin for everything
NumberForm[Interpreter["USState"][#]@"StateSalesTaxRate"#2,{9,2}]&

Takes a state name (any format; abbreviation or full name) and the dollar amount.
Try it on Wolfram Sandbox
Usage
f = NumberForm[Interpreter["USState"][#]@"StateSalesTaxRate"#2,{9,2}]&

f["CA", 1025.00]

61.50

f["miNnNesToA", 123.45]

8.49

Explanation
Interpreter["USState"][#]

Interpret the input as a US State name and generate an Entity.
... @"StateSalesTaxRate"

Get the sales tax rate.
... #2

Multiply that by the second input.
NumberForm[..., {9,2}]

Format the result into a number with 9 digits to the left of the decimal and 2 digits to the right.


><>, Score: 41

'd3*}>a!o-!<<8:5@lI55>@z:5ll55>>q:>|q::|,

and the disjoint program

"r00gr40g44++bb+0p64++?b6+0.22#eW4s )Z

Try it online!

A copy of my answer to the Mutually Exclusive Quine question. A mutually exclusive quine is made of two programs, A and B sharing no common characters, where A outputs B and B outputs A. This means it is a 2-cycle Levenquine and also qualifies for this question. This can act as a baseline for other more inventive answers (though I'm not very confidant this won't go the way of the original Levenquine question).

A more detailed explanation can be found here.


JavaScript (ES6), 58 56 bytes

Saved two bytes thanks to Martin Ender.

let f =
x=>x.replace(/[^!]+/g,eval).replace(/!(\d*)!?\d*/g,"$1")
<input value="2+2!5+5" oninput="try{O.value=f(value)}catch(e){}"><br>
<input id=O value="410" disabled>

Might be improved somehow...


Python 2 535 517 473 468 bytes

Saved 5 bytes thanks to @Easterly Ink!

Input expected to be comma separated (i.e., numArms,armLength,numRots)

Golfed Version

n,l,t=input()
b=[7,3,1,5,0,4,2,6][:n]
w=5+2*l
h=w-3
X=w/2
Y=h/2-1
z=range
d=[0,1,1,1,0,-1,-1,-1]
for j in z(t+1):
 g=[[' 'for _ in[1]*w]for _ in[1]*h];a=j%2;b=[(k+1)%8for k in b];print''
 if a:g[Y][X:X+2]='/\\';g[Y+1][X:X+2]='\\/'
 else:g[Y][X+1]='_';g[Y+1][X:X+3]='|_|'
 for k in b:k=k+8*a;x=[0,2,3,3,2,0,-1,-1,0,1,2,2,1,0,-2,-1][k]+X;y=[0,0,0,2,2,2,1,0,-1,-1,0,1,2,2,0,0][k]+Y;exec"g[y][x]='|/_\\\\'[k%4];x+=d[k%8];y+=d[(k-2)%8];"*l
 for k in z(h):print''.join(g[k])

Ungolfed Version

numArms, armLength, rotAmount = input()

# Choose which arms to draw
arms = [0,4,2,6,1,5,3,7][:numArms]
for i in xrange(rotAmount+1):

    # Set up the grid spacing
    maxWidth = 5 + 2 * armLength
    maxHeight = 2 + 2 * armLength
    grid = [[' ' for x in xrange(maxWidth)] for y in xrange(maxHeight)]

    # Add the base square
    angle = i%2
    startX = len(grid[0])/2
    startY = len(grid)/2 - 1
    if angle:
        grid[startY][startX:startX+2] = '/\\'
        grid[startY+1][startX:startX+2] = '\\/'
    else:
        grid[startY][startX+1] = '_'
        grid[startY+1][startX:startX+3] = '|_|'

    for armNum in arms:
        # Determine where this arm starts
        armIdx = armNum + 8*angle;
        armX = [0,2,3,3,2,0,-1,-1,0,1,2,2,1,0,-2,-1][armIdx] + startX
        armY = [0,0,0,2,2,2,1,0,-1,-1,0,1,2,2,0,0][armIdx] + startY

        # Determine the direction it travels
        d = [0,1,1,1,0,-1,-1,-1]
        dirX = [0,1,1,1,0,-1,-1,-1][armIdx%8]
        dirY = [-1,-1,0,1,1,1,0,-1][(armIdx)%8]
        sym = '|/_\\'[armIdx%4]

        # Draw the arm
        for i in xrange(armLength):
            grid[armY][armX] = sym
            armX += dirX
            armY += dirY

    # Increment which arms to draw next
    arms = [(a+1)%8 for a in arms]
    for i in xrange(len(grid)):
        print ''.join(grid[i])
    print ''

Explanation

Pretty simple when it's broken down. First figure out how big of grid is required, then plot the base square or diamond.

Each arm's starting location, symbol and direction is hardcoded in for each of the 8 possible arms for the square and diamond base. Then, drawing them is easy enough.

To rotate everything, I simply switch between the square and diamond base, then increment each of the arms, rotating them clockwise once.


CJam, 57 54 bytes

{[~]2/{`_'{#{1>W<"\u%04x"fe%s`}{~J}?}f%':f*',*{}s\*}:J

This is a named function that pops a VDF string from the stack and pushes a JSON string in return.

CJam has no JSON built-ins, so the bonus won't be worth it. Since conditionally escaping some characters would be a pain for the same reason, I decided to escape everything.

The result isn't pretty, but it's valid JSON. Try it online in the CJam interpreter.