Pack sequences of non-negative integers Let N be the set of nonnegative integers, i.e. {0, 1, 2, 3, ...}.

Let c0(N) be the set of all infinite sequences in N that converge to 0, i.e. { (xn) ∈ NN | xn → 0 as n → ∞}.

c0(N) can be equivalently written as the set of all finite sequences of natural numbers, such that there are no trailing zeroes. The infinite sequence of all zeroes (corresponding to a finite sequence of length 0) is an element of c0(N).

Your task is to implement a bijection in your language between N and c0(N), in as few characters as possible. This means every number in N corresponds to a unique item of c0(N), and vice versa. Do this by defining two functions: f, going from N and c0(N); and g, the inverse of f. The length in bytes of these two definitions is your score.

You may use the largest internal integer and list types of your language, even if they aren't bignums or capable of handling infinite length. However, they should theoretically still be able to terminate with the right answer if the language was modified with a suitable bignum or lazy/infinite list type.

Some suggestions for ways to pack are below. Note that these aren't quite solutions yet and could need some tweaking to work; they're mostly to get the blood flowing.

f(1463616) = f(2^6 * 3^3 * 5^0 * 7^1 * 11^2) = [6, 3, 0, 1, 2] - Factorize the number into primes and read off exponents to get the sequence.
f(64971) = f(0b1111110111001011) = [6, 3, 0, 1, 2] - Expand the number in binary and use 0 as a separator to read strings of ones, representing the sequence in unary.

While this is a code-golf and the shortest answer will win, creative and interesting solutions are encouraged and may be subject to a bounty.

J - 17 char

g=:(f=:_ q:>:)inv

We implement the prime exponent idea with this bijection—that's what the _ q: is doing, getting a list of the exponents of the primes of a number—except we also increment the input number by one before doing so, with >:, so that we don't forget 0, who doesn't have its own prime factorization.

For the definition of g, it's exactly what it looks like: instead of writing it ourselves, we just tell J to take the inverse of f. Arguably this is cheating, or just not interesting, but I think that the ability to do this is what makes J such an interesting language: J can often figure things out for you, allowing you to focus on expressing your solution instead of implementing it.

   i. 20
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
   f i. 20  NB. J pads with zeroes on right
0 0 0 0 0 0 0 0
1 0 0 0 0 0 0 0
0 1 0 0 0 0 0 0
2 0 0 0 0 0 0 0
0 0 1 0 0 0 0 0
1 1 0 0 0 0 0 0
0 0 0 1 0 0 0 0
3 0 0 0 0 0 0 0
0 2 0 0 0 0 0 0
1 0 1 0 0 0 0 0
0 0 0 0 1 0 0 0
2 1 0 0 0 0 0 0
0 0 0 0 0 1 0 0
1 0 0 1 0 0 0 0
0 1 1 0 0 0 0 0
4 0 0 0 0 0 0 0
0 0 0 0 0 0 1 0
1 2 0 0 0 0 0 0
0 0 0 0 0 0 0 1
2 0 1 0 0 0 0 0
   g f i. 20
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19

Proving that this is a bijection is straightforward: the injectivity of this f is a well known fact and, if you assume that J's automagical inverse is correct (which it is), then this is trivial.

If you don't want to take it on faith that J knows how to take the inverse of f, we can inspect its automatic inverse for _&q::

   _&q: b. _1
(p:@i.@# */ .^ ])"1 :.(_&q:)

and then check the definition:

(p:@i.@# */ .^ ])"1 :.(_&q:)  NB. the alleged inverse of _&q:
                    :.(_&q:)  NB. defining _&q:inv inv to be _&q:
(               )"1           NB. operate on rows of the argument
       #                      NB. length of argument
    i.@                       NB. nonnegative integers less than
 p:@                          NB. n-th prime for each integer n
               ]              NB. the argument again
            .^                NB. pointwise exponentiation
         */                   NB. product

and then confirm that J's inverse of f gives the decrement of the result of this:

   >: b. _1  NB. inverse of increment is decrement
<:
   f b. _1   NB. ([: f g) is one way of writing f composed with g
[: <: (p:@i.@# */ .^ ])"1 :.(_&q:)


Two-Coloring Overlapping Circles Write a program or function that takes in the following input in a reasonable format of your choice:

Two positive integers W and H that define the width and height of the image you'll be generating.
Two RGB colors C1 and C2 that will be used to color the image.
A list of 3-tuples of the form (r, x, y) that define circles with radius r and center x, y in the plane of the image. r is a positive integer and x and y are any integers. The top left pixel of the image is 0, 0 and the x-axis increases to the right and the y-axis increases downward.

Output an image with dimensions W by H that is colored with C1 and C2 such that no two neighboring regions defined by all the overlapping circles are the same color.

  For example: If the input is

W = 300
H = 200
C1 = (255, 200, 0)
C2 = (128, 0, 255)
Circles = (25, 50, 80), (40, 80, 120), (300, -100, 6), (17, 253, 162)

  then the circle boundaries look like this:

  There are six distinct, contiguous regions in the image created by the
  circles. Each region must be colored with C1 (yellow) or C2 (purple)
  such that no two neighboring regions are the same color.

  There are two ways to do this, their only difference being that the
  colors are swapped:

  Thus, either of these two images would be valid output for the example
  input.

  Something like this would be invalid output since two yellow regions
  neighbor each other.

Your output images should follow these guidelines:

Besides C1 and C2, a third, neutral color such as black or white may be used for circle boundaries as long as they are no more than 5 pixels thick. (Black, 1-pixel thick boundaries are present in the example above.)
Circles boundaries are not required, however. The regions may neighbor each other directly:

Both of these is another valid output to the example above.
Circles should be as accurate as reasonably possible, using circle drawing algorithms or whatever your graphics library provides.
In general, pixel-perfection is not required, but if the input parameters are scaled equally larger and larger, the resulting image should become more and more accurate.
Anti-aliasing is allowed but not required.
Gridlines or axis labels etc. in the background are not allowed.

The shortest code in bytes wins.

More Examples

All using these inputs with different sets of circles:

W = 100
H = 60
C1 = (255, 0, 0)
C2 = (0, 0, 255)

In any example the colors can be swapped and remain valid.

Circles =
A. empty list
B. (13, 16, 20)
C. (30, 16, 20)
D. (200, 16, 20)
E. (42, 50, 20)
F. (42, 50, 20), (17, 40, 30)
G. (42, 50, 20), (17, 20, 30)
H. (42, 50, 20), (17, 10, 30), (10, 50, 30)
I. (42, 50, 20), (17, 10, 30), (35, 50, 20)
J. (18, 36, 40), (18, 63, 40), (18, 50, 20)
K. (100, -10, -20), (60, 50, -10)
L. (18, 36, 40), (18, 63, 40), (18, 50, 20), (14, 50, 20), (5, 50, 18), (20, 0, 0), (70, 22, 0), (10000, -9970, 0), (135, 100, -80)

A.  B.  C.  D.
E.  F.  G.  H.
I.  J.  K.  L.

Make sure your output behaves similar to all these examples.

Mathematica, 165 bytes

ContourPlot[Cos@Tr[Boole[Norm[{x,y}-#2]<#]Pi&@@@#4],{x,0,#},{y,0,#2},PlotPoints->5!,AspectRatio->Automatic,Frame->False,ContourShading->RGBColor@@@#3,Contours->{0}]&

Pure function taking four arguments: the width, the height (both integers), an ordered pair of triples of numbers between 0 and 1 (representing the two RGB colors), and a list of items of the form {r, {x, y}} to record the radii and centers of the circles. For example, the first example in the OP would be called with the arguments [300, 200, {{1, 0.784, 0}, {0.5, 0, 1}}, {{25, {50, 80}}, {40, {80, 120}}, {300, {-100, 6}}, {17, {253, 162}}}]. The positive y-axis points upwards in Mathematica.

Norm[{x,y}-#2]<# detects whether a point is inside a given circle; Boole[...]Pi converts that True or False to π or 0. After computing those πs/0s over all the input circles, Tr adds them up and Cos converts even multiples of π to 1, odd multiples of π to –1. ContourPlot[...,Contours->{0}] then colors the appropriate region of the plane in two colors depending on whether the value is greater or less than 0. AspectRatio->Automatic makes circles look like circles; PlotPoints->5! gives a decent accuracy (boost it to 9! if you really want an amazing picture, far in the future!); Frame->False gets rid of the axes; and ContourShading->RGBColor@@@#3 uses the input colors for the contours.

Sample output, with the first pair of colors (since they're nice) but the last set of circles:


HexaGolf: Rotatagons See also: Wordagons

Challenge

Given a hexagon and a number n as input, output the same hexagon rotated n times.

Hexagon

The hexagon will be a string like so:

  a b c
 d d e e
f f o g g
 h h i i
  j k l

The hexagon will always be regular and will only ever contain the printable ASCII characters:

 !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~

Rotation

To find how much to rotate the hexagon by, multiply n by 60 degrees to get the angle of rotation. For example, using the above hexagon, if n is 2, we multiply that by 60 to get 120 degrees. Then, we rotate the hexagon by 120 degrees:

  j h f
 k h f d
l i o d a
 i g e b
  g e c

Note that each side has moved two sides clockwise.

If n is positive, you should rotate the hexagon clockwise. If n is negative, you should rotate the hexagon anticlockwise.

n will always be an integer in the range -6 to 6 inclusive.

Examples

Input:

  . u .
 .  |  .
l - + - r
 .  |  .
  . d .

n = 3

  . d .
 .  |  .
r - + - l
 .  |  .
  . u .

Input:

  - - -
 /     \
<       >
 \     /
  - - -

n = -1

Output:

  - \ >
 -     /
-       -
 /     -
  < \ -

Input:

   h e x a
  g o n s a
 n d t r i a
n g l e s m a
 k e m e s a
  d l y m a
   d d e r

n = 6

Output:

   h e x a
  g o n s a
 n d t r i a
n g l e s m a
 k e m e s a
  d l y m a
   d d e r

Winning

The shortest program in bytes wins.

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

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

Try it online - Supports decimal rotations as well!

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


Can I restack the buckets? My little kid has a toy like this:

This toy consists of 10 stackable little buckets, that we are going to number from 1 (the smallest one) to 10 (the biggest one). Sometimes he makes small piles and the toy ends up like this:

We can represent schematically the piles like this:

      1  6
4  9  2  7
5  10 3  8
----------  <-- Floor
1  2  3  4  <-- Pile #

Or, put it another way:

[[4,5],[9,10],[1,2,3],[6,7,8]]

This set of bucket piles is easily restackable to rebuild the original set (the first image) just by consecutively placing piles of smaller buckets inside piles of bigger buckets:

                             1                            1  6
                             2                            2  7
      1  6                   3        6                   3  8
4  9  2  7                   4  9     7                   4  9
5  10 3  8                   5  10    8                   5  10
---------- > [Pile 3 to 1] > ---------- > [Pile 4 to 2] > ---------- > [Pile 1 to 2] > Done!
1  2  3  4                   1  2  3  4                   1  2  3  4

Nonetheless, sometimes my kid tries to build towers, or throws buckets away, and the piles end up being inconsistent and the original set cannot be rebuild just by placing one pile inside another. Examples of this:

[[1,3,2],[4]] (the kid tried to build a tower by placing a bigger bucket
               over a smaller one, we would need to reorder the buckets
               first)
[[1,3,4],[2]] (the kid left aside an unordered bucket, we would need to remove
               bucket #1 from pile #1 before restacking)
[[1,2,3],[5]] (the kid lost a bucket, we need to find it first)

Challenge

Given a list of lists of integers representing a set of bucket piles, return a truthy value if the lists represent an easily restackable set of piles, or falsey in any other case.

Input will be given as a list of lists of integers, representing the buckets from top to bottom for each stack.
There won't be empty starting piles (you won't get [[1,2,3],[],[4,5]] as input).
The total number of buckets can be any within a reasonable integer range.
My kid only has one set of buckets so there won't be duplicate elements.
You can select any two consistent (and coherent) values for truthy or falsey.
The buckets will be labelled from #1 to #N, being N the largest integer in the lists of integers. My kid still does not know the concept of zero.
You may receive the input in any reasonable format as long as it represents a set of piles of buckets. Just specify it in your answer if you change the way you receive the input.
This is code-golf, so may the shortest program/function for each language win!

Examples

Input:  [[4,5],[9,10],[1,2,3],[6,7,8]]
Output: Truthy

Input:  [[6,7,8,9,10],[1],[2],[3,4,5],[11,12,13]]
Output: Truthy

Input:  [[2,3,4],[1],[5,6,7]]
Output: Truthy

Input:  [[1,2],[5,6],[7,8,9]]
Output: Falsey (buckets #3 and #4 are missing)

Input:  [[2,3,4],[5,6,7]]
Output: Falsey (bucket #1 is missing)

Input:  [[1,3,4],[5,7],[2,6]]
Output: Falsey (non-restackable piles)

Input:  [[1,4,3],[2],[5,6]]
Output: Falsey (one of the piles is a tower)

Jelly, 6 5 bytes

Thanks to @Lynn for saving 1 byte.

ṢFµJ⁼

Try it online! (comes with test-suite footer)

Explanation

ṢFµJ⁼    Main link. Argument: piles
Ṣ          Sort the piles by the size of the top bucket.
 F         Stack the piles, putting the left one to the top.
   J       See what a full pile with this many buckets would look like.
    ⁼      See if that looks like the pile you built.


May the fourth be with flu Since tomorrow is the 4th of May, here's a little Star Wars themed post to prepare you mentally to all the bad jokes coming tomorrow.

BACKSTORY

During a session of the galactic senate all the senators are sitting in an n*n grid.
A sudden outbreak of JarJar flu (which lasts forever and causes the infected to speak like JarJar Binks) causes some of the senators to get infected.

Here's an example with a 6*6 grid where the X are the infected senators, the corresponding list is : [[0,5],[1,4],[2,3],[2,1],[3,3],[3,0],[4,5],[0,5]]:

After that the infection begins to spread step by step. Two senators are adjacent if they share a whole edge on the grid (i.e., top,bottom,right,left), which means we exclude diagonals.

We can conclude a senator can be adjacent to 2,3 or 4 other senators and claim the following rules for the infection :

A senator that has been infected stays infected forever
A senator is infected at a step if he was adjacent to 2 or more infected senator at the previous step

Here's an example with the previous grid which shows the 2 first steps of the infection :

After the nexts steps all the senate will be infected

YOUR TASK

Your code doesn't need to handle invalid inputs like a list greater than n*n or coordinates that aren't distincts.

Your code will take as input a list of couples of integers (or a binary grid or any other format that suits your language) and an integer n (which can be unnecessary if you use another format than a list) , for instance :

8 [[1,2],[1,1],[7,4],[2,7],[4,3]]

n being the side of the grid which means the grid will be a n*n grid, and the list of couples of integers being the coordinates of the cells of the initally infected senators.

The bottom left of the grid is [0,0] and the top right is [n-1,n-1]. The top left is [0,n-1].

Your code must output an integer :

-1 or a falsy value or an error if the whole grid will never be totally infected
or the minimum number of steps required to infect the whole grid

Test cases

6 [[0,5],[1,4],[2,3],[2,1],[3,3],[3,0],[4,5],[5,0]] => 7

4 [[1,1][0,3][1,0][3,0][3,3]] => 9

Remember that this is code-golf, thus the shortest answer in bytes wins !

APL (Dyalog 16.0), 54 characters or 60 bytes
Takes enclosed matrix as argument, returns the step number which completes infection, i.e. 1=is already fully infected. 0=does not fully spread, which is just 1 + the OP's numbers.
54 characters (Unicode):
(≢×0=0∊⊃){(⊢≡f←⊢∨2≤{+/,⍵×3 3⍴0 1}⌺3 3)⊃⍵:⍵⋄(⊂f⊃⍵),⍵}⍣≡

60 bytes (Classic):
(≢×0=0∊⊃){(⊢≡f←⊢∨2≤{+/,⍵×3 3⍴0 1}⎕U233A 3 3)⊃⍵:⍵⋄(⊂f⊃⍵),⍵}⍣≡

⌺ is equivalent to ⎕U233A
Examples' run:
      g←(≢×0=0∊⊃){(⊢≡f←⊢∨2≤{+/,⍵×3 3⍴0 1}⌺3 3)⊃⍵:⍵ ⋄ (⊂f⊃⍵),⍵}⍣≡
      ⎕IO←0
      b←⊂⊖⍉~@(⎕JSON'[[0,5],[1,4],[2,3],[2,1],[3,3],[3,0],[4,5],[5,0]]')⊢0⍴⍨2⍴6
      g b
8
      b←⊂⊖⍉~@(⎕JSON'[[1,1],[0,3],[1,0],[3,0],[3,3]]')⊢0⍴⍨2⍴4
      g b
10

The steps are as follows:

┌─────────────┬─────────────┬─────────────┬─────────────┬─────────────┬─────────────┬─────────────┬─────────────┐
│ X       X   │ X X     X   │ X X X   X   │ X X X X X   │ X X X X X   │ X X X X X   │ X X X X X   │ X X X X X X │
│   X         │ X X X       │ X X X X     │ X X X X X   │ X X X X X   │ X X X X X   │ X X X X X X │ X X X X X X │
│     X X     │   X X X     │ X X X X     │ X X X X     │ X X X X X   │ X X X X X X │ X X X X X X │ X X X X X X │
│             │     X       │   X X X     │ X X X X X   │ X X X X X X │ X X X X X X │ X X X X X X │ X X X X X X │
│     X       │     X X     │     X X X   │   X X X X X │ X X X X X X │ X X X X X X │ X X X X X X │ X X X X X X │
│       X   X │     X X X X │     X X X X │     X X X X │   X X X X X │ X X X X X X │ X X X X X X │ X X X X X X │
└─────────────┴─────────────┴─────────────┴─────────────┴─────────────┴─────────────┴─────────────┴─────────────┘
┌─────────┬─────────┬─────────┬─────────┬─────────┬─────────┬─────────┬─────────┬─────────┬─────────┐
│ X     X │ X     X │ X     X │ X     X │ X     X │ X     X │ X   X X │ X X X X │ X X X X │ X X X X │
│         │         │         │         │       X │     X X │   X X X │ X X X X │ X X X X │ X X X X │
│   X     │   X     │   X X   │   X X X │   X X X │   X X X │   X X X │   X X X │ X X X X │ X X X X │
│   X   X │   X X X │   X X X │   X X X │   X X X │   X X X │   X X X │   X X X │   X X X │ X X X X │
└─────────┴─────────┴─────────┴─────────┴─────────┴─────────┴─────────┴─────────┴─────────┴─────────┘


Princely Prefix by a Program in Pattern You should write a program or function which outputs or returns as much of Chapter I of The Little Prince as it can. Your program or function has to be an M-by-N block of code containing only printable ascii characters (codepoint from 32 to 126) and newlines at the end of each row.

You can only use at most 26 characters of your choosing from the 96 printable ascii characters (and the newlines at the end of the rows).

In each row and column every character has to be distinct similar to a sudoku puzzle i.e. there can't be a letter in a row or column twice.

A correct example codeblock with M = 4, N = 3 and alphabet = {a,b,c,d,/,*}:

abcd
bcd*
*/ac

Code details

You can choose the shape of your code-block (i.e. M and N).
The block has to be filled with characters entirely i.e. every row has to have the same length.
A trailing newline at the end of the last row is optional.
As written above in each row and column every character has to be distinct.

Output details

You should output or return a prefix of Chapter I of The Little Prince  without any additional output.
If you reach a newline in the text you can represent it as any common variant (\r,\n,\r\n) but use only one of them and count it as 1 byte to the score.
An extra trailing newline is optional.

Your score is the length of the output text excluding an additional newline if present. Higher score is better.

Example answer

##Python3, score = 6

alphabet = `print('O\ce w)#X` (alphabet element count = 16)

    print('O\
    nce w')#X

You can check the validity of your code with this Python 3 (ideone) program or this CJam program (online) provided by @MartinBüttner.

Pip, score = 38
eyli:
"Once
when0
I was
si01x
year5
old I
0sMw1
1M 0"
X1RMh
Rnsxy
iR:'M
'aiR
:5'si

Alphabet:  "'015:IMORXacdehilnorswxy
(I sure would hate to try this in a real programming language.)
Explanation:
eyl      Statements consisting of single variables are no-ops
i:       Assign to i the following:
"Once
when0
I was
si01x
year5
old I
0sMw1
1M 0"    ...this string
X1       ...repeated once (no-op to get alignment right)
RMh      ...with all 1s and 0s removed (h is preinitialized to 100)
Rns      ...and all newlines replaced with spaces.
xy       More no-ops
iR:'M'a  Replace every M with a, assigning result back to i
iR:5's   Replace every 5 with s, assigning result back to i
i        Auto-print i


Print custom alphabet The Challenge

Display the alphabet from a given letter read from console input. If the letter is uppercase, you have to display the alphabet uppercased. The alphabet printed must end in the precedent letter of the one inserted. If an additiontal parameter is added to the input (a simple dot .) the alphabet should be printed one letter in each line. Otherwise, the alphabet should be printed in the same line, separed by a simple space. If wrong input is send to the program it will not print anything.

Inputs examples:

Input:

c

Program's ouput:

d e f g h i j k l m n o p q r s t u v w x y z a b

Input

H.

Program's ouput:

I
J
K
L
M
N
O
P
Q
R
S
T
U
V
W
X
Y
Z
A
B
C
D
E
F
G


Calculating Resistance (Nerd Sniping) Good Afternoon Golfers,

Our challenge for today is inspired by XKCD comics 356 and 370. We're going to write a program to calculate the resistance of a group of resistors. A forewarning that this is nearly tough enough to warrant being a code challenge, however I think that there is a certain art to writing slightly more complex programs in a golfed format. The lowest amount of characters wins.

Calculating the resistance relies on the following two formulas:

If the resistors are in series, the resistance is the sum of the each resistor's resistance
If the resistors are in parallel, the resistance is the inverse of the sum of the inverse of the resistance of each resistor

So - for example:

Your challenge is to, in the least amount of characters possible, calculate the resistance of a group of up to 64 resistors. My apologies for the complexity, particularly of the input rules. I've attempted to define them in such a way that every language will be usable.

Each resistor will be connected to 2 or more other resistors.
The input is guaranteed to be valid, with only one entry and one exit point, which will connect
The network will be series-parallel to prevent requiring more maths then what is presented
Input will be via file, argument or stdin, depending on what is appropriate for your language.
Input will consist of a series of newline or forward slashed separated statements consisting of an integer of the resistance of the resistor, and spaces separating the IDs of the resistors that one side of the resistor is connected to.
The ID of the first resistor will be 1, incrementing by one for each successive resistor
The start will always have an ID of 0
The final resistor will always have a resistance of 0 ohms, and only have the connections defined in its line

For example:

Could be represented as

3 0
6 1
1 0
5 0
0 2 3 4

Output can be to stdout or file. It may be represented in one of the following ways:

A number with a minimum of 2 decimal places, followed by a newline
A fraction consisting of an integer (the numerator), a forward slash and another integer (the denominator), followed by a newline. The fraction does not need to be the to be in its lowest form - 4/4 or 10/8 are, for instance acceptable. The fraction must be accurate within 1/100. There is no bonus for being perfectly accurate - this is provided is a crutch to enable languages without fixed or floating point operations to compete.

I hope that covers all the points. Good luck!

Python, 329 chars

import sys
N=[[1]]+[map(int,x.split())for x in sys.stdin]
N[-1][0]=1
n=len(N)
S=[set([i])for i in range(2*n)]
for x in range(n):
 C=S[2*x]
 for y in N[x][1:]:C|=S[2*y+1]
 for x in C:S[x]|=C
V=[0]*(2*n-1)+[1]
for k in range(999):
 for i in range(1,2*n-1):V[i]+=sum((V[j^1]-V[i])/N[j/2][0]for j in S[i])/9./len(S[i])
print 1/V[1]-2

Calculates the resistance by doing a voltage relaxation on the circuit.  First it tacks on a 1 ohm resistor to the start and changes the last resistor from 0 ohm to 1 ohm.  Then it sets the input voltage to 0 and the output voltage to 1 volt.  After simulating current flow through the network, the network resistance is calculated using the voltage drop across the first 1 ohm resistor.

Each resistor is given two numbers, the number for its left terminal and the number for its right terminal.  Resistor r's left terminal is 2*r and its right terminal is 2*r+1.  The input is used to calculate S, the sets of terminals that are connected together.  Each terminal is given a voltage V[t] and a relaxation is done by raising the voltage if current is net flowing into a terminal set and lowering the voltage if current is net flowing out.


OMG! We're Twinning! Introduction

We define twin primes as two natural numbers p,p+2 which both are prime.

Example: 5 and 7 are twin primes.

Let's define the twin number of some set of numbers as the number of twin prime numbers in that set

Example: {6,7,11,13,18,29,31} has a twin number 4, since there are four twin primes; 11,13 and 29,31.

Program

Input: A number n

Output: The twin number of the set of all natural numbers below n

Scoring

This is code-golf, so lowest bytes wins.

MATL, 7 bytes
qZqd2=s

This solution exploits the fact that the prime gap (the difference between successsive prime numbers) is always >= 2 (with the exception being the gap between 2 and 3). Because of this fact, all twin primes will be successive prime numbers. In this solution we just compute the differences between all primes less than the input n and count how many of these differences are equal to 2.
Try it Online
Explanation
    % Implicitly grab input, N
q   % Subtract one from the input (N-1)
Zq  % Get an array of all primes <= (N-1)
d   % Compute successive differences (prime gaps)
2=  % Create a boolean array indicating which prime gaps are equal to 2
s   % Count the TRUE values in this array to determine the twin number
    % Implicitly display the result

If you instead want the not the number of pairs but the number of primes that are part of a pair, the following would work
qZqt!-|H=az

Try it Online


Decode ascii and reversed words sentence In a challenge of CodingGame, there is a challenge that ask you to decode a string composed by reversed words ('Hello world' > 'olleH dlrow') then each characters converted into ascii value separeted by space:

>>> decode('111 108 108 101 72 32 100 108 114 111 119 32 41 58')
Hello world :)

The challenge is to be the fastest to write the decode function, but I later tried to write it with the fewest character possible.

Here is my result (104 characters):

def decode(m,s=' '):return s.join([w[::-1]for w in(''.join([chr(int(c))for c in m.split(s)]).split(s))])

The name of the function doesn't matter, it can be shorter, but only rename variable isn't good enough for an answer.

Is it possible to improve this result ?

Use lambdas

def f(a,b):return c

can be shortened to

f=lambda a,b:c

(the f= can also be removed per CGCC site standards)

Remove excess []s

x.join([a for b in c])

can be

x.join(a for b in c)

since join can take a generator instead of a list

Split is on spaces by default

Thanks ElPedro for reminding me about this

So the split(' ')s can be shortened, which in turn means the s=' ' doesn't help (and it only broke even in the first place).

Take input from STDIN and output to STDOUT

print will automatically print arguments with space as a separator if you use * to unpacks the sequence/collection into positional arguments, and taking input via input() is shorter. Also, setting s to space doesn't actually save any bytes.

Altogether, this is 79 bytes:

print(*[w[::-1]for w in(''.join(chr(int(c))for c in input().split()).split())])

Try it online!

or, if you're dedicated to having a function, 82 bytes:

lambda m:' '.join(w[::-1]for w in(''.join(chr(int(c))for c in m.split()).split()))

Try it online!

plus seven or so characters if you really need the function to be called decode


Remove boxes under preservation of shape This challenge is specific to languages of the APL family. Although it might be solvable in other languages, please do not expect this to be easy as it depends on some specific concepts of this language family.

Many array oriented languages have the concept of a box (also called enclosure). A box encapsulates an array, hiding its shape. Here is an example of a boxed array:

┌─┬───────┬─────┐
│0│1 2 3 4│0 1 2│
│ │       │3 4 5│
└─┴───────┴─────┘

This array was generated from the J sentence 0 ; 1 2 3 4 ; i. 2 3 and contains three boxes, the first containing the scalar 0, the second containing a vector of shape 4, and the third containing a matrix of shape 2 3.

Some arrays of boxes look like they are plain arrays broken apart by boxes:

┌─┬───────────┐
│0│1 2 3 4    │
├─┼───────────┤
│5│ 9 10 11 12│
│6│13 14 15 16│
│7│17 18 19 20│
│8│21 22 23 24│
└─┴───────────┘

The previous array was generated from the J expression 2 2 $ 0 ; 1 2 3 4 ; (,. 5 6 7 8) ; 9 + i. 4 4.

Your goal in this challenge is to take an array like that and remove the boxes separating the subarrays from one another. For instance, the previous array would be transformed into

0  1  2  3  4
5  9 10 11 12
6 13 14 15 16
7 17 18 19 20
8 21 22 23 24

Submit a solution as a monadic verb / function. The verb must work on arrays of arbitrary rank. You may assume that the shapes of the boxed arrays fit, that is, boxed subarrays adjacent on an axis have to have the same dimensions in all but that axis. Behaviour is undefined if they don't.

This challenge is code golf. The submission compromising the least amount of characters wins.


Need change of 78 cents You bought a tasty Orange in the supermarket and got 78 cents change. How many possible ways the supermarket guy can give you the change using 1,5,10 or 25 coins

Input: Change amount
Output: The number of possible ways to give the change.

Order is not important 1,5 is same as 5,1

Win conditions:

Best performance
Shortest code

Also please add the result for 78 in your title.


Official Dyalog APL 2016 Year Game If you think this could be fun, but too much work, consider participating in this much smaller challenge.

A bit of fun (and possibly frustration!) for 2016... Dyalog's "puzzle of the year". Enjoy!
The Objective
Find Dyalog APL (download) expressions (other languages are allowed, see Eligibility below) involving exactly the digits 2 0 1 6 in that order to equal the numbers 0 to 100. For example:
20=16
×2016
2⌊016
2+0+1*6
...
The aim is to use as few characters as possible in each expression (the minimum number of characters for an expression is 5 – the four digits 2 0 1 6 and a single primitive function/operator).
The Rules

Each expression must contain the digits 2 0 1 6 (in that order) and
no other digits. Pre-set constants and variables are also not allowed.
In addition to the four digits 2 0 1 6, only built-in symbols and names, parentheses/braces, spaces, high minus signs and
decimal points can be used. The resultant expressions must be
deterministic (that is, give the same result on repeated
evaluations). For non-APLs, functions/operators with a name are also allowed; same rules as here.
Assume all default settings for your language. For Dyalog APL, this means ⎕ML and ⎕IO are both 1, and ⎕PP is 10.
Each entry comprising correct expressions for all the numbers from 0
to 100 inclusive will be rated according to the number of characters
used by those expressions excluding redundant spaces (minimum 505 for
all 101 expressions).

Eligibility
Anyone can enter. You may answer in any language, but only APL answers will be considered for accepting. If you use another language than APL, you may use snippets, programs, functions, etc. as alternatives to expressions, and you may print, leave the number in an accessible memory location, or otherwise return the result, as long as your code directly evaluates to the desired number as any standard numeric data type for your language.
Closing Date
30 November 2016.
Prizes

Have your answer accepted
Be immortalised in Dyalog's 2016 Hall of Fame!

Submitting Your Entry
After 30 November 2016, I will accept the shortest answer, and submit your answer, in your name, to Dyalog's 2016 Hall of Fame.
FAQ

Is J (e.g. 37=⌈⍟!20J16) allowed?
No: In addition to the four digits 2 0 1 6, only only built-in symbols and names, parentheses/braces, spaces, high minus signs and decimal points can be used.

Is output as a string acceptable?
No: equal the numbers 0 to 100.

Physical digits, or data digits?
Data digits, as per OP: same rules as here, where one of the examples contain LOG10(.

Is assigning variables then using them as part of the expression (e.g. 56=a+16+a←20) allowed?
Yes, but you may not use an assignment from one expression in another one.

I have explicit written permission to post this challenge here from the original author of this challenge. Feel free to verify by following the provided link and contacting the author. I gave the original competition author the link to this page within the minute I posted it, so they can check if I submit someone's answer as my own.


What will be on the top of this decorative calendar? Someone gave my wife a decorative calendar consisting of four cubes. Here it is showing today's date (as of the posting of this challenge) on the front:

When I first saw it, I looked at it from the wrong angle (from directly above) and couldn't figure out why it gave this information:

[["February", "January"], [3], [7], ["Monday", "Tuesday"]]

Your job is to replicate my error for any date in 2019.

Challenge

Write a program or function that takes any date from 2019, and outputs what appears on the top of all the cubes when that date is displayed facing out from the front of the calendar.

Here are all six sides for all the cubes. To display a 6 you just turn the 9 upside down. The 0 is vertically symmetrical, so 0 upside down is still 0. There might be more than one correct answer for some dates (e.g. any 11th of any month will have more than one way to use the cubes, and the 0 thing) so you can output any correct answer.

Rules

Standard loopholes forbidden.
Input/output format is flexible.
The output does have to be in order by cube, but not within a cube. The order must be month cube first, then the two number cubes, followed by the weekday cube. But when a cube has two elements on top, those two elements can be in either order.
You can replace January to December 0-11 or 1-12 if you like.
You can replace the days of the week with 0-6 or 1-7 if you like, and you can start the week on either Sunday or Monday (but you can't start the week on any other day - this is PPGC, not some sort of crazy-town.)
This is code-colf. Fewest bytes for each language wins.
Explanations encouraged.

Test cases

(Tue) 2019-01-29   [[ "July", "August" ], [3], [7], [ "Thursday", "Wednesday" ]]
                   [[ "August", "July" ], [3], [7], [ "Wednesday", "Thursday" ]]

                   etc. since the order within each cube doesn't matter.

(Thu) 2019-07-11   [[ "May", "June" ], [3], [8], [ "Saturday", "Friday" ]]
                   [[ "May", "June" ], [8], [3], [ "Saturday", "Friday" ]]

                   since the two 1 cubes could be either way.

(Sun) 2019-10-27   [[ "January", "February" ], [3], [6], [ "Friday", "Saturday" ]]

(Wed) 2019-05-01   [[ "March", "April" ], [8], [3], [ "Monday", "Tuesday" ]]
                   [[ "March", "April" ], [6], [3], [ "Monday", "Tuesday" ]]
                   [[ "March", "April" ], [9], [3], [ "Monday", "Tuesday" ]]

                   since the 0 cube could have either the 8 side or the 6 side facing up, and the 6 could also be considered a 9.

(Sat) 2019-08-24   [[ "February", "January" ], [8], [5], [ "Sunday" ]]


Be the First 1 (leave only the first Truthy) Intro
Every year, Dyalog Ltd. holds a student competition. The challenge there is to write good APL code. This is a language agnostic code-golf edition of this year's eighth problem.
I have explicit permission to post this challenge here from the original author of the competition. Feel free to verify by following the provided link and contacting the author.
Problem
Given a Boolean* list, "turn off" all the Truthies after the first Truthy.
No Truthies? No problem! Just return the list unmodified.
Examples
[falsy,truthy,falsy,truthy,falsy,falsy,truthy] → [falsy,truthy,falsy,falsy,falsy,falsy,falsy]
[] → []
[falsy,falsy,falsy,falsy] → [falsy,falsy,falsy,falsy]

* All your truthies must be identical, and all your falsies must be identical. This includes output.

Python 2, 35 bytes

while 1:b=input();print b;True&=b<1

Try it online! Input and output are lines of True/False.

Based on Dennis's solution. Redefines the variable True to be False after a True input is encountered. That way, any further inputs of True will evaluate to False and be printed as such. Python 3 no longer allows True and False to be redefined, so this answer uses Python 2.

The redefinition is True&=b<1, i.e. True = True & (b<1). When the input b is True, then (b<1) is False (since True==1), so True becomes False. See Kevin Cruijssen's answer for a shorter way to handle this redefinition.


This Is A Self-Referential Problem Tupper's Self-Referential Formula (copied from Wikipedia)
Tupper's self-referential formula is a formula defined by Jeff Tupper that, when graphed in two dimensions at a very specific location in the plane, can be "programmed" to visually reproduce the formula itself. It is used in various math and computer science courses as an exercise in graphing formulae.
$$
\frac{1}{2} <
    \left\lfloor
     \text{mod}\left(
      \left\lfloor
       \frac{y}{17}
      \right\rfloor
      2^{
        -17
        \lfloor x \rfloor
        -\text{mod}\left(
         \lfloor y \rfloor
         ,17
        \right)
      }
     ,2
     \right)
    \right\rfloor
$$
where  \$\lfloor\cdot\rfloor\$  is the floor function.
Let \$k\$ be the following 543-digit number:
960939379918958884971672962127852754715004339660129306651505519271702802395266424689642842174350718121267153782770623355993237280874144307891325963941337723487857735749823926629715517173716995165232890538221612403238855866184013235585136048828693337902491454229288667081096184496091705183454067827731551705405381627380967602565625016981482083418783163849115590225610003652351370343874461848378737238198224849863465033159410054974700593138339226497249461751545728366702369745461014655997933798537483143786841806593422227898388722980000748404719
If one graphs the set of points \$(x, y)\$ in \$0 \le x < 106\$ and \$k \le y < k + 17\$ satisfying the inequality given above, the resulting graph looks like this (note that the axes in this plot have been reversed, otherwise the picture comes out upside-down):

So what?
The interesting thing about this formula is that it can be used to graph any possible black and white 106x17 image. Now, actually searching through to search would be extremely tedious, so there's a way to figure out the k-value where your image appears. The process is fairly simple:

Start from the bottom pixel of the first column of your image.
If the pixel is white, a 0 will be appended to the k-value. If it is black, append a 1.
Move up the column, repeating step 2.
Once at the end of the column, move to the next column and start from the bottom, following the same process.
After each pixel is analyzed, convert this binary string to decimal, and multiply by 17 to get the k-value.

What's my job?
Your job is to create a program which can take in any 106x17 image, and output its corresponding k-value. You can make the following assumptions:

All images will be exactly 106x17
All images will only contain black (#000000) or white (#FFFFFF) pixels, nothing in between.

There's a few rules, too:

Output is simply the k-value. It must be in the proper base, but can be in any format.
Images must be read from either a PNG or PPM.
No standard loopholes.

Test Images
[  ] should produce ~1.4946x10542
[  ] should produce ~7.2355x10159
[  ] should produce 21801 * 17
[  ] should produce (21802-1) * 17
Check out this Gist for the exact solutions.
This is code-golf, so least number of bytes wins.

Helpful Links
Wikipedia
Wolfram Mathworld

Pyth - 21 bytes
Simple to do with pyth's i base conversion. Takes input as PBM file name and reads using ' command. I had to use !M to negate blacks and whites. Everything else is self-explanatory.
*J17i!MsC_cJrstt.z7 2

Try it here online. (Web interpreter can't read files, so is modified and takes file as input).


Score counter for Skat You task is to write a small program, that counts the points of a Skat hand. A Skat deck has cards 7 to 10, Jack, Queen, King and Ace (called Unter, Ober, König and Daus). We use the German suits, which have Acorns, Leaves, Hearts and Bells instead of Clubs, Spades, Hearts and Diamonds. The points are determined by the number on the card:

7, 8 and 9 are 0 points
Unter is 2 points
Ober is 3 points
König is 4 points
10 is 10 points
Daus is 11 points.

Input / Output
The input format consists of two symbols, the first one represents the value, while the second one stands for the suit:

7, 8 and 9 stand for them self
0 (zero) stands for 10
Unter, Ober, König and Daus are named after their first letters (U, O and D)
The same for Acorns, Leaves, Hearts and Bellys (A, L, H and B)

The input is a single line of cards, separated by a single whitespace. You may take the input from anywhere, command line arguments are okay too. The output is the value of the hand, either printed out or returned as an exit code. The output of your program must show an error, if any card appears twice in the hand. (So 7A 0L 7A must return an error instead of 10). It is also okay to quit with an exit code of 255 instead of showing an error, if this is the default way of your program to output the result.
Examples

7A 8A 9A UA OA KA 0A DA 7L 8L 9L UL OL KL 0L DL 7H 8H 9H UH OH KH 0H DH 7B 8B 9B UB OB KB 0B DB gives 120
7A 8L 0K DB 8L gives an error
UA OB DL KH gives 20

Rules

Code golf: The shortest code wins
Usual code golf rules apply
The program has to work for all hands, not just the examples
GIGO: If the input is invalid, the output may be arbitrary

Ruby 1.9, 52 characters

Input via command line arguments. I'm assuming the error message when having duplicate cards doesn't matter, so it just complains about an eval/type conversion error.

p eval$*.uniq!||$*.map{|i|"..UOK#$<.0D"=~/#{i}?/}*?+

Example usage:

$ ruby1.9 skatscore.rb 7A 8A 9A UA OA KA 0A DA 7L 8L 9L UL OL KL 0L DL 7H 8H 9H UH OH KH 0H DH 7B 8B 9B UB OB KB 0B DB
120

$ ruby1.9 skatscore.rb 7A 7A
skatscore.rb:1:in `eval': can't convert Array into String (TypeError)
    from skatscore.rb:1:in `<main>'


Spiralize a Word, Triangularly! Challenge
Given a string of any length, write it as a triangle, spiraling out from the center.  For example, abcdefghijklmnop becomes:
   g
  fah
 edcbi
ponmlkj

Or more explicitly:

If you like, you can spiral counter-clockwise instead:
   g
  haf
 ibcde
jklmnop

Or add spaces uniformly:
      g

    f a h

  e d c b i

p o n m l k j

The input characters will be ascii, but may include spaces.   Also, the number of characters may not be a perfect square (Hello World!):
  W
  Ho
oller
   !dl

A couple more edge cases.  2 letter input ab:
 a
  b

And 3 letter input abc:
 a
 cb

Procedural Description
In case the above examples aren't clear, here's a procedural description of the process:

Put down your initial letter.
Move diagonally down and to the right (i.e., this direction \).  So if you started at (0,0), you will now be at (1,-1).  Put down your second letter.
Move left one space a time, dropping a letter on each space, for a total of 3 spaces.  That is, drop letters on (0,-1), (-1,-1), and (-2, -1).
Next move diagonally up and to the right / two spaces, dropping letters on (-1,0) and (0,1).
Now cycle back to moving diagonally down and to the right, continuing to step and drop letters as long as your current position is left-right adjacent to an existing letter.
Next move left again, continuing to step and drop letters as long as you are diagonally adjacent / to an existing letter.
Move diagonally up and to the right again /, stepping and dropping letters as long as your current position is left-right adjacent to an existing letter.
Repeat steps 5-7 until all letters are used up.

More examples
Rules

Code golf, standard rules apply.
Trailing spaces or newlines are ok.
Consistent leading spaces or newlines are also ok, as long as the shape of the triangle is preserved.

Wolfram Language (Mathematica), 99 bytes
sPrint@@@Array[s[[4# #-2#+1-#2&@@If[Abs@#2<2#,!##,#-Abs@#2|-#2]]]/._@__->" "&,2{L=Tr[1^s],L},-L]

Try it online!
Directly computes the index of each position: in Cartesian coordinates,
\$\operatorname{index}(x,y)=\textit{offset}+\begin{cases}2y(2y+1)-x,&|x|<-2y\\
2\left(y+|x|\right)\left(2\left(y+|x|\right)+1\right)+x,&\text{else}\end{cases}\$
where \$\textit{offset}\$ is the index of the "first" character (1, in Mathematica).
Takes a list of characters as input.

Older approach, 123 122 109 107 bytes
Print@@@Normal@SparseArray[i=0;p=2Length@#;(p+=ReIm[I[2+I,1-I][[⌈2√i++⌉~Mod~4-1]]-1])->#&/@#,2p," "]&

Try it online!
The direction of the (1-indexed) ith character relative to the previous character can be computed with \$\Big\lceil2\sqrt i\Big\rceil\bmod 4\$:

1: ↗
2: ↘
3,0: ←


Calculate the Super-Logarithm This should be a simple challenge.
Given a number \$n \ge 0\$, output the super-logarithm (or the \$\log^*\$, log-star, or iterated logarithm, which are equivalent since \$n\$ is never negative for this challenge.) of \$n\$.
$$\log^*(n) = \begin{cases}
0  & \text{ if } n \le 1 \\
1 + \log^*(\log(n)) & \text{ if } n > 1
\end{cases}$$
This is one of the two inverse functions to tetration. The other is the super-root, which is in a related question.
Examples
Input       Output
0           0
1           0
2           1
3           2
4           2
...
15          2
16          3
...
3814279     3
3814280     4

Rules

You do not need to support decimals, though you may.
You need to support input of at least \$3814280 =  \left\lceil e^{e^e} \right\rceil\$.
You may not hard-code the values like 3814280. (Your program must theoretically support higher numbers.) I want an algorithm to be implemented.
Shortest code wins.

Related OEIS

Jelly, 8 bytes

ÆlÐĿĊḊi1

Try it online! or verify all test cases.

Background

We start by successively taking natural logarithms of the input and the subsequent results until the result no longer changes. This works because the extension of the natural logarithm to the complex plane has a fixed point; if z = e-W(-1) ≈ 0.318 + 1.337i – where W denotes the Lambert W function – we have log(z) = z.

For input n, after computing [n, log(n), log(log(n)), …, z], we first apply the ceiling function to each of the results. Jelly's implementation (Ċ) actually computes the imaginary part of complex number instead†, but we're not interested in these anyway.

Once the kth application of log yields a value less than or equal to 1, Ċ will return 1 for the first time. The 0-based index of that first 1 is the desired result.

The straightforward implementation (compute 1-based index, decrement) fails because of edge case 0, which does not have a 1 in its list of logarithms. In fact, for input 0, the sequence of logarithms is

[0, None]

This is because Jelly's logarithm (Æl) is overloaded; it first tries math.log (real logarithm), then cmath.log (complex logarithm), and finally "gives up" and returns None. Fortunately, Ċ is similarly overloaded and simply returns it argument if it cannot round up or take an imaginary part.

Likewise, input 1 returns

[1, 0, None]

which may create problems in other approaches that do or do not involve Ċ.

One way to fix this problem is apply Ḋ (dequeue; removes first element) to the array of logarithms. This maps

0ÆlÐĿ -> [0, None]    -> [None]
1ÆlÐĿ -> [1, 0, None] -> [0, None]

so neither list has a 1 now. This way, finding the index of the first 1 will return 0 (not found), which is the desired output for inputs 0 and 1.

How it works

ÆlÐĿĊḊi1  Main link. Argument: n (non-negative integer)

  ÐĿ      Apply the following link until the results are no longer unique.
Æl          Natural logarithm.
          Return the array of all unique results.
    Ċ     Round all resulting real numbers up to the nearest integer. This takes
          the imaginary part of complex numbers and does nothing for non-numbers.
     Ḋ    Dequeue; remove the first item (n) of the array of results.
      i1  Find the first index of 1 (0 if not found).

† This is one of the only three atoms in Jelly that are overloaded in a non-obvious manner.


What is my exponential potential? We'll define the N-exponential potential of a positive integer M as the count of prefixes of MN that are perfect N-powers.

The prefixes of an integer are all the contiguous subsequences of digits that start with the first one, interpreted as numbers in base 10. For example, the prefixes of 2744 are 2, 27, 274 and 2744.

A prefix P is a perfect N-power if there exists an integer K such that KN = P. For example, 81 is a perfect 4-power because 34 = 81.

Given two strictly positive integers M and N, compute the N-exponential potential of M according to the definition above.

For instance, the 2-exponential potential of 13 is 3 because 132 is 169, and 1, 16 and 169 are all perfect squares.

Test cases

Naturally, the outputs will nearly always be pretty small because powers are... well... exponentially growing functions and having multiple perfect-power prefixes is rather rare.

M, N     -> Output

8499, 2  -> 1
4,    10 -> 2
5,    9  -> 2
6,    9  -> 2
13,   2  -> 3

Brachylog, 12 bytes

{^a₀.&b~b^}ᶜ

Try it online!

Explanation

{^a₀.&b~b^}ᶜ
{         }ᶜ  Count the number of ways the following can succeed:
  a₀            A prefix of
 ^                the first {input} to the power of the second {input}
    .&          produces the same output with the same input as
       ~b         any number
         ^        to the power of
      b           all inputs but the first (i.e. the second input)


Calculating total slots Given a list of jobs, which must be done in order, with each taking a slot to do, how long will it take to perform them all if after doing a job the same job cannot be done for the next two slots (cooling off slots)? However, a different job can be assigned in this cooling off slots.

For example,

[9,10,9,8] => output: 5

Because jobs will be allocated as [9 10 _ 9 8].
1. First, 9 needs two cooling off spots _ _. So we start with 9 _ _.
2. Next job 10 is different from the previous job 9, so we can allocate one of _ _. Then we will have 9 10 _.
3. Third, 9 cannot be allocated now, since first job 9 is the same job and it needs cooling off time. 9 10 _ 9.
4. Last, 8 is not same as any other previous two jobs, so it can be allocated right after 9 and since this is last job, it does not need cooling off time. Final list is 9 10 _ 9 8 and expected output is 5, which is the number of spots (or number of slots)

Test cases:

[1,2,3,4,5,6,7,8,9,10] => output : 10 ([1 2 3 4 5 6 7 8 9 10])
[1,1,1] => output: 7 ([1 _ _ 1 _ _ 1])
[3,4,4,3] => output: 6 ([3 4 _ _ 4 3])
[3,4,5,3] => output: 4 ([3 4 5 3])
[3,4,3,4] => output : 5 ([3 4 _ 3 4])
[3,3,4,4] => output : 8 ([3 _ _ 3 4 _ _ 4])
[3,3,4,3] => output : 7 ([3 _ _ 3 4 _ 3])
[3,2,1,3,-4] => output : 5 ([3 2 1 3 -4])
[] => output : 0 ([])
[-1,-1] => output : 4 ([-1 _ _ -1])

Input value can be any integer (negative, 0, positive).
Length of job-list is 0 <= length <= 1,000,000.
Output will be an integer, the total number of slots, which is indicated in test case as output. The list inside the parenthesis is how the output would be generated.

Winning criterion
code-golf

05AB1E, 22 bytes
v¯R¬yQiõˆ}2£yåiˆ}yˆ}¯g

Try it online or verify all test cases.
Explanation:

v           # Loop over the integers `y` of the (implicit) input-list:
 ¯R         #  Push the global_array, and reverse it
   ¬        #  Get the first item (without popping the reversed global_array itself)
    yQi  }  #  If it's equal to the integer `y`:
       õˆ   #   Add an empty string to the global_array
   2£       #  Then only leave the first 2 items of the reversed global_array
     yåi }  #  If the integer `y` is in these first 2 items:
        ˆ   #   Add the (implicit) input-list to the global_array
 yˆ         #  And push the integer `y` itself to the global_array
}¯g         # After the loop: push the global array, and then pop and push its length
            # (which is output implicitly as result)


Python; accuracy = 54,074,818; size = 65,526 bytes

Previous scores: 50,227,165; 50,803,687; 50,953,001

#coding=utf-8
d=r'''<65,400 byte string>'''
def f(x,y):
 a=max(x,y)-20000;b=min(x,y)-20000;c=(a*(a+1)//2+b)%523200
 return(ord(d[c//8])>>(c%8))&1

This approach divides all unique entries of the matrix into 523,200 groups and reads the best guess for the group (x, y) from a binary string. You can download the full source code from Google Drive.

I've used @PeterTaylor's parities to generate the string and to compute the accuracy.


Find out my number neighbors The input consists of i rows with neighbors information. Each ith row contains 4 values, representing the neighbor of i to the North, East, South and West directions, respectively. So each value represents a neighbor at the given direction of the ith row, starting from row 1, and can go up to 65,535 rows. The 0 value indicates no neighbor to that direction.

For instance, if the first row is "0 2 3 10" it means that the i neighbor has three other neighbors: no one to the north, neighbor 2 to the east, neighbor 3 to the south and neighbor 10 to the west.

You need to output the array of neighbors, starting from the value which is most to the northwest. Each neighbor will be displayed only once, at its position relative to others. Let's see some examples:

Input:

0 0 0 0

No neighbors (empty case), output:

1

Input:

0 2 0 0
0 0 0 1

1 has neighbor 2 to the east. 2 has neighbor 1 to the west

Output:

1 2

Input:

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

1 has neighbor 2 to the east. 2 has neighbor 1 to the west and 3 to the south.
3 has neighbor 2 to the north

Output:

1 2
  3

Input:

2 0 0 0
0 0 1 0

Output:

2
1

Input:

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

Output:

1 2
3 4

Rules:

Test cases are separated by one empty line. Output of different test cases must also be separated by one empty line.
The output graph is always connected. You are not going to have 1 neighbor to 2 only, along with 3 neighbor to 4 only (isolated from 1-2 component).
All entries are valid. Example of invalid entries:

Entries containing letters or any symbol different than spaces, line breaks and digits (0-9).
the ith row containing the ith value (because one can't be its own neighbor).
a negative value or value higher than 65,535.
Less than four values in a row.
More than four values in a row.
The same neighbor pointing to two different directions (ex: 0 1 1 0).

Standard loopholes apply, and the shortest answer in bytes wins.

Python 2, 152 bytes

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

Try it online!

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


How Many Rectangles in the Grid? Well, although this challenge turned out to be a huge success, it also turned out to be very trivial to solve. Therefore, for those of looking for more of a challenge, I created a sequel to this challenge in which you must now count the number of unique rectangles. Check it out!
Now, for those of you looking to solve this challenge, here it comes.

Well, we don't really have a challenge like this yet, so here we go.
Consider this 3 x 3 grid of rectangles:

How many rectangles are there? Well, counting visually, we can see that there are actually 36 rectangles, including the entire plane itself, which are all shown in the animated GIF below:

The Task
The counting of rectangles as shown above is the task. In other words, given 2 integers greater than or equal to 0, m and n, where m represents the width and n represents the height, output the total number of rectangles in that m x n grid of rectangles.
Rules

The use of any built-ins that directly solve this problem is explicitly disallowed.

This challenge is not about finding the shortest answer, but finding the shortest answer in every language. Therefore, no answer will be accepted.

Standard loopholes are prohibited.

Test Cases
Presented in the format Array of Integers Input -> Integer Output:
[0,0] -> 0
[1,1] -> 1
[3,3] -> 36 (Visualized above)
[4,4] -> 100
[6,7] -> 588

References

http://oeis.org/A096948

Remember, this is code-golf, so shortest code wins!

Python, 22 bytes
lambda m,n:m*~m*n*~n/4

The formula m*n*(m+1)*(n+1)/4 is shortened using the bit-complement ~m=-(m+1), expressing (m+1)*(n+1) as ~m*~n.
Why is the number of rectangles m*n*(m+1)*(n+1)/4? Each rectangle is specified by the choice of two horizontal lines (top and bottom) and two vertical lines (left and right). There are m+1 horizontal lines, of which we choose a subset of two distinct ones. So the number of choices is choose(m+1,2), which is m*(m+1)/2. Multiplying by the n*(n+1)/2 choices for vertical lines gives the result.


The Nth Gryphon Number I came up with a series of numbers the other day and decided to check what the OEIS number for it was.  Much to my surprise, the sequence did not appear to be in the OEIS database, so I decided to name the sequence after myself (note that someone else who's a lot smarter than me has probably already come up with this, and if someone finds the actual name of this sequence, please comment and I'll change the question title).  As I couldn't find the sequence anywhere, I decided to name it after myself, hence "Gryphon Numbers".  EDIT: Thanks to @Surb for bringing to my attention the fact that this sequence is equal to OEIS sequence A053696 - 1.

A Gryphon number is a number of the form \$a+a^2+...+a^x\$, where both \$a\$ and \$x\$ are integers greater than or equal to two, and the Gryphon sequence is the set of all Gryphon numbers in ascending order.  If there are multiple ways of forming a Gryphon number (the first example is \$30\$, which is both \$2+2^2+2^3+2^4\$ and \$5+5^2\$) the number is only counted once in the sequence.  The first few Gryphon numbers are: \$6, 12, 14, 20, 30, 39, 42, 56, 62, 72\$.

Your Task:

Write a program or function that receives an integer \$n\$ as input and outputs the \$n\$th Gryphon number.

Input:

An integer between 0 and 10000 (inclusive).  You may treat the sequence as either 0-indexed or 1-indexed, whichever you prefer.  Please state which indexing system you use in your answer to avoid confusion.

Output:

The Gryphon number corresponding to the input.

Test Cases:

Please note that this assumes the sequence is 0-indexed.  If your program assumes a 1-indexed sequence, don't forget to increment all the input numbers.

Input:    Output:
0   --->  6
3   --->  20
4   --->  30
10  --->  84
99  --->  4692
9999 -->  87525380

Scoring:

This is code-golf, so the lowest score in bytes wins.

Jelly, 9 bytes

bṖ’ḅi-µ#Ṫ

A full program which reads a (1-indexed) integer from STDIN and prints the result.

Try it online!

How?

A Gryphon number is a number which is expressible in a base less than itself such that all the digits are ones except the least significant, which is a zero. For example:

\$30=1\times 2^4+1\times 2^3+1\times2^2+1\times2^1+0\times2^0 \rightarrow 30_2 = 11110\$

\$84=1\times 4^3+1\times 4^2+1\times 4^1+0\times 4^0 \rightarrow 84_4 = 1110\$

This program takes n, then starts at v=0 and tests for this property and increments v until it finds n such numbers, then outputs the final one.

To test a base b number it subtracts one from every digit, converts from base v, and then checks if the result is \$-1\$. (Note that b is less than v)

\$30_2 \rightarrow 0\times 30^4+0\times 30^3+0\times30^2+0\times30^1+(-1)\times30^0 = -1\$

\$84_4 \rightarrow 0\times 84^3+0\times 84^2+0\times 84^1+(-1)\times 84^0 = -1\$

bṖ’ḅi-µ#Ṫ - Main Link: no arguments
       #  - set v=0 then count up collecting n=STDIN matches of:
      µ   -  the monadic link -- i.e. f(v):  e.g. v=6
 Ṗ        -    pop (implicit range of v)            [1,2,3,4,5]
b         -    to base (vectorises)                 [[1,1,1,1,1,1],[1,1,0],[2,0],[1,2],[1,1]]
  ’       -    decrement (vectorises)               [[0,0,0,0,0,0],[0,0,-1],[1,-1],[0,1],[0,0]]
   ḅ      -    from base (v) (vectorises)           [0,-1,5,1,0]
     -    -    literal -1                           -1
    i     -    first index of (zero if not found)   2
          - }  e.g. n=11 -> [6,12,14,20,30,39,42,56,62,72,84]
        Ṫ - tail         -> 84
          - implicit print


Mirror and reverse text Inspired by I reverse the source code, ...
Your task, if you wish to accept it, is to reverse text and mirror select characters. Yes, yes, I know. Very surprising.
Input
A string, stdin, an array of characters, or any other source of text. All characters of the input are guaranteed to be in the printable ASCII range (32-126).
Output
The reversed text with some characters mirrored. To do this:

You replace any occurrences of the characters (, ), /, \, <, >, [, ], {, or } in the text with the corresponding "mirrored" character: ), (, \, /, >, <, ],  [, }, or {.
and then reverse the text.

You may assume a maximum line length of 255.
Rules

Standard loopholes apply.
This is code-golf, which means that the shortest answer in each programming languages wins. Consequently, I will not be accepting an answer.

Testcases
(s)t/r\i<n>g[i]e{s} -> {s}e[i]g<n>i/r\t(s)
stringies -> seignirts
()/\<>[]{} -> {}[]<>/\()
{s}e[i]g<n>i/r\t(s) -> (s)t/r\i<n>g[i]e{s}
seignirts -> stringies
{}[]<>/\() -> ()/\<>[]{}
qwertyuiop database -> esabatad poiuytrewq

As seen above, the output should go back to the input if run through the program again.
Sandbox link

Python 3, 61 60 59 bytes

lambda s,t="(/<[{}]>\)":[(c+t)[~t.find(c)]for c in s][::-1]

Try it online!

 -1 byte thanks to @xnor.

Changed the lookup string, so that the c in t test is eliminated.

Python 2, 63 bytes

lambda s,b='(/<[{}]>\)':map(dict(zip(b,b[::-1])).get,s,s)[::-1]

Try it online!

-1 byte thanks to @xnor.

Python 3, 65 64 bytes

lambda s,b=b'(/<[{}]>\)':s.translate(dict(zip(b,b[::-1])))[::-1]

Try it online!

Just for fun using idiomatic Python. (More idiomatic would be using str.maketrans, but it's way too long.)

-1 byte for both because the \ in '\)' doesn't need to be escaped.


Produce an image based on an elementary cellular automata ruleset What is elementary cellular automata?

Since I'm not sure I'll be able to explain this so that somebody who has never heard of this is able to understand, I'm giving an explanation from https://mathworld.wolfram.com/ElementaryCellularAutomaton.html

  Elementary cellular automata have two possible values for each cell (0 or 1), and rules that depend only on nearest neighbor values. As a result, the evolution of an elementary cellular automaton can completely be described by a table specifying the state a given cell will have in the next generation based on the value of the cell to its left, the value the cell itself, and the value of the cell to its right. Since there are 2×2×2=2^3=8 possible binary states for the three cells neighboring a given cell, there are a total of 2^8=256 elementary cellular automata, each of which can be indexed with an 8-bit binary number. For example, the table giving the evolution of rule 30 (30=00011110_2) is illustrated above. In this diagram, the possible values of the three neighboring cells are shown in the top row of each panel, and the resulting value the central cell takes in the next generation is shown below in the center.

  The evolution of a one-dimensional cellular automaton can be illustrated by starting with the initial state (generation zero) in the first row, the first generation on the second row, and so on. For example, the figure bellow illustrated the first 20 generations of the rule 30 elementary cellular automaton starting with a single black cell.

The task

Given a ruleset n, where n is positive and less than 256, produce an image like the one above, with 15 generations (+1 starting gen-0) and 2 colors of your choice. The starting gen-0 is one active cell in the center, like in the image above. You can choose to start from the bottom and work upwards.

Input

You can take input either as  a:

Binary number (for example, rule 30 would be 00011110 or the reverse 01111000)
Decimal number (rule 30 would be 30)

You cannot take images from external resources, the image should made from scratch by your program.

Output

Your output should be a 31x16 image, with each row representing a separate generation. Generations should not be given in a mixed order.

Submissions

Your submission should always contain the following:

Your code
An image produced by your program, representing a ruleset of your liking.
Standard loopholes apply. Your program should work for any n in the range [0,256).

Scoring is done by byte count

EDIT

As requested, adding some test cases specifically for edge handling.

rule 222:

rule 201:

rule 162:

rule 16:

Python 2, 178 167 ... 128 bytes

-13 bytes thanks to @Surculose Sputum!

-2 bytes thanks to @dingledooper!

thanks @Surculose Sputum again for saving some bytes and fixing the boundary bug!!!!

n=input()
print'P1 31 16'
c='%061d'%10**30
exec"print' '.join(c[15:46]);c='0'+''.join(n[int(c[u:u+3],2)]for u in range(60));"*16

Try it online!

Output a 31x16 pbm image in stdout. You might need a magnifying glass to see those tinnie images though.

  '01111000' =>  (30 in reverse)
  '01011000' =>  (26 in reverse)


Alphanumeric balance Write a program which gets a string as its input, and counts the number of alphanumeric and non-alphanumeric characters in it. It has to display its result like this:

input: http://stackexchange.com
output: 20 + 4 = 24

The catch is, your source code has to have the same number of alphanumeric characters as non-alphanumeric ones. Comments are not allowed, whitespace is ignored. (The language called Whitespace might compete for votes, but will not be selected as winner, obviously)

Characters in the code must have at least some minor justification, they should not be completely superfluous. For example, longer variable names are allowed, i = (j*3)+4; instead of i = j*3+4; is also allowed. However, i = i + 1;;;;;; is not.

Besides this, standard code-golf rules apply.

Perl, 32 + 32 = 64

The string is expected in STDIN. The output is written to STDOUT. White space is ignored. My interpretation of the task is that the program should be able to run on itself to get the score.

$/ = $,;
$_ = <>;
s x\sxxg;
$\ = length;
print s x[0-9a-z]xxgi,
      ' + ',
      s x.xxg,
      ' = '

Ungolfed with comments

$/ = $,; # The input separator becomes undefined, because the default for $, is "undef"
$_ = <>; # now $_ takes the whole file (STDIN) instead of the first line
s x\sxxg; # $_ =~ s/\s//g;
          # white space is removed from $_
$\ = length; # The number of the other characters are put into $\,
             # which is automatically printed the end of "print".
print s x[0-9a-z]xxgi, # s/[0-9a-z]//gi
                       # Remove alphanumeric characters and return their count
      ' + ',
      s x.xxg, # s/.//g
               # Remove the remaining special characters and return their count.
               # "." does not catch new lines, but we have already
               # removed white spaces including new lines.
      ' = '

I found several variations with the same byte counts, e.g.:

$/ = $x;
$_ = <>, s x\sxxg;
$\ = split $x;
print s x[\da-z]xxgi,
      " + ",
      s x.xxg,
      ' = '

Examples

Example from the question:

echo 'http://stackexchange.com' | perl a.pl
20 + 4 = 24

Running on itself (a.pl):

cat a.pl | perl a.pl
32 + 32 = 64

The file size is 104 bytes, thus 40 bytes are ignored as white space.

Perl, 29 + 29 = 58

$_=<>;s x\sxxg;$\=length;print s x[0-9a-z]xxgi,' + ',s/.//g,' = '

The string is expected at STDIN and it is limited to the first line. The result is printed to STDOUT.
White space is ignored.

Ungolfed

$_ = <>;
s x\sxxg; # same as s/\s//gx; removes white space;
$\ = length($_); # sum is automatically appended at the end of print
print sx[0-9a-z]xxgi, # same as s/[0-9a-z]//gi;
                      # the number of alphanumeric characters
      ' + ',
      s/.//g, # the number of the remaining special characters
      ' = '

Examples

File a.pl contains the Perl script.

Example from the question:

echo 'http://stackexchange.com' | perl a.pl
20 + 4 = 24

Running on itself:

cat a.pl | perl a.pl
29 + 29 = 58

The file size of a.pl is 65 bytes, thus 7 bytes are ignored as white space.


Take that frown and turn it around A celebration of the many faces of APL
Given a string among those in column 1 or column 2 of the below table, return the string's neighbor to its right. In other words, if given a string in column 1 then return column 2's string on that row, and if given a string in column 2 then return column 3's string on that row.
The codepoints (other than :'s) are listed on the far right.
 column 1   column 2   column 3
 :⊢ → ⍡ → ⊣:   U+22a2  U+2361  U+22a3
 :▷ → ⍢ → ◁:   U+25b7  U+2362  U+25c1
 :⋆ → ⍣ → ⋆:   U+22c6  U+2363  U+22c6
 :∘ → ⍤ → ∘:   U+2218  U+2364  U+2218
 :○ → ⍥ → ○:   U+25cb  U+2365  U+25cb
 :≀ → ⍨ → ≀:   U+2240  U+2368  U+2240
 :∧ → ⍩ → ∨:   U+2227  U+2369  U+2228
Anecdote: Most of these symbols are valid or proposed in some APL dialect (they are all links).
Per request, just the symbols:
:⊢ ⍡ ⊣:
:▷ ⍢ ◁:
:⋆ ⍣ ⋆:
:∘ ⍤ ∘:
:○ ⍥ ○:
:≀ ⍨ ≀:
:∧ ⍩ ∨:


Array Merge without Duplicates I recently saw this Javascript code on StackOverflow for merging two arrays, and removing duplicates:

Array.prototype.unique = function() {
    var a = this.concat();
    for(var i=0; i<a.length; ++i) {
        for(var j=i+1; j<a.length; ++j) {
            if(a[i] === a[j])
                a.splice(j--, 1);
        }
    }
    return a;
};

var array1 = ["Vijendra","Singh"];
var array2 = ["Singh", "Shakya"];
var array3 = array1.concat(array2).unique();

While this code works, it is horribly inefficient (O(n^2)). Your challenge is to make an algorithm with less complexity.

The winning criteria is the solution with the least complexity, but ties will be broken by shortest length in characters.

Requirements:

Package all your code together in a function that meets the following requirements for "correctness:"

Input: Two arrays
Output: One array
Merges elements of both arrays together- Any element in either input array must be in the outputted array.
The outputted array should have no duplicates.
Order doesn't matter (unlike the original)
Any language counts
Don't use the standard library's array functions for detecting uniqueness or merging sets/arrays (although other things from the standard library is okay). Let me make the distinction that array concatenation is fine, but functions that already do all of the above are not.

JavaScript O(N) 131 124 116 92 (86?)

Golfed version:

function m(i,x){h={};n=[];for(a=2;a--;i=x)i.map(function(b){h[b]=h[b]||n.push(b)});return n}

Human readable golfed version:

function m(i,x) {
   h = {}
   n = []
   for (a = 2; a--; i=x)
      i.map(function(b){
        h[b] = h[b] || n.push(b)
      })
   return n
}

I could use concat like so and do it in 86 characters:

function m(i,x){h={};n=[];i.concat(x).map(function(b){h[b]=h[b]||n.push(b)});return n}

But I am not sure if it is still O(N) based on this JsPerf: http://jsperf.com/unique-array-merging-concat-vs-looping as the concat version is marginally faster with smaller arrays but slower with larger arrays (Chrome 31 OSX).

In practice do this (golf is full of bad practices):

function merge(a1, a2) {
   var hash = {};
   var arr = [];
   for (var i = 0; i < a1.length; i++) {
      if (hash[a1[i]] !== true) {
        hash[a1[i]] = true;
        arr[arr.length] = a1[i];
      }
   }
   for (var i = 0; i < a2.length; i++) {
      if (hash[a2[i]] !== true) {
        hash[a2[i]] = true;
        arr[arr.length] = a2[i];
      }
   }
   return arr;
}
console.log(merge([1,2,3,4,5],[1,2,3,4,5,6]));

I'm not great at computing complexity but I believe this is O(N). Would love if someone could clarify.

Edit: Here is a version that takes any number of arrays and merges them.

function merge() {
   var args = arguments;
   var hash = {};
   var arr = [];
   for (var i = 0; i < args.length; i++) {
      for (var j = 0; j < args[i].length; j++) {
        if (hash[args[i][j]] !== true) {
          arr[arr.length] = args[i][j];
          hash[args[i][j]] = true;
        }
      }
    }
   return arr;
}
console.log(merge([1,2,3,4,5],[1,2,3,4,5,6],[1,2,3,4,5,6,7],[1,2,3,4,5,6,7,8]));


Hungry Image Snake - Hole #3 Hole #1

Joe the snake is hungry.

He eats pictures, one pixel at a time.

He really likes bright pixels.

The Challenge

Program Joe to eat the most bright pixels he can find, given that he can only move up, down, left or right.

Specifications

Joe must start at the upper left pixel of the image.
Joe can only move horizontally or vertically by 1 each move
Joe has only enough time to move 1/3 of the amount of pixels in the picture (1/3 as many moves as pixels). If the number of pixels is not a multiple of 3, round down to the nearest integer.
Joe may cross his path, though that counts as 0 brightness
Brightness is based on the sum of r,g and b, so rgb(0,0,0) has a brightness of 0 while rgb(255,255,255) has maximum brightness.

Input

You may input the image however you like.

Output

an image showing the end result of your picture (with black being eaten pixels).
The amount of brightness eaten (please specify what range in your answer)

Scoring

Your program will be graded on:

The average brightness of pixels Joe eats
/ The average brightness of the pixels in the picture*

*you may hardcode this in your program

Your total score will be the average of the scores for the following images:

Test images:

http://upload.wikimedia.org/wikipedia/en/thumb/f/f4/The_Scream.jpg/800px-The_Scream.jpg

C++, Score: 1.42042 1.46766

This is essentially a slightly more sophisticated version of the two existing solutions:
Of the four possible moves, it selects the one that maximizes brightness.
However, instead of only looking at the brightness of the target pixel, it looks at the weighted sum of pixel-brightness in the neighborhood of the target pixel, where pixels closer to the target have a greater weight.

EDIT: Using nonlinear brightness in neighborhood calculation improves the score slightly.

Compile with g++ joe.cpp -ojoe -std=c++11 -O3 -lcairo. Requires cairo.

Run with joe <image-file> [<radius>].
<image-file> is the input PNG image.
<radius> (optional argument) is the radius of the summed-over neighborhood, in pixels (smaller is faster, larger is (roughly) better.)
Outputs the score and an image named out.<image-file>.

#include <cairo/cairo.h>
#include <iostream>
#include <iterator>
#include <algorithm>
#include <string>

using namespace std;

int main(int argc, const char* argv[]) {
    auto* img = cairo_image_surface_create_from_png(argv[1]);
    int width = cairo_image_surface_get_width(img),
        height = cairo_image_surface_get_height(img),
        stride = cairo_image_surface_get_stride(img);
    unsigned char* data = cairo_image_surface_get_data(img);

    double* brightness = new double[width * height];
    double total_brightness = 0;
    for (int y = 0; y < height; ++y) {
        for (int x = 0; x < width; ++x) {
            const unsigned char* p = data + stride * y + 4 * x;
            total_brightness += brightness[y * width + x] = p[0] + p[1] + p[2];
        }
    }

    const int r = argc > 2 ? stoi(argv[2]) : 64, R = 2 * r + 1;
    double* weight = new double[R * R];
    for (int y = -r; y <= r; ++y) {
        for (int x = -r; x <= r; ++x)
            weight[R * (y + r) + (x + r)] = 1.0 / (x*x + y*y + 1);
    }

    auto neighborhood = [&] (int x, int y) {
        double b = 0;
        int x1 = max(x - r, 0), x2 = min(x + r, width - 1);
        int y1 = max(y - r, 0), y2 = min(y + r, height - 1);
        for (int v = y1; v <= y2; ++v) {
            const double *B = brightness + width * v + x1;
            const double *W = weight + R * (v - (y - r)) + (x1 - (x - r));
            for (int u = x1; u <= x2; ++u, ++B, ++W)
                b += (*W) * (*B) * (*B);
        }
        return b;
    };

    int n = (2 * width * height + 3) / 6;
    int x = 0, y = 0;
    double path_brightness = 0;
    int O[][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
    for (int i = 0; i < n; ++i) {
        if (i % 1000 == 0) cerr << (200 * i + n) / (2 * n) << "%\r";

        path_brightness += brightness[width * y + x]; brightness[width * y + x] = 0;
        unsigned char* p = data + stride * y + 4 * x;
        p[0] = p[1] = 16 * i % 255; p[2] = 0;

        auto O_end = partition(begin(O), end(O), [&] (const int* o) {
            return x + o[0] >= 0 && x + o[0] < width &&
                   y + o[1] >= 0 && y + o[1] < height;
        });
        const int* o_max; double o_max_neighborhood = -1;
        for (auto o = O; o != O_end; ++o) {
            double o_neighborhood = neighborhood(x + (*o)[0], y + (*o)[1]);
            if (o_neighborhood > o_max_neighborhood)
                o_max = *o, o_max_neighborhood = o_neighborhood;
        }
        x += o_max[0]; y += o_max[1];
    }

    cout << (path_brightness * width * height) / (n * total_brightness) << endl;

    cairo_surface_write_to_png(img, (string("out.") + argv[1]).c_str());

    delete []brightness;
    delete []weight;
    cairo_surface_destroy(img);
}

Results

Bridge    1.39945
Balls     1.77714
Scream    1.38349
Fractal   1.31727
Vortex    1.66493
Tornado   1.26366
-----------------
Average   1.46766

More eye-candy


05AB1E, 11 bytes
-1 byte thanks to @KevinCruijssen
gžQ×æêéI¡н

Try it online!
TIO link is for "abcd" instead of printable ascii since powerset of len(input) printable ascii takes a while to compute...

Explanation
gžQ×                 - repeat printable ascii length of the input times
    æ                - get the powerset of this string
     êé              - sort and uniquify lexicographically then sort by length
       I¡            - split on the input
         н           - and take the elements that are before it
                     - output these implicitly


Generate Some Secure PINs Inspired by this badly received migrated post.

The head of security at your company is concerned about your PIN generating system after it gave him 12345. He also didn't really appreciate the Spaceballs joke you made at his expense, so you've been delegated to re-write the PIN generator. Since it has to fit on some special hardware, you have to make it as small as possible.

Your Task

You take two inputs - # of PINs, and PIN size in digits.
Generate the specified number of PINs of the specified size randomly and print it out.
All valid PIN's of the size must be possible to be printed out, even if they aren't uniformly probable.
However, there are some restrictions on the PINs - here are the invalid ones:

If all the pairs are the same digit: 114422 (Note: this will obviously include all same digit PINs).
Increasingly linear PINs (mod 10): 246802.
All groups of 3 are physical lines on the keypad of 1 2 3;4 5 6;7 8 9;bksp 0 enter;: 147369.
The PIN can be entirely split up into groups from rule 1 and rule 3.

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

Pyth, 120 bytes

Arz7VGJ1WJK%"%0*d",HO-^TH1=J|q1l{m%-F_vMcd1T.:K2u|GHmu|GHm?qlk2:k"(.)\\1"0?qlk3}k+++=bcS"123456789"3_Mb.Tb_M.TbZdZ./K0)K

Figured I should add a real implementation then. Generates random numbers until one is found that meets all requirements. Can probably be improved a lot!

Online version


Determine the critical path In project management there's a method, called the critical path method, that is used for scheduling activities and for determining which activities' timings are crucial (i.e. critical) and for which activities the schedule offers a timing tolerance.

Your program's task is to order a set of activities chronologically and for each of those activities determine their:

earliest possible start;
earliest possible finish;
latest possible start;
latest possible finish.

Lastly, your program should mark which subsequent activities make up the longest, uninterrupted path; i.e. the critical path.

The input will be the activities by their name, with their duration (in an unspecified time unit) and with the names of the activities they depend on.  For this challenge only so-called finish to start dependencies will be presented as input. In other words: any possibly provided dependencies for a given activity signify that said activity can only start when all the activities, that this activity depends on, have finished. No other forms of dependencies will be presented.

The expected input is in the form of (possibly multiples of):

[F:12;C,B]

Where:

F signifies the activity's name; an uppercase alphabetic character;
12 signifies the duration as a positive integer;
C,B signifies the optional dependencies, as a comma-separated list of activity names.

Here's an example input:

[A:15][B:7][C:9;A,B][D:3;B,C][E:5;C][F:11;D][G:4;D,E,F]

Meaning:

 name | duration | dependencies
------+----------+--------------
    A |       15 |
    B |        7 |
    C |        9 |          A,B
    D |        3 |          B,C
    E |        5 |            C
    F |       11 |            D
    G |        4 |        D,E,F

Your program's output will be an ASCII table, in the exact following form, but filled with different data, depending on the input of course (here I'm using the example input, from above, as input):

 name | estart | efinish | lstart | lfinish | critical
------+--------+---------+--------+---------+----------
    A |      0 |      15 |      0 |      15 |        Y
    B |      0 |       7 |      8 |      15 |        N
    C |     15 |      24 |     15 |      24 |        Y
    D |     24 |      27 |     24 |      27 |        Y
    E |     24 |      29 |     33 |      38 |        N
    F |     27 |      38 |     27 |      38 |        Y
    G |     38 |      42 |     38 |      42 |        Y

Where:

the activities are ordered chronologically ascending by estart (and then arbitrarily);
estart is earliest start;
efinish is earliest finish;
lstart is latest start;
lfinish is latest finish;
critical is a Y/N value, signifying whether this activity belongs to the critical path (i.e. lstart - estart = 0 and lfinish - efinish = 0).

The expected constraints for the input will be:

The activity names will never exceed Z; i.e. the total amount of activities will never exceed 26;
The total duration (i.e. the latest finish of the last activity) will never exceed 9999999 (the width of the lfinish column, with padding);
The number of dependencies, for any given activity, will never exceed 6;
The input will never be inconsistent (e.g. no non-existent dependencies, etc.).

The constraints for your program are:

No use of existing PM/CPM APIs1; you must create the algorithm from scratch.

This is a popularity-contest2; the most elegant solution (or at least, I hope that's what voters will vote for), by popular vote, wins. The winner will be determined 4 days after the submission time of this challenge.

1. If any such API even exists.
2. I want to give the more verbose languages a fair shot at this as well.


Energy levels of electrons Energy levels of electrons

Electrons are ordered into "shells". However, sometimes electrons get excited, for example by heat, and leave their shell to go to another! These electrons will go back at some point, but they cannot go back to their original shell without emitting energy in the form of radio waves.

For example, the energy levels for hydrogen look like this:

The base energy level of an electron in hydrogen is at n = 1. If it gets 'excited', it might go to n = 4. However, on the way back, the electron does not always simply go from n = 4 to n = 1, it has different options. See the example.

Task

Write a program or function that takes an integer and outputs the amount of options the electron has to get back to its un-excited state. For this task, you can take granted that an electron can only emit energy from its excited state. It will not get more energy once it has been excited.

This is code-golf, the answer with the least amount of bytes wins.

If you are interested in these type of questions, check out this similar question. Also check out this for more info on these matters.

Input

The input of your function/program is a whole integer. It is greater than 0 and less than 2^31.

Output

An integer, the amount of options the electron has to return to its original state, which is n = 1 (for hydrogen). When the input is 1, return 0, as it is already in its original energy level.

Examples

Input: 4
Output: 4

Because the options are:

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

Visualised:

Pyth, 5 bytes
/^2Q4

I integer-divide by 4 instead of subtracting two from the power and flooring.


Print integers in any base up to 36 Possible Duplicate:
  Integer to string with given radix

This question is inspired by Pythons builtin int function. int is used to convert other numbers or strings into integers. If you are converting a string you can provide the additional parameter base, that contains the base that your number is represented in within the string:

>>> int('137')
137
>>> int('137',base=8)
95
>>> int('ff',base=16)
255
>>> int('1AZ',base=36)
1691

Unfortunately Python doesn't provide a function for the reverse case, where you want to convert a number into a string in a specific base.

Your task is to write such a function.

the function may return the value or print it
you must provide support for all bases between 2 and 36
digits to use are 0123456789abcdefghijklmnopqrstuvwxyz
all languages are allowed
built in functions for this purpose are boring and thus forbidden
shortest code wins

Befunge, 17x4 = 68 characters

1-&00p&>:!#v_:00v
v-10<  ^/g00\%g <
< >:^@_.# #$v#:!`
"_^#`9::$  <<,+"W

Online interpreter: http://www.bedroomlan.org/tools/befunge-93-playground

First input is base, second is number.

Similar to other solutions here this does not output anything when the number is 0.  I may look at fixing this at some point.


Concatenate Strings with Context Strings with Context

For the purposes of this challenge, a string with context is a triple of strings, called the left context, the data part, and the right context. It represents a substring of a longer string. We use the vertical pipe | as a separator, so an example of a string with context is cod|e-go|lf, where the left context is cod, the data is e-go, and the right context is lf. This example represents the substring e-go of code-golf.

Now, to concatenate two strings with context, we proceed as follows, using aa|bcc|dee and cc|de|eee as examples. We align the strings as in the diagram

a a|b c c|d e e
      c c|d e|e e e

so that their data parts are adjacent. The data part of the concatenation is the concatenation of the data parts, in this case bccde. The left context is the part that extends the furthers to the left of the first data part, in this case aa. Similarly, the right context is eee, so the concatenation is the string with context aa|bccde|eee. For a second example, consider a|bb|cd and aabb|cd|, where the second word has a empty right context. The alignment diagram is

  a|b b|c d
a a b b|c d|

where the left context of the second word extends further than that of the first. The concatenation is aa|bbcd|.

But wait, there's a gotcha: if the letters of the alignment diagram don't match, the concatenation doesn't exist! As an example, the diagram of aa|bb|cc and c|c|c is

a a|b b|c c
      c|c|c

where the b and c on the fourth column disagree, so they cannot be concatenated.

The Task

Your job is to write a program that takes in two strings with context whose parts are separated by | as above, and outputs their concatenation if it exists, and something else if not. The "something else" can be any value, including no output, as long as it's not a valid string with context, and it is the same in all cases. However, throwing an error is not acceptable. You can give either a STDIN-to-STDOUT program or a function, and anonymous functions are accepted as well. The smallest byte count wins, and standard loopholes are disallowed.

Test Cases

aa|bcc|dee cc|de|eee -> aa|bccde|eee
a|bb|cd    aabb|cd|  -> aa|bbcd|
a|b|cccd   aab|cc|c  -> aa|bcc|cd
a|b|c      b||cd     -> a|b|cd
aa|bb|cc   c|c|c     -> None
aaa|b|c    abb|cd|d  -> None
|bb|cd     abb|c|ed  -> None
a|b|c      a||cd     -> None

Haskell, 184 182 201 199 155
s&t|(a,'|':b)<-f t,(x,'|':y)<-f$r s,x#b,a#y=r(y!r a)++b!r x|0<1=""
r=reverse
a!b=a++drop(length a-1)b
(#)a=and.zipWith(==)(r a).filter h
f=span h
h=(/='|')

example run:
"|a|"&"|b|" -- returns "|ab|"
"|a|x"&"|b|" -- returns ""

if there isn't a match an empty string will be returned. otherwise the result would be returned.
partial explanation:
# is a function which gets two strings, and returns whether or not they match.
! gets two strings and returns the first one concatenated with extra character from the second (if there are any).
the main function & uses span (/='|') to split the inputs into two parts, a|b|c to a, b|c, checks if the contexts match, and then uses ! twice to assemble the output.
Edit: mage-late regolfing seems to be pretty effective.


Write a code golf problem in which Java wins Write a code golf task such that

The only input (if any) required by the task is text from standard input, and the only output required by the task is text to standard output.
There is exactly one correct output string of characters for every possible legal input as defined by the task.
Each possible legal input is less than 10000 characters long.
Each correct output is less than 10000 characters long.
The shortest program (that StackExchange users manage to write) that successfully completes the task for every input is in Java.

The task with the shortest associated Java program wins.

48 characters

Task: Ignore any input. Always produce exactly the following output:

java.lang.ExceptionInInitializerError
Caused by: java.lang.ArithmeticException: / by zero
    at M.<init>(M.java:1)
    at M.<clinit>(M.java:1)

Solution:

enum M{M;System x;{x.setErr(x.out);int y=1/0;}}

Save as M.java, compile with javac M.java and run with java M. It also produces an error message on standard error, but that doesn't violate any of the rules.


Shortest total non-primitive recursive function Natural numbers ≡ \$\mathbb{N}≡\{0,1,2,...\}\$

The submission can be either a program or a function, both cases will henceforth be referred to as "function".

The task is to golf the shortest function \$\mathbb{N}^n→\mathbb{N}\$, i.e. a function that maps \$n\$ natural numbers (with \$n>0\$ being a number of your choosing) to a natural number, such that the function is not primitive recursive, that is, a function that is not composable from only the following functions (each variable being a natural number):

(from https://en.wikipedia.org/wiki/Primitive_recursive_function)

Zero
$$Z()=0$$

Successor
$$S(x)=x+1$$

Projection
$$P_i^n(x_0,x_1,\dots,x_{n-1})=x_i$$

Composition
$$h(x_0,x_1,\dots,x_m)=f(g_1(x_0,x_1,\dots,x_m),\dots,g_k(x_0,x_1,\dots,x_m))$$

Primitive recursion

$$\begin{align}h(0,x_0,\dots,x_k)&=f(x_0,\dots,x_k)\\h(S(y),x_0,\dots,x_k)&=g(y,h(y,x_0,\dots,x_k),x_0,\dots,x_k)\end{align}$$

From the above five functions/operations, we can get many functions like the constant function, addition, multiplication, exponentiation, factorial, primality test, etc.

A (total) function that is not primitive recursive could be one that grows faster than any primitive recursive function, like the Ackermann function. Its proof of not being primitive recursive is on Wikipedia.

Or a function could be non primitive recursive due to contradictions that would arise otherwise; examples are provided in the answers to this Math Stack Exchange question as pointed out by Bubbler.

The submissions are free to use any radix as long as the same radix is used for each of the input and output numbers.

Your submission can take input as a list of numbers, a list of strings representing numbers, a string containing (constant) delimiter-separated numbers, or the like. In the case of using a string or equivalent, your submissions are free to use any character to represent each digit of the radix chosen, as long the choice is consistent throughout all inputs and output.

The function will always be called with the same number of inputs.

The submission should always terminate and return a result, that is, it cannot loop indefinitely.

The function should always give deterministic output.

The submission should theoretically work for any input, including those outside of the used numeric data types.

A proof accompanying your answer is appreciated, but not required.

This challenge was drafted thanks to the helpful commenters at its Sandbox.

Haskell, 29 bytes

(+1)?(2?)
z?f=(iterate f z!!)

Try it online!

An Ackermann-like function. Starting the base numerical value at 2 makes for a simple base case. An annoying number of bytes are spent converting the arguments order for "apply f n times starting from z" from iterate f z!!n to (?) z f n which can be curried nicely.

Same thing written more explicitly for 2 bytes longer:

31 bytes

0%n=n+1
m%n=iterate((m-1)%)2!!n

Try it online!

Another alternative to the original is to flip the two arguments to ?, allowing it to be defined in a point-free way for the same byte count.

29 bytes

(?2)?(+1)
(?)=((!!).).iterate

Try it online!

29 bytes

(?2)?(+1)
(?)f=(!!).iterate f

Try it online!

31 bytes

n?0=n+1
0?m=2
n?m=(n-1)?m?(m-1)

Try it online!