Why? To please the rich programmer! Have you ever wanted to ask the compiler "Why?" Most of us have been frustrated when the code isn't working as it should. Mathworks has therefore implemented a nice little function, why, that answers the question. To give a few examples from MATLAB:

why
The programmer suggested it.

why
To fool the tall good and smart system manager.

why(2)
You insisted on it.

why(46)
Bill insisted on it.

Your task is to implement the why function in your language. The function should work with and without an input argument (alternatively use input 0 or -1). The function must be named why (or, writing why(n) in STDIN should result in the appropriate string being printed).

If no argument is given, or the argument is zero or negative, the output string should be a random, valid phrase.  So, there should be a function why, why(), why(0) or why(-1) that returns a random sentence.

If an input argument, n is given (function argument, not STDIN), the output should be the n'th string (defined below). So, why(1) should always output (print/display) the same result.

The sentences are built up as follows (Type 1, Type 2 and Special). All sentences end with !.

"Person" "ending" !
"Verb" "adjective" "Person" !
A list of special cases

The list of persons:

Stewie
Peter
Homer
The programmer
The system manager
You

The list of endings:

suggested it
insisted on it
did it

The list of verbs are:

To fool
To satisfy
To please

The list of adjectives:

the smart
the bald
the tall
the rich
the stupid

The list of special cases:

How should I know?
Stop asking!
Don't ask!

The way to select a numbered one is:

Type of sentences:

Odd number => Type 1
Even number => Type 2
n % 7 = 0 => Type 3 (% is the modulus operator)

Names: The nth name is defined using modulus (%).

n = 1:   1 % 7  => Stewie
n = 2:   2 % 7  => Peter
...
n = 6:   6 % 7  => You
n = 7:   7 % 7  => How should I know?
n = 11:  11 % 7 => The programmer
n = 14:  14 % 7 => Stop asking!
n = 21:  21 % 7 => Don't ask!

Endings: The nth ending is also defined using the modulus. Assume the endings (1, 2 and 3) are listed like (1 2 2 3). As the numbers are always odd, use ((n+1)/2 % 4)

n = 1:    ((1+1)/2 % 4)  => suggested it
n = 3:    ((3+1)/2 % 4)  => insisted on it
n = 13:   ((13+1)/2 % 4) => did it

Adjectives: The nth adjective is defined using the modulus. As the numbers are always even, use: (n % 10)/2

n = 2:   (2 % 10)/2 => Smart
n = 6:   (6 % 10)/2 => The tall
...

Verbs: The nth verb is also defined using the modulus. Assume the verbs (1, 2 and 3) are listed like (1 2 2 3) As the numbers are always even for verbs, use (n % 8) / 2

n = 2:   (2 % 8)/2 => To fool
n = 4:   (4 % 8)/2 => To satisfy
n = 6:   (6 % 8)/2 => To satisfy
n = 8:   (8 % 8)/2 => To please

Now, the way to create a random one should be fairly simple, simply select a random n.

Some examples:

why
You suggested it!

why
To fool the tall Homer!

why
Don't ask!

why(1)
Stewie suggested it!

why(14)
Stop asking!

why(8)
To please the rich Stewie!

Standard code golf rules apply. A winner will be selected one week from the day the challenge was posted.

JavaScript (ES6) 345

Not sure about the numbers, but here is my attempt.

Test running the snippet below in an EcmaScript compliant browser.

why=n=>(n<1?n=Math.random()*840|0:0,s="suggested,insisted on,did,fool,satisfy,please,stupid,smart,bald,tall,rich,Don't ask!,How should I know?,Stop asking!,Stewie,Peter,Homer,programmer,system manager,You".split`,`,n%7?(p=s[n%7+13],n&1?(p>'a'?'The ':'')+p+` ${s['2011'[-~n/2%4]]} it!`:`To ${s['5344'[n%8/2]]} the ${s[n/2%5+6]} ${p}!`):s[11+n%3])

for(o='',i=0;++i<1e3;)o+=i+':'+why(i)+'\n';O.innerHTML=o

function test() { R.innerHTML=why(+I.value) }

// Less golfed

WHY=n=>(
  n=n<1?Math.random()*999|0:n,
  s=["suggested", "insisted on", "did", "fool", "satisfy", "please",
     "stupid", "smart", "bald", "tall", "rich",
     "Don't ask!", "How should I know?", "Stop asking!",
     "Stewie", "Peter", "Homer", "programmer", "system manager", "You"],
  n%7
    ? ( p=s[n%7+13],
        n&1
        ? (p>'a'?'The ':'')+p+` ${s['2011'[-~n/2%4]]} it!`
        : `To ${s['5344'[n%8/2]]} the ${s[n/2%5+6]} ${p}!`)
    : s[11+n%3]
)
#O { height:300px; width:50%; overflow:auto }
#I { width:2em }
Why(<input id=I>)<button onclick=test()>-></button>


RPN calculator without pointers Me and some other students were at a bar discussing programming languages, in particular the C programming language. At some point a first year student said he didn't need no damn pointers. Another student said that he couldn't use arrays either since "they're basically pointers".

This led to a programming challenge:
Implement a reverse polish notation calculator in C without using arrays and pointers.

Description

You must implement a RPN calculator that

operates on integers,
supports addition (+),
supports multiplication (*).

Your implementation

must not use pointers or arrays
you may use structs
the input is read from stdin
your lexer may use pointers and arrays (but it shouldn't be needed)
when EOF is read then print the top of the stack
the behavior can be as undefined as you want for malformed input
should be in a language sufficiently c-like that the "no-pointers and no-arrays" restriction has a sensible interpretation (please elaborate if you think people may not get it)

The lexer could have a signature a la thisNote: this is not taken from my own code. Please tell me if there's an error or it looks unreasonable

typedef enum {
  val,
  op,
  eof
} TYPE;

typedef enum {
  add,
  mul
} OPERATION;

typedef struct {
  TYPE type;
  union {
    int val;
    OPERATION op;
  } dat;
} token;

token next();

A solution using a stack with push() and pop() could look something like this:

token t;
while ((t = next()).type != eof) {
  switch (t.type) {
    case val:
      push(t.dat.val);
    case op:
      switch (t.dat.op) {
        case add:
          int v1 = pop();
          int v2 = pop();
          push(v1+v2);
        case mult:
          int v1 = pop();
          int v2 = pop();
          push(v1*v2);
      }
    case eof:
      printf("Result: %d\n", pop());
  }
}

Other languages than C are also accepted, but the constraints should be comparable. It is hard to state the constraints in a way that fits all languages, but something like »all used data structures must have fixed size and fixed "depth"«. If there's any doubt please ask in the comments.

I have a solution that I can post. After cleaning up the code a bit. I wrote it the morning after while hungover.

This is a stand-alone C version, it doesnt require any external lexer. It works recursivly, like ratchet freaks solution.

All characters that are not +, *, - or numbers are treated as spaces. A - is treated as a space if it is not directly followed by a number.

#include <stdio.h>

int rpn(int n1, int n2) {
        int c, sign = 1, skip = 0;
        if(n1 < 0) sign = -1;
        do {
                c = getchar();
                if(c == '+') return n1+n2;
                if(c == '*') return n1*n2;
                if(c >= 48 && c <= 57) {
                        if(!skip) n1 = n1 * 10 + sign * (c - 48);
                        else n1 = rpn(sign * (c - 48), n1);
                } else {
                        skip = 1;
                        sign = 1;
                }
                if(c == '-') sign = -1;
        } while(c != EOF);
        return n1;
}

void main() {
        printf("%d\n", rpn(0, 0));
}


Minimally destroy CGCC in Game of Life Inspiration
Conway's Game of Life is a well known cellular automaton "played" on an infinite grid, filled with cells that are either alive or dead. Once given an initial state, the board evolves according to rules indefinitely. Those rules are:

Any live cell with 2 or 3 living neighbours (the 8 cells immediately around it) lives to the next state
Any dead cell with exactly 3 living neighbours becomes a living cell
Any other cell becomes a dead cell

Game of Life is known for having simple rules yet structures can quickly become chaotic with minimal change.
Consider the following initial state:

In 5 generations, this reaches this configuration, which is a period 2 oscillator. However, by adding in 8 live cells next to it:

we end up with a completely empty board after 54 generations.

Now, consider instead the following initial state:

That is, CGCC made up of living cells. Each letter is in a \$4\times6\$ bounding box, with a single empty column of cells between boxes, for a total bounding box of \$19\times6\$. This is a zoomed-in version.
After 256 generations, the board looks like

From this point, no meaningful change will happen: there are 2 oscillators which do not interact with anything else, and the rest are still lifes.
Your task is to "destroy" this by adding in living cells around the initial configuration.
You will start with the CGCC initial state, as shown above. You will add \$n\$ living cells to the board. Those cells must be outside of the \$19\times6\$ bounding box of the CGCC (but may touch against the outside). When this new initial state (with your added cells) is run, it must eventually result in an empty board.
Note that the board is considered infinite, so if your configuration produces any spaceships, it is not a valid configuration.
Your score is equal to \$n\$. The lowest score wins, ties are broken by the fewest generations required to empty the board. Please provide either a testing environment to demonstrate your solution, or provide a video/gif of it running.
Here is a pre-filled CGCC pattern in a GoL simulator

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

               X

Image of initial state

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

Try this pattern on copy.sh!
Slow animated gif


Help me untangle these wires! My wires are all tangled!

Isn't it annoying when wires get all tangled up? Well, that just happened to me, so I'd like to to help me untangle them! For your convenience, I've disconnected them all from the device, but they're all still connected to the outlet. Your challenge is to figure out how to untangle them!

Input

The input will consist of spaces, pipes, and Xs (both cases). The input will look something like this:

| | | |
 X  | |
| |  x
|  X  |
| | | |

A capital X means that the left wire crosses over the right wire, and a lowercase x means the opposite. The first and last lines will always be | | | |.... You may take the input as a comma separated string, an array of strings, etc. The format is not strict, as long as it makes sense and doesn't contain any extra information.

Output

For this challenge, not only do I need to know how long I will take, I need to know exactly what to do. So, output a list of integer pairs with the character R or L, case insensitive, representing which two wires to untangle and which way (R means right over left, and vice versa for L). You need to tell me which way to uncross them; I can't figure that out myself. Output is pretty flexible too, as long as you output all of the integer pairs + character in the correct order and you don't output any extra nonsense text (brackets, commas, etc. are fine). The wires can be zero or one indexed, but the index must start from the left. Note that you must untangle from the bottom, not the top. Output style must be consistent, and please specify how you are outputting if it is not obvious. The case of the character doesn't have be consistent, if that helps at all.

Sample Output

For the example input above, the output would be something like:

2 3 R
3 4 L
1 2 R

The output format here is a newline separated list of space separated values. This is 1-indexed.

Further specifications

It is valid to have X and x stacked vertically over each other in either order. Since I'm lazy, I don't want to switch wires around unnecessarily, so don't output anything for these cases; if I find that, I'll just pull the wires gently to get them straight.

It is also valid to have multiple X and x stacked vertically, and as long as neither wire is involved in other crossings, I don't want any extra moves (because I'm lazy). Thus, if the characters X X x X x x show up in a column without any other crossings, the output should still be blank!

In case this isn't clear, R eliminates X and L eliminates x.

There could be two wire crossings in the same row, in which case the order of these two swaps does not matter. You will never get something like |  X X  | (this does not make sense because it implies that the middle wire is being crossed over the wires on both its left and its right).

There aren't always crossings...

The input could be a single pipe. However, the input will never be blank.

Shortest valid solution wins on December 20th!

More Examples

As I promised:

Example 1

Input

| | | | | |
| |  X   x
 X  |  x  |
|  x  |  X
 X   X  | |
| | | | | |

Output

1 2 R
3 4 R
2 3 L
5 6 R
1 2 R
4 5 L
3 4 R
5 6 L

Example 2

Input

| | |
 X  |
|  x
| | |
|  X
|  x
| | |

Output

2 3 L
1 2 R

Example 3

Input

|

Output is blank. Yes, you have to deal with this case.

Example 4

Input

| |
 X
 x
 X
 x
 X
 x
 X
 x
 X
 x
| |

Output is blank. Just for fun :).

Example 5

Input

| |
 X
 X
 x
 X
 x
 x
| |

Output is still blank...

Pyth - 26 25 bytes
Very straightforward, maybe I can golf the filtering.
fhhT_m+hB/xrdZ\x2@"RL"}\x

Try it online here.


Equal out bracket types Based on  THIS question.

Given a string, replace each bracket ()[]{}<> with a bracket of the appropriate type so that the brackets match, and the nested brackets cycle as follows:

Outermost ones are ()
Directly inside of () should be []
Directly inside of [] should be {}
Directly inside of {} should be <>
Directly inside of <> will be () again (cycles)

All non-bracket chars must remain exactly as they are. Open brackets may only be replaced with open brackets of some type, and close brackets with close brackets.

The input will always make this possible. This means its brackets matched correctly if their type is ignored. So, {ab<)c] is a valid input, but ab)(cd or ab((cd are not.

Examples:

2#jd {¤>. = 2#jd (¤).
abcdef    = abcdef
(3×5+(4-1)) = (3×5+[4-1])
<<<>><<>><<<<<<>>>>>>> = ([{}][{}][{<([{}])>}])

The use of native transforming of input this way (auto syntax of language) is not allowed.

As always: shortest code wins.


Goodness, it's covered in tabs! Space indentation users, unite! We must fight against all the lowly tab users!
Your mission (should you choose to accept it) is to write a program or function that takes in two arguments:

A string: This is the input.
A positive integer: This the number of spaces per tab.

You must go through every line of the string and replace every tab used for indentation with the given number of spaces, and every tab not used for indentation (e.g. in the middle of a line) with one space.
Note that lines such as \t \tabc are undefined behavior; they were inserted by the evil tab users to complicate your programs.
According to the Tabs Must Die Society, your program must be as short as possible to avoid detection by the evil tab users.
Example
\t is used to represent tabs here.
Input string:
a
\t\tb\tc
d

Input number:
4

Output:
a
        b c
d

The middle line was indented by 8 spaces, 4 per tab (since the given number was 4).
Input string:
\ta\t\tb

Input number:
4

Output:
    a  b

NOTE: This is not a duplicate of the tab expansion challenge; it requires a very different input format and slightly different requirements.

K5, 53 45 bytes

{{,/(b+a&~b:x*&\a:9=y){$[x;x#" ";y]}'y}[x]'y}

In action:

  {{,/(b+a&~b:x*&\a:9=y){$[x;x#" ";y]}'y}[x]'y}[4;(,"a";"\t\tb\tc";,"d")]
(,"a"
 "        b c"
 ,"d")

I just want the record to show that this question is morally reprehensible.


all non-empty sublists partitionings of a list I had to write a code for finding all non-empty sublists partitionings of a list:

def f(s):
    if s:
        for j in range(1,len(s)+1):
            for p in f(s[j:]):
                yield [s[:j]]+p
    else:
        yield []

I managed to shorten it (for Python 3.4+) to:

def f(s, p=[]):
    if s:
        for j in range(1,len(s)+1):
            yield from f(s[j:],p+[s[:j]])
    else:
        yield p

using yield from and an accumulator argument p (prefix).

Any suggestions on how to shorten it even more?

Example output:

>>> for p in f([1,2,3,4]): print(p)
...
[[1], [2], [3], [4]]
[[1], [2], [3, 4]]
[[1], [2, 3], [4]]
[[1], [2, 3, 4]]
[[1, 2], [3], [4]]
[[1, 2], [3, 4]]
[[1, 2, 3], [4]]
[[1, 2, 3, 4]]
>>>

66 bytes
p=lambda l:[q+[l[i:]]for i in range(len(l))for q in p(l[:i])]or[l]

If the last part is changed from [l] to [[]], then it can also be used with tuples or strings, in addition to lists.


Anagramming Stack Exchange question titles into programs Stack Exchange currently has 134 question and answer sites. This includes all beta sites (such as PPCG) but not Area 51 proposals nor any meta sites, except for the "mother meta".
To answer this question, choose one of those sites and write a program where every line of code is an anagram of the title of a different question on that site. Any questions from that site may be used as long as they have not been deleted, and were asked before this question.
The title of a question includes all characters that appear in the Title textbox when the edit link is clicked below a question, be they whitespace, mathjax formatting, crazy Unicode characters, whatever. (You can use the Stack Exchange API if you want to query a bunch of question titles at a time.)
The program you write must output the string that reliably appears at the top of every Stack Exchange page:
Questions Tags Users Badges Unanswered Ask Question

This exact text, plus an optional trailing newline, is the only thing your program should output. There is no input. The output should go to stdout or, if that's not possible, a similar alternative.
Since doing this with only anagrams of question titles may be kind of tricky, you may optionally add one character of your choice to each line in your program, in any column. Not all lines need to have an extra character and it does not have to be the same character across lines. The character may be anything except for a line terminator. The characters in the line minus this one new character should still be a perfect anagram of a question title.
Scoring
Your score is (number of lines with no added character) + 2 * (number of lines with an added character). The lowest score wins. In case of ties the earlier answer wins.
Details

You must provide links to all the questions you have used the titles from.

You may choose the same Stack Exchange site as someone else though you are encouraged to choose unused sites, just for some variety.

If a question you used gets deleted before the winner is chosen, your submission will be invalid, so it's best to choose well established questions.

If titles are edited on some of your questions then your submission is still valid as long as the edit history shows that your titles were correct when you posted your answer.

Comments in your program are fine.

Editing question titles to suit your needs is very bad form.

Golfscript, 3 lines with no added characters

"Questions Tags Users Badge"'exception SLSATE[HY000][1049]eymfny incnue while pn chma afte intallin FOSBundl'or
"s Unanswered Ask "'Reoccurring error The current idetity(NT THORITY\NETWORK SERVICE)oe ot have it cc toC:\WINDOWS\Microsoft.NET\Framewor\v2.0.50727\Tempary ASP.NET Files'or
"Question""D he 'S'  SL stand f standard or strctured?"or

I hit StackOverflow, since it probably had the most (useful) posts. A lot of Qs could be found in jQuery and SQL.

Bibliography:

exception "SQLSTATE[HY000] [1049] Base 'symfony' inconnue" while updating schema after installing FOSUserBundle
Reoccurring error "The current identity (NT AUTHORITY\NETWORK SERVICE) does not have write access to 'C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files'"
Does the 'S' in SQL stand for "standard" or "structured"?

Uses two strings each line, and takes the first one with or. I don't know any proper Golfscript, but I tested it here.

It's possible to get the necessary quotes in two lines, but you'll need a language that lets you dump chars.


Write the prettiest bytebeat composition Bytebeat is a style of music one can compose by writing a simple C program that's output is piped to aplay or /dev/dsp.

main(t){for(;;t++)putchar(((t<<1)^((t<<1)+(t>>7)&t>>12))|t>>(4-(1^7&(t>>19)))|t>>7);}

There is a good deal of information on the bytebeat site, a javascript implementation, and more demos and example compositions in this thread.

Very simple rules : Try to write a pretty sounding composition.  Most up votes wins since that's obviously subjective, although not that subjective considering the usual results.

(Signed 16-bit little endian, 8000Hz mono (--format=S16_LE))

Music

Much better than before! (although it's quite long)

main(t){for(;;t++)putchar(((7&(((t>>17)+1)>>2)+((t>>10)&1+2*(t>>18&1))*(("23468643"[7&t>>12]-48)+(3&t>>11))+((3&t>>17)>0)*(3&t>>9)*!(1&t>>10)*(((2+t>>10&3)^(2+t>>11&3))))*t*"@06+"[3&t>>15]/32));}

(You can listen this at here)

I wrote this, but even I don't know how some part works, like >0 and (especially) the first 7&.

Change for loop to for(;!(t>>22);t++)... to listen it 'once'. I don't know whether it "loops" exactly the same way, however.

Melody (base of above music)

I love this melody I made (C-G-A-F ftw), but it's too 'plain'...

main(t){for(;;t++)putchar(((t>>10)&1)*(t*("23468643"[7&t>>12]-48)+t*(3&t>>11))*"@06+"[3&t>>15]/32);}

Simple music (which I made before)

main(t){for(;;t++)putchar(t*(3&t>>11)+(t&t>>11)*4*!((t>>11)%3));}


Do n and n^3 have the same set of digits? Given a number n (0 <= n <= 2642245), check if n and n3 have the same set of digits, and output a truthy or falsey value accordingly.

For example, let's check the number 100.

1003 is 1000000.

The set of digits in 100 is {0, 1}.

The set of digits in 1000000 is {0, 1}.

Therefore, 100 should give a truthy value.

Test cases

0 -> True
1 -> True
10 -> True
107624 -> True
251894 -> True
251895 -> False
102343 -> False

Remember, this is code-golf, so the code with the fewest bytes wins.

OEIS A029795

Python 3, 36 32 bytes
lambda x:{*str(x)}=={*str(x**3)}

I think this only works in Python 3.5 and later.
Four bytes have gone, thanks to Copper.


Write a Polish notation interpreter, then change it to RPN in shortest number of chars Write a program to convert Polish prefix notation to infix notation, then change it to an RPN-to-infix converter in the shortest number of chars.

Your score is 100 minus the number of characters changed, added and deleted.

Don't write one PPN and one RPN function, then do something like:
"I changed rpn(raw_input()) to ppn(raw_input())"
No ingenious variations of the above rule such as

def f(s, rpn = False):
if rpn:
    #rpn logic here
else:
    #ppn logic here

In short, your program must only implement one kind of logic, not both.
It must not be possible to only delete characters from the original program and so obtain a program which converts RPN to infix.
Try not to use inbuilt libraries.
Accept input from STDIN or from a file.
Note that program length itself does not matter.
Have fun.

Python - 100!

I'm pretty sure I've met all the criteria. I don't think its possible to make it more identical, without just having a big ol' if block, which would violate the criteria. Using cmp(), and what @PeterTaylor pointed out you can determine the direction you need to go. Rather than use an if/then which would violate the spirit of the challenge, this get the position of the first number and operator and compares those. While the list comprehensions use an if this is just to safely filter the indices and doesn't direct help determine if we are doing forward or reverse polish notation, but this does bend the rules a bit.

Rule-bending program: Both prefix and reverse Polish notation

s = raw_input().strip()                          # Get input
ops = "*-+/^"                                    # A string of operators
num="0123456789"                                 # A string of numbers
p_num= min([s.index(n) for n in num if n in s])  # Find the first number
p_op = min([s.index(o) for o in ops if o in s])  # Find the first operator
                                                 # We use the above 2 lines to determine what
                                                 #   direction we are going on line '2' below

                          #  Just like the original below
s=s.split()                  #  1. Split the input
d = cmp(p_op,p_num)          #  2. Set the direction... depending on what comes first!
                             #     If the first number is before the operator, go forwards
                             #     If the first number is after the operator, go backwards
def f(i):                    #  3. Define our recursive function
 if s[i] in operators:       #  4. If its an operator...
  a = f(i+d)                 #  5.  Recursively get the first argument
  b = f(i+d)                 #  6.  By the time the above is resolved the array is modified
                             #     So we can use the same offset
  c = [a,b,a]                #  7. Mash these in a padded array so the trick below works
  inf = c[d-1]+s.pop(i)+c[d] #  8. Lets put these in order... BASED ON d!!
                             #      And remove the operator from the array
  return "("+inf+")"         #  9. Return the infix version of this operator
 return s.pop(i)             # 10. Just a number?, pop and return.
print f([0,-1,42][d-1])      # 11. Call the recursive start case from the head of the array
                             #    i.e element 0, or just 0.
                             #    Print the final infix

If the above is too rule bendy, here is the code I had before that scored 99.

Original program: Polish prefix notation

s = raw_input().split(" ")   #  1. Get input
d = 1                         # 2. Set the direction to forwards
                             #     If the first number is before the operator, go forwards
                             #     If the first number is after the operator, go backwards
def f(i):                    #  3. Define our recursive function
 if s[i] in operators:       #  4. If its an operator...
  a = f(i+d)                 #  5.  Recursively get the first argument
  b = f(i+d)                 #  6.  By the time the above is resolved the array is modified
                             #     So we can use the same offset
  c = [a,b,a]                #  7. Mash these in a padded array so the trick below works
  inf = c[d-1]+s.pop(i)+c[d] #  8. Lets put these in order... BASED ON d!!
                             #      And remove the operator from the array
  return "("+inf+")"         #  9. Return the infix version of this operator
 return s.pop(i)             # 10. Just a number?, pop and return.
print f([0,-1,42][d-1])      # 11. Call the recursive start case from the head of the array
                             #    i.e element 0, or just 0.
                             #    Print the final infix

Modified to produce: Reverse polish notation

s = raw_input().split(" ")
d = -1                        # 2. Set the direction to backwards
def f(i):
 if s[i] in "*-+/^":
  a = f(i+d)
  b = f(i+d)
  c = [a,b,a]
  inf = c[d-1]+s.pop(i)+c[d]
  return "("+inf+")"
 return s.pop(i)
print f([0,-1,42][d-1])       #11. No change, but this pulls the second last (-2) element
                              #    Hence, why we bump it to 3 elements long.

Differences (not including the comments):

Line 2: 1 char, added - to change from +1 to -1

For a total of 1 character changed, which in Polish notation, gives

- 100 1 = 99


Compare two poker hands Challenge:

Given two five-card hands, determine which one wins by the standard ranking of poker hands.

Input:

Ten cards separated by spaces from stdin or as command line arguments, whichever you prefer. The first five cards are Player 1's hand while the last five are Player 2's hand. Each card will be a two letter string of the form RS where R is rank and S is suit. The ranks range from 2-9, T for ten, and J, Q, K, and A for Jack, Queen, King, and Ace respectively. The suits are H, D, C, S for Hearts, Diamonds, Clubs, and Spades respectively. You must output the number of the player that wins: '1' or '2'.

Examples of Cards:

AS - the Ace of Spades
QD - the Queen of Diamonds
2C - the Two of Clubs
TH - the Ten of Hearts

Input to Output Examples:

5H 5C 6S 7S KD 2C 3S 8S 8D TD -> 2

Explanation: Player 1 has a Pair of Fives while Player 2 has a Pair of Eights.

5D 8C 9S JS AC 2C 5C 7D 8S QH -> 1

Explanation: Neither Player has anything special, but Player 1's high card is an Ace while Player 2's high card is a Queen.

2D 9C AS AH AC 3D 6D 7D TD QD -> 2

Explanation: Player 1 has Three Aces, Player 2 has a Flush of Diamonds.

4D 6S 9H QH QC 3D 6D 7H QD QS -> 1

Explanation: Both players have a Pair of Queens, but Player 1's second highest card is a Nine whereas Player 2's is a Seven.

Rules and Clarifications:

Refer to the standard ranking of poker hands for the details of comparing hands.
You may assume that there are no repeated cards in each pair of hands.
You may assume that there is a definite winner in each case.
Suit does not factor into the ranking of a hand. For example, two royal flushes of different suits are equal (therefore any input where both players have a royal flush is invalid by the preceding rule).
As this is code golf, the shortest answer wins.

Notes:

Related to this question and this one.
Based on Project Euler Problem 54

Python - 774 722 707 698 685 chars
import sys
t,q,e,u='--23456789TJQKA','SDCH',enumerate,len
_=lambda c,i=0:chr(97+c[i])
def j(s):
 v,g,l=[0]*15,[0]*4,''
 for c in s:
  r,s=c[0],c[1];v[t.find(r)]+=1;g[q.find(s)]+=1
 c,h,k,m,f=0,0,[0,0,[],[],[]],0,0
 for x,i in e(v):
  for b in[2,3,4]:
   if i==b:k[b]+=[x]
 v[1]=v[14]
 for x,i in e(v):
  if i:
   c+=1
   if c==5:m,h=1,x
   if i==1:l+=_([x])
  else:c=0
 f,l,d=max(g)//5*2,l[::-1],'';z=f+m
 if z==3:d='z'+l
 if k[4]:d='y'+_(k[4])+l
 if k[2] and k[3]:d='x'+_(k[3])+_(k[2])
 if z==2:d='w'+l
 if z==1:d='v'+_([h])
 if k[3]:d='u'+_(k[3])+l
 if u(k[2])>1:d='t'+_(k[2],1)+_(k[2])+l
 if u(k[2])==1>u(k[3]):d='s'+_(k[2])+l
 return d or l
p=sys.argv
print(1+(j(p[1:6])<j(p[6:])))

I chose to generate a string for each hand that represents it, starting with a character for the type of hand, followed by characters describing the particular variation of the type (for example, which card did you just have 4 of?), followed by the values of the remaining cards in case of a tie (if both players have the same double pair, the 5th card will have to decide who wins). I've tested it quite extensively, but I don't actually play poker, so I hope I got it right. Also, I know it's not fully golfed yet, I can probably shave off a few dozen chars later on.


The number of possible numeric outcomes of parenthesizations of 2^2^...^2 Consider an expression 2^2^...^2 with n operators ^. Operator ^ means exponentiation ("to the power of"). Assume that it has no default assosiativity, so the expression needs to be fully parenthesized to become unambiguous. The number of ways to parenthesize the expression are given by Catalan numbers C_n=(2n)!/(n+1)!/n!.

Sometimes different parenthesizations give the same numeric outcome, for example (2^2)^(2^2)=((2^2)^2)^2, so the number of different possible numeric outcomes for a given n is less than C_n for all n>1. The sequence starts as 1, 1, 2, 4, 8, ... as opposed to Catalan numbers 1, 2, 5, 14, 42, ...

The problem is to write the fastest program (or function) that accepts n as an input and returns the number of different possible numeric outcomes of the expression 2^2^...^2 with n operators ^. The performance should not significantly deteriorate as n grows, so direct calculation of high power towers is probably a bad idea.

Python 2.7

This approach takes advantage of the following considerations:

Any integer can be represented as a sum of powers of two.  The exponents in the powers of two can also be represented as powers of two.  For example:

8 = 2^3 = 2^(2^1 + 2^0) = 2^(2^(2^0) + 2^0)

These expressions that we end up with can be represented as sets of sets (in Python, I used the built-in frozenset):

0 becomes the empty set {}.
2^a becomes the set containing the set representing a.  E.g.: 1 = 2^0 -> {{}} and 2 = 2^(2^0) -> {{{}}}.
a+b becomes the concatenation of the sets representing a and b.  E.g., 3 = 2^(2^0) + 2^0 -> {{{}},{}}

It turns out that expressions of the form 2^2^...^2 can easily be transformed into their unique set representation, even when the numerical value is much too large to be stored as an integer.

For n=20, this runs in 8.7s on CPython 2.7.5 on my machine (a bit slower in Python 3 and much slower in PyPy):

"""Analyze the expressions given by parenthesizations of 2^2^...^2.

Set representation:  s is a set of sets which represents an integer n.  n is
  given by the sum of all 2^m for the numbers m represented by the sets
  contained in s.  The empty set stands for the value 0.  Each number has
  exactly one set representation.

  In Python, frozensets are used for set representation.

  Definition in Python code:
      def numeric_value(s):
          n = sum(2**numeric_value(t) for t in s)
          return n"""

import itertools

def single_arg_memoize(func):
    """Fast memoization decorator for a function taking a single argument.

    The metadata of <func> is *not* preserved."""

    class Cache(dict):
        def __missing__(self, key):
            self[key] = result = func(key)
            return result
    return Cache().__getitem__

def count_results(num_exponentiations):
    """Return the number of results given by parenthesizations of 2^2^...^2."""
    return len(get_results(num_exponentiations))

@single_arg_memoize
def get_results(num_exponentiations):
    """Return a set of all results given by parenthesizations of 2^2^...^2.

    <num_exponentiations> is the number of exponentiation operators in the
    parenthesized expressions.

    The result of each parenthesized expression is given as a set.  The
    expression evaluates to 2^(2^n), where n is the number represented by the
    given set in set representation."""

    # The result of the expression "2" (0 exponentiations) is represented by
    # the empty set, since 2 = 2^(2^0).
    if num_exponentiations == 0:
        return {frozenset()}

    # Split the expression 2^2^...^2 at each of the first half of
    # exponentiation operators and parenthesize each side of the expession.
    split_points = xrange(num_exponentiations)
    splits = itertools.izip(split_points, reversed(split_points))
    splits_half = ((left_part, right_part) for left_part, right_part in splits
                                           if left_part <= right_part)

    results = set()
    results_add = results.add
    for left_part, right_part in splits_half:
        for left in get_results(left_part):
            for right in get_results(right_part):
                results_add(exponentiate(left, right))
                results_add(exponentiate(right, left))
    return results

def exponentiate(base, exponent):
    """Return the result of the exponentiation of <operands>.

    <operands> is a tuple of <base> and <exponent>.  The operators are each
    given as the set representation of n, where 2^(2^n) is the value the
    operator stands for.

    The return value is the set representation of r, where 2^(2^r) is the
    result of the exponentiation."""

    # Where b is the number represented by <base>, e is the number represented
    # by <exponent> and r is the number represented by the return value:
    #   2^(2^r) = (2^(2^b)) ^ (2^(2^e))
    #   2^(2^r) = 2^(2^b * 2^(2^e))
    #   2^(2^r) = 2^(2^(b + 2^e))
    #   r = b + 2^e

    # If <exponent> is not in <base>, insert it to arrive at the set with the
    # value: b + 2^e.  If <exponent> is already in <base>, take it out,
    # increment e by 1 and repeat from the start to eventually arrive at:
    #   b - 2^e + 2^(e+1) =
    #   b + 2^e
    while exponent in base:
        base -= {exponent}
        exponent = successor(exponent)
    return base | {exponent}

@single_arg_memoize
def successor(value):
    """Return the successor of <value> in set representation."""
    # Call exponentiate() with <value> as base and the empty set as exponent to
    # get the set representing (n being the number represented by <value>):
    #   n + 2^0
    #   n + 1
    return exponentiate(value, frozenset())

def main():
    import timeit
    print timeit.timeit(lambda: count_results(20), number=1)
    for i in xrange(21):
        print '{:.<2}..{:.>9}'.format(i, count_results(i))

if __name__ == '__main__':
    main()

(The memoization decorator's concept is copied from http://code.activestate.com/recipes/578231-probably-the-fastest-memoization-decorator-in-the-/ .)

Output:

8.667753234
0...........1
1...........1
2...........1
3...........2
4...........4
5...........8
6..........17
[...]
19.....688366
20....1619087

Timings for different n:

 n    time
16    0.240
17    0.592
18    1.426
19    3.559
20    8.668
21   21.402

Any n above 21 results in a memory error on my machine.

I'd be interested if anyone can make this faster by translating it into a different language.

Edit: Optimized the get_results function.  Also, using Python 2.7.5 instead of 2.7.2 made it run a bit faster.


Order and Chaos and Codegolf Order and Chaos is a variant of Tic-Tac-Toe played on a 6x6 board. What makes the game unique, however, is that both players can place either an X or an O! Each turn (starting with Order), a player places an X or O in any unoccupied square.
Winning is simple. Order wins if there are 5 Xs or Os (vertically, horizontally, or diagonally) in a row on the board. Chaos wins if the board is filled and there are no strings of 5 Xs or Os on the board. Your job? Well, since this is Programming Puzzles and Code Golf, you're going to program the game, and golf it.
The Rules

You must accept input as x y t, where x and y are coordinates, and t is the tile type (X or O). Coordinates start with 0 0 in the upper-left corner and increase up to 5 5 (the lower-right corner).
You must accept q to quit, and print INVALID if the user enters invalid coordinates, tiles, any input not in the form of x y t, or tries to place a tile where there already is one. (The only exception is q, as this quits the program.)
If Order wins, you will output P1 WINS. If Chaos wins, you will output P2 WINS.
Order must go first.
A blank space is represented by ..
Tiles are X and O (uppercase). You do not have to accept lowercase, but uppercase is required.
Your board must only consist of .XO.
You're actually simulating both players playing the game, not being given a board and checking who wins. It accepts a move as input, then prints the board, accepts another move, and so on, until one player wins.

The starting board looks like this:
......
......
......
......
......
......

And after the first player (Order) inputs 1 2 X, it should look like this:
......
......
.X....
......
......
......

Likewise, when the next player (Chaos) inputs 3 3 O, it will look like this:
......
......
.X....
...O..
......
......

And this continues until one player wins.
As always, Standard loopholes which take the fun out of everything are forbidden.
The winner is the one with the shortest code on June 15, 00:00 UTC (about one month from when this challenge was posted.)

JavaScript, 360

Edit Modified interactive game, should run even in MSIE

As requested, text based game, input via popup, output in console (so to have a monospaced font).

Quit game with 'q' or clicking 'cancel' at prompt.

Not using ES5 features, it should run on any moder browser (where you can have a JS console panel)

b='\n......'.repeat(6).split('');
for(h=t=0;!h&t<36;)
{
  i=prompt();
  if(i=='q')i=null;
  i=i.match(/([0-5]) ([0-5]) ([XO])/);
  m='INVALID';
  if(b[p=i?i[2]*7-~i[1]:0]=='.')
  {
    ++t;
    b[p]=i[3];
    m=b.join('');
    for(x=z='',c=0;c++<6;)
      for(x+='_',z+='_',r=0;r<6;r++)
        x+=b[c+r*7],z+=b[c<4?c-1+r*8:c+1+r*6];
    h=(/X{5}|O{5}/.test(b.join('')+x+z))
  }
  console.log(m);
}
console.log("P"+(2-h)+" WINS")

Now, some more fun Interactive and graphic version, run snippet to play.

function start() {
  b=Array(7).join('\n......').split('');
  t=0;
  $('#O').text('');
  $('table')[0].className='';
  show();
  $('th').eq(1).html('Left-click: O
Right-click: X');
  $('#B')
  .off('mouseup')
  .on('mouseup','td.F',function(ev){
    var x,y, p=~~this.id.slice(1)
    x=p%7-1
    y=p/7|0
    b[p]=ev.which > 1 ?'X':'O';
    ++t
    for(x=z='',c=0;c++<6;)
      for(x+='_',z+='_',r=0;r<6;r++)
        x+=b[c+r*7],z+=b[c<4?c-1+r*8:c+1+r*6];
    show()
    if (/X{5}|O{5}/.test(b.join('')+x+z))
      end(1)
    else if(t==6*6)
      end(2)
    return false
  })
}

function end(w) {
  var n=['Order','Chaos'][w-1]
  $('th').eq(0).text('P'+w+' '+n+' Wins')
  $('th').eq(1).text('Click to play again')

  $('table')[0].className=$('tr')[0].className =n[0];
  $('#B').off('mouseup').on('mouseup', start)
}
function show() {
  var w,p
  p=t&1
  $('tr')[0].className=$('#B')[0].className='OC'[p];
  w=b.map(function(c,i){
    return c>' '?''+c+'	':'

'
  }).join('');
  $('th').eq(0).text('Playing: '+['Order','Chaos'][p]);
  $('#B').html('
' + w +'
');
}

start()
th {
  font-size: 12px;
}
.C th { color: #807; }
.O th { color: #047; }
.C td.F:hover { background: #f0e; }
.O td.F:hover { background: #0fe; }
table.C td { background: #f0e; }
table.O td { background: #0fe; }

td {
  font-family: monospace;
  font-size: 12px;
  width: 1.2em;
  height: 1em;
  text-align: center;
}


Print the first character of the previous answers The accepted winner is isaacg, with his 7-bit ASCII answer. However, the challenge isn't over yet - this bounty is awarded to the shortest answer. If, somehow, you get all the first characters of all the other answers down into 10 bytes, you will win the bounty. This includes all the characters from Round 2's GolfScript answer (plus the one added by that answer itself). This is the ONE time I will let you go out of order - if you have any objections to this, let me know in the comments.

  I'd like to give credit to randomra, who helped me with my old idea and gave me this new one.

Previous Winners

Round 1: isaacg, with 7-bit ASCII
Next bytes: 30 (or 10 if you want that sweet, sweet rep)
You know, code-golfing is really cool. People take a challenge, and it slowly gets smaller! But let's do this another way. So, here is my challenge:
The code will print the first character of all the previous answers in the order they were posted (the first answer prints nothing)
The code starts at 100 bytes and decreases by 5 each time.
If two posts are going by the same answer (i.e, they both posted within a few seconds of each other), the newer one has to add the old one's character and decrease by 5 bytes (even by a few seconds).
Any language can be used.
Your code must not produce any errors.
Your code must use all the bytes required for the first step.
Your code must print to STDOUT.
Non-printable characters are OK, but:

They can not be the first character (for the sake of the purpose of this question)
You must let everyone know where they are

You may post multiple answers, but:

You must wait 2 answers before posting another (so if you posted the 100 bytes, you have to wait until 85 bytes.)

You can't:

use more than 10 bytes of comments
have variables that go unused for the entire program
fill the program with whitespace
have variable names longer than 10 bytes (but you can have multiple less-than 10-byte variables)
(EMBLEM's first answer being the exception to these rules, because it was posted before these restrictions.)

No standard loopholes. Unless you want to take all the fun out of the challenge.
When no more answers are submitted for 3 weeks, the answer that uses the fewest bytes wins. (In the event of a tie, the one printing the longer string wins.)

Example: The third answer has to be a 90 bytes long code outputting two characters (the first char of the 100-byte code then the first char of the 95-byte code). The first answer outputs nothing (no previous answers to get chars from).

7-bit ASCII, 15 bytes

Updated: I did not realize that padding should occur at the end.

Correct version, padded at end:

hexdump (xxd):

0000000: e1c3 af0e 1438 a8b6 8f37 7a7b 7250 b6    .....8...7z{rP.

Printouts (not sure which is correct):

�ï8��z{rP�

áÃ¯8¨¶7z{rP¶

Old version, incorrectly padded at the front:

pá×
T[G½=¹([

The language / format here is 7-bit ascii, where each group of 7 bits corresponds to an ASCII character. It is used in transferring SMS data. A decoder is located here.

No widely accepted ruling exists on whether answers to fixed output questions which are not written in a programming language are allowed. See this meta post for more information. (I apologize, I misread that post earlier.)


Find the longest word in an array Your challenge is to take an array of strings and output the longest string in the array. So for

["tiny", "small", "bigger", "biggest"]

the output would be biggest.

If two elements of the array have the same length, you should choose the one that appears first in the array. That means if the array looks like this:

["one", "two", "no"]

the output is one, but if the array looked like this:

["two", "one", "no"]

the output is two.

As this is code-golf, the shortest code in bytes wins.

Imperative Tampio, 168 bytes
Listan x on riippuen siitä,onko sen ensimmäisen alkion pituus suurempi tai yhtä suuri kuin sen jokaisen alkion pituus,joko sen ensimmäinen alkio tai sen hännän x.

Online version
Ungolfed:

Listan pisin alkio on riippuen siitä, onko sen ensimmäisen alkion pituus suurempi tai yhtä suuri kuin sen jokaisen alkion pituus, joko

sen ensimmäinen alkio tai
sen hännän pisin alkio.

Online version
The only golfing opportunity this has is to replace pisin alkio (meaning "the longest element") with x.
Translation:

The longest item in a list is, depending on whether the length of the first item is greater or equal to the length of each element in the list, either

the first item in the list, or
the longest item in the tail of the list.


Recognizing Repetition in strings Create a program which gets an input from the user and tells the user what repetitions exist in the it. A few examples of inputs the user could give and outputs they should get:

  Input: 112211221122

  Output: 1122 * 3

Or:

  Input: 123123

  Output: 123 * 2

Or:

  Input: 1234

  Output: No repetitions found!

Tiebreaker: if your code can recognize more than one repetition:

  Input: 123123456456

  Output: 123 * 2, 456 * 2

Then you win if you are tied for 1st place with someone's code who doesn't recognize more than one repetition.

If your code requires a limit on the repetition length, it should be able to recognize repetitions at least 4 characters long. This is a code-golf question, so the shortest code wins (but please explain the code in your answer)

Perl, 74 (73 + 1) bytes

Assumes -n flag (+1 byte).
say is a feature of version 5.10 and needs to be enabled.
This can be done by flag -M5.010 or easier with -E instead of -e.
Therefore I follow the other Perl answer in the calculation method of the costs.
It also reports repetitions as long as they do not overlap.

s/(.+)(?{$i=1})(\1(?{$i++}))+/say"$1 * $i"/ge||say"No repetitions found!"

Usage and tests

echo 112211221122 | perl -nE 's/(.+)(?{$i=1})(\1(?{$i++}))+/say"$1 * $i"/ge||say"No repetitions found!"'
1122 * 3

echo 123123 | perl -nE 's/(.+)(?{$i=1})(\1(?{$i++}))+/say"$1 * $i"/ge||say"No repetitions found!"'
123 * 2

echo 1234 | perl -nE 's/(.+)(?{$i=1})(\1(?{$i++}))+/say"$1 * $i"/ge||say"No repetitions found!"'
No repetitions found!

echo 123123456456 | perl -nE 's/(.+)(?{$i=1})(\1(?{$i++}))+/say"$1 * $i"/ge||say"No repetitions found!"'
123 * 2
456 * 2

Ungolfed with comments

s/
    (.+)              # catches the repeat unit
    (?{ $i=1 })       # initialize counter $1 with 1
    (
        \1            # next repetition
        (?{ $i++ })   # increase counter
    )+                # repeat unit must appear at least twice
/
    say "$1 * $i"     # print result as a side effect of the replacement;
                      # "say" adds a new line at the end
/gex                  # g: global, find all repetitions (without overlap)
                      # e: replacement text is executed as code
                      # x: only ungolfed: readability and comments
    ||                # s/// returns the number of replacements,
                      # this is zero, if no repetitions could be found
    say "No repetitions found!"


Hamilton is coming to town It's almost Christmas, so Santa has to plan his route. You're helping him, for reasons unknown.

Santa needs help planning the route and wants you to give him a solution, but since you're all ungrateful and unwilling to give to the man who has given you so much, so have decided to give him a program with as few bytes as possible to accomplish the following.

The houses Santa needs to visit can be represented by coordinates on the Cartesian plane (the coordinates of the houses need not be integers, there cannot be more than 1 house at any point, and there is no house at the origin). These coordinates will be the input. Starting at the origin, Santa will visit each coordinate and then return to the origin.

Santa rides his sleigh at a constant one unit per second in a straight line between houses. However, when Santa crosses any lattice point (a point with integer x and y coordinates) he stops for one second to eat a cookie (the initial and final crossings of the origin do not count, though crossing it on the path between, say, (-1,-1) and (1,1) would). When he stops at a house, he spends five seconds to deliver a present (so he spends six seconds at houses on lattice points).

Write a program that takes as its input a set of coordinates and prints the smallest number of seconds Santa needs to deliver all of the presents to the houses and return to the origin, rounded to three digits. Take 25% off your code if it also prints any order of coordinates Santa visits that minimizes the time.

Test cases

(1,1) (2,4) (2,2)
==> 14.301
==> (Bonus) (1,1) (2,2) (2,4)

(3,4) (2,-1) (0,-3.5) (1,6)
==> 27.712
==> (Bonus) (0,-3.5) (2,-1) (3,4) (1,6)

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

Note that this is a modification of the Travelling Salesman Problem, so your program does not need to terminate in any reasonable amount of time for an unreasonable number of inputs (this is a problem in O(n!) after all).

Perl 6, 198 bytes (264 bytes - 25% bonus)

Managed to actually get this sucker into a Whatever block by inlining the helper functions from the original version.

*.permutations.map({([+] -1,5*@_,|(for (0,0),|@_ Z |@_,(0,0) ->((\i,\j),(\x,\y)){my ($s,\p)=0,i.Rat.nude[1]*j.Rat.nude[1]*abs(i -x).Rat.nude[0];(i+(x -i)*$_/p)%%1&&(j+(y -j)*$_/p)%%1&&$s++ for ^p;sqrt(abs(i -x)²+abs(j -y)²)+(p??$s!!abs(j.Int -y.Int))})),@_}).min

Try it online!

No doubt there are still a few little improvements that can be made.  Trickiest part was figuring out how to calculate the number of lattice points crossed.  The solution I went with uses the denominators of each X coordinate to calculate an iteration interval that is guaranteed to hit each whole number along with X axis, thus allowing a check for landing on a lattice point.  There is a catch, of course, that if there is no movement along X then the lattice points crossed will be the absolute value of the floor value of each Y coordinate.

This will be, nonetheless, very tricky for languages that don't have built in rationals, because of floating point errors (I can already see the .1 + .2 = .3 issue cropping up if any two X or Y coordinates are 10 apart).

Ungolfed version:

*                           #  Whatever block, takes a list of coordinates
.permutations.map({         #  Get all combinations and to each of them ...
 (                          #   Implicitly return a list consisting of
  [+]                       #    The sum of
   -1,                      #     -1 (to discount lattice +1 on return to origin)
   5*@_,                    #     5 * number of coordinates (or stops)
   |(for                    #     each value in the loop across
    (0,0),|@_ Z |@_,(0,0)   #      the coordinates (zipping with the origin
                            #        first/last for the return)
    ->((\i,\j),(\x,\y)) {   #      deconstructing into i,j,x,y
     my ($s,\p)=0,          #      set S (lattice stops) to 0
       i.Rat.nude[1]        #      set P (x check interval) to denominator of i
       *j.Rat.nude[1]       #       times denominator of p (psuedo lcm)
       *abs(i -x).Rat.nude[0]; #    times x-diff numerator (bc Rat simplification)
     (i+(x -i)*$_/p)%%1&&   #      check X is whole, if so,
      (j+(y -j)*$_/p)%%1&&  #       check Y is whole, if so,
      $s++                  #        increment S (trip crossed a lattice point)
     for ^p;                #      do the checks for 0 to P
     sqrt(                  #      implicitly return
      abs(i -x)²+abs(j -y)² #       the distance
     )+(p                   #        plus, if X values were different,
      ??$s                  #         S value, else
      !!abs(j.Int -y.Int)   #         Y difference = vertical lattice crossings
     )
    }
   )                        #
   ,@_)                     #   And the permutation
.min                        #  Find best (smallest) time

I'll probably add a more readable version because this golfing got unreadable fast.


Shortest class to implement Perl hash-of-hashes At some point, I bumped into an SO question asking how to implement Perl's trivial hash-of-hashes data structure in Java.

For those who don't know Perl, the hash value can be a scalar or another hash, or technically speaking hash reference. Arbitrary depth. Additional feature offered by Perl is autovivification - assigning an element 4 layers deep will automatically create correct hashes with proper keys 4 levels deep, without Java's need to assign hash object on level 1, then hash object on level 2 (being added to the first hash as a value) etc...

So, Perl code to assign a value to N-level hash at a known depth is

my $myHash; # initialization isn't required due to autovivification
$myHash->{$key1}->{$key2}->{$key3}->{$key4} = $value;

And to retrieve it

my $value = $myHash->{$key1}->{$key2}->{$key3}->{$key4};

The more generic code to assign a hash by arbitrary set of keys can be implemented by 5-10 line subroutine done properly; or 2-3 lines golf hack with eval.

Not being anywhere near a Java expert, my SO answer was ~30 lines of code that implemented a fixed-depth 3 level hash of hash of hashes.

Your mission, should you choose to accept it, is to produce the smallest code in a strongly typed language which implements Perl equivalent data structure which is a hashmap of hashmaps of ...; of arbitrary and non-uniform depth (basically, a tree); with hasmap keys being of String type; and leaf-level values String or Integer. The code should support 100% of what the Perl hash-of-hashes code does, including:

Retrieving a value based on a list of keys
Assigning a value based on a list of keys

As part of this, you should be able to replace a scalar leaf level node with an internal hashmap node, if your list of keys leads to that.

E.g. set("val1","k1","k2");set("val2","k1","k2","k3") basically erases "val1" from existence after second call as it's replaced by a 3rd level hashmap.

The code should be resilient, e.g. no null exceptions etc... even for the bad input (simply return NULL)

You can use any strongly typed language other than Java, though I would personally prefer Java answers due to how/why this question originated.

Caveat: using some 3rd party library that implements equivalent of Perl hashes is NOT acceptable. 100% of the code must be using only the native core capabilities of the language.

Scala, 231 214 199 193 bytes

Immutability always wins! (turns out the long package name of collection.mutable.Map wasn't worth the hassle...)

class A{var a=Map[String,Any]()
def g(s:String*):Any={val y=s(0);if(s.size>1)g(y).asInstanceOf[A].g(s.drop(1):_*)else if(a.contains(y))a(y)else{a+=y->new A;a(y)}}
def s(s:String,v:Any)=a+=s->v}

Only thing that's problematic is the need to cast back to A... but having another method entirely that'd return a.type is actually longer (and with cannot be used).

Example:

val a = new A()
a.g("hey").asInstanceOf[A].s("foo", "bar")
a.g("hey").asInstanceOf[A].s("int", 3)
println(a.g("hey").asInstanceOf[A].g("foo"))
println(a.g("hey", "foo"))
println(a.g("hey", "int"))
a.s("hey", 42)
println(a.g("hey"))

Output:

bar
bar
3
42


Number of unique outputs by substituting variables Given a set of formulas like this:

bacb
bcab
cbba
abbc

Give an algorithm that finds the number of unique results you can get when each variable is substituted for either "0" or "1" in every formula.

There are (k!)^2 formulas, each with 2k-1 variables and k^2 terms. Express your asymptotics in terms of k.

Fastest algorithm wins. In case of a tie the solution with lower asymptotic memory usage wins. If that's still a tie, first post wins.

For the example above the following results can be acquired by substituting the variables:

1110, 0110, 1001, 0100, 1000, 0000, 0010, 1101, 1111, 0001, 1011, 0111

So the correct answer is 12. Among others, 1010 can not be made using the above formulas.

I've made  three more tests cases, with respective solutions of 230, 12076 and 1446672.

Mathematica, O(k^2(k!)^2) time
Length[Union@@(Fold[Flatten[{StringReplace[#,#2->"0"],StringReplace[#,#2->"1"]}]&,#,Union[Characters[#]]]&/@#)]&

Hopefully I calculated the time complexity correctly. Input is a list of formulas such as {"bacb","bcab","cbba","abbc"}. Runs in less than 30 seconds for every test case on my machine, but who cares about absolute times?
Explanation:

First off, the & at the end makes it a pure function, with # referring to the first argument, #2 being the second argument, etc.
Length[*..*] takes the length of the list contained inside it.
Union@@(*..*) takes the contained list and supplies it as the arguments for Union, which returns a list of the unique elements in any of its arguments.
*..*&/@# takes a pure function and maps it over the list of formulas, so that {a,b,c} becomes {f[a],f[b],f[c]}. Note that in nested pure functions, #n refers to its innermost arguments.
Fold[*..*&,#,*..*] takes a accumulator function, starting value, and list, and returns f[f[...[f[starting value,l_1],l_2],...],l_n].
Union[Characters[#]] takes all the characters in the current formula and gets all the unique elements, giving us the variables.
Flatten[*..*] flattens its argument, so that {{{a},b},{{c,{d}}}} becomes {a,b,c,d}.
{*..*,*..*} is simply a way to combine the two results using the above Flatten.
StringReplace[#,#2->"0/1"] takes the previous result and returns it with the current variable replaced with either 0 or 1.


Produce different behaviour in all versions of your language Write a program that:

if a compiled language is used, compiles without errors
if an interpreted language is used, runs without syntax errors

for every major release of your language, and produces different output for every major release under which it is compiled/run. (It may produce the same or different output for versions within the same major release, as long as it varies among major releases.) You may not output or use any part of the language version in your program.

A "major release" of a language is defined to be a publicly available release that added to the major version number. For example, C# has had 6 major releases, C has had 3 (K&R is not a numbered version and does not contribute to the count), and Ruby has also had 3 (due to version 0.95). What number constitutes the major version number can change over time (Java has had 8 major releases).

Any language used in this challenge must have:

At least three major releases, and
A dedicated Wikipedia article.

Python

if 2 + 2 is 4:
    # Lies must be abolished

    try:
        fact = '2 + 2 = %r' % 5
        exec('True = False')
        exec('assert (2 + 2 == 5) is True')
    except ValueError:
        print('War is peace.')
    except NameError:
        print('Freedom is slavery.')
    except SyntaxError:
        print('Ignorance is strength.')

else:
    # All is good
    print('Big Brother is watching you.')

(Edit: Had to make a change because string formatting was actually introduced in... 0.9.9)

Tested on the following versions:

0.9.1: Prints Big Brother is watching you. because 2 + 2 is 5.*
1.5: Prints War is peace. since %r string formatting is unavailable, raising a ValueError,
2.1: Prints Freedom is slavery. since True is not defined, raising a NameError,
3.4: Prints Ignorance is strength. since True cannot be assigned to, raising a SyntaxError.

As a bonus, Python 2.3 to 2.7 gives no output, since the assertion passes.

Note that there are four spaces on both "blank" lines, and the file also needs to have a trailing newline.

* is checks object equality, and only from 1.0.0 onwards were small integers shared. You can still see the effect today by trying larger numbers, e.g. 999 + 1 is 1000 gives False.


Biggest Irreducible Cat I guess you could call this the next challenge in the "Irreducible series".

Hello World

Challenge
Create a cat subject to the constraint that it is irreducible.
A cat program C is considered irreducible if there does not exist a cat (in the same programming language as C) that can be constructed by removing characters from C.
For example
console.log(prompt.call());

can have the the bracketed characters removed
console.log(prompt[.call]())[;] ->
console.log(prompt())

And it will still be a cat. Therefore console.log(prompt.call()); is not irreducible.
The winner will be the program with the longest source code.
Extras
A big shout out to @acupoftea for showing that, for any given language, there is actually a maximum score. Otherwise you could construct an infinite set that would break Higman's lemma!.

Jelly -u, \$4\times10^{41}\$ bytes
“...”WẈbØ%ỌV

Except instead of ... its \$133390687877217192365177139021057049493695\$ Ɱ characters
More specifically, a score of \$400172063631651577095531417063171148481103\$
How it works
The standard cat program in Jelly is
ƈȮøL¿

Try it online!
If we convert each of these characters to their Unicode code point we get
[392, 558, 248, 76, 191]

Treat this a base \$4294967296 = 2^{32}\$ number and convert it back to decimal to get \$133390687877217192365177139021057049493695\$
The above program has a string consisting of \$133390687877217192365177139021057049493695\$ Ɱ characters. We then take its length, convert it to base \$4294967296\$, convert back to characters and run as Jelly code.
By forcing Jelly to encode the source as UTF-8 rather than using the Jelly code page, multi byte characters are counted as multiple bytes rather than just 1.
This is 100% irreducible. The cat program it encodes is optimal for Jelly, so there's no way to remove any of the Ɱ characters and still create a cat program, and all of the other characters are necessary to correctly convert the string to a program and execute it. More specifically:

Removing either “ or ” will cause syntax errors
Removing the W will cause Ẉ to return a list of lists of \$1\$s rather than the code points in base \$4294967296\$
Removing the Ẉ will mean the program won't ever convert the string to the code points in base \$4294967296\$
Removing any of bØ% will prevent the base conversion happening
Removing Ọ or V will stop the program from converting to characters and running the program

Furthermore, I believe this is the longest you can get using the method of "long string's length in a high base" in Jelly. The base being used must meet the following criteria:

The number isn't "constructed" via commands to be larger, as these commands can be removed and the long string adjusted for the lower base
The number doesn't have digits in it, as characters can be removed to just isolate the lowest digit and the long string can then be adjusted to match this new base

Ø% is the largest constant Jelly has which meets these criteria at \$2^{32}\$, so, as a higher base leads to a longer string, an answer in Jelly cannot beat this one.


How fast can I say your program? I recently decided to download some dictation software, in order to help with my writing. However, it doesn't work very well when I'm coding, since I have to change from saying words to symbols and back again. It's even worse when I'm coding in an esoteric language which is all symbols.

In order to make my use of the dictation program more consistent, I decided to switch it over to character mode, where I just say the name of each character instead. Problem solved! Though this does delay my novel's release date a little bit...

So, assuming that the longer the name of a character, the longer it takes to say, how long will it take me to spell out some of my programs/sentences?

Specifications

Given a string consisting of only printable ASCII, return the sum of each character's unicode name. For example, / is called SOLIDUS with 7 characters, and A is LATIN CAPITAL LETTER A with 22 characters.

But remember, I have to say your programs out loud to execute them, so their score will be based on how long it takes me to say them, i.e. as the sum of the lengths of each character's unicode name.

Test Cases:

In format input => output with no trailing/leading spaces in input.

A      => 22
/      => 7
Once upon a time...           => 304
slurp.uninames>>.comb.sum.say => 530
JoKing => 124
!" #$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~        =>  1591
Double-check your \s on the last test case ;)   => 755
<say "<$_>~~.EVAL">~~.EVAL     => 388
,[.,]  => 58
19     => 19

Rules:

Input to your program will only consist of printable ASCII characters, that is, the codepoints 32 (space) to 126 (tilde).

For convenience sake, here is the list of lengths of the characters you have to handle: [5,16,14,11,11,12,9,10,16,17,8,9,5,12,9,7,10,9,9,11,10,10,9,11,11,10,5,9,14,11,17,13,13,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,19,15,20,17,8,12,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,18,13,19,5]

Here is a reference program you can use to score your program.

Peter Taylor has pointed out that the reference program normalises some unicode characters. It should still work for most solutions, but feel free to correct it if you need

Since you're saying what the characters actually look like, your solution will be scored by the characters that are displayed, not the bytes involved. This is directed at languages with custom encodings.

You can assume that I've memorised the entire Unicode library and can say whatever strange characters you use.

Sorry Rogem, but answers have to be composed of displayable characters. Unprintables are fine, I just have to be able to read the characters out loud.
Whatever you do, do not use ﯹ in your program.

Java 8, score 846 838 822 816

ௐ->ௐ.map(ˇ->Character.getName(ˇ).length()).sum()

-8 score thanks to @tsh replacing the _1 with ꀊ.
-22 score thanks to @ASCII-only replacing the ꀊ with ˇ and $ with ௐ.
Try it online.
Explanation:
The ௐ and ˇ are used instead of the s and c I would normally use, because lowercase letters are all 20 (i.e. LATIN SMALL LETTER S), but ௐ (TAMIL OM) is 8 and ˇ (CARON) is 5.
ௐ->                         // Method with IntStream parameter and integer return-type
  ௐ.map(ˇ->                 //  Map each character to:
      Character.getName(ˇ)  //   Get the name of the character
               .length())   //   Get the length of that name
   .sum()                   //  And after the map: sum all lengths together,
                            //  and return it as result


Convert __DATE__-style string to sortable string Goal is to write the shortest possible C89 and C99-compliant single-module C program which will compute and print out a single-line string whose sort order will correspond with the date given by the predefined __DATE__ macro (in other words, later dates will yield later-sorting strings).  The programmer is free to arbitrarily select the mapping between dates and strings, but every entry should specify the mapping and it should be obvious that it will sort correctly (e.g. a programmer could decide to compute (day + month*73 + year*4129) and output that as a number, though it's likely that particular encoding would probably require a longer program than some others).

The program should yield identical results on any standards-compliant compiler on which 'int' is 32 bits or larger and both source and target character sets are 7-bit ASCII, and should not rely upon any implementation-defined or undefined behavior nor print any characters outside the 32-126 range except for a single newline at the end.  The program should contain the following aspects indicated below (replacing «CODE» with anything desired):

♯include <stdio.h>
«CODE»int main(void){«CODE»}

All output shall be produced by the printf at the end (i.e. the correct value will be in an int called z).  The required elements will be included in the character total for each entry.

Code should operate correctly for all future dates through Dec 31 9999.  Libraries which are standard in both C89 and C99 may be used, provided that appropriate headers are included.  Note that standard date libraries may not be assumed to operate beyond the Unix limits.

Note: Code is permitted to perform Undefined Behavior if and only if the __DATE__ macro expands to a macro other than a date between Feb 11 2012 and Dec 31 9999 (expressed in that format, using C-standard abbreviated English month names Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec)

Note 2: For compliance with C99 standards, 'main' should return an arbitrary, but defined value, and the newline is required.  The first requirement, btw, adds 7 characters to my best effort; the single new-line adds 5.

C, 137 184 184 140 120 106 103 characters

Replaced the month name lookup with a magic formula.
The formula (m[1]*4388^m[2]*7)%252 is ascending for month names.
Changed it to nicely return 0, at no cost.
It no longer prints a number. Instead it prints a string, which should sort right.
Implemented supercat's %*s idea, which inserts more spaces for earlier months, along with a function that's descending for month names - (m[1]*29^m[2]+405)%49.

#include<stdio.h>
int main(void){
    char*m=__DATE__"%*.6s\n"+1;
    return!printf(m+6,(*m*29^m[1]+405)%49,m);
}

I thought single digit days are represented as Jan_1_2012 (_ being a space), when in fact it's Jan__1_2012 (extra space). This complicated things, so my previous versions were more complicated:

#include<stdio.h>
int main(void){
    char*m=__DATE__+1,*t=m+m[4]/16;
    return!printf("%s%3d%s\n",t+3,(*m*4388^m[1]*7)%252,t);
}


Calculate the middle number of a row of the pascal triangle Write a function that calculates a row of the pascal triangle and returns the middle number, if there are 2 it should return their sum.

Example:

5

would return

20

Example 2:

4

would return

6

EDIT:

To be clear:

a) if the number inputted is odd then find then return the middle number of a row on the pascal triangle.

b) if the number inputted is even then find the two middle numbers of the row on the pascal triangle and sum the 2 numbers.

The nth row is using zero-based indicies. For numbers other than zero, this is the row which has its second number as the number inputted into the function.

Ohm, 6 bytes

½⌠Ddac

Try it online!

If the number is even it is you calculate (n n/2) if it is odd (n+1 (n+1)/2)

         Inplicit input
½        Half
 ⌠       Ceil
  D      Duplicate on stack
   d     x2
    a    Swap on stack
     c   Binomial


Arbitrarily Shift Bit Array Represented As Array of 32-bit Integers Given an array of 32-bit integers which represent a bit array, shift the values by a specified amount in either direction. Positive shifts go to the left and negative values go to the right. This is a bit array so bits should wrap across values in the array.

For example, given the following data:

a[2] = 11110000 11110000 11110000 11110000
a[1] = 11110000 11110000 11110000 11110000
a[0] = 11110000 11110000 11110000 11110000 <-- 0th bit

Shifting the original by 2 should result in:

a[3] = 00000000 00000000 00000000 00000011
a[2] = 11000011 11000011 11000011 11000011
a[1] = 11000011 11000011 11000011 11000011
a[0] = 11000011 11000011 11000011 11000000 <-- 0th bit

Shifting the original by -3 should result in:

a[2] = 00011110 00011110 00011110 00011110
a[1] = 00011110 00011110 00011110 00011110
a[0] = 00011110 00011110 00011110 00011110 <-- 0th bit

There's no restriction on shift amount (i.e., can be greater than 32) so be mindful of where your bits are going!

Here's the method signature:

int[] bitArrayShift(int[] bits, int shift)

Implementations should:

Return an array whose contents represented the original bit array's contents shifted by the supplied number.
Return an array whose size is the minimum amount required to hold the values after the shift. You should not wrap back around to the 0th bit but rather expand to hold it.
Not mutate the input array. It should be treated as being passed by reference (therefore having mutable contents). Basically, don't put any new values at any position in the input array.

The following assertion should always return true for any value of 'bit' and 'shift':

// Given 'originalBits' as incoming bit array.
// Given 'bit' as a number between [0, originalBits.length * 32).
// Given 'shift' as any integer value.

// Get the value in the array at the index of 'bit'
bool original = ((originalBits[bit / 32] & (1 << (bit % 32)) != 0
// Shift the original bits by the specified 'shift'
int[] shiftedBits = bitArrayShift(originalBits, shift)
// Offset the original 'bit' by the specified 'shift'
int shiftedBit = bit + shift
// Get the value in the shifted array at the index of 'shiftedBit'
bool shifted = ((shiftedBits[shiftedBit / 32] & (1 << (shiftedBit % 32)) != 0
// They should be equal.
assert original == shifted

Smallest character count wins. Count method body contents ONLY sans leading and trailing whitespace. That is, the method declaration up to and including the block start (if any) and ending exclusively at the block end (if any).

E.g., for Java:

public static int[] shiftBitArray(int[] bits, int shift) {
  << COUNT THIS ONLY >>>
}

Java 306

public static int[] shiftBitArray(int[] bits, int shift) {
    BigInteger r = BigInteger.ZERO;
    for (int i = bits.length - 1; i >= 0;) r = BigInteger.valueOf(0xffffffffL & bits[i--]).or(r.shiftLeft(32));
    r = r.shiftLeft(shift);
    int[] a = new int[(int) Math.ceil(r.bitLength() / 32d)];
    for (int i = 0; i < a.length; r = r.shiftRight(32)) a[i++] = r.intValue();
    return a;
}


Solving the water bucket riddle! Context

The water buckets riddle or the water jugs riddle is a simple riddle that can be enunciated in a rather general form as:

Given \$n > 0\$ positive integers \$a_1, a_2, \cdots, a_n\$ representing the capacities (in units of volume) of \$n\$ buckets and a positive integer \$t \leq \max(a_1, a_2, \cdots, a_n)\$, find a sequence of "moves" that places \$t\$ units of volume of water in some bucket \$i\$.

To define the valid "moves", let \$c_1, c_2, \cdots, c_n\$ represent the units of volume of water each bucket \$i\$ contains, with \$0 \leq c_i \leq a_i\ \forall i\$. Then, at each step you can do any of the following:

fill a bucket \$i\$ entirely, setting \$c_i = a_i\$
empty a bucket \$i\$ entirely, setting \$c_i = 0\$
pour a bucket \$i\$ over a bucket \$j\$, setting

$$\begin{cases}
c_i = \max(0, c_i - (a_j - c_j)) \\
c_j = \min(a_j, c_j + c_i)
\end{cases}$$

i.e you pour bucket \$i\$ over bucket \$j\$ until bucket \$i\$ becomes empty or bucket \$j\$ becomes full, whatever happens first (or both if both things happen at the same time).

Task

Given the bucket capacities and the target measurement, your task is to output a minimal sequence of movements that places \$t\$ units of volume of water in one of the buckets.

Input

The capacities of the buckets are positive integers. You can assume these capacities are unique and ordered. You can take them in a number of reasonable formats, including but not limited to:

a list of integers
arguments to a function

Additionally, you will take a positive integer t that is not larger than the maximum number present in the input capacity list.

You can assume the input parameters specify a solvable instance of the water buckets problem.

Output

Your program/function/etc should output the shortest sequence of moves that places t units of volume of water in one of the buckets. If several such sequences exist you can output any one sequence. Please note that some moves commute and that also introduces multiple solutions to some problems.

Your program can print the sequence or return it as a list of moves or any other sensible thing.

To identify the moves and the buckets, you can choose any encoding suitable for your needs, as long as it is consistent across test cases and completely unambiguous. A suggestion is, use three letters to identify the three moves, like "E" for emptying a bucket, "F" for filling and "P" for pouring and use numbers to identify the buckets (0-index or 1-indexed or using its total capacity, for example).

With this encoding, to identify a move you always need one letter and a number. In case of a "pouring" move, a second integer is also needed. It is up to you to consistently use "P" n m as n was poured over m or m was poured over n.

Test cases

We use the encoding above and "P" n m means "pour bucket n over bucket m".

[1, 2, 3, 4], 1 -> ['F 1']
[1, 2, 3, 4], 2 -> ['F 2']
[1, 2, 3, 4], 3 -> ['F 3']
[1, 2, 3, 4], 4 -> ['F 4']
[13, 17], 1 -> ['F 13', 'P 13 17', 'F 13', 'P 13 17', 'E 17', 'P 13 17', 'F 13', 'P 13 17', 'E 17', 'P 13 17', 'F 13', 'P 13 17']
[4, 6], 2 -> ['F 6', 'P 6 4']
[1, 4, 6], 2 -> ['F 6', 'P 6 4']
[3, 4, 6], 2 -> ['F 6', 'P 6 4']
[4, 5, 6], 2 -> ['F 6', 'P 6 4']
[4, 6, 7], 2 -> ['F 6', 'P 6 4']
[1, 3, 5], 2 -> ['F 3', 'P 3 1']
[7, 9], 4 -> ['F 9', 'P 9 7', 'E 7', 'P 9 7', 'F 9', 'P 9 7']
[8, 9, 13], 6 -> ['F 9', 'P 9 8', 'P 8 13', 'P 9 8', 'F 13', 'P 13 8']
[8, 9, 13], 7 -> ['F 8', 'P 8 9', 'F 8', 'P 8 9']
[8, 9, 11], 10 -> ['F 8', 'P 8 9', 'F 11', 'P 11 9']
[8, 9, 12], 6 -> ['F 9', 'P 9 12', 'F 9', 'P 9 12']
[8, 9, 12], 5 -> ['F 8', 'P 8 12', 'F 9', 'P 9 12']
[23, 37, 41], 7 -> ['F 41', 'P 41 23', 'P 41 37', 'P 23 41', 'F 41', 'P 41 23', 'P 41 37', 'F 41', 'P 41 37', 'E 37', 'P 41 37', 'E 37', 'P 41 37', 'F 41', 'P 41 37']
[23, 31, 37, 41], 7 -> ['F 23', 'P 23 37', 'F 31', 'P 31 37', 'P 31 41', 'P 37 31', 'P 31 41']

You can check a vanilla Python reference implementation here

Python 3, 243 239 bytes

-4 bytes thanks to @JonathanFrech!

def f(a,t,k=1):
 while g(a,t,[0]*len(a),[],k):k+=1
def g(a,t,c,p,k):n=len(a);k,i=k//n,k%n;k,j=k//n,k%n;exec(["c[i]=0","c[i]=a[i]","x=min(a[j]-c[j],c[i]);c[i]-=x;c[j]+=x"][k%3]);p+=k%3,i,j;return g(a,t,c,p,k//3)if k>2else{t}-{*c}or print(p)

Try it online!

Input: a list of bucket capacities a, and the target t.
Output: to stdout, a list of integers, where each triplet m,i,j denotes a move: m is the move type (0,1,2 corresponds to empty, fill, pour), and i,j are the bucket indices (0-index). For move types empty and fill, the 2nd bucket is ignored.

How: Each sequence of moves p can be encoded by an integer k using modular arithmetic. g is a recursive function that checks if the sequence p encoded by k will result in the target t. If so, that sequence is printed to stdout, and a Falsy value is returned.

Old solution using itertools.product

Python 3.8 (pre-release), 279 249 bytes

Whopping -30 thanks to @ovs's double product trick!

from itertools import*
P=product
a,t=eval(input())
for r in count():
 for p in P(*tee(P((0,1,2),R:=range(n:=len(a)),R),r)):
  c=[0]*n;[exec(["c[i]=0","c[i]=a[i]","x=min(a[j]-c[j],c[i]);c[i]-=x;c[j]+=x"][m])for m,i,j in p]
  if t in c:print(p);exit()

Try it online!

Slow, ugly and can probably be golfed more.

Input: from stdin, a,t where a is the list of bucket capacities, and t is the goal.
Output: to stdout, the optimal list of moves, each move has the form (m, i, j) where:

m is the move type 0,1,2 (empty, fill, pour)
i and j are the target buckets' indices (0-index).
The moves empty and fill only affects the 1st bucket i, and thus the irrelevant 2nd bucket j is set to an arbitrary value.
The move (2,i,j) pours the water from bucket i to bucket j.

How:
This program simply tries all possible sequence of move, in order of length.

To generate all sequence of r moves:

product((0,1,2), range(n), range(n)) generates a list of all possible moves by performing the Cartesian product between all move types 0,1,2, all values of i and all values of j.
tee(product(...), r) clones the move list into r lists.
product(*tee(...)) takes the Cartesian product ofrmove lists, which results in all possible sequence ofr` moves.

To perform a sequence of move p:

c[i]=0,c[i]=a[i], and x=min(a[j]-c[j],c[i]);c[i]-=x;c[j]+=x respectively handles emptying, filling, and pouring between bucket i and j. Note that pouring can handle i==j, which results in a no-op.
exec(["handle E", "handle F", "handle P"][m]) selects the correct handler for move type m.


Write an program that terminates after 60 seconds - Robbers Thread This is a cops and robbers challenge - Cop's Thread

Each of the cops have been tasked to write a program that terminates after exactly 60 seconds, or as close as possible. For example:

#include <unistd.h>
int main(int argc, char **argv){
    sleep(60);
    return 0;
}

Your goal is to take any of the uncracked submissions and change it so that it terminates after 31 seconds. If a cop's answer has been up for more than two weeks, it is immune to cracking. The original answer and your edit must have a Levenshtein edit distance of up to half of the original program's length.

The robber with the most cracks wins!

The cops have been allowed to do either of the following if they do not wish to use the system time calls:

The speed of printing to stdout is controlled by the baud rate of the terminal you are printing to. If you wish, you can control the speed of your program by printing to stdout with a set baud rate. However, you must also cite an actual piece of hardware or terminal program that has that baud rate as default (e.g. a serial printer with a default print speed of 300 baud).
If you are working in a language where all operations take some constant amount of time (such as assembly language), you can control the speed of your program by specifying the processor's clock rate. However, this too must be accompanied with a citation of an actual processor chip that runs at that speed (e.g. the 1 MHz 6502 put inside Apple //e and NES boards).

If you encounter a solution with this specification, you cannot change this parameter. (Not that it would help you much anyway, since it's hard to find an upgraded chip or serial output device with a 31:60 speed ratio).

Jelly, edit distance 5 from 30 bytes

Original:

69266249554160949116534784œSÆl

Crack:

69266249554160949116534784œSÆl_29$$

I just subtracted 29 from the timeout immediately before the œS runs. (_29 subtracts 29, the dollars control precedence, a bit like parentheses in other languages.)


Why isn't it ending? Your task: To write a program that should obviously terminate, but it never (to the extent of a computer crash) does. Make it look like it should perform a simple task: adding numbers, printing something,... But it just gets caught in an infinite loop.

Try to make your program very clear and simple, while it actually will get stuck in an unforeseen loop. Voters: judge the answers on how "underhanded" they are!

This is a popularity contest: Be creative!

Javascript

var x=prompt('Enter a value under 100');
while (x != 100) {
  x=x+1;
}
console.log('End!');

   prompt() returns a string and the loop appends the character '1', it will never be equal to 100.


How do I get more Klotski in my life? I really love sliding tile puzzles, but recently, I haven't had time for them.  Hence, I need a program to give me my fix of sliding-tile puzzles, specifically Klotski puzzles.

Your input will be in the following format:

#######
#001gg#
##.222#
.######

where # represents walls, . represents an open area, g represents the goal, and adjacent numbers represent different blocks.  You can assume that:

There will be no more than 10 blocks
There won't be two blocks with the same number
All blocks will be enclosed by walls
The grid is rectangular
The 0 block is large enough to cover all of the goal squares.
There is a valid solution

You need to return a sequence of moves that will put the 0 block so that it covers all of the goal squares.  Blocks cannot pass through walls or other blocks.  For the above puzzle, an appropriate sequence would be

2L,1R,1R,1D,0R,0R,0R

while represents moving the 2 block 1 square left, the 1 block 2 squares right (on top of the goal) then 1 square down, and then 0 block 3 squares right.

There are actually several sequences that will work for the above problem, and producing any of them is acceptable.  Your solution should be optimal, meaning that it should produce a sequence that solves the puzzle in as few as steps as possible.

The sequence should be printed out as above, but can be comma, newline, or space
separated.  I don't care if there are trailing commas or whitespace.  You should produce the output in reasonable time (maximum 120 seconds on the puzzles below).

Puzzle 1:

..####..
..#00#..
###00###
#......#
#.1122.#
##3124##
.#3344#.
.##55##.
..#gg#..
..####..

Puzzle 2:

######
#1002#
#1002#
#3445#
#3675#
#8gg9#
######

Puzzle 3:

.####.
##1g##
#22g3#
#4255#
#4.56#
#.006#
#7008#
######

Puzzle 4:

.####.
##00##
#.00g#
#.0.1#
#..g2#
######

This is code-golf, so the shortest solution (in bytes) wins!

Python, 1761
Kind of burnt out on this question, so couldn't bring myself to golf it. Either way, right now it's the only solution that solves everything within the time limit (longest, #3, takes 27 seconds).
pieces = {}
taken = set()
goals = set()

y = 0
while True:
    try:
        for x, c in enumerate(input()):
            if c == ".": continue
            if c == "g":
                goals.add((x, y))
            else:
                if c in "0123456789":
                    if c not in pieces: pieces[c] = set()
                    pieces[c].add((x, y))
                taken.add((x, y))

        y += 1

    except: break

def translate_comp(coords):
    o = min(sorted(coords))
    return set((c[0] - o[0], c[1] - o[1]) for c in coords)

similar = {}
for piece in pieces:
    k = tuple(translate_comp(pieces[piece]))
    if k not in similar: similar[k] = []
    similar[k].append(piece)

seen = set()
states = [(pieces, taken, ())]
while states:
    state = states.pop(0)
    if not goals - state[0]["0"]:
        names = {
            (-1, 0): "L",
            (1, 0): "R",
            (0, 1): "D",
            (0, -1): "U",
        }

        print(len(state[2]))
        print(" ".join(piece + names[d] for d, piece in state[2]))
        break

    for piece in pieces:
        for d in ((-1, 0), (1, 0), (0, 1), (0, -1)):
            new_pieces = state[0].copy()
            new_pieces[piece] = {(c[0] + d[0], c[1] + d[1]) for c in state[0][piece]}
            new_taken = state[1] - state[0][piece]

            # Collision
            if new_pieces[piece] & new_taken:
                continue

            gist = tuple(frozenset().union(*(new_pieces[piece] for piece in similar_set))
                         for similar_set in similar.values())

            if gist in seen:
                continue

            seen.add(gist)
            new_taken |= new_pieces[piece]
            states.append((new_pieces, new_taken, state[2] + ((d, piece),)))


position of the only 1 in a number in binary format Every number of the form 2i (where i is a non-negative integer) has a single 1 in its binary representation. Given such a number, output the 1-based position of the 1.

Examples:

DECIMAL   BINARY    POSITION
--------------------------
1            0001      1
2            0010      2
4            0100      3
8            1000      4

N         0...1...0     ?

Stolen wholesale from Bit twiddling hacks:

uint8_t f(uint32_t v)
{
    static const uint8_t MultiplyDeBruijnBitPosition2[32] = {
          0, 1, 28, 2, 29, 14, 24, 3, 30, 22, 20, 15, 25, 17, 4, 8,
            31, 27, 13, 23, 21, 19, 16, 7, 26, 12, 18, 6, 11, 5, 10, 9
    };
    return MultiplyDeBruijnBitPosition2[(uint32_t)(v * 0x077CB531U) >> 27];
}


ASCII Character Jumble Write a program that takes as its input a string consisting of printable characters (ASCII 20-7E) and an integer n in [2,16] and performs the following modification to the string.

Each character in the string is converted to its ASCII code (the examples given are in hexadecimal, though base 10 is also acceptable).
The ASCII codes are converted to base n and are concatenated together.
The new string is split every other character. If there are an odd number of characters, then the last character is removed entirely.
Printing ASCII codes (in base 16) are converted back into their characters, whereas non-printing ASCII codes are removed.
The resulting string is printed.

Test case

Input

Hello, World!
6

Steps

Hello, World!
48 65 6C 6C 6F 2C 20 57 6F 72 6C 64 21
2002453003003031125222330331030024453
20 02 45 30 03 00 30 31 12 52 22 33 03 31 03 00 24 45

The output of this program is  E001R"31$E.

This is code golf, so standard rules apply. Shortest code in bytes wins.

Pyth - 22 bytes
Hope to golf a lot more, pretty straightforward.
sfq3l`TmCid16csjRQCMz2

Try it online here.


Is it a Rubik's Cube? A venerated pass time of pedants is to point out that pictures of "Rubik's Cubes" (on t-shirts, posters etc.) are not actually solvable.

The first thing that should be checked is that the cube is made up of the right pieces.  To be solvable a cube needs six colors each with nine squares.  The cube also needs each edge and corner unit (these are the smaller cubes that make up the cube) to be unique.  Not only must they be unique but if two center pieces are opposite each other no edge or corner piece can contain both of those colors.

Once you have a cube that is made up of all the right pieces you still need to verify it can be solvable.  There are a couple of rules here, so I'll defer to an expert to explain them, the spoiler below explains how we can do this.  If you are interested in solving the problem on your own you don't need to visit the site to understand or participate in this challenge.

   Linked explanation

Your task is to take a pattern as input and determine if it is in fact a solvable Rubik's cube.  To be solvable there must be a way to perform valid moves on a cube so that the cube has only one color on each face (and the different faces have different colors).  Most Rubik's cubes have a standard coloring (White is opposite Yellow, etc.) you may not assume that the solve state follows this particular coloring.

A valid move is either the clockwise or anti-clockwise rotation of a single face of the cube.  With the rotation of the face of the cube any squares bordering the face are rotated as well, staying connected to the face they were previously touching.

IO

You may take the cube in any reasonable manner.  If your language has some builtin "cube-face" type, good for you, that is fine as input, other wise you can take a 2D array of the net, of the cube, 1 3 by 3 lists for each face.  Just be reasonable.  If you want to know if a specific format is acceptable comment or ping me in chat and I will add to the challenge to state its validity.

Your input format need only support up to 9 possible colors.

For output this is a decision problem so you should output one constant value for "Yes, this is a valid Rubik's cube" and one different constant value for "No, this is not a valid Rubiks cube".

This is code-golf so answers will be scored in bytes with less bytes being better.

Test Cases

Here are test cases.  They are formatted as the net of a cube with each square as a single letter.  Different letters represent different colors.
Any more testcases can be added upon request.

Solvable

   RRR
   RRR
   RRR
GGGWWWBBBOOO
GGGWWWBBBOOO
GGGWWWBBBOOO
   YYY
   YYY
   YYY

   GRR
   GRR
   ORW
WWRBWYBOOGGY
GGRBWGYBBOOO
OOGRWGYWWRBB
   WYO
   YYB
   YYB

Unsolvable

   RRR
   RRR
   RRR
GGGWWWBBBOOO
GGGWWWBBBOOO
GGGWYWBBBOOO
   YWY
   YYY
   YYY

   RRR
   RRR
   RRR
GGGWWWBBBOOO
GGGWWWBBBOOO
GGGWWWBBBOOO
   YWY
   YYY
   YYY

   RRR
   RRR
   GGG
GGYWYWRBBOBO
GGYWWWROBOOO
GGYWWWRBBOOO
   BBB
   YWY
   YYY

   RRW
   RRW
   GGG
GGYWWYEOBROO
GGYWWYEBBROO
GGOWWYWBBROO
   BBB
   YYW
   YYO

Cubically, 1664 1631 1089 bytes

⇒FD2F'R'D2RUR'D2RFD2F'U'
⇒Ff1F'
⇒LFf1F'L'
⇒F'f1F
⇒F2f1F2
⇒L'F2f1F2L
⇒D'F'f1FD
⇒LR'FLR'DLR'B2L'RDL'RFL'RU2
⇒LFf8F'L'
⇒R'F'f8FR
⇒Ff8F'
⇒F'f8F
⇒ULU'f8UL'U'
⇒U'R'Uf8U'RU
⇒F2f8F2
⇒Df15D'
⇒D'f15D
⇒D2f15D2
⇒UF2UF2D'L2B2U'B2DL2F2D2B2D2F2
⇒U'DL2UD'B2
⇒UF2UF2D'L2B2D'R2UR2F2D2B2U2B2
⇒BL'BU2D2F'RF'U2D2
⇒LD'F2U'B2U'RU2R'F2R2F2D'R2DF2D
⇒B2URB2D2B2RB2U'D'L2D'B2
⇒B2LF'U'B2UFL'R2B2U'D2L2D'B2U
⇒B2RB2D2B2RB2U'L2UD'F2U'F2B2
⇒D2R'FUB2U'F'RU2B2D'F2R2UF2UF2
⇒B2R2U'L'D2B2U2R'U2R2F2L2R2UR2
⇒D2L'B2U2F2RUL2U'F2R2U'R2U2F2DL2D'
⇒UB2U'L2DL2B2DB2D'B2
⇒BR'BL2B'RBL2B2
⇒UF2B2U'F2B2U'F2L2R2B2R2
⇒R2U'F2DR2UF2D'R2DF2R2D'F2
⇒U'F2DF2UL2F2DL2DF2L2D2F2
⇒U2D'L2U'F2L2U'B2L2R2U'L2B2
⇒F2D'R2U2L2B2UF2L2U2F2L2UF2R2
⇒[f1]3
⇒[f2f37]3
⇒[f3f38]3
⇒[f4f39]3
⇒[f5f40]3
⇒[f6f41]3
⇒[f7f42]3
⇒[f8f43]2
⇒[f9f44]2
⇒[f10f45]2
⇒[f11f46]2
⇒[f12f47]2
⇒[f13f48]2
⇒[f14f49]2
⇒[f15f50]2
⇒[f16f51]2
⇒[f17f52]2
⇒[f18f53]2
⇒[f19f54]2
⇒[f20f55]3
⇒[f21f56]4
⇒[f22f57]5
⇒[f23f58]6
⇒[f24f59]7
⇒[f25f60]8
⇒[f26f61]9
⇒[f27f62]9[f27f62]2
⇒[f28f63]9[f28f63]3
⇒[f29f64]9[f29f64]4
⇒[f30f65]2
⇒[f31f66]3
⇒[f32f67]4
⇒[f33f68]5
⇒[f34f69]6
⇒[f35f70]7
rs[f36f71]8

Output if solvable: Solved!
Output if unsolvable: (empty, no output)

Input should be formatted as a Cubically cube-dump (see the Debug section). This was explicitly allowed by the OP.

Explanation

This program takes the approach of using a Devil's Algorithm to iterate over every possible state of the cube in the same group as the solved cube. If the cube is solvable, it will be solved at some point before the algorithm has finished (assuming the algorithm I used works properly).

Every line beginning with ⇒ (0x84 in Cubically's codepage) is a function definition; these functions build off of each other to make up the actual Devil's Algorithm. The first line to be executed is the last one:

rs[f36f71]8

r reads a cube from stdin and sets the memory cube to it. s puts the interpreter into "solvemode", which means that it exits and prints Solved! if the cube becomes solved (after being unsolved) at any point. The rest of the commands (which simply repeat f36f71 8 times) correspond to the final algorithm at the bottom of the linked page:

(D) = (CP) = (CPT8) = [(CPC8)(CPT7)]8 (3,847,762,288,469,010,006,992 moves)

(D) is the Devil's Algorithm. If you apply it to the cube, it will be solved at some point before you have done the algorithm once. As you can see, it is terribly long, nearly a thousand times more moves than there are possible positions.

How can I run it?

You can try it online, but that link doesn't work. TIO will almost definitely time out before this algorithm finishes (the maximum runtime for an interpreter is 60 seconds). If the cube is not solvable, this algorithm will take up to 11 million years for Cubically to finish (at ~15.2 million moves per second, which is what my Cloud9 IDE gets).

Additionally, you need a lot of memory to perform 3 sextillion moves. Cubically can perform about 4 million moves per second, but the process will most likely be killed due to overcommitted memory. It dies after 15 seconds on my VM with 512MB of memory. Why should performing moves on an already-allocated flat array cost memory? Found a memory leak (or twenty) and fixed it.

Here is a much more readable version that behaves the same way.

But I really want to see that it works!

The first actual move that is executed in this devil's algorithm is F2, so the quickest cube to solve would be one scrambled with F2:

   000
   000
   555
113222133444
113222133444
113222133444
   000
   555
   555

This indeed executes in 0.007 seconds on TIO.

How can this be improved?

There are certainly more devil's algorithms; I've found one that uses less than a thirtieth of the moves this one does. However, that would come at the cost of several thousand bytes (around 100MB more) and several dozen hours of converting a complex Hamiltonian circuit to Cubically code.

It's also possible to remove some of the functions and put them straight in the loop at the bottom. However, I'm going to sacrifice some bytes for some readability.

Additionally, I'm considering a modification of Cubically's looping behavior so that I can more easily repeat algorithms 7 or 8 times (instead of just hard-coding them with the function calls repeated 7 or 8 times in the source). Or I'll work some magic out with the notepad, and golf this using more loops.

Note that I will continue to optimize anything possible in the interpreter, so this may work on an average PC sometime in the future!

Cubically, 2 bytes

r▦

I like the above answer better so I'm adding this as an alternate solution. This runs in under a second, as opposed to a few million years.

r    read cube from standard in
 ▦   and solve it

Output if the cube is solvable: (nothing)
Output if the cube is unsolvable: Error: The cube has reached an unsolvable state.


Convert CMYK values to RGB Given Color codes in CMYK, convert it to RGB value.
Input:
string of 4 integers(ranging from 0-100) separated by space
86 86 0 43
28 14 0 6
0 41 73 4

Output:
#141592
#ABCDEF
#F49043

Shortest code wins!

HINT: For converting CMYK to RGB you may use formula such as:
Red   = 255 x (1 - Cyan/100)    x (1 - Black/100)
Green = 255 x (1 - Magenta/100) x (1 - Black/100)
Blue  = 255 x (1 - Yellow/100)  x (1 - Black/100)

and use these three variables to get the value in #RRGGBB format