Python 3, 240 236 bytes

import subprocess as s,itertools as i
def f(S,T,A,N=0):
 while 1:
  for P in i.product(A,repeat=N):
   try:
    P="".join(P);open("a","w").write(P)
    if s.check_output(["py","-3","a"],timeout=T).decode()==S:return P
   except:1
  N+=1

Don't run this. On my computer, at least, I found the program really hard to stop once it started running due to the pop-up windows created per process.
timeouts were only added to subprocess.check_output in Python 3, which is why we're using this rather than Python 2.
Here's an alternative version with a time.sleep that also prints all valid programs found along the way, as well as their corresponding output:
import subprocess as s,itertools as i
import time
def f(S,T,A,N=0):
 while 1:
  for P in i.product(A,repeat=N):
   time.sleep(0.2)
   try:
    P="".join(P);open("a","w").write(P);C=s.check_output(["py","-3","a"],timeout=T).decode()
    print(P,repr(C))
    if C==S:return P
   except:1
  N+=1

The program uses the filename a for each program P to be tested, so if you run this make sure you don't already have a file of that name. Replace ["py","-3","a"] with the appropriate command for your setup (e.g. ["python","a"] or ["python3","a"]).
Feel free to change the sleep duration at your own risk :). Call like f("1\r\n",1,"1()print"), where T is timeout in seconds.
First few lines of output from the tester with the above call:
 ''
1 ''
11 ''
() ''
111 ''
(1) ''
int ''
1111 ''

(If you want to help the program along a bit  you can change P="".join(P) to P="print"+"".join(P))
Since the above programs all have no output, here's the result for f("1\r\n",1,["print","(",")","1"]) (tokens aren't part of the challenge, but I wanted to show what happens):
 ''
print ''
1 ''
() ''
11 ''
print() '\r\n'
(print) ''
(1) ''
111 ''
print(print) '<built-in function print>\r\n'
print(1) '1\r\n'

The return value is the string 'print(1)'.
Finally, just for fun, here's what happens if the alphabet is string.printable, i.e.
0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c

Pastebin link of all valid 0-2 char Python 3 programs


Python 2 - Naive implementation - 224

Well, let's start with "the most naive algorithm" as some kind of reference solution:

import itertools

path = input()
total = input()

with open(path) as f:
    menu = map(lambda l: l.split(':'), f.read().split('\n'))

names, prices = zip(*menu)
prices = map(float, prices)

for i in range(len(menu)):
    for comb in itertools.combinations(range(len(menu)), i):
        if sum(prices[c] for c in comb) == total:
            for i in comb:
                print names[i]

Input:

"data.txt"
68.70

Output:

Burger
Lobster Thermidore
Ice Cream

Complexity:

O(2^N * N)

--> exponential in the number of menu items N (of course)

Edit:

To reflect the new winning criterion I golfed it down quite a bit:

from itertools import*
S=str.split
f,t=S(input())
m=[S(l,':')for l in S(open(f).read(),'\n')]
R=range(len(m))
F=float
for i in R:
 for C in combinations(R,i):
  if sum(F(m[c][1])for c in C)==F(t):
   for j in C:print m[j][0]

The input format changed to data.txt 68.70 (both on one line separated with a whitespace).


MATL, 11 bytes

t"G!Z~Ghu]n

Try it online!

The last test case doesn't run in the online interpreter because of memory limitations, but runs offline in less than 2 seconds on a modern computer.

Explanation

For input of size n, this does the following:

Initiallize result to input.
Repeat n times:

Apply bitwise XOR to all pair of entries from current result and input.
Attach input values to the result.
Deduplicate.

The output is the number of elements of the final result.

Commented code.

t      % Implicit input: row vector. Duplicate
"      % For each (i.e. do as many times as the input size)
  G!   %   Push input as a column vector
  Z~   %   Bitwise XOR with broadcast, i.e. for all pairs of entries of the
       %   two arguments. The first argument is the accumulated result
       %   from the previous iteration, the second is the input vector
  G    %   Push input again
  h    %   Postpend
  u    %   Unique values. Gives a row vector
]      % End
n      % Number of entries. Implicitly display

Example

The intermediate results (steps 2.1 and 2.3) for input [256 259 3] are:

First iteration: [256 259 3] with [256 259 3]: computing all pairs of bitwise-XOR gives the matrix

  0   3 259
  3   0 256
259 256   0

Attaching [256 259 3] and deduplicating

0 3 259 256

Second iteration: current result [0 3 259 256] with [256 259 3]. After deduplicating this again gives

0 3 259 256

Third iteration: again

0 3 259 256

So the output is 4 (number of entries of result).


Underload (stringie), 33 bytes each
((aS(:^):SHello, Permuttions!):^)
(S(Hello, Permutations!)(:::^^S))
((Hello, Permutations!)S(:::^^S))

Try it online!
These are function submissions that input via the argument stack, but output to standard output. (The functions also produce garbage output using the more normal mechanism for function output, but according to our normal I/O rules, we only look in one place.)
Explanations
(aS(:^):SHello, Permuttions!):^
(aS(:^):SHello, Permuttions!)     string literal
                             :    non-destructive
                              ^     eval
 a                                enclose {the string literal} in parens
  S                               print it
   (:^)                           string literal
        S                         print that too
       :                          retaining a copy
         Hello, Permuttions       no-ops
                           !      discard the retained copy

S(Hello, Permutations!)(:::^^S)
S                                 print {function input}
 (Hello, Permutations!)           string literal {2nd return value}
                       (:::^^S)   string literal {1st return value}

(Hello, Permutations!)S(:::^^S)
(Hello, Permutations!)            string literal
                      S           print it
                       (:::^^S)   string literal {return value}

If we weren't exploiting this site's I/O rules, it'd cost one extra byte (along with a little code rearrangement) to output the output we wanted (either to standard output or as the function return value), and delete the output we didn't want. But just leaving the extra characters that we're forced to use in order to make a permutation on the argument stack is very slightly shorter.
The quine is an eval quine: we write most of the program in a string literal and eval it, but we still have the original string literal available (because we made the eval non-destructive) and can print it in addition to running it. (This isn't code reading itself, rather the :^ reads one string and uses it for two different purposes.)


Python - 17 chars

Solely as an expression:

min(B,key=B.count)

Full, standalone program with input and output, 34 chars:

B=input()
print min(B,key=B.count)

edit: What gnibbler said.


Create a Language of The Month answer scraper

05AB1E, 283 282 bytes
žgŽ7?-©ƵÇ+400÷®<т÷(®69-4÷®70-365*•ΘÏF•ºS₂+žf<£`žgт‰0Kθ4ÖOŽª+·*’¸¸.Â‚‹º.ŒŒ/–«?€¼=ƒËŠˆ&€š‚‚=ÿ’žYì.w„†ä_¡¦ε',¡нþ}Ùε’ƒËŠˆ.Â‚‹º.ŒŒ/’žYì©’ÿ…é/ÿ’.w……<h1¡¦ε„><S¡3èy’="/a/’¡1è'"¡н®"ÿa/ÿ"y'†§™’ÜÇ.µÔ/ÿ’¡1è…><"S¡64Sè`®¨ì)}ćнδª}€`ʒнlIlQ}ʒ1è'/¡4èXså]DεƵ=Sè`“- [ÿ](ÿ)€‹ [ÿ]“}»sε32Sè`"[ÿ]:ÿ"}Ù»¶2×ý

Ugh..
No TIO of the full program, because .w is disabled.
Explanation:

Step 1: Get the current year and month, and convert it to a Unix timestamp (using this formula):
žg                     # Push the current year
  Ž7?-                 # Subtract 1900
      ©                # Store it in variable `®` (without popping)
       ƵÇ+             # Add 299
          400÷         # Integer-divide by 400
      ®                # Push year-1900 again from variable `®`
       <               # Subtract 1
        т÷             # Integer-divide by 100
          (            # Negate it
      ®                # Push year-1900 again
       69-             # Subtract 69
          D            # Duplicate it
           4÷          # Integer-divide the copy by 4
          s            # Swap so year-1969 is at the top again
           <           # Subtract 1 to make it year-1970
            365*       # Multiply by 365
•ΘÏF•                  # Push compressed integer 5254545
     º                 # Mirror it to 52545455454525
      S                # Convert it to a list of digits
       ₂+              # Add 26 to each: [31,28,31,30,31,30,31,31,30,31,30,31,28,31]
         žf            # Push the current month
           <           # Subtract it by 1
            £          # Leave that many trailing items in the list
             `         # Pop and push them all separated to the stack
žg                     # Push the current year again
  т‰                   # Divmod by 100: [year//100,year%100]
    0K                 # Remove 0s from this pair
      θ                # Leave the last item
       4Ö              # Check if it's divisible by 4
                       # (this results in 1 for leap years; 0 for non-leap years)
O                      # Sum all values on the stack
 Žª+                   # Push compressed integer 43200
    ·                  # Double it to 86400
     *                 # Multiply the sum by this 86400

Try just this first step online.
Step 2: Use this timestamp to create the stackexchange-API URL, and get the content of this url (which contains the JSON of all answers created this month):
’¸¸.Â‚‹º.ŒŒ/–«?€¼=ƒËŠˆ&€š‚‚=ÿ’
                       # Push dictionary string "api.stackexchange.com/answers?site=codegolf&fromdate=ÿ",
                       # where the `ÿ` is automatically replaced with the timestamp
 žYì                   # Prepend constant "https://"
    .w                 # Browse to this URL, and read its contents as string

Try the first two steps online (without .w).
Step 3: Extract all unique answer-id and question-ids from this JSON:
D                      # Duplicate the JSON
 „†ä_¡                 # Split it on dictionary string "question_"
      s                # Swap so the JSON is at the top again
       „Ž»_¡           # Split it on dictionary string "answer_"
            ‚          # Pair those two lists together
ε                      # Map over the pairs:
 ¦                     #  Remove the first item
  ε                    #  Map over each inner string:
   ',¡                '#   Split it on ","
      н                #   Pop and leave just the first item
       þ               #   Pop and leave just the digits in this string
  }Ù                   #  After the inner map: uniquify the resulting ids
}                      # Close the outer map

Try just this third step with the JSON as input.
Step 4: Convert each question-id to an URL, and get its contents (which is the entire HTML page of a question):
`                      # Pop and push both lists separated to the stack
 U                     # Pop the list of answer-ids and store it in variable `X`
ε                      # Map over the question-ids:
 ’ƒËŠˆ.Â‚‹º.ŒŒ/’       #  Push dictionary string "codegolf.stackexchange.com/"
   žYì                 #  Prepend constant "https://"
      ©                #  Store this string in variable `®` (without popping)
       ’ÿ…é/ÿ’         #  Push dictionary string "ÿ/questions/ÿ",
                       #  where the first `ÿ` is automatically replaced with "https://codegolf.stackexchange.com/"
                       #  and the second `ÿ` is automatically replaced with the current question-id
              .w       #  Browse to this URL, and read its contents as string

Try steps 3 and 4 with JSON input (without .w).
Step 5: For each HTML-content of a question, get a list of its [language_name, answer_url, user_name, user_url, question_name] (this may contain some garbage in the result - i.e. the trailing item, or if an answer contains multiple <h1>-refs, but we'll filter those out later):
…<h1¡                  #  Split the HTML-content on "<h1"
     ¦                 #  Remove the first item
      ε                #  Map over each string:
       „><S¡           #   Split it on both ">" and "<"
            3è         #   Get the fourth item (which is the question name in the first iteration,
                       #   and language name in every other iteration)
       y               #   Push the string again
        ’="/a/’¡      "#   Split it on "="/a/"
                1è     #   Get the second item (which is the trailing answer-id URL portion)
                  '"¡ '#   Split that on '"'
                     н #   Pop and leave the first item
        ®              #   Push "https://codegolf.stackexchange.com/" from variable `®`
         "ÿa/ÿ"        #   Push dictionary string "ÿa/ÿ",
                       #   where the `ÿ` are filled again to create the answer-URL
       y               #   Push the string again
        '†§           '#   Push dictionary string "person"
           ™           #   Titlecase it to "Person"
            ’ÜÇ.µÔ/ÿ’  #   Push dictionary string "schema.org/ÿ",
                       #   where the `ÿ` is replaced with "Person"
             ¡         #   Split the string on that
              1è       #   Get the second item
        …><"S¡        "#   Split that on ">", "<", and '"'
              64Sè     #   Get the seventh and fifth items
                       #   (which are the user name and trailing user URL portion)
                  `    #   Push those separated to the stack
                   ®   #   Push "https://codegolf.stackexchange.com/" again
                    ¨  #   Remove the trailing "/"
                     ì #   Prepend it in front to create the user-URL
       )               #   Wrap all four values into a list
      }ć               #  After the map: extract the first quadruple
        н              #  Pop and push its first item (the question name)
         δ             #  Map over each remaining quadruples
          ª            #   And append the question name as trailing item to each

Try just this fifth step with the HTML as input.
Step 6: Filter this list, so it only contains answers from the earlier list, and only the language that's equal to the input:
ʒ                      #  Filter this list of quintuples by:
 н                     #   Pop and leave its first item (the language name)
  l                    #   Convert it to lowercase
   Il                  #   Get the input in lowercase as well
     Q                 #   And check that both are equal
}ʒ                     #  After the filter: filter once again:
  1è                   #   Get the second item (the answer URL)
    '/¡               '#   Split it on "/"
       4è              #   Leave its fifth item (the answer-id)
         X             #   Push the list of answer-ids from variable `X`
          så           #   And check if the current answer-id is in it
]                      # Close both the filter and outer map

Try just the sixth step with the list of quintuples of the previous step as input.
Step 7: Convert it to the output in the specified format:
 €`                    # After the map over the questions, flatten it one level down
   D                   # Duplicate this list
    ε                  # Map over the quintuplets:
     Ƶ=                #  Push compressed integer 214
       Sè              #  Leave just the third, second, and fifth items
          `            #  Pop and push them separated to the stack
      “- [ÿ](ÿ)€‹ [ÿ]“ #  Push dictionary string "- [ÿ](ÿ) by [ÿ]",
                       #  where the `ÿ` are filled again
    }»                 # After the map: join the strings by newlines
   sε                  # Swap, and map over the quintuplets again:
     32Sè              #  Leave just the fourth and third items
         `             #  Pop and push them separated to the stack
      "[ÿ]:ÿ"          #  Push string "[ÿ]:ÿ",
                       #  where the `ÿ` are filled again
    }»                 # After the map: join the strings by newlines as well
      ¶2×ý             # Then join these two strings with "\n\n" as delimiter
                       # (after which the result is output implicitly)

Try just the sixth and seventh steps with the list of quintuplets of step five as input.
See this 05AB1E tip of mine (sections How to use the dictionary? and How to compress large integers?) to understand how the dictionary strings and compressed integers work.


MATL, 29 26 25 bytes
Thanks to @Adriaan for 3 bytes off!
Q:qG/q1e3YytP+1e6j*ZeYsXG

Here's an example with input 365 366... because today is MATL's first birthday! (and 2016 is a leap year; thanks to @MadPhysicist for the correction).
Or try it in MATL online! (experimental compiler; refresh the page if it doesn't work).

Explanation
Q:q    % Input N implicitly. Push range [0 1 ... N] (row vector)
G/     % Divide by N, element-wise
q      % Subtract 1. This gives NP projected onto the x axis for each mirror element
1e3    % Push 1000. This is NP projected onto the y axis
Yy     % Hypotenuse function: computes distance NP
tP     % Duplicate, reverse. By symmetry, this is the distance SN
+      % Add. This is distance SNP for each mirror element (row vector)
1e6j   % Push 1e6*1i
*      % Multiply
Ze     % Exponential
Ys     % Cumulative sum
XG     % Plot in the complex plane


APL (171 166 162 chars, all bonuses: 999 - 171 166 162  + 20 + 20 + 200 = 1068 1073 1077)

This is the longest golfed APL program I've written so far. This might be slightly cheating, but there's nothing in the question that actually disallows this. What I'm doing is putting all the nodes on a vertical line and drawing the graph as an arc diagram. It is obviously still a graph though.

It still took me a few hours.

V←' '⍴⍨99,⍨2×⍴P←∪,C←(2,⍨2÷⍨⍴G)⍴G←G/⍨⎕A∊⍨G←⍞⋄V[2×⍳⍴P;50]←P⋄M←1⋄G←⍴D←{⍵[⍋⍵]}¨↓P⍳C⋄{V[A B←⍵;L←50+M×⌽⍳G]∘←'-'⋄V[A+⍳B-A;⊃L]∘←'|'⋄V[⍵;⊃L]∘←'+'⋄M×←¯1⋄G-←1}¨2×D[⍒|-/↑D]⋄V

The nodes must be single uppercase letters, so it supports 26 nodes maximum. It can handle crossed lines, and each node can have as many connections as the display will handle.

Example output:

A,B C,A C,D

      +-A--+
      |    |
      +-B  |
           |
        C+-+
         |
        D+

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

          +--A-+-+-+
          |    | | |
          |  B-+ | |
          |      | |
        +-+--C   | |
        |        | |
        |    D---+ |
        |          |
        |    E-----+
        |
        |   +F
        |   |
        +---+G

 T,H E,Q U,I C,K B,R O,W N,F O,X J,U M,P S,O V,E R,T H,E L,A Z,Y D,O G,S

               +---+----------T
               |   |
               |   +-------+--H
               |           |
               |           +--E---------+-------+
               |                        |       |
               |              Q---------+       |
               |                                |
               |     +--------U---------------+ |
               |     |                        | |
               |     +--------I               | |
               |                              | |
               |              C-------+       | |
               |                      |       | |
               |              K-------+       | |
               |                              | |
               |       +------B               | |
               |       |                      | |
               +-------+------R               | |
                                              | |
             +----------------O-----+-----+-+ | |
             |                      |     | | | |
             |                W-----+     | | | |
             |                            | | | |
             |           +----N           | | | |
             |           |                | | | |
             |           +----F           | | | |
             |                            | | | |
             |                X-----------+ | | |
             |                              | | |
             |                J-------------|-+ |
             |                              |   |
             |                M---+         |   |
             |                    |         |   |
             |                P---+         |   |
             |                              |   |
             |   +------------S-------------+   |
             |   |                              |
             |   |            V-----------------+
             |   |
             |   |            L-+
             |   |              |
             |   |            A-+
             |   |
             |   |           +Z
             |   |           |
             |   |           +Y
             |   |
             +---|------------D
                 |
                 +------------G


Python 2, 23 bytes

lambda l:map(l.count,l)

Try it online!


ed, 35 characters

s/[a-zA-Z]*\([a-zA-Z]\)\|./\1/g
p
Q

So, the world ends in ed. As I like to be too literal, I decided to write to write the solution with ed - and apparently it is actually a programming language. It's surprisingly short, even considering many shorter solutions already exist in this thread. It would be nicer if I could use something other than [a-zA-Z], but considering ed isn't a programming language, it's actually good enough.

First, I would like to say this only parses the last line in file. It would be possible to parse more, just type , at beginning of two first lines (this specified "everything" range, as opposed to standard last line range), but that would increase code size to 37 characters.

Now for explanations. The first line does exactly what Perl solution does (except without support for Unicode characters). I haven't copied the Perl solution, I just invented something similar by coincidence.

The second line prints last line, so you could see the output. The third line forces quit - I have to do it, otherwise ed would print ? to remind you that you haven't saved the file.

Now for how to execute it. Well, it's very simple. Just run ed with the file containing test case, while piping my program, like that.

ed -s testcase < program

-s is silent. This prevents ed from outputing ugly file size at beginning. After all, I use it as a script, not editor, so I don't need metadata. If I wouldn't do that, ed would show file size that I couldn't prevent otherwise.


Haskell

Here is a point-free implementation.  No variables, formal parameters, or explicit recursion.  I used lambdabot's @pl ("pointless") refactoring feature quite a bit.

import Data.List
import Control.Applicative
import Control.Monad
import System.Random

shuffle :: [a] -> IO [a]
shuffle = liftM2 (<$>) ((fst .) . foldl' (uncurry ((. flip splitAt) . (.) .
          (`ap` snd) . (. fst) . flip flip tail . (ap .) . flip flip head .
          ((.) .) . (. (++)) . flip . (((.) . (,)) .) . flip (:))) . (,) [])
          (sequence . map (randomRIO . (,) 0 . subtract 1) . reverse .
          enumFromTo 1 . length)

main = print =<< shuffle [1..52]

Here's my test procedure to make sure the numbers were uniformly distributed:

main = print . foldl' (zipWith (+)) (replicate 52 0)
       =<< replicateM 1000 (shuffle [1..52])

Here is the original algorithm:

shuffle :: [a] -> IO [a]
shuffle xs = shuffleWith xs <$>
             sequence [randomRIO (0, i - 1) | i <- reverse [1..length xs]]

shuffleWith :: [a] -> [Int] -> [a]
shuffleWith xs ns = fst $ foldl' f ([], xs) ns where
    f (a,b) n = (x:a, xs++ys) where
        (xs, x:ys) = splitAt n b


Retina 0.8.2, 7 bytes
M`4|5
1

Try it online! Link includes test cases. Outputs 0 for right and 1 for left. Explanation:
M`[45]

The number of 4s and 5s...
1

... must equal 1 if the serve is on the left.


rs, 107 bytes
\t/
(?<!\\)((\*|_){2})((?=\S)(?!\2)(\\\2|.)*?)?(?<=\S)\1/(\n)^^((^^\3))\3
\\(\*|_)/\t
[^\t\n]/
\n/_
\t_?/
(_*)/(^^\1)

Live demo and test cases.
This is a pretty crazy...thing.
The newest test case does not work yet. WIP...
Explanation
\t/

Replace tabs with spaces. They have the same character count, and tabs are used later on as a special character.
(?<!\\)((\*|_){2})((?=\S)(?!\2)(\\\2|.)*?)?(?<=\S)\1/(\n)^^((^^\3))\3

Replace any text of length N that should be bolded
with N newlines followed by the original text.
\\(\*|_)/\t

Replace any occurrences of a delimiter immediately preceded by a slash with a tab. This is to make sure that entries like **a\*** have a character count of 2 instead of 3.
[^\t\n]/

Remove any character that's not a tab or newline.
\n/_

Replace all the newlines with underscores.
\t_?/

Remove any tabs (which represent escaped delimiters), along with any underscores that may follow them. This is related to the above issue of character counts with escaped ending delimiters.
(_*)/(^^\1)

Replace the underscore sequence with its length. This is the character count.


Pyth, 12 10 bytes

!%ys*VQUQs

Try it online

Saved 2 bytes thanks to Mr. Xcoder and Erik the Outgolfer.

Explanation

!%ys*VQUQs
    *VQUQ    Multiply each input by its index.
  ys         Take twice the sum (to handle half-integer positions).
!%       sQ  Check if that's a multiple of the total weight.


Jelly, 2 bytes
Code:
t0

Explanation:
t   # Trim off...
 0  #  zero at both sides

Try it online!


Perl 6, 33 31 bytes

-2 bytes thanks to nwellnhof

{(grep {$^a²~~/$a/},1..*)[$_]}

Try it online!

Explanation:

{                            }  # Anonymous code block that returns
 (                      )[$_]   # The nth index of
  grep {          },1..*        # Filtering from the natural numbers
        $^a²                    # If the square of the number
            ~~/$a/              # Contains the number


Calculate the probability of seeing a landmark when starting at a given point and walking straight in a random direction

Haskell, 65 63

import Data.Complex
(s,l)%d=100*min(asin(d/magnitude(s-l))/pi)1

Use like (xstart:+ystart, xlandmark:+ylandmark) % distance.  Gives result in percent.  Why is it so expensive to load modules in Haskell?!?

Note that there is no if/then/else, pattern matching, etc. in this code, min does the magic.


Pyth, 22 bytes
!}zS+*hzhS,/Q\?-4l@z+w

Try it online.


Python 3, 33 bytes

lambda a,b:a-a*.5**(6048e5/b)>9e3

Explanation:

         6048e5         # number of milliseconds in 1 week
               /b       # half-lifes per week
  a*.5**(        )      # mgs of substance remaining after 1 week
a-                      # mgs of substance decayed after one week
                  >9e3  # return true if more than 9000mgs has decayed in 1 week

Try here


Calculate the longest series of 1's in an integer's binary value

JavaScript (ES6),  33  32 bytes
f=x=>x&(k=x>>1)?f(x&k):k&&1+f(k)

Try it online!

JavaScript (ES6),  41 40 36  34 bytes
Saved 4 bytes thanks to @ThePirateBay
f=x=>(k=x&x/2)?f(k):Math.log2(x)|0

Try it online!
How?
General case x > 0
We recursively AND the input x with x / 2 which progressively reduces the patterns of consecutive set bits until only the rightmost bit of the sequence remains. We keep a copy of the last non-zero value and determine the position of its most significant bit by floor-rounding its base-2 logarithm.
Below are the steps we go through for x = 750 (1011101110 in binary).
    1011101110 --.
,----------------'
'-> 1011101110
AND 0101110111
    ----------
=   0001100110 --.
,----------------'
'-> 0001100110
AND 0000110011
    ----------
=   0000100010 --.  --> output = position of MSB = 5  (0000100010)
,----------------'                                         ^
'-> 0000100010
AND 0000010001
    ----------
=   0000000000

Edge case x = 0
The special case x = 0 immediately leads to Math.log2(0) | 0. The logarithm of 0 evaluates to -Infinity and the binary bitwise OR forces a coercion to a 32-bit integer. In compliance with the specification of the abstract operation ToInt32, this gives the expected 0:

If number is NaN, +0, −0, +∞, or −∞, return
+0


JavaScript ES6, 246 bytes

Still some golfing to be done, but at least it's a solution!

C=a=>new Function("x","return "+a.replace(/(\d)x/g,"$1*x"));n=>{n=n.split("=");t=Math.abs,r=C(n[0]),c=C(n[1]),a=0,i=r(a)-c(a);a++;v=r(a)-c(a);o=t(i)<t(v)?-1:1;for(u=1/0;r(a)!==c(a);)a+=o,e=t(r(a)-c(a)),e>u&&(u=1/0,o/=10),u=Math.min(e,u);return a}

Name the function n=>{n=n.split("=")... to use it.

Hyper-ungolfed:

function solveLinear(equation){
    equation = equation.split("=");
    var abs = Math.abs;
    var LHS = convertToFunction(equation[0]), RHS = convertToFunction(equation[1]);
    var pivot = 0;
    var dir;
    var dir1 = LHS(pivot) - RHS(pivot);
    pivot++;
    var dir2 = LHS(pivot) - RHS(pivot);
    if(abs(dir1)<abs(dir2)) dir = -1;
    else dir = 1;
    var dif, minDif = Infinity;
    while(LHS(pivot) !== RHS(pivot)){
        pivot += dir;
        dif = abs(LHS(pivot) - RHS(pivot));
        if(dif > minDif){
            minDif = Infinity;
            dir /= 10;
        }
        minDif = Math.min(dif, minDif);
        console.log(pivot,dir,dif,minDif);
    }
    return {
        x: pivot,
        LHS: LHS,
        RHS: RHS
    };
}

This uses a pivot approach. (I'm not sure if this is what the algorithm is called, just a name I invented.) It first gathers which direction to search for from zero (i.e., which way the slopes of the two sides of the equations will intersect) and looks for the value. Once it finds a point of minimal difference, it goes to that point and decreases the search increment. This eventually yields as precise of a solution we need.


Calculate the internal angles of a regular polygon with N sides

Perl 6, 8 bytes

π- τ/*

Try it online!

Output in radians. Simple function in WhateverCode notation which computes \$π-τ/n\$. \$τ\$ is the constant tau equaling \$2π\$.


Ruby 1.9, 115 characters

The movement logic is quite similar to Danko's answer.

This version has been tested on Linux only.

p=0
loop{u=(?|+?\s*18+"|
")*8
u[165-21*(7-p%14).abs-(17-p%34).abs]=?*
p+=1
puts"\e[2J",r=?++?-*18+?+,u,r
sleep 0.1}


Brachylog, 4 bytes

fk+?

Try it online!

The predicate succeeds for perfect inputs and fails for imperfect inputs, printing true. or false. if run as a complete program (except on the last test case which takes more than a minute on TIO).

        The input's
f       factors
 k      without the last element
  +     sum to
   ?    the input.


GolfScript

Dear Boss Man.
It came to my attention that my keyboard needs replacement; the keys required  to write the
symbols ~ $ ` . and } are not functioning properly.
It's very difficult to work like this! Please instruct the IT department to exchange the faulty
keyboard as soon as possible.
Sincerely,
Dennis

Try it online!
How it works

 Undefined tokens (e.g., most English words) are noops in GolfScript.

 . ; duplicates the input string and discards the copy.

  ~ $ evaluates the input string and sorts the resulting array.

 ` inspects the array (for pretty printing).

  . and duplicates the output string and discards the copy.

 } is a "super comment" since it is unmatched; everything following it is ignored.


Python 2, 68 67 66 bytes

-1 byte thanks to Mr. Xcoder
-1 byte thanks to ovs

x=input()
for j in x:k=sum(i%j%2for i in x);print(k<len(x)-1)+0**k

Try it online!

Returns 1,0,2 instead 0,1,2.


Pyth - 27 25 bytes
Extremely super slow brute force approach.
K2W<ZQ~K1IqKsf!%KTr1KK~Z1

Trial division to factor, then while loop till length of perfect numbers is enough.
Try it here online.


Mathematica, 164 165 bytes

This is an abomination, but I want someone to share my pain.

StringReplace[f[f@"g"="j"]="g";f[f@"G"="J"]="G";z=IgnoreCase->1>0;#,x:"g"|"j"~~y:"if ":>{f@x,y,"(as in ",RandomChoice@StringCases[#2,f@x~~Except[","]..,z]}<>") ",z]&

Function which expects the first argument # to be the sentence to be (in)corrected and the second argument #2 to a be comma separated string of words.

f[f@"g"="j"]="g";f[f@"G"="J"]="G" defines a function f which takes the letters g, G, j, and J to their appropriate replacements. This is ever so slightly shorter than f@"g"="j";f@"j"="g";f@"G"="J";f@"J"="G".

I also set z equal to IgnoreCase->True since I'll be using it twice.

x:"g"|"j"~~y:"if " is a StringExpression which matches "gif " or "jif ", naming the first letter x and the last three characters y. Since the option z (also known as IgnoreCase->True) is passed to StringReplace, these letters can be in any combination of upper and lower case.

I then replace every such match with

{f@x,y,"(as in ",RandomChoice@StringCases[#2,f@x~~Except[","]..,z]}<>") "

RandomChoice@StringCases[#2,f@x~~Except[","]..,z] randomly selects a word out of the second argument #2 which begins with f[x], again ignoring case because the option z is given.


Bash + GNU utilities, 33 bytes

dc<<<[6000]sL${1/:/ 60*}+dlLx\<Lp

Try it online!

Or try the test suite.

The input string is passed as an argument, and the output is on stdout.

How it works

First bash expands ${1/:/ 60*} by taking argument 1 and replacing the : with 60* (there's a space before the 60 that StackExchange isn't displaying here).  For example, if the input is 01:30, the expansion is 01 60*30.

Also, \< gets used as the character < without its special meaning in the shell.

So what happens is that dc is run with

[6000]sLminutes60*seconds+dlLx<Lp

as its program (where "minutes" and "seconds" refer to the actual two-digit numbers).

This carries out the following operations:

[6000]               Definition of a macro which pushes 6000 on the stack.
sL                   Save the macro in register L.
minutes 60*seconds+  Compute minutes*60+seconds,
                        which is the total number of seconds.
d                    Duplicate the total number of seconds on the stack.
lLx                  Run macro L, which pushes 6000 on the stack.
                     The stack now looks like:
                        #seconds #seconds 6000
                        (top of stack on the right).
<L                   Pop 6000 and #seconds from the stack;
                        if 6000 < #seconds,
                          then run macro L to push 6000 on the stack again.
                     At this point, the item at the top of the stack is:
                        #seconds, if #seconds <= 6000,
                        6000, if #seconds > 6000.
p                    Print the top of the stack.


LeetCode 552: Student Attendance Record II

Tips:

The first argument self can be renamed to something shorter.
Use while n:n-=1 to loop n times
(Python 2 specific) You can use a single tab for the second level of indentation, instead of 2 spaces.
For this problem, it's sufficiently fast to just mod b every loop, instead of having to mod both a and d.
The part a,b,c,d,e,f=... can be broken into a,b,c=...;d,e,f=..., which allows reusing the updated value a=a+b+c
c,e,f can be initialized to 10**9+7 instead of 0 (found by @xnor).

Python 2, 136 134 131 127 125 bytes

class Solution:
 def checkRecord(_,n):
	a=b=d=1;c=e=f=M=10**9+7
	while n:n-=1;a,b,c=a+b+c,a%M,b;d,e,f=a+d+e+f,d,e
	return d%M

Try it online!


Output the simplified Goodstein sequence

Python 2, 77 74 bytes

-3 bytes thanks to Lynn

n=input();b=1
while n:print"+".join(n/b*[`b`]+[`n%b`][:n%b]);n+=n/b-1;b+=1

Try it online!

Easily runs up to n = 100 (though the output is too long for tio fully show).


Jelly,  5  4 bytes

!:RS

Try it online! Or see the test-suite.

How?

When we introduce an \$n^{\text{th}}\$ train it allows:

\$(n-1)!\$ states - by being placed behind none of the \$n-1\$ existing trains and being faster than all of them.
all the previous end states, each in \$n\$ different ways - by being placed behind at least one existing train and being faster than \$[0,n-1]\$ of the \$n-1\$ existing trains

We know \$a(1) = 1\$ so...

n  a(n)
1  1
2  1! + 1*2
3  2! + 1!*3 + 1*2*3
4  3! + 2!*4 + 1!*3*4 + 1*2*3*4
5  4! + 3!*5 + 2!*4*5 + 1!*3*4*5 + 1*2*3*4*5
... etc

Which is:

n  a(n)
1  1
2  1 + 2
3  1*2 + 1* 3 + 2*3
4  1*2*3 + 1*2* 4 + 1* 3*4 + 2*3*4
5  1*2*3*4 + 1*2*3* 5 + 1*2* 4*5 + 1* 3*4*5 + 2*3*4*5
...
n  n!/n + n!/(n-1) + n!/(n-2) + ... + n!/1

Hence the code:

!:RS - integer, n
!    - (n) factorial      n!
  R  - range (n)          [1,...,n-2,n-1,n]
 :   - integer division   [n!/1,...,n!/(n-2),n!/(n-1),n!/n]
   S - sum                a(n)


Python 616
Not particularly efficient, but works in reasonable time for inputs whose results are around 5 or 6 characters. To check a string to see if it matches, it loops through every possible combination of truth/false values for all the variables and makes sure each one agrees. Using this it checks every possible string comprised of the relevant characters (not even necessarily a syntactically correct one).
It actually will print every equivalent expression (of every size) and does not actually ever terminate.
Code:
c=['t','f'];o=['1 ','0 ']
def e(s,v):
 for k in v:s=s.replace(k,v[k])
 return eval(s)
def z(t,p='~/\\() '):
 w=[]
 if p=='':return[t]*(t not in['']+c)
 for s in t.split(p[0]):w.extend(z(s,p[1:]))
 w.sort(key=lambda v:-len(v));return w
def m(v):
 l=list('~\\/()')+v
 for s in l:yield s
 for r in m(v):
    for s in l:yield s+r
def n(x):
 if x<1:yield []
 else:
    for l in n(x-1):
     for b in o:yield[b]+l
t=raw_input();v=z(t)+c;l=len(v)
for s in m(v):
 g=1
 for y in n(l):
    y[-2:]=o;d=dict(zip(v+['/\\','\\/','~'],y+['and ','or ','not ']))
    try:
     if e(s,d)!=e(t,d):g=0
    except:g=0
 if g:print s

Input/Ouput:
> ~(~P /\ ~Q)
Q\/P
P\/Q
...

> P /\ ~P
f
~t
...

> (P \/ Q) /\ P
P
(P)
...


R, 113 100 75 70 68 67 65 59 63 57 bytes

As a statistical, functional programming language, it's not surprising that R is fairly well-suited to this kind of task. The fact that most functions can take vectorized input is really helpful for this problem, as rather than looping over N iterations, we just pass around vectors of size N. Thanks to @Billywob for some suggestions that lead to cutting off 4 bytes. Many thanks to @Primo for patiently explaining to me how my code wasn't working for cases where t > l, which is now fixed.

pryr::f(2*l*N/t/sum(floor(runif(N)+sinpi(runif(N))*l/t)))

Try it online!

Sample output:

N=1000, t=1000, l=500
3.037975

N=10000, t=1000, l=700
3.11943

N=100000, t=1000, l=700
3.140351

Explanation

The problem boils down to determining whether the two x values of the needle are on either side of a parallel line. This has some important consequences:

y-values are irrelevant
The absolute location on the x-axis is irrelevant, only the position relative to the closest parallel lines.

Essentially this is a task in a 1-dimensional space, where we generate a line with length in [0, l] (the angle a determines this length), and then we check to see how many times this length exceeds t. The rough algorithm is then:

Sample x1 values from [0, 1000000]. Since parallel lines occur at every tth point along the x-axis, the relative x-position is x modulo t.
Sample an angle a.
Calculate the x2 position based on a.
Check how many times x1+x2 fits into t, i.e. take the floor of (x1+x2)/t.

Sampling N numbers in [0, 1e6] modulo t is equivalent to simply sampling N numbers in [0, t]. Since (x1+x2)/t is equivalent to x1/t + x2/t, the first step becomes sampling from [0, t]/t, i.e. [0, 1]. Lucky for us, that is the default range for R's runif function, which returns N real numbers from 0 to 1 from a uniform distribution.

                          runif(N)

We repeat this step to generate a, the angle of the needle.

                                         runif(N)

These numbers are is interpreted as a half-turn (i.e. .5 is 90 degrees). (The OP asks for degrees from 1 to 180, but in comments it's clarified that any method is allowed if it is as or more precise.) For an angle θ, sin(θ) gives us the x-axis distance between the ends of the needle. (Normally you'd use the cosine for something like this; but in our case, we are considering the angle θ as being relative to the y-axis, not the x-axis (that is, a value of 0 degrees goes up, not right), and therefore we use the sine, which basically phase-shifts the numbers.) Multiplied by l this gives us the x location of the end of the needle.

                                   sinpi(runif(N))*l

Now we divide by t and add the x1 value. This yields (x1+x2)/t, which is how far the needle protrudes from x1, in terms of number of parallel lines. To get the integer of how many lines were crossed, we take the floor.

                    floor(runif(N)+sinpi(runif(N))*l/t)

We calculate the sum, giving us the count c of how many lines are crossed by needles.

                sum(floor(runif(N)+sinpi(runif(N))*l/t))

The rest of the code is just implementing the formula for approximating pi, that is, (2*l*N)/(t*c). We save some bytes on parentheses by taking advantage of the fact that (2*l*N)/(t*c) == 2*l*N/t/c:

        2*l*N/t/sum(floor(runif(N)+sinpi(runif(N))*l/t))

And the whole thing is wrapped into an anonymous function:

pryr::f(2*l*N/t/sum(floor(runif(N)+sinpi(runif(N))*l/t)))


Convert between Lambda Calculus Notations

Haskell, 211 197 186 bytes

(Saved 10 bytes by using interact as suggested by @Challenger5, and one more by not having a final newline.)

m(')':r)=([],r)
m s|(a,u)<-e s,(b,v)<-m u=(a:b,v)
f s|(a,r)<-m s=(tail(a>>"`"):a>>=id,r)
e('\\':v:_:s)|(a,r)<-f s=('\\':v:a,')':r)
e('(':s)=f s
e(v:s)=([v],s)
main=interact$fst.f.(++")")

Initially I had a function to perform the whole transformation, but now that is inlined into the main function which makes it a complete program. Dealing with a complete program instead of using a function String -> String at the interpreter also avoids the need to type and read double backslashes. The other functions follow the (simplified) pure functional parsing pattern of returning a parsing result and the unparsed rest of the string. f parses a list of expressions (possibly a multiple application) . It uses a helper function m  that also parses a list of expressions and has a list of parses as result. e handles the remaining cases: lambdas, parenthesized expressions, and variables. Instead of generating a parsing tree, we directly generate the desired output.

Try it online!

Using interact ruined clean I/O behaviour. If you don't use the TIO link but run it at the  command line of your computer, you have to make sure that there is no trailing whitespace, it would be treated like a variable. You can do something like echo -n '\f.(\x.xx)\x.f(xx)' | ./prog. Alternatively, you could replace the last line by the previous version main=getLine>>=putStrLn.fst.f.(++")").


JavaScript (ES6),  117  116 bytes
Outputs comma-delimited digits, each digit being expressed as a decimal quantity (e.g. \$19_{20}\$ is \$19\$ and \$21_{20}\$ is \$1,1\$).
b=>(g=n=>n>1?g(n-1)+`
`+((s=n%(b+2>>1)?'':'Fizz',n%(b/3+3.9|0)?s:s+'Buzz')||(g=n=>n?[...g(n/b|0),n%b]:s)(n)):1)(5e3)

Try it online!
(limited to 100 so that TIO's output does not blow up)


C / C++, 79 78 73 bytes

Thanks to @ETHproductions for saving a byte!

int f(int a,int b){int c,d=a*b;for(;a;b=c)c=a,a=b%a;auto e=.5;c=e?d/b:b;}

C calculates the GCD: Try it online!

C++ calculates the LCM: Try it online!

In C, auto e=.5 declares an integer variable with the auto storage class (which is the default), which is then initialized to 0, whereas in C++11 it declares a double, which is initialized to 0.5. So the variable's value will be truthy in C++ and falsy in C.

The function calculates the GCD with Euclid's algorithm, and the LCM by dividing the product of a and b by the GCD.

Omitting the return statement works at least on GCC. The 78 byte solution below should work with any compiler:

int f(int a,int b){int c,d=a*b;for(;a;b=c)c=a,a=b%a;auto e=.5;return e?d/b:b;}


Jelly, 16 14 13 bytes

3 bytes thanks to Erik the Outgolfer.

ḟ⁶ỴV€€sS€ẎsS€

Try it online!


Java (OpenJDK 8), 45 44 bytes

n->{int i=0;for(;++i<n;n-=i);return~-n+i*i;}

Try it online!

-1 byte thanks to @Nevay

After staring at this for a while, I noticed a pattern. Every time we drop n numbers, the next number in the sequence is a perfect square. Seeing this, I mentally broke the sequence into convenient chunks: [[1],[4,5],[9,10,11],...] Basically, the ith chunk starts with i*i, and iterates upwards for i elements.

To find the nth number in this sequence, we want to find first which chunk the number is in, and then which position in the chunk it occupies. We subtract our increment number i from n until n is less than i (which gives us our chunk), and then simply add n-1 to i*i to get the correct position in the chunk.

Example:

n = 8
n > 1? Yes, n = n - 1 = 7
n > 2? Yes, n = n - 2 = 5
n > 3? Yes, n = n - 3 = 2
n > 4? No, result is 4 * 4 + 2 - 1 = 17


GolfScript, 28 / 34 chars

n/:a{|}*{a{.[2$]--}%*$-1=}%$

The 28-character program above assumes that all the input letters are in the same case.  If this is not necessarily so, we can force them into upper case by prepending {95&}% to the code, for a total of 34 chars:

{95&}%n/:a{|}*{a{.[2$]--}%*$-1=}%$

Notes:

For correct operation, the input must include at least one newline.  This will be true for normal text files with newlines at the end of each line, but might not be true if the input consists of just one line with no trailing newline.  This could be fixed at the cost of two extra chars, by prepending n+ to the code.
The uppercasing used in the 34-character version is really crude — it maps lowercase ASCII letters to their uppercase equivalents (and spaces to NULs), but makes a complete mess of numbers and most punctuation.  I'm assuming that the input will not include any such characters.
The 28-character version treats all input characters (except newlines and NULs) equally.  In particular, if the input contains any spaces, some will also appear in the output; conveniently, they will sort before any other printable ASCII characters.  The 34-character version, however, does ignore spaces (because it turns out I can do that without it costing me any extra chars).

Explanation:

The optional {95&}% prefix uppercases the input by zeroing out the sixth bit of the ASCII code of each input byte (95 = 64 + 31 = 10111112).  This maps lowercase ASCII letters to uppercase, spaces to null bytes, and leaves newlines unchanged.
n/ splits the input at newlines, and :a assigns the resulting array into the variable a.  Then {|}* computes the set union of the strings in the array, which (assuming that the array has at least two elements) yields a string containing all the unique (non-newline) characters in the input.
The following { }% loop then iterates over each of these unique characters.  Inside the loop body, the inner loop a{.[2$]--}% iterates over the strings in the array a, removing from each string all characters not equal to the one the outer loop is iterating over.

The inner loop leaves the ASCII code of the current character on the stack, below the filtered array.  We make use of this by repeating the filtered array as many times as indicated by the ASCII code (*) before sorting it ($) and taking the last element (-1=).  In effect, this yields the longest string in the filtered array (as they all consist of repeats of the same character, lexicographic sorting just sorts them by length), except if the character has ASCII code zero, in which case it yields nothing.
Finally, the $ at the end just sorts the output alphabetically.


Pyth, 19 18 bytes

j" ~BOO!~ "cz]OtUz

Thanks to @Jakube for golfing off 1 byte!

Try it online.

How it works

                    (implicit) Store the input in z.
                Uz  Compute [0, ... len(z)-1].
               t    Remove the first element.
              O     Select an integer, pseudo-randomly.
             ]      Wrap it in an array.
           cz       Split the input string at that point.
j" ~BOO!~ "         Join the split string, using " ~BOO!~ " as separator.


Ruby,107
->a,b,n{(-b..b).map{|i|s='..'*b+?.
i%b==0&&(i==0?s[b]=n :s[b+a]=s[b-a]=?o)
i.abs==a&&s[0]=s[-1]=?o
puts s}}

Ungolfed in test program
f=->a,b,n{
  (-b..b).map{|i|                           #iterate from -i to i (lines of grit)
    s='..'*b+?.                             #make a string of 2n+1 .'s
    i%b==0&&(i==0?s[b]=n :s[b+a]=s[b-a]=?o) #if i%b=0 plot the centre character (if i=0) or the o's on the top and bottom rows
    i.abs==a&&s[0]=s[-1]=?o                 #if i.abs=a plot the o's in left and right columns
    puts s                                  #having substituted the .'s with o and centre as necessary, output the current line
  }
}

a=gets.to_i
b=gets.to_i
n=gets.chop
f[a,b,n]


Debunking Stroustrup's debunking of the myth “C++ is for large, complicated, programs only”

Wolfram

This feels like complete cheating

Import["http://www.stroustrup.com/C++.html", "Hyperlinks"]

So just add some honest parsing on top

Cases[
 Import["http://www.stroustrup.com/C++.html", "XMLObject"],
 XMLElement["a", {___, "href" -> link_, ___}, ___] :>
  link /; StringMatchQ[link, RegularExpression["((http://)?www([./#\\+-]\\w*)+)"]]
, Infinity]


Python 2, 43 bytes

f=lambda n,a=0,b=1:a*(2*n<a+b)or f(n,b,a+b)

Try it online!

Iterates through pairs of consecutive Fibonacci numbers (a,b) until it reaches one where the input n is less than their midpoint (a+b)/2, then returns a.

Written as a program (47 bytes):

n=input()
a=b=1
while 2*n>a+b:a,b=b,a+b
print a

Same length:

f=lambda n,a=0,b=1:b/2/n*(b-a)or f(n,b,a+b)


Python 3, 194 bytes

n=int(input())
R=range
w=n//max(i*(i*i<=n>1>n%i)for i in R(1,n))
m=0
for i in R(n):m=m*10+1+7*(abs(i%w*2-w+1)//2*w>i-w)
while any(m%p<1for p in R(2,m)):m+=1
m=str(m)
while m:print(m[:w]);m=m[w:]

Try it online!

too slow for most inputs, especially x > 8

-6 bytes thanks to Jonathan Frech
-98 bytes thanks to Leaky Nun


How many squares are guarded by chess queens?

APL, 40 characters

≢⍸a<∨/(⍳8 8)∘.{∨/⊃=/(⊢,+/,-/)¨⍺⍵}⍸a←'Q'=

⍸a←'Q'= transforms the matrix in a nested vector whose elements are the coordinates of the given queens.

(⊢,+/,-/) returns for every cell: the coordinates, their sum, their difference.

{∨/⊃=/(⊢,+/,-/)¨⍺ ⍵} returns 1 if cells ⍺ & ⍵ share one coordinate, the coordinates sum or the coordinates difference; that is gives 1 if a queen can move orizontally, vertically or diagonally from ⍺ to ⍵.

⍵∘.{∨/⊃=/(⊢,+/,-/)¨⍺⍵}⍳8 8 applies the previous function to each queen and each cell in the chessboard.

∨⌿ returns the boolean matrix of cell reachable from some queens
≢⍸a< counts the cell reachable by the queens and not already occupied by queens.


Convert __DATE__-style string to sortable string

C, 137 184 184 140 120 106 103 characters

Replaced the month name lookup with a magic formula.
The formula (m[1]*4388^m[2]*7)%252 is ascending for month names.
Changed it to nicely return 0, at no cost.
It no longer prints a number. Instead it prints a string, which should sort right.
Implemented supercat's %*s idea, which inserts more spaces for earlier months, along with a function that's descending for month names - (m[1]*29^m[2]+405)%49.

#include<stdio.h>
int main(void){
    char*m=__DATE__"%*.6s\n"+1;
    return!printf(m+6,(*m*29^m[1]+405)%49,m);
}

I thought single digit days are represented as Jan_1_2012 (_ being a space), when in fact it's Jan__1_2012 (extra space). This complicated things, so my previous versions were more complicated:

#include<stdio.h>
int main(void){
    char*m=__DATE__+1,*t=m+m[4]/16;
    return!printf("%s%3d%s\n",t+3,(*m*4388^m[1]*7)%252,t);
}


More fun with gates: Karnaugh simplification

Python, 609 chars

N=input()
M=[[(255,['A']),(3855,['B']),(13107,['C']),(21845,['D'])]]
U=[1]*65536
for f,a in M[0]:U[f]=0
s=lambda x:x if x else''
L=1
B=65535
while all(f-N for f,a in sum(M,[])):
 K={}
 for f,a in M[L-1]:
  if U[f^B]:K[f^B]=[u'ᐂ',u'│']+a;U[f^B]=0
 for i in range((L+1)/2):
  for f,a in M[L-1-i]:
   A=max(len(x)for x in a)
   for g,b in M[i]:
    if U[f&g]|U[f|g]:
     d=[u'├'+u'─'*(A-1)+u'┐']+map(lambda x,y:s(x)+' '*(A-len(s(x)))+s(y),a,b)
     if U[f&g]:K[f&g]=[u'ᗝ']+d;U[f&g]=0
     if U[f|g]:K[f|g]=[u'ᗣ']+d;U[f|g]=0
 M+=[K.items()]
 L+=1
print '\n'.join([a for f,a in sum(M,[])if f==N][0])

Functions are specified by listing their truth table values as a binary input.  The first bit is the output for ABCD=0000, the second bit is the output for ABCD=0001, and the last bit is the output for ABCD=1111.  Does a brute-forceish search for the minimal circuit that computes the function.  It never shares subcomputations, so it will always be a tree.  M[L] contains a list of functions computable with L gates, represented as a pair (function,array of strings) where the function is computable with the circuit drawn by the strings when printed one per line.  To make sure we get the minimum circuit, we run in increasing L order and U keeps track of which functions we've already found a circuit for.

$ echo 0b1110000000000111 | ./gates.py
ᗣ
├───┐
ᐂ   ᗝ
│   ├──┐
ᗣ   ᗝ  A
├──┐├─┐
ᗣ  Aᗣ B
├─┐ ├┐
ᗝ B CD
├┐
CD

I used some awesome Unified Canadian Aboriginal syllabics unicode glyphs for the gates, and box drawing glyphs for the connections.  Yes, you heard right: *Unified Canadian Aboriginal*!  If they don't display correctly in your browser, upgrade your unicode-fu.  (They look awesome in my terminal; they are a bit misaligned on stackexchange.)

Depending on the input, could be fast or could take up to ~1/2 hour.

You might need to add something like # -*- coding: utf-8 -*- to the start of the program if running as a script.


CJam, 13 12 bytes

qN/(f&{,}$W=

Test it here.

Explanation

q     e# Read all input.
N/    e# Split into lines.
(     e# Pull off the keypad buttons.
f&    e# Take the set intersection of each key line with the keypad, preserving the order
      e# order in the key line.
{,}$  e# Sort the results by length.
W=    e# Pick the last (longest) one.


Write program which verifies Erdős–Straus conjecture


Read numbers in the base of the largest digit and write it using underscores

Pyth, 26

JscR).zjd*R\_jsiRKhseSsJJK

Demonstration.

JscR).z
     .z                       Take the input as a list of lines.
  cR)                         Remove all whitespace from each line.
 s                            Combine the lines.
J                             Save the result to J.
                              J is now the list of the string forms of the numbers.
       jd*R\_jsiRKhseSsJJK
                      sJ      Combine J into one string.
                    eS        Find the maximum of that string.
                   s          Convert it to an integer.
                  h           Add one.
                 K            Save to K. K is the base.
               iRK      J     Convert the strings in J to base K.
              s               Add them together.
             j           K    Convert the result back to base K, as a list of ints.
         *R\_                 Map each int in that list to that many underscores.
       jd                     Join on spaces and print.


Moving from JavaScript to Japt

As you may know, Japt is simply a shortened, extended version of JavaScript. I created Japt because I was tired of long property names, like String.fromCharCode(x) and Math.floor(x), and the tediousness of doing things such as creating a range. Here's the bare minimum you need to know when going from JavaScript to Japt:

Japt is a transpiled language; Japt code is transpiled to JavaScript and then run as JS. (I guess you could say compiled, but transpiled sounds more hipster. Disclaimer: I know absolutely nothing about being hipster)
All entries are full programs by default. The input is implicitly parsed, and the first six inputs are put into the variables U, V, W, X, Y, and Z; the full array is stored in N. The result of the last expression is automatically printed.
All uppercase letters are variables, and stay the same when transpiled. Most have preset values, which you can find in the "Variables" section of the Japt docs (at the interpreter).
All lowercase letters are prototype functions, or methods. Japt adds the methods a-z (and à-ÿ) on numbers, strings, and arrays. When you use one of these letters, Japt fills in the . and (; Uc in Japt is equivalent to U.c( in JavaScript, which could mean ceil, charCodeAt, or concat, depending on the type of U. This is where most of Japt's power comes from; you can find full lists of these methods under the "_____ functions" sections of the Japt docs (at the interpreter).
A space represents ), and ) represents )). This is because when I first designed Japt, I wanted to save as many bytes as possible, and that's how I first thought of doing this. (Though Us w n does look better than Us)w)n), IMHO.)
A function is denoted as ABC{...}, where the ABC can be any string of variables. Functions work for the most part as they do in JS, the main difference being the last expression is automatically returned (rather than having to use return or fancy ES6 parentheses).
' denotes a single char string (i.e. 'a is the same as "a"), and # takes the next char-code and becomes that number (#e is the same as 101).
Anything between dollar signs $ stays the same during the transpilation process. You can use this to implement for loops, for example, since Japt doesn't have those, but I would suggest using other methods (such as m on strings and arrays, or o on numbers).
Most other chars commonly used in JS — "", 0-9, (, +, =, etc. — stay the same when transpiled (for the most part, anyway).

And that is all you need to know to write basic Japt code. Achieving maximum golf power in Japt requires more knowledge, but that can be found in other answers.

Here's a basic example. Say you have want to take a string of ASCII characters and replace each with its hexadecimal char code. Here's how you might do that in JavaScript:

U.split("").map(x=>x.charCodeAt(0).toString(16)).join("")

Now to convert to Japt. .split("") in JS is equivalent to q"" in Japt, or even shorter, just q. .join("") is also just q, the difference being that the object is an array instead of a string. .map( is m, .charCodeAt( is c, and .toString( is s. So our Japt code might look like:

Uq mX{Xc0 s16} q

In Japt, though, m works as well on strings as it does on arrays, so we can remove both qs:

UmX{Xc0 s16}

Test it online! As you can see in the "JS code" box, this directly transpiles to:

U.m(function(X){return X.c(0).s(16)})

As you learn to work with Japt, you'll become less and less focused on converting back and forth from JavaScript and be able to code in Japt as its own language. Here's an explanation leaving out the JavaScript portion entirely:

UmX{Xc0 s16}
               // Implicit: U = input string
UmX{       }   // Take U, and replace each character X with the result of this function:
    Xc0        //   Take the char-code at index 0 in X (the first and only one).
        s16    //   Convert this to a hexadecimal string.
               // Implicit: output result of last expression


APL (Dyalog), 36 bytes

{(⊢≡⌊)(⌈/⍎¨⍵/⍨~o)*÷≢⍵/⍨o←⌽⌊\1,2=/⌽⍵}

Try it online!

How?

Almost a poem.

⌽⍵ - reverse the input once,

1,2=/ - get the differences list.

⌊\ - keep only the first group of ones,

⌽ - and flip it over to complete.

o← - assign to o,

~o - switch ones and zero(s),

⍵/⍨ - filter the input with it,

⍎¨ - turn the result into list of each digit,

⌈/ - and get the maximum. (that's A)

⍵/⍨o - filter the input with o unalt(ered),

≢ - and take the length, that would be B.

÷ - get one divided by this result,

* - and take A to that power thee.

⊢≡⌊ - integer?


05AB1E, 12 11 bytes
œε.œJ€.«m}ß

Try it online or verify all test cases or try it online with added debug-lines.
Explanation:

œ            # Get all permutations of the (implicit) input-list
 ε           # Map each permutation to:
  .œ         #  Get all its partitions
    J        #  Join each inner-most list together
     €       #  For each inner list:
      .«     #   Right-reduce it by:
        m    #    Taking the power
         }ß  # After the map: pop and push the flattened minimum
             # (after which it is output implicitly as result)


I text the correct combo of ones and zeros

Pyth, 14 13 bytes

-1 byte thanks to Erik the Outgolfer (z can be removed for implicit input).

sm.[\08.Bd.n'

Explanations

sm.[\08.Bd.n'

            '    # Open the path/URL given as implicit input. Return list of color triples for color images: [(255, 125, 23), ...]
          .n     # Flatten the list
 m     .Bd       # For each element of the list, convert to binary
  .[\08          # Pad with zeros on the left up to 8 characters
s                # Concatenate the list of bytes

Unfortunately, because of safety reasons, that cannot be tested with the online interpreter; you will have to clone Pyth to test it on your own computer.


Haskell, 120 bytes

import Data.Complex
p%a=zipWith(\x y->x-a*y)(p++[0])$0:p
f n=foldl(%)[1][cis(2*pi/fromInteger n)^^k|k<-[1..n],gcd n k<2]

Try it online!

Gives a list of complex floats that has entries like 1.0000000000000078 :+ 3.314015728506092e-14 due to float inacurracy. A direct method of multiplying out to recover the polynomial from its roots.

The fromInteger is a big concession to Haskell's type system. There's got to be a better way. Suggestions are welcome. Dealing with roots of unity symbolically might also work.

Haskell, 127 bytes

(h:t)%q|all(==0)t=[]|1>0=h:zipWith(\x y->x-h*y)t q%q
f n=foldl(%)(1:(0<$[2..n])++[-1])[tail$f k++[0,0..]|k<-[1..n-1],mod n k<1]

Try it online!

No imports.

Uses the formula

Computes Φ_n(x) by dividing the LHS by each of the other terms in the RHS.

The operator % does division on polynomials, relying on the remainder being zero. The divisor is assumed to be monic, and is given without the leading 1, and also with infinite trailing zeroes to avoid truncating when doing zipWith.


Ruby, 275 bytes

n=gets.to_i;p (2.upto(n**(1/3r)).map{|i|(1..n).to_a.permutation(i**3).map{|x|c=eval'x'+".each_slice(#{i}).to_a"*2;[c,c.map(&:transpose),c.transpose.map(&:transpose)].map{|q|q.map{|a|a.map{|b|b.inject(:+)}}.flatten.uniq.length}.inject(:+)==3?1:0}}+[0]).flatten.inject(:+)/48+n

Try it online!

In theory, this works. In practice, since it creates every permutation of the list of possible numbers, it'll take hopelessly large amounts of time and memory for any input more than 13 or so. I haven't taken the time to test it past 12, but it seems no 2×2×2 magic cubes exist for that range, so all it really does is tell you how many 1×1×1 cubes you can make.

I "golfed" it a bit (really just made it hard to read for minimal size reduction returns). I'm sure the size can be reduced quite a bit, though getting it under 100 characters is a pretty tall order.

Ruby 2.4 added .sum, but TIO doesn't support it yet, so this has a few .inject(:+)s.

I'll add a non-golfed version + explanation if requested.


APL (Dyalog Unicode), 28 15 bytes

-13 bytes thanks to ngn!

{3 3⍴5⌽⍵,⍵≥8?8}

Explanation:

{...} A direct function (D-Fn), ⍵ is its right argument.

8?8 deal 8 random numbers from the list 1..8:

      8?8
7 2 1 8 4 6 5 3

⍵≥ is the argument greater or equal to each of them?:

      5 ≥ 7 2 1 8 4 6 5 3
0 1 1 0 1 0 1 1

⍵, prepend the argument to the boolean list:

      5 , 0 1 1 0 1 0 1 1
5 0 1 1 0 1 0 1 1

5⌽ rotate the list 5 positions to the left, so that the argument is in the center:

      5 ⌽ 5 0 1 1 0 1 0 1 1
1 0 1 1 5 0 1 1 0

3 3⍴ reshape the list to a 3x3 matrix:

      3 3 ⍴ 1 0 1 1 5 0 1 1 0
1 0 1
1 5 0
1 1 0

Try it online!

J, 15 bytes

Also many bytes thanks to ngn!

3 3$5|.],]>8?8:

Try it online!


APL (Dyalog Unicode), 60 bytesSBCS

Full program. Prompts for character matrix from stdin. Prints 1 or 0 to stdout. Requires zero-indexing (⎕IO←0) which is default on many systems.

P←{' '0∊⍨s←(×⍨≢⍺)⊃,⍵:1∊⍵⋄s}
1∊⊢⌿{P⌺3 3⊢(⍴⍵)⍴1@0P⌺3,⍵}⍣≡3/3⌿⎕

Try it online! (space characters replaced by ░ for clarity)

The method here is basically to seed fill from the top left corner, but alternating between 1D and 2D seed fill to account for line wrapping and vertical/diagonal motion. Diagonal motion is simple horizontal motion followed by vertical motion, since the cursor sits in between adjacent characters.

The first line defines a helper function P(rocess) which will be called on each neighbourhood.

P←{…} "dfn"; ⍵ is the neighborhood, ⍺ is the number of padded elements for each dimension:

 ,⍵ ravel (flatten) the neighbourhood into a list

 (…)⊃ pick the following element from that:

  ⍺ the paddings per dimension (so a 1 or 2 element list, depending on ⍵ being 1D or 2D)

  ≢ the tally of that (1 or 2)

  ×⍨ the square of that (lit. multiplication selfie; 1 or 4)

 s← assign to s(elf; i.e. the centre of the neighbourhood)

' '0∊⍨ is that a member of [" ",0]?

 : if so:

  1∊⍵ return whether the neighbourhood has a one

 ⋄ else:

  s return s(elf unmodified, i.e. leave as-is for now)

The second line is the main part of the program:

⎕ prompt for evaluated input via the console (stdin)

3⌿ triplicate each row (ensures we have at least 3 — makes no difference to connectivity)

3/ triplicate each column (ensures we have at least 3 — makes no difference to connectivity)

{…}⍣≡ apply this function repeatedly until two successive results are identical (i.e. until stable):

 ,⍵ ravel (flatten) the matrix into a list

 P⌺3 apply P to each neighbourhood of 3 elements

 1@0 replace the current value at position 0 with a 1 (this seeds the top left corner)

 (…)⍴ reshape that into the following shape:

  ⍴⍵ the original shape of the matrix

⊢⌿ get the bottom row (lit. vertical right-reduction)

1∊ is there any 1 there?


Visually Explain the Pythagorean Theorem

Pyth, 35 32 31 30 bytes
j_.ts.i.imm*d\#d+Qs.aQ"+="mk4d

Try it online.


Javascript (E6) 215 (315 - 2*50 bonus) 252

Edit Simplified. Correct bug of 0 missing

Defined as a function, then counting 10 more byte for output using alert()

Important Really this one is not valid according to the rules, because javascript can not handle big numbers. For instance with parameters 2,5 it can't find 2^2^2^2^2 (ie 2^65536). A number this big is 'Infinity' in javascript.

Golfed

F=(n,k,g={})=>{k+=k-1;for (l=i=1;x=i.toString(6),l+=!!x[l],l<k;i++)if(x.split(0).length*2==l+1){for(s=[n,n],p=l;o=x[--p];)
if(-o)b=s.pop(),a=s.pop(),s.push(o<2?a+b:o<3?a-b:o<4?a*b:o<5?a/b:Math.pow(a,b));else s.push(x[p]=n);
r=Math.floor(s.pop());r>=0&isFinite(r)&!isNaN(r)&!g[r]&&(g[r]=x)}return Object.keys(g)};

To be golfed. I have an idea I want to share: use a postfix notation. In postfix any type of expression is made just of values and operators - no parentheses needed.
The postfix notation can be translated to usual algebraic infix notation - but that's out of scope in this challenge.

Usage

alert(F(4,3))

Output 1,2,3,4,5,8,12,16,20,32,64,252,256,260,1024,4096,65536,4294967296,1.3407807929942597e+154

Ungolfed

F=(n, k, g={})=>{
  k += k - 1;
  // Count in base 6 - '0' means Value, '1'..'5' means operators
  // A valid expression starts with Value twice, then n operators intermixed with n-1 Values
  // x: Coded expression, l: Expression length, k Expression limit length from param
  for (l = i = 1; x = i.toString(6), l += !!x[l], l<k; i++)
    if (x.split(0).length*2 == l+1) // check balancing values/operators
    {
      for (s = [n,n], p = l; o = x[--p];) // Calc stack starts with N,N
        if (-o) // If not '0'
          b=s.pop(),a=s.pop(), // Do calc
          s.push(o<2 ? a+b : o<3 ? a-b : o<4 ? a*b : o<5 ? a/b : Math.pow(a,b))
        else // Push value
          s.push(n) //
      r = Math.floor(s.pop()); // Last result in stack
      r >= 0 & isFinite(r) & !isNaN(r) & !g[r] && (g[r]=x) // Put in hashtable avoiding duplicates
    }
  // Uncomment this to see the postfix expression list
  // for (i in g) console.log(i, [n,n,...[...g[i]].reverse().map(v=>v>0?'x+-*/^'[v]:n)])
  return Object.keys(g) // Retust list of hashtable keys
}

First version this is more complicated but maybe easier to follow

Display the postfix expression for each number

F=(n,k)=> {
  var i,l,s;
  var cmd;
  var op='n+-*/^'
  var bag = {}
  function Calc(val,pos,stack)
  {
    while (c = cmd[pos])
    {
        if (c == 0)
        {
            stack.push(n);
            cmd[pos] = n
            pos++
        }
        else
        {
            var b=stack.pop(), a=stack.pop();
            stack.push(c < 2 ? a+b : c < 3 ? a-b : c < 4 ? a*b : c < 5 ? a/b
               : Math.pow(a,b))
            cmd[pos]=op[c]
            pos++
        }
    }
    var res = Math.floor(stack.pop())
    if (res > 0 && isFinite(res) && !isNaN(res) && !bag[res])
    {
       bag[res] = cmd
    }
  }
  k=k+k-3;
  for (i=1;s=i.toString(6), !s[k]; i++)
  {
       l=s.split(0).length;
       if (l+l-1==s.length)
       {
          var cmd = (s+'00').split('').reverse()
          Calc(n, 0, [], cmd.map(c=>op[c]).join(' '))
       }
  }

  for (i in  bag)
  {
    console.log(bag[i],'=', i)
  }
}

Usage

F(4,3)

Output

[4, 4, "/"] = 1
[4, 4, "+", 4, "/"] = 2
[4, 4, 4, "/", "-"] = 3
[4, 4, "-", 4, "+"] = 4
[4, 4, "/", 4, "+"] = 5
[4, 4, "+"] = 8
[4, 4, "+", 4, "+"] = 12
[4, 4, "*"] = 16
[4, 4, "*", 4, "+"] = 20
[4, 4, "+", 4, "*"] = 32
[4, 4, "*", 4, "*"] = 64
[4, 4, "^", 4, "-"] = 252
[4, 4, "^"] = 256
[4, 4, "^", 4, "+"] = 260
[4, 4, "^", 4, "*"] = 1024
[4, 4, "+", 4, "^"] = 4096
[4, 4, "*", 4, "^"] = 65536
[4, 4, "^", 4, "^"] = 4294967296
[4, 4, 4, "^", "^"] = 1.3407807929942597e+154


What are you waiting for? (A mahjong solver)

Python, 312 281 bytes

def W(S):H=lambda C,n=0,t=1:sum([m<C[0]and H([c-s for c in C][:l]+C[l:],n+1,u)for m,s,l,u in(2,3,1,t),(t,2,1,4),(4-5*all(C[:3]),1,3,t)])|H(C[1:],n,t)if C[2:]and max(C)<5else n>4;T=[i+s for s in"mps"for i in"12345678900"];return" ".join(t for t in T if("1"<t)*H(map((S+t).count,T)))

W takes a string as input and returns a string as output.

The small number of tiles (27) makes it fast enough to test if each of them completes the hand.
The problem becomes to check if a hand is valid.
The function uses a simple backtracking algorithm that considers all possible choices of sets and checks if any of them adds up to a complete hand.

Hands are represented as tile histograms, i.e. a list of tile counts (for all the tiles, not only the ones present in the hand.) This makes it easy to both check if we have a certain number of a certain tile, and if we have a sequence of adjacent tiles (padding between tiles of different suits prevent multi-suit sequences.)


Print a specific value in this generated binary matrix

J - 42 38 char

Pretty fast, 100% accurate, and well within the memory constraints.

([{+2&(~:/@#:@#@],~:/\,(p:>:)&#)0:)&<:

The strategy is as follows: we will calculate successive antidiagonals of this matrix, performing a pairwise XOR to move along and adding the current Thue-Morse and prime bits to the ends. We then pull the required digit out of the antidiagonal when we get there.

Explanation by explosion:

(                                 )&<:  NB. decrement each of x and y
     &(                        )        NB. apply the following function...
   +                                    NB. ... (x-1)+(y-1) times...
                                0:      NB. ... starting with a zero:
    2             ~:/\                  NB.   pairwise XOR on the argument
                      ,(p:>:)&#         NB.   append prime bit (is 1+length prime?)
       ~:/@#:@#@],                      NB.   prepend TM bit (XOR of binary)
 [{                                     NB. take the x-th bit (at index x-1)

Usage of this verb is x m y for M(x, y) as specified in the question, where m is the verb.

   5 ([{+2&(~:/@#:@#@],~:/\,(p:>:)&#)0:)&<: 8
0
   m =: ([{+2&(~:/@#:@#@],~:/\,(p:>:)&#)0:)&<:
   1+i.16
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
   m/~ 1+i.16
0 1 1 0 1 0 0 1 1 0 0 1 0 1 1 0
1 0 1 1 0 0 0 1 0 0 0 1 1 0 1 1
1 1 0 1 1 1 1 0 0 0 0 1 0 0 1 0
0 1 1 0 1 0 1 1 1 1 1 0 0 0 1 1
1 0 1 1 0 0 1 0 1 0 1 1 1 1 0 1
0 0 1 0 0 0 1 1 0 0 1 0 1 0 0 1
1 1 0 0 0 0 1 0 0 0 1 1 0 0 0 1
0 1 1 1 1 1 0 0 0 0 1 0 0 0 0 1
0 1 0 1 0 1 1 1 1 1 0 0 0 0 0 1
0 1 1 0 0 1 0 1 0 1 1 1 1 1 1 0
1 0 1 1 1 0 0 1 1 0 1 0 1 0 1 1
0 0 1 0 1 1 1 0 1 1 0 0 1 1 0 1
1 1 0 0 1 0 1 1 0 1 1 1 0 1 1 0
0 1 1 1 0 0 1 0 0 1 0 1 1 0 1 1
0 1 0 1 1 1 0 0 0 1 1 0 1 1 0 1
0 1 1 0 1 0 0 0 0 1 0 0 1 0 0 1

To save keystrokes we don't try to tell if we still need more prime or Thue-Morse bits, so we compute the entire antidiagonal to get the bit we want. However, 8192 m 8192 still runs in less than 0.07 s and about 100 KiB on my modest laptop.


Mathematica 67 bytes

Doesn't hit 8675309 though - not sure of OP's intention on this.

Column@FoldList[NextPrime,2,Flatten@Array[{9,7,8,6,4,1,10}&,12937]]


Pyth, 7 bytes

o%CN258

Try it online!

Convert each string to a number via treating its ASCII codes as a base 256 number, then take that mod 258, and sort. This gives the mapping

['Monday', 49]
['Tuesday', 75]
['Wednesday', 89]
['Thursday', 99]
['Friday', 103]
['Saturday', 125]
['Sunday', 211]

Same length but less fun is

.P1314S

The 1314th permutation of the sorted input in lexicographic order.


There is no simple answer to this question.

GolfScript almost never beats CJam. It has a lot less built-ins than CJam and the overall syntax is a bit more verbose. For example, print and {+}* become
o and :+ in CJam.

The only exceptions are extremely trivial problems where the fact that GolfScript implicitly reads from STDIN is an advantage and the few occasions where block concatenation is useful (example).

With CJam and Pyth, it's a bit more complicated. Both languages can beat the other in particular challenges, although, by my completely unscientific observation, Pyth seems to have the upper hand on more occasions.

A few particular cases where picking one over the other is rather easy:

Choose Pyth if it has a built-in that CJam lacks and significantly simplifies the task.

For example, Pyth has r<iterable>2, which is Python's swapcase(). If that's useful in a challenge (example), it will be hard to beat with CJam.
On occasions, you have to build the output piece by piece. After finishing the program, CJam implicitly prints the entire stack, so you can just dump the pieces and let the interpreter do the rest.

For example, ascii-art challenges are usually won by CJam.
The length of a single built-in may be a decisive factor in a challenge.

Here, Pyth's C, which is shorter than CJam's 256b, was enough to outgolf CJam.

This would be longer in Pyth, partly because trigonometric functions are 3-character built-ins in Pyth and 2-character built-ins in CJam.

To sum it up, there is no single language that will magically make you win all code golf competitions. You haven't even considered APL, J, K, O, Q, TI-BASIC, Retina, Perl, sed and Mathematica, which all have beaten both CJam and Pyth in a few occasions.

You have several options:

Learn Pyth and CJam. Use the one that's more suited for each task.
Learn the one (first) you like better.

Personally, I'm crazy about stack-based languages, which I find much more easier to write and read.
Learn the one suited better for the challenges you enjoy.

ascii-art is your thing? Go with CJam. Nothing beats array-manipulation? Forget about both and learn J.


Corrupting A Binary File By Interpreting It As Text

Perl 5, 62 53 bytes

y/\x80-\xff/\0-\c?/;s/\e(\[.*?[a-z]|.)|[^\t\n -~]//gi

Try it online! No, I don't know how to input nonprinting characters, particularly illegal UTF-8 sequences, into TIO. Edit: Saved 10 bytes thanks to @NahuelFouilleul.


Mathematica, 22 bytes

EvenQ@Log2@Max[#,-2#]&

Try it online! (Using Mathics instead, where this solution also works.)

I tried to find a solution with bitwise operators for a while, and while one definitely exists, I ended up finding something which is probably simpler:

Max[#,-2#] multiplies the input by -2 if it's negative. Multiplying by another factor of -2 doesn't change whether the value is a power of -2 or not. But now all odd powers of -2 have been turned into even powers of -2.
But even powers of -2 are also even powers of 2, so we can use a simple Log2@... and check if the result is an integer (to check whether it's a power of 2). This already saves two bytes over Log[4,...] (another way to look at even powers of -2).
As an added bonus, checking whether a value is an even integer is shorter than just checking whether it's an integer: we can save three more bytes by using EvenQ instead of IntegerQ.


JavaScript (ES6), 25 bytes

x=>y=>((x<3?x:3)+x)*y/2+1
x=>y=>(x<3?x+x:x+3)*y/2+1
x=>y=>(x<3?x:(x+3)/2)*y+1
x=>y=>(x<3?x:x/2+1.5)*y+1

All of these compute the same value; I can't seem to come up with a shorter formulation.

When x is less than 3, you take as much water as you can and walk as far as you can, which is simply x*y+1.

When x is at least 3, you have to start building caches.

From the oasis, you can leave a full bucket at a distance y/2 and return to the oasis. You need 2 buckets to do this, but this is not useful if you only have 2 buckets because you want to be able to fill up 2 buckets when you return to the oasis.

From the oasis, with a bucket at a distance y/2, you can leave a full bucket at a distance y and return to the oasis. You need 3 buckets to do this.

From the oasis, with full buckets at both y and y/2, you can leave a full bucket at a distance 3y/2 and return to the oasis. You need 4 buckets to do this. You then have to leave a full bucket at a distance of y/2 and return to the oasis.

Eventually you can end up with a full bucket at (x-1)y/2. (You cannot leave a full bucket at xy/2 because you would not be able to get back to the oasis, as the round trip is xy, the total capacity of the buckets.)

Using your remaining buckets, you can leave full buckets at (x-3)y/2 ... y or y/2. At this point you simply walk as far as you can, picking up your full buckets as you go. When you reach (x-1)y/2 you still have two full buckets left, allowing you to reach (x+3)y/2.

The extra 1 comes from the quirk in the rules allowing you to walk your last mile without having any water. Although the example shows that you can leave the buckets slightly further away than described above, this actually does not help you walk any further, as you either have to leave less water or drink the water from the bucket as you reach it before you can move on.


Python 2.7 492 bytes (beats.mp3 only)

This answer can identify the beats in beats.mp3, but will not identify all notes on beats2.mp3 or noisy-beats.mp3. After the description of my code, I'll go into detail as to why.

This uses PyDub (https://github.com/jiaaro/pydub) to read in the MP3. All other processing is NumPy.

Golfed Code

Takes a single command line argument with the file name. It will output each beat in ms on a separate line.

import sys
from math import *
from numpy import *
from pydub import AudioSegment
p=square(AudioSegment.from_mp3(sys.argv[1]).set_channels(1).get_array_of_samples())
n=len(p)
t=arange(n)/44.1
h=array([.54-.46*cos(i/477) for i in range(3001)])
p=convolve(p,h, 'same')
d=[p[i]-p[max(0,i-500)] for i in xrange(n)]
e=sort(d)
e=d>e[int(.94*n)]
i=0
while i<n:
 if e[i]:
  u=o=0
  j=i
  while u<2e3:
   u=0 if e[j] else u+1
   #u=(0,u+1)[e[j]]
   o+=e[j]
   j+=1
  if o>500:
   print "%g"%t[argmax(d[i:j])+i]
  i=j
 i+=1

Ungolfed Code

# Import stuff
import sys
from math import *
from numpy import *
from pydub import AudioSegment

# Read in the audio file, convert from stereo to mono
song = AudioSegment.from_mp3(sys.argv[1]).set_channels(1).get_array_of_samples()

# Convert to power by squaring it
signal = square(song)
numSamples = len(signal)

# Create an array with the times stored in ms, instead of samples
times = arange(numSamples)/44.1

# Create a Hamming Window and filter the data with it. This gets rid of a lot of
# high frequency stuff.
h = array([.54-.46*cos(i/477) for i in range(3001)])
signal = convolve(signal,h, 'same') #The same flag gets rid of the time shift from this

# Differentiate the filtered signal to find where the power jumps up.
# To reduce noise from the operation, instead of using the previous sample,
# use the sample 500 samples ago.
diff = [signal[i] - signal[max(0,i-500)] for i in xrange(numSamples)]

# Identify the top 6% of the derivative values as possible beats
ecdf = sort(diff)
exceedsThresh = diff > ecdf[int(.94*numSamples)]

# Actually identify possible peaks
i = 0
while i < numSamples:
 if exceedsThresh[i]:
  underThresh = overThresh = 0
  j=i
  # Keep saving values until 2000 consecutive ones are under the threshold (~50ms)
  while underThresh < 2000:
   underThresh =0 if exceedsThresh[j] else underThresh+1
   overThresh += exceedsThresh[j]
   j += 1
  # If at least 500 of those samples were over the threshold, take the maximum one
  # to be the beat definition
  if overThresh > 500:
   print "%g"%times[argmax(diff[i:j])+i]
  i=j
 i+=1

Why I miss notes on the other files (and why they are incredibly challenging)

My code looks at changes in signal power in order to find the notes. For beats.mp3, this works really well. This spectrogram shows how the power is distributed over time (x axis) and frequency (y axis). My code basically collapses the y axis down to a single line.

Visually, it's really easy to see where the beats are. There's a yellow line that tapers off again and again. I highly encourage you to listen to beats.mp3 while you follow along on the spectrogram to see how it works.

Next I'll go to noisy-beats.mp3 (because that's actually easier than beats2.mp3.
.
Once again, see if you can follow along with recording. Most of the lines are fainter, but still there. However, in some spots, the bottom string is still ringing when the quiet notes start. That makes finding them especially hard, because now, you have to find them by changes in frequency (the y axis) rather than just amplitude.

beats2.mp3 is incredibly challenging. Here's the spectrogram

In the first bit, there some lines, but some notes really bleed over the lines. To reliably identify notes, you'd have to start tracking the pitch of the notes (fundamental and harmonics) and seeing where those change. Once the first bit is working, the second bit is twice as hard as the tempo doubles!

Basically, to reliably identify all of these, I think it takes some fancy note detection code. Seems like this would be a good final project for someone in a DSP class.


Imperative Tampio, 930 bytes

Yöllä on ilot.Olkoon oma ilo uusi yö, jonka iloja ovat ilo"1s",ilo"2s",ilo"2p",ilo"3s",ilo"3p",ilo"3d",ilo"4s",ilo"4p",ilo"4d",ilo"5s",ilo"5p",ilo"4f",ilo"5d",ilo"6s",ilo"6p",ilo"5f",ilo"6d",ilo"7s"ja ilo"7p".Olkoon iso yö uusi yö, jonka iloja ovat 2,2,6,2,6,10,2,6,10,2,6,14,10,2,6,14,10,2 ja 6.Kun iso luku juo ison ilon,iso ilo näyttää oman yön,missä oma yö on oman ilon ensimmäinen ilo ja ujo ilo on ison yön ensimmäinen ilo,jos iso luku on suurempi kuin ujo ilo,niin iso ilo näyttää ujon ilon,iso ilo näyttää ilon" ",oman ilon iloiksi asetetaan oman ilon ilot toisesta alkaen,ison yön iloiksi asetetaan ison yön ilot toisesta alkaen ja iso luku vähennettynä ujolla ilolla juo ison ilon ja,jos iso luku on pienempi tai yhtä suuri kuin ujo ilo,niin iso ilo näyttää ison luvun.Olkoon oma muuttuja uusi muuttuja.Kun iso sivu avautuu,omaan muuttujaan luetaan luku ja oman muuttujan arvo juo ison sivun.

  Yöllä on ilot.Olkoon oma ilo uusi yö, jonka iloja ovat ilo"1s",ilo"2s",ilo"2p",ilo"3s",ilo"3p",ilo"3d",ilo"4s",ilo"4p",ilo"4d",ilo"5s",ilo"5p",ilo"4f",ilo"5d",ilo"6s",ilo"6p",ilo"5f",ilo"6d",ilo"7s"ja ilo"7p".Olkoon iso yö uusi yö, jonka iloja ovat 2,2,6,2,6,10,2,6,10,2,6,14,10,2,6,14,10,2 ja 6.Kun iso luku juo ison ilon,iso ilo näyttää oman yön,missä oma yö on oman ilon ensimmäinen ilo ja ujo ilo on ison yön ensimmäinen ilo,jos iso luku on suurempi kuin ujo ilo,niin iso ilo näyttää ujon ilon,iso ilo näyttää ilon" ",oman ilon iloiksi asetetaan oman ilon ilot toisesta alkaen,ison yön iloiksi asetetaan ison yön ilot toisesta alkaen ja iso luku vähennettynä ujolla ilolla juo ison ilon ja,jos iso luku on pienempi tai yhtä suuri kuin ujo ilo,niin iso ilo näyttää ison luvun.Olkoon oma muuttuja uusi muuttuja.Kun iso sivu avautuu,omaan muuttujaan luetaan luku ja oman muuttujan arvo juo ison sivun.

Online version

It is a very straightforward implementation. In the golfed version I simply replaced the words with short words like ilo, yö, iso, oma, etc.

Ungolfed:

  Listalla on alkiot.

  Olkoon lyhyt orbitaalilista uusi lista, jonka alkioita ovat
      orbitaali "1s",
      orbitaali "2s",
      orbitaali "2p",
      orbitaali "3s",
      orbitaali "3p",
      orbitaali "3d",
      orbitaali "4s",
      orbitaali "4p",
      orbitaali "4d",
      orbitaali "5s",
      orbitaali "5p",
      orbitaali "4f",
      orbitaali "5d",
      orbitaali "6s",
      orbitaali "6p",
      orbitaali "5f",
      orbitaali "6d",
      orbitaali "7s" ja
      orbitaali "7p".

  Olkoon lyhyt maksimilista uusi lista, jonka alkioita ovat
      2,
      2,
      6,
      2,
      6,
      10,
      2,
      6,
      10,
      2,
      6,
      14,
      10,
      2,
      6,
      14,
      10,
      2 ja
      6.

  Kun jaetaan orbitaaleille pienehkö elektronimäärä nykyisellä sivulla,

  nykyinen sivu näyttää nykyisen orbitaalin, missä
      nykyinen orbitaali on lyhyen orbitaalilistan ensimmäinen alkio ja
      nykyinen maksimi on lyhyen maksimilistan ensimmäinen alkio,
  jos pienehkö elektronimäärä on suurempi kuin nykyinen maksimi,
  niin

  nykyinen sivu näyttää nykyisen maksimin,
  nykyinen sivu näyttää välin " ",
  lyhyen orbitaalilistan alkioiksi asetetaan lyhyen orbitaalilistan alkiot toisesta alkaen,
  lyhyen maksimilistan alkioiksi asetetaan lyhyen maksimilistan alkiot toisesta alkaen
  ja  jaetaan orbitaaleille pienehkö elektronimäärä vähennettynä nykyisellä maksimilla nykyisellä sivulla,

  ja, jos pienehkö elektronimäärä on pienempi tai yhtä suuri kuin nykyinen maksimi,

  niin
  nykyinen sivu näyttää pienehkön elektronimäärän.

  Olkoon mukava muuttuja uusi muuttuja.

  Kun nykyinen sivu avautuu,

  mukavaan muuttujaan luetaan luku
  ja  jaetaan orbitaaleille mukavan muuttujan arvo nykyisellä sivulla.

Online version

Translation:

  A list has items.

  Let the short orbital list be a new list, its items are
  the orbital "1s",
  the orbital "2s",
  the orbital "2p",
  the orbital "3s",
  the orbital "3p",
  the orbital "3d",
  the orbital "4s",
  the orbital "4p",
  the orbital "4d",
  the orbital "5s",
  the orbital "5p",
  the orbital "4f",
  the orbital "5d",
  the orbital "6s",
  the orbital "6p",
  the orbital "5f",
  the orbital "6d",
  the orbital "7s" and
  the orbital "7p".

  Let the short maximum list be a new list, its items are
  2,
  2,
  6,
  2,
  6,
  10,
  2,
  6,
  10,
  2,
  6,
  14,
  10,
  2,
  6,
  14,
  10,
  2 and
  6.

  When a small number of electrons is divided to the orbitals at the current page,

  the current page shows the current orbital, where the current orbital is the first item in the short orbital list and the current maximum is the first element in the short maximum list,
  if the small number of electrons is greater than the current maximum,

  the current page shows the current maximum,
  the current page shows the space " ",
  the elements of the short orbital list are set to be the elements of the short orbital list beginning from the second,
  the elements of the short maximum list are set to be the elements of the short maximum list beginning from the second
  and the small number of electrons subtracted by one is divided to the orbitals at the current page,

  and, if the small number of electrons is less than or equal to the current maximum,

  the current page shows the small number or electrons.

  Let the nice variable be a new variable.

  When the current page opens,

  a number is read to the nice variable
  and the value of the nice variable is divided to the orbitals at the current page.

The translation is approximate, I had to change the word order to make the English more natural.


JavaScript (ES6),  103 99 87  86 bytes
Saved 1 byte thanks to @MatthewJensen

s=>Object.values(o=/(\w*=)(\w*)/g,s.replace(o,(s,k,v)=>o[k]=o[k]?o[k]+[,v]:s)).join`&`

Try it online!
Commented
s =>                  // s = query string
  Object.values(      // get the values of ...
    o =               //   ... the object of this regular expression, which is
      /(\w*=)(\w*)/g, //   re-used to store the keys and values of the query
    s.replace(        //   match each key with the '=' sign and the corresponding
      o,              //   value, using the regular expression defined above
      (s, k, v) =>    //   for each matched string s, key k and value v:
        o[k] =        //     update o[k]:
          o[k] ?      //       if it's already defined:
            o[k] +    //         get the current value
            [, v]     //         append a comma, followed by v
          :           //       else:
            s         //         set it to the entire matched string
                      //         (key, '=', first value)
    )                 //   end of replace()
  ).join`&`           // end of Object.values(); join with '&'


JavaScript (ES6), 31 bytes

n=>~-(n*9+4).toPrecision(1)/9|0

Directly computes the lazy value for each n.

Edit: Only works up to 277777778 due to the limitations of JavaScript's integer type. Alternative versions:

n=>((n*9+4).toPrecision(1)-1)/9>>>0

35 bytes, works up to 16666666667.

n=>((n=(n*9+4).toPrecision(1))-n[0])/9

38 bytes, works up to 944444444444443. But that's still some way short of 253 which is 9007199254740992.


Python 2, 58 55 52 49 47 45 bytes
-13 bytes with great contributions from Arnauld (thanks!!!), xnor and xash.
Switched from Python 3 to Python 2 for an extra 2 bytes.
Tried to profit from the overlapping regions. You don't even need a size M, because the sizes of S and L don't have a gap between them. Luckily, the number of X's for S and L can be expressed as a linear integer expression.

lambda h:max(173-h>>2,h/3-60)*'X'+'SL'[h>173]

Try it online!
Just for fun (and for educational purposes) the original 58 bytes submission:

lambda h:(-h+173)//4*'X'+'S'if h<174else(h-180)//3*'X'+'L'


Javascript (ES6) - 446 418 422 420 bytes

Minified:

F=s=>{D=[];z='000000000';N=t=n=i=e=0;s=(z+s.replace(/^([^.]*)$/,'$1.')+z).replace(/~/g,'-').replace(/-?\d/g,s=>((D[n++]=s/1),0));for(;i<n-3;i=j){if(p=D[j=i+1]){if(!e&&p<0){D=D.map(k=>-k);N=~N;p=-p}e=1}d=D[i];x=D[i+2];m=D[i+3];if(p<0){d--;p++;x++;e=j=0}if(p>1){d++;m++;p-=2;e=j=0}if(!d&&p*x==1){d=p;e=j=p=x=0}D[i]=d;D[i+1]=p;D[i+2]=x;D[i+3]=m}return(N?'-':'')+s.replace(/0/g,()=>D[t++]).replace(/^(0(?!\.))+|0+$/g,'')}

Expanded:

F = s => {
    D = [];
    z = '000000000';
    N = t = n = i = e = 0;
    s = (z + s.replace( /^([^.]*)$/, '$1.' ) + z).replace( /~/g, '-' ).
        replace( /-?\d/g, s => ((D[n++]=s/1),0) );

    for( ; i < n-3; i = j ) {
        if( p = D[j = i+1] ) {
            if( !e && p < 0 ) {
                D = D.map( k=>-k );
                N = ~N;
                p = -p;
            }
            e = 1;
        }
        d = D[i];
        x = D[i+2];
        m = D[i+3];

        if( p < 0 ) {
            d--;
            p++;
            x++;
            e = j = 0;
        }
        if( p > 1 ) {
            d++;
            m++;
            p-=2;
            e = j = 0;
        }
        if( !d && p*x == 1 ) {
            d = p;
            e = j = p = x = 0;
        }

        D[i] = d;
        D[i+1] = p;
        D[i+2] = x;
        D[i+3] = m;
    }

    return (N ? '-' : '') + s.replace( /0/g, ()=>D[t++] ).replace( /^(0(?!\.))+|0+$/g, '' );
}

The code produces a function F that performs the specified conversion.

It's a tough problem to golf. Numerous edge cases creep up that prevent simplification of the code. In particular, dealing with negatives is a pain, both in terms of parsing and in terms of logical handling.

I should note that the code only handles a "reasonable range" of inputs. To extend the domain of the function without bound, the number of zeros in z can be increased, and the constant bounding the while( c++ < 99 ) loop can be increased. The range currently supported is already overkill for the supplied test cases.

Sample Outputs

F('1')          1.
F('9')          10010.0101
F('1~3.2~1')    -0.0101
F('0.~1021')    -0.
F('105.~2')     1010.0101
F('~31~5.~1')   -100000.1001

The -0. isn't pretty, but the answer is still correct. I can fix it if necessary.


I used to solve code golf puzzles like you, but then I took an arrow in the knee

Python, 599 chars

import os,sys
from math import*
I=os.read(0,999)
O=[]
h=v=0
for i in I:
 if'#'==i:O+=[(h,v,h+1,v+1),(h+1,v,h,v+1)]
 if'O'==i:O+=[(h,v+1,h-2,v+3)];T=(h,v+5,h-2,v+7)
 if'}'==i:e=h+.5;c=v+.5
 h+=1
 if'\n'==i:v+=1;h=0

def X(K,L):
 A,B,C=K;p=L[0];q=L[2]-p;r=L[1];s=L[3]-r;A,B,C=A*q*q,2*A*p*q+B*q-s,A*p*p+B*p+C-r;d=B*B-4*A*C
 return 0 if d<0 else any(0<x<1 for x in[(sqrt(d)-B)/2/A,(-sqrt(d)-B)/2/A])

R=range(1,999)
for v in R:
 for z in R:
  z*=pi/999;d=v*sin(z)/10;b=-v*cos(z)/10
  K=20/d/d,b/d-40*e/d/d,c+20*e*e/d/d-b*e/d
  if X(K,T)and not any(X(K,x)for x in O):print v/2,z;sys.exit(0)
print'ERROR'

The X(K,L) routine takes a parabola K=(a,b,c) representing y=ax^2+bx+c and a line segment L=(a,b,c,d) representing the segment between (a,b) and (c,d).  Both obstacles (O) and the target (T) are repesented as line segments.  All distances are scaled by a factor of 2.

The example input gives the following trajectory (by default, the minimum velocity one):

  --                             #          --
--                                            -       O
                        #                      -     /|\
                                                -   / | \
            #                                    -    |
                            #                     -   |
                                                   - / \
                                                    -   \

you can reverse R to get the maximum velocity path:

                                 #
-------------                                         O
             -----------#                            /|\
                        --------                    / | \
            #                   -------               |
                            #          -----          |
                                            -----    / \
                                                 -----  \


Python 3, 61 60 59 bytes

lambda s,t="(/<[{}]>\)":[(c+t)[~t.find(c)]for c in s][::-1]

Try it online!

 -1 byte thanks to @xnor.

Changed the lookup string, so that the c in t test is eliminated.

Python 2, 63 bytes

lambda s,b='(/<[{}]>\)':map(dict(zip(b,b[::-1])).get,s,s)[::-1]

Try it online!

-1 byte thanks to @xnor.

Python 3, 65 64 bytes

lambda s,b=b'(/<[{}]>\)':s.translate(dict(zip(b,b[::-1])))[::-1]

Try it online!

Just for fun using idiomatic Python. (More idiomatic would be using str.maketrans, but it's way too long.)

-1 byte for both because the \ in '\)' doesn't need to be escaped.


Make a minimal and maximal 2-digit number from digits of two 3-digit numbers

Husk, 15 14 13 9 bytes
§,▼▲f←ṁP*

Try it online!
Takes two input arrays, outputs pair (min,max).
-1 byte from Dominic Van Essen.
-1 more byte from Dominic Van Essen (after some more struggling).
-4 bytes taking arrays of digits as input.
Explanation
§,▼▲f←ṁP*
        * cartesian product pairs of the inputs
      ṁP  map each to permuations, and flatten the list
    f←    remove elements where first digit is falsy(<10)
§,        create pair with
  ▼▲      minimum and maximum


Python 2, 170 131 112 bytes

def f(C,t=1):i="#".join(C).find("#")+1;return([]<C)*(i<1or(i<t
and f([r[i:]for r in C],t-i))+(i>1)*f(C[1:],i-1))

A function, f, taking the obstacle course as a list of rows, and returning the number of essentially different paths.

Explanation

The basic concept is this:
We choose a certain obstacle, o, such that there are no other obstacles in the box bounding o and the top-left corner.

+--+....
|..|....
+--#<==== o
.....#..
.#......
........

We then consider the two sub-courses to the east and to the south of o.
We only consider either of these sub-courses if o can actually be crossed from a direction that leads to them, that is, crossed from the north to get to the east, and crossed from the west to get to the south.
We solve the problem for each of the selected sub-courses, and return the sum of the results.
These numbers correspond to the number of essentially different paths when crossing o from the left and from the right, respectively,
therefore the two resulting sets of paths are essentially different.
Since there are no obstacles between the starting point and o, there is a path between the starting point and any entry point into each of these regions, and all such paths that lead to the same point are essentially similar, hence the above sum is the complete number of essentially different paths in the entire course.

                               A
_
........       ...|////      |....
........       ...|////      |....
...#....  -->  ...#////  -->  ....
.#....#.       .#..//#/       ..#.
........       ....////       ....

   |                           |
   v                           v
                  B
........       ___
........       .#....#.
___#....  -->  ........  -->   +
/#////#/
////////

Things are slightly complicated by the fact that the obstacle course alone doesn't convey all the information needed.
For example, consider course B in the diagram above.
Taken by itself, we can't determine whether each of the obstacles can be crossed from the north.
If B were the input course, then, since all paths start at the top-left corner, neither obstacle could have been crossed from the north, but, since we can reach B from either side of the left obstacle when crossing o from the east, we should treat this obstacle as though it can be crossed from the north when solving the course; the same doesn't hold for the right obstacle, however, which can't be crossed from this direction.

We convery this extra information by specifying, along with the obstacle course, the number of characters along the first row, starting from the left, that the path can start at.
In the diagram above, this is depcited as the solid line next to each course.
While, technically, we also need to specify the corresponding number of characters along the first column that the path can start at, as in the case of sub-course A, in practice we always selected the highest obstacle, so this information is not required.

The actual selection of o is as follows:
We pretend that each row, other than the last, is followed by an obstacle (i.e., has a # appended to it), and select the first obstacle in the resulting course, in reading order.
For rows (other than the last) that had no obstacle originally, this effectively mean that we skip them (while noting that the path below may start at any character along the top row).
Eventually, we end up with a course that has a single row with no obstacles, for which there is only one possible path.


A list of number modulus their indices in the list

Haskell, 20 bytes

($[1..]).zipWith mod

Try it online!

A trick to flip I learned from a golf of Anders Kaseorg.


Python 2, 104

def f(L,k,d=1):
 M=[];p=L[0]
 for x in L:M+=range(p+d,x,d);p=x
 return M[k:]and f(L,k,d+1)or sorted(L+M)

Tries different maximum increments d, starting from 1 and counting up. Fills in gaps of each pair (p,x) of successive elements by taking every d'th number in the gap. If M is longer than the quota allows, recurses to try a higher d. Otherwise, returns a list of the added and original elements, sorted.

This does all the test cases without delay on my machine.