CJam, -20
COUNTErREVOLUTIONARIES],

Outputs the nth element in the sequence A010861.
COUNTE                      e# push values of six preinitialized variables
      r                     e# read a token of input
       REVOLUTIONARIES      e# push values of 15 other preinitialized variables
                      ]     e# wrap whole stack in array
                       ,    e# get length

Removing a character from the word results in a completely different sequence A010860. There is a quite interesting relationship between the two sequences: at every index n, A010860(n) is coprime to A010861(n)! There must be some deep mathematical reason behind this.
Try it here.


MATL, 51*0.9 = 45.9 54 57 58 63 bytes

Thanks to Dennis for removing 3 bytes!

'%i To %i'j0h!3'PDFTS'tkXc=s4:Hh*sSPYD3MdXK?kK0<?Xk

An empty input string is represented in the online compiler as a single newline character.

EDIT (June 8, 2016): The link below includes a modification as per release 18.1.0 of the language (move he first 3 right before Xc)

Try it online!

I bet on the Broncos.

Explanation

The scores are detected using a single letter, either upper or lowercase (uppercase is shown in the following):

P for XP (1 point)
D for XD (2 points)
F for FG (3 points) and for FCK (3 points)
T for TD (6 points)
S for S (2 points)

Each of these five letters corresponds uniquely to a score event except that

F is reused for FG and FCK, which have the same score. Thanks to @Dennis for this!
D will detect both TD and XD. So T will be assigned 4 points instead of 6 to compensate.

The ordering PDFTS, saves a few bytes when defining the number array that specifies the points: [1,2,3,4,2].

Each event is detected by the presence of one of the above letters in uppercase or lowercase. The comparison is done in three dimensions: input string length (N) × number of teams (2) × number of detected score events (5). Extensive use is made of broadcasting, which is the automatic expansion of an array along a singleton dimension to match the size of a larger array.

'%i To %i'  % string with format specifiers for two integers
j0h         % input string. Attach 0 so it's never empty. Gives string of length N>0
!           % transpose into char array of size N×1
3           % number literal
'PDFTS'     % characters to detect the five combined types of score
tk          % duplicate and convert to lowercase
Xc          % concatenate along the third dimension to produce a 1×5×2 array
=           % test for equality with broadcast. Gives N×5×2 array
s           % sum along 1st dim. Gives 1×5×2 array
4:Hh        % array [1,2,3,4,2] to compute the total score. Size 1×5(×1)
*           % multiply with broadcast. Gives 1×5×2 array
s           % sum along 2nd dim. Gives 1×1×2 array with the two scores
SP          % sort in reverse order along 3rd dim
YD          % sprintf. Gives output string with "To"
3M          % push array with the two scores again
dXK         % difference along 3rd dim. Gives a number. Copy to clipboard K
?           % is it non-zero? If so we need to make either lowercase or uppercase
  k         %   make (tentatively) lowercase
  K0<       %   did the uppercase team win?
  ?         %   if so...
    Xk      %     make uppercase
            % implicitly end the two if's and display string


Accumulator, Python

Let's get this party started! My submission should work both on Python 2 and Python 3.

import sys

inputs = [(i, x[0], int(x[1:])) for (i, x) in enumerate(sys.argv[1].split())]

own_nodes = sorted([(s,i) for (i,o,s) in inputs if o == 'F'])
targets = sorted([(s,i) for (i,o,s) in inputs if o == 'E'])

if targets:
    t_copy = targets[:]
    out = ""
    total_str = 0
    attackers = []
    for (s,i) in own_nodes:
        attackers += [i]
        if t_copy:
            total_str += s
            if t_copy[0][0] < total_str - 1:
                j = max([j for j in range(len(t_copy)) if t_copy[j][0] < total_str - 1])
                out += " ".join([str(k) + "," + str(t_copy[j][1]) for k in attackers]) + " "
                attackers = []
                total_str = 0
                t_copy = t_copy[:j] + t_copy[j+1:]
    if attackers:
        if t_copy:
            out += " ".join([str(k) + "," + str(t_copy[0][1]) for k in attackers])
        else:
            out += " ".join([str(k) + "," + str(attackers[0]) for k in attackers])
else:
    out = " ".join([str(i) + "," + str(own_nodes[0][1]) for (s,i) in own_nodes])

print(out.rstrip())
sys.stdout.flush()

The idea is really simple.
I start enumerating my nodes in ascending order of strength, keeping a running sum of the strengths.
When the sum exceeds the strength of the weakest enemy node (+1 for a possible increase), I attack that node and remove it from the pool, reset the sum, and continue.
At the end, if the strongest nodes can't find anyone to attack, they'll collect more strength.

EDIT: Accumulator is now a bit smarter.
Instead of always attacking the weakest enemy node, it accumulates the strength until it could do so, and then attacks the strongest free node it can with that strength.
Also, if there are still enemies left at the end, any unassigned nodes will attack the weakest remaining enemy, just in case it decides to transfer its strength away.


MATL, 5 bytes
B42*c

Try it online!
Explanation
B     % Implicitly input an array of numbers. Convert to binary.
      % Gives a matrix with each row corresponding to a number
42    % Push 42 (ASCII code of '*')
*     % Multiply
c     % Convert to char. Char 0 is displayed as space. Implicitly display


Standardise leading zeroes in an input string

Ruby, 111 bytes

I hope this catches all the details of the spec

puts $*[0].gsub(r=/(?<![^,\s])(-?)(\d+)(?=\.?\d*(?![^,\s]))/){$1+$2.rjust(i.scan(r).map{|m|m[1].size}.max,'0')}

It reads the input as the first command line argument and prints the result to STDOUT.


Bash script (7 characters, 7 bytes)

rm "$0"


GolfScript, 51 characters
{[[]]\{[.;]`{1$[1$]+@@`1$`{[2$]-@@[+]+}++/}+%}/}:P;

The script defines a variable P which takes an array from top of the stack and pushes back a list of all partitions, e.g.
[1 2] P            # => [[[1] [2]] [[1 2]]]
["a" "b" "c"] P    # => [[["a"] ["b"] ["c"]] [["b"] ["a" "c"]] [["a"] ["b" "c"]] [["a" "b"] ["c"]] [["a" "b" "c"]]]

It does also work on larger lists:
6, P ,p            # prints 203, i.e. Bell number B6
8, P ,p            # 4140

You may perform own tests online.


Gol><>, 49 45 bytes

<<H~Kla}\`q%2l}}ss2"<\
<<H~Kla}\`q%2l}}ss2"<\

Try it online!

Verification!

I did this in Gol><> rather than ><> because the former has the handy K operator that copies the top n items on the stack, which makes duplicating the clean copy of the source code easier.

Explanation:

This works by having two copies of the executing code, and redirecting to the second one if the first is damaged. This fails when the last \ or the middle newline is removed, both of which are compensated for later.

<<                       Redirect left
                    <\  Switch to other source code if this line is irradiated
                   "     Push source with wrapping string literal
                ss2      Push quote
              }}         Move "< to end
          q%2l           If the length of the stack is not right
        \`               Push an extra \
       }                 Move the \ to the end
      a                  Newline
    Kl                   Duplicate the stack
   ~                     Pop the extra newline
  H                      Halt and print stack


Clip, 69

*cTx\{fFx`Tf[tFtx}T`[Fx[y!VVx"O-"Vy"O-"}[TC"A+ B+ AB+ O+ A- B- AB- O-

Input: AB-

Output: {{"AB+", "AB-"}, {"A-", "B-", "AB-", "O-"}}

Explanation

A blood type x can give to y if all of x's antigens are included in y. The program defines the function F as whether x can give to y, and T as the list of types.

*cTx                 .- If T contains x (the input)         -.
    \                .- Print                               -.
     {             ` .- a list of                           -.
      fFx`T          .- filter each t in T with F(x,t)      -.
           f[tFtx}T  .- filter each t in T with F(t,x)      -.

[Fx[y              } .- F is a function of x and y          -.
     !V              .- all letters of ... are included in ...   -.
       Vx"O-"        .- x, with O and - removed             -.
             Vy"O-"  .- y, with O and - removed             -.

[TC"A+ B+ AB+ O+ A- B- AB- O-   .- T is the list of types -.


Jelly, 7 bytes

b8d4ḅ5Ḍ

Try it online!

How it works

b8d4ḅ5Ḍ  Main link. Argument: n (integer)

b8       Convert n from integer to base 8.
  d4     Divmod each base-8 digit by 4, mapping the digit d to [d / 4, d % 4].
    ḅ5   Convert the quotient-remainder pairs from base 5 to integer, mapping
         [d / 4, d % 4] to (d / 4 * 5 + d % 4).
         The last two steps establish the following mapping for octal digits.
             0 -> [0, 0] -> 0
             1 -> [0, 1] -> 1
             2 -> [0, 2] -> 2
             3 -> [0, 3] -> 3
             4 -> [1, 0] -> 5
             5 -> [1, 1] -> 6
             6 -> [1, 2] -> 7
             7 -> [1, 3] -> 8
      Ḍ  Convert the resulting array of digits from decimal to integer.


Compress data with context free grammars

GolfScript, 111 108 characters
1/{.}{:^1<{^1$/,2>.{;,)^<.0?)!}*}do-1<.,1>{^1$/[10):10]*0+\+}{;^}if(\}while][0]%.,,]zip{))9+`"="+\~" "*+}%n*

This is a quite clumsy approach using GolfScript. The second version performs much better than the initial one. It is much longer than the intended code but my implementation had nested do-loops and this caused issues with the interpreter.
Examples:
> abcba
10=a b c b a

> abcabcbc
10=11 11 12
11=a 12
12=b c

> abcabcbcbcabcacacabcabab
10=11 12 12 13 14 14 c 11 15
11=15 13
12=c b
13=14 b
14=c a
15=a b


Quine with prime sourcecode character distribution constraints

Golfscript, 21 15 characters
11{'aa.~' }aa.~

After removing all NOPs, their images, and the leading 11, this becomes the quine
{`'.~'}.~

reading: block(string(dup, eval)); dup; eval.
Now to shoot for the stars (20 characters - the minimum for 2-3-5) or even galaxies (12 characters - the absolute minimum)  I've taken a short stop at Alpha Centauri B to refuel, now I'm drifting through intergalactic medium. Thanks,  Goldbach's conjecture.
Live: http://golfscript.apphb.com/?c=MTF7J2FhLn4nMTE7fWFhLn4K


Shortest class to implement Perl hash-of-hashes

Scala, 231 214 199 193 bytes

Immutability always wins! (turns out the long package name of collection.mutable.Map wasn't worth the hassle...)

class A{var a=Map[String,Any]()
def g(s:String*):Any={val y=s(0);if(s.size>1)g(y).asInstanceOf[A].g(s.drop(1):_*)else if(a.contains(y))a(y)else{a+=y->new A;a(y)}}
def s(s:String,v:Any)=a+=s->v}

Only thing that's problematic is the need to cast back to A... but having another method entirely that'd return a.type is actually longer (and with cannot be used).

Example:

val a = new A()
a.g("hey").asInstanceOf[A].s("foo", "bar")
a.g("hey").asInstanceOf[A].s("int", 3)
println(a.g("hey").asInstanceOf[A].g("foo"))
println(a.g("hey", "foo"))
println(a.g("hey", "int"))
a.s("hey", 42)
println(a.g("hey"))

Output:

bar
bar
3
42


Assuming you're using a flavor of regex that include look-aheads, detecting a pangram is straightforward, but tedious.  Using Python syntax:

r"(?=.*a)(?=.*b)(?=.*c)(?=.*d)(?=.*e)(?=.*f)(?=.*g)(?=.*h)(?=.*i)(?=.*j)(?=.*k)(?=.*l)(?=.*m)(?=.*n)(?=.*o)(?=.*p)(?=.*q)(?=.*r)(?=.*s)(?=.*t)(?=.*u)(?=.*v)(?=.*w)(?=.*x)(?=.*y)(?=.*z).*"

https://regex101.com/r/Z7NjEQ/2

The (?=.*a) block tests if what follows after that point matches .*a; another way to say that is, is this expression followed by any characters and then an a, or just, does this include an a?  Then repeat that check for every letter of the alphabet.

Without lookaheads, it's still possible, but even more tedious, because you have to account for every possible ordering of the alphabet.  If you were limited to the letters abc, here's what it might look like:

r".*(a.*b.*c|a.*c.*b|b.*a.*c|b.*c.*a|c.*a.*b|c.*b.*a).*"

https://regex101.com/r/OnXQe7/1/

This checks for an a, any set of characters, a b, any set of characters, then a c, OR an a, any set of characters, a c, any set of characters, then a b, OR...you get the idea.

You could use the same approach to check for the standard meaning of perfect pangram (every character exactly once), but not the modified version used here.


05AB1E, 11 bytes

∞<ÅΔÅγs.ιJQ

Try it online!

Computes the look and say of all integers until finding one that matches the input. Will timeout for large outputs.


Backtickify code snippets on Stack Exchange

APL (90)

(Yes, the APL charset does fit in a byte, here's IBM's codepage 907.)

{⎕ML←3⋄(,/m,m,⍨{⍵=m:'\`'⋄⍵}¨⍵),⊂(⌽g),⍵,g←(''↑⍨∨/t[1,⍴t]),m/⍨0⍳⍨z∊⍨⍳⌈/0,z←,⊃⍴¨⍵⊂⍨t←⍵=m←'`'}

This is a function that takes a string, and returns an array of two strings, where the first string is the comment representation and the second string is the full post representation.

Tests:

      backtickify←{⎕ML←3⋄(,/m,m,⍨{⍵=m:'\`'⋄⍵}¨⍵),⊂(⌽g),⍵,g←(''↑⍨∨/t[1,⍴t]),m/⍨0⍳⍨z∊⍨⍳⌈/0,z←,⊃⍴¨⍵⊂⍨t←⍵=m←'`'}
      ↑backtickify 'potato'
`potato`
`potato`

      ↑backtickify 'this is a backtick: `'
`this is a backtick: \``
`` this is a backtick: ` ``

      ↑backtickify '` `` ``` ````` ``````'
`\` \`\` \`\`\` \`\`\`\`\` \`\`\`\`\`\``
```` ` `` ``` ````` `````` ````

      ⍝ testcase for not wrapping with spaces
      ↑backtickify 'no`spaces``at````the`edges'
`no\`spaces\`\`at\`\`\`\`the\`edges`
```no`spaces``at````the`edges```

Note: I gave the function a name for readability's sake, this is not strictly necessary to use it (you can just put the argument next to the anonymous function) so I didn't count it.


BBC BASIC
Rev 1 Golfed code, 655 ASCII characters, tokenised filesize 614
Some major improvements to the data table, by hashing the string A.B..N to a number (1*A+2*B+..n*N)+n before looking up, and by storing only one translation vector (the other one is generated by code.) More explanation when I have finished golfing.
t=PI*2DIMm(9)
c=0z=0INPUTz$
FORi=1TOLEN(z$)d%=VAL(MID$(z$,i))IFd%c+=1m(c)=d%i-=d%=12z+=c*d%
NEXTREPEATREADl,e,f
UNTILl=z+c
l=4-3*(m(3)MOD3=0)-8*(l=59)
DATA69,0,70,65,100,35,66,149,0,49,109,0,52,80,0,55,0,189,39,120,0,44,40,40,58,55,95,47,136,0,59,40,0
VDU23,23,3|
FORr=-9TO19FORs=-9TO9a=1+e*(r*2+s)-f*l*s/4b=1+f*(r*2+s)+e*l*s/4p=40q=0FORk=1TOm(c)/2FORj=1TOc
n=m(j)o=TAN(PI/3)IFe=109ANDn<>4o=1
w=-p*COS(t/n)-q*SIN(t/n)q=p*SIN(t/n)-q*COS(t/n)p=w
u=p:v=q
x=a:y=b
MOVEx,y
FORi=1TO14x+=u*2y+=v*2IFVAL(z$)DRAWx,y ELSEGCOL9LINEx-u-v/o,y-v+u/o,x-u+v/TAN(PI/n),y-v-u/TAN(PI/n)
w=v*COS(t/n)-u*SIN(t/n)u=v*SIN(t/n)+u*COS(t/n)v=w
NEXTNEXT
p=u:q=v
a=x:b=y
NEXTNEXTNEXT

Rev 0 Golfed code, 770 ASCII characters, tokenised filesize 728
All I've done here is remove comments, unnecessary whitespace and quote marks, and put all the DATA on one line. There's certainly room for more golfing.
t=PI*2DIMm(9)
c=0INPUTz$
FORi=1TOLEN(z$)d%=VAL(MID$(z$,i))IFd%c+=1:m(c)=d%:i-=d%=12
NEXTREPEATREADl$,e,f,g,h
UNTILMID$(z$,1-(VAL(z$)=0))=l$
DATA3.3.3.3.3.3,240,0,120,70,3.3.3.3.6,200,70,40,210,3.3.3.4.4,80,0,40,150,3.3.4.3.4,-40,150,150,40,3.12.12,300,0,150,260,3.4.6.4,220,0,110,188,3.6.3.6,160,0,80,140,4.4.4.4,80,0,0,80,4.6.12,0,380,330,-190,4.8.8,272,0,136,136,6.6.6,240,0,120,70
VDU23,23,3|
FORr=-9TO19 FORs=0TO9a=1+e*r+g*s
b=1+f*r+h*s
p=40q=0FORk=1TOm(c)/2FORj=1TOc
n=m(j)o=TAN(PI/3):IFe=220ANDn<>4o=1
w=-p*COS(t/n)-q*SIN(t/n)q=p*SIN(t/n)-q*COS(t/n)p=w
u=p:v=q
x=a:y=b
MOVEx,y
FORi=1TO14x+=u*2y+=v*2IFVAL(z$)DRAWx,y ELSEGCOL9LINEx-u-v/o,y-v+u/o,x-u+v/TAN(PI/n),y-v-u/TAN(PI/n)
w=v*COS(t/n)-u*SIN(t/n)u=v*SIN(t/n)+u*COS(t/n)v=w
NEXTNEXT
p=u:q=v
a=x:b=y
NEXTNEXTNEXT

Explanation
This is a continuation of my previous Level 1 answer, but I decided to post it separately because it's rather long.
Level 2
This is achieved by translation of my "level 1.5" templates from my previous answer. The two translation vectors for each tiling are hardcoded. I take advantage of the fact that an isosceles triangle of base 80 and height 70 is a very good approximation of an equilateral triangle, and a right triangle with hypotenuse vector (56,56) has a hypotenuse length very close to 80.
Level 3
To plot the duals, instead of plotting an edge of the polygon, we plot a spoke from the middle of that edge to the centre of the polygon. This is at right angles to the edge and has length of 1/TAN/(PI/n) times of the vector (u,v) which in turn is half as long as the edge.
Unfortunately, because certain polygons in tilings 3.3.3.3.6 and 3.4.6.4 are not plotted explicitly, they would not be plotted if we only did this. Therefore the spoke also extends outward from the polygon. The outward extension is controlled by the variable o.
By default the extension is sufficient to reach the centre of a triangle, but for 3.4.6.4 it needs to be extended more in order to draw the duals of the squares that are not plotted explicitly. So enough extension to fill in the missing squares is applied when hexagons and triangles are plotted explicitly, but the normal extension is applied when squares are plotted explicitly, to avoid spurious lines in the adjacent triangles.
Here's what they look like without the spoke extensions. The holes in the dual pattern can be clearly seen. The correct output can be seen in the main picture at the bottom of the answer

Commented Code
Differences from my previous answer are indicated inline
  t=PI*2                                          :REM constant Tau = PI*2

  DIMm(9)                                         :REM declare array for the numbers in the input
  c=0                                             :REM number of polygons in the list

  INPUTz$
  FORi=1TOLEN(z$)                                 :REM for each character in the input
    d%=VAL(MID$(z$,i))                            :REM use VAL to return the numeric value of the substring to the right and store to integer variable
    IF d% c+=1 :m(c)=d%: i-=d%=12                 :REM if the last character read was a number, d% contains it, otherwise 0. Advance c and store to m. If it is 12, increment i to skip a character.
  NEXT

  REM BLOCK OF NEW CODE to define vectors (e,f) and (g,h) for each possible tiling

  REPEAT
    READ l$,e,f,g,h                               :REM read an entire line of the data below
  UNTIL MID$(z$,1-(VAL(z$)=0))=l$                 :REM abort the loop when l$ coincides with the input. the MID$ strips off the 'V' from the input where necessary.

  DATA"3.3.3.3.3.3",240,0,120,70
  DATA"3.3.3.3.6",200,70,40,210
  DATA"3.3.3.4.4",80,0,40,150
  DATA"3.3.4.3.4",-40,150,150,40
  DATA"3.12.12",300,0,150,260
  DATA"3.4.6.4",220,0,110,188
  DATA"3.6.3.6",160,0,80,140
  DATA"4.4.4.4",80,0,0,80
  DATA"4.6.12",0,380,330,-190
  DATA"4.8.8",272,0,136,136
  DATA"6.6.6",240,0,120,70

  VDU23,23,3|                                           :REM change linewidth to 3 (default is 1)

  REM END BLOCK OF NEW CODE

  FORr=-9TO19 FORs=0TO9                                 :REM two new loops for translations

      a=1+e*r+g*s                                       :REM modified code for
      b=1+f*r+h*s                                       :REM coordinates to start drawing at

      p=40:q=0                                          :REM vector of first line

      FORk=1TOm(c)/2                                    :REM draw half as many vertex figures as there are sides on the last polygon in the list

        FORj=1TOc                                       :REM for each polygon on the list
          n=m(j)                                        :REM n=number of sides
          o=TAN(PI/3): IF e=220 AND n<>4 o=1            :REM new code for the spoke extension 1/o.

          w=-p*COS(t/n)-q*SIN(t/n)                      :REM rotate the starting vector anticlockwise by the internal angle of the current polygon
          q=p*SIN(t/n)-q*COS(t/n)                       :REM to avoid overlapping the previous one, if any.
          p=w

          u=p:v=q                                       :REM make a local copy of the vector and coordinates
          x=a:y=b                                       :REM to avoid corruption of p,q,a,b during the drawing of the polygon
          MOVE x,y                                      :REM move the graphics cursor to the start without drawing
          FORi=1TO14                                    :REM do 14 iterations regardless of the number of sides on the polygon
            x+=u*2                                      :REM increment x and y by the vector representing the side
            y+=v*2                                      :REM the value is double (u,v) to facilitate drawing duals later

            REM if z$ begins with a numeric character, draw an edge. If not, change to red and draw a spoke.
            IFVAL(z$) DRAW x,y ELSE GCOL9: LINEx-u-v/o,y-v+u/o,x-u+v/TAN(PI/n),y-v-u/TAN(PI/n)

            w=v*COS(t/n)-u*SIN(t/n)                     :REM rotate the vector clockwise
            u=v*SIN(t/n)+u*COS(t/n)                     :REM through the external angle of the polygon
            v=w
          NEXT                                          :REM draw next edge of the current polygon
        NEXT                                            :REM draw next polygon of the current vertex

        p=u:q=v                                         :REM once the vertex is finished, we will be two sides around the perimeter of the last polygon.
        a=x:b=y                                         :REM copy the position and direction data into p,q,a,b.
      NEXT                                              :REM draw next vertex figure

    NEXT                                                :REM close the two new translation loops
  NEXT

Output
The program performs only one tiling or dual for each run. However it plots the duals in red. To save space, I ran the program twice without clearing the screen in order to superimpose the dual on top of the regular tiling.


Verify a solution for Conway Immobilizer

JavaScript (ES7),  229 224  213 bytes
Input: a function (the solver) expecting an array of 3 values among 'Q', 'K', 'A' or undefined for empty, and returning a move as a pair [from, to] (0-indexed)
Output: 0 or 1

f=(F,n=162)=>!n--||(g=s=>(s[k=s.join`/`]^=1)?/A,K,/.test(k)|g(s,[x,y]=F(s.map(a=>a[0])),s[y].unshift(s[x].shift())):0)([0,1,2].map(i=>s[n/3**i%3|0].push('QKAKQAAQKQAKKAQAKQ'[3*~~(n/27)+i]),s=[[],[],[]])&&s)&f(F,n)

Try it online!


Polar Bear, Polar Bear, what do you hear?

05AB1E, 349 331 330 322 314 311 bytes
•4i;kV_†©:š×Îj€Yå—‚‘%˜ESÎ´þ¤çÑ9¶‹{Å€7¾à{Ì®qA•35B0¡…ing«lV•7ü[¿‘¢wÀ¶à-‚¤î„jHâ™ÐJ'µ‡ÀÂý6›ü‚š¸€%NtÅýµL›fU¥ì€€uîT¡›Ÿ{!œ>'Ì&ý§¨Ü?é>•36B1ð:0¡™D©„, «D‚ø“€À€·€î—«?“¶«¸â€˜€JU¦“„¾“‚˜lv„I “—«0€†€¯¶å.“«0¡`yð«Y¦õ‚˜Nè«sr„ aN5Qi'n«}ð«N9›ijrj¨ðs«…...«}srJˆ}X¯‚ø€Jvy,¶?}…...DU?Y¨vN__i',¶}yð“€è€…“N6Qi'n«}ð®NèJl?}X,“€Š's€À I—«.“?

Try it online
Explanation
•4i;kV_†©:š×Îj€Yå—‚‘%˜ESÎ´þ¤çÑ9¶‹{Å€7¾à{Ì®qA•
Packed string containing the sounds GROWL0ROAR0SNORT0FLUT0BRAY0HISS0TRUMPET0SNARL0YELP0BELLOW0WHISTL
35B0¡…ing«lV
Unpack, split on 0, add "ing" to each word, convert to lower and store in variable Y
•7ü[¿‘¢wÀ¶à-‚¤î„jHâ™ÐJ'µ‡ÀÂý6›ü‚š¸€%NtÅýµL›fU¥ì€€uîT¡›Ÿ{!œ>'Ì&ý§¨Ü?é>•
Packed string containing the animals POLAR1BEAR0LION0HIPPOPOTAMUS0FLAMINGO0ZEBRA0BOA1CONSTRICTOR0ELEPHANT0LEOPARD0PEACOCK0WALRUS0ZOOKEEPER
36B1ð:0¡™
Unpack, replace 1 with space, split on 0 and convert to title case
D©„, «D‚ø
Duplicate, save to register for later use, add ", " to one copy, duplicate that and zip.
“€À€·€î—«?“¶«¸
Dictionary words "what do you hear?", followed by a new line, added to a new list
â€˜€JU
Cartesian product of list of "Animal, Animal, " and "what do you hear?\n", flattened and joined and stores it in variable X.
Pruduces list of strings of the form "Animal, Animal, what do you hear?n".
¦“„¾“‚˜l
Take the remaining list of animals from before, remove the zookeeper and add children, convert to lower case.
v
For each animal:
„I “—«0€†€¯¶å.“«0¡`

Push "I hear0 in my ear.", split on 0 and push as separate strings.
yð«Y¦õ‚˜Nè«
Push "animal sound" with children having no sound
sr„ a
Push "a" in correct place
N5Qi'n«}
If the animal is "Elephant" add "n"
ð«
Add space.
N9›ijrj¨ðs«…...«}
If animal is children, remove space and add "..."
srJˆ}
Join the sentence "I hear a(n) animal sound in my ear." (as well as the children one), store in global array and end loop
X¯‚ø€J
Retrieve the first lines, zip and join producing the first part of the rhyme "Animal, Animal, what do you hear?\nI hear a(n) animal sound in my ear."
vy,¶?}
Print followed by new line.
…...DU?
Print "..." and store a copy in variable X.
Y¨v
For each sound except "whistling":
N__i',¶}
For each line except the first one, start it with ",\n" (making the comma go on previous line)
yð“€è€…“
Push sound, space and "like a"
N6Qi'n«}
If Elephant add "n".
ð®NèJl?}X,
Retrieve the animal saved in register, join everything, print and end loop followed by "...".
This produces the "sound like a(n) animal," lines.
“€Š's€À I—«.“?
Print dictionary string "that's what I hear."


Python 3.3 (354?)

I noticed this as an unanswered question and decided to give it a go:

v=input().split('/')+input().split(',')+[input().split(' '),0,1,'X','U','D','L','R']
w,h,x,y,d,c,p,r,m,n,s,l,e=v
w,h,x,y=int(w),int(h),int(x),int(y)
g=[[' 'for x in range(int(h))]for y in range(int(w))]
while p<len(c):
 i=c[p]
 if r:
  g[y][x]=m
 if i=='RESET':
  w,h,x,y,d,c,p,r,m,n,s,l,e=v
 if i=='DRAW':
  m='X'
 if i=='ERASE':
  m=' '
 if i=='UP':
  r=0
 if i=='DOWN':
  r=1
 if i=='DIRECTION':
  p+=1
  i=int(c[p])
  d=''
  if i in[8,1,2]:
   d+=n
  if i in[4,5,6]:
   d+=s
  if i in[6,7,8]:
   d+=l
  if i in[2,3,4]:
   d+=e
 if i=='FORWARD':
  p+=1
  i=int(c[p])
  for _ in range(i):
   if d.find(n)+1:
    y-=1
   if d.find(s)+1:
    y+=1
   if d.find(l)+1:
    x-=1
   if d.find(e)+1:
    x+=1
   if r:
    g[y][x]=m
 if i=='DISPLAY':
  for z in g:
   print(''.join(z))
 if i=='POSITION':
  print(x,y)
 if i=='SETPOS':
  p+=3
  x,y=c[p-2:p]
  d=''
  if i in[8,1,2]:
   d+=n
  if i in[4,5,6]:
   d+=s
  if i in[6,7,8]:
   d+=w
  if i in[2,3,4]:
   d+=e
 if i=='STOP':
  while input()!='~':
   pass
  exit
 if x>w or x<0 or y>h or y<0:
  print('!')
  exit
 p+=1

  PS I am unsure about the scoring setup so my score may be incorrect!


54 Languages, 1331 bytes

><>,
Gol><>,
Foo,
Befunge-93,
Befunge-98,
brainfuck,
Brain-Flak,
Python 2,
Python 3,
Hexagony,
Perl,
Ruby,
Julia,
Cardinal,
Brainbash,
Turtlèd,
Deadfish~,
Whitespace,
Braille,
Rail,
Fission,
ETA,
Trigger,
Self-modifying Brainfuck,
Numberwang,
Actually,
Emoji,
Symbolic Brainfuck,
TinCan,
Alphuck,
Shove,
Cood,
Wise,
Width,
Whispers,
Thue,
Surface,
Stones,
evil,
Set,
Prelude,
Gaot++,
Cubix,
Cubically,
PATH,
Commercial,
Brian & Chuck,
Monkeys,
Nhohnhehr,
Beam,
AsciiDots,
Alumin,
Alice,
Whirl

This is getting very long, so at @MDXF's suggestion, I'm moving the subprograms and comments to a gist. The program here is only the final program. Thanks to MDXF again for providing the TIO test driver.

54. Whirl

##\$"404"#N#S# , ,,#$#?@\404!?@GJlICJlGCC*G^+0%=%=+0%x&fqpqqqiipsoddddoiipsohphhhhyhhhh? 	  ?nnn4$4#!000110000011110000100000100000110000011001100000111100001110011000111000110000
#?\++++:----:++++:H@((((4O0O4O@((((()()()){}){x}x){}x()){}){}()){}){})<[-]>[-]-[<+>-----]<+x%"404"?.⌂----.++++.>11
#i(N/"404"ooo@ENTHOEONHSSEONTHOEONSETssipceaiiiiiscejiiiijeeeejapmzaeeaeueewzaeeeaeewzaeeaeueewqs??|?)999|997+|++++!999777+++++!999997+++++!
print(404)

__DATA__=1
# \"404"*CC'[-][ .-$_"404"&]
"""pp
I want 404 of this
How much is it
#  -52, Z, -1                          #
#  -48, Y, -1                          #
#  -52, X, -1                          #
[-][
x::=~404
::=
x
]<<<
> 404
>> Output 1
red up two blue up red up one blue up red up two blue up
baaaaa bleeeeeeeeet bleeeeeeeeet baaaaa bleeeeeeeeet
a now 404 dollar off!
a has been selling out worldwide!
2 LEFT
2 LEFT
2 UP
2 LEFT
2 TEACH
1 LEFT
1 RIGHT
1 BOND
1 BOND
1 TEACH
2 YELL
1 FIGHT
2 YELL
1 TEACH
2 YELL
set ! 52
set ! 48
set ! 52
+------+
|$0011\|
|/000\0|
|0/0@11|
|00  10|
|0\10/0|
|\1100/|
+------+
$'main'
 \-444o000o444omm^

[-][$++++++++++++++++++++++++++++++++++++++++++++++++++++.----.++++.#
<<<<<<```>>>>.>.>.
]
ss"""
#7777777777777777777777777777724091557093543643404➡77▲▲▲²²▲²²¡▼▼▼▼¡▲▲▲▲¡⠎⡆⡎⡆⢐⠣⠃s&&&&~-<<:<<:<<<:<:>>>>>>>>:^||||G<>

Try it online!

Whirl is described as a Turning Tarpit [sic], which uses only two instructions, 1 and 0. 1 rotates the current wheel of instructions (either the math wheel or the operations wheel), 0 swaps the rotation of the wheel, and two 0s executes the instruction and switches wheels. The relevant instructions are on the first line:

000110000011110000100000100000110000011001100000111100001110011000111000110000

000110000 Switch to math wheel and execute math.not (math.val = 1)
011110000 Execute math.store, (memval = math.val = 1)
10000     Execute math.add, (math.val = math.val+memval = 1+1 = 2)
010000    Execute math.store (memval = math.val = 2)
0110000   Execute math.multiply, (math.val = math.val*memval = 2*2 = 4)
01100     Execute math.store (memval=math.val) and switch to the ops ring
110000    Execute ops.one (ops.val = 1)
011110000 Executes ops.intio, printing memval (4)
11100     Add one to memory pointer (memval=0)
1100      Execute maths.nop to switch back to ops ring
011100    Execute ops.intio, printing memval (0)
01100     Execute maths.store, (memval=maths.val=4)
00        Execute maths.intio, printing memval (4)

The leading 01s cancel each other out, and the trailing 01s cause a floating point exception.

Edit: fixed a bunch of broken stuff

(Commands to be careful about in the future: UDLR%"[.]o473psjw)

If any programs work for future languages or don't work for current or previous languages, please comment.


Explicit-ify APL expressions involving trains

APL (Dyalog Classic), 63 59 58 54 52 51 bytes

∊⍎'.[A-Z].'⎕r'{0::&⍵⋄''() '',⍪⍺&⍵}'⊢'\w'⎕r'''&'''⊢⍞

Try it online!

put all letters in quotes, replace uppercase letters with dfns that return either "(left) self right" or "self right" depending on the presence of a left arg, and execute.


Build a script to generate the Deep Note

C, 323 bytes

#include<math.h>
#define A y=-2*y*y*y+3*y*y
main(i,j,o,e){e=44100;write(1,"RIFF´9WAVEfmt      D¬  ±    data9",44);float r[30],x,y,k,v;for(i=0;i++<30;r[i]=.5-(9*i%7)/7.);for(i=0;i++<9*e;){x=2.*M_PI*i/(0.+e),k=y=1-i/(8.*e),v=0,A,A,A,y=y>1?1:y;for(j=0;j++<30;o=j%6,v+=(7-o)*.1*sin(x*(20<<o)*(1+y*r[j])));write(1,&v,4);}}

(among others, NUL characters could't be pasted in the textbox; you can view or download the original file here)

Usage:

gcc deep-note.c -o deep-note
./deep-note > deep-note.wav

Click here to listen to a preview of the generated sound!


This challenge is about recursion (Robbers' thread)

Octave, by Sanchises 27 bytes

There are so many, many ways to do this in a loopy-way. For instance this one, if an explicit loop is needed:

for i=1:input('')disp(i)end

Try it online!

Or, if you want to create a vector (I haven't golfed this terribly well, since using a loop like this is kinda pointless):

x=0;for i=1:input(''),x(i)=i;end,x

Or 7 bytes if it's OK to not use a loop at all:

@(n)1:n


Easier communication means faster coding means fewer coders means …

SVG(HTML5), 336 bytes

<svg width=500 height=500><defs><path id=p d=M49,250a201,201,0,0,1,402,0a201,201,0,0,1,-402,0></defs><text font-size="32"><textPath xlink:href=#p>EASIER COMMUNICATION MEANS FASTER CODING MEANS FEWER CODERS MEANS</textPath><animateTransform attributeName=transform type=rotate from=360,250,250 to=0,250,250 dur=9s repeatCount=indefinite>

Edit: Some people have found that the font doesn't quite fit for them so here is a version that allows you a few pixels of adjustment:

<input type=number value=0 min=0 max=9 oninput=p.setAttribute('d','M250,250m20_,0a20_,20_,0,1,1,-20_,-20_a20_,20_,0,1,1,-20_,20_a20_,20_,0,1,1,20_,20_a20_,20_,0,1,1,20_,-20_'.replace(/_/g,this.value))>

<svg width=500 height=500><defs><path id=p d=M250,250m200,0a200,200,0,1,1,-200,-200a200,200,0,1,1,-200,200a200,200,0,1,1,200,200a200,200,0,1,1,200,-200></defs><text font-size="32"><textPath xlink:href=#p>EASIER COMMUNICATION MEANS FASTER CODING MEANS FEWER CODERS MEANS</textPath><animateTransform attributeName=transform type=rotate from=360,250,250 to=0,250,250 dur=9s repeatCount=indefinite>


C, 74 73 70 69 67 characters

67 character solution with many good ideas from @ugoren & others:

i;main(j){main(poll(printf("%*c|\n",j=21+sin(i++*.1)*20,0),0,50));}

69 character solution with while loop instead of recursion:

i;main(j){while(printf("%*c|\n",j=21+sin(i++*.1)*20,0))poll(0,0,50);}

Approaching perl territory. :)


Python 2, 39 38 bytes

lambda l:{v for v in l if~-l.count(v)}

Try it online!

Python 3, 37 bytes

lambda l:[*map(l.remove,{*l})]and{*l}

Try it online!


Monday Mini-Golf #4: JARVIS (Just Another Rather Vast set of Integer Sequences)

Pyth, 15 14 bytes

.uu|*GHhGjNT1Q

1 byte thanks to Dennis

Test Suite

This challenge feels like it was made for Pyth's reduce functions. One reduce over the digits, one reduce until the value stops changing, and we're good.


Truth Tables: Your great-grandfather's computer

JavaScript (ES6), 141

Simple function, no bonus, 141 chars. (140 uft8, 1 unicode wide)

Complex function handling ~ or ¬, 254 chars (253 utf, 1 unicode wide), score 229

Could save 6 bytes using alert instead of console.log, but alert is particularly unfit to display tables.

Test running the snippet below in an EcmaScript 6 compliant browser (tested with Firefox. Won't work in Chrome as Chrome does not support .... Also, the bonus version use an extension of split that is Firefox specific).

/* TEST: redirect console.log into the snippet body */ console.log=x=>O.innerHTML+=x+'\n'

// Simple
F=s=>{[a,o,b]=[...s],z='  ',r=a+z+b+z+a+` ${o} ${b}
`;for(w='FT',n=4;n--;r+=w[c]+z+w[e]+z+z+w[o<'∧'?c|e:c&e]+`
`)c=n&1,e=n>>1;console.log(r)}

// Simple, more readable
f=s=>{
   [a,o,b]=[...s]
   r=a+'  '+b+'  '+a+` ${o} ${b}\n`
   for(w='FT',n=4; n--; )
   {
     c = n&1, e = n>>1, x=o<'∧' ? c|e : c&e
     r += w[c]+'  '+w[e]+'    '+w[x]+'\n'
   }
   console.log(r)
}

// 10% Bonus
B=s=>{[a,o,b]=s.split(/([∧∨])/),t=a>'z',u=b>'z',z='  ',r=(t?a[1]+z:'')+a+z+(u?b[1]+z:'')+b+z+a+` ${o} ${b}
`;for(s=v=>'FT'[v]+z,n=4;n--;r+=s(c)+(t?s(d)+' ':'')+s(e)+(u?s(f)+' ':'')+(t?'   ':z)+s(o<'∧'?d|f:d&f)+`
`)c=n&1,d=c^t,e=n>>1,f=e^u;console.log(r)}

Test1 = ['q∨p','q∧p']
Test2 = Test1.concat([
  '~q∨p','q∨~p','~q∨~p','~q∧p','q∧~p','~q∧~p',
  '¬q∨p','q∨¬p','¬q∨¬p','¬q∧p','q∧¬p','¬q∧¬p'
])

console.log('SIMPLE')
Test1.forEach(t=>F(t));

console.log('BONUS')
Test2.forEach(t=>B(t));


Pyth, 9 bytes
e.fqlPZQE

Explanation
          - autoassign Q = eval(input())
     PZ   -      prime_factors(Z)
    l     -     len(^)
   q   Q  -    ^ == Q
 .f     E -  first eval(input()) of (^ for Z in range(inf))
e         - ^[-1]

Try it here!
Or try a test suite!


Perl, 156 143 134 128 127 125 120 119 117 113 109 bytes

Includes +1 for -p

Run with the control string on STDIN, e.g.

perl -p rubic.pl <<< "^^>^^<^^^"

rubic.pl:

@1=wryobg=~/./g;s##$n=w&$&;$y+=$x-=$y+=$x,@1[0,4,2,5,3,1]=@1while--$n%9;@{$n&&--$y%3}[3,0..2]=@1;$1[$n+9]#eg

Explanation

Older version:

@f=gboyrw=~/./g;s##$n=w&$&;$y+=$x-=$y+=$x,@f=@f[2,4,1,3,0,5]while--$n%9;@f=@f[0,$y=1,5,2..4]if$n&&$y--<0;$f[$n+8]#eg

The challenge of this question is to find a coordinate system that makes it easy to track the position and direction of the ant and to still easily get the face identity.

The system I chose was to put standard (x,y) coordinates on the face the ant is on such that the ant is always facing in the negative y direction with the center of the face being (0,0). So:

rotate right: (x',y') <- (-y,  x)
rotate left:  (x',y') <- ( y, -x)  alternatve: 3 right rotations
Step forward:   y' <- y-1

If y was already -1 the ant will leave the current face and step onto the next one. In the new coordinate system there x keeps its value, but y' becomes 1.

This gives an easy coordinate system within a face. I also need something for the faces themselves. There I use an array consisting of

The face to right of the ant            g in the initial position
The face to the left of of the ant      b
The face behind the ant                 o
The face opposite to the ant            y
The face before the ant                 r
The face the ant is on                  w

So the initial array is (g,b,o,y,r,w). Moving to the next face corresponds to rotating the last 4 elements, so moving from white to red makes this (g,b,w,o,y,r). Turning right is a permutation of the first 5 elements giving (o,r,b,y,g,w). Turning left is a simular permutation but can also be done by turning right 3 times, so applying this permutation 3 times. And not turning at all can also be done by applying the permutation 8 times. In fact turning right can also be done by applying the permutation 5 times.

Knowing this the program is rather simple:

@f=gboyrw=~/./g                 Set up the initial face orientation
s## ... #eg                     Process each control string character
                                {this is equivalent to s#.#...#eg because
                                the empty regex repeats the last
                                succesful regex)
$n=w&$&                         Calculate n, the number of right
                                rotations+1 modulo 9.
                                This abuses a coincidence of the control
                                characters:
                                 "<" & "w" = "4" -> 3 right rotations
                                 ">" & "w" = "6" -> 5 right rotations
                                 "^" & "w" = "V" = 0 but that is 9 mod 9
                                 so leads to 8 right rtations

$y+=$x-=$y+=$x,                 This is the same as ($x,$y)=(-$y,$x), so
                                a right rotation of the face coordinates
@f=@f[2,4,1,3,0,5]              Right rotation of the face array
   while --$n%9                 Rotate right n-1 times. After this n=0
                                If this was a step then n was effectively 0.
                                So rotate right 8 times leaving n=-9

    ... if $n                   If a step...
               $y--             ... decrease y ...
             &&$y--<0           ... but if y was already negative ...
@f=@f[0,$y=1,5,2..4]            ... change face and set y to 1

$f[$n+8]                        return the last element (current face)
                                if this was a step, otherwise empty

So for that last statement rotations lead to the empty string and steps forward lead to the current face. Therefore $_ gets replaced by the faces visited on each step.


JavaScript ES6, 57 bytes

s=>s[r="replace"](/-+/,s=>s[r](/-/g,`
$'/`))[r](/-/g,' ')

Outputs a leading newline. Works by taking the row of -s and converting them into a triangle, then replacing the -s with spaces.

Edit: Saved 5 bytes thanks to @edc65.


Find the first n digits of the square root of a number

Python, 143 chars

m,n=map(int,raw_input().split())
d=10**m
n*=d*d
a=0
b=n
while a<b-1:c=(a+b)/2;a,b=[[c,b],[a,c]][c*c>n]
print('%d.%0*d'%(a/d,m,a%d))[:m+(a/d<d)]

Computes the answer by multiplying n by 10^2m, doing an integer square root (using binary search), then "dividing" the result by 10^m.


Ruby, 288 255 bytes

->m{h={[?O]=>-2,%w[F Cl]=>-1,%w[H Li Na K Rb Cs Fr]=>1,%w[Be Mg Ca Sr Ba Ra]=>2};a=m.scan /([A-Z][a-z]*\d*)/;r=a.flat_map{|(b)|b=~/(\D+)(\d*)/;[a.size==1?0:h[h.keys.find{|v|v.include?$1}]]*($2=='' ? 1:$2.to_i)};r.map{|j|j||-((r-[p]).inject:+)/r.count(p)}}

Try it online!

Saved 1 byte thanks to Jenkar
Saved 32 more bytes by inlining definitions and removing parentheses

Ungolfed
oxidation_state = -> molecule {
    h = {
        %w[H] => 1,
        %w[O] => -2,
        %w[F] => -1,
        %w[Cl] => -1,
        %w[Li Na K Rb Cs Fr] => 1,
        %w[Be Mg Ca Sr Ba Ra] => 2,
    }
    find_oxidation = -> a {
        k = h.keys.find { |as| as.include?(a) }
        h[k]
    }
    atoms = molecule.scan(/([A-Z][a-z]*\d*)/)
    r = atoms.flat_map { |(a)|
        a.match(/([^\d]+)(\d*)/)
        [atoms.length == 1 ? 0 : find_oxidation[$1]] * ($2=='' ? 1 : $2.to_i)
    }
    r.map { |j|
        sum = r.compact.inject(:+)
        !j ? -sum / r.count(nil) : j
    }
}


Sum the rows of the concatenated triangle

Husk, 7 bytes
1-indexed
Σ!CNṁdN

Try it online!
Explanation
    ṁ     Map then concatenate
     d    Integer digits
      N   Over the natural numbers
  CN      Cut into lists of lengths corresponding to the natural numbers
 !        Index it
Σ         Sum


Reverse words without changing capitals or punctuation

GolfScript, 58 54 48 characters
" "/{.{65- 223&26<}:A,\{.A{96&\)31&@+}*}%+}%" "*

This is a GolfScript solution which became rather long. Lots of the code is actually finding out if a character is in a-zA-Z. Maybe someone can find an even shorter way of testing it.
You can try the code online. Examples:
> Hello, I am fish.
Olleh, I ma hsif.

> This; Is Some Text!
Siht; Si Emos Txet!

> Don't try this at home.
Tno'd yrt siht ta emoh.


Haskell, 75 bytes

Thanks Ørjan for saving one byte!

g n=sum[x#n|x<-[1..n],let a#n=sum$[b#(n-a*b)|b<-[1..n],a/=b]++[0^n^2|a==x]]

Try it online!

The problem is equivalent to:

How many ways can \$n\$ be written as \$\sum_{i=0}^ka_ia_{i+1}\$ with \$a_i\in\mathbb N,a_i\neq a_{i+1},a_0=a_k\$


Brachylog, 13 bytes

s↔B&sA,B,A~s?

Try it online!

How it works

s↔B&sA,B,A~s?
s              the input has substring temp
 ↔B            temp reversed is B
   &           and the input
    sA         has substring A
      ,B,A     A,B,A
          ~s?  is a substring of input


Canvas, 15 9 bytes
 _；１＊⁸／∔╬

Try it here!, another 9 bytes
-6 bytes after fixing the program.
Draws a quarter of the hexagon, and quad palindromizes.


CJam, 16 15 13 12 bytes

q2*A~<$e`3=(

Test it here.

Explanation

The basic idea is to manipulate the string such that we can make CJam's built-in run-length encoding work for us.

Let's go through an example (the one from the question). The input string is

 _________
|         |
|  H   H  |
|  H H H  |
---H---H---

We repeat that twice:

 _________
|         |
|  H   H  |
|  H H H  |
---H---H---
 _________
|         |
|  H   H  |
|  H H H  |
---H---H---

And remove the last line:

 _________
|         |
|  H   H  |
|  H H H  |
---H---H---
 _________
|         |
|  H   H  |
|  H H H  |

Then we sort this string. It'll now have a bunch of newlines at the start, and then this (shortened by a few spaces to avoid a horizontal scrollbar):

                                    ---------HHHHHHHHHHHH__________________||||||||||||

While the suit character will vary, it'll always be an upper case letter, found in the fourth run of the sorted string (accounting for the newline). When we run-length encode this we get

[8 '\n] [46 ' ] [9 '-] [12 'H] [18 '_] [12 '|]]

So all we need to do is pick out the fourth  element and reverse it.

Here is a breakdown of the actual code:

q              e# Read the input.
 2*            e# Repeat twice.
   A~<         e# Remove the last 11 characters, i.e. the last line.
      $        e# Flatten into a single string and sort its characters.
       e`      e# Run-length encode: turns the sorted string into 5 pairs of numbers
               e# and characters.
         3=    e# Select the one corresponding to the suit.
           (   e# Pull off the number so that its printed after the suit.


Julia, 30 bytes

n->"$n"join(n-1:-1:0)[1:n]"$n"

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

We construct and join the descending sequence from n-1 to 0, and take the first n characters from the resulting string. We prepend and append this with the input as a string.

Verify all test cases online


Motorola 68000 assembly - 34 bytes

(GNU assembler syntax)

| short min_fib_partition(long N asm("%d2"), long *out asm("%a0"))
min_fib_partition:
    | Generate Fibonacci numbers on the stack (-1, 1, 0, 1, 1, 2, 3, ..., 1134903170).
    moveq #-1, %d0          | A = -1
    moveq #1, %d1           | B = 1
generate_loop:
    move.l %d0, -(%sp)      | Push A to the stack.
    exg.l %d0, %d1          | A' = B
    add.l %d0, %d1          | B' = A + B
    bvc.s generate_loop     | Stop when signed long overflows.

    | Go back up the stack, partitioning N using the greedy algorithm.
    moveq #0, %d0           | Initialize return value (number of terms).
subtract_loop:
    move.l (%sp)+, %d1      | Pop a Fibonacci number F off the stack.
    cmp.l %d1, %d2          | If N < F, continue to smaller Fibonacci number.
    blt.s subtract_loop
    addq.w #1, %d0          | Increment the term count.
    move.l %d1, (%a0)+      | Append F to the output array.
    sub.l %d1, %d2          | N -= F
    bne.s subtract_loop     | Continue if N has not yet reached zero.

    | Clear the stack by searching for that -1.
clear_stack_loop:
    tst.l (%sp)+
    bge clear_stack_loop

done:
    rts

36 → 34: Made Fibonacci generator stop on overflow rather than by counting, and fixed the 0 case so it outputs [0] rather than [].  However, passing a negative N crashes now.

The comment at the top is the C prototype of this function, using a language extension to identify what parameters go where (by default, they go on the stack).

My TI-89, with its 10MHz processor, takes 5 minutes to run this function on 1 – 1,000,000.

Although the machine code is (currently) fewer bytes than the GolfScript solution, it would probably be unfair to accept this as the shortest solution because:

Machine code is normally not counted as "source code".  Unlike source code, machine code usually has high symbol complexity and, more importantly, is unprintable.  See "Should executable binaries be considered a reasonable solution for code-golf?".
This solution only takes a single number as input, rather than multiple inputs.
This solution is a function, not a program.

If you have a TI-89/92/V200, you can download the full project here (outdated):

https://rapidshare.com/files/154945328/minfib.zip

Good luck coaxing RapidShare to give you the actual file.  Does anyone know of a good host for files this big?  8940 is an awful lot of bytes.


Perl

Some say perl is a language full of ascii noise and random symbols like $... That is not true :P

s zzHelloq worldmz and s zqzchr 44ze and s zmzchr 33ze and print

  Let's break this up into subexpressions:
(s zzHelloq worldmz) and (s zqzchr 44ze) and (s zmzchr 33ze) and (print)

 It should be obvious that it executes from left to right as long as every expression returns true. But what on earth is s zqzchr 44ze?
In perl, there is a group of "quote-like operators" which includes  q(str), qw(li st), /regex/, s/from/to/ among other things. It turns out all of these operators can use almost any character as a delimeter, with a couple pecularities: opening parethesis has to be closed by a matching closing parenthesis, and if you wish to use a letter as a delimiter you have to put a space after the operator letter (to disambiguate it from a bareword).
In this case we see three uses of the s/// (regex substitution) operator:
s//Helloq worldm/
s/q/chr 44/e
s/m/chr 33/e
All delimited by the character z. The /e flag on the last two causes the substitution to be interpreted as code to be evaluated, rather literal text.
A fairly well-known fact about perl is that most operations default to operating on the $_ builtin variable unless otherwise specified. All these three substitutions and the print operate on $_ in this case, so first we put the words Hello world into the variable, then we fix the punctuation by using the numeric ascii values of the characters, then we print the contents of the variable.


Use // as a replacement
When you define a bunch of replacements, e.g.:
/a/b//c/d//e/f//g/h//i/j//k/l//m/n//o/p//q/r//s/t//u/v//w/x//y/z/

(65 bytes).
You can use // as a replacement:
/~/\/\///a/b~c/d~e/f~g/h~i/j~k/l~m/n~o/p~q/r~s/t~u/v~w/x~y/z/

(61 bytes).


GolfScript (339 303 302 301 294 chars)

n/{{{32|}%}:L~['']{{`{\+}+'HHeLiBeBCNOFNeNaMgAl
PSClArKCa TiVCrMnFe

ZnGaGeAsSeBrKrRbSrYZr
MoTcRuRhPdAgCd

TeIXe
BaLaCePrNdPmSmEuGdTbDy
ErTm
Lu
TaWRe
IrPtAuHgTl

AtRnFrRaAcThPaU

AmCm

EsFmMd
LrRfDbSg

MtDsRg
UutFl
Lv'{[1/{.0=96>{+}*}/]}:S~:^/}%.{L}%2$?.){=S{^?}%`+p 0}{;{L.,2$<=},.}if}do}%;

With credit to PhiNotPi whose observation on unnecessary elements allowed me to save 33 chars.

This is IMO much more idiomatic GolfScript than the previous recursive approach.

Note that I allow words in the dictionary to be mixed case (L is a function to lower-case text on the assumption that it doesn't matter if non-alpha characters get broken) but reject any with apostrophes or accents.

Since this is code golf, I've optimised for code length rather than speed. This is horrendously slow. It expects the word list to be supplied at stdin and outputs to stdout in the format:

"ac[89]"
"accra[89 6 88]"
"achebe[89 2 4]"
...

(lower-casing any mixed-case input words for which it finds a match).

If you're more interested in the elements than the numbers per se, for the low low price of 261 253 chars you can use

n/{{{32|}%}:L~['']{{`{\+}+'HHeLiBeBCNOFNeNaMgAlPSClArKCaTiVCrMnFeZnGaGeAsSeBrKrRbSrYZrMoTcRuRhPdAgCdTeIXeBaLaCePrNdPmSmEuGdTbDyErTmLuTaWReIrPtAuHgTlAtRnFrRaAcThPaUAmCmEsFmMdLrRfDbSgMtDsRgUutFlLv'[1/{.0=96>{+}*}/]/}%.{L}%2$?.){=p 0}{;{L.,2$<=},.}if}do}%;

which gives output like

"Ac"
"AcCRa"
"AcHeBe"
...


C, 106

Size is 74 chars if allowed to rename program "W00WG5WW1GW66WG4WW2GW33WG"

main(int i,char**s){
    for(s[0]="W00WG5WW1GW66WG4WW2GW33WG";i=*s[0]++;putchar(s[1][i&7]-49?i==71?10:32:42));
}

running:

./a.out 1101101
 **
   *
 **
*
 **

notes:

'W' and 'G' (0x47 and 0x57) are chosen such that the value & 7 = 7, i.e they safely index the null character that terminates the input string.


Python 2, 74 bytes

lambda l:max(reduce(lambda i,x:i+(a+i*(b-a)==x),l,0)for a in l for b in l)

Try it online!

Tries every possible sequence of the form a,b,... with a and b in the input l.

To find the smallest index i of this arithmetic progression that's outside l, we do something a bit unusual. Instead of counting up the progression to find an element not in l, we iterate over l, taking advantage of it being sorted. For each successive element x of l, we move to the next index in the arithmetic progression if its current value matches x, and stay at the current index otherwise.


Use symbolic identifiers
From The Definition of Standard Ml (revised) [PDF], Section 2.4:

An identifier is either alphanumeric: any sequence of letters,
digits, primes (') and underbars (_) starting with a letter or
prime, or symbolic:  any non-empty sequence of the following symbols:
!  %  &  $  #  +  -  /  :  <  =  >  ?  @  \  ~  ‘  ^  |  *

In either case, however, reserved words are excluded. This means that for
example # and | are not identifiers, but ## and |=| are identifiers.

The important part (concerning golfing) is that you do not need white space between symbolic identifiers and alphanumeric identifiers or keywords.
Example

fun f a b c=if b then a else c

By replacing f by $ and b by !, we can save 6 bytes:
fun$a!c=if!then a else c

Note, however, that a symbolic identifier needs white space when next to other symbols. That's why we cannot replace a and c in the above example to get to the same byte count:
fun f$b!=if b then$else!    (* syntax error because != is parsed as one token *)


Python (Symbols, 87 82)

from string import punctuation
from string import digits
print digits
print punctuation

I just love Python's string module...

Edit:

from string import punctuation as p
from string import digits as d
print d
print p

Output:

0123456789
!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~

FALSE (Letters, 21) DUP (Letters, 20):

FALSE solution:

65[$91\>][$,$32+,1+]#

DUP sollution (1 char shorter)

65[$91<][$,$32+,1+]#

Output (for both):

AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz

Interpreter for FALSE.

Total: 102


Restricted mini challenges Robbers Thread

Haskell, xnor

s=show s
ss=show[[s]]
w h=[ss!!h]<show[h]

Try it online!

The first line defines s as the fixed point of the show function, which is the infinite string

"\"\\\"\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\...

It has "s at indices 0, 2, 6, 14, 30… Powers of two, minus two.

The second line defines ss as the string

[["\"\\\"\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\\\\\\\\\\\\\\\...

It has non-\s at indices 0, 1, 2, 4, 8, 16, 32… Powers of two, ignoring 0.

We’re in luck: in ASCII, " < [ < \, so we can write an indicator function for the less-than-backslashes in this string, and we’re done!

w h is our answer: it checks if the h’th element of ss is less than a backslash. Well, we can’t construct a string containing only a backslash, so we construct some other string that’s always bigger than "[", namely show[h].


GolfScript, 73 characters
n%(' '-:C;~:T,,1>{T/zip{.,1>*.&.,1=*}%''*C&C=},.{0=T/n*}{'no solution'}if

Breaks at the first position which is possible. The input must be given on STDIN in the format specified in the question.
Example (online):
X Y
abcdeXfYghijklmnXoYpqrstuvwXxYyzXYZ

abcdeXfYghi
jklmnXoYpqr
stuvwXxYyzX
YZ

Annotated code:
n%               # Split the input at newlines
(' '-:C;         # Extract the first line, remove all spaces
                 # and assign the resulting string to variable C
~:T              # Take the second line and assign this string
                 # to variable T
,,1>             # Makes an array [1 2 3 ... L-1] where L is the
                 # length of T
{                # A filter block {...}, selects all possible
                 # line wrap positions from this array
  T/             #   Test the current length by splitting T (input)
                 #   in pieces
  zip            #   Transpose the result (i.e. we now have a array
                 #   of strings representing the columns)
  {              #   For each column
    .,1>*        #     Is the length greater than one, then keep the column
                 #     else transforms it to the empty string (string * 0)
    .&           #     "and"s the string with itself, i.e. the result
                 #     is a string of the distinct characters in the column
    .,1=*        #     If the length is 1 (i.e. only one character) keep
                 #     the column, otherwise reduce it to the empty string
  }%
  ''*            #   Combine the resulting characters into a string again
  C&C=           #   Check if this string contails all characters from C
},
.{               # If the filter returns at least one possible wrap position
  0=             #   Take the first one
  T/n*           #   Split the string and join again with newlines
}{               # Else
  'no solution'  #   Return 'no solution'
}if              # Endif


05AB1E, 14 bytes

*Š*‚[ICÓ-W_iõq

Try it online!

Uses p instead of b, because pink is prettier than black.

Explanation:

*             # number of white shirts * durability of white shirts
 Š            # swap
  *           # number of pink shirts * durability of pink shirts
   ‚          # pair the two products in a list
[             # infinite loop
 I            # get the next input
  =           # print (only in the TIO version, not actually needed)
   C          # convert from binary (this yields 51 for p and 58 for w, don't ask why)
    Ó         # list of exponents in the prime factorization
     -        # subtract from the durability list
      W_i     # if the minimum of the list is now 0
         õq   # exit without printing anything


Largest Number in Brainfuck BigInt for each program length up to 50 instructions


Java 5218

This is the (golfed) code:

class a{int[]a=new int[5];public static void main(String[]a){new a().b(1,1);}void b(int t,int p){if(t>4)for(t=0;++t<=p&&4%p==0;)System.out.print(a[t]);else{a[t]=a[t-p];b(t+1,p);for(a[t]=a[t-p];++a[t]<=9;)b(t+1,t);}}}

It prints a specially crafted sequence to stdout. The completed sequence has all combinations, only once, in the shortest way possible. The total length is 10.000 with the first combination after 4 (obviously) and the last after 10.000. So if I understand the challenge correctly my score is:

4 + ((10000-4)/2) = 5002 avg length to break the code
5002 + 216 (code length) = 5218

Obviously this score will be improved (Java is pretty verbose), so I'm not going to tell you the name of the sequence I'm using...


Pyth, 33 30 - 25 = 5 bytes

Jiz8K+lzQ%"%0*o",KuxG/G8rQ^2KJ

Run it by input from stdin like (online interpreter: https://pyth.herokuapp.com/):

111
3

and the result will be written to stdout.

This is a direct translation of:

Python 2, 127 118 79 - 25 = 54 bytes

def i(s,k):
 l=int(s,8);t=len(s)+k
 while k<1<<t:l^=l/8;k+=1
 print'%0*o'%(t,l)

Call it like i("111", 3), and the result will be written to stdout.

Note that we expect k not being too large, since for code-golfing purpose the inner loop will run for O(2k) times.

I think we usually call this operation "xorshift" or something. If we express the input as big-endian integers, then the function f is simply:

f(x) = x ⊕ (x ≫ 1)

If we apply f twice we will get:

f2(x) = x ⊕ (x ≫ 2)

However applying 3 times will have a different pattern:

f3(x) = x ⊕ (x ≫ 1) ⊕ (x ≫ 2) ⊕ (x ≫ 3)

Applying 4 times get back to the basic form:

f4(x) = x ⊕ (x ≫ 4)

And so on:

f2k(x) = x ⊕ (x ≫ 2k)

Note that if we choose a big-enough 2k, then (x ≫ 2k) = 0, meaning f2k(x) = x, and the inverse is trivially the identity function!

So the strategy for finding f-k(x) without calling f-1(x) at all is:

Find K such that:

K ≥ k
K > log2 x
K is a power of 2

Express f-k(x) = f-K + (K-k)(x) = f-K(fK-k(x)) = fK-k(x)
Thus, the result is f called K-k times
25 chars profit :p

Update 1: Used octal representation instead of binary so that we could use % formatting to save lots of bytes.

Update 2: Exploit the periodic structure of f. Retired the iterative version since the non-iterative one is shorter even without the -25 bytes bonus.

Update 3: Reduced 3 bytes from Pyth, thanks isaacg!


Python 3, 142 151 148 bytes

import re
l=dict(re.findall("(\D+)(\d+)",input()))
m=lambda k:int(l.get(k,0))
print(m("C")and m("C")+1+(m("N")-sum(map(m,"F I H Cl Br".split())))/2)

Returns 0 on error.

Thanks to @HyperNeutrino bringing the bytes down.

Try it online!


Determine the position of a non-negative number in the infinite spiral

Python, 46 bytes

f=lambda n:n and 1j**int((4*n-3)**.5-1)+f(n-1)

Dennis's answer suggested the idea of summing a list of complex numbers representing the unit steps. The question is how to find the number of quarter turns taken by step i.

[0, 1, 2, 2, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7]

These are generated by int((4*k-n)**.5-1), and then converted to a direction unit vector via the complex exponent 1j**_.


A doubly linked list that only stores 1 pointer per element

This is an xor linked list:

struct node {
  int myValue;
  uintptr_t xor_prev_and_next;
  node *next(node *prev) {
    return (node*)((uintptr_t)prev ^ xor_prev_and_next);
  }
  node *prev(node *next) {
    return (node*)((uintptr_t)next ^ xor_prev_and_next);
  }
}

struct list {
  node *first;
  node *last;
  int sum_forwards() {
    int sum = 0;
    node *prev = NULL;
    node *curr = first;
    while (curr) {
      sum += curr->myValue;
      prev, curr = curr, curr->next(prev);
    }
    return sum;
  }
}


K, 43 38

{d:(x;0N,x;y)@\:&~~':y;d[1]:(1_d 1),*|x;+d}

{a::*|x;+@[(x;{x,a};y)@\:&~~':y;1;1_]}

.

k){a::*|x;+@[(x;{x,a};y)@\:&~~':y;1;1_]}[1 2 3 4 5 6 7;9 9 15 15 15 30 9]
1 2 9
3 5 15
6 6 30
7 7 9

Explanation

The function takes two vectors, x and y, as input

a::*|x takes the last value of x and assigns it to a.

&~~':y returns a list of indices where the y vector changes:

k){&~~':y}[1 2 3 4 5 6 7;9 9 15 15 15 30 9]
0 2 5 6

(x;{x,a};y) creates a three element list containing

1) the x vector,

2) the function {x,a} which takes an input variable x(not to be confused with the x vector which was input into the original function) and appends a, and

3) the y vector

(x;{x,a};y)@\:&~~':y takes this three element list and applies the indices to each element
so that we return the x vector at those indices, the indices with a appended, and the y vector at those indices

k){b::*|x;(x;{x,b};y)@\:&~~':y}[1 2 3 4 5 6 7;9 9 15 15 15 30 9]
1 3 6 7
0 2 5 6 7
9 15 30 9

@[(x;{x,a};y)@\:&~~':y;1;1_] takes the matrix we've created and drops the first element of the second row.

k){b::*|x;@[(x;{x,b};y)@\:&~~':y;1;1_]}[1 2 3 4 5 6 7;9 9 15 15 15 30 9]
1 3  6  7
2 5  6  7
9 15 30 9

+ then transposes the result

k){b::*|x;+@[(x;{x,b};y)@\:&~~':y;1;1_]}[1 2 3 4 5 6 7;9 9 15 15 15 30 9]
1 2 9
3 5 15
6 6 30
7 7 9


Python 2, 55 bytes
Following JPvdMerwe suggestion:

n=input()
while`n`!=`n`[::-1]:n+=int(`n`[::-1])
print n

Python 2, 62:
n=raw_input()
while n!=n[::-1]:n=`int(n)+int(n[::-1])`
print n


JavaScript (Node.js), 33 bytes, score: 34

Expects a BigInt as input.

f=(n,x=0n,y=1n)=>y%n?f(n,y,x+y):y

Try it online!


Haskell, 132 bytes

q x=if length x==132then putStr x else fail[];main=q$(++)<*>show$"q x=if length x==132then putStr x else fail[];main=q$(++)<*>show$"

Try it online!

This is an extension of the quine

main=putStr$(++)<*>show$"main=putStr$(++)<*>show$"

which works by concatenating the data string with a quoted version (by using show) of itself and printing the result. However, this is not pristine as any characters in the data string can be removed without failing and also the $(++)<*>show$ or (++)<*> part could be dropped without the program breaking.

To fix this, a custom print function q is defined which checks the length of the given string and calls fail if it's shorter than 132. This catches the removing of any sequence from the data string and also the removals of $(++)<*>show$ or (++)<*>, as in both cases the resulting string passed to q is shorter.

In q the number 132 could be shortened to 1, 13, 32 or 2, but in each case again fail is called.

As far as I can tell, the removal of any other substring causes either an syntax or type error, so the program does not even compile in the first place. (Haskell's strict type system comes in handy here.)

Edit: Thanks to Ørjan Johansen and Shelvacu for pointing out a flaws!


Calculate the 3BV of a Minesweeper Board

MATLAB, 92 90 86 83 79 74 72 bytes
x=input('');I=@(x)~imdilate(x,ones(3));[C,N]=bwlabel(I(x));nnz(I(C)-x)+N

This solution accepts the input in the form of a 2D matrix of 0's and 1's and will display the 3BV value for the provided input.
Here is slightly modified demo in Octave for those of you without MATLAB.
Explanation
The input matrix is dilated using a 3 x 3 matrix of 1's and then inverted (using ~) which identifies all of the points that do not have mines as neighbors (1) or do (0). To determine the number of connected regions, we use bwlabel to label each connected region of 1's. The first output is the label matrix (0 where the input was zero and any value in the range 1...N where there was a 1 in the input where N is the index of the connected group that it belongs to). The second output is the number of regions (the number of clicks required to open them). The result of the bwlabel is shown in the image on the left.

We expand the first output of bwlabel using imdilate (all non-zeros are expanded) using a 3 x 3 matrix of 1's. The result is shown in the image in the middle.
To determine the remaining clicks, we then count the squares that are not in this expanded region (~imdilate()) and not a mine (-x) (white squares in the image on the right) and add this to the total number of open regions (the number of different colors in the image on the left) to get the 3BV.


Perl, 301 296 282

Edit 2: Actually, competition or not, there is no reason not to golf it a little further. Test it online.

Edit: Couple of parentheses gone, simpler regex to check for non-zero integer.

With newlines and indentation for readability:

sub i{<>=~/\S+/g}
@b=map[i],@r=0..<>-1;
print.1<=>(map{
    @a[1,0,2,4,3]=@a;
    @b=map{$i=$_;[map$b[$_][$i],@r]}@r;
    grep$a[3]
        &&($k=(($x=$_)-$a[0])/$a[3])**2<=$k
        &&pop[sort map@{$b[$_]}[$x-!!$x,$x],
                   ($_=$a[1]+$k*$a[4]),$_-/^\d+$/]
           >=$a[2]+$k*$a[5]
    ,@R=@r
}@a=map$_-shift@v,i,@u=@v=@$_),$/for([i])x<>

It requires 5.14 because of scalar (array reference) argument to pop.


The number of reachable snake orientations

Python 3 - provisional score: n=11 (n=13 with PyPy*)
Since there have been no answers in the first week, here is an example in Python to encourage competition. I've tried to make it reasonably readable so that inefficiencies can be identified easily to give ideas for other answers.
Approach

Start with the straight snake and find all the positions that can be legally reached in one move.
Find all the positions that can be legally reached from those positions, that haven't already been identified.
Repeat until no more can be found, and return the number of positions found altogether.

Code
(now with some doctests and asserts after my incorrect first attempt)
'''
Snake combinations

A snake is represented by a tuple giving the relative orientation at each joint.
A length n snake has n-1 joints.
Each relative orientation is one of the following:

0: Clockwise 90 degrees
1: Straight
2: Anticlockwise 90 degrees

So a straight snake of length 4 has 3 joints all set to 1:

(1, 1, 1)

x increases to the right
y increases upwards

'''

import turtle

def all_coords(state):
    '''Return list of coords starting from (0,0) heading right.'''
    current = (1, 0)
    heading = 0
    coords = [(0,0), (1,0)]
    for item in state:
        heading += item + 3
        heading %= 4
        offset = ((1,0), (0,1), (-1,0), (0,-1))[heading]
        current = tuple(current[i]+offset[i] for i in (0,1))
        coords.append(current)
    return coords

def line_segments(coords, pivot):
    '''Return list of line segments joining consecutive coords up to pivot-1.'''
    return [(coords[i], coords[i+1]) for i in range(pivot+1)]

def rotation_direction(coords, pivot, coords_in_final_after_pivot):
    '''Return -1 if turning clockwise, 1 if turning anticlockwise.'''
    pivot_coord = coords[pivot + 1]
    initial_coord = coords[pivot + 2]
    final_coord = coords_in_final_after_pivot[0]
    initial_direction = tuple(initial_coord[i] - pivot_coord[i] for i in (0,1))
    final_direction = tuple(final_coord[i] - pivot_coord[i] for i in (0,1))
    return (initial_direction[0] * final_direction[1] -
            initial_direction[1] * final_direction[0]
            )

def intersects(arc, line):
    '''Return True if the arc intersects the line segment.'''
    if line_segment_cuts_circle(arc, line):
        cut_points = points_cutting_circle(arc, line)
        if cut_points and cut_point_is_on_arc(arc, cut_points):
            return True

def line_segment_cuts_circle(arc, line):
    '''Return True if the line endpoints are not both inside or outside.'''
    centre, point, direction = arc
    start, finish = line
    point_distance_squared = distance_squared(centre, point)
    start_distance_squared = distance_squared(centre, start)
    finish_distance_squared = distance_squared(centre, finish)
    start_sign = start_distance_squared - point_distance_squared
    finish_sign = finish_distance_squared - point_distance_squared
    if start_sign * finish_sign <= 0:
        return True

def distance_squared(centre, point):
    '''Return the square of the distance between centre and point.'''
    return sum((point[i] - centre[i]) ** 2 for i in (0,1))

def cut_point_is_on_arc(arc, cut_points):
    '''Return True if any intersection point with circle is on arc.'''
    centre, arc_start, direction = arc
    relative_start = tuple(arc_start[i] - centre[i] for i in (0,1))
    relative_midpoint = ((relative_start[0] - direction*relative_start[1])/2,
                         (relative_start[1] + direction*relative_start[0])/2
                         )
    span_squared = distance_squared(relative_start, relative_midpoint)
    for cut_point in cut_points:
        relative_cut_point = tuple(cut_point[i] - centre[i] for i in (0,1))
        spacing_squared = distance_squared(relative_cut_point,
                                           relative_midpoint
                                           )
        if spacing_squared <= span_squared:
            return True

def points_cutting_circle(arc, line):
    '''Return list of points where line segment cuts circle.'''
    points = []
    start, finish = line
    centre, arc_start, direction = arc
    radius_squared = distance_squared(centre, arc_start)
    length_squared = distance_squared(start, finish)
    relative_start = tuple(start[i] - centre[i] for i in (0,1))
    relative_finish = tuple(finish[i] - centre[i] for i in (0,1))
    relative_midpoint = tuple((relative_start[i] +
                               relative_finish[i]
                               )*0.5 for i in (0,1))
    determinant = (relative_start[0]*relative_finish[1] -
                   relative_finish[0]*relative_start[1]
                   )
    determinant_squared = determinant ** 2
    discriminant = radius_squared * length_squared - determinant_squared
    offset = tuple(finish[i] - start[i] for i in (0,1))
    sgn = (1, -1)[offset[1] < 0]
    root_discriminant = discriminant ** 0.5
    one_over_length_squared = 1 / length_squared
    for sign in (-1, 1):
        x = (determinant * offset[1] +
             sign * sgn * offset[0] * root_discriminant
             ) * one_over_length_squared
        y = (-determinant * offset[0] +
             sign * abs(offset[1]) * root_discriminant
             ) * one_over_length_squared
        check = distance_squared(relative_midpoint, (x,y))
        if check <= length_squared * 0.25:
            points.append((centre[0] + x, centre[1] + y))
    return points

def potential_neighbours(candidate):
    '''Return list of states one turn away from candidate.'''
    states = []
    for i in range(len(candidate)):
        for orientation in range(3):
            if abs(candidate[i] - orientation) == 1:
                state = list(candidate)
                state[i] = orientation
                states.append(tuple(state))
    return states

def reachable(initial, final):
    '''
    Return True if final state can be reached in one legal move.

    >>> reachable((1,0,0), (0,0,0))
    False

    >>> reachable((0,1,0), (0,0,0))
    False

    >>> reachable((0,0,1), (0,0,0))
    False

    >>> reachable((1,2,2), (2,2,2))
    False

    >>> reachable((2,1,2), (2,2,2))
    False

    >>> reachable((2,2,1), (2,2,2))
    False

    >>> reachable((1,2,1,2,1,1,2,2,1), (1,2,1,2,1,1,2,1,1))
    False

    '''
    pivot = -1
    for i in range(len(initial)):
        if initial[i] != final[i]:
            pivot = i
            break

    assert pivot > -1, '''
        No pivot between {} and {}'''.format(initial, final)
    assert initial[pivot + 1:] == final[pivot + 1:], '''
        More than one pivot between {} and {}'''.format(initial, final)

    coords_in_initial = all_coords(initial)
    coords_in_final_after_pivot = all_coords(final)[pivot+2:]
    coords_in_initial_after_pivot = coords_in_initial[pivot+2:]
    line_segments_up_to_pivot = line_segments(coords_in_initial, pivot)

    direction = rotation_direction(coords_in_initial,
                                   pivot,
                                   coords_in_final_after_pivot
                                   )

    pivot_point = coords_in_initial[pivot + 1]

    for point in coords_in_initial_after_pivot:
        arc = (pivot_point, point, direction)
        if any(intersects(arc, line) for line in line_segments_up_to_pivot):
            return False
    return True

def display(snake):
    '''Display a line diagram of the snake.

    Accepts a snake as either a tuple:

    (1, 1, 2, 0)

    or a string:

    "1120"

    '''
    snake = tuple(int(s) for s in snake)
    coords = all_coords(snake)

    turtle.clearscreen()
    t = turtle.Turtle()
    t.hideturtle()
    s = t.screen
    s.tracer(0)

    width, height = s.window_width(), s.window_height()

    x_min = min(coord[0] for coord in coords)
    x_max = max(coord[0] for coord in coords)
    y_min = min(coord[1] for coord in coords)
    y_max = max(coord[1] for coord in coords)
    unit_length = min(width // (x_max - x_min + 1),
                      height // (y_max - y_min + 1)
                      )

    origin_x = -(x_min + x_max) * unit_length // 2
    origin_y = -(y_min + y_max) * unit_length // 2

    pen_width = max(1, unit_length // 20)
    t.pensize(pen_width)
    dot_size = max(4, pen_width * 3)

    t.penup()
    t.setpos(origin_x, origin_y)
    t.pendown()

    t.forward(unit_length)
    for joint in snake:
        t.dot(dot_size)
        t.left((joint - 1) * 90)
        t.forward(unit_length)
    s.update()

def neighbours(origin, excluded=()):
    '''Return list of states reachable in one step.'''
    states = []
    for candidate in potential_neighbours(origin):
        if candidate not in excluded and reachable(origin, candidate):
            states.append(candidate)
    return states

def mirrored_or_backwards(candidates):
    '''Return set of states that are equivalent to a state in candidates.'''
    states = set()
    for candidate in candidates:
        mirrored = tuple(2 - joint for joint in candidate)
        backwards = candidate[::-1]
        mirrored_backwards = mirrored[::-1]
        states |= set((mirrored, backwards, mirrored_backwards))
    return states

def possible_snakes(snake):
    '''
    Return the set of possible arrangements of the given snake.

    >>> possible_snakes((1, 1, 1, 1, 2, 1, 2, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 2, 2, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1))
    {(1, 1, 1, 1, 2, 1, 2, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 2, 2, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1)}

    '''
    reached = set()
    candidates = set((snake,))

    while candidates:
        candidate = candidates.pop()
        reached.add(candidate)
        new_candidates = neighbours(candidate, reached)
        reached |= mirrored_or_backwards(new_candidates)
        set_of_new_candidates = set(new_candidates)
        reached |= set_of_new_candidates
        candidates |= set_of_new_candidates

    excluded = set()
    final_answers = set()
    while reached:
        candidate = reached.pop()
        if candidate not in excluded:
            final_answers.add(candidate)
            excluded |= mirrored_or_backwards([candidate])

    return final_answers

def straight_derived_snakes(length):
    '''Return the set of possible arrangements of a snake of this length.'''
    straight_line = (1,) * max(length-1, 0)
    return possible_snakes(straight_line)

if __name__ == '__main__':
    import doctest
    doctest.testmod()
    import sys
    arguments = sys.argv[1:]
    if arguments:
        length = int(arguments[0])
    else:
        length = int(input('Enter the length of the snake:'))
    print(len(straight_derived_snakes(length)))

Results
On my machine the longest snake that can be calculated in under 1 minute is length 11 (or length 13 with PyPy*). This is obviously just a provisional score until we find out what the official score is from Lembik's machine.
For comparison, here are the results for the first few values of n:
 n | reachable orientations
-----------------------------
 0 | 1
 1 | 1
 2 | 2
 3 | 4
 4 | 9
 5 | 22
 6 | 56
 7 | 147
 8 | 388
 9 | 1047
10 | 2806
11 | 7600
12 | 20437
13 | 55313
14 | 148752
15 | 401629
16 | 1078746
17 | MemoryError (on my machine)

Please let me know if any of these turn out to be incorrect.
If you have an example of an arrangement that should not be able to be unfolded, you can use the function neighbours(snake) to find any arrangements reachable in one step, as a test of the code. snake is a tuple of joint directions (0 for clockwise, 1 for straight, 2 for anticlockwise). For example (1,1,1) is a straight snake of length 4 (with 3 joints).
Visualisation
To visualise a snake you have in mind, or any of the snakes returned by neighbours, you can use the function display(snake). This accepts a tuple like the other functions, but since it is not used by the main program and therefore does not need to be fast, it will also accept a string, for your convenience.
display((1,1,2,0)) is equivalent to display("1120")
As Lembik mentions in the comments, my results are identical to OEIS A037245 which does not take into account intersections during rotation. This is because for the first few values of n there is no difference - all shapes that do not self-intersect can be reached by folding a straight snake. The correctness of the code can be tested by calling neighbours() with a snake that cannot be unfolded without intersection. Since it has no neighbours it will contribute only to the OEIS sequence, and not to this one. The smallest example I am aware of is this length 31 snake that Lembik mentioned, thanks to David K:
(1,1,1,1,2,1,2,1,1,1,1,1,1,2,1,1,1,2,1,1,2,2,1,0,1,0,1,1,1,1)
display('111121211111121112112210101111') gives the following output:

Tip: If you resize the display window and then call display again, the snake will be fitted to the new window size.

I'd love to hear from anyone who has a shorter example with no neighbours. I suspect that the shortest such example will mark the smallest n for which the two sequences differ.

*Note that each increment of n takes very roughly 3 times as long, so increasing from n=11 to n=13 requires almost 10 times the time. This is why PyPy only allows increasing n by 2, even though it runs considerably faster than the standard Python interpreter.


Find amount of heads and tails from percentages

Dyalog APL, 3 bytes

,÷∨

This is a dyadic function train that accepts the percentages as left and right arguments:

┌─┼─┐
, ÷ ∨

It is equivalent to the following, train-less function:

{(⍺,⍵)÷⍺∨⍵}

Try it online on TryAPL.

How it works

  ∨  Compute the GCD of both arguments.
,    Concatenate both arguments.
 ÷   Divide the latter by the former.


PowerShell, 262 155 151 127 125 95 bytes

$args|sort{"rlyegwbrscbrocpyrvo lvnfaldgccvmacmcvseraolsrygpptwkpnoeb".indexof((-join$_[3,0]))}

Try it online!

Naive approach. PowerShell sort-object can sort based on a script block that gets executed for every object. Here we're simply getting the .IndexOf() the color from a string, which will assign a numerical value to each color, and then sorts based on those numbers. The string is constructed from the fourth and first letters of each color to ensure uniqueness. Output is implicit.

-4 bytes thanks to Shaggy.
-2 bytes thanks to mazzy.
A whopping -30 bytes thanks to KGlasier.


Python 2, URL length = 170 bytes

https://tio.run/##K6gsycjPM/r/v9hWqQDCjqlISwPhYlvVIuvM3IL8ohKFpMTiVDMT64KizLwS9YySkoJiK339ksx8vaLSPH1lZXVtiAK9JDOT1Lzk/JRUDY1iVdViTT0YT70qJzNJXVMz2shK1yRWE2aHEkUW4Db//38A

s="python2\xff\xffs=%r;import base64;print'https://tio.run/##'+base64.b64encode((s%%s).encode(('zlib'))[2:-4])\xff\xff";import base64;print'https://tio.run/##'+base64.b64encode((s%s).encode(('zlib'))[2:-4])

Try it online!

This relies on three coincidences:

The default zlib level 6 happens to give the same results as zlib level 9 for this string, modulo the header that I strip.
The compressed length is divisible by 3, so base64 does not generate any = padding characters.
The base64 output does not contain any + characters.


C golfing tips - returning 0 without return statement

You don't need to do anything.
This assumption:

then program will use result of last operation

is erroneous. If there is no return statement, main returns 0. It is not dependent on whatever might be left over in registers or anything like that.
From the standard:

5.1.2.2.3 Program termination
If the return type of the main function is a type compatible with int, a return from the initial call to the main function is equivalent to calling the exit function with the value returned by the main function as its argument; reaching the } that terminates the main function returns a value of 0.  If the return type is not compatible with int, the termination status returned to the host environment is unspecified.

(emphasis mine)
Your program's main already returns zero, or something is wrong somewhere else.


JavaScript (ES6), 131 bytes

Outputs 0 as the tap character.

r=>l=>`  ${g=n=>n?s.replace(/./g,(_,x)=>[,a=x%(k/r),x%=k/l,a*x][n]&&' '):++k%l|k%r?'-'+g():`-
`,s=g(k=0)}R ${g(1)}L ${g(2)}M `+g(3)

Try it online!

How?

We use the same helper function \$g()\$ for two different purposes.

When \$g()\$ is called with no argument or an argument equal to \$0\$, it recursively builds the hyphen string of length \$k=\operatorname{lcm}(l,r)\$ with a trailing linefeed:

g = _ => ++k % l | k % r ? '-' + g() : `-\n`

This string is saved in \$s\$.

When \$g()\$ is called with \$1 \le n \le 3\$, it generates a tap string by replacing each hyphen at position \$x\$ in \$s\$ with either a space or \$0\$:

g = n => s.replace(/./g, (_, x) => [, a = x % (k / r), x %= k / l, a * x][n] && ' ')


CJam, 53 52 46 38 37 bytes

3,q~f{f&:L,{L=},}$~ff{-z}_z+::e<W+:e>

Takes input on STDIN as a CJam style array:

[0 1 2 3]

Here is a test harness which converts all the test cases to this format and runs the code on them. Although the results are in the input field, they are not used by the code (remove them if you don't trust me :)).

Explanation

First, we parse the input to get the two sets A and B:

3,q~f{f&:L,{L=},}$~
3,                  "Push [0 1 2]. 1 is for A, 2 is for B, and 0 we can luckily ignore
                     as we'll see later.";
  q~                "Read and evaluate the input.";
    f{          }   "Map this block onto the [0 1 2] array, copying in the input for
                     each iteration.";
      f&:L          "Take the bitwise AND with each element of the input and store the
                     result in L.";
          ,{  },    "Get the length N, and filter the range [0 .. N-1] by evaluating
                     the block for each element.";
            L=      "Check if the bitwise AND at that index yielded something non-zero.
                     This gives an empty array for 0, A for 1 and B for 2.";
                 $  "Sort the three arrays. This has two important effects: a) it moves
                     the empty array resulting from 0 to the front, and b) if only one
                     of A and B is empty, it moves the non-empty one to the end.";
                  ~ "Unwrap the array, dumping all three sets on the stack.";

And now we find the absolute differences and select the max of the mins:

ff{-z}_z+::e<W+:e>
ff{-z}             "Turn A and B into a matrix of absolute differences.";
      _z           "Duplicate and transpose.";
        +          "Add the two together, so I've got one row of distances for
                    each element in either A or B.";
         ::e<      "Find the minimum of each row.";
             W+    "Add a -1 in case one set was empty.";
               :e> "Get the overall maximum.";

Note that we've kept the empty array resulting from the initial 0 at the bottom of the stack all the time, but empty arrays don't contribute anything to the output.


JavaScript (ES6), 73 54 50 bytes
(Saved some bytes thanks to @LeakyNun, the edited challenge, and @CraigAyre.)
s=>s.match(/../g).map((c,i)=>('0x'+c)/(i-3?1:255))

let f=

s=>s.match(/../g).map((c,i)=>('0x'+c)/(i-3?1:255))

console.log(f('00ff0080'));


APL (Dyalog Extended), 5 bytes

⊣÷⍥!-

⊣      left argument
 ÷⍥!   divide over factorial, apply factorial to both arguments and then divide
    -  subtract

Try it online!


Ruby 2.0, 69 bytes

#!ruby -Kn0rdigest
p'×ñF<ìX‚É²Ÿ_'.index Digest::MD5.digest(gets)[0]

Hexdump (to faithfully show the binary data in the string):

00000000  23 21 72 75 62 79 20 2d  4b 6e 30 72 64 69 67 65  |#!ruby -Kn0rdige|
00000010  73 74 0a 70 27 d7 f1 46  3c 1f ec 58 82 c9 b2 9f  |st.p'..F<..X....|
00000020  5f 02 27 2e 69 6e 64 65  78 20 44 69 67 65 73 74  |_.'.index Digest|
00000030  3a 3a 4d 44 35 2e 64 69  67 65 73 74 28 67 65 74  |::MD5.digest(get|
00000040  73 29 5b 30 5d                                    |s)[0]|

Explanation:

The -Kn option reads the source file as ASCII-8BIT (binary).
The -0 option allows gets to read in the whole input (and not just one line).
The -rdigest option loads the digest module, which provides Digest::MD5.
The code then does an MD5 of the input, takes the first byte of the digest, and gets its index in the given binary string.


Perfect timing for this question. @isaacg just added a new feature today, that allows to shorten such numbers immensely.

The basic technique is to convert the number to base 256 and convert it to chars. You can do this using the code ++NsCMjQ256N. You can then use the resulting string in combination with C, which does exactly the opposite (convert chars to int and interpret the result as base-256 number). So you get 13 chars: C"2ìÙ½}ü¶d". Some of the chars are unprintable.

But notice that I said 13 CHARS, not bytes. If I copy the chars and count the with https://mothereff.in/byte-counter, it says 13 chars and 18 bytes. This is due the character encoding of chars, which is UTF-8 by default. And UTF-8 only allows 2^7 different 1-byte character. Every char c with ord(c) > 127 actually gets stored using two bytes instead of one.

And here come's @isaacg's new feature into play. He changed the default code-format from UTF-8 to iso-8859-1. iso-8859 can represent 256 characters with only 1 byte. So now you can actually reach 13 BYTES. This is only possible with the standard compiler though, this doesn't work in the online compiler.

First you want to convert the number to hex-values by using this script: jdm.[2.Hd"0"jQ256. This gives you  12 32 ec d9 bd 07 7d fc b6 64.  Afterwards copy those numbers into your code-file using a hex-editor (e.g. hexedit for linux).

Notice:

Obviously you remove the " at the end, if the string is the last part of the code.
This only works if there is no 34 (the byte 22) in the base-256 representation of you numbers, since this is the " char and will end the string. Escaping works though (5C 22).
Btw, when you open a file with a hex-editor you will likely see the byte 0A or 0d 0a at the end, which you can remove. This only indicates the end of the line.


Calculate the points in a "sjoelen"-game

CJam, 23 21 20 bytes
q~_$0=f+1m>{X):X*+}*

I might be able to golf a couple of bytes off this.
Input is like
[3 5 4 3]

Output is the score
70

How it works
q~                         "Read the input and evaluate into an array";
  _$0=                     "Copy the array, sort it and get the minimum number";
                           "This minimum is the number of common schijven";
      f+                   "Increment each of the schijven by the common schijven number";
        1m>                "Take 1 element from the end of the array and put";
                           "it in the beginning";
           {      }*       "Reduce the elements of the array based on this block";
            X):X           "Increment and update the value of X (initially 1)";
                *          "Multiply the number of schijven with X";
                 +         "Add it to current score";

Algorithm

Since I have right shifted the number of schijven, the score order now becomes [1 2 3 4].
Moreover, using the fact that 1 + 2 + 3 + 4 = 10, I simply add the minimum common schijven to each one to get the effect of bonus 10 score.
Now when I reduce, I get 2 elements initially on stack, the first one, which I ignore is the one with a score of 1 each, then I multiply the second one with 2 and add it to first. In the next iteration, I get the current sum and score 3 schijven. And so on.

Try it online here


Jelly, 9 bytes, cracks @Dennis' answer

²sµUFḤ$¦G

Try it online!

Should be correct now; I had to rather rethink what I was doing.

Explanation

The hardest part of this problem is getting a list of the even indices inside the ¦ (which applies an operation at specific indices). Unlike most operations, which use the input to the whole program as a default for the second operand, ¦ uses the most recently seen value as a default (because it conceptually has two left operands, rather than a left and a right operand like most things that take in two values).

However, we can observe that we have a list of numbers, including all integers from 1 to half the input, already in the current value at the time. As such, flattening and doubling it gives us a list of even numbers, including all the even indices (also some other even numbers but we don't care about those). It's even possible to spend one µ solely to avoid a parsing ambiguity and still come in within 9 characters.

²sµUFḤ$¦G
 s         Split
²          {the list of numbers from 1 to} the square of {the input}
  µ        into a number of pieces equal to {the input};
   U       then reverse
       ¦   the elements at indexes
    F      obtained by flattening the split list
      $    and
     Ḥ     doubling each element in the flattened list;
        G  finally, format it into a grid.


Find patterns in numbers based on the similarity of characters?

Python 2, 48 46 bytes

Saved two bytes thanks to @ovs!

s=set(''.join(l))
while s:s&=set(l[input()-1])

Try it online!

Renamed numbers to l. If that's not okay then add 10 bytes for l=numbers.


Haskell, 27 16 bytes

This function checks whether x is contained in the list of nonnegative integers that are not greater than x.

f x=elem x[0..x]

Try it online!


Ruby - 312 306 285 273 269 259 characters

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

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

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

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

Ungolfed version (expects input in variable string):

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


R, 61 bytes

cat(paste0(c("  1
 ","","
","9 ","
 ","","
  "),sample(2:8)))

Try it online!

Prints alternately the proper whitespace/newline (with 1 and 9 included) and elements of a random permutation of \$\{2,\ldots,8\}\$.


Print the total length of all "quoted" characters

APL (Dyalog Unicode), 36 bytesSBCS

Full program. Prompts for input from stdin.

≢∊t⊣{t,←'(.)(.*?)\1'⎕S'\2'⊢⍵}⍣≡⍞⊣t←⍬

Try it online!

t←⍬ set up an accumulator t (for total)

⍞⊣ discard that in favour of string input from stdin (symbol: quote in console)

{…}⍣≡ apply the following anonymous lambda until stable (fix-point; previous ≡ next)

 ⊢⍵ on the argument

 …⎕S'\2' PCRE Search for the following, returning group 2 for each match:

  (.) any character (we'll call this group 1)
  (.*?) as few characters as possible (we'll call this group 2)
  \1 the group 1 character

 t,← update t by append that to t's current value

t⊣ discard that (the final list of no matches) in favour of t

≢ count the number of characters in that


C, 192 bytes

i;g(s,b,i,n,j)char*s,*b;{for(b[i+1]=0;b[n+j];++n)s[n]-b[n+j]&&(n=-1,++j);return n;}f(char*s){char*b=calloc(strlen(s),1);for(i=0;s[i];)i=(b[i]=putchar(rand()%95+32))-s[i]?i?g(s,b,i,0,0):0:i+1;}

Try it online!

It's a mess now, but at least it works even for the corner cases...

C,  63   62  61 bytes

Thanks to @Jonathan Frech for saving a byte!

i;f(char*s){for(i=0;s[i=putchar(rand()%95+32)-s[i]?0:i+1];);}

Try it online!


Most complex "Hello world" program you can justify

C++, trollpost

  Most complex “Hello world” program you can justify

#include <iostream>

using namespace std;

int main(int argc, char * argv[])
{
    cout << "Hello, world!" << endl;
    return 0;
}

My brain cannot justify writing a longer one :)


Make the pattern from composition notebooks

Mathematica

Blur[Binarize[Blur[RandomImage[1, {1000, 1000}, ImageSize -> Large], 6], .52]]

Quite simple. Creates a random grayscale image, blurs it, takes the pixels above a threshold, and blurs it again. It uses a couple of hand-tweaked values. The result:


Many script languages, 6 UTF-8 bytes

It doesn't print ASCII art, but...

""

The character in the quote is the unicode character penguin (U+1F427) (if you want to see the penguin above, download the Symbola font). It looks like this (but a lot smaller):


Work out \$x^y\$ using only addition and subtraction

APL (Dyalog Unicode), 7 bytesSBCS

Anonymous tacit infix function. y is left argument and x is right argument.

(+/⍴)/⍴

Try it online!

⍴ cyclically reshape (gives y copies of x)

(…)/ reduce by the following function:

 ⍴ cyclically reshape to left argument copies of right argument

 +/ sum


Scala 168 228

My first submission had a bug where it didn't consider multiple insertions at the same point in the input string.

After

val k = 1
val s = "1111011010"

The code that counts is:

def e(k:Int,s:String):Set[String]=if(k<1)Set(s)else e(k-1,s).flatMap(e=>"01"map(_+e))++(if(s=="")Set()else e(k,s.tail).map(s.head+_)++e(k-1,s.tail).flatMap(e=>(Set("0","1","")-(s take 1))map(_+e)))
print(e(k,s))

To run, save both sections together as a file and run like:

$ scala distancek.scala
Set(111111010, 111101010, 1111001010, 11110011010, 1101011010, 11101011010, 111101101, 111101100, 11111011010, 1111011011, 1111011000, 11110101010, 1111010010, 11110110110, 11110110101, 111101110, 11110110010, 0111011010, 1110011010, 11110110100, 10111011010, 11011011010, 01111011010, 1011011010, 1111111010, 111011010, 11110111010, 1111011110)
$

Recursive function to build the edited strings. k is the number of edits remaining, s is the string to edit. Slightly ungolfed:

def e(k:Int,s:String):Set[String]=
  if(k<1) Set(s)                           // No edits left
  else e(k-1,s).flatMap(e=>"01"map(_+e))++ // Insert a character, consume an edit, continue from the same point
      (if(s=="") Set()                     // We're at the end of the string so only insertions are allowed
       else e(k,s.tail).map(s.head+_)++    // skip past this character, making no edit
       e(k-1,s.tail).flatMap(e=>(Set("0","1","")-(s take 1))map(_+e))) // replace this character with its inverse or ""

Note that each step makes at least one of k, s smaller so we're guaranteed to terminate.

First submission (Incorrect)

print((0 to 10).permutations.flatMap{i=>((s.map(_+""):+"")zip i).:\(Set("")){case((s,i),a)=>a.flatMap{a=>(if(i<k)Set(1+s,0+s,"","0","1")-s else Set(s))map(_+a)}}}toSet)

We take the permutations of 0..10 and zip them with the word s + a terminal "" (for insertions at the end).
All the positions < k are positions where an edit should occur. For each edit we replace the string at that position with

Set(1+s,0+s,"","0","1")-s # don't count substituting s for itself as an edit.

and finally convert to a set to remove duplicates.


Python 2.7 + xkcd,  55 bytes

xkcd is a third-party Python package. In Python, there is a package for everything!

lambda n:[xkcd.getComic(n).altText][n==859]
import xkcd

  For 404: urllib2.HTTPError: HTTP Error 404: Not Found

  For 859: IndexError: list index out of range


CJam, 58 56 42 bytes

I am sure this is too long and can be golfed a lot. But here goes for starters:

86400q':/:d_,({60bd\/}{~*i60b{s2Ue[}%':*}?

Try it online here


Vim 8 + unimpaired.vim, 93 89 85 70 73 71 bytes

-4 bytes thanks to tsh
-2 bytes thanks to Ian Emnace
-2 bytes thanks to FatalMerlin
-1 byte thanks to tsh/ckjbgames

:s/ /+/g
D:e http://google.us/complete/search?client=gma&q="
d3f";D]yy

As a bonus, the last bytes look like they're winking at you ;D Since this contains non-printing characters, the explanation contains substitutions (and I've replaced the pre-querystring part of the url with [url], for brevity):

:s/ /+/g<CR>D:e [url]?client=gma&q=<C-R>"<CR>d3f";D]yy
:s/ /+/g<CR>                                           " Replace spaces with +
            D                                          " Delete and yank result
             :e                                        " Type :e ('edit' command) and a space
                [url]?client=gma&q=                    " Type the url, except the query
                                   <C-R>"              " Paste from the default register
                                         <CR>          " Execute the command, which opens the response
                                                       "   in a new buffer
                                             d3f"      " Delete through the first three quotation marks
                                                       "   This deletes everything before the suggestion
                                                 ;     " Repeat motion; this jumps to the next \"
                                                  D    " Delete everything from there, leaving only the suggestion
                                                   ]yy " unimpaired.vim C string unescape to handle escaped '

As far as running goes, it works fine if you save it to a file named script and run with vim -s script input.txt on macOS, at least. It doesn't work if you add -u NONE, but it works fine if my .vimrc is empty. I assume it is using something from the system .vimrc to make the URL stuff work. This means, however, that it doesn't work in V, so no TIO link.

Some more test cases:

'what' => 'whataburger'
'what ' => 'what time is it' (Seriously? People Google that?)

What I really need is a way to open a URL with spaces in it. Replacing them with + first is just too many bytes!


LabVIEW, 32 LabVIEW Primitives

Reads line by line and concatenates numbers space and newlines, then deletes a trailing number, space and newline.