Magic Square, Magic Code A magic square is an \$ n \times n \$ square grid, such that the sum of the integers on each row and column are equal. Note that the definition which will be used in this challenge is different than the one used by Wikipedia, since

diagonal sums are not accounted for
the numbers are not required to be distinct or in the range \$ 1, 2, ..., n^2 \$

Task

Write a program/function such that given an \$ n \times n \$ square, return Truthy if it is a magic square, and Falsey otherwise. There is a catch, however. The source code itself must also form a magic square, where each character in the source code corresponds to its Unicode codepoint.

Rules/Clarifications

You may take input in any reasonable format (e.g. 2D array, flattened list, etc.)
The source code should be a list of \$ n \$ strings, each consisting of \$ n \$ characters, joined by newlines.
The unicode character should be in its composed representation.
Here is a program to check if your program/function is a magic square

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

05AB1E, 11 bytes

Executed code is the same as this answer. I was extremely lucky all the required characters were in the 05AB1E codepage.

ø«O
Ëq¶
/Öí

Try it online!  Verify it!


Parse a Unicode vulgar fraction Objective

Given a string with single Unicode vulgar fraction, parse it to a rational number.

Valid inputs

A valid input is one of:

¼ U+00BC; one quarter
½ U+00BD; one half
¾ U+00BE; three quarters
⅐ U+2150; one seventh
⅑ U+2151; one ninth
⅒ U+2152; one tenth
⅓ U+2153; one third
⅔ U+2154; two thirds
⅕ U+2155; one fifth
⅖ U+2156; two fifths
⅗ U+2157; three fifths
⅘ U+2158; four fifths
⅙ U+2159; one sixth
⅚ U+215A; five sixths
⅛ U+215B; one eighth
⅜ U+215C; three eighths
⅝ U+215D; five eighths
⅞ U+215E; seven eighths
⅟ (U+215F; fraction numerator one) followed by ASCII decimal digits (U+0030 – U+0039)
ASCII decimal digits followed by ⁄(U+2044; fraction slash) followed by ASCII decimal digits

There are exceptions. See below.

Invalid inputs

If the denominator is zero, the parser must fall in an erroneous state. This includes:

Monadic failing
Returning an erroneous value
Throwing an error

Rules

Encoding of the input doesn't matter.
Output type and format doesn't matter either. Though native rational number type is preferred, a pair of integers is permitted.
Inputs that are neither valid nor invalid fall in don't care situation. This includes:

Whole numbers
Improper fractions
Reducible fractions
Fractions with zero numerator
Negative fractions

Examples

⅛ (U+215B) parses to one eighth.

⅟13 (U+215F U+0031 U+0033) parses to one thirteenth.

24⁄247 (U+0032 U+0034 U+2044 U+0032 U+0034 U+0037) parses to twenty-four 247ths.

1⁄7 (U+0031 U+2044 U+0037) parses to one seventh. Note that ⅐ and ⅟7 will parse to the same.

0 (U+0030) falls in don't care situation. It's a whole number.

9⁄8 (U+0039 U+2044 U+0038) falls in don't care situation. It's an improper fraction.

4⁄8 (U+0034 U+2044 U+0038) falls in don't care situation. It's reducible to one half.

↉ (U+2189) falls in don't care situation. Its numerator is zero.

-½ (U+002D U+00BD) falls in don't care situation. It is negative.

1⁄0 (U+0031 U+2044 U+0030) must make the parser be in erroneous state. Its denominator is zero.

Ungolfed solution

Haskell

import Control.Monad
import Data.Ratio
import Text.ParserCombinators.ReadP as ReadP
import Text.Read
import Text.Read.Lex

fractionParser :: ReadP Rational
fractionParser = choice [
    char '¼' >> return (1 % 4),
    char '½' >> return (1 % 2),
    char '¾' >> return (3 % 4),
    char '⅐' >> return (1 % 7),
    char '⅑' >> return (1 % 9),
    char '⅒' >> return (1 % 10),
    char '⅓' >> return (1 % 3),
    char '⅔' >> return (2 % 3),
    char '⅕' >> return (1 % 5),
    char '⅖' >> return (2 % 5),
    char '⅗' >> return (3 % 5),
    char '⅘' >> return (4 % 5),
    char '⅙' >> return (1 % 6),
    char '⅚' >> return (5 % 6),
    char '⅛' >> return (1 % 8),
    char '⅜' >> return (3 % 8),
    char '⅝' >> return (5 % 8),
    char '⅞' >> return (7 % 8),
    char '⅟' >> do
        d <- readDecP
        guard (0 /= d)
        return (1 % d),
    do
        n <- readDecP
        char '⁄'
        d <- readDecP
        guard (0 /= d)
        return (n % d)
    ]

Raku, 17 bytes

{S!\⅟!1/!.EVAL}

Try it online!

Returns a rational number type. Raku actually natively supports unicode literals and operators, though it doesn't do ⅟, so we need to substitute for that. Also, division by zero won't cause an error, but returns a value that causes an Exception when you try to use or print it.


Recording xiangqi moves The game of xiangqi, also known as Chinese chess, is a chess-like game popular in China, Vietnam, Taiwan, and other East Asian countries. The colours of the two sides in xiangqi are red and black. There are 16 black pieces in xiangqi: the 1 general (G), 2 advisor (A), 2 elephant (E), 2 horse (H), 2 chariot (R), 2 cannon (C), and 5 soldier (S). The vertical lines are known as files (columns), and the horizontal lines are known as ranks (rows).

A notation system partially described in A Manual of Chinese Chess and used by several computer software implementations describes moves in relative terms as follows:

[single-letter piece abbreviation][former file][operator indicating direction of movement][new file, or in the case of purely vertical movement, number of ranks traversed]

The file numbers are counted from each player's right to each player's left. For black, the file numbers are shown in the picture, white background.

In case there are two identical pieces in one file, symbols + (front, higher rank) and - (rear, lower rank) are used instead of former file number. If there are more than two, +(highest rank), 2(2nd highest rank), 3(3rd highest rank), ... is used. It's fine either you use the number or - to mean the lowest rank if more than two exist. If more than one file contain multiple identical pieces, both former file and order can't be omitted, but the piece abbreviation can be omitted.

[former order in the file][single-letter piece abbreviation][operator indicating direction of movement][new file, or in the case of purely vertical movement, number of ranks traversed]
[former order in the file][former file][operator indicating direction of movement][new file, or in the case of purely vertical movement, number of ranks traversed]

A plus sign(+) is used to indicate forward movement. A minus sign(-) is used to indicate backwards movement. A dot or period(.) or equal sign(=) is used to indicate horizontal or lateral movement. For a piece that moves diagonally, the plus or minus sign is used rather than the period.

Thus, if the five soldiers are at (5,6), (7,6), (9,6), (5,8), (7,8), then each of them moving one rank forward are expressed as -5+1, -7+1, S9+1, +5+1, +7+1; two horses at (3,4) and (3,8) each moving to (4,6) are expressed as -H+4 and +H-4; five soldiers are at (5,6), (7,6), (5,4), (5,8), (7,8), then each of them moving one rank forward are expressed as 25+1, -7+1, 35+1, +5+1, +7+1; two horses at (3,4) and (5,8) each moving to (4,6) are expressed as 3H+4 and 5H-4.

Given the current position and destination of the piece to move, and a list/set containing all positions of the same kind of pieces, output its expression. Input format is quie flexible. Shortest code win.

Samples: (use format that first item of the array is moved)

S [(5,6), (7,6), (9,6), (5,8), (7,8)] (5,7) -> -5+1 or -S5+1
S [(7,6), (5,6), (9,6), (5,8), (7,8)] (7,7) -> -7+1 or -S7+1
S [(9,6), (5,6), (7,6), (5,8), (7,8)] (9,7) -> S9+1
S [(5,8), (5,6), (7,6), (9,6), (7,8)] (5,9) -> +5+1 or +S5+1
S [(7,8), (5,6), (7,6), (9,6), (5,8)] (7,9) -> +7+1 or +S7+1
H [(3,4), (3,8)]                      (4,6) -> -H+4
H [(3,8), (3,4)]                      (4,6) -> +H-4
H [(3,8)]                             (4,6) -> H3-4
S [(5,4), (5,8), (7,8), (5,6), (7,6)] (5,5) -> 35+1 or -5+1 or 3S5+1 or -S5+1
S [(5,6), (5,8), (7,8), (5,4), (7,6)] (5,7) -> 25+1 or 2S5+1
S [(5,8), (5,6), (7,8), (5,4), (7,6)] (5,9) -> +5+1 or +S5+1

Pieces starting places and moving rules about from place(x0,y0), to place(x,y) and their distance r, if that helps:

G (5,1)      r=1 & 3<x<7 & y<4
A (4,1)(6,1) r^2=2 & 3<x<7 & y<4
E (3,1)(7,1) r^2=8 & y<6
H (2,1)(8,1) r^2=5
R (1,1)(9,1) (x-x0)(y-y0)=0
C (2,3)(8,3) (x-x0)(y-y0)=0
S (1,4)(3,4)(5,4)(7,4)(9,4)
             r=1 & y>=y0 & (y>y0 | y>5)

Stax, 63 bytes
÷Qa9═wë•Θ╣äUuâ£▼+∙8WU▓kw≈▲!.┤α@∟┐₧╨═ºî⌂z▼0╬⌂6╕ú▄O&⌂¼^Mgâ╗╕.î¡☼:

Run and debug it
Takes input as <position before> <piece type> [<other pieces>] <position after>.
Unpacked:
;x\EE-c:+"=+-"@s|aaE=s,h?$+Ydx]+MEsxh|I@|oc%vcaHX-xn^$'-?'+?z?,b'S<*!,h$*++y+

Run and debug it
Explanation:
The first part calculates the last part: The direction of movement and the resulting file/change in rank:
;x\EE-c:+"=+-"@s|aaE=s,h?$+Yd
;x                            Push position after and before
  \                           Zip -> [[file after, file before], [rank after, rank before]]
   E                          Push files and ranks separately
    E-                        Difference in ranks (after - before)
      c:+                     Copy and get the sign (-1, 0, +1)
         "=+-"@               Index into the string "=+-" (-1 means last one)
               s|a            Get the absolute value of the difference in rank
                  aE=         Check whether file before = file after (pure vertical movement)
                     s        Swap with abs of difference in rank
                      ,h      Get file after
                        ?     If file before = file after:
                                abs(rank after - rank before)
                              Else:
                                file after
                              (this is the number in the end)
                         $    Convert to string
                          +   Concat the sign (-=+) and number.
                           Yd Store in Y register and delete from stack.

The second part calculates the index in the file (+, - or a digit):
x]+MEsxh|I@|oc%vcaHX-xn^$'-?'+?z?
x]+                               Append the position before to the list of other pieces
   ME                             Push list of files, then list of ranks
     s                            Swap the two
      xh|I                        Find indices with file = file before
          @                       Get ranks of these
           |o                     Calculate destination index of each element if the ranks were sorted
             c%v                  Get length of the array - 1
                                    (no. of other pieces in file)
                ca                Get the array of dest. indices again
                  HX              Get the last index (= index of the moving pieces)
                                    and store in register X
                    -             Then subtract from the no. of other pieces
                     xn^          ... and increment the result
                                    -> That's the index from big rank to small
                        $         ... and convert to string
                         '-?      If register X = 0 (lowest rank): "-"
                                  Else: The index from big to small
                            '+?   If index from big to small = 0 (high rank): "+"
                                  Else: Result from above
                               z? If length of array = 1: ""
                                  Else: Result from above

So this means:

If there are no other pieces in this rank, ""
Else if we have the highest rank, "+"
Else if we have the lowest rank, "-"
Else, the index of the rank as a string

These conditionals work in a somewhat special way: First, all the conditions are produced, most important to least important, then the true branch of the first condition is made (the index as a string). After this we push the falsy value for each condition, least important to most important, directly before performing the conditional ?.
The third part checks whether we need to add the file number:
,b'S<*!,h$*
,           Get the piece type
 b          Copy both the result of part 2 and the piece type
  'S<       Test whether the piece type is NOT "S"
              (actually less than "S", because all other piece types come before S in ASCII)
     *      Repeat the result of part 2 by the result of this test:
            "" if the piece type is "S"
            the result of part 2 otherwise
      !     Negate this, "" is falsey.
            => This means NOT (part 2 is empty AND NOT piece type is "S")
            => Part 2 is empty iff this is the only piece in the file
            => NOT (only piece in file AND NOT piece type is "S")
            => NOT only piece in file OR piece type is "S"
       ,h   Push the file before
         $  and convert it to string
          * Repeat that string by the result of above check:
            "" unless other pieces in file or piece type is "S"

So, after parts 1-3, the stack looks like this:
<position in the file (+, -, or number)> <piece type> <file if necessary>

And the Y register contains the movement itself (from part 1).
The final part combines these into a single string:
++y+ "<position in the file>" "<piece type>" "<file if necessary>"
+    "<position in the file>" "<piece type><file if necessary>"
 +   "<position in the file><piece type><file if necessary>"
  y  "<position in the file><piece type><file if necessary>" "<movement>"
   + "<position in the file><piece type><file if necessary><movement>"

This final result is implicitly output.


5 Seconds to Find Pie Pi times e (or Pie if you like ambiguous notation) to 100 decimal places is:

8.5397342226735670654635508695465744950348885357651149618796011301792286111573308075725638697104739439...

(OIES A019609) (argument for possible irrationality)

Your task is to write a program that takes in a positive integer N, and outputs Pi*e truncated to N decimal places. e.g. if N = 2, then the output should be 8.53.

This is an optimization problem, so the submission that can give the correct output for the highest value of N will win.

To ensure all submissions are judged using the same computing power, your code must be run on ideone, using any language they support. According to the ideone faq, there is a 5 second run time limit for not logged in users. This 5 second limit is the one you must use, not the 15 second limit for logged in users. (See faq for other limits like memory, code size, etc.)

Specifically, anyone not logged into ideone should be able to run your program on ideone for all values of N from 1 to some maximum Nmax, and see correct output nearly all of the time. without any Time limit exceeded or Memory limit exceeded, etc. errors. The submission with the largest Nmax wins.

(Whether the actual time taken is a smidge over 5 seconds doesn't matter as long as ideone doesn't give errors. "Nearly all of the time" is defined as more than 95% of the time for any particular N.)

Details

You may use any mathematical method you like to calculate Pi*e, but you may not hardcode the output beyond the first dozen digits of Pi, e or Pi*e.

Your program should be able to work for any N, given unlimited resources.
You may use built in Pi or e constants if your language happens to have them.

You may not access websites or resources external to your code (if ideone even allows this).
Beyond hardcoding and accessing external resources, anything that ideone allows is almost certainly fine.
Your input and output must (obviously) work with whatever ideone provides for i/o (stdin/stdout only it seems). It's fine if you need quotes around the input N or the output is something like ans = ..., etc.
Please include a link to an ideone snippet of your code with your Nmax as input.
If there happens to be a tie (only likely if multiple submissions hit the 64kB output character limit) the highest votes answer wins.

Python - 65535

http://ideone.com/knKRhn

from math import exp, log

def divnr(p, q):
  """
    Integer division p/q using Newton-Raphson Division.
    Assumes p > q > 0.
  """

  sp = p.bit_length()-1
  sq = q.bit_length()-1
  sr = sp - sq + 1

  s = []
  t = sr
  while t > 15:
    s = [t] + s
    t = (t>>1) + 1
  # Base-case division
  r = (1 << (t<<1)) / (q >> sq-t)

  for u in s:
    r = (r << u-t+1) - (r*r * (q >> sq-u) >> (t<<1))
    t = u
  return (r * (p >> sq)) >> sr

def pibs(a, b):
  if a == b:
    if a == 0:
      return (1, 1, 1123)
    p = a*(a*(32*a-48)+22)-3
    q = a*a*a*24893568
    t = 21460*a+1123
    return (p, -q, p*t)
  m = (a+b) >> 1
  p1, q1, t1 = pibs(a, m)
  p2, q2, t2 = pibs(m+1, b)
  return (p1*p2, q1*q2, q2*t1 + p1*t2)

def ebs(a, b):
  if a == b:
    if a == 0:
      return (1, 1)
    return (1, a)
  m = (a+b) >> 1
  p1, q1 = ebs(a, m)
  p2, q2 = ebs(m+1, b)
  return (p1*q2+p2, q1*q2)

if __name__ == '__main__':
  n = input()

  pi_terms = int(n*0.16975227728583067)

  # 10^n == e^p
  p = n*2.3025850929940457

  # Lambert W_0(p/e) a la Newton
  k = log(p) - 1
  w = k - (k-1)/(k+1)
  while k > w:
    k = w
    w -= (k - p*exp(-k-1))/(k+1)

  # InverseGamma(e^p) approximation
  e_terms = int(p / w)

  pp, pq, pt = pibs(0, pi_terms)
  ep, eq = ebs(0, e_terms)

  z = 10**n
  p = 3528*z*ep*abs(pq)
  q = eq*abs(pt)

  pie = divnr(p, q)
  print pie,

Ideone doesn't seem to have gmpy2 installed, which is unfortunate for at least two reasons. One, because it would make the calcuation a lot faster, and two, because it makes any formula requiring an arbitrary precision square root impractical.

The formula I use for π was listed by Ramanujan as Formula (39):

which converges at the rate of ~5.89 digits per term. To my knowledge, this is the fastest converging series of its kind that doesn't require the evaluation of an arbitrary precision square root. Formula (44) in the same paper (convergence rate ~7.98 digits per term) is most often referred to as the Ramanujan Formula.

The formula I use for e is the sum of inverse factorials. The number of terms required is calculated as Γ-1(10n), using an approximation I found on mathoverflow. The Lambert W0 component is found using Newton's Method.

The calculation of each of these summations is done via the Fast E-function Evalution (more generally known as binary-splitting), originally devised by Karatsuba. The method reduces a summation to n terms to a single rational value p/q. These two values are then multiplied to produce the final result.

Update:
Profiling revealed that over half of the time needed for the calculation was spent in the final division. Only the upper most log2(10n) bits of q are needed to obtain full precision, so I trim a few off beforehand. The code now fills the Ideone output buffer in 3.33s.

Update 2:
Since this is an optimization challenge, I decided to write my own division routine to combat CPython's slowness. The implementation of divnr above uses Newton-Raphson Division. The general idea is to calculate d = 1/q · 2n using Newton's Method, where n is the number of bits the result requires, and compute the result as p · d >> n. Runtime is now 2.87s - and this is without even chopping off bits before the calculation; it's unnecessary for this method.


Carve some ASCII jewels! March 13 is recognized as National Jewel Day, which is the theme of this challenge. So, given an integer n where n is greater than 0, create an ASCII jewel. For example:

n = 1          n = 2             n = 3
                                       ______
                     ____             /      \
 __                 /    \            \      /
/  \                \    /             \    /
\  /                 \  /               \  /
 \/                   \/                 \/

The bottom is defined as the very bottom of the jewel to the highest pair of of \/. The rest is the top. For the above example where n = 1:

Bottom: \  /    Top:   __
         \/           /  \

As you can see, the bottom is made of n + 1 layers of \/ with (1 * lines from the bottom) * 2 spaces in between with a maximum of n lines from the bottom of the jewel. If we take the second jewel (n = 2), we can see that:

 ____
/    \
\    /  2 (or n) layers from the bottom with 1*2*2 or 4 spaces in between \/
 \  /   1 layer from the bottom with 1*1*2 or 2 spaces in between \/
  \/    The bottom (0 layers) with 1*0*2 spaces or 0 spaces in between \/

The top is made of one pair of /\ with n*2 spaces in between with n*2 underscores on top.

Rules

Must be able to take in any nonzero positive integers as user input
Must create a jewel with the specs defined above (restated here):

The top is made of one pair of /\ with n*2 spaces in between with n*2 underscores on top.
The bottom is made of n + 1 layers of \/ with (1 * lines from the bottom) * 2 spaces in between with a maximum of n lines from the bottom of the jewel.

Trailing newlines after the jewel, or trailing spaces on each line are allowed.
No standard loopholes allowed

Winning Criteria

Least bytes wins!

Charcoal, 17 bytes

Code:

ＮβＧ←β_↙↙¹→↘⁺β¹‖Ｍ→

Explanation:

Ｎβ                      # Place the input into β
   Ｇ←β_                 # Draw a line of length β with _ as the filling character
        ↙                # Move the cursor one down and one left
         ↙¹              # Draw a line from the cursor position to one position ↙
           →             # Move the cursor 1 to the right
             ⁺β¹         # Add one to the input and..
            ↘            # Create a line pointing ↘, with the size calculated above
                ‖Ｍ→     # Mirror to the right

A very neat command is ‖Ｍ, which also automatically mirrors / into \.

Uses the Charcoal encoding.

Try it online!


Script that outputs a script that prints a given input Write a piece of code that takes a string as input, and outputs a piece of code in the same language that, when run, will output the initial input string.

It must be able to handle any combination of characters A-Z, a-z, and 0-9.

Example in Python:

import sys
print "print('" + sys.argv[1]  + "')"

Given the input of testing123, it will return print('testing123').

Since this is code-golf, the shortest answer in bytes will win.

pl, 0 bytes
Code:

Try it online!
Explanation:
An empty program in pl is simply a cat program, outputting the exact same as the input.
In pl, all ASCII characters are essentially variables, but when the variable doesn't exist (yet), pl assumes that they are part of a string.


(Can I) Add parentheses to make this true I saw this recent Puzzling question:

Add parentheses to make this true

And saw that one answer used a Python script to try all possibilities.

Your challenge is, given an expression (as a string) and an integer, is to make a program that can tell whether you can add parens to make the expression equal the integer.

For example, if the expression is 1 + 2 * 3 and the integer is 9, than you can add parens like (1 + 2) * 3, which equals 9, so the output should be truthy. But if the expression is 1 + 2 - 3 * 4 / 5 and the integer is 9999999999999, you can't add any amount of parens to make that equal 9999999999999, so the output should be falsey.

Note that the integer input may be positive or negative, but the expression will only contain positive integers. In fact, the expression will always match (\d+ [+*/-] )+ \d (regex). In other words, no parens, no exponents, just +, -, * and /. Standard operator order (* and /, then + and -).

More test cases:

1 + 2 - 3 * 4 / 9 and -1 -> truthy, ((1 + 2) - (3 * 4)) / 9
10 - 9 * 8 - 7 * 6 - 5 * 4 - 3 * 2 - 2 * 1 and 1, falsey, see linked question
10 + 9 - 8 * 7 + 6 - 5 * 4 + 3 - 2 * 1 and 82 -> truthy, (10 + (9 - 8)) * 7 + (6 - 5) * 4 + 3 - 2 * 1
34 + 3 and 15 -> falsey
1 + 2 + 5 + 7 and 36 -> falsey
1 / 10 * 3 + 3 / 10 * 10 and 6 -> truthy, (1/10*3+3/10)*10

Any questions?

You may output the expression with parenthesis if it is possible, for instance (10 + (9 - 8)) * 7 + (6 - 5) * 4 + 3 - 2 * 1 for the last test case. I would prefer this over just a truthy value, but it is up to you. Using 2(5) for multiplication is not allowed, only *.

Python 2, 286 285 282 bytes

from fractions import*
P=lambda L:[p+[L[i:]]for i in range(len(L))for p in P(L[:i])]or[L]
x,y=input()
x=x.split()
for p in P(['Fraction(%s)'%e for e in x[::2]]):
 try:print 1/(eval(''.join(sum(zip(eval(`p`.replace("['","'(").replace("']",")'")),x[1::2]+[0]),())[:-1]))==y)
 except:0

Try it online
Explanation:
This version will print all of the working expressions (with the Fraction objects).
from fractions import*
# Sublist Partitions (ref 1)
P=lambda L:[p+[L[i:]]for i in range(len(L))for p in P(L[:i])]or[L]
x,y=input()
x=x.split()
# Convert all numbers to Fractions for division to work
n=['Fraction(%s)'%e for e in x[::2]]
# Operators
o=x[1::2]
# Try each partition
for p in P(n):
    # Move parens to be inside strings
    n=eval(`p`.replace("['","'(").replace("']",")'"))
    # Alternate numbers and operators (ref 2)
    x=''.join(sum(zip(n,o+[0]),())[:-1])
    # Prevent division by zero errors
    try:
        # Evaluate and check equality
        if eval(x)==y:print x
    except:0

Try it online
References:

Partitioning function

Alternating zip

Saved 3 bytes thanks to Felipe Nardi Batista


Computing time sheets Time sheets
In a work place you often have to complete time sheets. This task is write code to help this.
Input
Two times in a slightly non- standard 12 hour clock signifying the start and end of the day separated by a space.  A third number represents the number of minutes taken for lunch. For example
9:14 5:12 30

This means you started work at 9:14am, finished work at 5:12pm and took 30 minutes for lunch.
You can assume that

Any time in the first column is from 00:00 (midnight) up to but not including 1pm and any time in the second column is 1pm at the earliest up until 11:59pm.
The lunch break is no longer than the working day!

The input format must be as in the examples given.
Task
Your code should read in a file (or standard input) of these triples, and for each one output how long you worked. This output should indicate the number of hours. For the example above this is:
7hr and 58min minus 30 minutes which is 7hr 28min.
Output
Your output must specify the (whole) number of hours and minutes and must not list more than 59 minutes. That is you can't output 2hr 123min. Apart from that, your code can output in any easily human read format that is convenient for you.
Examples
10:00 1:00 30    --> 2hr 30min
12:59 1:00 0     --> 0hr 1min
00:00 11:59 0    --> 23hr 59min
10:00 2:03 123   --> 2hr 0min

MATL, 28 bytes

`jYb0&)YOd.5+wgU13L/- 15XODT

Try it online!


Extended Truth Machine Many people know what a truth machine in programming is. But is time we kick things up a notch. Introducing, the extended truth machine! An extended truth machine takes two things as input, a integer n and a nonempty string s. It outputs s n times with optional trailing whitespace. However, if n is equal to 0, you must output s until the program is manually stopped i.e. it should never terminate.

Also, if n is a negative number, then the string needs to be reversed. For example with s=hello and n=-1, output would be olleh.

Standard methods of input, any kind of output as long as it can handle infinite. If you have an answer that does not handle infinite, feel free to post it if it is interesting or in a language that cannot handle infinite output.

Test Cases

n, s, output

5, "hello world", "hello worldhello worldhello worldhello worldhello world"
0, "PPCG", "PPCGPPCGPPCGPPCG..."
-2, "truThY", "YhTurtYhTurt"
2000, "o", "oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo"

This is code-golf, so shortest code wins!

Here is the original Sandbox post. Edits have been made to it. Thanks go to @ComradeSparklePony for creating the idea of this challenge

Haskell, 57 54 bytes

f 0=cycle
f n|n<0=f(-n).reverse|n>0=concat.replicate n

Explanation:

f 0           -- If n=0 ..
 =cycle       -- infinitely repeat the input
f n|n<0       -- Otherwise, if n<0 ..
 =f(-n)       -- call f with the negative of n ..
 .reverse     -- and the reverse of the input
 |n>0         -- Finally, if n>0 ..
 concat       -- concatenate the result of ..
 .replicate n -- repeating the input n times

-3 bytes thanks to @nimi


FizzBuzz Reverse Solver Synopsis: Given the output of a generalised FizzBuzz program, return the list of factors and words used for the program.

Challenge Description
Imagine a generalised FizzBuzz program that takes in as input a list of factors and words to use and the number to start from. For instance, if the input of this program was
3 2,Ninja 5,Bear 7,Monkey

The program would print out numbers from 3 to 100, replacing numbers divisible by 2 with Ninja, numbers divisible by 5 with Bear, and numbers divisible by 7 with Monkey. For numbers that are divisible then more than one of those terms, the program will concatenate the words, printing things such as NinjaBear or BearMonkey or NinjaMonkey or NinjaBearMonkey. Here's the output of that input:
3
Ninja
Bear
Ninja
Monkey
Ninja
9
NinjaBear
11
Ninja
13
NinjaMonkey
Bear
Ninja
17
Ninja
19
NinjaBear
Monkey
Ninja
23
Ninja
Bear
Ninja
27
NinjaMonkey
29
NinjaBear
31
Ninja
33
Ninja
BearMonkey
Ninja
37
Ninja
39
NinjaBear
41
NinjaMonkey
43
Ninja
Bear
Ninja
47
Ninja
Monkey
NinjaBear
51
Ninja
53
Ninja
Bear
NinjaMonkey
57
Ninja
59
NinjaBear
61
Ninja
Monkey
Ninja
Bear
Ninja
67
Ninja
69
NinjaBearMonkey
71
Ninja
73
Ninja
Bear
Ninja
Monkey
Ninja
79
NinjaBear
81
Ninja
83
NinjaMonkey
Bear
Ninja
87
Ninja
89
NinjaBear
Monkey
Ninja
93
Ninja
Bear
Ninja
97
NinjaMonkey
99
NinjaBear

Note that whenever the program needs to combine words together, it always goes from lowest number to highest number. So it won't print out something like MonkeyBear (since Monkey is a higher number than Bear is).
Your program should take in the output of the generalised FizzBuzz program as input, and output the input given to the generalised FizzBuzz program. In other words, write a "reverse program" for the generalised FizzBuzz program. For instance, given the code block above as input, your program should output 3 2,Ninja 5,Bear, 7,Monkey.
There are some rules that the words will always follow:

It will always be possible to tell exactly what the factors and words are from the input.
Each word will begin with a capital letter and will not contain any other capital letters, or numbers.
Each factor is unique.

Sample Inputs and Outputs
Input:
Calvins
7
Hobbies
9
10
11
Calvins
13
14
15
Hobbies
17
Calvins
19
20
21
22
23
CalvinsHobbies
25
26
27
28
29
Calvins
31
Hobbies
33
34
35
Calvins
37
38
39
Hobbies
41
Calvins
43
44
45
46
47
CalvinsHobbies
49
50
51
52
53
Calvins
55
Hobbies
57
58
59
Calvins
61
62
63
Hobbies
65
Calvins
67
68
69
70
71
CalvinsHobbies
73
74
75
76
77
Calvins
79
Hobbies
81
82
83
Calvins
85
86
87
Hobbies
89
Calvins
91
92
93
94
95
CalvinsHobbies
97
98
99
100

Output:
6 6,Calvins 8,Hobbies

Input:
FryEggman
7
Am
Fry
The
11
FryAmEggman
13
14
FryThe
Am
17
FryEggman
19
AmThe
Fry
22
23
FryAmEggman
The
26
Fry
Am
29
FryTheEggman
31
Am
Fry
34
The
FryAmEggman
37
38
Fry
AmThe
41
FryEggman
43
Am
FryThe
46
47
FryAmEggman
49
The
Fry
Am
53
FryEggman
The
Am
Fry
58
59
FryAmTheEggman
61
62
Fry
Am
The
FryEggman
67
Am
Fry
The
71
FryAmEggman
73
74
FryThe
Am
77
FryEggman
79
AmThe
Fry
82
83
FryAmEggman
The
86
Fry
Am
89
FryTheEggman
91
Am
Fry
94
The
FryAmEggman
97
98
Fry
AmThe

Output:
6 3,Fry 4,Am 5,The 6,Eggman

Input:
DeliciousTartApplePie
DeliciousCreamPancakeStrawberry
DeliciousProfiterole
DeliciousCream
DeliciousPancake
DeliciousCreamStrawberryTart

Output:
95 1,Delicious 2,Cream 3,Pancake 4,Strawberry 5,Tart 19,Apple 95,Pie 97,Profiterole

You can get the code I used to generate the inputs here.

Pyth, 73 bytes

jd+J-101lK.zjL\,Sm,_-F>2+_Jf}d@KTUKd{smtcdf-@dTGUdf>T\:K

That was certaintly a tough one. I think I've covered all the edge cases, including everything in @MartinBüttner's example, and the no repeat factors example.

NinjaBearMonkey, Deliciousness

At the high level, the program first finds all of the words by chopping up the alphabetical strings on capital letters.

Then, the rows are mapped to whether or not each string appears in the row, and each possible factor is tested to see if it produces the same ordering. If it does, the factor is added to a gobal list, which is check to see if the factor was already present. If it was not already present, the factor is used. The strings are ordered by first appearance in the input, which disambiguates the ordering of strings that each appear only once in the same row.

After that, it's just formatting and printing.


Are the lists divisible? Inspired (with the explanation stolen from) this

Background

Say you have two lists A = [a_1, a_2, ..., a_n] and B = [b_1, b_2, ..., b_n] of integers. We say A is potentially-divisible by B if there is a permutation of B that makes a_i divisible by b_i for all i. The problem is then: is it possible to reorder (i.e. permute) B so that a_i is divisible by b_i for all i?
For example, if you have

A = [6, 12, 8]
B = [3, 4, 6]

Then the answer would be True, as B can be reordered to be B = [3, 6, 4] and then we would have that a_1 / b_1 = 2, a_2 / b_2 = 2, and a_3 / b_3 = 2, all of which are integers, so A is potentially-divisible by B.

As an example which should output False, we could have:

A = [10, 12, 6, 5, 21, 25]
B = [2, 7, 5, 3, 12, 3]

The reason this is False is that we can't reorder B as 25 and 5 are in A, but the only divisor in B would be 5, so one would be left out.

Your task

Your task is, obviously, to determine whether two lists (given as input) are potentially divisible. You may take input in any accepted manner, as with output.

Duplicates in the lists are a possibility, and the only size restrictions on the integers are your language. All integers in both lists will be larger than 0, and both lists will be of equal size.

As with all decision-problems the output values must be 2 distinct values that represent true and false.

This is a code-golf so shortest code wins!

Test cases

Input, input => output

[6, 12, 8], [3, 4, 6] => True
[10, 5, 7], [1, 5, 100] => False
[14, 10053, 6, 9] [1,1,1,1] => True
[12] [7] => False
[0, 6, 19, 1, 3] [2, 3, 4, 5, 6] => undefined

Husk, 7 6 5 bytes
Saved 2 bytes thanks to @Zgarb
▼▲‡¦P

Takes argents in reverse order and returns 1 for True and 0 for False.
Try it online!
Explanation
    P     -- Permutations of the first argument
  ‡       -- Deep zip (vectorises function) with second argument
   ¦      --   Does x divide y
 ▲        -- Get the maximum of that list, returns [1,1...1] if present
▼         -- Get the minimum of that list, will return 0 unless the list is all 1s


Bijective mapping from integers to a variable number of bits A variable number of bits is an array of 0 or more bits. So [0, 1] is a variable number of bits, but so is [].

Write a function or program that, given an nonnegative integer returns a variable number of bits such that every integer has a one-to-one (bijective) mapping with an array.

There are an infinite amount of such mappings, you are free to construct one as you please, but it must be one-to-one. Your mapping must conceptually be one-to-one for an arbitrarily sized integer, but it's OK if your implementation fails for large integers due to numerical limits of types in your preferred language (e.g. C's int).

As an example of what is not a one-to-one mapping, is simply listing the binary digits of the integer. In such a system 5 becomes [1, 0, 1] (or 0b101), but it's not one-to-one, because 0b0101 or [0, 1, 0, 1] also means 5.

It should be fairly obvious that a mapping is not one-to-one if it skips an integer (e.g. it doesn't work for 5), but I'd like to make it clear that skipping a variable bit array is also not one-to-one. You must map to every possible variable bit array, including [].

Shortest code in bytes wins.

Python, 20 bytes

lambda n:bin(~n)[4:]

Test:

>> [bin(~n)[4:] for n in range(16)]
['', '0', '1', '00', '01', '10', '11', '000', '001', '010', '011', '100', '101', '110', '111', '0000']

Doing lambda n:bin(n+1)[3:] increments the input, then takes the binary representation with the first symbol removed ([3:] because the prefix 0b is two chars chars). Since any positive number starts with 1 in binary, this uniquely gives a binary representation.

A byte is saved by instead using the bit complement ~n to get the negation -(n+1), and removing the negative sign by chopping off one more symbol.


Can you calculate the average Levenshtein distance exactly? The Levenshtein distance between two strings is the minimum number of single character insertions, deletions, or substitutions to convert one string into the other one.

The challenge is to compute the average Levenshtein distance between two independent and uniformly random chosen binary strings of length n each.  Your output must be exact but can be given in any easy to understand human readable form.

Examples:

These are the answer for n up to 24.

1 1/2
2 1
3 47/32
4 243/128
5 1179/512
6 2755/1024
7 12561/4096
8 56261/16384
9 124329/32768
10 2175407/524288
11 589839/131072
12 40664257/8388608
13 174219279/33554432
14 742795299/134217728
15 1576845897/268435456
16 13340661075/2147483648
17 14062798725/2147483648
18 59125997473/8589934592
19 123976260203/17179869184
20 259354089603/34359738368
21 8662782598909/1099511627776
22 72199426617073/8796093022208
23 150173613383989/17592186044416
24 1247439983177201/140737488355328

Score

Your score is the highest value of  you can reach. Where humanly possible, I will run your code on my Linux machine for 10 minutes and then kill the job to get the score.

Notes

As always this should be a competition per language. I will maintain a leaderboard that shows the best score for each language used in an answer.  I will also give a bounty of 50 points for the first answer to get to n = 20.

My CPU is an Intel(R) Xeon(R) CPU X5460.

Leaderboard

n = 18 in Python+numba by Shamis (timing pending...).
n = 19 in Java by Bob Genom (278 seconds).
n = 19 in C by ngn (257 seconds).
n = 21 in Rust by Anders Kaseorg (297 seconds). 150 point bonus awarded.

Rust, score ≈ 22

This uses a dynamic programming approach (I’ve added an explanation here) whose running time seems to scale as approximately \$\tilde O(2^{1.5n})\$, rather than the \$\tilde O(2^{2n})\$ of a brute-force search.  On my Ryzen 7 1800X (8 cores/16 threads), it gets through \$1 \le n \le 21\$ in 1.7 minutes, \$1 \le n \le 22\$ in 5.1 minutes.

Now using SIMD for the inner loop.

src/main.rs

use fxhash::FxBuildHasher;
use itertools::izip;
use rayon::prelude::*;
use std::arch::x86_64::*;
use std::collections::HashMap;
use std::hash::{Hash, Hasher};
use std::mem;
use typed_arena::Arena;

#[global_allocator]
static ALLOC: mimallocator::Mimalloc = mimallocator::Mimalloc;

type Distance = i8;
type Count = u32;
type Total = u64;

#[derive(Debug)]
struct Distances(__m128i);

impl PartialEq for Distances {
    fn eq(&self, other: &Distances) -> bool {
        unsafe {
            let x = _mm_xor_si128(self.0, other.0);
            _mm_testz_si128(x, x) != 0
        }
    }
}

impl Eq for Distances {}

impl Hash for Distances {
    fn hash<H: Hasher>(&self, state: &mut H) {
        unsafe {
            _mm_extract_epi64(self.0, 0).hash(state);
            _mm_extract_epi64(self.0, 1).hash(state);
        }
    }
}

fn main() {
    let splat0 = unsafe { _mm_set1_epi8(0) };
    let splat1 = unsafe { _mm_set1_epi8(1) };
    let splatff = unsafe { _mm_set1_epi8(!0) };
    let splat7f = unsafe { _mm_set1_epi8(0x7f) };
    let seq = unsafe { _mm_set_epi8(15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0) };
    let grow0 = unsafe {
        _mm_set_epi8(
            -0x80, 0, 0x20, 0, 0x8, 0, 0x2, 0, 0, 0x40, 0, 0x10, 0, 0x4, 0, 0x1,
        )
    };
    let grow1 = unsafe {
        _mm_set_epi8(
            0, 0x40, 0, 0x10, 0, 0x4, 0, 0x1, -0x80, 0, 0x20, 0, 0x8, 0, 0x2, 0,
        )
    };

    for n in 1 as Distance.. {
        if n > 31
            || (n as Count).leading_zeros() < n as u32
            || (n as Total).leading_zeros() < 2 * n as u32
        {
            break;
        }

        let total: Total = (0u32..1 << (n - 1))
            .into_par_iter()
            .map(|a| {
                let mut a_sym = a.reverse_bits();
                a_sym ^= (a_sym >> 31).wrapping_neg();
                a_sym >>= 32 - n as usize;
                if a_sym < a {
                    return 0;
                }

                let arena = Arena::<Distances>::new();
                let stride = (n as usize + 16) / 16 * 16;
                let idx = |i: Distance, j: Distance| i as usize + stride * j as usize;
                let both = |[x, y]: [Distance; 2]| x.max(y);
                let mut worst = vec![[stride as Distance; 2]; idx(0, n + 1)];
                for j in 0..=n {
                    worst[idx(n, j)] = [n - j; 2];
                }
                for i in (0..n).rev() {
                    worst[idx(i, n)] = [n - i; 2];
                    let good = (a >> i & 1) as usize;
                    let bad = good ^ 1;
                    for j in (0..n).rev() {
                        worst[idx(i, j)][good] = both(worst[idx(i + 1, j + 1)]);
                        worst[idx(i, j)][bad] = 1 + worst[idx(i + 1, j)][bad]
                            .min(both(worst[idx(i, j + 1)]))
                            .min(both(worst[idx(i + 1, j + 1)]));
                    }
                }
                let worst: &[Distances] = arena.alloc_extend(
                    worst
                        .into_iter()
                        .map(both)
                        .collect::<Box<[Distance]>>()
                        .chunks(16)
                        .map(|chunk| {
                            Distances(unsafe {
                                _mm_loadu_si128(chunk as *const [i8] as *const __m128i)
                            })
                        }),
                );

                let mut states: HashMap<&[Distances], Count, FxBuildHasher> = HashMap::default();
                let mut new_states = HashMap::default();

                states.insert(
                    arena.alloc_extend(
                        (0..n + 1)
                            .step_by(16)
                            .map(|i| Distances(unsafe { _mm_add_epi8(_mm_set1_epi8(i), seq) })),
                    ),
                    1,
                );

                let bvs: Vec<_> = [a, !a]
                    .iter()
                    .map(|b| {
                        arena.alloc_extend((0..n + 1).step_by(16).map(|i| unsafe {
                            let x = _mm_set1_epi16(((b << 1) >> i) as i16);
                            Distances(_mm_xor_si128(
                                _mm_cmpeq_epi8(
                                    _mm_or_si128(
                                        _mm_and_si128(x, grow0),
                                        _mm_and_si128(_mm_alignr_epi8(x, x, 1), grow1),
                                    ),
                                    splat0,
                                ),
                                splatff,
                            ))
                        }))
                    })
                    .collect();

                for j in 1..=n {
                    new_states.reserve(2 * states.len());
                    let worst_slice = &worst[idx(0, j) / 16..idx(0, j + 1) / 16];
                    for (state, count) in states.drain() {
                        for bv in &bvs {
                            let mut x = j;
                            let mut y = n.into();
                            let mut bound = n;

                            let new_state: &mut [Distances] =
                                arena.alloc_extend(izip!(&**bv, state, worst_slice).map(
                                    |(&Distances(bc), &Distances(yc), &Distances(wc))| unsafe {
                                        let o = _mm_min_epi8(
                                            _mm_add_epi8(yc, splat1),
                                            _mm_sub_epi8(
                                                _mm_insert_epi8(_mm_slli_si128(yc, 1), y, 0),
                                                bc,
                                            ),
                                        );
                                        y = _mm_extract_epi8(yc, 15);
                                        let o = _mm_sub_epi8(o, seq);
                                        let o = _mm_min_epi8(o, _mm_set1_epi8(x));
                                        let o = _mm_sub_epi8(splat7f, o);
                                        let o = _mm_max_epu8(o, _mm_slli_si128(o, 1));
                                        let o = _mm_max_epu8(o, _mm_slli_si128(o, 2));
                                        let o = _mm_max_epu8(o, _mm_slli_si128(o, 4));
                                        let o = _mm_max_epu8(o, _mm_slli_si128(o, 8));
                                        let o = _mm_sub_epi8(splat7f, o);
                                        x = _mm_extract_epi8(o, 15) as i8 + 16;
                                        let o = _mm_add_epi8(o, seq);
                                        let z = _mm_add_epi8(o, wc);
                                        let z = _mm_min_epi8(z, _mm_srli_si128(z, 1));
                                        let z = _mm_min_epi8(z, _mm_srli_si128(z, 2));
                                        let z = _mm_min_epi8(z, _mm_srli_si128(z, 4));
                                        let z = _mm_min_epi8(z, _mm_srli_si128(z, 8));
                                        bound = bound.min(_mm_extract_epi8(z, 0) as i8);
                                        Distances(o)
                                    },
                                ));

                            let bound = unsafe { _mm_set1_epi8(bound) };
                            for (i, Distances(x)) in (0..).step_by(16).zip(&mut *new_state) {
                                *x = unsafe {
                                    _mm_min_epi8(
                                        *x,
                                        _mm_sub_epi8(
                                            bound,
                                            _mm_abs_epi8(_mm_add_epi8(_mm_set1_epi8(i - j), seq)),
                                        ),
                                    )
                                };
                            }

                            *new_states.entry(&*new_state).or_insert(0) += count;
                        }
                    }
                    mem::swap(&mut states, &mut new_states);
                }

                let control = unsafe { _mm_insert_epi8(splatff, (n % 16).into(), 0) };
                Total::from(
                    states
                        .into_iter()
                        .map(|(state, count)| unsafe {
                            count
                                * _mm_extract_epi8(
                                    _mm_shuffle_epi8(state[n as usize / 16].0, control),
                                    0,
                                ) as Count
                        })
                        .sum::<Count>(),
                ) * if a_sym == a { 1 } else { 2 }
            })
            .sum();

        let shift = total.trailing_zeros();
        println!(
            "{} {}/{}",
            n,
            total >> shift,
            (1 as Total) << (2 * n as u32 - 1 - shift),
        );
    }
}

Cargo.toml

[package]
name = "levenshtein"
version = "0.1.0"
authors = ["Anders Kaseorg <andersk@mit.edu>"]
edition = "2018"

[profile.release]
lto = true
codegen-units = 1

[dependencies]
fxhash = "0.2.1"
itertools = "0.8.2"
mimallocator = "0.1.3"
rayon = "1.3.0"
typed-arena = "2.0.0"

Running

RUSTFLAGS='-C target-cpu=native' cargo build --release
target/release/levenshtein

Output

(With cumulative timing data prepended by ts -s %.s.)

0.000008 1 1/2
0.000150 2 1/1
0.000219 3 47/32
0.000282 4 243/128
0.000344 5 1179/512
0.000413 6 2755/1024
0.000476 7 12561/4096
0.000538 8 56261/16384
0.000598 9 124329/32768
0.000660 10 2175407/524288
0.000721 11 589839/131072
0.000782 12 40664257/8388608
0.000843 13 174219279/33554432
0.006964 14 742795299/134217728
0.068070 15 1576845897/268435456
0.310136 16 13340661075/2147483648
1.062122 17 14062798725/2147483648
3.586745 18 59125997473/8589934592
11.265840 19 123976260203/17179869184
33.691822 20 259354089603/34359738368
101.514674 21 8662782598909/1099511627776
307.427106 22 72199426617073/8796093022208
956.299101 23 150173613383989/17592186044416
3077.477731 24 1247439983177201/140737488355328
10276.205241 25 5173410986415247/562949953421312
34550.754308 26 5356540527479769/562949953421312

Static core2 build for Anush


Square root of ASCII art You are working as an intern for a mathematician who really hates TeX, LaTeX, etc. So much so that he has decided to abandon all typesetting whatsoever and make you do all the formatting in ASCII. You got tired of this after a while and decided to start automating parts of it, starting with square roots.

Here's how a square root is made:

###  this is the input
###
###

_____  put a row of underscores stretching one character off either side on top
 ###
 ###
 ###

   _____  put a diagonal of slashes in front going the height of the input
  / ###
 /  ###
/   ###

      _____ put a diagonal of backslashes in front of that, going up half of the input's height rounded up
     / ###
 \  /  ###
  \/   ###

And that's it!

Rules

You are to make a program or function that takes in a string, list of strings  (i.e. lines), or array of characters, and outputs the input transformed according to the description above (not necessarily by the exact same order or process)

You may assume that the input is rectangular if preferred. Trailing whitespace is neither required nor disallowed.

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

Examples:

Input:
40
Output:
  ____
\/ 40

Input:
  ____
\/ 40
Output:
   ________
  /   ____
\/  \/ 40

Input:
/|
 |
 |
_|_
Output:
      _____
     / /|
    /   |
\  /    |
 \/    _|_

Input:
#  #
#  #
#####
   #
   #
Output:
        _______
       / #  #
      /  #  #
\    /   #####
 \  /       #
  \/        #

Python 2, 196 bytes

x=Q=input()
l=len(x)
k=(l+1)/2
q=l+k
x=[[' ']*(q+1)+list(y)for y in x]
for i in range(k):x[i+l/2][i]='\\'
for j in range(l):x[j][q-j-1]='/'
print'\n'.join([' '*q+'_'*(2+len(Q[0]))]+map(''.join,x))

Try it online!

-2 bytes thanks to Step Hen

-13 bytes thanks to Jonathan Allan


Smaller-Base Palindromes For the purpose of this challenge, a smaller-base palindrome (SBP) is a number which is palindromic in a base between 1 and itself (exclusive), and is not a repdigit in the same base.  For example, 5 is a SBP because it is a palindrome in base 2 (101).  The first few SBPs are 5,9,10,16,17,20,21,23,25,26,27,28,29,33...

Your Task:

Write a program or function that, when given an integer i as input, returns/outputs the ith SBP.

Input:

An integer i where 0 <= i < 1,000,000.

Output:

The ith SBP.

Test Cases:

12 -> 29
18 -> 41

Scoring:

This is code-golf, lowest score in bytes wins!

Python 2, 133 119 bytes

-3 thanks to Ovs

-5 thanks to Lynn

1-indexed

j=i=0
n=input()
while n:
 j+=1;l=[];N=i
 while N:l+=N%j,;N/=j
 if{i%j}<set(l)>l==l[::-1]or j>i:n-=j<i;i+=1;j=1
print~-i

Try it online!


Valentine's day greetings card generator Create a program that, given a name as input, will generate a Valentine’s day greeting card featuring that name, with its source code also having a Valentine’s day theme. The greeting can be either ASCII art or a generated picture.

Additional conditions:

The source code has to look like something Valentine's day themed (like a heart, or a poem or anything. Be creative)
All code and related assets need to fit into your answer.
You can use network connections, but you can only download this page (in case this question acquires multiple pages you can download them as well). You can use the StackApps API if you want to.
The "has to look like something Valentine's day themed" rule also applies to anything you try to use from this page (if using network connections).
No other external files are permitted.
You can use the standard library of your language, but no external packages are allowed.

Other restrictions:

None. This is a popularity contest.

Scoring:

Each visible vote (= upvotes minus downvotes) is worth 10 points
For every two upvote on a comment on your answer you get 1 points
Answer having the most score will be accepted on Valentine's day (14 Feb 2014)

**This contest is now closed, thanks for participating! ** You can still add answers if you'd like though

C

What can be more romantic than syntax highlighting?

  *xx=       "De"
 "ar %"     "s:\n"
"Consta"   "nts ar"
"e red, " "variable"
"s are blue.\nIf lo"
"ve had a syntax, I"
 "'d highlight you"
  ".\n",n[9];main(
    ){printf(xx,
      gets(n))
        ;xx;
         }

Output:

$ echo Ilana | ./vanentine
Dear Ilana:
Constants are red, variables are blue.
If love had a syntax, I'd highlight you.


Sequentia Filii Bonacci Leonardo of Pisa (ca. 1175 - ca. 1245) is better known as Fibonacci. But this is actually a short for the Latin "filius Bonacci" (the son of Bonacci) which was made up during the 18th century (according to Wikipedia).

In this challenge, you'll be given an ordinal number (in the literal sense) between 1st and 20th and you have to return the corresponding term in the Fibonacci sequence.

The twist is that the ordinal number will be given in Latin.

Example: "duodecimus" → \$89\$.

Full I/O table

 input              | meaning | output
--------------------+---------+--------
 "primus"           |   1st   |    0
 "secundus"         |   2nd   |    1
 "tertius"          |   3rd   |    1
 "quartus"          |   4th   |    2
 "quintus"          |   5th   |    3
 "sextus"           |   6th   |    5
 "septimus"         |   7th   |    8
 "octavus"          |   8th   |   13
 "nonus"            |   9th   |   21
 "decimus"          |  10th   |   34
 "undecimus"        |  11th   |   55
 "duodecimus"       |  12th   |   89
 "tertius decimus"  |  13th   |  144
 "quartus decimus"  |  14th   |  233
 "quintus decimus"  |  15th   |  377
 "sextus decimus"   |  16th   |  610
 "septimus decimus" |  17th   |  987
 "duodevicesimus"   |  18th   | 1597
 "undevicesimus"    |  19th   | 2584
 "vicesimus"        |  20th   | 4181

Rules

The input is guaranteed to be exactly one of the strings described above.
If that helps, you may take it in full uppercase instead. But it must be consistent for all entries. Mixed cases are not allowed.
Depending on your algorithm and language, hardcoding or computing the terms of the sequence may either win or lose bytes. Both approaches are explicitly allowed.
This is code-golf!

R, 91 86 bytes

Look up the index of the sum of bytes in a brute-forced UTF8 lookup table and use the magic Fibonacci generating function to give the answer.

function(x)round(1.618^match(sum(!x)%%93,!'%(-1!5+3JOSCW6')*.2765)
"!"=utf8ToInt

Try it online!

Edit: -2 bytes by improved numeric rounding

Edit: -3 bytes with a change to the lookup (thanks for the hint, @Giuseppe!)


Olympic Rings Sequence Challenge:

Given an index integer n, either output the n'th item in this sequence, or output the sequence up to and including index n:

25,25,7,28,29,20,21,22,23,14,35,26,7,28,29,20,16,29,12,15,28,21,14,17,30,13,16,29,12,15,28,21,10,6,12,18,15,11,7,13,19,17,13,9,15,21,18,14,10,16,22,19,15,11,17,23,20,16,12,18,24,21,17,13,19,25,23,19,15,21,27,24,20,16,22,28,25,21,17,23,29,16,13,9,15,21,18,14,10,16,22,20,16,12,18,24,21,17,13,19

How does this sequence work?

NOTE: In this explanation, index n is 1-indexed.
Put the numbers 1 through x on two lines of length n*6 - 1, where x depends on the current iteration and the length of the numbers used, and then sum the digits of the n'th/right-most Olympic Rings of those two lines.

The first number in the sequence is calculated as follows:

The length of the lines are 5 (because 1*6 - 1 = 5):
12345
67891(0)

Then leave the digits in an Olympic Rings pattern:
1 3 5
 7 9

And sum them:
1+3+5+7+9 = 25

So n=1 results in 25.

The second number in the sequence is calculated as follows:

The length of the lines are 11 (because 2*6 - 1 = 11):
12345678910
11121314151(6)

Then leave the digits in the second/right-most Olympic Rings pattern:
      7 9 0
       4 5

And sum them:
7+9+0+4+5 = 25

So n=2 results in 25.

The third number in the sequence is calculated as follows:

The length of the lines are 17 (because 3*6 - 1 = 17):
12345678910111213
14151617181920212(2)

Then leave the digits in the third/right-most Olympic Rings pattern:
            1 2 3
             0 1

And sum them:
1+2+3+0+1 = 7

So n=3 results in 7.

etc.

Challenge rules:

When you output the n'th item in the sequence, you are allowed to take the input as 0-indexed instead of 1-indexed, but keep in mind that the calculations of n*6 - 1 will then become (n+1)*6 - 1 or (n+1)*5 + n.
Single numbers of more than one digit can be split up at the end of the first line when we've reached the length n*5 + n-1, so it is possible that a number with 2 or more digits is partially the trailing part of line 1, and partially the leading part of line 2.

General rules:

This is code-golf, so shortest answer in bytes wins.
Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.
Standard rules apply for your answer, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call.
Default Loopholes are forbidden.
If possible, please add a link with a test for your code.
Also, please add an explanation if necessary.

Test cases:

Here is a paste-bin of the test cases 1-1,000, so feel free to choose any of them.

Some additional higher test cases:

1010:   24
1011:   24
2500:   19
5000:   23
7500:   8
10000:  8
100000: 25

Retina, 70 68 62 bytes

.+
10**
.
$.>`
~(`.+
6*$+*
)`.(.+)
L`.{$.1}
%,-6`.

,2,9`.
*
_

Try it online!

Explanation

Let's call the input n, and we'll use 3 as an example.

.+
10**

The 10** is short for 10*$&*_ which replaces the input with a string of 10n underscores.

.
$.>`

Now we replace each underscore with the length of the string up to and including that underscore. So this just results in the number from 1 to 10n all concatenated together (10n is always enough to fill up two lines of the required length).

~(`.+
6*$+*

Eval! This and the next stage will generate the source code of another program, which is then run against that string of concatenated integers.

To generate that program, this stage first replaces the integers with a string of 6n underscores ($+ refers to the program's original input).

)`.(.+)
L`.{$.1}

Then replace those underscores with L`.{…}, where … is 6n-1 (the length of the lines we're looking at). So we've generated a regex, whose quantifier depends on the original input.

When this program gets eval'ed it matches chunks of length 6n-1, of which there will be at least two. For our example input 3, we end up with:

12345678910111213
14151617181920212
22324252627282930

Now we just need to extract the relevant digits.

%,-6`.

First, on each line (%) we remove all but the last five digits (,-6). That gives us

11213
20212
82930

Finally:

,2,9`.
*

We expand every other digit (2) in the first ten (9, this is 0-based) in unary. Those happen to be those in the Olympic Rings positions.

_

And we count the number of resulting underscores, to sum them and convert the result to decimal.


Generate an infinite group of infinite galaxies Here is the challenge as proposed by @trichoplax thanks to him for consolidating my post and standarizing it to PPCG common-rules.

A galaxy is a group of numbers where each one is mapped to another via a precise function f either a symbolic one or mathematical, a structure of numbers sharing some common points with this challenge i got inspired from with an exception that a galaxy sequence is not cyclic, but holds in a black hole, where more than one number can be mapped to it.
A black hole is a specific unique number from a galaxy where all numbers (not individually) are mapped transitively to it, by repeating a function f infinitely over an infinite far number in a same galaxy, or just once if a number is the closest in the same galaxy, for example if the function is the ceiling of the square root then a black hole for the biggest galaxy so far excluding only the number 1 is 2, because mapping the closest number 3 or the infinite repetitively leads to the same number.

Task

Conceive a universe of an infinite number of distinct galaxies where all galaxies encompass an infinite number of integers.

Note that the example of ceiling of square root is banned for two reasons:

The galaxy {1} is finite.
There is a finite number of galaxies.

A valid example, is dividing by the smallest prime factor. This gives an infinite number of infinite galaxies.

2*2*3*5*5*7, 2*3*5*5*7, 3*5*5*7, 5*5*7, 5*7, 7, 7*5*5*5, 7*5*5*5....
5*5*7*11, 5*7*11, 11*7*7*7... , ....
...

Or one galaxy as a tree:

2*2*5 - 2*5 \
             \
2*3*5 - 3*5 - 5
3*3*5 /       |
             /
2*5*5 - 5*5 /
3*5*5 /

Each galaxy consists of all numbers that share the same largest prime factor, and the function takes them all step by step towards the black hole which is that prime factor.

Note also, you may choose any domain of integers as long as the range is infinite, i mean you can exclude a range of numbers that makes the rest still boundless like {1,0} from last example.

Your program takes any integer input via a function's dimension , STDIN, and outputs an integer as the image mapped from this preimage, otherwise prints "error" or any string prespecified for an outputless range of enteries.

For the same example:

(IN/OUTPUT)

   20
   10

   15
   5

   77
   11

   0
   'undefined'

   1
   'undefined'

This is code-golf so shortest program in bytes wins.

I would have really liked to add a bonus-score for anyone who succeeds to find a function generating a universe without trees, alas, bonuses for code-golf are excluded.

Python 2, 15 bytes
lambda n:n>>n%2

The domain is nonnegative integers.


CodeGolf - Barry the messy developer #2 This is a follow-up of
  CodeGolf - Ignore the noise #1
  the only problem being that Barry has made things even worse for us. Lets see what happened

Update

I've added code to create random input and expected output because I'm not that good at explaining what I want, and I guess that sometimes words are more misleading than code (isn't that always?)

Description

Another method in Dumb Corp's API gives us the current price a provider is giving us for an item, the optimal price we would be making maximum sales with and the tendency of that price compared to previous prices as a string UP or DOWN. We need to decide if we should remove the item from the shop or wait.

Input

80,90,UP
150,100,DOWN
65,65,UP
1618,1618,DOWN
840,1200,DOWN
54,12,UP
30,1,UP

For a huge input sample demo with expected output, put the following code (js) in your browsers console and it should output valid random input for testing.

var output = "";
var result = "";

for(i=10;i--;){
  var currentPrice = Math.floor(Math.random() * 10000) + 1;
  var optimalPrice = Math.floor(Math.random() * 10000) + 1;
  var tendency = Math.round(Math.random())?"UP":"DOWN";
  var tresult = "WAIT\n";

  if((currentPrice > optimalPrice && tendency == "UP") ||
     (currentPrice < optimalPrice && tendency == "DOWN")){
       tresult = "STOP\n";
     }

  output +=currentPrice+","+optimalPrice+","+tendency+"\n";
  result +=tresult;
}
console.log(output);
console.log(result);

As always we will have a variable G as our input, however if your language makes it easier for you to simply read the input, that's also fine. The format is constant, and follow the format int,int,string

Desired Output

You're the brains of this operation, Barry should be doing this calculation on the server, but we can't count on him as you should know. You need to output WAIT if the tendency is towards the optimal price, or STOP if the tendency is towards loses.

In other words, with the 80,90,UP as input, we know that there is a product with current price of 80 and optimal price of 90 with a tendency to rise up, so we should WAIT. On the other hand, 840,1200,DOWN means the product price is going down and our optimal price is higher, so we should stop losses by outputting STOP.

If the two prices are identical, output WAIT regardless of the tendency.

Each product in a new line, single word per line:

WAIT
WAIT
WAIT
WAIT
STOP
STOP
STOP

Please, when possible, provide a way of verifying that your code is working since we can't all know just by looking at the syntax. As always, use as few characters as possible and remember that you're not competing against other languages necessarily, your competing against languages with similar syntax


Doing shorter comparisons in PowerShell One of the annoying bits about PowerShell, which helps amplify its disadvantage against other languages in code-golf, is that there are no symbolic comparison or logical operators.

A comparison that could be as short as this:

$x<10&&$x>5

Has to be:

$x-lt10-and$x-gt5

This bloats the code for even the simplest of comparisons by about 50% compared to many other regular scripting and programming languages, never mind any golfing languages. Even an Excel formula for a similar comparison comes up shorter by one character!

=AND(A1<10,A1>5)

Another one that really bugs me:

$x==$k&&$i>9&&$i%10!=0

Has to be:

$x-eq$k-and$i-gt9-and$i%10-ne0

Interestingly, this one's exactly as long as the comparable formula for Excel, but that's mainly due to Excel's lack of a symbolic modulus operator.

=AND(A1=B1,C1>9,MOD(C1,10)<>0)

Is there a way this can be shortened at all, or is this strictly a limitation of the language? Are there any particular scenarios to keep in mind where shortcuts can be used for joining multiple comparisons?

I found a semi-edge case where a multiple comparison can be shortened. This is useful when you need to test two or more variables for equality, and only return true if all tests are true.

Instead of this:

$a-eq$b-and$c-eq$d

You might be able to do this:

"$a$c"-eq"$b$d"

It's worked for me in a Pisano Period script, where I changed:

$a-eq1-and$b-eq0

To:

"$a$b"-eq10

Another example:

$a-eq'apple'-and$b-eq'orange'

Can be cut down to:

"$a$b"-eq'appleorange'


Maximum Recursion Depth Does your language have a maximum recursion depth (MRD)?

Let's say your language has MRD=500

Write a code that finds the recursion depth and outputs the exact value

For the case above your program (or function) should output 500

Code-Golf
Shortest answer wins!

Mathematica, 15 bytes

$RecursionLimit

¯\_(ツ)_/¯

Try it online!


Game of Life arrowslits Background

This challenge is in honor of apsillers, who won the Not as simple as it looks category in Best of PPCG 2016 with their challenge Can my 4-note music box play that song?
Congratulations!

On their "About Me" page, this user has a really neat simulator for the Game of Life cellular automaton.
(Seriously, go check it out.)
On the other hand, the word aspillera is Spanish for "arrowslit".
In light of these facts, this challenge is about arrowslits in Game of Life.

Game of Life arrowslits

In GoL, we will represent an arrow by a glider, and a wall by a sequence of blocks.
A single glider approaches the wall from above, and tries to fly through a gap in the wall (the arrowslit).
Your task is to check whether the glider passes through the arrowslit or crashes into the wall.

Input

Your input is a grid of bits, which represents a GoL configuration.
You can take it in any reasonable format (multiline string of any two distict printable ASCII characters, list of strings, 2D array of integers, 2D array of booleans etc).
For clarity, I will use multiline strings of the characters .# in the following.

The input is guaranteed to have several properties.
First, its height is 2N for some N ≥ 6, and its width is at least 2N+2.
The input will be all .s, except that somewhere on the top three rows is a glider, and on the two middle rows there is a wall of blocks.
The glider will be heading southwest or southeast, and its position is such that if the walls are removed, it will not pass through a side edge before reaching the bottom edge (but it may reach a corner of the grid).
The glider is initially separated from the left and right edges by at least one step of .s.
It can be in any phase.

The wall consists of blocks, which are separated by one column of .s, except in one place, where they will be separated by at least two columns of .s.
Like the glider, the leftmost and rightmost blocks are also separated from the edges by one step of .s.
There will always be at least one block on the left edge and one block on the right edge.

Here is an example of a valid input grid:

....#......................
..#.#......................
...##......................
...........................
...........................
...........................
.##.##............##.##.##.
.##.##............##.##.##.
...........................
...........................
...........................
...........................
...........................
...........................

Output

As stated, your task is to determine whether the glider crashes into the wall or makes it through to the south edge.
For the purposes of this challenge, a crash occurs if the configuration no longer consists of a single glider and the wall of blocks, regardless of what happens later in the simulation.
The following diagrams show the smallest gaps that a southeast glider can go through without crashing in the two distinct phases (the condition for southwest gliders is symmetric).

...#...........
.#.#...........
..##...........
...............
...............
##...........##
##...........##

...#...........
....#..........
..###..........
...............
...............
##...........##
##...........##

If the glider flies through the wall, you shall output a truthy value, and otherwise a falsy value.
For the example above, the correct output is falsy, since the glider will crash into the left part of the wall.

For the purposes of this challenge, you can assume that if you simulate GoL on the input for 2*(height - 3) steps, the glider is on the bottom row in the expected position and the wall is intact, then the output is truthy.

Rules and scoring

You can write a full program or a function.
The lowest byte count wins.

Test cases

I have collected the test cases into a GitHub repository, since they are quite large.
Here are links to the individual files:

Truthy test cases as 2D arrays of bits
Falsy test cases as 2D arrays of bits
All test cases in human-readable format

Python 2, 142 136 135 bytes
-6 bytes thanks to ElPedro
-1 byte thanks to TuukkaX

p=input()
z=p[2].index(1)
m=(p[1][z]-p[1][z+1]<1)*2-1
k=i=0
for b in p[3:]:x=p[2][::m].index(1)+i;k|=1in b[::m][x-2:x+8];i+=1
print 1-k

Try it online! or Verify all test cases
Checking orientation (east/west):

Using z=p[2].index(1) to get the first square on 3rd row (represented by the red square), and then m=(p[1][z]-p[1][z+1]<1)*2-1 to subtract the value on the right (green) from the one on the left (blue), this way all the 4 gliders states that are going to southwest result in 1 (top row in the image), while the ones going to southeast result in 0 or -1.
Then convert : 1 -> -1 and 0,-1 -> 1 to be used on parameter to reverse the lists when dealing with west ones. This way the gliders going southwest are threated the same as the one going southeast.
Glider movement

This is the movement that the glider going southeast do, it has a "ladder" pattern, and the leftmost block on 3rd line is constant to every pattern. Using it as starting point, the surrounding 3 blocks on left and right, and the middle 4 blocks are checked for the presence of 1s (that would be the wall).


Traveling on a flat Earth Coordinates in the flat-Earth world consist of latitude (x) and longitude (y), which are integers in the range 0...9999. Much like Gaussian integers, but they are always written using this notation:

411S 370E

That is, with S or N appended to the latitude, and E or W appended to the longitude, with space(s) between the two components.

Goal

Write a program (not a function) that reads two coordinates, separated by whitespace, and outputs their sum. The first coordinate is a starting point, the second one is a displacement, and the output is the resulting position.

Input/Output

Since this challenge is partially about formatting, I'll try to define the input and output formats unambiguously.

The preferred input format has 1 space between the coordinate components, no leading zeros, and a newline character between the two coordinates. The program must be able to read the preferred format.

The output can contain any amount of whitespace and leading zeros. If it's different from the preferred input format, the program must be able to read this format too.

Just to make it clear, the input cannot (will not) contain any additional formatting characters. Just spaces and newlines where needed.

Scoring

This is an experiment on a new winning condition. I'll choose the winner by accepting an answer in a few weeks. If a better answer appears afterwards, I'll change the accepted answer.

The score for the program is its byte count. The winning program is one that is shorter than 400 bytes, has the fewest byte count, but is written in the most verbose programming language. To determine the winner:

Remove programs with byte count 400 or more (they can participate but cannot win)
Consider only the shortest program for each programming language
The longest program wins

Polyglots compete against programs in all languages in which they are valid (e.g. if a program is valid in both bash and sh, it competes against programs in both languages).

Test cases

In the test cases, the first two lines are the input, and the third line is the output.

0S 0E
0S 0W
0N 0E

(the direction of zero doesn't matter, both in input and output)

0S 9999E
9999N 9999W
9999N 0E

(maximal values)

42S 314W
42N 2718W
0N 3032W

(the direction of zero doesn't matter in the output)

5555N 8888W
7777S 0E
2222S 8888W

(no negative values; change the direction if you need to change the sign)

0001N        4545W
0999N        5454W
1000N        9999W

(if the program outputs leading zeros and several spaces, it must be able to read them; it must also be able to read input that doesn't contain them)

8888N 8888W
9999N 9999W

(invalid input - any behavior is acceptable, including crash and infinite loop)

MATLAB, 327 304 296 290 282 276 267 259  255  253 bytes
I think I'm closing in on a limit now. I've managed to remove 51, 60 68 72 74 bytes from an answer I thought was well golfed. =)
Removed 8 bytes by taking the input inside the strsplit, thanks to Luis Mendo. Removed another 6 bytes by taking all the input into one cell array instead of two. Removed another 8 bytes by taking both last statements inside disp(). Removed 6 bytes by removing char and some brackets. This wasn't possible in a previous revision of the answer. Splitting the cell elements into four variables costed 15 bytes, but saved 24, thus 9 bytes saved! 8 additional bytes due to improved disp scheme. 5*~~s saves two bytes compared to (s>0)*5. Thus 4 new bytes saved (for s and t). Taking the opposite of this last expression saves yet another 2 bytes, 83-5*~s is shorter than 78+5*~~s
Golfed code:
x=strsplit([input('','s'),' ',input('','s')]);[a,b,c,d]=x{:};f=@str2num;n=@num2str;i=@sign;s=f(a(1:end-1))*i(a(end)-79)+f(c(1:end-1))*i(c(end)-79);t=f(b(1:end-1))*i(b(end)-79)+f(d(1:end-1))*i(d(end)-79);disp([n(abs(s)),83-5*~s,32,n(abs(t)),87-18*~t,''])

Same code, but with line breaks:
x=strsplit([input('','s'),' ',input('','s')]);
[a,b,c,d]=x{:};
f=@str2num;
n=@num2str;
i=@sign;
s=f(a(1:end-1))*i(a(end)-79)+f(c(1:end-1))*i(c(end)-79);
t=f(b(1:end-1))*i(b(end)-79)+f(d(1:end-1))*i(d(end)-79);
disp([n(abs(s)),78+5*~~s,32,n(abs(t)),69+18*~~t,''])

Test cases:
Save the above as flat_earth.m
flat_earth
0S 0E
0S 0W
0N 0E

flat_earth
0S 9999E
9999N 9999W
9999N 0E

flat_earth
42S 314W
42N 2718W
0N 3032W

flat_earth
5555N 8888W
7777S 0E
2222S 8888W

flat_earth
0001N        4545W
0999N        5454W
1000N 9999W


Make a 24 Game Solver The 24 Game is a card game. On each cards are four interger numbers. For a player, the goal is to use Addition, Subtraction, Multiplication and Division to end up with 24.

The goal of this code golf/puzzle is to write a program that, for four intergers, will state the one or multiple solutions possible with those numbers.

Further notes:

Should work for an input of any four interger numbers (below 24, above 0). If there is no solution, display 0 solutions as output.
Should output the total number of solutions for this set of four numbers as well as the formulas used.

Brackets ()  can be used (and are often important) to get one or multiple solutions.

Should only display distinct solutions. For instance, when given {1, 1, 4, 4}, it should not display the cases where the ones and the fours are swapped. Also, if have a solution (a*b)*(c*d), you should not output (c*d)*(a*b) as well, for instance.

An example:
For {9, 6, 3, 2}, the program should output:

   (9-3-2)×6
   (6+2)×9/3
   6×2+9+3
   (9-3)×(6-2)
   (3-2/6)×9
   9×6/2-3
   9×3-6/2
   (9+6-3)×2
   8 solutions

Kudos if you can make a working program that follows the rules outlined above.

Even more kudos if you do this in as little code as possible.

Happy Code Puzzling/Golfing!


Split string into n pieces (or pieces of length n) The Challenge
In this challenge you have to do two different (but related) tasks depending of the order of the input.
Your program will recieve a string s and an integer n as input and will

split s into pieces of length n if s comes first. The last element will be shorter if necessary.
split s into n pieces of equal length if n comes first. If len(s) is not a multiple of n the first len(s) mod n elements will be one longer.

You may only take those 2 inputs. s will never contain only digits.
Notes

You may use the reverse mapping. Note this in your answer if you do that.
s will only contain printable ASCII characters (no newlines).
You may not use any builtins that solve either those two tasks directly. All other builtins are allowed.
You have to take both arguments from the same source.
You may take the arguments in an ordered list or any other format which clearly indicates their order as long as it is unambiguous.
You may take the input as one string/ stream and use a character which is not a valid input (like a nullbyte) to separate them.
n will always be equal or less than the length of s and greater than zero.
You may output the resulting list in any resonable format as long as it clearly indicates the particular pieces and their order.

Example
Input:  programming, 3
The last element contains only 2 characters, because 11 is not divisible by 3.
Output: ["pro", "gra", "mmi", "ng"]
Input: 3, programming
11 is not a multiple of 3, so the first 2 elements will be one longer:
Output: ["prog", "ramm", "ing"]
Rules

Function or full program allowed.
Default rules for input/output.
Standard loopholes apply.
This is code-golf, so lowest byte-count wins. Tiebreaker is earlier submission.

Test cases
The test cases got generated with this Pyth program (uses builtins, so no valid answer). Thanks to @FryAmTheEggman for providing the base version of that!

3, helloworld -> ['hell', 'owo', 'rld']
helloworld, 3 -> ['hel', 'low', 'orl', 'd']
1, programming -> ['programming']
programming, 1 -> ['p', 'r', 'o', 'g', 'r', 'a', 'm', 'm', 'i', 'n', 'g']
8, programming -> ['pr', 'og', 'ra', 'm', 'm', 'i', 'n', 'g']
programming, 8 -> ['programm', 'ing']
9, code golf -> ['c', 'o', 'd', 'e', ' ', 'g', 'o', 'l', 'f']
code golf, 9 -> ['code golf']
4, 133tspeak -> ['133', 'ts', 'pe', 'ak']
133tspeak, 4 -> ['133t', 'spea', 'k']

Happy Coding!

JavaScript (ES6), 132 bytes

(s,t)=>+t?[...Array(-~(~-s.length/+t))].map((_,i)=>s.substr(i*t,t)):[...Array(s=+s)].map(_=>t.slice(p,p-=~((t.length-p-1)/s--)),p=0)

This is probably hopelessly over-engineered.


What do you see in an inkspot? Rorschach generation' So I'd like you to attempt to generate Rorschach images like the below image:

Here is a link to further inspiration.

This is a popularity contest, but I will say that colours are likely to be more popular than black and white, as well as textures.

Rorschach images are created by folding paper with ink on so one criteria is symmetry.

ASCII art is valid, but will be subject to the same criteria as above.

Python

Not quite the best or smoothest, but here's a python solution:

from PIL import Image
import random
import sys

imgsize = (int(sys.argv[1]), int(sys.argv[2]))
color = (0, 0, 0)
img = Image.new("RGB", imgsize, "white")

for j in range(0,int(sys.argv[3])):
    start = (random.randrange(0, imgsize[0]/2), random.randrange(0, imgsize[1]))
    point = start
    img.putpixel(point, color)

    blotsize = random.randrange(0, int(sys.argv[4]))
    for i in range(blotsize):
        directions = [(point[0], point[1]+1), (point[0], point[1]-1), (point[0]+1, point[1]), (point[0]-1, point[1])]
        toremove = []
        for direction in directions:
            if direction[0]>=(imgsize[0]/2) or direction[1]>=imgsize[1] or direction[0]<0 or direction[1]<0:
                toremove.append(direction)
        for d in toremove:
            directions.remove(d)
        point = random.choice(directions)
        img.putpixel(point, color)

cropped = img.crop((0, 0, imgsize[0]/2, imgsize[1]))
img = img.transpose(Image.FLIP_LEFT_RIGHT)
img.paste(cropped, (0, 0, imgsize[0]/2, imgsize[1]))

img.save("blot.png")

It just makes a "wandering path" for a blot, and makes several of those.

An example usage:

py inkblot.py width height blots blotsize
py inkblot.py 512 512 20 10000

And some example images:


Build a NAND gate using multiple NAND gates A question that had popped up in my head once - how many NAND gates would it take to build a larger, "meta-NAND" gate?

Your task is to build a black-box circuit that takes two input wires A and B and returns one output wire that satisfies A NAND B, subject to the following restrictions:

You must use at least two NAND gates in this construction (and no gates other than NAND).
You may not have null configurations of gates - that is, systems of gates that are equivalent to a gateless wire. (For example, two NOT gates in series are a null configuration.)
You cannot have any stray wires (discarded values or constants).

Fewest gates wins.

Three gates.  Compute (((A nand A) nand B) nand B).  Unlike the four-gate solution above in which three of the four gates compute A nand B, two of them simultaneously, and substituting one of the simultaneous outputs for the other would yield two consecutive inverters, the three-gate solution uses the three gates to compute different functions: "not A", "A or not B", and "A nand B".  Only the last gate computes the desired function.


Prove that a Number is Algebraic Inspired by this answer (emphasis mine):

We will play a game. Suppose you have some number x. You start with x and then you can add, subtract, multiply, or divide by any integer, except zero. You can also multiply by x. You can do these things as many times as you want. If the total becomes zero, you win.
For example, suppose x is 2/3. Multiply by 3, then subtract 2. The result is zero. You win!
Suppose x is 7^(1/3). Multiply by x , then by x again, then subtract 7. You win!
Suppose x is √2+√3. Here it's not easy to see how to win. But it turns out that if you multiply by x, subtract 10, multiply by x twice, and add 1, then you win. (This is not supposed to be obvious; you can try it with your calculator.)
But if you start with x=π, you cannot win. There is no way to get from π to 0 if you add, subtract, multiply, or divide by integers, or multiply by π, no matter how many steps you take. (This is also not supposed to be obvious. It is a very tricky thing!)

Numbers like √2+√3 from which you can win are called algebraic. Numbers like π with which you can't win are called transcendental.

Why is this interesting? Each algebraic number is related arithmetically to the integers, and the winning moves in the game show you how so. The path to zero might be long and complicated, but each step is simple and there is a path. But transcendental numbers are fundamentally different: they are not arithmetically related to the integers via simple steps.

Essentially, you will use the steps used in the question quoted above to "win" the game for given input.
Given a real, algebraic constant x, convert the number to zero by using the following allowed operations:

Add or Subtract an integer.
Multiply or Divide by a non-zero integer.
Multiply by the original constant x.

Input is a string that may contain integers, addition, subtraction, multiplication, division, exponentiation (your choice of ** or ^, exponents are used to represent roots), and parentheses. Spaces in the input are optional, but not in the output. You should output the steps necessary to obtain a result of zero, so multiplying by 7 as one step would be output as *7. A trailing space and/or newline is allowed.
Examples
0               ->  +0 (or any other valid, or empty)
5/7 + 42        ->  -42 *7 -5 (or shorter: *7 -299)
2^(1/3)         ->  *x *x -2
5*(3**(1/4))    ->  *x *x *x -1875
2^(1/2)+3^(1/2) ->  *x -10 *x *x +1

Shortest code wins.

SageMath, 108 bytes

def f(s):p=map('{:+} '.format,numerator(minpoly(sage_eval(s)/1)));return'*'+p[-1][1:]+'*x '.join(p[-2::-1])

Try it on SageMathCell.

Explanation:

Evaluate the string symbolically as an algebraic number (sage_eval()).  Every algebraic number is a zero of some polynomial a[0] + a[1] x^1 + a[2] x^2 + ⋯ + a[n] x^n with rational coefficients a[0], …, a[n] (minpoly()). Multiply all the coefficients by their common denominator to turn them into integers (numerator()), then write this polynomial in the desired output format,

*a[n] +a[n-1] *x +a[n-2] *x … *x +a[1] *x +a[0]

SageMath, 102 bytes, almost

lambda s:(lambda a,*p:'*%d'%a+'*x'.join(map(' {:+} '.format,p)))(*numerator(minpoly(1/sage_eval(s))))

This works for all inputs except 0, because a polynomial for 1/α is a polynomial for α with the coefficients reversed.  :-(


Write a better BCS computer ranking Input

A CSV file, read from standard input, containing the 2011 college football scores with the 4 columns: Winner, Winner Score, Loser, Loser Score.  For example,

Cincinnati,35,Connecticut,27
Pittsburgh,33,Syracuse,20
Baylor,48,Texas,24

This file was generated by a script I have that screen-scrapes rivals.yahoo.com.  Teams that played fewer than 3 games were omitted.

Output

Print to standard output a newline-separated ranking of teams, ordered from "best" to "worst".

It is permitted to output a "truncated" ranking (e.g., Top 25 or Top 50), but this is discouraged.

Scoring

The ranking produced by your program will be scored on its ability to predict the winners of bowl games.

A victory for Team A over Team B is considered "predicted" by your ranking if either:

You ranked Team A higher than (i.e., earlier in the output than) Team B.
You ranked (i.e., listed anywhere in the output) Team A but not Team B.

You get 1 point for each bowl game "predicted" by your ranking.

Highest score gets the accepted answer.  In case of a tie, the earliest submission wins.

Rules

Deadline for entries is Friday, December 16, at 17:00 CST (23:00 UTC).
You may use the language of your choice.
You may use third-party open-source math libraries such as SciPy.
You may submit multiple entries.
The output must be a pure function of the input.  (So if you need an arbitrary tiebreaker in your ranking, don't use rand(), use alphabetical order.)

Scores: It's a tie!

(Based on results from rivals.yahoo.com)

dan04: 11 points

Auburn > Virginia
Baylor > Washington
Boise St. > Arizona St.
Oklahoma > Iowa
Oklahoma St. > Stanford
Oregon > Wisconsin
South Carolina > Nebraska
Southern Miss > Nevada
TCU > Louisiana Tech
Texas > California
Texas A&M > Northwestern

AShelly: 11 points

Arkansas > Kansas St.
Baylor > Washington
Boise St. > Arizona St.
Cincinnati > Vanderbilt
Houston > Penn St.
Michigan > Virginia Tech
Oklahoma St. > Stanford
Rutgers > Iowa St.
South Carolina > Nebraska
Southern Miss > Nevada
TCU > Louisiana Tech

I'll give it a shot.   Here's some ugly Ruby that bases its ranking on how well each team scored compared to the opponent's average points against.  It weights scores based on the opponent's rank in the list, and iterates until it is stable.

class Team
  attr_accessor :wins,:loss,:for,:agn,:rank,:old_rank
  attr_reader :beat,:fell, :name
  def initialize nm
    @name = nm
    @wins=0
    @loss=0
    @for = 0
    @agn = 0
    @beat = []
    @fell  = []
  end
  def win pts,opp,opts
    @wins+=1
    @for+=pts
    @agn+=opts
    @beat << [opp,pts,opts]
  end
  def lose pts,opp,opts
    @loss+=1
    @for+=pts
    @agn+=opts
    @fell << [opp,pts,opts]
  end
  def avgPtsFor
    @for.to_f/(@wins+@loss)
  end
  def avgPtsAgn
    @agn.to_f/(@wins+@loss)
  end
  def score teams
    #most points for scoring above opponents average, scaled by opponent's rank.
    x = @beat.inject(0){|sum,game|opp = teams[game[0]]
      sum+(game[1]/opp.avgPtsAgn*(1-(opp.rank/teams.size)))/@beat.size
      }
    y = @fell.inject(0){|sum,game|opp = teams[game[0]];
      sum+(game[1]/opp.avgPtsAgn*(opp.rank/teams.size))/@fell.size
      }
    (x+y)*(@wins/@loss.to_f)++(@rank/teams.size)/8
  end

end

#read the file
teams = Hash.new
ARGF.each_line{|l|
  result = l.split(',')
  team = teams[result[0]]||Team.new(result[0])
  team.win(result[1].to_i,result[2],result[3].to_i)
  teams[result[0]]=team
  team = teams[result[2]]||Team.new(result[2])
  team.lose(result[3].to_i,result[0],result[1].to_i)
  teams[result[2]]=team
}
#initial ranking by w/l,pts for, pts against
rankings = teams.map{|n,t|t}.sort_by{|t|[t.wins.to_f/t.loss,t.for,t.agn]}
rankings.each_with_index{|a,i|a.rank = (i+1.0)}

#loop
stable = false
loops = 0
while !stable and loops < 1000 do
  stable = true
  n = rankings.size.to_f
  rankings = rankings.sort_by{|t|
  t.score(teams)
  }
  rankings = rankings.each_with_index{|t,i|
    t.old_rank = t.rank
    t.rank = (i+1.0)
    stable = false if (t.rank != t.old_rank)
  }
  loops+=1
end

i=0
puts rankings.reverse.map{|t|"#{i+=1}: "+t.name}

Here's the output:

1: Oklahoma St.
2: LSU
3: Boise St.
4: Houston
5: Stanford
6: Oregon
7: Alabama
8: Arkansas
9: Wisconsin
10: TCU
11: Michigan
12: Georgia
13: South Carolina
14: Arkansas St.
15: Southern Miss
16: Michigan St.
17: West Virginia
18: Baylor
19: USC
20: Georgia Tech
21: Clemson
22: Tulsa
23: BYU
24: Oklahoma
25: Kansas St.
26: Nebraska
27: Virginia Tech
28: Penn St.
29: Notre Dame
30: Cincinnati
31: Northern Illinois
32: LA Lafayette
33: San Diego St.
34: Toledo
35: Florida Intl.
36: Texas A&M
37: Louisiana Tech
38: Ohio
39: Florida St.
40: North Carolina
41: Nevada
42: Iowa
43: Temple
44: Washington
45: West. Kentucky
46: Rutgers
47: Air Force
48: Auburn
49: Wyoming
50: California
51: Texas
52: Ohio St.
53: W. Michigan
54: Virginia
55: Utah St.
56: Florida
57: Missouri
58: Northwestern
59: SMU
60: Vanderbilt
61: Mississippi St.
62: Pittsburgh
63: Ball St.
64: Louisville
65: Purdue
66: East Carolina
67: UCLA
68: Wake Forest
69: Marshall
70: North Texas
71: N.C. State
72: Arizona St.
73: Utah
74: South Florida
75: Hawaii
76: San Jose St.
77: Texas Tech
78: Illinois
79: Kent St.
80: UTEP
81: UCF
82: Tennessee
83: East. Michigan
84: Connecticut
85: Navy
86: Duke
87: Rice
88: New Mexico St.
89: LA Monroe
90: Washington St.
91: Bowling Green
92: Kentucky
93: Syracuse
94: Arizona
95: Fresno St.
96: Troy
97: Oregon St.
98: Army
99: Colorado
100: Iowa St.
101: UNLV
102: UAB
103: Buffalo
104: Middle Tenn. St.
105: Minnesota
106: Boston Coll.
107: Cent. Michigan
108: Colorado St.
109: Mississippi
110: Tulane
111: Florida Atlantic
112: Memphis
113: Idaho
114: Kansas
115: New Mexico
116: Indiana
117: Maryland
118: Akron


Cracking the Enigma? Introduction
The Enigma was one of the first electro-mechanical rotor cipher machines used in World War II. That means that after a single letter is coded, it would change the key for the next letter. This was considered unbreakable by the Germans, due to the enormous key space. Even brute-forcing was almost impossible. However, there was a design error in the Enigma. Encrypting a letter would never result into itself. That means that the letter A can encrypt to every letter except the letter A.
Let's take an example of a coded message:
BHGEFXWFTIUPITHHLPETTTCLOEWOELMRXXPAKAXMAMTXXUDLTWTNHKELEPPLHPRQ

A typical German word was WETTERBERICHT, or weather report in English. With the principe above, we can determine at which locations the word could possibly be:
BHGEFXWFTIUPITHHLPETTTCLOEWOELMRXXPAKAXMAMTXXUDLTWTNHKELEPPLHPRQ
WETTERBERICHT
         ^

This is not possible, because the I can't be encrypted to itself, so we move on 1 place:
BHGEFXWFTIUPITHHLPETTTCLOEWOELMRXXPAKAXMAMTXXUDLTWTNHKELEPPLHPRQ
 WETTERBERICHT
             ^

This is also not possible, so we move another place again:
BHGEFXWFTIUPITHHLPETTTCLOEWOELMRXXPAKAXMAMTXXUDLTWTNHKELEPPLHPRQ
  WETTERBERICHT
   ^

This again is not possible. In fact, the first possible occurence of WETTERBERICHT is:
BHGEFXWFTIUPITHHLPETTTCLOEWOELMRXXPAKAXMAMTXXUDLTWTNHKELEPPLHPRQ
             WETTERBERICHT
0123456789012345678901234567890123456789012345678901234567890123
             ^
             13

So, we return the 0-indexed position of the first possible occurence, which is 13.
The Task

Given a coded message and a word, find the index of the first possible occurence.
Assume that only basic uppercase alphabetic characters will be used (ABCDEFGHIJKLMNOPQRSTUVWXYZ).
If no occurence is found, you can output any negative integer, character, or nothing (e.g. -1, X).
Input may be accepted as argument, on seperate newlines, lists or anything else.
This is code-golf, so the submission with the least amount of bytes wins!

Test cases
Input: BHGEFXWFTIUPITHHLPETTTCLOEWOELM, WETTERBERICHT
Output: 13

Input: ABCDEFGHIJKL, HELLO
Output: 0

Input: EEEEEEEEEEEE, HELLO
Output: -1

Input: XEEFSLBSELDJMADNADKDPSSPRNEBWIENPF, DEUTSCHLAND
Output: 11

Input: HKKH, JJJJJ
Output: -1

JavaScript, 40
(c,p)=>c.search(p.replace(/./g,"[^$&]"))

Using replace, this maps the plaintext input into a regular expression of form /[^H][^E][^L][^L][^O]/ (e.g., for plaintext input HELLO) and then uses search to test for the first index of the ciphertext substring that matches that regex. This regex means "a pattern where the first character is not H, the second character is not E, etc."
$& is a special sequence for replace output that substitutes in the value matched by the first replace argument (in this case, each single character matched by /./).


Find the number in the Champernowne constant Introduction
In base 10, the Champernowne constant is defined by concatenating representations of successive integers. In base 10: 0.1234567891011121314151617... and so on.
You can see that the first appearence of 15 starts at the 20th decimal:
  Position
  0000000001111111111222222222233333333334444444444555555555566666666
  1234567890123456789012345678901234567890123456789012345678901234567
                     ^
0.1234567891011121314151617181920212223242526272829303132333435363738...
                     ^^
                     15 = position 20

The first appearence of 45 starts at the 4th decimal:
  Position
  0000000001111111111222222222233333333334444444444555555555566666666
  1234567890123456789012345678901234567890123456789012345678901234567
     ^
0.1234567891011121314151617181920212223242526272829303132333435363738...
     ^^
     45 = position 4

So, the task is easy. Given a non-negative integer, output the position of the integer in the Champernowne constant.
Rules

You may provide a function or a program
This is code-golf, so the submission with the least amount of bytes wins!

Test cases
Input: 20
Output: 30

Input: 333
Output: 56

Input: 0
Output: 11 (note that the 0 before the decimal point is ignored)

Input: 2930
Output: 48

LabVIEW, 29 LabVIEW Primitives

This uses strings for now. It matches the input as a pattern and outputs the offset - (input lenght -1).