APL (Dyalog Unicode), 193 bytes

{G←{⍵⊃⍨⊃⍋(+/' '=,)¨⍵}
G{s←,30-⍳,⍨61
G,⊢∘⊂⌺30 30⊢((≢a)/⍪' '~⍨,x)@(B∘.+a)⊢''⍴⍨(⍴b)+⊃⌈/a←(⊢-⌊/)(⊃+/)¨s×⊂⍵}¨o/⍨(⍱/X∊⍨+/,-/)¨o←,∘.,⍨⊂¨∪{⍵/⍨0<2⊥¨×⍵}(,B∘.-⍸b<(1∊⊢)⌺3 3⊢b)~X←,B∘.-B←⍸b←(⍉0,⌽)⍣4⊢' '≠x←⍵}

Try it online!
A monadic dfn that takes a matrix of characters and returns the 30-by-30 matrix of a possible tiling with minimal blanks. Runs in 5 seconds for the smallest test case and in under a minute for the last one.
The idea
The task looks pretty straightforward at first glance, but it was surprisingly hard to derive a valid solution, and even harder to get one that "runs in a reasonable amount of time" (which somewhat explains why it was unanswered so far).
The first obstacle was that there are infinitely many possible tiling vectors. I solved this by limiting the vectors to the ones where the original tile and the moved tile share at least a point. If ab is the given tile, this means the following movements are considered as tiling vector candidates:
                                        AB   AB  AB  AB   AB
ABab    ab   ab  ab  ab   ab    abAB  ab    ab   ab   ab    ab
      AB    AB   AB   AB    AB

Then I filter out redundant ones (keeping only one of \$v\$ or \$w\$ when \$v = -w\$), generate all possible pairs of these candidate tiling vectors, and only keep the ones \$v, w\$ where neither \$v+w\$ nor \$v-w\$ movement overlaps with the original tile.
Reasoning: We know that the pairs of tiles at offsets \$(0, v)\$ and \$(0, w)\$ do not overlap, and therefore \$(v, v+w)\$ and \$(w, v+w)\$. Once it is known that \$(0, v+w)\$ and \$(v, w)\$ (alternatively \$(0, v-w)\$) pairs are safe, we know that \$(0, v, w, v+w)\$ are mutually safe, and by translation in four directions \$v, w, -v, -w\$, the entire infinite tiling is safe.
Given a full list of candidate vector pairs, I chose a naive way: for each vector pair, generate a large enough board of actual tiling, extract all 30-by-30 regions, and choose the one with the smallest number of blanks. For that, I used \$-30 \le a,b \le 30\$ for the formula \$av + bw\$. In order to prevent the memory (and execution time) blowing up, I apply this filtering twice, first within each vector pair, and then across all minimally chosen boards.
Ungolfed
The code changed a lot while golfing, but the core idea remains the same.
f←{
  ⍝ A boolean matrix where 1 means non-blanks, padded once to all directions
  bool←(⍉0,,∘0)⍣2⊢' '≠x←⍵
  ⍝ Spread 1s to adjacent cells (8 directions)
  padded←({1∊⍵}⌺3 3>⊢)bool
  ⍝ Extract the coordinates of ones
  cbool←⍸bool
  cpadded←⍸padded
  ⍝ badoffs: All offsets that move a cell to already occupied cell
  ⍝ offs: All offsets that move a cell to a cell adjacent to the tile,
  ⍝       badoffs removed and (negative, any) and (zero, negative) removed
  offs←∪{⍵/⍨0<2⊥¨×⍵}(,cbool∘.-cpadded)~badoffs←,cbool∘.-cbool
  ⍝ Pairs of valid offsets
  offpairs←,∘.,⍨⊂¨offs
  ⍝ Remove offset pairs (v,w) if v+w or v-w is bad
  filter←{⍱/(⍺+⍵)(⍺-⍵)∊badoffs}/¨offpairs
  pairs←filter/offpairs

  ⍝ Aux. function: Select the matrix with smallest number of blanks
  MinBlanks←{⍵⊃⍨⊃⍋(+/' '=,)¨⍵}
  ⍝ Aux. function: Given an offset pair, tile the floor using them and
  ⍝                extract the 30x30 region with minimum blanks
  GetResults←{
    somepair←⍵
    ⍝ -30 to 30, inclusive (the values of a and b)
    steps←30-⍳61
    ⍝ All values of av + bw, offset to the minimum coordinates of (0,0)
    alloffs←⊃{,(steps×⊂⍺)∘.+steps×⊂⍵}/somepair
    alloffs-←⌊/alloffs
    ⍝ Initialize a big enough blank grid
    dims←(⍴bool)+⊃⌈/alloffs
    grid←dims⍴''
    ⍝ Fill the grid with the tiles' cells moved accordingly
    filled←((≢alloffs)/⍪' '~⍨,x)@(cbool∘.+alloffs)⊢grid
    ⍝ Extract all 30x30 regions and return the one with minimum blanks
    results←,{⊂⍵}⌺30 30⊢filled
    MinBlanks results
  }
  ⍝ Map the above function over each of the pairs, and extract min blanks
  results←GetResults¨pairs
  MinBlanks results
}


CJam, 13 bytes

{{a.m>1m<z}/}

An unnamed block (function) that takes the matrix and the list on top of the stack (in that order) and leaves the new matrix in their place.

Run all test cases.

Same idea, same byte count, different implementations:

{{\(@m>a+z}/}
{{(Im>a+z}fI}
{{:\Im>]z}fI}

Explanation

Ideally we want to treat each instruction in the list the same, and just use it to rotate the first row of the matrix. This can be done quite easily by transforming the matrix after each instruction a bit and making sure that all those extra transformations cancel out in the end. So after processing each instruction, we rotate all rows one up (such that the next instruction along the same dimension processes the next row) and then transpose the matrix, such that we're actually processing columns next. These additional transformations are orthogonal to the instructions in the list and have a period of exactly 2n, just what we need.

As for the code:

{      e# For each instruction...
  a    e#   Wrap it in a singleton array.
  .m>  e#   Combine it element-wise with the matrix to rotate right. This is
       e#   a fairly common idiom to apply a binary operation only to the first
       e#   element of an array, since element-wise operations just retain all the
       e#   unpaired elements of the longer array.
  1m<  e#   Rotate the rows one up.
  z    e#   Transpose.
}/


Jelly,  40  38 bytes

z0j@€0,0µ⁺ṡ3Z€ṡ€3S€€⁺Ḥ
L€ḣ@"Ç+e€€7,9,6

A monadic link accepting and returning lists of lists of ones and zeros

Try it online!

How?

Cells will be alive in the next generation if:

it was alive in a neighbourhood (including itself) of three or four
it was dead in a neighbourhood of exactly three

Therefore if double the neighbourhood plus "was alive" is seven or nine (case 1) or six (case 2) then it will be alive next generation.

(For all other possible cases the sum of double the neighbourhood and "was alive" are other integers in the range [0,19])

z0j@€0,0µ⁺ṡ3Z€ṡ€3S€€⁺Ḥ - Link 1, neighbourhood counts * 2: board
        µ⁺             - perform this monadic link twice:
z0                     -   transpose with filler zero
     0,0               -   list [0,0]
  j@€                  -   join €ach with swapped arguments (surround each with zeros)
          ṡ3           - all overlapping sub-lists of length three (i.e. lists of rows)
            Z€         - transpose €ach
              ṡ€3      - all overlapping sub-lists of €ach of length three (i.e. 3x3 neighbourhoods)
                 S€€⁺  - repeated sum for €ach for €ach (neighbourhood sum)
                     Ḥ - double
                       - Note: the result includes counts of off-board areas filling right

L€ḣ@"Ç+e€€7,9,6 - Main link: board
     Ç          - call the last link (1) as a monad (get 2 * neighbourhood counts)
L€              - length of each row of the input board
  ḣ@"           - zip with head to index with swapped arguments
                - (i.e trim the neighbourhood counts to the shape of the input board)
      +         - add (vectorises) (i.e. 2 * neighbourhood count + was alive)
          7,9,6 - list = [7,9,6]
       e€€      - exists in? for €ach for €ach


Smallest sum (and largest difference) of two 3-digit integers

Jelly, 12 bytes

Ṣs3¬Þ€Fs2ZḌṚ

Try it online! or verify all test cases.

Background

Consider six digits a < b < c < d < e < f.

If a ≠ 0, a number pair of three-digit integers with minimal sum must clearly use a and b for the leftmost digits, c and d for the middle digits, and e and f for the rightmost digits.

That gives eight possible arrangements with identical sums (100(a + b) + 10(c + d) + (e + f)).

Since the difference should be as large as possible, all digits of the first integer should be larger than the corresponding digits of the second integer, leaving bdf10, ace10 as the optimal arrangement (difference 100(b - a) + 10(d - c)+ (f - e)).

Finally, if a = 0, a should still occur as early as possible (as middle digit), and a similar process reveals that the pair cdf10, bae10 is the correct solution.

How it works

Ṣs3¬Þ€Fs2ZḌṚ  Main link. Argument: <a, b, c, d, e, f> (in any order)

Ṣ             Sort; yield [a, b, c, d, e, f].
 s3           Split into triplets; yield [[a, b, c], [d, e, f]].
   ¬Þ€        Sort each triplet by logical NOT.
              If a ≠ 0, all digits have logical NOT 0, so this leaves the triplets
              unaltered. If a = 0, its logical NOT is 1, so the first triplet is
              sorted as [b, c, a], leaving [[b, c, a], [d, e, f]].
      F       Flatten; yield [a, b, c, d, e, f] or [b, c, a, d, e, f].
       s2     Split into pairs; yield [[a, b], [c, d], [e, f]] or
              [[b, c], [a, d], [e, f]].
         Z    Zip; yield [[a, c, e], [b, d, f]] or [[b, a, e], [c, d, f]].
          Ḍ   Undecimal; convert each triplet from base 10 to integer.
           Ṛ  Reverse the order of the generated integers.


Java, 881 bytes

import java.awt.image.BufferedImage;import static java.lang.Math.*;class J{BufferedImage o=new BufferedImage(999,999,1);java.awt.Graphics g=o.getGraphics();double v=2.5132,w=1.2566,p=PI,s=(p-v)/2,u=(p+w)/2;public static void main(String[]v){new J(Integer.parseInt(v[0]));}J(int i){d(609,391,v,p/4+s,500,i);try{javax.imageio.ImageIO.write(o,"png",new java.io.File("a.png"));}catch(Exception e){}}void d(int x,int y,double o,double q,double l,int r){int m=(int)(2*l*sin((p-o)/2)),a=(int)(x+cos(q)*l),b=(int)(y+sin(q)*l),c=(int)(x+cos(q+o/2)*m),d=(int)(y+sin(q+o/2)*m),e=(int)(x+cos(q+o)*l),f=(int)(y+sin(q+o)*l);if(r-->0){double n=l/(2*sin((v)/2));if(o>w){d(x,y,v,q-s,n,r);d(c,d,v,q+p+s,n,r);d(a,b,w,q+u,n,r);}else{d(x,y,w,q-s,n,r);d(c,d,w,q+p+s,n,r);d(e,f,w,q-p/2,n,r);d(a,b,v,q+p/2-s-s,n,r);}}else{g.drawLine(x,y,a,b);g.drawLine(a,b,c,d);g.drawLine(x,y,e,f);g.drawLine(c,d,e,f);}}}

Ungolfed

import java.awt.image.BufferedImage;

import static java.lang.Math.*;

class Q79373 {
    BufferedImage image = new BufferedImage(999, 999, 1);
    java.awt.Graphics graphics = image.getGraphics();
    double aRad = 2.5132, bRad = 1.2566, pi = PI, aAcuteHalf = (pi - aRad) / 2, bRadHalfPi = (pi + bRad) / 2;

    public static void main(String[] v) {
        new Q79373(Integer.parseInt(v[0]));
    }

    Q79373(int i) {
        draw(609, 391, aRad, pi / 4 + aAcuteHalf, 500, i);
        try {
            javax.imageio.ImageIO.write(image, "png", new java.io.File("a.png"));
        } catch (Exception e) {
        }
    }

    void draw(int x, int y, double rad, double rot, double length, int recDepth) {
        int
                height = (int) (2 * length * sin((pi - rad) / 2)),
                a = (int) (x + cos(rot) * length),
                b = (int) (y + sin(rot) * length),
                c = (int) (x + cos(rot + rad / 2) * height),
                d = (int) (y + sin(rot + rad / 2) * height),
                e = (int) (x + cos(rot + rad) * length),
                f = (int) (y + sin(rot + rad) * length);

        if (recDepth-- > 0) {
            double lengthNew = length / (2 * sin((aRad) / 2));
            if (rad > bRad) {
                draw(x, y, aRad, rot - aAcuteHalf, lengthNew, recDepth);
                draw(c, d, aRad, rot + pi + aAcuteHalf, lengthNew, recDepth);
                draw(a, b, bRad, rot + bRadHalfPi, lengthNew, recDepth);
            } else {
                draw(x, y, bRad, rot - aAcuteHalf, lengthNew, recDepth);
                draw(c, d, bRad, rot + pi + aAcuteHalf, lengthNew, recDepth);
                draw(e, f, bRad, rot - pi / 2, lengthNew, recDepth);
                draw(a, b, aRad, rot + pi / 2 - aAcuteHalf - aAcuteHalf, lengthNew, recDepth);
            }
        } else {
            graphics.drawLine(x, y, a, b);
            graphics.drawLine(a, b, c, d);
            graphics.drawLine(x, y, e, f);
            graphics.drawLine(c, d, e, f);
        }
    }
}

Notes

The results arent 100% acurate thanks to integer precision. I used integers for the coordinates because Graphics::drawLine only takes integers as arguments, and I would've ended up with way more integer casts than I have now.
I'll probably golf a bit more later, still not optimal.

Results

Full image filled

Recursion 1

Recursion 2

Recursion 3


Circular shift an arbitrary byte-array bitwise

C 89

Shifting is done in-place in *s array. l is array length and f is number of bits to shift.

void f(char*s,l,f){while(f--)for(int i=0,j,c=*s<0;s[j=i++]<<=1,s[j]+=i%l?s[i]<0:c,i<l;);}


Ruby - 541..., 394

The basic algorithm is a recursive depth-first search of duplicates to affirmatively select, looking through row 1, then column 1, then row 2, etc, and checking that two neighbors are not killed and that the grid is connected (that's the break if clause in there, and the bit that comes before it).

K=(0...(N=gets.to_i)*N).to_a
J=gets(p).split*''
H=->m{K&[m+1,m-1,m+N,m-N]}
Q=->k{s=[k[j=0]]
(j=s.size
s.map{|x|(s+=H[x]&k).uniq!})while s[j]
break if(K-k).any?{|m|(H[m]-k)[0]}||k!=k&s
$><<K.map{|m|[k.index(m)?J[m]:?#,m%N>N-2?"
":p]}*''|exit if !g=((0...N*2).map{|x|(k.select{|m|m.divmod(N)[x/N]==x%N}.group_by{|m|J[m]}.find{|l,c|c[1]}||[])[1]}-[p]).min
g.map{|d|Q[k-g<<d]}}
Q[K]
puts"no answer"

Some neat tricks:

if w[1] is much shorter than if !w.one? and if you know there's at least one member, it's the same result.

Similarly, [0] is shorter than any? if there's no block, and s[j] is a cute shortcut for j<s.size (technically, it's more like j.abs<s.size)

And y%N+(y/N).i is much shorter than Complex(y%N,y/N)

Also, when there's two complicated conditionals to generate strings, it might be shorter to do [cond1?str1a:str1b,cond2?str2a:str2b]*'' than to add all the parens or #{}s in.

Ungolfing and explanation:

(This is from the 531 byte version.  I've made changes.  Most notably, I've since eliminated the call to product - just solve one digit per row/column at a time, and J is now just an array, indexed by integers. All coordinates are just integers.)

H calculates neighbors

def H m
  # m, like all indices, is a complex number
  #    where the real part is x and the imaginary is y
  # so neighbors are just +/-i and +/-1

  i='i'.to_c
  neighborhood = [m+1, m-1, m+i, m-i]

  # and let's just make sure to eliminate out-of-bounds cells
  K & neighborhood
end

N is the size of the grid

N = gets.to_i

K are the keys to the map (complex numbers)

# pretty self-explanatory
# a range of, e.g., if N=3, (0..8)
# mapped to (0+0i),(1+0i),(2+0i),(0+1i),(1+1i),(2+1i),...
K = (0..N**2-1).map{|y| (y%N) +(y/N).i }

J is the input map (jail)

# so J is [[0+0,"2"],[0+1i,"3"],....].to_h
J=K.zip($<.flat_map {|s|
  # take each input line, and...
  # remove the "\n" and then turn it into an array of chars
  s.chomp.chars
}).to_h

k are the non-killed keys

# starts as K

Q is the main recursive method

def Q k
  j=0 # j is the size of mass
  # the connected mass starts arbitrarily wherever k starts
  mass=[k[0]]
  while j < s.size # while s hasn't grown
    j = mass.size
    mass.each{|cell|
      # add all neighbors that are in k
      (mass+=H[cell] & k).uniq!
    }
  end
  # if mass != k, it's not all orthogonally connected
  is_all_connected = k!=k&mass

  # (K-k) are the killed cells
  two_neighbors_killed = (K-k).any?{|m|
    # if any neighbors of killed cells aren't in k,
    # it means it was killed, too
    (H[m]-k)[0]
  }
  # fail fast
  return if two_neighbors_killed || is_all_connected

  def u x
    x.group_by{|m|J[m]}.select{|l,c|c[1]}
  end

  rows_with_dupes = Array.new(N){|r|u[k.select{|m|m.imag==r}]}

  cols_with_dupes = Array.new(N){|r|u[k.select{|m|m.real==r}]}

  # dupes is an array of hashes
  # each hash represents one row or column.  E.g.,
  #   {
  #     "3"=>[(0+0i),(1+0i),(3+0i)],
  #     "2"=>[(2+0i),(4+0i)]
  #   }
  # means that the 0th, 1st and 3rd cells in row 0
  # all are "3", and 2nd and 4th are "2".
  # Any digits without a duplicate are rejected.
  # Any row/col without any dupes is removed here.
  dupes = (rows_with_dupes+cols_with_dupes-[{}])

  # we solve one row at a time
  first_row = dupes[0]

  if !first_row
    # no dupes => success!
    J.map{|m,v|k.member?(m)?v:?#}.each_slice(N){|s|puts s*''}
    exit
  else
    # the digit doesn't really matter
    t=first_row.values

    # cross-multiply all arrays in the row to get a
    # small search space. We choose one cell from each
    # digit grouping and drop the rest.
    t.inject(:product).map{ |*e|
      # Technically, we drop all cells, and add back the
      # chosen cells, but it's all the same.
      new_k = k-t.flatten+e.flatten

      # and then search that space, recursively
      Q[new_k]
    }
  end
end

The code is executed with:

# run with whole board
Q[K]

# if we get here, we didn't hit an exit, so we fail
puts"no answer"

Changelog

394 added @blutorange's suggestion below, and chopped out a lot more manipulation

408 revised output once more. Also use .min instead of .inject(:+) since I'm just taking one row anyway.

417 shorter output calculation

421 dropped complex numbers. Just use integers. Save a bundle

450 more input improvements

456 input improvements

462 incremental improvements - esp. find, not select

475 dropped u and squashed the row/col dupe builder

503 only solve one duplicate digit per row/column at a time.

530 use map &:pop instead of values

531 pull out the lambda that makes the dupes array

552 oops! missed a requirement

536 marginally improved population of dupes array (what was formerly d)

541 initial


Represent n as an expression containing all the digits

05AB1E, 25 24 bytes
9Ýœ"+-*m"9ãðδšδ.ιJ˜.Δ.VQ

Brute-force approach, so obviously extremely slow.
Outputs in reverse Polish notation, with the characters +-*m for addition, subtraction, multiplication, and exponentiation respectively. Division isn't necessary for the \$[0,100000]\$ range we have to support.
Try it online with additional (first) input to specify the digit-range \$[0,n]\$ instead of \$[0,9]\$, for which I've used 4 right now as example.
Explanation:

9Ý           # Push a list in the range [0,9]
  œ          # Get all possible permutations of this list
"+-*m"       # Push string "+-*m"
      9ã     # Get all possible combinations of size 9 with the cartesian product
         δ   # Map over each string of operations:
        ð š  #  Convert it to a list of characters, and prepend a space
δ            # Apply double-vectorized with both lists of lists:
 .ι          #  Interleave the lists
J            # Then join each inner list together to a string
.Δ           # Find the first string which is truthy for:
  .V         #  Evaluate/execute the string as 05AB1E code
    Q        #  And check if the result is equal to the (implicit) input-integer
             # (after which the found result is output implicitly)

If we are allowed to output all possible results instead of just one, the .Δ (find first) could be ʒ (filter) for -1 byte. Although in that case it would become even slower than it already is..


Take a ride on the Reading, If you pass Go, collect $200

Retina, 74 bytes

FKCIIBAVWMGN_PT_NC_CS_PP_SV_CS_PE_LS_BJCVCORIBCMG
S_`(._.)
_
9$*
\B

1

The third to last and last lines should contain a single space.

Try it online!

Explanation

FKCIIBAVWMGN_PT_NC_CS_PP_SV_CS_PE_LS_BJCVCORIBCMG

This replaces the (empty) input with the string on the second line.

S_`(._.)

This is split stage, which splits the string around matches of the regex (._.) (that is, any three characters with a _ in the middle). The reason we put the whole regex in a group is that split stages also return the results of capturing groups. E.g. splitting abcd around bc gives [a, d], but splitting it around b(c) gives [a, c, d]. This way we get all the ._. parts on separate lines but also the 11-character parts at the beginning and end. We use the _ option to omit empty results between the individual ._. matches. The result would be this:

FKCIIBAVWMG
N_P
T_N
C_C
S_P
P_S
V_C
S_P
E_L
S_B
JCVCORIBCMG

Next we process the underscores:

_
9$*

This replaces each underscore with nine 1s. The reason we use 1s here instead of spaces immediately is that it makes it easier to insert the padding spaces next.

\B

Remember that there's a space on the second line. This inserts a space in every position that isn't a word boundary, i.e. everywhere except at the beginning and end of the lines.

1

And finally, we replace all those 1s with spaces as well.


05AB1E, 16 15 bytes

Very inefficient.
Empty output if there is no solution.

°LʒDSImOQ}ʒgQ}н

Try it online!


Count how many months are having a full 31 days by counting knuckles

Jelly, 21 bytes

ḅ12r/ị7RḂṁ12¤żC$S×⁼Ṣ$

Takes input like [[y, m], [y, m]].

Try it online!

How it works

ḅ12r/ị7RḂṁ12¤żC$S×⁼Ṣ$  Main link. Argument: [[a, b], [c, d]]

ḅ12                    Unbase 12; yield [x, y] := [ 12a + b, 12c + d].
   r/                  Reduce by range; yield [x, ..., y].
           ¤           Combine the five links to the left into a niladic chain.
      7                  Set the return value to 7.
       R                 Range; yield [1, 2, 3, 4, 5, 6, 7].
        Ḃ                Bit; yield [1, 0, 1, 0, 1, 0, 1].
         ṁ12             Mold 12; repeat the Booleans to create an array of length
                         12. Yields [1, 0, 1, 0, 1, 0, 1, 1, 0, 1, 0, 1].
     ị                 At-index; yield the elements of the array to the right at
                       the indices (1-based and modular) of the array to the left.
               $       Combine the two links to the left into a monadic chain.
              C          Complement; map t -> 1-t over the array.
             ż           Zip the original array with the complements.
                S      Take the sum of each column.
                    $  Combine the two links to the left into a monadic chain.
                  Ṣ      Sort [[a, b], [c, d]].
                   ⁼     Compare the result with [[a, b], [c, d]], yielding 1 if
                         the input is sorted, 0 if not.
                 ×     Multiply the results to both sides.


Optimal solution to go to opposite corner of a rectangle

Retina, 54 53 bytes

\d+
$*.
S_`(?<=(.+)¶.*).|\D
T`.`#`.¶|.*$
:m-1=`^#
X
#

Takes input separated by a linefeed and outputs the solution grid followed by the move count.

Try it online!

Explanation

\d+
$*.

Turn both integers into that many .s, i.e. convert them to unary.

S_`(?<=(.+)¶.*).|\D

This builds a grid of .s, by matching each . in the unary height and capturing the unary representation of the width. The S activates split mode which returns the captured strings, and the |\D and _ together ensure that everything else is removed from the string.

T`.`#`.¶|.*$

This turns the last character of each line as well as the entire last line into #s.

:m-1=`^#
X

This uses a ton of options to convert only the first # on the last row to X (we need to make sure that only the last row is affected because of width-1 inputs). m activates multi-line mode which makes ^ match the beginning of lines. -1= tells Retina to perform the substitution only on the last match. Finally, : switches off the default silent mode such that the grid is printed to STDOUT as an intermediate result.

#

Finally, we simply count the number # in the string, which corresponds to the number of moves.


Regex Golf: Regions of Italy vs. States of USA

Perl - 51 36 bytes (for regex)

print<>=~/.A|ise|net|te|z.o|[cp]a|[lr]ia|r[cd]/?"Italy
":"USA
"

Nothing special, but may as well post it, because it's different to other 51 bytes solution.

Or alternatively, shorten my already short solution by 15 bytes. This wins for now, I think.


Little Endian Number to String Conversion

05AB1E, 10 9 bytes

žJ+h¦2ôRJ

Try it online!

-1 byte by inspiration of the Jelly answer.

žJ+   add 2^32 to input
h     convert to hex
¦     drop leading 1
2ô    split in groups of 2
R     reverse groups
J     and join them


Python 3, 70 69 65 bytes

-1 byte thanks to @Uriel
-4 bytes thanks to @xnor

f=lambda s,b=0:s and'(['[b]+s[0]+f(s[1:-1],~b)+s[1:][-1:]+')]'[b]

Try it online!


APL (132 126 123 147 145 143)

This was a bit harder than I thought it'd be :)

Edit: the hard drive is infinite :S. All sequences that could not fit in the original space, are now appended onto the end of the output.

F←⍬⋄{×⍴⍵:∇1↓⍵⊣{∨/P←S⍷⍨1⍴⍨⍴⍵:S[R]∘←0⊣D[R←1-⍨(⍳⍴⍵)+⌊/P/⍳⍴P]∘←⍵⋄F∘←F,⍵}⊃⍵⋄D[S/⍳⍴S]∘←'-'}G[⍒⊃∘⍴¨G←K⊂⍨1≠|-⌿K,[÷2]¯1⌽K←K[⍋K←(S←~⎕)/D←⎕]]⋄F,⍨D/⍨~⌽∧\⌽S

This is what it does to your 1st and 2nd example (the 2nd example is different, but in your example the output length is not the same as the input length and you said in a comment it was wrong, so...)

⎕:    25 30 11 12 13 14 68 69 31 26 32
⎕:    0  0  1  1  1  1  0  0  0  0  0
25 26 11 12 13 14 30 31 32 68 69

⎕:    2 3 5 14 8 10 11 12 4 6 28 30 29 15 16 7
⎕:    0 0 0 0  0 1  1  1  0 0 0  0  0  0  0  0
14 15 16 - - 10 11 12 2 3 4 5 6 7 8 28 29 30

Explanation:

F←⍬: set F to the empty list. This will hold the overflow.
K←K[⍋K←(S←~⎕)/D←⎕]: read two lists. The first list (numbers) is stored in D. The second list (whether the data is unmovable) is inverted and then stored in S. Get all movable numbers, and sort them. Store this in K.
G←K⊂⍨1≠|-⌿K,[÷2]¯1⌽K: Subtract each element of K from the next element of K. Wherever this is not 1, we found the beginning of a new sequence. Store the list of sequences in G.
G[⍒⊃∘⍴¨G...]: sort the list of sequences by descending length. This way, we place the longest sequences first.
{×⍴⍵:...}G: as long as this list of sequences is not empty...
∇1↓⍵⊣: handle the tail of the list, after...
{...}⊃⍵: doing the following with the head:
∨/P←S⍷⍨1⍴⍨⍴⍵: find, in S, a list of ones that is as long as the current sequence (⍵).
S[R]∘←0⊣D[R←1-⍨(⍳⍴⍵)+⌊/P/⍳⍴P]∘←⍵: if there is one, store ⍵ in D at the first position that it fits, and mark these positions as unmovable in S.
⋄F∘←F,⍵: if there is no room, add it to the overflow.
⋄D[S/⍳⍴S]∘←'-': when we're at the end of the list of sequences, all positions where S is still one are places where we couldn't put anything. Mark these with -.
⋄F,⍨D/⍨~⌽∧\⌽S: then, at the end, display D, with the trailing -s removed, followed by the overflow (F) per the new rules.


Python 2, 46 45 bytes

thanks to xnor for -1 byte

f=lambda n:n>0and f(n-2)+f(n-3)+f(n-5)or n==0

Try it online!


J, 3 bytes, non-competing.

*./

Given a list of rational inputs, this folds LCM through it.


C - 0.1 Secs on Ideone

http://www.ideone.com/E3S2t

Explanation included in code.

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

long long A[1000001]={0};
int main()
{
    int isprime[1001],d,n,k,i,e,p;

    for (n=2;n<1001;n++)
        isprime[n]=1;

    //Sieve of Eratosthenes for Prime
    //Storing the smallest prime which divides n.
    //If A[n]=0 it means it is prime number.
    for(d=2;d<1001;d++)
    {
        if(isprime[d])
        {
            for (n=d*d;n<1001;n+=d)
            {
                isprime[n]=0;
                A[n]=d;
            }
            for (;n<=1000000;n+=d)
                A[n]=d;
        }
    }

    //Uses multiplicative property of
    //Euler Totient Function
    //Phi(n)=Phi(p1^k1)*Phi(p2^k2)...*Phi(pr^kr)
    //and Phi(pi^ki)=(pi-1)*(pi^(ki-1))
    A[1]=1;
    for(n=2;n<=1000000;n++)
    {
        if (A[n]==0)
           A[n]=n-1;
        else
        {
           p=A[n],k=n/p,e=1;
           while (k%p==0)
                 k/=p,e*=p;
           A[n]=A[k]*e*(p-1);
        }
    }
    //Number of terms in Farey Series
    //|F(n)| = 1 + Sigma(i,1,n,phi(i))
    A[1]=2;
    for(n=2;n<=1000000;n++)
        A[n]+=A[n-1];

    while (~scanf("%d",&i))
        printf("%lld\n",A[i]);
    return 0;
}

A little more explanation:

  For all numbers we get a prime factor
  of it from the sieve(or 0 if it is a
  prime). Next we use the fact that ETF
  is multiplicative. That is if m and n
  are coprime then
  phi(m*n)=phi(m)*phi(n). Here we take
  out the multiple of prime factor out
  and hence the left part and the
  multiple part are co-prime. We already
  have the ETF for the left part since
  it is either smaller then current
  value or equal to 1. We only need to
  calculate the ETF for the multiple
  which we calculate using the formula
  phi(pi^ki)=(pi-1)*(pi^(ki-1)).


Ruby

Based on the Dining Philosophers tale - 4 philosophers:

  Five silent philosophers sit at a table around a bowl of spaghetti. A
  fork is placed between each pair of adjacent philosophers. (An
  alternative problem formulation uses rice and chopsticks instead of
  spaghetti and forks.)

  Each philosopher must alternately think and eat. However, a
  philosopher can only eat spaghetti when he has both left and right
  forks. Each fork can be held by only one philosopher and so a
  philosopher can use the fork only if it's not being used by another
  philosopher. After he finishes eating, he needs to put down both forks
  so they become available to others. A philosopher can grab the fork on
  his right or the one on his left as they become available, but can't
  start eating before getting both of them.

class Fork

  attr_reader :owner
  def initialize
   @mutex = Mutex.new
  end

  def pickup(new_owner)
    @mutex.synchronize do
      if @owner.nil?
        @owner = new_owner
    return true
      end
      return false
    end
  end

  def release(owner)
     @mutex.synchronize do
      if @owner == owner
        @owner = nil
    return true
      end
      return false
    end
  end
end

class Philosopher

  attr_reader :name, :hungry
  attr_accessor :left_fork, :right_fork

  def initialize(name, left_fork, right_fork)
    @name = name
    @hungry = true
    @left_fork = left_fork
    @right_fork = right_fork
  end

  def eat
    while hungry
      got_left = left_fork.pickup(self)
      think
      got_right = right_fork.pickup(self)
      if got_left && got_right
        @hungry = false
    puts "#{name} has eaten!"
      end
      right_fork.release(self)
      think
      left_fork.release(self)
    end
    puts "#{name} ended"
  end

  def think
    puts "#{name} thinks..."
    sleep 1
  end
end

fork = nil
philosophers = %w(aristotle plato confucius descartes).map { |p| Philosopher.new(p, fork, fork = Fork.new) }
philosophers[0].left_fork = fork

threads = philosophers.map do |p|
  puts p.left_fork.pickup(p)
  Thread.new {
    p.eat
  }
end

threads.map(&:join)


List all times in the day at a half hour rate

Pyth, 26 bytes
Pjbm%"'%02d:%s0',"d*U24"03

Demonstration.
We start with the cartesian product of range(24) (U24) with the string "03".
Then, we map these values to the appropriate string formating substitution (m%"'%02d:%s0',"d).
Then, the resultant strings are joined on the newline character (jb).
Finally, we remove the trailing comma (P) and print.


Python: shortest way to interleave items from two lists

Zip and Sum

[*sum(zip(l2,l1),())]

Try it online!

Zips the two lists together then adds all the tuples to make one combined list. The zip only works if the lists are guaranteed to be the same size, otherwise it truncates the longer list.

Added the surrounding [*  ] to transform it into a list as FryAmTheEggman suggests.


Python 3, 120 bytes

many bytes saved thanks to @JonathanAllan

lambda s,a='abcdefghijklmnopqrstuvwxyz VOďƄɹ5ʇη^MXʎ2ɐʠ>Pəɟ6ɥ!ɾʞ|W ':''.join(a[(a.find(c)+27)%54]for c in s)

Try it online!


Jelly, 5 bytes

²µSHe

Try it online!

Technical note: Bytes are counted in Jelly codepage.

Explanation:

²µSHe  Main link.
²      Square each number.
 µ     With the new list,
  S    calculate its sum,
   H   and halve it.
    e  Check if the result exists in the new list (squared input)

The problem is equivalent to being given three numbers a, b, c, and asking if there is a permutation such that a² + b² = c². This is equivalent to whether (a² + b² + c²) ÷ 2 is one of a², b² or c², so the program just checks that.


Python 2, 446 Bytes

Just decodes the Base64 and decompresses using zlib.

import zlib,base64
print zlib.decompress(base64.b64decode("eNrl1MFtwzAMBdCeMwUXEOgJPIcPBLqIhk8ofkq2QdFQb215iZDkgdSXZfpeLHrVY1JCJPpJtH2KSNfMG9c52WBORAUlRL7MDNJESsT6dGIiG8yNE4gjIzCdmMiJGyMQDwQGXUycSW2ncBS+GScQnZTPUhMtxPc+neAXJ0KlUqtS8Gfq5V2sxmAyvjS0TWoQXiW8PljbPuv25bp97kTkun1dWiJF7sKPEubhKLmdILrA5ETFOEqYlDCeRd++mYyYGIPBJARiXDGYhECcLrKZjJg4vy6ayQYzcXkpqXk4l6j+C6nCdY3s+ljti11Y6q9MbBJPEJ+TWTxBfKNLHE8Q32wvyZQx2bMpZ12k/jTkKMechDk+dQly/FMX+Q3ohQN5"))


Pyth, 25 24 22 bytes
VSsm,Rdcd\ QAN:HGjG"<>

Try it online.
Takes input as an array of lines, like ["Green Sleeves","Time Was Lost"].
Explanation
VSsm,Rdcd\ QAN:HGjG"<>   implicit: Q = evaluated input

   m       Q                   map input lines:
       cd\                         split input line to words
    ,Rd                          replace each word by pair [word, entire line]
  s                          concatenate results for all input lines
 S                         sort the array of pairs lexicographically
V                        loop over the array
            AN             assign the word to G and the corresponding line to H
                 jG"<>       put the word between <>
              :HG          replace the word by the above in the line and print


Wordfuck, 5761 2686 bytes

I guess using his name as a source code gets Adam West some honor.

adam west adam west adam_wes t_a dam_we st_a dam_ west adam west adam west adam west_ad am_west_a dam_we st ad am we st ad am we st ad am west_a dam_we st_a dam_ west_ada m_w est ada m_w est ada m_west_ adam west_a dam_west_ adam_we st_ ad am_west ad am we st ad am we st ad am we st ad am we st ad am we st ad am we st ad am_wes t_ adam_w est_ adam west adam west adam west adam west adam we st_adam west_ad am we st ad am we st adam_w es t_ ad am west_ad am we st ad am we st ad am we st_ada m_ west_ad am we st ad am west_a da m_west_ ad am we st ad am we st ad am west_a da m_ we st adam_w es t_adam_ west_ad am we st ad am west_a da m_ we st adam_we st ad am we st ad am we st ad am we st_ada m_ we st ad am we st adam_we st ad am we st ad am we st ad am we st_ada m_ we st ad am_wes t_ adam_we st_adam we st ad am_wes t_ ad am we st ad am_west ad am we st ad am we st ad am we st adam_w es t_ ad am we st ad am_west ad am we st ad am we st ad am we st adam_w es t_ ad am we st adam_w es t_adam_ west_ad am we st_ada m_ we st ad am we st ad am west_ad am we st ad am we st ad am west_a da m_ we st ad am we st ad am_west ad am we st ad am we st ad am_wes t_ ad am we st ad am we st adam_w es t_adam_ west_ad am west_a da m_ we st ad am we st ad am we st ad am we st ad am we st ad am we st ad am we st ad am we st ad am we st ad am we st ad am we st ad am we st_ada m_ west_ad am we st ad am we st ad am we st ad am we st ad am we st ad am we st ad am we st ad am we st ad am we st ad am we st ad am we st ad am we st ad am west_a da m_west_ ad am we st ad am we st ad am we st ad am we st ad am we st ad am we st ad am we st ad am we st ad am we st ad am we st ad am we st ad am we st ad am_wes t_ adam_we st ad am we st ad am we st ad am we st ad am we st ad am we st ad am we st ad am we st ad am we st ad am we st ad am we st ad am we st ad am we st adam_w es t_adam_ west_ad am west_a da m_ we st ad am we st ad am we st ad am we st ad am we st ad am we st ad am we st ad am we st ad am we st ad am we st ad am we st ad am we st_ada m_ west_ad am_west ad am west_a da m_ we st ad am_west ad am we st ad am we st_ada m_ we st ad am we st ad am we st ad am we st ad am we st ad am west_ad am we st ad am we st adam_w es t_ ad am we st_ada m_ west_ad am_west ad am we st adam_w es t_ ad am west_ad am we st ad am we st adam_w es t_ ad am_west ad am we st adam_w es t_ ad am we st_adam we st ad am west_a da m_ we st_adam we st ad am we st ad am_wes t_ ad am we st_ada m_ west_ad am_west ad am we st ad am we st_ada m_ we st_adam we st ad am we st ad am_wes t_ adam_we st ad am we st ad am_wes t_ ad am west_ad am we st ad am we st_ada m_ west_ad am we st ad am we st adam_w es t!

Try it online! (transpiled brainfuck)

Adam West singing (thanks @carusocomputing)


Python, 89 bytes

from random import*
lambda n,k:[x-i for i,x in enumerate(sorted(sample(range(1,n+k),k)))]

Generating an increasing sequence rather than a non-decreasing one would be straightforward: this is just a random subset of k numbers between 1 and n, sorted.

But, we can convert an increasing sequence to a non-decreasing one by shrinking each gap between consecutive numbers by 1. So, a gap of 1 becomes a gap of 0, making equal numbers. To do so, decrease the i'th largest value by i

r[0], r[1], ..., r[n-1]  =>  r[0]-0, r[1]-1, ..., r[n-1]-(n-1)

For the result to be from 1 to n, the input must be from 1 to n+k-1. This gives a bijection between non-decreasing sequences of numbers between 1 and n, to increasing sequences between 1 and n+k-1. The same bijection is used in the stars and bars argument for counting such sequences.

The code uses the python function random.sample, which takes k samples without replacement from the input list. Sorting it gives the increasing sequence.


JavaScript

So I went a little crazy with this. I did it between breaks from working on my GUI to track IP's using Visual Basic.

You can access it by going to the super serious domain I made for it tonight as well so you can look busy anywhere Gui Hacker and fork and create your own from the following sources

Fiddle
CodePen
github

Basically, if you have this running no one will bother you because they know you are doing some serious stuff.

var canvas = document.querySelector(".hacker-3d-shiz"),
  ctx = canvas.getContext("2d"),
  canvasBars = document.querySelector(".bars-and-stuff"),
  ctxBars = canvasBars.getContext("2d"),
  outputConsole = document.querySelector(".output-console");

canvas.width = (window.innerWidth / 3) * 2;
canvas.height = window.innerHeight / 3;

canvasBars.width = window.innerWidth / 3;
canvasBars.height = canvas.height;

outputConsole.style.height = (window.innerHeight / 3) * 2 + 'px';
outputConsole.style.top = window.innerHeight / 3 + 'px'

/* Graphics stuff */
function Square(z) {
  this.width = canvas.width / 2;
  this.height = canvas.height;
  z = z || 0;

  this.points = [
    new Point({
      x: (canvas.width / 2) - this.width,
      y: (canvas.height / 2) - this.height,
      z: z
    }),
    new Point({
      x: (canvas.width / 2) + this.width,
      y: (canvas.height / 2) - this.height,
      z: z
    }),
    new Point({
      x: (canvas.width / 2) + this.width,
      y: (canvas.height / 2) + this.height,
      z: z
    }),
    new Point({
      x: (canvas.width / 2) - this.width,
      y: (canvas.height / 2) + this.height,
      z: z
    })
  ];
  this.dist = 0;
}

Square.prototype.update = function() {
  for (var p = 0; p < this.points.length; p++) {
    this.points[p].rotateZ(0.001);
    this.points[p].z -= 3;
    if (this.points[p].z < -300) {
      this.points[p].z = 2700;
    }
    this.points[p].map2D();
  }
}

Square.prototype.render = function() {
  ctx.beginPath();
  ctx.moveTo(this.points[0].xPos, this.points[0].yPos);
  for (var p = 1; p < this.points.length; p++) {
    if (this.points[p].z > -(focal - 50)) {
      ctx.lineTo(this.points[p].xPos, this.points[p].yPos);
    }
  }

  ctx.closePath();
  ctx.stroke();

  this.dist = this.points[this.points.length - 1].z;

};

function Point(pos) {
  this.x = pos.x - canvas.width / 2 || 0;
  this.y = pos.y - canvas.height / 2 || 0;
  this.z = pos.z || 0;

  this.cX = 0;
  this.cY = 0;
  this.cZ = 0;

  this.xPos = 0;
  this.yPos = 0;
  this.map2D();
}

Point.prototype.rotateZ = function(angleZ) {
  var cosZ = Math.cos(angleZ),
    sinZ = Math.sin(angleZ),
    x1 = this.x * cosZ - this.y * sinZ,
    y1 = this.y * cosZ + this.x * sinZ;

  this.x = x1;
  this.y = y1;
}

Point.prototype.map2D = function() {
  var scaleX = focal / (focal + this.z + this.cZ),
    scaleY = focal / (focal + this.z + this.cZ);

  this.xPos = vpx + (this.cX + this.x) * scaleX;
  this.yPos = vpy + (this.cY + this.y) * scaleY;
};

// Init graphics stuff
var squares = [],
  focal = canvas.width / 2,
  vpx = canvas.width / 2,
  vpy = canvas.height / 2,
  barVals = [],
  sineVal = 0;

for (var i = 0; i < 15; i++) {
  squares.push(new Square(-300 + (i * 200)));
}

//ctx.lineWidth = 2;
ctx.strokeStyle = ctxBars.strokeStyle = ctxBars.fillStyle = '#00FF00';

/* fake console stuff */
var commandStart = ['Performing DNS Lookups for',
    'Searching ',
    'Analyzing ',
    'Estimating Approximate Location of ',
    'Compressing ',
    'Requesting Authorization From : ',
    'wget -a -t ',
    'tar -xzf ',
    'Entering Location ',
    'Compilation Started of ',
    'Downloading '
  ],
  commandParts = ['Data Structure',
    'http://wwjd.com?au&2',
    'Texture',
    'TPS Reports',
    ' .... Searching ... ',
    'http://zanb.se/?23&88&far=2',
    'http://ab.ret45-33/?timing=1ww'
  ],
  commandResponses = ['Authorizing ',
    'Authorized...',
    'Access Granted..',
    'Going Deeper....',
    'Compression Complete.',
    'Compilation of Data Structures Complete..',
    'Entering Security Console...',
    'Encryption Unsuccesful Attempting Retry...',
    'Waiting for response...',
    '....Searching...',
    'Calculating Space Requirements '
  ],
  isProcessing = false,
  processTime = 0,
  lastProcess = 0;

function render() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);

  squares.sort(function(a, b) {
    return b.dist - a.dist;
  });
  for (var i = 0, len = squares.length; i < len; i++) {
    squares[i].update();
    squares[i].render();
  }

  ctxBars.clearRect(0, 0, canvasBars.width, canvasBars.height);

  ctxBars.beginPath();
  var y = canvasBars.height / 6;
  ctxBars.moveTo(0, y);

  for (i = 0; i < canvasBars.width; i++) {
    var ran = (Math.random() * 20) - 10;
    if (Math.random() > 0.98) {
      ran = (Math.random() * 50) - 25
    }
    ctxBars.lineTo(i, y + ran);
  }

  ctxBars.stroke();

  for (i = 0; i < canvasBars.width; i += 20) {
    if (!barVals[i]) {
      barVals[i] = {
        val: Math.random() * (canvasBars.height / 2),
        freq: 0.1,
        sineVal: Math.random() * 100
      };
    }

    barVals[i].sineVal += barVals[i].freq;
    barVals[i].val += Math.sin(barVals[i].sineVal * Math.PI / 2) * 5;
    ctxBars.fillRect(i + 5, canvasBars.height, 15, -barVals[i].val);
  }

  requestAnimationFrame(render);
}

function consoleOutput() {
  var textEl = document.createElement('p');

  if (isProcessing) {
    textEl = document.createElement('span');
    textEl.textContent += Math.random() + " ";
    if (Date.now() > lastProcess + processTime) {
      isProcessing = false;
    }
  } else {
    var commandType = ~~(Math.random() * 4);
    switch (commandType) {
      case 0:
        textEl.textContent = commandStart[~~(Math.random() * commandStart.length)] + commandParts[~~(Math.random() * commandParts.length)];
        break;
      case 3:
        isProcessing = true;
        processTime = ~~(Math.random() * 5000);
        lastProcess = Date.now();
      default:
        textEl.textContent = commandResponses[~~(Math.random() * commandResponses.length)];
        break;
    }
  }

  outputConsole.scrollTop = outputConsole.scrollHeight;
  outputConsole.appendChild(textEl);

  if (outputConsole.scrollHeight > window.innerHeight) {
    var removeNodes = outputConsole.querySelectorAll('*');
    for (var n = 0; n < ~~(removeNodes.length / 3); n++) {
      outputConsole.removeChild(removeNodes[n]);
    }
  }

  setTimeout(consoleOutput, ~~(Math.random() * 200));
}

render();
consoleOutput();

window.addEventListener('resize', function() {
  canvas.width = (window.innerWidth / 3) * 2;
  canvas.height = window.innerHeight / 3;

  canvasBars.width = window.innerWidth / 3;
  canvasBars.height = canvas.height;

  outputConsole.style.height = (window.innerHeight / 3) * 2 + 'px';
  outputConsole.style.top = window.innerHeight / 3 + 'px';

  focal = canvas.width / 2;
  vpx = canvas.width / 2;
  vpy = canvas.height / 2;
  ctx.strokeStyle = ctxBars.strokeStyle = ctxBars.fillStyle = '#00FF00';
});
@font-face {
  font-family: 'Source Code Pro';
  font-style: normal;
  font-weight: 400;
  src: local('Source Code Pro'), local('SourceCodePro-Regular'), url(http://themes.googleusercontent.com/static/fonts/sourcecodepro/v4/mrl8jkM18OlOQN8JLgasDxM0YzuT7MdOe03otPbuUS0.woff) format('woff');
}
body {
  font-family: 'Source Code Pro';
  background: #000;
  color: #00FF00;
  margin: 0;
  font-size: 13px;
}
canvas {
  position: absolute;
  top: 0;
  left: 0;
}
.bars-and-stuff {
  left: 66.6%;
}
.output-console {
  position: fixed;
  overflow: hidden;
}
p {
  margin: 0
}
<canvas class='hacker-3d-shiz'></canvas>
<canvas class='bars-and-stuff'></canvas>


JavaScript (ES6), 58 57 bytes

NB: This turns out to use the same trick as Jonathan Allan in this Jelly answer (though I noticed after posting).

Saved 1 byte thanks to Jonathan Allan

Works on arrays of strings.

s=>s.map(s=>s+'01120101'.replace(/./g,n=>s.substr(-n,1)))

Test cases

let f =

s=>s.map(s=>s+'01120101'.replace(/./g,n=>s.substr(-n,1)))

console.log(f(['ellipsis']))
console.log(f(['goat']))
console.log(f(['covfefe']))
console.log(f(['programmer5000']))
console.log(f(['up', 'vote', 'down', 'goat']))
console.log(f(['it', 'is', 'golf', 'yo']))
console.log(f(['crossed', 'out', '44', 'is', 'still', '44']))


Python 2, 32 bytes

print>>open(*"ww"),"Hello World"

Yes, this is valid python.


Pyth, 37 bytes

jc:*d*QQiRQhos.aMNf.Am}_dTT.c^UQ2vzNQ

Slow solution. Generates all possible pairs of [0, m), generate all possible n-combinations of those pairs (without repetition). Filter each combination of pairs such that if P is in the combination, so is reverse(P). This guarantees diagonal symmetry. Sort by the sum of distances to the origin. Decode the pairs of numbers as base-m numbers, giving a list of indices. Create a string of spaces except for those indices, putting quotation marks instead. Finally chop into m pieces and join by newlines. Creates outputs like such:

""""
"""
""
"


Tcl/Tk, 100

pack [entry .e -textv e] -f both -e 1
bind . <Return> {catch {expr $e} e}
bind . <Escape> {set e {}}

Buttons are not required, so leave them alone.
The GUI is great. So simple that you can finally focus on the task that you try to do.


Haskell, 159 bytes

With preprocessing of the input to fit the defined tree datatype (included in score) since trees can't be represented as a nested list.

data T=T[Char][T]
r=reverse;z=zipWith;a%b=a:cycle[b]
p(T s b)|k<-r$p<$>b=s:(concat$r$z(z(++))(("└── "%"    ")%("├── "%"│   "))k)
mapM putStrLn.p

Usage:

> mapM putStrLn.p $ T"kingdom"[T"mineral"[],T"animal"[T"dog"[T"schnauzer"[],T"whippet"[]]],T"vegetable"[T"cabbage"[]]]
kingdom
├── mineral
├── animal
│   └── dog
│       ├── schnauzer
│       └── whippet
└── vegetable
    └── cabbage


Javascript, 68 63 61 60 52 bytes

5 bytes off thanks @ETHproductions. 2 3 11!! bytes off thanks @NotthatCharles.

f=(i,a,m=0)=>/[^01]/.test(i+=a[m++%10])?f(i,a,m):m/2

Test here.


Implement "tac": Print lines from a file in reverse

GS2, 3 bytes

* +

The three bytes are, in order, split lines, reverse, and join lines.


Perl - 125 79 chars

Count includes 4 chars for "-ln" options.  Takes n from stdin.

New constructive approach:

@a=0;map{%a=();map{$a{"$`100$'"}=1while/0/g;}@a;@a=keys%a}1..$_;print for@a

Form the solution for n by substituting a new internal node ("100") for each leaf ("0"), in turn, in each tree from the solution for n-1.

(I owe this concept to other's solutions that use the internal node to leaf [100->0] substitution for verifying sequentially-generated strings, and I believe I saw--after writing my answer based on that concept--this same 0->100 method of construction in someone's intermediate edit.)

Previous recursive approach:

sub t{my$n=shift;if($n){--$n;for$R(0..$n){for$r(t($R)){for$l(t($n-$R)){push@_,"1$l$r"}}}}else{push@_,"0"}@_}print for t$_

Recursive ungolfed:

sub tree {
  my ($n) = @_;
  my @result = ();
  if ( $n ) {
    for $right_count ( 0 .. $n-1 ) {
      for $right ( tree( $right_count ) ) {
        for $left ( tree( ($n-1) - $right_count ) ) {
          push @result, "1$left$right";
        }
      }
    }
  }
  else {
    push @result, "0";
  }
  return @result;
}
foreach $tree ( tree($_) ) {
  print $tree;
}


Python 2, 115 111 110 109 bytes

-6 bytes thanks to Mr. Xcoder

lambda n:n>2and cmp(*map(all,zip(*[[n%x==1or~f(x)%n,n%x]for x in range(2,n)])))<0
f=lambda x:0**x or x*f(x-1)

Try it online!

The functions consist of two parts ~-n%x<1or~f(x)%n>0 that verifies if n don't satisfies the "Pillai conditions", and n%x>0 for the prime validation.
After that all is applied to both items, the first item will contain False/0 if there is a valid "Pillai number", and the second will contain True/1 if n is prime.
These are passed to cmp that will return -1 in this cenario (is a valid Pillai prime). The other combinations [[0, 0], [1, 0], [1, 1]] will return 0 or 1


Python 2, 194 182 bytes

from random import*
h=m=H,M=input()
while[h,m]!=[H,M/5]:
 h=m=0;s=[]
 for n in 1,1,2,3,5:c=randint(0,3);h+=c%2*n;m+=c/2*n;s=zip(*(["WRGB"[c]*n]*n+s)[::-1])
for L in s:print"".join(L)

The algorithm is just rejection sampling, so it keeps generating clocks until it gets one that's right. The clock is built by starting with nothing, then doing "add a square above and rotate clockwise" 5 times.

Takes two comma-separated integers via STDIN.

>>> ================================ RESTART ================================
>>>
7,17
BBBWWWWW
BBRWWWWW
RRRWWWWW
RRRWWWWW
RRRWWWWW
>>> ================================ RESTART ================================
>>>
7,17
GGBRRRRR
GGRRRRRR
WWWRRRRR
WWWRRRRR
WWWRRRRR


Mine for 2016 in Bitcoins! PCG.SE New Year's Puzzle 2016

Mathematica, 94

(For[i=0,IntegerDigits[4Hash[#<>ToString@++i,"SHA256"],64]~SequenceCount~{54,52,53,58}<1,];i)&

This function will try positive integers as candidates. It takes over 4 minutes on my laptop to get the correct answer.

%["foo"]
(* 196870 *)

Longer however faster (~5x) implementation makes use of parallelization:

f[k_]:=
    Do[If[Length@#>0,Return[i+#[[1,1]]]]&@
        Position[ParallelMap[IntegerDigits[4Hash[k<>ToString@#,"SHA256"],64]
            ~SequenceCount~{54,52,53,58}&,i+Range@1*^4],1]
        ,{i,0,∞,1*^4}]


Jelly, 6 bytes

I;ḢṚ+\

Try it online!

How it works

I;ḢṚ+\  Main link. Argument: A (array)

I       Increments; compute the deltas of A.
  Ḣ     Head; yield the first element of A.
 ;      Concatenate the results to both sides.
   Ṛ    Reverse the resulting array.
    +\  Compute the cumulative sum of the reversed array.


05AB1E, 4 bytes
Note that if only a single iteration was required (n=1), then the program would be the palindrome û€û.
Fû€û

Try it online
F       Do n times
 û      Palindromize the list
  €û    Palindromize each element in the list

If padding the input was still a required part of the program (11 bytes):
€R.B€RIFû€û

I couldn't find a shorter way to right-justify. Left-justification and centering were all easy, but this was longer for some reason. Using E or ² instead of I also works.


Retina, 108 104 bytes
[A-Z]
;$&
Ne
xF
F
xxxO
O
xxN
N
xxC
C
xB
B
11$*x
e
xxx
H
x
x(?=x*(\d+))
$1$*x
[A-Z]
30$*x
[^x]

M`x{29}
0

Try it online!
Test suite.


Scala, 56 bytes

s=>new java.awt.Font(s,0,0).canDisplayUpTo("ŐőŰű")<0

canDisplayUpTo is a method of the Font object that returns the index of the first charater that cannot be displayed by the font. It return -1 if all characters can be displayed. javadoc


J, 74 72 characters

Here's my J implementation (f =. not included in character count):

f =. **}.^:(*@#*0={.)@([:((12-~[),0>:@{.@]`[`]}])`,@.(6>[)/&.|.0,12&#.^:_1)@|

And some tests (each result is boxed, and underscore means negative):

   NB. Integers [-10..10]:
   (<@f"0)i:10
┌────┬────┬────┬────┬────┬──┬──┬──┬──┬──┬─┬─┬─┬─┬─┬─┬────┬────┬────┬────┬────┐
│_1 2│_1 3│_1 4│_1 5│_1 6│_5│_4│_3│_2│_1│0│1│2│3│4│5│1 _6│1 _5│1 _4│1 _3│1 _2│
└────┴────┴────┴────┴────┴──┴──┴──┴──┴──┴─┴─┴─┴─┴─┴─┴────┴────┴────┴────┴────┘
   NB. Some boundary values:
   (<@f"0)215 216 217 71 72 73
┌──────┬──────┬──────┬────┬──────┬──────┐
│1 6 _1│2 _6 0│2 _6 1│6 _1│1 _6 0│1 _6 1│
└──────┴──────┴──────┴────┴──────┴──────┘

Interestingly, the rules for 6 have no special place in the function. They work that way just by handling all digits >= 6 together and only working on positive numbers.

I made another version, which doesn't rely on #.^:_1, but it's longer:

**_2&([:}.^:(0={.)+/\)@(((<.@%&12,(1,-&12)`(0,])@.(6>])@(12&|))@{.,}.)^:(0~:{.)^:_)@(,&0)@|


When life gives you lemons, make lemonade

JavaScript (ES6), 159 157 155 162 bytes

Edit: +7 bytes to "output what was do-able with the letters given" rather than throwing out an error

A recursive function that returns the modified string.

f=(s,a=s.split(/(lemon)/i),n=(a.length-1)*1.5)=>n?f(n,a.map((s,i)=>i&1|!n||(a[i]=s.replace([/a/i,/e/i,/d/i][n%3],c=>(a[--n/3<<1|1]+=c,''))))&&a,n-(n==s)):a.join``

How it works

The expression s.split(/(lemon)/i) splits the input string on lemon but preserves the capture groups in the result.

For instance, "foo lemon bar LEMON baz".split(/(lemon)/i) will produce the array [ 'foo ', 'lemon', ' bar ', 'LEMON', ' baz' ].

We recursively iterate on this array, extracting the characters a, d and e or their uppercase counterparts from the entries located at an even position, and appending them to the entries located at an odd position.

Commented

f = (                                   // given:
  s,                                    //   s = input string or previous value of 'n'
  a = s.split(/(lemon)/i),              //   a = split array, as described above
  n = (a.length - 1) * 1.5              //   n = total number of characters to be found
) =>                                    //
  n ?                                   // if there's still at least one character to find:
    f(                                  //   do a recursive call with:
      n,                                //     1) the current value of 'n'
      a.map((s, i) =>                   //     2) an updated version of 'a', where
        i & 1 | !n || (                 //       for even positions:
          a[i] = s.replace(             //         we look for the next character
            [/a/i, /e/i, /d/i][n % 3],  //           'a', 'e' or 'd' (case insensitive)
            c => (                      //           append it to
              a[--n / 3 << 1 | 1] += c, //           one of the entries at an odd position
              ''                        //           and remove it from the original entry
            )                           //           end of replace() callback
          )                             //         end of replace()
        )                               //       end of position condition
      ) && a,                           //     end of map() -> yield the updated 'a'
      n -                               //     3) the updated value of 'n', skipping the
      (n == s)                          //        current character if not found at all
    )                                   //   end of recursive call
  :                                     // else:
    a.join``                            //   success: join 'a' and return it

Demo

f=(s,a=s.split(/(lemon)/i),n=(a.length-1)*1.5)=>n?f(n,a.map((s,i)=>i&1|!n||(a[i]=s.replace([/a/i,/e/i,/d/i][n%3],c=>(a[--n/3<<1|1]+=c,''))))&&a,n-(n==s)):a.join``

console.log(f("I found a lemon when I was a kid"))
console.log(f("I found a lemon when I was a kid. I found another lemon when I was older."))
console.log(f("bdblemon"))
console.log(f("he hAD lemOn"))


Create a Fanatic bot for Stack Exchange sites

Ruby, 456 characters

require'mechanize'
s,*e=gets.split
a,o=Mechanize.new,'http://openid.stackexchange.com/'
a.agent.http.verify_mode=OpenSSL::SSL::VERIFY_NONE
l=a.get(o+'account/login').forms[0]
l.email,l.password=e
a.submit l,l.buttons[0]
g=a.get(s+'/users/login').forms.find{|f|f.action=='/users/authenticate'}
g.openid_identifier=o
a.submit g,g.buttons[-1]
loop{p=a.get s+'/questions'
10.times{p=p.links.find{|i|i.href=~/^\/questions\/\d/}.click}
puts'visited'
sleep 86400}

Ungolfed version:

require 'mechanize'

site, email, password = gets.split

agent = Mechanize.new
agent.agent.http.verify_mode = OpenSSL::SSL::VERIFY_NONE

login_form = agent.get('http://openid.stackexchange.com/account/login').forms.first
login_form.email = email
login_form.password = password
agent.submit login_form, login_form.buttons.first
puts 'logged in with SE openid'

site_login_form = agent.get(site + '/users/login').forms.find {|form| form.action == '/users/authenticate' }
site_login_form.openid_identifier = 'http://openid.stackexchange.com/'
agent.submit site_login_form, site_login_form.buttons.last
puts 'logged in to site'

loop {
    page = agent.get(site + '/questions')
    10.times do page = page.links.find{|link| link.href =~ /^\/questions\/\d/ }.click; end
    puts 'visited'
    sleep 60 * 60 * 24
}


Haskell, 190 bytes

i!j|j<0=reverse$map(0-)$i!(-j)|i==j=[i,i+1,-i]|i+1==j=[i]|i+j==0=[j+1]|i+j==1=[-j,-i,j]
_!j=[j]
j%(k:a)|j+k==0=a
j%a=j:a
i&a=foldr(%)[]$foldr((=<<).(!))[i]a
a?n=map(&a)[1..n]
(a#b)n=a?n==b?n

Try it online!

How it works

Let Fn be the free group on n generators x1, …, xn.  One of the first results in braid theory (Emil Artin, Theorie der Zöpfe, 1925) is that we have an injective homomorphism f : Bn → Aut(Fn) where the action fσi of σi is defined by

fσi(xi) = xixi + 1xi−1,
fσi(xi + 1) = xi,
fσi(xj) = xj for j ∉ {i, i + 1}.

The inverse fσi−1 is given by

fσi−1(xi) = xi + 1,
fσi−1(xi + 1) = xi + 1−1xixi + 1,
fσi−1(xj) = xj for j ∉ {i, i + 1}

and of course composition is given by fab = fa ∘ fb.

To test whether a = b ∈ Bn, it suffices to test that fa(xi) = fb(xi) for all i = 1, …, n.  This is a much simpler problem in Fn, where we only need to know how to cancel xi with xi−1.

In the code:

i!j computes fσi(xj) (where either i or j may be negative, representing an inverse),
foldr(%)[] performs reduction in the free group,
i&a computes fa(xi),
a?n computes [fa(x1), …, fa(xn)],
and (a#b)n is the equality test for a = b in Bn.


Pyth, 60 57 54 51 50 52 bytes
2015-10-22: fixing a bug took 2 bytes.
=HfTcjd.zdWHAcH]f|qTlH>jd<HhTQ1s.iGcJ|tlG1*d?H-QlsGJ

Try it online.


Ruby, 167 bytes

l={}
y=p=n=0
101.times{|i|
d/=d.abs if(d=n-p)!=0
l[y-=d]||=Array.new 101," "*4
l[y][i]=n.to_s.ljust 4
p,n=n,rand(18)-9}
puts l.sort_by(&:first).map(&:last).map(&:join)

First time golfing Ruby, so I'm sure I'm missing something.


Enumerate the primes using only unary arithmetic

Haskell, 212 135 130 111 104 characters

x⊡[1]=print x>>p x
x⊡s@(_:r)=s∇x where[]∇[]=p x;_∇[]=x⊡r;[]∇y=s∇y;(_:t)∇(_:y)=t∇y
p x=(1:x)⊡x
main=p[1]

The sieve was fun to implement, but simple exhaustive remainder checking is smaller. Strictly adheres to the terms. Unary numbers are represented as lists of 1.

First ten primes:

& runhaskell 13159-UnaryPrimes.hs | head
[1,1]
[1,1,1]
[1,1,1,1,1]
[1,1,1,1,1,1,1]
[1,1,1,1,1,1,1,1,1,1,1]
[1,1,1,1,1,1,1,1,1,1,1,1,1]
[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]
[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]
[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]
[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]

No library functions are used at all in the computation. In fact, the only library function used is print, which you can't get away from since you need some library function to output.


I give you ascii-art, you make it pseudo-3d

sed 4.2.2, Score 25
26 bytes, but scoring ¯ as 1, as per note in challenge.
s|1(1*)1|/\1\\|g
y/01/_¯/

Try it online!


Bash + coreutils + Lynx browser, 61 bytes
Thanks to @FDinoff for the tips:
lynx -dump codegolf.stackexchange.com/posts/28164/body|grep 2


JavaScript

That was fun!

arr = []
index = 0

function init(seed) {
    index = 0
    arr[0] = seed
    for (var i = 1; i < 624; i ++) {
        arr[i] = (1812433253 * (arr[i-1] ^ (arr[i-1] >>> 30)) + i) | 0
    }
 }

function getNumber() {
    if (index == 0) generateNumbers()

    var y = arr[index]
    y ^= (y >>> 11)
    y ^= ((y << 7) & 2636928640)
    y ^= ((y << 15) & 4022730752)
    y ^= (y >>> 18)

    index = (index + 1) % 624
    return y
}

function generateNumbers() {
    for (var i = 0; i < 624; i ++) {
        var y = (arr[i] & 0x80000000) + (arr[(i+1) % 624] & 0x7fffffff)
        arr[i] = arr[(i + 397) % 624] ^ (y >>> 1)
        if (y % 2 != 0) arr[i] ^= 2567483615
    }
}

// let's get our seed now from the SE API
var x = new XMLHttpRequest()
x.open('GET', 'http://api.stackexchange.com/2.2/answers?pagesize=10&order=desc&sort=activity&site=stackoverflow&filter=!Sri2UzKb5mTfr.XgjE', false)
x.send(null)
// we've got the answer data, now just add up all the numbers.
// only 4 digits at a time to prevent too big of a number.
var seed = 0
var numbers = x.responseText.match(/\d{0,4}/g)
for (var i = 0; i < numbers.length; i++) seed += +numbers[i]

init(seed)
for (var i = 0; i < 10; i++) console.log(getNumber())

I wrote up the Mersenne Twister in JS. Then, I realized I had to get a seed from somewhere.

So, I decided I would get it from the Stack Exchange API! (I could use localStorage and increment a counter, but that's no fun.) So, I grabbed the 10 most recently active answers, and then I just took every 4 or less consecutive digits in the response and added them up.

These seeds are always different, since Stack Overflow is constantly updating (and my quota keeps going down!) The numbers include answer IDs, question IDs, scores, up/downvote counts, owner rep/IDs, and the wrapper data (quota and such). On one run I got 256845, then 270495, and then 256048, etc....

This logs 10 random 32-bit two's-complement numbers to the console. Sample output:

247701962
-601555287
1363363842
-1184801866
1761791937
-163544156
2021774189
2140443959
1764173996
-1176627822


Bash, 27 bytes

trap -- 'trap|base64' EXIT

Based on this Bash quine. Note the trailing linefeed.

Try it online!


Python 2, 60 bytes

lambda l:min(l,key=lambda x:sorted(map(`l`.count,set(x)))+l)

Try it online!
Explanation
The idea is much like every other answer. In every word, we compute the frequency of each character. Then we take the word whose least frequent character occurs most often.
In the code, we sort the array as opposed to finding the minimum. Here is an example to show how this works: Input: thee lee baa. For each word, we compute a frequency table (duplicates are ignored): [(1, 1, 4), (1, 4), (1, 2)]. After sorting, the lexiocgraphically smallest list is (1, 1, 4), therefore the answer is thee.
There is also an edge case to consider: Input: a bc, which gives the following frequency table: [(1), (1, 1)]. The lexicographically smallest list would be (1), which is incorrect since the second list contains more 1s. I'll leave out the specifics of how the code resolves this issue


Python: 64 53 46 bytes
x=input()
m=x+3&~3
t=m-x
print m,m/4,t-t/2,t/2

Second Third attempt seems pretty minimal. Thanks for the help.
First attempt seems sort of long, we'll see what an hour or two of mulling it over will shave off of the byte count. Could also probably make it shorter if a function is allowed instead of program.
> python chip.py
9
(12, 3, 2, 1)

Also made a version that prints chips, seems like the -50 isn't worth it in python. Total score of 102-50=52.
x=input()
m=x+3&~3
n=m/4
t=m-x
s=['+'*-~n]
print'\n'.join(s+['+'+' '*~-n+'+']*~-n+s+[`m,n,t-t/2,t/2`])

Example:
> python chip.py
9
++++
+  +
+  +
++++
(12, 3, 2, 1)


Pyth, 12 bytes
l.Ml{.:Z)^UE

Try it online.
Pure brute force.
Explanation

Implicit: append Q to the program.
Implicit: read and evaluate a line of input (n) in Q.
E: read and evaluate a line of input (k).
U: get a range [0, ..., k-1].
^: get all n-length strings of [0, ..., k-1].
.M: find the ones that give a maximum for function f(Z):

.:Z: find the substrings of Z
{: remove duplicates
l: get the number of unique substrings

l: get the number of such strings


05AB1E, 64 63 56 53 48 46 bytes

°ÅPIùćÐ4FˆθUKD.ΔθyXÅ?yXÅ¿)¯gè}ÐNĀiR}¦}I¯JŽ9¦SΛ

-1 byte thanks to @Mr.Xcoder
-5 bytes thanks to @Grimy.

Try it online. (Times out for \$n>4\$. Here the slightly faster 53 bytes version which times out for \$n>7\$ instead.)

Explanation:

°                 # Raise the (implicit) input to the power 10
 ÅP               # Get a list of primes within the range [2, n^10]
   Iù             # Only keep those of a length equal to the input
ć                 # Extract the head; push the remainder-list and first prime separately
 Ð                # Triplicate this first prime
4F                # Loop 4 times:
  ˆ               #  Add the (modified) prime at the top of the stack to the global array
  θU              #  Pop and store the last digit of the prime in variable `X`
  K               #  Remove this prime from the prime-list
  D               #  Duplicate the prime-list
   .Δ             #  Find the first prime `y` in the prime list which is truthy for:
     θ            #   Get the last digit of prime `y`
     yXÅ?         #   Check if prime `y` starts with variable `X`
     yXÅ¿         #   Check if prime `y` ends with variable `X`
     )            #   Wrap the three results above into a list
      ¯g          #   Get the amount of items in the global array
        è         #   And use it to index into these three checks
                  #   (Note that only 1 is truthy for 05AB1E, so the `θ` basically checks
                  #    if the last digit of prime `y` is 1)
    }Ð            #  Triplicate the found prime
      NĀi }       #  If the loop index is 1, 2, or 3:
         R        #   Reverse the found prime
      ¦           #  And then remove the first digit of the (potentially reversed) prime
}                 # After the loop:
 I                # Push the input as length
 ¯J               # Push the global array joined together to a single string
 Ž9¦S             # Push compressed integer 2460 converted to a list of digits: [2,4,6,0]
 Λ                # Draw the joined string in the directions [2,4,6,0] (aka [→,↓,←,↑])
                  # of a length equal to the input
                  # (which is output immediately and implicitly as result)

See this 05AB1E tip of mine (section How to compress large integers?) to understand why Ž9¦ is 2460. And see this 05AB1E tip of mine to understand how the square is output with the Λ Canvas builtin.

The relevant code for printing the Canvas in a square is: NĀiR}¦ and I¯JŽ9¦SΛ. Let's take n=4 as example. The primes it will find with the rest of the code are [1009,9001,1021,1031]. The first code-part mentioned in this paragraph will save them as this instead: [1009,"001","201","301"]. The second code part of this paragraph will then use the Canvas builtin Λ with options:
- \$a\$ (side-length) = I: the input
- \$b\$ (string to print) = ¯J: the global array joined together (so "1009001201301" for n=4)
- \$c\$ (direction) = Ž9¦S: the directions [2,4,6,0], which will be [→,↓,←,↑] respectively


Husk, 7 bytes
This returns the result as a singleton list
ΩεSotṙ←

Try it online!
Explanation
Ω               Until
 ε              the result is a singleton list
     ṙ          Rotate left by
  S   ←         the first element
   ot           Then remove the first element


C++11
Further small update: Do much less adding, and try all numbers of form A*B+C. I believe that, within the time limit, this is fairly close to optimal, assuming you only use +, * and !. I leave other operators to people with more time than me!
Small update: Try harder to make use of factorials and numbers like 11....111. Also fixed bug that I wasn't counting ! in my costing
New result:
Primary Score = 3,810,660
Secondary Score = 12/09/2016 20:00
2532 1s, 1505 operators.
Various tricks put together. My program starts by setting the shortest program for all factorials and numbers of the form 111..111 (I don't think this falls foul of the hard-wiring rule, as these are the shortest ways to make these numbers. I could rearrange my code so I check these patterns in my dynamic programming if you want). Then do a partial dynamic programming approach, trying various forms:

A + B
A*B + C
A! + B
11....11 + B

Unfortunately I can't try all the ways of decomposing a number, so I choose for factorial and 11...11 to only try the nearest number, for A+B to try things near A/2, and for A*B+C to try only quite small As.
It would be easy to extend this to try some '-'s, by trying to overshoot slightly sometimes (particular in A*B - C), but I quite like only trying to grow.
Also, it is very hard to optimise the optimisation condition (I don't like it!) because in principle you can't come up with a 'best' value for each number in isolation, you have to consider your set of answers globally (which I don't intend to do).
Warning: This program needs a 64-bit machine, and around 10GB of memory (as I inefficiently make a giant array for all partially-computed results).
Program:
#include <algorithm>
#include <vector>
#include <string>
#include <assert.h>
#include <iostream>
#include <cmath>

std::vector<int> numints;
std::vector<int> numops;
std::vector<std::string> strings;

void fill_all_ones(long maxval)
{
    int val = 1;
    int len = 1;
    std::string name = "1";
    while(val < maxval) {
        val = val * 10 + 1;
        len++;
        name = name + "1";
        numints[val] = len;
        strings[val] = name;
    }
}

void get_best_for_next_full(long i);
// let's just assume this is the best way to make factorials
void fill_all_factorials(long maxval)
{
    // skip 1 and 2
    long result = 6;
    long val = 3;
    while(result < maxval) {
        get_best_for_next_full(val);
        strings[result] = "(" + strings[val] + ")!";
        numints[result] = numints[val];
        numops[result] = numops[val] + 1;
        val++;
        result = result * val;
    }
}

long get_nearest_all_ones(long i)
{
    int val = 11;
    int prevval = 1;
    while(val < i) {
        prevval = val;
        val = val * 10 + 1;
    }
    return prevval;
}

long get_nearest_factorial(long i)
{
    int val = 6;
    int prevval = 2;
    int step = 3;
    while(val < i) {
        prevval = val;
        step++;
        val = val * step;
    }
    return prevval;
}

int getlen(long i);

void get_best_for_next_full(long i)
{
    if(numints[i] > 0)
        return;

    int best = INT_MAX; // we'll do better than this
    std::string beststring = "invalid2";
    int ones = -1;
    int ops = -1;
    for(long loop = 1; loop <= i/2; loop++)
    {
        int new_val = getlen(loop) + getlen(i - loop);
        if(new_val < best) {
            best = new_val;
            ones = numints[loop] + numints[i - loop];
            beststring = "(" + strings[loop] + "+" + strings[i - loop] + ")";
            ops = numops[loop] + numops[i - loop] + 1;
        }
    }

    for(long loop = 2; loop * loop <= i; loop++)
    {
        long divisor = i / loop;
        long rem = i - loop*divisor;
        assert(rem >= 0);
        int new_val;
        if(rem == 0)
        {
            new_val = getlen(divisor) + getlen(loop);
        }
        else
        {
            new_val = getlen(divisor) + getlen(rem) + getlen(loop);
        }

        if(new_val < best) {
            best = new_val;
            if(rem == 0) {
                ones = numints[divisor] + numints[loop];
                beststring = "(" + strings[divisor] + "*" + strings[loop] + ")";
                ops = numops[divisor] + numops[loop] + 1;
            } else {
                ones = numints[divisor] + numints[loop] + numints[rem];
                beststring = "(" + strings[divisor] + "*" + strings[loop] + "+" + strings[rem] + ")";
                ops = numops[divisor] + numops[loop] + numops[rem] + 2;
            }
        }
    }

    numints[i] = ones;
    strings[i] = beststring;
    numops[i] = ops;
}

void check_divising(const long i, const long loop, long& best, long& ones, std::string& beststring, long& ops);
void check_adding(const long i, const long loop, long& best, long& ones, std::string& beststring, long& ops);

void get_best_for_next_partial(long i)
{
    if(numints[i] > 0)
        return;

    long best = INT_MAX; // we'll do better than this
    long ones = 1;
    std::string beststring = "invalid";
    long ops = 1;

    // Special: Try a nearby all ones
    {
        long loop = get_nearest_all_ones(i);
        check_adding(i, loop, best, ones, beststring, ops);
    }

    // Special: Try nearest factorial
    {
        long loop = get_nearest_factorial(i);
        check_adding(i, loop, best, ones, beststring, ops);
    }

    for(long loop = 2; loop * loop <= i; loop++)
    {
       check_divising(i, loop, best, ones, beststring, ops);
    }

    numints[i] = ones;
    strings[i] = beststring;
    numops[i] = ops;
}

void check_adding(const long i, const long loop, long& best, long& ones, std::string& beststring, long& ops)
{
    int new_val = getlen(loop) + getlen(i - loop);
    if(new_val < best) {
        best = new_val;
        ones = numints[loop] + numints[i - loop];
        beststring = "(" + strings[loop] + "+" + strings[i - loop] + ")";
            ops = numops[loop] + numops[i - loop] + 1;
    }
}

void check_divising(const long i, const long loop, long& best, long& ones, std::string& beststring, long& ops)
{
    long divisor = i / loop;
    long rem = i - loop*divisor;
    assert(rem >= 0);
    int new_val;
    if(rem == 0)
    {
        new_val = getlen(divisor) + getlen(loop);
    }
    else
    {
        new_val = getlen(divisor) + getlen(rem) + getlen(loop);
    }

    if(new_val < best) {
        best = new_val;
        if(rem == 0) {
            ones = numints[divisor] + numints[loop];
            beststring = "(" + strings[divisor] + "*" + strings[loop] + ")";
            ops = numops[divisor] + numops[loop] + 1;
        }
        else {
            ones = numints[divisor] + numints[loop] + numints[rem];
            beststring = "(" + strings[divisor] + "*" + strings[loop] + "+" + strings[rem] + ")";
            ops = numops[divisor] + numops[loop] + numops[rem] + 2;
        }
    }
}

long count = 0;
long countops = 0;

const int little_cutoff = 200000;

int getlen(long i)
{
    if(numints[i] == 0) {
        if(i < little_cutoff)
            get_best_for_next_full(i);
        else
            get_best_for_next_partial(i);
    }
    if(numints[i] == 0) {
        std::cout << i << " failure!" << numops[i] << ":" << strings[i] << std::endl;
        exit(1);
    }

    return numints[i] + numops[i];
}

const std::vector<long> vals = {945536, 16878234, 32608778, 42017515, 48950830, 51483452, 52970263, 54278649, 63636656, 78817406, 89918907, 90757642, 95364861, 102706605, 113965374, 122448605, 126594161, 148064959, 150735075, 154382918, 172057472, 192280850, 194713795, 207721209, 220946392, 225230299, 227043979, 241011012, 248906099, 249796314, 250546528, 258452706, 276862988, 277140688, 280158490, 286074562, 308946627, 310972897, 322612091, 324445400, 336060042, 346729632, 349428326, 352769482, 363039453, 363851029, 392168304, 401975104, 407890409, 407971913, 425780757, 459441559, 465592122, 475898732, 482826596, 484263150, 506235403, 548951531, 554295842, 580536366, 587051904, 588265985, 588298051, 590968352, 601194306, 607771869, 618578932, 626776380, 667919873, 681786366, 689854904, 692055400, 697665495, 711608194, 734027104, 750869335, 757710567, 759967747, 777616154, 830071127, 833809927, 835873060, 836438554, 836945593, 863728236, 864158514, 871273503, 881615667, 891619600, 897181691, 918159061, 920521050, 924502226, 929983535, 943162304, 950210939, 950214176, 962610357, 974842859, 988572832};

const long biggest = 988572832;

int main(void)
{
    numints.push_back(2);
    strings.push_back("(1-1)");
    numops.push_back(1);

    numints.push_back(1);
    strings.push_back("1");
    numops.push_back(0);

    numints.push_back(2);
    strings.push_back("(1+1)");
    numops.push_back(1);

    numints.resize(biggest + 1);
    strings.resize(biggest + 1);
    numops.resize(biggest + 1);

    fill_all_ones(biggest);
    fill_all_factorials(biggest);

    for(long i = 0; i < little_cutoff; ++i)
        get_best_for_next_full(i);

    for(long v : vals) {
        get_best_for_next_partial(v);
        std::cout << v << ":" << strings[v] << "\n";
        count += numints[v];
        countops += numops[v];

    }

    std::cout << count << ":" << countops << ":" << count * countops << "\n";

}

Results:
945536:((1111*(1+(11+11))+(1+1))*((1+11)*(1+(1+1))+1)+1)
16878234:(((1+(1+1111))*(1+(1+(1+111)))+(11+11))*((1+11)*11+1)+(1+1))
32608778:((((((1+(1+1)))!+(111+11111))*(11*11)+111)*(1+11)+1)*(1+1))
42017515:((11)!+((((1+111)*11)*11+1)*((1+11)*(1+11)+11)))
48950830:((((11+11)*(1+11))+(11111*(1+(1+1))))*((1+111)*(1+(1+11))+1)+1)
51483452:(((1+(1+1111))*(1+111)+1)*(11+(((1+11)*11+(1+1))*(1+(1+1))))+111)
52970263:((11+((1111*11+(1+(1+1)))*(1+(1+1))))*(111*(1+(1+11))+1)+11)
54278649:((11)!+(((1+(11+(11+(11+1111))))*111+1)*(1+(1+111))+1))
63636656:((((11+111)*(1+(1+1)))*(1+111)+11)*(1+(111+((((1+(1+1)))!)!*(1+1)))))
78817406:(((((111*(11+11)+1)*(1+1))*(1+111)+111)*(1+11)+1)*(1+11)+(1+1))
89918907:(((111+((1+(1+((1+(1+1)))!)))!)*(1+1))*(1+1111)+((11*11)*(1+(1+1))))
90757642:((1111+((11+11111)*(1+1)))*(111*(11+((1+(1+(1+1))))!)+1)+(1+111))
95364861:((11)!+(((((((11+11)*11)+11111)*111)*11+(1+1))*(1+1))*(1+1)+1))
102706605:(((11)!+(((111+((11*11)*11))*(1+(((1+(1+1)))!)!))*11))*(1+1)+1)
113965374:((((111*(1+(1+(1+11))))*1111+((1+(11+11))*11+1))*11+1)*((1+(1+1)))!)
122448605:(((((1+(1+1)))!)!+((111*11)*11))*((1+(((1+(1+1)))!)!)*(1+11)+1)+(1+1))
126594161:(((((11*11)+(((1+(1+1)))!)!)*(1+111))*(1+11)+1)*(1+111)+1)
148064959:((11)!+(((111*111+(1+11))*111+1)*((1+(1+11))*((1+(1+1)))!+1)+(1+(1+1))))
150735075:(((111*111+(1+1))*(1+1111)+(1+11))*11+(1+((1+(1+1)))!))
154382918:((1111*(1+11)+1)*(((1+(11+(111+111)))*(1+1))+11111)+111)
172057472:((((((1+11)*11)*11+1)*(1+(1+1)))+11111)*(11+11111)+((1+11)*11))
192280850:(((11111*(1+11)+11)*(1+(((1+(1+1)))!)!)+(11+111))*(1+1))
194713795:((11)!+((((111+11111)*(1+(1+(1+111)))+((1+(1+1)))!)*11)*11+1))
207721209:(((111*111)*(1+(11+11))+(1+1))*(1+(1+(11+(((1+(1+1)))!)!)))+(1+(1+(1+1))))
220946392:((11)!+((((1+(1+(1+1111)))*(11+111))*111+11)*(1+11)+(1+(1+(1+1)))))
225230299:((111111111+((111*111+(1+((1+(1+1)))!))*(11+111)+(11+11)))*(1+1)+1)
227043979:((((((11+11)*11)+11111)*(1+(1+1))+1)*1111+(1+(1+1)))*((1+(1+1)))!+1)
241011012:(((11)!+((11)!+((11)!+((11+1111)*((1+111)*((1+(1+1)))!+1)))))*(1+1))
248906099:(((11111+(((((1+(1+1)))!)!*111)*(1+1)))*(1+111)+111)*(1+(1+11)))
249796314:(((11)!+(((((1+(1+1)))!)!+((1+1111)*(1+11)))*(11+111)+111))*((1+(1+1)))!)
250546528:((11)!+(((111*111)*(1+(1+(1+11)))+11)*(111*11)+(1+(11+1111))))
258452706:(((11)!+(((((1+(1+1)))!)!*((1+(1+1)))!+1)*(11+(((1+(1+1)))!)!)))*((1+(1+1)))!)
276862988:(((11+(1111*(1+1)))*(((1+(1+1)))!+1111))*111+(((1+(1+1)))!+11))
277140688:(((111*111+(1+(1+(1+(1+11)))))*(1+1))*(11+(111+11111))+(1+111))
280158490:((11)!+(((1+(111+111111))*(((1+(1+1)))!)!+(1+(1+1)))*(1+(1+1))+1))
286074562:(((11)!+((((11+1111)*(11+11))*(1+1)+1)*(1+(11+1111))))*(1+(1+1))+1)
308946627:((11)!+((((1+1111)*(((1+(1+1)))!)!+((11+11)*(1+1)))*(1+111)+1)*(1+(1+1))))
310972897:((11111*(1+(1+1))+1)*(((1111+(111*11))*(1+1))*(1+1)+1)+11)
322612091:((((((1+11)*(1+11))*(1+11)+(1+1))*111+1)*(1+111))*(1+(1+(1+(1+11))))+11)
324445400:(((1111111+(1+(1+1)))*(1+1))*((1+11)*(1+11)+(1+1))+(1+111))
336060042:(((1+1111)*(1+(11+111))+(1+111))*(11+((111*11+1)*(1+1)))+(1+1))
346729632:(((1+(1+(11111+(111*111))))*((1+111)*11+1)+(1+(1+(1+11))))*(1+11))
349428326:(((((11+11)*11)*11+1)*(1+1111)+1)*(1+(((1+(1+1)))!+111)))
352769482:(((1+11111)*(111*(11+11))+((11+111)*((1+1)*(1+1)+1)))*(1+(1+11)))
363039453:(((((1+111)*(1+111)+1)*(1+1))*(1+(1+11))+11)*(1+(1+1111)))
363851029:((((111*11+1)*1111+11)*((1+11)*11+(1+1))+(1+11))*(1+1)+1)
392168304:(((((1+(1+1111))*(1+111))*11+1)*(1+(1+11))+11)*(11+11))
401975104:(((((1+11)*(1+11)+1)*111)*111+11)*((1+111)*(1+1)+1)+(1+(1+(1+1))))
407890409:(((1+11111)*11)*((1+1111)*(1+(1+1))+1)+((1+1111)*(1+1)+1))
407971913:((11)!+((11)!+(((1+(1+11111))*(1+1)+1)*(((11+111)*11)*11+1)+(1+1111))))
425780757:(((1111+((((1+11)*11)+11111)*(1+(1+1))))*11+1)*1111+((1+(1+1)))!)
459441559:(((11111+(((1+(1+111))*(1+1)+1)*111))*111+1)*(1+(1+(1+111)))+(1+(1+11)))
465592122:(((11)!+((((1111*(11*(1+(1+1))+1)+1)*(1+(11+11)))*(1+1)+1)*111))*(1+1))
475898732:(((11)!+(((((1+111)*11+(1+1))*(1+11))*(1+1)+1)*(1+(1+111))))*11+1)
482826596:(((1+(((111*11)*11)+(11111*(1+1))))*111+1)*(11+111)+((1+(1+1)))!)
484263150:(((111*111+(1+(1+1)))*111+11)*(1+(111+((11+11)*11))))
506235403:(((1+11))!+((((1+(1+1111))*(1+1111)+((11+111)*(1+1)))*11+1)*(1+1)+1))
548951531:((((111+111)*(1+1)+1)*111+11)*11111+((11+111)*(1+11)+1))
554295842:(((1+11))!+((((1+1111)*111+1)*((1+1)*(1+1)+1))*(11+111)+(1+111)))
580536366:(((1+(111+((111*111+11)*(1+11))))*(1+111)+1)*(11+((1+(1+(1+1))))!)+11)
587051904:(((((1+1111)*(1+11))*(1+(1+1))+1)*(111*11+1)+(111*((1+(1+1)))!))*(1+11))
588265985:(((1+11))!+((1+(111+(1111*(1+(1+11)))))*((1+111)*(11*((1+(1+1)))!+1)+(1+(1+1)))))
588298051:((((((11+111)*11)*11)+(11111*(1+(1+1))))*(1+1111)+1)*11)
590968352:(((((((1+(1+1)))!)!+11111)*111+(11+11))*((1+111)*(1+1)+1)+1)*(1+1))
601194306:((((1111*(1+(1+(1+(11+111))))+1)*111+(1+1))*(1+(1+1))+1)*(1+(1+11))+11)
607771869:(((1+11))!+(((11)!+(((1111*11+1)*(1+1))*(1+(11+111))+11))*(1+(1+1))))
618578932:(((((1111*111)*11+1)*(1+1)+1)*(1+1))*(1+(1+(1+111)))+(1+111))
626776380:((((1+(1+(1+1))))!+((((1+(1+1)))!)!+(1111*111)))*(1+(11+((1+((1+(1+1)))!))!)))
667919873:((((((1+(11+111))*11+1)*111+(1+(1+1)))*1111+1)*(1+1))*(1+1)+1)
681786366:(((1+11))!+((11)!+(((11)!+((11)!+((1+(1+11111))*((1+11)*(1+11))+111)))*(1+1))))
689854904:(((11+((11111+((1+1111)*11))*(1+1)))*((11+111)*11+1)+11)*11+(1+1))
692055400:(((1+11))!+(((((1+(1+111))*(1+(1+(1+11))))*11)*11+1)*(1+(1+1111))+1))
697665495:(((1+11))!+(((((((1+(1+1)))!)!*(1+(1+(1+111)))+1)*(1+11))*(1+1)+1)*111))
711608194:(((11)!+(((1+(1+(1+(1+1111))))*(11+((11+111)*(1+1)))+(1+1))*1111))*(1+1))
734027104:(((111*(11+((1+(1+(1+1))))!)+1)*(((1+(1+1)))!+11)+1)*11111+1111)
750869335:((11111111+((1+(((1+(1+1)))!)!)*((1+11)*11+1)+1))*(11*((1+(1+1)))!+1))
757710567:((((((11+111)*11)+111111)*(1+(1+1))+1)*(1+(11+1111))+(1+(1+1)))*(1+1)+1)
759967747:(((11)!+(((1+(1+(111+11111)))*(1+(1+111)))*(1+(11+11))+1))*11)
777616154:((11111*(111+(((111*11+1)*(1+1))*(1+1)))+(11+111))*(1+(1+(1+11))))
830071127:((((1+111)*111)*((1+(1+1)))!+1)*(((1+(1+1)))!+(11+11111))+(111*(1+1)+1))
833809927:((((11+1111)*(1+1)+1)*111+1)*(1+(1+(11+(1111*(1+(1+1))))))+111)
835873060:(((((11+(111+111))*111+1)*(1+(1+111))+1)*(1+(1+11))+1)*(11+11))
836438554:(((1+11))!+(((11111*(1+1)+1)*((11+(((1+(1+1)))!)!)*11+1)+1111)*(1+1)))
836945593:(((1111*1111+(1+111))*(1+(1+111))+(1+(1+1)))*((1+(1+1)))!+1)
863728236:(((1+(1111+((11+11111)*(1+1))))*(111*111+((1+(1+1)))!))*(1+(1+1)))
864158514:(((1+11))!+(((1111*(1+(1+(1+11)))+((1+(1+1)))!)*111+1)*(111*(1+1)+1)+11))
871273503:((((1+11111)*(11+11)+1)*((1+(1+11))*(1+1)+1)+1)*((1+11)*11)+111)
881615667:((11111+((111*111+11)*(1+1)))*((111*111)*(1+1)+1)+((11+1111)*11))
891619600:(((11)!+((11)!+((((1+(11+11))*(1+1))+111111)*11)))*11+(1+(1+1)))
897181691:((11+(11+(11+((1+(1+((1+(1+1)))!)))!)))*(11+(11111*(1+1)))+((111*11+1)*11))
918159061:(((11)!+(((11+11)*11+1)*(1+(1+11))))*(1+(11+11))+(1+(1+(1+1))))
920521050:(((11)!+((((1+(11+1111))*(1+(1+(1+1111))))*(1+111)+111)*(1+(1+1))))*(1+1))
924502226:((((1111*(1+11))*(1+1)+1)*((111*(1+11)+1)*(1+1)+1))*(1+(1+11))+11)
929983535:(((11)!+((((11+111)*111+1)*111)*((1+11)*(1+1)+1)+(1+1)))*(1+11)+11)
943162304:(((11)!+((((((1+((1+(1+1)))!))!+(111*111))*111+(1+1))*(1+111))*(1+1)))*(1+1))
950210939:(((11+(111+11111))*(1+(1+(1+(((1+(1+1)))!)!)))+(1+1))*(((1+(1+1)))!+111)+(1+1))
950214176:(((11)!+((((111*111)*(1+(1+11)))*11+1)*((1+(11+111))*(1+1)+1)))*(1+1))
962610357:((((1+11))!+((1+((((1+(1+1)))!)!+(111*(1+11))))*(11+1111)+(1+111)))*(1+1)+1)
974842859:((((((11*(1+((1+(1+1)))!))+1111)*11+1)*(1+111))*((1+(1+1)))!)*111+11)
988572832:(((111111111+((11111*(1+(1+1111))+11)*11+(1+(1+1))))*(1+1))*(1+1))


Retina, 20 bytes

T`Lld`Ⓐ-⓪①-⑨

Try it online!

How it works

There's a gap between the code points of (0) and (1), but – fortunately – the character right after (z) is (0). This way, we can transliterate the character from concatenated ranges A-Za-z0-9 to the characters of the concatenated ranges (A)-(0)(1)-(9).

The rest is straightforward: T activates transliteration mode, Lld yields all uppercase ASCII letters (L), all lowercase ASCII letters (l) and all digits (d), and Ⓐ-⓪①-⑨ the corresponding bubble characters.


Mathematica - 106 bytes

c=RegionPlot[x^2+y^2<Abs@Sin[#x~ArcTan~y/2]||x>0&&y^2<.001,{x,-1,1},{y,-1,1},Frame->0>1,PlotStyle->Green]&

Ungolfed version:

c[leaves_] := (
    angle = ArcTan[x,y];
    RegionPlot[
        x^2 + y^2 < Abs[Sin[leaves*angle/2]]
        || x > 0 && y^2 < .001
      , {x,-1,1}
      , {y,-1,1}
      , Frame -> False, PlotStyle -> Green
    ]);

Here are the outputs for c[3] through c[6].

At the cost of another 7 bytes you can improve the colour (using PlotStyle->Darker@Green or PlotStyle->Hue[.3,1,.7] instead), and for another 15 bytes you can remove some of the sampling artifacts (using an additional option ,PlotPoints->90), giving a total of 128 bytes for these beauties:

The braces and commes in those pictures are not produced by c, but just by how I output them to fit them all in one row.

Lastly, here is an attempt at somewhat neater shading. I didn't even bother golfing this down further, the option names are just too long. I'm not even sure I'm too pleased with the result, but I thought I'd post it anyway. This is 188 bytes as it stands:

c=RegionPlot[x^2+y^2<Abs@Sin[(l=#)x~(a=ArcTan)~y/2]||x>0&&y^2<.001,{x,-1,1},{y,-1,1},Frame->0>1,PlotPoints->90,ColorFunction->(Hue[.3,1,.5+.2Sin[.5l#~a~#2]^8]&),ColorFunctionScaling->0>1]&


Parsing the raw bytestream: Haskell (319 = 332 - 13)

Without any imports at all, this program crops P1 PBM images.

g _[]=[]
g z x=(\(a,b)->a:g z b).splitAt z$x
q=map
f=filter
main=do c<-readFile"in.pbm";let(r:p)=tail.f((/='#').head).lines$c;(w:h:_)=(q read).words$r;m=min w h;t s=take m.drop((s-m)`div`2);k d=[[m,m]]++(q(t w)(t h d))in writeFile"out.pbm".("P1\n"++).unlines.q(unwords.(q show)).k.(q((q read).g 1)).take h.g w.f(`elem`"01").concat$p

Special case: helpful formatting (214 = 227 - 13)

My first attempt at PBM (P1) was based on the example at Wikipedia and assumed spaces separated the pixels, and lines in the text correlated with lines in the image. Under those conditions, this shorter version works fine.

main=do c<-readFile"in.pbm";writeFile"out.pbm".("P1\n"++).unlines.q(unwords.(q show)).k.q((q read).words).tail.filter((/='#').head).lines$c
k((w:h:_):d)=let m=min w h;t s=take m.drop((s-m)`div`2)in[[m,m]]++(q(t w)(t h d))
q=map

Bonus feature: strips out comments!

Both of the above work in essentially the same manner as the original below, but with a simpler header, lower bit depth, and no padding, although the topmost program works harder to allow for a range of formatting options.

Also available in a wide range of colours: Haskell (545 = 558 - 13)

No pre-existing image-handling functions were harmed in the making of this program.

Uncompressed 24-bit RGB bitmaps have a fairly straight-forward header system but are complicated by the mod-4 padding for each row's byte array. This code grabs the bitmap offset, width, and height from the input header, calculates the row padding, and extracts the bitmap data into a list of lists (rows of columns, bottom-left corner first).

Cropping is as simple as dropping half the excess and then taking the desired length from each list. The new file size is calculated as 3*(padded width)*height + 54 bytes (for the minimal required headers). The new header is constructed and the cropped image data appended. It's all mapped to characters and written back out to disk.

Input: in.bmp (6 characters removed from total)
Output: out.bmp (7 characters removed from total)

I think there's still some redundancy still in there, but my brain hurts to look at it this way.

import System.IO
import Data.Char
import Data.List.Split
main=do k"in.bmp"ReadMode(\h->do i h u;c<-hGetContents h;let d=l(ord)c;w=s 18d;h=s 22d;p=o w;m=min w h;q=o m;j a b=y a(r b m)in k"out.bmp"WriteMode(\g->do i g u;hPutStr g$"BM"++l chr((z e[m*(3*m+q)+54,0,54,40,m,m,1572865,0,0,1,1,0,0])++((z((++(f q$cycle[0])).y(3*m)(3*r w m)).j m h$chunksOf(3*w+p)$n(s 10d)d)))))
i=hSetBinaryMode
k=withFile
z=concatMap
l=map
v=div
f=take
n=drop
u=True
y t d=f t.n d
s d=sum.zipWith(*)(l(256^)[0..3]).y 4d
o=(`mod`4)
r a b=v(a-b)2
e x=l((`mod`256).(x`v`).(256^))[0..3]

For comparison, an ungolfed version is over 8 times as long, at 4582 (4595 - 13) bytes:

import System.IO
import Data.Char
import Data.List.Split

main = readImage cropImageToSquare

cropImageToSquare fileHandle = do

  hSetBinaryMode fileHandle True
  fileContents <- hGetContents fileHandle

  let
    inImageData         = asBytes fileContents

    inImageBitmapOffset = getIntFromWordAt 10 inImageData
    inImageWidth        = getIntFromWordAt 18 inImageData
    inImageHeight       = getIntFromWordAt 22 inImageData

    inImageBitmapData   = drop inImageBitmapOffset inImageData
    inImageBitmap       = chunksOf (paddedBytesForWidth inImageWidth) inImageBitmapData

    outImageSideLength  = min inImageWidth inImageHeight

    outFileHeader       = fileHeader  outImageSideLength outImageSideLength
    outImageHeader      = imageHeader outImageSideLength outImageSideLength
    outHeaders          = outFileHeader ++ outImageHeader

    outImageBitmap      = crop outImageSideLength outImageSideLength inImageWidth inImageBitmap

    in
      writeImage "out.bmp" outHeaders outImageBitmap

--- Read Image ---------------------------------------------------------

readImage = withFile "in.bmp" ReadMode

--------------------------------------------------------- Read Image ---

--- Write Image --------------------------------------------------------

writeImage filename header imageBitmap = do
  withFile filename WriteMode write'
    where
      write' fileHandle = do
        hSetBinaryMode fileHandle True
        hPutStr fileHandle . ("BM"++)
                           . map chr $ (concatMap wordFromInt header)
                                     ++ (concat imageBitmap)

-------------------------------------------------------- Write Image ---

--- Character-Integer Conversion ---------------------------------------

asBytes = map ord

getWordAt offset = take 4 . drop offset

getIntFromWordAt offset = intFromWord . getWordAt offset

intFromWord     = sum . zipWith (*) (map (256^) [0..3])

wordFromInt int = map((`mod` 256) . (int `div`) . (256^)) [0..3]

--------------------------------------- Character-Integer Conversion ---

--- Headers ------------------------------------------------------------

fileHeader width height = [ fileSize
                          , reserved
                          , bitmapOffset
                          ]
  where
    fileSize     = imageFileSize width height
    reserved     = 0
    bitmapOffset = 54

imageFileSize width height = 54 + height * (paddedBytesForWidth width)
paddedBytesForWidth width  = 3 * width + rowPadding width
rowPadding = (`mod` 4)

imageHeader width height = [ imageHeaderSize
                           , width
                           , height
                           , planesAndBits
                           , compression
                           , bitmapSize
                           , horizontalImageResolution
                           , verticalImageResolution
                           , paletteSize
                           , coloursUsed
                           ]
  where
    imageHeaderSize  = 40
    planesAndBits    = int32FromInt16s colourPlanes bitDepth
    colourPlanes     = 1
    bitDepth         = 24
    compression      = 0
    bitmapSize       = 0
    horizontalImageResolution = pixelsPerMetreFromDPI 72
    verticalImageResolution   = pixelsPerMetreFromDPI 72
    paletteSize      = 0
    coloursUsed      = 0

pixelsPerMetreFromDPI = round . (* (100/2.54))

int32FromInt16s lowBytes highBytes = lowBytes + shift 2 highBytes
shift bytesUp number  = (256 ^ bytesUp) * number

------------------------------------------------------------ Headers ---

--- Crop Image ---------------------------------------------------------

crop toHeight toWidth fromWidth = cropWidth toWidth fromWidth
                                . cropHeight toHeight

cropHeight toHeight image = take toHeight
                          . drop ( halfExtra (length image) toHeight)
                          $ image

cropWidth toWidth fromWidth image = map ( padRow toWidth
                                        . take (3 * toWidth)
                                        . drop (3 * (halfExtra fromWidth toWidth))
                                        )
                                      $ image

padRow toWidth xs = take (paddedBytesForWidth toWidth)
                      $ xs ++ (repeat 0)

halfExtra fromLength toLength = (fromLength - toLength) `div` 2

--------------------------------------------------------- Crop Image ---


Python 2, 59 bytes

s="------x------\n|  |  x  |  |\n|  |--x"
print s+s[-2::-1]

Try it online!

Prints the first half of the string followed by its reverse. It's boring but efficient. I tried extracting repeating parts of out s, especially the -, but didn't find anything shorter.

Python 2, 59 bytes

for n in 6,0,2,0,6:x='-'*n+'  |  |'[n:];print x[::-1]+'x'+x

Try it online!

Using Jo King's construction.

Python 2, 62 bytes

b='|  '*2
for r in'-'*6,b,'|  |--',b,'-'*6:print r+'x'+r[::-1]

Try it online!

Prints the first half of each line, followed by 'x', followed by the first half reversed.


TSQL, 61 59 bytes
DECLARE @ int=50

,@x int=1WHILE @>2SELECT @=@/4*2,@x*=2PRINT replicate(@,@x)

Try it out


Transform number into 7-segment display pattern

Commodore 64 BASIC

PETSCII art rules :)

Output:


Python 3, O(n*log(n)), 167 bytes

import math
def f(p):p=[math.atan2(*x)for x in p];q=sorted(p);d=[b-a for a,b in zip(q,q[1:])]+[math.pi*2-q[-1]+q[0]];i=d.index(max(d));return map(p.index,(q*2)[i:i+2])

Try it online!

The sorting step takes O(n*log(n)) time, all other steps take linear time.

Ungolfed

import math
def f(p):
  p=[math.atan2(x, y)for x, y in p]   # convert coords to angle (radians)
  q=sorted(p)                         # sort by angle
  d=[b-a for a,b in zip(q,q[1:])]     # calculate the difference between two adjacent points
  d+=[math.pi*2-q[-1]+q[0]]           # difference between first and last point
  i=d.index(max(d))                   # where is the maximum delta?
  return map(p.index,(q*2)[i:i+2])    # where were these two points in the original list?


Shortest code to find next prime palindrome

CJam, 15 bytes

li{)__mfsW%i^}g

Reads a single, positive integer from STDIN. Try it online.

Example run

$ cjam <(echo 'li{)__mfsW%i^}g') <<< 250
313

How it works

This uses a tricky prime check instead of the built-in mp:

15 mf, for example, pushes [3 5]. We cast to a string ("35"), reverse that string ("53"), cast to integer (53) and XOR the result with the original integer (22). Since the result in non-zero, 35 is not a palindromic prime.

li                 " N := int(input())        ";
  {          }g    " While R:                 ";
   )               "   N += 1                 ";
     _mfs          "   R := str(factorize(N)) ";
         W%i       "   R := int(reverse(K))   ";
    _       ^      "   R ^= N                 ";


Assembly (DOS .com file)

start:

%rep 2
    call $+3

    mov ah, 9
    mov dx, 100h + (end - start) / 2
    int 21h

    mov ah, 2
    mov dl, "$" - 1
    inc dx
    int 21h

    ret
    db "$"

%endrep

end:

Assemble with nasm quine.asm -o quine.com. Try with dosbox quine.com.

Proof of correctness (you can also verify by the smilies here):


ECMAScript 6 Javascript (399 401 431)

Has to be run in a browser supporting ECMAScript 6 due to the arrow functions.

Here are fiddles which have been altered to run in any (common) browser by not using arrow functions. They also print to a textarea instead:

Normal
Animated

Golfed Version

i=prompt(),v=[],c=0,x=[0],y=[0],s='unshift',k='slice',t='sort',h=[0,-1,0,1,0]
while(c<i.length){m='wasd'.indexOf(i[c++]);v[s]('^<v>'[m]);x[s](x[0]+h[m]);y[s](y[0]+h[m+1])}f=(a,b)=>a-b
q=x[k]()[t](f)[0],e=x[k]()[t]((a,b)=>b-a)[0],w=y[k]()[t](f)[0],o=[]
while((i=y.pop())!=null){i-=w;j=x.pop()-q;t=(o[i]||Array(e+1-q).join(" ")).split("");t.splice(j,1,v.pop()||"@");o[i]=t.join("")}alert(o.join("\n"))

Animated GIF:

One of the OP's examples:

The example from Stretch Maniac:

Ungolfed

Here is a (slightly) ungolfed version from sometime before I started really golfing it down:

var input = prompt(),
    values = [],
    c = 0,
    x = [0],
    y = [0],
    s = 'unshift';
while (c < input.length) {
    var mapped = 'wasd'.indexOf(input[c++]);
    values[s]('^<v>'[mapped]);
    x[s](x[0]+[0, -1, 0, 1][mapped]);
    y[s](y[0]+[-1, 0, 1, 0][mapped]);
}

var minX = x.slice().sort(function (a,b){return a-b})[0];
var maxX = x.slice().sort(function (a,b){return b-a})[0];
var minY = y.slice().sort(function (a,b){return a-b})[0];

var output = [];
while((i=y.pop())!=null) {
    i-=minY;
    j=x.pop()-minX;
    t=(output[i]||Array(maxX+1-minX).join(" ")).split("");
    t.splice(j,1,values.pop()||"@");
    output[i]=t.join("");
}

console.log(output.join("\n"));


Funciton, 1840 bytes

Damn, this language is ungolfable.

This program expects the first character of the input to be the character to search for, and the rest of the input to make the string to search through. This means that aaaba will search for a in the input aaba (and thus output 1). You can separate them with a newline or space (a aaba) but only because the extra newline/space makes no difference to the output.

As always, you can get a nicer-looking rendering (without the line spacing) if you execute $('pre').css('line-height',1) in your browser console.

      ┌───┐
      │╓─╖└─────────────┐
      └╢³╟┐    ┌─────┐ ┌┴┐╓─╖
┌─────┐╙─╜└────┤┌─╖ ┌┴╖│┌┘║¹║
│     ├───────┐└┤²╟─┤·╟┘│ ╙┬╜╔═══════╗
│    ┌┴╖╔═╗┌─╖├┐╘╤╝ ╘╤╝┌┘  └┬╢2097151║
│    │♭║║5╟┤%╟┘└─┴──┐│┌┘┌───┘╚═══════╝
│    ╘╤╝╚═╝╘╤╝╔═╗┌─╖│││┌┴┐┌────┐
│    ┌┴╖   ┌┘ ║3╟┤%╟┘││└┬┘│╔══╗└┐
│  ┌─┤·╟─┐ │  ╚═╝╘╤╝ │└┐  │║21╟┐│
│  │ ╘╤╝ ├─┘┌─────┘  └┐└┐ │╚══╝│└─┐
│ ┌┴╖┌┴╖┌┴╖┌┴╖┌─╖    ┌┴╖│ │┌─╖┌┴─╖│
│┌┤·╟┤?╟┤?╟┤?╟┤+╟────┤³║│ └┤²╟┤>>║└──┐
││╘╤╝╘╤╝╘╤╝╘╤╝╘╤╝    ╘╤╝│  ╘╤╝╘╤═╝╓─╖│
││ │ ┌┴╖┌┴╖┌┴╖┌┴╖╔═╗ ┌┴╖│  ┌┴╖ ├──╢²╟┤
││ └─┤·╟┤·╟┤?╟┤·╟╢1║┌┤·╟┘  │♯║┌┴╖ ╙─╜│
│└──┐╘╤╝╘╤╝╘╤╝╘╤╝╚═╝│╘╤╝   ╘╤╝│¹║┌───┘
└──┐│╔╧╗ └┬─┘ ┌┴╖   │┌┴─╖   │ ╘╤╝│
   ││║1║ ┌┴┐┌─┤?╟───┴┤>>╟┐ ┌┴╖┌┴╖│
   ││╚═╝ └┬┘│ ╘╤╝    ╘══╝│┌┤?╟┤=║│
   │└────┐│╔╧╗     ┌─────┘│╘╤╝╘╤╝│
╔═╗└────┐│├╢0║╔══╗┌┴╖┌─╖ ╔╧╗   └─┘
║ ║     │└┘╚═╝║21╟┤×╟┤♯╟┐║0║
╚╤╝     └──┐  ╚══╝╘═╝╘═╝│╚═╝
 │┌──┴────╖└────────────┘
 ││int→str║
 │╘══╤════╝
┌┴─╖┌┴╖┌─╖╔╗
│>>╟┤³╟┤¹╟╢║
╘═╤╝╘═╝╘═╝╚╝
╔═╧╗
║21║
╚══╝

(1840 bytes when encoded as UTF-16.)

Explanation

¹ returns the first character of a string.
² counts the number of occurrences of a character at the start of a given string. For example, given the character a and the string aaba, it returns 2. For a and baa, it returns 0.
³ calls ² to get the number of characters at the start, examines whether the number is divisible by 3 and 5 and whether it is equal to 1 and determines the proper increment/decrement. It also removes one extra character from the start of the string (e.g. given aaabba it removes 3+1=4 characters, giving ba). Then it calls itself recursively with the shorter string and adds the result.
The main program calls ¹ to remove the first character from the input and calls ³ with that character and the rest of the string as separate arguments.