Typesetting multidimensional labels In a steam-punk multidimensional world, our boss wants to affix printed index labels to each drawer in our conglomerate's multidimensional file cabinet.

The boss wants to typeset the entire label sheet as a single form, using a font bought only for this purpose, so we have to order the sorts (metal symbol pieces). Since sorts are very expensive, our order must be for the exact count of each digit-symbol.

For a given (by any means) set of lengths of dimensions ≥ 0, return (by any means) our order, which is the frequency table of digits required to typeset all the Cartesian coordinates. It must be arranged by keyboard order of appearance (i.e. 0 after 9), and may not include orders of 0 sorts, so if no sorts are to be ordered at all (because a dimension has length 0); print nothing.

Bonus of -3 sorts if your code can handle (i.e. print nothing) 0 dimensions too.
Final newline chars are acceptable.
Prohibition on standard loopholes apply.
As mentioned, sorts are expensive, this is therefore codecolf.

A kind soul may edit this challenge to include automated scoring, so include a header like:# LanguageName, 123 sorts

Test cases

Given 11, print:

1 4
2 1
3 1
4 1
5 1
6 1
7 1
8 1
9 1
0 1

because the needed labels are 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, and 11.

Given 2 3, print:

1 5
2 5
3 2

because the needed labels are 1 1,  1 2,  1 3,  2 1,  2 2,  and 2 3.

Given 2 0, print an empty line:

or nothing.

Given 1 2 3, print:

1 11
2  5
3  2

because the needed labels are 1 1 1, 1 1 2, 1 1 3, 1 2 1, 1 2 2, and 1 2 3

Given 5 5 5 5, print:

1 500
2 500
3 500
4 500
5 500

And no, I'm not going to list all 625 labels.

Mathematica, 48 bytes - 3 = 45

Grid@Tally@Flatten@IntegerDigits@Tuples@Range@#&


Increasing Goldbach partitions The Goldbach conjecture states that:

every even number that is greater than 2 is the sum of two primes.

We will consider a Goldbach partition of a number n to be a pair of two primes adding to n.  We are concerned with numbers is of increasing Goldbach partition. We measure the size of a number's Goldbach partitions by the size of the smallest prime in all of that number's partitions.  A number is of increasing partition if this size is greater than the size of all smaller even numbers.
Task
Given an even integer n > 2, determine if n is of increasing Goldbach partition, and output two unique values, one if it is and one if it is not.
This is code-golf, so you should aim to minimize the number of bytes in your source code.
OEIS A025018

Jelly, 12 bytes

ÆRðfạṂ
Ç€M⁼W

Try it online!

How it works

Ç€M⁼W   Main link. Argument: n

Ç€      Map the helper link over [1, ..., n].
  M     Get all indices of the maximum.
    W   Wrap; yield [n].
   ⁼    Test the results to both sides for equality.

ÆRðfạṂ  Helper link. Argument: k

ÆR      Prime range; get all primes in R := [1, ..., k].
  ð     Begin a dyadic chain with arguments R and k.
    ạ   Absolute difference; yield k-p for each p in R.
   f    Filter; keep the q in R such that q = k-p for some p in R.
     Ṃ  Take the minimum.
        This yields 0 if the array is empty.


Draw and label an ASCII hexagonal grid In my previous challenge, I
drew the first diagram mostly by hand (with the help of vim's visual block
mode). But surely there must be a better way...

Given an input of two dimensions, a width and a height, output a hexagonal grid
with those dimensions in ASCII art.

Here's the diagram referenced in the intro (with minor edits), which should be
your output for the input width=7, height=3:

         _____         _____         _____
        /     \       /     \       /     \
  _____/ -2,-1 \_____/  0,-1 \_____/  2,-1 \_____
 /     \       /     \       /     \       /     \
/ -3,-1 \_____/ -1,-1 \_____/  1,-1 \_____/  3,-1 \
\       /     \       /     \       /     \       /
 \_____/ -2,0  \_____/  0,0  \_____/  2,0  \_____/
 /     \       /     \       /     \       /     \
/ -3,0  \_____/ -1,0  \_____/  1,0  \_____/  3,0  \
\       /     \       /     \       /     \       /
 \_____/ -2,1  \_____/  0,1  \_____/  2,1  \_____/
 /     \       /     \       /     \       /     \
/ -3,1  \_____/ -1,1  \_____/  1,1  \_____/  3,1  \
\       /     \       /     \       /     \       /
 \_____/       \_____/       \_____/       \_____/

Notice several things:

The width and height are essentially equivalent to how many hexagons there
are for a given y and x coordinate respectively. These will always be odd
numbers.
Each hexagon is represented by the ASCII art

  _____
 /     \
/       \
\       /
 \_____/

but borders are "shared" between neighboring hexagons.
The comma in the coordinates is always exactly two characters below the
center of the top edge. The x-coordinate is then positioned directly before
the comma, and the y-coordinate directly after.

You may assue that the coordinates will never be too large such that they
would overlap the hexagon's borders.

Input may be taken as a whitespace-/comma-separated string, an array of
integers, or two function/commandline arguments. Output must be a single string
(to STDOUT, as a return value, etc.).

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

The grid above can be used as a test case. The maximum-sized
width=199, height=199 grid is obviously impractical to include here, but the
first few rows and columns should look like the following:

         _____         ___
        /     \       /
  _____/-98,-99\_____/-96,
 /     \       /     \
/-99,-99\_____/-97,-99\___
\       /     \       /
 \_____/-98,-98\_____/-96,
 /     \       /     \
/-99,-98\_____/-97,-98\___
\       /     \       /
 \_____/-98,-97\_____/-96,
 /     \       /     \
/-99,-97\_____/-97,-97\___
\       /     \       /

Ruby, 221 bytes
->w,h{s=' '
a=(s*9+?_*5)*(w/2)+$/
(2-h*2).upto(h*2+3){|y|c=y<4-h*2
a+=[b=c ?s:?\\,s+b,s,''][y%4]
(0-w/2).upto(w/2){|x|a+=["/#{h<y/2?s*7:"%3d,%-3d"}\\",s*7,?_*5,"/     \\"][(y+x*2+w)%4]%[x,y/4]}
a+='//  '[c ?3:y%4]+$/}
a}

Ungolfed in test program
f=->w,h{
  s=' '                                #set s to space for golfing reasons
  a=(s*9+?_*5)*(w/2)+$/                #start building the output with a row of just _ and space

  (2-h*2).upto(h*2+3){|y|              #iterate 4 times for each row of hexagons, plus an extra 2 at the end to finish last row
    c=y<4-h*2                          #condition for first two rows
    a+=[b=c ?s:?\\,s+b,s,''][y%4]      #string to be output before main set of hexagons (spaces for top row, \ for certain other rows

    (0-w/2).upto(w/2){|x|              #iterate through hexagons on each row, 4 lines for each with the following printf type string
      a+=["/#{h<y/2?s*7:"%3d,%-3d"}\\",#line 1:contains ends / \ and numbers
         s*7,                          #line 2 padding spaces
         ?_*5,                         #line 3 padding ___
         "/     \\"][(y+x*2+w)%4]%     #line 0 top of hexagon / \; formula to select string to be printed
           [x,y/4]                     #numbers to be printed (if format for current line does not require them they are ignored)
    }

    a+='//  '[c ?3:y%4]+$/             #ending alternates between / and space; / are suppressed for first two rows
  }
  a
}

puts g[7,3]
puts g[5,5]

Output
As I was finishing debugging, I noticed an ambiguity in the spec. Where w+1 is divisible by 4, the first and last x coordinates are odd, and there is no ambiguity. But where w-1 is divisible by 4 the first and last x coordinates are even. I assumed that the first and last columns should be offset below the next ones. But then I read the previous question and noted in that case it was the odd columns that should be offset below the even ones (note for w-1 divisible by 4 it is not possible to do both.)
That distinction was not made in this question, however. I will leave this up to OP's judgement and rework if necessary, though I'd prefer not to have to.
         _____         _____         _____
        /     \       /     \       /     \
  _____/ -2,-1 \_____/  0,-1 \_____/  2,-1 \_____
 /     \       /     \       /     \       /     \
/ -3,-1 \_____/ -1,-1 \_____/  1,-1 \_____/  3,-1 \
\       /     \       /     \       /     \       /
 \_____/ -2,0  \_____/  0,0  \_____/  2,0  \_____/
 /     \       /     \       /     \       /     \
/ -3,0  \_____/ -1,0  \_____/  1,0  \_____/  3,0  \
\       /     \       /     \       /     \       /
 \_____/ -2,1  \_____/  0,1  \_____/  2,1  \_____/
 /     \       /     \       /     \       /     \
/ -3,1  \_____/ -1,1  \_____/  1,1  \_____/  3,1  \
\       /     \       /     \       /     \       /
 \_____/       \_____/       \_____/       \_____/
         _____         _____
        /     \       /     \
  _____/ -1,-2 \_____/  1,-2 \_____
 /     \       /     \       /     \
/ -2,-2 \_____/  0,-2 \_____/  2,-2 \
\       /     \       /     \       /
 \_____/ -1,-1 \_____/  1,-1 \_____/
 /     \       /     \       /     \
/ -2,-1 \_____/  0,-1 \_____/  2,-1 \
\       /     \       /     \       /
 \_____/ -1,0  \_____/  1,0  \_____/
 /     \       /     \       /     \
/ -2,0  \_____/  0,0  \_____/  2,0  \
\       /     \       /     \       /
 \_____/ -1,1  \_____/  1,1  \_____/
 /     \       /     \       /     \
/ -2,1  \_____/  0,1  \_____/  2,1  \
\       /     \       /     \       /
 \_____/ -1,2  \_____/  1,2  \_____/
 /     \       /     \       /     \
/ -2,2  \_____/  0,2  \_____/  2,2  \
\       /     \       /     \       /
 \_____/       \_____/       \_____/


vim, 139 138 134

$x0xqq%ls<cr><esc>@qq@q:se nosol|%s/,/\t/g|%s/]/\t./|%!column -t -s'<C-v><Tab>'<cr>qwf";;h<C-v>GI|<esc>@wq@wll<C-v>Gls|<esc>0<C-v>Gs| <esc>:%s/"//g<cr>Yp:s/[^|]/-/g|s/|/+/g<cr>YggpkP

Accepts input in the form shown in the test cases. May or may not be valid, as this relies on the input string never containing any ", ,, ], or | characters.

If the input has to be able to contain ]s, then :%s/]/\t./<cr> can be replaced with qe$s<Tab>.<esc>j@eq@e for 2 extra chars. There is no easy way to allow ",| in the input.

Must be run in a Unix environment, as it relies on the column command line tool.

Slightly outdated explanation (by one revision, but that was just a bit of rearranging):

:se nosol<cr>    we need this later: G in visual block shouldn't go to BOL
$x0x             delete the surrounding pair of brackets
qq               record a macro
 %ls<cr><esc>    put each element of the big array on its own line
 @qq             recurse
@q               play back the macro until EOF
:%s/,/\t/g<cr>   replace all remaining commas with tabs
:%s/]/\t./<cr>   replace the ] at the end of lines with tabs and a dot
                 we need this for the line at the right edge of the table
:%!column -t     run the whole file through `column' on tabs
 -s'<C-v><Tab>
 '<cr>
qw               record another macro
 f";;            go forward 3 "s--that is, to the next "column"
 h               go back to the middle of the column
 <C-v>GI|<esc>   insert a line behind the cursor from top to bottom
 @wq             recurse
@w               play back until EOF
ll               move right before the line of dots we added earlier
<C-v>Gl          select the dots
s|<esc>          replace with a line (top to bottom)
0<C-v>G          select all the opening brackets
s| <esc>         again, (the leftmost) line
:%s/"//g<cr>     kill all the quotes around the data
Yp               duplicate bottom line
:s/[^|]/-/g<cr>  replace everything that's not a line with a dash
:s/|/+/g<cr>     now replace the lines with plus signs
YggpkP           put the separators before and after the first line

Thanks smpl for a byte!


Is it a Cyclops number? "Nobody" knows! Task:

Given an integer input, figure out whether or not it is a Cyclops Number.

What is a Cyclops number, you may ask?  Well, it's a number whose binary representation only has one 0 in the center!

Test Cases:

Input | Output | Binary  | Explanation
--------------------------------------
0     | truthy | 0       | only one zero at "center"
1     | falsy  | 1       | contains no zeroes
5     | truthy | 101     | only one zero at center
9     | falsy  | 1001    | contains two zeroes (even though both are at the center)
10    | falsy  | 1010    | contains two zeroes
27    | truthy | 11011   | only one zero at center
85    | falsy  | 1010101 | contains three zeroes
101   | falsy  | 1100101 | contains three zeroes
111   | falsy  | 1101111 | only one zero, not at center
119   | truthy | 1110111 | only one zero at center

Input:

An integer or equivalent types. (int, long, decimal, etc.)
Assume that if evaluating the input results in an integer overflow or other undesirable problems, then that input doesn't have to be evaluated.

Output:

Truthy or falsy.
Truthy/falsy output must meet the used language's specifications for truthy/falsy.  (e.g. C has 0 as false, non-zero as true)

Challenge Rules:

Input that is less than 0 is assumed to be falsy and thus does not have to be evaluated.
If the length of the binary representation of the number is even, then the number cannot be a Cyclops number.

General Rules:

This is code-golf, so the shortest answers in bytes wins!.
Default loopholes are forbidden.
Standard rules apply for your answer with default I/O rules.

This is my first Programming Puzzles & Code Golf challenge, so any feedback on how I should improve would be much appreciated!

Python 2, 30 bytes

lambda n:(2*n^2*n+3)**2==8*n+9

Try it online!

Note that 2*n^2*n+3 is the bitwise xor of 2*n and 2*n+3, because that's Python's operator precedence.


Palindromize this string! Your task is to palindromize a string as follows:

Take the string.

abcde

Reverse it.

edcba

Remove the first letter.

dcba

Glue it onto the original string.

abcdedcba

But here's the catch: since this challenge is about palindromes, your code itself also has to be a palindrome.

Remember, this is code-golf, so the code with the smallest number of bytes wins.


How much more reputation do I need? Programming Puzzles and Code Golf has graduated from beta. Soon we will get a custom site design, and with that the reputation boundaries for privileges will go up. A lot of users will lose privileges on the site. So your task is to write a program that tells us how much extra reputation we'll need to keep our privileges.

Task

Your task is to write the shortest code to find the amount of extra reputation a user will need to keep their current privileges after the site design, given the number of reputation points.

Input / Output

You can accept input and give output in any way you like, so long as it follows these rules:

Input - An integer from 1 to 250000+ inclusive. Your program or function should be able to accept numbers bigger than this, but it must accept numbers in this range.

Output - An integer representing the number of reputation points the user will need to get to keep their current privileges after the graduation.

No standard loopholes, please.

Example algorithm

Set variable i to the input
Set variable r to variable i.
While r is not in list beta:

Subtract 1 from r.

Set n to the position of r in beta.
Set r to item n of graduated.
Set variable o to the result of r - i.
If o < 0:

Set variable o to 0.

Output variable o.

Tables

Table of privileges that will change

 | privilege name              | beta rep | graduation rep |
-+-----------------------------+----------+----------------+-
 | create tags                 |      150 |           1500 |
 | access review queues        |      350 |            500 |
 | cast close and reopen votes |      500 |           3000 |
 | established user            |      750 |           1000 |
 | edit questions and answers  |     1000 |           2000 |
 | create tag synonyms         |     1250 |           2500 |
 | approve tag wiki edits      |     1500 |           5000 |
 | access to moderator tools   |     2000 |          10000 |
 | protect questions           |     3500 |          15000 |
 | trusted user                |     4000 |          20000 |
 | access to site analytics    |     5000 |          25000 |
-+-----------------------------+----------+----------------+-
 | privilege name              | beta rep | graduation rep |

Table of privileges that won't change

 | privilege name               | reputation |
-+------------------------------+------------+-
 | create posts                 |          1 |
 | participate in meta          |          1 |
 | create wiki posts            |         10 |
 | remove new user restrictions |         10 |
 | vote up                      |         15 |
 | flag posts                   |         15 |
 | talk in chat                 |         20 |
 | comment everywhere           |         50 |
 | set bounties                 |         75 |
 | create chatrooms             |        100 |
 | edit community wiki          |        100 |
 | vote down                    |        125 |
-+------------------------------+------------+-
 | privilege name               | reputation |

Testcases

wizzwizz4                |   750 |  2250
cat                      |  2004 |  7996
Dennis ♦                 | 72950 |     0
Dr Green Eggs and Ham DJ |  4683 | 15317
New User                 |     1 |     0

Not all reputation counts are correct at time of writing
If you want your past or present reputation count here, just comment below and I'll maybe add it.


Quining, but with Windows files! Write a quine, that when run, creates itself in the current directory, in a source file named itself. We will be using Windows in this, so the file name (and therefore quine) must have the following limitations:

None of these characters \ / : ? * < > |
Fewer than 211 255 characters

Limitations and assumptions

Your code must be a full program (It's going to be run after all).

No copying from the source file.

You can assume that there isn't another file with your Quine as its name (as it would produce Quine (1)).

Errors are allowed (as long as they don't get into the source code

This is code-golf, shortest code in bytes wins!
Edit
Maybe I wasn't clear, the file with the name of the quine has to actually contain the quine. My bad.

Vitsy, 10 27 bytes

'rddd++&"rdd8++a[v}v1-D);].

If : was allowed, I could shorten this to 11 bytes. :(

Explanation:

'rddd++&"rdd8++a[v}v1-D);].
'                           Capture all instructions as a string until encountering
                              ' again, looping if necessary.
 r                          Reverse the current stack (output is top-down).
  ddd++                     Push char literal ' to the stack.
       &                    Push a new stack to the stack stack.
        "                   Same as ', but " specific.
         r                  Reverse the current stack.
          dd8++             Push char literal " to the stack.
               a            Push 10 to the stack.
                [        ]  Loop forever.
                 v          Capture the top value as a variable.
                  }         Take the bottom item of the stack and put it on the top.
                   v        Dump the variable to the stack.
                    1-      Subtract 1.
                      D     Duplicate the top item.
                       );   Pop n; if n is 0, exit the loop.
               a[v v1-D);]  This is a makeshift for loop with 10 iterations.
                          . Pop the top stack as n, and the second stack as o.
                              Write a file called "n" with the contents of "o".

The two stacks will be identical at the end. On some Java versions, this may throw a FileNotFoundException due to different implementations of the FileInputStream class.

Previous answer before edit:

&'rddd++}.

Explanation:

&           Push a new stack to the stack stack.
 'rddd++    Modified standard quine.
        }   Move the ' to the right place.
         .  Pop the top stack as n, and the second stack as o. Write a file called
                 "n" with the contents of "o". (Quine name, no content)

Because I might as well, here's a diagram of the steps that occur within the stacks (each stack is represented by []):

Initial state: [[]]

&              [[], []]
                  Push a new stack to the stack stack.

 '             [[], ["r", "d", "d", "d", "+", "+", "}", ".", "&"]]
                  This stack state occurs because ' will loop around the line
                    until finding the next '.

  r            [[], ["&", ".", "}", "+", "+", "d", "d", "d", "r"]]
                  Reverses the top (last) stack.

   ddd         [[], ["&", ".", "}", "+", "+", "d", "d", "d", "r", 13, 13, 13]
                  Push thirteen thrice.

      ++       [[], ["&", ".", "}", "+", "+", "d", "d", "d", "r", "'"]
                  Because char ' is 39 = 13 + 13 + 13.

        }      [[], [".", "}", "+", "+", "d", "d", "d", "r", "'", "&"]]
                  Takes the bottom item, then puts it on the top.

         .     []
                  Writes a file with content from the second-to-top stack and the
                    name as the concatenation of all elements in the top stack,
                    with top member priority (backwards from my representation).

I'm actually not sure how this works right; minute changes cause this to break. For example, placing the & in various other locations should work just as well, but it causes ClassCastExceptions, IOExceptions, and ArrayOutOfBoundsExceptions depending on where you put it. I might need to do some bugfixing.


How to golf wrap-around assignments? This is a relatively simple question. I'm trying to golf a Snake game I've written, and I'm trying to work out if there's a way to golf the following conditional assignments which control x and y coordinates of the snake ensuring a wrap around of the play area:
if (P<0) {
  P = T-1;
}
if (P>T-1) {
  P = 0;
}
if (Q<0) {
  Q = T-1;
}
if (Q>T-1) {
  Q = 0;
}

Is there a simpler way of expressing these, regardless of the value of T?

Try the following, it ensures x to be inside [0, n] (say n = 5), only when x > -n and x < 2n.

x = (5 + x) % 5

Thanks to ovs!
Try it online!

As mentioned by xash in the comments, if you want to make it work for any x, then do
x = ((x % 5) + 5) % 5

Try it online!


Sandbox Visualization Module Emulator The Zachtronics game TIS-100 contains a graphics display called the visualization module. I could try and explain the specs of this module, but the game's manual will do a better job:

(As you may have guessed, the motivation of this problem is to create a code golf challenge in which TIS-100 is the optimal language.)
Your job is to, in as few characters as possible, implement a program which will output the correct image for any valid input sequence. There are no requirements on what happens for an invalid input sequence. This can be a graphical window or console output. This includes strings of more than 1 command! If it has multiple -1s, multiple lines should be drawn.
Test Cases:
Input:

    3, 4, 4, 3, 2, 1, 0, 1, 2, 3, 4, -1

Output:

Input:

    1, 1, 4, 4, -1, 8, 8, 4, 4, -1

Output:

Input:

    5, 5, 4, -1, 5, 5, 0, -1

Output:

The simple TIS implementation is:
TIS-100, 64 55 Bytes
-9 thanks to feersum
@1
MOV UP ANY
@5
MOV UP ANY
@9
MOV UP ANY
@10
MOV ANY ANY

An additional byte is added as a single character in the filename is relevant.

Ruby, 114 bytes

->h,g=[0]*792{h.chunk{|x|x<0&&p}.map{|z,(x,y,*r)|g[36*y+x,r.size]=r}
puts'P3 36 22 5',g.map{|i|i>3?'5 0 0':[i]*3}}

This function takes its input as an array of ints, and writes the resulting image to STDOUT in the human readable version of PPM format. For those unfamiliar, the PPM image format is an uncompressed image format that's, essentially, a whitespace separated list of RGB values.

About PPM

More particularly, it begins with a short header of the format P3 W H M, where P3 is a magic number, W is the width of the image, H is the height of the image, and M is an int from 1 to 65536 representing the maximum possible value a color channel can have. For instance, if M = 255, then the RGB triplet (255, 255, 255) represents white. If M = 10, then (10, 10, 10) is white.

After the header, each pixel is described, row by row, by providing an RGB triplet for its color, with each value separated by spaces. It has the neat property that you can use it to represent an image as human readable text. For instance, a 3x1 pixel image containing a red pixel, a green pixel, and a blue pixel would be:

3 1 255
255 0 0   0 255 0   0 0 255

The precise whitespace used doesn't matter, so the above image is equivalent to, among many others:

3 1 255
255
 0    0          0       255        0
        0     0       255

Explanation of Code

The reason all that was necessary was to explain why, when you run the program, you'll see output that looks like this:

P3 36 22 5
0
0
0
3
0 # And so on...

It's a PPM! And it's generated like this:

# Create an array g, full of 0s, of size (36*22) to hold the image
g = [0] * 792
# Break the input array into chunks, splitting on values < 0
h.chunk{|x|x < 0 && p}
# Use each chunk to fill the subarray of g beginning at its x and y coordinates
 .map{|z,(x,y,*r)|g[36*y+x,r.size]=r}
# Print the header ...
puts'P3 36 22 5',
# ... and the colors, replacing each color id with itself repeated 3 times
# (for the various shades of gray) or '5 0 0', in the case of red, and
# separating each item with a newline.
g.map{|i|i>3?'5 0 0':[i]*3}

If you take this output and paste it into a text file, you'll be able to view it in any image viewer capable of opening PPMs.

Try it online!


Plug it back in tonight or this weekend This is my first code golf so please let me know if it's too broad or if I'm missing any information for a good puzzle!

Challenge

In Ontario and possibly other areas of the world, electricity is billed using Time-Of-Use (TOU) pricing, which varies the cost per kilowatt-hour according to when you use power.

Given a date and time, I want to know whether I'm in an on-peak (red), mid-peak (yellow), or off-peak (green) time period.

Input

Assume that input is provided in an acceptable timezone-less ISO 8601 date-time format with the minimum precision of hours: YYYY-MM-DDThh[:mm[:ss]] (the T is literal).

Examples

2014-09-01T14
2014-09-01T17:30
2014-09-01T17:30:02

Output

The output should be a string On, Mid, or Off.

Rules

Shortest code wins
For the purposes of this challenge, ignore statutory holidays
Assume the information found in this post. The actual rules of time-of-use pricing might change in the future by the Ontario Ministry of Energy.

Information

Summer weekdays (May 1st to October 31st)

Off-peak: 19h00 - 07h00
Mid-peak: 07h00 - 11h00 and 17h00 - 19h00
On-peak: 11h00 - 17h00

Winter weekdays (November 1st to April 30th)

Off-peak: 19h00 - 07h00
Mid-peak: 11h00 - 17h00
On-peak: 07h00 - 11h00 and 17h00 - 19h00

Weekends

Off-peak: All day

Python 2 - 164

from datetime import*
d,t=input().split('T')
y,m,d=map(int,d.split('-'))
t=int(t[:2])
print'OMOfinfd'[(1+((10<t<17)==(4<m<11)))*(date(y,m,d).weekday()<5<6<t<19)::3]

If needed, below is a explanation of the logic in the final line:

The final line prints a slice of 'OMOfinfd' depending on the evaluation of its conditionals.

First, evaluate the operation 1+((10<t<17)==(4<m<11)).

If the XNOR between the conditions 10<t<17 and 4<m<11 is False, this will evaluate to 1+False => 1+0 => 1. Otherwise, the operation will evaluate to 1+True => 1+1 => 2.
Finally, multiply that result of the above operation by whether the day is a weekday and whether the time is between 6am-7pm.

If this is False, either the day is a weekend or the time is between 7pm-6am, and the result will be (1|2)*0 => 0. Otherwise the result will be (1|2)*1 => 1|2.

A result of 0 will print Off, 1 will print Mid, and 2 will print On.


Find the min and max number of substitutions The Levenshtein distance between two strings is the minimum number of single character insertions, deletions and substitutions needed to transform one string into the other.  Let us call insertions, deletions and substitutions "edit operations".  We will say that any sequence of \$k\$ edit operations that transforms one string into another one is optimal if \$k\$ is also the Levenshtein distance between the two strings.

For example, take the strings \$ab\$ and \$ba\$.  The optimal sequence of edit operations "insert \$b\$ at index 0", "delete the final character" transforms \$ab\$ into \$ba\$.  However a different optimal sequence "substitute the first character for a \$b\$",  "substitute the second character for an \$a\$" also transforms \$ab\$ into \$ba\$. In general there may be many different optimal sequences of edit operations for a given pair of strings.

For an optimal sequence of edit operations we are interested in counting the number of substitutions in the sequence.  In particular, for a given pair of strings, we want to count the smallest possible number of substitutions in an optimal sequence of edit operations and also the largest possible.  We will assume that both strings have the same length.

Example

0000 0000 . In this case every optimal sequence has length 0 and so min = max = 0.
0010 1001 . Levenshtein distance 2 by one insertion and one deletion. min = max = 0.
1100 1110 . Levenshtein distance 1. min = max = 1. There is no optimal sequence with an insertion or deletion.
1010 1100 . Levenshtein distance 2. min = 0. max = 2.
1010 0111 . Levenshtein distance 3. min = 1. max = 3.
0011 1100 . Levenshtein distance 4. min = 0. max = 4.
10000011 11110100. Levenshtein distance 6. min = 2. max = 6.
000111101110 100100111010. Levenshtein distance 5. min = 1. max = 5.
0011011111001111 1010010101111110. Levenshtein distance 7. min = 3.  max = 7.
0010100001111111 0010010001001000. Levenshtein distance 7.  min = 5. max = 7.
10100011010010110101011100111011 01101001000000000111101100000000. Levenshtein distance 15. min = max = 9.
11011110011010110101101011110100 00100010101010111010000000001110. min = 8. max = 12.
32123323033013011333111032331323 13100313103110123321321211233032. min = 6. max = 14.
17305657112546416613111655660524 23146332512152524313021536474017. min = 11. max = 21.

Task

For a given pair of strings of the same length, output the minimum and maximum number of substitutions in an optimal sequence of edit operations for those two strings.

You can assume the input is given in any convenient form you choose and may similarly provide the output in any way that is convenient for you.

JavaScript (ES10),  169 168  161 bytes

Saved 7 bytes thanks to @KevinCruijssen

Takes the strings as (s)(t). Returns [min, max].

s=>t=>[[...Array(d=(g=(k,m=s.length,n=m,c)=>m*n?1+Math.min(g(k,m,n-1),g(k,--m,n),g(k-=c=s[m]!=t[--n],m,n)-!c):k?1/0:m-~n)())].flatMap((_,i)=>g(i)-d?[]:j=i)[0],j]

Try it online! (fast test cases)

Try it online! (a longer test case which may time out if TIO is overloaded)

Commented

Helper function \$g\$

\$g\$ is a function that computes the standard Levenshtein distance when it's called with \$k\$ undefined, or the edit distance with exactly \$k\$ substitutions when it's called with \$k\ge0\$. An additional offset of \$+1\$ is added to the result in both cases.

NB: It is presented separately for readability but must be defined within the scope of the main function so that the source string \$s\$ and the target string \$t\$ are defined.

g = (                         // g is a recursive function taking:
  k,                          //   k = allowed number of substitutions, or undefined
  m = s.length,               //   m = 1st pointer, initialized to the length of s
  n = m,                      //   n = 2nd pointer, initialized to the length of s
  c                           //   c = substitution cost
) =>                          //       (needs to be defined in the local scope)
  m * n ?                     // if both m and n are greater than 0:
    1 +                       //   add 1 to the final result
    Math.min(                 //   add the minimum of:
      g(k, m, n - 1),         //     recursive call for insertion with (m, n - 1)
      g(k, --m, n),           //     recursive call for deletion with (m - 1, n)
      g(                      //     recursive call for substitution:
        k -=                  //       set c if s[m - 1] is not equal to t[n - 1]
          c = s[m] != t[--n], //       and decrement k if c is set
        m, n                  //       use (m - 1, n - 1)
      ) - !c                  //     subtract 1 from the result if c is not set
    )                         //   end of Math.min()
  :                           // else (leaf node):
    k ?                       //   if k is not equal to 0 or NaN:
      1 / 0                   //     return +Infinity
                              //     (to make sure that this branch is not chosen)
    :                         //   else:
      m - ~n                  //     return m + n + 1

Main function

s => t =>                     // s = source string, t = target string
  [                           // the final result is a pair:
    [                         //   build an array containing:
      ...Array(d = g()),      //     d entries, where d = Levenshtein distance (+1)
    ]                         //
    .flatMap((_, i) =>        //   for each entry at position i in there:
      g(i)                    //     if the edit distance (+1) with i substitutions
      - d ?                   //     is not equal to d:
        []                    //       reject this entry
      :                       //     else:
        j = i                 //       append it to the array and copy i to j
    )[0],                     //   end of flatMap(); return the 1st entry (minimum)
    j                         //   followed by the last entry (maximum)
  ]                           // end of result


What is this date format? For Gregorian calendars, the date format varies from a country to another. There are three main formats recognized:

YY-MM-DD (big-endian)
DD-MM-YY (little-endian)
MM-DD-YY (middle-endian)

Your task is to write a program which, given an input string representing a date, output all the possible date formats by which this string can be interpreted as a date.

Rules

The input date is in the format xx-xx-xx, where each field is two digits and zero-padded.
The date is always valid (so you cannot get things like 14-13-17)
The date is always at least one of the formats above (so you cannot get things like 17-14-11)
Because we are in fact in a parallel world, there are 31 days for every month of the year, and consequently no leap years
The date is between January 01, 2001 and December 31, 2099
If there is only one format for the date, the code must print only it (only trailing newlines are allowed)
If there are several formats for the date, they must be either separated by a comma, a space, a newline, or a combination of those
You must output the exact name(s) of the format(s). Using distinct arbitrary values is not allowed.
No leading or trailing characters others than a trailing space are allowed
The output must be lowercase
You are not allowed to use any built-in date or calendar functions
The output formats do not have to be sorted

Examples

Input      Output
30-05-17   big-endian, little-endian
05-15-11   middle-endian
99-01-02   big-endian
12-11-31   big-endian, little-endian, middle-endian
02-31-33   middle-endian

This is code-golf so the shortest code in bytes wins. Explanations are encouraged.

Python 2, 123 bytes

a,b,c=map(int,input().split('-'))
for a,b,c in[[b,c,'big'],[b,a,'little'],[a,b,'middle']]:print(c+'-endian')*(a<13)*(b<32),

Try it online!

Python 2, less input parsing, 123 bytes

d=input()
for a,b,c in[[3,6,'big'],[3,0,'little'],[0,3,'middle']]:print(c+'-endian')*(int(d[a:a+2])<13)*(int(d[b:b+2])<32),

Try it online!


Groups of repeating items Challenge description
Given a list / array of items, display all groups of consecutive repeating items.
Input / output description
Your input is a list / array of items (you can assume all of them are of the same type). You don't need to support every type your language has, but is has to support at least one (preferably int, but types like boolean, although not very interesting, are also fine). Sample outputs:
[4, 4, 2, 2, 9, 9] -> [[4, 4], [2, 2], [9, 9]]
[1, 1, 1, 2, 2, 3, 3, 3, 4, 4, 4, 4] -> [[1, 1, 1], [2, 2], [3, 3, 3], [4, 4, 4, 4]]
[1, 1, 1, 3, 3, 1, 1, 2, 2, 2, 1, 1, 3] -> [[1, 1, 1], [3, 3], [1, 1], [2, 2, 2], [1, 1], [3]]
[9, 7, 8, 6, 5] -> [[9], [7], [8], [6], [5]]
[5, 5, 5] -> [[5, 5, 5]]
['A', 'B', 'B', 'B', 'C', 'D', 'X', 'Y', 'Y', 'Z'] -> [['A'], ['B', 'B', 'B'], ['C'], ['D'], ['X'], ['Y', 'Y'], ['Z']]
[True, True, True, False, False, True, False, False, True, True, True] -> [[True, True, True], [False, False], [True], [False, False], [True, True, True]]
[0] -> [[0]]

As for empty lists, output is undefined - it can be nothing, an empty list, or an exception - whatever suits your golfing purposes the best. You don't have to create a separate list of lists either, so this is a perfectly valid output as well:
[1, 1, 1, 2, 2, 3, 3, 3, 4, 9] ->

1 1 1
2 2
3 3 3
4
9

The important thing is to keep the groups separated in some way. This is code-golf so the shortest code in bytes wins

Mathematica, 5 bytes

Split

... there's a built-in for that.


Build an exact change calculator When I'm at a store and I pay for something in cash, I always try to give as exact change as possible in order to minimize the number of coins I have left in my wallet afterwards.

Your task is to build a program that will automate this process for me.

Your program will accept as input:

a line containing a single decimal number representing the price of an item.
a line consisting of a list of pairs of numbers, each pair representing the value of a denomination of coin or bill, and then the current amount of that denomination that I have in my wallet.
a line consisting of a list of denominations that the cashier has (you may assume they have an unlimited amount of each).

For example, the following input:

21.36
0.01 6 0.05 2 0.10 3 0.25 4 1.00 1 2.00 2 5.00 1 20.00 5
0.01 0.05 0.10 0.25 1.00 2.00 5.00 10.00 20.00 50.00 100.00

represents that I'm buying an item costing $21.36, and I have six pennies, two nickels, three dimes, four quarters, one loonie, two toonies, one five-dollar bill, and five 20-dollar bills.

Your program will then output the following:

the change that I should give to the cashier.
the change that the cashier will give me in return. You must optimize this as well in order to have a good solution.
the list of coins and bills still left in my wallet.
the total number of coins and bills left in my wallet after the transaction.

In this case, the optimal output is:

0.01 6 0.05 2 0.10 2 0.25 4 20.00 1

0.10 1 1.00 1 2.00 2 5.00 1 20.00 4
12

because I have exact change and this configuration uses the most coins to give that change. The second line is blank because no change was given in return.

Note that your program must support unconventional denominations such as 0.04 or 15.32, if they are part of the input. You are not guaranteed that every denomination will be a multiple or factor of another, except that every denomination will be a multiple of the lowest one, so that there is always a valid solution. You may assume that I will always have enough money to pay for the item whose price is listed.

In a few days, I will be posting a suite of 1,000 test cases for this program. Your program will be scored by the sum of the total number of coins and bills left in my wallet for each test case, with shorter code being a tie-breaker.

I think I have a Python 3 solution that should work for any test case. It took me quite a few tries to get something that wouldn't explode for certain degenerate inputs. It's still pretty slow for some large inputs where you have thousands of coins in your wallet to start, but I don't think it's possible to do much better in those cases (you must search a very large set of possible combinations of payment and change).
I've made two version of my solution, one that minimizes the number of coins you end up with in your wallet at the end (as per the current scoring rule), and another that minimizes the number of coins you are given in change (which is equivalent to minimizing the number of coins in your wallet at the end plus the number of coins you paid with, which Joe Z. has been considering changing the scoring rule to). You can switch which version is run by moving the leading # for the comment in the if __name__ == "__main__" block to the previous line. Both versions are based on of the same recursive change making algorithm (in the make_change function), they just run it with slightly different inputs.
The code exploits the effect that Cruncher noted in the question's comments, that the best overall algorithm is to give all your money to the cashier and then get ideal change for your final balance back. What my code does is give all the money to the cashier, then charge a "cost" to the solution for each coin or bill returned to the customer. The best solution is the one with the combined cost for its bills and coins. Later I do some cleaning up, and eliminate any payments that get directly returned using the same bills or coins.
For the version optimized for the original scoring rule, the cost is 1 for every coin or bill. For the alternative scoring rule, the cost is 0 for bills and coins that were originally in the customer's wallet (and are being returned), and 1 for anything that needs to come from the cashier's drawer.
The core algorithm is a depth-first search for combinations of coins that yield exact change. Larger coins are tried first, and more of them before fewer. This means the first result we find will be the "greedy" one (though we keep searching and may find a better result later).
The interesting part of the algorithm is that it keeps track of the cost of the best result found so far, and stops searching for more results down any branch that costs more than that that result. This lets it avoid considering a lot of possible combinations that require too much from the cashier (like thousands of pennies).
I do get a different optimal result for the example case given in the question, but it is in fact better for the current scoring rule (I pay several extra small bills and get a single $50 in change). My output is:
0.01 6 0.05 2 0.10 2 0.25 4 1.00 1 2.00 2 5.00 1 20.00 3
50.00 1
0.10 1 20.00 2 50.00 1

For the alternate scoring rule I get the same result shown in the question.
I've not made much effort at minimizing the number of characters in this code, though some parts were written in terse, code-golf style before I got more distracted by performance issues and correctness. I think I've factored out the all the repeated code into separate functions, but let me know if you see any obvious improvements.
def make_change(value, coins, best_cost=float("inf")):
    if value == 0:
        return [], 0

    best_solution=None
    for i, (coin, count, cost) in enumerate(coins):
        max_num = min(count, value//coin, best_cost//cost if cost else float("inf"))
        for num in range(max_num, 0, -1):
            coin_value = num*coin
            coin_cost = num*cost
            if coin_cost < best_cost: # this is always true the first iteration, but may not be later
                solution, solution_cost = make_change(value-coin_value, coins[i+1:],
                                                      best_cost-coin_cost)
                if solution is not None:
                    best_solution = [(coin, num)] + solution
                    best_cost = coin_cost + solution_cost
    return best_solution, best_cost

def parse():
    value = int(input().replace(".",""))
    wallet = dict(zip(*[iter(map(int,input().replace(".","").split()))]*2))
    cashier = list(map(int,input().replace(".","").split()))
    return value,wallet,cashier

def print_output(pay, change, final_wallet):
    print(" ".join("{:.2f} {}".format(coin/100, count) for coin, count in pay if count != 0))
    print(" ".join("{:.2f} {}".format(coin/100, count) for coin, count in change if count != 0))
    print(" ".join("{:.2f} {}".format(coin/100, count) for coin, count in final_wallet if count != 0))

def solve(value, wallet, coins):
    result, cost = make_change(value, coins)
    pay=[]
    change=[]
    for coin, count in result:
        if coin in wallet:
            if wallet[coin] > count:
                pay.append((coin, wallet[coin] - count))
            elif wallet[coin] < count:
                change.append((coin, count - wallet[coin]))
            del wallet[coin]
        else:
            change.append((coin, count))
    pay.extend(wallet.items())
    pay.sort()
    change.sort()
    result.sort()
    return pay, change, result

def minimize_wallet(value, wallet, cashier):
    wallet_value = sum(coin*count for coin,count in wallet.items())
    coin_dict = wallet.copy()
    coin_dict.update((coin, wallet_value//coin) for coin in cashier)
    coin_list = [(coin, count, 1) for coin, count in sorted(coin_dict.items(), reverse=True)]
    return solve(wallet_value-value, wallet, coin_list)

def minimize_change(value, wallet, cashier):
    wallet_value = sum(coin*count for coin,count in wallet.items())
    coin_list = [(coin, count, 0) for coin, count in wallet.items()]
    coin_list.extend((coin, wallet_value//coin, 1) for coin in cashier)
    coin_list.sort(key=lambda x: (-x[0], x[2]))
    return solve(wallet_value-value, wallet, coin_list)

if __name__ == "__main__":
    print_output(*minimize_wallet(*parse()))
    #print_output(*minimize_change(*parse())) # use this if the scoring rules are changed

I'd also like to suggest a testcase that is likely to break many implementations:
1.00
100.00 10000
0.01 0.05 0.10 0.25 1.00 2.00 5.00 10.00 20.00 50.00 100.00 999999.00

This testcase comes with a story I like to call "The bank robber and the debt limit":

One day, Alice robbed a bank. She made a clean getaway with exactly one million dollars in $100 bills. On her way home from the bank, she stopped off at a convenience store to buy a candy bar, but realized that she had not brought her wallet with her, so the only money she had was her bag of stolen money (ten thousand $100 bills will fit snugly in a decent sized backpack if they're shrink wrapped). She hoped the clerk would be willing to break a $100 bill.
Unbeknownst to Alice, Bob the convenience store clerk had been recently laid off as a worker at the US Mint. He had worked for several months this past spring and summer preparing high-denomination platinum coins in case they would be the only way for the US Government to make its interest payments without Congress increasing the debt limit. It turned out the coins were not needed, so their existence was never acknowledged. When he was told his job was being cut, Bob decided he would keep on of the coins he had worked so hard on. He smuggled out a single $1,000,000-denominated coin in his box of personal effects.
Sadly for everyone involved, Bob was showing off his million dollar coin to a coworker when Alice came to his register to see if he'd give her $99 in change for her $1 candy bar. Alas, seeing the coin, Alice's compulsion to receive the smallest amount of change possible got the better of her. She misinterpreted the text on the coin saying it was "0.999999 pure Platinum" to mean it was worth that fraction of its face value. If that was the case, it would be exact change for her candy bar if she paid Bob with her backpack full of money. She'd go from having 10,000 bills to having just one coin!

Can your code satisfy Alice? Expected output:
100.00 10000
999999.00 1
999999.00 1


Validate a Wikipedia page name Wikipedia has several restrictions on an article's title. I summarize them here:

It may not be empty.
It may not begin with a lowercase letter. A character is considered lowercase if it has an Ll after its name in UnicodeData.txt.
It may not contain any of the characters: # < > [ ] | { } _
It may not be . or ..
It may not begin with ./ or ../.
It may not contain /./ or /../.
It may not end with /. or /...
It may not contain any space character (a character is considered a space if it has Zs after its name in UnicodeData.txt) except for U+0020 SPACE.
It may not contain more than one consecutive space.
It may not consist entirely of spaces.
It may not begin with a colon.
It may not begin with the language prefix of any of the 292 language editions of Wikipedia followed by a colon. This includes en: for English.
It may not begin with the prefix of another Wikimedia Foundation project or its shortcut followed by a colon.
It may not contain the character % followed by two hexadecimal digits.
It may not contain a named HTML character entity. Numbered entities are already forbidden through #.
It must contain no more than 256 bytes when encoded in UTF-8.

Write a function that takes in a string (or whatever data type your language normally uses to manipulate text) and outputs a boolean indicating whether the string is a valid Wikipedia article title. You are permitted to use networking libraries to download and read from any page that I linked in this question.


Implement the Max-Pooling operation from Convolutional Neural Networks In convolutional neural networks, one of the main types of layers usually implemented is called the Pooling Layer. Sometimes, the input image is big (and therefore time consuming especially if you have a big input set) or there is sparse data. In these cases, the objective of the Pooling Layers is to reduce the spatial dimension of the input matrix (even though you would be sacrificing some information that could be gathered from it).

A Max-Pooling Layer slides a window of a given size \$k\$ over the input matrix with a given stride \$s\$ and get the max value in the scanned submatrix. An example of a max-pooling operation is shown below:

In the example above, we have an input matrix of dimension 4 x 4, a window of size \$k=2\$ and a stride of \$s=2\$.

Task

Given the stride and the input matrix, output the resulting matrix.

Specs

Both the input matrix and the window will always be square.
The stride and the window size will always be equal, so \$s=k\$.
The stride is the same for the horizontal and the vertical direction
The stride \$s\$ will always be a nonzero natural number that divides the dimension of the input matrix. This guarantees that all values are scanned by the window exactly once.
Input is flexible, read it however you see fit for you.
Standard loopholes are not allowed.

Test Cases

Format:
s , input, output

2, [[2, 9, 3, 8], [0, 1, 5, 5], [5, 7, 2, 6], [8, 8, 3, 6]] --> [[9,8], [8,6]]
1, [[1, 2, 3], [4, 5, 6], [7, 8, 9]] --> [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
4, [[12, 20, 30, 0], [8, 12, 2, 0], [34, 70, 37, 4], [112, 100, 25, 12]] --> [[112]]
3, [[0, 1, 2, 3, 4, 5, 6, 7, 8], [9, 10, 11, 12, 13, 14, 15, 16, 17], [18, 19, 20, 21, 22, 23, 24, 25, 26], [27, 28, 29, 30, 31, 32, 33, 34, 35], [36, 37, 38, 39, 40, 41, 42, 43, 44], [45, 46, 47, 48, 49, 50, 51, 52, 53], [54, 55, 56, 57, 58, 59, 60, 61, 62], [63, 64, 65, 66, 67, 68, 69, 70, 71], [72, 73, 74, 75, 76, 77, 78, 79, 80]] --> [[20, 23, 26], [47, 50, 53], [74, 77, 80]]

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

Python 3, 101 108 bytes

def f(m,w):r=range(0,len(m),w);return[[max(sum([x[i:i+w]for x in m[j:j+w]],[]))for i in r]for j in r]

Thanks to Jo King and Jonathan Allan for some more bytes off!

Try it online!

Alternate (longer) version as a single Lambda expression:

Try it online!


Is this Sequence Graphic? A graphic sequence is a sequence of positive integers each denoting the number of edges for a node in a simple graph.  For example the sequence 2 1 1 denotes a graph with 3 nodes one with 2 edges and 2 with one connection.
Not all sequences are graphic sequences. For example 2 1 is not a graphic sequence because there is no way to connect two nodes so that one of them has two edges.

Task
You will take a sequence of integers by any reasonable method.  This includes, but is not limited to, an array of integers and its size, a linked list of unsigned integers, and a vector of doubles.  You may assume that there will be no zeros in the input.  You may also assume the input is sorted from least to greatest or greatest to least.
You must output whether or not the sequence is a graphic sequence.  A truthy value if it is a falsy value otherwise.

Goal
This is code-golf the goal is to minimize the number of bytes in your program
Testcases
Sorted greatest to least
                  -> True
3 3 3 2 2 2 1 1 1 -> True
3 3 2 2 1 1       -> True
3 3 2             -> False
8 1 1 1 1 1 1 1 1 -> True
1 1 1 1           -> True
1 1 1             -> False
9 5 4             -> False

Mathematica, 25 bytes

<<Combinatorica`
GraphicQ

Yeah, another builtin. (Takes the input as a list of positive integers.) Requires loading the Combinatorica package.


What base is this number in? Here's a nice easy challenge:

Given a string that represents a number in an unknown base, determine the lowest possible base that number might be in. The string will only contain 0-9, a-z. If you like, you may choose to take uppercase letters instead of lowercase, but please specify this. You must output this lowest possible base in decimal.

Here is a more concrete example. If the input string was "01234", it is impossible for this number to be in binary, since 2, 3, and 4 are all undefined in binary. Similarly, this number cannot be in base 3, or base 4. Therefore, this number must be in base-5, or a higher base, so you should output '5'.
Your code must work for any base between base 1 (unary, all '0's) and base 36 ('0-9' and 'a-z').
You may take input and provide output in any reasonable format. Base-conversion builtins are allowed. As usual, standard loopholes apply, and the shortest answer in bytes is the winner!
Test IO:
#Input          #Output
00000       --> 1
123456      --> 7
ff          --> 16
4815162342  --> 9
42          --> 5
codegolf    --> 25
0123456789abcdefghijklmnopqrstuvwxyz    --> 36

Python, 27 22 bytes

lambda s:(max(s)-8)%39

This requires the input to be a bytestring (Python 3) or a bytearray (Python 2 and 3).

Thanks to @AleksiTorhamo for golfing off 5 bytes!

Test it on Ideone.

How it works

We begin by taking the maximum of the string. This the code points of letters are higher than the code points of digits, this maximal character is also the maximal base 36 digit.

The code point of '0' – '9' are 48 – 57, so we must subtract 48 from their code points to compute the corresponding digits, or 47 to compute the lowest possible base. Similarly, the code points of the letters 'a' – 'z' are 97 – 122. Since 'a' represents the digit with value 10, we must subtract 87 from their code points to compute the corresponding digits, or 86 to compute the lowest possible base. One way to achieve this is as follows.

The difference between 97 and 58 (':', the character after '9') is 39, so taking the code points modulo 39 can achieve the subtraction. Since 48 % 39 = 9, and the desired result for the character '0' is 1, we first subtract 8 before taking the result modulo 39. Subtracting first is necessary since otherwise 'u' % 39 = 117 % 39 = 0.

c    n    n-8    (n-8)%39
0    48    40     1
1    49    41     2
2    50    42     3
3    51    43     4
4    52    44     5
5    53    45     6
6    54    46     7
7    55    47     8
8    56    48     9
9    57    49    10
a    97    89    11
b    98    90    12
c    99    91    13
d   100    92    14
e   101    93    15
f   102    94    16
g   103    95    17
h   104    96    18
i   105    97    19
j   106    98    20
k   107    99    21
l   108   100    22
m   109   101    23
n   110   102    24
o   111   103    25
p   112   104    26
q   113   105    27
r   114   106    28
s   115   107    29
t   116   108    30
u   117   109    31
v   118   110    32
w   119   111    33
x   120   112    34
y   121   113    35
z   122   114    36


Converting integers to English words The goal of this code golf is to convert integers to English words.

The program prompts for input. If this input isn't an integer, print NaN. If it is an integer, convert it to English words and print these words. Minimum input: 0 (zero). Maximum input: 9000 (nine thousand).
So, 5 returns five (case doesn't matter), and 500 returns five hundred or five-hundred (dashes don't matter).

Some other rules:

A one before hundred or thousand is optional: one hundred is correct, but hundred too (if the input is 100 of course).

The word and in for example one hundred and forty five is optional too.

Whitespace matters. So, for 500, five-hundred or five hundred is correct, but fivehundred is not.

Good luck!

JavaScript (375)

Probably a terrible attempt, but anyway, here goes...

alert(function N(s,z){return O="zero,one,two,three,four,five,six,seven,eight,nine,ten,eleven,twelve,thir,,fif,,,eigh,,,,twen,,for".split(","),(z?O[s]||O[s-10]||O[s-20]:s<13?N(s,1):s<20?N(s,1)+"teen":s<100?N(a=20+(s/10|0),1)+"ty"+(s%10?" "+N(s%10):""):s<1e3?N(s/100|0)+" hundred"+(s%100?" "+N(s%100):""):s<1e5?N(s/1e3|0)+" thousand"+(s%1e3?" "+N(s%1e3):""):0)||NaN}(prompt()))

Pretty-printed (as a function):

function N(s,z) {
  return O = "zero,one,two,three,four,five,six,seven,eight,nine,ten,eleven,twelve,thir,,fif,,,eigh,,,,twen,,for".split(","),
      (z? O[s] || O[s-10] || O[s-20]
       : s < 13?  N(s,1)
       : s < 20?  N(s,1) + "teen"
       : s < 100? N(a=20+(s/10|0),1) + "ty" + (s%10?" "+N(s%10):"")
       : s < 1e3?  N(s/100|0) +  " hundred" + (s%100?" "+N(s%100):"")
       : s < 1e5?  N(s/1e3|0) + " thousand" + (s%1e3?" "+N(s%1e3):"") : 0) || NaN
}

Sample conversion (note that it even outputs NaN when out of bounds, i.e. invalid input):

540: five hundred forty
4711: four thousand seven hundred eleven
7382: seven thousand three hundred eighty two
1992: one thousand nine hundred ninety two
hutenosa: NaN
1000000000: NaN
-3: NaN


The lost pawn problem The lost pawn problem
After the chess game ended, a surviving pawn was left behind enemy lines. let's help him find the shortest way back home.
The original problem describes a nXn "chess" board, and a function f: {1,..,n-1}X{1,..,n}X{-1,0,1} => R+ of weights. the goal is to find the best path from some square in the buttom line, to some other square in the top line, where the possible moves are: left-up,up,right-up, and you may not exit the board.
The problem is relatively easy to solve in O(n^2) using dynamic programming, but this is codegolf, and we don't care about useless stuff like running time complexity...
The Problem
input: a 3-dimentional array (or some other collection of your choice, received through stdin, or as a function argument), corresponding to a regular chess board, exactly in size: 7X8X3 (#linePasses X #rowSize X #movesPerPass) containing non-negative integers.
the moves cost from some position (i,j) where i is the row index, and j is the column index, are:

a[i][j][0] for the cost to travel up-left to square (i+1,j-1), or graphically: \.
a[i][j][1] for the cost to travel up to square (i+1,j), or graphically: |.
a[i][j][2] for the cost to travel up-right to square (i+1,j+1), or graphically: /.

you may assume it will not contain a path that sums greater than MAX_INT.
output: an 8X8 ascii output showing the best (shortest, i.e. minimum sum of weights) path (if there is more than 1 optimal result, you may show an arbitrary path of your choice). the path is drawn bottom to top, where in each line, the character corresponding to the pawn's position in the path, is the one it about to make. e.g. if the pawn is about to move up-left from column 3 (to column 2), the you should draw:
#?######
##\#####

where ? should be replaced with the next move. final position needs to be drawn as X.
Examples
input:
[
  [[1,1,1],[1,1,1],[0,1,1],[1,1,1],[1,1,1],[1,1,1],[1,1,1],[1,1,1]],
  [[1,1,1],[1,0,1],[1,1,1],[1,1,1],[1,1,1],[1,1,1],[1,1,1],[1,1,1]],
  [[1,1,1],[1,1,0],[1,1,1],[1,1,1],[1,1,1],[1,1,1],[1,1,1],[1,1,1]],
  [[1,1,1],[1,1,1],[1,1,0],[1,1,1],[1,1,1],[1,1,1],[1,1,1],[1,1,1]],
  [[1,1,1],[1,1,1],[1,1,1],[1,0,1],[1,1,1],[1,1,1],[1,1,1],[1,1,1]],
  [[1,1,1],[1,1,1],[1,1,1],[1,0,1],[1,1,1],[1,1,1],[1,1,1],[1,1,1]],
  [[1,1,1],[1,1,1],[1,1,1],[0,1,1],[1,1,1],[1,1,1],[1,1,1],[1,1,1]]
]

output:
##X#####
###\####
###|####
###|####
##/#####
#/######
#|######
##\#####

input:
[
  [[41,27,38],[12,83,32],[50,53,35],[46,32,26],[55,89,82],[75,30,87],[2,11,64],[8,55,22]],
  [[56,21,0],[83,25,38],[43,75,63],[56,60,77],[68,55,89],[99,48,67],[94,30,9],[62,62,58]],
  [[23,18,40],[24,47,61],[96,45,72],[71,6,48],[75,63,98],[93,56,51],[23,31,30],[49,34,99]],
  [[20,47,42],[62,79,72],[32,28,44],[68,61,55],[62,39,57],[4,17,49],[97,85,6],[91,18,12]],
  [[51,50,11],[32,39,56],[12,82,23],[33,88,87],[60,55,22],[29,78,14],[70,11,42],[63,94,67]],
  [[75,64,60],[27,79,86],[70,72,56],[55,45,32],[95,67,12],[87,93,98],[81,36,53],[38,22,93]],
  [[31,80,50],[77,71,22],[59,46,86],[64,71,53],[41,19,95],[62,71,22],[92,80,41],[26,74,29]]
]

output:
######X#
#####/##
####/###
#####\##
#####|##
######\#
######|#
#######\

this is code-golf, so shortest code wins.
play fair. no loopholes...
EDIT:
Iv'e written an un-golfed straight forward solution in scala you can look at. There's also a site you can play with scala code on-line: scalafiddle (just copy&paste the gist to scalafiddle, and hit the play button)


Replace letters by their rank, keeping punctuation intact The problem is simple. Given a string such as Hello World! the program would output 8-5-12-12-15 23-15-18-12-4-!. Any delimiters will do, (please specify what they are though) I just chose to use space between words and dashes between characters.
The conversion is that all alphabetical characters will be converted to their numeric equivalent. i.e. A=1,B=2,...,Z=26. All other characters must be kept intact. Case insensitive.
Another example
Here's another example, I hope that this will illustrate my point! If it's unable, more specs will be given.
8-5-18-5-'-19 1-14-15-20-8-5-18 5-24-1-13-16-12-5-, 9 8-15-16-5 20-8-1-20 20-8-9-19 23-9-12-12 9-12-12-21-19-20-18-1-20-5 13-25 16-15-9-14-20-! 9-6 9-20-'-19 21-14-1-2-12-5-, 13-15-18-5 19-16-5-3-19 23-9-12-12 2-5 7-9-22-5-14-.

Note that there are no trailing or starting delimiters between characters.
Scoring will be based on the shortest amount of code. Any language is welcome.
As long as more answers are provided I will change the winner.
GLHF!

Ruby 2.0, 41+1 characters

There, now it complies with the updated rules and makes prettier output.

gsub(/\w+/){$&.chars.map{|c|c.ord&31}*?-}

Run with -p switch:

ruby -p ord.rb <<< "ABC! Defghi, jklmnopqr stuvwxyz"
1-2-3! 4-5-6-7-8-9, 10-11-12-13-14-15-16-17-18 19-20-21-22-23-24-25-26


Tips for Creating/Maintaining a Golfing Language Creating a golfing language can be hard. Let's help budding golfing language creators out and provide some helpful tips on how to create one.

I'm looking for tips on:

The design process
Implementation
Community engagement

One tip per answer would be appreciated, and tips like "don't create a new language, use an existing one" probably aren't very helpful.

You don't need to have created a golfing language to answer this question. Feel free to answer from personal experiences or from general observations.

Here are some suggestions. Sorry that this partially overlaps with other answers, which have been posted as I was writing this.
Design process

One possibility (by all means not the only one) to decide which features (functions, data types, etc.) your language L should have is to base it on another language B that you have been using for long. That way you already have a good idea which functions of B are used most often, and therefore should be included in your language L, and you can assign shorter names in L to functions that are commonly used in B.

Examples:

L = MATL: B = MATLAB/Octave.
L = Pyth: B = Python.
L = Japt: B = JavaScript.
L = Brachylog: B = Prolog.
L = Husk: B = Haskell.
L = ShortC: B = C.
L = V: B = Vim.

Decide which "paradigm" your language will use. Some examples are

Stack-based (Cjam, MATL, 05AB1E);
Tacit (Jelly);
Prefix notation (Pyth);
Infix notation (Pip, Japt);
Fixed arity (Pyth);
Variable arity (CJam, MATL, Japt).

These decisions are quite independent from item 1. For example, MATL's function f has the same functionality as MATLAB's find, but is used differently in that it pops its inputs from the stack and pushes its outputs onto it, whereas MATLAB uses normal function arguments which can be stored in variables.

Incorporate functions from other golfing languages that you find useful. Don't let item 1 (if applicable) limit language L's definition.

Be prepared to add functions in the future. As you (or others) use the language, you will find things it would be nice to add. So reserve some of the "namespace" for future expansion. For example, don't use up all your single-character names at once.

Implementation

Write the compiler (or interpreter) for your language L in a language C that you know well (often C = B).
The compiler is most often actually a transpiler into another language T (which can be the same as B or C). Language T should have a free implementation. That way it is viable to have an online compiler for your language. The compiler will be a program in C that takes source code in L to produce transpiled code in T, and then calls T's compiler/interpreter to run the transpiled code.

A natural choice is C = T. Examples:

L = Japt: B = C = T = JavaScript.
L = Jelly: C = T = Python (and Jelly is inspired by J; but perhaps not so much as to claim that B = J).
L = MATL: B = C = T = MATLAB/Octave.

Community engagement

Host your compiler/interpreter in a public repository such as GitHub, so people can easily download it, create bug reports, suggest new features or even contribute with code.
Write good documentation. That helps users understand your language better. Besides, I found that task more rewarding than I expected. I recommend writing the specification while you are designing the language, not at the end. That way consistency between language behaviour and its specification is ensured.
Ideally the documentation should include some quick reference (table or summary), so experienced users don't have to go to the full documentation simply because they have forgotten the name or the syntax of a function they know.
Create an esolangs page with basic information about your language.
Create a chat room where people can ask and discuss about the language. Visit it often.
Answer questions in your language, with explanations about how the code works. You'll want to do that anyway (it's your language, you will find it fun to use), but this also helps get people curious about your language, and shows some of the language's properties, which might get people interested.
If you chose to base your language L on a language B (see item 1) that is general-purpose and well known, users of B will find it easy to switch to L, which will allow them to provide short answers (in L) with minimal effort (coming from B).


A Slashy Dashy Spiral Given a positive integer N, output the innermost N×N square of an ASCII art spiral made of -|/\ that spirals clockwise inward.

The - is used for horizontal portions, | for vertical portions, and / and \ for corners. The first character is - and the spiral proceeds left and down.

Specifically, when N is 1 the output is:

-

When N is 2 the output is:

/-
\-

When N is 3 the output is:

--\
/-|
\-/

When N is 4 the output is:

 /--\
 |/-|
 |\-/
 \---

Note how every output is a square of N by N characters.

The pattern continues in the same way:

N=1
-

N=2
/-
\-

N=3
--\
/-|
\-/

N=4
/--\
|/-|
|\-/
\---

N=5
----\
/--\|
|/-||
|\-/|
\---/

N=6
/----\
|/--\|
||/-||
||\-/|
|\---/
\-----

N=7
------\
/----\|
|/--\||
||/-|||
||\-/||
|\---/|
\-----/

N=8
/------\
|/----\|
||/--\||
|||/-|||
|||\-/||
||\---/|
|\-----/
\-------

etc.

The shortest code in bytes wins.

Charcoal, 17 16 bytes:

↶⁴-Ｆ⊖Ｎ«↶²/ι↶²\-ι

Try it online! Link is to verbose version of code.

↷²-¶Ｆ⊖Ｎ«/ι↶²\-ι↶

Try it online! Link is to verbose version of code.

Edit: Saved 1 byte thanks to @icrieverytim.


Create a T9 keyboard This question asks for a T9 dictionary matching functionality which is a very interesting problem. But T9 has another way of typing and that is typing character-by-character. You would NOT need a dictionary to implement this keyboard.

Here is key-map of a T9 keyboard if you forgot:

+-------+-------+-------+
|   1   |   2   |   3   |
|  .?!  |  ABC  |  DEF  |
+-------+-------+-------+
|   4   |   5   |   6   |
|  GHI  |  JKL  |  MNO  |
+-------+-------+-------+
|   7   |   8   |   9   |
| PQRS  |  TUV  |  WXYZ |
+-------+-------+-------+
|   *   |   0   |   #   |
|   ←   | SPACE |   →   |
+-------+-------+-------+

How T9 works

To type a character with T9, you need to press number key representing that character n times. n is order of that character written on that key. Numbers are the last character you can type for each key. For example, to type B I press 2 two times, or to type 5 I press 5 four times. To finish typing this character I press #. * is simply backspace. In our version of keyboard there is no capitalization.

Input and output examples:

8#99999#055#33#999#22#666#2#777#3# → T9 KEYBOARD

Explanation:

8 selects T and # moves to next character
99999 select last character of 9 key which is 9 and # moves to next charachter
0 inserts a space
33 selects second character of  3 key which is K and # moves to next character
And so on...

Rules

Your function or program should accept a string representing T9 keypresses. Output is the resulting text from those keypresses, as outlined above.

This is basic code golf, so the winner is shortest in bytes, and standard rules/loopholes apply.

CJam, 109 94 bytes (2nd bonus)
A very naive and long solution
q'#/);{__'*-:A-,_g{){;}*A_}*;'0/{_,g{)~".?~1"a'[,65>292994 5b{/(X):X+\s}%+1:Xm>=\,=}*}%S*1/~}%

This is a full program, although a function will be of the same length.
The input goes into STDIN
Example:
8#99999#055#33#999#***22#666#2#777#3#

Output:
T9 BOARD

Try it online here


Running gene crossover algorithm Your task is to accept as input two gene sequences, and a sequence of "cross over points", and return the gene sequence that results from the indicated cross overs.
What I mean by this is, say you have the sequences [A, A, A, A, A, A, A] and [Z, Z, Z, Z, Z, Z, Z], and cross over points of 2 and 5. The resulting sequence would be [A, A, Z, Z, Z, A, A], because:

Cross Here:   V     V
Indices:  0 1 2 3 4 5 6

Genes 1:  A A A A A A A
Genes 2:  Z Z Z Z Z Z Z

Result:   A A Z Z Z A A
              ^     ^

Note that while I'm using letters here for clarity, the actual challenge uses numbers for genes.
The result is the first sequence until a cross over point is encountered, then the result takes from the second sequence until another cross over point is encountered, then the result takes from the first sequence until a cross over point is encountered...
Input:

Input can be any reasonable form. The two sequences can be a pair, with the points as the second argument, all three can be separate arguments, a single triplet of (genes 1, genes 2, cross-points), a map with named keys...

The cross points will always be in order, and will always be inbounds. There won't be duplicate points, but the list of cross over points may be empty.

Gene sequences will always be the same length, and will be non-empty.

Indices can be 0 or 1 based.

Genes will always be numbers in the range 0-255.

It doesn't matter which argument is "genes 1" or "genes 2". In the case of no cross over points, the result can either be either entirely "genes 1" or "genes 2".

Output

Output can be any reasonable form that isn't ambiguous. It can be a array/list of numbers, an array of string numbers, a delimited string of numbers (some non-numeric character must separate the numbers)...

It can be returned or printed to the std-out.

Entries can by full programs or functions.

Test Cases (genes 1, genes 2, cross points) => result:
[0], [1], [0] => [1]
[0, 1], [9, 8], [1] => [0, 8]
[0, 2, 4, 6, 8, 0], [1, 3, 5, 7, 9, 1], [1, 3, 5] => [0, 3, 5, 6, 8, 1]
[1, 2, 3, 4], [5, 6, 7, 8], [] => [1, 2, 3, 4]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [0, 2, 3, 6, 8] => [1, 1, 0, 1, 1, 1, 0, 0, 1, 1]

This is Code Golf.

JavaScript (ES6), 47 45 bytes
Saved 2 bytes thanks to @ETHproductions
Takes input as a triplet [a, b, c] where a and b are the gene sequences and c is the list of 0-indexed cross-points.

x=>x[i=j=0].map(_=>x[(j+=x[2][j]==i)&1][i++])

Try it online!
Commented
x =>                    // given x = [ geneSeqA, geneSeqB, crossPoints ]
  x[i = j = 0]          // initialize i = gene sequence pointer and j = cross point pointer
  .map(_ =>             // for each value in the first gene sequence:
    x[(                 //   access x[]
      j += x[2][j] == i //     increment j if i is equal to the next cross point
    ) & 1]              //   access either x[0] or x[1] according to the parity of j
    [i++]               //   read gene at x[0][i] or x[1][i]; increment i
  )                     // end of map()


Optimize paper folding to mitigate inkblots Dark black ink has splattered all over your white sheet of printer paper! The obvious solution is to fold the paper so black and white parts meet and both become grey as the ink diffuses. Then unfold and refold until your paper is all equally grey.

Finding the best way to make these folds is your task in this coding challenge. This Pastebin contains four different sized grids of ones and zeros. Each grid represents a piece of ink splattered paper that you must turn grey. Zeros are paper and ones are ink.

In these grids, only horizontal and vertical folds along the spaces between lines and columns are valid. When a fold is made the pairs of overlapping values are averaged. Folds are done one at a time and always unfolded. Folds only change the ink distribution, not the size of the paper.

Rn denotes folding the left edge of the grid to the right, starting after the nth column. Dn denotes folding the top edge of the grid downward fold, starting after the nth row. (n is 1-indexed)

Example

Given this grid

0 1 1 1
0 0 0 0
0 0 0 0

a D1 fold means "fold the entire top row down then unfold".

0 0.5 0.5 0.5
0 0.5 0.5 0.5
0   0   0   0

Then an R2 will produce

0.25 0.5 0.5 0.25
0.25 0.5 0.5 0.25
   0   0   0    0

and another R2 will not change anything.

Goal

Your goal is to write an algorithm that finds the best ink-spreading folding sequence for each of the four grids using exactly 8 folds each time. The folds may be any combination of Rs or Ds.

Scoring

The score of your submission is the sum of your scores for each grid. A grid's score is the sum of the absolute differences between each of its values and its average (its sum divided by its area). Lower scores are better. A score of 0 is perfect, but is probably impossible in only 8 folds.

You must report your four 8-step folding sequences with your code in your answer. This is so we can verify your algorithm really works.

Please put them in this form:

20*20R1D2R3D4R5D6R7D8
40*20R1D2R3D4R5D6R7D8
40*40R1D2R3D4R5D6R7D8
20*80R1D2R3D4R5D6R7D8

Here is a Python script that will calculate your scores given your folding sequences.

Naturally you should not copy someone else's sequence submission. Sequences for each grid only belong to the person who first created them.

Clarifications

Ideally your algorithm will work well on any grid, though you can tailor it to these specific ones.
You must submit your code with your sequence. To win you need the smallest-scoring set of 8-step folding sequences that has not already been posted, and also an algorithm that stands up to public scrutiny. Explain your code, don't obfuscate it.
The grid should never contain negative numbers.
Standard loopholes apply.

Python

Exhaustively tries different combinations of folds for the first few folds, then does the rest of the folds using a greedy approach.

The exhaustive approach is bounded within a reasonable range of folds in the center, such that it won't take forever, while not ignoring too many possible folds to yield a good minimum.

Ran using pypy on my macbook air.

Answers:

20*20D9R15R6D11R10R9D10R11
40*20D6D13D9R19R21R20D11D10
40*40D21R21R11D19R23R20D23D15
20*80D33D47D40R10D39D41R9R11

Outputs:

Exhaustive folds levels: 3
Percentage pruned from sides from exhaustive folds: 0.2
Time taken: 4.016076s
Score: 7.91125
20*20D9R15R6D11R10R9D10R11

Exhaustive folds levels: 3
Percentage pruned from sides from exhaustive folds: 0.2
Time taken: 28.529278s
Score: 16.34375
40*20D6D13D9R19R21R20D11D10

Exhaustive folds levels: 3
Percentage pruned from sides from exhaustive folds: 0.25
Time taken: 98.430465s
Score: 42.13
40*40D21R21R11D19R23R20D23D15

Exhaustive folds levels: 3
Percentage pruned from sides from exhaustive folds: 0.25
Time taken: 234.873787s
Score: 32.30875
20*80D33D47D40R10D39D41R9R11

Total Score: 7.91125 + 16.34375 + 42.13 + 32.30875 = 98.69375

Code:

import time, math
from collections import deque

numberOfFolds = 8 # Total number of folds

startTime = time.clock()

exec "grid = ("+"""
1 1 1 0 1 1 0 0 1 0 0 1 0 1 1 0 1 0 1 1
1 1 0 0 0 1 0 1 1 0 0 0 1 0 1 1 1 0 1 1
0 1 0 0 0 1 0 1 0 1 1 1 1 0 1 0 1 0 1 0
0 0 0 1 0 1 0 0 0 0 1 1 1 0 1 1 0 0 0 1
0 1 0 1 1 0 0 0 0 0 1 0 1 1 1 0 1 0 1 0
1 0 1 1 0 1 1 1 1 1 1 0 0 1 0 1 0 1 0 1
0 1 1 1 0 0 0 1 1 0 1 0 1 1 0 0 0 0 0 0
0 0 0 0 0 0 1 1 1 1 1 0 0 0 1 1 0 0 0 0
1 1 1 0 1 0 0 1 0 1 1 1 1 1 1 0 0 0 0 1
1 1 0 0 0 1 1 1 0 1 0 1 0 0 1 1 0 0 1 0
0 1 1 0 0 0 1 1 0 1 1 1 0 1 1 1 0 1 0 1
0 1 1 1 1 0 0 1 1 0 1 0 1 1 1 1 0 1 1 0
0 0 0 1 0 0 0 1 0 1 0 0 1 0 0 0 1 0 0 1
0 0 1 1 1 1 1 1 0 0 1 1 0 0 1 1 0 0 1 1
1 1 1 1 0 1 1 0 0 0 0 1 1 1 0 0 0 0 0 1
1 0 0 1 0 0 0 0 1 0 0 1 1 0 0 0 0 0 0 0
0 1 1 1 0 0 1 1 0 0 1 1 1 1 0 1 1 0 0 1
0 0 1 0 1 1 1 1 0 1 1 0 1 0 1 0 0 1 1 0
0 1 1 0 1 0 0 1 0 0 1 1 1 1 1 0 1 1 0 0
0 0 1 0 1 1 1 0 0 1 0 0 0 1 0 1 1 1 1 1
""".replace(" ",",").replace("\n","],[")[2:-2]+")"

def getAverage(grid):
    count = total = 0
    for j in grid:
        for i in j:
            count += 1
            total += i
    return total/float(count)

def getScore(grid, average):
    score = 0
    for j in grid:
        for i in j:
            score += abs(average-i)
    return score

def downFoldedGrid(grid, row, width, height, copy=True):
    if copy: grid = [r[:] for r in grid]
    foldRange = min(row, height-row)
    for j in xrange(foldRange):
        rowRef1 = grid[row+j]
        rowRef2 = grid[row-1-j]
        for i in xrange(width):
            rowRef1[i] = rowRef2[i] = (rowRef1[i] + rowRef2[i]) * .5
    return grid

def downFoldedScore(grid, score, average, row, width, height):
    foldRange = min(row, height-row)
    average2  = 2*average
    for j in xrange(foldRange):
        rowRef1 = grid[row+j]
        rowRef2 = grid[row-1-j]
        a = b = c = 0
        for i in xrange(width):
            a = rowRef1[i]
            b = rowRef2[i]
            c = a+b
            score += abs(average2-c) - abs(average-a) - abs(average-b)
    return score

def rightFoldedGrid(grid, column, width, height, copy=True):
    if copy: grid = [r[:] for r in grid]
    foldRange = min(column, width-column)
    for j in xrange(height):
        rowRef = grid[j]
        for i in xrange(foldRange):
            a = column+i
            b = column-1-i
            rowRef[a] = rowRef[b] = (rowRef[a] + rowRef[b]) * .5
    return grid

def rightFoldedScore(grid, score, average, column, width, height):
    foldRange = min(column, width-column)
    average2 = 2*average
    for j in xrange(height):
        rowRef = grid[j]
        a = b = c = 0
        for i in xrange(foldRange):
            a = rowRef[column+i]
            b = rowRef[column-1-i]
            c = a+b
            score += abs(average2-c) - abs(average-a) - abs(average-b)
    return score

def bestFoldsGreedy(grid, average, maxFolds, width, height):
    score  = getScore(grid, average)
    folds  = []
    append = folds.append
    for z in xrange(maxFolds):
        bestFold      = 0
        bestFoldScore = score
        bestFoldGrid  = grid
        for i in xrange(1, width): #Try all right folds
            foldScore = rightFoldedScore(grid, score, average, i, width, height)
            if foldScore < bestFoldScore:
                bestFold      = i
                bestFoldScore = foldScore
        for i in xrange(1, height): #Try all down folds
            foldScore = downFoldedScore(grid, score, average, i, width, height)
            if foldScore < bestFoldScore:
                bestFold      = -i
                bestFoldScore = foldScore
        if bestFold:
            append(bestFold)
            score = bestFoldScore
            if bestFold > 0: rightFoldedGrid(grid, bestFold, width, height, False)
            else:            downFoldedGrid(grid, -bestFold, width, height, False)
    return score, folds

# Get the height and width
height  = len(grid)
width   = len(grid[0])

# Transpose the grid if height > width for better locality of reference
transposed = False
if height > width:
    grid = [[grid[i][j] for i in range(height)] for j in range(width)]
    transposed = True
    height, width = width, height

# The exhaustive grids and folds attempted
exhaustiveGridsAndFolds = deque([(grid,[])])
popleft = exhaustiveGridsAndFolds.popleft
append  = exhaustiveGridsAndFolds.append

# Set the bounds to exhaustively test for
exhaustiveLevels   = 3
prunePadding       = [0.2, 0.25][width*height > 1000]
leftBound          = int(max(width*prunePadding, 1))
rightBound         = int(width*(1.0-prunePadding))
topBound           = int(max(height*prunePadding, 1))
bottomBound        = int(height*(1.0-prunePadding))

# Populate the exhaustive grids and folds
while 1:
    grid, folds = popleft()
    if len(folds) == exhaustiveLevels:
        append((grid, folds))
        break
    for i in xrange(leftBound, rightBound):
        if i not in folds:
            append((rightFoldedGrid(grid, i, width, height), folds+[i]))
    for i in xrange(topBound, bottomBound):
        if -i not in folds:
            append((downFoldedGrid(grid, i, width, height), folds+[-i]))

# Test all the exhaustive grids and folds greedily
average             = getAverage(grid)
bestFinalScore      = getScore(grid, average)
bestFinalFolds      = []
numberOfGreedyFolds = numberOfFolds-exhaustiveLevels
while exhaustiveGridsAndFolds:
    grid, exhaustiveFolds = popleft()
    finalScore, greedyFolds = bestFoldsGreedy(grid, average, numberOfGreedyFolds, width, height)
    if finalScore <= bestFinalScore:
        bestFinalScore = finalScore
        bestFinalFolds = exhaustiveFolds + greedyFolds

# Repeat the last fold till the total number of folds if needed
if len(bestFinalFolds) < numberOfFolds:
    bestFinalFolds += [bestFinalFolds[-1]]*(numberOfFolds-len(bestFinalFolds))

# Print the best result
foldsString = ""
down  = "D"
right = "R"
if transposed:
    down,  right  = right,  down
    width, height = height, width
for fold in bestFinalFolds:
    if   fold > 0: foldsString += right+str(fold)
    elif fold < 0: foldsString += down+str(-fold)
print "Exhaustive folds levels: " + str(exhaustiveLevels)
print "Percentage pruned from sides from exhaustive folds: " + str(prunePadding)
print "Time taken: " + str(time.clock()-startTime) + "s"
print "Score: " + str(bestFinalScore)
print str(width) + "*" + str(height) + foldsString


Letters between two letters Write a program that accepts a single lowercase word as input and outputs the number of pairs of letters that have the same number of letters between them in the word as in the alphabet.

For example, in the word 'nature', we have 4 pairs:

nr: since there are three letters between them inside the word (a, t, u) and three letters between them in the alphabet (o, p, q)
ae: since there are three letters between them inside the word (t, u, r) and three letters between them in the alphabet (b, c, d)
tu:  since there are no letters between them inside the word and no letters between them in the alphabet
tr:  since there is one letter between them inside the word (u) and one letter between them in the alphabet (s)

Since there are four pairs, the output in this case should be 4.

Pyth, 19 bytes

lfqF-MSMCT.cCUBCMz2

Try it online: Demonstration

Explanation:

lfqF-MSMCT.cCUBCMz2
                 z   read a string from input
               CM    convert into list of ascii-values
            CUB      create a list of pairs (ascii-value, index in string)
          .c      2  all combinations of length 2
 f                   filter for combinations T, which satisfy:
        CT              transpose T ((ascii1, ascii2), (index1, index2)
      SM                sort each list
    -M                  create the the difference for each
  qF                    check if they are equal
l                    print the number of remaining combinations


Return closest to zero Description :

You are given a string of numbers (positive and negative but not decimals) along with the number of entries like so.

Like so

8
'1 2 5 0 7 -9 12 -8'

Task :

Your job is to return the number closest to zero be it +ve or -ve. Your input will be separated by spaces only. You are free to return the answer in any way you like namely :

     A string
     A float (Why would you though)
     An array (One digit array I guess)
     A number (preferred)

Since this is code golf the answer with the shortest will be the winner. I guess?

Have fun.

code snippets :

console.log(`6
'1 -2 -8 4 3 5'`) // should return 1
console.log(`3
'-12 -5 -137'`) // should return -3
console.log(`8
'1 2 5 0 7 -9 12 -8'`) // should return 0

Note :

This is my first attempt at this. Apologies in advance for any mistakes, do tell so I can correct them. Thanks

Python 2, 41 bytes

lambda n:min(map(abs,map(int,n.split())))

Try it online!


Remove the Salutations Challenge

Hi, given a string as input, remove any salutations found at the start of the string.

The program which performs the most correct substitutions in under 50 bytes wins.

Salutations

Hey, a salutation is defined as one of the following words:

hi
hey
hello
dear
greetings
hai
guys
hii
howdy
hiya
hay
heya
hola
hihi
salutations

The first letter may be capitalised.

There will always be a comma and/or a single space following the salutation which must also be removed. The comma and the space may be in any order (,<space> or <space>,) and both should be removed.

The greeting and the following word will only ever be separated by a comma and/or single space.

You must then capitalise the first letter of the word which would have followed the salutation. Even if no replacement has taken place, you should still capitalise the first word of the output.

Capitalisation only applies to lowercase alphabetical characters (abcdefghijklmnopqrstuvwxyz). You should leave any other character as it was.

The salutation will always be at the start of the string. You should not replace a salutation which is not at the start.

There may not always be a salutation.

Your code must be under 50 bytes.

Examples

Input > Output

Salutations, what's going on? > What's going on?
hello i have quetions how does juice an avocado > I have quetions how does juice an avocado
How d'you do > How d'you do
Hey,You! > You!
hola cows eat hay > Cows eat hay
hey Hi there! > Hi there!
hihi ,guys > Guys

Test battery

Hola, there are 1000 different inputs in total:

The test battery can be found here where each input is separated by a newline: https://github.com/beta-decay/Remove-Substitutions-Battery/blob/master/inputs.txt
The corresponding correct outputs are here: https://github.com/beta-decay/Remove-Substitutions-Battery/blob/master/replaced.txt

A Bash command to retrieve both the above is

wget https://raw.githubusercontent.com/beta-decay/Remove-Substitutions-Battery/master/{inputs,replaced}.txt

Winning

Howdy, the program with the most correct substitutions from the 1000 inputs above wins.

You must put the percentage of the inputs your program handles correctly in your header like so:

# Language Name, percentage%

I'm not completely sure why Jeff made this a thing, but it makes a nice challenge nevertheless.

Retina, 68% 72.8% (old) 74.8% 77.5% (new test battery)

i`^h(a[iy]|eya?|i(h?i|ya|)|ello)[ ,]+

T`l`L`^.

Try it online! Edit: Gained 4.8% (old) 2.7% (new) coverage with help from @MartinEnder's tips.


I'd like a homework pizza with everything on it, but no loops So there was a "please do my homework question" on StackOverflow that lead to an idea. As everyone knows loops are quite expensive, in some places they can get as high as $12.99 an iterations, so to save money there shouldn't be any loops.

So, lets do the homework, but in the least intuitive way.

  Write a program that decides, among competing candidate pizzas, which is the
  best deal, in the sense of the smallest cost per unit area. Pizzas come in three shapes:
  round, square, and oval (elliptical). The area of an oval is pi*ab/4, where:
   a and b are the longer and shorter dimensions of the oval.

The rest of the specifications are in the linked PDF, which I can add in if needed. The input and output should conform to the assignment.

As per breadboxes suggestion the I/O has changed a bit to be more golfy.

Your program must accept input for each pizza (lower case is a literal, uppercase is an argument):

In all of the below: C is the cost for that pizza in drachma (a float), and all units of length are in attoparsecs (~3cm).
C s L - a square pizza, with a size length L
C r D - a round pizza, with diameter D
C o L S - an oval pizza, with long side L and short side R, all ovals have an area of pi*L*S/4 (for some reason).
An empty string denotes that there are no more pizzas.

For each pizza, print out the area in attoparsecs, a literal @ and the cost in Drachma per square attoparsecs (just numbers, units not required).
After the user indicates there are no more pizzas, print the index of cheapest pizza (starting at 1).
Pi may be approximated to 3.1415

An example run would be (> indicates input, < is output, but these don't need to be printed to screen):

> 13.59 r 14.2
< 158.37 @ 0.086
> 14.04 s 12.3
< 151.29 @ 0.093
> 12.39 o 14.1 8.3
< 91.92 @ 0.135
>
< 1

Spaces are optional in output, but the @ symbol must be in the output of the pizza

However, you can't use any traditional loops. Recursion, gotos or list comprehension are all fine, but any thing that is syntactically a loop like a for, while or do ... while are all strictly forbidden.

Shortest code wins.

HTML/JavaScript, 160 bytes

(linebreaks/indentation only added here do prevent scrolling)

<input onchange='window.n++||(n=1,L=1e9);s=this.value.split(" ");d=s[2];
        a=[5.5/7*d*(s[3]||d),d*d][1*(s[1]=="s")];c=s[0]/a;alert(a!=a?m:a+"@"+c);
        L<c||(L=c,m=n)'>

The input is a text box (press Enter to submit); the output is an alert box.

A few caveats (or cheats, if you will):

Pi/4 is 5.5/7
in some cases, it assumes that the pizzas have non-zero areas
it's not possible to enter the same pizza twice in a row (because that won't trigger a change event)
note that defocusing the input also counts as "enter"
assumes that at least one pizza costs less than a billion Drachmas per square attoparsecs
no fault tolerance for the input whatsoever
you could argue that it's not qualified because it uses the browser's event loop


Minimalist Hex Clock Your challenge is to create a clock that displays the time as a hex number, and the background color as the hex color code of the time.

Requirements: No input. In the center of your output you should display the number sign and the current time in 24 hour format as "#hhmmss". The program should update to the current time at least once every second. The text must be centered and white (or a light color that stands out). The background should be entirely the color of the hex code. Shortest code wins, but creative answers are encouraged.

Live example. Idea from r/InternetIsBeautiful.

HTML/CSS/JavaScript 207 183 180 161 152

Tested and working in the latest Firefox and Chrome browsers.

<body id=b onload=setInterval("b.innerHTML=b.bgColor=Date().replace(/.*(..):(..):(..).*/,'#$1$2$3')",0) text=#fff style=position:fixed;top:50%;left:47%>

Demo Here


One out of Infinity: Interpolating polynomials For this challenge, when given a list of (x,y) points your submission needs to output a polynomial function that goes through all of them.
For example, if your points were [(0,0), (2,5)], you could return y = 2.5*x or y = x + 1/4x^2.

All points passed in will consist only of integers
Two points will never have the same y value
Your function be of the form y = a*x^n + ... b*x^m.   Reducing of terms is allowed.
Constants (the exponent and coefficient) can either be in decimal or fractional form.  Decimals should be accurate to at least 3 decimal places
You should be able to handle an arbitrary number of points
Output must be a string starting with "y=". Whitespace anywhere in the string is fine.

Test cases
Note, the given output is not the only valid output, just one of the possibilities.
(1,4)                                                    -> y=x+3
(0,0), (1,8)                                             -> y=8x
(0,6), (-1,90)                                           -> y=-84x+6
(6,4), (70,4), (-1,-6)                                   -> y=−10/497x^2+760/497x−316/71
(4,5), (5,6), (6,7)                                      -> y=x+1
(20,1), (-20,1), (0,5), (10, 4), (11,12), (17,4), (2,4)  -> y=488137/10424165400x^6−643187/473825700x^5−87561839/10424165400x^4+550999039/1042416540x^3−21590713027/5212082700x^2+300110420/52120827x+5

This is a code-golf, so make your answers as short as possible in your favorite language!

MATL, 38 bytes
ynq3$ZQ'y=' '%+fx^%i'btn:qP&vYDh1J3-h)

Inputs are an array with the x values and an array with the y values.
Try it online!
y          % Inplicitly take the two inputs, and push another copy of the first
nq         % Get its length minus 1. This is the required polynomial degree.
3$ZQ       % Coefficients of polynomial fitted to those data (`polyfit`)
'y='       % Push this string
'%+fx^%i'  % Push format string for `sprintf`
b          % Bubble up the polynomial coefficients to the top of the stack
tn:qP      % Duplicate and produce [n n-1  ... 0] where n is the polynomial degree.
           % These are the exponents
&v         % Concatenate vertically. This gives a 2D array with the coefficients in
           % the first row and the exponents in the second
YD         % Apply `sprintf` to this array with previous format string. The array
           % is read in column-major order: down, then across
h          % Concatenate 'y=' and formatted string representing the polynomial
1J3-h)     % The string ends in '...x^0'. Remove last three chars to delete this.
           % Implicitly display


Code Golf: Create a string of 100 of the same character The problem is to create a string of the same character repeated 100 times.

One potential solution in JavaScript is:

var i = 100,
    s = '';

while(i--) s += "Z";

Shortest code wins.

golflua: 109 15

w(S.t("a",100))

Which is more-or-less equivalent to Heiko's Lua answer


Reverse Boustrophedon Text Boustrophedon is a type of bi-directional text where successive lines alternate between reading left-to-right and right-to-left. Character direction was also mirrored with respect to reading direction. In reverse boustrophedon writing systems, characters were rotated 180 instead of mirrored.

Challenge

Write a program/function that accepts a string of text and a number of columns, and outputs the string formatted into the specified number of columns with alternating lines flipped upside down.

Input

Your program should accept two arguments:

S, the string of text to format
N, the number of columns

Output

Your program should output S wrapped in N columns with alternating lines flipped 180 degrees.

The reading direction of the first line is always left-to-right.
Don't worry about where to place line breaks, lines can be split at any character, no hypenation of words required.
You may assume input string will not contain any line breaks.

Here are the characters your program should support with their flipped counterparts:

Uppercase:
ABCDEFGHIJKLMNOPQRSTUVWXYZ
∀qƆpƎℲפHIſʞ˥WNOԀQɹS┴∩ΛMX⅄Z

Lowercase:
abcdefghijklmnopqrstuvwxyz
ɐqɔpǝɟƃɥᴉɾʞlɯuodbɹsʇnʌʍxʎz

Punctuation:
&_?!"'.,
⅋‾¿¡„,˙'

Test Cases

S: The quick brown fox jumps over the lazy dog.
N: 30
Output:
The quick brown fox jumps over
                ˙ƃop ʎzɐl ǝɥʇ

S: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque vel libero arcu. Nunc dictum elementum lectus nec aliquet. Donec dolor nunc, sodales at dolor rhoncus, hendrerit scelerisque purus. Pellentesque vel sagittis libero, et rutrum leo. Nullam vulputate enim et massa dictum, vitae venenatis augue lobortis. Fusce sollicitudin ultrices consequat. Vestibulum quis nunc non tortor eleifend facilisis. In at nunc elit. Aliquam pellentesque, lectus quis aliquam posuere, quam lectus sagittis metus, ut auctor sem quam a neque. Integer rhoncus lobortis nisl. Pellentesque mi dui, laoreet in metus quis, mollis accumsan est. Nunc dignissim tortor ac eleifend tempus. Ut ut tellus aliquam, luctus nulla quis, consectetur nunc. Suspendisse viverra molestie condimentum. Curabitur et hendrerit augue.
N: 50
Output:
Lorem ipsum dolor sit amet, consectetur adipiscing
uǝɯǝlǝ ɯnʇɔᴉp ɔunN ˙nɔɹɐ oɹǝqᴉl lǝʌ ǝnbsᴉnQ ˙ʇᴉlǝ
tum lectus nec aliquet. Donec dolor nunc, sodales
lǝԀ ˙snɹnd ǝnbsᴉɹǝlǝɔs ʇᴉɹǝɹpuǝɥ 'snɔuoɥɹ ɹolop ʇɐ
lentesque vel sagittis libero, et rutrum leo. Null
sᴉʇɐuǝuǝʌ ǝɐʇᴉʌ 'ɯnʇɔᴉp ɐssɐɯ ʇǝ ɯᴉuǝ ǝʇɐʇndlnʌ ɯɐ
 augue lobortis. Fusce sollicitudin ultrices conse
ɔɐɟ puǝɟᴉǝlǝ ɹoʇɹoʇ uou ɔunu sᴉnb ɯnlnqᴉʇsǝΛ ˙ʇɐnb
ilisis. In at nunc elit. Aliquam pellentesque, lec
ʇǝɯ sᴉʇʇᴉƃɐs snʇɔǝl ɯɐnb 'ǝɹǝnsod ɯɐnbᴉlɐ sᴉnb snʇ
us, ut auctor sem quam a neque. Integer rhoncus lo
snʇǝɯ uᴉ ʇǝǝɹoɐl 'ᴉnp ᴉɯ ǝnbsǝʇuǝllǝԀ ˙lsᴉu sᴉʇɹoq
 quis, mollis accumsan est. Nunc dignissim tortor
u snʇɔnl 'ɯɐnbᴉlɐ snllǝʇ ʇn ʇ∩ ˙sndɯǝʇ puǝɟᴉǝlǝ ɔɐ
ulla quis, consectetur nunc. Suspendisse viverra m
˙ǝnƃnɐ ʇᴉɹǝɹpuǝɥ ʇǝ ɹnʇᴉqɐɹnƆ ˙ɯnʇuǝɯᴉpuoɔ ǝᴉʇsǝlo

Bash + GNU utilities, 204

fold -$1|sed 2~2{s/.\\+/printf\ %$1's "`echo "&"|rev`"/e
y/'`printf %s {A..Z} {a..z}`"&_?!\"'.,/∀qƆpƎℲפHIſʞ˥WNOԀQɹS┴∩ΛMX⅄Zɐqɔpǝɟƃɥᴉɾʞlɯuodbɹsʇnʌʍxʎz⅋‾¿¡„,˙'/
}"

N is given on the command line and S is given via STDIN:

$ echo "The quick brown fox jumps over the lazy dog." | ./boustrophedon.sh 30
The quick brown fox jumps over
                ˙ƃop ʎzɐl ǝɥʇ
$

Explanation

fold -N splits the input into lines of length N.
The rest of the processing is done by sed, line-by-line:

2~2 matches every other line, starting at line 2
s/.+/printf %'N's "`echo "&"|rev`"/e uses GNU Sed's exec feature to call a shell to reverse the line and left-pad it with up to N spaces
y/ABC.../∀qƆ.../ transform characters

Note ABC... is generated using a bash expansion and printf.  Also some fancy quoting for all the different characters.