Python 2 Python 3, 359 365 338 chars

from itertools import*
from collections import*
m=h=set(product(*['123456']*4))
def f(g,k):b=sum(x==y for x,y in zip(g,k));return'%s %s'%(sum(min(g.count(c),k.count(c))for c in set(g))-b,b)
while len(m)>1:g=min(h,key=lambda g:max(Counter(f(g,k)for k in m).values()));print(*g);s=input();m=set(x for x in m if s==f(g,x))
print(*(m.pop()))

Funny, it took me many edits to realize I had a five character variable name.

I do not like the long imports.  It feels like I should be able to implement a replacement for collections.Counter that would save the import.

I also do not like the print(*(m.pop())) at the end.  It feels like it should disappear into the while loop, but I can't find a way to do it without making it longer.


Jelly, 14 13 12 bytes

;"s€2U×¥/ḅ-U

Try it online!

How it works

;"s€2U×¥/ḅ-U Main link. Input: [a1, a2, a3], [b1, b2, b3]

;"           Concatenate each [x1, x2, x3] with itself.
             Yields [a1, a2, a3, a1, a2, a3], [b1, b2, b3, b1, b2, b3].
  s€2        Split each array into pairs.
             Yields [[a1, a2], [a3, a1], [a2, a3]], [[b1, b2], [b3, b1], [b2, b3]].
       ¥     Define a dyadic chain:
     U         Reverse the order of all arrays in the left argument.
      ×        Multiply both arguments, element by element.
        /    Reduce the 2D array of pairs by this chain.
             Reversing yields [a2, a1], [a1, a3], [a3, a2].
             Reducing yields [a2b1, a1b2], [a1b3, a3b1], [a3b2, a2b3].
         ḅ-  Convert each pair from base -1 to integer.
             This yields [a1b2 - a2b1, a3b1 - a1b3, a2b3 - a3b2]
           U Reverse the array.
             This yields [a2b3 - a3b2, a3b1 - a1b3, a1b2 - a2b1] (cross product).

Non-competing version (10 bytes)

OK, this is embarrassing, but the array manipulation language Jelly did not have a built-in for array rotation until just now. With this new built-in, we can save two additional bytes.

ṙ-×
ç_ç@ṙ-

This uses the approach from @AlexA.'s J answer. Try it online!

How it works

ṙ-×     Helper link. Left input: x = [x1, x2, x3]. Right input: y = [y1, y2, y3].

ṙ-      Rotate x 1 unit to the right (actually, -1 units to the left).
        This yields [x3, x1, x2].
  ×     Multiply the result with y.
        This yields [x3y1, x1y2, x2y3].

ç_ç@ṙ-  Main link. Left input: a = [a1, a2, a3]. Right input: b = [b1, b2, b3].

ç       Call the helper link with arguments a and b.
        This yields [a3b1, a1b2, a2b3].
  ç@    Call the helper link with arguments b and a.
        This yields [b3a1, b1a2, b2a3].
_       Subtract the result to the right from the result to the left.
        This yields [a3b1 - a1b3, a1b2 - a2b1, a2b3 - a3b2].
    ṙ-  Rotate the result 1 unit to the right.
        This yields [a2b3 - a3b2, a3b1 - a1b3, a1b2 - a2b1] (cross product).


Simple DTMF decoding: find the phone key!

JavaScript (ES6), 39 35 bytes

a=>b=>"310*58# 47269"[a%b%83%16%13]

Maps the two inputs into numbers in the range [0, 13) by calculating:
col % row % 83 % 16 % 13.
Takes input in currying syntax (f(col)(row)) and returns a single-char string.

Test Cases

let f=
a=>b=>"310*58# 47269"[a%b%83%16%13]

console.log( f(1336)(941) )
console.log( f(1209)(697) )
console.log( f(1336)(697) )
console.log( f(1477)(697) )
console.log( f(1209)(770) )
console.log( f(1336)(770) )
console.log( f(1477)(770) )
console.log( f(1209)(852) )
console.log( f(1336)(852) )
console.log( f(1477)(852) )
console.log( f(1209)(941) )
console.log( f(1477)(941) )
.as-console-wrapper{max-height:100%!important}

History

Started with the range of [0, 20) with calculation col % row % 29 % 20, which required 8 wasted characters in the mapping.


Haskell, 552 499 493 characters

import Control.Monad.RWS
import Data.Map
main=interact$z.lines
z x=let(s:_,w)=evalRWS(mapM(q.t)x)w[]in s.f.i.t$last x
p=get>>=q
q(l:":":x)=x%do a<-p;tell$f[(l,a)];r a
q(v:"+":x)=x%fmap(.a v 1)p
q(v:"-":x)=x%liftM2(d v)p p
q(('"':s):x)=x%r(\w->unlines[init s,do(v,x)<-assocs w;v++'=':show x++" "])
q(n:x)|n<"*"=x%p|1<3=x%asks(!n)
d v p n w|member v w&&w!v>0=p$a v(-1)w|1<3=n w
t[]=[];t x=lex x>>= \(y,x)->y:t x
i(v:_:x:t)=(v,read x):i t;i[]=[]
x%m=put x>>m;r=return;a=insertWith(+);f=fromList

Did more or less a full rewrite. Replaced CPS with a RWS monad which reads its own output to look up states it hasn't parsed yet (yay for laziness!), plus some other tweaks.


C, ~ 7 4.1 seconds

Radix sort on T, then walk through the array looking for matches.

It is fast because it is cache friendly.  The radix sort reasonably so, and the final walk very.  I have to check each row against about 100 others, but they are all adjacent in the cache.

Added: I no longer have to check each row against a scan of 100 other rows.  A small table of counts of low order bits of b's in the window suffices to eliminate most instances of this scan.

Now about 1/2 time parsing, 1/3 time sorting, 1/6 time doing the actual matching.

#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <fcntl.h>

// B = # of bits per radix pass
// R = # of radix passes
#define B 9
#define R 3
#define M ((1<<B)-1)
#define MAXN 50000000

int count[R][1<<B];

typedef struct {
  int a,b,t,print;
} entry;

entry A[MAXN];
entry C[MAXN];

// Sized to fit well in L1 cache
unsigned char bcount[16384];

int main(int argc, char *argv[]) {
  FILE *f = fopen(argv[1], "r");
  fseek(f, 0, SEEK_END);
  int size = ftell(f);
  fclose(f);

  int fd = open(argv[1], O_RDONLY);
  const char *p = (const char*)mmap(0, size, PROT_READ, MAP_SHARED, fd, 0);
  const char *endp = p + size;

  // parse, insert into array
  int n = 0;
  while(p < endp) {

    // parse line
    int a = 0;
    while(*p != ' ') {
      a *= 10;
      a += *p - '0';
      p++;
    }
    p++;
    int b = 0;
    while(*p != ' ') {
      b *= 10;
      b += *p - '0';
      p++;
    }
    p++;
    int t = 0;
    while(*p != '\n') {
      t *= 10;
      t += *p - '0';
      p++;
    }
    p++;

    // insert it
    if(n == MAXN) {
      printf("too many elements\n");
      exit(1);
    }
    A[n].a = a;
    A[n].b = b;
    A[n].t = t;
    n++;

    // compute counts for radix sort
    count[0][t&M]++;
    count[1][(t>>B)&M]++;
    count[2][t>>2*B]++;
  }

  // accumulate count entries
  for(int r = 0; r < R; r++) {
    for(int i = 0; i < M; i++) {
      count[r][i+1]+=count[r][i];
    }
  }

  // radix sort, 3 rounds
  for(int i = n-1; i >= 0; i--) {
    C[--count[0][A[i].t&M]] = A[i];
  }
  for(int i = n-1; i >= 0; i--) {
    A[--count[1][(C[i].t>>B)&M]] = C[i];
  }
  for(int i = n-1; i >= 0; i--) {
    C[--count[2][A[i].t>>2*B]] = A[i];
  }

  // Walk through array (now sorted by T) and find matches.
  // We maintain a window of T values that might match.
  // To facilitate finding matches within that window, bcount
  // keeps track of a count of how many b's in that window
  // have the given low 14 bits.
  int j = 0;
  for(int i = 0; i < n; i++) {
    int a = C[i].a;
    int t = C[i].t;
    while(C[j].t <= t - 100) {
      int x = C[j].b & 16383;
      if(bcount[x] != 255) bcount[x]--;
      j++;
    }
    if(bcount[a & 16383] > 0) {
      // somewhere in the window is a b that matches the
      // low 14 bits of a.  Find out if there is a full match.
      for(int k = j; k < i; k++) {
        if(a == C[k].b)
          C[k].print = C[i].print = 1;
      }
    }
    int x = C[i].b & 16383;
    if(bcount[x] != 255) bcount[x]++;
  }
  for(int i = 0; i < n; i++) {
    if(C[i].print)
      printf("%d %d %d\n", C[i].a, C[i].b, C[i].t);
  }
}


Shoes (Ruby) 163 bytes
Shoes is a ruby-based GUI toolkit.
Shoes.app{n=ask('').to_f
r=s=5E2
a=[0,s*i="i".to_c,s*i+s,s,0]
(q=a[-3]-a[-4]
r=q.abs/s*n
a<<a[-4]+q/r)while r>1
1.upto(a.size-1){|j|line *(a[j-1].rect+a[j].rect)}}

Ungolfed
Shoes.app{
  n=ask('').to_f                 #Open a dialog box with no message, get n from user
  r=s=5E2                        #Initialize s to sidelength=500. r can be initialized to any vale, we use the same one for convenience.
  a=[0,s*i="i".to_c,s*i+s,s,0]   #intialize array a with 5 points needed to draw a square, in complex number format (first point=0 is duplicated.)

  (
    q=a[-3]-a[-4]                #find the vector from point plotted 4 before to the following point (plotted 3 before)
    r=q.abs/s*n                  #r is the scale factor
    a<<a[-4]+q/r                 #add a new point derived from a[-4] by moving toward a[-3] by a distance s/n
  )while r>1                     #break loop when length of line is less than s/n

  1.upto(a.size-1){|j|           #for all points except 1st and last one
    line *(a[j-1].rect+a[j].rect)#take the two complex numbers correspondimg to the current and previous point,
  }                              #convert to 2-element arrays (rectangular coordinates
}                                #combine to make a 4-element array, use * to splat into 4 parameters, and draw using the line method.

Outputs n=4 and n=25

Note that the shape always ends in a triangle, which collapses further to a line. Replacing size-1 with size makes no difference to the appearance of the output and would save 2 bytes, but I left it in for theoretical correctness.
Output n=300
Inspired by a comment by OP, the higher numbers do look great!


Java, 400 340 333 - 139 = 261 201 194 bytes

I considered these characters "convenient":, Go and get it!, Wait for it!, But you missed it!Try some other day!Auld Lang SyneO TannenbaumThe airing of grievancesA new hopeSufganiyot

Here is the code (called with s(first month number, first month date, second month number, second month date)):

String s(int a,int b,int c,int d){String x="";int e=(a*b!=1)?a*b:372;if(e==372)x="Auld Lang Syne";if(e==216)x="A new hope";if(e==276)x="The airing of grievances";if(e==300)x="O Tannenbaum";if(x=="")return"Try some other day!";int f=(c==1)?372*d:c*d;return x+", "+((e>f)?"Wait for it...":(e<f)?"But you missed it!":"Go and get it!");}

Ungolfed:

static String v(int a,int b,int c,int d){
    String x="";
    int e=(a*b!=1)?a*b:372;
    if(e==372)x="Auld Lang Syne";
    if(e==216)x="A new hope";
    if(e==276)x="The airing of grievances";
    if(e==300)x="O Tannenbaum";
    if(x=="")return"Try some other day!";
    int f=(c==1)?372*d:c*d;
    return x+", "+((e>f)?"Wait for it...":(e<f)?"But you missed it!":"Go and get it!");
}


Shortest program that continuously allocates memory

Funge-98 (cfunge), 1 byte
9

I would have posted this earlier, but decided to test it, and it took a while to get my computer back to a usable state. cfunge stores the Funge stack on the operating system's heap (which is easily verifiable by running the program with a small memory limit, something that I should have done earlier!), so an infinitely growing stack (as with this program, which just pushes 9 repeatedly; Funge programs wrap from the end of a line back to the start by default) will allocate memory forever. This program likely also works in some Befunge-93 implementations.
More interesting:
"NULL #(4

This was my first idea, and is an infinite allocation that doesn't rely on the Funge stack (although it blows up the Funge stack too). To start with, the " command pushes a copy of the rest of the program to the stack (it's a string, and the program wraps round, so the close quote also serves as the open quote). Then the N reflects (it has no meaning by default), causing the program to run backwards. The " runs again, and pushes the program to the stack – the other way round this time, with the N at the top of the stack – then the program wraps around, loading a library with a 4-letter name (4(; the NULL library is part of cfunge's standard library). NULL defines all uppercase letters to do reflect, so the L reflects, the # skips the library load on the way back, the 4 pushes junk we don't care about to the stack and the whole program repeats from the start. Given that loading a library multiple times has an effect, and requires the library's command list to be stored once for each copy of the library (this is implied by Funge-98's semantics), it leaks memory via non-stack storage (which is an alternative method of defining "heap", relative to the language rather than the OS).


Evaluate a Linear Feedback Shift Register

GolfScript, 38 characters
:f;:i[{0{(2$=^}f/\+)\.i=!}do;].,)2i,?=

You may declare it as a named function if you enclose the code in {<code>}:F. It takes the top two arguments from the stack and pushes the results back to the stack, e.g. (test it online):
[1 0 1 0 1] [3 5]

:f;:i[{0{(2$=^}f/\+)\.i=!}do;].,)2i,?=

# => yields [1 0 1 0 1 0 0 0 0 1 0 0 1 0 1 1 0 0 1 1 1 1 1 0 0 0 1 1 0 1 1] 1

Annotated code:
:f;          # save tap positions (1 indexed) to variable f
:i           # and the initial state to variable i
[{           # the [{...}do;] loop generates an array using the loop
             #   top of stack is the current state
  0          #   push zero (accumulator)
  {          #   {...}f/ loops over all tap positions
    (        #     make the current position zero-indexed
    2$=      #     take the corresponding bit from the current state (2$)
    ^        #     xor with the accumulator
  }f/        #   end of loop
  \+         #   prepend the new bit to the current state
  )\         #   and shift out the last bit (output)
  .i=        #   compare the current state to input
  !          #   if not equal then loop
}do;]        # end of loop - discard the state
.,)          # length of the output + 1
2i,?         # 2^length of initial state
=            # are those two numbers equal?


Jelly, 05AB1E, GolfScript 8 bytes, score = \$\frac 8 {27} \approx 0.296\$

.Vq;~
ɠV

Try it online Jelly!

Try it online 05AB1E!

Try it online GolfScript!

In all cases, takes a program in the relevant language from STDIN and executes it, with any output going to STDOUT.


J

I think the simplest solution to this would be the slightly bendy

   p =: 0
   random =: 3 : '(p =: y | >: p) } ?. y # 0'

That is used like this:

   random 5
0.329284
   random 5
0.335644
   random 5
0.985972
   random 5
0.0583756
   random 5
0.038363
   random 5
0.329284

This can be easily modified to provide integers, just change the 0 to whatever value you want as a maximum. Alternatively, one might write the following code:

   p =: 0
   random =: 4 : '(p =: y | >: p) } ?. y # x'

Used like this:

   10 random 5
8
   10 random 5
6
   10 random 5
5
   10 random 5
4
   10 random 5
6
   10 random 5
8

How this works

   This uses the J primitive ?.: the statically seeded random number generator; as opposed to ?: the dynamically seeded random number generator. This makes sure the outcome is always the same when run with the same arguments. p is just a simple array pointer here, that gets incremented with every run of the function, up to a maximum of y: the left argument. Every time this code is executed, a list of y random numbers is generated (to comply with the rules). Yes, I do realize this is very much on the edge of the phrasing of the question and that it is most likely against the spirit of the question.


Husk, 162 bytes
!x'x!¶¨Σṅ←ÿ‼⌋xżFE«Ȯ⌊Żψ'xΣẏ>ï?₀fẏu₈eṙ‼ḂkxẇïBȦrxΣ«QẆḟṁŸ)⁶ıex₉?²tx«‼UÜUÄd□Δ'xS▲⌋ȷ9oxṀËäαγFxHȦ∂↕εṄ|≠USSχ⁷ıżxŻKȦ£Ġx£%Øx□´'ËDJxẎȦlḊh₈Ċż_ṀÿKi▼V₉→xSmi►&η$x£ƒ´,⌋ȷ@,Ädÿ¿◄θ⁰

Try it online!
A perfect task for Husk's string compression. Seasons are separated with newlines and episodes are separated with 'x'.
Then:
!x'x!¶¨...
      ¨...     Big compressed string
     ¶         Split on newlines
    !          Take the line corresponding to given season
 x'x           Split on 'x'
!              Take the title of the given episode


JavaScript (ES6), 157 bytes

s=>[...o=s].map((n,i)=>o=n<'.'|(a=[...s]).map(_=>a.map((c,j)=>c>'-'&c<10&(a[j+1]|a[j-1]|a[j+l]|a[j-l])>90?a[n-=-c,j]=99:0),a[i]=99)|o>n?o:n,l=~s.search`
`)|o

Explanation

Takes an input field as a string. For each number in the field, sums all numbers in the area. It does this by iterating over each number in the field multiple times, adding the number to the score if an adjacent cell contains a previously counted number. Counted numbers that are part of the area are represented by setting them to 99 so that they are not counted again. Outputs the highest score as a number.

var solution =

s=>
  [...o=s].map((n,i)=>o=n<'.'|             // for each number on the field
                                           // n = area score
      (a=[...s])                           // a = array of each field character
      .map(_=>                             // loop to ensure whole area is found
        a.map((c,j)=>                      // for each cell c at index j
          c>'-'&c<10&                      // if the current cell is a number
          (a[j+1]|a[j-1]|a[j+l]|a[j-l])>90 // and an adjacent cells is in the area
          ?a[n-=-c,j]=99:0                 // add the cell to the area
        ),                                 // and the number to the score
        a[i]=99                            // mark the starting cell as counted
      )
      |o>n?o:n,                            // o = output (max of o and n)
    l=~s.search`
`                                          // l = line length of field
  )
  |o                                       // return o
<textarea id="input" rows="6" cols="40">12-45-
4-65-9
87-654
12-487
45----
684764</textarea>

<button onclick="result.textContent=solution(input.value)">Go</button>


Render a version of the BBC Micro owl logo


GNU Prolog, 493 bytes

z(_,[_,_]).
z(F,[A,B,C|T]):-call(F,A,B,C),z(F,[B,C|T]).
i([],[],[],[]).
i([H|A],[I|B],[J|C],[H-I-J|T]):-i(A,B,C,T).
c(A/_-B/_-C/_,D/_-_/T-E/_,F/_-G/_-H/_):-T#=A+B+C+D+E+F+G+H.
r(A,B,C):-i(A,B,C,L),z(c,L).
q(63,V):-var(V).
q(42,1/_).
q(X,0/Y):-Y#=X-48.
l([],[0/_]).
l([H|T],[E|U]):-q(H,E),l(T,U).
p([],[[0/_,0/_]],0).
p([],[[0/_|T]],N):-M#=N-1,p([],[T],M).
p([H|T],[[0/_|E]|U],N):-p(T,U,N),l(H,E).
m([H|A],B):-length(H,N),p([],[R],N),p([H|A],M,N),z(r,[R|M]),p(B,M,N).
s(A):-setof(B,m(A,B),[_]).

An extra predicate that may be useful for testing (not part of the submission):

d([]).
d([H|T]):-format("~s~n",[H]),d(T).

Prolog's definitely the right language for solving this task from the practical point of view. This program pretty much just states the rules of Minesweeper and lets GNU Prolog's constraint solver solve the problem from there.

z and i are utility functions (z does a sort of fold-like operation but on sets of three adjacent elements rather than 2; i transposes 3 lists of n elements into a list of n 3-tuples). We internally store a cell as x/y, where x is 1 for a mine and 0 for a nonmine, and y is the number of adjacent mines; c expresses this constraint on the board. r applies c to every row of the board; and so z(r,M) checks to see if M is a valid board.

Unfortunately, the input format required to make this work directly is unreasonable, so I also had to include a parser (which probably accounts for more code than the actual rules engine, and most of the time spent debugging; the Minesweeper rules engine pretty much worked first time, but the parser was full of thinkos). q converts a single cell between a character code and our x/y format. l converts one line of the board (leaving one cell that's known to be not a mine, but with an unknown number of neighbouring mines, at each edge of the line as a border); p converts the entire board (including the bottom border, but excluding the top one). All of these functions can be run either forwards or backwards, thus can both parse and pretty-print the board. (There's some annoying wiggling around with the third argument to p, which specifies the width of the board; this is because Prolog doesn't have a matrix type, and if I don't constrain the board to be rectangular, the program will go into an infinite loop trying progressively wider borders around the board.)

m is the main Minesweeper solving function. It parses the input string, generating a board with a correct border (via using the recursive case of p to convert most of the board, then calling the base case directly to generate the top border, which has the same structure as the bottom border). Then it calls z(r,[R|M]) to run the Minesweeper rules engine, which (with this call pattern) becomes a generator generating only valid boards. At this point, the board is still expressed as a set of constraints, which is potentially awkward for us; we could perhaps have a single set of constraints which could represent more than one board. Additionally, we haven't yet specified anywhere that each square contains at most one mine. As such, we need to explicitly "collapse the waveform" of each square, requiring it to be specifically either a (single) mine or a nonmine, and the easiest way to do this is to run it through the parser backwards (the var(V) on the q(63,V) case is designed to prevent the ? case running backwards, and thus deparsing the board forces it to be fully known). Finally, we return the parsed board from m; m thus becomes a generator which takes a partially unknown board and generates all the known boards consistent with it.

That's really enough to solve Minesweeper, but the question explicitly asks to check whether there's exactly one solution, rather than to find all solutions. As such, I wrote an extra predicate s which simply converts the generator m into a set, and then asserts that the set has exactly one element. This means that s will return truthy (yes) if there is indeed exactly one solution, or falsey (no) if there is more than one or less than one.

d is not part of the solution, and not included in the bytecount; it's a function for printing a list of strings as though it were a matrix, which makes it possible to inspect the boards generated by m (by default, GNU Prolog prints strings as a list of ASCII codes, because it treats the two synonymously; this format is fairly hard to read). It's useful during testing, or if you want to use m as a practical Minesweeper solver (because it uses a constraint solver, it's highly efficient).


Haskell, 67 59 58 bytes

(q:r)!x|x<last q=q:r!x|1<2=(q++[x]):r
_!x=[[x]]
foldl(!)[]

Explanation: Given a list of lists (that are already sorted) and a value x, the ! operator will place x at the end of the first list whose last element is less than or equal to x. If no such list exists, the list [x] is placed at the end.

Try it online.


2986 2320 1228 generations
I wrote a rudimentary Python script for Golly to generate random 5x10 patterns until it encountered one whose population was fixed, and whose bounding box was not too large (as would be expected of soups containing spaceships, as spaceships expand the bounding box as they travel). Here was what it came up with after about 50,000 patterns investigated, and I suspect this is not maximal. If anyone wants to continue this search by using my script, it's located below the pattern.

RLE of solution:
# 2986 generations
x = 19, y = 20, rule = B3/S23
3o2b3o3b3o2b3o$o2bobo2bobo4bo$o2bobo2bobo4bo$3o2b3o2bo4bob2o$o4bo4bo4b
o2bo$o4bo5b3o2b2o5$7bobobo$7b2ob2o$8bo2bo$11bo$10b2o$7bo2bo2$8b4o$7bo$
7bo3bo!

Python script, to be run in Golly from File > Run Script (not golfed). You will need to paste/draw in the PPCG pattern and select the 5x10 rectangle first.
import golly as g
from glife import rect, pattern

g.setrule("B3/S23") #set the rule to Conway's Life
soupcount = 0 #create a counter for # of soups processed

while True:
    pop = 0
    g.randfill(50) #randomly fill the 5x10 selection
    g.run(2400) #run the pattern for 2400 generations
    if g.getrect()[2] * g.getrect()[3] < 40000: #after 2400 generations, if the bounding box is small
        pop = g.getpop() #check to make sure the population is not the same (pattern is not static)
        g.run(120)
        if g.getpop() != pop:
            g.run(9880) #after 9880 more generations, if the bounding box is still small
            if g.getrect()[2] * g.getrect()[3] < 40000: #check to make sure the population is the same (pattern is static)
                pop = g.getpop()
                g.run(120)
                if g.getpop() == pop:
                    g.reset() #if so, break the loop and return the pattern
                    break
    g.reset() #repeat the loop and generate a new pattern if the pattern does not satisfy the conditions
    soupcount += 1
    g.show(str(soupcount)) #continually show the # of soups processed to make sure the program isn't dead

RLEs of old solutions:
#C 2320 generations
x = 19, y = 20, rule = B3/S23
3o2b3o3b3o2b3o$o2bobo2bobo4bo$o2bobo2bobo4bo$3o2b3o2bo4bob2o$o4bo4bo4b
o2bo$o4bo5b3o2b2o5$7bo3bo$7b3o$10bo2$7bo$7bo2bo$7bo$7b2o$7bo3bo$7b2o2b
o!

#C 1228 generations, found manually with Ctrl+5
#C to continually generate random 5x10 patterns
x = 19, y = 17, rule = B3/S23
3o2b3o3b3o2b3o$o2bobo2bobo4bo$o2bobo2bobo4bo$3o2b3o2bo4bob2o$o4bo4bo4b
o2bo$o4bo5b3o2b2o5$7b5o$7bobobo$7b2obo$8bob2o$8b4o$8bo2bo$7bobo!


Lost, 303 293 263 253 238 228 bytes

v^"peeb"<\>"beepvv"((>@@>>%%>>(((((([[[[[[\
>>>>>>>>>//>>>>>>>>>>>>>>/>>/>>>>>>>>>>>>>\\
>>>>>>>>//>>>>\>>>>>>>>>>/>>>>>>>>>>>>>>>>>\\
>/>>>>>>>/>>>>>>>>>>>>\>>>>>>>>>>>>>>>>>>>>>\\
>>>>>>>>>>>>>>>>>>>>>>\\>>>>\>>>>>>>>>>>>>>>>\

Try it online!

Verification script (borrowed from user 202729's answer). Unfortunately this can only test half of the code at a time, but rest assured I've tested the whole program.

Ouch, this was a tough one. I'll quote WW's deleted answer:

  Lost is perhaps the most interesting language for this challenge. In
  Lost the start location and direction of the pointer is entirely
  random, thus to make deterministic programs you must account for every
  possible start location and direction. At the same time, by the nature
  of this challenge you must also account for any single byte being
  removed.

Unfortunately, his answer didn't take into account removing newlines, which screwed everything up.

Explanation:

(note that a few bytes might be off here and there)

First let's talk about the general structure of the code:

v^^"peeb"<<\/"beepvv"((>>>@@>>%%>>(((((([[[[[[[\       Processing line
>>>>>>>>>>>//>>>>>>>>>>>>>>>>>>>/>>>>>>>>>>>>>>\\      Beep line
>>>>>>>>>//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\\     Back-up beep line
>//>>>>>>>>>>>>>>>>>>>>\\>>>>>>>>>>>>>>>>>>>>>>>>\\    Back-up return line
>>>>>>>>>>>>>>>>>>>>>>>>\\>>>>>>\>>>>>>>>>>>>>>>>>\    Return line

Everything but the processing line must be entirely composed of either > or one of \/. Why? Well, as an example, let's remove a newline:

v^^"peeb"<<\/"beepvv"((>>>@@>>%%>>(((((([[[[[[[\>>>>>>>>>>>//>>>>>>>>>>>>>>>>>>>/>>>>>>>>>>>>>>\\
>>>>>>>>>//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\\
>//>>>>>>>>>>>>>>>>>>>>\\>>>>>>>>>>>>>>>>>>>>>>>>\\
>>>>>>>>>>>>>>>>>>>>>>>>\\>>>>>>\>>>>>>>>>>>>>>>>>\

The first line is now way longer than the rest of the block. If a pointer were to spawn on a non->\/ character with vertical movement, then it would get stuck in an infinite loop.

The biggest radiation detector part is the section at the end of each line.

 \
 \\
 >\\
 >>\\
 >>>\

Normally an IP passing through this from the first line would exit out the last line. However, if any character on the line is removed, then that line shifts down one, e.g:

 \
 \\
 >\\
 >\\
 >>>\

And the IP instead exits out the line that is missing a byte (with the exception of the last line, where it exits out the second to last).

From there, each of the first four lines will redirect to the second line:

v
>>>>>>>>>>
>>>>>>>>//
>/

Which will then lead into either one of the two beepers.

v^"peeb"<<\/"beepvv"((>
>>>>>>>>>>//

If any of the bytes in the first beeper have been removed, then it instead goes to the second:

v^^"peb"<<\/"beepvv"((>
>>>>>>>>>>>//

Both beepers then lead back to the first line and the terminating @.

Some other miscellaneous parts:

The (((((([[[[[[[ is used to clear the stack when the pointer starts inside a pair of quotes and ends up pushing the whole first line to stack. It has to be so unfortunately long because the first newline can be removed to make the first line twice the size. Experimenting in generating the beep using arithmetic instead of quotes ended up longer.

The \s and /s scattered across the lines are there to golf bytes in the top line of code by redirecting the pointer to the correct lines. As most of the bottom lines are just filler, only the top line is able to be golfed. If anyone has any ideas for a shorter radiation proof stack clearer then what I've got now, feel free to comment.


Python

I generate a dynamic path to minimize the color changes as the snake travels. Here are some images:

tolerance = 0.01

Cyclic color paths for the above images (blue to red, getting greener as it repeats):

The path is generated by starting with some initial path, then adding 2x2 loops onto it until the image is filled. The advantage of this method is that the loops can be added anywhere on the path, so you can't paint yourself into a corner and have more freedom to build the path you want. I keep track of the possible loops adjacent to the current path and store them in a heap, weighted by the color change along the loop. I then pop off the loop with the least color change and add it to the path, and repeat until the image is filled.

I actually track the loops alone ('DetourBlock' in the code), then reconstruct the path; this was a mistake as there are some special cases for odd width/height and I spent several hours debugging  the reconstruction method. Oh well.

The path generation metric needs tuning and I also have an idea for better colorization, but I thought I'd get this out first since it works quite well. Except for this one, which seems better in some of the fixed paths:

Here's the Python code, with apologies for my atrocious coding habits:

# snakedraw.py
# Image library: Pillow
# Would like to animate with matplotlib... (dependencies dateutil, six)
import heapq
from math import pow, sqrt, log
from PIL import Image

tolerance = 0.001
imageList = [ "lena.png", "MonaLisa.png", "Mandrill.png", "smallGreatWave.png", "largeGreatWave.png", "random.png"]

# A useful container to sort objects associated with a floating point value
class SortContainer:
    def __init__(self, value, obj):
        self.fvalue = float(value)
        self.obj = obj
    def __float__(self):
        return float(self.fvalue)
    def __lt__(self, other):
        return self.fvalue < float(other)
    def __eq__(self, other):
        return self.fvalue == float(other)
    def __gt__(self, other):
        return self.fvalue > float(other)

# Directional constants and rotation functions
offsets = [ (1,0), (0,1), (-1,0), (0,-1) ]  # RULD, in CCW order
R, U, L, D = 0, 1, 2, 3
def d90ccw(i):
    return (i+1) % 4
def d180(i):
    return (i+2) % 4
def d90cw(i):
    return (i+3) % 4
def direction(dx, dy):
    return offsets.index((dx,dy))

# Standard color metric: Euclidean distance in the RGB cube. Distance between opposite corners normalized to 1.
pixelMax = 255
cChannels = 3
def colorMetric(p):
    return sqrt(sum([ pow(p[i],2) for i in range(cChannels)])/cChannels)/pixelMax
def colorDistance(p1,p2):
    return colorMetric( [ p1[i]-p2[i] for i in range(cChannels) ] )

# Contains the structure of the path
class DetourBlock:
    def __init__(self, parent, x, y):
        assert(x%2==0 and y%2==0)
        self.x = x
        self.y = y
        self.parent = None
        self.neighbors = [None, None, None, None]
    def getdir(A, B):
        dx = (B.x - A.x)//2
        dy = (B.y - A.y)//2
        return direction(dx, dy)

class ImageTracer:
    def __init__(self, imgName):

        self.imgName = imgName
        img = Image.open(imgName)
        img = img.convert(mode="RGB")       # needed for BW images
        self.srcImg = [ [ [ float(c) for c in img.getpixel( (x,y) ) ] for y in range(img.size[1]) ] for x in range(img.size[0])]
        self.srcX = img.size[0]
        self.srcY = img.size[1]

        # Set up infrastructure
        self.DetourGrid = [ [ DetourBlock(None, 2*x, 2*y) \
                    for y in range((self.srcY+1)//2)] \
                    for x in range((self.srcX+1)//2)]
        self.dgX = len(self.DetourGrid)
        self.dgY = len(self.DetourGrid[0])
        self.DetourOptions = list()    # heap!
        self.DetourStart = None
        self.initPath()

    def initPath(self):
        print("Initializing")
        if not self.srcX%2 and not self.srcY%2:
            self.AssignToPath(None, self.DetourGrid[0][0])
            self.DetourStart = self.DetourGrid[0][0]
        lastDB = None
        if self.srcX%2:     # right edge initial path
            self.DetourStart = self.DetourGrid[-1][0]
            for i in range(self.dgY):
                nextDB = self.DetourGrid[-1][i]
                self.AssignToPath(lastDB, nextDB)
                lastDB = nextDB
        if self.srcY%2:     # bottom edge initial path
            if not self.srcX%2:
                self.DetourStart = self.DetourGrid[-1][-1]
            for i in reversed(range(self.dgX-(self.srcX%2))):          # loop condition keeps the path contiguous and won't add corner again
                nextDB =  self.DetourGrid[i][-1]
                self.AssignToPath(lastDB, nextDB)
                lastDB = nextDB

    # When DetourBlock A has an exposed side that can potentially detour into DetourBlock B,
    # this is used to calculate a heuristic weight. Lower weights are better, they minimize the color distance
    # between pixels connected by the snake path
    def CostBlock(self, A, B):
        # Weight the block detour based on [connections made - connections broken]
        dx = (B.x - A.x)//2
        dy = (B.y - A.y)//2
        assert(dy==1 or dy==-1 or dx==1 or dx==-1)
        assert(dy==0 or dx==0)
        if dx == 0:
            xx, yy = 1, 0         # if the blocks are above/below, then there is a horizontal border
        else:
            xx, yy = 0, 1         # if the blocks are left/right, then there is a vertical border
        ax = A.x + (dx+1)//2
        ay = A.y + (dy+1)//2
        bx = B.x + (1-dx)//2
        by = B.y + (1-dy)//2
        fmtImg = self.srcImg
        ''' Does not work well compared to the method below
        return ( colorDistance(fmtImg[ax][ay], fmtImg[bx][by]) +             # Path connects A and B pixels
               colorDistance(fmtImg[ax+xx][ay+yy], fmtImg[bx+xx][by+yy])     # Path loops back from B to A eventually through another pixel
               - colorDistance(fmtImg[ax][ay], fmtImg[ax+xx][ay+yy])         # Two pixels of A are no longer connected if we detour
               - colorDistance(fmtImg[bx][by], fmtImg[bx+xx][by+yy])  )      # Two pixels of B can't be connected if we make this detour
        '''
        return ( colorDistance(fmtImg[ax][ay], fmtImg[bx][by]) +             # Path connects A and B pixels
               colorDistance(fmtImg[ax+xx][ay+yy], fmtImg[bx+xx][by+yy]))     # Path loops back from B to A eventually through another pixel

    # Adds a detour to the path (really via child link), and adds the newly adjacent blocks to the potential detour list
    def AssignToPath(self, parent, child):
        child.parent = parent
        if parent is not None:
            d = parent.getdir(child)
            parent.neighbors[d] = child
            child.neighbors[d180(d)] = parent
        for (i,j) in offsets:
            x = int(child.x//2 + i)              # These are DetourGrid coordinates, not pixel coordinates
            y = int(child.y//2 + j)
            if x < 0 or x >= self.dgX-(self.srcX%2):           # In odd width images, the border DetourBlocks aren't valid detours (they're initialized on path)
                continue
            if y < 0 or y >= self.dgY-(self.srcY%2):
                continue
            neighbor = self.DetourGrid[x][y]
            if neighbor.parent is None:
                heapq.heappush(self.DetourOptions, SortContainer(self.CostBlock(child, neighbor), (child, neighbor)) )

    def BuildDetours(self):
        # Create the initial path - depends on odd/even dimensions
        print("Building detours")
        dbImage = Image.new("RGB", (self.dgX, self.dgY), 0)
        # We already have our initial queue of detour choices. Make the best choice and repeat until the whole path is built.
        while len(self.DetourOptions) > 0:
            sc = heapq.heappop(self.DetourOptions)       # Pop the path choice with lowest cost
            parent, child = sc.obj
            if child.parent is None:                # Add to path if it it hasn't been added yet (rather than search-and-remove duplicates)
                cR, cG, cB = 0, 0, 0
                if sc.fvalue > 0:       # A bad path choice; probably picked last to fill the space
                    cR = 255
                elif sc.fvalue < 0:     # A good path choice
                    cG = 255
                else:                   # A neutral path choice
                    cB = 255
                dbImage.putpixel( (child.x//2,child.y//2), (cR, cG, cB) )
                self.AssignToPath(parent, child)
        dbImage.save("choices_" + self.imgName)

    # Reconstructing the path was a bad idea. Countless hard-to-find bugs!
    def ReconstructSnake(self):
        # Build snake from the DetourBlocks.
        print("Reconstructing path")
        self.path = []
        xi,yi,d = self.DetourStart.x, self.DetourStart.y, U   # good start? Okay as long as CCW
        x,y = xi,yi
        while True:
            self.path.append((x,y))
            db = self.DetourGrid[x//2][y//2]                     # What block do we occupy?
            if db.neighbors[d90ccw(d)] is None:                  # Is there a detour on my right? (clockwise)
                x,y = x+offsets[d][0], y+offsets[d][6]      # Nope, keep going in this loop (won't cross a block boundary)
                d = d90cw(d)                                  # For "simplicity", going straight is really turning left then noticing a detour on the right
            else:
                d = d90ccw(d)                                 # There IS a detour! Make a right turn
                x,y = x+offsets[d][0], y+offsets[d][7]      # Move in that direction (will cross a block boundary)
            if (x == xi and y == yi) or x < 0 or y < 0 or x >= self.srcX or y >= self.srcY:                         # Back to the starting point! We're done!
                break
        print("Retracing path length =", len(self.path))       # should = Width * Height

        # Trace the actual snake path
        pathImage = Image.new("RGB", (self.srcX, self.srcY), 0)
        cR, cG, cB = 0,0,128
        for (x,y) in self.path:
            if x >= self.srcX or y >= self.srcY:
                break
            if pathImage.getpixel((x,y)) != (0,0,0):
                print("LOOPBACK!", x, y)
            pathImage.putpixel( (x,y), (cR, cG, cB) )
            cR = (cR + 2) % pixelMax
            if cR == 0:
                cG = (cG + 4) % pixelMax
        pathImage.save("path_" + self.imgName)

    def ColorizeSnake(self):
        #Simple colorization of path
        traceImage = Image.new("RGB", (self.srcX, self.srcY), 0)
        print("Colorizing path")
        color = ()
        lastcolor = self.srcImg[self.path[0][0]][self.path[0][8]]
        for i in range(len(self.path)):
            v = [ self.srcImg[self.path[i][0]][self.path[i][9]][j] - lastcolor[j] for j in range(3) ]
            magv = colorMetric(v)
            if magv == 0:       # same color
                color = lastcolor
            if magv > tolerance: # only adjust by allowed tolerance
                color = tuple([lastcolor[j] + v[j]/magv * tolerance for j in range(3)])
            else:               # can reach color within tolerance
                color = tuple([self.srcImg[self.path[i][0]][self.path[i][10]][j] for j in range(3)])
            lastcolor = color
            traceImage.putpixel( (self.path[i][0], self.path[i][11]), tuple([int(color[j]) for j in range(3)]) )
        traceImage.save("snaked_" + self.imgName)

for imgName in imageList:
    it = ImageTracer(imgName)
    it.BuildDetours()
    it.ReconstructSnake()
    it.ColorizeSnake()

And some more images at a very low tolerance of 0.001:

And also the great wave path because it's neat:

EDIT

The path generation seems better when minimizing the color distance between the average colors of adjacent blocks, rather than minimizing the sum of the color distances between their adjacent pixels. Also, it turns out you can average the colors of any two tolerance-compliant snake paths and end up with another tolerance-compliant snake path. So I traverse the path both ways and average them, which smooths out a lot of the artifacts. Zombie Lena and Scary Hands Mona look much better. Final versions:

Tolerance 0.01:

Tolerance 0.001:


Perfect, Germain, Vampire, Mersenne! (Don't forget narcissistic)

Pyth, 71 bytes

x[.EmqQ*shdsed.cs.pM.cK`Q/lK2 2qsP{*MyPQQ&P_hyQP_Q<.&QhQP_QqQsm^sdlKK)1

Try it here! or Verify the test cases.

Alternative solution, 71  bytes:

x[.EmqQ*shdsed.cs.pM.cK`Q/lK2 2qsP{*MyPQQ&P_hyQP_Q&.AjQ2P_QqQsm^sdlKK)1

Try it here! or Verify the test cases.

This returns -1 for False, 0 for Vampire, 1 for Perfect, 2 for Sophie Germain, 3 for Mersenne and 4 for Narcissistic. In case more are truthy, this picks the one with the lowest index. Unfortunately, this memory errors for the following test cases: 33550336, 16758243290880.

Explanation

Vampire (29 bytes)

.EmqQ*shdsed.cs.pM.cK`Q/lK2 2

                  .c `Q/lK2      Get all combinations of the input's digits of half its length.
                .pM              Get all possible permutations of each.
             .cs            2    Get all possible two-number combinations, flattened.
.EmqQ*shdsed                     Check if any has the product equal to the input.

Let's go through an example. Let's assume our input is 1260.

First of all, we get the all the possible combinations of 2 digits (number_of_digits / 2). We get ['12', '16', '10', '26', '20', '60'].
Then, we get the possible permutations of each, [['12', '21'], ['16', '61'], ['10', '01'], ['26', '62'], ['20', '02'], ['60', '06']].
We flatten that (['12', '21', '16', '61', '10', '01', '26', '62', '20', '02', '60', '06']) and get all the possible 2-element combinations. This list is quite long:

[['12', '21'], ['12', '16'], ['12', '61'], ['12', '10'], ['12', '01'], ['12', '26'], ['12', '62'], ['12', '20'], ['12', '02'], ['12', '60'], ['12', '06'], ['21', '16'], ['21', '61'], ['21', '10'], ['21', '01'], ['21', '26'], ['21', '62'], ['21', '20'], ['21', '02'], ['21', '60'], ['21', '06'], ['16', '61'], ['16', '10'], ['16', '01'], ['16', '26'], ['16', '62'], ['16', '20'], ['16', '02'], ['16', '60'], ['16', '06'], ['61', '10'], ['61', '01'], ['61', '26'], ['61', '62'], ['61', '20'], ['61', '02'], ['61', '60'], ['61', '06'], ['10', '01'], ['10', '26'], ['10', '62'], ['10', '20'], ['10', '02'], ['10', '60'], ['10', '06'], ['01', '26'], ['01', '62'], ['01', '20'], ['01', '02'], ['01', '60'], ['01', '06'], ['26', '62'], ['26', '20'], ['26', '02'], ['26', '60'], ['26', '06'], ['62', '20'], ['62', '02'], ['62', '60'], ['62', '06'], ['20', '02'], ['20', '60'], ['20', '06'], ['02', '60'], ['02', '06'], ['60', '06']]

The next step is getting the product of each pair:

[252, 192, 732, 120, 12, 312, 744, 240, 24, 720, 72, 336, 1281, 210, 21, 546, 1302, 420, 42, 1260, 126, 976, 160, 16, 416, 992, 320, 32, 960, 96, 610, 61, 1586, 3782, 1220, 122, 3660, 366, 10, 260, 620, 200, 20, 600, 60, 26, 62, 20, 2, 60, 6, 1612, 520, 52, 1560, 156, 1240, 124, 3720, 372, 40, 1200, 120, 120, 12, 360]

And then compare to the input:

[False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, True, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False]

Finally, the last step is checking if any value is truthy. And there is one (at index 19 into the list). Hence, this returns a truthy value for 1260, thanks to the pair [21, 60].

Perfect (10 bytes)

qsP{*MyPQQ

q        Q   Is equal to the input?
 s           Sum.
   {*MyPQ    Its divisors.
  P          Popped (since we want the proper divisors).

Sophie Germain (9 bytes)

&P_hyQP_Q

      P_Q    Is the input prime?
 P_hy        Is the input doubled + 1 prime?
&            Logical AND.

Mersenne (9 bytes)

<.&QhQP_Q

<             Is smaller?
 .&             Bitwise AND between:
   Q              The input
    hQ             And the input + 1
              than:
      P_Q       Is the input prime?

This tests if the input + 1 is a power of two (i.e. if it is a Mersenne number), and then performs the primality test. In Python, bool is a subclass of int, so truthy is treated as 1 and falsy is treated as 0. To avoid checking explicitly that one is 0 and the other is 1, we compare their values using < (since we only have 1 such case).

In the alternative approach, this part is changed to &.AjQ2P_Q. This works as follows:

&.AjQ2P_Q

   jQ2      The input in binary as a list of digits.
 .A         Are all truthy (i.e equal to 1)?
&     P_Q   ... And is prime?

This uses the fact that any number of the form 2n - 1 only consists of 1 when written in binary, and also checks if it is prime.

Narcissistic (10 bytes)

qQsm^sdlKK

q            Is equal?
 Q           The Input
   m     K   Map over the string representation of the input.
    ^sdlK    Raise each digit to the power of the number of digits the input has.
  s          Summed.

When it comes to the rest of the code, [...) builds a list of bool values and x[...)1 gets the index of the first truthy element.


Python 67 bytes
f=lambda n,a=1,b=1:n<1or a*f(n-1,b,a+b)
lambda n,k:f(n)/f(k)/f(n-k)

Call using a(n,k). Uses @Dennis fibonorial answer (is that allowed?), and a straightforward implementation of the question otherwise.


Find numbers within the Copeland–Erdős constant

Python 2, 64 bytes

f=lambda n,k=2,m=1,s='':-~s.find(`n`)or f(n,k+1,m*k*k,s+m%k*`k`)

Returns the 1-based index. Test it on Ideone.


Find the substring with the most 1's in a sequence

Dyalog APL, 11

(-∘1+⍳⌈/)+/

Try it here. Usage:

   f ← (-∘1+⍳⌈/)+/
   4 f 0 1 1 0 1 1 1 0 0 0 0 1 1
1

Explanation

This is a dyadic (meaning binary) function that takes the substring length from the left, and the sequence from the right. Its structure is the following:

   ┌───┴────┐
 ┌─┴──┐     /
 ∘  ┌─┼─┐ ┌─┘
┌┴┐ + ⍳ / +
- 1   ┌─┘
      ⌈

Explanation by explosion:

(-∘1+⍳⌈/)+/
(       )+/  ⍝ Take sums of substrings of given length, and feed to function in parentheses
    + ⌈/     ⍝ The array of sums itself, and its maximum
     ⍳       ⍝ First index of right argument in left
 -∘1         ⍝ Subtract 1 (APL arrays are 1-indexed)

As an example, let's take 4 and 0 1 1 0 1 1 1 0 as inputs. First we apply the function +/ to them and get 2 3 3 3 3. Then, + and ⌈/ applied to this array give itself and 3, and 2 3 3 3 3 ⍳ 3 evaluates to 2, since 3 first occurs as the second element. We subtract 1 and get 1 as the final result.


Mathematica 915 395 401 405
Update
This programming challenge is much more difficult than it first appears to be.
The present approach works with simple cases, where there is but a single intersection along the length of any line segment.  With multiple crossings along one segment, it is necessary to
keep track of all of the intersection points along each line and create new sub-segments (hence additional graph edges) connecting the new intersection to all the intersection points along the target line.
Despite that limitation, it may be worth sharing the logic underlying the current approach.

The input line segments are treated as regions. If they intersect, the centroid will be the coordinates of the intersection.
We need to eliminate those intersections that occur at the vertices of line segments.
Lines that do not intersect will have an indeterminate centroid.
Four new edges are created for each intersection point. They connect the intersection point to the four vertices of the two intersecting lines.
A graph such as the one below on the right is generated using both the old and new edges.
The vertices are the coordinates of the respective points.
Cycles, i.e., closed loops of three vertices will be triangles provided that the three vertices are not collinear.
Presently we check to see whether any "triangle" has an indeterminate area.  (For some reason it does not return an area of 0 for three collinear points.)

A simple example
Below are (a) the figure plotted in the coordinate plane and (b) the graph showing the given nodes as well as the intersection node, {114/23, 314/69}.  In the latter, the vertices are not located at the respective Cartesian coordinates.
It may appear that their are more edges in the right figure than in the left. But remember that there are overlapping graph edges on the left.  Each diagonal actually corresponds to 3 graph edges!

    f@w_ :=(h@{a_, b_, c_, d_} := (r = RegionCentroid@RegionIntersection[Line@{a, b}, Line@{c, d}];
     {r <-> a, r <-> b, r <-> c, r <-> d});
      Cases[FindCycle[Graph[Union@Join[w /. {{a_, b_Integer}, {c_, d_}} :> {a, b} <-> {c, d},
      Cases[Flatten[h /@ Cases[{Length[Union@#] < 4, #} & /@ (FlattenAt[#, {{1}, {2}}] & /@
      Subsets[w, {2}]),{False, c_} :> c]], Except[{Indeterminate, _} <-> _]]]], {3}, 50],
      x_ /; NumericQ[RegionMeasure@Triangle[x[[All, 1]]]]][[All, All, 1]]//N//Grid)

Each row below is a triangle.
f[{{{2,8},{8,1}},{{0,4},{8,1}},{{0,4},{9,5}},{{8,1},{9,5}},{{2,8},{0,4}},{{9,5},{2,8}}}]

A more complex example
f@{{{9, 5}, {0, -10}}, {{9, 5}, {0, 2}},  {{9, 5}, {2, -1}}, {{0, -10}, {2, -1}}, {{0, -10}, {-2, -1}}, {{-9, 5}, {0, -10}}, {{-9, 5}, {0, 2}}, {{-9, 5}, {-2, -1}}, {{0, 2}, {0, -10}}, {{-9, 5}, {2, -1}}, {{9, 5}, {-2, -1}}, {{-9, 5}, {9, 5}}}

Here's the graph corresponding to the input coordinates. The vertices are at their expected Cartesian coordinates. (If you run the golfed code it will display the vertices elsewhere while respecting the vertex labels and edges. For readability, I assigned the vertex coordinates using a smattering of additional code, not necessary for the solution.)

Here's the derived graph.
It includes the derived point of intersection (0,1/11), where some of the input lines cross.

The code found 19 triangles.  Nine of them have the point, (0,1/11) as one of the vertices.


Generate a random program in your favorite language

Python → Brainf*ck (185 223 233 255 285 287 303 characters)

Code

import random as r,sys
r.seed(int(sys.argv[1]))
c=list('<>.,+-')+['']
n=9/r.random()
def b():
 global n
 s=''
 while n>0:n-=1;o=r.choice(c);s+=o if o else'[%s]'%b()
 return s
print b()

303 → 287 Characters: Removed math.ceil (it's not really necessary).
287 → 285 Characters: Switched to an empty string to denote the branch operator.
285 → 255 Characters: Condensed the if statement in the while loop.
255 → 233 Characters: Implemented JBernardo's suggestions from the comments.
233 → 223 Characters: Implemented tjko's suggestion from the comments.
223 → 185 Characters: Implemented some whitespace reduction suggestions from the comments.

Examples

$ python generate.py 1
-->,,+-<<-,-<,->[[<<,[.>.<>,,>>>,.<-,+>[[<.-+[.-+.+[-,+<>-.>,++.,,-,.,<<+[+]]]]]]]]
$ python generate.py 2
[<<--+.+++>]
$ python generate.py 3
,.++<<->>[,-,+>+[,-+<-+.<[,-[+[.-,[[<<>[,+.]]]]]]]]

Actually figuring out what the resulting BF programs do is left as an exercise to the reader.


APL(Dyalog Unicode), 21 bytes SBCS
(+/⊢×1∘⌽)⎕←(⊢÷+/)?⎕⍴0

Try it on APLgolf!
A tradfn submission which prints the list and returns the sum.
                  ⎕⍴0 ⍝ create a vector with input-many 0's
                 ?    ⍝ for each 0, get a random number between 0 and 1
            ⊢÷        ⍝ divide each number by
              +/      ⍝ the sum of all numbers
         ⎕←           ⍝ print the resulting vector
   ⊢×                 ⍝ multiply the vector element-wise
     1∘⌽              ⍝ with the vector rotated to the left by 1
 +/                   ⍝ take the sum of all products

If appending the sum to the list is fine as output, this could be 20 bytes: x,+/x×1⌽x←(⊢÷+/)?⎕⍴0


Pyth, 7 bytes
l{I#./Q

Try it online. Test suite.

Take the input (Q).
Find its partitions (./).
Filter it (#) on uniquify ({) not changing (I) the partition. This removes partitions with duplicates.
Find the result's length (l).


"Creative" ways to determine if an array is sorted

Ruby
Everyone knows: sorting is very slow and takes many cycles (the best you can do is something with n log(n)). Thus it is quite easy to check if the array is sorted. All you have to do is compare the runtime of sorting the array and sorting the sorted array.
array = [1, 5, 4, 2, 3]

## measure the time needed to sort the array 1m times
tstart = Time.now
1000000.times {
  array.sort
}
trun = Time.now - tstart

## now do a reference measurement on a sorted array
array.sort!
tstart = Time.now
1000000.times {
  array.sort
}
treference = Time.now - tstart

## compare run times
if trun > treference
  print "array was not sorted"
else
  print "array was sorted"
end


"Useful" self-modifying script for financial firm

Pseudocode

// Set up a cron job to run this script (only) once a day

yesterdays_stock_price = '46.48'

todays_stock_price = curl_google_finance('VTSMX')

print "Difference between yesterday's stock price and today's: "

print todays_stock_price

self = open('self.file')

self.replace( /yesterdays_stock_price = '[0-9\.]+'/, todays_stock_price)

self.save()


Python, 176 189 chars

import sys,re
for s in sys.stdin:x,y,z=eval(re.sub(r'(\S+) (\S+)',r'\1+\2j,',s));w=z-x;w/=y-x;c=(x-y)*(w-abs(w)**2)/2j/w.imag-x;print'(x%+.3f)^2+(y%+.3f)^2=%.3f^2'%(c.real,c.imag,abs(c+x))

Does all its work in the complex plane.  I go the math from the bottom of this page.  -c is the center of the circle.


2sable, 36 bytes
//9#999999//,#,#,221'/,#q',#q,qq2///

\$y=8\$. Used so far: 1'2q#,9/
Try it online.
Maybe this opens up some other languages that use // to comment. :)
Explanation:

2sable is an old version of 05AB1E (legacy) (which of itself is an old version of 05AB1E).
The legacy version outputs a leading newline however: try it online.
And the latest 05AB1E version outputs three leading newline: try it online.
//                                    # Divide twice, no-ops with an empty stack
  9                                   # Push 9
   #                                  # Pop and split it by spaces
                                      # (since it contains no spaces, it only pops)
    999999                            # Push 999999
          /                           # Divide the empty stack by this, popping the integer
           /                          # No-op divide again with an empty stack
            ,                         # No-op print (which would output a newline in the
                                      # newer versions)
             #,#,                     # Some more no-ops
                 221                  # Push 221
                    '/               '# Push "/"
                      ,               # Pop and print this "/" to STDOUT
                       #              # Split the 221 on spaces, so it just pops
                        q             # Exit the program
                         ',#q,qq2/// '# No-ops


Pyth, 122 - 20 - 15 = 87
=Z/lzQ=ks^lz.5Jm]dUzL[-bk+bk?tb%bkb?hb%hbkb)FNJIgNZB~Jm+NksmybN;|jbS{msm+@zk@S*Z<GQxsdkUzfqSsTUz^fqsmv@*ZzbY/smvdzQJQ"None

Changes:

130 -> 120: Switched to newline separated input.

120 -> 134: Fixed a bug involving groups not of size equal to the side length of the matrix.

134 -> 120: Prints all solutions, including ones equivalent under group renaming.

120 -> 122: Fixed a bug where only paths would be generated, instead of all legal groups.

Test run:
pyth programs/sum_group.pyth <<< '156790809
3'
1a5a6b7c9a0b8c0c9b
1a5a6c7b9a0c8b0b9c
1b5b6a7c9b0a8c0c9a
1b5b6c7a9b0c8a0a9c
1c5c6a7b9c0a8b0b9a
1c5c6b7a9c0b8a0a9b

pyth programs/sum_group.pyth <<< '156790808
3'
None

pyth programs/sum_group.pyth <<< '1111
2'
1a1a1b1b
1a1b1a1b
1b1a1b1a
1b1b1a1a

Explanation:
Pyth code           (Pseudo)-Python code              Comments

(implicit)          z = input()                       z is the digit string
(implicit)          Q = eval(input())                 S is the number of groups
(implicit)          G = 'abcdefghijklmnopqrstuvwxyz'
=Z/lzQ              Z = len(z)/Q                      Z is the size of each group.
=ks^lz.5            k = int(len(z) ** .5)             k is the side length of the matrix.
Jm]dUz              J = map(lambda d:[d], range(len(z))) Locations are encoded as numbers.
L                   def y(b): return                  y will be the transition function.
 [-bQ                         [b-k,                   Move up - the row above is k less.
  +bQ                          b+k,                   Move down - the row below is k more.
  ?tb%bkb                      b-1 if b%k else b      Move left, unless at the left edge.
  ?hb%hbkb)                    b+1 if (b+1)%k else b] Move right, unless at right edge.
FNJ                 for N in J:                       This constructs the list of all
   IgNZB                       if N[Z-1]: break       Z-length connected groups.
   ~Jm+Nk                      J+=map(lambda k: N+[k],  Append to J the group of N +
      smybN                          sum(map(lambda b:  anything reachable from
                                     y(b),N)))        anywhere in N.
   ;                (end for)
|                   or                                Print first truthy thing between
 S{                 sorted(set(                       Unique elements in sorted order of
   ms               map(lambda b:sum(                 Map+sum over allowable combinations
     m+@zd          map(lambda d:z[d]+                Character in original digit string
       @S*Z<GQ      sorted(G[:Q]*Z)[                  Repeated and sorted early alphabet
        xsbd        sum(b).index(d)],                 At index of number in sum of groups
      Uz                range(len(z)))                Over possible indexes.
   f                filter(lambda T:                  To generate allowable combinations,
                                                      we will filter all groups of Q paths.
    qSsTUz          sorted(sum(T)) == range(len(z))   Ensure all locations are visited.
    ^                                                 Combinations of
     f              filter(lambda Y:                  Filter over connected Z-length groups
      qsm           equal(sum(map(lambda k:           Sum of the values of the group
         v@*ZzkY    eval((z*Z)[k]),Y)                 In the original digit string
       /smvbzQ      sum(map(lambda b:eval(b),z))/Q    must equal the sum of all values in z
                                                      divided by the number of groups.
      J             J                                 Filter over connected Z-length groups
     Q              Q                                 Combinations of length Q
 "None              "None"                            If the above was empty, print "None"


brainfuck, 105 103 95 bytes

Outputs \x00 for false and \x01 for true.

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

Try it online!

The general principle is comparing against all values (decreasing partial distances of the char-codes), using loops to logically OR the results, and if none matched - change the output cell from 1 to 0.

See my 4 answer for a more detailed explanation (4 instructions read more easily).


J, 23 22 bytes
(];/:')'=;)&|._2{.\cut

Try it online!
                    cut    split by space
               _2{.\       only odds
             |.            reverse
   ;/:')'=;                join and sort by equality with ')'


Python, 133 bytes
The only answer so far to comply with the "Units are in pixels" rule...
from turtle import*
c=circle
r,n,l=input()
lt(90)
exec'c(r,360/n);fd(l);bk(l);'*n
fd(l)
lt(towards(-r,0)-180)
c(distance(-r,0),360,n)

Add exitonclick() to the end if you don't want the window to close immediately.
Output:
python tangentpoly.py <<< "20, 6, 30":

python tangentpoly.py <<< "100, 8, 200":


Pyth, 120 bytes

Arz7VGJ1WJK%"%0*d",HO-^TH1=J|q1l{m%-F_vMcd1T.:K2u|GHmu|GHm?qlk2:k"(.)\\1"0?qlk3}k+++=bcS"123456789"3_Mb.Tb_M.TbZdZ./K0)K

Figured I should add a real implementation then. Generates random numbers until one is found that meets all requirements. Can probably be improved a lot!

Online version


Count switches in a smallest square root sequence mod \$2^n\$

05AB1E, 15 14 bytes

LoεLnαy%0k}üÊO

Try it online!

For each n, this finds the smallest square root of a by brute-force.

05AB1E, 26 23 bytes (fast)

13v¹yλ£DnIαN>o%2÷+]@γg<

Try it online!

This one properly uses Cook's formula.

13                    # literal 13
  v               ]   # for each digit:
   ¹                  #  push the input k
    y             ]   #  push the digit
     λ£               #  recurse k times with base case y:
       Dn             #   square of the current value
         Iα           #   absolute difference with input a
           N>o%       #   modulo 2**(N+1)
               2÷     #   integer divide by 2
                 +    #   add to the current value
@                     # compare the two lists element-wise
 γ                    # group consecutive equal elements
  g                   # length
   <                  # -1


Charcoal, 25 23 bytes

ＡθＩＥ⌈ＥθＬιＥ⌈ＥθＬ§λ⁰ΣＥθ§§νιλ

Try it online! Link is to verbose version of code. Takes input as a 3-dimensional array. Explanation:

Ａθ

Input everything.

    θ                   Input
   Ｅ                    Map over arrays
      ι                 Current array
     Ｌ                  Length
  ⌈                     Maximum
 Ｅ                      Map over implicit range
          θ             Input
         Ｅ              Map over arrays
             λ          Current array
            § ⁰         First element
           Ｌ            Length
        ⌈               Maximum
       Ｅ                Map over implicit range
                 θ      Input
                Ｅ       Map over arrays
                    ν   Current array
                   § ι  Cyclically index using outer loop index
                  §   λ Cyclically index using inner loop index
               Σ        Sum
Ｉ                       Cast to string
                        Implicitly print on separate lines and paragraphs


C - 224 bytes - Running time O(n)
o=0,w=0,n[55],t,*m=n,*p=n;main(r){for(;scanf("%d",++p);t<3?--p,w+=t/2,o+=t&1:t<*m|m==n?m=p:9)t=*p=abs(*p);t=o<w?o:w;o-=t;w-=t;t+=o/3;for(o%3?o%3-2?t?t--,w+=2:++*m:w++:9;t--;)r*=3;for(r<<=w;--p>n;)r*=*p;printf("%d",r>1?r:o);}

It was amusing to see only exponential-time solutions for a linear-time problem, but I suppose it was the logical way to proceed since there were no bonus points for actually having an algorithm, which is an anagram of logarithm.
After converting negative numbers to positive and discarding zeroes, clearly we are mostly interested in multiplication. We want to maximize the logarithm of the final number.
log(a + b) < log(a) + log(b) except when a = 1 or b = 1, so ones are the only case in which we are interested in adding anything together. In general it is better to add a 1 to  a smaller number, because that causes a bigger increase in logarithm, i.e. a larger percentage increase, than adding 1 to a big number.
There are four possible scenarios, ordered most to least preferable, for utilizing ones:

Adding one to a 2 gives +log .405  [log(3) - log(2)]
Combining ones into threes gives +log .366 per one  [log(3) / 3]
Making a 2 out of ones gives +log .347 per one  [log(2) / 2]
Adding one to a number 3 or higher gives +log .288 or less  [log(4) - log(3)]

The program keeps track of the number of ones, the number of twos, and the minimum number greater than 2, and goes down the list of the most to least preferable ways of using the ones. Finally, it multiplies all the remaining numbers.


JavaScript (ES6) 87 bytes
Edit 1 byte saved thx ETHProductions
Edit 1 more byte saved thx l4me
An anonymous function. Long, but I didn't find a way to golf this more
s=>(l=t=0,s.replace(/[a-z]/ig,c=>l+=++t&&c>'Z'),l/=t,l<.5?1-l+' upp':l+' low')+'ercase'

Less golfed
s=>( // arrow function returning the value of an expression
  // here I use comma for clarity,
  // in the golfed version it's all merged in a single expression
  t = 0, // counter for letters
  l = 0, // counter for lowercase letters
  s.replace(
    /[a-z]/ig, // find all alphabetic chars, upper or lowercase
    c => // execute for each found char (in c)
        l += ++t && c>'Z', // increment t, increment l if c is lowercase
  ),
  l /= t, // l is the ratio now
  ( l < .5 // if ratio < 1/2
    ? (1-l) +' upp' // uppercase count / total (+" upp")
    : l +' low'     // lowrcase count / total (+" low")
  ) + 'ercase' // common suffix
)


Python 2, 322 240 bytes

def f(X):
 X=[[c>' 'for c in s.split('|')]for s in X.split('\n')];h=L=len(X[0])-1;p=range(L)
 for x in X:p=[a-x[a]+x[a+1]for a in p]
 while h:h=i=0;exec"if p[i]>p[i+1]:print'|'+i*' |'+'-|'+(L-i-2)*' |';h=p[i],p[i+1]=p[i+1],p[i]\ni+=1\n"*~-L

Try it online!

A function which takes the string in the specified form, and prints out the reduced Amidakuji in that form as well.

The basic idea here is to first convert the input into a permutation (in the for x in X loop); and then in the while loop, perform a bubble sort of that permutation, since as the wikipedia article notes, this results in a 'prime' Amidakuji.


Python 2, 620 bytes
import re
i=input()
s='m|e|pr|b|p|hex|h|o|n|de';d=dict(zip(s.split('|'),range(1,11)))
z=[[eval('['+a+']'),d[b]]for a,b in re.findall('(?:(\d[,\d]*).*?[\-ia]|l)('+s+')',i[:-3])]
v=z[-1][1]
l=[[0,0]for _ in range(v)]
c=0
for a,b in sorted([(i,b)for a,b in z[:-1]for i in a]):l[a-1][c]=b;c=~c
m=[max(x) for x in zip(*l)]
L,R=[[[' 'for _ in '_'*2*i]for _ in '_'*(2*v+1)]for i in m]
c=[' |'*v+' ']
C=c+['-C'*v+'-']+c
for i in range(len(l)):
 X=L;q=2*i+1
 for a in l[i]:
  if a>0:
   for j in range(0,2*a,2):
    X[q][j]='C'
    X[q-1][j]=X[q+1][j]='-'
    X[q][j+1]='|'
  X=R
for l in zip(*L)[::-1]+C+zip(*R):print ''.join(l)

Explanation
Input:
'2-ethyl-2,4,6-trimethyldecane'
First parses to string with regex (last group is root):
[[[2], 2], [[2, 4, 6], 1], [[], 10]]
Each branch is written in an array of length len(root) (Alternating up/down is handled here):
[[0, 0], [1, 2], [0, 0], [1, 0], [0, 0], [0, 1], [0, 0], [0, 0], [0, 0], [0, 0]]
'Left' and 'Right'(L,R) and 'root' (C) string branches are initialized.
Each branch is then added to the corresponding 'string' branch (big loop).
The two sides and center are printed at the end:
   |   |
  -C- -C-
 | | | | | | | | | |
-C-C-C-C-C-C-C-C-C-C-
 | | | | | | | | | |
  -C-     -C-
   |       |
  -C-
   |


Haskell, 110 120 107 characters

import Random
s l=randomRIO(1,length l-2)>>=g.($l).splitAt
g(a:b,c:d)=fmap(a:).s$c:b++d
g(a,b)=return$a++b

An example of a program using this function:

main = getLine >>= s >>= putStrLn


Mathematica, 80 58 bytes

Saved a whopping 22 bytes thanks to JungHwan Min

(FindCycle[#,∞,All]/.{}->{Cases[#,v_v_]})[[-1,;;,1]]&

 is the three byte private use character U+F3D5 representing \[DirectedEdge]. Pure function with first argument # expected to be a list of directed edges. Finds All cycles of length at most Infinity in Graph@#, then replaces the empty list with the list of self-loops. Cycles are represented as lists of edges and sorted by length, so we take the last such cycle, then from all of its edges we take the first argument so that we get a list of vertices in the specified output format.

If only Mathematica treated loops as a cycle of length 1 (AcyclicGraphQ @ CycleGraph[1, DirectedEdges -> True] gives True, seriously), then we could save another 26 bytes:

FindCycle[#,∞,All][[-1,;;,1]]&


CJam, 23 16 bytes

There's probably an elegant mathematical solution to this problem. But I have no clue how to find one, so super compressed hard coding it is!

I found one! Well, it's not a classically elegant mathematical solution as it uses bitwise operations, but it is entirely formulaic.

li_o1^_p_6|o3+6%

Try it online.

Cube layout

  4-----7          4-----7          3-----2
 /|    /|         /  0  /|         /  3  /|
1-----0 |        1-----0 |        6-----5 |
| |   | |        |     |2|        |     |4|
| 5---|-2        |  1  | 2        |  5  | 7
|/    |/         |     |/         |     |/
6-----3          6-----3          1-----4

Explanation

My old answer already laid out the cube such that each face can be described with its first (top-left) vertex number equal to the face number. But I wanted to be able to calculate more vertex numbers using the face number. At some point, I came up with the idea that got my foot in the door, to calculate the second (top-left) vertex number as the face number XOR 1. And after a while of trial and error, I managed to come up with the layout shown above and the formulas below that allow me to to calculate every vertex number for a face n quite succinctly:

Top-left: n
Top-right: n^1
Bottom-left: (n^1)|6
Bottom-right: ((n^1)+3)%6

For reference, I'll reproduce the output for each face in the desired layout here:

Face:      0     1     2     3     4     5

Vertices:  01    10    23    32    45    54
           74    63    70    65    72    61

So the whole program just comes down to reading the input face number and producing these values in order, albeit with slightly different printing logic for different vertices. Note that, because every vertex after the first starts with a base of n^1, I only need to calculate that once, which compacts the logic even further.

For posterity's sake, and because I think it was still a pretty good approach, here's my old answer.

CJam, 23 bytes

There's probably an elegant mathematical solution to this problem. But I have no clue how to find one, so super compressed hard coding it is!

"pÜ×ñè¨"487b8b3/ri_o=~p

Try it online.

Cube layout

  0-----7          0-----7          3-----6
 /|    /|         /  0  /|         /  3  /|
1-----2 |        1-----2 |        4-----5 |
| |   | |        |     |2|        |     |5|
| 5---|-6        |  1  | 6        |  4  | 7
|/    |/         |     |/         |     |/
4-----3          4-----3          1-----0

Explanation

The basic approach employed is to hard code the vertices for each face in as little space as possible. Similarly to Optimizer's base conversion solution, this treats the vertex list as an octal number packed as ASCII character data. But that's about where the similarities end to make way for further optimizations!

Here are the three key optimizations I made to the "naive" solution:

Lay out the cube such that each face can be described with its face number as the first vertex number. Looking at my cube layout as presented above, one can see that the top-left vertex number of each face is equal to the face number. This allows me to encode six fewer vertices at the cost of having to print the input back, which turns out to save a byte.
Pack the vertex data into a string for which each "character" has a maximum larger than 256. As this maximum increases past 256, the length of the string slowly decreases, but it becomes increasingly likely that any one "character" exceeds 256 and is thus no longer part of the 1-byte ASCII character set. So I wrote a program that tries encoding the vertex data in every base from 256 to 1000, with which I found about 10 bases that save one byte of character data compared to base 256. I chose 487, as that also has the nice property that the resulting string consists entirely of printable ASCII.
Mixed with the first optimization, produce the output asymetrically. The usual approach in CJam would be to format the vertex data as a 2-element list of 2-element lists, insert a newline in the middle, and let the output be implicitly printed. But I instead print the first vertex (equal to the input face number) with an operator that doesn't add a newline, retrieve the 3-element list of the other vertices, grab the next vertex and print it with an operator that does add a newline, and let the other two vertices be implicitly printed. This saves a byte.


05AB1E, 3 bytes

l.ª

Try it online!

Nothing like a good old built-in answer! This converts the string to lowercase and then performs sentence case.


Fill the rows, columns, and diagonals of an NxN grid with 1 through N

Funciton, non-competitive

UPDATE! Massive performance improvement! n = 7 now completes in under 10 minutes! See explanation at bottom!

This was good fun to write. This is a brute-force solver for this problem written in Funciton. Some factoids:

It accepts an integer on STDIN. Any extraneous whitespace breaks it, including a newline after the integer.
It uses the numbers 0 to n − 1 (not 1 to n).
It fills the grid “backwards”, so you get a solution where the bottom row reads 3 2 1 0 rather than where the top row reads 0 1 2 3.
It correctly outputs 0 (the only solution) for n = 1.
Empty output for n = 2 and n = 3.
When compiled to an exe, takes about 8¼ minutes for n = 7 (was about one hour before the performance improvement). Without compiling (using the interpreter) it takes about 1.5 times as long, so using the compiler is worth it.
As a personal milestone, this is the first time I wrote a whole Funciton program without first writing the program in a pseudocode language. I did write it in actual C# first though.
(However, this is not the first time I made a change to massively improve the performance of something in Funciton. The first time I did that was in the factorial function. Swapping the order of the operands of the multiplication made a huge difference because of how the multiplication algorithm works. Just in case you were curious.)

Without further ado:

            ┌────────────────────────────────────┐           ┌─────────────────┐
            │                                  ┌─┴─╖ ╓───╖ ┌─┴─╖   ┌──────┐    │
            │                    ┌─────────────┤ · ╟─╢ Ӂ ╟─┤ · ╟───┤      │    │
            │                    │             ╘═╤═╝ ╙─┬─╜ ╘═╤═╝ ┌─┴─╖    │    │
            │                    │               └─────┴─────┘   │ ♯ ║    │    │
            │                  ┌─┴─╖                             ╘═╤═╝    │    │
            │     ┌────────────┤ · ╟───────────────────────────────┴───┐  │    │
          ┌─┴─╖ ┌─┴─╖   ┌────╖ ╘═╤═╝ ┌──────────┐         ┌────────┐ ┌─┴─╖│    │
          │ ♭ ║ │ × ╟───┤ >> ╟───┴───┘        ┌─┴─╖       │ ┌────╖ └─┤ · ╟┴┐   │
          ╘═╤═╝ ╘═╤═╝   ╘══╤═╝          ┌─────┤ · ╟───────┴─┤ << ╟─┐ ╘═╤═╝ │   │
    ┌───────┴─────┘ ┌────╖ │            │     ╘═╤═╝         ╘══╤═╝ │   │   │   │
    │     ┌─────────┤ >> ╟─┘            │       └───────┐      │   │   │   │   │
    │     │         ╘══╤═╝            ┌─┴─╖   ╔═══╗   ┌─┴─╖ ┌┐ │   │ ┌─┴─╖ │   │
    │     │           ┌┴┐     ┌───────┤ ♫ ║ ┌─╢ 0 ║ ┌─┤ · ╟─┤├─┤   ├─┤ Ӝ ║ │   │
    │     │   ╔═══╗   └┬┘     │       ╘═╤═╝ │ ╚═╤═╝ │ ╘═╤═╝ └┘ │   │ ╘═╤═╝ │   │
    │     │   ║ 1 ╟───┬┘    ┌─┴─╖       └───┘ ┌─┴─╖ │   │      │   │   │ ┌─┴─╖ │
    │     │   ╚═══╝ ┌─┴─╖   │ ɓ ╟─────────────┤ ? ╟─┘   │    ┌─┴─╖ │   ├─┤ · ╟─┴─┐
    │     ├─────────┤ · ╟─┐ ╘═╤═╝             ╘═╤═╝   ┌─┴────┤ + ╟─┘   │ ╘═╤═╝   │
  ┌─┴─╖ ┌─┴─╖       ╘═╤═╝ │ ╔═╧═╕ ╔═══╗ ┌───╖ ┌─┴─╖ ┌─┴─╖    ╘═══╝     │   │     │
┌─┤ · ╟─┤ · ╟───┐     └┐  └─╢   ├─╢ 0 ╟─┤ ⌑ ╟─┤ ? ╟─┤ · ╟──────────────┘   │     │
│ ╘═╤═╝ ╘═╤═╝   └───┐ ┌┴┐   ╚═╤═╛ ╚═╤═╝ ╘═══╝ ╘═╤═╝ ╘═╤═╝                  │     │
│   │   ┌─┴─╖ ┌───╖ │ └┬┘   ┌─┴─╖ ┌─┘           │     │                    │     │
│ ┌─┴───┤ · ╟─┤ Җ ╟─┘  └────┤ ? ╟─┴─┐   ┌─────────────┘                    │     │
│ │     ╘═╤═╝ ╘═╤═╝         ╘═╤═╝   │   │╔════╗╔════╗                      │     │
│ │       │  ┌──┴─╖ ┌┐   ┌┐ ┌─┴─╖ ┌─┴─╖ │║ 10 ║║ 32 ║    ┌─────────────────┘     │
│ │       │  │ << ╟─┤├─┬─┤├─┤ · ╟─┤ · ╟─┘╚══╤═╝╚╤═══╝ ┌──┴──┐                    │
│ │       │  ╘══╤═╝ └┘ │ └┘ ╘═╤═╝ ╘═╤═╝     │ ┌─┴─╖ ┌─┴─╖ ┌─┴─╖                  │
│ │     ┌─┴─╖ ┌─┴─╖  ┌─┴─╖  ┌─┴─╖ ╔═╧═╕     └─┤ ? ╟─┤ · ╟─┤ % ║                  │
│ └─────┤ · ╟─┤ · ╟──┤ Ӂ ╟──┤ ɱ ╟─╢   ├───┐   ╘═╤═╝ ╘═╤═╝ ╘═╤═╝                  │
│       ╘═╤═╝ ╘═╤═╝  ╘═╤═╝  ╘═══╝ ╚═╤═╛ ┌─┴─╖ ┌─┴─╖   │     └────────────────────┘
│         └─────┤      │            └───┤ ‼ ╟─┤ ‼ ║   │        ┌──────┐
│               │      │                ╘═══╝ ╘═╤═╝   │        │ ┌────┴────╖
│               │      │                      ┌─┴─╖   │        │ │ str→int ║
│               │      └──────────────────────┤ · ╟───┴─┐      │ ╘════╤════╝
│               │          ┌─────────╖        ╘═╤═╝     │    ╔═╧═╗ ┌──┴──┐
│               └──────────┤ int→str ╟──────────┘       │    ║   ║ │ ┌───┴───┐
│                          ╘═════════╝                  │    ╚═══╝ │ │ ┌───╖ │
└───────────────────────────────────────────────────────┘          │ └─┤ × ╟─┘
           ┌──────────────┐                                  ╔═══╗ │   ╘═╤═╝
╔════╗     │ ╓───╖ ┌───╖  │                              ┌───╢ 0 ║ │   ┌─┴─╖ ╔═══╗
║ −1 ║     └─╢ Ӝ ╟─┤ × ╟──┴──────┐                       │   ╚═╤═╝ └───┤ Ӂ ╟─╢ 0 ║
╚═╤══╝       ╙───╜ ╘═╤═╝         │                       │   ┌─┴─╖     ╘═╤═╝ ╚═══╝
┌─┴──╖ ┌┐ ┌───╖ ┌┐ ┌─┴──╖ ╔════╗ │                       │ ┌─┤   ╟───────┴───────┐
│ << ╟─┤├─┤ ÷ ╟─┤├─┤ << ║ ║ −1 ║ │                       │ │ └─┬─╜ ┌─┐ ┌─────┐   │
╘═╤══╝ └┘ ╘═╤═╝ └┘ ╘═╤══╝ ╚═╤══╝ │                       │ │   └───┴─┘ │   ┌─┴─╖ │
  │         └─┘      └──────┘    │                       │ └───────────┘ ┌─┤ ? ╟─┘
  └──────────────────────────────┘         ╓───╖         └───────────────┘ ╘═╤═╝
                               ┌───────────╢ Җ ╟────────────┐                │
      ┌────────────────────────┴───┐       ╙───╜            │
      │                          ┌─┴────────────────────┐ ┌─┴─╖
    ┌─┴─╖                      ┌─┴─╖                  ┌─┴─┤ · ╟──────────────────┐
    │ ♯ ║ ┌────────────────────┤ · ╟───────┐          │   ╘═╤═╝                  │
    ╘═╤═╝ │                    ╘═╤═╝       │          │     │              ┌───╖ │
┌─────┴───┘    ┌─────────────────┴─┐   ┌───┴───┐    ┌─┴─╖ ┌─┴─╖          ┌─┤ × ╟─┴─┐
│              │                 ┌─┴─╖ │   ┌───┴────┤ · ╟─┤ · ╟──────────┤ ╘═╤═╝   │
│              │ ┌───╖ ┌───╖  ┌──┤ · ╟─┘ ┌─┴─┐      ╘═╤═╝ ╘═╤═╝        ┌─┴─╖ │     │
│         ┌────┴─┤ ♭ ╟─┤ × ╟──┘  ╘═╤═╝   │ ┌─┴─╖ ┌───╖└┐ ┌──┴─╖      ┌─┤ · ╟─┘     │
│         │      ╘═══╝ ╘═╤═╝ ┌───╖ │     │ │ × ╟─┤ Ӝ ╟─┴─┤ ÷% ╟─┐    │ ╘═╤═╝ ┌───╖ │
│   ┌─────┴───┐     ┌────┴───┤ Ӝ ╟─┴─┐   │ ╘═╤═╝ ╘═╤═╝   ╘══╤═╝ │    │   └───┤ Ӝ ╟─┘
│ ┌─┴─╖ ┌───╖ │     │ ┌────╖ ╘═╤═╝   │   └───┘   ┌─┴─╖      │   │    └────┐  ╘═╤═╝
│ │ × ╟─┤ Ӝ ╟─┘     └─┤ << ╟───┘   ┌─┴─╖ ┌───────┤ · ╟───┐  │ ┌─┴─╖ ┌───╖ │    │
│ ╘═╤═╝ ╘═╤═╝         ╘══╤═╝   ┌───┤ + ║ │       ╘═╤═╝   ├──┴─┤ · ╟─┤ × ╟─┘    │
└───┤     └────┐ ╔═══╗ ┌─┴─╖ ┌─┴─╖ ╘═╤═╝ │ ╔═══╗ ┌─┴─╖ ┌─┴─╖  ╘═╤═╝ ╘═╤═╝      │
  ┌─┴─╖ ┌────╖ │ ║ 0 ╟─┤ ? ╟─┤ = ║  ┌┴┐  │ ║ 0 ╟─┤ ? ╟─┤ = ║    │     │ ┌────╖ │
  │ × ╟─┤ << ╟─┘ ╚═══╝ ╘═╤═╝ ╘═╤═╝  └┬┘  │ ╚═══╝ ╘═╤═╝ ╘═╤═╝    │     └─┤ << ╟─┘
  ╘═╤═╝ ╘═╤══╝ ┌┐     ┌┐ │     │     └───┘       ┌─┴─╖   ├──────┘       ╘═╤══╝
    │     └────┤├──┬──┤├─┘     ├─────────────────┤ · ╟───┘                │
    │          └┘┌─┴─╖└┘       │     ┌┐   ┌┐     ╘═╤═╝ ┌┐   ┌┐            │
    └────────────┤ · ╟─────────┘   ┌─┤├─┬─┤├─┐     └───┤├─┬─┤├────────────┘
                 ╘═╤═╝             │ └┘ │ └┘ │         └┘ │ └┘
                   └───────────────┘    │    └────────────┘

Explanation of the first version

The first version took about an hour to solve n = 7. The following explains mostly how this slow version worked. At the bottom I will explain what change I made to get it to under 10 minutes.

An excursion into bits

This program needs bits. It needs lots of bits, and it needs them in all the right places. Experienced Funciton programmers already know that if you need n bits, you can use the formula

which in Funciton can be expressed as

When doing my performance optimization, it occurred to me that I can calculate the same value much faster using this formula:

I hope you’ll forgive me that I didn’t update all the equation graphics in this post accordingly.

Now, let’s say you don’t want a contiguous block of bits; in fact, you want n bits at regular intervals every k-th bit, like so:

                                 LSB
                                  ↓
00000010000001000000100000010000001
                            └──┬──┘
                               k

The formula for this is fairly straight-forward once you know it:

In the code, the function Ӝ takes values n and k and calculates this formula.

Keeping track of used numbers

There are n² numbers in the final grid, and each number can be any of n possible values. In order to keep track of which numbers are permitted in each cell, we maintain a number consisting of n³ bits, in which a bit is set to indicate that a particular value is taken. Initially this number is 0, obviously.

The algorithm begins in the bottom-right corner. After “guessing” the first number is a 0, we need to keep track of the fact that the 0 is no longer permitted in any cell along the same row, column and diagonal:

LSB                               (example n=5)
 ↓
 10000 00000 00000 00000 10000
 00000 10000 00000 00000 10000
 00000 00000 10000 00000 10000
 00000 00000 00000 10000 10000
 10000 10000 10000 10000 10000
                             ↑
                            MSB

To this end, we calculate the following four values:

Current row: We need n bits every n-th bit (one per cell), and then shift it to the current row r, remembering every row contains n² bits:

Current column: We need n bits every n²-th bit (one per row), and then shift it to the current column c, remembering every column contains n bits:

Forward diagonal: We need n bits every... (did you pay attention? Quick, figure it out!)... n(n+1)-th bit (well done!), but only if we’re actually on the forward diagonal:

Backward diagonal: Two things here. First, how do we know if we’re on the backward diagonal? Mathematically, the condition is c = (n − 1) − r, which is the same as c = n + (−r − 1). Hey, does that remind you of something? That’s right, it’s two’s complement, so we can use bitwise negation (very efficient in Funciton) instead of the decrement. Second, the formula above assumes that we want the least significant bit to be set, but in the backward diagonal we don’t, so we have to shift it up by... do you know?... That’s right, n(n − 1).

This is also the only one where we potentially divide by 0 if n = 1. However, Funciton doesn’t care. 0 ÷ 0 is just 0, don’t you know?

In the code, the function Җ (the bottom one) takes n and an index (from which it calculates r and c by division and remainder), calculates these four values and ors them together.

The brute-force algorithm

The brute-force algorithm is implemented by Ӂ (the function at the top). It takes n (the grid size), index (where in the grid we’re currently placing a number), and taken (the number with n³ bits telling us which numbers we can still place in each cell).

This function returns a sequence of strings. Each string is a full solution to the grid. It’s a complete solver; it would return all solutions if you let it, but it returns them as a lazy-evaluated sequence.

If index has reached 0, we’ve successfully filled the whole grid, so we return a sequence containing the empty string (a single solution that covers none of the cells). The empty string is 0, and we use the library function ⌑ to turn that into a single-element sequence.
The check described under performance improvement below happens here.
If index has not yet reached 0, we decrement it by 1 to get the index at which we now need to place a number (call that ix).

We use ♫ to generate a lazy sequence containing the values from 0 to n − 1.

Then we use ɓ (monadic bind) with a lambda that does the following in order:

First look at the relevant bit in taken to decide whether the number is valid here or not. We can place a number i if and only if taken & (1 << (n × ix) << i) isn’t already set. If it is set, return 0 (empty sequence).
Use Җ to calculate the bits corresponding to the current row, column and diagonal(s). Shift it by i and then or it onto taken.
Recursively call Ӂ to retrieve all solutions for the remaining cells, passing it the new taken and the decremented ix. This returns a sequence of incomplete strings; each string has ix characters (the grid filled in up to index ix).
Use ɱ (map) to go through the solutions thusly found and use ‼ to concatenate i to the end of each. Append a newline if index is a multiple of n, otherwise a space.

Generating the result

The main program calls Ӂ (the brute forcer) with n, index = n² (remember we fill the grid backwards) and taken = 0 (initially nothing is taken). If the result of this is an empty sequence (no solution found), output the empty string. Otherwise, output the first string in the sequence. Note that this means it will evaluate only the first element of the sequence, which is why the solver doesn’t continue until it has found all solutions.

Performance improvement

(For those who already read the old version of the explanation: the program no longer generates a sequence of sequences that needs to be separately turned into a string for output; it just generates a sequence of strings directly. I’ve edited the explanation accordingly. But that wasn’t the main improvement. Here it comes.)

On my machine, the compiled exe of the first version took pretty much exactly 1 hour to solve n = 7. This was not within the given time limit of 10 minutes, so I didn’t rest. (Well, actually, the reason I didn’t rest was because I had this idea on how to massively speed it up.)

The algorithm as described above stops its search and backtracks every time that it encounters a cell in which all the bits in the taken number are set, indicating that nothing can be put into this cell.

However, the algorithm will continue to futilely fill the grid up to the cell in which all those bits are set. It would be much faster if it could stop as soon as any yet-to-be-filled-in cell already has all the bits set, which already indicates that we can never solve the rest of the grid no matter what numbers we put in it. But how do you efficiently check whether any cell has its n bits set without going through all of them?

The trick starts by adding a single bit per cell to the taken number. Instead of what was shown above, it now looks like this:

LSB                               (example n=5)
 ↓
 10000 0 00000 0 00000 0 00000 0 10000 0
 00000 0 10000 0 00000 0 00000 0 10000 0
 00000 0 00000 0 10000 0 00000 0 10000 0
 00000 0 00000 0 00000 0 10000 0 10000 0
 10000 0 10000 0 10000 0 10000 0 10000 0
                                       ↑
                                      MSB

Instead of n³, there are now n²(n + 1) bits in this number. The function that populates the current row/column/diagonal has been changed accordingly (actually, completely rewritten to be honest). That function will still populate only n bits per cell though, so the extra bit we just added will always be 0.

Now, let’s say we are halfway through the calculation, we just placed a 1 in the middle cell, and the taken number looks something like this:

                 current
LSB              column           (example n=5)
 ↓                 ↓
 11111 0 10010 0 01101 0 11100 0 11101 0
 00011 0 11110 0 01101 0 11101 0 11100 0
 11111 0 11110 0[11101 0]11100 0 11100 0    ← current row
 11111 0 11111 0 11111 0 11111 0 11111 0
 11111 0 11111 0 11111 0 11111 0 11111 0
                                       ↑
                                      MSB

As you can see, the top-left cell (index 0) and the middle-left cell (index 10) are now impossible. How do we most efficiently determine this?

Consider a number in which the 0th bit of each cell is set, but only up to the current index. Such a number is easy to calculate using the familiar formula:

What would we get if we added these two numbers together?

LSB                                               LSB
 ↓                                                 ↓
 11111 0 10010 0 01101 0 11100 0 11101 0           10000 0 10000 0 10000 0 10000 0 10000 0        ╓───╖
 00011 0 11110 0 01101 0 11101 0 11100 0     ║     10000 0 10000 0 10000 0 10000 0 10000 0            ║
 11111 0 11110 0 11101 0 11100 0 11100 0  ═══╬═══  10000 0 10000 0 00000 0 00000 0 00000 0  ═════   ╓─╜
 11111 0 11111 0 11111 0 11111 0 11111 0     ║     00000 0 00000 0 00000 0 00000 0 00000 0  ═════   ╨
 11111 0 11111 0 11111 0 11111 0 11111 0           00000 0 00000 0 00000 0 00000 0 00000 0          o
                                       ↑                                                 ↑
                                      MSB                                               MSB

The result is:

             OMG
              ↓
        00000[1]01010 0 11101 0 00010 0 00011 0
        10011 0 00001 0 11101 0 00011 0 00010 0
═════   00000[1]00001 0 00011 0 11100 0 11100 0
═════   11111 0 11111 0 11111 0 11111 0 11111 0
        11111 0 11111 0 11111 0 11111 0 11111 0

As you can see, the addition overflows into the extra bit that we added, but only if all the bits for that cell are set! Therefore, all that’s left to do is to mask out those bits (same formula as above, but << n) and check if the result is 0:

00000[1]01010 0 11101 0 00010 0 00011 0    ╓╖    00000 1 00000 1 00000 1 00000 1 00000 1         ╓─╖ ╓───╖
10011 0 00001 0 11101 0 00011 0 00010 0   ╓╜╙╖   00000 1 00000 1 00000 1 00000 1 00000 1        ╓╜ ╙╖    ║
00000[1]00001 0 00011 0 11100 0 11100 0   ╙╥╥╜   00000 1 00000 1 00000 0 00000 0 00000 0  ═════ ║   ║  ╓─╜
11111 0 11111 0 11111 0 11111 0 11111 0   ╓╜╙╥╜  00000 0 00000 0 00000 0 00000 0 00000 0  ═════ ╙╖ ╓╜  ╨
11111 0 11111 0 11111 0 11111 0 11111 0   ╙──╨─  00000 0 00000 0 00000 0 00000 0 00000 0         ╙─╜   o

If it is not zero, the grid is impossible and we can stop.

Screenshot showing solution and running time for n = 4 to 7.


JavaScript, 71 characters

function f(s){return "\u202E"+s.split("").reverse().join("")+"\u202C";}

Try it out on JSFiddle.

By the way, this would be a good bit shorter in CoffeeScript (53 characters)

f=(s)->"\u202E#{s.split('').reverse().join ''}\u202C"

EDIT: I just noticed that UTF-8 requirement. That's going to be tough in JavaScript. :-/


Jelly, 13 bytes

L:Øe³ḣȯ-Ṁ<i1ị

Definitely an O(n) algorithm, hopefully an O(n) implementation. Try it online!

How it works

L:Øe³ḣȯ-Ṁ<i1ị  Main link. Argument: A (list of scores)

L              Get the length of A.
 :Øe           Divide the length by e, flooring the result.
    ³ḣ         Retrieve the that many scores from the beginning of A.
      ȯ-       Logical OR; replace an empty list with -1.
        Ṁ      Compute the maximum of those scores.
         <     Compare each score in A with that maximum.
          i1   Find the first index of 1 (0 if not found).
            ị  Retrieve the element of A at that index (the last one if 0).


Check if an array (or equivalent) has the same number of odd and even numbers - Code Golf Edition!

Haskell, 20 bytes

(==0).sum.map((-1)^)

Try it online!


List of programming languages that can run code at runtime

A few I recall:

Lua: loadstring("2 + 2")
*Script (Coffee, Java, Type, Action): eval("2 + 2")
Erlang / Elixir: Code.eval_string("a + b", [a: 2, b: 2], file: __ENV__.file, line: __ENV__.line)
J: ". '2 + 2' (eval it right away) or 3 : '2 + 2' (define a function; (3 : '2 + 2') 0 runs it)
Ruby: eval "2 + 2"
Perl: eval "2 + 2"
Bash: a="ls | wc -l", eval $a
PHP: eval("2 + 2")
Lisp, obviously: (setq test'(+ 2 2)) and (eval test)
Python: eval('2 + 2')
ColdFusion: <cfset x = "int(2+2)"> and <cfset y = Evaluate(x)>
FORTH: S" 2 2 + ." eval (note: it depends on the implementation; most use either EVALUATE or eval)
VBScript, VBA: Execute('2 + 2') (note: for VBA as far as I recall, it's eval)
Smalltalk: Compiler evaluate:'2 + 2'
APL: The ⍎ primitive executes a character vector that contains a valid APL expression: ⍎ '2×3' or ⍎ 'S←A String'. The former will execute the mathematical expression and return 6; the latter will create a variable S in the APL workspace, and assign it the value A String
PowerShell: invoke-expression '2 + 2'
R: eval(parse(text = "2 + 2"))
Io: doString("2 + 2")
Burlesque: "2 2.+"pe

Other languages:

Java: see ScriptEngine functionality.
C, C++: they can execute shellcode
D: via mixins, int a = 0; and then mixin("a = 2 + 2;"); (note: the string must be constant and known at the compile time)


Pyth - 83 82 bytes
Jesus, this is long, probably a few redundancies, but the formulas are long. This is a recursive solution that just implements the formulas given. The reference solution seems to be doing something else, but I don't know what. Maybe if I knew more about what all of this does...
KEM?H+.x*c-KJ@QG-@Q+GHJgGtHZ.x*c-=T@Qh+GHK-T@QhGghGtHZ&|>K@QGqK@QG<K@QhGgRvzt-lQvz

Test Suite.


Translate your English source code into a foreign language

Python, Koine Greek - Πύθων
My favorite programming language, in my favorite foreign language--perfect! And it doesn't hurt that the name is already Greek.
The translator program in Python 3 (thank goodness for native Unicode support):
with open(__file__, encoding="utf-8") as f:
    code = f.read()

replacements = [
    ("print", "γραψάτω"),
    ("input", "λαβέτω"),
    ("read", "ἀναγνώτω"),
    ("open", "ἀνεῳξάτω"),
    ("file", "βιβλίον"),
    ("import", "εἰσενεγκάτω"),
    ("encoding", "τύπος"),
    ("code", "λόγοι"),
    ("replacements", "νεόλογοι"),
    ("location", "τόπος"),
    ("old", "παλαιόν"),
    ("new", "νέον"),
    ("find", "εὑρέτω"),
    ("replace", "ἀλλαξάτω"),
    ("for", "ἕκαστον"),
    ("while", "ἐν τῷ"),
    ("elif", "εἰ δὲ"),
    ("if", "εἰ"),
    ("else", "εἰ δὲ μή"),
    ("is not", "οὐκ ἔστιν"),
    ("is", "ἔστιν"),
    ("not in", "οὐκ ἐν"),
    ("in", "ἐν"),
    ("and", "καὶ"),
    ("or", "ἢ"),
    ("not", "οὐ"),
    ("with", "μετὰ"),
    ("as", "ὡς"),
    ("re", "ῥλ"),
    ("sys", "σύς"),
    (":", "·"),
    ("ph", "φ"),
    ("th", "θ"),
    ("ch", "χ"),
    ("ps", "ψ"),
    ("a", "α"),
    ("b", "β"),
    ("c", "κ"),
    ("d", "δ"),
    ("e", "ε"),
    ("f", "φ"),
    ("g", "γ"),
    ("h", ""),
    ("i", "ι"),
    ("j", "ι"),
    ("k", "κ"),
    ("l", "λ"),
    ("m", "μ"),
    ("n", "ν"),
    ("o", "ο"),
    ("p", "π"),
    ("r", "ρ"),
    ("s ", "ς "),
    ("s.", "ς."),
    ("s,", "ς,"),
    ("s·", "ς·"),
    ("s", "σ"),
    ("t", "τ"),
    ("u", "ου"),
    ("v", "ου"),
    ("w", "ου"),
    ("x", "ξ"),
    ("y", "υ"),
    ("z", "ζ")
    ]

for old, new in replacements:
    if old == "for":
        location = 0
        while old in code[location:]:
            location = code.find(old, location)
            if code[location+3] != '"':
                location = code.find("in", location)
                code = code[:location] + "ἐκ" + code[location+2:]
            else:
                location += 1
    code = code.replace(old, new)

print(code)

Results of running the code on itself (with the big translation list redacted):
μετὰ ἀνεῳξάτω(__βιβλίον__, τύπος="ουτφ-8") ὡς φ·
    λόγοι = φ.ἀναγνώτω()

νεόλογοι = [
    ("γραψάτω", "γραψάτω"),
    ("λαβέτω", "λαβέτω"),
    ("ἀναγνώτω", "ἀναγνώτω"),
    ...
    ]

ἕκαστον παλαιόν, νέον ἐκ νεόλογοι·
    εἰ παλαιόν == "ἕκαστον"·
        τόπος = 0
        ἐν τῷ παλαιόν ἐν λόγοι[τόπος·]·
            τόπος = λόγοι.εὑρέτω(παλαιόν, τόπος)
            εἰ λόγοι[τόπος+3] != '"'·
                τόπος = λόγοι.εὑρέτω("ἐν", τόπος)
                λόγοι = λόγοι[·τόπος] + "ἐκ" + λόγοι[τόπος+2·]
            εἰ δὲ μή·
                τόπος += 1
    λόγοι = λόγοι.ἀλλαξάτω(παλαιόν, νέον)

γραψάτω(λόγοι)

Koine Greek is 2000 years old, so it was fun translating programming terms. Here's a few of my favorites:

βιβλίον = "scroll" (file)
γραψάτω = "write" (print)
λαβέτω = "take" (input)
εἰσενεγκάτω = "bring in" (import)
τύπος = "pattern, type" (encoding)
λόγοι/νεόλογοι = "words"/"new words" (code/replacements)
ἕκαστον... ἐκ = "each... from" (for ... in)
εἰ... εἰ δὲ... εἰ δὲ μή = "if... but if... but if not" (if ... elif ... else)
ἐν τῷ literally means "in the," but in certain contexts it can be an idiom for "when, while"
"Regular expression" became ῥήμα λογικόν, "rational/reasonable saying"; thus, the abbreviation re is ῥλ

Most of the words can be also found by searching on Wiktionary.
Some other salient features:

English programming uses a bunch of imperative verbs (print, read, replace). I suspect the ancient Greeks would feel a bit foolish talking to the computer like this, so I made them all third-person imperatives: "it must print," "it must read," "it must replace."
Greek punctuation is a bit different from English. I didn't go overboard with this, because I'm not sure what to replace the square brackets and underscores with, but I did swap out colons for ano teleia or "high period" (·).
For words that aren't in the list, I made sure to transliterate all the lowercase letters too. There isn't always a straight one-to-one correspondence; so for example, utf turns into ουτφ--which sounds about like "ootf" if you try to pronounce it.

This still leaves a lot to be desired grammar-wise. Greek is a much more highly inflected language than English, and my code isn't nearly sophisticated enough to get all the cases and numbers right. For example, ἕκαστον παλαιόν, νέον ἐκ νεόλογοι ought to read ἐκ νεολόγων, with the object of the preposition in the genitive case. However, I'm not about to put that much time into this! The look is sufficiently Greek (at least to the untrained eye) and the high periods add a nice touch. All in all, I'm pretty satisfied with the results.


Mathematica, 34+20=54
to Decimal
ToExpression@StringDrop[#,-1]/100&

to Percentage
ToString[100#]<>"%"&


Bash + coreutils, 11 bytes

tr xy yx<$0

This prints

tr yx xy<$0

Try it online!

In turn, that prints

tr xy yx<$0