C (gcc), 1288 1212 1188 1171 1146 bytes

#define P printf(
#define A case
#define B break
#define L(i,e,t,f,s)for(o=i;o e;){strcpy(l[o t],l[o f]);c[o t]=c[s o];}
#define R(m,o){return b<1|b>m?m o:b;}
#define N(f)sscanf(f,"%d,%d",&i,&j)||sscanf(f,",%d",&j)
r,i,j,o,z,c[999],*C,x=1,y=1;char a[999],l[999][999],(*L)[999];D(){L(r,>y,,-1,--)r++?strcpy(l[o],l[o-1]+--x),c[o-1]=x,l[o-1][x]=0:0;c[y++]=strlen(l[o]);x=1;}U(){strcat(*L,l[y]);*C=strlen(*L);L(y+1,<r,-1,,++)--r;*l[r]=c[r]=0;}X(b)R(c[y-1],+1)Y(b)R(r,)main(){for(;;){z=i=y;L=l+--z;C=c+z;j=x;!r||y/r&&x>*C?P"end> "):P"%d,%d> ",y,x);scanf("%[^\n]%*c",a)?a[2]*=!!a[1],N(a)?y=Y(i+(i<0|*a=='+')*y),x=X(j+(j<0||strchr(a+1,'+'))*x):0:(*a=D(),scanf("%*c"));switch(*a){A'e':y=r;x=c[r-1]+1;B;A'b':y=1;x=1;B;A'L':for(o=y-4;++o<y+2;)o<0^o<r&&P"%c%s\n",o^z?' ':'>',l[o]);for(o=x+1;--o;)P" ");P"^\n");B;A'l':puts(*L);B;A'p':i=1;j=0;N(a+2);for(o=Y(i)-1;o<Y(j);++o)puts(l[o]);B;A'A':y=r++;strcpy(l[y],a+2);x=c[y]=strlen(a+2);++x;++y;B;A'i':D();--y;x=X(0);A'r':strcpy(*L+x-1,a+2);*C=strlen(*L);x=1;++y>r&&++r;B;A'I':o=strlen(a+2);memmove(*L+x+o-1,*L+x-1,*C-x+1);*C+=o;memcpy(*L+x-1,a+2,o);x+=o;B;A'd':**L?**L=*C=0,x=1:U();y=y>r?r:y;B;A'j':y<r&&U();}}}

Demo

First time trying to do something like this, so there are probably some missed opportunities for making it smaller. (Thanks Jerry Jeremiah for pointing out some)

Here's a (slightly) more readable version:

// often used functions/keywords:
#define P printf(
#define A case
#define B break

// loops for copying rows upwards/downwards are similar -> macro
#define L(i,e,t,f,s)for(o=i;o e;){strcpy(l[o t],l[o f]);c[o t]=c[s o];}

// range check for rows/columns is similar -> macro
#define R(m,o){return b<1|b>m?m o:b;}

// checking for numerical input is needed twice (move and print command):
#define N(f)sscanf(f,"%d,%d",&i,&j)||sscanf(f,",%d",&j)

// room for 999 rows with each 999 cols (not specified, should be enough)
// also declare "current line pointers" (*L for data, *C for line length),
// an input buffer (a) and scratch variables
r,i,j,o,z,c[999],*C,x=1,y=1;char a[999],l[999][999],(*L)[999];

// move rows down from current cursor position
D()
{
    L(r,>y,,-1,--)
    r++?strcpy(l[o],l[o-1]+--x),c[o-1]=x,l[o-1][x]=0:0;
    c[y++]=strlen(l[o]);
    x=1;
}

// move rows up, appending uppermost to current line
U()
{
    strcat(*L,l[y]);
    *C=strlen(*L);
    L(y+1,<r,-1,,++)
    --r;
    *l[r]=c[r]=0;
}

// normalize positions, treat 0 as max
X(b)R(c[y-1],+1)
Y(b)R(r,)

main()
{
    for(;;)
    {
        // initialize z as current line index, the current line pointers,
        // i and j for default values of positioning
        z=i=y;L=l+--z;C=c+z;j=x;

        // prompt:
        !r||y/r&&x>*C?P"end> "):P"%d,%d> ",y,x);

        // read a line of input (using scanf so we don't need an include)
        scanf("%[^\n]%*c",a)?

        // no command arguments -> make check easier:
        a[2]*=!!a[1],

        // numerical input -> have move command:
        // calculate new coordinates, checking for "relative"
        N(a)?y=Y(i+(i<0|*a=='+')*y),x=X(j+(j<0||strchr(a+1,'+'))*x):0:

        // check for empty input, read single newline and perform <return> command:
        (*a=D(),scanf("%*c"));

        switch(*a)
        {
            A'e':y=r;x=c[r-1]+1;B;
            A'b':y=1;x=1;B;
            A'L':for(o=y-4;++o<y+2;)o<0^o<r&&P"%c%s\n",o^z?' ':'>',l[o]);for(o=x+1;--o;)P" ");P"^\n");B;
            A'l':puts(*L);B;
            A'p':i=1;j=0;N(a+2);for(o=Y(i)-1;o<Y(j);++o)puts(l[o]);B;
            A'A':y=r++;strcpy(l[y],a+2);x=c[y]=strlen(a+2);++x;++y;B;
            A'i':D();--y;x=X(0);
            // Commands i and r are very similar -> fall through from i to r
            // after moving rows down and setting position at end of line:
            A'r':strcpy(*L+x-1,a+2);*C=strlen(*L);x=1;++y>r&&++r;B;
            A'I':o=strlen(a+2);memmove(*L+x+o-1,*L+x-1,*C-x+1);*C+=o;memcpy(*L+x-1,a+2,o);x+=o;B;
            A'd':**L?**L=*C=0,x=1:U();y=y>r?r:y;B;
            A'j':y<r&&U();
        }
    }
}

This challenge leaves quite a lot of corner cases to explore -- I guess I fixed all bugs by now, but if somebody finds one more, please comment. Regarding the revisions, I removed byte counts for earlier versions that contained subtle bugs.


Charcoal, 26 24 bytes

ＦθＦ⎇﹪℅ι²buzz¦fizz⎇№αι↥κκ

Try it online! Originally inspired by @CarlosAlejo. Edit: Saved 2 bytes by looping over the letters of fizz/buzz instead of assigning to a temporary. Explanation:

Ｆθ          Loop over the input (i = loop variable)
  Ｆ         Choose and loop over the word (k = loop variable)
   ⎇        Ternary
    ﹪℅ι²    If i has an odd ASCII code
    buzz
    fizz
            Print (implicit)
  ⎇         Ternary
   №αι      If i is an uppercase letter
    ↥κ      Uppercase(k)
     κ      k


05AB1E, 7 bytes

þSDg×+O

Try it online!

Explanation

þSDg×+O Implicit input
þ       Keep digits
 S      Get chars
  D     Duplicate
   g    Length
    ×   Repeat string(s)
     +  Add (implicit input added to all elements)
      O Sum


Pyth, 44 39 bytes

&!eJsM._smm^.j)x"NESW"hdstd:z".\d+"1{IJ

Test suite.


Python 2 + requests, 198 191 bytes

from requests import*
def f(c):
 for i in range(24):
	u='http://'+c+`i/3`*3+'.'+'cnooermtg'[i%3::3]
	try:a=get(u,allow_redirects=0).status_code
	except:a=404
	if a/100==3:a='200 R'
	print u,a

Sample output for a:

http://a000.com 404
http://a000.net 404
http://a000.org 404
http://a111.com 200
...
http://a666.org 502
http://a777.com 403
http://a777.net 200 R
http://a777.org 200


Jelly,  18 16  15 bytes
Assumes self-connections may be any weight (i.e. they are not necessarily only either \$0\$ or the equal weight).
Jœcṗ2EÐḟœị³EƲ€S

Try it online!
the two subsets of size 3 being ACE and BCD
With n=2 all 10 subsets of size 2 work as its symmetric.
How?
Jœcṗ2EÐḟœị³EƲ€S - Link: list of lists of integers, M; integer, n
J               - range of length of M = [1,2,3,...,length(M)]
 œc             - Combinations of length n e.g. [[1,2,3],[1,2,4],[1,3,4],[2,3,4]]
             €  - for each:
            Ʋ   -   last four links as a monad:
   ṗ2           -     Cartesian power with 2
      Ðḟ        -     discard if:
     E          -       all-equal (i.e. diagonal co-ordinates like [3,3])
        œị      -     multi-dimensional index into:
          ³     -       program's 3rd argument (1st input), M
           E    -     all equal?
              S - sum


Create a programming language that only appears to be unusable

Shuffle (written in C++), Cracked! by Martin

Edit Martin cracked it. To see his solution, click the link. My solution has also been added.

Edit Fixed print-d command to be able to handle both registers and stacks. As this is a debugging command which is not permitted in a solution, this should not affect anyone using the previous version of the interpreter

I'm still new to this, so if there is something wrong with my answer or my interpreter, please let me know. Please ask for clarification if something is not clear.

I don't imagine that this will be too terribly difficult, but hopefully it will provide some sort of challenge. What makes shuffle fairly unusable is that it will only print when things are in their proper place.

-->Basics:

There are 24 Stacks, we call them stack1, ... stack24. These stacks live in a list. At the beginning of any program, these stacks have zero pushed and they start in their proper place, i.e. stacki in the ith position in the list (Note that we will index beginning from 1, unlike C++). During a course of a program, the order of the stacks within the list will shift. This is important for reasons that will be explained when I discuss the commands.

There are 5 registers available for use. They are named Alberto, Gertrude, Hans, Leopold, ShabbySam. Each of these is set to zero at the beginning of a program.

So, at the onset of any program, there are 24 stacks, each has its number matching its index in the stack list. Every stack has exactly one zero on top. Each of the five registers is initialized to zero.

-->Commands and Syntax:

There are 13 commands (+1 debugging command) that are available in Shuffle. They are as follows

cinpush this command takes no arguments. It waits for command line input in the fashion described in the question (other input will lead to unspecified/undefined results). It then splits the input string into integers, e.g. 101011100 --> 1,1,3. For each input received, it does the following: (1) permutes the list of stacks based on the value. Let the integer value in question be called a. If a is less than 10 it does permutation u. If a is between 9 and 30 (noninclusive) it does permutation d. Otherwise it does permutation r. (2) It then pushes a onto the the stack which is first in the list. Note that I do not mean stack1 (although it may be the case that stack1 is first in the list). The permutations are defined below.  Since cinpush is the only way to get user input, it must appear in any solution.
mov value register The mov command is basically variable assignment. It assigns value to register. value can take several forms: it can be (1) an integer, e.g. 47 (2) the name of a different register, e.g. Hans (3) the index of a stack followed by 's', e.g. 4s. Note that this is the index in the list, not the number of the stack. As such, the number should not exceed 24.

Some mov examples:

mov 4s Hans
mov Hans ShabbySam
mov 9999 Gertrude

movfs index register This stands for 'move from stack'. It is similar to the mov command. It exists so that you may access a stack indexed by a register. For example, if earlier you set Hans equal to 4 ( mov 4 Hans) Then you may use movfs Hans Gertrude to set Gertrude equal to the top of stack 4. This type of behavior is not accessible simply using mov.
inc register increases register value by 1.
dec register decreases register value by 1.
compg value value register This stands for 'compare greater'. It sets the register equal to the greater of the two values. value can be an integer, a register, or a stack index followed by 's', as above.
compl value value register 'compare lesser' same as above, except takes the smaller value.
gte value1 value2 register Checks if value1 >= value2 then puts the Boolean value (as 1 or 0 ) into register.
POP!! index pops off the top of the stack indexed by index in the stack list.
jmp label jumps unconditionally to the label label. This is a good time to talk about labels. A label is word followed by ':'. The interpreter pre-parses for labels, so you are able to jump forward to labels as well as back.
jz value label jumps to label if value is zero.
jnz value label jumps to label if value is nonzero.

Examples of labels and jumping:

this_is_my_label:
     jmp this_is_my_label

mov 10 Hans
jnz Hans infinite_loop

infinite_loop:
     jmp infinite_loop

"shuffle" permutation Here is the shuffle command. This allows you to permute the list of stacks. There are three valid permutations that can be used as arguments, l, f, and b.
print register This checks if all the stacks are in their initial positions, i.e stacki is at index i in the stack list. If this is the case, it prints the value at register in unary. Otherwise, it prints a nasty error. As you can see, to output anything, the stacks must all be in the correct places.
done! this tells the program to quit with no error. If the program ends without done!, it will print to the console the number on top of each stack followed by the stack's number. The order that the stacks are printed is the order they appear in the stack list. If a stack is empty, it will be omitted. This behavior is for debugging purposes and may not be used in a solution.
print-d value this prints the value of the stack, register, or integer given (to access stack i, pass is as argument, as explained above). This is a debugging tool and not part of the language, as such it is not permitted in an solution.

--> Here is the interpreter code

All the parsing happens in the main function. This is where you will find it parsing for specific commands.

#include<fstream>
#include<iostream>
#include<string>
#include<stack>
#include<cmath>

using namespace std;

class superStack: public stack<long> {
    private:
        int m_place;
    public:
        static int s_index;

        superStack() {
            m_place = s_index;
            s_index++;
        }

        int place() {
            return m_place;
        }
};
int superStack::s_index=1;

superStack  stack1,stack2,stack3,stack4,stack5,stack6,stack7,stack8,stack9,stack10,stack11, \
            stack12,stack13,stack14,stack15,stack16,stack17,stack18,stack19,stack20,stack21,stack22,stack23,stack24;

superStack* stackptrs[]=    { \
                        &stack1,&stack2,&stack3,&stack4,&stack5,&stack6,&stack7,&stack8,&stack9,&stack10,&stack11, \
                        &stack12,&stack13,&stack14,&stack15,&stack16,&stack17,&stack18,&stack19,&stack20,&stack21,&stack22,&stack23,&stack24 \
                        };

long Gertrude=0;
long Hans=0;
long Alberto=0;
long ShabbySam=0;
long Leopold=0;

void SWAP( int i, int j) {    // 0 < i,j < 25

    i--;
    j--;

    superStack* tempptr = stackptrs[i];
    stackptrs[i]=stackptrs[j];
    stackptrs[j] = tempptr;

}

void u() {
    int list[3][4] = {
                        {1,9,6,13},
                        {2,10,5,14},
                        {17,19,20,18},
                    };

    for(int i=0;i<3;i++) {
        for(int j=1;j<4;j++) {
            SWAP( list[i][0], list[i][j] );
        }
    }
}
void d() {
    int list[3][4] = {
                        {3,11,8,15},
                        {4,12,7,16},
                        {22,24,23,21},
                    };

    for(int i=0;i<3;i++) {
        for(int j=1;j<4;j++) {
            SWAP( list[i][0], list[i][j] );
        }
    }
}
void r() {
    int list[3][4] = {
                        {2,17,8,24},
                        {4,18,6,23},
                        {9,10,12,11},
                    };

    for(int i=0;i<3;i++) {
        for(int j=1;j<4;j++) {
            SWAP( list[i][0], list[i][j] );
        }
    }
}
void l() {
    int list[3][4] = {
                        {1,19,7,22},
                        {3,20,5,21},
                        {14,13,15,16},
                    };

    for(int i=0;i<3;i++) {
        for(int j=1;j<4;j++) {
            SWAP( list[i][0], list[i][j] );
        }
    }
}
void f() {
    int list[3][4] = {
                        {20,9,24,16},
                        {18,11,22,14},
                        {1,2,4,3},
                    };

    for(int i=0;i<3;i++) {
        for(int j=1;j<4;j++) {
            SWAP( list[i][0], list[i][j] );
        }
    }
}
void b() {
    int list[3][4] = {
                        {19,10,23,15},
                        {17,12,21,13},
                        {5,6,8,7},
                    };

    for(int i=0;i<3;i++) {
        for(int j=1;j<4;j++) {
            SWAP( list[i][0], list[i][j] );
        }
    }
}

void splitpush(string input) {
    long value=0;

    for(long i=0;i<input.size();i++) {

        if(input[i]=='1'){
            value++;
        }
        else if(input[i]=='0' && value!=0 ) {
            if(value<10) {
                u();
            }
            else if (value<30) {
                d();

            }
            else {
                r();
            }
            (*stackptrs[0]).push(value);
            value=0;

        }
        else {
            break;
        }

    }

}

long strToInt(string str) { // IF STRING HAS NON DIGITS, YOU WILL GET GARBAGE, BUT NO ERROR
    long j=str.size()-1;
    long value = 0;
    for(long i=0;i<str.size();i++) {
        long x = str[i]-48;

        value+=x*floor( pow(10,j) );
        j--;
    }
    return value;
}

bool isEmpty(superStack stk) {
    if( stk.size()>0){return false; }
    else {return true;}

}

long getValue(string str) {
    if(str=="ShabbySam") {
        return ShabbySam;
    }
    else if(str=="Hans") {
        return Hans;
    }
    else if(str=="Gertrude") {
        return Gertrude;
    }
    else if(str=="Alberto") {
        return Alberto;
    }
    else if(str=="Leopold") {
        return Leopold;
    }
    else if(str[ str.size()-1 ]=='s'){
        str.pop_back();

        long index = strToInt(str)-1;

        if( !isEmpty( (*stackptrs[index]) ) ) {
            return (*stackptrs[index]).top();
        }
        else {
            cerr<<"Bad Expression or Empty Stack";

        }
    }
    else {
        return strToInt(str);
    }

}

void printUnary(long i) {
    while(i>0) {
        cout<<1;
        i--;
    }
}

int main(int argc, char**argv) {

    if(argc<2){std::cerr<<"No input file given"; return 1;}
    ifstream inf(argv[1]);
    if(!inf){std::cerr<<"File open failed";return 1;}

    for(int i=0;i<24;i++) {
        (*stackptrs[i]).push(0);         // Pre push a zero on every stack
    }

    string labels[20];
    unsigned labelPoints[20];
    int index=0;

    string str;
    while(inf) { //  parse for labels
        inf>>str;
        //cout<<inf.tellg()<<" ";
        if(inf) {
            if(str[str.size()-1]==':') {
                str.pop_back();
                bool alreadyExists = false;
                for(int i=0; i<index;i++){
                    if(labels[i] == str ) { alreadyExists=true;}
                }
                if(!alreadyExists) {
                    labels[index]=str;
                    labelPoints[index]= inf.tellg();
                    index++;
                }
            }

        }

    }
    inf.clear();
    inf.seekg(0,inf.beg);

    while(inf) { // parse for other commands
        inf>>str;

        if(inf) {

            if(str=="cinpush") {
                string input;
                cin>>input;
                splitpush(input);
            }

            else if(str=="mov") {
                inf>>str;
                long value = getValue(str);

                inf>>str;
                if(str=="Gertrude"){Gertrude=value;}
                else if(str=="Hans"){Hans=value;}
                else if(str=="ShabbySam"){ShabbySam=value;}
                else if(str=="Alberto"){Alberto=value;}
                else if(str=="Leopold"){Leopold=value;}
                else {cerr<<"Bad register name. ";}

            }

            else if(str=="movfs") {
                inf>>str;
                long index = getValue(str);
                if(!isEmpty( *stackptrs[index-1] )) {
                    inf>>str;
                    long value = (*stackptrs[index-1]).top();
                    if(str=="Gertrude"){Gertrude=value;}
                    else if(str=="Hans"){Hans=value;}
                    else if(str=="ShabbySam"){ShabbySam=value;}
                    else if(str=="Alberto"){Alberto=value;}
                    else if(str=="Leopold"){Leopold=value;}
                    else {cerr<<"Bad register name.";}
                }
                else {
                    cerr<<"Empty Stack";
                }

            }

            else if(str=="inc") {
                inf>>str;
                if(str=="Gertrude"){Gertrude++;}
                else if(str=="Hans"){Hans++;}
                else if(str=="ShabbySam"){ShabbySam++;}
                else if(str=="Alberto"){Alberto++;}
                else if(str=="Leopold"){Leopold++;}
                else {cerr<<"Bad register name. ";}
            }
            else if(str=="dec") {
                inf>>str;
                if(str=="Gertrude"){Gertrude--;}
                else if(str=="Hans"){Hans--;}
                else if(str=="ShabbySam"){ShabbySam--;}
                else if(str=="Alberto"){Alberto--;}
                else if(str=="Leopold"){Leopold--;}
                else {cerr<<"Bad register name. ";}
            }

            else if(str=="compg") {
                inf>>str;
                long value1 = getValue(str);
                inf>>str;
                long value2 = getValue(str);
                inf>>str;
                long larger;
                if(value1>value2){larger = value1;}
                else {larger = value2;}

                if(str=="Gertrude"){Gertrude=larger;}
                else if(str=="Hans"){Hans=larger;}
                else if(str=="ShabbySam"){ShabbySam=larger;}
                else if(str=="Alberto"){Alberto=larger;}
                else if(str=="Leopold"){Leopold=larger;}
                else {cerr<<"Bad register name. ";}

            }
            else if(str=="compl") {
                inf>>str;
                long value1 = getValue(str);
                inf>>str;
                long value2 = getValue(str);
                inf>>str;
                long larger; //LARGER IS REALLY SMALLER HERE
                if(value1>value2){larger = value2;}
                else {larger = value1;}

                if(str=="Gertrude"){Gertrude=larger;}
                else if(str=="Hans"){Hans=larger;}
                else if(str=="ShabbySam"){ShabbySam=larger;}
                else if(str=="Alberto"){Alberto=larger;}
                else if(str=="Leopold"){Leopold=larger;}
                else {cerr<<"Bad register name. ";}

            }

            else if(str=="gte") {
                inf>>str;
                long value1= getValue(str);
                inf>>str;
                long value2= getValue(str);
                inf>>str;
                bool torf = value1 >= value2;

                if(str=="Gertrude"){Gertrude=torf;}
                else if(str=="Hans"){Hans=torf;}
                else if(str=="ShabbySam"){ShabbySam=torf;}
                else if(str=="Alberto"){Alberto=torf;}
                else if(str=="Leopold"){Leopold=torf;}
                else {cerr<<"Bad register name. ";}

            }

            else if(str=="lte") {
                inf>>str;
                long value1= getValue(str);
                inf>>str;
                long value2= getValue(str);
                inf>>str;
                bool torf = value1 <= value2;

                if(str=="Gertrude"){Gertrude=torf;}
                else if(str=="Hans"){Hans=torf;}
                else if(str=="ShabbySam"){ShabbySam=torf;}
                else if(str=="Alberto"){Alberto=torf;}
                else if(str=="Leopold"){Leopold=torf;}
                else {cerr<<"Bad register name. ";}

            }

            else if(str=="POP!!") {
                inf>>str;
                long index = getValue(str);
                index--; //because we (C++ and this interpreter) index differently
                if(!isEmpty( *stackptrs[index] )) {
                    (*stackptrs[index]).pop();
                }
                else {cerr<<"Can't POP!! from empty stack";}

            }

            else if(str=="push"){cerr<<" You can't. ";}

            /*
            else if(str[str.size()-1]==':') {
                str.pop_back();
                bool alreadyExists = false;
                for(int i=0; i<index;i++){
                    if(labels[i] == str ) { alreadyExists=true;}
                }
                if(!alreadyExists) {
                    labels[index]=str;
                    labelPoints[index]= inf.tellg();
                    index++;
                }
            }*/

            else if(str=="jmp") {
                inf>>str;
                for(int i=0;i<index;i++) {
                    if( labels[i]==str) {
                        inf.seekg( labelPoints[i], ios::beg);
                    }
                }
            }
            else if(str=="jz") {
                inf>>str;
                long value = getValue(str);

                if(value==0) {
                    inf>>str;
                    for(int i=0;i<index;i++) {
                        if( labels[i]==str) {
                            inf.seekg( labelPoints[i], ios::beg);
                        }
                    }
                }
            }

            else if(str=="jnz") {
                inf>>str;
                long value = getValue(str);

                if(value!=0) {
                    inf>>str;
                    for(int i=0;i<index;i++) {
                        if( labels[i]==str) {
                            inf.seekg( labelPoints[i], ios::beg);
                        }
                    }
                }
            }

            else if(str== "\"shuffle\"") {
                inf>>str;
                if(str=="l"){ l(); }
                else if(str=="f"){ f(); }
                else if(str=="b"){ b(); }
                else {cerr<<"Bad shuffle parameter";}

            }

            else if(str=="print") {

                for(int i=0;i<24;i++) {

                    if( (i+1) != (*stackptrs[i]).place() ) {
                        cerr<< "Sorry, your stacks are in the wrong place! You can't print unless you put them back! Exiting. ";
                        return 1;
                    }

                }
                inf>>str;
                if(str=="Gertrude"){printUnary(Gertrude);}
                else if(str=="Hans"){printUnary(Hans);}
                else if(str=="ShabbySam"){printUnary(ShabbySam);}
                else if(str=="Alberto"){printUnary(Alberto);}
                else if(str=="Leopold"){printUnary(Leopold);}
                else {cerr<<"Bad register name. ";}

            }

            else if(str=="done!") {return 0;}

            else if(str=="print-d" ){
                inf>>str;
                long value = getValue(str);
                cout<<str;
              }
        }

    }

    /*for(int i=1;i<25;i++) {
        (*(stackptrs[i-1])).push(i);
    }

    u();d();r();l();f();b();
    */

    cout<<"\n";
    for(int i=1;i<25;i++) {
        if( (*(stackptrs[i-1])).size()>0 ) {
            cout<<(*(stackptrs[i-1])).top()<<" "<<(*(stackptrs[i-1])).place()<<"\n";
            (*(stackptrs[i-1])).pop();
        }
    }
    /*
    for (int i=0;i<index;i++) {
        cout<<labels[i]<<": "<<labelPoints[i]<<"\n";
    }*/

    return 1;
}

-->Permutations
The permutations permute the elements of the stack list in the following fashion:

Where  means that

(These also appear in the interpreter code. If there is a discrepancy, the interpreter is correct.)

-->Simple Example

These two simple programs print the numbers from 24 to 1 (in unary) with no whitespace.

mov 24 Hans
start:
    print Hans
    dec Hans
    jnz Hans start
done!

or

mov 24 Hans start: print Hans dec Hans jnz Hans start done!

They are the same program.

Explanation and Solution:

Martin has a good explanation in his answer as well.

As Martin figured out, this language was inspired by the pocket cube (aka 2x2 Rubik's cube). The 24 stacks are like the 24 individual squares on the cube. The permutations are the basic moves allowed: up, down, right, left, front, back.

The main struggle here is that when values are pushed, only three moves are used: up, down, and right. However, you do not have access to these moves when "shuffling" the stacks. You have only the other three moves.

As it turns out, both sets of three moves actually span the entire group (i.e. are generators), so the problem is solvable. This means that you can actually solve any 2x2 Rubik's cube only using 3 of the moves.

All that is left to do is figure out how to undo the up, down, and right moves using the other three. To this end, I employed a computer algebra system called GAP.

After undoing the permutations, finding the third largest number is fairly trivial.

cinpush
main:
    mov 1s ShabbySam
    POP!! 1
    jmp compare
    continue:
        gte 0 ShabbySam Leopold
        jnz Leopold end
        gte ShabbySam 9 Leopold
        jz Leopold uinverse
        gte ShabbySam 29 Leopold
        jz Leopold dinverse
        jnz Leopold rinverse
compare:
    gte ShabbySam Alberto Leopold
    jz Leopold skip
    mov Gertrude Hans
    mov Alberto Gertrude
    mov ShabbySam Alberto
    jmp continue
    skip:
        gte ShabbySam Gertrude Leopold
        jz Leopold skip_2
        mov Gertrude Hans
        mov ShabbySam Gertrude
        jmp continue
    skip_2:
        gte ShabbySam Hans Leopold
        jz Leopold continue
        mov ShabbySam Hans
        jmp continue
uinverse:
    "shuffle" f
    "shuffle" f
    "shuffle" f
    "shuffle" l
    "shuffle" b
    "shuffle" l
    "shuffle" b
    "shuffle" b
    "shuffle" b
    "shuffle" l
    "shuffle" l
    "shuffle" l
    "shuffle" b
    "shuffle" b
    "shuffle" b
    "shuffle" l
    "shuffle" l
    "shuffle" l
    "shuffle" f
    jmp main
dinverse:
    "shuffle" f
    "shuffle" b
    "shuffle" l
    "shuffle" b
    "shuffle" b
    "shuffle" b
    "shuffle" f
    "shuffle" f
    "shuffle" f
    jmp main
rinverse:
    "shuffle" b "shuffle" l "shuffle" f "shuffle" l "shuffle" b
    "shuffle" f "shuffle" f "shuffle" f "shuffle" b
    "shuffle" l "shuffle" l "shuffle" l
    "shuffle" b "shuffle" b "shuffle" b
    "shuffle" f "shuffle" f "shuffle" f
    "shuffle" l "shuffle" f "shuffle" l "shuffle" f
    "shuffle" l "shuffle" f "shuffle" f "shuffle" f
    "shuffle" l "shuffle" l "shuffle" l
    "shuffle" f "shuffle" l "shuffle" l
    "shuffle" f "shuffle" f "shuffle" f
    "shuffle" l "shuffle" l "shuffle" l
    "shuffle" l "shuffle" l "shuffle" l "shuffle" f
    "shuffle" l "shuffle" l "shuffle" l
    "shuffle" f "shuffle" f "shuffle" f
    "shuffle" l "shuffle" l "shuffle" l
    "shuffle" f "shuffle" f "shuffle" f
    "shuffle" l "shuffle" l "shuffle" l
    "shuffle" f "shuffle" f "shuffle" f
    "shuffle" l "shuffle" l "shuffle" l
    "shuffle" f "shuffle" f "shuffle" f
    "shuffle" l "shuffle" f "shuffle" l "shuffle" f "shuffle" l "shuffle" f
    "shuffle" l "shuffle" l "shuffle" l
    jmp main
end:
    print Hans
    done!


Give a permutation with no two consecutive integers next to each other

Jelly, 3 2 bytes

ḂÞ

Sorts the integers in [1, ..., n] by their LSB.

Try it online!


The Government has a Limited Supply of Walls

Mathematica, 257 253 chars
d="city.txt"~Import~"Table";g=EdgeAdd[#,∞<->Tr@#&/@Position[VertexDegree@#,2|3]]&@GridGraph@d[[1,{2,1}]];{o,x,s}=Tr/@Position[Join@@d[[2;;]],#]&/@{"o","x","."};Catch@Do[If[Min[GraphDistance[VertexDelete[g,x⋃w],∞,#]&/@o]==∞,Throw@Length@w],{w,Subsets@s}]

Input is read from "city.txt".
Explanation:
Mathematica has many functions to deal with graphs.
First, I read the data from "city.txt".
d="city.txt"~Import~"Table";

Then I construct a grid graph with 'm'*'n' vertices (GridGraph@d[[1,{2,1}]]), and add to it a "vertex at infinity" which is connected to every vertex on the "edges" of the graph. This vertex is where the water flow from.
g=EdgeAdd[#,∞<->Tr@#&/@Position[VertexDegree@#,2|3]]&@GridGraph@d[[1,{2,1}]];

And o, x and s denote the positions of "o", "x" and "." respectively.
{o,x,s}=Tr/@Position[Join@@d[[2;;]],#]&/@{"o","x","."};

Then for any subset w of s (the subsets are sorted by length), I delete the vertices in x and w from g (VertexDelete[g,x⋃w]), and find the length of the shortest path from the "vertex at infinity" to the encampment o. If the length is infinity, then the encampment will be safe. So the length of the first such w is the minimum number of walls required to protect an encampment.
Catch@Do[If[Min[GraphDistance[VertexDelete[g,x⋃w],∞,#]&/@o]==∞,Throw@Length@w],{w,Subsets@s}]


Compute the minimum \$a(n)>a(n-1)\$ such that \$a(1)+a(2)+\dots+a(n)\$ is prime (OEIS A051935)

Brachylog, 13 bytes

~l.<₁a₀ᵇ+ᵐṗᵐ∧

Try it online!

Output is the list of first n terms of the sequence.

?~l.<₁a₀ᵇ+ᵐṗᵐ∧    Full code (? at beginning is implicit)

?~l.              Output is a list whose length is the input
    <₁            Output is an increasing list
      a₀ᵇ+ᵐ       And the cumulative sum of the output
           ṗᵐ     Consists only of prime numbers
             ∧    No further constraints on output

Explanation for a₀ᵇ+ᵐ:
a₀ᵇ               Get the list of all prefixes of the list
                  Is returned in increasing order of length
                  For eg. [2, 3, 6, 8] -> [[2], [2, 3], [2, 3, 6], [2, 3, 6, 8]]
   +ᵐ             Sum each inner list  -> [2, 5, 11, 19]


Python 2, 166 bytes

def Q(x,n,a=0):
 e=n/2
 while pow(a*a-x,e,n)<2:a+=1
 w=a*a-x;b=r=a;c=s=1
 while e:
    if e%2:r,s=(r*b+s*c*w)%n,r*c+s*b
    b,c=(b*b+c*c*w)%n,2*b*c;e/=2
 return min(r,-r%n)


Java 10, 120 113 112 109 107 102 92 bytes

n->{var r="|";for(var c='1';n++>0;c+=c>64?1:c*4%22%9,n/=3)r=n%3<1?c+r:n%3>1?r+c:r;return r;}

-3 bytes by using part of the trick of @Arnauld's JavaScript (ES6) answer,
changing i=0 and i++<1?49:i<3?51:i<4?57:i+61 to i=4 and ++i>9?i+55:i>8?57:++i+43.
-6 bytes thanks to @Arnauld directly, by getting rid of i.
-10 bytes thanks to @ceilingcat.
Order of output: Highest-to-lowest, |-delimiter, lowest-to-highest.
Explanation:
Try it online.
n->{              // Method with integer parameter and String return-type
  var r="|";      //  Result-String, starting at the delimiter "|"
  for(var c='1';  //  Character, starting at '1'
      n++>0       //  Loop as long as `n` is larger than 0
                  //  Increasing it by 1 with `n++` at the start of every iteration
      ;           //    After every iteration:
       c+=        //     Change character `c` to:
          c>64?   //      If the current `c` is an uppercase letter:
               1  //       Simply go to the next letter using `c+=1`
              :   //      Else:
               c*4%22%9,
                  //       Change '1' to '3', '3' to '9', or '9' to 'A'
       n/=3)      //     Integer-divide `n` by 3
     r=           //   Change the result to:
       n%3<1?     //    If `n` modulo-3 is 0:
        c+r       //     Prepend the character to the result
       :n%3>1?    //    Else-if `n` modulo-3 is 2:
        r+c       //     Append the character to the result
       :          //    Else (`n` modulo-3 is 1):
        r;        //     Leave `r` unchanged
   return r;}     //  Return the result-String


Find out how Abstractly Capacious™ someone is!

Python 2, 61 bytes

def f(a,i):r=a*9+i*4;print r/36,(r+44-i*4)/9-a,(r+39-a*9)/4-i

Try it online!


Hello world! with limited character repetition

Ruby (1.9+)

Since this is a popularity contest let's try to not use ANY of the characters from 'Hello world!' while still using other characters only a maximum of two times:

puts("S\107VsbG8gV29ybGQhCg".unpack(?m))

It's 40 chars btw.

Bash

And this one uses unicode magic.

Notes:

While the orignal characters appear elsewhere (unlike the ruby example), the printed string contains only non-ascii characters.
Two from the three spaces are actually tabs, so there are no utf-8 characters that appear more than 2 times
As binary some of the octets do appear more than 2 times, hopefully that's not against the rules. I'm trying to resolve them though.

Code:

echo ' ¡'|iconv -t  asCIi//TRANSLIT

For those who don't have a proper font installed it looks like this:

Here is the hexdump:

00000000  65 63 68 6f 20 27 f0 9d  93 97 f0 9d 90 9e f0 9d  |echo '..........|
00000010  91 99 f0 9d 92 8d f0 9d  93 b8 e2 80 8a f0 9d 93  |................|
00000020  a6 f0 9d 97 88 f0 9d 96  97 f0 9d 96 91 f0 9d 98  |................|
00000030  a5 c2 a1 27 7c 69 63 6f  6e 76 09 2d 74 09 61 73  |...'|iconv.-t.as|
00000040  43 49 69 2f 2f 54 52 41  4e 53 4c 49 54 0a        |CIi//TRANSLIT.|
0000004e

You have to run it on a machine where the default charset is utf-8. I tried on an OSX10.8 using iTerm2 with the following environment:

PHP 5.4

This uses zLib: (unfortunately it does uses the characters e and o)

<?=gzuncompress('x▒▒H▒▒▒W(▒/▒IQ▒!qh');

Hexdump:

00000000  3c 3f 3d 67 7a 75 6e 63  6f 6d 70 72 65 73 73 28  |<?=gzuncompress(|
00000010  27 78 9c f3 48 cd c9 c9  57 28 cf 2f ca 49 51 e4  |'x..H...W(./.IQ.|
00000020  02 00 21 71 04 68 27 29  3b                       |..!q.h');|
00000029

+1

Here is the ruby 2.0 code I used to test for duplicates:

d=ARGF.read
p [d.split(//),d.unpack('C*')].map{|x|x.inject(Hash.new(0)){|i,s|i[s]+=1;i}.select{|k,v|v>2}}


Python 2, 80 bytes

s=[]
exec'x=q=1\nwhile(x in s)+q%1:x+=1;q=(v+x)**.5\nv=q;s+=x,;'*input()
print s

Try it online!


We had a question once which only failed on Sundays

Bash + coreutils, 15 14 bytes

`date|grep Su`

Try it online!


Python, 54 bytes

f=lambda l,*p:l and l[:p<=l[:1]>=l[1:2]]+f(l[1:],l[0])

Try it online!

I/O is with tuples rather than lists.

Python, 57 bytes

f=lambda l,p=0:l and l[:[p]<=l[:1]>=l[1:2]]+f(l[1:],l[0])

Try it online!

Alt 57:

f=lambda l,p=0:l and l[l<[max(p,*l[:2])]:1]+f(l[1:],l[0])


Help my maniacal wife decorate our Christmas tree


Head, Shoulders, Knees and Toes, Knees and Toes

JavaScript (ES6), 91 88 87 bytes

n=>'knees,toes,head,shoulders,eyes,ears,mouth,nose'.split`,`[(245890>>(n%22&~1))&6|n%2]

How it works

We have 4 distinct pairs of words that always appear together: 'head' is always followed by 'shoulders', 'knees' is always followed by 'toes', etc.

Therefore, we can use the following index:

00: [ 'knees', 'toes' ]
01: [ 'head', 'shoulders' ]
10: [ 'eyes', 'ears' ]
11: [ 'mouth', 'nose' ]

And compress the whole sequence (in reverse order) into the following binary mask:

00 00 01 11 10 00 00 01 00 00 01

We use [ 'knees', 'toes' ] as the first pair to get as many leading zeros as possible.

We pad this sequence with an extra 0 so that the extracted value is premultiplied by 2, which leads to:

0b00000111100000010000010 = 245890

Hence the final formula for the correct word:

(245890 >> (n % 22 & ~1)) & 6 | n % 2

Test cases

let f =

n=>'knees,toes,head,shoulders,eyes,ears,mouth,nose'.split`,`[(245890>>(n%22&~1))&6|n%2]

console.log(f(0));    // head
console.log(f(1));    // shoulders
console.log(f(7));    // shoulders
console.log(f(13));   // ears
console.log(f(20));   // knees
console.log(f(35));   // ears
console.log(f(37));   // nose
console.log(f(98));   // knees
console.log(f(543));  // nose
console.log(f(1000)); // knees


Python, 1219 Bytes

I didn't spend very much time/effort trying to golf this, but I might improve it if other answers start popping up.  I use A* search with an admissible heuristic, guaranteeing optimality.  I am pretty sure (although I haven't bothered to confirm) that the heuristic is also consistent, meaning that it is O(dynamic programming).

The program reads in four lines from STDIN in the format you have specified, and prints the result to STDOUT, also in the format you specified.

from heapq import heappush,heappop
from itertools import combinations
N,E,S,W=range(4)
L="L"
R="R"
T="S"
d=[{L:E,R:W,T:S},{L:S,R:N,T:W},{L:W,R:E,T:N},{L:N,R:S,T:E}]
b=set([(N,S,W,E),(N,S,E,W),(S,N,W,E),(S,N,E,W),(E,W,N,E),(N,S,W,N),(S,N,E,S),(W,E,S,W)])
for x in list(b):b.add(x[2:]+x[:2])
def v(*a):return a[1]!=a[3] and a not in b
i=lambda:raw_input()+'\n'
i=map(lambda l:map(lambda e:("NESW"[l[0]],d[l[0]][e]), l[1]),enumerate((i()+i()+i()+i()).split()))
q=[]
heappush(q,(0,[],i))
while q:
    h,a,n=heappop(q)
    m=sum(map(bool,n))
    if m==0:
        print "\n".join(a)
        break
    for r in range(4,0,-1):
        f=False
        for c in combinations(range(4),r):
            l=True
            for i in c:
                if not n[i]:
                    l=False
                    break
            if not l:continue
            l=True
            for x,y in combinations(c,2):
                if not v(x,n[x][0][1],y,n[y][0][1]):
                    l = False
                    break
            if l==False:continue
            f=True
            e=list(n)
            for i in c:e[i]=e[i][1:]
            heappush(q,(m-r+min(map(len,e)),a+["".join([n[x][0][0] for x in c])],e))
        if f:break

Example usage:

$ time echo "RRLLSSRLSLLSSLRSLR\nRLSLRLSLSSRLRLRRLLSSRLR\nRLSLRLRRLSSLSLLRLSSL\nLLLRRRSSRSLRSSSSLLRRRR" | python 4way.py
NES
NEW
NSW
NS
NS
ESW
NS
NES
NEW
NS
NES
NSW
NS
NS
NSW
NW
NS
NS
NS
EW
ES
SW
EW
EW
SW
ES
EW
EW
EW
EW
E
EW
EW
EW
EW
EW
E
EW
echo   0.00s user 0.00s system 38% cpu 0.002 total
python 4way.py  0.02s user 0.01s system 90% cpu 0.030 total


Write a mathematical function whose result is "hello world"

I'll do better than just printing it, I'll print it infinitely many times!

The rational number

1767707668033969 / 3656158440062975

returns the following base-36 expansion:

0.helloworldhelloworldhelloworldhelloworldhelloworld...

Try it out! (Wolfram Alpha)

Or, if you want a more subliminal message, try:

2399843759207982499621172523113947162810942763812298565948669
/ 1357602166130257152481187563160405662935023615

Which returns (again in base 36):

helloworld.helpimtrappedinanumberfactoryhelpimtrappedinanumberfactoryhelpimtrappedinanumberfactory...

If your program worked with only integers, you'd never see the fractional part.


Pyth, 27 - 50 = -23 bytes

Lj\*m+ed?+\^jyhd`HthdkrPb8

This defines a recursive function y. Try it online: Demonstration

The output is valid LaTeX code, so I claim the bonus. The call y66430125 returns the string 3^{2^{2}*3}*5^{3}, which renders to

Quite proud for finding a way to print the curly brackets without using curly brackets in my code.

Explanation:

L                            define a function y(b): return ...
                       Pb       prime factorization of b
                      r  8      run-length-encoded, gives pairs of (exponent, prime)
    m                           map each pair d (exponent, prime) to:
      ed                          prime
     +                            +
             yhd                    recursive call
            j   `H                  join repr(H) by ^
                                      H is preinitialized with an empty dictionary
                                      so the repr(H) gives the string "{}"
                                      and join inserts the prime-factorization
                                      of the exponent between the chars of "{}"

         +\^                        add "^" at the beginning
        ?         thd               if exponent - 1 != 0 else
                     k              "" (empty string)
 j\*                            join by "*"


Ruby, 29 bytes
->s{!s[/[^aeiou]{3}|[jqxz]/]}

Hopefully I've got this right - it's my first time programming in Ruby. I actually did all my testing in Python, but import re was far too long for me.
This is an anonymous function which takes in a string and outputs true/false accordingly. It uses a regex which looks for one of the following two things:

Three consonants in a row
Contains one of jqxz

If either of these are present, we classify the input as not a word.
The function matches 2030 words (incorrectly failing on 206) and fails on 1782 non-words (incorrectly matching 454), for a total of 660 misclassifications. Tested on ideone.
Thanks to @MartinBüttner for the Ruby help. Martin also points out that a full program takes the same number of bytes:
p !gets[/[^aeiou]{3}|[jqxz]/]

Also thanks to user20150203 for simplifying the regex.

Ruby, 1586 1488 1349 1288 1203 bytes
For a bonus, here's a function with a much longer regex:
->s{!s[/[^aeiouyhs]{3}|[^aeiouy]{4}|q[^u]|^x|^[bdf][^aeioulry]|^[cgkprtwy][mfdsbktjgxpc]|^a[aoz]|^e[hf]|^i[ea]|^o[ecy]|^u[^ltnspgr]|[bdgktyz][cgmpw]$|[fhpvx][^aieoflnrsty]$|eh$|i[iyh]|[wkybp]z|[dghz]t|[fjzsv]y.|h[ns].|ae.|y.?[yifj]|[ejo]..[iuw]|[inv]..[gpuvz]|[eu].[jqwx]|[vyz][^t][fhmpqy]|i[^ae][fjqrv]|[ospen].?j|[ceg][iuy][ghkoux]|[bcpx]f|[hnuy]w|[ghnw]b|[txz]n|[jk]r|.[fjuyz]u|[hnt]ia|lsy|.p.o|.l.l|.tas|zal|f.p|eeb|wei|.sc.|.pl|yat|hov|hab|aug|v.re|aba|ohu|ned|s.dd|uc$|nux|oo$|dgo|lix|wua|v.o|vo$|ryo|wue|dk|oic|yol|.tr|yrb|oba|ruh|c.ls|idd|chn|doy|ekh|tk|lke|asl|cir|eez|asc|uil|iou|m..p|awt|irp|zaa|td|swk|ors|phe|aro|yps|q.e|ati|ibt|e.mo|we.y|p.de|ley|eq|tui|e..g|sps|akh|dny|swr|iul|.t.t|.tao|rcy|.p.y|idi|j.o|.kl|oms|ogi|jat|.lis|mye|uza|rsi|.ala|ibo|ipi|yaa|eun|ruy|wog|mm$|oex|koi|uyn|.hid|osc|ofe|w.op|auc|uzy|yme|aab|slm|oza|.fi|bys|z.e|nse|faf|l.h|f.va|nay|hag|opo|lal|seck|z.b|kt|agl|epo|roch|ix.|pys|oez|h.zi|nan|jor|c.ey|dui|ry.d|.sn|sek|w.no|iaz|ieb|irb|tz.|ilz|oib|cd|bye|ded|f.b|if$|mig|kue|ki.w|yew|dab|kh.|grs|no.t|cs.|.n.m|iea|y.na|vev|eag|el[uz]|eo[dkr]|e[hlsu]e|e[dho]l|eov|e[adp]y|r[grt]u|yn[klo]|.[^ilv].v|s[bdgqrz]|m[dfghrz]|[vpcwx]{2}|^[hjlmnvz][^aeiouy]|^[drw]l|l[hnr]/]}

I wanted to show that regex can still beat compression, so this one classifies every given case correctly. The regex itself is a bit like exponential decay — the first bits match a lot of non-words, then every bit after matches fewer and fewer until I gave up and just concatenated the rest (about 200 or so) at the end. Some of the ones that were left looked surprisingly like real words (such as chia which is a word).
I threw the regex at my regex golf cleaner which I wrote for another challenge — it golfed about 300 bytes before I had to try shuffling things around manually. There's still a fair bit to be golfed though.


Enhanced Builder Pattern, verified at compile time

How about something like this, in Haskell:

{-# LANGUAGE GADTs, DataKinds, KindSignatures, StandaloneDeriving #-}
module Builder ( Human', Human, mkHuman, unHuman
               , withName, withAge, withMoney
               ) where

data Optional (b :: Bool) (a :: *) where
    Missing :: Optional False a
    Present :: a -> Optional True a
deriving instance (Show a) => Show (Optional b a)

data Human' b1 b2 b3 where
    MkHuman :: Optional b1 String -> Optional b2 Int -> Optional b3 Double -> Human' b1 b2 b3
deriving instance Show (Human' b1 b2 b3)

type Human = Human' True True True

mkHuman :: Human' False False False
mkHuman = MkHuman Missing Missing Missing

unHuman :: Human -> (String, Int, Double)
unHuman (MkHuman (Present name) (Present age) (Present money)) = (name, age, money)

withName :: String -> Human' False b2 b3 -> Human' True b2 b3
withName name (MkHuman _ age money) = MkHuman (Present name) age money

withAge :: Int -> Human' b1 False b3 -> Human' b1 True b3
withAge age (MkHuman name _ money) = MkHuman name (Present age) money

withMoney :: Double -> Human' b1 b2 False -> Human' b1 b2 True
withMoney money (MkHuman name age _) = MkHuman name age (Present money)

Example usage:

h1, h2 :: Human
h1 = withName "n" . withMoney 0.15 . withAge 1 $ mkHuman
h2 = withName "n" . withAge 1 . withMoney 0.15 $ mkHuman

takesCareOfTheName :: Human' False b2 b3 -> Human' True b2 b3
takesCareOfTheName = withName "John"

-- This doesn't typecheck
h3 :: Human
h3 = withName "newName" h1

-- Neither does this
h4 :: Human
h4 = withName "n" . withAge 1 $ mkHuman


Pyth, 13 bytes
?hu]+HG_UQYQY

Try it here.
                 Implicit:
                 Q = eval(input())
                 Y = []
?           QY   If Q = 0, print Y
 h               else, print the first element of
  u     _UQY     the reduce, where Y is the initial value, over the list
                 reversed(range(Q))
   ]+HG          The reduce function: The list containing H prepended onto G.
                 The new number is inserted into the accumulated list,
                 then the resultant list is wrapped in another list.


Calculate the Kronecker sum of two matrices

CJam, 40 39 38 bytes

9Yb2/q~f{.{_,,_ff=?}:ffff*::.+:~}:..+p

Input format is a list containing A and B as 2D lists, e.g.

[[[1 2] [3 4]] [[5 10] [7 9]]]

Output format is a single CJam-style 2D list.

Test suite. (With more readable output format.)

Explanation

This code is an exercise in compound (or infix) operators. These are generally useful for array manipulation, but this challenge exacerbated the need for them. Here is a quick overview:

f expects a list and something else on the stack and maps the following binary operator over the list, passing in the other element as the second argument. E.g. [1 2 3] 2 f* and 2 [1 2 3] f* both give [2 4 6]. If both elements are lists, the first one is mapped over and the second one is used to curry the binary operator.
: has two uses: if the operator following it is unary, this is a simple map. E.g. [1 0 -1 4 -3] :z is [1 0 1 4 3], where z gets the modulus of a number. If the operator following it is binary, this will fold the operator instead. E.g. [1 2 3 4] :+ is 10.
. vectorises a binary operator. It expects two lists as arguments and applies the operator to corresponding pairs. E.g. [1 2 3] [5 7 11] .* gives [5 14 33].

Note that : itself is always a unary operator, whereas f and . themselves are always binary operators. These can be arbitrarily nested (provided they have the right arities). And that's what we'll do...

9Yb      e# Push the binary representation of 9, i.e. [1 0 0 1].
2/       e# Split into pairs, i.e. [[1 0] [0 1]]. We'll use these to indicate
         e# which of the two inputs we turn into an identity matrix.
q~       e# Read and evaluate input, [A B].
f{       e# This block is mapped over the [[1 0] [0 1]] list, also pushing
         e# [A B] onto the stack for each iteration.
  .{     e#   The stack has either [1 0] [A B] or [0 1] [A B]. We apply this
         e#   block to corresponding pairs, e.g. 1 A and 0 B.
    _,   e#     Duplicate the matrix and get its length/height N.
    ,_   e#     Turn into a range [0 1 ... N-1] and duplicate it.
    ff=  e#     Double f on two lists is an interesting idiom to compute an
         e#     outer product: the first f means that we map over the first list
         e#     with the second list as an additional parameter. That means for
         e#     the remaining operator the two arguments are a single integer
         e#     and a list. The second f then maps over the second list, passing
         e#     in the the number from the outer map as the first parameter.
         e#     That means the operator following ff is applied to every possible
         e#     pair of values in the two lists, neatly laid out in a 2D list.
         e#     The operator we're applying is an equality check, which is 1
         e#     only along the diagonal and 0 everywhere else. That is, we've
         e#     created an NxN identity matrix.
    ?    e#     Depending on whether the integer we've got along with the matrix
         e#     is 0 or 1, either pick the original matrix or the identity.
  }
         e#   At this point, the stack contains either [A Ib] or [Ia B].
         e#   Note that A, B, Ia and Ib are all 2D matrices.
         e#   We now want to compute the Kronecker product of this pair.
  :ffff* e#   The ffff* is the important step for the Kronecker product (but
         e#   not the whole story). It's an operator which takes two matrices
         e#   and replaces each cell of the first matrix with the second matrix
         e#   multiplied by that cell (so yeah, we'll end up with a 4D list of
         e#   matrices nested inside a matrix).
         e#   The leading : is a fold operation, but it's a bit of a degenerate
         e#   fold operation that is only used to apply the following binary operator
         e#   to the two elements of a list.
         e#   Now the ffff* works essentially the same as the ff= above, but
         e#   we have to deal with two more dimensions now. The first ff maps
         e#   over the cells of the first matrix, passing in the second matrix
         e#   as an additional argument. The second ff then maps over the second
         e#   matrix, passing in the cell from the outer map. We multiply them
         e#   with *.
         e#   Just to recap, we've essentially got the Kronecker product on the
         e#   stack now, but it's still a 4D list not a 2D list.
         e#   The four dimensions are:
         e#     1. Columns of the outer matrix.
         e#     2. Rows of the outer matrix.
         e#     3. Columns of the submatrices.
         e#     4. Rows of the submatrices.
         e#   We need to unravel that into a plain 2D matrix.
  ::.+   e#   This joins the rows of submatrices across columns of the outer matrix.
         e#   It might be easiest to read this from the right:
         e#     +    Takes two rows and concatenates them.
         e#     .+   Takes two matrices and concatenates corresponding rows.
         e#     :.+  Takes a list of matrices and folds .+ over them, thereby
         e#          concatenating the corresponding rows of all matrices.
         e#     ::.+ Maps this fold operation over the rows of the outer matrix.
         e#   We're almost done now, we just need to flatten the outer-most level
         e#   in order to get rid of the distinction of rows of the outer matrix.
  :~     e#   We do this by mapping ~ over those rows, which simply unwraps them.
}
         e# Phew: we've now got a list containing the two Kronecker products
         e# on the stack. The rest is easy, just perform pairwise addition.
:..+     e# Again, the : is a degenerate fold which is used to apply a binary
         e# operation to the two list elements. The ..+ then simply vectorises
         e# addition twice, such that we add corresponding cells of the 2D matrices.
p        e# All done, just pretty-print the matrix.


Check If Two or More Variables Are All Equal to Zero in JavaScript

(EDIT: This first part refers to the original phrasing of the question.)

First, (!x&&!y&&!z) returns a boolean, which makes ?true:false entirely redundant. It's basically like using

if (x == true)
  return true;
else if (x == false)
  return false;

instead of return x;.

That gives you

!x&&!y&&!z

(EDIT: The remainder still applies to the new version of the question.)

Now you could apply De Morgan's law. The above is equivalent to

!(x||y||z)

Which is the same length for 3 variables and longer for 2 variables. But for each variable beyond the third, you save one more character!

Lastly, if you know that your variables are numbers, you can also use the bitwise operator, i.e.

!(x|y|z)

If you actually need booleans (which I assume from your snippet), this doesn't work for the & case, because !x&!y&!z will give you an integer. Then again, in JavaScript it's often enough to have truthy or falsy values, in which case, that's a perfectly valid option.

Bonus tip: if you ever want to turn a truthy/falsy value (like a non-zero/zero number) into a boolean, don't use x?true:false either, but use !!x instead. !x is a boolean with the opposite truthiness/falsiness than x, so !!x is true for x truthy  and false for x falsy.


Can you cancel the stackoverflow exception in the following code?

Here, another try:

class Foo
{
    //static Foo foo = new Foo(); // you are not allowed using this approach
    //static readonly Foo foo = new Foo(); // you are not allowed using this approach
    Foo foo = new Foo();
    MWAHAHAHA, THIS LINE GIVES A COMPILE ERROR! NO STACKOVERFLOW EXCEPTION ANYMORE! LOL
}
class Program
{
    static void Main(string[] args)
    {
        new Foo();
    }
}


Solve quadratic equation using only 3 variables and arithmetic

Hybrid of iterative approaches; score: 62

I originally posted an answer which purely used Newton-Raphson; however, in the cases of large b and c this requires a lot of iterations. Consider only the most interesting quadratics: those which have two solutions. If we normalise them to the form x^2 + bx + c = 0 then we can plot the number of iterations required for various approaches as a function of b and c. For example, we can modify the continued fraction route to get the direct approach:

c = -c;
a = b * 0.5;
while (loopCount-- > 0) { // This loop would be unrolled in the final solution
    a = a + b;
    a = c / a;
}
// Roots are a and -c/a

That gives a loop count diagram of

2236...................6322
2224n.................n4222
22236.................63222
22224n...............n42222
222236...............632222
222224m.............m422222
2222236.............6322222
2222224j...........j4222222
22222234P.........P43222222
22222223d.........d32222222
222222222t.......t222222222
2222222225Z.....Z5222222222
22222222219/////91222222222
/////////////./////////////
222222222*********222222222
222222222*********222222222
22222222***********22222222
22222223***********32222222
2222223*************3222222
2222224*************4222222
222223***************322222
222224***************422222
22223*****************32222
22224*****************42222
2223*******************3222
2224*******************4222
223*********************322

where c is negative in the first row and increases downwards, b increases from left to right, * means negative discriminant, / means only one root was within tolerance in 62 iterations, . means no root was within tolerance in 62 iterations, and numbers are in base-62 with digits 0-9a-zA-Z. This is pretty decent for a certain range, but fails completely for another range.

bmarks' original implementation is similar to (but not the same; this is a reimplementation from the continued fraction):

a = b;
while (loopCount-- > 0) {
    a = c / a;
    a = b - a;
}
// Roots are -a, -c/a (which is better than a-b)

with loop count diagram

1117...................7111
1112n.................n2111
11117.................71111
11112n...............n21111
111117...............711111
111112m.............m211111
1111117.............7111111
1111112j...........j2111111
11111115Q.........Q51111111
11111111d.........d11111111
111111113u.......u311111111
1111111116/...../6111111111
1111111111a/////a1111111111
1111111111111.1111111111111
111111111*********111111111
111111111*********111111111
11111111***********11111111
11111112***********21111111
1111111*************1111111
1111112*************2111111
111111***************111111
111113***************311111
11111*****************11111
11113*****************31111
1111*******************1111
1113*******************3111
111*********************111

My naïve N-R was quite bad, but the really interesting thing to note about it is where the worst areas are:

njfdcccccccccccccccccccdfjn
njgcbbbbbbbbbbbbbbbbbbbcgjn
njgc9999999999999999999cgjn
njgc9777777777777777779cgjn
njgc9666666666666666669cgjn
njgc9544444444444444459cgjn
njgc9521111111111111259cgjn
njgc9534444444444444359cgjn
njgc9535555555555555359cgjn
njgc9536777777777776359cgjn
njgc9536888888888886359cgjn
njgc9536899999999986359cgjn
njgc95368aaaaaaaaa86359cgjn
njgc95368aaaaaaaaa86359cgjn
njgc95368*********86359cgjn
njgc95369*********96359cgjn
njgc9536***********6359cgjn
njgc9536***********6359cgjn
njgc953*************359cgjn
njgc954*************459cgjn
njgc95***************59cgjn
njgc94***************49cgjn
njgc9*****************9cgjn
njgc8*****************8cgjn
njgc*******************cgjn
njgb*******************bgjn
njf*********************fjn

So the thing to do is to hybridise. For the areas where it's good, I use the continued fraction; for the rest, I use N-R, but I've done some optimisation: I've experimentally found two cutoffs and three initial values which converge in 5 iterations to a worst-case mixed error abs(value - correct_value) / (1 + abs(correct_value) of 0.000052. (Thanks to Martin Büttner for the idea of doing a case split). The final loop count (mixing the two cases into one diagram) is:

111555555555555555555555111
111233333333333333333332111
111133333333333333333331111
111125555555555555555521111
111115555555555555555511111
111112333333333333333211111
111111333333333333333111111
111111255555555555552111111
111111144444444444441111111
111111112111111111111111111
111111113222222222211111111
111111111333333333111111111
111111111444444444111111111
111111111111111111111111111
111111111*********111111111
111111111*********111111111
11111111***********11111111
11111112***********21111111
1111111*************1111111
1111112*************2111111
111111***************111111
111113***************311111
11111*****************11111
11113*****************31111
1111*******************1111
1113*******************3111
111*********************111

and the code is

solve_quad(&float a, &float b, &float c) {
    float t; // 20 points
    if (a != 0) { // 21
        if (c == 0) {
            // x(x+b) = 0
            b = -b; // 22
            a = 2;
        }
        else {
            // Normalise so that we're solving x^2 + bx + c = 0 and have `a` free to use
            // Hereon, mentions of b and c in comments refer to these normalised values.
            b = b / a; // 22
            c = c / a; // 23

            // Three cases:
            //   b^2 < 4c: negative determinant, no solutions
            //   b^2 < -4c: use Newton-Raphson
            //   Otherwise: use the continued fraction method that bmarks was the first to post

            a = b / 2; // 24
            a = a * a; // 25
            if (a < c) { // 26
                a = 0;
            }
            else {
                t = a + c; // 27
                if (t < 0) { // 28
                    c = a - c; // 29, c holds the determinant

                    // Carefully optimised case split:
                    if (c < 0.05) // 30
                        a = 0.025;
                    else if (c < 250) // 31
                        a = 2;
                    else a = 193;

                    t = c / a; a = a + t; a = a / 2; // 34
                    t = c / a; a = a + t; a = a / 2; // 37
                    t = c / a; a = a + t; a = a / 2; // 40
                    t = c / a; a = a + t; a = a / 2; // 43
                    t = c / a; a = a + t; a = a / 2; // 46

                    // At this point a ~= sqrt(determinant)
                    t = b / 2; // 47
                    a = a + t; // 48
                    t = t * t; // 49
                    c = t - c; // 50
                    // At this point a ~= b/2 + sqrt(determinant) and c holds its original value
                }
                else {
                    a = b;

                    a = c / a; a = b - a; // 52
                    a = c / a; a = b - a; // 54
                    a = c / a; a = b - a; // 56

                    // At this point a ~= b/2 + sqrt(determinant)
                }

                b = -a; // 57
                c = c / b; // 58
                a = 2;
            }
        }
    }
    else {
        // bx + c = 0
        if (b != 0) { // 59
            a = 1;
            c = -c; // 60
            b = c / b; // 61
        }
        else {
            // c = 0
            if (c != 0) a = 0; // 62
            else a = 3;
        }
    }
}


Julia 1.0, 61 bytes

f(n,p,q=1:n-1)=[(x,y,z) for x=q,y=q,z=q if(x^p+y^p)%n==z^p%n]

-1 thanks to Glen O

Try it online!


Map an array of functions to their return values in point-free style

Based on the answer by Rory O'Kane:

  10 tokens: Number.call.bind(String.call)

Try it online!

It is trivial, since Number.call, String.call, Object.call, Function.call, (function () {}).call, Function.prototype.call are all the same.

If Bind Operator Proposal is accepted, this could be simplified to:

  6 tokens: ::Function.call.call

Babel

BTW, if eval is allowed eval("Number.call.bind(String.call)") only use 4 tokens.


Husk, 5 bytes
This prints an infinite list
ΣṖ…İ±

Try it online! or find the first index of your sequence. (Takes a lot of memory for most sequences)
Explanation:
   İ±   Infinite list [1,-1,2,-2,3,-3,4,-4,5,-5...]
  …     Rangify       [1,0,-1,0,1,2,1,0,-1,-2,...]
 Ṗ      Powerset
Σ       Concatenate

In Husk Ṗ behaves nicely for infinite lists. You can see it's behaviour here


Python2.x

import re
try: re.compile("[")
except re.error, e: print e.message.split()[0]

try it


How many unique ways are there to achieve a score in Football?

Mathematica - 42

Length@IntegerPartitions[#,∞,{2,3,6,7,8}]&

Prolog - 140

Never wrote anything in Prolog before, just knew that this problem should be quite nice for it.

p(0,_,[]).
p(N,[H|T],O):- N>=H,p(N,T,O).
p(N,[H|S],[H|T]):- N>=H,M is N-H,p(M,[H|S],T).
f(N,C):- aggregate(count,X^p(N,[2,3,6,7,8],X),C).

?- f(9,C).
C = 4.


Ruby, 405 403 401 400 bytes
A wise man (Jamie Zawinski) once said, "Some people, when confronted with a problem, think 'I know, I'll use regular expressions.' Now they have two problems."
I don't think I fully appreciated that quote until I tried to solve this problem with recursive regex. Initially, the regex cases seemed simple, until I had to deal with the edge cases involving letters adjacent to brackets, and then I knew that I was in hell.
Anyways, run it online here with test cases
->s{s.gsub!(/{(-?\w+)..(-?\w+)(..(\d+))?}/){x,y=$1,$2;a,b,c=[x,y,$4].map &:to_i
$1[/\d/]?0:(a,b=x,y)
k=a<b ?[*a..b]:[*b..a].reverse
?{+0.step(k.size-1,$4?c:1).map{|i|k[i]}*?,+?}}
r=1
t=->x{x[0].gsub(/^{(.*)}$/){$1}.scan(/(({(\g<1>|,)*}|[^,{}]|(?<=,|^)(?=,|$))+)/).map{|i|i=i[0];i[?{]?r[i]:i}.flatten}
r=->x{i=x.scan(/({(\g<1>)*}|[^{} ]+)/).map(&t)
i.shift.product(*i).map &:join}
s.split.map(&r)*' '}

Ungolfed:
->s{
  s.gsub!(/{(-?\w+)..(-?\w+)(..(\d+))?}/){  # Replace all range-type brackets {a..b..c}
    x,y=$1,$2;a,b,c=[x,y,$4].map &:to_i     # Set up int variables
    $1[/\d/]?0:(a,b=x,y)                    # Use int variables for a,b if they're numbers
    k=a<b ?[*a..b]:[*b..a].reverse          # Create an array for the range in the correct direction
    '{'+                                    # Return the next bit surrounded by brackets
      0.step(k.size-1,$4?c:1).map{|i|k[i]   # If c exists, use it as the step size for the array
      }*','                                 # Join with commas
      +'}'
  }
  r=1                                       # Dummy value to forward-declare the parse function `r`
  t=->x{                                    # Function to parse a bracket block
    x=x[0].gsub(/^{(.*)}$/){$1}             # Remove outer brackets if both are present
                                            # x[0] is required because of quirks in the `scan` function
    x=x.scan(/(({(\g<1>|,)*}|[^,{}]|(?<=,|^)(?=,|$))+)/)
                                            # Regex black magic: collect elements of outer bracket
    x.map{|i|i=i[0];i[?{]?r[i]:i}.flatten   # For each element with brackets, run parse function
  }
  r=->x{                                    # Function to parse bracket expansions a{b,c}{d,e}
    i=x.scan(/({(\g<1>)*}|[^{} ]+)/)        # Regex black magic: scan for adjacent sets of brackets
    i=i.map(&t)                             # Map all elements against the bracket parser function `t`
    i.shift.product(*i).map &:join          # Combine the adjacent sets with cartesian product and join them together
  }
  s.split.map(&r)*' '                       # Split on whitespace, parse each bracket collection
                                            #   and re-join with spaces
}


CJam, 33 31

"",AA#b:c~

There are 11300000000950000000034000000011600000001010000000115000000011600000000340000000061000000003300000000420000000058000000010500000000500000000102000000009800000000490000000102000000009800000000490000000098 null bytes between the double quotes.

The code is equivalent to

11300000000950000000034000000011600000001010000000115000000011600000000340000000061000000003300000000420000000058000000010500000000500000000102000000009800000000490000000102000000009800000000490000000098
AA#b:c~

which can be tested online.

How this works

"",  e# Push the length of the string.
AA#  e# Push 10000000000.
b    e# Turn the length into the array of its base-10000000000 digits.
:c   e# Cast each digit to character. This pushes the following:
     e# q_"test"=!*:i2fb1fb1b
~    e# Evaluate the string.

How that works

q_     e# Read all input and push a copy.
"test" e# Push the string "test".
=!*    e# Check for inequality and repeat the string 0 or 1 times.
       e# This replaces input "test" with the empty string.
:i     e# Cast each character to integer
2fb    e# Replace each integer by the array of its base-2 digits.
1fb    e# Replace each array of base-2 digits by the sum of its digits.
1b     e# Add the sums of digits.

This source code has an ecological footprint of 75.


Cheddar, 50 45 42 37 bytes

25|>0=>i->print" "*(i/2|0)+(65+i)@"90

Straightforward, but utilizes cheddar's consise ranging syntax (both numerical and alphabetical)

Try it online!

Explanation

25 |> 0 =>    // Map range [0, 26) (i.e. [25, 0] reversed) over....
   i ->
     print    // Prints in it's own line...
     " " * (i/2 |0) +     // Number of spaces is floor(n/2).
                          // `|0` for flooring is hack from JS
     (65 + i) @" 90       // Char code range is this

65 is char code for A and 90 for A


Say Hello to the Pioneers of Computer Science

CJam, 230 117 115 114 113 110 107 106 bytes * 13 = 1378

23)3*c11(2#)c111(((c3*))))22 2*c32c23 3*c3))$(113))c1$)))2$)2$(32c3)))$(3)$))1($)1($)3))$)1($)1$(12$(((33c

Test it here.

I chose Edsger Dijkstra, born 1930, which gives me c#2&$1>b()* 3 (whom I really just chose because he was the first one I found whose name yielded useful characters for CJam; I've checked a dozen names since and none looked as promising).

The code basically just builds the ASCII codes using 1, 2, 3, *, # (exponentiation) and (, ) (decrement, increment) and converts them to a character with c. To save some characters I can sometimes copy an earlier character with $ (0$ copies the top stack element, 1$ copies the second-to-top stack element and so on).

Here is the breakdown of the code into characters (this is also runnable):

23)3*c    "(23+1)*3 -> 72 -> H";
11(2#)c   "(11-1)^2+1 -> 101 -> e";
111(((c   "111-3 -> 108 -> l";
3*)       "Turn l into string lll and split off the third l.";
)))       "l+3 -> o";
22 2*c    "22*2 -> 44 -> ,";
32c       "32 -> Space";
23 3*c    "23*3 -> 69 -> E";
3))$(     "e-1 -> d";
113))c    "113+2 -> 115 -> s";
1$)))     "d+3 -> g";
2$)       "d+1 -> e";
2$(       "s+1 -> r";
32c       "32 -> Space";
3)))$(    "E-1 -> D";
3)$))     "g+2 -> i";
1($)      "i+1 -> j";
1($)      "j+1 -> k";
3))$)     "r+1 -> s";
1($)      "s+1 -> t";
1$(       "s-1 -> r";
12$(((    "d-3 -> a";
33c       "33 -> !";


Brain-Flak, 685, 155, 151, 137 bytes

(())({<{}({}()<(()()()())>)({}(<>))<>{(({})){({}[()])<>}{}}{}<>
([{}()]{})(({})){{}({}[()])(<()>)}{}(<>)<>{{}<>{}({}<>)}{}(<>[]<>)>()}<>)

Try it online!

136 bytes of code, plus one byte for -a. One indexed.

530 bytes golfed off! That's probably the largest golf I've ever done.

14 bytes saved thanks to Riley!

This abuses a formula of the opening/closing parenthesis: if you take the ASCII values, increment it by one, and take modulo of 4, the openers (({[<) will always get 0 or 1, whereas the closers ()}]>) will always get 2 or 3.

Explanation:

#Push 1
(())

#While true
({<

    #Pop stack height
    {}

    #Compute (TOS + 1) % 4
    ({}()<(()()()())>)({}(<>))<>{(({})){({}[()])<>}{}}{}<>([{}()]{})

    #Decrement if positive
    (({})){{}({}[()])(<()>)}{}

    #Push 0 onto alternate
    (<>)

    #Toggle back
    <>

    #Pop two zeros from alternate if closer
    {{}<>{}({}<>)}{}

    #Push height of alternate stack
    (<>[]<>)

#Make each time through evaluate to 1
>()

#Endwhile
}

#Push the number of loops onto the offstack
<>)


Wolfram Language (Mathematica), 36 34 33 30 bytes
#-1|#&~Array~#~Tuples~3/.#->0&

Try it online!
Returns a length-\$n^3\$ list of \$\{x|x',y|y',z|z'\}\$ colorings.
Verify with a \$n\times n\times n\$ matrix output.

Explanation:
Consider a cube \$x\$th from the front in some initial configuration. If the frontmost layer of cubes is painted \$1\$, the second \$2\$, etc., so that the color number increments with each shift, the front face of the cube will be painted \$x\$. After one more shift, the cube will be in the backmost layer, so the back face is painted \$x+1\$.
The same logic applies in other dimensions, so we can paint the cube at position \$(x,y,z)\$ with colors \$(x,y,z,x+1,y+1,z+1)\$ (modulo \$n\$).
#-1|#&~Array~#~Tuples~3         (* 3-tuples of {0|1, 1|2, ..., n-1|n} *)
                       /.#->0&  (* and replace n with 0. *)


Is it possible to make a clamp function shorter than a ternary in JS?

20 bytes
For reference, this is the original version without whitespace and without naming the function:

n=>n>0?n<255?n:255:0

Try it online!

19 bytes
We can save a byte by inverting the logic of the ternary tests and using n>>8 to test whether \$n\$ is greater than \$255\$. Because of the bitwise operation, this will however fail for \$n\ge 2^{32}\$.

n=>n<0?0:n>>8?255:n

Try it online!

19 bytes
This one returns \$false\$ instead of \$0\$ but works for \$n\ge 2^{32}\$.

n=>n>255?255:n>0&&n

Try it online!

18 bytes
By combining both versions above, we end up with a function that works for \$256-2^{32}\le n<2^{32}\$ and returns \$false\$ for \$n<0\$.

n=>n>>8?n>0&&255:n

Try it online!
Commented
n =>          // n = input number
  n >> 8 ?    // if n is greater than 255 or n is negative:
    n > 0 &&  //   return false if n is negative
    255       //   or 255 otherwise
  :           // else:
    n         //   return n unchanged

(This is a fixed revision of the code proposed by @ValueInk in the comments.)

17 bytes
We can go a step further by limiting the valid input range to \$-2^{24}< n\le 2^{24}\$:

n=>n>>8?-n>>>24:n

Try it online!
Commented
n =>          // n = input number
  n >> 8 ?    // if n is greater than 255 or n is negative:
    -n >>> 24 //   non-arithmetic right-shift of -n by 24 positions
  :           // else:
    n         //   return n unchanged


JavaScript (ES7), 138 bytes

F=s=>s.replace(/.*#|(\d+)-?(\d+)? ?(\d|\w*)s?/g,(_,a,b,c)=>b?[for(i of Array(b-a--+1))if(++a*c?(b-a)%c<1:!c||a%2==c>'f')a].join`, `:a||'')

F=s=>s.replace(/.*#|(\d+)-?(\d+)? ?(\d|\w*)s?/g,(_,a,b,c)=>b?[for(i of Array(b-a--+1))if(++a*c?(b-a)%c<1:!c||a%2==c>'f')a].join`, `:a||'')
button.onclick=()=>output.innerHTML=F(range.value)
button, textarea {
  display: block;
  width: 100%;
  margin-bottom: 0.5em;
  box-sizing: border-box;
}
<textarea id="range"></textarea>
<button id="button">submit</button>


Pyth, 100 bytes

$import os$KsM$os.urandom(10)$JuuXN@LN,T=+Z+@NT@+CMzKT)bGQU=b256=Z0sCM+K.exCb@=XJ=N@LJ,hk=+Z@Jhk)sNw

This script uses the $ command, which allows executing Python code. To prevent executing malicious code on the server, the this command is disabled in the online compiler. You have to run it with the off-line compiler which you can find here.

The input is in the format:

secret key
5 (number of repeats)
secret message

The program outputs the encrypted string, which might contain unprintable chars. If you want to verify it using the CipherSaber Encryption & Decryption Tool, you can use the following code, which converts the string to a series of hexadecimal digits.

$import os$KsM$os.urandom(10)$JuuXN@LN,T=+Z+@NT@+CMzKT)bGQU=b256=Z0
jdm.[2.HCd`0
sCM+K.exCb@=XJ=N@LJ,hk=+Z@Jhk)sNw

Pyth doesn't support cryptographically secure pseudorandom numbers and importing them from Python costs 25 bytes. A shorter code, which uses Pyth's/Python's normar pseudorandom-number generator and also works in the online compiler is:

KmO=b256TJuuXN@LN,T=+Z+@NT@+CMzKT)bGQUb=Z0sCM+K.exCb@=XJ=N@LJ,hk=+Z@Jhk)sNw

Try it online: returning a string or a series of hexadecimal digits

The code is nothing special. Just a lot of dirty assignments and immediate reuses of computed results and applying twice the list-swap trick.

Explanation:

                                  implicit: z = 1st input (= key string)
                                  Q = 2nd input (number of repetitions)
$import os$KsM$os.urandom(10)$
$import os$                       import Python's os module
              $os.urandom(10)$    create 10 cryptographically secure
                                  pseudo-random bytes
            sM                    convert them to ints
           K                      store them in K

JuuXN@LN,T=+Z+@NT@+CMzKT)bGQU=b256
                             =b256assign b with 256
 u                         QUb    start with G = [0, 1, ..., 255],
                                  evaluate the following expression Q times and
                                  update G with the result each time:
  u                      bG         start with N = G,
                                    for each T in [0, 1, ..., 255] evaluate the
                                    following expression and update N each time:
                   CMz                convert key to list of ints
                  +   K               extend it with K
                 @     T              take the Tth element (modulo length)
              @NT                     take the Tth element of N
             +                        add these two values
           +Z                         add Z (with is initially 0)
          =                           and update Z with the result
        ,T  Z                         make the pair of indices [T, Z]
     @LN                              look-up their values in N
   XN                   )             and switch these two values in N
J                                 assign the result (the key setup) to J

=Z0                               set Z to 0

sCM+K.exCb@=XJ=N@LJ,hk=+Z@Jhk)sNw
                                w read a string from input (message)
     .e                           map each index k, char b in message to:
                         @Jhk       look-up the (k+1)th element in J
                      =+Z           add it to Z and update Z
                   ,hk  Z           make the pair of indices [k+1,Z]
                @LJ                 look-up their values in J
              =N                    assign the result to N
            XJ N             )      swap these values in J
           =                        and update J with the result
          @  J                sN    take the sum(N)th element of J
        Cb                          convert b to int
       x                            bitwise xor of these two elements
   +K                             insert K at the beginning
 CM                               convert each element to char
s                                 sum them (generate a string)
                                  implicitly print


Mathematica, 303

Here with white-space and expanded symbols.
Everything happens in the Switch statement of the EventHandler where I pattern match {pressed key, next letter}.

Might want to replace the Quit with something less sinister before hitting escape:

z := AbsoluteTime[];
f = "a"; y = Dynamic;
DynamicModule[{
  a = f~CharacterRange~"z", c = 1, d = f, r = \[Infinity]},
 EventHandler[
  y@d~InputField~String,
  "KeyDown" :> Switch[
    {CurrentValue@"EventKey", a[[c]]},
    {f ..},
      t = z; c++; d = y@a[[c]],
    {"z" ..},
      t = z - t;
      d = If[t < r,
         r = t; "!!New record!!,",
         ""] ~~ ToString@t;
      c = 1,
    {a_, a_},
      c++,
    {"\[RawEscape]", _}, Quit[],
    _, d = "Failed"; c = 1]]]


Pyth - 118 bytes, score: 154 + 567 + 597 + 620 + 530 + 875 + 1092 = 6630 6623 4653 4435
Now using the factor multiplication algo!
This is a pretty simple algorithm, although slightly better than the above ones. I was planning to use Pyth, but with the current algorithm Python fits<140 bytes.
=zecz"//"=z?>z4}"www."zz=z?Pzqez\/zFNzKCNJ/^K.5 1=d\+pk+holN[?*-KZd>KZ*-ZK\-+\>*dK+++++\>*Jd"[>"*Jd"<-]>"*-K*JJd)\.=ZK

It first strips out the http:// by using split("//") and the www. and / at the end. Then it uses the min function to check which is the best of the the three options that is considered:

Use + or - to update current cell value to desired cell value
Go to new cell and just fill with +'s
Go to new cell and use multiplication to update by doing sqrt(n)*sqrt(n)+remainder since square has minimum perimeter of constant area. http://cydathria.com/bf/bf_ex3.html

I then always put a . to output each char.
A detailed explanation of the new code is coming soon. I kind of half-assed the golfing, especially the stripping of www. and the / at the end but I can't be bothered since I'm 20 bytes under the limit.
This surprisingly works on the ftp:// urls since this is chrome and chrome automatically makes ftp.freebsd.org/pub/FreeBSD/ into ftp://ftp.freebsd.org/pub/FreeBSD/
I plan to next use a dictionary to store the cell values and see if the character was already made in a cell.

Brainfuck Omnibox Extension
That's right! After I saw @BrainSteel's comment, I knew I had to make it. This doesn't take over the entire omnibox, only when you do bf,tab. Also since the omnibox api is weird, it doesn't let me forward the code to the omnibox, I have to handle it myself. So I do my own http:// checking and then set the tab's url.
Since I didn't feel like paying the $5 necessary to put your extension on the webstore, you guys will have to install it manually. Just download the zip from here: https://drive.google.com/file/d/0B0qkKIzGc0QiNzBzVUJjZkRIZ0k/view?usp=sharing, unzip, go into the extensions page in chrome, click dev mode option box on top-right, and load the unpacked extension.
Hope you guys enjoy! :)


Wolfram Language (Mathematica), 88 85 76 bytes

(For[i=k=j=p=0,k<#,i~FreeQ~p||k++,i=i|p;p+=If[p>++j&&FreeQ[i,p-j],-j,j]];p)&

Try it online!

1-indexed.

Explanation

For[

For loop.

i=k=j=p=0

Start with i (\$=\{a_1, a_2, \ldots\}\$), k (number of duplicates found), j (\$=n\$), p(\$=a_{n-1}\$) equal to 0.

k<#

Repeat while k is less than the input.

i=i|p

Append p to i using the head Alternatives (a golfier version of List in this case).

p+=If[p>++j&&FreeQ[i,p-j],-j,j]

Increment j. If p is greater than j (i.e. \$a_{n-1} > n\$) and p-j is not in i (i.e. \$a_{n-1} - n\$ is new), then increment p by -j. Otherwise, increment p by j.

i~FreeQ~p||k++

Each iteration, increment k if p is not in i (the || (= or) short-circuits otherwise).

... ;p

Return p.


C, 28 bytes each
p(i){return"@cefijk"[i]&15;}
b(i){return"@bdghlm"[i]&15;}

This is basically the same as the answer by kirbyfan64sos, but uses a char array instead of integers, and has a dummy first byte so there is no need to subtract 1 from the function parameter.


Convert degrees to one of the 32 points of the compass

Javascript 470 453 438 434 432 421 404

s=String;s.prototype.a=s.prototype.replace;var a=prompt()/11.25,a=a+0.5|0,b,k,c=a,d=c%8,c=c/8|0,e=["north","east","south","west"],f,g,h;f=e[c];g=e[(c+1)%4];h=f==e[0]|f==e[2]?f+g:g+f;b="1;1 by 2;1-C;C by 1;C;C by 2;2-C;2 by 1".split(";")[d].a(1,f).a(2,g).a("C",h);k=b.a(/north/g,"N").a(/east/g,"E").a(/south/g,"S").a(/west/g,"W").a(/by/g,"b").a(/[\s-]/g,"");b=b[0].toUpperCase()+b.slice(1);alert(b+" "+k)

You can copy this code to your console and execute it. It prompts you for the degrees input and outputs the result with alert();

Ungolfed Javascript can be found at this fiddle:
http://jsfiddle.net/AezL3/11


Bash + coreutils + xxd, 73 71 69 bytes

printf \\x%s `xxd -r|xxd -p -s0x$1 -l$[(e=1+0x$2)?e-0x$1:-1]|fold -2`

Expects the hexdump on STDIN and start/end as command-line arguments.

This prints some warnings to STDERR, which is allowed by default.


Jelly,  13  12 bytes

LXṬ,N$X+µẸÐ¿

A monadic Link accepting a list of integers which yields a list of lists of integers.

Try it online!

How?

LXṬ,N$X+µẸÐ¿ - Link: list of integers, p (length d)
          Ð¿ - collect up while...
         Ẹ   - ...condition: any? (when we reach [0]*d this does not hold
        µ    - ...do: the monadic chain - i.e. f(v); initially v=p:
L            -   length (of v) = d
 X           -   random integer (in range [1,d])
  Ṭ          -   untruth     e.g. 4 -> [0,0,0,1]
     $       -   last two links as a monad:
    N        -     negate              [0,0,0,-1]
   ,         -     pair                [[0,0,0,1],[0,0,0,-1]]
      X      -   random choice         [0,0,0,1] OR [0,0,0,-1]
       +     -   add (to v)  e.g. [0,0,0,-1] + [4,2,3,2,5] = [4,2,3,1,5]


Gaia, 25 bytes

ṇ\+†ṅ\⟨)₌¤:~+4ṛ⟨ṛ₌¤⟩ₓ\⟩¦$

Try it online!

Thanks to Kevin Cruijssen for pointing out 2 bugs!

ṇ\				| delete the last character from the input
  +†				| push the input again and concatenate together, so for instance
				| 'abc' 'bc' becomes ['ab' 'bc' 'c']
    ṅ\				| delete the last element
       ⟨       		⟩¦	| for each of the elements, do:
	)₌			| take the first character and push again
	  ¤			| swap
	   :			| dup
	    ~			| swap case
	     +			| concatenate strings
	      4ṛ		| select a random integer from [1..5]
	        ⟨    ⟩ₓ		| and repeat that many times
		 ṛ₌¤		| select a random character from the string
		      \ 	| clean up stack
			   $	| convert to string

Note that 4ṛ is because ṛ is implemented for an integer z as python's random.randint(1,z+1), which returns an integer N such that 1<=N<=z+1.


Reverse a string while maintaining the capitalization in the same places

Python, 71 bytes
lambda s:''.join((z*2).title()[c.isupper()-1]for c,z in zip(s,s[::-1]))

Try it online
-3 bytes from Ruud, plus the inspiration for 2 more.
-4 more bytes from FryAmTheEggman


Jelly, 10 8 bytes

Thanks to Dennis for saving 2 bytes.

^\Ḅ‘^H$B

Input and output are lists of 0s and 1s.

Try it online!

Explanation

The inverse of the Gray code is given by A006068. Using this we don't need to generate a large number of Gray codes to look up the input. One classification of this sequence given on OEIS is this:

a(n) = n XOR [n/2] XOR [n/4] XOR [n/8] ...

Where the [] are floor brackets. Consider the example of 44 whose binary representation is 101100. Dividing by 2 and flooring is just a right-shift, chopping off the least-significant bit. So we're trying to XOR the following numbers

1 0 1 1 0 0
  1 0 1 1 0
    1 0 1 1
      1 0 1
        1 0
          1

Notice that the nth column contains the first n bits. Hence, this formula can be computed trivially on the binary input as the cumulative reduction of XOR over the list (which basically applies XOR to each prefix of the list and gives us a list of the results).

This gives us a simple way to invert the Gray code. Afterwards, we just increment the result and convert it back to the Gray code. For the latter step we use the following definition:

a(n) = n XOR floor(n/2)

Thankfully, Jelly seems to floor the inputs automatically when trying to XOR them. Anyway, here is the code:

^\          Cumulative reduce of XOR over the input.
  Ḅ         Convert binary list to integer.
   ‘        Increment.
    ^H$     XOR with half of itself.
       B    Convert integer to binary list.


R, 54 bytes

function(n)combn(n,2,function(x){z=1:n
z[x]=rev(x)
z})

Try it online!

Returns a matrix where each column is a permutation.

combn(n,k) generates all combinations of size k from the list n, or from 1:n if n is a single integer. It also optionally takes a function FUN to be applied to the resultant combinations. So we write a function that performs the swap and returns the swapped list. The results are then all accumulated into an array, which is in this case 2-dimensional and hence a matrix.


CJam, 72 70 69 bytes

q~:QW=3m*{:,2ff*),)ff+}%{::)1fbQ=}=~W%ee_,S*W'_t@,~'~t.{S\+.*"\/".+N}

Try it online in the CJam interpreter.

Run time and memory usage are O(scary), so the last three test cases should be verified using the Java interpreter (and extra heap space).

Example run

$ time java -Xmx4G -jar cjam-0.6.5.jar bowl.cjam <<< '[42 102]'
\                     /
 \                   /
  \~~~~~~~~~~~~~~~~~/
   \               /
    \             /
     \___________/

real    0m40.669s
user    3m13.100s
sys     0m11.690s

How it works

q~:Q     e# Read from STIDN, evaluate and save the result in Q.
W=       e# Select the last element of Q (bowl volume B).
3m*      e# Push all vectors of {0,...,B-1} × {0,...,B-1} x {0,...,B-1}.

{        e# For each vector [X Y Z]:
  :,     e#   Push [[0 1 ... X-1] [0 1 ... Y-1] [0 1 ... Z-1]].
  2ff*   e#   Multiply each coordinate by 2.
  ),)    e#   Pop the last vector, compute its length and increment.
  ff+    e#   Add the result to each component of each vector.
}%       e# Result: [[Z Z+2 ... Z+2(X-1)] [Z Z+2 ... Z+2(Y-1)]]

{        e# Find:
  ::)    e#   Increment each coordinate (to account for the volume in "\/").
  1fb    e#   Sum the coordinate of both vectors.
  Q=     e#   Compare the result to Q (desired volumes).
}=       e# If they match, push the array and break.

~        e# Dump both vectors on the stack.
W%       e# Reverse the rightmost one (corresponds to the bowl volume).
ee       e# Enumerate its coordinates.
         e# [Z+2(Y-1) ... Z+2 Z] -> [[0 Z+2(Y-1)] ... [Y-2 Z+2] [Y-1 Z]].
_,S*     e# Compute the length (Y) and push a string of Y spaces.
W'_t     e# Replace the last space with an underscore.
@        e# Rotate the leftmost vector (corresponds to the water volume) on top.
,        e# Compute its length (X).
~'~t     e# Replace the space at index X from the right with a tilde.

.{       e# For each enumerates coordinate and the corresponding character:
  S\+    e#   Append the character to the string " ".
  .*     e#   Vectorized repetition: [1 2] " ~" -> [" " "~~"]
  "\/".+ e#   Append the first (second) solidus to the first (second) string.
  N      e#   Push a linefeed.
}


Pyth - 25 24 bytes
Will refactor.
AC.tQdV.SU
G
=XGN@HN.d_1

Try it online here.


Polite Near-Sighted Drunk Bot on a Minefield

Python 2, 65 bytes

def p(n):b=2**n;r=b*b-((~b)**n/b**(n/2)%-b)**2;print~n%2*r/(r&-r)

Try it online!

The probability the bot is dead can be expressed as:

  $$ f(n) = 2s-s^2\text{, where }  s=\frac{1}{2^n}\binom{n}{n/2}$$

and the binomial is understood to equal \$0\$ when \$n/2\$ isn't whole.

We can reason like this. What's the probability that the bot lands on the \$y=x\$ line? This happens if the total number of up and left moves equals the total number of down and right moves. This is the same probability that, say, you flip a coin \$n\$ times and get as many tails as heads. You must choose \$n/2\$ flips to be heads of \$n\$ flips, which can be done in \$\binom{n}{n/2}\$ ways, of \$2^n\$ possible sequences overall, giving probability

$$s=\frac{1}{2^n}\binom{n}{n/2}$$

The probability of landing the \$y=-x\$ line is also \$s\$. So, the probability of landing on either line is the sum of these or \$2s\$, except we're double-counting the probability of landing of \$x=y=0\$ in both lines, and must subtract it to compensate.

It turns out the probability of landing on \$x=y=0\$ is just \$s^2\$, the product of the probability of landing on each line. We can argue the events are independent as follows: if we pick a random sequence of equal numbers of "Up or Left" and "Down or Right" to land on \$x=y\$ and likewise with "Up or Right" and "Down or Left" for \$x=-y\$, we can uniquely combine them into a sequence of Up, Down, Left, Right by taking the intersection of the pairs of directions at each position.

So, the probability of landing on \$x=y\$ or \$x=-y\$ is \$2s-s^2\$.

The code computes the binomial \$\binom{n}{n/2}\$ using this expression as (b+1)**n/b**(n/2)%b with base b=2**n. To extract the numerator from the probability fraction, we note that the denominator is a power of 2, so we use the expression r/(r&-r) to divide out the maximal power of 2 is r, expressed as the classic bit trick r&-r.

The solution is golfed by writing \$2s-s^2\$ as \$1-(1-s)^2\$ so that \$s\$ is only referenced once, and working without the \$1/2^n\$ fractions to stay within the integers. The computation is polynomial-time in \$n\$ even with the funky way of computing binomials.

After writing the proof of the probability the bot dies, I found a possibly cleaner way to prove it and present it.

Let's keep track of the values of \$a=x+y\$ and \$b=x-y\$ after each move of the bot. Each of the four directions up, down, left, and right either increments or decrements each of \$a\$ and \$b\$, with the four directions corresponding to the four combinations.

So, a random move is equivalent to randomly adding \$\pm 1\$ to \$a\$ and independently \$\pm 1\$ to \$b\$. This is equivalent to doing separate random walks on \$a\$ and \$b\$.

Now, the robot ends on the line \$x=y\$ or \$x=-y\$ exactly when \$a=0\$ or \$b=0\$. So, the probability of ending with \$a=0\$ is \$s=\frac{1}{2^n}\binom{n}{n/2}\$ and likewise for \$b=0\$. Since the walks are independent, the probability that \$a\neq 0\$ and \$b\neq 0\$ is \$(1-s)^2\$, so the probability that at least one is zero is the complement \$1-(1-s)^2\$.


Jelly, 3 bytes
IỊẠ

Try it online!
How?
Just the perfect challenge for Jelly.

IỊẠ   Full program.

I     Increments; Get the difference between consecutive elements.
 Ị    Insignificant; return abs(number) ≤ 1.
  Ạ   All; returns 1 if all the elements are truthy, 0 otherwise.


PHP golfing tips: Reading/writing files and the CLI

You can read a line from STDIN in 13 characters:

fgets(STDIN);

as seen here.

Reading from a file:

file('filename')

returns an array of lines of the file.

Using fputs instead of fwrite will save a character on writing, but I can't think of a shorter way than:

fputs(fopen('filename','w')); //use 'a' if you're appending to a file instead of overwriting

which is marginally shorter than:

file_put_contents('filename');


Universal (rule-bending) Code Golf solver

C, –110 chars

This version of the program uses the linear-runtime algorithm to generate the sequence. Subtracting 512 from the 402 chars in the program gives a total of negative 110.

#define C v=calloc(7,8),v->p=p
#define G(F,K)u->F[d[K]]
#define S(F,T)G(f,T)=F,G(t,T)=T,G(n,T)=
struct{int p,f[2],t[2];void*n[2];}r,*u,*v,*w;char*d,c;p,b,h,i,j,k;
main(s){for(;d=++p-s?d:realloc(d,s*=2);){d[i=p]=b;c+=c+b;p%8||putchar(c);
for(u=&r;b=u->p,u->p=p,w=G(n,k=i);S(i,k)v=G(n,k),u=v)for(h=G(f,k),j=G(t,k);j>h;--i,--j)
if(d[i]-d[j]){S(i,k)C;u=v;S(h,j)w;S(0,i)C;b=w->p;goto x;}S(0,i)C;x:b=1-d[b+1];}}

As per the problem, the program runs in an infinite loop, which necessitates lots of memory allocation, and using realloc() to keep the sequence contiguous can contribute to heap fragmentation. You can improve the program's memory usage by replacing calloc(7,8) on the first line with calloc(1,sizeof*v). This will help especially on a 32-bit machine, where 56 is likely too large by a factor of two.

The code is kind of unreadable, and not in an interesting way; for that I apologize. Frankly, even the ungolfed version isn't terribly clear:

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

typedef struct branch branch;
typedef struct node node;

struct branch {
    int from, to;
    node *next;
};

struct node {
    int pos;
    branch br[2];
};

static node root = { 0 };

static unsigned char *data = NULL;
static int endpos = 0;
static int size = 1;

static node *mknode(void)
{
    node *n;

    n = calloc(1, sizeof *n);
    n->pos = endpos;
    return n;
}

static branch *getbranch(node *n, int p)
{
    return &n->br[data[p]];
}

static void setbranch(node *n, int from, int to, node *next)
{
    n->br[data[to]].next = next;
    n->br[data[to]].from = from;
    n->br[data[to]].to = to;
}

int main(void)
{
    node *u, *v, *w;
    int follower, from, i, i0, j;
    int out, b;

    out = b = 0;
    for (;;) {
        ++endpos;
        if (endpos == size) {
            size *= 2;
            data = realloc(data, size);
        }
        data[endpos] = b;
        out = (out << 1) | b;
        if (endpos % 8 == 0) {
            putchar(out);
            out = 0;
        }

        i = endpos;
        u = &root;
        for (;;) {
            follower = u->pos + 1;
            u->pos = endpos;
            w = getbranch(u, i)->next;
            if (!w)
                break;
            i0 = i;
            from = getbranch(u, i0)->from;
            for (j = getbranch(u, i0)->to ; j > from ; --j) {
                if (data[i] != data[j]) {
                    /* divide branch */
                    v = mknode();
                    setbranch(u, i, i0, v);
                    u = v;
                    setbranch(u, from, j, w);
                    setbranch(u, 0, i, mknode());
                    follower = w->pos + 1;
                    goto bitfound;
                }
                --i;
            }
            v = getbranch(u, i0)->next;
            setbranch(u, i, i0, v);
            u = v;
        }
        /* extend branch */
        setbranch(u, 0, i, mknode());

      bitfound:
        b = 1 - data[follower];
    }
}

(The ungolfed code above is based on the code written by Grzegorz Herman and Michael Soltys, as referenced in the problem description, and from Soltys' home page.)

Thanks to @schnaader and @r.e.s. for reporting a bug in the initial version.


Flex, 1170+4=1174

1170 characters in the flex code + 4 characters for a compilation flag.  To produce an executable, run flex pre.l ; gcc lex.yy.c -lfl.  The entry leaks memory like a sieve and doesn't close included files.  But otherwise, it should be completely functional as per the spec.

%{
#define M malloc
#define X yytext
#define A a=X
#define B(x) BEGIN x;
#define Y YY_CURRENT_BUFFER
*a,*b,**v,**V,**t,**T,i,s=1,o;
g(){t=M(++s);T=M(s);for(i=1;i<s-1;i++)t[i]=v[i],T[i]=V[i];free(v);free(V);v=t;V=T;}
f(){for(i=1;i<s;i++)if(!strcmp(v[i],a))return i;return 0;}
d(y){X[yyleng-y]=0;}
%}
%x D F I
N .*\n
%%
"//".*
"/*"([^\*]|\*[^\/])*"*/"
\"(\\.|[^\\"])*\" ECHO;
^"#include "\"[^\"]*\" d(1),yypush_buffer_state(yy_create_buffer(fopen(X+10,"r"),YY_BUF_SIZE));
^"#define "[^ ]* {B(D)strcpy(a=M(yyleng),X+8);}
<D>" "?{N} {b=M(yyleng);d(1);f(strcpy(b,X+(X[0]==32)))?free(V[i]),V[i]=b:g(),v[s-1]=a,V[s-1]=b;B(0)}
^"#undef "{N} d(1),v[f(A+7)][0]=0;
^"#if defined(".*")\n" h(2,12);
^"#ifdef "{N} h(1,7);
^"#if "{N} {d(1);if(!atoi(X+4))B(F)}
^"#ifndef "{N} {d(1);if(f(A+8))B(F)}
<F>^"#if"{N} o++;
<F>^"#endif"{N} if(!o--)B(++o)
<F>^"#else"{N} if(!o)B(0)
<F>^"#elif defined(".*")\n" if(!o){d(2);if(f(A+14))B(0)}
<F>^"#elif "{N} if(!o){d(1);if(atoi(X+6))B(0)}
<F>{N}
^"#endif"{N}
^"#el"("se"|"if"){N} B(I)
<I>^"#endif"{N} B(0)
<I>{N}
[a-zA-Z_][a-zA-Z_0-9]* printf(f(A)?V[i]:a);
<<EOF>> {a=Y;yypop_buffer_state();if(!Y)exit(0);fclose(a);}
%%
h(x,y){d(x);if(!f(A+y))B(F)}

Some explanation:

a and b are temps to hold strings from the input.  a is also used as the parameter to function f.
v holds the names of macros and V holds the 'V'alues of macros
t and T are 't'emporary holders for when we grow v and V
i is an 'i'ncrementer for loops
s is the 's'ize of the macro array
o is the count of the 'o'pen ifs inside a false conditional
g() 'g'rows the macro arrays
f() 'f'inds a macro with the same value in v as a
d(y) 'd'rops the last y characters from the current input
state D is for inside a 'D'efine
state F is for ignoring a 'F'alse conditional
state I is for 'I'gnoring else/elif after a true conditional was found.

EDIT1: cleaned up many of the memory leaks and implemented file closing

EDIT2: modified code to handle nested macros more correctly

EDIT3: crazy amount of golfing

EDIT4: more golfing

EDIT5: more golfing; I've also noticed that my call to fclose() causes issues on some computers...looking into this.


Sample space of n consecutive coin flips

Jelly, 4 bytes
⁾HTṗ

A monadic Link accepting a non-negative integer which yields a list of characters.
Try it online! (footer calls the Link and joins with newline characters)
How?
⁾HTṗ - Link: integer, n
⁾HT  - list o characters = ['H', 'T']
   ṗ - (that) Cartesian power (n)


C#

Program:

#warning Lonesome
class _{
    static void Eye(long forYou='
        ){ /* My program ends here. */ ;}}

Read:

Warning: Lonesome class.
Static void. I long for you.
My program ends here.

Compiler output:

#warning: 'Lonesome'        (read: hash warning lonesome)
Empty character literal     (read: empty character lit’ral)
Newline in constant


JavaScript (ES6), 45 bytes

f=(n,x=0,y=1)=>n?f(n-1,y,(x%9||x)+(y%9||y)):x
<input type=number min=0 oninput=o.textContent=f(this.value)><pre id=o>

x and y can't both be 9, since that would require the previous number to be 0, so their digital sum can't exceed 17. This means that the digital root for numbers greater than 9 is the same as the remainder modulo 9.