Here's Bub. A not-so-world-class soccer player This is Bub. Bub is a soccer player. However, he's not a very good one. He still can't kick the ball to the net! (If you haven't noticed, @ is the ball.

                                                       _____
                                                      |     \
  O                                                   |      \
 \|/                                                  |       \
  |                                                   |  net   \
 / ─   @                                              |_________\

To help develop his skills, he's developed a system to help evaluate his performance when he kicks the ball. He's called it the "10 point system."

However, he doesn't know what he needs to do to achieve x number of points. You need to help him visualize where the ball will be, so that he can set an expectation of how many points he wants to get. There are 10 points per round that he can achieve.

Therefore, this is your challenge.

Given a number x, the number of points Bub gets, output the location of the ball on the field. Here are some helpful markers:

Bub is exactly 50 spaces away from the net.
For each point that Bub gets, the ball moves 5 spaces closer to the net. Therefore, if Bub gets 3 points, the ball is 35 spaces away from the net.
For every 3 points that Bub gets, the ball begins to move in the air! It moves one space up.
If the number of points Bub gets would move the ball behind the net, you can put the ball anywhere inside the net.

Remember, you need to draw Bub, the ball, and the net.

To get you started, here's an example:

Number of Points: 5

                                                       _____
                                                      |     \
  O                                                   |      \
 \|/                                                  |       \
  |                          @                        |        \
 / ─                                                  |_________\

Standard rules apply. Code with the lowest number of bytes wins! Happy golfing!


List all multiplicative partitions of n Given a positive number n, output all distinct multiplicative partitions of n in any convenient format.

A multiplicative partition of n is a set of integers, all greater than one, such that their product is n. For example, 20 has the following distinct multiplicative partitions:

2 * 2 * 5
2 * 10
4 * 5
20

Order does not matter, so 2 * 2 * 5 is the same partition as 2 * 5 * 2.

Examples:

1 -> {}
2 -> {2}
4 -> {2, 2}, {4}
20 -> {2, 2, 5}, {2, 10}, {4, 5}, {20}
84 -> {2, 2, 3, 7}, {2, 2, 21}, {2, 14, 3}, {2, 6, 7}, {2, 42}, {4, 3, 7}, {28, 3}, {4, 21}, {6, 14}, {12, 7}, {84}

Brachylog, 16 bytes

>~l:{1<}a.*?,.=o

This is a function (not a full program) which takes a positive number as input and generates all multiplicative partitions of it. (I also avoided using any prime factorization builtins in this solution, mostly because I wasn't sure they'd help; I might try a more builtin-heavy solution too at some point.)

Try it online! (Extra code has been added around the function here to make it into a full program; if you provide the function shown above to TIO directly, it will run the function but not print its output anywhere, which is kind-of useless as a demonstration.)

This program really disappoints me, because much of it is working around bugs in the Brachylog interpreter and deficiencies in its specification, rather than actually solving the problem; but the interpreter is what it is. (Even with the program like this, the interpreter uses much more memory than it logically should, and crashes due to memory exhaustion, but luckily on small problems it manages to produce the desired output first.) In a hypothetical "perfect version of Brachylog" you could just write ~*.o.:{>1}a,, which would be 4 bytes shorter, but I needed to add extra constraints to help the interpreter out a bit. (I don't really like Brachylog much, and would rather stick to Prolog, but it needed similar hints to make the program work and they're much longer to write. So Brachylog it is.)

Explanation:

As usual, a Brachylog program is a set of constraints; by default, the first constraint constrains the input against an unknown (which I'll call A), the second constraint constrains A against a second unknown B, and so on until we reach the output. Some characters, such as {}, can change this general flow, so I use a different set of letters (e.g. X/Y) to represent unknowns in nested predicates.

>       A is smaller than the input
~l      B has length A
  1<    X is 1, Y is larger
:{1<}a  For each element X of B, it corresponds to an element Y of C
.       C, the output, and D are all identical
*       E is the product of D's elements
?       E, the input, and F are all identical
,       There's no constraint between F and G
.       G, the output, and H are all identical
=       H and I are identical, and need to be evaluated early
o       The output can be produced by sorting I

It's still unclear how the program works, so let's try simplifying the constraints a bit. C, D, G, H, and I are all the same (and equal to the output). E and F are also the same (and equal to the input). So our constraints boil down to this:

A is the length of B and of the output, and is smaller than the input.
B consists of all 1s, and isn't particularly useful (it's part of the program simply because in the existing Brachylog interpreter, :{1<}a needs its left argument to have a constrained length, or else the interpreter goes into an infinite loop).
The output consists entirely of numbers greater than 1 (i.e. greater than the corresponding element of B).
The product of the elements of the output is equal to the input.
The output is unchanged by sorting it (i.e. is in sorted order).

Incidentally, I didn't explicitly specify that all the elements of the output are integers, something which might seem to be required; however, Brachylog's constraint solver can't handle non-integers, so it'll conveniently produce only the solutions that involve integers.

Clearly, "the length of the output is smaller than the input" is going to be true whenever the output is a multiplicative partition of the input (because 2x > x for all nonnegative x, i.e. positive 2x). So we can disregard that constraint; it's only there to give the Brachylog interpreter a working strategy for evaluating the program. The other constraints (that the output is sorted, that its product is the input, and that its elements are all greater than 1) are the definition of a multiplicative partition, and therefore this function is basically just a direct implementation of the question.


Golf Dennis a thermometer Dennis puts in a huge amount of effort for this community, including as moderator, language designer, and provider of TIO.

Unfortunately, his four-year-old daughter has caught a cold, so let us all help him keep track of her recovery (may it be speedy) by providing him with a thermometer:

.-----------.
|           |
|           |
'-.       .-'
.-'   -   '-.
|107.6- 42.0|
|106.7- 41.5|
|105.8- 41.0|
|104.9- 40.5|
|104.0- 40.0|
|103.1- 39.5|
|102.2- 39.0|
|101.3- 38.5|
|100.4- 38.0|
| 99.5- 37.5|
| 98.6- 37.0|
| 97.7- 36.5|
| 96.8- 36.0|
| 95.9- 35.5|
| 95.0- 35.0|
'---. - .---'
    | - |
    |---|
    |   |
    '---'

Since Dennis does not have much time to read code, you must keep yours as short as possible.


Would this number make a good 2048 combo? Inspired by xkcd.

Your challenge is to determine whether a number would make a good combination in the game 2048. Your input will be a number, such as:

8224

And the output will be whether that number would make a good 2048 combo, which for this input would be true or yes or 1 or any other way of indicating a positive result.

For those not familiar with the game, here's a simple explanation: powers of two are arranged on a grid, like this: [2] [2]. Tiles can be moved in any direction, and if two identical tiles meet, they become the next power of two (so [2] [2] when moved left or right becomes [4]). Or, you could just try the game here.

What does "a good 2048 combination" mean? It means any number that, if it was in the game "2048", it could be combined into one single number. (A zero means an empty space, and can be ignored if needed.) Note that numbers could possibly be multiple digits! However, the numbers must not change between moves. Here are some examples/test cases (with "Good" indicating a good combination, and "Bad" meaning not good):

Good: 8224 (8224 -> 844 -> 88 -> 16)
Good: 2222 (2222 -> 44 -> 8)
Good: 22048 (22048 -> 448 -> 88 -> 16)
Bad: 20482 (cannot combine the outer 2's, nor can you combine a 2048 and a 2)
Good: 20482048 (20482048 -> 4096)
Bad: 210241024 (210241024 -> 22048, but this is now [2] [2048] and cannot be combined since numbers cannot change between moves)
Good: 2048 (it's already one number)
Bad: 2047 (it's not a power of 2)
Bad: 11 (there are no 1's in the game)
Good: 000040000000 (zeroes are empty spaces)

Miscellaneous rules:

Input can be from anywhere reasonable, i.e. STDIN, function argument, file, etc.
Output can also be anywhere reasonable, i.e. STDOUT, function return value, file, etc.
Ignore the grid size - 22222222 should still output true.
The is no maximum to what s number could be, as long as it's a power of two. Therefore the possible numbers are any power of two greater than 0.
For those worried about zeroes causing ambiguity, that is not the case. For example, 22048 can be parsed as either [2] [2048] or [2] [2] [0] [4] [8]. The first one doesn't work, but the second one does, so it should output true.
This is code-golf, so the shortest code in bytes will win!

Python: 457 422 characters
z=range
def c(n):
 for x in z(1,12):
  if int(n)==2**x:return 1
 return 0
def p(s):
 if s=='':return[]
 for i in z(len(s),0,-1):
  if c(s[:i])>0and p(s[i:])!=1:return [int(s[:i])]+p(s[i:])
 return 1
def r(a):
 if len(a)==1:return 1
 i,t=1,a[:1]
 while i<len(a):
  if a[i]==t[-1]:t[-1]*=2
  else:t+=[a[i]]
  i+=1
 if len(t)==len(a):return 0
 return r(t)
def f(s):
 if p(s)==1or r(p(s))==0:print('bad')
 else:print('good')

The function f(s) gets a string of digits and outputs 'good' or 'bad' accordingly.
I chose not to use 0 as spaces because spaces are meaningless in the game and they create ambiguity when parsing strings (is 22048 good or bad?). This only uses numbers up to 2048, but that can be changed without adding characters.
At the cost of 10 characters or so I can also print all the steps of combining the numbers.
And I realize that this code isn't golfed enough yet; don't worry, edits are coming.


Sum of first n terms of this series Given a digit x (between 0 to 9, inclusive) and a number n, calculate the sum of the first n terms of the following sequence:
\$x,10x+x,100x+10x+x,\dots\$
For example, if x is 6 and n is 2, then the result will be 6+66 meaning 72.
There can be trailing whitespace in the output but not leading whitespace.


Put together a Senate majority There are one hundred members of the United States Senate. Assuming that nobody filibusters and that the Vice President isn't cooperating, at least fifty-one members are necessary to pass a bill. But some members work together better than others, entropy-wise.
Your task: Output the last names of at least 51 of the US senators at the time this question was posted in 2017. Any 51 are acceptable; put together a Cruz-Sanders coalition if you'd like. The names may be output in any order.
The full list is as follows (note that Van Hollen is one person):

Alexander, Baldwin, Barrasso, Bennet, Blumenthal, Blunt, Booker,
Boozman, Brown, Burr, Cantwell, Capito, Cardin, Carper, Casey,
Cassidy, Cochran, Collins, Coons, Corker, Cornyn, Cortez Masto,
Cotton, Crapo, Cruz, Daines, Donnelly, Duckworth, Durbin, Enzi, Ernst,
Feinstein, Fischer, Flake, Franken, Gardner, Gillibrand, Graham,
Grassley, Harris, Hassan, Hatch, Heinrich, Heitkamp, Heller, Hirono,
Hoeven, Inhofe, Isakson, Johnson, Kaine, Kennedy, King, Klobuchar,
Lankford, Leahy, Lee, Manchin, Markey, McCain, McCaskill, McConnell,
Menendez, Merkley, Moran, Murkowski, Murphy, Murray, Nelson, Paul,
Perdue, Peters, Portman, Reed, Risch, Roberts, Rounds, Rubio, Sanders,
Sasse, Schatz, Schumer, Scott, Shaheen, Shelby, Stabenow, Strange,
Sullivan, Tester, Thune, Tillis, Toomey, Udall, Van Hollen, Warner,
Warren, Whitehouse, Wicker, Wyden, Young

Querying Wolfram Alpha (or any other database of senators) is specifically disallowed. Anything else is fair game; use gzip as a language if you'd like.

Bubblegum, 165 164 163 162 161 160 bytes

00000000: 1dc6 410a 0231 0c00 c0bf b50a c22a 880a  ..A..1.......*..
00000010: e231 b4c1 0697 6449 5aa5 bede c4cb 303b  .1....dIZ.....0;
00000020: 2046 5bc2 5b1b 0ead 2b59 5a07 f72c 5eb6   F[.[...+YZ..,^.
00000030: bdb2 f9c5 c75f 4ac8 8c7d 09eb cc60 1818  ....._J..}...`..
00000040: c5b5 12bb 1bea a964 886f d425 2b6c cef8  .......d.o.%+l..
00000050: 5e4b 83ee 4aef 49e5 c3d9 23ae f20c 5fa8  ^K..J.I...#..._.
00000060: f759 9193 4894 4a08 ca7f 15f9 e092 1d04  .Y..H.J.........
00000070: df71 3370 7b69 572f 5ec8 625c 51ed 8c3d  .q3p{iW/^.b\Q..=
00000080: 84b1 ded0 bc59 4a53 e093 0443 1566 727d  .....YJS...C.fr}
00000090: 5b9b 4784 0017 e2e7 05b1 3e64 789c 6a3f  [.G.......>dx.j?

Try it online!

Output

  DainesKaineThuneTillisBluntCollinsErnstCoonsEnziBennetKennedyCaseyCassidyCardinCarperMcCainCapitoCrapoCruzSchatzScottBrownCottonCornynCorkerWydenBookerWickerWarnerWarrenHarrisHoevenHassanHatchSasseRischSandersPetersPaulTesterCochranMoranMurrayBurrMurphyLeahyLeeKingReedYoungRounds

How I generated this

Previous versions were generated by simulated annealing, but now I’ve switched strategies to late acceptance hill-climbing.  I’m not sure whether it’s fundamentally better or I just got luckier this time, but I do appreciate that LAHC has fewer parameters to tweak to get good results.

from __future__ import print_function
import random
import zlib

try: range = xrange
except NameError: pass

senators = b'Alexander, Baldwin, Barrasso, Bennet, Blumenthal, Blunt, Booker, Boozman, Brown, Burr, Cantwell, Capito, Cardin, Carper, Casey, Cassidy, Cochran, Collins, Coons, Corker, Cornyn, Cortez Masto, Cotton, Crapo, Cruz, Daines, Donnelly, Duckworth, Durbin, Enzi, Ernst, Feinstein, Fischer, Flake, Franken, Gardner, Gillibrand, Graham, Grassley, Harris, Hassan, Hatch, Heinrich, Heitkamp, Heller, Hirono, Hoeven, Inhofe, Isakson, Johnson, Kaine, Kennedy, King, Klobuchar, Lankford, Leahy, Lee, Manchin, Markey, McCain, McCaskill, McConnell, Menendez, Merkley, Moran, Murkowski, Murphy, Murray, Nelson, Paul, Perdue, Peters, Portman, Reed, Risch, Roberts, Rounds, Rubio, Sanders, Sasse, Schatz, Schumer, Scott, Shaheen, Shelby, Stabenow, Strange, Sullivan, Tester, Thune, Tillis, Toomey, Udall, Van Hollen, Warner, Warren, Whitehouse, Wicker, Wyden, Young'.split(b', ')
assert len(senators) == 100

random.shuffle(senators)
score = 9999
best = score
recent = 65536 * [score]
recent_index = 0

while True:
    old_score = score
    step = random.randrange(2)
    if step == 0:
        i, j = 100, 100
        while i >= 51 and j >= 51:
            i, j = random.sample(range(100), 2)
        senators[i], senators[j] = senators[j], senators[i]
    else:
        i, j, k = 100, 100, 100
        while i >= 51:
            i, j, k = sorted(random.sample(range(101), 3))
        senators[i:k] = senators[j:k] + senators[i:j]

    bound = max(old_score, recent[recent_index])

    z = zlib.compressobj(9, zlib.DEFLATED, -zlib.MAX_WBITS, 9)
    sin = b''.join(senators[:51])
    sout = bytearray(z.compress(sin) + z.flush())
    score = len(sout) * 8
    if score - 7 <= bound:
        for bit in range(7):
            sout[-1] ^= 128 >> bit
            try:
                if zlib.decompress(bytes(sout), -zlib.MAX_WBITS) == sin:
                    score -= 1
                else:
                    break
            except zlib.error:
                break

    if score > bound:
        if step == 0:
            senators[i], senators[j] = senators[j], senators[i]
        else:
            j = i + k - j
            senators[i:k] = senators[j:k] + senators[i:j]
        score = old_score
    elif score < recent[recent_index]:
        recent[recent_index] = score
        if score < best:
            best = score
            print(score, b''.join(senators[:51]).decode())
    recent_index = (recent_index + 1) % len(recent)


Point-free look and say sequence You are too make a program that take an integer as the input and outputs the first what ever that number was of the look and say sequence.

For example:

$ ./LAS
8
[1,11,21,1211,111221,312211,13112221,1113213211]

The exact way you output the list is unimportant, as long as users can distinctly see the different numbers of the sequence. Here is the catch though. You can't use any sort of user-defined variable.

For example:

No variables, including scoped variables.
When you have functions, they can not have a name. (Exception, if your language requires a main function or similar to work, you may have that function.)
When you have functions, they can not have named arguments.

Also, you may not use a library with specific capabilities relating to the look and say sequence, and you can not access the network, or provide your program with any files (although it can generate and use its own.) This is code golf, so shortest code in characters wins!

Haskell 206 Chars

import Data.List
import Control.Applicative
import Data.Function
main= readLn >>= print .(flip take (map read $ fix (("1":). map (concat .(map ((++)<$>(show . length)<*>((:[]). head))). group))::[Integer]))

It works by using the group function to group them into groups of equal things. Then it uses applicatives with functions to build a function that simultaneously reads the length, and appends it to with one the elements. It uses a fix and a map to create a recursive definition (point-free.) And there ya go.


Longest code to add two numbers Task:

I know we can all add two numbers the short way, using +. Your task is to create the longest code you can to add two input numbers.

Rules:

All of the code must be on topic (don't fill it with non-addition code to add length)
The count is in characters, but do not count tabs, spaces, or newlines.
Do not use extraneously long variable names
This is code-bowling, so the longest answer wins!


Sum of smallest prime factors SF(n) is a function which computes the smallest prime factor for a given number n.

We'll call T(N) the sum of every SF(n) with 2 <= n <= N.

T(1) = 0 (the sum is over 0 summands)

T(2) = 2 (2 is the first prime)

T(3) = 5 = 2 + 3

T(4) = 7 = 2 + 3 + 2

T(5) = 12 = 2 + 3 + 2 + 5

...

T(10000) = 5786451

The winner will be the one who manages to compute the largest T(N) in 60 seconds on my own laptop (Toshiba Satellite L845, Intel Core i5, 8GB RAM).

Current top score: Nicolás Siplis - 3.6e13 points - Nim

Nim, 3.6e13

Simply sieving is not the best answer when trying to calculate the highest N possible since the memory requirements become too high. Here's a different approach (started with Nim a couple days ago and fell in love with the speed and syntax, any suggestions to make it faster or more readable are welcome!).

import math
import sequtils
import nimlongint # https://bitbucket.org/behrends/nimlongint/

proc s(n : int) : int128 =
    var x = toInt128(n)
    (x * x + x) div 2 - 1

proc sum_pfactor(N : int) : int128 =
    var
        root = int(sqrt(float(N)))
        u = newSeqWith(root+1,false)
        cntA,cntB,sumA,sumB = newSeq[int128](root+1)
        pcnt,psum,ret : int128
        interval,finish,d,q,t : int

    for i in 0..root:
        cntA[i] = i-1
        sumA[i] = s(i)

    for i in 1..root:
        cntB[i] = N div i - 1
        sumB[i] = s(N div i)

    for p in 2..root:
        if cntA[p] == cntA[p-1]:
            continue

        pcnt = cntA[p - 1]
        psum = sumA[p - 1]
        q = p * p
        ret = ret + p * (cntB[p] - pcnt)
        cntB[1] = cntB[1] - cntB[p] + pcnt
        sumB[1] = sumB[1] - (sumB[p] - psum) * p
        interval = (p and 1) + 1
        finish = min(root,N div q)

        for i in countup(p+interval,finish,interval):

            if u[i]:
                continue

            d = i * p

            if d <= root:
                cntB[i] = cntB[i] - cntB[d] + pcnt
                sumB[i] = sumB[i] - (sumB[d] - psum) * p
            else:
                t = N div d
                cntB[i] = cntB[i] - cntA[t] + pcnt
                sumB[i] = sumB[i] - (sumA[t] - psum) * p

        if q <= root:
            for i in countup(q,finish-1,p*interval):
                u[i] = true

        for i in countdown(root,q-1):
            t = i div p
            cntA[i] = cntA[i] - cntA[t] + pcnt
            sumA[i] = sumA[i] - (sumA[t] - psum) * p

    sumB[1] + ret

var time = cpuTime()
echo(sum_pfactor(int(3.6e13))," - ",cpuTime() - time)


Tell me the Lunar Phase! Challenge

Given an image of the Moon as input, output the phase of the Moon.

Phases of the Moon

Your program will be supplied one of these images in png format and you must output the phase exactly as given:

new moon

hexdump

waxing crescent

hexdump

first quarter

hexdump

waxing gibbous

hexdump

full moon

hexdump

waning gibbous

hexdump

third quarter

hexdump

waning crescent

hexdump

Input

The input will be the path to a 240 px by 240 px png file and will be the one of the images above.

The image bytes are guaranteed to be the same.

Winning

Shortest code wins


Find the reference angle This is a fairly simple question. According to this random website I found — Web Archive, a reference angle is the acute angle formed by the terminal side of the given angle and the x-axis. You have to write a program to find these.
I don't remember anything from algebra 2, what does this mean?
Angles are usually given in standard form, which is measured by placing one side of the angle and measuring to the other side, counterclockwise, like so:

This will be your input. Your output will be the reference angle of this. You can think of this as basically the smallest distance from the terminal side to the x-axis. Except it's an angle, not a distance. Here are some examples:

Clarifications

All the defaults on inputs and submissions.
Angles is in degrees.
Negative angles, non-integer angles, and angles > 360 deg are allowed.
Output in form 60 deg.
This is code-golf, so shortest code in bytes wins!

Another helpful link.
Test Cases
70      ->  70 deg
135     ->  45 deg
210     ->  30 deg
-60     ->  60 deg
91      ->  89 deg
610     ->  70 deg
-1000   ->  80 deg

Pyth, 17 bytes

+hS%R180,Q_Q" deg

Coincidentally, this is equivalent to @xnor's answer.

Try it online.


Unwise bit operations I like to golf in dc, but I'm sometimes frustrated because dc doesn't have bitwise operations.
Challenge
Provide four named functions which implement the equivalent of the c bitwise operations &, |, ~ and ^ (bitwise AND, OR, NOT and XOR).  Each function will take two operands (~ takes only one) which are at least 32-bit unsigned integers.  Each function will return an unsigned integer of the same bit-width as the operands.
Restriction
You may only use operations that are supported by dc.  These are:

+ - * / Arithmetic addition, subtraction, multiplication and division
~ modulo (or divmod if your language supports it)
^ exponentiation
| modular exponentiation
v square root
> >= == != <= < standard equality/inequality operators
>> << bit shift operators.  dc doesn't have these, but since they are trivially implemented in terms of division/multiplication by powers of 2, then I will allow these.

Control structures in dc my be clumsily built using (recursive) macros and (in)equality operations.  You may use whatever built-in control structures your language has.
You may also use logical operators && || !, even though these aren't directly available in dc.
You must not use the bitwise operators &, |, ~ and ^ or any functions that trivially implement them.
In addition you must not use built-in base-conversion-of-string operators or functions.

Please also consider providing a test program or online compiler snippet (not included in the golf score) to help verify your answer.

C, 134

The C preprocessor is pretty fun to abuse. Basically this macro defines the 3 functions, a, o, and x, for and, or, and xor respectively. The only difference in the algorithm for these operations is the criteria for setting the bit in the result.

not is the function n.

#define f(n,c)n(a,b){for(r=0,i=31;i+1;--i)if(((a>>i)%2+(b>>i)%2)c)r+=1<<i;return r;}
i,r;n(a){return 0xffffffff-a;}f(a,/2)f(o,)f(x,%2)

Tester program (takes a long time, I didn't spend any time optimizing it at all, but it does test every test case possible, beside MAX_INT related ones):

#define m_assert(expected, condition, actual)\
    if(!((expected) condition (actual)))\
        printf("assert fail @ line %i, expected: %x, actual %x, condition "#condition"\n", __LINE__, expected, actual);

int main()  {
    unsigned int j,k;
    for(j=0; j<0xffff; ++j)    {
        m_assert(~j, ==, n(j));
        for(k=0; k<0xffff; ++k)    {
            m_assert(j & k, ==, a(j,k));
            m_assert(j | k, ==, o(j,k));
            m_assert(j ^ k, ==, x(j,k));
        }
    }


RUBY (449 436 chars)

I=*(0..8)
b=$*[0].split('').map{|v|v<'1'?I.map{|d|d+1}:[v.to_i]};f=b.map{|c|!c[1]}
[[z=I.map{|v|v%3+v/3*9},z.map{|v|v*3}],[x=I.map{|v|v*9},I],[I,x]
].map{|s,t|t.map{|i|d=[a=0]*10;s.map{|j|c=b[i+j];c.map{|v|d[v]+=1if !f[i+j]}
v,r=*c;s.map{|k|b[i+k].delete(v)if j!=k}if !r
s[(a+=1)..8].map{|k|s.map{|l|b[i+l]-=c if l!=k&&l!=j}if c.size==2&&c==b[i+k]}}
v=d.index 1;f[i+k=s.find{|j|b[i+j].index v}]=b[i+k]=[v]if v}}while f.index(!1)
p b*''

Example:

C:\golf>soduku2.rb 030001000006000050500000983080006302000050000903800060714000009020000800000400030
"832591674496387251571264983185746392267953418943812765714638529329175846658429137"

quick explanation:
Board b is an array of 81 arrays holding all the possible values for each cell.
The array on line three holds [offset,start_index] for each group (boxes,rows,columns).
Three tasks are performed while iterating through the groups.

The value of any cell of size 1 is removed from the rest of the group.
If any pair of cells contain the same 2 values, these values are removed from the rest of the group.
The count of each value is stored in d - if there is only 1 instance of a value, we set the containing cell to that value, and mark the cell fixed in f

Repeat until all cells are fixed.


The negative order integer challenge, but it's Prime Time! Im talking about this question, take a look at it if you are a bit confused.

Main Task

Your task is to output concatenated integers, in decreasing order, but increasing the maximum integer everytime you hit 1 (for this question, 1 will be considered a prime number). While this doesn't sound any different from the first question, here comes the tricky part: All outputted numbers may only be primes. These will be strung together into a single string without spaces or newlines. Your input will also be a prime number.

Example:

1
21
321
5321
75321
1175321
Valid output:
1213215321753211175321

Input

Your code may only take one input: the highest prime to be printed. This input can come from anywhere (graphical, STDIN). You are assured that the input is a prime number.

Output

You will have to output the resulting number. You can get this number by keep counting down, only count the number if it's a prime, then connect all results together to one number. The last number "row" (e.g. 7, 5, 3, 2, 1) has to be printed fully. The output could be anything (numbers, strings, graphical), as long as it's readable. The same Regex pattern for checking your test cases applies:

^(\D*(\d)+\D*|)$

If your output doesn't match with this pattern, your code is invalid.

Rules

The input is assured to be prime, do not include error handling, unless you want/need to.
The output may only be a full-connected number, therefore not split up by anything, not even newlines.
Your algorithm shouldn't check for the first instance of N appearing (for instance, the 17 in 1175321), but rather for the first instance of N as the actual number.
Your input is assured to be positive, do not add handling unless you want/need to.

Test cases

Input: -2, 0
Output: Any, or none (number isn't positive)

Input: 9
Output: Any, or none (number isn't prime)

Input: 1
Output: 1

Input: 7
Output: 121321532175321

Input: 23
Output: 1213215321753211175321131175321171311753211917131175321231917131175321

Winner

This is code-golf, so the author of the code with the least length in bytes wins!

Processing, 161 bytes
int p(int n){for(int k=1;++k<=sqrt(n);)if(n%k<1)return 0;return 1;}void t(int n){for(int i=1,j;i<=n;i++){if(p(i)<1)continue;for(j=i;j>0;j--)print(p(j)<1?"":j);}}

One function does the primality checking, the other does the printing. Call it by t(7)
Ungolfed
The first function does the primality checking. It returns an int instead of a boolean since this way more bytes are saved. (int instead of boolean, 0 instead of false, 1 instead of true)
int Q103891p(int n){
  for(int k=1;++k<=sqrt(n);)
    if(n%k<1)return 0;
  return 1;
}

The second function prints out the string. It iterates through every number, if it is not a prime, skip to the next iteration. If it is a prime, it continues down to the printing inside another for-loop. Again, if the number is prime, then we print it, otherwise not.
void Q103891(int n){
  for(int i=1,j;i<=n;i++){
    if(p(i)<1)continue;
    for(j=i;j>0;j--)
      print(p(j)<1?"":j);
  }
}


Just Another Perl Hacker Classic code golf challenge. Write the most obscure Perl program to print "Just another Perl hacker". Here's the Wikipedia article on it. Bonus points if it fits in 3 lines / 70 characters each.


Fibonacci is so QUINE! Your program must output atleast half of its sourcecode in reverse. Any single part of the sourcecode as long as it is one single block of neighbouring characters.
Your program should not take any input (from user, filename, network or anything).
The output has some additional constraints. The character position (first character is #1) on the output is either a fibonacci-sequence number (1, 1, 2, 3, 5, 8, 13, 21, ...) or not (4, 6, 7, 9, 10, 11, 12, ...), and this is the constraints:

3.1 Every third fibonacci-sequence number output position must be a letter (a-z|A-Z). Starting at fibonacci-sequence number #2 (output char|byte pos: 1, 5, 21, ...).
3.2 Every third fibonacci-sequence number output position must be a number (0-9). Starting at fibonacci-sequence number #3 (output char|byte pos: 2, 8, 34, ...).
3.3 Every third fibonacci-sequence number output position must be a symbol !(0-9|a-z|A-Z). Starting at fibonacci-sequence number #4 (output char|byte pos: 3, 13, 55, ...).

The output must contain exactly all of these three phrases in any place as long as the other rules is not broken (case sensitive): Fibonacci is so QUINE!, 3 is more than {4}, {'{"\}

This is code-golf, shortest sourcecode in bytes wins! Good luck, have fun!

Befunge '98, 91 characters

Was formerly 104, then 101. Saved another 10 chars by moving the "Fi...E!" sentence to output position 89 using 'E' (instead of ' ' at 55), and moving the actual code into the space this opened up, with a slightly improved print loop.

"!ENIUQ os si iccanobiF"f6*>:;#-1,g0;#:_ "}\"f:4++"{'{",,0$,,,,@"}4{ naht erom si 30" b >0a

produces the following output (fibonacci positions marked):

a0> b "03 is more than {4}"@,,,,$0,,"{'{"++4:f"\}" _:#;0g,1-#;:>*6f"Fibonacci is so QUINE!{'{"\}
--- -  -    -       -            -                    -                                 -
|   |               |                                                                   |
 |     |                         |
  |         |                                         |

This snippet outputs all of itself, except for the first character, in reverse order. Then it appends {'{"\} to the output, yielding a total of 96 chars including 98.9% of the code.

Positions 1, 5, 21 and 89 are each occupied by 'a', 'b' or 'E'.
Positions 2, 8 and 34 each have a '0'.
In positions 3, 13 and 55, we find '>', ' ' and ';', all symbols according to the definition given by Plarsen.

There are 3 completely unused cells, and all of b >0a is utterly useless code, only there for the aesthetics of a0> b  0. There may (still) be room for optimization.

Since String mode means pushing a reverse string to the stack and then pop/print-ing it forward, writing them in reverse order is totally natural in Befunge.

Breakdown

f6* calculates 90, the index of the last character in the source. It's 15 * 6.
>: means 'head east and duplicate the top of stack value'. Stack [ ... 90 90 ].
;...; skips over the code in between.
#:_ skips the :, then pops TOS and heads back west if not 0. Stack [ ... 'F' 90].
Now RTL: ,g0;#: duplicates TOS, skips entry to the ; portal, gets the character at (TOS, 0) and prints it.
Still RTL: :;#-1 decrements TOS, skips ; and duplicates TOS. Execution continues at step 2.) Stack [ ... 89 89 ]
Once the TOS counter is down to 0, _ lets us through.
We push the third required string , whereby we have to calculate the '"' because there is no escaping in Befunge. f:4++ is 15 + 15 + 4. The commas write it back out from the stack. I had to insert 0$ there (push 0 then pop/discard) to meet the requirement.
@ terminates.


Write a program to compose a quine of a specified length Write a program, in a language of your choice, that will compose a quine program of a requested size. The generated program may be in the same or a different language, if desired.

Programs are scored based on the following formula:

  generating_program_length + smallest_supported_size + 512 * number_of_supported_sizes ^ (-3/4)

Halve your score if you support every size between the minimum and maximum supported sizes.

Lowest score wins.

GolfScript → GolfScript: (4 + 0 + 0) / 2 = 2

~1`*

Program length: 4
Minimum supported size: 0
Maximum supported size: unbounded
All sizes supported: yes

This program simply reads an integer n from its input, and outputs an n-digit integer consisting of n 1 digits.  For example, the input 5 yields the output 11111.  In GolfScript, any integer literal (without leading zeros) is a quine, and since GolfScript integers can be arbitrarily large, the maximum supported length is only bounded by the amount of memory available.

For the input 0, the code outputs an empty program, which is also a quine in GolfScript.

Ps. The generated quines work for several other languages too, including PHP.


Perimeter of Conway hexagon Background

Given a triangle \$ABC\$, extend its three sides by the opposite side length, as shown in the figure below. Then the six points surprisingly lie on a circle called the Conway circle, whose center coincides with the incenter (the center of incircle, the circle that is tangent to the three sides from the inside).

Task

Given three side lengths \$a,b,c\$ of the triangle \$ABC\$, calculate the perimeter of the hexagon \$A_b B_a B_c C_b C_a A_c\$ (formed by the six points on the Conway circle).

The answer must be within 1e-6 relative error from the expected. You can assume the side lengths form a valid non-degenerate triangle.

The shortest code in bytes wins.

Test cases

a   b   c         ans
---------------------
1   1   1    9.000000
2   2   3   20.399495
3   4   5   35.293155
6   7   12  65.799785
2.3 4.5 6.7 31.449770

Python 3, 89 87 69 68 bytes
Thanks @xnor for finding a shorter expression, saving 1 byte!

f=lambda a,b,c,n=3:n and(a+b+c)*(c*c/a/b-a/b-b/a+2)**.5+f(b,c,a,n-1)

Try it online!
A recursive function, takes in 3 sides of the triangle as input.
Recursion is used to repeats the function 3 times, each time with the positions of a,b,c swapped in order to calculate each of the 3 summands in the formula below.
How
We can see that each side of the hexagon is the base of an isosceles triangle, whose vertex angle is an angle of the original triangle. For example:

\$C_aC_b\$ is the base of \$CC_aC_b\$ - an isosceles triangle with leg \$c\$ and vertex angle \$\widehat{C}\$.
\$A_bB_a\$ is the base of \$CA_bB_a\$ - an isosceles triangle with leg \$a+b\$ and vertex angle \$\widehat{C}\$.

Given the leg \$l\$ and vertex angle \$\theta\$ of an isosleces triangle, the base is calculated as:
$$l\sqrt{2-2\cos{\theta}}$$
Consider 2 opposites side of the hexagon, says \$C_aC_b\$ and \$A_bB_a\$. Since their corresponding triangles have the same vertex angle, their total length is:
$$c\sqrt{2-2\cos{\widehat{C}}}+(a+b)\sqrt{2-2\cos{\widehat{C}}}$$$$=(a+b+c)\sqrt{2-2\cos{\widehat{C}}}$$
Then the perimeter of the hexagon is the sum of 3 opposite pairs:
$$(a+b+c)\left(\sqrt{2-2\cos{\widehat{A}}}+\sqrt{2-2\cos{\widehat{B}}}+\sqrt{2-2\cos{\widehat{C}}}\right)$$
The cosine of an angle can be calculated from the sides of the triangle:
$$2-2\cos{\widehat{C}}=\frac{c^2-(a-b)^2}{ab}$$
Thus, the final formula for the hexagon's perimeter is:
$$(a+b+c)\left(\sqrt{\frac{a^2-(b-c)^2}{bc}}+\sqrt{\frac{b^2-(a-c)^2}{ac}}+\sqrt{\frac{c^2-(a-b)^2}{ab}}\right)$$


Jelly,  187  166 bytes

ḣ9;⁾| ṁ5¤oµ€“µ½¿‘¦
“ _/ |/|”;€⁶;”_ṁ"“¡ẇḞ6’D¤ṃ@“Ė⁸ġṾṗ¢œƝṇRK⁹ṄẸŒÐ¤ɓḂı)ḥṆqƓị¹÷ḄƝṁPʠVW1JĊTc;[¤ÆWŒṠṬ#ʋÆ6ẉ⁷ZḷƊḤƑẹẠGḊ|qi×Ƭ®ÐėƁ1(⁸ṪU¹Bgoƭ<Gḋ×c:ȦṚƇĊ¬e*⁽%ḷİ°U’Fs27Ç¹⁸?x€15¦€19Y

A full program.

Try it online!

How?

103 bytes are a 101 digit base 250 number, which is a base-8 compression of a possible cube, with trailing spaces added to equalise the row-lengths, without new lines, and without 18 characters from the middle of each row, like this, but without newlines:

         _________________
        / _____________  /|
       / / ___________/ / |
      / / /| |       / /  |
     / / / | |      / /   |
    / / /| | |     / / /| |
   / / / | | |    / / / | |
  / / /  | | |   / / /| | |
 / /_/___|_|_|__/ / / | | |
/________________/ /  | | |
| ______________ | |  | | |
| | |    | | |_| | |__| | |
| | |    | |___| | |____| |
| | |   / / ___| | |_  / /
| | |  / / /   | | |/ / /
| | | / / /    | | | / /
| | |/ / /     | | |/ /
| | | / /      | |   /
| | |/_/_______| |  /
| |____________| | /
|________________|/

The 8 base-8 digits represent the strings of characters:

1      2    3    4    5    6        7        0
"   ", "_", "/", " ", "|", "/ / /", "| | |", "_____"

So the compression is then like the below where 1s, 6s, 7s and 0s are to be replaced by the strings shown above:

111000__111/ 00___  /|11 / / 00_/ / |116| |11 / /  |1  6 | |11/ /1|1 671  6| |16 71 6 | |  6  7167 6___|_|_|__6 7/000_/ /  7| 00____ | |  771 7_7__771 | |___7____| |71/ / ___7_  / / 7  6176  7 61 7 / /1761  7/ /1 7 / /11| |1/1  7/_/0__| |  /11| |00__| | /11 |000_|/11

The program reverses the process and changes the characters that need changing if the cube should be an impossible one:

“ _/ |/|”;€⁶;”_ṁ"“¡ẇḞ6’D¤ṃ@“ ... ’Fs27Ç¹⁸?x€15¦€19Y  Main link: V
                                                     ...splitting this up...
                                                     ...Main link part 1:
“ _/ |/|”;€⁶;”_ṁ"“¡ẇḞ6’D¤ - make the list of strings of characters
“ _/ |/|”                 - list of characters = " _/ |/|"
           ⁶              - literal space character
         ;€               - concatenate €ach -> ["  ","_ ","/ ","  ","| ","/ ","| "]
             ”_           - literal = '_'
            ;             - concatenate -> ["  ","_ ","/ ","  ","| ","/ ","| ", '_']
                        ¤ - nilad followed by link(s) as a nilad:
                 “¡ẇḞ6’   -   base 250 literal = 31111555
                       D  -   convert to decimal list -> [3,1,1,1,1,5,5,5]
                "         - zip with:
               ṁ          -   mould like
                          -   -> ["   ","_","/"," ","|","/ / /","| | |","_____"]

                                                     ...Main link, part 2:
...ṃ@“ ... ’Fs27 - make the rows of a possible cube without the middle repetitions:
...              - part 1, above
     “ ... ’     - the 101 digit base 250 number
   ṃ@            - base decompression with swapped @rguments
            F    - flatten (because the digit values we are using are actually lists)
             s27 - split into chunks of length 27 (into the rows)

                                                     ...Main link part 3:
...Ç¹⁸?x€15¦€19Y - make "impossible" if need be, add the row middles and output
...              - part 2, above
       ?         -  if:
      ⁸          -    chain's left argument = V
   Ç             - ...then: call last link (1) as a monad
                 -          (make it an impossible cube - see link 1, below)
    ¹            - ...else: identity (do nothing)
            €    - for €ach
         ¦       - apply sparsely:
       15        - ...to index: 15
     x€    19    - ...this: repeat €ach nineteen times
               Y - join with newlines
                 - implicit print

ḣ9;⁾| ṁ5¤oµ€“µ½¿‘¦  Link 1, replace characters to make impossible: rows
                 ¦  apply sparsely:
            “µ½¿‘   ...to indexes: code-page indexes = [9,10,11]
                    ...this:
          µ€          for €ach:
ḣ9                      head to index 9
        ¤               nilad followed by link(s) as a nilad:
   ⁾|                     list of characters = ['|',' ']
      ṁ5                  mould like 5 = ['|',' ','|',' ','|']
  ;                     concatenate
         o              logical or (vectorises) with the row
                          (which has the effect of appending the rest of the row)


Draw boxes from box drawing characters In the old DOS operating system, a number of characters were provided to draw boxes. Here is a selection of these characters and their code points:

B3 B4 BF C0 C1 C2 C3 C4 C5 D9 DA
│  ┤  ┐  └  ┴  ┬  ├  ─  ┼  ┘  ┌

You can use these characters to draw boxes like this:

┌─────────┐
│         │
└─────────┘

Boxes can be attached to each other:

        ┌───┐
        │   │
┌───┬───┤   │
│   │   │   │
│   ├───┴───┘
│   │
└───┘

or intersect each other:

┌─────┐
│     │
│  ┌──┼──┐
│  │  │  │
└──┼──┘  │
   │     │
   └─────┘

or overlap each other partially or completely:

┌─────┐
├──┐  │
│  │  │
├──┘  │
└─────┘

Challenge description

Write a program that receives a series of positive decimal integers separated by whitespace from standard input. The number of integers you receive is a multiple of four, each set of four integers x1 x2 y1 y2 is to be interpreted as the coordinates of two points x1 y1 and x2 y2 forming opposing corners of a box. You may assume that for each set of coordinates, x1 ≠ x2 and y1 ≠ y2.

The coordinate system originates in the top left corner with x coordinates progressing to the right and y coordinates progressing downwards. You can assume that no x coordinate larger than 80 and no y coordinate larger than 25 appears.

Your program shall output in either UTF-8, UTF-16, or Codepage 437 a series of whitespace, carriage returns, line feeds, and box drawing characters such that the output shows the boxes described in the input. There may be extraneous whitespace at the end of lines. You may terminate lines either with CR/LF or just LF but stick to one, stray CR characters are not allowed. You may output any number of lines filled with an arbitrary amount of whitespace at the end of the output.

Examples

The following input draws the first diagram from the question:

1 11  1 3

The second diagram is offset a little bit, the leading whitespace and empty lines must be reproduced correctly:

17 13   3  7
 9  5   5  9
 9 13   5  7

The third diagram also tests that input is parsed correctly:

1 7 1
5 4 10
3 7

The fourth diagram:

11 5 2 6
5 8 3 5

As a final test case, try this fifth diagram:

    ┌─────┬─────┐
┌───┼───┬─┼─┬───┴───┐
│   │   │ │ │       │
└───┼───┴─┼─┴───┬───┘
    └─────┴─────┘

Which looks like this:

9 21 2 4 1
13 4 2 11 5
1 5 17 11 1
2 11 17 4 5

Winning condition

This is code golf. The shortest solution in octets (bytes) wins. Standard loopholes apply, (worthless) bonus points for writing a solution that works on DOS.

PHP>=7.1, 820 Bytes

<?preg_match_all("#(\d+(\s+\d+){3})#s",$_GET[0],$t);$r=($w="array_fill")(1,25,$w(1,80," "));function u($n,$y,$x){global$r;$u=[$z=[" ","│",$c="┤","┐","└",$d="┴",$e="┬",$b="├","─","┘","┌",$a="┼"],["│",$c,$b,$a],[$c,$a],["┐",$c,$e,$a],["└",$d,$b,$a],[$d,$a],[$e,$a],[$b,$a],["─",$d,$e,$a],["┘",$c,$d,$a],["┌",$e,$b,$a],[$a]];$o=$r[$y][$x];$s=array_intersect($u[($k="array_search")($n,$z)],$u[$k($o,$z)]);$r[$y][$x]=reset($s);}foreach($t[1]as$e){[$a,$b,$c,$d]=explode(" ",preg_replace("#\s+#"," ",$e));u("┌",$h=min($c,$d),$f=min($a,$b));u("┐",$h,$g=max($a,$b));u("└",$i=max($c,$d),$f);u("┘",$i,$g);foreach(($l="array_slice")(range($f,$g),1,-1)as$x){u("─",$h,$x);u("─",$i,$x);}foreach($l(range($h,$i),1,-1)as$y){u("│",$y,$f);u("│",$y,$g);}}foreach($r as$v)echo join($v)."\n";

-6 Bytes for use "array_fill","array_search", "array_slice" without "

+19 Bytes echo ltrim(rtrim(join($v))."\n","\n"); instead of echo join($v)."\n"; to print only the necessary Chars

Online Version

Expanded

preg_match_all("#(\d+(\s+\d+){3})#s",$_GET[0],$t); # find all rects
$r=($w="array_fill")(1,25,$w(1,80," ")); # fill a empty 2 D array with spaces
function u($n,$y,$x){ # Char , Y Coordinate, X Coordinate as parameter
global$r; # result array must be global to make changes
# The following array based on Set Theory
$u=[
$z=[" ","│",$c="┤","┐","└",$d="┴",$e="┬",$b="├","─","┘","┌",$a="┼"],
["│",$c,$b,$a],
[$c,$a],
["┐",$c,$e,$a],
["└",$d,$b,$a],
[$d,$a],
[$e,$a],
[$b,$a],
["─",$d,$e,$a],
["┘",$c,$d,$a],
["┌",$e,$b,$a]
,[$a]];
$o=$r[$y][$x]; # old value for YX
$s=array_intersect($u[($k="array_search")($n,$z)],$u[$k($o,$z)]); # make the Cut quantity
$r[$y][$x]=reset($s); # Take the first value Cut quantity and set it as new value
}
foreach($t[1]as$e){ # for each rect
[$a,$b,$c,$d]=explode(" ",preg_replace("#\s+#"," ",$e)); #split the four coordinates
# next 4 rows make edges and set minimum and maximum for X an Y values
u("┌",$h=min($c,$d),$f=min($a,$b));
u("┐",$h,$g=max($a,$b));
u("└",$i=max($c,$d),$f);
u("┘",$i,$g);
foreach(($l="array_slice")(range($f,$g),1,-1)as$x){u("─",$h,$x);u("─",$i,$x);} # make the X lines
foreach($l(range($h,$i),1,-1)as$y){u("│",$y,$f);u("│",$y,$g);} # make the  Y lines
}
foreach($r as$v)echo join($v)."\n"; # Output

Order of the array Set Theory

foreach($u as $k0=>$v0)
foreach($u as $k1=>$v1)
echo "\n\n'".$z[$k0]."' + '".$z[$k1]."' = '". join("','",array_intersect($v0,$v1))."'";

Examples Set Theory all possible values

The array without the use of variables to short it

$u=[
$z=[" ","│","┤","┐","└","┴","┬","├","─","┘","┌","┼"],
["│","┤","├","┼"],
["┤","┼",],
["┐","┤","┬","┼"],
["└","┴","├","┼"],
["┴","┼"],
["┬","┼"],
["├","┼"],
["─","┴","┬","┼"],
["┘","┤","┴","┼"],
["┌","┬","├","┼"]
,["┼"]];');


Numerical Integration through Plotting Inspired by this on Spiked Math:

(source: spikedmath.com)

In this code golf, you are going to write a numerical integrator. Instead of weighting, you first plot on a graphic canvas pixel-by-pixel or plot on a 2D array, then calculate the integral by counting the colored pixels.

You are implementing a function with the following arguments:

f: the function, in lambda or function pointer
xmin, xmax: the interval, also the familiar window settings on a typical graphic calculator
ymin, ymax: window settings for y-axis, note: it is the caller's responsibility to choose ymax, because the function can go over ymax, and the parts went over will not be counted.
xres, yres: resolution of the plot: size of the canvas or the dimensions of the 2D array

Here is an explanation:

To integrate sin(x) from 1.0 to 8.0 with y = -1.0 to 1.0, and resolution 30 * 15, first plot

 ++++                       ++
++++++                     +++
+++++++                   ++++
++++++++                 +++++
++++++++                 +++++
+++++++++               ++++++
+++++++++              +++++++
          -------------
           -----------
           -----------
            ---------
            --------
             -------
              -----

Count the total number of +s: 83
total number of -s: 64
and N = 83 - 64 = 19

(the formula for N is actually

notice xres-1, x never equal to xres, don't make this off-by-one error
)

and calculate the integral:

N / canvas size * window area
= (N / (xres * yres) ) * ((ymax - ymin) * (xmax - xmin))
= 19 / (30 * 15) * ((1 - (-1)) * (8 - 1))
~= 0.5911

Shortest code wins.

Test cases:

| f(x)       |  xmin |  xmax |  ymin | ymax  | xres | yres | S f(x) dx |
| 3          |  0.0  |  10.0 |   0.0 |   2.0 |   25 |   25 |  20.0     |
| 3          |  0.0  |  10.0 |   0.0 |   5.0 |    5 |    5 |  30.0     |
| 3          |  0.0  |  10.0 |   0.0 |   4.0 |    5 |    5 |  32.0     |
| 2x + 2     | -5.0  |   5.0 | -10.0 |  10.0 |   50 |   50 |  18.72    |
| 2x + 2     | -5.0  |   5.0 | -20.0 |  20.0 |  500 |  500 |  20.1648  |
| x^2        |  0.0  |  10.0 |   0.0 | 120.0 |   10 |   10 | 348.0     |
| x^2        |  0.0  |  10.0 |   0.0 | 120.0 |  100 |  100 | 335.88    |
| x^2        |  0.0  |  10.0 |   0.0 | 120.0 |  500 |  500 | 333.6768  |
| x^2 sin(x) | -3.14 |  3.14 |  -5.0 |   5.0 |   50 |   50 |   0.60288 |
| x^2 sin(x) | -3.14 |  3.14 |  -5.0 |   5.0 | 1500 | 1500 |   0.60288 |
| sin(x^2)   |  0.0  | 10.0  |  -1.0 |   1.0 |  250 |   50 |   0.7808  |
| sin(x^2)   |  0.0  | 10.0  |  -1.0 |   1.0 | 1000 | 1000 |   0.59628 |

Lua, 219 chars

Done it all in 1 step, no need for an intermediate table. Plots the function too ;)

function I(f,x,X,y,Y,r,R)I=io.write N=0 for k=R-1,0,-1 do for l=0,r-1 do v=f(x+l*(X-x)/r) K=y+k*(Y-y)/R c=(K<0 and K>v)and'-'or(K>0 and K<v and'+')or' 'N=c=="+"and N+1 or(c=="-"and N-1 or N)I(c)end I'\n'end return N end

Test code:

assert(I(math.sin,1.0,8.0,-1,1,30,15)==19)


Compute the runs of a string Consider the following definitions taken from The number of runs in a string by W. Rytter.  Note that word, string and substring are all roughly synonyms.

  A run in a string is a nonextendable (with the same minimal period)
  periodic segment in a string.

  A period p of a word w is any positive integer p such that w[i]=w[i+p]
  whenever both sides of this equation are defined. Let per(w) denote
  the size of the smallest period of w . We say that a word w is
  periodic iff per(w) <= |w|/2.

For, example consider the string x = abcab. per(abcab) = 3 as x[1] = x[1+3] = a, x[2]=x[2+3] = b and there is no smaller period. The string abcab is therefore not periodic.  However, the string abab is periodic as per(abab) = 2.

A run (or maximal periodicity) in a string w is an interval [i...j] with j>=i, such that

w[i...j] is a periodic word with the period p = per(w[i...j])
It is maximal. Formally, neither w[i-1] = w[i-1+p] nor w[j+1] = w[j+1-p].  Informally, the run cannot be contained in a larger run with the same period.

Denote by RUNS(w) the set of runs of w.

Examples

The four runs of atattatt are [4,5] = tt, [7,8] = tt, [1,4] = atat, [2,8] = tattatt.

The string aabaabaaaacaacac contains the following 7 runs:

[1,2] = aa, [4,5] = aa, [7,10] = aaaa, [12,13] = aa, [13,16] = acac, [1,8] = aabaabaa, [9,15] = aacaaca.

Your output should be a list of runs. Each run should specify the interval it represents but does not need to output the substring itself. The exact formatting can be whatever is convenient for you.

The examples use 1-indexing but you are free to use 0-indexing instead if it is more convenient.

TASK

Write code that given a string w, output RUNS(w).

Languages and input

You can use any language you like and take the input string in whatever form is most convenient.  You must give a full program however and you should show an example of your code running on the example input.

Pyth, 38 bytes

{smm,hk+ekdfgaFTdcx1xM.ttB+0qVQ>QdZ2Sl

  m                                 SlQ   map for d in [1, …, len(input)]:
                            qVQ>Qd          pairwise equality of input[:-d] and input[d:]
                        tB+0                duplicate this list, prepending 0 to one copy
                      .t          Z         transpose, padding with 0
                    xM                      pairwise xor
                  x1                        find all occurrences of 1
                 c                 2        chop into groups of 2
           f                                filter for groups T such that:
             aFT                              the absolute difference between its elements
            g   d                             is greater than or equal to d
   m                                        map for groups k:
     hk                                       first element
    ,  +ekd                                   pair with the last element plus d
 s                                        concatenate
}                                         deduplicate

Test suite


Play scrabble with the periodic table You've got a set of tiles with the symbols from the periodic table. Each symbol appears once. You're thinking up words to make but you want to know if it's possible or not.

The Challenge

Write a program in your favourite language that will take in a string as an input parameter. You may assume that input is not null, has no spaces and consists of ASCII characters.

Your program should take that string and output a truthy value if that word can made up of symbols from the periodic table of elements, and a falsey value if the word cannot.

To make this challenge more difficult, you may not use a symbol twice. So if you use Nitrogen N you may not use N again in the same word.

Rules

Standard loopholes are not allowed. You may use symbols from elements 1-118 (Hydrogen to Ununoctium). You can find a list of all the elements here. You may read the list of symbols in from a file or input arguments if you wish.

Test Cases:

Laos - true (LaOs)
Amputation - true (AmPuTaTiON)
Heinous - true (HeINoUS)
Hypothalamus - true (HYPoThAlAmUS)
Singapore - true (SiNGaPoRe)
Brainfuck - true (BRaInFUCK)
Candycane - false

This is a code golf challenge, shortest code wins.

BEFORE YOU CLOSE AS DUPLICATE: While this may seem similar to this challenge, I feel it is different because it is not 'Generate a list of all words that are possible from the periodic table', it is 'Take in arbitrary input and determine if it can be made from the periodic table'

05AB1E, 16 bytes
œvyŒ€J})˜Ùvy²Q}O

Explained
œv                # for each permutation of the list of elements
  yŒ              # get all sublist of elements
    €J            # join as strings to form the words possible to spell
      })˜Ù        # convert to list of unique spellable strings
          vy²Q}   # compare each word with input word
               O  # sum giving 1 if the word is found, else 0

Warning: Extremely slow. I recommend testing on a much smaller subset of elements in the online interpreter.
Takes list of elements as first argument.
Takes word to test as second argument.
Returns 1 for true and 0 for false.
Try it online on a small subset of elements


Extend the most recent "nice" OEIS sequence: stepping stone puzzle on a grid Today Neil Sloane of the OEIS sent out an email asking for a confirmation of the current terms, and computation of some larger terms of the latest OEIS sequence A337663 with the keyword "nice".
Here's how this sequence works:
You label \$n\$ cells on the infinite square grid with \$1\$s, and then

place the numbers \$2,3,4,\dots,m\$ in order, subject to the rule that when you place \$k\$, the sum of its [horizontal, vertical, and diagonal] neighbors must equal \$k\$. Then \$A337663(n)\$ is the maximum \$m\$ that can be achieved over all initial placings of the \$1\$-cells.

Here's an illustration of \$A337663(2) = 16\$:
+----+----+----+----+----+----+
|  9 |  5 | 10 | 11 |    |    |
+----+----+----+----+----+----+
|    |  4 |  1 |    |    |    |
+----+----+----+----+----+----+
| 12 |  8 |  3 |  2 |    | 16 |
+----+----+----+----+----+----+
|    |    |    |  6 |  1 | 15 |
+----+----+----+----+----+----+
|    |    | 13 |  7 | 14 |    |
+----+----+----+----+----+----+

Notice that the \$2\$-cell has two \$1\$-cells as neighbors (and \$1 + 1 = 2\$); the \$3\$-cell has a \$1\$-cell and a \$2\$-cell as neighbors (and \$1 + 2 = 3\$); etc.
The challenge.
Like this previous challenge, the goal of this code-challenge is to compute as many terms as possible in this sequence, which begins 1, 16, 28, 38 and where the \$n\$-th term is \$A337663(n)\$.
Run your code for as long as you'd like. The winner of this challenge will be the user who posts the most terms of the sequence, along with their code to generate it. If two users post the same number of terms, then whoever posts their last term earliest wins.

C + OpenMP, N=5
New version with a proper handling of the 112-1113 case.
a(5) = 49
 0 46 26  0  0  0  0  0  0  0  0 35  0

 0 20  0  6 28 48  0  0  0  0 34  1 36

39 19  1  2  3 17  0 30  0  0 33  0 37

 0  0 18  7  1  4  9  0 21 32  0  0  0

 0 40  0  8 38  5 43 10 11  0 44  0  0

 0  0 22  0 13  0 15  0  1 12  0  0  0

47 23  0 14 27  0 31 16 29  0  0  0  0

 0 24  1  0 41  0  0  0 45  0  0  0  0

49 25  0 42  0  0  0  0  0  0  0  0  0

How it works
The program will only work for N=5, for higher numbers you'd need some adjustments. First lets take a look how an easier approach for N=4 would look like. We need at least 112 next to each other in some arrangement. Because there are only two 1s left, every other number cannot be made only by new 1s.
So starting from the six possible starting positions for 112:
1 1   1 2 1   1 _ 1   1 _   1 _ _   1 _ _
2 _           _ 2 _   2 1   _ 2 1   _ 2 _
                                    _ _ 1

we can take a look at every space placed two spots away and check their sum (Note: with some proper case handling, you should be fine to check the direct neighbors, though I took the safe route).
      0 0 0 0 0 0
      0 1 2 2 1 0

1 1 -> 0 3 . . 1 0
2 _    0 3 . 4 1 0
0 2 2 2 0 0
0 0 0 0 0 0
For every spot: check if the sum is the next needed number (in this case 3) or if we can still place some 1s: is the sum plus some newly added 1s the next needed number. In the latter case, we need to make sure that the new 1s don't interfere with existing numbers > 1, e.g.
3 1
1 1 1
  2

wouldn't be valid as the 2-placement would have been illegal, but
1 1
2   3 1
    1

would be fine. Note that I only increase the bounding box for two spots around non-1 numbers. So for the lower right corner, the next spots to try are as following:
1 _ _ _
_ 3 1 _
_ 1 _ _
_ _ _ _
  x

The x spot wouldn't get checked, as its number would only neighbor new 1s – and for N=4 this is not possible as mentioned before.
For N>4 this get a little more complicated: it is not guaranteed that every number will be connected to the first 112. Another cluster might start independently: 1113. But after that every number cannot be made only of new 1s, thus will be connected to either 1113 or 112. Note that we don't have to handle anything else in the N=5 case (but would need for N>5): having two clusters with 1 and 11114 will already be handled, as 2 and 3 must also be placed in 11114; so every 11114 will already be checked by 112 or 1113.
So we need to get a bounding box to find out how close 112 and 1113 can be placed. For this we run two boards that cannot touch, scoring them by the sum of the distances they managed to get away from the starting position. This is the best they manage:
  0  0  0  0  0  0  0  0  0

  0  0  0  0  0  0  0  0  0

  0  0  0  0 15  0  0  0  0

  0  0 11 10  5  0  0  0  0

  0  0  0  1  4 12  0  0  0

  0  0  0  0  2  1 13  0  0

  0  0  0  0  0  0 14  0  0

  0  0  0  0  0  0  0  0  0

  0  0  0  0  0  0  0  0  0

  …

  0  0  0  0  0  0  0  0

  0  0  0  0  0  0  0  0

  0  0 17  9  0  3  1  0

  0  0  0  8  1  6  1  0

  0  0  0 16  7  0  0  0

  0  0  0  0  0  0  0  0

  0  0  0  0  0  0  0  0

They cannot leave 5 tiles. So if we place the initial 3 within a 20x20 (+ a padding of 4 for off-by-one-errors :-)) field centered around the 2, we either get two disconnected clusters that have a score independent on where they are exactly, or two clusters that eventually will join up. So anything up to
1 1 _ _ _ _ _ _ _ _ _ _ _ 1 1
_ 2 a b c d e _ e d c b a 3 1

will be checked with 11 spaces in between; enough that they cannot meet up.
With all this, then just recursively try out all the possibilities in a depth-first-search. Always modifying only one board, we only need memory for a(N) recursive steps.
OMP is only used to check the initial boards in parallel. This is far from a balanced workload; the final position needs about twice as long as the others. However, it is the easiest to implement. :-)
The program
Compiled with clang -O3 -o main main.c -fopenmp and ran with time OMP_NUM_THREADS=4 ./main.
#include <stdint.h>
#include <stddef.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

typedef uint8_t mem_t;
typedef uint16_t sum_t;
#define S 64
const int startx = S/2, starty = S/2;
// for N > 5, adjust the unrolled loops in step
#define MAX_CELL 5
#define MAX_BOARDS 2

#define MAX(x,y) (x>y?x:y)
#define MIN(x,y) (x<y?x:y)

const int ys[8] = {0,1,1,1,0,-1,-1,-1};
const int xs[8] = {1,1,0,-1,-1,-1,0,1};

inline
void add_sum(sum_t v, int y, int x, sum_t sum[S][S]) {
    for(int d=0;d<8;d++)
        sum[y+ys[d]][x+xs[d]] += v;
}
inline
void add_placed(sum_t v, int y, int x, mem_t placed[S][S]) {
    for(int d=0;d<8;d++)
        placed[y+ys[d]][x+xs[d]] += v;
}

typedef struct board {
  int y0, y1, x0, x1;
  mem_t b[S][S], placed[S][S];
  sum_t sum[S][S];
} board_t;

void st_print(int c, int max, board_t *b) {
    printf("%d cells, %d max\n", c, max);
    for(int y=b->y0;y<=b->y1;y++){
        for(int x=b->x0;x<=b->x1;x++) printf("%*d", 3, b->b[y][x]);
        puts("\n");
    }
}

void step(int c, mem_t max, board_t *bs, int bl, mem_t *best_max, board_t best_b[MAX_BOARDS], int optimize_spread) {
    // check board size
    for(int i=0;i<bl;i++) {
            if (bs[i].y0 < 2 || bs[i].y1 >= S - 2 || bs[i].x0 < 2 || bs[i].x1 >= S - 2) {
                    st_print(c, max, &bs[i]);
                printf("board too small %d %d %d %d", bs[i].y0, bs[i].y1, bs[i].x0, bs[i].x1);
                exit(1);
            }
    }
    // new best
    if (c == MAX_CELL) {
        int score = 0;
            if (optimize_spread) {
                    for (int i=0;i<bl;i++)
                        score += MAX(starty - bs[i].y0,
                                 MAX(bs[i].y1 - starty,
                                 MAX(startx - bs[i].x0,
                                     bs[i].x1 - startx)));
            } else {
                    score = max;
            }
            if (*best_max < score) {
                for (int i=0;i<bl;i++)
                        memcpy(&best_b[i], &bs[i], sizeof(board_t));
                *best_max = score;
            }
    }
    // place with 0 new 1-cells
    if(!optimize_spread || max != 2)
    for(int i=0;i<bl;i++) {
            board_t *b=bs+i;
            for(int y=b->y0;y<=b->y1;y++)
            for(int x=b->x0;x<=b->x1;x++)
            if(b->sum[y][x] == max + 1 && !b->b[y][x]) {
                b->b[y][x] = max + 1;
                add_sum(max+1,y,x,b->sum);
                add_placed(1,y,x,b->placed);
                int y0o = b->y0, y1o = b->y1, x0o = b->x0, x1o = b->x1;
                b->y0 = MIN(b->y0, y-2);
                b->y1 = MAX(b->y1, y+2);
                b->x0 = MIN(b->x0, x-2);
                b->x1 = MAX(b->x1, x+2);
                step(c, max + 1, bs, bl, best_max, best_b, optimize_spread);
                b->y0 = y0o, b->y1 = y1o, b->x0 = x0o, b->x1 = x1o;
                add_placed(-1,y,x,b->placed);
                add_sum(-(max+1),y,x,b->sum);
                b->b[y][x] = 0;
            }
    }
    // sorry for the repetition, couldn't get clang to optimize it otherwise
    // place with 1 new 1-cells
    if(!optimize_spread || max != 2)
    if(c + 1 <= MAX_CELL)
    for(int i=0;i<bl;i++) {
            board_t *b=bs+i;
            for(int y=b->y0;y<=b->y1;y++)
            for(int x=b->x0;x<=b->x1;x++)
            if(b->sum[y][x] == (max + 1) - 1 && !b->b[y][x]) {
                for(int d1=0;d1<8;d1++) {
                    if (b->placed[y+ys[d1]][x+xs[d1]]) continue;

                    b->b[y+ys[d1]][x+xs[d1]] = 1;
                    b->b[y][x] = max + 1;
                    add_sum(max+1,y,x,b->sum);
                    add_sum(1,y+ys[d1],x+xs[d1],b->sum);
                    add_placed(1,y,x,b->placed);
                        int y0o = b->y0, y1o = b->y1, x0o = b->x0, x1o = b->x1;
                        b->y0 = MIN(b->y0, y-2);
                        b->y1 = MAX(b->y1, y+2);
                        b->x0 = MIN(b->x0, x-2);
                        b->x1 = MAX(b->x1, x+2);
                        step(c + 1, max + 1, bs, bl, best_max, best_b, optimize_spread);
                        b->y0 = y0o, b->y1 = y1o, b->x0 = x0o, b->x1 = x1o;
                    add_placed(-1,y,x,b->placed);
                    add_sum(-(max+1),y,x,b->sum);
                    add_sum(-1,y+ys[d1],x+xs[d1],b->sum);
                    b->b[y+ys[d1]][x+xs[d1]] = 0;
                    b->b[y][x] = 0;
                }
            }
    }
    // place with 2 new 1-cells
    if(!optimize_spread || max != 2)
    if(c + 2 <= MAX_CELL)
    for(int i=0;i<bl;i++) {
            board_t *b=bs+i;
            for(int y=b->y0;y<=b->y1;y++)
            for(int x=b->x0;x<=b->x1;x++)
            if(b->sum[y][x] == (max + 1) - 2 && !b->b[y][x]) {
                for(int d1=0;d1<8-1;d1++) {
                    if (b->placed[y+ys[d1]][x+xs[d1]]) continue;
                for(int d2=d1+1;d2<8;d2++) {
                    if (b->placed[y+ys[d2]][x+xs[d2]]) continue;

                    b->b[y+ys[d1]][x+xs[d1]] = 1;
                    b->b[y+ys[d2]][x+xs[d2]] = 1;
                    b->b[y][x] = max + 1;
                    add_sum(max+1,y,x,b->sum);
                    add_sum(1,y+ys[d1],x+xs[d1],b->sum);
                    add_sum(1,y+ys[d2],x+xs[d2],b->sum);
                    add_placed(1,y,x,b->placed);
                        int y0o = b->y0, y1o = b->y1, x0o = b->x0, x1o = b->x1;
                        b->y0 = MIN(b->y0, y-2);
                        b->y1 = MAX(b->y1, y+2);
                        b->x0 = MIN(b->x0, x-2);
                        b->x1 = MAX(b->x1, x+2);
                        step(c + 2, max + 1, bs, bl, best_max, best_b, optimize_spread);
                        b->y0 = y0o, b->y1 = y1o, b->x0 = x0o, b->x1 = x1o;
                    add_placed(-1,y,x,b->placed);
                    add_sum(-(max+1),y,x,b->sum);
                    add_sum(-1,y+ys[d1],x+xs[d1],b->sum);
                    add_sum(-1,y+ys[d2],x+xs[d2],b->sum);
                    b->b[y+ys[d1]][x+xs[d1]] = 0;
                    b->b[y+ys[d2]][x+xs[d2]] = 0;
                    b->b[y][x] = 0;
                }
                }
            }
    }
    // place with 3 new 1-cells
    if(c + 3 <= MAX_CELL)
    for(int i=(optimize_spread && max == 2);i<bl;i++) {
            board_t *b=bs+i;
            for(int y=b->y0;y<=b->y1;y++)
            for(int x=b->x0;x<=b->x1;x++)
            if(b->sum[y][x] == (max + 1) - 3 && !b->b[y][x]) {
                for(int d1=0;d1<8-2;d1++) {
                    if (b->placed[y+ys[d1]][x+xs[d1]]) continue;
                for(int d2=d1+1;d2<8-1;d2++) {
                    if (b->placed[y+ys[d2]][x+xs[d2]]) continue;
                for(int d3=d2+1;d3<8;d3++) {
                    if (b->placed[y+ys[d3]][x+xs[d3]]) continue;

                    b->b[y+ys[d1]][x+xs[d1]] = 1;
                    b->b[y+ys[d2]][x+xs[d2]] = 1;
                    b->b[y+ys[d3]][x+xs[d3]] = 1;
                    b->b[y][x] = max + 1;
                    add_sum(max+1,y,x,b->sum);
                    add_sum(1,y+ys[d1],x+xs[d1],b->sum);
                    add_sum(1,y+ys[d2],x+xs[d2],b->sum);
                    add_sum(1,y+ys[d3],x+xs[d3],b->sum);
                    add_placed(1,y,x,b->placed);
                        int y0o = b->y0, y1o = b->y1, x0o = b->x0, x1o = b->x1;
                        b->y0 = MIN(b->y0, y-2);
                        b->y1 = MAX(b->y1, y+2);
                        b->x0 = MIN(b->x0, x-2);
                        b->x1 = MAX(b->x1, x+2);
                        step(c + 3, max + 1, bs, bl, best_max, best_b, optimize_spread);
                        b->y0 = y0o, b->y1 = y1o, b->x0 = x0o, b->x1 = x1o;
                    add_placed(-1,y,x,b->placed);
                    add_sum(-(max+1),y,x,b->sum);
                    add_sum(-1,y+ys[d1],x+xs[d1],b->sum);
                    add_sum(-1,y+ys[d2],x+xs[d2],b->sum);
                    add_sum(-1,y+ys[d3],x+xs[d3],b->sum);
                    b->b[y+ys[d1]][x+xs[d1]] = 0;
                    b->b[y+ys[d2]][x+xs[d2]] = 0;
                    b->b[y+ys[d3]][x+xs[d3]] = 0;
                    b->b[y][x] = 0;
                }
                }
                }
            }
    }
}

void set_starting_board(board_t* b, int i) {
    int x0 = startx, y0 = starty;
    b->b[y0][x0] = 2;
    if (i == 0) b->b[y0-1][x0-1] = 1,
                b->b[y0+1][x0+1] = 1;
    if (i == 1) b->b[y0-1][x0-1] = 1,
                b->b[y0][x0+1] = 1;
    if (i == 2) b->b[y0][x0-1] = 1,
                b->b[y0][x0+1] = 1;
    if (i == 3) b->b[y0-1][x0] = 1,
                b->b[y0][x0+1] = 1;
    if (i == 4) b->b[y0-1][x0-1] = 1,
                b->b[y0-1][x0+1] = 1;
    if (i == 5) b->b[y0-1][x0] = 1,
                b->b[y0-1][x0+1] = 1;

    for(int y=1;y+1<S;y++)
    for(int x=1;x+1<S;x++)
    for(int yd=-1;yd<=1;yd++)
    for(int xd=-1;xd<=1;xd++)
    if(yd!=0||xd!=0)
        b->sum[y][x] += b->b[y+yd][x+xd];
    for(int y=1;y+1<S;y++)
    for(int x=1;x+1<S;x++)
    for(int yd=-1;yd<=1;yd++)
    for(int xd=-1;xd<=1;xd++)
        b->placed[y][x] += b->b[y+yd][x+xd] > 1;

}

int get_bounding_box() {
    int x0 = startx, y0 = starty;
    board_t best_b[6][3] = {0};
    mem_t best_max[6] = {0};

 #pragma omp parallel for
    for(int i=0;i<6;i++) {
        board_t bs[] = {(board_t){y0 - 3, y0 + 3, x0 - 3, x0 + 3, {0}, {0}, {0}},
                            (board_t){y0, y0, x0, x0, {0}, {0}, {0}}};
            set_starting_board(&bs[0], i);
        step(2, 2, bs, 2, &best_max[i], best_b[i], 1);
    }

    int best_i=0, mm = 0;
    for(int i=0;i<6;i++)
        if (best_max[i] > mm)
            mm = best_max[i],
            best_i = i;
    printf("most spread of distant 112 and 1113: %d\n", best_max[best_i]);
    st_print(MAX_CELL, best_max[best_i], &best_b[best_i][0]);
    st_print(MAX_CELL, best_max[best_i], &best_b[best_i][1]);

    return best_max[best_i] + 4;
}

int main(int argc, char **argv) {
    int bb = get_bounding_box();

    int x0 = startx, y0 = starty;
    board_t best_b[6][3] = {0};
    mem_t best_max[6] = {0};

 #pragma omp parallel for
    for(int i=0;i<6;i++) {
        board_t bs[] = {(board_t){y0 - bb, y0 + bb, x0 - bb, x0 + bb, {0}, {0}, {0}},};
            set_starting_board(&bs[0], i);
        step(2, 2, bs, 1, &best_max[i], best_b[i], 0);
    }

    int best_i=0, mm = 0;
    for(int i=0;i<6;i++)
        if (best_max[i] > mm)
            mm = best_max[i],
            best_i = i;
    st_print(MAX_CELL, best_max[best_i], &best_b[best_i][0]);

    return 0;
};


Crossword Compulsions! Chris, a cryptic crosswords addict, has a set algorithm for the order in which he solves them.

We will use the above image as a guide.

Chris always starts off with the first across clue, in this case 1 Across. Chris is a capable crossword enthusiast, so it is assumed that he will always know the answer to the clue he is working on.
Once Chris completes a clue, he will check for all clues adjoining those he has completed (in the first case, 1 Down, 2 Down and 3 Down) and then complete the clue with the lowest number. If there are no adjoining clues, he would go to step 3.
If the clue is such that the next number (as described in Step 3) has both an across clue and a down clue, he will complete the across clue first (100% certainty, this borders on OCD!)
If there are no adjoining clues, he will go to the next available clue that's next in number (across or down)
Repeat from Step 2 until all clues are completed.

And this is where it comes down to you, dear coders. You have been tasked to create code that can, on being provided with a crossword template, provide output describing the order of clues based on Chris's algorithm for solving it.

The code will accept input of a crossword puzzle template, in the form of a . representing a white square and a # representing a black square.

Example:

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

Input can be through: a) a file read of the representation of the crossword, or b) by line input of each line of the crossword, followed by \n, with a second \n indicating EOF.

And then it will determine the method by which Chris would solve it according to the above algorithm he has described.

Output must be in the format of a series of comma separated instructions in the form of n(A|D), where n is the clue number followed by A for across or D for down.

So in the example above (both from the image, and the example template, which are the one and the same), the output would be:

1A,1D,2D,3D,9A,10A,4D,5D,6D,7D,8D,11A,12A,13A,15A,14D,15D,16A,17A,18D,19D,20A,21D,23A,22D,24A,25D,27A,28A,26D,29A,30A,31A

Shortest code wins...

Testing

You must provide with your submission the code, a byte count, as well as one of the four test cases represented in the . and # format, as well as the output generated from this input. There are four test cases, the three below as well as the above example template.

Example test cases:

Test Case 1

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

Output: 1A,1D,2D,3D,4A,5A,6A,7A

Test Case 2

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

Output: 1A,1D,2D,5A,4D,4A,3D,3A,7A,8A,6D,9A

Test Case 3

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

Output: 1A,2D,3D,4D,5D,7A,8A,9A,10A,11A,11D,12A,13A,6D,14D,15A,16A,17A

Test Case 4

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

Output: 1A,1D,2D,3D,9A,10A,4D,4A,5D,6D,7D,8D,11A,12A,13A,15A,14D,15D,16A,17A,18D,19D,20A,21D,23A,22D,24A,25D,27A,28A,26D,29A,30A,31A

Good luck!


Howdy! I'm the sheriff of code golf! It's likely that anyone who used Twitter a couple of months ago would know about the 'Howdy! I'm the sheriff of X" meme. Where a simple image of a sheriff is drawn with emoji, and changes to fit a theme. So I thought it was time for the Sheriff of Code Golf. Here he is:

    ###
   #####
    ###
    ###
    ###
     #
   #####
  #  #  #
 #   #   #
 #   #   #
     #
    ###
   #   #
   #   #
   #   #
   #   #

This one in particular has 'pixels' which are one character wide, and one character high. To generate him, the arguments will be 1 and 1.

What if he is to be wider than he is tall?

      ######
    ##########
      ######
      ######
      ######
        ##
    ##########
  ##    ##    ##
##      ##      ##
##      ##      ##
        ##
      ######
    ##      ##
    ##      ##
    ##      ##
    ##      ##

He's got a height of 1, but a width of 2.

Rules:

The challenge is to write code to draw your own Sheriff of Code Golf, in the fewest characters possible.
Use any programming language your heart desires.
Your code should take two arguments, both of which are integers, for the height and width of the Sheriff.
The output should be composed of single white spaces for the background, and any other character(s) you choose for the Sheriff. (I've used hashes for the test cases, but it doesn't matter what you use).
It should be possible for the height to be a negative integer, inverting the image.
The width can be a negative integer, but because the image is symmetrical, it will be identical to it's positive value.
Trailing white-spaces are irrelevant.
If either argument is 0, that dimension is 'flattened' to a single row or column. The length of this line is the other argument multiplied by the height, or width of the Sheriff, respectively.
If both arguments are 0, both lines are 'flattened', leaving a single positive character.
Not essential, but please include a link to an online interpreter such as tio.run
The output should be a string, over multiple lines, or output to the console.

Test Cases

1 high, 1 wide

    ###
   #####
    ###
    ###
    ###
     #
   #####
  #  #  #
 #   #   #
 #   #   #
     #
    ###
   #   #
   #   #
   #   #
   #   #

2 high, 1 wide

    ###
    ###
   #####
   #####
    ###
    ###
    ###
    ###
    ###
    ###
     #
     #
   #####
   #####
  #  #  #
  #  #  #
 #   #   #
 #   #   #
 #   #   #
 #   #   #
     #
     #
    ###
    ###
   #   #
   #   #
   #   #
   #   #
   #   #
   #   #
   #   #
   #   #

1 high, 2 wide

      ######
    ##########
      ######
      ######
      ######
        ##
    ##########
  ##    ##    ##
##      ##      ##
##      ##      ##
        ##
      ######
    ##      ##
    ##      ##
    ##      ##
    ##      ##

2 high, 2 wide

      ######
      ######
    ##########
    ##########
      ######
      ######
      ######
      ######
      ######
      ######
        ##
        ##
    ##########
    ##########
  ##    ##    ##
  ##    ##    ##
##      ##      ##
##      ##      ##
##      ##      ##
##      ##      ##
        ##
        ##
      ######
      ######
    ##      ##
    ##      ##
    ##      ##
    ##      ##
    ##      ##
    ##      ##
    ##      ##
    ##      ##

-1 high, 1 wide

   #   #
   #   #
   #   #
   #   #
    ###
     #
 #   #   #
 #   #   #
  #  #  #
   #####
     #
    ###
    ###
    ###
   #####
    ###

1 high, -1 wide

    ###
   #####
    ###
    ###
    ###
     #
   #####
  #  #  #
 #   #   #
 #   #   #
     #
    ###
   #   #
   #   #
   #   #
   #   #

0 high, 0 wide

#

1 high, 0 wide

#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#

0 high, 2 wide

##################

Have fun, y'all!

JavaScript (ES6), 171 bytes

Takes input in currying syntax (width)(height). Returns an array of strings.

w=>h=>[...Array((h>0?h:-h)*16||1)].map((_,y)=>'012345678'.replace(/./g,x=>' #'[((c=+'3733317900134444'[(h<0?16-~y/h:y/h)|0]||17)>>4-x|c>>x-4)&1|!h].repeat(w>0?w:-w))||'#')

Try it online!

How?

Only the left half of the sheriff is encoded as binary bitmasks, including the middle column:

    ##.         00011     3
   ###..        00111     7
    ##.         00011     3
    ##.         00011     3
    ##.         00011     3
     #          00001     1
   ###..        00111     7
  #  #  .       01001     9
 #   #   .  --> 10001 --> 17
 #   #   .      10001     17
     #          00001     1
    ##.         00011     3
   #   .        00100     4
   #   .        00100     4
   #   .        00100     4
   #   .        00100     4

Because there are only two values greater than \$9\$ and they're both equal to \$17\$, we can replace them with \$0\$ in order to have one character per row and still have a rather straightforward decoding process. Hence the packed string:

'3733317900134444'

For \$0 \le x \le 8\$ and \$0 \le y \le 15\$, the 'pixel' at \$(x,y)\$ is given by:

' #'[                                  // character lookup:
  (                                    //   0 = space
    (                                  //   1 = '#'
      c = +'3733317900134444'[y] || 17 // extract the bitmask for this row; 0 -> 17
    )   >> 4 - x                       // test the left part, middle column included
    | c >> x - 4                       // test the right part, middle column also included
  ) & 1                                // isolate the least significant bit
]                                      // end of character lookup


Write a program that turns every 17th bit of a text file to a 1 My coworker and I work on a legacy piece of software that we hate sometimes.
Whenever you run it, debug asserts come flying everywhere, and it's never a guarantee that anything will work. The motivation for this round of code golf came from my coworker saying the following about our software.

"It's like every time you run this program, you're agreeing to some terms of service that says every 17th bit on your hard drive will be turned into a 1"

Goal: Write a program that will make an exact copy of a file and turn every 17th bit of a text file into a 1

You may NOT turn EVERY bit of the file to a 1. i.e. your program must show some intelligence that it is only targeting every 17th bit
You may NOT write to the original file in any way shape or form
The Winner is the smallest program submission at the end of the month

Have fun with this one! Go!

CJam, 22 bytes

q256b2H#b1f|2H#b256b:c

Try it online.

Touches every 17th bit, counting from the last.

I've used STDIN and STDOUT since CJam has no file I/O. If that's not allowed, the program can be wrapped in a Bash script at the cost of 24 extra bytes:

cjam <(echo q256b2H#b1f\|2H#b256b:c)<"$1">"$2"

How it works

q                      " Read from STDIN.                                                 ";
 256b                  " Convert to integer by considering the input a base 256 number.   ";
     2H#b              " Convert to array by considering the integer a base 2**17 number. ";
         1f|           " Set the LSB of every integer in the array element to 1.          ";
            2H#b       " Convert to integer by considering the array a base 2**17 number. ";
                256b   " Convert to array by considering the integer a base 256 number.   ";
                    :c " Turn character codes into characters.                            ";


Slices of triangular alphabets Given an input number n from 1 to 26 (or 0 to 25), output the alphabet reading left-to-right up to and including that corresponding letter, with a=1, b=2, c=3, .... The twist is the letters must also be repeated vertically corresponding to their position in the alphabet. Odd numbers (when 1-indexed) should be balanced across the horizontal line, while even numbers should alternate between favoring the top or bottom (you can choose which direction to go first). If you're 0-indexing, then swap odd/even in the previous sentence.

Worded another way -- if the alphabetical value of a letter ? is #, then there should be # copies of that letter in the output, all of them in the #th column. These letters should be evenly balanced above and below the horizontal line that has the a. If the letters cannot be balanced evenly, then alternate having the "extra" letter above and below that line.

Here are the first six outputs (n = 1,2,3,4,5,6, 1-indexed, choosing to alternate to the bottom first), separated by newlines, so you can see the pattern. Comments explaining the pattern start with #.

a         # On a line by itself

ab
 b        # The "extra" letter is below the horizontal

  c
abc       # The 'c' splits evenly
 bc

   d      # Because the 'b' was below, the extra 'd' must be above
  cd
abcd
 bcd

   de
  cde
abcde     # The 'e' balances
 bcde
    e

   def
  cdef
abcdef
 bcdef
    ef
     f    # Since the 'd' was above, the extra 'f' must be below

(skip a few to n=26)

                       xyz
                      wxyz
                   tuvwxyz
                  stuvwxyz
               pqrstuvwxyz
              opqrstuvwxyz
           lmnopqrstuvwxyz
          klmnopqrstuvwxyz
       hijklmnopqrstuvwxyz
      ghijklmnopqrstuvwxyz
   defghijklmnopqrstuvwxyz
  cdefghijklmnopqrstuvwxyz
abcdefghijklmnopqrstuvwxyz
 bcdefghijklmnopqrstuvwxyz
    efghijklmnopqrstuvwxyz
     fghijklmnopqrstuvwxyz
        ijklmnopqrstuvwxyz
         jklmnopqrstuvwxyz
            mnopqrstuvwxyz
             nopqrstuvwxyz
                qrstuvwxyz
                 rstuvwxyz
                    uvwxyz
                     vwxyz
                        yz
                         z

Rules

You can choose to output in uppercase or lowercase, but it must be consistent.
The output cannot have extraneous whitespace, except for an optional trailing newline.
Either a full program or a function are acceptable.
The input number can be taken via any suitable format.
Standard loopholes are forbidden.
This is code-golf so all usual golfing rules apply, and the shortest code (in bytes) wins.

Python 2, 101 99 bytes

r=range(input())
for x in sorted(r,key=lambda x:x*-(x&2)):print bytearray([97+i,32][i<x]for i in r)

xsot saved two bytes by realizing x*-(x&2) suffices as a sorting key — the bottom half of the resulting image is unaffected due to sorted guaranteeing a stable sort.


Two-way Palindromic Closure Generator Introduction
A palindromic closure of an input string is the shortest palindrome that can be constructed out of the input string where the final palindrome starts with the input string.
For this challenge, we will consider a two-way palindromic closure such that

Left Palindromic Closure of an input string is the shortest palindrome possible that starts with the input string.
Right Palindromic Closure of an input string is the shortest palindrome possible that ends with the input string.
Two-way Palindromic Closure of an input string is the shorter of either of Left or Right Palindromic Closure of the input string.

Task
Your task is simple. Given a string (consisting only of printable ASCII, new lines and white spaces), output the two-way palindromic closure of that string. In case of tie, either of the left or right palindromic closures are valid output.
You may write a program or function, taking input via STDIN (or closest alternative), command-line argument or function argument, and either printing the result to STDOUT (or closest alternative) or returning it as a string.
You can assume that the input will never be an empty string.
Few examples:
<Input>   -> <Output>
"abcdef"  -> "abcdefedcba"  (or "fedcbabcdef")
"abcba"   -> "abcba"
"abcb"    -> "abcba"
"cbca"    -> "acbca"

Initial Idea credit goes to VisualMelon, final idea with help from Martin and Zgarb
The terms palindromic closure, left-pallindromic closure and right-palindromic closure were first used and defined by this paper.

Pyth, 22 19

hfq_TTsm,+z_d+_dzyz

Try it online.

Explanation

The two-way palindromic closure is either of the form AX or XA, where X is the input string and A is a substring of X. I actually has to be a contiguous substring of X, a prefix for the one form, a suffix for the other form. But I don't care about these defails. A substring (contiguous or not) is all I need in Pyth.

                        Implicit: z = raw_input() // Read a string
                 yz     A list with all substrings (contiguous or not) of z
       m                For each of these substrings d, build
        ,                  a pair of two strings:
         +z_d              ( z + inveres(d) ,
             +_dz            inverse(d) + z )
      s                 Sum (put all created pairs into a list)
 fq_TT                  filter elements T, where inverse(T) == T (Palindrom)
h                          Take the first element

Edit

The old version ordered the the strings after filtering by length .olN.... Just realized, that y returns the substrings ordered by length. So these palindromes are already sorted.


Convert a decimal to a fraction, approximately Take the decimal number \$0.70710678\$. As a fraction, it'd be \$\frac{70710678}{100000000}\$, which simplifies to \$\frac{35355339}{50000000}\$. If you were to make the denominator \$1\$, the closest fraction is \$\frac{1}{1}\$. With \$2\$, it'd be \$\frac{1}{2}\$, and with \$3\$ it's \$\frac{2}{3}\$. Because \$0.\bar{6}\$ is closer to \$0.70710678\$ than \$\frac{3}{4}\$ or \$\frac{4}{5}\$, it would still be the closest with a maximum denominator up to (and including) \$6\$.
Task
There are two inputs: a decimal, and a maximum denominator.
The first input consists of a number \$n\$ as input, where \$0\le n<1\$, and the fractional part is represented with a decimal (although not necessarily using base 10). This can be represented as a floating point number, an integer representing a multiple of \$10^{-8}\$ (or some other sufficiently smaller number), a string representation of the number, or any other reasonable format.
The second input is an integer \$n\ge1\$, also taken in any reasonable format.
The output should be a fraction, with a denominator \$d\le n\$, where \$n\$ is the second input. This should be the closest fraction to the inputted decimal that is possible with the restrictions placed on the denominator. If there are multiple which are equally close (or equal to the inputted number), the one with the smallest denominator should be chosen. If there are two with the same denominator which are equidistant, either are acceptable.
The outputted fraction can be represented in any reasonable format, as long as it consists of a numerator and denominator, both being natural numbers.
Test cases
0.7         4   ->   2 / 3
0.25285     15  ->   1 / 4
0.1         10  ->   1 / 10
0.1         5   ->   0 / 1
0.68888889  60  ->  31 / 45
0.68888889  30  ->  20 / 29
0.0         2   ->   0 / 1
0.99999999  99  ->   1 / 1

Other
This is code-golf, shortest answer in bytes per language wins!

Scratch 3.0, 45 blocks/254 bytes

As SB Syntax:
define(n)(d)
set[A v]to(0
set[D v]to(d
set[i v]to(0
repeat((n)+(1
set[j v]to(0
repeat((n)+(1
set[r v]to((i)/(j
if<(D)>([abs v]of((r)-(D)))>then
set[A v]to(join(i)(join(/)(j
set[D v]to([abs v]of((r)-(D
end
set[j v]to((j)+(1
end
set[i v]to((i)+(1
end
say(A

Try it on Scratch!
Just wouldn't be right if I didn't do this in Scratch.
Explained
define(n)(d) // Define an empty name function with parameters `n` (the denominator) and `d` (the decimal to fractionify)
set[D v]to(d // This will store the current absolute difference between potential fraction and actual decimal
set[i v]to(0 // outer-cartesian-loop variable
repeat((n)+(1
set[j v]to(0 // inner-cartesian-loop variable
repeat((n)+(1 // simulate cartesian product of range(0, n+1) and range(0, n+1)
set[r v]to((i)/(j // divide i / j
if<(D)>([abs v]of((r)-(D)))>then // if the difference between (i/j) and d is smaller than the current smallest difference
set[A v]to(join(i)(join(/)(j // update answer and difference
set[D v]to([abs v]of((r)-(D
end
set[j v]to((j)+(1
end
set[i v]to((i)+(1
end
say(A // output answer


Triangles with rational side lengths This challenge will have give you a positive integer \$n\$ and ask you to output \$t(n)\$, the number of triangles (up to congruence) satisfying the three conditions:

The triangles have perimeter of 1,
the triangles have side lengths \$\displaystyle\frac{a_1}{b_1}, \frac{a_2}{b_2}\$, and \$\displaystyle\frac{a_3}{b_3}\$, and
when written in lowest terms, \$\max \{b_1, b_2, b_3\} = n\$.

Examples
For \$n = 2\$, there are no such triangles, so \$t(2) = 0\$.
For \$n = 3\$, there is one such triangle, so \$t(3) = 1\$:
$$
  \frac{a_1}{b_1} = \frac{a_2}{b_2} = \frac{a_3}{b_3} = \frac 1 3
$$
For \$n = 4\$, there are no such triangles, so \$t(4) = 0\$.
For \$n = 5\$, there is one such triangle, so \$t(5) = 1\$:
$$
  \left(\frac{a_1}{b_1}, \frac{a_2}{b_2}, \frac{a_3}{b_3}\right) =
  \left(\frac 1 5, \frac 2 5, \frac 2 5\right)
$$
For \$n = 6\$, there are no such triangles, so \$t(6) = 0\$.
For \$n = 7\$, there are two such triangles, so \$t(7) = 2\$:
$$
  \left(\frac{a_1}{b_1}, \frac{a_2}{b_2}, \frac{a_3}{b_3}\right) =
  \left(\frac 2 7, \frac 2 7, \frac 3 7\right)
  \hspace{1em} \text{and} \hspace{1em}
  \left(\frac{a_1}{b_1}, \frac{a_2}{b_2}, \frac{a_3}{b_3}\right) =
  \left(\frac 1 7, \frac 3 7, \frac 3 7\right)
$$
For \$n = 8\$, there is one such triangle, so \$t(8) = 1\$:
$$
  \left(\frac{a_1}{b_1}, \frac{a_2}{b_2}, \frac{a_3}{b_3}\right) =
  \left(\frac 1 4, \frac 3 8, \frac 3 8\right)
$$
The first thirty pairs, \$\left(n, t(n)\right)\$ are:
(1,0),(2,0),(3,1),(4,0),(5,1),(6,0),(7,2),(8,1),(9,2),(10,1),(11,4),(12,2),(13,5),(14,2),(15,5),(16,4),(17,8),(18,4),(19,10),(20,8),(21,10),(22,6),(23,14),(24,8),(25,15),(26,9),(27,16),(28,14),(29,21),(30,13)

This is a code-golf challenge, so shortest code wins.

JavaScript (ES6),  188 184  183 bytes

n=>{for(o=r=[],a=n;x=--a/n;)for(P=n;P;P--)for(p=P;y=--p/P;)for(Q=n;Q;)!(z=Q-x*Q-y*Q,g=(a,b)=>b?g(b,a%b):z%1||a>1)(a,n)&!o[k=[x,y,z/=Q--].sort()]&x+y>z&x+z>y&y+z>x?o[k]=++r:0;return+r}

Try it online!
How?
Given \$n\$, we look for all pairs \$(x,y)\$ defined as:
$$x=\dfrac{a}{n},\:1\le a <n$$
$$y=\dfrac{p}{P},\:1\le p < P \le n$$
For each pair \$(x,y)\$, we compute \$z=1-x-y\$.
The triplet \$(x,y,z)\$ is valid if all the following conditions are met:

\$a\$ and \$n\$ are coprime
there is some \$Q,\:1\le Q \le n\$ such that \$Qz\$ is an integer
we have \$x+y>z\$, \$x+z>y\$ and \$y+z>x\$

Commented
NB: this is the 184-byte version, which is slightly more readable
n => {                       // n = input
  for(                       // 1st loop:
    o = r = [],              //   o = lookup object, r = output counter
    a = n; x = --a / n;      //   go from a = n - 1 to 1
  )                          //   and define x = a / n
  for(                       // 2nd loop:
    P = n; P; P--            //   go from P = n to 1
  )                          //
  for(                       // 3rd loop:
    p = P; y = --p / P;      //   go from p = P - 1 to 1
  )                          //   and define y = p / P
  for(                       // 4th loop:
    Q = n; Q;                //   go from Q = n to 1
  ) (                        //
      z = Q - x * Q - y * Q, //   define z = Q(1 - x - y)
      g = (a, b) =>          //   g is a helper function which
        b ?                  //     recursively computes the GCD
          g(b, a % b)        //     of 2 given integers
        :                    //
          a < 2              //     and returns true if it equals 1
    )(a, n) &                //   use it to figure out if a and n are coprime
    !(z % 1) &               //   make sure that z is an integer
    !o[                      //   make sure that the key k ...
      k = [x, y, z /= Q--]   //     ... made of [ x, y, z / Q ] ...
          .sort()            //     ... and sorted (lexicographically)
    ] &                      //   was not already found
    x + y > z &              //   make sure that all triangle inequalities
    x + z > y &              //   are fulfilled
    y + z > x ?              //   if all of the above is true:
      o[k] = ++r             //     increment r and save the key in o
    :                        //   else:
      0;                     //     do nothing
  return +r                  // return the final result
}                            //


bROKEN cAPSLOCK kEY fIASCO Some of your employees have broken capslock keys and you're too cheap to replace them. Help them out by creating the shortest program possible to correct their work! Simply convert each character in a given string from uppercase to lowercase and vice-versa... but there's a twist!

You're also very excited for Christmas! So you're going to leave in a tiny "bug" that doesn't correct letters which are within sequences of Christmas (case-insensitive).

Input

For input you will use one single string (or array of bytes) that may contain newlines and ascii between 0x20 and 0x7e ( - ~). You don't need to worry about carriage returns or any other characters being in the string.

Output

The output should contain only the provided string with the upper and lowercase characters swapped (and the Christmas bug of course!). It can contain up to one extra trailing whitespace.

Christmas Bug

Let's explain this with an example:

Input: i CAN HARDLY WORK LIKE THIS please GET ME A NEW KEYBOARD FOR cHRISTMAS
Output: I Can HaRdly work lIke thiS PLEASE geT Me A new keyboard for ChriStmas

can contains "c" which is the first letter of Christmas, so that isn't changed. The next letter in Christmas is "h", which is in hardly (which also contains the "r"), so that isn't changed, etc. Christmas itself only has one letter unchanged because by the time the code reaches there, it's actually looking for "s", not "c".

Once the sequence is found, it should start all over again at "c", and begin iterating through Christmas once more. So ChristmasChristmas would be left unchanged.

Test Cases

Input: Hello World!
Output: hELLO wORLD!

Input: I like pie :)
Output: i LIKE PIE :)

Input: hELP my KeYboarD
       iS BROKEN
Output: Help MY kEyBOARd
        Is broken

Input: cHRISTMAS IS COMING REALLY SOON!
Output: cHRISTMAS is Coming really soon!

Input: C is the first letter in cHRISTMAS
Output: C IS ThE FIrST LETTER iN ChriSTMAS

Winner

This is code-golf so the shortest answer wins!

05AB1E, 16 bytes

Thanks to Emigna for saving a byte and fixing a bug!

vyÐl'ŒÎ¾èQi¼ëš}?

Explanation:

vy                # For each character in the string...
  Ð               #   Triplicate that character
   l              #   Convert to lowercase
    'ŒÎ           #   Compressed version of "christmas"
       ¾          #   Push the counting variable (let's call this N)
        è         #   Get the nth character of "christmas", with modular indexing
         Qi   }   #   If equal...
           ¼      #      N += 1
            ë     #   Else...
             š    #      Swapcase
               ?  #   Print that character

Uses the CP-1252 encoding. Try it online!


Find a representative submatrix You have a matrix of size m x n.

Each cell in the matrix has a uniformly random integer value v, where 0 ≤ v < i, and i ≤ (m x n). (Meaning, the matrix contains a maximum of m x n distinct values, but it may have fewer.)

1) Write a function that accepts input values of m, n, i, and returns a matrix that meets the criteria above.

2) Write a second function that accepts the output of the first function as input, and returns the smallest contiguous submatrix that contains every value of v (by returning the submatrix itself, or its coordinates). By “smallest” I mean the submatrix containing the fewest cells.

(If it helps you visualize, the original inspiration for this problem was wondering how to find the smallest rectangle within a GIF that contained all the colors in its palette.)

APL (23 + 56 = 79)

Function 1 (23):

{¯1+⍵⍴(V⍴⍺?⍺)[V?V←×/⍵]}

This takes i as its left argument and m n as its right argument, like so:

      +mat←8 {¯1+⍵⍴(V⍴⍺?⍺)[V?V←×/⍵]} 5 5
2 4 7 1 3
7 5 6 7 3
3 1 2 4 6
0 4 2 6 1
5 5 0 0 6

Function 2 (56):

{⊃V[⍋≢∘∊¨V←V/⍨{∧/⍵∊⍨∪∊M}¨V←⊃,/{↓∘⍵¨¯1+,⍳⍴⍵}¨↑∘⍵¨,⍳⍴M←⍵]}

This takes the output from the first function as its right argument, like so:

      {⊃V[⍋≢∘∊¨V←V/⍨{∧/⍵∊⍨∪∊M}¨V←⊃,/{↓∘⍵¨¯1+,⍳⍴⍵}¨↑∘⍵¨,⍳⍴M←⍵]} mat
7 5 6
3 1 2
0 4 2