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)


Ruby, 510 460 bytes

p=[0];w=[n=x=0]
i=gets.split.map{|s|
if x!=1
if s[0]=="A"
w<<n
else
if s[0..1]=="T+"
t=n
q=s[2..-1].to_i
if w[-1]==t||(w[-1]>t&&w[-1]<n+q)
w<<w[-1]
n+=q
else
n+=(t<p[-1]&&n+q>p[-1])?q%(p[-1]-n):q
end
elsif s[0..1]=="T-"
t=n
p<<n
n-=s[2..-1].to_i
x=(x==0&&w[-1]>0&&t>w[-1]&&n>w[-1])?1:0
else
t=n
q=s.to_i
if w[-1]==t||(w[-1]>t&&w[-1]<n+q)
w<<w[-1]
n+=q
else
n+=(t<p[-1]&&n+q>p[-1])?q%(p[-1]-n):q
end
end
end
else
break
end}
p x

Input

As per example

Output

0 = No Paradox, 1 = Paradox

Sample

The sample input provided: 1000 T+250 250 T+0 500 T-200 100 T-50 125 A 225 T-400 500 A 100 T-200 150 T-25 100 T+100 50 A 25
returns 1, indicating a paradox occurred.

Notes

This is not only the first codegolf exercise I attempt, but it is also the first Ruby program I have written. Hence, it could probably be even shorter.

Brief Explanation

p: Infinite loops
w: Alternate timelines
n: Now (regardless of timeline)
x: Paradox

Infinite loops will only occur while traveling forward in time. I am happy for any feedback - especially if it is pointing out a better way to solve this.


Haskell, 70 64 bytes

a%b=abs$a-b
x@(a:b)#y@(c:d)|e:_<-d,a%c>a%e=x#d|1>0=a%c+b#y
_#_=0

Try it online!

Explanation

First we define (%) to be the absolute difference between two numbers.  Then we define (#) to be the interesting function. In the first line we match when both lists are non-empty:

x@(a:b)#(c:d:e)

On our first case from here we bind d to e:_ with e:_<-d.  This ensures that d is non-empty and sets it's first element to e.

Then if the second element of \$Y\$ (e) is closer than the first (c) to the first element of \$X\$ (a), we return x#d removing the first element of \$Y\$ and calling again with the same \$X\$.

If we match the pattern but don't pass the condition we do:

a%c+b#y

Which, removes the first item of \$X\$ and adds the absolute difference of it from the first element of \$X\$ to the remaining result.

Lastly if we don't match the pattern we return \$0\$.  Not matching the pattern means that \$X\$ must be empty because \$Y\$ cannot be empty.

This algorithm has order notation \$O(|X|+|Y|)\$.

Haskell, 34 bytes

Here's how I would do it in \$O(\left|X\right|\times\left|Y\right|)\$ time:

x#y=sum[minimum$abs.(z-)<$>y|z<-x]

Try it online!


Python 2, 51 bytes

lambda l:max((10**len(`l`)*a/b,s)for s,b,a in l)[1]

Does the obvious thing of finding the entry with the biggest ratio, but sidesteps the prohibition against floats by first multiplying the numerator by a huge input-dependent power of 10 before floor-dividing.
I'll prove this coefficient is big enough to make floor-division act the same difference as non-floor division.
Claim: If a1/b1 > a2/b2, then floor(Na1/b1) > floor(Na2/b2) for any N≥b1b2.
Proof: Note that a1/b1 - a2/b2 is a multiple of 1/b1b2, so a1/b1 - a2/b2 > 0 implies that

a1/b1 - a2/b2
≥ 1/b1b2

Then, multiplying both sides by N,

Na1/b1 - Na2/b2
≥ N/b1b2 ≥ 1

So, since Na1/b1 and Na2/b2 differ by at least 1, their respective floors are distinct. ∎
Now, note that the product b1b2 has digit length at most their total digit length, which is less than the string length of the input. Since the input is in base 10, its suffices to use 10 to the power of its length N=10**len(`l`) to produce a number with more digits than it, guaranteeing the condition.


Deranged !Combinatorics: Compute the Subfactorial

Funciton, 336 bytes

Byte count assumes UTF-16 encoding with BOM.

┌─╖┌─╖  ┌─╖
│f╟┤♭╟┐┌┤♭╟┐
╘╤╝╘═╝├┘╘═╝├────┐
 │┌─╖ │ ┌┐┌┘╔═╗╓┴╖
 ││f╟─┴┐└┴┼─╢0║║f║
 │╘╤╝  │  │ ╚═╝╙─╜
 │┌┴╖ ┌┴╖┌┴╖ ╔═╗
 ││+╟┐│×╟┤?╟┐║1║
 │╘╤╝│╘╤╝╘╤╝┘╚╤╝
 └─┘ └─┘  └───┘

This defines a function f which takes one integer and outputs another integer at a 90 degree turn to the left. It works for arbitrarily large inputs.

Try it online!

Considering this is Funciton it's even reasonably fast (n = 20 takes about 14 seconds on TIO). The main slowdown comes from the double-recursion, as I don't think the Funciton interpreter automatically memoises functions.

Unfortunately, some monospaced fonts don't correctly monospace the ♭ and/or insert small gaps between the lines. Here's a screenshot of the code from TIO in all its beauty:

I think it might be possible to golf this some more, e.g. by changing the condition from >0 to <1 and swapping the branches of the conditional, so that I could reuse the number literal, or maybe by using a completely different formula, but I'm quite happy with how compact it is already.

Explanation

This basically implements the recursion given in the challenge, although it uses the base case !(-1) = !0 = 1. n-1 and n-2 are computed with the predecessor function ♭, and the intermediate result n-1 is reused in three places. There isn't much more to it, so I'll just quickly go through the control flow:

               ─┐
               ╓┴╖
               ║f║
               ╙─╜

This is the function header which emits the function's input n long the attached line. This immediately reaches T-junction, which simply duplicates the value.

        ┌┐┌┘╔═╗
        └┴┼─╢0║
          │ ╚═╝

The 0 box is just a numeric literal. A 4-way junction computes two functions: the path that leads off the bottom computes 0 < n, which we'll use to determine the base case. The path that goes left separately computes 0 << n (a left-shift), but we discard this value with the Starkov construct.

         ┌┴╖ ╔═╗
         ┤?╟┐║1║
         ╘╤╝┘╚╤╝
          └───┘

We lead this into the three-way conditional ?. If the value is false, we return the constant result 1. The loose end right of the ? is the function output. I'm twisting it around by 180 degrees here, so that the relative orientation of input and output of f is more convenient in the rest of the program.

If the condition was true, then the other value will be used. Let's look at the path that leads to this branch. (Note that Funciton's evaluation is actually lazy so that this branch will never be evaluated if it's not needed, which makes the recursion possible in the first place.)

        ┌─╖
      ┐┌┤♭╟┐
      ├┘╘═╝
      │
     ─┴┐

In the other branch we first compute n-1 and then split the path twice so we get three copies of the value (one for the coefficient of the recurrence, one for the first subfactorial, the last for n-2).

┌─╖┌─╖
│f╟┤♭╟
╘╤╝╘═╝
 │┌─╖
 ││f╟
 │╘╤╝
 │┌┴╖
 ││+╟
 │╘╤╝
 └─┘

Like I said, we decrement one copy again with another ♭, then we feed both n-1 and n-2 recursively to f and finally add the two results together in the +.

       ┐
       │
      ┌┴╖
     ┐│×╟
     │╘╤╝
     └─┘

All that's left is to multiply n-1 by !(n-1) + !(n-2).


Retina, 44 bytes

+`.+ /| |/\.?/
/
+1`/?[^/]*/\.\.|/\.?$

^$
/

Input is expected to be the two paths separated by a single space.

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


Batch, 37 bytes

@set/ps=
@if exist %s% %0
@echo %s%

(For some reason current Windows 10 CMD.EXE corrupts the title when it executes the %0.)


J, 30 28  38 bytes
1 :'](]*i.@u+>.@%),(]+0 0-:|~)u>.@%~-'

Try it online!
This is a J adverb modifing n, the number of ticks, and taking the max and min as left and right args, respectively.  Called like:
19 (4 f) 0

u>.@%~- Calculates step size by dividing n into the difference between the max and min.

,(]+0 0-:|~) Adds one to the step size if the step size evenly divides both endpoints.

]* The step size times...

i.@u Produces range 0..n-1
+ Add elementwise to...
>.@% The ceiling of >.@ the min divided by the step size % -- adjusts so the first tick starts where we want.


Non-deterministic Turing Machine, 20 states, 52 transitions (882 bytes maybe)
How do you convert this to bytes? I've written the files (absolutely not golfed) to execute this machine with Alex Vinokur's Simulator of a Turing Machine1. wc -c outputs the following (excluding the description file and the input files):
 12 alphabet
 49 meta
740 rules
 81 states
882 total

Anyways, I was preparing for my Computer Science A-Levels, so I thought this would be a good exercise (I don't know what I was thinking). So here's the definition:
$$\begin{align*}
M & = (Q, \Sigma, \iota, \sqcup, A, \delta) \\
Q & = \{q_{0},q_{1},q_{2},q_{3},q_{4},q_{5},q_{6},q_{7},q_{8},q_{9},q_{10},q_{11},q_{12},q_{13},q_{14},q_{15},q_{16},q_{17},q_{18},q_{19}\} \\
\Sigma & = \{< \: ; \: > \: ; \: , \: ; \: . \: ; \: X \: ; \: $\} \\
\iota & = q_0 \\
\sqcup & = $ \\
A & = \{q_0, q_5\}
\end{align*}$$

(the transition function)
Excuse the bad image, but I couldn't be bothered with redrawing this thing on a computer. If you actually want to decipher the transition rules, I recommend you read through the rules file I linked above.

I've used Xs instead of spaces because spaces are hard to visualize here and the simulator doesn't accept spaces in the alphabet.
The concept is fairly simple - q1 to q4 are used to catch right-facing fishes, q11 to q14 are used to catch left-facing fishes, q15 to q19 for crabs and the q5 to q10 blob is simply for inserting a space and moving all following characters one to the right.
If the string is interpretable, it accepts the string and the tape contains the string with spaces inserted. Otherwise it rejects the string (I guess this counts as no output - emptying the tape would be pretty easy but would require lots of transition rules and I don't think it would make the transition function prettier to look at).

1 Note: It's difficult to compile. I had to edit the src/tape.cpp file and replace LONG_MAX with 1<<30 and then go to the demo directory, edit the Makefile to replace EXE_BASENAME with turing.exe and execute make. Then go to the directory with the files I've written and execute /path/to/turing/download/src/turing.exe meta.


Python, 33 bytes

f=lambda n:n<2or~-n*f(n-2)+f(n-1)

Try it online!

Uses the recursive formula.


How to encode shortest brainf_ck strings

I can give question number 1. a go:

++++++++++

The first series of +'s defines first memory cell (cell0) to be a loop counter to 10.

[>+++++++>++++++++++>+++>+<<<<-]

Above is the loop that executes 10 times. The loop adds 7 to cell1, 10 to cell2, 3 to cell3 and 1 to cell4 for each iteration. After 10 iterations we have the following in the first 5 memory cells: 0, 70, 100, 21, 10

>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+.>.

Above is kind of self explanatory, it just moves the memory pointer to the value that is closest to what is needed, does some minor inc's and dec's and outputs.


Noel Constant's idiotically simple investment system

Unix tools, 111 * 0.9

(Not counting downloading and parsing the Bible)

$ curl -s https://www.gutenberg.org/cache/epub/10/pg10.txt|grep '^[0-9]:'|cut -d' ' -f2-|sed 's/[^a-z]//gi'|tr -d \\n|fold -w2|xargs -n1 sh -c 'grep -i ^$0 symbols.txt'|sed -r 's/(..) (.*)/\2 \(\1\)/'
Zylog Systems Ltd (IN)
Zynga Inc - Cl A (TH)
Zwahlen & Mayr Sa-br (EB)
Surpapelcorp Sa (EG)
Zylog Systems Ltd (IN)
Nisource Inc. (NI)
Novagold Resources Inc. (NG)
Zealand Pharma A/s (DC)
Everest Re Group, Ltd. (RE)
Atlantic Power Corporation (AT)
^C

I am not a professional investor but I think that the more times a company is mentioned in the Bible the more successful it will be, so I would invest in these:

  10027 th - Zynga Inc - Cl A
   9026 he - Hawaiian Electric Industries, Inc.
   4748 nd - *
   3681 an - Autonation, Inc.
   3150 ha - Hawaiian Holdings, Inc.
   3109 er - *
   2925 re - Everest Re Group, Ltd.
   2829 in - Zylog Systems Ltd
   2665 nt - *
   2519 es - *

(Future founders, consider creating a company with stock symbols I marked with *, they are not yet taken)


CFDG, 134 characters

This one isn't exactly valid, because you cannot limit the recursion depth. But the problem just calls for a solution in this one. :)

startshape t
c(q)=cos(q/2)^2
d(q)=1+sin(q)/2
p=acos(-1)
shape t{w=rand(p)
SQUARE[x .5 .5]t[trans 0 1 c(w) d(w)]t[trans c(w) d(w) 1 1]}

The results look something like this

For another 46 characters (180 characters in total), you can even colour it in:

startshape t
c(q)=cos(q/2)^2
d(q)=1+sin(q)/2
p=acos(-1)
shape t{w=rand(p)
SQUARE[x .5 .5 h 25 sat 1 b .2]t[trans 0 1 c(w) d(w) b .08 .8 h 2.2]t[trans c(w) d(w) 1 1 b .08 .8 h 2.2]}


Jelly, 27 26 bytes

ØJḟ“<>`{}”ḟØAɓi@€_33^\96_ị

Try it online!

Alternate version, 22 bytes (non-competing)

Jelly finally caught up with other golfing langs and got a printable ASCII atom, so this works now.

ØṖḟ“<>`{}”ḟØAɓi@€’^\Nị

Try it online!

How it works

ØJḟ“<>`{}”ḟØAɓi@€_33^\96_ị  Main link. Argument: s (string)

ØJ                          Yield Jelly's code page, i.e., 32 non-ASCII characters,
                            followed by all printable ASCII characters, followed by
                            129 non-ASCII characters.
  ḟ“<>`{}”                  Filterfalse; remove the characters "<>`{}".
          ḟØA               Filterfalse; remove all uppercase ASCII letters.
                            Let's call the resulting alphabet a.
             ɓ              Begin a new, dyadic chain.
                            Left argument: s. Right argument: a
              i@€           Find the (1-based) index of all characters of s in a.
                 _33        Subtract 33, so ' ' maps to 0, '~' maps to 63.
                    ^\      Compute the cumulative bitwise XOR.
                            We didn't take the bitwise NOT of the first index,
                            which can be rectified by subtracting all results from
                            63. However, we must also add 33 to account for the
                            fact that the index of ' ' in a is 33.
                      96_   Subtract the results from 96.
                         ị  Index into a.


Python 3, 100 bytes

import numpy
def f(a):
 if len(a): a=numpy.rot90(a,axes=(1,0));a[1:-1,1:-1]=f(a[1:-1,1:-1]);return a

Try it online!


Python 3.6 (pre-release), 87
lambda s:f"${int(s.translate({46:'',44:''})[1:])*[110,15,0,137][ord(s[0])%4]/1e4:,.2f}"

Uses f-strings to evaluate the result and format it.
s.translate({46:'',44:''}) removes dots and commas from s, thus making it a valid int literal, then int(...) converts it into the actual int object.


Build a solver for the "N balls on a scale" problem

Tcl, 455 426

proc weight n {
   set num [expr {int(log($n*2-1)/log(3))+1}]
   set len [expr {$n/3}]
   set pn 0
   set pri {2 5 7 11 13 17 19 23 29 31 37 41 43 59 61 67}
   for {set i 0} {$i < $num} {incr i} {
       set a {}
       while {![llength $a]} {
           set a {}
           set b {}
           set c {}
           while {
               ($n+1)%[lindex $pri $pn]==0
             ||($n-1)%[lindex $pri $pn]==0
             ||$n%[lindex $pri $pn]==0} {incr pn; puts $pn}
           set cpn [lindex $pri $pn]
           for {set j 0} {$j < $len} {incr j} {
               set tmp [expr {($j*$cpn)%$n}]
               lappend a $tmp
               incr tmp 1
               if {$tmp in $a} {set a {}; break}
               lappend b $tmp
           }
           incr pn
       }
       for {set j 0} {$j < $n} {incr j} {
           if {$j ni $a && $j ni $b} {lappend c $j}
       }
       puts "[lsort -integer $a] VS [lsort -integer $b] - Which is havier? -1 = left, 0 = equal, 1 = right"
       set idx [expr {[gets stdin] + 1}]
       if {$i == 0} {
           if {$idx == 1} {
               set p1 $c
               set p2 $c
           } elseif {$idx == 0} {
               set p1 $a
               set p2 $b
           } else {
               set p1 $b
               set p2 $a
           }
       } else {
           set lists [list $a $c $b]
           set p1 [lmap it [lindex $lists $idx] {if {$it ni $p1} continue; set it}]
           set p2 [lmap it [lindex $lists 2-$idx] {if {$it ni $p2} continue; set it}]
       }
   }
   if {[llength $p1]} {puts "Result $p1"} {puts "Result $p2"}
}
puts "Number of balls?"
weight [gets stdin]

No matter what you choose, the next question is always the same.


Find how many ordered pairs of integers share only one digit

APL (Dyalog Extended or 18.0), 24 22 bytesSBCS

Full program.

≢⍸∘.(<∧1=∘≢∘∪∩⍥⍕)⍨1↓⍳⎕

Try it online!

⎕ prompt for N from the console

⍳ first N integers

1↓ drop the first one (0)

 ⍨ apply the following function using those integers as both left and right argument:

  ∘.(…) apply the following function between all combinations of left and right elements:

   ⍥⍕ stringify (make into character list) both arguments, then:

    ∩ find the intersection between the character lists

   ∪ find the Unique elements of that

   ∘ then:

    ≢ count that

   ∘ then:

    1= check if that is equal to 1

   ∧ and

   < the left argument is less than the right argument

⍸ find the ɩndices of the trues

≢ count them


Is case sensitivity important? Part II: reality check


Given a list of circles, output the area of the smallest containing rectangle

Python 2 + PySCIPOpt, 267 bytes

from pyscipopt import*
R=input()
m=Model()
V,C=m.addVar,m.addCons
a,b,c=V(),V(),V()
m.setObjective(c)
C(a*b<=c)
P=[]
for r in R:
 x,y=V(),V();C(r<=x);C(x<=a-r);C(r<=y);C(y<=b-r)
 for u,v,s in P:C((x-u)**2+(y-v)**2>=(r+s)**2)
 P+=(x,y,r),
m.optimize()
m.printBestSol()

How it works

We write the problem as follows: minimize c over variables a, b, c, x1, y1, …, xn, yn, where

ab ≤ c;
ri ≤ xi ≤ a − ri and ri ≤ yi ≤ b − yi, for 1 ≤ i ≤ n;
(xi − xj)2 + (yi − yj)2 ≥ (ri + rj)2, for 1 ≤ j < i ≤ n.

Obviously, we’re using an external optimization library on these constraints, but you can’t just feed them to any old optimizer—even Mathematica’s NMinimize gets stuck at local minima for these tiny test cases.  If you stare closely at the constraints, you’ll see that they constitute a quadratically-constrained quadratic program, and finding the global optimum for a non-convex QCQP is NP-hard.  So we need some incredibly high-powered magic.  I chose the industrial-strength solver SCIP, which is the only global QCQP solver I could find with so much as a free license for academic use.  Happily, it has some very nice Python bindings.

Input and output

Pass the radius list on stdin, like [5,3,1.5].  The output shows objective value: rectangle area, x1, x2 rectangle dimensions, x3 rectangle area again, x4, x5 first circle center coordinates, x6, x7 second circle center coordinates, etc.

Test cases

[5,3,1.5] ↦ 157.459666673757

SCIP Status        : problem is solved [optimal solution found]
Solving Time (sec) : 0.04
Solving Nodes      : 187
Primal Bound       : +1.57459666673757e+02 (9 solutions)
Dual Bound         : +1.57459666673757e+02
Gap                : 0.00 %
objective value:                     157.459666673757
x1                                                 10   (obj:0)
x2                                   15.7459666673757   (obj:0)
x3                                   157.459666673757   (obj:1)
x4                                                  5   (obj:0)
x5                                                  5   (obj:0)
x6                                                  7   (obj:0)
x7                                   12.7459666673757   (obj:0)
x8                                                1.5   (obj:0)
x9                                   10.4972522849871   (obj:0)

[9,4,8,2] ↦ 709.061485909243

This is better than the OP’s solution.  The exact dimensions are 18 by 29 + 6√3.

SCIP Status        : problem is solved [optimal solution found]
Solving Time (sec) : 1.07
Solving Nodes      : 4650
Primal Bound       : +7.09061485909243e+02 (6 solutions)
Dual Bound         : +7.09061485909243e+02
Gap                : 0.00 %
objective value:                     709.061485909243
x1                                                 18   (obj:0)
x2                                   39.3923047727357   (obj:0)
x3                                   709.061485909243   (obj:1)
x4                                                  9   (obj:0)
x5                                   30.3923047727357   (obj:0)
x6                                                 14   (obj:0)
x7                                   18.3923048064677   (obj:0)
x8                                                  8   (obj:0)
x9                                                  8   (obj:0)
x10                                                 2   (obj:0)
x11                                  19.6154311552252   (obj:0)

[18,3,1] ↦ 1295.999999999

SCIP Status        : problem is solved [optimal solution found]
Solving Time (sec) : 0.00
Solving Nodes      : 13
Primal Bound       : +1.29599999999900e+03 (4 solutions)
Dual Bound         : +1.29599999999900e+03
Gap                : 0.00 %
objective value:                       1295.999999999
x1                                   35.9999999999722   (obj:0)
x2                                                 36   (obj:0)
x3                                     1295.999999999   (obj:1)
x4                                   17.9999999999722   (obj:0)
x5                                                 18   (obj:0)
x6                                   32.8552571627738   (obj:0)
x7                                                  3   (obj:0)
x8                                                  1   (obj:0)
x9                                                  1   (obj:0)

Bonus cases

[1,2,3,4,5] ↦ 230.244214912998

SCIP Status        : problem is solved [optimal solution found]
Solving Time (sec) : 401.31
Solving Nodes      : 1400341
Primal Bound       : +2.30244214912998e+02 (16 solutions)
Dual Bound         : +2.30244214912998e+02
Gap                : 0.00 %
objective value:                     230.244214912998
x1                                   13.9282031800476   (obj:0)
x2                                    16.530790960676   (obj:0)
x3                                   230.244214912998   (obj:1)
x4                                                  1   (obj:0)
x5                                   9.60188492354373   (obj:0)
x6                                    11.757778088743   (obj:0)
x7                                   3.17450418828415   (obj:0)
x8                                                  3   (obj:0)
x9                                    13.530790960676   (obj:0)
x10                                  9.92820318004764   (obj:0)
x11                                   12.530790960676   (obj:0)
x12                                                 5   (obj:0)
x13                                                 5   (obj:0)

[3,4,5,6,7] ↦ 553.918025310597

SCIP Status        : problem is solved [optimal solution found]
Solving Time (sec) : 90.28
Solving Nodes      : 248281
Primal Bound       : +5.53918025310597e+02 (18 solutions)
Dual Bound         : +5.53918025310597e+02
Gap                : 0.00 %
objective value:                     553.918025310597
x1                                   21.9544511351279   (obj:0)
x2                                   25.2303290086403   (obj:0)
x3                                   553.918025310597   (obj:1)
x4                                                  3   (obj:0)
x5                                   14.4852813557912   (obj:0)
x6                                   4.87198593295855   (obj:0)
x7                                   21.2303290086403   (obj:0)
x8                                   16.9544511351279   (obj:0)
x9                                                  5   (obj:0)
x10                                                 6   (obj:0)
x11                                                 6   (obj:0)
x12                                  14.9544511351279   (obj:0)
x13                                  16.8321595389753   (obj:0)

[3,4,5,6,7,8] ↦ 777.87455544487

SCIP Status        : problem is solved [optimal solution found]
Solving Time (sec) : 218.29
Solving Nodes      : 551316
Primal Bound       : +7.77874555444870e+02 (29 solutions)
Dual Bound         : +7.77874555444870e+02
Gap                : 0.00 %
objective value:                      777.87455544487
x1                                   29.9626413867546   (obj:0)
x2                                   25.9614813640722   (obj:0)
x3                                    777.87455544487   (obj:1)
x4                                   13.7325948669477   (obj:0)
x5                                   15.3563780595534   (obj:0)
x6                                   16.0504838821134   (obj:0)
x7                                   21.9614813640722   (obj:0)
x8                                   24.9626413867546   (obj:0)
x9                                   20.7071098175984   (obj:0)
x10                                                 6   (obj:0)
x11                                  19.9614813640722   (obj:0)
x12                                                 7   (obj:0)
x13                                                 7   (obj:0)
x14                                  21.9626413867546   (obj:0)
x15                                  8.05799919177801   (obj:0)


Haskell
Easy 4 characters
Returns a list of jolly integers if and only if a list of jolly integers is given as input. This is legal based on "Just a function that accepts arguments however and returns something that indicates jolly or not".
j=id

Alternative easy solution with 61 characters:
Takes in a list and returns the empty list if the sequence is jolly.
import List
j n=zipWith(\x->abs.(x-))n(tail n)\\[1..length n]


MATL, 15 12 bytes
,i4:)d|S]/da

The program inputs two  3×1 vectors of complex numbers representing the coordinates; and outputs 0 for similar, 1 for not similar.
Try it online! Or verify all test cases.
Explanation
The code checks if the side lengths, sorted for each triangle, are proportional between the two triangles.
,      % Do twice
  i    %   Take input: 3×1 vector of complex numbers
  4:)  %   Modular index to repeat 1st number after the 3rd. Gives a 4×1 vector
  d    %   Consecutive differences
  |    %   Absolute value, element-wise
  S    %   Sort
]      % End
/      % Divide, element-wise
d      % Consecutive differences
a      % Any: gives 0 if and only if all values are 0
       % Implicit display


Python 3, 89 87 69 68 bytes
Thanks @xnor for finding a shorter expression, saving 1 byte!

f=lambda a,b,c,n=3:n and(a+b+c)*(c*c/a/b-a/b-b/a+2)**.5+f(b,c,a,n-1)

Try it online!
A recursive function, takes in 3 sides of the triangle as input.
Recursion is used to repeats the function 3 times, each time with the positions of a,b,c swapped in order to calculate each of the 3 summands in the formula below.
How
We can see that each side of the hexagon is the base of an isosceles triangle, whose vertex angle is an angle of the original triangle. For example:

\$C_aC_b\$ is the base of \$CC_aC_b\$ - an isosceles triangle with leg \$c\$ and vertex angle \$\widehat{C}\$.
\$A_bB_a\$ is the base of \$CA_bB_a\$ - an isosceles triangle with leg \$a+b\$ and vertex angle \$\widehat{C}\$.

Given the leg \$l\$ and vertex angle \$\theta\$ of an isosleces triangle, the base is calculated as:
$$l\sqrt{2-2\cos{\theta}}$$
Consider 2 opposites side of the hexagon, says \$C_aC_b\$ and \$A_bB_a\$. Since their corresponding triangles have the same vertex angle, their total length is:
$$c\sqrt{2-2\cos{\widehat{C}}}+(a+b)\sqrt{2-2\cos{\widehat{C}}}$$$$=(a+b+c)\sqrt{2-2\cos{\widehat{C}}}$$
Then the perimeter of the hexagon is the sum of 3 opposite pairs:
$$(a+b+c)\left(\sqrt{2-2\cos{\widehat{A}}}+\sqrt{2-2\cos{\widehat{B}}}+\sqrt{2-2\cos{\widehat{C}}}\right)$$
The cosine of an angle can be calculated from the sides of the triangle:
$$2-2\cos{\widehat{C}}=\frac{c^2-(a-b)^2}{ab}$$
Thus, the final formula for the hexagon's perimeter is:
$$(a+b+c)\left(\sqrt{\frac{a^2-(b-c)^2}{bc}}+\sqrt{\frac{b^2-(a-c)^2}{ac}}+\sqrt{\frac{c^2-(a-b)^2}{ab}}\right)$$


Constructing an evil maze against random exploration

No dead ends near the entrance, 21,477,560 21,485,005
Try it online!
Yay, 21 million. The giant horizontal segments up to row 19 are also removed, so about 20% of the entire grid is just an open space.
Also, as the "real maze" starts at the leftmost column, moving the entrance to the top right gives a slight bump to the score. (Thanks to @Neil)

Previous version, 20,211,703
Try it online!
Yes, 20 million. It's actually good to remove some dead ends and add some open spaces near the entrance, but it stops being good as it gets sufficiently far away from it.
This is a derivation from width-3 dead end maze by removing some h-walls (it's called h-walls in the code, but it is a vertical segment in the image):

The h-walls from row 1 to row 22 (inclusive) are entirely removed.
The h-walls from row 23 to row 40 (inclusive) are reduced by half, keeping the odd indices.


05AB1E, 20 18 16 15 14 bytes
*j.rS²ô2Føε8.ø

Takes three inputs in the order: height, width, string. Output as a 2D list of characters.
Uses 8 as border, but could be any digit.
-1 byte thanks to @Grimy.
Try it online or verify all test cases. (TIO contains }}J» in the footer to pretty-print the result; feel free to remove it to see the actual output 2D list of characters instead.)
Explanation:

*               # Multiply the (implicit) width and height inputs
 j              # Pad the (implicit) input-string with up to that amount of leading spaces,
                # so the total string-length is equal to that value
  .r            # Shuffle the characters in the string
    S           # Convert the string to a list of characters
                # (edge-case for the zip below with strings of size 1 with 1x1 dimensions)
     ²          # Push the width input again
      ô         # Split the list of characters into parts of that size
       2F       # Loop 2 times:
         ø      #  Zip/transpose the 2D list; swapping rows/columns
          ε     #  Inner map over each line:
           8.ø  #   And surround this line-list with a leading/trailing "8"
                # (after the loop, the result is output implicitly)


54 52 50 49 48 45 39 bytes
Removed 4 bytes thanks to Dennis.
The latest version is inspired by the "some reason" in xnor's answer.
class t(int):__add__=type
a=b=t()
c=d=0


HTML + JS (ES6), 8 + 60 = 68 bytes

Tested in Chrome.

setInterval`a.innerHTML=new Date().toLocaleTimeString('fr')`

-1 byte (@ETHProductions): Use French time format instead of .toTimeString().slice(0,8)

HTML + JS (ES6), 8 + 62 = 70 bytes

This will work in FireFox.

setInterval('a.innerHTML=new Date().toLocaleTimeString`fr`',0)

-3 bytes (@ETHProductions): Use French time format instead of .toTimeString().slice(0,8)


Shortest Way of creating a basic Space Invaders Game in Python

3060 3031 characters

OKAY, this was fun. But I very highly doubt that my code is short enough to compete, or if it's basic enough. I'm new to code golf but regardless, I had fun and that's what matters. I'm too used to object-oriented programming so a lot of my code is probably just too much objects...
Game runs solely in the console, and I shortened most of the code with the exec''''''.replace() method. Complete with input of your name, random enemy firing, walls, aliens are randomly generated, worth 50 points each. each time you fire you lose one point so that you lose points if you just hold space in one spot to beat the level. Enemy speed increases each level, capped at every 0.2 seconds. Prints the level number, and game over at the bottom, your name,lives, and score at the top left. you have 3 lives. Ungolfed version is ~9500 characters, but I'll leave that out of here for now

instructions: fire with space, move with a and d, exit with x

let me know what think, if I can improve on anything

edit: forgot that msvcrt is Windows-Only. perhaps I can make a unix version too...

exec'''import threading as t
import msvcrt,Queue,time,random,os
u=raw_input('name:')
r=range
@Z:
$~(S):S.w=78;S.h=30;S.X();S.l='';S.Q=[];S.q=[];S.m=''
$J(S,x,y,c):S.q.append([x,y,c])
$X(S):S.s=[[' '^y in r(78)]^x in r(30)]
$V(S):
?s='';S.X()
?^x,y,z in S.q:S.s[y][x]=z
?S.q=[]
?^x in S.s:
? ^y in x:s+=y
? s+='\\n'
?s+=S.m.center(S.w)
?if s!=S.l:os.system('cls');S.l=s;print s
@E(Exception):pass
@C:
$~(S,g,c,p):S.g=g;S.c=c;S.p=p;S.s=[]
$M(S,a,d):
?if (a<0 and S.p[d]==0) or (a>0 and S.p[d]==(S.g.z.h if d else S.g.z.w)-1):raise E()
?S.p[d]+=a
$X(S):S.s.remove(S)
@A(C):
$~(S,g):C.~(S,g,'A',[39,28])
$M(S,a,d=0):
?try:C.M(S,a,d)
?except E:pass
@Y(A):
$~(S,g,p):C.~(S,g,'Y',p);S.s=g.a
@B(C):
$~(S,g,p,n):C.~(S,g,'|'if n<0 else'*',[p[0],p[1]+n]);S.s=g.b;S.d=n;S.a=0 if n<0 else 1
$M(S):
?try:C.M(S,S.d,1)
?except E:S.X()
$b(S):S.g.z.J(S.p[0],S.p[1],'X');S.g.z.V();S.X()
$co(S):
?^w in S.g.w:
? if S.p==w.p:S.b();w.X()
?if S.a:
? if S.p==S.g.p.p:S.b();S.g.d()
?else:
? ^a in S.g.a:
??if S.p==a.p:S.b();S.g.P(50);a.X()
@W(C):
$~(S,g,p):C.~(S,g,'#',p);S.s=g.w
@I(t.Thread):
$~(S,g):t.Thread.~(S);S.f=1;S.c={'a':g._g4,'d':g._g3,'x':g._X,' ':g._fi};S.start()
$run(S):
?while S.f:
? c=msvcrt.getch()
? if c in S.c:S.c[c]()
$X(S):S.f=0
@G:
$~(S):S.z=Z();S.x=3.0;S.c=0;S.b=[];S.Q=Queue.Queue();S.I=I(S);S.g2=0;S.g1=0;S.do=0;S.f=1;S.v=0;S.l=3;S.ti=[];S.G(1);S.O()
$O(S):
?while S.f:
? time.sleep(0.02)
? if not S.a:S.G(1)
? S.ch();S.B();S.u()
$u(S):
?S.z.X();S.P(0)
?s=u+' '+`S.l`
?^i in r(len(s)):S.z.J(i,0,s[i])
?^i in S.a+S.b+[S.p]+S.w:S.z.J(i.p[0],i.p[1],i.c)
?S.z.V()
$ch(S):
?try:
? while not S.Q.empty():S.Q.get_nowait()();S.Q.task_done()
?except Queue.Empty:pass
$cl(S):
?try:
? while not S.Q.empty():S.Q.get_nowait();S.Q.task_done()
?except Queue.Empty:pass
$_g4(S):
?if not S.g2:S.g2=1;S.Q.put(S.g4)
$g4(S):S.p.M(-1);S.g2=0
$_g3(S):
?if not S.g1:S.g1=1;S.Q.put(S.g3)
$g3(S):S.p.M(1);S.g1=0
$_X(S):S.I.X();S.Q.put(S.X)
$X(S):S.f=0;S.I.X();S.st()
$_fi(S):
?if not S.do:S.do=1;S.Q.put(S.fi)
$fi(S):S.b.append(B(S,S.p.p[:],-1));S.do=0;S.P(-1)
$_af(S):S.Q.put(S.af)
$af(S):c=random.choice(S.a);S.b.append(B(S,c.p[:],1));S.nt(random.uniform(0.1,2),S._af)
$nt(S,n,f):x=t.Timer(n,f);S.ti.append(x);x.start()
$st(S):
?^i in S.ti:i.cancel()
$G(S,n=0):
?S.st();S.cl();S.p=A(S);S.a=[];S.w=[];S.b=[]
?^x in[[i,o]^i in r(30)^o in r(3,10)]:
? if random.randint(0,99)%4==0:S.a.append(Y(S,x))
?S._m();S._af();f=[]
?^x in [6,27,46,65]:f+=[[z,y]^z in r(x,x+6)^y in r(23,26)]
?^i in f:S.w.append(W(S,i))
?S.v+=n;S.z.m='Level %s'%S.v;S.u()
?if S.x>0.2:S.x=1.6 - S.v*0.1
?S.m1=0;S.m2=0;S.k=1;time.sleep(3)
$_m(S):S.Q.put(S.m)
$m(S):
?x=0
?if S.m2:S.m2=0;S.m1=0;S.k=-S.k;x=1
?^i in S.a:i.M(*(abs(S.k),1)if x else(S.k,0))
?if S.m1==47:S.m2=1
?else:S.m1+=1
?S.nt(S.x,S._m)
$B(S):
?^i in S.b:i.M();i.co()
$d(S):
?S.l-=1
?if S.l==0:S.z.m='Game Over!';S.X();return
?S.G(0)
$P(S,n):
?S.c+=n if S.c+n>0 else 0;x=`S.c`
?^n in r(len(x)):S.z.J(n,1,x[n])
G()'''.replace('@','class ').replace('?','  ').replace('$',' def ').replace('^','for ').replace('~','__init__')

what the screen looks like:

Blazer 3
488            |

      YY  Y         YY  Y Y Y     Y
      YY  Y   YY  Y  Y           Y
      Y   Y    Y      Y    YY
                           Y   Y  Y
       YY Y   Y   Y Y             Y
           Y  YY YX Y Y
       Y       Y |                 Y

                   |

         *

                    |

      ####           |     ######             ######             ######
      ######               ######             ######             ######
      ######               ######             ######             ######

                     A

                                   Level 1

edit: managed to remove something I accidentally left in I wasn't using anymore


Jelly, 6 bytes

R2*%i1

Try it online!

How it works

R2*%i1  Input: n

R       Range; yield [1, ..., n].
 2*     Compute [2**1, ..., 2**n].
   %    Hook; take all powers modulo n.
    i1  Get the index of the first 1.
        Indices are 1-based, so index k corresponds to the natural number k.


I see your BIDMAS and raise you a BADMIS

JavaScript (V8),  118  112 bytes

Prints the results.

f=(s,x='',y=x,o='+-*/')=>[...o].map(v=>f(s.split(v).join(x+v+y),x+')',y+'(',o.replace(v,'')))|print(eval(y+s+x))

Try it online!

Or see the deduplicated results.


Golfscript, 24 characters
"QUESTIONNAIRE"{32+}%36*

Way too easy.
36 repetitions of "questionnaire" = 36*13 characters = 468 characters.
36 repetitions of "questionnaire" = 37+36+...1 point = (37+1)(37)/2 points = 703 points.


Mathematica, 13 bytes

CompleteGraph

Looks like this only fails to give a circular embedding for n=4, but the question states n>=20


Python 3, 32 bytes

x='L'
while[print(end=x)]:x='ol'

Try it online!
In Python 3, the print function by default has end='\n' to put a newline after what you print. Rather than changing that to the empty string, we stick the value x that we want to be printed there, and don't provide any value to be printed.
We stick the printing in the while loop condition. Since print returns None by default but this is Falsey and won't continue the loop, we wrap it in a singleton list to make it Truthy.
I had tried to stick an infinite iterator into print like print(*iter(...),sep=''), but it looks like Python will consume the whole iterable first and never actually print.


Count how many numbers are divisible by perfect numbers in a given range

Mathematica - 117

Naive approach, linear for the range size

With[{p=#(#+1)/2&/@Select[2^Range@@Floor@Log2@Sqrt@#-1,PrimeQ]},Length@Select[Range@@#,Or@@Divisible[#,p]&]]&@Input[]

The correct way would be constructing numbers from the perfect numbers that are in the given range of course.


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.


JavaScript, 38 bytes

Yet another way to do this, shortest of all.

This supposedly prints each number on a new line using \n. Now as the data is being written to an HTML document, \n is not of any use and the numbers appear to be separated by space only.

for(i=1;i<1e5;i+=2)document.writeln(i)


Bash + lynx, 73
lynx -dump http://nyti.ms/2BY72Ph|grep -Po '\[(1[6-9]|2[0-3])]\K[^.]*...'

Output is as follows:
General Electric Co          10.11
Advanced Micro Devices Inc   33.13
PG&E Corp                    6.14
Fiat Chrysler Automobiles NV 14.98
Neuralstem Inc               1.83
AT&T Inc                     38.20
GrubHub Inc                  34.00
Twitter Inc                  29.86


C# (.NET Core), 83, 80, 60 59 bytes

n=>{int i=0;for(var t="";t!=n;)t=++i%2<1?t+i:i+t;return i;}

Try it online!

Takes the input as a string into a lambda function. 1-indexed. Returns the index of the value for truthy, or infitnitely loops for a "falsey"


05AB1E, 17 14 13 bytes
Thanks to @KevinCruijssen and @Grimmy for the fix and inspiration from Kevin's now deleted answer
-1 byte further thanks to @Grimmy
L.ÆʒRÆo@}ʒPI%

Try it online!

Explanation
L.Æ                    - Combinations of [1..N] with 2 elements
    ʒ     }            - Filter this when ...
     RÆo               - 2^(The difference of each pair) is...
        @              - <= the input
           ʒPI%        - Then filter this list further where the product modulo input is 1


JavaScript (ES6), 149 bytes

u=>u.split`/`.map((p,i)=>i?/^\d+$/.test(p)?(+p).toString(36):p[0]:(d=p.split`.`).slice(0,-1).map((s,j)=>s[l=j,0]).join``+"."+d[l].slice(1,3)).join`/`

Explanation

I made this independent of @Neil's solution but it ended up looking very similar.

u=>
  u.split`/`.map((p,i)=>       // for each part p at index i
    i?                         // if this is not the first part
      /^\d+$/.test(p)?         // if p is only digits
        (+p).toString(36)      // return p as a base-36 number
      :p[0]                    // else return the first letter
    :
      (d=p.split`.`)           // d = domain parts
      .slice(0,-1).map((s,j)=> // for each domain part before the last
        s[l=j,0]               // return the first letter, l = index of last domain part
      ).join``
      +"."+d[l].slice(1,3)     // add the 2 letters as the final domain
  )
  .join`/`                     // output each new part separated by a slash

Test

var solution = u=>u.split`/`.map((p,i)=>i?/^\d+$/.test(p)?(+p).toString(36):p[0]:(d=p.split`.`).slice(0,-1).map((s,j)=>s[l=j,0]).join``+"."+d[l].slice(1,3)).join`/`
<input type="text" id="input" value="math.stackexchange.com/a/2231/" />
<button onclick="result.textContent=solution(input.value)">Go</button>


Vim, 42 strokes

:s/[^A-Z0-9]//g
YPVr-i+<DOWN><LEFT>|<ESC><C-V>ky$pYjppVr $xrv

Replace <DOWN> with ↓, <LEFT> with ←, <ESC> with esc and <C-V> with CTRL+V.

Here's an animation of this script running (old version which uses a V instead of a v):

Explanation of the script:

:s/[^A-Z0-9]//g                               # Remove all the characters that are not uppercase or numbers using a Regex.
YPVr-                                         # Duplicate the current, and replace all the characters of the upper one with dashes.
     i+<DOWN><LEFT>|<ESC>                     # Insert a + on the upper line, and a | on the second line.
                         <C-V>ky$p            # Copy the + and | to the end of both lines.
                                  Yjpp        # Copy the upper line to the bottom two times.
                                      Vr $    # Replace the bottom most line with spaces and put the cursor on the last character.
                                          xrv # Remove the last character and replace the second last character with a v.


CJam, 26 25 21 bytes

WqN/":.+""\%"(~+N-~N*

Thanks to @MartinBüttner for golfing off 4 bytes!

Try it online in the CJam interpreter: original program | rotated program

This is the rotated program:

W
q
N
/
"
:
.
+
"
"
\
%
"
(
~
+
N
-
~
N
*

Idea

We can rotate the input a quarter turn clockwise by splitting it at linefeeds, reversing the order of the resulting rows, transposing rows with columns, and finally joining the rows, separated by linefeeds.

Likewise, we can rotate counterclockwise by transposing first, then reversing the rows.

Since the transposition built-in z is forbidden, we can use :.+ (reduce by vectorized character or string-character concatenation) to achieve the same effect.

:.+ is the only part of the source code that cannot be broken up. We push the strings "W%" and ":.+", conditionally reverse them if the second string contains a linefeed, concatenate, remove all linefeeds, and evaluate the result.

Code

W     e# Push -1.
qN/   e# Read all input at split it at linefeeds.
":.+" e# Push a string that, when evaluated, transposes rows and columns.
      e# As explained in the previous section, this does NOT use a built-in
      e# for matrix transposition.
"\%"  e# Push a string that, when evaluated, reverses the rows.
(~    e# Shift out the first character and evaluate it.
      e# For the original code, this evaluates '\', swapping the strings on
      e# the stack. For the rotated code, this evaluates `\n', doing nothing.
+N-   e# Concatenate and remove linefeeds.
      e# The stack now contains:   -1 input "%:.+"   or   -1 input ":.+\%"
~     e# Evaluate the string on top of the stack.
N*    e# Join the resulting array, separating by linefeeds.


Python 2, 160 158 156 148 124 bytes
Prepare to be amazed! The resulting text is drawn on a canvas... by a Turtle! :D

from turtle import*
h,n=input()
up()
rt(n*60)
l=0
for c in h:
 write(c);fd(9);l-=1
 if" ">c:fd(9*l);rt(90);fd(15);lt(90);l=0

Try it online - Supports decimal rotations as well!

If you would prefer the turtle to be shaped like one, you can add the line t.shape("turtle").
View the revision history to see past versions.
Aliases used:
up() - penup()
rt() - right()
lt() - left()
fd() - forward()
bk() - backward()
Thanks to Sherlock9 for the suggestions!


Ruby 134 131/10=13.1
->g,b{"Rowdy Rumble|Dread of Night|Riku|One Winged Angel|Rage Awakened|Vim and Vigor|The Key|The 13th Struggle".split(?|)[b.ord%8]}

This is a lambda function, which takes arguments for the game and the boss. The argument for the game is actually ignored by the code, but the OP has clarified that the argument cannot be eliminated.
In fact it only uses the first letter of the boss's name. the ASCII code is taken modulo 8 (this gives the same answer for a given letter, regardless of case) and one of 8 song titles is returned. As two song titles appear twice, this covers a total of 10 elements:
Game   Boss                      Array  Song
                                 index
Coded  Pete                         0   Rowdy Rumble
DDD    Anti Black Coat Nightmare    1   Dread of Night
Coded  Riku                         2   Riku
1      Sephiroth                    3   One Winged Angel
2      Sephiroth                    3   One Winged Angel
2      Lingering Sentiment          4   Rage Awakened
BBS    Terra vs Master Xehanort     4   Rage Awakened
Coded  Maleficent                   5   Vim and Vigor
BBS    Ventus vs Vanitas            6   The Key
CoM    Organization XIII            7   The 13th Struggle

It was a lucky coincidence that the Ascii codes for L and T give the same result modulo 8, so both incidences of Rage Awakened could be covered.
Call the function as in this test program:
f=->g,b{"Rowdy Rumble|Dread of Night|Riku|One Winged Angel|Rage Awakened|Vim and Vigor|The Key|The 13th Struggle".split(?|)[b.ord%8]}
B=gets                  #get boss name from stdin
puts f.call("dummy",B)  #call function, and output return value to stdout


Storing a DNS name as compactly as possible in memory (preferably in C#)

You could interpret it as a base 39 number. Since only the first character can be an asterisk, you can encode it as the sign. If i use the characters as digits in the order you named them, www.google.com would be 10903065870001232914011 in decimal and 24f0e6f41d8ecd3a65b in hex, which could be stored in 10 bytes.

*.google.com would be -310664672884413873 in decimal and fbb04c2040762a4f in hex, if you store it in 8 bytes.


CJam, 42 40 bytes

"wertyuiop asdfghjkl zxcvbnm"q/W=S%Sf*N*

Test it here.

Explanation

"we...nm"
     e# Push the letters in order, without q. We don't need q, because it will never
     e# be part of the output.
q/   e# Split the string around the input. If the input is "q", the entire string
     e# will go into a single chunk.
W=   e# Select the last chunk.
S%   e# Split the string around spaces, discarding empty segments (only relevant for the
     e# first segment if the input is "p" or "l").
Sf*  e# Join each line by spaces.
N*   e# Join the lines by linefeeds.


Should be answers to respective challenges (if they exist). Note that some of these code samples might alerady be answers somewhere else.

If you just want to print undefined, use this 4-byte, 1-char program.

Infinite loop (6 bytes, 2 chars).

ℹ⏩

Cat (owned by Conor O'Brien) (15 bytes, 5 chars).

⏫⏪⏬⏫⏩

This program should output the 8 phases of the moon, but it doesn't seem to work (61 bytes, 16 chars).

⏪⏬⏩

Hypothenuse (27 bytes, 7 chars).

➕


JavaScript (ES6), 39 34 bytes
a=>[a.sort((x,y)=>x-y).pop(),...a]

Sort the array in ascending order, pop the last element and use it as the first element of a new array. Then destructure the remaining elements of the original array into the new array (In JS, both sort and pop modify the original array).

Test it

o.innerText=(f=

a=>[a.sort((x,y)=>x-y).pop(),...a]

)(i.value=[1,2,3]);oninput=_=>o.innerText=f(i.value.split`,`)
<input id=i><pre id=o>


Python 3, 354 341 336 bytes

import re
S=re.sub
def f(x):
	r=x.splitlines();C=r[-1].strip('%put ');D=0
	while D!=C:
		D=C
		for a in sorted([l.strip('%let ').replace(" ","").split(';')[0].split('=')for l in r[:-1]],key=lambda y:-len(y[0])):
			s=1
			while s:C,s=re.subn('&'+a[0]+'(\.?)',a[1]+'\\1',S('+\.([^\.])','\\1',C),0,re.I)
	return S('+\.?','',C)

Try it online!

edit: some easy shortening

edit: reverse sort by -len(...) instead of [::-1] (5 bytes), thanks to Jonathan Frech!

Ungolfed

import re
S=re.sub # new name for the function re.sub()
def f(x):
    r=x.splitlines() # input string to list of rows
    C=r[-1].strip('%put ') # get the string to put (from the last row)
    D=0
    while(D!=C): # iterate until the result does not change
        D=C
        for a in                                                                                : # iterate over the list of variables
                 sorted(                                                                          ,key=lambda y:len(y[0]),reverse=1) # sort list for greediness by decreasing var.name lengths
                        [l.strip('%let ') # cut the 'let' keyword
                                         .replace(" ","") # erase spaces
                                                         .split(';')[0] # cut parts after ';'
                                                                       .split('=') # create [variable_name,value] list
                                                                                for l in r[:-1]] # for each row but last
            s=1
            while(s): # iterate until the result does not change
                C,s=re.subn( # substitute
                            '&'+a[0]+'(\.?)', # &varname. or &varname
                                                 a[1]+'\\1', # to value. or value
                                                              S('+\.([^\.])','\\1',C), # in the string we can get from C erasing ('s)(.) sequences if the next char is not .
                                                                                0,re.I) # substituting is case insensitive
    return S('+\.?','',C) # erase smileys and one .


Python 3, 574 \$\cdots\$ 338 337 bytes

from random import*
e,L,B,P=exit,"Lose","Bank:","Player:"
d=[*range(2,12)]*4+[10]*12
c=d.pop
def h(l,m):
 l+=[c()]
 if sum(l)>21and 11in l:l[l.index(11)]=1
 print(m,*l);return sum(l)
shuffle(d)
b=[]
t=h(b,B)
p=[c()]
u=h(p,P)
u>20<e("Blackjack")
while'h'==input():u=h(p,P)
u>21<e(L)
while t<18:t=h(b,B)
22>t>u<e(L)
u==t<e("Draw")
e("Win")

Try it online!

Saved 34 bytes thanks to @ReinstateMonica!!!


JavaScript 52

for(i=s=0;i++<1e4;)s+=Math.random()<2/3;alert(s/100)

Doors are 1:[0,1/3), 2:[1/3,2/3), 3:[2/3, 1)

Assume the prize is always in door 3. If the guest picks doors 1 or 2, which is range [0,2/3), and they switch, they've won the prize.


Bash: 47 bytes

Still no bash entry? I'm disappointed ...

case $1 in
    [1-7]) date -d "14-08-1$1" +%A
esac

It uses the days of the current week and simply substitutes the last digit (11-17 August 2014 -- 11 is Monday, 12 is Tuesday, etc.).


What's the shortest way to define an anonymous recursive function in Octave?


Ruby, 73 71 bytes
Saved two bytes thanks to @vrintle (one directly and another with further golfing)

77.times{|i|$><<(~i%11>0?:RD[i%2]+'+-'[rand 2]*2+' ':?U+?'*rand(2)+$/)}

Try it online!
$/ is the input record separator, which is a newline by default.

In Ruby 2.7 (newer than the version on TIO), we get 70 bytes using numbered block parameters:
77.times{$><<(~_1%11>0?:RD[_1%2]+'+-'[rand 2]*2+' ':?U+?'*rand(2)+$/)}


Build a solver for the monks and buns problem

R: 81 characters

i=scan();p=combn(0:i[2],2);cat(p[,p[1,]+p[2,]==i[2]&i[3]*p[1,]+p[2,]/i[4]==i[1]])

A brute force solver which takes all possible combinations of non-negative integers and subset the one corresponding to criteria.


Reduce string to a snippet of the alphabet

JavaScript (ES6), 66 79 68 67 bytes

f=([c,...s],p)=>c?(p?~parseInt(c+p,36)%37:c<'!')?f(s,p):c+f(s,c):''

How?

Testing consecutive letters

Because converting two characters to their ASCII codes would be a rather lengthy operation in JS, we use the following formula instead:

~parseInt(b + a, 36) % 37

Provided that both a and b are in [a-zA-Z ], the above expression equals 0 if and only if a and b are consecutive letters (i.e. consecutive digits in base 36), no matter the case of the characters.

For instance:

~parseInt("Y" + "x", 36) = ~(36 * parseInt("Y", 36) + parseInt("x", 36))
                         = ~(36 * 34 + 33)
                         = -(36 * 34 + 33 + 1)
                         = -(37 * 34)

Formatted and commented

f = ([c,                              // c = current character
         ...s],                       // s = array of remaining characters
                p) =>                 // p = previous matching letter
  c ? (                               // if there's still at least 1 character to process:
      p ?                             //   if p was already defined:
        ~parseInt(c + p, 36) % 37     //     test if p and c are NON-consecutive letters
      :                               //   else:
        c < '!'                       //     test if c is a space character
    ) ?                               //   if the above test passes:
      f(s, p)                         //     ignore c and keep the current value of p
    :                                 //   else:
      c + f(s, c)                     //     append c to the final result and update p to c
  :                                   // else:
    ''                                //   stop recursion

Test cases

f=([c,...s],p)=>c?(p?~parseInt(c+p,36)%37:c<'!')?f(s,p):c+f(s,c):''

console.log(f("codegolf")) // -> cdef
console.log(f("CodEgolf")) // -> CdEf
console.log(f(" codeolfg")) // -> cdefg
console.log(f("ProgrammingPuzzles")) // -> P
console.log(f("Stack Exchange")) // -> St
console.log(f("The quick red fox jumped over the lazy brown dog")) // -> Tuvw
console.log(f("Zebra")) // -> Z
console.log(f("Abcdegfhijkl")) // -> Abcdef


Write a Programming language of Unknown Completeness

Legendre

This language is only Turing-complete if and only if Legendre's conjecture is false, i.e. there exists a integer n > 0 such that there are no primes between n^2 and (n+1)^2. This language takes some inspiration from Underload, though in some respects it is very different from it.

Programs in Legendre are made up of series of positive integers (0 is especially banned, because it essentially negates the entire purpose of the language). Each integer corresponds to a base command in Legendre, or a potential user-defined one. Which command it is assigned to is based on the number of primes between its square and the next integer (equivalent to the OEIS sequence A014085).

The language's commands modify a stack, which can hold arbitrarily large positive integers. If the stack ever holds 0, the 0 is immediately removed. In detail, the commands are:

2 (smallest integer producing this command: 1): Push the next integer in the program onto the stack.
3 (smallest producing integer: 4): Pop the top integer on the stack and execute the command associated with it.
4 (smallest: 6): Pop the top integer. If it was 1, increment the top integer on the stack.
5 (10): Swap the top two stack items.
6 (15): Decrement the top integer on the stack. If that results in 0, pop the 0 and discard it.
7 (16): Duplicate the top integer on the stack.
8 (25): Halt execution and print the stack contents.

This is the basic instruction set, which is unable to do anything interesting, let alone loop. However, there is another command, which can be accessed only if Legendre's conjecture proves false.

0 (unknown): Remove all items from the stack and combine them into a new function, which will execute all commands starting at the original bottom of the stack and ending at the top, accessible as a command whose "command number" is equal to the one the next integer in the program source corresponds to.

If this command is somehow accessible, the language becomes Turing-complete, as one can simulate a Minsky machine in it.

When the command 8 is execute or the end of the program is reached, the program terminates and the (Unicode) character corresponding to each integer on the stack is printed.

Example programs

1 2 1 3 1 10 4

This simple program pushes the number 2, then 3 and finally a 10, before executing a 4 (command: 3), which causes the 10 (command: 5) to be popped and executed, swapping the 2 and 3.

1 5 3 15 2 1 6 7

This program demonstrates the use of the indirect integer-to-command correspondence. First, a 5 is pushed, then a 15 and a 1, using three different ways of encoding the 2 command. Then, the 1 is popped and as a result, the 15 is incremented to a 16, and finally executed. The program ends with two instances of the number 5 on the stack.

1 1 1 5 ? 24 1 15 1 31 ? 31 24 31

This program demonstrates the use of the 0 command, using ? as a placeholder number. The program first stores '1 5' in the function 9, then '15 31' in 10, before running function 9 (using 24), which pushes 5 onto the stack, and the repeatedly decrements it, until it reaches 0 and is removed. Then, the program halts.

Minsky machine

In order to convert a Minsky machine to Legendre code, the 0 command must be used. Because this command is inaccessible unless Legendre's conjecture is false, I have used a placeholder ? instead.

Note that all Minsky machine instruction line names need to have integers with different A014085 correspondences from each other and the base commands as well as 24 (9) and 31 (10).

Initialization:

1 1 1 1 ? 24

x INC (A/B) y:

A:

1 y 1 24 1 ? 1 6 1 1 16 1 24 ? x

B:

1 y 1 24 1 ? 1 10 1 6 1 1 16 1 10 1 24 ? x

x DEC (A/B) y z:

A:

1 4 1 10 1 15 1 10 1 31 1 1 1 10 1 z 1 1 1 16 1 24 1 31 1 ? 1 24 1 15 1 y 1 6 16 1 24 16 1 ? 1 1 16 1 10 1 1 16 1 24 ? x

B:

1 4 1 10 1 15 1 10 1 31 1 1 1 10 1 z 1 1 1 16 1 24 1 31 1 ? 1 24 1 15 1 10 1 y 1 6 16 1 24 16 1 ? 1 1 16 1 10 1 1 16 1 10 1 24 ? x

x HALT:

1 25 ? x

To create the final program, append all parts (with x,y,z replaced by their counterparts) and add a single integer to start the first instruction in the chain. This should prove the language's Turing-completeness in case Legendre's conjecture is proven false by counterexample.

Interpreter

This interpreter is written in Python (3), and has been tested on all three above examples. Use the -a/--allowZero flags to allow ? to be used, -f/--file to run code directly from a file and -s/--stackOut to output the stack as a Python list instead. If no file is given, the interpreter enters a sort of REPL mode, which is best used with --stackOut.

import sys
import argparse
import io

class I_need_missing(dict): #used to avoid try/except statements. Essentially a dict
    def __missing__(self,key):
        return None

def appropriate(integer,prev): #returns number of primes between the square of the integer given and the next

    return_value = 0

    if prev[integer]:
        return prev[integer],prev
    if integer == "?":
        return 0,prev
    for i in range(integer ** 2, (integer + 1) ** 2):
        t = False
        if i > 1:
            t = True
            for j in range(2,int(i ** 0.5)+1):
                t = i/j != round(i/j)
                if not t:
                    break
        return_value += t

    prev[integer] = return_value
    return return_value,prev

def run_command(commandseries,stack,functions,prev): #Runs the appropriate action for each command.

    command,prev = appropriate(commandseries.pop(0),prev)

    halt = False

    if command == 0: #store in given number
        functions[appropriate(commandseries.pop(0),prev)[0]] = stack
        stack = []

    elif command == 2:#push
        stack.append(commandseries.pop(0))

    elif command == 3:#execute top instruction
        commandseries.insert(0,stack.pop())

    elif command == 4:#pop, add 1 to new top if popped value was 1
        if stack.pop() == 1:
            stack[-1] += 1

    elif command == 5:#swap top two integers/?
        stack[-1],stack[-2] = stack[-2],stack[-1]

    elif command == 6:#subtract 1 from top of stack
        stack[-1] -= 1
        if stack[-1] == 0:
            stack.pop()

    elif command == 7:#duplicate top of stack
        stack.append(stack[-1])

    elif command == 8:#halt
        halt = True

    else:#run custom
        try:
            commandseries[0:0] = functions[command]
        except TypeError:
            print("Warning: unassigned function " + str(command) + " is unassigned", file = sys.stderr)

    return commandseries,stack,functions,prev,halt

def main(stack,functions,prev):
    #Parser for command line options
    parser = argparse.ArgumentParser(description = "Interpreter for the Legendre esoteric programming language.")
    parser.add_argument("-a","--allowZero", action = "store_true")
    parser.add_argument("-f","--file")
    parser.add_argument("-s","--stackOut", action = "store_true")

    args = parser.parse_args()
    allow_zero = bool(args.allowZero)

    #Program decoding starts
    pre = ""

    if not args.file:
        pre = input()
        if pre == "":
            return
    else:
        pre = open(args.file).read()

    mid = pre.split()
    final = []

    for i in mid:
        if i == "?" and allow_zero:
            final.append("?")
        elif i != 0 or allow_zero: #and allow_zero)
            final.append(int(i))

    halt = False

    #Functional programming at its best
    while final and not halt:
        final,stack,functions,prev,halt = run_command(final,stack,functions,prev)

    #Halting and output
    else:
        if args.stackOut:
            print(stack)
        else:
            for i in stack:
                print(i == "?" and "?" or chr(i),end = "")
            print("")
        if args.file or halt:
            return
        else:
            main(stack,functions,prev)

if __name__ == '__main__':
    main([],I_need_missing(),I_need_missing())


How many balloons do I need in each corner?

Jelly, 14 bytes

3Ḷ×þ`ZU$Ƭ×µ§§‘

Try it online!

Takes input as a 3x3 matrix and outputs a list going clockwise starting from the bottom-right.

Explanation

3Ḷ×þ`ZU$Ƭ×µ§§‘     Main Link
3Ḷ                 [0, 1, 2]
  ×þ`              outer product by multiplication with itself ([0, 0, 0], [0, 1, 2], [0, 2, 4])
        Ƭ          (include the original, plus) rotate clockwise until results are no longer unique (4 results total)
     ZU$           zip and upend (clockwise rotation)
         ×         vectorized multiply with original (gets the workload distributions to each balloon)
           §§      sum results for each balloon (vectorized-sum rows in the matrix; sum the results)
              ‘    increment


I reverse the source code, you reverse the input!

JavaScript, 32 bytes

s=>s//``nioj.)(esrever.]s...[>=s

Reversed:
s=>[...s].reverse().join``//s>=s


05AB1E, 16 bytes
Uses the fact that 05AB1E has a constant predefined to "()<>[]{}" and isn't affected the visually reversion.
Code:
,q‡"}{][><)("užR

Explanation:
,                 # Pop and print the input.
 q                # Quit.
  ‡"}{][><)("užR  # This part is ignored.

Try it online!

Reversed:
Ržu"()<>[]{}"‡q,

Explanation:
R                 # Reverse the input.
 žu               # Short for "()<>[]{}".
   "()<>[]{}"     # Push this string.
             ‡    # Transliterate (no-op, since everything is transliterated to itself).
              q   # Quit and implicitly print.
               ,  # This part is ignored.

Try it online!

Visually reversed:
Ržu")(><][}{"‡q,

Explanation:
R                 # Reverse the input.
 žu               # Short for "()<>[]{}".
   ")(><][}{"     # Push this string.
             ‡    # Transliterate (giving the visually reversed string).
              q   # Quit and implicitly print.
               ,  # This part is ignored.

Try it online!
Uses CP-1252 encoding.


Tips for Golfing in ECMAScript 6 and above

Spread operator ...

The spread operator transforms an array value into a comma separated list.

Use case 1:

Directly use an array where a function expects a list

list=[1,2,3]
x=Math.min(...list)
list=[10,20], a.push(...list) // similar to concat()

Use case 2:

Create an array literal from an iterable (typically a string)

[...'buzzfizz'] // -> same as .split('')

Use case 3:

Declare a variable number of arguments for a function

F=(...x) => x.map(v => v+1)
// example: F(1,2,3) == [2,3,4]

See mozilla doc


Python 2, 76 bytes

f=lambda n,k=1000:n>19and(f(n/k,k/10)+`k-k%4*5`)*(n>=k)+f(n%k,k/10)or`n`[:n]

Try it online!

Test suite from Chas Brown.

A fully recursive solution that splits on place values k=1000, k=100, and k=10. The separator for the place values is computed as k-k%4*5, which maps

1000 -> 1000
100  -> 100
10   -> 0

By stopping when n<=19, we avoid one-word numbers in the teens being split up.


C#, 288 bytes
Stag is a great shoW.        "="=""="="Agent"plastic"Was"tryin"to"Release"an"Astroid"."$Money$"st@le"tigers"and"Agent"plastic"got"mad"."$Money$"sic","man","t0tally"rad"."Sistrs"Rms"titAnic";"Civic"Ace"in"{sC@m}{hic}{vicis}..{cats}sAc}((@))((@)){{{>>{{{{{{}}}}}}}}}\\\\\\\;;;(@)((@)()),,;;

My strategy is for all the short ones to get cracked and nobody bothers with this considering how long it is... Also I suppose I should note that this is a full program, not just a function.


how to find n'th number in the decimal expansion of a proper fraction?

GolfScript 17

10\?@abs*\abs/10%

GolfScript can't handle real numbers well, but multiplying by powers of 10 is equivalent.

Here's an explanation and walkthrough with sample input, for any of you who are new to GolfScript, since I think this is a nice simple introduction:

59 -17 5
10\ #Place 10 on the stack and then switch the top 2 elements
-> 59 -17 10 5
? #Exponentiate
-> 59 -17 100000
@ #Rotate top 3 elements
-> -17 100000 59
abs #Take absolute value of top element
-> -17 100000 59
* #Multiply the top 2 elements
-> -17 5900000
\ #Switch top 2 elements
-> 5900000 -17
abs #Take absolute value of top element
-> 5900000 17
/ #Do integer division
-> 347058
10% #Place 10 on the stack and then take modulo
-> 8


Pyth, 36 bytes

lu{smmXd,0@dk)fq1.a.DR4,Txd0UdGQ]U16

Demonstration. Test harness.

lu{smmXd,0@dk)fq1.a.DR4,Txd0UdGQ]U16

                 .a.DR4,Txd0            Find the Euclidean distance between the
                                        present location of 0 and a given location.
              fq1           Ud          Filter over all locations on that distance
                                        equaling 1.
     mXd,0@dk)                          Map each such location to the grid with 0
                                        and the value at that location swapped.
  {sm                         G         Map all unique grids possible after n-1
                                        steps to all unique grids after n steps.
 u                             Q]U16    Repeat <input> times, starting with the
                                        initial grid.
l                                       Print the length of the resulting set.


Answer-Chaining - Positive divisors of a number

Answer 20, Brain-Flak, 11

I would like to just take the time to thank everyone that has helped contribute to this goal:

Riley, 20 bytes
LegionMammal, 15 bytes
ETHproductions, 11 bytes
Lynn, 1 byte

The following users were not able to contribute bytes directly but did help in other ways:

Mistah Figgins
DJMcMayhem
feersum

Thanks everyone for making this possible!

"qd:A(),(;{A\%!},pe#&f!0pv'%QTS|Q@░┼_¥f::+!vUGw
)((({})<>)){((({}[()]<n=int(input({})(<>))><>)<{i=1div=wvhile(({})){({}[()])<>}{}}{}<>([{}()]{})><>)<>{ifn%i==g00div.append(<{}<>{}<>>i)i=i+1}{}printdiv)}
#R
{}T:.eX╜R;j`;╜0%Y*`M∩\"ILD¹s%_Ï,

Try it online!


Jelly, 5 4 bytes

ṗṬML

This is an O(kn) brute force solution.

Try it online!

How it works

ṗṬML  Main link. Left argument: k. Right argument: n.

ṗ     Cartesian power; yield the list of all n-tuples over {1, ..., k}.
      Each tuple represents a (not necessarily surjective) function from
      {1, ..., n} to {1, ..., k}.
 Ṭ    Apply the "untruth" atom to each tuple.
      Ṭ maps a list of indices to an array with 1's at those indices, and exactly
      as many zeroes as needed to build the array.
      Examples:
           [1, 2, 3, 3, 3] -> [1, 1, 1]
           [1, 3, 5]       -> [1, 0, 1, 0, 1]
           [2, 6, 2, 4, 4] -> [0, 1, 0, 1, 0, 1]
  M   Yield all indices of maximal elements, i.e., all indices of [1] * k.
   L  Take the length.


Compression algorithms

You can apply LZMA compression to the string.
Many languages support it.

Run-length encoding

You can use processing instructions such as [char][number] (e.g. b12).
This compression algorithm is used here: https://codegolf.stackexchange.com/a/20589/10920

Further reading: http://en.wikipedia.org/wiki/Run-length_encoding

Integer packing

You can use arrays of integers to store small shapes such as:

// This is an invader!
// (SE line height makes it looks awful)
// ~158 characters

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

Each space will be translated into a 0.
Each sharp will be translated into a 1.

// ~58 characters
// Saved ~100 bytes!
[
  196656,  49344,   262128,  999228,
  4194303, 3407859, 3342387, 62400
]

Each bit is then read using bitwise operator &.

The above algorithm could be improved by using a bigger integer base:

// ~44 characters
// Integers are in base 36.
// Use `_` as a separator (or a line break).
"47qo_122o_5m9c_lf0c_2hwcf_211ir_1zn03_1c5c"


Converting a number from Zeckendorf Representation to Decimal

Taxi, 1987 1927 bytes

-60 bytes due to the realization that linebreaks are optional.

Go to Post Office:w 1 l 1 r 1 l.Pickup a passenger going to Chop Suey.Go to Chop Suey:n 1 r 1 l 4 r 1 l.[B]Switch to plan C if no one is waiting.Pickup a passenger going to Cyclone.Go to Cyclone:n 1 l 3 l.Pickup a passenger going to Narrow Path Park.Pickup a passenger going to Sunny Skies Park.Go to Zoom Zoom:n.Go to Sunny Skies Park:w 2 l.Go to Narrow Path Park:n 1 r 1 r 1 l 1 r.Go to Chop Suey:e 1 r 1 l 1 r.Switch to plan B.[C]1 is waiting at Starchild Numerology.1 is waiting at Starchild Numerology.Go to Starchild Numerology:n 1 l 3 l 3 l 2 r.Pickup a passenger going to Addition Alley.Pickup a passenger going to Cyclone.Go to Cyclone:w 1 r 4 l.[D]Pickup a passenger going to Addition Alley.Pickup a passenger going to Cyclone.Go to Addition Alley:n 2 r 1 r.Go to Cyclone:n 1 l 1 l.Pickup a passenger going to Multiplication Station.Go to Zoom Zoom:n.Go to Narrow Path Park:w 1 l 1 l 1 r.Switch to plan E if no one is waiting.Pickup a passenger going to The Babelfishery.Go to The Babelfishery:e 1 r.Pickup a passenger going to Multiplication Station.Go to Multiplication Station:n 1 r 2 l.Pickup a passenger going to Joyless Park.Go to Joyless Park:n 2 l 1 r 1 r.Go to Addition Alley:w 1 r 2 l 1 l.Pickup a passenger going to Cyclone.Go to Cyclone:n 1 l 1 l.Pickup a passenger going to Addition Alley.Switch to plan D.[E]Go to Addition Alley:w 1 l 1 r 1 l.Pickup a passenger going to Riverview Bridge.Go to Riverview Bridge:n 1 r.Go to Joyless Park:e 1 r 2 l.Pickup a passenger going to Addition Alley.[F]Switch to plan G if no one is waiting.Pickup a passenger going to Addition Alley.Go to Fueler Up:w 1 l.Go to Addition Alley:n 3 l 1 l.Pickup a passenger going to Addition Alley.Go to Joyless Park:n 1 r 1 r 2 l.Switch to plan F.[G]Go to Addition Alley:w 1 r 2 l 1 l.Pickup a passenger going to The Babelfishery.Go to The Babelfishery:n 1 r 1 r.Pickup a passenger going to Post Office.Go to Post Office:n 1 l 1 r.

Try it online!

Because I don't return to the Taxi Garage at the end, my boss fires me, so it exits with an error.


Array-of-array string conversion to and from matrix

Japt, 30 bytes
F=_OxZ}G=_Oo'[+Zm_'[+Z+']} +']

Try it online!
Function F converts a string into a matrix, and function G converts a matrix into a string.


Python 3 2, 125 119 81 bytes

lambda e,f,s,t,n=2*'A G# G F# F E Eb D C# C B Bb'.split():n[n.index(e)+2*f+s+3*t]

Try it online!

Saved a lot of bytes thanks to Jonathan Allan.

My original solution (in Python 3):

n=2*'Bb B C C# D Eb E F F# G G# A'.split()
e,f,s,t=str(input()).split()
print(n[n.index(e,9)-2*int(f)-int(s)-3*int(t)])

Try it online!

Saved 6 bytes thanks to @HyperNeutrino.

Explanation

First, I make an array of notes, but doubled in length so I don't have to worry about looping around from Bb to A.

Then, I take input in the following format (for example):

Bb 1 0 1

I then find the index of the starting note using n.index(e,9) (the 9 is there to make sure that I start well in the middle of the (doubled) list. I calculate the desired offset with the expression:

2*int(f) - int(s) - 3*int(t)

Where f is the first valve, s is the second valve, and t is the third.

Finally, it simply prints the note found in the list by subtracting the offset from the starting index.


Align a horizontally-aligned, right-angled ASCII shape along a diagonal

Python 2 - 285

import sys
l=list(sys.stdin)
L=len;R=range
r=L(l)-2
c=L(max(l,key=L))-2
k=r+c+1
d=int(l[-1])/90%4
a=d/2;x=a^d%2
z=1-x*2;t=1-a*2
m=[k*[' ']for i in R(k)]
for i in R(r+1):
 for j in R(L(l[i])-1):m[a*c+x*r+z*i+t*j][r-a*r+x*c-t*i+z*j]='  \/'[ord(l[i][j])/40^d%2]
for s in m:print''.join(s)

I strongly suspect it can be golfed more, tips are welcome.

Examples:

% python r45.py <<< "||
_____
45"
 /
\ /
 \
  \
   \
    \

% python r45.py <<< " _
| |_
|___|
-45"

    / \
 / \ /
    /
 \ /
  \

If the 2nd one looks misaligned, that's because of some issues with the question:
First, the underscore is at the bottom of the character "cell", while the pipe, slash and backslash are all in the middle. It would be fairer to use a dash (-) instead of underscore.
Second, with the rotation of the heart in the question, you couldn't represent it in any reasonable way if the first line was ___ (3 underscores) instead of
 _, as the 1st and 3rd underscore would be "capping" the pipes in the 2nd line.

Here's a better heart:

% python r45.py <<< " _
| |
|  _
|   |
 ___
-45"

 / \ / \

 \     /
  \   /
   \ /


Python 2, 39 bytes

f=lambda a,d,p=1:p%256and-~f(a+d,d,p*a)

Try it online!

Tracks the product p of the arithmetic progression until it's divisible by 256.


Python, 63 bytes

lambda m,n:["df%d/du%%d "%i*n%tuple(range(n))for i in range(m)]

For m=3,n=2, outputs

['df0/du0 df0/du1 ', 'df1/du0 df1/du1 ', 'df2/du0 df2/du1 ']

The string formatting is 1 byte shorter than the more obvious

lambda m,n:[["df%d/du"%i+`j`for j in range(n)]for i in range(m)]


Python 2, 149 bytes

a=input()
l=len(a)
n=p=0
for i in range(l):
 for j in range(l-1,i+3,-1):
  if(j>p)>(.15<sum(a[i:j+1])/(j+1.-i)+a[i]+a[j]<2.85):n+=1;p=j;break
print n

The first loop scans across the array from left to right. Each bit, indexed by i, is checked to see if it could be the first bit in a maximal phase.

This is done by the inner loop, which scans from right to left. If the subarray between i and j is a phase, we increase the counter and move on. Otherwise, we keep going until the subarray becomes too small or j reaches the end of the previous maximal phase.

1 1 1 0 0 0 0 1 0 0 1 0 1 1 1 1 1 0 1 0
i ->                               <- j

Example:

$ python phase.py
[1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0]
3