# Question
Title: Print the lyrics to "Twinkle Twinkle Little Star"
Your goal is to print the lyrics to the song "Twinkle Twinkle Little Star" as each note is played.

The computer's microphone will hear notes. If the pitch (but not necessarily the length) of the note is correct, print the appropriate syllable. Otherwise, do nothing. Each note will be at least half a second long, and there will be a break of at least a quarter of a second between notes.

Use the musical notes provided here, and the following lyrics: (Vertical lines represent syllable breaks.)

> Twin|kle, twin|kle, lit|tle star,
>
> How I won|der what you are.
>
> Up a|bove the world so high,
>
> Like a dia|mond in the sky.
>
> Twin|kle, twin|kle, lit|tle star,
>
> How I won|der what you are.

A recording of the music can be found here.

# Example

The computer hears a middle C and prints "Twin"

It hears another middle C and prints "kle,"

Then it hears another middle C (wrong note) and does nothing.

Then it hears the G above middle C and prints "twin" and so on.

# Rules

* Punctuation must be as shown.
* Spacing must be as shown (with spaces and newlines).
* The whitespace may be printed along with either the previous or the next syllable.

# Answer
> 7 votes
## Python 3 - Partial solution (~~760~~ ~~742~~ ~~734~~ ~~710~~ ~~705~~ 657 characters)

*(Last edit; I promise)*

This seems like a really, pretty, very hard problem (especially recognizing where the notes start or end). Automatic transcription of music seems like an open research topic (not that I know anything about it). So here's a partial solution that doesn't do any note segmentation (eg it prints "Twinkle" all at once when it hears the frequency) and probably only works for that specific ogg file:

```
A=-52
F=44100
C=4096
import pyaudio as P
import array
import scipy.signal as G
import numpy as N
import math
L=math.log
i=0
j=[9,2,0,2,4,5,7,9]
k=[2,4,5,7]
n=j+k+k+j
w="Twinkle, |twinkle, |little |star,\n|How I |wonder |what you |are.\n|Up a|bove the |world so |high,\n|Like a |diamond |in the |sky.\n".split('|')
w+=w[:8]
e=P.PyAudio().open(F,1,8,1,0,None,0,C)
while i<24:
 g=array.array('h',e.read(C));b=sum(map(abs,g))/C
 if b>0 and 20*L(b/32768,10)>A:
  f=G.fftconvolve(g,g[::-1])[C:];d=N.diff(f);s=0
  while d[s]<=0:s+=1
  x=N.argmax(f[s:])+s;u=f[x-1];v=f[x+1]
  if int(12*L(((u-v)/2/(u-2*f[x]+v)+x)*F/C/440,2))==n[i]+15:print(w[i],end='',flush=1);i+=1

```

This requires...

Change the A=-52 (minimum amplitude) on the top line depending on your microphone, ammount of ambient sound, how loud the song is playing, etc. On my microphone, less than -57 seems to pick up a lot of extraneous noise and more than -49 requires you play it very loud.

This could be golfed a LOT more; I'm sure there are ways to save a bunch of characters on the words array in particular. This is my first non-trivial program in python, so I'm not very familiar with the language yet.

I stole the code for frequency detection via autocorrelation from https://gist.github.com/endolith/255291

Ungolfed:

```
import pyaudio
from array import array
import scipy.signal
import numpy
import math
import sys

MIN_AMPLITUDE = -52
FRAMERATE = 44100

def first(list):
    for i in range(len(list)):
        if(list[i] > 0):
            return i
    return 0

# Based on: https://en.wikipedia.org/wiki/Decibel#Acoustics
def getAmplitude(sig):
    total = 0;
    elems = float(len(sig))
    for x in sig:
        total += numpy.abs(x) / elems
    if(total == 0):
        return -99
    else:
        return 20 * math.log(total / 32768., 10)

# Based on: https://en.wikipedia.org/wiki/Piano_key_frequencies
def getNote(freq):
    return int(12 * math.log(freq / 440, 2) + 49)

# --------------------------------------------------------------------------
# This is stolen straight from here w/ very slight modifications: https://gist.github.com/endolith/255291
def parabolic(f, x):
    return 1/2. * (f[x-1] - f[x+1]) / (f[x-1] - 2 * f[x] + f[x+1]) + x

def getFrequency(sig):
    # Calculate autocorrelation (same thing as convolution, but with
    # one input reversed in time), and throw away the negative lags
    corr = scipy.signal.fftconvolve(sig, sig[::-1], mode='full')
    corr = corr[len(corr)/2:]

    # Find the first low point
    diffs = numpy.diff(corr)

    # Find the next peak after the low point (other than 0 lag). This bit is
    # not reliable for long signals, due to the desired peak occurring between
    # samples, and other peaks appearing higher.
    # Should use a weighting function to de-emphasize the peaks at longer lags.
    start = first(diffs)
    peak = numpy.argmax(corr[start:]) + start
    return parabolic(corr, peak) * (FRAMERATE / len(sig))
# --------------------------------------------------------------------------

# These are the wrong keys (ie it is detecting middle C as an A), but I'm far too lazy to figure out why.
# Anyway, these are what are detected from the Wikipedia .ogg file:
notes = [73,          66,           64,       66,         68,       69,        71,          73,       66,     68,          69,         71,         66,        68,         69,        71      ]
words = ["Twinkle, ", "twinkle, ", "little ", "star,\n",  "How I ", "wonder ", "what you ", "are.\n", "Up a", "bove the ", "world so ", "high,\n", "Like a ", "diamond ", "in the ", "sky.\n"]
notes += notes[:8]
words += words[:8]

pa = pyaudio.PyAudio()
stream = pa.open(format=pyaudio.paInt16, channels = 1, rate = FRAMERATE, input = True, frames_per_buffer = 4096)
idx = 0
while(idx < len(notes)):
    # Read signal
    sig = array('h', stream.read(4096))
    if(getAmplitude(sig) > MIN_AMPLITUDE):
        note = getNote(getFrequency(sig))
        if(note == notes[idx]):
            sys.stdout.write(words[idx])
            sys.stdout.flush()
            idx += 1

```

---
Tags: code-golf, music, audio
---


title: Mastermind strategy

text:
# Question
Title: Mastermind strategy
I could only find code-golf challenges for Mastermind, so here's a code-challenge version that I would have liked to take on myself.

An optimal strategy for the normal Mastermind game, MM(4,6), was found by Koyama and Lai in 1993, having an average # of guesses = 5625/1296 ~ 4.34. MM(5,8) is still unsolved, but is estimated to have an average # of guesses ~ 5.5.

Your task is to create an MM(5,8) strategy, that is for 5 holes and 8 colors, covering all `pow(8,5) = 32768` possible distinct solutions. Obviously, it doesn't have to be an optimal one. You have two choices:

1. Post a deterministic program that generates the strategy. The program must be compileable/runnable on Windows 7, Mac OS X or Linux without any extra non-free software.
2. Publish your strategy (along with your StackExchange name) somewhere on the Internet and post the URL here.

In both cases, state the score (see below) in the answer's header.

The strategy must be encoded according to the following grammar:

```
strategy : guessing-strategy | known-solution-strategy
guessing-strategy : '{' guess ':' branches '}'
known-solution-strategy : guess
guess : color color color color color
color : 'A'..'H'
branches : '{' branch (',' branch)* '}'
branch : reply ':' strategy
reply : number-of-blacks number-of-whites
number-of-blacks : number-of-key-pegs
number-of-whites : number-of-key-pegs
number-of-key-pegs : '0'..'5'

```

The algorithm used to decide the number of black/white key pegs is described in http://en.wikipedia.org/wiki/Mastermind\_(board\_game)

Note that the reply "50" (i.e. correct guess) is implied and not part of the grammar.

Scoring: N = the sum of the number of guesses for each of the 32768 paths/solutions. The strategy with the lowest N wins. First tie-break: The lowest maximum number of guesses. Second tie-break: The first posted answer. The competition ends **August 1, 2014 0:00 GMT**.

---

An example of a strategy for MM(2,3) with score = 21:

```
{AB:{10:{AC:{10:AA,01:CB,00:BB}},02:BA,01:{BC:{01:CA}},00:CC}}

```

Using this strategy, the 9 possible games will go like this:

* AB 20
* AB 10, AC 20
* AB 10, AC 10, AA 20
* AB 10, AC 01, CB 20
* AB 10, AC 00, BB 20
* AB 02, BA 20
* AB 01, BC 20
* AB 01, BC 01, CA 20
* AB 00, CC 20

I will soon post a Java-based MM(5,8) strategy verifier for your convenience.

# Answer
> 6 votes
## Java

My algorithm for MM(5,8) scores with ~~177902~~ ~~178006~~ ~~182798~~ **182697** with a maximum depth of ~~8~~ **9** and needs only a few seconds (on my slow computer).

An example output of a strategy for MM(2,3) with score = 21 found by this algorithm looks like this:

```
{BC:{00:AA,01:AB:{01:CA},02:CB,10:AC:{00:BB,01:BA,10:CC}}}

```

---

There is nothing exciting with my algorithm. No invention. I just followed recipes found in the net and compressed them into this Java code. The only optimization I did is trying to optimize the lines of code (in a way). It goes like this:

1. Create the initial set S0 of all possible codes to be the current set S.
2. Codebreaker finds a (greedy) good guess for S. Each guess leads to a partition P of S, where each subset S' collects all codes (from S) having the same reply on the guess. A good guess has a good partition, as the one giving most information for the guess.
3. Take the good guess and its P. For each nonempty S' in P apply codebreaker recursive (step 2).

@MrBackend: Writing a verifier is hard, I guess. ;-)

```
import java.util.TreeMap;
import java.util.Vector;

public class MM {
    Vector<String> codeset = new Vector<String>();
    String guess;
    TreeMap<Integer, MM> strategy = new TreeMap<Integer, MM>();

    public String toString() {
        String list="";
        for (Integer reply: strategy.keySet()) {
            if (strategy.get(reply)!=null) list+=(list.length()>0?",":"")+(reply<10?"0":"")+reply+":"+strategy.get(reply);
        }
        if (list.length()>0) return guess+":{"+list+"}"; else return guess;
    }

    MM() { }

    MM(int h, int c) {
        for (int i = 0; i < Math.pow(c, h); i++) {
            String code = "";
            for (int j = 0, p=i; j < h; j++) {
                code+="ABCDEFGH".charAt(p%c);
                p/=c;
            }
            codeset.add(code);
        }
    }

    int replyAccordingToDonaldKnuth(String secret, String guess) {
        int black=0;
        int totalHitsBlackAndWhite=0;
        for (char n = 'A'; n <= 'H'; n++) {
            int a=0, b=0;
            for (int i = 0; i < secret.length(); i++) {
                if (secret.charAt(i)==n) a++;
                if ( guess.charAt(i)==n) b++;
            }
            totalHitsBlackAndWhite+=Math.min(a, b);
        }
        for (int i = 0; i < secret.length(); i++) {
            if (secret.charAt(i) == guess.charAt(i)) black++;
        }
        return 10 * black + (totalHitsBlackAndWhite-black);
    }

    int reply(String secret, String guess) {
        return replyAccordingToDonaldKnuth(secret, guess);
    }

    MM codebreaker(Vector<String> permuts) {
        int fitness=0;
        MM protostrategy=null;
        for (int greedy = 0; greedy < Math.min(permuts.size(), 200); greedy++) {
            MM tmp=partition(permuts, permuts.get(greedy));
            int value=tmp.strategy.size();
            if (fitness<=value) {
                fitness=value;
                protostrategy=tmp;
                protostrategy.guess=permuts.get(greedy);
            }
        }
        if (protostrategy!=null) {
            for (Integer reply: protostrategy.strategy.keySet()) {
                protostrategy.strategy.put(reply, codebreaker(protostrategy.strategy.get(reply).codeset));
            }
        }
        return protostrategy;
    }

    MM partition(Vector<String> permuts, String code) {
        MM protostrategy=new MM();
        for (int c = 0; c < permuts.size(); c++) {
            int reply=reply(permuts.get(c), code);
            if (!protostrategy.strategy.containsKey(reply)) protostrategy.strategy.put(reply, new MM());
            if (permuts.get(c)!=code) protostrategy.strategy.get(reply).codeset.add(permuts.get(c));
        }
        return protostrategy;
    }

    public static void main(String[] args) {
        MM mm = new MM(5,8);
        System.out.println("{"+mm.codebreaker(mm.codeset)+"}");
    }
}

```

**Some remarks:**

1. No consistency check is needed because sets S and their partitions are build in a (auto-)consistent way.
2. Picking a good guess out of S0 (instead of S) makes sense. But I don't follow this approach in the current code.
3. My greedy search is artificially pruned to 200 tries.
4. I know, "giving most information for the guess" is not very precise. The simple idea is to pick the partition with the most number of subsets.
5. The result heavily depends on how you calculate the reply(..). Finally I adapted Donald Knuth's expression.

The strategy for `MM(5,8)` can be found here. GitHub has some issues displaying lines that long, so click on the **Raw** button.

# Answer
> 2 votes
## Ruby

**EDIT:** Added some logic to exclude impossible guesses. Hence, the strategies now comply with the given format and are much more manageable.

So here is one attempt to get this going. It's pretty naive (and not very legible - it helps to read the if/elsif/else branch from bottom to top).

```
Holes, Colors = ARGV.map &:to_i

ColorChars = ('A'..'H').to_a

def is_possible(guess, blacks, result)
    blacks == guess.chars.zip(result.chars).count {|chars| chars[0] == chars[1]}
end

def print_strategy(known_colors, remaining_permutations, next_color)
    char = ColorChars[next_color]
    if remaining_permutations
        guess = remaining_permutations[0]
        print guess
        if remaining_permutations.length > 1
            print ':{'
            (Holes-1).times do |i|
                new_permutations = (remaining_permutations - [guess]).select { |perm| is_possible(guess, i, perm) }
                next if new_permutations.empty?
                print "#{i}#{Holes-i}:"
                print '{' if new_permutations.length > 1
                print_strategy(known_colors, new_permutations, next_color)
                print '}' if new_permutations.length > 1
                print ',' if i < Holes-2
            end
            print '}'
        end
    elsif known_colors.length == Holes
        print_strategy(known_colors, known_colors.chars.permutation.map(&:join).uniq, next_color)
    elsif next_color == Colors-1
        print_strategy(known_colors+char*(Holes - known_colors.length), remaining_permutations, next_color+1)
    else
        print char*Holes, ':{'

        (Holes - known_colors.length + 1).times do |i|
            break if i == Holes
            print "#{i}0:"
            print '{' if next_color < Colors-2 || i > 0 || known_colors.length > 0
            print_strategy(
                known_colors+char*i,
                remaining_permutations,
                next_color+1
            )
            print '}' if next_color < Colors-2 || i > 0 || known_colors.length > 0
            print ',' if i < (Holes - known_colors.length) && i < Holes-1
        end
        print '}'
    end
end

print '{'
print_strategy('', nil, 0)
puts '}'

```

First, I try 5 of each colour: `AAAAA`, `BBBBB`, etc. From that I figure out which colours are actually used in the pattern. And then I simply try all permutations of the given colours, omitting those which have been ruled out by the black pegs already.

Here is the `MM(2,3)` strategy:

```
{AA:{00:{BB:{00:CC,10:{BC:{02:CB}}}},10:{BB:{00:{AC:{02:CA}},10:{AB:{02:BA}}}}}}

```

The strategy for `MM(5,8)` takes 376KB and can be found here. GitHub has some issues displaying lines that long, so click on the **Raw** button.

Now if I get a verifier, I can also tell you what my actual score is. :)

---
Tags: code-challenge, game, optimization, generation, graph-theory
---


title: Play a perfect game of 2048

text:
# Question
Title: Play a perfect game of 2048
Your job is to simulate a mathematically perfect game of 2048. The idea is to find the theoretical upper limit of how far a 2048 game can go, and find how to get there.

To get an idea of what this looks like, play with this 2x2 clone and try to score 68 points. If you do, you will end up with a 2, 4, 8, and 16 tile. It's impossible to advance past that point.

Your task is made easier because you can choose where tiles spawn and what their values are, just like this clone.

You must write a program or function that accepts a 2048 board as input, and outputs the board with the spawned tile and the board after collapsing tiles. For example:

```
Input:
-------
0 0 0 0
0 0 0 0
0 0 0 0
0 0 8 8

Output:
-------
0 0 0 0
0 0 0 0
0 0 0 0
0 4 8 8

0 0 0 0
0 0 0 0
0 0 0 0
0 0 4 16

```

Your program will be repeatedly fed its own output to simulate an entire game of 2048. The first input of the program will be an empty board. You must spawn one tile on it, unlike the original game's two tiles. At the last step of the game, you will be unable to move, so your two output boards can be identical.

You must of course only output legal moves. Only a 2 or 4 can be spawned, you must move or collapse at least one tile on a move, etc.

I've purposely made the input and output requirements vague. You are free to choose the format of the input and output. You can use matrices, arrays, strings, or whatever you want. As long as you can simulate a 2048 game with them, your inputs and outputs are fine.

The winner will be the one who ends the game with the highest sum of tiles on the board, then by the lowest number of bytes in the source code. The scoring from the original game will not be taken into account. (Hint: use 4's)

# Answer
## Ruby, Into the Corner, Score: 3340

Here is a very simple strategy to kick this off. I do have an idea for a (near) perfect score, but I'm having trouble formalising it, so here is something simple to get things going.

```
def slide board, dir
    case dir
    when 'U'
        i0 = 0
        i_stride = 1
        i_dist = 4
    when 'D'
        i0 = 15
        i_stride = -1
        i_dist = -4
    when 'L'
        i0 = 0
        i_stride = 4
        i_dist = 1
    when 'R'
        i0 = 15
        i_stride = -4
        i_dist = -1
    end

    4.times do |x|
        column = []
        top_merged = false
        4.times do |y|
            tile = board[i0 + x*i_stride + y*i_dist]
            next if tile == 0
            if top_merged || tile != column.last
                column.push tile
                top_merged = false
            else
                column[-1] *= 2
                top_merged = true
            end
        end

        4.times do |y|
            board[i0 + x*i_stride + y*i_dist] = column[y] || 0
        end
    end

    board
end

def advance board
    if board.reduce(:*) > 0
        return board, board
    end

    16.times do |i|
        if board[15-i] == 0
            board[15-i] = 4
            break
        end
    end

    spawned = board.clone

    # Attention, dirty dirty hand-tweaked edge cases to avoid
    # the inevitable for a bit longer. NSFS!
    if board[11] == 8 && (board[12..15] == [32, 16, 4, 4] ||
                          board[12..15] == [16, 16, 4, 4] && board[8..10] == [256,64,32]) ||
       board[11] == 16 && (board[12..15] == [32, 8, 4, 4] ||
                           board[12..15] == [4, 32, 8, 8] ||
                           board[12..15] == [4, 32, 0, 4])

        dir = 'R'
    elsif board[11] == 16 && board[12..15] == [4, 4, 32, 4] ||
          board[11] == 8 && board[12..15] == [0, 4, 32, 8]
        dir = 'U'
    else
        dir = (board.reduce(:+)/4).even? ? 'U' : 'L'
    end

    board = slide(board, dir)

    if board == spawned
        dir = dir == 'U' ? 'L' : 'U'
        board = slide(board, dir)
    end
    return spawned, board
end

```

The `advance` function is the one your asking for. It takes a board as 1d array and returns the board after the tile has been spawned and after the move has been made.

You can test it with this snippet

```
board = [0]*16
loop do
    spawned, board = advance(board)
    board.each_slice(4) {|row| puts row*' '}
    puts
    break if board[15] > 0
end

puts "Score: #{board.reduce :+}"

```

The strategy is very simple, and is the one I actually used to skip to the 128 when I was playing 2048 myself: just alternate between **up** and **left**. To make this work for as long as possible, new `4`s are spawned in the bottom right corner.

**EDIT:** I've added a hard coded switch to go right a few times at specific steps just before the end, which actually lets me reach 1024. This is getting somewhat out of hand though, so I'll stop with this for now and think about a generally better approach tomorrow. (Honestly, the fact that I can increase my score by a factor of 4 by adding hand-tweaked hacks only tells me that my strategy is crap.)

This is the board you end up with

```
1024 512 256 128
 512 256 128  16
 256 128  64   8
   8  32   8   4

```
> 4 votes

---
Tags: code-golf, sliding-puzzle
---


title: Solve the (Rubiks) Pocket Cube

text:
# Question
Title: Solve the (Rubiks) Pocket Cube
# Your task

.. is to do what Brian Fantana apparently couldn't do, and solve the 2x2x2 Rubik's Cube.

## The Layout

```
- -   A B   - -   - -
- -   C D   - -   - -

E F   G H   I J   K L
M N   O P   Q R   S T

- -   U V   - -   - -
- -   W X   - -   - -

```

And will be given to you via stdin or the command line (your choice - please specify in your answer) in the format:

```
ABCDEFGHIJKLMNOPQRSTUVWX

```

Note that A-D make up the U-face(up), EFMN make up the L-face(left), GHOP make up the F-face(front), IJQR make up the R-face(right), KLST make up the B-face(back), and U-X make up the D-face(down).

There will be six unique characters representing each color, but they may vary, so prepare for any combination of 6 ascii characters to be used for each color.

## Specifications

* Your code should output a solution using only the Right (R), Upper (U), and Front(F) faces, and should use the standard notation: R , R' , R2 , U , U' , U2 , F , F' , F2. You can find more info here. The restriction to the RUF subset is standard for the 2x2 cube (Hint: treat the bottom-back-left corner as a fixed base to work from).
* Your code must be capable of solving all possible permutations of the pocket cube.
* Each solution should take less than 30 seconds to complete.
* Each solution should be less than 30 moves.
* A bonus of -20% will be given for solutions always providing answers less than 20 moves (please advertise it in your answer so I can do a thorough check for it)
* A bonus of -50% will be given for code which always provides an optimal solution. - Again, please advertise in your answer
* Solutions must not contain two consecutive moves on the same face, because they can be easily combined into one move.
* Solutions can optionally contain a single space - and *only* a single space - between each move.
* The whole solution sequence, if necessary, may be contained in a pair of parentheses, quotation marks, braces, brackets, or carets, but no other extraneous output is allowed.
* Please provide either a briefly commented version of your code or a thorough explanation of your code.
* No use of external files. This includes internet, data tables, and libraries/packages made for this sort of problem.
* Shortest code by byte count wins.
* Winner chosen Wednesday (July 30, 2014).

# Answer
# Python 2.7: 544 bytes -50% = 272 bytes\**

```
import sys;o=''.join;r=range;a=sys.argv[1];a=o([(' ',x)[x in a[12]+a[19]+a[22]] for x in a]);v={a:''};w={' '*4+(a[12]*2+' '*4+a[19]*2)*2+a[22]*4:''}
m=lambda a,k:o([a[([0x55a5498531bb9ac58d10a98a4788e0,0xbdab49ca307b9ac2916a4a0e608c02,0xbd9109ca233beac5a92233a842b420][k]>>5*i)%32] for i in r(24)])
def z(d,h):
 t={}
 for s in d[0]:
  if s in d[1]:print d[h][s]+d[1-h][s];exit()
  n=[d[0][s],'']
  for k in r(3):
   for j in r(3):s=m(s,k);t[s]=n[h]+'RUF'[k]+" 2'"[(j,2-j)[h]]+n[1-h]
   s=m(s,k)
 d[0]=t;return d
while 1:v,w=z([v,w],0);w,v=z([w,v],1)

```

Stackexchange replaces tabs with multiple whitespaces. So technical this version has 549 bytes. Just replace the first two spaces in the lines 6-10 with a tabulator.

Idea behind my program: My first idea was a breath first search. But this took too long. Around 2 minutes for a hard (11 move optimal) scramble. So I decided to approach the problem from both sides. I use two sets. I generate sequentially all states with distance 1,2,3,... to the scramble and save them in set1, and at the same time all states with distance 1,2,3,... to the solved state and save them in set2. The first time a state is in both sets, we found the solution.

For this I need the colors of the solved cube, which are not known. The characters 13, 20 and 23 define the left, back and down color. But these 3 colors are sufficient to represent the cube. I simply replace the other 3 colors with whitespaces and I can represent my solved state as '\____ll\____bbll\____dddd'.

Oh, and for shortening the permutations I used an idea from https://codegolf.stackexchange.com/a/34651/29577

Ungolfed version:

```
import sys

#define permutations for R,U,F
permutation = [[0,7,2,15,4,5,6,21,16,8,3,11,12,13,14,23,17,9,1,19,20,18,22,10],
            [2,0,3,1,6,7,8,9,10,11,4,5,12,13,14,15,16,17,18,19,20,21,22,23],
            [0,1,13,5,4,20,14,6,2,9,10,11,12,21,15,7,3,17,18,19,16,8,22,23]]

def applyMove(state, move):
    return ''.join([state[i] for i in permutation[move]])

scramble = sys.argv[1]
#remove up,front,rigth colors
scramble = ''.join([(' ', x)[x in scramble[12]+scramble[19]+scramble[22]] for x in scramble])
solved = ' '*4+scramble[12]*2+' '*4+scramble[19]*2+scramble[12]*2+' '*4+scramble[19]*2+scramble[22]*4

dict1 = {scramble: ''} #stores states with dist 0,1,2,... from the scramble
dict2 = {solved: ''} #stores states with dist 0,1,2,... from the solved state

moveName = 'RUF'
turnName = " 2'"

for i in range(6):
    tmp = {}
    for state in dict1:
        if state in dict2:
            #solution found
            print dict1[state] + dict2[state]
            exit()
        moveString = dict1[state]
        #do all 9 moves
        for move in range(3):
            for turn in range(3):
                state = applyMove(state, move)
                tmp[state] = moveString + moveName[move] + turnName[turn]
            state = applyMove(state, move)
    dict1 = tmp
    tmp = {}
    for state in dict2:
        if state in dict1:
            #solution found
            print dict1[state] + dict2[state]
            exit()
        moveString = dict2[state]
        #do all 9 moves
        for move in range(3):
            for turn in range(3):
                state = applyMove(state, move)
                tmp[state] = moveName[move] + turnName[2 - turn] + moveString
            state = applyMove(state, move)
    dict2 = tmp

```

I'm pretty happy with the result, because I'm quite new to Python. This is one of my first python programs.

## edit: half a year later: 427 - 50% = 213.5

Got a little bit more experience in Python and in golfing. So I revised my original code and could save more than 100 character.

```
import sys;o=''.join;a=sys.argv[1];d=[{o((' ',x)[x in a[12]+a[19]+a[22]]for x in a):[]},{' '*4+(a[12]*2+' '*4+a[19]*2)*2+a[22]*4:[]}]
for h in[0,1]*6:
 for s,x in d[h].items():
  for y in range(12):
   d[h][s]=x+[y-[1,-1,1,3][h*y%4]];
   if s in d[1-h]:print o('RUF'[x/4]+" 2'"[x%4]for x in d[0][s]+d[1][s][::-1]);exit()
   s=o(s[ord(c)-97]for c in'acahabcdnpbfegefhugiovjgqkciljdeklflmmmnnvoopxphrqdjrrbsstttuuqsviwwwkxx'[y/4::3])

```

I basically use the exact same approach. The biggest change is, that I don't define a function anymore. Instead of

```
def z(d,h):
 for s in d[0]:
  if s in d[1]:...
while 1:v,w=z([v,w],0);w,v=z([w,v],1)

```

I can do

```
for h in[0,1]*6:
 for s in d[h]:
  if s in d[1-h]:...

```

Also I changed the move lamda a little bit. First shortend, and then integrated the code directly, since the function call only appears once.

I keep for each state a list of numbers between 0 and 11, to represent the moves, instead of a string containing the moves. The numbers are converted at the very end.

Also I combined the two for-loops `'for k in r(3):for j in r(3):` into one `for y in r(12)`. Therefore I also have to do the moves `U4, R4, F4`. Of course such a move doesn't appear in the shortest solution, so `" 2'"[x%4]` works. (If `x % 4 == 3`, there would be a index out of range exception)

It's also a little bit faster, since I look for the entry in the second set earlier. About 0.5 second for a 11 move solution.
> 12 votes

# Answer
# C, 366 - 50% optimal bonus = 183

```
char c[99],t[3][26]={"ZGONFZCPTEZBHUMZ","ZIQPHZRUGAZJWOCZ","ZACB@ZJHFDZKIGEZ"};r=20;f(int m,int n){int e,i,j;for(i=4;i--;){for(j=15;j--;)c[t[n][j+1]]=c[t[n][j]];c[m]="FRU"[n],c[m+1]="4'2 "[i],c[m+2]=0;for(e=0,j=68;j<76;j++) e+= (c[j]!=c[j+8]) + (c[j]!=c[j^1]);i&&e&&e<45-m*2&m<r?f(m+2,(n+1)%3),f(m+2,(n+2)%3):e||(puts(c),r=m);}}main(){scanf("%s",c+64);f(0,2),f(0,1),f(0,0);}

```

**Using recursion, the program searches** through a tree of up to 11 moves deep (the max length of an optimal soluton according to http://en.wikipedia.org/wiki/Pocket\_Cube and the page mentioned below) and when it finds a solution it prints it (up to 22 characters long, tracked by function argument `m`.) The order used is a kind of dictionary order, where all routes begining U,U2,U' are searched before any routes beginning R or F are searched. Thus it does not necessarily find the optimal solution first.

When a solution is printed, `r` is made equal to `m` which ensures that only equal or shorter solutions will be printed afterwards. Putting `r=m-2` costs an extra 2 characters but ensures only one solution of each length found (down to optimal) is printed. If you want it to ONLY show the optimal solution, the best solution found so far must be stored to a variable, and the optimal solution printed at the end of the program (this would cost about an extra 15 characters.)

the input is read into the array `c[]` from index 64 onwards. This is necessary in order to use alphabet characters in the movetable. The symbols `@` through `W` are used instead of A through X per the question, because it is necessary to start on an even number to make the test for solutions work. `c['Z']` is also used for temporary storage, because in order to perform 4-fold rotation a total of 5 assignments are needed. Because the first part of `c[]` is unused, it is available to store the solution (which is terminated with a zero byte, like all C strings.)

`for(i..)` goes through a sequence of 4 quarterturns of the face specified by `n`.

The first `for(j..)` performs the actual swapping according to table `t[]`.

To test if the cube is solved, **it is only necessary to check the four side faces.** The pieces URF and DFR can be distinguised even with the U and D stickers removed, because one piece reads XRF in the clockwise direction and the other XFR. If the two pieces are interchanged so that U shows on the down face and vice versa, the F colour will show on the right face and vice versa.

The second `for(j..)` counts the number of mismatches on the four side faces. For example for the front face it compares G & O, H & P, and G & H (twice.) If `e`==0, the cube is solved. If `e`\<9 or `e`\<13, it might be possible to solve the cube in the next one move or 2 moves respectively. Otherwise it definitely not possible to solve the cube in this number of moves. In order to save time, **this heuristic is used to prune the search tree** and avoid wasting time on many of those branches of depth 10 or 11 which will be unsuccesful. Expressed as a formula, this becomes `e<45-m*2`.

**Ungolfed Code**

```
char c[99],t[3][26]={"ZGONFZCPTEZBHUMZ","ZIQPHZRUGAZJWOCZ","ZACB@ZJHFDZKIGEZ"};
r=20;                                                       //All moves are output as 2 characters. The index of the last move of the longest solution (11 moves) shall be 20.

f(int m,int n){                                             //perform a cycle through four 1/4 turns of the face specified in n. The index of the move reported in the solution is m.
  int e,i,j;                                                //e is for counting mismatches. i loops through the four 1/4 turns. j performs other functions.
  for(i=4;i--;){

    for(j=15;j--;)c[t[n][j+1]]=c[t[n][j]];                  //A 1/4 turn is performed as three 4-sticker rotations of the type z=a;a=b;b=c;c=d;d=z using the data in the movetable t[][]

    c[m]="FRU"[n],c[m+1]="4'2 "[i],c[m+2]=0;                //Write to the output in c[] the face to be turned and the number of 1/4 turns. Terminate with a zero byte to overwrite any longer solution that may have been found before.

    for(e=0,j=68;j<76;j++)e+=(c[j]!=c[j+8])+(c[j]!=c[j^1]); //Compare each sticker of the top row of the side faces (64+4 through 64+11) with the stickers below and beside it. Count the number of mismatches.

    i && e && e<45-m*2 & m<r?                               //if the number of 1/4turns is not 4 AND the cube is not solved AND the heuristic (as described in the text) is good AND a shorter solution has not already been found,
      f(m+2,(n+1)%3), f(m+2,(n+2)%3):                       //deepen the search to another faceturn of the other two faces.
      e||(puts(c),r=m);                                     //otherwise, if a solution has been found, print the solution and reduce the value of r to the new max solution length.
  }
}

main(){
  scanf("%s",c+64);                                         //scan in the current cube state to c[] at index 64.
  f(0,2),f(0,1),f(0,0);                                     //call f() three times to search for solutions beginning with U R and F.
}

```

**Performance**

The program was tested with patterns 1 to 13 at http://www.jaapsch.net/puzzles/cube2.htm

Results as follows give the timing on my machine to find ALL optimal solutions (for the curious-minded.) Also for the more complex positions, the timing is given for the 2-byte modification mentioned above which finds just one optimal solution. For this timings are given both to find the first solution and for the program to terminate. The solutions given (which are generally different to the solutions obtained by reversing the generators on the linked page) have been verified with an online cube simulator.

```
U 4 (1 move) horizontal flags (not mirror symmetric)
1 solution 1 sec

U2 (1 move) 4 horizontal flags (mirror symmetric)
1 solution 1 sec

F2 R2 F2 (3 moves) 4 vertical flags
UUUULRBFRLFBLRBFRLFBDDDD 2 solutions 1 sec

U2 F2 R2 U2 (4 moves) Supertwist; 6 flags
DDUURRBFRRFBLLBFLLFBUUDD 3 solutions 1 sec

U F2 U2 R2 U (5 moves) 4 vertical flags, 2 checkerboards
UDDULBRFRFLBLBRFRFLBUDDU 2 solutions 1 sec

R2 F2 R2 U2 (4 moves) 4 checkerboards
UUUURLFBLRBFLRBFRLFBDDDD 4 solutions 1 sec

R U2 R' F2 R U' R2 U F2 U' (10 moves) Cube in cube
FFFUDDRFRULLLDRRUULBBBDB 18 solutions 26 sec; 1 solution U F2U'R2U R'F2R U2R' 1,13 sec

R F U' R2 U F' R U F2 R2 (10 moves) Cube in cube 2
DDDUFFLFRBRRLFLLBBRBUUDU 8 solutions 28 sec; 1 solution R F U'R2U F'R U F2R2 12,21 sec

U R F2 U R F2 R U F' R (10 moves)3-Cycle
UFFULDRFRULBLLFRURBBDBDD 45 solutions 26 sec; 1 solution U R'F U'F'R'F2U R F2 8,14 sec

U R U' R2 U' R' F' U F2 R F' (11 moves) Column turn
UUUDLLFRFRBBLLFRFRBBDUDD many solutions 29 sec; 1 solution U R U'F U2R F'R'F'U2F' 3,27 sec

F' U R' F2 U' R F U R2 U R' (11 moves)Corner swap
UUUURLFBLRBFLLFFRRBBDDDD 29 sec 24 solutions; 1 solution R U'F R U'R2U'F'R'U F2 12,28 sec

U F2 U' (3 moves) Zig-zag
UDUDLLFRFFLBLBRRFRBBUUDD 1 solution 1 sec

U' F2 U2 R2 U' F2 U2 R2 U' (9 moves) 2 Checkerboards, 4 L
DUUDLLFBRRBFLRFFRLBBUDDU 8 solutions 13 sec; 1 solution U F2U2R2U R2U2F2U' 1,5 sec

```
> 7 votes

---
Tags: code-golf, puzzle-solver, permutations, rubiks-cube
---


# Question
Title: Make a webpage where it looks like the browser is hanging / crashing
Your task today is to create a HTML page.

This page, when opened in a browser, behaves as if the browser has a problem (hanging, crashing, network error, virus, etc.)

* You **can** use all the HTML(5), CSS(3) and JavaScript features you want.
* You **can't** use Flash or other plugins.
* You **can't** provoke a real problem in the browser (for example, you can't make the browser hang with an infinite loop, or crash with a bug exploit, etc.), just make it *look like* there is a problem.

Please post your source code and provide an URL to view your page, and precise on which browsers / devices it works (if specific).

I recommend http://www.c99.nl/ to host your page easily.

This is a popularity contest, so the most upvoted answer wins!

Thanks, and have fun!

# Answer
> 6 votes
```
<html>
 <head>
  <title>Connecting...</title>
 </head>

 <body style="margin: 0px; overflow:hidden;">
  <div style="position: relative;">
   <div style="position: absolute; top: 0; left: 0; width: 100%; height: 100%; cursor:wait;"></div>
   <iframe src="http://www.wikipedia.com/" width="100%" height="100%" style="border: 0px;">
   </iframe>
  </div>
 </body>
</html>

```

http://c99.nl/f/64943.html

# Answer
> 4 votes
## Better don't mess with Bond villains

Enter Blofelds secret ambush...
And in case you want to see the code: jsfiddle

> After 3 seconds there will pop up a message, that the script isn't responding, but that's only an alert popup and not a real message from a hanging page. After 15 seconds there will be additional greetings from Blofeld.

# Answer
> 4 votes
# Zombie Error

https://dl.dropboxusercontent.com/u/141246873/ZombieError/index.html

Note: It might take a few seconds to load due to the image file.

The webpage consists of the below html, css and javascript as well as an image file zombie.png (graphics by Clint Bellanger licensed CC-BY 3.0).

Tested in google chrome v36, but I expect it will work in most browsers.

### Update:

26th Jul: Now removes zombies once they walk off the screen

28th Jul: You can now click on the zombies to blast them off the website

HTML:

```
<!DOCTYPE html>

<html lang="en">
<head>
    <meta charset="utf-8" />
    <title>Zombie Error</title>
    <link rel="stylesheet" href="app.css" type="text/css" />
    <script src="zombie.js"></script>
</head>
<body style="margin: 0px;">
    <div style="position: relative;">
        <div style="margin: 0 auto; width:100%; height:100%;">
            <iframe src="https://godaddy.com/" style="width: 100%; height: 100%; margin: 0; border-width: 0px;"></iframe>
        </div>
    </div>
</body>
</html>

```

CSS:

```
body {
    font-family: 'Segoe UI', sans-serif;
}

span {
    font-style: italic;
}

.zombie{
    width: 78px;
    height: 78px;
    background-image: url('https://dl.dropboxusercontent.com/u/141246873/ZombieError/zombie.png');
    background-position: left;
    background-position-x: 0px;
    background-position-y: 0px;
    position: absolute;
    left: 10px;
    top: 10px;
}

body{
    overflow: hidden;
}

```

Javascript:

```
var directionWest = 0;
var directionNorth = 6;
var directionEast = 4;
var directionSouth = 2;

var stateWalking = 0;
var stateDying = 1;
var stateDead = 2;

var animWalk = {
    speed: 0.15,
    numFrames: 8,
    frames: [4, 5, 6, 7, 8, 9, 10, 11]
}

var animDying = {
    speed: 0.10,
    numFrames: 8,
    frames: [28, 29, 30, 31, 32, 33, 34, 35]
}

var spriteWidth = 128;
var spriteHeight = 128;

var spriteOffsetX = 25;
var spriteOffsetY = 25;

var spritesheetWidth = 4608;

function Zombie(_id, _x, _y, _direction) {
    this.direction = _direction
    this.id = _id;
    this.pos = { x: _x, y: _y }
    this.anim = animWalk;
    this.animFrame = 0;
    this.animDelta = 0;
    this.speed = 30;
    this.state = stateWalking;
    this.corpseDelta = 0;
    return this;
}

Zombie.prototype.Update = function (delta) {
    if (this.state == stateDead)
        return;

    //update the animation frame
    this.animDelta += delta;
    if (this.animDelta >= this.anim.speed) {
        this.animDelta -= this.anim.speed;
        this.animFrame++;
        if (this.animFrame >= this.anim.numFrames)
            this.animFrame = 0;
    }

    //background-position-x
    var div = document.getElementById(this.id);
    div.style.backgroundPositionX = ((spritesheetWidth - (spriteWidth * this.anim.frames[this.animFrame])) - spriteOffsetX) + "px";
    div.style.backgroundPositionY = ((spriteHeight * this.direction) - spriteOffsetY) + "px";

    if (this.state == stateWalking) {
        //update position
        if (this.direction == directionEast)
            this.pos.x += (this.speed * delta);
        if (this.direction == directionWest)
            this.pos.x -= (this.speed * delta);
        if (this.direction == directionNorth)
            this.pos.y -= (this.speed * delta);
        if (this.direction == directionSouth)
            this.pos.y += (this.speed * delta);
        div.style.left = Math.floor(this.pos.x) + "px";
        div.style.top = Math.floor(this.pos.y) + "px";
    }
    else if (this.state == stateDying && this.animFrame == (this.anim.numFrames - 1)) {
        this.state = stateDead;
    }
}

var zombies = []

var nextZombieID = 0;

function GetZombie(zombieID)
{
    return zombies.filter(function (z) { return z.id == zombieID })[0];
}

function ZombieClick(div)
{
    var zombie = GetZombie(div.srcElement.id);

    if (zombie.state == stateWalking) {
        zombie.state = stateDying;
        zombie.animFrame = 0;
        zombie.animDelta = 0;
        zombie.anim = animDying;
    }
}

function NewZombie()
{
    var x = 0;
    var y = 0;
    var direction = 0;

    var rand = Math.random();
    if (rand < 0.25)
    {
        //spawn from left of screen
        x = spriteWidth * -1;
        y = (Math.random() * screen.height) - spriteHeight;
        direction = directionEast;
    }
    else if (rand < 0.5) {
        //spawn from right of screen
        x = screen.width;
        y = (Math.random() * screen.height) - spriteHeight;
        direction = directionWest;
    }
    else if (rand < 0.75) {
        //spawn from top of screen
        x = (Math.random() * screen.width) - spriteWidth;
        y = spriteWidth * -1;
        direction = directionSouth;
    }
    else {
        //spawn from bottom
        x = (Math.random() * screen.width) - spriteWidth;
        y = screen.height;
        direction = directionNorth;
    }

    //generate an id
    var id = nextZombieID;
    nextZombieID++;

    //create a div
    var div = document.createElement("div");
    div.id = id;
    div.classList.add("zombie");
    div.onclick = ZombieClick;
    document.body.appendChild(div);

    //create a zombie
    zombies.push(new Zombie(id, x, y, direction));
}

var spawnRate = 1;
var spawnDelta = 0;

function spawnZombies(delta)
{
    spawnDelta += delta;
    if (spawnDelta >= spawnRate) {
        spawnDelta -= spawnRate;
        NewZombie();
    }
}

var corpseDuration = 3;

function cleanupZombies(delta)
{
    for (var i = zombies.length - 1; i >= 0 ; i--) {
        //if the zombie has walked off the screen, remove them
        if (zombies[i].pos.x < (spriteWidth * -2)
            || zombies[i].pos.x > screen.width + spriteWidth
            || zombies[i].pos.y < (spriteHeight * -2)
            || zombies[i].pos.y > screen.height + spriteHeight)
        {
            var element = document.getElementById(zombies[i].id);
            element.parentNode.removeChild(element);
            zombies.splice(i, 1);
        }

    }

    for (var i = zombies.length - 1; i >= 0 ; i--) {
        //if the zombie has died, remove their corpse after some time
        if (zombies[i].state == stateDead) {
            zombies[i].corpseDelta += delta;

            if (zombies[i].corpseDelta > corpseDuration) {
                var element = document.getElementById(zombies[i].id);
                element.parentNode.removeChild(element);
                zombies.splice(i, 1);
            }
        }
    }

}

var started = false;

var main = function () {
    var now = Date.now();
    var delta = now - then;
    if (started) {
        cleanupZombies(delta / 1000);

        spawnZombies(delta / 1000);

        for (var i in zombies)
            zombies[i].Update(delta / 1000);
    }

    then = now;

    setTimeout(main, 30);
};

var then = Date.now();
setTimeout(main, 30);

setTimeout(function () {
    alert("Error 8102: Unexpected zombie attack. Please stand by...");
    started = true;
}, 2000)

```

# Answer
> 3 votes
Redirect to `about:crash`, which shows the default crash screen on Chrome \[won't work on modern versions of Chrome, Firefox, or other browsers\]:

```
<meta http-equiv="refresh" content="0; url=about:crash">

```

It probably doesn't qualify as a "full HTML page", but it will be rendered correctly by Chrome.
To try it, type this into the Chrome address bar:

```
data:text/html;base64,PG1ldGEgaHR0cC1lcXVpdj0icmVmcmVzaCIgY29udGVudD0iMDsgdXJsPWFib3V0OmNyYXNoIj4=

```

*I couldn't test this answer because I don't have a Chrome install handy, please remove this notice once you test it.*

# Answer
> 1 votes
# Glitchy scroll

No, that's not bad image compression. Unintended side effect from something else I was trying.

Try it out with the link in the title; The page starts looking weird while you scroll, and the scroll should become very jittery after a while. I think you need font smoothing of some sort activated, but everyone has this nowadays, right? The screenshot is from Chrome on OS X.

### The jQuery code:

```
$( window ).scroll(function() {
    $('#main').clone().prependTo('body');
});

```

# Answer
> 1 votes
# HTML + CSS + JavaScript/jQuery/jQuery UI

This simulates a Windows error dialog. (It drags, too!) Like all good error messages, it fulfills two main requirements:

1. It displays a cryptic error message meaning nothing to all but a few.
2. The buttons seem to do nothing when clicked except show the `wait` cursor.

See it in action at http://codepen.io/anon/pen/onbAi. (JSFiddle was not loading jQuery UI well.) It should display reasonably well on all browsers.

```
<!DOCTYPE html><html>
<head><style>
body {
  font: 11px sans-serif;
}
#window {
  background-color: #ECE9D8;
  padding: 3px;
  width: 574px;
  margin: 20px auto 0 auto;
  -moz-user-select: -moz-none;
  -khtml-user-select: none;
  -webkit-user-select: none;
  -ms-user-select: none;
  user-select: none;
}
header {
  background-color: #1E74EF;
  background-image: -moz-linear-gradient(left, #003ac9 0%, #4492e5 100%);
  background-image: -webkit-linear-gradient(left, #003ac9 0%, #4492e5 100%);
  background-image: linear-gradient(to right, #003ac9 0%, #4492e5 100%);
  clear: both;
  padding: 3px;
}
p {
  margin-left: 60px;
}
h1 {
  font: bold 13px sans-serif;
  color: white;
  margin: 1px;
}
button {
  background-color: #ECE9D8;
  outline: none;
  cursor: inherit;
}
#close {
  float: right;
  font-size: 16px;
  font-weight: bold;
  padding: 0 2px;
  margin: 0;
  text-align: center;
  height: 18px;
  line-height: 16px;
}
#ok {
  width: 75px;
  height: 23px;
  margin: 0 auto;
  margin-bottom: 13px;
  display: block;
}
</style></head><body>
<div id="window">
  <header>
    <button id="close" title="Close">×</button>
    <h1><span id="browser"></span>Application Error</h1>
  </header>
  <p>The instruction at "</span>" referenced memory at "<span class="hex"></span>". The memory could not be "read".</p>
  <p>Click on OK to terminate the program</p>
  <button id="ok">OK</button>
</div>
<script src='//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js'></script>
<script src='//ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/jquery-ui.min.js'></script>

$('#window').draggable({handle:'header'});

function randomHex(){
  return '0x'+(Math.floor(Math.random()*0xffffffff)).toString(16);
}

$('.hex').each(function(){
  $(this).text(randomHex());
});

var reg = /(opera|chrome|safari|firefox|msie)/i,
    browser = navigator.userAgent.match(reg)[0].toLowerCase();
if(!browser){
  browser = 'firefox';
} else if(browser == 'msie'){
  browser = 'ie';
}
$('#browser').text(browser + '.exe - ');

$('button').click(function(){
  $('html, body').css('cursor','wait');
});
</script>
</body></html>

```

# Answer
> 0 votes
I've tested this on my smartphone. I can't get it to load properly on c99.nl, though. Must be that obscure.

It makes your browser look possessed with some sort of obscure virus affecting the loading bar.

```
<!DOCTYPE html>
<script>
window.location.href = document.location.href;
</script>
<title>Redirecting...</title>
<h3>Redirecting...</h3>

```

## Notes:

1. This can easily be tested locally by copying it into a plain text file, and the name or place doesn't matter beyond file extension. It is valid HTML5 + JavaScript (you can see for yourself here...only warning is missing `<meta charset=utf-8 />`).
2. Make sure that if you test it, especially on a mobile device, stop the loading loop first (same as cancelling a page load) before you exit, or it ***may crash***. (I learned this the hard way...)

> In case you hadn't noticed, it's continually redirecting to the same page. `window.location.href` and `document.location.href` are synonymous, so it's assigning the current location to its synonym. It could look like server lag or a browser hang, depending on the browser and largely it's caching mechanism.
>
> That last line is just for theme.

# Answer
> 0 votes
```
data:text/html, <meta http-equiv="refresh" content="0"><script>document.write("Error Code : " + (Math.floor(Math.random() * 10000)  % 1000) + ". Description: Network connection error.")</script>

```

The error code keeps changing, and the computer goes noisy.

# Answer
> 0 votes
Simulates an lagging loading spinner

http://c99.nl/f/104794.html

Sourcecode: http://jsfiddle.net/3QURA/2/

HTML:

```
<div id="loader" style="">
<br/>
<div id="spinner"> </div>
<br/>
<br/>
Loading...
</div>

```

CSS:

```
body,html {
    width:100%;
    height:100%;
    margin:0;
    color:white;
}
#spinner {
    background:transparent;
    width:100px;
    height:100px;
    left:calc(50% - 100px / 2);
    position:relative;
    -webkit-animation: load infinite 1s;
    -webkit-border-radius: 100%;
    border-right:white 8px solid;
}
@-webkit-keyframes load {
    0% { -webkit-transform:rotate(0deg) }
    100% { -webkit-transform:rotate(360deg) }
}
.paused {
    -webkit-animation-play-state:paused;
}
#loader {
    font-family:Helvetica Light, Helvetica Neue, Helvetica, Arial, sans-serif;
    left:0%;
    position:fixed;
    text-align:center;
    background:rgba(55,55,55,0.5);
    width:100%;
    height:100%;
}

```

JavaScript and jQuery:

```
window.setInterval(update, 1000/2);
function update() {
window.setTimeout(function () {
    $("#spinner").addClass("paused");
},1000);
window.setTimeout(function () {
    $("#spinner").removeClass("paused");
},1200);
}

```

# Answer
> 0 votes
## Chrome Crash Page

Actual Link: **chrome://crash/**

**HTML**

```
<!DOCTYPE html>
<html>
<head>
  <script src="//cdnjs.cloudflare.com/ajax/libs/prefixfree/1.0.7/prefixfree.min.js"></script>
  <meta charset="utf-8">
  <title>JS Bin</title>
</head>
<body>
 <img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEIAAABCCAQAAABJXchjAAAAjklEQVR4Xu3ZgQbAIAAG4d7/pbeJxJCOWf26DozSh0RWrg0aAESIEEEtxJ6E6ICZUXrTc7MQZID5pyFEiPiwAMQPNYiIpyBEAwIoWBOEAACwJhHhmfCeEEH17++DEPwRlI/giRAhoow7ANE2gchkBN8c4GMQNI6JRHhjiqitAOyEWPsXqkq2QSxNhAgR4269KKbHaOQ5OgAAAABJRU5ErkJggg==" alt="Crash">
  <div>Aw, Shit!</div>
  <p>This page is really fucked up, run for the hills.</p>
  <button>Reload</button>
  <p>If it doesn't work, it's all your fault.</p>
</body>
</html>

```

**CSS**

```
html, button {
  user-select: none;
  cursor: wait;
  font-family: Calibri, Sans-serif;
  text-align: center;
}
body {
  padding-top: 120px;
  background: #212e3d;
  font-size: 80%;
  color: white;
}
button {
  font-family: Calibri, Sans-serif;
  padding: 5px 10px;
}
div {
  font-size: 140%;
}

```

---
Tags: popularity-contest, browser
---


# Question
Title: How much time will I need to unlock my Android phone?
**Scenario**

I am using pattern matching lockscreen and I sadly forgot my pattern. I would like to know how much time I will need to unlock it. Here are the specifications of Google's lock screen, that we will use for this challenge.

* Every 5 wrong code, the user has to wait `30 seconds` before any further entry.
* A pattern must, at least, consist in `4 points` (see below)
* A point can be only used once, but you can go over it several times (see image right below):

Here, the center point is only used once, even if we go over it again for this particular pattern.

**Hypothesis & Facts**

We'll assume we're superheroes and that we can draw any pattern in `1 second`, we never need to eat or sleep. Yeah, we're superhumans.

I'm a very unlucky person. "Worst case scenario" is my daily life so the pattern I will attempt **last** will be the right one.

**What do we have to pwn?**

For those who don't know it, Android (and other phones now) offers the ability of unlocking the phone through drawing a pattern on a 9-point matrix. This matrix can be described as follow :

```
C(A)  M(B)  C(C)
M(D)  X(E)  M(F)
C(G)  M(H)  C(I)

```
* C standing for "corner point"
* M for "middle point"
* X for "center point"
* I have given identifiers to the points to make it easier

The permitted **direct** connections are as follows :

**Corner point :**

**Middle point :**

**Center point :**

However, as pointed out by steveverrill, "once the centre has been used (and therefore becomes unavailable) a direct connection between the bottom left and top right corner becomes unambiguous and therefore possible". Same goes for every "middle point", if e.g. the point B has already been counted, then a direct connection between A and C is possible. If e.g. F has already been counted, then a direct connection between C and I is possible. Etc...

**Rules**

* The point of this challenge is to return how much time (in human readable form, aka year/day/month/hour/whatever the time you find) I will need to unlock this damn phone.
* You can't hardcode the number of possible valid patterns (don't even Google it, you fool), calculate it (that's actually the fun part, isn't it ?)
* Shortest piece of code wins
* Good luck !

# Answer
> 3 votes
# Rebmu: ~~197 175 168~~ 167 characters

Generates combinations as a series of numbers (ex. 12369 is top-left to top-right to bottom-right), checks if combination is valid, and increments a counter if it is. This might take a **while\*** to run. Returns the number of seconds needed to unlock the phone.

```
B[[2 13][4 17][6 39][8 79][5 19][5 28][5 37][5 46][a 0]]Fdz[Q1feCb[st[a]paStsC/1 Qa^Qa^e?NNfiAtsC/2 e?NNfiArvTSc/2]]rpJ987653088[StsADj1233iA^e?SuqSf[++K]]adKmp30dvK 5

```

Unmushed and commented:

```
; for each subarray c:
; the sequences c/2 and c/3 are invalid before the point c/1 is pressed
; a 0 - a is never in the sequence, therefore 0 is always invalid
b: [[2 13] [4 17] [6 39] [8 79] [5 19] [5 28] [5 37] [5 46] [a 0]]
; checks (most) conditions of validity
f: dz[
    ; set q to 1
    q: 1
    ; foreach array in b as c
    fe c b [
        ; set a to be portion of s before c/1
        st [a] pa s ts c/1
        ; q = q and (a does not contain c/2) and (a does not contain reverse of c/2)
        q: a^ q
           a^ e? nn fi a ts c/2
              e? nn fi a ts rv c/2
    ]
]
; repeat 98765308 times, with j = 1 to 98765308
; 987653088 = 987654321 (largest valid combination) - 1234 (smallest valid combination) + 1
rp j 987653088 [
    ; set s to j+1233 (smallest valid combination - 1) as a string
    s: ts ad j 1233
    ; if f returns trues and s does not contain duplicates, increment k
    i a^ e? s uq s
          f
     [++ k]
]
; print k (number of combinations) + 30 * (k/5) -> number of seconds needed
ad k mp 30 dv k 5

```

The program loops from 1 to (987654321-1233), checking 1233+loop counter (therefore checking 1234 to 987654321).

If the number `987653088` is replaced with, `9876-1233` or `8643`, then the program will find the time taken for all 4-point combinations.

Output for `9876-1233=8643` (4-point combinations):

```
>> rebmu %combinations.rebmu
== 11344

```

Output for `98765-1233=97532` (4 and 5-point combinations):

```
>> rebmu %combinations.rebmu
== 61426

```

Output for `987654-1233=986421` (4,5,6-point combinations):

```
>> rebmu %combinations.rebmu
== 243532

```

---

\*4/5-point took me about 8 seconds to run; 4-6 took about 77 seconds. It might take ~24 hours or longer depending on who runs this to calculate number of combinations for 4-9 point combinations.

---
Tags: code-golf, combinatorics
---


title: What is your star-sign?

text:
# Question
Title: What is your star-sign?
Write a program that takes a birth date (month and day-of-month) as input and outputs the corresponding sign, element and quality of the western zodiac. For the purposes of this challenge, these are defined exactly as in the table in the linked wikipedia page:

```
Sign           Date Range                    Element    Quality

Aries          March 21 to April 19          Fire       Cardinal
Taurus         April 20 to May 20            Earth      Fixed
Gemini         May 21 to June 21             Air        Mutable
Cancer         June 22 to July 22            Water      Cardinal
Leo            July 23 to August 22          Fire       Fixed
Virgo          August 23 to September 22     Earth      Mutable
Libra          September 23 to October 23    Air        Cardinal
Scorpio        October 24 to November 20     Water      Fixed
Sagittarius    November 21 to December 22    Fire       Mutable
Capricorn      December 23 to January 20     Earth      Cardinal
Aquarius       January 21 to February 21     Air        Fixed
Pisces         February 22 to March 20       Water      Mutable

```

### Rules

* The sign, element and quality will be calculated from the input date exactly according to the wikipedia table.
* I am giving some freedom over input date format (see **Input** section below). You must clearly state in your answer what format you are using.
* If an invalid date is provided (unparsable date, or month or day-of-month out of range), the program will exit with the message `Invalid date`.
* The program must correctly handle leap years. i.e. if Feb 29th is the input, then output must correctly be `Pisces, Water, Mutable`.
* Your language's Date libraries/APIs are allowed, but any APIs that specifically calculate signs of the zodiac are banned.
* Standard “loopholes” which are no longer funny
* This is , so the shortest answer in bytes wins.

### Input

* The program may read the input date from STDIN, command-line, environment variables or whatever method is convenient for your language of choice.
* This is not primarily an exercise in datestring-parsing, so the input string may be provided in whatever format you choose, as long as it consists of only month and day-of-month components and not other values (such as year or time). E.g. `Jul 24` or `24th of July` or `7/24` or `24/07` or whatever format is convenient. If input not matching your choice of input format is entered, then the `Invalid date` error must be thrown.

### Output

* The program will output to STDOUT, dialog box or whatever display method is convenient for your language of choice.
* The output format will be the sign, element and quality separated by a comma and a space: `Sign, Element, Quality`

### Examples

```
Input                 Output
1/1                   Capricorn, Earth, Cardinal
2/29                  Pisces, Water, Mutable
7/24                  Leo, Fire, Fixed
13/1                  Invalid date
2/31                  Invalid date
-1/-1                 Invalid date
1st of Golfember      Invalid date

```

# Answer
> 8 votes
# JavaScript, 285 bytes

(My first answer here after lurking here for a while)

```
d=prompt(m=prompt(e='MutableCardinalFixedAirWaterFireEarthCapricornAquariusPiscesAriesTaurusGeminiCancerLeoVirgoLibraScorpioSagittarius'.match(/[A-Z][a-z]+/g)));alert(m>0&m<13&d>0&d<29-~'202121221212'[--m]?e[n=7+m%12+(d>18-~'121012333413'[m])]+', '+e[n%4+3]+', '+e[n%3]:'Invalid date')
```

The first `prompt()` is the month in numerical form, and the second `prompt()` is the day of the month (Ignore the text of the prompt). Leading zeroes are optional for both. The output is displayed with `alert()`. (Thanks to bitpwner, Snack, edc65, and core1024 for helping shorten the code.)

Try it above using Stack Snippets or at http://jsfiddle.net/8vq89/5/.

Code with whitespace and comments to explain the confusing parts added:

```
var m = prompt(), d = prompt(),
e = 'MutableCardinalFixedAirWaterFireEarthCapricornAquariusPiscesAries\
TaurusGeminiCancerLeoVirgoLibraScorpioSagittarius'.match(/[A-Z][a-z]+/g);
alert(m > 0 && m < 13 && d > 0
      & d < 29 - ~'202121221212'[--m] /* ~ is bitwise NOT, which yields -(x + 1). It also
                                         converts a string to a number. Subtracting that
                                         number from 29 gives the number of days in the
                                         month given. */
      ? e[n = 7 + // 7 is added to skip over the 7 qualities and elements in array e.
      m % 12 // The modulus allows dates near the end of December to wrap around to January.
      + (d > 18 - ~'121012333413'[m])] + ', ' +
      e[n % 4 + 3] + /* Qualities and elements follow a pattern, so the modulus determines
                        which one it is. 3 is added to skip over the 3 qualities. */
      ', ' + e[n % 3] : 'Invalid date')

```

# Answer
> 3 votes
# C 353 ~~352~~

**Edit** Fixed bug and typo, 1 char more

Before you ask: yes, even without #include is valid and working C standard.
Input format: two numbers, first month, then day.

```
char*s[]={"Air","Water","Fire","Earth","Fixed","Mutable","Cardinal","Aquarius","Pisces","Aries","Taurus","Gemini","Cancer","Leo","Virgo","Libra","Scorpio","Sagittarius","Capricorn"};
main(m,d){
  scanf("%d%d",&m,&d);
  m>0&m<13&d>0&d<(32-(4460832>>m>>m&3))
  ?m+=10+(" 121012333413"[m]-29<d),printf("%s, %s, %s\n",s[m%12+7],s[m%4],s[m%3+4])
  :puts("Invalid date");
}

```

**Test**

```
char*s[]={"Air","Water","Fire","Earth","Fixed","Mutable","Cardinal","Aquarius","Pisces","Aries","Taurus","Gemini","Cancer","Leo","Virgo","Libra","Scorpio","Sagittarius","Capricorn"};
char *test(char *o, int m, int d)
{
  char *result=o;
  m>0&m<13&d>0&d<(32-(4460832>>m>>m&3))
  ?m+=10+(" 121012333413"[m]-29<d),sprintf(o, "%s, %s, %s\n",s[m%12+7],s[m%4],s[m%3+4])
  :(result = 0);
  return result;
}

int main()
{
  char buf[100];
  int m,d;
  for (m=0;m<14;m++)
    for(d=0;d<40;d++)
      if (test(buf, m,d)) printf("%d %d %s", m, d, buf);
  return 0;
}

```

# Answer
> 2 votes
# Perl 287 (286 + 1 for the `-p` flag)

```
/\//;$_=32-(26830452>>$`*2&3)<$'|$'<1|$`<1|$`>12?'Invalid date
':qw(Aquarius01 Pisces23 Aries45 Taurus61 Gemini03 Cancer25 Leo41
Virgo63 Libra05 Scorpio21 Sagittarius43
Capricorn65)[$`-1-($'<20+(219503166088>>$`*3&7))].$/;s/\d/', '.qw(Air
Fixed Water Mutable Fire Cardinal Earth)[$&]/eg

```

The input is from STDIN and the output goes to STDOUT. Here are the tests from OP:

```
1/1
Capricorn, Earth, Cardinal
2/29
Pisces, Water, Mutable
7/24
Leo, Fire, Fixed
13/1
Invalid date
2/31
Invalid date
-1/-1
Invalid date
1st of Golfember
Invalid date

```

# Answer
> 1 votes
# Python, ~~447~~ 387 characters

```
import sys
try:S=sys.argv[1];a,b=int(S[:2])-1,int(S[3:])
except:a=b=0
print['Invalid date',', '.join((s.split()*5)[a+(b>[20,21,20,19,20,21,22,22,22,23,20,22][a%12])]for s in"Capricorn Aquarius Pisces Aries Taurus Gemini Cancer Leo Virgo Libra Scorpio Sagittarius Capricorn|Earth Air Water Fire|Cardinal Fixed Mutable".split("|"))][-1<a<12and 0<b<[32,30,32,31,32,31,32,32,31,32,31,32][a]]

```

Takes input as MM/DD, must always be two digits.

```
$ python zods.py 01/01
Capricorn, Earth, Cardinal
$ python zods.py 02/29
Pisces, Water, Mutable
$ python zods.py 07/24
Leo, Fire, Fixed
$ python zods.py 13/01
Invalid date
$ python zods.py 02/31
Invalid date
$ python zods.py -1/-1
Invalid date
$ python zods.py First of golfember
Invalid date
$ python zods.py
Invalid date

```

# Answer
> 1 votes
# Javascript, ~~403~~ 396 bytes

```
M=prompt(),D=+prompt(),i=[52,85,117,147,180,213,246,278,310,343,372,406,415];if([0,0,-2,0,1,0,1,0,0,1,0,1,0][M]<D-31||M<1||D<1||M>12)alert("Invalid date");else for(x in i)if(M*32+D<=i[x]){alert("Capricorn0Aquarius0Pisces0Aries0Taurus0Gemini0Cancer0Leo0Virgo0Libra0Scorpio0Sagittarius0Capricorn".split(0)[x]+", "+["Earth","Air","Water","Fire"][x%4]+", "+["Cardinal","Fixed","Mutable"][x%3]);break}

```

Another approach. I think I can golf down more, but later.

Input month on first prompt, date on second prompt.

# Answer
> 1 votes
# PHP - 294 bytes (w/o php tags\*)

**\*As the other php entry did**

Input:`Month Day` as integers, leading zero not required.

Ex:`php starsign.php <<< "2 29"` for February 29th.

Golfed (do not copy this directly, see below):

```
<?@eval(gzinflate('=Œ1Â0…ÿŠC!Ë
¦q+JQ—
BEq¸¶¡Ô¤^ðç{¤"ï>/Ãò®`³GOBqú7v¥±MP#äpúµ;$:Å€Ý$“g¦Þ³ƒê‘).p¦¥·TL’Œ,ÝÑ¾È‘¬]oëáJ<zh¨c„V3yhq¤VË_ü(²®TZË¥ØêÜ³ÓF_'));die(fscanf(STDIN,'%u%u',$m,$d)/2&$m<13&&$m*$d&&$d<33-$b[$m]?$a[7+$m-=$d<20+$b[$m+9]].$a[$m%4].$a[$m%3+4]:'Invalid date');

```

Hexdump of php file:

```
3f3c 6540 6176 286c 7a67 6e69 6c66 7461
2865 3d27 318c c20b 1030 ff85 438a cb21
a60d 2b71 4a1d 9751 420a 0745 b871 a1b6
d41e 5ea4 f013 7be7 22a4 ef07 1e3e 2f8f
f2c3 60ae 47b3 4f0e 4205 7115 37fa 760c
03a5 4db1 2350 e40f fa70 1fb5 243b c53a
dd80 9324 671a dea6 83b3 1dea 2991 702e
a5a6 0bb7 4c54 1792 2c8c d1dd c8be ac91
6f5d 1a19 e1eb 3c4a 687a 63a8 5684 3304
6879 a471 5610 5fcb 28fc aeb2 5a54 9d1b
a5cb ead8 18dc d3b3 1546 275f 2929 643b
6569 6628 6373 6e61 2866 5453 4944 2c4e
2527 2575 2775 242c 2c6d 6424 2f29 2632
6d24 313c 2633 2426 2a6d 6424 2626 6424
333c 2d33 6224 245b 5d6d 243f 5b61 2b37
6d24 3d2d 6424 323c 2b30 6224 245b 2b6d
5d39 2e5d 6124 245b 256d 5d34 242e 5b61
6d24 3325 342b 3a5d 4927 766e 6c61 6469
6420 7461 2765 3b29

```

To generate golfed file, run the following php script (generates to `starsign.php`):

```
<?php
$a=<<<'NOW'
$a=[', Earth',', Air',', Water',', Fire',', Cardinal',', Fixed',', Mutable',Capricorn,Aquarius,Pisces,Aries,Taurus,Gemini,Cancer,Leo,Virgo,Libra,Scorpio,Sagittarius,Capricorn];$b='1131212112121012333413';
NOW;
$p = '<?@eval(gzinflate(\'';
$s = <<<'NOW'
'));die(fscanf(STDIN,'%u%u',$m,$d)/2&$m<13&&$m*$d&&$d<33-$b[$m]?$a[7+$m-=$d<20+$b[$m+9]].$a[$m%4].$a[$m%3+4]:'Invalid date');
NOW;
file_put_contents('starsign.php',$p . gzdeflate($a) . $s);

```

Completely ungolfed version:

```
<?php
$a=[', Earth',', Air',', Water',', Fire',', Cardinal',', Fixed',', Mutable',Capricorn,Aquarius,Pisces,Aries,Taurus,Gemini,Cancer,Leo,Virgo,Libra,Scorpio,Sagittarius,Capricorn];$b='1131212112121012333413';
if(fscanf(STDIN, '%u%u', $m, $d) == 2
 and $m < 13
 and $m
 and $d
 and $d < 33-$b[$m]){
    if($d < 20 + $b[$m+9])
        --$m;
    die($a[7+$m] . $a[$m%4] . $a[$m%3+4]);
}else die('Invalid date');

```

# Answer
> 1 votes
# Python 3 - 332 bytes

```
s="Capricorn Aquarius Pisces Aries Taurus Gemini Cancer Leo Virgo Libra Scorpio Sagittarius Earth Air Water Fire Cardinal Fixed Mutable".split()
import sys
try:m,d=map(int,sys.argv[1:]);13>m>0<d<b" 313232332323"[m]-19or E
except:x="Invalid date"
else:i=m-1+(d>b" 121012333413"[m]-29);x=s[i%12]+", "+s[-7+i%4]+", "+s[-3+i%3]
print(x)

```
* Takes input as separate arguments (i.e. `1 1`)
* One split for all strings
* Indexing bytes in py3 gives the ord
* `or E` is a cheap way to generate an exception (`NameError`)
* Is there a cheaper way to concatenate the strings? `+` and literals turned out to be smaller than `join`.
* There's no good reason for one bytes lookup to start with 1 and the other with 0, I just forgot the 29-day February and changed 0-\>1 instead of redoing the whole thing.

# Answer
> 0 votes
# PHP ~~548~~ ~~524~~ ~~502~~ 419 (w/o php tags)

Requires PHP \>= 5.4.0

Input: `Day Month` (numerical value starting at 1) e.g. `2 3` for March 2nd.

```
<?
$x='Invalid date';
@list($d,$m)=split(' ',fgets(STDIN));
if(@$m<1||$m>12||@$d<1)die($x);
$z=['Aquarius','Pisces','Aries','Taurus','Gemini','Cancer','Leo','Virgo','Libra','Scorpio','Sagittarius','Capricorn','Air','Water','Fire','Earth','Fixed','Mutable','Cardinal','121012333413202121221212'];
$m=$m+0;$d<$z[19][--$m]+20&&$m--;$m<0&&$m=11;$d>$z[19][$m+12]+29&&die($x);
echo$z[$m+0],", {$z[$m%4+12]}, {$z[$m%3+16]}";

```

**EDIT:** The `A non well formed numeric value` notice is caused by performing a pre-increment on the string `$m`. Regardless of the notice, the following output should still be correct. This notice varies per version of `PHP`. To fix this, a simple string to integer conversion should be placed before the second last line. I've updated the code with the conversions.

Sample Input/Output (on Windows):

```
// March 2nd
Input > echo 2 3 | php star.php
Output > Pisces, Water, Mutable

// Feb. 30th
Input > echo 30 2 | php star.php
Output > Invalid date

// June 30th
Input > echo 30 6 | php star.php
Output > Cancer, Water, Cardinal

```

---
Tags: code-golf, kolmogorov-complexity, date
---


# Question
Title: Find prime which is generating longest primes sequence using p(n+1)=(p(n)^2+1)/2
Consider following recurrence relation:

```
p[n + 1] = (p[n]^2 + 1) / 2

```

If `p[1]`, `p[2]`, ..., `p[k]` are primes and `p[k+1]` is not, then `k` is length of sequence starting with `p[1]`.
For example, if `p[1] = 3`, then `p[2] = 5, p[3] = 13, p[4] = 85 = 5 * 17`, thus length of sequence is 3.

# Goal

Write program which find number producing longest sequence you can find.
Give in your answer starting number, sequence length, source code and time in which program executes.

If multiple answers with same sequence length, then one with greater starting integer wins.
If even starting integer is same, then one with smaller executing time wins.
If you have taken starting integer for your program from another answer, then you should add its time. Picking starting integer at random is disallowed.

Winner will selected 1 week after first answer posted.

# Answer
## Mathematica, 66th 6-prime sequence starting at 178,308,225,421

```
best = {0, 0}
start = TimeUsed[];
For[i = 1, True, i++,
 p = Prime@i;
 length = 0;
 q = p;
 While[PrimeQ@q,
  ++length;
  q = (q^2 + 1)/2;
  ];
 If[length > best[[1]],
  Print[{best = {length, p}, TimeUsed[] - start}]];
 ]
best
TimeUsed[] - start

```

That's a fairly trivial exhaustive search. The search doesn't terminate, so you need to abort it with `Alt`+`.` after which it'll tell you how long it has run in total.

Some timings on my machine

```
Length    Starting Prime    Cumulative Time

4         271               0.002 s
5         169,219           0.297 s
6         356,498,179       692.1 s ~ 11.5 min

```

The search for 7 primes is still running. (After 110 hours I'm still an order of magnitude below the next result as given by OEIS.)

**Edit:** I got a moderate speed-up by ditching the lookup table.

**Edit:** The search has been running all night. This time I kept track of how all n-prime sequences before the first (n+1)-prime sequence. I also switched to `NextPrime` but I think it's actually slower - of course, I'll need it if I keep this running over the weekend.

Here is some data:

If `m(n)` is the number of n-prime sequences before the first (n+1)-prime sequence, then m(n) progresses like {1, 0, 4, 10, 55, \>65}.

The first 5-prime sequence starts at 169,219 and took 0.3s. The last 5-prime sequence (before the 6-prime ones start) starts at 350,505,151 and took 680s to find. While the distance between two consecutive 5-prime sequences is usually on the order of 106, the two most closely spaced such sequences start at 222,193,661 and 222,266,839.

So far I've found the following 6-prime sequences:

```
 Starting Prime    Cumulative Time

    356,498,179       692.2 s ~  11.5 min
    432,448,789       860.1 s ~  14.5 min
  5,380,300,469    13,967.6 s ~   3.9 h
 10,667,785,241    30,519.5 s ~   8.5 h
 11,238,777,509    32,353.6 s ~   9.0 h
 12,129,977,791    35,218.5 s ~   9.8 h
 23,439,934,621    71,781.2 s ~  20.0 h
     ...  29 more ...
 95,986,224,779   304,385.  s ~  84.5 h
 99,143,377,451   314,512.  s ~  87.4 h
102,928,086,161   326,881.  s ~  90.8 h
     ...   7 more ...
125,338,612,429   398,873.  s ~ 110.8 h
     ...  18 more ...
178,308,225,421   568,694.  s ~ 158.0 h

```

As for the spacing of 6-prime sequences, the largest gap was about 11e9 between the 6th and 7th sequence. The two closest sequences were about 5e6 apart, the first one starting at 123,333,728,319 - they were found within 16 seconds of each other, when sometimes there is no new sequence for several hours. Also, there are 5 sequences starting between 33.99e9 and 34.9e9.

**Edit:** The week is over in a couple of hours, and I think 66 6-prime sequences is a good number, so I'm stopping this now.
> 3 votes

# Answer
# Sage, 5 primes in 7.86 s (via Sage Notebook)

Not nearly as fast as Martin's answer, but it does work. I'm working on installing Sage onto my computer to see if it runs faster on my machine, rather than on the web.

```
def PrimePermutation(b):
    t = cputime()
    best = 0
    P = Primes()
    i=1
    while i<b:
        i=i+1
        q = P.next(i)
        r = q
        length = 0
        while q in P:
            length=length+1
            q = (q^2+1)/2
        if length > best:
            print(r, length, cputime() - t)
            best = length

PrimePermutation(4e10)

```

Returns (so far)

```
(3, 3, 0.0)
(271, 4, 0.009999999999990905)
(169219, 5, 7.860000000000014)

```
> 0 votes

---
Tags: code-challenge, primes
---


# Question
Title: Homework time! Find me the lowest even digit in a string
Another brilliant question from Stack Overflow turned into a challenge!

Write a program that:

1. Accepts a **string** as user input (not *piped in* or a command line argument). The data type of the input must be a string, if the language does auto evals on input, it must be cast to a string.
2. Finds the index (0 or 1 based) of the first lowest even *digit*.
3. **Prints 2 integers**, the index and the lowest even *digit*.
4. If there is no even *digit*, return -1 as the index, the second number can be anything.
5. For the purposes of this *zero is not even*.

Test examples, given the string on the left output the values on the right:

```
25376  -->  0,2
523726 -->  1,2
583746 -->  4,4
53771  --> -1,0
_4___2 -->  5,2

```

**The winner: is the program with the lowest character count.** No bonuses, no penalties.

**edit: (about stdin)** I screwed up on the user input part, basically no piping data in, and no command line arguments. You must provide a user prompt of some kind within the program itself.

# Answer
# Golfscript, 26 (28) characters

```
'#{gets}'.'246'&8+$1<.@\?

```

Example:

```
;'583746'
.'246'&8+$1<.@\?
#44

;'53771'
.'246'&8+$1<.@\?
#8-1

```

live test: http://golfscript.apphb.com/?c=Oyc1Mzc3MScKLicyNDYnJjgrJDE8LjA9QD8%3D

Explanation:

* `'#{gets}'` is an escape to ruby to satisfy the I/O requirements; STDIN is assumed to be empty
* `.` clones the input
* `'246'&8+` finds which even digits are present in the input, except `8` is always retained
* `$1<` sorts the list, then takes the first digit, but keeps it as a string
* `.@\?` orders the stack {digit, input, digit}, then finds the digit in the input; thanks @peterTaylor for noticing me of the \[array, array\] signature of `?`.

I've been very bold with the spec interpretation this time; namely:

* The spec does not mandate in which order the integers are output; Use the other @peter's suggestion `:x?x` to fix (I don't like temporary variables.
* The spec does not require any delimiter between the two integers; since the digit found is always a single digit, this does not matter much. If it does, append `n@` (which also performs the swap), `n\` (which doesn't), or `]`` (which formats the output as `["8" -1]`).
> 6 votes

# Answer
## APL (37)

(1-based by default, but obeys `⎕IO`)

```
{×⍴m←⍵/⍨⍵∊'2468':z,⍨⍵⍳⍕z←⌊/⍎¨m⋄¯1,0}⍞

```

Explanation:

* : read user input
* `m←⍵/⍨⍵∊'2468'`: remove all the characters that aren't `2468`, store in `m`.
* `×⍴m`: see if there are any
* `:`: If so:
    + `z←⌊/⍎¨m`: evaluate each character in `m`, find the lowest number and store in `z`.
    + `z,⍨⍵⍳⍕z`: return the index of `z` in , followed by `z`.
* : If not:
    + `¯1,0`: return `(-1, 0)`
> 5 votes

# Answer
**Python 3 ,69**

combining ideas from here.

```
s=input();print(([(s.find(x),x)for x in'2468'if x in s]+[(-1,0)])[0])

```
> 3 votes

# Answer
# Ruby, 60 characters

```
x=gets.chars.sort.find{|c|c=~/[2468]/};p x ?$_.index(x):-1,x

```
* `$_` contains the last input read by `gets`.
* `p` calls `inspect` on the arguments and prints the results.
> 3 votes

# Answer
# Perl 6, ~~37~~ ~~55~~ *60* characters

```
$_=get;say m/<{~.comb(/<[2468]>/).min}>/.from//-1,',',$/.Int

```

EDIT: I misunderstood the question the first time. This update should be correct. It finds the lowest number of 2,4,6, or 8 that the input contains, and then does a regex match against the input with that lowest number. `$/.from` gets the position of the match and `',', $/.Int` is a comma plus the match itself, or 0 if the text didn't match.

While you're here, go upvote G. Cito, who helped me fix my entry in the comments and on irc :)
> 3 votes

# Answer
## perl - -~~94~~\- 53 chars (or 48)

Instead of `index()`'s zero-based approach we use `pos` and start at one; no CPAN. Run this with `perl -nE` and it will wait for input (which it can also receive from `STDIN`).

The first match (`//`) operation works on the default value (`$_`) from input, matching against the given even numbers, `sort`ing the matches into an array, and then storing them in a "scalar list" `($m)`. In scalar context the list value of the sorted array is one item long and thus consists of the lowest matched even digit in the number.

Having isolated the lowest even matched digit, we then use `$m` for a second match operation which will find the first occurrence of the value of `$m` in the original string. We are still using the default value here `$_` and we are saving the match against the contents of `$m` in `$1` (the reason for the `()` around `$m` in the second statement). After that, `pos` and `say` do the rest (and in fewer characters than `index` and `print`).

```
perl -nE'($m)=sort/[2468]/g;/($m)/g;$1?say pos.",$1":say"-1,0"'
33467
3,4

```

If output order or commas don't matter then it's possible to make this 5 chars shorter:

```
($m)=sort/[2468]/g;/($m)/g;$1?say$1.pos:say"-10"

```

In my earlier attempt I rushed and made an error - I just wanted to beat python and ruby (but failed) ... sigh.

Congrats to the winner and the other participants on their cool solutions - especially to `perl6` :-) A possible Perl6 adaptation of this approach could use "`.comb` (suggested on freenode by Masak *et.al.*).

```
$_=get;my $n=.comb(/<[2468]>/).min;/$n/;say $/.from//-1,",$/"

```
> 3 votes

# Answer
# Python 2.7 - 76

A reference answer I fully expect to be beaten. But to start people off:

```
s=raw_input()
print[(s.index(`e`),e)for e in[2,4,6,8]if`e`in s][:1]or(-1,0)

```
> 2 votes

# Answer
# J, 44 characters

```
echo(;{&i){._1,~(#~(#i)&>)'2468'i.~i=.1!:1]1

```

outputs the last character of the input if no even digit is found

Example:

```
   echo(;{&i){._1,~(#~(#i)&>)'2468'i.~i=.1!:1]1
523726
+-+-+
|1|2|
+-+-+
   echo(;{&i){._1,~(#~(#i)&>)'2468'i.~i=.1!:1]1
53771
+--+-+
|_1|1|
+--+-+

```

Explanation:

* `echo ... i=.1!:1]1` is input/output. Way longer than I want it to. Input is stashed away into `i` as well.
* `'2468'i.~` finds the first occurence of each even digit in the input, returning the input length if the digit cannot be found
* `(#~(#i)&>)` reads "select by the length of input being greater than this"; in other words, select those indices that point into the input. Way longer than I want it to.
* `_1,~` appends -1 to the back. Underscore is the J's way of representing negative values.
* `{.` selects the first element
* `(;{&i)` concatenates it with the input character at that position in two boxes; since we're concatenating a number with a character, non-boxing concatenation (`,`) won't do. If unboxed display is desired, the index needs to be formatted (`":`) first at a cost of two chars.
> 2 votes

# Answer
## R, 104

```
y=as.integer(strsplit(scan(,""),"")[[1]]);z=which(!y%%2&y);a=z[which.min(y[z])];cat(a,"-1 0"[!sum(a)],y[a])

```

Examples (in R, the index starts at 1):

```
_4_502
6  2

_3_501
-1 0

583746
5  4

```
> 2 votes

# Answer
## Powershell, ~~76~~ ~~73~~ 71

```
$s=read-host;2,4,6,8|%{if($i=$s.indexof("$_")+1){"$i,$_";break}};"-1,0"

```
* `$s=read-host` stores user input into `$s`
* `2,4,6,8|%{...}` runs what's inside `{}` for digits 2,4,6,and 8
* `$i=$s.indexof("$_")+1` sets `$i` to 1-based index of a digit in `$s` or `0` if the digit is not found
* `if( $i=... ){...}` the condition will be true when `$i` is not `0`
* `"$i,$_";break` outputs the index and the digit, and stops execution
* `"-1,0"` otherwise outputs `-1,0`
> 2 votes

# Answer
# C++11, 173 (including two new-line chars)

Here's the compressed version:

```
#include<iostream>
#include<string>
int main(){std::string s;std::cin>>s;for(char c:"2468")for(char&k:s)if(k==c){std::cout<<(&k-&s[0])<<','<<c;return 0;}std::cout<<"-1,8";}

```

Here's the readable version:

```
#include<iostream>
#include<string>
int main() {
    std::string s; // auto s = ""s; (since C++14: -3 characters)
    std::cin >> s;
    for (char c : "2468")
        for (char& k : s)
            if (k == c) {
                std::cout << (&k - &s[0]) << ',' << c;
                return 0;
            }
    std::cout << "-1,8";
}

```

---

Here's an older version:

**C++11, 175 (including two new-line chars)**

Here's the compressed version:

```
#include<iostream>
#include<string>
int main(){std::string s;std::cin>>s;for(char c:"2468"){int i=s.find(c);if(i<s.size()){std::cout<<i<<','<<c;return 0;}}std::cout<<"-1,8";}

```

Here's the readable version:

```
#include<iostream>
#include<string>
int main() {
    std::string s;
    std::cin >> s;
    for (char c : "2468") {
        int i = s.find(c);
        if (i < s.size()) {
            std::cout << i << ',' << c;
            return 0;
        }
    }
    std::cout << "-1,8";
}

```
> 2 votes

# Answer
## C, 80 character

```
main(){char a[81],b=strcspn((gets(a),a),"2468");printf("%d,%c",a[b]?b:-1,a[b]);}

```
> 1 votes

# Answer
## C# - 124

I'm a bit late to the party

```
void Main(string[]a){var x=a[0].Where(w=>char.IsDigit(w));var y=x.Min();Console.Write(y%2==0?a[0].IndexOf(y)+","+y:"-1,0");}

```
> 1 votes

# Answer
## Haskell, 79 characters

```
s&d=filter((==d).snd)$zip[-1..]$'0':s
main=interact$show.head.("24680">>=).(&)

```

This runs a little fast and loose with the output formatting:

```
& echo 523726 | runhaskell 16083-LowEven.hs
(1,'2')
& echo 583746 | runhaskell 16083-LowEven.hs
(4,'4')
& echo 53771 | runhaskell 16083-LowEven.hs
(-1,'0')
& echo _4___2 | runhaskell 16083-LowEven.hs
(5,'2')
& echo 25376 | runhaskell 16083-LowEven.hs
(0,'2')

```
> 0 votes

# Answer
# PowerShell: 145 103

> **Changes from original**
> Removed error quelch per comment from asker.

**Code:**

```
"$([array]::IndexOf(($s=(read-host)-split''|?{$_}),($x=$s|?{$_%2-eq0}|?{$_-gt0}|sort|select -f 1))),$x"

```

**Walkthrough:**

`"`...`"` Everything within the quotes will be included in the output.

`$(`...`)` Everything between the parenthesis will be treated as a commands, and the output of that code will be included instead of the commands themselves.

`[array]::IndexOf(`...`)` This is used to get the index of an element with the array. Its first parameter is the array object to be searched. The second parameter is the object to be found. This only outputs the index of the first matching element. I tried simply using an `IndexOf` method directly against `$s` (e.g.: `$s.IndexOf($x)`, but this fails for some reason I've yet to figure out - it claims the method doesn't exist on that object.

`(`...`)` Expression within the parenthesis will be the first parameter for `IndexOf`.

`$s=` $s will be a variable to store the user input.

`(read-host)-split''` Gets user input, and splits it into an array of characters.\`

`|?{$_}` Filters out extra empty array elements that are generated by `-split''`.

`,(`...`)` Expression within the parenthesis will be the second parameter for `IndexOf`.

`$x=` $s will be a variable to store the lowest even digit from the user input.

`$s|?{$_%2-eq0}` Pulls out the even numbers from $s.

`|?{$_-gt0}` Invalidates zero.

`|sort` Sorts the remaining objects, default order is ascending.

`|select -f 1` Picks the first object, which will by now be the lowest even digit.

`,$x` The above code will output the index of our lowest even digit. This adds a comma, and then outputs the digit itself.

**Notes:**

This is perhaps stretching rule #4 a little bit. If there is no even digit, the output will not include a second number.

Also, this will throw some non-terminating errors if the input includes non-numeric elements. The script will still run and give proper output, but you might want to set `$ErrorActionPreference` to `'SilentlyContinue'` before running it.
> 0 votes

# Answer
**vb.net (108c)**

```
Sub Main()
t=ReadLine()                          '12c
For Each c In "2468"                  '20c
i=t.IndexOf(c)                        '14c
If i>=0 Then Exit For                 '21c
Next                                  ' 4c
WriteLine("{0},{1}",i,If(i<0,0,t(i))) '37c
End Sub

```

Smells slightly cos it's exploiting VB's dynamic setting. **Option Explicit Off** and **Imports System.Console**.
> 0 votes

# Answer
**VB.net (193c) using LINQ**

This one is primarily utilising a LINQ query.

```
Dim r = From d In "2468" Group Join q In ReadLine.Select(Function(c, p) New With {.c = c, .i = p})
                              On d Equals q.c Into g = Group
                                        Skip While g.Count = 0 ' 138c
WriteLine(If(r.Any,r(0).g(0).i&","&r(0).g(0).c,"-1,0"))        '  55c

```
> 0 votes

# Answer
## Golf-Basic 84, 91 characters

```
:L1/L1_L2i`L1:fpart(L1,2)2_L1:SortA(L1)@cumSum(L1)=length(L1):Thend`-1#d`cumSum(L1):Endd`L1

```
* Make sure there's no `0` in the input (it's not even, who said it had to be odd?)
* Get input into L1 (List 1)
* Loop finding modulus of 2 for each value
* Sort L1 from smallest to highest
* Display the index (either -1 or the cumulative sum) and the smallest number
> 0 votes

# Answer
## Bourne shell (sh), 88 chars

```
(echo 88;sed 's/./\n&/g')|nl -v-1|awk '{print $2,$1}'|sed '/^[^2468]/d'|sort -n|head -n1

```

I thought I'd do a string-processing thing for fun. Technically it reads from stdin, but if you run it interactively it'll prompt the user for input since the keyboard is the default stdin stream. Uses basic shell commands to split up the input on lines, number them (using the ill-known `nl` utility), filter out lines fitting the criteria, sort them and output the lowest-digit one. Prints `88 -1` if no even digit was found.
> 0 votes

# Answer
# C++ - 223 ~~221~~ Characters:

```
#include<iostream>
#include<string>using namespace std;
int main(){int s=9;int p=-1;string x;cout<<"Enter characters: ";cin>>x;for(int i=0;i<x.length();i++){int n=x[i]-48;if(n%2==0&n<s){s=n;p=i;}}cout<<p<<", "<<s;return 0;}

```

Readable version:

```
#include<iostream>
#include<string>
using namespace std;

int main() {
    int s = 9;
    int p= - 1;
    string x;

    cout << "Enter characters: ";
    cin >> x;

    for (int i = 0; i < x.length(); i++) {
        int n = x[i] - 48;

        if (n % 2 == 0 & n < s) {
            s = n;
            p = i;
        }
    }

    cout << p << ", " << s;

    return 0;
}

```

It is long, but not as bad as Java.
> 0 votes

# Answer
# Javascript 93 characters

```
b=prompt();((r=b.match(/[2468]/g)||[-1]).sort(function(a,b){return a-b})[0])+","+b.indexOf(r)

```

Get all event numbers, sort the array and prints the first digit.
> 0 votes

# Answer
# Mathematica, 157 characters

```
f = Row@{If[(x = Min@#) == Infinity, -1, Position[#, x][[1, 1]]],
      ",", x} &[IntegerDigits@ToExpression@StringReplace[#,
       {"0" -> "1", x_?DigitQ :> x, _ -> "1"}] /. _?OddQ -> Infinity] &

inputs = {"25376", "523726", "583746", "53771", "_4___2"}

f /@ inputs // Column

```

> 1,2
>
> 2,2
>
> 5,4
>
> -1,∞
>
> 6,2
> 0 votes

# Answer
# Julia, 84

```
julia> f(a)=(for i=2:2:8;(k=search(a,'0'+i))==0||return(k,i);end;(-1,0))
julia> f(readline(STDIN))
583746
(5,4)
julia> f(readline(STDIN))
_4___2
(6,2)

```

Julia really needs a shorter way to get input for golfing. I counted the definition of `f` and one call to `f`. One based indexing is why the answers are different from the examples.
> 0 votes

# Answer
# JavaScript - 53 Characters

```
for(y=prompt(x=0);x<8&&(i=y.indexOf(x+=2))<0;);x+''+i

```

Reads input from prompt and outputs (to the console) the lowest even character then (without a delimiter) the first index of that character; if there are no non-zero even characters then it outputs `8-1`.
> 0 votes

# Answer
# C, 110 Characters

```
i,f,r,c,m=9;main(){while(r=getchar()>31){c=r-48;i++;if(c>=0&&~c&1&&c<m)m=c,f=i;}printf("%i,%i",m>8?-1:f-1,m);}

```

ungolfed:

```
i,f,r,c,m=9;
main(){
  while(r=getchar()>31){
    c=r-48;
    i++;
    if(c>=0&&~c&1&&c<m) m=c,f=i;
  }
  printf("%i,%i",m>8?-1:f-1,m);
}

```
> 0 votes

# Answer
# Javascript, 69

```
a=prompt(),b=[-1,9];for(i in a)if(+a[i]%2==0&&+a[i]<b[1])b=[+i,+a[i]]

```

Reads the value, iterates through each character, if the number representation mod 2 equals 0 and the number is less that what is already stored in `b`, replace the values in `b`
> 0 votes

# Answer
# Rebol, 69

```
s: input for n 2 8 2[if f: find s n[print[index? f f/1]q]]print[-1 0]

```
> 0 votes

# Answer
# Ruby 55

```
p gets.chars.sort*''=~/[2468]/?[$_.index($&),$&]:[-1,0]

```
> 0 votes

# Answer
## JavaScript/jQuery 149

Golfed

```
$(function(){
var i=prompt(),k=-1,n=0,c,e="2468";
while(n<i.length){c=i.charAt(n);k=e.indexOf(c);if(k>=0){break;}n++;}$('#d').append(k+","+n);
});

```

Full source

```
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
<div id="d"></div>
<script type="text/javascript">
$(function(){
var i=prompt();
var k=-1;
var n=0;
var c;
var e="2468";
while(n<i.length){
c=i.charAt(n);
k=e.indexOf(c);
if(k>=0){
break;
}
n++;
}
$('#d').append(k+","+n);
});
</script>
</body>
</html>

```
> 0 votes

---
Tags: code-golf
---


title: When is my piversary?

text:
# Question
Title: When is my piversary?
Since I want to celebrate this definitely not nerdy event, your job is to calculate the piversary (pi-anniversary) of a given date.

### Input

Your code has to have a possibilty to input a date in the format `DD/MM/YYYY`. You can expect, that the input is valid and the year is `0000<YYYY<9996`.

### Output

You have to release two dates, the date in Pi months and the date in Pi years.

### Rules

* If your language hasn't a build in Pi, you have to make a variable which will be exact enough to calculate the dates, but it is not allowed to calculate the days separately and use fix numbers.
* You have to take care, that the months have different amount of days, but you don't have to care about leap years (only if you want).
* If you calculate the date, you have to add the three years/months first and then the left part in rounded days.
* Your code has to accept **any** valid date and should be able to handle edge cases like `30/12/2000`

Example:

```
Input: 12/04/2010

Calculate monthly piversary:
date +  3 months = 12/07/2010
date + (31*(Pi-3)) = date + 4.39 = date + 4 = 16/07/2010 //31 because July has 31 days

Calculate yearly piversary:
date + 3 years = 12/04/2013
date + (365*(Pi-3)) = date + 52 = 03/06/2013

Output:
16/07/2010,03/06/2013

```

**May the shortest code win.**

# Answer
> 3 votes
## Mathematica, ~~152~~ 134 bytes

```
f[i_]:=DateList@{i,{d="Day",m="Month",y="Year"}}~DatePlus~{{3,#},{Round[#2*(Pi-3.)],d}}~DateString~{d,"/",m,"/",y}&@@@{{m,31},{y,365}}

```

Ungolfed

```
f[i_] :=
 DateString[
    DatePlus[
     DateList@{i,{d="Day",m="Month",y="Year"}},
     {{3, #}, {Round[#2*(Pi - 3.)], d}}
    ],
    {d, "/", m, "/", y}
 ] & @@@ {{m, 31}, {y, 365}}

```

This does handle leap years. It's also horribly long.

# Answer
> 1 votes
# MATLAB: 141 ~~157, 169~~

```
o='DD/mm/YY'
d=datenum(x,o)
f=@(s,v) datestr(addtodate(addtodate(d,3,s),(pi-3)*v,'day'),o)
f('year',365)
f('month',eomday(year(d),month(d)))

```

Quite long and straightforward. It assumes the input to be in `x`.

---

Here is a version that is a few chars longer for those without the financial toolbox:

```
o='DD/mm/YY'
d=datenum(x,o)
[y,m]=datevec(d)
f=@(s,v) datestr(addtodate(addtodate(d,3,s),(pi-3)*v,'day'),o)
f('year',365)
f('month',eomday(y,m))

```

# Answer
> 1 votes
## Groovy - 297 chars

Uses Joda Time. Does not handle leap years.

Golfed:

```
@Grab(group='joda-time', module='joda-time', version='2.3')
f=org.joda.time.format.DateTimeFormat.forPattern("dd/MM/yyyy")
t=f.parseDateTime(args[0])
p="plusDays"
m="Month"
println f.print(t."plus${m}s"(3)."$p"((t."dayOf$m"().maximumValue*(Math.PI-3)) as int))+","+f.print(t.plusYears(3)."$p"(52))

```

Sample run:

```
$ groovy Pi.groovy 12/04/2010
16/07/2010,03/06/2013

$ groovy Pi.groovy 30/12/2000
03/04/2001,20/02/2004

```

Ungolfed:

```
@Grab(group='joda-time', module='joda-time', version='2.3')

f = org.joda.time.format.DateTimeFormat.forPattern("dd/MM/yyyy")

t = f.parseDateTime(args[0])

println f.print(t.plusMonths(3).plusDays((t.dayOfMonth().maximumValue*(Math.PI-3)) as int))
        + "," +
        f.print(t.plusYears(3).plusDays(52))

```

---
Tags: code-golf, date, pi
---