Interpreting Fish (no, not that Fish) Consider these five ASCII art sea creatures:

Standard fish: ><> or <><
Speedy fish: >><> or <><<
Sturdy fish: ><>> or <<><
Stretchy fish: ><<<> or <>>><
Crab: ,<..>,

Write a program that accepts an arbitrary string of the characters <>,.. If there is a way to interpret the entire string as a series of non-overlapping sea creatures, then the string should be reprinted with single spaces inserted between creatures. If this interpretation is impossible, nothing should be output (the program silently ends).
For example, the string <><><> can be interpreted as two standard fish back-to-back. The corresponding output would be <>< ><>.
As another example, the string ><>><>> contains "instances" of...
(brackets only added as indicators)

a couple standard fish: [><>][><>]>
a speedy fish: ><[>><>]>
a sturdy fish in a couple ways: [><>>]<>> and ><>[><>>]

however, only the pairing of a standard fish and a sturdy fish [><>][><>>] spans the entire length of the string with no fish sharing characters (no overlaps). Thus the output corresponding to ><>><>> is ><> ><>>.
If there are multiple ways the string could be interpreted, you may print any one of them. (And only print one of them.) For example, <><<<>< can be interpreted as a standard fish and a sturdy fish: [<><][<<><], or as a speedy fish and a standard fish: [<><<][<><]. So either <>< <<>< or <><< <>< would be valid output.

The crabs are just for fun. Since they don't start or end with < or >, they are much easier to identify (at least visually). For example, the string
,<..>,><<<>,<..>,><>,<..>,<>>><,<..>,><>>,<..>,<<><,<..>,<><,<..>,>><>

would obviously produce the output
,<..>, ><<<> ,<..>, ><> ,<..>, <>>>< ,<..>, ><>> ,<..>, <<>< ,<..>, <>< ,<..>, >><>

Here are some examples of strings (one per line) that produce no output:
<><>
,<..>,<..>,
>>><>
><<<<>
,
><><>
,<><>,
<<<><><<<>>><>><>><><><<>>><>><>>><>>><>><>><<><

The last string here can be parsed if you remove the leading <:
<<>< ><<<> >><> ><> ><> <>< <>>>< >><> >><> >><> ><>> <<><

(There may be other possible outputs.)
Details

The input string will only contain the characters <>,..
The input string will be at least one character long.
Take input in any common way (command line, stdin) and output to stdout.
The shortest code in bytes wins. (Handy byte counter.) Tiebreaker is earlier post.

Non-deterministic Turing Machine, 20 states, 52 transitions (882 bytes maybe)
How do you convert this to bytes? I've written the files (absolutely not golfed) to execute this machine with Alex Vinokur's Simulator of a Turing Machine1. wc -c outputs the following (excluding the description file and the input files):
 12 alphabet
 49 meta
740 rules
 81 states
882 total

Anyways, I was preparing for my Computer Science A-Levels, so I thought this would be a good exercise (I don't know what I was thinking). So here's the definition:
$$\begin{align*}
M & = (Q, \Sigma, \iota, \sqcup, A, \delta) \\
Q & = \{q_{0},q_{1},q_{2},q_{3},q_{4},q_{5},q_{6},q_{7},q_{8},q_{9},q_{10},q_{11},q_{12},q_{13},q_{14},q_{15},q_{16},q_{17},q_{18},q_{19}\} \\
\Sigma & = \{< \: ; \: > \: ; \: , \: ; \: . \: ; \: X \: ; \: $\} \\
\iota & = q_0 \\
\sqcup & = $ \\
A & = \{q_0, q_5\}
\end{align*}$$

(the transition function)
Excuse the bad image, but I couldn't be bothered with redrawing this thing on a computer. If you actually want to decipher the transition rules, I recommend you read through the rules file I linked above.

I've used Xs instead of spaces because spaces are hard to visualize here and the simulator doesn't accept spaces in the alphabet.
The concept is fairly simple - q1 to q4 are used to catch right-facing fishes, q11 to q14 are used to catch left-facing fishes, q15 to q19 for crabs and the q5 to q10 blob is simply for inserting a space and moving all following characters one to the right.
If the string is interpretable, it accepts the string and the tape contains the string with spaces inserted. Otherwise it rejects the string (I guess this counts as no output - emptying the tape would be pretty easy but would require lots of transition rules and I don't think it would make the transition function prettier to look at).

1 Note: It's difficult to compile. I had to edit the src/tape.cpp file and replace LONG_MAX with 1<<30 and then go to the demo directory, edit the Makefile to replace EXE_BASENAME with turing.exe and execute make. Then go to the directory with the files I've written and execute /path/to/turing/download/src/turing.exe meta.


Serial voting detection Stack Exchange automagically detects serial
voting (when one user either
upvotes or downvotes many of another user's posts) and reverses it. In this
challenge, you will implement a very, very simple "serial vote" detector.

Input

The input is a string representing a list of votes. Every group of two
characters represents a vote—the first one is the voter, and the second is the
user being voted on. For example, the following input

ababbccd

can be parsed as ab ab bc cd, and represents a voting on b twice,
b voting on c once, and c voting on d once.

The input will consist of only lowercase letters, and it will always be an even
length > 0. You also can't vote on yourself (so no aa or hh).

Output

For the purposes of this challenge, serial voting is defined as any given
user voting on any other user three or more times.

The output is how many votes should be reversed for each user (that is, how
many votes on each user were reversed, not how many votes that they have
given were reversed), in the format [user][votes][user2][votes2].... For
example, an input of abababab (a voting on b four times) should output
b4 (four votes have been reversed from a to b).

The output may be in any order you would like, but both the input and output
must be single strings as described above.

Test cases

In                            Out
---------------------------------------------------------------------------
abababcbcbcbcbbababa          b7a3
edfdgdhdfgfgfgih              g3
jkkjjkkjjkkjljljljmlmlnmnmnm  j6k3m3
opqrstuv                      <none>
vwvwwvwv                      <none>
xyxyxyxyxyxyxyzyzyzyxzxzxz    y10z3
nanananananananabatman        a8
banana                        <none>


How many switches are ON A class has N student and the class room has N switches (all turned OFF and numbered 1 to N). Each student has an enrollment number assigned from 1 to N. Each student serially (by number) toggles the switches that has a number which is divisible by his/her enrollment number.

Example: Student 1 will turn all the switches ON. Student 2 will turn all even switches OFF. Student N just toggles the Nth switch.

Write a function that takes N as input as returns number of ON switches.
sample I/O

Input: 10
Output:3

No upper bound for N is given, but greater the scope, better the code. Shortest and innovative function wins

Python, 19 characters
f=lambda n:n**.5//1

Perfect squares are the only numbers with an odd number of divisors.
This used to be a 21-character answer:
f=lambda n:int(n**.5)

but since I originally wrote it in 2011, the floor-division // operator was introduced, which can replace the int call.
As a consequence, the answer is now returned as a floating-point number. (But f(10) == 3.0 is still a correct number of lockers!)


Decode MD5, Brute Force The Challenge

Create a program that brute-force* decodes the MD5-hashed string, given here:
92a7c9116fa52eb83cf4c2919599c24a which translates to code-golf

The Rules

You may not use any built-in functions that decode the hash for you if
the language you choose has such.
You may not use an online service to decode the hash for you.
This is code-golf, the program that accomplishes
the task in the shortest amount of characters wins.

Good luck. May the brute-force be with you.

*Brute-Force definition: looping from a-zzz.. including abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890-=[]\;',./~!@#$%^&*()_+{}|:"`<>? in a string, hashing it, and testing it against the hash given until the correct string that has been hashed has been found. Print the string to the program's output stream.

Haskell, 101 characters

import Data.Hash.MD5
main=interact$ \m->head.filter((==m).md5s.Str)$iterate([' '..'~']:)[]>>=sequence

Use it like so:

& ghc -O2 -o brute 42043-BruteForce.hs
& echo -n c-g | md5
bc098aea57599de26c8f17a9edbd492e
& echo -n bc098aea57599de26c8f17a9edbd492e | ./brute
c-g

This requires the common package MissingH.


Generate a valid equation using user-specified numbers This is based on a game one of my math teachers used to play in middle school. He would write 5 random one-digit numbers on the board, and then a random two-digit number. We would try to create an equation that used all 5 of the one-digit numbers to yield the two-digit number.
Here are some examples with solutions to explain this better:

Input:           Solution:
7 5 4 8 4 34     5*8-7+4/4 = 34
3 1 5 7 6 54     (7+3)*6-5-1 = 54
3 9 2 1 6 87     9*(2+1)*3+6 = 87
2 1 6 9 7 16     (9-7+6*1)*2 = 16
2 4 5 8 6 96     8*(5+6)+2*4 = 96
3 8 4 5 4 49     8*(4+4)-3*5 = 49

This challenge is to write a program that can generate such equations for a given input.
The input can be provided either via the command line or via a prompt. The 5 one-digit numbers will always be entered first (in no particular order), followed by the two-digit number. The program will then print out a solution equation it finds; you do not have to handle situations where there is no solution. The function must be capable of using the following operations in the equation: addition, subtraction, multiplication, and division. If you would like to allow additional basic operations, that's fine as long as they remain in the spirit of the challenge (negation, exponentiation, and modulus would be nice additions). Order of operations follows the standard math rules, so parenthesis will be needed for grouping.
The program must take less than a minute to run on a modern computer.

Programs will be scored based on code length (including required whitespace).
Note: division must be exact, not rounded or truncated to nearest integer.

Python 2.7 (284), Python 3.x (253)

from __future__ import division #(Remove for Python 3.x)
from itertools import *
a=raw_input().split()
for i in permutations(a[:-1],5):
 for j in product('+-*/',repeat=5):
  for k,l in combinations(range(1,12,2),2):
   d=''.join(sum(zip(i,j),()))[:-1];d='('+d[:l]+')'+d[l:]
   if eval(d)==int(a[-1]):print d;b

It gives an error (calling unknown function b) on solution.

Basically, it's a gigantic brute force. It takes in the input, splits it by its spaces (1 2 -> [1,2]), and then permutes through that list. With every permutation, it will iterate through all possible strings of length 5 using the characters +-*/. With each of those iterations, it will generate the combinations of length 2 of the list [1,3,5,7,9,11], interweave the permutation and the string together (12345 *-/+- -> 1*2-3/4+5-), and put in the parentheses. Finally, it will evaluate it, and if the answer and equation are true, then it prints the equation and stops.

This is horribly inefficient, about O(n!/(n-5)!)=O(n^5), but it runs in a reasonable time for the test inputs.


A Basic Pyth-like Syntax Checker Pyth is a golfing language based on Python. It uses prefix notation, with each command having a different arity (number of arguments it accepts).

Your task is to write a syntax checker for a (non-existent) Pyth-like language, Pith.

Pith's syntax

Pith only has 8 single-char commands:

01234()"

01234 each have arity of the corresponding number, and hence expect that many arguments after it. For example,

400010

is a correct Pith program because 4 is followed by four arguments 0 0 0 and 10, the last of which is a 1 followed by the single argument 0. To visualise this, we can look at the following tree:

      R
      |
      4
      |
-------------
|   |   |   |
0   0   0   1
            |
            0

where R is the root node. An alternative way to think about this is that each number refers to the number of children the corresponding node has in the tree above.

Here's another valid Pith program, with more than one base command:

210010

corresponding to

           R
           |
     -------------
     |           |
     2           1
     |           |
 ---------       0
 |       |
 1       0
 |
 0

On the other hand,

3120102100

is not a correct Pith program because the initial 3 only has two arguments, which we can see by looking at the tree below:

                R
                |
                3
                |
     ------------------------ ??
     |          |
     1          2
     |          |
     2        ------
     |        |    |
   ------     1    0
   |    |     |
   0    1     0
        |
        0

Next ( starts an unbounded, and ) ends an unbounded. An unbounded takes any number of arguments (greedily), and counts as a single argument to any parent command. Any unboundeds still open by the end of the program are automatically closed. A ) command is not an error if no unboundeds are open — it just does nothing.*

For instance, the Pith program

)31(0)0(201000100

corresponds to the tree

            R
            |
            3
            |
    ------------------------------
    |       |                    |
    1       0                    (
    |                            |
    (              -----------------------------
    |              |      |      |      |      |
    0              2      0      0      1      0
                   |                    |
                -------                 0
                |     |
                0     1
                      |
                      0

Empty unboundeds are okay, so () is a valid Pith program.

An invalid Pith program with an unbounded is

12(010

since the 2 only receives one argument (the unbounded).

Finally, " starts and ends a string, which is always 0 arity and counts as a single argument, e.g.

2"010""44)()4"

which is just a 2 being passed two string arguments "010" and "44)()4". Like unboundeds, strings may also be empty, and any unclosed strings by the end of the program are automatically closed.

*This part is different from the original Pyth which actually does do something in a case like 1), ending the 1-arity and raising an error.

Input/output

Input will be a single non-empty string consisting of only the characters 01234()". You may optionally assume that an additional trailing newline is always present. You may write a function or a full program for this challenge.

You should output a truthy value if the input is syntactically valid Pith, or a falsy value otherwise. The truthy and falsy values must be fixed, so you can't output 1 for one valid program and 2 for another.

Scoring

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

Test cases

Truthy:

0
)
(
"
()
""
10
400010
210010
("")00
3"""""
(0)))0)1)0
2(2(2(0)0)0)0
2"010""44)()4"
)31(0)0(201000100
())2)1))0"3())"))
3("4321("301(0)21100"4")"123"00)40"121"31000""01010

Falsy:

1
1(310
(1)0)
12(010
4"00010"
3120102100
20(2((0)(0)))
2(2(2(0)0)0)01)
4(0102)00)00000
2"00"("00"2(""))

CJam, 65 bytes

q'"/La+2%{0s*}:Z~_,:L')*+{L{4{)_Z+s/Z}/L{'(\Z')++/Z}/}*')-}2*0s-!

Gosh, I wish CJam had Regex, this could have been completed in less than 50 bytes then

The main idea is to keep reducing stuff to 0 i.e. 10 to 0, 200 to 0 and so on. Once that is done, we reduce all matched brackets to 0, i.e. () to 0, (0) to 0, (00) to 0 and so on. The we repeat the cycle L times, where L is the input length.

The input string initially goes through extra processing where we adjust for unmatched " and add lots of ) to compensate for unmatched (

This ensures that after all the iterations, we should only have 0 (and no-op )) left in the string.

Update - fixed a bug where top level ) no-op are considered harmful

Code expansion

q'"/La+2%{0s*}:Z~_,:L')*      "Part 1 - Preprocessing";
q'"/                          "Read the input and split it on quote";
    La+                       "Add an extra empty array to the split array to compensate";
                              "for unmatched ending quote";
        2%                    "Take every other splitted part, ignoring the contents";
                              "of the strings in the code";
          {0s*}:Z~            "Join the parts by string 0. Also create a function Z";
                              "that does that for future use. We are now done with";
                              "reducing "XYZ" to 0 ";
                  _,:L        "Store the length of the remaining code in L";
                      ')*     "Append L ) to the string to compensate for unmatched (";

{L{4{)_Z+s/Z}/L{'(\Z')++/Z}/}*')-}2*   "Part 2 - the reducing loop";
 L{                         }*         "Run the reduction logic L times";
   4{)_Z+s/Z}/                         "Part 2a - reducing arities";
   4{       }/                         "Run the iteration for 0, 1, 2 and 3";
     )_                                "Increment the iteration number and make a copy";
       Z+s                             "Get that many 0 and append it to the number";
          /Z                           "Split the code onto this number and convert it";
                                       "to 0. This successfully reduces 10, 200, ";
                                       "3000 and 4000 to 0";
              L{'(\Z')++/Z}/           "Part 2b - reducing groups";
              L{          }/           "Run the iteration for 0 through L - 1";
                '(\Z')++               "Get the string '(<iteration number of 0>)'";
                        /Z             "split on it and join by 0. This successfully";
                                       "reduces (), (0), (00) and so on .. to 0";
                              ')-      "After running the part 2 loop L times, all";
                                       "reducible arities and brackets should be reduced";
                                       "except for cases like '30)00' where the no-op )";
                                       "breaks the flow. So we remove ) from the code";
                                       "and run Part 2 L times again";

0s-!                          "Now, if the code was valid, we should only have 0 in the";
                              "remaining code. If not, the code was invalid";

Try it online here or run the whole suite


count number of valid, unique sequences for moving on a 1xn board There's a board with n squares in a horizontal row.

You start in the leftmost square, and roll a 3-faced dice.

3 possible outcomes for a single roll of the die:

Left: you move 1 step to the left, if possible.
None: you stay where you are
Right: you move 1 step to the right, if possible.

You want to roll the dice exactly t times, and end up at the rightmost square on the last roll.

If you arrive at the rightmost square before t rolls, your only valid move is None.

You need to determine the number of valid (meaning, for instance, that you don't count sequences that try to move left or right from the rightmost square), unique sequences of dice rolls, for given (t,n) pairs. As the answer may be large, give it modulo 1000000007 (ie. 10^9+7).

t is a positive integer s.t. t <= 1000
n is a positive integer s.t. 2 <= n <= 1000

Sample testcases:

t=1, n=2, answer=1
t=3, n=2, answer=3
t=4, n=3, answer=7

The shortest code in bytes wins.

Python, 74

f=lambda t,n,i=1:i==n or t*i and sum(f(t-1,n,i+d)for d in[-1,0,1])%(1e9+7)

A recusive solution. The current position i is stored 1-indexed as an optional argument.

If the current position i==n, we've arrived at the final square and are forced to stay still, giving 1 path.
Otherwise,

If the remaining time t==0, we've run out of time, so there's 0 paths.
If the current position i==0, we've run off the left end already, so there's 0 paths.

If neither of those was true, there we recurse. We add up the path counts for each of the directions left, none, and right, corresponding to displacements [-1,0,1], and take the result modulo 1e9+7 as required.

An alternative solution that uses eval with string substitution to do the sum. Same number of chars. Note the use of unary + to start the sum.

f=lambda t,n,i=1:i==n or t*i and eval(3*'+f(t-1,n,i+%d)'%(-1,0,1))%(1e9+7)

Here's another a solution that is surely short for any language with built-in matrices, so anyone who can golf it is welcome to take it.

Let M be the n*n transition matrix for the walk, which is a tridiagonal banded matrix with 1's on the main diagonal and the diagonals above and below it, except for a 0 for movement left from the rightmost cell.

1 1 0 0 0
1 1 1 0 0
0 1 1 1 0
0 0 1 1 1
0 0 0 0 1

Then, the output is (1,n) entry of the matrix power M^t.


The Banach–Tarski Paradox The Banach–Tarski paradox states that, given a ball in 3‑dimensional space, you can decompose the ball into a finite number of point subsets. These disjoint sets of points can then be reassembled to produce two copies of the initial ball. You would then, theoretically, have two identical balls.

The process of reassembly consists of only moving the aforementioned point subsets and rotating them, while not changing their spacial shape. This can be done with as few as five disjoint subsets.

Disjoint sets have no common elements by definition. Where A and B are any two point subsets of the initial ball, the common elements between A and B is an empty set. This is shown in the following equation.

For the disjoint sets below, the common members form an empty set.

The Challenge

Write a program that can take an input ASCII "ball", and output a duplicate "ball".

Input

Here is an example input ball:

      ##########
   ###@%$*.&.%%!###
  ##!$,%&?,?*?.*@!##
 ##&**!,$%$@@?@*@&&##
#@&$?@!%$*%,.?@?.@&@,#
#,..,.$&*?!$$@%%,**&&#
 ##.!?@*.%?!*&$!%&?##
  ##!&?$?&.!,?!&!%##
   ###,@$*&@*,%*###
      ##########

Each sphere is outlined by pound signs (#) and filled with any of theses characters: .,?*&$@!%. Every input will be a 22x10 characters (width by height).

Creating a Duplicate

First, each point inside the ball is given a numbered point based on its index in .,?*&$@!%. Here is the above example, once numbered:

      ##########
   ###7964151998###
  ##86295323431478##
 ##5448269677374755##
#75637896492137317572#
#21121654386679924455#
 ##1837419384568953##
  ##85363518238589##
   ###2764574294###
      ##########

Then, each point is shifted up one (nine goes to one):

      ##########
   ###8175262119###
  ##97316434542589##
 ##6559371788485866##
#86748917513248428683#
#32232765497781135566#
 ##2948521495679164##
  ##96474629349691##
   ###3875685315###
      ##########

Finally, each new point value is converted back to its corresponding character:

      ##########
   ###!.@&,$,..%###
  ##%@?.$*?*&*,&!%##
 ##$&&%?@.@!!*!&!$$##
#!$@*!%.@&.?,*!*,!$!?#
#?,,?,@$&*%@@!..?&&$$#
 ##,%*!&,.*%&$@%.$*##
  ##%$*@*$,%?*%$%.##
   ###?!@&$!&?.&###
      ##########

Output

These two balls are then output side-by-side, in this form (separated by four spaces at the equators):

      ##########                ##########
   ###@%$*.&.%%!###          ###!.@&,$,..%###
  ##!$,%&?,?*?.*@!##        ##%@?.$*?*&*,&!%##
 ##&**!,$%$@@?@*@&&##      ##$&&%?@.@!!*!&!$$##
#@&$?@!%$*%,.?@?.@&@,#    #!$@*!%.@&.?,*!*,!$!?#
#,..,.$&*?!$$@%%,**&&#    #?,,?,@$&*%@@!..?&&$$#
 ##.!?@*.%?!*&$!%&?##      ##,%*!&,.*%&$@%.$*##
  ##!&?$?&.!,?!&!%##        ##%$*@*$,%?*%$%.##
   ###,@$*&@*,%*###          ###?!@&$!&?.&###
      ##########                ##########

Note: Shifting the point values, and later characters, is symbolic of the rotations performed to reassemble the point subsets (character groupings).

Pyth, 21 bytes

#++Jw*4d.rJ".,?*&$@!%

Try it online: Demonstration

Finally a use-case for .r.

Explanation

#++Jw*4d.rJ".,?*&$@!%
#                       infinite loop
   Jw                   read a string from input and store it in J
     *4d                4 spaces
        .rJ".,?*&$@!%   rotate the chars of J using this char order
 ++                     combine the 3 strings (J, spaces, rotated) and print

The infinite loop breaks, when there is no more input available.


How much weight can you lift? With all the gyms closed down with the COVID-19 situation, we have to exercise with the weight we have lying around at home. The problem is, we have a small selection of plates at varying weights, and can't immediately determine if we can create a setup at the desired weight.

Given an unsorted array of weighted plates and an unsorted array of barbells of different weights, determine the fewest amount of plates you need to put on a barbell to reach the desired weight, in ascending order mirrored at the halfway point, basically mirroring how it would be loaded on a real barbell (see example output). The plates have to be in pairs; you cannot use a particular plate an odd number of times since you put one plate on each side for equilibrium (e.g. every plate of a certain weight on one side should have a counterpart of the same weight on the otherside). If the desired weight cannot be achieved, approximate as closely as possible (while still maintaining equilibrium on both sides).

Examples:

Input (3 barbells, a set of plates, and goal weight): [[10, 45, 6], [3.5,37,20,15,2.5,15,2.5,3.5,5,7], 47]

Output (exact match, barbell and plate arrangement): [10, [3.5,15,15,3.5]

Input (3 barbells, a set of plates, and goal weight): [[10, 45, 6], [3.5,37,20,15,2.5,15,2.5,3.5,5,7], 45]

Output (exact match, barbell and plate arrangement): [45, []]

Input (3 barbells, a set of plates, and goal weight): [[10, 45, 6], [3.5,37,20,15,2.5,15,2.5,3.5,5,7], 0]

Output (closest approximation, barbell and plate arrangement): [6, []]

Input (3 barbells, a set of plates, and goal weight): [[10, 45, 6], [3.5,37,20,15,2.5,15,2.5,3.5,5,7], 9001]

Output (closest approximation, barbell and plate arrangement): [45, [2.5,3.5,15,15,3.5,2.5]]

Winners will be selected first by time complexity, then character count for tie-breaker.

Python 2, \$ O(2^{\frac{|W|}2} \cdot |B| \cdot |W| + |W|^2) \$, 203 bytes

Naive implementation, looks at all combinations of possible weights \$W\$ and barbells \$B\$.

lambda B,W,T:min([(w+w[::-1],b)for w in p(sorted(sum([W.count(x)/2*[x]for x in set(W)],[])))for b in B],key=lambda(a,b):((T-sum(a)-b)**2,len(a)))
p=lambda l:l and[l[:1]+x for x in p(l[1:])]+p(l[1:])or[l]

Try it online!

Ungolfed

def f(Barbells, Weights, Target):
  # For every pair of same weights keep one, order them ascending
  usable_weights = concat([Weights.count(x)/2 * [x] for x in set(Weights)])
  usable_weights = sorted(usable_weights)

  # list all possible combinations of symmetric weights and barbells
  possible_setups = [(w+w[::-1], b)for w in powerset(usable_weights)for b in Barbells]

  # Find the one with the weight being the closest to the target,
  # on a tie take the one with the lowest number of weights
  return min(possible_setups, key=lambda(a,b): ((Target - sum(a) - b)**2, len(a)))

concat = lambda ls:sum(ls, [])
powerset = lambda l:l and [l[:1]+x for x in powerset(l[1:])]+powerset(l[1:]) or [[]]

Try it online!


Robot roadie needed to pack the truck As the band's roadie, you have to pack the truck. Your program will place the packages so that they fit in the smallest height.

A badly packed truck

Rules

Packages may be rotated through multiples of 90 degrees. Packages may touch but must not overlap.

The output is the repacked image (to file or stdout). Your program may use any input or output raster image format.

Your program must accept any number of packages of various shapes in images up to 4000x4000 pixels. It must not be hardcoded for this test image. If I suspect any submission to be tailored towards this specific image, I reserve the right to replace it by a new test image.

Score

Your score is the smallest height of a rectangle that will contain your arrangement (the width is the input rectangle width). In the case of a tie, the earliest entry wins.

Standard loopholes are prohibited as usual.

Language : Java
Score : 555 533
I just went for trying to brute force a solution by iterating over the shapes in order of decreasing area (perimeter in case of tie) and trying out all packing possibilities until a valid packing is found for that shape at which point the shape's position is fixed and the algorithm goes on to the next shape. In order to hopefully improve the quality of the result when searching for a valid packing first all possible positions are tried with the shape rotated such that it is taller than it is wider.
Note: this assumes that the input image(s) have all of the shapes separated by white space. It takes the maximum width of the output as the first argument and a list of shape images as the other arguments (each shape image can have one or more shape separated by at least one line of white pixels)
import java.awt.Color;
import java.awt.Graphics;
import java.awt.geom.AffineTransform;
import java.awt.geom.Point2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Set;

import javax.imageio.ImageIO;

public class Packer {
    public static void main(String[] args) throws Exception {
        long t1 = System.currentTimeMillis();

        int width = Integer.valueOf(args[0]);
        List<Item> itemList = new ArrayList<Item>();
        for (int i = 1; i < args.length; i++) {
            itemList.addAll(getItems(ImageIO.read(new File(args[i]))));
        }

        File outputFile = new File("output.png");
        if (outputFile.exists()) {
            outputFile.delete();
        }
        outputFile.createNewFile();

        ImageIO.write(pack(itemList, width), "PNG", outputFile);
        long t2 = System.currentTimeMillis();
        System.out.println("Finished in " + (t2 - t1) + "ms");
    }

    private static BufferedImage pack(List<Item> itemList, int width) {
        System.out.println("Packing " + itemList.size() + " items");
        Collections.sort(itemList, new Comparator<Item>() {

            @Override
            public int compare(Item o1, Item o2) {
                return o1.area < o2.area ? 1 : (o1.area > o2.area ? -1
                        : (o1.perimiter < o2.perimiter ? 1
                                : (o1.perimiter > o2.perimiter ? -1 : 0)));
            }
        });
        Packing packing = new Packing(width);
        PackedItem.Rotation[] widthRots = { PackedItem.Rotation.ZERO,
                PackedItem.Rotation.ONE_EIGHTY };
        PackedItem.Rotation[] heightRots = { PackedItem.Rotation.NINETY,
                PackedItem.Rotation.TWO_SEVENTY };
        int count = 0;
        for (Item item : itemList) {
            count++;
            int minSize = Math.min(item.width, item.height);
            int maxSize = Math.max(item.width, item.height);
            int x = 0;
            int y = 0;
            int rot = 0;
            PackedItem.Rotation[] rots = widthRots;
            if (item.width > item.height) {
                rots = heightRots;
            }
            boolean rotsSwitched = false;

            PackedItem packedItem = new PackedItem(item, rots[rot], x, y);
            System.out.format("Packing item %d which is %d by %d\n", count,
                    item.width, item.height);
            while (!packing.isValidWith(packedItem)) {
                if (rot == 0) {
                    rot = 1;
                } else {
                    rot = 0;
                    if (x + minSize >= width) {
                        x = 0;
                        y++;
                        if (!rotsSwitched
                                && y + maxSize > packing.height) {
                            rotsSwitched = true;
                            if (item.width > item.height) {
                                rots = widthRots;
                            } else {
                                rots = heightRots;
                            }
                            y = 0;
                        }
                    } else {
                        x++;
                    }
                }
                packedItem.set(x, y, rots[rot]);
            }
            packing.addItem(packedItem);
            System.out.format("Packed item %d\n", count);
        }
        return packing.getDrawing();
    }

    private static List<Item> getItems(BufferedImage image) {
        List<Item> itemList = new ArrayList<Item>();
        boolean[][] pointsProcessed = new boolean[image.getWidth()][image
                .getHeight()];

        for (int i = 0; i < image.getWidth(); i++) {
            for (int j = 0; j < image.getHeight(); j++) {
                if (pointsProcessed[i][j]) {
                    continue;
                }
                ImagePoint point = ImagePoint.getPoint(i, j, image);
                if (point.getColor().equals(Color.WHITE)) {
                    pointsProcessed[point.x][point.y] = true;
                    continue;
                }
                Collection<ImagePoint> itemPoints = new ArrayList<ImagePoint>();
                Queue<ImagePoint> pointsToProcess = new LinkedList<ImagePoint>();
                pointsToProcess.add(point);
                while (!pointsToProcess.isEmpty()) {
                    point = pointsToProcess.poll();
                    if (pointsProcessed[point.x][point.y]) {
                        continue;
                    }
                    pointsProcessed[point.x][point.y] = true;
                    if (point.getColor().equals(Color.WHITE)) {
                        continue;
                    }
                    itemPoints.add(point);
                    pointsToProcess.addAll(point.getNeighbors());
                }
                itemList.add(new Item(itemPoints));
            }
        }

        return itemList;
    }

    private interface Point {
        int getX();

        int getY();

        Color getColor();
    }

    private static final class ImagePoint implements Point {
        private static final Map<BufferedImage, Map<Integer, Map<Integer, ImagePoint>>> POINT_CACHE = new HashMap<BufferedImage, Map<Integer, Map<Integer, ImagePoint>>>();
        private final int x;
        private final int y;
        private final Color color;
        private final BufferedImage image;
        private Collection<ImagePoint> neighbors;

        private ImagePoint(int x, int y, BufferedImage image) {
            this.x = x;
            this.y = y;
            this.image = image;
            this.color = new Color(image.getRGB(x, y));
        }

        static ImagePoint getPoint(int x, int y, BufferedImage image) {
            Map<Integer, Map<Integer, ImagePoint>> imageCache = POINT_CACHE
                    .get(image);
            if (imageCache == null) {
                imageCache = new HashMap<Integer, Map<Integer, ImagePoint>>();
                POINT_CACHE.put(image, imageCache);
            }
            Map<Integer, ImagePoint> xCache = imageCache.get(x);
            if (xCache == null) {
                xCache = new HashMap<Integer, Packer.ImagePoint>();
                imageCache.put(x, xCache);
            }
            ImagePoint point = xCache.get(y);
            if (point == null) {
                point = new ImagePoint(x, y, image);
                xCache.put(y, point);
            }
            return point;
        }

        Collection<ImagePoint> getNeighbors() {
            if (neighbors == null) {
                neighbors = new ArrayList<ImagePoint>();
                for (int i = -1; i <= 1; i++) {
                    if (x + i < 0 || x + i >= image.getWidth()) {
                        continue;
                    }
                    for (int j = -1; j <= 1; j++) {
                        if ((i == j && i == 0) || y + j < 0
                                || y + j >= image.getHeight()) {
                            continue;
                        }
                        neighbors.add(getPoint(x + i, y + j, image));
                    }
                }
            }
            return neighbors;
        }

        @Override
        public int getX() {
            return y;
        }

        @Override
        public int getY() {
            return x;
        }

        @Override
        public Color getColor() {
            return color;
        }
    }

    private static final class Item {
        private final Collection<ItemPoint> points;
        private final int width;
        private final int height;
        private final int perimiter;
        private final int area;

        Item(Collection<ImagePoint> points) {
            int maxX = Integer.MIN_VALUE;
            int minX = Integer.MAX_VALUE;
            int maxY = Integer.MIN_VALUE;
            int minY = Integer.MAX_VALUE;
            for (ImagePoint point : points) {
                maxX = Math.max(maxX, point.x);
                minX = Math.min(minX, point.x);
                maxY = Math.max(maxY, point.y);
                minY = Math.min(minY, point.y);
            }
            this.width = maxX - minX;
            this.height = maxY - minY;
            this.perimiter = this.width * 2 + this.height * 2;
            this.area = this.width * this.height;
            this.points = new ArrayList<ItemPoint>(points.size());
            for (ImagePoint point : points) {
                this.points.add(new ItemPoint(point.x - minX, point.y - minY,
                        point.getColor()));
            }
        }

        private static final class ItemPoint implements Point {
            private final int x;
            private final int y;
            private final Color color;

            public ItemPoint(int x, int y, Color color) {
                this.x = x;
                this.y = y;
                this.color = color;
            }

            @Override
            public int getX() {
                return x;
            }

            @Override
            public int getY() {
                return y;
            }

            @Override
            public Color getColor() {
                return color;
            }
        }
    }

    private static final class PackedItem {
        private final Collection<PackedPoint> points;
        private Rotation rotation;
        private int x;
        private int y;
        private AffineTransform transform;
        private int modCount;

        PackedItem(Item item, Rotation rotation, int x, int y) {
            this.set(x, y, rotation);
            this.points = new ArrayList<PackedPoint>();
            for (Point point : item.points) {
                this.points.add(new PackedPoint(point));
            }
        }

        void set(int newX, int newY, Rotation newRotation) {
            modCount++;
            x = newX;
            y = newY;
            rotation = newRotation;
            transform = new AffineTransform();
            transform.translate(x, y);
            transform.rotate(this.rotation.getDegrees());
        }

        void draw(Graphics g) {
            Color oldColor = g.getColor();
            for (Point point : points) {
                g.setColor(point.getColor());
                g.drawLine(point.getX(), point.getY(), point.getX(),
                        point.getY());
            }
            g.setColor(oldColor);
        }

        private enum Rotation {
            ZERO(0), NINETY(Math.PI / 2), ONE_EIGHTY(Math.PI), TWO_SEVENTY(
                    3 * Math.PI / 2);

            private final double degrees;

            Rotation(double degrees) {
                this.degrees = degrees;
            }

            double getDegrees() {
                return degrees;
            }
        }

        private final class PackedPoint implements Point {
            private final Point point;
            private final Point2D point2D;
            private int x;
            private int y;
            private int modCount;

            public PackedPoint(Point point) {
                this.point = point;
                this.point2D = new Point2D.Float(point.getX(), point.getY());
            }

            @Override
            public int getX() {
                update();
                return x;
            }

            @Override
            public int getY() {
                update();
                return y;
            }

            private void update() {
                if (this.modCount != PackedItem.this.modCount) {
                    this.modCount = PackedItem.this.modCount;
                    Point2D destPoint = new Point2D.Float();
                    transform.transform(point2D, destPoint);
                    x = (int) destPoint.getX();
                    y = (int) destPoint.getY();
                }
            }

            @Override
            public Color getColor() {
                return point.getColor();
            }
        }
    }

    private static final class Packing {
        private final Set<PackedItem> packedItems = new HashSet<PackedItem>();
        private final int maxWidth;
        private boolean[][] pointsFilled;
        private int height;

        Packing(int maxWidth) {
            this.maxWidth = maxWidth;
            this.pointsFilled = new boolean[maxWidth][0];
        }

        void addItem(PackedItem item) {
            packedItems.add(item);
            for (Point point : item.points) {
                height = Math.max(height, point.getY() + 1);
                if (pointsFilled[point.getX()].length < point.getY() + 1) {
                    pointsFilled[point.getX()] = Arrays.copyOf(
                            pointsFilled[point.getX()], point.getY() + 1);
                }
                pointsFilled[point.getX()][point.getY()] = true;
            }
        }

        BufferedImage getDrawing() {
            BufferedImage image = new BufferedImage(maxWidth, height,
                    BufferedImage.TYPE_INT_ARGB);
            Graphics g = image.getGraphics();
            g.setColor(Color.WHITE);
            g.drawRect(0, 0, maxWidth, height);
            for (PackedItem item : packedItems) {
                item.draw(g);
            }
            return image;
        }

        boolean isValidWith(PackedItem item) {
            for (Point point : item.points) {
                int x = point.getX();
                int y = point.getY();
                if (y < 0 || x < 0 || x >= maxWidth) {
                    return false;
                }
                boolean[] column = pointsFilled[x];
                if (y < column.length && column[y]) {
                    return false;
                }
            }
            return true;
        }
    }
}

The solution this produces (takes about 4 minutes 30 seconds on my machine) is:

Looking at this picture it seems like the result can be improved by iterating over all of the shapes post packing and trying to move them all up a bit. I might try doing that later.


Reverse and Invert a String Reverse and Invert a String

Challenge

In this challenge. You'll be writing a program which will output or return the input, reversed and inverted.

First, each character should be converted to its character code. Then, that should be converted to base-2. Following, that string should be reversed. After, the string should be inverted (1 -> 0 and 0 -> 1). Finally, that should be converted back to base 2 and then converted back to a character. If an character results to be an unprintable, you may optionally output it but they do not have to be removed.

H -> 72  -> 1001000 -> 0001001 -> 1110110 -> 118 -> v
e -> 101 -> 1100101 -> 1010011 -> 0101100 -> 44  -> ,
l -> 108 -> 1101100 -> 0011011 -> 1100100 -> 100 -> d
l -> 108 -> 1101100 -> 0011011 -> 1100100 -> 100 -> d
o -> 111 -> 1101111 -> 1111011 -> 0000100 -> 4   -> (unprintable)
, -> 44  -> 101100  -> 001101  -> 110010  -> 50  -> 2
  -> 32  -> 100000  -> 000001  -> 111110  -> 62  -> >
W -> 87  -> 1010111 -> 1110101 -> 0001010 -> 10  -> (newline)
o -> 111 -> 1101111 -> 1111011 -> 0000100 -> 4   -> (unprintable)
r -> 114 -> 1110010 -> 0100111 -> 1011000 -> 88  -> X
l -> 108 -> 1101100 -> 0011011 -> 1100100 -> 100 -> d
d -> 100 -> 1100100 -> 0010011 -> 1101100 -> 108 -> l
! -> 33  -> 100001  -> 100001  -> 011110  -> 30  -> (unprintable)

Scoring

Shortest code in bytes wins.

-15% Bonus: if your program removes un-printables from the output. This must be at least all characters below 32 except newlines (char 10)

Pyth, 14 bytes

smCi!M_jCd2 2z

Try it online.

How it works

 m           z  Map over the input with lambda d:
        Cd        Cast d to character.
       j  2       Convert to base 2.
      _           Reverse the resulting array.
    !M            Mapped logical NOT.
   i        2     Convert back to integer.
  C               Cast to character.
s               Concatenate the resulting characters.


Restricted mini challenges Cop's Thread Robber's thread

Your task as cops is to select three things:

A programming language
An OEIS sequence
A byte set

You are then to secretly write a program in that language that computes the nth term sequence using only the bytes in the set.  You will reveal the three pieces of information so that robbers can try to figure out the program.

Answers will be scored by the number of bytes in the byte set with more score being good. Cracked answers have an automatic score of 0.  If your answer is uncracked after one week you may reveal the intended program and mark your answer as "safe".

Answers must be capable of calculating every term in the b-files of the sequence, but are not required to calculate any terms after.

Sequences can be either 1 or 0 indexed for both cops and robbers.

Here is a Python Script that checks if your code matches the given byte set.

Haskell, A209229, (cracked)

11 characters (including newline):

s<=[ ]
how!

Outputs True/False as an indicator function for powers of 2:

1 => True
2 => True
3 => False
4 => True
5 => False
6 => False
7 => False
8 => True
9 => False
...

Inputs are positive integers.


Linear Function Solver from Two Points (x,y) The Task
Write a function L() that takes two Tuple arguments of coordinates in the form (x, y), and returns their respective linear function in the form (a, c), where a is the co-efficent of the x term and c is the y-intercept.
You can assume that the input will not be a line perpendicular the the x axis, and that the two inputs are separate points.
Scoring
This is Code Golf: shortest program wins.
Please Note: No use of any mathematical functions apart from basic operators (+,-,/,*).
Example
Here is my un-golfed solution in Python.
def L(Point1, Point2):
    x = 0
    y = 1
    Gradient = (float(Point1[y]) - float(Point2[y])) / (float(Point1[x]) - float(Point2[x]))
    YIntercept = Point1[y] - Gradient * Point1[x]
    return (Gradient, YIntercept)

Output:
>>> L( (0,0) , (1,1) )
(1.0, 0.0)

>>> L( (0,0) , (2,1) )
(0.5, 0.0)

>>> L( (0,0) , (7,1) )
(0.14285714285714285, 0.0)

>>> L( (10,22.5) , (5,12.5) )
(2.0, 2.5)

GNU dc, 30 24 bytes
[sysxly-rlx-/dlx*lyr-]sL

Defines a macro L such that
(x1, y1, x2, y2) should be pushed to the stack in that order before calling, and after calling L, (a, c) may be popped from the stack (in reverse order of course - it is a stack).
Testcase (save as "linear.dc" and run dc linear.dc):

[sysxly-rlx-/dlx*lyr-]sL   # Define L macro

10                         # Push x1 to the stack
22.5                       # Push y1 to the stack
5                          # Push x2 to the stack
12.5                       # Push y2 to the stack

lLx                        # Call L macro
f                          # Dump the stack

Output is:

$ dc linear.dc
2.5
2
$

Explanation of L macro:

sy pop y2 to y register
sx pop x2 to x register
ly push y register (y2)
- subtract y2 from y1
r swap (y1 - y2) and x1 on stack
lx push x register (x2)
- subtract x2 from x1
/ divide (y1 - y2) by (x1 - x2) to get gradient
d duplicate gradient
lx push x register (x2)
* multiply (x2) by gradient
ly push y register (y2)
r swap (y2) and (x2 * gradient) on stack
- subtract (x2 * gradient) from (y2)


Inverse symbolic calculator This challenge is based on the idea of Plouffle's Inverter.

Write a program in any language that does the following:

Takes as input a non-negative rational number X written in decimal, for example 34.147425.
Returns a mathematical expression using only non-negative integers, whitespace, parentheses, and the following binary operators:

Addition +
Subtraction -
Multiplication *
Division /
Exponentiation ^

The expression should evaluate to X, or at least agree with all the digits of X. To continue the example, a correct output could be 13 + 20^(5/4) / 2, since 13 + 20^(5/4) / 2 = 34.1474252688...
Output may optionally be written in Polish notation (prefix) or reverse Polish notation (postfix), i.e. + 13 / ^ 20 / 5 4 2 is fine.

The program is subject to the following retrictions:

Standard loopholes are forbidden! In particular, the program cannot read any external lookup table.
The source code of the program must be shorten than 1024 characters.

The program with the lowest average compression ratio will win.

To determine your average compression ratio, you can to use the following Python script, or write your own equivalent program. Here is the list of 1000 random numbers.

import random

def f(x):
    # edit this function so that it will return
    # the output of your program given x as input
    return "1 + 1"

random.seed(666)

S = 1000 # number of samples

t = 0.0

for n in xrange(0, S):
    # pick a random decimal number
    x = random.uniform(0, 1000)

    # compute the compression ratio
    # length of output / length of input
    r = len(f(x).translate(None, " +-*/^()")) / float(len(str(x).translate(None, ".")))
    t += r

print "Your average compression ratio is:", t / S

Good luck!

NOTES:

Whitespaces in the output are not mandatory. Strings like 1+1, 1 +2, or 1 + 2, are all okay. Indeed, the script to compute the score does not count whitespaces and parenthesis in the length of the output. However, note that the use of whitespaces is necessary if you choose Polish or reverse Polish notation.
Regarding the usual infix notation, the precedence rules are the following: first all exponentiation (^), then all divisions (/), then all multiplications (*), then all additions (+) and all subtractions (-). But I do not know how much this could matter, since you can use parentheses.
A way to edit the function f in the script above can be the following, however I think that it depends on your operating system; on GNU/Linux it works. Name your program "inverter" (or "inverter.exe") and place it in the same directory as the Python script. Your program should get X as the first argument of command line and return the expression in STDOUT. Then edit f as follows:

import os
def f(x):
    return os.popen("./inverter " + str(x)).read()

EDIT: As a consequence of the comment of Thomas Kwa, now the operators do not contribute to the length of the expression. The challenge should be more "challenging".

Haskell, 1.08404005439

import System.Environment
import Data.Ratio
import Data.Lists

main = do
   arg <- fmap head getArgs
   let number = read (arg ++ "5")
   let (_,_:decs) = span (/= '.') arg
   let acc = (read $ "0." ++ (decs >> "0") ++ "4999") :: Double
   putStr $ replace " % " "/" $ show $ approxRational number acc

This uses the approxRational function which converts a floating point number to a fraction with a accuracy of a given epsilon. It simply returns this fraction. As Haskell prints rationals with a % in-between, we have to replace it with the division sign /.

The accuracy parameter is calculated from the input number. We have to take into account that all the digits have to match, so 4.39 is fine for 4.3 but 4.29 isn't. I append a 5 to the number and the accuracy is a 4999 at the same decimal place as the appended 5, e.g.

12.347       -- input number
12.3475      -- append 5
 0.0004999   -- accuracy epsilon for the "approxRational" function.

E.g. 34.147425 -> 43777/1282.

Edit: the rules for accuracy have changed. The test case includes numbers with up to 11 decimal places and all have to match.

Edit II: it seems that the provides Python script doesn't strip off trailing newlines, so I've changed from putStrLn to putStr.

Edit III: again, new scoring rules


Print invisible text Given a string as input, output a number of whitespace characters (0x0A and 0x20) equal to the length of the string.

For example, given the string Hello, World! your code would need to output exactly 13 whitespace characters and nothing else. These can be any mix of spaces and newlines.

Your code should not output any additional trailing newlines or spaces.

Testcases:

     Input      -> Amount of whitespace to output
"Hello, World!" -> 13
"Hi"            -> 2
"   Don't
Forget about
Existing
Whitespace!   " -> 45
""              -> 0
"             " -> 13
"
"               -> 1

Scoring:

This is code-golf so fewest bytes wins!

Whitespace, 311 150 77 68 65 46 41 38 bytes
-3 bytes thanks to Kevin Cruijssen
-27 bytes thanks to Ephphatha

&nbsp&nbsp
&nbsp&nbsp&nbsp	&nbsp	&nbsp
&nbsp
&nbsp&nbsp
&nbsp
	&nbsp
	&nbsp&nbsp

&nbsp&nbsp
&nbsp

Try it online!
A visible format
'\n  \n   \t \t \n \n  \n \t\n\t \t\t\t\n\t  \n\t\n  \n \n\n'

Explanation (s = space, t = tab, n = new line)
nssn     # label(NULL) - loop start
ssststsn # push 10 in the stack -> [10]
sns      # duplicate the top of the stack -> [10, 10]
sns      # duplicate the top of the stack -> [10, 10, 10]
tnts     # read a single char from input, pop the stack and store at that address -> [10, 10] [10:<char that was read>]
ttt      # pop the stack and put the value at that adress on stack -> [10,<char>] [10:<char>]
ntssn    # jump to label(0) - since label(0) is not defined, the interpreter jumps to the end of the program - if the top of the stack (char) is 0 -> [10] [10:<char>]
tnss     # pop the top of the stack and print as ascii -> [] [10:<char>]
nsnn     # go back to the label(NULL)


Solve a deterministic version of 2048 using the fewest bytes Write a program that generates a winning sequence of moves to the deterministic variant of the game 2048. The sequence should be in the form of a string of numbers 0-3, with 0: up, 1: right, 2: down, 3: left.
For example, the string "1132" means right right left down. The winning program is the shortest source code that gets to 2048!

The rules to deterministic 2048:
The game is played on a 4x4 grid initially containing 1 tile, in the upper left-hand corner. Each move consists of the command "left", "right", "up" or "down". The command left slides all the tiles on the grid to the left, then combines and sums like tiles starting from the left. Likewise, the command right slides tiles to the right, then combines starting from the right.

Each tile can only participate in one combination per move.

After a move, a new 2 tile is created in the first column from the left with an available space, in the first available space from the top in that column.

For example, the sequence "right right left down" leads to the states

2___
____
____
____

2__2
____
____
____

2__4
____
____
____

24__
2___
____
____

2___
____
____
44__

The command right applied to the row _ 2 2 2 results in _ _ 2 4
The command right applied to the row 2 2 2 2 results in _ _ 4 4

This question inspired by http://jmfork.github.io/2048/

Python, 740 characters (665 characters compressed)

Code:

R=range
G=lambda:[[0]*4for _ in R(4)]
J=[(0,4,1),(2,-1,-1),(1,4,1)]
H=[0,-1,1]
def M(P,d):
 C=G();g,z=[(0,-1),(1,0),(0,1),(-1,0)][d];Q=H[g];W=H[z]
 while 1:
    N=[r[:]for r in P]
    for x in R(*J[g]):
     for y in R(*J[z]):
        s=N[y][x];q,w=y-W,x-Q;d=N[q][w];a,b,c=(((0,s,d),(1,0,s+d))[s==d],(0,0,s or d))[s<1 or d<1];
        if 2-a-(C[y][x]+C[q][w]>0):N[y][x]=b;N[q][w]=c;C[q][w]+=a
    if N==P:break
    P=N
 return N
def F(N):
 for x in R(4):
    for y in R(4):
     if N[y][x]==0:N[y][x]=2;return N
def Z(P,i):
 X=[d for d in R(4)if M(P,d)!=P]
 return i==0and(sum((256,c)[c>0] for v in P for c in v)+P[3][3]*10+P[3][2]*9,-1)or max((Z(F(M(P,d)),i-1)[0],d)for d in X)if X else(-1,-1)
B=G()
B[0][0]=2
h=''
while B[3][3]!=2048:_,X=Z(B,4);h+=`X`;B=F(M(B,X))
print h

(Mixes tabs with spaces for indentation to save a few bytes)

I must have sucked at golfing it because if I just compress the above code, base-64 encode it, and exec it, it's only 665 characters. The following is exactly equivalent to the above, no hard-coded solution or anything:

exec"""eJxVUl1vozAQfMa/wn2qnRjJcNzpDnf7QKS2qlRE+1IUy2oJkARdwl2hbT5+/a0NiXqSZXYH78zY
u0/QFe2qJrewKbaLqoi1lmYSLf909IU2LX1iETfkHjSTIhIBFywUfoALo8AhhtyBlhYMDKnqJX1g
mah4TOgMbhlXK3F01WOJxF06It8mRldGPcKdXhn1jJ+jIXS3bjY1DWLipaA7HRvrprNuMkM8m+wH
a5N7LEMlj1rwcAaPDvR6SPXB6L1Rb2IHB/9Z7P1HVSH6ZvTOqEIsRAmMoZ8eHTt3op9WnOseoDLW
KAIUuR12FbjwKjAK2ZslDf3CZ7NBYzobWK8lj0dZWKhRCko1/p5CQWxpCpDFi64ufhMvg5TQrn7/
6Fqauie8Yal9wC9XjeyNvtzS5dQSjVogz7Kh+o9sjv1oLF0OunKc1YmjOXXrAvBpTx4aJCvaivUf
W8bC7z9EyXV5LY2r/XR9cGFpw08+zfQ3g2sSyCEMzeSXbTce2RZ7xubshg0yXDSI44RhfDaSWxs5
rTd9zYbRIomdHJLgQVwQkjVcXpJhLJJB7AJCGf2MX0QOc5aIiKv1FF7zV5WAFUtEzjn52zXtO13/
AwRvylc=""".decode('base64').decode('zip')

Answer:

Takes ~47 seconds (17 seconds ungolfed) to find the 1111-move sequence:

  2221230232213120120232222222221221203211012312310123123101223113322222123230210302321222323223212322101202323123322032132021233212312332023123312111123231223113312312322312232123222021221332111332221012222312222302232021233212312332023212222222123221202332023120312123223221232232222222122122323222222212212232222222221322233231222322200232122312232313132022322212312332121332312320212211332312323223212320232322322133223213212323202123123321231313332122232310112113322212323222220130231233211313332122232312312223232231231232312222220232212312220212232312232123222021221332111332221012222312222302232021233212312332023212222222123221202332023120312123223221322323223312230230323312232313133232223233212312323123323222332222222132221321320323233223232121323212232013221323233032021223320231233220322203132123202123321231233202131321221111231213232131210212312232332132103123130213133213232213321323212332332212222123323322202302333121220222323232113123323221223032131201123212133123131222323313133313300123231332011222221223232331313313112312113230231121232332122323232321312323213212232313212323211330231231012

With the following final board position and move:

   4    2   16    4
   2    8  128    8
   2    .    . 1024
   .    .    . 1024
Best move: s, with EV=25654

Trivia: the solution is 309 bytes gzipped and 418 bytes if gzipped and base64-encoded. Thus it would be a shorter program to just decode that and print it out, but that is no fun at all.

Explanation:

Here's a pastebin of the ungolfed version which prints out the board after each move, very fun to watch!

It's a very simple brute-force AI. It assigns an EV for each board position:

ev =   256 * number of spaces
     + sum_of_values
     + 10 * board_bottom_right
     +  9 * board_bottom_2nd_right

It does a depth-first search four moves ahead and picks the path that leads to the highest EV in four moves. The ev function encourages it to clean up the board and to keep the highest-valued pieces in the corner, which ends up being pretty optimal. It's enough to get it there!

If you modify the EV function to place a higher value on other board spots, something like:

1  1  1  1
1  1  1  1
1  1  9 10
1  9 10 11

That function gets it as far as:

   2    8    4    2
  16   32   64   16
  64  128  512 1024
   2  256 2048 8192

16k:

Eureka! With a 5-step lookahead instead of a 4, and the following weights:

1  1  4  4
1  1  4 10
1  1 14 16
1 16 18 20

It almost almost gets 32k, ending on:

   2  128    4     2
  64  256  512     4
   4  128 1024  4096
  16 2048 8192 16384

The sequence is here.

32k:

Yes ladies and gentlemen, we have hit the 32k mark. The EV function, instead of multiplying squares by a constant, raises each square to the following powers and adds them. x means the square isn't involved:

x x x 3
x x x 4
x x 5 6
x 6 7 8

It still sums all the values once and adds 256 for each empty square. Lookahead was 4 all the way up to 32k, and then it bumped up to 5, but it doesn't really seem to do much. End board:

   2  128    8     2
  64  256  512     4
   4  128 1024  2048
  16 4096 8192 32768

Pastebin of the 24,625-move sequence.


Josephus problem (counting out) The challenge
Write a function that takes two positive integers \$n\$ and \$k\$ as arguments and returns the number of the last person remaining out of \$n\$ after counting out each \$k\$-th person.
This is a code-golf challenge, so the shortest code wins.
The problem
\$n\$ people (numbered from \$1\$ to \$n\$) are standing in a circle and each \$k\$-th is counted out until a single person is remaining (see the corresponding wikipedia article). Determine the number of this last person.
E.g. for \$k=3\$ two people will be skipped and the third will be counted out. I.e. for \$n=7\$ the numbers will be counted out in the order \$3 \, 6 \, 2 \, 7 \, 5 \, 1\$ (in detail \$\require{cancel}1 \, 2 \, \cancel{3} \, 4 \, 5 \, \cancel{6} \, 7 \, 1 \, \cancel{2} \, 4 \, 5 \, \cancel{7} \, 1 \, 4 \, \cancel{5} \, 1 \, 4 \, \cancel{1} \, 4\$) and thus the answer is \$4\$.
Examples
J(7,1) = 7      // people are counted out in order 1 2 3 4 5 6 [7]
J(7,2) = 7      // people are counted out in order 2 4 6 1 5 3 [7]
J(7,3) = 4      // see above
J(7,11) = 1
J(77,8) = 1
J(123,12) = 21

Minsky Register Machine (25 non-halt states)

Not technically a function, but it's in a computing paradigm which doesn't have functions per se...

This is a slight variation on the main test case of my first MRM interpretation challenge:

Input in registers n and k; output in register r; it is assumed that r=i=t=0 on entry. The first two halt instructions are error cases.


Mondrian Puzzle Sequence Partition an n X n square into multiple non-congruent integer-sided rectangles. a(n) is the least possible difference between the largest and smallest area.

 ___________
| |S|_______|
| | |   L   |
| |_|_______|
| |     |   |
| |_____|___|
|_|_________| (fig. I)

The largest rectangle (L) has an area of 2 * 4 = 8, and the smallest rectangle (S) has an area of 1 * 3 = 3. Therefore, the difference is 8 - 3 = 5.

Given an integer n>2, output the least possible difference.

All known values of the sequence at the time of posting:

2, 4, 4, 5, 5, 6, 6, 8, 6, 7, 8, 6, 8, 8, 8, 8, 8, 9, 9, 9, 8, 9, 10, 9, 10, 9, 9, 11, 11, 10, 12, 12, 11, 12, 11, 10, 11, 12, 13, 12, 12, 12

So a(3)=2, a(4)=4, ...

OEIS A276523

Related - this related challenge allows non-optimal solutions, has time constraints, and is not code-golf.

For more information, watch this video by Numberphile

Befunge, 708 bytes

p&>:10p1-:>20p10g:20g\`v`\g02:-1\p00+1g<>g-#v_10g:*30p"~":40p50p060p070p$>^
1#+\#1<\1_^# !`0::-1$  _:00g3p\:00g2p00^^00:>#:

>>:2-#v_$30p50p60p70g1-70p
^<<<<<:#<<<<<<$$$_v#:!g87g78g79$  _v#!\-1:g88$<_ 98p87g97g*00 v:+!\`*84g++7<
^>$1-:77p1g:2g\3g1>78p97p87p10g97g->88p10g87g-0^!\-1:g89_v#-!\_$1-:v>/88g+7^
^|!-3$<   >\87g/88g+77++p:#v_$
^>:5->v   ^+g89%g78:\g77:-1<>98g88g48*577g387g97g98g88v ^>77g87g97v:^g78\+g<
^ v-4:_$77p88p98p:97p\:87p*^^g79g7>#8\#$_40pv5+"A"g77g< ^14g88g89g<>:87g%98^
^v_$88p98p97p87p:77p60g50g-:40g\`#^_$$>>>>>>>
 >#4!_::80p2g\3g*:90p30g`!v>>>#@>#.>#g^#0
^v:g06p03:-g09\2:g03g05g06_^^_7#<0#<g#<3#<1#<<`g04_$00g1->:#-8#10#\g#1`#:_>$
^>90g\-:0`*+:60p50g:90g-:0`*-:50p-80g70g:1+70p1p\!^

Try it online!

This is obviously not going to win any awards for size, but it's actually reasonably fast considering it's a basic bruce force implementation in an esoteric language. On the Befunge reference interpreter it can handle up to n=6 in a couple of seconds. With a compiler it can handle up to n=8 before it starts getting sluggish; n=9 takes a couple of minutes and n=10 is close on 2 hours.

In theory the upper limit is n=11 before we run out of memory (i.e. there's not enough space left in the playfield to fit a larger square). However, at that point, the time taken to calculate the optimal solution is probably longer than anyone would be willing to wait, even when compiled.

The best way to see how the algorithm works is by running it in one of the Befunge "visual debuggers". That way you can watch as it attempts to fit the various rectangle sizes into the available space. If you want to "fast forward" to the point where it has a good match, you can put a breakpoint on the 4 in the sequence $_40p near the middle of the tenth line (9 if zero-based). The value at the top of the stack at that point is the current area difference.

Below is an animation showing the first few frames of this process for n=5:

Each distinct rectangle is represented by a different letter of the alphabet. However, note that the final rectangle is never written out, so that section of the square will just be blank.

I've also written a debug version of the code that outputs the current layout each time it finds a new best match (Try it online!). For the smaller sizes, the first match is often the optimal solution, but once you get past n=6 you'll likely get to see several valid but non-optimal layouts before it settles on the final solution.

The best layout found for n=10 looks like this:

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

12 - 4 = 8


Find the largest number that's adjacent to a zero Challenge:

Take a vector / list of integers as input, and output the largest number that's adjacent to a zero.

Specifications:

As always, optional input and output format
You may assume that there will be at least one zero, and at least one non-zero element.

Test cases:

1 4 3 6 0 3 7 0
7

9 4 9 0 9 0 9 15 -2
9

-4 -6 -2 0 -9
-2

-11 0 0 0 0 0 -12 10
0

0 20
20

Good luck and happy golfing!

MATL, 10 bytes
t~5BZ+g)X>

Try it online! Or verify all test cases.
Explanation
Let's take input [-4 -6 -2 0 -9] as an example.
t     % Input array. Duplicate
      %   STACK: [-4 -6 -2 0 -9],  [-4 -6 -2 0 -9]
~     % Logical negate. Replaces zeros by logical 1, and nonzeros by logical 0
      %   STACK: [-4 -6 -2 0 -9],  [0 0 0 1 0]
5B    % Push logical array [1 0 1] (5 in binary)
      %   STACK: [-4 -6 -2 0 -9], [0 0 0 1 0], [1 0 1]
Z+    % Convolution, maintaining size. Gives nonzero (1 or 2) for neighbours of
      % zeros in the original array, and zero for the rest
      %   STACK: [-4 -6 -2 0 -9], [0 0 1 0 1]
g     % Convert to logical
      %   STACK: [-4 -6 -2 0 -9], [0 0 1 0 1]
)     % Use as index into original array
      %   STACK: [-2 -9]
X>    % Maximum of array.
      %   STACK: -2
      % Implicitly display


Insert a given pattern at a given point The challenge
Insert one string into another at a given index.
Given a string input in the format:
#:Pattern:Word

Where:

# is a positive integer marking the index
Pattern is the string (whose length is undefined) to insert
: is a delimiter
Word is the string to insert into.

Assume that a : will not be used in either string.
For example, if your input was
3:A2C:Hello World!

The output would be
HelA2Clo World!

If an invalid index is provided, the program must respond with an error. For example
12:!*!:Hello

is a valid input and must be explicitly handled somehow. For example, printing "Invalid input!" (or nothing at all!) is a valid way to catch, however crashing is not valid.

CJam, 20 bytes

q':/~La+@~/(@@_{];}|

Try it online in the CJam interpreter.

How it works

q':/                e# Read all input and split it at colons.
    ~                e# Dump index, pattern and word on the stack.
     La+             e# Append the array [""] to the word.
                     e#   This increases the word's length by 1 (to deal with the
                     e#   highest index possible index) without affecting output.
        @~           e# Rotate the index on top and evaluate it.
          /          e# Split the word into chunks of that length.
           (         e# Shift out the first chunk.
            @@       e# Rotate pattern and remaining chunks on top.
              _      e# Copy the array of remaining chunks.
                     e#   This array will be empty if the index was too high.
               {];}| e# If the array if falsy, clear the stack.


Horizontally Aligned ASCII Art Your task is to accept as input two "ASCII Art"s, and align each piece of art next to each other horizontally.
For example, say you have two strings, "abc\ndef" and "123\n456". You need to align them horizontally to produce the string "abc123\ndef456". I'm calling this "aligning horizontally" because while the inputs, when printed, look like this:
abc
def

and:
123
456

The output, when printed, will look like this:
abc123
def456

Note how one input is placed next to the other.

Input

Input will be strings, and can be as two separate arguments, or as a sequence of strings.

The characters in the arts will have decimal codes in the range 32-126 (inclusive).

It's fine to support an arbitrary number of arts to align instead of just two (but obviously you must support at least two).

You can assume that each art will have the same dimensions, and that they will contain at least one line.

You must be able to support at least 100x100 character arts.

To align with conventions on the site, the argument order does not matter. It does not matter which art is on the left or right.

Output

Output will be the aligned arts as mentioned above, either returned or output to the stdout.

Any trailing whitespace in optional.

There must be no visual separator between the aligned arts.

Input and output arts must be \n or \r delimited strings. It would be overly trivial to allow 2D-arrays.
Submissions may be functions or full programs.
Test Cases:
"abc\ndef", "123\n456" -> "abc123\ndef456".

"qwertyuiop\n asdfghjkl", "Some other\nTextFiller" -> "qwertyuiopSome other\n asdfghjklTextFiller"

"  *  \n *** \n*****\n *** \n  *  \n", "  +  \n  +  \n+++++\n  +  \n  +  \n" -> "  *    +  \n ***   +  \n*****+++++\n ***   +  \n  *    +  \n"


Reverse factorial function Given a number n, find x such that x! = n, where both x and n are positive integers. Assume the input n will always be the factorial of a positive integer, so something like n=23 will not be given as input.

Examples: n=1 -> x=1 (0 is not a positive integer), n=24 -> x=4

Shortest code wins.

Python 2, 28 bytes (input \$\leq2^{64}\$)

lambda n:len(`n**8L`)**.6//1

Try it online!

This works on inputs up to \$20! =2432902008176640000 \$ that fall within 64-bit integers.

This uses an approximate fit inspired by Stirling's approximation. However, the constants were estimated manually and it breaks down for larger values. With Python not having a built-in log, we use the digit-length for \$n^8\$ as an approximation for \$c\cdot\log(n)\$. Actually, we use the long value 8L so that the string representations uniformly end in L for "long", which adds one to the lengths.

From there, raising the value to the power of \$0.6\$ and taking the integer part is apparently sufficient to give the correct output up to \$20!\$. It's lucky that the 0.6 is 0.60, since we'd usually need another digit of precision.


The cell at the end of the rainbow We all know of, or at least have heard of, brainfuck, one of the most famous and influential esoteric languages. While these days most implementations use an infinite tape, the original compiler by Urban Müller had a tape of 30000 cells. A little known fact* is that there is actually a special value at the end of the tape, something that is almost never interacted with in a typical brainfuck program.

While you could print this value with 29999 >s and a ., brainfuck is known for its short and concise solutions, so your aim is to print this value with the minimum number of characters.

*fiction

Rules:

A refresher on the brainfuck instructions:

+/-: Increment/decrement the current cell, wrapping from 255 to 0 when 255 is incremented and vice-versa
</>: Move the pointer left/right on the tape
.: Print the value of the current cell.
[: Jump to the corresponding ] if the value at the cell is 0
]: Jump to the corresponding [ if the value at the cell is not 0

In this case , (Get input) does nothing, as the original compiler leaves the cell unchanged on EOF, and this program should receive no input.
The tape is initially filled with all 0s, except for cell 30000, which contains an unknown value
The pointer starts at cell 1 and should end on cell 30000, having printed it.
Cells to the left of 1 and to the right of 30000 have undefined behaviour, so solutions should not visit these cells.
Note that the value at 30000 is may be a 0, so simply looping until you hit a non-zero cell will not work.
You should print only the value at cell 30000
The shortest solution wins!

Tie-breaker is the more efficient program (executes in the least steps), followed by the fastest submission time.

Tip: Esolanging Fruit suggests using https://copy.sh/brainfuck to test your code. The specs are as described in this challenge, and you can select the abort option so your program halts if it goes out of bounds.


Make a JavaScript/jQuery slideshow I am working on making a minimalistic personal testing website to conduct various experiments for my role at work. I'd like to add a couple of bells and whistles to it, particularly a slideshow that cycles between several images. I could just as easily grab a plug-in, but I'd like to promote this Stack Exchange beta site and offer a simple challenge with concrete rules.

Rules:

JavaScript and jQuery are allowed. The jQuery library is assumed to be included.
The function of the code is to take three images and fade-cycle through each of them at regular intervals of five seconds indefinitely. Fade time is one second.
Must be compatible with Internet Explorer 9 (and later), Chrome, and Firefox.
The code golf submission is the total number of characters between the inline script. Characters in externally referenced files are also included.

HTML is the following, pretty-printed as it's not part of the challenge:

    <title>JS Slideshow code golf</title>

Full attribution will be given to the author on any code I end up using.

70 68(JS) + 22(CSS) characters

setInterval('$(".s").append($(".s :first").hide().fadeIn(1e3))',5e3)

CSS:

img{position:absolute}

jsfiddle: http://jsfiddle.net/QACAY/

pure jQuery. The only browser-stuff is setInterval, which dates as far back as IE4. jQuery support doesn't reach that far. Javascript syntax here is ancient as well.

Of course, in practice, do not pass strings to setInterval! It is ten characters shorter (fewer with es6 arrow functions), but it's unreadable (madness? This is code golf!), it forces you into the global scope (which we don't mind here), it's slower (but we are far from being concerned with performance of calling jQuery code) and it won't pass any decent code review.

Works best if all images have the same shape. But, it will work just as fine with semitransparent images as long as visible stacking counts as fine and no more background is visible when any single image is removed.

Since this does not wait for DOM ready, there's a tiny chance that only some of the image elements inside a gallery are loaded when an interval fires. In this case, the stack of images will get reordered. I don't think it's a problem. In fact, I kinda like it.

After slight tweaking, it looks like code that could easily pass through a code review and get into production (also, be sure to modify the CSS to not be too aggressive):

$(function(){
  $(".s").each(function(_, s){
    setInterval(function(){
      $(":first", s).hide().appendTo(s).fadeIn(1000);
    }, 5000);
  });
});


Approximate a Bell Curve Create a program to display some approximation of a bell curve. You are free to use whatever method you wish for generating the data, but the data must be displayed vertically, as in oriented like so:

Other restrictions:

Your code must create the approximation, that is, don't hardcode or take data from the internet.
The shape must actually look like a bell.

This is a popularity-contest, so be creative.

Java
The method of generation is based off of the game Sugar, Sugar. In that game, sugar particles fall, traveling randomly left and right. In my program, Dust objects fall until they hit the ground. I collect data based on where they land; this is the bell curve:
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Random;
import java.util.Stack;
import javax.imageio.ImageIO;

/**
 *
 * @author Quincunx
 */
public class ApproxBellCurve {

    public static final int NUM_DUST = 10_000_000;
    public static final int NUM_THREADS = Runtime.getRuntime().availableProcessors() - 1;
    public static final int LOOP_LIMIT = NUM_DUST / (NUM_THREADS + 1);

    public static void main(String[] args) {
        BufferedImage output = new BufferedImage(2049, 2049, BufferedImage.TYPE_INT_RGB);

        Stack<Thread> threads = new Stack();

        for (int i = 0; i < NUM_THREADS; i++) {
            threads.push(new Thread(new Duster()));
            threads.peek().start();
        }

        Dust d;
        Random r = new Random();
        for (int i = 0; i < LOOP_LIMIT + NUM_DUST - (LOOP_LIMIT * (NUM_THREADS + 1)); i++) {
            d = new Dust(r);
            while (!d.end) {
                d.step();
            }
            if ((i & 1024) == 0) {
                r = new Random();
            }
        }
        while (threads.size() > 0) {
            try {
                threads.pop().join();
            } catch (InterruptedException ex) {

            }
        }
        int maxy = 0;
        for (int x = 0; x < Dust.data.length; x++) {
            maxy = Dust.data[x] > maxy ? Dust.data[x] : maxy;
        }

        for (int x = 0; x < Dust.data.length; x++) {
            for (int y = 0; y < output.getHeight(); y++) {
                output.setRGB(x, y, (y >= output.getHeight() - (Dust.data[x] * output.getHeight() / maxy)) ? 6591981 : 16777215);
            }
        }
        try {
            ImageIO.write(output, "png", new File("Filepath"));
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    private static class Duster implements Runnable {

        @Override
        public void run() {
            Dust d;
            Random r = new Random();
            for (int i = 0; i < LOOP_LIMIT; i++) {
                d = new Dust(r);
                while (!d.end) {
                    d.step();
                }
                if ((i & 1024) == 0) {
                    r = new Random();
                }
            }
        }

    }

    private static class Dust {

        public static int[] data = new int[2049];

        static {
            for (int i = 0; i < data.length; i++) {
                data[i] = 0;
            }
        }

        private int[] location;
        private Random r;
        public boolean end;

        public Dust(Random rand) {
            location = new int[]{1024, 0};
            r = rand;
            end = false;
        }

        public void step() {
            if (end) {
                return;
            }
            if (location[1] >= 1024) {
                end = true;
                synchronized (data) {
                    data[location[0]] += 1;
                }
                return;
            }
            location[1] += 1;
            location[0] += r.nextInt(21) - 10;
        }
    }
}

Sample output (took 1 minute to create):

Because of the nature of the random number generation, it is possible to get an ArrayIndexOutOfBoundsException.
I used multithreading to speed up the process. The program determines the number of processors available and creates that many threads to run the simulations.
To obtain a finer image, NUM_DUST can be increased, but that would also lead to an increased risk of an ArrayIndexOutOfBoundsException.
Each thread creates a new Random after every 1024 Dust objects are simulated. When that code was removed, the image was more coarse.
rand.nextInt(21) - 10 is to widen the distribution. A change to rand.nextInt(3) - 1 would remove all chance of an ArrayIndexOutOfBoundsException.


Fastest way to compute order of magnitude in x86 assembly The task is simple: write assembly that computes the order of magnitude of an integer using as few clock cycles as possible.

Order of magnitude is defined as log10, not log2.
The range of valid input is 0 to 1012, inclusive. Behaviour for input outside that range is undefined.
Values should be rounded down to the nearest integer, with the exception that given input 0 the output should be 0. (You can consider this to be the best representation of negative infinity that's possible in unsigned integers).
Must be x86 assembly.
The integer must be a runtime value, not a static/inline integer. So we don't know what it is at compile time.
Assume that you have an integer loaded into a register already. (But include setting the value in the register in the answer for clarity).
Can't call any external libraries or functions.
Free to use any of the available instructions in the Intel docs.
No C.
Any of the ~7 Intel Core architectures are acceptable (listed on page 10). Ideally Nehalem (Intel Core i7).

The winning answer is one that uses the fewest clock cycles possible. That is, it can have the most operations per second. Approximate clock cycle summaries are here: http://www.agner.org/optimize/instruction_tables.pdf. Calculating clock cycles can happen after the answer is posted.

7 cycles, constant time
Here's a solution based on my answer to this SO Question.
It uses BSR to count how many bits are needed to hold the number. It looks up how many decimal digits needed to represent the largest number that many bits can hold. Then it subtracts 1 if the actual number is less than the nearest power of 10 with that many digits.

    .intel_syntax noprefix
    .globl  main
main:
    mov rdi, 1000000000000              #;your value here
    bsr rax, rdi
    movzx   eax, BYTE PTR maxdigits[1+rax]
    cmp rdi, QWORD PTR powers[0+eax*8]
    sbb al, 0
    ret
maxdigits:
    .byte   0
    .byte   0
    .byte   0
    .byte   0
    .byte   1
    .byte   1
    .byte   1
    .byte   2
    .byte   2
    .byte   2
    .byte   3
    .byte   3
    .byte   3
    .byte   3
    .byte   4
    .byte   4
    .byte   4
    .byte   5
    .byte   5
    .byte   5
    .byte   6
    .byte   6
    .byte   6
    .byte   6
    .byte   7
    .byte   7
    .byte   7
    .byte   8
    .byte   8
    .byte   8
    .byte   9
    .byte   9
    .byte   9
    .byte   9
    .byte   10
    .byte   10
    .byte   10
    .byte   11
    .byte   11
    .byte   11
    .byte   12
powers:
    .quad   0
    .quad   10
    .quad   100
    .quad   1000
    .quad   10000
    .quad   100000
    .quad   1000000
    .quad   10000000
    .quad   100000000
    .quad   1000000000
    .quad   10000000000
    .quad   100000000000
    .quad   1000000000000

Compiles on GCC 4.6.3 for ubuntu and returns the value in the exit code.
I'm not confident interpreting that cycles table for any modern processor, but using @DigitalTrauma's method, on the Nehalim processor, I get 7?
ins        uOps Latency
---        -    -
BSR r,r  : 1    3
MOVZX r,m: 1    -
CMP m,r/i: 1    1
SBB r,r/i: 2    2


codegolf.com: Saving Time From codegolf.com (not loading as of Sept 15, 2011) was one that was driving me crazy. Print to STDOUT a clock of an exacting form, reading time from STDIN and marking an h at the hour and m at minute (rounded down to a multiple of 5) and an x if they overlap, unused ticks are marked with an o, so that

echo "23:13" | perl script.pl

yields

        o
    h       o

 o             m

o               o

 o             o

    o       o
        o

Mine is:

$/=':';($h,$m)=<>;printf'%9s
%5s%8s

%2s%14s

%s%16s

%2s%14s

%5s%8s
%9s',map{qw'o h m x'[2*($_==int$m/5)^$_==$h%12]}map{$_,11-$_}0..5

for 136 characters, using Perl. I wish I could get on the site, but I seem to recall that the leaders were under 100, also using Perl. Can someone else beat it?

Golfscript, 75 bytes

Inspired by the article linked in the comments.

':'/{~}/5/:m;12%:h;"XXXXXXXXXXXX"{..318\%9/' '*@12%.h=2*\m=+'omhx'=@85/n*}%

The XXXXXXXXXXXX part represents 12 bytes of data, some of them unprintable, and should be replaced with the byte sequence 120 47 253 22 194 9 183 44 196 55 125 246.

For convenience, here is a base64 encoded version:

JzonL3t+fS81LzptOzEyJTpoOyJ4L/0Wwgm3LMQ3ffYiey4uMzE4XCU5LycgJypAMTIlLmg9Mipc
bT0rJ29taHgnPUA4NS9uKn0l

Example run:

$ echo -n "JzonL3t+fS81LzptOzEyJTpoOyJ4L/0Wwgm3LMQ3ffYiey4uMzE4XCU5LycgJypAMTIlLmg9MipcbT0rJ29taHgnPUA4NS9uKn0l" | base64 -d > saving-time.gs
$ ls -l saving-time.gs
-rw-r--r-- 1 ahammar ahammar 75 2012-01-29 17:31 saving-time.gs
$ ruby golfscript.rb saving-time.gs <<< "15:37"
        o
    o       o

 o             o

o               h

 o             o

    m       o
        o


Find a mirror configuration to match laser destinations UPDATED SCORING: As this challenge is more difficult than I anticipated, I have adjusted the scoring. A program that can solve a single mirror input is a valid answer. More sophisticated programs get a bonus to their score.

There have been several puzzles on PPCG to find a laser path in a box of
mirrors. In this puzzle, you need to create a box of mirrors to match a number
of laser destinations.

You are given a box and a specifications where lasers are to enter and exit.
Your program needs to place exactly N double-sided mirrors in the box to meet
the specification. The mirrors must be angled at 45 degrees but can be forward
sloping or back sloping.

Input

Your program should accept a box grid via STDIN, command line argument, or file
in the following format examples:

+--G--+     +abcde+
G     |     f/////d
|    /|     a//   c
+-----+     f     |
            +-b-e-+

The letter pairs ([a-zA-Z] may be used) indicate the input/output of up to 52 lasers.
Inside the box will be N / mirrors. The box dimensions will be
3 <= W,H <= 200. The box is made of +|- characters. There may be any number of
  mirrors in the box including zero.

Output

The output should match the input, except the / characters may be moved and/or
changed into \ characters.  Your program should send a correct mirror box
string to STDOUT or a file, trailing new line optional. If no placement of
mirrors can meet the input specification, output Impossible\n. Examples of
possible solutions:

+--G--+     +abcde+
G  /  |     f \ \ d
|     |     a/ \  c
+-----+     f / //|
            +-b-e-+

Testing example

Input:

+abcdefghijklmnopqrstuvwxyA-+
|///////////////            |
|///////////////            |
|                           |
+-Abcdefghijklmnopqrstuvwxya+

Example output:

+abcdefghijklmnopqrstuvwxyA-+
|\                         \|
|/                        / |
|\\\\\\\\\\\\\\\\\\\\\\\\\\ |
+-Abcdefghijklmnopqrstuvwxya+

Scoring (UPDATED)

This is code-golf with bonuses. You should nominate with your answer how many mirrors your program can solve (N). Your score is the length of your program in bytes divided by N. This allows people to enter with a simple program, but rewards more ambition programmers with a bonus.

Standard loopholes disallowed.

Python, 671 654 bytes

Not a solution, but an attempt, read below.

import random as R
def V(F):
 for S,_x,_y in (F[0],0,1),(F[-1],0,-1),([L[0] for L in F],1,0),([L[-1] for L in F],-1,0):
  for i,C in enumerate(S):
   if not C in '+-|':
    x=_x;y=_y
    if not x: X=i;Y=y
    elif not y: Y=i;X=x
    while F[Y][X] != C:
     if F[Y][X]=='\\':x,y=y,x
     if F[Y][X]=='/':a=x+y;x,y=x-a,y-a
     X+=x;Y+=y
     try:
      if F[Y][X] in '+-|':return False
     except:
      return False
 return True
F=open(input()).read().split('\n')
while 1:
 _=[F[0]]+['\n'.join([L[0]+''.join([R.choice(' \\/')for i in range(len(F[0])-2)])+L[-1] for L in F[1:-1]])]+[F[-1]]
 if V(_):
  for l in _: print l
  break

I did not golf this to the max, since I'm not satisfied with the solution.
V validates a given solution by walking the field F for each character C it finds on the sideline. Solutions are generated at random. It's ugly, it works for entry1, but takes a Lot of time for the other entries. Since it randomly tries solutions, I don't consider this to be an actual solution for the given problem; but it might help others.

Run:
echo "entry1.txt" | python script.py


Every nth prime number up to 8675309 Read this if you're confused.
Challenge:
The goal of this code-golf is based around the number 8675309...
Your goal is to print out every prime number from 2 to 8675309, starting with the number 2 and then skipping 8 prime numbers, then skipping 6, then skipping 7, etc. In essence, skip a number of primes determined by the next number in the sequence 8675309. Cycling over to 8 once it reaches 9.
Output:
2
29

(skipped 8 to get to the 10th prime)
59

(skipped 6 to get to the 17th prime)
97

(skipped 7 to get to the 25th prime)

Example: (PHP-like pseudo-code where $prime is an array containing all the prime numbers.)
$tn=1;
$c=1;
$na=array(8,6,7,5,3,0,9);
l:
output($prime[$tn]);
if ($prime[$tn]>=8675309) {exit(8675309)};
$c+=1;
if ($c>=8) {$c=1};
$tn+=$na[$c];
goto l;

When I say skip 8 primes, I mean to go from the #1 prime, to the #10 prime (skipping the 8 in between).
Each number must be on a new line.
When you reach the 0 in 8675309, just just print the next prime number without skipping any.
This is code-golf so the shortest code (in-bytes) wins.

Mathematica 67 bytes

Doesn't hit 8675309 though - not sure of OP's intention on this.

Column@FoldList[NextPrime,2,Flatten@Array[{9,7,8,6,4,1,10}&,12937]]


Commutation of 27 functions Introduction

Let's define a ternary function as a function from the three-element set S = {0,1,2} to itself: it associates to each element of S another element of S.
One example of a ternary function f is

f(0) = 0; f(1) = 2; f(2) = 0

There are exactly 27 different ternary functions, and we represent them with integers from 0 to 26: a function f is encoded as f(0) + 3*f(1) + 9*f(2).
The example function above is encoded as the number 6.

We can apply two ternary functions f and g in sequence, and if f(g(k)) == g(f(k)) holds for all k in S, then the functions commute.
Your task is to verify whether this is the case.

Input

Your inputs are two integers in the inclusive range from 0 to 26.
They represent two ternary functions f and g.
Input must be taken in decimal, binary or unary (string of 1s) format.

Output

Your output is a truthy value if f and g commute, and a falsey value if they don't.
You may not assume that the inputs are ordered.

Examples

Consider the inputs 5 and 16.
They encode the ternary functions

f(0) = 2; f(1) = 1; f(2) = 0
g(0) = 1; g(1) = 2; g(2) = 1

We have f(g(1)) == f(2) == 0 and g(f(1)) == g(1) == 2, so f and g don't commute and the correct output is falsey.

On the other hand, the inputs 3 and 10 encode the ternary functions

f(0) = 0; f(1) = 1; f(2) = 0
g(0) = 1; g(1) = 0; g(2) = 1

and it can be verified that f(g(k)) == g(f(k)) holds for all k in S.
Then the correct output is truthy.

Here is the 27×27 table of all possible inputs, with + marking a truthy output and - a falsey output:

+ - - + - - + - - + - - + - - + - - + - - + - - + - -
- + - - - - - - - - - - + - - - - - - - - + - - - - -
- - + - - - - - - - - - - - - - - - - - - + - - + - -
+ - - + - - - - - - + - - + - - - - + - - + - - - - -
- - - - + - - - - - - - - + - - - - - - - + - - - - -
- - - - - + - - - - - - - + - - - - - - - + - - - - -
+ - - - - - + - - - - - - - - - - - - - - + - - - - -
- - - - - - - + - - - + - - - - - - - - - + - - - - -
- - - - - - - - + - - - - - - - - - + - - + - - - - -
+ - - - - - - - - + - - - - - - - - - - - + - - - - -
- - - + - - - - - - + - - - - - - - - - - + - - - - -
- - - - - - - + - - - + - - - - - - - - - + - - - - -
+ + - - - - - - - - - - + + - - - - - - - + + - - - -
- - - + + + - - - - - - + + + - - - - - - + + + - - -
- - - - - - - - - - - - - + + - - - - - - + - - - - -
+ - - - - - - - - - - - - - - + - - - - - + - - - - -
- - - - - - - - - - - - - - - - + - - - - + - + - - -
- - - - - - - - - - - - - - - - - + - - - + + - - - -
+ - - + - - - - + - - - - - - - - - + - - + - - - - +
- - - - - - - - - - - - - - - - - - - + - + - - - - +
- - - - - - - - - - - - - - - - - - - - + + - - - - +
+ + + + + + + + + + + + + + + + + + + + + + + + + + +
- - - - - - - - - - - - + + - - - + - - - + + - - - +
- - - - - - - - - - - - - + - - + - - - - + - + + - +
+ - + - - - - - - - - - - - - - - - - - - + - + + - +
- - - - - - - - - - - - - - - - - - - - - + - - - + +
- - - - - - - - - - - - - - - - - - + + + + + + + + +

Rules and scoring

You can write a full program or a function.
The lowest byte count wins, and standard loopholes are disallowed.

Jelly, 17 14 13 bytes

+13ḃ3Um0ị2/⁼/

Try it online! or verify all 27×27 cases.

How it works

+13ḃ3Um0ị2/⁼/  Main link. Argument: [f, g] (encoded as integers)

+13            Add 13 ([1, 1, 1] in base 3) to f and g.
   ḃ3          Convert f + 13 and g + 13 to bijective base 3.
               Bijective base 3 uses the digits 1 to 3 instead of 0 to 2.
               This yields [[f(2)+1, f(1)+1, f(0)+1], [g(2)+1, g(1)+1, g(0)+1]].
               The increments account for 1-based indexing.
     U         Reverse each digit array.
               This yields [[f(0)+1, f(1)+1, f(2)+1], [g(0)+1, g(1)+1, g(2)+1]].
      m0       Concatenate the list with a reversed copy of itself.
        ị2/    Split the result into pairs, and reduce each one by indexing.
               This computes g○f and f○g.
          ⁼/   Reduce by match; return 1 iff g○f = f○g.


Fastest C/C++ comparison function for an opaque field containing doubles Description:
Write the fastest comparison function for an opaque field containing a double. Here is my example:
// Three-way comparison function:
//   if a < b: negative result
//   if a > b: positive result
//   else: zero result
inline int Compare(const unsigned char* a, const unsigned char* b) const
{
    if (*(double*)a < *(double*)b) return -1;
    if (*(double*)a > *(double*)b) return +1;
    return 0;
}

Size: 188 characters (excluding the comments)
Speed: N/A
Background:
Google's LevelDB stores keys as opaque fields (i.e. bytes) and it requires the use of a comparator when the keys cannot be compared as bytes, such as the case with doubles. You can read this article to see why Floating-Point binary comparison is tricky, so when LevelDB stores key-value pairs on disk it has to properly compare the opaque keys in order to achieve good data locality.
Correct Submission:

The submission must be written in C/C++.
The submission must correctly compare the opaque fields as doubles.
Given that 1 and 2 are satisfied, the winner should be selected based on the minimum CPU operations ticks (i.e. the fastest comparison).

If there is a tie, then the shortest correct submission will be awarded.
P.S. This is my first time posting, so please let me know if I should correct/improve something in the competition.

This function is written in MMIX assembly. It should perform the calculation in 2υ
+ 5μ. If you inline it, the call is no longer needed so you can save the POP instruction. This function should be compatible with gcc for MMIX. (Read TAOCP vol 1. fasc 1 for more information):

compareDoubles IS @  ; Declare symbol, @ is the current position
   LDOU $0,$0,0      ; Load first double  (LDOU: load octa unsigned), 1v
   LDOU $1,$1,0      ; Load second double, 1
   FCMP $0,$0,$1     ; Compare floating point values, 4µ
   POP  1,0          ; return, 1µ

If you assemble it, the code is 16 bytes long and may looks this:

8f 00 00 00  8f 01 01 00  01 00 00 01  f8 01 00 00


Significant Whitespace: Robbers This is part of a Cops and Robbers challenge. Go here for the cops' part.

For the purpose of this challenge, we'll define whitespace as only linefeeds (0x0A) and spaces (0x20). Note that most languages and regex flavours consider many other characters as whitespace as well, both inside and outside the ASCII range so you might not be able to make use of the corresponding built-ins.

The Robbers' Challenge

A cop's answer can be cracked by transforming it into a valid program or function (in the chosen language), which performs the task of removing whitespace from an input string, by inserting whitespace into the code. For example if you received the following input:

H e l l o,
 W o r l  d!

The program should output

Hello,World!

After inserting whitespace, the byte count of the solution must not exceed the byte count stated in the cop's answer. You don't have to find the exact same solution as the cop intended, as long as yours is valid by the above constraints.

If you manage this, post an answer with the solution, linking to the cop's answer, and leave a comment on the cop's answer linking back to yours.

The robber who cracks the most cop answers wins. Ties are broken by the sum of sizes of the cracked cop answers (in favour of the robber who cracks longer submissions).

Each cop answer can only be cracked once, and of course, you're not allowed to crack your own answer. If the cop's answer turns out to be invalid before or after being cracked, it is not counted towards the robber's score.

Haskell, 100 bytes, by Laikoni

main=interact$id doid lines id words
doid oi d o id=do
 iddoid<-do oi id
 oid<-do o iddoid
 do d oid