Flag mashup generator Part 2 of the challenge is here

Flags Mashup Bot is a small Twitter bot that generates a new flag based on two random flags and tweets the result every couple of minutes.

Task

Your task is to replicate what the bot does by writing a script or a function based on the following criteria:

The input is any two lossless images composed of at least two, but no more than eight colours.
To mix up the flags the following algorithm has to be used:

Take the first image
For every colour in the first image assign a colour randomly from the second image
Each colour from the second image has to be used at least once

Unless there are less colours in the first image than colours in the second.
You can choose randomly which colours to drop from the second image in this case.

Each colour from the first image has to be replaced with a different colour

Unless there are not enough colours in the second image.
You can choose randomly which colours will be used multiple times in this case.
However you need to make sure none of the colours are used more than any other colour by more than one
example: if you need to assign 2 colours to a flag of 5 colours you'll need to use one of the colour 3 times, while the other one 2 times. You cannot mix them 1 & 4

If a colour is present in both images you cannot assign that colour with itself you'll need to pick another one

The output is the resulting image

Examples

UK & Hungary

Notes: Both flags have three colours, however both use red and white, so those have to be replaced, hence the first invalid example. The second one doesn't use all three colours, and the third one uses non-existent colours.

South Africa & Sweden

Notes: South Africa's flag has 6 colours, while Sweden's have 2, meaning each of the two colours have to be used exactly 3 times. The invalid ones use the colours in a way which is not compatible with this constraint. Note that although both flags use the colour yellow they are actually not the same shade so are considered different

Poland & Poland

Notes: The only valid solution is switching up the two colours.

Notes

The two images don't need to have the same dimensions
The colour list can be different for the two images, so in total there might be 16 colours
The input can be either a lossless image file (example GIF, PNG, BMP, SVG, etc.), or (especially in case of functions) a two dimensional bitmap array holding the colours of the image in any reasonable format. Any native way of storing a bitmap in your language is also fine.
For both input and output images a two dimensional array holding ASCII characters, where different characters count as different colours, counts as a reasonable format, but solutions that work on "real" bitmaps are preferred
The output and input formats don't need to match
I think the colour replacement rules won't prohibit it to work for any valid two input images, but if yes your program doesn't need to work for them
Colours are considered the same only if they are exactly the same based on their RGB value. E.g. #FF0000 and #FF0001 are considered two different colours.
Standard loopholes, as usual, are prohibited

code-golf, so shortest code by byte count wins and will be accepted. If possible please include example a set of input & output images with your submission

JavaScript (Node.js),  160  159 bytes
I/O format: matrix of 24-bit integers.
Takes input as (a)(b).

a=>F=b=>(g=a=>[...new Set(a.flat())].sort(_=>Math.random()-.5))(a).every((c,i)=>c^=F[c]=B[i%B.length],B=g(b).slice(-g(a).length))?a.map(r=>r.map(c=>F[c])):F(b)

Try it online!
Commented
Helper function
The helper function \$g\$ takes a matrix as input and returns a shuffled list of the distinct values it holds.
g = a =>
  [...new Set(a.flat())]
  .sort(_ => Math.random() - .5)

Main code
a => F = b =>                 // a[] = first image, b[] = second image
  g(a).every((c, i) =>        // for each color c at position i in the list of shuffled
                              // colors of the first image:
    c ^=                      //   make sure that c is different from the
      F[c] = B[i % B.length], //     substitute color F[c] picked from the second image
    B =                       //   define B[] as:
      g(b)                    //     the list of shuffled colors from the second image
      .slice(-g(a).length)    //     resized to the number of colors in the first image
  ) ?                         // end of every(); if truthy:
    a.map(r =>                //   return a[] with each original color
      r.map(c => F[c])        //   replaced with its substitute color
    )                         //
  :                           // else:
    F(b)                      //   try again


Calculate Power Series Coefficients Given a polynomial \$p(x)\$ with integral coefficients and a constant term of \$p(0) = \pm 1\$, and a non-negative integer \$N\$, return the \$N\$-th coefficient of the power series (sometimes called "Taylor series") of \$f(x) = \frac{1}{p(x)}\$ developed at \$x_0 = 0\$, i.e., the coefficient of the monomial of degree \$N\$.
The given conditions ensure that the power series exist and that the its coefficients are integers.
Details
As always the polynomial can be accepted in any convenient format, e.g. a list of coefficients, for instance \$p(x) = x^3-2x+5\$ could be represented as [1,0,-2,5].
The power series of a function \$f(x)\$ developed at \$0\$ is given by
$$f(x) = \sum_{k=0}^\infty{\frac{f^{(n)}(0)}{n!}x^n}$$
and the \$N\$-th coefficient (the coefficient of \$x^N\$) is given by
$$\frac{f^{(N)}}{N!}$$
where \$f^{(n)}\$ denotes the \$n\$-th derivative of \$f\$
Examples

The polynomial \$p(x) = 1-x\$ results in the geometric series \$f(x) = 1 + x + x^2 + ...\$ so the output should be \$1\$ for all \$N\$.

\$p(x) = (1-x)^2 = x^2 - 2x + 1\$ results in the derivative of the geometric series \$f(x) = 1 + 2x + 3x^2 + 4x^3 + ...\$, so the output for \$N\$ is \$N+1\$.

\$p(x) = 1 - x - x^2\$ results in the generating function of the Fibonacci sequence \$f(x) = 1 + x + 2x^2 + 3x^3 + 5x^4 + 8x^5 + 13x^6 + ...\$

\$p(x) = 1 - x^2\$ results in the generating function of \$1,0,1,0,...\$ i.e. \$f(x) = 1 + x^2 + x^4 + x^6 + ...\$

\$p(x) = (1 - x)^3 = 1 -3x + 3x^2 - x^3\$ results in the generating function of the triangular numbers \$f(x) = 1 + 3x + 6x^6 + 10x^3 + 15x^4 + 21x^5 + ...\$ that means the \$N\$-th coefficient is the binomial coefficient \$\binom{N+2}{N}\$

\$p(x) = (x - 3)^2 + (x - 2)^3 = 1 + 6x - 5x^2 + x^3\$ results in \$f(x) = 1 - 6x + 41x^2 - 277x^3 + 1873x4 - 12664x^5 + 85626x^6 - 57849x^7 + \dots\$

Mathematica, 24 23 bytes
Saved 1 byte thanks to Greg Martin
D[1/#2,{x,#}]/#!/.x->0&

Pure function with two arguments # and #2. Assumes the polynomial #2 satisfies PolynomialQ[#2,x]. Of course there's a built-in for this:
SeriesCoefficient[1/#2,{x,0,#}]&


What time is it? (Obfuscation) Your goal is to write an obfuscated program that displays the current time.

Guidelines: The program can print local or global time. You are allowed to draw ASCII numbers, display an analog clock, etc. No input should be needed. Whether you include 12 or 24 hour, including AM/PM, milliseconds and seconds or not, it all doesn't matter. This is a popularity contest.

Inspired by sykes2.c, an impressive display of confusing naming, obscure language features, and clever tricks.

Analog clock, JS

Analog clock? Challenge accepted.

Golfed/Obfuscated into the zone of not-exactly-understanding-what-it-does-even-after-reading-through-a-few-times:

for(var a=new Date,b=a.getMinutes(),c=a.getHours()+b/60,d=[],e=Math.round,f=Math.PI,g=Math.sin,h=Math.cos,k=0;11>k;k++)d[k]=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];for(var l=0;l<f;l+=0.05){var m=e(17/11*5*h(2*l)),n=e(5*g(2*l));d[n+5][m+8]=1}for(var p=0;2.5>=p;p+=0.5){var q=e(17/11*p*h(-(c*f/6)+f/2)),r=e(p*g(-(c*f/6)+f/2));d[r+5][q+8]=2}for(p=0;4.5>=p;p+=0.5){var s=e(17/11*p*h(-(b*f/30)+f/2)),t=e(p*g(-(b*f/30)+f/2));d[t+5][s+8]=3}d[5][8]=1;a="";for(k=d.length-1;-1<k;k--)a+=d[k].join("").replace(/0/g,".").replace(/1/g,"O").replace(/2/g,"h").replace(/3/g,"m")+"\n";console.log(a);

Outputs something like:

.....OOOOOOO......
...OO.......OO....
.OO...........O...
.O...h.........O..
O.....hh.......OO.
O......hOmmmmmmmO.
OO.............OO.
.O.............O..
.OO...........O...
...OO.......OO....
.....OOOOOOO......

...yeah, guess what time it is here. (Hint hint not AM)

Human readable version:

var date = new Date();
var min = date.getMinutes();
var hrs = date.getHours()+(b/60); // set up date
var a=[];
for(var i=0;i<11;i++)a[i]=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]; // set up array
function putX(x,y,i){a[y+5][x+8]=i;} // just for source neatness; this is expanded out in the obfuscated version
for(var p=0;p<Math.PI;p+=0.05){ // draw clock border
    putX(Math.round((17/11)*5*Math.cos(2*p)), Math.round(5*Math.sin(2*p)), 1);
}
for(var p=0;p<=2.5;p+=0.5){ // draw hour hand (transforming the angle to work)
    putX(Math.round((17/11)*p*Math.cos(-(hrs*2*Math.PI/12)+(Math.PI/2))), Math.round(p*Math.sin(-(hrs*2*Math.PI/12)+(Math.PI/2))), 2);
}

for(var p=0;p<=4.5;p+=0.5){ // draw the minute hand like the hour hand
    putX(Math.round((17/11)*p*Math.cos(-(min*2*Math.PI/60)+(Math.PI/2))), Math.round(p*Math.sin(-(min*2*Math.PI/60)+(Math.PI/2))), 3);
}

putX(0,0,1); // set the center point

date=""; // reuse date for maximum confusion :)
for(var i=a.length-1;i>-1;i--)date+=a[i].join("").replace(/0/g, ".").replace(/1/g, "O").replace(/2/g, "h").replace(/3/g, "m")+"\n"; // output ASCII art to string
console.log(date); // output string to console


Generate a pronounceable word The challenge is simple:

generate a word.

Specifications:

Word must be pronounceable.

This is defined as "alternating between a consonant and a vowel."
A consonant is one of the following letters: bcdfghjklmnpqrstvwxz
A vowel is one of the following letters: aeiouy

Word must be randomly generated.
Words must be able to contain every consonant and vowel. (You can't just use bcdf for consonants and aei for vowels.)
Word must contain 10 letters.
Shortest code (in character count) wins.

Ruby: 56 characters
([v=%w(a e i o u y),[*?a..?z]-v]*5).map{|a|$><<a.sample}

Example outputs:

itopytojog
umapujojim
ipagodusas
yfoqinifyw
ebylipodiz


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

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

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

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

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

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

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

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

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

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

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

Ruby, Into the Corner, Score: 3340

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

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

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

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

    board
end

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

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

    spawned = board.clone

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

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

    board = slide(board, dir)

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

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

You can test it with this snippet

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

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

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

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

This is the board you end up with

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


How do I craft that? There are 21 items in Minecraft that you can craft using only wood and items crafted from wood:

  axe
  boat
  bowl
  button
  chest
  crafting table
  door
  fence
  gate
  hoe
  ladder
  pickaxe
  planks
  pressure plate
  shovel
  sign
  slab
  stairs
  stick
  sword
  trapdoor

This list assumes that the 6 different types of wooden planks/slabs/doors/etc. all count as the same item. Another way to think of it is to assume you only have access to one type of wood.

Each of these 21 items has a different crafting recipe. We'll represent each of these recipes as a 2×2 or 3×3 grid of the characters .WPS. The . is an empty crafting slot, W is for wood, P is for wood planks, and S is for sticks. No other characters are needed for these particular items.

For example, this is the recipe for a chest:

PPP
P.P
PPP

Challenge

Write a program that takes in the name of one of our 21 items, exactly as it appears above, and prints a valid crafting recipe for that item.

Crafting recipes are translation invariant, so if the input is fence, both of these are valid:

PSP
PSP
...

...
PSP
PSP

If a recipe fits in a 2×2 grid, you can output it in a 2×2 or 3×3 grid. e.g. stick:

.P
.P

...
.P.
.P.

Recipes can also be mirrored horizontally (around a vertical line of symmetry), though this only makes a difference for the axe, hoe, and stairs. e.g. hoe:

.PP
.S.
.S.

PP.
.S.
.S.

So outputting any recipe that fits in the grid and has the correct shape (ignoring translation and mirroring) is what your program needs to do. These are all the recipes that the official game will recognize. (Note that recipes cannot be rotated or mirrored vertically.)

Details

Take input from stdin or the command line. You can assume the input is always valid. Requiring quotes around input (e.g. "chest") is fine.
Output to stdout (or closest alternative) with an optional trailing newline.
The shortest submission in bytes wins.

Example

Here's a list of all inputs and sample outputs:

axe
PP.
SP.
S..

boat
P.P
PPP
...

bowl
P.P
.P.
...

button
P.
..

chest
PPP
P.P
PPP

crafting table
PP
PP

door
PP.
PP.
PP.

fence
PSP
PSP
...

gate
SPS
SPS
...

hoe
PP.
S..
S..

ladder
S.S
SSS
S.S

pickaxe
PPP
.S.
.S.

planks
W.
..

pressure plate
PP
..

shovel
P..
S..
S..

sign
PPP
PPP
.S.

slab
PPP
...
...

stairs
P..
PP.
PPP

stick
P.
P.

sword
P..
P..
S..

trapdoor
PPP
PPP
...

CJam, 100 96 94 91 bytes

"+WcbKF AQH;_{GM8Lyf=_tmTn"141bDb3/l72b970%={Z"O>HVa=4a"98bZb+"P.SW"f=3/=}%N*

StackExchange mangles unprintables, so rather than copying and pasting here is the permalink. Additionally, here's the test program.

(Thanks to @Optimizer for telling me about f and @MartinBüttner for telling me about CJam's modulo indexing.)

Cygwin's hexdump:

0000000 0122 2b1e 571a 6308 621f 4b05 2046 5141
0000010 1608 1848 5f3b 1115 1d7b 4d47 4c38 6679
0000020 5f3d 6d74 0c54 226e 3431 6231 6244 2f33
0000030 376c 6232 3739 2530 7b3d 225a 1b4f 483e
0000040 6156 343d 2261 3839 5a62 2b62 5022 532e
0000050 2257 3d66 2f33 7d3d 4e25 002a
000005b

Explanation

To construct the recipes, we use 13 different rows (also listed are explanations why this is minimal):

0    W..    (required by planks)
1    ...    (required by many)
2    .PP    (required by many)
3    PPP    (required by chest)
4    .P.    (required by bowl)
5    ..P    (required by stairs)
6    S.S    (required by ladder)
7    SSS    (required by ladder)
8    .S.    (required by sign)
9    .SP    (required by axe)
10   P.P    (required by bowl)
11   PSP    (required by fence)
12   SPS    (required by gate)

We encode the rows via Z"O>HVa=4a"98bZb+"P.SW"f=3/, which gives

["W.." "..." ".PP" "PPP" ".P." "..P" "S.S" "SSS" ".S." ".SP" "P.P" "PSP" "SPS"]

The first bit "+WcbKF AQH;_{GM8Lyf=_tmTn"141bDb3/ encodes the recipes, giving

[[3 3 8] [1 0 0] [1 0 0] [3 8 8] [1 3 3] [2 8 8] [6 7 6] [1 0 0] [1 10 3] [1 1 2] [2 2 2] [1 11 11] [1 1 4] [1 0 1] [1 10 4] [2 9 8] [3 10 3] [1 2 2] [4 8 8] [1 4 4] [1 1 3] [1 12 12] [4 4 8] [5 2 3]]

Note how the first entry is [3 3 8], which is the recipe for sign.

l72b970%= reads in the input, then applies some magic to work out which recipe to take from the list. Even though we only have 21 recipes there are 24 in the list — the extra few spots correspond to the [1 0 0]s.

After reading the input, picking the recipe and converting the recipe to rows, we put in some newlines N* and auto-print.

CJam, 89 86 83 bytes

'W"9=!%)S@*m:@DQzk?V$%qyR55AmVEpPNW}"132b3b"P.S"f=+3/3/l57b5342%24%(=N*

... it turns out that hardcoding all the outputs does a bit better in CJam. I'm pretty disappointed.

Once again we have some unprintables so here's the permalink and test program.

Cygwin's hexdump:

0000000 5727 0222 3d39 1021 2925 531e 2a40 6d0b
0000010 403a 1844 7a51 3f6b 2456 7125 5279 3506
0000020 4135 046d 1a56 7045 1550 164e 1057 7d01
0000030 3122 3233 3362 2262 2e50 2253 3d66 332b
0000040 332f 6c2f 3735 3562 3433 2532 3432 2825
0000050 4e3d 002a
0000053

Explanation

The outputs are encoded using base 3, with the lone W being tacked onto the front before the string is split into 3s to give rows, and the rows are split into groups of 3s to give recipes.

Like above, base converting and modulo magic is used to select the recipe. There are 22 recipes (one unused) but we need to take modulo 24, so we actually need to explicitly specify 24% this time rather than relying on modulo indexing.


Draw ASCII boxes in boxes Problem

given input a,b,c

where a,b,c are positive even integers

and a > b > c

Make a box of any allowed character  with dimensions a x a

Center a box of a different allowed character with dimensions b x b within the previous

Center a box of another different allowed character with dimensions c x c within the previous

Allowed Characters are ASCII characters are in [a-zA-z0-9!@#$%^&*()+,./<>?:";=_-+]

Input a=6, b=4, c=2

######
#****#
#*@@*#
#*@@*#
#****#
######

Input a=8, b=6, c=2

########
#******#
#******#
#**@@**#
#**@@**#
#******#
#******#
########

Input a=12, b=6, c=2

############
############
############
###******###
###******###
###**@@**###
###**@@**###
###******###
###******###
############
############
############

Rules

Shortest code wins
Remember that you can choose which char to print within the range given
Trailing newlines accepted
Trailing whitespace accepted
functions may return string with newlines, string array, or print it

Jelly,  20  19 bytes

-1 byte using the quick ` to avoid a link, as suggested by Erik the Outgolfer.

H»þ`€Ḣ>Ð€HSUṚm€0m0Y

A full program taking a list [a,b,c] printing the boxes using a:2 b:1 c:0
... in fact, as is, it will work for up to 10 boxes, where the innermost box is 0 (for example).

Try it online!

How?

H»þ`€Ḣ>Ð€HSUṚm€0m0Y - Main link: list of boxes, B = [a, b, c]
H                   - halve B = [a/2, b/2, c/2]
    €               - for €ach:
   `                -   repeat left argument as the right argument of the dyadic operation:
  þ                 -     outer product with the dyadic operation:
 »                  -       maximum
                    - ... Note: implicit range building causes this to yield
                    -       [[max(1,1),max(1,2),...,max(1,n)],
                    -        [max(2,1),max(2,2),...,max(2,n)],
                    -        ...
                    -        [max(n,1),max(n,2),...,max(n,n)]]
                    -       for n in [a/2,b/2,c/2]
     Ḣ              - head (we only really want n=a/2 - an enumeration of a quadrant)
         H          - halve B = [a/2, b/2, c/2]
       Ð€           - map across right with dyadic operation:
      >             -   is greater than?
                    - ...this yields three copies of the lower-right quadrant
                    -    with 0 if the location is within each box and 1 if not
          S         - sum ...yielding one with 0 for the innermost box, 1 for the next, ...
           U        - upend (reverse each) ...making it the lower-left
            Ṛ       - reverse ...making it the upper-right
             m€0    - reflect €ach row (mod-index, m, with right argument 0 reflects)
                m0  - reflect the rows ...now we have the whole thing with integers
                  Y - join with newlines ...making a mixed list of integers and characters
                    - implicit print - the representation of a mixed list is "smashed"


Plant trees on a golf course! This challenge is inspired by this app.

This is a much easier version of this challenge. This challenge is code-golf, while the other one is fastest-code.

You'll be given a square input grid, of dimensions 6-by-6 which is divided into 6 areas, where the cells of each area have a unique identifier (I'll use lower case letters from a-f in the the text here, but you may choose whatever you like, for instance integers 1-6).

The input may look like this (optional input format):

aabbbb
aabbbb
aaccbb
acccdb
ecccdb
eeefff

Or, easier to visualize:

Challenge:

You are to place 6 trees in this park, according to the following rules:

There shall be exactly 1 tree per column, and 1 tree per row
All areas shall have exactly 1 tree.
No trees can be adjacent to another tree, vertically, horizontally or diagonally

The solution to the layout above is:

Note: There is only one solution to each puzzle

Additional rules:

The input and output formats are optional

The output might for instance be a list of indices, a grid with 1/0 indicating if there's a tree in that position, or a modified version of the input where the trees are indicated

The execution time must be deterministic
The program must finish within 1 minute on a reasonable modern laptop
Brownie points if you don't brute force!

Test cases:

aabbbb
aabbbb
aaccbb
acccdb
ecccdb
eeefff
---
aAbbbb
aabbbB
aaCcbb
acccDb
Ecccdb
eeeFff
----------
aabccc
aacccc
aaddce
aeeeee
aeeefe
eeeeee
---
aaBccc
aacccC
aadDce
Aeeeee
aeeeFe
eEeeee
----------
aaaabb
aacbbb
aadddb
addeef
ddddee
dddeee
---
aaaaBb
aaCbbb
Aadddb
addeeF
dDddee
dddEee
----------
abbbcd
abebcd
addddd
dddddd
effdff
eeffff
---
abBbcd
abebCd
Addddd
dddDdd
effdfF
eEffff

Same test cases on a format that's a bit easier to parse:

Test case 1:
[1,1,2,2,2,2;1,1,2,2,2,2;1,1,3,3,2,2;1,3,3,3,4,2;5,3,3,3,4,2;5,5,5,6,6,6]
Test case 2:
[1,1,2,3,3,3;1,1,3,3,3,3;1,1,4,4,3,5;1,5,5,5,5,5;1,5,5,5,6,5;5,5,5,5,5,5]
Test case 3:
[1,1,1,1,2,2;1,1,3,2,2,2;1,1,4,4,4,2;1,4,4,5,5,6;4,4,4,4,5,5;4,4,4,5,5,5]
Test case 4:
[1,2,2,2,3,4;1,2,5,2,3,4;1,4,4,4,4,4;4,4,4,4,4,4;5,6,6,4,6,6;5,5,6,6,6,6]

C, 223 182 bytes

O[15],U;main(y,v)char**v;{if(y>7)for(;y-->2;printf("%06o\n",O[y]));else for(int*r,x=1,X=8;X<14;U&x|*r|O[10-y]*9&x*9?0:(U^=O[9-y]=*r=x,*r=main(y+1,v),U^=x),x*=8)r=O+v[1][y*7-++X]-88;}

Takes input as an argument in the format given in the question. Writes output to stdout as a grid of 0s with 1s where the trees go.

./TreesMin 'aabbbb
aabbbb
aaccbb
acccdb
ecccdb
eeefff'

Sample output:

010000
000001
001000
000010
100000
000100

Breakdown

O[15],                                  // Tree positions & region usage
U;                                      // Column usage (bitmask)
main(y,v)char**v;{                      // Recursive main function
  if(y>7)                               // Finished grid?
    for(;y-->2;printf("%06o\n",O[y]));  //  Print it (rows are padded octal)
  else                                  // Not finished:
    for(int*r,x=1,X=8;X<14;             //  Loop over columns
      U&x|*r|O[10-y]*9&x*9              //   Current cell violates rules?
        ?0                              //    Do nothing
        :(U^=O[9-y]=*r=x,               //   Else: mark cell
          *r=main(y+1,v),               //    Recurse
          U^=x)                         //    Unmark cell
      ,x*=8)                            //   Advance to next column
      r=O+v[1][y*7-++X]-88;             //   Region pointer for current iteration
}

It's an adaptation of my answer to the fastest-code version of this question. Doesn't have as much short-circuiting, but it's plenty fast enough for 6x6 grids.


PPCG Jeopardy: Robbers How well do you know the site?  Let's find out.

This is a cops-and-robbers challenge.  Cop's thread.

As a robber, you need to:

Find a non-deleted, non-closed challenge that matches a cop's submission.  The challenge cannot have the following tags: cops-and-robbers, popularity-contest, code-trolling, underhanded, busy-beaver, king-of-the-hill, tips, answer-chaining.  The challenge must have restrictions on valid output.
Post the challenge here, and link to the cop you are cracking
Add a "Cracked" comment to the cops' post, with a link back to this answer

You will receive 1 point, plus 1 point for each 24-hour period the submission had remained uncracked (max 7).  Tiebreaker is the total number of cracked submisisons.

Notes:

If a challenge requires an output of X, and you output XY or YX where Y is anything besides whitespace, the submission is not valid for that challenge.
A challenge newer than 2016-11-17 is not allowed.
I reserve the right to ban certain challenges if they are widely applicable (could be applied to the majority of all submissions).
Make sure you add a sentence or two as an explanation (it also helps your submission from being converted to a comment)
Thanks to Daniel for the initial idea!

Calculate probability of getting half as many heads as coin tosses.

Cops entry (posted by Conor O'Brien): https://codegolf.stackexchange.com/a/100521/8927

Original question: Calculate probability of getting half as many heads as coin tosses.

The posted solution had a couple of obfuscation techniques applied, followed by multiple layers of the same obfuscation technique. Once past the first few tricks, it became a simple (if tedious!) task to extract the actual function:

nCr(a,b) = a! / ((a-b)! * b!)
result = nCr(x, x/2) / 2^x

Took a while to realise what I was looking at (for a while I suspected something to do with entropy), but once it twigged, I managed to find the question easily by searching for "probability of coin toss".

Since Conor O'Brien challenged an in-depth explanation of his code, here's a rundown of the more interesting bits:

It starts by obfuscating some built-in function calls. This is achieved by base-32 encoding the function names, then assigning them to new global-namespace names of a single character. Only 'atob' is actually used; the other 2 are just red-herrings (eval takes the same shorthand as atob, only to be overridden, and btoa simply isn't used).

_=this;
[
    490837, // eval -> U="undefined"       -> u(x) = eval(x) (but overwritten below), y = eval
    358155, // atob -> U="function (M,..." -> u(x) = atob(x)
    390922  // btoa -> U="function (M,..." -> n(x) = btoa(x), U[10] = 'M'
].map(
    y=function(M,i){
        return _[(U=y+"")[i]] = _[M.toString(2<<2<<2)]
    }
);

Next there are a couple of trivial string mix-ups to hide the code. These are easily reversed:

u(["","GQ9ZygiYTwyPzE6YSpk","C0tYSki","SkoYSkvZChhLWIpL2QoYikg"].join("K"))
// becomes
'(d=g("a<2?1:a*d(--a)"))(a)/d(a-b)/d(b) '

u("KScpKWIsYShFLCliLGEoQyhEJyhnLGM9RSxiPUQsYT1D").split("").reverse().join("")
// becomes
"C=a,D=b,E=c,g('D(C(a,b),E(a,b))')"

The bulk of the obfuscation is the use of the g function, which simply defines new functions. This is applied recursively, with functions returning new functions, or requiring functions as parameters, but eventually simplifies right down. The most interesting function to come out of this is:

function e(a,b){ // a! / ((a-b)! * b!) = nCr
    d=function(a){return a<2?1:a*d(--a)} // Factorial
    return d(a)/d(a-b)/d(b)
}

There's also a final trick with this line:

U[10]+[![]+[]][+[]][++[+[]][+[]]]+[!+[]+[]][+[]][+[]]+17..toString(2<<2<<2)
// U = "function (M,i"..., so U[10] = 'M'. The rest just evaluates to "ath", so this just reads "Math"

Although since the next bit is ".pow(T,a)", it was always pretty likely that it would have to be "Math"!

The steps I took along the route of expanding functions were:

// Minimal substitutions:
function g(s){return Function("a","b","c","return "+s)};
function e(a,b,c){return (d=g("a<2?1:a*d(--a)"))(a)/d(a-b)/d(b)}
function h(a,b,c){return A=a,B=b,g('A(a,B(a))')}
function j(a,b,c){return a/b}
function L(a,b,c){return Z=a,Y=b,g('Z(a,Y)')}
k=L(j,T=2);
function F(a,b,c){return C=a,D=b,E=c,g('D(C(a,b),E(a,b))')}
RESULT=F(
    h(e,k),
    j,
    function(a,b,c){return _['Math'].pow(T,a)}
);

// First pass
function e(a,b){
    d=function(a){return a<2?1:a*d(--a)}
    return d(a)/d(a-b)/d(b)
}
function h(a,b){
    A=a
    B=b
    return function(a){
        return A(a,B(a))
    }
}
function j(a,b){ // ratio function
    return a/b
}
function L(a,b){ // binding function (binds param b)
    Z=a
    Y=b
    return function(a){
        return Z(a,Y)
    }
}
T=2; // Number of states the coin can take
k=L(j,T); // function to calculate number of heads required for fairness
function F(a,b,c){
    C=a
    D=b
    E=c
    return function(a,b,c){return D(C(a,b),E(a,b))}
}
RESULT=F(
    h(e,k),
    j,
    function(a){return Math.pow(T,a)}
);

// Second pass
function e(a,b){...}
function k(a){
    return a/2
}
function F(a,b,c){
    C=a
    D=b
    E=c
    return function(a,b,c){return D(C(a,b),E(a,b))}
}
RESULT=F(
    function(a){
        return e(a,k(a))
    },
    function(a,b){
        return a/b
    },
    function(a){return Math.pow(2,a)}
);

// Third pass
function e(a,b) {...}
C=function(a){ // nCr(x,x/2) function
    return e(a,a/2)
}
D=function(a,b){ // ratio function
    return a/b
}
E=function(a){return Math.pow(2,a)} // 2^x function
RESULT=function(a,b,c){
    return D(C(a,b),E(a,b))
}

The structure of the function nesting is based around utility; the outer-most "D" / "j" function calculates a ratio, then the inner "C" / "h" and "E" (inline) functions calculate the necessary coin flip counts. The "F" function, removed in the third pass, is responsible for connecting these together into a usable whole. Similarly the "k" function is responsible for choosing the number of heads which need to be observed; a task which it delegates to the ratio function "D"/"j" via the parameter binding function "L"; used here to fix parameter b to T (here always 2, being the number of states the coin can take).

In the end, we get:

function e(a,b){ // a! / ((a-b)! * b!)
    d=function(a){return a<2?1:a*d(--a)} // Factorial
    return d(a)/d(a-b)/d(b)
}
RESULT=function(a){
    return e(a, a/2) / Math.pow(2,a)
}


Most efficient cubifier Cubically is too tedious to manually write any code in. Your challenge is to translate ASCII text into Cubically source code.

Cubically

This is just a quick run-down of Cubically; the repository has a more complete guide and details.

Cubically is an esolang I wrote a while ago, designed to be painful to use. It contains two pieces of memory, a 3x3x3 Rubik's Cube and a register called the "notepad".

Memory

The internal Rubik's Cube is initialized like this:

   000
   000          top face
   000
111222333444    left, front, right, and back faces, respectively
111222333444
111222333444
   555
   555          down face
   555

After performing a clockwise 90° turn on the right face, the memory cube would look like this:

   002
   002
   002
111225333044
111225333044
111225333044
   554
   554
   554

Commands

A non-integer character sets the default command. For each integer before the default command is set once again, the command is performed with that integer. For example, x524y312 would perform command x with 5, then with 2, then with 4, then perform command y with 3, then with 1, then with 2.

The integers that commands use represent face indexes. So x0 would perform x on the UP (0-indexed) face. x1 would perform x on the LEFT (1-indexed) face, and so on.

Performing any command with 6 will perform that command on the notepad value. Performing any command with any integer over 6 will result in an error.

Here are some example commands:

R1 - turn the RIGHT face clockwise 90° so the internal cube will look like the second example above
R11 - turn the RIGHT face clockwise 90° twice, identical to R2
+0 - add all values of the UP face to the notepad
+000 - add all values of the UP face to the notepad three times
@6 - print the nonexistent 6th-indexed face (memory) as a character
%4 - print the sum of all values on the BACK face as an integer

A complete list of commands and syntax is available at the repository.

Challenge

You will take ASCII text as input and print a Cubically program as output.

Examples (stolen from here and here):

Input -> Output
Hello, World! -> +53@6+1F2L2+0@6L2F2U3R3F1L1+2@66L3F3R1U1B3+0@6:4U1R1+00@6-000@6*0-4+000@6-00@6+2-000000@6-5+4000@6-00@6/0+00@6:0+0/0+00@6
1$2$3$4$5$6$7$8$9$10$ -> B1+2/2%6@4+00/0%6@4+00/1%6@4+21/1%6@4+30/0%6@4+22/1%6@4+22/1%6@4+40/1%6@4+52/1%6@4+42/1%6@4

Rules

Your program may not contain a dictionary containing the translations for the 100 testcases.
Your program must finish in less than 180 seconds (no brute-force programs that take weeks).
Your program must output valid Cubically code that finishes in less than 180 seconds.
Your program will take input via standard input, unless you want to mess with the test driver.
Your program must output Cubically code that produces nothing but your program's input when run. ಠ_ಠ

Scoring

You will test your program with 100 pseudorandom strings of pseudorandom length. (A bash script is provided that will do this for you.) Here is how you will score:

Let the length of the output program be o.
Let the length of the input string be l.
Let a variable r be the result of o/l.
Find the average of all r: (r1 + r2 + r... + r100) / 100.

Test with this script. You'll have to modify it as instructed. Note that the program does not check whether the output is valid Cubically code.
If you can't get the script working, I can help. Ping me in the Cubically chat room.

Lua, Score: 85.91 13.50 13.20 12.70 9.41 9.32 9.83 9.66 9.12 9.06 8.03 (Average)

-- Get input
local inp = io.read("*a")

local out = ""
local faces = { [5] = 45, [4] = 36, [3] = 27, [2] = 18, [1] = 9 }
local lastChar = nil

-- Mode the program is in
-- 2 = not set (needs :), 1 = just set (needs +), 0 = normal
local mode = 1;
for i = 1, inp:len() do
  -- Character value at current position
  local c = string.byte(inp, i)

  if c == lastChar then
    -- Repeat character
    out = out .. "6"
  elseif c % 9 == 0 and c <= 45 then
    if #out == 0 then
      out = out .. "@"
    end
    out = out .. (c / 9)
  else
    local c2 = c

    -- Handle if difference from lastChar is divisible by 9
    if lastChar and (c - lastChar) % 9 == 0 then
      local difference = c - lastChar
      if difference > 0 then
        out = out .. "+"
      else
        out = out .. "-"
        difference = difference * -1
      end

      for index = 5, 1, -1 do
        local face = faces[index]
        while difference >= face do
          difference = difference - face
          out = out .. index
        end
      end
      c = 0
    end

    -- Handle anything not divisible by 9
    local extra = c % 9
    if extra > 0 then
      -- Try to optimize by dividing by 9, if possible
      if lastChar and math.floor(lastChar / 9) == extra then
        out = out .. "/1"
        mode = 1
        extra = 0
      else
        while extra > 0 do
          local n = extra > 5 and 5 or extra

          if mode == 2 then
            out = out .. ":"
            mode = 1
          elseif mode == 1 then
            out = out .. "+"
            mode = 0
          end
          out = out .. n
          extra = extra - n
        end
        out = out .. "/1"
        mode = 1
      end

      c = c - (c % 9)
    end

    -- Handle anything divisible by 9
    for index = 5, 1, -1 do
      local face = faces[index]
      while c >= face do
        if mode == 2 then
          out = out .. ":"
          mode = 1
        elseif mode == 1 then
          out = out .. "+"
          mode = 0
        end
        c = c - face
        out = out .. index
      end
    end

    out = out .. "@6"
    lastChar = c2
  end

  mode = 2
end
print(out)

Try it online!

Okay, I don't think I can optimize this anymore.

This version iterates through each character, adding c % 9 (where c is the character's decimal value) by doing :5+2/1, then adds the parts divisible by 9 by adding that face's value. For example: :2/1+551@ to print "e", where :2/1 adds 2, +551 adds 99 (9 * (5 + 5 + 1), or 9 * 11), and @ prints the output. Input is read with io.read().

Optimizations include directly adding/subtracting after printing if the difference between characters is a multiple of 9, dividing the current value if possible rather than setting c % 9 from scratch, and repeating characters by printing the current value again rather than recalculating it. Additionally, I've implemented Kamil's method of instantly printing any face that already contains the target value, and MD XF's suggestion to not use : at the beginning, but instead just start with a +.


Which language is shortest? Create a program that find the latest 50 challenges with the code-golf-tag that have at least 20 answers. Then, extract the scores for each language in each of the challenges. If there are more than one answer using the same language, count all scores. Thereafter, take the top 20 most common languages and output a list with the language names, the number of answers, the average byte counts and the median byte counts. The list should be sorted by number of answers, in descending order.

You must account for variations in capitalization (for instance: Matlab = MATLAB).

In languages with many different version numbers (e.g. Python), count them as unique languages, so: Python != Python 2 != Python 2.7 != Python 3.x

Example output (output format is optional):

cJam,       66,  12.4,  8.5
Pyth,       58,   15.2,  19
Ruby,       44,   19.2,  22.5
Python,     34,   29.3,  32
Python 2.7, 22,   31.2,  40
...
...
Java,       11,   115.5, 94.5

Header formats that must be supported:

Starts with # Language name, or #Language name
Ends with xx bytes, xx Bytes or just xx
There can be a lot of garbage between the first comma and the last number.
If the language name is a link ([Name](link)), it can be skipped

If the answer has another header format, you may choose to skip it (or include it if your code can handle it).

As an example, all of the below headers must be supported:

# Language Name, N bytes
# Ruby, <s>104</s> <s>101</s> 96 bytes
# Perl, 43 + 2 (-p flag) = 45 Bytes
# MATLAB, 5

Rules:

It's OK to use API or just the website-url

The following can be extracted from the byte count (nothing else), so no need to use a url-shortener (Maximum 44 bytes):

https:// (or http://)
codegolf
.stackexchange.com
/questions

The program can take input. The input will be included in the byte count.

Other than that, standard rules apply.

R, 821 - 44 = 777 bytes

Updated results: please see the edit history to make sense of all the comments below.

           language num_answers avg_count median_count
1              RUBY          49  49.97959         30.0
2              CJAM          48  32.64583         22.0
3              PYTH          48  21.02083         14.0
4          PYTHON 2          46  86.78261         77.0
5             JULIA          43  58.90698         45.0
6           HASKELL          41  74.65854         56.0
7               PHP          40  73.52500         48.0
8              PERL          36  53.30556         34.0
9          PYTHON 3          34  90.91176         90.5
10       POWERSHELL          33  60.24242         44.0
11                C          32 221.84375         79.5
12                R          32  77.40625         62.5
13             JAVA          29 170.68966        158.0
14 JAVASCRIPT (ES6)          29  90.79310         83.0
15       JAVASCRIPT          28  68.39286         61.0
16               C#          25 193.92000        130.0
17      MATHEMATICA          23  56.04348         47.0
18           MATLAB          22  67.45455         55.0
19         TI-BASIC          19  47.05263         37.0
20              APL          18  16.55556         15.0

The code, which I could shorten a bit more:

W=library;W(XML);W(plyr)
X=xpathSApply;Y=xmlValue;D=data.frame;H=htmlParse;S=sprintf
Z="http://codegolf.stackexchange.com/"
R=function(FUN,...)do.call(rbind,Map(FUN,...))
G=function(url){d=H(url)
a=as.double(sub(".*?(\\d+)a.*","\\1",X(d,"//div[starts-with(@class,'status')]",Y)))
u=paste0(Z,X(d,"//*[contains(@class,'question-hyperlink')]",xmlGetAttr,"href"))
D(u,a)}
u=S("%s/questions/tagged/code-golf?page=%i",Z,1:50)
q=R(G,u)
u=with(q,head(u[a>20],50))
A=function(url){u=S("%s?page=%i",url,1:10)
f=function(u){d=H(u)
h=X(d, "//div[@class='post-text']//h1",Y)
p="^(.*?),.*? (\\d+)( [Bb]ytes)?$"
k=grep(p,h,v=T)
l=toupper(sub(p,"\\1",k))
c=as.double(sub(p,"\\2",k))
D(l,c)}
R(f,u)}
a=R(A,u)
L=names(tail(sort(table(a$l)),20))
x=subset(a,l%in%L)
arrange(ddply(x, "l",summarise,n=length(c),a=mean(c),m=quantile(c,0.5)),-n)

De-golfed:

library(XML)
library(plyr)
LoopBind <- function(FUN, ...) do.call(rbind, Map(FUN, ...))
GetQuestions <- function(url) {
  d = htmlParse(url)
  a=as.double(sub(".*?(\\d+)a.*","\\1",xpathSApply(d, "//div[starts-with(@class, 'status')]", xmlValue)))
  u=paste0("http://codegolf.stackexchange.com/",xpathSApply(d, "//*[contains(@class, 'question-hyperlink')]", xmlGetAttr, "href"))
  data.frame(u, a)
}
u <- sprintf("http://codegolf.stackexchange.com/questions/tagged/code-golf?page=%i", 1:50)
q <- do.call(rbind, Map(GetQuestions, u))
u <- with(q, head(u[a > 20], 50))

GetAnswers <- function(url) {
  u=sprintf("%s?page=%i",url,1:10)
  f=function(u) {
    d = htmlParse(u)
    h = xpathSApply(d, "//div[@class='post-text']//h1", xmlValue)
    p = "^(.*?),.*? (\\d+)( [Bb]ytes)?$"
    k = grep(p,h,v=T)
    l = toupper(sub(p,"\\1",k))
    c = as.double(sub(p,"\\2",k))
    data.frame(language=l,c)
  }
LoopBind(f,u)
}
a=LoopBind(GetAnswers, u)
L=names(tail(sort(table(a$l)),20))
x=subset(a,language%in%L)
arrange(ddply(x, "language", summarise, num_answers = length(c), avg_count = mean(c), median_count = quantile(c,0.5)),
        -num_answers)


Randomly Assign People to Tasks The challenge is to assign people to tasks randomly~.
From stdin you get 2 lines. Line one is a comma-separated list of names. Line 2 is a comma-separated list of jobs.
The output required is one line per task person combo.
The line should be formatted as Name:task.
If there are not enough people for jobs or vice verse then they will not be output.

~ Randomly is defined as each run with the same input has a reasonably different output.

Example Input:

Bob,John,Susan,Josie,Kim,Tom
Bins,Floor,Windows

Example Output:

Bob:Windows
Susan:Bins
Kim:Floor

05AB1E, 7 bytes
Code:
.r².r)ø

Try it online
Following the input/output spec strictly (16 bytes):
.r².r)øvy`r?':?,

Explained:
.r                # radomize first input
  ².r             # randomize second input
     )ø           # merge the lists to an array of pairs cutting out extras
       vy`r?':?,  # format output

Try it online


Fibonacci program lengths Write a program with length n that outputs another program whose length is the next Fibonacci number after n. The new program must do the same thing - output another program whose length is the next Fibonacci number, etc.
n itself (the original program's length) does not have to be a Fibonacci number, although it would be nice if it is.

Shortest code wins.

No external resources, ASCII only, free compiler/interpreter required.
If your output ends in a newline, it is also counted.


Javascript, 2227 bytes

@Peter Taylor: Challenge Accepted!

_='S=b9b?b^3?"{"+)+"}":\'"\'+)+\'"\':"["+b6SB" ")+"]":""+b};$=b||!b99b:[b]b6$B""L;M=b9$(bb+""};A=b?(gb.charCodeAt(0)A(b1))v=g,v=3,g,v};C=b9(k=b6Ck=b,kb};a=g,s,O,r=Wj,uX,d,c,i,yPb=(b?$(bb+"").match(/\'(.|[^\'])*\'|"(.|[^"])*"|-?\\d+|\\043[^\\n]*|[a-z_]\\w*|./imgFi=y=0;z=b[i++];)"{"Yz?!y++Zk=iy?"}"Yz!--yZe=A(bk,i-1B""))e=4\'"\'YzQ?A(eval(z.replace("\\n","n")))"\'"YzQ?A(z1,-1).replace(/(|\')/g,"$1"))":"Yz?r[b[i++]]=(d=s[s-1])^4?S(dd:r[z]?r[z]z+"."-0.1?eval(z)eval("//~t;t98?ts=st~t\\140A(S(G)))//[O.uns]JEt,u@`vEuX,v%`I!u)t%u!tPt3?[32]:[]Xu+tV-5!~tc)RcL# q-t/`I!u)Math.floot/u)!tPv=0;j%tY0ZvRvv,vvcdvLu^4Pp=1 ITPFd;\'.\'u;)ds[s-1]tGdL#{D;HL//*7I!t)q*t!uPFd;u--;)T?td=dCUd=8;T||dL8^4P!u8Zu6M)6A)d=dC(j?t:[]cd=8;GdL#{q.)HL//zipt;Fv=c;v--;)!d[v]Zd[v]d[v]c[v]?7IT)HG)Zcu# t9tuMath.pow(uX)$t;u=0;t9(T?(u=t,G)t).sort(uZaua,bubb-a}C(s~t)Q)=`t!9ut)Q:0|$(u)Y$U>N$U|0:t0Xu>t|0V)K()]:[t+1](K.)]:[t-1]&5v;~tc)vc   &t|5dvt |t^5v;k,ut!~tc)^!~kc)vc ^tif`v=?u:t;v^4?A(S(v)v!+!randMath.random()*G)|0)".split("//"+z)[1]L,\'{1$if}:and{1$if}:or{!!{!}*}:xor{..0sZOQ=sFfoGs(HctIif(Js.splice(O.))Kt;s=st9[tXL)}N`q9t9$(u)P){Q[0]RdT8>3U(t)V8//Wfunction(b,X,tY==Z(`;qu';for(Y=0;$='q`ZYXWVUTRQPNLKJIHGFEDB98765#  '[Y++];)with(_.split($))_=join(pop());eval(_)

Note: Contains some control characters, nothing outside of ASCII though. Here's a direct link to the file: gs.js. The code provides a function a which takes the Golfscript code as a single parameter and returns the resulting stack as an array, with strings and blocks represented as ASCII.

Differences from the official interpreter:

Numbers have only 53 bits precision
No exact output and no direct print (would be easy to add though)
Double quoted strings are parsed using Javascript's eval, which might work different than Ruby's. Also no access to Ruby functions via strings
Undefined behaviour (I tried my very best)

I've also made a bunch of test cases and set up a small form for running Golfscript code: http://copy.sh/golfscript/

Here are some examples:

pi, phi
fizzbuzz
primality test
a quine

This is my standard Golfscript library, suggestions are welcome:

{1$if}:and
{1$\\if}:or
{\!!{!}*}:xor
{..0<2**-}:abs
{\{!}+\while}:until
{0$}:.
"\n":n
{\.[]*{0{2$*\(@+1$}do@;\;}{[{.@.@\\%@@.@\/.}do;;]-1%}if}:base
];


Another Euler Brick in the Wall A Euler Brick is a cuboid where the length of all the edges are integers and all of the diagonals of the faces are integers as well. All sides must also be different.

Your program has to find as many different Euler Bricks where the sides are less than L within the time M (L and M will be defined later).

All of your calculated bricks have to be unique. This means that if your dimensions are the same, just in a different order, it must not be counted.

To calculate a brick means to find the lengths of the edges and the lengths of the diagonals of the faces of a valid Euler Brick.

Your bricks must also be indivisible by each other. In the same way that the Pythagorean triplet 6, 8, 10 is divisible by 3, 4, 5, your bricks must not be divisible by each other.

To test your program, I will need to the following:

The language your code is written in
A command to run your code
Your code

Your score will be the average number of bricks your program calculates (running the program five times). To do this, I will run your program and end it after M minutes have elapsed. Once you have submitted your answer, I will add a comment on your answer telling what your score is. If you make an edit to your code, please notify me directly so I can find your score again.

For that reason, I need your program to print the number of bricks either at throughout the running or at the end. This can be done like so (in Python it would help if people told me how to do this in other languages for this example):

try:
    # Calculation goes here

except KeyboardInterrupt: # I will use Ctrl-C
    print(numberofbricks)
    exit()

For this challenge L=10^30 and M=2 minutes. In the event of a tie, the actual time taken to calculate all of the bricks will be used. The lower time wins.

I will find your time using the script below. All programs will be tested on the same machine.

import time, subprocess
command = # How do you run your program?
s=time.time()
subprocess.Popen(command, shell=True)
e=time.time()
print(e-s)

Leaderboard

1. Peter Taylor  - 5731679685.5 bricks per minute
2. Steve Verrill - 680262303 bricks per minute
3. Beta Decay    - 0.5 bricks per minute

C using Saunderson's parameterisation and Berggren's tree

In 1740, Saunderson found the parameterisation that if (a, b, c) is a Pythagorean triple (i.e. a^2 + b^2 = c^2) then (a(2b-c)(2b+c), b(2a-c)(2a+c), 4abc) is a rational cuboid (this was before Euler studied them) with diagonals (c^3, a(5b^2+a^2), b(5a^2+b^2)). This doesn't generate all Euler bricks. Note that if the brick is primitive iff the Pythagorean triple is primitive.

If (x, y, z) is an Euler brick then so is (xy, xz, yz). Applying this once to a Saunderson brick creates a new brick which isn't Saunderson and which can be made primitive with division by ab. Applying the same transformation a second time gives the non-primitive xyz(x, y, z).

In 1934, Berggren discovered that the primitive Pythagorean triples form a ternary tree rooted at (3, 4, 5) which can be generated by a simple matrix multiplication and which contains each triple precisely once.

This implementation generates primitive Pythagorean triples and stores them in a stack, limiting the memory usage to 1.5GB. An earlier version used a circular buffer, but the stack gives much better results. This is probably a combination of fewer values being discarded and better cache locality.

Thanks to Steve Verrill for pointing out some bugs and for suggesting the use of a stack instead of a circular buffer. I've also followed him in removing the conjugate bricks for speed: previously the search space (minus the discarded branches) was exhausted within the two minutes, and there was value in spending time to get a few conjugates. But the new version can easily run for 5 minutes (as I discovered in the process of learning the value of the volatile keyword!), and most of the conjugates overflow, so on average the tests are wasted time.

#include <stdlib.h>
#include <inttypes.h>
#include <stdio.h>
#include <signal.h>
#include <string.h>

// Stack size. This is 1.5GB of memory.
#define N 33554432

typedef unsigned __int128 scalar;

typedef struct {
    scalar a, b, c;
} triple;

// Stack operations
#define take(st) st[--stp];
#define offer(A,B,C) if (stp < N) { st[stp].a=(A); st[stp].b=(B); st[stp].c=(C); stp++; }

volatile sig_atomic_t stop;

void handler(int sig, siginfo_t *siginfo, void *context) {
    stop = 1;
}

int main(int argc, char **argv) {
    // Register interrupt handler
    stop = 0;
    struct sigaction act;
    memset(&act, 0, sizeof(act));
    act.sa_sigaction = &handler;
    act.sa_flags = SA_SIGINFO;
    if (sigaction(SIGINT, &act, NULL) < 0) return 1;

    // L = 10^30
    const scalar L = ((scalar)0xc9f2c9cd0UL << 64) + 0x4674edea40000000UL;
    const scalar T = (scalar)1 << 64;   // used in an anti-overflow test

    // To avoid the optimiser removing the calculation of the bricks.
    int writeToStdOut = argc > 1;

    triple *st = (triple *)malloc(N * sizeof(triple));
    if (!st) return 2;

    uint32_t stp = 1; // Index of first empty space in stack
    st[0].a = 3; st[0].b = 4; st[0].c = 5;
    uint64_t count = 0;

    while (stp > 0) {
        if (stop) break;
        triple t = take(st);

        // Extend queue of Pythagorean triples
        offer(t.a + ((t.c - t.b) << 1), ((t.a + t.c) << 1) - t.b, ((t.a - t.b + t.c) << 1) + t.c)
        offer(t.a + ((t.c + t.b) << 1), ((t.a + t.c) << 1) + t.b, ((t.a + t.b + t.c) << 1) + t.c)
        offer(-t.a + ((t.c + t.b) << 1), ((-t.a + t.c) << 1) + t.b, ((-t.a + t.b + t.c) << 1) + t.c)

        // Saunderson brick
        scalar x = t.b * ( ((t.a << 1) >= t.c) ? ((t.a << 1) - t.c) : (t.c - (t.a << 1)) ) * ((t.a << 1) + t.c);
        scalar y = t.a * ((t.b << 1) - t.c) * ((t.b << 1) + t.c);
        scalar z = t.a * t.b * t.c << 2;
        scalar u = t.c * t.c * t.c;
        scalar v = t.b * (t.b * t.b + 5 * t.a * t.a);
        scalar w = t.a * (t.a * t.a + 5 * t.b * t.b);
        count++;
        if (writeToStdOut) {
            printf("Sides: 0x%016"PRIx64"%016"PRIx64, (uint64_t)(x >> 64), (uint64_t)x);
            printf(", 0x%016"PRIx64"%016"PRIx64, (uint64_t)(y >> 64), (uint64_t)y);
            printf(", 0x%016"PRIx64"%016"PRIx64, (uint64_t)(z >> 64), (uint64_t)z);
            printf("; diags 0x%016"PRIx64"%016"PRIx64, (uint64_t)(u >> 64), (uint64_t)u);
            printf(", 0x%016"PRIx64"%016"PRIx64, (uint64_t)(v >> 64), (uint64_t)v);
            printf(", 0x%016"PRIx64"%016"PRIx64"\n", (uint64_t)(w >> 64), (uint64_t)w);
        }
    }

    printf("%ld\n", count);

    return 0;
}

Compiles with gcc -O3 euler_brick.c -o euler_brick and handles SIGINT (Ctrl-C).  On my computer the earlier circular buffer version ran out of usably small Pythagorean triples after 85 seconds having found 843035517 (0.843 thousand million) Euler bricks. The new version runs to the two minutes (tested with timeout -sINT 2m ./euler_brick) and finds about 9.1 thousand million bricks. Exact numbers vary from run to run; the highest I've observed is 9113459216.

Note that this is single-threaded code. The process is embarrassingly parallel - just start each thread going down a different branch of the tree - and so the limitation to scaling it to multicore would be the shared memory bus.


Lookup without conditional statements This challenge was inspired by programming an Arduino microcontroller. I have 6 LEDs and 6 buttons connected to various pins on the board. In the code, each button and LED is assigned an ID number (1-6). Pin numbers (ranging from 0-13) corresponding to the ID numbers are looked up using a switch statement. Purely for amusement, I was wondering if these switches could be circumvented with an arithmetic/other function just to horrify future code maintainers.

The challenge

Provide the function/functions that take the ID number (integer) as a parameter and return the pin number (integer) for the 6 LEDs and/or the 6 buttons, without using conditional statements (no if, no switch and no ternary).

Return values for LEDs:

ID    Pin
1      3
2      5
3      6
4      9
5     10
6     11

Return values for buttons:

ID    Pin
1      2
2      4
3      7
4      8
5     12
6     13

Bonus challenge

Provide a single function that takes an ID number (integer) and second parameter (any type) indicating whether LED or button pins are requested, and returns the corresponding pin (integer).

Rules

This is not an Arduino-specific challenge. Use any language, do whatever you want.

Edit: at the suggestion of steveverril, this is now a code golf challenge.

Good luck!

(If you're still reading: although patently absurd and arbitrary by programming standards, the mappings are based on the Arduino Micro's pinout. Pins 0 and 1 are reserved for serial communication, LEDs are assigned to the 6 lowest-numbered PWM-capable pins, buttons are assigned to remaining pins)

C, 28 bytes each
p(i){return"@cefijk"[i]&15;}
b(i){return"@bdghlm"[i]&15;}

This is basically the same as the answer by kirbyfan64sos, but uses a char array instead of integers, and has a dummy first byte so there is no need to subtract 1 from the function parameter.


Find operations required to get result So task is simple, given array of numbers and result, you need to find what operations you need to use on numbers from array , to obtain requested result.

Let's make it simple for start, and allow only basic operations such as: addition, subtraction, multiplication and division.

Example:

Input  : [5,5,5,5,5] 100
Output : 5*5*5-5*5

To give some advantage to languages like Java, request is to implement function, not entire program, and result can be return via parameter or print to console.

Code is scored based on amount bytes, and as it's golf code challenge, lowest score wins.

Another requirment is You can get additional -10 points if for array contains only digids, support solutions where you could construct numbers from following digits.
Ie

Input  : [1,2,3,4,5] 0
Output : 12-3-4-5

Note that, provided outputs are proposed outputs, some cases might have more than one solution. It's up to you will you provide one or more solutions for given task.

EDIT:
Result has to be valid from mathematical point of view, hence division is rational division, not integer, and operation precedence is same as in classical math (first multiplication and division then addition and subtraction).

TSQL(sqlserver 2016) 310 294 280 bytes
What a wonderful opportunity to write ugly code:
Golfed:
DECLARE @ varchar(max)= '5,5,5'
DECLARE @a varchar(20) = '125'

,@ varchar(max)='';WITH D as(SELECT @a a UNION ALL SELECT STUFF(a,charindex(',',a),1,value)FROM STRING_SPLIT('*,+,./,-,',',')x,d WHERE a like'%,%')SELECT @+=a+','''+REPLACE(a,'.','')+'''),('FROM D WHERE a not like'%,%'EXEC('SELECT y FROM(values('+@+'null,null))g(x,y)WHERE x='+@b)

Try it online
Readable:(insertion of decimal point(.) and removal of the same is necessary in order for sql to accept that 4/5 is not 0 - well removal is for the people testing it)
DECLARE @a varchar(max)= '5,5,5'
DECLARE @b varchar(20) = '5'

,@ varchar(max)=''
;WITH D as
(
  SELECT @a a
  UNION ALL
  SELECT STUFF(a,charindex(',',a),1,value)
  FROM STRING_SPLIT('*,+,./,-,',',')x,d
  WHERE a like'%,%'
)
SELECT @+=a+','''+REPLACE(a,',','')+'''),('
FROM D
WHERE a not like'%,%'

EXEC('SELECT y FROM(values('+@+'null,null))g(x,y)WHERE x='+@b)

This solution can also handle these types of input:

Input :[1,2,3,4,5] 0 Output : 12-3-4-5


Let's get ready for Halloween I don't know about you all but I'm not preparing for Halloween––never did never will––but, my neighbor is, so we'll help her out.

She needs help figuring out which brand of candy she has, but she has so much candy she would not be able to finish before Halloween.

She has:

Snickers
KitKat
Starburst
GummyBears
Twix

Input

A multiline string (or any other reasonable form) containing only letters and spaces.

Output

A falsy value if it is not a valid candy, or which candy it is if it is a candy.

How to decide which candy it is

A candy is valid if it says one of the above brands on it. However, it's not that simple, because this is a valid candy:

K i t
       K a
           t

A valid candy is one where:

the letters are in order from left to right
the letters are capitalized correctly
the letters, going from left to right, do not both ascend and descend
the letters with whitespace removed form one of the above brands

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

Examples

Truthys:

1.
              kers
           c
        i
       n
    S

2.
  Kit K a t

3.
St a
    r b u
         r st

4.
         Bear s
G ummy

5.
T w i
                          x

Falsys:

1.
SNICKERS

2.
 C   n

   a   d y

3.
xiwT

4.
S C I
       ss o
              r       s

5.
Kit
Kat


Differences of MaxMin Divisor Pairs (DMDP) Let's talk about divisors...
Leaving out perfect squares (for a moment), all positive integers can be expressed as the product of 2 of their divisors. Quick example for 126: Here are all the divisors of 126

As you can see all the divisors can be paired. Here are what we will call the Divisor Pairs:
[1, 126], [2, 63], [3, 42], [6, 21], [7, 18], [9, 14]
For this challenge we will need only the last pair of this list (which is the center pair of the picture):
[9,14].We will call this pair the MaxMin Divisor Pair.
The Difference of MaxMin Divisor Pair (DMDP) is the difference of the two elements of the pair which is [9,14]=5
One more example for 544. The divisors are:

[1, 2, 4, 8, 16, 17, 32, 34, 68, 136, 272, 544]

and DMDP(544)=15  because 32-17=15
What about the perfect squares? All perfect squares have DMDP=0
Let's take for example 64 with divisors

{1, 2, 4, 8, 16, 32, 64}

As you can see in this case the MaxMin Divisor Pair is [8,8] which has DMDP=0
we are almost done..
The Challenge
Given an integer n>0, output how many integers less than or equal to 10000, have DMDP less than n
Test Cases
input -> output
1->100 (those are all the perfect squares)
5->492
13->1201
369->6175
777->7264
2000->8478
5000->9440
9000->9888
10000->10000
20000->10000

This is code-golf.Shortest answer in bytes wins.

JavaScript (ES7), 60 bytes

f=(n,i=1e4,j=i**.5|0)=>i?i%j?f(n,i,j-1):(i/j-j<n)+f(n,i-1):0

Probably exceeds your recursion limit, so you might prefer the iterative version for 70 bytes:

n=>[...Array(1e4)].map(g=(j=++i**.5|0)=>i%j?g(j-1):k+=i/j-j<n,i=k=0)|k


Given a fair coin as input, generate any particular unfair outcome It is easy to generate a fair coin using a unfair coin, but the reverse is harder to accomplish.

Your program will receive one number X (between 0 and 1, inclusive) as input. The input must not simply be hard-coded as a number in the middle of the source code. It must then return a single digit: a 1 with a probability of X and a 0 otherwise.

Your program is only allowed to use one form of random number generator in the source code: int(rand(2)) (or an equivalent), which returns either a zero or a one with equal probability. You can include or access this function as many times as you wish in your code. You also have to provide the function yourself as part of the code.

Your program is not allowed to use any other random number generating functions or external sources (such as time and date functions) that could function as a random number generating function.  It also cannot access any external files or pass the job along to external programs.

This is code golf, the shortest answer wins.

Perl, 37 42 char

($d/=2)+=rand>.5for%!;print$d/2<pop|0

Takes arbitrary probability as a command line argument. Builds a uniform random number in $d and compares it to the input.

Earlier, 52 char solution

$p=<>;do{$p*=2;$p-=($-=$p)}while$--(.5<rand);print$-


Evaluating Parentheses and Brackets as Integers Write a program that takes in a string of the four characters ()[] that satisfies these points:

Every left parenthesis ( has a matching right parenthesis ).
Every left bracket [ has a matching right bracket ].
Matching pairs of parentheses and brackets won't overlap. e.g. [(]) is invalid because the matching brackets are not fully contained in the matching parentheses, nor vice-versa.
The first and last characters are a matching pair of parentheses or brackets. So ([]([])) and [[]([])] are valid but []([]) is not.

(A grammar for the input format is <input> ::= [<input>*] | (<input>*).)

Each pair of matching parentheses and brackets evaluates to a non-negative integer:

The values of pairs inside matching parentheses are all summed. The empty  match () has value 0.
The values of pairs inside matching brackets are all multiplied. The empty match [] has value 1.

(The sum or product of one number is that same number.)

For example, ([](())([][])[()][([[][]][][])([][])]) can be broken down and evaluated as 9:

([](())([][])[()][([[][]][][])([][])])    <input>
(1 (0 )(1 1 )[0 ][([1 1 ]1 1 )(1 1 )])    <handle empty matches>
(1 0   2     0   [(1     1 1 )2     ])    <next level of matches>
(1 0   2     0   [3           2     ])    <and the next>
(1 0   2     0   6                   )    <and the next>
9                                         <final value to output>

Another example:

[([][][][][])([][][])([][][])(((((([][]))))))]    <input>
[(1 1 1 1 1 )(1 1 1 )(1 1 1 )((((((1 1 ))))))]
[5           3       3       (((((2     )))))]
[5           3       3       ((((2       ))))]
[5           3       3       (((2         )))]
[5           3       3       ((2           ))]
[5           3       3       (2             )]
[5           3       3       2               ]
90                                                <output>

Your program needs to evaluate and print the integer represented by the entire input string. You can assume the input is valid. The shortest code in bytes wins.

Instead of a program, you may write a function that takes in a string and prints or returns the integer.

CJam, 23

q"])(""1]:*0]:+["4/ers~

With BIG credits to Dennis! Try it online

Explanation:

The program converts the input to a CJam expression then evaluates it.
[…] becomes […1]:* (append 1 and multiply)
(…) becomes […0]:+ (append 0 and add)

q              read input
"])("          characters we want to replace
"1]:*0]:+["    replacement strings, concatenated
4/             split into strings of length 4: ["1]:*" "0]:+" "["]
er             replace (transliterate) the 3 characters with the 3 strings
s              convert the result (mixed characters and strings) to string
~              evaluate


Cause maximal disruption to a Straw Poll Context

Straw Poll is a website that is meant for the creation of simple/informal polls.  Provided with a list of options, the user can select their choice(s), and the votes are tallied up.  There's two very important features of a Straw Poll:

It is possible to view the current results before voting
It is often possible to select multiple options, which is treated the same way as if you voted multiple times, one for each option.

The one thing that's more fun than making Straw Polls is messing with the results. There's two main types of disruption:

Simple disruption, in which you vote for all the options
Advanced disruption, in which you strategically pick which options to vote for in order to maximize the effect.

In this challenge, you will write a program for advanced disruption.

The Math

To simply things mathematically, we can say that the higher the entropy of the votes, the more disrupted a poll is.  This means that a poll where a single option has all the votes isn't disrupted at all, while a poll where every option has an equal number of votes is maximally disrupted (this being the ultimate goal).

The entropy of a list of numbers [x1, x2, ..., xn] is given by the following equation from wikipedia. P(xi) is the probability of xi, which is xi / total_num_of_votes. If an option has received zero votes so far, it is simply not included in the summation (to avoid log(0)).  For our purposes, the logarithm can be in any base of your choice.

As an example, the entropy of [3,2,1,1] is approximately 1.277, using base e.

The next step is to determine what voting pattern leads to the greatest increase in entropy.  I can vote for any subset of options, so for example my vote could be [1,0,1,0].  If these were my votes, then the final tally is [4,2,2,1].  Recalculating the entropy gives 1.273, giving a decrease in entropy, which means this is a terrible attempt at disruption.  Here are some other options:

don't vote
[3,2,1,1] -> 1.277

vote for everything
[4,3,2,2] -> 1.342

vote for the 1s
[3,2,2,2] -> 1.369

vote for the 2 and 1s
[3,3,2,2] -> 1.366

From this, we can conclude that the optimal voting pattern is [0,0,1,1] since it gives the greatest increase in entropy.

Input

Input is a non-empty list of non-increasing, non-negative integers.  Examples include [3,3,2,1,0,0], [123,23,1], or even [4].  Any reasonable format is allowable.

Output

Output is a list (the same length as input) of truthy and falsey values, where the truths represent the options for which I should vote if I desired to cause maximal disruption.  If more than one voting pattern gives the same entropy, either one can be output.

Winning Criterion

This is code-golf, fewer bytes are better.

Test Cases

[3,2,1,1] -> [0,0,1,1]  (from 1.227 to 1.369)

[3,3,2,1,0,0] -> [0,0,0,1,1,1] (from 1.311 to 1.705)

[123,23,1] -> [0,1,1] (from 0.473 to 0.510)

[4] -> [0] OR [1] (from 0 to 0)

[7,7,6,6,5] -> [0,0,1,1,1] (from 1.602 to 1.608)

[100,50,1,1] -> [0,1,1,1] (from 0.707 to 0.761)

Mathematica, 19 44 bytes
...(loud complaining)
(x=Median@#[[;;Mod[Length@#,2]-3]];#≤x&/@#)&

Test:
{Test, data, goes, here};
(x=Median@#[[;;Mod[Length@#,2]-3]];#≤x&/@#)&
%%+Boole/@%


Calculate a probability exactly This task is about writing code to compute a probability exactly. The output should be a precise probability written as a fraction in its most reduced form. That is it should never output 4/8 but rather 1/2.

For some positive integer n, consider a uniformly random string of 1s and -1s of length n and call it A. Now concatenate to A its first value. That is A[1] = A[n+1] if indexing from 1.  A now has length n+1. Now also consider a second random string of length n whose first n values are -1, 0, or 1 with probability 1/4,1/2, 1/4 each and call it B.

For example, consider n=3. Possible values for A and B could be A = [-1,1,1,-1] and B=[0,1,-1]. In this case the two inner products are 0 and 2.

Now consider the inner product of A[1,...,n] and B and the inner product of A[2,...,n+1] and B.

Your code must output the probability that both inner products are zero.

For n=1 this probability is clearly 1/2.

I don't mind how n is specified in the code but it should be very simple and obvious how to change it.

Languages and libraries

You can use any language and libraries you like. I would like to run your code so please include a full explanation for how to run/compile your code in linux if at all possible.


Print out the first N characters of your code You should write a program or function that receives a positive integer N as input and prints out the first N characters of your code. If N is larger than the length of your code you should continue output your code cyclically.

Reading your source code in any way and reading from file, stdio, etc. are disallowed.

Examples

(assuming your code is yourcode)

Input => Output:

5 => yourc
10 => yourcodeyo
22 => yourcodeyourcodeyour

Clarification

Your program should be at least 1 byte long.

Python 2, 61 bytes

def f(n):a='def f(n):a=%r;print(a%%a*n)[:n]';print(a%a*n)[:n]

Try it online!


Help me I'm lost in the ocean! Introduction

Today I went fishing alone with my canoe, unfortunately I fell asleep and the stream brought me away, I lost my oars, now it's night and I am lost in the ocean! I can't see the coast so I must be far away!

I have my cell phone but is malfunctional because it got wet by the salty water, I can't talk or hear anything because the mic and phone speaker are broken, but I can send SMS to my friend who is on the coast's beach!

My friend has a very powerful torch and he raised it on top of bamboo's canes to show me the right direction, but I can’t row because I have no oars, so I must tell him how far I am so he can send someone to catch me!

My friend told me that he is keeping the torch at 11.50 meters on the sea level, and I can see the light right over the horizon. Now I only remember from the school that the Earth radius should be 6371 Km at the sea level, and I’m sittin in my canoe so you can assume that my eyes are at sea level too.

Task

Since the currents are moving me moment by moment, my friend is raising the torch from time to time (now it’s at 12.30 meters), please write a full program or function that will help me to calculate the distance from my friend’s position!

Here is a diagram (not to scale):

The orange point labelled M is me, the red point labelled T is the torch. The green line is the linear distance between M and T

Input

Take from standard input the torch height h in meters at the sea level, which I see right on top of the horizon, in the form of a floating point number with two decimals precision (with the accuracy of 1 centimeter or 0.01 meters), in the range from 0 to 100 included.

Output

You should return the euclidean length of the green line with the accuracy of 1 cm. For example if you output in meters, should be with two decimals (at least). The output can be either meters or kilometers, but respecting the accuracy.

Test cases:

All values in meters.

11.5 > 12105.08
13.8 > 13260.45

Rules

Shortest code wins.

05AB1E, 13 12 10 bytes

Saved 2 bytes thanks to Emigna.

Since there is no trigonometric functions to be called using OP's assumption that the earth is locally a plane, it becomes possible to make an 05AB1E solution.

•1#oC•+¹*t

           For understanding purposes input is referred to as 'h'
•1#oC•     Push 12742000 [ = 2*R, where R is the radius of earth]
      +    Compute 2*R+h
       ¹*  Multiply by h. Result is (2*R*+h)*h
         t Take the square root of it and implicitly display it

Try it online!


Find equally-weighted complete graphs Graph theory is used to study the relations between objects. A graph is composed of vertices and edges in a diagram such as this:

A-----B
|    / \
|   /   \
|  /     E
| /     /
|/     /
C-----D

In the above diagram, A is linked to B and C; B is linked to A, C, and E; C is linked to A, B, and D; D is linked to C and E; and E is linked to B and D. As that description was rather wordy, a graph can be represented as a symmetric boolean matrix where a 1 represents a connection and a 0 represents the lack thereof. The above matrix is translated to this:

01100
10101
11010
00101
01010

For the purpose of this problem, the matrix definition can be extended to include the distances or weights of the paths between nodes. If individual ASCII characters in the diagram have weight 1, he matrix would be:

05500
50502
55050
00502
02020

A "complete graph" consists of a set of points such that each point is linked to every other point. The above graph is incomplete because it lacks connections from A to D and E, B to D, and C to E. However, the subgraph between A, B, and C is complete (and equally weighted). A 4-complete graph would look like this:

A---B
|\ /|
| X |
|/ \|
C---D

and would be represented by the matrix:

01111
10111
11011
11101
11110

This problem is as follows: Given a symmetric matrix representing a graph and a positive integer n, find the number of distinct equally-weighted complete subgraphs of size n contained within.

You may assume that the input matrix is numeric and symmetric, and may choose input/output format. An entry in the matrix may be part of multiple equally-weighted subgraphs as long as they are distinct and of equal size. You may assume that n is a positive integer greater than or equal to 3.

The winning criterion for this challenge is code golf. Standard rules apply.

Jelly,  18 16  15 bytes
Assumes self-connections may be any weight (i.e. they are not necessarily only either \$0\$ or the equal weight).
Jœcṗ2EÐḟœị³EƲ€S

Try it online!
the two subsets of size 3 being ACE and BCD
With n=2 all 10 subsets of size 2 work as its symmetric.
How?
Jœcṗ2EÐḟœị³EƲ€S - Link: list of lists of integers, M; integer, n
J               - range of length of M = [1,2,3,...,length(M)]
 œc             - Combinations of length n e.g. [[1,2,3],[1,2,4],[1,3,4],[2,3,4]]
             €  - for each:
            Ʋ   -   last four links as a monad:
   ṗ2           -     Cartesian power with 2
      Ðḟ        -     discard if:
     E          -       all-equal (i.e. diagonal co-ordinates like [3,3])
        œị      -     multi-dimensional index into:
          ³     -       program's 3rd argument (1st input), M
           E    -     all equal?
              S - sum


Shortest example of code that is compiled and increasing the optimization level makes it take longer Just curious if someone can provide a short example of code that causes a compiler's optimizer to behave incorrectly:

without optimization (or at lower optimization), code takes X seconds to run
with optimization (or at higher optimization), code takes Y seconds to run where Y > X

In other words, the optimizer's cost model causes it to make a poor decision with a specific case, even though (presumably) it makes good decisions in general.

This is meant for C (with gcc the comparisons should be between -O0, -O1, -O2, -O3 in increasing order of optimization), but any compiled language should work.

C (gcc 6.2.0-5ubuntu12 x86_64), 58 bytes

typedef struct{long a,b}s;s f(long*c){return(s){*c,c[1]};}

Compiled with -O1, we get the following assembly code (minus boilerplate):

f:
    movq    8(%rdi), %rdx
    movq    (%rdi), %rax
    ret

With -O3, it looks like this:

f:
    movdqu  (%rdi), %xmm0
    movaps  %xmm0, -24(%rsp)
    movq    -24(%rsp), %rax
    movq    -16(%rsp), %rdx
    ret

This is obviously worse (the first version copies from memory to registers directly, the second version copies from memory into the wrong register, back into scratch space in memory, and then from there into the correct registers, which is just doing more work for no gain).

This is a pretty longstanding example of a silly gcc miscompilation. In older versions of gcc, the -O3 code was even worse (containing a full function setup/teardown sequence, stack protection checks, and the like); it seems to have improved somewhat in the more recent versions.

Incidentally, clang produces code almost identical to gcc's -O1 at any positive optimization level (the only difference is that sometimes the two assignments are done in the other order).


Can you outgolf me? (Robbers section) Robbers section
The cops section can be found here.
Challenge
Your task is to outgolf the submissions of the cops in the same language and the same version (for example, Python 3.5 ≠ Python 3.4, so that is not allowed). A submission is outgolfed when the length in bytes is shorter than the original submission. You only need to golf off at least 1 byte in order to crack a submission. E.g. if the task was to perform 2 × n, and the submission was the following:
print(2*input())

You could outgolf the cop by doing the following:
print 2*input()

Or even this (since lambda's are allowed):
lambda x:2*x

Post this with the following header:
##{language name}, <s>{prev byte count}</s> {byte count}, {cop's submission + link}

For example:

Python 2, 16 12 bytes, Adnan (+ link to submission)
lambda x:2*x

Computes A005843, (offset = 0).

In that case, you have cracked the submission.
Scoring
The person with who cracked the most submissions is the winner.
Rules

The crack submission must be in the same language as the cop submission.
The same input should result into the same output (so a(2) = 4 should remain 4).
For languages such as Python, you can import libraries that are standard included within the language. (So, no numpy/sympy etc.)
Input and output are both in decimal (base 10).

Note
This challenge is finished. The winner of the Robbers section is feersum. The final scores for the CnR are shown below:

feersum: 16 cracks
Dennis: 12 cracks
Leaky Nun: 6 cracks
Lynn: 4 cracks
miles: 3 cracks
Martin Ender: 2 cracks
Emigna: 2 cracks
jimmy23013: 1 crack
Sp3000: 1 crack
randomra: 1 crack
alephalpha: 1 crack
nimi: 1 crack
Destructible Watermelon: 1 crack
Dom Hastings: 1 crack

Jelly, 5 4 bytes, George V. Williams
RÆḊḞ

Try it here.
A hidden feature!
If I remembered correctly, ÆḊ(A) = sqrt(det(AAT)) is n! times the n dimensional Lebesgue measure of a simplex formed by n input point and the origin in m dimensional space. When n=1 it degenerate to the Euclidean distance. Not that weird after all...


Compute the minimum \$a(n)>a(n-1)\$ such that \$a(1)+a(2)+\dots+a(n)\$ is prime (OEIS A051935) Background

Consider the following sequence (A051935 in OEIS):

Start with the term \$2\$.
Find the lowest integer \$n\$ greater than \$2\$ such that \$2+n\$ is prime.
Find the lowest integer \$n'\$ greater than \$n\$ such that \$2 + n + n'\$ is prime etc.

A more formal definition:

$$a_n=\begin{cases}2 & \text{if }n=0 \\ \min\{x\in\Bbb{N}\mid x>a_{n-1} \text{ and }\left(x+\sum_{i=0}^{n-1}a_i\right) \text{ is prime}\} & \text{otherwise}\end{cases}$$

The first few terms of the sequence are (please refer to these as test cases):

2, 3, 6, 8, 10, 12, 18, 20, 22, 26, 30, 34, 36, 42, 44, 46, 50, 52, 60, 66, 72, 74, ...

Task

Your task is to generate this sequence in any of the following ways:

Output its terms indefinitely.
Given \$n\$, output \$a_{n}\$ (\$n^{\text{th}}\$ term, \$0\$ or \$1\$ indexed).
Given \$n\$, output \$\{a_1, a_2, \dots, a_n\}\$ (first \$n\$ terms).

You can compete in any programming language and can take input and provide output through any standard method, while taking note that these loopholes are forbidden by default. This is code-golf, so the shortest submission (in bytes) for every language wins.

Brachylog, 13 bytes

~l.<₁a₀ᵇ+ᵐṗᵐ∧

Try it online!

Output is the list of first n terms of the sequence.

?~l.<₁a₀ᵇ+ᵐṗᵐ∧    Full code (? at beginning is implicit)

?~l.              Output is a list whose length is the input
    <₁            Output is an increasing list
      a₀ᵇ+ᵐ       And the cumulative sum of the output
           ṗᵐ     Consists only of prime numbers
             ∧    No further constraints on output

Explanation for a₀ᵇ+ᵐ:
a₀ᵇ               Get the list of all prefixes of the list
                  Is returned in increasing order of length
                  For eg. [2, 3, 6, 8] -> [[2], [2, 3], [2, 3, 6], [2, 3, 6, 8]]
   +ᵐ             Sum each inner list  -> [2, 5, 11, 19]


print "Hello, world!" without using literals Write a program that prints "Hello, world!" without using any kinds of literals.
Don't use string literals, numeric literals, byte literals, char literals, etc. Default values are allowed in languages that have them.

Printing data from external files/websites/arguments is not encouraged.

edit: probably don't use Boolean literals either.

double edit: I don't necessarily want the code to be obfuscated. results that are clearly understandable are better.

triple edit: this is not duplicate because the other questions require obfuscated answers or are code-golf.


Output Buffalo buffalo Buffalo buffalo buffalo buffalo Buffalo buffalo Challenge
The goal is to output Buffalo buffalo Buffalo buffalo buffalo buffalo Buffalo buffalo.
Context. (Maybe another interesting challenge could be printing all of the other examples? This would probably use similar logic but involve either a function or just a for loop.)
Rule(s)

You cannot output anything other than the string with correct casing and spacing. Trailing new lines are allowed, trailing spaces are not.

This is code-golf, so fewest bytes win!


Get me back down to 1 rep! This is not an invitation for you to downvote everything I've posted. Just sayin' ;)

Challenge

Figure out how I can get myself back down to 1 reputation.

Details will follow input format, then followed by output.

Input

Input will consist of the my current reputation, the number of questions I have posted with an accepted answer (that is not my own), the number of questions I have posted without an accepted answer that have a valid answer that is not my own, and the number of answer downvotes that I have cast.

Details

Accepting an answer that is not my own gives me 2 rep. Unaccepting an answer takes away 2 rep from me. Undownvoting an answer gives me 1 rep (we assume that all of my answer votes are not locked in at the moment), and downvoting an answer makes me lose 1 rep (we assume there are enough answers on PPCG for me to not care about the number of answers that I can downvote). We also ignore potential serial vote reversal. Most of my reputation is going to have to be given away by bounties because I don't want to go around downvoting 5000 answers.

The challenge is to find the shortest way to get me back down to 1 rep using the shortest code. Please keep in mind that I need at least 125 rep to downvote and at least 75 rep to start a bounty. By "shortest way", I mean the way requiring the least actions, where each accept and downvote and their reverse actions and each bounty is a separate action. Note that it is impossible to award a bounty of more than +500 rep at once. Also note that you can only give out bounties in 50 rep increments.

If there is no way to get back down to 1 rep, then output some consistent error message. The error message may be output through crashing.

Output

Output the number of undownvotes, downvotes, accept-votes, unaccept-votes, and bounty actions I need to perform in any consistent order in any reasonable list format.

Test Cases

reputation, accepted_answers, no_accept_questions, answer_downvotes -> accepts, unaccepts, downvotes, undownvotes, bounties

101, 3, 2, 10 -> 0, 0, 0, 0, 1 // This one's easy, just give out a 100 rep bounty.
102, 3, 2, 10 -> 0, 1, 0, 1, 1 // Unaccept to get to 100, then undownvote to get to 101, then give a +100 bounty
103, 3, 2, 10 -> 0, 1, 0, 0, 1 // First unaccept one of those answers and then give out a 100 rep bounty or vice versa
3, 1, 0, 0 -> 0, 1, 0, 0, 0 // Unaccept that answer and lose the 2 rep
1000, 0, 1, 0 -> 1, 0, 1, 0, 2 // Accept an answer to get to 1002, then downvote an answer to get to 1001, then give out two +500 bounties

Rules

Standard Loopholes Apply
"Post a bunch of spam and get suspended" is not an answer, nor is anything similar
In the case of a tie between shortest methods, output one possible shortest method
This is code-golf, so the shortest code in bytes wins!

Mathematica, 302 bytes

Golfed version:

Unprotect@Null;Null=0;f[1,_,_,_]={,,,,};f[r_,a_,n_,d_]:=(f[r,a,n,d]=l={∞,,,,};f[r,a,n,d]=#&@@MinimalBy[{If[r>74,{,,,,1}+f[r-50Min[⌈r/50⌉-1,10],a,n,d],l],If[r>124,{,,1,,}+f[r-1,a,n,d+1],l],If[d>0,{,,,1,}+f[r+1,a,n,d-1],l],If[a>0,{,1,,,}+f[r-2,a-1,n+1,d],l],If[n>0,{1,,,,}+f[r+2,a+1,n-1,d],l]},Tr])

Normal version:

Unprotect@Null; Null = 0;
f[1, _, _, _] = {, , , ,};
l = {\[Infinity], , , ,};
f[r_, a_, n_, d_] := (
  f[r, a, n, d] = l;
  f[r, a, n, d] = # & @@ MinimalBy[{
      If[r > 74, {, , , , 1} +
        f[r - 50 Min[\[LeftCeiling]r/50\[RightCeiling] - 1, 10], a, n,
          d], l],
      If[r > 124, {, , 1, ,} + f[r - 1, a, n, d + 1], l],(*
      downvote one more *)
      If[d > 0, {, , , 1,} + f[r + 1, a, n, d - 1], l],
      (* un-downvote *)
      If[a > 0, {, 1, , ,} + f[r - 2, a - 1, n + 1, d], l],
      (* un-accept. -2 rep *)
      If[n > 0, {1, , , ,} + f[r + 2, a + 1, n - 1, d], l]
      (* accept. +2 rep *)
      }, Tr]
  )

Note:

Test this on https://sandbox.open.wolframcloud.com/ - paste the code, press Shift+Enter, then enter f[101,3,2,10] for example for first test case, then press Shift+Enter.
Use Block[{Null=0}, ...] can save some bytes, but I haven't test that.
Sometimes $IterationLimit=$RecursionLimit=∞ is necessary to get correct result.
The function will return {∞,0,0,0,0} or similar (that is, the sum of elements in list is infinite) when it is impossible, and a list with format similar to that in the sample output when it is possible.


What character is that HTML entity? The goal is really simple. Receiving a string as input, parse all the HTML entities that correspond to the following characters (including their uppercase variants):

áàãâäéèêëíìîïóòõôöúùûüýÿ

Parsing rules:

Each entity starts with & and ends with ;
The first character after the & will be the modified character (letter case is important!)
The remaining characters refer to the name of the accent to use (acute, grave, circ, tilde and uml). The accent name MUST be in lowercase! *
Any HTML entity that produces a character that isn't on that list, or that is invalid, should be left untouched (E.g.: &amp;, &etilde;, &a;)
Numeric entities should be ignored, since they don't fit in the rules above

This change was introduced as of 18-02-2016. All the existing answers that accept HTML entities with uppercase accent names are valid. Any future answer must follow this rule.

Examples:

&aacute; //á
T&eacute;h&egrave;h //Téhèh
an &amp; //an &amp;

Output:

The output can be in ISO-8859-X (1-15), windows-1252 or UTF-8/16/32.
You can pick one and only one of the valid encodings and use it for any output. You can safely assume that the input will be in ASCII.

Any of the following is a valid output for &aacute;:

á (ISO-8859-1/15 or windows-1252, equivalent to \xE1)
Ã¡ (UTF-8, equivalent to \xC3\xA1 or \u00E1)
aÌ (UTF-8, equivalent to a\xCC\x81 or a\u0301)
Any combination of diacritics, without using HTML entities.

The output has to be visually similar, when rendered/displayed, to the characters on the list.

Remember, all the standard loopholes and built-ins * are disallowed. Since this is code-golf, the shortest answer wins.

* This change was made due to the great disapproval of bonuses and penalities, and at the time of writting, doesn't invalidate any answer

JavaScript (ES6), 141 122 134 bytes
a=>a.replace(/&([aeiouyAEIOUY](acute|uml)|[aeiouAEIOU](grave|circ)|[aoAO]tilde);/g,b=>b[1]+{g:"̀",a:"́",c:"̂",t:"̃",u:"̈"}[b[2]])

Followed daavko's example using diacritical marks, and I feel like an idiot for not thinking of using it sooner. Actually gets surprisingly short for JavaScript.
EDIT: Neil caught some bad cases of undefined, which are now fixed.


What exactly was your question? Introduction
When you are given a boring text, you just want to get it over with as quick as possible. Let's observe the following text:
Ens colligi timenda etc priorem judicem. De quascunque ii at contingere
repugnaret explicetur intellectu. Adjuvetis hoc fortassis suspicari opportune
obversari vix eam? Dei praemia prudens hominum iii constet requiri haberem. Ima
sane nemo modi fuit lus pro dem haud. Vestro age negare tactum hoc cui lor. Ne et
ut quod id soli soni deus. At constare innumera is occurret ea. Nia calebat seu
acquiro fraudem effingo dicimus.

Note: This text has newlines for readability, while the test cases you need to handle don't have newline characters.
One way to skim text is to find questions that the writer has put into the text. For example, there is 1 question in the text above. Namely:
Adjuvetis hoc fortassis suspicari opportune obversari vix eam?

This can be done by splitting the text into sentences. A sentence will always end with one of the following punctuation symbols: .?! (others don't have to be handled). Other symbols than these are part of the sentence.

The Task
Given a line of text consisting of only

letters (A-Za-z)
numbers (0-9)
spaces
punctuation (,.;:?!) (a sentence cannot start with one of these).

Output the questions that are in the text in any reasonable format. You may assume that the text will always have at least 1 question. Outputting trailing and leading spaces before and after a question is allowed.
Important: Next to a punctuation symbol, there will never be another punctuation symbol (e.g. ?? is invalid and will not be required to handle).

Test cases
In the format:
Input
Output(s)

The test cases:
Huh? I haven't heard what you just said. Could you repeat that please?
Huh?
Could you repeat that please?

plz can i haz cheesburgr? i am cat pls.
plz can i haz cheesburgr?

This is a badly formatted question.Can u please help me,or my friends,with formatting this question    ?thankyou.
Can u please help me,or my friends,with formatting this question    ?

a.b.c.d?
d?

Does this question have a question mark? yes
Does this question have a question mark?

Why example.com resolves to 127.0.0.1 in 99.9 percent of cases?
9 percent of cases?

A? b? c? d!
A?
b?
c?

This is code-golf, so the submission with the lowest number of bytes wins!

Retina, 13 11 bytes

!`[^.?!]*\?

Try it online!

!`       print all matches
[^.?!]*  any number of non-ending-punctuation symbols
\?       followed by a question mark

Thanks to @MartinEnder for 2 bytes!