Interpret StackyMath! Time for you to implement my new stack based language! It's called StackyMath. This will be a stack based language with 8 operations on the stack and ways to add numbers to the stack.

List of operations:

/: Division. Performed on the top 2 numbers of the stack. Pushes the result back on the stack.
*: Multiplication. Performed on the top 2 numbers of the stack. Pushes the result back on the stack
-: Subtraction. Performed on the top 2 numbers of the stack. Pushes the result back on the stack
+: Addition. Performed on the top 2 numbers of the stack. Pushes the result back on the stack
^: Exponentiation. Performed on the top 2 numbers of the stack. Pushes the result back on the stack
%: Modulo. Performed on the top 2 numbers of the stack. Pushes the result back on the stack
!: Factorial. Performed on the top number on the stack. Pushes the result back on the stack
D: Duplicate the top number on the stack

Operations defined in pseudo code:

/: push(pop divided by pop)
*: push(pop times pop)
-: push(pop minus pop)
+: push(pop plus pop)
^: push(pop to the pop)
%: push(pop mod pop)
!: push(factorial pop)
D: t = pop; push(t); push(t)

How to push numbers to the stack:

Adding numbers to the stack is easy, just put the raw number in your program where you need it. If you need to put multiple numbers on the stack you can separate them with a comma (,). Your program will not need to process - numbers in the input, If the user wants one they should push the number they want negated, zero, and -. Numbers in the input of the program are also constrained to positive integers.

Input:

Your program should take the input on the command line, or from std in. Input will only consist of numbers (no scientific notation or decimals) delimited by , as needed, and the operations defined above.

Output:

Your program should print the number on the top of the stack.

Error cases:

If the program tries to over-pop the stack, you should print StackUnderflowException!!! .
If you have division by zero, print DivisionByZeroException!!!
If a number that exceeds 64-bits, either while executing the program or processing a number in the input, print NumberOverflowException!!!
If somehow you get a negative number on the top of the stack and you need to do a factorial, print NegativeFactorialException!!!
If you have a floating point number on the tops of the stack and the next operation is factorial, print FloatingFactorialException!!!
If no numbers are on the stack when the program exits (i.e. the program was empty) print EmptyProgram!!!

Notes:

All error output to should got yo std err or closest equivalent.
All numbers are constrained to 64-bit floating point.

Example programs:

50,47*                 -> 2350
50,47/                 -> 0.94
100,8!                 -> 40320
100D*                  -> 10000
!                      -> StackUnderflowException!!!
5,2/!                  -> FloatingFactorialException!!!
4,3!2*/                -> 3
654,489,48,43/5*7D+-*% -> 77.68749999999909
                       -> EmptyProgram!!!

(I can add more if needed)

Ruby, 412 410 404 392 380 377 characters

def e m,x='Exception';warn m+x+?!*3;exit;end
def o;e'StackUnderflow'if$*==[];$*.pop;end
u=->n{e'DivisionByZero'if n.infinite?;e'NumberOverflow'if n>2**64;$*<<n}
f=->n{e'NegativeFactorial'if n<0;e'FloatingFactorial'if n.to_i<n;n<2?1:f[n-1]*n}
gets.gsub(/(\d+)|([+*\/%^-])|(!)|D/){$1?u[$1.to_f]:$2?u[eval"o#{$2>?A?:**:$2}o"]:$3?u[f[o]]:u[x=o]+u[x]}
e'EmptyProgram',''if$*==[]
p o

This is regular precision version using Float. The result precision is as in the sample code, but numeric overflow detection is not exact.

Sample run:

bash-4.3$ ruby StackyMath.rb <<< '654,489,48,43/5*7D+-*%'
77.68749999999909

Ruby, 378 377 characters

def e m,x='Exception';warn m+x+?!*3;exit;end
def o;e'StackUnderflow'if$*==[];$*.pop;end
u=->n{e'NumberOverflow'if n>2**64;$*<<n}
f=->n{e'NegativeFactorial'if n<0;e'FloatingFactorial'if n.to_i<n;n<2?1:f[n-1]*n}
gets.gsub(/(\d+)|([+*\/%^-])|(!)|D/){$1?u[Rational$1]:$2?u[eval"o#{$2>?A?:**:$2}o"]:$3?u[f[o]]:u[x=o]+u[x]}rescue e'DivisionByZero'
e'EmptyProgram',''if$*==[]
p o.to_f

This is high precision version using Rational. The result precision is not always the same as in the sample code, but numeric overflow detection is exact.

Sample run:

bash-4.3$ ruby StackyMath-hi.rb <<< '654,489,48,43/5*7D+-*%'
77.6875


Appease Your Google Overlords: Draw the "G" Logo Write a program or function that takes in a positive integer N, and outputs an N×N pixel image of Google's "G" logo according to this* construction:

For example, if N is 400, a 400×400 pixel logo should be output, with correct dimensions and colors:

It should look accurate regardless of how large or small N is. e.g. here is N = 13:

Your code should not need to connect to the internet. For example, scaling an externally hosted svg is not allowed. (Scaling an svg encoded in your code would be fine though.)

Anti-aliasing may be used or not. It's up to you.

Notice that the horizontal bar of the "G" does not extend all the way to the right edge of the image. The circle curves normally inward on the right edge before it is cut off.

The shortest code in bytes wins.

* The construction of the logo has been simplified for this challenge. The correct construction can be seen here and here.

Mathematica, 229 226 225 224 221 206 169 bytes
Thanks @MartinEnder for 1 byte, @ChipHurst for 37 bytes!
Graphics[{RGBColor@{"#EA4335","#FBBC05","#34A853","#4285F4"}[[#]],{0,-1}~Cuboid~{√24,1},Annulus[0{,},{3,5},{(2#-9)Pi/4,ArcCsc@5}]}&~Array~4,ImageSize->#,PlotRange->5]&

What a fun challenge!
Explanation
...&~Array~4

Iterate from 1 to 4...
RGBColor@{"#EA4335","#FBBC05","#34A853","#4285F4"}[[#]]

Convert the color hex codes to RGBColor objects, so that they can be applied to the Google logo graphic. Change the color palette to the <input>th color.
{0,-1}~Cuboid~{√24,1}

Create a filled rectangle (2D cuboid), whose diagonal corners are (0, -1) and (sqrt(24), 1).
Annulus[0{,},{3,5},{(2#-9)Pi/4,ArcCsc@5}]}

Generate four filled quarter-Annuluss, centered at the origin, with inner radius 3 and outer radius 5. Do not draw past ArcCsc@5 (where the blue segment ends).
Graphics[ ... , ImageSize->#,PlotRange->5]

Create a graphic with size N x N, from x = -5 to x = 5 (removes the padding).
Outputs
N = 10

N = 100

N = 200

N = 10000 (click image for full resolution)


Write a program to fabricate elaborate acronyms "Hey Bob, I need a new acronym. Something better than 'Automated Support System'. I need you to fabricate me an acronym!"

"Sure thing Joe! I'd love to fabricate an elaborate way to renovate, and not replicate something that you can tolerate."

"Alright Bob, make sure it can separate itself from the old acronym we need to terminate! It'll be great, or at least, that's just what I speculate."

Okay, apologies. I had a lot of fun writing that. Here's the challenge:

You are now Bob. You need to write a program that accepts a string of words from standard input:

  This is an example string of words

The character encoding must be ASCII. Delimeters can be spaces and newlines only. From this string of words, it forms an acronym, which it shoots straight to standard output (or equivalent output log):

  T.I.A.E.S.O.W.

The program must read the words, case-insensitive, and output the first letter of each word, capitalized, followed by a period.

This is code-golf. Shortest program wins. Go nuts!

Jelly, 8 bytes

ŒtḟŒlp”.

Explanation:

ŒtḟŒlp”.
Œt       # Convert the string to Title Case (lowercases then uppercase beginnings of word)
   Œl    # And on the other side, convert the string to lowercase
  ḟ      # filter: remove the elements from the right side (lowercase) from the left side (Title Cased). Only leaves the initials
     p”. # Cartesian product with a dot.

Golfed down under the Pyth one, thanks Dennis and Fry!


Write a program that always prints N when it is shifted N times up the ASCII alphabet Write a program using only printable ASCII characters that takes no input. For reference, here are the 95 printable ASCII characters in order:
 !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~

When your program is run it should print 0 (plus an optional trailing newline) to stdout, then terminate normally.
When each character in your program is replaced by the character N spaces to its right in printable ASCII, looping around from ~ to space, the resulting printable ASCII string will ideally be a program runnable in the same language that takes no input and outputs N (plus an optional trailing newline) to stdout, then terminates normally, for N = 1 to 94.
For example, if your original program was
@Cat~(88 !)

running it should output 0 and shifting all the characters up the printable ASCII scale by one
ADbu )99!"*

should result in another program that outputs 1. Doing so again will ideally result in another program that outputs 2
BEcv!*::"#+

and so on with 3 and 4, etc. up to the point of shifting 94 times
?B`s}'77~ (

which ideally is a program that outputs 94.
The relief is that this is only the ideal behavior. Your program and its 94 derivatives do not all need to work, but the more that consecutively do from the start the better. (Programs that do not work may have any behavior whatsoever.)
Scoring
Your score is the number of consecutive programs starting from the original (the one that outputs 0) that do work, i.e. correctly output their corresponding N. The answer with the highest score (a maximum of 95) wins. If there's a tie then the program with the shortest length in bytes wins.
For example, if @Cat~(88 !) output 0 and ADbu )99!"* output 1 but BEcv!*::"#+ errored, then your score would be 2. It's 2 even if ?B`s}'77~ ( accurately outputs 94 and even if all the programs for N = 30 to 40 worked. Only the consecutive number of working programs, starting at zero, are counted.
Notes

To combat potential contention and loopholes, competing answers must output their numbers in decimal with no leading zeroes or signs or decimal points (i.e. plain 0 1 2 ... 94).
Languages that use different bases or number formats are allowed but are not eligible to win.
The presence of an optional trailing newline does not need to be consistent across programs.
Functions and REPL commands are not allowed, only full programs.


ASCII-art videogame edition I thought it might be fun to throw this on here.
Generate an ASCII-art for one of your favorite videogames.

What you want to generate is up to you but it should meet 2 requirements.

It should be able to identify the game. So either a logo or
something familiar like the triforce in Zelda. a pokeball for
pokémon or an actual pokémon.
Make it solid.

I'm guessing the second requirement is a bit vague, I just dont know how to explain it so let me show you with the triforce.

Wrong
       /\
      /__\
     /\  /\
    /__\/__\

Right
           #
          ###
         #####
        #######
       #       #
      ###     ###
     #####   #####
    ####### #######

This is a popularity-contest, so be creative and dont worry about the length of your code.

Rules

No external resources
You can use any language you like

Edit
You are meant to write some kind of algorithm that will create your ascii art rather than simply arranging the characters.
Sorry for changing the question

Happy Coding!

Bash

An actual pokémon? Ok. I present the Voltorb, seen from behind.

#!/bin/bash
echo -e '\e[31m'    # escape character for red font
s=6
for i in `seq 8 2 16`; do
    if [ $i -ne 10 ]; then
        for j in `seq $s`; do
            echo -n ' '
        done
        for j in `seq $i`; do
            echo -n '#'
        done
        echo
    fi
    s=`expr $s - 1`
done
echo -e -n '\e[97m'    # escape character for white font
s=2
for i in `seq 16 -2 8`; do
    if [ $i -ne 10 ]; then
        for j in `seq $s`; do
            echo -n ' '
        done
        for j in `seq $i`; do
            echo -n '#'
        done
        echo
    fi
    s=`expr $s + 1`
done
echo -e '\e[0m'    # escape character for default font color

Output:


Binary self-rotation Given a binary 3D array, for each layer, cyclically rotate up each of its columns as many steps as indicated by the binary encoding of the columns of the layer above it, and then cyclically rotate left each of its rows as many steps as indicated by the binary encoding of the rows of the layer below it.
There will always be at least three layers. The top layer's columns and the bottom layer's rows should not be rotated.
Walk-through
Lets start with the small 4-layer, 2-row, 3-column array:
[[[1,0,1],
  [1,0,0]],

 [[1,0,1],
  [0,1,1]],

 [[0,1,1],
  [1,1,1]],

 [[1,1,0],
  [1,1,1]]]

The first step is evaluating the numbers encoded in binary by the columns and rows of each layer:
     3 0 2
5 [[[1,0,1],
4   [1,0,0]],

     2 1 3
5  [[1,0,1],
3   [0,1,1]],

     1 3 3
3  [[0,1,1],
7   [1,1,1]],

     3 3 1
6  [[1,1,0],
7   [1,1,1]]]

The first layer, [[1,0,1],[1,0,0]] will not have its columns rotated, but its rows will be cyclically rotated left 5 steps and 3 step respectively, thus becoming [[1,1,0],[1,0,0]].
 The second layer, [[1,0,1],[0,1,1]], will have its columns cyclically rotated up 3, 0, and 2 steps respectively, giving [[0,0,1],[1,1,1]], and then the rows are cyclically rotated left 3 and 7 steps respectively, with no visible change.
 The third layer, [[0,1,1],[1,1,1]] rotated up 2, 1, and 3 steps stays the same, and neither does rotating left 6 and 7 steps do anything.
 Finally, the fourth layer, [[1,1,0],[1,1,1]] rotated up 1, 3, and 3 steps is [[1,1,1],[1,1,0]], but its rows are not rotated afterwards, as it is the last layer.
 Putting all the layers together again, gives us the binary self-rotated 3D array:
[[[1,1,0],
  [1,0,0]],

 [[0,0,1],
  [1,1,1]],

 [[0,1,1],
  [1,1,1]],

 [[1,1,1],
  [1,1,0]]]

Example cases:
[[[1,0,1],[1,0,0]],[[1,0,1],[0,1,1]],[[0,1,1],[1,1,1]],[[1,1,0],[1,1,1]]] gives
[[[1,1,0],[1,0,0]],[[0,0,1],[1,1,1]],[[0,1,1],[1,1,1]],[[1,1,1],[1,1,0]]]
[[[1]],[[1]],[[0]]] gives
[[[1]],[[1]],[[0]]]
[[[1,0,1],[1,0,1],[1,0,1]],[[0,0,1],[0,0,1],[0,0,1]],[[1,0,0],[1,0,1],[0,0,1]]] gives
[[[0,1,1],[0,1,1],[0,1,1]],[[0,1,0],[1,0,0],[0,1,0]],[[1,0,1],[1,0,1],[0,0,0]]]

Jelly,  18  17 bytes

ṙ""Ḅ}
Z€çŻṖ$$Z€çḊ

Try it online!

How?

ṙ""Ḅ} - Link 1, rotation helper: 3d matrix to rotate, 3d matrix of rotation instructions
    } - use the right argument for:
   Ḅ  -   un-binary (vectorises) - get the rotation amounts as a 2d matrix
  "   - zip with:
 "    -  zip with:
ṙ     -    rotate (the current row) left by (the current amount)

Z€çŻṖ$ $Z€çḊ - Main Link: 3d matrix, M
Z€           - transpose €ach (layer of M)
       $     - last two links as a monad:
     $       -   last two links as a monad:
   Ż         -     prepend a zero
    Ṗ        -     pop (i.e. remove the tail)
  ç          -   call the last Link as a dyad (i.e. f(Z€ result, ŻṖ$ result) )
        Z€   - transpose €ach (layer of that)
           Ḋ - dequeue (i.e. remove the head layer of M)
          ç  - call the last Link as a dyad (i.e. f(Z€çŻṖ$$Z€ result, Ḋ result) )

Note: $$ (or possibly $$ ... $$?) seems to mess up the code-block formatting (but only once posted, not in the preview), so I added a space to make my life easier.


How hyperperfect am I? A \$k\$-hyperperfect number is a natural number \$n \ge 1\$ such that
$$n = 1 + k(\sigma(n) − n − 1)$$
where \$\sigma(n)\$ is the sum of the divisors of \$n\$. Note that \$\sigma(n) - n\$ is the proper divisor sum of \$n\$. The sequence of \$k\$-hyperperfect numbers begins
$$6, 21, 28, 301, 325, 496, 697, \dots$$
This is A034897 on the OEIS.
For example:
$$\begin{align}
\sigma(21) & = 1 + 3 + 7 + 21 = 32 \\
21 & = 1 + 2(32 - 21 - 1) \\
& = 1 + 2 \times 10 \\
& = 21
\end{align}$$
Therefore, \$21\$ is a \$2\$-hyperperfect number.

You are to take a \$k\$-hyperperfect number \$n\$ as input and output the value of \$k\$. You can assume you will never have to handle numbers greater than your language's limit at any point (i.e. \$k\sigma(n)\$ will always be within the bounds of your language), and you may input and output in any convenient format.
The input is guaranteed to be a \$k\$-hyperperfect number, you don't have to handle inputs such as \$2, 87, 104\$ etc. that aren't \$k\$-hyperperfect.
This is code-golf, so the shortest code in bytes wins.
Test cases
These are the outputs for all the listed values in the OEIS for this sequence, and are the exhaustive list of inputs for \$n < 1055834\$
      n       k
      6       1
     21       2
     28       1
    301       6
    325       3
    496       1
    697      12
   1333      18
   1909      18
   2041      12
   2133       2
   3901      30
   8128       1
  10693      11
  16513       6
  19521       2
  24601      60
  26977      48
  51301      19
  96361     132
 130153     132
 159841      10
 163201     192
 176661       2
 214273      31
 250321     168
 275833     108
 296341      66
 306181      35
 389593     252
 486877      78
 495529     132
 542413     342
 808861     366
1005421     390
1005649     168
1055833     348

Jelly, 5 bytes
:Æṣ’$

:       integer divide
Æṣ’$    the decremented divisor sum

This uses \$\lfloor\frac{n}{\sigma(n)-n-1}\rfloor\$ instead of \$\frac{n-1}{\sigma(n)-n-1}\$, but it still works because \$\frac{1}{\sigma(n)-n-1}\$ can never be greater than or equal to 1.
Try it online!


Reverse Greek Conversion Golf Introduction

You must create a function to convert Greek numerals into Arabic numerals. The input will be a Greek numeral less than 1000 and more than 0. This is the reverse of my previous challenge.

Algorithm

Split input into letters (e.g. ΡΚΓ -> Ρ, Κ, Γ)
Take each letter, and change to character found in table below, for letter symbol, (e.g. ΡΚΓ -> Ρ, Κ, Γ -> 100, 20, 3).
Add (e.g. ΡΚΓ -> Ρ, Κ, Γ -> 100, 20, 3 -> 123)

Specifications

No built-in number-system conversion
Input will be capitalized as in example.
Output must be in base 10.
ΡΡΡΡ will never happen. It will be Υ.

Test Cases

ΡΚΓ -> 123
Η -> 8
ΨΟΖ -> 777
Ρ -> 100
ΧϜ -> 606
ΡϘ -> 190
ΜΒ -> 42
Ν -> 50

Table

Α = 1 = Alpha = 913 UTF-8
Β = 2 = Beta = 914 UTF-8
Γ = 3 = Gamma = 915 UTF-8
Δ = 4 = Delta = 916 UTF-8
Ε = 5 = Epsilon = 917 UTF-8
Ϝ = 6 = DiGamma = 988 UTF-8
Ζ = 7 = Zeta = 918 UTF-8
Η = 8 = Eta = 919 UTF-8
Θ = 9 = Theta = 920 UTF-8

Ι = 10 = Iota = 921 UTF-8
Κ = 20 = Kappa = 922 UTF-8
Λ = 30 = Lambda = 923 UTF-8
Μ = 40 = Mu = 924 UTF-8
Ν = 50 = Nu = 925 UTF-8
Ξ = 60 = Xi = 926 UTF-8
Ο = 70 = Omicron = 927 UTF-8
Π = 80 = Pi = 928 UTF-8
Ϙ = 90 = Koppa = 984 UTF-8

Ρ = 100 = Rho = 929 UTF-8
Σ = 200 = Sigma = 931 UTF-8
Τ = 300 = Tau = 932 UTF-8
Υ = 400 = Upsilon = 933 UTF-8
Φ = 500 = Phi = 934 UTF-8
Χ = 600 = Chi = 935 UTF-8
Ψ = 700 = Psi = 936 UTF-8
Ω = 800 = Omega = 937 UTF-8
Ϡ = 900 = SamPi = 992 UTF-8

Python 3, 112
Saved 4 bytes thanks to vaultah.
Booyah, beating JS!
lambda x,z="ΑΒΓΔΕϜΖΗΘΙΚΛΜΝΞΟΠϘΡΣΤΥΦΧΨΩϠ".find:sum((z(c)%9+1)*10**(z(c)//9)for c in x)

With test cases:
assert(f("ΡΚΓ")==123)
assert(f("Η")==8)
assert(f("ΨΟΖ")==777)
assert(f("Ρ")==100)
assert(f("ΧϜ")==606)

Loops through the string and uses its index in the list of potentials chars to calculate how much it's worth.


Convert Valve KV into JSON Valve's KV file format is as follows (in pseudo-EBNF):
<pair> ::= <text> <value>
<value> ::= <text> | <block>
<text> ::= "\"" <char>* "\""
<block> ::= "{" <pair>* "}"

The parsing starts on <pair> state. Whitespace is allowed anywhere, but is only required between two consecutive <text> tokens ("a""b" is invalid, but "a" "b" is valid, and so is "a"{}).
And since I'm lazy, <char> is any character, except ", unless preceded by \.
You can also see KV as JSON without commas and colons, and with only strings and objects as possible types.
Your task is to write a program or function that converts a input string (stdin, file or argument) in KV to a output string in JSON. You can output anywhere (stdout, file or return value), as long as it's a valid json string.
It isn't necessary to preserve whitespace in the output, as long as quoted text doesn't change.
Standard loopholes apply, of course.
Bonus
You get a -20 byte bonus if the output is pretty-printed, regardless of input. Pretty printed means indenting each level of blocks with 4 spaces, separating colons from values by 1 space and have one pair per line. Closing braces should stand on their own line.
Test cases
Input:
"foo" {
    "bar" "baz"
    "oof" {
        "rab" "zab"
    }
}

Output:
{
    "foo": {
        "bar": "baz",
        "oof": {
            "rab": "zab"
        }
    }
}

Input:
"obj" {
    "emptyo" {}
    "troll" "}{"
}

Output:
{
    "obj": {
        "emptyo": {},
        "troll": "}{"
    }
}

Input:
"newline" "
"

Output:
{
    "newline": "\n"
}

Input:
"key
with_newline" {
    "\"escaped\"quotes" "escaped_end\""
}

Output:
{
    "key\nwith_newline": {
        "\"escaped\"quotes": "escaped_end\""
    }
}

CJam, 57 54 bytes

{[~]2/{`_'{#{1>W<"\u%04x"fe%s`}{~J}?}f%':f*',*{}s\*}:J

This is a named function that pops a VDF string from the stack and pushes a JSON string in return.

CJam has no JSON built-ins, so the bonus won't be worth it. Since conditionally escaping some characters would be a pain for the same reason, I decided to escape everything.

The result isn't pretty, but it's valid JSON. Try it online in the CJam interpreter.


Solve an 0h n0 board 0h n0 is a very simple and enjoyable game, a bit like Sudoku or minesweeper.

Game rules

(I recommend using the tutorial in the game if you can, it is very simple and useful)

The puzzle starts with an n * n board containing some fixed pieces and some empty cells, and the solver must find a way to fill the empty cells with pieces and satisfy all of the constraints imposed by the fixed pieces. Here are the piece types we will be using with the abbreviation:

# Red piece (blocks view of a blue piece)
O Blue piece
. Empty location
number Numbered blue piece (number is a one digit number >0)

All the numbered pieces must see exactly the same amount of blue pieces as the number. For example:

#1O#O
...O.

The 1 piece can see only one other blue piece.

How pieces see each other

Two blue pieces can see each other if they are in the same row or column and no red piece is between them. Example:

(S is a location that the O piece can see, X can't be seen)

   S
   S
X#SOSS
   #
   X

Each blue piece must see at least one other blue piece:

#O#

Wont work, but:

#OO

Or:

###

Do work.

Demo board solve

.1..
..1.
....
22#2

The right bottom 2 can only see above itself, so they must be blue, and the top right must be red.

.1.#
..1O
...O
22#2

Since the 1 is filled, we can surround it with red pieces.

.1##
.#1O
..#O
22#2

The top left 1 can only see in one direction now, so we can fill it in.

O1##
.#1O
..#O
22#2

Now about those last 2s. We can put 2 blue pieces over them.

O1##
.#1O
OO#O
22#2

The last one will be filled with #

O1##
##1O
OO#O
22#2

Input

Input is a multi-line string. The size will be 9x9 without trailing space. It has the following piece types:

. Empty
# Preset red, cannot be changed
number Preset number, cannot be changed

(Note that blue will not ever be in the input)

Output

Output is the same as input, with the change that empty (.) is replaced with either a red or a blue to solve the board, and numbers are replaced with blue pieces (O).

Examples

(Note that multiple solutions may be possible for each puzzle, but you only need to show one of them)

Input:
........4
...3.1...
45...2.3.
..9......
1..6#44..
....4..5.
....4.36.
2.......6
1....4...

Output:
OOO###OOO
OOOO#O#OO
OOO#OO#OO
#OOOO#O##
O#OO#OOOO
O#OOOO#OO
#OOOO#OOO
OO#O#OOOO
O#OOOO#O#

Input:
..7..#...
#...8..11
2....5...
..5...48.
...#...4.
.5...6...
...1.2...
2.....6.8
.7..#....

Output:
OOOOO####
##OOOO#OO
O#OOOO###
OOO#OOOOO
OO##O##O#
#O##OOOOO
#O#O#O#OO
OO#OOOOOO
OOO###O#O

Input:
5.3..33..
...4...23
.6.6.34..
...3#....
....5..4.
.5....3..
7.98.6#.3
.5.6..2..
..6...2..

Output:
OOOOO####
##OOOO#OO
O#OOOO###
OOO#OOOOO
OO##O##O#
#O##OOOOO
#O#O#O#OO
OO#OOOOOO
OOO###O#O

Thanks to @PeterTaylor and @apsillers for all their help in the sandbox!

Haskell, 224 bytes

Not fully tested, because it's so slow (at least O(n*2^n^2)).

t=1<2
x!p|p<0=0|t=mod(div x$2^p)2
l#x=[[sum$map(p&)[-1,1,l+1,-l-1]|p<-[q..q+l]]|q<-[0,l..l*l],let i&v|x!i<1=0|t=x!(i+v)+(i+v)&v]
b%v|b<1=t|t=b==v
s b|l<-length b-1=[l#x|x<-[0..2^l^2],and.map and$zipWith(zipWith(%))b(l#x)]!!0

Explanation:

Basic idea is to represent a board of Red, Blue pieces as a list of lists of 0, 1, where the list of lists is packed into a single integer for easier enumeration. All such integers for the board size are generated and converted to a form with neighbor counts. The first such board that is a valid solution of the input is returned.

-- integer x at position p with out of bounds defined to be 0 (so no bounds checking)
(!) :: (Integral b, Integral r) => r -> b -> r
x ! p | p < 0     = 0
      | otherwise = mod (div x (2^p)) 2

-- Sum of values from position p along vector v (x is implicit)
-- Note that a cartesian vector (x,y) in this representation is (l*x + y)
(&) :: (Integral a, Integral b) => b -> b -> a
p & v | x ! p == 0 = 0
      | otherwise  = x ! (p+v)  +  (p+v) & v

-- Value of board at position p (implicit x, l)
value :: Integral a => a -> a
value p = sum $ map (p&) [-1, 1, l+1, -l-1]

-- Integer to board, where l is length, x is input integer
(#) :: (Integral t, Integral a) => a -> t -> [[t]]
l # x = [[sum $ map (p&) [-1,1,l+1,-l-1] | p <- [q..q+l-1]] | q <- [0,l..l*l]]

-- Comparison operator, to see whether a solved board is a solution of the input
(%) :: (Num a, Ord a) => a -> a -> Bool
b % v | b == 0    = True
      | otherwise = b == v

-- Check one possible solution
check :: Integral a => [[a]] -> Int -> [[a]] -> Bool
check b l x = (and . (map and)) zipWith(zipWith (%)) b (l # x)

-- Solver
solve :: Integral t => [[t]] -> [[t]]
solve b = [l # x | x <- [0..2^l^2], check b l x]
  where
    l = length b

The part that could probably be most golfed is: and.map and$zipWith(zipWith(%)). Otherwise, I caught a few off-by-one errors that added length and could probably be golfed more.


Tips for golfing in Elixir Elixir is a relatively new functional language, which I've taken a deep interest in. I'd like to get general tips about golfing in Elixir and learn techniques that can be applied to code-golf problems that are somewhat specific to Elixir in general.

Based on so many similar questions about Python, Ruby, Javascript, etc. I'll also try to post tips as I learn more about the language.

Don't use the Pipe operator or parenthesis for calling methods

# With Pipe
arg |> M.a |> M.b |> M.c   # 24 Bytes
arg|>M.a|>M.b|>M.c         # 18 Bytes

# With Parenthesis
M.c(M.b(M.a(arg)))         # 18 Bytes

# Only Spaces
M.c M.b M.a arg            # 15 Bytes


Build an EBCDIC converter using NAND logic gates In this question, a mapping is defined between EBCDIC and a superset of ISO-8859-1.

Your task is to build a network of two-input NAND gates that will take eight inputs A1, A2, A4, ..., A128 representing an EBCDIC character and return eight outputs B1, B2, B4, ..., B128 that represent the corresponding "ISO-8859-1" character according to that mapping.

To simplify things, you may use AND, OR, NOT, and XOR gates in your diagram, with the following corresponding scores:

NOT: 1
AND: 2
OR: 3
XOR: 4

Each of these scores corresponds to the number of NAND gates that it takes to construct the corresponding gate.

The logic circuit that uses the fewest NAND gates to correctly implement all the above requirements wins.

727 Gates

How I did it:

turned the code page translation from wikipedia into an appropriately formatted truth table using Excel (15 minutes)
minimized the truth table using Espresso (5 minutes, 30 minutes on 1st iteration getting back into the saddle)
fed the minimized truth table into a schematic generator (1 minute)
iterated on 2&3 until I got a reasonable answer (<1 hour)
turned the schematic into an uploadable image (30 min, %$#@! Microsoft)

Here's the 100% NAND gate result:

If I was actually going to implement this, I'd drop the NAND-centric scoring. Building XOR gates out of NANDs is a big waste of transistors. Then I'd start worrying about UMC, fire up the FPGA design tools, maybe break out the HDL manuals, etc. Whew! I love software.

NB, for hobbyists interested in FPGAs, I'll recommend FPGA4fun.


The Staircase Challenge Your work is to recreate this piece of art:

                        _____
                       |
                       |
                       |
                       |
                  _____|
                 |
                 |
                 |
                 |
            _____|
           |
           |
           |
           |
      _____|
     |
     |
     |
     |
_____|

The answer must recreate this and print this as a result. All languages allowed, no direct printing of art, ofc, some level of manipulation is required. The answer with the least bytes wins.

Closes on Thursday 6:30 AM UTC or so.

The original thing was shown to me by my friend who did this with Java, he refused to show me the source code and now I'll dazzle him with the brilliance of other languages possibly. :D

You cannot use any alternative character (makes it easier?).

Current leader board

Pyth - 28 bytes - isaacg
CJam - 30 bytes - Runer112
CJam - 32 bytes - Martin Büttner

Highest votes: C - 73 bytes - Paul R

isaacg takes the crown for passing the Staircase Challenge with Pyth. Watch out for more challenges like these on PPCG!


Tips for golfing in Tcl What general tips do you have for golfing in Tcl? I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to Tcl (e.g. "remove comments" is not an answer). Please post one tip per answer.

Use lmap instead foreach. This requires Tcl 8.6.

The syntax is the same, but lmap returns a list with the result of each loop.


Translate English to Corpus The Corpus are a fictional faction from the popular video game Warframe who have a somewhat interesting language.
Whilst other factions in the game such as the Grineer have some logic behind their language, the Corpus is simply a lossy substitution of the English language.
All Corpus words are the same as their English counterparts, except with the following alphabetical mappings:

This causes some problems with pronunciation as:
yes becomes yey
say becomes yay
yay becomes yay
sassy becomes yayyy
case becomes yaye
Here's a text version of the mappings:
a -> a
b -> t
c -> y
d -> p
e -> e
f -> t
g -> j
h -> k
i -> i
j -> t
k -> k
l -> p
m -> s
n -> t
o -> o
p -> k
q -> r
r -> t
s -> y
t -> p
u -> u
v -> t
w -> j
x -> k
y -> y
z -> b

The challenge
Given text using the English alphabet, output its Corpus translation.
For example, the text Hello, World! becomes Keppo, Jotpp! in Corpus
The Rules

Input will only consist of ASCII printable characters
Input text may contain whitespace and punctuation, these must be preserved
Capitalization of letters must be preserved
This is code-golf so naturally, fewest bytes wins!

The Testcases
Test cases are separated with <===========>, with a blank line between input and expected output
Hello, World!

Keppo, Jotpp!
<===========>
Yes

Yey
<===========>
TestcaSe

PeypyaYe
<===========>
Programming Puzzles and Code Golf

Ktojtassitj Kubbpey atp Yope Jopt
<===========>
This text has a
newline in it

Pkiy pekp kay a
tejpite it ip
<===========>
Corpus language best language

Yotkuy patjuaje teyp patjuaje
<===========>
Strip the flesh! Salt the wounds!

Yptik pke tpeyk! Yapp pke joutpy!
<===========>
"Install Warframe" they said, "It'll be fun" they said

"Itypapp Jatttase" pkey yaip, "Ip'pp te tut" pkey yaip
<===========>
What the **** did you just ****ing say about me, you little *****?
I'll have you know I graduated top of my class in the Navy Seals,
and I've been involved in numerous secret raids on Al-Quaeda,
and I have over 300 confirmed kills.

Jkap pke **** pip you tuyp ****itj yay atoup se, you pipppe *****?
I'pp kate you ktoj I jtapuapep pok ot sy ypayy it pke Taty Yeapy,
atp I'te teet ittoptep it tusetouy yeytep taipy ot Ap-Ruaepa,
atp I kate otet 300 yottitsep kippy.

The Bonus
If you also include an audio recording (or video with audio) of you pronouncing each of the testcase's Corpus translations, you may multiply your bytecount by 1 as a reward.

Bash + coreutils, 46

tr b-zB-Z ${a=typetjkitkpstokrtyputjkyb}${a^^}

Try it online!


IPv4 Integer Conversion Function Write the shortest function to convert an IP address into it's integer representation and output it as an integer.

To change an IPv4 address to it's integer representation, the following calculation is required:

Break the IP address into it's four octets.
(Octet1 * 16777216) + (Octet2 * 65536) + (Octet3 * 256) + (Octet4)

Sample Input

192.168.1.1           10.10.104.36           8.8.8.8

Sample Output

3232235777            168454180              134744072

PHP - 21 Characters

<?=ip2long($argv[1]);


Uncomment a COBOL program! COBOL is a very old language, at the time of writing it is 58 years old.
It is so old, in fact, that it has a very interesting quirk: the first six characters of each line are comments.

Why is this, you ask? Well, those 6 characters were intended to be used as line numbers, back in the day where programs weren't completely digital and typed out on a computer.

In addition, the seventh character could only be part of a very small set (it is usually * to comment out the line or a space to separate the line number from the code)

But what if you're on a more digital system, and you just want the raw program?

The comment system

There are two types of comments in COBOL: line comments and the aforementioned "line number" comments.

Uncommenting line numbers is simple: just take the first seven (six plus a single space) characters off each line.

000000 apple
000001 banana
celery donuts

would become:

apple
banana
donuts

Line comments make it a bit more difficult.
A line comment is started with an asterisk * placed in the seventh character position on the line, like so:

000323* this is a comment

This is not a line comment:

*00000 this isn't a comment

To uncomment a line comment, just remove the whole line.

An example commented "program":

000000 blah blah
000001* apples
000002 oranges?
000003* yeah, oranges.
000*04 love me some oranges

The uncommented version:

blah blah
oranges?
love me some oranges

In other words, to uncomment a string, remove the first six characters of each line, then return all but the first character of every line that does not begin with a star.

The challenge

Create a program or function that takes a commented program and returns its uncommented variant.

Clarifications

Asterisks (*) will never be found anywhere outside the first seven characters on a line (we're not asking you to verify syntax)
Each line will always have at least 7 characters.
You may assume the seventh character is always an asterisk or a space.
Input or output may be a matrix or list.
Only printable ASCII characters (plus newline) must be handled.
You may output with a trailing newline. You may also assume that the input will have a trailing newline, if you so choose.

Scoring

Since this is code-golf, the answer with the least bytes wins!

DISCLAIMER: I do not actually know COBOL and do not claim to. If any of the claims about COBOL I have made in this question are incorrect, I take no responsibility.

COBOL (GnuCOBOL), 191 + 17 = 208 bytes

I "learned" COBOL for this answer, so it's probably not fully golfed.

This is a full program, taking input on what I presume to be standard input and writing to what I presume to be standard output. Perhaps one day I'll return to this and (1) determine whether COBOL has functions and, if so, (2) see whether a function solution would be shorter.

Byte count includes program and compiler flags (-free and -frelax-syntax).

program-id.c.select i assign keyboard line sequential.fd i. 1 l pic X(80). 88 e value 0.open input i perform until e read i end set e to true end-read if not e and l(7:1)<>'*'display l(8:73).

Try It Online

Ungolfed program

program-id. c.

select i assign to keyboard organization line sequential.

fd i.
    1 l pic X(80).
    88 e value 0.

open input i
perform until e
    read i
        end set e to true
    end-read
    if not e and l(7:1) <> '*'
        display l(8:73).

Limitations

The output is, technically speaking, not correct. From my cursory research, it seems the only practical way to store a string in COBOL is in a fixed-size buffer. I have chosen a buffer size of 80 characters, since this is the line length limit for fixed-format programs. This presents two limitations:

Lines longer than 80 characters are truncated.
Lines shorter than 80 characters are right-padded with spaces.

I'm guessing this is acceptable since, well, it's COBOL. If not, I'd be willing to look into alternatives.

Acknowledgments

-166 bytes thanks to Edward H
-2 bytes thanks to hornj


Longest Common Subsequence of Two Strings containing a particular Substring A subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements.

Given three strings A, B and C (note the order) as input, find the length of the longest string S such that:

Condition 1: S is a subsequence of A
Condition 2: S is a subsequence of B
Condition 3: C is a substring of S

.

Testcase #1

Input:

ABCDEF

CDEFAB

B

Output:

2

Testcase #2

Input:

HELLO

WORLD

SUCKS

Output:

0

Testcase #3

Input:

ABCXD

BCDEF

CD

Ouput:

3

Testcase #4

Input:

X

Y

Z

Ouput:

0

Note:

The empty string is regarded as a subsequence as well as a substring of every string.
Assume all input strings are in uppercase.
Return 0 as output if any of the first two conditions (Condition 1 and Condition 2) is not going to be satisfied using Condition 3.

Constraints:

Assume the lengths of A, B and C will always be between 1 and 3000 (both inclusive)

Winner:

One with the shortest code.

APL (45)

⌈/0,⍴¨m/⍨∨/¨⍞∘⍷¨m←⊃∩/{/∘⍵¨↓⍉(z/2)⊤⍳2*z←⍴⍵}¨⍞⍞

Explanation:

¨⍞⍞: read two lines. For each of them:

⍳2*z←⍴⍵: get the numbers from 1 up to 2^length.
(z/2)⊤: encode each number as bits
↓⍉: separate each string of bits into its own array
/∘⍵¨: and use each of them as a bitmask on the string, giving the subsequences

m←⊃∩/: take the intersection of the two arrays of subsequences, store in m
∨/¨⍞∘⍷¨: read a third line, and see in which subsequences it occurs
m/⍨: select those elements from m that contained the third line
⍴¨: get the length of each remaining subsequence
0,: add a zero entry in case the resulting list is empty
⌈/: get the highest number in the list

Test cases:

      ⌈/0,⍴¨m/⍨∨/¨⍞∘⍷¨m←⊃∩/{/∘⍵¨↓⍉(z/2)⊤⍳2*z←⍴⍵}¨⍞⍞
ABCDEF
CDEFAB
B
 2
      ⌈/0,⍴¨m/⍨∨/¨⍞∘⍷¨m←⊃∩/{/∘⍵¨↓⍉(z/2)⊤⍳2*z←⍴⍵}¨⍞⍞
HELLO
WORLD
SUCKS
 0
      ⌈/0,⍴¨m/⍨∨/¨⍞∘⍷¨m←⊃∩/{/∘⍵¨↓⍉(z/2)⊤⍳2*z←⍴⍵}¨⍞⍞
ABCXD
BCDEF
CD
 3
      ⌈/0,⍴¨m/⍨∨/¨⍞∘⍷¨m←⊃∩/{/∘⍵¨↓⍉(z/2)⊤⍳2*z←⍴⍵}¨⍞⍞
X
Y
Z
 0


Hexadecimal To Decimal Read input of up to 8 characters presented as hexadecimal number and print this number as decimal number. In case that input can not be presented as hexadecimal input it has to print 0

Rules:
It is not allowed to use any function that takes or returns strings/characters, beside function that reads string/char from input and return strings/char as-is, function that takes integer and prints that integer to output as decimal number and function (if needed) that takes character and return its ASCII/UNICODE represented integer.

Shortest code wins

Example input
C0cAc01a

output
3234512922

Ruby, 74 characters
n=0;p gets.gsub(/./).all?{|x|n=n*16+(x>?9?9:0)+x.ord%16;/[\da-f]/i=~x}?n:0

Input must be given on STDIN. With command line option -ln (counted as 4) it can be shortened to 69 characters.
n=0;p chars.all?{|x|n=n*16+(x>?9?9:0)+x.ord%16;/[\da-f]/i=~x}?n:0


Golfed decimal fractions Your goal is to write some code that will output the shortest unique decimal sequence for the input fraction. No two fractions with the same denominator may have the same output, although it's possible for fractions with different denominators to have the same representation.

Take 2 integers as input, the first is the numerator, the second is the denominator.

E.g.:

n  d   output
-----  ------
0 13:  0.00
1 13:  0.07
2 13:  0.1
3 13:  0.2
4 13:  0.30
5 13:  0.38

etc.

3/13 is the only fraction with a denominator of 13 that starts with 0.2, so no further digits are required. 4/13 and 5/13 both start with 0.3, so another digit is required to distinguish between them.

You may output numbers greater than -1 and less than 1 either with or without a zero before the decimal point, as long as the output is consistent, i.e. 0.5 and .5 are the same number and are both valid. No other leading zeros are allowed. Trailing zeros must be shown if they are necessary to distinguish the output from another value.

You may not round any numbers away from zero; they must be truncated. There must be no leading or trailing spaces. There may optionally be a single trailing newline.

More test values:

   n    d   output
----------  ------
   0    1:   0 (this 0 may not be removed because there's no decimal point)
   5    1:   5
   0    3:   0.0 (or .0)
   4    3:   1.3
   5    3:   1.6
  10    8:   1.2
  11    8:   1.3
  12    8:   1.5
-496  -38:  13.05
 458  -73:  -6.27
  70  106:   0.660 (or .660)
 255  123:   2.07
 256 -123:  -2.081
-257 -123:   2.089
-258  123:  -2.09
 258 -152:  -1.697
-259  152:  -1.70
 260  152:   1.710
 272  195:   1.39
 380  247:   1.538
 455 -455:  -1.000
 -44  891:  -0.049 (or -.049)
 123 1234:   0.099 (or .099)

In each case, the output and the denominator are sufficient to uniquely work out the numerator.

Perl, 77 bytes

#!perl -p
$%++while/ /<grep{!index$_/$',$\=$`/$'.($`%$'?0:n).0 x$%&'?'x$%}$`-2..$`+2}{

Counting the shebang as one, input is taken from stdin.

Sample Usage

$ echo 0 3 | perl golf-decimals.pl
0.0

$ echo 4 3 | perl golf-decimals.pl
1.3

$ echo 11 8 | perl golf-decimals.pl
1.3

$ echo -496 -38 | perl golf-decimals.pl
13.05

$ echo 458 -73 | perl golf-decimals.pl
-6.27

$ echo -44 891 | perl golf-decimals.pl
-0.049


Crop an image to a square In this challenge, you will take an input image and crop it to make a square, leaving only the central part of the input image.

The answers must work with landscape, portrait, or square input images. The width of the output image should be equal to the shortest side of the input image e.g. the result of a 200x300 image should be a 200x200 image. An equal amount must be cropped from both ends of the input image e.g. for a 200x300 input image, 50 pixels should be cropped from each end of the image, leaving only the central part of the image. Where its not possible to crop an equal amount from both sides e.g. a 200x301 image, the extra 1 pixel may be cropped from either end of the image. For a square input image, the output should be identical to the input.

Input:

The input file should be read from the hard disk of the machine running the program. You may choose which of bmp, jpeg, png or pnm to support as the input image format.

Output

The output file should be written to the hard disk of the machine running the program. The format of the output image should be bmp, jpeg, png or pnm.

Win Criteria

This is code golf. Shortest code wins.

Notes:

The input/output file paths do not count towards the program size.
The standard libraries of your programming language may be used. Other libraries are disallowed.
Standard loopholes apply.

Example:

Input Image:

Expected Output:

Images by kirill777 - licenced CC-BY 3.0

Parsing the raw bytestream: Haskell (319 = 332 - 13)

Without any imports at all, this program crops P1 PBM images.

g _[]=[]
g z x=(\(a,b)->a:g z b).splitAt z$x
q=map
f=filter
main=do c<-readFile"in.pbm";let(r:p)=tail.f((/='#').head).lines$c;(w:h:_)=(q read).words$r;m=min w h;t s=take m.drop((s-m)`div`2);k d=[[m,m]]++(q(t w)(t h d))in writeFile"out.pbm".("P1\n"++).unlines.q(unwords.(q show)).k.(q((q read).g 1)).take h.g w.f(`elem`"01").concat$p

Special case: helpful formatting (214 = 227 - 13)

My first attempt at PBM (P1) was based on the example at Wikipedia and assumed spaces separated the pixels, and lines in the text correlated with lines in the image. Under those conditions, this shorter version works fine.

main=do c<-readFile"in.pbm";writeFile"out.pbm".("P1\n"++).unlines.q(unwords.(q show)).k.q((q read).words).tail.filter((/='#').head).lines$c
k((w:h:_):d)=let m=min w h;t s=take m.drop((s-m)`div`2)in[[m,m]]++(q(t w)(t h d))
q=map

Bonus feature: strips out comments!

Both of the above work in essentially the same manner as the original below, but with a simpler header, lower bit depth, and no padding, although the topmost program works harder to allow for a range of formatting options.

Also available in a wide range of colours: Haskell (545 = 558 - 13)

No pre-existing image-handling functions were harmed in the making of this program.

Uncompressed 24-bit RGB bitmaps have a fairly straight-forward header system but are complicated by the mod-4 padding for each row's byte array. This code grabs the bitmap offset, width, and height from the input header, calculates the row padding, and extracts the bitmap data into a list of lists (rows of columns, bottom-left corner first).

Cropping is as simple as dropping half the excess and then taking the desired length from each list. The new file size is calculated as 3*(padded width)*height + 54 bytes (for the minimal required headers). The new header is constructed and the cropped image data appended. It's all mapped to characters and written back out to disk.

Input: in.bmp (6 characters removed from total)
Output: out.bmp (7 characters removed from total)

I think there's still some redundancy still in there, but my brain hurts to look at it this way.

import System.IO
import Data.Char
import Data.List.Split
main=do k"in.bmp"ReadMode(\h->do i h u;c<-hGetContents h;let d=l(ord)c;w=s 18d;h=s 22d;p=o w;m=min w h;q=o m;j a b=y a(r b m)in k"out.bmp"WriteMode(\g->do i g u;hPutStr g$"BM"++l chr((z e[m*(3*m+q)+54,0,54,40,m,m,1572865,0,0,1,1,0,0])++((z((++(f q$cycle[0])).y(3*m)(3*r w m)).j m h$chunksOf(3*w+p)$n(s 10d)d)))))
i=hSetBinaryMode
k=withFile
z=concatMap
l=map
v=div
f=take
n=drop
u=True
y t d=f t.n d
s d=sum.zipWith(*)(l(256^)[0..3]).y 4d
o=(`mod`4)
r a b=v(a-b)2
e x=l((`mod`256).(x`v`).(256^))[0..3]

For comparison, an ungolfed version is over 8 times as long, at 4582 (4595 - 13) bytes:

import System.IO
import Data.Char
import Data.List.Split

main = readImage cropImageToSquare

cropImageToSquare fileHandle = do

  hSetBinaryMode fileHandle True
  fileContents <- hGetContents fileHandle

  let
    inImageData         = asBytes fileContents

    inImageBitmapOffset = getIntFromWordAt 10 inImageData
    inImageWidth        = getIntFromWordAt 18 inImageData
    inImageHeight       = getIntFromWordAt 22 inImageData

    inImageBitmapData   = drop inImageBitmapOffset inImageData
    inImageBitmap       = chunksOf (paddedBytesForWidth inImageWidth) inImageBitmapData

    outImageSideLength  = min inImageWidth inImageHeight

    outFileHeader       = fileHeader  outImageSideLength outImageSideLength
    outImageHeader      = imageHeader outImageSideLength outImageSideLength
    outHeaders          = outFileHeader ++ outImageHeader

    outImageBitmap      = crop outImageSideLength outImageSideLength inImageWidth inImageBitmap

    in
      writeImage "out.bmp" outHeaders outImageBitmap

--- Read Image ---------------------------------------------------------

readImage = withFile "in.bmp" ReadMode

--------------------------------------------------------- Read Image ---

--- Write Image --------------------------------------------------------

writeImage filename header imageBitmap = do
  withFile filename WriteMode write'
    where
      write' fileHandle = do
        hSetBinaryMode fileHandle True
        hPutStr fileHandle . ("BM"++)
                           . map chr $ (concatMap wordFromInt header)
                                     ++ (concat imageBitmap)

-------------------------------------------------------- Write Image ---

--- Character-Integer Conversion ---------------------------------------

asBytes = map ord

getWordAt offset = take 4 . drop offset

getIntFromWordAt offset = intFromWord . getWordAt offset

intFromWord     = sum . zipWith (*) (map (256^) [0..3])

wordFromInt int = map((`mod` 256) . (int `div`) . (256^)) [0..3]

--------------------------------------- Character-Integer Conversion ---

--- Headers ------------------------------------------------------------

fileHeader width height = [ fileSize
                          , reserved
                          , bitmapOffset
                          ]
  where
    fileSize     = imageFileSize width height
    reserved     = 0
    bitmapOffset = 54

imageFileSize width height = 54 + height * (paddedBytesForWidth width)
paddedBytesForWidth width  = 3 * width + rowPadding width
rowPadding = (`mod` 4)

imageHeader width height = [ imageHeaderSize
                           , width
                           , height
                           , planesAndBits
                           , compression
                           , bitmapSize
                           , horizontalImageResolution
                           , verticalImageResolution
                           , paletteSize
                           , coloursUsed
                           ]
  where
    imageHeaderSize  = 40
    planesAndBits    = int32FromInt16s colourPlanes bitDepth
    colourPlanes     = 1
    bitDepth         = 24
    compression      = 0
    bitmapSize       = 0
    horizontalImageResolution = pixelsPerMetreFromDPI 72
    verticalImageResolution   = pixelsPerMetreFromDPI 72
    paletteSize      = 0
    coloursUsed      = 0

pixelsPerMetreFromDPI = round . (* (100/2.54))

int32FromInt16s lowBytes highBytes = lowBytes + shift 2 highBytes
shift bytesUp number  = (256 ^ bytesUp) * number

------------------------------------------------------------ Headers ---

--- Crop Image ---------------------------------------------------------

crop toHeight toWidth fromWidth = cropWidth toWidth fromWidth
                                . cropHeight toHeight

cropHeight toHeight image = take toHeight
                          . drop ( halfExtra (length image) toHeight)
                          $ image

cropWidth toWidth fromWidth image = map ( padRow toWidth
                                        . take (3 * toWidth)
                                        . drop (3 * (halfExtra fromWidth toWidth))
                                        )
                                      $ image

padRow toWidth xs = take (paddedBytesForWidth toWidth)
                      $ xs ++ (repeat 0)

halfExtra fromLength toLength = (fromLength - toLength) `div` 2

--------------------------------------------------------- Crop Image ---


Generate a UK numberplate Modern British number plates (a.k.a. registration marks or license plates) use the format AANNXXX where AA is a "DVLA memory tag" (basically a location code), NN is the age identifier, and XXX is three random letters.
Your task is to, given a date, generate a random valid number plate with a date code matching the supplied date. Simplified from the actual implementation, this is how to generate them:

The memory tag will just be generated randomly:

First letter: random from ABCDEFGHKLMNOPRSVWY (the alphabet, minus IJQTUXZ)
Second letter: random from ABCDEFGHJKLMNOPRSTUVWXY (the alphabet, minus IQZ)

The age identifier follows this pattern:

1st September 2001 - 28th February 2002: 51
1st March 2002 - 31st August 2002: 02
September 2002 - February 2003: 52
March 2003 - August 2003: 03
...
March 2010 - August 2010: 10
September 2010 - February 2011: 60
March 2011 - August 2011: 11
September 2011 - 29th February 2012: 61
...
September 2020 - February 2021: 70
...
September 2049 - February 2050: 99
March 2050 - August 2050: 00
September 2050 - February 2051: 50
March 2051 - August 2051: 01

The 3 random letters are picked from ABCDEFGHJKLMNOPRSTUVWXYZ (the alphabet, minus IQ)

Rules

You must output in uppercase with no spaces or dashes between letters. However, trailing newlines, or any other output from your language that is not easily suppressible, are allowed
For the purposes of this challenge, "random" means picked pseudo-randomly with any distribution as long as all possibilities have a non-zero chance of occurring
You may assume the date will always be in the range 1st September 2001 to 31st August 2051
The date can be in any reasonable input format (for example, your language's native date object, april 28 2021, (28,4,21), 1619615864 (a Unix epoch timestamp))
You may ignore leap seconds, daylight savings time, and timezone issues (just assume the date is always in UTC)
You may use any reasonable I/O method
Standard loopholes are forbidden
This is code-golf, so the shortest code in bytes wins

Test cases
These are to test the date conversion alone.
23rd September 2001     51
1st March 2006          06
29th February 2012      61
1st December 2021       71
11th October 2049       99
19th January 2051       50

JavaScript (ES6), 121 bytes
Expects (month)(year). The day is ignored.

m=>y=>"9512444".replace(/./g,n=>(100+(y-(m<3))%50+50*(m<3|m>8)+n)[n]||'ABCDEFGHKLMNOPRSVWYJTUXZ'[Math.random()*(28-n)|0])

Try it online!


Be as fair as possible Introduction

In this challenge you should split an integer into two pieces. Since nobody likes getting the smaller piece of cake, your goal is to be as fair as possible. For example if you wanted to split the integer 7129 into two pieces, there are 3 possible ways of doing so.

7,129, 71,29 and 712,9 are all possibilities, but 71,29 is the fairest way of splitting it into two pieces because it minimizes the difference between the two:

7 129 -> |7-129| = 122
71 29 -> |71-29| = 42
712 9 -> |712-9| = 703

Challenge

Given an integer determine the best possible way of partitioning it as described above and report the resulting difference.

Rules

Splitting only makes sense for integers of length at least two, the input will always be ≥ 10
Input can be either an integer, list of digits or a string
You don't have to handle invalid input

Testcases

You only need to report the resulting difference, the partitioning is only here for illustration:

10 -> 1,0 -> 1
11 -> 1,1 -> 0
12 -> 1,2 -> 1
13 -> 1,3 -> 2
101 -> 1,01 -> 0
128 -> 12,8 -> 4
313 -> 3,13 -> 10
1003 -> 1,003 -> 2
7129 -> 71,29 -> 42
81128 -> 81,128 -> 47
999999 -> 999,999 -> 0
9999999 -> 999,9999 or 9999,999 -> 9000

Brachylog, 12 11 bytes
My first Brachylog answer
Take input as a string
{~cĊịᵐ-ȧ}ᶠ⌋

Try it online!
Explanation:
ᶠ will find all possible outputs for the predicate in {…} and store them in a list. ~c says that the output is a list that, when concatenated, is equal to the input. Next Ċ asserts that the the output of ~c has length 2.
ịᵐ converts both elements of the output into integers (this gets rid of leading 0s), -ȧ takes the absolute difference of the two elements.
Once we have our list of all possible outputs, we get the minimum element with ⌋


Marching Through A City There is a parade marching through a city! There are 3 main groups of marchers: the (B)and, Poster (C)arriers, and (F)lag Holders. Also, every (P)oliceman in the whole city is on duty.

Flag holders (F) can march anywhere in the parade, but two flag holders cannot march next to each other, unless three or more flag holders are together.

The band (B) has to be together. The poster carriers (C) all have to be behind the band (either together, or in two groups).

Given the number of flag holders, poster carriers, band members, and policemen separated by your choice of delimiter, print one line for every possible configuration, organized in alphabetical order.

Test case 1:

Input:
2 2 2 0
Output:
CCFBBF
CFCBBF
CFCFBB
FCCBBF
FCCFBB
FCFCBB

Test case 2:

Input:
3 3 3 0
Output:
CCCBBBFFF
CCCFFFBBB
CCFCFBBBF
CCFFFCBBB
CFCCFBBBF
CFCFCBBBF
CFFFCCBBB
FCCCFBBBF
FCCFCBBBF
FCFCCBBBF
FCFCFCBBB
FFFCCCBBB

Test case 3:

Input:
2 2 2 1
Output:
CCBBFPF
CCFBBFP
CCFBBPF
CCFPBBF
CCFPFBB
CCPFBBF
CFCBBFP
CFCBBPF
CFCFBBP
CFCFPBB
CFCPBBF
CFCPFBB
CFPCBBF
CFPCFBB
CFPFCBB
CPCFBBF
CPFCBBF
CPFCFBB
FCCBBFP
FCCBBPF
FCCFBBP
FCCFPBB
FCCPBBF
FCCPFBB
FCFCBBP
FCFCPBB
FCFPCBB
FCPCBBF
FCPCFBB
FCPFCBB
FPCCBBF
FPCCFBB
FPCFCBB
FPFCCBB
PCCFBBF
PCFCBBF
PCFCFBB
PFCCBBF
PFCCFBB
PFCFCBB

This is code-golf, so the shortest source code in bytes wins.
*Note: It doesn't count if it takes longer than 3 seconds to run each test case. I won't use integers more than 20.

Pyth, 56 bytes
jf&!},2\FrT8!:T"B.*C|C([^C]+C+){2}|B[^B]+B"0{S.ps*V"FCBP

Try it online!


Python 2, 444 391 372 bytes

Crossed out 444 is still regular 444 ;(

Huge thanks to @Dennis for a whopping -52 -71 bytes!

k=lambda c,a,b:abs(a+c*a-c*b)-c<abs(b-a)>0and k(c,b-c*a,a+b-c*b)or(a,b)
def f(*t):
 a,b=sorted(t);m=b-a+1,0;g=lambda _:min([k(1,*k(0,*s)),m][_!=b:],key=lambda(x,y):abs(x-y))
 if b<0:x,y=f(-a,-b);return-x,-y
 for c in range(-b,b+1):
    for s in(c,a),(a,c):
     x,y=s
     if min(s)>0:
        while y<b:x,y=y,x+y
        m=g(y)
     x,y=s
     while(x!=b)&((x>b)^(b>0)):x,y=y-x,x
     m=g(x)
 return m

Try it online!

The solution can be run by calling f(a, b) on the two input integers. It is based on the idea that if both a and b are within at least one of the same sequence (where a and b are ordered beforehand such that a ≤ b), it follows that there is at least one integer c equivalent to an adjacent value of a in a shared sequence of a and b for which the sequence generated by a and c contains b in it.

Furthermore, if at least one of the two integers is positive, all values of c must be bounded by -b ≤ c ≤ b for it to even be possible to generate the value of b on either side of the starting pair. Thus, the solution simply brute-forces values of c between -b and b that in combination with a are capable of generating b within the sequence, and finds the one for which the difference of the kernel values for a and c are minimal (this is possible because finding the kernel for two adjacent numbers in a sequence is trivial).

If neither a nor b is positive, the solution simply negates both and returns the negative of the kernel generated for the negated pair.


How far should I sum? How far should I sum?

The harmonic series is the "infinite sum" of all the fractions of the form \$\frac1n\$ for \$n\$ positive integer. I.e. the harmonic series is

$$\frac11 + \frac12 + \frac13 + \frac14 + \cdots$$

It is well-known that this sum diverges, which means that if you define

$$ H_n = \frac11 + \frac12 + \cdots + \frac1n$$

Then the value of \$H_n\$ goes to infinity. This can also be stated in a different way: for any positive value \$x\$ you pick, there is some value \$N\$ such that, to the right of \$N\$, the \$H\$ values are bigger than \$x\$:

$$\forall\ x\ \exists\ N: n > N \implies H_n > x $$

Your task

Write a program/function that takes as input a positive number x (not necessarily an integer) and outputs the first integer n for which

$$H_n \geq x$$

In theory your program must work for arbitrary x, even if in practice you are limited by the memory and/or precision of your programming language/computer.

Test cases

1.5 -> 2
2 -> 4
3 -> 11
3.1415 -> 13
4 -> 31
5 -> 83
7.5 -> 1015
10 -> 12367

This is code-golf so shortest solution wins! Standard loopholes are forbidden by default. Happy golfing.

APL (Dyalog), 13 bytes

-1 bytes thanks to ngn

{⊃⍸⍵≤+\÷⍳⌈*⍵}

Try it online!

A dfn solution that takes a right argument.

Explanation:

{           }   ⍝ dfn
 ⊃              ⍝ Take the first of
  ⍸             ⍝ The indexes of the truthy values of
   ⍵≤           ⍝ The right argument is smaller than or equal to
     \+         ⍝ The cumulative sum
       ÷        ⍝ The reciprocal of each of
        ⍳       ⍝ The range 1 to
         ⌈      ⍝ The ceiling of
          *⍵    ⍝ e to the power of the right argument


Rotating a 2D Matrix Let's say I have the following (2D) matrix:

[[1,  2,  3,  4 ],
 [5,  6,  7,  8 ],
 [9,  10, 11, 12],
 [13, 14, 15, 16]]

Rotate the matrix counterclockwise R times (not in 90 degree increments, just by 1 number each time),

1  2  3  4             2 3   4  8         3   4   8  12
5  6  7  8    -->      1 7  11 12   -->   2  11  10  16
9  10 11 12            5 6  10 16         1   7   6  15
13 14 15 16            9 13 14 15         5   9  13  14

Completed example:

Input:

2
[[1,  2,  3,  4 ],
 [5,  6,  7,  8 ],
 [9,  10, 11, 12],
 [13, 14, 15, 16]]

Output:

[[3,  4,  8, 12],
 [2, 11, 10, 16],
 [1,  7,  6, 15],
 [5,  9, 13, 14]]

(weird spaces are to align the numbers in nice columns)

The outer "ring" of the matrix rotates 2 counterclockwise, and the inner right rotates 2 also.  In this matrix, there are only two rings.

An example with 1 "ring":

2
[[1, 2],
 [3, 4],
 [5, 6]]

Should output:

[[4, 6],
 [2, 5],
 [1, 3]]

Your challenge is to take in a matrix and an integer R, and output the translated version after R rotations.

Rotation of a 4x5 matrix is represented by the following figure:

Constraints:

2 ≤ M, N ≤ 100, where M and N are the dimensions of the matrix. It is guaranteed that the minimum of M and N will be even.
1 ≤ R ≤ 80, where r is number of rotations.
The matrix will only ever contain positive integers.
Values are not always distinct.
The input should always be as a 2D array (if you can't take runtime input as a 2D array, then you just have to find another way to get input).

Another test case, with non-distinct values:

1
[[1, 1],
 [2, 2],
 [3, 3]]

Outputs:

[[1, 2],
 [1, 3],
 [2, 3]]

This is code-golf, so the shortest answer wins!

Octave, 210 bytes

function M=F(M,R);f=@(z)[-z/2:-1 !eye(!!mod(z,2)) 1:z/2];t=angle(f([x y]=size(M))'+f(y)*i);B=!!M;B(2:x-1,2:y-1)=0;d=bwdist(B,'ch');[~,I]=sortrows([d(:) t(:)]);for k=0:max(d(:));M(h)=shift(M(h=I(d(I)==k)),R);end

Try it on Octave Online!
Ungolfed version:
function M=F(M,R)
    [x y]=size(M);
    f=@(z)[-z/2:-1 !eye(!!mod(z,2)) 1:z/2];
    t=angle(f(x)'+f(y)*i);
    B=!!M;
    B(2:x-1,2:y-1)=0;
    d=bwdist(B,'chessboard');
    [~,I]=sortrows([d(:) t(:)]);
    for k=0:max(d(:))
        M(h)=shift(M(h=I(d(I)==k)),R);
    end
end
R=2;
M=randi(10,4,7)
F(M,R)

Explanation:
f=@(z)[-z/2:-1 !eye(!!mod(z,2)) 1:z/2];

A function that gets a number and generates a range that is ordered and centered
for input 4 (even) generates  -2  -1   1   2
for input 5(odd) generates -2.5 -1.5 0  1  2
only it should be ordered and centered
f(x)'+f(y)*i

a complex matrix generated from ranges
(-2,-2.5) (-2,-1.5) (-2,0) (-2,1) (-2,2)
(-1,-2.5) (-1,-1.5) (-1,0) (-1,1) (-1,2)
(1,-2.5)  (1,-1.5)  (1,0)  (1,1)  (1,2)
(2,-2.5)  (2,-1.5)  (2,0)  (2,1)  (2,2)

t=angle(f(x)'+f(y)*i);

Convert rectangular to polar coordinates and return angles so for each ring angles are sorted counteclockwise
-2.25  -2.50  3.14  2.68  2.36
-1.95  -2.16  3.14  2.36  2.03
-1.19  -0.98  0.00  0.79  1.11
-0.90  -0.64  0.00  0.46  0.79

B=!!M;
B(2:x-1,2:y-1)=0;

The following matrix generated
1   1   1   1   1
1   0   0   0   1
1   0   0   0   1
1   1   1   1   1

d=bwdist(B,'chessboard');

Computes the distance transform of B using chessboard distance to generate ring indices
0   0   0   0   0
0   1   1   1   0
0   1   1   1   0
0   0   0   0   0

for a 6 * 7 matrix we will have the following matrix
0   0   0   0   0   0   0
0   1   1   1   1   1   0
0   1   2   2   2   1   0
0   1   2   2   2   1   0
0   1   1   1   1   1   0
0   0   0   0   0   0   0

[~,I]=sortrows([d(:) t(:)]);

lexicographic sort first based on ring index and then by order of angle(indices of sorted elements returned)
    for k=0:max(d(:))
        M(h)=shift(M(h=I(d(I)==k)),R);
    end

and finally circular shift each ring.


Algorithmic braiding - for mother's day Task:

Your task is to create a program that, when given a number of strands and number of iterations of a braid, will tell where each strand goes. Rules are as follows:

The number of strands will always be odd, and between 3 and 6000 (inclusive)
When you start, the strands will be divided into 2 (almost) equal bunches, the left and the right. The left will have one more strand when you start.

For an input of 7:

/ / / / \ \ \
1 2 3 4 5 6 7

Every iteration, the outermost strand of the side with more strands will be put in the center facing the opposite direction. The center is defined as between opposite facing strands: ////middle\\\.

1 iteration of input 7 (strand 1 was moved to the center):

/ / / \ \ \ \
2 3 4 1 5 6 7

Example:

Input:

3 4

Computations:

1 2 3
 \
2 1 3
   /
2 3 1
 \
3 2 1
   /
3 1 2

Output:

3 1 2

Rules:

You do not need to display the slashes for strand direction, only the numbers.
You only need to display the numbers after the last iteration.
Your output will be space-deliminated ids of the strands
Input will be in the form: strands [space] iterations
The number of strands will always be odd, and 3<=x<=6000
This is code-golf, so the shortest code wins!

GolfScript, 33 characters
~\),(@{:^1$[=]:y-.,2//y*^~}*;' '*

The input must be provided on stdin.
Examples (you may test online):
> 7 1
2 3 4 1 5 6 7

> 3 4
3 1 2

> 11 2
2 3 4 5 6 11 1 7 8 9 10


Continuously expanding code Your job is to write a program that rewrites and makes itself longer on each run of the program.

Challenge

The program will print Hello, World!\n (\n denotes a newline). Then, it will modify its own file so that the new program length is exactly 2x the length at runtime. This modified file when run, will print Hello, World!\nHello, World!\n. When run a third time, the file will print Hello, World!\nHello, World!\nHello, World!\nHello, World!\n.

More simply, on the nth run of the program, it will output 2^(n-1) instances of Hello, World!\n, and have a program length of 2^(n-1) the length of the original.

This is code-golf, so shortest code (before first run) wins. Please comment if you need something is not clear.

Edit: To get past the restriction of file-rewriting, your program may print the modified source along with the Hello, World!\ns at a +40% penalty.

PHP, 100

More efficient, 101

<?$a=$argv[0];$b=file_get_contents($a);file_put_contents($a,$b.substr($b,81,20));echo"Hello World\n";

This script is appending an echo"Hello World";, but because you said the size should also vary, and because it's shorter, I'm also having this script:

Shorter, 100

<?$a=$argv[0];$b=file_get_contents($a);file_put_contents($a,$b.substr($b,2,98));echo"Hello World\n";

This script is appending itself, in a way it adds one Hello World, but this version will overall take more space and takes longer to execute.

Example

But the scripts don't vary when it comes to the output:

root@raspberrypi:~/stack# php hello_expand.php
Hello World
root@raspberrypi:~/stack# php hello_expand.php
Hello World
Hello World
root@raspberrypi:~/stack# php hello_expand.php
Hello World
Hello World
Hello World