Insanity Check Program Insanity: doing the same thing over and over again and expecting different results.

Write a program that just throws an exception (runtime error) each time it is run. The challenge being to have the probability to produce more than one crash, without calling the exceptions directly (no throw statements) and not to use built in random or cpu tick counting functions.

10 points for each possible error.
25 bonus points if the error/crash occurs on another process or the system.

Rules

Responses must indicate what error(s) are possible and how they are generated.
Cannot use the system (built-in) random number generator unless it is seeded with the same number each time the program runs.
Cannot use the number of tics or cpu cycles, unless they are counted relatively to the start of the main program thread.
Multithreading is allowed (if not encouranged).

Edit 1

GUID generation falls under the built-in random number generator. Custom "homegrown" GUID generation is permitted.
Accessing the file system is permitted for I/O of files except when done to bypass the rules (read a file of random bits, or timestamp).

Edit 2

Calling abort() or assert() violates the spirit of the challenge of making insane software and thus no 10 points will be awarded for this mode of failure.

Good luck!

Java, 400

Java is blessed (?) with many Exceptions and Errors. There are many Exceptions that are specific to the operation of a single class. As an example of one of the most extreme cases, there are more than 10 Exceptions (all are subclass of IllegalFormatException) dedicated to Formatter class alone, and I have taken time to make the code throws (almost) all of them.

My current answer features 40 different Exceptions/Errors, and they randomly get executed depending on the modulo of System.nanoTime() with some integer.

  This method can only be used to measure elapsed time and is not related to any other notion of system or wall-clock time. The value returned represents nanoseconds since some fixed but arbitrary origin time (perhaps in the future, so values may be negative). The same origin is used by all invocations of this method in an instance of a Java virtual machine; other virtual machine instances are likely to use a different origin.

The method above should be allowed, since it falls into case "3. Cannot use the number of tics or cpu cycles, unless they are counted relatively to the start of the main program thread".

Compilation Instruction

Oracle's JRE/JDK or OpenJDK is strongly recommended for running the code. Otherwise, some Exception may not be thrown, since some of them relies on the internal details of the reference implementation and I don't have a reliable fall-back.

The code below compiles successfully with javac 1.7.0_11 and produces all Exceptions on java 1.7.0_51.

To run this code, you need to copy and paste the code below to a Unicode aware editor (e.g. Notepad++), save it in UTF-16 (Big-Endian or Little-Endian doesn't matter as long as the BOM is written).
Change working directory (cd) to where the source code is saved (this is important).
Compile the code with the following command:

javac G19115.java -encoding "UTF-16"

And run the code:

java G19115

There is nothing destructive in my code, since I also want to test run it on my computer. The most "dangerous" code is deleting ToBeRemoved.class file in the current folder. Other than that, the rest doesn't touch the file system or the network.

import java.util.*;
import java.util.regex.*;
import java.lang.reflect.*;
import java.text.*;
import java.io.*;
import java.nio.*;
import java.nio.charset.*;
import java.security.*;

class G19115 {

    // The documentation says System.nanoTime() does not return actual time, but a relative
    // time to some fixed origin.
    private static int n = (int) ((System.nanoTime() % 40) + 40) % 40;

    @SuppressWarnings("deprecation")
    public static void main(String args[]) {

        /**
         * If the code is stated to be a bug, then it is only guaranteed to throw Exception on
         * Oracle's JVM (or OpenJDK). Even if you are running Oracle's JVM, there is no
         * guarantee it will throw Exception in all future releases future either (since bugs
         * might be fixed, classes might be reimplemented, and an asteroid might hit the earth,
         * in order from the least likely to most likely).
         */

        System.out.println(n);

        switch (n) {
            case 0:
                // Bug JDK-7080302
                // https://bugs.openjdk.java.net/browse/JDK-7080302
                // PatternSyntaxException
                System.out.println(Pattern.compile("a(\u0041\u0301\u0328)", Pattern.CANON_EQ));
                System.out.println(Pattern.compile("öö", Pattern.CANON_EQ));

                // Leave this boring pattern here just in case
                System.out.println(Pattern.compile("??+*"));
                break;
            case 1:
                // Bug JDK-6984178
                // https://bugs.openjdk.java.net/browse/JDK-6984178
                // StringIndexOutOfBoundsException
                System.out.println(new String(new char[42]).matches("(?:(?=(\\2|^))(?=(\\2\\3|^.))(?=(\\1))\\2)+."));

                // Leave this boring code here just in case
                System.out.println("".charAt(1));
                break;
            case 2:
                // IllegalArgumentException

                // Bug JDK-8035975
                // https://bugs.openjdk.java.net/browse/JDK-8035975
                // Should throw IllegalArgumentException... by documentation, but does not!
                System.out.println(Pattern.compile("pattern", 0xFFFFFFFF));

                // One that actually throws IllegalArgumentException
                System.out.println(new SimpleDateFormat("Nothing to see here"));
                break;
            case 3:
                // Bug JDK-6337993 (and many others...)
                // https://bugs.openjdk.java.net/browse/JDK-6337993
                // StackOverflowError
                StringBuffer buf = new StringBuffer(2000);
                for (int i = 0; i < 1000; i++) {
                    buf.append("xy");
                }
                System.out.println(buf.toString().matches("(x|y)*"));

                // Leave this boring code here just in case
                main(args);
                break;
            case 4:
                // NumberFormatException
                String in4 = "123\r\n";
                Matcher m4 = Pattern.compile("^\\d+$").matcher(in4);

                if (m4.find()) {
                    System.out.println(Integer.parseInt(in4));
                } else {
                    System.out.println("Bad input");
                }

                // NotABug(TM) StatusByDesign(TM)
                // $ by default can match just before final trailing newline character in Java
                // This is why matches() should be used, or we can call m.group() to get the string matched
                break;
            case 5:
                // IllegalStateException
                String in5 = "123 345 678 901";
                Matcher m5 = Pattern.compile("\\d+").matcher(in5);

                System.out.println(m5.group(0));

                // The Matcher doesn't start matching the string by itself...
                break;
            case 6:
                // ArrayIndexOutOfBoundsException

                // Who is the culprit?
                String[] in6 = {
                    "Nice weather today. Perfect for a stroll along the beach.",
                    " Mmmy  keeyboaardd    iisss   bbrokkkkeeen  ..",
                    "",
                    "\t\t\t     \n\n"};
                for (String s: in6) {
                    System.out.println("First token: " + s.split("\\s+")[0]);
                }

                // Culprit is "\t\t\t     \n\n"
                // String.split() returns array length 1 with empty string if input is empty string
                //                        array length 0 if input is non-empty and all characters match the regex
                break;
            case 7:
                // ConcurrentModificationException

                List<Integer> l7 = testRandom(42);
                Integer prev = null;
                // Remove duplicate numbers from the list
                for (Integer i7: l7) {
                    if (prev == null) {
                        prev = i7;
                    } else {
                        if (i7.equals(prev)) {
                            l7.remove(i7);
                        }
                    }
                }

                System.out.println(l7);

                // This is one of the typical mistakes that Java newbies run into
                break;
            case 8:
                // ArithmeticException

                // Integer division by 0 seems to be the only way to trigger this exception?
                System.out.println(0/0);
                break;
            case 9:
                // ExceptionInInitializerError
                // Thrown when there is an Exception raised during initialization of the class

                // What Exception will be thrown here?
                Static s9 = null;
                System.out.println(s9.k);

                // A bit less interesting
                Static ss9 = new Static();

                // ----
                // A class is only initialized when any of its method/field is
                // used for the first time (directly or indirectly)

                // Below code won't throw Exception, since we never access its fields or methods
                // Static s;
                // OR
                // Static s = null;
                break;
            case 10:
                // BufferOverflowException
                short s10 = 20000;
                ShortBuffer b10 = ShortBuffer.allocate(0).put(s10);

                // Boring stuff...
                break;
            case 11:
                // BufferUnderflowException
                ShortBuffer.allocate(0).get();

                // Another boring stuff...
                break;
            case 12:
                // InvalidMarkException
                ShortBuffer.allocate(0).reset();

                // Boring stuff again...
                // reset() cannot be called if mark() is not called before
                break;
            case 13:
                // IndexOutOfBoundsException
                System.out.println("I lost $m dollars".replaceAll("[$]m\\b", "$2"));

                // $ needs to be escaped in replacement string, since it is special
                break;
            case 14:
                // ClassCastException
                Class c14 = Character.class;
                for (Field f: c14.getFields()) {
                    System.out.println(f);
                    try {
                        int o = (int) f.get(c14);
                        // If the result is of primitive type, it is boxed before returning
                        // Check implementation of sun.reflect.UnsafeStaticIntegerFieldAccessorImpl
                        System.out.println(o);
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }
                }
                break;
            case 15:
                // NoSuchElementException
                List<Integer> l15 = new ArrayList<Integer>();
                Iterator i = l15.iterator();

                System.out.println(i.next());
                // Another boring one...
                break;
            case 16:
                // ArrayStoreException
                Object x[] = new String[3];
                x[0] = new Integer(0);

                // Straight from the documentation
                // I don't even know that this exists...
                break;
            case 17:
                // IllegalThreadStateException
                Thread t17 = new Thread();
                t17.start();
                t17.setDaemon(true);

                // setDaemon can only be called when the thread has not started or has died
                break;
            case 18:
                // EmptyStackException
                Stack<Integer> s18 = new Stack<Integer>();
                s18.addAll(testRandom(43));
                while (s18.pop() != null);

                // Originally ThreadDeath, which works when running from Dr. Java but not when
                // running on cmd line. Seems that Dr. Java provides its own version of
                // Thread.UncaughtExceptionHandler that prints out ThreadDeath.

                // Please make do with this boring Exception
                break;
            case 19:
                // NegativeArraySizeException
                Array.newInstance(Integer.TYPE, -1);

                // Do they have to create such a specific Exception?
                break;
            case 20:
                // OutOfMemoryError
                Array.newInstance(Integer.TYPE, 1000, 1000, 1000, 1000);
                break;
            case 21:
                // UnsupportedCharsetException

                // UCS-2 is superseded by UTF-16
                Charset cs21 = Charset.forName("UCS-2");
                CharsetEncoder ce21 = cs21.newEncoder();

                // Just in case...
                cs21 = Charset.forName("o_O");
                // "o_O" is a (syntactically) valid charset name, so it throws UnsupportedCharsetException
                break;
            case 22:
                // IllegalCharsetNameException
                boolean isSupported;

                isSupported = Charset.isSupported("o_O");
                isSupported = Charset.isSupported("+_+");
                Charset cs22 = Charset.forName("MerryChristmas!Hohoho!");

                // This is getting stupid...
                break;
            case 23:
                // NoClassDefFoundError
                File f = new File("ToBeRemoved.class");
                f.delete();

                ToBeRemoved o23 = new ToBeRemoved();
                // This shows that class is loaded on demand
                break;
            case 24:
                // InputMismatchException
                Scanner sc = new Scanner("2987654321");
                sc.nextInt();

                // Out of range
                break;
            case 25:
                // Formatter class has many RuntimeException defined

                // DuplicateFormatFlagsException
                System.out.printf("%0000000000000000000000000000000000000000000000000005%d\n", 42);
                break;
            case 26:
                // FormatFlagsConversionMismatchException
                System.out.printf("%,d\n", Integer.MAX_VALUE);

                System.out.printf("%,x\n", Integer.MAX_VALUE);
                // Thousand separator is only applicable to base 10

                System.out.printf("%(5.4f\n", Math.PI);
                System.out.printf("%(5.4f\n", -Math.PI);

                System.out.printf("%(5.4a\n", -Math.PI);
                // '(' flag is used to surround negative value with "( )" instead of prefixing with '-'
                // '(' can't be used with conversion 'a'
                break;
            case 27:
                // IllegalFormatCodePointException
                System.out.printf("%c", Character.MAX_CODE_POINT + 1);

                // Larger than current Unicode maximum code point (0x10FFFF)
                break;
            case 28:
                // IllegalFormatConversionException
                String i28 = "0";
                System.out.printf("%d", i28);

                // A boring example
                break;
            case 29:
                // IllegalFormatFlagsException
                System.out.printf("% d\n", Integer.MAX_VALUE);
                System.out.printf("% d\n", Integer.MIN_VALUE);

                System.out.printf("%+d\n", Integer.MAX_VALUE);
                System.out.printf("%+d\n", Integer.MIN_VALUE);

                System.out.printf("% +d\n", Integer.MIN_VALUE);
                // Use either ' ' or '+ ' flag, not both, since they are mutually exclusive
                break;
            case 30:
                // IllegalFormatPrecisionException
                System.out.printf("%5.4f\n", Math.PI);
                System.out.printf("%5.4a\n", Math.PI);
                System.out.printf("%5.4x\n", Math.PI);

                // Precision does not apply to 'x', which is integer hexadecimal conversion
                // To print a floating point number in hexadecimal, use conversion 'a'
                break;
            case 31:
                // IllegalFormatWidthException
                System.out.printf("%3n");

                // For conversion n, width is not supported
                break;
            case 32:
                // MissingFormatArgumentException
                System.out.printf("%s\n%<s", "Pointing to previous argument\n");
                System.out.printf("%<s", "Pointing to previous argument");

                // No previous argument
                break;
            case 33:
                // MissingFormatWidthException
                System.out.printf("%5d %<d\n", 42); // Pad left
                System.out.printf("%-5d %<d\n", 42); // Pad right

                System.out.printf("%-d\n", 42);
                // Missing width
                break;
            case 34:
                // UnknownFormatConversionException
                System.out.printf("%q", "Shouldn't work");

                // No format conversion %q

                // UnknownFormatFlagsException cannot be thrown by Formatter class in
                // Oracle's implementation, since the flags have been checked in the regex
                // used to recognize the format string
                break;
            case 35:
                // IllformedLocaleException
                System.out.printf(new Locale("ja"), "%tA %<tB %<tD %<tT %<tZ %<tY\n", new Date());

                System.out.printf(new Locale.Builder().setLanguage("ja").setScript("JA").setRegion("JA").build(), "%tA %<tB %<tD %<tT %<tZ %<tf\n", new Date());
                // Thrown by Locale.Builder.setScript()
                break;
            case 36:
                // NullPointerException
                Pattern p36 = Pattern.compile("a(b)?c");
                Matcher m36 = p36.matcher("ac");

                if (m36.find()) {
                    for (int i36 = 0; i36 <= m36.groupCount(); i36++) {
                        // Use Matcher#end(num) - Matcher#start(num) for length instead
                        System.out.printf("%3d [%d]: %s\n", i36, m36.group(i36).length(), m36.group(i36));
                    }
                }
                break;
            case 37:
                // AccessControlException
                System.setSecurityManager(new SecurityManager());
                System.setSecurityManager(new SecurityManager());
                break;
            case 38:
                // SecurityException
                // Implementation-dependent
                Class ϲlass = Class.class;
                Constructor[] constructors = ϲlass.getDeclaredConstructors();
                for (Constructor constructor: constructors) {
                    constructor.setAccessible(true);
                    try {
                        Class Сlass = (Class) constructor.newInstance();
                    } catch (Throwable e) {
                        System.out.println(e.getMessage());
                    }
                    // The code should reach here without any Exception... right?
                }

                // It is obvious once you run the code
                // There are very few ways to get SecurityException (and not one of its subclasses)
                // This is one of the ways
                break;
            case 39:
                // UnknownFormatFlagsException
                // Implementation-dependent
                try {
                    System.out.printf("%=d", "20");
                } catch (Exception e) {
                    // Just to show the original Exception
                    System.out.println(e.getClass());
                }

                Class classFormatter = Formatter.class;
                Field[] fs39 = classFormatter.getDeclaredFields();
                boolean patternFound = false;
                for (Field f39: fs39) {
                    if (Pattern.class.isAssignableFrom(f39.getType())) {
                        f39.setAccessible(true);
                        // Add = to the list of flags
                        try {
                            f39.set(classFormatter, Pattern.compile("%(\\d+\\$)?([-#+ 0,(\\<=]*)?(\\d+)?(\\.\\d+)?([tT])?([a-zA-Z%])"));
                        } catch (IllegalAccessException e) {
                            System.out.println(e.getMessage());
                        }
                        patternFound = true;
                    }
                }
                if (patternFound) {
                    System.out.printf("%=d", "20");
                }

                // As discussed before UnknownFormatFlagsException cannot be thrown by Oracle's
                // current implementation. The reflection code above add = to the list of flags
                // to be parsed to enable the path to the UnknownFormatFlagsException.
                break;
        }
    }

    /*
     * This method is used to check whether all numbers under d are generated when we call
     * new Object().hashCode() % d.
     *
     * However, hashCode() is later replaced by System.nanoTime(), since it got stuck at
     * some values when the JVM is stopped and restarted every time (running on command line).
     */
    private static List<Integer> testRandom(int d) {
        List<Integer> k = new ArrayList<Integer>();
        for (int i = 0; i < 250; i++) {
            k.add(new Object().hashCode() % d);
        }
        Collections.sort(k);

        System.out.println(k);

        return k;
    }
}

class ToBeRemoved {};

class Static {
    static public int k = 0;
    static {
        System.out.println(0/0);
    }
}

List of Exceptions and Errors

In order as declared in switch-case statement. There are 37 Exceptions and 3 Errors in total.

PatternSyntaxException (via bug in Pattern, with boring case as backup)
StringIndexOutOfBoundsException (via bug in Pattern, with boring case as backup)
IllegalArgumentException (helps me find a bug in Pattern, with boring case as backup)
StackOverflowError (via recursive implementation in Pattern, with boring case as backup)
NumberFormatException (shows that $ in Pattern can match before final line terminator)
IllegalStateException (via accessing matched groups in Matcher without performing a match)
ArrayIndexOutOfBoundsException (shows confusing behavior of split(String regex))
ConcurrentModificationException (via modifying a Collection during a for-each loop)
ArithmeticException (via integer division by 0)
ExceptionInInitializerError (via causing Exception during initialization of a class)
BufferOverflowException (java.nio.*-specific Exception)
BufferUnderflowException (java.nio.*-specific Exception)
InvalidMarkException (java.nio.*-specific Exception)
IndexOutOfBoundsException (via reference to non-existent capturing group in replacement)
ClassCastException
NoSuchElementException
ArrayStoreException
IllegalThreadStateException
EmptyStackException (java.util.Stack-specific Exception)
NegativeArraySizeException
OutOfMemoryError (via boring allocation of big array)
UnsupportedCharsetException
IllegalCharsetNameException (shows when Charset.isSupported(String name) returns false or throws Exception)
NoClassDefFoundError (shows that classes are loaded on first access to method/constructor or field)
InputMismatchException (java.util.Scanner-specific Exception)
DuplicateFormatFlagsException (from here to 35 are java.util.Formatter-specific Exceptions)
FormatFlagsConversionMismatchException (with interesting example of format syntax)
IllegalFormatCodePointException
IllegalFormatConversionException
IllegalFormatFlagsException
IllegalFormatPrecisionException
IllegalFormatWidthException
MissingFormatArgumentException (with interesting example of format syntax)
MissingFormatWidthException
UnknownFormatConversionException
IllformedLocaleException
NullPointerException
AccessControlException (shows that the default SecurityManager is usable)
SecurityException (via invoking constructor of Class class)
UnknownFormatFlagsException (shows that this Exception can't be thrown in Oracle's implementation, no backup)


Octave, 38 bytes

@(a,b)round(ifft(fft((a:a*b<a+b)).^a))

Try it online!
Explanation
Adding independent random variables corresponds to convolving their probability mass functions (PMF), or multiplying their characteristic functions (CF). Thus the CF of the sum of a independent, identically distributed variables is given by that of a single variable raised to the power of a.
The CF is essentially the Fourier transform of the PMF, and can thus be computed via a FFT. The PMF of a single b-sided die is uniform on 1, 2, ..., b. However, two modifications are required:

1 is used instead of the actual probability values (1/b). This way the result will be de-normalized and will contain integers as required.
Padding with zeros is needed so that the FFT output has the appropriate size (a*b-a+1) and the implicit periodic behaviour assumed by the FFT doesn't affect the results.

Once the characteristic function of the sum has been obtained, an inverse FFT is used to compute the final result, and rounding is applied to correct for floating-point inaccuracies.
Example
Consider inputs a=2, b=6. The code a:a*b<a+b builds a vector with b=6 ones, zero-padded to size a*b-a+1:
[1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0]

Then fft(...) gives
[36, -11.8-3.48i, 0.228+0.147i, -0.949-1.09i, 0.147+0.321i, -0.083-0.577i, -0.083+0.577i, 0.147-0.321i, -0.949+1.09i, 0.228-0.147i, -11.8+3.48i]

One can almost recognize the sinc function here (Fourier transform of a rectangular pulse).
(...).^a raises each entry to a and then ifft(...) takes the inverse FFT, which gives
[1, 2, 3, 4, 5, 6, 5, 4, 3, 2, 1]

Although the results in this case are exactly integers, in general there may be relative errors of the order of 1e-16, which is why round(...) is needed.


Can't see the forest for the trees Write a program or function that draws a tree of trees, thus constructing a forest.

The trees are drawn like stacking a pyramid. The first (top) row contains 1 tree, the next row down contains 2 (for a total of 3), the next contains 3 (for a total of 6), and so on. If there aren't enough trees to complete a full row, fill it to the left and leave the spots on the right empty. Additionally, lower-level trees slightly overlap upper-level trees due to their placement.

This is a forest of size 1

  /\
 //\\
///\\\
  ||
  ||

This is a forest of size 2

      /\
     //\\
  /\///\\\
 //\\ ||
///\\\||
  ||
  ||

This is a forest of size 3

      /\
     //\\
  /\///\\\/\
 //\\ || //\\
///\\\||///\\\
  ||      ||
  ||      ||

This is a forest of size 4

          /\
         //\\
      /\///\\\/\
     //\\ || //\\
  /\///\\\||///\\\
 //\\ ||      ||
///\\\||      ||
  ||
  ||

This is a forest of size 5 (note the top of the fifth tree is covering the trunk of the first tree)

          /\
         //\\
      /\///\\\/\
     //\\ || //\\
  /\///\\\/\///\\\
 //\\ || //\\ ||
///\\\||///\\\||
  ||      ||
  ||      ||

(skip a few)
This is a forest of size 8 (extending the pattern)

              /\
             //\\
          /\///\\\/\
         //\\ || //\\
      /\///\\\/\///\\\/\
     //\\ || //\\ || //\\
  /\///\\\/\///\\\||///\\\
 //\\ || //\\ ||      ||
///\\\||///\\\||      ||
  ||      ||
  ||      ||

and so on.

Input

A single positive integer in any convenient format, n > 0.

Output

An ASCII-art representation of the forest, following the above rules. Leading/trailing newlines or other whitespace are optional, provided that the trees all line up appropriately.

Rules

Either a full program or a function are acceptable. If a function, you can return the output rather than printing it.
Standard loopholes are forbidden.
This is code-golf so all usual golfing rules apply, and the shortest code (in bytes) wins.

Haskell 310 bytes

w i=putStr$unlines$reverse$b i 0 0[][]
b 0 _ _ w r=e w r
b c l 0 w r=b c(l+1)l(e w r)[]
b c l p w r=b(c-1)l(p-1)w(n(++)["  ||    ","  ||    ","///\\\\\\  "," //\\\\   ","  /\\    "]r)
e w r=t++n(n d)(map(\t->"    "++t)w)c where(t,c)=splitAt 2 r
n f(a:c)(b:d)=f a b:n f c d
n _ a[]=a
n _ _ a=a
d d ' '=d
d _ d=d

Call it with w 5, for example.

Here the uncompressed code:

-- TreeTree
-- by Gerhard
-- 12 February 2017

module TreeTree (wood,test) where

type Tree = [String]

-- Test cases
test = do
 wood 0
 wood 1
 wood 2
 wood 3
 wood 4
 wood 5

-- build wood
wood :: Int -> IO ()
wood i = printTree $ buildWood i 0 0 [] []

-- Prints the trees
printTree :: Tree -> IO ()
printTree = putStr . unlines . reverse

-- build wood
buildWood :: Int -> Int -> Int -> Tree -> Tree -> Tree
buildWood 0 _ _ w r = concatTree w r
buildWood c l 0 w r = buildWood c (l+1) l (concatTree w r) []
buildWood c l p w r = buildWood (c-1) l (p-1) w (addTree r)

-- indent definition
space :: String
space = "    "

-- tree definition
tree :: Tree
tree = reverse [
 "  /\\    ",
 " //\\\\   ",
 "///\\\\\\  ",
 "  ||    ",
 "  ||    "]

-- Add a Tree on the left side
addTree :: Tree -> Tree
addTree = match (++) tree

-- add tree row at the bottom of the wood
concatTree :: Tree -> Tree -> Tree
concatTree w r = trunk ++ matched
 where
  wood = grow w
  (trunk, crown) = splitAt 2 r
  matched = matchTree wood crown

-- elnarge forrest on the left side to match next tree line
grow :: Tree -> Tree
grow = map (\t -> space ++ t)

-- match
match :: (a -> a -> a) -> [a] -> [a] -> [a]
match f (a:az) (b:bz) = f a b : match f az bz
match _ a [] = a
match _ _ a  = a

-- match trees
matchTree :: Tree -> Tree -> Tree
matchTree = match matchLine

-- match lines
matchLine :: String -> String -> String
matchLine = match matchChar

-- match chars
matchChar :: Char -> Char -> Char
matchChar c ' ' = c
matchChar _ c   = c

-- End


Permutations in Disguise Given a \$n\$-dimensional vector \$v\$ with real entries, find a closest permutation \$p\$ of \$(1,2,...,n)\$ with respect to the \$l_1\$-distance.
Details

If it is more convenient, you can use permutations of \$(0,1,...,n-1)\$ instead. If there are multiple closest permutations, you can output any one or alternatively all of them.
The \$l_1\$ distance between two vectors \$u,v\$ is defined as $$d(u,v) = \sum_i \vert u_i-v_i\vert.$$
If you want, you can assume that the input solely consists of integers.

Examples
[0.5  1] -> [1 2], [2 1]
c*[1 1 ... 1] -> any permutation
[1 4 2 6 2] -> [1 4 3 5 2], [1 4 2 5 3]
[1 3 5 4 1] -> [2 3 5 4 1], [1 3 5 4 2]
[7 7 3 2 5 6 4 2] -> [8 7 3 2 5 6 4 1], [8 7 3 1 5 6 4 2], [7 8 3 2 5 6 4 1], [7 8 3 1 5 6 4 2]
[-2 4 5 7 -1 9 3] -> [1 4 5 6 2 7 3], [2 4 5 6 1 7 3], [1 4 5 7 2 6 3], [2 4 5 7 1 6 3]
[0 4 2 10 -1 10 5] -> [1 4 2 6 3 7 5], [1 4 3 6 2 7 5], [2 4 3 6 1 7 5], [3 4 2 6 1 7 5], [1 4 2 7 3 6 5], [1 4 3 7 2 6 5], [2 4 3 7 1 6 5], [3 4 2 7 1 6 5]

Octave script for generating more examples.

Python 2, 60 bytes

def f(l):z=zip(l,range(len(l)));print map(sorted(z).index,z)

Try it online!

Uses zero-indexing.

A fast algorithm with a simple idea. If we instead need to permute the input list to make it as close to \$(1,2,...,n)\$ as possible, we should just sort it, as proven below. Since we're instead permuting \$(1,2,...,n)\$, we choose the permutation that's ordered the same way as the input list, like in my challenge Imitate an ordering (except the input may have repeats). (Edit: miles pointed out this more identical challenge, where Dennis has this same answer.)

  Claim: A permutation of the list \$l\$ that minimizes its distance to \$(1,2,...,n)\$ is \$l\$ sorted.

  Proof: Consider some other permutation \$l'\$ of \$l\$. We'll prove it can't be better than \$l\$ sorted.

  Pick two indices \$i,j\$ that \$l'\$ has out-of-order, that is where \$i<j\$ but  \$l'_i > l'_j\$. We show that swapping them can't increase the distance to \$(1,2,...,n)\$. We note that swap changes the contribution these two elements as follows:
  $$ |l'_i - i | + |l'_j - j | \to |l'_i - j | + |l'_j - i|.$$

  Here's a neat way to show this can't be an increase. Consider two people walking on a number line, one going from \$l'_i\$ to \$i\$ and the other from \$l'_j\$ to \$j\$. The total distance they walk is the expression on the left. Since \$i<j\$ but \$l'_i > l'_j\$, they switch who is higher on the number line, which means they must cross at some point during their walks, call it \$p\$. But when they reach \$p\$, they could then swap their destinations and walk the same total distance. And then, it can't be worse for them to have walked to their swapped destinations from the start rather than using \$p\$ as a waypoint, which gives the total distance on the right-hand side.

  So, sorting two out-of-order elements in \$l'\$ makes its distance to \$(1,2,...,n)\$ smaller or the same. Repeating this process will sort \$l\$ eventually. So, \$l\$ sorted is at least as good as \$l'\$ for any choice of \$l'\$, which means it as optimal or tied for optimal.

Note that the only property of \$(1,2,...,n)\$ that we used is that it's sorted, so the same algorithm would work to permute any given list to minimize its distance to any fixed list.

In the code, the only purpose of z=zip(l,range(len(l))) is to make the input elements distinct, that is to avoid ties, while keeping the same comparisons between unequal elements. If the input we guaranteed to have no repeats, we could remove this and just have lambda l:map(sorted(l).index,l).


Computer Generated Textured Wall Paint The paint on the walls in my room has a random, almost fractal-like, 3-dimensional texture:

In this challenge you will write a program that generates random images that look like they could be part of my walls.
Below I've collected 10 images of different spots on my walls. All have roughly the same lighting and all were taken with the camera one foot away from the wall. The borders were evenly cropped to make them 2048 by 2048 pixels, then they were scaled to 512 by 512. The image above is image A.
These are only thumbnails, click images to view at full size!
A:
B:
C:
D:
E:
F:
G:
H:
I:
J:
Your task is to write a program that takes in a positive integer from 1 to 216 as a random seed, and for each value generates a distinct image that looks like it could have been the "eleventh image" of my wall. If someone looking at my 10 images and a few of yours can't tell which were computer generated then you've done very well!
Please show off a few of your generated images so viewers can see them without having to run the code.
I realize that the lighting in my images is not perfectly uniform in intensity or color. I'm sorry for this but it's the best I could do without better lighting equipment. Your images do not need to have variable lighting (though they could). The texture is the more important thing to focus on.
Details

You may use image processing tools and libraries.
Take the input in any common way you desire (command line, stdin, obvious variable, etc).
The output image can be in any common lossless image file format, or it can just be displayed in a window/bowser.
You may programmatically analyze my 10 images but don't assume that everyone running your code has access to them.
You must generate the images programmatically. You may not hard-code a slight variant of one of my images or some other stock image. (People would vote you down for this anyway.)
You may use built-in pseudorandom number generators and assume the period is 216 or more.

Scoring
This is a popularity contest so the highest-voted answer wins.

GLSL (+ JavaScript + WebGL)

Live demo | GitHub repository

How to use

Reload the page for a new random image. If you want to feed in a particular seed, open your browser's console and call drawScreen(seed). The console should display the seed used on load.

I haven't really tested this on a lot of platforms, so let me know if it doesn't work for you. Of course, your browser needs to support WebGL. Errors are displayed either in the column on the left, or in the browser's console (depending on the type of error).

New: You can now bring the walls to life a bit, by ticking the "movable light source" checkbox.

What is this sorcery?

I've got this WebGL boilerplate code floating around my GitHub account, which I use every now and then to quickly prototype some 2D graphics things in WebGL. With some shader magic, we can also make it look slightly 3D, so I thought that was the quickest way to get some nice effects going. Most of the setup is from that boilerplate code, and I'm considering that a library for this submission and won't include it in this post. If you're interested, have a look at the main.js on GitHub (and the other files in that folder).

All the JavaScript does is to set up a WebGL context, store the seed in a uniform for the shader, and then render a single quad over the entire context. The vertex shader is a simple passthrough shader, so all the magic happens in the fragment shader. That's why I called this a GLSL submission.

The largest part of the code is actually to generate the Simplex noise, which I found on GitHub. So I'm omitting that as well in the code listing below. The important part is, it defines a function snoise(vec2 coords) which returns simplex noise without using a texture or array lookup. It's not seeded at all, so the trick to getting different noise is to use the seed in determining where to do the lookup.

So here goes:

#ifdef GL_ES
precision mediump float;
#endif
#extension GL_OES_standard_derivatives : enable

uniform float uSeed;
uniform vec2 uLightPos;

varying vec4 vColor;
varying vec4 vPos;

/* ... functions to define snoise(vec2 v) ... */

float tanh(float x)
{
    return (exp(x)-exp(-x))/(exp(x)+exp(-x));
}

void main() {
    float seed = uSeed * 1.61803398875;
    // Light position based on seed passed in from JavaScript.
    vec3 light = vec3(uLightPos, 2.5);
    float x = vPos.x;
    float y = vPos.y;

    // Add a handful of octaves of simplex noise
    float noise = 0.0;
    for ( int i=4; i>0; i-- )
    {
        float oct = pow(2.0,float(i));
        noise += snoise(vec2(mod(seed,13.0)+x*oct,mod(seed*seed,11.0)+y*oct))/oct*4.0;
    }
    // Level off the noise with tanh
    noise = tanh(noise*noise)*2.0;
    // Add two smaller octaves to the top for extra graininess
    noise += sqrt(abs(noise))*snoise(vec2(mod(seed,13.0)+x*32.0,mod(seed*seed,11.0)+y*32.0))/32.0*3.0;
    noise += sqrt(abs(noise))*snoise(vec2(mod(seed,13.0)+x*64.0,mod(seed*seed,11.0)+y*64.0))/64.0*3.0;

    // And now, the lighting
    float dhdx = dFdx(noise);
    float dhdy = dFdy(noise);
    vec3 N = normalize(vec3(-dhdx, -dhdy, 1.0)); // surface normal
    vec3 L = normalize(light - vec3(vPos.x, vPos.y, 0.0)); // direction towards light source
    vec3 V = vec3(0.0, 0.0, 1.0); // direction towards viewpoint (straight up)
    float Rs = dot(2.0*N*dot(N,L) - L, V); // reflection coefficient of specular light, this is actually the dot product of V and and the direction of reflected light
    float k = 1.0; // specular exponent

    vec4 specularColor = vec4(0.4*pow(Rs,k));
    vec4 diffuseColor = vec4(0.508/4.0, 0.457/4.0, 0.417/4.0, 1.0)*dot(N,L);
    vec4 ambientColor = vec4(0.414/3.0, 0.379/3.0, 0.344/3.0, 1.0);

    gl_FragColor = specularColor + diffuseColor + ambientColor;
    gl_FragColor.a = 1.0;
}

That's it. I might add some more explanation tomorrow, but the basic idea is:

Choose a random light position.
Add up a few octaves of noise, to generate the fractal pattern.
Square the noise to keep the bottom rough.
Feed the noise through tanh to level off the top.
Add two more octaves for a little bit more texture on the top layer.
Compute the normals of the resulting surface.
Run a simple Phong shading over that surface, with specular and diffuse lights. The colours are chosen based on some random colours I picked from the first example image.


Code Golf Golf Score It's Friday... so let's go golfing!  Write code that determines the player's scoring on a hole in a game of golf.  The code can be either a function or entire program. As the genre suggests, shortest code wins.

Input (parameters or stdin, your choice):

An integer representing the hole's par, guaranteed to be between 3 and 6
An integer representing the golfer's score, guaranteed to be between 1 and 64

Output (print to stdout or return, trailing newline allowed but not required, your choice):

if score is 1, output "Hole in one"
if score == par - 4 and par > 5, output "Condor"
if score == par - 3 and par > 4, output "Albatross"
if score == par - 2 and par > 3, output "Eagle"
if score == par - 1, output "Birdie"
if score == par, output "Par"
if score == par + 1, output "Bogey"
if score == par + 2, output "Double Bogey"
if score == par + 3, output "Triple Bogey"
if score > par + 3, output "Haha you loser"

EDIT
Congrats to Dennis on having the shortest answer!

PHP 5.3+, 173 167 166 159 156 151 127 121 bytes

echo[Condor,Albatross,Eagle,Birdie,Par,$b=Bogey,"Double $b","Triple $b","Haha you loser"][min(4+$s-$p,8)]?:"Hole in one";

Notice-free version, 139 137 bytes

echo$s-1?["Condor","Albatross","Eagle","Birdie","Par",$b="Bogey","Double $b","Triple $b","Haha you loser"][min(4+$s-$p,8)]:"Hole in one";

Set $score and $par variables before the echo and you're off.

exploded view

echo [Condor,
      Albatross,
      Eagle,
      Birdie,
      Par,
      $b = Bogey,
      "Double $b",
      "Triple $b",
      "Haha you loser"][ min( 4+$s-$p,8 ) ]
  ?: "Hole in one";

Edits
-6: Not storing the array, just calling it if need be.
-1: Flipping the ternary around.
-7: The lowest $s-$p with $s>1 is -4, so the max() isn't necessary, since 4+$s-$p >= 0.
-3: Array -> explode(), thanks CoolestVeto!
-5: Cheaty string literal undefined constant plus $r[-1] -> false, thanks Ismael Miguel!
-24: Moving from an explode() function to a printf/%s setup, with some tweaks, more thanks to Ismael Miguel for the change of direction.
-6: Swerve, we're back to echo again!


Compound Interest... with Wizard Money Gringotts isn't just a vault, but a reputable financial institution and wizards need loans too. Since you don't want to be screwed over by the Gringotts goblins, you decided it would be a good idea to write a program to calculate interest. Interest is compounded only yearly.

Your task is to calculate total owed amount after interest given the principal, interest rate, and time (whole years), operating in whole denominations of wizard money, rounding down to the nearest whole Knut. There are 29 Bronze Knuts in a Silver Sickle and 17 Sickles in a Gold Galleon.

Example

Loan taken out:
 23 Knuts
 16 Sickles
103 Galleons
@ 7.250%
For 3 years

Total owed after interest:
 24 Knuts
  4 Sickles
128 Galleons

Notes and Rules

Input and output may be in any convenient format. You must take in Knuts, Sickles, Galleons, interest rate, and time. All but interest rate will be whole numbers. The interest rate is in increments of 0.125%.
Input money is not guaranteed to be canonical (i.e. you can have 29 or more Knuts and 17 or more Sickles.)
Output must be the canonical representation. (i.e. less than 29 Knuts and less than 17 Sickles)
Totals owed, up to 1,000 Galleons, should be accurate to within 1 Knut per year of interest when compared with arbitrary precision calculations.

You may round down after each year of interest or only at the end. Reference calculations can take this into account for accuracy checks.

Happy golfing!

R, 70 62 bytes

function(d,i,y)(x=d%*%(a=c(1,29,493))*(1+i)^y)%/%a%%c(29,17,x)

Try it online!

Takes input as d: deposit in knuts, sickles, galleons; i: interest rate as decimal; y: years. Outputs final deposit in knuts, sickles, galleons. Thanks to @Giuseppe for using matrix multiplication to save some bytes (and pointing out how to avoid the need to wrap at 1e99).


Evaluate an expression of minus and tilde Given an expression matching the regex /^[-~]*x$/, evaluate it in terms of x and output a string matching the regex /^-?x[+-]\d+$/.

For example, the string -~x evaluates to x+1, while the string -~-x evaluates to -x+1, and the string -~-~--x evaluates to x+2.

We start from x and evaluate the string right to left. - negates the term, while ~ converts y to -y-1.

Testcases:

    x  x+0
   ~x -x-1
  -~x  x+1
 ~-~x -x-2
-~-~x  x+2
--~~x  x+0
  ~-x  x-1
 -~-x -x+1

This is code-golf. Shortest answer in bytes wins.

The input/output format is strict. The "x" is mandatory.

Python 2, 42 41 39 bytes

lambda s,x=0:'-x%+d'[len(s)%2:]%eval(s)

Try it online!


N in a row (or column)! N in a row

Input:

The character and a 2-Dimensional array.

The array with a size of N x N where 1 <= N <= 26, it will be filled randomly like so:

N = 1

A

N = 2

B | A
-----
A | B

N = 3

A | B | C
----------
B | A | B
----------
C | A | C

As N increases by 1, so does the number of letters. A = 1, B = 2, C = 3. There will always be N number of each letter.
N = 3, there will be 3 As... 3 Bs... 3 Cs...
N = 4, there will be 4 As... 4 Bs... 4 Cs... 4 Ds...
N = 5, there will be 5 As... 5 Bs... 5 Cs... 5 Ds... 5 Es...

Output:

The original matrix as well as a manipulated matrix where any given letter has N in a row (or column).

Manipulations occur by swapping two letters within the 2-D grid that are adjacent on the x or y axis. You may not swap characters over the boundaries of the array. I.E. You cannot swap Array[0][N-1] with Array[0][0]. You also may not swap characters diagonally.

Objective:

Your job is to pick a character C to solve for given N. Swap characters within the matrix so that there are N of C in the same row or column.

Examples:

N = 3, C = A

A | B | C
----------
B | A | B
----------
C | A | C

Swap array[0][0] (A) with array[1][0] (B)
resulting in

B | A | C
----------
B | A | B
----------
C | A | C

Complete

N = 4, C = B

A | B | C | D
--------------
B | D | B | A
--------------
D | A | C | C
--------------
A | C | B | D

swap array[1][0] (B) with array[1][1] (D)

A | D | C | D
--------------
B | B | B | A
--------------
D | A | C | C
--------------
A | C | B | D

swap array[2][3] (B) with array[3][3] (D)

A | D | C | D
--------------
B | B | B | A
--------------
D | A | C | C
--------------
A | C | D | B

swap array[3][3] (B) with array[3][2] (C)

A | D | C | D
--------------
B | B | B | A
--------------
D | A | C | B
--------------
A | C | D | C

swap array[3][2] (B) with array[3][1] (A)

A | D | C | D
--------------
B | B | B | B
--------------
D | A | C | A
--------------
A | C | D | C

Complete!

Any letter can be chosen to solve for. As this is code-golf the shortest code wins!

Have Fun and Good Luck!

Python 2, 270 bytes

from random import*
e=lambda s,n:all(sum(map(ord,l))!=n*65for l in s)
R,C,d=randint,choice,[-1,1]
def w(a):
 print a;n=len(a);
 while e(a,n)and e(zip(*a),n):
    if n==2:x,y,w,z=0,0,0,1
    else:x,y=R(1,n-2),R(1,n-2);w,z=x+C(d),y+C(d)
    a[y][x],a[z][w]=a[z][w],a[y][x]
 print a

Always chooses A as character to complete a row/col. Performs random swaps until goal is reached.
Accepts the matrix as list of lists, usage for testing:
A="""ADCD
BBBA
DACC
ACDB"""
a=[[c for c in l] for l in A.split('\n')]
w(a)


Paper and Envelope Sizes Task

Given a letter (A, B, C), and a number (0-10), output the size of the matching standard paper size (Series A and B) or the matching standard envelope size (C series) in millimetres in the format aaaa x bbbb where aaaa and bbbb are the width and height measurements in millimetres as per ISO216 (Series A & B) or ISO296 (Series C)

To make things easier I will quote from Wikipedia's table of Paper Sizes

ISO paper sizes in portrait view
Format  A series    B series    C series
Size     mm × mm      mm × mm    mm × mm
0       841 × 1189  1000 × 1414 917 × 1297
1       594 × 841    707 × 1000 648 × 917
2       420 × 594    500 × 707  458 × 648
3       297 × 420    353 × 500  324 × 458
4       210 × 297    250 × 353  229 × 324
5       148 × 210    176 × 250  162 × 229
6       105 × 148    125 × 176  114 × 162
7        74 × 105     88 × 125   81 × 114
8        52 × 74      62 × 88    57 × 81
9        37 × 52      44 × 62    40 × 57
10       26 × 37      31 × 44    28 × 40

So examples of input and output:

**Test case 1**
Input: A4
Output: 210 x 297

**Test Case 2**
Input: B6
Output: 125 x 176

**Test Case 3**
Input: C2
Output: 458 x 648

Things to note:

The format "210 x 297" or "1000 x 1414" etc. While this is the preferable format, You can choose to omit the " x " from your output, i.e. in the form of an array or two numbers or whatever tickles your fancy as long as the width measurement is outputted before the height.
The ratio between the height and the width is roughly equivalent to the square root of 2, so in the calculation of the heights, the width is multiplied by sqrt(2), and then rounded up or down to the nearest millimetre, thus resulting in the measurements in the table above. This may help golf down your code.
In successive sizes for a series as you go down the table, the width for one size becomes the height for the next. This may also help you golf down your code.

Rules:

This is code-golf. Standard rules apply as a result. The score will be based on byte count. Lowest count will win.
No silly loopholes, we've been there before... We shan't go through this again.
If you can code it, then please also consider attaching a link to a working instance of your code so that other programmers and golfers can learn how your code works. This is not mandatory, but I'd like to encourage others to do this so we can all learn off one another. I certainly would love to learn more about other golfer's languages where possible.

Best of luck.

JavaScript (ES7), 57 bytes

Saved 1 byte thanks to @WallyWest

s=>n=>[n,n-1].map(x=>.707**x*{A:841,B:1e3,C:917}[s]+.2|0)


Determine if a number is less than another Introduction
Your job is to write a function or program that detects if a number a is less than a number b.
But... You are not allowed to use built-in alternatives for equals, less than, greater than, less than or equal to, greater than or equal to, or not equal to operators. (Writing your own implementation is allowed.) Similar alternative methods/alternatives in other languages that are designed to replace those operations are also restricted.
You are allowed to use operators that are not banned, e.g. bitwise operators and the not operator (but it would be better if your answer did not have the not operator).
Challenge
Simply return a truthy or falsy value (or something that evaluates in the language to true or false like 0 or 1) to indicate whether a is less than b. The winner of the challenge can be determined by the shortest code. External sources are not allowed, but anonymous functions are. Explaining your answer is not mandatory, but encouraged.
Example using Javascript:
(a,b)=>!!Math.max(0,b-a) //remove the !! for truthy and falsy numbers
/*Explanation
(a,b)                    Parameters a and b
     =>                  Function is
       !!                returns true if truthy and false if falsy
         Math.max(0,b-a) returns the greater number, 0 or b-a
*/

Examples of Input and Output
Input | Output
------|-------
1, 3  | true
2, 2  | false
3, 2  | false

APL (Dyalog Unicode), 2 bytesSBCS

Anonymous tacit prefix function. Requires ⎕IO←0

⊃⍒

Try it online!

⍒ gives the "grade". The indices into the argument that would stably sort it in descending order

If the first element is less than the second, it gives [1,0]
If the the elements are equal, it gives [0,1]
If the second element is less than the second, it gives [0,1]

⊃ picks the first element of that

If the first element is less than the second, it gives 1
If the the elements are equal, it gives 0
If the second element is less than the second, it gives 0


Write a function that tells you which of its lines has been removed Write a function that contains five lines.

If you run the function as-is, it should return 0.

If you remove any one of the five lines and run the function, it should tell you which of the lines has been removed (e.g., if you remove the final line it should return 5).

Brevity, novelty, and elegance all deserve consideration.  Highest upvoted solution (after a reasonable amount of time) wins.

Ruby

Eschewing magic numbers since it's not code golf.

def f
  r=2^3^4^5
  defined?(r) ? r^=2 : r=1^3^4^5
  r^=3
  r^=4
  r^=5
end

Each line strips its own number out of 1^2^3^4^5. It's Ruby, so the last line defines the return value.


Verify a Minesweeper board Your goal is to check whether a completed Minesweeper board is valid. This means that each number is a correct count of mines in cells adjacent to it, including diagonals. The board does not wrap around.

As usual, you should give a function or program, and shortest code in bytes wins.

See also past challenges to generate, solve, and fully implement Minesweeper.

Input:

A single string like this: 02X2 13X2 X211.

The rows of the minesweeper board are given separated by spaces. So, the above represents the 3x4 board:

02X2
13X2
X211
Each cell is a character: X for a mine, or a number 0 through 8.
All rows have the same length.
There are at least 3 rows and 3 columns.
The input doesn't start or end with a space, but you may include a newline at the end if you wish.

Output:

A consistent Truthy on correct boards, and a consistent Falsey value on incorrect boards. Consistent means that all Truthy outputs are the same and all Falsey outputs are the same.

Test cases

Each line is a separate test case.

True:

02X2 13X2 X211
XXXX XXXX XXXX XXXX
XX4X2 5X6X4 XX6XX 4XX54 2X4XX

False:

02X2 13X2 X212
XXXX XXXX X7XX XXXX
XX5X2 5X6X4 XX6XX 4XX54 2X5XX

Python 2, 132 129 128
def f(s):w=s.find(' ');E=dict(enumerate(s));return all(E[i]in' X'+`sum(E.get(i+d/3*~w+d%3+w,5)>'O'for d in range(9))`for i in E)

I used enumerate in a golf...and even used range elsewhere in the same program. Clearly something is wrong here.
Edit: Iterate over dict(enumerate(s)) rather than enumerate(s), so enumerate does not need to be called twice.


Largest Number in Brainfuck BigInt for each program length up to 50 instructions This challenge is for the largest finite number you can get BrainFuck programs of given lengths to contain in memory.

We must use one of the BF versions that uses big integers for the cells rather than byte values as not to be capped at 255. Do not use negative positions and values in memory. Do not use the BF instruction to input memory, also the output instruction is not needed.

Challenge:

Write Brainfuck programs with lengths from 0 to 50. Your score is the sum of each programs maximum value in memory.

As they may well be trivial feel free to omit the programs listed below and start from a length of 21, I'll use the following for the smaller sizes:

Length, Score, Program

0, 0
1, 1, +
2, 2, ++
3, 3, +++
Pattern Continues
10, 10, ++++++++++
11, 11, +++++++++++
12, 12, ++++++++++++
13, 16, ++++[->++++<]
14, 20, +++++[->++++<]
15, 25, +++++[->+++++<]
16, 30, ++++++[->+++++<]
17, 36, ++++++[->++++++<]
18, 42, +++++++[->++++++<]
19, 49, +++++++[->+++++++<]
20, 56, ++++++++[->+++++++<]

Total Score: 352

Related but different:

Large Numbers in BF

Largest Number Printable

Busy Brain Beaver

See the comments below for more info.

The combined results so far, being the sum of the best of each size:

length: 50
by l4m2

(262) - 2

length: 49
by l4m2

(212) - 2

length: 48
based on code by l4m2, by alan2here

(172) - 2

length: 39 to 47
based on code by l4m2, by alan2here

Σ (n = 4 to 12) of (fn(0) | f(x) := (4x+2 - 4) / 3)

length: 38
based on code by l4m2, by alan2here

(4^1366 - 4) / 3

length: up to 37
by alan2here

x |
  x > 6 ^ 20
  x > n
  x ≈ n
  n = 3,657,880,038,459,860


Let's play tennis 2: east-west game There is a challenge Let's play tennis by Daniel. He proposes to place a court in the North-South direction. My proposal is to create a court to play tennis in the East-West direction too.

You have to print a tennis court, but you have to do it in the fewest bytes possible because of confidential reasons.

Tennis court

------x------
|  |  x  |  |
|  |--x--|  |
|  |  x  |  |
------x------

Original rules are:

No extra spaces.
No tabs as they would be unfair.
One optional trailing newline is allowed.

This is code-golf, so shortest code in bytes wins!

Python 2, 59 bytes

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

Try it online!

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

Python 2, 59 bytes

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

Try it online!

Using Jo King's construction.

Python 2, 62 bytes

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

Try it online!

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


Filter a large file quickly The challenge is to filter a large file quickly.

Input: Each line has three space separated positive integers.
Output: All input lines A B, Tthat satisfy either of the following criterion.

There exists another input line C, D, U where D = A and 0 <= T - U < 100.
There exists another input line C, D, U where B = C and 0 <= U - T < 100.

To make a test file use the following python script which will also be used for testing. It will make a 1.3G file. You can of course reduce nolines for testing.

import random
nolines = 50000000 # 50 million
for i in xrange(nolines):
    print random.randint(0,nolines-1), random.randint(0,nolines-1), random.randint(0,nolines-1)

Rules. The fastest code when tested on an input file I make using the above script on my computer wins.  The deadline is one week from the time of the first correct entry.

My Machine The timings will be run on my machine. This is a standard 8GB RAM ubuntu install on an AMD FX-8350 Eight-Core Processor.  This also means I need to be able to run your code.

Some relevant timing information

Timings updated to run the following before each test.

sync && sudo bash -c 'echo  3 > /proc/sys/vm/drop_caches'

time wc test.file

real    0m26.835s
user    0m18.363s
sys     0m0.495s

time sort -n largefile.file  > /dev/null

real    1m32.344s
user    2m9.530s
sys     0m6.543s

Status of entries

I run the following line before each test.

sync && sudo bash -c 'echo  3 > /proc/sys/vm/drop_caches'

Perl (Waiting for bug fix.)
Scala 1 minutes 37 seconds by @James_pic. (Using scala -J-Xmx6g Filterer largefile.file output.txt)
Java. 1 minute 23 seconds by @Geobits. (Using java -Xmx6g Filter_26643)
C. 2 minutes 21 seconds by @ScottLeadley.
C. 28 seconds by @James_pic.
Python+pandas. Maybe there is a simple "groupby" solution?
C. 28 seconds by @KeithRandall.

The winners are Keith Randall and James_pic.

I couldn't tell their running times apart and both are almost as fast as wc!

C, ~ 7 4.1 seconds

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


Mountain range numbers Mountain range number

A number is a mountain range number if the inequalities satisfied by their consecutive digits alternate. In a way, looking at the number's digits should exhibit a /\/\/\... or a \/\/\/... pattern.

More formally, if our number n has \$k\$ digits

$$n = d_1d_2d_3\cdots d_k$$

then n is a mountain range number if

$$\begin{cases}d_1 > d_2 \\ d_2 < d_3 \\ d_3 > d_4 \\ \cdots \end{cases} \vee \begin{cases}d_1 < d_2 \\ d_2 > d_3 \\ d_3 < d_4 \\ \cdots \end{cases}$$

Your task

Given an integer with 3 or more digits, output a Truthy value if the number is a mountain range number or Falsy otherwise.

Input

A positive integer n with 3 or more digits, in any reasonable format, e.g.

Integer
String
List of digits

Test cases

Truthy

1324 -> Truthy
9191 -> Truthy
12121 -> Truthy
121212 -> Truthy
1212121 -> Truthy
19898 -> Truthy

Falsy

(Added another Falsy test case as per the comments, some answers might not cover the 4422 test case)

123 -> Falsy
321 -> Falsy
4103 -> Falsy
2232 -> Falsy
1919199 -> Falsy
4422 -> Falsy

This is code-golf so shortest answer in bytes wins! Standard loopholes are forbidden.

R, 44 40 bytes

 crossed out 44 is still regular 44

-1 byte thanks to Giuseppe.

function(x,d=diff)all(d(sign(d(x)))^2>3)

Try it online!

Computes the differences of the signs of the differences of the input. These must all be equal to 2 or -2, i.e. the square must equal 4; checking that the square is >3 is sufficient.

If two consecutive digits are equal, there will be a 0 in the signs of differences, leading to a difference of signs of differences equal to 1 or -1. If three consecutive digits are in ascending or descending order, then the corresponding differences will be of the same sign, leading to a difference of signs of differences equal to 0. If neither of these occurs, the number is a mountain range number.

Old version (included as it might be golfable):

R, 44 43 bytes

-1 byte thanks to Giuseppe.

function(x)all(s<-sign(diff(x)),rle(s)$l<2)

Try it online!

Computes the signs of the differences of consecutive digits. Then verifies that

none of the signs are 0s (would correspond to 2 equal consecutive digits);
the runs of the signs are all equal to 1, i.e. no 2 consecutive signs are equal.


Placing circles along a square spiral In this code golf challenge, you'll be computing the placement of circles of areas \$\pi, 2\pi, 3\pi, \dots\$ when greedily placed along integer points in a square spiral in such a way that no two overlap.
A square spiral is a sequence in \$\mathbb Z^2\$ that starts at \$(0,0)\$ and successively wraps around the origin. (Like Arnauld, you might find inspiration from this CGSE question.)
(0, 0) -> (1, 0) -> (1, 1) -> (0, 1) -> (-1, 1) -> (-1, 0) -> (-1, -1) -> (0, -1) -> (1, -1) -> (2, -1) -> (2, 0) -> (2, 1) -> (2, 2) -> (1, 2) -> (0, 2) -> (-1, 2) -> (-2, 2) -> (-2, 1) -> (-2, 0) -> (-2, -1) -> (-2, -2) -> (-1, -2) -> (0, -2) -> (1, -2) -> (2, -2) -> (3, -2) -> (3, -1) -> (3, 0) -> (3, 1) -> (3, 2) -> ...

In this challenge, you will start at the origin, walk around the spiral, and place circles with areas \$\pi, 2\pi, 3\pi\$, at integer points in a greedy fashion, as shown in the GIF below.
The first seven circles are:

a circle of area \$\pi\$ placed at \$(0,0)\$,
a circle of area \$2\pi\$ placed at \$(2,2)\$,
a circle of area \$3\pi\$ placed at \$(-2,2)\$,
a circle of area \$4\pi\$ placed at \$(3,-2)\$,
a circle of area \$5\pi\$ placed at \$(-3,-3)\$,
a circle of area \$6\pi\$ placed at \$(5,5)\$, and
a circle of area \$7\pi\$ placed at \$(0,6)\$.

Again, the circles are placed as soon as they fit. The second circle could not be placed at \$(1,0)\$, \$(1,1)\$, \$(0,1)\$, \$(-1,1)\$, \$(-1,0)\$, \$(-1, -1)\$, \$(0,-1)\$, \$(1, -1)\$, \$(2, -1)\$, \$(2, 0)\$, or \$(2, 1)\$ without overlapping with the first circle, but it could be—and is—placed at \$(2,2)\$.
Once we've placed "all" of the blue circles, we start over. In the second generation, we place "red" circles with areas \$\pi, 2\pi, 3\pi\$, in a greedy fashion:

Once we've placed all of the red circles from the second generation, we move onto yellow circles, cyan circles, magenta, dark green, purple, light green, orange, brown circles, and so on.

Challenge
Okay! That's a lot of setup! Here's your code-golf challenge:
Write a program that takes in two positive (alternatively, \$0\$-indexed) integers, g and k, and outputs the position of the circle of area \$k\pi\$ in the \$g\$-th generation.
When \$g=1\$, this corresponds to the blue circles; when \$g=2\$, this corresponds to the red circles; when \$g=3\$, the yellow circles, and so on.
Your program should be able to compute all of the values in the following table in practice, and it should be able to compute bigger values (without running into floating point errors) in principle.
Data table
 g |  k | position   | (color in GIFs; for reference only)
---+----+------------+------------------------------------
 1 |  1 | (0, 0)     | blue
 1 |  2 | (2, 2)     | blue
 1 |  3 | (-2, 2)    | blue
 1 | 50 | (36, -18)  | blue
 2 |  1 | (0, -4)    | red
 2 |  2 | (-3, 9)    | red
 2 | 14 | (-2, -59)  | red
 2 | 15 | (-66, 28)  | red
 3 |  1 | (-5, 2)    | yellow
 3 |  2 | (4, -10)   | yellow
 3 | 10 | (-58, 3)   | yellow
 8 |  1 | (-6, 10)   | orange
 8 |  2 | (16, 21)   | orange
 8 |  3 | (-27, -19) | orange
 9 |  1 | (-10, 6)   | orange
 9 |  2 | (-25, 4)   | orange
 9 |  3 | (17, -27)  | orange

JavaScript (ES7),  319  309 bytes
Expects (g)(k) and returns [x,y].
The formula for the spiral coordinates was inspired by this answer from Neil.

g=>k=>{a=[];p=[];r=[];H=Math.hypot;F=n=>{while((j=p[n]=-~p[n],C=_=>((i+2>>2)-i%2*j)*~-(i--&2),x=C(i=(--j*4+1)**.5|0,j-=i*i>>2),y=C(),n)&&a.every(([N,X,Y])=>~N+n|H(X,Y)<2*H(x,y))&&!F(n-1,p[n]--)||a.some(([_,X,Y,R])=>H(X-x,Y-y)<R**.5+q**.5,q=-~r[n]));a.push([n,x,y,r[n]=q])};while(~~r[g-1]<k)F(g-1);return[x,y]}

Try it online!
How?
One tricky point in the challenge is to figure out how many circles of generation \$n-1\$ must be processed before we can start generation \$n\$.
In this implementation, we don't attempt to put a new circle of generation \$n\$ at \$(x_0,y_0)\$ until there's at least one circle of generation \$n-1\$ at \$(x_1,y_1)\$ which is at least twice as far from the center of the spiral:
$$\sqrt{{x_1}^2+{y_1}^2}\ge2\times \sqrt{{x_0}^2+{y_0}^2}$$


Tips for golfing in R I'm looking for tips for golfing in the R statistical language.  R is perhaps an unconventional choice for Golf.  However, it does certain things very compactly (sequences, randomness, vectors, and lists), many of the built-in functions have very short names, and it has an optional line terminator (;).  What tips and tricks can you give to help solve code golf problems in R?

Some tips:

In R, it's recommended to use <- over =. For golfing, the
opposite holds since = is shorter...
If you call a function more than once, it is often beneficial to
define a short alias for it:

as.numeric(x)+as.numeric(y)

a=as.numeric;a(x)+a(y)

Partial matching can be your friend, especially when functions
    return lists which you only need one item of.  Compare
    rle(x)$lengths to rle(x)$l
Many challenges require you to read input. scan is often a good fit for this (the user ends the input by entring an empty line).

scan()    # reads numbers into a vector
scan(,'') # reads strings into a vector

Coercion can be useful.  t=1 is much shorter than t=TRUE.  Alternatively, switch can save you precious characters as well, but you'll want to use 1,2 rather than 0,1.

if(length(x)) {} # TRUE if length != 0
sum(x<3)         # Adds all the TRUE:s (count TRUE)

If a function computes something complicated and you need various other types of calculations based on the same core value, it is often beneficial to either: a) break it up into smaller functions, b) return all the results you need as a list, or c) have it return different types of values depending on an argument to the function.
As in any language, know it well - R has thousands of functions, there is probably some that can solve the problem in very few characters - the trick is to know which ones!

Some obscure but useful functions:

sequence
diff
rle
embed
gl # Like rep(seq(),each=...) but returns a factor

Some built-in data sets and symbols:

letters     # 'a','b','c'...
LETTERS     # 'A','B','C'...
month.abb   # 'Jan','Feb'...
month.name  # 'January','Feburary'...
T           # TRUE
F           # FALSE
pi          # 3.14...


Print the fingering for the note on a saxophone Your challenge is, given a series of notes, print the fingerings that minimize the amount of movements you need to make (explained below).

My not standard way of transforming fingerings to text:
The | line separates the left and right hand. Use 1 for the index finger, 2 for the middle finger and 3 for the ring finger. Use a-d for the right hand to represent the side keys played by the pinkies (and just a and b for the left hand).

An example for low A#/Bb:

which would be written as 123d|123b.

The side keys, which are hit with the part of your hand between the thumb and index finger, are labeled as e, f, and g.

In addition, there is a little key between the right hand's 1 and 2 used for playing Bb. This is called the i key.

The octave key is labeled o

These are the fingerings (note that b means flat, not the note B which is uppercase):

A#3 or Bb3: 123d|123b
B3 or Cb4: 123c|123b
B#3 or C4: 123|123b
C#4 or Db4: 123b|123b
D4: 123|123
D#4 or Eb4: 123|123a
E4 or Fb4: 123|12
E#4 or F4: 123|1
F#4 or Gb4: 123|2
G4: 123|                // Note that the | is still necessary
G#4 or Ab4: 123a|
A4: 12|
A#4 or Bb4: 12|g OR 1i| OR 1|1 OR 1|2
B4 or Cb5: 1|
B#4 or C5: 2| OR 1|f
C#5 or Db5: |  OR o3|  // No fingers down for first fingering
D5: o123|123
/* All fingerings from D5 - B#5/C6 are the same as the lower octave
   but with the octave key (prefixed with o) */
C#6 or Db6: o|
D6: of|
D#6 or Eb6: oef|
E6 or Fb6: oef|e
E#6 or F6: oefg|

Input:
A series of notes separated by semicolons.

Output:
A series of fingerings separated by semicolons.
If there is more than one way to finger a certain note, the program must chose the fingering that minimizes distance from its neighbors. If it is the only note or there is a tie, you may output any fingering.

A fingering's distance from another is how many fingers you would have to lift/press to change the note.

Example: 12| --> 1| has a distance of 1 because you have to lift finger 2.
Example: 12|g --> 12| has a distance of 1 because you only have to lift one side key.

Test cases:

C#5;D5;C#5 --> o3|;o123|123;o3|

Bonus: -100 if your program takes an audio file (probably midi) as input and outputs the fingering corresponding to the notes played.

Python 3, 528 525 bytes (ouch!)

Not the prettiest code in the world, but I think it works. Calculates the shortest overall distance by trying all possible fingering combinations, so also not the most efficient.

from itertools import*
def f(x,y):a,b=x.split('|');c,d=y.split('|');return len(set(a)^set(c))+len(set(b)^set(d))
print(";".join(min(product(*["zd|zb zc|zb z|zb zb|zb z|z z|za z|12 z|1 z|2 z| za| 12| 12|g&1i|&1|1&1|2 1| 2|&1|f |&o3| oz|z oz|za oz|12 oz|1 oz|2 oz| oza| o12| o12|g&o1i|&o1|1&o1|2 o1| o2|&o1|f o| of| oef| oef|e oefg|".replace('z','123').split()["C D EF G A B".find(n[0])+" #".find(n[1:-1])+12*int(n[-1])-46].split('&') for n in input().split(';')]),key=lambda x:sum(f(x[i],x[i+1]) for i in range(len(x)-1)))))

Not many tricks. Saved a bit by a string-replace on "123". Simplified distance calculation by doing each half separately. Note name to pitch calculation is fairly tight but should be able to golf the rest down.


calculate days of a month I would like to see the shortest expression to calculate the days (or the last day)  of a month in any language.

Considering y as the number of year and m as month.

Basic rules

without date / time functions.
considering leap years.
there is not other rule.

C, 47 45 characters
30+(m>7^m&1)-(m^2?0:2-!(y%100||(y/=100),y%4))

Taken from an answer to an earlier question where I borrowed a couple of tricks from another user. Returns the length of month m in year y for the Gregorian calendar. ugoren's answer to the same question is shorter and may give a shorter answer to this question.
With thanks to mob for his leap year calculation.


Print 'A' 1000 times with BrainFuck What is the best BrainFuck code (in terms of code size) to print 'A' 1000 times ?

My approach is:

set 'A' to p[0]
set 255 to p[1] to display 255 'A', 3 times
set 235 to p[1] to display 235 'A'

This is not effective but I cannot find a way to use tow counters simultaneously like a multiplication

Is there a better approach than a multiplication ?

A more general question: is there a rule to make a multiplication with a large number with the smallest possible code?

The method you seem to currently be using is 39 bytes:

>>+++[<-[-<.>]>-]++++[<----->-]<-[-<.>] (not including getting the A) (Try It Online!)

(loop 3 times, each time set the counter to 255 and print that many times, then subtract 20, subtract 1, and print that many times)

However, it is much shorter to loop 250 times and print 4 times each time (thanks to jimmy23013 for optimizing this over my original loop-4 loop-250 print-1 solution):

>------[<....>-] (16 bytes)

If your cells are unbounded (I'm assuming they're 8-bit otherwise you probably wouldn't try using 255 for golfing):

>>++++++++++[<++++++++++[<..........>-]>-] (42 bytes).


The Crow vs The Taxicab Imagine travelling to a point lying A miles away horizontally and B miles away vertically from your current position. Or in other words, travelling from (0, 0) to point (a, b). How far would you need to end up travelling? This seems like a straightforward question, but the answer depends on who you ask. If you're a crow, and you can travel as the crow flies, the distance travelled is just the Euclidean distance to (a, b). This is

sqrt(a^2 + b^2)

But if you're just a boring human, you don't really want to walk that far, so you'll need to take a taxi. Most taxis wont drive in a straight line towards your destination because they generally try to stay on the roads. So the real distance you'll end up travelling is the sum of the vertical distance and the horizontal distance. Or the formula is:

abs(a) + abs(b)

This is called the Taxicab Distance. This picture nicely demonstrates the difference between the two:

To travel to (6, 6), a crow can just fly on the green line, and this gives a distance of 6 * sqrt(2) or roughly 8.49. A taxicab can take the red, blue or yellow paths, but they will all take 12.

This leads to the real question I'm asking. If a crow and a taxicab both leave from point (0, 0), and travel to point (a, b), how much longer is the taxicab's path? Or, in more math jargon,

  Given a two dimensional vector, determine the difference between the norm2 of the vector, and the norm1 of the vector.

You must write the shortest possible program or function to answer this question. You may choose to take 'a' and 'b' as two separate inputs, or as a two item tuple. You can take input and output in any reasonable format. If the difference is a non integer, you must be accurate to at least two decimal places.

You can always assume that 'a' and 'b' will be integers, and that they won't both be 0. (Though it is possible that either one of them will be zero)

As usual, standard loopholes apply and try to make your program as short as possible, counted in bytes.

I will upvote any answer that posts an explanation of how the code works, and demonstrates any cool tricks used to save bytes.

Here are some examples for you to test your code on:

#input    #output
3, 4      2
-3, 4     2
-3, -4    2
6, 6      3.51
42, 0     0
10, 10    5.86
3, 3      1.76

Have fun golfing! :)

Taxi, 7394 3773 bytes

Go to Post Office:w 1 l 1 r 1 l.Pickup a passenger going to Tom's Trims.Pickup a passenger going to Tom's Trims.Go to Tom's Trims:n.[a]Pickup a passenger going to The Babelfishery.Go to The Babelfishery:s 1 l 1 r.Pickup a passenger going to Cyclone.Go to Cyclone:n 1 l 1 l 2 r.Pickup a passenger going to Addition Alley.Pickup a passenger going to Multiplication Station.1 is waiting at Starchild Numerology.Go to Starchild Numerology:s 2 l 2 r.Pickup a passenger going to Cyclone.Go to Cyclone:w 1 r 4 l.Pickup a passenger going to Addition Alley.Go to Addition Alley:n 2 r 1 r.Pickup a passenger going to The Underground.Go to Cyclone:n 1 l 1 l.Pickup a passenger going to Multiplication Station.Go to The Underground:n 2 r 2 r.Switch to plan "b" if no one is waiting.Pickup a passenger going to Charboil Grill.Go to Charboil Grill:s 2 r 1 l 1 l 2 r.-1 is waiting at Starchild Numerology.Go to Starchild Numerology:e 2 r.Pickup a passenger going to Multiplication Station.Go to The Underground:w 1 r 2 r 1 r 2 l.[b]Go to Multiplication Station:s 1 l 1 r.Go to Tom's Trims:s 1 r 3 r.Switch to plan "c" if no one is waiting.Switch to plan "a".[c]Go to Multiplication Station:s 1 l 3 l.Pickup a passenger going to Cyclone.Pickup a passenger going to Cyclone.Go to Cyclone:s 1 r 2 l 2 r.Pickup a passenger going to Addition Alley.Pickup a passenger going to Cyclone.Pickup a passenger going to Addition Alley.Go to Addition Alley:n 2 r 1 r.Pickup a passenger going to Multiplication Station.-1 is waiting at Starchild Numerology.Go to Starchild Numerology:n 1 l 1 l 1 l 3 l.Pickup a passenger going to Multiplication Station.Go to Multiplication Station:w 1 r 2 r 1 r 4 l.Pickup a passenger going to Rob's Rest.Go to Rob's Rest:s 1 r 2 l 1 l 1 r 1 r.Go to Cyclone:s 1 l 1 l 1 l 1 r.Pickup a passenger going to Cyclone.[d]Pickup a passenger going to Multiplication Station.Pickup a passenger going to Multiplication Station.Go to Multiplication Station:s 1 l 2 r 4 l.Pickup a passenger going to Addition Alley.Go to Cyclone:s 1 r 2 l 2 r.Switch to plan "e" if no one is waiting.Switch to plan "d".[e]Go to Addition Alley:n 2 r 1 r.Pickup a passenger going to Cyclone.99 is waiting at Starchild Numerology.Go to Starchild Numerology:n 1 l 1 l 1 l 3 l.Pickup a passenger going to The Underground.Go to Cyclone:e 1 l 2 r.Pickup a passenger going to Trunkers.Pickup a passenger going to Sunny Skies Park.Go to Sunny Skies Park:n 1 r.Go to Trunkers:s 1 l.[f]Pickup a passenger going to Cyclone.Go to Cyclone:w 2 r.Pickup a passenger going to Divide and Conquer.Pickup a passenger going to Trunkers.Go to Trunkers:s 1 l.Go to Sunny Skies Park:w 1 r.Pickup a passenger going to Cyclone.Go to Cyclone:n 1 l.Pickup a passenger going to Divide and Conquer.Go to Zoom Zoom:n.Go to Divide and Conquer:w 1 l 2 r 1 r.Pickup a passenger going to Addition Alley.Go to Cyclone:e 1 l 1 l 2 l.Pickup a passenger going to Addition Alley.Go to Addition Alley:n 2 r 1 r.Pickup a passenger going to Divide and Conquer.2 is waiting at Starchild Numerology.Go to Starchild Numerology:n 1 l 1 l 3 l 2 r.Pickup a passenger going to Divide and Conquer.Go to Divide and Conquer:w 1 r 2 r 1 r 2 l 3 l.Pickup a passenger going to Sunny Skies Park.Go to Sunny Skies Park:e 1 l 1 l 2 l 1 l.Go to The Underground:s 1 l 1 r 2 l.Switch to plan "g" if no one is waiting.Pickup a passenger going to The Underground.Go to Trunkers:s 2 r 1 l.Switch to plan "f".[g]Go to Rob's Rest:n 3 l 2 l 1 l 2 r 1 r.Pickup a passenger going to What's The Difference.Go to Sunny Skies Park:s 1 l 1 l.Pickup a passenger going to What's The Difference.Go to What's The Difference:n 1 r 1 l.Pickup a passenger going to The Babelfishery.Go to The Babelfishery:e 3 r.Pickup a passenger going to Post Office.Go to Post Office:n 1 l 1 r.

Try it online!

Engineer Toast, a much more experienced Taxi golfer, decided to take some time (probably a lot less than I did) and golf down my Taxi program by basically rewriting it. You can find my old answer body and links to my old TIOs in the edit history.

Engineer Toast's ungolfed square root algorithm: Try it online!

Ungolfed, with explanations:

[ Crow vs. Taxi ]

[ GET THE NEGATIVE ABSOLUTE VALUES OF BOTH STDINS ]

[Move the stdin values to Tom's Trims b/c:]
[1) Stdin doesn't count as a passenger waiting]
[2) Checking for no one waiting is shorter that keeping tracker of a count for just 2 iterations OR repeating all the code over again]
Go to Post Office:w 1 l 1 r 1 l.
Pickup a passenger going to Tom's Trims.
Pickup a passenger going to Tom's Trims.
Go to Tom's Trims:n.

[a]
[Clone the first waiting value]
[If we've already picked up both, move to the next process]
[Switch to plan "c" if no one is waiting.]
Pickup a passenger going to The Babelfishery.
Go to The Babelfishery:s 1 l 1 r.
Pickup a passenger going to Cyclone.
Go to Cyclone:n 1 l 1 l 2 r.
Pickup a passenger going to Addition Alley.
Pickup a passenger going to Multiplication Station.

[Add one to the value]
1 is waiting at Starchild Numerology.
Go to Starchild Numerology:s 2 l 2 r.
Pickup a passenger going to Cyclone.
Go to Cyclone:w 1 r 4 l.
Pickup a passenger going to Addition Alley.
Go to Addition Alley:n 2 r 1 r.
Pickup a passenger going to The Underground.

[Pick up a clone of that one to feed into Multiplication Station]
Go to Cyclone:n 1 l 1 l.
Pickup a passenger going to Multiplication Station.

[Subtract one and see if that's more than zero]
Go to The Underground:n 2 r 2 r.
Switch to plan "b" if no one is waiting.

[It was more than zero so we make it negative]
[First, though, get rid of the pesky result from The Underground]
Pickup a passenger going to Charboil Grill.
Go to Charboil Grill:s 2 r 1 l 1 l 2 r.
-1 is waiting at Starchild Numerology.
Go to Starchild Numerology:e 2 r.
Pickup a passenger going to Multiplication Station.
Go to The Underground:w 1 r 2 r 1 r 2 l.

[b]
[Make sure it's a negative value and leave it at Multiplication Station]
[Either it was already negative OR we now have -1 as a passenger]
Go to Multiplication Station:s 1 l 1 r.

[Get the next stdin unless we've already gotten them both]
Go to Tom's Trims:s 1 r 3 r.
Switch to plan "c" if no one is waiting.
Switch to plan "a".

[ ADD THE TWO NEGATIVES AND INVERT TO GET THE TAXI DISTANCE]

[c]
[Pickup the two negative absolute values and clone them]
Go to Multiplication Station:s 1 l 3 l.
Pickup a passenger going to Cyclone.
Pickup a passenger going to Cyclone.
Go to Cyclone:s 1 r 2 l 2 r.
Pickup a passenger going to Addition Alley.
Pickup a passenger going to Cyclone.
Pickup a passenger going to Addition Alley.

[Add the two clones values to get the negative Taxi distance]
Go to Addition Alley:n 2 r 1 r.
Pickup a passenger going to Multiplication Station.

[Invert to get the Taxi distance and store it at Rob's Rest]
-1 is waiting at Starchild Numerology.
Go to Starchild Numerology:n 1 l 1 l 1 l 3 l.
Pickup a passenger going to Multiplication Station.
Go to Multiplication Station:w 1 r 2 r 1 r 4 l.
Pickup a passenger going to Rob's Rest.
Go to Rob's Rest:s 1 r 2 l 1 l 1 r 1 r.

[ FIND THE CROW DISTANCE ]
[Uses the Babylonian method: https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method ]

[Square and Sum the cloned values]
Go to Cyclone:s 1 l 1 l 1 l 1 r.
Pickup a passenger going to Cyclone.
[d]
Pickup a passenger going to Multiplication Station.
Pickup a passenger going to Multiplication Station.
Go to Multiplication Station:s 1 l 2 r 4 l.
Pickup a passenger going to Addition Alley.
Go to Cyclone:s 1 r 2 l 2 r.
Switch to plan "e" if no one is waiting.
Switch to plan "d".
[e]
Go to Addition Alley:n 2 r 1 r.
Pickup a passenger going to Cyclone.

[Pickup our cycle counter]
[It's cheaper to do this than to check each iteration's value as equal to the last]
[Taxi can only handle integers up to 2^31-1 so 99 iterations is sufficient.]
99 is waiting at Starchild Numerology.
Go to Starchild Numerology:n 1 l 1 l 1 l 3 l.
Pickup a passenger going to The Underground.

[Duplicate stdin to be stored as S at Trunkers and as x0 at Sunny Skies Park]
[a & b are always integers so Trunkers won't hurt S and it's close with a short name so it's good for golfing]
Go to Cyclone:e 1 l 2 r.
Pickup a passenger going to Trunkers.
Pickup a passenger going to Sunny Skies Park.
Go to Sunny Skies Park:n 1 r.
Go to Trunkers:s 1 l.

[ This is our starting position for square root:           ]
[  • x at Sunny Skies Park                                 ]
[  • S at Trunkers                                         ]
[  • Taxi at Trunkers                                      ]
[  • The iterator as a passenger going to The Underground  ]

[f]

[Duplicate S so we don't lose it]
Pickup a passenger going to Cyclone.
Go to Cyclone:w 2 r.
Pickup a passenger going to Divide and Conquer.
Pickup a passenger going to Trunkers.
Go to Trunkers:s 1 l.

[Diplicate x for division and addition]
Go to Sunny Skies Park:w 1 r.
Pickup a passenger going to Cyclone.
Go to Cyclone:n 1 l.
Pickup a passenger going to Divide and Conquer.

[Gas will be super important in this loop]
Go to Zoom Zoom:n.

[Perform (x + S/x)/2]
[(/2) turns out to be a few bytes shorter than (*.5), mostly due to place names]
Go to Divide and Conquer:w 1 l 2 r 1 r.
Pickup a passenger going to Addition Alley.
Go to Cyclone:e 1 l 1 l 2 l.
Pickup a passenger going to Addition Alley.
Go to Addition Alley:n 2 r 1 r.
Pickup a passenger going to Divide and Conquer.
2 is waiting at Starchild Numerology.
Go to Starchild Numerology:n 1 l 1 l 3 l 2 r.
Pickup a passenger going to Divide and Conquer.
Go to Divide and Conquer:w 1 r 2 r 1 r 2 l 3 l.
Pickup a passenger going to Sunny Skies Park.
Go to Sunny Skies Park:e 1 l 1 l 2 l 1 l.
[Now we have the next iteration of x]

[Check the iterator]
Go to The Underground:s 1 l 1 r 2 l.
Switch to plan "g" if no one is waiting.
Pickup a passenger going to The Underground.

[Reset the loop]
Go to Trunkers:s 2 r 1 l.
Switch to plan "f".

[ ADD THE NEGATIVE SUM TO THE SQUARE ROOT TO GET THE NEGATIVE DIFFERENCE ]

[g]
Go to Rob's Rest:n 3 l 2 l 1 l 2 r 1 r.
Pickup a passenger going to What's The Difference.
Go to Sunny Skies Park:s 1 l 1 l.
Pickup a passenger going to What's The Difference.
Go to What's The Difference:n 1 r 1 l.
Pickup a passenger going to The Babelfishery.
Go to The Babelfishery:e 3 r.
Pickup a passenger going to Post Office.
Go to Post Office:n 1 l 1 r.


The repetitive byte counter Your task is to write a non-empty program / function of byte count L, which, when repeated M times, checks whether a given positive integer N is equal to L × M.

You should, in theory, support an arbitrary number of repetitions (an arbitrary positive integer value of M), but it's fine if, due to language limitations, it cannot work over a certain threshold.  Reading the source code of your program or accessing information about it is strictly forbidden.

For providing output, you should choose a consistent value for one of the states (either truthy or falsy) and use any other (not necessarily consistent) possible output for the other state (Discussion).

Your answers will be scored by your initial program's length L (in bytes), with less bytes being better.

Example

Let's say your (initial) program is ABCDE. Then:

ABCDE (1 repetition) should check if the input equals 5.
ABCDEABCDE (2 repetitions) should check if the input equals 10.
ABCDEABCDEABCDE (3 repetitions) should check if the input equals 15. Etc...

The score of this sample code would be 5, as the initial source is 5 bytes long.

Jelly, 1 byte

’

Output is 0 for a match, non-zero for a non-match.

Try it online!

How it works

This makes advantage of the overly liberal output format. Repeating ’ M times simply decrements the input M times, so the result will be zero if and only if the input is LM, where L = 1.


Numbers that are palindromes in N bases Given an non-negative integer \$n \ge 0\$, output forever the sequence of integers \$x_i \ge 3\$ that are palindromes in exactly \$n\$ different bases \$b\$, where the base can be \$2 \le b le x_i-2\$.
This is basically the inverse of OEIS A126071, where you output which indices in that sequence have the value \$n\$. It's a bit different, because I changed it so you ignore bases \$b = x_i-1, \: x_i, \: x_i+1\$, since the results for those bases are always the same (the values are always palindromes or always not). Also, the offset is different.
\$x_i\$ is restricted to numbers \$\ge 3\$ so that the first term of the result for each \$n\$ is A037183.
Note that the output format is flexible, but the numbers should be delimited in a nice way.
Examples:
n   seq
0   3 4 6 11 19 47 53 79 103 137 139 149 163 167 ...
1   5 7 8 9 12 13 14 22 23 25 29 35 37 39 41 43 49 ...
2   10 15 16 17 18 20 27 30 31 32 33 34 38 44 ...
3   21 24 26 28 42 45 46 50 51 54 55 56 57 64 66 68 70 ...
4   36 40 48 52 63 65 85 88 90 92 98 121 128 132 136 138 ...
5   60 72 78 84 96 104 105 108 112 114 135 140 156 162 164 ...
10  252 400 420 432 510 546 600 648 784 800 810 816 819 828 858 882 910 912 1040 1056 ...

So for \$n=0\$, you get the output of this challenge (starting at \$3\$), because you get numbers that are palindromes in n=0 bases.
For \$n=1\$, \$5\$ is a palindrome in base \$2\$, and that's the only base \$2 \le b \le (5-2)\$ that it's a palindrome in. \$7\$ is a palindrome in base \$2\$, and that's the only base \$2 \le b \le (7-2)\$ that it's a palindrome in. Etc.

Iff your language does not support infinite output, you may take another integer z as input and output the first z elements of the sequence, or all elements less than z. Whichever you prefer. Please state which you used in your answer if this is the case.
Related

Mathematica, 80 71 bytes

Thanks to JungHwan Min for saving 9 bytes!

Do[#!=Length[i~IntegerReverse~Range[2,i-2]~Cases~i]||Echo@i,{i,3,∞}]&

(∞ is the three-byte character U+221E.)
Pure function taking a nonnegative integer as input. i~IntegerReverse~Range[2,i-2] creates a list of the reversals of the number i in all the bases from 2 to i-2; then Length[...~Cases~i] counts how many of these reversals are equal to i again. #!=...||Echo@i halts silently if that count is not equal to the input, and echoes i if it is equal to the input. That procedure is embedded in a straightforward infinite loop.


Is my Matrix Arrowhead? Definition
An arrowhead matrix is a matrix that has all entries equal to 0, except the ones on the main diagonal, top row and leftmost column. In other words, the matrix should look like this:

* * * * * *
* * 0 0 0 0
* 0 * 0 0 0
* 0 0 * 0 0
* 0 0 0 * 0
* 0 0 0 0 *

Where each * is any non-zero entry.
Task
Given a square matrix of non-negative integers, check whether it is arrowhead according to the definition above.
You may not take the size of the matrix as input, unless your language’s equivalent to an array is something like a pointer and a length (like C). It will always be at least 3 x 3.
The shortest code in bytes in each language wins.
Input and Output
You can pick among any of the following formats for receiving input:

A matrix in the native matrix type (if your language has one)
A 2D array1 (an array of 1D arrays, each corresponding to one row)
A 1D array (since the matrix is always square)
A string (you chose the spacing, but please do not abuse this in any way).

When it comes to providing output, you can either report a truthy / falsy value following the standard decision-problem definition, or choose any two distinct and consistent values.
Moreover, you can take input and give output through any standard method, in any programming language, while taking note that these loopholes are forbidden by default. If want to pick any other format or are unsure about something, please ask in the comments.
1: or your language's equivalent (list, vector, etc.)
Examples
Let's look at the following examples:

1 2 2 2
2 1 0 0
3 0 1 0
4 0 0 1

This is an arrowhead matrix (your programs should report a truthy value), because the elements on the main diagonal are 1 1 1 1, those on the top row are 1 2 2 2 and those on the leftmost column are 1 2 3 4. All other entries are 0, so this satisfies all the conditions.

3 5 6
7 1 0
8 0 0

This matrix is not arrowhead because there is a 0 on the main diagonal.

9 9 9 9
9 9 0 0
9 7 9 0
9 0 0 9

This one is not arrowhead either, because it contains a 7 in place of a 0.
More test cases
Truthy:

[[1, 1, 1], [1, 1, 0], [1, 0, 1]]
[[1, 2, 3, 4], [1, 1, 0, 0], [1, 0, 1, 0], [1, 0, 0, 1]]
[[1, 2, 2, 2], [2, 1, 0, 0], [3, 0, 1, 0], [4, 0, 0, 1]]
[[34, 11, 35, 5], [56, 567, 0, 0], [58, 0, 679, 0], [40, 0, 0, 7]]

Falsy:

[[3, 5, 6], [7, 1, 0], [8, 0, 0]]
[[9, 9, 9, 9], [9, 9, 0, 0], [9, 7, 9, 0], [9, 0, 0, 9]]
[[1, 0, 3, 4], [1, 1, 0, 0], [1, 0, 1, 0], [1, 0, 0, 1]]
[[1, 6, 3, 4], [13, 2, 0, 6], [29, 0, 1, 0], [2, 0, 0, 4]]


Program that runs when rows and columns are transposed I posted this to The Daily WTF coder challenge forum a few years ago but only got one response. I figure CodeGolf stack exchange might generate more interest!

Description

Write a program that runs when the rows and columns of the source code are transposed.

In other words, imagine each character on each line is a cell in a matrix (pad out shorter lines as necessary to make the matrix rectangular). Write a functioning program that still functions even if its "matrix" is transposed.

This is just a creative puzzle, not a golf.

Details

The program must execute without error and do something interesting*
The transpose of the program must execute without error and do something interesting, although not necessarily the same thing as the original.
Any language.
No shebang required.
Single row/single column entries disallowed.

*Interesting is the subjective opinion of the CodeGolf community.

Deadline April 15 2011

Trivial Example

Here's a really stupid example, but it illustrates the rules pretty well. Of course, any "symmetric" program will meet this challenge, but I encourage you to try non-symmetric programs.

# #####################
 print "hello,world\n";
#r
#i
#n
#t
#
#"
#h
#e
#l
#l
#o
#,
#w
#o
#r
#l
#d
#\
#n
#"
#;

Transposer Reference Implementation

Here's a perl snippet that does the type of transposing that I am talking about. This is not the objective of the puzzle, it is just a helper tool.

#!/usr/bin/perl
my @matrix;
open('SOURCE', $ARGV[0]);
my $matrixwidth = -1;
my $matrixheight = 0;
foreach (<SOURCE>) {
  chomp;
  if ($matrixwidth < length $_) {$matrixwidth = length $_}
  my @row = split(//, $_);
  push @matrix, \@row;
  $matrixheight++;
}
foreach my $x (0 .. ($matrixwidth-1)) {
  foreach my $y (0 .. ($matrixheight-1)) {
    print(defined $matrix[$y]->[$x] ? $matrix[$y]->[$x] : ' ');
  }
  print "\n";
}

Here's one I came up with when I originally wrote the challenge a few years back. It's a perl script that can transpose other scripts. You can run it on itself, save the output as a new script, then run that new script on itself to get the original.

#######       p           $f f   ]'
#      ofm    u        $  ho o   -
#      poy    s        w  +r r  p>'
#      er ####h########=##+ #   r[}
    open   'M' , $ARGV[ 0]  ; # i$p
  for(;   <M>  ; ){         #   nxr
      #((@             $  }( (  t]i
      #';r             #   $ $   ?n
      #M<=    @        r   x y   $t
      #'M     m        +   = =   m
      # >     ,        1   0 0   ["
my @r=   $_ =~ /./g;#  >   ; ;   $\
      #  _ /  \                # yn
push @m,     \@r;              # ]"
      # ;=    r            $ $   -}
      #  ~    ;        $   x y   >
$w=($#r   + 1>        $w)      # [
?$#r+1:     $w ;$h++}# ?   < <   $
for (     $x=0 ;$x<$w;         # x
          $x++ ){              # ]
for (     $y=0 ;$y<$h;
          $y++ ){           #$
  print               #$   $ h  d:
defined                #   w ;  e
      #$)/    #        r   ; $  f
      #A{.             +   $ y  i
      #R#/             1   x +  n
      #G g             :   + +  e
      #V ;                 + )  d
     $m[  $y]->[$x]
      #0 #                 ) {  $
 ?$m[$y]->[$x]:' '}          #  m
      #)               $   {    [
      #;               w        $
  print "\n"} #        ;        y