Natural Pi #1 - Sand Goal

Generate (N) random line segments of uniform length (l), check if they cross the equidistant (t) parallel lines.

Simulation

What are we simulating? Buffon's needle. Smooth out the sand in your sandbox, draw a set of equally spaced parallel lines (call the distance in between t). Take a straight stick of length l and drop it N times into the sandbox. Let the number of times it crossed a line be c. Then Pi = (2 * l * n) / (t * c)!

How are we simulating this?

Take input N,t,l
With N, t, l all being positive integers
Do the following N times:

Generate a uniformly random integer coordinate x,y
With 1 <= x, y <= 10^6
x,y is the center of a line segment of length l
Generate a uniformly random integer a
With 1 <= a <= 180
Let P be the point where the line segment would cross the x-axis
Then a is the angle (x,y), P, (inf,0)

Count the number, c, of line segments that cross the line x = i*t for any integer i
Return (2 * l * N) / (t * c)

Specification

Input

Flexible, take input in any of the standard ways (eg function parameter,STDIN) and in any standard format (eg String, Binary)

Output

Flexible, give output in any of the standard ways (eg return, print)
White space, trailing and leading white space is acceptable
Accuracy, please provide at least 4 decimal places of accuracy (ie 3.1416)

Scoring

Shortest code wins!

Test Cases

Your output may not line up with these, because of random chance. But on average, you should get about this much accuracy for the given value of N, t, l.

Input (N,t,l)    ->  Output
-----------        ------
10,10,5          -> ?.????
10,100,50        -> ?.????
1000,1000,600    -> 3.????
10000,1000,700   -> 3.1???
100000,1000,700  -> 3.14??

TL;DR

These challenges are simulations of algorithms that only require nature and your brain (and maybe some re-usable resources) to approximate Pi. If you really need Pi during the zombie apocalypse, these methods don't waste ammo! There are nine challenges total.

R, 113 100 75 70 68 67 65 59 63 57 bytes

As a statistical, functional programming language, it's not surprising that R is fairly well-suited to this kind of task. The fact that most functions can take vectorized input is really helpful for this problem, as rather than looping over N iterations, we just pass around vectors of size N. Thanks to @Billywob for some suggestions that lead to cutting off 4 bytes. Many thanks to @Primo for patiently explaining to me how my code wasn't working for cases where t > l, which is now fixed.

pryr::f(2*l*N/t/sum(floor(runif(N)+sinpi(runif(N))*l/t)))

Try it online!

Sample output:

N=1000, t=1000, l=500
3.037975

N=10000, t=1000, l=700
3.11943

N=100000, t=1000, l=700
3.140351

Explanation

The problem boils down to determining whether the two x values of the needle are on either side of a parallel line. This has some important consequences:

y-values are irrelevant
The absolute location on the x-axis is irrelevant, only the position relative to the closest parallel lines.

Essentially this is a task in a 1-dimensional space, where we generate a line with length in [0, l] (the angle a determines this length), and then we check to see how many times this length exceeds t. The rough algorithm is then:

Sample x1 values from [0, 1000000]. Since parallel lines occur at every tth point along the x-axis, the relative x-position is x modulo t.
Sample an angle a.
Calculate the x2 position based on a.
Check how many times x1+x2 fits into t, i.e. take the floor of (x1+x2)/t.

Sampling N numbers in [0, 1e6] modulo t is equivalent to simply sampling N numbers in [0, t]. Since (x1+x2)/t is equivalent to x1/t + x2/t, the first step becomes sampling from [0, t]/t, i.e. [0, 1]. Lucky for us, that is the default range for R's runif function, which returns N real numbers from 0 to 1 from a uniform distribution.

                          runif(N)

We repeat this step to generate a, the angle of the needle.

                                         runif(N)

These numbers are is interpreted as a half-turn (i.e. .5 is 90 degrees). (The OP asks for degrees from 1 to 180, but in comments it's clarified that any method is allowed if it is as or more precise.) For an angle θ, sin(θ) gives us the x-axis distance between the ends of the needle. (Normally you'd use the cosine for something like this; but in our case, we are considering the angle θ as being relative to the y-axis, not the x-axis (that is, a value of 0 degrees goes up, not right), and therefore we use the sine, which basically phase-shifts the numbers.) Multiplied by l this gives us the x location of the end of the needle.

                                   sinpi(runif(N))*l

Now we divide by t and add the x1 value. This yields (x1+x2)/t, which is how far the needle protrudes from x1, in terms of number of parallel lines. To get the integer of how many lines were crossed, we take the floor.

                    floor(runif(N)+sinpi(runif(N))*l/t)

We calculate the sum, giving us the count c of how many lines are crossed by needles.

                sum(floor(runif(N)+sinpi(runif(N))*l/t))

The rest of the code is just implementing the formula for approximating pi, that is, (2*l*N)/(t*c). We save some bytes on parentheses by taking advantage of the fact that (2*l*N)/(t*c) == 2*l*N/t/c:

        2*l*N/t/sum(floor(runif(N)+sinpi(runif(N))*l/t))

And the whole thing is wrapped into an anonymous function:

pryr::f(2*l*N/t/sum(floor(runif(N)+sinpi(runif(N))*l/t)))


Balance the Brackets Your objective: Given a string of brackets, output the minimum Damerau-Levenshtein Distance required to turn the input string into a string where the brackets are balanced.
Input
The input string will only contain brackets and no other characters. That is, it is a combination of any of the characters in (){}[]<>. You may take input as either a string or an array of characters. You may not make any other assumptions about the input string; it may be arbitrarily long (up to the maximum size supported by your language), it may be empty, the brackets may already be balanced, etc.
Damerau-Levenshtein Distance
The Damerau-Levenshtein Distance between two strings is the minimum number of insertions, deletions, single-character substitutions, and transpositions (swapping) of two adjacent characters.
Output
The output should be the minimum Damerau-Levenshtein Distance between the input string and a string in which the brackets are matched. Output should be a number, not the resulting balanced string.
A pair of brackets is considered "matched" if the opening and closing brackets are in the right order and have no characters inside of them, such as
()
[]{}

Or if every sub-element inside of it is also matched.
[()()()()]
{<[]>}
(()())

Sub-elements can also be nested several layers deep.
[(){<><>[()]}<>()]
<[{((()))}]>

(Thanks to @DJMcMayhem for the definition)
Test Cases
Input                   Possible Balanced       Output

Empty                   Empty                   0
[](){}<>                [](){}<>                0
[(){}<>                 [(){}<>]                1
[(])                    []()                    1
[[[[[[[[                [][][][]                4
(](<>}[>(}>><(>(({}]    ()(<>)[(<><>){}]        7
>]{])<                  []{()}                  3
([)}}>[                 (){}<>                  4
{<((<<][{{}>[<)         <>(<<[]>{}>[])          5
{><({((})>}}}{(}}       {<><({()})>}{}{()}      4
(](<)>}[>(}>>{]<<(]]    (<()<><<>()>>[])<()>    9
}})(                    {}()                    2

(Thanks to @WheatWizard for solving half of the test cases)
This is code-golf, fewest bytes wins!
Your submissions should be testable, meaning it should output a result for  each test case in no more than an hour.


JavaScript, 297 277 262 235 223 chars

No carriage returns in the golfed version are significant; they are there only to make the answer readable. Semicolons are significant.

Edit: Replaced the outer map with a while loop and other edits. Finally inside of 2× the size of the Golfscript version (for now)!

Edit: Replaced the indexOf with math, broke down the lookup table, other small improvements.

Edit: Another map to for and put in a final \n I had been unnecessarily eating. Finally inside of Jules's Python version.

i=prompt(o='').split(' ');for(r=6;o+=' EADGBe'[r]+' ',r--;o+='\n')
for(j=0;n=i[j++];o+=(([84,13,52,5][2*/m/.test(n)+x]*8>>2*r&3)+y-7*x)+'---')
y=n.charCodeAt(0),y=(2*y-(y>66)-(y>69)+(n[1]<'$')-(n[1]=='b')+2)%12,x=y>6;alert(o)

Output no longer takes advantage of the trailing --- being optional as:

e 2---2---0---0---3---5---0---2---
B 3---2---2---0---3---7---0---2---
G 4---3---2---1---4---7---0---3---
D 4---4---2---2---5---7---2---4---
A 2---4---0---2---5---5---2---4---
E 2---2---0---0---3---5---0---2---


Generate a random point outside a given rectangle within a map Introduction
Given this visualization of a playing field:
(0,0)
+----------------------+(map_width, 0)
|           A          |
|-----+-----------+----|
|  D  |     W     | B  |
|-----+-----------+----|
|           C          |
+----------------------+(map_width, map_height)
(0, map_height)

The entire map the game is played on is the rectangle with the corner coordinates (0,0) and (map_width, map_height). The points eligible for spawning enemies is the Union $$S = \bigcup (A, B, C, D) $$
The Challenge
Write code that returns a random point(x, y) that is guaranteed to be inside S. Your code cannot introduce any additional bias, meaning that the probability of each coordinate is uniformly distributed given the assumption that your choice of generating randomness (e.g. function|library|dev/urandom) is unbiased.
Shortest solutions in bytes win!
Input
You will be given a total of 6 positive integer input variables in order:
map_width, map_height, W_top_left_x, W_top_left_y, W_width, W_height. You can assume that the (calculated) surface area of all regions(A,B,C,D,W) is each >10, so there are no empty spaces/regions.
Example Input: 1000, 1000, 100, 100, 600, 400
The input has to contain the 6 values described above but it can be passed as fewer numbers of arguments and in any order. For instance passing (map_width, map_height) as python tuple is allowed. What is not allowed of course are calculated parameters like the bottom right point of the W.
Output
2 randomly generated integers (x, y) where
$$(0 \leq x \lt \text{map_width}) \land (0 \leq y \lt \text{map_height}) \land[\neg (\text{W_top_left_x} \leq x \lt \text{W_top_left_x} + \text{view_width})\lor \neg (\text{W_top_left_y} \leq y \lt \text{W_top_left_y} + \text{view_height})]$$
holds.
Examples
Input                                    Output(valid random samples)

1000 1000 100 100 600 400                10 10
1000 1000 100 100 600 400                800 550
1000 1000 100 100 600 400                800 10
1000 1000 100 100 600 400                10 550

For details and limitations for input/output please refer to the default input/output rules

Python 2, 114 106 102 101 bytes

lambda w,h,X,Y,W,H:choice([(i%w,i/w)for i in range(w*h)if(W>i%w-X>-1<i/w-Y<H)<1])
from random import*

Try it online!


Combinatorial Decomposition In the body of this challenge, \$\begin{pmatrix}n\\k\end{pmatrix}\$ is used to represent the number of combinations of \$k\$ elements of \$n\$, also written as \$\frac{n!}{k!(n-k)!}\$ or \$n\mathrm{C}r\$.
Any nonnegative integer \$m\$, for arbitrary natural (positive) \$r\$, can be written as a unique series of \$r\$ combinations such that $$m=\sum\limits_{i=1}^{r}\begin{pmatrix}C_i\\i\end{pmatrix}$$ provided the sequence \$C\$ both strictly increases (i.e. \$C_{\ell-1}\lneq C_\ell\$) and consists solely of nonnegative integers. \$C\$ is not necessarily unique without these restrictions.

Example
Consider \$m=19\$ and \$r=4\$. Values of \$C_4\$, \$C_3\$, \$C_2\$ and \$C_1\$ must be found for the equation $$19=\sum\limits_{i=1}^4\begin{pmatrix}C_i\\i\end{pmatrix}\\$$ which can be rewritten as $$\begin{pmatrix}C_4\\4\end{pmatrix}+\begin{pmatrix}C_3\\3\end{pmatrix}+\begin{pmatrix}C_2\\2\end{pmatrix}+\begin{pmatrix}C_1\\1\end{pmatrix}=19$$ Begin by finding the largest value of \$C_4\$ which satisfies the inequality \$\begin{pmatrix}C_4\\4\end{pmatrix}\leq 19\$. \$C_4\$ is six: $$\begin{pmatrix}6\\4\end{pmatrix}+\begin{pmatrix}C_3\\3\end{pmatrix}+\begin{pmatrix}C_2\\2\end{pmatrix}+\begin{pmatrix}C_1\\1\end{pmatrix}=19\\15+\begin{pmatrix}C_3\\3\end{pmatrix}+\begin{pmatrix}C_2\\2\end{pmatrix}+\begin{pmatrix}C_1\\1\end{pmatrix}=19\\\begin{pmatrix}C_3\\3\end{pmatrix}+\begin{pmatrix}C_2\\2\end{pmatrix}+\begin{pmatrix}C_1\\1\end{pmatrix}=4$$ The problem has been reduced to \$m=4\$ and \$r=3\$. The largest value of \$C_3\$ which satisfies the inequalities \$\begin{pmatrix}C_3\\3\end{pmatrix}\leq4\$ and \$C_3\lneq C_4\$ must be found. \$C_3\$ is four: $$\begin{pmatrix}4\\3\end{pmatrix}+\begin{pmatrix}C_2\\2\end{pmatrix}+\begin{pmatrix}C_1\\1\end{pmatrix}=4\\4+\begin{pmatrix}C_2\\2\end{pmatrix}+\begin{pmatrix}C_1\\1\end{pmatrix}=4\\\begin{pmatrix}C_2\\2\end{pmatrix}+\begin{pmatrix}C_1\\1\end{pmatrix}=0$$ Any combination of the form \$\begin{pmatrix}n\\k\end{pmatrix}\$ with \$n<k\$ is zero, and so \$C_2=1\$ and \$C_1=0\$: $$\begin{pmatrix}1\\2\end{pmatrix}+\begin{pmatrix}0\\1\end{pmatrix}=0\\0+0=0\\0=0\checkmark$$
Note that \$C_2\$ cannot be zero because then \$C\$ would not strictly increase unless \$C_1\$ were negative, which cannot be the case due to the condition that \$C\$ consists solely of nonnegative integers. The solution is summarized with the statement \$C=(0,1,4,6)\$ (here, 1-based indexing is used). The process followed here is guaranteed to produce the correct \$C\$.

The Challenge
Given \$m\$ and \$r\$, find the elements of \$C\$.
Rules

This is code-golf so the shortest answer in bytes wins.

Assume only valid input will be given.

Input and output may assume whatever form is most convenient. This can include outputting the elements of \$C\$ in any order, because \$C\$ strictly increases and so the actual order of the elements is trivially found by sorting them.

Terms whose combinations evaluate to zero, e.g. \$C_2\$ and \$C_1\$ in the example, cannot be neglected in output.

A program should theoretically work for arbitrarily large values of \$m\$ and \$r\$, but is still acceptable if it is limited by memory constraints.

Test Cases
Here \$m\$ is the first number and \$r\$ is the second, and the output begins with \$C_1\$.
In: 19 4
Out: 0 1 4 6

In: 0 4
Out: 0 1 2 3

In: 40000 6
Out: 6 8 9 11 12 20

In: 6 6
Out: 1 2 3 4 5 6

In: 6 5
Out: 0 1 2 3 6

In: 6 20
Out: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 15 16 17 18 19 20 (note 14 is skipped)

In: 6 1
Out: 6

JavaScript (ES6),  95 93 86  82 bytes
Expects (r)(m).

r=>F=(m,x=r)=>r?(g=k=>!k||g(--k)*(k-x)/~k)(r)>m?[...F(m-g(r--,--x)),x]:F(m,x+1):[]

Try it online!
How?
Helper function
The helper function \$g\$ is used to compute:
$$\binom{x}{r}=\frac{x(x-1)\dots(x-r+1)}{r!}=\prod_{k=1}^{r}\frac{x-k+1}{k}$$
(g = k =>     // g is a recursive function taking k
  !k          // if k = 0, stop the recursion and return 1
  ||          // otherwise:
    g(--k)    //   decrement k and do a recursive call with the updated value
    * (k - x) //   multiply the result by k - x
    / ~k      //   divide by -k - 1
              //   which is equivalent to g(k - 1) * (x - k + 1) / k
)(r)          // initial call to g with k = r

Main function
r =>                      // r = requested number of combinations
F = (m, x = r) =>         // F is a recursive function taking the target number m
                          // and a counter x, initialized to r
  r ?                     // if r is not equal to 0:
    g(r) > m ?            //   if C(x, r) is greater than m:
      [ ...F(             //     append the result of a recursive call to F:
          m - g(r--, --x) //       with m - C(x - 1, r) and r - 1
        ),                //     end of recursive call
        x                 //     append x (which was decremented above)
      ]                   //
    :                     //   else:
      F(m, x + 1)         //     increment x until C(x, r) > m
  :                       // else:
    []                    //   stop the recursion


Sort by shuffling blocks Block shuffle sort

The block shuffle sort is a (rather artificial) method of sorting a list.
It works as follows, illustrated by an example.

[6, 1, 0, 3, 2, 4, -2, -1]
                            Break list into contiguous blocks
[6][1, 0][3, 2, 4][-2, -1]
                            Sort each block
[6][0, 1][2, 3, 4][-2, -1]
                            Sort blocks lexicographically
[-2, -1][0, 1][2, 3, 4][6]
                            Concatenate
[-2, -1, 0, 1, 2, 3, 4, 6]

The partition into contiguous blocks can be chosen arbitrarily.
However, not all choices of blocks will yield a sorted list at the end:

[6, 1, 0, 3, 2, 4, -2, -1]
[6, 1, 0][3, 2, 4][-2, -1]
[0, 1, 6][2, 3, 4][-2, -1]
[-2, -1][0, 1, 6][2, 3, 4]
[-2, -1, 0, 1, 6, 2, 3, 4]

If all blocks have length 1, or if there is only one block, then the result will of course be sorted.
But these are rather extreme cases.
In this challenge, your task is to find a balance between the number of blocks and the maximum length of a block.

The task

Your input is a nonempty list of integers L, taken in any reasonable format.
Your output shall be the smallest integer N such that L can be block shuffle sorted so that the number of blocks and the length of each block are at most N.

The lowest byte count in each language wins.
Standard code-golf rules apply.

Test cases

[5] -> 1
[1,2] -> 2
[0,2,1,-1] -> 3
[-1,0,2,1] -> 2
[9,3,8,2,7] -> 4
[9,2,8,3,7] -> 3
[5,9,3,7,2,4,8] -> 7
[-1,-2,1,2,-1,-2,7] -> 4
[6,1,0,3,2,4,-2,-1] -> 4
[12,5,6,-6,-1,0,2,3] -> 3
[1,0,1,0,1,0,1,0,1,0] -> 6
[1,2,1,3,1,2,3,2,4,3] -> 5
[7,7,7,7,8,9,7,7,7,7] -> 4

Brachylog, 23 22 20 19 bytes

Thanks to Zgarb, H.PWiz and Fatalize for saving some amount of bytes.

~cᶠ{oᵐoc≤₁&≡ᵃlᵐ⌉}ˢ⌋

Try it online!

I'm sure there's more to golf here...

Explanation

~cᶠ      Find all lists that concatenate into the input, i.e. all partitions
         of the input.
{        Discard all partitions for which this predicate fails, and replace
         the rest with the output of this predicate.
  oᵐ       Sort each sublist of the partition.
  o        Sort the entire list.
  c≤₁      And require concatenation of the result to be sorted.
  &        Then:
  ≡ᵃ       Append the partition to itself.
  lᵐ       Map "length" over this list, i.e. we get the length of each block, as
           well as the length of the partition itself.
  ⌉        Take the maximum.
}ˢ
⌋        Take the minimum of all those maxima.


Insert commas into numbers Write a program that reads a string, and inserts commas to divide large numbers in groups of 3. i.e. 10000 => 10,000. It should 'fix' incorrectly formatted numbers as described below.

It must work for all numbers on the same line
It should not modify numbers after a decimal point. i.e. 1234.5678 => 1,234.5678
Leading zeros should be removed (or inserted where appropriate):

00000 => 0
00001234 => 1,234
.1234 => 0.1234
00.1234 => 0.1234
1000.1234 => 1,000.1234

All non-digit characters should not be altered.
It should correct, incorrectly placed "," characters only when followed before or after a digit:

10,,00 => 1,000
00,000 => 0
a,2 => a2
2,a => 2a
,a2 => ,a2
0,a2 => 0a2
,,, => ,,,
,,,. => ,,,.
,,,1 => 1
,.,,1 => 0.1

Numbers that contain multiple "." should not be treated as a number, and therefore no comma separation should be used:

1..3 => 1..3
1234.5678.9012 => 1234.5678.9012
1234,,.5678abc.123 => 1,234.5678abc0.123
1234.,.5678abc.123 => 1234.,.5678abc0.123

Explanations to unusual cases:

,,,. => ,,,. (not a number, no special meanings to ",", ".")
,,,.0 => 0 (these characters are neighbouring a number and treated as such)
1,,, => 1
,,,1 => 1
,.,,1 => 0.1 (the "." indicates decimal number, remove incorrectly placed "," in number).
,.,,.1 => ,.,,.1 (not a number because multiple ".")
a,,,b1234 = > a,,,b1,234 (first few characters are not neighbouring a number and treated as text)

Example inputs:

10000
10,000
$1234.12
~$123456789.12345~
HELLO123456.99BYE
The_amount_€45678_is_$USD51805.84
5000000-1999999=3000001
!1234567.1234+1234567.1234=2469134.2468!
00000a00
0b0001234
.a.1234
00.1234
1000.1234
10,,00
00,000
a,2
2,a
,a2
0,a2
,,,
,,,.
,,,1
,.,,1
1..3
1234.5678.9012
1234,,.5678abc.123
1234.,.5678abc.123
,,,.
,,,.0
1,,,
,,,1
,.,,1
,.,,.1
a,,,b1234

Corresponding outputs:

10,000
10,000
$1,234.12
~$123,456,789.12345~
HELLO123,456.99BYE
The_amount_€45,678_is_$USD51,805.84
5,000,000-1,999,999=3,000,001
!1,234,567.1234+1,234,567.1234=2,469,134.2468!
0a0
0b1,234
.a0.1234
0.1234
1,000.1234
1,000
0
a2
2a
,a2
0a2
,,,
,,,.
1
0.1
1..3
1234.5678.9012
1,234.5678abc0.123
1234.,.5678abc0.123
,,,.
0
1
1
0.1
,.,,.1
a,,,b1,234

Code golf: shortest code wins.

Retina, 71 bytes

/[\d.,]+/_/\d/&/\..*\./^&(`,

^0+

^\B
0
'.&`\.?0+$

/^\d+/_r`\B...
,$&

Try it online! Link includes test cases. Explanation:

/[\d.,]+/_

Find all runs of digits, .s and ,s.

/\d/&

Ignore those with no digits.

/\..*\./^&

Ignore those with two .s.

(`

Process the rest of the script on each remaining match.

,

Delete all commas.

^0+

Delete all leading zeros.

^\B
0

Insert a leading zero if the number does not begin with a digit.

'.&`

If the number contains a ....

\.?0+$

... delete trailing zeros and any preceding ..

/^\d+/_

On the part of the number before the ....

r`\B...
,$&

Match groups of three starting from the end, but leave at least one digit at the beginning, and insert commas before each match.


Is it a Linearized Tree? (Breadth-first Edition) Background

An unlabelled tree may look like this:

   o
 / | \
o  o  o
|    / \
o   o   o

To linearize this tree, we first label each node o with it's number of child nodes:

   3
 / | \
1  0  2
|    / \
0   0   0

and then write the numbers in a list in a breath-first manner, meaning line by line and left to right:

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

This is a unique and unambiguous representation of the tree above, meaning that no two different pure trees will have the same linearizations and that we can reconstruct the original tree from the list.

Although each tree corresponds to a certain integer list, not each integer list represents a valid linearized tree: For example [2, 0, 0, 0] does not represent a valid tree, if we try to de-linearize it we end up with this tree

[2,0,0,0] -> 2 [0,0,0] -> 2 [0,0] -> 2 [0]
            / \          / \        / \
                        0          0   0

but still have a 0 left in the list and nowhere to put it. Similarly [2, 0] is not a valid tree linearization either, as the de-linearized tree has an empty child spot:

  2
 / \
0

Task

Given an integer list, decide whether it is a valid linearization of a tree using as few bytes as possible. You may write a full program or a function.

Input:  A non-empty list of non-negative integers.

Output:  A truthy value if the list is a linearization of a tree, a falsy value otherwise.

Testcases

Truthy

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

Falsy

[0, 1]
[2, 0]
[2, 0, 0, 0]
[1, 0, 1]
[3, 2, 1, 0]
[2, 0, 0, 2, 0, 0]
[4, 1, 0, 3, 0, 0, 0, 0]
[4, 2, 0, 3, 1, 0, 0, 0, 0, 0]

Haskell, 44 bytes

f[n:k]=iterate f[k]!!n
f _=[]
g x=f[x]==[[]]

Defines a function g that takes a list and returns a boolean.
See it pass all test cases.

Explanation

This relies on the fact that depth-first and breadth-first linearizations produce the same arrays.
See Martin's answers for details; basically they both give the same arithmetical condition on the array.

The function f is given the input list wrapped in a singleton list.
It pops one number n off the list, then calls itself n times on the remaining list to process the children of the popped node (depth first).
Popping the empty list results in [], which I use as an error state.
The function g checks that the end result is [[]], the unique non-erroneous state with no unprocessed nodes.
If Haskell was weakly typed, I could just use 0 or something as the error state, and wouldn't have to wrap the input into another list.


Generate me some appropriate license plates! The scenario: You are a software designer working for a gov't-run company that designs license plates for cars and other vehicles. You've been asked to develop software that generates license plates. Before you got to work, your bosses laid down these ground rules.

A license plate cannot contain:

ASS
666
69<any number here>
<any number here>69
KKK
SHT

Rules and requirements:

License plate must be randomly generated.
Once a random license plate is generated, the same license plate cannot be generated again.
You must output at least 200 unique license plates. You can generate more if you want to.
You may store generated plates in a file to "remember" them.
The license plate contains 2 sections, one containing only three letters, and one containing only three numbers, separated by a dash, like this: 233-ADF or ADF-233.
You can only use numbers and capital letters.
License plates can be written to stdout, or a file.
Each "side" of a license plate will contain either three numbers or letters.
This is a code-golf, so shortest, most popular, answer wins. Winner will be chosen after seven days.

General rules

Answer should include, but not limited to, the following.
Language name.
Character count.
File size.
How the code is run.
The code itself.
Example: Python 234 chars or Python 23mb.

If I need to clarify any additional details, please mention it in the comments and I will add it to my post. Anyways, good luck, and generate me some appropriate license plates!

Update 1: Winner will be chosen slightly earlier.

Turns out I have to go on a trip soon, so I will be choosing a winner around 00:00 UTC, July 25. After the winner is chosen, you can still submit entires, just know that a winner has been chosen. Bai.

Update 2: Winners!

We have winners! Yay! Cheese and wine to everyone who participated! Here's who won.

1st place: Àngel - Bash (95 characters)
2nd place: Martin Büttner - Mathematica (182 bytes)
2nd place: Emilio M Bumachar - Pyg (92 ?)
2nd place: Peter Taylor - Golfscript (98 characters)
3rd place: Mark Thomas - Ruby (127 characters)

Wow, three second place ties. Wow. The competition is over, but feel free to submit entries if you want to. Bai!

bash (95 chars)

Save the script as m in a folder in your PATH with execute bit set.

Run as bash m. The plates are stored in file p

l(){ tr -dc $1</dev/urandom|head -c3;};egrep -ve"ASS|666|69|KKK|SHT" -fp>>p<<<`l 0-9`-`l A-Z`;m

This is equivalent to running the following:

# Print three random numbers and three random letters
echo $(tr -dc 0-9 < /dev/urandom | head -c3)-$(tr -dc A-Z < /dev/urandom | head -c3) |

# Print only plates not matching the blacklist or any line of p
# Append the plates ton p
egrep -v -e "ASS|666|69|KKK|SHT" -f p >> p

# Execute itself again
m

Caveat: The final m should actually be exec m (+5 chars) in order to avoid leaving processes waiting for completion (but you can have thousands without much problem)

Credit goes to  http://www.cyberciti.biz/faq/linux-random-password-generator/ for the idea of using tr -dc


Shortest paths in a divisor graph Introduction

In this challenge, we will be dealing with a certain infinite undirected graph, which I call the high divisor graph.
Its nodes are the integers starting from 2.
There is an edge between two nodes a < b if a divides b and a2 ≥ b.
The subgraph formed by the range from 2 to 18 looks like this:

16-8 12 18
  \|/ |/|
   4  6 9 10 15 14
   |  |/   |/   |
   2  3    5    7  11 13 17

It can be shown that the infinite high divisor graph is connected, so we can ask about the shortest path between two nodes.

Input and output

Your inputs are two integers a and b.
You can assume that 2 ≤ a ≤ b < 1000.
Your output is the length of the shortest path between a and b in the infinite high divisor graph.
This means the number of edges in the path.

You may find the following fact useful: there always exists an optimal path from a to b that's first increasing and then decreasing, and only visits nodes that are strictly less than 2b2.
In particular, since b < 1000 you only need to consider nodes less than 2 000 000.

Examples

Consider the inputs 3 and 32.
One possible path between the nodes 3 and 32 is

3 -- 6 -- 12 -- 96 -- 32

This path has four edges, and it turns out there are no shorter paths, so the correct output is 4.

As another example, an optimal path for 2 and 25 is

2 -- 4 -- 8 -- 40 -- 200 -- 25

so the correct output is 5.
In this case, no optimal path contains the node 50 = lcm(2, 25).

Rules and scoring

You can write a full program or a function.
The lowest byte count wins, and standard loopholes are disallowed.
There are no time or memory limits, so brute forcing is allowed.

Test cases

2 2 -> 0
2 3 -> 4
2 4 -> 1
2 5 -> 5
3 5 -> 4
6 8 -> 2
8 16 -> 1
12 16 -> 2
16 16 -> 0
2 25 -> 5
3 32 -> 4
2 256 -> 3
60 77 -> 3
56 155 -> 3
339 540 -> 2
6 966 -> 4
7 966 -> 2
11 966 -> 4
2 997 -> 7
991 997 -> 4

Matlab, 218 190 175 bytes
function f(a,b);q=a;l(b)=0;l(a)=1;while~l(b);x=q(1);q=q(2:end);l(end+1:x^2)=0;g=x+1:x^2;s=2:x-1;u=[g(~mod(g,x)),s(~mod(x,s)&s.^2>=x)];u=u(~l(u));q=[q,u];l(u)=l(x)+1;end;l(b)-1

Thanks @beaker for the shortcut in in the list lengthening step!
This is a relatively straightforward dijkstra implementation:
q=a;                  %queue
l(b)=0;       %list of path lengths
l(a)=1;
while~l(b);         %if there is no predecessor to b
    x=q(1);         %get first queue element
    q=q(2:end);
    %add edges
    l(end+1:x^2)=0;% lengthen predecessor list if too short
    g=x+1:x^2;      % g=greater neighbours
    s=2:x-1;        % s=smaller neighbours %keep only valid/unvisited neighbours
    u=[g(~mod(g,x)),s(~mod(x,s)&s.^2>=x)]; %-1byte
    u=u(~l(u));
    q=[q,u];      %add only hte valid nodes edges to queue
    l(u)=l(x)+1;       %mark x as predecessor
end;
l(b)-1 %output length to the end of the path

 no convolution today


The Snail in the Well Background

There's a common riddle that goes something like this:

  A snail is at the bottom of a 30 foot well. Every day the snail is able to climb up 3 feet. At night when they sleep, they slide back down 2 feet. How many days does it take for the snail to get out of the well?

The intuitive answer is

   30 days, because the snail climbs at 1 foot per day for 30 days to reach the top,

but actually the answer is

   28 days, because once the snail is 27 feet in the air (after 27 days), they will simply climb the remaining 3 feet to the top on the 28th day.

Challenge

This challenge generalizes this riddle. Given three positive integers as input, representing the total height, the climb height, and the fall height, return the number of days it will take to climb out of the well.

If the snail cannot climb out of the well, you may return 0, return a falsy value, or throw an exception. You may also write code that will halt if and only if a solution exists.

If you wish, you may take the fall height as a negative integer.

Test Cases

(30,  3,  2) -> 28
(84, 17, 15) -> 35
(79, 15,  9) -> 12
(29, 17,  4) -> 2
(13, 18,  8) -> 1
( 5,  5, 10) -> 1
( 7,  7,  7) -> 1
(69,  3,  8) -> None
(81, 14, 14) -> None

Scoring

This is code-golf, so the shortest answer in each language wins.

Gray Snail, 1206 bytes for numeric I/O, 149 bytes for unary I/O

For fun. Composition of first program:

451 bytes, converting number into dots
121 bytes, core function (a separated version is written below)
634 bytes, converting dots into number

Take numeric input and output.
Input is A, B, C respectively. Compared to other (near) O(1) answer, the code has a complexity of O(n). But for large number, it may eat up your memory first.

Hang if no solution is found.

INPUT p
POP Z r .!
f
POP Z o .
q
POP Z p [p]
GOTO [Z]
0
POP Z n .
GOTO w
1
POP Z n ..
GOTO w
2
POP Z n ...
GOTO w
3
POP Z n ....
GOTO w
4
POP Z n .....
GOTO w
5
POP Z n ......
GOTO w
6
POP Z n .......
GOTO w
7
POP Z n ........
GOTO w
8
POP Z n .........
GOTO w
9
POP Z n ..........
GOTO w
w
POP Z o .[o][o][o][o][o][o][o][o][o][o][n]
GOTO [r] [p]
GOTO q
!
POP Z A .[o]
INPUT p
POP Z r .@
GOTO f
@
POP Z B .[o]
INPUT p
POP Z r .#
GOTO f
#
POP Z C .[o]
POP H N .[B]
U
POP Z A [A]
POP Z B [B]
GOTO D [A]
GOTO $ [B]
GOTO U
$
POP Z A .[A][C]
POP Z H ..[H]
POP Z B .[N]
GOTO U
D
POP Z r .
POP Z M .
POP Z N ...........
POP Z z .[N]
POP Z V .[H]
+
GOTO l[V] [H]
POP Z H [H]
POP Z z [z]
GOTO ( [z]
GOTO +
(
GOTO ) [H]
POP Z z .[N]
POP Z M ..[M]
POP Z V .[H]
GOTO +
)
POP Z r .0[r]
POP Z M ..[M]
POP Z H .[M]
POP Z M .
POP Z V .[H]
POP Z z .[N]
GOTO +
l
POP Z r .0[r]
GOTO -
l.
POP Z r .1[r]
GOTO -
l..
POP Z r .2[r]
GOTO -
l...
POP Z r .3[r]
GOTO -
l....
POP Z r .4[r]
GOTO -
l.....
POP Z r .5[r]
GOTO -
l......
POP Z r .6[r]
GOTO -
l.......
POP Z r .7[r]
GOTO -
l........
POP Z r .8[r]
GOTO -
l.........
POP Z r .9[r]
GOTO -
-
GOTO / [M]
POP Z H .[M]
POP Z M .
POP Z V .[H]
POP Z z .[N]
GOTO +
/
OUTPUT [r]

f is a (maybe) recursive function to convert integers into dots. Argument is saved in [p] and output in [o].

U is a function testing S1>=S2, storing parameter in B, A while saving A-B into A.

Code starting from D is a stub converting dots into numbers.

The underlying principle is the same with my C answer (ripping off falsy output for impossible solutions).

Standalone version, 149 156 157 167 170 230 bytes, only support unary I/O

Input needs to be dots, e.g. .......... for 10.

INPUT A
INPUT B
INPUT C
POP N H .
GOTO U
$
POP N A .[A][C]
POP Z H ..[H]
U
POP Z A [A]
POP Z N ..[N]
GOTO D [A]
GOTO $ .[B] [N]
GOTO U
D
OUTPUT .[H]

U calculates A=A-B, and jumps to D when A<=0. Otherwise $ assigns A+C to A and call U.

Hang if no solution is found.

Tricks: abuse the "compiler"'s ability to interpret empty string. You can rip off conditions in GOTO statement to make unconditioned jumps and the same trick works for POP.

Remark: I may golf it more by 3 bytes but by doing so, mine and WheatWizard's answer would have the exact same logic. The result is probably the shortest GraySnail solution and I'm trying to prove it.


R, 20 bytes

Is this what you are after?  Uses table to count the occurrences of each of the scan input values.  Tests if count is > 1 and sums the trues.

sum(table(scan())>1)

Try it online!


Golfing with Python Import When is it beneficial to use inline, single use importing in Python?

For example:

__import__("x").doSomething()

Is the above ever shorter than the below?

import x
x.doSomething()

Or

from x import*
doSomething()

This can be useful if you want to use a module just once in an anonymous lambda function, as it allows you to avoid writing a separate statement:

lambda x:__import__('SomeModule').foo(x,123)

is one byte shorter than

from SomeModule import*;f=lambda x:foo(x,123)

If the code is a named function or program, then __import__ is unlikely to help except in the most extreme or contrived circumstances.


Print 0-255 in grey code Gray Code is a number system where only 1 bit of the number changes from one number to the next number.  Print the 8 bit Gray Code values of 0 to 255.

Shortest Code wins!

Start of output:

 0 00000000
 1 00000001
 2 00000011
 3 00000010
 4 00000110
 5 00000111
 6 00000101
 7 00000100
 ...

You only have to print the Gray Code in binary.  The decimal numbers in the example are just for reference.

Ruby, 48 33 Bytes

15 Bytes saved thanks to G B

256.times{|i|puts "%08b"%(i^i/2)}


Two dozen kissing number approximations Given a number from 1 to 24, output the kissing number to the best of current knowledge (some numbers will have more than one acceptable output). Knowledge of geometry is not essential as the outputs are all listed below.

From the Wikipedia page on the Kissing Number Problem:

  a kissing number is defined as the number of non-overlapping unit spheres that can be arranged such that they each touch another given unit sphere

That is, given one unit sphere, how many more unit spheres can touch it without any of them overlapping? The question will be asked in N dimensional space, where a sphere is understood to be an N-1 dimensional sphere.

For example:

in 2 dimensional space, a unit circle can touch 6 other unit circles.
in 3 dimensional space, a unit sphere can touch 12 other unit spheres.

The Wikipedia page lists values for 1 to 24 dimensional space. However, some of these are not yet known accurately, so only a lower and upper bound are given. The table is reproduced here so that it will remain fixed, regardless of any future narrowing of the ranges due to new proofs. Solutions are judged against this fixed table, even if the Wikipedia page is modified in future.

Table of bounds

Dimension   Lower bound     Upper bound
1           2               2
2           6               6
3           12              12
4           24              24
5           40              44
6           72              78
7           126             134
8           240             240
9           306             364
10          500             554
11          582             870
12          840             1357
13          1154            2069
14          1606            3183
15          2564            4866
16          4320            7355
17          5346            11072
18          7398            16572
19          10668           24812
20          17400           36764
21          27720           54584
22          49896           82340
23          93150           124416
24          196560          196560

Input

The dimension: An integer from 1 to 24 (inclusive).

Here "integer" indicates that the input will have no fractional part - it may be 2 or 3 but never 2.5. A solution may still take input as a float, or a string, for example.

Output

A number in the relevant range, from the lower limit to the upper limit for that input (inclusive).

The output must be deterministic (always the same for the same input).

The output must be integer. For example, for input 5 the possible valid outputs are 40, 41, 42, 43, 44. Note this is a restriction on the value, not the type. It is acceptable to return a float, provided it has zero fractional part. For example, 41.5 would not be valid, but 41.0 would be valid.

Scoring

This is code-golf. Your score is the number of bytes in your code. For each language, the winner is the solution with the lowest score.

Julia 0.6, 52 bytes

n->ceil(n<8?3.7exp(.51n)-5.1:n<24?9exp(.41n):196560)

Try it online!

How?

Machine learning! (Kinda. Maybe. Not really.)

First, from plotting the lower and upper limit data against N, and some manual trial and error, it seemed like an exponential function could fit well for N >= 8. After some attempts at manually finding this function, I resorted to using a parameter tuning function to tune \$ a * e^{b K} + c \$  (where K = 8 to 24) to find a, b, and c such that the expression gave values that lie within the correct range for each K (with successively smaller range of possible values and correspondingly higher precisions for a, b, c in different runs of the function). There were a few such set of values, though none of them could fit the N=24 case exactly, so I went with one that had 0 c and hardcoded the value for N=24.

For lower N, from 1 to 7, I was hoping to find some simpler expression or polynomial, but couldn't find any that fit. So back to fitting \$ a * e^{b K} + c \$ , this time for K = 1 to 7 (though I didn't really think an exponential would be a right fit in this case, based on visual plot trends). Thankfully, there were parameters a, b, c that could give correct values throughout the range here (at least to within a ceil call).


Sequence Without Sevens This challenge is based on a drinking game. I advise against alcohol consumption while programming.

In this game, the players count up in turns: the first player says 1, the second says 2 and so on. Here's the twist however: each number that is divisible by 7 or has a 7 in its digits (in base 10) is replaced by another counter. This means 7 is replaced by 1, 14 is replaced by 2, 17 is replaced by 3 and so on. For this "sub-sequence", the same rules apply! 35 would be replaced by 7, which in turn is replaced by 1. This process repeats until the number is "valid".

Here's a visualization of the first 100 numbers in the sequence:

n = 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
gets replaced by:
                1                  2        3           4                 5  6                    7     8              9             10    11                   12 13                14          15       16 17 18 19 20 21 22 23 24 25             26       27          28                29 30
gets replaced by:
                                                                                1                                                                                2                       3           4                                   5           6

final sequence:
    1 2 3 4 5 6 1 8 9 10 11 12 13  2 15 16  3 18 19 20  4 22 23 24 25 26  5  6 29 30 31 32 33 34  1 36  8 38 39 40 41  9 43 44 45 46 10 48 11 50 51 52 53 54 55 12 13 58 59 60 61 62  2 64 65 66 15 68 69 16  3 18 19 20  4 22 23 24 25 80 81 82 83 26 85 86  5 88 89 90  6 92 93 94 95 96 29 30 99 100

In the final sequence, no number has a seven in its digits or is divisible by seven.

Input description

An integer n (1 <= n <= 7777 or 0 <= n <= 7776)

You may choose whether you use a 0-indexed or 1-indexed input.

Output description

The nth number in the sequence

Examples

The examples are 1-indexed. For 0-indexed, subtract one from n.

n   ->   f(n)
1        1
5        5
7        1
35       1
77       23
119      1
278      86
2254     822
2255     2255
7777     3403

Scoring

This is code-golf, so shortest answer in bytes wins!

Java, 122 121 98 97 bytes

int c(int n){int a=0,b=0,c=n;for(;n-->0;c+=a=((--b+"").indexOf(55)&b%7)>>31);return a<0?-b:c(c);}

-23 bytes thanks to @Nevay.
-1 byte thanks to @Neil.
Explanation:
Try it here.
int c(int n){                            // Method with integer as parameter and return-type
  int a=0,                               //  Flag integer
      b=0,                               //  Regular counter
      c=n;                               //  7-counter
  for(;n-->0;                            //  Loop over the input
    c+=                                  //   Append `c` with:
       a=                                //    Set `a` to:
         ((--b+"").indexOf(55)&b&7)      //     If `b` is divisible by or contains 7:
                                         //     (and decrease `b` by 1 in the process)
                                   >>31  //      Bitwise right shift so `a` is either `-1` or `0`
  );                                     //  End of loop
  return a<0?                            //  If `a` is now -1:
    -b                                   //   Return the regular counter `b` (as positive)
   :                                     //  Else:
    c(c);                                //   Recursive call with 7-counter `c` as input
}                                        // End of method


Resolve quadratic equation Challenge:

Write the smallest program (in characters) that resolves quadratic equations
i.e. ax² + bx + c = 0

Rules:

Given 3 numbers in R comma-delimited on STDIN: a,b,c (a != 0),
print on STDOUT the 2 roots in C, one per line.

R stands for real numbers, C for complex numbers.

Examples:

Input         Output

1,0,0         r1=0     also accepted: r1=(-0-sqrt(0))/2
              r2=0

1,2,1         r1=-1    also accepted: r1=(-2-sqrt(0))/2
              r2=-1

1,1,1         r1=(-1-isqrt(3))/2  also accepted: r1=(-1-sqrt(-3))/2 or r1=-0.5-0.866i
              r2=(-1+isqrt(3))/2

R, 19 chars

polyroot(scan(n=3))

or more strictly following the I/O requirements in 58 chars:

r=polyroot(rev(scan(sep=",")));cat("r1=",r[1],"\nr2=",r[2])

edit: reversed coefficients


Calculate the Kronecker sum of two matrices In the examples below, A and B will be 2-by-2 matrices, and the matrices are one-indexed.

A Kronecker product has the following properties:

A⊗B =  A(1,1)*B   A(1,2)*B
        A(2,1)*B   A(2,2)*B

     =  A(1,1)*B(1,1)   A(1,1)*B(1,2)   A(1,2)*B(1,1)   A(1,2)*B(1,2)
        A(1,1)*B(2,1)   A(1,1)*B(2,2)   A(1,2)*B(2,1)   A(1,2)*B(2,2)
        A(2,1)*B(1,1)   A(2,1)*B(1,2)   A(2,2)*B(1,1)   A(2,2)*B(1,2)
        A(2,2)*B(2,1)   A(2,2)*B(1,2)   A(2,2)*B(2,1)   A(2,2)*B(2,2)

A Kronecker sum has the following properties:

A⊕B = A⊗Ib + Ia⊗B

Ia and Ib are the identity matrices with the dimensions of A and B respectively. A and B are square matrices. Note that A and B can be of different sizes.

A⊕B =  A(1,1)+B(1,1)  B(1,2)         A(1,2)         0
        B(2,1)         A(1,1)+B(2,2)  0              A(1,2)
        A(2,1)         0              A(2,2)+B(1,1)  B(1,2)
        0              A(2,1)         B(2,1)         A(2,2)+B(2,2)

Given two square matrices, A and B, calculate the Kronecker sum of the two matrices.

The size of the matrices will be at least 2-by-2. The maximum size will be whatever your computer / language can handle by default, but minimum 5-by-5 input (5 MB output).
All input values will be non-negative integers
Builtin functions that calculate the Kronecker sum or Kronecker products are not allowed
In general: Standard rules regarding I/O format, program & functions, loopholes etc.

Test cases:

A =
     1     2
     3     4
B =
     5    10
     7     9

A⊕B =
     6    10     2     0
     7    10     0     2
     3     0     9    10
     0     3     7    13

----

A =
    28    83    96
     5    70     4
    10    32    44
B =
    39    19    65
    77    49    71
    80    45    76

A⊕B =
    67    19    65    83     0     0    96     0     0
    77    77    71     0    83     0     0    96     0
    80    45   104     0     0    83     0     0    96
     5     0     0   109    19    65     4     0     0
     0     5     0    77   119    71     0     4     0
     0     0     5    80    45   146     0     0     4
    10     0     0    32     0     0    83    19    65
     0    10     0     0    32     0    77    93    71
     0     0    10     0     0    32    80    45   120

----

A =
    76    57    54
    76     8    78
    39     6    94
B =
    59    92
    55    29

A⊕B =
   135    92    57     0    54     0
    55   105     0    57     0    54
    76     0    67    92    78     0
     0    76    55    37     0    78
    39     0     6     0   153    92
     0    39     0     6    55   123

CJam, 40 39 38 bytes

9Yb2/q~f{.{_,,_ff=?}:ffff*::.+:~}:..+p

Input format is a list containing A and B as 2D lists, e.g.

[[[1 2] [3 4]] [[5 10] [7 9]]]

Output format is a single CJam-style 2D list.

Test suite. (With more readable output format.)

Explanation

This code is an exercise in compound (or infix) operators. These are generally useful for array manipulation, but this challenge exacerbated the need for them. Here is a quick overview:

f expects a list and something else on the stack and maps the following binary operator over the list, passing in the other element as the second argument. E.g. [1 2 3] 2 f* and 2 [1 2 3] f* both give [2 4 6]. If both elements are lists, the first one is mapped over and the second one is used to curry the binary operator.
: has two uses: if the operator following it is unary, this is a simple map. E.g. [1 0 -1 4 -3] :z is [1 0 1 4 3], where z gets the modulus of a number. If the operator following it is binary, this will fold the operator instead. E.g. [1 2 3 4] :+ is 10.
. vectorises a binary operator. It expects two lists as arguments and applies the operator to corresponding pairs. E.g. [1 2 3] [5 7 11] .* gives [5 14 33].

Note that : itself is always a unary operator, whereas f and . themselves are always binary operators. These can be arbitrarily nested (provided they have the right arities). And that's what we'll do...

9Yb      e# Push the binary representation of 9, i.e. [1 0 0 1].
2/       e# Split into pairs, i.e. [[1 0] [0 1]]. We'll use these to indicate
         e# which of the two inputs we turn into an identity matrix.
q~       e# Read and evaluate input, [A B].
f{       e# This block is mapped over the [[1 0] [0 1]] list, also pushing
         e# [A B] onto the stack for each iteration.
  .{     e#   The stack has either [1 0] [A B] or [0 1] [A B]. We apply this
         e#   block to corresponding pairs, e.g. 1 A and 0 B.
    _,   e#     Duplicate the matrix and get its length/height N.
    ,_   e#     Turn into a range [0 1 ... N-1] and duplicate it.
    ff=  e#     Double f on two lists is an interesting idiom to compute an
         e#     outer product: the first f means that we map over the first list
         e#     with the second list as an additional parameter. That means for
         e#     the remaining operator the two arguments are a single integer
         e#     and a list. The second f then maps over the second list, passing
         e#     in the the number from the outer map as the first parameter.
         e#     That means the operator following ff is applied to every possible
         e#     pair of values in the two lists, neatly laid out in a 2D list.
         e#     The operator we're applying is an equality check, which is 1
         e#     only along the diagonal and 0 everywhere else. That is, we've
         e#     created an NxN identity matrix.
    ?    e#     Depending on whether the integer we've got along with the matrix
         e#     is 0 or 1, either pick the original matrix or the identity.
  }
         e#   At this point, the stack contains either [A Ib] or [Ia B].
         e#   Note that A, B, Ia and Ib are all 2D matrices.
         e#   We now want to compute the Kronecker product of this pair.
  :ffff* e#   The ffff* is the important step for the Kronecker product (but
         e#   not the whole story). It's an operator which takes two matrices
         e#   and replaces each cell of the first matrix with the second matrix
         e#   multiplied by that cell (so yeah, we'll end up with a 4D list of
         e#   matrices nested inside a matrix).
         e#   The leading : is a fold operation, but it's a bit of a degenerate
         e#   fold operation that is only used to apply the following binary operator
         e#   to the two elements of a list.
         e#   Now the ffff* works essentially the same as the ff= above, but
         e#   we have to deal with two more dimensions now. The first ff maps
         e#   over the cells of the first matrix, passing in the second matrix
         e#   as an additional argument. The second ff then maps over the second
         e#   matrix, passing in the cell from the outer map. We multiply them
         e#   with *.
         e#   Just to recap, we've essentially got the Kronecker product on the
         e#   stack now, but it's still a 4D list not a 2D list.
         e#   The four dimensions are:
         e#     1. Columns of the outer matrix.
         e#     2. Rows of the outer matrix.
         e#     3. Columns of the submatrices.
         e#     4. Rows of the submatrices.
         e#   We need to unravel that into a plain 2D matrix.
  ::.+   e#   This joins the rows of submatrices across columns of the outer matrix.
         e#   It might be easiest to read this from the right:
         e#     +    Takes two rows and concatenates them.
         e#     .+   Takes two matrices and concatenates corresponding rows.
         e#     :.+  Takes a list of matrices and folds .+ over them, thereby
         e#          concatenating the corresponding rows of all matrices.
         e#     ::.+ Maps this fold operation over the rows of the outer matrix.
         e#   We're almost done now, we just need to flatten the outer-most level
         e#   in order to get rid of the distinction of rows of the outer matrix.
  :~     e#   We do this by mapping ~ over those rows, which simply unwraps them.
}
         e# Phew: we've now got a list containing the two Kronecker products
         e# on the stack. The rest is easy, just perform pairwise addition.
:..+     e# Again, the : is a degenerate fold which is used to apply a binary
         e# operation to the two list elements. The ..+ then simply vectorises
         e# addition twice, such that we add corresponding cells of the 2D matrices.
p        e# All done, just pretty-print the matrix.


string length comparer this program has to take two strings and compare their length, then tell you which one is longer (string-a or string-b) and by how much

rules:

no using .length or other built-in length checking methods (duh!)
no using addition or subtraction, this includes improvised addition/subtraction, in case you find some sort of weird improvisation.
no > / < (greater then/less then) inside if / if-else statements (you can use them in loops though), this obviously includes >= etc. and no cheating (bool = a > b;if(bool))
emphasis is on short rather then efficient code
oh yeah almost forgot... good luck!

SED, 45 (43 + 2 for the -n flag)

s/./a/g
h
n
s/./b/g
G
:a
s/b\(.*\)a/\1/
ta

Expects input as two separate lines, outputs the difference in unary, using "a" or "b" to indicate the longer string. run with sed -n.


Reverse a Rubik's Cube Algorithm Whenever you make a move on a Rubik's Cube, there is a reverse move which undoes the first move. Because of this, every algorithm (set of moves) has a reverse algorithm which undoes the first algorithm.
The goal of this challenge is to find the reverse of a given algorithm.
Specification:
The input consists of an array of individual moves. Each move is a string of length 1 or 2. Of course, you can use whatever input format makes the most sense in your language. Each move consists of the structure X or X' or X2, where X is an uppercase or lowercase letter.
To reverse X, simply replace it with X'. Likewise, X' becomes X. X2 on the other hand does not get changed.
To create the output, reverse each move, and then reverse the array.
Examples (strings separated by spaces):
R => R'
D U' => U D'
S T A C K => K' C' A' T' S'
A2 B2 => B2 A2
Scoring:
This is code-golf, so the fewest amount of bytes win. Standard loopholes are not allowed.

Python 2, 71 57 54 53 bytes

-15 bytes thanks to ovs! -3 bytes thanks to Rod.

lambda l:[i.strip("'")+" '"[len(i):]for i in l[::-1]]

Try it online!

String I/O, 70 bytes

lambda s:' '.join(i.strip("'")+"'"*(len(i)<2)for i in s.split()[::-1])

Try it online!


Compress an image to a 4 KiB preview In this challenge you will be creating an image preview compression algorithm. It's goal is to
reduce an arbitrary image file to a 4 KiB preview image, that can be used to quickly identify images
with very little bandwidth.

You must write two programs (or one combined program): a compressor and a decompressor. Both must
take a file or stdin as input, and output to a file or stdout. The compressor must accept one image
in a mainstream lossless image format of choice (e.g. PNG, BMP, PPM), and output a file of at
most 4096 bytes. The decompressor must accept any file generated by the compressor, and output an image as close as possible to the input. Note that there is no source code size limit for the encoder/decoder, so you
can be creative in your algorithm.

Restrictions:

No 'cheating'. Your programs may not use hidden inputs, storing data on the internet, etc. You are
also forbidden from including features / data pertaining only to the set of scoring images.
For libraries / tools / built-ins you are allowed to use generic image processing operations
(scaling, blurring, color space transformation, etc), but not image decoding / encoding /
compression operations (except for compressor input and decompressor output). Generic compression / decompression is also disallowed. It is intended
that you implement your own compression for this challenge.
The dimensions of the image output by the decompressor must exactly match those of the original
file given to the compressor. You may assume that the image dimensions do not exceed
216 in either direction.
Your compressor must run on an average consumer PC in under 5 minutes, and the decompressor must
run in under 10 seconds for any image in the set below.

Scoring

To help quick verification and visual comparison, please include a lossless image album of the test corpus after compression using your answer.

Your compressor will be tested using the following corpus of images:

You can download all images in a zip file here.

Your score will be the average structural similarity index for your compressor on all the images. We will be using the open source dssim for this challenge. It is easily built from source, or if you're on Ubuntu it also has a PPA. It is preferred if you score your own answer, but if you do not know how to build C applications and you do not run Debian/Ubuntu, you can let someone else score for you. dssim expects input/output in PNG, so convert your output to PNG first if you output in a different format.

To make scoring painless, here's a quick helper Python script, usage python score.py corpus_dir compressed_dir:

import glob, sys, os, subprocess

scores = []
for img in sorted(os.listdir(sys.argv[1])):
    ref, preview = (os.path.join(sys.argv[i], img) for i in (1, 2))
    sys.stdout.write("Comparing {} to {}... ".format(ref, preview))
    out = subprocess.check_output(["dssim", ref, preview]).decode("utf-8").split()[0]
    print(out)
    scores.append(float(out))

print("Average score: {:.6f}".format(sum(scores) / len(scores)))

Lowest score wins.

Python with PIL, score 0.094218

Compressor:
#!/usr/bin/env python
from __future__ import division
import sys, traceback, os
from PIL import Image
from fractions import Fraction
import time, io

def image_bytes(img, scale):
    w,h = [int(dim*scale) for dim in img.size]
    bio = io.BytesIO()
    img.resize((w,h), Image.LANCZOS).save(bio, format='PPM')
    return len(bio.getvalue())

def compress(img):
    w,h = img.size
    w1,w2 = w // 256, w % 256
    h1,h2 = h // 256, h % 256
    n = w*h
    total_size = 4*1024 - 8 #4 KiB minus 8 bytes for
                            # original and new sizes
    #beginning guess for the optimal scaling
    scale = Fraction(total_size, image_bytes(img, 1))
    #now we do a binary search for the optimal dimensions,
    # with the restriction that we maintain the scale factor
    low,high = Fraction(0),Fraction(1)
    best = None
    start_time = time.time()
    iter_count = 0
    while iter_count < 100: #scientifically chosen, not arbitrary at all
        #make sure we don't take longer than 5 minutes for the whole program
        #10 seconds is more than reasonable for the loading/saving
        if time.time() - start_time >= 5*60-10:
            break
        size = image_bytes(img, scale)
        if size > total_size:
            high = scale
        elif size < total_size:
            low = scale
            if best is None or total_size-size < best[1]:
                best = (scale, total_size-size)
        else:
            break
        scale = (low+high)/2
        iter_count += 1
    w_new, h_new = [int(dim*best[0]) for dim in (w,h)]
    wn1,wn2 = w_new // 256, w_new % 256
    hn1, hn2 = h_new // 256, h_new % 256
    i_new = img.resize((w_new, h_new), Image.LANCZOS)
    bio = io.BytesIO()
    i_new.save(bio, format='PPM')
    return ''.join(map(chr, (w1,w2,h1,h2,wn1,wn2,hn1,hn2))) + bio.getvalue()

if __name__ == '__main__':
    for f in sorted(os.listdir(sys.argv[1])):
        try:
            print("Compressing {}".format(f))
            with Image.open(os.path.join(sys.argv[1],f)) as img:
                with open(os.path.join(sys.argv[2], f), 'wb') as out:
                    out.write(compress(img.convert(mode='RGB')))
        except:
            print("Exception with {}".format(f))
            traceback.print_exc()
            continue

Decompressor:
#!/usr/bin/env python
from __future__ import division
import sys, traceback, os
from PIL import Image
from fractions import Fraction
import io

def process_rect(rect):
    return rect

def decompress(compressed):
    w1,w2,h1,h2,wn1,wn2,hn1,hn2 = map(ord, compressed[:8])
    w,h = (w1*256+w2, h1*256+h2)
    wc, hc = (wn1*256+wn2, hn1*256+hn2)
    img_bytes = compressed[8:]
    bio = io.BytesIO(img_bytes)
    img = Image.open(bio)
    return img.resize((w,h), Image.LANCZOS)

if __name__ == '__main__':
    for f in sorted(os.listdir(sys.argv[1])):
        try:
            print("Decompressing {}".format(f))
            with open(os.path.join(sys.argv[1],f), 'rb') as img:
                decompress(img.read()).save(os.path.join(sys.argv[2],f))
        except:
            print("Exception with {}".format(f))
            traceback.print_exc()
            continue

Both scripts take input via command line arguments, as two directories (input and output), and convert all images in the input directory.
The idea is to find a size that fits under 4 KiB and has the same aspect ratio as the original, and use a Lanczos filter to get as high of a quality out of the downsampled image as possible.
Imgur album of compressed images, after resizing to original dimensions
Scoring script output:
Comparing corpus/1 - starry.png to test/1 - starry.png... 0.159444
Comparing corpus/2 - source.png to test/2 - source.png... 0.103666
Comparing corpus/3 - room.png to test/3 - room.png... 0.065547
Comparing corpus/4 - rainbow.png to test/4 - rainbow.png... 0.001020
Comparing corpus/5 - margin.png to test/5 - margin.png... 0.282746
Comparing corpus/6 - llama.png to test/6 - llama.png... 0.057997
Comparing corpus/7 - kid.png to test/7 - kid.png... 0.061476
Comparing corpus/8 - julia.png to test/8 - julia.png... 0.021848
Average score: 0.094218


APL, 87

t[3]←(1+3⌷t←137 91 4 100⊤⍎2⍕⎕÷864)⌷'Looplab' 'Sevit' 'Hexteria' 'Sinpad'
'  '⎕R'-'⍕t

APL has an advantage in these time system conversion challenges due to the built-in encode function, at the cost of expensive string manipuation

Explanation
(using 1357510372 as example)

⎕÷864 takes user input from screen, divide by 864 (1571192.56018519)
⍎2⍕ and round to 2 dp.  (1571192.56)
137 91 4 100⊤ Then, converts to Noxu Time System (43 14 3 92.56)
t← and assign that to variable t.
1+3⌷ take the 3rd item from t, add 1 to account for 1-based indexing, (4)
(...)⌷'Looplab' 'Sevit' 'Hexteria' 'Sinpad' convert to Skizzle name, (Sinpad)
t[3]← and finally plug back into the 3rd item of t.

⍕t Convert t to a string representation, (43 14  Sinpad  92.56)
'  '⎕R'-' and replaces 2 spaces with a dash (43 14-Sinpad-92.56)


Code Johnny Code, Code! Rock-and-roll founding father Chuck Berry sadly passed away today.
Consider the chorus of his famous song "Johnny B. Goode":
Go, go
Go Johnny go, go
Go Johnny go, go
Go Johnny go, go
Go Johnny go, go
Johnny B. Goode

(There are other ways it has been punctuated but the above will serve for the purposes of the challenge.)
Challenge
Given a nonempty, lowercase string of letters a-z, output the chorus of "Johnny B. Goode" with all the instances of Go or go replaced with the input string, capitalized in the same way.
A trailing newline may optionally follow. Nothing else in the chorus should change.

For example, if the input is code the output must be exactly
Code, code
Code Johnny code, code
Code Johnny code, code
Code Johnny code, code
Code Johnny code, code
Johnny B. Codeode

optionally followed by a newline.

Note that the capitalization of all words matches the original chorus, and (despite lack of rhythm) the Go in Goode is replaced as well as the individual words Go and go.
The shortest code in bytes wins.
Test Cases
"input"
output

"go"
Go, go
Go Johnny go, go
Go Johnny go, go
Go Johnny go, go
Go Johnny go, go
Johnny B. Goode

"code"
Code, code
Code Johnny code, code
Code Johnny code, code
Code Johnny code, code
Code Johnny code, code
Johnny B. Codeode

"a"
A, a
A Johnny a, a
A Johnny a, a
A Johnny a, a
A Johnny a, a
Johnny B. Aode

"johnny"
Johnny, johnny
Johnny Johnny johnny, johnny
Johnny Johnny johnny, johnny
Johnny Johnny johnny, johnny
Johnny Johnny johnny, johnny
Johnny B. Johnnyode

"fantastic"
Fantastic, fantastic
Fantastic Johnny fantastic, fantastic
Fantastic Johnny fantastic, fantastic
Fantastic Johnny fantastic, fantastic
Fantastic Johnny fantastic, fantastic
Johnny B. Fantasticode

Go, 123 bytes

Go Johnny, Go!

Try it online!

import."strings"
func(s string)string{t,e:=Title(s),", "+s+"\n";return t+e+Repeat(t+" Johnny "+s+e,4)+"Johnny B. "+t+"ode"}


Sort an array only using recursion Your task is to write a function that sorts an array.

Your function:

Cannot call other functions (excluding itself, of course);
Must receive an array of integers as input, and it must return the ordered array. Feel free to add other parameters as input, if you need them.
Cannot use any kind of loop (for, while...) except recursion;
Cannot access the internet;
Can be overloaded if you need it.

Code-Golf here. Shortest code wins, as usual.

Happy coding!

APL (36)

{⍵≡⍬:⍬⋄(∇z/m),p,∇m/⍨~z←(p←⊃⍵)≥m←1↓⍵}

It's quicksort:

⍵≡⍬: if the list is equal to the empty list
:⍬: then return the empty list
⋄: otherwise:

m←1↓⍵: m is the list minus its first element
p←⊃⍵: p (pivot) is the first element
z←(p←⊃⍵)≥m: z is a bitmask of those values of m that are smaller than p.
∇m/⍨~z select the inverse of z from m (= larger numbers) , and sort it recursively
p,: pivot
∇z/m: select z from m (= smaller or equal numbers) and sort it recursively


The ultimate inequality challenge Task

Given two positive integers a, b and a Unicode mathematical inequality symbol c, determine if a c b is true.

You many take the character or its Unicode codepoint for the input c. You may output your language's truthy/falsy values, or two distinct values for true and false respectively.

Standard code-golf rules apply. The shortest code in bytes wins.

List of symbols to support

Symbol  |  Hex   |  Dec   |  Name
--------+--------+--------+-------------
<       |  003C  |  60    |  Less than
=       |  003D  |  61    |  Equal to
>       |  003E  |  62    |  Greater than
≠       |  2260  |  8800  |  Not equal to
≤       |  2264  |  8804  |  Less than or equal to
≥       |  2265  |  8805  |  Greater than or equal to
≮       |  226E  |  8814  |  Not less than
≯       |  226F  |  8815  |  Not greater than
≰       |  2270  |  8816  |  Neither less than nor equal to
≱       |  2271  |  8817  |  Neither greater than nor equal to

The last four symbols may look broken in Chrome. They are four symbols <>≤≥ with slash overstrike, indicating negation.

Truthy test cases

1 < 2
1 = 1
2 > 1
1 ≠ 2
2 ≠ 1
1 ≤ 1
1 ≤ 2
2 ≥ 1
1 ≥ 1
2 ≮ 1
1 ≮ 1
1 ≯ 1
1 ≯ 2
2 ≰ 1
1 ≱ 2

Falsy test cases

1 < 1
2 < 1
1 = 2
2 = 1
1 > 1
1 > 2
1 ≠ 1
2 ≤ 1
1 ≥ 2
1 ≮ 2
2 ≯ 1
1 ≰ 1
1 ≰ 2
2 ≱ 1
1 ≱ 1

JavaScript (ES6),  58 45  42 bytes
Saved 3 bytes thanks to @Neil
Expects the Unicode code point for \$c\$. Returns \$0\$ or \$1\$.
(a,c,b)=>'14353426'[c%61%9]>>(a>b?2:b>a)&1

Try it online!
How?
Each comparison character is assigned a 3-bit mask describing if it should be truthy for a > b, a < b or a == b.
 char. | code | meaning                           | > | < | = | mask
-------+------+-----------------------------------+---+---+---+------
   <   |   60 | Less than                         | 0 | 1 | 0 |  2
   =   |   61 | Equal to                          | 0 | 0 | 1 |  1
   >   |   62 | Greater than                      | 1 | 0 | 0 |  4
   ≠   | 8800 | Not equal to                      | 1 | 1 | 0 |  6
   ≤   | 8804 | Less than or equal to             | 0 | 1 | 1 |  3
   ≥   | 8805 | Greater than or equal to          | 1 | 0 | 1 |  5
   ≮   | 8814 | Not less than                     | 1 | 0 | 1 |  5
   ≯   | 8815 | Not greater than                  | 0 | 1 | 1 |  3
   ≰   | 8816 | Neither less than nor equal to    | 1 | 0 | 0 |  4
   ≱   | 8817 | Neither greater than nor equal to | 0 | 1 | 0 |  2

We store these masks in a 8-character lookup string whose index is computed by applying two consecutive modulos to the code point:
 code | mod 61 | mod 9 | mask
------+--------+-------+------
   60 |   60   |   6   |  2
   61 |    0   |   0   |  1
   62 |    1   |   1   |  4
 8800 |   16   |   7   |  6
 8804 |   20   |   2   |  3
 8805 |   21   |   3   |  5
 8814 |   30   |   3   |  5
 8815 |   31   |   4   |  3
 8816 |   32   |   5   |  4
 8817 |   33   |   6   |  2


Tips for golfing in Subleq Subleq is a programming language with only one instruction. Each instruction contains 3 parameters. Code and data space is the same. How it works:

A B C

A, B and C are signed ints. Instructions are executed in the next way:

*B = *B - *A
if(*B <= 0) goto C;

One post is one tip. Write your tips for Subleq here!

Online interpreter, assembler and C to Subleq converter

Third Argument in Output Command is Extra Memory
Subleq specifies output with the three word command x -1 y, where x is the address of the value to be output. Unlike other Subleq commands, execution will proceed to the next command in all cases and y is ignored.  This means it is available to be used for memory.
For example 0:2 -1 65 will print the "A" (CHAR(65)) stored in 2: and then proceed to 3:.


Output ISO8601 date string from seconds and nanoseconds One reason why ISO8601 is the best date string format, is that you can simply append as much precision as you like. Given 2 integers representing seconds and nanoseconds that have passed since 1970-01-01T00:00:00, return an ISO8601 string as described below.
Output:
The standard output format without timezone looks like this:
1970-01-01T00:00:00.000001
The date is encoded as "year, month,day" with 4,2,2 digits respectively, separated by a "-". The time of day is encoded as "hour, minute, seconds" with 2,2,2 digits respectively. Then, optionally a dot with exactly 6 digits of precision can follow, encoding microseconds that have passed after the given date+(time in hours+minutes+seconds) since. This is only appended if it'd be not equal to 000000. See examples below
Yes, we are allowed to append 6 digits(microseconds) of precision and theoretically more are simply appendable,  though not defined further in the standard.
Input:
You'll get 2 integers(seconds, nanoseconds). For the sake of simplicity, let's constrain them to be within 0 <= x < 10^9 both. Make sure to discard/round down any precision beyond microseconds.
Examples:
Input: 616166982 , 34699909     Output: 1989-07-11T13:29:42.034699
Input: 982773555 , 886139278    Output: 2001-02-21T16:39:15.886139
Input: 885454423 , 561869693    Output: 1998-01-22T07:33:43.561869
Input: 0         , 100000       Output: 1970-01-01T00:00:00.000100
Input: 0         , 1000         Output: 1970-01-01T00:00:00.000001
Input: 0         , 999          Output: 1970-01-01T00:00:00
Input: 999999999 , 999999999    Output: 2001-09-09T01:46:39.999999

Task:
Provide a function that takes in 2 integers as described in the Input section and returns a String as described in the Output section.
For details and limitations for input/output please refer to the default input/output rules.
This is codegolf: Shortest solution in bytes wins.

Bash + sed, 37, 59, 50 bytes

printf '%(%FT%T)T.%06d' $1 $[$2/1000]

printf "%(%FT%T)T.%06d" $1 ${2::-3}|sed s/\\.0*$//

Try it online!
8 bytes saved thanks to @DigitalTrauma


Find a binary tree's deepest node Write a program that takes a binary tree as input, and outputs the deepest node and its depth. If there is a tie, print all involved nodes as well as their depths. Each node is represented as:

T(x,x)

T(x)

T

where T is the identifier of one or more alphanumeric characters and each x is another node.

Here's a simple definition of a binary tree:

At the head of a binary tree is a node.
A node in a binary tree has at most two children.

For example, the input A(B(C,D(E))) (below) would output 3:E.

While the following tree is a three-way tie between 5, 11, and 4, and their depth is also 3 (starting from 0):

The input 2(7(2,6(5,11)),5(9(4))) (below) would output 3:5,11,4.

This is code golf, so the shortest code measured in bytes wins.

CJam, 49 47

0q')/{'(/):U;,+:TW>{T:W];}*TW={U]',*}*T(}/;W':@

0                 " Push 0 ";
q                 " Read the whole input ";
')/               " Split the input by ')' ";
{                 " For each item ";
  '(/             " Split by '(' ";
  )               " Extract the last item of the array ";
  :U;             " Assign the result to U, and discard it ";
  ,               " Get the array length ";
  +               " Add the top two items of the stack, which are the array length and the number initialized to 0 ";
  :T              " Assign the result to T ";
  W>{             " If T>W, while W is always initialized to -1 ";
    T:W];         " Set T to W, and empty the stack ";
  }*
  TW={            " If T==W ";
    U]',*         " Push U and add a ',' between everything in the stack, if there were more than one ";
  }*
  T(              " Push T and decrease by one ";
}/
;                 " Discard the top item, which should be now -1 ";
W                 " Push W ";
':                " Push ':' ";
@                 " Rotate the 3rd item to the top ";


Help me procrastinate on my computer repairs! This challenge is brought to you by real (and tragic) inspiration. Recently, the number row on my keyboard has been a bit sporadic. The keys 1-9 work sometimes--but other times they have no result. As an avid programmer, this is horrible! (See that exclamation point? That's how you know they're working right now.) Not only do I often need the numbers themselves, but the symbols !@#$%^&*( are completely ineffective half the time as well! As a C programmer, rather than take time off my busy schedule of doodling around with code to fix my laptop, I've been more interested in working around the problem. Over the course of the past few weeks, slowly, all of the number literals in my code have been replaced with hexadecimal so that I don't have to go hunting around for numbers to copy and paste. However, some numbers aren't easy to type without the keys 1-9. For example, the number 1 cannot be written so simply in hexadecimal, and I've resorted to replacing 1s in my code with 0xF - 0xE. The only keys that are affected are 1-9, so I maintain full use of symbols like +, -, and /. However, I cannot use multiplication or parentheses, as * and ( are often broken. This leads to your challenge.

Input

An integer, n to stdin or your language's equivalent. If you wish, the integer may be preceded or followed by a new line or other whitespace character. Alternatively, you may receive input via a command line argument.

Your program should respond to negative input correctly, and be able to handle at least 32-bit signed integers.

Output

Your program should output, in some observable form, the shortest (in non-whitespace characters) possible way to write the number n as a sum, difference, or division of one or more hexadecimal values. There is more than one way to solve this problem, and there is no requirement that you favor any equal-length output over any other.

The output should be in the form A % A % A... where A is a hexadecimal value following 0x containing only digits A-F a-f, and % is one of of the symbols -+/. Let / describe integer division, not floating-point.

(Note that your output should result in n when evaluating divisions first, left to right, and then additions and subtractions, left to right, as is convention.)

Test Cases

Input Output

1

0xF - 0xE (or 0xF-0xE or 0xB-0xA or 0xd - 0xc or 0xF/0xF)
15

0xF
255

0xFF
30

0xF + 0xF

Scoring and Rules

This is code-golf. Your preliminary score is the number of bytes in your source file.

You may NOT use any of the digits 1-9 in your source.

You MAY use symbols !@#$%^&*( in your source, but each comes at a penalty of +20 to your score.

Your program may be replaced by a function that takes n as an argument as long as that function produces some form of human-readable output. Your function's return value does NOT count as output.

Standard loopholes are not allowed.

Lowest score wins! Good luck!

Did I goof something up formatting/questioning/clarity-wise? Let me know! This is my first submission to this site!

JavaScript 287 (187+20*5) 295 (195 +20*5) 338 (198 + 20*7)

A function that check every possible combinations of the 6 allowed hex digits (0xA to 0xF) and the 3 allowed operators.
Output via popup and not returning a value, as requested.

I used [] to group comma separated expression but could not avoid 5 7 open brackets for loops and function calling.
To avoid digits there are variables A,B,C for 1,2,3 (this makes the code even more obscure)

Edit code revised focusing on avoiding '('. Removed ifs and explicit RegExp creation

Beware: this function is incredibly slow, it will exceed the time limit for a script in FireFox, even for small input like 90.

To enumerate all the possible expression, I use number starting at 3 and going up forever.  Digits encoding:
  0,1,2 are the operators +,-,/
  4 to 9 are the hex digits A..F
  3 is not allowed
Each number is checked with a regexp /3|[0-2]{2}/ to avoid the digit 3 and having 2 consecutive operators (the check also avoid traling and leading operators - see code)

The resulting string is something like 0xA + 0xA - 0xD that is valid javascript, so I use eval to evaluate it. Unfortunatley the '/' operator is floating point and not integer in JavaScript, so I'm not 100% sure that the result are correct event casting to integer the final result (but I am quite confident, given that a small rounding error can not be amplified by a '*')

F=x=>{
  for(A=-~0,B=A+A,i=C=A+B,j=0;j?x-~~eval(L):A;)
  {
    j=++i+'0',k=0+j;
    for(c of~k.search(C+'|[0-'+B+']{'+B+'}',L='',w='0x')?j='':j)
      c>C?w+=' ABCDEF'[c-C]:[L+=w,w=' '+'+-/'[c]+' 0x']
  }
  alert(L)
}

Something else

Now, something funnier. I used an oversimplified expressione parser to avoid the eval call and, amusingly, that turned out to be a lot faster.

The parser is really simplified, in a real parser V and O should be arrays containing the pending values stack and the pending operators stack. Here V is the single pending value (and also the return value) and O is a string with at most 2 characters. P contains the operators precedence table, for '-+/' => '112'

This scores 275 + 4*20 => 355

F=x=>{
  for(A=-~0,B=A+A,i=C=A+B,D=A+C,j=0,P=''+A+A+B;j?x-V:A;)
  {
    j=++i+'0',k=0+j;
    for(c of~k.search(C+'|[0-'+B+']{'+B+'}',v=V=O=L='',w='0x')?j='':j)
      c>C?
        w+='ABCDEF'[v<<=D,v+=D+A-~c,c-D]
      :[
          P[O[0]]>=P[c]?[v=O>A?V/v|0:O>0?V+v:V-v,O=c]:O=c+O,
          L+=w,w=' '+'-+/'[c]+' 0x',V=v,v=0
      ]
  }
  alert(L)
}

Test In Firefox/FireBug console, change alert with return (a lot more usable)

;[0, 1, 15, 255, 30].forEach(x=>console.log(x,F(x)))

  0 0xA - 0xA
  1 0xA / 0xA
  15 0xF
  255 0xFF
  30 0xF + 0xF

Just a little less obvious (but be patient)

;[16,40, 51, 62, 73, 84, 95].forEach(x=>console.log(x,F(x)))

  16 0xBA / 0xB
  40 0xA + 0xF + 0xF
  51 0xDD - 0xAA
  62 0xEA - 0xAC
  73 0xA + 0xEA - 0xAB
  84 0xFE - 0xAA
  95 0xA + 0xFF - 0xAA


Simulate a Cyclic Tag System A cyclic tag system is a tiny, Turing-complete computational model consisting of a two-symbol alphabet (I'll use {0,1}), a finite, nonempty cyclic list of productions that consist of those two symbols, and an unbounded word which also consists of those two symbols.

At each step:

the first element in the word is removed
if it was 0 the current production is skipped
if it was 1 the current production is appended to the end of the word.
the next production becomes active. If this was the last production, go back to the first one.

The system halts when the word becomes empty.

An example (from Wikipedia):

Productions: (010, 000, 1111)
Initial word: 11001

Generation  Production   Word (before)            Word (after)
   0           010           11001             →     1001010
   1           000            1001010          →      001010000
   2           1111            001010000       →       01010000
   3           010              01010000       →        1010000
   4           000               1010000       →         010000000
   5           1111               010000000    →          10000000
   6           010                 10000000    →           0000000010
   7           000                  0000000010 →            000000010
   8           1111                  000000010 →             00000010
   9           010                    00000010 →              0000010

Your task, if you choose to accept it, is to write a program or function that takes:

a list of productions,
the initial word, and
a generation,

and prints or returns the word at that generation.

For example,

cyclic_tag(
      prod=[[0,1,0],[0,0,0],[1,1,1,1]],
      word=[1,1,0,0,1],
      gen=4) => [1,0,1,0,0,0,0]

Implementation details:

The alphabet does not matter. You may use 0 and 1, True and False, T and NIL, A and B, or even 1 and 0, or whatever else you may come up with, as long as you are consistent. All input and output must use the same alphabet, and you must indicate what you are using for 0 and what for 1.
The length of the word must be theoretically unbounded. That is, you may not hardcode a maximum word length. If I run your program on an ideal computer with an infinite amount of memory, your program must theoretically be able to make use of it. (You may ignore your interpreter's/compiler's limits.)
If the given system halts before the given generation is reached, you must return or print the empty word.
The empty production exists, and you must be able to handle it. If you write a full program, your I/O must also be able to handle it.

Edit: I had originally intended for generation 0 to be the input word itself, and generation 1 to be the result of the first step. I.e., I had intended for you to return the before column. However, as I have not been clear enough in stating this, I will accept both options; for each generation you may return the value in either the before or the after column. You must state that you are following the after column, if you are doing so. You must also be consistent in which column you choose.

I will award the smallest code a week from now (10/27/2014).

Haskell, 55 53 51
(t:w)%p|t=w++p|0<1=w
x%_=x
e w=(!!).scanl(%)w.cycle

this uses True as 1 and False as 0.
example run:
*Main> let t=True ; f=False
*Main> e [t,f,t] [[f,f,f],[t,t,t]] 4
[False,False,False,False,False]


How many Wazirs can be placed on an N×N Chessboard? Suppose a new fairy chess piece named the Wazir is introduced to chess. Wazirs can move from a position (x, y) to:
 (x+1, y)
 (x, y+1)
 (x-1, y)
 (x, y-1)
That is, they move orthogonally like the rook, but only one step at a time like the king. How many such wazirs can be placed on an N×N chessboard so that no two wazirs can attack each other?
 On a 1×1 board, there can be only 1 such piece.
 On a 2×2 board, there can be 2 such pieces.
 On a 3×3 board, there can be 5 such pieces.
Given N, return the number of wazirs that can be placed on an N×N chessboard.
This is OEIS sequence A000982.
More test cases
7 → 25
8 → 32
100 → 5000

Whitespace, 45 bytes

Try it online!

By the way, here is a proof that the ⌈n²/2⌉ formula is correct.

We can always place at least ⌈n²/2⌉ wazirs: just lay them out in a checkerboard pattern! Assuming the top-left tile is white, there are ⌈n²/2⌉ white tiles and ⌊n²/2⌋ black tiles on the n × n board. And if we place wazirs on the white tiles, no two of them are attacking each other, as every wazir only “sees” black tiles.

Here’s how we place 13 wazirs on a 5 × 5 board (each W is a wazir).

We can’t do any better: let’s arbitrarily tile the checkerboard with 2 × 1 domino pieces, optionally using a 1 × 1 piece for the final corner of an odd-length chessboard, like so:

We need ⌈n²/2⌉ dominoes to cover the chessboard. Clearly, putting two wazirs on one domino makes it so that they can attack one another! So each domino can only contain at most one wazir, meaning we can’t possibly place more than ⌈n²/2⌉ wazirs on the board.


All possible ways to interleave two strings I recently saw this question on stackoverflow. It's a great question, but there's one fatal problem with the question. They are asking for the best way to do it. E.g, easiest to read, most idiomatic, neatest etc. Don't they know that isn't what matters? You're supposed to ask about how to do it with the fewest bytes of code!

Since I doubt that question will be appreciated on stackoverflow, I decided to ask it here.

The challenge

You must write the shortest possible program or function that generates all possible ways to interleave any two arbitrary strings. For example, if the two strings are 'ab' and 'cd', the output is:

['abcd', 'acbd', 'acdb', 'cabd', 'cadb', 'cdab']

As you can see, a is always before b, and c is always before d.

IO can be in any reasonable format. Use this python code to verify to check your output. (credit: JeD)

def shuffle(s,t):
    if s=="":
        return [t]
    elif t=="":
        return [s]
    else:
        leftShuffle=[s[0]+val for val in shuffle(s[1:],t)]
        rightShuffle=[t[0]+val for val in shuffle(s,t[1:])]
        leftShuffle.extend(rightShuffle)
        return leftShuffle

Sample IO:

shuffle("$", "1234"):
['$1234', '1$234', '12$34', '123$4', '1234$']

shuffle("az", "by"):
['azby', 'abzy', 'abyz', 'bazy', 'bayz', 'byaz']

shuffle("code", "golf"):
['codegolf', 'codgeolf', 'codgoelf', 'codgolef', 'codgolfe', 'cogdeolf', 'cogdoelf',
'cogdolef', 'cogdolfe', 'cogodelf', 'cogodlef', 'cogodlfe', 'cogoldef', 'cogoldfe',
'cogolfde', 'cgodeolf', 'cgodoelf', 'cgodolef', 'cgodolfe', 'cgoodelf', 'cgoodlef',
'cgoodlfe', 'cgooldef', 'cgooldfe', 'cgoolfde', 'cgoodelf', 'cgoodlef', 'cgoodlfe',
'cgooldef', 'cgooldfe', 'cgoolfde', 'cgolodef', 'cgolodfe', 'cgolofde', 'cgolfode',
'gcodeolf', 'gcodoelf', 'gcodolef', 'gcodolfe', 'gcoodelf', 'gcoodlef', 'gcoodlfe',
'gcooldef', 'gcooldfe', 'gcoolfde', 'gcoodelf', 'gcoodlef', 'gcoodlfe', 'gcooldef',
'gcooldfe', 'gcoolfde', 'gcolodef', 'gcolodfe', 'gcolofde', 'gcolfode', 'gocodelf',
'gocodlef', 'gocodlfe', 'gocoldef', 'gocoldfe', 'gocolfde', 'goclodef', 'goclodfe',
'goclofde', 'goclfode', 'golcodef', 'golcodfe', 'golcofde', 'golcfode', 'golfcode']

As usual, standard loopholes apply, and the shortest answer in bytes wins. Since the question was originally about python, I'd love to see the shortest python answer. (And no, pyth is not python). However, answers in any language are encouraged.

Haskell, 53 48 bytes

a%""=[a]
a%b=[x:t|(x:y,z)<-[(a,b),(b,a)],t<-y%z]

Defines a function % for which a%b with strings a,b gives a list of strings.
Given two strings, we choose one of the two to take the first character from. We then recurse on the remainder of two strings, prepending that character to each result.
When one of the string is empty, the only possible result is the other string. ""%""=[""] would also suffice, but's it's longer.

53 bytes:
a@(b:c)%d@(e:f)=((b:)<$>c%d)++((e:)<$>a%f)
a%d=[a++d]

Defines a function % for which a%d with strings a,d gives a list of strings.
The function is defined recursively. If we take a character from the first string, then it must be prepended to each result of the recursive call on the remained of the first string with the second string. Symmetrically for the other string.
For the base case, if one of the strings is empty, the result is a single-element list of their concatenation. This is shorter than two cases for each string being empty.


Multiplication algorithm on a 4004 So I was playing around with this emulator of the Intel 4004 and decided I wanted to set a challenge for myself. The first use for the 4004 was in a calculator, so I decided  that I would try to code golf every operator on said calculator(addition, subtraction, multiplication, division, decimal points, and the square root) in hexadecimal. Now this was my first code golf challenge I ever set for myself, like ever, and I am relatively new at coding in general, but I thought it would be a fun thing to try out. This was the code for multiplication, specifically 3*4(In order to change it, simply replace the nybbles following the Ds[except for the 0] with any number you want as long as the product is below 16 and the second and third Ds have the same nybble trailing them):

 D4 B1 D3 B0 D3 B2 A0 82 B0 D0 B1 F8 F3 14 12 B1 40 06 B0 92 F3 E0

Are there any flaws in my 22-byte design, and is there a way to shorten the code?
For reference, the instruction set for the 4004 in binary is in this table: http://www.e4004.szyc.org/iset.html

4004 machine code, 12 bytes

This is the best code I could come up with using the same I/O as the provided code:

D4      LDM 4
B0      XCH R0
D3      LDM 3
F4      CMA
B1      XCH R1
D0      LDM 0
40 09   JUN TEST
        :LOOP
80      ADD R0
        :TEST
71 08   ISZ R1, LOOP
E0      WRM

If you omit the first 3 instructions and the last instruction then the inputs become R0 and the accumulator and the accumulator becomes the output.

Note that this does not handle overflow very well at all; you can add in a CLC to ensure that it at least calculates it correctly modulo 16, or in case the caller has left the carry set.


No strings (or numbers) attached If you like this, consider participating in:

The Official Dyalog APL 2016 Year Game
The monthly Dyalog APL 2017 Code Golf Challenge

Make 12 snippets/expressions, in the same language, that result in the numbers 0 through 10, and 42 respectively, but without writing any literal numeric, string, or character data.

Build-in data, like PI() and ALPHABET(), are fine, and so are e.g. CJam's U, X, Y, Z, and A constants, and Processing's BLEND, CHORD, CENTER, BREAK, and  LINES.

Every snippet must be able to stand on its own, i.e. they may not be interdependent. However, inside a single snippet, you may assign a variable and use it freely, as long as you refer to it directly by name, and not through a string containing its name.

All the snippets must be valid on the submitter’s computer at the time of submission (as reported by SE), but may not rely on unusual local conditions like number of files in a directory, the exact date or time, or specific input from the user.

Examples of valid snippets

3: INT(LOG10(YEAR(TODAY())))   because it remains true in the foreseeable future
4: CUBICROOT(LEN(CHARACTERSET()))   because a 256 letter character set is very common
8: SQRT(SYSTEMTYPE())   because 64-bit systems are very common

Examples of invalid snippets

5: LEN(USERNAME())   because most people do not use “Admin” as login :-)
9: LOG10(SYSTEMMEMORY())   because it only works on systems with exactly 1 GB of memory
42: CODE("*")   because it contains a string/character literal

The result of each snippet must result in an actual number (value, int, float, etc.) that can be used for further calculations using the same language as the snippet, i.e not a text string representing that number.

Only character based languages allowed.

Score is total byte count of all the 12 snippets combined. Newlines separating the snippets are not counted in.

Note that the above rules may prevent some languages from participating, even if they are Turing complete.

FAQ

Q Can the programs accept any input?
A Yes, but you may not just ask for input and enter the relevant number.

Q Are physical digits (non-data) digits allowed?
A Yes, e.g. LOG10().

Q Do Symbols in Ruby count as literals?
A Yes.

Q Does score include newlines between each snippet?
A No.

Q Is TI-BASIC "character based" enough to be valid?
A Yes.

Q Do false and true count as number literals?
A No, they are acceptable.

Q Can we use a number literal to call a function if that's the only way and the number doesn't influence the output of the function?
A Yes, if that is the normal way to write code in your language.

Q My language assumes there is a [something] at the start of each program/expression. Must I include it, or should my snippets just work if placed in the middle of a program/expression?
A They should just work in the middle of a program/expression.

Q What about regex literals?
A Forbidden, except for languages that only do regexes.

Q Is one piece of code that could print all the specified numbers acceptable?
A No, they have to be separate and mutually independent.

Q May I assume a boilerplate like int main() {}... or equivalent?
A Yes.

Q What output datatypes are allowed?
A Any numeric datatype, like int, float, etc.

Q Do I need to print the result of each snippet?
A No, making the result available for subsequent use is enough.

Q Are pre-set variables allowed?
A Yes, and they become reset (if changed) for every snippet.

Q Are π and e considered number literals?
A No, you may use them.

Q May I return 4 and 2 in different cells for 42?
A No, they must be connected as one number.

Q Bytes or characters?
A Bytes, but you may choose any desired codepage.

Q May constant functions and preset variables like J's 9:, Actually's 9, and Pretzel's 9 be used?
A Yes, if the vocabulary is finite (19 for J, 10 for Actually and Pretzel).

Funciton, 1222 bytes

Apart from numeric literals, there are two ways I can produce a value (any value at all) in Funciton: stdin and lambda expressions. Stdin is a single box while a full lambda expression requires more syntax, so I’m going with stdin. However, while stdin could be anything, all of the following work regardless of what input is provided.

All of the library functions used here existed before the challenge was posted.

0 (40 bytes in UTF-16)

╔╗┌┐
║╟┤└┼┬┐
╚╝└─┘└┘

This uses the raw syntax for less-than. A value is never less than itself, so the result of this is 0.

1 (52 bytes in UTF-16)

╔╗┌─╖┌─╖
║╟┤⌑╟┤ɕ╟
╚╝╘═╝╘═╝

⌑ returns a lazy sequence containing a single element and ɕ counts the number of elements. (The lazy sequence is lazy enough that this snippet doesn’t actually evaluate stdin at all!)

2 (70 bytes in UTF-16)

╔╗┌─╖┌─╖┌─╖
║╟┤⌑╟┤ʂ╟┤ɕ╟
╚╝╘═╝╘═╝╘═╝

= 2¹. ʂ generates all subsequences of a sequence, and thus turns a sequence of n elements into one with 2ⁿ.

3 (88 bytes in UTF-16)

╔╗┌─╖┌─╖┌─╖┌─╖
║╟┤⌑╟┤ʂ╟┤ɕ╟┤♯╟
╚╝╘═╝╘═╝╘═╝╘═╝

= 2 + 1. ♯ increments a value by 1.

4 (88 bytes in UTF-16)

╔╗┌─╖┌─╖┌─╖┌─╖
║╟┤⌑╟┤ʂ╟┤ʂ╟┤ɕ╟
╚╝╘═╝╘═╝╘═╝╘═╝

= 2².

5 (106 bytes in UTF-16)

╔╗┌─╖┌─╖┌─╖┌─╖┌─╖
║╟┤⌑╟┤ʂ╟┤ʂ╟┤ɕ╟┤♯╟
╚╝╘═╝╘═╝╘═╝╘═╝╘═╝

= 4 + 1.

6 (106 bytes in UTF-16)

╔╗┌─╖┌─╖┌─╖┌─╖┌─╖
║╟┤⌑╟┤ʂ╟┤ɕ╟┤♯╟┤!╟
╚╝╘═╝╘═╝╘═╝╘═╝╘═╝

= 3 factorial.

7 (110 bytes in UTF-16)

┌───┐┌─╖┌─╖┌─╖╔╗
│┌─╖├┤ɕ╟┤ʂ╟┤⌑╟╢║
└┤A╟┘╘═╝╘═╝╘═╝╚╝
 ╘╤╝

= A(2, 2) (Ackermann function).

8 (118 bytes in UTF-16)

┌────┐┌─╖┌─╖┌─╖╔╗
│┌──╖├┤ɕ╟┤ʂ╟┤⌑╟╢║
└┤<<╟┘╘═╝╘═╝╘═╝╚╝
 ╘╤═╝

= 2 << 2 (shift-left).

9 (128 bytes in UTF-16)

┌───┐┌─╖┌─╖┌─╖┌─╖╔╗
│┌─╖├┤♯╟┤ɕ╟┤ʂ╟┤⌑╟╢║
└┤×╟┘╘═╝╘═╝╘═╝╘═╝╚╝
 ╘╤╝

= 3 × 3.

10 (146 bytes in UTF-16)

┌───┐┌─╖┌─╖┌─╖┌─╖┌─╖╔╗
│┌─╖├┤♯╟┤ɕ╟┤ʂ╟┤ʂ╟┤⌑╟╢║
└┤+╟┘╘═╝╘═╝╘═╝╘═╝╘═╝╚╝
 ╘╤╝

= 5 + 5.

42 (170 bytes in UTF-16)

┌──────┐┌─╖┌─╖┌─╖┌─╖┌─╖╔╗
│┌─╖┌─╖├┤!╟┤♯╟┤ɕ╟┤ʂ╟┤⌑╟╢║
└┤♯╟┤×╟┘╘═╝╘═╝╘═╝╘═╝╘═╝╚╝
 ╘═╝╘╤╝

= 6 × (6 + 1).


Recovering Range Parameters Description

You are given the results of a range function where every element has been rounded down to the nearest whole number. Your goal is to recover the original list.

For example, the following function (in Python3) will produce an input for your program:

from numpy import arange, floor
def floored_range(A, B, C):
    return list(floor(arange(A, B, C)))

The output of your program should be a valid guess of the original data. Here, valid guess means that it must exactly match the input when floored and it must be a possible output of a range function (ie, when graphed it must form a perfectly straight line).

Examples

Input: [1,2,3,4]
Output: [1,2,3,4]

Input: [1,2,3,4]
Output: [1.9,2.7,3.5,4.3]

Input: [1,2,3,4,5,5]
Output: [1.9,2.7,3.5,4.3,5.1,5.9]

Input: [1,1,2,2,3,3,4,4]
Output: [1,1.5,2,2.5,3,3.5,4,4.5]

Input: [1,1,2,3,3,4]
Output: [1,1.7,2.4,3.1,3.8,4.5]

Input: [56, 54, 52, 50, 48, 45, 43, 41, 39, 37, 35, 32, 30, 28, 26, 24, 22, 19, 17, 15, 13, 11]
Output: [56.7  , 54.541, 52.382, 50.223, 48.064, 45.905, 43.746, 41.587,
   39.428, 37.269, 35.11 , 32.951, 30.792, 28.633, 26.474, 24.315,
   22.156, 19.997, 17.838, 15.679, 13.52 , 11.361]

Octave, 82 bytes

function y=f(x)
while any(floor(y=linspace(x(1)+rand,x(end)+rand,numel(x)))-x),end

Running time is non-deterministic, but the code ends in finite time with probability 1.
Try it online!
Explanation
The code defines a function of x that outputs y. The function consists of a while loop.
In each iteration, the right amount (numel(x)) of linearly spaced values are generated (linspace), starting at x(1)+rand and ending at x(end)+rand. These two calls to the rand function give random offsets between 0 and 1, which are applied to the initial and final values of x.
The loop is repeated for as long as any of the floored results differs (-)  from the corresponding entry in x.


Find the largest and the smallest number in an array The Task

The task is very simple. Given an array containing only integers and strings, output the largest number and the smallest number.

Test Cases

Input: [1, 2, 3, 4, 5, 6, 7, 8]
Output: 1, 8

Input: [5, 4, 2, 9, 1, 10, 5]
Output: 1, 10

Input: [7, 8, 10, "Hello", 5, 5]
Output: 5, 10

Numbers in strings are not considered integers:

Input: [1, 2, 3, 4, "5"]
Output: 1, 4

If there is only one integer, it is both the largest and smallest integer:

Input: [1]
Output: 1, 1

Input: ["1", "2", "3", "4", 5]
Output: 5, 5

Rules

You can assume that an array will always contains at least one integer.
All integers are positive (greater than 0)
The order of the output doesn't matter.
This is code-golf, so the submission with the least amount of bytes wins!
Strings can contain all printable ASCII characters (32 - 126) and are non-empty.

JavaScript (ES6), 54 56
Edit 2 bytes saved thx @Neil
Note: x===+x is true if and only if x is a number
a=>[Math.max(...a=a.filter(x=>x===+x)),Math.min(...a)]