Highly composite numbers A highly composite number is a positive integer that has more divisors than any smaller positive integer has. This is OEIS sequence A002182. Its first 20 terms are
1, 2, 4, 6, 12, 24, 36, 48, 60, 120, 180, 240, 360, 720, 840, 1260, 1680, 2520, 5040, 7560

For example, 4 is in the sequence because it has 3 divisors (namely 1, 2, 4), whereas 3 only has 2 divisors, 2 also has 2 divisors, and 1 has 1 divisors.
Challenge
Given a positive integer input n, output either the n-th highly composite number or the first n highly composite numbers, at your choice (but the choice must be the same for every input n).
Rules
The program or function should theoretically work for arbitrarily large inputs given infinite time and memory, and without considering data type limitations. Essentially, this means no hardcoding a finite number of values.
In practice, the program or function should run in a reasonable amount of time, say less than 1 minute, for n up to 20. Maximum input or output may be limited by your language standard data type (but again, the algorithm should theoretically work for arbitrarily large numbers).
Any reasonable input and output format is allowed, including unary.
Code golf. Fewest bytes wins.

Jelly, 15 bytes

,®ÆDL€ṛ©0>/?µƓ#

For input n, this prints the first n highly composite numbers.

For n = 20, it takes less than two seconds on Try it online!

How it works

,®ÆDL€ṛ©0>/?µƓ#  Main link. No implicit input.

            µ    Push the chain to the left on the local link stack.
             Ɠ   Read an integer n from STDIN.
              #  Execute the chain for k = 0, 1, 2, ..., until it returned a truthy
                 value n times. Return the list of matches.

,®               Pair k with the value in the register (initially 0).
  ÆD             Compute the divisors of k and the register value.
    L€           Count both lists of divisors.
           ?     If
         >/        k has more divisors than the register value:
      ṛ©             Save k in the register and return k.
        0          Else: Return 0.

Alternate version, 13 bytes (non-competing)

While the below code worked in the latest version of Jelly that precedes this challenge, the implementation of M was very slow, and it did not comply with the time limit. This has been fixed.

ÆDL®;©MḢ’>µƓ#

Try it online!

How it works

ÆDL®;©MḢ’>µƓ#  Main link. No implicit input.

          µ    Push the chain to the left on the local link stack.
           Ɠ   Read an integer n from STDIN.
            #  Execute the chain for k = 0, 1, 2, ..., until it returned a truthy
               value n times. Return the list of matches.

ÆD             Compute the divisors of k.
  L            Count them.
   ®;          Append the count to the list in the register (initially 0 / [0]).
     ©         Save the updated list in the register.
      M        Obtain all indices the correspond to maximal elements.
       Ḣ       Retrieve the first result.
        ’>     Subtract 1 and compare with k.
               This essentially checks if the first maximal index is k + 2, where
               the "plus 2" accounts for two leading zeroes (initial value of the
               register and result for k = 0).


Omit needless spaces for me A great Python golfing tip is to omit needless spaces. But if you are like me, you don't always have the time to search for which spaces to remove. If only there was a way to speed up the process...

Task

Given a single line of Python, as input, return/output a new line which omits all needless spaces. The table below shows which spaces are needless, and must be removed for maximum golfage.

   | L D S
---+-------
 L | s s n
 D | n - n
 S | n n n

First token is row, second token is column
L: Letter
D: Digit
S: Symbol

s: space
n: no space
-: never happens (except multidigit numbers)

Clarifications

What is considered a letter, digit, and symbol?

Letter: _ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz
Digit: 0123456789
Symbol: !"\#$%&'()*+,-./:;<=>?@[]^`{|}~

You can assume that all characters in the input are either a Letter, Digit, Symbol, or Space.
You can assume that there will be no such test case where two digits are separated by one or more spaces
You can assume that all test cases contain valid Python syntax
You can assume that there will be no leading or trailing spaces.
Follow the above rules for omitting spaces, regardless of whether omitting them will produce incorrect or different code

Test Cases

Input

print ( "Hello, World!" )
eval("eval('eval(`1`)')")
_  =  '_  =  %  r  ;  print _  %%  _'  ;  print _  %  _
[ 1for _ in range(10, 6 , -1)     ]
print 16

Output

print("Hello,World!")
eval("eval('eval(`1`)')")
_='_=%r;print _%%_';print _%_
[1for _ in range(10,6,-1)]
print 16

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

Retina 0.8.2, 22 21 bytes

Saved a byte thanks to a mysterious hint from @Neil :P

(\d|\W) +
$1
 (\W)
$1

Try it online!


Chemical sentences! Decrypting Background

You are sitting in chemistry class and your friend keep sending you these strange letters. It is your job to decrypt the messages into words.

This is the inverse of this challenge.

The Challenge

Input: A list or a string of integers from 1 to 118.

Output: The words for each chemical element if possible. Otherwise return False, throw an error, or blank. Note in your program 0 must return a whitespace or newline. Ignore all integers not in range.

Test cases
Input 1:

9 53 75

Output 1:

fire

Input 2:

91 120 91

Output 2:

papa

Input 3:

9 53 75 0 53 16 0 9 92 7

Output 3:

fire is fun

Note: Again no built in functions for generating the periodic system or external libaries. Standard loopholes are not allowed.

Scoring

Submissions will be scored in bytes. I recommend this website to keep track of your byte count, though you can use any counter you like.

This is code-golf, so the lowest score wins!


Navigate text with arrow keys Background

Most (halfway decent) text editors allow you to navigate text using the arrow keys.  Up and down allow you to navigate lines, while left and right move across a line but also wrap around.  Furthermore, if the line is shorter than your cursor's X position, the cursor appears at the end of the line but returns to the same X position if you keep moving up or down.  Perhaps the following visual explanation will help:

Examples Of Motion

A simple sample of text could look like this.  The cursor will be inserted between two characters in this text, or at an end.

-----
---
------

let's put the cursor here:

X-----
---
------

move down (v):

-----
X---
------

move left (<):

-----X
---
------

v

-----
---X
------

v (notice how the X position of the cursor has been maintained)

-----
---
-----X-

^

-----
---X
------

>  (more line wrapping)

-----
---
X------

<

-----
---X
------

^ (the X-position from earlier is no longer maintained due to the left-right motion)

---X--
---
------

The Challenge

Given several lines of ASCII test, find the shortest path from the start location to the end location.  The start location is represented by ^ and the end location is represented by $, and there will only be one of each.  These aren't considered part of the text and don't contribute to that line's "length."

The input will consist of several non-blank lines of text.  Output will be a series of ^v<> characters that show one of the shortest paths.  You may optionally assume an additional newline at the end of each, but that is not included as part of the navigable text.

You can write a program or named function.  The winner will be the shortest submission, measured in bytes.

Example I/O

^Squares
are
fun$ny

vv<v  (which is better than the naive vv>>>)

Squares
^are
funny$

<vv

Alp$habet^
Song

v<^

Mary had a little lamb,
His fleece was white as snow,
And$ everywhere that ^Mary went,
The lamb was sure to go.

^^>>>>v>>>

$^degenerate case

(no output)

CJam, 139 bytes

Well this took many hours to come to something that feels done. It feels like the time it takes to aggressively optimize CJam code is something larger than O(n) with respect to the size of the code...

You can try it online, but for any input for which the best path is at least 6 operations or so, you should probably try it offline with a faster interpreter.

Squished:

q_'$-_'^-:T;'^#\'^-'$#W{)2$5Y$5b+{:D[L"_T<W%_N#)_@>N+N#X-Ue>+-"_"W%-U"--2'<t2'>t'++'(')]=~0e>T,e<D3/1$T<N\+W%N#X?:X;}/2$-}g5b{" ^v<>"=}%]W=

Expanded and commented:

q               "Read the input";
_'$-            "Remove the end marker";
_'^-:T;         "Remove the start marker and save the text";
'^#             "With only the end marker removed, locate the start marker";
\'^-'$#         "With only the start marker removed, locate the end marker";
W               "Initialize the path number to -1";
{               "Do...";
  )               "Increment the path number";
  2$              "Initialize the cursor position to that of the start marker";
  5Y$5b+          "Convert the path number to base 5, then add a leading 5
                   (the leading 5 will act to initialize the column memory)";
  {:D             "For each digit in the path digit string:";
    [               "Begin cases:";
      L               "0: Do nothing";
      "_T<W%_N#)_@>N+N#X-Ue>+-"
"REFS: [   1   ][  2  ][ 3 ]45
                       1: [1] Calculate the distance to the end of the previous
                              line (0 if no such line)
                          [2] Calculate the length of the previous line (0 if
                              no such line)
                          [3] Calculate the distance to move backwards in the
                              previous line as the maximum of the length of the
                              previous line minus the column memory and 0
                          [4] Calculate the total distance to move as the sum
                              of [1] and [3]
                          [5] Subtract [4] from the cursor position";
      _"W%-U"-        "2: Start with a base of the logic of case 1, but with a
                          few operations adjusted.";
      -2'<t2'>t       "   [1] Calculate the distance to the *start* of the
                              *next* line (0 if no such line)
                          [2] Calculate the length of the *next* line (0 if no
                              such line)
                          [3] Calculate the distance to move *forwards* in the
                              *next* line as the *minimum* of the length of the
                              *next line* and *the column memory*
                          [4] Calculate the total distance to move as the sum
                              of [1] and [3]";
      '++             "   [5] *Add* [4] *to* the cursor position";
      '(              "3: Decrement the cursor position";
      ')              "4: Increment the cursor position";
    ]=~             "Execute the case corresponding to the path digit mod 5";
    0e>T,e<         "Clamp the cursor position to [0, text length]";
    D3/             "Check if the path digit is not 0, 1, or 2...";
    1$T<N\+W%N#     "Calculate the current column";
    X?:X;           "If the above check succeeded, update the column memory";
  }/              "End for each";
  2$-             "Subtract the end marker position from the cursor position";
}g              "... While the above subtraction is nonzero";
5b              "Convert the path number to base 5";
{" ^v<>"=}%     "Map each digit in the path string to its operation symbol";
]W=             "Clean up";

Overall, this is a pretty straightforward solution. It "executes" the digits of the base-5 representation of a path number that is incremented every iteration, starting with 0, until a path works. The digits 1-4 map to the operations up, down, left, and right, and 0 does nothing. The first iteration using a path of just 0 catches the degenerate case. All other paths that contain a 0 are never selected because they're just versions of already-tested paths with added no-ops.

The state is modeled in as minimalistic of a way as possible: the text with start and end markers removed, the cursor position in the text, and the "column memory." Newlines are mostly treated like any other character, so there's no concept of a row, and the cursor position is just an index. This makes moving left and right dead simple, which are just implemented as decrement and increment (with clamping to the size of the text). Moving up and down is a bit trickier, but still manageable.

Code reuse was a pretty vital optimization tactic. Examples of this include:

Writing the code for moving up in a way such that it's smaller to generate the code for moving down at runtime than to write its own code. This is done by copying the code for moving up and removing/replacing a few characters.
Updating the "column memory" is done conditionally based on the path digit divided by 3 instead of it being coded into the logic of the operation. This also allows initialization of the column memory by adding a dummy 5 operation to the start of the path string, which also just so happens to use the 0 no-op logic due to circular array indexing and there being only 5 defined operations.

Overall, I'm very happy with how this came out. This is definitely the most work I've put into a code golf answer to date (for something that fits into a tweet!?). The run time is pretty abysmal, though. CJam isn't exactly the fastest language to begin with and this algorithm has a complexity of something like O(m*5n), where m is the size of the input and n is the size of the output. Good thing speed doesn't count!


A small puzzle. Why does this code work the way it does? This was given to me by a friend of mine, it prints out 0 through 9. We have been quite puzzled over this. Does anyone know why this works?

#include <iostream>

using namespace std;

void x(int a)
{
    *(&a-1) += a;
}

int main()
{
    for(int i = 0; i < 10; ++i)
    {
        x(8);
        i = 0;
        cout << i << endl;
    }
}

First of all, the line *(&a-1) += a; is undefined behavior, so this could do anything depending on compiler version, flags used, alignment of the stars, etc.

That said, the reason why it works in your case is probably because &a-1 happens to point to the return address of x, and incrementing it by 8 causes the i = 0; to be skipped.


The jumping digits to letters transformation Imagine you have an infinite sequence of the alphabet repeated infinitely many times:

abcdefghijklmnopqrstuvwxyzabcd...

You start at index 0, which corresponds to the letter a, and the should_write boolean flag is False.

The input is a list or string of single-digit numbers. For each number n in the input, you should:

Print (or add to the return value) the n-th item of the list if the should_write flag is set to True
If n is 0, swap the should_write flag.
Otherwise move (jump) the index n places forward.

At the end of the input, stop (and return the result if using a function).

Input

A sequence of digits (list or string).

Output

The text that comes out after applying the above procedure.

Examples

>>> g('99010')
st
>>> g('100')
b
>>> g('2300312')
f
>>> g('390921041912042041010')
mvxyptvab
>>> g('1')
>>> g('1045')
bf
>>> g('33005780')
g
>>> g('100100102')
bcd
>>> g('012')
ab

Python 3, 60

i=b=0
for c in input():b and print(chr(97+i%26));b^=c<1;i+=c

Takes a list of numbers and prints the chars on separate lines.

Basically just follows the instructions. The index is i and the should_write flag is b. The expression b and short-circuits to print only when b is true.


Generating minimal regular expression character classes Background
Character classes are a standard way to indicate a set of characters to match in regular expressions. For example, the class [ab] matches a or b, [a-z] matches any lower case letter, and [^a] matches everything but a. For the purpose of this question, classes can contain:

a sequence of characters to match, where  the characters \, ], - and ^ must normally be escaped with a \.
a range of characters to match, indicated by separating two characters with a -: e.g. [0-9]. Note that if - is the first or last character in a class then it need not be escaped, as it's not indicating a range.
a combination of sequences and ranges: e.g. [ac-fhk-o]. Note that the class cannot be empty, and if ] is the first character in the class then it need not be escaped.
a complement match indicated by the first character in the class being ^: e.g. [^a-z]. Note that if ^ is not the first character in the class, then it need not be escaped.

Task
Given a non-empty string made up of printable ASCII characters (" " to "~" = 0x20-0x7E), output the shortest character class that matches precisely those characters. The string may contain duplicate characters. Default Input/Output methods apply.
Scoring
This is code-golf, so shortest code in bytes wins, with all the standard loopholes forbidden.
Test cases
"the"     => "[the]" or "[eht]" etc
"faced"   => "[ac-f]" or "[c-fa]"
"0-121"   => "[-0-2]" or "[012-]" etc
"]"       => "[]]"
"[-^]"    => "[][^-]" or "[]^[-]"
"[\]"     => "[[-\]]" or "[]\\[]" or "[][\\]"

No answers after a few days, so thought I'd have a go. Found it trickier than expected, so the answer's pretty long, but I'm reasonably confident it works. Should be able to trim it a fair bit more.
Python 3.8, 431 405 410 bytes

import re,itertools as I
B,M,C,P="\-]^"
s=sorted;x=s({*input()})
d=[ord(x)-i for i,x in enumerate(x)];l=[];i=0
for _,g in I.groupby(d):n=len([*g]);l+=[[x[i]+M+x[i+n-1]],x[i:i+n]][n<4];i+=n
o="".join(s(l,key=lambda i:2*(M in i[::2])+(P in i)-3*(i[0]==M<C not in x)-2*(C in i)))
print("["+re.sub(".",lambda m:B*((x:=m.group())==B or x==P==o[0]or x==M<M*2==o[(i:=m.start()):i+2]in o[1:-1]or x==C in o[1:])+x,o)+C)

Try it online!
Explanation
The overall approach is to:

Split the letters into ranges of length at least 4 and individual characters. Note that ranges of length 3 are never necessary (eg. "[abc]" is the same length as "[a-c]" and "[]\\[]" is the same length "[[-\]]") and are sometimes worse (e.g. "]-./" is shorter as  "[]./-]" than as "[]\--/]" or "[--/\]]").

Sort the letters and ranges, so "]" goes first, otherwise "-" goes first, otherwise "-" goes last, and with "^" as late as posssible. There is no conflict between putting "]" first and "-" last since "]--" is not a valid range.

Escape as necessary: \ always, ] unless it's first, ^ if it's first, and - if it's in the middle (which will only happen if it's the beginning of a range).

Extra test cases
"-^"      => "[-^]"
"-4]"     => "[]4-]"
"abcde^"  => "[a-e^]"
"XYZ[\\]" => "[X-\]]"
"-./0]"   => "[]\--0]"
"+*,-^"   => "[\^*--]"
"^_`a"    => "[\^-a]"


Implement a Variable Length Hash My friend and I have this game that we play with words. It is a fun pastime and it involves "canceling out" letters in a word until there is nothing left. I am really tired of him being so much faster than me at it, so it is your job to implement it and let me finally beat him. Obviously, since I have to make the program as easy to hide as possible, it has to be small as possible.
How does this game work?
The game is a pretty simple algorithm. It reduces a alphabetical string until it can't be reduced any further, thus making it a sort of hash. The actual game that we humans do is very hard to implement, but it can be simplified into the following algorithm:
You start by folding the alphabet in half and lining up the two pieces like such:
a b c d e f g h i j k l m
z y x w v u t s r p q o n

Then, starting from the middle, you assign the positive integers to the top half and the negative to the bottom:
a  b  c  d  e f g h i j k l m
13 12 11 10 9 8 7 6 5 4 3 2 1

z   y   x   w   v  u  t  s  r  p  q  o  n
-13 -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1

Then you take your string (we will be using hello world) and ignoring any non-alphabetical characters, translate it:
h e l l  o w   o  r  l d
6 9 2 2 -2 -10 -2 -5 2 10

Then you sum the letter values. The ones that lined up in the earlier diagram (e.g. d and w, l and o) will cancel out, while the others will add up.
sum(6 9 2 2 -2 -10 -2 -5 2 10 )=12

12 is the number for b, so the hash of hello world is b
For a word that completely cancels out (e.g. love), you output the "0 character": -. Note that in the input, - will still be disregarded. It only matters in the output.
If the number's magnitude is larger than 13, then you start doubling up on the a's and the z's You basically take as many a's or z's fit into the number and take whatever is left into the last letter like so:
code golf: 43.

Fits 3 a's and has 4 left over:
aaa 4: j
result: aaaj

Hint: This part is basically divmod except that it rounds toward zero, not -infinity (e.g. -43 would become 3 z's and and a -4 which is p so zzzp).
Note: the dash does not come if the a's or z's fit in perfectly, only if it is exactly 0.
Clarifications:

The hash is case insensitive
Standard Loopholes are not allowed
I/O can be in any format that isn't too outlandish, stdin, stdout, command-line arg, function, etc.
This is code-golf so shortest size in bytes wins.

Examples:
hello world  -->  b

love  -->  -

this is an example -->  aak

hello *&*(&(*&%& world  -->  b

good bye --> ae

root users --> zzs


Compute the Discrete Fourier Transform Implement the Discrete Fourier Transform (DFT) for a sequence of any length. This may implemented as either a function or a program and the sequence can be given as either an argument or using standard input.
The algorithm will compute a result based on standard DFT in the forward direction. The input sequence has length N and consists of [x(0), x(1), ..., x(N-1)]. The output sequence will have the same length and consists of [X(0), X(1), ..., X(N-1)] where each X(k) is defined by the relation below.
$$X_k\overset{\text{def}}{=}\sum_{n=0}^{N-1}x_n\cdot e^{-2\pi ikn/N}$$
Rules

This is code-golf so the shortest solution wins.
Builtins that compute the DFT in forward or backward (also known as inverse) directions are not allowed.
Floating-point inaccuracies will not be counted against you.

Test Cases
DFT([1, 1, 1, 1]) = [4, 0, 0, 0]
DFT([1, 0, 2, 0, 3, 0, 4, 0]) = [10, -2+2j, -2, -2-2j, 10, -2+2j, -2, -2-2j]
DFT([1, 2, 3, 4, 5]) = [15, -2.5+3.44j, -2.5+0.81j, -2.5-0.81j, -2.5-3.44j]
DFT([5-3.28571j, -0.816474-0.837162j, 0.523306-0.303902j, 0.806172-3.69346j, -4.41953+2.59494j, -0.360252+2.59411j, 1.26678+2.93119j] = [2, -3j, 5, -7j, 11, -13j, 17]

Help
There was a previous challenge for finding the DFT using a FFT algorithm for sequences with lengths equal to a power of 2. You may find some tricks there that might help you here. Keep in mind that this challenge does not limit you to any complexity and also requires your solution to work for sequences of any length.

Python 3, 77 bytes

lambda x,e=enumerate:[sum(t/1j**(4*k*n/len(x))for n,t in e(x))for k,_ in e(x)]

Test it on Ideone.
The code uses the equivalent formula


Traverse a directory tree and output a list of all files Write the shortest code that traverses a directory tree and outputs a flat list of all files.

It should traverse the whole directory tree
The order in which it enters sub-directories doesn't matter
The directories should not be output
The output should be a plain list — the definition is flexible, but it shouldn't contain irrelevant data
You are free to use any programming technique

find 14 characters (12 on GNU)

find . -type f

Run this in the directory you want to list. Add -printf '%f\n' to only print names without the path.

Non-portable: find -type f.


A code golf challenge, m'kay Mr. Mackey is a South Park character well-known for adding "m'kay" in everything he says.

Write a program or function that transforms a string of text into something Mr. Mackey would say.

M'kay placement

m'kay has a random 50% chance of being added after the punctuations ,, ., ? and !. If that is the case, it will be followed by the exact same punctuation mark that preceeds it and preceeded by a space.

For example, in the sentence Test, test., there are two places where m'kay can be added: after the comma, and after the period, with a 50% chance at each place. Possible results would be Test, m'kay, test. or Test, test. M'kay. or Test, m'kay, test. M'kay..
There must always be at least one m'kay added. Moreover, it cannot always be at the same place and each valid place where m'kay could be added must occur with equal probability. That is, you can't add m'kay always at the end of the string if because of randomness you never added any m'kay. If there is only one m'kay, it must have the same probability of appearing in each valid position, even though its presence is enforced.
If m'kay is after ?, . or !, the m must be uppercased.
The number of m in m'kay must be uniformely picked between 1 and 3. That is, m'kay, mm'kay and mmm'kay are all possible choices, each with probability 0.33... If it must be uppercased (see above rule), all m must be uppercased.

Inputs, outputs

Inputs are ASCII strings containing characters from ASCII Dec 32 (Space) to ASCII Dec 126 (Tilde ~). There are no linebreaks in the input. You may assumed that any input will contain at least one of , . ? !.
You may assume that there are no m'kay or any of its variants in the input.

Inputs may be taken from STDIN, function arguments, command line, or anything similar.
Output may be via STDOUT, a function return, or something similar.

Test cases

Input: Test.

Possible output: Test. M'kay.

Input: Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. It's 100% free, no registration required.

Possible output: Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. MMM'kay. It's 100% free, mm'kay, no registration required.

Input: Drugs are bad, so, if you do drugs, you're bad, because drugs are bad. They can hurt your body, cause drugs are bad.

Possible output: Drugs are bad, m'kay, so, if you do drugs, you're bad, m'kay, because drugs are bad. They can hurt your body, m'kay, cause drugs are bad. M'kay.

Input: Do you understand? Really? Good!

Possible output: Do you understand? MM'kay? Really? Good! MMM'kay!

Scoring

This is code-golf, so the shortest code in bytes wins, m'kay?

APL (66)

{∊⍉⍵⍪⍉⍪(¯1+⌈?2×⍵∊',.!?')/¨{' ',⍵,⍨'''kay',⍨'mM'[1+⍵≠',']/⍨?3}¨⍵}⍣≢

Result of 10 runs:

      ↑ ({∊⍉⍵⍪⍉⍪(¯1+⌈?2×⍵∊',.!?')/¨{' ',⍵,⍨'''kay',⍨'mM'[1+⍵≠',']/⍨?3}¨⍵}⍣≢)¨ 10/⊂'Test, test. Test! Test?'
Test, m'kay, test. Test! Test?
Test, test. M'kay. Test! MMM'kay! Test? M'kay?
Test, mm'kay, test. Test! MM'kay! Test? MM'kay?
Test, mmm'kay, test. Test! Test? M'kay?
Test, mm'kay, test. Test! Test? M'kay?
Test, test. MM'kay. Test! Test? MMM'kay?
Test, test. MMM'kay. Test! MMM'kay! Test? M'kay?
Test, test. Test! MM'kay! Test?
Test, mm'kay, test. M'kay. Test! Test?
Test, test. MM'kay. Test! MM'kay! Test?

Explanation:

{...}⍣≢: apply the function to the input until the value changes

Generate a M'kay for each character:
{...}¨⍵: for each character in the input:

'mM'[1+⍵≠',']/⍨?3: generate 1 to 3 ms or Ms depending on whether the character was a comma or not.
'''kay',⍨: append the string 'kay.
⍵,⍨: append the character
' ',: prepend a space.

(¯1+⌈?2×⍵∊',.!?')/¨: for each M'kay', if its corresponding character is one of .,!?, select it with 50% chance, otherwise select it with 0% chance.
⍉⍵⍪⍉⍪: match each selection with its character,
∊: list all the simple elements (characters) in order.


Draw an ASCII hexagon of side length n Given a positive integer \$n\$ output an ASCII hexagon with diagonal side length \$n\$, as pictured (note there are \$2n\$ _ characters on the top edge)
Examples:
\$n = 1\$
 __
/  \
\__/

\$n = 2\$
  ____
 /    \
/      \
\      /
 \____/

\$n = 5\$
     __________
    /          \
   /            \
  /              \
 /                \
/                  \
\                  /
 \                /
  \              /
   \            /
    \__________/

etc.
Shortest code in bytes wins.
Usual input/output methods apply.

Canvas, 15 9 bytes
 _；１＊⁸／∔╬

Try it here!, another 9 bytes
-6 bytes after fixing the program.
Draws a quarter of the hexagon, and quad palindromizes.


Highest cardinality grouping of contiguous integers with minimum-sum threshold Challenge

Given an array of positive integers and a threshold, the algorithm should output a set of consecutive-element-groupings (subarrays) such that each group/subarray has a sum greater than the threshold.

Rules

The solution should honor two additional criteria:

be of highest cardinality of the groups (i.e. highest number of groups)
having the maximum group-sum be as lowest as possible.

Mathematical Description:

input array \$L = [l_1, l_2, ..., l_n]\$
threshold \$T\$

output groups/subarrays \$G = [g_1, g_2, ..., g_m]\$ where:

\$m \leq n\$
\$\bigcap\limits_{i=1}^m{g_i}=\varnothing\$
\$\bigcup\limits_{i=1}^m{g_i}=L\$
if we denote the sum of elements in a group as \$s_{g_i} = \sum\limits_{l \in g_i}l\$, then all groups have sum greater than threshold \$T\$. In other words: \$\underset{g \in G}{\operatorname{min}}{\{s_g\}} \ge T\$
if cardinality \$|g_i|=k\$, then \$g_i=[l_j, ..., l_{j+k-1}]\$ for an arbitrary \$j\$ (i.e. all elements are consecutive).
optimal solution has highest cardinality: \$|G_{opt}| \ge \max\left(|G| \right),\,\,\forall G\$
optimal solution \$G_{opt}\$ has lowest maximum group-sum: \$\underset{g \in G_{opt}}{\operatorname{max}}{\{s_g\}} \le \underset{g \in G}{\operatorname{max}}{\{s_g\}}, \,\,\, \forall G\$

Assumption

for simplicity, we assume such a solution exists by having: \$\sum\limits_{i=1}^n l_i \ge T\$

Example:

Example input:

L = [1, 4, 12, 6, 20, 10, 11, 3, 13, 12, 4, 4, 5]
T = 12

Example output:

G = {
  '1': [1, 4, 12, 6],
  '2': [20],
  '3': [10, 11],
  '4': [3, 13],
  '5': [12],
  '6': [4, 4, 5]
}

Winning Criteria:

Fastest algorithm wins (computational complexity in \$O\$ notation).
Additionally, there might be situations where an element \$l_i >\!\!> T\$ is really big, and thus it becomes its own group; causing the maximum subarray sum to be always a constant \$l_i\$ for many potential solutions \$G\$.
Therefore, if two potential solutions \$G_A\$ and \$G_B\$ exists, the winning algorithm is the one which results in output that has the smallest max-subarray-sum amongst the non-intersecting groups.
In other words: if we denote \$G_{A \cap B}=\{g_i: \,\, g_i \in G_A \cap
 G_B\}\$, then optimum grouping, \$G_{opt}\$, is the one that has:

$$\underset{g \in \mathbf{G_{opt}} - G_{A \cap B}}{\operatorname{max}}{\{s_g\}} = \min\left( \underset{g \in \mathbf{G_A} - G_{A \cap B}}{\operatorname{max}}{\{s_g\}}\, , \,\,\underset{g \in \mathbf{G_{B}} - G_{A \cap B}}{\operatorname{max}}{\{s_g\}} \right)$$

Java (JDK), 1248 bytes

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
class TestCG{
	public static void main(String [] args) {
		int [] input = new int[] {1,4,12,6,20,10,11,3,13,12,4,4,5};
		int threshold = 12;
		List<List<Integer>> groups = new ArrayList<>();

		int currentGroupSum = 0;
		int previousGroupSum = 0;

		int maxGroupSum = 0;
		int boundaryValue = 0;
		List<Integer> currentGroup =  new ArrayList<>();

		for(int i=0; i<input.length; i++) {
			currentGroup.add(input[i]);
			currentGroupSum+=input[i];

			if(currentGroupSum>=threshold) {
				if(i<input.length-1) {
					boundaryValue = input[i+1];
				}

				if(currentGroupSum>maxGroupSum) {
					maxGroupSum = currentGroupSum;
				}

                if(currentGroupSum > previousGroupSum && (currentGroupSum - boundaryValue)>=threshold) {

                	groups.get(groups.size()-1).add(boundaryValue);
                	currentGroup.remove(0);
                }

				previousGroupSum = currentGroupSum;

				currentGroupSum = 0;
				groups.add(currentGroup);
				currentGroup = new ArrayList<>();
			}
		}
		System.out.println(groups.size());

		for(List<Integer> group : groups) {
			System.out.println(group);
		}
	}

}

Try it online!

Complexity O(n)


The Squiggly Sequence All credits to Adnan for coming up with this challenge.

My last challenge, before I go on break.

Task

Given positive integer n, if n is odd, repeat / that many times; if n is even, repeat \ that many times.

(Seriously, the testcases would be much clearer than this description, so just look at the testcases.)

Specs

Any reasonable input/output format.
Standard loopholes apply.

Testcases

n output
1 /
2 \\
3 ///
4 \\\\
5 /////
6 \\\\\\

Javascript, 22 bytes

n=>"\\/"[n%2].repeat(n)

Defines an anonymous function.

If only * repeated strings in Javascript. sighs


Probabilistic approach puzzle A few hours earlier, I got this puzzle:

  Suppose, you toss a coin n times, then what is the probability of getting m number of heads? ( where m belongs to the set of all prime numbers)

For instance, take n = 2, then
SS = { HH, HT, TH, TT }

So, output is 1/4 (for HH case)

Then, for n = 3,
SS = { HHH, HHT, HTH, THH, HTT, THT, TTH, TTT }

So, output is (1 + 3)/8 (for 3 H's case and 2 H's cases respectively)

Input: n ( an integer, 0 <= n <= 1000 )
Output: The probability (in any distinguishable form, i.e., decimal, exponential, fraction, etc)

This is a code-golf, so fewest bytes would win!

Wolfram Language (Mathematica), 33 bytes

Uses Binomial and outputs ,really fast, fractions

Tr@Binomial[#,Prime@Range@#]/2^#&

Try it online!

The original code according to my formula was

Tr@Binomial[#,Prime@Range@PrimePi@#]/2^#&

but, as @attinat commented, instead of searching all Primes < n  we can
search the first n primes because every prime > n returns zero binomial.
In this way we save 8 bytes

Here is also the graph of the first 1000 cases which looks pretty cool


Float 754 to Hamming You will be given as input an integer k in the range from -4503599627370496 (−252) to 4503599627370496 (252). As is well known, integers in this range can be represented exactly as double-precision floating-point values.

You should output the Hamming weight (number of ones) of the encoding of k in  binary64 format. This uses 1 bit for the sign, 11 bits for the exponent (encoded with an offset), and 52 for the mantissa; see the above link for details.

As an example, number 22 is represented as

0 10000000011 0110000000000000000000000000000000000000000000000000

Since there are 5 ones, the output is 5.

Note that endianness doesn't affect the result, so you can safely use your machine's actual internal representation of double-precision values to compute the output.

Additional rules

Programs or functions are allowed.
Any programming language can be used.
Standard loopholes are forbidden
The input number will be in decimal. Other than that, input/output means and format are flexible as usual.
Shortest code in bytes wins.

Test cases

22                ->   5
714               ->   6
0                 ->   0
1                 ->  10
4503599627370496  ->   5
4503599627370495  ->  55
1024              ->   3
-1024             ->   4
-4096             ->   5
1000000000        ->  16
-12345678         ->  16

x86_64 machine language (Linux), 16 bytes
0:       f2 48 0f 2a c7          cvtsi2sd %rdi,  %xmm0
5:       66 48 0f 7e c0          movq     %xmm0, %rax
a:       f3 48 0f b8 c0          popcnt   %rax,  %rax
f:       c3                      retq

Accepts a single 64-bit integer parameter in RDI, converts it to a floating-point value in XMM0, stores those bits back in RAX, and then computes the hamming weight of RAX, leaving the result in RAX so it can be returned to the caller.
Requires a processor that supports the POPCNT instruction, which would be Intel Nehalem, AMD Barcelona, and later microarchitectures.
To Try it online!, compile and run the following C program:
#include<stdio.h>
const char g[]="\xF2\x48\x0F\x2A\xC7\x66\x48\x0F\x7E\xC0\xF3\x48\x0F\xB8\xC0\xC3";
#define f(x) ((int(*)(long))g)(x)

int main(int a){
  printf("%d\n",f(22));
  printf("%d\n",f(714));
  printf("%d\n",f(0));
  printf("%d\n",f(1));
  printf("%d\n",f(4503599627370496L));
  printf("%d\n",f(4503599627370495L));
  printf("%d\n",f(1024));
  printf("%d\n",f(-1024));
  printf("%d\n",f(-4096));
  printf("%d\n",f(1000000000));
  printf("%d\n",f(-12345678));
}

Edit: Fixed segfault in TIO link.


Let's do some "deciph4r4ng" In this challenge, your task is to decipher a string. Luckily, the algorithm is pretty simple: reading from left to right, each encountered digit N (0 to 9) must be replaced with the character which is N+1 positions before it.
Example
The input string "Prog2am0in6" would be decoded this way:

Hence, the expected output is "Programming".
Clarifications and rules

The input string will contain ASCII characters in the range 32 - 126 exclusively. You can assume that it will never be empty.
The original deciphered string is guaranteed not to contain any digit.
Once a character has been decoded, it may in turn be referenced by a subsequent digit. For instance, "alp2c1" should be decoded as "alpaca".
References will never wrap around the string: only previous characters can be referenced.
You can write either a full program or a function, which either prints or outputs the result.
This is code golf, so the shortest answer in bytes wins.
Standard loopholes are forbidden.

Test cases
Input : abcd
Output: abcd

Input : a000
Output: aaaa

Input : ban111
Output: banana

Input : Hel0o W2r5d!
Output: Hello World!

Input : this 222a19e52
Output: this is a test

Input : golfin5 3s24o0d4f3r3y3u
Output: golfing is good for you

Input : Prog2am0in6 Puz0les7&1Cod74G4lf
Output: Programming Puzzles & Code Golf

Input : Replicants 4re3lik448ny3oth8r5mac6in8.8T64y'r371it9376a1b5n1fit7or2a1h2z17d.
Output: Replicants are like any other machine. They're either a benefit or a hazard.

Java 7, 81 80 bytes

void a(char[]a){for(int i=0;++i<a.length;)if(a[i]>47&a[i]<58)a[i]=a[i-a[i]+47];}

Try it online!

Saved 1 byte thanks to Anders Tornblad. The first character cannot be a digit so it doesn't need to be checked meaning we can preincrement before checking our terminate condition.


10 PRINT CHR$(205.5+RND(1)); : GOTO 10 in PHP (or anything else, for that matter) Just had a 'spirited' conversation with a co-worker about the succinctness of the following BASIC statement:

10 PRINT CHR$(205.5+RND(1)); : GOTO 10

It's the title of this book, and will simply print a sequence of / and \ characters, alternating between the two randomly, resulting in a pattern similar to this:

(Image borrowed from http://www.flickr.com/photos/rndmcnlly/5058442151/sizes/o/in/photostream/)

Being of a PHP proclivity, we wondered what the most compact way of writing the same thing in PHP would be, and came up with this:

while(1) { echo chr(47 + 45 * rand(0,1)); }

chr(47) is a / character, and chr(92) is a \. So the statement echo chr(47 + 45 * rand(0,1)); will randomly alternative between the two, ad nauseum.

In a language of your choosing, write the shortest program or function to output an infinite random sequence of \ and / characters, where each character has an equal probability of being chosen.

Since this has been migrated to codegolf...

PHP 30 bytes

<?for(;;)echo rand(0,1)?~Ð:~£;

The Ð is character 208, and the £ is character 163.

Sample usage (on a Windows box):

color 18 & php maze.php

Produces something similar to:

It works best with a monospace font that is exactly square (here I've chosen the standard system font 8x8). To go back to your default color, you can type color again without any parameters.


More fun with gates: Karnaugh simplification Take a classic Boolean function with 4 variables, and perform a Karnaugh simplification (you can use any other method of Boolean algebra to arrive to the simplest form). The catch is: the result has to be displayed as a circuit diagram using ASCII graphics! (in a text-mode grid display, not just characters painted in arbitrary orientations in arbitrary positions)

You can choose how to evaluate input; it can be a form of 0000001011111110 as copied directly from the truth table, its 16 bit integer representation, etc.

This example

simplifies to this

For which you have to draw the circuit diagram out of ASCII characters.

Standard code-golf rules apply. The ASCII graphics can be as beautiful or as ugly as you like, but the diagram has to be unambiguously identifiable at first glance.

Python, 609 chars

N=input()
M=[[(255,['A']),(3855,['B']),(13107,['C']),(21845,['D'])]]
U=[1]*65536
for f,a in M[0]:U[f]=0
s=lambda x:x if x else''
L=1
B=65535
while all(f-N for f,a in sum(M,[])):
 K={}
 for f,a in M[L-1]:
  if U[f^B]:K[f^B]=[u'ᐂ',u'│']+a;U[f^B]=0
 for i in range((L+1)/2):
  for f,a in M[L-1-i]:
   A=max(len(x)for x in a)
   for g,b in M[i]:
    if U[f&g]|U[f|g]:
     d=[u'├'+u'─'*(A-1)+u'┐']+map(lambda x,y:s(x)+' '*(A-len(s(x)))+s(y),a,b)
     if U[f&g]:K[f&g]=[u'ᗝ']+d;U[f&g]=0
     if U[f|g]:K[f|g]=[u'ᗣ']+d;U[f|g]=0
 M+=[K.items()]
 L+=1
print '\n'.join([a for f,a in sum(M,[])if f==N][0])

Functions are specified by listing their truth table values as a binary input.  The first bit is the output for ABCD=0000, the second bit is the output for ABCD=0001, and the last bit is the output for ABCD=1111.  Does a brute-forceish search for the minimal circuit that computes the function.  It never shares subcomputations, so it will always be a tree.  M[L] contains a list of functions computable with L gates, represented as a pair (function,array of strings) where the function is computable with the circuit drawn by the strings when printed one per line.  To make sure we get the minimum circuit, we run in increasing L order and U keeps track of which functions we've already found a circuit for.

$ echo 0b1110000000000111 | ./gates.py
ᗣ
├───┐
ᐂ   ᗝ
│   ├──┐
ᗣ   ᗝ  A
├──┐├─┐
ᗣ  Aᗣ B
├─┐ ├┐
ᗝ B CD
├┐
CD

I used some awesome Unified Canadian Aboriginal syllabics unicode glyphs for the gates, and box drawing glyphs for the connections.  Yes, you heard right: *Unified Canadian Aboriginal*!  If they don't display correctly in your browser, upgrade your unicode-fu.  (They look awesome in my terminal; they are a bit misaligned on stackexchange.)

Depending on the input, could be fast or could take up to ~1/2 hour.

You might need to add something like # -*- coding: utf-8 -*- to the start of the program if running as a script.


Compute the polyomino capacity of a rectangle Write a program or function that takes as input three positive integers x, y, and a and returns or outputs the maximum number of whole a✕1 rectangles that can be packed (axis-aligned) into an x✕y rectangle.  Although the result will always be an integer, the program need not give the result using an integer type; in particular, floating-point outputs are acceptable.  Use of standard loopholes is forbidden.  Answers are scored in bytes including the cost of non-standard compiler flags or other marks.

Sample inputs and outputs:

 x,  y,  a -> result
--------------------
 1,  1,  3 ->      0
 2,  2,  3 ->      0
 1,  6,  4 ->      1
 6,  1,  4 ->      1
 1,  6,  3 ->      2
 6,  1,  3 ->      2
 2,  5,  3 ->      2
 5,  2,  3 ->      2
 3,  3,  3 ->      3
 3,  4,  3 ->      4
 4,  3,  3 ->      4
 4,  4,  3 ->      5
 6,  6,  4 ->      8
 5,  7,  4 ->      8
 7,  5,  4 ->      8
 6,  7,  4 ->     10
 7,  6,  4 ->     10
 5,  8,  3 ->     13
 8,  5,  3 ->     13
12, 12,  8 ->     16
12, 13,  8 ->     18
13, 12,  8 ->     18
 8,  8,  3 ->     21
12, 12,  5 ->     28
13, 13,  5 ->     33

In response to a question in the comments, note that some optimal packings may not be obvious at first glance.  For instance, the case x=8, y=8, and a=3 has solutions that look like this:

||||||||
||||||||
||||||||
---||---
---||---
|| ||---
||------
||------

(8 + 2 + 2 = 12 vertical placements and 2 + 3 + 4 = 9 horizontal placements gives 12 + 9 = 21 placements in total.)

Python 2, 53 bytes
lambda p,q,n:p/n*q+q/n*(p%n)-min(0,n-p%n-q%n)*(p>n<q)

Adapts the formula given in this paper, which is:
def f(p,q,n):a=p%n;b=q%n;return(p*q-[a*b,(n-a)*(n-b)][a+b>=n and p>=n and q>=n])/n


Queue Our Decomposition In this challenge I will ask you to find a QR decomposition of a square matrix.  The QR decomposition of matrix A is two Matrices Q and R such that A = QR.  In particular we are looking for Q to be an orthogonal matrix (that is QTQ=QQT=I where I is the multiplicative identity and T is the transpose) and R to be a upper triangular matrix (every value below its diagonal must be zero).

You will write code that takes a square matrix by any reasonable method and outputs a QR decomposition by any method.  Many matrices have multiple QR decompositions however you only ever need output one.

Elements of your resultant matrices should be within two decimal places of an actual answer for every entry in the matrix.

This is a code-golf competition so answers will be scored in bytes with fewer bytes being a better score.

Test Cases

These are only possible outputs, your outputs need not match all of these as long as they are valid.

0 0 0     1 0 0   0 0 0
0 0 0 ->  0 1 0   0 0 0
0 0 0     0 0 1 , 0 0 0

1 0 0     1 0 0   1 0 0
0 1 0 ->  0 1 0   0 1 0
0 0 1     0 0 1 , 0 0 1

1 2 3     1 0 0   1 2 3
0 3 1 ->  0 1 0   0 3 1
0 0 8     0 0 1 , 0 0 8

0 0 1     0 0 1   1 1 1
0 1 0 ->  0 1 0   0 1 0
1 1 1     1 0 0 , 0 0 1

0 0 0 0 1     0 0 0 0 1   1 0 0 0 1
0 0 0 1 0     0 0 0 1 0   0 1 1 1 0
0 0 1 0 0 ->  0 0 1 0 0   0 0 1 0 0
0 1 1 1 0     0 1 0 0 0   0 0 0 1 0
1 0 0 0 1     1 0 0 0 0 , 0 0 0 0 1

Octave, 19 bytes

@(x)[[q,r]=qr(x),r]

Try it online!

My first Octave answer \o/

Octave’s qr has quite a few alternatives in other languages that return both Q and R: QRDecomposition (Mathematica), matqr (PARI/GP), 128!:0 - if I recall correctly - (J), qr (R)...


Print the AdamN tile Adam7 is an interlacing algorithm for raster images, such as PNG. It is called the "Adam7" algorithm because it was invented by Adam M. Costello, and it is generated by following a certain pattern 7 times. One of the cool things about the Adam7 algorithm that makes it really fun for code golf, is that the pattern can be repeated an arbitrary number of times, as long as it's odd. Back when 1996 when the PNG standard was developed, using only 7 iterations was seen as sufficient, since the 9 iterations was too complex, and 5 iterations is not as efficient.
Here is the first iteration of the tile:
a

Pretty simple. This is an "Adam1" tile. Here's how we get to the next iteration, the "Adam3" tile.
Since our last tile was 1x1, we double the height and width, and the next one will be 2x2. First, we start with an 'a' in the upper left corner.
a-
--

Step 2, copy this pattern to the right, and increase the letter we're on by one.
ab
--

Step 3, same as step 2, but copy down instead of right.
ab
cc

Boom. The "Adam3" tile. Let's do the "Adam5" also, so you can actually see how the algorithm works. This tile will, again, be twice as large, so 4x4. Again, we start with a a in the upper left corner:
a---
----
----
----

Double this pattern, increase the letter, and move it to the right:
a-b-
----
----
----

Again, this time down.
a-b-
----
c-c-
----

Again, this time to the right.
adbd
----
cdcd
----

Again, this time down.
adbd
eeee
cdcd
eeee

This is the "Adam5" tile. Here is the ASCII representation of the Adam7 tile:
afdfbfdf
gggggggg
efefefef
gggggggg
cfdfcfdf
gggggggg
efefefef
gggggggg

And while we're at it, here is a fun animation of each step of the Adam7 tile (although it does several tiles side by side):

The challenge
Given a positive odd number N, output the "AdamN" tile. You can use any default method of IO. Since we're using the alphabet in lieu of numbers, you only need to handle inputs up to 25. You can choose to output lower-case or upper-case characters as long as you specify and it's consistent.
Sample IO
1:
a

3:
ab
cc

5:
adbd
eeee
cdcd
eeee

7:
afdfbfdf
gggggggg
efefefef
gggggggg
cfdfcfdf
gggggggg
efefefef
gggggggg

9:
ahfhdhfhbhfhdhfh
iiiiiiiiiiiiiiii
ghghghghghghghgh
iiiiiiiiiiiiiiii
ehfhehfhehfhehfh
iiiiiiiiiiiiiiii
ghghghghghghghgh
iiiiiiiiiiiiiiii
chfhdhfhchfhdhfh
iiiiiiiiiiiiiiii
ghghghghghghghgh
iiiiiiiiiiiiiiii
ehfhehfhehfhehfh
iiiiiiiiiiiiiiii
ghghghghghghghgh
iiiiiiiiiiiiiiii

As usual, this is code-golf, so standard loopholes apply, and shortest answer in bytes wins!

CJam, 20 bytes

Laq~{'a+_@f*\f+z}/N*

Try it online.

La                      Push [[]]
  q~                    Push input n
    {           }/      For i in 0..n-1 ...
     'a+                  Add to char 'a to give current char
        _@f*              Join each row by char
            \f+           Add char to the end of each row as well
               z          Zip to transpose
                  N*    Join result by newlines

20/21-byte alternatives:

Laaq~{'a+aff+:sz}/N*
Laaq~{'a+\Laf+f*z}/N*
Laq~{'a+f{_@*\+}z}/N*


Maximum Concatenated Product We are given a list of integers p1, ..., pk (not necessarily distinct) where each has a value between 1 and 9, inclusive. Using each of the p1, ..., pk exactly once, we can form concatenations of digits, to achieve a new list of numbers; we then output the product of this new list. The goal is to maximize this product by choosing the best concatenations of digits.

For example, we are given the list: 2 3 2 (separated by spaces). We can form the following concatenations:

2 3 2 (product of these concatenations is 12)
23 2 (product is 46)
32 2 (product is 64)
22 3 (product is 66)

Since the largest product that we can form of concatenations is 66, we output that.

Rules:

There must be at least one multiplication (i.e., you cannot just concatenate all of the digits and output that).
You cannot use any other operators other than multiplication, or insert parentheses, etc.
Assume that the list of integers given is separated by spaces, and all integers have values between 1 and 9.

Shortest code (in bytes) wins!

Test cases:

Input: 1 2 3; Output: 63 (i.e., 21*3)

Input: 2 5 9; Output: 468 (52*9)

Input: 1 2 3 4; Output: 1312 (41*32)

CJam, 32 28 23 12 bytes

0le!f{~*}:e>

Try it online in the CJam interpreter.

Thanks to @user23013 for helping me save 16 whole bytes!

Idea

Permuting the characters in the input string divides it into integers (groups of consecutive digits) separated by spaces. By pushing a zero and then evaluating the permuted input string, we push two or more integers. Multiplying the topmost two will result either in the product of the input divided into exactly two integers or some suboptimal value.

Code

 le!         e# Push all possible character permutations of the input.
0   f{  }    e# For each permutation:
             e#   Push 0, then the permuted string.
      ~      e#   Evaluate the string. Pushes one or more integers.
       *     e#   Multiply the two topmost integers.
         :e> e# Retrieve the greatest integer in the array.


Regex that matches any regex Your task is to write a regular expression that matches any valid regular expression and no invalid expression.

You may pick any regex flavour for your answer, but you have to match regular expressions of that same flavour.

This is regex-golf, so the shortest regex wins.

You can't invent your own regex language for this. That would be an example of a standard loophole.

Not possible in Ruby!

I wanted to write a regular expression in Ruby that matches valid regular expressions in Ruby, but I must conclude that writing one is not possible.

At first, Ruby seems like a good choice. If I want to check for matching parentheses, I can write a recursive expression like (?<mparen>([^()]|\(\g<mparen>\))*) where mparen matches zero or more things that are either not parentheses, or are a set of parentheses with mparen inside.

So I listed things that are valid and not valid in Ruby regular expressions. Then I found things that I cannot check with regular expressions.

Empty ranges of characters

In Ruby, [a-b] is a valid, but [b-a] is not valid, because a comes before b. This rule is common to several flavors of regular expressions:

$ ruby21 -e '/[b-a]/'
-e:1: empty range in char class: /[b-a]/
$ perl -e 'qr/[b-a]/'
Invalid [] range "b-a" in regex; marked by <-- HERE in m/[b-a <-- HERE ]/ at -e line 1.
$ sed '/[b-a]/!d'
sed: 1: "/[b-a]/!d": RE error: invalid character range

So how do I write a regular expression that matches a-b but not b-a, and works with any range? I can't.

I would like to write (?<begin>.)-[\k<begin>-z] using a backreference to the first character. This would become a-[a-z] or b-[b-z] or so on. (Later I would change z to the highest character, but for now I test lowercase letters.) This fails because I can't use backreferences in ranges! [\k<begin>-z] is the same as [<>-z], as the range >-z includes the letters begkin.

I can write in 202 characters:

a-[a-z]|b-[b-z]|c-[c-z]|d-[d-z]|e-[e-z]|f-[f-z]|g-[g-z]|h-[h-z]|i-[i-z]|j-[j-z]|k-[k-z]|l-[l-z]|m-[m-z]|n-[n-z]|o-[o-z]|p-[p-z]|q-[q-z]|r-[r-z]|s-[s-z]|t-[t-z]|u-[u-z]|v-[v-z]|w-[w-z]|x-[x-z]|y-[yz]|z-z

This covers 26 lowercase letters, but only in their literal forms. Octal and hex escapes are also part of the regular expression syntax. Now a is also \141 and \x61, and z is also \172 and \x7a. My regular expression would need to match \141-\172 and \x61-\x7a, and also a-\172 and \x61-z and so on.

(a|\\141|\\x61)-([a-z]|\\1(4[2-7]|[5-7][0-7])|\\x(4[1-9a-fA-F]|[5-7]\h))

I would not try to extend this to the 1112064 codepoints of Unicode.

Missing capture groups

A regular expression is not valid if it has a backreference to an undefined capture group. For example, (?<a>)\k<b> is not valid because it has no capture group b. So, my regular expression for valid regular expressions would need to check \k<b> against the set of valid names. I can't think of a way to do this in one regular expression.

The answer is not (?<=\(\?<b>.*)\\k<b>. This would use the lookbehind feature to match \k<b> if there was a (?<b> earlier in the string. It fails because variable quantifiers like * are not valid in lookbehind expressions.

Another problem happens with subexpression calls. It is valid for two capture groups to share the same name, but it is not valid for a subexpression call to use a multiplex name. So (?<a>)(?<a>) is valid but (?<a>)(?<a>)\g<a> is not.

Encoding troubles

A valid regular expression must also be valid in its character encoding. If the encoding is UTF-8, then \xc4\x80 is valid but \x80\x80 is not. My regular expression for regular expressions would also need to validate UTF-8. It is valid to mix octal and hex escapes, so \xc4\200 and \304\x80 are valid too.

Ruby has other encodings. My regular expression would also need to validate EUC-JP, Windows-31J, GB18030, and every other ASCII-compatible encoding known to Ruby. That's not possible! My regular expression can't know which encoding to validate.

Is \200 a valid regular expression? Regexp.new '\200'.encode('binary') is valid, but Regexp.new '\200'.encode('utf-8') is not valid. My regular expression can't see the encoding tag. It can only see the four ASCII characters in \200, so it can't decide whether \200 is valid.

I might fix this if I decree that my regular expression for regular expressions only works with one encoding. I might pick 'us-ascii', which has only 128 characters. This does not fix my problem with capture groups.


See you in another life, brotha! Most of us LOST fans out there remember the computer that Desmond had to type the characters "4 8 15 16 23 42" in every 108 minutes or the world would end (or would it?).

The challenge here is to create a program that would do the same thing by requiring that every 108 seconds the input 4 8 15 16 23 42 is entered or it will display the message

Sorry, the world has ended with status code -1

It should warn the user at 100 seconds that they need to enter a number with the message

Enter, Quick!

The program must be able to read input at any time and if it is the correct input it will reset the timer. If incorrect input is given nothing happens.

The program should run indefinitely. So the timeline after the last valid input looks like

From 0 to 99 seconds: no output
At 100 seconds: Enter, Quick!
At 108 seconds: Sorry, the world has ended with status code -1.

This is code golf so the shortest answer (in bytes) that accomplishes this task wins! Good Luck!

bash, 160 bytes

I()($s 100&&echo Enter, Quick!&$s 108&&echo Sorry, the world has ended with status code -1&)
i()(read r;[[ $r = '4 8 15 16 23 42' ]]&&pkill $s&&I;i)
s=sleep;I;i

I'm currently uncertain what the expected behavior is after "the world has ended".

Run like this:

bash lost.sh 2>&-

2>&- is required to ignore STDERR, which is allowed by default.


Exponential-ish number sequence Your program must print out this exact sequence:

1
2
4
10
24
54
116
242
496
1006
2028
4074
8168
16358
32740
65506
131040
262110
NOPE!

As usual, shortest program wins. Standard code golf rules apply.

Python 2, 51 bytes

i=0;exec"print 2**i-i<<(i>0);i+=1;"*18;print"NOPE!"

Try it online!

Notices that the formula is 2(2n-n), for all n except 0.

Saved two bytes thanks to Wheat Wizard (i<<1-(i<1) changed to i<<(i>0), duh!).

Python 2, 53 bytes

i=0;exec"print[2**i-i<<(i>0),'NOPE!'][i>17];i+=1;"*19

Try it online!


How happy is this emoticon? In this challenge, submissions will be programs or function which, when given an emoticon such as :-), :(, or :D, will rate their happiness from 0 to 3.

An emoticon will be one of the following:

:(: 0
:|: 1
:): 2
:D: 3

Emoticons may also have noses (a - after the :).

Test cases:

:(  -> 0
:-| -> 1
:D  -> 3
:-) -> 2
:|  -> 1

This is a code golf challenge, shortest answer per language wins.

Python 3, 26 bytes

lambda s:ord(s[-1])*2%19%4

Try it online!

$$ f(x) = (2x \bmod 19) \bmod 4 $$


Restricted Integer Partitions Pk(n) means the amount of partitions of n into exactly k parts. Given n and k, calculate Pk(n).

  Tip: Pk(n) = Pk(n−k) + Pk−1(n−1), with initial values p0(0) = 1 and pk(n) = 0 if n ≤ 0 or k ≤ 0. [Wiki]

Examples

n    k    Ans
1    1    1
2    2    1
4    2    2
6    2    3
10   3    8

Rules

General code-golf rules apply.

Swift, 76 73 bytes

func P(_ n:Int,_ k:Int)->Int{return n*k>0 ?P(n-k,k)+P(n-1,k-1):n==k ?1:0}

Try it online!

Explanation
How does the code structurally work?
First of all, we define our function P, with two integer parameters n and k, and give it a return type of Int, with this piece of code: func P(_ n:Int,_ k:Int)->Int{...}. The cool trick here is that we tell the compiler to ignore the names of the parameters, with _ followed by a space, which saves us two bytes when we call the function. return is obviously used to return the result of our nested ternary described below.
Another trick I used was n*k>0, which saves us a couple of bytes over n>0&&k>0. If the condition is true (both the integers are still higher than 0), then we recursively call our function with n decremented by k as our new n and k stays the same, and we add the result of P() with n and k decremented by 1. If the condition is not true, we return either 1 or 0 depending on whether n is equal to k.
How does the recursive algorithm work?
We know that the first element of the sequence is p0(0), and so we check that both integers are positive (n*k>0). If they are not higher than 0, we check if they are equal (n==l ?1:0), here being two cases:

There is exactly 1 possible partition, and thus we return 1, if the integers are equal.

There are no partitions if one of them is already 0 and the other is not.

However, if both are positive, we recursively call P twice, adding the results of P(n-k,k) and P(n-1,k-1). And we loop again until n has reached 0.

* Note: The spaces cannot be removed.


Calculate the internal angles of a regular polygon with N sides This is a simple challenge: given n in any way practical (Function arg, stdin, file, constant in code) output the internal angles
(NOT the sum of the internal angles, just one) of a regular polygon with n sides. The output can be in degrees, gradians or radians, and can be displayed in any way practical (Function return, stdout, stderr if you feel like it, file etc)

As usual, smallest byte count wins.

Perl 6, 8 bytes

π- τ/*

Try it online!

Output in radians. Simple function in WhateverCode notation which computes \$π-τ/n\$. \$τ\$ is the constant tau equaling \$2π\$.


Meta-atomic code golf In this meta-challenge, you will score your own atomic-code-golf submissions. More precisely, you will need to write a program P in language L such that the atomic-score of P is produced by P.

Score

The idea behind atomic-code-golf is to count language tokens instead of bytes. However, in practice, it is hard to define a general set of rules for all questions (see Count big-ints/symbols/variables as N tokens in atomic-code-golf). That's why it is recommended to clarify rules for each challenge.

Intuitively, tokens are nodes in the abstract syntax tree of your language, except for strings, where each character count (due to potential abuse).

Things that count as single tokens:

variable/function/type  identifiers
literals, except strings, where each byte counts
built-in keywords and operators
(edit) Empty lists, empty vectors, empty strings

Things that are ignored from counting:

preprocessor/reader macros
include/import statements
separating and grouping symbols used to build tuples, lists, arrays, statements, function parameters, structs are ignored (,;:(){}[]<>|). However, if those symbols are tokens, they count (I am looking at you, CJam (or Brainfuck)). Also, quotes enclosing strings are not counted.

Corner cases

Using identifiers to hold data is a nice hack (see feersum's comment), but it might be considered abusive. So, there should be a penaly of +25 if your answer exploits identifiers' names for computations. This penalty needs not be correctly scored by your program. If you manage to add a penalty to programs which abuse identifiers' names for computation (for a reasonable subset of programs in your language), you deserve -100 points of bonus (this bonus needs not be correctly scored by your program).

Challenge

You should write a program in the language of your choice that scores programs in that language according to the above atomic-score rules. Your own answer will be scored according to that program.

Input may be read from STDIN or given as a function parameter
Output is a number, as a return value or printed to STDOUT
Answer with lowest atomic-score wins
I'll provide an example answer (if it has the lowest score, the next one wins).

Unary, 1
The program is a string of 47297560408284 zeroes
i.e.
000000000000000000000000000000000000000000.... 47297560408284 times

A brainfuck quivalent code would be
+[>+<+++++]>--.

which just prints 1
as in unary, the whole program is made up of just 0 which are all a single token.


Golf some quine stripes in different languages You will choose m languages and write n programs in each language, each with length n*m. The kth program should output the kth character of each program, ordered by the program number.
For example, in this submission (for demonstration only; they can be any characters including newlines and tabs):
ABC
DEF
GHI

Program ABC should output ADG, and programs DEF and GHI should output BEH and CFI respectively.
All programs in the list must not be a normal quine. So ABC and ADG must be different. Same applies to the other two programs. Note that n*m must be at least 2 to make this possible.
You don't have to use your languages in specific order. So you can write two programs in language A, then three in language B, then another in language A again. But all languages must be used exactly the same number of times.
Leading / trailing newline in your program and output doesn't matter.
The answer with minimum n(m+10)/m3 wins. But I'll also award at least +100 bounty to the answer with most languages if it used at least 3 of them. Deadline for the bounty: after a week without improvement or Mar 1st, 2015 if no answer satisfied the criterion.
Rules about languages
You can use any languages with different names, or different versions which are generally considered different enough (such as Python 2/3, ECMAScript 5/6). But your programs must not output exactly the same thing in any other language you have used.


Pour me a drink, will you? The Challenge

I am thirsty and need a drink, but I don't know what to order. Your task is to provide me with either a drink or options for one.

I/O

Input will be either a base or a drink name.

If given a base, your program should output one random drink from a list of drinks with that base.
If given a drink name, your program should output the base that drink is made from.

Below is a list of drink names, ordered by their bases:

Absinthe:
    Death in the Afternoon
    Earthquake
    Green Russians
    Green Vesper
    Moloko Plus

Beer:
    Black and Tan
    Black Velvet
    Boilermaker
    Michelada
    Irish Car Bomb

Brandy:
    B&B
    Brandy Alexander
    French Connection
    Horse's Neck
    Sidecar

Cachaça:
    Caipirinha
    Leite de Onça
    Quentão
    Rabo-de-Galo
    Royce

Gin:
    Bramble
    Casino
    Clover Club Cocktail
    Gin Fizz
    Martini

Rum:
    Bacardi
    Cuba Libre
    Daiquiri
    El Presidente
    Piña Colada

Tequila:
    El Toro Loco
    Margarita
    Matador
    Paloma
    Tequila Sunrise

Vodka:
    Black Russian
    Bloody Mary
    Cosmopolitan
    Kamikaze
    Screwdriver

Whiskey:
    Bourbon Lancer
    Irish Coffee
    Manhattan
    Rusty Nail
    Whiskey Sour

Rules:

Standard Loopholes are forbidden.
If given a base, the program's output should be non-deterministic, meaning that multiple runs should result in different outputs.
Accordingly, when given a drink name, the program's output should be deterministic, yielding the same result for drinks with the same base.
You may assume the input will always be one of the bases or drink names in the list compiled above.
You may choose to print characters such as ç, ñ and ã as c, n and a, respectively.
You may accept I/O in any reasonable format.
This is a code-golf challenge, so the shortest answer (in bytes) wins.

Test Cases:

Input:                    Output (Any one of the following):
Absinthe                  Death in the Afternoon
                          Earthquake
                          Green Russians
                          Green Vesper
                          Moloko Plus

Beer                      Black and Tan
                          Black Velvet
                          Boilermaker
                          Michelada
                          Irish Car Bomb

Brandy                    B&B
                          Brandy Alexander
                          French Connection
                          Horse's Neck
                          Sidecar

Cachaça                   Caipirinha
                          Leite de Onça
                          Quentão
                          Rabo-de-Galo
                          Royce

Gin                       Bramble
                          Casino
                          Clover Club Cocktail
                          Gin Fizz
                          Martini

Rum                       Bacardi
                          Cuba Libre
                          Daiquiri
                          El Presidente
                          Piña Colada

Tequila                   El Toro Loco
                          Margarita
                          Matador
                          Paloma
                          Tequila Sunrise

Vodka                     Black Russian
                          Bloody Mary
                          Cosmopolitan
                          Kamikaze
                          Screwdriver

Whiskey                   Bourbon Lancer
                          Irish Coffee
                          Manhattan
                          Rusty Nail
                          Whiskey Sour

Likewise, the input can be any of the drink names in the output column. If so, the output should be the corresponding base.

Python 3, 693 690 686 687 bytes

Yeah, naive approach. I tried some compression methods, and this one seems to be the shortest.

-2 bytes thanks to HyperNeutrino.

EDIT: Bug fixed.

import random
v="Absinthe$Death in the Afternoon$Earthquake$Green Russians$Green Vesper$Moloko Plus$Beer$Black and Tan$Black Velvet$Boilermaker$Michelada$Irish Car Bomb$Brandy$B&B$Brandy Alexander$French Connection$Horse's Neck$Sidecar$Cachaca$Caipirinha$Leite de Onca$Quentao$Rabo-de-Galo$Royce$Gin$Bramble$Casino$Clover Club Cocktail$Gin Fizz$Martini$Rum$Bacardi$Cuba Libre$Daiquiri$El Presidente$Pina Colada$Tequila$El Toro Loco$Margarita$Matador$Paloma$Tequila Sunrise$Vodka$Black Russian$Bloody Mary$Cosmopolitan$Kamikaze$Screwdriver$Whiskey$Bourbon Lancer$Irish Coffee$Manhattan$Rusty Nail$Whiskey Sour".split('$');a=v.index(input());print(v[a-a%6if a%6else random.randint(1,5)+a])

Try it online!


404 - Unique 404 page not found Inspired by a polyglot on the Stack Overflow 404 page:

Goal
Your goal is simple, to create a polyglot that outputs the number 404, and then terminate, in as many languages as possible.
Restrictions
Here's the twist, there's a restriction to make it harder:
You have to write N programs and pick N languages in a particular order. the ith program needs to print 404 in the first i languages, but not in any language after the ith. This is to prevent very simple solutions from destroying competition
Scoring:

The first criterion for determining a winner is the number of languages the main program runs in.
The second criterion is byte count, where the programs with more languages have more importance for this criterion.
The third and final criterion is time of submission

Clarifications:
The source codes of the programs do not need to have any relation. They're run as separate programs. Any of the programs can output trailing and/or leading whitespace. THE PROGRAMS DO NOT HAVE TO BE SUBSEQUENCES OF EACH OTHER!
Thanks to @MartinEnder for a better explanation!

54 Languages, 1331 bytes

><>,
Gol><>,
Foo,
Befunge-93,
Befunge-98,
brainfuck,
Brain-Flak,
Python 2,
Python 3,
Hexagony,
Perl,
Ruby,
Julia,
Cardinal,
Brainbash,
Turtlèd,
Deadfish~,
Whitespace,
Braille,
Rail,
Fission,
ETA,
Trigger,
Self-modifying Brainfuck,
Numberwang,
Actually,
Emoji,
Symbolic Brainfuck,
TinCan,
Alphuck,
Shove,
Cood,
Wise,
Width,
Whispers,
Thue,
Surface,
Stones,
evil,
Set,
Prelude,
Gaot++,
Cubix,
Cubically,
PATH,
Commercial,
Brian & Chuck,
Monkeys,
Nhohnhehr,
Beam,
AsciiDots,
Alumin,
Alice,
Whirl

This is getting very long, so at @MDXF's suggestion, I'm moving the subprograms and comments to a gist. The program here is only the final program. Thanks to MDXF again for providing the TIO test driver.

54. Whirl

##\$"404"#N#S# , ,,#$#?@\404!?@GJlICJlGCC*G^+0%=%=+0%x&fqpqqqiipsoddddoiipsohphhhhyhhhh? 	  ?nnn4$4#!000110000011110000100000100000110000011001100000111100001110011000111000110000
#?\++++:----:++++:H@((((4O0O4O@((((()()()){}){x}x){}x()){}){}()){}){})<[-]>[-]-[<+>-----]<+x%"404"?.⌂----.++++.>11
#i(N/"404"ooo@ENTHOEONHSSEONTHOEONSETssipceaiiiiiscejiiiijeeeejapmzaeeaeueewzaeeeaeewzaeeaeueewqs??|?)999|997+|++++!999777+++++!999997+++++!
print(404)

__DATA__=1
# \"404"*CC'[-][ .-$_"404"&]
"""pp
I want 404 of this
How much is it
#  -52, Z, -1                          #
#  -48, Y, -1                          #
#  -52, X, -1                          #
[-][
x::=~404
::=
x
]<<<
> 404
>> Output 1
red up two blue up red up one blue up red up two blue up
baaaaa bleeeeeeeeet bleeeeeeeeet baaaaa bleeeeeeeeet
a now 404 dollar off!
a has been selling out worldwide!
2 LEFT
2 LEFT
2 UP
2 LEFT
2 TEACH
1 LEFT
1 RIGHT
1 BOND
1 BOND
1 TEACH
2 YELL
1 FIGHT
2 YELL
1 TEACH
2 YELL
set ! 52
set ! 48
set ! 52
+------+
|$0011\|
|/000\0|
|0/0@11|
|00  10|
|0\10/0|
|\1100/|
+------+
$'main'
 \-444o000o444omm^

[-][$++++++++++++++++++++++++++++++++++++++++++++++++++++.----.++++.#
<<<<<<```>>>>.>.>.
]
ss"""
#7777777777777777777777777777724091557093543643404➡77▲▲▲²²▲²²¡▼▼▼▼¡▲▲▲▲¡⠎⡆⡎⡆⢐⠣⠃s&&&&~-<<:<<:<<<:<:>>>>>>>>:^||||G<>

Try it online!

Whirl is described as a Turning Tarpit [sic], which uses only two instructions, 1 and 0. 1 rotates the current wheel of instructions (either the math wheel or the operations wheel), 0 swaps the rotation of the wheel, and two 0s executes the instruction and switches wheels. The relevant instructions are on the first line:

000110000011110000100000100000110000011001100000111100001110011000111000110000

000110000 Switch to math wheel and execute math.not (math.val = 1)
011110000 Execute math.store, (memval = math.val = 1)
10000     Execute math.add, (math.val = math.val+memval = 1+1 = 2)
010000    Execute math.store (memval = math.val = 2)
0110000   Execute math.multiply, (math.val = math.val*memval = 2*2 = 4)
01100     Execute math.store (memval=math.val) and switch to the ops ring
110000    Execute ops.one (ops.val = 1)
011110000 Executes ops.intio, printing memval (4)
11100     Add one to memory pointer (memval=0)
1100      Execute maths.nop to switch back to ops ring
011100    Execute ops.intio, printing memval (0)
01100     Execute maths.store, (memval=maths.val=4)
00        Execute maths.intio, printing memval (4)

The leading 01s cancel each other out, and the trailing 01s cause a floating point exception.

Edit: fixed a bunch of broken stuff

(Commands to be careful about in the future: UDLR%"[.]o473psjw)

If any programs work for future languages or don't work for current or previous languages, please comment.


Chinese checkerboard The game of Chinese checkers is played on a board with spaces in the shape of a six-pointed star:

Image from Wikipedia

We can create an ASCII-art representation of this board, using . for empty spots and the letters GYORPB for the six colored starting locations:

            G
           G G
          G G G
         G G G G
B B B B . . . . . Y Y Y Y
 B B B . . . . . . Y Y Y
  B B . . . . . . . Y Y
   B . . . . . . . . Y
    . . . . . . . . .
   P . . . . . . . . O
  P P . . . . . . . O O
 P P P . . . . . . O O O
P P P P . . . . . O O O O
         R R R R
          R R R
           R R
            R

To make it more interesting, we can also change the size. We'll measure the size of a board by the side length of its triangular starting locations: the board above is size 4.

Since it's really a pain to type all that by hand, let's write a program (or function) to do it!

Details

Your code should take a positive integer representing the size of the board, via STDIN, ARGV, or function argument. Output the checkerboard pattern to STDOUT (you may alternately return it as a string if your submission is a function).

Output must either

have no trailing spaces at all, or
have exactly enough trailing spaces to fill out the pattern to a perfect rectangle of width 6 * N + 1.

Output may optionally have a trailing newline. No other extra (leading, trailing) whitespace is permitted.

Examples

Size 1:

   G
B . . Y
 . . .
P . . O
   R

Size 2:

      G
     G G
B B . . . Y Y
 B . . . . Y
  . . . . .
 P . . . . O
P P . . . O O
     R R
      R

Size 4:

            G
           G G
          G G G
         G G G G
B B B B . . . . . Y Y Y Y
 B B B . . . . . . Y Y Y
  B B . . . . . . . Y Y
   B . . . . . . . . Y
    . . . . . . . . .
   P . . . . . . . . O
  P P . . . . . . . O O
 P P P . . . . . . O O O
P P P P . . . . . O O O O
         R R R R
          R R R
           R R
            R

Scoring

This is code-golf: the shortest code in bytes wins.

Python 2, 152

n=input();x=N=2*n
while~N<x:s='';y=n*3;exec"a=x+y;q=[0,a>N,x-y>N,-x>n,-a>N,y-x>N,x>n,1];s+=' BYROPG.'[q.index(sum(q)<~a%2*3)];y-=1;"*(y-~y);print s;x-=1

This is, in retrospect, the wrong approach for Python, but I'm posting it here in case someone can make use of it. Rather than explaining this mess of code, I'll try to say the idea behind it.

The idea is to use triangular coordinates, in which the triangular lattice corresponds to integer triples (a,b,c) with a+b+c=0.

(Here, the lattice points are drawn as hexagons.)

We can convert Cartesian coordinates to triangular ones as

a = (x+y)/2
b = (x-y)/2
c = -x

noting that x and y must have the same parity, or otherwise it's off-checkerboard and we should print a space.

In triangular coordinates, the bounding lines of the six-sided star have equations: a==n, b==n, c==n, a==-n, b==-n, c==-n.

So, we can determine what region we're in by which of [a,b,c,-a,-b,-c] are greater than n.

If none are, we're in the center and print a dot.
If exactly one is, we're in one of the six outer triangles, and print the letter corresponding to the index.
If two or more are, we're outside the board, and print a space.

The bounding rectangle requires that we do this for x in the closed interval [-2*n,2*n] and y in the closed interval [-3*n,3*n].


Strict partitions of a positive integer OEIS A000009 counts the number of strict partitions of the integers. A strict partition of a nonnegative integer n is a set of positive integers (so no repetition is allowed, and order does not matter) that sum to n.

For example, 5 has three strict partitions: 5, 4,1, and 3,2.

10 has ten partitions:

10
9,1
8,2
7,3
6,4
7,2,1
6,3,1
5,4,1
5,3,2
4,3,2,1

Challenge

Given a nonnegative integer n<1000, output the number of strict partitions it has.

Test cases:

0 -> 1

42 -> 1426

Here is a list of the strict partition numbers from 0 to 55, from OEIS:

[1,1,1,2,2,3,4,5,6,8,10,12,15,18,22,27,32,38,46,54,64,76,89,104,122,142,165,192,222,256,296,340,390,448,512,585,668,760,864,982,1113,1260,1426,1610,1816,2048,2304,2590,2910,3264,3658,4097,4582,5120,5718,6378]

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

Pyth, 7 bytes
l{I#./Q

Try it online. Test suite.

Take the input (Q).
Find its partitions (./).
Filter it (#) on uniquify ({) not changing (I) the partition. This removes partitions with duplicates.
Find the result's length (l).


Is it a substring of itself? Given a string, return whether the string is a substring of the program's source code.

Standard quine rules apply, meaning you cannot read your own source code. The length of the input is guaranteed to be less than or equal to the length of the program. You may return any two distinct values, not necessarily truthy and falsey values. You may also submit a function, rather than a full program.

This is a code-golf so shortest code wins!

An example

If your source code is print(input() = False), it should return True for nt(i but False for tupn.

Python 2, 41 bytes

s="print input()in's=%r;exec s'%s";exec s

Try it online!


Different tasks, same characters In this challenge, you need to solve 4 different tasks using the same set of characters. You can rearrange the characters, but you can't add or remove characters.

The winner will be the submission that solves all tasks using the smallest number of characters. All tasks must be solved in the same language.

Note that it's the smallest number of characters, not the smallest number of unique characters.

Task 1:

Output the first N numbers of every third composite number. The codeblock below shows the first 19 composite numbers in the first row, and every third composite number on the row below.

4, 6, 8, 9, 10, 12, 14, 15, 16, 18, 20, 21, 22, 24, 25, 26, 27, 28, 30
4,       9,         14,         18,         22,         26,         30

If N=5 then the output should be 4, 9, 14, 18, 22. You must support 1<=N<=50.

Composite numbers are positive numbers that aren't prime numbers or 1.

The result for N=50 is:

4, 9, 14, 18, 22, 26, 30, 34, 38, 42, 46, 50, 54, 57, 62, 65, 69, 74, 77, 81, 85, 88, 92, 95, 99, 104, 108, 112, 116, 119, 122, 125, 129, 133, 136, 141, 144, 147, 152, 155, 159, 162, 166, 170, 174, 177, 182, 185, 188, 192

Task 2:

Output a N-by-N multiplication table. You must support 1<=N<=20

Example:

N = 4
1   2   3   4
2   4   6   8
3   6   9  12
4   8  12  16

The output format is optional, the following is acceptable output [[1,2,3,4],[2,4,6,8],[3,6,9,12],[4,8,12,16]].

Task 3:

Determine if a number is a Fibonacci number. You must support positive N up to the default integer limit of your language. If there are both 32-bit integers and 64-bit integers then you can choose to use the one that requires the shortest code. For instance, use int instead of long int if you have the choice. You can not choose a smaller integers than 32-bit unless that's default (you can't use 8-bit integers if 32-bit is default).

true/false, false/true, 1/0, 1/-1, a/b are all acceptable output as long as it's consistent.

Task 4:

Take N as input and output the result of 1^1+2^2+3^3+...N^N. You must support 1<=N<=10.

The 10 different results are:

1, 5, 32, 288, 3413, 50069, 873612, 17650828, 405071317, 10405071317

This is code-golf, so the shortest submission in each language wins!

This Stack Snippet will help check your solution. It measures the minimum set of characters needed to include all four solutions, and shows the leftover characters.

function update() {
  var m = {};
  var a = [q1.value, q2.value, q3.value, q4.value];
  var o = [{}, {}, {}, {}]
  for (var i = 0; i < 4; i++) {
    for (var j = 0; j < a[i].length; j++) o[i][a[i][j]] = -~o[i][a[i][j]];
    for (var c in o[i]) if (!(o[i][c] < m[c])) m[c] = o[i][c];
  }
  var t = 0;
  for (var c in m) t += m[c];
  for (var i = 0; i < 4; i++) {
    t += "\n";
    for (var c in m) t += c.repeat(m[c] - ~~o[i][c]);
  }
  p.textContent = t;
}

  <textarea id="q1"></textarea>
  <textarea id="q2"></textarea>
  <textarea id="q3"></textarea>
  <textarea id="q4"></textarea>

Python, 88 87 bytes

lambda n:[a for a in range(11*n)if any(a%b<1for b in range(2,a))][:3*n:3]#1,,,=====bd++
lambda n:[[a*b for b in range(1,n+1)]for a in range(1,n+1)]#,,::ybaaa(*i%n< =====2)d33f
f=lambda n,a=1,b=1:a<n and f(n,b,a+b)or n==a#2eerrrfo::((**iii11[[aannn+     ]]y))%33gg
f=lambda n,a=1:a<=n and a**a+f(n,a+1)#::ooeeiii]]      y))bbbgg,,rrrra((11[[nnnnf==2%33

Didn't put too much effort into sharing characters or the golfs themselves, this will almost surely be beat.


Write an interpreter for * The task is simple. Write an interpreter for the language *.

Here's a bigger link to the wiki.

There are only three valid * programs:

* Prints "Hello World"
 *  Prints a random number between 0 and 2,147,483,647
*+* Runs forever.

The third case must be an infinite loop according to the specifications in this question

Input:

The input can be taken via any acceptable input method by our standard I/O rules
It will always be one of the above programs

Output:

The first case should print exactly Hello World, with or without a trailing line break.
For the second case, if your language's integer maximum is smaller than 2,147,483,647, use your language's integer maximum
The first and second cases can print to any acceptable output by our standard I/O rules.
The third case should not give any output.

Scoring:

As this is code-golf, the shortest answer, in bytes, wins.

*, 0 bytes

Since * has no way of reading input, the default rules allow specifying that the input must be given by concatenating it onto the program.

(... I think. There's an "at least twice as many upvotes as downvotes" condition that I don't have the rep to verify).


What's my lucky factor? Lucky numbers (A000959) are numbers generated by applying the following sieve:
Begin with the list of natural numbers:
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, ...

Now, remove every second element (\$n = 2\$, the smallest element in the list aside from 1):
1,    3,    5,    7,    9,     11,     13,     15,     17,     19,     21,     23,     25, ...

Now, remove every third element (\$n = 3\$, the next remaining element after 2):
1,    3,          7,    9,             13,     15,             19,     21,             25, ...

Now, remove every seventh element (\$n = 7\$, the next remaining element after 3):
1,    3,          7,    9,             13,     15,                     21,             25, ...

Then continue removing the \$n\$th remaining numbers, where \$n\$ is the next number in the list after the last surviving number. Next in this example is 9, then 13 and so on.
Eventually, this converges to the lucky numbers:
1, 3, 7, 9, 13, 15, 21, 25, 31, 33, 37, 43, 49, 51, 63, 67, 69, 73, 75, 79, 87, 93, 99, ...

However, we've already looked at the lucky numbers. Today, we'll be looking at a related sequence: the lucky factors (A264940). These are the values of \$n\$ that remove a specific integer \$x\$.
For example, \$x = 2\$ is removed when \$n = 2\$, so \$2\$'s lucky factor is \$2\$
Additionally, \$x = 19\$ is removed when \$n = 7\$, so \$19\$'s lucky factor is \$7\$
If \$x\$ is lucky, its lucky factor is \$0\$.
The first 50 elements of this sequence are
0, 2, 0, 2, 3, 2, 0, 2, 0, 2, 3, 2, 0, 2, 0, 2, 3, 2, 7, 2, 0, 2, 3, 2, 0, 2, 9, 2, 3, 2, 0, 2, 0, 2, 3, 2, 0, 2, 7, 2, 3, 2, 0, 2, 13, 2, 3, 2, 0, 2

This is a standard sequence challenge. You may choose to:

Take a positive integer \$x\$ and output the lucky factor of \$x\$
Take a positive integer \$x\$ and output the lucky factors of each integer \$1 \le i \le x\$
Output the infinite list of lucky factors

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

Test cases
 x  n
15  0
57  9
26  2
41  3
50  2
13  0
48  2
20  2
19  7
22  2
24  2
27  9
60  2
54  2
49  0
 2  2
 7  0
45 13
55 15

Python 2, 72 bytes
Takes a positive integer \$ x \$ and outputs the lucky factor of \$ x \$. Outputs via exit code.

x=input()
R=range(1,x+1)
for i in R:i+=i<2;del R[i-1::i];x>R[-1]<exit(i)

Try it online!


Write a C / C++ Polyglot This challenge's concept is pretty simple. All you have to do is write a program that will compile as both valid C and valid C++! Well, there are some catches. The program must behave differently when compiled in each language. The program must have different output for each language in order to be considered "behaving differently".

Rules

The program must be both valid C and C++
The program must have different outputs based on the language it was compiled in.
#ifdef __cplusplus or other "easy" preprocessor tricks are discouraged! (Other preprocessor operations are perfectly fine, though.)
Try not to make it look completely obvious that the program does something different.

This is a popularity-contest, so whoever has the most interesting and surprising solution wins. Have fun!

Example:

I created my own program to see if this was even possible to do with out #ifdef tricks:

#include <stdio.h>
#include <string.h>

char *m="C++ rules!";

int t[11]={0,0,0,0,1,-1,-3,9,-8,82,0};

char tr(char c,int i)
{
    return c+((sizeof('!')+1)&1)*t[i];
}

int main()
{
    int i = 0;
    for(;i<strlen(m);i++)
    {
        printf("%c",tr(m[i],i));
    }
    printf("\n");
    return 0;
}

This program outputs C++ rules! when compiled in C++ and C++ stinks when compiled in C.

Explanation:

   What causes the difference between languages is the tr() function. It takes advantage of one of the differences between C and C++, specifically, how char literals are treated. In C, they are treated as integers, so sizeof('!') returns 4, as opposed to 1 in C++. The ((...+1)&1) part is just part of a simple bitwise operation that will return 1 if sizeof('!') returns 4, and 0 if it returns 1. That resulting number is multiplied by the ints in array t and then that product is finally added to the specific character being transformed. In C++ the product will always be zero, so the string C++ rules! remains unchanged. In C, the product will always be the value in t, and so the string changes to C++ stinks.

Is the cake a lie?

As there has been much debate over whether the cake is or is not a lie, I wrote this program to answer this contentious question.

#include <stdio.h>

// checks if two things are equal
#define EQUALS(a,b) (sizeof(a)==sizeof(b))

struct Cake{int Pie;}; // the cake is a pie!
typedef struct Cake Lie;
main(){
    struct CakeBox{
        struct Cake{ // the cake contains lies!
            Lie Lies[2];
        };
    };
    typedef struct Cake Cake;

    printf("The cake is ");
    if(EQUALS(Cake, Lie)){
        printf("a LIE!\n");
    }else{
        printf("..not a lie?\n");
    }
    return 0;
}

What will the outcome be?

C:

   The cake is ..not a lie?

C++:

   The cake is a LIE!


Convolve integers in subquadratic time An linear discrete convolution is an operation that turns two vectors of numbers into a third vector of numbers by multiplying elements inside-out. Formally, for two vectors a and b with elements 0 to n - 1, the discrete linear convolution of a and b can be computed with this loop:

for i = 0 to 2*n - 2
    c[i] = 0;
    for j = 0 to n - 1
        if i - j >= 0 and i - j < n
            c[i] = c[i] + a[j] * b[i - j];

As an example, the convolution of a = { 1, 2, 3, 4 } and b = { 5, 6, 7, 8 } is c = { 5, 16, 34, 60, 61, 52, 32 }.
These convolutions appear when doing long multiplication, for example:

1234 * 5678 =
         20 24 28 32
      15 18 21 24
   10 12 14 16
 5  6  7  8
--------------------
 5 16 34 60 61 52 32
--------------------
      32
     52
    61
   60
  34
 16
 5
--------------------
 7006652

Your task is to write a program or function that, given two arrays (or similar) a and b of non-negative integers of equal length n and optionally, n and an output array c, computes the linear discrete convolution of a and b and returns it, assigns it to the parameter c. or prints it out. You may also take input from the user while or before your code is running. The following constraints apply:

Your program must run in subquadratic or o(n 2) time. An algorithm like the pseudo-code above that runs in quadratic time Θ(n 2) is invalid.
You may assume that all integers in in- and output are in the range from 0 to 65535, this also applies to n.
You may not claim that your algorithm runs in subquadratic time because n has an upper bound.
The results must be exact.
This is code golf, the shortest code in octets wins.
You may not use existing library routines or similar to compute a Fourier transform or a number theoretic transform or the respective inverse transformations.

Python 2, 250 bytes, n^log_2(3)

s=lambda a,b,S=1:[x+y*S for x,y in zip(a,b)]
def f(a,A):
 n=len(a);m=n/2
 if m<1:return[a[0]*A[0]]
 if n%2:return f([0]+a,[0]+A)[2:]
 b,c=a[:m],a[m:];B,C=A[:m],A[m:];p=f(b,B);r=f(c,C);z=m*[0];return s(z+z+r,s(z+s(f(s(b,c),s(B,C)),s(p,r),-1)+z,p+z+z))

This isn't well golfed, but more a proof of concept of the algorithm. Let's look at a more readable version.
s=lambda a,b,S=1:[x+y*S for x,y in zip(a,b)]

def f(a,A):
 n=len(a)
 if n==1:return[a[0]*A[0]]
 if n%2:return f([0]+a,[0]+A)[2:]
 m=n/2
 b,c=a[:m],a[m:]
 B,C=A[:m],A[m:]
 p=f(b,B)
 r=f(c,C)
 q=s(f(s(b,c),s(B,C)),s(p,r),-1)
 z=m*[0]
 return s(z+z+r,s(z+q+z,p+z+z))

The idea is to divide and conquer adapting the Karatsuba multiplication algorithm to do convolution. As before, it runs in time n^log_2(3), as it makes 3 recursive calls which shrink the input length in half. This isn't as good as the quasilinear of DFT, but still better than quadratic.
We can think of convolution as multiplication of formal polynomials. Alternatively, if multiplication were done without regrouping, you'd get convolution. So, adapting the algorithm only requires doing vector addition and subtraction instead of the numerical operations. These additions are still linear-time.
Unfortunately for Python, it doesn't have built-in vector addition and subtraction, so we hack together a function s to do both: addition by default, and subtraction when passed an optional argument of -1. Whenever we add, we make sure to pad with zeroes to avoid truncation.
We handle odd list lengths by padding with a zero to an even length, removing the extraneous zeroes that result.


Billiard balls collision Given the 2-dimensional positions and velocities of a pair of billiard balls right before impact, calculate their velocities after a perfectly elastic collision. The balls are assumed to be ideal spheres (or equivalently: circles) with the same radius, same mass, uniform density, and no friction.

Input consists of 8 numbers: p0x,p0y,v0x,v0y,p1x,p1y,v1x,v1y where p0x,p0y is the centre of the first ball, v0x,v0y its velocity, and similarly p1x,p1y,v1x,v1y for the second ball. You can accept input in any order and structured in any convenient way, e.g. as a 2x2x2 array, or maybe a 2x2 array for p and two length-2 arrays for v0 and v1. It's also fine to take complex numbers (if your language supports them) instead of xy pairs. However, you should not take input in a coordinate system other than Cartesian, i.e. polar is not allowed.

Note that the radius of a billiard ball is half the distance between p0x,p0y and p1x,p1y, so it's not given as an explicit part of the input.

Write a program or function that outputs or returns 4 numbers in any convenient Cartesian representation: the post-collision values of v0x,v0y,v1x,v1y.

A possible algorithm is:

find the normal line that passes through both centres
find the tangent line that passes through the midpoint between the two centres and is perpendicular to the normal line
change coordinate system and break down v0x,v0y and v1x,v1y into their tangential and normal components v0t,v0n and v1t,v1n
swap the normal components of v0 and v1, preserving their tangential components
change back to the original coordinate system

Tests (results rounded to 5 decimal places):

   p0x   p0y   v0x   v0y   p1x   p1y   v1x   v1y ->      v0x'       v0y'       v1x'       v1y'
[-34.5,-81.8, 34.7,-76.1, 96.2,-25.2, 59.2,-93.3] [  49.05873, -69.88191,  44.84127, -99.51809]
[ 36.9, 77.7,-13.6,-80.8, -7.4, 34.4, 15.1,-71.8] [   5.57641, -62.05647,  -4.07641, -90.54353]
[-51.0, 17.6, 46.1,-80.1, 68.6, 54.0,-35.1,-73.9] [ -26.48927,-102.19239,  37.48927, -51.80761]
[-21.1,-52.6,-77.7, 91.5, 46.0, 94.1, 83.8, 93.7] [ -48.92598, 154.40834,  55.02598,  30.79166]
[ 91.3, -5.3, 72.6, 89.0, 97.8, 50.5, 36.2, 85.7] [  71.73343,  81.56080,  37.06657,  93.13920]
[-79.9, 54.9, 92.5,-40.7,-20.8,-46.9,-16.4, -0.9] [  47.76727,  36.35232,  28.33273, -77.95232]
[ 29.1, 80.7, 76.9,-85.1,-29.3,-49.5,-29.0,-13.0] [  86.08581, -64.62067, -38.18581, -33.47933]
[ 97.7,-89.0, 72.5, 12.4, 77.8,-88.2, 31.5,-34.0] [  33.42847,  13.97071,  70.57153, -35.57071]
[-22.2, 22.6,-61.3, 87.1, 67.0, 57.6,-15.3,-23.1] [ -58.90816,  88.03850, -17.69184, -24.03850]
[-95.4, 15.0,  5.3, 39.5,-54.7,-28.5, -0.7,  0.8] [  21.80656,  21.85786, -17.20656,  18.44214]
[ 84.0,-26.8,-98.6,-85.6,-90.1, 30.9,-48.1, 37.2] [ -89.76828, -88.52700, -56.93172,  40.12700]
[ 57.8, 90.4, 53.2,-74.1, 76.4,-94.4,-68.1,-69.3] [  51.50525, -57.26181, -66.40525, -86.13819]
[ 92.9, 69.8,-31.3, 72.6,-49.1,-78.8,-62.3,-81.6] [-123.11680, -23.48435,  29.51680,  14.48435]
[-10.3,-84.5,-93.5,-95.6, 35.0, 22.6, 44.8, 75.5] [ -11.12485,  99.15449, -37.57515,-119.25449]
[ -3.9, 55.8,-83.3,  9.1, -2.7,-95.6, 37.7,-47.8] [ -82.84144, -48.75541,  37.24144,  10.05541]
[-76.5,-88.4,-76.7,-49.9, 84.5, 38.0,  4.2, 18.4] [   6.52461,  15.43907, -79.02461, -46.93907]
[ 64.2,-19.3, 67.2, 45.4,-27.1,-28.7, 64.7, -4.3] [  59.66292,  44.62400,  72.23708,  -3.52400]
[  9.8, 70.7,-66.2, 63.0,-58.7, 59.5, 83.7,-10.6] [  68.07646,  84.95469, -50.57646, -32.55469]
[ 62.9, 46.4, 85.0, 87.4, 36.3,-29.0,-63.0,-56.3] [  23.53487, -86.82822,  -1.53487, 117.92822]
[ -5.5, 35.6, 17.6,-54.3, -2.2, 66.8,-15.2, 11.8] [  24.15112,   7.63786, -21.75112, -50.13786]

Shortest wins. No loopholes.

thanks @Anush for helping fix the diagram's background colour

Python 3, 67 66 bytes, 53 bytes

def f(p,v,q,w):p-=q;d=((v-w)/p).real*p;return v-d,w+d

Try it online!
-1 byte thanks to @ngn
-13 bytes thanks to @Neil
This function f takes four complex numbers as input and returns two complex numbers. The ungolfed version is shown in the following.
Ungolfed

def elastic_collision_complex(p1, v1, p2, v2):
    p12 = p1 - p2
    d = ((v1 - v2) / p12).real * p12
    return v1 - d, v2 + d

Try it online!
The computation formula is derived based on the 2D-vector formula on wiki.
Since \$m_1=m_2\$, the formula can be simplified to
$$\left\{\begin{array}{l} v_1'=v_1-dv \\ v_2'=v_2+dv\end{array}\right.$$
Let \$x_{12}=x_1-x_2\$ and \$v_{12}=v_1-v_2\$, we have
$$dv=\frac{\langle v_{12}, x_{12}\rangle}{\|x_{12}\|^2}x_{12} = \frac{Re(v_{12}\cdot\overline{x_{12}})}{x_{12}\cdot \overline{x_{12}}}x_{12}=Re\left(\frac{v_{12}\cdot\overline{x_{12}}}{x_{12}\cdot \overline{x_{12}}}\right)x_{12}=Re\left(\frac{v_{12}}{x_{12}}\right)x_{12}$$
In the ungolfed program, p12, v1 - v2, d correspond to \$x_{12}\$, \$y_{12}\$, and \$dv\$, respectively.


Matchmaker, Matchmaker, make me a match (we won't be finding a Find or catching a tryCatch, though)

This is part two of a multi-part series of implementing some interesting R functions. Part one can be found here.

The task:

You are to implement R's match function in as few bytes as possible.

Input:

x, a possibly empty list/array of integers
table, a possibly empty list/array of integers
nomatch, a single integer value
incomparables, a possibly empty list/array of integers

Output:

a single array/list of integers O of equal length to x, where each value O[i] represents either:

The index j of the first value in table where table[j]==x[i]
nomatch, indicating that no value in table is equal to x[i] OR that x[i] is in the list of incomparables.

Test Cases

All in the form x, table, nomatch, incomparables -> output
outputs

[], [1,2,3], 0, [5] -> []

[1, 2, 3], [], 0, [5] -> [0, 0, 0]

[9, 4, 3, 6, 3], [9, 8, 7, 6, 5, 4, 3, 2, 1], -1, [4] -> [1, -1, 7, 4, 7]

[8, 6, 7, 5, 3, 0, 9], [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5, 8, 9, 7, 9, 3, 2, 3, 8, 4, 6, 2, 6], 1000, [1] -> [12, 8, 14, 5, 1, 1000, 6]

More test cases can be generated as needed.

Additional rules:

R has 1-based indices, but a consistent alternative-based indices are acceptable. So you can use indices that start at 3 or 17 or whatever, but this must be consistent, and you must indicate this in your answer.
If you chosen language has a builtin that does this, please also implement your own solution.
Explanations are appreciated.

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

Jelly,  10  8 bytes

-2 thanks to Erik the Outgolfer

,⁷y⁵iⱮ⁶o

A full program accepting four command line arguments, incomparables nomatch table x which prints a Jelly representation* of the list of R's match function results.

Try it online!

How?

e.g. with incomparables nomatch table x = [1,4], 2, [2,4], [4,3,2,1,0]:

,⁷y⁵iⱮ⁶o - Main Link: list, incomparables; list, nomatch
 ⁷       - newline character                                '\n'
,        - pair (incompararables) with (right)              [[1,4],'\n']
   ⁵     - 5th argument (3rd input = table)                 [2,4]
  y      - translate (right) with lookup (left)             [2,'\n']
      ⁶  - 6th argument (4th input = x)                     [4,3,2,1,0]
     Ɱ   - map with:
    i    -   first index of (right) in (left)               [0,0,1,0,0]
       o - logical OR                                       [2,2,1,2,2]

* An empty list is represented as nothing, a list of lenth one is represented as just the item, while other lists are enclosed in [] and delimited by ,