Python 3, 48 bytes

Takes as input \$ K \$ and \$ S \$, the keyboard and the target string. \$ K \$ is a taken as a list of lists.

lambda K,S:{r.pop(0)for r in K for i in r}>={*S}

Try it online!

Explanation

It essentially converts \$ S \$ and the valid keyboard characters \$ K' \$ into sets, and returns True iff \$ S \$ is a subset of \$ K' \$. To obtain only the first half of each row of \$ K \$, we use the pop trick, which is explained in this answer of mine.

The previous answer, where \$ K \$ is taken as a list of strings instead.

Python 3, 54 bytes

lambda K,S:{*''.join(r[:-~len(r)//2]for r in K)}>={*S}

Try it online!


Haskell, 312 318 chars

import Data.List
s(ξ:υ:_,λ:σ:η:_)(x:y:_,l:w:_)=(ξ+λ<=x||ξ>=x+l||υ+σ<=y||υ>=y+w)&&ξ+λ<7&&υ+σ<13&&η<6
y p l=[(v,r):l|v<-[[x,y,0]|x<-[0..5],y<-[0..11]],r<-permutations p,all(s(v,r))l]
main=do
 n<-readLn
 p<-mapM(fmap(map read.words).const getLine)[1..n]
 putStr.r$foldr((=<<).y)[[([9,0],[0..])]]p
r[]="NO"
r _="YES"

For some reason that I don't fully understand at the moment, it doesn't finish your tests #9 and #16 in reasonable time. But you didn't say anything about performance, did you?

373 383 chars

This version runs much faster for the examples: it first checks if it's not impossible simply because the area is too small, and then it starts with the largest parcels rather then inserting them in the given order. Note that the area detection is not perfect: it doesn't consider rotations, so it may on some inputs give wrong results. But it does work with the test script.

import Data.List
s(ξ:υ:_,λ:σ:η:_)(x:y:_,l:w:_)=(ξ+λ<=x||ξ>=x+l||υ+σ<=y||υ>=y+w)&&ξ+λ<7&&υ+σ<13&&η<6
y p l=[(v,r):l|v<-[[x,y,0]|x<-[0..5],y<-[0..11]],r<-permutations p,all(s(v,r))l]
π=product
main=do
 n<-readLn
 p<-mapM(fmap(map read.words).const getLine)[1..n]
 putStr$if sum(map(π.init)p)>72||null(foldr((=<<).y)[[([9,0],[0..])]].sortBy((.π).compare.π)$p)then"NO"else"YES"


x86-64 Machine Code, 24 bytes
01 FF FF C7 6A 01 59 89 F8 FF C1 99 F7 F9 85 D2 75 F5 39 F9 0F 94 C0 C3

The above code defines a function that takes a single parameter (the input value, known to be a prime) in EDI (following the System V AMD64 calling convention used on Gnu/Unix), and returns a Boolean result in AL (1 if the input is a Sophie Germain prime, 0 otherwise).
The implementation is very similar to the solution to this challenge, since all we really have to do is determine whether a number is prime using as little code as possible, which means an inefficient iterative loop.
Basically, we take the input and immediately transform it into 2 × input + 1. Then, starting with a counter set to 2, we loop through and check to see if the counter is a factor. The counter is incremented each time through the loop. As soon as a factor is found, the loop ends and that factor is compared against 2 × input + 1. If the factor is equal to the test value, then that means we didn't find any smaller factors, and therefore the number must be prime. And since we have thus confirmed that 2 × input + 1 is prime, this means that input must be a Sophie Germain prime.
Ungolfed assembly language mnemonics:
IsSophieGermainPrime:
   add   edi, edi            ; input *= 2
   inc   edi                 ; input += 1
   push  1
   pop   rcx                 ; counter = 1

.CheckDivisibility:
   inc   ecx                 ; increment counter
   mov   eax, edi            ; EAX = input (needs to be in EAX for IDIV; will be clobbered)
   cdq                       ; sign-extend EAX into EDX:EAX
   idiv  ecx                 ; EDX:EAX / counter
   test  edx, edx            ; check the remainder to see if divided evenly
   jnz   .CheckDivisibility  ; keep looping if not divisible by this one

   cmp   ecx, edi            ; compare counter to input
   sete  al                  ; set true if first found factor is itself;
   ret                       ;          otherwise, set false


sed 144

Most of you will know this little episode from roman times, when Cesar invented the Cesar crypting (aka rot13) using SED.

As a big fanatic of SED, he printed the most common used commands: substitute, print, quit and read (SPQR) on signs which he carried with him to teach his soldiers the use of SED.

#  63 = sed-file
#  81 = this
# 144 summa summarum
tac a|rev|sed y/gs/sg/ >b
echo $1|sed -f a|sed "s/$(echo $2|sed -f a)//"|sed -f b

first version 181:

# 126 = 2 sed-files =126
#  55 = this
# 181 summa summarum
echo $1|sed -f a|sed "s/$(echo $2|sed -f a)//"|sed -f b

2 files to use which count to the solution:

a:

s/M/DD/g
s/D/CCCCC/g
s/C/LL/g
s/L/XXXXX/g
s/X/VV/g
s/V/IIIII/g

b:

s/IIIII/V/g
s/VV/X/g
s/XXXXX/L/g
s/LL/C/g
s/CCCCC/D/g
s/DD/M/g

but b can be produced with the first line of the new solution from a: it is - more or less - the inverse, and so we read the file from bottom to top (tac) and from right to left (rev), and switch s and g which are now in the wrong order.

Invocation:

./cg-6061-roman-minus.sh MDCCCCLXV LXVI
MDCCCLXXXXVIIII

I guess I can golf this further, but I liked to occupy wallstreet the sed slot. :)

Since the logic isn't only in the sed files, but in the invocation too, I sum it all up. It could be argued about echo $1, but what about the nested $2? Let's just sum it together.

The sedfiles are pretty long and very redundant in their structure. There seems to be room for optimization.

Luckily, the romans already had QVANTVM <OMPVTVVMZ, so they didn't care for the otherwise lousy performance.

tl;dr:

I convert both numbers into church numerals (IIIIII=6), remove the second from the first, and reconvert the result back.

s.e.d. - sod errat demonstrandum.


Python 3, 112
Saved 4 bytes thanks to vaultah.
Booyah, beating JS!
lambda x,z="ΑΒΓΔΕϜΖΗΘΙΚΛΜΝΞΟΠϘΡΣΤΥΦΧΨΩϠ".find:sum((z(c)%9+1)*10**(z(c)//9)for c in x)

With test cases:
assert(f("ΡΚΓ")==123)
assert(f("Η")==8)
assert(f("ΨΟΖ")==777)
assert(f("Ρ")==100)
assert(f("ΧϜ")==606)

Loops through the string and uses its index in the list of potentials chars to calculate how much it's worth.


Manipulate destiny, fake random numbers: Be Dirty Harry

How about this? Solution at the very bottom, encoded in base64. Language is C.

#include <stdio.h>
int lfsr = 0xACE1u;
/*Toy LFSR implementation stolen from wikipedia.*/
int random_bit(){
    /* taps: 16 14 13 11; feedback polynomial: x^16 + x^14 + x^13 + x^11 + 1 */
    int bit  = ((lfsr >> 0) ^ (lfsr >> 1) ^ (lfsr >> 3) ^ (lfsr >> 5) )&1 ;
    lfsr =  (lfsr >> 1) | (bit << 15);
    return ((lfsr >> 14)&(lfsr >> 15))^bit;
}
int surrendered=0,scratched=0,shot =0;

void harry_tis_but_a_scratch(){scratched++;}
int harry_catchy_phrase(){return random_bit();}
void bandit_surrender(){surrendered++;}
void harry_use_magnum(){shot++;}
int bandit_roll_dice() {return random_bit();}
void bandit_grab_gun() {}

int main()
{
    int random_number=0;
    /*Test bench random bit*/
    for(int y=1;y<51;++y){
        for(int x=0;x<8*sizeof(int);++x)random_number= (random_number<<1)|random_bit();
        printf("%-15d%c",random_number,y%5?' ':'\n');
    }
    printf("\nLooks pretty random\n\n");
    /*Play the game*/
    for(int x=0;100000 >=++ x;){
        int doYouFeelLuckyPunk = harry_catchy_phrase();
        int actuallyIsLucky = bandit_roll_dice();
        if(doYouFeelLuckyPunk) {
            bandit_grab_gun();
            if(!actuallyIsLucky) harry_use_magnum();
            else harry_tis_but_a_scratch();
        }else bandit_surrender();
    }
    printf("Shot: %d Surrendered: %d  Scratched: %d\n",shot,surrendered,scratched);
    return 0;
}
/*
                               Example Output
   1414529544,  -2071427967,     89395234,    690094340,    704663586,
     41977888,  -1572861663,   1107591810,    143171844,    546578948,
  -1542942712,  -1600056768,  -1571682240,     84415044,  -2138746864,
    705971264,    302123561,    168036485,    553717833,    545294674,
     71909648,  -1994096044,   1426227848,   1218611781,    138707496,
     16810505,    553783616,  -1861155808,  -1803283192,   1111626024,

Looks pretty random

Shot: 24941 Surrendered: 75059  Scratched: 0

                                  SOLUTION

IFRoZSB3YXkgdGhpcyB3b3JrcyBpcyBxdWl0ZSBzaW1wbGUsIHRoZSBMRlNSIGlzIHJlYWwgYW5k
IGRvZXMgaW4gZmFjdCBnZW5lcmF0ZQ0KIGdvb2QgcHNldWRvLXJhbmRvbSBudW1iZXJzLkFuZCBp
dCBpcyBpbmZhY3QgYW4gZXhhY3QgaW1wbGVtZW50YXRpb24gb2YgdGhlIG9uZQ0KIGZyb20gd2lr
aXBlZGlhLCBleGNlcHQgZm9yIG9uZSBhZGRpdGlvbjoNCiANCiBUaGUgb3V0cHV0IGJpdCBpcyB4
b3InZCB3aXRoICgobGZzcj4+MTQpJihsZnNyPj4xNSkpDQogDQogTm9ybWFsbHkgdGhpcyBzaG91
bGRuJ3QgYmUgYSBwcm9ibGVtLCBhcyB0aGUgcmVzdWx0IG9mIGEgcmFuZG9tIGJpdCB4b3InZCB3
aXRoDQogYW55IGZ1bmN0aW9uIGJlc2lkZXMgaXRzZWxmIGlzIHNlbGYgaXMgc3RpbGwgYSByYW5k
b20gYml0Lg0KIA0KIEhvd2V2ZXIsICgobGZzcj4+MTQpJihsZnNyPj4xNSkpIGlzIG5vdCBhIG5v
cm1hbCBmdW5jdGlvbi4gRHVlIHRvIHRoZSBMRlNSIGFsc28NCiBiZWluZyBhIHNoaWZ0IHJlZ2lz
dGVyIHRoZSBvdXRwdXQgb2YgdGhlIHJhbmRvbSBiaXQgZnVuY3Rpb24gaXMgYWN0dWFsbHkgdGhp
czoNCiANCiByZXR1cm4gKGxhc3RfYml0JmJpdCleYml0Ow0KIA0KIFNvLCBpZiB0aGUgbGFzdCBi
aXQgd2FzIGEgMSB0aGUgYml0IHJldHVybmVkIGlzIGd1YXJhbnRlZWQgdG8gYmUgMC4NCiANCiBT
byBpdCBpcyBpbXBvc3NpYmxlIHRvIGdldCB0byB0aGUgJ3RpcyBidXQgYSBzY3JhdGNoJyBmdW5j
dGlvbiwgYXMNCiBpdCBpcyBpbXBvc3NpYmxlIGZvciBib3RoIGRvWW91RmVlbEx1Y2t5UHVuayBh
bmQgYWN0dWFsbHlJc0x1Y2t5IHRvIGJlIHRydWUu

*/


We produce such a matrix of any dimension n. It is simply a matrix of all 1's except 2's on the diagonal.

r = range(n)
M = [[1 + (i==j) for i in r] for j in r]

Example:

n=5
M=[[2 1 1 1 1]
   [1 2 1 1 1]
   [1 1 2 1 1]
   [1 1 1 2 1]
   [1 1 1 1 2]]

 #Within 10 steps, the procedure converges to the matrix's square root
  [[ 1.28989795  0.28989795  0.28989795  0.28989795  0.28989795]
   [ 0.28989795  1.28989795  0.28989795  0.28989795  0.28989795]
   [ 0.28989795  0.28989795  1.28989795  0.28989795  0.28989795]
   [ 0.28989795  0.28989795  0.28989795  1.28989795  0.28989795]
   [ 0.28989795  0.28989795  0.28989795  0.28989795  1.28989795]]

In general, the procedure converges for matrices with positive real eigenvalues. This is because if we work in the basis of eigenvectors of the original matrix, it and all its iterates are diagonal matrices, and we can view the procedure as applying the Babylonian method to each individual diagonal entry. The starting matrix is the still the identity in this basis.

Since the Babylonian method converges only if the original value was positive, the matrix version converges when every eigenvalue is real and positive. I'm not sure what happens for complex eigenvalues.

I constructed the given matrix to have positive eigenvalues as follows. First, start with the matrix of all ones, which is rank-1, and so has a single eigenvalue (of n) and all others 0. Then, add the identity, which shifts the eigenvalues up by 1 to get (n+1,1,1,...,1). Iterating makes the eigenvalues converge to (sqrt(n+1),1,1,...,1). Note that the 1's are unchanged by each iteration.


Here's my code, 494 characters in python:

import sys,re
m=sys.stdin.readlines()
Z=lambda c,s:re.findall(r'(\w)%s+(\d*)[^\w]*(\w)'%c,''.join(x*2for x in s))
T=lambda n:''.join(x for a in map(None,*n)for x in a if x)
E=Z('-',''.join(m))+Z('\\|',T(m))+Z('/',T(' '*m.index(s)+s for s in m))+Z('\\\\',T(' '*m[::-1].index(s)+s for s in m))
E+=[x[::-1]for x in E]
S={}
for x in E:S[x[0]]=1e9
S['S']=0
P={}
for i in E:
 for x,w,y in E:
  w=int('1'+w)%10
  if S[y]>S[x]+w:S[y]=S[x]+w;P[y]=x
i=p='T'
while i!='S':i=P[i];p=i+p
print'%d:'%S['T']+p


JavaScript (ES6), 47 bytes

Takes input in currying syntax (n)(p), where n is the number of net upvotes and p is the percentage of upvotes. May return false for 0.

n=>p=>(g=u=>u/(u-n/2)*50+.5^p?g(u+1):u)(n>0&&n)

Try it online!

Commented

n => p => (          // given n and p
  g = u =>           // g = recursive function taking u = number of upvotes
    u / (u - n / 2)  //   compute u / (total_votes / 2)
    * 50 + .5        //   turn it into a percentage, add 1/2
    ^ p ?            //   XOR it with p, which gives 0 if the integer parts are matching
                     //   if the result is not equal to 0:
      g(u + 1)       //     try again with u + 1
    :                //   else:
      u              //     stop recursion and return u
)(n > 0 && n)        // initial call to g() with u = max(0, n)

Edge cases

Let Fn(u) = u / (u - n / 2) * 50 + 0.5

If u = 0 and n = 0, then Fn(u) = NaN and Fn(u) XOR p = p. So, we return u = 0 if n = p = 0 (first iteration of the first test case) or continue with the recursion if p != 0 (first iteration of the 7th test case).
If u > 0 and u = n / 2, then Fn(u) = +Infinity and -- again -- Fn(u) XOR p = p. Unless p = 0, we just go on with the next iteration. (This happens in the 9th and 11th test cases.)


Python 2, 115 114 106 105 94 bytes

Golfing suggestions welcome. Try it online!

Edit: -9 bytes thanks to mbomb007. -2 bytes thanks to FlipTack.

def a(n,f,t,d,z=0,s=''):
 for i in n:z=z*f+d.find(i)
 while z:s=d[z%t]+s;z/=t
 print s or d[0]

Ungolfed:

def arbitrary_base_conversion(num, b_from, b_to, digs, z=0, s=''):
    for i in num:
        z = z * b_from + digs.index(i)
    while z:
        s = digs[z % b_to] + s
        z = z / t
    if s:
        return s
    else:
        return d[0]


C - one operation calculator

Let's have this for a start.
It's actually quite hard to find pieces of C programs that aren't whole programs. I had most trouble with declarations.

// http://stackoverflow.com/a/2911978 Block #1 (changed i to a)
static int a = 10;
// http://stackoverflow.com/a/2911978 Block #1 (changed i to b)
static int b = 10;
// http://stackoverflow.com/a/442647 Block #1 (changed c to op)
unsigned char op = (unsigned char)-1;
// http://stackoverflow.com/q/3711048 Inline block #1
int main()
// http://stackoverflow.com/a/14902422 Inline block #1
{
// http://stackoverflow.com/q/217074 Inline block #2 (changed i to a)
scanf("%d", &a)
// http://stackoverflow.com/a/23353870 Inline block #2
;
// http://stackoverflow.com/q/217074 Block #2 (changed c to op)
scanf("%c", &op)
// http://stackoverflow.com/a/23353870 Inline block #2
;
// http://stackoverflow.com/q/217074 Inline block #2 (changed i to b)
scanf("%d", &b)
// http://stackoverflow.com/a/23353870 Inline block #2
;
// http://stackoverflow.com/a/4173188 Block #2
int result = 0;
result = (op == '*') ? a * b : result;
result = (op == '/') ? a / b : result;
result = (op == '+') ? a + b : result;
result = (op == '-') ? a - b : result;
printf("%d",result);
// http://stackoverflow.com/a/3245525 Block #2
printf("\n");  /* prints newline */
// http://stackoverflow.com/q/4138649 Inline block #1
return 0;
// http://stackoverflow.com/a/14902422 Inline block #2
}

Takes a simple integral operation like 3+151 or 41/2 on stdin and outputs the result to stdout.


Pyth, 36 35 bytes

u%@[t_G/G2yGi_jGJ16JG)x"!><@"H256z0

Test harness

The internal representation of the accumulator is an integer. This integer is mod-ed by 256 on each iteration, as desired. The operations performed are -G-1, G/2, G*2 and G converted to base 16, reversed, and converted back to base 10, where G is the accumulator.

I missed the line about ignoring everything else. This has been remedied. Thanks, @Dennis.


Determine whether rational coordinates are in the right Sierpinski triangle

Python 2, 68

lambda n,d,N,D:1>=n/d>=0<=N/D<=1and(n<<abs(D*d))/d&(N<<abs(D*d))/D<1

A nice way to check for gasket membership made ugly. If we were guaranteed that the inputs are non-negative and in the unit square, we would have 38:

lambda n,d,N,D:(n<<D*d)/d&(N<<D*d)/D<1

The idea is that we check whether a point lies within the gasket by checking whether their binary fraction expansions bitwise-AND to 0. To get the first k character of the expansion, we bit-shift the numerator k bits left before integer-dividing by the denominator. We need to make k sufficiently large to catch a repeat. We note that the binary expansion n/d has period at most d, so the joint expansions have period at most d*D, so k=d*D suffices.

The rest is to check whether the fraction is in the box and insulate against inputs given like -1/-3.


CJam, 51 45 42 38 36 bytes

"c\o/
_0_""^[c_o_
 0
/ \^["{_o\6e4m!}g

The above uses caret notation; the sequence ^[ is actually the ASCII character with code point 27.

I've borrowed the escape sequence (^[c) from @DomHastings' answer (with his permission) to save 4 bytes.

Verification

You can recreate the file like this:

base64 -d > jj.cjam <<< ImNcby8KXzBfIiIbY19vXwogMAovIFwbIntfb1w2ZTRtIX1n

To run the code, download the CJam interpreter and execute this:

java -jar cjam-0.6.5.jar jj.cjam

This will work on any terminal that supports console_codes or an appropriate subset.1

How it works

e# Push both jumping jacks on the stack.

"c\o/
_0_"

"^[c_o_
 0
/ \^["

e# When chained together, they contain two occurrences of the string "\ec",
e# which resets the terminal. Encoding the ESC byte in the second string
e# eliminates the need two escape a backslash before the string terminator.

{         e# Do:
  _o      e#   Copy the jumping jack on top of the stack and print the copy.
  \       e#   Swap the order of the jumping jacks.
  6e4m!   e#   Calculate the factorial of 60,000 and discard the result.
          e#   This takes "about a second".
}g        e# Since the discarded factorial was non-zero, repeat the loop.

1 The jumping jacks will look better if you hide the terminal's cursor before running the program. In Konsole, e.g., you can set the cursor's color to match the background color. This has to be done via your terminal's settings, since ^[c resets the terminal.


The of operator is used to get a property from an object:

log words of "Hello World"

But in many cases you can use 's as a shortcut to save 1 character:

log "Hello World"'s words


Python 3, 154 140 bytes

from winsound import*
for i in input():Beep(int(65.406*2**('1!2"34$5%6^78*9(0qQwWeErtTyYuiIoOpPasSdDfgGhHjJklLzZxcCvVbBnm'.find(i)/12)),999)

I chose the second task type.

The loop passes through each character and looks for the index of this element in the string. This index is the number of semitone up from Low C ('1'). Calculation of the desired frequency is made by this formula.

P.S. This library works only in Windows.

-13 bytes thanks to ovs.

-1 byte thanks to Jonathan Allan.


Python 2, 305
This is the golfed version. It is practically unusable for n > 3, as the time (and space) complexity is like 3n2... actually that may be way too low for the time. Anyway, the function accepts a list of strings.
def f(i):
 Z=range;r=map(__import__('fractions').Fraction,i);R=r[1:];n=len(R);L=[[[1]*n,[0]]];g=0
 for m,p in L:
  for d in([v/3**i%3for i in Z(n)]for v in Z(3**n)):
    try:x=min(m[i]/R[i]/d[i]for i in Z(n)if m[i]*d[i]>0);L+=[[[m[i]-x*R[i]*d[i]for i in Z(n)],[p[0]+x]+p]]
    except:g|=p[0]-r[0]in p
 return g

A slightly optimized version can finish the test cases in a couple of minutes. It might still be slow for an impossible n=5 case though.
def fLessslow(i):
 Z=range
 r=map(__import__('fractions').Fraction,i)
 R=r[1:]
 n=len(R)
 L=[((1,)*n,(0,))]
 ls = set(L)
 for m,p in L:
  if p[0]-r[0]in p: return 1
  for d in([v/3**i%3 for i in Z(n)]for v in Z(3**n)):
   if any(d[i] and m[i]<=0 for i in Z(n)):continue
   try:
    x=min(m[i]/R[i]/d[i]for i in Z(n)if m[i]*d[i]>0)
    thing = (tuple(m[i]-x*R[i]*d[i]for i in Z(n)),(p[0]+x,)+p)
    if thing not in ls:L+=[thing];ls.add(thing)
   except:5
 return 0

print fLessslow('5/1 6/1 1/6 9/1 1/9'.split())
print fLessslow('29/6 3/2 2/3 3/5 3/7 7/5'.split())


Given a fair coin as input, generate any particular unfair outcome

Perl, 37 42 char

($d/=2)+=rand>.5for%!;print$d/2<pop|0

Takes arbitrary probability as a command line argument. Builds a uniform random number in $d and compares it to the input.

Earlier, 52 char solution

$p=<>;do{$p*=2;$p-=($-=$p)}while$--(.5<rand);print$-


Python 3, 62 bytes

f=lambda a:0in(f([x for x in a if{r}-{*x}])for r in sum(a,()))

Try it online!
Python 2, 61 bytes

f=lambda a:0in(f(filter({y}.__sub__,a))for x in a for y in x)

Try it online!
-5 bytes thanks to Unrelated String
-6 bytes thanks to dingledooper
-1 byte if we use Python 2 thanks to dingledooper
-2 bytes thanks to xnor
Outputs True for player 0 winning and False or () for player 1 winning (() is an empty tuple in Python, which is a falsey value in the language)


Shortest method to implement the Pythagorean Theorem

APL (54)

'The hypotenuse of this right triangle is',3⍕.5*⍨+/⎕*2

Test:

      'The hypotenuse of this right triangle is',3⍕.5*⍨+/⎕*2
⎕:
      9 10
The hypotenuse of this right triangle is 13.454

Explanation:

⎕*2: raise the values in the input to the second power
+/: take the sum
.5*⍨: raise the result to the 0.5th power
3⍕: round to 3 decimal places


Japt, 189 bytes

I almost went insane while trying to get this to work properly...

U?S+'_pC +R:"  oo  o oo\n "+'opC +"\no")+"\\, \\,} |, /,/"q', £(V=(!Y«U?"|: |" +SpA +'|+X,(1+5*Mr)o mZ=>Ul <Y*4+4©(V=Vh2+A*Mr ,'° ),V)qR +"\n \\"+'_pA +'/+R+(Ul ¥3?"Yuck, foam.":Ug22 ?`B¨p:

Try it online!

(Note: This program was made for an older version of Japt, and doesn't currently work in the latest version. To get around this, the older version is specified in the URL. Unfortunately, this also means the top-right code box doesn't work.)

This is by far the longest program I have ever written in Japt. Here's a breakdown:

Step 1: Create the top of the beer mug.

U?S+'_pC +R:"  oo  o oo\n "+'opC +"\no")

           // Implicit: U = input string
           // Begin the ASCII art with:
U?S+       //  If U is not an empty string, a space +
'_pC +R:   //   "_".repeat(12) + a newline.
:"..."+    //  Otherwise, this string +
'opC +     //   "o".repeat(12) +
"\no")     //   a newline and an "o".

If U is an empty string, this makes:

  oo  o oo
 oooooooooooo
o

Otherwise, this makes:

 ____________

Step 2: Create the middle rows of the mug.

+"\\, \\,} |, /,/"q', £(V=(!Y«U?"|: |" +SpA +'|+X,

+"..."    // Add to the previous string: this string,
q', £(    // split at commas, with each item X and its index Y mapped to:
V=(       //  Set variable V to the result of concatenating:
!Y«U?     //   If Y is 0 and U is an empty string,
"|: |"    //    "|"; otherwise, " |";
+SpA      //   10 spaces,
'|+X,     //   "|", and X.

This results in the previous string plus:

 |          |\
 |          | \
 |          |} |
 |          | /
 |          |/

Step 3: Add the bubbles.

(1+5*Mr)o mZ=>Ul <Y*4+4©(V=Vh2+A*Mr ,'° ),V)

            // Note: We're still looping through the five rows at this point.
(1+5*Mr)    // Generate a random integer between 1 and 5.
o           // Create an array of this many integers, starting at 0.
mZ=>        // Map each item Z in this range to:
Ul <Y*4+4©  //  If the length of U is less than Y*4+4,
            //  (in other words, if there's less than Y+1 "sip"s)
(V=Vh   '°  //   Insert "°" at position
2+A*Mr      //    2 + random number between 0 and 9.
),V)qR      // Finally, return V, and join the five rows with newlines.

At this point, the mug looks something like this:

 ____________
 |          |\
 |          | \
 |     °    |} |
 |° °     ° | /
 | °    °   |/

Step 4: Add the final row and optional text.

+"\n \\"+'_pA +'/+R+(Ul ¥3?"Yuck, foam.":Ug22 ?`B¨p:

+"\n \\"    // Add a newline and " \".
+'_pA       // Add 10 "_"s.
+'/+R       // Add a slash and a newline.
+(Ul ¥3?    // If the length of U is 3 (i.e. 1 "sip"),
"..."       //  add the string "Yuck, foam.".
:Ug22 ?     // Otherwise, if U has a character at position 22 (six or more "sip"s),
`B¨p        //  decompress this string ("Burp") and add it.
:           // Otherwise, add nothing.

Now everything is ready to be sent to output, which is done automatically. If you have any questions, feel free to ask!


Compute every combination of operations written in a .TXT file


I wrote this program for another challenge, but I decided to try and make it a valid answer for this one too:

Shirred Eggs.

This recipe prints the number 2 and, in doing so, yields two delicious
shirred eggs.

Ingredients.
2 eggs

Cooking time: 12 minutes.

Pre-heat oven to 175 degrees Celsius.

Method.
Put eggs into mixing bowl. Pour contents of the mixing bowl into the
baking dish. Shirr the eggs. Bake the eggs until shirred.

Serves 1.

As I mentioned in the other answer, it seems pretty hard to write anything in Chef that involves something more complicated than mixing stuff in a bowl and baking it, and still have it work both as a program and as a recipe.

Edit: Changed the recipe from fried to shirred eggs — thanks to Blazer for the suggestion!  The cooking time and temperature should be considered advisory only; I haven't actually tried the recipe yet myself, so I can't vouch for their accuracy.


Converting Numbers to a "Not quite place-value system"

Mathematica, 64 bytes

Part[Join@@Array[Tuples@Join[{{1}},Array[Range,#-1,3]-1]&,#],#]&

Unnamed function taking a positive integer argument and returning a list of integers.

Join[{{1}},Array[Range,#-1,3]-1] returns the nested list { {1}, {0,1,2}, {0,1,2,3}, ..., {0,1,...,#} }. Then Tuples returns the (sorted) set of all tuples whose first element lies in {1}, whose second element lies in {0,1,2}, and so on; these are the #-digit numbers in this numbering system. Join@@Array[...,#] returns an array of all the numbers in this numbering system with at most # digits, and Part[...,#] extracts the #th such number.

This is hopelessly slow! It runs fine for the input up to 9. For larger input, test it by replacing the end ,#],#]& with ,Ceiling[0.9Log[#]]],#]&; this puts a more realistic cap on the number of digits necessary to go far enough in the numbering system to find the one we want.


441 characters

OK, here is another approach — this time breaking things down into a giant binary tree of tests. I was hoping this could be done recursively, but the C preprocessor doesn't support recursive functions...so I did this as a fallback.

Algorithm: This tests N for divisibility by 2 and by all odd numbers up to the square root of 2³². (Note: That's a bit of overkill, because it need only test potential divisors up to the square root of 2³¹, but it's easier to stick to powers of 2.)

#define A(x) (N%(x)||N==x)
#define B(x) A(x)&A(x+2)&A(x+4)&A(x+6)
#define C(x) B(x)&B(x+8)&B(x+16)&B(x+24)
#define D(x) C(x)&C(x+32)&C(x+64)&C(x+96)
#define E(x) D(x)&D(x+128)&D(x+256)&D(x+384)
#define F(x) E(x)&E(x+512)&E(x+1024)&E(x+1536)
#define G(x) F(x)&F(x+2048)&F(x+4096)&F(x+6144)
#define H(x) G(x)&G(x+8192)&G(x+16384)&G(x+24576)
#include <stdio.h>
int main(){
#if A(2)&H(3)&H(32771)
printf("Hello world!");
#else
Walkmen;
#endif
}

Notes:

The value 32771 is really just 3+32768.
Yes, the parentheses around x in N%(x) are indeed needed (but not in N==x).
Compiles as per instructions and obeys rules of output.
Elapsed time for each test of N (e.g., each invocation of the compiler) is about 1/6 second on my machine.


An Old Irish Blessing, reasked (without using encodings)

Golfscript, 198 characters
[]"-!9 4(% 2/!$<)3A50H/ -%%4 9/5
XXXN7).X\"?!,7I3>4UU2I!#+
[[[S35.;(`A[2- 50/.]]]&]%
YO2!U3F|,`/&4ZZZZZK)%,$3
!.$ }4),ze-%%Z!'!k\n-!9 '/S(/]hh )o4(%GG,/7 /&A)3;!v"{.32>{.58<{32+}{56-~1$>2<}if}*+}/+

Output:
$ ruby golfscript.rb blessing.gs
MAY THE ROAD RISE UP TO MEET YOU
MAY THE WIND BE ALWAYS AT YOUR BACK
MAY THE SUN SHINE WARM UPON YOUR FACE
THE RAINS FALL SOFT UPON YOUR FIELDS
AND UNTIL WE MEET AGAIN
MAY GOD HOLD YOU IN THE HOLLOW OF HIS HAND

The poem is compressed to 158 characters by using part of the ASCII range for back-references (of fixed length 2). The coding scheme is as follows:
[10]      : newline (unencoded)
[32]      : space (unencoded)
[33..57]  : literal (33=A, 34=B, ... 57=Y, Z not needed)
[58..126] : back-reference relative to the end of the decompressed string so far.

The remaining 40 characters make up the decompression code which can probably be golfed a little further, since this is my first attempt at Golfscript.

Case-sensitive version, 207 characters
Same concept, but trading some of the back-reference range for lower case letters at the cost of some compression.
[]"-AY THE ROAD RISaUPhO MEET YOU
xxxnWINxB_ALWiS^TuuRiACK
{{{sSUN[HINa{RM UPON}}}F}E
4HoRAuS fLL SOFTzzzzzkIELDS
!NDlNTIwWE MEEzAGAIN
-AY 'OsHOLxYOU k THEggLOW OF (ISeAND"{.32>{.90<{32+}{88-~1$>2<}if}*+}/+

Output:
$ ruby golfscript.rb blessing-casesensitive.gs
May the road rise up to meet you
May the wind be always at your back
May the sun shine warm upon your face
The rains fall soft upon your fields
And until we meet again
May God hold you in the hollow of His hand


sed 4.2.2, 20 bytes

-nr options required at the command-line.

s/^[Vv]r(o*)m!$/\1/p

This outputs the speed in unary as the number of os.

Try it online!


Python 2, 53 52 51 bytes
-2 bytes thanks to g.rocket
-1 byte thanks to Jonathan Frech
-1 byte thanks to RootTwo

def F(x):n=sorted(x);print[n.pop(-(e>x))for e in x]

Try it online!
The sorted list will have the numbers first and then the chars like [3, 5, 6, 'a', 'b', 'x'], then use e>x to filter what is number and what is char, in python any number is less than a list (input) and a list is less than a string.


Python, 39 bytes

Takes the inputs:

a list of (x, y) integer coordinates
b list of strings
c single character string

lambda a,b,c:{b[y][x]for x,y in a}=={c}


Print an arch of ascending / descending numbers

Python 2, 65 55 53 51

s=12345678
while s:r='%-8d'%s;print r+r[::-1];s/=10

Shortened using some of ugoren's ideas.


JavaScript (ES6), 57 bytes
Returns false for "mov", true for "movs", 2 for "ldr", 3 for "mvn" or 4 for "movw".

f=(n,r)=>n>>8?~n>>8?r>31?n>>16?2:4:f(n>>>31|n*2,-~r):3:!r

Try it online!
Commented
f = (                       // f is a recursive function taking:
  n,                        //   n = input
  r                         //   r = rotation counter, initially undefined
) =>                        //
  n >> 8 ?                  // if some of the upper 24 bits of n are not 0's:
    ~n >> 8 ?               //   if some of the upper 24 bits of n are not 1's:
      r > 31 ?              //     if the input was rotated 32 times (which means
                            //     that we've tried all possible rotations and we
                            //     are back to the original value):
        n >> 16 ?           //       if some of the upper 16 bits of n are not 0's:
          2                 //         return 2 for "ldr"
        :                   //       else:
          4                 //         return 4 for "movw"
      :                     //     else:
        f(                  //       do a recursive call:
          n >>> 31 | n * 2, //         rotate n by 1 position to the left
          -~r               //         increment r
        )                   //       end of recursive call
    :                       //   else:
      3                     //     return 3 for "mvn"
  :                         // else:
    !r                      //   return true for "movs" if r is zero'ish
                            //   or false for "mov" if r is greater than 0


Pyth 145 97 bytes

=Y.d[,\A,25 25,\B,*TT5,\C,T*5T)Km=G@YdzJm=H@YdwW&KJMX0hG_smedH gKJ gJKI<hhK0=tK)I<hhJ0=tJ;?K1?J2Z

A little less naive than before.

Try it online!

Explanations:

Let's cut the program in several parts.

=Y.d[,\A,25 25,\B,*TT5,\C,T*5T)

     ,\A,25 25                     Create this list: ['A', [25, 25]]
              ,\B,*TT5             Create this list: ['B', [100, 5]]
                      ,\C,T*5T     Create this list: ['C', [10, 50]]
  .d[                         )    From the three lists, create a dictionary whose keys are the letters, and values are the inner lists
=Y                                 Assign to the variable Y

The dictionary Y is: {'A': [25, 25], 'C': [10, 50], 'B': [100, 5]}. Then:

Km=G@YdzJm=H@YdwMX0hG_smedH

 m=G@Ydz                           For all letters in first input string, make a copy of Y[letter]. Make a list of all those values...
K                                  ...and assign the list to the variable K
         m=H@Ydw                   For all letters in second input string, make a copy of Y[letter]. Make a list of all those values...
        J                          ...and assign the list to the variable J
                MX0hG_smedH        Create a function g which takes two lists of couples, and subtract the sum of the second elements of the couples of the second list from the first element of the first couple of the first list

At this point, K is a list of couples that represents the first army. Each couple of this list is a letter of the army, and is (health, damage) for that letter. J is exactly the same, but for the second army. g is a function which takes two armies, and deals the damage made by the second army to the first one. Now:

W&KJ gKJ gJKI<hhK0=tK)I<hhJ0=tJ;

W&KJ                               While K not empty and J not empty
     gKJ                           Call g(K,J). That computes the damages to first army
         gJK                       Call g(J,K). That computes the damages to second army
            I<hhK0=tK)             If the first army's first letter is dead, remove it
                      I<hhJ0=tJ    If the second army's first letter is dead, remove it
                               ;   End of while loop

When the while loop is over, K and J have their final value. If they are both empty, it's a tie; otherwise the non-empty army win. That is handled by the last piece of code:

?K1?J2Z

?K1                                If K non-empty, display 1. Else...
   ?J2                             ...if J non-empty, display 2. Else...
      Z                            ...display zero

That's it!


Python 3 - 168 162 + 230 = 392
Oh, Python, you try so hard, but multiplying the import sys;sys.argv stuff by 4 really hurts!
import sys;a=eval(sys.argv[1])
print("import sys\nfor i in range(1,int(sys.argv[1])+1):print("+"+".join('"%s"*(i%%%d==0)'%t for t in a)+(a and"or str(i))"or"i)"))

Output programs:
import sys
for i in range(1,int(sys.argv[1])+1):print(i)
import sys
for i in range(1,int(sys.argv[1])+1):print("Golf"*(i%1==0)or str(i))
import sys
for i in range(1,int(sys.argv[1])+1):print("Fizz"*(i%3==0)+"Buzz"*(i%5==0)or str(i))

Expected input for the main program is an eval-able sequence of Python tuples or '()' for no input. (You did say "convenient".) Example input: '()', '("Golf",1),', '("Fizz",3),("Buzz",5)' Note quoting for shell and trailing comma for one input.

Fixed 1am mistake by changing from dict (undefined ordering!) to tuples.

Expected input for the other programs is just the number


J, 63 58 53 52 51 47 bytes
_1}.1#.a:~:[:([#~[e.&,(],,)&.>/)^:a:~@;<@(<\)\.

Try it online!
-2 bytes thanks to Bubbler
-3 bytes thanks to FrownyFrog for golfier way to create all substrings of a string.
how
We'll use MOM as our example:

[:...;<@(<\)\. All substrings of the input, boxed.
┌─┬─┬─┬──┬──┬───┐
│M│O│M│MO│OM│MOM│
└─┴─┴─┴──┴──┴───┘

(...)^:a:~ Using the substrings as both the left and right args ~,
apply the verb in parens until a fixed point, keeping track of each iteration's
results ^:a:.

(...(],,)&.>/) To create the next "level" of candidates, create all possible
combinations that look like <level_n><orig substring><level_n> where
level_n is any element from the current level, and <orig substring> is
one of the original input substrings (level 0).  Then the 1st level looks like:
┌─────┬─────┬─────┬───────┬───────┬─────────┐
│MMM  │OMO  │MMM  │MOMMO  │OMMOM  │MOMMMOM  │
├─────┼─────┼─────┼───────┼───────┼─────────┤
│MOM  │OOO  │MOM  │MOOMO  │OMOOM  │MOMOMOM  │
├─────┼─────┼─────┼───────┼───────┼─────────┤
│MMM  │OMO  │MMM  │MOMMO  │OMMOM  │MOMMMOM  │
├─────┼─────┼─────┼───────┼───────┼─────────┤
│MMOM │OMOO │MMOM │MOMOMO │OMMOOM │MOMMOMOM │
├─────┼─────┼─────┼───────┼───────┼─────────┤
│MOMM │OOMO │MOMM │MOOMMO │OMOMOM │MOMOMMOM │
├─────┼─────┼─────┼───────┼───────┼─────────┤
│MMOMM│OMOMO│MMOMM│MOMOMMO│OMMOMOM│MOMMOMMOM│
└─────┴─────┴─────┴───────┴───────┴─────────┘

[#~[e.&,... Check if each original substring is an element of this candidate
list [e.&,, and use that to filter the original substrings [#~.  In the above
example, only MOM passes.

After the above process iterates to its fixed point (no more matches), the result
is:
┌───┬─┬─┬──┬──┬───┐
│M  │O│M│MO│OM│MOM│
├───┼─┼─┼──┼──┼───┤
│MOM│ │ │  │  │   │
├───┼─┼─┼──┼──┼───┤
│   │ │ │  │  │   │
└───┴─┴─┴──┴──┴───┘

a:~: Since we don't want to count empty boxes, we perform an elementwise
test for "not equal to the empty box a:", giving us a 0-1 matrix:
1 1 1 1 1 1
1 0 0 0 0 0
0 0 0 0 0 0

1#. Sum rows:
6 1 0

_1}. And kill the last element:
6 1


Create a program that output's itself as a series of punch cards

Ruby - 925

I'll get the ball rolling. Run as "ruby hammer.rb hammer.rb".

Golfed

def z x
l=x.unpack u='C*'
d=[]
(0..9).each do|i|d<<[].fill(48+i,0,80);end
d<<a=[].fill(32,0,80)
d<<a.dup
h=Hash.new
i=0;' abcdefghi'.unpack(u).each do|c|h[c-32]=[i,11];h[c]=[i,11,0];i+=1;end
i=0;' jklmnopqr'.unpack(u).each do|c|h[c-32]=[i,10];h[c]=[i,10,11];i+=1;end
i=0;'  stuvwxyz'.unpack(u).each do|c|h[c-32]=[i,0];h[c]=[i,0,10];i+=1;end
h[47]=[1,0]
i=0;'0123456789-&'.unpack(u).each do|c|h[c]=[i];i+=1;end
i=0;'  :#@\'="'.unpack(u).each do|c|h[c]=[i,8];i+=1;end
i=0;'  [.<(+|'.unpack(u).each do|c|h[c]=[i,8,11];i+=1;end
i=0;'  ]$*);^'.unpack(u).each do|c|h[c]=[i,8,10];i+=1;end
i=0;'  \,%_>?'.unpack(u).each do|c|h[c]=[i,8,0];i+=1;end
h[32]=[]
i=0;l.slice(0,80).each do|c|h[c].each do|r|d[r][i]=215;end;i+=1;end
puts'    %s'%('_'*81)
puts'   /%-80s |'%l.pack(u)
puts'  / %s |'%d[11].pack(u)
puts' /  %s |'%d[10].pack(u)
(0..9).each do|i|puts'|   %s |'%d[i].pack(u);end
puts'|%s|'%('_'*84)
end
ARGF.each do|l|z l.chop;end

Ungolfed

def punch029(line) # line is array of ASCII characters in ordinal (integer) form
  chad=[]
  (0..9).each do |i| chad<<[].fill(48+i,0,80) end
  chad<<[].fill(32,0,80)
  chad<<[].fill(32,0,80)

  r10 = 10-10
  r11 = 11-1
  r12 = 12-1
  # Reward "bad" input characters with all-row multi-punch.
  # hash = Hash.new( [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] )
  #
  #   OR
  #
  # Reward "bad" input characters by letting Ruby puke. (Jam the machine.)
  hash = Hash.new
  '0123456789-&'.unpack('C*').each_with_index do|c,i| hash[c]=[i] end
  ' ABCDEFGHI'.unpack('C*').each_with_index do|c,i| hash[c]=[i,r12] end
  ' JKLMNOPQR'.unpack('C*').each_with_index do|c,i| hash[c]=[i,r11] end
  ' /STUVWXYZ'.unpack('C*').each_with_index do|c,i| hash[c]=[i,r10] end
  '  :#@\'="'.unpack('C*').each_with_index do|c,i| hash[c]=[i,8] end
  '  [.<(+|'.unpack('C*').each_with_index do|c,i| hash[c]=[i,8,r12] end
  '  ]$*);^'.unpack('C*').each_with_index do|c,i| hash[c]=[i,8,r11] end
  '  \,%_>?'.unpack('C*').each_with_index do|c,i| hash[c]=[i,8,r10] end
  ' abcdefghi'.unpack('C*').each_with_index do|c,i| hash[c]=[i,r12,r10] end
  ' jklmnopqr'.unpack('C*').each_with_index do|c,i| hash[c]=[i,r11,r12] end
  '  stuvwxyz'.unpack('C*').each_with_index do|c,i| hash[c]=[i,r10,r11] end
  hash[32] = []              # fix space

  hole = 215
  line.slice(0,80).each_with_index do |c, index|
    hash[c].each do |row| chad[row][index] = hole end
  end

  puts '    %s' % ('_'*81)
  puts '   /%-80s |' % line.pack('C*')
  puts '  / %s |' % chad[11].pack('C*')
  puts ' /  %s |' % chad[10].pack('C*')
  (0..9).each do |i|
    puts '|   %s |' % chad[i].pack('C*')
  end
  puts "|%s|" % ('_'*84)
end
#        1         2         3         4         5         6         7         8
#2345678901234567890123456789012345678901234567890123456789012345678901234567890

ARGF.each do |line|
  punch029(line.chomp.unpack('C*'))
end


Stack a random number of cups into a perfect two dimensional pyramid (triangle)

Haskell, 64 68

This works out the base directly by inverting the triangular number formula, t = (b^2+b)/2, and calculating b = (sqrt(8*t+1) - 1) / 2.

f n=init.tail$show(b,div(b^2+b)2)where b=floor$(sqrt(8*n+1)-1)/2

And rather than constructing the string-based answer as show b++","++show t, it simply chops the brackets off the shown tuple.

Edit: calculating the new triangular number in place instead of declaring a new variable, t, saves 4 characters.


One-to-one correspondence between pairs of integers and the positive integers

MATL, 43 36 bytes
This uses the spiral (1YL) function, which generates a square 2D array of given size with values arranged in an outward spiral. For example, with input 7 it produces
43 44 45 46 47 48 49
42 21 22 23 24 25 26
41 20  7  8  9 10 27
40 19  6  1  2 11 28
39 18  5  4  3 12 29
38 17 16 15 14 13 30
37 36 35 34 33 32 31

The center of the array, which contains 1,  corresponds to the tuple [0 0]. The upper left corner corresponds to [-3 -3] etc. So for example f (-3,-3) will be 43 and g (43) will be [-3 -3].
The code generates a 2D array with this spiral matrix, as large as needed to do the conversion. Note that larger sizes always give the same result for the entries already included in smaller sizes.
From Z2 to N (18 bytes):
|X>tEQ1YLGb+QZ}3$)

Try it online!
|X>   % input is a 2-tuple. Take maximum of absolute values
tEQ   % duplicate. Multiply by 2 and increase by 1. This gives necessary size of spiral
1YL   % generate spiral
G     % push input 2-tuple again
b+Q   % bubble up, add, increase by 1. This makes the center correspont to [0 0]
Z}    % split tuple into its values
3$)   % use those two value as indices into the spiral array to obtain result

From N to Z2 (25 18 bytes)
Eqt1YLG=2#fhw2/k-q

Try it online!
Eq      % input is a number. Multiply by 2, add 1. This assures size is enough and odd
t1YL    % duplicate. Generate spiral of that size
G=      % compare each entry with the input value
2#fh    % 2-tuple of row and column indices of matching entry
w2/k-q  % swap. Offset values so that center corresponds to [0 0]

Snippet for checking
Note that G needs to be modified to accomodate the fact that we have don't have a single input. The code is slow, so the link checks tuples with values from -9 to 9 only. For -99 to 99 just replace the first line.
The code tests each tuple with values in the defined range. It does the conversion to a number, then from that number back to a tuple, and then checks if the original and recovered tuple are equal. The results should all be 1, indicating that all comparisons give true.
It takes a while to run.
Try it online!
-9:9                     % Or use -99:99. But it takes long
HZ^!"@                   % Cartesian power: gives tuples [-9 -9] ... [9 9].
                         % For each such tuple
|X>tEQ1YL@b+QZ}3$)       % Code from Z^2 to N with `G` replaced by `@` (current tuple)
XJ                       % Copy result into clipboard J
Eqt1YLJ=2#fhw2/k-q       % Code from N to Z^2 with `G` replaced by `J`
@!X=                     % Compare original tuple with recovered tuple: are they equal?


determine longest group of consecutive numbers

APL, 26 21 characters

1+⌈/+/^\9 9⍴0,1=-2-/⎕

Here's the 26-character solution:

i←⎕⋄⌈/{1++/^\⍵↓1=-2-/i}¨⍳9

I used Dyalog APL as my interpreter, and ⎕IO should be set to 0 for the 26-character version.

Example:

      1+⌈/+/^\9 9⍴0,1=-2-/⎕
⎕:
      6 7 51 51 53 51 54 55 56 55
3

This answer explains most of what I in the 26-character solution, but I might have to write a new one up for the 21-character version.


88 Cities, 341 seconds runtime on NEOS

In a recent paper we constructed a family of hard to solve euclidean TSP instances. You can download the instances from this family as well as code for generating them here:

http://www.or.uni-bonn.de/%7Ehougardy/HardTSPInstances.html

The 88 city instance from this family takes Concorde on the NEOS server more than 5 minutes. The 178-city instance from this family takes already more than a day to solve.


Ruby, score 240 238 234 = 249 - 10 - 5
s=->t,r,c{c>0?(t+t.reverse).gsub(/[A-O]{2}[a-o]/){|j|s[t.tr(j,j.swapcase),r+"Peg #{j[0].ord-64} jumps Peg #{j[1].ord-64} to Hole #{j[2].ord-96}.\n",c-1]}:$><<r+"\n"}
s["aBD,BDG,DGK,CEH,EHL,FIM,aCF,CFJ,FJO,BEI,EIN,DHM,DEF,GHI,HIJ,KLM,LMN,MNO,","",13]

A plain ruby implementation which prints all possible solutions to this puzzle (takes less than a minute on my computer). The first lines of output can be seen here:
Peg 6 jumps Peg 3 to Hole 1.
Peg 4 jumps Peg 5 to Hole 6.
Peg 1 jumps Peg 2 to Hole 4.
Peg 14 jumps Peg 9 to Hole 5.
Peg 7 jumps Peg 8 to Hole 9.
Peg 12 jumps Peg 13 to Hole 14.
Peg 10 jumps Peg 6 to Hole 3.
Peg 4 jumps Peg 5 to Hole 6.
Peg 3 jumps Peg 6 to Hole 10.
Peg 15 jumps Peg 10 to Hole 6.
Peg 6 jumps Peg 9 to Hole 13.
Peg 14 jumps Peg 13 to Hole 12.
Peg 11 jumps Peg 12 to Hole 13.

Peg 6 jumps Peg 3 to Hole 1.
Peg 4 jumps Peg 5 to Hole 6.
Peg 1 jumps Peg 2 to Hole 4.
Peg 14 jumps Peg 9 to Hole 5.
Peg 7 jumps Peg 8 to Hole 9.
...

And the online example can be found here.


Haskell, 130 128 bytes

a n=or[f x&&f(n-x)|x<-[2..n],2*x<n]
f m=or[and[p(x+y)/=(y<m)|y<-[2..m]]|x<-scanl1(*)$filter p[2..m]]
p n=all((>0).mod n)[2..n-1]

Try it online!
This solution is based on the following observation.
Fact. An integer \$m>1\$ is Fortunate if and only if, for some prime number \$p_n<m\$, \$m\$ is the smallest integer \$>1\$ such that
\$
p_1 p_2\cdots p_n+m
\$
is prime.
Proof. The claim follows easily from the fact that if \$p_n\ge m\$ then there is some \$p_i\$ with \$i\le n\$ such that \$p_i\mid m\$, and therefore \$p_i\mid p_1 p_2\cdots p_n+m\$.
At this point, checking if a number \$m\$ is Fortunate is trivial: we just have to check the condition for all the prime numbers up to \$m\$.
Explanation of the code
p n=all((>0).mod n)[2..n-1]

The standard prime-checking function. Only works for n>1, but that's ok.

f m=or[and[p(x+y)/=(y<m)|y<-[2..m]]|x<-scanl1(*)$filter p[2..m]]

A function to check whether a number m is Fortunate. As explained above, it calculates the primorials \$\texttt{x}=p_1p_2\cdots p_n\$ until \$p_n\le\texttt{m}\$ and tests whether m is the smallest integer \$\texttt{y}>1\$ such that \$\texttt{x}+\texttt{y}\$ is prime.

a n=or[f x&&f(n-x)|x<-[2..n],2*x<n]

The final function, to check whether n is a Fortunate sum. Pretty straightforward, the only thing to be careful of is that x and n-x must be different: this is the reason why we only iterate over values of x such that 2*x<n.


Determine if an integer is divisible by 3

C - 2 tokens

int div3(int x) {
    return x * 0xAAAAAAAB <= x;
}

Seems to work up to 231-1.

Credits to zalgo("nhahtdh") for the multiplicative inverse idea.


Empty a Swimming Pool . . . With Only a Red Solo Cup

JavaScript ES6, 100 78 82 81 74 bytes

Thanks to @UndefinedFunction for helping golf off 4 bytes

(a,z,d,f=([a,g,k,p])=>g*k*(a[6]?p/-~!a[8]:3.14*g))=>Math.ceil(f(a)/f(z))*d

Usage:

t(["triangle",10,12.25,3],["circle",5,2.2],5);


Dyalog APL, 8 bytes

×/¨1<⊂|⍳

This monadic function train takes height and width as right arguments and returns a 2D array of 0's (border) and 1's (interior). Test it on TryAPL.

How it works

×/¨1<⊂|⍳  Right argument: h w

       ⍳  Generate all index pairs (1-based) of a h×w array.
     ⊂    Enclose (h w), so it depth matches the one of the index array.
      |   For each pair (i j) compute the remainders of the division by (h w).
   1<     Compare all remainders with 1.
×/¨       Reduce each pair of Booleans by multiplication.


Python 2, 69 48 46 44 bytes

print"start\n\n"*19+(27*"A right\n"+"\n")*99

See it in action on youtube!

Automatically found with (a modified version of) this hacky script:

start = 18
oncycle = 21
offcycle = 4

while true do
    emu.poweron()
    -- emu.speedmode("maximum")

    starting = 0
    i = 0
    frames = 0
    last_mario_x = -1

    emu.message(start .. " " .. oncycle .. " ".. offcycle)

    state = 0
    while state ~= 6 and state ~= 11 and frames < 4000 do
        if frames > 500 and frames % 100 == 0 then
            mario_x = memory.readbyte(0x6D) * 0x100 + memory.readbyte(0x86)
            if mario_x == last_mario_x then emu.message("stuck " .. mario_x .. " " .. last_mario_x); break end
            last_mario_x = mario_x
        end

        if starting < start then
            joypad.set(1, {start=1})
            emu.frameadvance(); frames = frames + 1;
            joypad.set(1, {})
            emu.frameadvance(); frames = frames + 1;
            starting = starting + 1
        else
            if i < oncycle then
                joypad.set(1, {A=1, B=1, right=1})
                i = i + 1
            else
                joypad.set(1, {})
                i = i +  1
                if i == oncycle + offcycle then
                    i = 0
                end
            end

            emu.frameadvance()
            frames = frames + 1
        end

        state = memory.readbyte(0x000E)
        if state == 4 then
            emu.message("success!")
            os.exit()
            break
        end

    end

    if start < 30 then
        start = start + 1
    elseif offcycle < 10 then
        start = 18
        offcycle = offcycle + 1
    else
        offcycle = 1
        oncycle = oncycle + 1
    end
end


Bash shell, 16 characters

tr A-Za-z a-zA-Z

Sample runs:

llama@llama:~$ tr A-Za-z a-zA-Z
ThIs is a TeSt!
tHiS IS A tEsT!
llama@llama:~$ echo 'Programming Puzzles & Code Golf Stack Exchange' | tr A-Za-z a-zA-Z
pROGRAMMING pUZZLES & cODE gOLF sTACK eXCHANGE

It works in a file, too (of course):

llama@llama:~$ echo 'tr A-Za-z a-zA-Z' > swapcase.sh
llama@llama:~$ echo 'This is a test!' | bash swapcase.sh
tHIS IS A TEST!


67 bytes
In C there's no real alternative to trial division, but it can certainly be golfed a bit.
for(int p=1,d;p++<999;d&&printf("%d\n",p))for(d=p;--d>1;)d=p%d?d:1;

Requires C99 initial declarations, which saves 1 byte.


Generate the k-ary necklaces of length n

Jelly, 8 bytes

ṗṙJṂȯƲ€Q

A dyadic Link accepting the alphabet size, k, on the left and the necklace length, n, on the right which yields a list of the necklaces using the positive integers up to k as the alphabet.

Try it online!

How?

ṗṙJṂȯƲ€Q - Link: integer k, integer n
ṗ        - Cartesian power of [1,2,...,k] with n
         -   i.e. all n-length lists using alphabet [1,2,...,k]
     Ʋ€  - last four links as a monad for €ach list, L:
  J      -   range of length - i.e. [1,2,...,n]
 ṙ       -   rotate left by each of those values - i.e. get all rotations
   Ṃ     -   minimum
    ȯ    -   logical OR with L (since the minimum of an empty list is 0 not [])
      Q  - unique values the resulting list


05AB1E, 130 133 144 148 150 151 155 156 157 159 programs
Uses the custom  05AB1E encoding for all programs.
All programs are a TIO-link to verify them.
Either type of input is fine:
1) (empty program): Implicit input is output implicitly
2,3)   (a space), \n (a newline): The whitespaces are ignored; implicit input is output implicitly  (with trailing newline)
4) w: Unbound no-op; implicit input is output implicitly (with trailing newline)
5) I: Explicit input is output implicitly (with trailing newline)
6) ¹: Explicit first input is output implicitly (with trailing newline)
7) $: Push 1 and the input, after which the top input is output implicitly (with trailing newline)
8) Î: Push 0 and the input, after which the top input is output implicitly (with trailing newline)
9) ,: Implicit input is output explicitly with trailing newline
10) =: Implicit input is output explicitly with trailing newline (without popping)
11) ?: Implicit input is output explicitly without trailing newline
12) q: Exit program; implicit input is output implicitly (with trailing newline)
13,14) D, Ð: Duplicate / triplicate the implicit input and output the top implicitly (with trailing newline)
15) r: Reverse the values on the stack (which is empty); implicit input is output implicitly (with trailing newline)
16,17) s, Š: Swap / triple swap two / three implicit inputs; the top is output implicitly (with trailing newline)
18) Δ: Loop until the result no longer changes; the implicit input is used, it loops twice, and the unmodified input is output implicitly (with trailing newline)
19) :: Replace the implicit input-string with the implicit input-string, after which the unmodified input is output implicitly (with trailing newline)
20,21,22,23) J, », O, P: Join the empty stack without delimiter / join the empty stack with newline delimiter / sum the empty stack / take the product of the empty stack, after which the implicit input is output implicitly (with trailing newline)
24,25) U, V: Pop the implicit input, and store it in variable X or Y respectively, after which the implicit input is output implicitly (with trailing newline)
26) ©: Store the implicit input in variable ® (without popping), after which it is output implicitly (with trailing newline)
27) ˆ: Pop the implicit input, and add it to the global array, after which the implicit input is output implicitly (with trailing newline)
28) i: If-statement, if the (implicit) input is 1 it enters it. But whether the input is 1 and it enters the if-statement or not, the implicit input is output implicitly (with trailing newline) either way
29) v: For-each over each character/digit of the implicit input (but don't push any, since we don't use y). After the loop, the implicit input is output implicitly (with trailing newline)
30,31) }, ]: Close the inner-most or all if-statement(s)/loop(s), for which there are none right now. The implicit input is output implicitly (with trailing newline)
32) †: Filter the implicit input to the front of the implicit input; it will remain unmodified and is output implicitly (with trailing newline)
33) ‡: Transliterate the characters of the implicit input to the characters of the implicit input; it will remain unmodified and is output implicitly (with trailing newline)
34) ´: Clear the global array (which is already empty). After which the implicit input is output implicitly (with trailing newline)
35) §: Cast the implicit input to a string, after which it is output implicitly (with trailing newline)
36) Ã: Keep all values of the implicit input in the implicit input, after which the unmodified result is output implicitly (with trailing newline)
37) é: Sort the implicit input by length. Since it's a single string/integer, the characters/digits will remain at the same position, after which the unmodified input is output implicitly (with trailing newline)
38,39) ., Å, ž: All three are used to open up more 2-byte operations, but on their own they're unbound no-ops. So the implicit input is output implicitly (with trailing newline).
40) \: Discard the top item on the stack (which is already empty), after which the implicit input is output implicitly (with trailing newline)
41) ¼: Increase the counter_variable by 1. After which the implicit input is output implicitly (with trailing newline)
42) ½: If the implicit input is 1, increase the counter_variable by 1. After which the implicit input is output implicitly (with trailing newline)
43) ë: Else-statement, which is a no-op without if-statement. So the implicit input is output implicitly (with trailing newline)
44) ÿ: Used for string interpolation; outside of a string it's a no-op. So the implicit input is output implicitly (with trailing newline)
45) šн: Convert the implicit input implicitly to a character-list, and prepend the implicit input at the front. Then pop and push the first item of this list, which is output implicitly (with trailing newline).
46) ªθ: Convert the implicit input implicitly to a character-list, and append the implicit input at the end. Then pop and push the last item of this list, which is output implicitly (with trailing newline).
47) η¤: Get all prefixed of the implicit input. Push its last item (without popping), after which the top of the stack is output implicitly (with trailing newline).
48) ðý: Join the empty stack with space delimiter, after which the implicit input is output implicitly (with trailing newline).
49) õK: Remove all empty strings from the implicit input, after which the unmodified result is output implicitly (with trailing newline).
50) ¸` : Wrap the implicit input into a list, and then pop and dump the contents of that list to the stack, after which it is output implicitly (with trailing newline)
51) ʒX: Start a filter, and push variable X, which is 1 (truthy) by default. So all characters/digits in the implicit input will remain, and the unmodified input is output implicitly (with trailing newline)
52) RR: Reverse the implicit input, and reverse it back. After which the unmodified input is output implicitly (with trailing newline).
53) ÂÂ: Bifurcate (short for Duplicate & Reverse copy) twice, after which the unmodified input at the top of the stack is output implicitly (with trailing newline)
54) ÁÀ: Rotate the implicit input once towards the right, and then back towards the left. After which the unmodified input is output implicitly (with trailing newline).
55) Ć¨: Enclose the implicit input, appending its own first character/digit, and then remove the last character/digit again. After which the unmodified input is output implicitly (with trailing newline).
56) Σ9: Sort the characters/digits in the implicit input by 9 (so they'll all stay at the same positions), after which the unmodified input is output implicitly (with trailing newline).
57) 8ì¦: Prepend an 8 in front of the implicit input, and then remove the first character again. After which the unmodified input is output implicitly (with trailing newline)
58) āĀÏ: Push a list in the range [1, implicit input-length] (without popping). Python-style truthify each value in this list (so they'll all becomes 1s). Only keep the characters/digits of the implicit input at the truthy (1) indices, after which the unmodified result is output implicitly (with trailing newline).
59) ""«: Append an empty string to the implicit input, after which the unmodified input is output implicitly (with trailing newline).
60,61) ‘‘Û, ’’Ü: Trim all leading / trailing empty strings of the implicit input, after which the unmodified input is output implicitly (with trailing newline).
62) ““¡: Split the implicit input on an empty string, after which the unmodified input is output implicitly (with trailing newline).
63) ₆¢: Count the amount of 36 in the implicit input. Not sure why, but when using a multi-character value with the count, there seems to be a bug and it results in the unmodified string, instead of the actual amount of 36 substrings in the string I was expecting.. So this will output the unmodified input implicitly (with trailing newline).
Only string input:
64 through 125) ǝαβив!%&(*+-/÷;<>BLbcefhjmnoptxz~‰£°±·¿ÃÆÈÉÌÍÑÒÓÕÖ×ØÝãäçèîôöùú: All these are integer operations (see the Wiki-page linked in the title to see what each does). They are no-ops for the (implicit) input-string(s); after which the unmodified input at the top of the stack is output implicitly.
126) ∍: Extend/shorten the implicit input-string to a size equal to the implicit input-string, after which it is output implicitly (with trailing newline).
127) δ: Apply double-vectorized. For integer inputs, it will implicitly convert to a \$[1, a]\$ range before applying double-vectorized. For strings, the implicit input is output implicitly.
128) Λ: Apply the Canvas with three options. For the digits 0 through 7, it will output the digit in a certain direction and length, depending on the input. For any other input, it will be a no-op outputting the implicit input implicitly (with trailing newline).
129) –: If the top of the stack is 1, it will print index N. So this will output 0 for input 1, but will output the implicit input itself implicitly (with trailing newline) for any other input.
130) —: If the top of the stack is 1, it will print item y. So this will output an empty string for input 1, but will output the implicit input itself implicitly (with trailing newline) for any other input.
131) œW: Get all permutations of the implicit input-string. Then push the minimum (without popping), which for string inputs will simply use the very first string. Then output this unmodified input at the top of the stack implicitly (with trailing newline).
Only string input, and the output is a character-list:
132) S: Convert the implicit input to a list of characters and output it implicitly (with trailing newline).
133,134) ε, €: Map over each character in the implicit input, and output the resulting character-list implicitly (with trailing newline).
135) gι: Push the length of the implicit input. Uninterleave the implicit input using this length as block-size. After which the resulting character-list is output implicitly (with trailing newline).
136) øøø¬: Zip/transpose three times; swapping rows/columns. If it's a matrix, it will do as expected. If it's a string or list, it will use the implicit input as a pair-and-zip/tranpose. Since we're doing it three times, the following will happen: "abc" → ["aa","bb","cc"] → [["a","aa"],["b","bb"],["c","cc"]] → [["a","b","c"], ["aa","bb","cc"]]. Then we'll push the first inner list (without popping), after which this list at the top of the stack is output implicitly (with trailing newline).
137) ü1: ü is the overlapping builtin. It can be used with any other builtin to execute that builtin on every overlapping pair. But it can also be used with a single digit to create overlapping pair (2), triplets (3), quartets (4), etc. Apparently it also works with 1 to just convert the (implicit) input-string into a character-list, which is output implicitly (with trailing newline).
Only character-list input:
138) í: Reverse each character in the implicit input-list, after which the unmodified input-list is output implicitly (with trailing newline).
139) ˜: Flatten the implicit input-list, after which the unmodified input-list is output implicitly (with trailing newline).
140) ζζΩ: Zip/transpose the (implicit) input-list twice: ["a","b","c"] → [["a","a"],["b","b"],["c","c"]] → [["a","b","c"],["a","b","c"]]. And then pop and push a random item of this list of lists, which are both the unmodified input-list. After which it will be output implicitly (with trailing newline).
Only integer input:
141,142,143,144) E, F, G, ƒ: Start a ranged loop with the implicit input (E = \$[1, a]\$; F = \$[0, a)\$; G = \$[1, a)\$; ƒ = \$[0, a]\$), and output the implicit input implicitly (with trailing newline) afterwards.
145) ï: Convert the implicit input to an integer, after which the unmodified input is output implicitly (with trailing newline).
146) ò: Round to the nearest integer (which it already is), after which the unmodified input is output implicitly (with trailing newline).
147) þ: Only keep the digits of the implicit input-integer, after which the unmodified input is output implicitly (with trailing newline).
148) #: Split the implicit input-integer by spaces (it has none), after which the unmodified input is output implicitly (with trailing newline).
149,150,151) u, l, ™: Convert the implicit input-integer to uppercase / lowercase / titlecase, after which the unmodified input is output implicitly (with trailing newline).
152) ¶м: Remove all newline characters of the implicit input-integer, after which the unmodified input is output implicitly (with trailing newline).
153) ‚ß: Pair the implicit input-integer with the implicit input-integer, and then pop and push its minimum. After which it is output implicitly (with trailing newline).
154) AÚ: Trim leading and trailing lowercase alphabets of the implicit input-integer, after which the unmodified input is output implicitly (with trailing newline).
155) |M: Push all inputs as list. Push the largest value on the stack (including in all inner lists/matrices). After which the top of the stack is output implicitly (with trailing newline).
156) ∞@0k: Push an infinite positive list [1,2,3,...]. Check for each value if the (implicit) input is larger than or equal to this value (1 if truthy; 0 if falsey). And then get the 0-based index of the first 0 in this infinite list. After which it is output implicitly (with trailing newline).
157) µ¾Ê: Continue looping until the counter_variable (default 0) is equal to the implicit input-integer. Push the counter_variable each iteration, and check that it's NOT equal to the implicit input-integer. If this is truthy, the counter_variable will implicitly be increased by 1 after every iteration. When it becomes falsey, it means it's equal to the input-integer, and thus the loops stops, after which the counter_variable is output implicitly (with trailing newline) as result.
158) Œà: Push all substrings of the implicit input-integer, and then pop and push its maximum. After which this top of the stack is output implicitly (with trailing newline).
159) Z)Z: Get the largest digit of the implicit input-integer (without popping). Then wrap all values on the stack into a list, which is the input itself and its max digit. And then get the maximum again of this integer-pair (without popping), which will be the input itself. Then output the input at the top of the stack implicitly (with trailing newline).
Unused characters / builtins:
I'm pretty sure nothing useful is left anymore now..
Integer constants: 234567Tт₁₂₃₄₅Y®N•
Empty list constant: ¯
Empty string constant (if used twice): ”
(Partially) uniquify / sort builtins: Ù{êÔγ
Convert from binary/hexadecimal to integer (which works on any input unfortunately): CH
Checks resulting in truthy/falsey (0/1): Θ≠Qad›‹Ëå
Recursive environment (which I can't close without `}` nor `]`): λ
Infinite loop (which I can't stop without `#` nor `q`): [
(Compressed) string/integer builtins, which result in errors on their own: '„…ƵŽ
Ord (convert to codepoint integers): Ç
Convert to a list and cycle infinitely: Þ
Only leave the letters (which won't work if the input contains anything else): á
Get the second or third input (we are only allowed to take a single input): ²³
Palindrome / mirror: ûº
Cartesian product: â


Husk, 16 bytes

¤/#ωȯ↑⁰J¹`C∞²N¹²

Try it online!

Takes inputs in the same order as the test cases.
Outputs a rational number.
I feel like this has too many superscripts, but I don't know how to get rid of them...

Explanation

¤/#ωȯ↑⁰J¹`C∞²N¹²  Inputs are n, k, i.
             N    Starting with the natural numbers [1,2,3..
   ωȯ             do this until a fixed point is reached:
                    Argument is a list s.
           ∞²       Take the infinite list [n,n,n..
         `C         and split it to the lengths in s.
       J¹           Join the resulting blocks with k.
     ↑⁰             Take the first i elements.
                  Call the result x.
¤             ¹²  For each of n and k,
  #               count their number of occurrences in x
 /                and perform exact division on the results.


Pyth, 8 bytes

.AxM.PQ2

Test suite

Take all 2 element permutations of the input, map each to the index of one string in the other (0 for a prefix) and return whether all results are truthy (non-zero).


JavaScript (ES6), 37 - 10% = 33.3 bytes

Saved 4 bytes thanks to @edc65

Saved 5.6 bytes thanks to @Mateon

s=>!/^\d|\W|^$/.test(s)/-~(s[0]=='_')


JavaScript (ES6), 208 197 bytes

s=>((q=x=>x.map((_,i)=>(a=[...x.slice(0,i*=2),p="("+x[i]+x[++i]+x[++i]+")",...x.slice(i+1)],x[i]?a[1]?q(a):r.push(p):0)))([...s.replace(/ /g,o="")],r=[]),r.map((l,i)=>r.indexOf(l)(                                  // s = input string
  (q=x=>                              // q = parenthesise array function
    x.map((_,i)=>(
      a=[                             // a = p with parenthesised pair of terms
        ...x.slice(0,i*=2),
        p="("+x[i]+x[++i]+x[++i]+")", // parenthesise and join 2 terms and an operator
        ...x.slice(i+1)
      ],
      x[i]?a[1]                       // make sure the loop is not over
        ?q(a)                         // check next level of permutations
        :r.push(p)                    // add the permutation to the results
      :0
    ))
  )([...s.replace(/ /g,               // remove spaces and parenthesise all expressions
    o="")],                           // o = output string
    r=[]),                            // r = array of result strings
  r.map(                              // filter out duplicates
    (l,i)=>r.indexOf(l)<i?0:o+=l+`
`
  ),o)                                // return o

Test

Input = <input type="text" id="input" value="a * b|c|d" /><button onclick='results.innerHTML=(

s=>((q=x=>x.map((_,i)=>(a=[...x.slice(0,i*=2),p="("+x[i]+x[++i]+x[++i]+")",...x.slice(i+1)],x[i]?a[1]?q(a):r.push(p):0)))([...s.replace(/ /g,o="")],r=[]),r.map((l,i)=>r.indexOf(l)Go</button>


Python 2, 48 bytes

lambda x:reduce(lambda a,b:set(a)&set(b)and b,x)

Try it online!

Print a empty set for False and the last element for True


Python, 88 87 bytes

lambda n:[a for a in range(11*n)if any(a%b<1for b in range(2,a))][:3*n:3]#1,,,=====bd++
lambda n:[[a*b for b in range(1,n+1)]for a in range(1,n+1)]#,,::ybaaa(*i%n< =====2)d33f
f=lambda n,a=1,b=1:a<n and f(n,b,a+b)or n==a#2eerrrfo::((**iii11[[aannn+     ]]y))%33gg
f=lambda n,a=1:a<=n and a**a+f(n,a+1)#::ooeeiii]]      y))bbbgg,,rrrra((11[[nnnnf==2%33

Didn't put too much effort into sharing characters or the golfs themselves, this will almost surely be beat.


Jelly, 21 bytes

“ṣȤW¶¬þḷẒ⁶4ẹ’Œ?ịṢØA;"

Input and output are string arrays.

Try it online!

Background

While there are 26! = 403291461126605635584000000 different inputs, we can sort the input so we have to deal only with one permutation of this phonetic alphabet. Sorting lexicographically, we get

-ray
ango
ankee
apa
cho
elta
harlie
hiskey
ictor
ierra
ike
ilo
ima
lfa
ndia
niform
olf
omeo
otel
ovember
oxtrot
ravo
scar
uebec
uliett
ulu

We can simply index into this array to sort it by the removed letters. The (1-based) indices are

14 22  7  6  5 21 17 19 15 25 12 13 11 20 23  4 24 18 10  2 16  9  8  1  3 26

All that's left to do is to prepend the uppercase letters of the alphabet to the strings in the result.

How it works

“ṣȤW¶¬þḷẒ⁶4ẹ’Œ?ịṢØA;"  Main link. Argument: A (string array)

“ṣȤW¶¬þḷẒ⁶4ẹ’          Replace the characters by their indices in Jelly's code page
                       and convert the result from bijective base 250 to integer.
                       This yields k := 214215675539094608445950965.
             Œ?        Construct the k-th permutation (sorted lexicographically)
                       of [1, ..., n], with minimal n (26 here). This yields
                       [14, 22,  7,  6,  5, 21, 17, 19, 15, 25, 12, 13, 11,
                        20, 23,  4, 24, 18, 10,  2, 16,  9,  8,  1,  3, 26].
                Ṣ      Yield A, sorted.
               ị       For each j in the array to the left, select the j-th string
                       from the array to the right.
                 ØA    Yield "ABCDEFGHIJKLMNOPQRSTUVWXYZ".
                   ;"  Concatenate zipwith; prepend the j-th character from the
                       alphabet to the j-th string of the permuted input.


HTML + JavaScript, 210 bytes

<script>[d,b]=location.search.match(/[\d]([\d]*)?/g);1/b/d&&document.write([i=b^d][i--&i]+'<!-'+'-')</script></script>0<script>[d,b]=location.search.match(/\d+/g);document.body.innerHTML=[i=b^d][i&i-1]</script>

Open page with search parameters index.html?a=1&b=2.

Validation (Python + Selenium + Firefox)

# -*- coding: utf-8 -*-
from selenium import webdriver
import os
source = "<script>[d,b]=location.search.match(/[\d]([\d]*)?/g);1/b/d&&document.write([i=b^d][i--&i]+'<!-'+'-')</script></script>0<script>[d,b]=location.search.match(/\d+/g);document.body.innerHTML=[i=b^d][i&i-1]</script>"
filename = os.path.abspath("temp1.html")

browser = webdriver.Firefox()

def test(html, input_values, expected):
    with open(filename, "w", encoding="latin-1") as html_file:
        html_file.write(html)
    [a, b] = input_values
    browser.get("file:///" + filename + "?a=" + str(a) + "&b=" + str(b))
    text = browser.find_element_by_tag_name("body").text
    if text == "true" and expected == True: return True
    if text == "false" and expected == False: return True
    if text == "undefined" and expected == False: return True
    try:
        if int(text) != 0 and expected == True: return True
        if int(text) == 0 and expected == False: return True
    except: pass
    print(html, input_values, expected, text)

testcases = [
    [[1, 1], False],
    [[1, 2], False],
    [[1, 3], True],
]

fullTestcases = [
    [[0, 1], True],
    [[1, 0], True],
    [[152, 24], True],
    [[10, 10], False],
    [[10, 11], True],
    [[11, 12], False],
    [[255, 0], False],
]

def runAllTestcases(html, testcases):
    for testcase in testcases:
        test(html, *testcase)

runAllTestcases(source, fullTestcases)

for pos in range(len(source)):
    for flip in range(8):
        flip_char = chr(ord(source[pos]) ^ (2 ** flip))
        flip_source = source[0:pos] + flip_char + source[pos+1:]
        runAllTestcases(flip_source, testcases)
    print(pos, "/", len(source))

browser.quit()

Usage:

make sure you have python3 and firefox installed.
save this python code to your locale.
pip install selenium
download firefox web driver and put it in the same folder of this python source.
execute this validator and wait it finish.

How

If the modification is on the first time of script. The script will throw some errors (syntax error, undefined variable, etc.). And the second time of script will run correctly and overwrite the output.

If the modification is not on the first time of script. The script output

Learn some (useless) HTML knowledge

document.write insert HTML to current position. You should not output unbalanced HTML in usual. When unbalanced HTML is printed. It inserted as is. And following HTML are re-parsed. You may even insert something like <!-- to open a comment.
When trying to parse <head>, if HTML parser got anything should not be existed here, the <head> tag is closed immediately and a <body> is created.
When the  tag is created, document.body is accessible.
<script> tag is closed by </script>. Anything between them are script. Script may not be valid, and that doesn't matter (doesn't break HTML).
Exception in previous <script> tag does not prevent the following 's execution.


Brainfuck, score: 31 (2208 bytes)

Base64-encoded program:

[encoded data, 5160 characters]

Works for shifts 0, 4, 8, 12, 32, 36, 40, 44, 64, 68, 72, 76, 96, 100, 104, 108, 128, 132, 136, 140, 160, 164, 168, 172, 192, 196, 200, 204, 224, 228, 232 and 236.

For every value between 0 and 255, there is exactly one of those shifts that sends that character to a valid brainfuck instruction.

The program relies on 8-bit cells with wrapping on overflows.
This could probably be golfed quite a bit, as the shift just consists of a repeated + or - (whichever is shorter).

Python code used to generate this:

l = [0, 4, 8, 12, 32, 36, 40, 44, 64, 68, 72, 76, 96, 100, 104, 108, 128, 132, 136, 140, 160, 164, 168, 172, 192, 196, 200, 204, 224, 228, 232, 236]
shift = lambda s,n:"".join(chr((ord(i)+n)%256) for i in s)
code = ""
for i in l:
    code += shift(",[{}.,]".format(i*"+" if i<=128 else (256-i)*"-"),-i)


C, 84 83 78 Characters

m;main(a,b){for(scanf("%d%d",&a,&b);a;b+=b)a&1?m+=b:0,a>>=1;printf("%d\n",m);}

In a more readable form
m;main(a,b)
{
    scanf("%d%d",&a,&b);
    while (a)
    {
        if (a&1)
           m+=b;
        a>>=1;
        b+=b;
    }
    printf("%d\n",m);
}

The algorithm is better known as the Ethiopian Multiplication or the Russian Peasant Multiplication.Here’s the algorithm :

Let the two numbers to be multiplied be a and b.
If a is zero then break and print the result.
If a is odd then add b to the result.
Half a, Double b. Goto Step 2.


Python 2, 127 103 101 bytes

lambda a:min(zip(*[[1,0,i%2,~-i%2]for i in range(len(a))]),key=lambda N:sum(o^b for o,b in zip(a,N)))

Try it online!

Makes the lists 111..., 000..., 101... and 010... with the first zip then finds the min of these lists with key function: sum of the xor of each element in the each possible output the input.


TI-BASIC, 62 bytes
:Input A
:A
:For(N,3,8
:ClrHome
:Output(8,1,"----I     I----
:Output(N,Ans,"--O--
:Ans+(Ans<6)-(Ans>6
:End

Note that TI-BASIC does not support _ or | and therefore I replaced with a capital I and -. This should not effect byte count.


Find The Sum of the First n Bouncy Numbers

Jelly, 10 8 bytes

ṢeṚƬ¬µ#S

Try it online!

How it works

ṢeṚƬ¬µ#S  Main link. No arguments.

      #   Read an integer n from STDIN and call the chain to the left with argument
          k = 0, 1, 2, ... until n of them return a truthy result.
          Yield the array of successful values of k.
     µ    Monadic chain. Argument: k (integer)
Ṣ           Sort, after promoting k to its digit array.
  ṚƬ        Reverse 'til the results are no longer unique and yield unique results.
            Calling Ṛ on k promotes it to its digit array. If k = 14235, the
            result is [14235, [5,3,2,4,1], [1,4,2,3,5]].
 e          Check if the result to the left appears in the result to the right.
    ¬       Negate the resulting Boolean.
       S  Take the sum.


Python 2, 47 bytes

n=input()
for c in 1,4,1:exec"print'# '*c*n;"*n

Try it online!

Prints this net, chosen for being left-justified:

# #
# #
# # # # # # # #
# # # # # # # #
# #
# #

The lines have n or 4*n copies of '# '. For each of 1,4,1, we print n times that many copies, done n times for n lines. Having an exec loop inside a for loop seems wasteful, but I didn't see better.

Alternatives I tested:

lambda n:('# '*n*3+'\n')*n+('  '*n+'# '*n+'\n')*3*n

lambda n:('# '*n*3+'\n')*n+(' '*4*n+'# '*n*3+'\n')*n

def f(n):
 for c in[3]*n+[1]*3*n:print('# '*c*n).center(6*n)

def f(n):
 for c in[4]*n+[0]*n:print' '*c*n+'# '*n*3

def f(n):
 for c in[1]*n+[4]*n+[1]*n:print'# '*c*n

def f(n):
 c=1;exec("print'# '*c*n;"*n+"c^=5;"*n)*3

def f(n):
 for i in range(3*n):print'# '*[1,4,1][i/n]*n

def f(n):
 for c in 1,4,1:print('# '*c*n+'\n')*n,

def f(n):
 for c in 1,4,1:exec"print'# '*c*n;"*n

(The def functions can all be one shorter as a program.)


Haskell, 72 bytes

f n=[(a,b)|b<-[1..n],a<-[1..b-1],mod n 4<2,mod(a+b+sum[b|odd n,a<2])4<2]

Try it online!
A belated improvement inspired by ideas from kops. Takes vertex 1 to the the special vertex in the \$n=1 \bmod 4\$ case, rather than vertex n.

Haskell, 77 bytes

f n=[(a,b)|b<-[1..n],a<-[1..b-1],mod n 4<2,mod(a+(last$b:[a|odd n,n==b]))4<2]

Try it online!
This uses an easy-to-compute explicit criterion to decide whether an edge (a,b) belongs in the graph. Instantiates this algorithm, with the permutation cycling among the values modulo 4
4*m -> 4*m+1 -> 4*m+2 -> 4*m+3 -> 4*m

We include edges whose two endpoint vertices add to 0 or 1 modulo 4. Note that cycling vertices as per this permutation adds 2 modulo 4 to the vertex sum on each each, and so swaps edges and non-edges. This gives a permutation of vertices that complements the edges.
If the graph has an extra node beyond a multiple of 4, it is put in a cycle alone. We include edges with it when then other vertex is even. Permuting the vertices flips the parity, and so the graph remains self-complementary.
If the number of vertices isn't 0 or 1 modulo 4, no self-complementary graph is possible because there's an odd number of edges in the complete graph
Overall, here are the conditions:

If the input n isn't 0 or 1 modulo 4, output an empty list
Otherwise if n is even, include all edges (a,b) with a<b and a+b equal to 0 or 1 modulo 4.
Otherwise if n is odd, do the same, but instead include edges of the form (a,n) when a is even.

The code combines the second and third cases by replacing the condition mod(a+b)4<2 with mod(a+a)4<2 when both odd n and b==n.


OCaml, 1588 (n = 36)

This solution uses the usual bit pattern approach to represent vectors of -1s and 1s. The scalar product is as usual calculated by taking the xor of two bit vectors and subtracting n/2. Vectors are orthogonal iff their xor has exactly n/2 bits set.

Lyndon words are not per se useful as a normalized representation for this, as they exclude any pattern that is a rotation of itself. They are also relatively expensive to compute. Therefore, this code uses a somewhat simpler normal form, which requires that the longest consecutive sequence of zeroes after rotation (or one of them, if there are multiples) must occupy the most significant bits. It follows that the least significant bit is always 1.

Observe also that any candidate vector must have at least n/4 ones (and at most 3n/4). We therefore only consider vectors with n/4 ... n/2 bits set, since we can derive others via complement and rotation (in practice, all such vectors seem to have between n/2-2 and n/2+2 ones, but that seems to also be difficult to prove).

We build these normal forms from the least significant bit up, observing the constraint that any remaining runs of zeroes (called "gaps" in the code) must follow our normal form requirement. In particular, as long as at least one more 1-bit has to be placed, there must be room for the current gap and another than that is at least as big as the current gap or any other gap observed so far.

We also observe that the list of results is small. Therefore, we do not try to avoid duplicates during the discovery process, but simply record the results in per-worker sets and calculate the union of these sets at the end.

It is worth noting that the runtime cost of the algorithm still grows exponentially and at a rate that is comparable to that of the brute-force version; what this buys us is essentially a reduction by a constant factor, and comes at the cost of an algorithm that is more difficult to parallelize than the brute-force version.

Output for n up to 40:

 4: 12
 8: 40
12: 144
16: 128
20: 80
24: 192
28: 560
32: 0
36: 432
40: 640

The program is written in OCaml, to be compiled with:

ocamlopt -inline 100 -nodynlink -o orthcirc unix.cmxa bigarray.cmxa orthcirc.ml

Run ./orthcirc -help to see what options the program supports.

On architectures that support it, -fno-PIC may offer some small additional performance gain.

This is written for OCaml 4.02.3, but may also work with older versions (as long as they aren't too old).

UPDATE: This new version offers better parallelization. Note that it uses p * (n/4 + 1) worker threads per instance of the problem, and some of them will still run considerably shorter than others. The value of p must be a power of 2. The speedup on 4-8 cores is minimal (perhaps around 10%), but it scales better to a large number of cores for large n.

let max_n = ref 40
let min_n = ref 4
let seq_mode = ref false
let show_res = ref false
let fanout = ref 8

let bitcount16 n =
  let b2 n = match n land 3 with 0 -> 0 | 1 | 2 -> 1 | _ -> 2 in
  let b4 n = (b2 n) + (b2 (n lsr 2)) in
  let b8 n = (b4 n) + (b4 (n lsr 4)) in
  (b8 n) + (b8 (n lsr 8))

let bitcount_data =
  let open Bigarray in
  let tmp = Array1.create int8_signed c_layout 65536 in
    for i = 0 to 65535 do
      Array1.set tmp i (bitcount16 i)
    done;
    tmp

let bitcount n =
  let open Bigarray in
  let bc n = Array1.unsafe_get bitcount_data (n land 65535) in
  (bc n) + (bc (n lsr 16)) + (bc (n lsr 32)) + (bc (n lsr 48))

module IntSet = Set.Make (struct
  type t = int
  let compare = Pervasives.compare
end)

let worker_results = ref IntSet.empty

let test_row vec row mask n =
  bitcount ((vec lxor (vec lsr row) lxor (vec lsl (n-row))) land mask) * 2 = n

let record vec len n =
  let m = (1 lsl n) - 1 in
  let rec test_orth_circ ?(row=2) vec m n =
    if 2 * row >= n then true
    else if not (test_row vec row m n) then false
    else test_orth_circ ~row:(row+1) vec m n
  in if test_row vec 1 m n &&
        test_orth_circ vec m n then
  begin
    for i = 0 to n - 1 do
      let v = ((vec lsr i) lor (vec lsl (n - i))) land m in
      worker_results := IntSet.add v !worker_results;
      worker_results := IntSet.add (v lxor m) !worker_results
    done
  end

let show vec n =
  for i = 0 to n / 2 - 1 do
    let vec' = (vec lsr i) lor (vec lsl (n - i)) in
    for j = 0 to n-1 do
      match (vec' lsr (n-j)) land 1 with
      | 0 -> Printf.printf "  1"
      | _ -> Printf.printf " -1"
    done; Printf.printf "\n"
  done; Printf.printf "\n"; flush stdout

let rec build_normalized ~prefix ~plen ~gap ~maxgap ~maxlen ~bits ~fn =
  if bits = 0 then
    fn prefix plen maxlen
  else begin
    let room = maxlen - gap - plen - bits in
    if room >= gap && room >= maxgap then begin
      build_normalized
        ~prefix:(prefix lor (1 lsl (plen + gap)))
        ~plen:(plen + gap + 1)
        ~gap:0
        ~maxgap:(if gap > maxgap then gap else maxgap)
        ~maxlen
        ~bits:(bits - 1)
        ~fn;
      if room > gap + 1 && room > maxgap then
        build_normalized ~prefix ~plen ~gap:(gap + 1) ~maxgap ~maxlen ~bits ~fn
    end
  end

let rec log2 = function
| 0 -> -1
| n -> 1 + (log2 (n lsr 1))

let rec test_gap n pat =
  if n land pat = 0 then true
  else if pat land 1 = 0 then test_gap n (pat lsr 1)
  else false

let rec test_gaps n maxlen len =
  let fill k = (1 lsl k) -1 in
  if len = 0 then []
  else if test_gap n ((fill maxlen) lxor (fill (maxlen-len))) then
    len :: (test_gaps n maxlen (len-1))
  else test_gaps n maxlen (len-1)

let rec longest_gap n len =
  List.fold_left max 0 (test_gaps n len len)

let start_search low lowbits maxlen bits fn =
  let bits = bits - (bitcount low) in
  let plen = log2 low + 1 in
  let gap = lowbits - plen in
  let maxgap = longest_gap low lowbits in
  worker_results := IntSet.empty;
  if bits >= 0 then
    build_normalized ~prefix:low ~plen ~gap ~maxgap ~maxlen ~bits ~fn;
  !worker_results

let spawn f x =
  let open Unix in
  let safe_fork () = try fork() with _ -> -1 in
  let input, output = pipe () in
  let pid = if !seq_mode then -1 else safe_fork() in
  match pid with
  | -1 -> (* seq_mode selected or fork() failed *)
     close input; close output; (fun () -> f x)
  | 0 -> (* child process *)
    close input;
    let to_parent = out_channel_of_descr output in
    Marshal.to_channel to_parent (f x) [];
    close_out to_parent; exit 0
  | pid -> (* parent process *)
    close output;
    let from_child = in_channel_of_descr input in
    (fun () ->
      ignore (waitpid [] pid);
      let result = Marshal.from_channel from_child in
      close_in from_child; result)

let worker1 (n, k) =
  start_search 1 1 n k record

let worker2 (n, k, p) =
  start_search (p * 2 + 1) (log2 !fanout + 1) n k record

let spawn_workers n =
  let queue = Queue.create () in
  if n = 4 || n = 8 then begin
    for i = n / 4 to n / 2 do
      Queue.add (spawn worker1 (n, i)) queue
    done
  end else begin
    for i = n / 2 downto n / 4 do
      for p = 0 to !fanout - 1 do
        Queue.add (spawn worker2 (n, i, p)) queue
      done
    done
  end;
  Queue.fold (fun acc w -> IntSet.union acc (w())) IntSet.empty queue

let main () =
  if !max_n > 60 then begin
    print_endline "error: cannot handle n > 60";
    exit 1
  end;
  min_n := max !min_n 4;
  if bitcount !fanout <> 1 then begin
    print_endline "error: number of threads must be a power of 2";
    exit 1;
  end;
  for n = !min_n to !max_n do
    if n mod 4 = 0 then
    let result = spawn_workers n in
    Printf.printf "%2d: %d\n" n (IntSet.cardinal result);
    if !show_res then
      IntSet.iter (fun v -> show v n) result;
    flush stdout
  done

let () =
  let args =[("-m", Arg.Set_int min_n, "min size of the n by n/2 matrix");
             ("-n", Arg.Set_int max_n, "max size of the n by n/2 matrix");
             ("-p", Arg.Set_int fanout, "parallel fanout");
             ("-seq", Arg.Set seq_mode, "run in single-threaded mode");
             ("-show", Arg.Set show_res, "display list of results") ] in
  let usage = ("Usage: " ^
               (Filename.basename Sys.argv.(0)) ^
               " [-n size] [-seq] [-show]") in
  let error _ = Arg.usage args usage; exit 1 in
  Arg.parse args error usage;
  main ()


GNU sed 98 96 88 80 77 74 69 59 54 (48 + 1 for -r) 49

:;s,(.+)(=[^&]*[& ]|&)(.*)\1,\3 ,
t;s,[?&]? .*,,

The list of parameters to remove are separated by spaces.

$ echo 'http://example.com/?foo=1&bar=2&baz=3 foo bar baz' | sed -rf sed.txt
http://example.com/

$ echo 'http://example.com/?foo&bar=2&baz= foo baz' | sed -rf sed.txt
http://example.com/?bar=2

$ echo 'http://example.com/' | sed -rf sed.txt
http://example.com/


For what block sizes is this checksum valid?

05AB1E, 10 8 bytes
Input is a list of bits.
gÑ¨ʒιOÈP

Try it online!
Commented:
gÑ          # push the divisors of the length of the input
  ¨         # remove the last one (the length itself)
   ʒ        # filter this list on:
    ι       #   push [a[0::b], a[1::b], ..., a[(b - 1)::b]] where a is the input b the divisor
            #   this groups the digits from each group at the same index together
     O      #   sum each list
      ÈP    #   are all sums even?


Use dup and add for large numbers

If you need to produce a big but reasonable number which is a multiple of 2 (and in some cases, even not a multiple), you can push half the number and end with  +* (dup and add) instead of pushing the whole number. The threshold for this is 8 and above.

As mentioned, sometimes you can double, then subtract one (threshold 27), and with multiples of higher 2 powers it can be repeated to gain greater numbers.

Try it online!


hello, world!, 13 bytes, 1193
hello, world!


Ohm v2, 5 bytes
υ!+υy

Try it online!
Explanation:
υ!+υy
υ!     get the current timestamp in seconds
  +    sum with the implicit input
   υy  get the year from the resulting timestamp


CJam, 29 26 24 bytes

Thanks to Sp3000 for saving 3 bytes.

q~2b{_1&}{W\({%}*0+}w],(

Test suite. (This prints all results from 0 to the integer given on STDIN.)

Explanation

This turns the spec on its head a bit: instead of moving the shell through the binary string, we shift and reverse the binary string such that the shell is always at the front, pointing to the right:

q~      e# Read and evaluate the input.
2b      e# Convert to base-2 to get the "level".
{_1&}{  e# While there is a 1 in the level...
  W\    e#   Put a -1 below the level.
  (     e#   Pull off the first digit, i.e. the cell the shell is pointing at.
  {     e#   If it's a 1 (i.e. a brick)...
    %   e#     Reverse the level, consuming the -1. This isequivalent to reversing the
        e#     shell in place.
  }*
  0+    e#   Append a zero. If the cell was a brick, this just replaces it with an empty
        e#   cell. Otherwise, this rotates the level by one cell. This is equivalent
        e#   to moving the shell one cell through the periodic level.
        e#   Note that if the leading cell was 0, the -1 remains on the stack.
}w
],(     e# Wrap the stack in an array, get its length and decrement.


Mathematica, 81 79 bytes

Thanks to Martin Ender for saving 2 bytes!

(c=Ceiling;For[j=0;z=E,c@z>z,p=(x=c@Sqrt[j+=#])+{z=Sqrt[x^2-j],-z}];p/#~GCD~p)&

Pure function taking a semiprime as input and returning an ordered pair of positive integers. The For loop implements the exact procedure described in the question (using # for the input in place of n), with x as defined there, although we store j = k*n instead of k itself and z=Sqrt[y] instead of y itself. We also compute p={x+z,x-z} inside the For loop, which ends up saving one byte (on like the seventh try). Then the two desired factors are (x+z)/GCD[#,x+z] and (x-z)/GCD[#,x-z], which the concise expression p/#~GCD~p computes directly as an ordered pair.

Curiosities: we want to loop until z is an integer; but since we're going to use Ceiling already in the code, it saves two bytes over !IntegerQ@z to define c=Ceiling (which costs four bytes, as Mathematica golfers know) and then test whether c@z>z. We have to initialize z to something, and that something had better not be an integer so that the loop can start; fortunately, E is a concise choice.


PHP, 230 bytes

I've added the first two newlines for readibility.

function($l){for($y=count($l);$y>=0;$f[]="$a|   |$a")$a=str_repeat($y--?$w=' ':'-',99);
foreach($l as$x){for($x+=101,$s=$y=0;!$s;$b[$x]!=$w?$b[$x+1]!=$w?$b[$x-1]!=$w?$s=1:--$x
:++$x:0)$b=$f[$y++];$f[$y-2][$x]=a;}echo join('
',$f);};

Ideone

Here is the ungolfed version:

function drawApples(array $listStartX)
{
    $field = [];
    $maximalHeight = count($listStartX);
    for ($y = $maximalHeight; $y >= 0; --$y)
    {
        $line = str_repeat($y > 0 ? ' ' : '-', 98);
        $field[] = $line .'|   |'. $line;
    }

    foreach ($listStartX as $x)
    {
        $x += 100;
        for ($y = 0; true; ++$y)
        {
            if ($field[$y][$x] === ' ') {
                continue;
            }

            if ($field[$y][$x + 1] === ' ') {
                ++$x;
                continue;
            }

            if ($field[$y][$x - 1] === ' ') {
                --$x;
                continue;
            }

            $field[$y - 1][$x] = 'a';
            break;
        }
    }

    echo implode("\n", $field);
}


Find all numbers between 2 and 100 co-prime to a given number

CJam, 23 bytes

101,:N2>q~mf{N%-}/", "*

Try it online. Paste the Code, type an integer in Input and click Run.

Example

$ cjam factor.cjam <<< 210
11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97

How it works

101,:N # Push the array [ 0 ... 100 ] and save it in “N”.
2>     # Remove 0 and 1 from the array.
q~mf   # Read from STDIN, interpret the input and factorize the resulting integer.
{      # For each prime factor:
  N%   # Collect all multiples of the prime factor in an array.
  -    # Apply set difference with the array on the stack.
}/     # This leaves only integers that are coprime with the input.
", "*  # Join by commas and spaces.


Ruby 164
Pretty straightforward. Interesting features:
The crapping out cases are summarised as r%12<4 and the remaining natural cases are summarised as r%4==3.
The initial string is stored in c and further rolls are taken only if this is later alphabetically than the single letter ?P (which only occurs for Point.)
f=->{rand(6)+rand(6)+2}
s=0
r=f[]
print c=r%12<4?'Crapping out':r%4==3?'Natural':'Point',": #{r}
"
c>?P&&(until s==r||s==7
p s=f[]end
print s==7?"Don't ":"","Pass")


CJam, 62 57 bytes

As far as I can see, this is completely different approach to implement the solution from aditsu's answer.

q~:C;:HaH)*H){(:I\_@>2<:-C>{I0a*C~)+C1a*+]z1fb_,}I?}h-H-,

Input goes in the form of h c

Example:

80 5

Output:

28

How it works

The logic is pretty straight forward here with a few tricks used to reduce code size.

Get h + 1 (+ 1 for h = 0 case) length array with each element being h to represent the cliff
Start iterating from the right most index of this array

If the two elements from current index have different more than c

Remove c from the current index element
Add 1 to next c elements of the array from the current index
Make the current index equal to the length of this new array
This makes sure that we stabilize the stones to the right of the current index first

else, reduce the current index

When we hit the left most index, we are making sure that all adjacent indexes have less than or equal to c difference
Remove any 0 or h value from the array and get length.

Code expansion

q~:C;:HaH)*H){(:I\_@>2<:-C>{I0a*C~)+C1a*+]z1fb_,}I?}h-H-,
q~:C;:HaH)*H)
q~:C;:H                  "Read the input, evaluate it, store height in H and coeff. in C";
       aH)*              "Wrap the height number in an array and repeat it H + 1 times";
           H)            "Put H+1 on stack, representing the current index of iteration";
{(:I\_@>2<:-C>{I0a*C~)+C1a*+]z1fb_,}I?}h
(:I\_@>2<:-C>
(:I                      "Decrement the current index and store it in I";
   \_                    "Swap to put array on top and make 1 copy";
     @>2<                "Get the two elements starting from Ith index";
         :-              "Get the difference. The best part of this approach is that";
                         "For the right most index, where there is only element, it";
                         "returns the element itself, which is the expected difference";
           C>            "Check if difference is greater than C";
{I0a*C~)+C1a*+]z1fb_,}   "This block will be executed when the difference is more than C";
 I0a*                    "Get an array of I length and all elements 0";
     C~)+                "Get -C value and append it to the above array";
         C1a*+           "Get C length array of 1s and concat with the above array";
              ]          "Wrap the two arrays, the cliff and the above one in an array";
               z1fb      "Transpose to get number pairs and add those pairs. For example";
                         "If we are at the right most index with H = 80 and C = 5,";
                         "The right section of the cliff looks like:";
                         "[ ... 80 80 80 80 80] and the array created in above step";
                         "looks like [ ... 0 0 0 0 -5 1 1 1 1 1]. After z, we have:";
                         "[ ... [80 0] [80 0] [80 0] [80 0] [80 -5] [1] [1] [1] [1] [1]]";
                         "After 1fb we get [ ... 80 80 80 80 75 1 1 1 1 1]";
                   _,    "Take a copy of the above resultant array and take its length";
I?                       "If difference was not greater than C, put I on stack";
                         "Now we either have the decremented index or new array length";
                         "on stack."
{ ... }h                 "This is a do while loop which makes sure that we iterate to";
                         "the left of the array. This loops runs till the top stack";
                         "element is 0 while not popping the top element";
        -H-,             "After the loop, we have the final cliff array and 0 on stack";
                         "Remove any 0 elements from the array, then remove any H";
                         "elements from the array and then take length to get the";
                         "number of columns which were modified";

Try it online here


Python 2, 45 bytes

lambda n:[i for i in range(32)if n|1<<i>n][1]

Try it online!

Uses 0-indexing, unsigned numbers, and throws an error on no second zero.

Simply creates a list of indices of non-set bits, from lowest to highest, and returns the second entry.