Flexagonal flexagation Being programmers, watching us flex aren't very interesting. Today we change that! In this challenge you will lex and flex hexaflexagons.

About

For a video introduction, watch viharts video(s) on flexagons

A flexagon is a shape that you can flex to reveal faces other than the top and bottom one; we are making a hexahexaflexagon, which has 6 faces. See the image below on how to fold a hexahexaflexagon out of a strip of paper.

A shows both sides of the strip. The two white triangles are glued together.
This is how you would flex it:

Below is a diagram of possible states and their relationships:

The colored circles represent the 6 triangles with the same number from the first image. Each of the circes have two colors- the bottom most represent the back face (what you would see if you where to flip your flexagon around), which you don't have to consider in this challenge.

The gray circles in the background represent how you can flex your flexagon in any given state: there are 4 different ways to flex it, we call these Left, Right, Up and Down. You don't actually flex in these directions, the important bit is that some are opposite to each other.

If you are in the center you can use Left and Right to go to the other center ones. To get out of the center you use Up and Down. If you aren't in the center you cannot use Left or Right.

Left/Down = clockwise
Right/Up  = anti-clockwise

Challenge

Create a function or program that take as input what should be on the 18 front faces and the 18 back faces of a flexagon, a sequence of left, right, up and down flexes, and return the 8 visible faces after the flexes.

Elaborate example computation:

flex "hexaflexaperplexia"
     "flexagationdevices"
     [Right, Right, Left]

Divide a strip of paper into 18 triangles:
1/2\3/1\2/3\1/2\3/1\2/3\1/2\3/1\2/3   Front
4/4\5/5\6/6\4/4\5/5\6/6\4/4\5/5\6/6   Back

Write "hexaflexaperplexia" on the front of the paper strip:
1/2\3/1\2/3\1/2\3/1\2/3\1/2\3/1\2/3

hexaflexaperplexia
123123123123123123
h  a  e  p  p  x     Face 1, Initially the front face
 e  f  x  e  l  i    Face 2, Initially the back face
  x  l  a  r  e  a   Face 3, Initially hidden

Write "flexagationdevices" on the back of the paperstrip:
4/4\5/5\6/6\4/4\5/5\6/6\4/4\5/5\6/6

flexagationdevices
445566445566445566
fl    at    ev       Face 4, up from 3
  ex    io    ic     Face 5, up from 2
    ag    nd    es   Face 6, up from 1

Flex it [Right, Right, Left]
  The initial visible face is 1: "haeppx"
  flexing Right ..
  The current visible face is 2: "efxeli"
  flexing Right ..
  The current visible face is 3: "xlarea"
  flexing Left ..
  The current visible face is 2: "efxeli"
  flexed [Right, Right, Left]!

outputting "efxeli"

Example implementation: http://jdoodle.com/a/18A

Input and expected output:

> hexaflexaperplexia flexagationdevices RRL
= efxeli

> loremipsumdolorsit hexaflexamexicania RUU
= riuort

> abcdefghijklmnopqr stuvwxyz1234567890 UL
= I can't flex that way :(

> abcdefghijklmnopqr stuvwxyz1234567890 RRRRLLUDDUUUULDD
= uv1278

Rules

You may take input and return output in any reasonable way
If the input is impossible, you should indicate so in some way that is distinct from regular output
Standard loopholes apply
This is Codegolf. Shortest code in bytes win.


Negative Space Graphs Task

You will be given a positive integer and you must output a "self-complementary graph" with that many nodes.  If you don't know what a self-complementary graph is the wikipedia article wont help you much so below are two explanations, a technical and a non-technical one.

Non-Technical

A graph is a set of nodes that are connected by lines.  Each pair of points can be connected by one line or none.  The "complement" of a graph is the result of taking a graph and connecting all the nodes that are not connected and disconnecting all the nodes that are.

A self-complementary graph is a graph whose complement can be rearranged into the shape of the original.  Below is an example of a self-complementary graph and a demonstration of how.

Here is a graph with 5 nodes:

We will highlight the all the places where connections could go with red dotted lines:

Now we will find the complement of the graph by swapping the red and black edges:

This does not look like the original graph but if we move the nodes around like so (each step swaps two nodes):

We get the original graph!  The graph and its complement are the same graph

Technical

A self-complementary graph is a graph that is isomorphic to its complement.

Specifications

You will receive an positive integer via whatever method suits you best.  And you will output a graph in whatever method you deem appropriate,  this includes but is not limited to Adjacency Matrix Form, Adjacency List Form, and of course pictures!  The outputted graph must be its own complement and have as many nodes as the integer input.  If no such graph exists you must output a falsy value.

This is code-golf and you should aim to minimize your byte count.

Test Cases

Below are pictures of possible outputs for several n

4

5

9

Haskell, 72 bytes

f n=[(a,b)|b<-[1..n],a<-[1..b-1],mod n 4<2,mod(a+b+sum[b|odd n,a<2])4<2]

Try it online!
A belated improvement inspired by ideas from kops. Takes vertex 1 to the the special vertex in the \$n=1 \bmod 4\$ case, rather than vertex n.

Haskell, 77 bytes

f n=[(a,b)|b<-[1..n],a<-[1..b-1],mod n 4<2,mod(a+(last$b:[a|odd n,n==b]))4<2]

Try it online!
This uses an easy-to-compute explicit criterion to decide whether an edge (a,b) belongs in the graph. Instantiates this algorithm, with the permutation cycling among the values modulo 4
4*m -> 4*m+1 -> 4*m+2 -> 4*m+3 -> 4*m

We include edges whose two endpoint vertices add to 0 or 1 modulo 4. Note that cycling vertices as per this permutation adds 2 modulo 4 to the vertex sum on each each, and so swaps edges and non-edges. This gives a permutation of vertices that complements the edges.
If the graph has an extra node beyond a multiple of 4, it is put in a cycle alone. We include edges with it when then other vertex is even. Permuting the vertices flips the parity, and so the graph remains self-complementary.
If the number of vertices isn't 0 or 1 modulo 4, no self-complementary graph is possible because there's an odd number of edges in the complete graph
Overall, here are the conditions:

If the input n isn't 0 or 1 modulo 4, output an empty list
Otherwise if n is even, include all edges (a,b) with a<b and a+b equal to 0 or 1 modulo 4.
Otherwise if n is odd, do the same, but instead include edges of the form (a,n) when a is even.

The code combines the second and third cases by replacing the condition mod(a+b)4<2 with mod(a+a)4<2 when both odd n and b==n.


Fastest code to find the next prime The problem is as follows.

Input: An integer n

Output: The smallest prime bigger than n.

The challenge is to give the fastest code possible to do this.  I will test the code on values starting at size   roughly 10^8 10^200 and doubling in size until it takes more than one minute 10 seconds on my computer.

The winning code will find the next prime for the largest input size.

By way of comparison, a simple sieve written in python is able to find the next prime bigger than 10^8 in about 20 seconds.

The requirement that I can test it on my 4GB RAM ubuntu computer is strict. All code must be free (in both senses) and if it uses libraries they must also be free and easily installable. Any false primes reported will immediately disqualify the submission.

I will award separate commendations for the winners in each programming language too if the code is entirely written in that language without the use of external libraries. I will  also keep a running table of the fastest times as the competition goes on so people can see how they are doing.

Table so far

Python. An astonishing 357 digit prime 343239883006530485749095039954069660863471765007165270469723172959277159169882802606127982033072727748864815569574042901856099399985832190628701414555752857600000000000000000000000000000000000000002872284792758930912601189043411951050852357613658978971208596097634095500808832510259693761982135208603287199546795000697807728609476163156438356035166156820611 was the final number under 10 seconds using the code supplied by primo. Will anyone beat this first entry?

Python ~451 digits

This is part of the library I wrote for a semiprime factorization problem, with unnecessary functions removed. It uses the Baillie-PSW primality test, which is technically a probabilistic test, but to date, there are no known pseudoprimes – and there's even a cash reward if you're able to find one (or for supplying a proof that none exist).

Edit: I hadn't realized that Python has built-in modular exponentiation. Replacing my own for the built-in results in a performance boost of about 33%.

my_math.py

# legendre symbol (a|m)
# note: returns m-1 if a is a non-residue, instead of -1
def legendre(a, m):
  return pow(a, (m-1) >> 1, m)

# strong probable prime
def is_sprp(n, b=2):
  d = n-1
  s = 0
  while d&1 == 0:
    s += 1
    d >>= 1

  x = pow(b, d, n)
  if x == 1 or x == n-1:
    return True

  for r in range(1, s):
    x = (x * x)%n
    if x == 1:
      return False
    elif x == n-1:
      return True

  return False

# lucas probable prime
# assumes D = 1 (mod 4), (D|n) = -1
def is_lucas_prp(n, D):
  P = 1
  Q = (1-D) >> 2

  # n+1 = 2**r*s where s is odd
  s = n+1
  r = 0
  while s&1 == 0:
    r += 1
    s >>= 1

  # calculate the bit reversal of (odd) s
  # e.g. 19 (10011) <=> 25 (11001)
  t = 0
  while s > 0:
    if s&1:
      t += 1
      s -= 1
    else:
      t <<= 1
      s >>= 1

  # use the same bit reversal process to calculate the sth Lucas number
  # keep track of q = Q**n as we go
  U = 0
  V = 2
  q = 1
  # mod_inv(2, n)
  inv_2 = (n+1) >> 1
  while t > 0:
    if t&1 == 1:
      # U, V of n+1
      U, V = ((U + V) * inv_2)%n, ((D*U + V) * inv_2)%n
      q = (q * Q)%n
      t -= 1
    else:
      # U, V of n*2
      U, V = (U * V)%n, (V * V - 2 * q)%n
      q = (q * q)%n
      t >>= 1

  # double s until we have the 2**r*sth Lucas number
  while r > 0:
      U, V = (U * V)%n, (V * V - 2 * q)%n
      q = (q * q)%n
      r -= 1

  # primality check
  # if n is prime, n divides the n+1st Lucas number, given the assumptions
  return U == 0

# primes less than 212
small_primes = set([
    2,  3,  5,  7, 11, 13, 17, 19, 23, 29,
   31, 37, 41, 43, 47, 53, 59, 61, 67, 71,
   73, 79, 83, 89, 97,101,103,107,109,113,
  127,131,137,139,149,151,157,163,167,173,
  179,181,191,193,197,199,211])

# pre-calced sieve of eratosthenes for n = 2, 3, 5, 7
indices = [
    1, 11, 13, 17, 19, 23, 29, 31, 37, 41,
   43, 47, 53, 59, 61, 67, 71, 73, 79, 83,
   89, 97,101,103,107,109,113,121,127,131,
  137,139,143,149,151,157,163,167,169,173,
  179,181,187,191,193,197,199,209]

# distances between sieve values
offsets = [
  10, 2, 4, 2, 4, 6, 2, 6, 4, 2, 4, 6,
   6, 2, 6, 4, 2, 6, 4, 6, 8, 4, 2, 4,
   2, 4, 8, 6, 4, 6, 2, 4, 6, 2, 6, 6,
   4, 2, 4, 6, 2, 6, 4, 2, 4, 2,10, 2]

max_int = 2147483647

# an 'almost certain' primality check
def is_prime(n):
  if n < 212:
    return n in small_primes

  for p in small_primes:
    if n%p == 0:
      return False

  # if n is a 32-bit integer, perform full trial division
  if n <= max_int:
    i = 211
    while i*i < n:
      for o in offsets:
        i += o
        if n%i == 0:
          return False
    return True

  # Baillie-PSW
  # this is technically a probabalistic test, but there are no known pseudoprimes
  if not is_sprp(n): return False
  a = 5
  s = 2
  while legendre(a, n) != n-1:
    s = -s
    a = s-a
  return is_lucas_prp(n, a)

# next prime strictly larger than n
def next_prime(n):
  if n < 2:
    return 2
  # first odd larger than n
  n = (n + 1) | 1
  if n < 212:
    while True:
      if n in small_primes:
        return n
      n += 2

  # find our position in the sieve rotation via binary search
  x = int(n%210)
  s = 0
  e = 47
  m = 24
  while m != e:
    if indices[m] < x:
      s = m
      m = (s + e + 1) >> 1
    else:
      e = m
      m = (s + e) >> 1

  i = int(n + (indices[m] - x))
  # adjust offsets
  offs = offsets[m:]+offsets[:m]
  while True:
    for o in offs:
      if is_prime(i):
        return i
      i += o

A sample test script:

from time import clock
from my_math import *

n = i = 317**79
while True:
  i *= 317
  time1 = clock()
  n, o = next_prime(i), n
  span = clock()-time1
  if span > 10:
    break
  print(len(str(n)), span)
print(o)

A factor of 317 was chosen, because it's approximately the square root of 10000, adding roughly 2.5 digits per iteration (and because doubling was too slow to sit through). Output shows the current number of digits, and the time taken.

Sample results:

201 0.13121248650317288
203 0.059535499623555505
206 0.9157767258129175
208 0.2583420518529589
211 0.15367400046653978
213 0.32343915218274955
216 1.3962866788935466
218 0.5986165839513125
221 0.973842206202185
223 2.346910291671148
...
428 0.932809896229827
431 4.345940056627313
433 9.511724255457068
436 6.089835998709333
438 1.3793498894412721
441 4.290633027381972
443 3.5102506044762833
446 3.1629148397352083
448 3.364759208223404
451 7.34668009481652
1551197868099891386459896063244381932060770425565921999885096817830297496627504652115239001983985153119775350914638552307445919773021758654815641382344720913548160379485681746575245251059529720935264144339378936233043585239478807971817857394193701584822359805681429741446927344534491412763713568490429195862973508863067230162660278070962484418979417980291904500349345162151774412157280412235743457342694749679453616265540134456421369622519723266737913

All code is now python 3 compatible.


Calculate to how many cubes one cube can be cut Imagine some cube which we can cut into smaller cubes without remaining pieces.

Find to how many cubes a cube can be cut.

For example, a cube can be cut into 8, 27 (obviously 3rd powers of integers) and 20 (19 small cubes plus one eight times the size of the others, see image).
See here some help: http://mathworld.wolfram.com/CubeDissection.html

Program should take as input integer n (0 <= n <= 1 000) and print all numbers less or equal to n so that a cube can be cut into that number of cubes.
Suppose that cube can be cut into 1 cube and cannot into 0 cubes.

You can use only integral data-types (no arrays, objects etc) of size no greater than 64-bits.
Shortest code wins.

Mathematica, 62 bytes (or 52)

It's hardcoded answer, nothing interesting.

  If[EvenQ@BitShiftRight[164015534735101,n],Print@n]~Do~{n,1000}

This one is 52 bytes long but violates my rules - it uses large integers (powers of 2) and lists (Range).

  Select[Range@1000,EvenQ@Floor[164015534735101/2^#]&]


Solve Hitori Puzzles Introduction

Write a solver for the Hitori puzzles using least bytes.

Challenge

Your task is write a solver for the Hitori (ひとり, the word for "alone" in Japanese; the meaning of the game name is "Leave me alone") logical puzzles. The rules are as follows:

You are presented with a n-by-n grid of cells, each cell contains an integer between 1 and n (inclusive).
Your goal is to make sure that no number appear more than once in each row and each column of the grid, by removing numbers from the given grid, subject to the restriction indicated in the next two rules,
You cannot remove two numbers from two adjacent (horizontally or vertically) cells.
The remaining numbered cells must be all connected to each other. It means that any two remaining numbered cells can be connected with a curve that is composed solely of segments connecting adjacent remaining numbers (horizonally or vertically). (Thanks to @user202729 for pointing out that this is missing)

I hope the rules are clear by now. If there is anything unclear about the rules, check the Wikipedia page.

Test Cases

The cells from which the numbers are removed are represented with 0s.

Input  ->  Output

4
2 2 2 4      0 2 0 4
1 4 2 3  ->  1 4 2 3
2 3 2 1      2 3 0 1
3 4 1 2      3 0 1 2

4
4 2 4 3      0 2 4 3
4 1 1 2  ->  4 1 0 2
3 1 2 1      3 0 2 1
4 3 1 3      0 3 1 0

5
1 5 3 1 2      1 5 3 0 2
5 4 1 3 4      5 0 1 3 4
3 4 3 1 5  ->  3 4 0 1 5
4 4 2 3 3      4 0 2 0 3
2 1 5 4 4      2 1 5 4 0

8
4 8 1 6 3 2 5 7      0 8 0 6 3 2 0 7
3 6 7 2 1 6 5 4      3 6 7 2 1 0 5 4
2 3 4 8 2 8 6 1      0 3 4 0 2 8 6 1
4 1 6 5 7 7 3 5  ->  4 1 0 5 7 0 3 0
7 2 3 1 8 5 1 2      7 0 3 0 8 5 1 2
3 5 6 7 3 1 8 4      0 5 6 7 0 1 8 0
6 4 2 3 5 4 7 8      6 0 2 3 5 4 7 8
8 7 1 4 2 3 5 6      8 7 1 4 0 3 0 6

9
8 6 5 6 8 1 2 2 9      8 0 5 6 0 1 2 0 9
5 6 2 4 1 7 9 8 3      5 6 2 4 1 7 9 8 3
5 8 2 5 9 9 8 2 6      0 8 0 5 0 9 0 2 0
9 5 6 6 4 3 8 4 1      9 5 6 0 4 3 8 0 1
1 1 6 3 9 9 5 6 2  ->  0 1 0 3 9 0 5 6 2
1 1 4 7 3 8 3 8 6      1 0 4 7 0 8 3 0 6
3 7 4 1 2 6 4 5 5      3 7 0 1 2 6 4 5 0
3 3 1 9 8 7 7 4 5      0 3 1 9 8 0 7 4 5
2 9 7 5 3 5 9 1 3      2 9 7 0 3 5 0 1 0

These test cases are taken from Concept Is Puzzles, PuzzleBooks, Concept Is Puzzles, Wikipedia, and Youtube, respectively.

Specs

No need to worry about exception handling.
You can assume that the input is always a valid puzzle with a unique solution and you can take advantage of this in writing your code.
This is code-golf, the lowest number of bytes wins.
4 <= n <= 9 (16 originally, changed to 9 following Stewie Griffin's suggestion, also save some trouble in IO)
You can take input and provide output through any standard form, and you are free to choose the format.
Some suggestions for the output format are (but you are not restricted to these)

Outputting the final grid
Outputting the grid containing all removed numbers
Output a list of coordinates of one of the above

As usual, default loopholes apply here.

Related(inspired by this challenge): Check if All Elements In a Matrix Are Connected

My last challenge: Extension of the Game of Sevens


Determine your language's version Your challenge is to write a polyglot that works in different versions of your language. When run, it will always output the language version.

Rules

Your program should work in at least two versions of your language.
Your program's output should only be the version number. No extraneous data.
Your program may use whatever method you like to determine the version number. However, the output must follow rule 2; however you determine the version number, the output must only be the number.
Your program only needs to output the major version of the language. For example, in FooBar 12.3.456789-beta, your program would only need to output 12.
If your language puts words or symbols before or after the version number, you do not need to output those, and only the number. For example, in C89, your program only needs to print 89, and in C++0x, your program only needs to print 0.
If you choose to print the full name or minor version numbers, e.g. C89 as opposed to C99, it must only print the name. C89 build 32 is valid, while error in C89 build 32: foo bar is not.
Your program may not use a builtin, macro, or custom compiler flags to determine the language version.

Scoring

Your score will be the code length divided by the number of versions it works in. Lowest score wins, good luck!

Python 3.0 and Python 2, score 6

(12 bytes, 2 versions)

print(3/2*2)

Try it Online:

Python 2
Python 3

Relies on the fact that Python 3+ uses float division by default, unlike Python 2, which uses floor division.


How annoying is my Euler diagram? Challenge

Premise

Euler diagrams consist of simple closed shapes in a 2-D plane that each depict a set or category. How or whether these shapes overlap demonstrates the relationships between the sets.

I'm a spoilt brat who thinks Euler diagrams are hard to draw. For any Euler diagram, I want to know the minimum number of points where the perimeters of two shapes intersect. Here's an example:

The Euler diagram drawn above represents a relationship where:

foo and bar are disjoint.
All baz are foo but not vice versa.
Some qux are baz; some qux are foo but not baz; and some qux are bar.
Not all baz are qux; not all non-baz foo are qux; and not all bar are qux.

In this particular example you can't do better than a whopping six crossings, but that's life.

Task

Input: a sequence of multiple integers as follows.

An integer, say \$A\$, which designates a set.
An integer, say \$m\$. This means 'the set designated by \$A\$ is a proper subset of the following \$m\$ sets'.*
\$m\$ integers (except if \$m=0\$), each designating a set.
An integer, say \$n\$. This means 'the set designated by \$A\$ is equivalent to the following \$n\$ sets'.*
\$n\$ integers (except if \$n=0\$), each designating a set.
An integer, say \$p\$. This means 'the set designated by \$A\$ is a proper superset of the following \$p\$ sets'.*
\$p\$ integers (except if \$p=0\$), each designating a set.*
An integer, say \$q\$. This means 'the set designated by \$A\$ contains part but not all of each of the following \$q\$ sets'.*
\$q\$ integers (except if \$q=0\$), each designating a set.
Repeat the above until the whole system is defined.

The input format isn't fixed. The Python dict or JS object, for example, would be just as good - in such cases, the starred (*) lines wouldn't be so necessary.

Please note that the input is guaranteed not to produce 'exclaves' (as in this image, namely 'Centaurs').

Output: the minimum number of crossings, of the perimeters of two shapes, in the Euler diagram.

Example 1

Input, with bracketed remarks for your benefit:

1 (Consider the set designated by 1.)
0   (It's not a proper subset of anything.)
0   (It's equivalent to no other set.)
1   (It's a proper superset of:)
3     (the set designated by 3.)
1   (It; the set designated by 1; contains part but not all of:)
4     (the set designated by 4.)
2 (Consider the set designated by 2.)
0   (It's not a proper subset of anything.)
0   (It's equivalent to no other set.)
0   (It's not a proper superset of anything.)
1   (It contains part but not all of:)
4     (the set designated by 4.)
3 (Consider the set designated by 3.)
1   (It's a proper subset of:)
1     (the set designated by 1.)
0   (It; the set designated by 3; is equivalent to no other set.)
0   (It's not a proper superset of anything.)
1   (It contains part but not all of:)
4     (the set designated by 4.)
4 (Consider the set designated by 4.)
0   (It's not a proper subset of anything.)
0   (It's equivalent to no other set.)
0   (It's not a proper superset of anything.)
3   (It contains part but not all of:)
1     (the set designated by 1,)
2     (the set designated by 2 and)
3     (the set designated by 3.)

Output: 6

This example exactly matches the one in the section 'Premise' (set 1 would be foo, 2 bar, 3 baz, 4 qux).

Suppose we want to have the input be like a JS object instead. A possibility is:

{
 1:[[],[],[3],[4]],
 2:[[],[],[],[4]],
 3:[[1],[],[],[4]],
 4:[[],[],[],[1,2,3]]
}

Example 2

Input: 1 0 0 1 2 1 3 2 1 1 0 0 1 3 3 0 0 0 2 1 2

Output: 4

Please see here.

Suppose we want to have the input be like a JS object instead. A possibility is:

{
 1:[[],[],[2],[3]],
 2:[[1],[],[],[3]],
 3:[[],[],[],[1,2]]
}

Remarks

This is code-golf, so fewest bytes wins.
Standard rules, I/O rules and loophole rules apply.
If possible, link an online demo of your code.
Please explain your code.

MATLAB - 109 Bytes
Try it online
function n=E(s)
i=2;k=1;n=0;while i<numel(s)
k=mod(k,4)+1;n=n+s(i)*((k==1)-(k==3)/2);i=i+s(i)+1+(k<2);end

ungolfed:
function n=E(s)             % function def, input 2 and output n
i=2;                        % sequence index
k=1;                        % 1=sub,2=equivalent,3=super,4=part
n=0;                        % initialized output
while i<numel(s)            % Loop through sequence
k=mod(k,4)+1;               % if k==4, then a new set has started, so back to 1.
n=n+s(i)*((k==1)-(k==3)/2); % s(i) represents n,m,p,q
                            % If k==1, then s(i)=q, so add s(i) to n.
                            % If k==3, s(i)=m, so subtract s(i)/2 from n.
i=i+s(i)+1+(k<2);           % Advance index by (n,m,p,q) and 1 if k==1 (aka k<2) to skip set number definition.
end                         % end

Explanation:
This may be a naive approach, but from what I see, the only way to have a perimter intersection is when you have a set as a part of another.
For super/subsets, there will be no perimeter intersections, since they will be concentric.
For sets that match exactly, there will only be one shape that represents two sets, so there are no perimeter crossings between them.
Therefore, the only time you can have an overlap is for parts. From there it is simple: every crossing includes two points, since by the nature of overlapping rectangles, there will be two and only two intersections of the perimeters. And since the sets that contain parts of another must reference each other (i.e. if set 1 and 2 overlap, set 1 will have 2 in its part input, and 2 will have 1), there will be 2*(number of sets that are part of another). However, sets that are exactly equal only produce one shape, so any crossings between this shape and another must be reduced according to the number of sets that are equivalent. Thus, the sum of the number of elements that fall into the "parts" category across all sets equals the number intersections.
Mathematically,
For \$k\$  sets
\$ n_{crossings} = \displaystyle \sum_{i=1}^k(q_i - m_i/2) \$


Raindrops are falling on my... glasses? I live in the UK, where it rains. A lot. I also have the unfortunate necessity to need to wear glasses to see, which means that when it rains (as it is now), I can barely see out of them. This challenge is so that you can all experience the same!

Task

Output ASCII art glasses with a drop of water added each second.

Input

None

Output

A pair of glasses with drops of water on them.

Glasses

 ________________________
|          /__\          |
|         /    \         |
|        /      \        |
\_______/        \_______/

Raindrops

A raindrop is denoted by a .. A raindrop is randomly placed on the glasses' lenses. So when a raindrop is placed, the glasses might look like this

 ________________________
|          /__\          |
|    .    /    \         |
|        /      \        |
\_______/        \_______/

If it is placed on a blank space (), an . is placed on the image. If it is placed on a square which already has a raindrop, the drop graduates.

The steps on drops are

no drops placed:
1 drop placed: .
2 drops placed: o
3 drops placed: O
4+ drops placed: @

Rules

The image should look as though it stays in place. This means that you can either clear the screen or print enough newlines to "clear" the screen. You cannot return a list of steps. Sorry about this, but you should be able to work around that.
When outputting newlines to "clear" the screen, you must have at least 3 newlines between the glasses.
The code runs until the glasses are full of fully graduated drops i.e. until the output looks like this:

     ________________________
    |@@@@@@@@@@/__\@@@@@@@@@@|
    |@@@@@@@@@/    \@@@@@@@@@|
    |@@@@@@@@/      \@@@@@@@@|
    \_______/        \_______/

Shortest code in bytes wins.

JavaScript (ES6), 269 267 265 bytes

document.write('<pre id=o>')
a=[...` _8_8_8
| 9 /__\\  9|
| 9/ 4\\ 9|
| 8/ 6\\ 8|
\\_7/ 8\\_7/`.replace(/.\d/g,s=>s[0].repeat(s[1]))]
s=" .oO@@"
g=_=>o.innerHTML=a.join``
f=(i=s.indexOf(a[j=Math.random()*a.length|0])+1)=>i?g(a[j]=s[i]):f()
g()
setInterval(f,1e3)

Edit: Saved 2 4 bytes thanks to @Shaggy.


Prime parity peregrination The purpose of this challenge is to graphically depict a walk on the plane, where the direction of each step \$k\$ is determined by the primality of \$k\$ and the parity of its binary expansion. Specifically,

Initial direction is fixed, say North.
All steps have the same length.
The direction of step \$k\$ can be North, West, South or East, and is determined as follows:

If \$k\$ is not prime, the direction does not change.
If \$k\$ is prime and the binary expansion of \$k\$ has an even number of ones, turn right.
If \$k\$ is prime and the binary expansion of \$k\$ has an odd number of ones, turn left.

As a worked example, assume that the initial direction is North. The first steps are:

\$k=1\$ is not prime. So we move one step in the current direction, which is North.
\$k=2\$ is prime, and its binary expansion, 10, has and odd number of ones. So we turn left, and are now facing West. We move one step in that direction.
\$k=3\$ is prime, and its binary expansion, 11, has and even number of ones. So we turn right, and are now facing North. We move one step in that direction.
\$k=4\$ is not prime. So we move one step in the current direction, which is North.

The challenge

Input: positive integer \$N\$.

Output: plot of the \$N\$-step walk as defined above.

Additional rules

The initial direction can be freely chosen (not necessarily North), but should be the same for all \$N\$.
The turning rule can be the opposite to that described above, that is, turn right for odd parity and left for even; but it has to be the same for all \$N\$.
The output has to be a graphical depiction of the walk. For instance:

The walk can be drawn with line segments.
The visited points can be shown with a marker, such as a dot; with or without connecting line segments.
A two-colour raster image can be provided, with one colour corresponding to visited points and another for non-visited.

The scales of the horizontal and vertical axes need not be the same. Also axis labels and similar elements are optional. As long as the walk can be clearly seen, the plot is valid.
Note that some points are visited more than once. The plot is not sensitive to this. For instance, if line segments are shown in the plot, each unit segment is displayed the same no matter how many times it has been traversed.
The code should work for any N given unlimited resources. It is acceptable if in practice it fails for large N due to time, memory or data-type limitations.
Input and output are flexible as usual. In particular, any of the standard means for outputting images can be used.
The shortest code in bytes wins.

Test cases

The following plots use North as initial direction; even parity turns right; and the walk is depicted with line segments.

N = 7:

N = 3000:

N = 20000:

N = 159000:

N = 1200000:

N = 11000000:

MATL, 25 24 21 bytes
Q:qJyZpbB!sEq*^YpYsXG

Try it at MATL online
Thanks @LuisMendo for a nice golfing session in chat that ultimately led to this 21 byte version, by suggesting Eq*^
Explanation
Q:q % Push 0:n
J   % Push 1i for later use.
y   % Duplicate 0:n from below
Zp  % Vector result of isprime()
b   % Bubble 0:n from bottom of stack
B!s % Sum of bits in binary representation
Eq  % Double minus one to get an odd number
*   % Multiply by isprime result to get either zero or aforementioned odd number
^   % Exponentiate 1i by an odd number or zero to get -i, 1 or i (corresponding to left turn, straight ahead, right turn).
Yp  % Cumulative product to get a vector of directions
Ys  % Cumulative sum to get vector of positions
XG  % Plot

Example for \$k=12345\$:


Product of digit runs We seem to quite like digit runs lately, so here's a fairly simple challenge.

Given a positive integer, split it into it's digit runs, and return the product.

For example:

11122333 would become 111, 22, 333, the product of which is 813186

Input may be taken as an integer, string, or list/array of digits/characters. Your entry must work for any number within it's representable range. I have tested this for 32-bit integers (2^32-1 max value) and the largest possible result I have found is 1099999989 from 1199999999, which is also within the 32-bit integer range. I have yet to find a number who's output is larger than the input.

For the purposes of this challenge, runs of length 1 are not counted.

If there is only 1 run, return the run. If there are no runs, do anything (undefined behaviour)

Standard I/O rules apply, output can be given as an integer or string.

Testcases

11122333 -> 813186
1112333 -> 36963
1122855098 -> 13310
98776543 -> 77
1000000 -> 0
123456789 -> undefined
1 -> undefined
99445662 -> 287496
1199999999 -> 1099999989
999999999 -> 999999999

Scoring

This is code-golf so fewest bytes in each language wins!

Haskell, 63 55 bytes

Since no one has done Haskell yet here's my take on it.  Takes a string as input (of course).

import Data.List
f s=product[read x|x@(_:_:_)<-group s]

Try it online!

This code almost looks as if it is not golfed, but I cannot find anyway to make it shorter.


Wanna be an Alchemist Wanna be an Alchemist

I've been watching Full Metal Alchemist these past days and I've been wondering, It is really possible to trans-mutate matter? In the real world, I don't know if it is possible, but in the machine world, we think we "can".

Problem

Your task is, Given an input of N chemical elements (K, Mg, C, O, etc...), you are going to:

Get the first letter of the element
Convert that letter into binary
Rotate 2 bits to the right
Apply Binary Addition
If the result is more that 8 bits then get the one's complement of the result and removes the highest bit
Output the ASCII (ISO 8859-1) representation of the result

Example

Given Chemical Elements: (K, Ca, Mg)

Get the first letter of the element

K, C, M

Convert that letter into binary

K => 01001011, C => 01000011, M => 01001101

Rotate 2 bits to the right

K => 11010010, C => 11010000, M => 01010011

Sum bits

K => 11010010 +
 C => 11010000 +
 M => 01010011 = 111110101
If the result is more that 8 bits then get the one's complement and removes the highest bit

00001010

Output the ASCII representation of the result.
Result:

Test Cases

(H, Mn, C) =>  Ê

(I, H, Se) =>  Ç

(K, Ca, Mg) =>

This is code golf so the shortest answer wins

Python 2, 78 bytes

e=sum(ord(e[0])/4+ord(e[0])%4*64for e in input());print chr([e,~e][e>255]%256)

Try it online!

-8 bytes thanks to Jonathan Frech


Drawing a cube in ASCII art Task description:

Draw a cube in ASCII art in roughly a cabinet projection.

Monospaced fonts often have characters that are about twice as high as they are wide. Since the input is the length of the vertical lines (excluding the corners), horizontal lines are drawn with twice as many characters so that the resulting image is really roughly a cube. The receding lines are drawn at half the length as mandated by a cabinet projection.

Corners of the cube are represented by +, horizontal lines by -, vertical lines by | and diagonal ones use /.

Summarizing: Let the input be n, then

A horizontal edge of the cube are drawn with - and consists of 2 n characters.
A vertical edge of the cube are drawn with | and consists of n characters.
A diagonal edge of the cube are drawn with / and consists of n/2 characters.
Corners of the cube are drawn with +. Corners are not counted for the length of an edge as detailed above (see examples below as well).

Input:

The input, given on standard input, is a single positive, even number n (2 ≤ n ≤ 30) that gives the length of the vertical lines of the cube. It is followed by a single line break.

Output:

The output is a cube on standard output following above rules. Trailing whitespace on the lines is ignored.

Sample input 1:

2

Sample output 1:

  +----+
 /    /|
+----+ |
|    | +
|    |/
+----+

Sample input 2:

4

Sample output 2:

   +--------+
  /        /|
 /        / |
+--------+  |
|        |  |
|        |  +
|        | /
|        |/
+--------+

ETA: I now accepted the shortest solution. I will update the accepted answer when a shorter one comes along.

Since some people asked how long the entries of our contestants were:

  227 – Python
  240 – Perl
  310 – C
  315 – C
  326 – VB.NET
  459 – C

As well as our own solutions (not ranked with the others):

  140 – Golfscript
  172 – Ruby
  183 – PowerShell

Python - 248 243 230 227 191

Slightly messy but it basically prints the cube line by line(using a string buffer).

t=v=h=input()/2
s,p,b,f,n=" +|/\n"
l=p+"-"*t*4+p;S=s*4*t;k=s*h;K=b+S+b
r=s*t+s+l+n
while t:r+=s*t+f+S+f+s*(h-t)+b+n;t-=1
r+=l+k+b+n+(K+k+b+n)*(v-1)+K+k+p+n
while v:v-=1;r+=K+s*v+f+n
print r+l

Thanks to @marcog, for pointing out the first line, @ThomasO for pointing out the second line and to @Juan for making me realise I can combine lines.


Shortest code to throw SIGILL Background

We already have a challenge about throwing SIGSEGV, so why not a challenge about throwing SIGILL?

What is SIGILL?

SIGILL is the signal for an illegal instruction at the processor, which happens very rarely. The default action after receiving SIGILL is terminating the program and writing a core dump. The signal ID of SIGILL is 4. You encounter SIGILL very rarely, and I have absolutely no idea how to generate it in your code except via sudo kill -s 4 <pid>.

Rules

You will have root in your programs, but if you don't want to for any reasons,  you may also use a normal user. I'm on a Linux computer with German locale and I do not know the English text which is displayed after catching SIGILL, but I think it's something like 'Illegal instruction'. The shortest program which throws SIGILL wins.

PDP-11 Assembler (UNIX Sixth Edition), 1 byte
9

Instruction 9 is not a valid instruction on the PDP-11 (in octal, it would be 000011, which does not appear on the list of instructions (PDF)). The PDP-11 assembler that ships with UNIX Sixth Edition apparently echoes everything it doesn't understand into the file directly; in this case, 9 is a number, so it generates a literal instruction 9. It also has the odd property (unusual in assembly languages nowadays) that files start running from the start, so we don't need any declarations to make the program work.
You can test out the program using this emulator, although you'll have to fight with it somewhat to input the program.
Here's how things end up once you've figured out how to use the filesystem, the editor, the terminal, and similar things that you thought you already knew how to use:
% a.out
Illegal instruction -- Core dumped

I've confirmed with the documentation that this is a genuine SIGILL signal (and it even had the same signal number, 4, all the way back then!)


Display OEIS sequences The On-Line Encyclopedia of Integer Sequences (OEIS) is an online database of integer sequences. It contains nearly 280000 sequences of mathematical interest.

Examples of sequences:

positive integers (A000027)
prime numbers (A000040)
Fibonacci numbers (A000045)

Your task is to write a program or function that displays as many OEIS sequences as you can, with a source code of 100 bytes maximum. Your program should accept as input the sequence id (without the prepending A and the zeroes), and output the 20 first numbers in that sequence.

You are not allowed to fetch the data directly from the OEIS website; all sequences must be computed by your code.

Scoring

Score is the number of OEIS sequences the program can display.
Answers will have to list the IDs of the sequences recognised by their program.

Example

Here's a valid answer in Java 8:

(int a) -> {
    for (int i = 0; i < 20; i++) {
        System.out.println(a==27?i+1:i*i);
    }
};

This program can display the positive integers (A000027 - input 27) and the squares (A000290 - input 290), thus its score is 2.

Note

Please avoid scraping the whole OEIS website :-) you can download the sequence names (about 3 megs) or sequence values (about 9 megs). Note that this download is covered by the OEIS End-User License Agreement.

Python 2, 875 sequences

print', '.join('%020d'%(10**20/(input()-21004)))

Works for 875 of the sequences 21016 (decimal digits of 1/12) through 21999 (decimal digits of 1/995).

I found this chunk with the sophisticated search algorithm of haphazardly typing in sequence id's by hand. Some of the sequences in the range are not of this format and appear elsewhere (thanks to Mitchell Spector for pointing this out). For example, 21021 is not the expansion of 1/17.

Even with the interruptions, the sequences for 1/n appear as id n+21004. The remainder is not shifted, but the missing sequences appear elsewhere. For example, 1/17 appears as 7450.

I counted the ones that match using a downloaded copy of the sequence names.

A different block gives 848 sequences from 16742 to 17664.

n=input()-16729
for i in range(20):k=n/12;a=int((8*k+1)**.5/2+.5);print(a*i+k-a*(a-1)/2)**(n%12+1)

These all have form n -> (a*n+b)^c, where 2≤a≤12, 0≤b<a, 1≤c≤12. The code extracts the coefficients via inverting triangular numbers and moduli. As before, not all sequences in the range match. If these two expressions could fit in 100 bytes, it would give 1723 sequences.

Promising chunks:

1929 matching sequences: 41006 through 42397, numerators and denominators of continued fraction convergents.
~3300 matching sequences: 147999 to 151254: counts of walks on Z^3, if you can find how the vector lists are ordered.

Here are categories for other potential chunks, via grouping the OEIS sequence names by removing all numbers (digits, minus sign, decimal point). They are sorted by number of appearances.

3010    Number of walks within N^ (the first octant of Z^) starting at (,,) and consisting of n steps taken from {(, , ), (, , ), (, , ), (, , ), (, , )}
2302    Number of reduced words of length n in Coxeter group on  generators S_i with relations (S_i)^ = (S_i S_j)^ = I
979     Primes congruent to  mod
969     Numerators of continued fraction convergents to sqrt()
967     Denominators of continued fraction convergents to sqrt()
966     Continued fraction for sqrt()
932     Decimal expansion of /
894     Duplicate of A
659     Partial sums of A
577     Divisors of
517     Inverse of th cyclotomic polynomial
488     Expansion of /((x)(x)(x)(x))
480     Decimal expansion of th root of
471     Number of nX  arrays with each element x equal to the number its horizontal and vertical neighbors equal to ,,,, for x=,,,,
455     First differences of A
448     Decimal expansion of log_ ()
380     Numbers n such that string , occurs in the base  representation of n but not of n+
378     Erroneous version of A
375     Numbers n such that string , occurs in the base  representation of n but not of n
340     Numbers n with property that in base  representation the numbers of 's and 's are  and , respectively

35 sequences:

c=input()
for n in range(20):print[(c-1010)**n,(c-8582)*n][c>2e3]

Works from 8585 (multiples of 3) through 8607 (multiples of 25), and 1018 (powers of 8) through 1029 (powers of 19). Conveniently, these are all in one chunk ordered by id.

This uses only 65 of the 100 allowed bytes and isn't fully golfed yet, so I'll look for another nice chunk.


Fishing for Cube Nets Cubes can be made of six squares as sides. But you could also fold three 2x1 rectangles in half and glue them together to form a cube. Now in this challenge you get a set of pieces which are each made from squares, and you have to determine whether you can choose pieces to form a unit cube. Not all of the pieces have to be used, there might be some left over.
Details
The pieces are given as a string of two different characters or a black and white image or any convenient 2D raster format. In the following I assume the pixels that form the pieces are black, and the background is in white.
Two pixels who share a side are considered to belong to the same piece. The pieces can only be folded along the gridlines that separate the pixels, and they cannot be cut. Each side of the cube has the size of one pixel, and each side of the cube can only be made of a single layer.
The output must be a truthy or falsey value.
Testcases
In the following, the spaces   are background and hash symbols # represent the pieces.
(more to be added)
Valid
##
 ##
  ##

 #
####
 #

# # # # # # #

# ##
## #

Invalid
###
###

#  #
####

### ## ####

Run the following snippet for more testcases.

document.getElementById("asdfasdf").style.display = "block";

Valid

    ##
     ##
      ##

     #
    ####
     #

    # # # # # # #

    # ##
    ## #

    #   #
    ###
      #

Invalid

    ###
    ###

    #  #
    ####

    ### ## ####

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

PS: This is a generalization of this challenge

C, 824 803 bytes

#define Z return
#define Y char*b
#define N --n
i,j,n,w,h,A,B,C,D,E,F,G,H;char c[9999],*r,*d;x(b)Y;{if(b<c||*b<35)Z;++n;*b^=1;x(b-1);x(b+1);x(b-w);x(b+w);}m(b,p,y)Y,*p;{d=b;if(!y)for(y=-1,--p;1[++p]&31;)d+=w;for(i=0;*p&31?!(*p&16>>i)||b[i]&1:0;++i>4?p+=y,b+=w,i=0:0);Z!(*p&31)?x(d),n:0;}a(b)Y;{for(j=n=0;j<w*h;++j)if(m(c+j,b,1)||m(c+j,b,0))Z n;Z 0;}f(Y){bzero(c,9999);for(h=0,b=strcpy(c,b);r=b,b=strchr(b+1,10);h++,w=b-r);for(A=2,r=1+"@_`^C@|T@^R@XO@XX`|FB@|PP@|DD@PXN@XHX@XPX`PPXL@XHHX@XLDD@XPPX`PPPXH@PXHHH@PPPPP@";*r;r+=A+=r[-1]/96)while(a(r));A=B=C=D=E=F=G=H=0;while(a("PX")||a("XH")) (n-=3)?N?N?N?0:++H:++G:++F:++C;while(a("^")||a("PPPP"))(n-=4)?N?N?0:++H:++G:++E;while(a("P"))N?N?N?N?N?N?0:++H:++G:++F:++D:++B:++A;Z H||(G&&A)||(F&&B+B+A>1)||(E&&A>1)||D>1||C>1||((D||C)*3+B*2+A>5)*(A>1||B>2||A*B);}

  Note: Includes a bug fix (the previous entry falsely identified a tromino and two dominoes as forming a cube).
  In the TIO driver code, there are more test cases and there's now a pass/fail tracker; hexomino test cases were updated with the expected pass/fail value in the label.

Try it online!

...and before explaining this in detail, it's worth a high level overview.

Basic Overview

This algorithm applies a pattern matcher to classify each polyomino it finds with a given pattern as its subset.  As polyominoes are matched they are "unmarked", excluding them from pattern matching again.  The initial classification given by the matcher is simply a count of the number of tiles in the polyomino.

The matcher is applied first to cull out all polyominoes that cannot be folded onto a cube; the classification of these polyominos is discarded.  The match succeeds if these polyominoes appear within higher level ones; therefore, we only care about the smallest subset of "unfoldable" for each class.  Shown here along with padded encodings are all such polyominoes (excluding their vertical reflections).  The encoding uses bits 4-0 of each character to represent squares on each row:

[^C```] [XHX``] [PPPXH] [XHHX`] [PXN``] [|PP``]
 ####.   ##...   #....   ##...   #....   ###..
 ...##   .#...   #....   .#...   ##...   #....
 .....   ##...   #....   .#...   .###.   #....
 .....   .....   ##...   ##...   .....   .....
 .....   .....   .#...   .....   .....   .....
[|FB``] [XPX``] [PPXL`] [XLDD`] [XPPX`] [|DD``]
 ###..   ##...   #....   ##...   ##...   ###..
 ..##.   #....   #....   .##..   #....   ..#..
 ...#.   ##...   ##...   ..#..   #....   ..#..
 .....   .....   .##..   ..#..   ##...   .....
 .....   .....   .....   .....   .....   .....
[|T```] [^R```] [PXHHH] [XO```] [_````] [PPPPP]
 ###..   ####.   #....   ##...   #####   #....
 #.#..   #..#.   ##...   .####   .....   #....
 .....   .....   .#...   .....   .....   #....
 .....   .....   .#...   .....   .....   #....
 .....   .....   .#...   .....   .....   #....

[XX```]
 ##...
 ##...
 .....
 .....
 .....

Once these polyominoes are culled, we categorize the remaining polyominoes into relevant categories.  It's worth noting that in almost all cases, one can just find polyominoes that remain (those foldable onto cubes) and simply search for sums of six.  There are two exceptions:

A corner tromino and a line tromino cannot form a cube
A line tetromino and a domino cannot form a cube

In order to be able to accommodate this restriction we form 8 categories, from A-H: A for monominoes (lone tiles), B for dominoes, C for corner trominoes, D for line trominoes, E for line tetrominoes, F for other tetrominoes, G for pentominoes, and H for hexominoes.  Anything not falling into one of these categories is just ignored.  Counting polyominoes that fall into each category suffices.

At the end, we just return truthiness or falsiness based on a giant equation and these tabulations.

Ungolfed with comments

i,j,n,w,h,A,B,C,D,E,F,G,H;char c[9999],*r,*d;
x(b)char*b;{      // recursively unmarks polyomino pointed to by b.
   if(b<c||*b<35)return;
   ++n; *b^=1;    // Tabulates tiles in n as it goes.
   x(b-1);x(b+1);x(b-w);x(b+w); // left/up/down/right
}
m(b,p,y)char*b,*p;{ // pattern match area b with pattern p, direction y.
                    //   y=1 scans down; y=0 scans up.
   d=b; // d tracks a tile in the currently matched pattern for unmarking.
        // Note that all patterns are oriented to where "top-left" is a tile.
   if(!y) // ...when scanning up, move p to the end, set y to -1 to count backward,
          //    and advance d to guarantee it points to a tile (now "bottom-left")
      for(y=-1,--p;1[++p]&31;)d+=w;
   // Match the pattern
   for(i=0;*p&31?!(*p&16>>i)||b[i]&1:0;++i>4?p+=y,b+=w,i=0:0);
   return !(*p&31)   // If it matches...
          ? x(d),n   // ...unmark/count total polyomino tiles and return the count
          : 0;
}
a(b)char*b;{ // Scan for an occurrence of the pattern b.
   for(j=n=0;j<w*h;++j)
      if(m(c+j,b,1)||m(c+j,b,0)) // (short circuit) try down then up
         return n;
   return 0;
}
// This is our function.  The parameter is a string containing the entire area,
// delimited by new lines.  The algorithm assumes that this is a rectangular area.
// '#' is used for tiles; ' ' spaces.
f(char*b) {
   bzero(c,9999); // Init categories, c buffer
   for(h=0,b=strcpy(c,b);r=b,b=strchr(b+1,10);h++,w=b-r); // Find width/height
   // Unmark all polyominoes that contain unfoldable subsets.  This was
   // compacted since the last version as follows.  A tracks
   // the current pattern's length; r[-1], usually terminator for the
   // previous pattern, encodes whether the length increases; and o/c
   // the patterns were sorted by length.
   for(A=2,r=1+"@_`^C@|T@^R@XO@XX`|FB@|PP@|DD@PXN@XHX@XPX`PPXL@XHHX@XLDD@XPPX`PPPXH@PXHHH@PPPPP@";*r;r+=A+=r[-1]/96)
      while(a(r));
   A=B=C=D=E=F=G=H=0;
   // Match corner trominoes now to ensure they go into C.
   while(a("PX")||a("XH"))
      (n-=3)
         ?   --n
             ?   --n
                 ?   --n
                    ?   0 // More than 6 tiles?  Ignore it.
                    : ++H // 6 tiles?  It's an H.
                 : ++G // 5 tiles?  It's a G.
             : ++F // 4 tiles?  It's an F.
        : ++C; // only 3 tiles?  It's a C.
   // Now match line tetrominoes to ensure they go into E.
   while(a("^")||a("PPPP"))
      (n-=4)
         ?   --n
             ?   --n
                 ?   0 // More than 6 tiles?  Ignore it.
                 : ++H // 6 tiles?  It's an H.
             : ++G // 5 tiles?  It's a G.
         : ++E; // only 4 tiles?  It's an E.
   // Find all remaining tetrominoes ("P" is a monomino pattern)
   while(a("P"))
      --n
         ?   --n
             ?   --n
                 ?   --n
                     ?   --n
                         ?   --n
                             ?   0 // More than 6 tiles?  Ignore it.
                             : ++H // 6 tiles?  It's an H.
                         : ++G // 5 tiles? It's a G.
                     : ++F // 4 tiles?  It's an F.
                : ++D // 3 tiles?  It's a D.
            : ++B // 2 tiles?  It's a B.
         : ++A; // only 1 tile? It's an A.
   // Figure out if we can form a cube:
   return H               // Yes if we have a foldable hexomino
      ||(G&&A)            // Yes if we have a foldable pentomino
                          // and a monomino
      ||(F&&B+B+A>1)      // Yes if we have a foldable non-line tetromino
                          // and 2 other tiles (dominoes count twice).
                          // Either one domino or two monominoes will do.
      ||(E&&A>1)          // Yes if we have a foldable line tetromino (E)
                          // and two monominoes (A).  Note we can't make a
                          // cube with a line tetromino and a domino (B).
      ||D>1               // Yes if we have two line trominoes
      ||C>1               // Yes if we have two corner trominoes
      ||((D||C)*3+B*2+A>5)
                          // Any combination of trominoes, dominoes, monominoes>6,
                          // where trominoes are used at most once
                          // (via logical or)...
         * (A>1||B>2||A*B)
                          // ...times this includer/excluder fudge factor
                          // that culls out the one non-working case;
                          // see table:
                          //
                          // Trominos Dominos Monomos Cube  A>1 B>2 A*B
                          //    1        0       3+    yes   Y   N   0
                          //    1        1       1+    yes   Y   N   1
                          //    1        2       0     no    N   N   0
                          //    0+       3       0+    yes   Y   Y   1
      ;
}


Generate N number of "Go First" dice Background

As described here http://www.ericharshbarger.org/dice/#gofirst_4d12, "Go First" Dice is a set of four dice, each with unique numbering, so that:

There will never be a tie. Each die has a unique set of numbers.
Regardless of what subset of dice are rolled against one another, each player will always have an equal chance of rolling the high number.

Here is the specific numbering for the four dice mentioned, as an example:

DICE COUNT: 4
FACE COUNT: 12
D1: 1,8,11,14,19,22,27,30,35,38,41,48
D2: 2,7,10,15,18,23,26,31,34,39,42,47
D3: 3,6,12,13,17,24,25,32,36,37,43,46
D4: 4,5, 9,16,20,21,28,29,33,40,44,45

(via)

Goal

Without requiring any particular result, I would like to be able to generate a set of N "Go First" dice... Such that, example output might look like so (formatted, python console):

    >>> generate_dice(players=4)
    [[1,8,11,14,19,22,27,30,35,38,41,48],
     [2,7,10,15,18,23,26,31,34,39,42,47],
     [3,6,12,13,17,24,25,32,36,37,43,46],
     [4,5,9,16,20,21,28,29,33,40,44,45]]

The number of sides here is chosen just for example purposes, because it matches the other example given. The number of sides of the dice can be determined by the algorithm used.

Ideally the solution would be in Python, but I can also read PHP, Javascript, some Ruby, quite well.

I'm honestly puzzling over this, and would love to understand what terminology/math I should have studied to figure this out. I've tried to explain it before, but seem to be having trouble not using words that imply too many things about what should be generated, and what odds should be, etc. I'm specifically interested in being able to generate "a set of N 'Go First' dice".

Extra

Here's some ugly python, to "prove" the dice, and perhaps give an example.

def fair_chance(die1, die2):
    wins = 0
    losses = 0
    ties = 0
    for i in die1:
        for x in die2:
            if cmp(i, x) < 0:
                losses += 1
            if cmp(i, x) > 0:
                wins += 1
            if cmp(i, x) == 0:
                ties += 1
    if wins == losses and losses != 0 and ties == 0:
        return True
    return False

Give the above example dice:

D1 = [1,8,11,14,19,22,27,30,35,38,41,48]
D2 = [2,7,10,15,18,23,26,31,34,39,42,47]
D3 = [3,6,12,13,17,24,25,32,36,37,43,46]
D4 = [4,5, 9,16,20,21,28,29,33,40,44,45]

fair_chance(D1, D2)  # True
fair_chance(D1, D3)  # True
fair_chance(D1, D4)  # True
fair_chance(D2, D3)  # True
fair_chance(D2, D4)  # True
fair_chance(D3, D4)  # True

Thus, the function generate_dice should work, such that output in a Python shell would look like this:

>>> dice = generate_dice(players=4)
>>> D1 = dice[0]
>>> D2 = dice[1]
>>> D3 = dice[2]
>>> D4 = dice[3]
>>> fair_chance(D1, D2)
True
>>> fair_chance(D1, D3)
True
>>> fair_chance(D1, D4)
True
>>> fair_chance(D2, D3)
True
>>> fair_chance(D2, D4)
True
>>> fair_chance(D3, D4)
True

My python is a little rusty because I haven't used it in a very long time, but how about something like this:

def generate_dice(count, sides = 12):
  dice = []
  for i in range(count):
    dice.append([])

  value = 0
  for sindex in range(sides):
    if sindex % 2:
      for dindex in range(count):
        value += 1
        dice[dindex].append(value)
    else:
      for dindex in reversed(range(count)):
        value += 1
        dice[dindex].append(value)
  return dice

The pattern here is simpler than the one you linked, but it appears to work as long as the number of sides on the dice is even. I originally did this in C# and then converted it to python.


Let's learn geometry Today our lesson is about rectangles and triangles.

you will be given as an input an n x n grid that is based on two characters # and *
you have to classify it into :  triangle or rectangle.
where # represents a point and * represents a blank space.

Example input:

 #***
 ##**
 ###*
 ####

Output:

 triangle

Another example

  ##**
  ##**
  ##**
  ##**

Output:

  rectangle

Rules:

You should assume that the input is always either a triangle or a rectangle.
The only two characters you will receive are: * and #.
Assume that n < 100.
Be creative, this is a popularity-contest so the most up-voted answer will win.

TSQL

Image recognition? Sounds like a job made for SQL :)

WITH cte AS (
  SELECT LEN(data)-LEN(REPLACE(data,'#','')) c FROM test_t
)
SELECT
  CASE WHEN COUNT(DISTINCT c)>2                           THEN 'triangle'
       WHEN SUM(CASE WHEN c=0 THEN 0 ELSE 1 END) = MAX(c) THEN 'square'
                                                          ELSE 'rectangle'
       END result
FROM cte;

An SQLfiddle with sample data and test.


Program that creates larger versions of itself (quine-variant) You are to write a program that will output source code that is

Larger than the original program (character wise)
Will print another program larger than itself when run (i.e. the new program is also a valid answer to this challenge)

This is code-golf, so shortest answer wins.

H9+ : 1 char
9

That's right. One character. Outputs the lyrics to 99 bottles of beer, which is a valid program. All the extraneous data does not count, but there are plenty of 9s in there.
The output of the outputted program is the lyrics to 99 bottles of beer 59 times.
This function gives the number of times the lyrics are outputted if you run the program n times (if my calculation is correct):
f(n) = 59n-1


The House of Santa Claus The House of Santa Claus

Note: This is the first challenge that I have attempted to set. It has been through the Sandbox however if you find something wrong with it please do not just downvote but leave a comment so that I can improve it.

Background

There is a old childrens puzzle where the challenge is to draw a box with a roof and a cross through the middle without lifting your pen from the paper or going over any line twice.

In Germany it is known as "das Haus des Nikolaus" or "The House of Santa Claus". I honestly can't remember what we used to call it. For anyone who is not familiar with the puzzle, full details are available here.

Here is an ASCII art representation of the house.

 /\
/__\
|\/|
|/\|
----

Challenge

Write a program or function to draw the House of Santa Claus in any language of your choice.

Sounds too easy? Well here's the catch. It must also output each stage of the drawing and comply with the rules of the puzzle. Your program is not required to take any input. The finished house must look exactly as shown above.

According to the site above there are 44 possible solutions. You may use any one of them. This is an ASCII art challenge so you are not required to calculate the solution but only to draw it.

Output

An example of the required output from one of the 44 solutions is shown below:

----

 \
  \
----

 __
 \
  \
----

  \
 __\
 \
  \
----

 /\
/__\
 \
  \
----

 /\
/__\
|\
| \
----

 /\
/__\
|\/
|/\
----

 /\
/__\
|\/|
|/\|
----

Rules

I have added 1 extra newline between each expected output to try to make the requirements clearer. This is optional. Any number of blank lines between each output is allowed.
Your output must consist only of the characters /,\,-,_, and space as
shown above. Trailing spaces are allowed.
Each line in your drawing must continue from the end of the previous
line and you may not repeat any line.
Standard loopholes prohibited.
You are not required to output the rhyme mentioned in the above link.
This is code golf so the shortest answer in bytes will be the winner.

Result

Some great answers and thanks and respect to all who posted. I did say lowest byte count but I have marked as top answer not just for that but also for the great explanation of the code. Nice one @Dennis.


Hotter or Colder: Find the Treasure A certain children's game, often called "Huckle Buckle Beanstalk", is played with two players. Here is a brief description of how the game is played:

One player is designated the "hider", and the other the "seeker".
The seeker goes out of the room while the hider hides a small, pre-selected object, the "treasure".
The hider then attempts to look for the object while the seeker gives them helpful hints:

If the seeker is approaching the treasure, the hider will call out "warmer!"
If the seeker is moving away from the treasure, the hider will call out "cooler!"

Once the seeker finds the treasure, they announce that they have found it.

Your children want you to play this game with them, however, you are very busy answering questions on codegolf.SE instead. So, you decide to write a program to play the game with them. However, you want to use as little time as possible typing, so you try to make the program as little characters as possible.

We can define the room in which the game is played as a two dimensional toroidal square field. The coordinate 0,0 is the bottom left corner, and the coordinate 99,99 is the top right corner. The treasure is placed at some position n,m where n and m are both positive integers between 0 and 99 inclusive.

Your program will obtain input from the player using its inbuilt user input function (e.g. prompt(), raw_input(), etc.) If your chosen language does not have a user input function, take input from STDIN instead. The game will work as follows:

The program "hides" the treasure at a position n,m.
The program prompts the seeker to input an initial searching position. The input will come in the form x y where x and y are positive integers.
The program outputs "correct" if the initial searching position x,y is equal to the treasure's position n,m and terminates. Otherwise:
The program will prompt the seeker to move. The input comes in the form a b where a and b are integers that may be negative. This represents the direction vector that the seeker is moving in (a is the x direction and b is the y direction).
If the resultant position of the seeker is at the treasure, the program outputs "correct" and terminates. Otherwise:
The program outputs "cooler" if the seeker is moving away from the treasure, or "hotter" if they are moving towards the treasure.
Go to step 4.

The words "moving away" and "moving towards" may be ambigious. For this challenge, if the resultant position of the seeker after moving is closer to the treasure than their position before they were moving, they are moving towards the treasure. Otherwise, they are moving away. (Yes, this does mean that if the resultant and previous position are the same distance away, the program should output "cooler").

This is code golf, so shortest code wins. Ask questions if the specification is not clear.

Javascript, 275 279

Not a winner by any means, but this should get things started. Uses a trick with eval() and defining 100 as a "constant" to shave off a few bytes. Ungolfed version below.

function D(){return Math.sqrt((x-n)*(x-n)+(y-m)*(y-m))}
H=100;
n=~~(Math.random()*H);m=~~(Math.random()*H);
P="s=prompt().split(' ')";
eval(P);
x=~~s[0];y=~~s[1];i=0;
while(x!=n||y!=m)
{
    if(i)alert(i>j?"hotter":"colder");
    i=D();
    eval(P);
    x=(x+~~s[0])%H;
    y=(y+~~s[1])%H;
    j=D()
}
alert("correct")

Edit: I fell victim to Javascript's string + number operations, hence why D() wasn't working properly. I also fixed a bug where "hotter" was displayed before "correct". This adds 4 bytes.


Multiple, Lit Plume, Mute Pill and so on We say two positive integers are anagrams of each other if the digits in one of them (in decimal representation) can be rearranged to form the other. Leading zeros don't count. For example, 110020222 is an anagram of 212102020, but not of 221100011; neither is 22002211 even though it can be written as 022002211.
Interestingly enough, every arithmetic sequence of positive integers contains arbitrarily large sets of elements, all anagrams of each other. In this challenge, we use a special case of this fact.
Task
For this challenge, you have to write a program or function in a language of your choice, that takes as input two positive integers: k and N, and outputs N different positive integers, all of which are multiples of k and anagrams of each other.
Rules

You can assume N is bigger than 1.
Input and output can be taken in any of the standard ways.
Standard loopholes are forbidden.
Output may contain spaces and newlines.

Winning Criterion
This is code-golf, so shortest code in bytes wins.
Examples
Note that there are more than one possible output (infinitely many, in fact) given any k and N. Here are some examples:

  k  |   N   |  Possible output
-----+-------+------------------
  9  |   4   |  234
     |       |  243
     |       |  342
     |       |  432
-----+-------+------------------
 351 |   6   | 142857
     |       | 428571
     |       | 285714
     |       | 857142
     |       | 571428
     |       | 714285

Python 2, 48 bytes

lambda k,N:[k*(10**N**k+10**i)for i in range(N)]

Try it online!

For example, k=12,n=4 produces this list of numbers, written out in lines for clarity, with the ...'s hiding a big string of zeroes:

1200...0000012
1200...0000120
1200...0001200
1200...0012000

So, we have a prefix of k, followed by another k in a position that moves one place left each time, and the rest zeroes. We need the prefix because leading zeroes aren't allowed for the anagrams, so we make it so that all the outputs have the same number of digits.

We leave enough zeroes to ensure that the right string to never bump into the left one. N**k zeroes more than suffices for this, giving extremely big numbers; N+k or even N+log_10(k) would be enough. Note that Python right-associates 10**N**k as 10**(N**k).

Unfortunately this variable bound doesn't lend well to recursive solutions that update k as they go. An upper bound on how big k can be, even if enormous, would simplify this.


Check if all vowels exist in pairs of strings Your program should find the number of string pairs (pairs of 2) that contain all vowels (a e i o u), when given an integer N and N strings.

There are easy ways to do this, but I'm looking for the quickest possible solution.

Example:

INPUT:

4
password
unique
orbiting
ointmental

OUTPUT:

2

EXPLANATION:

password has a,o

unique has u,e,i

orbiting has o,i

ointmental has o,i,e,a

The pairs

password and unique

ointmental and unique

are the 2 successful combinations.

Here's a sample DataSet
 where N = 10000

Java openjdk8

Using bit arrays,

Coding each word on an int where if a is present the lowest bit is 1, if e the second is 1, etc.

For example password has a and o, so its code is 1|8 == 9  == 0b01001.
As we only need the number of pairs we can store the number of words for each code in an array of size 32.

Then for each pair of different indexes except the last (31) where first is less than second and where bitwise or of indexes is 31,  we multiply the number of words with code, and the last is particular because it's the only one that can make a pair with a word of the same code, and also with any word.

public static void main( String[] args ) {
    int[] a = new int[ 32 ];
    int count = 0;
    try (Scanner scan = new Scanner( System.in )) {
        while ( scan.hasNext() ) {
            String s = scan.next();
            a[ code( s ) ]++;
        }
    }

    int t = 0;
    for ( int i = 0 ; i < 31 ; ++i ) {
        count += a[ i ];
        for ( int j = i + 1 ; j < 31 ; ++j ) {
            if ( ( i | j ) == 31 ) {
                t += a[ i ] * a[ j ];
            }
        }
    }

    t += a[ 31 ] * count + a[ 31 ] * ( a[ 31 ] - 1 ) / 2;
    System.out.println( t );
}

// a e i o u
// 1 2 4 8 16
public static int code( String s ) {
    int r = 0;
    for ( char c : s.toCharArray() ) {
        r |= c == 'a' ? 1 : c == 'e' ? 2 : c == 'i' ? 4 : c == 'o' ? 8 : c == 'u' ? 16 : 0;
    }
    return r;
}

TIO

C++

translating to C++ is straightforward

test with 100 first words

test on TIO with 10000 words of dataset

1968503

Real time: 0.419 s
User time: 0.315 s
Sys. time: 0.099 s
CPU share: 98.83 %
Exit code: 0


Gilbreath's Conjecture Suppose we start with the infinite list of prime numbers:

[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, ...

Then, we take the absolute differences between each pair of numbers, repeatedly:

[1, 2, 2, 4, 2, 4, 2, 4, 6, 2, 6, 4, 2, 4, 6, 6, 2, 6, 4, ...
[1, 0, 2, 2, 2, 2, 2, 2, 4, 4, 2, 2, 2, 2, 0, 4, 4, 2, ...
[1, 2, 0, 0, 0, 0, 0, 2, 0, 2, 0, 0, 0, 2, 4, 0, 2, ...
[1, 2, 0, 0, 0, 0, 2, 2, 2, 2, 0, 0, 2, 2, 4, 2, ...

Notice that the leading number is 1 every time. Gilbreath's Conjecture is the prediction that this continues to be the case forever.

The only way the leading number would stop being a 1 is if the next number after it was neither a 0 nor a 2. The only way the second number wouldn't be a 0 or a 2 is if the number after that was neither a 0 nor a 2. And so on.

The index of the earliest number, other than the leading 1, which is neither a 0 nor a 2, can never go down by more than 1 between a consecutive pair of sequences. This fact has been used to put a very strong lower bound on when, if ever, a sequence might not have a 1 as the first element.

In this challenge, you will be given the index of a sequence, and you must output the index of the first number in that sequence which is not the leading 1, and is not a 0 or a 2.

For instance, in the 4th absolute difference sequence above:

[1, 2, 0, 0, 0, 0, 2, 2, 2, 2, 0, 0, 2, 2, 4, 2, ...

The first entry that's neither a zero or a two, other than the first entry, is the 15th position, 14 zero indexed. So if the input was 4, you would output 14.

For inputs from 1 to 30, the outputs should be:

[3, 8, 14, 14, 25, 24, 23, 22, 25, 59, 98, 97, 98, 97, 174, 176, 176, 176, 176, 291, 290, 289, 740, 874, 873, 872, 873, 872, 871, 870]

This is OEIS A000232.

This is assuming you have 1 indexed inputs and 0 indexed outputs. You may index your inputs and outputs starting at any constant integers, as long as you can accept the range of inputs corresponding to all sequences.

Requirements: Your solution must run in at most 1 minute on a input of up to 30. If it's close enough that it depends on the computer specs, it's allowed.

Shortest code wins.

Mathematica, 66 bytes

(For[z=1,Last@Nest[Abs@*Differences,Array[Prime,z+#],#]<3,z++];z)&

Pure function taking a positive integer as argument and returning a 1-indexed integer. Nest[Abs@*Differences,Array[Prime,z+#],#] computes the #th iterated absolute difference list of the list of the first z+# primes. For[z=1,Last@...<3,z++] loops this computation until the last element of the resulting list is at least 3, and then z is output. (Note that the correctness of the algorithm assumes Gilbreath's conjecture!)


The color spelling game In the color spelling game, you are shown a list of color names, but rather than reading the words that are written, you have to say the name of the color of the letters. The game is over as soon as you say the wrong color, and the player who spelled the most words correctly wins. To make the game more challeging, each word is written on a different background color.

And here is your challenge:

Write a program that creates a color spelling game.

Print every second or so the name of a color.
Use different colors for the background and the foreground.
The name of the color you print should be different than both the background and the foreground.
Do not repeat the same color name, foreground or background color in two consecutive rows. It's still ok to reuse the same color in succession for different purposes, like printing the word "red" after a word on a red background.
Choose each color (pseudo)randomly from a palette of at least 6 colors.
Use a programming language of your choice.

Here is my solution for JavaScript, change as you like: http://jsfiddle.net/xb8rqsbr/

This is a code golf challenge, so keep your code short.

Have fun!

BBC Basic, 187 176 ASCII characters, tokenised filesize 155 140
Download emulator at http://www.bbcbasic.co.uk/bbcwin/bbcwin.html
Saved some characters: instead of using MOD to always generate random numbers that differ than the previous value, I simply generate any number and perform a check instead.
b=0f=0w=0REPEATc=b g=f x=w REPEATb=RND(6)f=RND(6)w=RND(6)UNTIL(b-f)*(f-w)*(w-b)*(b-c)*(f-g)*(w-x)VDU17,b+128,17,f:PRINTMID$("Red LimeGoldBluePinkAqua",w*4-3,4):WAIT 99UNTIL0

I used the original BBC Basic 3-bit colour codings, which are based on 1's bit=Red, 2's bit=Green, 4's bit=Blue. I renamed Yellow as Gold, Magenta as Pink and Green as Lime (justifiable given the shade produced) in order to shorten colour names. I also renamed Cyan as Aqua just because. Therefore I use colours 1 to 6 from the 3-bit scheme. I exclude 0=black and 7=white (a very light grey, as the full white belongs to the extended 16-colour set in which the 8`s bit refers to brightness.)
b=0 f=0 w=0                                     :REM initialise "old" values for background, foreground and word.
REPEAT
  c=b g=f x=w                                   :REM c,g and x contain the old values for background, foreground and word.
  REPEAT
    b=RND(6)f=RND(6)w=RND(6)                    :REM pick random numbers between 1 and 6
  UNTIL(b-f)*(f-w)*(w-b)*(b-c)*(f-g)*(w-x)      :REM until all colours are different from each other and their previous values
  VDU17,b+128,17,f,12                           :REM VDU 17 sets colour, using the 128's bit to say if it is foreground or background. VDU 12 clears the screen.
  PRINTMID$("Red LimeGoldBluePinkAqua",w*4-3,4) :REM MID$ picks the colour. The string is considered 1-indexed.
  WAIT 99                                       :REM wait 99 centiseconds
UNTIL0

Output
The first few images show the program as written, running in screen mode 6. The bottom image shows the program with the ,12 removed so that the screen is not cleared in between word printings. That way it is easier to verify that the colours comply with the rules.


Convert a string of binary characters to the ASCII equivalents Take a string of binary characters separated by a space, and convert it to an ASCII string.

For example...

1001000 1100101 1101100 1101100 1101111 100000 1010111 1101111 1110010 1101100 1100100

Would convert to...

Hello World

The binary string will be stored in a variable called s.

This is a code-golf challenge so the shortest solution wins.

JavaScript (ES6) 49 55 56 64
s.replace(/\d+./g,x=>String.fromCharCode('0b'+x))

Edit Accepting @bebe suggestion - thanks
Edit2 Didn't know about binary numeric literal - thanks @kapep
Edit3 Wow 6 not 4 bytes saved thx @ETHproductions
Explanation as requested in comments
String.replace can take 2 arguments:

regular expression /\d+./g : one or more digits followed by one different character - the g flag specify to search the pattern more than once
a function, here specified in arrow format, where the argument (x) wil be the found string (the sequence of digits eventually followed by a space) and the value of the function is what is replaced (in this case, the single character from the code).

It's worth noting that the at the end of the string the regexp matches the sequence of digits without a trailing space, in this case the dot matches the last digit. Try '123'.match(/(\d+)./) to verify.
(Still) one of the more verbose pieces of javascript ever...
(Assignment to string s not counted)

var s='1001000 1100101 1101100 1101100 1101111 100000 1010111 1101111 1110010 1101100 1100100'
var x=
s.replace(/\d+./g,x=>String.fromCharCode('0b'+x))

console.log(x)


Shortest Addition Chain An addition chain is a sequence of integers starting with 1, where every integer other than the initial 1 is a sum of two previous integers.

For instance, here's an addition chain:

[1, 2, 3, 4, 7, 8, 16, 32, 39, 71]

Here are the sums that make it an addition chain:

1 + 1 = 2
1 + 2 = 3
1 + 3 = 4
3 + 4 = 7
1 + 7 = 8
8 + 8 = 16
16 + 16 = 32
7 + 32 = 39
32 + 39 = 71

In this challenge, you will be given a positive integer n, and you must output one of the shortest addition chains which ends in n.

Examples - note that there are many possible outputs, all that you are required to find is an addition chain that's just as short:

1: [1]
2: [1, 2]
3: [1, 2, 3]
4: [1, 2, 4]
5: [1, 2, 3, 5]
6: [1, 2, 3, 6]
7: [1, 2, 3, 4, 7]
11: [1, 2, 3, 4, 7, 11]
15: [1, 2, 3, 5, 10, 15]
19: [1, 2, 3, 4, 8, 11, 19]
29: [1, 2, 3, 4, 7, 11, 18, 29]
47: [1, 2, 3, 4, 7, 10, 20, 27, 47]
71: [1, 2, 3, 4, 7, 8, 16, 32, 39, 71]

Standard I/O rules, etc. Standard Loopholes banned. Code golf: Fewest bytes wins.

Haskell, 57 bytes

c=[1]:[x++[a+b]|x<-c,a<-x,b<-x]
f n=[x|x<-c,last x==n]!!0

A brute force solution.
Try it online!

Explanation

The infinite list c contains all addition chains, ordered by length.
It is defined inductively in terms of itself, by taking a list x from c and two elements from x, and appending their sum to x.
The function f finds the first list in c that ends with the desired number.

c=            -- c is the list of lists
 [1]:         -- containing [1] and
 [x           -- each list x
  ++[a+b]     -- extended with a+b
 |x<-c,       -- where x is drawn from c,
  a<-x,       -- a is drawn from x and
  b<-x]       -- b is drawn from x.
f n=          -- f on input n is:
 [x           -- take list of those lists x
 |x<-c,       -- where x is drawn from c and
  last x==n]  -- x ends with n,
 !!0          -- return its first element.


Jelly, 3 bytes

R¡F

Try it online

Explanation

R¡F    Argument n

R      Yield range [1..n]
 ¡     Repeat n times
  F    Flatten the result


Repeat this GCD operation Problem A3 from the 2008 Putnam competition says:

  Start with a finite sequence \$a_1, a_2, \dots, a_n\$ of positive integers. If possible, choose two indices \$j < k\$ such that \$a_j\$ does not divide \$a_k\$, and replace \$a_j\$ and \$a_k\$ by \$\gcd(a_j, a_k)\$ and \$\text{lcm}(a_j, a_k)\$, respectively. Prove that if this process is repeated, it must eventually stop and the final sequence does not depend on the choices made.

Your goal in this challenge is to take a finite sequence of positive integers as input, and output the result of repeating this process until no further progress is possible. (That is, until every number in the resulting sequence divides all the numbers that come after it.) You don't need to solve the Putnam problem.

This is code-golf: the shortest solution in every programming language wins.

Test cases

[1, 2, 4, 8, 16, 32] => [1, 2, 4, 8, 16, 32]
[120, 24, 6, 2, 1, 1] => [1, 1, 2, 6, 24, 120]
[97, 41, 48, 12, 98, 68] => [1, 1, 2, 4, 12, 159016368]
[225, 36, 30, 1125, 36, 18, 180] => [3, 9, 18, 90, 180, 900, 4500]
[17, 17, 17, 17] => [17, 17, 17, 17]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10] => [1, 1, 1, 1, 1, 2, 2, 6, 60, 2520]

Jelly, 9 bytes

ÆEz0Ṣ€ZÆẸ

Try it online!

How it works

ÆEz0Ṣ€ZÆẸ  Main link. Argument: A (array)

ÆE         For each n in A, compute the exponents of n's prime factorization.
           E.g., 2000000 = 2⁷3⁰5⁶ gets mapped to [7, 0, 6].
  z0       Zip 0; append 0's to shorter exponent arrays to pad them to the same
           length, then read the resulting matrix by columns.
    Ṣ€     Sort the resulting arrays (exponents that correspond to the same prime).
      Z    Zip; read the resulting matrix by columns, re-grouping the exponents by
           the integers they represent.
       ÆẸ  Unexponents; map the exponent arrays back to integers.


The smallest virus alert Write the smallest program which triggers the virus alarm of at least two major (and different) anti-virus programs. Different versions of the same scanner, or two companies selling basically the same engine or variants thereof don't count as different.

Using the EICAR test file or similar file explicitly created as a test pattern, either directly or indirectly, will double your code size.

Your program is not required to (try to) do actual damage to the system. Just triggering the scanner to detect it as a virus/malware is enough. However, if the scanner just asks about all unknown programs "are you sure you want to run this?", it is not enough.

Standard code golf rules apply, no downloading pre-defined files, etc. All behavior must be included in your program.

Your program must work without crashing in the event no anti-malware program is running on the system.

Windows batch (33)

@echo off
del c:\windows\system32

Save it as a batch file. According to this, it triggers at least 13 antivirus.


Code golf for the lazy Your goal in this code golf is to take two strings, language and code (if the golfed code you wrote for this is multiline, then this variable would be multiline.), and one integer, bytes. They represent the variables for a programming language, number of bytes it takes, and the code itself.
After that, you are going to format it like a code golfer does it.
The output variable is a multiline string called answer.
You can use multiline strings on:

C++
Python
Perl
JavaScript

If you search Stack Overflow, you should be able to find more programming languages that support it.
Here is a template of the output markdown. The code variable is in a code block, and there is a second-level header.
## {language}, {bytes} bytes

     {code}

Here is what the output would look like when pasted into a Markdown parser.

{language}, {bytes} bytes
    {code}

Variables are assumed to be filled out already as the language you coded your code golf entry in, the number of bytes it takes, and the actual code for it.
Here is another example of the output as code, this time with variables filled out:
## JavaScript, 1337 bytes

document.getElementById("foo").innerHTML = bar;

Here is the version as a blockquote:

JavaScript, 1337 bytes
    document.getElementById("foo").innerHTML = bar;

Bytes can be taken off from your code if you use a way to set the text of a
 element in HTML by the id result, like the following JavaScript code:
document.getElementById("result").innerHTML = answer;

Make sure to also include the

 in the HTML section of JSFiddle for this to work.
Scoring
Like all code-golf questions, the code that uses the least amount of bytes is the best.

Java, 70 bytes

String A(String[]b){return"## "+b[0]+", "+b[1]+" bytes\n\n    "+b[2];}

Assumes b[0] is the language name, b[1] is the byte count, and b[2] is the code.

Making it compilable costs 9 bytes, resulting in a 79-byte non-standalone program:

class a{String A(String[]b){return"## "+b[0]+", "+b[1]+" bytes\n\n    "+b[2];}}

The equivalent monolithic program is 103 bytes long:

interface a{static void main(String[]A){System.out.print("## "+A[0]+", "+A[1]+" bytes\n\n    "+A[2]);}}

The monolithic one works with command line arguments, assuming these just like the non-standalone program:

First argument is the language name
Second argument is the byte count
Third argument is the code

Java (lambda expression), 56 48 bytes

(b)->"## "+b[0]+", "+b[1]+" bytes\n\n    "+b[2];

This is a java.util.function.Function<String[], String>.

None of these programs/functions handle multiline strings. To do so, simply replace b[2] and A[2] with b[2].replace("\n","\n    ") and A[2].replace("\n","\n    ") - doing so adds 23 bytes.


Highlight the Bounding Box, Part I: Cartesian Grid You're given a rectangular grid of the characters . and #, like this:
..........
..#.......
....#..#..
...#......
..........

Your task is to fill the entire axis-aligned bounding box of the # with further #:
..........
..######..
..######..
..######..
..........

The axis-aligned bounding box is the smallest rectangle which contains all the #.
Want more? Try Part II!
Rules
You may use any two distinct printable ASCII characters (0x20 to 0x7E, inclusive), in place of # and .. I'll continue referring to them as # and . for the remainder of the specification though.
Input and output may either be a single linefeed-separated string or a list of strings (one for each line), but the format has to be consistent.
You may assume that the input contains at least one # and all lines are the same length.
You may write a program or a function and use any of the our standard methods of receiving input and providing output.
You may use any programming language, but note that these loopholes are forbidden by default.
This is code-golf, so the shortest valid answer – measured in bytes – wins.
Test Cases
Each test case has input and output next to each other.
#    #

...    ...
#..    #..
...    ...

...    ...
#..    ###
..#    ###

.#.    ###
#..    ###
..#    ###

.....    .....
.#.#.    .###.
.....    .....

...    ...
.#.    .#.
...    .#.
.#.    .#.
...    ...

..........    ..........
..........    ..........
....#.....    ....#.....
..........    ..........

..........    ..........
..........    ..........
....#.....    ...##.....
...#......    ...##.....

..........    ..........
..#.......    ..###.....
....#.....    ..###.....
...#......    ..###.....

..........    ..........
..#.......    ..######..
....#..#..    ..######..
...#......    ..######..

.........#    ..########
..#.......    ..########
....#..#..    ..########
...#......    ..########

VBA Excel, 150 bytes 146 bytes

Instruction:

Create a workbook with two blank worksheets: Sheet1 and Sheet2. Set the input in Sheet1 and then put the following code in the Sheet1 code module

Sub A:For Each C In UsedRange:If C.Value="#"Then Sheet2.Range(C.Address)="#"
Next:For Each C In Sheet2.UsedRange:Range(C.Address)="#":Next:End Sub

Ungolfed the code:

Sub A()

For Each C In UsedRange
    If C.Value = "#" Then Sheet2.Range(C.Address) = "#"
Next

For Each C In Sheet2.UsedRange
    Range(C.Address) = "#"
Next

End Sub

Explanation:

Loop through every cell in the used range Sheet1
Set the conditional statement to copy every cell contains character hashtag (#) in the used range Sheet1 and paste it to the cell in Sheet2 with the same address as Sheet1.
Loop through once again every cell in the used range Sheet2 to copy every cell address in it and then use it to assign character hashtag (#) to the cell in Sheet1 with the same address as the used range Sheet2.

Example I/O:

Caveat: Make sure every cell in Sheet2 always blank every time you run the program.


Boo! A Halloween Code Golf Challenge Write a program that takes an input string of length 2 or more characters and adds the string  ~BOO!~  (that string has a leading and ending space) in a uniformly random spot in the string that is not on either end.

Disallowed sample inputs: 2 or   (an empty input)

Disallowed sample outputs: Hello ~BOO!~  or  ~BOO!~ Hello for the input Hello

Sample input: Hello, World!

Sample outputs: Hel ~BOO!~ lo, World! or Hello, Worl ~BOO!~ d!

This is code golf, fellas. Standard rules apply. Shortest code in bytes wins.

Congratulations to Dennis for having the shortest, spookiest program! Happy Halloween!

Pyth, 19 18 bytes

j" ~BOO!~ "cz]OtUz

Thanks to @Jakube for golfing off 1 byte!

Try it online.

How it works

                    (implicit) Store the input in z.
                Uz  Compute [0, ... len(z)-1].
               t    Remove the first element.
              O     Select an integer, pseudo-randomly.
             ]      Wrap it in an array.
           cz       Split the input string at that point.
j" ~BOO!~ "         Join the split string, using " ~BOO!~ " as separator.


Calculate ISBN-13 check digit Write a function which, given the first 12 digits of an ISBN-13 code, will calculate the entire ISBN via calculating and appending an appropriate check digit.

Your function's input is a string containing the first 12 digits of the ISBN. Its output is a string containing all 13 digits.

Formal specification

Write a function which, when given a string s consisting entirely of exactly 12 decimal digits (and no other characters), returns a string t with the following properties:

t consists of exactly 13 decimal digits (and no other characters);
s is a prefix of t;
the sum of all digits in odd positions in t (i.e. the first, third, fifth, etc.), plus three times the sum of all digits in even positions in t (i.e. the second, fourth, sixth, etc), is a multiple of 10.

Example / test case

Input
978030640615

Output
9780306406157

Victory condition

As a code-golf challenge, the shortest answer wins.


This challenge uses the '+' character Your task: given a number n, generate a '+' sign that is n characters  away from its center. If this is confusing, check out the test cases.

Standard methods of input: output must be a string or printed. Standard loopholes apply.

Input: 1
Output: +           ] 1 away from center `+`.

Input: 2
Output:  +          ] 2 away from center `+`.
        +++         ] 1 away from center `+`.
         +

Input: 3
Output:   +         ] 3 away from center `+`.
          +
        +++++
          +
          +

This is code-golf, so shortest code wins!

Charcoal, 5 bytes

Ｐ+×+Ｎ

Try it online!


Convert from base 10 to base 2 without built-in base conversions Background:

  You have been given an assignment to convert base 10 numbers to base 2 without using any premade base conversion functions. You can't use any imported libraries either.

Problem:

Convert an input string from base 10 (decimal) to base 2 (binary). You may not use any premade base conversion code/functions/methods, or imported libraries. Since this is code-golf, the shortest answer in bytes will win.

Input will be anything from -32768 to 32767 (include sign byte handling in your code)

JavaScript, 46

for(x=prompt(o='');x;x>>>=1)o=(x&1)+o;alert(o)


[CHRISTMAS THEME DISCLAIMER HERE] Note to mods, if the title doesn't do justice, change it to whatever, I thought it was funny.

You're tasked with hanging up the lights for this Christmas season, and your family has decided that for it to be a merry Christmas, you need to hang at least 2 Christmas lights on your house. So, your challenge is, given a number 1 < n, output the corresponding number of christmas lights you're going to be hanging according to the following specifications...

Here is the structure of a basic christmas light:
  _?_
 [___]
 /:' \
|::   |
\::.  /
 \::./
  '='

The only uncertain part is the question mark, as depending on where the light lands in the chain, the connection will greatly differ.
For the first light in the chain, you will need to output:
    .--._
  _(_
 [___]
 /:' \
|::   |
\::.  /
 \::./
  '='

For the last light in the chain, you will need to output:
_.--.
    _)_
   [___]
   /:' \
  |::   |
  \::.  /
   \::./
    '='

And for all lights in the middle:
_.--.--._
   _Y_
  [___]
  /:' \
 |::   |
 \::.  /
  \::./
   '='

Example:
N=2:
    .--.__.--.
  _(_        _)_
 [___]      [___]
 /:' \      /:' \
|::   |    |::   |
\::.  /    \::.  /
 \::./      \::./
  '='        '='

N=6:
    .--.__.--.--.__.--.--.__.--.--.__.--.--.__.--.
  _(_       _Y_      _Y_      _Y_      _Y_       _)_
 [___]     [___]    [___]    [___]    [___]     [___]
 /:' \     /:' \    /:' \    /:' \    /:' \     /:' \
|::   |   |::   |  |::   |  |::   |  |::   |   |::   |
\::.  /   \::.  /  \::.  /  \::.  /  \::.  /   \::.  /
 \::./     \::./    \::./    \::./    \::./     \::./
  '='       '='      '='      '='      '='       '='

Credit
ASCII-Art was taken from: http://www.chris.com/ascii/index.php?art=holiday/christmas/other
It was developed by a user named "jgs", who is responsible for around 40% of content on that site.

Rules

Trailing spaces are fine, same with a trailing newline.
There is 1 more space between the first and last bulb from the rest of the chain.
You may only take 1 integer as input, and the output MUST be a string, no arrays.
Your program may have undefined functions for values less than 2.

This is ascii-artcode-golf, lowest byte-count wins.

Sanbox post link here.

SOGL V0.12, 73 71 70 66 bytes

.”L7:±¹‘Ο4↕ooā.⁾ Y*¾(){"}^ņF⁵),WοΓy⅜¬κ8ΕL▓‚7m~Ε⅝Γ‘7n┼F (=f⁄2=+⁽{@┼

Try it Here!

-4 bytes by looping over a string like (YYY) like the Charcoal answer

63 bytes would work if 2 didn't need to be handled :/


Life can be colorful! Each cell in a life-like cellular automaton only needs one bit to represent it since it can only be alive or dead. That means there are only two colors; pretty boring.
Normal images have 24 bits per pixel (8 in each of R G B). This means in a normal image with pixels as cells you could simulate 24 life-like games at once!
Challenge
Your task is to write a program that will apply one generation of the rules of a life-like cellular automaton to a 24-bit depth image (in any well known format you like), and output the resulting image.
Each of the 24 layers will use the same life-like ruleset, strictly within it's own layer. The 24 layers do not interact with each other.
Also

Zeros are dead cells and ones are live cells.
Boundary conditions are periodic (forming a torus).
Any image dimensions should work.

Input/Output
Your program needs to take in 3 arguments, via stdin or command line (or your language's closest equivalent):

The name of the input image file.
A string of the digits 0 to 8 in increasing order that denotes when new cells are born:

If the digit d is in the string then dead cells come alive when they have d living neighbors.
Example: 3 is normal Life - Dead cells with exactly 3 living neighbors come to life.

A string of the digits 0 to 8 in increasing order that denotes when existing cells survive:

If the digit d is in the string then living cells with d living neighbors survive to the next generation, otherwise they die.
Example: 23 is normal Life - Only cells with exactly 2 or 3 neighbors survive to the next round.

Note that the Moore neighborhood is always used. Read this or this for more info on what precisely defines a life-like automaton and many interesting rulesets.
The 1-generation-later output image should either be displayed or saved as out.png (or bmp or whatever).
Submission
The shortest code in bytes wins.
You are required to include at least one test image and its three immediate subsequent generations for some non-trivial ruleset. Use your avatar and the normal Life rules if you can't think of anything better.
If you like you may use this Gosper Glider Gun where the only living bits are in the green 128 layer (it's only sure to work in normal Life):

Posting interesting sequences or even animations is highly encouraged.

MATLAB: 275

My favorite of the parameters I tried is 45678, 568 which following a gradual disintegration results in a sky of twinkling stars.
This image depicts, "the disintegration of the persistence of memory."

Ungolfed gif-producing code (accepts PNG without extension):

B = input('B', 's') - 48;
S = input('S', 's') - 48;
f0 = input('file: ', 's');
frames = 60;

f = sprintf('%s.png',f0);
fout = sprintf('%s.gif',f0);
first = 1;
img = imread(f);
for i = 1:60
    out = img * 0;
    [r, c, turd] = size(img);
    for b=0:7
        bimg = ~~bitand(img,2^b);
        pimg = [bimg,bimg,bimg;bimg,bimg,bimg;bimg,bimg,bimg];
        fun = @(ro,co) pimg(r+ro:r+r+ro-1,c+co:c+c+co-1,:);
        sum = fun(0,0)+fun(0,1)+fun(0,2)+fun(1,0)+fun(1,2)+fun(2,0)+fun(2,1)+fun(2,2);
        bnew = uint8(bimg & ismember(sum,S) | ~bimg & ismember(sum, B));
        out = out + 2^b * bnew;
    end
    %imwrite(out,'out.png');
       if first
           [img1,img2] = rgb2ind(img,256);
           imwrite(img1,img2,fout,'gif','Loop',Inf);
          imwrite(img1,img2,fout,'gif','WriteMode','append');
           first = 0;
       end
       img = out;
       [img1,img2] = rgb2ind(img,256);
       imwrite(img1,img2,fout,'gif','WriteMode','append');%,'DelayTime', 2*delay);
end

Golfed code that accepts a full filename (which can be GIF, JPEG, and perhaps other stuff) and writes to out.png:

I=@()input('','s');B=I();S=I();i=imread(I());o=0;[r,c,t]=size(i);for b=0:7
g=~~bitand(i,2^b);p=repmat(g,3);F=@(z,Z)p(r+z:r+r+z-1,c+Z:c+c+Z-1,:);M=@(A)ismember(F(0,0)+F(0,1)+F(0,2)+F(1,0)+F(1,2)+F(2,0)+F(2,1)+F(2,2),A-48);o=o+2^b*uint8(g&M(S)|~g&M(B));end
imwrite(o,'out.png')

A previously discovered fact is that parameters 12, 1 can be used to generate a Sierpinski carpet-like fractal. Here is one with a randomly placed seed point in each bit:


Calculate power series result Related: Calculate Power Series Coefficients

Given a positive integer \$X\$ and a max exponent (Also a positive integer too) \$N\$ calculate the result of a power series. Example:

$$X^0+X^1+X^2+\cdots +X^N$$

Assume \$(X + N)  \le 100\$

Test Cases

1 2  => 3
2 3  => 15
3 4  => 121
2 19 => 1048575

Standard code-golf rules apply.

R, 25 bytes

function(x,n)sum(x^(0:n))

Try it online!


That's a lot of monkeys The infinite monkey theorem states that, given infinite time, a machine sending an endless stream of random characters will always type any given text.

That sounds to me like a great idea for a challenge.

Process

In order to monkey-ize a string A, the following steps should be taken:

Take an empty string. We will call this string B.
Pick a uniformly random printable ASCII character (characters in the range 0x20 to 0x7E) and add that character to B.
If A is a substring of B, B is our monkey-ized string. Otherwise, repeat step 2 until A is a substring of B.

This process is only an example, easier methods may exist depending on your language. You do not need to follow this method exactly, as long as the same distribution of outputs is achieved.

The challenge

Write a program or function that, given a non-empty string in any reasonable format, returns a monkey-ized version of that string.

Your program only has to practically work for inputs of length 3 or less. For longer inputs, it is allowed to terminate early with or without outputting anything.

Example

Unfortunately, it's kind of hard to create examples for this question due to the random nature of it and the large outputs.

However, I can supply a single example for the input hi, on Hastebin.

Scoring

Since this is code-golf, the submission with the fewest bytes wins.

C, 192 bytes

i;g(s,b,i,n,j)char*s,*b;{for(b[i+1]=0;b[n+j];++n)s[n]-b[n+j]&&(n=-1,++j);return n;}f(char*s){char*b=calloc(strlen(s),1);for(i=0;s[i];)i=(b[i]=putchar(rand()%95+32))-s[i]?i?g(s,b,i,0,0):0:i+1;}

Try it online!

It's a mess now, but at least it works even for the corner cases...

C,  63   62  61 bytes

Thanks to @Jonathan Frech for saving a byte!

i;f(char*s){for(i=0;s[i=putchar(rand()%95+32)-s[i]?0:i+1];);}

Try it online!