Fastest Mini-Flak Quine Mini-Flak is a subset of the Brain-Flak language, where the <>, <...> and [] operations are disallowed.  Strictly speaking it must not match the following regex:
.*(<|>|\[])

Mini-Flak is the smallest known Turing complete subset of Brain-Flak.

A little while ago I was able to make a Quine in Mini-Flak, but it was too slow to run in the lifetime of the universe.
So my challenge to you is to make a faster Quine.

Scoring
To score your code put a @cy flag at the end of your code and run it in the Ruby interpreter (Try it online uses the ruby interpreter) using the -d flag. Your score should print to STDERR as follows:
@cy <score>

This is the number of cycles your program takes before terminating and is the same between runs.  Since each cycle takes about the same amount of time to be run your score should be directly correlated to the time it takes to run your program.
If your Quine is too long for you to reasonably run on your computer you can calculate the number of cycles by hand.
Calculating the number of cycles is not very difficult.  The number of cycles is equivalent to 2 times the number of monads run plus the number of nilads run.  This is the same as replacing every nilad with a single character and counting the number of characters run in total.
Example scoring

(()()()) scores 5 because it has 1 monad and 3 nilads.

(()()()){({}[()])} scores 29 because the first part is the same as before and scores 5 while the loop contains 6 monads and 2 nilads scoring 8.  The loop is run 3 times so we count its score 3 times.  1*5 + 3*8 = 29

Requirements
Your program must...

Be at least 2 bytes

Print its source code when executed in Brain-Flak using the -A flag

Not match the regex .*(<|>|\[])

Tips

The Crane-Flak interpreter is categorically faster than the ruby interpreter but lacks some of the features.  I would recommend testing your code using Crane-Flak first and then score it in the ruby interpreter when you know it works.  I would also highly recommend not running your program in TIO.  Not only is TIO slower than the desktop interpreter, but it will also timeout in about a minute.  It would be extremely impressive if someone managed to score low enough to run their program before TIO timed out.

[(...)]{} and (...)[{}] work the same as <...> but do not break the restricted source requirement

You can check out Brain-Flak and Mini-Flak Quines if you want an idea of how to approach this challenge.

Mini-Flak, 6851113 cycles

The program (literally)

I know most people aren't likely expecting a Mini-Flak quine to be using unprintable characters and even multi-byte characters (making the encoding relevant). However, this quine does, and the unprintables, combined with the size of the quine (93919 characters encoded as 102646 bytes of UTF-8), make it fairly difficult to place the program into this post.

However, the program is very repetitive, and as such, compresses really well. So that the entire program is available literally from Stack Exchange, there's an xxd reversible hexdump of a gzip-compressed version of the full quine hidden behind the collapsible below:

00000000: 1f8b 0808 bea3 045c 0203 7175 696e 652e  .......\..quine.
00000010: 6d69 6e69 666c 616b 00ed d9db 6a13 4118  miniflak....j.A.
00000020: 0060 2f8b f808 0d64 a1c1 1dc8 4202 c973  .`/....d....B..s
00000030: 4829 4524 0409 22e2 5529 a194 1242 1129  H)E$..".U)...B.)
00000040: d2d7 ca93 f9cf 4c4c d45b 9536 e6db 6967  ......LL.[.6..ig
00000050: 770e 3bc9 ffed eca9 edb7 b1a4 9ad2 6a1d  w.;...........j.
00000060: bfab 75db c6c6 6c5f 3d4f a5a6 8da6 dcd8  ..u...l_=O......
00000070: 465b d4a5 5a28 4bd9 719d 727b aa79 f9c9  F[..Z(K.q.r{.y..
00000080: 43b6 b9d7 8b17 cd45 7f79 d3f4 fb65 7519  C......E.y...eu.
00000090: 59ac 9a65 bfdf 8f86 e6b2 69a2 bc5c 4675  Y..e......i..\Fu
000000a0: d4e4 bcd9 5637 17b9 7099 9b73 7dd3 fcb2  ....V7..p..s}...
000000b0: 4773 b9bc e9bd b9ba 3eed 9df7 aeaf 229d  Gs......>.....".
000000c0: e6ed 5eae 3aef 9d46 21b2 5e4d bd28 942e  ..^.:..F!.^M.(..
000000d0: 6917 d71f a6bf 348c 819f 6260 dfd9 77fe  i.....4...b`..w.
000000e0: df86 3e84 74e4 e19b b70e 9af0 111c fa0d  ..>.t...........
000000f0: d29c 75ab 21e3 71d7 77f6 9d8f f902 6db2  ..u.!.q.w.....m.
00000100: b8e1 0adf e9e0 9009 1f81 f011 18d8 1b33  ...............3
00000110: 72af 762e aac2 4760 6003 1bd8 698c c043  r.v...G``...i..C
00000120: 8879 6bde 9245 207c 04ae 5ce6 2d02 e1bb  .yk..E |..\.-...
00000130: 7291 4540 57f8 fe0d 6546 f89b a70b 8da9  r.E@W...eF......
00000140: f5e7 03ff 8b8f 3ad6 a367 d60b f980 679d  ......:..g....g.
00000150: d3d6 1c16 f2ff a767 e608 57c8 c27d c697  .......g..W..}..
00000160: 4207 c140 9e47 9d57 2e50 6e8e c215 b270  B..@.G.W.Pn....p
00000170: bdf6 9926 9e47 9d05 ce02 0ff0 5ea7 109a  ...&.G......^...
00000180: 8ba6 b5db 880b 970b 9749 2864 47d8 1b92  .........I(dG...
00000190: 39e7 9aec 8f0e 9e93 117a 6773 b710 ae53  9........zgs...S
000001a0: cd01 17ee b30e d9c1 15e6 6186 7a5c dc26  ..........a.z\.&
000001b0: 9750 1d51 610a d594 10ea f3be 4b7a 2c37  .P.Qa.......Kz,7
000001c0: 2f85 7a14 8fc4 a696 304d 4bdf c143 8db3  /.z.....0MK..C..
000001d0: d785 8a96 3085 2acc 274a a358 c635 8d37  ....0.*.'J.X.5.7
000001e0: 5f37 0f25 8ff5 6854 4a1f f6ad 1fc7 dbba  _7.%..hTJ.......
000001f0: 51ed 517b 8da2 4b34 8d77 e5b2 ec46 7a18  Q.Q{..K4.w...Fz.
00000200: ffe8 3ade 6fed b2f2 99a3 bae3 c949 9ab5  ..:.o........I..
00000210: ab75 d897 d53c b258 a555 1b07 63d6 a679  .u...<.X.U..c..y
00000220: 4a51 5ead a23a 6a72 9eb6 d569 960b f3dc  JQ^..:jr...i....
00000230: 9ceb 53fa 658f 345f ad07 6f6f efce 06ef  ..S.e.4_..oo....
00000240: 0677 b791 cef2 f620 57bd 1b9c 4521 b241  .w..... W...E!.A
00000250: 4d83 2894 2eaf a140 8102 050a 1428 50a0  M.(....@.....(P.
00000260: 4081 0205 0a14 2850 a040 8102 050a 1428  @.....(P.@.....(
00000270: 50a0 4081 0205 0a14 2850 a040 8102 050a  P.@.....(P.@....
00000280: 1428 50a0 4081 0205 0a14 2850 a040 8102  .(P.@.....(P.@..
00000290: 050a 1428 50a0 4081 0205 0a14 2850 a040  ...(P.@.....(P.@
000002a0: 8102 050a 1428 50a0 4081 0205 0a14 2850  .....(P.@.....(P
000002b0: a040 8102 050a 1428 50a0 4081 0205 0a14  .@.....(P.@.....
000002c0: 2850 a040 8102 050a 1428 50a0 4081 0205  (P.@.....(P.@...
000002d0: 0a14 2850 a040 8102 050a 1428 50a0 4081  ..(P.@.....(P.@.
000002e0: 0205 0a14 2850 a040 8102 050a 1428 50a0  ....(P.@.....(P.
000002f0: 4081 0205 0a14 2850 a040 8102 050a 1428  @.....(P.@.....(
00000300: 50a0 4081 0205 0a14 2850 a040 8102 050a  P.@.....(P.@....
00000310: 1428 50a0 4081 0205 0a14 2850 a040 8102  .(P.@.....(P.@..
00000320: 050a 1428 50a0 4081 0205 0a14 2850 a040  ...(P.@.....(P.@
00000330: 8102 050a 1428 50a0 4081 0205 0a14 2850  .....(P.@.....(P
00000340: a040 8102 050a 1428 50a0 4081 0205 0a14  .@.....(P.@.....
00000350: 2850 a040 8102 050a 1428 50a0 4081 0205  (P.@.....(P.@...
00000360: 0a14 2850 a040 8102 050a 1428 50a0 4081  ..(P.@.....(P.@.
00000370: 0205 0a14 2850 a01c 14ca 7012 cbb4 a6e9  ....(P....p.....
00000380: e6db e6b1 e4b1 9e4c 4ae9 d3be f5f3 745b  .......LJ.....t[
00000390: 37a9 3d6a af49 7489 a6e9 ae5c 96dd 488f  7.=j.It....\..H.
000003a0: d31f 5da7 fbad 5d56 3e73 5277 7cf5 aa7b  ..]...]V>sRw|..{
000003b0: 3fbc df7c e986 c3ba 5ee4 3c6f 74f7 c3e1  ?..|....^.<ot...
000003c0: 301a bb45 d795 9afb fbdc 1495 65d5 6d9b  0..E........e.m.
000003d0: baf7 a5b4 a87d 4a5b d7fd b667 b788 ec27  .....}J[...g...'
000003e0: c5d8 28bc b96a 9eda 7a50 524d 290a a5cb  ..(..j..zPRM)...
000003f0: cbef 38cb c3ad f690 0100                 ..8.......

(Yes, it's so repetitive that you can even see the repeats after it's been compressed).

The question says "I would also highly recommend not running your program in TIO. Not only is TIO slower than the desktop interpreter, but it will also timeout in about a minute. It would be extremely impressive if someone managed to score low enough to run their program before TIO timed out." I can do that! It takes about 20 seconds to run on TIO, using the Ruby interpreter: Try it online!

The program (readably)

Now I've given a version of the program that computers can read, let's try a version that humans can read. I've converted the bytes that make up the quine into codepage 437 (if they have the high bit set) or Unicode control pictures (if they're ASCII control codes), added whitespace (any pre-existing whitespace was converted to control pictures), run-length-encoded using the syntax «string×length», and some data-heavy bits elided:

␠
(((()()()()){}))
{{}
    (({})[(()()()())])
    (({})(
        {{}{}((()[()]))}{}
        (((((((({})){}){}{})){}{}){}){}())
        {
            ({}(
                (␀␀!S␠su! … many more comment characters … oq␝qoqoq)
                («()×35» («()×44» («()×44» («()×44» («()×44» («()×45»
                … much more data encoded the same way …
                («()×117»(«()×115»(«()×117»
                «000010101011┬â┬ … many more comment characters … ┬â0┬â┬à00␈␈
                )[({})(
                    ([({})]({}{}))
                    {
                        ((()[()]))
                    }{}
                    {
                        {
                            ({}(((({}())[()])))[{}()])
                        }{}
                        (({}))
                        ((()[()]))
                    }{}
                )]{}
                %Wwy$%Y%ywywy$wy$%%%WwyY%$$wy%$$%$%$%$%%wy%ywywy'×almost 241»
                ,444454545455┬ç┬ … many more comment characters … -a--┬ü␡┬ü-a␡┬ü
            )[{}()])
        }{}
        {}({}())
    )[{}])
    (({})(()()()()){})
}{}{}␊

(The "almost 241" is because the 241st copy is missing the trailing ', but is otherwise identical to the other 240.)

Explanation

About the comments

The first thing to explain is, what's up with the unprintable characters and other junk that isn't Mini-Flak commands? You may think that adding comments to the quine just makes things harder, but this is a speed competition (not a size competition), meaning that comments don't hurt the speed of the program. Meanwhile, Brain-Flak, and thus Mini-Flak, just dump the contents of the stack to standard output; if you had to ensure that the stack contained only the characters that made up the commands of your program, you'd have to spend cycles cleaning the stack. As it is, Brain-Flak ignores most characters, so as long as we ensure that junk stack elements aren't valid Brain-Flak commands (making this a Brain-Flak/Mini-Flak polyglot), and aren't negative or outside the Unicode range, we can just leave them on the stack, allow them to be output, and put the same character in our program at the same place to retain the quine property.

There's one particularly important way we can take advantage of this. The quine works by using a long data string, and basically all the output from the quine is produced by formatting the data string in various ways. There's only one data string, despite the fact that the program has multiple pieces; so we need to be able to use the same data string to print different parts of the program. The "junk data doesn't matter" trick lets us do this in a very simple way; we store the characters that make up the program in the data string by adding or subtracting a value to or from their ASCII code. Specifically, the characters making up the start of the program are stored as their ASCII code + 4, the characters making up the section that's repeated almost 241 times as their ASCII code − 4, and the characters making up the end of the program are stored as their ASCII code − 8. We can then print any of these three parts of the program via printing every character of the data string with an offset; if, for example, we print it with 4 added to every character code, we get one repeat of the repeated section, with some comments before and after. (Those comments are simply the other sections of the program, with character codes shifted so that they don't form any valid Brain-Flak commands, because the wrong offset was added. We have to dodge Brain-Flak commands, not just Mini-Flak commands, to avoid violating the restricted-source part of the question; the choice of offsets was designed to ensure this.)

Because of this comment trick, we actually only need to be able to output the data string formatted in two different ways: a) encoded the same way as in the source, b) as character codes with a specified offset added to every code. That's a huge simplification that makes the added length totally worth it.

Program structure

This program consists of four parts: the intro, the data string, the data string formatter, and the outro. The intro and outro are basically responsible for running the data string and its formatter in a loop, specifying the appropriate format each time (i.e. whether to encode or offset, and what offset to use). The data string is just data, and is the only part of the quine for which the characters that make it up are not specified literally in the data string (doing that would obviously be impossible, as it would have to be longer than itself); it's thus written in a way that's particularly easy to regenerate from itself. The data string formatter is made of 241 almost identical parts, each of which formats a specific datum out of the 241 in the data string.

Each part of the program can be produced via the data string and its formatter as follows:

To produce the outro, format the data string with offset +8
To produce the data string formatter, format the data string with offset +4, 241 times
To produce the data string, format the data string via encoding it into the source format
To produce the intro, format the data string with offset -4

So all we have to do is to look at how these parts of the program work.

The data string

(«()×35» («()×44» («()×44» («()×44» («()×44» («()×45» …

We need a simple encoding for the data string as we have to be able to reverse the encoding in Mini-Flak code. You can't get much simpler than this!

The key idea behind this quine (apart from the comment trick) is to note that there's basically only one place we can store large amounts of data: the "sums of command return values" within the various nesting levels of the program source. (This is commonly known as the third stack, although Mini-Flak doesn't have a second stack, so "working stack" is likely a better name in the Mini-Flak context.) The other possibilities for storing data would be the main/first stack (which doesn't work because that's where our output has to go, and we can't move the output past the storage in a remotely efficient way), and encoded into a bignum in a single stack element (which is unsuitable for this problem because it takes exponential time to extract data from it); when you eliminate those, the working stack is the only remaining location.

In order to "store" data on this stack, we use unbalanced commands (in this case, the first half of a (…) command), which will be balanced within the data string formatter later on. Each time we close one of these commands within the formatter, it'll push the sum of a datum taken from the data string, and the return values of all the commands at that nesting level within the formatter; we can ensure that the latter add to zero, so the formatter simply sees single values taken from the data string.

The format is very simple: (, followed by n copies of (), where n is the number we want to store. (Note that this means we can only store non-negative numbers, and the last element of the data string needs to be positive.)

One slightly unintuitive point about the data string is which order it's in. The "start" of the data string is the end nearer the start of the program, i.e. the outermost nesting level; this part gets formatted last (as the formatter runs from innermost to outermost nesting levels). However, despite being formatted last, it gets printed first, because values pushed onto the stack first are printed last by the Mini-Flak interpreter. The same principle applies to the program as a whole; we need to format the outro first, then the data string formatter, then the data string, then the intro, i.e. the reverse of the order in which they are stored in the program.

The data string formatter

)[({})(
    ([({})]({}{}))
    {
        ((()[()]))
    }{}
    {
        {
            ({}(((({}())[()])))[{}()])
        }{}
        (({}))
        ((()[()]))
    }{}
)]{}

The data string formatter is made out of 241 sections which each have identical code (one section has a marginally different comment), each of which formats one specific character of the data string. (We couldn't use a loop here: we need an unbalanced ) to read the data string via matching its unbalanced (, and we can't put one of those inside a {…} loop, the only form of loop that exists. So instead, we "unroll" the formatter, and simply get the intro/outro to output the data string with the formatter's offset 241 times.)

)[({})( … )]{}

The outermost part of a formatter element reads one element of the data string; the simplicity of the data string's encoding leads to a little complexity in reading it. We start by closing the unmatched (…) in the data string, then negate ([…]) two values: the datum we just read from the data string (({})) and the return value of the rest of the program. We copy the return value of the rest of the formatter element with (…) and add the copy to the negated version with {}. The end result is that the return value of the data string element and formatter element together is the datum minus the datum minus the return value plus the return value, or 0; this is necessary to make the next data string element out produce the correct value.

([({})]({}{}))

The formatter uses the top stack element to know which mode it's in (0 = format in data string formatting, any other value = the offset to output with). However, just having read the data string, the datum is on top of the format on the stack, and we want them the other way round. This code is a shorter variant of the Brain-Flak swap code, taking a above b to b above a + b; not only is it shorter, it's also (in this specific case) more useful, because the side effect of adding b to a is not problematic when b is 0, and when b is not 0, it does the offset calculation for us.

{
    ((()[()]))
}{}
{
    …
    ((()[()]))
}{}

Brain-Flak only has one control flow structure, so if we want anything other than a while loop, it'll take a bit of work. This is a "negate" structure; if there's a 0 on top of the stack, it removes it, otherwise it places a 0 on top of the stack. (It works pretty simply: as long as there isn't a 0 on top of the stack, push 1 − 1 to the stack twice; when you're done, pop the top stack element.)

It's possible to place code inside a negate structure, as seen here. The code will only run if the top of the stack was nonzero; so if we have two negate structures, assuming the top two stack elements aren't both zero, they'll cancel each other out, but any code inside the first structure will run only if the top stack element was nonzero, and the code inside the second structure will run only if the top stack element was zero. In other words, this is the equivalent of an if-then-else statement.

In the "then" clause, which runs if the format is nonzero, we actually have nothing to do; what we want is to push the data+offset to the main stack (so that it can be output at the end of the program), but it's there already. So we only have to deal with the case of encoding the data string element in source form.

{
    ({}(((({}())[()])))[{}()])
}{}
(({}))

Here's how we do that. The {({}( … )[{}()])}{} structure should be familiar as a loop with a specific number of iterations (which works by moving the loop counter to the working stack and holding it there; it'll be safe from any other code, because access to the working stack is tied to the nesting level of the program). The body of the loop is ((({}())[()])), which makes three copies of the top stack element and adds 1 to the lowest. In other words, it transforms a 40 on top of the stack into 40 above 40 above 41, or viewed as ASCII, ( into ((); running this repeatedly will make ( into (() into (()() into (()()() and so on, and thus is a simple way to generate our data string (assuming that there's a ( on top of the stack already).

Once we're done with the loop, (({})) duplicates the top of the stack (so that it now starts ((()… rather than (()…. The leading ( will be used by the next copy of the data string formatter to format the next character (it'll expand it into (()(()… then (()()(()…, and so on, so this generates the separating ( in the data string).

%Wwy$%Y%ywywy$wy$%%%WwyY%$$wy%$$%$%$%$%%wy%ywywy'

There's one last bit of interest in the data string formatter. OK, so mostly this is just the outro shifted 4 codepoints downwards; however, that apostrophe at the end may look out of place. ' (codepoint 39) would shift into + (codepoint 43), which isn't a Brain-Flak command, so you may have guessed that it's there for some other purpose.

The reason this is here is because the data string formatter expects there to be a ( on the stack already (it doesn't contain a literal 40 anywhere). The ' is actually at the start of the block that's repeated to make up the data string formatter, not the end, so after the characters of the data string formatter have been pushed onto the stack (and the code is about to move onto printing the data string itself), the outro adjusts the 39 on top of the stack into a 40, ready for the formatter (the running formatter itself this time, not its representation in the source) to make use of it. That's why we have "almost 241" copies of the formatter; the first copy is missing its first character. And that character, the apostrophe, is one of only three characters in the data string that don't correspond to Mini-Flak code somewhere in the program; it's there purely as a method of providing a constant.

The intro and outro

(((()()()()){}))
{{}
    (({})[(()()()())])
    (({})(
        {{}{}((()[()]))}{}
        (((((((({})){}){}{})){}{}){}){}())
        {
            ({}(
                (␀␀!S␠su! … many more comment characters … oq␝qoqoq)
                …
            )[{}()])
        }{}
        {}({}())
    )[{}])
    (({})(()()()()){})
}{}{}␊

The intro and outro are conceptually the same part of the program; the only reason we draw a distinction is that the outro needs to be output before the data string and its formatter are (so that it prints after them), whereas the intro needs to be output after them (printing before them).

(((()()()()){}))

We start by placing two copies of 8 on the stack. This is the offset for the first iteration. The second copy is because the main loop expects there to be a junk element on top of the stack above the offset, left behind from the test that decides whether to exist the main loop, and so we need to put a junk element there so that it doesn't throw away the element we actually want; a copy is the tersest (thus fastest to output) way to do that.

There are other representations of the number 8 that are no longer than this one. However, when going for fastest code, this is definitely the best option. For one thing, using ()()()() is faster than, say, (()()){}, because despite both being 8 characters long, the former is a cycle faster, because (…) is counted as 2 cycles, but () only as one. Saving one cycle is negligible compared to a much bigger consideration for a quine, though: ( and ) have much lower codepoints than { and }, so generating the data fragment for them will be much faster (and the data fragment will take up less space in the code, too).

{{} … }{}{}

The main loop. This doesn't count iterations (it's a while loop, not a for loop, and uses a test to break out). Once it exits, we discard the top two stack elements; the top element is a harmless 0, but the element below will be the "format to use on the next iteration", which (being a negative offset) is a negative number, and if there are any negative numbers on the stack when the Mini-Flak program exits, the interpreter crashes trying to output them.

Because this loop uses an explicit test to break out, the result of that test will be left on the stack, so we discard it as the first thing we do (its value isn't useful).

(({})[(()()()())])

This code pushes 4 and f − 4 above a stack element f, whilst leaving that element in place. We're calculating the format for the next iteration in advance (while we have the constant 4 handy), and simultaneously getting the stack into the correct order for the next few parts of the program: we'll be using f as the format for this iteration, and the 4 is needed before that.

(({})( … )[{}])

This saves a copy of f − 4 on the working stack, so that we can use it for the next iteration. (The value of f will still be present at that point, but it'll be in an awkward place on the stack, and even if we could manoeuvre it to the correct place, we'd have to spend cycles subtracting 4 from it, and cycles printing the code to do that subtraction. Far easier simply to store it now.)

{{}{}((()[()]))}{}

A test to see if the offset is 4 (i.e. f − 4 is 0). If it is, we're printing the data string formatter, so we need to run the data string and its formatter 241 times rather than just once at this offset. The code is fairly simple: if f − 4 is nonzero, replace the f − 4 and the 4 itself with a pair of zeros; then in either case, pop the top stack element. We now have a number above f on the stack, either 4 (if we want to print this iteration 241 times) or 0 (if we want to print it only once).

(
    ((((((({})){}){}{})){}{}){}){}
    ()
)

This is an interesting sort of Brain-Flak/Mini-Flak constant; the long line here represents the number 60. You may be confused at the lack of (), which are normally all over the place in Brain-Flak constants; this isn't a regular number, but a Church numeral, which interprets numbers as a duplication operation. For example, the Church numeral for 60, seen here, makes 60 copies of its input and combines them all together into a single value; in Brain-Flak, the only things we can combine are regular numbers, by addition, so we end up adding 60 copies of the top of the stack and thus multiplying the top of the stack by 60.

As a side note, you can use an Underload numeral finder, which generates Church numerals in Underload syntax, to find the appropriate number in Mini-Flak too. Underload numerals (other than zero) use the operations "duplicate top stack element" : and "combine top two stack elements" *; both those operations exist in Brain-Flak, so you just translate : to ), * to {}, prepend a {}, and add enough ( at the start to balance (this is using a weird mix of the main stack and working stack, but it works).

This particular code fragment uses the church numeral 60 (effectively a "multiply by 60" snippet), together with an increment, to generate the expression 60x + 1. So if we had a 4 from the previous step, this gives us a value of 241, or if we had a 0, we just get a value of 1, i.e. this correctly calculates the number of iterations we need.

The choice of 241 is not coincidental; it was a value chosen to be a) approximately the length at which the program would end up anyway and b) 1 more than 4 times a round number. Round numbers, 60 in this case, tend to have shorter representations as Church numerals because you have more flexibility in factors to copy. The program contains padding later on to bring the length up to 241 exactly.

{
    ({}(
        …
    )[{}()])
}{}

This is a for loop, like the one seen earlier, which simply runs the code inside it a number of times equal to the top of the main stack (which it consumes; the loop counter itself is stored on the working stack, but visibility of that is tied to the program's nesting level and thus it's impossible for anything but the for loop itself to interact with it). This actually runs the data string and its formatter 1 or 241 times, and as we've now popped all the values we were using for our control flow calculation from the main stack, we have the format to use on top of it, ready for the formatter to use.

(␀␀!S␠su! … many more comment characters … oq␝qoqoq)

The comment here isn't entirely without interest. For one thing, there are a couple of Brain-Flak commands; the ) at the end is naturally generated as a side effect of the way the transitions between the various segments of the program work, so the ( at the start was manually added to balance it (and despite the length of the comment inside, putting a comment inside a () command is still a () command, so all it does is add 1 to the return value of the data string and its formatter, something that the for loop entirely ignores).

More notably, those NUL characters at the start of the comment clearly aren't offsets from anything (even the difference between +8 and -4 isn't enough to turn a ( into a NUL). Those are pure padding to bring the 239-element data string up to 241 elements (which easily pay for themselves: it would take much more than two bytes to generate 1 vs. 239 rather than 1 vs. 241 when calculating the number of iterations required). NUL was used as the padding character because it has the lowest possible codepoint (making the source code for the data string shorter and thus faster to output).

{}({}())

Drop the top stack element (the format we're using), add 1 to the next (the last character to be output, i.e. the first character to be printed, of the program section we just formatted). We don't need the old format any more (the new format is hiding on the working stack); and the increment is harmless in most cases, and changes the ' at one end of the source representation of the data string formatter into a ( (which is required on the stack for next time we run the formatter, to format the data string itself). We need a transformation like that in the outro or intro, because forcing each data string formatter element to start with ( would make it somewhat more complex (as we'd need to close the ( and then undo its effect later), and we'd somehow need to generate an extra ( somewhere because we only have almost 241 copies of the formatter, not all 241 (so it's best that a harmless character like ' is the one that's missing).

(({})(()()()()){})

Finally, the loop exit test. The current top of the main stack is the format we need for the next iteration (which just came back off the working stack). This copies it and adds 8 to the copy; the resulting value will be discarded next time round the loop. However, if we just printed the intro, the offset was -4 so the offset for the "next iteration" will be -8; -8 + 8 is 0, so the loop will exit rather than continuing onto the iteration afterwards.


A Snake, A Camel And A Kebab As many of you will know, almost every programming language has a standard casing system; unfortunately, we have not been able to agree on a singular system to use and now must frequently switch between camelCase, snake_case, PascalCase and kebab-case.
Now I know what you're thinking... wouldn't it be nice if we had a program that could convert from one casing to another?
Well - soon we're going to have plenty!!! (This is where you come in)
Challenge
You're job is to write a program/function that will take an input string, and a casing system. It will then print/return the converted string.
Inputs:
You're program will receive two inputs, an alphabetic string that is to be converted and a string that will always be one of kebab camel pascal or snake.
Outputs:
You're program should output a string that conforms to the new casing. You can assume the input string is valid and will only conform to one of the casings (i.e. it won't be mixed_Casing).
As most programming languages prefer lowercase variable names, you should convert all letters to lowercase unless it is needed to be upper case for the casing requirements.

Snake Case: All letters are lower case, with underscores separating words.
Kebab Case: All letters are lower case, with hyphens separating words.
Camel Case: The first letter of every word after the first is capitalized, with no spaces.
Pascal Case: The first letter of every word is capitalized, with no spaces.

Test Cases:
"aJavaVariable", "snake" = "a_java_variable"
"a_python_variable", "kebab" = "a-python-variable"
"golf", "camel" = "golf"
"camelToPascal", "pascal" = "CamelToPascal"
"PascalToCamel", "camel" = "pascalToCamel"
"", "snake" = ""
"doHTMLRequest", "kebab" = "do-h-t-m-l-request"

<!-- Run the snippet to see the leaderboard. Report any bugs to @ozewski on Github. -->    <iframe src="https://ozewski.github.io/ppcg-leaderboard/?id=216396" width="100%" height="100%" style="border:none;">Oops, your browser is too old to view this content! Please upgrade to a newer version of your browser that supports HTML5.</iframe><style>html,body{margin:0;padding:0;height:100%;overflow:hidden}</style>


Island Golf #1: Circumnavigation This is the first in a series of Island Golf challenges. Next challenge

Given an island in ASCII-art, output an optimal path to circumnavigate it.

Input

Your input will be a rectangular grid consisting of two characters, representing land and water. In the examples below, land is # and water is ., but you may substitute any two distinct characters you wish.

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

There will always be at least one land tile. The land tiles will all be contiguous (i.e. there's only one island). The water tiles will also be contiguous (i.e. there are no lakes). The outer border of the grid will all be water tiles. Land tiles will not be connected diagonally: i.e., you will never see something like

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

Output

Your code must output the same grid, with a shortest circumnavigation drawn on it. In the examples below, the circumnavigation path is drawn with o, but you may substitute any character as long as it is distinct from your land and water characters.

A circumnavigation is a simple closed curve, drawn entirely on water tiles, that fully encircles all land tiles on the grid. Diagonal connections are allowed. For instance, this is a circumnavigation of the above island (but not a shortest one):

.ooooo.....
o..##.oo...
o.#####.o..
o.#######o.
o#########o
ooo#######o
..o#####.#o
..oo####..o
....oooooo.

The length of a circumnavigation is computed as follows: For every pair of adjacent tiles on the path, if they are connected horizontally or vertically, add 1; if they are connected diagonally, add √2. The length of the above path is 22 + 7√2 (≈ 31.9).

A shortest circumnavigation is a circumnavigation with the shortest possible length. Your program should output any one path that satisfies this condition. For most islands, there will be multiple possible solutions. Here is one solution for the above island, with length 10 + 13√2 (≈ 28.4):

...oo......
..o##oo....
.o#####oo..
.o#######o.
o#########o
.o.#######o
..o#####.#o
...o####.o.
....ooooo..

Details

Your solution may be a full program or a function. Any of the default input and output methods are acceptable.

Your input and output may be a multiline string or a list of strings. If your language has a character type distinct from single-character strings, you may substitute "list of characters" for "string" in the previous sentence. If your language needs to input the height and/or width of the grid, you may do so. Your output may (optionally) have a single trailing newline. As mentioned above, you may use any three distinct characters in place of #.o (please specify in your submission which characters you're using).

Test cases

A. Islands with unique shortest circumnavigations:

...
.#.
...

.o.
o#o
.o.

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

.oooo.
o####o
.oooo.

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

......
..oo..
.o##o.
..o#o.
...o..
......

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

.ooooo.
o#####o
o..#..o
o..#..o
o#####o
.ooooo.

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

...o...
..o#o..
.o.#.o.
o#####o
.o.#.o.
..o#o..
...o...

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

.ooooo.
o#####o
o##..#o
.o#..#o
..oooo.

B. Example of an island with multiple possible solutions:

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

Possible outputs:

....oo..
...o##o.
..o####o
.o###.o.
o#####o.
o#####o.
.o##oo..
..oo....

....oo..
...o##o.
..o####o
.o###.o.
o#####o.
o#####o.
.o##.o..
..ooo...

....oo..
...o##o.
..o####o
.o###..o
o#####.o
o#####o.
.o##oo..
..oo....

....oo..
...o##o.
..o####o
.o###..o
o#####.o
o#####o.
.o##.o..
..ooo...

C. Large test case as a Gist

This is code-golf: the shortest code in each language wins.

Mathematica (version 9), 165 bytes

The nice, short ConvexHullMesh function that Greg Martin used was only introduced in Mathematica version 10, so I thought I'd make an attempt without it, using my ancient Mathematica version 9. I managed to get it slightly shorter, though! It's a function that takes and returns a list of strings (with ., # and o as the symbols).

""<>#&/@("o"MorphologicalTransform[MorphologicalComponents[#,Method->"ConvexHull"],Max[#(1-#[[2,2]])CrossMatrix@1]&]+"#"#/.{0->"."})&[Characters@#/.{"."->0,"#"->1}]&

Explanation:

First, Characters@# /. {"."->0, "#"->1} turns the input into a matrix of 0s and 1s.
"o"MorphologicalTransform[MorphologicalComponents[#,Method->"ConvexHull"],Max[#(1-#[[2,2]])CrossMatrix@1]&]+"#"# then uses Mathematica's powerful (but extremely byte-heavy…) image processing capabilities to first fill in the island's convex hull (which is the shape you'd get if you stretched a piece of string around it), and then take its boundary. We then multiply this matrix by the string "o" to get a matrix of 0s and "o"s (thanks to Mathematica's impressive adaptability about types), and add this to "#" times the matrix of the island.
Finally, ""<>#& /@ (... /. {0->"."}) turns this matrix of "o"s, "#"s and 0s into a matrix of "o"s, "#"s and "."s, and joins each row into a string.

When we test this on example B, we get the output

{"....oo..",
 "...o##o.",
 "..o####o",
 ".o###..o",
 "o#####o.",
 "o#####o.",
 ".o##oo..",
 "..oo...."}

[Edit, thanks to Greg Martin:] If we're allowed to use arrays of characters instead of lists of strings, we can trim this down to 144 bytes:

"o"MorphologicalTransform[MorphologicalComponents[#,Method->"ConvexHull"],Max[#(1-#[[2,2]])CrossMatrix@1]&]+"#"#/.{0->"."}&[#/.{"."->0,"#"->1}]&


Output the date in the Mel calendar The Mel calendar is used in the fictional world of Kaldia. Your goal is to convert dates into the Mel calendar.

This calendar has 13 months of 28 days each, plus 1 or 2 extra days after the last month. A year that is divisible by 4 but not by 100, or divisible by 400 has 366 days, and other years have 365 (i.e. our leap year rules, but with years in the Mel calendar).

You should use the month and day name abbreviations:

months: dia vio lis gil ful dyu mel ral zan pal mik fav ruj

days: dia vio lis gil ful dyu mel ral zan pal mik fav ruj ser rav tan lin rez jil din ket len lax nen pin mat kun mir

The extra days outside of any month have the month name of myuxet (no abbreviation here), and the day names are axet and teems, respectively.

0 dia dia is 1988/11/30.

You can take the input date as a string or a (year, month, day) tuple; alternatively, for functions, the parameter can be in your standard library's date type. The output should be a space-separated string.

Test cases

1776-07-04 => -213 ral ket
1859-12-15 => -129 dia rav
1917-04-14 => -72 ful nen
1981-02-04 => -8 lis mik
1988-11-30 => 0 dia dia
1988-12-01 => 0 dia vio
1988-12-28 => 0 vio dia
2017-01-01 => 28 vio ful
2019-04-22 => 30 dyu lis
2019-11-30 => 30 myuxet axet
2019-12-01 => 31 dia dia
2021-11-29 => 32 myuxet axet
2021-11-30 => 32 myuxet teems
2089-11-30 => 101 dia dia
2389-11-30 => 400 myuxet teems

You should be able to handle dates from 1 AD to 9999 AD at least.

Reference implementation in Perl 6

Standard loopholes are forbidden.

Perl 6, 174 bytes

{~(.year,(|[X]("diaviolisgilfuldyumelralzanpalmikfavrujserravtanlinrezjildinketlenlaxnenpinmatkunmir".comb(3)xx 2)[^364],|("myuxet"X <axet teems>))[.day-of-year-1])}o*-726436

Try it online!

Generate a list of all the valid dates and then indexes the day of the year into that list.

Explanation

{                                                   }  # Anonymous code block
                                                     o*-726436  # Subtract some days from the input
  (.year,                               # Output the year
           [X]("...".comb(3))[^365]     # Then produce a list of all months/days
         (|                        ,
          |("myuxet"X <axet teems>))    # And the extra days
                                    [.day-of-year-1]   # And get the current date
 ~   # Stringify the list


"Hello, World!" (Robbers' thread) This is the robbers' thread. The cops' thread is here.

Your challenge is to take an uncracked submission from the cops' thread and find, for what input or inputs, the program will print Hello, World! and a newline. Capitalization, spacing, and punctuation must be exact.

Please comment on the cop's submission when you've cracked their code.

Bash by Sisyphus

Original code:

[[ ! "${1////x}" =~ [[:alnum:]] ]]&&[[ $# = 1 ]]&&bash -c "$1"

Input:

__=; (( __++, __-- ));
(( ___        = __,        ___++));
(( ____       = ___,       ____++));
(( _____      = ____,      _____++));
(( ______     = _____,     ______++));
(( _______    = ______,    _______++));
(( ________   = _______,   ________++));
(( _________  = ________,  _________++));

${!__##-} <<<\$\'\\$___$______$_______\\$___$______$_____\\$___$_______$__\\$___$_______$_________\'\ \$\'\\$___$___$__\\$___$______$_______\\$___$_______$______\\$___$_______$______\\$___$_______$_________,\ \\$___$____$_________\\$___$_______$_________\\$___$________$____\\$___$_______$______\\$___$______$______\\$__$______$___\'

Explanation:

This encodes "echo Hello, World!" as octal escape sequences (\xxx).

Except you also can't use numbers, so the first part builds up variables for the numbers 0-7. You can use those to build a string with octal sequences that will evaluate to give you the actual command.

But eval is also alphanumeric. So instead this pipes that string as input to another instance of bash. $0 contains the name of the command used to invoke Bash, which is usually just bash (or -bash for a login shell) if you're running it normally (through TIO or by pasting it in a terminal). (This incidentally means that if you try to run this by pasting it into a script, things will go horribly wrong as it tries to fork itself a bunch of times.)

But anyway, you can't say $0 directly. Instead, $__ contains the name of $0 ("0"), and you can use indirect expansion to access it (${!__} refers to the contents of $0).

And that, finally, gives you all the pieces you need.


Triangular code, triangular output For this challenge, submissions should be a program or function shaped like a right triangle, which produces a right triangle of the same size.

What is a right triangle?

For this challenge, a right triangle consists of 1 or more lines, each containing a number of characters (assume all non-newline characters are the same width) equal to that line number:

.
..
...
....

Trailing newlines are allowed.

The challenge:

Your code should form a right triangle, and output a right triangle with the same height made up of any non-newline characters.

As this is code golf, shortest answer in bytes per language wins.


Find the largest prime whose length, sum and product is prime The number 113 is the first prime whose length 3 is prime, digital sum 5 = 1 + 1 + 3 is prime, and digital product 3 = 1 * 1 * 3 is prime.
A prime that has these 3 properties will be called supremely prime. The primes 11117 and 1111151 are other examples.
Goal
Write a program that can find the largest supremely prime number possible in less than an hour on a decent modern personal computer (such as the preferred spec here).
You should not simply give us a large supreme prime. You need to show us your search process with code that actually works. You can build on your or other people's solutions but be sure to give them credit. We're kind of communally trying to find the largest supreme prime realizable on a normal computer in an hour.
Scoring
The submission that finds the largest supreme prime wins. If it turns out that there are finitely many supreme primes then the first submission that generates the highest supreme prime wins.
(If you can mathematically prove that either there are or aren't infinitely many supreme primes I'll give you 200 bounty rep just because. :) )
Details

You may use any source to generate your primes (e.g. internet).

You may use probabilistic prime testing methods.

Everything is in base 10.

Zero and one are NOT considered prime.

Primes that contain 0 have a digital product of 0 so obviously they can't be supreme.

To keep the page less cluttered put large (100+ digit) supreme primes in the form:
  {[number of 1's before the prime digit]}[prime digit]{[number of 1's after the prime digit]}

So 1111151 could be expressed as {5}5{1}.


Block-sorting rows and columns in a 2D array Given a 2D array of integers, let's sort its rows and columns in blocks. This means that you only have to sort a given row or column, but applying the transformations needed for sorting it to every other row or column in the 2D array.

Rules

Input will be a 2D array of integers and a 1-indexed integer. This integer will represent the row to be sorted if the number is positive, or the column to be sorted if the number is negative (or the other way round you want). Example: Given a 4x3 (rows x columns) array you can sort the second column with a -2 argument or the third row with a 3 argument. This second argument will never be zero and its absolute value will never be greater than the corresponding dimension of the array.
Output will be also a 2D array of integers with the needed transformations applied to sort the given row or column. Alternatively you can just write the array to STDOUT.
The output array will have the specified row or column sorted in ascending order. Just note that when you need to swap two numbers in a row, the whole columns where the numbers lay will be swapped. And when you need to swap two numbers in a column, the whole rows where the numbers lay will be swapped.
In the case in which the same number appears several times in the row/column to be sorted, there will be several solutions possible according to the way you swap the values, just do accordingly with the rest of rows/columns to be swapped.

Examples

Positive indices for rows and negative indices for columns

[5  8  7  6                                  [1  3  2  4
 1  3  2  4   order by -3 (3rd column)  -->   9  6  3  0
 9  6  3  0]                                  5  8  7  6]

[5  8  7  6                                  [9  6  3  0
 1  3  2  4   order by -4 (4th column)  -->   1  3  2  4
 9  6  3  0]                                  5  8  7  6]

[5  8  7  6                                  [5  7  8  6
 1  3  2  4     order by 2 (2nd row)  -->     1  2  3  4
 9  6  3  0]                                  9  3  6  0]

[5  8  7  6                                  [6  7  8  5
 1  3  2  4     order by 3 (3rd row)  -->     4  2  3  1
 9  6  3  0]                                  0  3  6  9]

[1  2                                    [1  2     [3  2
 3  2]   order by -2 (2nd column)  -->    3  2] or  1  2]  (both are valid)

[7  5  9  7                                  [5  7  7  9     [5  7  7  9
 1  3  2  4     order by 1 (1st row)  -->     3  1  4  2  or  3  4  1  2
 9  6  3  0]                                  6  9  0  3]     6  0  9  3]

This is code-golf, so may the shortest code for each language win!

R, 55 bytes

function(x,n)`if`(n>0,x[,+x[n,]],x[+x[,-n],])
`+`=order

Try it online!

Reassigns the + operator (actually a function in R) to the order function, which returns the indices of a vector from smallest to largest. Then it's just array manipulation.


Determine If a Challenge is Worth Answering I am a very casual code golfer, and don't often see posts until they show up in the "Hot Network Questions" sidebar over on StackOverflow.  Usually, I'm late to the game, and since the only language I know is Python, there is little point in me answering as there are already several Python answers.  Your challenge is to figure out if a question is worth me answering.

Input:

Your code (function or program) will take one input parameter i

Output:

Truthy or Falsey value for question id i.  Output Truthy if question has more than 5 answers, greater than 3 question score, and one or less answer in Python (no distinction between version).

Rules/Clarifications:

Input format can be anything reasonable (stdin, file, command line), but should be specified in your answer.  Data types and leading/trailing whitespace doesn't matter.
Assume question id is valid for codegolf.stackexchange.com.
Ignore language specific question requirements.  (i.e. if a question meets votes and answers, and has no Python answers because it is Java only, it still results in Truthy).
An answer qualifies as a Python answer if "python" (case insenstive) occurs anywhere before the first newline of the post.
This is code golf, so shortest code in bytes wins.

Sample Cases*

id = 79082 => True
id = 78591 => False (less than 5 answers, also hella hard)
id = 78410 => True
id = 76428 => False (greater than 1 Python answer)
id = 78298 => False (not high enough question score)

*Verified at time of posting, may have changed

05AB1E, 167 160 159 158 156 154 143 bytes

Damn, almost as long as a normal language...

Crap... longer currently beating the the Ruby answer by 1 byte.

Now longer than the Ruby answer, argh!.

I probably should go to bed right now.

Thanks to @wnnmaw for saving 1 byte and thanks to @R. Kap for saving another 2 bytes!

Code:

’£Ø ˆå§¾.‡¢ as g;#.¾¿„–(g.ˆåƒÛ('·Ç://ÐÏg.´¢/q/'+•œ_#()).‚Ø())’.e©’„à="Ž»"’DU¢®…îŒ€ƒŠ‡¡`99£þs\®X¡¦vy’„à="‚¬-„¹"’¡¦'>¡¦¦¬l’±¸’¢s\}rUV)O2‹X5›Y3›)P

Or with more readability:

’£Ø ˆå§¾.‡¢ as g;#.¾¿„–(g.ˆåƒÛ('·Ç://ÐÏg.´¢/q/'+•œ_#()).‚Ø())’
 .e©
’„à="Ž»"’
 DU¢®
“îŒ€ƒŠ‡“
 ¡`99£þs\®X¡¦
v
 y’„à="‚¬-„¹"’¡¦'>¡¦¦¬l’±¸’¢s\}rUV)O2‹X5›Y3›)P

Explanation:

First of all, a lot of text is being compressed here, which translates to good old Python. The uncompressed version is:

"import urllib.request as g
 f=g.urlopen('http://ppcg.lol/q/'+pop_#())
 #.append(f.read())"
.e©“class="answer"“¢®"useful and clear"¡`99£þs\®“class="answer"“¡¦vy“class="post-text"“¡¦'>¡¦¦¬l"python"¢s\}rUV)O2‹X5›Y3›)P

This part:

import urllib.request as g
stack.append(g.urlopen('http://ppcg.lol/q/'+pop_stack()).read())`

actually pops a stack value, copies it into the url and fetches all HTML data. The HTML data is pushed on top of the stack using #.append(f.read()).

We count the number of answers, by count the number of occurences of class="answer".

To count the number of votes, we just split the data at "useful and clear" and keep only the digit values of [0:99] using ®"useful and clear"¡`99£þ. This is the number of upvotes.

Eventually, we need to check every answer if the text "Python" exists before the closing header text. To get all answers, we just split the data on class="post-text" and split each of them again on <. We remove the first two elements to get the part in which the language is displayed and check if the lowercase version is in this string.

So, now our stack looks like this for id = 79273:

`[6, '14', 0, 0, 0, 1, 0, 0]`
  │    │   └───────┬──────┘
  │    │           │
  │    │   is python answer?
  │    │
  │    └── number of upvotes
  │
  └─── number of answers

This can also be seen with the -debug flag on in the interpreter.

So, it's just a matter of processing the data:

rUV)O2‹X5›Y3›)P

r                # Reverse the stack
 U               # Pop the number of answers value and store into X
  V              # Pop the number of upvotes value and store into Y
   )O            # Wrap everything together and sum it all up
     2‹          # Check if smaller than 2
       X5›       # Push X and check if greater than 5
          Y3›    # Push Y and check if greater than 3
             )P  # Wrap everything into an array and take the product.
                   This results into 1 if and only if all values are 1 (and not 0).

Uses CP-1252 encoding. You can download the interpreter here.


Count the rectangles in a diagonal grid As a follow-up to this challenge, we now want to count the number of rectangles in grid with r rows and c columns where there is a line crossing through every diagonal of a square in the grid. Now, we are still counting the the same rectangles as before, but this time we must also include rectangles that are tilted by 45 degrees.

Your goal is to create a function or program that given the number of rows r and columns c outputs the number of rectangles in a diagonal grid with dimensions (r, c).

As a demonstration, this is an animation that iterates through all 37 rectangles formed by a (2 x 3) diagonal grid.

Test Cases

Each case is [rows, columns] = # of rectangles
[0, 0] = 0
[0, 1] = 0
[1, 0] = 0
[1, 1] = 1
[3, 2] = 37
[2, 3] = 37
[6, 8] = 2183
[7, 11] = 5257
[18, 12] = 40932
[42, 42] = 2889558
[51, 72] = 11708274

Rules

This is code-golf so the shortest code wins.
Builtins that solve this are not allowed.

Ruby, 58 bytes

This is a straightforward implementation of the algorithm in Releasing Helium Nuclei's C answer.

g=->m,n{n>m ?g[n,m]:m*~m*n*~n/4+n*((2*m-n)*(4*n*n-1)-3)/6}

I have been investigating why this formula works, with limited success. It's easy to confirm that the number of upright rectangles is equal to (m+1)*m/2 * (n+1)*n/2, the number of diagonal rectangles is a little more elusive.

Neil has confirmed for m==n that the number of tilted rectangles in an n*n square is (4*n**4-n*n-3*n)/6 and that when m>n you need to add an additional (m-n)(n*(4*n*n-1)/3) (related to OEIS A000447), though this does not explain where those two formulas came from. I have found part of the answer.

For m==n, the shape inside the grid is an Aztec diamond.

The number of rectangles in an Aztec diamond is the sum of number of large rectangles superimposed to make it (for the fourth diamond, which is found in a 5x5 grid, 2x8, 4x6, 6x4, and 8x2) minus the number of the rectangles counted twice (the number of rectangles in the previous Aztec diamond).

The formula here is (TeX to be added later):

# superimposed rectangles, 2x(2n-2), 4*(2n-4), ...
f = lambda n: sum( (2*k)*(2*k+1)/2 * (2*n-2*k)*(2*n-2*k+1)/2 for k in range(1, n) )
aztec_rect = f(n) - f(n-1)

According to Wolfram Alpha, the closed form for f is 1/30*(n-1)*n*(4*n**3+14*n**2+19*n+9) and the closed form for aztec_rect is, as Neil discovered, 1/6*n*(n-1)*(4*n**2+4*n+3) == 1/6*(4*n**4-n**2-3*n).

I have yet to discover why (m-n)(n*(4*n*n-1)/3) works, though I suspect that it is because one definition of A000447 is binomial(2*n+1, 3). I will keep you posted.

Update: I have reason to believe that the function of the number of rectangles in an extended Aztec diamond m>n is related to the number of superimposed 2k*2(n-k) rectangles in the diamond minus F(m-1,n-1). More results when I have them.

Update: I tried a different route and ended up with another formula for extended Aztec diamonds that is mostly explainable but has one term that I don't yet understand. Huzzah! :D

def f(m,n):
 if n > m:
     return f(n,m)
 if n == 0:
     return 0
 else:
     return(m-n+1)*(4*n**4-n*n-3*n)/6-f(m-1,n-1)+(m-n)*2+(m-n)*(n-2)-(m-n-1)*f(n-1,n-1)

A quick breakdown of that last formula:

(m-n+1)*(4*n**4-n*n-3*n)/6 is the number of superimposed Aztec diamonds of size n in the structure, as f(n,n) = (4*n**4-n*n-3*n)/6. f(7,3) has 5 superimposed Aztec diamonds size 3, while f(3,3) has only 1 diamond.
-f(m-1,n-1) removes some of the duplicate rectangles from the middle of the superimposed diamonds.
+(m-n)*2 accounts for 2 extra 2-by-(2n-1) rectangles for each extra diamond.
+(m-n)*(n-2) accounts for an extra n-by-n square for each extra diamond.
-(m-n-1)*f(n-1,n-1) This is the new puzzling term. Apparently I have not accounted for some extra squares in my counting, but I haven't figured out where they are in the extended diamond.

Note: when m==n, m-n-1 = -1, meaning that this last term adds squares to the counting. I might be missing something in my regular formula. Full disclosure, this was only meant to be a patch to an earlier draft of this formula that just happened to work. Clearly, I still need to dig into what's going on, and it may be that my formula has some bugs in it. I'll keep you posted.

Russell, Gary and Weisstein, Eric W. "Aztec Diamond." From MathWorld--A Wolfram Web Resource. http://mathworld.wolfram.com/AztecDiamond.html


It's raining in my terminal! Challenge Description

You have to show a simulation of rain in terminal.

In the example given below its adding 100 raindrops at random (use the default random function which your language offers) coordinates, waiting for 0.2 seconds and then redrawing again until the given time expires. Any character can be used for representing the raindrop.

Parameters

Wait time between redrawing in seconds.
Time for which the rain will be visible. This is just an integer representing the number of iterations. [So, the net time for which the rain will be visible is this integer multiplied by the wait time]
Message to be displayed when the rain ends. (This has to be centered)
Number of raindrops to be displayed on the screen.

Rules

A single byte should be used for representing a rain drop, and it can be anything, even cats and dogs.
It doesn't have to be responsive to terminal size which means you don't have to handle the bug for varied terminal sizes. You can specify the terminal width and height on your own.
Standard rules of golfing apply.

Code Sample and Output

This is an ungolfed version written in python 2.7 using ncurses.

import curses
import random
import time

myscreen = curses.initscr()
curses.curs_set(0) # no cursor please
HEIGHT, WIDTH = myscreen.getmaxyx()
RAIN = '/' # this is what my rain drop looks like
TIME = 10

def make_it_rain(window, tot_time, msg, wait_time, num_drops):
    """
    window    :: curses window
    time      :: Total time for which it rains
    msg       :: Message displayed when it stops raining
    wait_time :: Time between redrawing scene
    num_drops :: Number of rain drops in the scene
    """
    for _ in range(tot_time):
        for i in range(num_drops):
            x,y=random.randint(1, HEIGHT-2),random.randint(1,WIDTH-2)
            window.addstr(x,y,RAIN)
        window.refresh()
        time.sleep(wait_time)
        window.erase()

    window.refresh()
    window.addstr(HEIGHT/2, int(WIDTH/2.7), msg)

if __name__ == '__main__':
    make_it_rain(myscreen, TIME, 'IT HAS STOPPED RAINING!', 0.2, 100)
    myscreen.getch()
    curses.endwin()

Output -

MATL, 52 bytes
xxx:"1GY.Xx2e3Z@25eHG>~47*cD]Xx12:~c!3G80yn-H/kZ"why

Inputs are, in this order: pause between updates, number of drops, message, number of repetitions. The monitor has size 80×25 characters (hard-coded).
GIF or it didn't happen! (Example with inputs 0.2, 100, 'THE END', 30)

Or try it at MATL Online.
Explanation
xxx      % Take first three inputs implicitly and delete them (but they get
         % copied into clipboard G)
:"       % Take fourth input implicitly. Repeat that many times
  1G     %   Push first input (pause time)
  Y.     %   Pause that many seconds
  Xx     %   Clear screen
  2e3    %   Push 2000 (number of chars in the monitor, 80*25)
  Z@     %   Push random permutation of the integers from 1 to 2000
  25e    %   Reshape as a 25×80 matrix, which contains the numbers from 1 to 2000
         %   in random positions
  HG     %   Push second input (number of drops)
  >~     %   Set numbers that are <= second input to 1, and the rest to 0
  47*c   %   Multiply by 47 (ASCII for '/') and convert to char. Char 0 will
         %   be displayed as a space
  D      %   Display
]        % End
Xx       % Clear screen
12:~     % Push row vector of twelve zeros
c!       % Convert to char and transpose. This will produce 12 lines containing
         % a space, to vertically center the message in the 25-row monitor
3G       % Push third input (message string)
80       % Push 80
yn       % Duplicate message string and push its length
-        % Subtract
H/k      % Divide by 2 and round down
Z"       % Push string of that many spaces, to horizontally center the message
         % in the 80-column monitor
w        % Swap
h        % Concatenate horizontally
y        % Duplicate the column vector of 12 spaces to fill the monitor
         % Implicitly display


Tips for golfing in Sesos If you have any tips regarding golfing in Sesos, a language made by Dennis, and nobody else has covered them yet, please post them here! Only one tip is allowed per answer. Your tip should be at least somewhat specific to Sesos itself, and not just brainfuck. If your tip is relevant to brainfuck in general, you should post it here instead.

What's different in Sesos?

Golfing in Sesos is similar to golfing in brainfuck in that it has limited control flow, and that you have to grapple with the specifics of memory layout.

However, this does not mean you should write brainfuck code first and then translate it instruction-by-instruction to Sesos!

Here are some things that are different:

You barely pay for repeated commands. For example, add 1 is a 1-byte Sesos program. add 100 is a 3-byte Sesos program. add 1000 is still a 3-byte Sesos program. This means that things that would have been prohibitively expensive in brainfuck (e.g. ++++++++++) are fine in Sesos.
Unless you have set mask on, cells are not 8-bit unsigned integers—they are signed bignums. This means that you can do things like store an offset into an array as a cell without having to worry about the possibility of the array being more than 256 elements and causing overflow.
Control flow is a bit more flexible: you have do-while loops that are guaranteed to execute at least once (with the use of nop). You also have jne, which is the equivalent of ,] in a single instruction.


Pi Bowling to 10 in 10 Your Goal: Estimate pi to at least 10 decimal places. The format is your choice - it can output as a number, as a string, as an output to STDOUT, etc.

Seems easy, right? But wait, it's not as simple as it seems...

The Rules: You get exactly 10 function calls (this includes operators). These functions cannot be ones that naturally induce or define pi, such as the arc-trig functions or a function converting degrees to radians (this also includes any function that operates as a "solver", such as one that can find roots of sin(x)). If your language has complex number capabilities, this capability cannot be used. All functions must be part of your languages built-in functions or within a standard library (loading the library does not count as an operation, but it must be a standard library, not just a popular one).

All function calls must be crucial to your code - this means that you cannot use division by one, or factorial of two. You also cannot use any literal (except for three digits in the form of one, two, or three integers)*, reading of files of any sort, or a code's ability to convert itself into values (such as a function to get the name of a variable as a string).

*Note: an exception is made for format strings for languages that require them for output. However, only formats, not actual contents, can be found in the format strings, so you can have printf("%f%f",x,y), but not printf("%f.%f",x,y).

Loops may be used, but will eat up your function calls - the 10 function calls are calls, not total functions used. Assignment does not count as an operation, but operations such as array slicing (including obtaining a single value from an array) count, in which case a[1] would count as two bytes (for []).

If you think you've found a loophole for the rules, then it's also against the rules. This is not a challenge for finding the best bending of the rules, or the best way of abusing a minor oversight in the challenge question... if your instinct is to call it a "loophole", then post it as a comment to help close it.

Scoring: This is code bowling, so you're after the highest score. But it's not the total number of bytes in your code that is being counted.

Instead, it's the sum of bytes in the functions being used. That is, if you use 4*cos(2/3) (which happens to be approximately 3.14355), then you have three functions - *, cos, and /, with the total being 5 bytes. If you were to use, for instance (using Julia), sum(map(n->1/n,1:4)), then the operations are sum, map, /, and :, for 8 bytes... but as 1/n is being called four times, it uses 7 function calls (sum, map, four instances of /, and :). User-made functions do not count towards either the function call allowance or the byte count (note: functions used in those user-made functions do count).

Additional emphasis: The point, here, is to find the best way to abuse your language's longest built-in/standard function names in the context of calculating pi. More digits of pi aren't necessary, but I will personally be more likely to upvote an answer that gets more digits than necessary.

Remember, since you're after long function names, you should probably avoid unary and binary operators, as most of these have full function equivalents (in Julia, for instance, * can be replaced by prod).

Quick Summary: You have 10 built-in function calls (includes operators/subroutines/etc). You must estimate pi to 10 decimal places. You can use a total of 3 characters for integer literals (so you can have 1 and 36, or 1 and 2 and 3, or 328, but you can't have 22 and 49). Score is count of built-in function name bytes (if the user defines the name, it doesn't count). No functions that calculate or use pi directly. No complex numbers. This is not a challenge to find loopholes.

R, 34 42 Points

I think I have complied with all the rules and scored it correctly.
Edit  Turns out not complying with the rules in the first place was a bit of a bonus.
Use this formula to calculate pi (63/25)x((17+sqrt(5)*15)/(7+sqrt(5)*15))
# set up the required numbers
a<-5
b<-2
# Calculate 5^.5 * 15                    3 Operations 11 Bytes
c<-prod(sqrt(a),sum(a,a,a))
# Calculate (17 + c) / (7 + C)           3 Operations 7 Bytes
d<-sum(a,a,a,b,c)/sum(a,b,c)
# Calculate (63/25)*d                    3 Operations 19 Bytes
pi<-prod(as.double(paste0(b,'.',a,b)),d)
# Output pi showing all digits           1 Operations 5 Bytes
strwrap(pi)

Test run
> a<-5
> b<-2
> c<-prod(sqrt(a),sum(a,a,a))  # 3 Operations 11 Bytes
> d<-sum(a,a,a,b,c)/sum(a,b,c) # 3 Operations 7 Bytes
> pi<-prod(as.double(paste0(b,'.',a,b)),d) # 3 Operations 19 Bytes
> strwrap(pi)                    # 1 Operations 5 Bytes
[1] "3.14159265380569"


Do you know your 'KVZ's? Concept

In what ways can you scramble the English alphabet so that it can still be sung to the tune Twinkle Twinkle Little Star without ruining the tune?

Rules

Swapping

Let's just assume the letters contained in each of the following sets can be swapped freely by default without ruining the tune:

{ A, J, K }
{ B, C, D, E, G, P, T, V, Z }
{ I, Y }
{ Q, U }
{ S, X, F }
{ M, N }
Therefore H, L, O, R, and W are locked in place

Output

The program needs to output a single RANDOM string (or list of characters) containing the complete English alphabet in any order provided that order satisfies the conditions above. There should be no way for you to predict which string your program will output(if we ignore seeding), meaning you can't just hardcode it.

Your program must have some positive probability (not necessarily uniform) of generating each of the \$ 9! \cdot 3! \cdot 3! \cdot 2! \cdot 2! \cdot 2! = 104509440 \$ outputs.

There are no particular formatting restrictions regarding spacing, delimiters or case, just be consistent.

Goal

Fewest bytes wins!

Examples:

KCDBPSVHIAJLMNOZQRXGUEWFYT
A,G,Z,V,P,X,C,H,Y,K,J,L,N,M,O,T,U,R,S,D,Q,B,W,F,I,E
KVTDCFBHIJALNMOPURSZQGWXYE
j c d e b x t h i k a l n m o g u r s v q p w f y z
ABCDEFGHIJKLMNOPQRSTUVWXYZ

Nonexample:

HLWROABCDEFZXYGIJKMNPQTSVU

Proof of Concept: (Python3, 529 bytes)

import random
g1 = ['A', 'J', 'K']
g2 = ['B', 'C', 'D', 'E', 'G', 'P', 'T', 'V', 'Z']
g3 = ['I', 'Y']
g4 = ['Q', 'U']
g5 = ['S', 'X', 'F']
g6 = ['M', 'N']
random.shuffle(g1)
random.shuffle(g2)
random.shuffle(g3)
random.shuffle(g4)
random.shuffle(g5)
random.shuffle(g6)
print(g1[0] + g2[0] + g2[1] + g2[2] + g2[3] + g5[0] + g2[4] + 'H' + g3[0] + g1[1] + g1[2] + 'L' + g6[0] + g6[1] + 'O' + g2[5] + g4[0] + 'R' + g5[1] + g2[6] + g4[1] + g2[7] + 'W' + g5[2] + g3[1] + g2[8])

Python 3, 140 133 124 123 bytes

d=*map(set,'AJK BCDEGPTVZ IY QU SXF MN H L O R W'.split()),
print([d[int(c,16)].pop()for c in'0111141620075581394131a421'])

Try it online!

-1 byte, thanks to Jo King

Python 2, 174 170 158 bytes

from random import*
s=''
for c in'abbbbebHcaaLffObdRebdbWecb':s+=choice(list(set(('AJK BCDEGPTVZ IY QU SXF MN '+c).split()['abcdef'.find(c)])-set(s)))
print s

Try it online!


Quaternion square root Background

Quaternion is a number system that extends complex numbers. A quaternion has the following form

$$ a + bi + cj + dk $$

where \$ a,b,c,d \$ are real numbers and \$ i,j,k \$ are three fundamental quaternion units. The units have the following properties:

$$ i^2 = j^2 = k^2 = -1 $$
$$ ij = k, jk = i, ki = j $$
$$ ji = -k, kj = -i, ik = -j $$

Note that quaternion multiplication is not commutative.

Task

Given a non-real quaternion, compute at least one of its square roots.

How?

According to this Math.SE answer, we can express any non-real quaternion in the following form:

$$ q = a + b\vec{u} $$

where \$ a,b\$ are real numbers and \$ \vec{u} \$ is the imaginary unit vector in the form \$ xi + yj + zk \$ with \$ x^2 + y^2 + z^2 = 1 \$. Any such \$ \vec{u} \$ has the property \$ \vec{u}^2 = -1 \$, so it can be viewed as the imaginary unit.

Then the square of \$ q \$ looks like this:

$$ q^2 = (a^2 - b^2) + 2ab\vec{u} $$

Inversely, given a quaternion \$ q' = x + y\vec{u} \$, we can find the square root of \$ q' \$ by solving the following equations

$$ x = a^2 - b^2, y = 2ab $$

which is identical to the process of finding the square root of a complex number.

Note that a negative real number has infinitely many quaternion square roots, but a non-real quaternion has only two square roots.

Input and output

Input is a non-real quaternion. You can take it as four real (floating-point) numbers, in any order and structure of your choice. Non-real means that at least one of \$ b,c,d \$ is non-zero.

Output is one or two quaternions which, when squared, are equal to the input.

Test cases

   Input (a, b, c, d)  =>  Output (a, b, c, d) rounded to 6 digits

 0.0,  1.0,  0.0,  0.0 =>  0.707107,  0.707107,  0.000000,  0.000000
 1.0,  1.0,  0.0,  0.0 =>  1.098684,  0.455090,  0.000000,  0.000000
 1.0, -1.0,  1.0,  0.0 =>  1.168771, -0.427800,  0.427800,  0.000000
 2.0,  0.0, -2.0, -1.0 =>  1.581139,  0.000000, -0.632456, -0.316228
 1.0,  1.0,  1.0,  1.0 =>  1.224745,  0.408248,  0.408248,  0.408248
 0.1,  0.2,  0.3,  0.4 =>  0.569088,  0.175720,  0.263580,  0.351439
99.0,  0.0,  0.0,  0.1 =>  9.949876,  0.000000,  0.000000,  0.005025

Generated using this Python script. Only one of the two correct answers is specified for each test case; the other is all four values negated.

Scoring & winning criterion

Standard code-golf rules apply. The shortest program or function in bytes in each language wins.

APL (NARS), 2 bytes

√

NARS has built-in support for quaternions. ¯\_(⍨)_/¯


Create a Paint program! Introduction
One day, you were showing your kid how to draw on a computer. You type mspaint.exe in the run bar. To your horror, it says "No items match your search". You must create a simple version of paint so your kid can draw!
Challenge
You must create a simple drawing program. To do this, open a white display window (larger than 99x99 pixels). Anytime the mouse is pressed down, change the pixel that the mouse is on to black.
This is code-golf, so shortest answer in bytes wins!

8086 machine code, 32 31 28 26 bytes

00000000  b8 0f 00 cd 10 b8 02 10  ba 18 01 cd 10 b8 03 00  |................|
00000010  cd 33 4b b8 01 0c eb f3  3f 00                    |.3K.....?.|
0000001a

Assumes the presence of a VGA graphics card, and any Microsoft-compatible mouse driver.

-2 bytes thanks to @berendi!

How it works:

            |   org 0x100
            |   use16
b8 0f 00    |       mov ax, 0x000f      ; set screen mode: 640x350 monochrome
cd 10       |       int 0x10            ; call video bios
b8 02 10    |       mov ax, 0x1002      ; set palette
ba 18 01    |       mov dx, palette     ; pointer to palette data
cd 10       |   @@: int 0x10            ; call video bios
b8 03 00    |       mov ax, 0x0003      ; get mouse position in (CX, DX) and button status in BL
cd 33       |       int 0x33            ; call mouse driver
4b          |       dec bx              ; if no buttons pressed, --BX = 0xFFFF (invalid page)
b8 01 0c    |       mov ax, 0x0c01      ; plot pixel with color AL at (CX, DX) in page BH
eb f3       |       jmp @b              ; repeat
3f 00       |   palette db 0x3f, 0x00   ; palette in 2:2:2 rgb. color 0 = white, 1 = black.
            |                           ; this should be a 17-byte struct, but we only care about the first two colors here

That's all there is to it. No magic involved, just a few function calls.


Shh... Can You Split a Secret? In Applied Cryptography by Bruce Schneier (which I have been reading quite a lot recently), a protocol for splitting secrets is discussed. Here is a brief description:

  Trent generates a random byte string, R, the same length as the message, M.
  Trent XORS M with R to make S.
  He gives R to Alice and S to Bob.

Your task is to, given an input, split the input into two output files or print the split secret to STDOUT. One output/part of output should contain the random string; the other should contain the original input XOR'd with the random string. Input and output may be to/from files or to/from STDIN/STDOUT. Outputting to STDERR is also allowed.
There are a few restrictions, however:

Your program must take 1 input (1 input filename & 2 outputs if doing file I/O), and output the random string and the original string XOR'd with that random string into the other.
Your program must be cryptographically secure. All random number generators must be cryptographically secure. For example, /dev/random is fine, but the Mersenne Twister (usually randint(number,number) is not. Any random number generator must be explicitly cryptographically secure.

If you want to know anything more about what "cryptographically secure" means, check here.

Standard rules and loopholes apply.

This is code-golf, so the code with the fewest bytes will win.
May the best coder prosper...


Create an interface that fits the XKCD Types colors.rgb("blue") yields "#0000FF". colors.rgb("yellowish blue") yields NaN. colors.sort() yields "rainbow"

Using the rules set out in the image and its title text (quoted here), create a program that accepts all the given input and displays the appropriate output.

Input can be taken with stdin or nearest equivalent. There should be a line like [n]> on which to type it, and n increases by 1 each command. It should start at 1.
The result should be displayed using stdout or nearest equivalent. There should be a => on each line of output.

All 13 conditions, plus the 3 in the title (quoted) must work.

This is code golf, so shortest answer wins.

Python 3, 700 698 697 689 683 639 611

Tabs as indentation.

from ast import*
E=literal_eval
O='=>%s\n'
P=print
I=int
def Q(a):P(O%a)
def W(a):Q('"%s"'%str(a))
def gb(a):W(_ if'y'in a else'#0000FF')
def t():W('rainbow')
def FLOOR(n):P(O%'|'*3+(O%'|{:_^10}').format(n))
def RANGE(*a):Q([('"','!',' ','!','"'),(1,4,3,4,5)][len(a)])
c=0
while 1:
    try:
        c+=1;A,*B=input('[%d]>'%c).split('+')
        if not A:W(c+I(B[0]))
        elif A=='""':Q("'\"+\"'")
        elif B:
            A=E(A);B=E(B[0])
            if A==B:Q('DONE')
            elif type(A)==list:Q(A[-1]==B-1)
            elif type(B)==list:W([I(A)])
            else:W(A+I(B))
        else:eval(A.lstrip('colrs.'))
    except:Q('Na'+['N','P','N.%s13'%('0'*13)][('-'in A)+len(B)])

Since this uses a bare Except you can't Ctrl-C it. Ctrl-Z and kill %% work though

Some of the conditions are generalized and others will only work with exact input.

A+"B" will work with any A and B not just when A == B
"A"+[] will work for any A that can be converted to an int (Includes hex and binary strings e.g 0xff and 0b01010)
(A/0) will work for any A, Eval Causes DivideByZeroError which is handled in the except
(A/0)+B will work with any A or B. literal_eval (E) raises an error.
""+"" only works for the + sign. Anything else will print NaN, NaP or NaN.00...
[A, B, C]+D works by checking that D == C+1 so will work for any length of list and any numbers.
^^
2/(2-(3/2+1/2)), Anything that fails to parse that has - with a + somewhere after it will output NaN.000...13
RANGE(" ") Hardcoded
+A will work for any A. Ouputs "current_line_number+A"
A+A works for any A as long as they are the same and are bulitin python types
RANGE(1,5) Hardcoded.
FLOOR(A) works for any A.
colors.rgb("blue") The lstrip in eval turns this in gb("blue") which has a hardcoded response.
colors.rgb("yellowish blue") The lstrip in eval turns this in gb("yellowish blue") which attempts to use a non existent variable if y is present in the arguement causing an error which the except turns into NaN
colors.sort() The lstrip turns this into t() which has a hardcoded response.

Brainsteel pointed out an error in my assumption for rule 10.


Calculate Swatch Internet Time Output the current time of day as Swatch Internet Time.

Specifically, output a three-digit (zero-padded) number of ".beats" (1000ths of a day) which represent the current time of day in the Swatch Internet Time time zone of UTC+01:00 ("Biel Meantime").

For example, if the current time in UTC is 23:47, then it is 00:47 in UTC+1 ("Biel Meantime"), and the output would be 032.

Examples:

UTC Current Time  ->  SIT Output
23:47             ->  032
23:00             ->  000
11:00             ->  500
14:37             ->  651

The program should produce this output then immediately exit.

Output is to standard output (or equivalent). Must be a complete, runnable program, not a function. The program takes no input; it outputs the current time.

PHP, 12 bytes

<?=@date(B);

But it can only be so short because PHP has built-in Swatch Internet Time support. So this answer isn't much fun.

<?= exits HTML mode and evaluates an expression, then echoes it.

@ silences an error.

date() outputs the current time, formatting it with a given format string.

B is an undefined constant. In PHP, if you reference a constant that doesn't exist, you get back a string containing its name, and it also produces a “notice”-level error. Here, the @ suppresses that error. B is the date() format code for Swatch Internet Time.

; terminates the expression.

If we assume PHP is being run with the default error-reporting settings, where “notices” are silenced, we could skip the @, and it would only be 11 bytes.


Shortest Game of Life Conway's Game of Life is the classic example of cellular automation. The cells form a square grid and each has two states: alive or dead. On each turn, each cell simultaneously updates according to its state and those of its eight neighbours:

A live cell remains alive if it has exactly two or three live neighbours
A dead cell becomes alive if it has exactly three live neighbours

Your mission, should you choose to accept it, is to code the shortest Game of Life implementation in your favourite language.

The rules:

The grid must be at least 20x20
The grid must wrap around (so the grid is like the surface of a Torus)
Your implementation must allow the user to input their own starting patterns
GoL is a bit pointless if you can't see what is happening, so there must be visual output of the automaton running, with each turn's result being shown for long enough to be seen!

Python, 219 chars

I went for maximum golfage, with just enough interface to satisfy the question.

import time
P=input()
N=range(20)
while 1:
 for i in N:print''.join(' *'[i*20+j in P]for j in N)
 time.sleep(.1);Q=[(p+d)%400 for d in(-21,-20,-19,-1,1,19,20,21)for p in P];P=set(p for p in Q if 2-(p in P)<Q.count(p)<4)

You run it like this:

echo "[8,29,47,48,49]" | ./life.py

The numbers in the list represent the coordinates of the starting cells.  The first row is 0-19, the second row is 20-39, etc.

Run it in a terminal with 21 rows and it looks pretty snazzy.


Jelly, 10 5 bytes

ẋ"z0Ä

Try it online!

How it works

ẋ"z0Ä  Main link. Argument: A (array)

       e.g. [2, 1, 3, 1]

ẋ"     Repeat each n in A n times.

       e.g. [[2, 2   ]
             [1      ]
             [3, 3, 3]
             [1      ]]

  z0   Zipfill 0; read the result by columns, filling missing elements with 0's.

        e.g. [[2, 1, 3, 1]
              [2, 0, 3, 0]
              [0, 0, 3, 0]]

    Ä  Take the cumulative sum of each row vector.

       e.g. [[2, 3, 6, 7]
             [2, 2, 5, 5]
             [0, 0, 3, 3]]


Tips for golfing in MathGolf What general tips do you have for golfing in MathGolf? I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to MathGolf (for tips which can be applied to loads of programming languages, look at the general tips).

Writing 513 in a MathGolf program will push three separated digits (5;1;3), instead of the number 513 itself.
In MathGolf there are therefore quite a lot of 1-byte builtins for numbers: -3 through and including 38; 60; 64; 100; 128; 256; 512; 1000; 1024; 2048; 3600; 4096; 10000; 86400; 100000; 1000000; 10000000; 100000000.

However, for other numbers it can sometimes be tricky to find the shortest way to generate it, so here an overview of the integers in the range [1, 1000]:

NOTE: This is W.I.P. I will add more when I have some time. I was unable to make an evaluation program to check all possibilities (thus far), so these were done by hand.. I've also made it a community wiki, so if anyone else finds shorter alternatives or wants to continue with the numbers, feel free to edit it.
Of course many variations can be found for certain numbers, as can be seen here and here. So the list below contains just one of the shortest variations.

-3-0:   d, c, b, 0
1-10:   1, 2, 3, 4, 5, 6, 7, 8, 9, ♂
11-20:  A, B, C, D, E, ☻, F, G, H, I
22-30:  J, K, L, M, N, O, P, Q, R, S
31-40:  T, ♥, U, V, W, X, Y, Z, Z), Z⌠
41-50:  Dx, J∞, Vx, K∞, K∞), L∞, L∞), M∞, 7², N∞       TODO: 2-byters for 45,47
51-60:  Ex, O∞, Wx, P∞, ♂f, Q∞, ╟╫, R∞, ╟(, ╟
61-70:  ☻x, T∞, Xx, ♦, ♦), U∞, U∞), V∞, V∞), W∞        TODO: 2-byters for 67,69
71-80:  Fx, X∞, Yx, Y∞, Y∞), Z∞, Z∞), Z∞⌠, ♦E+, ♦F+    TODO: 2-byters for 75,77,78,79,80
81-90:  Gx, Qx, Zx, Zx), Zx⌠, ♦K+, ♦L+, R■, ♂f, ♦O+    TODO: 2-byters for 84,85,86,87,90
91-100: Hx, Rx, ♦R+, T■, ♦T+, ♦U+, ♦V+, ♀⌡, ♀(, ♀      TODO: 2-byters for 93,95,96,97
TODO: Continue through 1000

Here is a universal constant-generating method in MathGolf. Example (generating 513):

û☺☻$

This defines a two-character string and takes its ord code. The ord code of ☻ is 2, and the ord code of ☺ is 1. The ord code of this string is therefore 2*256+1=513.

Taking the ord code also works for single characters. (Constants generated by this method are likely to be unoptimal.) This one returns 2.

'☻$

Also works for string length 3 and so on...

ùUTS$
83*256*256+84*256+85=5461077


Dense Number Sequence OEIS: A167171
A dense number is a number that has exactly as many prime divisors as non-prime divisors (including 1 and itself as divisors). Equivalently, it is either a prime or a product of two distinct primes. The first 100 dense numbers are:
2, 3, 5, 6, 7, 10, 11, 13, 14, 15, 17, 19, 21, 22, 23, 26, 29, 31, 33, 34, 35, 37, 38, 39, 41, 43, 46, 47, 51, 53, 55, 57, 58, 59, 61, 62, 65, 67, 69, 71, 73, 74, 77, 79, 82, 83, 85, 86, 87, 89, 91, 93, 94, 95, 97, 101, 103, 106, 107, 109, 111, 113, 115, 118, 119, 122, 123, 127, 129, 131, 133, 134, 137, 139, 141, 142, 143, 145, 146, 149, 151, 155, 157, 158, 159, 161, 163, 166, 167, 173, 177, 178, 179, 181, 183, 185, 187, 191, 193, 194

Given a nonnegative integer n, output dense(n). n may be 0-indexed or 1-indexed.
Reference implementation (Sage)
import itertools

def dense_numbers():
    n = 1
    while True:
        prime_divisors = [x for x in divisors(n) if x.is_prime()]
        non_prime_divisors = [x for x in divisors(n) if not x.is_prime()]
        if len(prime_divisors) == len(non_prime_divisors):
            yield n
        n += 1

N = 20

print itertools.islice(dense_numbers(), N, N+1).next()

Try it online

Jelly, 9 bytes

ÆE²Sḍ2µ#Ṫ

Reads from STDIN and uses 1-based indexing. Try it online!

How it works

ÆE²Sḍ2µ#Ṫ  Main link. No arguments. Implicit argument: 0

      µ#   Read an integer n from STDIN and execute the chain to the left for
           k = 0, 1, 2, ... until n of them return a truthy value.
           Return the array of matches.
ÆE           Compute the exponents of k's prime factorization.
  ²          Square each exponent.
   S         Compute the sum of all squares.
    ḍ2       Test if 2 is divisible by the result (true iff  the sum is 1 or 2).
        Ṫ  Tail; extract the last (n-th) matching value of k.


Saying a number in the shortest way A string of digits (positive integer) can be converted to plain English in various ways. For instance, 115 can be read as "hundredfifteen", "oneonefive", "elevenfive", "twoonesfive". So question's challenge is to output the shortest string representation for a given digits string.

Rules:

The input string can start with a zero and the output should account for that.
Maximum length of input is 18. So you deal with numbers less than a Quintillion.
You should use only the following mathematical words for numbers in your output: zero, one, ..., nine, ten, eleven, ..., twenty, ..., ninety, hundred, million, billion, trillion. You can use their plural forms for sequences (i.e. "fivetens" for 1010101010). No synonyms (i.e. "oh" for 0) or slang (i.e. legs for 11) are allowed. You don't need to include a "one" prefix for cases like 100, just "hundred" is fine.
You don't need to put spaces between different words in your output.
The output shouldn't be ambigous. This means, from the output string one should be able to determine the input unambigously. So for 705 you can't output "seventyfive" since it may be the output of 75 also. You may use "and" if that'll remove ambiguity, otherwise you don't need to include "and" in your output.
Winner is the entry that will have the shortest code length excluding import statements and if not some user finds out a deficit in the code (i.e. a shorter representation than the program spits out for a particular input ).
Please post your output for the following test cases to make evaluation easier: 1234, 00505, 122333, 565577555555666888, 1000010, 10001000, 10101010.
No reading from an input file, so usage of a dictionary or hash map should count towards your code length.

edit1: Changed the competition type to code-golf per comments and added test cases.

edit2: Restricted the words that can be used in the output. Thanks to @PeterTaylor for the examples.

4

This is cheeky and a cheat. I wrote this script about a year ago based off of this comic (tad of profanity).

The idea goes like this. Given any number as a string, adding the number of characters will eventually condense to 4. Four itself is 4 letters long and thus the end of the line.

For example:

10 -> 'ten'
'ten' -> 3 (letters long)
3 -> 'three'
'three' -> 5 (letters long)
5 -> 'five'
'five' -> 4 (letters long)

I verified up to 100,000. Very hacky but got the job done:

to20 = [
        'zero'
        ,'one'
        ,'two'
        ,'three'
        ,'four'
        ,'five'
        ,'six'
        ,'seven'
        ,'eight'
        ,'nine'
        ,'ten'
        ,'eleven'
        ,'twelve'
        ,'thirteen'
        ,'fourteen'
        ,'fifteen'
        ,'sixteen'
        ,'seventeen'
        ,'eighteen'
        ,'nineteen'
        ]

by10s = ['twenty'
         ,'thirty'
         ,'forty'
         ,'fifty'
         ,'sixty'
         ,'seventy'
         ,'eighty'
         ,'ninety'
         ]

by10powers = [
             'hundred'
             ,'thousand'
             ]

def cosmetize(number):

    # the number is too damn high!
    if number >= 100000:
        return "Too high"

    numstr = str(number)

    # Do ones
    if number < 10:
        return to20[number]

    # Pshh.. who needs zero anymore?
    to20[0] = ''

    # Do tens
    numstr10 = numstr[-2:]
    if int(numstr10) < 20:
        numstr10 = to20[int(numstr10)]
    else:
        numstr10 = by10s[int(numstr10[0])-2] + to20[int(numstr10[1])]
    if number < 100:
        return numstr10

    # Do hundreds
    numstr100 = numstr[-3]
    if numstr10 == '':
        numstr10 = ""
        numstr100 = to20[int(numstr100)] + by10powers[0]
    elif int(numstr[-2:]) > 19:
        numstr100 = to20[int(numstr100)] + by10powers[0]
        numstr100 += 'and'
    else:
        numstr100 = 'and'
    if number < 1000:
        return numstr100 + numstr10

    # Do thousands
    numstr1000 = numstr[:-3]
    if numstr100 == 'hundred':
        numstr100 = ""
    if int(numstr1000) < 20:
        numstr1000 = to20[int(numstr1000)] + by10powers[1]
    else:
        numstr1000 = by10s[int(numstr1000[0])-2] + by10powers[1]

    return numstr1000 + numstr100 + numstr10

i = 0
mx = []
z = 0
while i < 100000:
    length = cosmetize(i)
    x = [length]
    while not len(length) == 4:
        length = cosmetize(len(length))
    i += 1

# No inifinite loop? what magic is this?
print "OMG"


Find unique elements based on a given key Input

Take a list of values xi each paired with a key yi.

[(x1, y1), (x2, y2), ...]

Output

Return a list L containing only values from the set {xi}.

The length of L must be equal to the number of unique keys k in the set {yi}.
For each unique key k there must be a value from {xi} that has key k.

Details

Standard loopholes disallowed.
You can assume all values in the input will be nonnegative integers.
There may be duplicate values and keys.
You can assume there is at least one value/key pair in the input.
If you prefer to take two lists of equal length as input (one for values, one for keys) that is fine.
You may not take any other input.
The order of the list you output does not matter.
The xi you choose for each key does not matter.

For example, with input [[0, 0], [1, 3], [2, 3]] you can return either [0, 1] or [0, 2] or any permutation of these.

Examples

[[1, 2], [3, 2], [3, 0]]  -> [1, 3] or [3, 3]
[[7, 2], [7, 0], [7, 1]]  -> [7, 7, 7]
[[4, 0], [4, 0], [9, 1], [5, 2]]  -> [4, 9, 5]
[[9, 1], [99, 10], [5, 5], [0, 3]]  -> [9, 99, 5, 0]

Fewest bytes wins.

Python 2, 34 bytes

lambda a,b:dict(zip(b,a)).values()

Try it online!

Takes input as list of values and list of keys.
Generate dictionary, swapping keys and values, which leaves only unique y values. Return all corresponding x values


Calculate the prime factors We had a prime factorization challenge a while ago, but that challenge is nearly six years old and barely meets our current requirements, so I believe it's time for a new one.

Challenge

Write a program or function that takes as input an integer greater than 1 and outputs or returns a list of its prime factors.

Rules

Input and output may be given by any standard method and in any standard format.
Duplicate factors must be included in the output.
The output may be in any order.
The input will not be less than 2 or more than 231 - 1.
Built-ins are allowed, but including a non-builtin solution is encouraged.

Test cases

2 -> 2
3 -> 3
4 -> 2, 2
6 -> 2, 3
8 -> 2, 2, 2
12 -> 2, 2, 3
255 -> 3, 5, 17
256 -> 2, 2, 2, 2, 2, 2, 2, 2
1001 -> 7, 11, 13
223092870 -> 2, 3, 5, 7, 11, 13, 17, 19, 23
2147483646 -> 2, 3, 3, 7, 11, 31, 151, 331
2147483647 -> 2147483647

Scoring

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

Pyth, 1 byte

P

I like Pyth's chances in this challenge.


Write a self replicating program that stops replicating after "printing" "Hello world!" with the filenames Write a self replicating program, in the source code filename H.*, contianed in an empty folder then manually compile and run or just run the program if your chosen language is dynamic, and it should then just create a new source file, e.*, with the same exact source code, and automatically compile/run that new program, which makes the new source file l.*, etc. until the source file !.* is made, and that program should do essentially nothing once it is compiled/run. "Hello world!" has some repeated characters, so the second character should be created by a similar filename, just with a new <space> at the end. Programs that just make/compile source files from the single instance of the program are invalid, and yes, " " is a valid filename. It should appear to say "Hello World!" when viewed in the file explorer sorted by time created.

For example, if you were to attempt this challenge in python, than you would create the source file H.py, which complies and runs e.py, which then itself creates l.py, that file l .py, o.py, .py, w.py, o .py, r.py, l  .py and d.py which finally creates and runs !.py, which does not do anything once run.

Python 2, 194

import os,sys
h,A='H|e|l|l |o| |w|o |r|l  |d|!'.split('|'),sys.argv[0]
d,a,F=dict(zip(h,h[1:])),A.split('.')[0],file
if a in d:o=d[a]+'.py';F(o,'w').write(F(A).read());os.popen('python "'+o+'"')


Compressing boolean formulae Syntax

~ not
/\ and
\/ or
t true
f false
P, Q, FISH, etc: variables

(Operators are given in order of precedence)

Introduction

Some boolean formulae can be changed to different forms to make them shorter. For example, the formula

~(~P /\ ~Q)

can be changed to the shorter form

P\/Q

while the formula

P \/ ~P

can be changed to the shorter form

t

Challenge

In this challenge, you are required to write a program that, given any boolean formula using only /\, \/, ~, t, f, parentheses, boolean variables (in uppercase), and whitespace, outputs a shortest form (since there may be more than one shortest form) in characters of that expression which is equivalent for all assignments of the variables. Shortest code (in any language) wins. I/O can be done in any reasonable manner.

Also, since answers are difficult to verify, it would be helpful (but isn't required) to include a brief explanation of how the code works.

Python 616
Not particularly efficient, but works in reasonable time for inputs whose results are around 5 or 6 characters. To check a string to see if it matches, it loops through every possible combination of truth/false values for all the variables and makes sure each one agrees. Using this it checks every possible string comprised of the relevant characters (not even necessarily a syntactically correct one).
It actually will print every equivalent expression (of every size) and does not actually ever terminate.
Code:
c=['t','f'];o=['1 ','0 ']
def e(s,v):
 for k in v:s=s.replace(k,v[k])
 return eval(s)
def z(t,p='~/\\() '):
 w=[]
 if p=='':return[t]*(t not in['']+c)
 for s in t.split(p[0]):w.extend(z(s,p[1:]))
 w.sort(key=lambda v:-len(v));return w
def m(v):
 l=list('~\\/()')+v
 for s in l:yield s
 for r in m(v):
    for s in l:yield s+r
def n(x):
 if x<1:yield []
 else:
    for l in n(x-1):
     for b in o:yield[b]+l
t=raw_input();v=z(t)+c;l=len(v)
for s in m(v):
 g=1
 for y in n(l):
    y[-2:]=o;d=dict(zip(v+['/\\','\\/','~'],y+['and ','or ','not ']))
    try:
     if e(s,d)!=e(t,d):g=0
    except:g=0
 if g:print s

Input/Ouput:
> ~(~P /\ ~Q)
Q\/P
P\/Q
...

> P /\ ~P
f
~t
...

> (P \/ Q) /\ P
P
(P)
...