Make a WaterOverflow You and a friend are playing a game - who can overflow the most containers? There are n containers numbered 1 to n. Each container has a certain maximum capacity of water, in litres.

You take turns with your friend to pour discrete amounts of water into the containers. On your turn, you may pour 2 litres of water into one container (you can't distribute into multiple containers), and on your friend's turn, he must pour 3 litres. You may also choose, on your turn, to not pour water in any of the containers (you cannot, however, choose to only pour 1 litre). The person who manages to overflow the container - that is, after they finish their turn, the litres of water inside the container is greater than its maximum capacity - gets a point.

The input comes in the form of space separated integers. The leftmost one is labelled 1 and the rightmost one is labelled n. For instance:

Y 2 1 4 3

Note that the letter indicates who goes first. Y means that you go first, and F means that your friend goes first. The 2 litre container is labelled 1, the 1 litre container is labelled 2, etc. So we would call the 2 litre container "Container 1", because it is labelled 1.

Now, your friend has a very naïve strategy. He always pours all his 3 litres of water into the container that is closest to overflowing. If there is more than one container that is equally closest to overflowing, he will pour all his water in the one that is labelled with the lowest number.

Suppose I use the same naïve strategy of pouring all my 2 litres of water into the container that is closest to overflowing. The example input would work out like this:

I pour all my water into Container 2. It overflows, and I get one point.
My friend pours all his water into Container 1. It overflows, and he gets one point.
I pour all my water into Container 4. It now has 2L of water in it, so it needs another 2L to overflow.
My friend pours all his water into Container 4. It overflows, and he gets one point.
I pour all my water into container 3. It now has 2L of water in it, so it needs another 3L to overflow.
My friend pours all his water into Container 3. It overflows, and he gets one point.

Altogether, I only got one point, and my friend got three. That's not good. I can do better than that if I make use of my ability to pass on my turn without pouring water:

I pour all my water into Container 2. It overflows, and I get one point.
My friend pours all his water into Container 1. It overflows, and he gets one point.
I pass.
My friend pours all his water into Container 4. It now has 3L of water in it, so it needs another 1L to overflow.
I pour my water into Container 4. It overflows, and I get one point.
My friend pours all his water into Container 3. It has 3L of water in it now, so it needs another 2L to overflow.
I pour my water into Container 3. It overflows, and I get one point.

By strategically choosing which container to pour my water in, I have managed to obtain 3 points instead of 1. The output format is a list of space separated instructions, where P indicates a pass, and an integer from 1 to n indicates which container I poured water into. For instance, the naïve nonoptimal strategy listed above could be represented as:

2 4 3

Which means I poured into Container 2, then Container 4, then Container 3. The more optimal strategy would be represented as:

2 P 4 3

Which means I poured into Container 2, then passed, then Container 4, then Container 3 (This, by the way, is the output format).

Your program will take in input as described above and return the most optimal solution to get as many points as possible. If there is more than one optimal solution, output either.

Python, 217 202 176
import sys
A=sys.argv[1:]
t=A>["G"]
C=[[int(A[i]),i]for i in range(1,len(A))]
while C:
 c=min(C);d=1.5
 if t:d=c[0]%5<2;print["P",c[1]][d],
 c[0]-=2*d;t^=1
 if[0]>c:C.remove(c)

Reads input from the command line.
Strategy:

If the remaining capacity in the container with the least remaining capacity is congruent 0 or 1 modulo 5, pour 2 litres (it either overflows, or our friend pours 3 more litres into the same container, bringing us back to the same point.)
Otherwise, no move improves our position, so do nothing (note that this isn't necessarily the shortest optimal strategy.)


Analysing the most common words in a text, and replacing them with a single byte This is a very crude text encoding algorithm I came up with the other day. It won't work if the text has more than 256 different characters in it – but it does support Unicode, at least in my Python implementation.

The algorithm:

Find all the unique characters in the text. Let's call this list, unique-chars.
Break the text into a sequence of tokens, which can be either words (continuous runs of alphanumeric characters, and apostrophes) and symbols (anything that isn't a word). If there's two symbols (say, a comma and a space), take each only once.
Sort the tokens, most commonly occurring first. Then, take the top (256 - length of unique-chars). Put the two lists – unique-chars, and most-common-tokens – together into one. Let's call this list substitution-table.
Iterate through each token. If it's present in substitution-table, take the index in which this token is found, and convert it into a character. Otherwise, iterate through each letter in the token, and perform the same character conversion.

This way, the most common words become one byte long; and those which are not as common, stay of the same length. I know, this is not very efficient. But it works.

For reference, use King James' Bible, by Project Gutenberg; 4 452 069 bytes, MD5: 3b83dd48fa7db8df0819108f6d50f64f. Download here.

The processed version is 3 422 006 bytes, MD5: 17c52a22abe48dd4135a577e2a4aff8d. Download here.

No restrictions apply on the language used, external libraries/programs, dirty tricks, or operating system.

My Python 3 implementation runs in about 3.3–3.5 seconds, in average. Speed has precedence on everything else. Compiled language implementations, especially in C, would be appreciated. A solution in APL or Perl would be most welcome, I'm curious how they'd look like.

As for how to time the solution, I'd say, time 30 executions (possibly cleaning the RAM after each execution, in case caching occurs), and report both the lowest time (which is indicative limit as for how long it takes the machine to run the program in the best conditions) and the rest of times, for completeness' sake. Obviously, this is not perfectly accurate, but it'll do for an indicative value.

That said, happy coding~!

Perl - 154 bytes (KJB in ~1.94s)

while(<>){push@w,/[\w\']+|\W/g}
\@c{length>1?$w{$_}++?():/./g:$_}for@w;
@t{sort{$w{$b}-$w{$a}}keys%w}=grep!exists$c{$_},map{chr}0..255;
print$t{$_}//$_ for@w

This is substantially golfed, but I can say with confidence that it hasn't affected the performance in any noticable way.
Sample Usage:
$ perl encoder.pl < king-james-bible.txt > kjb.cmp

The created filesize is 3,253,677 bytes, runtime is approximately 1.94 seconds. If you want to test the correctness, you can export a translation table by appending the following three lines of code:
;use Storable;
%u=reverse%t;
store\%u,'trans.tbl'

This will create, and possibly overwrite, a file named trans.tbl in the current working directory. Then, decode with the following script:
#!perl -n0
use Storable;
%t=%{retrieve 'trans.tbl'};
print$t{$_}//$_ for/./sg

Sample usage:
$ perl decoder.pl < kjb.cmp > kjb.txt

The output is exactly 4,452,069 bytes, as expected.

Unrolled and commented
while(<>){      # for each line
  push@w,/[\w\']+|\W/g # tokenize, add tokens to array
}

\@c{            # mark the following chars
  length>1?     # token is 2 or more chars
    $w{$_}++    # increment occurrence in word hash
    ?           # if this word has already been seen
      ()        # mark nothing
    :           # else
      /./g      # mark each char individually
  :             # else
    $_          # mark the single char
}for@w;         # iterate over all tokens

@t{             # create the translation table
  sort{$w{$b}-$w{$a}}keys%w # most frequent words
}=grep!exists$c{$_},map{chr}0..255; # assign to an unmarked char

print           # output
  $t{$_}        # the value in the trans hash
    //          # or, if previous value is undefined
  $_            # output the untranslated string
for@w           # iterate over the tokens previously found

Time analysis
Min: 1.843s
Max: 1.984s
Avg: 1.939s
1.953, 1.953, 1.953, 1.843, 1.921, 1.937, 1.921, 1.953, 1.953, 1.921, 1.937, 1.968, 1.906, 1.984, 1.937, 1.968, 1.953, 1.921, 1.921, 1.937, 1.968, 1.937, 1.890, 1.968, 1.937, 1.953, 1.937, 1.937, 1.937, 1.953
According to profiling, the time usage for each statement is approximately the following:
1.09s:
while(<>){push@w,/[\w\']+|\W/g}
31.3ms:
\@c{length>1?$w{$_}++?():/./g:$_}for@w;
15.6ms:
@t{sort{$w{$b}-$w{$a}}keys%w}=grep!exists$c{$_},map{chr}0..255;
750ms:
print$t{$_}//$_for@w
Note that for the purpose of time usage analysis, the result was actually written to a file. Excluding the final output, or piping to /dev/null instead produces times 600ms to 750ms faster.

Major Performance Gains

The individual characters of a word are marked only the first time the word is seen, instead of every time. As noted by @VadimR, this alone saves around 2s, over 25% of the previous execution time.
The most frequent words are translated with unmarked characters, and marked characters left untranslated. This saves a great deal of time during output, because words not in the translation table can be output directly, without having to translate each individual character.
Tokenizing the file one line at a time - instead of all at once - is quite a bit faster.


Find the coterminal angle on [0, 2π) This challenge is very simple:

Given an angle measure in degrees or radians (your choice), output the angle between 0 and 2π non-inclusive  [0º, 360º) that is coterminal with it.

Input

A positive or negative angle measure. You can pick if you want to take it in degrees or in radians.

Output

The angle on [0, 2π) that is coterminal with the input angle. If you take the input in degrees, the output must also be in degrees; if you take it in radians, the output must be in radians too. The coterminal angle is essentially a the angle mod 360°.

Examples (in degrees)

745 -> 25
1728 -> 288
90 -> 90
0 -> 0
360 -> 0
-50 -> 310
-543.21 -> 176.79

Python 3, 14 bytes

lambda n:n%360

Try it online!


Optimize my Nullifiers I am a big fan of the game Creeper World, and especially the sequel. You don't need to know how this game works to answer the question, I just wanted to mention where my question originated from.

In the game, your objective is to destroy the Emitters that are spawning Creeper, using a weapon known as a nullifier.

Nullifiers can destroy any emitter in this radius:

 eee
eeeee
eenee
eeeee
 eee

Each nullifier CAN target multiple Emitters.

Your objective

Given an array simulating a 2D map consisting of nothing and emitters with whatever characters you like, could be spaces and e or numbers - just be sure they are distinguishable, output the same map with the optimal amount of nullifiers n (or what you would like) placed, so that the emitters are destroyed with the least amount of nullifiers.

If there are multiple optimal ways of doing it, just outputting one would be fine. If, however, the task is not solvable, say there are so many emitters that no layout will ever hit all of them, you must output a distinguishably different something, null will suffice

Quick Rules:

Input: multidimensional array
Input will contain two characters, meaning nothing and emitter, include what is what in your answer
Output: multidimensional array
Output will contain three characters, meaning nothing, emitter and nullifier OR a distinguishable output if the input is unsolvable
You may only replace the nothing character with a nullifier
A nullifier can hit multiple emitters, and will always hit all that
are in range
A nullifier can hit in the area specified above, and will always hit all emitters that it can target
Shortest answers in bytes win
standard loopholes forbidden

Examples

Input:

[[ , ,e, , ],
 [ , , , , ],
 [e, , , ,e],
 [ , , , , ],
 [ , ,e, , ]]

Output:

 [[ , ,e, , ],
  [ , , , , ],
  [e, ,n, ,e],
  [ , , , , ],
  [ , ,e, , ]]

Input:

[[e,e,e,e,e],
 [e, , , ,e],
 [e, , , ,e],
 [e, , , ,e],
 [e,e,e,e,e]]

Output:

[[e,e,e,e,e],
 [e, ,n, ,e],
 [e, , , ,e],
 [e, ,n, ,e],
 [e,e,e,e,e]]

Input:

[[e, , , , , , ,e, ,e, , , ,e, ,e, ,e, ,e],
 [ , ,e, , ,e, , , ,e,e, , , , ,e, , , , ],
 [ , ,e, , , ,e, ,e, ,e, ,e, ,e, ,e, , , ],
 [e, , , ,e, ,e, , , , , , , , , , , ,e, ],
 [e, , ,e, , , , , ,e, ,e, ,e, ,e, , , ,e],
 [ , , ,e, ,e, ,e, , , , , , , , , ,e, , ],
 [ ,e,e, ,e, , , ,e, ,e,e, ,e, ,e, ,e, , ],
 [ , ,e, , , ,e, , , , , , , , ,e,e, ,e, ],
 [ , , ,e, , , , ,e,e, , , , , , , , ,e, ],
 [e, , , , , , ,e, , , ,e,e, ,e, , , , , ],
 [ ,e,e, , ,e, , , , ,e, , , , , , ,e, , ],
 [ , , ,e,e, ,e, ,e, , , ,e,e, ,e, ,e, ,e],
 [e,e, , , , ,e, , , ,e, , , , , , , , , ],
 [ , , ,e, , , , , ,e, , ,e, ,e, ,e, ,e, ],
 [ , , , ,e, ,e, , , , , , , , , , , , , ],
 [e,e, , ,e,e, , ,e, , ,e, ,e, ,e, ,e, ,e],
 [e, ,e, ,e, , ,e,e,e, , ,e, , , ,e, , ,e],
 [ , , , ,e, , , , , ,e, , , ,e, , , , , ],
 [ , ,e, , , ,e, ,e, , , ,e, , , , ,e, , ],
 [ , , ,e, ,e, ,e, , ,e,e, , ,e,e, , ,e, ]]

Output (This output is hand-made, and might not be the optimal output):

[[e, , , , , , ,e, ,e, , , ,e, ,e, ,e, ,e],
 [ , ,e, , ,e, , ,n,e,e, , , ,n,e, , , , ],
 [ ,n,e, , ,n,e, ,e, ,e, ,e, ,e, ,e, ,n, ],
 [e, , , ,e, ,e, , , , , , , , , , , ,e, ],
 [e, , ,e, , , , , ,e, ,e, ,e, ,e, , , ,e],
 [ , ,n,e, ,e, ,e, , , ,n, , , , , ,e, , ],
 [ ,e,e, ,e, ,n, ,e, ,e,e, ,e, ,e,n,e, , ],
 [ , ,e, , , ,e, , , , , , , , ,e,e, ,e, ],
 [ , , ,e, , , , ,e,e, , , , , , , , ,e, ],
 [e, ,n, , , , ,e, , , ,e,e, ,e, , , , , ],
 [ ,e,e, , ,e,n, , ,n,e, , , ,n, , ,e,e, ],
 [ , , ,e,e, ,e, ,e, , , ,e,e, ,e, ,e, ,e],
 [e,e, , , , ,e, , , ,e, , , , , , , , , ],
 [ , , ,e, ,n, , , ,e, , ,e, ,e, ,e, ,e, ],
 [ ,n, , ,e, ,e, , , , , , , ,n, , , ,n, ],
 [e,e, , ,e,e, , ,e,n, ,e, ,e, ,e, ,e, ,e],
 [e, ,e, ,e, , ,e,e,e, , ,e, , , ,e, , ,e],
 [ , , , ,e, , , , , ,e, ,n, ,e, , ,n, , ],
 [ , ,e, ,n, ,e, ,e, , , ,e, ,n, , ,e, , ],
 [ , , ,e, ,e, ,e, ,n,e,e, , ,e,e, , ,e, ]]

Input:

[[e,e],
 [e,e]]

Output:

null

Python 3, 558 511 509 bytes

from itertools import*
E=enumerate
L=len
def s(s):
 q=[(x,y)for y,r in E(s)for x,k in E(r)if k==w]
 for i in range(1,L(q)):
  for c in combinations(q,i):
   m=[l*1for l in s]
   for p in c:
    m[p[1]][p[0]]=n
    for y,r in E([list(r) for r in' xxx ,xxxxx,xxnxx,xxxxx, xxx '.split(',')]):
     for x,k in E(r):
      o=(p[0]-x+2,p[1]-y+2)
      if k==d and-1<o[0]<L(m[0])and-1<o[1]<L(m)and m[o[1]][o[0]]==e:
       m[p[1]-y+2][p[0]-x+2]=d
   if e not in ','.join([''.join(r)for r in m]):return(m)
print(s(m))

Try it online!

It's very loopy, but I don't know enough about Python to optimize it further. I did learn some things from ovs's answer, so that was fun.

The input (modified to make it easier to write test cases) expects ' ' or 'e', while the output uses ' ', 'n' for nullifier, and 'x' for a nullified emitter. The function takes the expected input that was described in the question.

I set the e, w, n, and d variables outside because they could be easily replaced with numbers and, if the input and output were modified to use numbers as well, it would print out the same thing. I used letters because they made it more readable while working on it.

Fun question, OP! Creeper World is great and it was a cool inspiration for the question :)

Edit: -47 bytes thanks to Erik the Outgolfer


Given an input, move it along the keyboard by N characters The Challenge:

Given any input that can be typed on a keyboard, move the text along by N chars.

Here is the QWERTY keyboard to be used. You can ignore the modifier keys (Shift, Caps, Enter, Delete and Tab). Once you reach one side (for example |) loop back round, so | goes to Q if N = 1.

Spaces do not have to be moved along (they go back round to space as you skip modifiers). If shift was used to type the character (e.g. ! and @) the changed character should also be typed using shift (i.e. ! goes to @ not 2 if N = 1).

UK keyboards are different to this, but please use this so that we can compare.

Input:

Any sentence that can be typed on the above keyboard followed by a positive integer. There is no maximum to the size of this integer.

Output:

The same sentence, shifted along by N.

Examples:

My name is Tim 3
?o .f/y [g I[/

Hello World 7
Spgge Oe[g;

I Wi5h I h4d b3773r C@d3ing ski{{s 3
{ T[8l { l7h ,6006u N%h6[.k g'[QQg

This is code golf, so shortest code wins.

C, 217 bytes

char*t=" @A$%^*a)_(~.=/z-234567890\"'>`?Z#SNVFRGHJOKL:<MP{WTDYIBECUX]q\\&=1snvfrghjokl;,mp[wtdyibecux}Q|!";l,d,k;f(char*s){for(l=strlen(s);s[--l]-32;);d=atoi(s+l);for(s[l]=0;d--;)for(k=l;k--;s[k]=t[s[k]-32]);puts(s);}

Readable version with whitespace, includes, etc:

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

char* t = " @A$%^*a)_(~.=/z-234567890\"'>`?Z#SNVFRGHJOKL:<MP{WTDYIBECUX]q\\&=1snvfrghjokl;,mp[wtdyibecux}Q|!";
int l, d, k;

void f(char* s) {
    l = strlen(s);
    for( ; s[--l] - 32; );
    d = atoi(s + l);
    s[l] = 0;
    for ( ; d--; ) {
        for (k = l; k--; s[k] = t[s[k] - 32]);
    }
    puts(s);
}

The code pretty much speaks for itself. Just a lookup table that maps from each character to the next character, which is applied the given number of times. Much of the code is actually for parsing the number out of the input.


Reverse Range Successors Given a positive integer n, do the following (and output every stage):

start with a list containing n copies of n.
do the following n times:
at the ith step, gradually decrement the ith entry of the list until it reaches i

So, for example, if the given n is 4, then you start with [4,4,4,4], and then at the first step you have [3,4,4,4], [2,4,4,4], [1,4,4,4]. At the second step, you have [1,3,4,4], [1,2,4,4]. At the third step you have [1,2,3,4]. Nothing is done on the fourth step.

So your output is [[4,4,4,4],[3,4,4,4],[2,4,4,4],[1,4,4,4],[1,3,4,4],[1,2,4,4],[1,2,3,4]].

Any reasonable input/output format is permitted.

Standard loopholes apply. This is code-golf: the answer with the smallest byte-count wins.

Python implementation for checking purposes.


Seven's Cycle Sum Sequence Take a look at the sevens multiplication table from 7×0 to 7×9:
0, 7, 14, 21, 28, 35, 42, 49, 56, 63

If we just look at the digits in the one's place we get a permutation of the digits 0 through 9:
0, 7, 4, 1, 8, 5, 2, 9, 6, 3

Consider taking some positive decimal integer N and replacing each digit D in N with the the digit in the one's place of 7×D.
For example, 15209 becomes 75403 because 1 maps to 7, 5 maps to 5, 2 maps to 4, 0 maps to 0, and 9 maps to 3.
Now lets repeat this process with this new decimal integer until we see a cycle, i.e. until an integer we've already seen comes up.
For example, with 15209 we get the cycle
15209 -> 75403 -> 95801 -> 35607 -> 15209 -> repeats...
                                      ^
                                      |
                             cycle restarts here

As another example, 505 has the short cycle
505 -> 505 -> repeats...
        ^
        |
cycle restarts here

It turns out that for any N these cycles will always contain exactly 1 or 4 distinct integers. (I'll leave it to you to figure out why that is.) What's interesting is that if you sum all the distinct integer in a cycle, you almost always get a decimal integer that only consists of 2's and 0's.
For example, 15209 + 75403 + 95801 + 35607 = 222020.
N = 505 is one of the exceptions. The only integer in the cycle is 505 so the total sum is 505 itself.
Here are the sums of the cycles for N = 1 to 60:
N sum
1 20
2 20
3 20
4 20
5 5
6 20
7 20
8 20
9 20
10 200
11 220
12 220
13 220
14 220
15 220
16 220
17 220
18 220
19 220
20 200
21 220
22 220
23 220
24 220
25 220
26 220
27 220
28 220
29 220
30 200
31 220
32 220
33 220
34 220
35 220
36 220
37 220
38 220
39 220
40 200
41 220
42 220
43 220
44 220
45 220
46 220
47 220
48 220
49 220
50 50
51 220
52 220
53 220
54 220
55 55
56 220
57 220
58 220
59 220
60 200
We'll call this the Seven's Cycle Sum Sequence.
Challenge
Write a program or function that takes in a positive decimal integer N and prints or returns, in decimal, the corresponding term of the Seven's Cycle Sum Sequence.
For example, if the input is 95801, the output should be 222020. If the input is 505, the output should be 505. If the input is 54, the output should be 220.
The shortest code in bytes wins.

Python 2, 69 bytes

lambda n:[''.join('02'[x>'0']for x in`n`)+'0',n][set(`n`)<=set('05')]

The function is simple to describe:

If n consists of only 0's and 5's, output it unchanged.
Otherwise, replace each digit of n with 2, except 0 stays 0, and tack on a 0 to the end.

The golfing can be improved, I'm mostly posting to share the method. A language with native regex should allow a short solution.
An alternative statement of the function is

In n, replace each digit with a 5, except 0 stays as 0
If this changed n (it had a digit other than 0 or 5), multiply the result by 4


Find the most important character Find the most important character

The challenge is to write a program that outputs the most occurrent character in the input string, excluding these bracketing characters ()[]{}.  Each submission should consist only of non-trivial* characters.  Each solution is scored using the formula in the scoring section.  Bracketing characters are allowed in the program, but may not be selected by the program as the most occurrent character.  In cases where letters occur with the same frequency, any or all of the characters may be returned.

*Non-trivial is defined in this case to be a character that contributes to the functionality of the program.  If the character can be removed without influencing how the program runs, it is a trivial character.

Scoring

Score is determined as follows:

$$(\frac{n_{char}}{n_{total}}) * 100(\%) $$

With nchar being the number of occurrences of the most frequent character in the input, and ntotal being the total number of non-trivial characters in the input.  With this scoring criteria, all scores should be within the range \$[0,100]\$

Highest scoring solution per language wins.

Input

Solutions should take in any valid string as input.  A convenient method of determining the most occurrent character in the program itself would be to use the program's source code as input to the program itself.  The program does not have to check for non-trivial characters, as they should not be included in the program source.

Output

A single character with the highest percentage occurrence.  Each solution should be capable of outputting standard ASCII, as well as the language's codepage (if applicable).

Errata

Creative solutions are encouraged.  Boring solutions with long padded strings substituted in for numbers are discouraged.  Standard loopholes are disallowed.

Examples

Program:

aabbbc

Output:

b

Program:

aabb

Output:

a or b or ab

Sandbox Link

05AB1E, 99.999999999999999957%

1111111111111111111 ... (9352835025086960662 1's total) ... 11111g₅B.V

g gets the length of the large integer literal. Obviously this is too long for TIO, so try a version using 9352835025086960662 instead of the equivalent 1111...1111g.


Source Code Byte Frequency Source Code Byte Frequency

Write a program that get a single byte character as an input and prints the frequency of that byte in the program's source code as an output.
Examples:
Assuming my program is: ab#cd%b then the output of the program should be (each line is a separate execution):
input         output
-----         ------
  a           0.1428571428571429
  b           28.57%
  #           14.2857143%
  c           1/7
  B           0

Rules:

The format of the proportion does not need to be consistent across all inputs, e.g. a fraction for one, decimal for another, percent for a third, plain zero for non-existent byte, etc...
If a proportion is represented as decimal, the result must be accurate to at least 4 decimal places.
Source code should be at least 1 byte long.

Scoring:
This is code-golf - the shortest code (≥1) wins.

(It would also be fun to get the shortest code in every language, so don't hesitate to post multiple entries)

JavaScript (ES6), 40 bytes
All used characters appear exactly twice. Therefore, this returns either 0 or 2/40 = 0.05.

F=_=>(F+'+./02>cdeilnsu').includes(_)/20

Try it online!


Make a Bowl of Alphabet Soup This is what we'll call a bowl of alphabet soup - a roughly circular ascii-art shape with the 26 uppercase English letters (A-Z) arranged clockwise to form the perimeter:
   XYZABC
 VW      DE
U          F
T          G
S          H
 RQ      JI
   PONMLK

Write a program that takes in a single letter character, A-Z, and outputs that same bowl of alphabet soup "rotated", so to speak, so the input letter appears where the A does in the example above and the rest of the alphabet cycles fully around clockwise.
So the output for input A would be that same original bowl of alphabet soup.
And the output for input B would be this one:
   YZABCD
 WX      EF
V          G
U          H
T          I
 SR      KJ
   QPONML

Likewise the output for H would be:
   EFGHIJ
 CD      KL
B          M
A          N
Z          O
 YX      QP
   WVUTSR

Or for Z:
   WXYZAB
 UV      CD
T          E
S          F
R          G
 QP      IH
   ONMLKJ

This needs to work for all 26 letters, A through Z.
Details:

You can assume the only input will be a single letter, A through Z.
If convenient you may use lowercase a-z for input and/or output, you can even mix and match lower and uppercase.
The alphabet order must cycle clockwise, not counter-clockwise.
You must use spaces, not something else, to indent and fill the soup bowl.
There may be leading or trailing newlines or spaces in the output as long as the soup bowl is arranged properly.
Note that the bowl shape is 12 characters wide by 7 tall to make it appear roughly circular as text. Your bowls need to be the same shape.

This is code golf so the shortest code wins!

05AB1E, 21 bytes

Defines a program \$f : \color{purple}{\texttt{AlphabeticChar}} \rightarrow \color{purple}{\texttt{String}}\$

Code:

2AA¹k._•1ëª»*Ć,ãiDΣ•Λ

Try it online!

Breakdown:

2AA¹k._•1ëª»*Ć,ãiDΣ•Λ

2                       # <length>
 AA¹k._                 # <filler>
       •1ëª»*Ć,ãiDΣ•    # <pattern>
                    Λ   # Invoke the canvas function.

Explanation:

The canvas (Λ) in this particular context works as a function with the following signature:

$$
\mathsf{\Lambda} : \left(\texttt{length}: \color{purple}{\texttt{Nat}},\ \texttt{filler}: \color{purple}{\texttt{String}},\ \texttt{pattern}: \color{purple}{\texttt{Nat}}\right) \rightarrow \color{purple}{\texttt{String}}
$$

The \$\texttt{pattern}\$ parameter is in this situation a number defining the directions. In the code, this number is represented as •1ëª»*Ć,ãiDΣ•, which is a compressed version of the big number \$2232344565666667670012122\$. Directions are denoted in the following manner:

$$
\begin{array}{l}
7 & & 0 & & 1 \\
  & \nwarrow & \uparrow & \nearrow & \\
6 & \leftarrow & \bullet & \rightarrow & 2 \\
  & \swarrow & \downarrow & \searrow & \\
5 & & 4 & & 3
\end{array}
$$

This means that the big number represents the following pattern of directions:

$$
[\rightarrow, \rightarrow, \searrow, \rightarrow, \searrow, \downarrow, \downarrow, \swarrow, \leftarrow, \swarrow, \leftarrow, \leftarrow, \leftarrow, \leftarrow, \leftarrow, \nwarrow, \leftarrow, \nwarrow, \uparrow, \uparrow, \nearrow, \rightarrow, \nearrow, \rightarrow, \rightarrow]
$$

With this signature context, the canvas iterates through the \$\texttt{pattern}\$ list and writes \$\texttt{length}\$ characters from the \$\texttt{filler}\$ in the current direction.

The \$\texttt{length}\$ is specified in the code as \$2\$ (at the beginning of the code). For the \$\texttt{filler}\$, we need a rotated version of the alphabet such that it starts with the given input. That is done with the following code (try it here):

AA¹k._

 A¹k       # Find the <index> of the given input character in the alphabet
A   ._     # Rotate the alphabet to the left <index> times.

In pseudocode, this would be executed by the canvas function:

\$
\begin{array}{l}
1. & \text{Write } \color{blue}{\texttt{ab}} \text{ in the direction} \rightarrow \\
2. & \text{Write } \color{blue}{\texttt{bc}} \text{ in the direction} \rightarrow \\
3. & \text{Write } \color{blue}{\texttt{cd}} \text{ in the direction} \searrow \\
4. & \text{Write } \color{blue}{\texttt{de}} \text{ in the direction} \rightarrow \\
5. & \text{Write } \color{blue}{\texttt{ef}} \text{ in the direction} \searrow \\
6. & \text{Write } \color{blue}{\texttt{fg}} \text{ in the direction} \downarrow \\
\dots
\end{array}
\$

Lastly, you can see that the filler argument is 'rotated' \$\texttt{length} - 1\$ times to the right, meaning that the canvas would iterate through the following (cycled and therefore infinite) list:

$$
[\color{blue}{\texttt{ab}}, \color{blue}{\texttt{bc}}, \color{blue}{\texttt{cd}}, \color{blue}{\texttt{de}}, \color{blue}{\texttt{ef}}, \color{blue}{\texttt{fg}}, \color{blue}{\texttt{gh}}, \color{blue}{\texttt{hi}}, \color{blue}{\texttt{ij}}, \color{blue}{\texttt{jk}}, ...
$$

Which results in the desired alphabet soup ascii-art shape.


Benfords Law of Words Background

Benford's Law is freaky!

Of all the numbers in the world, roughly 30% of them start with a 1! 17.6% start with a 2, 12.5% start with a 3, and so on, and so on.

For example, take a look at the following graph. Take the largest 120000 towns in the world, take their altitude, and voila - they obey Benford's law. Divide these numbers by ~3 to convert them into meters, and amazingly, they still obey this law!

In fact, it can be generalized past the first digit:

Source

Challenge

So I wondered, how does this apply to letters and words?

Your challenge is to parse the big list of words below and formulate the table above (printing a matrix will suffice). Unlike this work, you will not only need to find the occurrence of the first letter, but also the second, third, fourth, and fifth. If a word does not have the nth digit, you can ignore that word (i.e. if you are compiling the 5th column (looking at the fifth digit), you should ignore all words less than 5 characters long)

Big List of Words: https://raw.githubusercontent.com/kevina/wordlist/master/alt12dicts/2of4brif.txt

Due to suggestion in the comments, this contest is now a code golf competiton, so shortest code in bytes wins. The entry must be a complete program and must output the table specified above. Built-ins are allowed.

Good luck!

Mathematica 246 bytes
The probabilities are based on all the words in the file.
p=Prepend;t=Transpose;d="Digit";
p[t[p[N[#/Total@#,5]&/@ t[Sort[Cases[Tally[Position[Characters
@Import["t.txt","List"],#][[All,2]]],{n_,_} /;n<6]]/.{_,k_}->k&/@
(c=CharacterRange["a","z"])],c]],{d,"1st "<> d,"2nd "<>d,"3rd "<>d,"4th "<>d,"5th "<>d}]
//Grid

In the given list of 60387 words, the occurrences are distributed as follows. Letters "s" and "c" are the most likely to appear at the beginning of a word (7455 and 6008, respectively). Only 11 words begin with the letter "x".

Without headers in table  162 bytes
t=Transpose;t[N[#/Total@#]&/@t[Sort[Cases[Tally[Position[Characters@Import["t.txt", "List"], #][[All,2]]],{n_,_} /;n<6]]/.{_,k_}->k&/@CharacterRange["a","z"]]]//Grid


Transformers in Disguise (Cops' Thread) The robber's thread is here

The cops task is to write a function or program that, when given an input of itself, outputs a finite deterministic string. If the program is given a different input, it should return a different output.

Rules:

Submissions consist of

Language name

If any flags are used, they should be revealed.

Byte count of program
Byte count of output
Output

If it is particularly long, please provide a pastebin or something similar
If it contains unprintables, please provide a hexdump.
Trailing newlines and whitespace should be included in the output

Where the input is coming from (STDIN, command line, etc.)

If applicable, you may assume that the byte representing EOF is not present in the input, unless you use that byte in your program.
If your program is cracked, add a link to the corresponding answer in the robber's thread in your title.
Your program is not safe until a week has passed and you mark it so.
I disapprove of techniques like seeding random with the input or cryptographic hash functions. I can't stop them, but I will not be accepting a solution that utilises either of these. Also note that some of these techniques might have collisions, where a different string produces the same output.
Your goal is to have the shortest output. The shortest safe solution posted within three weeks of posting this question wins!

The robber's task is to find a program of size equal to or less than the original, which also obeys the above rules.

If a robber cracks your program with a different solution than intended, then you have the opportunity to 'uncrack' it by proving that the robber's solution is incorrect. You can do this by finding an input to the robber's program that will produce the same output.

Example Submission:

brainfuck, 10 bytes, Score: 10

]<.[<],>[,

This solution is ,[>,]<[.<] which simply reverses the input

Good luck!

7, 31 characters, score 30, safe but possibly broken?

A 7 program is normally just a number, but it can contain whitespace, splitting it into multiple numbers. This submission therefore consists of two numbers (which are implicitly concatenated by the 7 interpreter), and the program likewise takes two numbers as input, via standard input. (The "31 characters" in the header is the total length of the two numbers, plus one separating whitespace character; the digits that make up the numbers are interpreted as octal when used as a program, but decimal when used as an input, and it's the digits that are the same in the two cases, not the actual numbers. Note that it's irrelevant either when treated as a program, or when treated as an input, whether you separate them with a space or a newline; I hope that doesn't invalidate the submission.)

The expected output is the following number (expressed here in decimal, as that's the output format that the 7 interpreter uses):

238363505302130098723162537059

Note that the 7 interpreter linked from the Esolang wiki internally stores numbers in unary, meaning you're unlikely to have enough memory to actually run the program on itself to see what it does. I verified the program via working out its behaviour manually, and testing it on small inputs to verify that it did what I expected it to do. An alternative approach would be to write an interpreter that uses a more efficient method of storing numbers.

Avoiding cracks here was something of a pain, but I'm finally now satisfied that no two numbers other than those in the program itself are capable of producing 238363505302130098723162537059 as output. (EDIT 1 week later: I may have been wrong, depending on how you interpret the question; see below.)

Solution

The original program was:

  711170237403706
111723603700633

This program takes two numbers \$x\$ and \$y\$, and calculates the result of the expression \$3xy-y-2\$ (i.e. \$y(3x-1)-2\$). If we perform this calculation at \$x=711170237403706\$ and \$y=111723603700633\$, we get a result of \$238363505302130098723162537059\$ as required.

It was intended that no other input will give the desired result because:

  The input must be chosen such that \$y(3x-1)-2=238363505302130098723162537059\$, i.e. \$y(3x-1)=238363505302130098723162537061\$ (adding 2 to both sides). This number is a semiprime, with only two factors: \$111723603700633\$ and \$2133510712211117\$. Only one of these numbers, \$2133510712211117\$, can be expressed in the form \$3x-1\$ (giving \$(3 \times 711170237403706)-1=2133510712211117\$). So we can uniquely identify which number is \$x\$ and which is \$y\$, meaning that only one input works.

However, depending on how you interpret the question, there may be a second input that produces the desired output (thus invalidating this solution):

  Unfortunately, there are two multiplicative partitions of a semiprime into two factors: one is to divide it into the two prime factors, but the other is the trivial partition consisting of \$1\$ and the number itself. \$1\$ cannot be written in the form \$3x-1\$ with integer \$x\$, but the desired output can be; thus a potential meta-crack involves giving the input as \$79454501767376699574387512354\$ and \$1\$. However, the first number here involves characters (\$8\$ and \$9\$) which are not in the character set for 7 programs. So if input is restricted to being in the same character set as the program, this solution is valid; but if input containing characters from outside the program's character set is allowed, this solution is invalid.

Explanation

Here's how the intended solution functions:

  711170237403706 111723603700633
7   7   7                         Stack element separators
 111 023 403706 111723603700633   Initial stack elements
 111                              Number 3, in unary
     023                          I/O DSL for "input a number"
         403706 111723603700633   Main program
(Implicit: execute a copy of the main program element, preserving the original)
         40                       Swap {023} above {program}, escaping it
           3                      Do I/O using {023}; pop {program}
     0                            I/O: numeric
      23                          Input a number, copying {111} that many times
            706                   Append "6" to the number (decrementing it)
                11                Push two empty stack elements
                  17236           Push a stack element "23" (unescaped)
                       0          Escape {23}, consuming an empty element
                        3         Do I/O using {23}; pop {the element below}
                    23            Copy the top of stack input many times
                         7006     Append "66" (i.e. subtract 2)
                             3    Output {as a number}
                              3   Exit the program (due to low stack)
The leading 7 and trailing 3 aren't necessary for the program's functionality, they're just there to get the prime factors of the output right. It helps to follow this program if you understand the numeric format; numbers are stored in a unary variant in which 1 and 7 increase the value by 1, and 0 and 6 decrease the value by 1 (thus appending 66 decreases the value by 2, repeating the number multiplies it, and so on). Input's done by repeating a stack element (thus if the stack element is 12345 and the input is \$3\$, the new stack element will be \$123451234512345\$).


Pair and sort from two integer lists You are given two arbitrary integer lists, e.g. [-10, 99, -6, 43], [100, 32, 44]. You are to pick one integer from each list and sum them up, then sort the best pairs ordered by the absolute distance to 100 in ascending order. Paired up integers from each list shall not be repeated in the output.

For instance, we have

(-10, 100): |100 - (-10 + 100)| = 10
(-10, 32) : |100 - (-10 + 32 )| = 78
(-10, 44) : |100 - (-10 + 44 )| = 66
(99, 100) : |100 - (99 + 100 )| = 99
(99, 32 ) : |100 - (99 + 32  )| = 31
(99, 44 ) : |100 - (99 + 44  )| = 43
(-6, 100) : |100 - (-6 + 100 )| = 6
(-6, 32 ) : |100 - (-6 + 32  )| = 74
(-6, 44 ) : |100 - (-6 + 44  )| = 62
(43, 100) : |100 - (43 + 100 )| = 43
(43, 32 ) : |100 - (43 + 32  )| = 25
(43, 44 ) : |100 - (43 + 44  )| = 13

After pairing with the first item -10, it is tempted to pick the pair (-10, 100) as the best pair as it has the least distance to 100. But further checking down the list, (-6, 100) in fact has a lesser distance to 100, hence it should be the best pair picked. After picking the pair, they are removed from their lists, leaving us

(-10, 32) : |100 - (-10 + 32)| = 78
(-10, 44) : |100 - (-10 + 44)| = 66
(99, 32 ) : |100 - (99 + 32 )| = 31
(99, 44 ) : |100 - (99 + 44 )| = 43
(43, 32 ) : |100 - (43 + 32 )| = 25
(43, 44 ) : |100 - (43 + 44 )| = 13

Then next pair to pick will be (43, 44). Notice that the distance to 100 is 13 for this pair, which is higher than the pair (-10, 100), but only because 100 has been paired with -6 and hence the pair (-10, 100) is gone. Moving on, we have these remaining

(-10, 32) : |100 - (-10 + 32)| = 78
(99, 32 ) : |100 - (99 + 32 )| = 31

And finally (99, 32) is picked. Hence the output (-6, 100), (43, 44), (99, 32). Ignore the rest that have nothing to pair up.

Note: when there is a tie, just pick any pair, without worrying the consequence to the remaining candidates.

The challenge here is to complete the task with the least number of comparisons operating on the inputs. i.e. if all comparison result has to come from a function comp(a, b), then the least number of call to this function wins. Looping control etc. are not included. Three way comparison is essentially 2 operations. General purpose code only and no special purpose optimisation is required. Favour code that can verify the number of comparison calls, however, when using build in functions, please explain their complexity for us to examine.

Python O(mn log mn)

The best pairs can be found computing the distances of all the possible pairs, and iteratively choosing the best pair among those remaining after filtering out the already chosen items.

A simple implementation is shown in the following code:

def find_nearest_pairs_to_100(l, m):
    pair_list = sorted([((i, j), abs(100 - i - j)) for i in l for j in m], key=lambda x: x[1])
    chosen_pairs = []
    while pair_list:
        best_pair = pair_list[0][0]
        chosen_pairs.append(best_pair)
        pair_list = [(p, s) for (p, s) in pair_list if p[0] != best_pair[0] and p[1] != best_pair[1]]
    return chosen_pairs

The find_nearest_pairs_to_100 function takes the two lists in input and returns an ordered list with the chosen pairs.

The sorted function in Python is based on Timsort algorithm, that requires O(n log n) comparisons in the worst case (where n is the length of the list).

In this case the length of the list is the cardinality of the Cartesian product of the two input lists, i.e. mn (with n > m). Therefore, the total cost of this implementation is of O(mn log mn) comparisons, excluding the other comparison operations needed for filtering.

Including comparisons for filtering, at each iteration, in the worst case, all the items of the list are checked against the elements of the chosen pair; the length the pair_list is mn at the first iteration, (n-1)(m-1) at the second, (n-2)(m-2) at the third, and n-m+1 at the last step. So the total number of comparisons for filtering is O(n^3).

If you like golfing, it is a golfed version (163 bytes) of the previous one (a little bit different):

f=lambda l,m:l and m and[[k]+f(l.remove(k[0])or l,m.remove(k[1])or m)for k in sorted([[[[i,j]],abs(100-i-j)]for i in l for j in m],key=lambda x:x[1])[0][0]][0]or[]


Create a C preprocessor The goal is to create a preprocessor for the C language, as small as possible in terms of source code size in bytes, in your preferred language.
Its input will be a C source file, and its output will be the pre-processed source code.

The items that it will need to be able to process shall be:
Comment removal (line/block), #include directives (by opening files at relative paths and replacing text at the point needed), #define, #undef, #if, #elif, #else, #endif, #ifdef, #ifndef, and defined(). Other C preprocessor directives like #pragmas or #errors may be ignored.

There is no need to calculate arithmetic expressions or comparison operators in #if directives, we assume the expression will evaluate to true as long as it contains an integer other than zero (its main use will be for the defined() directive). Examples of possible input and output follow (possible extra whitespaces in output files were trimmed for better appearance, there is no need for your code to do so). A program able to process the following examples properly will be considered sufficient.

----Input file: foo.c (main file being preprocessed)

#include "bar.h" // Line may or may not exist

#ifdef NEEDS_BAZZER
#include "baz.h"
#endif // NEEDS_BAZZER

#ifdef _BAZ_H_

int main(int argc, char ** argv)
{
    /*  Main function.
        In case that bar.h defined NEEDS_BAZ as true,
        we call baz.h's macro BAZZER with the length of the
        program's argument list. */
    return BAZZER(argc);
}

#elif defined(_BAR_H_)

// In case that bar.h was included but didn't define NEEDS_BAZ.
#undef _BAR_H_
#define NEEDS_BARRER
#include "bar.h"

int main(int argc, char ** argv)
{
    return BARRER(argc);
}

#else

// In case that bar.h wasn't included at all.
int main()
{return 0;}

#endif // _BAZ_H_

----Input file bar.h (Included header)

#ifndef _BAR_H_
#define _BAR_H_

#ifdef NEEDS_BARRER

int bar(int * i)
{
    *i += 4 + *i;
    return *i;
}

#define BARRER(i) (bar(&i), i*=2, bar(&i))

#else
#define NEEDS_BAZZER // Line may or may not exist
#endif // NEEDS_BARRER

#endif // _BAR_H_

----Input file baz.h (Included header)

#ifndef _BAZ_H_
#define _BAZ_H_

int baz(int * i)
{
    *i = 4 * (*i + 2);
    return *i;
}

#define BAZZER(i) (baz(&i), i+=2, baz(&i))

#endif // _BAZ_H_

----Output file foopp.c (no edits)

int baz(int * i)
{
    *i = 4 * (*i + 2);
    return *i;
}

int main(int argc, char ** argv)
{
    return (baz(&argc), argc+=2, baz(&argc));
}

----Output file foopp2.c (with foo.c's first line removed)

int main()
{return 0;}

----Output file foopp3.c (with bar.h's line "#define NEEDS_BAZZER" removed)

int bar(int * i)
{
    *i += 4 + *i;
    return *i;
}

int main(int argc, char ** argv)
{
    return (bar(&argc), argc*=2, bar(&argc));
}

Flex, 1170+4=1174

1170 characters in the flex code + 4 characters for a compilation flag.  To produce an executable, run flex pre.l ; gcc lex.yy.c -lfl.  The entry leaks memory like a sieve and doesn't close included files.  But otherwise, it should be completely functional as per the spec.

%{
#define M malloc
#define X yytext
#define A a=X
#define B(x) BEGIN x;
#define Y YY_CURRENT_BUFFER
*a,*b,**v,**V,**t,**T,i,s=1,o;
g(){t=M(++s);T=M(s);for(i=1;i<s-1;i++)t[i]=v[i],T[i]=V[i];free(v);free(V);v=t;V=T;}
f(){for(i=1;i<s;i++)if(!strcmp(v[i],a))return i;return 0;}
d(y){X[yyleng-y]=0;}
%}
%x D F I
N .*\n
%%
"//".*
"/*"([^\*]|\*[^\/])*"*/"
\"(\\.|[^\\"])*\" ECHO;
^"#include "\"[^\"]*\" d(1),yypush_buffer_state(yy_create_buffer(fopen(X+10,"r"),YY_BUF_SIZE));
^"#define "[^ ]* {B(D)strcpy(a=M(yyleng),X+8);}
<D>" "?{N} {b=M(yyleng);d(1);f(strcpy(b,X+(X[0]==32)))?free(V[i]),V[i]=b:g(),v[s-1]=a,V[s-1]=b;B(0)}
^"#undef "{N} d(1),v[f(A+7)][0]=0;
^"#if defined(".*")\n" h(2,12);
^"#ifdef "{N} h(1,7);
^"#if "{N} {d(1);if(!atoi(X+4))B(F)}
^"#ifndef "{N} {d(1);if(f(A+8))B(F)}
<F>^"#if"{N} o++;
<F>^"#endif"{N} if(!o--)B(++o)
<F>^"#else"{N} if(!o)B(0)
<F>^"#elif defined(".*")\n" if(!o){d(2);if(f(A+14))B(0)}
<F>^"#elif "{N} if(!o){d(1);if(atoi(X+6))B(0)}
<F>{N}
^"#endif"{N}
^"#el"("se"|"if"){N} B(I)
<I>^"#endif"{N} B(0)
<I>{N}
[a-zA-Z_][a-zA-Z_0-9]* printf(f(A)?V[i]:a);
<<EOF>> {a=Y;yypop_buffer_state();if(!Y)exit(0);fclose(a);}
%%
h(x,y){d(x);if(!f(A+y))B(F)}

Some explanation:

a and b are temps to hold strings from the input.  a is also used as the parameter to function f.
v holds the names of macros and V holds the 'V'alues of macros
t and T are 't'emporary holders for when we grow v and V
i is an 'i'ncrementer for loops
s is the 's'ize of the macro array
o is the count of the 'o'pen ifs inside a false conditional
g() 'g'rows the macro arrays
f() 'f'inds a macro with the same value in v as a
d(y) 'd'rops the last y characters from the current input
state D is for inside a 'D'efine
state F is for ignoring a 'F'alse conditional
state I is for 'I'gnoring else/elif after a true conditional was found.

EDIT1: cleaned up many of the memory leaks and implemented file closing

EDIT2: modified code to handle nested macros more correctly

EDIT3: crazy amount of golfing

EDIT4: more golfing

EDIT5: more golfing; I've also noticed that my call to fclose() causes issues on some computers...looking into this.


Parse a Scala expression Scala isn't a very commonly used language around here. Most of those who know it like it[citation needed], but some go :\ when they encounter its user-defined operators, saying they're too complicated.
However, they're governed by a very simple set of rules, outlined here. Their precedence depends on the first character. Here's the list for that (highest to lowest precedence):
* / %
+ -
:
= !
< >
&
^
|
(all letters)

So this
a + b ^? c less a ==> b | c

would be the same as this
((a + b) ^? c) less ((a ==> b) | c)

Your task is to turn such an expression (only infix applications) into a tree-like structure or a string with all the sub-expressions in parentheses.
Input
A string or multiple characters given as an argument to a function, read from STDIN, given as command-line arguments, or using one of the other default input methods. This string is the expression to be parsed.
Output
You could do one of the following, printed to STDOUT, returned from a function, or one of the other default output methods:

The same string but with parentheses outside each sub-expression (the outermost expression may or may not be parenthesized). E.g., expr op expr2 op2 expr3 -> (expr op expr2) op2 expr3. If you wish, you may also parenthesize the atoms ((((expr) op (expr2)) op2 (expr3)))
A multidimensional list, where each expression would broken up into the left argument, the operator/method, and the right argument. E.g., expr op expr2 op2 expr3 -> [['expr','op','expr2'],'op2','expr3']
Some tree-like structure equivalent to the above 2 representations. You get the idea.

Rules

All operators used are binary, infix, and left-associative.
Parsing goes from left to right.
There will always be one or more spaces between arguments and operators.
Operators may consist of any of the symbols mentioned above (*/%+-:=!<>&^|) and uppercase or lowercase letters([A-Za-z]). They will be one or more characters.
Arguments to methods may be other expressions or alphabetical identifiers ([A-Za-z]).
This is code-golf, so shortest code wins!

Test cases
More coming soon
Input                             -> Output
a -- blah /\ foo                  -> a -- (blah /\ foo)
same ** fst *^ chr *& operators   -> ((same ** fst) *^ chr) *& operators
Lots   Of     SpAceS // here      -> Lots Of (SpAceS // here)
Not : confusing * At / ALL iS it  -> (Not : ((confusing * At) / ALL)) iS it
This *isnot* valid ** Scala       -> (This *isnot* valid) ** Scala

JavaScript (ES6),  180 ... 155  152 bytes
Returns a multidimensional list. The outermost expression is parenthesized, and so are the atoms.

f=(i,a=i.split(/ +/))=>"w | ^ & <> =! : +- */%".split` `.some(p=>a.map((s,j)=>i=!!s.match(`^[\\${p}]`)&j?j:i)|i)?[f(i=a.splice(i),a),i.shift(),f(a,i)]:a

Try it online!
How?
This is a recursive algorithm. At each iteration, we look for the last operator with the lowest precedence, split the expression at this position and process recursive calls on both resulting parts. We stop the recursion when we reach an atom.
In order to split the expression and isolate the operator, we use a combination of splice() and shift() as shown in the following example, where integers are used instead of operators and operands.
a = [ 0, 1, 2, 3, 4, 5, 6 ];
i = 3;
i = a.splice(i); // --> a[] = [ 0, 1, 2 ] (left expression)
                 //     i[] = [ 3, 4, 5, 6 ] (operator + right expression)
i.shift();       // --> operator = 3
                 //     i[] = [ 4, 5, 6 ] (right expression)

Commented
f = (                      // f is a recursive function taking:
  i,                       //   i   = input string on the 1st iteration,
                           //         and then some non-empty array
  a = i.split(/ +/)        //   a[] = input string split on spaces
) =>                       //         NB: operators are expected at odd positions
  "w | ^ & <> =! : +- */%" // this string describes the groups of operators,
                           // from lowest to highest precedence
  .split` `                // split it
  .some(p =>               // for each pattern p:
    a.map((s, j) =>        //   for each string s at position j in a[]:
      i =                  //     update i:
        !!s.match(         //       see if s matches p; the '\' is required for
          `^[\\${p}]`      //       'w' and '^', and harmless for the other ones
        ) & j ?            //       if there's a match and j is odd:
          j                //         update i to j
        :                  //       else:
          i                //         leave i unchanged
    )                      //   end of map()
    | i                    //   make some() succeed if i is a number
  ) ?                      // end of some(); if successful:
    [                      //   build a new array consisting of:
      f(                   //     the result of a recursive call ...
        i = a.splice(i), a //     ... with the left expression
      ),                   //
      i.shift(),           //     followed by the operator
      f(                   //     followed by the result of a recursive call ...
        a, i               //     ... with the right expression
      )                    //
    ]                      //   end of new array
  :                        // else:
    a                      //   just return a[]


How many carries do I need to add these two numbers? Task

Given two positive integers, output the number of carries needed to add them together in long addition in base 10.

Examples

¹¹¹   <-- carries
 999
+  1
----
1000

Three carries are needed.

 ¹
 348
+ 91
----
 439

One carry is needed.

Testcases

999,   1 -> 3
398,  91 -> 1
348,  51 -> 0
348,  52 -> 2
  5,  15 -> 1
999, 999 -> 3
505, 505 -> 2

Scoring

This is code-golf. Shortest answer in bytes wins. Standard loopholes apply.

Mathematica, 46 39 bytes
x=Tr@*IntegerDigits;(x@#+x@#2-x@+##)/9&

input

[348,51]

-7 bytes from JungHwan


Find the unique twins You will be given two Arrays / Lists / Vectors of non-negative integers A and B. Your task is to output the highest integer N that appears in both A and B, and is also unique in both A and B.

You may assume that there is at least one such number.
Any reasonable Input and Output method / format is allowed.
These Loopholes are forbidden.
This is code-golf, so the shortest code in every programming language wins!

Test Cases:

A, B -> Output

[6], [1, 6] -> 6
[1, 2, 3, 4], [4, 5, 6, 7] -> 4
[0, 73, 38, 29], [38, 29, 73, 0] -> 73
[1, 3, 4, 6, 6, 9], [8, 7, 6, 3, 4, 3] -> 4
[2, 2, 2, 6, 3, 5, 8, 2], [8, 7, 5, 8] -> 5
[12, 19, 18, 289, 19, 17], [12, 19, 18, 17, 17, 289] -> 289
[17, 29, 39, 29, 29, 39, 18], [19, 19, 18, 20, 17, 18] -> 17
[17, 29, 39, 29, 29, 39, 18, 18], [19, 19, 18, 20, 17, 18] -> 17

Jelly, 7 bytes

fċ@ÐṂ;Ṁ

Try it online!

How it works

fċ@ÐṂ;Ṁ  Main link. Left argument: A. Right argument: B

f        Filter; keep those elements of A that appear in B.
   ÐṂ    Yield all elements of the result for which the link to left yields a
         minimal value (2).
 ċ@        Count the occurrences of the element...
     ;     in the concatenation of A and B.
      Ṁ  Take the maximum.


Brachylog, 27 23 bytes

:1f
hS,?tye.:S+:.L*$pL,

Try it online!

Verify all testcases.

Predicate 0 (main predicate)

:1f                     Find all solutions of predicate 1
                        given Input as Input,
                        Unify Output with the set of all solutions.

Predicate 1 (auxiliary predicate)

hS,?tye.:S+:.L*$pL,

hS                      the first element of Input is S,
   ?tye.                Output is an element between 0 and
                        the last element of Input,
       .:S+:.L          The list [Output+S,Output] is L,
             L*$pL      The product of L, prime-factorized, is still L


Can I take your order: a Chipotle concept conund Challenge

Your program will take in a string from stdin, and output multiple lines to stdout.

An example of input looks like this:

My favorite Chipotle order:

  B1113YNNY

Let's break it down:

The first character is either A (burrito), or B (burrito bowl).
The second character is 1 (black beans), or 2 (pinto beans).
The third character is either 1 (white rice), or 2 (brown rice).
The fourth character is either 1 (chicken), 2 (sofritas), or 3 (steak).
The fifth character is either 1 (mild salsa), 2 (medium salsa), or 3 (hot salsa).
The last four characters are Y if they want the item, or N otherwise:
character 6 is corn
character 7 is guacamole
character 8 is sour cream
character 9 is cheese

A working program for this challenge will output this to stdout:

  burrito bowl with:
  black beans
  white rice
  chicken
  hot salsa
  corn
  cheese

Replace the above words with the words acquired from input.

Clarifications.

Standard loopholes are disallowed.
You may only get input from stdin, and only put output to stdout.

Python 3, 293 bytes

j=input();a,b,c,d,e,f,g,h,i=[1-ord(c)%7%5for c in j];print('\n'.join(('burrito'+[' bowl',''][a]+' with:',['pinto','black'][b]+' beans',['brown','white'][c]+' rice',['sofritas','chicken','steak'][d],['medium','mild','hot'][e]+' salsa'))+'\ncorn'*f+'\nguacamole'*g+'\nsour cream'*h+'\ncheese'*i)

Mostly basic lookups with a little modulo trickery for the indexes of items:
AB123YN yielding indexes -1,-2,1,0,-1,1,0 respectively, and
using string multiplication for the optional items rather than a lookup.


Print all ASCII alphanumeric characters without using them Challenge

Print the following characters:

abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890

The catch is that you may not use any one of them in your code.

You may print them in arbitrary order, with or without a leading or trailing newline, but you may not print any other characters.

Rules

You may not use any characters from the set mentioned above
You may use any other characters
No cheating
Standard loopholes banned
This is code-golf, shortest answer wins.

Clarifications

If your language uses a different charset, you may not use codepoints in that charset that correspond to alphanumeric characters.
Returning a string from a function is considered a valid form of output.
You may return a char array.

Octave, 52 46 40 bytes

['['-('"':'+'),'{'-(_='!':':'),_+'@','']

This evaluates to

9876543210ZYXWVUTSRQPONMLKJIHGFEDCBAabcdefghijklmnopqrstuvwxyz

Explanation

Here we are using the fact that characters are implicitly converted to integers when arithmetic operations like +- or the range function : are applied. When concatenated with an empty string ([...,'']), the numbers again are converted to characters.

Try it online!


Motion on a hexagonal grid Given an input of a series of characters representing movements on a hexagonal
grid, output the final coordinates of the "pointer."

Our hexagons will be numbered like so (imagine a rectangular grid with every odd-numbered column shifted downwards slightly):

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

The pointer starts at (0, 0).

The instructions you must support are as follows:

q: move up-left
w: move up
e: move up-right
a: move down-left
s: move down
d: move down-right
r: rotate grid clockwise
R: rotate grid counterclockwise

The rotation commands rotate the entire grid while keeping the pointer at the same coordinates. (Why qweasd? They match up with the directions nicely on a QWERTY keyboard.)

To help visualize this, here's what the movement commands would do, assuming
the pointer starts in the middle:

         _____
        /     \
  _____/   w   \_____
 /     \       /     \
/   q   \_____/   e   \
\       /     \       /
 \_____/       \_____/
 /     \       /     \
/   a   \_____/   d   \
\       /     \       /
 \_____/   s   \_____/
       \       /
        \_____/

After a clockwise rotation (r), the commands are remapped to (imagine it as
rotating the entire hex grid but still keeping "w" as up, etc., which is
equivalent to the following):

         _____
        /     \
  _____/   e   \_____
 /     \       /     \
/   w   \_____/   d   \
\       /     \       /
 \_____/       \_____/
 /     \       /     \
/   q   \_____/   s   \
\       /     \       /
 \_____/   a   \_____/
       \       /
        \_____/

Similarly, rotating counterclockwise (R) after that would return the grid to
normal, and rotating counterclockwise again would "remap" qwedsa to aqweds.

Input must be given as a single string, and output can be either a single
string joined by any non-numerical characters (ex. 1 2 or 3,4) or an array
of integers.

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

Test cases:

In                         Out
---------------------------------
edeqaaaswwdqqs             -2, 0
dddddddddd                 10, 5
wswseaeadqdq               0, 0
<empty string>             0, 0
esaaqrweesrqrq             -1, 0
wrwrwrwrw                  -1, 0
RRssrrrs                   -1, -1
aRRRRwddrqrrqqq            -1, -4
rrrrrrrrrrrrRRRRRRrrrrrrq  -1, -1
rrRrRrrRrrrrRRrRrRR        0, 0

Retina, 353 339 178 175 150 130 129 117 bytes

R
5$*r
T`aq\we\ds`so`r.+
)`r(.*)
$1
^
:
a
sq
e
wd
+`(.+)q
w$1
+`(.+)d
s$1
+`sw

(.*)(\1w?):
$0$2
+`sw|ws

w+
-$0
\w
1

Output is in unary, separated by a colon. That means you won't really see zeroes in the output (although the presence of a colon will tell you which of the two coordinates is zero, if there is only one).

Try it online!

This was really fun and ended up being surprisingly short. :)

Explanation

Some background first. There are several coordinate systems to describe hexagonal grids. The one asked for uses offset coordinates. That's essentially like rectangular grid coordinates, except that one axis "wobbles" a bit. In particular, the question asks for the "odd-q" layout shown on the linked page. This coordinate system is a bit annoying to work with, because how the coordinates change during a move depends not only on the direction of the move but also on the current position.

Another coordinate system uses axial coordinates. That's essentially imagining the hexgrid as a diagonal slice through a volume of cubes, and using two of the axes (e.g. x and z) to find a position on the 2D plane. On the hex grid, that means that the two axes form an angle of 60 (or 120) degrees. This system is a bit less intuitive but much easier to work with, since every direction corresponds to a fixed "delta" vector. (For a better explanation of how to arrive at this coordinate system, check out the link and the lovely diagrams and animations there.)

So here's what we'll do: we compute the movement in axial coordinates (taking care of rotation as suggested in the challenge, by remapping the meaning of the commands), and when we're done we convert axial to to odd-q offset coordinates.

The six moves map to the following delta vectors in (x-z) axial coordinates:

q => (-1,  0)
w => ( 0, -1)
e => ( 1, -1)
d => ( 1,  0)
s => ( 0,  1)
a => (-1,  1)

Wait, this is Retina, we'll have to work with unary numbers. How do we work with negative unary numbers? The idea is to use two different digits. One represents +1 and the other represents -1. That means regardless of whether we want add or subtract 1 from the current position, we can always do so by adding a digit. When we're done we collapse the result into its magnitude (of the corresponding digit) by cancelling balanced digits. Then we figure out the sign based on the remaining digit, and replace all digits with 1.

The plan is to build up the axial x and z components to the left and right of a : (as a separator), in front of the input. w and s will add to the right-hand side. q and d will add to the left-hand side, and e and a will add to both sides. Since w and s are already on the correct side of the : (which will go in front), we will use those as the -1 and +1 digits, respectively.

Let's go through the code.

R
5$*r

We start by turning each R into five rs. Of course, one left turn is the same as five right turns on a hex grid, and by doing so we can a lot of duplication on the remapping step.

T`aq\we\ds`so`r.+

This is a transliteration stage which rotates the six commands, if they are found after the first r (thereby processing the first r). w and d need to be escaped to prevent them from expanding into character classes. The o inserts the source set into the target set which saves a bunch of bytes for these rotation tasks. The character mapping is therefore:

aqweds
saqweds

where the last s in the second row can simply be ignored.

)`r(.*)
$1

This removes the first r from the string, because it's been processed (I wish I had already implemented substitution limits...). The ) also tells Retina to run all stages up to this one in a loop until the string stops changing. On subsequent iterations, the first stage is a no-op because there are no more Rs and the second stage will apply another rotation as long as there are rs left in the string.

When we're done, we've mapped all commands to the direction they correspond to on the unrotated grid and can start processing those. Of course this movement is just a sum of those delta vectors, and sums are commutative, so it doesn't really matter in which order we process them now that rotations have been eliminated.

^
:

Insert the coordinate delimiter at the front.

Now we don't really need to process s and w. They are our +1 and -1 digits and they're already on the correct side of the : so they'll just drop out as required in the end. We can make another simplification: a is simply s + q and e is w + d. Let's do that:

a
sq
e
wd

Again, those s and w will just drop out. All we need to do is move those qs and ds to the front and turn them into ws and ss themselves. We do that with two separate loops:

+`(.+)q
w$1
+`(.+)d
s$1

So that's done. Time for the conversion from axial to offset coordinates. For that we need to collapse the digits. However, for now we only care about the left-hand side. Due to the way we've processed the qs and ds, we know that all the ss in the left-hand side will appear in front of any ws, so we only need to check one pair for collapsing the them:

+`sw

Now the actual conversion. Here is the pseudocode, taken from link above:

# convert cube to odd-q offset
col = x
row = z + (x - (x&1)) / 2

Right, so the left-hand side is already correct. The right-hand side needs the correction term (x - (x&1)) / 2 though. Taking &1 is the same as modulo 2. This basically parses as x/2, integer division, rounded towards minus infinity. So for positive x, we add half the number of digits (rounded down), and for negative x, we subtract half the number of digits (rounded up). This can be expressed surprisingly concisely in regex:

(.*)(\1w?):
$0$2

Due to the greediness, for even x, group 1 will match exactly half the digits, \1 the other half and we can ignore the w?. We insert that half after the : (which is x/2). If x is even, then we need to distinguish positive and negative. If x is positive, then w? will never match, so the two groups will still have to match the same number of digits. That's no problem if the first s is simply skipped, so we round down. If x is negative and odd, then the possible match is with \1 (half of x rounded down) and that optional w. Since both of those go into group 2, we will write x/2 with the magnitude rounded up (as required).

+`sw|ws

Now we collapse the digits on the right-hand side. This time, we don't know the order of the s and w, so we need to account for both pairs.

w+
-$0

Both parts are now reduced to a single repeated digit (or nothing). If that digit is w, we insert a minus sign in front.

\w
1

And finally we turn both into w and s into a single reasonable unary digit. (I suppose I could save a byte by using w or s as the unary digit, but that seems like a bit of a stretch.)


Write a program to print the sum of the ascii codes of the program Your task is to write a program to print the sum of the ASCII codes of the characters of the program itself. You are not allowed to open any file (Any input such as command line arguments, standard input or files is prohibited).

The program that prints the lowest number (i.e. has the lowest sum of ASCII codes) wins.

Here is an example (not the shortest) of such a program  written in C:

#include <stdio.h>
int main(){
printf("4950");/*i*/
return 0;
}

(no new line after })

PHP, m4, and other cat-like languages: 150

150

Found this solution using a simple Haskell program to brute-force it:

f :: String -> Bool
f s = (read s :: Int) == (sum . map fromEnum) s

main = mapM_ print [filter f $ sequence $ replicate n ['0'..'9'] | n <- [1..10]]


What do I need to destroy the world? The gravitational binding energy of a planet is the amount of energy required to separate every tiny piece of it so that no piece will orbit or collide with another piece. For a uniform sphere, Wikipedia gives this formula:

$$E = \frac{3GM^2}{5R}$$

Where G is the gravitational constant (6.672e-11 m3•kg-1•s-2), M is mass, and R is the radius.

I could make this challenge about merely calculating this in Joules (kg•m2•s-2), but… that would be boring. And besides, not everyone understands Joules.

So instead, let's convert it into the following units:

Kilotons of TNT (4.184 trillion Joules, shorthand kilotons)
Hiroshima nuclear weapons (62.76 trillion Joules, shorthand nukes)
Hostess™ Twinkies (560,000 Joules, shorthand twinkies)
Kilowatt-hours (exactly 3.6 million Joules, shorthand kWh)
Kilograms of mass-energy (1 kg mass-energy = 299,792,4582 Joules, shorthand kg)

So, take in the following input:

mass in kilograms
radius in meters
one of six distinct inputs representing the unit to use

And output the binding energy in the specified units. Append the shorthand unit to the end of the output.

Rules

The shorthand for Joules is J.
Arbitrary whitespace is allowed, as long as it doesn't split the shorthand unit or the number.
Scientific notation is allowed, in whatever format your language uses.
You only need 4 significant figures. Floating points are highly recommended.
Blah blah shortest answer in bytes.

Test Cases

Generated with this spreadsheet.

Mass (kg)   Radius (m)  J           kilotons    nukes       twinkies    kWh         kg
3.302E+23   2440000     1.789E+30   4.275E+17   2.850E+16   3.194E+24   4.969E+23   1.990E+13
4.869E+24   6052000     1.568E+32   3.748E+19   2.499E+18   2.800E+26   4.356E+25   1.745E+15
5.974E+24   6371000     2.242E+32   5.360E+19   3.573E+18   4.004E+26   6.229E+25   2.495E+15
6.419E+23   3390000     4.866E+30   1.163E+18   7.753E+16   8.689E+24   1.352E+24   5.414E+13
1.899E+27   69911000    2.065E+36   4.935E+23   3.290E+22   3.687E+30   5.736E+29   2.298E+19
5.685E+26   58232000    2.222E+35   5.310E+22   3.540E+21   3.968E+29   6.172E+28   2.472E+18
8.683E+25   25360000    1.190E+34   2.845E+21   1.896E+20   2.125E+28   3.306E+27   1.324E+17
1.024E+26   24620000    1.705E+34   4.075E+21   2.717E+20   3.045E+28   4.736E+27   1.897E+17
1.311E+22   1186000     5.801E+27   1.387E+15   9.244E+13   1.036E+22   1.611E+21   6.455E+10
1.989E+30   696300000   2.274E+41   5.436E+28   3.624E+27   4.062E+35   6.318E+34   2.531E+24
7.350E+22   1737000     1.245E+29   2.976E+16   1.984E+15   2.223E+23   3.458E+22   1.385E+12

Inspired by Powering the Death Star with Twinkies by Scott Manley.


Cheating Cyclic Quine Concept

Write a program that outputs code in its programming language. That code, when executed, must output the original program.

Rules

Since this is a cheating quine, you can read the original source code.
First output program must be in the same language as the original program.
You may not output a regular quine. The two programs must be different.
Standard loopholes apply.
This is code-golf so shortest answer wins, however it will not be selected.

Bash + coreutils, 11 bytes

tr xy yx<$0

This prints

tr yx xy<$0

Try it online!

In turn, that prints

tr xy yx<$0


Triple-balanced numbers Description

We consider an integer with at least 3 digits triple-balanced if, when split into three parts, the digits in every part sum up to the same number. We split numbers as follows:

abcdefghi - Standard case: the number of digits is divisable through 3:
abc def ghi

abcdefgh - Number % 3 == 2: The outer groups are both assigned another digit
abc de fgh (the inner group will have one digit less than both outer groups)

abcdefghij - Number % 3 == 1: The inner group is assigned the extra digit
abc defg hij (the inner group will have one digit more than the outer groups)

Challenge

Your task is to write a program, that, given an integer with at least 3 digits, determines whether the given number is triple-balanced and outputs a truthy or falsy value based on it's result.

Test cases

333 -> True
343 -> False
3123 -> True
34725 -> True
456456 -> False
123222321 -> True

This is code-golf, so standard loopholes apply and may the shortest answer in bytes win!

Python 2, 93 88 86 bytes

-4 bytes thanks to @LeakyNun
-2 bytes thanks to @Mr.Xcoder

def g(i):l=-~len(i)/3;print f(i[:l])==f(i[l:-l])==f(i[-l:])
f=lambda a:sum(map(int,a))

Try it online!


Output the current time in ascii art Challenge

Your task is to output the time (in 12 hour time) in ascii art.

All characters that will be used are as follows:

  ___    __   ___    ____    _  _     _____     __    ______
 / _ \  /_ | |__ \  |___ \  | || |   | ____|   / /   |____  |
| | | |  | |    ) |   __) | | || |_  | |__    / /_       / /
| | | |  | |   / /   |__ <  |__   _| |___ \  | '_ \     / /
| |_| |  | |  / /_   ___) |    | |    ___) | | (_) |   / /
 \___/   |_| |____| |____/     |_|   |____/   \___/   /_/

   ___     ___
  / _ \   / _ \                                _
 | (_) | | (_) |   __ _ _ __    _ __ _ __     (_)
  > _ <   \__, |  / _` | '  \  | '_ \ '  \     _
 | (_) |    / /   \__,_|_|_|_| | .__/_|_|_|   (_)
  \___/    /_/                 |_|

(For each number/symbol individually, consult this gist).

You will receive input in an array of the form:

[hours, minutes, 'am/pm']. For example, [4, 57, 'am'], with single quotes only used for am/pm
or "hours-minutes-am/pm". For example, "4-56-am"
or [hours, 'minutes', 'am/pm'] for languages that cannot handle leading zeroes on numbers. For example, [4, '07', 'am']

You may use either input method.

Output will be in the form 1  2 : 5  9 am, where there is one initial space, two spaces between each number (in the gist, each number already has one space on each side), one space between : (colon) and the neighbouring numbers, and one space between the last number and am/pm, with an optional leading and/or trailing newline. All spaces are between the right-most point of the symbol on the left and the left-most point of the symbol on the right.

Implicit output is allowed.

Lowest byte size wins.

The am/pm are to be aligned such that the bottom of the p in pm is aligned with the bottom of the rest of the output, that is, the undercore denoting the top of am/pm starts on the third line down (not counting a leading newline).

The colon is to be aligned such that it's first character (an underscore) starts on the second line down (not counting a leading newline).

For minutes < 10, output the minutes with a leading 0 (you should receive this in the input). For example, [8, 04, 'pm'] -> 8 : 0  4 pm.

You must not fetch the data for the numbers from a library or external resource. All data must be contained within the program.

For example, for the input [12, 47, 'am'], the output would be as follows:

  __    ___          _  _      ______
 /_ |  |__ \    _   | || |    |____  |
  | |     ) |  (_)  | || |_       / /   __ _ _ __
  | |    / /    _   |__   _|     / /   / _` | '  \
  | |   / /_   (_)     | |      / /    \__,_|_|_|_|
  |_|  |____|          |_|     /_/

(If you see any edge cases that you can't decide what to do with, please post in comments and I will add them to examples).

Perl, 592 579 540 522 510 bytes

Under a sector!

($L,$C,$b)=unpack"W/aW/aB*",q!12346677889999 _|/\)(
'<,>.` PP¨
¨@T @ôäð˜SÀ§€fÌU`à¨Àäð'€GÖf`3 X½`fÍ5 s Î|½`gËÖ— $¡))õ™˜À8Sô BÁªx~O àÔýåËþÏÃÆ~O‡ŸY¬Àf s
½`À*õŸ/X8|½`p>^€<¯åkgúºÖ·ÓÊ¸°ªÀj® kª¸•p¸å\×   ô!;@c=map{$i<<=$_-$P if$_>$P;$P=$_;sprintf"%${l}b",$i++}$L=~/./g;while($b){$b=~s/^$c[$_]// and$g.=($C=~/./sg)[$_]for 0..$#c}$_=pop;s/-/:/;y/apm-/;</d;for$a(0..5){map{$o.=substr((split$/,$g)[$a],($x=-48+ord)*12,('6356766766099'=~/./g)[$x]+3)}/./g;$o.=$/}print$o

This program expects the time in the 2nd format ("12-34-am") as a commandline argument.

Commented:

($L,$C,$b) = unpack "W/aW/aB*",             # extract code lengths, chars, and bitstream
    q!12346677889999 _|/\)(
'<,>.` PP¨
¨@T @ôäð˜SÀ§€fÌU`à¨Àäð'€GÖf`3 X½`fÍ5 s Î|½`gËÖ— $¡))õ™˜À8Sô BÁªx~O àÔýåËþÏÃÆ~O‡ŸY¬Àf s
½`À*õŸ/X8|½`p>^€<¯åkgúºÖ·ÓÊ¸°ªÀj® kª¸•p¸å\×   ô!;
@c = map {                                  # reconstruct huffman prefix codes
    $i <<= $_-$P if $_ > $P;                # increase code size
    $P = $_;                                # keep track of previous code
    sprintf "%${l}b", $i++                  # append code as bitstring
}
$L=~/./g;                                   # canonical huffman prefix lengths
while ( $b ) {                              # decompress font
        $b =~ s/^$c[$_]//                   # match and strip prefix code
        and $g .= ($C=~/./sg)[$_]           # append char for prefix code
    for 0..$#c                              # iterate prefix codes in order
}                                           # luckily we can omit checking trailing bytes

$_ = pop;                                   # get cmdline arg "12-34-am"
s/-/:/;                                     # ord(':')-ord('0')=10
y/apm-/;</d;                                # 'a'-> chr(11), 'p' -> chr(12), strip -,m
for $a (0..5) {                             # iterate 6 output lines
    map {                                   # iterate each char in input
        $o .= substr(
            ( split $/, $g )[$a],           # grab line $a
            ( $x=-48+ord ) * 12,            # $x=glyph index, 12=glyph width
            ('6356766766099'=~/./g)[$x]+3   # glyph display width
        )
    } /./g;
    $o .= $/                                # append newline
}
print $o                                    # output

Note that due to character encoding issues, when you paste the above code in a file, the output may be somewhat malformed. So here's the golfed version, base-64 encoded. Copy it, and paste it into base64 -d > 510.pl:

KCRMLCRDLCRiKT11bnBhY2siVy9hVy9hQioiLHEhDjEyMzQ2Njc3ODg5OTk5DiBffC9cKSgKJzws
Pi5gFQBQAVACqAIgCqgBQBVUAqAFQAH05PAOmANTwBqngGbMBlVgHOAaqMDk8AcngEfWZmAzAA9Y
Ar1gZs0DNQBzoAHOBny9YGfL1g+XoAUkoSkp9ZmYDMAHOANT9A1Cwap4Bn5PABzgH9T9AeV/GBAB
y/7Pw8Z+Tx+Hn1mswGYAc6AKvWAMwCr1gZ8vWAc4Bny9YA5wPl6APK/lrWtn+rrWt9PKuAawBqrA
aq4AawGquAeVcA64AeVcAdcAAAABrfQhO0BjPW1hcHskaTw8PSRfLSRQIGlmJF8+JFA7JFA9JF87
c3ByaW50ZiIlJHtsfWIiLCRpKyt9JEw9fi8uL2c7d2hpbGUoJGIpeyRiPX5zL14kY1skX10vLyBh
bmQkZy49KCRDPX4vLi9zZylbJF9dZm9yIDAuLiQjY30kXz1wb3A7cy8tLzovO3kvYXBtLS87PC9k
O2ZvciRhKDAuLjUpe21hcHskby49c3Vic3RyKChzcGxpdCQvLCRnKVskYV0sKCR4PS00OCtvcmQp
KjEyLCgnNjM1Njc2Njc2NjA5OSc9fi8uL2cpWyR4XSszKX0vLi9nOyRvLj0kL31wcmludCRv

Here's the font I'm using. I've spaced the glyphs 12 characters apart
(the size of the am/pm) for easy indexing.

   ___        __          ___         ____        _  _        _____         __        ______       ___         ___
  / _ \      /_ |        |__ \       |___ \      | || |      | ____|       / /       |____  |     / _ \       / _ \      _
 | | | |      | |           ) |        __) |     | || |_     | |__        / /_           / /     | (_) |     | (_) |    (_)          __ _ _ __   _ __ _ __
 | | | |      | |          / /        |__ <      |__   _|    |___ \      | '_ \         / /       > _ <       \__, |     _          / _` | '  \ | '_ \ '  \
 | |_| |      | |         / /_        ___) |        | |       ___) |     | (_) |       / /       | (_) |        / /     (_)         \__,_|_|_|_|| .__/_|_|_|
  \___/       |_|        |____|      |____/         |_|      |____/       \___/       /_/         \___/        /_/                              |_|

This font is 592 bytes.
The previous approach used a few variations on RLE compression to reduce this to 353 bytes, at the cost of 78 bytes decompression code.
The Huffman coding compresses the font to 221 bytes at the cost of 154 bytes for the decompression algorithm.


Flip the commented-out code This puzzle works for any programming language that has the same // single-line and /* ... */ multi-line comments that C++, C# and Java do.

You are debugging an application. You find a fishy block of code, which you comment out and replace with some new code:

/*
code block A
*/
code block B

After some debugging, you find that you need to step through block A again to see how it worked. This requires quite a lot of cursor movement:

                ← remove “/*” here
code block A
/*              ← change “*/” to “/*” here
code block B
*/              ← add “*/” here

This is very laborious if you need to keep switching between block A and block B. So you decide to find a better way.

Place combinations of asterisks and slashes before block A, between the blocks, and after block B, such that you can flip between block A and block B by adding/removing only one character in one place. You may assume that the code blocks A and B do not contain any /* or */.

There are two possible solutions.

Toggle commented out blocks by adding/removing the last slash on the first line:

/**/
code block A
/*/
code block B
/**/

Bonus solution, toggle this one by adding/removing the first slash on the first line:

//*
code block A
/*/
code block B
/**/


Alphanumeric Line and Curve Counting Given an input string, write a program that outputs the total number of lines and curves it has.

The Challenge

Take input from STDIN, or any other input method.
Output to STDOUT, or any other output method, the total number of lines and curves contained in the string, in that order, based on the below table in the code snippet.
Any non-alphanumeric characters should be ignored.
Standard loopholes are forbidden.
This is code-golf, so shortest code wins.

Clarifications

The lines and curves are determined by the font used on Stackexchange for code blocks.
Circles (like O, o, 0) and dots (i, j), are considered to be 1 curve each.
Input can be a string, list of characters, stream of characters, bytecodes etc.
Output can be an array of integers, tuple of integers, comma-separated string, etc. The two numbers must be separate, so 104 is not valid, but 10,4, 10        4, 10\n4, [10,4], (10, 4), and so on is.
Heading and trailing whitespace is perfectly acceptable.

Sample Input and Output

# Format: str -> line, curve
hi -> 4, 2
HELLO WORLD -> 20, 4
l33+ 5pEak -> 13, 8
+=-_!...?~`g@#$%^ -> 1, 2
9001 -> 5, 3
O o O o O o -> 0, 6

Character Table

Char | Lines | Curves
0    | 1     | 1
1    | 3     | 0
2    | 1     | 1
3    | 0     | 2
4    | 3     | 0
5    | 2     | 1
6    | 0     | 1
7    | 2     | 0
8    | 0     | 2
9    | 0     | 1
A    | 3     | 0
B    | 1     | 2
C    | 0     | 1
D    | 1     | 1
E    | 4     | 0
F    | 3     | 0
G    | 2     | 1
H    | 3     | 0
I    | 3     | 0
J    | 1     | 1
K    | 3     | 0
L    | 2     | 0
M    | 4     | 0
N    | 3     | 0
O    | 0     | 1
P    | 1     | 1
Q    | 0     | 2
R    | 2     | 1
S    | 0     | 1
T    | 2     | 0
U    | 0     | 1
V    | 2     | 0
W    | 4     | 0
X    | 4     | 0
Y    | 3     | 0
Z    | 3     | 0
a    | 0     | 2
b    | 1     | 1
c    | 0     | 1
d    | 1     | 1
e    | 1     | 1
f    | 1     | 1
g    | 1     | 2
h    | 1     | 1
i    | 3     | 1
j    | 1     | 2
k    | 3     | 0
l    | 3     | 0
m    | 3     | 2
n    | 2     | 1
o    | 0     | 1
p    | 1     | 1
q    | 1     | 1
r    | 1     | 1
s    | 0     | 1
t    | 1     | 1
u    | 1     | 1
v    | 2     | 0
w    | 4     | 0
x    | 4     | 0
y    | 1     | 1
z    | 3     | 0

Haskell, 214 199 188 175 bytes

 g 0=[]
 g n=mod n 5:g(div n 5)
 d#s=sum[n|c<-d,(i,n)<-zip['0'..]$g s,c==i]
 f s=(s#0x300BBD37F30B5C234DE4A308D077AC8EF7FB328355A6,s#0x2D5E73A8E3D345386593A829D63104FED5552D080CA)

Try it online!

The numbers of lines and curves are the digits of base-5 numbers and stored as base-16 numbers. Function g translates back to base-5.

Edit: -13 bytes thanks to @cole.


Antiferromagnetic ordering Antiferromagnetism is what IBM researchers used to jump from a 1 terabyte disk to a 100 terabyte disk in the same amount of atoms.

In materials that exhibit antiferromagnetism, the magnetic moments of atoms or molecules, usually related to the spins of electrons, align in a regular pattern with neighboring spins (on different sublattices) pointing in opposite directions.

Your job is to write a program that draws the ordering of antiferromagnetic atoms like the picture shown above. You must be able to have at least four sets of pairs, though you may have more.

Each pair must be shown as follows, though they must be actual arrows:

 up  down
down  up
 up  down

Your output can be in ascii art or graphical output.

You can make only a function or a whole program, but it must take an input and draw that many pairs. Examples with only words:

Input: 1

 up  down
down  up
 up  down

Input: 2

 up  down  up  down
down  up  down  up
 up  down  up  down

Acceptable arrows:

↑ and ↓
⇅ and ⇵
/|\ and \|/

Please put your answers in Language, X bytes format, as it's easy to read. The least amount of bytes wins!

APL, 18 12 bytes

⍉(2×⎕)3⍴'↑↓'

This constructs a 2n x 3 matrix, where n is the input (⎕), filled with the characters ↑ and ↓. The transpose (⍉) of this matrix is then printed.

You can try it online.


Find all strings at distance k The edit (or Levenshtein) distance between two strings is the minimal number of single character insertions, deletions and substitutions needed to transform one string into the other.

The challenge is to write code to output all strings with edit distance exactly k from a fixed string of length 10, where k is a variable set in your code as is the fixed string.   The alphabet is 0 or 1. To test, take

1111011010

as the fixed string. The twist is that you can't output the same string twice.

You may not use any library or built in functions that compute the Levenshtein distance for you.

Score

This is a standard code-golf challenge. You can assume k will be a one-digit number.

Reference Implementation

(added by Martin Büttner)

For reference, here is a Mathematica solution (which isn't valid, due to use of EditDistance) which can be used to check results for correctness:

s = "1111011010";
k = 2;
Union @ Cases[
     Join @@ Array[# <> "" & /@ {"0", "1"}~Tuples~# &, 2 k + 1, 10 - k],
     x_ /; x~EditDistance~s == k
]

For the first ten values of k I the following results:

 k | # of results

 0              1
 1             28
 2            302
 3           1652
 4           5533
 5          14533
 6          34808
 7          80407
 8         180663
 9         395923

Scala 168 228

My first submission had a bug where it didn't consider multiple insertions at the same point in the input string.

After

val k = 1
val s = "1111011010"

The code that counts is:

def e(k:Int,s:String):Set[String]=if(k<1)Set(s)else e(k-1,s).flatMap(e=>"01"map(_+e))++(if(s=="")Set()else e(k,s.tail).map(s.head+_)++e(k-1,s.tail).flatMap(e=>(Set("0","1","")-(s take 1))map(_+e)))
print(e(k,s))

To run, save both sections together as a file and run like:

$ scala distancek.scala
Set(111111010, 111101010, 1111001010, 11110011010, 1101011010, 11101011010, 111101101, 111101100, 11111011010, 1111011011, 1111011000, 11110101010, 1111010010, 11110110110, 11110110101, 111101110, 11110110010, 0111011010, 1110011010, 11110110100, 10111011010, 11011011010, 01111011010, 1011011010, 1111111010, 111011010, 11110111010, 1111011110)
$

Recursive function to build the edited strings. k is the number of edits remaining, s is the string to edit. Slightly ungolfed:

def e(k:Int,s:String):Set[String]=
  if(k<1) Set(s)                           // No edits left
  else e(k-1,s).flatMap(e=>"01"map(_+e))++ // Insert a character, consume an edit, continue from the same point
      (if(s=="") Set()                     // We're at the end of the string so only insertions are allowed
       else e(k,s.tail).map(s.head+_)++    // skip past this character, making no edit
       e(k-1,s.tail).flatMap(e=>(Set("0","1","")-(s take 1))map(_+e))) // replace this character with its inverse or ""

Note that each step makes at least one of k, s smaller so we're guaranteed to terminate.

First submission (Incorrect)

print((0 to 10).permutations.flatMap{i=>((s.map(_+""):+"")zip i).:\(Set("")){case((s,i),a)=>a.flatMap{a=>(if(i<k)Set(1+s,0+s,"","0","1")-s else Set(s))map(_+a)}}}toSet)

We take the permutations of 0..10 and zip them with the word s + a terminal "" (for insertions at the end).
All the positions < k are positions where an edit should occur. For each edit we replace the string at that position with

Set(1+s,0+s,"","0","1")-s # don't count substituting s for itself as an edit.

and finally convert to a set to remove duplicates.


Prefix Notation to Postfix Notation Disclaimer: No, this is not a joke challenge to reverse a string.

Task

There is only one operation to support: subtraction (-).

You also only have two atoms to support: zero (0) and one (1).

Here, the prefix notation -AB is equivalent to the postfix notation AB-, where A and B are expressions.

Your task is to (recursively) convert an expression in prefix notation to its equivalent in postfix notation.

Definitions

An expression in prefix notation is generated by the following grammar:

S > -SS
S > 0
S > 1

An expression in postfix notation is generated by the following grammar:

S > SS-
S > 0
S > 1

Example

Prefix notation:  --01-0-01
Parentheses:      -(-01)(-0(-01))
Convert:          (01-)(0(01-)-)-
Postfix notation: 01-001---

Rules and freedom

You may rename the operation and the atoms to whichever character, as long as it is consistent.
The input format must be consistent with the output format (apart from the fact that the input is in prefix notation and the output is in postfix notation).

Testcase

Input       Output
1           1
0           0
-01         01-
-10         10-
--01-0-01   01-001---

Testcases credits to Dada.

brainfuck, 32 bytes

,[[->++++<<+>]>[[-]<<[.[-]<]]>,]

Try it online!

I used @ as the operation, because its code point (64) is convenient.  U is also possible with the same byte count, using 3*85+1=256=0.

Explanation

The tape is used as a stack.  In each iteration of the main loop, the data pointer starts two cells right of the top of the stack.

,[                Take input and start main loop
  [->++++<<+>]    Push input, and compute 4*input
  >[              If 4*input is nonzero (and thus input is not @):
    [-]<<           Zero out this cell and move to top of stack
    [.[-]<]         Pop from stack and output until \0 is reached
  ]
  >,              Move pointer into the correct position.  If input was @, the earlier > pushed \0 onto the stack.
]


The greedy regex (robbers) This is the robbers' post. The cops' is here.

Your challenge is to take a cop's post and find an input that the regex matches but the program returns a falsey value.

Once you have cracked a cop's post, comment in a link to your crack. (If you don't have enough rep to comment, please say so, and someone will do it for you.) The robber with the most cracks wins.

Example

Let's say a cop's regex is (all of the flavors):

/^[0-9]$/

And the program is (JS):

x=>Boolean(parseInt(x))

Than a valid crack would be 0, because the regex matches 0 but 0 is falsey.

Python 3, pperry

İ

Try it online!

The lower case variant i̇ of this character is created by a an i and a ċȯṁḃi̇̇ṅi̇̇ṅġ ḋȯṫ which results in a length of 2.


What characters are more common in my MD2 hash? The challenge is simple

Write a script that, when given a string input, will hash the string using the MD2 hashing algorithm, and then return either a positive integer or negative integer output based on which character set below is more common in the resulting hash as a hexadecimal string:

01234567 - (positive)
89abcdef - (negative)

The input will always be a string, but may be of any length up to 65535
The entire input, whitespace and all, must be hashed
For the purposes of this challenge, the integer 0 is considered neither positive nor negative (see tie output)
The more common set is the one who's characters are more common within the 32 character hexadecimal hash string
Your output may contain trailing whitespace of any kind, as long as the only non-whitespace characters are a valid truthy or falsey output
In the event of a tie, where the hexadecimal string contains exactly 16 characters from each set, the program should output a 0

I/O Examples

Input: "" (Empty String)
Hash: 8350e5a3e24c153df2275c9f80692773
Output: 1

Input: "The quick brown fox jumps over the lazy cog" (Without quotes)
Hash: 6b890c9292668cdbbfda00a4ebf31f05
Output: -1

Input: "m" (Without quotes)
Hash: f720d455eab8b92f03ddc7868a934417
Output: 0

Winning Criterion

This is code-golf, fewest bytes wins!

Mathematica, 43 bytes

Tr@Sign[15-2#~Hash~"MD2"~IntegerDigits~16]&

Outputs the number of digits in 01234567 minus the number of digits in 89abcdef.


How frustrating is my movie? My parents have an home theater device.  The remote is broken making it incredibly difficult to navigate rightwards in a menu.  Most the time it doesn't work but when it does it moves rightwards incredibly quickly.

This is obviously frustrating but it is most frustrating when you want to enter a movie title which requires navigating a keyboard that looks like this:

a b c d e f
g h i j k l
m n o p q r
s t u v w x
y z 1 2 3 4
5 6 7 8 9 0

Your task is to take as input a movie title and calculate how "frustrating" it is to type that movie title.  The frustration number of a particular string is the number of letters that require moving right from the letter before them.  We don't care how far right they are, since if we start moving right we pretty much instantly go to the end of the line, and we don't care about up, down or leftwards movement because they are easy.

For example if we wanted to type in

keyboard

We start at k for free.
e is just above k so we don't need to move right.
y is all the way left so no need to move right.
b however is on the next column rightwards so we need to move right to get to it.
o is on the next column over so we have to move rightwards to get to it.
a is back in the first column so we move left to get to it.
r is all the way on the right so we move right to it.
d is two columns to the left of r's column.

The characters that need to move to the right are bor meaning that this is frustration 3.

Additional rules

This is a code-golf challenge so your answers will be scored in bytes with fewer bytes being better.  The input will always consist of alphanumeric characters, you can support either capital or lowercase letters and you only need to support one.  The input will never be empty.

Testcases

keyboard -> 3
2001aspaceodyssey -> 6
sorrytobotheryou -> 8
thinblueline -> 5
blast2 -> 3

JavaScript (Node.js), 61 55 54 bytes

Saved 1 byte thanks to @nwellnhof

Takes input as an array of characters.

s=>s.map(p=c=>r+=p>(p=(+c?~c:1-Buffer(c)[0])%6),r=0)|r

Try it online!

How?

For all characters but digits greater than \$0\$, the 0-indexed column \$x\$ is given by:

$$x=(c-1)\bmod 6$$

where \$c\$ is the ASCII code of the character.

For positive digits \$n\$, we need to do instead:

$$x=(n+1)\bmod 6$$

Examples:

"a" --> (97 - 1) mod 6 = 96 mod 6 = 0
"b" --> (98 - 1) mod 6 = 97 mod 6 = 1
"0" --> (48 - 1) mod 6 = 47 mod 6 = 5
"3" --> ( 3 + 1) mod 6 =  4 mod 6 = 4

Commented

s =>                       // s = input string (as array)
  s.map(p =                // initialize p to a non-numeric value
  c =>                     // for each character c in s:
    r +=                   //   update the result r:
      p > (                //   compare p with
        p = (              //   the new value of p defined as:
          +c ?             //     if c is a positive digit:
            ~c             //       -(int(c) + 1)
          :                //     else:
            1-Buffer(c)[0] //       -(ord(c) - 1)
        ) % 6              //     apply modulo 6
      ),                   //   yields 1 if the previous value is greater than the new one
    r = 0                  //   start with r = 0
  ) | r                    // end of map(); return r