I'm thinking of a number (Robber's thread)

Java, by okx

Note: the original challenge to which this post answers has been deleted, it's however still accessible with the link to anyone having the privilege to see deleted answers. The explanations below include what the challenge was about.

Number: 18

The code is effectively looking for primes with the form 112n-2.

By this Wikipedia list, we know that the 20th largest known prime number has 2,900,832 digits. No prime with the form 112n-2 are in that list, so that digit number will be our limit.

All numbers of the form 112n-2 that have at most that many digits have this constraint: n < 22. Factordb tells us that 11222-2 has 4,367,918 digits. This is proof enough.

The code by okx limits us to n above 6.

So, let's do the list:

112n-2 is factorizable for n = 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 19, 20 and 21 (factors proofs are on factordb.com and wolfram alpha; factordb has some proofs that wolfram alpha hasn't and vice-versa).

The only value n for which we can't prove the factorization is 18 (factordb, WolframAlpha).

So (a) if there is a prime number of the form 112n-2 with n > 6, then (b) 6 < n < 22, and (c) I proved each number with such n is composite except for 18, so (d) the prime we're looking for has n = 18.

Note that I don't exclude that 11218-2 is composite. I haven't proved that that number is a prime: I only proved that if the OP thought about that number, it can only be 18. If that number is indeed a prime, congrats to okx for finding it :-)

However

There are no proof that 11218-2 is the only number, though. It's the only number in the range of numbers for which we can currently prove the primality.

So I don't exclude the fact that one day someone might prove that 11251-2 or 112124-2 is prime.

I therefore believe that the original entry by okx is invalid because there are no such proof that for n between 19 and the (231-1)231-1 (the theoretical limit of Java's BigInteger), there are no other primes.


JavaScript (ES6),  62 58 49  46 bytes
Saved 3 bytes thanks to @Oliver
Returns the list as a comma-separated string.

f=a=>+a||f(a.map(n=>a-(a=n),a=a.shift()))+[,a]

Try it online!
Commented
f = a =>              // f = recursive function taking the input list a[]
  +a                  // if a[] consists of a single positive integer:
                      //   stop recursion and return this integer
  ||                  // else:
    f(                //   do a recursive call to f:
      a.map(n =>      //     for each value n in a[]:
        a - (a = n),  //       yield the difference between the previous value and n
                      //       and update a to n
        a = a.shift() //       start by removing the first element and saving it in a
                      //       (because of the recursion, it's important here to reuse
                      //       a variable which is defined in the scope of f)
      )               //     end of map()
    )                 //   end of recursive call
    + [, a]           //   append the last entry from a[]


Convert binary search tree into ordered linked list

Python: 100

class N:l=r=v=None
def T(p,q=None):
 if not p:return q
 r=p.r=T(p.r,q)
 if r:r.l=p
 return T(p.l,p)

Ungolfed Version

class Node:
    left = right = value = None

def transform(node, next=None):
    """
    node: head node to convert
    next: next node for the tail node to connect
    return: The converted head
    """
    if not node:
        return next
    node.right = transform(node.right, next)
    if node.right:
        node.right.left = node
    return transform(node.left, node)

Instead of returning a (head, tail) pair, in my solution, a next node is passed as argument to the transform function so that it only need to return the head node. This make the code shorter and cleaner.


Is this a valid input for this hardware?

Python 2, 52 bytes

lambda s:eval("'EDCBA9801234567'.find(%r)<"*8%s+'s')

Try it online!

Takes input as a tuple like ('F', 'E', 'D', 'C', 'B', 'A', '9', '8').

The idea is to produce out and evaluate a long chain of inequalities like:

'EDCBA9801234567'.find('F')<'EDCBA9801234567'.find('E')<'EDCBA9801234567'.find('D')<'EDCBA9801234567'.find('C')<'EDCBA9801234567'.find('B')<'EDCBA9801234567'.find('A')<'EDCBA9801234567'.find('9')<'EDCBA9801234567'.find('8')<s

The s at the end of the chain takes care of the extra trailing < symbol by giving an always-true comparison of "number < string" in Python 2 logic.


Binary Reduce a List By Addition With a Right Bias

Python 2, 40 bytes

Takes as input a list \$ l \$, and outputs the two sums in reverse order ([right, left]).

lambda l:[sum(l.pop()for x in l),sum(l)]

Explanation

In sum(l.pop()for x in l), we pop the last element, in each iteration, and sum the popped elements. Surprisingly, the loop only runs \$ \lceil{\frac{|l|}{2}}\rceil \$ times, since for every element we iterate from the left, we are removing an element from the right, resulting in the loop terminating somewhere in the middle. Therefore it gives us the sum of the right portion of the list. The sum of the remaining elements make up the left portion.

Try it online!


Scala, 860 bytes

Golfed:

    object D extends App{val s=args(0)split("\n")
    val r=Seq(P(1,0),P(1,-1),P(0,-1),P(-1,-1),P(-1,0),P(-1,1),P(0,1),P(1,1))
    var m=r(0)
    val e=s.map(_.toCharArray)
    case class P(x:Int,y:Int){def u=x==0||h
    def h=y==0
    def p(o:P)=P(x+o.x,y+o.y)
    def o="\\/".contains(c)
    def w="-|+".contains(c)
    def c=try s(y)(x) catch {case _=>'E'}
    def n=r.filter(!_.u).map(d => d.j(p(d))).sum
    def j(t:P):Int=if(t.o)1+j(p(t))else 0
    def q=if(c=='X'){m=this
    r.filter(_.u).map{d=>if(p(d).c==' '&&p(P(d.x*(n+1),d.y*(n+1))).w)d.i}}
    def i:Unit=Seq(r++r,(r++r).reverse).map(l=>l.drop(l.indexOf(this)+1)).map(_.take(4)).filter(_.exists(a=>a.p(m)o))(0).grouped(2).foreach{p=>if(p(1)p(m)w){p(0)add;return}}
    def add=if(r.filter(_.h).map(p(_)p(m)).exists(_.w))e(y*m.n+m.y)(x+m.x)='.'else e(y+m.y)(x*m.n+m.x)='.'}
    val f=args(0).size
    Array.tabulate(f,f){(i,j)=>P(i,j)q}
    e.map(_.mkString).map(println)}

Un-golfed:

    object DoorknobCleanVersion extends App {
            val s = args(0) split ("\n")

            val r = Seq(P(1, 0), P(1, -1), P(0, -1), P(-1, -1), P(-1, 0), P(-1, 1), P(0, 1), P(1, 1))
            val HorizontalDirections = r.filter(_.isHorizontal)

            var hinge = r(0)
            val result = s.map(_.toCharArray)

            type I = Int
            case class P(x: Int, y: Int) {
                    def isCardinal = x == 0 || isHorizontal
                    def isHorizontal = y == 0

                    override def toString = x + "," + y

                    def p(o: P) = P(x + o.x, y + o.y)

                    def isDoor = Seq('\\', '/').contains(charAt)
                    def isWall = Seq('-', '|', '+').contains(charAt)

                    def charAt = try s(y)(x) catch { case _ => 'E' }

                    def doorLength = r.filter(!_.isCardinal).map(d => d.recursion2(p(d))).sum

                    def recursion2(currentPosition: P): Int =
                            if (currentPosition.isDoor)
                                    1 + recursion2(p(currentPosition))
                            else
                                    0

                    def findDoorway =
                            if (charAt == 'X') {
                                    hinge = this
                                    r.filter(_.isCardinal).map { d =>
                                            if (p(d).charAt == ' ' && p(P(d.x * (doorLength + 1), d.y * (doorLength + 1))).isWall)
                                                    d.getCorrectRotation2
                                    }
                            }

                    def getCorrectRotation2: Unit = Seq(r ++ r, (r ++ r).reverse).map(l => l.drop(l.indexOf(this) + 1))
                            .map(_.take(4))
                            .filter(_.exists(a => a.p(hinge)isDoor))(0)
                            .grouped(2)
                            .foreach {
                                    p =>
                                            if (p(1) p (hinge)isWall) {
                                                    p(0)add;
                                                    return
                                            }
                            }

                    def add =
                            if (HorizontalDirections.map(p(_) p (hinge)).exists(_.isWall))
                                    result(y * hinge.doorLength + hinge.y)(x + hinge.x) = '.'
                            else
                                    result(y + hinge.y)(x * hinge.doorLength + hinge.x) = '.'

            }

            val size = args(0).size
            Array.tabulate(size, size) { (i, j) => P(i, j).findDoorway }

            result.map(_.mkString).map(println)
    }

Using OOP was definitely the wrong approach here, in hindsight. If I could do it again I would definitely go with a bunch of hardcoded truth tables.


TI-BASIC, 77 - 34 (error text) = 43
In case he wants to do in on his TI-83/84 calculator ;)
As standard for functions, file string should be in Ans so it can return and display the output.
Ans->Str1:If 1=inString(Ans,"A
Then:"B
Else:"A
End:Disp "ERROR ON LINE 1","'"+Ans+sub(Str1,2,-1+length(Str1))+"'"," ^ INVALID

Note that many tokens are one byte.


Rust, n ≈ 1400

How to run

Build with cargo build --release, and run with target/release/arbitrary-randomness n.

This program runs fastest with lots of memory (as long as it’s not swapping, of course).  You can adjust its memory usage by editing the MAX_BYTES constant, currently set at 8 GiB.

How it works

The set is constructed by a sequence of binary decisions (each number is either inside or outside the set), each of whose probabilities are computed combinatorially by counting the number of possible sets constructible after each choice using dynamic programming.

Memory usage for large n is reduced by using a version of this binomial partitioning strategy.

Cargo.toml

[package]
name = "arbitrary-randomness"
version = "0.1.0"
authors = ["Anders Kaseorg <andersk@mit.edu>"]

[dependencies]
rand = "0.6"

src/main.rs

extern crate rand;

use rand::prelude::*;
use std::env;
use std::f64;
use std::mem;

const MAX_BYTES: usize = 8 << 30; // 8 gibibytes

fn ln_add_exp(a: f64, b: f64) -> f64 {
    if a > b {
        (b - a).exp().ln_1p() + a
    } else {
        (a - b).exp().ln_1p() + b
    }
}

fn split(steps: usize, memory: usize) -> usize {
    if steps == 1 {
        return 0;
    }
    let mut u0 = 0;
    let mut n0 = f64::INFINITY;
    let mut u1 = steps;
    let mut n1 = -f64::INFINITY;
    while u1 - u0 > 1 {
        let u = (u0 + u1) / 2;
        let k = (memory * steps) as f64 / u as f64;
        let n = (0..memory)
            .map(|i| (k - i as f64) / (i as f64 + 1.))
            .product();
        if n > steps as f64 {
            u0 = u;
            n0 = n;
        } else {
            u1 = u;
            n1 = n;
        }
    }
    if n0 - (steps as f64) <= steps as f64 - n1 {
        u0
    } else {
        u1
    }
}

fn gen(n: usize, rng: &mut impl Rng) -> Vec<usize> {
    let s = n * n.wrapping_sub(1) / 2;
    let width = n.min(MAX_BYTES / ((s + 1) * mem::size_of::<f64>()));
    let ix = |m: usize, k: usize| m + k * (s + 1);
    let mut ln_count = vec![-f64::INFINITY; ix(0, width)];
    let mut checkpoints = Vec::with_capacity(width);
    let mut a = Vec::with_capacity(n);
    let mut m = s;
    let mut x = 1;

    for k in (1..=n).rev() {
        let i = loop {
            let i = checkpoints.len();
            let k0 = *checkpoints.last().unwrap_or(&0);
            if k0 == k {
                checkpoints.pop();
                break i - 1;
            }
            if i == 0 {
                ln_count[ix(0, i)] = 0.;
                for m in 1..=s {
                    ln_count[ix(m, i)] = -f64::INFINITY;
                }
            } else {
                for m in 0..=s {
                    ln_count[ix(m, i)] = ln_count[ix(m, i - 1)];
                }
            }
            let k1 = k - split(k - k0, width - 1 - i);
            for step in k0 + 1..=k1 {
                for m in step..=s {
                    ln_count[ix(m, i)] = ln_add_exp(ln_count[ix(m - step, i)], ln_count[ix(m, i)]);
                }
            }
            if k1 == k {
                break i;
            }
            checkpoints.push(k1);
        };

        while m >= k && rng.gen_bool((ln_count[ix(m - k, i)] - ln_count[ix(m, i)]).exp()) {
            m -= k;
            x += 1;
        }
        a.push(x);
        x += 1;
    }
    a
}

fn main() {
    if let [_, n] = &env::args().collect::<Vec<_>>()[..] {
        let n = n.parse().unwrap();
        let mut rng = StdRng::from_entropy();
        println!("{:?}", gen(n, &mut rng));
    } else {
        panic!("expected one argument");
    }
}

Try it online!

(Note: the TIO version has a few modifications.  First, the memory limit is reduced to 1 GiB. Second, since TIO doesn’t let you write a Cargo.toml and depend on external crates like rand, I instead pulled in drand48 from the C library using the FFI.  I didn’t bother to seed it, so the TIO version will produce the same result on every run.  Don’t use the TIO version for official benchmarking.)


Parallel resistance in electric circuits

05AB1E, 5 3 bytes
zOz

Try it online!

Explanation
z                     # compute 1/x for each x in input
 O                    # sum input
  z                   # compute 1/sum


Python 2, 38 bytes

lambda s:sum(map(ord,s))*3%61%37%9%7%2

Try it online!

A good ol' modulo chain applied to the sum of ASCII values of the input string, making for a solution that's just overfitting. The total ASCII value is distinct for each possible input, except that those with 0 1 and 1 0 give the same result, which is works out because all the logic gates used are symmetric.

The *3 separates out otherwise-adjacent values for inputs that different only in the bits, since these make it hard for the mod chain to split up. The length and size of numbers in the mod chain creates roughly the right amount of entropy to fit 18 binary outputs.

A shorter solution is surely possible using hash(s) or id(s), but I avoided these because they are system-dependent.

Python 2, 50 bytes

lambda s:'_AX0NRD'.find((s*9)[35])>>s.count('0')&1

Try it online!

A slightly more principled solution. Each logic gate gives a different result for each count of zeroes in the input, encodable as a three-bit number from 1 to 6. Each possible logic gate is mapped to the corresponding number by taking (s*9)[35], which are all distinct. For OR, this winds up reading one of the bits so the character could be 0 or 1, but it turns out to work to check if it's 0, and a 1 will correctly give a 1 result anyway.


Mathematica, 202 bytes
{g[#],##}~r~" "&@@@GatherBy[#&@@@SortBy[Tally@StringReplace[StringSplit@#,x_/;!LetterQ@x->""],-Last@#&],g=""<>ToString/@(\[LeftFloor]If[#<113,(#-91)/3,(#-88.2)/3.4]\[RightFloor]&/@ToCharacterCode@#)&]~(r=Riffle)~"
"<>""&

Note that \[LeftFloor] and \[RightFloor] are 3 bytes each.


JavaScript (ES6) - 122 124 148 162 172 178 187 190 193 208 bytes
Many thanks to Optimizer and DocMax for helpful suggestions on how to improve this code:
F=a=>(D=(x,y,d)=>!D[i=[x,y,d]]&&(D[i]=1,x-=~d%2,y-=~-~d%2,x*y==49||!((x|y)&8||a[y][x])&&(D(x,y,d)||D(x,y,~-d%4))),D(-1,0))

Returns true (truthy) for solvable and false (falsy) for unsolvable.
Works only in Firefox as of today becasue of JavaScript 1.7 features.
Test Board


112 bytes

G1 $:(ƒ=(Τ,$=+[])=>Τ[$]?Τ[$]+ƒ(Τ,++$+'5'[+[]]*(Τ[$]==':')):'')[ƒ('constructor')](ƒ('alert("pwned")'))()

function gcode(str){
  //Removes comment, parses command name and args
  const [,f,args] = (str.match(/^([GM]\d+) ([^;]+)/) || [,"",""]);
  //A1.2 B43 C -> {A: 1.2, B: 42, C: 0}
  eval(f+"({"+args.replace(/(\w)([\d\.]*)/g,"$1: $2+0,")+"})");
}
const G1 = console.log;

payload = `G1 $:(ƒ=(Τ,$=+[])=>Τ[$]?Τ[$]+ƒ(Τ,++$+'5'[+[]]*(Τ[$]==':')):'')[ƒ('constructor')](ƒ('alert("pwned")'))()`;
gcode(payload);

Each ƒ (U+0192), Τ (U+03A4) cost 2 bytes, they are not as same as ASCII f, T.

The gcode function will keep any /\W/ characters as is. So, we just need to use these characters to write some logic here. The idea is basically based on how JSF**k works. We construct the codes like this:

(()=>{})["constructor"]('alert("pwned")')

We need string literal "constructor" and alert("pwned"). But gcode convert "constructor" to "c: +0,o: +0,n: +0,....r: +0". So we need to convert the string back. We use this function to do the convert:

ƒ=(Τ,$=+[])=>Τ[$]?Τ[$]+ƒ(Τ,++$+'5'[+[]]*(Τ[$]==':')):''

Τ is the text inputed, $ is index. We first initialize $ to 0 using +[]. Then we output the character at the index position, and check if next character is ":", if so we skip the following 5 characters.

Thanks to l4m2, saves few bytes.


APL (dzaima/APL), 8 bytes

128(⊣⊥|)

Try it online!
How:
128(⊣⊥|) ⍝ Anonymous function
128   |  ⍝ Input modulo 128
    ⊣⊥   ⍝ Decoded from base 128


JavaScript (ES6), 256 ... 229 227 bytes

Takes input as two strings (p, s), where p is the case-insensitive name of the piece and s is the source square. Returns a space-separated list of destination squares.

f=(p,s,i=128)=>i--?f(p,s,i)+([x=255,x<<8,2,x,195,60][P=(I=parseInt)(p,32)*5&7]>>i/8&((d=i%8)<(S=(x=I(s,18)-181)/18|x%18*16,P>2?8:P<2|S>23||2))&!((S+=I('gfh1eivx'[i>>4],36)*(i&8?d+1:~d))&136)?'abcdefgh'[S&7]+(S+16>>4)+' ':''):''

How it works

Piece name decoding

The name of the piece p is converted to an integer P by parsing it in base 32, multiplying the result by 5 and isolating the 3 least significant bits: parseInt(p, 32) * 5 & 7

 Piece    | As base 32 |        * 5 | & 7
----------+------------+------------+----
 "king"   |     674544 |    3372720 |  0
 "knight" |  695812669 | 3479063345 |  1
 "pawn"   |        810 |       4050 |  2    NB: 'pawn' is parsed as 'pa', because 'w'
 "queen"  |   28260823 |  141304115 |  3        is not a valid character in base 32
 "rook"   |     910100 |    4550500 |  4
 "bishop" |  388908825 | 1944544125 |  5

In addition to being a perfect hash, a good thing about this formula is that all sliding pieces (Queen, Rook and Bishop) appear at the end of the list, which allows to identify them with a simple P > 2.

Source square decoding

The source square s is converted to an integer S by parsing it in base 18 and converting the result to 0x88 coordinates.

That leads to the following board representation:

     a    b    c    d    e    f    g    h
8  0x70 0x71 0x72 0x73 0x74 0x75 0x76 0x77
7  0x60 0x61 0x62 0x63 0x64 0x65 0x66 0x67
6  0x50 0x51 0x52 0x53 0x54 0x55 0x56 0x57
5  0x40 0x41 0x42 0x43 0x44 0x45 0x46 0x47
4  0x30 0x31 0x32 0x33 0x34 0x35 0x36 0x37
3  0x20 0x21 0x22 0x23 0x24 0x25 0x26 0x27
2  0x10 0x11 0x12 0x13 0x14 0x15 0x16 0x17
1  0x00 0x01 0x02 0x03 0x04 0x05 0x06 0x07

Directions encoding

There are 16 possible directions: 4 along ranks and files, 4 along diagonals and 8 for the knights.

As hexadecimal:                     As decimal:

      +0x1F       +0x21                    +31         +33
+0x0E +0x0F +0x10 +0x11 +0x12        +14   +15   +16   +17   +18
      -0x01 [SRC] +0x01                     -1  [SRC]   +1
-0x12 -0x11 -0x10 -0x0F -0x0E        -18   -17   -16   -15   -14
      -0x21       -0x1F                    -33         -31

Therefore, the list of directions that a piece can move towards can be encoded as a 16-bit bitmask.

Bit:    |   F   E   D   C   B   A   9   8   7   6   5   4   3   2   1   0 | As
Vector: | +33 -33 +31 -31 +18 -18 +14 -14  +1  -1 +17 -17 +15 -15 +16 -16 | decimal
--------+-----------------------------------------------------------------+--------
King    |   0   0   0   0   0   0   0   0   1   1   1   1   1   1   1   1 | 255
Knight  |   1   1   1   1   1   1   1   1   0   0   0   0   0   0   0   0 | 65280
Pawn    |   0   0   0   0   0   0   0   0   0   0   0   0   0   0   1   0 | 2
Queen   |   0   0   0   0   0   0   0   0   1   1   1   1   1   1   1   1 | 255
Rook    |   0   0   0   0   0   0   0   0   1   1   0   0   0   0   1   1 | 195
Bishop  |   0   0   0   0   0   0   0   0   0   0   1   1   1   1   0   0 | 60

The absolute values of the direction vectors can be stored in base 36:

[16, 15, 17, 1, 14, 18, 31, 33][n] <==> parseInt('gfh1eivx'[n], 36)

Formatted and commented

f = (p, s, i = 128) =>                     // given a piece p, a square s and a counter i
  i-- ?                                    // if i is >= 0:
    f(p, s, i) + (                         //   do a recursive call to f()
      [ x = 255, x << 8, 2, x, 195, 60 ][  //   take the direction bitmask for:
        P = (I = parseInt)(p, 32) * 5 & 7  //   P = piece index in [0 .. 5]
      ] >> i / 8 & (                       //   and test the bit for the current direction
        (d = i % 8) < (                    //   d = current move distance - 1
          S = (x = I(s, 18) - 181) / 18 |  //   S = source square in
              x % 18 * 16,                 //       0x88 representation
          P > 2 ? 8 : P < 2 | S > 23 || 2  //   compare d with the maximum move range for
        )                                  //   this piece
      ) ?                                  //   if the above test passes:
        (                                  //     we add to S:
          S += I(                          //       the absolute value of the vector of
            'gfh1eivx'[i >> 4], 36         //       the current direction,
          ) *                              //       multiplied by
          (i & 8 ? d + 1 : ~d)             //       the move distance with the vector sign
        ) & 136 ?                          //     if the result AND'd with 0x88 is not null:
          ''                               //       this is an invalid destination square
        :                                  //     else:
          'abcdefgh'[S & 7] +              //       it is valid: convert it back to ASCII
          (S + 16 >> 4) + ' '              //       and append a space separator
      :                                    //   else:
        ''                                 //     this is an invalid move
    )                                      //   end of this iteration
  :                                        // else:
    ''                                     //   stop recursion

Test cases

f=(p,s,i=128)=>i--?f(p,s,i)+([x=255,x<<8,2,x,195,60][P=(I=parseInt)(p,32)*5&7]>>i/8&((d=i%8)<(S=(x=I(s,18)-181)/18|x%18*16,P>2?8:P<2|S>23||2))&!((S+=I('gfh1eivx'[i>>4],36)*(i&8?d+1:~d))&136)?'abcdefgh'[S&7]+(S+16>>4)+' ':''):''

console.log(f('Rook',   'a8'));
console.log(f('Pawn',   'a2'));
console.log(f('Pawn',   'a3'));
console.log(f('Knight', 'a1'));
console.log(f('Bishop', 'h1'));
console.log(f('King',   'b2'));
console.log(f('Queen',  'h1'));


CJam, 45 bytes

q"-F"/"1 -"*"+F"/"1Y$-*+"*'F-S/)d\2/'\f*W%S*~

Uses precedence rule 6: strictly right-to-left. It expects ASCII input.

Take it for a spin!

Explanation

Read input, and perform the following transformations in order:

"-F"   to   "1 -"
"+F"   to   "1Y$-*+"
 "F"   to   ""

Then split over spaces (S/). Extract the rightmost element and convert it to a double ()d). Then take pairs from the rest of the list (\2/), join them all by \ ('\f*) and evaluate the resulting strings as CJam code in reverse order (W%S*~).

For example, it converts 5 +F 10 + 3

to 5 1Y$-*+ 10 + 3 in the first step,
then to 3 [["10" "+"] ["5" "1Y$-*+"]],
then to 3 ["10\+" "5\1Y$-*+"],
then to 3 10\+ 5\1Y$-*+, which is CJam code that computes the right answer, -47.


Python 2, 58 bytes

f=lambda n:(n>15and f(n/16)or"")+"HBKD"[n/4%4]+"OAEI"[n%4]

A recursive solution. Try it on Ideone.


Checking a Windows 95 OEM Key for validity

perl -pl -MList::Util=sum, 106 113 bytes

$_=/^(?!000)(([012]\d\d|3([0-5]\d|6[0-5]))(9[5-9]|0[0-3])|366(00|96))-OEM-00(\d{5})-\d{5}$/&&!(sum(split//,$6)%7)

Try it online!

This assumes an ASCII only input. If the input can be outside of ASCII, we'd have to add a single extra byte (a trailing a modifier on the main regexp). It also assumes a leading 366 can only occur in the years 96 and 00, them being leap years. The bulk of the matching is done by a regexp; testing of divisibility by 7 is done outside of it.

Reads keys from STDIN; writes 1 to STDOUT for valid keys, empty lines for invalid keys.

Edit: fixed the issue mentioned by @Dingus.


APL (34 30)

(1⍳⍨+/∘.=⍨2|⎕)⊃'ABC',⊂'no one'

Explanation:

2|⎕: read a line of input, take the mod-2 of each number (giving a list, i.e. 1 0 1)
∘.=⍨: compare each element in the vector to each element in the vector, giving a matrix
+/: sum the rows of the matrix, giving for each element how many elements it was equal to. If there were two the same and one different, we now have a vector like 2 1 2 where the 1 denotes who was different. If they were all the same, we get 3 3 3.
1⍳⍨: find the position of the 1. If there is no 1, this returns one more than the length of the vector, in this case 4.
⊃'ABC',⊂'no one': display the string at the given index.


APL (Dyalog), 13 bytes

-1 bytes thanks to ngn

{⊃⍸⍵≤+\÷⍳⌈*⍵}

Try it online!

A dfn solution that takes a right argument.

Explanation:

{           }   ⍝ dfn
 ⊃              ⍝ Take the first of
  ⍸             ⍝ The indexes of the truthy values of
   ⍵≤           ⍝ The right argument is smaller than or equal to
     \+         ⍝ The cumulative sum
       ÷        ⍝ The reciprocal of each of
        ⍳       ⍝ The range 1 to
         ⌈      ⍝ The ceiling of
          *⍵    ⍝ e to the power of the right argument


Python 2, 45 41 40 37 bytes

lambda n,j,x:range(j-x/2,x%2or n-x,j)

Pretty much the trivial solution. I just quickly scanned for patterns and found a pattern. 1-indexed, 1 is at the back of the queue.

-4 bytes by avoiding ternaries and using an array for the values instead
-1 byte thanks to some inspiration from @DeadPossum, by using and instead of ternaries or array selectors
-3 bytes by switching to or in the opposite order. Only works because of 1-indexing

Also, crossed out 4 is still 4 on all of the 4s :(

Try it online!


JavaScript (Firefox 30-57), 74 73 bytes

(a,[s],i=0,p)=>[for(e of a)if({i:e>p,d:e<p,o:e<2,t:e>1,a:1}[p=e,i++,s])i]

Array comprehensions are a neat way of combining map and filter in one go. Edit: Saved 1 byte thanks to @edc65.


Recursion bracketed; or Dyck words generation

C99, 105 bytes

i,j,s;f(n){for(char a[31]={};++i%(1<<2*n);s||puts(a))for(j=s=0;~s&&j<2*n;)s+=1-(a[j]=40+(i>>j++)%2)%2*2;}

Iterates over all strings of 2n parentheses.

With piped output and compiler flag -O3, input n = 15 takes roughly 15.5 seconds on my machine. Memory consumption is 1.2 MB.

Test it on Ideone.


171 bytes1

Wooohoooo! It took half the day, but it was fun...

So, here it is. I think it conforms to the specs (wraparound of cell pointer, echo of characters on input, reading char by char, echo of input chars, ...), and it seems to actually work (well, I didn't try many programs, but given the simplicity of the language, the coverage isn't that bad, I think).

Limitations

One important thing: if your brainfuck program contains other chars than the 8 brainfuck instructions, or if the [] are not well-balanced, it will crash on you, mouhahahaha!

Also, the brainfuck program can't exceed 512 bytes (a sector). But this seems conforming since you say "executable Brainfuck is located at second disk sector".

Last detail: I didn't explicitly initialized the cells to zero. Qemu seem to do it for me, and I'm relying on this, but I don't know whether a real BIOS on a real computer would do it (initialization would just take a few bytes more, anyway).

The code

(based on your template, and by the way, thanks for this, I would never have tried without it):

[BITS 16]
[ORG 0x7C00]

%define cellcount 30000 ; you can't actually increase this value much beyond this point...

; first sector:

boot:
    ; initialize segment registers
    xor ax, ax
    mov ss, ax
    mov ds, ax
    mov es, ax
    jmp 0x0000:$+5

    ; initialize stack
    mov sp, 0x7bfe

    ; load brainfuck code into 0x8000
    ; no error checking is used
    mov ah, 2       ; read
    mov al, 1       ; one sector
    mov ch, 0       ; cylinder & 0xff
    mov cl, 2       ; sector | ((cylinder >> 2) & 0xc0)
    mov dh, 0       ; head
                    ; dl is already the drive number
    mov bx, 0x8000  ; read buffer (es:bx)
    int 0x13        ; read sectors

    ; initialize SI (instruction pointer)
    mov si, bx ; 0x8000
    ; initialize DI (data pointer)
    mov bh, 0x82
    mov di, bx ; 0x8200

decode:
    lodsb ; fetch brainfuck instruction character
.theend:
    test al, al ; endless loop on 0x00
    jz .theend
    and ax, 0x0013 ; otherwise, bit shuffling to get opcode id
    shl ax, 4
    shl al, 2
    shr ax, 1
    add ax, getchar ; and compute instruction implementation address
    jmp ax

align 32, db 0

getchar:
    xor ah, ah
    int 0x16
    cmp al, 13
    jne .normal
    mov al, 10 ; "enter" key translated to newline
.normal:
    mov byte [di], al
    push di
    jmp echochar

align 32, db 0

decrementdata:
    dec byte [di]
    jmp decode

align 32, db 0

putchar:
    push di
    mov al, byte [di]
echochar:
    mov ah, 0x0E
    xor bx, bx
    cmp al, 10 ; newline needs additional carriage return
    jne .normal
    mov al, 13
    int 0x10
    mov al, 10
.normal:
    int 0x10
    pop di
    jmp decode

align 32, db 0

incrementdata:
    inc byte [di]
    jmp decode

align 32, db 0

decrementptr:
    dec di
    cmp di, 0x8200 ; pointer wraparound check (really, was that necessary?)
    jge decode
    add di, cellcount
    jmp decode

align 32, db 0

jumpback:
    pop si
    jmp jumpforward

align 32, db 0

incrementptr:
    inc di
    cmp di, 0x8200+cellcount  ; pointer wraparound check
    jl decode
    sub di, cellcount
    jmp decode

align 32, db 0

jumpforward:
    cmp byte [di], 0
    jz .skip
    push si
    jmp decode
.skip:
    xor bx, bx ; bx contains the count of [ ] imbrication
.loop:
    lodsb
    cmp al, '['
    je .inc
    cmp al, ']'
    jne .loop
    test bx, bx
    jz decode
    dec bx
    jmp .loop
.inc:
    inc bx
    jmp .loop

; fill sector
times (0x1FE)-($-$$) db 0

; boot signature
db 0x55, 0xAA

; second sector contains the actual brainfuck program
; currently: "Hello world" followed by a stdin->stdout cat loop

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

times 0x400-($-$$) db 0

Tricks used

Ok, I cheated a bit. Since you said "being a bootloader, the size of the program is counted in non-zero bytes in the compiled code", I made the code smaller by allowing "holes" between the implementation of the eight brainfuck opcodes. This way, I don't need a big sequence of tests, a jump table, or anything: I just jump to the brainfuck "opcode id" (from 0 to 8) multiplied by 32 to execute the brainfuck instruction (worth to note that it means the implementation of the instructions can't take more than 32 bytes).

Moreover, to get this "opcode id" from the brainfuck program character fetched, I noticed just a bit of bit shuffling was necessary. Indeed, if we just consider bits 0, 1 and 4 of the opcode character, we end up with the 8 unique combinations:

   X  XX
00101100 0x2C , Accept one byte of input, storing its value in the byte at the pointer.
00101101 0x2D - Decrement (decrease by one) the byte at the pointer.
00101110 0x2E . Output the value of the byte at the pointer.
00101011 0x2B + Increment (increase by one) the byte at the pointer.
00111100 0x3C < Decrement the pointer (to point to the next cell to the left).
01011101 0x5D ] Jump back after the corresp [ if data at pointer is nonzero.
00111110 0x3E > Increment the pointer (to point to the next cell to the right).
01011011 0x5B [ Jump forward after the corresp ] if data at pointer is zero.

And, lucky me, there is actually one opcode that requires more than 32 bytes to implement, but it's the last one (jump forward [). As there is more room after, everything is fine.

Other trick: I don't know how a typical brainfuck interpreter works, but, to make things much smaller, I did not actually implement ] as "Jump back after the corresponding [ if data at pointer is nonzero". Instead, I always go back to the corresponding [, and, from here, re-apply the typical [ implementation (which then, eventually, goes forward after the ] again if needed). For this, each time I encouter a [, I put the current "brainfuck instruction pointer" on the stack before executing the inner instructions, and when I encounter a ], I pop back the instruction pointer. Pretty much as if it was a call to a function. You could therefore theoretically overflow the stack by making many many imbricated loops, but not with the current 512-bytes limitation of the brainfuck code, anyway.

1. Including the zero bytes that were part of the code itself, but not those that were part of some padding


CJam, 53 52 47 bytes

l~"X    0'ò"2/Dfb+:%"gÇâì6Ô¡÷Ç8nèS¡a"312b2b=

There's unprintables, but the two strings can be obtained by

[88 9 48 5 39 5 29 1 242]:c
[8 103 199 226 236 54 212 15 161 247 199 56 110 232 83 161 97]:c

respectively. This also shows that the code points are below 256.

This is a modulo chain answer, where we apply the following modulos to the input integer, in order:

[1153 629 512 378 242 136]

Since this list contains integers greater than 255, the list is encoded using two chars each. The decoding is done by 2/Dfb, which splits the string into chunks of length two and converts each from a base 13 number (e.g. 88*13 + 9 = 1153). However, there are two exceptions to the decoding:

The last number (136) is not included (see below),
The second-last number is represented by a single char, since the number (242) is less than 256 and splitting an odd-length array into chunks of size 2 will leave a size 1 array at the end. Thanks to @MartinBüttner for this tip!

Once the modulos have reduced the input integer to a relatively small number, we perform a lookup from a table. This table is encoded via the second string, which is converted to a base 312 number then decoded to base 2, which we index. Since CJam's array indexing wraps, we can leave out the final modulo as mentioned earlier.

Try it online | Test suite


Which languages are optimal for problems that require "reading" input while also writing to it like a stack

The approach you're asking seems like reduce/left fold in general. Many languages have this, such as Python (reduce(f,seq) or functools.reduce(f,seq)), APL (f⍨/⌽seq), Jelly (f/seq), and Haskell (foldl f start seq).
As a Python example, let's assume we already have the input parsed as a list seq=[1, 'AND', 0, 'OR', 1, 'XOR', 1]. Then reduce(f,seq) is equivalent to
f(f(f(f(f(f(1, 'AND'), 0), 'OR'), 1), 'XOR'), 1)

The trouble here is that we need to take 3 arguments at a time. A way this could be done is by grouping most of the sequence into pairs seq2=[1, ['AND',0], ['OR',1], ['XOR',1]], so reduce(f,seq) would be equivalent to
f(f(f(1, ['AND',0]), ['OR',1]), ['XOR',1])

This could work well in Jelly because it has a builtin s that could help split into pairs (output looks funny strings are internally lists of chars).
However, a loop-based approach would work better in Python by assigning to a slice of an array:
seq=[1, 'AND', 0, 'OR', 1, 'XOR', 1]
while len(seq)>1:
  seq[1:3] = [f(*seq[1:3])]
print(seq[0])

This would output f(f(f(1, 'AND', 0), 'OR', 1), 'XOR', 1).
As @AdHocGarfHunter notes in the comments, recursion is a good idea too:
# (ungolfed)
def r(s):
  if len(s)>1:
    return r(f(*s[:3]) + s[3:])
  else:
    return s[0]

APL has little boilerplate for this: {1=⍴⍵:⊃⍵⋄∇(3↓⍵),f3↑⍵} (∇ is the recursion). Jelly does too, with 1 byte recursion.


We're Spiralling out of control, Doctor!

JavaScript (ES6) 124 163 177

Edit Totally different way, no need of an array to store visited cells. Using the fact that the side of the spiral increase of 1 after every 2 turns.

// New way
f=(h,w,y,x)=>
  (e=>{
    for(o=[],d=i=t=l=0;l<w*h;i<t?i+=2:[i,d,e]=[1,-e,d,++t])
      o[l]=y*w-w+x,l+=x>0&x<=w&y>0&y<=h,x+=d,y-=e
  })(1)||o

// Golfed
g=(h,w,y,x)=>
  (g=>{
    for(e=n=0;n<h*w;)g[[n%w+1,-~(n/w)]]=++n;
    for(o=[g[[x,y]]],l=d=1;l<n;l+=!!(o[l]=g[[x+=d,y+=e]]))
      g[[x,y]]=0,
      g[[x+e,y-d]]!=0&&([d,e]=[e,-d])
  })([])||o

// Not golfed
u=(h,w,y,x)=>{
  var i,j,dx,dy,kx,ky,o,n,
    g={} // simulate a 2dimensional array using a hashtable with keys in the form 'x,y'

  for(n=i=0; i++<h;) // fill grid (probably better done in a single loop)
    for(j=0; j++<w;)
      g[[j,i]] = ++n;
  o=[g[[x,y]]] // starting point in output
  dx=1, dy=0 // start headed right

  for(; !o[w*h-1]; ) // loop until all w*h position are put in output
  {
    g[[x, y]] = 0 // mark current position to avoid reusing
    kx=dy, ky=-dx // try turning left
    if(g[[x+kx, y+ky]] != 0) // check if position marked
    { // found a valid position
      dx=kx, dy=ky // change direction
    }
    x+=dx, y+=dy // move
    k=g[[x, y]] // get current value
    if (k) o.push(k) // put in output list if not 'undefined' (outside grid)
  }
  return o
}

// TEST - In FireFox

out=x=>O.innerHTML+=x+'\n';
[
 [[5,5,3,3],'13 8 7 12 17 18 19 14 9 4 3 2 1 6 11 16 21 22 23 24 25 20 15 10 5'],
 [[2,4,1,2],'2 1 5 6 7 3 8 4']
].forEach(t=>out(t[0] + '\n Result: ' + f(...t[0])+'\n Check:  ' + t[1]))

test=()=>
{
  var r, i=I.value.match(/\d+/g), h=i[0]|0, w=i[1]|0, y=i[2]|0, x=i[3]|0
  if (y>h||x>w) r = 'Invalid input'
  else r = f(h,w,y,x)
  out(i+'\n Reault: ' +r)
}

Your test:<input id=I><button onclick="test()">-></button>


QBasic (56)

A$="CCGGAAG2FFEEDDC2"
B$="GGFFEED2"
PLAY "L4"+A$+B$+B$+A$

Focus is on reminiscence :)

(Don't have a QBasic to test this though)


8086 MS-DOS .COM file / BMP, output file size = 2192 bytes

Encoder

The encoder is written in C. It takes two arguments: Input file and output file. The input file is a 64x64 RAW RGB image (meaning it is simply 4096 RGB triplets). Number of colours is limited to 4, so that the palette can be as short as possible. It is very straight-forward in its doings; it merely builds a palette, packs pixels pairs into bytes and glues it together with pre-made headers and the decoder program.

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

#define MAXPAL      4
#define IMAGESIZE   64 * 64

int main(int argc, char **argv)
{
    FILE *fin, *fout;
    unsigned char *imgdata = malloc(IMAGESIZE * 3), *outdata = calloc(IMAGESIZE / 2, 1);
    unsigned palette[MAXPAL] = {0};
    int pal_size = 0;

    if (!(fin = fopen(argv[1], "rb")))
    {
        fprintf(stderr, "Could not open \"%s\".\n", argv[1]);
        exit(1);
    }

    if (!(fout = fopen(argv[2], "wb")))
    {
        fprintf(stderr, "Could not open \"%s\".\n", argv[2]);
        exit(2);
    }

    fread(imgdata, 1, IMAGESIZE * 3, fin);

    for (int i = 0; i < IMAGESIZE; i++)
    {
        // BMP saves the palette in BGR order
        unsigned col = (imgdata[i * 3] << 16) | (imgdata[i * 3 + 1] << 8) | (imgdata[i * 3 + 2]), palindex;
        int is_in_pal = 0;

        for (int j = 0; j < pal_size; j++)
        {
            if (palette[j] == col)
            {
                palindex = j;
                is_in_pal = 1;
            }
        }

        if (!is_in_pal)
        {
            if (pal_size == MAXPAL)
            {
                fprintf(stderr, "Too many unique colours in input image.\n");
                exit(3);
            }

            palindex = pal_size;
            palette[pal_size++] = col;
        }

        // High nibble is left-most pixel of the pair
        outdata[i / 2] |= (palindex << !(i & 1) * 4);
    }

    char BITMAPFILEHEADER[14] = {
        0x42, 0x4D,                 // "BM" magic marker
        0x90, 0x08, 0x00, 0x00,     // FileSize
        0x00, 0x00,                 // Reserved1
        0x00, 0x00,                 // Reserved2
        0x90, 0x00, 0x00, 0x00      // ImageOffset
    };

    char BITMAPINFOHEADER[40] = {
        0x28, 0x00, 0x00, 0x00,     // StructSize
        0x40, 0x00, 0x00, 0x00,     // ImageWidth
        0x40, 0x00, 0x00, 0x00,     // ImageHeight
        0x01, 0x00,                 // Planes
        0x04, 0x00,                 // BitsPerPixel
        0x00, 0x00, 0x00, 0x00,     // CompressionType (0 = none)
        0x00, 0x00, 0x00, 0x00,     // RawImagDataSize (0 is fine for non-compressed,)
        0x00, 0x00, 0x00, 0x90,     // HorizontalRes
                                    //      db 0, 0, 0
                                    //      nop
        0xEB, 0x1A, 0x90, 0x90,     // VerticalRes
                                    //      jmp Decoder
                                    //      nop
                                    //      nop
        0x04, 0x00, 0x00, 0x00,     // NumPaletteColours
        0x00, 0x00, 0x00, 0x00,     // NumImportantColours (0 = all)
    };

    char DECODER[74] = {
        0xB8, 0x13, 0x00, 0xCD, 0x10, 0xBA, 0x00, 0xA0, 0x8E, 0xC2, 0xBA,
        0xC8, 0x03, 0x31, 0xC0, 0xEE, 0x42, 0xBE, 0x38, 0x01, 0xB1, 0x04,
        0xFD, 0x51, 0xB1, 0x03, 0xAC, 0xD0, 0xE8, 0xD0, 0xE8, 0xEE, 0xE2,
        0xF8, 0x83, 0xC6, 0x07, 0x59, 0xE2, 0xEF, 0xFC, 0xB9, 0x00, 0x08,
        0xBE, 0x90, 0x01, 0xBF, 0xC0, 0x4E, 0xAC, 0xD4, 0x10, 0x86, 0xC4,
        0xAB, 0xF7, 0xC7, 0x3F, 0x00, 0x75, 0x04, 0x81, 0xEF, 0x80, 0x01,
        0xE2, 0xEE, 0x31, 0xC0, 0xCD, 0x16, 0xCD, 0x20,
    };

    fwrite(BITMAPFILEHEADER, 1, 14, fout);
    fwrite(BITMAPINFOHEADER, 1, 40, fout);
    fwrite(palette, 4, 4, fout);
    fwrite(DECODER, 1, 74, fout);

    // BMPs are stored upside-down, because why not
    for (int i = 64; i--; )
        fwrite(outdata + i * 32, 1, 32, fout);

    fclose(fin);
    fclose(fout);
    return 0;
}

Output file

The output file is a BMP file which can be renamed .COM and run in a DOS environment. Upon execution, it will change to video mode 13h and display the image.

A BMP file has a first header BITMAPFILEHEADER, which contains among other things the field ImageOffset, which denotes where in the file the image data begins. After this comes BITMAPINFOHEADER with various de-/encoding information, followed by a palette, if one is used. ImageOffset can have a value that points beyond the end of any headers, allowing us to make a gap for the decoder to reside in. Roughly:

BITMAPFILEHEADER
BITMAPINFOHEADER
PALETTE
<gap>
IMAGE DATA

Another problem is to enter the decoder. BITMAPFILEHEADER and BITMAPINFOHEADER can be tinkered with to make sure they are legal machine code (which does not produce a non-recoverable state), but the palette is trickier. We could of course have made the palette artificially longer, and put the machine code there, but I opted to instead use the fields biXPelsPerMeter and biYPelsPerMeter, the former to make the code aligned properly, and the latter to jump into the decoder. These fields will of course then have garbage in them, but any image viewer I have tested with displays the image fine. Printing it might produce peculiar results, though.

It is, as far as I know, standard-compliant.

One could make a shorter file if the JMP instruction was put in one of the reserved fields in BITMAPFILEHEADER. This would allow us to store the image height as -64 instead of 64, which in the magical wonderland of BMP files means that the image data is stored the right way up, which in turn would allow for a simplified decoder.

Decoder

No particular tricks in the decoder. The palette is populated by the encoder, and shown here with dummy-values. It could be slightly shorter if it did not return to DOS upon a keypress, but it was not fun testing without that. If you feel you must, you can replace the last three instructions with jmp $ to save a few bytes. (Don't forget to update the file headers if you do!)

BMP stores palettes as BGR (not RGB) triplets, padded with zeroes. This makes setting up the VGA palette more annoying than usual. The fact that BMPs are stored upside-down only adds to the flavour (and size).

Listed here in NASM style:

Palette:
    db 0, 0, 0, 0
    db 0, 0, 0, 0
    db 0, 0, 0, 0
    db 0, 0, 0, 0

Decoder:
    ; Set screen mode
    mov ax, 0x13
    int 0x10

    mov dx, 0xa000
    mov es, dx

    ; Prepare to set palette
    mov dx, 0x3c8
    xor ax, ax
    out dx, al

    inc dx
    mov si, Palette + 2
    mov cl, 4
    std
pal_loop:
    push cx
    mov cl, 3
pal_inner:
    lodsb
    shr al, 1
    shr al, 1
    out dx, al
    loop pal_inner

    add si, 7
    pop cx
    loop pal_loop
    cld

    ; Copy image data to video memory
    mov cx, 64 * 64 / 2
    mov si, ImageData
    mov di, 20160
img_loop:
    lodsb
    aam 16
    xchg al, ah
    stosw
    test di, 63
    jnz skip
    sub di, 384
skip:
    loop img_loop

    ; Eat a keypress
    xor ax, ax
    int 0x16

    ; Return to DOS
    int 0x20

ImageData:


pb, 240 bytes

<[8]^w[Y!14]{w[X!24]{>[8]b[124]^b[124]v}vw[X!-8]{b[45]<}vv}>[12]^[12]b[49]>[12]w[T!8]{<[4]b[T+50]^<w[X%8!6]{b[65+T*3+X%8%3]>}>[10]vw[B!124]{<[24]vvv}t[T+1]}<[4]b[42]>[8]b[48]>[8]b[35]^[4]>w[B!0]{b[B+2]<}b[87]w[X!2]{<[5]w[B!0]{b[B+1]<}}b[80]

(This program will prompt for input in the current version of pbi, because it goes to Y=-1 and the B variable tries to update itself. Even if you do enter input, nothing will break. It's annoying but it's better than the old version that prompted for input no matter what.)

pb is a language all about treating the terminal as a 2D canvas. To output, you have to move the "brush" (a point represented by the current values of the X and Y variables) to where you want that character to go and put it there. It's cumbersome for things like printing out a word but for art it's often convenient.

This program doesn't actually draw exactly what the question specifies. (Wait, don't downvote me yet! Let me explain!)

Drawing boxes with loops is pretty easy, but there's a catch. If you repeat the following shape:

--------
|
|

You do get boxes, but the right and bottom ones will be open. You can manually draw the extra sides, but that costs bytes. To get around this, my program actually draws this, with the open edges on the left and top:

        |       |       |       |
        |       |       |       |
 --------------------------------
        |       |  ABC  |  DEF  |
        |   1   |   2   |   3   |
 --------------------------------
        |  GHI  |  JKL  |  MNO  |
        |   4   |   5   |   6   |
 --------------------------------
        | PQRS  |  TUV  | WXYZ  |
        |   7   |   8   |   9   |
 --------------------------------
        |       |       |       |
        |   *   |   0   |   #   |
 --------------------------------

  But monorail! That's not what the spec says! You can't just draw something else because it's easier and you feel like it! Also, while I have your attention, you are very smart and cute.

Shh, shh, it's okay. pb allows you to "write" to a point on the canvas with one or more negative values in its coordinates. The value is stored while the program runs, but only points where X and Y are both >= 0 are actually written to the screen. This program positions the brush so that areas that are tinted in this image have a negative X or Y:

Although extra lines are "drawn", they're never printed.

After looping through and creating the grid, this program fills in the top nine boxes. The first is hardcoded, a 1 is written and the program moves on. The other eight are generated programmatically. Ignoring code for moving to the next box, noticing when the row is empty, etc (assume the brush always starts on the bottom row of the box and in the middle column), this is what is run eight times:

b[T+50]
^<w[X%8!6]{b[65+T*3+X%8%3]>}
t[T+1]

Even knowing that b is the command to write a character, ^v<> move the brush and w[a!b]{} runs the code in curly braces until a != b, this is hard to follow. The first important thing to note is that you can't define variables in pb. There are six in every program and you have to learn to live with them. Second, T is the only variable that you can actually use the way you're used to using variables; assigning a value and then reading it later. Every other variable either can't be set and just tells you something about the point in the canvas you're on or can only be set indirectly and with side effects (^v<> change X and Y, which also changes the brush location. c sets P to (P+1)%8, which also changes the output colour). Keeping a counter for what number needs to be written and which letters is simply impossible. Instead, this code only keeps track of the number and figures out the letters based on it. Here's how:

b[T+50]                       # We start printing at box 2 with T==0, 0+50=='2'
^<                            # Go up and to the left of the number
w[X%8!6]{                     # Take the X coordinate mod 8 so it's like we're in
                              # the leftmost box. Until hitting the sixth cell:
    b[                          # Write this character:
      65                          # 'A'
      + T * 3                     # Number of current box - 2 (letters start at
                                  # 2) * 3 (3 letters per box)
      + X % 8 % 3                 # X % 8 makes every box behave like it's on the
                                  # left, % 3 puts 0 at the point where the first
                                  # letter goes, then 1, then 2. This is how each
                                  # letter is made different in a box.
    ]
    >                           # Move to the right
}
t[T+1]                        # Box is done, increase counter

This is imperfect, as only 3 letters are put into boxes 7 and 9. So, after filling the bottom row (simple hardcoding), each letter in box 9 is increased by 2 and the W is placed manually. Similarly, every letter in boxes 7 and 8 are increased by 1 and the P is placed manually.

Ungolfed:

<[8]^                         # Go to (-8, -1)
w[Y!14]{                      # While the brush is not on Y=14:
    w[X!24]{                      # While the brush is not on X=24:
        >[8]                          # Go right 8
        b[124]^b[124]v                # Draw a pipe at the current location and above it
    }
    vw[X!-8]{b[45]<}              # Go down and draw hyphens all the way until X=-8
    vv                            # Go down by 2 to start drawing next row
}
>[12]^[12]b[49]               # Write a 1 in the first box
>[12]                          # Go to the bottom pipe on the right of box 2
w[T!8]{                       # While T is not 8:
    <[4]                          # Go to center cell of the box
    b[T+50]                       # Write the number that belongs there
    ^<w[X%8!6]{b[65+T*3+X%8%3]>}  # Write the letters
    >[10]v                        # Go to the next box
    w[B!124]{                     # If the next box isn't there:
        <[24]vvv                      # Go down a row
    }
    t[T+1]                        # Increase counter
}
<[4]b[42]>[8]b[48]>[8]b[35]   # Put the asterisk, 0 and hash in their boxes
^[4]>w[B!0]{b[B+2]<}          # Increase all letters in the 9th box by 2
b[87]                         # Put a W in the 9th box
w[X!2]{<[5]w[B!0]{b[B+1]<}}   # Increase all letters in the 7th/8th box by 1
b[80]                         # Put a P in the 7th box


Calling a Dyad

Assuming you had a dyadic (2-argument) function f:

f: {x+2*y}

You would ordinarily call it like so:

f[3;47]

You can save a character by instead currying in the first argument and then applying the resulting partial function to the second argument by juxtaposition:

f[3]47

The same naturally works for array indexing:

  z: (12 17 98;90 91 92)
(12 17 98
 90 91 92)

  z[1;2]
92

  z[1]2
92


Jelly, 4 bytes

‘æRḤ

Try it online!

waiting for OP's answer in comment...

(doesn't work for n=1)


In what base this string equals the following decimal value?

Mathematica, 183 bytes * 0.7 = 128.1

f[s_,n_]:=(For[i=2,1>0,++i,d=(l=Length)@(g=IntegerDigits)[n,i];Which[Count[c=Characters@s,c[[-1]]]>1&&d==1,Return@0,l@c>=d&&And@@Unequal@@@(t=Thread)@Union@t@{g[n,i,l@c],c},Print@i]])

Less golf

f[s_, n_] := (
  For[i = 2, 1 > 0, ++i,
   d = (l = Length)@(g = IntegerDigits)[n, i];
   Which[
    Count[c = Characters@s, c[[-1]]] > 1 && d == 1,
    Return@0,
    l@c >= d && And @@
      Unequal @@@
       (t = Thread)@
        Union@
         t@
          {g[n, i, l@c], c},
    Print@i
    ]
   ]
  )

I don't actually recommend running this, because quick and infinite output is a bit tricky to abort in Mathematica sometimes. To get only the first result, change Print to Result (which is even a character longer). If you're using the version as is, a final 0 output will indicate that no further bases will be found (similar to the returning case).

The first part of the Which simply aborts the loop when no base can possibly be found (it might be possible to shorten this). The second loop is the interesting check. These are the steps taken:

Convert n to digits in the current base (Mathematica can handle arbitrarily large bases.)
Zip those digits up with the characters, basically creating the mapping at each position.
Union throws out duplicates - these are uninteresting because they just point to a consistent mapping.
Transpose the mapping, so I get a list of digits and a list of characters.
If there are no duplicates in either, we have an injective mapping and print the base.


Oasis, 3 bytes

The program is 0-indexed. Code:

<q2

Uses the formula: a(n) = nth_prime(a(n-1) - 1), with the base case a(0) = 2.

Code explanation:

  2   = a(0)

<     # Decrement a(n - 1) to get a(n - 1) - 1
 q    # prime(a(n - 1) - 1)

Try it online!


Python 3, 124 bytes

def f(n):
 while n&4369<n/n:n>>=1
 while n&15<1:n>>=4
 return'TJLZSIO'["rēȣc63ıGtĲȱᄑ@'̢̑@@@@Ȳq".index(chr(n))%7]

Try it online!

Expects an integer n representing a 4 × 4 binary matrix. Throws if no tetromino is found.

Line 2 slides the shape to the right until a 1 is in the rightmost column. (4369 is 0001 0001 0001 0001 in binary.) Line 3 lowers the shape until a 1 is in the bottom row. Together this turns e.g.:

    0 1 0 0        0 0 0 0
    1 1 1 0  into  0 0 0 0
    0 0 0 0        0 0 1 0
    0 0 0 0        0 1 1 1

Then we look for the index of n in this list:

 [114  275  547   99   54   15   51
  305   71  116  306  561 4369   64
   39  802  785   64   64   64   64
  562  113   23]
#   T    J    L    Z    S    I    O

Each column of indices equivalent modulo 7 corresponds to a tetromino shape. 64 (@) is used as a padding value as n cannot be 64 at this point in the code.

NB. An exception is thrown for input 0 by computing n/n instead of 1.


R, 46 bytes

for(i in scan():0){cat(i,"\n");Sys.sleep(i/i)}

Crashes after printing 0 because the sleep function is called using 0/0 which returns NaN in R:

Error in Sys.sleep(time) : invalid 'time' value


x86 Linux, AT&T syntax: 244

push $10
push $34
push $s
push $34
push $37
push $37
push $s
call printf
mov $0,%ebx
mov $1,%eax
int $128
s:.ascii "push $10
push $34
push $s
push $34
push $37
push $37
push $s
call printf
mov $0,%cebx
mov $1,%ceax
int $128
s:.ascii %c%s%c%c"

(I compiled it with this: gcc -nostartfiles -lc quine.S -o quine)


Which Friends characters were really the best friends?

Haskell, 187 bytes

f=g.(>>=(q.words)).lines
g t=p"CJMPRS">>=(\k->show(sum.map snd$filter((==k).fst)t)++' ':k++"\n")
q[n]=[("",read n)]
q[n,s]=[(k,read n)|k<-tail$p s]
p s=map concat$sequence[[[],[c]]|c<-s]

f is a function that takes the input, as a single multi-line string, and returns the multi-line output as single string. Probably plenty left to golf here.

λ: putStr test1
504 CRS
1 J
199 J
345 MP
980
2000 CJMPRS

λ: putStr $ f test1
980
2504 S
2504 R
2504 RS
2345 P
2000 PS
2000 PR
2000 PRS
2345 M
2000 MS
2000 MR
2000 MRS
2345 MP
2000 MPS
2000 MPR
2000 MPRS
2200 J
2000 JS
2000 JR
2000 JRS
2000 JP
2000 JPS
2000 JPR
2000 JPRS
2000 JM
2000 JMS
2000 JMR
2000 JMRS
2000 JMP
2000 JMPS
2000 JMPR
2000 JMPRS
2504 C
2504 CS
2504 CR
2504 CRS
2000 CP
2000 CPS
2000 CPR
2000 CPRS
2000 CM
2000 CMS
2000 CMR
2000 CMRS
2000 CMP
2000 CMPS
2000 CMPR
2000 CMPRS
2000 CJ
2000 CJS
2000 CJR
2000 CJRS
2000 CJP
2000 CJPS
2000 CJPR
2000 CJPRS
2000 CJM
2000 CJMS
2000 CJMR
2000 CJMRS
2000 CJMP
2000 CJMPS
2000 CJMPR
2000 CJMPRS


APL

vs←{
    n←'Scissors' 'Paper' 'Rock' 'Lizard' 'Spock'
    x←n⍳⊂⍺ ⋄ y←n⍳⊂⍵ ⋄ X←⍺ ⋄ Y←⍵ ⋄ r←{X,⍵,⊂Y}
    x=y:     r (-x=0)↓'ties'
    y=5|1+x: r x⌷'cut' 'covers' 'crushes' 'poisons' 'smashes'
    y=5|3+x: r x⌷'decapitate' 'disproves' 'breaks' 'eats' 'vaporizes'
    ⍵∇⍺
}

Output exactly as required in all cases, including tie/ties. No lookup table, except for the actual words.

You can try it on http://ngn.github.io/apl/web/

'Spock' vs 'Paper'
Paper  disproves  Spock

APL just knows!


Actually, 17 bytes
"HQ9"∩εj'N'9(t'.j

Try it online!
This program compiles HQ9+ to Actually.
Actually is (almost) a superset of HQ9+ - the only difference is that the 9 command in HQ9+ is N in Actually. Because + is a NOP in HQ9+ (the accumulator is never actually used or displayed, and thus many implementations treat it as a NOP), it is stripped out.
Explanation:
"HQ9"∩εj'N'9(t'.j
"HQ9"∩εj           strip all characters not in "HQ9", preserving order
        'N'9(t     replace all occurrences of "9" with "N"
              '.j  insert a "." between every pair of characters

-1 byte from Christian Irwin


Python 2, score 73  72 71

Edit: -1 thanks to @Jonathan Allan

def f(l,z=0):
&#9for i in map(ord,l):z+=i-[30,9][i&lt32];z*=97
&#9print(len(bin(z))-2)/8or 1

Try it online!


Count the number of cyclic words in an input

Python

Here's my solution. I think it might still be O(n2), but I think the average case is much better than that.

Basically it works by normalizing each string so that any rotation will have the same form. For example:

'amazing' -> 'mazinga'
'mazinga' -> 'mazinga'
'azingam' -> 'mazinga'
'zingama' -> 'mazinga'
'ingamaz' -> 'mazinga'
'ngamazi' -> 'mazinga'
'gamazin' -> 'mazinga'

The normalization is done by looking for the minimum character (by char code), and rotating the string so that character is in the last position. If that character occurs more than once, then the characters after each occurrence are used. This gives each cyclic word a canonical representation, that can be used as a key in a map.

The normalization is n2 in the worst case (where every character in the string is the same, e.g. aaaaaa), but most of the time there's only going to be a few occurrences, and the running time will be closer to n.

On my laptop (dual core Intel Atom @ 1.66GHz and 1GB of ram), running this on /usr/share/dict/words (234,937 words with an average length of 9.5 characters) takes about 7.6 seconds.

#!/usr/bin/python

import sys

def normalize(string):
   # the minimum character in the string
   c = min(string) # O(n) operation
   indices = [] # here we will store all the indices where c occurs
   i = -1       # initialize the search index
   while True: # finding all indexes where c occurs is again O(n)
      i = string.find(c, i+1)
      if i == -1:
         break
      else:
         indices.append(i)
   if len(indices) == 1: # if it only occurs once, then we're done
      i = indices[0]
      return string[i:] + string[:i]
   else:
      i = map(lambda x:(x,x), indices)
      for _ in range(len(string)):                       # go over the whole string O(n)
         i = map(lambda x:((x[0]+1)%len(string), x[1]), i)  # increment the indexes that walk along  O(m)
         c = min(map(lambda x: string[x[0]], i))    # get min character from current indexes         O(m)
         i = filter(lambda x: string[x[0]] == c, i) # keep only the indexes that have that character O(m)
         # if there's only one index left after filtering, we're done
         if len(i) == 1:
            break
      # either there are multiple identical runs, or
      # we found the unique best run, in either case, we start the string from that
      # index
      i = i[0][0]
      return string[i:] + string[:i]

def main(filename):
   cyclic_words = set()
   with open(filename) as words:
      for word in words.readlines():
         cyclic_words.add(normalize(word[:-1])) # normalize without the trailing newline
   print len(cyclic_words)

if __name__ == '__main__':
   if len(sys.argv) > 1:
      main(sys.argv[1])
   else:
      main("/dev/stdin")


Python 3, 118 116 bytes

I=input()
t=eval(I[:-1])
u=ord(I[-1])%7
exec("u=-~u%3;t=[t*1.8-459.67,(t-32)/1.8,t+273.15][u];print(t,'FCK'[u]);"*2)

Performs the conversions in a rotary order K -> F -> C -> K twice.


Brachylog, 1 byte

=

Try it online!

This acts on integers.

From src/predicates.pl#L1151:

brachylog_equal('integer':0, 'integer':0, 'integer':0).
brachylog_equal('integer':0, 'integer':I, 'integer':I) :-
    H #\= 0,
    integer_value('integer':_:[H|T], I),
    brachylog_equal('integer':0, [H|T], [H|T]).


Octave, 22 21 bytes
Saved one byte by changing from while ... end to do ... until.
tic;do
until toc>50;1

tic starts a timer, while toc returns the number of decimal seconds since the last call to tic. We initiate a do - until loop, where we'll loop until toc>50, doing nothing inside the loop. The loop stops after 50 seconds, followed by ans = 1 on the screen.
Try it on TIO (time changed to 5 seconds) or paste it into Octave Online.


05AB1E, 19 18 15 10 bytes
Code:
'.©«®δkZαú

Try it online! Explanation:
'.©«             # append . to each element
    ®δk          # Find index of . for all elements
       Z         # Get the largest
        α        # Get the absolute difference between the indices
         ú       # Pad by that much


Counting N-bit integer multiplication overflows


Convert 1, 2, 3, 4, 5, 6, 7, 8, and 9 to "one", "two", "three", etc

Python 2, 64
print' ottffssennwhoiieiieoruvxvgn  ere ehe  e   nt'[input()::9]

This is what the string looks like with some extra whitespace (try reading vertically):
o t t f f s s e n
n w h o i i e i i
e o r u v x v g n
    e r e   e h e
    e       n t

As explained in the comments below, [input()::9] starts at the given index and selects every ninth subsequent character.


CJam, 184 105 98 96 bytes

00000000: 22 73 20 6d 20 6b 67 41 20 4e 20 4a 20 57 20 48  "s m kgA N J W H
00000010: 7a 50 61 43 20 56 20 46 20 ce a9 53 20 57 62 54  zPaC V F ..S WbT
00000020: 20 48 22 32 2f 53 66 2d 22 d6 9c 64 c6 a1 24 a4   H"2/Sf-"..d..$.
00000030: 4b f9 1c 4a 57 f4 61 79 31 ed 82 34 22 33 31 38  K..JW.ay1..4"318
00000040: 62 35 62 32 66 6d 34 2f 6c 53 25 32 24 32 24 65  b5b2fm4/lS%2$2$e
00000050: 72 22 2f 22 61 2f 3a 3a 2e 2b 3a 2e 2d 61 23 3d  r"/"a/::.+:.-a#=

The above is a hexdump; it can be reversed with xxd -r.

Verify all test cases at once in the CJam interpreter. 1

Test run

$ LANG=en_US
$ cjam si.cjam <<< 'Hz s / Ω'; echo
S
$ cjam si.cjam <<< 'J / A s A'; echo
Ω

Idea

We can encode each unit u = sa mb kgc Ad as the vector tu = (a + c - d, b, c, d). 2

This way, for the input u1 … un / v1 … vm, we only have to calculate (tu1 + … + tun) - (tv1 + … + tvm) and check which unit it corresponds to.

Code

"s m kgA N J W HzPaC V F Î©S WbT H"

2/     e# Split the string into chunks of length 2.
Sf-    e# Remove all spaces (if any) from each chunk.

"ÖdÆ¡$¤KùJWôay1í4"

318b   e# Convert from base 318 to integer.
5b     e# Convert from integer to base 5.
2fm    e# Subtract 2 from each base-5 digit.
4/     e# Split into chunks of length 4.
lS%    e# Read one line of input sand split it at spaces.
2$2$   e# Copy the unit names and the vector table.
er     e# Perform transliteration.
"/"a/  e# Split at "/".
::.+   e# Add the vectors of numerator and denominator (if any).
:.-    e# Subtract the resulting sums (or leave a single sum untouched).
a#     e# Find the index of the resulting vector in the vector table.
=      e# Retrieve the corresponding unit.

1 Note that, due to limitations of the online interpreter, I cannot use a different encoding for source code and I/O. Therefore, the symbol Ω shows up as its UTF-8 encoding (Î©). The official Java interpreter does not share this limitation.
2 This saves a few bytes over the straightforward mapping to (a, b, c, d), since it shortens the range of the first coordinate.


J, 13 bytes

[:;_2|.\_3<\]

Try it online!

Example input: 'flybuys'

_3<\] Box every group of 3

┌───┬───┬─┐
│fly│buy│s│
└───┴───┴─┘

_2|. Split that into groups of 2, and reverse each one:

┌───┬───┐
│buy│fly│
├───┼───┤
│s  │   │
└───┴───┘

[:; Raze the result:

buyflys


Variant of racetrack with exact finishing point and zero terminal velocity

Python, 24 steps (work in progress)
The idea was to solve the continuous problem first, vastly reducing the search space, and then quantize the result to the grid (by just rounding to the nearest gridpoint and searching the surrounding 8 squares)
I parametrize the path as a sum of trigonometric functions (unlike polynomials, they dont diverge and are easier to keep in check). I also control the velocity directly instead of the acceleration, because its easier to enforce the boundary condition by simply multiplying a weighting function that tends to 0 at the end.
My objective function consists of
-exponential score for acceleration > 10
-polynomial score for euclidean distance between the last point and the target
-high constant score for each intersection with a wall, decreasing towards the edges of the wall
To minimize the score, i throw it all into Nelder-Mead optimization and wait a few seconds. The algorithm always succeeds in getting to the end, stopping there and not exceeding the maximum acceleration, but it has troubles with walls. The path either teleports through corners and gets stuck there, or stops next to a wall with the goal just across (left image)

During testing, i got lucky and found a path that was squiggled in a promising way (right image) and after tweaking the parameters some more i could use it as a starting guess for a successful optimization.
Quantization
After finding a parametric path, it was time to remove the decimal points. Looking at the 3x3 neighborhood reduces the search space from roughly 300^N to 9^N, but its still too big and boring to implement. Before i went down this road, i tried adding a "Snap to Grid" term to the objective function (the commented parts). A hundred more steps of optimization with the updated objective and simply rounding was enough to get the solution.

[(9, -1), (4, 0), (1, 1), (2, 2), (-1, 2), (-3, 4), (-3, 3), (-2, 3), (-2, 2), (
-1, 1), (0, 0), (1, -2), (2, -3), (2, -2), (3, -5), (2, -4), (1, -5), (-2, -3),
(-2, -4), (-3, -9), (-4, -4), (-5, 8), (-4, 8), (5, 8)]

The number of steps was fixed and not part of optimization, but since we have an analytical description of the path, (and since the maximal acceleration is well below 10) we can reuse it as a starting point for further optimization with a smaller number of timesteps
from numpy import *
from scipy.optimize import fmin
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection as LC

walls = array([[[0,0],[500,0]],   # [[x0,y0],[x1,y1]]
        [[500,0],[500,400]],
        [[500,400],[0,400]],
        [[0,400],[0,0]],

        [[200,200],[100,200]],
        [[100,200],[100,100]],
        [[100,100],[200,100]],

        [[250,300],[250,200]],

        [[300,300],[300,100]],
        [[300,200],[400,200]],
        [[300,100],[400,100]],

        [[100,180],[120, 200]], #debug walls
        [[100,120],[120, 100]],
        [[300,220],[320, 200]],
        #[[320,100],[300, 120]],
])

start = array([120,180])
goal = array([320,220])

###################################
# Boring stuff below, scroll down #
###################################
def weightedintersection2D(L1, L2):
    # http://stackoverflow.com/questions/563198/how-do-you-detect-where-two-line-segments-intersect
    p = L1[0]
    q = L2[0]
    r = L1[1]-L1[0]
    s = L2[1]-L2[0]
    d = cross(r,s)
    if d==0: # parallel
        if cross(q-p,r)==0: return 1 # overlap
    else:
        t = cross(q-p,s)*1.0/d
        u = cross(q-p,r)*1.0/d
        if 0<=t<=1 and 0<=u<=1: return 1-0*abs(t-.5)-1*abs(u-.5) # intersect at p+tr=q+us
    return 0

def sinsum(coeff, tt):
    '''input: list of length 2(2k+1),
    first half for X-movement, second for Y-movement.
    Of each, the first k elements are sin-coefficients
    the next k+1 elements are cos-coefficients'''
    N = len(coeff)/2
    XS = [0]+list(coeff[:N][:N/2])
    XC =     coeff[:N][N/2:]
    YS = [0]+list(coeff[N:][:N/2])
    YC =     coeff[N:][N/2:]
    VX = sum([XS[i]*sin(tt*ww[i]) + XC[i]*cos(tt*ww[i]) for i in range(N/2+1)], 0)
    VY = sum([YS[i]*sin(tt*ww[i]) + YC[i]*cos(tt*ww[i]) for i in range(N/2+1)], 0)
    return VX*weightfunc, VY*weightfunc

def makepath(vx, vy):
    # turn coordinates into line segments, to check for intersections
    xx = cumsum(vx)+start[0]
    yy = cumsum(vy)+start[1]
    path = []
    for i in range(1,len(xx)):
        path.append([[xx[i-1], yy[i-1]],[xx[i], yy[i]]])
    return path

def checkpath(path):
    intersections = 0
    for line1 in path[:-1]: # last two elements are equal, and thus wrongly intersect each wall
        for line2 in walls:
            intersections += weightedintersection2D(array(line1), array(line2))
    return intersections

def eval_score(coeff):
    # tweak everything for better convergence
    vx, vy = sinsum(coeff, tt)
    path = makepath(vx, vy)
    score_int = checkpath(path)
    dist = hypot(*(path[-1][1]-goal))
    score_pos = abs(dist)**3
    acc = hypot(diff(vx), diff(vy))
    score_acc = sum(exp(clip(3*(acc-10), -10,20)))
    #score_snap = sum(abs(diff(vx)-diff(vx).round())) + sum(abs(diff(vy)-diff(vy).round()))
    print score_int, score_pos, score_acc#, score_snap
    return score_int*100 + score_pos*.5 + score_acc #+ score_snap

######################################
# Boring stuff above, scroll to here #
######################################
Nw = 4 # <3: paths not squiggly enough, >6: too many dimensions, slow
ww = [1*pi*k for k in range(Nw)]
Nt = 30 # find a solution with tis many steps
tt = linspace(0,1,Nt)
weightfunc = tanh(tt*30)*tanh(30*(1-tt)) # makes sure end velocity is 0

guess = random.random(4*Nw-2)*10-5
guess = array([ 5.72255365, -0.02720178,  8.09631272,  1.88852287, -2.28175362,
        2.915817  ,  8.29529905,  8.46535503,  5.32069444, -1.7422171 ,
       -3.87486437,  1.35836498, -1.28681144,  2.20784655])  # this is a good start...
array([ 10.50877078,  -0.1177561 ,   4.63897574,  -0.79066986,
         3.08680958,  -0.66848585,   4.34140494,   6.80129358,
         5.13853914,  -7.02747384,  -1.80208349,   1.91870184,
        -4.21784737,   0.17727804]) # ...and it returns this solution

optimsettings = dict(
    xtol = 1e-6,
    ftol = 1e-6,
    disp = 1,
    maxiter = 1000, # better restart if not even close after 300
    full_output = 1,
    retall = 1)

plt.ion()
plt.axes().add_collection(LC(walls))
plt.xlim(-10,510)
plt.ylim(-10,410)
path = makepath(*sinsum(guess, tt))
plt.axes().add_collection(LC(path, color='red'))
plt.plot(*start, marker='o')
plt.plot(*goal, marker='o')
plt.show()

optres = fmin(eval_score, guess, **optimsettings)
optcoeff = optres[0]

#for c in optres[-1][::optimsettings['maxiter']/10]:
for c in array(optres[-1])[logspace(1,log10(optimsettings['maxiter']-1), 10).astype(int)]:
    vx, vy = sinsum(c, tt)
    path = makepath(vx,vy)
    plt.axes().add_collection(LC(path, color='green'))
    plt.show()

To Do: GUI that lets you draw an initial path to get a rough sense of direction. Anything is better than randomly sampling from 14-dimensional space


C + x86 assembly
Not satisfied with a constant defined in the software of your language?  Why not use a language that can access a constant value of PI right from your FPU hardware:
#include <stdio.h>

int main (int argc, char **argv) {
    double pi;
    __asm__("fldpi" : "=t" (pi));
    printf("%g\n", 3 * 3 * pi);
    return (0);
}


Jelly, 28 26 25 24 23 bytes

-1 byte thanks to carusocomputing (replace the word thimble with abcdefg)

9ØaḣŒ!s²ḣµs9K€;€”.K;⁷µ€

TryItOnline!

How?

Makes a list of all 362880 permutations of the first seven nine letters of the English alphabet abcdefghi, which all have the properties of Martian words and are all distinct, and formats them into an essay using the first 729 words.

9ØaḣŒ!s²ḣµs9K€;€”.K;⁷µ€ - Main link: no arguments
9                       - 9 as x
         µ              - monadic chain separation
 Øa                     - yield lowercase alphabet
   ḣ                    - head to x ("abcdefghi")
    Œ!                  - all permutations (362880 distinct Martian words)
       ²                - square x = 81
      s                 - split into chunks of length 81 (the paragraphs)
        ḣ               - head to x (get the first 9 paragraphs only)
                     µ€ - monadic chain for €ach (for each chunk:)
          s9            -     split into chunks of length 9 (the sentences)
            K€          -     join with spaces for €each (between words in each sentence)
              ;€        -     concatenate €ach with
                ”.      -         '.' (add a full stop* after each sentence)
                  K     -     join with spaces (add a space between the sentences)
                   ;    -     concatenate with
                    ⁷   -         a line feed
                        - implicit print

* period


C, 7.29min for ca.5.4^64.txt on an Intel Core i5-4570 + 8GB ram

Update: Sometimes gives wrong results

I've compiled it with gcc -O3 cav.c -o cav. Simply run it with the CA file's name as first (and only) parameter.
In my case: ./cav ca.2.2^4.txt

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>

int t, v, k, N; /* initial parameters */
uint16_t *ca; /* The CA */
uint16_t *cia; /* Column index array - the columns we selected to compare */
uint8_t *combos;
int num_combos; /* Size of the combo 'hash map' (see compareColumns()) */

int ipow(int base, int exp) /* basic integer pow function 'stolen' from StackOverflow ;) */
{
    int result = 1;
    while(exp)
    {
        if(exp & 1)
            result *= base;
        exp >>= 1;
        base *= base;
    }
    return result;
}

char compareColumns(int base, int child)
{
    int pos = base, maxpos = k - child, child_dec = child - 1;
    if(child == 0)
    {
        while(pos != maxpos)
        {
            cia[child] = pos++;
            memset(combos, 0, num_combos);
            int rv = 0; /* The offset in the CA for the current row */
            int n;
            for(n = 0; n < N; n++) /* For every row */
            {
                int key = 0; /* This is basically a HashMap key, using the same algorithm that you use for accessing 2D data in a 1D array. */
                int df = 1; /* Dimension factor - needed for the hash-map-key-like algorithm */
                int i;
                for(i = 0; i < t; i++) /* For every selected column */
                {
                    key += df * ca[cia[i] + rv]; /* Calculate the key */
                    df *= v;
                }
                combos[key] = 1; /* Set the 'boolean' at 'key' in the 'hash map' to 1 */
                rv += k;
            }
            if(memchr(combos, 0, num_combos) != NULL) /* If there are still any 0s (any needed combinations that aren't found), exit immediately! */
                return 0;
        }
    }
    else
    {
        while(pos != maxpos)
        {
            cia[child] = pos++;
            if(!compareColumns(pos, child_dec))
                return 0;
        }
    }
    return 1;
}

int main(int argc, char **argv)
{
    /* Fetch user input & allocate memory */
    sscanf(argv[1], "ca.%d.%d^%d.txt", &t, &v, &k);

    FILE *file = fopen(argv[1], "r");
    fscanf(file, "%d", &N);

    int num_vals = k * N, i;
    num_combos = ipow(v, t);

    ca  = (uint16_t*)malloc(num_vals * sizeof(uint16_t));
    cia = (uint16_t*)malloc(t * sizeof(uint16_t));
    combos = (uint8_t*)malloc(num_combos * sizeof(uint8_t));

    for(i = 0; i < num_vals; i++)
    {
        int val;
        fscanf(file, " %d", &val);
        ca[i] = val;
    }
    fclose(file);

    /* The main algorithm implementation */
    if(compareColumns(0, t - 1))
        printf("Valid!\n");
    else
        printf("Invalid!\n");

    /* Free memory */
    free(combos);
    free(cia);
    free(ca);
    return 0;
}

I'll try to explain: I'll begin with compareColumns: if it has children (int child), it goes through (allmost) all the columns and kicks off a new call to compareColumns after each step, which itself then walks from the last position of its parent until the end (minus it's own children) of the CA. However, if the function is called with no children (child = 0), it will take all the selected rows and generate something like a hash map key from it. This key will then be used to set a specific cell of the array combos to 1. At the end, it checks if all cells of 'combos' are 1 (i.e. if all combinations appeared at least once). If all cells are 1, it will proceed. If at least one cell is 0, it will abort immediately and print "Invalid!".


Detect the Nearly Perfect Licence Plates

Jelly, 29 28 30 bytes
+1 byte to fix a bug spotted by ChristianSievers (incorrectly dealing with substrings of only zeros)
+1 byte to fix false positives for "0", "00", ... found during above fixing (0 is a perfect square).
i@€ØAS;Æ²$
e€ØAœpV€€LÐfS€P;0⁼Ç

Try it online!, or run tests
How?
i@€ØAS;Æ²$ - Link 1: [letter-sum, letter-sum is perfect square?]: plate
i@€        - index of €ach char in plate [reversed @rguments] (1-based, 0 otherwise) in:
   ØA      -     uppercase alphabet
     S     - sum
         $ - last two links as a monad:
      ;    -     concatenate with:
       Æ²  -         is square?

e€ØAœpV€€LÐfS€P;0⁼Ç - Main link: plate                        e.g. "11BB2"
    œp              - partition plate at truthy values of:
e€                  -     is in? for €ach char in plate:
  ØA                -         uppercase alphabet                   [['1','1'],[''],['2']]
      V€€           - evaluate for €ach for €ach                   [[1,1],[],[2]]
          Ðf        - filter keep:
         L          -     length                                   [[1,1],[2]]
            S€      - sum each                                     [2,2]
              P     - product                                      4
               ;0   - concatenate a zero                           [4,0]
                  Ç - last link (1) as a monad (taking plate)      [4,1]
                 ⁼  - equal? (non-vectorising)                     0


Haskell, 207,535 202,073 bytes

5,462 bytes saved by using 0|9 instead of [09] where possible.

digits n
  | x == 0    = "0|9"
  | otherwise = show x
  where x = mod n 9

regex 0 = "[09]*"
regex n = (regex' n (-1) (-1)) ++ "*"

regex' 0 start end = digits (end - start)
regex' n start end = '(':(regex' 0 start end) ++ (concat ['|':(regex' (n-x) (start-x) (-1)) ++ (regex (n-x))
                                                  ++ (regex' (n-x) (-1) (end-x)) | x <- [1..n]]) ++ ")"

main = do
  putStr ("^" ++ (regex 8) ++ "$")

Try it online!

Just a quick adaptation of the regex given in the footnotes of the linked article to get things started.

Pastebin of output regex, courtesy of Herman Lauenstein.

While I have not been able to test the full regex, modifying the program to check divisibility by 3 instead gives something exactly equivalent to the regex I based this on.  Furthermore, modifying the program to check the digit sum's divisibility by 4 or 5 also seems to work on the numbers I tested it on.


You are given a string to make and starting with the empty string, make it using appending and cloning cost

Husk, 25 bytes

φ?ö▼z+:⁴∞²m⁰§:h§δf`€otṫḣ0

Try it online!

Inputs are in the order append cost, clone cost, target.

Explanation

φ?ö▼z+:⁴∞²m⁰§:h§δf`€otṫḣ0  Two explicit inputs and one implicit.
                           Example: 2, 3, s="abab"
φ                          Make a recursive function and call it on s:
 ?                      0   If s is empty, return 0.
  ö▼z+:⁴∞²m⁰§:h§δf`€otṫḣ    Otherwise do this.
                       ḣ    Prefixes: ["a","ab","aba","abab"]
                    otṫ     Suffixes except the first one: ["bab","ab","b"]
               §δf`€        Keep those prefixes that have the corresponding suffix as substring: ["ab","aba"]
            §:h             Prepend s minus last character: ["aba","ab","aba"]
          m⁰                Recurse on each: x=[6,4,6]
        ∞²                  Repeat the clone cost: [3,3,3,..
      :⁴                    Prepend append cost: [2,3,3,3,..
    z+                      Add component-wise to x: [8,7,9]
   ▼                        Minimum: 7


m3ph1st0s's programming puzzle 4 (C/C++): “3-way swap”

For 4.4 (14 characters, 1 digit and 4 letters):

int main()
{
  int a = 93;
  int b = 11;
  int c = 22528;

  b<<=a=(c=a)/8;
}

VS2010 with /Wall didn't show any warnings, but I'm still a bit suspicious about using a twice in there (even though it's only modified once).


Retina, 50 bytes

+`([#.])(([#.])*\|(?>(?<-3>[#.])*))(?!\1)[#.]
#$2#

Try it online! (The first line enables a linefeed-separated test suite.)

I guess this is the opposite of a (no regex) submission.

Explanation

This is simply a regex substitution, which is applied repeatedly (+) until the string stops changing. I'm using balancing groups to make sure that the two mirrored positions are the same distance from the given mirror (backreferences won't do, since the exact string on both sides of the | may be different).

([#.])            # Match and capture a non-mirror cell.
(                 # This will match and capture everything up to its corresponding
                  # cell so that we can write it back in the substitution.
  ([#.])*         #   Match zero or more non-mirror cells and push each one onto
                  #   group 3. This counts the distance from our first match to
                  #   the mirror.
  \|              #   Match the mirror.
  (?>             #   Atomic group to prevent backtracking.
    (?<-3>[#.])*  #     Match non-mirror while popping from group 3.
  )               #   There are three reasons why the previous repetition
                  #   might stop:
                  #   - Group 3 was exhausted. That's good, the next position
                  #     corresponds to the first character we matched.
                  #   - We've reached the end of the string. That's fine,
                  #     the last part of the regex will cause the match to fail.
                  #   - We've hit another mirror. That's also fine, because
                  #     the last part of the regex will still fail.
)
(?!\1)            # Make sure that the next character isn't the same as the first
                  # one. We're looking for .|# or #|., not for #|# or .|.
[#.]              # Match the last non-mirror character.

This is replaced with #$2# which simply replaces both the first and last character of the match with a #.


C, 32 bytes

#define f(d)d*time(0)/464083315.

If losing a little more accuracy is fine, I can get it down to about 29 bytes being still accurate to 4 digits past the decimal (as of the time of this posting):

#define f(d)d*time(0)/46408e4


Print a string in as few distinct characters as possible


Generate lowest degree polynomial from sequence

Pari/GP, 28 bytes

l->polinterpolate([1..#l],l)

Try it online!


JavaScript (ES6), 75 bytes
Saved 2 bytes thanks to @KevinCruijssen
Expects a 0-based index.

(h,w,i)=>[...'12221000'].map((k,j,a)=>(i+w+~-k)%w+~~(i/w+h+~-a[j+2&7])%h*w)

Try it online!
The surrounding indices are returned in the following order:
$$\begin{matrix}5&4&3\\6&\cdot&2\\7&0&1\end{matrix}$$
How?
The indices \$I_{dx,dy}\$ of each surrounding cell at \$(x+dx,y+dy)\$ are given by:
$$\begin{align}I_{dx,dy}&=((x+dx) \bmod w)+w((y+dy) \bmod h)\\&=((N+dx) \bmod w)+w((\left\lfloor\frac{N}{w}\right\rfloor+dy) \bmod h)\end{align}$$
where \$N=wy+x\$ is the index of the target cell.
We walk through the list \$[1,2,2,2,1,0,0,0]\$ and subtract \$1\$ to get the value of \$dx\$, which gives:
$$[0,1,1,1,0,-1,-1,-1]$$
For the corresponding values of \$dy\$, we use the same list shifted by 2 positions, which gives:
$$[1,1,0,-1,-1,-1,0,1]$$


Retina, 1 byte

]

Try it online! (The first line enables a linefeed-separated test suite.)

By default, Retina counts the number of matches of the given regex in the input. The unwrapped size is simply equal to the number of [] pairs in the input and therefore to the number of ].


C 33
If just a function is allowed, then even c can compete.
(For the record, 2 bytes saved thx to @Cool Guy. Mt thx comment is unexpectedly evaporated.)
1 more char saved thx @Mig
f(a,c){printf("%s\n%*c",a,c,94);}


JavaScript (ES6), V8 / SpiderMonkey vs Chakra, 66 63 bytes

n=>[...Array(n)].map((_,d)=>s+=n%d?0:d,[0,n>10].sort(x=>s=x))|s

Demo

let f =

n=>[...Array(n)].map((_,d)=>s+=n%d?0:d,[0,n>10].sort(x=>s=x))|s

console.log(JSON.stringify(
  [...Array(20)].map((_, n) => n + 1).map(f)
))

Output

Output of the above snippet on Chrome and Firefox (all correct):

[0,1,1,3,1,6,1,7,4,8,1,16,1,10,9,15,1,21,1,22]

Output on Edge (off by 1, starting at n = 11):

[0,1,1,3,1,6,1,7,4,8,2,17,2,11,10,16,2,22,2,23]

Why?

No algorithm is imposed by the specification for the .sort() method. It's not even required to be stable. Therefore, each JavaScript engine uses its very own implementation.

However, [0,1].sort(x=>x) gives [0,1] with all engines.

So what's the difference?

What's happening here is that Chakra is passing 1 as the first parameter of the first (and only) iteration to the callback function (asking for a comparison of 1 with 0), while V8 and SpiderMonkey are passing 0 (asking for a comparison of 0 with 1).

You can use the following snippet to check what your browser is doing.

[0, 1].sort((x, y) => console.log("Let's compare " + x + " with " + y + "!"))


Convert from Infix Notation to Prefix Notation


05AB1E, 34 31 30 bytes
7G¹N¢O3‰N*2LRN1Q+°*X5‚Nå_i¨}OO

Explanation
7G                                  # for N in 1..6
  ¹N¢O                              # count number of occurrences of N in input
      3‰                            # divmod 3
        N*                          # multiply by N
          2LRN1Q+°*                 # multiply by 10, 100 or 1000
                   X5‚Nå_i¨}        # if N is not 1 or 5, scrap the singles
                            OO      # sum all triple and single scores so far
                                    # implicitly display total sum

Try it online


Mayweather vs McGregor: Prepare the cash prize

Jelly,  92  75 bytes

⁽©Ḍṃ“_= ”x"“€Þ‘x2,6¤;"⁾_|x1,7¤z⁶ZUŒBY”$“¢=Ḷ't3y&ḅḄȥıḍḄḌṀṡḂẓPḣṁQṘ½ɗ’BT+134¤¦

Try it online!

How?

Step 1. Build a list of the rows of the right half of an empty briefcase, ignoring trailing spaces:

⁽©Ḍṃ“_= ”x"“€Þ‘x2,6¤;"⁾_|x1,7¤
    “_= ”                      - literal list of characters = "_= "
⁽©Ḍ                            - base 250 literal = 2674
   ṃ                           - base decompress (2674 in base: 1='_', 2='=', 0=' ')
                               -   ...yields the list of characters: "_ =    _"
                   ¤           - nilad followed by link(s) as a nilad:
           “€Þ‘                -   literal list of code page indexes = [12,20]
                2,6            -   literal list of numbers = [2,6]
               x               -   repeat -> [12,12,20,20,20,20,20,20]
         x                     - repeat -> ["_"*12, " "*12, "="*20, " "*20, ..., "_"*20]
                             ¤ - nilad followed by link(s) as a nilad:
                      ⁾_|      -   literal list of characters = "_|"
                          1,7  -   literal list of numbers = [1,7]
                         x     -   repeat -> list of characters "_|||||||"
                     "         - zip with the dyad:
                    ;          -   concatenate -> ["_"+"_"*12, "|"+" "*12, ...]

Step 2: transform that into a whole empty briefcase:

z⁶ZUŒBY
 ⁶      - literal space character
z       - transpose with filler (adds the "leading" spaces, to the 1st 2 rows)
  Z     - transpose (back from columns to rows again)
   U    - upend (reverse each row to make it a left-hand side of an empty briefcase)
    ŒB  - bounce (add a reflection of each row with one central character)
      Y - join with new lines

Step 3: Show me the money!

”$“¢=Ḷ't3y&ḅḄȥıḍḄḌṀṡḂẓPḣṁQṘ½ɗ’BT+134¤¦
                                     ¦ - sparse application of:
”$                                     -   literal '$' character
                                       - ...to indexes:
                                    ¤  - nilad followed by link(s) as a nilad:
  “¢=Ḷ't3y&ḅḄȥıḍḄḌṀṡḂẓPḣṁQṘ½ɗ’         - base 250 literal = 1999171130867115278012045759181600763304793110829063794065408
                              B        - convert to a binary list -> [1,0,0,1,1,1,1,1,0,0,1,1,1,1,1,0,0,1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,1,0,0,1,0,0,0,1,0,0,1,0,0,0,1,0,0,1,1,1,0,0,0,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,1,0,0,0,1,0,0,1,0,0,0,1,0,0,1,0,0,1,1,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,1,1,1,1,1,0,0,1,1,1,1,1,0,0,1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
                               T       - truthy indexes -> [1,4,5,6,7,8,11,12,13,14,15,18,26,39,43,46,50,53,57,60,61,62,66,67,68,85,88,92,95,99,102,105,106,107,110,127,130,131,132,133,134,137,138,139,140,141,144,152]
                                 134   - literal 134
                                +      - addition -> [135,138,139,140,141,142,145,146,147,148,149,152,160,173,177,180,184,187,191,194,195,196,200,201,202,219,222,226,229,233,236,239,240,241,244,261,264,265,266,267,268,271,272,273,274,275,278,286]
                                       -             (that's where the $s at!)


dc, 99 bytes
Golfed:
2?dsi1+^k1dddsa2v/sb4/stsp[lalb*vlalb+2/dla-d*lp*ltr-stsasblp2*spli1-dsi0<m]dsmxK2/1-klalb+d*4lt*/p

With whitespace and comments for "readability":
2?dsi               # Push 2. push input n, duplicate and store in i
1+^k                # Set calculation precision to 2^(n+1)
1dddsa              # Push four 1s. Store 1st in a
2v/sb               # Store 1/sqrt(2) in b
4/st                # Store 1/4 in t
sp                  # Store 1 in p
[                   # Start iteration loop macro
lalb*v              # Save sqrt(a*b) on stack
lalb+2/d            # Save a[i+1] = (a[i]+b[i])/2 on stack and duplicate
la-d*lp*ltr-        # Save t-p(a[i]-a[i+1])^2 on the stack
st                  # Store t result from stack
sa                  # Store a result from stack
sb                  # Store b result from stack
lp2*sp              # Store 2p in p
li1-dsi0<m]         # Decrement iteration counter i; recurse into macro if < 0
dsmx                # Duplicate, store and run macro
K2/1-k              # Set display precision to 2^n-1
lalb+d*4lt*/        # Save (a+b)^2/4t on stack
p                   # Print result

dc needs to be told how many digits of precision should be used.  The calculation precision needs to be higher than the final display precision, so the calculation precision is set to be 2^(n+1) digits.  I have verified the accuracy of the output with n=10 against http://www.angio.net/pi/digits/pi1000000.txt.
This slows down dramatically for larger n; n=12 takes 1.5 mins on my VM.  Running a few different samples shows the time complexity is O(e^n) (not surprising).  Extrapolating this to n=20 would have a runtime of 233 days.  Oh well.  Better than heat-death-of-the-universe at least.
This is moderately golfed - the stack is used to eliminate temporary variables during the calculations of each iteration, but there is possibly more use of the stack to shorten this more.
$ dc glpi.dc <<< 1
3.1
$ dc glpi.dc <<< 2
3.141
$ dc glpi.dc <<< 5
3.1415926535897932384626433832795
$ time dc glpi.dc <<< 7
3.1415926535897932384626433832795028841971693993751058209749445923078\
164062862089986280348253421170679821480865132823066470938446

real    0m0.048s
user    0m0.039s
sys 0m0.000s
$

If you don't like dc wrapping output at 70 chars, you can set the environment variable DC_LINE_LENGTH to 0:
$ DC_LINE_LENGTH=0 dc glpi.dc <<< 8
3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825342117067982148086513282306647093844609550582231725359408128481117450284102701938521105559644622948954930381964428810975665933446128475648233786783165271201909145648
$


Python, 24 bytes

range(123,790,111).count

An anonymous function that outputs 0 or 1. It creates the list [123, 234, 345, 456, 567, 678, 789] and counts how many times the input appears.
f=range(123,790,111).count

f(123)
=> 1
f(258)
=> 0


Check whether an integer is a power of 2 without using +,- operations

APL (7)

Yes, that's 7 bytes. Assume for the moment that I'm using IBM codepage 907 instead of Unicode and then each character is a byte :)

0=1|2⍟⎕

i.e. 0 = mod(log(input(),2),1)


C, 45 chars without goto, if, for, ...

Not the smallest solution, but I find this way of doing it quite interesting in C :)

Doesn't use goto, if, for, or any other kind of control structures.

The function by itself (45 chars):

m(){int (*a[])()={m,exit};i++;(*a[i>999])();}

A compilable, working program:

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

int i=0;
m(){int (*a[])()={m,exit};i++;printf("%i ",i);(*a[i>999])();}

int main()
{
  m();
}


PHP, 666 bytes
I suppose this is a rather appropriate code size for a song about Villains...
<?$s=gzinflate(base64_decode("zVLNitswEL4b/A6TUxLwPkNh99BkDynsT5ceJ9YkUjPWBEle47fvjJVCoWyh0EPRYMme8cz3ox3Nq7Z5I8BEcBiHIyX4Eqltdh8l6jrIBBxyoQg9Syae7ZdE6wyoiVKYgClniRAilBT6CyWtefEhg8ZZQjyDk2nJ68cilt6fYJYRJowR4ajD4WtgRi35FcI3LfH4TlAEeo/Z6vJ4peQpCejI4gnSGNvmccwFTsKscIcZBnmn3AFGBzkSXpScjNG1zT1Br0RPI0OUYn0HvCxta37z7P1Wt4en18PDzk4H6RR+XFvx2HsdiWW1reL8jZwfKLxDZahxU1pEseooUy9S6ZZxsIfvld+C8c2rGXvIOKu6namXCN1sZIpPMrXNZ1EMmxd7gVBMKB+GbmE8kIHfvJ59p74VtbGkWdkPpDPVKeJM2wpmwqJ8TUMmTLEDX3030R0hG9k1M2QO1yo1B0fVFoV/xKgLrkRsaH4S7eCM+bqCyYiZInYPnN2S1aebrPd4d9QIzvG8nG6hXPHut/iDDf+g0f+EpTay5w8="));foreach($argv as$a){@list($a,$b)=explode(",",$a);$s=str_ireplace($a,$b,$s);}echo $s;

Usage: php numberOne.php one,three net,villain


Mathematica, 60 54 50 bytes
Thanks @GregMartin for 4 bytes!
Array[s=2#2^2;E^(-{##}.{##}/s)/π/s&,1+2{#,#},-#]&

Takes r and sigma as input, returns the matrix (exact numbers).
Built-in version (58 bytes)
GaussianMatrix[{##},Standardized->1<0,Method->"Gaussian"]&

Of course, Mathematica has a built-in for this, too, but it's too long.


Pyth - 12 bytes
.wMC,cl.zz.z

Uses builtin split function and then uses splat-map on the write function. Doesn't work online.


PHP, -4 (156 - 20*3 - 30 - 50 - 20)
<?php $x=preg_replace("!(//.*|/\*.*\*/|[^()[\]{}<>])!sm",'',$argv[1]);while(strlen($x)!=strlen($x=str_replace(str_split('()[]{}<>',2),'',$x)));print $x?0:1;

It removes comments
It filters out all characters different than (, ), [, ], {, }, <, >
It replaces all (), [], {}, <> pairs until there are no matches
Prints 1 if the string is empty, 0 otherwise

(Edit: changed the regex; the source code is now 156 instead of 175)


Charcoal, 5 bytes

Ｐ+×+Ｎ

Try it online!


Perl, 167 - 973 = -806 142 - 55 = 87

Here's an entry in the proper spirit of this code challenge:

if($ARGV[0]=~s/r/X/){open F,$0;for(@x=split//,join"",<F>){
$c=$_++;open F,">$0~".++$x;print F@x;$_=$c}sleep 1;
fork||exit exec"perl $0~$_ @ARGV"for 1..@x}print"alive\n"

I forkbombed myself a few times in the process of writing this script. As a result, this version comes with a couple of safety features. First off is the sleep 1 just before the spawning loop. That leaves enough idle processing time to allow one to type killall perl, if and when such measures become necessary. The second safety feature is that the spawn loop is disabled by default. To run in full power, you need to supply the word reproduce as an argument on the command line.

(Seriously, it's embarrassing to acknowledge the number of times I've had to do a hard reboot today because of some bug in my script, before I finally got the balance right.)

The program ends up producing several thousand imperfect copies of itself, from which about one in eight succeeds in printing alive. Most of the copies have syntax errors and so don't get run. A handful of scripts run but produce invalid output.

Here's a sample test run. (Note that, due to the sleep, it takes several seconds before the spawning finally grinds to a halt and all the scripts stop running.)

$ mkdir run
$ cp changer run/
$ cd run
$ ls -l
total 4
-rw-r--r-- 1 breadbox breadbox 167 2013-07-19 21:35 changer
$ perl changer
alive
$ perl changer reproduce 2> /dev/null >> out
$ ls -l out
-rw-r--r-- 1 breadbox breadbox 2608 2013-07-19 21:35 out
$ ls -l out
-rw-r--r-- 1 breadbox breadbox 6404 2013-07-19 21:35 out
$ ls -l out
-rw-r--r-- 1 breadbox breadbox 9370 2013-07-19 21:35 out
$ ls -l out
-rw-r--r-- 1 breadbox breadbox 9370 2013-07-19 21:35 out
$ ls -l | wc -l
7691
$ grep -c alive out
973
$ cd ..
$ rm -r run/
$

Finally, I should note that the script has a bit of nondeterminism -- a common enough circumstance when starting up lots of child processes. As a result, the number of alives that get output varies a bit with each run. The highest count I've seen so far is 984, so I believe that it's not in any danger of exceeding the 1024 limit.


Need to use a method on variable for which you haven't yet constrained the type? Just compare it against a literal of the type you want it to be then throw away the result to annotate that variable's type:

let f (x:string)=x.Length
let f x=x="";x.Length


Dyalog APL, 4 bytes

⌊/⌈/

This is a monadic function train that expects array and integer as right and left arguments, resp.

Try it with TryAPL.

How it works

A train of two functions is an atop, meaning that the right one is called first (with both arguments), then the left one is called on top of it (with the result as sole argument).

A monadic f/ simply reduces its argument by f. However, if called dyadically, f/ is n-wise reduce, and takes the slice size as its left argument.

⌊/⌈/    Monadic function. Right argument: A (array). Left argument: n (list)

  ⌈/    N-wise reduce A by maximum, using slices of length n.
⌊/      Reduce the maxima by minimum.


Reducing Leibniz perl code in characters

Perl 53 bytes

You can save two more strokes:

<>;print${\map$a-=(-1)**$_/(2*$_-1),1..$_},$a=$/for<>


Ruby

z=gets;puts *z.reverse==z&&1||0||1&&z==esrever.z* stup;steg=z

Prints 1 if the input is a palindrome, 0 if it isn't. Input without linebreak.

Doesn't use any comments, instead it uses 2 tricks:

Short-circuiting: 0 is true-ish in Ruby (only nil and false evaluate to false), so 1&&z==esrever.z* stup isn't evaluated and thus can't raise a runtime exception
The splat/multiplication operator (*): To avoid a syntax error in z=esrever.z stup, we force the parser to parse this as z=esrever.z()*stup by adding a *. On the other side, the * is parsed as a splat operator, which in a function call splits an array in a series of parameters. If there's only one element instead of an array, it basically does nothing, so puts *foo is equivalent to puts foo.

Obvious solution using comments (prints true/false):

puts gets.reverse==$_#_$==esrever.steg stup