Regex (.NET flavour), 182 181 145 132 126 114 104 100 98 97 96 bytes

2D ASCII art pattern recognition? Sounds like a job for regex! (It doesn't.)

I know this is going to kick loose endless discussions again about whether regex submissions are valid programs or not, but I doubt this will beat APL or CJam anyway, so I don't see any harm. (That being said, they do pass our die-hard test for "What is a programming language?".)

This takes input as the string to be matched, and the result is the number of matches found. It uses _ in place of ., because I'd have to escape the latter. It also requires a trailing newline.

(X(X){1,21})(?=\D+((?>(?<-2>_)+)_))(?=.((?!\7)(.)*
.*(X\3X|()\1.)(?=(?<-5>.)*(?(5)!)
)){4,23}\7)

You can test it live at RegexHero or RegexStorm). The matches will be the top obsidian rows of the portals. If you can find a test case where it fails, please let me know!

What is this sorcery?

The following explanation assumes a basic understanding of .NET's balancing groups. The gist is that captures are stacks in .NET regex - every new capture for the same name is pushes onto the stack, but there's also syntax to pop captures from those stacks again, as well as syntax to pop captures from one stack and push captures onto another at the same time. For a more complete picture, you can have a look at my answer on Stack Overflow which should cover all the details.

The basic idea is to match a pattern like:

 X{n}..{m}
X_{n}X.{m} |
X_{n}X.{m} |  3 to 22 times
X_{n}X.{m} |
 X{n}..{m}

Where n is between 2 and 22 (inclusive). The tricky thing is getting all the ns and all the ms to be the same. Since the actual characters won't be the same, we can't just use a backreference.

Note that the regex has to embedded newlines, which I'll write as \n in the following.

(                     # Open capturing group 1. This will contain the top of a portal, which
                      # I can reuse later to match the bottom (being of the same length).
  X                   # Match a single X.
  (X){1,21}           # Match 1 to 21 X's, and push each separately on the <2> stack. Let's
                      # Call the number of X's captured N-1 (so N is the inner width of the
                      # portal).
)                     # End of group 1. This now contains N X's.
(?=                   # Start a lookahead. The purpose of this lookahead is to capture a
                      # string of N underscores in group 2, so I can easily use this to match
                      # the inside rows of the portal later on. I can be sure that such a
                      # string can always be found for a valid portal (since it cannot have 0
                      # inner height).
  \D+                 # Skip past a bunch of non-digits - i.e. *any* of the vaild characters
                      # of the input (_, X, \n). This to make sure I search for my N
                      # underscores anywhere in the remainder of the input.
  (                   # Open capturing group 3. This will contain a portal row.
    (?>               # This is an atomic group. Once the engine hass successfully matched the
                      # contents of this group, it will not go back into the group and try to
                      # backtrack other possible matches for the subpattern.
      (?<-2>_)+       # Match underscores while popping from the <2> stack. This will match as
                      # many underscores as possible (but not more than N-1).
    )                 # End of the atomic group. There are two possible reasons for the
                      # subpattern stopping to match: either the <2> stack is empty, and we've
                      # matched N-1 underscores; or we've run out of underscores, in which
                      # case we don't know how many underscores we matched (which is not
                      # good).
    _                 # We simply try to match one more underscore. This ensures that we
                      # stopped because the <2> stack was empty and that group 3 will contain
                      # exactly N underscores.
  )                   # End of group 3.
)                     # End of the lookahead. We've got what we want in group 2 now, but the
                      # regex engine's "cursor" is still at the end of the portal's top.
(?=                   # Start another lookahead. This ensures that there's actually a valid
                      # portal beneath the top. In theory, this doesn't need to be a
                      # lookahead - I could just match the entire portal (including the lines
                      # it covers). But matches cannot overlap, so if there were multiple
                      # portals next to each other, this wouldn't return all of them. By
                      # putting the remainder of the check in a lookahead the actual matches
                      # won't overlap (because the top cannot be shared by two portals).
  .                   # Match either _ or X. This is the character above the portal side.

  (                   # This group (4) is where the real magic happens. It's purpose is to to
                      # count the length of the rest of the current line. Then find a portal
                      # row in the next line, and ensure that it's the same distance from the
                      # end of the line. Rinse and repeat. The tricky thing is that this is a
                      # single loop which matches both inner portal rows, as well as the
                      # bottom, while making sure that the bottom pattern comes last.

    (?!\7)            # We didn't have a group 7 yet... group 7 is further down the pattern.
                      # It will capture an empty string once the bottom row has been matched.
                      # While the bottom row has not been matched, and nothing has been
                      # captured, the backreference will fail, so the negative lookahead will
                      # pass. But once we have found the bottom row, the backreference will
                      # always match (since it's just an empty string) and so the lookahead
                      # will fail. This means, we cannot repeat group 4 any more after the
                      # bottom has been matched.
    (.)*              # Match all characters until the end of the line, and push each onto
                      # stack <5>.
    \n                # Match a newline to go to the next line.
    .*                # Match as many characters as necessary to search for the next portal
                      # row. This conditions afterwards will ensure that this backtracks to
                      # the right position (if one exists).
    (                 # This group (6) will match either an inner portal row, or the bottom
                      # of the portal.
      X\3X            # Match X, then N underscores, then X - a valid inner portal row.
    |                 # OR
      ()              # Capture an empty string into group 7 to prevent matching further rows.
      \1.             # Use the captured top to match the bottom and another character.
    )
    (?=               # This lookahead makes sure that the row was found at the same
                      # horizontal position as the top, by checking that the remaining line
                      # is the same length.
      (?<-5>.)*       # Match characters while popping from the <5> stack.
      (?(5)!)\n       # Make sure we've hit end of the line, *and* the <5> stack is empty.
    )
  ){4,23}             # Repeat this 4 to 23 times, to ensure an admissible portal height.
                      # Note that this is one more than the allowed inner height, to account
                      # for the bottom row.
  \7                  # Now in the above repetition there is nothing requiring that we have
                      # actually matched any bottom row - it just ensured we didn't continue
                      # if we had found one. This backreference takes care of that. If no
                      # bottom row was found, nothing was captured into group 7 and this
                      # backreference fails. Otherwise, this backreference contains an empty
                      # string which always matches.
)

C#, 185 bytes

Here is a full C# function, just to make this a valid entry. It's time I wrote a command-line "interpreter" for .NET regular expressions...

static int f(string p){return System.Text.RegularExpressions.Regex.Matches(p,@"(X(X){1,21})(?=\D+((?>(?<-2>_)+)_))(?=.((?!\7)(.)*
.*(X\3X|()\1.)(?=(?<-5>.)*(?(5)!)
)){4,23}\7)").Count;}


Mathematica
This is a straightforward implementation with each rgb colour occupying an intersection in a 256 by 256 by 256 unit grid.
The jerkiness seems to be an artefact of the video, not an error in the data, which should be exact.
red values increase downwards, green values increase rightwards, and blue values increase by frame.
Perhaps I'll jumble things up later.
f@b_ := Image@Table[{r, g, b}/255, {r, 0, 255}, {g, 0, 255}]
Export["c.mov", Table[f@b, {b, 0, 255}]]

QuickTime clip


JavaScript (ES7),  367 362 359  357 bytes
Saved 1 byte thanks to @Shaggy
Expects (n)(m).

n=>m=>(T=Array(n*n).fill(N=0),g=(A,P=[-1],k=T.findIndex(v=>!v),B=[...A,P[S='sort']()][S]())=>g[B]?0:~[1,1,0,1,1,0][M='map'](r=>g[B=B[M](P=>P[M](i=>~i?(y=i**.5|0)*y-i-(r?1-((~y*~y+~i>>1)-n)**2:y*~-~y):i)[S]())[S]()]=1)/P[m]?~k?g(B):++N:T[M]((v,j)=>v||(~P?P.every(i=>(y=i**.5|0)^j**.5|(i-j)**2-1&&j-i+2*(i+y&1?y:~y)):j-k)||T[T[j]++,g(A,[...P,j]),j]--))([])&&N

Try it online!
How?
TL;DR
This is a recursive search that keeps track of all the patterns that were already tried, transformed in all possible ways, in order to prune the search as soon as possible when a collision is found. This allows it to perform at a decent speed on small triangles despite an otherwise inefficient piece-building method.
Triangle description and cell indexing
A size-\$n\$ triangle is simply stored as an array of \$n^2\$ binary values. Empty cells are marked with \$0\$'s and occupied cells are marked with \$1\$'s.
JS initialization:
T = Array(n * n).fill(0)

By convention, the cells are numbered from \$0\$ to \$n^2-1\$, from left to right and top to bottom.

Below are some basic formulas:

The 0-indexed row of the cell \$c\$ is \$y_c=\lfloor\sqrt{c}\rfloor\$
The 0-indexed position of the cell \$c\$ within its row is \$c-{y_c}^2\$
The 0-indexed distance of the cell \$c\$ from the last cell in its row is \${(y_c+1)}^2-c-1\$

Testing whether 2 cells are neighbors
Two cells \$c\$ and \$d\$ are horizontal neighbors if \$y_c=y_d\$ and \$|c-d|=1\$ (e.g. \$c=10\$ and \$d=11\$, or the other way around).
Two cells \$c\$ and \$d\$ are vertical neighbors if either:

\$c+y_c\$ is even and \$d=c+2\times(y_c+1)\$ (e.g. \$c=3\$ and \$d=7\$)
\$c+y_c\$ is odd and \$d=c-2\times y_c\$ (e.g. \$c=7\$ and \$d=3\$)

Hence the following JS expression which is truthy if the cells i and j are not neighbors:
(y = i ** .5 | 0) ^ j ** .5 | (i - j) ** 2 - 1 && j - i + 2 * (i + y & 1 ? y : ~y)

Reflections
A vertical reflection is applied by doing:
$$d=2\times y_c\times (y_c+1)-c$$
Examples:
$$2\times y_{10}\times (y_{10}+1)-10=2\times 3\times 4-10=14\\
2\times y_{14}\times (y_{14}+1)-14=2\times 3\times 4-14=10$$

Rotations
A 120° rotation is applied by doing:
$$d=\left(n-\left\lfloor\dfrac{(y_c+1)^2-c-1}{2}\right\rfloor\right)^2+{y_c}^2-c-1$$
Examples:

\$c=0\$ is turned into \$d=15\$
\$c=7\$ is turned into \$d=12\$

Combining reflections and rotations
In the JS implementation, both formulas are combined into the following expression. This code applies a reflection to the cell i when r = 0 or a rotation when r = 1.
(y = i ** .5 | 0) * y - i - (
  r ?
    1 - ((~y * ~y + ~i >> 1) - n) ** 2
  :
    y * ~-~y
)

To get all possible transformations of a tiling, we apply 2 rotations, followed by a reflection, followed by 2 rotations, followed by a reflection.
Hence the loop:
[1, 1, 0, 1, 1, 0].map(r =>
  /* ... apply the transformation to each cell of each piece of the tilling ... */
)

Describing the tiling
Each piece of the tiling is stored in an array of \$m+1\$ entries consisting of a leading -1 followed by \$m\$ indices corresponding to the cells it contains.
The current piece is stored in P[]. The array A[] contains the previous pieces. The array B[] contains the previous pieces and the current piece, with all pieces sorted in lexicographical order and all indices also sorted in lexicographical order within each piece.
Example:
The following tiling:

would be described with:
B = [
  [ -1, 0, 1, 2, 3 ],
  [ -1, 10, 11, 4, 9 ],
  [ -1, 12, 5, 6, 7 ],
  [ -1, 13, 14, 15, 8 ]
]

Once coerced to a string, this gives a unique key that allows us to detect whether a similar configuration was already encountered and prune the search.
"-1,0,1,2,3,-1,10,11,4,9,-1,12,5,6,7,-1,13,14,15,8"

The purpose of the -1 markers is to make sure that an incomplete piece followed by another piece in the key is not mixed up with another complete piece.
The keys are stored in the underlying object of the function g.
Main algorithm
The recursive search function goes as follows:

find the position k of the first empty cell in the triangle
update B[]
abort if B[] was already encountered
apply all transformations to B[] and mark them as encountered
if P[] is complete:

if the triangle is full (k is set to -1): we've found a new valid tiling, so increment the number of solutions N
otherwise, append P[] to A[] and start building a new piece

if P[] is not yet complete:

if P[] does not contain any tile, append k to it
otherwise, try to append the index of each tile that has at least one neighbor in P[]


PowerShell, 50 44 41 39 43 bytes

param($a,$m)gc z|sls $m|sls "^[$a$m]{5,9}$"

Notes

Using a scriptblock (unnamed function) because there's still a requirement for a function full program.
Takes the "allowed" letters as a single string.
Using The English Open Word List which is provided as a series of lists (one for each letter). I've combined them all into a single file named z, but I only included words that are between 5 and 9 letters, inclusive due to the new rule, the wordlist and my gist have been updated to not exclude any of the original words (of any size). Here's the list, for anyone else to use.

Explanation

Reads the wordlist file z as lines and does two regular expression matches (by way of Select-String with the sls alias). The first sls matches the mandatory letter, so the result is all the words that contain the letter, then that gets piped into the second sls which uses an expression that, in the case of the example input, looks like this: ^[acdhirn]{5,9}$ (so it matches only words that consist of those letters and no others, between 5 and 9 characters in length, inclusive).

Invocation and Output

&{param($a,$m)gc z|sls $m|sls ^[$a$m]+$} 'acdhir' 'n'

Output (57 words):

acarian
acaridan
acini
ahind
anana
anarch
anarchic
arachnid
arcana
arnica
cairn
canard
cancan
candid
candida
canid
canna
cannach
caranna
carina
chain
characin
chicana
china
chinar
chinch
cinch
circadian        #
cnida
cnidarian
cranch
crania
dharna
diarian
dinar
dinic
drain
handcar
harridan         #
inarch
indican
indicia
indri
iridian
nadir
naiad
naira
nanna
niacin           #
nicad
rachidian
radian
ranarian
ranch
rancid
randan
ricin


Enumerate all number that are palindromic in at least two of base 2, 8, 10, 16 or 64

Mathematica
f[number,minPalindromeLength,minCount]works as follows If number is a palindrome with minPalindromeLength in at least minCount bases, f returns the information about that number.
g[max,minPalindromeLength,minCount] makes an table of "palindrome numbers" from 1 through max.
f[number_,minPalindromeLength_:2,minCount_:2]:=Module[{print,palindromeQ,count,
convert64=Thread[Range[0,63]->Characters["0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ@_"]],
digits=IntegerDigits[number,#]&/@(bases={64,16,10,8,2})},
palindromeQ[dig_]:=(dig==Reverse[dig]);
count = Total@Boole[palindromeQ/@ Cases[digits,x_/;Length[x]>minPalindromeLength-1]];
If[count>minCount-1,Join[{count,Subscript[StringJoin[IntegerDigits[number,64]/.convert64],64]},BaseForm[number,#]&/@Rest[bases]],Sequence[]]];

g[max_,minPalindromeLength_:2,minCount_:2]:=
(Print["\nPalindromes: minPalindromeLength = ",minPalindromeLength "\tand minCount ", minCount ];
DeleteCases[Table[f[z,minPalindromeLength,minCount],{z,9,max}],Null]//Grid);

g[5000,2,3]
g[5000,3,3]
g[5000,4,2]


J, 3 bytes
That was fun to find.
&+/

Try it online!
How it works
10 (&+/) 3 1 4 1 5 will bind 10 as an argument of + as 10&+, one verb that gets inserted between the elements of the list by /. So we have: 3 (10&+) 1 (10&+) 4 (10&+) 1 (10&+) 5. Now x n&v y means that y gets applied to n&v for x times. With J's right to left evaluation we get: to 5 add 1 times 10, add 4 times 10, add 1 times 10, add 3 times 10. A challenge made for J's stranger parts. :-) And because + is commutative, +&/ would also be a valid solution.


Python 2 (PyPy), 238 235 222 bytes

a=input();n=len(a);r=range(n);a=zip(a,r);a=map(sorted(a).index,a)+[n]
def s(u,m):
 if m<1:return[0]
 for k in r:
  v=u[k::-1]+u[k+1:]
  if sum(1<abs(v[i]-v[i+1])for i in r)<m:
   p=s(v,m-1)
   if p:return[k]+p
print s(a,5*n/3)

*(2 spaces = tab)
Try it online!
Saved 13 bytes borrowing a method for ranking a list.
DFS with a simple heuristic that checks whether a flip separates a pair of "pancakes" that would be adjacent when sorted. Sorts it in ascending order. Output is 0-indexed from the left where 0 flips the first 2 and so on. The number of moves used is (5/3)*n+1 < 5/3*(n+1) where (18/11)*n < (5/3)*n+1 < 5/3*(n+1) and (18/11)*n is a tighter upper bound found in 2009.


Professor Schwartzman's Acme Canine Decoder 2000

Retina, 24 18 17 16 bytes

1 byte saved based on an idea in MT0's answer.

\wf?k?
y
\byy
He

Try it online!

Explanation

\wf?k?
y

This simply turns all letters into y, but if they are followed by an f or k we immediately replace that as well. By removing f and k we "normalise" the lengths of the words so that they now all have two more ys than they need.

\byy
He

This turns the first two y of every word into He, completing the transformation.


Python 3, no comments or string literals, 106 bytes

x=quit
y=x.__class__
y.__add__=print
y.__pos__=x
x+x++x+x
x=__sop__.y
tnirp=__dda__.y
__ssalc__.x=y
tixe=x

I've never liked how comments and string literals let you "turn off" most of your language's syntax in challenges like this, so I wanted to see how far I could golf things without using either comments or string literals. This is what I came up with.

Since I don't have any way to disable the syntactical significance of parentheses, I cannot use the function call operator. Any attempt to do so would result in the reversed code having a closing parenthesis before the first opening parenthesis, which is invalid outside a comment or string literal. I also can't use def or container literals (aside from unparenthesized tuples), and my access to language features is in general extremely restricted.

One thing I can do is take advantage of Python's operator overloading to call functions implicitly. My ability to define any classes or functions is extremely limited, but fortunately, there are enough tools lying around in the built-in namespace for me to use. Most built-ins don't let me perform the attribute assignment I need to redefine their operator overloads, but (unless Python is run with one of the flags that disables site importing) the auto-imported site module adds quit and exit objects to the built-ins. These objects are instances of non-C classes, so I can reassign their operator overloads.

Setting __add__ to print lets me use addition to print things, and setting __pos__ to quit or exit lets me use the unary + operator to abort the program before the rest of the code runs. Without setting __pos__, I would need a bunch of additional code to make sure the "backwards" part of the code can find all the variables and attributes it needs to not fail. With __pos__, I only need to make sure the "backwards" code is still syntactically valid.

Forward, the code prints

Use quit() or Ctrl-D (i.e. EOF) to exit

Backward, the code prints

Use exit() or Ctrl-D (i.e. EOF) to exit

(The messages are slightly different on Windows.)

I also tried to figure out a way to do this by defining my own class instead of messing with quit.__class__. I got as far as the following:

if.1j:adbmal=1j
class ton:adbmal
a=lambda:j1.fi
j1=a
a.__dict__=a.__globals__

class ton:adbmal is one of the very few combinations of class name and class body such that the class statement is syntactically valid backward. tressa, led, labolg, tropmi, and esiar would also have been valid class names (with a different class body, such as not fi), but ton is the only one where the reversed name can be part of an expression, giving the most flexibility.

if.1j:adbmal=1j assigns a value to adbmal to make the class body succeed, while still being syntactically valid backward.

The stuff with a and j1 lets me use j1.ton to refer to my ton class, which is still a valid expression backward.

At this point, I got stuck. I couldn't figure out how to get my class out of j1.ton and into a more useful variable. I can't assign attributes on j1.ton and still have valid syntax backward, so I can't set operator overloads. I also wanted to set builtins.__build_class__ to my class so I could abuse the class statement to construct instances without the function call operator, but trying to put j1.ton on the right side of an assignment produces invalid syntax backward.

If I had been able to name my class something like fi or tpecxe, I could have used tricks like b:j1.fi to get the class into an annotation and then a.__dict__=__annotations__ to get it into a.b, but I couldn't find any way to get the class statement and the annotation tricks to hook up. Anything that was compatible with the class statement was incompatible with the annotation tricks.

(You might wonder why I didn't abuse builtins.__build_class__ to call an existing function directly, like print. I couldn't figure out a way to do that and have the output be deterministic, and I wanted deterministic output.)


Random Golf of the Day #2: Numbers from a Normal Distribution

R, 68 bytes

function(S,N){set.seed(S);sqrt(-2*log(runif(N)))*cos(2*pi*runif(N))}

This uses the runif() function, which generates random deviates from a uniform distribution. The seed for the random number generation is specified using set.seed(), which by default uses the Mersenne-Twister algorithm with a period of 2^19937-1.

The result is an R vector of length N containing the computed standard normal deviates.

This uses the Box-Muller method: For two independent uniform random variables U and V,


Pyth, 22 13 bytes

mhf!xTd+Qd._z

m         _z  map over prefixes of second input...
 hf    +Qd    find the first element in (dictionary+word) which...
   !xTd       ... starts with k

Sample run:

llama@llama:~$ pyth -c 'mhf!xTd+Qd._z'
['alpha', 'calf', 'cave', 'coax', 'code', 'codegimmick', 'codegolf', 'cool', 'gamma']
codegolf
['calf', 'coax', 'code', 'code', 'codegimmick', 'codegolf', 'codegolf', 'codegolf']

Thanks to @FryAmTheEggman for 4 bytes!


Jelly, 11 10 bytes

ƓDUz0P€Uḅ³

Try it online!

I couldn't get this down to 10 bytes by myself, but @Pietu1998 pointed me to an atom I'd missed, this giving this 10-byte solution. Unusually for Jelly, this one takes input from standard input (in the form 1276,933024), not from the command line (this enables the use of the ³ command, which returns the command line argument, defaulting to 100).

Explanation:

ƓDUz0P€Uḅ³
Ɠ           read standard input
 D          convert to base 10
  U         reverse elements
   z0       transpose, padding the end with zeroes
     P€     take the product of each (€) inner list
       U    reverse elements back
        b³  convert from base 100

The use of base 100 is a simple way to implement the "pad to 2 digits, then convert to base 10" technique. The only other subtle thing here is the reversing; we want to pad with zeroes at the start of the number, but Jelly's z command pads at the end, so reversing the lists means that z will pad correctly.


Find the original string, without the repetition without the repetition in the middle

Perl 6, 40 bytes

{.subst: m:ex/(.*))>$0/.max(*.chars),''}

Try it

{
  .subst:             # substitute

    m                 # match
    :exhaustive
    /
      ( .* )          # any number of chars

      )>              # don't include the following in what is returned

      $0              # the first match again
    /.max( *.chars ), # find the first longest submatch

    ''                # substitute it with nothing
}


Throwback Friday: Renumber my ZX spectrum BASIC listing

JavaScript (ES6) 177

Edit Added the (costly) scan for the next valid line number

l=>l.split`
`.map((x,i)=>([,n,t]=x.match(/(\d+)(.*)/),l[n]=10*-~i,t),l=[]).map((x,i)=>10*-~i+x.replace(/(UN |GO TO |UB )(\d+)$/,(a,b,c)=>(l.some((v,i)=>i<c?0:a=b+v),a))).join`
`

TEST

f=l=>
  l.split`\n`
  .map((x,i)=>([,n,t]=x.match(/(\d+)(.*)/),l[n]=10*-~i,t),l=[])
  .map((x,i)=>10*-~i+x.replace(/(UN |GO TO |UB )(\d+)$/,(a,b,c)=>(l.some((v,i)=>i<c?0:a=b+v),a)))
  .join`\n`

//TEST
console.log=x=>O.textContent+=x+'\n'

test=`1 REM "A rearranged guessing game"
2 INPUT A: CLS
3 INPUT "Guess the number ", B
10 IF A=B THEN PRINT "Correct": STOP
100 IF AB THEN GO SUB 122
121 GO TO 3
125 PRINT "Try again"
126 RETURN`
console.log(test+'\n\n'+f(test))


Best free online resources to learn competitive programming

Practice Algorithmic Thinking

If there's one thing I believe programmers need to master, it's the process of dissecting a problem statement and planning their approach.

By this, I mean having the ability to approach an unseen challenge and think about what is being asked.

If I were you, I'd look at challenges posted around this website, ranging from trivial to difficult, and take the time to plan how you would solve the problem. That way, you'll be able to have a hands on experience with problem solving.

Once you do this enough, start placing time restrictions on your thinking time. Because I know from personal experience that competitive programming is most often timed. Once you have got that nailed, you should be ready for competitions.

In summary: practice. Y'all need to walk before y'all can run. I hope to see you as an active contributor around here!


Implement Two-Layer Perceptron Algorithm

I'm going to cheat here, hence community wiki: instead of logistic sigmoid, I'll use the hyperbolic tangent and instead of backprop, I'll use ELM to train the perceptron. Here's the version for XOR, in Python, using BLAS via SciPy.

import numpy as np
from scipy.linalg import pinv2

n_hidden = 10  # hyperparameter

# Training set
X_train = np.array([[0,0], [0,1], [1,0], [1,1]])
y_train = [0, 1, 1, 0]

# set hidden layer parameters randomly
w = np.random.randn(X_train.shape[1], n_hidden)
b = np.random.randn(n_hidden)

# compute hidden layer activation
H = np.tanh(np.dot(X_train, w) + b)

# fit output layer parameters
beta = np.dot(pinv2(H), np.atleast_2d(y_train).T)

# prediction and evaluation
pred_train = (np.dot(H, beta) > .5).ravel()
print "Training set accuracy:", np.mean(pred_train == y_train)

I previously published a digits classification script using this algorithm. After removing comments, this is 11 lines of code @ 425 characters.


Python 2, 47 bytes

lambda m,r,l:m/reduce(lambda u,x:u/r+x-x/r,l,m)

Try it online!
Takes timestamps sorted in descending order.
The idea is to compute the video duration as a polynomial in the inverse speedup rate 1/r using Horner's method with coefficients given by the sorted timestamps. This avoids needing to explicitly take the differences of consecutive timestamps. We then divide the duration of the original video by the resulting duration to get the desired slowdown factor.
53 bytes

f=lambda m,r,l:l==[]or r/(l.pop()*(r-1)/m+1/f(m,r,l))

Try it online!
An attempt to write the function fully recursively. While the new duration itself has a clean recursive expression, we want to get the slowdown factor which divides the original duration by the new duration, and this is messier to express recursively.


Excel, 78 bytes

Assumes input in cell A1, and that Wordwrap formatting is turned on for cell.  Use Alt+Enter to add line feeds within the string and note the whitespace.  Only handles input up to 3570 due to limit of REPT function (Good luck getting a cell to be that tall, though).

=LEFT(REPT("Yeah
But
No
But
Yeah
But
No
",595),A1*9)

Reprinting, with periods for whitespace

=LEFT(REPT("Yeah
But
No......
But.....
Yeah....
But
No...........
",595),A1*9)

How it works:
The pattern repeats every 6 numbers:

0 = Yeah and But      Yeah + linefeed + But + linefeed
1 = No                No + 6 whitespace + line feed
2 = But               But + 5 whitespace + linefeed
3 = Yeah              Yeah + 4 whitespace + linefeed
4 = But and No        But + linefeed + No + 3 whitespace
5 = Blank             8 whitespace + linefeed

Each of these can be expressed with 9 characters, so a string is made of 54 characters (9 * 6), then repeated as large as Excel will allow.  Then it takes the left 9 * (number of input) characters as the output.

Linefeed for the "but and no" one is placed after the blank so that the Yeah for #6, #12, (etc) is formatted to the left rather than the right, and so that there is no blank linefeed added every 6th line for that item.


CJam, 241 bytes
(with newlines removed.)
rri:Hri:Vri:Q[q~]3/_Qa3*a+_|$W%:Pf{\a#}:AH/:B0ff*
P,,[AHAW%HBz:+_W%V\V]2/
ff{~@@f=/::|1#}0Ua4*t:R;
P0f<
V{H{BI=J=_2$=
0R{"I>! I+V<J>! J+H<"4/+4/z{~~}%:&1$*\)}%);2$-|t
}fJ}fI
[P,{_La#\1$0t1$f-}*;;]
{:TR=2/~\~V\-,>\f{\_3$=@~H\-,>{Tt}/t}~}/
:~Pf=:~
~]S*N

It uses the ppm file format. Example usage (using ImageMagick):
convert IVYvE.png -compress none ppm:-| (time /path/to/cjam-0.6.4.jar 1.cjam) |display

Well, it is too long and too slow... Runs about a minute for the example.
I resized the test cases (and added some others) to make testing easier.

It seems the color space informations are lost so the colors are slightly different.


Find five friends to eat chicken with Paul

05AB1E, 18 17 bytes

•w[•Y·FDÑ¨O})„=>ý

Try it online!

Explanation

•w[•                # base 214 encoding of 12496
    Y·F             # loop 2*2 times
       D            # duplicate top of stack
        Ñ           # push divisors
         ¨          # remove the last element (itself)
          O         # sum
           }        # end loop
            )       # wrap in list
             „=>ý   # join list on "=>"

In short, we calculate each number as f(n+1) = sum(divisors(f(n)) - f(n)


Bijective mapping from integers to a variable number of bits

Python, 20 bytes

lambda n:bin(~n)[4:]

Test:

>> [bin(~n)[4:] for n in range(16)]
['', '0', '1', '00', '01', '10', '11', '000', '001', '010', '011', '100', '101', '110', '111', '0000']

Doing lambda n:bin(n+1)[3:] increments the input, then takes the binary representation with the first symbol removed ([3:] because the prefix 0b is two chars chars). Since any positive number starts with 1 in binary, this uniquely gives a binary representation.

A byte is saved by instead using the bit complement ~n to get the negation -(n+1), and removing the negative sign by chopping off one more symbol.


Score 1, 35 generations
Sorry, but I guess I wrecked the challenge. I brute-forced all meaningful one-dot additions by hand, and found no other answer that wins against this.
Raw ASCII format
 OOO  OOO  OOO  OOO
O    O    O    O
O    O    O    O
O    O OO O    O
O    O  O O    O
 OOO  OO   OOO  OOO

               X

Image of initial state

Copy.sh export
#C Generated by copy.sh/life
x = 19, y = 8, rule = B3/S23
b3o2b3o2b3o2b3o$o4bo4bo4bo$o4bo4bo4bo$o4bob2obo4bo$o4bo2bobo4bo$b3o2b
2o3b3o2b3o$$15bo!

Try this pattern on copy.sh!
Slow animated gif


05AB1E, 15 14 bytes

$FDx>DŠ+)˜ê}sè

Try it online!


HTML + CSS, 487 + 189 = 676

The compass rose is constructed from CSS borders using the triangle technique and some basic transformations. The letters are just given fixed positions, so that turned out quite long :/

The snippet below is scaled down so that it all fits. You can check out the JSFiddle here. Also, I'm not sure how well the letters will line up on different browsers (with different fonts, default styles, etc.).

html{transform:scale(0.2)}body{margin:5em}hr{margin:0;float:left;border:250px solid transparent;border-right:58px solid #E5E5E5;border-bottom:58px solid #9999FF}a{position:fixed;width:616px;font-size:4em}#a{transform:rotate(90deg)}#b{transform:rotate(270deg)}#c{transform:rotate(180deg)}#d{transform:rotate(45deg)scale(.8)}#n{top:20px;left:365px}#e{top:356px;left:700px}#s{top:700px;left:370px}#w{top:356px;left:10px}#N{top:150px;left:550px}#E{top:560px;left:550px}#S{top:560px;left:140px}#W{top:150px;left:140px}
NESWNESESWNW


Perl 6, 79 76 71 bytes

{($!=sort {[R,] -$_,{first $_%%*,$_^..1}...1},^2020)[+(@$!...$_)X-2,0]}

Try it online!

Sorts numbers 1 to 2019 lexicographically by the reversed, negated sequence of largest divisors, then finds the neighbors. Example mappings:

1760 => (-1 -11 -55 -110 -220 -440 -880 -1760)
  33 => (-1 -11 -33)
  99 => (-1 -11 -33 -99)

In other words, the negated cumulative product of prime factors in descending order.


JavaScript (Node.js), 52 bytes
Takes input as (b)(n), where b is a Buffer (using the characters described in the challenge) and n is the durability of the axe.
Returns a Boolean value and 2 integers as [ broken, [ small, big ]].
b=>n=>[b.some(c=>(n-=6&c+1)<0||!++a[c%3],a=[0,0]),a]

Try it online!
How?
Given an ASCII code c, we use 6 & (c + 1) to get the number of swings needed to chop the tree, and c % 3 to get an index into the tree-counting array a[] (0 for small, 1 for big).
 char. | c = ASCII code | 6 & (c + 1) | c % 3
-------+----------------+-------------+-------
  'i'  |       105      |      2      |   0
  '|'  |       124      |      4      |   1


JavaScript (ES6),  226 220  209 bytes
Saved 11 bytes thanks to @HermanL
Input is 1-indexed.

f=(x,n=m=c=1,D=k=>k?n%k?D(k-1):[k,...D(k-1)]:[],S=a=>s=eval(a.join`+`))=>(S(a=D(n))>m?m=s:0)|(s=a.length)<3|(s<c?0:c=s)|a.reduce((a,x,i)=>i?[...a,...a.map(y=>[...y,x])]:a,[[]]).some(a=>S(a)>=n)||--x?f(x,n+1):n

Try it online!
Optimizations are based on the following properties:

All primitive abundant numbers are either semiperfect or weird.
All highly composite numbers are largely composite.
All superabundant numbers are highly abundant.


Python 2, 152 bytes

l=input()
def f(x,y,n):
 if m[x][y]<n:m[x][y]=n;[f(i%3-1+x,i/3-1+y,h)for h,i in zip(l[n-1],[3,7,5,1])]
e=len(l)
m=eval(`[[0]*e*2]*e*2`)
f(e,e,1)
print m

Try it online!

The input order is NESW
f is a recursive function to populate the houses


Print strings without sharing characters

CJam, 0.24075

Programs

BA1]100cf|
"two"
{hree}`W<7a.-
N)92+_9+_6+_2~+
S(84^I^U$F^X$G^Y$(
's'i'x

Thanks to @user23013 for his suggestion to use ' for six.

Output, length, score, used characters

one    10  0.03162          01       AB         ]    c f         |
two     5  0.08944  "                                     o  tw
three  13  0.02133        -.     7  <        W     `a e h  r    { }
four   15  0.01721      )+    2 6  9      N       _                ~
five   18  0.01309   $ (       4  8    FGI SU XY ^
six     6  0.06804    '                                  i  s  x

Verify the results yourself in the CJam interpreter.


Mathematica 146 92 chars (score 2130/92 = 23.15)
Shorter Version (92 chars)
This palindrome has the characters grouped,
""<>{s=({#[[1]],Length@#~Quotient~2}&/@ Gather@Characters@t)
/.{c_,n_}:>c~Table~{n},Reverse@s}

Longer Version (146 chars)
This will return a maximum length, randomized palindrome from t.
Because capital letters are equivalent to lowercase letters, I converted all capitals to lower case.  (This can be changed if necessary.)
f@t_ := "" <> Join[s = RandomSample[ Flatten[({#[[1]], Quotient[Length[#], 2]} & /@
     Gather[Characters@ToLowerCase@t]) /. {c_, n_} :> ConstantArray[c, n]]], Reverse@s]

Example:
When t is the suggested, Lorem ipsum, text.  (Ignore line returns; all line returns were generated via the SE editor.)

"ti,iopexri  rpiuu opaat tismimetnesa lvuot oiaiu oaaittcoar nc
muapua elhpibemu utin ia f  ihide sdourgeeic e  oaasa.marsae dstircd
ci ndn   rs t egoaiq.aeatntreusng xi a lumalnoiieqqeq cc otiueasniieu
nrpupdlmnai o cdsm t gt.iccmittli i t tu.rust.li maui bea gqiceeo
pncu eonttecvtutqun eaaariusoquppsedlqu scrddmt esiafidurs  hitlpna
nlamltire ivmumbabi nbuderup td x uuualsoq.eiib li olel ru aeelau
idbc lrop iil ssur anda o scnmsr ,m uri,teo
esmiaveuomrt ldqqaid ihi snsr   spueeoevcre oe
msirulaleaisormm.oicolarsstteo td aatncn ieqrsuam boid te utcf eccp
siacu m etnqutlacniiereltiulqemltaqx a
qtdlxmliibileoheesimittlusqemooamuiippeaiilcgudsatfsiemamsc irn
rsgoi, ie
nmteiaiiptraned alsomsui noru ic,mditi ic ouud oadmv iudinrfuludet
eeiidueel nndaemcrepnioe sials unetuamconn,i
ubpo eiu ei dsn equi,ue ostmp udiatqu dalmau nueeiit ln e mioancteop
ntiiao ts noeefubtefrit ldeop earnmsm oas
d.catirotulvliodiellmesurotiomsmduia.nauenb iuiroimduriohs.lrndsaroc
t inidrssq apeuionnlaa eqdroounosmotidr arxr o taouarut  ussce uamae
is.dcadaimuoaprad iifl  i  lmml  i  lfii darpaoumiadacd.si eamau
ecssu  turauoat o rxra rditomsonuoordqe aalnnoiuepa qssrdini t
corasdnrl.shoirudmioriui bneuan.aiudmsmoitorusemlleidoilvlutoritac.d
sao msmnrae poedl tirfetbufeeon st oaiitn poetcnaoim e nl tiieeun
uamlad uqtaidu pmtso eu,iuqe nsd ie uie opbu
i,nnocmautenu slais eoinpercmeadnn leeudiiee tedulufrnidui vmdao duuo
ci itidm,ci uron iusmosla denartpiiaietmn
ei ,iogsr nri
csmameisftasdugcliiaeppiiumaoomeqsulttimiseehoelibiilmxldtq a
xqatlmeqluitlereiincaltuqnte m ucais pcce fctu et diob mausrqei
ncntaa dt oettssralocio.mmrosiaelalurism eo ercveoeeups   rsns ihi
diaqqdl trmouevaimse
oet,iru m, rsmncs o adna russ lii porl cbdi  ualeea ur lelo il
biie.qoslauuu x dt puredubn ibabmumvi eritlmaln anpltih  srudifaise
tmddrcs uqldesppuqosuiraaae nuqtutvcettnoe ucnp oeeciqg aeb iuam
il.tsur.ut t i ilttimcci.tg t msdc o ianmldpuprn  ueiinsaeuito cc
qeqqeiionlamul a ix gnsuertntaea.qiaoge t sr   ndn ic dcritsd
easram.asaao  e cieegruods edihi  f ai nitu umebiphle aupaum cn
raocttiaao uiaio touvl asentemimsit taapo uuipr  irxepoi,it"


Take advantage of curried functions and Prelude.ls

If the function is already curried, it can be much shorter overall. Also, Prelude.ls is the standard library, and its functions are often very useful. This means, unless otherwise specified, this library is 100% allowed. Examples:

f=->[1 to &0].reduce (*) # space required
f=->product [1 to &0]

s=(.reduce (+))
s=sum                    # better yet, avoid defining this when possible

d=(.map (*2))
d=map (*2)               # Sometimes even shorter than native methods

r=->&0.reduce (-&1-)
r=->fold1 (-&1-),&0      # Equal if starting value is required.

a.=sort!
a=sort a                 # sometimes the same length

a.=sort ->&1.length-&0.length # space before arrow required
a.=sort over (-),(.length)    # slightly more functional
a=sortBy (.length)            # specific builtin, always prefer CamelCase


APL, 32 characters
⍪⌽({⍵,⍨,/{⌽⍵,+/⍵⍷d}¨⍳⌈/d←⊃⍵}⍣⎕)1

This generates lines starting from 0 (i.e. 0 generates 1, 1 generates 1 followed by 1 1, etc.), as specified by user input. I used Dyalog APL for this, and ⎕IO should be set to its default of 1.
Example:
      ⍪⌽({⍵,⍨,/{⌽⍵,+/⍵⍷d}¨⍳⌈/d←⊃⍵}⍣⎕)1
⎕:
      0
1

      ⍪⌽({⍵,⍨,/{⌽⍵,+/⍵⍷d}¨⍳⌈/d←⊃⍵}⍣⎕)1
⎕:
      13
               1
             1 1
             2 1
         1 1 1 2
         3 1 1 2
     2 1 1 2 1 3
     3 1 2 2 1 3
     2 1 2 2 2 3
     1 1 4 2 1 3
 3 1 1 2 1 3 1 4
 4 1 1 2 2 3 1 4
 3 1 2 2 1 3 2 4
 2 1 3 2 2 3 1 4
 2 1 3 2 2 3 1 4

Once I get some more time, I'll write up an explanation. ⍨


PostgreSQL, 158 characters

select'public static boolean isPowerOfTen(long input) {
  return
   '||string_agg(' input == 1'||repeat('0',x)||'L','
  ||')||';
}'from generate_series(0,18)x


Jelly, 8 11 bytes

Thanks Johnathan Allan for updating the answer with the rules change.

ı_*@µĊ,ḞAÞṪ

Try it online!

ı_*@        z^(i-z)
    µ       new monadic link
     Ċ,Ḟ    pair real and imaginary parts
        AÞṪ sort by absolute value and take last value


Build a 4-vertex Connectedness Tester using NAND gates

19 NANDs
There is no simpler circuit than this.
There is code for testing it below the picture.
As for understanding it, that's difficult.
There are a couple of IF gates there, and the inputs are kinda grouped into a triangle with the free corner lines added for analysis one by one, but not in a simple way. If anyone manages to understand it, I will be impressed.

Verilog code with testing:
// 4-vertex Connectedness Tester
// Minimal at 19 NANDs
//
// By Kim Øyhus 2018 (c) into (CC BY-SA 3.0)
// This work is licensed under the Creative Commons Attribution 3.0
// Unported License. To view a copy of this license, visit
// https://creativecommons.org/licenses/by-sa/3.0/
//
// This is my entry to win this Programming Puzzle & Code Golf
// at Stack Exchange:
// https://codegolf.stackexchange.com/questions/69912/build-a-4-vertex-connectedness-tester-using-nand-gates/
//
// I am sure there are no simpler solutions to this problem.
// It has a logical depth of 11, which is deeper than
// circuits using a few more NANDs.

module counting6 ( in_000, in_001, in_002, in_003, in_004, in_005, in_006, out000 );
  input  in_000, in_001, in_002, in_003, in_004, in_005, in_006;
  output out000;
  wire   wir000, wir001, wir002, wir003, wir004, wir005, wir006, wir007, wir008, wir009, wir010, wir011, wir012, wir013, wir014, wir015, wir016, wir017;

  nand gate000 ( wir000, in_000, in_000 );
  nand gate001 ( wir001, in_001, in_003 );
  nand gate002 ( wir002, wir001, wir000 );
  nand gate003 ( wir003, in_002, wir002 );
  nand gate004 ( wir004, wir002, wir002 );
  nand gate005 ( wir005, wir004, in_002 );
  nand gate006 ( wir006, wir005, wir004 );
  nand gate007 ( wir007, in_005, wir006 );
  nand gate008 ( wir008, in_003, wir006 );
  nand gate009 ( wir009, in_004, wir003 );
  nand gate010 ( wir010, wir003, wir009 );
  nand gate011 ( wir011, wir009, wir000 );
  nand gate012 ( wir012, wir011, in_001 );
  nand gate013 ( wir013, wir008, wir012 );
  nand gate014 ( wir014, wir013, in_005 );
  nand gate015 ( wir015, wir006, wir013 );
  nand gate016 ( wir016, wir015, wir007 );
  nand gate017 ( wir017, wir016, wir010 );
  nand gate018 ( out000, wir014, wir017 );
endmodule

module connecting6_test;
   reg [5:0] X;
   wire a;

  counting6 U1 (
  .in_000 (X[0]),
  .in_001 (X[1]),
  .in_002 (X[2]),
  .in_003 (X[3]),
  .in_004 (X[4]),
  .in_005 (X[5]),
  .in_006 (X[6]),
  .out000 (a )
  );

  initial begin
    X = 0;
  end

  always
    #10  X = X+1;

 initial  begin
    $display("\t\t     \t_");
    $display("\t\ttime,\t \\db/_,\tconnected");
    $monitor("%d,\t%b,\t%d",$time, X, a );
  end

  initial
   #630  $finish;

endmodule

// iverilog -o hello hello.v
// vvp hello

Kim Øyhus


ID generator with no matching contiguous pairs

Brachylog, 11 10 bytes

{≤ṫẹ~ḅẉ}ᶠ⁾

Input is a list of two numbers.
Try it online!

Explanation

The built-in ḅ takes a list or string, like "1000220", and splits it into blocks of equal adjacent elements, like ["1","000","22","0"].
In this program, I apply the ~ operator to it, so it works in reverse: it takes a list of strings, checks that each string consists of repetitions of a single character and neighboring strings have different characters, and concatenates the list.
The predicate ≤ enumerates numbers starting from the first input in increasing order, and I check a condition on them, printing those that satisfy it and stopping when I've found enough.

{≤ṫẹ~ḅẉ}ᶠ⁾  Input is a pair, say [M=988,N=3].
{      }ᶠ⁾  Apply this predicate to M and compute the first N results.
 ≤          Take a number that is greater than or equal to M (first up is 988).
  ṫ         Convert it to string: "988"
   ẹ        Split it into substrings of length 1: ["9","8","8"]
     ~ḅ     Apply ḅ in reverse: fails, try next number.
       ẉ    If ḅ succeeds, print the resulting string and a newline.
            This counts as a result of the predicate.


Ruby, 171 167 157 bytes

require'io/console';t=Time;f=->a{loop{x=t.now;STDIN.getch==?\r?break: a<<t.now-x};a};p"Please type the key phrase";f[r=[]];p"Please type the key phrase again";p r.zip(f[[]]).map{|x,y|(1-x/y).abs}.reduce(:+)/r.size>0.2

Outputs true if average variance is above 20%, otherwise outputs false.

Dinosaur ASCII art attempt:

(_=/\
  \ \
   \ \
    \ \              _...---..__
     \ \          .∕` #{t=Time} `\._
      \ \      .∕ #{z='io/console'} `\.
       \ \.__.∕  #{require z;s=STDIN} `\.
        \ #{p'1:';f=->a{loop{x=t.now;#   \.
         s.getch==?\r?break: a<<t.now-x;# `\.
          };a};f[r=[]];p'2:';p r.zip(f[[]])#\
           .map{|x,y|(1-x/y).abs}.reduce(:+)#|
            .fdiv(r.size)>0.2}###########\   \
            `-._    ,___...----...__,   ,__\  \
                |   |_|           |_|   |    \ \
                |___|               |___|      \\/)

Ungolfed:

require 'io/console' # so we can read one char at a time

t = Time

f = ->(a) {
  loop {
    x = t.now # record start time
    break if STDIN.getch == ?\r
    a << t.now - x # push (start time - end time) into array
  }
  a
}

puts "Please type the key phrase"
f[r = []]

puts "Please type the key phrase again"

# interweave timing arrays, compute variances, sum elements
# then divide by array length. Check to see if average
# is greater than threshold (0.2)
p r.zip(f[[]]).map { |x,y| (1-x/y).abs }.reduce(:+) / r.size > 0.2

require 'io/console' could be removed when run in some Ruby REPLs, as the library is already loaded.


Ruby - 215 207

t,*d=$<.map &:chop;n,d,e=t.size+1,(d*S=?#).gsub(/[^#]/,W=" "),->c,i{puts [c,i/n+1,i%n+1]*" ";exit 1}
0.upto(d.size-1){|i|d[i]==d[-i-1]||e[?R,i];d[i]==W&&(d[i-1]!=W&&d[i+1]!=W||d[i-n]!=W&&d[i+n]!=W)&&e[?L,i]}

Ungolfed:

h, *g = $<.map &:chop
w = h.size+1
g = (g*?#).gsub(/[^#]/," ")
error = ->c,i{ puts [c,i/w+1,i% w+1]*" "; exit 1 }
0.upto(size-1) { |i|
        error[?R, i] if g[i] != g[-i-1]
        error[?L,i] if g[i]==" " && (g[i-1]!=" " && g[i+1]!=" " || g[i-w]!=" " && g[i+w] != " ")
}

.

h, *g = $<.map &:chop

This basically removes the last char (line break) of each input line by calling the chop method on them, and returning an array of the results.

h takes the first element of this array and *g takes the rest. So we end up with the first line in h and the crossword grid lines in g.

g = (g*?#).gsub(/[^#]/," ")

g*?# joins (*) the array g with the "#" (?# is a character literal). This is the same as g.*("#"), or g.join("#"). Then every non # is replaced by a space.

For the symmetry check we just have to check if the char at every index is equals to the char at the opposite index in the string:

0.upto(g.size-1) { |i| if g[i] != g[g.size - i - 1]; error() }

In Ruby we can index strings from the end using negative indexes (starting from -1 instead of 0), so that g[-i-1] is the opposite of g[i] in the string. This saves a few chars:

0.upto(g.size-1) { |i| if g[i] != g[-i-1]; error() }

We can save a ; by using a conditional statement:

0.upto(g.size-1) { |i| error() if g[i] != g[-i-1] }

In the golfed version we can save a few more chars:

0.upto(g.size-1){|i|g[i]==g[-i-1]||error()}

In a previous version I used recursion for iterating over the string:

(f=->i{g[i]&&f[i+1]&&g[i]!=g[-i-1]&&error()})[0]

An out of bound access to g returns nil, so once g[i] returns nil, this stops the iteration.

Output format:

{ L | R } line-number column-number

L for length errors, and R for rotation error (so L 1 2 means length error at line 1, column 2)


Operator that combines sum, product and difference between two numbers

JavaScript (ES7), 63 61 59 bytes

Saved 4 bytes thanks to Neil.

(a,b)=>[a*b,a+b,a-b].reduce((p,c)=>p*10**-~Math.log10(c)+c)

<input id=a type=number oninput="c.innerText=((a,b)=>[a*b,a+b,a-b].reduce((p,c)=>p*10**-~Math.log10(c)+c))(+a.value,+b.value)">
<input id=b type=number oninput="c.innerText=((a,b)=>[a*b,a+b,a-b].reduce((p,c)=>p*10**-!Math.log10(c)+c))(+a.value,+b.value)">
<p id=c>


CJam, 37 29 28 27 bytes

Thanks to Sp3000 for saving 3 bytes.

q{T):T/(\s}h]{z_Wf%_}3*])e=

Test suite.

This reuses some triangle rotation tricks from this challenge.

This also works for the same byte count:

q{T):T/(\s}h]3{;z_Wf%_}%)e=

Explanation

First, a quick recap from the triangle post I linked to above. We represent a triangle as a 2D (ragged) list, e.g.

[[0 1 1]
 [0 0]
 [0]]

The symmetry group of the triangle has 6 elements. There are cycles of length 3 by rotating the triangle and cycles of 2 by mirroring it along some axis. Conveniently, the rotations correspond to perform to two different reflections. We will use the following reflections to do this:

Transpose the list means reflecting it along the main diagonal, so we'd get:

[[0 0 0]
 [1 0]
 [1]]

Reversing each row represents a reflection which swaps the top two corners. Applying this to the result of the transposition we get:

[[0 0 0]
 [0 1]
 [1]]

Using these two transformations, and keeping the intermediate result, we can generate all six symmetries of the input.

A further point of note is the behaviour of transposition on a list like this:

[[0]
 [1 0]
 [1 0 0]
 []]

Because that's what we'll end up with after splitting up the input. Conveniently, after transposing, CJam flushes all lines to the left, which means this actually gets rid of the extraneous [] and brings it into a form that's useful for the above two transformations (all without changing the actual layout of the triangle beyond reflectional symmetry):

[[0 1 1]
 [0 0]
 [0]]

With that out of the way, here's the code:

q       e# Read input.
{       e# While the input string isn't empty yet...
  T):T  e#   Increment T (initially 0) and store it back in T.
  /     e#   Split input into chunks of that size.
  (     e#   Pull off the first chunk.
  \s    e#   Swap with remaining chunks and join them back together
        e#   into a single string.
}h
]       e# The stack now has chunks of increasing length and an empty string
        e# as I mentioned above. Wrap all of that in an array.
{       e# Execute this block 3 times...
  z_    e#   Transpose and duplicate. Remember that on the first iteration
        e#   this gets us a triangle of the desired form and on subsequent
        e#   iterations it adds one additional symmetry to the stack.
  Wf%_  e#   Reverse each row and duplicate.
}3*
        e# The stack now has all 6 symmetries as well as a copy of the
        e# last symmetry.
]       e# Wrap all of them in a list.
)       e# Pull off the copy of the last symmetry.
e=      e# Count how often it appears in the list of symmetries.


Fibtraction - Fibonacci but with subtraction

Oasis, 4 bytes
c-21

Try it online!
0-indexed.
I saw this language used for a similar challenge once, and immediately I knew I should try it here. Can't say I'm disappointed.
Explanation
   1    a(0) = 1
  2     a(1) = 2
c       a(n) = a(n - 2)
 -                      - a(n - 1)


Javascript, 2227 bytes

@Peter Taylor: Challenge Accepted!

_='S=b9b?b^3?"{"+)+"}":\'"\'+)+\'"\':"["+b6SB" ")+"]":""+b};$=b||!b99b:[b]b6$B""L;M=b9$(bb+""};A=b?(gb.charCodeAt(0)A(b1))v=g,v=3,g,v};C=b9(k=b6Ck=b,kb};a=g,s,O,r=Wj,uX,d,c,i,yPb=(b?$(bb+"").match(/\'(.|[^\'])*\'|"(.|[^"])*"|-?\\d+|\\043[^\\n]*|[a-z_]\\w*|./imgFi=y=0;z=b[i++];)"{"Yz?!y++Zk=iy?"}"Yz!--yZe=A(bk,i-1B""))e=4\'"\'YzQ?A(eval(z.replace("\\n","n")))"\'"YzQ?A(z1,-1).replace(/(|\')/g,"$1"))":"Yz?r[b[i++]]=(d=s[s-1])^4?S(dd:r[z]?r[z]z+"."-0.1?eval(z)eval("//~t;t98?ts=st~t\\140A(S(G)))//[O.uns]JEt,u@`vEuX,v%`I!u)t%u!tPt3?[32]:[]Xu+tV-5!~tc)RcL# q-t/`I!u)Math.floot/u)!tPv=0;j%tY0ZvRvv,vvcdvLu^4Pp=1 ITPFd;\'.\'u;)ds[s-1]tGdL#{D;HL//*7I!t)q*t!uPFd;u--;)T?td=dCUd=8;T||dL8^4P!u8Zu6M)6A)d=dC(j?t:[]cd=8;GdL#{q.)HL//zipt;Fv=c;v--;)!d[v]Zd[v]d[v]c[v]?7IT)HG)Zcu# t9tuMath.pow(uX)$t;u=0;t9(T?(u=t,G)t).sort(uZaua,bubb-a}C(s~t)Q)=`t!9ut)Q:0|$(u)Y$U>N$U|0:t0Xu>t|0V)K()]:[t+1](K.)]:[t-1]&5v;~tc)vc   &t|5dvt |t^5v;k,ut!~tc)^!~kc)vc ^tif`v=?u:t;v^4?A(S(v)v!+!randMath.random()*G)|0)".split("//"+z)[1]L,\'{1$if}:and{1$if}:or{!!{!}*}:xor{..0sZOQ=sFfoGs(HctIif(Js.splice(O.))Kt;s=st9[tXL)}N`q9t9$(u)P){Q[0]RdT8>3U(t)V8//Wfunction(b,X,tY==Z(`;qu';for(Y=0;$='q`ZYXWVUTRQPNLKJIHGFEDB98765#  '[Y++];)with(_.split($))_=join(pop());eval(_)

Note: Contains some control characters, nothing outside of ASCII though. Here's a direct link to the file: gs.js. The code provides a function a which takes the Golfscript code as a single parameter and returns the resulting stack as an array, with strings and blocks represented as ASCII.

Differences from the official interpreter:

Numbers have only 53 bits precision
No exact output and no direct print (would be easy to add though)
Double quoted strings are parsed using Javascript's eval, which might work different than Ruby's. Also no access to Ruby functions via strings
Undefined behaviour (I tried my very best)

I've also made a bunch of test cases and set up a small form for running Golfscript code: http://copy.sh/golfscript/

Here are some examples:

pi, phi
fizzbuzz
primality test
a quine

This is my standard Golfscript library, suggestions are welcome:

{1$if}:and
{1$\\if}:or
{\!!{!}*}:xor
{..0<2**-}:abs
{\{!}+\while}:until
{0$}:.
"\n":n
{\.[]*{0{2$*\(@+1$}do@;\;}{[{.@.@\\%@@.@\/.}do;;]-1%}if}:base
];


JavaScript (ES6), 78 74 bytes

f=(n,i)=>n<999.5?i?n.toPrecision(n<1^3)+' KMG'[i]+'iB':n+'B':f(n/1024,-~i)
<input oninput=o.textContent=f(this.value)><pre id=o>

Edit: Saved 4 bytes thanks to @Arnauld.


Python, 36 bytes

lambda m:(m+1-bin(m).count('1'),m+1)

Try it online!
A formula!
$$ f(m) = 1 - \frac{\text{#ones in bin}(m)}{m+1} = \frac{m+1-\text{#ones in bin}(m)}{m+1}$$


C (gcc), 101 100 99 bytes

Saved a byte thanks to pizzapants184.
Saved a byte.

s,t;a(i,r){for(t=~0;++t<r;puts(""))for(s=0;s<i;putchar(48+(t+(s>10-t)*(10*s+9-(s+++t-11)/2))%10));}

Try it online!


The requests module, if allowed, is much shorter and easier than urllib in Python (2 and 3):

__import__('requests').get('url').text

On my computer, the user agent defaults to:

python-requests/2.3.0 CPython/3.4.3 Darwin/14.3.0


JavaScript (ES6), 130 bytes

g=
(f,t,n)=>[...Array(++n+1)].map((_,i)=>f.replace(/../g,(e,j)=>((`0x${e}`*(n-i)+`0x${t[j]+t[j+1]}`*i)/n|256).toString(16).slice(1)))
;
p=_=>g(f.value,t.value,+n.value).map(e=>o.insertRow().insertCell().appendChild(document.createTextNode(e)).parentNode.bgColor=e);
<input id=f value=e14f09><input id=t value=9a04f6><input id=n value=4 type=number><input type=button onclick=p() value=Go!><table id=o bgcolor=black cellpadding=4>


Use the ; operator to refer to the previous object

There is a convenient shorthand in Smalltalk used to refer to the previous object. Say we want to add 3 items to the set x.

x:=Set new
x add:5.x add:7.x add:'foo'

However, we can save a few bytes by using the ; operator:

x:=Set new
x add:5;add:7;add:'foo'


What are the repeating Fibonacci Digits?

Jelly, 15 bytes

DFṫ-SṭḊ
d⁵ÇÐḶZḢ

Try it online!

How it works

d⁵ÇÐḶZḢ  Main link. Argument: n (integer)

d⁵       Divmod 10; yield [n:10, n%10].
  ÇÐḶ    Call the helper link until a loop is reached. Return the loop.
     Z   Zip/transpose the resulting array of pairs.
      Ḣ  Head; extract the first row.

DFṫ-SṭḊ  Helper link. Argument: [a, b] (integer pair)

D        Decimal; replace a and b with the digits in base 10.
 F       Flatten the resulting array of digit arrays.
  ṫ-     Tail -1; take the last two digits.
    S    Compute their sum.
      Ḋ  Dequeue; yield [b].
     ṭ   Append the sum to [b].


JavaScript (Node.js), 335 - 30 = 305 bytes
I'm not very happy with it, but let's get the ball rolling.
Takes input as a page name. Prints a list of page names, separated with linefeeds.
u=>(i=0,g=a=>(m=a.find(u=>u=='Rome'))?console.log((h=v=>g[v]==u?u:h(g[v])+`
`+g[v])(m)+`
`+m):require('https').get('https://en.wikipedia.org/wiki/'+(U=a[i++]),r=>r.on('data',s=>h+=s,h="").on("end",_=>g([...new Set([...a,...((h.match(/mw-b.*mw-d/s)||[''])[0].match(/(?<=href=".wiki.).*?(?=")/g)||[]).map(v=>(g[v]=g[v]||U,v))])]))))([u])

(Don't) try it online!
Example I/O
f("Commodore_64")

Results in:
Commodore_64
Christmas
Rome


05AB1E, 6 bytes

Code:

[Dg#à*

Uses the 05AB1E encoding. Try it online!

Explanation

[Dg#     # While the length of the number is not 1
    à    # Extract the largest element from the current number
     *   # Multiply it with the leftover number


128 years? Hypothetical leap year reform

C (gcc), 60 bytes

f(m,d,y){y-=m<3;return(y+y/4-y/128+"-bed=pen+mad."[m]+d)%7;}

Try it online!

Simple modification of Sakamoto's method. Takes input as integer arguments in the order month, day, year, and outputs the number of the day (0-indexed on Sunday).


PHP, 89 bytes, cracked by Benkerd22

<?php
$x=file_get_contents('php://stdin');
if(!preg_match('/.*golf.*/',$x))echo trim($x);

Try it online!
Outputs golf, exactly.


Solve the CodeSprint4 Leibniz code golf challenge in Python in 66 characters

Python, 65 characters

exec'print`sum((-1.)**x/(x-~x)for x in range(input()))`;'*input()


APL (Dyalog) (326 - 8 = 318)

Paste it in an editor window and call H. Input is taken from the keyboard.

H
⎕←'Source code contains invalid characters'/⍨~∧/'HhQq9+'∊⍨V←⍞
B←' of beer'
W←' on the wall'
L←⎕TC[2]
Z←{k←' bottle','s'/⍨⍵≠1⋄⍵<0:'99',k⋄⍵=0:'No',k⋄k,⍨⍕⍵}
{⍵∊'Hh':⎕←'Hello, world!'
⍵∊'Qq':⎕←V
⍵∊'9':{⎕←G,K,(G←Z⍵),B,L,(⊃'Go to the store and buy some more' 'Take one down and pass it around'[1+×⍵]),L,(Z⍵-1),K←B,W,L}¨1-⍨⌽⍳100}¨V


Answer to life, the universe, and everything

Golfscript, 20

26,{.97+\{.}*}%=42`*

with new line, 21 chars (by Nabb)

26,{).[96+]*}%n+=42`*

Actually Nabb beat mine, here is original solution for with new line, 22 chars

26,{.97+\{.}*}%n+=42`*

This is simply generating source string and just comparing it against string from stdin.


MY, 8 6 5 bytes
⍞PrH↵

Try it online!
How?

⍞ line of raw input
P basify
r convert from binary
H convert to hex
↵ output

Errors if input isn't correct.


Appease Your Google Overlords: Draw the "G" Logo

Mathematica, 229 226 225 224 221 206 169 bytes
Thanks @MartinEnder for 1 byte, @ChipHurst for 37 bytes!
Graphics[{RGBColor@{"#EA4335","#FBBC05","#34A853","#4285F4"}[[#]],{0,-1}~Cuboid~{√24,1},Annulus[0{,},{3,5},{(2#-9)Pi/4,ArcCsc@5}]}&~Array~4,ImageSize->#,PlotRange->5]&

What a fun challenge!
Explanation
...&~Array~4

Iterate from 1 to 4...
RGBColor@{"#EA4335","#FBBC05","#34A853","#4285F4"}[[#]]

Convert the color hex codes to RGBColor objects, so that they can be applied to the Google logo graphic. Change the color palette to the <input>th color.
{0,-1}~Cuboid~{√24,1}

Create a filled rectangle (2D cuboid), whose diagonal corners are (0, -1) and (sqrt(24), 1).
Annulus[0{,},{3,5},{(2#-9)Pi/4,ArcCsc@5}]}

Generate four filled quarter-Annuluss, centered at the origin, with inner radius 3 and outer radius 5. Do not draw past ArcCsc@5 (where the blue segment ends).
Graphics[ ... , ImageSize->#,PlotRange->5]

Create a graphic with size N x N, from x = -5 to x = 5 (removes the padding).
Outputs
N = 10

N = 100

N = 200

N = 10000 (click image for full resolution)


Perl, 69 66 62 56 53 bytes

Includes +1 for -p

Takes postorder followed by preorder as one line separated by space on STDIN (notice the order of pre and post). Nodes are represented as unique letters (any character that is not space or newline is OK).

inpost.pl <<< "98231 12983"

inpost.pl:

#!/usr/bin/perl -p
s%(.)(.)+\K(.)(.+)\3(\1.*)\2%$4$5$3$2%&&redo;s;.+ ;;

Using the original purely numeric format needs a lot more care to exactly identify a single number and comes in at 73 bytes

#!/usr/bin/perl -p
s%\b(\d+)(,\d+)+\K,(\d+\b)(.+)\b\3,(\1\b.*)\2\b%$4$5,$3$2%&&redo;s;.+ ;;

Use as

inpostnum.pl <<< "11,12,10,2,8,4,5,3,7 7,8,10,11,12,2,3,4,5"


Python 2, 64 69 bytes

def f(s):p=(s+s).find(s,1);return[s[~p::-1],s+s[:p]][len(s)/p%2]

Ungolfed:
def f(s):
    p = (s+s).find(s,1)
    n = len(s)/p
    return s[:p][::1|n%-2] * -~(n-1^1)

This finds the string's period, i.e. the minimal p such that s is a string of length p repeated n times (I found a golfy method on SO). Then if n is odd, it adds one more repetition of the period. If n is even, it removes one repeat of the period and reverses it.
Thanks to @Sp3000 for helping to implement the function mapping between 1<->2, 3<->4, etc.


Mathematica, 345 300 bytes

Still quite long, but I guess it's a start...

(s=StringSplit;v=Reverse;#=="|"||#=="\\"||#=="/"&[""<>s@#]&&(g={};i=0;(c={i,++j};d={i,j+1/2};e=2d-c;g=Join[g,Switch[#,"|",{d->{1,0}+d},"/",{c->c+1},"\\",{e->{i+1,j}},"_",{c->d,d->e,e->c},_,{}]])&/@Characters[++i;j=0;#]&/@{##};Sort@VertexOutComponent[Graph@g,g[[1,1]]]==Union@@List@@@g)&@@v@s[#,"
"])&

Here is a slightly ungolfed version:

(
  s = StringSplit;
  v = Reverse;
  # == "|" || # == "\\" || # == "/" &[
      "" <> s@#
      ] && (
      g = {};
      i = 0;
      (
           c = {i, ++j};
           d = {i, j + 1/2};
           e = 2 d - c;
           g = Join[g, Switch[#,
              "|", {d -> {1, 0} + d},
              "/", {c -> c + 1},
              "\\", {e -> {i + 1, j}},
              "_", {c -> d, d -> e, e -> c},
              _, {}
              ]]
           ) & /@ Characters[
          ++i;
          j = 0;
          #
          ] & /@ {##};
      Sort@VertexOutComponent[Graph@g, g[[1, 1]]] ==
       Union @@ List @@@ g
      ) & @@ v@s[#, "\n"]
) &

This defines an unnamed function which takes the string as input and returns True or False.

The basic idea is first to check that there's a single root, and then to build an actual (directed) Graph object to check if all vertices can be reached from the root. Here is how we build the graph:

Imagine an integer grid overlaid onto the ASCII art, where integer coordinates correspond to the corners of the character cells. Then on each of the cells there are six relevant points that can be connected. Here is an example, where I've also labelled the points a to f:

     |                 |
     |                 |
---(2,3)---(2.5,3)---(3,2)---
     | d      e      f |
     |                 |
     |                 |
     |                 |
     |                 |
     |                 |
     |                 |
     | a      b      c |
---(2,2)---(2.5,2)---(3,2)---
     |                 |
     |                 |

So we can build a graph whose vertices are these half-integer coordinates, and whose edges are determined by the non-space characters in the input. | connects b to e, / connects a to f and \ connects c to d. Note that these must be directed edges to ensure that we're never moving downwards while traversing the graph later. For _ we can go either way, so in theory we need four edges a -> b, b -> a, b -> c, c -> b. However, we can notice that all that matters is that there's a cycle containing all three vertices, so we can shorten this to three edges: a -> b, b -> c, c -> a.

Building this graph is quite simple in Mathematica, because any object can act as a vertex, so I can actually build a graph whose vertices are the coordinate pairs.

Finally, we check that every vertex can be reached from the root. The root's coordinate is easily found as the very first vertex we added to the graph. Then the shortest way I have found to check if all vertices can be reached is to check if the VertexOutComponent of the root (i.e. the set of all vertices reachable from the root) is identical to the set of all vertices in the graph.


Simple A* - Official score: 595

This solution uses simple A* pathfinding, with no long-term strategy - it always finds the optimal route towards just the next blue square.

var h = function(p, q) {
    // Manhattan distance.
    return Math.abs(p[0] - q[0]) + Math.abs(p[1] - q[1]);
};

var s = JSON.stringify;
var p = JSON.parse;
var walls = API.walls.map(s);
var start = API.coord;
var goal = API.goal;

var is_closed = {};
is_closed[s(start)] = 0;
var open = [s(start)];

var came_from = {};
var gs = {};
gs[s(start)] = 0;
var fs = {};
fs[s(start)] = h(start, goal);

var cur;
while (open.length) {
    var best;
    var bestf = Infinity;
    for (var i = 0; i < open.length; ++i) {
        if (fs[open[i]] < bestf) {
            bestf = fs[open[i]];
            best = i;
        }
    }

    cur = p(open.splice(best, 1)[0]);
    is_closed[s(cur)] = 1;

    if (s(cur) == s(goal)) break;

    for (var d of [[0, 1], [0, -1], [1, 0], [-1, 0]]) {
        var next = [cur[0] + d[0], cur[1] + d[1]];
        if (next[0] < 0 || next[0] >= API.width ||
            next[1] < 0 || next[1] >= API.height) {
            continue;
        }

        if (is_closed[s(next)]) continue;
        if (open.indexOf(s(next)) == -1) open.push(s(next));
        var is_wall = walls.indexOf(s(next)) > -1;
        var g = gs[s(cur)] + 1 + 10000 * is_wall;
        if (gs[s(next)] != undefined && g > gs[s(next)]) continue;

        came_from[s(next)] = cur;
        gs[s(next)] = g;
        fs[s(next)] = g + h(next, goal);
    }
}

var path = [cur];
while (came_from[s(cur)] != undefined) {
    cur = came_from[s(cur)];
    path.push(cur);
}

var c = path[path.length - 1];
var n = path[path.length - 2];
if (n[0] < c[0]) {
    API.left();
} else if (n[0] > c[0]) {
    API.right();
} else if (n[1] < c[1]) {
    API.up();
} else {
    API.down();
}


Brain-Flak, 76 68 58 52 46 bytes

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

Try it online!

Uses this relationship instead:

which is derived from this relationship modified from that provided in the sequence:

a(n+1) = a(n) * (a(n) - 1) + 1.

Explanation

For a documentation of what each command does, please visit the GitHub page.

There are two stacks in Brain-Flak, which I shall name as Stack 1 and Stack 2 respectively.

The input is stored in Stack 1.

<>(()())<>             Store 2 in Stack 2.

{                      while(Stack_1 != 0){
  ({}[()])                 Stack_1 <- Stack_1 - 1;
  <>                       Switch stack.
  ({({}[()])({})}{}())     Generate the next number in Stack 2.
  <>                       Switch back to Stack 1.
}

<>                     Switch to Stack 2, implicitly print.

For the generation algorithm:

({({}[()])({})}{}())      Top <- (Top + Top + (Top-1) + (Top-1) + ... + 0) + 1

(                  )      Push the sum of the numbers evaluated in the process:

 {            }               while(Top != 0){
  ({}[()])                        Pop Top, push Top-1    (added to sum)
          ({})                    Pop again, push again  (added to sum)
                              }

               {}             Top of stack is now zero, pop it.
                 ()           Evaluates to 1 (added to sum).

Alternative 46-byte version

This uses only one stack.

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

Try it online!


Python 3, 558 511 509 bytes

from itertools import*
E=enumerate
L=len
def s(s):
 q=[(x,y)for y,r in E(s)for x,k in E(r)if k==w]
 for i in range(1,L(q)):
  for c in combinations(q,i):
   m=[l*1for l in s]
   for p in c:
    m[p[1]][p[0]]=n
    for y,r in E([list(r) for r in' xxx ,xxxxx,xxnxx,xxxxx, xxx '.split(',')]):
     for x,k in E(r):
      o=(p[0]-x+2,p[1]-y+2)
      if k==d and-1<o[0]<L(m[0])and-1<o[1]<L(m)and m[o[1]][o[0]]==e:
       m[p[1]-y+2][p[0]-x+2]=d
   if e not in ','.join([''.join(r)for r in m]):return(m)
print(s(m))

Try it online!

It's very loopy, but I don't know enough about Python to optimize it further. I did learn some things from ovs's answer, so that was fun.

The input (modified to make it easier to write test cases) expects ' ' or 'e', while the output uses ' ', 'n' for nullifier, and 'x' for a nullified emitter. The function takes the expected input that was described in the question.

I set the e, w, n, and d variables outside because they could be easily replaced with numbers and, if the input and output were modified to use numbers as well, it would print out the same thing. I used letters because they made it more readable while working on it.

Fun question, OP! Creeper World is great and it was a cool inspiration for the question :)

Edit: -47 bytes thanks to Erik the Outgolfer


Excel Formula:), 36 chars

=SUBSTITUTE(ADDRESS(1,A1,4),"1","")

Usage:

Sorry, couldn't resist ...


Subarrays With At Least N Distinct Integers

JavaScript (ES6), 93 bytes
Saved 18 bytes thanks to @user81655
Saved 2 bytes thanks to @tsh
Expects (N)(sequence).

n=>C=a=>eval('for(i=j=a.length,c=s=0;~j;c+=c<n?(C[v=a[--j]]=-~C[v])<2:-!--C[s-=~j,a[--i]])s')

Try it online!


Counting ways of scoring k points in n games with half-points for draws

Perl 59 bytes

@0=map"$v"+($v=$u)+($u=$_),@0,0,0for(@0=1)x<>;print@0[<>*2]

Iteratively generates each row of the triangle of trinomial coefficients up to n, and then prints the correct term, 2k.

Ruby 73 bytes

r=*1
gets.to_i.times{r<<0<<u=v=0;r.map!{|t|v+(v=u)+u=t}}
p r[gets.to_f*2]

Largely equivalent to the Perl solution above.

Python 84 bytes

r=[1]
exec"r=map(sum,zip(r+[0],[0]+r,[0,0]+r))+[1];"*input()
print r[int(input()*2)]

Same method as both solutions above.

PHP 91 bytes

<?for($n=+fgets(STDIN);(${$j--}+=$$j+${$j-1})?:$n--*$j=$i+=2;${0}=1);echo${fgets(STDIN)*2};

Despite being the longest, this was actually the most fun to work on.


Smallest image containing one of every RGB color

49683 bytes

Generated by this Python code:

import struct
import zlib

width = 2 ** 16
height = 2 ** 8
bit_depth = 8
color_type = 2
compression_method = 0
filter_method = 0
interlace_method = 0
scanlines = bytes(
    ([1] + (2 ** 8) * ([2, 1, 1] + (2 ** 8 - 1) * [1, 1, 1]))
    + (2 ** 8 - 1) * ([2] + 2 ** 16 * [2, 1, 2])
)

header = struct.pack(
    "!IIBBBBB",
    width,
    height,
    bit_depth,
    color_type,
    compression_method,
    filter_method,
    interlace_method,
)
compress = zlib.compressobj(level=9, wbits=15, memLevel=9)
compressed = compress.compress(scanlines) + compress.flush()
png = b"\x89PNG\r\n\x1a\n"
for type, data in [(b"IHDR", header), (b"IDAT", compressed), (b"IEND", b"")]:
    crc = 0xFFFFFFFF
    for b in type + data:
        crc ^= b
        for k in range(8):
            crc = 0xEDB88320 * (crc & 1) ^ crc >> 1
    crc ^= 0xFFFFFFFF
    png += struct.pack("!I4s", len(data), type) + data + struct.pack("!I", crc)

print(len(png))
with open("rgb.png", "wb") as f:
    f.write(png)

Try it online!
(Note: many PNG readers accept an image missing the IEND chunk, but it is required by the PNG specification so I have included it.)


APL (Dyalog Unicode), 3 bytes

Full program. Exits with code 11 or 0. Requires ⎕IO←0.

÷?⎕

Try it online!

⎕ prompt for n

? generate random integer in range 0…n-1

÷ reciprocal (errors if argument is 0)


Mathematica (18)
Let me a little cheat
= 15char ASCII pwd

&(^F7yP8k:*1P<t

P.S. not safety :)


PHP 93 bytes

for(;$r=$g?$r+1:$g=$argv[++$i];[$g,$h[$r]]=[$h[$r],$g])$h=array_pad($h?:[],$g,0);print_r($h);

0 indexed. Uses a 2 in 1 loop that looks up the next guest after it gets a 0 (or a null form going beyond the current final room). Use like:

php -r "for(;$r=$g?$r+1:$g=$argv[++$i];[$g,$h[$r]]=[$h[$r],$g])$h=array_pad($h?:[],$g,0);print_r($h);" 1 4 3 1 2 1

Ungolfed:

for( $hotel = []; $room = $guest = $argv[ ++$i ]; )
{
    for( $hotel = array_pad( $hotel, $guest, 0 ); $guest; $room++ )
    {
        $last = $hotel[ $room ];
        $hotel[ $room ] = $guest;
        $guest = $last;
    }
}
print_r( $hotel );


Jelly, 10 6 bytes

ZŒ!ÆṭṀ

Try it online!

(4 bytes saved by @Dennis, who pointed out that Jelly had a "sum of main diagonal" builtin. I was not expecting it to have one of those; the previous solution implemented the operation without using the builtin. The operation in question, Æṭ, is defined as "trace", but the trace is only defined for square matrices; Jelly implements a generalisation to rectangular matrices too.)

The improvement over the other answers is mostly from a simpler (thus terser to express) algorithm; this program was originally written in Brachylog v2 ({\p\iᶠ∋₎ᵐ+}ᶠot), but Jelly has some builtins for parts of the program that have to be spelled out in Brachylog, so this came out shorter.

Explanation

ZŒ!ÆṭṀ
Z            Swap rows and columns
 Œ!          Find all permutations of rows (thus columns of the original)
   Æṭ        {For each permutation}, take the sum of the main diagonal
     Ṁ       Take the maximum

It should be clear that for any solution to the problem, we can permute the columns of the original matrix to put that solution onto the main diagonal. So this solution simply reverses that, finding all possible main diagonals of permutations.

Note that the "permute the columns" operation is done as "transpose, permute the rows" without bothering to transpose back; the rest of the algorithm happens to be symmetrical about the main diagonal, so we don't need to undo the transpose and thus can save a byte.


Find the absolute value of a number without built-in functions

J, 2 bytes

**

Usage:

   f =: **
   f 9.3
9.3
   f -9.3
9.3

Explanation:

This uses the * verb in both its monadic and dyadic forms. The monadic form returns -1 if it's given a negative number, 0 if it's given 0 and 1 if it's given a positive number. The dyadic form is just plain old multiplication. Putting them in a function literal turns them into a hook which gets evaluated like this: y * (*y).


Instead of using .ToString() use +"" for numerics and other types that can be natively cast to a string safely.

.ToString() <-- 11 chars
+""         <--  3 chars


Check if rectangles fill a rectangular space without gaps or overlaps

JavaScript (ES6), 249 bytes

with(Math)a=>!(a=a.map(([l,t,r,b])=>[l<r?l:r,t<b?t:b,l>r?l:r,t>b?t:b]).filter(g=([l,t,r,b])=>(r-l)*(b-t))).reduce((s,b)=>s-g(b),g([min,min,max,max].map((f,i)=>f(...a.map(a=>a[i])))))>a.some(([l,t,r,b],i)=>a.some(([m,u,s,c],j)=>i!=j&l<s&m<r&t<c&u<b))

Note: To use this, either evaluate it as a string and assign the result to a variable, or insert the assignment after the with(Math). Explanation:

with(Math)a=>!( Bring min and max into scope.
a=a.map(([l,t,r,b])=>[l<r?l:r,t<b?t:b,l>r?l:r,t>b?t:b]) Normalise the coordinates
.filter(g=([l,t,r,b])=>(r-l)*(b-t))) Remove empty rectangles, also defining a function to calculate area
.reduce((s,b)=>s-g(b), Subtract the areas of all the rectangles
g([min,min,max,max].map((f,i)=>f(...a.map(a=>a[i]))))) from the area of the bounding box
>a.some(([l,t,r,b],i)=>a.some(([m,u,s,c],j)=>i!=j&l<s&m<r&t<c&u<b)) and check that no rectangles overlap.


Print the last answerer's first submission

user, Java (OpenJDK 8), 75 bytes

interface T{static void main(String[]a){System.out.print("print(\"N\")");}}

Try it online!
My first language was Java, lol. This is my first answer. It's 1055 bytes. Have fun.
interface T{static void main(String[]a){System.out.print("The basic idea of a [tag:kolmogorov-complexity] challenge is to print a set output in the shortest code (though that meaning has changed now). We have had many of them, from [Borromean Rings](_%s/53417/ascii-borromean-rings) to [The Gettysburg Address_%s/15395/how-random-is-the-gettysburg-address). \n##Your Task\nThis % is similar, except that it requires printing of a special text - the text of this %. Specifically, the very Markdown code that I am typing right now. \nTo prevent an infinite recursion in the %, the exact text you have to print can be found [here_revisions/1f731ea3-0950-4b03-ae95-24fa812a9a28/view-source). \n##Clarifications\n- You are not allowed to use any external sources like the internet. \n- This means that the purpose of this % is not to download this % text and parse it, but instead to store it in you program. \n- This is [tag:code-golf], so shortest code in **bytes** wins!".replaceAll("_","])http://codegolf.stackexchange.com/").replaceAll("%","question"));}}


C

Must be compiled to 32bit. On 64bit machines use gcc -m32 or such.

#include <stdlib.h>

int main() {
    char *c = "echo Just another C hacker";
    int foo=123; //unused                          /* Warning: there's a
    int k=(int)1                                    * (long) system
    //now for the fun part!                         * of chinese boxes
    //behold:                                       * in this code. */
    +0;
    -1;
    ((int(*)(char *))k)(c);
}

Disclaimer: not my idea. I found it years ago hidden in some piece of code. Seriously. Theirs was even better, I forgot several little details. But the gist is there.

When you see it, you'll sh*t bricks.


Applescript
A silly, hacky mash-up that might upset some Cupertino/Mountain View folks, but I think its a creative silly, hacky mash-up.

set myNumber to text returned of (display dialog ¬
    "Enter number as text:" buttons {"Continue…"} ¬
    default answer "" default button 1)
tell application "Google Chrome"
    activate
    open location "https://www.google.com"
end tell
delay 5
say "ok google. " & myNumber
delay 2
tell application "System Events"
    tell application process "Google Chrome"
        set fullURL to value of text field 1 of toolbar 1 of window 1
    end tell
end tell
set AppleScript's text item delimiters to "="
display alert item 2 of text items of fullURL

Uses OSX text to speech to speak the text number, and google audio search to listen for it and convert it to an integer.
Requirements

OSX
Google chrome
speech-recognition enabled in your google account
volume turned up to a reasonable level

The delay timings may need to be adjusted depending on your chrome load time and google lookup time.
Example input:

Example output:


AutoHotkey, 100.5 m

After running the following script, it can be activated by pressing Windows+H (yes, it only works on Windows). It can be stopped by pressing Escape.
#SingleInstance force

Esc::ExitApp

#h::
    Loop,5 {
        Send, {w down}
        Sleep, 300
        Send, {w up}
        Sleep, 300
    }
    Loop,9999 {
        Loop, 23 {
            Send, {q down}
            Sleep, 200
            Send, {q up}
            Sleep, 400
            Send, {w down}
            Sleep, 350
            Send, {w up}
            Sleep, 400
        }
        Loop,6 {
            Send, {w down}
            Sleep, 250
            Send, {w up}
            Sleep, 400
        }
    }
return

This particular code reached the finish line the first time it was run. I don't want to test it again now, because it takes forever and I can't do anything else while running it (Please comment if you figure out how to send keys to the Flash player without it being in focus). Caveat: At around 30 m, no keys were sent for a few seconds because a Windows pop-up jacked the focus. It was tested in Chrome browser.
When the script reached the obstacle at 50 m, the script somehow jumped over it right away, which may be a lucky and unusual occurrence. As for the time, the game irritatingly does not tell you how long the run took, but it does have a built-in tiebreaker by allowing you to jump as far as possible beyond the finish line at the end.
Also, this game's code does not seem very robust:

Huh?


JavaScript (Node.js), 63 bytes

f=(a,t=1)=>a.some(v=>t%v[1])?f(a,1+t):a.map(([p,q])=>[p*t/q,t])

Try it online!

JavaScript (Node.js), 63 bytes

f=(a,t,b=a.map(([p,q])=>[m=p*t/q,o&=m%1||t],o=t))=>o?b:f(a,-~t)

Try it online!
m=p*t/q cannot be changed to p*=t/q due to floating point errors. For example, 11*15/11 is 15, but 11*(15/11) is 14.999999999999998. :(

The first answer here will output [[6, 12], [6, 12]]  for input [[2, 4], [3, 6]].
The second one will output [[1, 2], [1, 2]] for input [[2, 4], [3, 6]].

JavaScript (Node.js), 62 bytes

@Arnauld had modified the code to make it work in 62 bytes. This one would support positive fractions.

f=(a,t,o=-~t,b=a.map(([p,q])=>[p*t/q,t+=p*t%q]))=>t<o?b:f(a,o)

Try it online!


R, 106 bytes

Is not sure if is understand challenge because is has hard time reading.

function(s){u=toupper;all(strsplit(gsub("[^A-Z -']","",u(s)),"[ -]")[[1]]%in%u(scan("most used.txt","")))}

This creates an unnamed part of a computer thing that accepts a string and returns something like a true or like a not true.

Ungolfed + explanation:

partOfAComputerThing <- function(s) {
    # Remove everything but letters, spaces, dashes, and single quotes
    s <- gsub("[^A-Z -']", "", toupper(s))

    # Split s into a vector on spaces/dashes
    v <- strsplit(s, "[ -]")[[1]]

    # Read the file of words (assumed to reside in the current directory)
    m <- scan("most used.txt", "")

    # Determine if all words in the input are in the file
    all(v %in% toupper(m))
}

Thanks to Dennis for inspiration thing.


Ruby, 85 bytes

f=->l,n,s=n-l.sum-l.size+1{*a,b=l;b&&s>0?(a[0]?1+f[a,n-b-2,s-1]:(n.to_f/b).ceil-1):0}

Try it online!

Explanation

The first step is to establish a recursive divide and conquer strategy to solve subproblems.
I will use the variables \$l=[l_1,l_2,...,l_x]\$ for the list of clues, \$x\$ for the number of clues and \$n\$ for the number of cells.

Try to fit the last clue \$l_x\$:
We test the cell at \$n-l_x\$
(1) If it's empty: then all of the clues are before \$n-l_x\$.
So we lose a life and we call recursively \$1+f(l,n-l_x)\$
(2) If it's colored:
We are not sure how to place the last clue, so we test every cells to the right until finding an empty one
The worst case is finding the empty cell at the last index, we lose a life, but we have placed the last clue
so we can call recursively \$1+f(\tilde{l},n-l_x-2)\$ where \$\tilde{l}\$ is \$l\$ without the last clue.

So we can get the number of lives with this function
$$
f(l,n)=\begin{cases}
  0, & \text{if } \sum_1^xl_i+x-1 \geq n\\
  \lceil \frac{n}{l_x} \rceil - 1 & \text{if } x= 1\\
  1+\max\begin{cases}
f(l,n-l_x)\\
f(\tilde{l},n-l_x-2)
  \end{cases}, & \text{otherwise}
\end{cases}
$$

Here is an example _ are unknown, X is a known space, O is a known colored cell and L is life lost

[2,2,4] 15                  _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
(1) -> [2,2,4] 11           _ _ _ _ _ _ _ _ _ _ _ L X X X
    (1) -> [2,2,4] 7        _ _ _ _ _ _ _ L X X X L X X X
        0                   X X X L X X X L X X X L X X X
    (2) -> [2,2] 5          _ _ _ _ _ X O O O O L L X X X
        0                   O O X O O X O O O O L L X X X
(2) -> [2,2] 9              _ _ _ _ _ _ _ _ _ X O O O O L
    (1) -> [2,2] 7          _ _ _ _ _ _ _ L X X O O O O L
        (1) -> [2,2] 5      _ _ _ _ _ L X L X X O O O O L
            0               O O X O O L X L X X O O O O L
        (2) -> [2] 3        _ _ _ X O O L L X X O O O O L
            1               O O L X O O L L X X O O O O L
    (2) -> [2] 5            _ _ _ _ _ X O O L X O O O O L
        2                   O O L L X X O O L X O O O O L

It makes a binary tree, to get the number of lives lost, we just need to count the maximum height of the tree.
However this makes it \$\mathcal{O}(2^n)\$ because we evaluate all of the branches. We can do better.

Let's define a cost function \$h\$ that will help us "choose" the right branch at each step.

$$
h(l,n)=n - \sum_1^xl_i-x+1
$$

\$h\$ counts the number of superfuous spaces we have if we pack all the clues with one space in between.
So it is essentially an indicator of how much lives we are going to need to solve the instance, the higher it is,
the more lives are necessary. The idea is to apply this indicator on our recursive formula.

By definition of \$h\$ we have,
$$
\begin{align}
h(l,n-l_x) &= n - l_x - \sum_1^xl_i-x+1\\
& =(n - \sum_1^xl_i-x+1) - l_x\\
& = h(l,n) - l_x
\end{align}
$$

And,
$$
\begin{align}
h(\tilde{l},n-l_x-2) &= n - l_x - 2 - \sum_1^{x-1}l_i-(x-1)+1\\
& =(n - \sum_1^xl_i-x+1) - 1\\
& = h(l,n) - 1
\end{align}
$$

Then,
$$
h(l,n)=\begin{cases}
  \leq 0, & \text{if } \sum_1^xl_i+x-1 \geq n\\
  n - l_x, & \text{if } x=1\\
  \max\begin{cases}
h(l,n-l_x)+l_x\\
h(\tilde{l},n-l_x-2)+1
  \end{cases}, & \text{otherwise}
\end{cases}
$$

We want to maximize \$h\$ at each step to get the worst case so let's check the difference between the two expressions in the recurrence

$$
[h(l,n-l_x)+l_x] - [h(\tilde{l},n-l_x-2)+1]\\
\begin{align}
 &= n-l_x-n - \sum_1^xl_i-x+1 + l_x - [n-l_x-2 -\sum_1^{x-1}l_i-(x-1)+1+1]\\
 &=-2
\end{align}
$$

$$
\begin{align}
  [h(l,n-l_x)+l_x] - [h(\tilde{l},n-l_x-2)+1] &=-2\\
  [h(l,n-l_x)+l_x] - [h(\tilde{l},n-l_x-2)+1] &< 0\\
  [h(l,n-l_x)+l_x] &< [h(\tilde{l},n-l_x-2)+1]
\end{align}
$$
So the 2nd expression is always the max, we can remove the first one

$$
h(l,n)=\begin{cases}
  \leq 0, & \text{if } \sum_1^xl_i+x-1 \geq n\\
  n - l_x, & \text{if } x=1\\
  h(\tilde{l},n-l_x-2)+1 & \text{otherwise}
\end{cases}
$$

Finally this recursive definition of \$h\$ shows us that option (2) in function \$f\$ is always the worst case (giving the maximum number of possibilities i.e. maximizing \$h\$)

$$
f(l,n)=\begin{cases}
  0, & \text{if } \sum_1^xl_i+x-1 \geq n\\
  \lceil \frac{n}{l_x} \rceil - 1 & \text{if } x= 1\\
  1+ f(\tilde{l},n-l_x-2), & \text{otherwise}
\end{cases}
$$

Every step we decrease \$n\$ by at least 3 and there is now a single recursive call, complexity is \$\mathcal{O}(n)\$


Generate a (completely deterministic) pseudorandom bit stream


APL (Dyalog Unicode), 3 bytes

∪~∩

Try it online!

How it works

∪~∩  ⍝ Input: two sets as vectors
∪    ⍝ Set union
 ~   ⍝ Set minus
  ∩  ⍝ Set intersection

The rest is just for fun.

APL (Dyalog Unicode), 4 bytes

~∪~⍨

Try it online!

~∪~⍨
~     ⍝ Set difference (a~b)
 ∪    ⍝ Set union
  ~⍨  ⍝ Set difference reversed (b~a)

APL (Dyalog Unicode), 5 bytes

~⍨∪⍨~

Try it online!

This one is palindromic!

How it works

~⍨∪⍨~
~⍨     ⍝ Set difference reversed (b~a)
  ∪⍨   ⍝ Set union reversed
    ~  ⍝ Set difference (a~b)


Shortest Python 3 for sum of arithmetic progression

Python 3, 34 bytes

print(3**sum(range(int(input()))))

Try it online!
In Python 2 this is just print 3**sum(range(input())) for 28.


Slip, 38 27 25 bytes

S>(`=<<`P{1,5}>`P>`P*)+#E

Requires input to be padded to a rectangle such that there are spaces in every cell Mario needs to traverse (potentially with a leading line full of spaces). Prints either a string representing the valid path (which includes S, E and all the = walked on except the last) or nothing if no path exists.

Test it here.

Explanation

Slip was Sp3000's entry to our 2D pattern matching language design challenge. It's a bit like a 2D-extension of regex where you can give instructions to the engine's cursor when it's allowed or required to make left or right turns. It also has a convenient feature where you can prevent the cursor from advancing, allowing you to match a single position twice in a row (with different patterns).

Slip doesn't have something comparable to lookarounds in regex, but since you can move over any position multiple times, one can just test the condition and then return. We use this to ensure that we only jump when on the ground by moving into the ground tile after each step.

S           Match the starting position S.
>           Turn right, so that the cursor points south.
(           One or more times... each repetition of this group represents
            one step to the right.
  `=          Match a = to ensure we've ended up on ground level before.
  <<          Turn left twice, so that the cursor points north.
  `P{1,5}     Match 1 to 5 non-punctuation characters (in our case, either space,
              S or E, i.e. a non-ground character). This is the jump.
  >           Turn right, so that the cursor points east.
  `P          Match another non-ground character. This is the step to the right.
  >           Turn right, so that the cursor points south.
  `P*         Match zero or more non-ground characters. This is the fall.
)+
#           Do not advance the cursor before the next match.
E           Match E, ensuring that the previous path ended on the exit.


1. C

Contains no { or }.

#if 1
#define Q !"$&'",./=@[]^_\`|*
int WERTYUIOPASDFGHJKLZXCVBNM34567890(qwrtyuopasghjklzxcvbm)<%
	return qwrtyuopasghjklzxcvbm<2?1:WERTYUIOPASDFGHJKLZXCVBNM34567890(~-qwrtyuopasghjklzxcvbm)+WERTYUIOPASDFGHJKLZXCVBNM34567890(qwrtyuopasghjklzxcvbm-2);
%>
#endif

Try it online!

I hope I did this right.


Windows Batch (CMD), 205 204 bytes

@set/pc=
@set d=
@for %%s in (H D S C)do @for %%r in (2 3 4 5 6 7 8 9 10 J Q K A)do @call set d=%%d%% %%r%%s
@for %%c in (%c%)do @call set d=%%d: %%c=%%
@if "%d%"=="" set d= No missing cards
@echo%d%

Loops over the suits and ranks building a complete deck, then deletes the input cards. Save 1 byte if T is allowed instead of 10. Save 11 bytes if command-line arguments are acceptable input. Edit: Saved 1 byte thanks to @user202729.


Jelly, 16 11 7 bytes

_/N,‘FṀ

This approach is heavily based on @beaker's Octave answer.

Input format is Z, Y, X, with little-endian digit order, using the digit 0 for unary.

Try it online! or run all test cases.

How it works

Rather than incrementally testing potential bases, this solves the polynomial that corresponds to the array P := X + Y - Z. This returns either the largest coefficient of P ≠ 0 – which has to be a root, since there is at least one valid base – or the highest digit of X, Y and Z, incremented by 1.

_/N,‘FṀ  Main link. Argument: [Z, Y, X]

_/       Reduce by subtraction; yield Z - X - Y.
         This works since Z must have at least as many digits as X and Y.
  N      Negate to yield X + Y - Z.
    ‘    Yield [Z, Y, X], with all digits increments by 1.
   ,     Pair the results to the left and to the right.
     F   Flatten the resulting, nested list.
      Ṁ  Compute the maximum.


Original by bitpwner, Python, 5199

lambda x:eval(eval("'[encoded data, 5136 characters]'"+".decode('base64').decode('zlib')"*56))

Modified Version Python, 5198 Levenshtein Distance 2:

lambda x:eval(eval("'[encoded data, 5136 characters]'"+".decode('base64').decode('zip')"*56))

Replaced 'zlib' with shorter alias 'zip'.


05AB1E, 18 bytes

Code:

áS.u5ôJC>.bv'_y.;l

Uses the 05AB1E encoding. Try it online!

Explanation:

á                       # Remove non-letters from the input string.
 S                      # Split the result into individual characters.
  .u                    # Check if is uppercase for each character.
    5ôJ                 # Split into binary numbers of length 5.
       C                # Convert from binary to decimal.
        >               # Add one.
         .b             # Map 1 → A, 2 → B, 3 → C, ..., 25 → Y, 26 → Z.
           v            # For each letter:
            '_y.;       #   Replace the first occurrence of '_' with the current letter.
                 l      #   Convert the string to lowercase.


Divisible by 1000003? Easy, just multiply the last digit by 300001 and add!

JavaScript (ES6), 32 25 23 bytes

f=
n=>(3/(n%5*2-5)*n+1)/10
<input type=number min=1 oninput=o.textContent=this.value%5*(this.value%2)?f(this.value):``><pre id=o>

3/(n%5*2-5) would be written 9/n(mod -10) if I had access to balanced modulo division. Edit: Saved 2 bytes thanks to @EgorSkriptunoff


The answer to life, the universe, and everything

This takes about 75s on a raspberry pi overclocked to 1GHz

#!/usr/bin/env python
from itertools import product, count

for n in count(1):
    i = 0
    for a, b, c, d in product(range(n), repeat=4):
        if a > b > c > d > 0 == (a*b-c*d)%n == (a*c-b*d)%n == (a*d-b*c)%n:
            i += 1
    if i == n:
        break
print i

It works because:

  42 is the only known value that is the number of sets of four
  distinct positive integers a,b,c,d, each less than the value itself,
  such that ab-cd, ac-bd, and ad-bc are each multiples of the value.
  Whether there are other values remains an open question

http://www.mathpages.com/home/kmath255.htm


Two roads diverged in a yellow wood (part 2)

Retina, 28 bytes

\d
$*
%r`1\G
-
Os`.
+`-1

1+

Try it online!

Prints 0 for left and 1 for right. Assumes that there are not trailing spaces on any lines.

Explanation

\d
$*

Convert each digit N to a run  of N ones.

%r`1\G
-

One each line (%), match consecutive (\G)  ones from the end (r) and replace each of them with - (i.e. turn the right branch into -s).

Os`.

Sort all characters, so that all -s are directly in front of all 1s.

+`-1

Repeatedly cancel a pair of - and 1.

1+

Try to match at least one 1 (if so, there were more weights in the left path).


Jelly, 63 bytes

ḟØDOP%⁽¡ṛị“ÇṚÆ’BH+“Ḳ"ɦṀ⁷6<s¡_-¦y⁼Ḟ¡¡FPɓ‘¤÷5
fØDVȯ1×Ç
Œs>œṗ⁸ḊÇ€S

A monadic link accepting a list of characters and returning a number.

Try it online!

How?

ḟØDOP%⁽¡ṛị“ÇṚÆ’BH+“Ḳ"ɦṀ⁷6<s¡_-¦y⁼Ḟ¡¡FPɓ‘¤÷5 - Link 1, Atomic weight: list of characters
                                            -                              e.g. "Cl23"
 ØD                                         - digit yield = "0123456789"
ḟ                                           - filter discard                      "Cl"
   O                                        - cast to ordinals                [67,108]
    P                                       - product                            7236
      ⁽¡ṛ                                   - base 250 literal = 1223
     %                                      - modulo                             1121
                                        ¤   - nilad followed by link(s) as a nilad:
          “ÇṚÆ’                             -   base 250 literal  = 983264
               B                            -   convert to binary = [    1,    1,     1,     1,   0,  0,  0,   0, 0,  0,  0, 0,     1,     1,     1, 0, 0,  0,  0,   0]
                H                           -   halve             = [  0.5,  0.5,   0.5,   0.5,   0,  0,  0,   0, 0,  0,  0, 0,   0.5,   0.5,   0.5, 0, 0,  0,  0,   0]
                  “Ḳ"ɦṀ⁷6<s¡_-¦y⁼Ḟ¡¡FPɓ‘    -   code-page indexes = [177  , 34  , 160  , 200  , 135, 54, 60, 115, 0, 95, 45, 5, 121  , 140  , 195  , 0, 0, 70, 80, 155]
                 +                          -   addition          = [177.5, 34.5, 160.5, 200.5, 135, 54, 60, 115, 0, 95, 45, 5, 121.5, 140.5, 195.5, 0, 0, 70, 80, 155]
         ị                                  - index into (1-indexed and modular)
                                            -    ...20 items so e.g. 1121%20=1 so 177.5
                                         ÷5 - divide by 5                          35.5

fØDVȯ1×Ç - Link 2: Total weight of multiple of atoms: list of characters   e.g. "Cl23"
 ØD      - digit yield = "0123456789"
f        - filter keep                                                            "23"
   V     - evaluate as Jelly code                                                  23
    ȯ1   - logical or with one (no digits yields an empty string which evaluates to zero)
       Ç - call last link (1) as a monad (get the atomic weight)                   35.5
      ×  - multiply                                                               816.5

Œs>œṗ⁸ḊÇ€S - Main link: list of characters                             e.g. "C24HCl23"
Œs         - swap case                                                      "c24hcL23"
  >        - greater than? (vectorises)                                      10011000
     ⁸     - chain's left argument                                          "C24HCl23"
   œṗ      - partition at truthy indexes                          ["","C24","H","Cl23"]
      Ḋ    - dequeue                                                 ["C24","H","Cl23"]
       Ç€  - call last link (2) as a monad for €ach                  [  288,  1,  816.5]
         S - sum                                                                 1105.5


Babylon.js - loop through a scene and apply a simple fragment shader to all of the objects

In Javascript

// The suffix of all meshes wich should have the shader applied
var suffix = "shader";

//If true, the shader will be applied on this mesh
var predicate = function(mesh) {
    return (
       mesh.material
       && mesh.name.indexOf(suffix , mesh.name.length - suffix.length) !== -1
    );
};

// Creation of the shader material
var shaderMaterial = new BABYLON.ShaderMaterial("sampleShader", scene, "sample", {
            attributes: ["position"],
            uniforms: ["worldViewProjection"]
            });

// Apply the shader on all meshes
scene.meshes.forEach(function(m) {
    if (predicate(m)) {
        m.material = shaderMaterial;
    }
});


05AB1E, 5 bytes
Code:
SQγOM

Uses the 05AB1E encoding. Try it online!
Explanation:
SQ      # Check for each character if it is equal to the second input
  γ     # Split the list of zeros and ones into groups
   O    # Sum each array in the arrays
    M   # Get the maximum


Mathematica, 237 bytes

n={-1,1}#&;c_~g~s_:=Polygon[c+s#&/@{k={12,9},m=n@k,t={0,-12}}];p={#,#2~g~1,#3~g~-1}&;a=p[Cyan,#-k,#+m]&;b=p[Blue,#-t,#+k]&;c=p[Red,#-m,#+t]&;Graphics@{{a@#,b@#,c@#}&/@{j=4k,s=4{4,9},n@s,4m,r={-32,8},q=-4{4,5},4t,n@q,n@r},a@j,b@s,c@j,c@s}

Easier-to-read version:

1  n = {-1, 1} # &;
2  c_~g~s_ := Polygon[c + s # & /@ {k = {12, 9}, m = n@k, t = {0, -12}}];
3  p = {#, #2~g~1, #3~g~-1} &;
4  a = p[Cyan, # - k, # + m] &;
5  b = p[Blue, # - t, # + k] &;
6  c = p[Red, # - m, # + t] &;
7  Graphics@{
8    {a@#, b@#, c@#} & /@
9      {j = 4 k, s = 4{4, 9}, n@s, 4 m, r = {-32, 8},
10       q = -4{4, 5}, 4 t, n@q, n@r},
11   a@j, b@s, c@j, c@s}

Line 1 defines a function n that negates the first coordinate of an ordered pair. Line 2 defines a function g that produces a (roughly) equilateral triangle centered at the point c, and pointing down or up depending on whether s is 1 or -1. Line 3 defines p to be a parallelogram template consisting of a color and two triangles, and lines 4–6 define a, b, and c to be the three different specific types of parallelograms that appear in the cubes.

Line 8 defines a function {a@#, b@#, c@#}& that draws an entire cube centered at the point #; lines 9 and 10 apply that to the nine points needed to make the larger triangle. This produces nine cubes, starting at the upper right and going counterclockwise, where the later ones cover up parts of the earlier ones. Finally, line 11 redraws four parallelograms (in the upper right of the picture) so that they end up covering the later cubes as they're supposed to. The output is below: