Trigger the chutes and protect the jackpot You are going to participate in a gameshow. One of the challenges works as follows:

The first room contains a large number of identical balls.
The second room contains a series of chutes, each of which has a sensor which counts how many balls have been placed in it. A ball which is placed in a chute cannot then be recovered.
Each chute will trigger after a certain number of balls (its trigger count) have been placed into it. When it triggers it flashes lights, makes a noise, and leaves you in no doubt that it has triggered.
You must trigger N chutes to continue to the next challenge.
You know the trigger counts, but not the correspondence between count and chute.
You have one opportunity to take balls from the first room into the second. Once you put a ball into a chute, you cannot go back for more balls.
Each ball which you take deducts money from the jackpot.

Obviously you want to ensure that you will pass the challenge, but you want to minimise the jackpot money loss. Write a program, function, verb, etc. to tell you how many balls you need.

Example

Suppose the trigger counts are 2, 4, and 10, and you need to trigger 2 chutes to pass. There is a strategy to pass with 10 balls: place up to 4 balls in the first chute, up to 4 balls in the second chute, and up to 4 balls in the third chute. Since one of the three chutes will trigger after only 2 balls, you only use a total of 10. There is no strategy which is guaranteed to work with fewer than 10, so that is the correct output.

Input

The input consists of an array of integer trigger counts and a integer giving the number of chutes to trigger. You may take the two inputs in either order, and if needed you may take a third input with the length of the array.

You may assume that all of the inputs are greater than zero, and that the number of chutes which must be triggered does not exceed the number of chutes.

You may also assume that the counts are sorted (ascending or descending), as long as you state that clearly in your answer.

Output

The output should be a single integer, giving the number of balls required by the optimum strategy.

Test cases

Format: N counts solution

1 [2 4 10] 6
2 [2 4 10] 10
3 [2 4 10] 16
1 [3 5 5 5 5 5 5 5 5 5] 5
2 [1 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 8 11] 8
2 [1 2 6 6 6 6 6 6 6 10] 16
2 [1 2 3 3 4 4 6 6 6 11] 17
3 [1 2 3 4 5 5 6] 16
3 [2 4 7 7 7 7 7 7 7] 21
5 [1 2 2 3 3 3 3 3 5 9 9 11] 27
2 [5 15 15] 25
1 [4 5 15] 10
3 [1 4 4 4] 10
2 [1 3 4] 6
2 [1 3 3 8] 8

Python, 222 198 bytes

def S(G,P,T=0):
 T=T or[0]*len(P);r=[0]*(sum(t>=p for t,p in zip(T,P))>=G)
 for i,t in enumerate(T):
    if t<max(P):a=next(p for p in P if p>t)-t;T[i]+=a;r+=[a+S(G,P,sorted(T))];T[i]-=a
 return min(r)

Usage is S(2, (2, 4, 10)).

In order to test this program at any decent speed, add memoization by putting this after the function definition:

old_s = S
mem = {}
def S(G, P, T=0):
    k = (G, tuple(P), T and tuple(T) or 0)
    if k in mem: return mem[k]
    r = old_s(G, P, T)
    mem[k] = r
    return r

We do dynamic programming on an array T that contains the number of balls we've thrown into each chute, initially all zeroes. Without providing a rigorous proof, I claim that we can keep T sorted at all times, that is, assume we always throw the most balls into the last chute, which in turn we will assume was the largest chute.

If then T, when matched element for element with P (which is our problem input), has at least G (which is our goal) elements bigger, we've found a solution, and we return 0, because we need to throw 0 more balls to find a solution. This means that if G is 1 our least thrown into chute must contain an equal or more amount of balls than the smallest chute requirement, and so on for bigger G.

Otherwise, for each position we throw in enough balls to upgrade to the next chute requirement (anything in between would never be observable) and recurse. We then return the minimum of these recursive calls.


Praming Puzles & Colf: Condense a String Having spend some time on this site I have come to enjoy things being as short as possible. That may be the reason why I'm recently kind of offended by strings containing the same characters more than once. Your job is to write a function or program which condenses a given string according to the following rules:

Start with a 0-condensation, that is look for the first (leftmost) pair of the same characters with 0 other characters between them. If such a pair is found, remove one of the two characters and restart the algorithm by performing another 0-condensation. If no such pair is found, proceed with the next step. Examples:
  programming -C0-> programing
  aabbcc -C0-> abbcc
  test -C0-> test
Then perform a 1-condensation, that is look for the first pair of same characters with 1 other character between them. If such a pair is found remove one of them and all characters between them and restart with a 0-condensation. If no such pair is found, proceed with the next step. Examples:
abacac -C1-> acac
java -C1-> ja
Continue with a 2-condensation and so on up to a n-condensation with n being the length of the original string, each time restarting after a condensation removed some letters. Examples:
programing -C2-> praming
abcdafg -C3-> afg

The resulting string is called condensed and contains each character at most once.

Input:

A lower case string of printable ascii-characters.

Output:

The condensed string according to the rules above.

Examples:

examples     -> es
programming  -> praming
puzzles      -> puzles
codegolf     -> colf
andromeda    -> a
abcbaccbabcb -> acb
if(x==1):x++ -> if(x+
fnabnfun     -> fun
abcdefae     -> abcde

Detailed examples to clarify how the algorithm works:

fnabnfun -C0-> fnabnfun -C1-> fnabnfun -C2-> fnfun -C0-> fnfun -C1-> fun -C0-> fun
 -C1-> fun -C2-> ... -C8-> fun

abcbaccbabcb -C0-> abcbacbabcb -C0-> abcbacbabcb -C1-> abacbabcb -C0-> abacbabcb
 -C1-> acbabcb -C0-> acbabcb -C1-> acbcb -C0-> acbcb -C1-> acb -C0-> acb
 -C1-> ... -C12-> acb

Your approach doesn't have to implement the algorithm from above as long as your solution and the algorithm return the same output for all allowed inputs.
This is a code-golf challenge.

Thanks to @Linus for helpful sandbox comments!

JavaScript (ES6), 74 bytes

f=
(s,n=0,m=s.match(`(.).{${n}}\\1`))=>s[n]?m?f(s.replace(...m)):f(s,n+1):s
;
<input oninput=o.textContent=f(this.value)><pre id=o>


Find a number which generates all the integers mod q Consider the integers modulo q where q is prime,  a generator is any integer 1 < x < q so that x^1, x^2, ..., x^(q-1) covers all q-1 of the integers between 1 and q-1.  For example, consider the integers modulo 7 (which we write as Z_7).  Then 3, 3^2 mod 7 = 2, 3^3 = 27 mod 7 = 6, 3^4 = 81 mod 7 = 4, 3^5 = 243 mod 7 = 5, 3^6 = 729 mod 7 = 1 covers all the values 3, 2, 6, 4, 5, 1 covers all the integers 1..6 as required.

The task is to write code that  takes an input n and outputs a generator for Z_n.  You cannot use any builtin or library that does this for you of course.

The only restriction on the performance of your code is that you must have tested it to completion with n =  4257452468389.

Note that 2^n  means 2 to the power of n. That is ^ represents exponentiation.

Pyth, 16 15 bytes

f-1m.^T/tQdQPtQ

Test suite

If p is the input, we know that g^(p-1) = 1 mod p, so we just need to check that g^a != 1 mod p for any smaller a. But a must be a factor of p-1 for that to be possible, and any multiple of an a with that property will also have that property, so we only need to check that g^((p-1)/q) != 1 mod p for all prime factors q of p-1. So, we check all integers g in increasing order until we find one that works.

Explanation:

f-1m.^T/tQdQPtQ
f                  Return the first value T such that the following is truthy:
            PtQ    Take the prime factorization of the input - 1.
   m               Map those prime factors to
       /tQd        Take the input - 1 divided by the factor
    .^T    Q       Raise T to that exponent mod input,
                   performed as modular exponentiation, for performance.
 -1                Check that 1 is not found among the results.


Most creative way to display 42 Douglas Adams was born on March 11, 1952, and died when he was just 49. In honor of this wonderful writer, I challenge you to display 42 in the most creative way possible.

You could print it in the log, via some convoluted method, or display it as ASCII art, or anything! Just come up with a creative method of displaying 42.

Because this a popularity-contest, whichever answer has the most upvotes by March 11, will be declared the winner.

Note: this is not a duplicate. The question it was marked as duplicating was a code-trolling question whose goal was to write code to output 42, not find the most creative way to display it.

Winner: grovesNL! With an astounding 813 votes! Congrats!

Honorable Mentions:

Mr Lister C 228  For the clever use of #define

David Carraher Mathematica 45  For the complicated and convoluted math function to achieve 42

Aschratt Windows Calculator 20  Because, well, it's windows calculator And definitely 1337.

f.rodrigues Python 17 Because of the clever use of using external programs. And MSPaint

Jason C LMGTFY 14 For the use of LMGTFY (Let Me Google That For You)

Trimsty Python 12 For the clever use of an error message to output 42.

Mukul Kumar C++ 7 For the nice ASCII output.

If you think that there is another answer worth putting on the list, please comment it!


Tips for golfing in /// What general tips do you have for golfing in ///? I'm looking for ideas which can be applied to code-golf problems and which are also at least somewhat specific to /// (e.g. "remove unnecessary whitespace" is not an answer). Tips for itflabtijtslwi and Lines are on-topic and valid here as well.

Please post one tip per answer.

Use // as a replacement
When you define a bunch of replacements, e.g.:
/a/b//c/d//e/f//g/h//i/j//k/l//m/n//o/p//q/r//s/t//u/v//w/x//y/z/

(65 bytes).
You can use // as a replacement:
/~/\/\///a/b~c/d~e/f~g/h~i/j~k/l~m/n~o/p~q/r~s/t~u/v~w/x~y/z/

(61 bytes).


Co-primality and the number pi Introduction
Number theory is full of wonders, in the form of unexpected connections. Here's one of them.
Two integers are co-prime if they have no factors in common other than 1. Given a number \$N\$, consider all integers from 1 to \$N\$. Draw two such integers at random (all integers have the same probability of being selected at each draw; draws are independent and with replacement). Let \$p\$ denote the probability that the two selected integers are co-prime. Then \$p\$ tends to \${6} / {\pi^2} \approx 0.6079...\$ as \$N\$ tends to infinity.
The challenge
The purpose of this challenge is to compute \$p\$ as a function of \$N\$.
As an example, consider \$N = 4\$. There are 16 possible pairs obtained from the integers 1,2,3,4. 11 of those pairs are co-prime, namely \$(1,1)\$, \$(1,2)\$, \$(1,3)\$, \$(1,4)\$, \$(2,1)\$, \$(3,1)\$, \$(4,1)\$, \$(2,3)\$, \$(3,2)\$, \$(3,4)\$, \$(4,3)\$. Thus \$p = {11} / {16} = 0.6875\$ for \$N = 4\$.
The exact value of \$p\$ needs to be computed with at least \$4\$ decimals. This implies that the computation has to be deterministic (as opposed to Monte Carlo). But it need not be a direct enumeration of all pairs as above; any method can be used.
Function arguments or stdin/stdout may be used. If displaying the output, trailing zeros may be omitted. So for example \$0.6300\$ can be displayed as 0.63. It should be displayed as a decimal number, not as a fraction (displaying the string 63/100 is not allowed).
Winning criterion is fewest bytes. There are no restrictions on the use of built-in functions.
Test cases
Input / output (only four decimals are mandatory, as indicated above):
1    / 1.000000000000000
2    / 0.750000000000000
4    / 0.687500000000000
10   / 0.630000000000000
100  / 0.608700000000000
1000 / 0.608383000000000

Jelly, 12 8 bytes

RÆṪSḤ’÷²

Try it online!

The following binary code works with this version of the Jelly interpreter.

0000000: 52 91 b0 53 aa b7 9a 8a  R..S....

Idea

Clearly, the number of pairs (j, k) such that j ≤ k and j and k are co-prime equals the number of pairs (k, j) that satisfy the same conditions. Also, if j = k, j = 1 = k.

Thus, to count the number of co-prime pairs with coordinates between 1 and n, it suffices to calculate the amount m of pairs (j, k) such that j ≤ k, then compute 2m - 1.

Finally, since Euler's totient function φ(k) yields the number integers between between 1 and k that are co-prime to k, we can calculate m as φ(1) + … + φ(n).

Code

RÆṪSḤ’÷²    Input: n

R           Yield [1, ..., n].
 ÆṪ         Apply Euler's totient function to each k in [1, ..., n].
   S        Compute the sum of all results.
    Ḥ       Multiply the result by 2.
     ’      Subtract 1.
      ÷²    Divide the result by n².


Big integer multiplication Your challenge (if you choose to accept it) is to implement big integer multiplication in the shortest code possible.

Rules:

Take two integers (decimal form) as ASCII strings from the command line parameters of your program. If your language doesn't support command line parameters, I'll accept stdin or similar input mechanisms.
Output should be in ASCII decimal form, via a standard output mechanism (e.g. stdout)
Must support both positive and negative integers, as well as zero.
Must support any length integer integers up to 2**63 characters long, or at least the maximum you can store in memory.
You may not use any in-built classes or functionality that handles big integers.
The largest data type you may use is a 64-bit unsigned integer.
You may not use floating point operations.
You do not have to implement checks for valid inputs.

Example:

> multiply.exe 1234567890 987654321
1219326311126352690

Enjoy :)

APL (124 120 116)

This is way too long. It does grade school multiplication.

N←{↓⌽↑⌽¨⍵}⋄S↓'-',A/⍨∨\×A←{∨/M←9<T←0,⍵:∇(1⌽M)+T-M×10⋄⍵}⊃+/N↑⍨⌿2L⍴E,(L-1)+⍳L←⊃⍴E←⌽Y∘×¨⊃X Y←N⍎¨¨A~¨'-'⊣S←1≠+/'-'∊¨A←⍞⍞

Explanation:

N←{↓⌽↑⌽¨⍵}: N is a function that, given a vector of vectors, makes all the vectors the same length, padding with zeroes at the front. It does this by reversing all inner vectors (⌽¨), turning the vector of vectors into a matrix (↑), reversing this matrix (⌽), and turning it back into a vector of vectors (↓).
S←1≠+/'-'∊¨A←⍞⍞: Read two lines of input, as characters (⍞⍞), store them in A, and count how many minuses there are in the input. S is zero or one depending on whether the result will be positive.
X Y←N⍎¨¨A~¨'-': In A (our input) without (~) the minuses, evaluate each separate character (⍎¨¨), run it through the N function and save the two vectors in X and Y. If the input was 123 32, we now have X=1 2 3 Y=0 3 2.
L←⊃⍴E←⌽Y∘×¨⊃X Y: For each digit in the first vector, produce a vector with the digits from the second vector multiplied by that digit. Reverse this vector of vectors so that the least significant one is at the front. Store this vector in E and its length in L.
+/N↑⍨⌿2L⍴E,(L-1)+⍳L: Shift all of these vectors left, padding with zeroes on the right, by their index. Run them through N again so that they're all the same length. Then add all these vectors together. I.e.:

       1 2 3
         3 2
      ------
       2 4 6 (shift 0)
     3 6 9   (shift 1)
    --------
    3 8 13 6 (before carry)
     3 9 3 6 (after carry)

A←{∨/M←9<T←0,⍵:∇(1⌽M)+T-M×10⋄⍵}: Carry the ones. As long as there are still 'digits' higher than 10 (∨/M←9<T←0,⍵), add one to the next significant digit (∇(1⌽M)+T) and remove 10 from the offending digit (-M×10).
'-',A/⍨∨\×A: Remove any leading zeroes from the result vector, and add a minus in front.
S↓: Remove S characters from the front, i.e. if the result is supposed to be positive then remove the minus again.


EvenSt-ring C ode - g ol!f An 'Even string' is any string where the parity of the ASCII values of the characters is always alternating. For example, the string EvenSt-ring$! is an even-string because the ASCII values of the characters are:
69 118 101 110 83 116 45 114 105 110 103 36 33

And the parities of these numbers are:
Odd Even Odd Even Odd Even Odd Even Odd Even Odd Even Odd

Which is alternating the whole way. However, a string like Hello world! is not an even string because the ASCII values are:
72 101 108 108 111 32 87 111 114 108 100 33

And the parities are:
Even Odd Even Even Odd Even Odd Odd Even Even Even Odd

Which is clearly not always alternating.
The challenge
You must write either a full program or a function that accepts a string for input and outputs a truthy value if the string is even, and a falsy value otherwise. You can take your input and output in any reasonable format, and you can assume that the input will only have printable ASCII (the 32-127 range). You do not have to handle empty input.
Examples
Here are some examples of even strings:
#define
EvenSt-ring$!
long
abcdABCD
3.141
~
0123456789
C ode - g ol!f
HatchingLobstersVexinglyPopulateJuvenileFoxglove

And all of these examples are not even strings:
Hello World
PPCG
3.1415
babbage
Code-golf
Standard loopholes apply
Shortest answer in bytes wins
Happy golfing!

You may also use this ungolfed solution to test any strings if you're curious about a certain test-case.

MATL, 4 3 bytes

Thanks to Emigna for saving a byte and thanks to Luis Mendo for fixing some bugs. Code:

doA

Explanation:

d     # Difference between the characters
 o    # Mod 2
  A   # Matlab style all

Try it online!


Make a package manager It's time to make a more advanced program (rather than something simple, like printing some shape). You need a package manager for something, I guess.

First of all, if something wasn't defined, you are allowed to do anything, including destroying the computer (but please, don't, unless this will save your characters). After all, you will be using the package manager 100% correctly, so this won't happen. Who cares about security problems? It just has to be fast, like C programs.

The package manager should use STDIN and STDOUT as storage - that is, the database should be read from STDIN, and result database should be output to STDOUT, in true Unix style. The format of database is anything you want, as long you will be able to read it back.

The package manager shall support four commands. Typing unrecognized command is undefined, and anything can happen.

init - outputs the empty database to be read by other commands. This shouldn't read the database state.
install x y z - installs the programs x y z. If the program already exists, you can do anything
remove x y z - removes the programs x y z. If the program doesn't exist, you can do anything.
list - shows every program (with new line after every program). The list should be in alphabetical order. This mustn't output the database state.

The packages are only allowed to have lowercase ASCII letters (a-z). Anything else is undefined.

There is an example of example program:

$ ./lolmanager init > db
$ ./lolmanager install cat dog < db > db2
$ ./lolmanager remove dog < db2 > db
$ ./lolmanager list < db
cat
$ ./lolmanager install something else < db > db2
$ ./lolmanager list < db2
cat
else
something
$

The shortest code wins.

GolfScript, 59 characters
[{;;[]`}:it{|`}:ll{-`}:ve{;$n*}:st];~"#{ARGV*' '}"' '%(-2>~

Implemented the first idea which came into my mind. The database format is simply a GolfScript array representation. Install/remove also handle the case when a program is already installed.
Explanation
# Define four functions for later use ([...]; simply removes them from the stack):
[
  {;;[]`}:it         # init -> discard arguments, discard db, create empty db
  {|`}:ll            # install -> add arguments to db (if not already there)
  {-`}:ve            # remove -> remove all arguments from db
  {;$n*}:st          # list -> discard arguments, sort, join with newline
];

~                    # Parse db given on STDIN
"#{ARGV*' '}"' '%    # Parse command line arguments into array
(-2>                 # Take first argument (command) and the last two chars from it
~                    # Execute that command (i.e. "it" for "init", ...)


Solve Math Problem Notation Imagine I have an infinite number of homework problems (!) each given an integer number.

Math Problem Notation is a notation for describing subsets of the problem using problem specifiers.

An MPN expression can consist of several things:

A single value. This represents a set containing the number: 99 -> {99}.
A simple range. This represents the set containing all the numbers from the beginning to the end of the range: 10~13 -> {10, 11, 12, 13}. If the left or right sides are missing, then they are assumed to be -Infinity or Infinity respectively: ~10 -> {x|x ≤ 10}; ~ -> ℤ.
An MPN expression, followed by "skip" and another MPN expression. This represents the difference of the two sets: 10~20 skip 12~14 -> {10, 11, 15, 16, 17, 18, 19, 20}.
Two MPN expressions, separated by a comma. This represents the union of two sets: 1,8~9,15~17 -> {1,8,9,15,16,17}.

The "skip" operator binds tighter than the comma operator, so 16,110~112 skip 16 -> {16,110,111,112} (16 is not included in the set {110,111,112}, so the excluding 16 does not matter.)

You can also put expressions in parentheses for disambiguation:
1~9 skip (2~8 skip (3~7 skip (4~6 skip 5))) -> {1,3,5,7,9}

This is the grammar:

<expr>  ::= "(" <expr> ")"
         || <number>
         || [<number>] "~" [<number>]
         || <expr> "skip" <expr>
         || <expr> "," <expr>

Your task is to write a program that takes two inputs:

An MPN expression
A number

and outputs some truthy or falsey value depending on whether that problem is in the set described by the MPN expression.

Specifications

You can assume that the first input is a well-formed MPN expression (i.e. that it matches the above grammar)
Numbers in an MPN expression are always integers. They can be negative or zero, but will never have a fractional part.
This is code-golf, so the shortest valid submission (measured in bytes) wins.
You can use different characters for ~ and ,, if you want.

Test Cases

10~20             14 -> True
10~20             20 -> True
10~20 skip 14~18  17 -> False
~ skip 6          8  -> True
16,17 skip 16     16 -> True
(16,17) skip 16   16 -> False
~10,5~            8  -> True
~10,5~            4  -> True
6 skip 6,~        6  -> True

PowerShell, 189 195 bytes

param($m,$q)('$m',"'(\d*)~(\d*)','($q-ge(`$1)-and$q-le(`$2))'","'\(\)',$q","'((?<=,|skip )\d+|\d+(?=,| skip))','($q-eq`$1)'","'skip','-and!'"-join'-replace'|iex|% Sp* ','|%{"($_)"})-join'-or'|iex

Try it online! (with a single MPN and value)
Try all test cases with -100..100 as values
View the intermediate code generated, for all test cases (with 666 as the value)

Explanation
I realized early on that the infinities make this untenable for generating arrays and testing for values.
I looked into ranges but in .Net they don't have the range needed (the length of the range is limited to a signed (32 bit) integer, so even if it were ok to limit the range to a signed 32-bit int, I wouldn't have been able to handle all ranges.
So I started to just think about this in terms of starts and ends, and ultimately a series of boolean tests and started creating a bunch of regex replaces to turn an MPN into a boolean expression that PowerShell understands.
I basically broke this down into a few rules:

Ranges were easier to work with first because they can't be expressions on either end, but the open-endedness was a pain to implement shortly. The premise is 2~8 is like saying n >=2 && n <=8, but when one of the ends is missing, leave out the && and the missing side. When both are missing, I was going to originally just replace it with $true. What I ended up doing was not really testing for the missing sides at all, but I made sure to wrap each number in ().
and then do a straight substitution that replaces empty parentheses () with the input value. So, in the case of an MPN like ~8 with an input value of 55, the first replace will generate (55-ge()-and55-le(8)), then the second replace comes along to make it (55-ge55-and55-le(8)), essentially nullifying that part of the range.
Next I had to deal with individual numbers in the MPN, but had to take care not to mess with the ones I inserted from before. It's really just numbers in comma , separated lists, and individual numbers before or after a skip, so I used unfortunatley long lookarounds.
skip is basically the same as -and -not so I do a straight replace of skip to -and! (using ! as shorthand for -not).
The next tricky thing was the low order of precendence for the remaining commas. I originally just replaced them with -or but it didn't account for subsequent expressions so 16,17 skip 16 was generating code like ($n-eq16)-or($n-eq17) -and! ($n-eq16). It needed parentheses, but that seemed unworkable with a straight replace. Since all the other things were replaced except commas, and they have the lowest precedence, I just split the entire generated string on the remaining commas, then wrapped each element in parentheses, and rejoined it with -or.

Ultimately the generated code is just piped into Invoke-Expression (iex) to be executed and then we get the boolean result (you can see the code that gets generated instead of the result here).
This took way too long, and I'm sure there's some room to squeeze out a few more bytes, but I can't look at it anymore :-p


Toroidally magnify-blur a matrix Task

Given a matrix of numbers \$M\$ with \$r\$ rows and \$c\$ columns, and the magnification factor \$n\$, build the matrix with \$rn\$ rows and \$cn\$ columns where the original elements are spaced \$n\$ units apart and the gaps are filled by piecewise linear interpolation:

$$
    \begin{bmatrix}
    a_{11} & a_{12} & \cdots \\
    a_{21} & a_{22} & \cdots \\
    \vdots & \vdots & \ddots \\
    \end{bmatrix} \Rightarrow
    \begin{bmatrix}
    a_{11} & \frac{(n-1)a_{11} + a_{12}}{n} & \cdots & a_{12} & \cdots \\
    \frac{(n-1)a_{11} + a_{21}}{n} & \frac{(n-1) \frac{(n-1)a_{11} + a_{21}}{n} + \frac{(n-1)a_{12} + a_{22}}{n}}{n} & \cdots & \frac{(n-1)a_{12} + a_{22}}{n} & \cdots \\
    \vdots & \vdots & \ddots & \vdots \\
    a_{21} & \frac{(n-1)a_{21} + a_{22}}{n} & \cdots & a_{22} & \cdots \\
    \vdots & \vdots & & \vdots & \ddots \\
    \end{bmatrix}
$$

Because the operation is toroidal, the "gaps" between the \$r\$-th row and the 1st row (resp. the \$c\$-th column and the 1st column) must also be filled, which is placed below the original elements of the \$r\$-th row (resp. on the right side of the \$c\$-th column).

You can take \$M\$ and \$n\$ (and optionally \$r\$ and \$c\$) as input and output the resulting matrix in any suitable format. \$n\$ is guaranteed to be a positive integer. The input matrix and the result may have non-integers.

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

Test cases

# one-element matrix
M = [[1]], n = 3
[[1, 1, 1],
 [1, 1, 1],
 [1, 1, 1]]

# one-element matrix, large n
M = [[1]], n = 100
(100-by-100 matrix of ones)

# one-row matrix
M = [[0, 6, 3, 6]], n = 3
[[0, 2, 4, 6, 5, 4, 3, 4, 5, 6, 4, 2],
 [0, 2, 4, 6, 5, 4, 3, 4, 5, 6, 4, 2],
 [0, 2, 4, 6, 5, 4, 3, 4, 5, 6, 4, 2]]

# one-column matrix
M = [[0], [6], [3], [6]], n = 3
(transpose of the above)

# n = 1
M = [[1, 9, 8, 3],
     [5, 4, 2, 7],
     [3, 8, 5, 1]], n = 1
(same as M)

# 2-by-2 matrix; here the result is rounded to 2 decimal places for convenience.
# An answer doesn't need to round them, though one may choose to do so.
M = [[0, 9],
     [3, 6]], n = 3
[[0, 3,    6,    9, 6,    3],
 [1, 3.33, 5.67, 8, 5.67, 3.33],
 [2, 3.67, 5.33, 7, 5.33, 3.67],
 [3, 4,    5,    6, 5,    4],
 [2, 3.67, 5.33, 7, 5.33, 3.67],
 [1, 3.33, 5.67, 8, 5.67, 3.33]]

# a larger test case
M = [[0, 25, 0],
     [25, 0, 0],
     [0, 0, 25]], n = 5
[[0, 5, 10, 15, 20, 25, 20, 15, 10, 5, 0, 0, 0, 0, 0],
 [5, 8, 11, 14, 17, 20, 16, 12, 8, 4, 0, 1, 2, 3, 4],
 [10, 11, 12, 13, 14, 15, 12, 9, 6, 3, 0, 2, 4, 6, 8],
 [15, 14, 13, 12, 11, 10, 8, 6, 4, 2, 0, 3, 6, 9, 12],
 [20, 17, 14, 11, 8, 5, 4, 3, 2, 1, 0, 4, 8, 12, 16],
 [25, 20, 15, 10, 5, 0, 0, 0, 0, 0, 0, 5, 10, 15, 20],
 [20, 16, 12, 8, 4, 0, 1, 2, 3, 4, 5, 8, 11, 14, 17],
 [15, 12, 9, 6, 3, 0, 2, 4, 6, 8, 10, 11, 12, 13, 14],
 [10, 8, 6, 4, 2, 0, 3, 6, 9, 12, 15, 14, 13, 12, 11],
 [5, 4, 3, 2, 1, 0, 4, 8, 12, 16, 20, 17, 14, 11, 8],
 [0, 0, 0, 0, 0, 0, 5, 10, 15, 20, 25, 20, 15, 10, 5],
 [0, 1, 2, 3, 4, 5, 8, 11, 14, 17, 20, 16, 12, 8, 4],
 [0, 2, 4, 6, 8, 10, 11, 12, 13, 14, 15, 12, 9, 6, 3],
 [0, 3, 6, 9, 12, 15, 14, 13, 12, 11, 10, 8, 6, 4, 2],
 [0, 4, 8, 12, 16, 20, 17, 14, 11, 8, 5, 4, 3, 2, 1]]

APL (Dyalog Extended), 27 26 bytes

-1 thanks to Bubbler.

Anonymous infix lambda. Takes \$n\$ as left argument and \$M\$ as right argument.

{⊃+⌿,(⍳⍺)⍉⍤⌽\⍣2⊂⍺/⍺⌿⍵÷⍺*2}

Try it online! (the \$n=100\$ case run out of memory on TIO gives by default, but works offline)

{…} "dfn"; ⍺ is \$n\$ and ⍵ is \$M\$

 ⍺*2 \$n^2\$

 ⍵÷ \$M\over n^2\$

 ⍺⌿ replicate vertically so each row becomes \$n\$ copies

 ⍺/ replicate horizontally so each column becomes \$n\$ copies

 ⊂ enclose to work on entire matrix

 (⍳⍺)…⍣2 do the following twice, each time with the \$0,1…n-1\$ as left argument:

  \ outer "product" using the following tacit function instead of multiplication:

   ⌽ cyclically rotate the rows by the indices

   ⍤ then:

    ⍉ transpose

 , flatten

 +⌿ sum

 ⊃ disclose (since the summation reduced rank from 1 to 0 by enclosing)


Calculate the correlation coefficient Given a series of numbers for events X and Y, calculate Pearson's correlation coefficient. The probability of each event is equal, so expected values can be calculated by simply summing each series and dividing by the number of trials.

Input

1   6.86
2   5.92
3   6.08
4   8.34
5   8.7
6   8.16
7   8.22
8   7.68
9   12.04
10  8.6
11  10.96

Output

0.769

Shortest code wins. Input can be by stdin or arg. Output will be by stdout.

Edit: Builtin functions should not be allowed (ie calculated expected value, variance, deviation, etc) to allow more diversity in solutions. However, feel free to demonstrate a language that is well suited for the task using builtins (for exhibition).

Based on David's idea for input for Mathematica (86 char using builtin mean)

m=Mean;x=d[[All,1]];y=d[[All,2]];(m@(x*y)-m@x*m@y)/Sqrt[(m@(x^2)-m@x^2)(m@(y^2)-m@y^2)]

m = Mean;
x = d[[All,1]];
y = d[[All,2]];
(m@(x*y) - m@x*m@y)/((m@(x^2) - m@x^2)(m@(y^2) - m@y^2))^.5

Skirting by using our own mean (101 char)

m=Total[#]/Length[#]&;x=d[[All,1]];y=d[[All,2]];(m@(x*y)-m@x*m@y)/((m@(x^2)-m@x^2)(m@(y^2)-m@y^2))^.5

m = Total[#]/Length[#]&;
x = d[[All,1]];
y = d[[All,2]];
(m@(x*y)-m@x*m@y)/((m@(x^2)-m@x^2)(m@(y^2)-m@y^2))^.5

Mathematica 34 bytes
Here are a few ways to obtain the Pearson product moment correlation.  They all produce the same result.
From Dr. belisarius: 34 bytes
Dot@@Normalize/@(#-Mean@#&)/@{x,y}

Built-in Correlation function I: 15 chars
This assumes that x and y are lists corresponding to each variable.
x~Correlation~y

0.76909

Built-in Correlation function II: 31 chars
This assumes d is a list of ordered pairs.
d[[;;,1]]~Correlation~d[[;;,2]]

0.76909

The use of ;; for All thanks to A Simmons.

Relying on the Standard Deviation function: 118 115 chars
The correlation can be determined by:
s=StandardDeviation;
m=Mean;
n=Length@d;
x=d[[;;,1]];
y=d[[;;,2]];
Sum[((x[[i]]-m@x)/s@x)((y[[i]]-m@y)/s@y),{i,n}]/(n-1)

0.76909

Hand-rolled Correlation: 119 chars
Assuming x and y are lists...
s=Sum;n=Length@d;m@p_:=Tr@p/n;
(s[(x[[i]]-m@x)(y[[i]]-m@y),{i,n}]/Sqrt@(s[(x[[i]]-m@x)^2,{i,n}] s[(y[[i]] - m@y)^2,{i,n}]))

0.76909


Is there a shorter way to get user input in python? This is not a challenge. I'm wondering if it's at all possible to get user input into two separate variables in python (2 or 3) with less than 19 bytes. These are all the shortest I can get:

a,b=input(),input()
a=input();b=input() (newline replaced with semicolon for readability)
i=input;a,b=i(),i()

Is there any shorter way to do this?

If prompting the user doesn't matter, this is slightly shorter than eval for 3 or more:

a,b,c=map(input,[1]*3)
a,b,c=map(input,'111')

It's also shorter even if prompting is not ok:

a,b,c=map(input,['']*3)

Sadly, xnor's idea doesn't save anything for 2 inputs as it is still longer (19 bytes). However if you have some string (or appropriate iterable) with the appropriate length already (because magic?) then it could be shorter.

xnor found an example of a magic string for 3 inputs in Python 2 only:

a,b,c=map(input,`.5`)

This also requires that the prompts not be important, though.

This trick actually helps to save bytes for large numbers of inputs by using 1eX notation (getting x+3 inputs):

 a,b,c,d,e,f=map(input,`1e3`)

Explanation:

Python's map function performs the function it is passed on each element of the iterable that is also passed to it, and returns the list (or map object) containing the results of these calls. For the first example, the map could be decomposed to:

[input(1), input(1), input(1)]


ASCII Pumpkin Carving Today is Halloween and it's time to carve some pumpkins!

   &
((^.^))

Given an input integer, string, list of integers, etc., output the corresponding pumpkin. The input will always be of the form Stem, Eyes, Mouth, Width. For example, 2331 would be a valid input.

The pumpkin takes the form:

   S
((EME))

where S is the stem, E are the eyes, M is the mouth, and the parens form the body.

Definitions

Stem:
0 for a curl &
1 for a straight |
2 for a slant left \
3 for a slant right /

Eyes:
0 for angled ^
1 for small dots .
2 for medium dots o
3 for large dots O

Mouth:
0 for angled v
1 for small dot .
2 for medium dot o
3 for large dot O

Width:
0 for a skinny pumpkin (only one pair of parens)
1 for a fat pumpkin (two pairs of parens)

Examples

0011
   &
((^.^))

3100
   /
 (.v.)

2331
   \
((OOO))

1200
   |
 (ovo)

Rules

Input/output can be given by any convenient method.
You can print it to STDOUT or return it as a function result.
Either a full program or a function are acceptable.
Any amount of extraneous whitespace is permitted, provided the characters line up appropriately.
You must use the numbering and ordering of the pumpkin carvings as they are described above.
Standard loopholes are forbidden.
This is code-golf so all usual golfing rules apply, and the shortest code (in bytes) wins.

Add++, 56 bytes

L,"&|\/^.oOv.oO ((("4$Tz£:BF"("+@32C3*$+Bh$2D-1A:1+")"*J

Try it online!

Add++ is not the best at string manipulation challenges

How it works

We create an lambda function that takes a single argument - a list of integers - and outputs the final pumpkin.

L,                    - Define our function. Takes in a four element list e.g. [0 0 1 1]
                                                       STACK = [[0 0 1 1]]
  "&|\/^.oOv.oO ((("  - Push this string               STACK = [[0 0 1 1] '&|\/^.oOv.oO (((']
  4$T                 - Split it into 4 pieces         STACK = [[0 0 1 1] ['&|\/' '^.oO' 'v.oO' ' (((']
  z                   - Zip the lists together         STACK = [[['&|\\/' 0] ['^.oO' 0] ['v.oO' 1] [' (((' 1]]]
  £:                  - Index into each string         STACK = [['&' '^' '.' '(']]
  BF                  - Flatten the stack              STACK = ['&' '^' '.' '(']
  "("+                - Append a "(" to last element   STACK = ['&' '^' '.' '((']
  @                   - Reverse stack                  STACK = ['((' '.' '^' '&']
  32C3*$+             - Prepend 3 spaces to stalk      STACK = ['((' '.' '^' '   &']
  Bh                  - Output stack with newline      STACK = ['((' '.' '^']
  $2D                 - Push from under                STACK = ['((' '^' '.' '^']
  -1A:1+              - Add one the the last argument  STACK = ['((' '^' '.' '^' 2]
  ")"*                - Repeat ")" that many times     STACK = ['((' '^' '.' '^' '))']
  J                   - Join together                  STACK = ['((^.^))']
                      - Implicitly output


Real-time string matching Task

The task is to golf a real-time exact string matching algorithm of your choice.

Input

Two lines of text supplied on standard input, separated by a new line. The first line contains the "pattern" and will simply be an ASCII string drawn from the letters a-z.

The second line contains the longer "text" and will also simply be an ASCII string drawn from the letters a-z.

Output

A list of indices of where the exact matches occur.  You should output the position of the start of each match that occurs.

Specification

Your algorithm can spend linear time preprocessing the pattern. It must then read the text from left to right and take constant time for every single character in the text and output any new match as soon as it occurs.  Matches can of course overlap each other.

Algorithm

There are many real-time exact matching algorithms. One is mentioned on the wiki for KMP for example. You can use any one you like but you must always output the right answer.

I will keep a per language leader table so that those who prefer popular languages can also win in their own way.  Please explain which algorithm you have implemented.

Real-time

It seems there has been a lot of confusion over what real-time means. It doesn't simply mean linear time. So standard KMP is not real-time. The link in the question explicitly points to a part of the wiki page for KMP about a real-time variant of KMP. Neither is Boyer-Moore-Galil real-time.  This cstheory question/answer discusses the issue or one can just google "real-time exact matching" or similar terms.

Python 2, 495 bytes

This one is a real-time KMP, which is a lot shorter and only slightly slower than the BMG algorithm (which is usually sublinear). Call with K(pattern, text); output is identical to the BMG algorithm.

L,R,o=len,range,lambda x:ord(x)-97
def K(P,T):
 M,N=L(P),L(T);Z=[0]*M;Z[0]=M;r=l=0
 for k in R(1,l):
    if k>r:
     n=0
     while n+k<l<P[n]==P[n+k]:n+=1
     Z[k]=n
     if n>0:l,r=k,k+n-1
    else:
     p,_=k-l,r-k+1
     if Z[p]<_:Z[k]=Z[p]
     else:
        i=r+1
        while i<M<P[i]==P[i-k]:i+=1
        Z[k],l,r=i-k,k,i-1
 F=[[0]*26]*M
 for j in R(M-1,0,-1):z=Z[j];i,x=j+z-1,P[z+1];F[i][o(x)]=z
 s=m=0
 while s+m<N:
    c=T[s+m]
    if c==P[m]:
     m+=1
     if m==M:print s,;s+=1;m-=1
    else:
     if m==0:s+=1
     else:f=F[m][o(c)];s+=m-f;m=f


Calculate pi to 5 decimals This comes from http://programmers.blogoverflow.com/2012/08/20-controversial-programming-opinions/

"Given that Pi can be estimated using the function 4 * (1 – 1/3 + 1/5 – 1/7 + …) with more terms giving greater accuracy, write a function that calculates Pi to an accuracy of 5 decimal places."

Note, the estimation must be done by calculating the sequence given above.

JavaScript, 46 58 56 45 bytes

ES6 update: Turns out there's more features available to us now that five years have passed.

let f=(i=0,a=0)=>i>1e6?a:f(i+4,a+8/-~i/(i+3))

This version (45 bytes; yes, the let is required) works in ES6 strict mode in theory.  In practice, you can run it in V8 (e.g. with node) with --use-strict --harmony-tailcalls; the Proper Tailcalls feature isn't widely implemented yet, alas.  However, it's specified behaviour, so it should be fine.

If we want to stick to what's widely implemented, and not require strict-mode, we can simply use the ES6 fat-arrow syntax for functions but otherwise retain the same implementation as before (suggested by Brian H) for a cost of 48 bytes.

a=>{for(a=i=0;i<1e6;a+=8/++i/~-(i+=3));return a}

The choice of name for the single parameter doesn't really matter, but we might as well pick one of the names we use so as to minimise the global-scope pollution.

function(){for(a=i=0;i<1e6;a+=8/++i/~-(i+=3));return a}

This version is a function expression; add two characters (e.g. " f") if you want it named.  This version clobbers the globals a and i; this could be prevented if we added "a,i" to the parameter list.

Makes use of a reformulated version of the algorithm in order to circumvent the need for subtraction.

 1/1 - 1/3  +   1/5 - 1/7   +    1/9 - 1/11  + ...
(3/3 - 1/3) + (7/35 - 5/35) + (11/99 - 9/99) + ...
    2/3     +      2/35     +       2/99     + ...
  2/(1*3)   +    2/(5*7)    +     2/(9*11)   + ...

Here's a "plain" version without this adjustment:

function(){for(a=0,i=1;i<1e6;i+=2)a+=[,4,,-4][i%4]/i;return a}

which clocks in at 64 62 characters.

Thanks to @ardnew for the suggestion to get rid of the 4* before the return.

History

function(){for(a=i=0;i<1e6;a+=8/++i/~-(i+=3));return a}     // got rid of `i+=4`; restructured
// Old versions below.
function(){for(a=0,i=1;i<1e6;i+=4)a+=8/i/-~-~i;return a}    // got rid of `4*`
function(){for(a=0,i=1;i<1e6;i+=4)a+=2/i/-~-~i;return 4*a}


Program to Spoonerise words A spoonerisation is swapping the first letter/pronounceable syllable of two or more words.

Example: A lack of pies = A pack of lies. Bad salad = Sad ballad (ish) :)

Challenge: Write a program to spoonerise two words in the shortest characters possible.

Rules:

If the first letter is a consonant, you must include subsequent letters until you reach a vowel. (e.g. 'thanks' - the th gets removed and put on the front of the other word).
With words that start with vowels, do not remove anything from the start of the word.

Good luck :)

UPDATE: Multiple word spoonerisms are not strictly applicable, however from a programatic view we must cater for them so this is the rule: Every word must change. Example:

Weird Keen Monkey -> Meird Ween Konkey OR Keird Meen Wonkey NOT Meird Keen Wonkey

Also 'y' is treated as a vowel (just to simplify things a bit)

Ruby (60) (61) (93) (80) (75) (71) (69 / 57)

Program changed to handle the new requirement of handling multiple words.

EDIT: Golfed down to 80. 75. 71. 69.

w=[];gets.gsub(/(\S*?)([aeiouy]\S*)/i){w+=[$2,' ',$1]};$><<w.pop+w*''

If we're only spoonerizing words that start with a consonant, here's a solution in 73. 65. (I realized I can just use scan instead of gsub.) 57.

$><<gets.gsub(p=/\b[^aeiouy\s]+/i){($'+$`+$&).scan(p)[0]}

Old program (two words only):

p='(.*?)([aeiou].+)';puts gets.gsub(/#{p} #{p}/i,'\3\2 \1\4')


The Black Pawn's Revenge Objective

The black pawn wants revenge. Plot out its last attack.

Rules

The black pawn (L) starts at the top row and moves downwards to the bottom row. Maximise points taken, indicating the path with X. Pawns (P) are 1, bishops (B) and knights (N) 3, rooks (R) 5, and queens (Q) 9. There won't be any kings in the input.

If there is more than one path that has the maximum amount of points, output any of those paths. There will not be any situations where the pawn cannot reach the bottom row.

Examples

Input:

----L---
-----P--
------P-
--R--P-Q
----P-P-
---P-P-P
--P-N---
-P------

Output:

----L---
-----X--
------X-
--R--P-X
----P-X-
---P-X-P
--P-X---
-P--X---

Input:

--L-----
-P------
P-------
-P------
P--Q----
-P------
P-------
-P------

Output:

--L-----
-PX-----
P-X-----
-PX-----
P--X----
-P-X----
P--X----
-P-X----

Python, 332

def s(m,l,p):
 if not m:return 1
 b=m[0]+'-';z=filter(lambda i:(b[i]=='-')==(i==l),[l,l-1,l+1])
 if not z:return 0
 g=lambda i:s(m[1:],i,0)+[0,1,3,3,5,9]['-PBNRQ'.index(b[i])];i=max(z,key=g)
 if p:print m[0][:i]+'X'+m[0][i+1:];s(m[1:],i,p)
 return g(i)
import sys
t=sys.stdin.read().split('\n')
print t[0]
s(t[1:],t[0].index('L'),1)


The Burnt Pancake Problem This challenge is related to Flipping Pancakes.

You may have heard of pancake sorting, where a stack of pancakes is sorted by size by inserting spatula into the stack and flipping all of the pancakes above the spatula, until the pancakes are sorted smallest to largest on the plate. The burnt pancake problem is slightly different. All pancakes now have one side that is burnt, and the burnt side of each pancake must face the plate once the sorting is completed.

For example, given the following stack (size of pancake on the left. 0 meaning burnt-side down and 1 meaning burnt-side up on the right):

1 0
3 1
2 1

You may flip the whole stack to get 20 30 11, flip the top two to get 31 21 11 and flip the whole stack again to get 10 20 30, a sorted stack of burnt pancakes. This sequence of moves, flip 3, flip 2, flip 3, could be represented as 3 2 3.

The Challenge

Given an array of pancakes sizes (not necessarily unique) and their orientations, output any valid burnt pancake sorting sequence, that is, a sequence of flips that leads to the stack of pancakes being sorted from smallest to largest with burnt sides down.
Input and output may be any sane format with separators, but please specify which formats you use and state which end of your input format is the top of the stack (TOS).
Flipping zero pancakes is allowed.
Mixing separators in the input/output is allowed.

Test cases

For all of the following test cases, input is a list and output is a space-separated string, and TOS is on the left.

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

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

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

As always, if anything is unclear or incorrect, please let me know in the comments. Good luck and good golfing!

Python 2, 83
Input is expected to be the list of (size, orientation) tuples with the stack's top at the end. The output is a list of sizes to flip separated by various kinds of whitespace.

a=input()
while a:i=a.index(max(a));print len(a)-i,a[i][1],len(a),i;a=a[i+1:]+a[:i]


5 Day Weather Forecast Weather forecasting: Wrong too often to rely on, right too often to ignore.

Given a high and low temperature and one of four weather conditions per day, output an ASCII-art graphical five day weather forecast. The structure of the four graphical indicators are shown below.

 \ /
 -O-       Sunny
 / \

\ /
-O(==)     Partly Cloudy
(====)

  (==)     Cloudy
(====)

  (==)
(====)     Rainy
/////

The forecasting chart is as follows: each graphical indicator is centered in its own 9x5 box, with 5 boxes across the chart. Each box is separated by | characters. Below the graphical indicator is a three-letter abbreviation for the day of the week (MON, TUE, WED, THU, FRI, SAT, SUN) centered in its own 9x1 box. The temperatures are below the day of the week centered in their own 9x2 box. An example is shown below.

---------------------------------------------------
|         |         |         |         |         |
|    (==) |    (==) |  \ /    |   \ /   |   \ /   |
|  (====) |  (====) |  -O(==) |   -O-   |   -O-   |
|         |  /////  |  (====) |   / \   |   / \   |
|         |         |         |         |         |
---------------------------------------------------
|   MON   |   TUE   |   WED   |   THU   |   FRI   |
---------------------------------------------------
|  H 75   |   H 69  |  H 77   |   H 80  |  H 85   |
|  L 57   |   L 53  |  L 61   |   L 63  |  L 66   |
---------------------------------------------------

Note that "centered" can be taken loosely -- see in the example how the graphical alignment and the temperature horizontal alignment are somewhat flexible.

Additionally, since I'm from the US and therefore use Fahrenheit, you can safely assume that the temperatures are all double-digit, so 9 < t < 100.

I/O and Rules

The I/O examples here are demonstrative of the above example chart.

Input can be taken in any reasonable format and by any convenient method. For example,
1) you could use numbers for the days of the week, the high and low temperatures, and the four conditions, and take input as five tuples, like [0, 75, 57, 2], [1, 69, 53, 3], ...
2) you could take input as five tuples using words, like ['MON', 75, 57, 'CLOUDY'], ['TUE', 69, 53, 'RAINY'] ...
3) you could take input as just the first day, and a list of high temperatures, a list of low temperatures, and a list of conditions, like 1, [75, 69, ...], [57, 53, ...], [2, 3, ...]
4) etc.
Leading/trailing newlines or other whitespace are optional, provided that the characters line up appropriately.
Either a full program or a function are acceptable. If a function, you can return the output rather than printing it.
Output can be to the console, returned as a list of strings, returned as a single string, etc.
Standard loopholes are forbidden.
This is code-golf so all usual golfing rules apply, and the shortest code (in bytes) wins.

Emojicode, 1202 974 bytes

afD MON   TUE   WED   THU   FRI   SAT   SUN  f / \   \ /   -O-  (====)\ /   -O(==)        (==)(====)/////   (==)(====)l ---------------------------------------------------u      s |  S  |   wH L lLs u s u s u s u s u sLoi⏩-2 4o s◀1ios j⏩0 5▶1ioofa j 0i s◀1ioow ia j i 10SooDa j 1 so0i1i0iLll

Takes input as a list of lists of integers in the format of condition day high low where condition is an integer between 0 and 4. Try it online!


Distribute a number into a list of values as equal as possible whose sum is equal to that number Probably a simple code-golf challenge. Given 2 positive integers m and n, make a list of n values that are positive integers whose sum is equal to the number m. Either all values in the output are the same value or the difference is exactly 1.

Examples

For example

m=6 and n=3 would become 2, 2, 2
m=7 and n=3 would become 2, 2, 3 or 2, 3, 2 or  3, 2, 2
m=7 and n=2 would become 3, 4 or 4, 3
m=7 and n=1 would become 7
m=7 and n=8 would generate an error because the sum of 8 positive integers cannot be 7.
m=10 and n=4 would become 3, 3, 2, 2 or any other permutation

Rules

Both input and output is only about positive integers.
Either all values in the output are the same value or the difference is exactly 1.
The order of the values in the list is not important.
The sum of the values in the list is equal to m.
When it's not solvable, generate an error or a false value (in case of m=7 and n=8 for example).
As a result of the other rules m=8 and n=3 would generate any of the permutations of 3, 3, 2 (not 2, 2, 4)

The winner

This is code-golf, so the shortest valid answer – measured in bytes – wins.

Python 2, 48 43 bytes

Returns 0 on error.

lambda m,n:m/n and[m/n]*(n-m%n)+m%n*[m/n+1]

Try it online!

41 bytes (with @xnor's trick)

Throws NameError on error.

lambda m,n:[m/n or _]*(n-m%n)+m%n*[m/n+1]

Try it online!


Delete those pesky ".DS_Store" files If you use OS X then you might be familiar with the infamous hidden ".DS_Store" files that are produced as a result of using Finder.

The challenge is to write code that will go through the entire file system and delete any file named ".DS_Store".

Classic code golf - shortest code wins.

Clarifications:

The code does not need to delete any .DS_Store files that require superuser; assume no such files exist.
The code should only delete the relevant .DS_Store files and nothing else.

zsh, 19

rm -f /**/.DS_Store

(Make that 16 if it's ok to leave out -f.)


TUT language translator Text may be translated to a written version of TUT language by replacing each letter by the corresponding "TUT word", as given in the following table (adapted from the linked article)*:

a  e        h  hash     o  o        u  yu
b  bub      i  ay       p  pup      v  vuv
c  kut      j  jag      q  kwak     w  waks
d  dud      k  kak      r  rut      x  eks
e  i        l  lul      s  sus      y  yak
f  fuf      m  mum      t  tut      z  zuz
g  jug      n  nun

* Exceptions:
(1) Upper case letters have corresponding TUT words in upper case.
(2) A doubled letter becomes 'skwer' ('SKWER') followed by the TUT word for that letter.
    - An n-fold letter is treated as a number of doubles, followed by a single if needed.
    - To be considered a double or n-fold letter, the letters must be in the same case.
(3) 'rut' ('RUT') is replaced by 'rud' ('RUD') if immediately followed by 'dud' ('DUD').

Write a program with the following i/o behavior:

Input (from stdin): A binary (0/1) indicator i and an ASCII string s.

If i = 0 then s may contain any ASCII text.
If i = 1 then s must be the TUT Language output for some valid input.

Output (to stdout): A binary (0/1) indicator j and an ASCII string t.

If i = 0 then j = 1 and t is the translation of s to TUT Language.
If i = 1 then j = 0 and t is the translation of s from TUT Language.
For any valid input, applying the program to its own output must exactly reproduce the original input; i.e., program (program (i, s)) = (i, s). Input and output must have exactly the same format.

Scoring: The score is the number of characters in the program -- lowest score wins.

Examples

(a)

(0, 'Look for the birds.')
(1, 'LULskwerokak fuforut tuthashi bubayruddudsus.')

(b)

(0, '"Mrs. Hogwallop up and R-U-N-N-O-F-T."')
(1, '"MUMrutsus. HASHojugwakseskwerlulopup yupup enundud RUT-YU-NUN-NUN-O-FUF-TUT."')

(c)

(0, 'QWX WWW Rrrrd deeeeep')
(1, 'KWAKWAKSEKS SKWERWAKSWAKS RUTskwerrutruddud dudskweriskweriipup')

(d)

(0, 'aa AA aA Aa rd RD rD Rd')
(1, 'skwere SKWERE eE Ee ruddud RUDDUD rutDUD RUTdud)

(((Aside about pronunciation: The TUT words for the vowels (e, i, ay, o, yu) are supposed to represent the usual sounds of (a, e, i, o, u) when reciting the alphabet -- i.e., rhyming with (may, me, my, mow, mew). In the three-or-more-letter TUT words, the symbols (u,a,e) are supposed to sound as in (but, bat, bet) respectively -- these are ASCII replacements for (ʌ æ ɛ)  in the linked article.)))

Ruby, 310 311 characters
h=Hash[(?a..?z).zip %w{e bub kut dud i fuf jug hash ay jag kak lul mum nun o pup kwak rut sus tut yu vuv waks eks yak zuz}]
h["rd"]="ruddud"
h.keys.each{|k|h[k[0]+k]="skwer"+h[k]}
h.keys.each{|k|h[k.upcase]=h[k].upcase}
h=h.invert if b=getc==?1
i=gets
print b ?0:1;(k=i;k=k.chop until h[k]||!k[1];$><<(h[k]||k);i[k]="")until i==""

Correctly handles:

squared uppercase (unfix by merging iterations gains 18 characters)

if AA should turn into skwerE, swap lines #3 and #4
I also assume aA and Aa should turn into eE and Ee respectively

rrd translates to `skwerruddud (unfix gains 3 characters)
in cubes the first pair is reported as a square. rrrd turns into skwerrutruddud. rrrrd becomes skwerrutskwerruddud
the output is now a valid input. It is, indeed, required by the spec
uses newline as input terminator

Input requires there be no newline between the indicator and the string, output puts it there (fix: 1 character). Console output suppressed at this point to prevent mixing with STDIN. Unfix free, it's just a little bit uglier.
Example input:
0Hello

Output:
1
HASHiskwerlulo


Quine that takes as input the name of a language and outputs the same thing implemented in the input language From Quine central:

Write a quine that takes as input the name of a language and outputs the same thing implemented in the input language.

The source article has something you can work from, but as the author says this is much harder. Obviously you only need to support a limited set of languages. The choice is yours though, as well as the base language.

As a code-challenge, your score will be the number of languages your program supports; higher is better.

Ruby

require 'json';s=%q[{"ruby":[" %q[","require 'json';s=##;j=JSON.load s;puts j[l=gets.chomp][1].sub('##',j[l][0].delete(' ')+s+j[l][2].delete(' '))"," ]"],"python":["' ''","import json,re;s=##;j=json.loads(s);l=raw_input();print(re.sub('##',j[l][0].replace(' ','')+s+j[l][2].replace(' ',''),j[l][1],1))","' ''"]}];j=JSON.load s;puts j[l=gets.chomp][1].sub('##',j[l][0].delete(' ')+s+j[l][2].delete(' '))

Python

import json,re;s='''{"ruby":[" %q[","require 'json';s=##;j=JSON.load s;puts j[l=gets.chomp][1].sub('##',j[l][0].delete(' ')+s+j[l][2].delete(' '))"," ]"],"python":["' ''","import json,re;s=##;j=json.loads(s);l=raw_input();print(re.sub('##',j[l][0].replace(' ','')+s+j[l][2].replace(' ',''),j[l][1],1))","' ''"]}''';j=json.loads(s);l=raw_input();print(re.sub('##',j[l][0].replace(' ','')+s+j[l][2].replace(' ',''),j[l][1],1))

Both versions take input on stdin (ruby or python currently) and generate the output to stdout in either language.


Leak Memory in as few bytes as possible Your task is to write code that will leak at least one byte of memory in as few bytes as possible.  The memory must be leaked not just allocated.

Leaked memory is memory that the program allocates but loses the ability to access before it can deallocate the memory properly.  For most high level languages this memory has to be allocated on the heap.

An example in C++ would be the following program:

int main(){new int;}

This makes a new int on the heap without a pointer to it.  This memory is instantly leaked because we have no way of accessing it.

Here is what a leak summary from Valgrind might look like:

LEAK SUMMARY:
   definitely lost: 4 bytes in 1 blocks
   indirectly lost: 0 bytes in 0 blocks
     possibly lost: 0 bytes in 0 blocks
   still reachable: 0 bytes in 0 blocks
        suppressed: 0 bytes in 0 blocks

Many languages have a memory debugger (such as Valgrind) if you can you should include output from such a debugger to confirm that you have leaked memory.

The goal is to minimize the number of bytes in your source.

Perl (5.22.2), 0 bytes

Try it online!

I knew there'd be some language out there that leaked memory on an empty program. I was expecting it to be an esolang, but turns out that perl leaks memory on any program. (I'm assuming that this is intentional, because freeing memory if you know you're going to exit anyway just wastes time; as such, the common recommendation nowadays is to just leak any remaining memory once you're in your program's exit routines.)

Verification

$ echo -n | valgrind perl
…snip…
==18517==
==18517== LEAK SUMMARY:
==18517==    definitely lost: 8,134 bytes in 15 blocks
==18517==    indirectly lost: 154,523 bytes in 713 blocks
==18517==      possibly lost: 0 bytes in 0 blocks
==18517==    still reachable: 0 bytes in 0 blocks
==18517==         suppressed: 0 bytes in 0 blocks
==18517==
==18517== For counts of detected and suppressed errors, rerun with: -v
==18517== ERROR SUMMARY: 15 errors from 15 contexts (suppressed: 0 from 0)


The making of "Spot It!": Finding almost unique sets Puzzle: Find a deck of c cards, each containing p pictures, such that no two pictures match on a given card, and exactly 1 picture on each card matches exactly 1 picture on each of the other cards, where the number of unique pictures in the deck is minimized.

Criteria: Fastest code for c = 31 and p = 6.

Inspiration: This puzzle was inspired by wondering how the makers of the card game Spot It! came up with a deck of cards that differ from each other by only one picture. If it helps, the game's instructions say it contains 31 cards with at least 30 unique pictures.

Brute-force reference implementation: (Entirely impractical for use at the scale of the contest judging criteria, but perhaps useful for thinking about the problem.)

class Program
{
    const int CardCount = 31, PicturesPerCard = 6;

    static void Main()
    {
        for (int pictureLimit = PicturesPerCard; ; ++pictureLimit)
            new Solver(pictureLimit).FindValidCards(0, 0);
    }

    class Solver
    {
        readonly byte[,] cards = new byte[CardCount, PicturesPerCard];
        readonly int pictureLimit;

        public Solver(int pictureLimit)
        {
            this.pictureLimit = pictureLimit;
        }

        public void FindValidCards(int c, int p)
        {
            for (; c < CardCount; ++c) {
                for (; p < PicturesPerCard; ++p) {
                    for (int picture = p == 0 ? 0 : cards[c, p - 1] + 1; picture < pictureLimit; ++picture) { // Only consider pictures in numerically increasing sequence, since sequence order is irrelevant.
                        cards[c, p] = (byte)picture;
                        if (p < PicturesPerCard - 1) {
                            FindValidCards(c, p + 1);
                        } else if (c < CardCount - 1) {
                            FindValidCards(c + 1, 0);
                        } else if (AreCardsValid()) {
                            WriteCards();
                            System.Environment.Exit(0);
                        }
                    }
                }
            }
        }

        bool AreCardsValid()
        {
            for (int c = 0; c < CardCount; ++c)
                for (int otherC = c + 1; otherC < CardCount; ++otherC) {
                    int matchCount = 0;
                    for (int p = 0; p < PicturesPerCard; ++p)
                        for (int otherP = 0; otherP < PicturesPerCard; ++otherP)
                            if (cards[c, p] == cards[otherC, otherP])
                                ++matchCount;
                    if (matchCount != 1)
                        return false;
                }
            return true;
        }

        /// <summary>
        /// Writes to the console all the cards with each unique picture placed in its own column for easier comparison between cards.
        /// </summary>
        void WriteCards()
        {
            for (int c = 0; c < CardCount; ++c) {
                string cardString = string.Empty;
                for (int picture = 0; picture < pictureLimit; ++picture)
                    for (int p = 0; ; ++p) {
                        if (p == PicturesPerCard) {
                            cardString += ' ';
                            break;
                        }
                        if (cards[c, p] == picture) {
                            cardString += (char)(picture < 26 ? 'A' + picture : 'a' + (picture - 26));
                            break;
                        }
                    }
                System.Console.WriteLine(cardString);
            }
        }
    }
}

Edits: Reworded puzzle to correctly articulate the intent that the goal is to find a deck that matches the constraints. Added the missing constraint that no two pictures on a card may match. Changed contest type from code golf to speed.

This should be a comment rather than an answer, but it's not going to fit in a comment.

One way of looking at this problem is to flip it around:

  Given that you have N distinct pictures, what's the largest deck of cards you can build each of which has n distinct pictures such that the intersection of any two cards is precisely one picture?

Another way of phrasing this flipped-round problem is:

  What is the maximal size of binary code of length N, constant weight n and exact pairwise Hamming distance 2(n-1)?

This is bounded by the maximal size of binary codes of length N, constant weight n, and minimal Hamming distance 2(n-1). The best resource for such bounds appears to be http://www.win.tue.nl/~aeb/codes/Andw.html although some values here are extracted from OEIS (specifically A001839).

 N \ n  0   1   2   3   4   5   6   7   8   9
 0      1   -   -   -   -   -   -   -   -   -
 1      1   1   -   -   -   -   -   -   -   -
 2      1   1   1   -   -   -   -   -   -   -
 3      1   1   3   1   -   -   -   -   -   -
 4      1   1   3   1   1   -   -   -   -   -
 5      1   1   4   2   1   1   -   -   -   -
 6      1   1   5   4   1   1   1   -   -   -
 7      1   1   6   7   2   1   1   1   -   -
 8      1   1   7   8   2   1   1   1   1   -
 9      1   1   8   12  3   2   1   1   1   1
 10     1   1   9   13  5   2   1   1   1   1
 11     1   1   10  17  6   2   2   1   1   1
 12     1   1   11  20  9   3   2   1   1   1
 13     1   1   12  26  13  3   2   2   1   1
 14     1   1   13  28  14  4   2   2   1   1
 15     1   1   14  35  15  6   3   2   2   1
 16     1   1   15  37  20  6   3   2   2   1
 17     1   1   16  44  20  7   3   2   2   2
 18     1   1   17  48  22  9   4   3   2   2
 19     1   1   18  57  25  12  4   3   2   2
 20     1   1   19  60  30  16  5   3   2   2
 21     1   1   20  70  31  21  7   3   3   2
 22     1   1   21  73  37  21  7   4   3   2
 23     1   1   22  83  40  23  8   4   3   2
 24     1   1   23  88  42  24  9   4   3   3
 25     1   1   24  100 50  30  10  5   3   3
 26     1   1   25  104 52  30  13  5   4   3
 27     1   1   26  117 54  31  14  6   4   3
 28     1   1   27  121 63  33  16  8   4   3
 29     1   1   28  134 65  ?   20  8   4   3
 30     1   1   29  140 ?   ?   25  9   5   4
 31     1   1   30  155 ?   ?   31  9   5   4
 32     1   1   31  160 ?   ?   31  10  5   4

There are some easy to prove properties, but from what I've read so far it seems that in general there's no better method known than brute force.

Note that for n > 2 these bounds appear to be loose for N > n^2 - n + 1 (certainly they are for the values of n in the table above), and tight for N <= n^2 - n + 1.

One useful result which handles the case that most interests you is as follows. (I could also write some code to wrap this up by using special cases and falling back to brute force, but I don't see the point).

  If N = n^2 - n + 1 then there is a nicely structured deck of N cards satisfying the required property.

The construction is quite simple:

(-1,-1) (x,0) (x,1) ... (x,n-2)                for x in 0..n-1
(0,y) (1,y+z % n-1) ... (n-1, y+(n-1)z % n-1)  for y in 0..n-2, z in 0..n-2

Each element appears in precisely n cards, which makes it optimal for decks in which more than one picture repeats.

Call the most frequent picture (selecting arbitrarily in case of a tie) f.

Lemma 1

  If f appears in more than n cards then it must appear in every card, and no other element repeats.

Proof: because each pairwise intersection contains precisely one element, all of the other elements in the cards containing f must be distinct. But then a card which doesn't contain f must have a non-trivial intersection with more than n disjoint sets despite having only n elements, which is impossible.

Corollary

  The largest possible deck in which f appears in more than n cards has size floor((N-1) / (n-1))

Excluding f from the N available pictures we get N-1 from which to draw disjoint sets of size n-1 to complete each card.

Lemma 2

  Any deck in which f appears in no more than n cards has at most n^2 - n + 1 cards.

Consider an arbitrary card containing f. By definition of f, none of the n elements of that card appears in more than n cards, and since each appears in that card the number of other cards is no more than n(n-1). Hence the deck cannot be larger than n(n-1) + 1.

Theorem

  The largest possible deck has an upper bound of max(n^2 - n + 1, floor((N-1) / (n-1))).

By combining the corollary and lemma 2.


Evaluate expressions with significant figures Given an expression, your task is to evaluate it. However, your answer cannot show more digits than necessary, as this gives the impression of having more precise measurements than reality.

The number of significant figures that a number has is how many digits it has when written in scientific notation, including zeros at the end if a decimal point is present. For example, 1200 has 2 significant figures because it is 1.2*10^3 but 1200. has 4 significant figures and 1200.0 has 5 significant figures.

When adding two numbers, the result should be rounded to the same number of places as the number whose least significant digit is furthest to the left. For example, 1200 + 3 = 1200 (rounded to the hundreds place since 1200 is rounded to the hundreds place), 1200.01 + 3 = 1203, and 4.59 + 2.3 = 6.9. Note that 5 rounds up. This same rule applies to subtraction. 0 is rounded to the ones place. Note that adding and subtracting do not depend on the number of significant digits. For example, 999 + 2.00 = 1001 because 999 is rounded to the ones place and 2.00 is rounded to the hundredths place; the one rounded to fewer places is 999, so the result, 1001.00, should be rounded to the ones place as well. Similarly, 300 + 1 - 300 is exactly equal to 1, but 300 is rounded to the hundreds place, so the final result should also be rounded to the hundreds place, giving 0. 300. + 1 - 300. would equal 1 on the other hand.

When multiplying or dividing two numbers, round to the number of significant digits of the number with the least significant digits. For example, 3.839*4=20 because the exact value, 15.356, rounds to 20 since 4 has only one significant figure. Similarly, 100/4=30 since both numbers have one significant figure, but 100./4.00=25.0 since both numbers have 3 significant figures. 0 is defined to have 1 significant figure.

Expressions will only contain *, /, +, and -, (and parentheses). Order of operations should be followed and results should be rounded after every operation. If parentheses are left out in a string of additions or subtractions or a string of multiplications and divisions, then round after all operations are completed. For example, 6*0.4*2 = 5 (one significant figure), while 0.4*(2*6)=0.4*10=4 and (6*0.4)*2=2*2=4.

Input: A string, with an expression containing ()*/+- and digits. To simplify things, - will only be used as a subtraction operator, not to signify negative numbers; answers, however, could still be negative and would require - as a prefix.

Output: The result of the expression, evaluated and rounded to the correct number of digits. Note that 25 is incorrect for 25.0.

Test cases:

3 + 0.5 --> 4
25.01 - 0.01 --> 25.00
4*7*3 --> 80
(4*7)*3 --> 90
(8.0 + 0.5)/(2.36 - 0.8 - 0.02) --> 5.7
6.0 + 4.0 --> 10.0
5.0 * 2.0 --> 10.0
1/(2.0 * (3.0 + 5.0)) --> 0.06
0.0020 * 129 --> 0.26
300 + 1 - 300 --> 0
0 - 8.8 --> -9
3*5/2*2 --> 20

Edge case: Consider the problem of 501*2.0. The exact value is 1002. Printing 1002 gives too many significant figures (4, when we need 2) but 1000 gives too few (1, when we need 2). In this case, your program should print 1000 anyway.

This source explains significant digits as well: http://www.purplemath.com/modules/rounding2.htm

Java 11, 1325 1379 1356 1336 1290 bytes

import java.math.*;String c(String s)throws Exception{String r="",T=r,a[],b[],z="\\.";int i=0,l,A[],M=0,m=s.length(),j,f=0,q=m;if(s.contains("(")){for(;i<m;){var c=s.charAt(i++);if(f<1){if(c==40){f=1;continue;}r+=c;}else{if(c==41&T.replaceAll("[^(]","").length()==T.replaceAll("[^)]","").length()){r+="x"+s.substring(i);break;}T+=c;}}return c(r.replace("x",c(T)));}else{for(a=s.split("[\\+\\-\\*/]"),A=new int[l=a.length];i<l;f=b.length>1&&(j=b[1].length())>f?j:f)M=(j=(b=a[i++].split(z))[0].length())>M?j:M;for(b=a.clone(),i=0;i<l;A[i]=b[i].contains(".")?j=b[i].length()-1:b[i].replaceAll("0*$","").length(),i++)for(q=(j=b[i].replace(".","").length())<q?j:q,j=a[i].split(z)[0].length();j++<M;)b[i]=0+b[i];double R=new Double(new javax.script.ScriptEngineManager().getEngineByName("JS").eval(s)+""),p;for(int x:A)m=x<m?x:m;m=m==M&R%1==0&(int)R/10%10<1&(j=(r=R+"").split(z)[0].length())>m?j-q>1?q:j:R>99?m:R%10==0?r.length()-1:m<1?1:m;R=new BigDecimal(R).round(new MathContext((R<0?-R:R)<1?m-1:m)).doubleValue();r=(m<M&(p=Math.pow(10,M-m))/10>R?(int)(R/p)*p:R)+"";l=r.length()-2;r=(r=f<1?r.replaceAll(z+"0$",""):r+"0".repeat(f)).substring(0,(j=r.length())<m?j:r.contains(".")?(j=r.replaceAll("^0\\.0+","").length())<m?m-~j:m+1:m);for(i=r.length();i++<l;)r+=0;return r.replaceAll(z+"$","");}}

+54 bytes to fix the edge case 501*2.0 (gave result 1002 before, but now correct 1000).
I now understand why this challenge was unanswered for almost two years.. >.> This challenge has more special cases than the Dutch language, which is saying something..
Java is certainly not the right language for these kind of challenges (or any codegolf challenge for that matter.. ;p), but it's the only language I know good enough to even attempt a difficult challenge like this.
Input format as String without spaces (if that is not allowed, you can add s=s.replace(" ","") (+19 bytes) at the top of the method).
Try it online.
Explanation:
Sorry for the long post.
if(s.contains("(")){
  for(;i<m;){
    var c=s.charAt(i++);
    if(f<1){
      if(c==40){
        f=1;
        continue;}
      r+=c;}
    else{
      if(c==41&T.replaceAll("[^(]","").length()==T.replaceAll("[^)]","").length()){
        r+="x"+s.substring(i);
        break;}
      T+=c;}}
  return c(r.replace("x",c(T)));}

This part is used for input containing parenthesis. It will get the separated parts and use recursive-calls.

0.4*(2*6) becomes 0.4*A, where A is a recursive call to c(2*6)
(8.3*0.02)+(1.*(9*4)+2.2) becomes A+B, where A is a recursive call to c(8.3*0.02) and B a recursive call to c(1.*(9*4)+2.2) → which in turn becomes 1.*C+2.2, where C is a recursive call to c(9*4)

for(a=s.split("[\\+\\-\\*/]"),A=new int[l=a.length];
    i<l;
    f=b.length>1&&(j=b[1].length())>f?j:f)
  M=(j=(b=a[i++].split(z))[0].length())>M?j:M;

This first loop is used to fill the values M and k, where M is the largest integer-length regarding significant figures and k the largest decimals-length.

1200+3.0 becomes M=2, k=1 (12, .0)
999+2.00 becomes M=3, k=2 (999, .00)
300.+1-300. becomes M=3, k=0 (300, .)

for(b=a.clone(),i=0;
    i<l;
    A[i]=b[i].contains(".")?j=b[i].length()-1:b[i].replaceAll("0*$","").length(),i++)
  for(q=(j=b[i].replace(".","").length())<q?j:q,
      j=a[i].split(z)[0].length();
      j++<M;)
    b[i]=0+b[i];

This second loop is used to fill the arrays A and b as well as value q, where A is the amount of significant figures, b hold the integers with leading zeroes to match M, and q is the lowest length disregarding dots.

1200+3.0 becomes A=[2, 5] (12, 00030), b=[1200, 0003.0], and q=2 (30)
999+2.00 becomes A=[3, 5] (999, 00200), b=[999, 002.00], and q=3 (both 999 and 200)
300.+1-300. becomes A=[3, 3, 3] (300, 001, 300), b=[300., 001, 300.], and q=1 (1)
501*2.0 becomes A=[3, 4] (501, 0020), b=[501, 002.0], and q=2 (20)

double R=new Double(new javax.script.ScriptEngineManager().getEngineByName("JS").eval(s)+"")

Uses a JavaScript engine to eval the input, which will be saved in R as double.

1200+3.0 becomes R=1203.0
999+2.00 becomes R=1001.0
300.+1-300. becomes R=1.0

for(int x:A)
  m=x<m?x:m;

This sets m to the smallest value in the array A.

A=[2, 5] becomes m=2
A=[3, 5] becomes m=3
A=[3, 3, 3] becomes m=3

 m=m==M                // If `m` equals `M`
   &R%1==0             // and `R` has no decimal values (apart from 0)
   &(int)R/10%10<1     // and floor(int(R)/10) modulo-10 is 0
   &(j=(r=R+"").split(z)[0].length())>m?
                       // and the integer-length of R is larger than `m`:
    j-q>1?             //  If this integer-length of `R` minus `q` is 2 or larger:
     q                 //   Set `m` to `q` instead
    :                  //  Else:
     j                 //  Set `m` to this integer-length of `R`
   :R>99?              // Else-if `R` is 100 or larger:
    m                  //  Leave `m` the same
   :R%10==0?           // Else-if `R` modulo-10 is exactly 0:
    r.length()-1       //  Set `m` to the total length of `R` (minus the dot)
   :m<1?               // Else-if `m` is 0:
    1                  //  Set `m` to 1
   :                   // Else:
    m;                 //  Leave `m` the same

This modifies m based on multiple factors.

999+2.00 = 1001.0 & m=3,q=3 becomes m=4 (because m==M (both 3) → R%1==0 (1001.0 has no decimal values) → (int)R/10%10<1 ((int)1001.0/10 becomes 100 → 100%10<1) → "1001".length()>m (4>3) → "1001".length()-q<=1 (4-3<=1) → so m becomes the length of the integer-part "1001" (4))
3.839*4 = 15.356 & m=1,q=1 stays m=1 (because m==M (both 1) → R%1!=0 (15.356 has decimal values) → R<=99 → R%10!=0 (15.356%10==5.356) → m!=0 → so m stays the same (1))
4*7*3 = 84.0 & m=1,q=1 stays m=1 (because m==M (both 1) → R%1==0 (84.0 has no decimal values) → (int)R/10%10>=1 ((int)84/10 becomes 8 → 8%10>=1) → R<=99 → R%10!=0 (84%10==4) → m!=0 → so m stays the same (1))
6.0+4.0 = 10.0 & m=2,q=2 becomes m=3 (because m!=M (m=2, M=1) → R<=99 → R%10==0 (10%10==0) → so m becomes the length of the total R (minus the dot) "10.0".length()-1 (3))
0-8.8 = -8.8 & m=0,q=1 becomes m=1 (because m!=M (m=0, M=1) → R<=99 → R%10!=0 (-8.8%10==-8.8) → m<1 → so m becomes 1)
501*2.0 = 1001.0 & m=3,q=2 becomes m=2 (because m==M (both 3) → R%1==0 (1001.0 has no decimal values) → (int)R/10%10<1 ((int)1001.0/10 becomes 100 → 100%10<1) → "1001".length()>m (4>3) → "1001".length()-q>1 (4-2>1) → so m becomes q (2))

R=new BigDecimal(R).round(new MathContext((R<0?-R:R)<1?m-1:m)).doubleValue();

Now R is rounded based on m.

1001.0 & m=4 becomes 1001.0
0.258 & m=3 becomes 0.26 (because abs(R)<1, m-1 (2) instead of m=3 is used inside MathContext)
-8.8 & m=1 becomes -9.0
1002.0 & m=2 becomes 1000.0

m<M&(p=Math.pow(10,M-m))/10>R?(int)(R/p)*p:R;

This modifies the integer part of R if necessary.

300.+1-300. = 1.0 & m=3,M=3 stays 1.0 (because m>=M → so R stays the same (1.0))
0.4*10 = 4.0 & m=1,M=2 stays 4.0 (because m<M → (10^(M-m))/10<=R ((10^1)/10<=4.0 → 10/10<=4.0 → 1<=4.0) → so R stays the same (4.0))
300+1-300 = 1.0 & m=1,M=3 becomes 0.0 (because m<M → (10^(M-m))/10>R ((10^2)/10>1.0 → 100/10>1.0 → 10>1.0) → so R becomes 0.0 because of  int(R/(10^(M-m)))*(10^(M-m)) (int(1.0/(10^2))*(10^2) → int(1.0/100)*100 → 0*100 → 0)

r=(...)+"";                  // Set `R` to `r` as String (... is the part explained above)
l=r.length()-2;              // Set `l` to the length of `R` minus 2
r=(r=k<1?                    // If `k` is 0 (no decimal values in any of the input-numbers)
      r.replaceAll(z+"0$","")
                             //  Remove the `.0` at the end
     :                       // Else:
      r+"0".repeat(f)
                             //  Append `k` zeroes after the current `r`
  ).substring(0,             // Then take the substring from index `0` to:
     (j=r.length())<m?       //  If the total length of `r` is below `m`:
       j                     //   Leave `r` the same
     :r.contains(".")?       //  Else-if `r` contains a dot
       (j=r.replaceAll("^0\\.0+","").length())<m?
                             //   And `R` is a decimal below 1,
                             //   and its rightmost decimal length is smaller than `m`
        m-~j                 //    Take the substring from index 0 to `m+j+1`
                             //    where `j` is this rightmost decimal length
       :                     //   Else:
        m+1                  //    Take the substring from index 0 to `m+1`
     :                       //  Else:
      m);                    //   Take the substring from index 0 to `m`

This sets R to r as String, and modifies it based on multiple factors.

1203.0 & m=4,k=2 becomes 1203. (because k>=1 → so r becomes 1001.000; r.length()>=m (8>=4) → r.contains(".") → r.length()>=m (8>=4) → substring from index 0 to m+1 (5))
6.9 & m=2,k=2 stays 6.9 (because k>=1 → so r becomes 6.900; r.length()>=m (5>=2) → r.contains(".") → r.length()>=m (5>=2) → substring from index 0 to m+1 (3))
1.0 & m=3,k=0 becomes 1 (because k<1 → so r becomes 1; r.length()<m (1<3) → substring from index 0 to r.length() (1))
25.0 & m=4,k=4 becomes 25.00 (because k>=1 → so r becomes 25.00000; r.length()>=m (8>=4) → r.contains(".") → r.length()>+m (8>=4) → substring from index 0 to m+1 (5))
0 & m=1,k=0 stays 0 (because k<1 → so r stays 0; r.length()>=m (1>=1) → !r.contains(".") → substring from index 0 to m (1))

for(i=r.length();i++<l;)
  r+=0;

This puts trailing zeroes back again to the integer part if necessary.

r="12" & R=1200.0 becomes r="1200"
r="1" & R=10.0 becomes r="10"
r="8" & R=80.0 becomes r="80"

return r.replaceAll(z+"$","");

And finally we return the result, after we've removed any trailing dots.

1203. becomes 1203
5. becomes 5

Can definitely be golfed by a couple hundred bytes, but I'm just glad it's working now. It already took a while to understand each of the cases and what was being asked in the challenge. And then it took a lot of trial-and-error, testing and retesting to get to the result above. And while writing this explanation above I was able to remove another ±50 bytes of unused code..


Words from periodic table of elements Back when I was a freshman in highschool taking chemistry, I'd look at the periodic table of elements and spell dirty words out with the number of the elements (HeCK would be 2619, 2-6-19).

I was thinking about this the other day when I saw an amazing shirt that spelled out BeEr (4-68)

So my codegolf challenge is shortest program to output a list of words you can spell with the periodic table of elements AND the number code that would represent that word.

/usr/share/dict/words or whatever dictionary you want to use for the word list. If you're using a "non-standard" word list, let us know what it is!

GolfScript (339 303 302 301 294 chars)

n/{{{32|}%}:L~['']{{`{\+}+'HHeLiBeBCNOFNeNaMgAl
PSClArKCa TiVCrMnFe

ZnGaGeAsSeBrKrRbSrYZr
MoTcRuRhPdAgCd

TeIXe
BaLaCePrNdPmSmEuGdTbDy
ErTm
Lu
TaWRe
IrPtAuHgTl

AtRnFrRaAcThPaU

AmCm

EsFmMd
LrRfDbSg

MtDsRg
UutFl
Lv'{[1/{.0=96>{+}*}/]}:S~:^/}%.{L}%2$?.){=S{^?}%`+p 0}{;{L.,2$<=},.}if}do}%;

With credit to PhiNotPi whose observation on unnecessary elements allowed me to save 33 chars.

This is IMO much more idiomatic GolfScript than the previous recursive approach.

Note that I allow words in the dictionary to be mixed case (L is a function to lower-case text on the assumption that it doesn't matter if non-alpha characters get broken) but reject any with apostrophes or accents.

Since this is code golf, I've optimised for code length rather than speed. This is horrendously slow. It expects the word list to be supplied at stdin and outputs to stdout in the format:

"ac[89]"
"accra[89 6 88]"
"achebe[89 2 4]"
...

(lower-casing any mixed-case input words for which it finds a match).

If you're more interested in the elements than the numbers per se, for the low low price of 261 253 chars you can use

n/{{{32|}%}:L~['']{{`{\+}+'HHeLiBeBCNOFNeNaMgAlPSClArKCaTiVCrMnFeZnGaGeAsSeBrKrRbSrYZrMoTcRuRhPdAgCdTeIXeBaLaCePrNdPmSmEuGdTbDyErTmLuTaWReIrPtAuHgTlAtRnFrRaAcThPaUAmCmEsFmMdLrRfDbSgMtDsRgUutFlLv'[1/{.0=96>{+}*}/]/}%.{L}%2$?.){=p 0}{;{L.,2$<=},.}if}do}%;

which gives output like

"Ac"
"AcCRa"
"AcHeBe"
...


All ASCII characters with a given bit count (Title with thanks to @ChasBrown)

Sandbox

The Background

This challenge is inspired by a question that I recently posted on Puzzling Stack Exchange. Please feel free to follow the link if you are interested in the original question. If not then I won't bore you with the details here.

The Facts

Every printable standard ASCII character has a decimal value between 32 and 126 inclusive. These can be converted to their corresponding binary numbers in the range 100000 to 1111110 inclusive. When you sum the bits of these binary numbers you will always end up with an integer between 1 and 6 inclusive.

The Challenge

Given an integer between 1 and 6 inclusive as input, write a program or function which will output in any acceptable format all of the printable standard ASCII characters where the sum of the bits of their binary value is equal to the input integer.

The Examples/Test Cases

1 -> ' @'
2 -> '!"$(0ABDHP`'
3 -> '#%&)*,1248CEFIJLQRTXabdhp'
4 -> ''+-.3569:<GKMNSUVYZ\cefijlqrtx'
5 -> '/7;=>OW[]^gkmnsuvyz|'
6 -> '?_ow{}~'

An ungolfed Python reference implementation is available here (TIO).

The Rules

Assume the input will always be an integer (or string representation of an integer) between 1 and 6 inclusive.
You may write a program to display the results or a function to return them.
Output may be in any reasonable format but must be consistent for all inputs. If you choose to output a quoted string then the same type of quotes must be used for all inputs.
Standard loopholes prohibited as usual.
This is code golf so shortest code in each language wins.

8088 assembly, IBM PC DOS, 35 30 29 bytes
Machine code:
be81 00ad 8afc b330 b108 d0c8 12dd e2fa 3afb 7504 b40e cd10 fec0 79ea c3

Listing:
BE 0081     MOV  SI, 081H   ; SI = memory address of command line string
AD          LODSW           ; AL = start ASCII value (init to 20H from space on cmd line)
8A FC       MOV  BH, AH     ; BH = target number of bits (in ASCII)
        CHR_LOOP:
B3 30       MOV  BL, '0'    ; BL = counter of bits, reset to ASCII zero
B1 08       MOV  CL, 8      ; loop through 8 bits of AL
        BIT_LOOP:
D0 C8       ROL  AL, 1      ; rotate LSB of AL into CF
12 DD       ADC  BL, CH     ; add CF to BL (CH is always 0)
E2 FA       LOOP BIT_LOOP   ; loop to next bit
3A FB       CMP  BH, BL     ; is current char the target number of bits?
75 04       JNE  NO_DISP    ; if not, do not display
B4 0E       MOV  AH, 0EH    ; BIOS write char to screen function
CD 10       INT  10H        ; display ASCII char in AL (current char in loop)
        NO_DISP:
FE C0       INC  AL         ; increment char to next ASCII value
79 EA       JNS  CHR_LOOP   ; if char <= 127, keep looping
C3          RET             ; return to DOS

Standalone PC DOS executable program, input number from command line.  Output is displayed to console window.

Download and test ABCT.COM (AsciiBitCounT).


Tips for golfing in SmileBASIC SmileBASIC deserves more attention. I've only seen 3 users here (including myself!) providing SB answers, and while that doesn't surprise me, it disappoints me. It being a paid lang as well as being a BASIC dialect certainly turns people off, but for those who own it it's actually pretty flexible and, surprisingly, golfable. I figured I'd open this tips thread for it and see what comes up.

I expect 12Me21 to visit frequently :)

Replace string!="" with string>""

SB allows you to do greater/less comparisons on strings, based on their codepoints. However, the empty string is considered the smallest string there is.

So for situations where you do string!="" you can use either string>"" or ""<string, since every string is greater than "" and "" is less than every string. Depending on whether you use < or > depends on if the statement needs whitespace before or after to be valid syntax, which can also save you bytes.

For example:

WHILE S$!=""

can be turned into

WHILE S$>""

and further golfed to

WHILE""<S$


Hast Thou Slain the Jabberwock? Your task is to output the exact string

The Jabberwocky

without taking input.  Normal rules for input and output apply, so both functions and programs are allowed.

Of course there is a catch, it wouldn't be fun without a catch.  Your program, when stripped of non-alphabetic characters, must start the poem The Jabberwocky (case insensitive).  To start the poem it must be a continuous substring of the poem starting at the beginning.  The empty string is fine (although you probably won't score very well).

Here is the text for reference:

twasbrilligandtheslithytovesdidgyreandgimbleinthewabeallmimsyweretheborogovesandthemomerathsoutgrabebewarethejabberwockmysonthejawsthatbitetheclawsthatcatchbewarethejubjubbirdandshunthefrumiousbandersnatchhetookhisvorpalswordinhandlongtimethemanxomefoehesoughtsorestedhebythetumtumtreeandstoodawhileinthoughtandasinuffishthoughthestoodthejabberwockwitheyesofflamecamewhifflingthroughthetulgeywoodandburbledasitcameonetwoonetwoandthroughandthroughthevorpalbladewentsnickersnackheleftitdeadandwithitsheadhewentgalumphingbackandhastthouslainthejabberwockcometomyarmsmybeamishboyofrabjousdaycalloohcallayhechortledinhisjoytwasbrilligandtheslithytovesdidgyreandgimbleinthewabeallmimsyweretheborogovesandthemomerathsoutgrabe

Here is a program you can use to test this property.

If you run out of poem to use you may not use any additional alphabetic characters.

Alphabetic characters are characters a-z and A-Z here is the complete list:

ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz

Scoring

Your program will be scored in the number of non-alphabetic bytes used with fewer being better.

Here is a Haskell program that scores answers. (This assumes inputs are valid)

Example program

The following program would be valid:

twas&*brilliga77812nd Thesli thyt Oves didgy reand Gim bleinth ewab eal lmims ywe""""""""
ret h eb or o g o ve sa n dthemomerAthsoutgrabebewaretheJABBERWOCKmysonthe)(*)()((*98980908(()*(jawsthatbit

When stripped down to alphabetic characters it is:

twasbrilligandTheslithytOvesdidgyreandGimbleinthewabeallmimsyweretheb orogovesandthemomerAthsoutgrabebewaretheJABBERWOCKmysonthejawsthatbit

Which matches the first bit of the poem (case insensitive).

This program would score 59 because it contains these non-alphabetic characters:

&*77812           """"""""
          )(*)()((*98980908(()*(

oOo CODE, score 0

Thanks to Dennis for golfing the Brainfuck code.

TwASbRIlLIgAnDthEsliTHyTOvEsdiDgyreaNdgImbleinthEwaBeaLlmimSywEreThEBoroGoveSAndTheMOmERaTHSoutGRabEbeWArEthEjaBbeRWockMYsONtHEJawsTHaTBiTEThecLawSthATcaTChBeWAReTHeJuBJuBBiRDAndsHUNtHeFRuMIoUSbANdERSnatchheTooKHisvORpaLswORdinhAndLonGtiMetHEmanXomEFoEHeSOUg

Try it online!

I've got bad news for this challenge... :(

oOo CODE is just a binary encoding of brainfuck which uses the case of a letter for each bit. So yeah, since the poem is long enough (or the output short enough) to cover a Brainfuck program that prints The Jabberwocky (without actually trying hard to golf it), this becomes a trivial optimal answer.


Is the graph acyclic? A Directed Acyclic Graph (DAG) is a type of graph that has no cycles in it. In other words, if there is a link from node A to node B, there exists no path from B to A (via any nodes).

Challenge

Determine whether the directed graph given as input is acyclic.

Input

A list of lists of integers representing the links between nodes, where a node is identified by its index in the list.

Output

Standard I/O for decision problems; generally a truthy value for acyclic graphs, and a falsy one for cyclic graphs. Additionally, your program may halt/not halt to indicate truthy and falsy, if you wish.

Test Cases

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

Represents the following graph (where all edges are directed downwards):

        0
      /   \
     1     2
    / \   /
   3  4  5
      | /
      6

This example is acyclic, so the result should be truthy.

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

Represents the following graph:

 -----<-----<----
/                \
0 --> 3 --> 1 --> 2
 \---->----/

This example is cyclic, so the result should be falsey. (Sorry for my terrible drawing; if this is unclear let me know.)

Constraints

No input will ever be invalid; i.e. no node will link to a node that does not exist
Self loops must be handled ([[0]] is a cyclic graph)

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


Plz Halp, Need Investors ASAP Bob has a startup that is developing a product that uses “advanced AI” and “black magic” to automatically code-golf computer programs. Unfortunately, Bob is running out of cash and desperately needs money from investors to keep his company running. Each investor that Bob has contacted wishes to schedule a meeting with a certain start and end time. However, some of meeting times conflict with each other. Bob wishes to meet with as many investors as possible so he can raise the largest amount of money. How many investors can Bob meet with, given that Bob can only meet with one investor at a time?
Input Format
Input is given as an array of pairs (or the equivalent in your chosen language). Each pair p represents one investor, where p[0] is the start time of the investor’s meeting and p[1] is the end time.
For example, in the test case [(0,10),(5,10),(12,13)], there are three investors: one who wants to meet from time 0 to time 10, one who wants to meet from time 5 to time 10, and one who wants to meet from time 12 to time 13. Meetings will always have a positive duration, and a meeting that ends at time k does not conflict with a meeting that starts at time k.
You may use any reasonable I/O method for input.
Test Cases
[(0,10),(5,10),(12,13)] => 2 (investors 1 and 3)

[(10,20),(10,20),(20,30),(15,25)] => 2 (investors 1 and 3)

[(0,3),(1,5),(1,5),(1,5),(4,9),(6,12),(10,15),(13,18),(13,18),(13,18),(17,19)] => 4 (investors 1,5,7 and 11)

[(1,1000),(1,2),(2,3),(3,4),(4,5),(5,6),(6,7)] => 6 (every investor except the first)

[(1,2),(101,132),(102,165),(3,9),(10,20),(21,23),(84,87)] => 6 (investors 1,2,4,5,6,7)

Output
Your program should output an integer, the maximum number of investors that Bob can meet with.
Standard loopholes are prohibited. This is code-golf, so the shortest solution in each language wins.

Python 2, 53 52 bytes
Based on xnor's answer.
-1 byte thanks to dingledooper!

f=lambda l,t=0:-min([a<t or~f(l,b)for a,b in l]+[0])

Try it online!
This is a recursive function which takes 2 arguments:

l: a list of all offered meetings
t: the time our last meeting ended (initially 0)

The list comprehension iterates over all offered meetings (a, b).
If the meeting starts before our last meeting ended (a<t), a<t or ... evaluates to True, which is basically the same as 1 in Python.
Otherwise f(l,b) is called to see how much more meetings we can fit in if we take the current meeting. The bitwise inverted value of this gets into the list.
If a<t was false for any meeting (a, b) in the comprehension, min returns the smallest of all possible ~f(l,b) values. Then -min(...) returns -~f(l,b)==1+f(l,b) for some meeting.
Otherwise -min(...) is equal to 0.

47 bytes if we can assume that the input is not empty:

f=lambda l,t=0:1-min(a<t or-f(l,b)for a,b in l)

Try it online!


Output a binary path from a number For an integer n that satisfies n > 0, write its value as a right-descending path based on its binary representation.

Rules

The first (most significant) set bit is always in the top-left corner.
When the next bit is set (a 1), draw a character ("filled") on the next line in the same column as the previous character drawn. Try to use spaces ("empty") to fill, but any character will do as long as it's always the same.
When the next bit is unset (a 0), draw a character ("filled") on the same line immediately to the the right of the previous character drawn.
Your code must support numbers with at least 20 significant bits.
Write a full program, a function, a lambda, etc. but no snippet.
No leading spaces (or "empty" char) / lines allowed
Any number of trailing spaces (or "empty" char) / lines allowed
Any kind of 1D input is accepted: number, string, array of booleans, etc. Keep the order of bits untouched though.
Any kind of visual 2D output is accepted: on stdout, a string (with any two distinct values representing "filled" and "empty"), you can even output a matrix if you want. A list of numbers seems hard to reconcile with the "no heading spaces" rule, but I'm open to it if you find a way to use it. Note: if you chose to print or return a string, the characters used must be ASCII characters in the codepoints range [32-126].
Standard loopholes are banned.
This is codegolf so the shortest code wins.

Examples

Input: 1

*

Input: 2

**

Input: 3

*
*

Input: 4

***

Input: 5

**
 *

Input: 6

*
**

Input: 7

*
*
*

Input: 25

*
***
  *

Input: 699050

**
 **
  **
   **
    **
     **
      **
       **
        **
         **

Input: 1047552

*
*
*
*
*
*
*
*
*
***********

Input: 525311

**********
         *
         *
         *
         *
         *
         *
         *
         *
         *
         *

MATL, 14 bytes

J_iB^YsJ+'o-'&XG

Produces graphical output as a path starting at coordinates (0,0). Try it at MATL Online! Or see some offline examples below:

Input 7:

Output:

Input 699050:

Output:

If you prefer, you can see the path as complex coordinates for 9 bytes:

J_iB^YsJ+

Try it online!

Explanation

J_      % Push -1j (minus imaginary unit)
i       % Push input number
B       % Convert to binary. Gives an array of 0 and 1 digits
^       % Power, element-wise. A 0 digit gives 1, a 1 digit gives -1j
Ys      % Cumulative sum. Produces the path in the complex plane
J+      % Add 1j, element-wise. This makes the complex path start at 0
'o-'    % Push this string, which defines plot makers
&XG     % Plot


Generate alphabet with 4 copies of each letter Note that this is not the same as Print the alphabet four times.

This task is to write a program to generate four copies of each letter of the English alphabet, one letter per line, on standard output:

A
A
A
A
B
B
B
B

etc.

The output should include newlines after each letter.

Uppercase letters with no extra output are preferred; however, lowercase letters and/or extra whitespace are acceptable if capitalizing/stripping would lengthen your solution.

EDITED TO ADD: The solution must be complete enough to execute.  I should be able to invoke an implementation of the language, paste the code from the answer, and get results, without typing any additional code.

The above question of completeness came up in the context of a C solution. Surely there must be a standing rule or convention about this on a code golfing site?  If so, I'll gladly yield to the community guidelines.  But this is my take:

With regard to C specifically, you need to include (and count) the main(){...} around the code, since it won't compile otherwise.  Warnings because there's no #include <stdio.h> are fine as long as the code still compiles. In general, a compiled language requires a compilable unit.
A bare expression that yields the desired results is acceptable if there's a way to execute the expression directly; for instance, if the language has a REPL. So you can submit Haskell without a main= as long as it actually works as written at e.g. the ghci prompt. But since that means putting let on your declarations, it may be a net win to stick with the runhaskell format.
Similarly, awk scripts should be in BEGIN (or END, with the assumption that stdin is attached to /dev/null) blocks since we're not processing any input.

etc.

APL (5)

⍪4/⎕A

Matrix format (⍪) of 4-replication (4/) of alphabet (⎕A).


Generate lazy microwave input Related: Program my microwave oven and Generate lazy values.

My colleague is so lazy that he doesn't even bother to move his finger when programming the microwave oven. (This is actually true!)

Help him find the microwave input that gives the time closest to what he wants, but where all digits are the same. If two inputs result in the same time difference from the desired time, choose the one with fewer digits. If both have the same number of digits, choose the lesser – so he doesn't have to wait so long.

Input is the integer that a perfectionist would enter, e.g. 430 is 4 minutes and 30 seconds while 100 and 60 each is 1 minute. It will be greater than 0 and will not exceed 9999.

Output must an integer, e.g. 444 is 4 minutes and 44 seconds and 55 is 55 seconds.

Both input and output may only be in simple seconds (no minutes) if the total time is below 1 minute and 40 seconds.

This is code-golf, so your code must be as short as possible.

Test cases:

  30 →   33
  60 →   55
  70 →  111
  90 →   88
 100 →   55
 101 →   66
 120 →   77
 130 →   88
 200 →   99
 201 →  222
 500 →  444
 700 →  666
1000 →  888
1055 →  999
1056 → 1111
1090 → 1111

Jelly, 26 bytes

bȷ2ḅ60
³ÇạÇ,
9Rẋ€4R¤ḌFÇ€ṂṪ

Explanation:

bȷ2ḅ60             f(x) = x tobase 100 frombase 60
³ÇạÇ,              g(x) = (abs(f(arg) - f(x)), x)
9Rẋ€4R¤            main(arg) = [1..9] repeat each with [1..4],
       ḌF           then get digits and flatten,
         Ç€         then map g,
           Ṃ        then minimum,
            Ṫ       then last element.

Try it online!