Golf Practice: Python This is a challenge of practicing golf optimization in Python -- reusable tricks and shortcuts to shave off a few characters. Many will be familiar to Python golfers and use common ideas from the Python Tips. Some of these use Python-specific features that you might not know exist unless you've seen them, so do take a look at the tips if you're stuck.

Goal:
 There are ten problems, each a reference snippet of Python code for you to optimize and a description of the code does. Your goal is rewrite it to be shorter but still functionally-equivalent.

Your score, which you're trying to minimize, is the total length of your code all the snippets. The length of the reference snippets is 150. Tiebreaker is earliest post.

Posting answers: For each problem, post your code and its character count. You can post the reference snippet if you didn't find something shorter. It's intended that you don't look at others' answers when you post yours. Please spoiler-tag each individual problem including the individual character counts. You can leave the total count revealed. Feel free now to unspoiler your solution or post new unspoilered solutions.

Details on legality: Functional equivalence means the code can be replaced in a program without affecting its behavior (ignoring things like memory usage and operator precedence as part of an expression). Expressions should produce values that are equivalent by ==. Note that 1.0==1==True. Your code should have no side-effects unless otherwise stated. I don't intend the problems to be version-specific, but just in case, you can specify a Python version for each problem.

Problem 1: Keep iterating as long as the list L has at least 7 elements

# 16 chars
while len(L)>=7:

Problem 2: Check whether two floats x and y are both positive.

# 11 chars
x>0 and y>0

Problem 3: If Boolean b is true, remove the first element of L. Otherwise, leave it unchanged.

# 12 chars
if b:L=L[1:]

Problem 4: Check if all elements of a non-empty list L of numbers are equal. For this problem, it's OK to modify the list.

# 22 chars
all(x==L[0]for x in L)

Problem 5: Append a number n to the end of a list L only if L already contains that number.

# 16 chars
if n in L:L+=[n]

Problem 6: Express the sign of a float x: +1 for positive, 0 for 0, -1 for negative.

# 20 chars
abs(x)/x if x else 0

Problem 7 Continue a loop as long as the first element of L, a list of Booleans, is True. Also stop if L is empty.

# 17 chars
while L and L[0]:

Problem 8: Continue a loop as long as n is greater than 1. The number n is guaranteed to be a positive integer.

# 10 chars
while n>1:

Problem 9: Check if an integer represented as a string s is negative (i.e, starts with '-').

# 9 chars
s[0]=='-'

Problem 10: Convert a Boolean b to "Win"/"Lose", with True->"Win" and False->"Lose".

# 17 chars
["Lose","Win"][b]

Warning: Spoilers below, don't scroll down if you want to solve these yourself.

If you just want to know the optimal score for a problem:

Problem 1:

  12

Problem 2:

  5

Problem 3:

  7

Problem 4:

  13

Problem 5:

  13

Problem 6:

  8

Problem 7:

  12

Problem 8:

  9

Problem 9:

  5

Problem 10:

  15

Total: 104 101 99 chars

Problem 1

   12 chars
 while L[6:]:

Problem 2

   5 chars
 x>0<y

Problem 3

   7 chars
 L=L[b:]

Problem 4

   13 chars
 len(set(L))<2
 L[1:]==L[:-1]

Problem 5

   13 chars
 L+=set(L)&{n}

Problem 6

   11 chars
 (x>0)-(x<0)

 8 chars (Python 2)
 cmp(x,0)

Problem 7

   12 chars
 while[.5]<L:

Problem 8

   9 chars
 while~-n:

Problem 9

   5 chars
 s<'.'

Problem 10

   15 chars
 'LWoisne'[b::2]


Generalised Taxicab Numbers \$\newcommand{T}[1]{\text{Ta}(#1)} \newcommand{Ta}[3]{\text{Ta}_{#2}^{#3}(#1)} \T n\$ is a function which returns the smallest positive integer which can be expressed as the sum of 2 positive integer cubes in \$n\$ different ways. For example, \$\T 1 = 2 = 1^3 + 1^3\$ and \$\T 2 = 1729 = 1^3 + 12^3 = 9^3 + 10^3\$ (the Hardy-Ramanujan number).
Let's generalise this by defining a related function: \$\Ta n x i\$ which returns the smallest positive integer which can be expressed as the sum of \$x\$ \$i\$th powers of positive integers in \$n\$ different ways. In this case, \$\T n = \Ta n 2 3\$ (note: this is the same function here, \$\Ta n x i = \text{Taxicab}(i, x, n)\$)
Your task is to take 3 positive integers \$n, x\$ and \$i\$ and return \$\Ta n x i\$. This is code-golf so the shortest code in bytes wins.
In case \$x = 1 \$ and \$ n > 1\$, your program can do anything short of summoning Cthulhu, and for other cases where \$\Ta n x i\$ is not known to exist (e.g. \$\Ta n 2 5\$), the same applies.
Test cases
n, x, i -> out
1, 1, 2 -> 1
1, 2, 3 -> 2
2, 2, 2 -> 50
2, 2, 3 -> 1729
3, 3, 2 -> 54
3, 3, 3 -> 5104
2, 6, 6 -> 570947
2, 4, 4 -> 259
6, 4, 4 -> 3847554
2, 5, 2 -> 20
2, 7, 3 -> 131
2, 5, 7 -> 1229250016
5, 8, 4 -> 4228

Properties of \$\Ta n x i\$

\$\forall i : \Ta 1 x i = x\$ as \$x = \underbrace{1^i + \cdots + 1^i}_{x \text{ times}}\$
\$\Ta n 1 i\$ does not exist for all \$n > 1\$
\$\Ta n 2 5\$ is not known to exist for any \$n \ge 2\$

This is a table of results \$\{\Ta n x i \:|\: 1 \le n,x,i \le 3 \}\$, ignoring \$\Ta 2 1 i\$ and \$\Ta 3 1 i\$:
$$\begin{array}{ccc|c}
n & x & i & \Ta n x i \\
\hline
1 & 1 & 1 &  1 \\
1 & 1 & 2 &  1 \\
1 & 1 & 3 &  1 \\
1 & 2 & 1 &  2 \\
1 & 2 & 2 &  2 \\
1 & 2 & 3 &  2 \\
1 & 3 & 1 &  3 \\
1 & 3 & 2 &  3 \\
1 & 3 & 3 &  3 \\
2 & 2 & 1 &  4 \\
2 & 2 & 2 &  50 \\
2 & 2 & 3 &  1729 \\
2 & 3 & 1 &  5 \\
2 & 3 & 2 &  27 \\
2 & 3 & 3 &  251 \\
3 & 2 & 1 &  6 \\
3 & 2 & 2 &  325 \\
3 & 2 & 3 &  87539319 \\
3 & 3 & 1 &  6 \\
3 & 3 & 2 &  54 \\
3 & 3 & 3 &  5104 \\
\end{array}$$

05AB1E, 15 bytes
∞.ΔL¹m²ã€{ÙOy¢Q

Try it online!
This is really slow, inserting ¹zmï after .Δ limits the search space significantly: Try it online!
Commented:

                # Inputs ¹=i, ²=x, ³=n
∞.Δ             # find the first natural number k that satisfies:
   L            #   each of the range [1..k]
    ¹m          #   raised to the i-th power
      ²ã        #   take the list to the x-th cartesian power
        €{      #   sort each x-tuple
          Ù     #   deduplicate the tuples
           O    #   sum each x-tuple
            y¢  #   count the number of k's
              Q #   is this equal to the last input?

ã€{Ù does the same as Python's itertools.combinations_with_replacement, but there doesn't seem to be a builtin for this in 05AB1E.


Lights out, 7-segment version Given a 7-segment display with some segments switched on and some off, find a sequence of digits (0-9), such that after toggling the corresponding segments for each digit, all segments are switched off.

Example

  _
  _    [3] =>     |   [1] =>    [OFF]
  _               |

Numbers and their corresponding segments:

 _         _   _         _    _    _    _    _
| |    |   _|  _|  |_|  |_   |_     |  |_|  |_|
|_|    |  |_   _|    |   _|  |_|    |  |_|   _|

Rules

Codegolf ⊨ shortest entry wins.

Input

A non-empty list of segments which are switched on, given as

A sequence of numbers. Segments are numbered from top to bottom, left to right; starting from 0 or 1. Numbers need not be in order.
A single 7-bit digit. MSB/LSB not specified (thus you can choose).

Non-numeric characters between numbers are allowed (but not required to be supported).

Eg. for number 7: 136 or 1010010 or 0100101

Output

A sequence of numbers to be "applied" to the display. Not restricted in any way, such as order of the digits. Eg. for initial state corresponding to number 1, valid outputs would be 1, 111, 010, etc.

An alternative output is a 10-bit digit (again, MSB/LSB is your choice). Eg. for 1 as input, the output would be 1000000000 or 0000000001.

Some combinations have several non-repetitive solutions, eg. segments corresponding to the uppercase letter H can be switched off by 013, but also 489 and 0258.

If no solution exists (which I believe is not possible), the output is empty.

Jelly, 26 25 bytes
2ṗ⁵’µ×“wØ][:koR¶{‘^/=µÐfḢ

Try it online!
Takes input as a 7-bit integer. Returns the binary form of a 10-bit integer.
This just brute forces all possibilities. Remove the Ḣ to get all possible outputs or replace it with an X to get a random possible output.
Magic Visualization Program!
How it works
2ṗ⁵’µ×“wØ][:koR¶{‘^/=µÐfḢ  - main link, takes one integer
2ṗ⁵’                       - generate all length-10 binary arrays
    µ                µÐf   - now we find those arrays which correspond to digit-
                              sequences which work to switch off all segments:
                              Filter (keep) those arrays which:
     ×                      - multiplied by
      “wØ][:koR¶{‘          - [119, 18, 93, 91, 58, 107, 111, 82, 127, 123]
                               (encoding for turned-on segments given number)
                  ^/        - reduced by XOR
                    =      - are equal to (implicit) the program's input
                        Ḣ  - output the first of these valid arrays


Find the smallest positive integer which has all integers from 1 to n as factors The question's pretty much described by the title: write a program or function that takes a positive integer n as input, and returns the smallest positive output which has all integers from 1 to n as factors. (Another way of looking at this is that you're looking for the least common multiple of the integers from 1 to n.)

This is a code-golf challenge, so the shortest entry in bytes wins.

Inspired by this challenge. (This challenge is basically the inverse of that one.)

Test cases

Input: 1; Output: 1
Input: 6; Output: 60
Input: 19; Output: 232792560
Input: 22; Output: 232792560

You don't need to worry about integer precision issues (unless your language has integers so small that this would trivialise the problem). If your language does have bignums, though, you might also want to test your program on this case, just for fun:

Input: 128; Output: 13353756090997411579403749204440236542538872688049072000

Python, 46 bytes

g=lambda n,c=0:n<1or(c%n<1)*c or g(n,c+g(n-1))

Take that, past xnor!

50 bytes:

g=lambda n,i=1:n<1or(i*n%g(n-1)<1)*i*n or g(n,i+1)

I apparently golfed this problem 5 months ago, and I don't remember how this code works or why I golfed it. I think I have a golfing problem.

(Edit: It's from this answer. Thanks to Dennis for inspiring the solution and saving 4 bytes.)

Apparently, this code recursively finds lcm(1..n) as lcm(lcm(1..n-1),n). So, the function g expresses g(n) as the smallest positive multiple i*n of n that's also a multiple of g(n-1). (It could instead search multiples of g(n-1) for multiples of n, but this is golfier because g(n-1) only needs to be referenced once. Thanks to Dennis for this improvement.)

Here's the rest of the file, full of other golfing attempts:

f=lambda a,b:a and f(b%a,a)or b
g=lambda n:reduce(lambda a,b:a*b/f(a,b),range(1,n+1))

f=lambda a,b:a and f(b%a,a)or b
g=lambda n:n==1 or n*g(n-1)/f(n,g(n-1))

import math
g=lambda n:n==1 or n*g(n-1)/math.gcd(n,g(n-1))

g=lambda n,k=1:k*all(k%~i==0for i in range(n))or g(n,k+1)
g=lambda n,k=1:min(k%~i for i in range(n))and g(n,k+1)or k

l=lambda a,b:a%b and l(b,a%b)*a/(a%b)or a
g=lambda n:n<1or l(n,g(n-1))

g=lambda n,i=1:n==0 or (g(n-1)*i if g(n-1)*i%n==0 else g(n,i+1))

g=lambda n,i=1:n<1or g(n-1)*i*(g(n-1)*i%n<1)or g(n,i+1)

g=lambda n,i=1:n<1or(i*g(n-1)%n<1)*i*g(n-1)or g(n,i+1)

g=lambda n,r=1,c=1:r if n<2 else (g(n-1,r,r)if r%n==0 else g(n,r+c,c))

g=lambda n,r=1,c=1:r*(n<1)or r%n and g(n,r+c,c)or g(n-1,r,r)

g=lambda n,i=1:n<1or(i*g(n-1)%n or i)*g(n-1)or g(n,i+1)

def g(n):
 if n==0:return 1
 a=b=g(n-1)
 while b%n:b+=a
 return b

g=lambda n,i=1:n<1or g(n-1)*i%n and g(n,i+1)or g(n-1)*i

g=lambda n:n<1or min(range(n,3**n,n),key=g(n-1).__rmod__)

g=lambda n,i=1:n<1or(i*n%g(n-1)<1)*i*n or g(n,i+1)

r=n=input()
while n:
 c=r
 while r%n:r+=c
 n-=1
print r

r=n=input()
while n:
 c=r
 while r%n:r+=c
 n-=1
print r

r=1
for n in range(input()):
 c=r
 while r%~n:r+=c
print r

r=n=input()
while n:
 exec"r+=c*(r%n>0);"*n
 n-=1;c=r
print r

r=n=input();exec("r+=r%n and c;"*n+"n-=1;c=r;")*n;print r

It's eerie looking at my own past work. In trying to golf it, I keep thinking "maybe I can save some bytes by ..." and then seeing there's already a piece of code that attempted to do just that.

You think you've thought of everything, past xnor? Well, I'll show you!


Maximize order of operations Here's a problem to which I don't know the answer. Suppose you have an ordered list of integers with an operator in between each consecutive pair. Let's restrict ourselves to three operations that are closed over the integers, namely addition, multiplication and subtraction. Is there a good way to find the order we should perform the operations such that the expression evaluates to the maximum value?

For example, given the input 5 * 5 - 3 + 8 * -2 the correct order is to first perform the addition leading to 5 * 5 - 11 * -2, then perform the last multiplication leading to 5 * 5 - -22, then perform the subtraction leading to 5 * 27, then perform the final multiplication giving 135, which is maximal.

The question is: does there exist a reasonably efficient way to find this answer? I can see some tricks that might help a little, but I can also see some roadblocks.

Here's a program in python that computes the solution in the dumb recursive O(2^n) fashion. It might be helpful to check answers.

def find_max(x):
    if len(x) == 1:
        return x[0]
    y = [find_max(contract(x, i)) for i in xrange(len(x)//2)]
    return max(y)

def contract(x, i):
    return x[:2*i] + [do_op(*x[2*i:2*i + 3])] + x[2*i + 3:]

def do_op(left, op, right):
    return {"+": left + right, "-": left - right, "*": left * right}[op]

init = [int(x) if i%2 == 0 else x for i,x in enumerate(raw_input().split())]
print find_max(init)

Usage: python findmax.py < in.txt where in.txt contains a sequence like 4 * -3 + 6 - 2 * 10.

Is there a significantly faster way?

Haskell, O(n3)

import Data.Array

data Op = Plus | Minus | Times

exampleTerms :: [Integer]
exampleTerms = [5, 5, 3, 8, -2]

exampleOps :: [Op]
exampleOps = [Times, Minus, Plus, Times]

main = print $ maximalOrder exampleTerms exampleOps

type MinMax = (Integer, Integer)

-- Given an operator and minimal/maximal values for left- and right-hand sides,
-- compute the minimal/maximal value of the expressions joined together with this operator.
combine :: Op -> MinMax -> MinMax -> MinMax
combine Plus  (lmin, lmax) (rmin, rmax) = (lmin + rmin, lmax + rmax)
combine Minus (lmin, lmax) (rmin, rmax) = (lmin - rmax, lmax - rmin)
combine Times (lmin, lmax) (rmin, rmax) = (minimum ps, maximum ps)
    where ps = [lmin * rmin, lmin * rmax, lmax * rmin, lmax * rmax]

maximalOrder :: [Integer] -> [Op] -> Integer

maximalOrder []    _                 = error "maximalOrder: No terms"
maximalOrder terms ops
    | length terms /= length ops + 1 = error "maximalOrder: Mismatched terms/ops lists."

maximalOrder terms ops = snd $ minMax 0 (termCount - 1) where
    termCount :: Int
    termCount = length terms

    termsA :: Array Int Integer
    termsA = array (0, termCount-1) $ zip [0..] terms

    opsA :: Array Int Op
    opsA = array (0, termCount-2) $ zip [0..] ops

    dp :: Array (Int, Int) MinMax
    dp = array ((0,0), (termCount-1,termCount-1))
         [((start, end), minMax start end)
             | start <- [0..termCount-1], end <- [start..termCount-1]]

    minMax :: Int -> Int -> MinMax
    minMax start end
        | start == end =
            let x = termsA ! start
            in (x,x)
        | otherwise =
            let xs = [combine (opsA ! i) (dp ! (start,i)) (dp ! (i+1,end)) | i <- [start..end-1]]
            in (minimum (map fst xs), maximum (map snd xs))

This computes the minimal and maximal values of every substring in the expression, by going through each intervening operator and finding the minimal/maximal result of treating that operator as the root of the expression.  It collects these results into the overall minimal and maximal values for this substring.

This algorithm runs in O(n3) time and uses O(n2) space.  Finding the minimal/maximal value of an expression string, once its substrings have been visited, takes O(len), where len is the length of the substring.  The minimal/maximal value of every substring needs to be computed:

1..5
1..4 2..5
1..3 2..4 3..5
1..2 2..3 3..4 4..5
1..1 2..2 3..3 4..4 5..5

In this case, it takes 5*1 + 4*2 + 3*3 + 2*4 + 1*5.  In general, the number of operations grows in a cubic fashion.

At the heart of the algorithm is the combine function, which takes an operator and the minimal/maximal values of each of its operands, and produces the minimal/maximal results.

To maximize the result:

If adding two numbers, maximize both arguments.
If subtracting two numbers, maximize the left argument and minimize the right argument.
If multiplying two numbers, try the following:

Maximize both arguments.  This gives us the maximal result when multiplying two positive numbers.
Minimize both arguments.  This gives us the maximal result when multiplying two negative numbers, since a negative times a negative equals a positive.
Minimize the left argument and maximize the right argument, or vice versa.  We'd rather multiply two positives or two negatives and get a positive result, but if we have to multiply a positive and a negative and get a negative result, we want it to be as close to zero as possible.  To do so, we minimize the positive number and maximize the negative number.


Primes and Twin Primes Your challenge is to write a program to print all the primes (separated by one or more whitespace characters) less than a given integer N with an asterisk (*) next to each twin prime. A twin prime is a prime number that is either two more or two less than another prime.
(Hardcoding outputs is allowed, but it is not likely to result in very short code.)
Shortest code wins!
Input

N is always one of 50, 100, 1000, 1000000, or 10000000

Output

The output for input 50 should be 2 3* 5* 7* 11* 13* 17* 19* 23 29* 31* 37 41* 43* 47

Python 2, 81 79 bytes
-2 bytes thanks to dingledooper with a different way to detect if k-2 is a prime which works with k=2.
Uses Wilson's theorem for the primality tests and the fact that \$p\$, \$p+1\$ and \$p+2\$ are coprime for most primes \$p\$.

P=k=q=1
exec"if P%k:print`k`+'*'[k<3:P%(k+2)|q/k];q=k+2\nP*=k*k;k+=1\n"*input()

Try it online!
The output includes the input if it is prime, but this is fine since all testcases are composite.
How?
We use the following result of Wilson's theorem:
$$
(k-1)!^2 \operatorname{mod} k =
\begin{cases}
1 & \text{if $k$ is prime}\\
0 & \text{otherwise.}
\end{cases}
$$
In the code P is used to keep track of \$(k-1)!^2\$ and P%k tests if k is a prime.
If this is the case, we print the output and update q to k+2.
If k==q at the print statement, we know that k-2 was a prime and k is a twin prime.
P%(k+2) tests if k+2 is a prime number. If we would use the exact same prime test as before, this would be P*k*k*(k+1)*(k+1)%(k+2), but with our assumption that \$k\$, \$k+1\$ and \$k+2\$ are coprime for prime \$k\$, this gives the same result.
The assumption doesn't hold for k=2, but this is handled separately with '*'[k<3:], which results in the empty string if k<3.


Code Golf: Directory Tree -> Tree Contest (!): In the language of your choice, write a program that will traverse the directory tree of a given directory and output a tree (i.e., an array of arrays) corresponding to it. Assume the directory is a predefined variable D. Smallest character count wins.

Rules:

You must use recursion
See Rules

Note: Assume that there are no recursion depth limits. In other words, your code just needs to work for sufficiently small directory trees, and in principle for larger ones.

For instance:

Directory tree is

dir1
├── dir11
│   ├── file111
│   └── file112
├── dir12
│   ├── file121
│   ├── file122
│   └── file123
├── file11
├── file12
└── file13

Output tree is

[[[],[]],[[],[],[]],[],[],[]]

First code golf here so lemme know if I'm doing something wrong.

Have fun :)

Mathematica 120 21 20

Explicit recursion (thanks alephalpha for saving one char):
f=f/@__~FileNames~#&

f["~/StackExchange/dir1"]

{{{}, {}}, {{}, {}, {}}, {}, {}, {}}

TreeForm[%]

Previous overcomplicated solution:
d="~/StackExchange/dir1"

f@{x___,Longest@s:{y_,___}..,z___}:=f@{x,f@Drop[{s},1,1],z}
f[FileNameSplit/@FileNames[__,SetDirectory@d;"",∞]]/.f->(#&)


Return the Closest Prime Number Challenge

This is a simple one: Given a positive integer up to 1,000,000, return the closest prime number.

If the number itself is prime, then you should return that number; if there are two primes equally close to the provided number, return the lower of the two.

Input is in the form of a single integer, and output should be in the form of an integer as well.

I don't care how you take in the input (function, STDIN, etc.) or display the output (function, STDOUT, etc.), as long as it works.

This is code golf, so standard rules apply—the program with the least bytes wins!

Test Cases

Input  =>  Output
------    -------
80     =>      79
100    =>     101
5      =>       5
9      =>       7
532    =>     523
1      =>       2

JavaScript (ES6), 53 bytes

n=>(g=(o,d=N=n+o)=>N%--d?g(o,d):d-1?g(o<0?-o:~o):N)``

Try it online!
Commented
n => (            // n = input
  g = (           // g = recursive function taking:
    o,            //   o = offset
    d =           //   d = current divisor, initialized to N
    N = n + o     //   N = input + offset
  ) =>            //
    N % --d ?     // decrement d; if d is not a divisor of N:
      g(o, d)     //   do recursive calls until it is
    :             // else:
      d - 1 ?     //   if d is not equal to 1 (either N is composite or N = 1):
        g(        //     do a recursive call with the next offset:
          o < 0 ? //       if o is negative:
            -o    //         make it positive (e.g. -1 -> +1)
          :       //       else:
            ~o    //         use -(o + 1) (e.g. +1 -> -2)
        )         //     end of recursive call
      :           //   else (N is prime):
        N         //     stop recursion and return N
)``               // initial call to g with o = [''] (zero-ish)


Adjacent Letter Test One aspect of password strength testing is runs of adjacent letters on the keyboard. In this challenge, a program must be created that returns true if a string contains any runs of adjacent letters.

What counts as a run of adjacent letters?

For this simplified version of a password strength tester, a run of adjacent characters is 3 or more letters which are next to each other in a single direction (left, right, above or below) on a QWERTY keyboard. For the purpose of this challenge the layout of the keyboard looks like this:

1234567890
QWERTYUIOP
ASDFGHJKL
ZXCVBNM

In the diagram above Q is below 1 but not below 2, so a string that contains 1qa or aq1 anywhere inside it would make the program return true, but 2qa would not.

Input

The password string to check. It will only contain the characters [0-9a-z] or [0-9A-Z] (your choice).

Output

The program must return a truthy value if the password contains one or more runs of adjacent keys, or falsey if it contains none.

Examples

The following inputs should output true:

asd
ytrewq
ju7
abc6yhdef

And these inputs should output false:

abc
aaa
qewretry
zse
qwdfbn
pas

Rules

Answers may be complete programs or functions.
Standard loopholes are disallowed.
This is code-golf, lowest score (in bytes) wins!

Pyth - 66 62 60 bytes
Pretty straightforward approach. Checks if any of substrings len 3 are in any of the rotations of the keyboard. Will be using base encoding for keyboard.
.E}Rjb+J+Kc+jkS9"0
qwertyuiop
asdfghjkl
zxcvbnm"b.tKN_MJ.:z3

Test Suite.


How many dice can you roll without rolling the most probable number Problem

Starting from n=2 dice:

Roll n dice, with each number 1 to 6 equally likely on each die.
Check if their sum equals the most probable sum for n dice, that is 3.5*n.

If they're equal, terminate.
Otherwise, print n, and repeat from the start with n+2 dice

Your code doesn't have to do this procedure exactly, but should give random output probabilistically equivalent to it, based on our definition of randomness.

Your program should output all of the numbers on their own line; for example, if the program got up to 8 dice and rolled the most probable number with 8 dice, the output would be:

2
4
6

Example Run

On 2 dice, 7 is the most probable sum. Let's say the numbers rolled were 2 and 3. Then, you would print 2.

On 4 dice, 14 is the most probable sum. Let's say the numbers rolled were 3, 4, 2, and 5. Then, the sum is 14, so the program would terminate here.

The final output in this case is "2".

Rules

code-golf so shortest solution in bytes wins
Standard Loopholes Apply
The meta definition of randomness applies
You may use functions as well as programs

Python 2, 70 bytes

from random import*
n=2
while eval("+randrange(6)-2.5"*n):print n;n+=2

Try it online!

The trick is to compute the sum by evaling a string the looks like

'+randrange(6)-2.5+randrange(6)-2.5'

with n copies of the expression concatenated. The randrange(6) outputs a random number from [0,1,2,3,4,5], which is shifted down by 2.5 to have average of 0. When the sum if 0, the while condition fails and the loop terminates.

An alternative using map was 4 bytes longer:

from random import*
n=2
while sum(map(randrange,[6]*n))-2.5*n:print n;n+=2

I've found a bunch of equal-length expressions for a die shifted to mean zero, but none shorter

randrange(6)-2.5
randint(0,5)-2.5
randrange(6)*2-5
uniform(-3,3)//1


Singly lossy integers: Concatenated sequences missing a single element I define the method of combining a sequence to mean that every number in the sequence is concatenated as a string, then that result is made an integer.

[1, 2, 3] -> 123

For every finite sequence of at least 3 consecutive integers, missing exactly one element in the sequence, and this missing element may not be the first or last element in the sequence, output the integer resulting from the combined sequence. I am referring to this as a "singly lossy integer".

[1, 2, 3] -> {1, 3} (missing an element) -> 13

This sequence of singly lossy integers is the union of the following subsequences (partitions?):

The first subsequence {n, n+2} is A032607.

{n, n+2}            -> 13, 24, 35, 46, 57, 68, 79, 810, 911, 1012, ...
{n, n+1, n+3}       -> 124, 235, 346, ...
{n, n+2, n+3}       -> 134, 245, 356, ...
{n, n+1, n+2, n+4}  -> 1235, 2346, 3457, ...
{n, n+1, n+3, n+4}  -> 1245, 2356, 3467, ...
{n, n+2, n+3, n+4}  -> 1345, 2456, 3567, ...
...
for n ∈ ℕ (integers >= 1)

These integers must be printed in ascending order. The first 25 singly lossy integers are below:

13, 24, 35, 46, 57, 68, 79, 124, 134, 235, 245, 346, 356, 457, 467, 568, 578, 679, 689, 810, 911, 1012, 1113, 1214, 1235, ...

First 7597 Singly Lossy Integers

Ungolfed reference implementations. I made it to be faster, rather than smaller.

Ideone
TIO (fastest, higher limits)

Rules:

Shortest code wins
You may either (say which one):

Print the singly lossy integers forever
Given a positive integer n, print or return the first n elements as a list, or a comma- or whitespace- delimited string.

You should support arbitrarily large integers if your language allows it, especially if you're printing forever.

Inspired by / Related

Note: There is not yet an entry in the OEIS for this sequence.

Another note: I named them the "Singly Lossy Integers" so that there could in turn be "Doubly Lossy Integers", "N-ly Lossy Integers", "(N+1)-ly Lossy Integers", and the "Lossy Integers" (union of all of these).

APL (Dyalog Unicode), 62 bytesSBCS

Infinite printing full program, 63 bytes

s←⍎' '~⍨⍕
{⎕←s⊢a←⊃⍵⋄b←1+a⋄t←∪(b,⍨⊃a)(a,⊃⌽b)b,1↓⍵⋄t[⍋s¨t]}⍣≡⊂1 3

Try it online!

This one is pretty fast. Theoretically can be made faster using a min heap, but the challenge is code golf after all.

How it works: the concept

If we denote each item in the sequence as a list of integers ([1,3] for 13, [1,2,4] for 124, and so on), observe that subsequent items can be derived from an existing item x in three ways:

Add 1 to all numbers in x
Add 1 to all numbers in x, and then prepend the first element of x
Append 1 plus the last element of x to x

Therefore, the algorithm is to start with the single known value and infinitely run the following:

Extract the smallest item and print it
Derive three larger values from it and add them to the list of next candidate items

How it works: the code

s←⍎' '~⍨⍕  ⍝ Helper function: concat a list of numbers
        ⍕  ⍝   Stringify entire array, which will contain blanks between items
   ' '~⍨   ⍝   Remove blanks
  ⍎        ⍝   Eval
s←         ⍝   Store the function to s

⍝ Main program: print all items in the sequence infinitely
{⎕←s⊢a←⊃⍵⋄b←1+a⋄t←∪(b,⍨⊃a)(a,⊃⌽b)b,1↓⍵⋄t[⍋s¨t]}⍣≡,⊂1 3
{...}⍣≡⊂1 3  ⍝ Specify starting item and infinite loop
       ⊂1 3  ⍝   singleton array containing [1 3]
{...}⍣≡      ⍝   Pass it to the infinite looping function

⎕←s⊢a←⊃⍵⋄b←1+a⋄t←∪(b,⍨⊃a)(a,⊃⌽b)b,1↓⍵⋄t[⍋s¨t]  ⍝ Single iteration
       ⍵  ⍝ Sorted candidate items
    a←⊃⍵  ⍝ Take the first element and store to a
⎕←s⊢a     ⍝ Concat and print it

b←1+a  ⍝ Add 1 to all items of a and store to b

t←∪(b,⍨⊃a)(a,⊃⌽b)b,1↓⍵  ⍝ Add next candidates
                   1↓⍵  ⍝ Remove the first item (already printed)
   (b,⍨⊃a)(a,⊃⌽b)b,     ⍝ Prepend three candidates:
                 b      ⍝   1+a
          (a,⊃⌽b)       ⍝   append 1+last element of a to a
   (b,⍨⊃a)              ⍝   prepend first element of a to 1+a
t←∪                     ⍝ Uniquify and store to t

t[⍋s¨t]  ⍝ t sorted with the key function s (concat'ed value)

Function returning first n values, 62 bytes

⎕CY'dfns'
⊢↑∘{(⍋⊃¨⊂)⍵{a b c←⍵-1 0⍺⋄⍎dab⍕c↓a↓b~⍨⍳⍺}¨↓3cmat⍵}2+⊢

Try it online!

Slower, but still can handle 100 items in around 5 seconds.

How it works: the concept

This solution uses a systematic way to generate all possible singly lossy integers from the list 1..n. It is equivalent to selecting three members from 1..n:

Select three distinct integers a < b < c from 1..n.
Take the inclusive range a..c and discard b.

Original list: 1 2 3 4 5 6 7 8 9
Selection:       ^ ^       ^
                 a b       c
Take a..c:       2 3 4 5 6 7
Discard b:       2   4 5 6 7
Result: 24567

I use dfns.cmat to generate all 3-combinations, generate all singly lossy numbers, sort them and take first n elements. We need length n+2 for the combinations because lower numbers won't give enough number of items.

How it works: the code

⎕CY'dfns'  ⍝ Import dfns library, so that we can use cmat

⍝ Inner function: generate enough singly lossy integers
{(⍋⊃¨⊂)⍵{a b c←⍵-1 0⍺⋄⍎dab⍕c↓a↓b~⍨⍳⍺}¨↓3cmat⍵}  ⍝ Input: 2+n

⍵{...}¨↓3cmat⍵  ⍝ Generate all 3-combinations, and get singly lossy integers
        3cmat⍵  ⍝ 3-combinations of 1..2+n
⍵{   }¨↓        ⍝ Map the inner function to each row of above, with left arg 2+n

a b c←⍵-1 0⍺⋄⍎' '~⍨⍕c↓a↓b~⍨⍳⍺  ⍝ From 3-combination to a singly lossy integer
a b c←⍵-1 0⍺  ⍝ Setup the numbers so that
              ⍝ "remove b, drop first a and last c elements" gives desired value
⍎dab⍕c↓a↓b~⍨⍳⍺  ⍝ Compute the target number
     c↓a↓b~⍨⍳⍺  ⍝ Remove b, drop first a and last c elements from 1..2+n
⍎dab⍕           ⍝ Concat the numbers (dab stands for Delete All Blanks)

(⍋⊃¨⊂)  ⍝ APL idiom for sorting

⊢↑∘{...}2+⊢  ⍝ Outer function; input: n
  ∘{...}2+⊢  ⍝   Pass 2+n to the inner function
⊢↑           ⍝   Take first n elements from the result

APL (Dyalog Extended), 49 bytesSBCS

⊢↑∘{∧⍵{a b c←⍵-1 0⍺⋄⍎⌂dab⍕c↓a↓b~⍨⍳⍺}¨↓3⌂cmat⍵}2+⊢

Try it online!

Simply uses extra built-ins provided in Extended version (dfns library pre-loaded as ⌂ functions, ∧ for ascending sort).


JavaScript (ES6), 18 bytes

f=n=>n&&1+f(n>>>1)
<input type=number min=0 step=1 value=8 oninput="O.value=f(this.value)">
<input id=O value=4 disabled>


Expression that equals its length Given a number, find an expression in words equaling that number, with a length of that number.

Thus, to an input of 15, you might output sixteen minus one, which has fifteen characters (not counting spaces). If multiple solutions exist, print whichever you want. If none exist, print impossible

Use only the operators plus, minus, times, and divided by. Operators are evalutated left to right.

Format 1234 as one thousand two hundred thirty four. Note the absence of "and", and that there are no dashes or commas.

The input and all numbers used in the output must be positive integers less than 10,000.

The input will be given as a command line argument. Print to standard output.

Examples

1: impossible
4: four
7: impossible
13: eight plus five (you could also output "five plus eight")
18: one plus two times six (note that operators are evaluated from left to right)
25: one thousand divided by forty

JS, 1719/1694

Theory

Unfortunately, the rule set that you provide may not be a wise decision from a mathematical point of view. In fact, using a smaller subset of rules, you can find a solution for every number in the given interval

except for

for which there is no solution.

Reduced rule set

Consider the following subet of rules:

Use only the operators plus, minus and times.
You don't need to implement multiple occurrences of plus or minus in your expressions.
You don't need to implement neither division nor operator associativity (as their solution set is already covered by the first rule).

The reason why this works is that, as you discussed earlier with @Qwix, you allow boring answers, that is, expressions that end in the regular expression
( times one)+$. Allowing this, each number in the given interval will have a solution.

When you replied in one of your comments,

  @Qwix Yes; boring answers are acceptable, although that one doesn't
  work for 104, 105, 106, 107, 108, 109, 110, or 111. –

you were absolutely right: This does not work when you're trying to build your expression starting with the numbers themselves, i.e. one hundred four times one times one … or any other of those numbers.

If however, your expression starts with an expression whose evaluation equals one of the given numbers, you're out of luck. For example, note that 17 + 87 is indeed 104, so we could write 104 as:

104: seventeen plus eighty seven times one times one times one times one times one times one times one times one times one times one

To see that this subset works, save this file as num.js and make sure that SpiderMonkey, a JavaScript engine for command lines, is installed on your system.

The algorithm

Let us define the property K for positive integers as the state of the number having N letters and having a value of N.
Let us further define the property F for an expression as the state of its word conversion being 8k-times shorter than its evaluation with k ∈ ℕ. F stands for "fillable" and describes whether or not we can fill the word conversion of the expression with expressions of length 8 (i.e. " times one") such that the resulting expression might get the property N.

We then proceed as follows:

Convert the input number to words.
Check if the input number has property K.

If it does, return the words (4 is the only number with this property, unfortunately).
If it doesn't, proceed.

For all two-operand expressions (additions, subtractions and multiplications in this order) that result in the input number, check if their evaluation has property K.

If it does, return the words.
If it doesn't, check if the two-operand expression has property N.

If it does, fill the expression with " times one" and check if the evaluation of the resulting expression has property K.

If it does, return the words
If it doesn't, proceed

If it doesn't, proceed

Go drink a coffee

Practice

num.js (for SpiderMonkey / command lines)

function X(e,t){return e+": "+t}function P(e){var n,t;for(n=1;.5*e+(e%2===0?1:0)>n;++n){if(t=C.s(n)+" plus "+C.s(e-n),t.replace(/\s/g,"").length===e)return t;if(F(e,t)&&e>t.length)return G(e,t)}return!1}function M(e){var t,n;for(t=L;t>1;--t){if(0>t-e)return!1;if(n=C.s(t)+" minus "+C.s(t-e),n.replace(/\s/g,"").length===e)return n;if(F(e,n)&&e>n.length)return G(e,n)}return!1}function F(e,t){return(e-t.replace(/\s/g,"").length)%8===0}function G(r,t){var e,i=(r-t.replace(/\s/g,"").length)/8,n="";for(e=0;i>e;++e)n+=" times one";return t+n}function T(e){var t,n,r;if(F(e,C.s(e)))return G(e,C.s(e));for(t=1,n=1;t<Math.floor(Math.sqrt(e));++t){for(;e>tn;)++n;if(tn===e&&(r=C.s(t)+" times "+C.s(n),r.replace(/\s/g,"").length===e))return r}return!1}function Y(e){var n,r,t;return e===C.s(e).length?X(e,C.s(e)):(n=P(e))?X(e,n):(r=M(e))?X(e,r):(t=T(e),t?X(e,t):X(e,"impossible"))}var L=1e4,C=new function(){return this.o=["","one","two","three","four","five","six","seven","eight","nine"],this.t=["","","twenty","thirty","forty","fifty","sixty","seventy","eighty","ninety"],this.T=["ten","eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen","eighteen","nineteen"],this.s=function(e){return e?this.m(e):"zero"},this.m=function(e){return e>=1e6?this.m(Math.floor(e/1e6))+" million"+(e%1e6!==0?" "+this.Z(e%1e6):""):this.Z(e)},this.Z=function(e){return e>=1e3?this.h(Math.floor(e/1e3))+" thousand"+(e%1e3!==0?" "+this.h(e%1e3):""):this.h(e)},this.h=function(e){return e>99?this.o[Math.floor(e/100)]+" hundred"+(e%100!==0?" "+this.U(e%100):""):this.U(e)},this.U=function(e){return 10>e?this.o[e]:e>=10&&20>e?this.T[e-10]:this.t[Math.floor(e/10)]+(e%10!==0?" "+this.o[e%10]:"")},this};print(Y(0|arguments[0]))

num.js (for browsers)

The given code from above can't work for browsers due to its last command, which grabs the command line arguments in order to make a nice command out of the given script.

In order to run the JavaScript code directly from within your browser, select this piece of the above code:

function X(e,t){return e+": "+t}function P(e){var n,t;for(n=1;.5*e+(e%2===0?1:0)>n;++n){if(t=C.s(n)+" plus "+C.s(e-n),t.replace(/\s/g,"").length===e)return t;if(F(e,t)&&e>t.length)return G(e,t)}return!1}function M(e){var t,n;for(t=L;t>1;--t){if(0>t-e)return!1;if(n=C.s(t)+" minus "+C.s(t-e),n.replace(/\s/g,"").length===e)return n;if(F(e,n)&&e>n.length)return G(e,n)}return!1}function F(e,t){return(e-t.replace(/\s/g,"").length)%8===0}function G(r,t){var e,i=(r-t.replace(/\s/g,"").length)/8,n="";for(e=0;i>e;++e)n+=" times one";return t+n}function T(e){var t,n,r;if(F(e,C.s(e)))return G(e,C.s(e));for(t=1,n=1;t<Math.floor(Math.sqrt(e));++t){for(;e>tn;)++n;if(tn===e&&(r=C.s(t)+" times "+C.s(n),r.replace(/\s/g,"").length===e))return r}return!1}function Y(e){var n,r,t;return e===C.s(e).length?X(e,C.s(e)):(n=P(e))?X(e,n):(r=M(e))?X(e,r):(t=T(e),t?X(e,t):X(e,"impossible"))}var L=1e4,C=new function(){return this.o=["","one","two","three","four","five","six","seven","eight","nine"],this.t=["","","twenty","thirty","forty","fifty","sixty","seventy","eighty","ninety"],this.T=["ten","eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen","eighteen","nineteen"],this.s=function(e){return e?this.m(e):"zero"},this.m=function(e){return e>=1e6?this.m(Math.floor(e/1e6))+" million"+(e%1e6!==0?" "+this.Z(e%1e6):""):this.Z(e)},this.Z=function(e){return e>=1e3?this.h(Math.floor(e/1e3))+" thousand"+(e%1e3!==0?" "+this.h(e%1e3):""):this.h(e)},this.h=function(e){return e>99?this.o[Math.floor(e/100)]+" hundred"+(e%100!==0?" "+this.U(e%100):""):this.U(e)},this.U=function(e){return 10>e?this.o[e]:e>=10&&20>e?this.T[e-10]:this.t[Math.floor(e/10)]+(e%10!==0?" "+this.o[e%10]:"")},this}

Now, paste it into your browser's JavaScript console, so you can produce the same results from within your browser with, for example:

Y(1234);

Examples (command line)

chiru@chiru ~ $ js num.js 28
28: fourteen plus fourteen times one
chiru@chiru ~ $ js num.js 7
7: impossible
chiru@chiru ~ $ js num.js 42
42: nine thousand sixty minus nine thousand eighteen

And in order to see the trick with which you can make each number work, just have a look at the boring answer for js num.js 1337:
1337: ten plus one thousand three hundred twenty seven times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one

The provided codes generates valid solutions for the given interval (and probably even above, you'd only have to raise the value of the variable L).

Statistics

I was interested in "how boring" the expressions were (or: how much the substring times one was used per expression within this algorithm), as this part was responsible for finding a solution for every number within the given interval. See for yourselves:

x: n-th expression (min. 0, max. 10,000)

y: number of occurences of substring " times one" within expression (min. 0, max. 1245)

Conclusions:

The expressions tend to get more and more boring in a linear manner.
Over 99% of solutions are boring.


The Strange Unsorting Machine for Nefarious Purposes Good Evening Golfers!

Your challenge is to completely unsort a series of numbers.

Input

Exactly 100 integers will be fed to your program. Your program may accept the input either as a file, or via stdin. Each integer will be separated by a newline character.

Those 100 integers will range from the minimal to the maximal values of a signed integer in your chosen language.

There will be no duplicate values. The values may be ordered, unordered or partially ordered - your program should be able to handle each case.

Output

The output must be each of the 100 integers, completely unsorted, each separated by a newline character. The output may be via stdout, or to a file.

Completely Unsorted means that no value is adjacent to any value which it would be adjacent to if the list were completely sorted in an ordered sequence.

Score

1 point per character, and lowest score wins. There is a bonus of -100 for any solution using no built in or library sorting functions. There is a bonus of -20 for any solutions using no built in random number functions.

I have tried to define this question as completely as possible. If you have any questions, please ask. If you have any comments on how I could do better next time, please let me know.

Fore!

GolfScript (score 27 - 120 = -93)

~].,{{.2$<{\}*}*]}*.(;+2%n*

Note: that $ is referencing an element on the stack. There is sorting, but it's done with an manually coded bubble sort.

Thanks to Howard, for -90 => -92; and Ilmari, who inspired -92 => -93.


Tips for Golfing in T-SQL What general tips do you have for golfing in T-SQL? I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to T-SQL. Please post one tip per answer.

Thanks to Marcog for the original idea. :)

My general bag of tricks::

@ is a valid variable in t-sql.
T-sql 2012 added iif a VB style case statement. This is almost always shorter than an equivalent if else.
\ is a useful way to initialize a number as 0 in a money type. You can convert a value to to a float by adding e. e.g. 4e or \k which will set k to the value 0.00 money.
rCTE seem to be the best way to create a number table of less than a 100 entries. Even shorter than using spt_values. If you need more than a 100, cross join and add them.
+= and other compound operators were added in 2008. Use them it saves a few characters.
Literals are usually a good enough delimiter for aliasing purposes. You rarely need a space or a ;.
Use ANSI SQL joins if you need them. Select*from A,B where condition is shorter than select*from A join b on condition
If you can be assured that the your while loop will do the first iteration it's best to rewrite it as a do-while style goto loop.
STR() is the shortest function to turn an int into a string. If you are doing more than one conversion or may need to concat numerous different datatypes consider the concat function.  E.g. 'hello'+str(@) is shorter than concat('hello',@), but hello+str(@)+str(@a) is longer than concat('hello',@,@a)

For example
These two are semantically equivalent.

while @<100begin/*code*/set @+=1 end
s:/*code*/set @+=1if @<100goto s

You can use Values to create a table or subquery. This will only really be a benefit if you need a few constant rows.


Surround a string with hashes I've already made this in Python, but it seems that it could be shortened a lot:

txt = input("Type something.. ")
c = "#"
b = " "
print(c * (len(txt) + 4))
print(c, b * len(txt), c)
print(c, txt, c)
print(c, b * len(txt), c)
print(c * (len(txt) + 4))

So if the user types:

Hello World

The program prints:

###############
#             #
# Hello World #
#             #
###############

Fewest bytes wins—and of course, the answer can be written in any language.

CJam, 22 20 bytes

qa{4/3*' +f+W%z}8/N*

Test it here.

Explanation

How do you wrap a 2D grid of characters in one layer of spaces (or any other character)? Correct: four times, you append a space to each line and then rotate the grid by 90 degrees. That's exactly what I'm doing here with eight rotations: four for spaces, four for #:

qa      e# Read the input and wrap it in an array, to make it a 2D grid.
{       e# Execute this block for each value from 0 to 7.
  4/3*  e#   Divide by 4, multiply by 3. Gives 0 for the first four iterations and
        e#   and 3 for the other four.
  ' +   e#   Add the result to a space character (space + 3 == #).
  f+    e#   Append this to each line of the grid.
  W%z   e#   Reverse the lines, then transpose the grid - together these rotate it.
}8/
N*      e# Join the lines of the grid by newlines.


When is the closest Conway's Doomsday? A quote from MO.SE answer:

  Although it is well known that Conway was able to quickly calculate the day of the week of any given date, it is less well known that one part of the algorithm is easy to remember and useful in practice: In any given year, the following dates all fall on the same day of the week: 4/4, 6/6, 8/8, 10/10, 12/12, 5/9, 9/5, 7/11, 11/7, and the last day of February. For example, in 2020, all these dates fall on a Saturday. Conway, in his characteristically colorful way, would say that the Doomsday of 2020 is Saturday. Knowing this fact allows you to calculate fairly quickly in your head, with no special training, the day of the week for any date in 2020.

Well, it sounds easy, but then we need to check which doomsday is the closest from the given date in order to quickly calculate the day of week. Now that sounds hard.

Practically, we'd just compare a given date with the Doomsday in the same month (or adjacent month in case of January and March).

Task

Given a date consisting of full year, month, and day, output the closest Conway's Doomsday (i.e. one of 4/4, 6/6, 8/8, 10/10, 12/12, 5/9, 9/5, 7/11, 11/7, and the last day of February) from the given date.

The closest Doomsday can be in the same month, a different month, or even a different year. If the given date has two nearest Doomsdays, output any one or both of them. Also note that the last day of February can be either 28th or 29th (depending on leap-year-ness).

You can take input and produce output in any suitable format, e.g. three integers, a formatted string, or even a built-in Date object (if your language has one). You can assume the given date is valid, and the input year is between 1901 and 2099 inclusive. Gregorian calendar is assumed in this challenge.

Test cases

YYYY-MM-DD => YYYY-MM-DD, ...
-------------------------------
2020-05-18 => 2020-05-09
2020-05-30 => 2020-06-06
2020-10-31 => 2020-11-07
2020-10-24 => 2020-10-10 or 2020-11-07
2020-01-20 => 2019-12-12
2020-01-21 => 2020-02-29
2019-01-20 => 2018-12-12 or 2019-02-28

Reference implementation in Python.

Charcoal, 138 110 98 bytes

≔§⪪”)¶⊟eΦＯ∨ü&-T[¿Ｑ№i⧴⊕%⁰q”⁴ＬΦ⪪”)¶ »Ｒ≦ＰH↘{⎚″4χχβ´ΣP”⁴›ι✂θ⁴χ¹η¿⁼Ｉη¹²⁺⊖…θ⁴1212«…θ⁴¿⁻Ση³η«022§9888Ｉ…θ⁴

Try it online! Link is to verbose version of code. Edit: Saved 28 bytes by switching I/O to compact ISO format (yyyymmdd). Saved 12 bytes when the supported year range was restricted to 1901 to 2099. Explanation:

≔§⪪”)¶⊟eΦＯ∨ü&-T[¿Ｑ№i⧴⊕%⁰q”⁴ＬΦ⪪”)¶ »Ｒ≦ＰH↘{⎚″4χχβ´ΣP”⁴›ι✂θ⁴χ¹η

Take the dates (in mmdd format) 0120, 0317, 0421, 0523, 0623, 0725, 0822, 0922, 1024, 1124. These represent the cutoff points above which the next Doomsday is nearer. (In some cases the Doomsday is equidistant but in particular for 0120 that is not true on leap years.) Work out which cutoff point applies by counting the number of dates that fall before the input date. Then look up the relevant Doomsday date from the list (in mmdd format) 1212, 1107, 1010, 0905, 0808, 0711, 0606, 0509, 0404, 0300, 0012.

If I had access to a date library I could then ask it to fix up my date, but unfortunately I have to do that manually:

¿⁼Ｉη¹²

Is this the 0012 date, meaning the 12th of month 0, i.e. last December?

⁺⊖…θ⁴1212«

If so then output the previous year and a month and day of 12.

…θ⁴

Otherwise the year is at least correct...

¿⁻Ση³

Is this the 0300 date, meaning the 0th of March, i.e. the last day of February?

η«

If not then this is the date we seek.

022

Output February the 2?th.

§9888Ｉ…θ⁴

Output 9 if the year is a multiple of 4, otherwise 8.


Prisoner's Dilemma with access to opponent In this challenge, you will write a bot that play's the prisoner's dilemma. Here's the catch: you will not have access to the history of previous games. Instead, you will have access to the opponent itself. In this version, both players get +2 points if they both cooperate, +1 points if they both defect, and if one cooperates but one defects, the defector gets +3 while the other gets no points. Each submission will be played against every other submission, including itself, 10 times. The winner is the submission with the most total points.

Controller:
You should write a javascript function, in the form

function submissionName(them) {
  /* Your code here */
}

The controller uses the function's name property to display the results, so if it is not in this format (and is instead f = x => ... or f = function() { ... }) it will be difficult to see your score and you will not be able to access your own function.

The function will accept one parameter: them which is the opponent's function.  It may then call that function to see what the opponent's reaction would be given certain functions as inputs. Based on that data, you must return 'C' or 'D' for cooperate or defect respectively.

Examples (will be competing):

function cooperate(them) {
    return 'C';
}

function defect(them) {
    return 'D';
}

function nice(them) {
    // Do whatever they would do when faced with a cooperator
    return them(wrap(_ => 'C'));
}

The controller is available here

Rules:

You won't be able to see the opponent's code itself. All functions are wrapped so that they look the same when toString() is called. The only way to examine an opponent (who could be yourself) is to test them.
Your function does not have to be deterministic. You may only save state by setting properties on your own function, such as submissionName.state = {};. However, between matches (even between matches of the same players), state is cleared by calling toString() and eval. Therefore, there is no memory of previous matches.
The order of which function is called first in each match is randomized.
If your code throws an error, it will be treated as though you cooperated while your opponent defected. If you are the first to run, the opponent's code will not even be called. This happens even if the error occurs in your opponent's code while while you are calling them. Be wary of stack overflow errors, especially if your code calls them(wrap(submissionName)), as they might do the same.
You may not access the variable self, or any other variable that happens to be in scope when eval is called EXCEPT the function wrap. This function allows you to call the opponent in a manner indistinguishable from how the controller calls a function. You may not write to Math, window, etc. (You may use functions, such as Math.random(), however).
You may not access the stack trace by creating an Error or by some other method.

A note on taking too long: please avoid getting stuck in a while loop forever. The combined time of both competitors should not exceed 1 second in any given round. To enforce this, a random timeout between 1000 ms and 2000 ms is chosen (this is to avoid gaming by intentionally waiting a known amount of time), and if the worker takes longer than that to execute, an error will be thrown. If this happens, the cause of the error will be determined as follows: the execution will be paused at a random moment after 1000 ms, and the call stack at that moment will be inspected. The most recently called competitor that is currently in a loop (or loop-like recursion, in the sense that it is a recursion set up to avoid a stack overflow error) will be blamed. If the same competitor is blamed for causing a "taking too long" error several times, that competitor will be disqualified. This means that even if you cause the opponent to take too long by getting stuck in a loop when your opponent calls you, it will still be your fault, because it is the call stack that matters.

BoomBot

function boom(them) {
  throw 1;
}

If the opponent is run first and calls this without try..catch, this bot automatically wins 3 points. Zero points in any other case.


Build a program with one simple GOTO Your task is to build the largest program you can that uses exactly one GOTO, without which the entire program (or at least a huge chunk of it) must be completely restructured. The score is counted as the number of statements in your code that change places or are newly introduced (removing statements doesn't add to your score) when the code is restructured without the GOTO (others are allowed to challenge your restructuring by presenting a more elegant one). As this is code bowling, highest score wins.

Note: I do not claim any liability for velociraptor attacks by attempting this challenge.

C fizzbuzz

This solution runs around the idea of interrupts and label variables (gcc only, sorry). The program sets up a timer which periodically calls main, where we goto whichever place the last execution of our interrupt handler (main) told us we should.

I've never used timers or label variables before, so I think there is much to bowl here.

#include <sys/time.h>
#include <signal.h>
#include <stdio.h>

int main(int argc)
{
    static int run = 1;
    static int* gotoloc = &&init;
    static int num = 0;
    static int limit = 50;

    goto *gotoloc;
init:
    signal(SIGVTALRM, (void (*)(int)) main);
    gotoloc = &&loop;

    struct itimerval it_val;

    it_val.it_value.tv_sec = 0;
    it_val.it_value.tv_usec = 100000;
    it_val.it_interval.tv_sec = 0;
    it_val.it_interval.tv_usec = 100000;
    setitimer(ITIMER_VIRTUAL, &it_val, NULL);

    while(run);

loop:
    num = num + 1;
    run = num < limit;
    gotoloc = &&notfizz + (&&fizz - &&notfizz) * !(num % 3);
    return 1;

fizz:
    printf("fizz");
    gotoloc = &&notbuzz + (&&buzz - &&notbuzz) * !(num % 5);
    return 1;

notfizz:
    gotoloc = &&notfizzbuzz + (&&buzz - &&notfizzbuzz) * !(num % 5);
    return 1;

buzz:
    printf("buzz\n");
    gotoloc = &&loop;
    return 1;

notbuzz:
    printf("\n");
    gotoloc = &&loop;
    return 1;

notfizzbuzz:
    printf("%d\n", num);
    gotoloc = &&loop;
    return 1;
}


Black or white keys of jazz chords? When playing the piano, I realized that to play a chord right, I usually need to remember just which tones of the chord are played on white and which on black keys. The rest is usually handled by the "autopilot".

Let's write a program that given a 7th chord, it outputs which of its tones are to be played on black (character ^) and which on white keys (character -). Each chord name has a root, which is a capital letter A to G, optionally followed by b or #, and then by its type, which is one of the following. All 7th chords contain 4 notes, and the formulas are given in integer notation below.

7 Dominant (0,4,7,10)
M7 Major (0,4,7,11)
m7 Minor (0,3,7,10)
dim7 Diminished (0,3,6,9)
m7b5 Half-Diminished (0,3,6,10)
-M7 Minor/Major (0,3,7,11)

Integer notation means that you must play the four notes that are (w,x,y,z) semitones from the root. (w is the root and is therefore always zero.)

So for example for input Bb-M7 the output would be ^^-- (corresponding to Bb-Db-F-A).

The program should either read the chord form stdin and output the result to stdout, or it should be a function that accepts a string and returns a string.

Python3, 293 242 bytes
This is my first CodeGolf. I am curious to see how others do this.
def f(s):
 for j in 4,3,2,1:
  try:return ''.join(['-^--^-^--^-^'[('A BC D EF G'.index(s[0])-('b'==s[1])+('#'in s)+i)%12]for i in(0,)+{'7':(4,7,10),'M7':(4,7,11),'m7':(3,7,10),'dim7':(3,6,9),'m7b5':(3,6,10),'-M7':(3,7,11)}[s[-j:]]])
  except:pass

Edit on 01.06.15
Thanks to the commenters, we found some tricks to shorten the code. I also discovered that changing to a function is slightly shorter. Old code: http://ideone.com/j5gmV2. P.S. I am just copying the code into triple quotes in Python and calling len to get the number of bytes.
Note:
I am assuming that Bb-M7 is Bb Major/Minor, i.e. that there is no delimiter between the note and the chord type, as described in the OP's second paragraph. Thus Bb-M7 gives ^^--. If Bb-M7 means Major, then what is Bb Major/Minor? Should it be Bb--M7?


Generate regular expressions for matching natural numbers between `m` and `n` The type of regular expression is PCRE.

Write a program that output a valid PCRE such that it matches all natural numbers between m and n and does not match anything else. No leading zeros are allowed.

For example, let m and n be 123 and 4321, then the program might output
1(2[3-9]|[3-9]\d)|[2-9]\d\d|[123]\d\d\d|4([012]\d\d|3([01]\d|2[01])).

This matches the exact string, so ^ and $ anchors are implicit.

One should try to balance the two:

The regular expression should have a reasonable size.
The code should be short.

Let's optimize for

code length in characters + 2*regular expression length for input 123456 and 7654321

Side Note: It be interesting if we can prove the shortest PCRE regular expression is of the size O(log n log log n) or something.

Perl, score 455

191 chars, 132 regex length

sub b{my$a=shift;$_=(@_>0&&$a.b(@_).($a-->0&&'|')).($a>=0&&($a>1
?"[0-$a]":$a));/\|/?"($_)":$_}sub a{b(@a=split//,<>-1+$x++).(@a>
1&&"|.{1,$#a}")}print'(?!0|('.a.')$)(?=('.a.'$))^\d{1,'.@a.'}$'

Input: 123456, 7654321

(?!0|((1(2(3(4(5[0-5]|[0-4])|[0-3])|[0-2])|1)|0)|.{1,5})$)(?=((7(6(5(4(3(21|1)|[0-2])|[0-3])|[0-4])|[0-5])|[0-6])|.{1,6}$))^\d{1,7}$

Update: I was able to further simplify this when I realized that most of the patterns ended with things like \d{3}.  These were doing nothing more than enforcing a string length--and doing so very repetitively, since they occurred on every term.  I eliminated this by using another lookahead to enforce the "less than" condition, only checking that either: 1) the first part of the number does not exceed the input or 2) the number is fewer digits than the input.  Then the main regex just verifies that it is not too many digits.

I also incorporated Peter Taylor's idea of negative look-ahead for checking the "greater than" condition.

The key to simplifying this problem (at least for me) was to break the regex in two: a look-ahead makes sure the number is not less than the minimum, then the main part of the regex checks that it is not greater than the maximum.  It is a little bit silly for small input, but it is not so bad for large input.

Note: the 0| at the beginning is to exclude anything that starts with a zero from matching.  This is required because of the recursive nature of the regex function: inner parts of the match can start with zero, but the entire number cannot.  The regex function can't tell the difference, so I excluded any number starting with zero as a special case.

Input: 1, 4

(?!0|(0)$)(?=([0-4]$))^\d{1,1}$

Unreasonably Long Regex Version, 29 chars:

print'^',join('|',<>..<>),'$'


Compute OEIS A005434 The task is to compute OEIS A005434 as quickly as possible.

Consider a binary string S of length n.  Indexing from 1, we can determine if S[1..i+1] matches S[n-i..n] exactly for all i in order from 0 to n-1.      For example,

S = 01010

gives

[Y, N, Y, N, Y].

This is because 0 matches 0, 01 does not match 10, 010 matches 010, 0101 does not match 1010  and finally 01010 matches itself.

Define f(n) to be the number of distinct arrays of Ys and Ns one gets when iterating over all 2^n different possible bit strings S of length n.

The observant will notice this question is a simpler variant of another recent question of mine. However, I expect that clever tricks can make this much faster and easier.

Task

For increasing n starting at 1, your code should output n, f(n).

Example answers

For n = 1..24, the correct answers are:

1, 2, 3, 4, 6, 8, 10, 13, 17, 21, 27, 30, 37, 47, 57, 62, 75, 87, 102, 116, 135, 155, 180, 194

Scoring

Your code should iterate up from n = 1 giving the answer for each n in turn. I will time the entire run, killing it after two  minutes.

Your score is the highest n you get to in that time.

In the case of a tie, the first answer wins.

Where will my code be tested?

I will run your code under Virtualbox in a Lubuntu guest VM (on my Windows 7 host).

My laptop has 8GB of RAM and an Intel i7 5600U@2.6 GHz (Broadwell) CPU with 2 cores and 4 threads. The instruction set includes SSE4.2, AVX, AVX2, FMA3 and TSX.

Leading entries per language

n = 599 in Rust bu Anders Kaseorg.
n= 30 in C by Grimy. Parallel version gets to 32 when run natively  in cygwin.

Rust, n ≈ 660

use std::collections::HashMap;
use std::iter::once;
use std::rc::Rc;

type Memo = HashMap<(u32, u32, Rc<Vec<u32>>), u64>;

fn f(memo: &mut Memo, mut n: u32, p: u32, mut s: Rc<Vec<u32>>) -> u64 {
    debug_assert!(p != 0);
    let d = n / p;
    debug_assert!(d >= 1);
    let r = n - p * if d >= 2 { d - 1 } else { 1 };

    let k = s.binary_search(&(n - r + 1)).unwrap_or_else(|i| i);
    for &i in &s[..k] {
        if i % p != 0 {
            return 0;
        }
    }

    if d >= 3 {
        let o = n - (p + r);
        n = p + r;
        s = Rc::new(s[k..].iter().map(|i| i - o).collect());
    } else if n == p {
        return 1;
    } else if k != 0 {
        s = Rc::new(s[k..].to_vec());
    }

    let query = (n, p, s);
    if let Some(&c) = memo.get(&query) {
        return c;
    }
    let (n, p, s) = query;

    let t = Rc::new(s.iter().map(|i| i - p).collect::<Vec<_>>());
    let c = if d < 2 {
        (1..r + 1).map(|q| f(memo, r, q, t.clone())).sum()
    } else if r == p {
        (1..p + 1)
            .filter(|&q| p % q != 0 || q == p)
            .map(|q| f(memo, r, q, t.clone()))
            .sum()
    } else {
        let t = match t.binary_search(&p) {
            Ok(_) => t,
            Err(k) => {
                Rc::new(t[..k]
                            .iter()
                            .cloned()
                            .chain(once(p))
                            .chain(t[k..].iter().cloned())
                            .collect::<Vec<_>>())
            }
        };
        (1..t.first().unwrap() + 1)
            .filter(|&q| p % q != 0 || q == p)
            .map(|q| f(memo, r, q, t.clone()))
            .sum()
    };
    memo.insert((n, p, s), c);
    c
}

fn main() {
    let mut memo = HashMap::new();
    let s = Rc::new(Vec::new());
    for n in 1.. {
        println!("{} {}",
                 n,
                 (1..n + 1)
                     .map(|p| f(&mut memo, n, p, s.clone()))
                     .sum::<u64>());
    }
}

Try it online!

How it works

This is a memoized implementation of the recursive predicate Ξ given in Leo Guibas, “Periods in strings” (1981).  The function f(memo, n, p, s) finds the number of correlations of length n with smallest period p and also each of the periods in the set s.


Build railroad tracks and cheat the government You are a railroad entrepreneur in the 19th-century United States when trains become popular because they are the most efficient means of transporting large volumes of materials by land. There is a national need for railroad tracks from the east coast through some recently colonized lands in the west.

To accommodate this need, the U.S. government is going to levy a tax to subsidize railroads. They have promised to pay money to your railroad company for each mile of track laid. Since laying tracks in hilly and mountainous regions is more expensive than laying tracks in flat land, they adjust the amount they give accordingly. That is, the government will pay

$5,000 per mile of track laid in flat land
$12,500 per mile of track laid in hilly land
$20,000 per mile of track laid in mountains.

Of course, this plan does not accurately reflect how much it actually costs to lay tracks.

You have hired some cartographers to draw relief maps of the regions where you will be laying track to analyze the elevation. Here is one such map:

S12321
121234
348E96

Each digit represents one square mile of land. S is the starting point, E is the ending point. Each number represents the intensity of the elevation changes in that region.

Land numbered 1-3 constitutes flat land.
Land numbered 4-6 constitutes hilly land.
Land numbered 7-9 constitutes a mountain range.

You have, through years of experience building railroad tracks, assessed that the cost of track building (in dollars) satisfies this formula:

Cost_Per_Mile = 5000 + (1500 * (Elevation_Rating - 1))

That means building on certain elevation gradients will cost you more money than the government gives, sometimes it will be profitable, and sometimes you will just break even.

For example, a mile of track on an elevation gradient of 3 costs $8,000 to build, but you only get paid $5,000 for it, so you lose $3000. In contrast, building a mile of track on an elevation gradient of 7 costs $14,000, but you get paid $20,000 for it: a $6,000 profit!

Here is an example map, as well as two different possible paths.

S29    S#9    S##
134    1#4    1##
28E    2#E    2#E

The first track costs $30,000 dollars to construct, but the government pays you $30,000 for it. You make no profit from this track.

On the other hand, the second costs $56,500 to build, but you get paid $62,500 for it. You profit $6,000 from this track.

Your goal: given a relief map, find the most profitable (or perhaps merely the least expensive) path from the start to the end. If multiple paths tie, any one of them is an acceptable solution.

Program Details

You are given text input separated with a rectangular map of numbers and one start and end point. Each number will be an integer inclusively between 1 and 9. Other than that, the input may be provided however you like, within reason.

The output should be in the same format as the input, with the numbers where track has been built replaced by a hash (#). Because of arbitrary regulations imposed by some capricious politicians, tracks can only go in horizontal or vertical paths. In other words, you can't backtrack or go diagonally.

The program should be able to solve in a reasonable amount of time (i.e. <10 minutes) for maps up to 6 rows and 6 columns.

This is a code golf challenge, so the shortest program wins.

I have an example (non-golfed) implementation.

Sample I/O

S12321
121234
348E96

S12321
######
3##E##

S73891
121234
348453
231654
97856E

S#3###
1###3#
3#####
######
#####E

Python, 307 chars

import os
I=os.read(0,99)
n=I.find('\n')+1
I='\0'*n+I+'\0'*n
def P(p):
 S=[]
 for d in(-n,-1,1,n):
  y=p[-1]+d
  if'E'==I[y]:S+=[(sum((int(I[v])-1)/3*75-15*int(I[v])+15for v in p[1:]),p)]
  if'0'<I[y]<':'and y not in p:S+=P(p+[y])
 return S
for i in max(P([I.find('S')]))[1][1:]:I=I[:i]+'#'+I[i+1:]
print I,

P takes a partial path p and returns all ways of extending it to reach E.  Each returned path is paired with its score so max can find the best one.

Takes about 80 seconds on a 6x6 map.


Immutable dictionaries in Haskell You need to implement immutable dictionaries using only functions without any other data types (custom or built-in).
The dictionary must be indexed by any data type of class Eq and contain values of arbitrary type, but all the values in a dictionary should be of the same type.

Here are some examples of usage:

dict `access` True -- returns value of key True
dict `access` "y"  -- returns value of key "y"
(update "x" 10 dict) `access` "x" -- returns 10 for any dict

update key1 value obj = \key2 -> if key2 == key1 then value else obj key2
access = id

Given the above definitions, your examples should work. Also, you can define an empty dictionary as const x where x is the default value for keys not in the dictionary.


How to count the syllables in a word Input: You will be passed a string containing a single english word.  All letters will be lowercase, and there will be no non-alphabetic characters in the string.

Output: You will return an integer from 1 to 7 representing how many syllables you think are in the word.

Scoring: Your program will be run against all of the words found on this repository.  If you get N words correct, and your program is M bytes large, then your score is N-(M*10).  Largest score wins.

To generate my syllable count, I used this as my word list and this to count the syllables.

Ruby, 8618 correct (91.1%), 53 bytes, 8618 - 10 * 53 = 8088 score

->s{s.scan(/[aiouy]+e*|e(?!d$|ly).|[td]ed|le$/).size}

This is an anonymous Ruby function which uses regexes to count syllables.

The function adds a syllable for every instance of:

A run of non-e vowels, followed by zero of more es
An e which is not part of a trailing ed or ely, with the exception of trailing ted or deds
A trailing le

Analysis

The basic idea is to count runs of vowels, but this by itself isn't very accurate ([aeiouy]+ gets 74% correct). The main reason for this is because of the silent e, which modifies the previous vowel sound while not being pronounced itself. For example, the word slate has two vowels but only one syllable.

To deal with this, we take e out of the first part of the regex and treat it separately. Detecting silent es is hard, but I found two cases where they occur often:

As part of a trailing ed (unless it's a ted or ded like settled or saddled),
As part of a trailing evy (e.g. lovely)

These cases are specifically excluded in what would otherwise be e..

The reason for the . in e(?!d$|ly). is to consume the next char if there is a double vowel (e.g. ea or ee), and so that e at the end of the word are not counted. However a trailing le is usually pronounced, so that is added back in.

Finally, vowel runs are counted as one syllable. While this may not always be the case (e.g. curious), it's often difficult to work out whether there are multiple syllables. Take the ia of celestial and spatial, as an example.

Test program

I don't really know Ruby so I'm not sure how well it can be golfed. I did manage to scrape together a test program by consulting a lot of SO though:

cases = 0
correct = 0

s = "->s{s.scan(/[aiouy]+e*|e(?!d$|ly).|[td]ed|le$/).size}"

f = eval s

for i in 1 ... 8
    filepath = i.to_s + "-syllable-words.txt"
    file = File.open(filepath)

    while (line = file.gets)
        word = line.strip
        cases += 1
        if f.call(word) == i
            correct += 1
        end
    end
end

p "Correct: #{correct}/#{cases}, Length: #{s.length}, Score: #{correct - s.length*10}"


Turing Machine Simulator Write a Turing machine simulator.

For simplicity we can assume statuses as integer, symbols as char, blank symbol equals whitespace

5-tuple in the form of current state, input symbol, next state, output symbol, direction (left or right) the order is not mandatory but specify if you swap it

The machine must stop when an unknown state is reached, no other halt condition allowed.

The tape is infinite in both directions and you can always read an empty character.

Input: the initial tape, an initial state and a program. you are free to read the data from anywhere in the format you like

Output: the tape after the execution of the program

Required: an example program that run on top of your simulator

This is a code-colf so the shortest code win.

I'll post an implementation and some example programs in the next few hours.

GNU sed with -r - 133 117 111 93 chars

Yes, sed is turing complete. GNU sed and -r (extended regexps) is only to save a few characters, it is only a small change to work with POSIX sed.

:s
s/^(.*@)(.*)>(.)(.*#\1\3([^@]*@)(..))/\5\2\6>\4/
T
s/(..)l>|r>/>\1/
s/>@/@> /
s/>#/> #/
bs

Input format is

[initial state]@[non-empty tape with > marking head position]#[state]@[input symbol][next state]@[output symbol][direction l or r]#...

The delimiters @, # and head character > cannot be used as a symbol on the tape. State labels cannot contain @ > or #.

It will run all of the programs in the input, one per line

Examples:

Marco's anbn program

  Input

0@>aaabbb#0@a1@ r#0@ 4@ r#1@a1@ar#1@b1@br#1@ 2@ l#2@b3@ l#2@a5@al#3@b3@bl#3@a3@al#3@ 0@ r#4@ 5@Tr

  Output

5@    T>  #0@a1@ r#0@ 4@ r#1@a1@ar#1@b1@br#1@ 2@ l#2@b3@ l#2@a5@al#3@b3@bl#3@a3@al#3@ 0@ r#4@ 5@Tr

Marco's Hello! program

  Input

0@> #0@ 1@Hr#1@ 2@er#2@ 3@lr#3@ 4@lr#4@ 5@or#5@ 6@!r

  Output

6@Hello!> #0@ 1@Hr#1@ 2@er#2@ 3@lr#3@ 4@lr#4@ 5@or#5@ 6@!r


Tips for restricted source in Haskell I tested the waters on this sort of question with python, but now I get to the real question I want to ask.
restricted-source challenges are uniquely rewarding in Haskell because of Haskell's strict rule set.  Type coercion which is the bread and butter for other languages in these sort of challenges is arguably non-existent but when pushed to the limits Haskell provides some weird and interesting solutions.
What are some tips for solving restricted-source challenges in Haskell?
Please only include 1 tip per answer. If your tip only works for a specific compiler, or version of Haskell please note that.

What makes a good tip here?
There are a couple of criteria I think a good tip should have:

It should be (somewhat) non obvious.
Similar to the code-golf tips it should be something that someone who has golfed in python a bit and read the tips page would not immediately think of.  For example "Replace a + b with a+b to avoid using spaces", is obvious to any golfer since it is already a way to make your code shorter and thus not a good tip for this question.

It should not be too specific.
Since there are many different types of source restrictions, answers here should be at least somewhat applicable to multiple source restrictions, or one common source restriction.  For example tips of the form How to X without using character(s) Y are generally useful since banned characters is a common source restriction, or the byproduct of more unique restrictions.  The thing your tip helps to do should also be somewhat general.  For example tips of the form How to create numbers with X restriction are useful since many programs utilize numbers regardless of the challenge.  Tips of the form How to implement Shor's algorithm with X restriction are basically just answers to a challenge you just invented and not very helpful to people solving other challenges.

Break tokens with comments
A neat fact I discovered a little while ago (and the impetus for this sort of tips question in the first place), is that a block comment allows you to split tokens apart without a space.
For example if you want to write
main=interact tail

Without using whitespace, parentheses or $ you can do the following:
main=interact{--}tail

Here {--} is a block comment, which normally would do nothing, however here placed between interact and tail it serves to prevent the two as being parsed as a single token, interacttail.
This could also be used to split other kinds of tokens for example:
main=print${--}-3

Here we split the $ and the - without using spaces or parentheses.
data{--}K=K

Here we split a keyword from a type declaration (which unlike the earlier example cannot be done with $).
Pretty much anywhere you would use a space outside a String or Char literal you can use a block comment instead.


Quack the Angry Duck No one is quite certain what the emoticon >:U is intended to represent, but many scholars believe it looks like an angry duck. Let's assume that's the case.

Task

Given an integer n between 0 and 3 inclusive, print or return

quack

if n = 0,

>:U

if n = 1,

     U   U
>  : U   U
 >   U   U
>  : U   U
      UUU

if n = 2, or

                  >:U         >:U
>:U               >:U         >:U
   >:U       >:U  >:U         >:U
      >:U         >:U         >:U
         >:U      >:U         >:U
      >:U         >:U         >:U
   >:U       >:U  >:U         >:U
>:U               >:U         >:U
                     >:U>:U>:U

if n = 3.

You can assume the input will always be valid. There should be no leading space in the output, but any amount of trailing space is fine. Ducks (with the possible exception of @cobaltduck) have no tolerance for loopholes. Shortest code in bytes wins.

Java, 303 286 bytes

Saved 17 bytes thanks to @VoteToClose!

Not actually meant to be the shortest, I just thought it would be fun to try in Java.

Creates a list of string variables representing common strings, then creates an array of all the outputs, then prints the right one.

String a(int y){String n="\n",d=">:U",A=" ",B=A+A,C=B+B,D=C+C,a="U"+B+" U"+n,G=D+A,H=C+B,c=d+G+d+n,E=B+A,F=C+E;String[]z={"quack",d,C+A+a+">"+B+": "+a+" >"+E+a+">"+B+": "+a+C+B+"UUU",D+D+B+c+d+D+F+c+B+A+d+F+d+B+c+H+d+G+c+G+d+H+c+H+d+G+c+E+d+F+d+B+c+d+D+F+c+D+D+C+A+d+d+d};return z[y];}

Ungolfed:

String a(int y) {
    String n = "\n", d = ">:U", A = " ", B = A + A, C = B + B, D = C + C,
            a = "U" + B + " U" + n, G = D + A, H = C + B, c = d + G + d + n,
            E = B + A, F = C + E;
    String[] z = { "quack", d, C + A + a + ">" + B + ": " + a + " >" + E + a + ">" + B + ": " + a + C + B + "UUU", D + D + B + c + d + D + F + c + B + A + d + F + d + B + c + H + d + G + c + G + d + H + c + H + d + G + c + E + d + F + d + B + c + d + D + F + c + D + D + C + A + d + d + d };
    return z[y];
}

This is my first answer on this site, so please tell me if I have done something wrong.


How many paths are available? Objective
Find out how many possible (unique) paths you can take to get from the top left of a NxN grid to the bottom right.
The program will receive either 1 integer (or 2 for -20 points bonus) as input for the gridsize.
Input has to be anywhere in the range of 1..2000.
Output will be a string containing the number of possible paths in either decimal or hex format.
Moving
You can only move in 2 directions, right and down.
Example
This example will show the possible paths in a 2x2 grid so you can see what correct paths are.

I gave each line a different color, the output for a 2x2 grid will be 6.
This will be a big number
Indeed, it will be a big number, huge, enormous, gigantic or any other word you can come up with. Just to keep the fun in the challenge you are not allowed to use any plugins, libraries, native functions or any other thing I forgot to name that allows you to handle integers that would exceed an int64. So come up for a creative way to handle this.
Restrictions
As said before you cant use anything simular to BigInteger in C# for example.
Write an algorithm to solve this problem rather than a built-in function that would destroy the challenge.
Scoring
This is codegolf so obviously the score is based on the length of your code.
Achievements

Y U NO SQR() - The program accepts non square grids ex. [4,3], [100,20] etc. Reward: -20 points + invisible baby panda
Need for Speed! - The size of the grid will not result in a significant difference in the runtime where 1 second is considered significant. Reward: -20 points + Invisible bamboo for the baby panda (you dont want him to starve right?)
IT'S OVER NINE THOUSAANNNNDD - The program accepts gridsizes over 9000 Reward: -20 points + Invisible unicorn costume (baby panda size) Coz asians love cosplay

Assumptions
You can assume the following:

The input will never be a negative integer.
The input will always be >0 and never >2000.
You will always start at [0,0] and move to [N,N]

These baby pandas are sad and lonely, I cant take care of them all by myself so I need your help. Get on with it and claim your own baby panda while theyre still fresh ^.^ (instant delivery guaranteed.)
Happy coding :D

C, 201-20-20=161
Completely refactored since rev 0. Bonuses claimed: non-square and over 9000.
#define B i%w][j]
char a[22000][5999];n,m,i,j,w=21669,c;main(){scanf("%d%d",&n,&m);
for(a[w/2][w/4]=1;i<w*(n+m);i+=2)for(j=5418;j--;a[1+B-=c*10)c=(a[1+B=(a[B+a[2+B+c)%48+48)>57;
printf("%s",a[w/2+n-m]);}

Algorithm
Calculating a number like 4000!/(2000!)^2 using multiplication and division seemed rather complicated to me. Instead I went for an approach based on iterating through the rows of Pascal's triangle, using only addition.
Here's an example using an int32 type, just to show the algorithm clearly:
int a[999],n,m,i,w=997;
main(){
  scanf("%d %d",&n,&m);
  a[w/2]=1;
  for(i=0;i<w*(n+m);i+=2)a[i%w+1]=a[i%w]+a[i%w+2];
  printf("%d",a[w/2+n-m]);
}

Where n+m is the number of rows of Pascal's triangle (counting the 1 at the top as row zero.) At the end of the program, a[] contains rows x and x-1 of Pascal's triangle, the even row in the even cells, and the odd row in the odd cells.
It's important that w is an odd number, so that on each pass through the array it alternates between writing to the odd and even cells. Also, it is important to ensure that the 1 used to initialise the array is not overwritten on the first pass. This requires that w/2 be even. I will explain this later.
This program will give the right answer, up to about n=m=16, after which the integer type overflows.
Ungolfed code
This works in the same way, but uses an array of char to store the decimal digits (in big endian format.)  In order to minimise the code needed to print the answer, the calculations are performed using the ASCII values (add 48 to each value.)
Note that the value of w is enough to hold rows 9000 and 8999 the same time (a total of 9001+9000=18001 big numbers.) We actually get as far as row 18000 of Pascal's triangle, so by that stage there will not be enough space in the array to hold all 9001+9000 big numbers, and some wrapping around will occur. But this does not affect the central cell of row 9000, which is the only cell we are interested in.
Besides adding whitespace, I have explicitly spelt out the #define and ungolfed w/4 to the correct value of 5417. This value is chosen because 18000C9000 has 5417 digits.
char a[22000][5999];
n,m,i,j,w=21669,c;
main(){
  scanf("%d%d",&n,&m);
  for(a[w/2][5417]=1;i<w*(n+m);i+=2)                       //Initialise array with a 1 in least significant bit of the middle cell of [a]. Loop through the numbers of each row of Pascal's triangle.
    for(j=5418;j--;a[1+i%w][j]-=c*10)                      //Loop through the digits of each number. The code to subtract 10 from the digit if carry flag `c` is executed after the following line.
      c=(a[1+i%w][j]=(a[i%w][j]+a[2+i%w][j]+c)%48+48)>57;  //Update the cell with a digit that is the sum of the ones to the left and right, taking into account the carry, and using mod 48 arithmetic in order to store the number as its ASCII code. The return value of the assigment to a[1+i%w][j] is compared with ASCII 57 (`9`) and if it is greater the carry flag `c` is set.
  printf("%s",a[w/2+n-m]);
}

Output
My first program took about an hour to print 4000C2000. This one can handle more digits and a higher number of rows to comply with the over 9000 rule. Consequently it takes about 15 hours to print 4000C2000 and would take several days to print 18000C9000.
For 2000x2000 it prints the following (formatted to 80 columns for clarity.) This can be verified to be correct here: http://www.wolframalpha.com/input/?i=4000C2000
First 50 rows of 80 zeros (total 4000) omitted
00000000000000000000000000000000000000000000000000000000000000000000000000000000
00000000000000000000000000000000000000000000000000000000000000000000000000000000
00000000000000000000000000000000000000000000000000000001662897875033835069539536
82646038155801622559738864034512798427681344501750925293497511985938004836061174
06787175851646432467983900275415704358907838322828226892377078626044702804227263
60225612674740415245206094268141079326236405795693301673758014841914146088010797
10165776274135023159100265188426666848338060694979313461996523028997743355283203
07681570747572865349817098575890269928612521344100050157521073022188690505729147
51382188762791861883958161617214384992392748400481691029679535864524592128327086
43054316262086765263594646961335049751537926540975614276702537605304524934071255
73064101385096253973516475386956779128378613359541658838021140118989221026997673
52312197112642059780157612212146003819787455505953360709346068359603711700350715
41788401648588967587345651743656288974543012791416766391390825096496908159194487
46858927217899313004799502582220660617063988223169179908327236982684836052004811
13856792890524143074688488766572261180609865630282282923756619604128170737791195
46057911790152387847927530536412500605466256862821891455217494809727772321234293
80354002249110229834175370966913440248688425483608677217484634416362795730488526
6233145705056647940287649067948285761750402006009891416640


Graphical, networked, two-(human)-player Tic-Tac-Toe Create a Tic-Tac-Toe game that allows two human players to play against each other using two networked devices.

Requirements:

Network play.
Program must let both players know whose turn it is.
Program must show who won and how (like drawing a line through the three in a row).
Graphical game board displayed for both players.
Player moves inputted "graphically" (point and click, etc...).
Enforce all Tic-Tac-Toe rules.

Preferred:

Any libraries are allowed but smaller libraries are better.
Support as many different platforms/devices as possible.
Make it "pretty".

I would love to invent scoring that would take into account the "Preferred" points, but that appears impossible.  So vote for the code that does the best on the "Preferred" points.

Scoring:

byte count / vote count
lowest score wins

PHP, work in progress (474 chars / 2 upvotes = 237 score)

It's fully functional except it doesn't have win detection yet.

What I really like about this solution is that I only learned PHP about 3 days ago, so the code is probably terrible. :D

t.php, 474 chars (newlines can be removed and are there only for readability):

<?php
$f=file("a");$p=$_GET["p"];if($p!="x"&&$p!="o")die();
if(isset($_GET["m"])){$s=$f[0];$s[intval($_GET["m"])]=$p;fwrite(fopen('a','w'),$s.($f[1]=='x'?'o':'x'));echo"back";}
else{$i=0;while($i<9){$s=($p==$f[1]&&$f[0][$i]=='.')?'a':'div';echo"<$s href='t.php?p=$p&m=$i'>".$f[0][$i++]."</$s>";}echo $f[1]."'s turn";}
?>

reset.php, 57 chars

<?php fwrite(fopen('a','w'),"..........\nx");?>Reset done

It's live on my website. Player X should go to this URL:

http://keyboardfire.com/misc/tictactoegolf/t.php?p=x

And Player O should go here:

http://keyboardfire.com/misc/tictactoegolf/t.php?p=o

(don't worry, I added a check that only lets player "o" or "x" in so that you can't do any fancy XSS stuff :P)

To reset, go here:

http://keyboardfire.com/misc/tictactoegolf/reset.php

Obviously, it's really easy to cheat (moving for the other player, randomly resetting the board, etc.), but it's code golf so it doesn't matter :P


Crash IRB (interactive Ruby) Ruby comes with a built-in REPL, which is quite handy.

Your challenge is to crash it in the least amount of code!

The definition of "crash" is "make it exit in an unintended way." This means exit, quit, abort, irb_exit, irb_quit, et. al. are not valid answers.

Furthermore, you may not cause any side-effect to any other part of the system. For example, `rm -rf /` is not valid either.

Any version 1.9.3 or above is valid. If your code only works on a specific version of Ruby, you may specify that in the answer.

The final restriction is that you may not rely on any gems.

This is code-golf, so the shortest code that crashes IRB will win!

16 characters

String=0
String=0

Not the shortest, but I think it's funny that it doesn't crash until the second line. Generates roughly 20 lines of text before IRB exits. For some reason it cannot be shortened to for instance 2.times{String=0}.

edit

Of all the answers so far, this is the only one that has worked for me (and it works in all versions I could get my hands on), and I've tested all of them in these versions:

On whatever kind of Linux I get when ssh'ing into my university:

ruby 1.9.2p180 (2011-02-18 revision 30909) [x86_64-linux]
ruby 1.8.5 (2006-08-25) [x86_64-linux]

Mac OS X Mavericks default:

ruby 2.0.0p247 (2013-06-27 revision 41674) [universal.x86_64-darwin13]

Installed through Homebrew on OS X:

ruby 1.9.3p448 (2013-06-27 revision 41675) [x86_64-darwin12.4.0]

edit 2

7 characters

Combining my first version (and/or @Howard's answer, for maximum cross reference) with @chinese perl goth's answer:

STDIN=0


Approx how many search results When one performs a search query using Google, one of the first things you see is an approximation of how many results were found. Today, you'll be simulating this in as few bytes as possible.
Input
A short string of length at most 10 with characters from a-z.
Output
The approx count that Google reports for the number of hits.
Test Cases
query string -> approximate number of results
fish -> 2340000000
quantock -> 1390000
codegolf -> 891000
google -> 9340000000
e -> 22500000000
bzoea -> 34700
zoea -> 529000

Extra Clarifications
You may use any regional Google you like.
You can either scrape the page resulting from the search query, or interface with Google APIs.
Search queries are usually in the format https://www.google.com/query?q=<query>
This is code-golf, so the shortest code in bytes wins

Python 3, 158 137 131 bytes
Using requests module and a doctored User-Agent header. Still looking for a shorter functioning UA header.

lambda q:get(f'http://goo.gl/search/{q}',headers={'User-Agent':'Firefox/8'}).text.split('out ')[1].split()[0]
from requests import*

Try it online!


Compactify the input Given a word, your task is to compact it by saving its first character and removing any other vowel (aeiou).

Input

Your input can be the word in STDIN, a function argument or any other input format that doesn't break the standard loopholes.  You can assume the input only consists of lower characters.

Output

Your output must be the word, compacted.

Examples

i -> i
ate -> at
potato -> ptt
ksboejqfgcrauxpwivtzndlhmy -> ksbjqfgcrxpwvtzndlhmy

Score

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

05AB1E, 6 bytes
ćsžMм«

Try it online!
Explanation
       Input (e.g.). potato
ć      Head extract. otato, p
 s     Swap        . p, otato
  žM   Vowels      . p, otato, aeiou
    м  Remove      . p, tt
     « Concatenate . ptt

Implicit output    .


Ninjas in a Chat Log Thanks to HyperNeutrino for making more test cases
Often in chat, someone will ask a question, and multiple people will answer it at the same time. Usually, the person who was beaten to the gun will say "ninja'd", creating even more unnecessary chat.
Given a chat log similar to the following:
Community: Hi
Test: Hi
Rando: What is 4 times 4?
Test: @Rando 16
Community: @Rando 16
Community: ninja'd

You are looking for the number of extraneous lines, which in the above exchange is 2. Two users both replied to another user with the same text, although he only wanted one answer, and then the second user said "ninja'd".
Extraneous Messages
Note that for the following statement, a message is only the content left of the :<space>. However, if an extraneous message is removed, the <username>:<space> is also removed.
Your only task is finding extraneous messages in the input, and counting them. The first type of extraneous message is a message starting with @ that is basically (spaces and case differences are ignored) the same as the message before it. The second type of extraneous message is a message reading exactly ninja'd (case insensitive) immediately after an extraneous message of the first type by the same user (there will never be users with the same name in different cases, and the same user will always be in the same case).
Input
Your input is the chat log, including the user's names, followed by a colon and a space, followed by their message. You may take the input as a newline-separated string, a list of strings, or another appropriate input format.
Output
Your output is the number of extraneous messages.
Test Cases
Community: Hi
Test: Hi
Rando: What is 4 times 4?
Test: @Rando 16
Community: @Rando 16
Community: NINJA'D

2

A: how is everyone doing today
B: good
C: good
C: this doesn't work: `print5`
A: @C add a space
B: @C add aSpace
B: ninja'd
C: ninja'd

2

A: test
B: @A hi
C: @Ahi
C: ninja'd

2

A: test
B: @A hi
B: @A hi
B: ninja'd

2

A:
B: @
B: @
B: ninja'd
B: ninja'd

2

A: ninja'd
B: ninja'd
C: @B ninja'd
B: @B ninja'd
B: ninja'd
C: ninja'd
C: ninja'd

2

Test: test
Testie: @Test TESTIE
Test: @Testie TESTIE
Test: ninja'd
Testie: TESTIE
Test: TESTIE

0

A: @B hi
C: @B hi
C: ninja'd
B: @C no
A: @CNO
A: ninja'd

4

Retina, 50 bytes

T`l`L

(:@.*)¶(.+)\1
b$2a
b(.*)a¶\1:NINJA'D
aa
a

Try it online!


Find nearest number in a given array This is inspired by a real world problem I had. I'm curious to see if there is any clever way to go about this.

You are given two unsorted arrays, A and B, each containing an arbitrary number of floats. A and B don't necessarily have the same lengths. Write a function that takes the elements of A sequentially and finds the nearest value in array B. The result has to be contained in a new array.

Win condition

Shortest code wins (as usual).

APL, 13 17

(21 byte in UTF-8)

B[{↑⍋|⍵-B}¨A]

If you want true lambda (A as left argument and B as right):

{⍵[⍺{↑⍋|⍺-⍵}¨⊂⍵]}

How it works:

{...}¨A invokes lambda function {...} with every A value (instead of invoking with A as array), gathering results to array of same shape

|⍵-B computes absolute values of difference between argument ⍵ and all in B (- is subtraction, | is abs).

↑⍋ takes index of least element (⍋ sorts array returning indices, ↑ get first element)

B[...] is just fetching element(s) by index(es).

The solution is quite strightforward, altough it uses
wonderful feature of APL's sorting function returning permutation vector (sorted element's indices in original array) rather than sorted array itself.


Ambiguous Roman Numeral Magic Squares The king of Ancient Rome is having difficulties determining if a magic square is valid or not, because the magic square he is checking does not include any separators between the numbers. He has hired a software engineer to help him determine if a magic square is valid or not.

Input Description

Input comes in on STDIN or command line arguments. You cannot have the input pre-initialised in a variable (e.g. "this program expects the input in a variable x"). Input is in the following format:

<top>,<middle>,<bottom>

Each of <top>, <middle>, and <bottom> is a string that will only ever contain the uppercase characters I, V, and X. It will not contain spaces or any other characters. Each string represents three Roman numerals, thus resulting in a 3x3 matrix of numbers. However, these Roman numerals may (but not necessarily) be ambiguous. Allow me to illustrate this with an example. Consider the following example row of three Roman numerals, with no spaces between each number:

IVIIIIX

Because there are no spaces between the letters, there are two possibilites to the numbers here:

1, 8, 9 (I VIII IX)
4, 3, 9 (IV III IX)

When you consider that all three rows of the matrix can be ambigious, there is the potential for there to be many different 3x3 matrixes from a single input.

Note that sequences such as 1, 7, 1, 9 (I VII I IX) are not possible because each row will always represent three Roman numerals. Also note that the Roman numerals must be valid, so sequences such as 1, 7, 8 (I VII IIX) are also not possible.

Output Description

Output:

An integer A, where A is the number of unique 3x3 matrixes that can be formed from the ambigious input, and:
A truthy value if any of the unique 3x3 matrixes form a magic square, or:
A falsy value if none of the unique 3x3 matrixes form a magic square.

The truthy and falsy values must be consistent. They are seperated by a comma.

Some explanation is required on what is counted as unique. As long as a matrix does not have exactly the same numbers in exactly the same positions as a previously found matrix, it is counted as unique. This means that reflections, etc. of previously found matrixes are counted as unique.

Example Inputs and Outputs

In these examples, I use true as my truthy value and false as my falsy value.

Input: VIIIIVI,IIIVVII,IVIXII
Output: 24,true
(The magic triangle is 8-1-6, 3-5-7, 4-9-2.)

Input: IIIXVIII,IVIII,VIIII
Output: 210,false

Extras

You are not allowed to use inbuilt Roman Numeral conversion functions if your chosen language has one.